File size: 9,915 Bytes
34d9afb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Evaluate retrieval against a versioned, domain-reviewed JSONL benchmark."""

from __future__ import annotations

import argparse
import json
import math
import time
from collections import defaultdict
from pathlib import Path
from typing import Any

import jsonschema

from infrastructure.database import search_vector_candidates
from infrastructure.embeddings import DEFAULT_MODEL, generate_embedding
from infrastructure.logger import get_logger, setup_logger
from infrastructure.vector_search import find_nearest_neighbors

logger = get_logger()
REQUIRED_CATEGORIES = {
    "paraphrase",
    "defined_term",
    "section_reference",
    "metadata_filter",
    "cross_document",
    "insufficient_context",
}


def _identity(item: dict[str, Any]) -> tuple[str, int]:
    return str(item.get("document_sha256") or ""), int(item["chunk_index"])


def retrieval_metrics(
    results: list[dict[str, Any]], relevant: list[dict[str, Any]], *, k: int = 5
) -> dict[str, float]:
    """Compute Recall, reciprocal rank, and graded nDCG at K."""
    ranked = [_identity(item) for item in results[:k]]
    grades = {_identity(item): int(item["grade"]) for item in relevant}
    if not grades:
        empty_score = 1.0 if not ranked else 0.0
        return {"recall": empty_score, "mrr": empty_score, "ndcg": empty_score}

    hits = [identity for identity in ranked if identity in grades]
    recall = len(set(hits)) / len(grades)
    first_rank = next(
        (rank for rank, identity in enumerate(ranked, start=1) if identity in grades),
        None,
    )
    mrr = 1.0 / first_rank if first_rank is not None else 0.0
    dcg = sum(
        (2 ** grades[identity] - 1) / math.log2(rank + 1)
        for rank, identity in enumerate(ranked, start=1)
        if identity in grades
    )
    ideal = sum(
        (2**grade - 1) / math.log2(rank + 1)
        for rank, grade in enumerate(sorted(grades.values(), reverse=True)[:k], start=1)
    )
    return {"recall": recall, "mrr": mrr, "ndcg": dcg / ideal if ideal else 0.0}


def _average(rows: list[dict[str, float]]) -> dict[str, float]:
    if not rows:
        return {"recall": 0.0, "mrr": 0.0, "ndcg": 0.0}
    return {
        metric: sum(row[metric] for row in rows) / len(rows)
        for metric in ("recall", "mrr", "ndcg")
    }


def _percentile(values: list[float], percentile: float) -> float:
    if not values:
        return 0.0
    ordered = sorted(values)
    index = max(0, math.ceil(percentile * len(ordered)) - 1)
    return ordered[index]


def _retrieve(row: dict[str, Any], *, top_k: int, mode: str) -> list[dict[str, Any]]:
    filters = row.get("filters") or {}
    if mode == "vector-baseline":
        query_vector = generate_embedding(row["query"], model=DEFAULT_MODEL)
        return (
            search_vector_candidates(
                query_vector,
                model=DEFAULT_MODEL,
                limit=top_k,
                filters=filters,
            )
            if query_vector
            else []
        )
    return find_nearest_neighbors(row["query"], top_k, where=filters)


def _filter_leaks(results: list[dict[str, Any]], filters: dict[str, Any]) -> int:
    leaks = 0
    for result in results:
        for name, expected in filters.items():
            if name == "doc_id":
                matches = int(result.get("doc_id") or 0) == int(expected)
            else:
                values = {
                    value.strip().casefold()
                    for value in str(result.get(name) or "").split(",")
                    if value.strip()
                }
                matches = str(expected).strip().casefold() in values
            if not matches:
                leaks += 1
                break
    return leaks


def load_benchmark(path: Path, *, allow_small: bool = False) -> list[dict[str, Any]]:
    """Load and validate approved benchmark rows."""
    schema_path = Path(__file__).parents[1] / "evals/retrieval/benchmark.schema.json"
    schema = json.loads(schema_path.read_text(encoding="utf-8"))
    rows: list[dict[str, Any]] = []
    for line_number, line in enumerate(
        path.read_text(encoding="utf-8").splitlines(), 1
    ):
        if not line.strip():
            continue
        row = json.loads(line)
        try:
            jsonschema.validate(row, schema)
        except jsonschema.ValidationError as exc:
            raise ValueError(
                f"invalid benchmark row {line_number}: {exc.message}"
            ) from exc
        rows.append(row)
    if not allow_small and len(rows) < 40:
        raise ValueError("acceptance benchmark must contain at least 40 approved rows")
    if not allow_small:
        missing_categories = REQUIRED_CATEGORIES - {
            str(row["category"]) for row in rows
        }
        if missing_categories:
            raise ValueError(
                "acceptance benchmark is missing categories: "
                + ", ".join(sorted(missing_categories))
            )
    if len({row["query_id"] for row in rows}) != len(rows):
        raise ValueError("benchmark query_id values must be unique")
    return rows


def evaluate(
    rows: list[dict[str, Any]],
    *,
    top_k: int = 5,
    mode: str = "hybrid",
    verify_determinism: bool = True,
) -> dict[str, Any]:
    """Run retrieval and aggregate benchmark metrics."""
    if top_k < 1 or top_k > 20:
        raise ValueError("top_k must be from 1 to 20")
    query_reports: list[dict[str, Any]] = []
    latencies: list[float] = []
    if rows:
        _retrieve(rows[0], top_k=top_k, mode=mode)
    for row in rows:
        started = time.perf_counter()
        results = _retrieve(row, top_k=top_k, mode=mode)
        latency_ms = (time.perf_counter() - started) * 1000
        latencies.append(latency_ms)
        repeat_ids: list[int] | None = None
        if verify_determinism:
            repeat_ids = [
                int(item["chunk_id"]) for item in _retrieve(row, top_k=top_k, mode=mode)
            ]
        result_ids = [int(item["chunk_id"]) for item in results]
        metrics = retrieval_metrics(results, row["relevant"], k=top_k)
        query_reports.append(
            {
                "query_id": row["query_id"],
                "category": row["category"],
                "latency_ms": latency_ms,
                "filter_leaks": _filter_leaks(results, row.get("filters") or {}),
                "deterministic": repeat_ids is None or repeat_ids == result_ids,
                **metrics,
            }
        )

    by_category: dict[str, list[dict[str, float]]] = defaultdict(list)
    for report in query_reports:
        by_category[report["category"]].append(report)
    return {
        "query_count": len(rows),
        "top_k": top_k,
        "mode": mode,
        "overall": _average(query_reports),
        "categories": {
            category: _average(category_rows)
            for category, category_rows in sorted(by_category.items())
        },
        "latency_ms": {
            "p50": _percentile(latencies, 0.50),
            "p95": _percentile(latencies, 0.95),
        },
        "filter_leaks": sum(report["filter_leaks"] for report in query_reports),
        "deterministic": all(report["deterministic"] for report in query_reports),
        "queries": query_reports,
    }


def compare(candidate: dict[str, Any], baseline: dict[str, Any]) -> dict[str, Any]:
    """Apply the approved quality and latency acceptance thresholds."""
    category_drops = {
        category: candidate["categories"].get(category, {}).get("ndcg", 0.0)
        - metrics["ndcg"]
        for category, metrics in baseline.get("categories", {}).items()
    }
    checks = {
        "ndcg_gain_at_least_0_05": (
            candidate["overall"]["ndcg"] - baseline["overall"]["ndcg"] >= 0.05
        ),
        "recall_not_lower": (
            candidate["overall"]["recall"] >= baseline["overall"]["recall"]
        ),
        "mrr_not_lower": candidate["overall"]["mrr"] >= baseline["overall"]["mrr"],
        "no_category_ndcg_drop_over_0_05": all(
            difference >= -0.05 for difference in category_drops.values()
        ),
        "zero_filter_leakage": candidate.get("filter_leaks") == 0,
        "deterministic_repeat_rankings": candidate.get("deterministic") is True,
        "p95_under_one_second": candidate["latency_ms"]["p95"] < 1000,
        "p95_no_more_than_twice_baseline": (
            candidate["latency_ms"]["p95"] <= 2 * max(baseline["latency_ms"]["p95"], 1)
        ),
    }
    return {"passed": all(checks.values()), "checks": checks}


def _parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("benchmark", type=Path)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--baseline", type=Path)
    parser.add_argument("--top-k", type=int, default=5)
    parser.add_argument(
        "--mode", choices=("hybrid", "vector-baseline"), default="hybrid"
    )
    parser.add_argument("--skip-determinism-check", action="store_true")
    parser.add_argument("--allow-small", action="store_true", help=argparse.SUPPRESS)
    return parser


def main() -> int:
    setup_logger()
    args = _parser().parse_args()
    rows = load_benchmark(args.benchmark, allow_small=args.allow_small)
    report = evaluate(
        rows,
        top_k=args.top_k,
        mode=args.mode,
        verify_determinism=not args.skip_determinism_check,
    )
    if args.baseline:
        baseline = json.loads(args.baseline.read_text(encoding="utf-8"))
        report["acceptance"] = compare(report, baseline)
    args.output.write_text(
        json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8"
    )
    logger.info("Wrote retrieval benchmark report to %s", args.output)
    return 0 if report.get("acceptance", {}).get("passed", True) else 1


if __name__ == "__main__":
    raise SystemExit(main())