Download tasks/data/reverse/aasaam__nginx-error-log-parser.a2f68f1/tests/grader.py from Lego-X/ProgramGen: direct link, hf CLI and curl.
- Browser
- Download file 15.5 kB
-
https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/reverse/aasaam__nginx-error-log-parser.a2f68f1/tests/grader.py
- Command line
-
hf download hf://datasets/Lego-X/ProgramGen/tasks/data/reverse/aasaam__nginx-error-log-parser.a2f68f1/tests/grader.py
-
curl -L -o grader.py https://huggingface.co/datasets/Lego-X/ProgramGen/resolve/main/tasks/data/reverse/aasaam__nginx-error-log-parser.a2f68f1/tests/grader.py
15.5 kB
| 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) | |