File size: 10,721 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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/<system>-<YYYYmmdd-HHMMSS>.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: <system>-<stamp>, 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()