"""Step 4b: run one system over the question set and save what it did. uv run python -m coveragecheck.evals.run dummy [--ids Q001,Q005] [--questions path] Output: evals/runs/-.parquet (one row per question) and a .json sidecar with the run's metadata (date used, git commit, questions file hash and ids, system settings incl. index hash, package versions, timings, complete flag), so a number in the report can be traced to its run. Read runs with store.load_table. Owner decisions (4b): a system only ever receives the question text and the date, never the gold; an exception on one question is recorded and the run goes on (metrics count it as a fail); no run-level cache (retrieval is ~26 ms a question and LLM calls are cached per call in .cache/llm); recall is computed in metrics.py from the retrieved ids, because each system's hit rule differs (A: covers_sources; B/C: section ancestry). Error rows keep answer/abstained/confidence = None (an error is not an abstention: 4d counts it as a fail via the `error` column). """ import argparse import hashlib import importlib import json import statistics import subprocess import time from collections.abc import Callable, Iterator from datetime import date, datetime from importlib import metadata from pathlib import Path import pandas as pd from coveragecheck import config from coveragecheck.agent.schemas import AnswerFailed, Response, System, Work from coveragecheck.evals.questions import Question, load_questions # Packages whose version can change a run's numbers (recorded in the sidecar). VERSIONED = ["fastembed", "bm25s", "numpy", "pandas", "pydantic", "anthropic", "langgraph"] def record( q: Question, day: date, response: Response | None, ms: float, error: str | None, work: Work | None = None, error_kind: str | None = None, ): """One output row: the question and its eval labels (never shown to the system), what the system said, what it retrieved and spent, and how long it took. response is None when it raised; work is then what the failure reported (AnswerFailed.work), so an error row keeps its retrieval and cost (5b). error_kind: None on success, AnswerFailed.kind (api, refusal, stopped, truncated, invalid) or "exception".""" w = response if response is not None else work # a Response is a Work row = { "question_id": q.id, "question": q.question, # grade.py's cache key needs it; saves a join "category": q.category, "answerable": q.answerable, "cost_class": q.cost_class, "n_docs": q.n_docs, "policy_effective_date": q.policy_effective_date and q.policy_effective_date.isoformat(), "day": day.isoformat(), "latency_ms": ms, "error": error, "error_kind": error_kind, } a = response.answer if response else None return row | { "answer": a.answer if a else None, "abstained": a.abstain if a else None, "confidence": a.confidence if a else None, # JSON text: pandas reads list-of-struct parquet columns back awkwardly "citations_json": json.dumps([c.model_dump() for c in a.citations]) if a else "[]", "cited_source_ids": [c.source_id for c in a.citations] if a else [], "missing_info": list(a.missing_info) if a else [], "retrieved_chunk_ids": list(w.retrieved_chunk_ids) if w else [], "retrieved_source_ids": list(w.retrieved_source_ids) if w else [], "tokens_in": w.tokens_in if w else 0, "tokens_out": w.tokens_out if w else 0, "llm_calls": w.llm_calls if w else 0, "reasks": w.reasks if w else 0, "api_retries": w.api_retries if w else 0, "cache_hits": w.cache_hits if w else 0, "replayed_ms": w.replayed_ms if w else 0.0, "trace_json": json.dumps(w.trace) if w else "{}", } def iter_run( system: System, questions: list[Question], today: date, clock: Callable[[], float] = time.perf_counter, ) -> Iterator[dict]: """Ask the system every question, in file order, yielding one row per question as it finishes (so an interrupted run keeps what it has). Call system.warm_up() first (main does, inside its load timer). One date for the whole run (today), so a run that crosses midnight stays consistent. Catches Exception, not KeyboardInterrupt: one bad LLM response must not lose the run, but Ctrl-C must still stop it. An AnswerFailed keeps the work it reports (retrieval, tokens) on the error row.""" for q in questions: day = q.search_day(today) start = clock() response, error, work, kind = None, None, None, None try: response = system.answer(q.question, day) except AnswerFailed as exc: error, work, kind = f"AnswerFailed: {exc}", exc.work, exc.kind except Exception as exc: # noqa: BLE001 - recorded, counted as a fail error, kind = f"{type(exc).__name__}: {exc}", "exception" yield record(q, day, response, (clock() - start) * 1000, error, work, kind) def run_system(system: System, questions: list[Question], today: date, **kwargs) -> list[dict]: """iter_run, collected.""" return list(iter_run(system, questions, today, **kwargs)) def git_commit() -> str | None: """HEAD's hash, with "-dirty" if tracked files have uncommitted changes (the run then can't be reproduced from the commit alone). Untracked files (scratch, new notes) don't count: they can't change the code that ran. None outside git.""" try: head = subprocess.run( ["git", "rev-parse", "HEAD"], cwd=config.ROOT, capture_output=True, text=True ) status = subprocess.run( ["git", "status", "--porcelain", "--untracked-files=no"], cwd=config.ROOT, capture_output=True, text=True, ) except OSError: return None if head.returncode != 0: return None return head.stdout.strip() + ("-dirty" if status.stdout.strip() else "") def versions() -> dict[str, str | None]: """Installed versions of the packages that can change a run's numbers.""" out = {} for name in VERSIONED: try: out[name] = metadata.version(name) except metadata.PackageNotFoundError: out[name] = None return out def run_path(runs_dir: Path, system: str, stamp: str) -> Path: """A parquet path for a new run that no earlier run uses: -, then -2, -3 ... Chosen BEFORE the run, so two runs started in the same second (a double launch) both keep their results instead of the second failing at the end.""" path, n = runs_dir / f"{system}-{stamp}.parquet", 1 while path.exists() or path.with_suffix(".json").exists(): n += 1 path = runs_dir / f"{system}-{stamp}-{n}.parquet" return path def write_run(rows: list[dict], meta: dict, path: Path) -> None: """Save rows at path and meta beside it as .json. The parquet goes through a temp file and a rename, and the sidecar is written last, so a reader never sees a half-written table, and a table without its sidecar means the run didn't finish saving.""" path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(".tmp") pd.DataFrame(rows).to_parquet(tmp, index=False) tmp.replace(path) path.with_suffix(".json").write_text(json.dumps(meta, indent=2), encoding="utf-8") # name -> "module:factory"; imported only when chosen (the factory loads models). SYSTEMS = { "dummy": "coveragecheck.evals.dummy:build", "a": "coveragecheck.retrieve.naive:build", # Step 5b: naive RAG "b": "coveragecheck.retrieve.structured:build", # Step 6b: structure-aware hybrid RAG "c": "coveragecheck.agent.graph:build", # Step 7: LangGraph agent (judge + research) } def build_system(name: str) -> System: module, factory = SYSTEMS[name].split(":") return getattr(importlib.import_module(module), factory)() def select(questions: list[Question], ids: list[str] | None) -> list[Question]: """The questions to run: all, or the listed ids in file order. An unknown id raises, so a typo doesn't silently run nothing.""" if ids is None: return questions unknown = sorted(set(ids) - {q.id for q in questions}) if unknown: raise ValueError(f"unknown question id(s): {unknown}") return [q for q in questions if q.id in set(ids)] def main() -> None: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("system", choices=sorted(SYSTEMS)) parser.add_argument("--ids", help="comma-separated question ids (default: all)") parser.add_argument("--questions", type=Path, default=config.QUESTIONS_PATH) args = parser.parse_args() # hash the questions file BEFORE the run: an edit during it must not be recorded questions_sha256 = hashlib.sha256(args.questions.read_bytes()).hexdigest() questions = select(load_questions(args.questions), args.ids and args.ids.split(",")) started, t0 = datetime.now(), time.perf_counter() system = build_system(args.system) system.warm_up() load_s = time.perf_counter() - t0 # until ready to answer: build + model load path = run_path(config.RUNS_DIR, system.name, started.strftime("%Y%m%d-%H%M%S")) rows, complete = [], False try: for row in iter_run(system, questions, started.date()): rows.append(row) complete = True finally: # Ctrl-C still saves the answers already paid for, marked incomplete meta = { "system": system.name, "settings": system.settings, "today": started.date().isoformat(), "started_at": started.isoformat(timespec="seconds"), "git_commit": git_commit(), "versions": versions(), "questions_path": str(args.questions), "questions_sha256": questions_sha256, "question_ids": [q.id for q in questions], "n_questions": len(rows), "complete": complete, "load_s": round(load_s, 3), "total_s": round(time.perf_counter() - t0, 3), } write_run(rows, meta, path) errors = sum(r["error"] is not None for r in rows) abstained = sum(bool(r["abstained"]) for r in rows) print(f"{len(rows)} questions, {abstained} abstained, {errors} errors -> {path}") if rows: ms = [r["latency_ms"] for r in rows] print( f"latency ms median {statistics.median(ms):.1f} max {max(ms):.1f}; ready {load_s:.1f} s" ) if __name__ == "__main__": main()