File size: 15,488 Bytes
d086025 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 | from __future__ import annotations
import hashlib
import json
import os
import shutil
import subprocess
import tarfile
import tempfile
import traceback
import xml.etree.ElementTree as ET
from pathlib import Path
TESTS = Path("/tests")
ARTIFACT = Path("/logs/artifacts/submission.tar.gz")
RESULTS_DIR = Path("/logs/verifier")
REWARD = RESULTS_DIR / "reward.txt"
def sha256(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def safe_extract(tar_path: Path, dest: Path) -> None:
with tarfile.open(tar_path, "r:gz") as tf:
dest_resolved = dest.resolve()
for member in tf.getmembers():
member_path = (dest / member.name).resolve()
try:
member_path.relative_to(dest_resolved)
except ValueError as exc:
raise RuntimeError(f"unsafe tar member: {member.name}") from exc
tf.extractall(dest, filter="data")
def load_reference_hashes() -> set[str]:
path = TESTS / "hashes.txt"
if not path.exists():
return set()
return {line.strip() for line in path.read_text().splitlines() if line.strip()}
def remove_reference_binaries(workspace: Path, hashes: set[str]) -> None:
if not hashes:
return
for path in workspace.rglob("*"):
if path.is_file():
try:
if sha256(path) in hashes:
path.unlink()
except OSError:
pass
def run_cmd(args: list[str], cwd: Path, timeout: int = 120) -> subprocess.CompletedProcess[str]:
return subprocess.run(args, cwd=cwd, text=True, capture_output=True, timeout=timeout)
def compile_submission(workspace: Path) -> tuple[bool, str]:
compile_sh = workspace / "compile.sh"
if not compile_sh.exists():
return False, "missing compile.sh"
compile_sh.chmod(0o755)
proc = run_cmd(["bash", "compile.sh"], cwd=workspace, timeout=300)
if proc.returncode != 0:
return False, proc.stdout + proc.stderr
executable = workspace / "executable"
if not executable.exists():
return False, "compile.sh did not produce ./executable"
executable.chmod(0o755)
return True, proc.stdout + proc.stderr
def reset_workspace(workspace: Path) -> None:
workspace.mkdir(parents=True, exist_ok=True)
for child in workspace.iterdir():
if child.is_dir() and not child.is_symlink():
shutil.rmtree(child)
else:
child.unlink()
def tag_name(tag: str) -> str:
return tag.rsplit("}", 1)[-1]
def parse_junit(path: Path) -> list[dict]:
if not path.exists():
return []
root = ET.parse(path).getroot()
results = []
for case in root.iter():
if tag_name(case.tag) != "testcase":
continue
classname = case.attrib.get("classname", "")
name = case.attrib.get("name", "")
test_id = f"{classname}.{name}" if classname else name
outcomes = {
tag_name(child.tag)
for child in list(case)
if tag_name(child.tag) in {"failure", "error", "skipped"}
}
results.append(
{
"name": test_id,
"passed": not outcomes,
"outcomes": sorted(outcomes),
}
)
return results
def configured_test_names(items: object) -> list[str]:
if not isinstance(items, list):
return []
names = []
for item in items:
if isinstance(item, str):
name = item
elif isinstance(item, dict):
name = item.get("name") or item.get("id")
else:
name = None
if name:
names.append(str(name))
return list(dict.fromkeys(names))
def canonical_test_id(test_id: str) -> str:
if test_id.startswith("eval.tests."):
return "tests." + test_id.removeprefix("eval.tests.")
return test_id
def test_ids_match(actual: str, expected: str) -> bool:
actual = canonical_test_id(actual)
expected = canonical_test_id(expected)
if actual == expected:
return True
return actual.endswith("." + expected) or expected.endswith("." + actual)
def lookup_test_result(results: list[dict], test_id: str) -> dict | None:
matches = [
result
for result in results
if test_ids_match(str(result.get("name", "")), test_id)
]
if not matches:
return None
canonical_names = {
canonical_test_id(str(result.get("name", ""))) for result in matches
}
if len(canonical_names) > 1:
names = sorted(str(result.get("name", "")) for result in matches)
raise ValueError(f"ambiguous test id {test_id!r}: {names}")
if len(matches) == 1:
return matches[0]
return {
"name": next(iter(canonical_names)),
"passed": all(result.get("passed", False) for result in matches),
"outcomes": sorted(
{
outcome
for result in matches
for outcome in result.get("outcomes", [])
}
),
"multiplicity": len(matches),
}
def score_branch(path: Path, branch_meta: dict) -> dict:
raw_results = parse_junit(path)
active_tests = configured_test_names(branch_meta.get("tests"))
ignored_tests = configured_test_names(branch_meta.get("ignored_tests"))
scored_results = [
result
for result in raw_results
if not any(
test_ids_match(str(result.get("name", "")), ignored)
for ignored in ignored_tests
)
]
matched_results = {
test_id: lookup_test_result(scored_results, test_id)
for test_id in active_tests
}
missing_tests = [
test_id for test_id, result in matched_results.items() if result is None
]
unexpected_tests = [
str(result.get("name", ""))
for result in scored_results
if not any(
test_ids_match(str(result.get("name", "")), expected)
for expected in active_tests
)
]
passed = sum(
1
for result in matched_results.values()
if result is not None and result.get("passed", False)
)
return {
"passed": passed,
"matched_total": len(active_tests) - len(missing_tests),
"total": len(active_tests),
"raw_total": len(raw_results),
"ignored_total": len(raw_results) - len(scored_results),
"expected_active_total": len(active_tests),
"expected_ignored_total": len(ignored_tests),
"missing_total": len(missing_tests),
"missing_tests": missing_tests,
"unexpected_total": len(unexpected_tests),
"unexpected_tests": unexpected_tests,
}
def calculate_reward(passed: int, total: int, *, complete: bool) -> float:
reward = passed / total if total else 0.0
return 0.0 if reward >= 1.0 and not complete else reward
def write_score(
*,
passed: int,
matched_total: int,
raw_total: int,
ignored_total: int,
expected_active_total: int,
expected_ignored_total: int,
processed_branch_count: int,
branch_count: int,
timed_out_branches: list[str],
branch_results: dict,
) -> dict:
missing_total = max(0, expected_active_total - matched_total)
complete = (
processed_branch_count == branch_count
and not timed_out_branches
and missing_total == 0
)
reward = calculate_reward(passed, expected_active_total, complete=complete)
payload = {
"compiled": True,
"complete": complete,
"passed": passed,
"failed": max(0, matched_total - passed),
"total": expected_active_total,
"raw_total": raw_total,
"ignored_total": ignored_total,
"expected_active_total": expected_active_total,
"expected_ignored_total": expected_ignored_total,
"missing_total": missing_total,
"processed_branch_count": processed_branch_count,
"branch_count": branch_count,
"timed_out_branches": timed_out_branches,
"pass_rate": passed / expected_active_total if expected_active_total else 0.0,
"reward": reward,
"branches": branch_results,
}
REWARD.write_text(f"{reward:.12g}\n")
write_summary(payload)
return payload
def load_tests_meta() -> dict:
return json.loads((TESTS / "tests.json").read_text())
def active_branch_names(tests_meta: dict) -> list[str]:
return [
name
for name, item in tests_meta.get("branches", {}).items()
if isinstance(item, dict) and not item.get("ignored", False)
]
def write_summary(payload: dict) -> None:
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
(RESULTS_DIR / "summary.json").write_text(
json.dumps(payload, indent=2, sort_keys=True)
)
def captured_text(value: str | bytes | None) -> str:
if value is None:
return ""
if isinstance(value, bytes):
return value.decode("utf-8", errors="replace")
return value
def main() -> int:
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
# Default to reward 0 immediately so verifier timeouts or external kills
# still leave Harbor with a valid reward file.
REWARD.write_text("0\n")
if not ARTIFACT.exists():
write_summary({"error": "missing submission artifact"})
return 1
tests_meta = load_tests_meta()
branches_meta = tests_meta.get("branches", {})
branch_names = active_branch_names(tests_meta)
expected_active_total = sum(
len(configured_test_names(branches_meta.get(branch, {}).get("tests")))
for branch in branch_names
)
expected_ignored_total = sum(
len(configured_test_names(branches_meta.get(branch, {}).get("ignored_tests")))
for branch in branch_names
)
branch_count = len(branch_names)
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
workspace = Path("/workspace")
reset_workspace(workspace)
safe_extract(ARTIFACT, workspace)
remove_reference_binaries(workspace, load_reference_hashes())
ok, compile_log = compile_submission(workspace)
(RESULTS_DIR / "compile.log").write_text(compile_log)
if not ok:
REWARD.write_text("0\n")
write_summary({"compiled": False, "error": compile_log[-4000:]})
return 1
executable_backup = root / "executable"
shutil.copy2(workspace / "executable", executable_backup)
branch_results: dict[str, dict] = {}
timed_out_branches: list[str] = []
passed = matched_total = raw_total = ignored_total = 0
processed_branch_count = 0
write_score(
passed=passed,
matched_total=matched_total,
raw_total=raw_total,
ignored_total=ignored_total,
expected_active_total=expected_active_total,
expected_ignored_total=expected_ignored_total,
processed_branch_count=processed_branch_count,
branch_count=branch_count,
timed_out_branches=timed_out_branches,
branch_results=branch_results,
)
for branch in branch_names:
branch_meta = branches_meta.get(branch, {})
branch_tar = TESTS / "branches" / f"{branch}.tar.gz"
if not branch_tar.exists():
result = score_branch(TESTS / "missing-results.xml", branch_meta)
result["error"] = "missing branch archive"
branch_results[branch] = result
processed_branch_count += 1
write_score(
passed=passed,
matched_total=matched_total,
raw_total=raw_total,
ignored_total=ignored_total,
expected_active_total=expected_active_total,
expected_ignored_total=expected_ignored_total,
processed_branch_count=processed_branch_count,
branch_count=branch_count,
timed_out_branches=timed_out_branches,
branch_results=branch_results,
)
continue
safe_extract(branch_tar, workspace)
shutil.copy2(executable_backup, workspace / "executable")
(workspace / "executable").chmod(0o755)
env = os.environ.copy()
env["CANDIDATE_EXECUTABLE"] = str(workspace / "executable")
timed_out = False
try:
proc = subprocess.run(
["bash", "eval/run.sh"],
cwd=workspace,
env=env,
text=True,
capture_output=True,
timeout=300,
)
returncode = proc.returncode
output = proc.stdout + proc.stderr
except subprocess.TimeoutExpired as exc:
timed_out = True
returncode = 124
output = captured_text(exc.stdout) + captured_text(exc.stderr)
timed_out_branches.append(branch)
(RESULTS_DIR / f"{branch}.log").write_text(output)
result = score_branch(workspace / "eval" / "results.xml", branch_meta)
result["returncode"] = returncode
result["timed_out"] = timed_out
passed += result["passed"]
matched_total += result["matched_total"]
raw_total += result["raw_total"]
ignored_total += result["ignored_total"]
branch_results[branch] = result
processed_branch_count += 1
write_score(
passed=passed,
matched_total=matched_total,
raw_total=raw_total,
ignored_total=ignored_total,
expected_active_total=expected_active_total,
expected_ignored_total=expected_ignored_total,
processed_branch_count=processed_branch_count,
branch_count=branch_count,
timed_out_branches=timed_out_branches,
branch_results=branch_results,
)
shutil.rmtree(workspace / "eval", ignore_errors=True)
write_score(
passed=passed,
matched_total=matched_total,
raw_total=raw_total,
ignored_total=ignored_total,
expected_active_total=expected_active_total,
expected_ignored_total=expected_ignored_total,
processed_branch_count=processed_branch_count,
branch_count=branch_count,
timed_out_branches=timed_out_branches,
branch_results=branch_results,
)
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as exc:
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
summary_path = RESULTS_DIR / "summary.json"
if summary_path.is_file():
try:
payload = json.loads(summary_path.read_text())
except (OSError, ValueError):
payload = {}
else:
payload = {}
if not REWARD.is_file():
REWARD.write_text("0\n")
payload["complete"] = False
payload["verifier_error"] = repr(exc)
payload["traceback"] = traceback.format_exc()[-4000:]
write_summary(payload)
raise SystemExit(1)
|