"""In-container verifier for pr_runtime tasks (graded F2P/P2P reward). This module is the **standalone verifier** that runs inside the task's Docker container, NOT a helper used at generation time. It is read as source at generation time, base64-encoded, and embedded into ``tests/test.sh``. At run time the container decodes it back to a file and invokes it after the test suite has run. Why a graded reward instead of binary pass/fail ------------------------------------------------ SWE-bench resolution is binary: a patch "resolves" the issue iff ALL FAIL_TO_PASS tests pass AND ALL PASS_TO_PASS tests still pass. That's the right signal for an eval leaderboard, but a terrible gradient for RL training — an agent that fixes 4 of 5 failing tests scores the same 0.0 as one that fixes nothing. So this verifier emits BOTH: * /logs/verifier/reward.txt — the GRADED scalar (training signal, which Harbor reads): reward = f2p_rate * p2p_factor * /logs/verifier/reward-details.json — carries the strict SWE-bench ``resolved`` bool (eval signal) PLUS the full breakdown. Refs: SWE-bench (F2P/P2P semantics), SWE-RL / SWE-Gym (dense reward for RL), UTBoost (weak-test coverage lets wrong patches pass — hence we record p2p_count so consumers can judge regression-guard strength). Scoring ------- Given the baked FAIL_TO_PASS / PASS_TO_PASS test-name lists (computed by the generation-time two-stage validation) and the agent-run test log: f2p_rate = (# F2P tests now PASSED) / (# F2P tests) p2p_rate = (# P2P tests still PASSED) / (# P2P tests) [1.0 if no P2P] p2p_factor = p2p_rate # regressions scale the reward down reward = f2p_rate * p2p_factor resolved = (all F2P pass) AND (all P2P pass) # strict SWE-bench Oracle invariant: the gold patch flips every F2P and keeps every P2P, so f2p_rate=1.0, p2p_rate=1.0 -> reward=1.0 and resolved=True. This is what the T3 oracle gate (reward == 1.0) relies on. Graceful degradation: if the log can't be parsed into per-test statuses (unrecognized runner output), fall back to the exit-code reward (1.0 if the suite exited 0, else 0.0) and stamp ``parse_status="fallback_exitcode"`` — never crash, never silently zero out a real fix. Pure stdlib — uses only ``argparse``, ``json``, ``os``, ``re``, ``sys``. The 4 per-runner parsers are condensed ports of ``repo2rlenv.log_parsers.*`` kept in lockstep via the unit tests under ``tests/test_pr_runtime_verifier.py``. """ from __future__ import annotations import argparse import json import os import re import sys # Canonical statuses. (Plain strings — no typing.Literal so the baked # module stays import-light when decoded standalone in the container.) PASSED = "PASSED" FAILED = "FAILED" SKIPPED = "SKIPPED" ERROR = "ERROR" # --------------------------------------------------------------------------- # Per-runner log parsers (condensed ports of repo2rlenv.log_parsers.*) # --------------------------------------------------------------------------- _PYTEST_STATUSES = (PASSED, FAILED, SKIPPED, ERROR) # Keep these patterns in sync with log_parsers/pytest_parser.py. This module # also runs standalone inside task containers, without a repo2rlenv install. _PYTEST_PROGRESS = ( r"\[\s*\d+%\]|\[\s*\d+\s*/\s*\d+\s*\]" r"|\d+(?:\.\d+)?(?:us|ms|s)|\d+m \d+s|\d+h \d+m" ) _PYTEST_VERBOSE_RE = re.compile( r"^(?P.+?(?:\[.*?\])?)\s+(?PPASSED|FAILED|SKIPPED|ERROR)" rf"(?:\s+\(.*\))?(?:\s+(?:{_PYTEST_PROGRESS}))?$" ) _PYTEST_SUMMARY_NAME_RE = re.compile(r"^(?P.+?(?:\[.*?\])?)(?: - .*)?$") # pytest-xdist worker label, e.g. `[gw1] [ 20%] PASSED tests/foo.py::test_x`. _PYTEST_XDIST_PREFIX_RE = re.compile(rf"^\[gw\d+\]\s+(?:(?:{_PYTEST_PROGRESS})\s+)?") def parse_pytest(log: str) -> dict[str, str]: """{test_name -> status} from pytest output (verbose or summary).""" out: dict[str, str] = {} if not log: return out for raw in log.split("\n"): line = raw.strip() if not line: continue line = _PYTEST_XDIST_PREFIX_RE.sub("", line, count=1) # Summary lines (STATUS first), preserving the full node ID. leading = None for st in _PYTEST_STATUSES: if line.startswith(st + " ") or line == st: leading = st break if leading is not None: work = line[len(leading) :].strip() if leading == SKIPPED and re.match(r"^\[\d+\](?:\s|$)", work): # Folded skips report a file location, not a parametrized ID. tokens = work.split(maxsplit=2) if len(tokens) < 2: continue out[tokens[1]] = leading elif m := _PYTEST_SUMMARY_NAME_RE.match(work): out[m.group("name")] = leading continue # Verbose progress (NAME first, STATUS after) # Filter non-test output before attempting the backtracking regex. head = line.split(None, 1)[0] if "::" not in head and not head.endswith(".py"): continue m = _PYTEST_VERBOSE_RE.match(line) if m: name = m.group("name") if "::" in name or name.endswith(".py"): out[name] = m.group("status") return out _GO_TEST_RE = re.compile(r"^\s*---\s+(?PPASS|FAIL|SKIP):\s+(?P\S+)") _GO_STATUS = {"PASS": PASSED, "FAIL": FAILED, "SKIP": SKIPPED} def parse_go_test(log: str) -> dict[str, str]: """{test_name -> status} from `go test -v` output.""" out: dict[str, str] = {} if not log: return out for raw in log.split("\n"): m = _GO_TEST_RE.match(raw) if m: out[m.group("name")] = _GO_STATUS[m.group("status")] return out # Keep these patterns in sync with log_parsers/cargo_parser.py. _CARGO_TEST_RE = re.compile(r"^test\s+(?P\S.*?) \.\.\. (?Pok|FAILED|ignored)\b") _CARGO_MODE_RE = re.compile(r" - (?:should panic|compile fail|compile)$") _CARGO_DOCTEST_RE = re.compile(r"^(?P\S+) - (?:(?P.+?) )?\(line \d+\)$") _CARGO_STATUS = {"ok": PASSED, "FAILED": FAILED, "ignored": SKIPPED} _CARGO_DOCTEST_RANK = {SKIPPED: 0, PASSED: 1, FAILED: 2} def parse_cargo_test(log: str) -> dict[str, str]: """{test_name -> status} from `cargo test` output. Test modes (` - should panic`) are dropped from names, and doctests are keyed without their `(line N)` so line shifts don't change identity; the worst status among an item's doctests wins. """ out: dict[str, str] = {} if not log: return out for raw in log.split("\n"): m = _CARGO_TEST_RE.match(raw) if not m: continue name = _CARGO_MODE_RE.sub("", m.group("name")).rstrip() status = _CARGO_STATUS[m.group("status")] doctest = _CARGO_DOCTEST_RE.match(name) if doctest: item = doctest.group("item") name = f"{doctest.group('file')} - {item}" if item else doctest.group("file") if name in out and _CARGO_DOCTEST_RANK[out[name]] > _CARGO_DOCTEST_RANK[status]: continue out[name] = status return out _JEST_FILE_RE = re.compile(r"^ ?(?:PASS|FAIL)\s+(?P\S+\.(?:ts|tsx|js|jsx|mjs|cjs))\b") _JEST_TEST_RE = re.compile( r"^(?P\s*)(?P✓|√|✕|×|✗|○|◯)\s+(?P.+?)(?:\s+\(\d+(?:\.\d+)?\s*m?s\))?$" ) _JEST_GLYPH = { "✓": PASSED, "√": PASSED, "✕": FAILED, "×": FAILED, "✗": FAILED, "○": SKIPPED, "◯": SKIPPED, } # Keep these patterns in sync with log_parsers/jest_parser.py. _ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]") _VITEST_MARKER_RE = re.compile(r"^\s*(?:RUN\s+v\d+\.\d+|Test Files\s+\d)", re.MULTILINE) _VITEST_TEST_RE = re.compile( r"^\s*(?P[✓×↓□]) (?:\|(?P[^|]+)\| | (?P