File size: 9,687 Bytes
5cba866
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run the original trusted coding rubric in a fresh, offline verifier container."""

from __future__ import annotations

import asyncio
import hashlib
import importlib
import importlib.metadata
import json
import os
import shlex
import shutil
import signal
import subprocess
import sys
from pathlib import Path
from typing import Any

from evidence import REVISION, validate_report

OUT = Path("/logs/verifier")
PRIVATE = Path("/var/lib/task-evidence")
CONFIG = Path("/tests/config.json")
PATCH = Path("/workspace/submissions/submitted.patch")
GRADER_HOME = "/tmp/agent-home"


def _run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
    return subprocess.run(command, text=True, capture_output=True, timeout=300, **kwargs)


def _preflight(config: dict[str, Any]) -> None:
    if importlib.metadata.version("hud") != config["grader_version"]:
        raise RuntimeError("Grader library version does not match the task")
    for filename, expected in config["verifier_files"].items():
        if hashlib.sha256(Path(filename).read_bytes()).hexdigest() != expected:
            raise RuntimeError(f"Verifier source changed: {filename}")
    for command in config["preflight"]:
        completed = _run(command, cwd="/workspace/repo")
        if completed.returncode:
            raise RuntimeError(f"Prerequisite failed: {command}: {completed.stderr[-2000:]}")


def _readable_mode(path: Path) -> int:
    # World-readable, keeping what is executable so: a grader may ship tools.
    return 0o755 if path.is_dir() or path.stat().st_mode & 0o111 else 0o644


def _permissions() -> None:
    # The orchestrator owns reports and rubric definitions. Grader commands,
    # and so the candidate's code, run as uid 1000: the user the task installed
    # its toolchain and caches for. They cannot read gold/vault or overwrite
    # the rubric or the result files, which stay root's.
    Path("/hud").chmod(0o711)
    for root in (Path("/hud/grader"), Path("/hud/base"), Path("/hud/base-src")):
        if root.exists():
            root.chmod(0o755)
            for path in root.rglob("*"):
                if not path.is_symlink():
                    path.chmod(_readable_mode(path))
    home = Path(GRADER_HOME)
    home.mkdir(parents=True, exist_ok=True)
    os.chown(home, 1000, 1000)
    for directory in ("/hud/logs", "/hud/gocache", "/hud/grader/runner"):
        path = Path(directory)
        path.mkdir(parents=True, exist_ok=True)
        for item in (path, *path.rglob("*")):
            if not item.is_symlink():
                os.chown(item, 1000, 1000)
                item.chmod(_readable_mode(item))


def _hand_over_checkout() -> None:
    # The original grader runs as root and may run the candidate's own suite in
    # place, which writes into the tree. The rubric resets and re-applies the
    # candidate as root, so give what root touched back to the grading user.
    # Installed dependency trees are large and already that user's.
    subprocess.run(
        [
            "find",
            "/workspace/repo",
            "-path",
            "*/node_modules",
            "-prune",
            "-o",
            "!",
            "-user",
            "1000",
            "-exec",
            "chown",
            "-h",
            "1000:1000",
            "{}",
            "+",
        ],
        check=True,
        capture_output=True,
        timeout=3600,
    )


async def _grade(config: dict[str, Any], record: dict[str, Any]) -> None:
    _preflight(config)
    sys.path.insert(0, "/app")
    task: Any = importlib.import_module("tasks")
    await task._setup()
    _permissions()
    patch = PATCH.read_bytes()
    if patch:
        checked = _run(["git", "apply", "--check", str(PATCH)], cwd="/workspace/repo")
        if checked.returncode:
            record.update(
                status="rejected_patch",
                patch_error=checked.stderr[-4000:],
                result={"reward": 0.0, "subscores": None},
            )
            return
        _run(["git", "apply", str(PATCH)], cwd="/workspace/repo", check=True)
    original = task.BashGrader
    fault_exit = config.get("fault_exit")
    faulted: list[tuple[tuple[Any, ...], dict[str, Any], str]] = []

    class ObservedGrader:
        @classmethod
        async def grade(cls, *args: Any, **kwargs: Any) -> Any:
            command = kwargs["command"]
            _hand_over_checkout()
            kwargs["command"] = (
                "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs "
                f"env HOME={GRADER_HOME} bash -lc " + shlex.quote(command)
            )
            score = await original.grade(*args, **kwargs)
            snapshot = score.model_dump(mode="json")
            record["commands"].append(snapshot)
            (PRIVATE / "commands.json").write_text(json.dumps(record["commands"], indent=2))
            info = snapshot.get("info") or {}
            if info.get("timed_out") or type(info.get("exit_code")) is not int:
                raise RuntimeError(f"Grader infrastructure failure: {snapshot['name']}")
            if fault_exit is not None and info["exit_code"] == fault_exit:
                # The grader says it could not judge. Whether the submission or
                # the environment is the reason is settled after grading.
                faulted.append((args, dict(kwargs), snapshot["name"]))
            elif info["exit_code"] not in (0, 1):
                raise RuntimeError(f"Grader command exit {info['exit_code']}: {snapshot['name']}")
            return score

    task.BashGrader = ObservedGrader
    result = await task._grade(None)
    if faulted:
        # Ask the same commands about the untouched repository. A verdict there
        # means the grader works here and the submission is what it could not
        # judge, so the criterion stays unmet. No verdict there means the
        # environment is at fault, and the attempt is invalid.
        await task.repo_lib.git(task.REPO_DIR, "reset", "--hard", "HEAD")
        await task.repo_lib.git(task.REPO_DIR, "clean", "-fd")
        # Graders keep state between criteria, some of them a copy of the tree
        # they judged. It describes the submission, so it goes too.
        for leftover in Path(getattr(task, "LOGS_DIR", "/hud/logs")).iterdir():
            if leftover.is_dir() and not leftover.is_symlink():
                shutil.rmtree(leftover)
            else:
                leftover.unlink()
        record["fault_probes"] = []
        for args, kwargs, name in faulted:
            _hand_over_checkout()
            probe = (await original.grade(*args, **kwargs)).model_dump(mode="json")
            info = probe.get("info") or {}
            record["fault_probes"].append(
                {
                    "name": name,
                    "exit_code": info.get("exit_code"),
                    "timed_out": info.get("timed_out"),
                    "stdout": (info.get("stdout") or "")[-2000:],
                }
            )
            (PRIVATE / "fault_probes.json").write_text(json.dumps(record["fault_probes"], indent=2))
            if info.get("timed_out") or info.get("exit_code") not in (0, 1):
                raise RuntimeError(f"Grader cannot judge the untouched repository: {name}")
    record["result"] = result.model_dump(mode="json")
    # A rubric may answer an empty change without running any criterion.
    record["status"] = "empty_patch" if not patch and not record["commands"] else "graded"


def _stop_candidate_processes() -> None:
    # A candidate may fork. End its UID's processes before publishing evidence
    # to a host bind mount, whose permissions may differ on Docker Desktop.
    for directory in Path("/proc").iterdir():
        if not directory.name.isdecimal():
            continue
        try:
            status = (directory / "status").read_text()
            uid = next(line.split()[1] for line in status.splitlines() if line.startswith("Uid:"))
            if uid == "1000":
                os.kill(int(directory.name), signal.SIGKILL)
        except (FileNotFoundError, ProcessLookupError):
            pass


def main() -> None:
    """Persist structured evidence and publish reward only after validation."""
    OUT.mkdir(parents=True, exist_ok=True)
    PRIVATE.mkdir(parents=True, exist_ok=True, mode=0o700)
    PRIVATE.chmod(0o700)
    reward_path = OUT / "reward.txt"
    reward_path.unlink(missing_ok=True)
    config = json.loads(CONFIG.read_text())
    shutil.copy2(CONFIG, OUT / "config.json")
    record: dict[str, Any] = {
        "revision": REVISION,
        "task_id": config["task_id"],
        "grader_version": importlib.metadata.version("hud"),
        "commands": [],
        "status": "error",
    }
    try:
        if PATCH.is_symlink() or not PATCH.is_file() or PATCH.stat().st_size > 32 * 1024 * 1024:
            raise ValueError("Missing, oversized or symlink submission")
        record["patch_sha256"] = hashlib.sha256(PATCH.read_bytes()).hexdigest()
        try:
            asyncio.run(_grade(config, record))
        finally:
            _stop_candidate_processes()
        reward_path.unlink(missing_ok=True)
        validate_report(record, config, record["patch_sha256"])
        (OUT / "report.json").write_text(json.dumps(record, indent=2))
        reward_path.write_text(str(record["result"]["reward"]) + "\n")
    except BaseException as error:
        reward_path.unlink(missing_ok=True)
        record.update(status="error", error={"type": type(error).__name__, "message": str(error)})
        (OUT / "report.json").write_text(json.dumps(record, indent=2))
        raise


if __name__ == "__main__":
    main()