Marquis03 commited on
Commit
5b39d16
·
verified ·
1 Parent(s): 79fde60

Upload folder using huggingface_hub (part 30)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +18 -0
  2. mpc-sok--frameworks.2af8f22/tests/harbor_prepare_download_env.sh +34 -0
  3. mpc-sok--frameworks.2af8f22/tests/programgym_evaluator.py +1201 -0
  4. mpc-sok--frameworks.2af8f22/tests/programgym_task.json +0 -0
  5. mpc-sok--frameworks.2af8f22/tests/test.sh +82 -0
  6. mpc-sok--frameworks.2af8f22/tests/workspace.tar.gz +3 -0
  7. mpolden--echoip.746db5e/environment/Dockerfile +60 -0
  8. mpolden--echoip.746db5e/environment/download.sh +169 -0
  9. mpolden--echoip.746db5e/environment/executable +3 -0
  10. mpolden--echoip.746db5e/environment/programgym-go.tar.gz +3 -0
  11. mpolden--echoip.746db5e/environment/workspace.tar.gz +3 -0
  12. mpolden--echoip.746db5e/instruction.md +98 -0
  13. mpolden--echoip.746db5e/solution/solve.sh +33 -0
  14. mpolden--echoip.746db5e/task.toml +69 -0
  15. mpolden--echoip.746db5e/tests/Dockerfile +68 -0
  16. mpolden--echoip.746db5e/tests/blobs/tests/generated_module_01.tar.gz +3 -0
  17. mpolden--echoip.746db5e/tests/blobs/tests/generated_module_02.tar.gz +3 -0
  18. mpolden--echoip.746db5e/tests/blobs/tests/generated_module_03.tar.gz +3 -0
  19. mpolden--echoip.746db5e/tests/blobs/tests/generated_module_04.tar.gz +3 -0
  20. mpolden--echoip.746db5e/tests/download.sh +169 -0
  21. mpolden--echoip.746db5e/tests/executable +3 -0
  22. mpolden--echoip.746db5e/tests/programgym-go.tar.gz +3 -0
  23. mpolden--echoip.746db5e/tests/programgym_evaluator.py +1201 -0
  24. mpolden--echoip.746db5e/tests/programgym_task.json +552 -0
  25. mpolden--echoip.746db5e/tests/test.sh +82 -0
  26. mpolden--echoip.746db5e/tests/workspace.tar.gz +3 -0
  27. mpostument--grafana-sync.0dd7ef8/environment/Dockerfile +64 -0
  28. mpostument--grafana-sync.0dd7ef8/environment/download.sh +0 -0
  29. mpostument--grafana-sync.0dd7ef8/environment/executable +3 -0
  30. mpostument--grafana-sync.0dd7ef8/environment/harbor_prepare_download_env.sh +34 -0
  31. mpostument--grafana-sync.0dd7ef8/environment/programgym-go.tar.gz +3 -0
  32. mpostument--grafana-sync.0dd7ef8/environment/workspace.tar.gz +3 -0
  33. mpostument--grafana-sync.0dd7ef8/instruction.md +98 -0
  34. mpostument--grafana-sync.0dd7ef8/solution/solve.sh +33 -0
  35. mpostument--grafana-sync.0dd7ef8/task.toml +69 -0
  36. mpostument--grafana-sync.0dd7ef8/tests/Dockerfile +73 -0
  37. mpostument--grafana-sync.0dd7ef8/tests/blobs/tests/generated_module_01.tar.gz +3 -0
  38. mpostument--grafana-sync.0dd7ef8/tests/blobs/tests/generated_module_02.tar.gz +3 -0
  39. mpostument--grafana-sync.0dd7ef8/tests/blobs/tests/generated_module_03.tar.gz +3 -0
  40. mpostument--grafana-sync.0dd7ef8/tests/blobs/tests/generated_module_04.tar.gz +3 -0
  41. mpostument--grafana-sync.0dd7ef8/tests/download.sh +0 -0
  42. mpostument--grafana-sync.0dd7ef8/tests/executable +3 -0
  43. mpostument--grafana-sync.0dd7ef8/tests/harbor_prepare_download_env.sh +34 -0
  44. mpostument--grafana-sync.0dd7ef8/tests/programgym-go.tar.gz +3 -0
  45. mpostument--grafana-sync.0dd7ef8/tests/programgym_evaluator.py +1201 -0
  46. mpostument--grafana-sync.0dd7ef8/tests/programgym_task.json +285 -0
  47. mpostument--grafana-sync.0dd7ef8/tests/test.sh +82 -0
  48. mpostument--grafana-sync.0dd7ef8/tests/workspace.tar.gz +3 -0
  49. mptre--yank.b9f76bc/environment/Dockerfile +56 -0
  50. mptre--yank.b9f76bc/environment/download.sh +24 -0
.gitattributes CHANGED
@@ -1760,3 +1760,21 @@ mozillazg--request.f66876a/environment/executable filter=lfs diff=lfs merge=lfs
1760
  mozillazg--request.f66876a/tests/executable filter=lfs diff=lfs merge=lfs -text
1761
  mpc-sok--frameworks.2af8f22/environment/executable filter=lfs diff=lfs merge=lfs -text
1762
  mpc-sok--frameworks.2af8f22/tests/executable filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1760
  mozillazg--request.f66876a/tests/executable filter=lfs diff=lfs merge=lfs -text
1761
  mpc-sok--frameworks.2af8f22/environment/executable filter=lfs diff=lfs merge=lfs -text
1762
  mpc-sok--frameworks.2af8f22/tests/executable filter=lfs diff=lfs merge=lfs -text
1763
+ mpolden--echoip.746db5e/environment/executable filter=lfs diff=lfs merge=lfs -text
1764
+ mpolden--echoip.746db5e/tests/executable filter=lfs diff=lfs merge=lfs -text
1765
+ mpostument--grafana-sync.0dd7ef8/environment/executable filter=lfs diff=lfs merge=lfs -text
1766
+ mpostument--grafana-sync.0dd7ef8/tests/executable filter=lfs diff=lfs merge=lfs -text
1767
+ mrdimidium--nanoid.359c02d/environment/executable filter=lfs diff=lfs merge=lfs -text
1768
+ mrdimidium--nanoid.359c02d/tests/executable filter=lfs diff=lfs merge=lfs -text
1769
+ mrjackwills--havn.fe9eba1/environment/executable filter=lfs diff=lfs merge=lfs -text
1770
+ mrjackwills--havn.fe9eba1/tests/executable filter=lfs diff=lfs merge=lfs -text
1771
+ mrnugget--fzz.0ef022a/environment/executable filter=lfs diff=lfs merge=lfs -text
1772
+ mrnugget--fzz.0ef022a/tests/executable filter=lfs diff=lfs merge=lfs -text
1773
+ mroth--slacknimate.9a4cd3e/environment/executable filter=lfs diff=lfs merge=lfs -text
1774
+ mroth--slacknimate.9a4cd3e/tests/executable filter=lfs diff=lfs merge=lfs -text
1775
+ msoap--go-carpet.ebd5df8/environment/executable filter=lfs diff=lfs merge=lfs -text
1776
+ msoap--go-carpet.ebd5df8/tests/executable filter=lfs diff=lfs merge=lfs -text
1777
+ msoap--shell2http.378e751/environment/executable filter=lfs diff=lfs merge=lfs -text
1778
+ msoap--shell2http.378e751/tests/executable filter=lfs diff=lfs merge=lfs -text
1779
+ msokalski--delabella.0b8d371/environment/executable filter=lfs diff=lfs merge=lfs -text
1780
+ msokalski--delabella.0b8d371/tests/executable filter=lfs diff=lfs merge=lfs -text
mpc-sok--frameworks.2af8f22/tests/harbor_prepare_download_env.sh ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ cd /workspace
4
+ set -a
5
+ source /workspace/download.sh
6
+ set +a
7
+ python3 - <<'PY' > /etc/profile.d/programgym_download_env.sh
8
+ import os
9
+ import shlex
10
+
11
+ ignored = {
12
+ "ALL_PROXY",
13
+ "HTTP_PROXY",
14
+ "HTTPS_PROXY",
15
+ "NO_PROXY",
16
+ "OLDPWD",
17
+ "PIP_PROXY",
18
+ "PWD",
19
+ "SHLVL",
20
+ "_",
21
+ "all_proxy",
22
+ "http_proxy",
23
+ "https_proxy",
24
+ "no_proxy",
25
+ "pip_proxy",
26
+ }
27
+ for key in sorted(os.environ):
28
+ if key in ignored or key.startswith("BASH_FUNC_"):
29
+ continue
30
+ value = os.environ[key]
31
+ if "\n" in value:
32
+ continue
33
+ print(f"export {key}={shlex.quote(value)}")
34
+ PY
mpc-sok--frameworks.2af8f22/tests/programgym_evaluator.py ADDED
@@ -0,0 +1,1201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """In-place ProgramGym evaluator.
3
+
4
+ Mirrors ProgramGym's ``Evaluator`` pipeline as closely as a single-container,
5
+ no-Docker-in-Docker host allows. Run from ``tests/test.sh`` inside the agent's
6
+ cleanroom container after Harbor flips the verifier-phase network policy.
7
+
8
+ Differences from ``programgym.eval.eval.Evaluator`` that are structural to
9
+ running in one container:
10
+
11
+ * No fresh container per branch. ``snapshot_workspace`` / ``restore_workspace``
12
+ copy a post-compile workspace snapshot to a temp directory and restore it
13
+ before each branch; ``cleanup_lingering_processes`` kills leftover branch
14
+ processes between attempts to approximate the fresh-container boundary.
15
+ * No ``docker commit``. The post-compile workspace snapshot serves the same
16
+ role as the committed image upstream.
17
+ * Hidden test blobs are fetched on demand from HuggingFace via
18
+ ``huggingface_hub.snapshot_download`` (matching ``programgym.utils.blob_store``)
19
+ rather than being pre-staged into ``/tests/blobs/``. Override with
20
+ ``PROGRAMGYM_BLOB_DIR`` for offline reruns.
21
+
22
+ Everything else (eval_clean_hashes scrub, deterministic synthetic git seed,
23
+ ``compile.sh`` then stash + hash the executable, best-effort
24
+ ``pytest-rerunfailures``, per-branch test-tar overlay, executable hash
25
+ ``--max-worker-restart=4``, xdist worker-crash retry with serial fallback,
26
+ best-of-N attempt selection, active vs ignored test bookkeeping, scoring) is
27
+ preserved.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import hashlib
33
+ import json
34
+ import os
35
+ import re
36
+ import shlex
37
+ import shutil
38
+ import signal
39
+ import subprocess
40
+ import tempfile
41
+ import time
42
+ import traceback
43
+ import xml.etree.ElementTree as ET
44
+ from pathlib import Path
45
+ from typing import Any
46
+
47
+ WORKSPACE = Path(os.environ.get("PROGRAMGYM_WORKSPACE", "/workspace"))
48
+ STASHED_EXECUTABLE = Path("/opt/programgym-stashed-executable-do-not-modify")
49
+ METADATA_PATH = Path(
50
+ os.environ.get("PROGRAMGYM_METADATA", "/tests/programgym_task.json")
51
+ )
52
+ LOG_DIR = Path(os.environ.get("PROGRAMGYM_LOG_DIR", "/logs/verifier"))
53
+ WORKER_CRASH_PHRASE = "worker '"
54
+ XDIST_COLLAPSE_MARKERS = (
55
+ "maximum crashed workers reached",
56
+ "xdist: maximum crashed",
57
+ )
58
+
59
+ DEFAULT_HF_REPO_ID = "programgym/ProgramGym-Tests"
60
+ DEFAULT_HF_REVISION = "main"
61
+
62
+ # Oracle agent handoff files (see solution/solve.sh). Must not appear in the
63
+ # post-compile workspace snapshot or they pollute tree-scanning tests (dutree).
64
+ _ORACLE_HANDOFF_NAMES = (".programgym_oracle_reference",)
65
+
66
+ _TOOLCHAIN_BIN_DIR_CANDIDATES = (
67
+ "/usr/local/go/bin",
68
+ "/go/bin",
69
+ "/usr/local/cargo/bin",
70
+ "/root/.cargo/bin",
71
+ "/root/.ghcup/bin",
72
+ )
73
+
74
+
75
+ def toolchain_bin_dirs() -> list[str]:
76
+ """Return toolchain bin directories that exist on this image."""
77
+ candidates = list(_TOOLCHAIN_BIN_DIR_CANDIDATES)
78
+ candidates.extend(
79
+ str(path)
80
+ for path in sorted(Path("/usr/lib").glob("go-*/bin"))
81
+ if _is_accessible_dir(path)
82
+ )
83
+ seen: set[str] = set()
84
+ present: list[str] = []
85
+ for path in candidates:
86
+ if path in seen:
87
+ continue
88
+ seen.add(path)
89
+ if _is_accessible_dir(path):
90
+ present.append(path)
91
+ return present
92
+
93
+
94
+ def _is_accessible_dir(path: str | Path) -> bool:
95
+ """Return whether path is a directory without failing on protected homes."""
96
+ try:
97
+ return Path(path).is_dir()
98
+ except OSError:
99
+ return False
100
+
101
+
102
+ def bootstrap_toolchain_path() -> str:
103
+ """Prepend discovered toolchain dirs to PATH (idempotent)."""
104
+ prepend = toolchain_bin_dirs()
105
+ current_parts = [part for part in os.environ.get("PATH", "").split(":") if part]
106
+ merged: list[str] = []
107
+ for path in prepend + current_parts:
108
+ if path not in merged:
109
+ merged.append(path)
110
+ new_path = ":".join(merged)
111
+ os.environ["PATH"] = new_path
112
+ return new_path
113
+
114
+
115
+ def _bash_login_command(command: str) -> str:
116
+ """Run ``command`` under bash -lc with an explicit PATH export."""
117
+ path = bootstrap_toolchain_path()
118
+ return f"export PATH={shlex.quote(path)}; {command}"
119
+
120
+
121
+ def sha256(path: Path) -> str:
122
+ h = hashlib.sha256()
123
+ with path.open("rb") as f:
124
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
125
+ h.update(chunk)
126
+ return h.hexdigest()
127
+
128
+
129
+ def write_json(path: Path, data: dict[str, Any]) -> None:
130
+ tmp = path.with_suffix(path.suffix + ".tmp")
131
+ tmp.write_text(json.dumps(data, indent=2, sort_keys=True))
132
+ tmp.replace(path)
133
+
134
+
135
+ def _read_log_tail(path: Path | None, max_bytes: int = 65536) -> str:
136
+ if path is None or not path.exists():
137
+ return ""
138
+ data = path.read_bytes()
139
+ if len(data) <= max_bytes:
140
+ return data.decode(errors="replace")
141
+ return data[-max_bytes:].decode(errors="replace")
142
+
143
+
144
+ def _close_pipes(proc: subprocess.Popen[Any]) -> None:
145
+ for stream in (proc.stdout, proc.stderr):
146
+ if stream is not None:
147
+ try:
148
+ stream.close()
149
+ except OSError:
150
+ pass
151
+
152
+
153
+ def _terminate_process_tree(proc: subprocess.Popen[Any]) -> None:
154
+ try:
155
+ os.killpg(proc.pid, signal.SIGKILL)
156
+ except ProcessLookupError:
157
+ pass
158
+ try:
159
+ proc.kill()
160
+ except ProcessLookupError:
161
+ pass
162
+
163
+
164
+ _PKILL_PATTERNS = (
165
+ f"{WORKSPACE}/eval/",
166
+ f"{WORKSPACE}/tests/",
167
+ "tail -f",
168
+ "development.log",
169
+ " less ",
170
+ " less$",
171
+ "/less ",
172
+ )
173
+
174
+
175
+ def _pkill_aggressive() -> str:
176
+ """Best-effort kill of branch pytest/subprocess trees (Modal gVisor fallback)."""
177
+ notes: list[str] = []
178
+ workspace = str(WORKSPACE)
179
+ patterns = list(_PKILL_PATTERNS) + [
180
+ f"pytest.*{workspace}",
181
+ f"xdist.*{workspace}",
182
+ ]
183
+ for pattern in patterns:
184
+ result = subprocess.run(
185
+ ["pkill", "-9", "-f", pattern],
186
+ capture_output=True,
187
+ text=True,
188
+ )
189
+ notes.append(f"pkill -9 -f {pattern!r}: rc={result.returncode}")
190
+ return "\n".join(notes)
191
+
192
+
193
+ def run_step(
194
+ command: str,
195
+ cwd: Path,
196
+ *,
197
+ timeout: int,
198
+ env: dict[str, str] | None = None,
199
+ step: str,
200
+ accept_failure: bool = False,
201
+ log_output: bool | None = None,
202
+ max_output_bytes: int = 65536,
203
+ ) -> dict[str, Any]:
204
+ if log_output is None:
205
+ log_output = step == "run_tests" or timeout >= 60
206
+
207
+ started = time.monotonic()
208
+ stdout_path: Path | None = None
209
+ stderr_path: Path | None = None
210
+ stdout_f = None
211
+ stderr_f = None
212
+
213
+ if log_output:
214
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
215
+ log_id = f"{step}-{int(started * 1000)}"
216
+ stdout_path = LOG_DIR / f"run-step-{log_id}.stdout.log"
217
+ stderr_path = LOG_DIR / f"run-step-{log_id}.stderr.log"
218
+ stdout_f = stdout_path.open("w", encoding="utf-8")
219
+ stderr_f = stderr_path.open("w", encoding="utf-8")
220
+ popen_stdout: Any = stdout_f
221
+ popen_stderr: Any = stderr_f
222
+ else:
223
+ popen_stdout = subprocess.PIPE
224
+ popen_stderr = subprocess.PIPE
225
+
226
+ proc = subprocess.Popen(
227
+ ["bash", "-lc", _bash_login_command(command)],
228
+ cwd=cwd,
229
+ env={**os.environ, **(env or {})},
230
+ stdout=popen_stdout,
231
+ stderr=popen_stderr,
232
+ start_new_session=True,
233
+ text=True,
234
+ )
235
+ timed_out = False
236
+ stdout = ""
237
+ stderr = ""
238
+ try:
239
+ if log_output:
240
+ proc.wait(timeout=timeout)
241
+ else:
242
+ stdout, stderr = proc.communicate(timeout=timeout)
243
+ except subprocess.TimeoutExpired:
244
+ timed_out = True
245
+ _terminate_process_tree(proc)
246
+ cleanup_lingering_processes(aggressive=True)
247
+ try:
248
+ proc.wait(timeout=5)
249
+ except subprocess.TimeoutExpired:
250
+ proc.kill()
251
+ if not log_output:
252
+ _close_pipes(proc)
253
+ finally:
254
+ if stdout_f is not None:
255
+ stdout_f.close()
256
+ if stderr_f is not None:
257
+ stderr_f.close()
258
+
259
+ if timed_out:
260
+ if log_output:
261
+ output = _read_log_tail(stdout_path, max_output_bytes) + _read_log_tail(
262
+ stderr_path, max_output_bytes
263
+ )
264
+ else:
265
+ output = ""
266
+ entry = {
267
+ "step": step,
268
+ "command": command,
269
+ "wall_time": time.monotonic() - started,
270
+ "output": output,
271
+ "returncode": 124,
272
+ "exception_info": f"timed out after {timeout}s",
273
+ }
274
+ else:
275
+ if log_output:
276
+ output = _read_log_tail(stdout_path, max_output_bytes) + _read_log_tail(
277
+ stderr_path, max_output_bytes
278
+ )
279
+ else:
280
+ output = stdout + stderr
281
+ entry = {
282
+ "step": step,
283
+ "command": command,
284
+ "wall_time": time.monotonic() - started,
285
+ "output": output,
286
+ "returncode": proc.returncode,
287
+ "exception_info": "",
288
+ }
289
+ if entry["returncode"] and not accept_failure:
290
+ raise RuntimeError(
291
+ f"{step} failed: {entry['exception_info'] or entry['output']}"
292
+ )
293
+ return entry
294
+
295
+
296
+ def cleanup_lingering_processes(*, aggressive: bool = False) -> dict[str, Any]:
297
+ started = time.monotonic()
298
+ patterns = [
299
+ str(WORKSPACE / "executable"),
300
+ f"{WORKSPACE}/eval/",
301
+ f"{WORKSPACE}/tests/",
302
+ # lazygit --logs/-l tests spawn `tail -f` outside /workspace/.
303
+ "tail -f",
304
+ "development.log",
305
+ ]
306
+ killed: list[int] = []
307
+ proc_root = Path("/proc")
308
+ proc_available = proc_root.exists()
309
+ if proc_available:
310
+ for proc_dir in proc_root.iterdir():
311
+ if not proc_dir.name.isdigit():
312
+ continue
313
+ pid = int(proc_dir.name)
314
+ if pid in {os.getpid(), os.getppid()}:
315
+ continue
316
+ try:
317
+ raw = (proc_dir / "cmdline").read_bytes()
318
+ except (FileNotFoundError, PermissionError, ProcessLookupError):
319
+ continue
320
+ cmdline = raw.replace(b"\0", b" ").decode(errors="replace")
321
+ if not any(pattern in cmdline for pattern in patterns):
322
+ continue
323
+ try:
324
+ os.kill(pid, signal.SIGKILL)
325
+ except (PermissionError, ProcessLookupError):
326
+ continue
327
+ killed.append(pid)
328
+ pkill_output = ""
329
+ if aggressive or not proc_available:
330
+ pkill_output = _pkill_aggressive()
331
+ output_parts = []
332
+ if killed:
333
+ output_parts.append("\n".join(str(pid) for pid in killed))
334
+ if pkill_output:
335
+ output_parts.append(pkill_output)
336
+ return {
337
+ "step": "cleanup_lingering_processes",
338
+ "command": "kill leftover branch processes referencing the workspace",
339
+ "wall_time": time.monotonic() - started,
340
+ "output": "\n".join(output_parts),
341
+ "returncode": 0,
342
+ "exception_info": "",
343
+ }
344
+
345
+
346
+ def extract_trusted_blob(tar_path: Path, dest: Path) -> None:
347
+ import tarfile
348
+
349
+ with tarfile.open(tar_path, "r:gz") as tf:
350
+ try:
351
+ tf.extractall(dest, filter="fully_trusted")
352
+ except TypeError:
353
+ tf.extractall(dest)
354
+
355
+
356
+ def find_results_xml() -> Path | None:
357
+ """Return the junit xml path if pytest wrote one."""
358
+ for candidate in (WORKSPACE / "eval" / "results.xml", WORKSPACE / "results.xml"):
359
+ if candidate.exists():
360
+ return candidate
361
+ return None
362
+
363
+
364
+ def remove_oracle_handoff_artifacts() -> list[str]:
365
+ """Drop oracle-agent handoff files from /workspace before snapshot/restore."""
366
+ removed: list[str] = []
367
+ for name in _ORACLE_HANDOFF_NAMES:
368
+ path = WORKSPACE / name
369
+ if path.exists():
370
+ if path.is_dir():
371
+ shutil.rmtree(path)
372
+ else:
373
+ path.unlink()
374
+ removed.append(name)
375
+ return removed
376
+
377
+
378
+ def _remove_tree(path: Path) -> None:
379
+ """Remove a file or directory tree, with a shell fallback for overlay races."""
380
+ if path.is_symlink() or path.is_file():
381
+ path.unlink(missing_ok=True)
382
+ return
383
+ if not path.is_dir():
384
+ path.unlink(missing_ok=True)
385
+ return
386
+ for attempt in range(3):
387
+ try:
388
+ shutil.rmtree(path)
389
+ if not path.exists():
390
+ return
391
+ except OSError:
392
+ if attempt == 2:
393
+ run_step(
394
+ f"rm -rf {shlex.quote(str(path))}",
395
+ path.parent,
396
+ timeout=120,
397
+ step="clear_workspace_fallback",
398
+ accept_failure=True,
399
+ )
400
+ if not path.exists():
401
+ return
402
+ raise
403
+
404
+
405
+ def ensure_workspace_dir() -> None:
406
+ """Guarantee WORKSPACE exists as a writable directory (not a symlink/file)."""
407
+ if WORKSPACE.exists() and not WORKSPACE.is_dir():
408
+ if WORKSPACE.is_symlink() or WORKSPACE.is_file():
409
+ WORKSPACE.unlink()
410
+ else:
411
+ shutil.rmtree(WORKSPACE)
412
+ WORKSPACE.mkdir(parents=True, exist_ok=True)
413
+
414
+
415
+ def clear_workspace() -> None:
416
+ ensure_workspace_dir()
417
+ for path in list(WORKSPACE.iterdir()):
418
+ _remove_tree(path)
419
+
420
+
421
+ def restore_reference_executable() -> None:
422
+ """Write the stashed reference binary into /workspace after a branch overlay.
423
+
424
+ Branch blobs may ship ``executable`` as a dangling symlink into
425
+ ``target/release/...``; ``shutil.copy2`` would follow it and raise
426
+ ``FileNotFoundError``. Drop whatever the blob left and copy the stashed
427
+ reference as a regular file.
428
+ """
429
+ ensure_workspace_dir()
430
+ if not STASHED_EXECUTABLE.is_file():
431
+ raise FileNotFoundError(
432
+ f"missing stashed reference executable at {STASHED_EXECUTABLE}"
433
+ )
434
+ dest = WORKSPACE / "executable"
435
+ if dest.exists() or dest.is_symlink():
436
+ if dest.is_dir():
437
+ shutil.rmtree(dest)
438
+ else:
439
+ dest.unlink(missing_ok=True)
440
+ shutil.copy2(STASHED_EXECUTABLE, dest)
441
+ dest.chmod(0o755)
442
+
443
+
444
+ def snapshot_workspace(dest: Path) -> None:
445
+ if dest.exists():
446
+ shutil.rmtree(dest)
447
+ shutil.copytree(WORKSPACE, dest, symlinks=True)
448
+
449
+
450
+ def restore_workspace(source: Path) -> None:
451
+ clear_workspace()
452
+ shutil.copytree(source, WORKSPACE, dirs_exist_ok=True, symlinks=True)
453
+ ensure_workspace_dir()
454
+
455
+
456
+ def remove_hashed_files(root: Path, hashes: set[str]) -> list[str]:
457
+ removed: list[str] = []
458
+ for path in root.rglob("*"):
459
+ if path.is_file() and not path.is_symlink():
460
+ try:
461
+ if sha256(path) in hashes:
462
+ path.unlink()
463
+ removed.append(str(path.relative_to(root)))
464
+ except OSError:
465
+ continue
466
+ return removed
467
+
468
+
469
+ def branch_tests(branch_info: dict[str, Any]) -> list[str]:
470
+ ignored = {
471
+ item["name"] for item in branch_info.get("ignored_tests", []) if "name" in item
472
+ }
473
+ return [name for name in branch_info.get("tests", []) if name not in ignored]
474
+
475
+
476
+ def ignored_tests(metadata: dict[str, Any]) -> set[str]:
477
+ result: set[str] = set()
478
+ for branch, info in metadata.get("branches", {}).items():
479
+ result.update(
480
+ f"{branch}/{item['name']}"
481
+ for item in info.get("ignored_tests", [])
482
+ if "name" in item
483
+ )
484
+ return result
485
+
486
+
487
+ def active_tests(metadata: dict[str, Any]) -> set[str]:
488
+ active: set[str] = set()
489
+ for branch, info in metadata.get("branches", {}).items():
490
+ if info.get("ignored"):
491
+ continue
492
+ ignored = {
493
+ item["name"] for item in info.get("ignored_tests", []) if "name" in item
494
+ }
495
+ active.update(
496
+ f"{branch}/{name}" for name in info.get("tests", []) if name not in ignored
497
+ )
498
+ return active
499
+
500
+
501
+ def inject_not_run(
502
+ result: dict[str, Any], branch: str, tests: list[str], error_code: str
503
+ ) -> None:
504
+ result["test_results"].extend(
505
+ {
506
+ "name": name,
507
+ "branch": branch,
508
+ "status": "not_run",
509
+ "extra": {"error_code": error_code},
510
+ }
511
+ for name in tests
512
+ )
513
+
514
+
515
+ def testcase_name(case: ET.Element) -> str:
516
+ classname = case.attrib.get("classname", "")
517
+ name = case.attrib.get("name", "")
518
+ return f"{classname}.{name}" if classname else name
519
+
520
+
521
+ # Only these tags under <testcase> represent a result. <system-out> /
522
+ # <system-err> are stdout/stderr captures and must not be treated as results
523
+ # (a leading <system-out> followed by <failure> would otherwise be classified
524
+ # as a stdout-only "passed").
525
+ JUNIT_RESULT_TAGS = {"skipped", "failure", "error"}
526
+
527
+
528
+ def parse_junit(
529
+ raw_xml: str, branch: str, expected: list[str], ignored: set[str]
530
+ ) -> tuple[list[dict[str, Any]], list[str]]:
531
+ root = ET.fromstring(raw_xml)
532
+ got: set[str] = set()
533
+ results: list[dict[str, Any]] = []
534
+ for case in root.iter("testcase"):
535
+ name = testcase_name(case)
536
+ got.add(name)
537
+ extra: dict[str, Any] = {}
538
+ if "time" in case.attrib:
539
+ try:
540
+ extra["time"] = float(case.attrib["time"])
541
+ except ValueError:
542
+ extra["time"] = case.attrib["time"]
543
+ result_children = [c for c in case if c.tag in JUNIT_RESULT_TAGS]
544
+ # Collapse duplicate same-tag result children. Pytest's
545
+ # "pytest.internal" pseudo-test sometimes emits two identical <error>
546
+ # entries; treating that as a system_error would over-flag a real
547
+ # single failure. Mirrors upstream eval.py:816-820.
548
+ if len(result_children) > 1 and len({c.tag for c in result_children}) == 1:
549
+ result_children = [result_children[0]]
550
+ if not result_children:
551
+ status = "passed"
552
+ elif len(result_children) != 1:
553
+ status = "system_error"
554
+ extra["error_details"] = (
555
+ f"Expected 1 result for {name}, got {len(result_children)}: "
556
+ f"{[c.tag for c in result_children]}"
557
+ )
558
+ else:
559
+ first = result_children[0]
560
+ status = first.tag # "skipped" | "failure" | "error"
561
+ extra["message"] = first.attrib.get("message") or ""
562
+ if first.text:
563
+ extra["text"] = first.text
564
+ results.append(
565
+ {"name": name, "branch": branch, "status": status, "extra": extra}
566
+ )
567
+
568
+ active_expected = [name for name in expected if name not in ignored]
569
+ missing = [name for name in active_expected if name not in got]
570
+ results.extend(
571
+ {
572
+ "name": name,
573
+ "branch": branch,
574
+ "status": "not_run",
575
+ "extra": {"error_code": "missing_from_junit_xml"},
576
+ }
577
+ for name in missing
578
+ )
579
+ unexpected = got - set(expected) - ignored
580
+ warnings = (
581
+ [f"Branch {branch}: {len(unexpected)} test(s) in JUnit XML not in tests.json"]
582
+ if unexpected
583
+ else []
584
+ )
585
+ return results, warnings
586
+
587
+
588
+ def count_worker_crashes(raw_xml: str) -> int:
589
+ if WORKER_CRASH_PHRASE not in raw_xml:
590
+ return 0
591
+ try:
592
+ root = ET.fromstring(raw_xml)
593
+ except ET.ParseError:
594
+ return 0
595
+ crashes = 0
596
+ for case in root.iter("testcase"):
597
+ for child in case:
598
+ text = (child.get("message") or "") + " " + (child.text or "")
599
+ if (
600
+ child.tag in {"error", "failure"}
601
+ and WORKER_CRASH_PHRASE in text
602
+ and "crashed" in text
603
+ ):
604
+ crashes += 1
605
+ break
606
+ return crashes
607
+
608
+
609
+ def run_output_indicates_xdist_collapse(output: str) -> bool:
610
+ lower = output.lower()
611
+ return any(marker in lower for marker in XDIST_COLLAPSE_MARKERS)
612
+
613
+
614
+ def count_junit_failures(raw_xml: str) -> int:
615
+ try:
616
+ root = ET.fromstring(raw_xml)
617
+ except ET.ParseError:
618
+ return 0
619
+ failures = 0
620
+ for case in root.iter("testcase"):
621
+ for child in case:
622
+ if child.tag in {"failure", "error"}:
623
+ failures += 1
624
+ break
625
+ return failures
626
+
627
+
628
+ def count_junit_passed(raw_xml: str) -> int:
629
+ try:
630
+ root = ET.fromstring(raw_xml)
631
+ except ET.ParseError:
632
+ return 0
633
+ passed = 0
634
+ for case in root.iter("testcase"):
635
+ if not any(child.tag in JUNIT_RESULT_TAGS for child in case):
636
+ passed += 1
637
+ return passed
638
+
639
+
640
+ def branch_attempt_metrics(
641
+ raw_xml: str, *, run_output: str, expected_tests: int
642
+ ) -> tuple[int, int, int, int]:
643
+ """Return (crashes, n_testcases, failures, missing_from_xml)."""
644
+ crashes = count_worker_crashes(raw_xml)
645
+ if run_output_indicates_xdist_collapse(run_output):
646
+ crashes = max(crashes, 1)
647
+ n_tests = count_testcases(raw_xml)
648
+ failures = count_junit_failures(raw_xml)
649
+ missing = max(0, expected_tests - n_tests)
650
+ return crashes, n_tests, failures, missing
651
+
652
+
653
+ def needs_serial_retry(
654
+ *,
655
+ serial: bool,
656
+ crashes: int,
657
+ missing: int,
658
+ failures: int,
659
+ n_tests: int,
660
+ expected_tests: int,
661
+ run_output: str,
662
+ ) -> bool:
663
+ if serial:
664
+ return False
665
+ high_failure_rate = (
666
+ expected_tests > 0 and n_tests >= expected_tests and failures / n_tests >= 0.8
667
+ )
668
+ return (
669
+ crashes > 0
670
+ or missing > 0
671
+ or high_failure_rate
672
+ or run_output_indicates_xdist_collapse(run_output)
673
+ )
674
+
675
+
676
+ def count_testcases(raw_xml: str) -> int:
677
+ try:
678
+ return sum(1 for _ in ET.fromstring(raw_xml).iter("testcase"))
679
+ except ET.ParseError:
680
+ return 0
681
+
682
+
683
+ def scored_results(
684
+ result: dict[str, Any], metadata: dict[str, Any]
685
+ ) -> list[dict[str, Any]]:
686
+ active = active_tests(metadata)
687
+ by_key = {
688
+ f"{test['branch']}/{test['name']}": test
689
+ for test in result["test_results"]
690
+ if f"{test['branch']}/{test['name']}" in active
691
+ }
692
+ return [
693
+ by_key.get(
694
+ key,
695
+ {
696
+ "branch": key.split("/", 1)[0],
697
+ "name": key.split("/", 1)[1],
698
+ "status": "not_run",
699
+ "extra": {"error_code": "missing_from_results"},
700
+ },
701
+ )
702
+ for key in sorted(active)
703
+ ]
704
+
705
+
706
+ def summarize(result: dict[str, Any], metadata: dict[str, Any]) -> dict[str, Any]:
707
+ scored = scored_results(result, metadata)
708
+ n_passed = sum(t["status"] == "passed" for t in scored)
709
+ n_tests = len(scored)
710
+ pass_rate = n_passed / n_tests if n_tests else 0.0
711
+ # Multi-key reward: Harbor's default Mean aggregates each key independently
712
+ # (see harbor.metrics.base.aggregate_reward_dicts), so mean("resolved") is
713
+ # the proportion of tasks scoring a perfect pass-rate and mean of
714
+ # "almost_resolved" is the proportion scoring >= 0.95. "reward" stays the
715
+ # per-task pass-rate whose mean is the overall mean reward.
716
+ return {
717
+ "reward": pass_rate,
718
+ "resolved": 1.0 if pass_rate >= 1.0 else 0.0,
719
+ "almost_resolved": 1.0 if pass_rate >= 0.95 else 0.0,
720
+ }
721
+
722
+
723
+ def diagnostics(result: dict[str, Any], metadata: dict[str, Any]) -> dict[str, Any]:
724
+ scored = scored_results(result, metadata)
725
+ n_passed = sum(t["status"] == "passed" for t in scored)
726
+ n_tests = len(scored)
727
+ pass_rate = n_passed / n_tests if n_tests else 0.0
728
+ return {
729
+ "pass_rate": pass_rate,
730
+ "resolved": int(
731
+ bool(
732
+ n_tests
733
+ and n_passed == n_tests
734
+ and not result["test_branch_errors"]
735
+ and not result["error_code"]
736
+ )
737
+ ),
738
+ "n_passed": n_passed,
739
+ "n_tests": n_tests,
740
+ "n_branch_errors": len(result["test_branch_errors"]),
741
+ "infra_error": int(bool(result["error_code"] or result["test_branch_errors"])),
742
+ "executable_hash_present": int(bool(result.get("executable_hash"))),
743
+ }
744
+
745
+
746
+ def use_script_pty() -> bool:
747
+ return os.environ.get("PROGRAMGYM_SCRIPT_PTY", "").strip() == "1"
748
+
749
+
750
+ def script_pty_available() -> bool:
751
+ return shutil.which("script") is not None
752
+
753
+
754
+ def branch_env(
755
+ *,
756
+ serial: bool,
757
+ has_rerunfailures: bool,
758
+ extras: dict[str, str] | None = None,
759
+ ) -> dict[str, str]:
760
+ addopts = ["--max-worker-restart=4"]
761
+ # A serial fallback is already a complete second execution. Re-running each
762
+ # failing test two more times makes large, failure-heavy suites prohibitively
763
+ # slow and adds little signal.
764
+ if has_rerunfailures and not serial:
765
+ addopts.extend(["--reruns=2", "--reruns-delay=1"])
766
+ env = {
767
+ "PYTEST_ADDOPTS": " ".join(addopts),
768
+ # Match upstream non-TTY regression environments (dirble log format, etc.).
769
+ "NO_COLOR": "1",
770
+ "TERM": "dumb",
771
+ "CLICOLOR": "0",
772
+ "CLICOLOR_FORCE": "0",
773
+ "COLORTERM": "",
774
+ }
775
+ if extras:
776
+ env.update(extras)
777
+ xdist_workers = os.environ.get("PROGRAMGYM_XDIST_WORKERS")
778
+ if serial:
779
+ xdist_workers = "1"
780
+ if xdist_workers:
781
+ env["PYTEST_XDIST_AUTO_NUM_WORKERS"] = xdist_workers
782
+ return env
783
+
784
+
785
+ _SERIAL_RUN_SH = ".programgym_run_serial.sh"
786
+ # ``eval/run.sh`` usually passes ``-n auto`` on the command line, which overrides
787
+ # ``PYTEST_ADDOPTS``. Rewrite to ``-n 0`` in a verifier-local copy for retries.
788
+ _RUN_SH_XDIST_RE = re.compile(r"-n\s*(?:auto|\d+)")
789
+
790
+
791
+ def prepare_serial_run_sh(run_sh: Path) -> Path:
792
+ """Write a serial-only copy of ``eval/run.sh`` with xdist disabled."""
793
+ serial_sh = run_sh.with_name(_SERIAL_RUN_SH)
794
+ patched = _RUN_SH_XDIST_RE.sub("-n 0", run_sh.read_text())
795
+ serial_sh.write_text(patched)
796
+ serial_sh.chmod(0o755)
797
+ return serial_sh
798
+
799
+
800
+ def run_tests_command(*, serial: bool) -> str:
801
+ if serial:
802
+ inner = f"chmod +x ./eval/{_SERIAL_RUN_SH} && ./eval/{_SERIAL_RUN_SH}"
803
+ else:
804
+ inner = "chmod +x ./eval/run.sh && ./eval/run.sh"
805
+ if use_script_pty() and script_pty_available():
806
+ return f"script -q -c {shlex.quote(inner)} /dev/null"
807
+ return inner
808
+
809
+
810
+ BAKED_BLOB_DIR = Path(os.environ.get("PROGRAMGYM_BAKED_BLOB_DIR", "/tests/blobs"))
811
+
812
+
813
+ def resolve_blob_dir(instance_id: str, metadata: dict[str, Any]) -> Path:
814
+ """Locate the per-instance blob directory.
815
+
816
+ Resolution order:
817
+
818
+ 1. ``/tests/blobs/`` if pre-fetched into the task at generation time
819
+ (``programgym-adapter --download-blobs``). Verifier-only mount, so
820
+ agent never sees these.
821
+ 2. ``PROGRAMGYM_BLOB_DIR`` env override pointing at an HF-cache-shaped
822
+ tree on disk (``<dir>/<instance_id>/tests/<branch>.tar.gz``). Useful
823
+ for offline reruns sharing a cache across many tasks.
824
+ 3. ``huggingface_hub.snapshot_download`` from
825
+ ``programgym/ProgramGym-Tests`` (default repo, ``main`` revision).
826
+
827
+ The returned directory contains ``tests/<branch>.tar.gz`` per active
828
+ branch — same shape as ``programgym/ProgramGym-Tests/<instance_id>/``
829
+ on HF.
830
+ """
831
+ if BAKED_BLOB_DIR.exists() and (BAKED_BLOB_DIR / "tests").exists():
832
+ return BAKED_BLOB_DIR
833
+
834
+ local = os.environ.get("PROGRAMGYM_BLOB_DIR", "").strip()
835
+ if local:
836
+ candidate = Path(local) / instance_id
837
+ if candidate.exists():
838
+ return candidate
839
+ raise FileNotFoundError(
840
+ f"PROGRAMGYM_BLOB_DIR set but {candidate} does not exist"
841
+ )
842
+
843
+ repo_id = os.environ.get("PROGRAMGYM_HF_REPO") or metadata.get(
844
+ "hf_repo_id", DEFAULT_HF_REPO_ID
845
+ )
846
+ revision = os.environ.get("PROGRAMGYM_HF_REVISION") or metadata.get(
847
+ "hf_revision", DEFAULT_HF_REVISION
848
+ )
849
+
850
+ from huggingface_hub import snapshot_download
851
+
852
+ cache_root = Path(
853
+ snapshot_download(
854
+ repo_id,
855
+ repo_type="dataset",
856
+ revision=revision,
857
+ allow_patterns=f"{instance_id}/**",
858
+ )
859
+ )
860
+ blob_dir = cache_root / instance_id
861
+ if not blob_dir.exists():
862
+ raise FileNotFoundError(
863
+ f"HF blob directory missing for {instance_id} at {blob_dir}"
864
+ )
865
+ return blob_dir
866
+
867
+
868
+ def evaluate(metadata: dict[str, Any]) -> dict[str, Any]:
869
+ bootstrap_toolchain_path()
870
+ branches = metadata.get("branches", {})
871
+ active_branch_items = [
872
+ (name, info) for name, info in branches.items() if not info.get("ignored")
873
+ ]
874
+ result: dict[str, Any] = {
875
+ "test_results": [],
876
+ "error_code": None,
877
+ "error_details": None,
878
+ "log": [],
879
+ "solution_branch": "submission",
880
+ "test_branches": [name for name, _ in active_branch_items],
881
+ "test_branch_errors": {},
882
+ "executable_hash": None,
883
+ "warnings": [],
884
+ }
885
+
886
+ instance_id = metadata["instance_id"]
887
+
888
+ compile_timeout = int(os.environ.get("PROGRAMGYM_COMPILE_TIMEOUT", "900"))
889
+ branch_timeout = int(os.environ.get("PROGRAMGYM_BRANCH_TIMEOUT", "3600"))
890
+
891
+ def fail_all(error_code: str, details: str) -> dict[str, Any]:
892
+ result["error_code"] = error_code
893
+ result["error_details"] = details
894
+ for branch, info in active_branch_items:
895
+ inject_not_run(result, branch, branch_tests(info), error_code)
896
+ return result
897
+
898
+ with tempfile.TemporaryDirectory(prefix="programgym-eval-") as tmp:
899
+ compiled_snapshot = Path(tmp) / "compiled"
900
+
901
+ started = time.monotonic()
902
+ removed = remove_hashed_files(
903
+ WORKSPACE, set(metadata.get("eval_clean_hashes", []))
904
+ )
905
+ result["log"].append(
906
+ {
907
+ "step": "remove_hashed_files",
908
+ "command": "remove files matching eval_clean_hashes",
909
+ "wall_time": time.monotonic() - started,
910
+ "output": "".join(f"removed '{path}'\n" for path in removed),
911
+ "returncode": 0,
912
+ "exception_info": "",
913
+ }
914
+ )
915
+
916
+ compile_sh = WORKSPACE / "compile.sh"
917
+ if not compile_sh.exists():
918
+ return fail_all(
919
+ "missing_compile_sh", "submission did not contain compile.sh"
920
+ )
921
+
922
+ seed = (
923
+ "if [ ! -d .git ]; then "
924
+ "GIT_AUTHOR_DATE='2000-01-01T00:00:00Z' "
925
+ "GIT_COMMITTER_DATE='2000-01-01T00:00:00Z' "
926
+ "git -c init.defaultBranch=gold init -q && "
927
+ "git -c user.email=gold@local -c user.name=gold -c commit.gpgsign=false add -A && "
928
+ "GIT_AUTHOR_DATE='2000-01-01T00:00:00Z' "
929
+ "GIT_COMMITTER_DATE='2000-01-01T00:00:00Z' "
930
+ "git -c user.email=gold@local -c user.name=gold -c commit.gpgsign=false commit -q --allow-empty -m gold; "
931
+ "fi"
932
+ )
933
+ try:
934
+ result["log"].append(
935
+ run_step(seed, WORKSPACE, timeout=300, step="seed_git")
936
+ )
937
+ compile_log = run_step(
938
+ "chmod +x ./compile.sh && ./compile.sh",
939
+ WORKSPACE,
940
+ timeout=compile_timeout,
941
+ step="compile",
942
+ accept_failure=True,
943
+ )
944
+ result["log"].append(compile_log)
945
+ if compile_log["returncode"]:
946
+ return fail_all("compile_failed", compile_log["output"])
947
+ executable = WORKSPACE / "executable"
948
+ if not executable.exists():
949
+ return fail_all(
950
+ "missing_executable",
951
+ "compile.sh completed but did not create ./executable",
952
+ )
953
+ STASHED_EXECUTABLE.parent.mkdir(parents=True, exist_ok=True)
954
+ # `move` (not copy) so /workspace doesn't keep a parallel copy of
955
+ # the agent's executable during the stash→restore window. Mirrors
956
+ # upstream `mv ./executable {STASHED}` (eval.py:472).
957
+ shutil.move(str(executable), STASHED_EXECUTABLE)
958
+ result["executable_hash"] = sha256(STASHED_EXECUTABLE)
959
+ result["log"].append(
960
+ run_step(
961
+ "pip3 install -q --disable-pip-version-check pytest-rerunfailures",
962
+ WORKSPACE,
963
+ timeout=120,
964
+ step="install_rerunfailures",
965
+ accept_failure=True,
966
+ )
967
+ )
968
+ has_rerunfailures = result["log"][-1]["returncode"] == 0
969
+ handoff_removed = remove_oracle_handoff_artifacts()
970
+ if handoff_removed:
971
+ result["log"].append(
972
+ {
973
+ "step": "remove_oracle_handoff",
974
+ "command": "remove oracle handoff artifacts from workspace",
975
+ "wall_time": 0.0,
976
+ "output": "".join(
977
+ f"removed '{name}'\n" for name in handoff_removed
978
+ ),
979
+ "returncode": 0,
980
+ "exception_info": "",
981
+ }
982
+ )
983
+ snapshot_workspace(compiled_snapshot)
984
+ except Exception as exc:
985
+ return fail_all(type(exc).__name__, str(exc))
986
+
987
+ try:
988
+ blob_dir = resolve_blob_dir(instance_id, metadata)
989
+ except Exception as exc:
990
+ details = f"{type(exc).__name__}: {exc}"
991
+ for branch, info in active_branch_items:
992
+ result["test_branch_errors"][branch] = [
993
+ {
994
+ "error_code": "blob_resolution_failed",
995
+ "error_details": details,
996
+ }
997
+ ]
998
+ inject_not_run(
999
+ result, branch, branch_tests(info), "blob_resolution_failed"
1000
+ )
1001
+ return result
1002
+
1003
+ for branch, info in active_branch_items:
1004
+ tests = branch_tests(info)
1005
+ blob = blob_dir / "tests" / f"{branch}.tar.gz"
1006
+ if not blob.exists():
1007
+ result["test_branch_errors"][branch] = [
1008
+ {"error_code": "missing_test_blob", "error_details": blob.name}
1009
+ ]
1010
+ inject_not_run(result, branch, tests, "missing_test_blob")
1011
+ continue
1012
+
1013
+ best_xml = ""
1014
+ # Prefer a complete, clean XML result, then the result covering the
1015
+ # most expected tests, and only then the one with the most passes.
1016
+ # Pass-count-only ranking can retain a partial xdist result over a
1017
+ # complete serial result.
1018
+ best_quality = (-1, -1, -1)
1019
+ serial = bool(metadata.get("force_serial_branches"))
1020
+ branch_log: list[dict[str, Any]] = []
1021
+ branch_ignored = {
1022
+ item["name"] for item in info.get("ignored_tests", []) if "name" in item
1023
+ }
1024
+ n_expected = len([name for name in tests if name not in branch_ignored])
1025
+
1026
+ def merge_best_xml(raw_xml: str) -> None:
1027
+ try:
1028
+ parsed, warnings = parse_junit(
1029
+ raw_xml, branch, list(info.get("tests", [])), branch_ignored
1030
+ )
1031
+ except Exception as exc:
1032
+ result["test_branch_errors"][branch] = [
1033
+ {"error_code": "xml_parse_error", "error_details": str(exc)}
1034
+ ]
1035
+ inject_not_run(result, branch, tests, "xml_parse_error")
1036
+ else:
1037
+ result["test_results"].extend(parsed)
1038
+ result["warnings"].extend(warnings)
1039
+
1040
+ while True:
1041
+ branch_log.append(cleanup_lingering_processes())
1042
+ restore_workspace(compiled_snapshot)
1043
+ extract_trusted_blob(blob, WORKSPACE)
1044
+ restore_reference_executable()
1045
+ actual_hash = sha256(WORKSPACE / "executable")
1046
+ if actual_hash != result["executable_hash"]:
1047
+ result["test_branch_errors"][branch] = [
1048
+ {
1049
+ "error_code": "executable_hash_mismatch",
1050
+ "error_details": (
1051
+ f"expected {result['executable_hash']}, got {actual_hash}"
1052
+ ),
1053
+ }
1054
+ ]
1055
+ inject_not_run(result, branch, tests, "executable_hash_mismatch")
1056
+ break
1057
+ run_sh = WORKSPACE / "eval" / "run.sh"
1058
+ if not run_sh.exists():
1059
+ result["test_branch_errors"][branch] = [
1060
+ {
1061
+ "error_code": "missing_run_sh",
1062
+ "error_details": "eval/run.sh missing",
1063
+ }
1064
+ ]
1065
+ inject_not_run(result, branch, tests, "missing_run_sh")
1066
+ break
1067
+ # Upstream rewrites thread→signal so xdist workers fail cleanly
1068
+ # instead of os._exit(1) on timeout. That works in fresh
1069
+ # containers per branch; here we reuse one container and
1070
+ # signal timeouts leave TUI/log-watcher subprocesses alive
1071
+ # (e.g. lazygit --logs + tail -f), wedging pytest for up to
1072
+ # branch_timeout. Keep the blob's thread method and rely on
1073
+ # cleanup_lingering_processes + serial fallback after crashes.
1074
+ env = branch_env(
1075
+ serial=serial,
1076
+ has_rerunfailures=has_rerunfailures,
1077
+ extras=metadata.get("branch_env"),
1078
+ )
1079
+ branch_log.append(
1080
+ run_step(
1081
+ "rm -f eval/results.xml results.xml",
1082
+ WORKSPACE,
1083
+ timeout=120,
1084
+ step="clean_stale_results",
1085
+ accept_failure=True,
1086
+ )
1087
+ )
1088
+ if serial:
1089
+ prepare_serial_run_sh(run_sh)
1090
+ run_entry = run_step(
1091
+ run_tests_command(serial=serial),
1092
+ WORKSPACE,
1093
+ timeout=branch_timeout,
1094
+ env=env,
1095
+ step="run_tests",
1096
+ accept_failure=True,
1097
+ )
1098
+ branch_log.append(run_entry)
1099
+ branch_log.append(cleanup_lingering_processes())
1100
+ xml_path = find_results_xml()
1101
+ if xml_path is None:
1102
+ if best_xml:
1103
+ merge_best_xml(best_xml)
1104
+ break
1105
+ if serial:
1106
+ result["test_branch_errors"][branch] = [
1107
+ {
1108
+ "error_code": "missing_results_xml",
1109
+ "error_details": "eval/results.xml was not produced",
1110
+ }
1111
+ ]
1112
+ inject_not_run(result, branch, tests, "missing_results_xml")
1113
+ break
1114
+ serial = True
1115
+ continue
1116
+ raw_xml = xml_path.read_text(errors="replace")
1117
+ crashes, n_tests, failures, missing = branch_attempt_metrics(
1118
+ raw_xml,
1119
+ run_output=run_entry.get("output", ""),
1120
+ expected_tests=n_expected,
1121
+ )
1122
+ useful = count_junit_passed(raw_xml)
1123
+ quality = (
1124
+ int(crashes == 0 and missing == 0),
1125
+ n_tests,
1126
+ useful,
1127
+ )
1128
+ if quality > best_quality:
1129
+ best_xml = raw_xml
1130
+ best_quality = quality
1131
+ retry = needs_serial_retry(
1132
+ serial=serial,
1133
+ crashes=crashes,
1134
+ missing=missing,
1135
+ failures=failures,
1136
+ n_tests=n_tests,
1137
+ expected_tests=n_expected,
1138
+ run_output=run_entry.get("output", ""),
1139
+ )
1140
+ if not retry:
1141
+ merge_best_xml(best_xml)
1142
+ break
1143
+ serial = True
1144
+ for entry in branch_log:
1145
+ entry["branch"] = branch
1146
+ result["log"].extend(branch_log)
1147
+
1148
+ return result
1149
+
1150
+
1151
+ def write_outputs(result: dict[str, Any], metadata: dict[str, Any]) -> None:
1152
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
1153
+ write_json(LOG_DIR / "programgym_eval.json", result)
1154
+ write_json(LOG_DIR / "harbor_diagnostics.json", diagnostics(result, metadata))
1155
+ rewards = summarize(result, metadata)
1156
+ write_json(LOG_DIR / "reward.json", rewards)
1157
+ (LOG_DIR / "reward.txt").write_text(str(rewards["reward"]))
1158
+
1159
+
1160
+ def main() -> None:
1161
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
1162
+ log_path = LOG_DIR / "programgym_eval.log"
1163
+ metadata = json.loads(METADATA_PATH.read_text())
1164
+ branches = metadata.get("branches", {})
1165
+ try:
1166
+ result = evaluate(metadata)
1167
+ except Exception as exc:
1168
+ error_code = type(exc).__name__
1169
+ result = {
1170
+ "test_results": [],
1171
+ "error_code": error_code,
1172
+ "error_details": str(exc),
1173
+ "log": [
1174
+ {
1175
+ "step": "evaluator_exception",
1176
+ "exception_info": traceback.format_exc(),
1177
+ "returncode": 1,
1178
+ }
1179
+ ],
1180
+ "solution_branch": "submission",
1181
+ "test_branches": [
1182
+ name for name, info in branches.items() if not info.get("ignored")
1183
+ ],
1184
+ "test_branch_errors": {
1185
+ "__evaluator__": [{"error_code": error_code, "error_details": str(exc)}]
1186
+ },
1187
+ "executable_hash": None,
1188
+ "warnings": [],
1189
+ }
1190
+ for branch, info in branches.items():
1191
+ if info.get("ignored"):
1192
+ continue
1193
+ inject_not_run(result, branch, branch_tests(info), error_code)
1194
+ log_path.write_text(traceback.format_exc())
1195
+ else:
1196
+ log_path.write_text("")
1197
+ write_outputs(result, metadata)
1198
+
1199
+
1200
+ if __name__ == "__main__":
1201
+ main()
mpc-sok--frameworks.2af8f22/tests/programgym_task.json ADDED
The diff for this file is too large to render. See raw diff
 
mpc-sok--frameworks.2af8f22/tests/test.sh ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ # Verifier exec may not inherit image ENV (Modal/gVisor, login-shell resets).
5
+ export PATH="/usr/local/go/bin:/go/bin:/usr/local/cargo/bin:/root/.cargo/bin:${PATH}"
6
+
7
+ mkdir -p /logs/verifier /logs/artifacts
8
+
9
+ write_failure() {
10
+ local code="$1"
11
+ local details="$2"
12
+ python3 - "$code" "$details" <<'PY'
13
+ import json
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ code, details = sys.argv[1:3]
18
+ try:
19
+ metadata = json.loads(Path("/tests/programgym_task.json").read_text())
20
+ n_tests = sum(
21
+ len([
22
+ name for name in info.get("tests", [])
23
+ if name not in {item.get("name") for item in info.get("ignored_tests", [])}
24
+ ])
25
+ for branch, info in metadata.get("branches", {}).items()
26
+ if not info.get("ignored")
27
+ )
28
+ except Exception:
29
+ n_tests = 0
30
+ result = {
31
+ "test_results": [],
32
+ "error_code": code,
33
+ "error_details": details,
34
+ "log": [],
35
+ "solution_branch": "submission",
36
+ "test_branches": [],
37
+ "test_branch_errors": {
38
+ "__infra__": [{"error_code": code, "error_details": details}]
39
+ },
40
+ "executable_hash": None,
41
+ "warnings": [],
42
+ }
43
+ diagnostics = {
44
+ "pass_rate": 0.0,
45
+ "resolved": 0,
46
+ "n_passed": 0,
47
+ "n_tests": n_tests,
48
+ "n_branch_errors": 1,
49
+ "infra_error": 1,
50
+ "executable_hash_present": 0,
51
+ }
52
+ Path("/logs/verifier/programgym_eval.json").write_text(
53
+ json.dumps(result, indent=2, sort_keys=True)
54
+ )
55
+ Path("/logs/verifier/harbor_diagnostics.json").write_text(
56
+ json.dumps(diagnostics, indent=2, sort_keys=True)
57
+ )
58
+ Path("/logs/verifier/reward.json").write_text(
59
+ json.dumps(
60
+ {"reward": 0.0, "resolved": 0.0, "almost_resolved": 0.0},
61
+ indent=2,
62
+ sort_keys=True,
63
+ )
64
+ )
65
+ Path("/logs/verifier/reward.txt").write_text("0.0")
66
+ Path("/logs/verifier/programgym_eval.log").write_text(details)
67
+ PY
68
+ }
69
+
70
+ if ! command -v python3 >/dev/null 2>&1; then
71
+ write_failure "missing_python3" "python3 is required in the cleanroom image"
72
+ exit 0
73
+ fi
74
+
75
+ if ! python3 /tests/programgym_evaluator.py; then
76
+ if [ ! -s /logs/verifier/reward.txt ]; then
77
+ write_failure "evaluator_crashed" \
78
+ "programgym_evaluator.py exited non-zero with no reward written"
79
+ fi
80
+ fi
81
+
82
+ exit 0
mpc-sok--frameworks.2af8f22/tests/workspace.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:36fe9644924b0d7e4c776462b192290955c2c449d2401d3ba1bc739f625d0920
3
+ size 2218
mpolden--echoip.746db5e/environment/Dockerfile ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive
3
+ ENV RUSTUP_DIST_SERVER="https://static.rust-lang.org"
4
+ ENV RUSTUP_UPDATE_ROOT="https://static.rust-lang.org/rustup"
5
+ ENV CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse
6
+ ENV CARGO_REGISTRIES_CRATES_IO_INDEX="sparse+https://index.crates.io/"
7
+ ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
8
+ ENV GOPROXY="https://proxy.golang.org,direct"
9
+ ENV GOSUMDB=sum.golang.google.cn
10
+ ENV GOTOOLCHAIN=auto
11
+ ENV UV_INSECURE_HOST=""
12
+ ENV UV_INDEX_URL="https://pypi.org/simple"
13
+ ENV UV_EXTRA_INDEX_URL=https://pypi.org/simple
14
+ ENV UV_CACHE_DIR=/workspace/.cache/uv
15
+ ENV npm_config_registry="https://registry.npmjs.org/"
16
+ ENV npm_config_strict_ssl=false
17
+ ENV npm_config_cache=/workspace/.cache/npm
18
+ ENV PIP_INDEX_URL="https://pypi.org/simple"
19
+ ENV PIP_EXTRA_INDEX_URL=https://pypi.org/simple
20
+ ENV PIP_TRUSTED_HOST=""
21
+ ENV HOME=/workspace
22
+ ENV XDG_CACHE_HOME=/workspace/.cache
23
+ ENV PIP_CACHE_DIR=/workspace/.cache/pip
24
+ ENV PYTHONUSERBASE=/workspace/.local
25
+ ENV GOROOT=/usr/local/go
26
+ ENV GOPATH=/workspace/.go
27
+ ENV GOCACHE=/workspace/.cache/go-build
28
+ ENV PIP_BREAK_SYSTEM_PACKAGES=1
29
+ ENV PATH=/opt/programgym-venv/bin:/usr/local/go/bin:/workspace/.go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
30
+ ENV PAGER=cat
31
+ ENV MANPAGER=cat
32
+ ENV LESS=-R
33
+ ENV TQDM_DISABLE=1
34
+ ENV VIRTUAL_ENV=/opt/programgym-venv
35
+ RUN apt-get update && apt-get install -y --no-install-recommends bash build-essential ca-certificates git make pkg-config python3 python3-pip curl wget xz-utils unzip zip bzip2 zstd patch file binutils python3-venv tar && rm -rf /var/lib/apt/lists/*
36
+ COPY programgym-go.tar.gz /tmp/programgym-go.tar.gz
37
+ RUN set -eux; rm -rf /usr/local/go; tar -C /usr/local -xzf /tmp/programgym-go.tar.gz; rm -f /tmp/programgym-go.tar.gz; if [ ! -x /usr/local/go/bin/go ]; then echo "official Go tarball did not create /usr/local/go/bin/go" >&2; exit 1; fi; /usr/local/go/bin/go version
38
+ RUN python3 -m venv /opt/programgym-venv && /opt/programgym-venv/bin/python -m pip install --no-cache-dir --only-binary=:all: pytest pytest-xdist coverage
39
+ WORKDIR /workspace
40
+ ADD workspace.tar.gz /workspace/
41
+ COPY executable /workspace/executable
42
+ COPY download.sh /workspace/download.sh
43
+ RUN chmod 755 /workspace/download.sh
44
+ RUN ["bash","-lc","set -euo pipefail; cd /workspace; set -a; source /workspace/download.sh; set +a; python3 - <<'PY' > /etc/profile.d/programgym_download_env.sh\nimport os\nimport re\nimport shlex\nignored = {\"OLDPWD\", \"PWD\", \"SHLVL\", \"_\"}\nvalid_name = re.compile(r\"^[A-Za-z_][A-Za-z0-9_]*$\")\nfor key in sorted(os.environ):\n if key in ignored or key.startswith(\"BASH_FUNC_\") or not valid_name.fullmatch(key):\n continue\n value = os.environ[key]\n if \"\\n\" in value:\n continue\n print(f\"export {key}={shlex.quote(value)}\")\nPY\n"]
45
+ ENV BASH_ENV=/etc/profile.d/programgym_download_env.sh
46
+ RUN chmod 111 /workspace/executable
47
+ WORKDIR /workspace
48
+ # programgym-runtime-workspace-cleanup: v1
49
+ RUN ["bash","-lc","rm -f -- /workspace/download.sh /workspace/reference/build.sh && rm -rf -- /workspace/.programgym_build_env"]
50
+ # Harbor synthetic ProgramGym adapter: run the agent as an unprivileged user.
51
+ # Keep tool/runtime state under /home/agent and reserve /workspace for the
52
+ # submission handed to the separate verifier. Keep the reference executable
53
+ # execute-only; the oracle temporarily restores owner read permission.
54
+ RUN id -u agent >/dev/null 2>&1 || useradd -m -s /bin/bash agent
55
+ RUN mkdir -p /home/agent \
56
+ && chown -R agent:agent /home/agent /workspace \
57
+ && chown agent:agent /workspace/executable \
58
+ && chmod 111 /workspace/executable
59
+ ENV HOME=/home/agent
60
+ WORKDIR /workspace
mpolden--echoip.746db5e/environment/download.sh ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # PROGRAMGYM-MANAGED-GO-DOWNLOAD: v1
3
+ # Generated deterministically from repository module metadata; do not edit.
4
+ set -u
5
+ export GOTOOLCHAIN=auto
6
+ mkdir -p /workspace/.programgym_build_env/go-prefetch
7
+ cat > /workspace/.programgym_build_env/go-prefetch/go.mod <<'PROGRAMGYM_GO_MOD_EOF'
8
+ module github.com/mpolden/echoip
9
+
10
+ go 1.24
11
+
12
+ require github.com/oschwald/geoip2-golang v1.13.0
13
+
14
+ require (
15
+ github.com/oschwald/maxminddb-golang v1.13.0 // indirect
16
+ golang.org/x/sys v0.20.0 // indirect
17
+ )
18
+ PROGRAMGYM_GO_MOD_EOF
19
+ cat > /workspace/.programgym_build_env/go-prefetch/go.sum <<'PROGRAMGYM_GO_SUM_EOF'
20
+ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
21
+ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
22
+ github.com/oschwald/geoip2-golang v1.13.0 h1:Q44/Ldc703pasJeP5V9+aFSZFmBN7DKHbNsSFzQATJI=
23
+ github.com/oschwald/geoip2-golang v1.13.0/go.mod h1:P9zG+54KPEFOliZ29i7SeYZ/GM6tfEL+rgSn03hYuUo=
24
+ github.com/oschwald/maxminddb-golang v1.13.0 h1:R8xBorY71s84yO06NgTmQvqvTvlS/bnYZrrWX1MElnU=
25
+ github.com/oschwald/maxminddb-golang v1.13.0/go.mod h1:BU0z8BfFVhi1LQaonTwwGQlsHUEu9pWNdMfmq4ztm0o=
26
+ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
27
+ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
28
+ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
29
+ github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
30
+ golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
31
+ golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
32
+ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
33
+ gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
34
+ PROGRAMGYM_GO_SUM_EOF
35
+ PROGRAMGYM_INTERNAL_GO_PRIMARY_PROXY="${GOPROXY:-direct}"
36
+ PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY=""
37
+ case "$PROGRAMGYM_INTERNAL_GO_PRIMARY_PROXY" in
38
+ *"|"*|*","*)
39
+ PROGRAMGYM_INTERNAL_GO_FIRST_PROXY="${PROGRAMGYM_INTERNAL_GO_PRIMARY_PROXY%%[,|]*}"
40
+ PROGRAMGYM_INTERNAL_GO_PROXY_REMAINDER="${PROGRAMGYM_INTERNAL_GO_PRIMARY_PROXY#*[,|]}"
41
+ if [[ "$PROGRAMGYM_INTERNAL_GO_FIRST_PROXY" =~ [^[:space:]] ]] && [[ "$PROGRAMGYM_INTERNAL_GO_PROXY_REMAINDER" =~ [^[:space:]] ]]; then
42
+ PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY="${PROGRAMGYM_GO_PUBLIC_FALLBACK_PROXY:-${PROGRAMGYM_INTERNAL_GO_PROXY_REMAINDER}}"
43
+ fi
44
+ ;;
45
+ esac
46
+ if ! [[ "$PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY" =~ [^[:space:]] ]]; then
47
+ PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY=""
48
+ fi
49
+ cat > /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py <<'PROGRAMGYM_GO_TIMEOUT_SUPERVISOR_EOF'
50
+ import os
51
+ import signal
52
+ import subprocess
53
+ import sys
54
+ import time
55
+
56
+ sentinel_path, timeout_text, grace_text, proxy, *command = sys.argv[1:]
57
+ if not command:
58
+ raise SystemExit(125)
59
+ environment = os.environ.copy()
60
+ environment["GOPROXY"] = proxy
61
+ process = subprocess.Popen(command, env=environment, start_new_session=True)
62
+ try:
63
+ returncode = process.wait(timeout=float(timeout_text))
64
+ except subprocess.TimeoutExpired:
65
+ with open(sentinel_path, "w", encoding="utf-8") as sentinel:
66
+ sentinel.write("expired\n")
67
+ try:
68
+ os.killpg(process.pid, signal.SIGTERM)
69
+ except ProcessLookupError:
70
+ pass
71
+ deadline = time.monotonic() + float(grace_text)
72
+ group_alive = True
73
+ while time.monotonic() < deadline:
74
+ process.poll()
75
+ try:
76
+ os.killpg(process.pid, 0)
77
+ except ProcessLookupError:
78
+ group_alive = False
79
+ break
80
+ time.sleep(0.05)
81
+ if group_alive:
82
+ try:
83
+ os.killpg(process.pid, signal.SIGKILL)
84
+ except ProcessLookupError:
85
+ pass
86
+ process.wait()
87
+ raise SystemExit(124)
88
+ if returncode < 0:
89
+ returncode = 128 - returncode
90
+ raise SystemExit(returncode)
91
+ PROGRAMGYM_GO_TIMEOUT_SUPERVISOR_EOF
92
+ PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS="${PROGRAMGYM_GO_NEXUS_ATTEMPT_TIMEOUT_SECONDS:-90}"
93
+ if ! [[ "$PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS" =~ ^[1-9][0-9]*$ ]]; then
94
+ printf '%s\n' "download.sh: invalid PROGRAMGYM_GO_NEXUS_ATTEMPT_TIMEOUT_SECONDS=${PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS}" >&2
95
+ rm -f /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py
96
+ if [ "${BASH_SOURCE[0]}" != "$0" ]; then
97
+ return 1
98
+ else
99
+ exit 1
100
+ fi
101
+ fi
102
+ if ! command -v python3 >/dev/null 2>&1; then
103
+ printf '%s\n' 'download.sh: python3 is required for bounded Nexus Go downloads' >&2
104
+ rm -f /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py
105
+ if [ "${BASH_SOURCE[0]}" != "$0" ]; then
106
+ return 1
107
+ else
108
+ exit 1
109
+ fi
110
+ fi
111
+ _programgym_go_with_nexus_timeout() {
112
+ local programgym_go_rc
113
+ local programgym_go_timeout_sentinel
114
+ if ! programgym_go_timeout_sentinel="$(mktemp "${TMPDIR:-/tmp}/programgym-go-timeout.XXXXXX")"; then
115
+ return 1
116
+ fi
117
+ if python3 /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py "$programgym_go_timeout_sentinel" "$PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS" "5" "$PROGRAMGYM_INTERNAL_GO_PRIMARY_PROXY" "$@"; then
118
+ programgym_go_rc=0
119
+ else
120
+ programgym_go_rc=$?
121
+ fi
122
+ if [ ! -s "$programgym_go_timeout_sentinel" ]; then
123
+ rm -f "$programgym_go_timeout_sentinel"
124
+ return "$programgym_go_rc"
125
+ fi
126
+ rm -f "$programgym_go_timeout_sentinel"
127
+ if [ -z "$PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY" ]; then
128
+ printf '%s\n' "download.sh: primary Go request exceeded ${PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS}s; GOPROXY has no explicit non-empty fallback remainder" >&2
129
+ return "$programgym_go_rc"
130
+ fi
131
+ printf '%s\n' "download.sh: Nexus-first Go request exceeded ${PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS}s; retrying with GOPROXY=${PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY}" >&2
132
+ env GOPROXY="$PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY" "$@"
133
+ }
134
+ PROGRAMGYM_GO_BASE_GOROOT="$(GOTOOLCHAIN=local go env GOROOT)"
135
+ if ! PROGRAMGYM_GO_RESOLVED_GOROOT="$(cd /workspace/.programgym_build_env/go-prefetch && _programgym_go_with_nexus_timeout env GOTOOLCHAIN=auto go env GOROOT)"; then
136
+ printf '%s\n' 'download.sh: Go toolchain resolution failed' >&2
137
+ rm -f /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py
138
+ if [ "${BASH_SOURCE[0]}" != "$0" ]; then
139
+ return 1
140
+ else
141
+ exit 1
142
+ fi
143
+ fi
144
+ if [ "$PROGRAMGYM_GO_RESOLVED_GOROOT" != "$PROGRAMGYM_GO_BASE_GOROOT" ]; then
145
+ PROGRAMGYM_GO_TOOLCHAIN_ROOT=/opt/programgym-go-toolchain
146
+ mkdir -p "$PROGRAMGYM_GO_TOOLCHAIN_ROOT"
147
+ cp -a "$PROGRAMGYM_GO_RESOLVED_GOROOT/." "$PROGRAMGYM_GO_TOOLCHAIN_ROOT/"
148
+ export GOROOT="$PROGRAMGYM_GO_TOOLCHAIN_ROOT"
149
+ else
150
+ export GOROOT="$PROGRAMGYM_GO_BASE_GOROOT"
151
+ fi
152
+ export PATH="$GOROOT/bin:$PATH"
153
+ export GOTOOLCHAIN=local
154
+ if ! (cd /workspace/.programgym_build_env/go-prefetch && _programgym_go_with_nexus_timeout go mod download -modfile=/workspace/.programgym_build_env/go-prefetch/go.mod all); then
155
+ printf '%s\n' 'download.sh: Go dependency prefetch failed' >&2
156
+ rm -f /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py
157
+ if [ "${BASH_SOURCE[0]}" != "$0" ]; then
158
+ return 1
159
+ else
160
+ exit 1
161
+ fi
162
+ fi
163
+ rm -f /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py
164
+ unset -f _programgym_go_with_nexus_timeout
165
+ unset PROGRAMGYM_INTERNAL_GO_PRIMARY_PROXY
166
+ unset PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY
167
+ unset PROGRAMGYM_INTERNAL_GO_FIRST_PROXY
168
+ unset PROGRAMGYM_INTERNAL_GO_PROXY_REMAINDER
169
+ unset PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS
mpolden--echoip.746db5e/environment/executable ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ebd09d363ef915651c1d1178d229aa2afdd9bd27c274f53cd6e8f205d174cc06
3
+ size 12867026
mpolden--echoip.746db5e/environment/programgym-go.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:39042a078ea9ceebe3ecda4a7188f0f5b96e14a071d27923ba7f40b456e85ae3
3
+ size 59908810
mpolden--echoip.746db5e/environment/workspace.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:208a90f2afe3b5d5b0f692914d92b5c350df1fdb7a2e7465f36b1f0937845656
3
+ size 9936
mpolden--echoip.746db5e/instruction.md ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a helpful assistant that can interact with a computer.
2
+
3
+ This is a reverse-engineering benchmark. You are given a compiled binary and its documentation.
4
+ Your job is to write a new, original codebase from scratch that produces an executable with identical behavior.
5
+ You must figure out the behavior solely by running and interacting with the provided binary.
6
+ Writing original code based on observed behavior is the entire point of this benchmark.
7
+
8
+ Any approach that shortcuts this — finding existing source code, wrapping the binary,
9
+ or installing the original tool — does not count as a solution. It will be detected by an
10
+ automated judge, marked as a disqualification, and scored as a failure.
11
+ The trace will be posted to an online wall of shame.
12
+
13
+ <RULES>
14
+ ## What is not allowed
15
+
16
+ ### 1. Obtaining source code
17
+
18
+ The only source of truth about what the executable does is the executable itself and its
19
+ bundled documentation. You must not search the internet, package registries, or any external
20
+ source for information about this project's source code. Even if you recognize what the
21
+ executable is, you must reimplement it from behavioral observation alone.
22
+
23
+ This includes but is not limited to:
24
+ - Cloning or browsing the original GitHub repository, its forks, or mirrors
25
+ - Downloading the project from package registries: `cargo install <project>`, `go get github.com/<org>/<project>`, `pip install <project>`, `apt-get source <project>`, `npm install <project>`, etc.
26
+ - Fetching source tarballs from project websites (e.g., `curl https://lua.org/ftp/lua-5.5.0.tar.gz`)
27
+ - Using a package manager to download the project as a dependency and then reading its cached source (e.g., navigating into `~/.cargo/registry/src/` or `$(go env GOPATH)/pkg/mod/`)
28
+ - Searching the web for the project's source code or implementation details
29
+
30
+ ### 2. Wrapping or reusing the original binary
31
+
32
+ Your submission must be a genuine reimplementation. The provided `./executable` is for
33
+ observation only — your final solution must not depend on it or any other pre-built version
34
+ of the same tool at runtime.
35
+
36
+ This includes but is not limited to:
37
+ - Writing a wrapper script that delegates to the original binary (e.g., `exec zstd "$@"`)
38
+ - Installing the tool from a package manager and shimming to it (e.g., `apt-get install nnn && cp $(which nnn) ./executable`)
39
+ - Writing a `compile.sh` that simply makes the provided binary executable (`chmod +x ./executable`) or copies it (`cp ./executable ./executable`)
40
+ - Building a binary whose main function shells out to an external tool (e.g., `Command::new("miniserve").args(args).exec()`)
41
+ - Re-linking prebuilt `.o` object files found in the workspace without writing new source code
42
+
43
+ ### 3. Binary analysis of the provided executable
44
+
45
+ All information about the provided `./executable` must be obtained by interacting with it
46
+ through its normal user interface (CLI flags, stdin/stdout, etc.).
47
+ - You MUST NOT decompile `./executable` or use disassemblers (objdump, Ghidra, etc.) on it
48
+ - You MUST NOT use strace, ltrace, or similar tracing/instrumentation tools on `./executable`
49
+
50
+ Note: this restriction applies ONLY to the provided `./executable`. You are free to use any
51
+ analysis tools on binaries that you produce yourself during development.
52
+
53
+ ## What IS allowed
54
+
55
+ - Running the executable with any inputs, flags, and arguments to observe its behavior
56
+ - Reading any documentation files bundled in the workspace
57
+ </RULES>
58
+
59
+ ## Task context
60
+
61
+ We want to write the source code for a given executable.
62
+ The executable is located at `./executable` in the workspace root.
63
+
64
+ You also have access to the existing documentation.
65
+
66
+ ## Your task
67
+
68
+ Implement the source code to generate an executable of exactly identical behavior as the original.
69
+
70
+ No project-specific dependencies are pre-installed.
71
+ You do NOT have access to the internet.
72
+ **IMPORTANT**: Make sure that the executable(s) and everything else that is an artifact is not committed, i.e., is in your `.gitignore` file.
73
+ Finally, commit your changes.
74
+
75
+ Make sure that you have a `./compile.sh` file that produces an executable `./executable` in the workspace root.
76
+ `compile.sh` should be executable and should install any dependencies needed to compile the executable.
77
+ If your compile.sh fails to compile on a fresh checkout, your task has failed.
78
+
79
+ ## Important: This is a reverse-engineering benchmark
80
+
81
+ Your goal is to write original code from scratch that reproduces the executable's behavior.
82
+ The only way to learn what the executable does is to run it and read its bundled documentation.
83
+
84
+ Any attempt to obtain source code — whether successful or not — or to wrap/reuse the
85
+ provided binary will be detected by an automated judge, disqualified, and scored as zero.
86
+ See the full rules in the system prompt above. Key points:
87
+
88
+ - Do NOT search the internet, clone repos, or download the project from any package registry
89
+ - Do NOT wrap, shim, or delegate to the provided `./executable` or any installed version of the same tool
90
+ - Do NOT decompile the provided `./executable` or use strace/ltrace on it (analyzing your own binaries is fine)
91
+ - You SHOULD extensively test the executable to understand its behavior before writing code.
92
+ If you are dealing with a TUI, tmux/libtmux has been installed to help you test/inspect/it.
93
+
94
+ ## Recommended Workflow
95
+
96
+ 1. Explore all documentation files
97
+ 2. Play with the executable to understand its behavior (however, you MUST NOT decompile `./executable` or perform any other form of binary or strace/ltrace analysis on it)
98
+ 3. Write the source code to implement the behavior
mpolden--echoip.746db5e/solution/solve.sh ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Oracle-only ceiling check. The reference is execute-only for normal agents;
3
+ # because the oracle runs as the owning `agent` user it can temporarily add read
4
+ # permission and encode the binary for Harbor's normal artifact handoff.
5
+ set -euo pipefail
6
+ test -f ./executable
7
+ chmod u+r ./executable
8
+ python3 - <<'PY'
9
+ import base64
10
+ from pathlib import Path
11
+
12
+ Path(".programgym_oracle_reference").write_bytes(
13
+ base64.b64encode(Path("executable").read_bytes())
14
+ )
15
+ PY
16
+ chmod u-r ./executable
17
+ cat > compile.sh <<'EOF'
18
+ #!/usr/bin/env bash
19
+ set -euo pipefail
20
+ if [ -f ./.programgym_oracle_reference ]; then
21
+ python3 - <<'PY'
22
+ import base64
23
+ from pathlib import Path
24
+
25
+ Path("executable").write_bytes(
26
+ base64.b64decode(Path(".programgym_oracle_reference").read_bytes())
27
+ )
28
+ PY
29
+ fi
30
+ test -f ./executable
31
+ chmod +x ./executable
32
+ EOF
33
+ chmod +x compile.sh
mpolden--echoip.746db5e/task.toml ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.3"
2
+ source = "ProgramGym"
3
+ artifacts = [
4
+ "/logs/verifier/programgym_eval.json",
5
+ "/logs/verifier/harbor_diagnostics.json",
6
+ "/logs/verifier/programgym_eval.log",
7
+ "/logs/verifier/reward.json",
8
+ "/logs/verifier/reward.txt",
9
+ # Keep agent/runtime state out of the submission handoff. In particular,
10
+ # Claude Code installs an absolute symlink under .local/bin; transferring it
11
+ # makes Python's safe tar extraction reject the entire workspace archive.
12
+ { source = "/workspace", exclude = [
13
+ "executable",
14
+ ".git",
15
+ ".bashrc",
16
+ ".cache",
17
+ ".cc-switch",
18
+ ".claude",
19
+ ".local",
20
+ ] },
21
+ ]
22
+
23
+ [task]
24
+ name = "programgym/mpolden--echoip.746db5e"
25
+ description = "Synthetic ProgramGym cleanroom reconstruction task for mpolden/echoip"
26
+ authors = [{ name = "Harbor ProgramGym Synthetic Adapter" }]
27
+ keywords = ["programgym", "synthetic", "reverse-engineering", "cleanroom", "go"]
28
+
29
+ [metadata]
30
+ source = "ProgramGym"
31
+ instance_id = "mpolden__echoip.746db5e"
32
+ repository = "mpolden/echoip"
33
+ commit = "746db5ebf42f87da5d487de444dccc884f9d1c39"
34
+ language = "go"
35
+ difficulty = "easy"
36
+ difficulty_score = 1.61320735210376
37
+ test_branches = 4
38
+ test_count = 441
39
+
40
+ [agent]
41
+ timeout_sec = 14400
42
+ user = "agent"
43
+ network_mode = "allowlist"
44
+ allowed_hosts = ["api.anthropic.com", "api.openai.com"]
45
+
46
+ [verifier]
47
+ timeout_sec = 7200
48
+ user = "root"
49
+ environment_mode = "separate"
50
+
51
+ [verifier.env]
52
+ PROGRAMGYM_XDIST_WORKERS = "8"
53
+
54
+ [verifier.environment]
55
+ build_timeout_sec = 1800
56
+ cpus = 8
57
+ memory_mb = 16384
58
+ storage_mb = 30720
59
+ gpus = 0
60
+ workdir = "/workspace"
61
+
62
+ [environment]
63
+ network_mode = "public"
64
+ build_timeout_sec = 1800
65
+ cpus = 8
66
+ memory_mb = 16384
67
+ storage_mb = 30720
68
+ gpus = 0
69
+ workdir = "/workspace"
mpolden--echoip.746db5e/tests/Dockerfile ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive
3
+ ENV RUSTUP_DIST_SERVER="https://static.rust-lang.org"
4
+ ENV RUSTUP_UPDATE_ROOT="https://static.rust-lang.org/rustup"
5
+ ENV CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse
6
+ ENV CARGO_REGISTRIES_CRATES_IO_INDEX="sparse+https://index.crates.io/"
7
+ ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
8
+ ENV GOPROXY="https://proxy.golang.org,direct"
9
+ ENV GOSUMDB=sum.golang.google.cn
10
+ ENV GOTOOLCHAIN=auto
11
+ ENV UV_INSECURE_HOST=""
12
+ ENV UV_INDEX_URL="https://pypi.org/simple"
13
+ ENV UV_EXTRA_INDEX_URL=https://pypi.org/simple
14
+ ENV UV_CACHE_DIR=/workspace/.cache/uv
15
+ ENV npm_config_registry="https://registry.npmjs.org/"
16
+ ENV npm_config_strict_ssl=false
17
+ ENV npm_config_cache=/workspace/.cache/npm
18
+ ENV PIP_INDEX_URL="https://pypi.org/simple"
19
+ ENV PIP_EXTRA_INDEX_URL=https://pypi.org/simple
20
+ ENV PIP_TRUSTED_HOST=""
21
+ ENV HOME=/workspace
22
+ ENV XDG_CACHE_HOME=/workspace/.cache
23
+ ENV PIP_CACHE_DIR=/workspace/.cache/pip
24
+ ENV PYTHONUSERBASE=/workspace/.local
25
+ ENV GOROOT=/usr/local/go
26
+ ENV GOPATH=/workspace/.go
27
+ ENV GOCACHE=/workspace/.cache/go-build
28
+ ENV PIP_BREAK_SYSTEM_PACKAGES=1
29
+ ENV PATH=/opt/programgym-venv/bin:/usr/local/go/bin:/workspace/.go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
30
+ ENV PAGER=cat
31
+ ENV MANPAGER=cat
32
+ ENV LESS=-R
33
+ ENV TQDM_DISABLE=1
34
+ ENV VIRTUAL_ENV=/opt/programgym-venv
35
+ RUN apt-get update && apt-get install -y --no-install-recommends bash build-essential ca-certificates git make pkg-config python3 python3-pip curl wget xz-utils unzip zip bzip2 zstd patch file binutils python3-venv tar && rm -rf /var/lib/apt/lists/*
36
+ COPY programgym-go.tar.gz /tmp/programgym-go.tar.gz
37
+ RUN set -eux; rm -rf /usr/local/go; tar -C /usr/local -xzf /tmp/programgym-go.tar.gz; rm -f /tmp/programgym-go.tar.gz; if [ ! -x /usr/local/go/bin/go ]; then echo "official Go tarball did not create /usr/local/go/bin/go" >&2; exit 1; fi; /usr/local/go/bin/go version
38
+ RUN python3 -m venv /opt/programgym-venv && /opt/programgym-venv/bin/python -m pip install --no-cache-dir --only-binary=:all: pytest pytest-xdist coverage
39
+ WORKDIR /workspace
40
+ ADD workspace.tar.gz /workspace/
41
+ COPY executable /workspace/executable
42
+ COPY download.sh /workspace/download.sh
43
+ RUN chmod 755 /workspace/download.sh
44
+ RUN ["bash","-lc","set -euo pipefail; cd /workspace; set -a; source /workspace/download.sh; set +a; python3 - <<'PY' > /etc/profile.d/programgym_download_env.sh\nimport os\nimport re\nimport shlex\nignored = {\"OLDPWD\", \"PWD\", \"SHLVL\", \"_\"}\nvalid_name = re.compile(r\"^[A-Za-z_][A-Za-z0-9_]*$\")\nfor key in sorted(os.environ):\n if key in ignored or key.startswith(\"BASH_FUNC_\") or not valid_name.fullmatch(key):\n continue\n value = os.environ[key]\n if \"\\n\" in value:\n continue\n print(f\"export {key}={shlex.quote(value)}\")\nPY\n"]
45
+ ENV BASH_ENV=/etc/profile.d/programgym_download_env.sh
46
+ RUN chmod 111 /workspace/executable
47
+ WORKDIR /workspace
48
+ # programgym-runtime-workspace-cleanup: v1
49
+ RUN ["bash","-lc","rm -f -- /workspace/download.sh /workspace/reference/build.sh && rm -rf -- /workspace/.programgym_build_env"]
50
+ # Harbor uses tests/ as the separate verifier build context. Start with the
51
+ # same toolchain as the agent, then remove every cleanroom workspace artifact.
52
+ RUN rm -rf /workspace/* /workspace/.[!.]* 2>/dev/null || true \
53
+ && mkdir -p /workspace /tests
54
+
55
+ # Synthetic cleanroom Dockerfiles commonly install Ubuntu's pytest-xdist 2.5.0.
56
+ # Installing a newer pytest alone leaves that apt package importable and creates
57
+ # an incompatible mixed apt/pip stack (xdist 2.5 imports the removed py.log).
58
+ # Install and constrain the verifier test runner as one coherent pip toolchain.
59
+ RUN printf 'pytest<9\n' > /etc/pip-constraint.txt
60
+ ENV PIP_CONSTRAINT=/etc/pip-constraint.txt
61
+ RUN python3 -m pip install --no-cache-dir --disable-pip-version-check \
62
+ 'pytest<9' 'pytest-xdist>=3,<4' pytest-rerunfailures pytest-timeout
63
+
64
+ COPY test.sh /tests/test.sh
65
+ COPY programgym_evaluator.py /tests/programgym_evaluator.py
66
+ COPY programgym_task.json /tests/programgym_task.json
67
+ COPY blobs/ /tests/blobs/
68
+ RUN chmod +x /tests/test.sh
mpolden--echoip.746db5e/tests/blobs/tests/generated_module_01.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7cd33fb742a76891fdc51daa89cbf85ecc88b20dec028c54f32802418054748a
3
+ size 14802
mpolden--echoip.746db5e/tests/blobs/tests/generated_module_02.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:83f0fa88f91047c5326748a39d006437883bc5317fb834346b92f64832a9aa82
3
+ size 16296
mpolden--echoip.746db5e/tests/blobs/tests/generated_module_03.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7bd73ad1c595bfd3da4c8897b23fbb3986f4625e667616ee30ac55308b26effa
3
+ size 16164
mpolden--echoip.746db5e/tests/blobs/tests/generated_module_04.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9644106801f54308ad688c0a881d1e22d6b55dce3dcd268b2a0c5e05fdaf8d79
3
+ size 15704
mpolden--echoip.746db5e/tests/download.sh ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # PROGRAMGYM-MANAGED-GO-DOWNLOAD: v1
3
+ # Generated deterministically from repository module metadata; do not edit.
4
+ set -u
5
+ export GOTOOLCHAIN=auto
6
+ mkdir -p /workspace/.programgym_build_env/go-prefetch
7
+ cat > /workspace/.programgym_build_env/go-prefetch/go.mod <<'PROGRAMGYM_GO_MOD_EOF'
8
+ module github.com/mpolden/echoip
9
+
10
+ go 1.24
11
+
12
+ require github.com/oschwald/geoip2-golang v1.13.0
13
+
14
+ require (
15
+ github.com/oschwald/maxminddb-golang v1.13.0 // indirect
16
+ golang.org/x/sys v0.20.0 // indirect
17
+ )
18
+ PROGRAMGYM_GO_MOD_EOF
19
+ cat > /workspace/.programgym_build_env/go-prefetch/go.sum <<'PROGRAMGYM_GO_SUM_EOF'
20
+ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
21
+ github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
22
+ github.com/oschwald/geoip2-golang v1.13.0 h1:Q44/Ldc703pasJeP5V9+aFSZFmBN7DKHbNsSFzQATJI=
23
+ github.com/oschwald/geoip2-golang v1.13.0/go.mod h1:P9zG+54KPEFOliZ29i7SeYZ/GM6tfEL+rgSn03hYuUo=
24
+ github.com/oschwald/maxminddb-golang v1.13.0 h1:R8xBorY71s84yO06NgTmQvqvTvlS/bnYZrrWX1MElnU=
25
+ github.com/oschwald/maxminddb-golang v1.13.0/go.mod h1:BU0z8BfFVhi1LQaonTwwGQlsHUEu9pWNdMfmq4ztm0o=
26
+ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
27
+ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
28
+ github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
29
+ github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
30
+ golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
31
+ golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
32
+ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
33
+ gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
34
+ PROGRAMGYM_GO_SUM_EOF
35
+ PROGRAMGYM_INTERNAL_GO_PRIMARY_PROXY="${GOPROXY:-direct}"
36
+ PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY=""
37
+ case "$PROGRAMGYM_INTERNAL_GO_PRIMARY_PROXY" in
38
+ *"|"*|*","*)
39
+ PROGRAMGYM_INTERNAL_GO_FIRST_PROXY="${PROGRAMGYM_INTERNAL_GO_PRIMARY_PROXY%%[,|]*}"
40
+ PROGRAMGYM_INTERNAL_GO_PROXY_REMAINDER="${PROGRAMGYM_INTERNAL_GO_PRIMARY_PROXY#*[,|]}"
41
+ if [[ "$PROGRAMGYM_INTERNAL_GO_FIRST_PROXY" =~ [^[:space:]] ]] && [[ "$PROGRAMGYM_INTERNAL_GO_PROXY_REMAINDER" =~ [^[:space:]] ]]; then
42
+ PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY="${PROGRAMGYM_GO_PUBLIC_FALLBACK_PROXY:-${PROGRAMGYM_INTERNAL_GO_PROXY_REMAINDER}}"
43
+ fi
44
+ ;;
45
+ esac
46
+ if ! [[ "$PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY" =~ [^[:space:]] ]]; then
47
+ PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY=""
48
+ fi
49
+ cat > /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py <<'PROGRAMGYM_GO_TIMEOUT_SUPERVISOR_EOF'
50
+ import os
51
+ import signal
52
+ import subprocess
53
+ import sys
54
+ import time
55
+
56
+ sentinel_path, timeout_text, grace_text, proxy, *command = sys.argv[1:]
57
+ if not command:
58
+ raise SystemExit(125)
59
+ environment = os.environ.copy()
60
+ environment["GOPROXY"] = proxy
61
+ process = subprocess.Popen(command, env=environment, start_new_session=True)
62
+ try:
63
+ returncode = process.wait(timeout=float(timeout_text))
64
+ except subprocess.TimeoutExpired:
65
+ with open(sentinel_path, "w", encoding="utf-8") as sentinel:
66
+ sentinel.write("expired\n")
67
+ try:
68
+ os.killpg(process.pid, signal.SIGTERM)
69
+ except ProcessLookupError:
70
+ pass
71
+ deadline = time.monotonic() + float(grace_text)
72
+ group_alive = True
73
+ while time.monotonic() < deadline:
74
+ process.poll()
75
+ try:
76
+ os.killpg(process.pid, 0)
77
+ except ProcessLookupError:
78
+ group_alive = False
79
+ break
80
+ time.sleep(0.05)
81
+ if group_alive:
82
+ try:
83
+ os.killpg(process.pid, signal.SIGKILL)
84
+ except ProcessLookupError:
85
+ pass
86
+ process.wait()
87
+ raise SystemExit(124)
88
+ if returncode < 0:
89
+ returncode = 128 - returncode
90
+ raise SystemExit(returncode)
91
+ PROGRAMGYM_GO_TIMEOUT_SUPERVISOR_EOF
92
+ PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS="${PROGRAMGYM_GO_NEXUS_ATTEMPT_TIMEOUT_SECONDS:-90}"
93
+ if ! [[ "$PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS" =~ ^[1-9][0-9]*$ ]]; then
94
+ printf '%s\n' "download.sh: invalid PROGRAMGYM_GO_NEXUS_ATTEMPT_TIMEOUT_SECONDS=${PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS}" >&2
95
+ rm -f /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py
96
+ if [ "${BASH_SOURCE[0]}" != "$0" ]; then
97
+ return 1
98
+ else
99
+ exit 1
100
+ fi
101
+ fi
102
+ if ! command -v python3 >/dev/null 2>&1; then
103
+ printf '%s\n' 'download.sh: python3 is required for bounded Nexus Go downloads' >&2
104
+ rm -f /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py
105
+ if [ "${BASH_SOURCE[0]}" != "$0" ]; then
106
+ return 1
107
+ else
108
+ exit 1
109
+ fi
110
+ fi
111
+ _programgym_go_with_nexus_timeout() {
112
+ local programgym_go_rc
113
+ local programgym_go_timeout_sentinel
114
+ if ! programgym_go_timeout_sentinel="$(mktemp "${TMPDIR:-/tmp}/programgym-go-timeout.XXXXXX")"; then
115
+ return 1
116
+ fi
117
+ if python3 /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py "$programgym_go_timeout_sentinel" "$PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS" "5" "$PROGRAMGYM_INTERNAL_GO_PRIMARY_PROXY" "$@"; then
118
+ programgym_go_rc=0
119
+ else
120
+ programgym_go_rc=$?
121
+ fi
122
+ if [ ! -s "$programgym_go_timeout_sentinel" ]; then
123
+ rm -f "$programgym_go_timeout_sentinel"
124
+ return "$programgym_go_rc"
125
+ fi
126
+ rm -f "$programgym_go_timeout_sentinel"
127
+ if [ -z "$PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY" ]; then
128
+ printf '%s\n' "download.sh: primary Go request exceeded ${PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS}s; GOPROXY has no explicit non-empty fallback remainder" >&2
129
+ return "$programgym_go_rc"
130
+ fi
131
+ printf '%s\n' "download.sh: Nexus-first Go request exceeded ${PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS}s; retrying with GOPROXY=${PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY}" >&2
132
+ env GOPROXY="$PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY" "$@"
133
+ }
134
+ PROGRAMGYM_GO_BASE_GOROOT="$(GOTOOLCHAIN=local go env GOROOT)"
135
+ if ! PROGRAMGYM_GO_RESOLVED_GOROOT="$(cd /workspace/.programgym_build_env/go-prefetch && _programgym_go_with_nexus_timeout env GOTOOLCHAIN=auto go env GOROOT)"; then
136
+ printf '%s\n' 'download.sh: Go toolchain resolution failed' >&2
137
+ rm -f /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py
138
+ if [ "${BASH_SOURCE[0]}" != "$0" ]; then
139
+ return 1
140
+ else
141
+ exit 1
142
+ fi
143
+ fi
144
+ if [ "$PROGRAMGYM_GO_RESOLVED_GOROOT" != "$PROGRAMGYM_GO_BASE_GOROOT" ]; then
145
+ PROGRAMGYM_GO_TOOLCHAIN_ROOT=/opt/programgym-go-toolchain
146
+ mkdir -p "$PROGRAMGYM_GO_TOOLCHAIN_ROOT"
147
+ cp -a "$PROGRAMGYM_GO_RESOLVED_GOROOT/." "$PROGRAMGYM_GO_TOOLCHAIN_ROOT/"
148
+ export GOROOT="$PROGRAMGYM_GO_TOOLCHAIN_ROOT"
149
+ else
150
+ export GOROOT="$PROGRAMGYM_GO_BASE_GOROOT"
151
+ fi
152
+ export PATH="$GOROOT/bin:$PATH"
153
+ export GOTOOLCHAIN=local
154
+ if ! (cd /workspace/.programgym_build_env/go-prefetch && _programgym_go_with_nexus_timeout go mod download -modfile=/workspace/.programgym_build_env/go-prefetch/go.mod all); then
155
+ printf '%s\n' 'download.sh: Go dependency prefetch failed' >&2
156
+ rm -f /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py
157
+ if [ "${BASH_SOURCE[0]}" != "$0" ]; then
158
+ return 1
159
+ else
160
+ exit 1
161
+ fi
162
+ fi
163
+ rm -f /workspace/.programgym_build_env/go-prefetch/.programgym_go_timeout_supervisor.py
164
+ unset -f _programgym_go_with_nexus_timeout
165
+ unset PROGRAMGYM_INTERNAL_GO_PRIMARY_PROXY
166
+ unset PROGRAMGYM_INTERNAL_GO_FALLBACK_PROXY
167
+ unset PROGRAMGYM_INTERNAL_GO_FIRST_PROXY
168
+ unset PROGRAMGYM_INTERNAL_GO_PROXY_REMAINDER
169
+ unset PROGRAMGYM_INTERNAL_GO_NEXUS_TIMEOUT_SECONDS
mpolden--echoip.746db5e/tests/executable ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ebd09d363ef915651c1d1178d229aa2afdd9bd27c274f53cd6e8f205d174cc06
3
+ size 12867026
mpolden--echoip.746db5e/tests/programgym-go.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:39042a078ea9ceebe3ecda4a7188f0f5b96e14a071d27923ba7f40b456e85ae3
3
+ size 59908810
mpolden--echoip.746db5e/tests/programgym_evaluator.py ADDED
@@ -0,0 +1,1201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """In-place ProgramGym evaluator.
3
+
4
+ Mirrors ProgramGym's ``Evaluator`` pipeline as closely as a single-container,
5
+ no-Docker-in-Docker host allows. Run from ``tests/test.sh`` inside the agent's
6
+ cleanroom container after Harbor flips the verifier-phase network policy.
7
+
8
+ Differences from ``programgym.eval.eval.Evaluator`` that are structural to
9
+ running in one container:
10
+
11
+ * No fresh container per branch. ``snapshot_workspace`` / ``restore_workspace``
12
+ copy a post-compile workspace snapshot to a temp directory and restore it
13
+ before each branch; ``cleanup_lingering_processes`` kills leftover branch
14
+ processes between attempts to approximate the fresh-container boundary.
15
+ * No ``docker commit``. The post-compile workspace snapshot serves the same
16
+ role as the committed image upstream.
17
+ * Hidden test blobs are fetched on demand from HuggingFace via
18
+ ``huggingface_hub.snapshot_download`` (matching ``programgym.utils.blob_store``)
19
+ rather than being pre-staged into ``/tests/blobs/``. Override with
20
+ ``PROGRAMGYM_BLOB_DIR`` for offline reruns.
21
+
22
+ Everything else (eval_clean_hashes scrub, deterministic synthetic git seed,
23
+ ``compile.sh`` then stash + hash the executable, best-effort
24
+ ``pytest-rerunfailures``, per-branch test-tar overlay, executable hash
25
+ ``--max-worker-restart=4``, xdist worker-crash retry with serial fallback,
26
+ best-of-N attempt selection, active vs ignored test bookkeeping, scoring) is
27
+ preserved.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import hashlib
33
+ import json
34
+ import os
35
+ import re
36
+ import shlex
37
+ import shutil
38
+ import signal
39
+ import subprocess
40
+ import tempfile
41
+ import time
42
+ import traceback
43
+ import xml.etree.ElementTree as ET
44
+ from pathlib import Path
45
+ from typing import Any
46
+
47
+ WORKSPACE = Path(os.environ.get("PROGRAMGYM_WORKSPACE", "/workspace"))
48
+ STASHED_EXECUTABLE = Path("/opt/programgym-stashed-executable-do-not-modify")
49
+ METADATA_PATH = Path(
50
+ os.environ.get("PROGRAMGYM_METADATA", "/tests/programgym_task.json")
51
+ )
52
+ LOG_DIR = Path(os.environ.get("PROGRAMGYM_LOG_DIR", "/logs/verifier"))
53
+ WORKER_CRASH_PHRASE = "worker '"
54
+ XDIST_COLLAPSE_MARKERS = (
55
+ "maximum crashed workers reached",
56
+ "xdist: maximum crashed",
57
+ )
58
+
59
+ DEFAULT_HF_REPO_ID = "programgym/ProgramGym-Tests"
60
+ DEFAULT_HF_REVISION = "main"
61
+
62
+ # Oracle agent handoff files (see solution/solve.sh). Must not appear in the
63
+ # post-compile workspace snapshot or they pollute tree-scanning tests (dutree).
64
+ _ORACLE_HANDOFF_NAMES = (".programgym_oracle_reference",)
65
+
66
+ _TOOLCHAIN_BIN_DIR_CANDIDATES = (
67
+ "/usr/local/go/bin",
68
+ "/go/bin",
69
+ "/usr/local/cargo/bin",
70
+ "/root/.cargo/bin",
71
+ "/root/.ghcup/bin",
72
+ )
73
+
74
+
75
+ def toolchain_bin_dirs() -> list[str]:
76
+ """Return toolchain bin directories that exist on this image."""
77
+ candidates = list(_TOOLCHAIN_BIN_DIR_CANDIDATES)
78
+ candidates.extend(
79
+ str(path)
80
+ for path in sorted(Path("/usr/lib").glob("go-*/bin"))
81
+ if _is_accessible_dir(path)
82
+ )
83
+ seen: set[str] = set()
84
+ present: list[str] = []
85
+ for path in candidates:
86
+ if path in seen:
87
+ continue
88
+ seen.add(path)
89
+ if _is_accessible_dir(path):
90
+ present.append(path)
91
+ return present
92
+
93
+
94
+ def _is_accessible_dir(path: str | Path) -> bool:
95
+ """Return whether path is a directory without failing on protected homes."""
96
+ try:
97
+ return Path(path).is_dir()
98
+ except OSError:
99
+ return False
100
+
101
+
102
+ def bootstrap_toolchain_path() -> str:
103
+ """Prepend discovered toolchain dirs to PATH (idempotent)."""
104
+ prepend = toolchain_bin_dirs()
105
+ current_parts = [part for part in os.environ.get("PATH", "").split(":") if part]
106
+ merged: list[str] = []
107
+ for path in prepend + current_parts:
108
+ if path not in merged:
109
+ merged.append(path)
110
+ new_path = ":".join(merged)
111
+ os.environ["PATH"] = new_path
112
+ return new_path
113
+
114
+
115
+ def _bash_login_command(command: str) -> str:
116
+ """Run ``command`` under bash -lc with an explicit PATH export."""
117
+ path = bootstrap_toolchain_path()
118
+ return f"export PATH={shlex.quote(path)}; {command}"
119
+
120
+
121
+ def sha256(path: Path) -> str:
122
+ h = hashlib.sha256()
123
+ with path.open("rb") as f:
124
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
125
+ h.update(chunk)
126
+ return h.hexdigest()
127
+
128
+
129
+ def write_json(path: Path, data: dict[str, Any]) -> None:
130
+ tmp = path.with_suffix(path.suffix + ".tmp")
131
+ tmp.write_text(json.dumps(data, indent=2, sort_keys=True))
132
+ tmp.replace(path)
133
+
134
+
135
+ def _read_log_tail(path: Path | None, max_bytes: int = 65536) -> str:
136
+ if path is None or not path.exists():
137
+ return ""
138
+ data = path.read_bytes()
139
+ if len(data) <= max_bytes:
140
+ return data.decode(errors="replace")
141
+ return data[-max_bytes:].decode(errors="replace")
142
+
143
+
144
+ def _close_pipes(proc: subprocess.Popen[Any]) -> None:
145
+ for stream in (proc.stdout, proc.stderr):
146
+ if stream is not None:
147
+ try:
148
+ stream.close()
149
+ except OSError:
150
+ pass
151
+
152
+
153
+ def _terminate_process_tree(proc: subprocess.Popen[Any]) -> None:
154
+ try:
155
+ os.killpg(proc.pid, signal.SIGKILL)
156
+ except ProcessLookupError:
157
+ pass
158
+ try:
159
+ proc.kill()
160
+ except ProcessLookupError:
161
+ pass
162
+
163
+
164
+ _PKILL_PATTERNS = (
165
+ f"{WORKSPACE}/eval/",
166
+ f"{WORKSPACE}/tests/",
167
+ "tail -f",
168
+ "development.log",
169
+ " less ",
170
+ " less$",
171
+ "/less ",
172
+ )
173
+
174
+
175
+ def _pkill_aggressive() -> str:
176
+ """Best-effort kill of branch pytest/subprocess trees (Modal gVisor fallback)."""
177
+ notes: list[str] = []
178
+ workspace = str(WORKSPACE)
179
+ patterns = list(_PKILL_PATTERNS) + [
180
+ f"pytest.*{workspace}",
181
+ f"xdist.*{workspace}",
182
+ ]
183
+ for pattern in patterns:
184
+ result = subprocess.run(
185
+ ["pkill", "-9", "-f", pattern],
186
+ capture_output=True,
187
+ text=True,
188
+ )
189
+ notes.append(f"pkill -9 -f {pattern!r}: rc={result.returncode}")
190
+ return "\n".join(notes)
191
+
192
+
193
+ def run_step(
194
+ command: str,
195
+ cwd: Path,
196
+ *,
197
+ timeout: int,
198
+ env: dict[str, str] | None = None,
199
+ step: str,
200
+ accept_failure: bool = False,
201
+ log_output: bool | None = None,
202
+ max_output_bytes: int = 65536,
203
+ ) -> dict[str, Any]:
204
+ if log_output is None:
205
+ log_output = step == "run_tests" or timeout >= 60
206
+
207
+ started = time.monotonic()
208
+ stdout_path: Path | None = None
209
+ stderr_path: Path | None = None
210
+ stdout_f = None
211
+ stderr_f = None
212
+
213
+ if log_output:
214
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
215
+ log_id = f"{step}-{int(started * 1000)}"
216
+ stdout_path = LOG_DIR / f"run-step-{log_id}.stdout.log"
217
+ stderr_path = LOG_DIR / f"run-step-{log_id}.stderr.log"
218
+ stdout_f = stdout_path.open("w", encoding="utf-8")
219
+ stderr_f = stderr_path.open("w", encoding="utf-8")
220
+ popen_stdout: Any = stdout_f
221
+ popen_stderr: Any = stderr_f
222
+ else:
223
+ popen_stdout = subprocess.PIPE
224
+ popen_stderr = subprocess.PIPE
225
+
226
+ proc = subprocess.Popen(
227
+ ["bash", "-lc", _bash_login_command(command)],
228
+ cwd=cwd,
229
+ env={**os.environ, **(env or {})},
230
+ stdout=popen_stdout,
231
+ stderr=popen_stderr,
232
+ start_new_session=True,
233
+ text=True,
234
+ )
235
+ timed_out = False
236
+ stdout = ""
237
+ stderr = ""
238
+ try:
239
+ if log_output:
240
+ proc.wait(timeout=timeout)
241
+ else:
242
+ stdout, stderr = proc.communicate(timeout=timeout)
243
+ except subprocess.TimeoutExpired:
244
+ timed_out = True
245
+ _terminate_process_tree(proc)
246
+ cleanup_lingering_processes(aggressive=True)
247
+ try:
248
+ proc.wait(timeout=5)
249
+ except subprocess.TimeoutExpired:
250
+ proc.kill()
251
+ if not log_output:
252
+ _close_pipes(proc)
253
+ finally:
254
+ if stdout_f is not None:
255
+ stdout_f.close()
256
+ if stderr_f is not None:
257
+ stderr_f.close()
258
+
259
+ if timed_out:
260
+ if log_output:
261
+ output = _read_log_tail(stdout_path, max_output_bytes) + _read_log_tail(
262
+ stderr_path, max_output_bytes
263
+ )
264
+ else:
265
+ output = ""
266
+ entry = {
267
+ "step": step,
268
+ "command": command,
269
+ "wall_time": time.monotonic() - started,
270
+ "output": output,
271
+ "returncode": 124,
272
+ "exception_info": f"timed out after {timeout}s",
273
+ }
274
+ else:
275
+ if log_output:
276
+ output = _read_log_tail(stdout_path, max_output_bytes) + _read_log_tail(
277
+ stderr_path, max_output_bytes
278
+ )
279
+ else:
280
+ output = stdout + stderr
281
+ entry = {
282
+ "step": step,
283
+ "command": command,
284
+ "wall_time": time.monotonic() - started,
285
+ "output": output,
286
+ "returncode": proc.returncode,
287
+ "exception_info": "",
288
+ }
289
+ if entry["returncode"] and not accept_failure:
290
+ raise RuntimeError(
291
+ f"{step} failed: {entry['exception_info'] or entry['output']}"
292
+ )
293
+ return entry
294
+
295
+
296
+ def cleanup_lingering_processes(*, aggressive: bool = False) -> dict[str, Any]:
297
+ started = time.monotonic()
298
+ patterns = [
299
+ str(WORKSPACE / "executable"),
300
+ f"{WORKSPACE}/eval/",
301
+ f"{WORKSPACE}/tests/",
302
+ # lazygit --logs/-l tests spawn `tail -f` outside /workspace/.
303
+ "tail -f",
304
+ "development.log",
305
+ ]
306
+ killed: list[int] = []
307
+ proc_root = Path("/proc")
308
+ proc_available = proc_root.exists()
309
+ if proc_available:
310
+ for proc_dir in proc_root.iterdir():
311
+ if not proc_dir.name.isdigit():
312
+ continue
313
+ pid = int(proc_dir.name)
314
+ if pid in {os.getpid(), os.getppid()}:
315
+ continue
316
+ try:
317
+ raw = (proc_dir / "cmdline").read_bytes()
318
+ except (FileNotFoundError, PermissionError, ProcessLookupError):
319
+ continue
320
+ cmdline = raw.replace(b"\0", b" ").decode(errors="replace")
321
+ if not any(pattern in cmdline for pattern in patterns):
322
+ continue
323
+ try:
324
+ os.kill(pid, signal.SIGKILL)
325
+ except (PermissionError, ProcessLookupError):
326
+ continue
327
+ killed.append(pid)
328
+ pkill_output = ""
329
+ if aggressive or not proc_available:
330
+ pkill_output = _pkill_aggressive()
331
+ output_parts = []
332
+ if killed:
333
+ output_parts.append("\n".join(str(pid) for pid in killed))
334
+ if pkill_output:
335
+ output_parts.append(pkill_output)
336
+ return {
337
+ "step": "cleanup_lingering_processes",
338
+ "command": "kill leftover branch processes referencing the workspace",
339
+ "wall_time": time.monotonic() - started,
340
+ "output": "\n".join(output_parts),
341
+ "returncode": 0,
342
+ "exception_info": "",
343
+ }
344
+
345
+
346
+ def extract_trusted_blob(tar_path: Path, dest: Path) -> None:
347
+ import tarfile
348
+
349
+ with tarfile.open(tar_path, "r:gz") as tf:
350
+ try:
351
+ tf.extractall(dest, filter="fully_trusted")
352
+ except TypeError:
353
+ tf.extractall(dest)
354
+
355
+
356
+ def find_results_xml() -> Path | None:
357
+ """Return the junit xml path if pytest wrote one."""
358
+ for candidate in (WORKSPACE / "eval" / "results.xml", WORKSPACE / "results.xml"):
359
+ if candidate.exists():
360
+ return candidate
361
+ return None
362
+
363
+
364
+ def remove_oracle_handoff_artifacts() -> list[str]:
365
+ """Drop oracle-agent handoff files from /workspace before snapshot/restore."""
366
+ removed: list[str] = []
367
+ for name in _ORACLE_HANDOFF_NAMES:
368
+ path = WORKSPACE / name
369
+ if path.exists():
370
+ if path.is_dir():
371
+ shutil.rmtree(path)
372
+ else:
373
+ path.unlink()
374
+ removed.append(name)
375
+ return removed
376
+
377
+
378
+ def _remove_tree(path: Path) -> None:
379
+ """Remove a file or directory tree, with a shell fallback for overlay races."""
380
+ if path.is_symlink() or path.is_file():
381
+ path.unlink(missing_ok=True)
382
+ return
383
+ if not path.is_dir():
384
+ path.unlink(missing_ok=True)
385
+ return
386
+ for attempt in range(3):
387
+ try:
388
+ shutil.rmtree(path)
389
+ if not path.exists():
390
+ return
391
+ except OSError:
392
+ if attempt == 2:
393
+ run_step(
394
+ f"rm -rf {shlex.quote(str(path))}",
395
+ path.parent,
396
+ timeout=120,
397
+ step="clear_workspace_fallback",
398
+ accept_failure=True,
399
+ )
400
+ if not path.exists():
401
+ return
402
+ raise
403
+
404
+
405
+ def ensure_workspace_dir() -> None:
406
+ """Guarantee WORKSPACE exists as a writable directory (not a symlink/file)."""
407
+ if WORKSPACE.exists() and not WORKSPACE.is_dir():
408
+ if WORKSPACE.is_symlink() or WORKSPACE.is_file():
409
+ WORKSPACE.unlink()
410
+ else:
411
+ shutil.rmtree(WORKSPACE)
412
+ WORKSPACE.mkdir(parents=True, exist_ok=True)
413
+
414
+
415
+ def clear_workspace() -> None:
416
+ ensure_workspace_dir()
417
+ for path in list(WORKSPACE.iterdir()):
418
+ _remove_tree(path)
419
+
420
+
421
+ def restore_reference_executable() -> None:
422
+ """Write the stashed reference binary into /workspace after a branch overlay.
423
+
424
+ Branch blobs may ship ``executable`` as a dangling symlink into
425
+ ``target/release/...``; ``shutil.copy2`` would follow it and raise
426
+ ``FileNotFoundError``. Drop whatever the blob left and copy the stashed
427
+ reference as a regular file.
428
+ """
429
+ ensure_workspace_dir()
430
+ if not STASHED_EXECUTABLE.is_file():
431
+ raise FileNotFoundError(
432
+ f"missing stashed reference executable at {STASHED_EXECUTABLE}"
433
+ )
434
+ dest = WORKSPACE / "executable"
435
+ if dest.exists() or dest.is_symlink():
436
+ if dest.is_dir():
437
+ shutil.rmtree(dest)
438
+ else:
439
+ dest.unlink(missing_ok=True)
440
+ shutil.copy2(STASHED_EXECUTABLE, dest)
441
+ dest.chmod(0o755)
442
+
443
+
444
+ def snapshot_workspace(dest: Path) -> None:
445
+ if dest.exists():
446
+ shutil.rmtree(dest)
447
+ shutil.copytree(WORKSPACE, dest, symlinks=True)
448
+
449
+
450
+ def restore_workspace(source: Path) -> None:
451
+ clear_workspace()
452
+ shutil.copytree(source, WORKSPACE, dirs_exist_ok=True, symlinks=True)
453
+ ensure_workspace_dir()
454
+
455
+
456
+ def remove_hashed_files(root: Path, hashes: set[str]) -> list[str]:
457
+ removed: list[str] = []
458
+ for path in root.rglob("*"):
459
+ if path.is_file() and not path.is_symlink():
460
+ try:
461
+ if sha256(path) in hashes:
462
+ path.unlink()
463
+ removed.append(str(path.relative_to(root)))
464
+ except OSError:
465
+ continue
466
+ return removed
467
+
468
+
469
+ def branch_tests(branch_info: dict[str, Any]) -> list[str]:
470
+ ignored = {
471
+ item["name"] for item in branch_info.get("ignored_tests", []) if "name" in item
472
+ }
473
+ return [name for name in branch_info.get("tests", []) if name not in ignored]
474
+
475
+
476
+ def ignored_tests(metadata: dict[str, Any]) -> set[str]:
477
+ result: set[str] = set()
478
+ for branch, info in metadata.get("branches", {}).items():
479
+ result.update(
480
+ f"{branch}/{item['name']}"
481
+ for item in info.get("ignored_tests", [])
482
+ if "name" in item
483
+ )
484
+ return result
485
+
486
+
487
+ def active_tests(metadata: dict[str, Any]) -> set[str]:
488
+ active: set[str] = set()
489
+ for branch, info in metadata.get("branches", {}).items():
490
+ if info.get("ignored"):
491
+ continue
492
+ ignored = {
493
+ item["name"] for item in info.get("ignored_tests", []) if "name" in item
494
+ }
495
+ active.update(
496
+ f"{branch}/{name}" for name in info.get("tests", []) if name not in ignored
497
+ )
498
+ return active
499
+
500
+
501
+ def inject_not_run(
502
+ result: dict[str, Any], branch: str, tests: list[str], error_code: str
503
+ ) -> None:
504
+ result["test_results"].extend(
505
+ {
506
+ "name": name,
507
+ "branch": branch,
508
+ "status": "not_run",
509
+ "extra": {"error_code": error_code},
510
+ }
511
+ for name in tests
512
+ )
513
+
514
+
515
+ def testcase_name(case: ET.Element) -> str:
516
+ classname = case.attrib.get("classname", "")
517
+ name = case.attrib.get("name", "")
518
+ return f"{classname}.{name}" if classname else name
519
+
520
+
521
+ # Only these tags under <testcase> represent a result. <system-out> /
522
+ # <system-err> are stdout/stderr captures and must not be treated as results
523
+ # (a leading <system-out> followed by <failure> would otherwise be classified
524
+ # as a stdout-only "passed").
525
+ JUNIT_RESULT_TAGS = {"skipped", "failure", "error"}
526
+
527
+
528
+ def parse_junit(
529
+ raw_xml: str, branch: str, expected: list[str], ignored: set[str]
530
+ ) -> tuple[list[dict[str, Any]], list[str]]:
531
+ root = ET.fromstring(raw_xml)
532
+ got: set[str] = set()
533
+ results: list[dict[str, Any]] = []
534
+ for case in root.iter("testcase"):
535
+ name = testcase_name(case)
536
+ got.add(name)
537
+ extra: dict[str, Any] = {}
538
+ if "time" in case.attrib:
539
+ try:
540
+ extra["time"] = float(case.attrib["time"])
541
+ except ValueError:
542
+ extra["time"] = case.attrib["time"]
543
+ result_children = [c for c in case if c.tag in JUNIT_RESULT_TAGS]
544
+ # Collapse duplicate same-tag result children. Pytest's
545
+ # "pytest.internal" pseudo-test sometimes emits two identical <error>
546
+ # entries; treating that as a system_error would over-flag a real
547
+ # single failure. Mirrors upstream eval.py:816-820.
548
+ if len(result_children) > 1 and len({c.tag for c in result_children}) == 1:
549
+ result_children = [result_children[0]]
550
+ if not result_children:
551
+ status = "passed"
552
+ elif len(result_children) != 1:
553
+ status = "system_error"
554
+ extra["error_details"] = (
555
+ f"Expected 1 result for {name}, got {len(result_children)}: "
556
+ f"{[c.tag for c in result_children]}"
557
+ )
558
+ else:
559
+ first = result_children[0]
560
+ status = first.tag # "skipped" | "failure" | "error"
561
+ extra["message"] = first.attrib.get("message") or ""
562
+ if first.text:
563
+ extra["text"] = first.text
564
+ results.append(
565
+ {"name": name, "branch": branch, "status": status, "extra": extra}
566
+ )
567
+
568
+ active_expected = [name for name in expected if name not in ignored]
569
+ missing = [name for name in active_expected if name not in got]
570
+ results.extend(
571
+ {
572
+ "name": name,
573
+ "branch": branch,
574
+ "status": "not_run",
575
+ "extra": {"error_code": "missing_from_junit_xml"},
576
+ }
577
+ for name in missing
578
+ )
579
+ unexpected = got - set(expected) - ignored
580
+ warnings = (
581
+ [f"Branch {branch}: {len(unexpected)} test(s) in JUnit XML not in tests.json"]
582
+ if unexpected
583
+ else []
584
+ )
585
+ return results, warnings
586
+
587
+
588
+ def count_worker_crashes(raw_xml: str) -> int:
589
+ if WORKER_CRASH_PHRASE not in raw_xml:
590
+ return 0
591
+ try:
592
+ root = ET.fromstring(raw_xml)
593
+ except ET.ParseError:
594
+ return 0
595
+ crashes = 0
596
+ for case in root.iter("testcase"):
597
+ for child in case:
598
+ text = (child.get("message") or "") + " " + (child.text or "")
599
+ if (
600
+ child.tag in {"error", "failure"}
601
+ and WORKER_CRASH_PHRASE in text
602
+ and "crashed" in text
603
+ ):
604
+ crashes += 1
605
+ break
606
+ return crashes
607
+
608
+
609
+ def run_output_indicates_xdist_collapse(output: str) -> bool:
610
+ lower = output.lower()
611
+ return any(marker in lower for marker in XDIST_COLLAPSE_MARKERS)
612
+
613
+
614
+ def count_junit_failures(raw_xml: str) -> int:
615
+ try:
616
+ root = ET.fromstring(raw_xml)
617
+ except ET.ParseError:
618
+ return 0
619
+ failures = 0
620
+ for case in root.iter("testcase"):
621
+ for child in case:
622
+ if child.tag in {"failure", "error"}:
623
+ failures += 1
624
+ break
625
+ return failures
626
+
627
+
628
+ def count_junit_passed(raw_xml: str) -> int:
629
+ try:
630
+ root = ET.fromstring(raw_xml)
631
+ except ET.ParseError:
632
+ return 0
633
+ passed = 0
634
+ for case in root.iter("testcase"):
635
+ if not any(child.tag in JUNIT_RESULT_TAGS for child in case):
636
+ passed += 1
637
+ return passed
638
+
639
+
640
+ def branch_attempt_metrics(
641
+ raw_xml: str, *, run_output: str, expected_tests: int
642
+ ) -> tuple[int, int, int, int]:
643
+ """Return (crashes, n_testcases, failures, missing_from_xml)."""
644
+ crashes = count_worker_crashes(raw_xml)
645
+ if run_output_indicates_xdist_collapse(run_output):
646
+ crashes = max(crashes, 1)
647
+ n_tests = count_testcases(raw_xml)
648
+ failures = count_junit_failures(raw_xml)
649
+ missing = max(0, expected_tests - n_tests)
650
+ return crashes, n_tests, failures, missing
651
+
652
+
653
+ def needs_serial_retry(
654
+ *,
655
+ serial: bool,
656
+ crashes: int,
657
+ missing: int,
658
+ failures: int,
659
+ n_tests: int,
660
+ expected_tests: int,
661
+ run_output: str,
662
+ ) -> bool:
663
+ if serial:
664
+ return False
665
+ high_failure_rate = (
666
+ expected_tests > 0 and n_tests >= expected_tests and failures / n_tests >= 0.8
667
+ )
668
+ return (
669
+ crashes > 0
670
+ or missing > 0
671
+ or high_failure_rate
672
+ or run_output_indicates_xdist_collapse(run_output)
673
+ )
674
+
675
+
676
+ def count_testcases(raw_xml: str) -> int:
677
+ try:
678
+ return sum(1 for _ in ET.fromstring(raw_xml).iter("testcase"))
679
+ except ET.ParseError:
680
+ return 0
681
+
682
+
683
+ def scored_results(
684
+ result: dict[str, Any], metadata: dict[str, Any]
685
+ ) -> list[dict[str, Any]]:
686
+ active = active_tests(metadata)
687
+ by_key = {
688
+ f"{test['branch']}/{test['name']}": test
689
+ for test in result["test_results"]
690
+ if f"{test['branch']}/{test['name']}" in active
691
+ }
692
+ return [
693
+ by_key.get(
694
+ key,
695
+ {
696
+ "branch": key.split("/", 1)[0],
697
+ "name": key.split("/", 1)[1],
698
+ "status": "not_run",
699
+ "extra": {"error_code": "missing_from_results"},
700
+ },
701
+ )
702
+ for key in sorted(active)
703
+ ]
704
+
705
+
706
+ def summarize(result: dict[str, Any], metadata: dict[str, Any]) -> dict[str, Any]:
707
+ scored = scored_results(result, metadata)
708
+ n_passed = sum(t["status"] == "passed" for t in scored)
709
+ n_tests = len(scored)
710
+ pass_rate = n_passed / n_tests if n_tests else 0.0
711
+ # Multi-key reward: Harbor's default Mean aggregates each key independently
712
+ # (see harbor.metrics.base.aggregate_reward_dicts), so mean("resolved") is
713
+ # the proportion of tasks scoring a perfect pass-rate and mean of
714
+ # "almost_resolved" is the proportion scoring >= 0.95. "reward" stays the
715
+ # per-task pass-rate whose mean is the overall mean reward.
716
+ return {
717
+ "reward": pass_rate,
718
+ "resolved": 1.0 if pass_rate >= 1.0 else 0.0,
719
+ "almost_resolved": 1.0 if pass_rate >= 0.95 else 0.0,
720
+ }
721
+
722
+
723
+ def diagnostics(result: dict[str, Any], metadata: dict[str, Any]) -> dict[str, Any]:
724
+ scored = scored_results(result, metadata)
725
+ n_passed = sum(t["status"] == "passed" for t in scored)
726
+ n_tests = len(scored)
727
+ pass_rate = n_passed / n_tests if n_tests else 0.0
728
+ return {
729
+ "pass_rate": pass_rate,
730
+ "resolved": int(
731
+ bool(
732
+ n_tests
733
+ and n_passed == n_tests
734
+ and not result["test_branch_errors"]
735
+ and not result["error_code"]
736
+ )
737
+ ),
738
+ "n_passed": n_passed,
739
+ "n_tests": n_tests,
740
+ "n_branch_errors": len(result["test_branch_errors"]),
741
+ "infra_error": int(bool(result["error_code"] or result["test_branch_errors"])),
742
+ "executable_hash_present": int(bool(result.get("executable_hash"))),
743
+ }
744
+
745
+
746
+ def use_script_pty() -> bool:
747
+ return os.environ.get("PROGRAMGYM_SCRIPT_PTY", "").strip() == "1"
748
+
749
+
750
+ def script_pty_available() -> bool:
751
+ return shutil.which("script") is not None
752
+
753
+
754
+ def branch_env(
755
+ *,
756
+ serial: bool,
757
+ has_rerunfailures: bool,
758
+ extras: dict[str, str] | None = None,
759
+ ) -> dict[str, str]:
760
+ addopts = ["--max-worker-restart=4"]
761
+ # A serial fallback is already a complete second execution. Re-running each
762
+ # failing test two more times makes large, failure-heavy suites prohibitively
763
+ # slow and adds little signal.
764
+ if has_rerunfailures and not serial:
765
+ addopts.extend(["--reruns=2", "--reruns-delay=1"])
766
+ env = {
767
+ "PYTEST_ADDOPTS": " ".join(addopts),
768
+ # Match upstream non-TTY regression environments (dirble log format, etc.).
769
+ "NO_COLOR": "1",
770
+ "TERM": "dumb",
771
+ "CLICOLOR": "0",
772
+ "CLICOLOR_FORCE": "0",
773
+ "COLORTERM": "",
774
+ }
775
+ if extras:
776
+ env.update(extras)
777
+ xdist_workers = os.environ.get("PROGRAMGYM_XDIST_WORKERS")
778
+ if serial:
779
+ xdist_workers = "1"
780
+ if xdist_workers:
781
+ env["PYTEST_XDIST_AUTO_NUM_WORKERS"] = xdist_workers
782
+ return env
783
+
784
+
785
+ _SERIAL_RUN_SH = ".programgym_run_serial.sh"
786
+ # ``eval/run.sh`` usually passes ``-n auto`` on the command line, which overrides
787
+ # ``PYTEST_ADDOPTS``. Rewrite to ``-n 0`` in a verifier-local copy for retries.
788
+ _RUN_SH_XDIST_RE = re.compile(r"-n\s*(?:auto|\d+)")
789
+
790
+
791
+ def prepare_serial_run_sh(run_sh: Path) -> Path:
792
+ """Write a serial-only copy of ``eval/run.sh`` with xdist disabled."""
793
+ serial_sh = run_sh.with_name(_SERIAL_RUN_SH)
794
+ patched = _RUN_SH_XDIST_RE.sub("-n 0", run_sh.read_text())
795
+ serial_sh.write_text(patched)
796
+ serial_sh.chmod(0o755)
797
+ return serial_sh
798
+
799
+
800
+ def run_tests_command(*, serial: bool) -> str:
801
+ if serial:
802
+ inner = f"chmod +x ./eval/{_SERIAL_RUN_SH} && ./eval/{_SERIAL_RUN_SH}"
803
+ else:
804
+ inner = "chmod +x ./eval/run.sh && ./eval/run.sh"
805
+ if use_script_pty() and script_pty_available():
806
+ return f"script -q -c {shlex.quote(inner)} /dev/null"
807
+ return inner
808
+
809
+
810
+ BAKED_BLOB_DIR = Path(os.environ.get("PROGRAMGYM_BAKED_BLOB_DIR", "/tests/blobs"))
811
+
812
+
813
+ def resolve_blob_dir(instance_id: str, metadata: dict[str, Any]) -> Path:
814
+ """Locate the per-instance blob directory.
815
+
816
+ Resolution order:
817
+
818
+ 1. ``/tests/blobs/`` if pre-fetched into the task at generation time
819
+ (``programgym-adapter --download-blobs``). Verifier-only mount, so
820
+ agent never sees these.
821
+ 2. ``PROGRAMGYM_BLOB_DIR`` env override pointing at an HF-cache-shaped
822
+ tree on disk (``<dir>/<instance_id>/tests/<branch>.tar.gz``). Useful
823
+ for offline reruns sharing a cache across many tasks.
824
+ 3. ``huggingface_hub.snapshot_download`` from
825
+ ``programgym/ProgramGym-Tests`` (default repo, ``main`` revision).
826
+
827
+ The returned directory contains ``tests/<branch>.tar.gz`` per active
828
+ branch — same shape as ``programgym/ProgramGym-Tests/<instance_id>/``
829
+ on HF.
830
+ """
831
+ if BAKED_BLOB_DIR.exists() and (BAKED_BLOB_DIR / "tests").exists():
832
+ return BAKED_BLOB_DIR
833
+
834
+ local = os.environ.get("PROGRAMGYM_BLOB_DIR", "").strip()
835
+ if local:
836
+ candidate = Path(local) / instance_id
837
+ if candidate.exists():
838
+ return candidate
839
+ raise FileNotFoundError(
840
+ f"PROGRAMGYM_BLOB_DIR set but {candidate} does not exist"
841
+ )
842
+
843
+ repo_id = os.environ.get("PROGRAMGYM_HF_REPO") or metadata.get(
844
+ "hf_repo_id", DEFAULT_HF_REPO_ID
845
+ )
846
+ revision = os.environ.get("PROGRAMGYM_HF_REVISION") or metadata.get(
847
+ "hf_revision", DEFAULT_HF_REVISION
848
+ )
849
+
850
+ from huggingface_hub import snapshot_download
851
+
852
+ cache_root = Path(
853
+ snapshot_download(
854
+ repo_id,
855
+ repo_type="dataset",
856
+ revision=revision,
857
+ allow_patterns=f"{instance_id}/**",
858
+ )
859
+ )
860
+ blob_dir = cache_root / instance_id
861
+ if not blob_dir.exists():
862
+ raise FileNotFoundError(
863
+ f"HF blob directory missing for {instance_id} at {blob_dir}"
864
+ )
865
+ return blob_dir
866
+
867
+
868
+ def evaluate(metadata: dict[str, Any]) -> dict[str, Any]:
869
+ bootstrap_toolchain_path()
870
+ branches = metadata.get("branches", {})
871
+ active_branch_items = [
872
+ (name, info) for name, info in branches.items() if not info.get("ignored")
873
+ ]
874
+ result: dict[str, Any] = {
875
+ "test_results": [],
876
+ "error_code": None,
877
+ "error_details": None,
878
+ "log": [],
879
+ "solution_branch": "submission",
880
+ "test_branches": [name for name, _ in active_branch_items],
881
+ "test_branch_errors": {},
882
+ "executable_hash": None,
883
+ "warnings": [],
884
+ }
885
+
886
+ instance_id = metadata["instance_id"]
887
+
888
+ compile_timeout = int(os.environ.get("PROGRAMGYM_COMPILE_TIMEOUT", "900"))
889
+ branch_timeout = int(os.environ.get("PROGRAMGYM_BRANCH_TIMEOUT", "3600"))
890
+
891
+ def fail_all(error_code: str, details: str) -> dict[str, Any]:
892
+ result["error_code"] = error_code
893
+ result["error_details"] = details
894
+ for branch, info in active_branch_items:
895
+ inject_not_run(result, branch, branch_tests(info), error_code)
896
+ return result
897
+
898
+ with tempfile.TemporaryDirectory(prefix="programgym-eval-") as tmp:
899
+ compiled_snapshot = Path(tmp) / "compiled"
900
+
901
+ started = time.monotonic()
902
+ removed = remove_hashed_files(
903
+ WORKSPACE, set(metadata.get("eval_clean_hashes", []))
904
+ )
905
+ result["log"].append(
906
+ {
907
+ "step": "remove_hashed_files",
908
+ "command": "remove files matching eval_clean_hashes",
909
+ "wall_time": time.monotonic() - started,
910
+ "output": "".join(f"removed '{path}'\n" for path in removed),
911
+ "returncode": 0,
912
+ "exception_info": "",
913
+ }
914
+ )
915
+
916
+ compile_sh = WORKSPACE / "compile.sh"
917
+ if not compile_sh.exists():
918
+ return fail_all(
919
+ "missing_compile_sh", "submission did not contain compile.sh"
920
+ )
921
+
922
+ seed = (
923
+ "if [ ! -d .git ]; then "
924
+ "GIT_AUTHOR_DATE='2000-01-01T00:00:00Z' "
925
+ "GIT_COMMITTER_DATE='2000-01-01T00:00:00Z' "
926
+ "git -c init.defaultBranch=gold init -q && "
927
+ "git -c user.email=gold@local -c user.name=gold -c commit.gpgsign=false add -A && "
928
+ "GIT_AUTHOR_DATE='2000-01-01T00:00:00Z' "
929
+ "GIT_COMMITTER_DATE='2000-01-01T00:00:00Z' "
930
+ "git -c user.email=gold@local -c user.name=gold -c commit.gpgsign=false commit -q --allow-empty -m gold; "
931
+ "fi"
932
+ )
933
+ try:
934
+ result["log"].append(
935
+ run_step(seed, WORKSPACE, timeout=300, step="seed_git")
936
+ )
937
+ compile_log = run_step(
938
+ "chmod +x ./compile.sh && ./compile.sh",
939
+ WORKSPACE,
940
+ timeout=compile_timeout,
941
+ step="compile",
942
+ accept_failure=True,
943
+ )
944
+ result["log"].append(compile_log)
945
+ if compile_log["returncode"]:
946
+ return fail_all("compile_failed", compile_log["output"])
947
+ executable = WORKSPACE / "executable"
948
+ if not executable.exists():
949
+ return fail_all(
950
+ "missing_executable",
951
+ "compile.sh completed but did not create ./executable",
952
+ )
953
+ STASHED_EXECUTABLE.parent.mkdir(parents=True, exist_ok=True)
954
+ # `move` (not copy) so /workspace doesn't keep a parallel copy of
955
+ # the agent's executable during the stash→restore window. Mirrors
956
+ # upstream `mv ./executable {STASHED}` (eval.py:472).
957
+ shutil.move(str(executable), STASHED_EXECUTABLE)
958
+ result["executable_hash"] = sha256(STASHED_EXECUTABLE)
959
+ result["log"].append(
960
+ run_step(
961
+ "pip3 install -q --disable-pip-version-check pytest-rerunfailures",
962
+ WORKSPACE,
963
+ timeout=120,
964
+ step="install_rerunfailures",
965
+ accept_failure=True,
966
+ )
967
+ )
968
+ has_rerunfailures = result["log"][-1]["returncode"] == 0
969
+ handoff_removed = remove_oracle_handoff_artifacts()
970
+ if handoff_removed:
971
+ result["log"].append(
972
+ {
973
+ "step": "remove_oracle_handoff",
974
+ "command": "remove oracle handoff artifacts from workspace",
975
+ "wall_time": 0.0,
976
+ "output": "".join(
977
+ f"removed '{name}'\n" for name in handoff_removed
978
+ ),
979
+ "returncode": 0,
980
+ "exception_info": "",
981
+ }
982
+ )
983
+ snapshot_workspace(compiled_snapshot)
984
+ except Exception as exc:
985
+ return fail_all(type(exc).__name__, str(exc))
986
+
987
+ try:
988
+ blob_dir = resolve_blob_dir(instance_id, metadata)
989
+ except Exception as exc:
990
+ details = f"{type(exc).__name__}: {exc}"
991
+ for branch, info in active_branch_items:
992
+ result["test_branch_errors"][branch] = [
993
+ {
994
+ "error_code": "blob_resolution_failed",
995
+ "error_details": details,
996
+ }
997
+ ]
998
+ inject_not_run(
999
+ result, branch, branch_tests(info), "blob_resolution_failed"
1000
+ )
1001
+ return result
1002
+
1003
+ for branch, info in active_branch_items:
1004
+ tests = branch_tests(info)
1005
+ blob = blob_dir / "tests" / f"{branch}.tar.gz"
1006
+ if not blob.exists():
1007
+ result["test_branch_errors"][branch] = [
1008
+ {"error_code": "missing_test_blob", "error_details": blob.name}
1009
+ ]
1010
+ inject_not_run(result, branch, tests, "missing_test_blob")
1011
+ continue
1012
+
1013
+ best_xml = ""
1014
+ # Prefer a complete, clean XML result, then the result covering the
1015
+ # most expected tests, and only then the one with the most passes.
1016
+ # Pass-count-only ranking can retain a partial xdist result over a
1017
+ # complete serial result.
1018
+ best_quality = (-1, -1, -1)
1019
+ serial = bool(metadata.get("force_serial_branches"))
1020
+ branch_log: list[dict[str, Any]] = []
1021
+ branch_ignored = {
1022
+ item["name"] for item in info.get("ignored_tests", []) if "name" in item
1023
+ }
1024
+ n_expected = len([name for name in tests if name not in branch_ignored])
1025
+
1026
+ def merge_best_xml(raw_xml: str) -> None:
1027
+ try:
1028
+ parsed, warnings = parse_junit(
1029
+ raw_xml, branch, list(info.get("tests", [])), branch_ignored
1030
+ )
1031
+ except Exception as exc:
1032
+ result["test_branch_errors"][branch] = [
1033
+ {"error_code": "xml_parse_error", "error_details": str(exc)}
1034
+ ]
1035
+ inject_not_run(result, branch, tests, "xml_parse_error")
1036
+ else:
1037
+ result["test_results"].extend(parsed)
1038
+ result["warnings"].extend(warnings)
1039
+
1040
+ while True:
1041
+ branch_log.append(cleanup_lingering_processes())
1042
+ restore_workspace(compiled_snapshot)
1043
+ extract_trusted_blob(blob, WORKSPACE)
1044
+ restore_reference_executable()
1045
+ actual_hash = sha256(WORKSPACE / "executable")
1046
+ if actual_hash != result["executable_hash"]:
1047
+ result["test_branch_errors"][branch] = [
1048
+ {
1049
+ "error_code": "executable_hash_mismatch",
1050
+ "error_details": (
1051
+ f"expected {result['executable_hash']}, got {actual_hash}"
1052
+ ),
1053
+ }
1054
+ ]
1055
+ inject_not_run(result, branch, tests, "executable_hash_mismatch")
1056
+ break
1057
+ run_sh = WORKSPACE / "eval" / "run.sh"
1058
+ if not run_sh.exists():
1059
+ result["test_branch_errors"][branch] = [
1060
+ {
1061
+ "error_code": "missing_run_sh",
1062
+ "error_details": "eval/run.sh missing",
1063
+ }
1064
+ ]
1065
+ inject_not_run(result, branch, tests, "missing_run_sh")
1066
+ break
1067
+ # Upstream rewrites thread→signal so xdist workers fail cleanly
1068
+ # instead of os._exit(1) on timeout. That works in fresh
1069
+ # containers per branch; here we reuse one container and
1070
+ # signal timeouts leave TUI/log-watcher subprocesses alive
1071
+ # (e.g. lazygit --logs + tail -f), wedging pytest for up to
1072
+ # branch_timeout. Keep the blob's thread method and rely on
1073
+ # cleanup_lingering_processes + serial fallback after crashes.
1074
+ env = branch_env(
1075
+ serial=serial,
1076
+ has_rerunfailures=has_rerunfailures,
1077
+ extras=metadata.get("branch_env"),
1078
+ )
1079
+ branch_log.append(
1080
+ run_step(
1081
+ "rm -f eval/results.xml results.xml",
1082
+ WORKSPACE,
1083
+ timeout=120,
1084
+ step="clean_stale_results",
1085
+ accept_failure=True,
1086
+ )
1087
+ )
1088
+ if serial:
1089
+ prepare_serial_run_sh(run_sh)
1090
+ run_entry = run_step(
1091
+ run_tests_command(serial=serial),
1092
+ WORKSPACE,
1093
+ timeout=branch_timeout,
1094
+ env=env,
1095
+ step="run_tests",
1096
+ accept_failure=True,
1097
+ )
1098
+ branch_log.append(run_entry)
1099
+ branch_log.append(cleanup_lingering_processes())
1100
+ xml_path = find_results_xml()
1101
+ if xml_path is None:
1102
+ if best_xml:
1103
+ merge_best_xml(best_xml)
1104
+ break
1105
+ if serial:
1106
+ result["test_branch_errors"][branch] = [
1107
+ {
1108
+ "error_code": "missing_results_xml",
1109
+ "error_details": "eval/results.xml was not produced",
1110
+ }
1111
+ ]
1112
+ inject_not_run(result, branch, tests, "missing_results_xml")
1113
+ break
1114
+ serial = True
1115
+ continue
1116
+ raw_xml = xml_path.read_text(errors="replace")
1117
+ crashes, n_tests, failures, missing = branch_attempt_metrics(
1118
+ raw_xml,
1119
+ run_output=run_entry.get("output", ""),
1120
+ expected_tests=n_expected,
1121
+ )
1122
+ useful = count_junit_passed(raw_xml)
1123
+ quality = (
1124
+ int(crashes == 0 and missing == 0),
1125
+ n_tests,
1126
+ useful,
1127
+ )
1128
+ if quality > best_quality:
1129
+ best_xml = raw_xml
1130
+ best_quality = quality
1131
+ retry = needs_serial_retry(
1132
+ serial=serial,
1133
+ crashes=crashes,
1134
+ missing=missing,
1135
+ failures=failures,
1136
+ n_tests=n_tests,
1137
+ expected_tests=n_expected,
1138
+ run_output=run_entry.get("output", ""),
1139
+ )
1140
+ if not retry:
1141
+ merge_best_xml(best_xml)
1142
+ break
1143
+ serial = True
1144
+ for entry in branch_log:
1145
+ entry["branch"] = branch
1146
+ result["log"].extend(branch_log)
1147
+
1148
+ return result
1149
+
1150
+
1151
+ def write_outputs(result: dict[str, Any], metadata: dict[str, Any]) -> None:
1152
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
1153
+ write_json(LOG_DIR / "programgym_eval.json", result)
1154
+ write_json(LOG_DIR / "harbor_diagnostics.json", diagnostics(result, metadata))
1155
+ rewards = summarize(result, metadata)
1156
+ write_json(LOG_DIR / "reward.json", rewards)
1157
+ (LOG_DIR / "reward.txt").write_text(str(rewards["reward"]))
1158
+
1159
+
1160
+ def main() -> None:
1161
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
1162
+ log_path = LOG_DIR / "programgym_eval.log"
1163
+ metadata = json.loads(METADATA_PATH.read_text())
1164
+ branches = metadata.get("branches", {})
1165
+ try:
1166
+ result = evaluate(metadata)
1167
+ except Exception as exc:
1168
+ error_code = type(exc).__name__
1169
+ result = {
1170
+ "test_results": [],
1171
+ "error_code": error_code,
1172
+ "error_details": str(exc),
1173
+ "log": [
1174
+ {
1175
+ "step": "evaluator_exception",
1176
+ "exception_info": traceback.format_exc(),
1177
+ "returncode": 1,
1178
+ }
1179
+ ],
1180
+ "solution_branch": "submission",
1181
+ "test_branches": [
1182
+ name for name, info in branches.items() if not info.get("ignored")
1183
+ ],
1184
+ "test_branch_errors": {
1185
+ "__evaluator__": [{"error_code": error_code, "error_details": str(exc)}]
1186
+ },
1187
+ "executable_hash": None,
1188
+ "warnings": [],
1189
+ }
1190
+ for branch, info in branches.items():
1191
+ if info.get("ignored"):
1192
+ continue
1193
+ inject_not_run(result, branch, branch_tests(info), error_code)
1194
+ log_path.write_text(traceback.format_exc())
1195
+ else:
1196
+ log_path.write_text("")
1197
+ write_outputs(result, metadata)
1198
+
1199
+
1200
+ if __name__ == "__main__":
1201
+ main()
mpolden--echoip.746db5e/tests/programgym_task.json ADDED
@@ -0,0 +1,552 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "branches": {
3
+ "generated_module_01": {
4
+ "ignore_reason": "",
5
+ "ignored": false,
6
+ "ignored_tests": [],
7
+ "tests": [
8
+ "eval.tests.test_cli.test_cli_matcher_user_agents_return_plain_ip[Go-http-client/1.1]",
9
+ "eval.tests.test_cli.test_cli_matcher_user_agents_return_plain_ip[HTTPie/0.9.3]",
10
+ "eval.tests.test_cli.test_cli_matcher_user_agents_return_plain_ip[Mikrotik/6.x Fetch]",
11
+ "eval.tests.test_cli.test_cli_matcher_user_agents_return_plain_ip[Wget/1.13.4 (linux-gnu)]",
12
+ "eval.tests.test_cli.test_cli_matcher_user_agents_return_plain_ip[Wget]",
13
+ "eval.tests.test_cli.test_cli_matcher_user_agents_return_plain_ip[curl/7.43.0]",
14
+ "eval.tests.test_cli.test_cli_matcher_user_agents_return_plain_ip[ddclient/3.8.3]",
15
+ "eval.tests.test_cli.test_cli_matcher_user_agents_return_plain_ip[fetch libfetch/2.0]",
16
+ "eval.tests.test_cli.test_cli_matcher_user_agents_return_plain_ip[httpie-go/0.6.0]",
17
+ "eval.tests.test_cli.test_cli_matcher_user_agents_return_plain_ip[xh 0.16.0]",
18
+ "eval.tests.test_cli.test_ip_empty_query_falls_back_to_peer",
19
+ "eval.tests.test_cli.test_ip_endpoint_ignores_accept_json",
20
+ "eval.tests.test_cli.test_ip_endpoint_returns_remote_ip",
21
+ "eval.tests.test_cli.test_ip_invalid_query_parameter_returns_bad_request",
22
+ "eval.tests.test_cli.test_ip_query_hostport_non_numeric_port_keeps_host",
23
+ "eval.tests.test_cli.test_ip_query_ipv6_expanded_compressed",
24
+ "eval.tests.test_cli.test_ip_query_parameter_ipv6",
25
+ "eval.tests.test_cli.test_ip_query_parameter_returns_lookup",
26
+ "eval.tests.test_cli.test_ip_query_parameter_strips_port",
27
+ "eval.tests.test_cli.test_ip_query_too_many_colons_bad_request",
28
+ "eval.tests.test_cli.test_root_accept_text_plain_returns_plain_ip",
29
+ "eval.tests.test_cli.test_root_curl_accept_json_favours_json",
30
+ "eval.tests.test_cli.test_root_curl_user_agent_returns_plain_ip",
31
+ "eval.tests.test_cli_exit.test_help_flag_prints_usage",
32
+ "eval.tests.test_cli_exit.test_listen_on_busy_port_fails",
33
+ "eval.tests.test_cli_exit.test_long_help_flag_prints_usage",
34
+ "eval.tests.test_cli_exit.test_missing_geo_db_fails_startup",
35
+ "eval.tests.test_cli_exit.test_positional_argument_prints_usage",
36
+ "eval.tests.test_cli_exit.test_undefined_flag_rejected",
37
+ "eval.tests.test_error_handling.test_bad_request_json_even_without_accept",
38
+ "eval.tests.test_error_handling.test_bad_request_json_with_accept",
39
+ "eval.tests.test_error_handling.test_internal_error_from_bad_template",
40
+ "eval.tests.test_error_handling.test_json_404_message",
41
+ "eval.tests.test_error_handling.test_plain_404_message",
42
+ "eval.tests.test_ip_detection.test_json_reflects_trusted_header_ip",
43
+ "eval.tests.test_ip_detection.test_missing_trusted_header_falls_back_to_peer",
44
+ "eval.tests.test_ip_detection.test_multiple_trusted_headers_first_present_wins",
45
+ "eval.tests.test_ip_detection.test_multiple_trusted_headers_skips_empty_first",
46
+ "eval.tests.test_ip_detection.test_non_xff_header_bracketed_ipv6_preserved",
47
+ "eval.tests.test_ip_detection.test_query_bracketed_ipv6_with_port",
48
+ "eval.tests.test_ip_detection.test_query_ip_wins_over_trusted_header",
49
+ "eval.tests.test_ip_detection.test_query_port_only_empty_host_rejected",
50
+ "eval.tests.test_ip_detection.test_trusted_header_empty_falls_back_to_peer",
51
+ "eval.tests.test_ip_detection.test_trusted_header_strips_port",
52
+ "eval.tests.test_ip_detection.test_trusted_x_real_ip_is_used",
53
+ "eval.tests.test_ip_detection.test_trusted_xff_empty_first_entry_falls_back",
54
+ "eval.tests.test_ip_detection.test_trusted_xff_ipv6_first_entry",
55
+ "eval.tests.test_ip_detection.test_trusted_xff_lowercase_config_splits",
56
+ "eval.tests.test_ip_detection.test_trusted_xff_multi_value_uses_first",
57
+ "eval.tests.test_ip_detection.test_trusted_xff_multi_value_with_spaces",
58
+ "eval.tests.test_ip_detection.test_trusted_xff_second_entry_used_when_first_empty",
59
+ "eval.tests.test_ip_detection.test_trusted_xff_single_value",
60
+ "eval.tests.test_ip_detection.test_untrusted_x_real_ip_is_ignored",
61
+ "eval.tests.test_ip_detection.test_xff_all_empty_commas_falls_back",
62
+ "eval.tests.test_ip_detection.test_xff_leading_whitespace_trimmed",
63
+ "eval.tests.test_json.test_cache_hit_reparses_user_agent",
64
+ "eval.tests.test_json.test_json_browser_user_agent_parsed",
65
+ "eval.tests.test_json.test_json_endpoint_content_type",
66
+ "eval.tests.test_json.test_json_includes_user_agent_for_curl",
67
+ "eval.tests.test_json.test_json_omits_user_agent_when_absent",
68
+ "eval.tests.test_json.test_json_omits_zero_geo_fields",
69
+ "eval.tests.test_json.test_json_query_ipv4_decimal",
70
+ "eval.tests.test_json.test_json_query_ipv6_decimal",
71
+ "eval.tests.test_json.test_json_query_multiple_ip_params_first_wins",
72
+ "eval.tests.test_json.test_json_query_zero_ipv4_decimal",
73
+ "eval.tests.test_json.test_json_returns_basic_response_fields",
74
+ "eval.tests.test_json.test_root_with_accept_json_returns_same_response",
75
+ "eval.tests.test_port.test_port_disabled_by_default",
76
+ "eval.tests.test_port.test_port_invalid_query_ip_is_ignored",
77
+ "eval.tests.test_port.test_port_max_boundary_valid",
78
+ "eval.tests.test_port.test_port_min_boundary_valid",
79
+ "eval.tests.test_port.test_port_negative_rejected",
80
+ "eval.tests.test_port.test_port_non_numeric_rejected",
81
+ "eval.tests.test_port.test_port_over_range_rejected",
82
+ "eval.tests.test_port.test_port_prefix_matches_nested_path",
83
+ "eval.tests.test_port.test_port_query_ip_is_ignored",
84
+ "eval.tests.test_port.test_port_reachable_when_server_listening",
85
+ "eval.tests.test_port.test_port_trailing_slash_still_parses_port",
86
+ "eval.tests.test_port.test_port_valid_endpoint_shape",
87
+ "eval.tests.test_port.test_port_zero_rejected",
88
+ "eval.tests.test_profile.test_cache_capacity_via_C_flag_sets_capacity",
89
+ "eval.tests.test_profile.test_cache_disabled_at_default_capacity_zero",
90
+ "eval.tests.test_profile.test_cache_eviction_when_exceeding_capacity",
91
+ "eval.tests.test_profile.test_cache_no_eviction_within_capacity",
92
+ "eval.tests.test_profile.test_cache_resize_empty_body_rejected",
93
+ "eval.tests.test_profile.test_cache_resize_float_rejected",
94
+ "eval.tests.test_profile.test_cache_resize_negative_rejected",
95
+ "eval.tests.test_profile.test_cache_resize_non_numeric_rejected",
96
+ "eval.tests.test_profile.test_cache_resize_reflected_in_stats",
97
+ "eval.tests.test_profile.test_cache_resize_requires_post",
98
+ "eval.tests.test_profile.test_cache_resize_valid_capacity",
99
+ "eval.tests.test_profile.test_cache_resize_zero",
100
+ "eval.tests.test_profile.test_debug_cache_stats_initial",
101
+ "eval.tests.test_profile.test_pprof_cmdline_available",
102
+ "eval.tests.test_profile.test_pprof_goroutine_index_route",
103
+ "eval.tests.test_profile.test_pprof_index_available",
104
+ "eval.tests.test_profile.test_pprof_symbol_available",
105
+ "eval.tests.test_profile.test_server_without_profile_hides_debug_cache",
106
+ "eval.tests.test_router.test_delete_health_method_mismatch",
107
+ "eval.tests.test_router.test_head_health_is_method_mismatch",
108
+ "eval.tests.test_router.test_head_ip_method_mismatch_empty",
109
+ "eval.tests.test_router.test_head_root_returns_no_content",
110
+ "eval.tests.test_router.test_health_returns_ok",
111
+ "eval.tests.test_router.test_post_json_is_not_found_by_method",
112
+ "eval.tests.test_router.test_put_health_method_mismatch",
113
+ "eval.tests.test_router.test_query_string_does_not_break_root_404",
114
+ "eval.tests.test_router.test_root_head_with_accept_json_is_no_content",
115
+ "eval.tests.test_router.test_root_with_browser_ua_is_404_without_template",
116
+ "eval.tests.test_router.test_root_without_accept_or_cli_ua_is_404",
117
+ "eval.tests.test_router.test_trailing_slash_ip_path_404",
118
+ "eval.tests.test_router.test_unknown_path_plain_404",
119
+ "eval.tests.test_router.test_unsupported_method_verb_404[DELETE-/health]",
120
+ "eval.tests.test_router.test_unsupported_method_verb_404[DELETE-/json]",
121
+ "eval.tests.test_router.test_unsupported_method_verb_404[OPTIONS-/ip]",
122
+ "eval.tests.test_router.test_unsupported_method_verb_404[OPTIONS-/json]",
123
+ "eval.tests.test_router.test_unsupported_method_verb_404[PATCH-/health]",
124
+ "eval.tests.test_router.test_unsupported_method_verb_404[PUT-/ip]",
125
+ "eval.tests.test_router.test_unsupported_method_verb_404[PUT-/json]",
126
+ "eval.tests.test_template.test_browser_page_does_not_echo_query_ip_as_request",
127
+ "eval.tests.test_template.test_browser_page_explicit_lookup_revealed",
128
+ "eval.tests.test_template.test_browser_page_includes_embedded_json",
129
+ "eval.tests.test_template.test_browser_page_renders_box_coordinates",
130
+ "eval.tests.test_template.test_browser_page_renders_host_and_ip",
131
+ "eval.tests.test_template.test_browser_template_execute_failure_prefixes_internal_error",
132
+ "eval.tests.test_template.test_nonexistent_template_dir_disables_default_handler",
133
+ "eval.tests.test_template.test_port_flag_rendered_in_template",
134
+ "eval.tests.test_template.test_sponsor_flag_rendered_in_template"
135
+ ]
136
+ },
137
+ "generated_module_02": {
138
+ "ignore_reason": "",
139
+ "ignored": false,
140
+ "ignored_tests": [],
141
+ "tests": [
142
+ "eval.tests.test_cache.test_cache_hit_returns_same_ip_but_refreshes_user_agent",
143
+ "eval.tests.test_cache.test_cache_stats_evictions_monotonic_with_more_adds",
144
+ "eval.tests.test_cache.test_cache_stats_json_fields",
145
+ "eval.tests.test_cache.test_cache_store_and_hit_consistent_ip_decimal",
146
+ "eval.tests.test_cache.test_disabled_cache_never_grows[1]",
147
+ "eval.tests.test_cache.test_disabled_cache_never_grows[3]",
148
+ "eval.tests.test_cache.test_disabled_cache_never_grows[5]",
149
+ "eval.tests.test_cache.test_disabled_cache_reports_zero_without_profile_flag",
150
+ "eval.tests.test_cache.test_distinct_ips_are_distinct_entries[198.51.100.1-203.0.113.1]",
151
+ "eval.tests.test_cache.test_distinct_ips_are_distinct_entries[2001:db8::1-2001:db8::2]",
152
+ "eval.tests.test_cache.test_distinct_ips_are_distinct_entries[203.0.113.10-203.0.113.20]",
153
+ "eval.tests.test_cache.test_duplicate_set_at_single_slot_capacity",
154
+ "eval.tests.test_cache.test_duplicate_set_same_ip_single_entry[2]",
155
+ "eval.tests.test_cache.test_duplicate_set_same_ip_single_entry[3]",
156
+ "eval.tests.test_cache.test_duplicate_set_same_ip_single_entry[5]",
157
+ "eval.tests.test_cache.test_fill_within_capacity_no_eviction[10-7-7-0]",
158
+ "eval.tests.test_cache.test_fill_within_capacity_no_eviction[5-1-1-0]",
159
+ "eval.tests.test_cache.test_fill_within_capacity_no_eviction[5-3-3-0]",
160
+ "eval.tests.test_cache.test_fill_within_capacity_no_eviction[5-5-5-0]",
161
+ "eval.tests.test_cache.test_hit_reports_latest_user_agent_per_request[Mozilla/5.0 (X11) Chrome/120.0-Mozilla]",
162
+ "eval.tests.test_cache.test_hit_reports_latest_user_agent_per_request[Wget/1.21-Wget]",
163
+ "eval.tests.test_cache.test_hit_reports_latest_user_agent_per_request[curl/8.1.2-curl]",
164
+ "eval.tests.test_cache.test_ipv6_client_cached[2001:4860:4860::8888]",
165
+ "eval.tests.test_cache.test_ipv6_client_cached[2606:4700:4700::1111]",
166
+ "eval.tests.test_cache.test_json_and_root_share_cache[/]",
167
+ "eval.tests.test_cache.test_json_and_root_share_cache[/json]",
168
+ "eval.tests.test_cache.test_lru_eviction_over_capacity[1-2-1-1]",
169
+ "eval.tests.test_cache.test_lru_eviction_over_capacity[2-6-2-4]",
170
+ "eval.tests.test_cache.test_lru_eviction_over_capacity[3-4-3-1]",
171
+ "eval.tests.test_cache.test_lru_eviction_over_capacity[3-5-3-2]",
172
+ "eval.tests.test_cache.test_lru_evicts_oldest_keeps_newest[3-0-5-True]",
173
+ "eval.tests.test_cache.test_lru_evicts_oldest_keeps_newest[3-0-6-True]",
174
+ "eval.tests.test_cache.test_nonnested_recent_ips_present_after_eviction[3-5-203.0.113.3]",
175
+ "eval.tests.test_cache.test_nonnested_recent_ips_present_after_eviction[3-5-203.0.113.4]",
176
+ "eval.tests.test_cache.test_plain_cli_endpoint_bypasses_cache",
177
+ "eval.tests.test_cache.test_repeated_json_requests_single_cache_entry",
178
+ "eval.tests.test_cache.test_resize_does_not_accept_negative_eviction_reset_only_on_success",
179
+ "eval.tests.test_cache.test_resize_malformed_body_rejected[ 5 ]",
180
+ "eval.tests.test_cache.test_resize_malformed_body_rejected[1e3]",
181
+ "eval.tests.test_cache.test_resize_malformed_body_rejected[5.5]",
182
+ "eval.tests.test_cache.test_resize_malformed_body_rejected[]",
183
+ "eval.tests.test_cache.test_resize_malformed_body_rejected[abc]",
184
+ "eval.tests.test_cache.test_resize_negative_capacity_rejected[-1-invalid capacity:]",
185
+ "eval.tests.test_cache.test_resize_negative_capacity_rejected[-5-invalid capacity:]",
186
+ "eval.tests.test_cache.test_resize_reports_new_capacity_message[1]",
187
+ "eval.tests.test_cache.test_resize_reports_new_capacity_message[50]",
188
+ "eval.tests.test_cache.test_resize_reports_new_capacity_message[5]",
189
+ "eval.tests.test_cache.test_resize_then_fill_reflects_new_capacity[3-5-4-4]",
190
+ "eval.tests.test_cache.test_resize_then_fill_reflects_new_capacity[5-2-2-2]",
191
+ "eval.tests.test_cache.test_resize_to_zero_disables_new_sets_keeps_entries[0]",
192
+ "eval.tests.test_cache.test_resize_up_keeps_entries_and_resets_evictions",
193
+ "eval.tests.test_cache_deep.test_cache_hit_does_not_promote_lru_recency",
194
+ "eval.tests.test_cache_deep.test_capacity_one_evicts_every_prior_entry[10-9]",
195
+ "eval.tests.test_cache_deep.test_capacity_one_evicts_every_prior_entry[3-2]",
196
+ "eval.tests.test_cache_deep.test_capacity_one_evicts_every_prior_entry[6-5]",
197
+ "eval.tests.test_cache_deep.test_evicted_entry_rerequest_reinserts_and_counts_eviction",
198
+ "eval.tests.test_cache_deep.test_first_request_misses_then_hits_single_entry",
199
+ "eval.tests.test_cache_deep.test_ip_decimal_stable_across_eviction_reinsert_cycles",
200
+ "eval.tests.test_cache_deep.test_mixed_v4_v6_share_lru_eviction[ips0-3-0]",
201
+ "eval.tests.test_cache_deep.test_mixed_v4_v6_share_lru_eviction[ips1-3-2]",
202
+ "eval.tests.test_cache_deep.test_mixed_v4_v6_share_lru_eviction[ips2-2-3]",
203
+ "eval.tests.test_cache_deep.test_resize_down_evicts_multiple_entries_in_single_set",
204
+ "eval.tests.test_cache_deep.test_resized_entries_readable_until_next_set_evicts",
205
+ "eval.tests.test_cache_lru_semantics.test_lru_victim_is_oldest_of_current_residents[3-sequence0-expected_victims0]",
206
+ "eval.tests.test_cache_lru_semantics.test_lru_victim_is_oldest_of_current_residents[3-sequence1-expected_victims1]",
207
+ "eval.tests.test_cache_lru_semantics.test_lru_victim_is_oldest_of_current_residents[3-sequence2-expected_victims2]",
208
+ "eval.tests.test_cache_lru_semantics.test_reenable_cache_after_resize_to_zero",
209
+ "eval.tests.test_cache_lru_semantics.test_rehit_present_ip_no_eviction_growth[2]",
210
+ "eval.tests.test_cache_lru_semantics.test_rehit_present_ip_no_eviction_growth[3]",
211
+ "eval.tests.test_cache_lru_semantics.test_rehit_present_ip_no_eviction_growth[6]",
212
+ "eval.tests.test_cache_lru_semantics.test_reinsert_moves_entry_to_most_recent_eviction_order",
213
+ "eval.tests.test_cache_lru_semantics.test_resize_down_then_up_preserves_entries_resets_evictions",
214
+ "eval.tests.test_cache_lru_semantics.test_resize_same_capacity_resets_evictions_keeps_entries",
215
+ "eval.tests.test_cache_round5.test_cache_stats_endpoint_rejects_post_method",
216
+ "eval.tests.test_cache_round5.test_default_capacity_zero_with_profiling_only",
217
+ "eval.tests.test_cache_round5.test_lru_order_preserved_across_resize_grow_specific_victim",
218
+ "eval.tests.test_cache_round5.test_resize_endpoint_rejects_non_post_method",
219
+ "eval.tests.test_cache_round5.test_resize_huge_positive_capacity_accepted",
220
+ "eval.tests.test_cache_round5.test_resize_integer_overflow_body_rejected",
221
+ "eval.tests.test_cache_round5.test_resize_positive_sign_body_accepted",
222
+ "eval.tests.test_cli.test_cache_size_flag_argument_errors[-flag needs an argument: -C]",
223
+ "eval.tests.test_cli.test_cache_size_flag_argument_errors[abc-invalid value \"abc\" for flag -C: parse error]",
224
+ "eval.tests.test_cli.test_failing_listener_runs_cache_startup_and_exits",
225
+ "eval.tests.test_cli.test_help_flag_usage_exit_zero[--help]",
226
+ "eval.tests.test_cli.test_help_flag_usage_exit_zero[-h]",
227
+ "eval.tests.test_cli.test_large_capacity_startup_logs_exact_value",
228
+ "eval.tests.test_cli.test_negative_capacity_clamps_without_capacity_log",
229
+ "eval.tests.test_cli.test_positional_arg_prints_usage_exit_zero",
230
+ "eval.tests.test_cli.test_unknown_flag_rejected",
231
+ "eval.tests.test_cli.test_zero_capacity_startup_emits_no_capacity_log"
232
+ ]
233
+ },
234
+ "generated_module_03": {
235
+ "ignore_reason": "",
236
+ "ignored": false,
237
+ "ignored_tests": [],
238
+ "tests": [
239
+ "eval.tests.test_args.test_bad_listen_address_exits_one",
240
+ "eval.tests.test_args.test_cache_capacity_accepted",
241
+ "eval.tests.test_args.test_help_flag_exits_zero_and_lists_flags",
242
+ "eval.tests.test_args.test_missing_flag_value_exits_two",
243
+ "eval.tests.test_args.test_port_flag_leaves_server_up",
244
+ "eval.tests.test_args.test_positional_arg_prints_usage_exit_zero",
245
+ "eval.tests.test_args.test_reverse_flag_leaves_server_up",
246
+ "eval.tests.test_args.test_short_help_flag_exits_zero",
247
+ "eval.tests.test_args.test_sponsor_flag_accepted",
248
+ "eval.tests.test_args.test_unknown_flag_exits_two",
249
+ "eval.tests.test_geo.test_country_eu_present_even_empty",
250
+ "eval.tests.test_geo.test_geo_empty_fields_absent_in_json",
251
+ "eval.tests.test_geo.test_geo_endpoints_not_registered_without_db",
252
+ "eval.tests.test_geo.test_geo_open_asn_and_city_missing_first",
253
+ "eval.tests.test_geo.test_geo_open_directory_db_error",
254
+ "eval.tests.test_geo.test_geo_open_empty_paths_ok_and_serves",
255
+ "eval.tests.test_geo.test_geo_open_invalid_db_file_error",
256
+ "eval.tests.test_geo.test_geo_open_nonexistent_asn_db_exit_code",
257
+ "eval.tests.test_geo.test_geo_open_nonexistent_city_db_exit_code",
258
+ "eval.tests.test_geo.test_geo_open_nonexistent_db_exit_code",
259
+ "eval.tests.test_geo_populated.test_full_geo_json_all_fields",
260
+ "eval.tests.test_geo_populated.test_geo_asn_number_only_no_org",
261
+ "eval.tests.test_geo_populated.test_geo_asn_org_only_no_number",
262
+ "eval.tests.test_geo_populated.test_geo_cli_subroute_outputs",
263
+ "eval.tests.test_geo_populated.test_geo_coordinates_formatting",
264
+ "eval.tests.test_geo_populated.test_geo_country_eu_false_zero_value",
265
+ "eval.tests.test_geo_populated.test_geo_country_name_without_iso",
266
+ "eval.tests.test_geo_populated.test_geo_eu_flag_true",
267
+ "eval.tests.test_geo_populated.test_geo_ip_not_in_db_empty_record",
268
+ "eval.tests.test_geo_populated.test_geo_isempty_false_for_country_only",
269
+ "eval.tests.test_geo_populated.test_geo_isempty_true_for_asn_only",
270
+ "eval.tests.test_geo_populated.test_geo_lookup_via_trusted_header",
271
+ "eval.tests.test_geo_populated.test_geo_lookup_via_xff_header",
272
+ "eval.tests.test_geo_populated.test_geo_mixed_country_nonus_city_asn",
273
+ "eval.tests.test_geo_populated.test_geo_non_us_metro_suppressed",
274
+ "eval.tests.test_geo_populated.test_geo_open_all_three_dbs_out_of_order",
275
+ "eval.tests.test_geo_populated.test_geo_partial_city_minimal",
276
+ "eval.tests.test_geo_populated.test_geo_registered_country_fallback",
277
+ "eval.tests.test_geo_populated.test_geo_subroute_unmatched_ip_empty_line",
278
+ "eval.tests.test_http_routes.test_browser_root_404_without_template",
279
+ "eval.tests.test_http_routes.test_browser_root_renders_template",
280
+ "eval.tests.test_http_routes.test_cli_ip_route_plain_remote",
281
+ "eval.tests.test_http_routes.test_forwarded_for_leading_space_trimmed",
282
+ "eval.tests.test_http_routes.test_forwarded_for_single_value",
283
+ "eval.tests.test_http_routes.test_forwarded_for_takes_first_hop",
284
+ "eval.tests.test_http_routes.test_head_root_no_content",
285
+ "eval.tests.test_http_routes.test_health_ok",
286
+ "eval.tests.test_http_routes.test_json_bare_uses_remote_loopback_ip",
287
+ "eval.tests.test_http_routes.test_json_route_echoes_ip",
288
+ "eval.tests.test_http_routes.test_pprof_not_registered_without_profiling",
289
+ "eval.tests.test_http_routes.test_profiling_flag_registers_pprof",
290
+ "eval.tests.test_http_routes.test_root_accept_text_plain_cli",
291
+ "eval.tests.test_http_routes.test_root_browser_user_agent_404_without_template",
292
+ "eval.tests.test_http_routes.test_root_curl_user_agent_returns_cli_plain_ip",
293
+ "eval.tests.test_http_routes.test_template_missing_logs_but_starts",
294
+ "eval.tests.test_http_routes.test_trusted_header_comma_value_not_split_400",
295
+ "eval.tests.test_http_routes.test_trusted_header_decimal_computed",
296
+ "eval.tests.test_http_routes.test_trusted_header_drives_reverse_lookup",
297
+ "eval.tests.test_http_routes.test_trusted_header_garbage_with_port_split",
298
+ "eval.tests.test_http_routes.test_trusted_header_invalid_ip_rejected",
299
+ "eval.tests.test_http_routes.test_trusted_header_ip_used",
300
+ "eval.tests.test_http_routes.test_trusted_header_missing_falls_back_to_remote",
301
+ "eval.tests.test_http_routes.test_trusted_header_query_param_wins",
302
+ "eval.tests.test_http_routes.test_two_trusted_headers_use_first_nonempty",
303
+ "eval.tests.test_http_routes.test_untrusted_header_ignored",
304
+ "eval.tests.test_http_routes.test_user_agent_field_parsed",
305
+ "eval.tests.test_http_routes.test_user_agent_not_cached_same_ip_diff_ua",
306
+ "eval.tests.test_ipdecimal.test_blank_ip_query_falls_back_to_remote",
307
+ "eval.tests.test_ipdecimal.test_custom_ip_query_overrides_remote",
308
+ "eval.tests.test_ipdecimal.test_decimal_is_big_integer_string",
309
+ "eval.tests.test_ipdecimal.test_invalid_ip_query_rejected",
310
+ "eval.tests.test_ipdecimal.test_invalid_ipv4_octet_rejected",
311
+ "eval.tests.test_ipdecimal.test_ip_field_canonical_ipv6_compression",
312
+ "eval.tests.test_ipdecimal.test_ipv4_boundary_min_max",
313
+ "eval.tests.test_ipdecimal.test_ipv4_decimal_conversion",
314
+ "eval.tests.test_ipdecimal.test_ipv4_mapped_ipv6_canonical_form",
315
+ "eval.tests.test_ipdecimal.test_ipv4_mapped_ipv6_is_32_bit",
316
+ "eval.tests.test_ipdecimal.test_ipv4_mapped_private_range",
317
+ "eval.tests.test_ipdecimal.test_ipv6_decimal_conversion",
318
+ "eval.tests.test_ipdecimal.test_ipv6_loopback_and_max",
319
+ "eval.tests.test_ipdecimal.test_ipv6_loopback_query_decimal",
320
+ "eval.tests.test_ipdecimal.test_ipv6_query_url_encoded_colons",
321
+ "eval.tests.test_ipdecimal.test_leading_zero_ipv4_rejected",
322
+ "eval.tests.test_ipdecimal.test_multi_value_ip_query_uses_first",
323
+ "eval.tests.test_reverse_port.test_hostname_is_unrooted",
324
+ "eval.tests.test_reverse_port.test_no_hostname_without_reverse_flag",
325
+ "eval.tests.test_reverse_port.test_port_closed_not_reachable",
326
+ "eval.tests.test_reverse_port.test_port_empty_segment_rejected",
327
+ "eval.tests.test_reverse_port.test_port_invalid_ip_query_ignored",
328
+ "eval.tests.test_reverse_port.test_port_invalid_non_numeric",
329
+ "eval.tests.test_reverse_port.test_port_invalid_too_large",
330
+ "eval.tests.test_reverse_port.test_port_ipv6_query_ignored_remote_used",
331
+ "eval.tests.test_reverse_port.test_port_leading_zero_accepted",
332
+ "eval.tests.test_reverse_port.test_port_lookup_disabled_without_flag",
333
+ "eval.tests.test_reverse_port.test_port_open_reachable",
334
+ "eval.tests.test_reverse_port.test_port_query_ip_param_ignored",
335
+ "eval.tests.test_reverse_port.test_port_upper_boundary_accepted",
336
+ "eval.tests.test_reverse_port.test_port_zero_rejected",
337
+ "eval.tests.test_reverse_port.test_reverse_lookup_hostname_field",
338
+ "eval.tests.test_reverse_port.test_reverse_lookup_ipv6_loopback",
339
+ "eval.tests.test_reverse_port.test_reverse_lookup_ipv6_other_loopback_no_hostname",
340
+ "eval.tests.test_reverse_port.test_reverse_lookup_unresolvable_no_hostname"
341
+ ]
342
+ },
343
+ "generated_module_04": {
344
+ "ignore_reason": "",
345
+ "ignored": false,
346
+ "ignored_tests": [],
347
+ "tests": [
348
+ "eval.tests.test_cache_debug.test_cache_resize_decimal_rejected",
349
+ "eval.tests.test_cache_debug.test_cache_resize_empty_body_rejected",
350
+ "eval.tests.test_cache_debug.test_cache_resize_negative_rejected",
351
+ "eval.tests.test_cache_debug.test_cache_resize_non_numeric_rejected",
352
+ "eval.tests.test_cache_debug.test_cache_resize_success",
353
+ "eval.tests.test_cache_debug.test_cache_resize_to_large_value",
354
+ "eval.tests.test_cache_debug.test_cache_resize_to_zero",
355
+ "eval.tests.test_cache_debug.test_cache_stats_initial_capacity",
356
+ "eval.tests.test_cache_debug.test_pprof_cmdline_reachable",
357
+ "eval.tests.test_cache_debug.test_pprof_index_reachable",
358
+ "eval.tests.test_cache_debug.test_profile_routes_absent_without_profile_flag",
359
+ "eval.tests.test_cli_flags.test_all_flag_logs_together",
360
+ "eval.tests.test_cli_flags.test_baseline_does_not_log_feature_lines",
361
+ "eval.tests.test_cli_flags.test_boolean_flag_needs_no_value",
362
+ "eval.tests.test_cli_flags.test_cache_capacity_log[100]",
363
+ "eval.tests.test_cli_flags.test_cache_capacity_log[10]",
364
+ "eval.tests.test_cli_flags.test_cache_capacity_log[1]",
365
+ "eval.tests.test_cli_flags.test_double_dash_help_prints_usage",
366
+ "eval.tests.test_cli_flags.test_extra_positional_argument_triggers_usage",
367
+ "eval.tests.test_cli_flags.test_help_flag_exits_zero_and_prints_usage",
368
+ "eval.tests.test_cli_flags.test_int_flag_without_value_reports_error",
369
+ "eval.tests.test_cli_flags.test_listen_address_uses_l_flag",
370
+ "eval.tests.test_cli_flags.test_missing_geoip_db_file_fatal[asn]",
371
+ "eval.tests.test_cli_flags.test_missing_geoip_db_file_fatal[city]",
372
+ "eval.tests.test_cli_flags.test_missing_geoip_db_file_fatal[country]",
373
+ "eval.tests.test_cli_flags.test_missing_template_logs_not_configuring",
374
+ "eval.tests.test_cli_flags.test_port_lookup_log_enabled",
375
+ "eval.tests.test_cli_flags.test_profiling_log_enabled",
376
+ "eval.tests.test_cli_flags.test_reverse_lookup_log_enabled",
377
+ "eval.tests.test_cli_flags.test_sponsor_log_enabled",
378
+ "eval.tests.test_cli_flags.test_string_flag_without_value_reports_error",
379
+ "eval.tests.test_cli_flags.test_trusted_header_multi_value_logged_comma_separated",
380
+ "eval.tests.test_cli_flags.test_trusted_header_single_value_logged",
381
+ "eval.tests.test_cli_flags.test_undefined_flag_exits_two",
382
+ "eval.tests.test_cli_flags.test_zero_cache_does_not_log_capacity",
383
+ "eval.tests.test_flag_wiring_behaviors.test_negative_cache_capacity_is_accepted_without_capacity_log",
384
+ "eval.tests.test_flag_wiring_behaviors.test_port_flag_absent_template_field_false",
385
+ "eval.tests.test_flag_wiring_behaviors.test_port_flag_sets_port_template_field",
386
+ "eval.tests.test_flag_wiring_behaviors.test_reverse_lookup_adds_hostname_to_json",
387
+ "eval.tests.test_flag_wiring_behaviors.test_reverse_lookup_disabled_omits_hostname",
388
+ "eval.tests.test_flag_wiring_behaviors.test_reverse_lookup_with_trusted_header_resolves_header_ip",
389
+ "eval.tests.test_flag_wiring_behaviors.test_sponsor_flag_absent_template_field_false",
390
+ "eval.tests.test_flag_wiring_behaviors.test_sponsor_flag_sets_sponsor_template_field",
391
+ "eval.tests.test_flag_wiring_behaviors.test_template_renders_custom_ip_query",
392
+ "eval.tests.test_flag_wiring_behaviors.test_template_renders_remote_ip_by_default",
393
+ "eval.tests.test_header_ordering_and_wiring.test_all_trusted_headers_empty_falls_back_to_remote",
394
+ "eval.tests.test_header_ordering_and_wiring.test_empty_first_header_falls_through_to_second",
395
+ "eval.tests.test_header_ordering_and_wiring.test_first_matching_trusted_header_wins",
396
+ "eval.tests.test_header_ordering_and_wiring.test_reverse_lookup_with_real_template_serves_html",
397
+ "eval.tests.test_header_ordering_and_wiring.test_third_trusted_header_used_when_earlier_ones_empty",
398
+ "eval.tests.test_header_ordering_and_wiring.test_three_trusted_headers_logged_in_order",
399
+ "eval.tests.test_header_ordering_and_wiring.test_trusted_header_with_real_template_renders_header_ip",
400
+ "eval.tests.test_header_ordering_and_wiring.test_trusted_header_without_reverse_lookup_omits_hostname",
401
+ "eval.tests.test_header_ordering_and_wiring.test_trusted_headers_log_line_when_empty_value",
402
+ "eval.tests.test_port_lookup.test_port_443_closed",
403
+ "eval.tests.test_port_lookup.test_port_65535_closed",
404
+ "eval.tests.test_port_lookup.test_port_hex_rejected",
405
+ "eval.tests.test_port_lookup.test_port_negative_rejected",
406
+ "eval.tests.test_port_lookup.test_port_non_numeric_rejected",
407
+ "eval.tests.test_port_lookup.test_port_path_prefix_matches",
408
+ "eval.tests.test_port_lookup.test_port_too_large_rejected",
409
+ "eval.tests.test_port_lookup.test_port_with_trailing_slash",
410
+ "eval.tests.test_port_lookup.test_port_zero_rejected",
411
+ "eval.tests.test_port_lookup.test_valid_port_closed_returns_reachable_false",
412
+ "eval.tests.test_server_http.test_custom_ipv4_query_param",
413
+ "eval.tests.test_server_http.test_custom_ipv6_query_param",
414
+ "eval.tests.test_server_http.test_custom_private_ip_query_param",
415
+ "eval.tests.test_server_http.test_default_handler_with_template_renders_html",
416
+ "eval.tests.test_server_http.test_empty_custom_ip_ignored",
417
+ "eval.tests.test_server_http.test_fetch_libfetch_user_agent_is_plain_ip",
418
+ "eval.tests.test_server_http.test_head_root_returns_204",
419
+ "eval.tests.test_server_http.test_health_endpoint_ok",
420
+ "eval.tests.test_server_http.test_httpie_user_agent_is_plain_ip",
421
+ "eval.tests.test_server_http.test_invalid_custom_ip_returns_400",
422
+ "eval.tests.test_server_http.test_ip_endpoint_returns_plain_ip",
423
+ "eval.tests.test_server_http.test_json_accept_on_root_returns_json",
424
+ "eval.tests.test_server_http.test_json_accept_on_unknown_path_json_404",
425
+ "eval.tests.test_server_http.test_json_endpoint_reports_loopback_ip",
426
+ "eval.tests.test_server_http.test_json_has_country_fields_present",
427
+ "eval.tests.test_server_http.test_post_on_ip_route_not_allowed",
428
+ "eval.tests.test_server_http.test_root_with_curl_user_agent_is_plain_ip",
429
+ "eval.tests.test_server_http.test_root_with_non_cli_ua_and_no_template_404",
430
+ "eval.tests.test_server_http.test_text_plain_accept_returns_ip",
431
+ "eval.tests.test_server_http.test_unknown_path_returns_404",
432
+ "eval.tests.test_server_http.test_unknown_trusted_header_no_override",
433
+ "eval.tests.test_server_http.test_wget_user_agent_is_plain_ip",
434
+ "eval.tests.test_server_http.test_x_forwarded_for_first_value_wins",
435
+ "eval.tests.test_server_http.test_x_forwarded_for_single_value",
436
+ "eval.tests.test_server_http.test_x_real_ip_header_override",
437
+ "eval.tests.test_server_http.test_xh_user_agent_is_plain_ip",
438
+ "eval.tests.test_startup_and_listen.test_address_already_in_use_logs_fatal",
439
+ "eval.tests.test_startup_and_listen.test_boolean_flag_explicit_false_does_not_enable",
440
+ "eval.tests.test_startup_and_listen.test_boolean_flag_space_value_is_positional_argument",
441
+ "eval.tests.test_startup_and_listen.test_empty_trusted_header_value_is_accepted",
442
+ "eval.tests.test_startup_and_listen.test_missing_port_logs_fatal",
443
+ "eval.tests.test_startup_and_listen.test_negative_port_logs_fatal",
444
+ "eval.tests.test_startup_and_listen.test_non_integer_cache_flag_is_parse_error",
445
+ "eval.tests.test_startup_and_listen.test_non_numeric_port_logs_fatal_and_exits_nonzero",
446
+ "eval.tests.test_startup_and_listen.test_out_of_range_port_logs_fatal",
447
+ "eval.tests.test_startup_and_listen.test_single_dash_help_flag_prints_usage",
448
+ "eval.tests.test_startup_and_listen.test_wildcard_host_and_random_port_serves",
449
+ "eval.tests.test_user_agent.test_bare_version_no_comment",
450
+ "eval.tests.test_user_agent.test_curl_comment_after_version",
451
+ "eval.tests.test_user_agent.test_decimal_version",
452
+ "eval.tests.test_user_agent.test_dotted_numeric_comment_split",
453
+ "eval.tests.test_user_agent.test_double_word_product_with_version",
454
+ "eval.tests.test_user_agent.test_empty_user_agent_omits_field",
455
+ "eval.tests.test_user_agent.test_full_browser_user_agent",
456
+ "eval.tests.test_user_agent.test_multiple_slashes_only_first_split",
457
+ "eval.tests.test_user_agent.test_plain_product_no_version",
458
+ "eval.tests.test_user_agent.test_product_slash_non_numeric_comment",
459
+ "eval.tests.test_user_agent.test_product_slash_version_only",
460
+ "eval.tests.test_user_agent.test_product_with_empty_version_slash",
461
+ "eval.tests.test_user_agent.test_product_with_hyphen",
462
+ "eval.tests.test_user_agent.test_raw_value_preserves_original",
463
+ "eval.tests.test_user_agent.test_raw_without_product_slash_leads_to_comment_split",
464
+ "eval.tests.test_user_agent.test_space_separated_product_and_comment",
465
+ "eval.tests.test_user_agent.test_spaces_only_in_comment",
466
+ "eval.tests.test_user_agent.test_uppercase_product_lowercase_version",
467
+ "eval.tests.test_user_agent.test_version_leading_zero",
468
+ "eval.tests.test_user_agent.test_version_with_non_numeric_suffix",
469
+ "eval.tests.test_user_agent.test_wget_with_comment"
470
+ ]
471
+ }
472
+ },
473
+ "commit": "746db5ebf42f87da5d487de444dccc884f9d1c39",
474
+ "data_source": "synthetic_programgym",
475
+ "difficulty": "easy",
476
+ "difficulty_score": 1.61320735210376,
477
+ "eval_clean_hashes": [
478
+ "ebd09d363ef915651c1d1178d229aa2afdd9bd27c274f53cd6e8f205d174cc06"
479
+ ],
480
+ "input_record": {
481
+ "commit": "746db5ebf42f87da5d487de444dccc884f9d1c39",
482
+ "commits": 354,
483
+ "contributors": 27,
484
+ "difficulty": "easy",
485
+ "difficulty_code_lines": 1026,
486
+ "difficulty_has_tests": false,
487
+ "difficulty_product_code_lines": 1026,
488
+ "difficulty_runtime_deps": 3,
489
+ "difficulty_score": 1.61320735210376,
490
+ "difficulty_test_code_lines": 509,
491
+ "full_name": "mpolden/echoip",
492
+ "github_stars": 4339,
493
+ "input_joern_zip": "go_joern/mpolden__echoip.zip",
494
+ "joern_status": true,
495
+ "joern_time": 13.48858488490805,
496
+ "language": "go",
497
+ "pb_match": [
498
+ {
499
+ "pb_fullname": "guumaster/hostctl",
500
+ "rank": 847,
501
+ "similarity": 0.44968006014823914
502
+ },
503
+ {
504
+ "pb_fullname": "sheepla/pingu",
505
+ "rank": 387,
506
+ "similarity": 0.5047612190246582
507
+ }
508
+ ],
509
+ "repo_age": 13.71,
510
+ "repo_path": "go/mpolden__echoip",
511
+ "source": "commit:746db5ebf42f87da5d487de444dccc884f9d1c39",
512
+ "status": "done",
513
+ "url": "https://github.com/mpolden/echoip"
514
+ },
515
+ "instance_id": "mpolden__echoip.746db5e",
516
+ "language": "go",
517
+ "module_iterations": [
518
+ {
519
+ "actual_iterations": 5,
520
+ "branch_name": "generated_module_01",
521
+ "iteration_limit": 5,
522
+ "module_index": 1,
523
+ "module_kind": "source",
524
+ "termination_reason": "max_iterations"
525
+ },
526
+ {
527
+ "actual_iterations": 5,
528
+ "branch_name": "generated_module_02",
529
+ "iteration_limit": 5,
530
+ "module_index": 2,
531
+ "module_kind": "source",
532
+ "termination_reason": "max_iterations"
533
+ },
534
+ {
535
+ "actual_iterations": 5,
536
+ "branch_name": "generated_module_03",
537
+ "iteration_limit": 5,
538
+ "module_index": 3,
539
+ "module_kind": "source",
540
+ "termination_reason": "early_stopping"
541
+ },
542
+ {
543
+ "actual_iterations": 5,
544
+ "branch_name": "generated_module_04",
545
+ "iteration_limit": 5,
546
+ "module_index": 4,
547
+ "module_kind": "source",
548
+ "termination_reason": "max_iterations"
549
+ }
550
+ ],
551
+ "repository": "mpolden/echoip"
552
+ }
mpolden--echoip.746db5e/tests/test.sh ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ # Verifier exec may not inherit image ENV (Modal/gVisor, login-shell resets).
5
+ export PATH="/usr/local/go/bin:/go/bin:/usr/local/cargo/bin:/root/.cargo/bin:${PATH}"
6
+
7
+ mkdir -p /logs/verifier /logs/artifacts
8
+
9
+ write_failure() {
10
+ local code="$1"
11
+ local details="$2"
12
+ python3 - "$code" "$details" <<'PY'
13
+ import json
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ code, details = sys.argv[1:3]
18
+ try:
19
+ metadata = json.loads(Path("/tests/programgym_task.json").read_text())
20
+ n_tests = sum(
21
+ len([
22
+ name for name in info.get("tests", [])
23
+ if name not in {item.get("name") for item in info.get("ignored_tests", [])}
24
+ ])
25
+ for branch, info in metadata.get("branches", {}).items()
26
+ if not info.get("ignored")
27
+ )
28
+ except Exception:
29
+ n_tests = 0
30
+ result = {
31
+ "test_results": [],
32
+ "error_code": code,
33
+ "error_details": details,
34
+ "log": [],
35
+ "solution_branch": "submission",
36
+ "test_branches": [],
37
+ "test_branch_errors": {
38
+ "__infra__": [{"error_code": code, "error_details": details}]
39
+ },
40
+ "executable_hash": None,
41
+ "warnings": [],
42
+ }
43
+ diagnostics = {
44
+ "pass_rate": 0.0,
45
+ "resolved": 0,
46
+ "n_passed": 0,
47
+ "n_tests": n_tests,
48
+ "n_branch_errors": 1,
49
+ "infra_error": 1,
50
+ "executable_hash_present": 0,
51
+ }
52
+ Path("/logs/verifier/programgym_eval.json").write_text(
53
+ json.dumps(result, indent=2, sort_keys=True)
54
+ )
55
+ Path("/logs/verifier/harbor_diagnostics.json").write_text(
56
+ json.dumps(diagnostics, indent=2, sort_keys=True)
57
+ )
58
+ Path("/logs/verifier/reward.json").write_text(
59
+ json.dumps(
60
+ {"reward": 0.0, "resolved": 0.0, "almost_resolved": 0.0},
61
+ indent=2,
62
+ sort_keys=True,
63
+ )
64
+ )
65
+ Path("/logs/verifier/reward.txt").write_text("0.0")
66
+ Path("/logs/verifier/programgym_eval.log").write_text(details)
67
+ PY
68
+ }
69
+
70
+ if ! command -v python3 >/dev/null 2>&1; then
71
+ write_failure "missing_python3" "python3 is required in the cleanroom image"
72
+ exit 0
73
+ fi
74
+
75
+ if ! python3 /tests/programgym_evaluator.py; then
76
+ if [ ! -s /logs/verifier/reward.txt ]; then
77
+ write_failure "evaluator_crashed" \
78
+ "programgym_evaluator.py exited non-zero with no reward written"
79
+ fi
80
+ fi
81
+
82
+ exit 0
mpolden--echoip.746db5e/tests/workspace.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:208a90f2afe3b5d5b0f692914d92b5c350df1fdb7a2e7465f36b1f0937845656
3
+ size 9936
mpostument--grafana-sync.0dd7ef8/environment/Dockerfile ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive
3
+ ENV RUSTUP_DIST_SERVER="https://static.rust-lang.org"
4
+ ENV RUSTUP_UPDATE_ROOT="https://static.rust-lang.org/rustup"
5
+ ENV CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse
6
+ ENV CARGO_REGISTRIES_CRATES_IO_INDEX="sparse+https://index.crates.io/"
7
+ ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
8
+ ENV GOPROXY="https://proxy.golang.org,direct"
9
+ ENV GOSUMDB=sum.golang.google.cn
10
+ ENV GOTOOLCHAIN=auto
11
+ ENV UV_INSECURE_HOST=""
12
+ ENV UV_INDEX_URL="https://pypi.org/simple"
13
+ ENV UV_EXTRA_INDEX_URL=https://pypi.org/simple
14
+ ENV UV_CACHE_DIR=/workspace/.cache/uv
15
+ ENV npm_config_registry="https://registry.npmjs.org/"
16
+ ENV npm_config_strict_ssl=false
17
+ ENV npm_config_cache=/workspace/.cache/npm
18
+ ENV PIP_INDEX_URL="https://pypi.org/simple"
19
+ ENV PIP_EXTRA_INDEX_URL=https://pypi.org/simple
20
+ ENV PIP_TRUSTED_HOST=""
21
+ ENV HOME=/workspace
22
+ ENV XDG_CACHE_HOME=/workspace/.cache
23
+ ENV PIP_CACHE_DIR=/workspace/.cache/pip
24
+ ENV PYTHONUSERBASE=/workspace/.local
25
+ ENV GOROOT=/usr/local/go
26
+ ENV GOPATH=/workspace/.go
27
+ ENV GOCACHE=/workspace/.cache/go-build
28
+ ENV PIP_BREAK_SYSTEM_PACKAGES=1
29
+ ENV PATH=/opt/programgym-venv/bin:/usr/local/go/bin:/workspace/.go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
30
+ ENV PAGER=cat
31
+ ENV MANPAGER=cat
32
+ ENV LESS=-R
33
+ ENV TQDM_DISABLE=1
34
+ ENV VIRTUAL_ENV=/opt/programgym-venv
35
+ RUN apt-get update && apt-get install -y --no-install-recommends bash build-essential ca-certificates git make pkg-config python3 python3-pip curl wget xz-utils unzip zip bzip2 zstd patch file binutils python3-venv tar && rm -rf /var/lib/apt/lists/*
36
+ COPY programgym-go.tar.gz /tmp/programgym-go.tar.gz
37
+ RUN set -eux; rm -rf /usr/local/go; tar -C /usr/local -xzf /tmp/programgym-go.tar.gz; rm -f /tmp/programgym-go.tar.gz; if [ ! -x /usr/local/go/bin/go ]; then echo "official Go tarball did not create /usr/local/go/bin/go" >&2; exit 1; fi; /usr/local/go/bin/go version
38
+ RUN python3 -m venv /opt/programgym-venv && /opt/programgym-venv/bin/python -m pip install --no-cache-dir --only-binary=:all: pytest pytest-xdist coverage
39
+ WORKDIR /workspace
40
+ ADD workspace.tar.gz /workspace/
41
+ COPY executable /workspace/executable
42
+ COPY download.sh /workspace/download.sh
43
+ RUN chmod 755 /workspace/download.sh
44
+ COPY harbor_prepare_download_env.sh /tmp/harbor_prepare_download_env.sh
45
+ RUN chmod 755 /tmp/harbor_prepare_download_env.sh \
46
+ && /bin/bash /tmp/harbor_prepare_download_env.sh \
47
+ && rm -f /workspace/download.sh \
48
+ && rm -f /tmp/harbor_prepare_download_env.sh
49
+ ENV BASH_ENV=/etc/profile.d/programgym_download_env.sh
50
+ RUN chmod 111 /workspace/executable
51
+ WORKDIR /workspace
52
+ # programgym-runtime-workspace-cleanup: v1
53
+ RUN ["bash","-lc","rm -f -- /workspace/download.sh /workspace/reference/build.sh && rm -rf -- /workspace/.programgym_build_env"]
54
+ # Harbor synthetic ProgramGym adapter: run the agent as an unprivileged user.
55
+ # Keep tool/runtime state under /home/agent and reserve /workspace for the
56
+ # submission handed to the separate verifier. Keep the reference executable
57
+ # execute-only; the oracle temporarily restores owner read permission.
58
+ RUN id -u agent >/dev/null 2>&1 || useradd -m -s /bin/bash agent
59
+ RUN mkdir -p /home/agent \
60
+ && chown -R agent:agent /home/agent /workspace \
61
+ && chown agent:agent /workspace/executable \
62
+ && chmod 111 /workspace/executable
63
+ ENV HOME=/home/agent
64
+ WORKDIR /workspace
mpostument--grafana-sync.0dd7ef8/environment/download.sh ADDED
The diff for this file is too large to render. See raw diff
 
mpostument--grafana-sync.0dd7ef8/environment/executable ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3feaa0a4c2b4a886cc4737971168e141bcf85da19a63d689e552a781e07f8070
3
+ size 14389124
mpostument--grafana-sync.0dd7ef8/environment/harbor_prepare_download_env.sh ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ cd /workspace
4
+ set -a
5
+ source /workspace/download.sh
6
+ set +a
7
+ python3 - <<'PY' > /etc/profile.d/programgym_download_env.sh
8
+ import os
9
+ import shlex
10
+
11
+ ignored = {
12
+ "ALL_PROXY",
13
+ "HTTP_PROXY",
14
+ "HTTPS_PROXY",
15
+ "NO_PROXY",
16
+ "OLDPWD",
17
+ "PIP_PROXY",
18
+ "PWD",
19
+ "SHLVL",
20
+ "_",
21
+ "all_proxy",
22
+ "http_proxy",
23
+ "https_proxy",
24
+ "no_proxy",
25
+ "pip_proxy",
26
+ }
27
+ for key in sorted(os.environ):
28
+ if key in ignored or key.startswith("BASH_FUNC_"):
29
+ continue
30
+ value = os.environ[key]
31
+ if "\n" in value:
32
+ continue
33
+ print(f"export {key}={shlex.quote(value)}")
34
+ PY
mpostument--grafana-sync.0dd7ef8/environment/programgym-go.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:39042a078ea9ceebe3ecda4a7188f0f5b96e14a071d27923ba7f40b456e85ae3
3
+ size 59908810
mpostument--grafana-sync.0dd7ef8/environment/workspace.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33c7a496f7c7c5cb0c1c11d5d3d25a07e90f6130db19d6bb29c478ae80de70c5
3
+ size 84170
mpostument--grafana-sync.0dd7ef8/instruction.md ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are a helpful assistant that can interact with a computer.
2
+
3
+ This is a reverse-engineering benchmark. You are given a compiled binary and its documentation.
4
+ Your job is to write a new, original codebase from scratch that produces an executable with identical behavior.
5
+ You must figure out the behavior solely by running and interacting with the provided binary.
6
+ Writing original code based on observed behavior is the entire point of this benchmark.
7
+
8
+ Any approach that shortcuts this — finding existing source code, wrapping the binary,
9
+ or installing the original tool — does not count as a solution. It will be detected by an
10
+ automated judge, marked as a disqualification, and scored as a failure.
11
+ The trace will be posted to an online wall of shame.
12
+
13
+ <RULES>
14
+ ## What is not allowed
15
+
16
+ ### 1. Obtaining source code
17
+
18
+ The only source of truth about what the executable does is the executable itself and its
19
+ bundled documentation. You must not search the internet, package registries, or any external
20
+ source for information about this project's source code. Even if you recognize what the
21
+ executable is, you must reimplement it from behavioral observation alone.
22
+
23
+ This includes but is not limited to:
24
+ - Cloning or browsing the original GitHub repository, its forks, or mirrors
25
+ - Downloading the project from package registries: `cargo install <project>`, `go get github.com/<org>/<project>`, `pip install <project>`, `apt-get source <project>`, `npm install <project>`, etc.
26
+ - Fetching source tarballs from project websites (e.g., `curl https://lua.org/ftp/lua-5.5.0.tar.gz`)
27
+ - Using a package manager to download the project as a dependency and then reading its cached source (e.g., navigating into `~/.cargo/registry/src/` or `$(go env GOPATH)/pkg/mod/`)
28
+ - Searching the web for the project's source code or implementation details
29
+
30
+ ### 2. Wrapping or reusing the original binary
31
+
32
+ Your submission must be a genuine reimplementation. The provided `./executable` is for
33
+ observation only — your final solution must not depend on it or any other pre-built version
34
+ of the same tool at runtime.
35
+
36
+ This includes but is not limited to:
37
+ - Writing a wrapper script that delegates to the original binary (e.g., `exec zstd "$@"`)
38
+ - Installing the tool from a package manager and shimming to it (e.g., `apt-get install nnn && cp $(which nnn) ./executable`)
39
+ - Writing a `compile.sh` that simply makes the provided binary executable (`chmod +x ./executable`) or copies it (`cp ./executable ./executable`)
40
+ - Building a binary whose main function shells out to an external tool (e.g., `Command::new("miniserve").args(args).exec()`)
41
+ - Re-linking prebuilt `.o` object files found in the workspace without writing new source code
42
+
43
+ ### 3. Binary analysis of the provided executable
44
+
45
+ All information about the provided `./executable` must be obtained by interacting with it
46
+ through its normal user interface (CLI flags, stdin/stdout, etc.).
47
+ - You MUST NOT decompile `./executable` or use disassemblers (objdump, Ghidra, etc.) on it
48
+ - You MUST NOT use strace, ltrace, or similar tracing/instrumentation tools on `./executable`
49
+
50
+ Note: this restriction applies ONLY to the provided `./executable`. You are free to use any
51
+ analysis tools on binaries that you produce yourself during development.
52
+
53
+ ## What IS allowed
54
+
55
+ - Running the executable with any inputs, flags, and arguments to observe its behavior
56
+ - Reading any documentation files bundled in the workspace
57
+ </RULES>
58
+
59
+ ## Task context
60
+
61
+ We want to write the source code for a given executable.
62
+ The executable is located at `./executable` in the workspace root.
63
+
64
+ You also have access to the existing documentation.
65
+
66
+ ## Your task
67
+
68
+ Implement the source code to generate an executable of exactly identical behavior as the original.
69
+
70
+ No project-specific dependencies are pre-installed.
71
+ You do NOT have access to the internet.
72
+ **IMPORTANT**: Make sure that the executable(s) and everything else that is an artifact is not committed, i.e., is in your `.gitignore` file.
73
+ Finally, commit your changes.
74
+
75
+ Make sure that you have a `./compile.sh` file that produces an executable `./executable` in the workspace root.
76
+ `compile.sh` should be executable and should install any dependencies needed to compile the executable.
77
+ If your compile.sh fails to compile on a fresh checkout, your task has failed.
78
+
79
+ ## Important: This is a reverse-engineering benchmark
80
+
81
+ Your goal is to write original code from scratch that reproduces the executable's behavior.
82
+ The only way to learn what the executable does is to run it and read its bundled documentation.
83
+
84
+ Any attempt to obtain source code — whether successful or not — or to wrap/reuse the
85
+ provided binary will be detected by an automated judge, disqualified, and scored as zero.
86
+ See the full rules in the system prompt above. Key points:
87
+
88
+ - Do NOT search the internet, clone repos, or download the project from any package registry
89
+ - Do NOT wrap, shim, or delegate to the provided `./executable` or any installed version of the same tool
90
+ - Do NOT decompile the provided `./executable` or use strace/ltrace on it (analyzing your own binaries is fine)
91
+ - You SHOULD extensively test the executable to understand its behavior before writing code.
92
+ If you are dealing with a TUI, tmux/libtmux has been installed to help you test/inspect/it.
93
+
94
+ ## Recommended Workflow
95
+
96
+ 1. Explore all documentation files
97
+ 2. Play with the executable to understand its behavior (however, you MUST NOT decompile `./executable` or perform any other form of binary or strace/ltrace analysis on it)
98
+ 3. Write the source code to implement the behavior
mpostument--grafana-sync.0dd7ef8/solution/solve.sh ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Oracle-only ceiling check. The reference is execute-only for normal agents;
3
+ # because the oracle runs as the owning `agent` user it can temporarily add read
4
+ # permission and encode the binary for Harbor's normal artifact handoff.
5
+ set -euo pipefail
6
+ test -f ./executable
7
+ chmod u+r ./executable
8
+ python3 - <<'PY'
9
+ import base64
10
+ from pathlib import Path
11
+
12
+ Path(".programgym_oracle_reference").write_bytes(
13
+ base64.b64encode(Path("executable").read_bytes())
14
+ )
15
+ PY
16
+ chmod u-r ./executable
17
+ cat > compile.sh <<'EOF'
18
+ #!/usr/bin/env bash
19
+ set -euo pipefail
20
+ if [ -f ./.programgym_oracle_reference ]; then
21
+ python3 - <<'PY'
22
+ import base64
23
+ from pathlib import Path
24
+
25
+ Path("executable").write_bytes(
26
+ base64.b64decode(Path(".programgym_oracle_reference").read_bytes())
27
+ )
28
+ PY
29
+ fi
30
+ test -f ./executable
31
+ chmod +x ./executable
32
+ EOF
33
+ chmod +x compile.sh
mpostument--grafana-sync.0dd7ef8/task.toml ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.3"
2
+ source = "ProgramGym"
3
+ artifacts = [
4
+ "/logs/verifier/programgym_eval.json",
5
+ "/logs/verifier/harbor_diagnostics.json",
6
+ "/logs/verifier/programgym_eval.log",
7
+ "/logs/verifier/reward.json",
8
+ "/logs/verifier/reward.txt",
9
+ # Keep agent/runtime state out of the submission handoff. In particular,
10
+ # Claude Code installs an absolute symlink under .local/bin; transferring it
11
+ # makes Python's safe tar extraction reject the entire workspace archive.
12
+ { source = "/workspace", exclude = [
13
+ "executable",
14
+ ".git",
15
+ ".bashrc",
16
+ ".cache",
17
+ ".cc-switch",
18
+ ".claude",
19
+ ".local",
20
+ ] },
21
+ ]
22
+
23
+ [task]
24
+ name = "programgym/mpostument--grafana-sync.0dd7ef8"
25
+ description = "Synthetic ProgramGym cleanroom reconstruction task for mpostument/grafana-sync"
26
+ authors = [{ name = "Harbor ProgramGym Synthetic Adapter" }]
27
+ keywords = ["programgym", "synthetic", "reverse-engineering", "cleanroom", "go"]
28
+
29
+ [metadata]
30
+ source = "ProgramGym"
31
+ instance_id = "mpostument__grafana-sync.0dd7ef8"
32
+ repository = "mpostument/grafana-sync"
33
+ commit = "0dd7ef88aaebebf92f3757907e572464aee2dd25"
34
+ language = "go"
35
+ difficulty = "easy"
36
+ difficulty_score = 1.561101383649056
37
+ test_branches = 4
38
+ test_count = 174
39
+
40
+ [agent]
41
+ timeout_sec = 14400
42
+ user = "agent"
43
+ network_mode = "allowlist"
44
+ allowed_hosts = ["api.anthropic.com", "api.openai.com"]
45
+
46
+ [verifier]
47
+ timeout_sec = 7200
48
+ user = "root"
49
+ environment_mode = "separate"
50
+
51
+ [verifier.env]
52
+ PROGRAMGYM_XDIST_WORKERS = "8"
53
+
54
+ [verifier.environment]
55
+ build_timeout_sec = 1800
56
+ cpus = 8
57
+ memory_mb = 16384
58
+ storage_mb = 30720
59
+ gpus = 0
60
+ workdir = "/workspace"
61
+
62
+ [environment]
63
+ network_mode = "public"
64
+ build_timeout_sec = 1800
65
+ cpus = 8
66
+ memory_mb = 16384
67
+ storage_mb = 30720
68
+ gpus = 0
69
+ workdir = "/workspace"
mpostument--grafana-sync.0dd7ef8/tests/Dockerfile ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:24.04
2
+ ENV DEBIAN_FRONTEND=noninteractive
3
+ ENV RUSTUP_DIST_SERVER="https://static.rust-lang.org"
4
+ ENV RUSTUP_UPDATE_ROOT="https://static.rust-lang.org/rustup"
5
+ ENV CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse
6
+ ENV CARGO_REGISTRIES_CRATES_IO_INDEX="sparse+https://index.crates.io/"
7
+ ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
8
+ ENV GOPROXY="https://proxy.golang.org,direct"
9
+ ENV GOSUMDB=sum.golang.google.cn
10
+ ENV GOTOOLCHAIN=auto
11
+ ENV UV_INSECURE_HOST=""
12
+ ENV UV_INDEX_URL="https://pypi.org/simple"
13
+ ENV UV_EXTRA_INDEX_URL=https://pypi.org/simple
14
+ ENV UV_CACHE_DIR=/workspace/.cache/uv
15
+ ENV npm_config_registry="https://registry.npmjs.org/"
16
+ ENV npm_config_strict_ssl=false
17
+ ENV npm_config_cache=/workspace/.cache/npm
18
+ ENV PIP_INDEX_URL="https://pypi.org/simple"
19
+ ENV PIP_EXTRA_INDEX_URL=https://pypi.org/simple
20
+ ENV PIP_TRUSTED_HOST=""
21
+ ENV HOME=/workspace
22
+ ENV XDG_CACHE_HOME=/workspace/.cache
23
+ ENV PIP_CACHE_DIR=/workspace/.cache/pip
24
+ ENV PYTHONUSERBASE=/workspace/.local
25
+ ENV GOROOT=/usr/local/go
26
+ ENV GOPATH=/workspace/.go
27
+ ENV GOCACHE=/workspace/.cache/go-build
28
+ ENV PIP_BREAK_SYSTEM_PACKAGES=1
29
+ ENV PATH=/opt/programgym-venv/bin:/usr/local/go/bin:/workspace/.go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
30
+ ENV PAGER=cat
31
+ ENV MANPAGER=cat
32
+ ENV LESS=-R
33
+ ENV TQDM_DISABLE=1
34
+ ENV VIRTUAL_ENV=/opt/programgym-venv
35
+ RUN apt-get update && apt-get install -y --no-install-recommends bash build-essential ca-certificates git make pkg-config python3 python3-pip curl wget xz-utils unzip zip bzip2 zstd patch file binutils python3-venv tar && rm -rf /var/lib/apt/lists/*
36
+ COPY programgym-go.tar.gz /tmp/programgym-go.tar.gz
37
+ RUN set -eux; rm -rf /usr/local/go; tar -C /usr/local -xzf /tmp/programgym-go.tar.gz; rm -f /tmp/programgym-go.tar.gz; if [ ! -x /usr/local/go/bin/go ]; then echo "official Go tarball did not create /usr/local/go/bin/go" >&2; exit 1; fi; /usr/local/go/bin/go version
38
+ RUN python3 -m venv /opt/programgym-venv && /opt/programgym-venv/bin/python -m pip install --no-cache-dir --only-binary=:all: pytest pytest-xdist coverage
39
+ WORKDIR /workspace
40
+ ADD workspace.tar.gz /workspace/
41
+ COPY executable /workspace/executable
42
+ COPY download.sh /workspace/download.sh
43
+ RUN chmod 755 /workspace/download.sh
44
+ COPY harbor_prepare_download_env.sh /tmp/harbor_prepare_download_env.sh
45
+ RUN chmod 755 /tmp/harbor_prepare_download_env.sh \
46
+ && /bin/bash /tmp/harbor_prepare_download_env.sh \
47
+ && rm -f /workspace/download.sh \
48
+ && rm -f /tmp/harbor_prepare_download_env.sh
49
+ ENV BASH_ENV=/etc/profile.d/programgym_download_env.sh
50
+ RUN chmod 111 /workspace/executable
51
+ WORKDIR /workspace
52
+ # programgym-runtime-workspace-cleanup: v1
53
+ RUN ["bash","-lc","rm -f -- /workspace/download.sh /workspace/reference/build.sh && rm -rf -- /workspace/.programgym_build_env"]
54
+ # Harbor uses tests/ as the separate verifier build context. Start with the
55
+ # same toolchain as the agent, then remove every cleanroom workspace artifact.
56
+ RUN rm -rf /workspace/* /workspace/.[!.]* 2>/dev/null || true \
57
+ && mkdir -p /workspace /tests
58
+
59
+ # Synthetic cleanroom Dockerfiles commonly install Ubuntu's pytest-xdist 2.5.0.
60
+ # Installing a newer pytest alone leaves that apt package importable and creates
61
+ # an incompatible mixed apt/pip stack (xdist 2.5 imports the removed py.log).
62
+ # Install and constrain the verifier test runner as one coherent pip toolchain.
63
+ RUN printf 'pytest<9\n' > /etc/pip-constraint.txt
64
+ ENV PIP_CONSTRAINT=/etc/pip-constraint.txt
65
+ RUN python3 -m pip install --break-system-packages \
66
+ --no-cache-dir --disable-pip-version-check \
67
+ 'pytest<9' 'pytest-xdist>=3,<4' pytest-rerunfailures pytest-timeout
68
+
69
+ COPY test.sh /tests/test.sh
70
+ COPY programgym_evaluator.py /tests/programgym_evaluator.py
71
+ COPY programgym_task.json /tests/programgym_task.json
72
+ COPY blobs/ /tests/blobs/
73
+ RUN chmod +x /tests/test.sh
mpostument--grafana-sync.0dd7ef8/tests/blobs/tests/generated_module_01.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1bd6f1a5c1ac5ec95951ba0bb9c393a33ca9342b0f0491d3dc6c474fd95a93b
3
+ size 9182
mpostument--grafana-sync.0dd7ef8/tests/blobs/tests/generated_module_02.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6883d1ca2d1e4c013f336073cc9b13d5454ae02b189829f201f7340df05b7b9e
3
+ size 10499
mpostument--grafana-sync.0dd7ef8/tests/blobs/tests/generated_module_03.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb3b3221fc1b2bebaed275a39b10264d2bfc9c924a2195408f434abea189575e
3
+ size 7015
mpostument--grafana-sync.0dd7ef8/tests/blobs/tests/generated_module_04.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:822c58810b08c2382fdf5976e25e19844e69b1f0dc4ebbb75767770cdae1baed
3
+ size 7929
mpostument--grafana-sync.0dd7ef8/tests/download.sh ADDED
The diff for this file is too large to render. See raw diff
 
mpostument--grafana-sync.0dd7ef8/tests/executable ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3feaa0a4c2b4a886cc4737971168e141bcf85da19a63d689e552a781e07f8070
3
+ size 14389124
mpostument--grafana-sync.0dd7ef8/tests/harbor_prepare_download_env.sh ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ cd /workspace
4
+ set -a
5
+ source /workspace/download.sh
6
+ set +a
7
+ python3 - <<'PY' > /etc/profile.d/programgym_download_env.sh
8
+ import os
9
+ import shlex
10
+
11
+ ignored = {
12
+ "ALL_PROXY",
13
+ "HTTP_PROXY",
14
+ "HTTPS_PROXY",
15
+ "NO_PROXY",
16
+ "OLDPWD",
17
+ "PIP_PROXY",
18
+ "PWD",
19
+ "SHLVL",
20
+ "_",
21
+ "all_proxy",
22
+ "http_proxy",
23
+ "https_proxy",
24
+ "no_proxy",
25
+ "pip_proxy",
26
+ }
27
+ for key in sorted(os.environ):
28
+ if key in ignored or key.startswith("BASH_FUNC_"):
29
+ continue
30
+ value = os.environ[key]
31
+ if "\n" in value:
32
+ continue
33
+ print(f"export {key}={shlex.quote(value)}")
34
+ PY
mpostument--grafana-sync.0dd7ef8/tests/programgym-go.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:39042a078ea9ceebe3ecda4a7188f0f5b96e14a071d27923ba7f40b456e85ae3
3
+ size 59908810
mpostument--grafana-sync.0dd7ef8/tests/programgym_evaluator.py ADDED
@@ -0,0 +1,1201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """In-place ProgramGym evaluator.
3
+
4
+ Mirrors ProgramGym's ``Evaluator`` pipeline as closely as a single-container,
5
+ no-Docker-in-Docker host allows. Run from ``tests/test.sh`` inside the agent's
6
+ cleanroom container after Harbor flips the verifier-phase network policy.
7
+
8
+ Differences from ``programgym.eval.eval.Evaluator`` that are structural to
9
+ running in one container:
10
+
11
+ * No fresh container per branch. ``snapshot_workspace`` / ``restore_workspace``
12
+ copy a post-compile workspace snapshot to a temp directory and restore it
13
+ before each branch; ``cleanup_lingering_processes`` kills leftover branch
14
+ processes between attempts to approximate the fresh-container boundary.
15
+ * No ``docker commit``. The post-compile workspace snapshot serves the same
16
+ role as the committed image upstream.
17
+ * Hidden test blobs are fetched on demand from HuggingFace via
18
+ ``huggingface_hub.snapshot_download`` (matching ``programgym.utils.blob_store``)
19
+ rather than being pre-staged into ``/tests/blobs/``. Override with
20
+ ``PROGRAMGYM_BLOB_DIR`` for offline reruns.
21
+
22
+ Everything else (eval_clean_hashes scrub, deterministic synthetic git seed,
23
+ ``compile.sh`` then stash + hash the executable, best-effort
24
+ ``pytest-rerunfailures``, per-branch test-tar overlay, executable hash
25
+ ``--max-worker-restart=4``, xdist worker-crash retry with serial fallback,
26
+ best-of-N attempt selection, active vs ignored test bookkeeping, scoring) is
27
+ preserved.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import hashlib
33
+ import json
34
+ import os
35
+ import re
36
+ import shlex
37
+ import shutil
38
+ import signal
39
+ import subprocess
40
+ import tempfile
41
+ import time
42
+ import traceback
43
+ import xml.etree.ElementTree as ET
44
+ from pathlib import Path
45
+ from typing import Any
46
+
47
+ WORKSPACE = Path(os.environ.get("PROGRAMGYM_WORKSPACE", "/workspace"))
48
+ STASHED_EXECUTABLE = Path("/opt/programgym-stashed-executable-do-not-modify")
49
+ METADATA_PATH = Path(
50
+ os.environ.get("PROGRAMGYM_METADATA", "/tests/programgym_task.json")
51
+ )
52
+ LOG_DIR = Path(os.environ.get("PROGRAMGYM_LOG_DIR", "/logs/verifier"))
53
+ WORKER_CRASH_PHRASE = "worker '"
54
+ XDIST_COLLAPSE_MARKERS = (
55
+ "maximum crashed workers reached",
56
+ "xdist: maximum crashed",
57
+ )
58
+
59
+ DEFAULT_HF_REPO_ID = "programgym/ProgramGym-Tests"
60
+ DEFAULT_HF_REVISION = "main"
61
+
62
+ # Oracle agent handoff files (see solution/solve.sh). Must not appear in the
63
+ # post-compile workspace snapshot or they pollute tree-scanning tests (dutree).
64
+ _ORACLE_HANDOFF_NAMES = (".programgym_oracle_reference",)
65
+
66
+ _TOOLCHAIN_BIN_DIR_CANDIDATES = (
67
+ "/usr/local/go/bin",
68
+ "/go/bin",
69
+ "/usr/local/cargo/bin",
70
+ "/root/.cargo/bin",
71
+ "/root/.ghcup/bin",
72
+ )
73
+
74
+
75
+ def toolchain_bin_dirs() -> list[str]:
76
+ """Return toolchain bin directories that exist on this image."""
77
+ candidates = list(_TOOLCHAIN_BIN_DIR_CANDIDATES)
78
+ candidates.extend(
79
+ str(path)
80
+ for path in sorted(Path("/usr/lib").glob("go-*/bin"))
81
+ if _is_accessible_dir(path)
82
+ )
83
+ seen: set[str] = set()
84
+ present: list[str] = []
85
+ for path in candidates:
86
+ if path in seen:
87
+ continue
88
+ seen.add(path)
89
+ if _is_accessible_dir(path):
90
+ present.append(path)
91
+ return present
92
+
93
+
94
+ def _is_accessible_dir(path: str | Path) -> bool:
95
+ """Return whether path is a directory without failing on protected homes."""
96
+ try:
97
+ return Path(path).is_dir()
98
+ except OSError:
99
+ return False
100
+
101
+
102
+ def bootstrap_toolchain_path() -> str:
103
+ """Prepend discovered toolchain dirs to PATH (idempotent)."""
104
+ prepend = toolchain_bin_dirs()
105
+ current_parts = [part for part in os.environ.get("PATH", "").split(":") if part]
106
+ merged: list[str] = []
107
+ for path in prepend + current_parts:
108
+ if path not in merged:
109
+ merged.append(path)
110
+ new_path = ":".join(merged)
111
+ os.environ["PATH"] = new_path
112
+ return new_path
113
+
114
+
115
+ def _bash_login_command(command: str) -> str:
116
+ """Run ``command`` under bash -lc with an explicit PATH export."""
117
+ path = bootstrap_toolchain_path()
118
+ return f"export PATH={shlex.quote(path)}; {command}"
119
+
120
+
121
+ def sha256(path: Path) -> str:
122
+ h = hashlib.sha256()
123
+ with path.open("rb") as f:
124
+ for chunk in iter(lambda: f.read(1024 * 1024), b""):
125
+ h.update(chunk)
126
+ return h.hexdigest()
127
+
128
+
129
+ def write_json(path: Path, data: dict[str, Any]) -> None:
130
+ tmp = path.with_suffix(path.suffix + ".tmp")
131
+ tmp.write_text(json.dumps(data, indent=2, sort_keys=True))
132
+ tmp.replace(path)
133
+
134
+
135
+ def _read_log_tail(path: Path | None, max_bytes: int = 65536) -> str:
136
+ if path is None or not path.exists():
137
+ return ""
138
+ data = path.read_bytes()
139
+ if len(data) <= max_bytes:
140
+ return data.decode(errors="replace")
141
+ return data[-max_bytes:].decode(errors="replace")
142
+
143
+
144
+ def _close_pipes(proc: subprocess.Popen[Any]) -> None:
145
+ for stream in (proc.stdout, proc.stderr):
146
+ if stream is not None:
147
+ try:
148
+ stream.close()
149
+ except OSError:
150
+ pass
151
+
152
+
153
+ def _terminate_process_tree(proc: subprocess.Popen[Any]) -> None:
154
+ try:
155
+ os.killpg(proc.pid, signal.SIGKILL)
156
+ except ProcessLookupError:
157
+ pass
158
+ try:
159
+ proc.kill()
160
+ except ProcessLookupError:
161
+ pass
162
+
163
+
164
+ _PKILL_PATTERNS = (
165
+ f"{WORKSPACE}/eval/",
166
+ f"{WORKSPACE}/tests/",
167
+ "tail -f",
168
+ "development.log",
169
+ " less ",
170
+ " less$",
171
+ "/less ",
172
+ )
173
+
174
+
175
+ def _pkill_aggressive() -> str:
176
+ """Best-effort kill of branch pytest/subprocess trees (Modal gVisor fallback)."""
177
+ notes: list[str] = []
178
+ workspace = str(WORKSPACE)
179
+ patterns = list(_PKILL_PATTERNS) + [
180
+ f"pytest.*{workspace}",
181
+ f"xdist.*{workspace}",
182
+ ]
183
+ for pattern in patterns:
184
+ result = subprocess.run(
185
+ ["pkill", "-9", "-f", pattern],
186
+ capture_output=True,
187
+ text=True,
188
+ )
189
+ notes.append(f"pkill -9 -f {pattern!r}: rc={result.returncode}")
190
+ return "\n".join(notes)
191
+
192
+
193
+ def run_step(
194
+ command: str,
195
+ cwd: Path,
196
+ *,
197
+ timeout: int,
198
+ env: dict[str, str] | None = None,
199
+ step: str,
200
+ accept_failure: bool = False,
201
+ log_output: bool | None = None,
202
+ max_output_bytes: int = 65536,
203
+ ) -> dict[str, Any]:
204
+ if log_output is None:
205
+ log_output = step == "run_tests" or timeout >= 60
206
+
207
+ started = time.monotonic()
208
+ stdout_path: Path | None = None
209
+ stderr_path: Path | None = None
210
+ stdout_f = None
211
+ stderr_f = None
212
+
213
+ if log_output:
214
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
215
+ log_id = f"{step}-{int(started * 1000)}"
216
+ stdout_path = LOG_DIR / f"run-step-{log_id}.stdout.log"
217
+ stderr_path = LOG_DIR / f"run-step-{log_id}.stderr.log"
218
+ stdout_f = stdout_path.open("w", encoding="utf-8")
219
+ stderr_f = stderr_path.open("w", encoding="utf-8")
220
+ popen_stdout: Any = stdout_f
221
+ popen_stderr: Any = stderr_f
222
+ else:
223
+ popen_stdout = subprocess.PIPE
224
+ popen_stderr = subprocess.PIPE
225
+
226
+ proc = subprocess.Popen(
227
+ ["bash", "-lc", _bash_login_command(command)],
228
+ cwd=cwd,
229
+ env={**os.environ, **(env or {})},
230
+ stdout=popen_stdout,
231
+ stderr=popen_stderr,
232
+ start_new_session=True,
233
+ text=True,
234
+ )
235
+ timed_out = False
236
+ stdout = ""
237
+ stderr = ""
238
+ try:
239
+ if log_output:
240
+ proc.wait(timeout=timeout)
241
+ else:
242
+ stdout, stderr = proc.communicate(timeout=timeout)
243
+ except subprocess.TimeoutExpired:
244
+ timed_out = True
245
+ _terminate_process_tree(proc)
246
+ cleanup_lingering_processes(aggressive=True)
247
+ try:
248
+ proc.wait(timeout=5)
249
+ except subprocess.TimeoutExpired:
250
+ proc.kill()
251
+ if not log_output:
252
+ _close_pipes(proc)
253
+ finally:
254
+ if stdout_f is not None:
255
+ stdout_f.close()
256
+ if stderr_f is not None:
257
+ stderr_f.close()
258
+
259
+ if timed_out:
260
+ if log_output:
261
+ output = _read_log_tail(stdout_path, max_output_bytes) + _read_log_tail(
262
+ stderr_path, max_output_bytes
263
+ )
264
+ else:
265
+ output = ""
266
+ entry = {
267
+ "step": step,
268
+ "command": command,
269
+ "wall_time": time.monotonic() - started,
270
+ "output": output,
271
+ "returncode": 124,
272
+ "exception_info": f"timed out after {timeout}s",
273
+ }
274
+ else:
275
+ if log_output:
276
+ output = _read_log_tail(stdout_path, max_output_bytes) + _read_log_tail(
277
+ stderr_path, max_output_bytes
278
+ )
279
+ else:
280
+ output = stdout + stderr
281
+ entry = {
282
+ "step": step,
283
+ "command": command,
284
+ "wall_time": time.monotonic() - started,
285
+ "output": output,
286
+ "returncode": proc.returncode,
287
+ "exception_info": "",
288
+ }
289
+ if entry["returncode"] and not accept_failure:
290
+ raise RuntimeError(
291
+ f"{step} failed: {entry['exception_info'] or entry['output']}"
292
+ )
293
+ return entry
294
+
295
+
296
+ def cleanup_lingering_processes(*, aggressive: bool = False) -> dict[str, Any]:
297
+ started = time.monotonic()
298
+ patterns = [
299
+ str(WORKSPACE / "executable"),
300
+ f"{WORKSPACE}/eval/",
301
+ f"{WORKSPACE}/tests/",
302
+ # lazygit --logs/-l tests spawn `tail -f` outside /workspace/.
303
+ "tail -f",
304
+ "development.log",
305
+ ]
306
+ killed: list[int] = []
307
+ proc_root = Path("/proc")
308
+ proc_available = proc_root.exists()
309
+ if proc_available:
310
+ for proc_dir in proc_root.iterdir():
311
+ if not proc_dir.name.isdigit():
312
+ continue
313
+ pid = int(proc_dir.name)
314
+ if pid in {os.getpid(), os.getppid()}:
315
+ continue
316
+ try:
317
+ raw = (proc_dir / "cmdline").read_bytes()
318
+ except (FileNotFoundError, PermissionError, ProcessLookupError):
319
+ continue
320
+ cmdline = raw.replace(b"\0", b" ").decode(errors="replace")
321
+ if not any(pattern in cmdline for pattern in patterns):
322
+ continue
323
+ try:
324
+ os.kill(pid, signal.SIGKILL)
325
+ except (PermissionError, ProcessLookupError):
326
+ continue
327
+ killed.append(pid)
328
+ pkill_output = ""
329
+ if aggressive or not proc_available:
330
+ pkill_output = _pkill_aggressive()
331
+ output_parts = []
332
+ if killed:
333
+ output_parts.append("\n".join(str(pid) for pid in killed))
334
+ if pkill_output:
335
+ output_parts.append(pkill_output)
336
+ return {
337
+ "step": "cleanup_lingering_processes",
338
+ "command": "kill leftover branch processes referencing the workspace",
339
+ "wall_time": time.monotonic() - started,
340
+ "output": "\n".join(output_parts),
341
+ "returncode": 0,
342
+ "exception_info": "",
343
+ }
344
+
345
+
346
+ def extract_trusted_blob(tar_path: Path, dest: Path) -> None:
347
+ import tarfile
348
+
349
+ with tarfile.open(tar_path, "r:gz") as tf:
350
+ try:
351
+ tf.extractall(dest, filter="fully_trusted")
352
+ except TypeError:
353
+ tf.extractall(dest)
354
+
355
+
356
+ def find_results_xml() -> Path | None:
357
+ """Return the junit xml path if pytest wrote one."""
358
+ for candidate in (WORKSPACE / "eval" / "results.xml", WORKSPACE / "results.xml"):
359
+ if candidate.exists():
360
+ return candidate
361
+ return None
362
+
363
+
364
+ def remove_oracle_handoff_artifacts() -> list[str]:
365
+ """Drop oracle-agent handoff files from /workspace before snapshot/restore."""
366
+ removed: list[str] = []
367
+ for name in _ORACLE_HANDOFF_NAMES:
368
+ path = WORKSPACE / name
369
+ if path.exists():
370
+ if path.is_dir():
371
+ shutil.rmtree(path)
372
+ else:
373
+ path.unlink()
374
+ removed.append(name)
375
+ return removed
376
+
377
+
378
+ def _remove_tree(path: Path) -> None:
379
+ """Remove a file or directory tree, with a shell fallback for overlay races."""
380
+ if path.is_symlink() or path.is_file():
381
+ path.unlink(missing_ok=True)
382
+ return
383
+ if not path.is_dir():
384
+ path.unlink(missing_ok=True)
385
+ return
386
+ for attempt in range(3):
387
+ try:
388
+ shutil.rmtree(path)
389
+ if not path.exists():
390
+ return
391
+ except OSError:
392
+ if attempt == 2:
393
+ run_step(
394
+ f"rm -rf {shlex.quote(str(path))}",
395
+ path.parent,
396
+ timeout=120,
397
+ step="clear_workspace_fallback",
398
+ accept_failure=True,
399
+ )
400
+ if not path.exists():
401
+ return
402
+ raise
403
+
404
+
405
+ def ensure_workspace_dir() -> None:
406
+ """Guarantee WORKSPACE exists as a writable directory (not a symlink/file)."""
407
+ if WORKSPACE.exists() and not WORKSPACE.is_dir():
408
+ if WORKSPACE.is_symlink() or WORKSPACE.is_file():
409
+ WORKSPACE.unlink()
410
+ else:
411
+ shutil.rmtree(WORKSPACE)
412
+ WORKSPACE.mkdir(parents=True, exist_ok=True)
413
+
414
+
415
+ def clear_workspace() -> None:
416
+ ensure_workspace_dir()
417
+ for path in list(WORKSPACE.iterdir()):
418
+ _remove_tree(path)
419
+
420
+
421
+ def restore_reference_executable() -> None:
422
+ """Write the stashed reference binary into /workspace after a branch overlay.
423
+
424
+ Branch blobs may ship ``executable`` as a dangling symlink into
425
+ ``target/release/...``; ``shutil.copy2`` would follow it and raise
426
+ ``FileNotFoundError``. Drop whatever the blob left and copy the stashed
427
+ reference as a regular file.
428
+ """
429
+ ensure_workspace_dir()
430
+ if not STASHED_EXECUTABLE.is_file():
431
+ raise FileNotFoundError(
432
+ f"missing stashed reference executable at {STASHED_EXECUTABLE}"
433
+ )
434
+ dest = WORKSPACE / "executable"
435
+ if dest.exists() or dest.is_symlink():
436
+ if dest.is_dir():
437
+ shutil.rmtree(dest)
438
+ else:
439
+ dest.unlink(missing_ok=True)
440
+ shutil.copy2(STASHED_EXECUTABLE, dest)
441
+ dest.chmod(0o755)
442
+
443
+
444
+ def snapshot_workspace(dest: Path) -> None:
445
+ if dest.exists():
446
+ shutil.rmtree(dest)
447
+ shutil.copytree(WORKSPACE, dest, symlinks=True)
448
+
449
+
450
+ def restore_workspace(source: Path) -> None:
451
+ clear_workspace()
452
+ shutil.copytree(source, WORKSPACE, dirs_exist_ok=True, symlinks=True)
453
+ ensure_workspace_dir()
454
+
455
+
456
+ def remove_hashed_files(root: Path, hashes: set[str]) -> list[str]:
457
+ removed: list[str] = []
458
+ for path in root.rglob("*"):
459
+ if path.is_file() and not path.is_symlink():
460
+ try:
461
+ if sha256(path) in hashes:
462
+ path.unlink()
463
+ removed.append(str(path.relative_to(root)))
464
+ except OSError:
465
+ continue
466
+ return removed
467
+
468
+
469
+ def branch_tests(branch_info: dict[str, Any]) -> list[str]:
470
+ ignored = {
471
+ item["name"] for item in branch_info.get("ignored_tests", []) if "name" in item
472
+ }
473
+ return [name for name in branch_info.get("tests", []) if name not in ignored]
474
+
475
+
476
+ def ignored_tests(metadata: dict[str, Any]) -> set[str]:
477
+ result: set[str] = set()
478
+ for branch, info in metadata.get("branches", {}).items():
479
+ result.update(
480
+ f"{branch}/{item['name']}"
481
+ for item in info.get("ignored_tests", [])
482
+ if "name" in item
483
+ )
484
+ return result
485
+
486
+
487
+ def active_tests(metadata: dict[str, Any]) -> set[str]:
488
+ active: set[str] = set()
489
+ for branch, info in metadata.get("branches", {}).items():
490
+ if info.get("ignored"):
491
+ continue
492
+ ignored = {
493
+ item["name"] for item in info.get("ignored_tests", []) if "name" in item
494
+ }
495
+ active.update(
496
+ f"{branch}/{name}" for name in info.get("tests", []) if name not in ignored
497
+ )
498
+ return active
499
+
500
+
501
+ def inject_not_run(
502
+ result: dict[str, Any], branch: str, tests: list[str], error_code: str
503
+ ) -> None:
504
+ result["test_results"].extend(
505
+ {
506
+ "name": name,
507
+ "branch": branch,
508
+ "status": "not_run",
509
+ "extra": {"error_code": error_code},
510
+ }
511
+ for name in tests
512
+ )
513
+
514
+
515
+ def testcase_name(case: ET.Element) -> str:
516
+ classname = case.attrib.get("classname", "")
517
+ name = case.attrib.get("name", "")
518
+ return f"{classname}.{name}" if classname else name
519
+
520
+
521
+ # Only these tags under <testcase> represent a result. <system-out> /
522
+ # <system-err> are stdout/stderr captures and must not be treated as results
523
+ # (a leading <system-out> followed by <failure> would otherwise be classified
524
+ # as a stdout-only "passed").
525
+ JUNIT_RESULT_TAGS = {"skipped", "failure", "error"}
526
+
527
+
528
+ def parse_junit(
529
+ raw_xml: str, branch: str, expected: list[str], ignored: set[str]
530
+ ) -> tuple[list[dict[str, Any]], list[str]]:
531
+ root = ET.fromstring(raw_xml)
532
+ got: set[str] = set()
533
+ results: list[dict[str, Any]] = []
534
+ for case in root.iter("testcase"):
535
+ name = testcase_name(case)
536
+ got.add(name)
537
+ extra: dict[str, Any] = {}
538
+ if "time" in case.attrib:
539
+ try:
540
+ extra["time"] = float(case.attrib["time"])
541
+ except ValueError:
542
+ extra["time"] = case.attrib["time"]
543
+ result_children = [c for c in case if c.tag in JUNIT_RESULT_TAGS]
544
+ # Collapse duplicate same-tag result children. Pytest's
545
+ # "pytest.internal" pseudo-test sometimes emits two identical <error>
546
+ # entries; treating that as a system_error would over-flag a real
547
+ # single failure. Mirrors upstream eval.py:816-820.
548
+ if len(result_children) > 1 and len({c.tag for c in result_children}) == 1:
549
+ result_children = [result_children[0]]
550
+ if not result_children:
551
+ status = "passed"
552
+ elif len(result_children) != 1:
553
+ status = "system_error"
554
+ extra["error_details"] = (
555
+ f"Expected 1 result for {name}, got {len(result_children)}: "
556
+ f"{[c.tag for c in result_children]}"
557
+ )
558
+ else:
559
+ first = result_children[0]
560
+ status = first.tag # "skipped" | "failure" | "error"
561
+ extra["message"] = first.attrib.get("message") or ""
562
+ if first.text:
563
+ extra["text"] = first.text
564
+ results.append(
565
+ {"name": name, "branch": branch, "status": status, "extra": extra}
566
+ )
567
+
568
+ active_expected = [name for name in expected if name not in ignored]
569
+ missing = [name for name in active_expected if name not in got]
570
+ results.extend(
571
+ {
572
+ "name": name,
573
+ "branch": branch,
574
+ "status": "not_run",
575
+ "extra": {"error_code": "missing_from_junit_xml"},
576
+ }
577
+ for name in missing
578
+ )
579
+ unexpected = got - set(expected) - ignored
580
+ warnings = (
581
+ [f"Branch {branch}: {len(unexpected)} test(s) in JUnit XML not in tests.json"]
582
+ if unexpected
583
+ else []
584
+ )
585
+ return results, warnings
586
+
587
+
588
+ def count_worker_crashes(raw_xml: str) -> int:
589
+ if WORKER_CRASH_PHRASE not in raw_xml:
590
+ return 0
591
+ try:
592
+ root = ET.fromstring(raw_xml)
593
+ except ET.ParseError:
594
+ return 0
595
+ crashes = 0
596
+ for case in root.iter("testcase"):
597
+ for child in case:
598
+ text = (child.get("message") or "") + " " + (child.text or "")
599
+ if (
600
+ child.tag in {"error", "failure"}
601
+ and WORKER_CRASH_PHRASE in text
602
+ and "crashed" in text
603
+ ):
604
+ crashes += 1
605
+ break
606
+ return crashes
607
+
608
+
609
+ def run_output_indicates_xdist_collapse(output: str) -> bool:
610
+ lower = output.lower()
611
+ return any(marker in lower for marker in XDIST_COLLAPSE_MARKERS)
612
+
613
+
614
+ def count_junit_failures(raw_xml: str) -> int:
615
+ try:
616
+ root = ET.fromstring(raw_xml)
617
+ except ET.ParseError:
618
+ return 0
619
+ failures = 0
620
+ for case in root.iter("testcase"):
621
+ for child in case:
622
+ if child.tag in {"failure", "error"}:
623
+ failures += 1
624
+ break
625
+ return failures
626
+
627
+
628
+ def count_junit_passed(raw_xml: str) -> int:
629
+ try:
630
+ root = ET.fromstring(raw_xml)
631
+ except ET.ParseError:
632
+ return 0
633
+ passed = 0
634
+ for case in root.iter("testcase"):
635
+ if not any(child.tag in JUNIT_RESULT_TAGS for child in case):
636
+ passed += 1
637
+ return passed
638
+
639
+
640
+ def branch_attempt_metrics(
641
+ raw_xml: str, *, run_output: str, expected_tests: int
642
+ ) -> tuple[int, int, int, int]:
643
+ """Return (crashes, n_testcases, failures, missing_from_xml)."""
644
+ crashes = count_worker_crashes(raw_xml)
645
+ if run_output_indicates_xdist_collapse(run_output):
646
+ crashes = max(crashes, 1)
647
+ n_tests = count_testcases(raw_xml)
648
+ failures = count_junit_failures(raw_xml)
649
+ missing = max(0, expected_tests - n_tests)
650
+ return crashes, n_tests, failures, missing
651
+
652
+
653
+ def needs_serial_retry(
654
+ *,
655
+ serial: bool,
656
+ crashes: int,
657
+ missing: int,
658
+ failures: int,
659
+ n_tests: int,
660
+ expected_tests: int,
661
+ run_output: str,
662
+ ) -> bool:
663
+ if serial:
664
+ return False
665
+ high_failure_rate = (
666
+ expected_tests > 0 and n_tests >= expected_tests and failures / n_tests >= 0.8
667
+ )
668
+ return (
669
+ crashes > 0
670
+ or missing > 0
671
+ or high_failure_rate
672
+ or run_output_indicates_xdist_collapse(run_output)
673
+ )
674
+
675
+
676
+ def count_testcases(raw_xml: str) -> int:
677
+ try:
678
+ return sum(1 for _ in ET.fromstring(raw_xml).iter("testcase"))
679
+ except ET.ParseError:
680
+ return 0
681
+
682
+
683
+ def scored_results(
684
+ result: dict[str, Any], metadata: dict[str, Any]
685
+ ) -> list[dict[str, Any]]:
686
+ active = active_tests(metadata)
687
+ by_key = {
688
+ f"{test['branch']}/{test['name']}": test
689
+ for test in result["test_results"]
690
+ if f"{test['branch']}/{test['name']}" in active
691
+ }
692
+ return [
693
+ by_key.get(
694
+ key,
695
+ {
696
+ "branch": key.split("/", 1)[0],
697
+ "name": key.split("/", 1)[1],
698
+ "status": "not_run",
699
+ "extra": {"error_code": "missing_from_results"},
700
+ },
701
+ )
702
+ for key in sorted(active)
703
+ ]
704
+
705
+
706
+ def summarize(result: dict[str, Any], metadata: dict[str, Any]) -> dict[str, Any]:
707
+ scored = scored_results(result, metadata)
708
+ n_passed = sum(t["status"] == "passed" for t in scored)
709
+ n_tests = len(scored)
710
+ pass_rate = n_passed / n_tests if n_tests else 0.0
711
+ # Multi-key reward: Harbor's default Mean aggregates each key independently
712
+ # (see harbor.metrics.base.aggregate_reward_dicts), so mean("resolved") is
713
+ # the proportion of tasks scoring a perfect pass-rate and mean of
714
+ # "almost_resolved" is the proportion scoring >= 0.95. "reward" stays the
715
+ # per-task pass-rate whose mean is the overall mean reward.
716
+ return {
717
+ "reward": pass_rate,
718
+ "resolved": 1.0 if pass_rate >= 1.0 else 0.0,
719
+ "almost_resolved": 1.0 if pass_rate >= 0.95 else 0.0,
720
+ }
721
+
722
+
723
+ def diagnostics(result: dict[str, Any], metadata: dict[str, Any]) -> dict[str, Any]:
724
+ scored = scored_results(result, metadata)
725
+ n_passed = sum(t["status"] == "passed" for t in scored)
726
+ n_tests = len(scored)
727
+ pass_rate = n_passed / n_tests if n_tests else 0.0
728
+ return {
729
+ "pass_rate": pass_rate,
730
+ "resolved": int(
731
+ bool(
732
+ n_tests
733
+ and n_passed == n_tests
734
+ and not result["test_branch_errors"]
735
+ and not result["error_code"]
736
+ )
737
+ ),
738
+ "n_passed": n_passed,
739
+ "n_tests": n_tests,
740
+ "n_branch_errors": len(result["test_branch_errors"]),
741
+ "infra_error": int(bool(result["error_code"] or result["test_branch_errors"])),
742
+ "executable_hash_present": int(bool(result.get("executable_hash"))),
743
+ }
744
+
745
+
746
+ def use_script_pty() -> bool:
747
+ return os.environ.get("PROGRAMGYM_SCRIPT_PTY", "").strip() == "1"
748
+
749
+
750
+ def script_pty_available() -> bool:
751
+ return shutil.which("script") is not None
752
+
753
+
754
+ def branch_env(
755
+ *,
756
+ serial: bool,
757
+ has_rerunfailures: bool,
758
+ extras: dict[str, str] | None = None,
759
+ ) -> dict[str, str]:
760
+ addopts = ["--max-worker-restart=4"]
761
+ # A serial fallback is already a complete second execution. Re-running each
762
+ # failing test two more times makes large, failure-heavy suites prohibitively
763
+ # slow and adds little signal.
764
+ if has_rerunfailures and not serial:
765
+ addopts.extend(["--reruns=2", "--reruns-delay=1"])
766
+ env = {
767
+ "PYTEST_ADDOPTS": " ".join(addopts),
768
+ # Match upstream non-TTY regression environments (dirble log format, etc.).
769
+ "NO_COLOR": "1",
770
+ "TERM": "dumb",
771
+ "CLICOLOR": "0",
772
+ "CLICOLOR_FORCE": "0",
773
+ "COLORTERM": "",
774
+ }
775
+ if extras:
776
+ env.update(extras)
777
+ xdist_workers = os.environ.get("PROGRAMGYM_XDIST_WORKERS")
778
+ if serial:
779
+ xdist_workers = "1"
780
+ if xdist_workers:
781
+ env["PYTEST_XDIST_AUTO_NUM_WORKERS"] = xdist_workers
782
+ return env
783
+
784
+
785
+ _SERIAL_RUN_SH = ".programgym_run_serial.sh"
786
+ # ``eval/run.sh`` usually passes ``-n auto`` on the command line, which overrides
787
+ # ``PYTEST_ADDOPTS``. Rewrite to ``-n 0`` in a verifier-local copy for retries.
788
+ _RUN_SH_XDIST_RE = re.compile(r"-n\s*(?:auto|\d+)")
789
+
790
+
791
+ def prepare_serial_run_sh(run_sh: Path) -> Path:
792
+ """Write a serial-only copy of ``eval/run.sh`` with xdist disabled."""
793
+ serial_sh = run_sh.with_name(_SERIAL_RUN_SH)
794
+ patched = _RUN_SH_XDIST_RE.sub("-n 0", run_sh.read_text())
795
+ serial_sh.write_text(patched)
796
+ serial_sh.chmod(0o755)
797
+ return serial_sh
798
+
799
+
800
+ def run_tests_command(*, serial: bool) -> str:
801
+ if serial:
802
+ inner = f"chmod +x ./eval/{_SERIAL_RUN_SH} && ./eval/{_SERIAL_RUN_SH}"
803
+ else:
804
+ inner = "chmod +x ./eval/run.sh && ./eval/run.sh"
805
+ if use_script_pty() and script_pty_available():
806
+ return f"script -q -c {shlex.quote(inner)} /dev/null"
807
+ return inner
808
+
809
+
810
+ BAKED_BLOB_DIR = Path(os.environ.get("PROGRAMGYM_BAKED_BLOB_DIR", "/tests/blobs"))
811
+
812
+
813
+ def resolve_blob_dir(instance_id: str, metadata: dict[str, Any]) -> Path:
814
+ """Locate the per-instance blob directory.
815
+
816
+ Resolution order:
817
+
818
+ 1. ``/tests/blobs/`` if pre-fetched into the task at generation time
819
+ (``programgym-adapter --download-blobs``). Verifier-only mount, so
820
+ agent never sees these.
821
+ 2. ``PROGRAMGYM_BLOB_DIR`` env override pointing at an HF-cache-shaped
822
+ tree on disk (``<dir>/<instance_id>/tests/<branch>.tar.gz``). Useful
823
+ for offline reruns sharing a cache across many tasks.
824
+ 3. ``huggingface_hub.snapshot_download`` from
825
+ ``programgym/ProgramGym-Tests`` (default repo, ``main`` revision).
826
+
827
+ The returned directory contains ``tests/<branch>.tar.gz`` per active
828
+ branch — same shape as ``programgym/ProgramGym-Tests/<instance_id>/``
829
+ on HF.
830
+ """
831
+ if BAKED_BLOB_DIR.exists() and (BAKED_BLOB_DIR / "tests").exists():
832
+ return BAKED_BLOB_DIR
833
+
834
+ local = os.environ.get("PROGRAMGYM_BLOB_DIR", "").strip()
835
+ if local:
836
+ candidate = Path(local) / instance_id
837
+ if candidate.exists():
838
+ return candidate
839
+ raise FileNotFoundError(
840
+ f"PROGRAMGYM_BLOB_DIR set but {candidate} does not exist"
841
+ )
842
+
843
+ repo_id = os.environ.get("PROGRAMGYM_HF_REPO") or metadata.get(
844
+ "hf_repo_id", DEFAULT_HF_REPO_ID
845
+ )
846
+ revision = os.environ.get("PROGRAMGYM_HF_REVISION") or metadata.get(
847
+ "hf_revision", DEFAULT_HF_REVISION
848
+ )
849
+
850
+ from huggingface_hub import snapshot_download
851
+
852
+ cache_root = Path(
853
+ snapshot_download(
854
+ repo_id,
855
+ repo_type="dataset",
856
+ revision=revision,
857
+ allow_patterns=f"{instance_id}/**",
858
+ )
859
+ )
860
+ blob_dir = cache_root / instance_id
861
+ if not blob_dir.exists():
862
+ raise FileNotFoundError(
863
+ f"HF blob directory missing for {instance_id} at {blob_dir}"
864
+ )
865
+ return blob_dir
866
+
867
+
868
+ def evaluate(metadata: dict[str, Any]) -> dict[str, Any]:
869
+ bootstrap_toolchain_path()
870
+ branches = metadata.get("branches", {})
871
+ active_branch_items = [
872
+ (name, info) for name, info in branches.items() if not info.get("ignored")
873
+ ]
874
+ result: dict[str, Any] = {
875
+ "test_results": [],
876
+ "error_code": None,
877
+ "error_details": None,
878
+ "log": [],
879
+ "solution_branch": "submission",
880
+ "test_branches": [name for name, _ in active_branch_items],
881
+ "test_branch_errors": {},
882
+ "executable_hash": None,
883
+ "warnings": [],
884
+ }
885
+
886
+ instance_id = metadata["instance_id"]
887
+
888
+ compile_timeout = int(os.environ.get("PROGRAMGYM_COMPILE_TIMEOUT", "900"))
889
+ branch_timeout = int(os.environ.get("PROGRAMGYM_BRANCH_TIMEOUT", "3600"))
890
+
891
+ def fail_all(error_code: str, details: str) -> dict[str, Any]:
892
+ result["error_code"] = error_code
893
+ result["error_details"] = details
894
+ for branch, info in active_branch_items:
895
+ inject_not_run(result, branch, branch_tests(info), error_code)
896
+ return result
897
+
898
+ with tempfile.TemporaryDirectory(prefix="programgym-eval-") as tmp:
899
+ compiled_snapshot = Path(tmp) / "compiled"
900
+
901
+ started = time.monotonic()
902
+ removed = remove_hashed_files(
903
+ WORKSPACE, set(metadata.get("eval_clean_hashes", []))
904
+ )
905
+ result["log"].append(
906
+ {
907
+ "step": "remove_hashed_files",
908
+ "command": "remove files matching eval_clean_hashes",
909
+ "wall_time": time.monotonic() - started,
910
+ "output": "".join(f"removed '{path}'\n" for path in removed),
911
+ "returncode": 0,
912
+ "exception_info": "",
913
+ }
914
+ )
915
+
916
+ compile_sh = WORKSPACE / "compile.sh"
917
+ if not compile_sh.exists():
918
+ return fail_all(
919
+ "missing_compile_sh", "submission did not contain compile.sh"
920
+ )
921
+
922
+ seed = (
923
+ "if [ ! -d .git ]; then "
924
+ "GIT_AUTHOR_DATE='2000-01-01T00:00:00Z' "
925
+ "GIT_COMMITTER_DATE='2000-01-01T00:00:00Z' "
926
+ "git -c init.defaultBranch=gold init -q && "
927
+ "git -c user.email=gold@local -c user.name=gold -c commit.gpgsign=false add -A && "
928
+ "GIT_AUTHOR_DATE='2000-01-01T00:00:00Z' "
929
+ "GIT_COMMITTER_DATE='2000-01-01T00:00:00Z' "
930
+ "git -c user.email=gold@local -c user.name=gold -c commit.gpgsign=false commit -q --allow-empty -m gold; "
931
+ "fi"
932
+ )
933
+ try:
934
+ result["log"].append(
935
+ run_step(seed, WORKSPACE, timeout=300, step="seed_git")
936
+ )
937
+ compile_log = run_step(
938
+ "chmod +x ./compile.sh && ./compile.sh",
939
+ WORKSPACE,
940
+ timeout=compile_timeout,
941
+ step="compile",
942
+ accept_failure=True,
943
+ )
944
+ result["log"].append(compile_log)
945
+ if compile_log["returncode"]:
946
+ return fail_all("compile_failed", compile_log["output"])
947
+ executable = WORKSPACE / "executable"
948
+ if not executable.exists():
949
+ return fail_all(
950
+ "missing_executable",
951
+ "compile.sh completed but did not create ./executable",
952
+ )
953
+ STASHED_EXECUTABLE.parent.mkdir(parents=True, exist_ok=True)
954
+ # `move` (not copy) so /workspace doesn't keep a parallel copy of
955
+ # the agent's executable during the stash→restore window. Mirrors
956
+ # upstream `mv ./executable {STASHED}` (eval.py:472).
957
+ shutil.move(str(executable), STASHED_EXECUTABLE)
958
+ result["executable_hash"] = sha256(STASHED_EXECUTABLE)
959
+ result["log"].append(
960
+ run_step(
961
+ "pip3 install -q --disable-pip-version-check pytest-rerunfailures",
962
+ WORKSPACE,
963
+ timeout=120,
964
+ step="install_rerunfailures",
965
+ accept_failure=True,
966
+ )
967
+ )
968
+ has_rerunfailures = result["log"][-1]["returncode"] == 0
969
+ handoff_removed = remove_oracle_handoff_artifacts()
970
+ if handoff_removed:
971
+ result["log"].append(
972
+ {
973
+ "step": "remove_oracle_handoff",
974
+ "command": "remove oracle handoff artifacts from workspace",
975
+ "wall_time": 0.0,
976
+ "output": "".join(
977
+ f"removed '{name}'\n" for name in handoff_removed
978
+ ),
979
+ "returncode": 0,
980
+ "exception_info": "",
981
+ }
982
+ )
983
+ snapshot_workspace(compiled_snapshot)
984
+ except Exception as exc:
985
+ return fail_all(type(exc).__name__, str(exc))
986
+
987
+ try:
988
+ blob_dir = resolve_blob_dir(instance_id, metadata)
989
+ except Exception as exc:
990
+ details = f"{type(exc).__name__}: {exc}"
991
+ for branch, info in active_branch_items:
992
+ result["test_branch_errors"][branch] = [
993
+ {
994
+ "error_code": "blob_resolution_failed",
995
+ "error_details": details,
996
+ }
997
+ ]
998
+ inject_not_run(
999
+ result, branch, branch_tests(info), "blob_resolution_failed"
1000
+ )
1001
+ return result
1002
+
1003
+ for branch, info in active_branch_items:
1004
+ tests = branch_tests(info)
1005
+ blob = blob_dir / "tests" / f"{branch}.tar.gz"
1006
+ if not blob.exists():
1007
+ result["test_branch_errors"][branch] = [
1008
+ {"error_code": "missing_test_blob", "error_details": blob.name}
1009
+ ]
1010
+ inject_not_run(result, branch, tests, "missing_test_blob")
1011
+ continue
1012
+
1013
+ best_xml = ""
1014
+ # Prefer a complete, clean XML result, then the result covering the
1015
+ # most expected tests, and only then the one with the most passes.
1016
+ # Pass-count-only ranking can retain a partial xdist result over a
1017
+ # complete serial result.
1018
+ best_quality = (-1, -1, -1)
1019
+ serial = bool(metadata.get("force_serial_branches"))
1020
+ branch_log: list[dict[str, Any]] = []
1021
+ branch_ignored = {
1022
+ item["name"] for item in info.get("ignored_tests", []) if "name" in item
1023
+ }
1024
+ n_expected = len([name for name in tests if name not in branch_ignored])
1025
+
1026
+ def merge_best_xml(raw_xml: str) -> None:
1027
+ try:
1028
+ parsed, warnings = parse_junit(
1029
+ raw_xml, branch, list(info.get("tests", [])), branch_ignored
1030
+ )
1031
+ except Exception as exc:
1032
+ result["test_branch_errors"][branch] = [
1033
+ {"error_code": "xml_parse_error", "error_details": str(exc)}
1034
+ ]
1035
+ inject_not_run(result, branch, tests, "xml_parse_error")
1036
+ else:
1037
+ result["test_results"].extend(parsed)
1038
+ result["warnings"].extend(warnings)
1039
+
1040
+ while True:
1041
+ branch_log.append(cleanup_lingering_processes())
1042
+ restore_workspace(compiled_snapshot)
1043
+ extract_trusted_blob(blob, WORKSPACE)
1044
+ restore_reference_executable()
1045
+ actual_hash = sha256(WORKSPACE / "executable")
1046
+ if actual_hash != result["executable_hash"]:
1047
+ result["test_branch_errors"][branch] = [
1048
+ {
1049
+ "error_code": "executable_hash_mismatch",
1050
+ "error_details": (
1051
+ f"expected {result['executable_hash']}, got {actual_hash}"
1052
+ ),
1053
+ }
1054
+ ]
1055
+ inject_not_run(result, branch, tests, "executable_hash_mismatch")
1056
+ break
1057
+ run_sh = WORKSPACE / "eval" / "run.sh"
1058
+ if not run_sh.exists():
1059
+ result["test_branch_errors"][branch] = [
1060
+ {
1061
+ "error_code": "missing_run_sh",
1062
+ "error_details": "eval/run.sh missing",
1063
+ }
1064
+ ]
1065
+ inject_not_run(result, branch, tests, "missing_run_sh")
1066
+ break
1067
+ # Upstream rewrites thread→signal so xdist workers fail cleanly
1068
+ # instead of os._exit(1) on timeout. That works in fresh
1069
+ # containers per branch; here we reuse one container and
1070
+ # signal timeouts leave TUI/log-watcher subprocesses alive
1071
+ # (e.g. lazygit --logs + tail -f), wedging pytest for up to
1072
+ # branch_timeout. Keep the blob's thread method and rely on
1073
+ # cleanup_lingering_processes + serial fallback after crashes.
1074
+ env = branch_env(
1075
+ serial=serial,
1076
+ has_rerunfailures=has_rerunfailures,
1077
+ extras=metadata.get("branch_env"),
1078
+ )
1079
+ branch_log.append(
1080
+ run_step(
1081
+ "rm -f eval/results.xml results.xml",
1082
+ WORKSPACE,
1083
+ timeout=120,
1084
+ step="clean_stale_results",
1085
+ accept_failure=True,
1086
+ )
1087
+ )
1088
+ if serial:
1089
+ prepare_serial_run_sh(run_sh)
1090
+ run_entry = run_step(
1091
+ run_tests_command(serial=serial),
1092
+ WORKSPACE,
1093
+ timeout=branch_timeout,
1094
+ env=env,
1095
+ step="run_tests",
1096
+ accept_failure=True,
1097
+ )
1098
+ branch_log.append(run_entry)
1099
+ branch_log.append(cleanup_lingering_processes())
1100
+ xml_path = find_results_xml()
1101
+ if xml_path is None:
1102
+ if best_xml:
1103
+ merge_best_xml(best_xml)
1104
+ break
1105
+ if serial:
1106
+ result["test_branch_errors"][branch] = [
1107
+ {
1108
+ "error_code": "missing_results_xml",
1109
+ "error_details": "eval/results.xml was not produced",
1110
+ }
1111
+ ]
1112
+ inject_not_run(result, branch, tests, "missing_results_xml")
1113
+ break
1114
+ serial = True
1115
+ continue
1116
+ raw_xml = xml_path.read_text(errors="replace")
1117
+ crashes, n_tests, failures, missing = branch_attempt_metrics(
1118
+ raw_xml,
1119
+ run_output=run_entry.get("output", ""),
1120
+ expected_tests=n_expected,
1121
+ )
1122
+ useful = count_junit_passed(raw_xml)
1123
+ quality = (
1124
+ int(crashes == 0 and missing == 0),
1125
+ n_tests,
1126
+ useful,
1127
+ )
1128
+ if quality > best_quality:
1129
+ best_xml = raw_xml
1130
+ best_quality = quality
1131
+ retry = needs_serial_retry(
1132
+ serial=serial,
1133
+ crashes=crashes,
1134
+ missing=missing,
1135
+ failures=failures,
1136
+ n_tests=n_tests,
1137
+ expected_tests=n_expected,
1138
+ run_output=run_entry.get("output", ""),
1139
+ )
1140
+ if not retry:
1141
+ merge_best_xml(best_xml)
1142
+ break
1143
+ serial = True
1144
+ for entry in branch_log:
1145
+ entry["branch"] = branch
1146
+ result["log"].extend(branch_log)
1147
+
1148
+ return result
1149
+
1150
+
1151
+ def write_outputs(result: dict[str, Any], metadata: dict[str, Any]) -> None:
1152
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
1153
+ write_json(LOG_DIR / "programgym_eval.json", result)
1154
+ write_json(LOG_DIR / "harbor_diagnostics.json", diagnostics(result, metadata))
1155
+ rewards = summarize(result, metadata)
1156
+ write_json(LOG_DIR / "reward.json", rewards)
1157
+ (LOG_DIR / "reward.txt").write_text(str(rewards["reward"]))
1158
+
1159
+
1160
+ def main() -> None:
1161
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
1162
+ log_path = LOG_DIR / "programgym_eval.log"
1163
+ metadata = json.loads(METADATA_PATH.read_text())
1164
+ branches = metadata.get("branches", {})
1165
+ try:
1166
+ result = evaluate(metadata)
1167
+ except Exception as exc:
1168
+ error_code = type(exc).__name__
1169
+ result = {
1170
+ "test_results": [],
1171
+ "error_code": error_code,
1172
+ "error_details": str(exc),
1173
+ "log": [
1174
+ {
1175
+ "step": "evaluator_exception",
1176
+ "exception_info": traceback.format_exc(),
1177
+ "returncode": 1,
1178
+ }
1179
+ ],
1180
+ "solution_branch": "submission",
1181
+ "test_branches": [
1182
+ name for name, info in branches.items() if not info.get("ignored")
1183
+ ],
1184
+ "test_branch_errors": {
1185
+ "__evaluator__": [{"error_code": error_code, "error_details": str(exc)}]
1186
+ },
1187
+ "executable_hash": None,
1188
+ "warnings": [],
1189
+ }
1190
+ for branch, info in branches.items():
1191
+ if info.get("ignored"):
1192
+ continue
1193
+ inject_not_run(result, branch, branch_tests(info), error_code)
1194
+ log_path.write_text(traceback.format_exc())
1195
+ else:
1196
+ log_path.write_text("")
1197
+ write_outputs(result, metadata)
1198
+
1199
+
1200
+ if __name__ == "__main__":
1201
+ main()
mpostument--grafana-sync.0dd7ef8/tests/programgym_task.json ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "branches": {
3
+ "generated_module_01": {
4
+ "ignore_reason": "",
5
+ "ignored": false,
6
+ "ignored_tests": [],
7
+ "tests": [
8
+ "eval.tests.test_cli_dispatch.test_completion_dispatcher_shows_shell_subcommands",
9
+ "eval.tests.test_cli_dispatch.test_completion_script_generation_for_each_shell[bash]",
10
+ "eval.tests.test_cli_dispatch.test_completion_script_generation_for_each_shell[fish]",
11
+ "eval.tests.test_cli_dispatch.test_completion_script_generation_for_each_shell[powershell]",
12
+ "eval.tests.test_cli_dispatch.test_completion_script_generation_for_each_shell[zsh]",
13
+ "eval.tests.test_cli_dispatch.test_config_file_is_reported_when_used",
14
+ "eval.tests.test_cli_dispatch.test_default_url_directory_and_apikey_appear_in_help",
15
+ "eval.tests.test_cli_dispatch.test_each_subcommand_prints_its_own_help[pull-dashboards]",
16
+ "eval.tests.test_cli_dispatch.test_each_subcommand_prints_its_own_help[pull-datasources]",
17
+ "eval.tests.test_cli_dispatch.test_each_subcommand_prints_its_own_help[pull-folders]",
18
+ "eval.tests.test_cli_dispatch.test_each_subcommand_prints_its_own_help[pull-notifications]",
19
+ "eval.tests.test_cli_dispatch.test_each_subcommand_prints_its_own_help[push-dashboards]",
20
+ "eval.tests.test_cli_dispatch.test_each_subcommand_prints_its_own_help[push-datasources]",
21
+ "eval.tests.test_cli_dispatch.test_each_subcommand_prints_its_own_help[push-folders]",
22
+ "eval.tests.test_cli_dispatch.test_each_subcommand_prints_its_own_help[push-notifications]",
23
+ "eval.tests.test_cli_dispatch.test_empty_directory_value_still_dispatches_to_network",
24
+ "eval.tests.test_cli_dispatch.test_help_for_unknown_topic_reports_unknown_help_topic",
25
+ "eval.tests.test_cli_dispatch.test_help_word_targeting_subcommand_prints_subcommand_help",
26
+ "eval.tests.test_cli_dispatch.test_invalid_integer_flag_value_is_rejected",
27
+ "eval.tests.test_cli_dispatch.test_malformed_custom_headers_flag_is_rejected",
28
+ "eval.tests.test_cli_dispatch.test_missing_config_file_does_not_prevent_execution",
29
+ "eval.tests.test_cli_dispatch.test_root_help_is_printed_for_standard_dispatches[help_flag]",
30
+ "eval.tests.test_cli_dispatch.test_root_help_is_printed_for_standard_dispatches[help_short]",
31
+ "eval.tests.test_cli_dispatch.test_root_help_is_printed_for_standard_dispatches[help_word]",
32
+ "eval.tests.test_cli_dispatch.test_root_help_is_printed_for_standard_dispatches[no_args]",
33
+ "eval.tests.test_cli_dispatch.test_unknown_command_help_flag_still_reports_unknown_command",
34
+ "eval.tests.test_cli_dispatch.test_unknown_command_is_rejected_on_stdout_and_stderr",
35
+ "eval.tests.test_cli_dispatch.test_unknown_root_flag_is_rejected",
36
+ "eval.tests.test_cli_dispatch.test_version_flag_prints_version_and_exits_zero[--version]",
37
+ "eval.tests.test_cli_dispatch.test_version_flag_prints_version_and_exits_zero[-v]",
38
+ "eval.tests.test_cli_dispatch.test_version_flag_short_circuits_even_with_subcommand_arg",
39
+ "eval.tests.test_config_env.test_apikey_flag_overrides_environment",
40
+ "eval.tests.test_config_env.test_apikey_from_config_file_becomes_bearer_token",
41
+ "eval.tests.test_config_env.test_apikey_from_environment_becomes_bearer_token",
42
+ "eval.tests.test_config_env.test_custom_headers_flag_is_parsed_and_sent[X-A=one,X-B=two-X-B-two]",
43
+ "eval.tests.test_config_env.test_custom_headers_flag_is_parsed_and_sent[X-A=one-X-A-one]",
44
+ "eval.tests.test_config_env.test_custom_headers_flag_overrides_config_file",
45
+ "eval.tests.test_config_env.test_custom_headers_from_config_file_are_sent",
46
+ "eval.tests.test_config_env.test_no_apikey_means_no_authorization_header",
47
+ "eval.tests.test_subcommands.test_dashboards_folder_id_flag_accepted_on_push",
48
+ "eval.tests.test_subcommands.test_dashboards_folder_name_forces_folder_lookup[pull-dashboards]",
49
+ "eval.tests.test_subcommands.test_dashboards_folder_name_forces_folder_lookup[push-dashboards]",
50
+ "eval.tests.test_subcommands.test_pull_dashboards_default_folder_id_omits_folder_filter",
51
+ "eval.tests.test_subcommands.test_pull_dashboards_non_default_folder_id_filters_url",
52
+ "eval.tests.test_subcommands.test_pull_dashboards_tag_flag_filters_search_url",
53
+ "eval.tests.test_subcommands.test_pull_folders_creates_output_directory_for_pulled_results",
54
+ "eval.tests.test_subcommands.test_pull_subcommand_against_dead_server_fails_with_connection_refused[pull-dashboards]",
55
+ "eval.tests.test_subcommands.test_pull_subcommand_against_dead_server_fails_with_connection_refused[pull-datasources]",
56
+ "eval.tests.test_subcommands.test_pull_subcommand_against_dead_server_fails_with_connection_refused[pull-folders]",
57
+ "eval.tests.test_subcommands.test_pull_subcommand_against_dead_server_fails_with_connection_refused[pull-notifications]",
58
+ "eval.tests.test_subcommands.test_pull_subcommand_succeeds_against_mock_empty_server[pull-dashboards]",
59
+ "eval.tests.test_subcommands.test_pull_subcommand_succeeds_against_mock_empty_server[pull-datasources]",
60
+ "eval.tests.test_subcommands.test_pull_subcommand_succeeds_against_mock_empty_server[pull-folders]",
61
+ "eval.tests.test_subcommands.test_pull_subcommand_succeeds_against_mock_empty_server[pull-notifications]",
62
+ "eval.tests.test_subcommands.test_push_subcommand_succeeds_with_empty_directory[push-dashboards]",
63
+ "eval.tests.test_subcommands.test_push_subcommand_succeeds_with_empty_directory[push-datasources]",
64
+ "eval.tests.test_subcommands.test_push_subcommand_succeeds_with_empty_directory[push-folders]",
65
+ "eval.tests.test_subcommands.test_push_subcommand_succeeds_with_empty_directory[push-notifications]",
66
+ "eval.tests.test_subcommands.test_push_subcommand_with_json_fails_on_network[push-dashboards-error on importing dashboard]",
67
+ "eval.tests.test_subcommands.test_push_subcommand_with_json_fails_on_network[push-datasources-error on importing]",
68
+ "eval.tests.test_subcommands.test_push_subcommand_with_json_fails_on_network[push-folders-error on importing folder]",
69
+ "eval.tests.test_subcommands.test_push_subcommand_with_json_fails_on_network[push-notifications-error on importing notification]",
70
+ "eval.tests.test_subcommands.test_push_subcommand_with_nonexistent_directory_fails[push-dashboards]",
71
+ "eval.tests.test_subcommands.test_push_subcommand_with_nonexistent_directory_fails[push-datasources]",
72
+ "eval.tests.test_subcommands.test_push_subcommand_with_nonexistent_directory_fails[push-folders]",
73
+ "eval.tests.test_subcommands.test_push_subcommand_with_nonexistent_directory_fails[push-notifications]"
74
+ ]
75
+ },
76
+ "generated_module_02": {
77
+ "ignore_reason": "",
78
+ "ignored": false,
79
+ "ignored_tests": [],
80
+ "tests": [
81
+ "eval.tests.test_cli_reachability.test_config_file_accepted",
82
+ "eval.tests.test_cli_reachability.test_config_nonexistent_still_runs",
83
+ "eval.tests.test_cli_reachability.test_directory_flag_defaults_to_current_dir",
84
+ "eval.tests.test_cli_reachability.test_extra_positional_ignored",
85
+ "eval.tests.test_cli_reachability.test_help_flag",
86
+ "eval.tests.test_cli_reachability.test_help_subcommand",
87
+ "eval.tests.test_cli_reachability.test_malformed_url",
88
+ "eval.tests.test_cli_reachability.test_pull_folders_help_flags",
89
+ "eval.tests.test_cli_reachability.test_unknown_flag",
90
+ "eval.tests.test_cli_reachability.test_unknown_subcommand",
91
+ "eval.tests.test_cli_reachability.test_unreachable_host_exits_nonzero",
92
+ "eval.tests.test_cli_reachability.test_url_flag_overrides_default",
93
+ "eval.tests.test_cli_reachability.test_version_flag",
94
+ "eval.tests.test_common_writefile.test_dashboard_no_tag_writes_root",
95
+ "eval.tests.test_common_writefile.test_dashboard_tag_subdirectory_written",
96
+ "eval.tests.test_common_writefile.test_datasource_file_written",
97
+ "eval.tests.test_common_writefile.test_directory_auto_created",
98
+ "eval.tests.test_common_writefile.test_empty_result_no_files",
99
+ "eval.tests.test_common_writefile.test_execution_error_flagged_on_partial_failure",
100
+ "eval.tests.test_common_writefile.test_existing_files_preserved",
101
+ "eval.tests.test_common_writefile.test_file_content_is_parsable_json",
102
+ "eval.tests.test_common_writefile.test_file_permission_user_rw",
103
+ "eval.tests.test_common_writefile.test_folder_file_written",
104
+ "eval.tests.test_common_writefile.test_multiple_folders_multiple_files",
105
+ "eval.tests.test_common_writefile.test_notification_file_written",
106
+ "eval.tests.test_common_writefile.test_tag_subdir_with_nested_parent",
107
+ "eval.tests.test_http_client.test_apikey_sets_authorization",
108
+ "eval.tests.test_http_client.test_custom_header_on_each_request",
109
+ "eval.tests.test_http_client.test_custom_header_value_preservation[X-Header= committed -committed]",
110
+ "eval.tests.test_http_client.test_custom_header_value_preservation[X-Header=---]",
111
+ "eval.tests.test_http_client.test_custom_header_value_preservation[X-Header=Bearer token with spaces-Bearer token with spaces]",
112
+ "eval.tests.test_http_client.test_custom_header_value_preservation[X-Header=a=b=c-a=b=c]",
113
+ "eval.tests.test_http_client.test_custom_header_value_preservation[X-Header=value-with-dashes_underscores-value-with-dashes_underscores]",
114
+ "eval.tests.test_http_client.test_custom_header_with_api_key_both_present",
115
+ "eval.tests.test_http_client.test_empty_custom_headers_value_rejected",
116
+ "eval.tests.test_http_client.test_multiple_custom_headers",
117
+ "eval.tests.test_http_client.test_no_custom_headers_when_none_set",
118
+ "eval.tests.test_http_client.test_single_custom_header",
119
+ "eval.tests.test_http_client.test_system_headers_preserved"
120
+ ]
121
+ },
122
+ "generated_module_03": {
123
+ "ignore_reason": "",
124
+ "ignored": false,
125
+ "ignored_tests": [],
126
+ "tests": [
127
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_connection_refused",
128
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_creates_missing_output_dir",
129
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_default_folder_is_minus_one",
130
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_empty_search_no_files",
131
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_file_is_valid_json",
132
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_folder_filter_appears_in_search",
133
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_folder_name_lookup_error",
134
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_folder_name_not_found_pulls_root",
135
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_folder_name_resolves_id",
136
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_malformed_url",
137
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_multiple_boards",
138
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_partial_error_keeps_files_exits_one",
139
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_search_http_error",
140
+ "eval.tests.test_pull_dashboards.test_pull_dashboard_tag_subdirectory",
141
+ "eval.tests.test_pull_folders.test_pull_folders_empty",
142
+ "eval.tests.test_pull_folders.test_pull_folders_http_error",
143
+ "eval.tests.test_pull_folders.test_pull_folders_malformed_url",
144
+ "eval.tests.test_pull_folders.test_pull_folders_multiple",
145
+ "eval.tests.test_pull_folders.test_pull_folders_writes_folder_file",
146
+ "eval.tests.test_push_dashboards.test_push_dashboard_default_folder_is_zero",
147
+ "eval.tests.test_push_dashboards.test_push_dashboard_empty_directory",
148
+ "eval.tests.test_push_dashboards.test_push_dashboard_folder_name_lookup_error",
149
+ "eval.tests.test_push_dashboards.test_push_dashboard_folder_name_resolves_id",
150
+ "eval.tests.test_push_dashboards.test_push_dashboard_ignores_non_json",
151
+ "eval.tests.test_push_dashboards.test_push_dashboard_invalid_json_exits_one",
152
+ "eval.tests.test_push_dashboards.test_push_dashboard_multiple_files",
153
+ "eval.tests.test_push_dashboards.test_push_dashboard_nonexistent_directory",
154
+ "eval.tests.test_push_dashboards.test_push_dashboard_posts_valid_body",
155
+ "eval.tests.test_push_dashboards.test_push_dashboard_upload_server_error_crashes",
156
+ "eval.tests.test_push_folders.test_push_folder_create_error_exits_one",
157
+ "eval.tests.test_push_folders.test_push_folder_creates_folder",
158
+ "eval.tests.test_push_folders.test_push_folder_empty_directory",
159
+ "eval.tests.test_push_folders.test_push_folder_ignores_non_json",
160
+ "eval.tests.test_push_folders.test_push_folder_invalid_json_exits_one",
161
+ "eval.tests.test_push_folders.test_push_folder_nonexistent_directory"
162
+ ]
163
+ },
164
+ "generated_module_04": {
165
+ "ignore_reason": "",
166
+ "ignored": false,
167
+ "ignored_tests": [],
168
+ "tests": [
169
+ "eval.tests.test_cli.test_pull_notifications_defaults_to_current_dir_on_success",
170
+ "eval.tests.test_cli.test_pull_notifications_help_mentions_directory_flag",
171
+ "eval.tests.test_cli.test_push_datasources_help_mentions_directory_flag",
172
+ "eval.tests.test_cli.test_root_help_lists_sync_subcommands",
173
+ "eval.tests.test_cli.test_unknown_flag_is_rejected",
174
+ "eval.tests.test_cli.test_version_prints_version_string",
175
+ "eval.tests.test_datasources.test_pull_datasources_bad_json_response_aborts",
176
+ "eval.tests.test_datasources.test_pull_datasources_connection_refused_fails",
177
+ "eval.tests.test_datasources.test_pull_datasources_empty_list_writes_nothing",
178
+ "eval.tests.test_datasources.test_pull_datasources_http_500_aborts_with_error",
179
+ "eval.tests.test_datasources.test_pull_datasources_malformed_url_fails",
180
+ "eval.tests.test_datasources.test_pull_datasources_sends_bearer_apikey_header",
181
+ "eval.tests.test_datasources.test_pull_datasources_writes_one_json_file_per_datasource",
182
+ "eval.tests.test_datasources.test_push_datasources_bad_json_file_marks_execution_error",
183
+ "eval.tests.test_datasources.test_push_datasources_create_api_error_sets_exit_nonzero",
184
+ "eval.tests.test_datasources.test_push_datasources_nonexistent_directory_fails",
185
+ "eval.tests.test_datasources.test_push_datasources_posts_each_valid_json_file",
186
+ "eval.tests.test_datasources.test_push_datasources_skips_non_json_files",
187
+ "eval.tests.test_notifications.test_pull_notifications_bad_json_response_aborts",
188
+ "eval.tests.test_notifications.test_pull_notifications_connection_refused_fails",
189
+ "eval.tests.test_notifications.test_pull_notifications_creates_nested_directory",
190
+ "eval.tests.test_notifications.test_pull_notifications_empty_list_writes_nothing",
191
+ "eval.tests.test_notifications.test_pull_notifications_file_content_is_pretty_printed_json",
192
+ "eval.tests.test_notifications.test_pull_notifications_http_500_aborts_with_error",
193
+ "eval.tests.test_notifications.test_pull_notifications_malformed_url_fails",
194
+ "eval.tests.test_notifications.test_pull_notifications_notification_without_name_writes_dotjson",
195
+ "eval.tests.test_notifications.test_pull_notifications_sends_bearer_apikey_header",
196
+ "eval.tests.test_notifications.test_pull_notifications_writes_one_json_file_per_notification",
197
+ "eval.tests.test_notifications.test_push_notifications_bad_json_file_marks_execution_error",
198
+ "eval.tests.test_notifications.test_push_notifications_create_api_error_sets_exit_nonzero",
199
+ "eval.tests.test_notifications.test_push_notifications_empty_directory_is_noop_success",
200
+ "eval.tests.test_notifications.test_push_notifications_nonexistent_directory_fails",
201
+ "eval.tests.test_notifications.test_push_notifications_posts_each_valid_json_file",
202
+ "eval.tests.test_notifications.test_push_notifications_skips_non_json_files"
203
+ ]
204
+ }
205
+ },
206
+ "commit": "0dd7ef88aaebebf92f3757907e572464aee2dd25",
207
+ "data_source": "synthetic_programgym",
208
+ "difficulty": "easy",
209
+ "difficulty_score": 1.561101383649056,
210
+ "eval_clean_hashes": [
211
+ "3feaa0a4c2b4a886cc4737971168e141bcf85da19a63d689e552a781e07f8070"
212
+ ],
213
+ "input_record": {
214
+ "commit": "0dd7ef88aaebebf92f3757907e572464aee2dd25",
215
+ "commits": 99,
216
+ "contributors": 7,
217
+ "difficulty": "easy",
218
+ "difficulty_code_lines": 728,
219
+ "difficulty_has_tests": false,
220
+ "difficulty_product_code_lines": 728,
221
+ "difficulty_runtime_deps": 4,
222
+ "difficulty_score": 1.561101383649056,
223
+ "difficulty_test_code_lines": 0,
224
+ "full_name": "mpostument/grafana-sync",
225
+ "github_stars": 218,
226
+ "input_joern_zip": "go_joern/mpostument__grafana-sync.zip",
227
+ "joern_status": true,
228
+ "joern_time": 14.19520522793755,
229
+ "language": "go",
230
+ "pb_match": [
231
+ {
232
+ "pb_fullname": "rs/jplot",
233
+ "rank": 69,
234
+ "similarity": 0.5859704613685608
235
+ },
236
+ {
237
+ "pb_fullname": "ariga/atlas",
238
+ "rank": 527,
239
+ "similarity": 0.514390766620636
240
+ }
241
+ ],
242
+ "repo_age": 5.62,
243
+ "repo_path": "go/mpostument__grafana-sync",
244
+ "source": "commit:0dd7ef88aaebebf92f3757907e572464aee2dd25",
245
+ "status": "done",
246
+ "url": "https://github.com/mpostument/grafana-sync"
247
+ },
248
+ "instance_id": "mpostument__grafana-sync.0dd7ef8",
249
+ "language": "go",
250
+ "module_iterations": [
251
+ {
252
+ "actual_iterations": 2,
253
+ "branch_name": "generated_module_01",
254
+ "iteration_limit": 5,
255
+ "module_index": 1,
256
+ "module_kind": "source",
257
+ "termination_reason": "module_coverage_threshold_reached"
258
+ },
259
+ {
260
+ "actual_iterations": 3,
261
+ "branch_name": "generated_module_02",
262
+ "iteration_limit": 5,
263
+ "module_index": 2,
264
+ "module_kind": "source",
265
+ "termination_reason": "module_coverage_threshold_reached"
266
+ },
267
+ {
268
+ "actual_iterations": 1,
269
+ "branch_name": "generated_module_03",
270
+ "iteration_limit": 5,
271
+ "module_index": 3,
272
+ "module_kind": "source",
273
+ "termination_reason": "module_coverage_threshold_reached"
274
+ },
275
+ {
276
+ "actual_iterations": 2,
277
+ "branch_name": "generated_module_04",
278
+ "iteration_limit": 5,
279
+ "module_index": 4,
280
+ "module_kind": "source",
281
+ "termination_reason": "module_coverage_threshold_reached"
282
+ }
283
+ ],
284
+ "repository": "mpostument/grafana-sync"
285
+ }
mpostument--grafana-sync.0dd7ef8/tests/test.sh ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ # Verifier exec may not inherit image ENV (Modal/gVisor, login-shell resets).
5
+ export PATH="/usr/local/go/bin:/go/bin:/usr/local/cargo/bin:/root/.cargo/bin:${PATH}"
6
+
7
+ mkdir -p /logs/verifier /logs/artifacts
8
+
9
+ write_failure() {
10
+ local code="$1"
11
+ local details="$2"
12
+ python3 - "$code" "$details" <<'PY'
13
+ import json
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ code, details = sys.argv[1:3]
18
+ try:
19
+ metadata = json.loads(Path("/tests/programgym_task.json").read_text())
20
+ n_tests = sum(
21
+ len([
22
+ name for name in info.get("tests", [])
23
+ if name not in {item.get("name") for item in info.get("ignored_tests", [])}
24
+ ])
25
+ for branch, info in metadata.get("branches", {}).items()
26
+ if not info.get("ignored")
27
+ )
28
+ except Exception:
29
+ n_tests = 0
30
+ result = {
31
+ "test_results": [],
32
+ "error_code": code,
33
+ "error_details": details,
34
+ "log": [],
35
+ "solution_branch": "submission",
36
+ "test_branches": [],
37
+ "test_branch_errors": {
38
+ "__infra__": [{"error_code": code, "error_details": details}]
39
+ },
40
+ "executable_hash": None,
41
+ "warnings": [],
42
+ }
43
+ diagnostics = {
44
+ "pass_rate": 0.0,
45
+ "resolved": 0,
46
+ "n_passed": 0,
47
+ "n_tests": n_tests,
48
+ "n_branch_errors": 1,
49
+ "infra_error": 1,
50
+ "executable_hash_present": 0,
51
+ }
52
+ Path("/logs/verifier/programgym_eval.json").write_text(
53
+ json.dumps(result, indent=2, sort_keys=True)
54
+ )
55
+ Path("/logs/verifier/harbor_diagnostics.json").write_text(
56
+ json.dumps(diagnostics, indent=2, sort_keys=True)
57
+ )
58
+ Path("/logs/verifier/reward.json").write_text(
59
+ json.dumps(
60
+ {"reward": 0.0, "resolved": 0.0, "almost_resolved": 0.0},
61
+ indent=2,
62
+ sort_keys=True,
63
+ )
64
+ )
65
+ Path("/logs/verifier/reward.txt").write_text("0.0")
66
+ Path("/logs/verifier/programgym_eval.log").write_text(details)
67
+ PY
68
+ }
69
+
70
+ if ! command -v python3 >/dev/null 2>&1; then
71
+ write_failure "missing_python3" "python3 is required in the cleanroom image"
72
+ exit 0
73
+ fi
74
+
75
+ if ! python3 /tests/programgym_evaluator.py; then
76
+ if [ ! -s /logs/verifier/reward.txt ]; then
77
+ write_failure "evaluator_crashed" \
78
+ "programgym_evaluator.py exited non-zero with no reward written"
79
+ fi
80
+ fi
81
+
82
+ exit 0
mpostument--grafana-sync.0dd7ef8/tests/workspace.tar.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33c7a496f7c7c5cb0c1c11d5d3d25a07e90f6130db19d6bb29c478ae80de70c5
3
+ size 84170
mptre--yank.b9f76bc/environment/Dockerfile ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ubuntu:22.04
2
+ ENV DEBIAN_FRONTEND=noninteractive
3
+ ENV RUSTUP_DIST_SERVER="https://static.rust-lang.org"
4
+ ENV RUSTUP_UPDATE_ROOT="https://static.rust-lang.org/rustup"
5
+ ENV CARGO_REGISTRIES_CRATES_IO_PROTOCOL=sparse
6
+ ENV CARGO_REGISTRIES_CRATES_IO_INDEX="sparse+https://index.crates.io/"
7
+ ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
8
+ ENV GOPROXY="https://proxy.golang.org,direct"
9
+ ENV GOSUMDB=sum.golang.google.cn
10
+ ENV GOTOOLCHAIN=auto
11
+ ENV UV_INSECURE_HOST=""
12
+ ENV UV_INDEX_URL="https://pypi.org/simple"
13
+ ENV UV_CACHE_DIR=/workspace/.cache/uv
14
+ ENV npm_config_registry="https://registry.npmjs.org/"
15
+ ENV npm_config_strict_ssl=false
16
+ ENV npm_config_cache=/workspace/.cache/npm
17
+ ENV PIP_INDEX_URL="https://pypi.org/simple"
18
+ ENV PIP_TRUSTED_HOST=""
19
+ ENV HOME=/workspace
20
+ ENV XDG_CACHE_HOME=/workspace/.cache
21
+ ENV PIP_CACHE_DIR=/workspace/.cache/pip
22
+ ENV PYTHONUSERBASE=/workspace/.local
23
+ ENV PAGER=cat
24
+ ENV MANPAGER=cat
25
+ ENV LESS=-R
26
+ ENV TQDM_DISABLE=1
27
+ RUN apt-get update && apt-get install -y --no-install-recommends bash build-essential ca-certificates git make pkg-config python3 python3-pip python3-dev autoconf automake gettext file binutils libtool libncurses-dev meson ninja-build python3-pytest python3-pytest-xdist python3-coverage && rm -rf /var/lib/apt/lists/*
28
+ ARG CMAKE_VERSION=3.31.10
29
+ ARG CMAKE_PYPI_INDEX_URL=https://pypi.org/simple
30
+ RUN set -eux; python3 -m pip install --no-cache-dir --index-url "${CMAKE_PYPI_INDEX_URL}" --trusted-host "mirror.example.invalid" "cmake==${CMAKE_VERSION}"; cmake --version; ctest --version; cpack --version
31
+ # programgym_quota_aware_nproc=1
32
+ RUN set -eux; printf '%s\n' '#!/bin/sh' 'if [ "$#" -gt 0 ]; then exec /usr/bin/nproc "$@"; fi' 'visible="$(/usr/bin/nproc)"' 'quota=""' 'period=""' 'if [ -r /sys/fs/cgroup/cpu.max ]; then' ' set -- $(cat /sys/fs/cgroup/cpu.max)' ' quota="${1:-}"' ' period="${2:-}"' 'elif [ -r /sys/fs/cgroup/cpu/cpu.cfs_quota_us ] && [ -r /sys/fs/cgroup/cpu/cpu.cfs_period_us ]; then' ' quota="$(cat /sys/fs/cgroup/cpu/cpu.cfs_quota_us)"' ' period="$(cat /sys/fs/cgroup/cpu/cpu.cfs_period_us)"' fi 'if [ -n "$quota" ] && [ "$quota" != max ] && [ "$quota" -gt 0 ] 2>/dev/null && [ "$period" -gt 0 ] 2>/dev/null; then' ' limit=$(( (quota + period - 1) / period ))' ' if [ "$limit" -lt 1 ]; then limit=1; fi' ' if [ "$limit" -lt "$visible" ]; then visible="$limit"; fi' fi 'printf "%s\n" "$visible"' > /usr/local/bin/nproc; chmod 0755 /usr/local/bin/nproc; /usr/local/bin/nproc >/dev/null
33
+ WORKDIR /workspace
34
+ ADD workspace.tar.gz /workspace/
35
+ COPY executable /workspace/executable
36
+ COPY download.sh /workspace/download.sh
37
+ RUN chmod 755 /workspace/download.sh
38
+ COPY harbor_prepare_download_env.sh /tmp/harbor_prepare_download_env.sh
39
+ RUN chmod 755 /tmp/harbor_prepare_download_env.sh \
40
+ && /bin/bash /tmp/harbor_prepare_download_env.sh \
41
+ && rm -f /workspace/download.sh \
42
+ && rm -f /tmp/harbor_prepare_download_env.sh
43
+ ENV BASH_ENV=/etc/profile.d/programgym_download_env.sh
44
+ RUN chmod 111 /workspace/executable
45
+ WORKDIR /workspace
46
+ # Harbor synthetic ProgramGym adapter: run the agent as an unprivileged user.
47
+ # Keep tool/runtime state under /home/agent and reserve /workspace for the
48
+ # submission handed to the separate verifier. Keep the reference executable
49
+ # execute-only; the oracle temporarily restores owner read permission.
50
+ RUN id -u agent >/dev/null 2>&1 || useradd -m -s /bin/bash agent
51
+ RUN mkdir -p /home/agent \
52
+ && chown -R agent:agent /home/agent /workspace \
53
+ && chown agent:agent /workspace/executable \
54
+ && chmod 111 /workspace/executable
55
+ ENV HOME=/home/agent
56
+ WORKDIR /workspace
mptre--yank.b9f76bc/environment/download.sh ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ #
3
+ # yank (mptre/yank): download stage.
4
+ #
5
+ # The offline build needs only a C toolchain and make, plus the standard C
6
+ # library headers. Everything required is already present in the base image
7
+ # (the default C toolchain and build-essential): yank.c links only against
8
+ # libc and depends on no third-party library. Therefore this stage has nothing
9
+ # to fetch and only exports the directory in which the offline build will run.
10
+ # It performs no compilation, linking, or test steps.
11
+ #
12
+ # This file is meant to be sourced (`source /source_ro/download.sh`), so it
13
+ # must not `exit` in normal control flow and must not rely on positional
14
+ # arguments.
15
+ #
16
+ # No repository build files (Makefile, source files) and no dependency
17
+ # manifests are read here; no dependency metadata is needed.
18
+
19
+ # The offline build stage copies the repository into /workspace/source and runs
20
+ # build.sh there. Export the working directory so build.sh inherits it.
21
+ export WORKSPACE_SOURCE="${WORKSPACE_SOURCE:-/workspace/source}"
22
+
23
+ # No packages or archives need to be downloaded: the dependencies (C toolchain,
24
+ # make, and the standard C library) are provided by the base image.