Benjamin-eecs's picture
release v1: 65 held-out tasks, 78 bootstrap records, r2e_local adapter, manifest ae94c40b
e1f5446 verified
Raw History Blame Contribute Delete
7.96 kB
"""LocalSandbox: drop-in replacement for repo2rlenv.bootstrap.docker.DockerSandbox.
Interface used by the pipeline (commit_runtime.py and pr_runtime_validate.py):
start(...), exec(command, timeout=...), read_file(), list_dir(), cleanup(),
context-manager protocol. commit() and push() are Docker-only and raise.
Semantics:
* `exec` runs `bash -lc <command>` as a subprocess with cwd = the sandbox
directory. The literal `/workspace` that the validation stage scripts
hardcode (pr_runtime_validate.py lines 66, 67, 117, 143, 151, 163, 170)
is rewritten to the sandbox directory.
* Each sandbox gets its own HOME (so `git config --global` stays local) and
its own virtual environment on PATH (`<sandbox>/.venv/bin`). The venv
directory is excluded by the stage script's `git clean -fdx -e .venv`.
* State persists across `exec` calls exactly as it does in a container.
"""
from __future__ import annotations
import os
import shlex
import subprocess
import time
from pathlib import Path
from repo2rlenv.bootstrap.docker import DockerError, ExecResult
WORKSPACE_LITERAL = "/workspace"
def _run_bash(
command: str,
*,
cwd: Path,
env: dict[str, str],
timeout: int,
) -> ExecResult:
"""Run one bash command; never raises on non-zero exit (mirrors docker._run)."""
start = time.monotonic()
try:
proc = subprocess.run(
["bash", "-lc", command],
cwd=str(cwd),
env=env,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired as exc:
out = exc.stdout
if isinstance(out, (bytes, bytearray)):
out = out.decode(errors="replace")
return ExecResult(
exit_code=124,
stdout=out or "",
stderr=f"[timeout after {timeout}s]",
duration_sec=time.monotonic() - start,
)
return ExecResult(
exit_code=proc.returncode,
stdout=proc.stdout,
stderr=proc.stderr,
duration_sec=time.monotonic() - start,
)
class LocalSandbox:
"""A persistent per-repository working directory with its own venv and HOME."""
def __init__(
self,
sandbox_dir: Path,
*,
extra_env: dict[str, str] | None = None,
post_clean_cmds: list[str] | None = None,
):
self.sandbox_dir = Path(sandbox_dir).resolve()
# BootstrapResult.rebuild_cmds: re-applied after every `git clean -fdx`
# in a validation stage, because the clean removes build-generated,
# untracked files (hatch-vcs / setuptools-scm version modules) that an
# editable install needs at import time. Same role the field has upstream.
self.post_clean_cmds = [c for c in (post_clean_cmds or []) if c.strip()]
if not (self.sandbox_dir / ".git").exists():
raise DockerError(f"sandbox {self.sandbox_dir} is not a git checkout")
self.venv_dir = self.sandbox_dir / ".venv"
self.home_dir = self.sandbox_dir.parent / f".home-{self.sandbox_dir.name}"
self.home_dir.mkdir(parents=True, exist_ok=True)
# Attribute parity with DockerSandbox for any caller that reads them.
self.container_id = f"local:{self.sandbox_dir.name}"
self.repo_mount = str(self.sandbox_dir)
self.platform = "local"
self._alive = True
self._extra_env = dict(extra_env or {})
# ----- construction -------------------------------------------------------
@classmethod
def start(
cls,
base_image: str = "",
repo_dir: Path | None = None,
*,
sandbox_dir: Path | None = None,
platform: str = "local",
workdir: str = WORKSPACE_LITERAL,
env: dict[str, str] | None = None,
timeout: int = 600,
on_phase=None,
post_clean_cmds: list[str] | None = None,
) -> LocalSandbox:
"""Signature-compatible with DockerSandbox.start; `base_image` is ignored.
`sandbox_dir` must point at a prepared checkout (see bootstrap_repo.py).
"""
del base_image, platform, workdir, timeout
target = sandbox_dir or repo_dir
if target is None:
raise DockerError("LocalSandbox.start needs sandbox_dir")
sb = cls(Path(target), extra_env=env, post_clean_cmds=post_clean_cmds)
if on_phase is not None:
try:
on_phase("sandbox_done", {"detail": sb.container_id})
except Exception:
pass
return sb
# ----- environment ---------------------------------------------------------
def _env(self) -> dict[str, str]:
venv_bin = self.venv_dir / "bin"
base_path = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
if os.path.isdir("/opt/homebrew/bin"):
base_path = "/opt/homebrew/bin:" + base_path
env = {
"PATH": f"{venv_bin}:{base_path}",
"HOME": str(self.home_dir),
"VIRTUAL_ENV": str(self.venv_dir),
"LANG": "C.UTF-8",
"LC_ALL": "C.UTF-8",
"PYTHONDONTWRITEBYTECODE": "1",
"PYTHONUNBUFFERED": "1",
"PIP_DISABLE_PIP_VERSION_CHECK": "1",
"GIT_TERMINAL_PROMPT": "0",
"R2E_SANDBOX_DIR": str(self.sandbox_dir),
}
env.update(self._extra_env)
return env
def _rewrite(self, command: str) -> str:
cmd = command.replace(WORKSPACE_LITERAL, str(self.sandbox_dir))
if self.post_clean_cmds:
rebuild = " && ".join(self.post_clean_cmds)
lines = cmd.split("\n")
out: list[str] = []
for line in lines:
out.append(line)
if line.lstrip().startswith("git clean -fdx"):
out.append(f"({rebuild}) >/dev/null 2>&1 || true")
cmd = "\n".join(out)
# `bash -lc` runs the login profile first; on macOS path_helper reorders
# PATH and would put /usr/bin ahead of the venv. Re-assert it afterwards.
venv_bin = self.venv_dir / "bin"
return f'export PATH="{venv_bin}:$PATH"\n{cmd}'
# ----- DockerSandbox interface --------------------------------------------
def exec(self, command: str, *, timeout: int = 300) -> ExecResult:
if not self._alive:
raise DockerError("sandbox has been cleaned up; cannot exec")
return _run_bash(
self._rewrite(command), cwd=self.sandbox_dir, env=self._env(), timeout=timeout
)
def read_file(self, path: str, *, max_bytes: int = 50_000) -> str:
r = self.exec(f"head -c {max_bytes} {shlex.quote(self._rewrite(path))}", timeout=30)
if not r.ok:
raise DockerError(f"read_file({path!r}) failed: {r.stderr.strip()[:200]}")
return r.stdout
def list_dir(self, path: str = ".") -> list[str]:
r = self.exec(f"ls -1A {shlex.quote(self._rewrite(path))} | head -200", timeout=10)
if not r.ok:
return []
return [line for line in r.stdout.splitlines() if line.strip()]
def commit(self, tag: str, *, message: str = "", timeout: int = 600) -> str:
raise DockerError("LocalSandbox has no image to commit")
def push(self, tag: str, *, timeout: int = 900) -> bool:
raise DockerError("LocalSandbox has no image to push")
def cleanup(self) -> None:
# The checkout and venv are persistent assets; only mark closed and
# restore a clean tree so the next user starts from the pinned ref.
if not self._alive:
return
self.exec("git reset -q --hard HEAD && git clean -fdxq -e .venv || true", timeout=120)
self._alive = False
def __enter__(self) -> LocalSandbox:
return self
def __exit__(self, *exc) -> None:
self.cleanup()