Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 16,104 Bytes
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9653a0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9653a0f
 
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
"""Move upstream pytest execution into a credential-free worker container.

The upstream workspace and logged file tools remain in the trusted episode
process. Only a bounded copy travels to the worker; regular text-file changes
are copied back. Execution is a fresh unprivileged, seccomp-filtered process.
"""

from __future__ import annotations

import argparse
import copy
import json
import os
import signal
import subprocess
import sys
import tempfile
import threading
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path, PurePosixPath

MAX_BYTES = 4 * 1024 * 1024
MAX_FILES = 128
LOCK = threading.Lock()


class ExecutionError(RuntimeError):
    """An unavailable or invalid executor is an infrastructure error."""


def validate_files(files: dict) -> dict[str, str]:
    if not isinstance(files, dict) or len(files) > MAX_FILES:
        raise ExecutionError("Invalid execution workspace")
    if len(json.dumps(files).encode()) > MAX_BYTES:
        raise ExecutionError("Execution workspace exceeds 4 MiB")
    for name, content in files.items():
        if not isinstance(name, str) or not isinstance(content, str):
            raise ExecutionError("Execution files must be text")
        path = PurePosixPath(name)
        if not name or path.is_absolute() or ".." in path.parts or "\\" in name or "\x00" in name:
            raise ExecutionError("Unsafe execution workspace path")
    return files


def snapshot(directory: Path) -> dict[str, str]:
    files = {}
    total = 0
    for path in sorted(directory.rglob("*")):
        if "__pycache__" in path.parts or ".pytest_cache" in path.parts:
            continue
        if path.is_symlink():
            raise ExecutionError("Execution workspace contains a symlink")
        if not path.is_file():
            continue
        if len(files) >= MAX_FILES or path.stat().st_size > MAX_BYTES:
            raise ExecutionError("Execution workspace exceeds limits")
        total += path.stat().st_size
        if total > MAX_BYTES:
            raise ExecutionError("Execution workspace exceeds 4 MiB")
        try:
            files[path.relative_to(directory).as_posix()] = path.read_bytes().decode("utf-8")
        except UnicodeError as error:
            raise ExecutionError("Execution workspace contains non-text output") from error
    return validate_files(files)


def _sync(directory: Path, files: dict[str, str]) -> None:
    validate_files(files)
    current = snapshot(directory)
    for name in current.keys() - files.keys():
        (directory / name).unlink()
    for name, content in files.items():
        destination = directory / name
        # The trusted workspace never executes code and cannot create symlinks.
        if destination.is_symlink():
            raise ExecutionError("Workspace destination is a symlink")
        destination.parent.mkdir(parents=True, exist_ok=True)
        destination.write_text(content)


class RemotePytestRunner:
    def __init__(self, url: str):
        self.url = url.rstrip("/")

    def __call__(self, cwd: Path, targets: list[str], exitfirst: bool,
                 noconftest: bool, timeout_s: int) -> tuple[int | None, str]:
        payload = {
            "files": snapshot(cwd), "targets": targets, "exitfirst": exitfirst,
            "noconftest": noconftest, "timeout_s": timeout_s,
        }
        request = urllib.request.Request(
            self.url + "/execute", data=json.dumps(payload).encode(),
            headers={"Content-Type": "application/json"}, method="POST",
        )
        try:
            with urllib.request.urlopen(request, timeout=timeout_s + 15) as response:
                raw = response.read(MAX_BYTES * 2 + 1)
            if len(raw) > MAX_BYTES * 2:
                raise ExecutionError("Execution response exceeds limit")
            result = json.loads(raw)
            if result.get("error"):
                raise ExecutionError(result["error"])
            if type(result.get("returncode")) not in (int, type(None)) or not isinstance(result.get("output"), str):
                raise ExecutionError("Invalid execution result")
            _sync(cwd, result["files"])
            return result["returncode"], result["output"]
        except ExecutionError:
            raise
        except Exception as error:
            raise ExecutionError("Coding execution worker failed") from error


class RecordingPytestRunner:
    """Record actual isolated executions, including exact pytest output."""

    def __init__(self, delegate, path: Path):
        self.delegate, self.path, self.calls = delegate, Path(path), []

    def __call__(self, cwd: Path, targets: list[str], exitfirst: bool,
                 noconftest: bool, timeout_s: int) -> tuple[int | None, str]:
        request = {"files": snapshot(cwd), "targets": targets, "exitfirst": exitfirst,
                   "noconftest": noconftest, "timeout_s": timeout_s}
        code, output = self.delegate(cwd, targets, exitfirst, noconftest, timeout_s)
        self.calls.append({"request": request, "result": {
            "returncode": code, "output": output, "files": snapshot(cwd),
        }})
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self.path.write_text(json.dumps({"schema_version": 1, "fixture": True, "calls": self.calls}, indent=2) + "\n")
        return code, output


class ReplayPytestRunner:
    """Strictly replay fixture executions so timing never changes observations.

    This proves transport parity, not code correctness. Real isolated execution
    is recorded first and independent verification must execute the final code.
    """

    def __init__(self, path: Path):
        value = json.loads(Path(path).read_text())
        if value.get("schema_version") != 1 or value.get("fixture") is not True or not isinstance(value.get("calls"), list):
            raise ExecutionError("Invalid fixture execution tape")
        self.calls, self.cursor = value["calls"], 0

    def __call__(self, cwd: Path, targets: list[str], exitfirst: bool,
                 noconftest: bool, timeout_s: int) -> tuple[int | None, str]:
        request = {"files": snapshot(cwd), "targets": targets, "exitfirst": exitfirst,
                   "noconftest": noconftest, "timeout_s": timeout_s}
        if self.cursor >= len(self.calls) or self.calls[self.cursor]["request"] != request:
            raise ExecutionError(f"Execution tape request mismatch at {self.cursor}")
        result = copy.deepcopy(self.calls[self.cursor]["result"])
        self.cursor += 1
        _sync(cwd, result["files"])
        return result["returncode"], result["output"]

    def assert_consumed(self) -> None:
        if self.cursor != len(self.calls):
            raise ExecutionError("Execution tape has unconsumed calls")


def validate_python_command(command) -> list[str]:
    """A bounded Python -c program or workspace-relative script, never a shell."""
    if (not isinstance(command, list) or not command or len(command) > 64
            or any(not isinstance(arg, str) or "\x00" in arg for arg in command)
            or len(json.dumps(command).encode()) > 65536):
        raise ExecutionError("Invalid Python command")
    if command[0] == "-c":
        if len(command) < 2 or not command[1]:
            raise ExecutionError("Invalid Python -c program")
    else:
        script = PurePosixPath(command[0])
        if (not command[0].endswith(".py") or command[0].startswith("-") or script.is_absolute()
                or ".." in script.parts or "\\" in command[0]):
            raise ExecutionError("Invalid Python script path")
    return list(command)


def child_pytest_args(pytest_args, workspace: str, targets, *, exitfirst: bool, noconftest: bool) -> list[str]:
    """Stanford's pytest arguments, with collection pinned to the workspace for --noconftest runs.

    Stanford's `-c /dev/null` moves pytest's confcutdir to /dev, so pytest scandir()s every
    ancestor of the workspace; the worker's /tmp is not listable (0711) and pytest then fails
    (spec_tests_pass False). Pinning confcutdir loads no conftest either way, so the worker and
    the verifier now agree.
    """
    targets = list(targets)
    args = pytest_args(workspace, targets, exitfirst=exitfirst, noconftest=noconftest)
    if noconftest:
        cut = len(args) - len(targets)
        args[cut:cut] = ["--confcutdir", workspace]
    return args


def execute(payload: dict) -> dict:
    """Trusted worker handler; never call this on a host containing credentials."""
    if os.geteuid() != 0:
        raise ExecutionError("Executor must be root inside its isolated container to drop child privileges")
    files = validate_files(payload["files"])
    timeout = payload.get("timeout_s")
    if type(timeout) is not int or not 1 <= timeout <= 120:
        raise ExecutionError("Execution timeout must be in [1, 120]")
    mode = payload.get("mode", "pytest")
    if mode not in {"pytest", "python"}:
        raise ExecutionError("Invalid execution mode")
    if mode == "python":
        command = validate_python_command(payload.get("command"))
        if type(payload.get("home")) is not bool:
            raise ExecutionError("Invalid Python home setting")
    else:
        targets = payload.get("targets")
        if not isinstance(targets, list) or any(not isinstance(t, str) or t.startswith("-") for t in targets):
            raise ExecutionError("Invalid pytest targets")
        if type(payload.get("exitfirst")) is not bool or type(payload.get("noconftest")) is not bool:
            raise ExecutionError("Invalid pytest settings")
    from collab_intel.harness.sandbox import pytest_args

    with (LOCK, tempfile.TemporaryDirectory(prefix="ci-execute-", dir="/tmp") as temporary,
          tempfile.TemporaryDirectory(prefix="ci-scratch-", dir="/tmp") as scratch):
        directory = Path(temporary)
        for name, content in files.items():
            destination = directory / name
            destination.parent.mkdir(parents=True, exist_ok=True)
            destination.write_text(content)
        for path in [directory, *directory.rglob("*")]:
            os.chown(path, 65534, 65534)
        os.chown(scratch, 65534, 65534)
        if mode == "python":
            command = [str(directory) if arg == "${CI_WORKSPACE}" else arg for arg in command]
            child_request = {"mode": "python", "command": command, "timeout_s": timeout}
        else:
            args = child_pytest_args(pytest_args, str(directory), targets,
                                     exitfirst=payload["exitfirst"], noconftest=payload["noconftest"])
            child_request = {"args": args, "timeout_s": timeout}
        child_env = {"PATH": "/usr/local/bin:/usr/bin:/bin", "PYTHONDONTWRITEBYTECODE": "1",
                     "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1", "TMPDIR": scratch}
        if mode == "pytest" or payload["home"]:
            child_env["HOME"] = str(directory)
        with tempfile.TemporaryFile() as output, tempfile.TemporaryFile() as errors:
            process = subprocess.Popen(
                [sys.executable, "-I", os.environ.get("CI_PYTEST_CHILD", str(Path(__file__).with_name("pytest_child.py")))],
                stdin=subprocess.PIPE, stdout=output, stderr=errors if mode == "python" else subprocess.STDOUT,
                cwd=directory,
                user=65534, group=65534, extra_groups=[], start_new_session=True,
                env=child_env,
            )
            timed_out = False
            try:
                process.communicate(json.dumps(child_request).encode(), timeout=timeout + 2)
            except subprocess.TimeoutExpired:
                timed_out = True
                os.killpg(process.pid, signal.SIGKILL)
                process.wait()
            finally:
                try:
                    os.killpg(process.pid, signal.SIGKILL)
                except ProcessLookupError:
                    pass
            marker = b"CI_EXECUTION_ISOLATED_V1\n"
            output.seek(0)
            isolated = output.read(len(marker)) == marker
            output.seek(0, os.SEEK_END)
            output.seek(max(len(marker) if isolated else 0, output.tell() - 65536))
            result = output.read(65536).decode(errors="replace")
            errors.seek(0, os.SEEK_END)
            errors.seek(max(0, errors.tell() - 65536))
            stderr = errors.read(65536).decode(errors="replace")
        if not isolated:
            raise ExecutionError("Execution isolation could not be activated: " + result[-1000:])
        if mode == "python":
            return {"returncode": None if timed_out else process.returncode,
                    "stdout": result, "stderr": stderr, "files": snapshot(directory)}
        return {"returncode": None if timed_out else process.returncode,
                "output": result, "files": snapshot(directory)}


class VerifierPytestRunner:
    """Execute in a fresh verifier, with private mounts unreadable by the child.

    This runner must not be used as a host-development shortcut. The generated
    verifier is credential-free, has its own filesystem, and runs as container
    root solely to drop the execution child's privileges.
    """

    def __init__(self):
        if os.environ.get("CI_EXECUTION_CONTAINER") != "1" or os.geteuid() != 0:
            raise ExecutionError("Independent coding verification requires its isolated verifier container")
        child = Path(os.environ.get("CI_PYTEST_CHILD", ""))
        if not child.is_file() or child.parent != Path("/opt"):
            raise ExecutionError("Verifier has no public execution child")
        for private in ("/tests", "/evidence", "/logs"):
            path = Path(private)
            if path.exists():
                path.chmod(0o700)

    def __call__(self, cwd: Path, targets: list[str], exitfirst: bool,
                 noconftest: bool, timeout_s: int) -> tuple[int | None, str]:
        result = execute({"files": snapshot(cwd), "targets": targets, "exitfirst": exitfirst,
                          "noconftest": noconftest, "timeout_s": timeout_s})
        _sync(cwd, result["files"])
        return result["returncode"], result["output"]


class Handler(BaseHTTPRequestHandler):
    def log_message(self, format, *args):
        pass

    def respond(self, status: int, value: dict) -> None:
        data = json.dumps(value).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if self.path != "/health":
            self.respond(404, {"ok": False})
            return
        # Standalone worker images carry this standard-library-only helper;
        # package imports also support the local offline executor tests.
        if __package__:
            from .provenance import runtime_code_identity
        else:
            from provenance import runtime_code_identity
        self.respond(200, {"ok": True, "code_identity": runtime_code_identity(Path(__file__).parent)})

    def do_POST(self):
        if self.path != "/execute":
            self.respond(404, {"error": "Unknown execution route"})
            return
        try:
            length = int(self.headers.get("Content-Length", "0"))
            if not 0 < length <= MAX_BYTES * 2:
                raise ExecutionError("Invalid execution request size")
            payload = json.loads(self.rfile.read(length))
            self.respond(200, execute(payload))
        except Exception as error:
            self.respond(500, {"error": f"Execution failed: {type(error).__name__}: {error}"})


def main(argv: list[str] | None = None) -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--host", default="0.0.0.0")
    parser.add_argument("--port", default=8002, type=int)
    args = parser.parse_args(argv)
    ThreadingHTTPServer((args.host, args.port), Handler).serve_forever()


if __name__ == "__main__":
    main()