File size: 7,962 Bytes
e1f5446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
"""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()