File size: 13,781 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
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
"""Step 4c: hand-grade system answers against the gold, blind, with a cache.

    uv run python -m coveragecheck.evals.grade [run.parquet ...] [--redo Q013,Q020]

With no run given, grades the newest run of each system in evals/runs/. You type p
(pass), f [note] (fail, optionally why), s (skip), u (undo: back one item) or q
(quit). Each grade is appended to evals/grades.jsonl (committed) the moment it is
typed, so quitting (or Ctrl-C) keeps progress.

Owner decisions (4c):
- Cache key = hash(question id + question + gold answer + answer + sorted cited
  source ids): a rerun that gives the same answer is not asked again; a changed gold
  answer (the draft set will be replaced) or a different citation asks again.
- Blind: the grader never sees the system name or its confidence, and answers from
  several runs are mixed in a fixed shuffled order, so no system is favoured.
- Auto-graded, never asked: an error (a fail), an abstention (correct if the
  question is unanswerable, else "abstain").
- An unanswerable question that a system answered IS graded by hand: pass = the
  answer, like the gold, says the documents don't support it (a refusal in prose
  without the abstain flag); fail = it asserts an answer. Researched first: keyword
  lists misfire on insurance prose full of "not covered"; safety-refusal classifiers
  are the wrong domain; an LLM judge fits but needs an LLM call and validation against
  these hand labels (option for Step 7).
"""

import argparse
import hashlib
import json
import random
import sys
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Literal

import pandas as pd
from pydantic import BaseModel, ConfigDict

from coveragecheck import config
from coveragecheck.evals.questions import Question, load_questions
from coveragecheck.index.store import load_table


class Grade(BaseModel):
    """One judgement, one line of grades.jsonl. run is provenance only (the same answer
    from another run reuses the grade through the key). grader says who judged:
    "owner" (hand grading; the default, so older lines read as hand grades) or
    "llm:<model>:<effort>" (owner's decision in 5c, for time: an LLM graded in the
    owner's place, UNVALIDATED against hand labels; the report says so)."""

    model_config = ConfigDict(extra="forbid", frozen=True)
    key: str
    question_id: str
    grade: Literal["pass", "fail"]
    note: str | None = None
    graded_at: str
    run: str
    grader: str = "owner"


@dataclass(frozen=True)
class Item:
    """One answer waiting for a human: its key, its run row and the gold question."""

    key: str
    row: dict
    question: Question
    run: str


def grade_key(question_id: str, question: str, gold: str, answer: str, cited: list[str]) -> str:
    """sha256 of the parts that decide a grade. Cited ids are sorted (their order
    doesn't change correctness); the quote text is left out, so a rerun that only
    trims a quote isn't graded again; runs of whitespace in the answer count as one
    space (an LLM varying its line breaks says the same thing). The format is pinned
    by a test: changing it orphans every committed grade."""
    parts = [question_id, question, gold, " ".join(answer.split()), sorted(cited)]
    return hashlib.sha256(json.dumps(parts, ensure_ascii=False).encode("utf-8")).hexdigest()


def row_key(row: dict, q: Question) -> str:
    """A run row's key, with the CURRENT gold answer (a changed gold asks again)."""
    return grade_key(q.id, row["question"], q.gold_answer, row["answer"], row["cited_source_ids"])


def auto_outcome(row: dict, q: Question) -> str | None:
    """The outcome when no human is needed: "error" (counted as a fail), or for an
    abstention "correct_abstain" (unanswerable) / "abstain" (answerable). None: a
    human must judge the answer."""
    if row["error"] is not None:
        return "error"
    if row["abstained"]:
        return "abstain" if q.answerable else "correct_abstain"
    return None


def load_grades(path: Path = config.GRADES_PATH) -> dict[str, Grade]:
    """key -> Grade. A key graded twice (--redo, undo) keeps the latest line. A missing
    file is an empty cache. utf-8-sig: Notepad may add a BOM. An unfinished last line
    (no newline: a crash mid-write) is ignored, so that grade is simply asked again;
    any other malformed line raises with its line number."""
    out: dict[str, Grade] = {}
    if not path.exists():
        return out
    lines = path.read_text(encoding="utf-8-sig").split("\n")
    for number, line in enumerate(lines, start=1):
        if line.strip():
            try:
                grade = Grade.model_validate_json(line, strict=True)
            except ValueError as error:
                if number == len(lines):  # the text after the last "\n": unfinished
                    continue
                raise ValueError(f"{path}:{number}: {error}") from error
            out[grade.key] = grade
    return out


def append_grade(path: Path, grade: Grade) -> None:
    """Add one line and close the file at once, so a crash or Ctrl-C keeps it. ASCII
    JSON (non-ASCII escaped), so a pasted U+2028 in a note can't split the line for a
    reader using splitlines(). If a crash left an unfinished last line (no final
    newline), it is cut off first: it is not a grade, only the start of one that was
    never saved (load_grades ignores it, so it is asked again). Gluing the new grade
    onto it, or keeping it above the new line, would break every later load."""
    path.parent.mkdir(parents=True, exist_ok=True)
    line = json.dumps(grade.model_dump(), ensure_ascii=True)
    if path.exists():
        data = path.read_bytes()
        if data and not data.endswith(b"\n"):
            path.write_bytes(data[: data.rfind(b"\n") + 1])  # keep complete lines only
    with path.open("a", encoding="utf-8", newline="\n") as f:
        f.write(line + "\n")


def pending(
    runs: list[tuple[str, pd.DataFrame]],
    questions: dict[str, Question],
    grades: dict[str, Grade],
    redo: frozenset[str] = frozenset(),
    seed: int = config.GRADE_SHUFFLE_SEED,
) -> tuple[list[Item], list[str]]:
    """(answers a human must grade, stale row notes). Skips auto-graded rows, rows
    already graded (unless their question is in redo), and duplicates (the same key
    from several runs is asked once). Stale: the row's question id is gone from the
    question file, its wording changed since the run (the answer was to a different
    question), or the run predates the `question` column. The list is shuffled
    with a fixed seed: blind and mixed across runs, and reproducible for the same
    pending set."""
    items, seen, stale = [], set(), []
    for run, table in runs:
        for row in table.to_dict("records"):
            q = questions.get(row["question_id"])
            if q is None or q.question != row.get("question"):
                stale.append(f"{run}: {row['question_id']}")
                continue
            if auto_outcome(row, q) is not None:
                continue
            key = row_key(row, q)
            if key in seen or (key in grades and q.id not in redo):
                continue
            seen.add(key)
            items.append(Item(key, row, q, run))
    items.sort(key=lambda item: item.key)  # a fixed order before the shuffle
    random.Random(seed).shuffle(items)
    return items, stale


def show(item: Item) -> str:
    """What the grader reads. No system name and no confidence (blind grading)."""
    q, row = item.question, item.row
    date = q.policy_effective_date or "none"
    lines = [f"{q.id}  {q.category}  policy date: {date}"]
    if not q.answerable:
        lines.append("UNANSWERABLE: pass only if the answer says the documents can't answer it")
    lines += ["", f"QUESTION  {q.question}", "", f"GOLD  {q.gold_answer}"]
    if q.review and q.review.key_points:
        lines += ["KEY POINTS"] + [f"  - {point}" for point in q.review.key_points]
    lines += ["", f"ANSWER  {row['answer']}"]
    for c in json.loads(row["citations_json"]):
        lines.append(f'  cites {c["source_id"]}: "{c["quote"]}"')
    if q.gold_sources:
        lines.append(f"GOLD SOURCES  {', '.join(q.gold_sources)}")
    return "\n".join(lines)


def parse_reply(reply: str) -> tuple[str, str | None] | None:
    """p -> ("pass", None); f [note] -> ("fail", note or None); s -> ("skip", None);
    u -> ("undo", None); q -> ("quit", None); anything else -> None (ask again)."""
    word, _, rest = reply.strip().partition(" ")
    word = word.lower()
    if word == "p" and not rest:
        return "pass", None
    if word == "f":
        return "fail", rest.strip() or None
    if word in ("s", "q", "u") and not rest:
        return {"s": "skip", "q": "quit", "u": "undo"}[word], None
    return None


def grade_session(
    items: list[Item],
    path: Path,
    ask: Callable[[str], str] = input,
    say: Callable[[str], None] = print,
    now: Callable[[], datetime] = datetime.now,
) -> dict[str, int]:
    """Ask about each item until the list ends or the grader quits (q, Ctrl-C or end
    of input); each grade is saved as soon as it is given. u goes back one item and
    asks it again: the new line wins over the old one (latest line per key), so
    nothing is rewritten. Returns counts of pass / fail / skip."""
    counts = {"pass": 0, "fail": 0, "skip": 0}
    done: list[str] = []  # the action taken on each item so far, for undo
    i = 0
    while i < len(items):
        item = items[i]
        tally = "  ".join(f"{k} {v}" for k, v in counts.items())
        say(f"\n=== {i + 1}/{len(items)}  ({tally}) " + "=" * 40 + "\n" + show(item))
        try:
            while (parsed := parse_reply(ask("p / f [note] / s / u (undo) / q > "))) is None:
                say("type p, f (optionally followed by a note), s, u or q")
        except (EOFError, KeyboardInterrupt):  # grades so far are already saved
            break
        action, note = parsed
        if action == "quit":
            break
        if action == "undo":
            if done:
                counts[done.pop()] -= 1
                i -= 1
            else:
                say("nothing to undo")
            continue
        if action in ("pass", "fail"):
            stamp = now().isoformat(timespec="seconds")
            grade = Grade(
                key=item.key,
                question_id=item.question.id,
                grade=action,
                note=note,
                graded_at=stamp,
                run=item.run,
            )
            append_grade(path, grade)
        counts[action] += 1
        done.append(action)
        i += 1
    return counts


@dataclass(frozen=True)
class Resolved:
    """A run row's final outcome: error | abstain | correct_abstain (auto), pass |
    fail (hand grade), pending (not graded yet) or stale (question removed or
    reworded since the run). grade carries the hand grade and its note (Step 9)."""

    outcome: str
    grade: Grade | None = None


def resolve(row: dict, q: Question | None, grades: dict[str, Grade]) -> Resolved:
    """THE single place that turns a run row into its outcome (4d uses only this),
    with the same rules as pending(): stale first, then auto outcomes, then the hand
    grade for this exact answer, else pending."""
    if q is None or q.question != row.get("question"):
        return Resolved("stale")
    auto = auto_outcome(row, q)
    if auto is not None:
        return Resolved(auto)
    grade = grades.get(row_key(row, q))
    return Resolved(grade.grade, grade) if grade else Resolved("pending")


def latest_runs(runs_dir: Path = config.RUNS_DIR) -> list[Path]:
    """The newest run of each system, by its sidecar's started_at. Runs without a
    sidecar (still being saved, or broken) are ignored."""
    best: dict[str, tuple[tuple[str, str], Path]] = {}  # system -> (stamp, path)
    for sidecar in runs_dir.glob("*.json"):
        path = sidecar.with_suffix(".parquet")
        if path.exists():
            meta = json.loads(sidecar.read_text(encoding="utf-8"))
            stamp = (meta["started_at"], path.name)
            if meta["system"] not in best or stamp > best[meta["system"]][0]:
                best[meta["system"]] = (stamp, path)
    return sorted(path for _, path in best.values())


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("runs", nargs="*", type=Path, help="run files (default: newest per system)")
    parser.add_argument("--redo", help="comma-separated question ids to grade again")
    parser.add_argument("--questions", type=Path, default=config.QUESTIONS_PATH)
    args = parser.parse_args()

    # paths and input passed explicitly: a default argument is bound at import, so
    # reads and writes could otherwise go to different files (a test caught it)
    paths = args.runs or latest_runs(config.RUNS_DIR)
    if not paths:
        sys.exit(
            f"no runs in {config.RUNS_DIR}; run: uv run python -m coveragecheck.evals.run dummy"
        )
    questions = {q.id: q for q in load_questions(args.questions)}
    runs = [(p.name, load_table(p)) for p in paths]
    redo = frozenset(args.redo.split(",")) if args.redo else frozenset()
    items, stale = pending(runs, questions, load_grades(config.GRADES_PATH), redo)
    if stale:
        print(f"skipped {len(stale)} stale rows (question removed or reworded), e.g. {stale[0]}")
    print(f"{len(items)} answers to grade from {len(paths)} run(s)")
    counts = grade_session(items, config.GRADES_PATH, ask=input)
    print(f"done: {counts['pass']} pass, {counts['fail']} fail, {counts['skip']} skipped")


if __name__ == "__main__":
    main()