File size: 9,709 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
from __future__ import annotations

import argparse
import json
import re
from pathlib import Path


GRADER_SCHEMA_VERSION = "programgen.forward-grader.v2"


_NO_TEST_MARKERS = (
    "collected 0 items",
    "no tests ran",
    "[no test files]",
    "no tests were found",
    "total tests: 0",
    "running 0 tests",
    "0 tests passed",
    "0 passed; 0 failed",
)

_COMPILE_FAILURE_MARKERS = (
    "could not compile",
    "compilation terminated",
    "error: linking with",
    "fatal error:",
    "undefined reference to",
    "[build failed]",
    "cmake error",
    "ninja: build stopped",
)


_ANSI_ESCAPE = re.compile(r"\x1b\[[0-9;]*[A-Za-z]")


def parse_test_output(text: str, *, return_code: int) -> dict[str, int | str] | None:
    # Normalize colored runner output before parsing summaries or verbose nodes.
    text = _ANSI_ESCAPE.sub("", text)

    # A verifier killed by the internal timeout may never print pytest's terminal
    # summary. ``-vv`` emits one outcome per completed node, which is sufficient
    # for honest partial credit against the persisted expected denominator.
    verbose = re.findall(
        r"(?m)^(.+?::.+?)\s+(PASSED|FAILED|ERROR)(?:\s+\[[^\]]+\])?\s*$",
        text,
    )
    if verbose:
        outcomes: dict[str, str] = {}
        for test_id, outcome in verbose:
            outcomes[test_id.strip()] = outcome
        counts = {
            outcome: sum(value == outcome for value in outcomes.values())
            for outcome in ("PASSED", "FAILED", "ERROR")
        }
        return {
            "passed": counts["PASSED"],
            "failed": counts["FAILED"],
            "errors": counts["ERROR"],
            "kind": "pytest-verbose",
        }

    cargo = re.findall(
        r"test result:\s+\w+\.\s+(\d+) passed;\s+(\d+) failed",
        text,
    )
    if cargo:
        passed = sum(int(row[0]) for row in cargo)
        failed = sum(int(row[1]) for row in cargo)
        if passed + failed:
            return {"passed": passed, "failed": failed, "errors": 0, "kind": "cargo"}

    passed_matches = re.findall(r"(?<![\w%])(\d+)\s+passed\b", text)
    failed_matches = re.findall(r"(?<!\w)(\d+)\s+failed\b", text)
    error_matches = re.findall(r"(?<!\w)(\d+)\s+errors?\b", text)
    if passed_matches or failed_matches or error_matches:
        return {
            "passed": int(passed_matches[-1]) if passed_matches else 0,
            "failed": int(failed_matches[-1]) if failed_matches else 0,
            "errors": int(error_matches[-1]) if error_matches else 0,
            "kind": "summary",
        }

    unittest_runs = re.findall(r"(?m)^Ran\s+(\d+)\s+tests?\b", text)
    unittest_status = re.findall(r"(?m)^(OK|FAILED)(?:\s+\(([^)]*)\))?\s*$", text)
    if unittest_runs and unittest_status:
        ran = int(unittest_runs[-1])
        _status, details = unittest_status[-1]
        counts = {
            key.strip().lower().replace("_", " "): int(value)
            for key, value in re.findall(r"([A-Za-z_ ]+?)=(\d+)", details)
        }
        excluded = counts.get("skipped", 0) + counts.get("expected failures", 0)
        errors = counts.get("errors", 0) + counts.get("unexpected successes", 0)
        failed = counts.get("failures", 0)
        total = max(0, ran - excluded)
        if total:
            return {
                "passed": max(0, total - failed - errors),
                "failed": failed,
                "errors": errors,
                "kind": "unittest",
            }

    declared = re.search(
        r"(?im)^\s*Total:\s*(\d+)\s*(?:\|\s*)?Passed:\s*(\d+)\s*"
        r"(?:\|\s*)?Failed:\s*(\d+)\s*$",
        text,
    )
    if declared:
        total, passed, failed = map(int, declared.groups())
        if total > 0 and passed + failed == total:
            return {"passed": passed, "failed": failed, "errors": 0, "kind": "declared"}

    go_passed = [
        line
        for line in re.findall(r"(?m)^ok\s+\S+(?:\s+[^\n]+)?$", text)
        if "[no test files]" not in line.lower()
    ]
    go_failed = re.findall(
        r"(?m)^FAIL\s+\S+\s+(?:\d+(?:\.\d+)?s|\[(?:build|setup) failed\])\s*$",
        text,
    )
    if go_passed or go_failed:
        return {
            "passed": len(go_passed),
            "failed": len(go_failed),
            "errors": 0,
            "kind": "go-packages",
        }

    ctest = re.search(
        r"(\d+)% tests passed,\s*(\d+) tests failed out of (\d+)",
        text,
        flags=re.IGNORECASE,
    )
    if ctest and int(ctest.group(3)) > 0:
        failed = int(ctest.group(2))
        total = int(ctest.group(3))
        return {
            "passed": max(0, total - failed),
            "failed": failed,
            "errors": 0,
            "kind": "ctest",
        }

    meson_passed = re.search(r"(?m)^Ok:\s*(\d+)\s*$", text)
    meson_failed = re.search(r"(?m)^Fail:\s*(\d+)\s*$", text)
    if meson_passed:
        passed = int(meson_passed.group(1))
        failed = int(meson_failed.group(1)) if meson_failed else 0
        if passed + failed:
            return {"passed": passed, "failed": failed, "errors": 0, "kind": "meson"}

    if any(marker in text.lower() for marker in _NO_TEST_MARKERS):
        return {"passed": 0, "failed": 0, "errors": 0, "kind": "no-tests"}
    return None


def score_test_run(
    text: str,
    *,
    return_code: int,
    expected_count: int,
    phase: str = "tests",
    reason: str = "",
) -> dict[str, object]:
    expected = max(0, int(expected_count))
    parsed = (
        parse_test_output(text, return_code=return_code) if phase == "tests" else None
    )
    passed = int(parsed.get("passed", 0)) if parsed else 0
    failed = int(parsed.get("failed", 0)) if parsed else 0
    errors = int(parsed.get("errors", 0)) if parsed else 0
    observed = passed + failed + errors
    denominator = max(expected, observed)
    lowered = text.lower()
    compile_failed = any(marker in lowered for marker in _COMPILE_FAILURE_MARKERS)

    completed_count = observed >= expected if expected else observed > 0
    expected_exit = return_code == 0 or (
        return_code in (1, 101) and failed + errors > 0
    )
    complete = bool(parsed and completed_count and expected_exit and not compile_failed)
    compiled = bool(parsed and observed > 0 and not compile_failed)
    reward = passed / denominator if denominator else 0.0
    if reward >= 1.0 and not complete:
        reward = 0.0

    if not reason:
        if phase != "tests":
            reason = f"{phase}-failed"
        elif parsed is None:
            reason = (
                "test-output-unparsed" if return_code == 0 else "test-process-failed"
            )
        elif parsed.get("kind") == "no-tests":
            reason = "no-tests-ran"
        elif compile_failed:
            reason = "compile-failed"
        elif observed < expected:
            reason = "incomplete-test-count"
        elif errors:
            reason = "test-errors"
        elif failed:
            reason = "test-failures"
        elif return_code != 0:
            reason = "unexpected-test-exit"
        else:
            reason = "complete"

    return {
        "schema_version": GRADER_SCHEMA_VERSION,
        "phase": phase,
        "reason": reason,
        "test_rc": int(return_code),
        "parser": str(parsed.get("kind")) if parsed else None,
        "passed": passed,
        "failed": failed,
        "errors": errors,
        "observed_test_count": observed,
        "expected_test_count": expected,
        "denominator": denominator,
        "compiled": compiled,
        "complete": complete,
        "reward": reward,
    }


def write_result(
    text: str,
    *,
    return_code: int,
    expected_count: int,
    phase: str,
    reason: str,
    reward_path: Path,
    metrics_path: Path,
) -> dict[str, object]:
    result = score_test_run(
        text,
        return_code=return_code,
        expected_count=expected_count,
        phase=phase,
        reason=reason,
    )
    reward_path.parent.mkdir(parents=True, exist_ok=True)
    metrics_path.parent.mkdir(parents=True, exist_ok=True)
    reward = result.get("reward")
    if not isinstance(reward, (int, float)):
        raise ValueError("grader result has no numeric reward")
    reward_path.write_text(f"{float(reward):.12g}\n", encoding="utf-8")
    metrics_path.write_text(
        json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8"
    )
    return result


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path)
    parser.add_argument("--return-code", type=int, required=True)
    parser.add_argument("--expected-count", type=int, required=True)
    parser.add_argument("--phase", default="tests")
    parser.add_argument("--reason", default="")
    parser.add_argument(
        "--reward-path", type=Path, default=Path("/logs/verifier/reward.txt")
    )
    parser.add_argument(
        "--metrics-path", type=Path, default=Path("/logs/verifier/metrics.json")
    )
    args = parser.parse_args(argv)
    text = ""
    if args.output and args.output.is_file():
        text = args.output.read_text(encoding="utf-8", errors="replace")
    result = write_result(
        text,
        return_code=args.return_code,
        expected_count=args.expected_count,
        phase=args.phase,
        reason=args.reason,
        reward_path=args.reward_path,
        metrics_path=args.metrics_path,
    )
    reward = result.get("reward")
    if not isinstance(reward, (int, float)):
        raise ValueError("grader result has no numeric reward")
    print(f"{float(reward):.12g}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())