"""Container sandbox. The only module that knows about the container runtime (Apptainer). Everything inside runs fully isolated from the host: no inherited environment, no host home, only the explicitly given binds. `home_dir(scratch)` is the sandbox home on the host. """ import contextlib import os import re import subprocess import sys from pathlib import Path from . import config # Upstream agent scripts hard-code this home directory. HOME = "/home/ben" HF_HOME = f"{HOME}/hf_cache" def home_dir(scratch: Path) -> Path: return scratch / "home" / Path(HOME).name def _runtime_env() -> dict[str, str]: """Keep Apptainer's build/cache files in the data dir; home and /tmp are often too small.""" env = dict(os.environ, APPTAINERENV_PREPEND_PATH=f"{HOME}/.local/bin") # agent CLIs install there for var, subdir in (("APPTAINER_TMPDIR", "tmp"), ("APPTAINER_CACHEDIR", "cache")): env.setdefault(var, str(config.DATA_DIR / "apptainer" / subdir)) Path(env[var]).mkdir(parents=True, exist_ok=True) return env def build_image(container: str) -> None: """Build an upstream container definition; its %files paths are relative to the upstream repo.""" config.CONTAINERS.mkdir(parents=True, exist_ok=True) # The def's %post chowns files (apt, openssh-client), which needs more than the single UID a # plain unprivileged build maps. --fakeroot gives the full range; --ignore-subuid falls back to # the libfakeroot emulation where /etc/subuid is not usable, e.g. inside a containerized job. # Override with PTB_BUILD_FLAGS (space separated) on machines that build as root. flags = os.environ.get("PTB_BUILD_FLAGS", "--fakeroot --ignore-subuid").split() # cwd stays the upstream repo whatever the definition's own location: its %files paths are # relative to it. build = subprocess.run( ["apptainer", "build", *flags, str(config.image(container)), str(config.definition(container))], cwd=config.UPSTREAM, env=_runtime_env(), check=False, ) if build.returncode: sys.exit(f"Build of {container} failed. It downloads ~20 GB, so network hiccups are the " "usual cause: just rerun.") @contextlib.contextmanager def hf_overlay(scratch: Path): """Yield a writable view of the shared HF cache, as upstream's `with_huggingface_overlay` does. The prefilled cache is hundreds of GB, so the agent cannot get a copy; it gets a fuse-overlayfs whose upper layer absorbs its writes and is thrown away with the run, leaving the shared cache untouched. """ upper, work, merged = (scratch / name for name in ("hf_upper", "hf_work", "hf_merged")) for path in (upper, work, merged, config.HF_CACHE): path.mkdir(parents=True, exist_ok=True) options = f"lowerdir={config.HF_CACHE},upperdir={upper},workdir={work}" subprocess.run(["fuse-overlayfs", "-o", options, str(merged)], check=True) try: yield merged finally: # The agent may still hold open files; lazy unmount so cleanup never blocks the run. subprocess.run(["fusermount", "-uz", str(merged)], check=False) def run( command: list[str], *, scratch: Path, hf_cache: Path, container: str, env: dict[str, str] | None = None, binds: dict[Path, str] | None = None, workdir: str = HOME, timeout_minutes: int | None = None, isolate_network: bool = False, log: Path | None = None, ) -> int: """Run `command` in the sandbox and return its exit code; after `timeout_minutes` it is killed. `binds` maps host paths to sandbox paths. Output goes to `log` if given. With `isolate_network` the sandbox gets an empty network namespace: only its own loopback, no route to anywhere. """ env = {"HF_HOME": HF_HOME, "VLLM_API_KEY": "inspectai", "PYTHONNOUSERSITE": "1", **(env or {})} if "CUDA_VISIBLE_DEVICES" in os.environ: env["CUDA_VISIBLE_DEVICES"] = os.environ["CUDA_VISIBLE_DEVICES"] # All of /home is replaced rather than using --home: sites that bind their own /home into # every container make a new directory below it impossible. HOME then has to be set by `env`. binds = {scratch / "home": "/home", scratch / "tmp": "/tmp", hf_cache: HF_HOME, **(binds or {})} for host_dir in (home_dir(scratch) / "hf_cache", scratch / "tmp", hf_cache): host_dir.mkdir(parents=True, exist_ok=True) argv = ["apptainer", "exec", "--nv", "--containall", "--cleanenv", "--pid", "--no-init", "--writable-tmpfs", "--no-home", "--pwd", workdir] if isolate_network: argv += ["--net", "--network=none"] for host_path, sandbox_path in binds.items(): argv += ["--bind", f"{host_path}:{sandbox_path}"] argv += [str(config.image(container)), "env", f"HOME={HOME}", *command] if timeout_minutes: argv = ["timeout", "--signal=TERM", "--kill-after=30s", f"{timeout_minutes}m", *argv] with open(log, "w") if log else contextlib.nullcontext() as out: # APPTAINERENV_* rather than --env keeps secrets off the command line. Apptainer # shell-evaluates the values, hence the escaping to pass them through literally. host_env = _runtime_env() | {f"APPTAINERENV_{k}": re.sub(r"([\\`$])", r"\\\1", v) for k, v in env.items()} return subprocess.run(argv, env=host_env, stdout=out, stderr=subprocess.STDOUT, check=False).returncode