File size: 3,463 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
"""Step 3d: the dev probes (evals/dev_probes.jsonl) and their report.



    uv run python -m coveragecheck.evals.probes



The probes are ~20 hand-checked questions with the sections that answer them. They

settled Step 3's open choices (query prefix, dotted-ancestor tokens, title-block

chunks, passage text) and are NEVER used for the reported numbers: tuning and final

evaluation on the same questions would flatter the system (owner's decision).

"""

import json
from collections.abc import Callable
from dataclasses import dataclass
from datetime import date
from pathlib import Path

from coveragecheck import config
from coveragecheck.evals.hits import ancestry, first_hit, summarize


@dataclass(frozen=True)
class Probe:
    id: str
    kind: str
    question: str
    expected: frozenset[str]  # any one of these sections answers the question
    policy_date: date | None
    note: str


def load_probes(path: Path = config.DEV_PROBES_PATH) -> list[Probe]:
    """One Probe per JSONL line; ids must be unique and every probe expects something."""
    probes = []
    for line in path.read_text(encoding="utf-8").splitlines():
        if line.strip():
            raw = json.loads(line)
            day = raw["policy_date"] and date.fromisoformat(raw["policy_date"])
            expected = frozenset(raw["expected"])
            fields = (raw["id"], raw["kind"], raw["question"], expected, day, raw["note"])
            probes.append(Probe(*fields))
    ids = [p.id for p in probes]
    if len(ids) != len(set(ids)) or not all(p.expected for p in probes):
        raise ValueError(f"{path}: probe ids must be unique and each must expect a section")
    return probes


# A search function: (question, policy date) -> retrieved source_ids, best first.
Search = Callable[[str, date | None], list[str]]


def probe_ranks(

    probes: list[Probe], search: Search, lineage: dict[str, frozenset[str]]

) -> list[int | None]:
    """Per probe, the rank of its first hit (None = not among the retrieved)."""
    return [first_hit(search(p.question, p.policy_date), p.expected, lineage) for p in probes]


def report(probes: list[Probe], ranks: list[int | None]) -> list[str]:
    """Lines: one per probe, then the metrics overall and per kind."""
    lines = [
        f"{p.id}  rank {r if r else '-':>3}  {p.kind:14} {p.question}"
        for p, r in zip(probes, ranks, strict=True)
    ]
    groups = {"all": list(range(len(probes)))}
    for i, p in enumerate(probes):
        groups.setdefault(p.kind, []).append(i)
    for name, idx in groups.items():
        m = summarize([ranks[i] for i in idx])
        cells = "  ".join(f"{k} {v:.2f}" for k, v in m.items())
        lines.append(f"{name:14} ({len(idx):>2})  {cells}")
    return lines


def main() -> None:
    from coveragecheck.index import dense  # app/index code only when actually run
    from coveragecheck.index.hybrid import Retriever
    from coveragecheck.index.store import load_table

    retriever = Retriever.load(dense.fastembed_embedder())
    lineage = ancestry(load_table(config.INDEX_DIR / "sections.parquet"))

    def search(question: str, day: date | None) -> list[str]:
        return [c.source_id for c in retriever.search(question, day).candidates]

    probes = load_probes()
    print("\n".join(report(probes, probe_ranks(probes, search, lineage))))


if __name__ == "__main__":
    main()