File size: 2,783 Bytes
d044abe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bebe819
d044abe
 
 
 
bebe819
d044abe
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""Fail-closed container boundary. Candidate code never runs on the host."""
import json
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import uuid

class SandboxUnavailable(RuntimeError):pass

class Sandbox:
    def __init__(self,image='smolscript-runtime:0.1.0',engine='docker'):
        if not shutil.which(engine):raise SandboxUnavailable(f'{engine} is unavailable; install Docker/Podman and build sandbox/Dockerfile. No host fallback exists.')
        self.engine=engine
        try:
            info=json.loads(subprocess.check_output([engine,'image','inspect',image],timeout=15))[0]
        except (subprocess.SubprocessError,ValueError,KeyError) as e:raise SandboxUnavailable('Sandbox image unavailable; build it before offline evaluation') from e
        self.image=info['Id']  # Immutable local ID, not a moving tag.
        self.identity={'engine':engine,'image_id':self.image,'repo_digests':info.get('RepoDigests',[])}

    def run(self,payload,timeout):
        # Only candidate, fixture, input values and observation selectors cross the
        # boundary. Expected answers, references, credentials and dataset do not.
        name='smolscript-'+uuid.uuid4().hex
        with tempfile.TemporaryDirectory(prefix='smolscript-input-') as directory:
            path=Path(directory)/'request.json'
            path.write_text(json.dumps(payload));path.chmod(0o444);os.chmod(directory,0o755)
            command=[self.engine,'run','--rm','--name',name,'--network','none','--read-only',
              '--cap-drop','ALL','--security-opt','no-new-privileges','--user','1000:1000',
              '--memory','2g','--memory-swap','2g','--cpus','1','--pids-limit','512',
              '--ulimit','nofile=256:256','--ulimit','core=0:0',
              '--tmpfs','/work:rw,exec,nosuid,size=256m,uid=1000,gid=1000',
              '--tmpfs','/tmp:rw,nosuid,size=128m,uid=1000,gid=1000','--shm-size','128m',
              '--mount',f'type=bind,src={directory},dst=/input,readonly',
              self.image,'python3','/opt/smolscript/supervisor.py','/input/request.json']
            try:
                result=subprocess.run(command,capture_output=True,text=True,timeout=timeout)
                if result.returncode:raise RuntimeError('Sandbox infrastructure failed: '+result.stderr[-2000:])
                value=json.loads(result.stdout)
                if 'infrastructure_error' in value:raise RuntimeError(value['infrastructure_error'])
                return value
            except subprocess.TimeoutExpired:
                raise RuntimeError('Sandbox supervisor timed out; outcome incomplete')
            finally:
                subprocess.run([self.engine,'rm','-f',name],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=15)