star_v1 / scripts /star /eval /chroot_runtime.py
pourasrp's picture
STAR v1 release
c921540 verified
Raw History Blame Contribute Delete
22.5 kB
#!/usr/bin/env python3
"""Chroot runtime for Tier 1 on a Docker-less Jarvis container (plan.md "TIER-1 DECISIONS -- USER 2026-10-10", Path A).
Why this exists: the Jarvis container has no Docker daemon, seccomp blocks user/mount namespaces (so `apptainer exec`
cannot run), but CAP_SYS_CHROOT and CAP_MKNOD are present, so a plain `chroot --userspec=1000:1000` into an unpacked
swebench image works (handoffs/tier1_feasibility.md). This module is used by _tools.ChrootEnv (rollouts) and by
tier1_grade.py (grading); it does not import swebench.
IMAGE STORE (fs 3147, `eval_env/images`, cap 15 GB compressed). The 50 per-image Apptainer SIFs would be ~56 GB (they
do not share layers); the registry layers shared by digest are 9.675 GB (image_footprint.json). So the store keeps the
registry's OWN layer blobs once each (`blobs/sha256/<hex>`) plus one manifest/config JSON per instance
(`manifests/<instance_id>.json`), fetched from docker.io/swebench with the plain registry v2 API (no Docker, no
apptainer, anonymous pull: one manifest-list GET + one manifest GET per image). A task rootfs is built by applying
the image's layers in order with GNU tar (OCI whiteouts handled), onto the LOCAL overlay disk, never fs 3147.
PER TASK: materialize (unpack) -> run -> grade -> delete. There is no resident rootfs cache.
SECURITY (verified on the A30): as root inside a chroot the classic escape reaches /home/jl_fs. Every command
therefore runs as uid 1000 (`chroot --userspec=1000:1000`, the whole rootfs `chown -R 1000:1000` first); the escape is
blocked at that uid. File reads/writes also go THROUGH the chroot (never through a host path: a symlink planted by
the agent could otherwise redirect a host-side write outside the rootfs).
NETWORK: NOT ISOLATED (no network namespace is possible here). Handling (user decision 2026-10-10): /etc/resolv.conf is
removed from the rootfs; the exec environment is rebuilt from the image config and never contains HTTP(S)_PROXY /
PIP_INDEX_URL / PIP_EXTRA_INDEX_URL / CONDA_CHANNELS; conda/pip config files are deleted; commands matching
`pip|conda|curl|wget|git clone` are LOGGED (not blocked) to a per-task net_audit.jsonl. Outbound access by raw IP is
still possible. Disclosure beside every Tier-1 number: "chroot runner, no network namespace; outbound attempts audited
by trajectory scan."
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
import signal
import stat
import subprocess
import sys
import tempfile
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import _common as C # noqa: E402
UID = GID = 1000
EVAL_ENV = C.STAR / "eval_env"
DEFAULT_STORE = EVAL_ENV / "images"
DEFAULT_WORK_ROOT = Path("/tmp/star_chroot") # LOCAL overlay; guarded against fs 3147 below
CAP_COMPRESSED_BYTES = 15 * 10**9 # user-approved cap on the image store (compressed)
REGISTRY = "https://registry-1.docker.io"
AUTH = "https://auth.docker.io/token?service=registry.docker.io&scope=repository:{repo}:pull"
ACCEPT = ",".join(["application/vnd.oci.image.index.v1+json", "application/vnd.docker.distribution.manifest.list.v2+json",
"application/vnd.oci.image.manifest.v1+json", "application/vnd.docker.distribution.manifest.v2+json"])
GZIP_LAYERS = {"application/vnd.oci.image.layer.v1.tar+gzip", "application/vnd.docker.image.rootfs.diff.tar.gzip"}
NETWORK_DISCLOSURE = "chroot runner, no network namespace; outbound attempts audited by trajectory scan."
NET_AUDIT_RE = re.compile(r"(?<![\w-])(pip3?|conda|curl|wget)(?![\w-])|git\s+clone")
DROP_ENV = {"HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy", "ALL_PROXY", "all_proxy", "FTP_PROXY", "ftp_proxy",
"PIP_INDEX_URL", "PIP_EXTRA_INDEX_URL", "PIP_TRUSTED_HOST", "PIP_FIND_LINKS", "CONDA_CHANNELS", "CONDA_DEFAULT_CHANNELS",
"CONDARC", "PIP_CONFIG_FILE"}
NET_CONFIG_FILES = ("root/.condarc", "opt/miniconda3/.condarc", "opt/miniconda3/condarc", "etc/conda/.condarc", "etc/conda/condarc",
"etc/pip.conf", "root/.pip/pip.conf", "root/.config/pip/pip.conf", "etc/resolv.conf",
"home/nonroot/.condarc", "home/nonroot/.config/pip/pip.conf", "home/nonroot/.pip/pip.conf")
class GateError(RuntimeError):
pass
def sha256_file(p: Path) -> str:
h = hashlib.sha256()
with open(p, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def _assert_local(path: Path) -> None:
rp = str(Path(path).resolve())
if rp.startswith("/home/jl_fs"):
raise RuntimeError(f"refusing to build/run a rootfs on the persistent filesystem: {rp}")
# ----------------------------------------------------------------------------- startup gate (10 s)
def startup_gate(work_root: Path = DEFAULT_WORK_ROOT, timeout: int = 10) -> dict:
"""os.chroot smoke (in a child process, so this process keeps its root) + os.mknod + `capsh --print`, verbatim.
Raises GateError if chroot is not permitted. Recorded in every manifest that uses the chroot runner."""
t0 = time.time()
work_root = Path(work_root)
work_root.mkdir(parents=True, exist_ok=True)
_assert_local(work_root)
d = Path(tempfile.mkdtemp(dir=work_root, prefix="gate_"))
try:
code = ("import os,stat,sys\nd=sys.argv[1]\nos.chroot(d)\nos.chdir('/')\n"
"os.mknod('/gate_null', 0o666|stat.S_IFCHR, os.makedev(1,3))\nprint('chroot+mknod-ok', os.getuid())\n")
r = subprocess.run([sys.executable, "-c", code, str(d)], capture_output=True, text=True, timeout=timeout)
capsh = subprocess.run(["capsh", "--print"], capture_output=True, text=True, timeout=timeout)
out = {"chroot_smoke_rc": r.returncode, "chroot_smoke_stdout": r.stdout.strip(), "chroot_smoke_stderr": r.stderr.strip(),
"capsh_print_rc": capsh.returncode, "capsh_print_verbatim": capsh.stdout + capsh.stderr,
"seconds": round(time.time() - t0, 3), "utc": C.now_utc(),
"chroot_version": subprocess.run(["chroot", "--version"], capture_output=True, text=True).stdout.splitlines()[:1],
"tar_version": subprocess.run(["tar", "--version"], capture_output=True, text=True).stdout.splitlines()[:1],
"uname": " ".join(os.uname())}
out["passed"] = r.returncode == 0 and "chroot+mknod-ok" in r.stdout
if not out["passed"]:
raise GateError(f"chroot is not permitted on this host: {json.dumps(out)[:1500]}")
return out
finally:
shutil.rmtree(d, ignore_errors=True)
# ----------------------------------------------------------------------------- registry fetch (cached on fs 3147)
def repo_of(instance_id: str) -> str:
return "swebench/sweb.eval.x86_64." + instance_id.replace("__", "_1776_").lower()
def _http():
import requests
return requests
def _token(repo: str) -> str:
return _http().get(AUTH.format(repo=repo), timeout=30).json()["token"]
def _get_json(url: str, tok: str, retries: int = 4) -> tuple[dict, str]:
last = None
for k in range(retries):
r = _http().get(url, headers={"Authorization": "Bearer " + tok, "Accept": ACCEPT}, timeout=60)
if r.status_code == 429:
raise RuntimeError(f"registry rate limit (HTTP 429) at {url}: {r.text[:200]}")
if r.status_code == 200:
return r.json(), r.headers.get("Docker-Content-Digest", "")
last = f"HTTP {r.status_code} {r.text[:200]}"
time.sleep(2 ** k)
raise RuntimeError(f"{url}: {last}")
def resolve_image(instance_id: str) -> dict:
"""Manifest (linux/amd64) + config for one swebench image. Exactly one manifest-list GET and one manifest GET."""
repo = repo_of(instance_id)
tok = _token(repo)
idx, idx_digest = _get_json(f"{REGISTRY}/v2/{repo}/manifests/latest", tok)
if "manifests" in idx:
pick = [m for m in idx["manifests"] if m.get("platform", {}).get("architecture") == "amd64" and m.get("platform", {}).get("os") == "linux"]
assert len(pick) == 1, f"{instance_id}: expected exactly one linux/amd64 manifest, got {len(pick)}"
man, man_digest = _get_json(f"{REGISTRY}/v2/{repo}/manifests/{pick[0]['digest']}", tok)
man_digest = man_digest or pick[0]["digest"]
else:
man, man_digest = idx, idx_digest
for l in man["layers"]:
assert l["mediaType"] in GZIP_LAYERS, f"{instance_id}: unsupported layer media type {l['mediaType']}"
cfg = _download_small(repo, man["config"]["digest"], tok)
return {"instance_id": instance_id, "repo": repo, "index_digest": idx_digest, "manifest_digest": man_digest, "manifest": man,
"config": cfg, "compressed_bytes_total": sum(l["size"] for l in man["layers"]),
"layers": [{"digest": l["digest"], "size": l["size"], "mediaType": l["mediaType"]} for l in man["layers"]]}
def _download_small(repo: str, digest: str, tok: str) -> dict:
r = _http().get(f"{REGISTRY}/v2/{repo}/blobs/{digest}", headers={"Authorization": "Bearer " + tok}, timeout=60)
r.raise_for_status()
return r.json()
def blob_path(store: Path, digest: str) -> Path:
algo, hexd = digest.split(":")
assert algo == "sha256"
return Path(store) / "blobs" / "sha256" / hexd
def _download_blob(repo: str, digest: str, size: int, dest: Path, retries: int = 4) -> int:
"""Stream a layer to dest (tmp + sha256 verify + rename). Returns bytes downloaded (0 if already present)."""
if dest.exists() and dest.stat().st_size == size:
return 0
dest.parent.mkdir(parents=True, exist_ok=True)
last = None
for k in range(retries):
tmp = dest.with_suffix(".part")
try:
tok = _token(repo)
h = hashlib.sha256()
with _http().get(f"{REGISTRY}/v2/{repo}/blobs/{digest}", headers={"Authorization": "Bearer " + tok}, stream=True, timeout=120) as r:
r.raise_for_status()
with open(tmp, "wb") as fh:
for chunk in r.iter_content(1 << 20):
fh.write(chunk)
h.update(chunk)
if "sha256:" + h.hexdigest() != digest or tmp.stat().st_size != size:
raise RuntimeError(f"digest/size mismatch for {digest}")
os.replace(tmp, dest)
return size
except Exception as e: # noqa: BLE001
last = e
tmp.unlink(missing_ok=True)
time.sleep(2 ** k)
raise RuntimeError(f"blob {digest}: {type(last).__name__}: {last}")
def cmd_fetch(a) -> int:
store = Path(a.store)
ids = a.ids or C.mini_ids()
(store / "manifests").mkdir(parents=True, exist_ok=True)
infos = {}
for iid in ids: # phase 1: manifests only (2 GETs per image); tiny
mp = store / "manifests" / f"{iid}.json"
if mp.exists():
infos[iid] = json.loads(mp.read_text())
continue
infos[iid] = resolve_image(iid)
mp.write_text(json.dumps(infos[iid], indent=1, sort_keys=True), encoding="utf-8")
uniq = {}
for i in infos.values():
for l in i["layers"]:
uniq[l["digest"]] = l["size"]
total = sum(uniq.values())
plan = {"n_images": len(infos), "unique_layers": len(uniq), "unique_compressed_bytes": total,
"unique_compressed_gb": round(total / 1e9, 3), "sum_if_no_sharing_gb": round(sum(i["compressed_bytes_total"] for i in infos.values()) / 1e9, 3),
"cap_gb": a.cap_gb}
print(json.dumps(plan), flush=True)
if total > a.cap_gb * 10**9:
print(f"STOP: unique compressed bytes {total} would exceed the cap {a.cap_gb} GB; nothing downloaded", flush=True)
return 3
have_before = {d for d, s in uniq.items() if blob_path(store, d).exists()}
repo_for = {}
for i in infos.values():
for l in i["layers"]:
repo_for.setdefault(l["digest"], i["repo"])
t0, done, got = time.time(), 0, 0
with ThreadPoolExecutor(a.workers) as ex:
futs = {ex.submit(_download_blob, repo_for[d], d, s, blob_path(store, d)): d for d, s in uniq.items()}
for f in as_completed(futs):
got += f.result()
done += 1
if done % 10 == 0 or done == len(futs):
print(f" layers {done}/{len(futs)} downloaded_bytes={got} elapsed={time.time() - t0:.0f}s", flush=True)
with ThreadPoolExecutor(a.workers) as ex: # whiteout sidecars (tiny) so per-task unpack reads each layer once
list(ex.map(lambda d: whiteouts_of(blob_path(store, d)), uniq))
per_image = {iid: {"compressed_bytes_all_layers": i["compressed_bytes_total"], "n_layers": len(i["layers"]),
"manifest_digest": i["manifest_digest"]} for iid, i in infos.items()}
log = {"utc": C.now_utc(), "plan": plan, "downloaded_bytes": got, "layers_already_present": len(have_before),
"elapsed_s": round(time.time() - t0, 1), "per_image": per_image}
store_bytes = sum(blob_path(store, d).stat().st_size for d in uniq) # blobs only (sidecars are bytes-small)
log["store_blob_bytes_on_disk"] = store_bytes
C.write_json_atomic(store / "fetch_log.json", log)
print(f"store blobs on disk: {store_bytes} B ({store_bytes / 1e9:.3f} GB); log {store / 'fetch_log.json'}", flush=True)
return 0
def load_image_info(instance_id: str, store: Path = DEFAULT_STORE) -> dict:
mp = Path(store) / "manifests" / f"{instance_id}.json"
if not mp.exists():
raise FileNotFoundError(f"image manifest missing for {instance_id}: {mp} (run `chroot_runtime.py fetch`)")
return json.loads(mp.read_text())
def require_images(ids: list[str], store: Path = DEFAULT_STORE) -> dict:
"""Pre-pull check: every id has a manifest and every layer blob is present with the right size. No network."""
missing, bad = [], []
for iid in ids:
try:
info = load_image_info(iid, store)
except FileNotFoundError:
missing.append(iid)
continue
for l in info["layers"]:
p = blob_path(store, l["digest"])
if not p.exists() or p.stat().st_size != l["size"]:
bad.append((iid, l["digest"]))
if missing or bad:
raise RuntimeError(f"image store incomplete: {len(missing)} ids without manifest {missing[:5]}, {len(bad)} bad layers {bad[:3]}")
return {"store": str(store), "n_ids": len(ids), "ok": True}
# ----------------------------------------------------------------------------- rootfs lifecycle
def whiteouts_of(layer: Path) -> list[str]:
"""Names in the layer that are OCI whiteouts. Cached next to the blob (<blob>.wh, written atomically) so a task's
unpack decompresses each layer once, not twice."""
side = layer.with_name(layer.name + ".wh")
if side.exists():
return json.loads(side.read_text())
names = subprocess.run(["tar", "-tzf", str(layer)], capture_output=True, text=True, check=True).stdout.splitlines()
wh = [n for n in names if os.path.basename(n.rstrip("/")).startswith(".wh.")]
tmp = side.with_name(side.name + f".{os.getpid()}.{threading.get_ident()}.tmp")
tmp.write_text(json.dumps(wh))
os.replace(tmp, side)
return wh
def _apply_layer(layer: Path, dest: Path) -> None:
"""GNU tar, with OCI whiteouts: `.wh.<name>` deletes <name>; `.wh..wh..opq` empties the directory first."""
for n in whiteouts_of(layer):
base = os.path.basename(n.rstrip("/"))
parent = dest / os.path.dirname(n.rstrip("/"))
if base == ".wh..wh..opq":
if parent.is_dir() and not parent.is_symlink():
for e in parent.iterdir():
shutil.rmtree(e) if (e.is_dir() and not e.is_symlink()) else e.unlink()
else:
tgt = parent / base[4:]
if tgt.is_dir() and not tgt.is_symlink():
shutil.rmtree(tgt)
elif tgt.exists() or tgt.is_symlink():
tgt.unlink()
subprocess.run(["tar", "-xzf", str(layer), "-C", str(dest), "--no-same-owner", "--exclude=.wh.*"], check=True,
capture_output=True)
def materialize(instance_id: str, store: Path = DEFAULT_STORE, work_root: Path = DEFAULT_WORK_ROOT, dns: bool = False) -> dict:
"""Unpack the image into a fresh rootfs on the local disk. Returns {rootfs, env, seconds, removed_net_config...}."""
work_root = Path(work_root)
work_root.mkdir(parents=True, exist_ok=True)
_assert_local(work_root)
t0 = time.time()
info = load_image_info(instance_id, store)
rootfs = Path(tempfile.mkdtemp(dir=work_root, prefix=instance_id.replace("/", "_") + "_"))
try:
os.chmod(rootfs, 0o755)
for l in info["layers"]:
_apply_layer(blob_path(store, l["digest"]), rootfs)
t_layers = time.time() - t0
# devices (CAP_MKNOD), /dev/shm (multiprocessing), /proc and /sys cannot be mounted: stay empty
dev = rootfs / "dev"
dev.mkdir(exist_ok=True)
for name, (maj, mino) in {"null": (1, 3), "zero": (1, 5), "random": (1, 8), "urandom": (1, 9), "tty": (5, 0)}.items():
p = dev / name
if p.exists() or p.is_symlink():
p.unlink()
os.mknod(p, 0o666 | stat.S_IFCHR, os.makedev(maj, mino))
os.chmod(p, 0o666)
(dev / "shm").mkdir(exist_ok=True)
os.chmod(dev / "shm", 0o1777)
(rootfs / "tmp").mkdir(exist_ok=True)
os.chmod(rootfs / "tmp", 0o1777)
removed = []
for rel in NET_CONFIG_FILES:
p = rootfs / rel
if dns and rel == "etc/resolv.conf":
continue
if p.exists() or p.is_symlink():
p.unlink()
removed.append(rel)
if dns:
shutil.copyfile("/etc/resolv.conf", rootfs / "etc" / "resolv.conf")
subprocess.run(["chown", "-R", f"{UID}:{GID}", str(rootfs)], check=True)
env = exec_env(info, rootfs)
return {"rootfs": str(rootfs), "env": env, "info": info, "unpack_s": round(time.time() - t0, 2),
"layers_s": round(t_layers, 2), "removed_net_config": removed, "dns": dns}
except BaseException:
shutil.rmtree(rootfs, ignore_errors=True)
raise
def exec_env(info: dict, rootfs: Path) -> dict:
"""Environment rebuilt from the image config (what `docker exec` would inherit) minus proxy / index settings."""
env = {}
for kv in (info.get("config", {}).get("config", {}) or {}).get("Env", []) or []:
k, _, v = kv.partition("=")
env[k] = v
home = "/tmp"
try:
for line in (Path(rootfs) / "etc" / "passwd").read_text().splitlines():
f = line.split(":")
if len(f) > 5 and f[2] == str(UID) and (Path(rootfs) / f[5].lstrip("/")).is_dir():
home = f[5]
except OSError:
pass
env["HOME"] = home
env.setdefault("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")
return {k: v for k, v in env.items() if k not in DROP_ENV and not k.startswith("PIP_")}
def delete_rootfs(rootfs: str | Path) -> float:
t0 = time.time()
_assert_local(Path(rootfs))
shutil.rmtree(rootfs, ignore_errors=True)
return round(time.time() - t0, 2)
def du_bytes(path: str | Path) -> int:
r = subprocess.run(["du", "-sb", str(path)], capture_output=True, text=True, check=True)
return int(r.stdout.split()[0])
def run_in_chroot(rootfs: str | Path, argv: list[str], env: dict, timeout: int | float | None, stdin: bytes | None = None,
merge_stderr: bool = False) -> tuple[bytes, bytes, int, bool]:
"""Run argv inside the chroot as uid 1000. Returns (stdout, stderr, rc, timed_out). On timeout the whole process
group is killed."""
cmd = ["chroot", f"--userspec={UID}:{GID}", str(rootfs)] + argv
p = subprocess.Popen(cmd, stdin=subprocess.PIPE if stdin is not None else subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT if merge_stderr else subprocess.PIPE, env=env, start_new_session=True)
try:
out, err = p.communicate(stdin, timeout=timeout)
return out, err or b"", p.returncode, False
except subprocess.TimeoutExpired:
try:
os.killpg(p.pid, signal.SIGKILL)
except ProcessLookupError:
pass
out, err = p.communicate()
return out or b"", err or b"", -1, True
def audit_write(path: str | Path | None, lock: threading.Lock, rec: dict) -> None:
if not path:
return
with lock:
with open(path, "a", encoding="utf-8") as fh:
fh.write(json.dumps(rec, ensure_ascii=False) + "\n")
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
sub = ap.add_subparsers(dest="cmd", required=True)
f = sub.add_parser("fetch", help="download the registry layers + manifests of the Verified-mini images into the store")
f.add_argument("--store", default=str(DEFAULT_STORE))
f.add_argument("--ids", nargs="*")
f.add_argument("--cap-gb", type=float, default=CAP_COMPRESSED_BYTES / 1e9)
f.add_argument("--workers", type=int, default=6)
f.set_defaults(fn=cmd_fetch)
g = sub.add_parser("gate", help="10-second chroot/capsh startup gate")
g.add_argument("--work-root", default=str(DEFAULT_WORK_ROOT))
g.set_defaults(fn=lambda a: print(json.dumps(startup_gate(Path(a.work_root)), indent=1)) or 0)
c = sub.add_parser("check", help="verify the store holds every layer of the given ids (no network)")
c.add_argument("--store", default=str(DEFAULT_STORE))
c.add_argument("--ids", nargs="*")
c.set_defaults(fn=lambda a: print(json.dumps(require_images(a.ids or C.mini_ids(), Path(a.store)))) or 0)
a = ap.parse_args()
return a.fn(a)
if __name__ == "__main__":
raise SystemExit(main())