"""Check the one output file a task names. Reward is 1.0 when every check passes, else 0.0. Checks only parse: no file under /app is executed here. The sw_fix family runs its hidden tests itself, as nobody, on a copy (see families/software.py). """ import csv import io import json import math import os import re import time import wave from typing import Any from ..families.base import Artifact, Built, Field, FileContent MAX_ARTIFACT_BYTES = 4 * 1024**2 def _norm_text(value: Any) -> str: return " ".join(str(value).strip().split()).casefold() def _as_list(value: Any) -> list | None: if isinstance(value, list): return value if isinstance(value, str): return [part for part in (p.strip() for p in value.split(",")) if part] return None def _as_number(value: Any) -> float | None: if isinstance(value, bool): return None if isinstance(value, (int, float)): return float(value) if isinstance(value, str): try: return float(value.strip().replace(",", "")) except ValueError: return None return None def score_field(field: Field, value: Any, expected: Any) -> float: if value is None: return 0.0 kind = field.kind if kind == "int": number = _as_number(value) return float(number is not None and math.isfinite(number) and number == int(expected)) if kind == "number": number = _as_number(value) if number is None or not math.isfinite(number): return 0.0 tol = max(field.tol, field.rel * abs(expected)) return float(abs(number - expected) <= tol + 1e-12) if kind == "text": return float(_norm_text(value) == _norm_text(expected)) if kind == "list": items = _as_list(value) if items is None: return 0.0 got = {_norm_text(x) for x in items} return float(len(got) == len(items) and got == {_norm_text(x) for x in expected}) raise ValueError(f"unknown field kind {kind!r}") def read_artifact(app: str, path: str) -> bytes | None: """The file's bytes, or None when it is missing, a symlink, not a regular file, outside the app dir or over MAX_ARTIFACT_BYTES. lstat first so a FIFO or a link planted at the path cannot hang or redirect the root-owned reader.""" app_real = os.path.realpath(app) full = os.path.join(app_real, path) if os.path.commonpath([app_real, os.path.realpath(os.path.dirname(full))]) != app_real: return None try: st = os.lstat(full) except OSError: return None import stat if not stat.S_ISREG(st.st_mode) or st.st_size > MAX_ARTIFACT_BYTES: return None with open(full, "rb") as fh: return fh.read(MAX_ARTIFACT_BYTES + 1) def _text(data: bytes) -> str: return data.decode("utf-8-sig", errors="replace").replace("\r\n", "\n") def _fields_by_name(artifact: Artifact) -> dict[str, Field]: return {f.name: f for f in artifact.fields} def compare_json(artifact: Artifact, data: bytes) -> bool: got = json.loads(_text(data)) if not isinstance(got, dict) or set(got) != set(artifact.expected): return False # exact key set, as the operator's verifiers check fields = _fields_by_name(artifact) for key, expected in artifact.expected.items(): field = fields.get(key) or Field(key, "text") if score_field(field, got.get(key), expected) != 1.0: return False return True def _csv_rows(text: str) -> tuple[list[str], list[dict]]: reader = csv.DictReader(io.StringIO(text)) rows = [{(k or "").strip(): (v or "").strip() for k, v in row.items()} for row in reader] header = [h.strip() for h in (reader.fieldnames or [])] return header, rows def compare_csv(artifact: Artifact, data: bytes) -> bool: header, rows = _csv_rows(_text(data)) fields = _fields_by_name(artifact) columns = [f.name for f in artifact.fields] if header != columns: return False # the exact header the instruction shows key = tuple(artifact.key) or tuple(columns[:1]) if any(k not in header for k in key): return False def row_key(row: dict) -> tuple: return tuple(_norm_text(row.get(k, "")) for k in key) expected = {row_key({k: str(v) for k, v in r.items()}): r for r in artifact.expected} got = {} for row in rows: k = row_key(row) if k in got: return False # duplicate key row got[k] = row if set(got) != set(expected): return False if artifact.ordered: want = [row_key({k: str(v) for k, v in r.items()}) for r in artifact.expected] if [row_key(r) for r in rows] != want: return False for k, want_row in expected.items(): for column in columns: if score_field(fields[column], got[k].get(column), want_row[column]) != 1.0: return False return True def compare_lines(artifact: Artifact, data: bytes) -> bool: lines = [_norm_text(ln) for ln in _text(data).split("\n") if ln.strip()] want = [_norm_text(x) for x in artifact.expected] if artifact.ordered: return lines == want return len(lines) == len(set(lines)) and set(lines) == set(want) _SRT_TIME = re.compile(r"(\d+):(\d\d):(\d\d)[,.](\d{1,3})") def _srt_ms(token: str) -> int: m = _SRT_TIME.fullmatch(token.strip()) if not m: raise ValueError(token) h, mi, s, ms = m.groups() return ((int(h) * 60 + int(mi)) * 60 + int(s)) * 1000 + int(ms.ljust(3, "0")) def parse_srt(text: str) -> list[tuple[int, int, str]]: cues = [] for block in re.split(r"\n\s*\n", text.strip()): lines = [ln.rstrip() for ln in block.strip().split("\n")] if len(lines) < 2: raise ValueError("short cue") if "-->" not in lines[0] and "-->" in lines[1]: lines = lines[1:] start, end = (t.strip() for t in lines[0].split("-->")) cues.append((_srt_ms(start), _srt_ms(end), "\n".join(lines[1:]).strip())) return cues def compare_srt(artifact: Artifact, data: bytes) -> bool: got = parse_srt(_text(data)) want = artifact.expected if len(got) != len(want): return False for (gs, ge, gt), (ws, we, wt) in zip(got, want): if abs(gs - ws) > artifact.tol_ms or abs(ge - we) > artifact.tol_ms: return False if _norm_text(gt) != _norm_text(wt): return False return True def compare_wav(artifact: Artifact, data: bytes) -> bool: with wave.open(io.BytesIO(data)) as got, wave.open(io.BytesIO(artifact.expected)) as want: if (got.getnchannels(), got.getsampwidth(), got.getframerate()) != ( want.getnchannels(), want.getsampwidth(), want.getframerate(), ): return False if got.getnframes() != want.getnframes(): return False return got.readframes(got.getnframes()) == want.readframes(want.getnframes()) COMPARERS = { "json": compare_json, "csv": compare_csv, "lines": compare_lines, "srt": compare_srt, "wav": compare_wav, } def _stem(path: str) -> str: return re.sub(r"[^a-z0-9]+", "_", os.path.basename(path).rsplit(".", 1)[0].lower()).strip("_") or "artifact" def verify(app: str, built: Built) -> tuple[float, dict[str, bool], str]: """Run the checks for the task's artifact. Returns (reward, named results, pytest-style tail).""" started = time.time() artifact = built.artifact stem = _stem(artifact.path) results: dict[str, bool] = {} if artifact.kind == "custom": exists = read_artifact(app, artifact.path) is not None if artifact.path else True results[f"test_{stem}_exists"] = exists try: results[f"test_{stem}_correct"] = bool(exists and artifact.verify(app)) except Exception: results[f"test_{stem}_correct"] = False else: data = read_artifact(app, artifact.path) results[f"test_{stem}_exists"] = data is not None try: results[f"test_{stem}_correct"] = data is not None and bool(COMPARERS[artifact.kind](artifact, data)) except Exception: results[f"test_{stem}_correct"] = False passed = sum(results.values()) failed = len(results) - passed elapsed = f"{time.time() - started:.2f}s" lines = [f"FAILED tests/test_outputs.py::{name}" for name, ok in results.items() if not ok] summary = f"{failed} failed, {passed} passed in {elapsed}" if failed else f"{passed} passed in {elapsed}" return (1.0 if not failed else 0.0), results, "\n".join(lines + [summary]) def render_artifact(artifact: Artifact) -> FileContent: """Oracle content for tests and replay: what a perfect agent would write.""" if artifact.render is not None: return artifact.render() kind = artifact.kind if kind == "json": return json.dumps(artifact.expected, indent=1) + "\n" if kind == "csv": columns = [f.name for f in artifact.fields] out = io.StringIO() writer = csv.DictWriter(out, fieldnames=columns, lineterminator="\n") writer.writeheader() for row in artifact.expected: writer.writerow({c: row[c] for c in columns}) return out.getvalue() if kind == "lines": return "\n".join(str(x) for x in artifact.expected) + "\n" if kind == "srt": blocks = [] for i, (start, end, text) in enumerate(artifact.expected, 1): blocks.append(f"{i}\n{_fmt_srt(start)} --> {_fmt_srt(end)}\n{text}") return "\n\n".join(blocks) + "\n" if kind == "wav": return artifact.expected raise ValueError(f"no renderer for {kind!r}; give the artifact a render callable") def _fmt_srt(ms: int) -> str: h, rem = divmod(ms, 3600_000) m, rem = divmod(rem, 60_000) s, ms = divmod(rem, 1000) return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}" def oracle_actions(path: str, content) -> list: """Actions that write an oracle artifact: write_file for text, chunked base64 through exec for bytes.""" from ..models import Tbench2Action if isinstance(content, str): return [Tbench2Action(action_type="write_file", file_path=path, content=content)] import base64 b64 = base64.b64encode(content).decode() acts = [Tbench2Action(action_type="exec", command=f'mkdir -p "$(dirname {path})" && : > {path}.b64')] for i in range(0, len(b64), 60000): acts.append(Tbench2Action(action_type="exec", command=f"printf %s {b64[i:i + 60000]} >> {path}.b64")) acts.append(Tbench2Action(action_type="exec", command=f"base64 -d {path}.b64 > {path} && rm {path}.b64")) return acts