From 91ef93243b17c0d7a91e1839ff14c8fffe09b4bc Mon Sep 17 00:00:00 2001 From: dietrich ayala Date: Tue, 18 Aug 2026 23:22:40 +0200 Subject: [PATCH] Add a retrieval-quality eval: query set, scorer, and baseline 25 known-answer queries across all 12 indexed repositories, a scorer that reuses embed() and Store.search() to report top-1/top-5 hit rate unscoped and repo-scoped, and the current index's baseline (24%/64% unscoped, 52%/76% repo-scoped) so later ranking changes have something concrete to be judged against instead of a handful of ad-hoc queries. --- eval/baseline.md | 45 +++++++++++++ eval/score.py | 126 +++++++++++++++++++++++++++++++++++ tests/test_score.py | 156 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 327 insertions(+) create mode 100644 eval/baseline.md create mode 100644 eval/score.py create mode 100644 tests/test_score.py diff --git a/eval/baseline.md b/eval/baseline.md new file mode 100644 index 0000000..1c023ac --- /dev/null +++ b/eval/baseline.md @@ -0,0 +1,45 @@ +# Retrieval baseline + +Recorded 2026-08-18 against the shared index at `~/.local/share/code-index/`: +2448 files, 37,704 chunks, 12 repositories, model `nomic-embed-text-v1.5.f16.gguf` +(built 2026-08-18 16:28:39). + +Query set: `eval/queries.jsonl`, 25 queries across all 12 indexed repositories. + +## Hit rate + +| | top-1 | top-5 | +|---|---|---| +| unscoped (`uv run python eval/score.py`) | 6/25 (24%) | 16/25 (64%) | +| repo-scoped (`uv run python eval/score.py --repo-scoped`) | 13/25 (52%) | 19/25 (76%) | + +Repo scoping roughly doubles top-1 hit rate (24% -> 52%) and lifts top-5 by 12 +points (64% -> 76%). Most of the gap between scoped and unscoped is +cross-repository ranking rather than retrieval failing outright: 6 of the 9 +unscoped top-5 misses become hits once the search is scoped to the right +repository, and the query's own repository directory almost always shows up +somewhere in an unscoped result set even when it doesn't win. + +## Misses that survive repo scoping + +Six queries miss the top 5 even scoped to their own repository — these are +retrieval failures, not cross-repository ranking noise: + +- `repo-e` — a Discord-mention scrubbing function, beaten by the repo's main + entry point. +- `repo-b` — a DID/service-type hashing helper, beaten by the main + server file. +- `repo-a` (x2) — a stalled-feature detector and the README's pipeline + description, both beaten by a dashboard-generation script that apparently + reads as topically closer to "pipeline" and "pass rate" language than the + actual sources. +- `repo-m` — a subdomain-slug validator, beaten by a spec document. +- `repo-h` — a ledger-replay accounting function, beaten by an unrelated + finite-state-machine spec file. + +## What this baseline is for + +Every later ranking change — dropping the path prefix from embedded text, +grouping results per repository, swapping the embedding model — is judged +against these four numbers rather than against a handful of ad-hoc queries. +Rerun both scorer invocations and diff the hit rates and the miss list. diff --git a/eval/score.py b/eval/score.py new file mode 100644 index 0000000..f1f7a12 --- /dev/null +++ b/eval/score.py @@ -0,0 +1,126 @@ +"""Scorer for the retrieval eval: known-answer queries against the live index. + +Reuses `code_index.embed.embed()` and `code_index.store.Store.search()` — the same +path `cli.py cmd_search()` takes — so this measures retrieval as a search actually +sees it rather than some parallel implementation of it. + + uv run python eval/score.py # unscoped + uv run python eval/score.py --repo-scoped # each query filtered to its own repo + +Run without CODE_INDEX_DATA set, so it scores the shared index every session +searches rather than an empty one built nowhere. +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from collections import defaultdict + +from code_index import embed +from code_index.store import Hit, Store + +QUERIES_PATH = os.path.join(os.path.dirname(__file__), "queries.jsonl") + + +def load_queries(path: str = QUERIES_PATH) -> list[dict]: + queries = [] + with open(path) as fh: + for line in fh: + line = line.strip() + if not line: + continue + queries.append(json.loads(line)) + return queries + + +def _matches(hit: Hit, query: dict) -> bool: + return os.path.basename(hit.repo) == query["repo"] and hit.rel == query["path"] + + +def run(queries: list[dict], store: Store, repo_scoped: bool, k: int = 5) -> list[dict]: + """Run every query, returning one result record each. + + A record carries whether `path` showed up in the top 1 / top 5 hits, and, on a + miss, what came back instead so a regression is diagnosable without a rerun. + """ + results = [] + for q in queries: + vec = embed.embed([q["query"]], is_query=True)[0] + repo = q["repo"] if repo_scoped else None + hits = store.search(vec, k=k, repo=repo) + results.append({ + "query": q, + "top1": bool(hits) and _matches(hits[0], q), + "top5": any(_matches(h, q) for h in hits), + "top_hit": f"{os.path.basename(hits[0].repo)}/{hits[0].rel}" if hits else None, + }) + return results + + +def summarize(results: list[dict]) -> tuple[dict, dict]: + """Overall and per-repo top-1 / top-5 hit counts.""" + overall = {"n": 0, "top1": 0, "top5": 0} + per_repo: dict[str, dict] = defaultdict(lambda: {"n": 0, "top1": 0, "top5": 0}) + for r in results: + for bucket in (overall, per_repo[r["query"]["repo"]]): + bucket["n"] += 1 + bucket["top1"] += r["top1"] + bucket["top5"] += r["top5"] + return overall, per_repo + + +def _rate(hit: int, n: int) -> float: + return hit / n if n else 0.0 + + +def print_report(results: list[dict], repo_scoped: bool, k: int = 5) -> None: + overall, per_repo = summarize(results) + label = "repo-scoped" if repo_scoped else "unscoped" + print(f"=== {label} ({overall['n']} queries) ===") + print( + f"overall: top-1 {overall['top1']}/{overall['n']} ({_rate(overall['top1'], overall['n']):.0%})" + f" top-5 {overall['top5']}/{overall['n']} ({_rate(overall['top5'], overall['n']):.0%})" + ) + for repo in sorted(per_repo): + b = per_repo[repo] + print( + f" {repo:20} top-1 {b['top1']}/{b['n']} ({_rate(b['top1'], b['n']):.0%})" + f" top-5 {b['top5']}/{b['n']} ({_rate(b['top5'], b['n']):.0%})" + ) + + misses = [r for r in results if not r["top5"]] + if misses: + print(f"misses (outside top {k}):") + for r in misses: + q = r["query"] + got = r["top_hit"] or "no hits" + print(f" [{q['repo']}] {q['query']!r} -> expected {q['path']}, got {got}") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Score the index against eval/queries.jsonl") + parser.add_argument("--queries", default=QUERIES_PATH, help="path to the query set") + parser.add_argument("-k", type=int, default=5, help="how many hits count as top-5") + parser.add_argument( + "--repo-scoped", action="store_true", + help="filter each query's search to its own repo", + ) + args = parser.parse_args(argv) + + queries = load_queries(args.queries) + store = Store(dim=embed.EMBED_DIM) + if store.vector_count() == 0: + print("index is empty; run `code-index index` first", file=sys.stderr) + return 1 + embed.start() + + results = run(queries, store, repo_scoped=args.repo_scoped, k=args.k) + print_report(results, repo_scoped=args.repo_scoped, k=args.k) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_score.py b/tests/test_score.py new file mode 100644 index 0000000..51c7e1e --- /dev/null +++ b/tests/test_score.py @@ -0,0 +1,156 @@ +"""The eval scorer, against a synthetic index with a known right answer. + +No embedding server and no model: `embed.embed` is replaced with a fixed +query -> vector lookup, and the index is built directly from unit vectors chosen so +which chunk ranks where is known ahead of time. The query set itself is data and is +never asserted on here — only that the scorer counts hits and misses correctly +against a fixed index. +""" + +from __future__ import annotations + +import os +import sys +import time + +import numpy as np +import pytest + +from code_index.store import Store + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "eval")) +import score # noqa: E402 + + +def unit(*values) -> np.ndarray: + vec = np.asarray(values, dtype=np.float32) + return vec / np.linalg.norm(vec) + + +@pytest.fixture +def store(tmp_path, monkeypatch): + monkeypatch.setattr("code_index.store.DATA_DIR", str(tmp_path)) + monkeypatch.setattr("code_index.store.DB_PATH", str(tmp_path / "index.sqlite3")) + monkeypatch.setattr("code_index.store.VEC_DIR", str(tmp_path / "vectors")) + st = Store(dim=4) + + # (repo, rel, start, end, text, vector) + rows = [ + ("/w/alpha", "one.ts", 1, 5, "alpha body", unit(1, 0, 0, 0)), + ("/w/beta", "two.ts", 1, 5, "beta body", unit(0, 1, 0, 0)), + # Same direction as alpha's chunk but ranks second within alpha, so a + # repo-scoped search for alpha still has to pick the right file. + ("/w/alpha", "decoy.ts", 1, 5, "decoy body", unit(0.9, 0.1, 0, 0)), + ] + now = time.time() + records = [(r, rel, f"sha-{rel}", s, e, t, now) for r, rel, s, e, t, _ in rows] + vectors = np.stack([v for *_, v in rows]).astype(np.float32) + st.rebuild(records, vectors) + return st + + +@pytest.fixture +def stub_embed(monkeypatch): + """Map a query's exact text to a fixed vector, so its rank is known ahead of time.""" + vectors: dict[str, np.ndarray] = {} + + def fake_embed(texts, is_query=False, timeout=None): + assert is_query, "the scorer must embed queries with is_query=True" + return np.stack([vectors[t] for t in texts]).astype(np.float32) + + monkeypatch.setattr(score.embed, "embed", fake_embed) + return vectors + + +def test_top1_hit_is_counted(store, stub_embed): + stub_embed["find alpha"] = unit(1, 0, 0, 0) + queries = [{"query": "find alpha", "repo": "alpha", "path": "one.ts"}] + + results = score.run(queries, store, repo_scoped=False) + + assert results[0]["top1"] is True + assert results[0]["top5"] is True + assert results[0]["top_hit"] == "alpha/one.ts" + + +def test_hit_outside_top1_but_within_top5_is_not_a_top1(store, stub_embed): + # Querying with decoy.ts's own direction outranks one.ts's exact match, so the + # expected answer lands in the top 5 but not top 1. + stub_embed["find alpha decoy"] = unit(0.9, 0.1, 0, 0) + queries = [{"query": "find alpha decoy", "repo": "alpha", "path": "one.ts"}] + + results = score.run(queries, store, repo_scoped=False) + + assert results[0]["top1"] is False + assert results[0]["top5"] is True + assert results[0]["top_hit"] == "alpha/decoy.ts" + + +def test_miss_reports_what_came_back_instead(store, stub_embed): + stub_embed["find beta"] = unit(0, 1, 0, 0) + # Ask for a path that is not what beta's own vector actually returns. + queries = [{"query": "find beta", "repo": "beta", "path": "nonexistent.ts"}] + + results = score.run(queries, store, repo_scoped=False) + + assert results[0]["top1"] is False + assert results[0]["top5"] is False + assert results[0]["top_hit"] == "beta/two.ts" + + +def test_repo_scoped_search_is_filtered_to_its_own_repo(store, stub_embed): + # Unscoped, this vector's nearest neighbours are all in beta; scoped to alpha it + # must still be forced to only alpha's chunks. + stub_embed["find in alpha only"] = unit(0.01, 1, 0, 0) + queries = [{"query": "find in alpha only", "repo": "alpha", "path": "one.ts"}] + + unscoped = score.run(queries, store, repo_scoped=False) + scoped = score.run(queries, store, repo_scoped=True) + + assert unscoped[0]["top_hit"] == "beta/two.ts" + assert scoped[0]["top_hit"] in ("alpha/one.ts", "alpha/decoy.ts") + + +def test_summarize_counts_overall_and_per_repo(store, stub_embed): + stub_embed["find alpha"] = unit(1, 0, 0, 0) + stub_embed["find beta"] = unit(0, 1, 0, 0) + stub_embed["find missing"] = unit(0, 0, 1, 0) + queries = [ + {"query": "find alpha", "repo": "alpha", "path": "one.ts"}, + {"query": "find beta", "repo": "beta", "path": "two.ts"}, + {"query": "find missing", "repo": "alpha", "path": "nonexistent.ts"}, + ] + + results = score.run(queries, store, repo_scoped=False) + overall, per_repo = score.summarize(results) + + assert overall == {"n": 3, "top1": 2, "top5": 2} + assert per_repo["alpha"] == {"n": 2, "top1": 1, "top5": 1} + assert per_repo["beta"] == {"n": 1, "top1": 1, "top5": 1} + + +def test_print_report_does_not_raise(store, stub_embed, capsys): + stub_embed["find alpha"] = unit(1, 0, 0, 0) + queries = [{"query": "find alpha", "repo": "alpha", "path": "one.ts"}] + + results = score.run(queries, store, repo_scoped=False) + score.print_report(results, repo_scoped=False) + + out = capsys.readouterr().out + assert "top-1" in out and "top-5" in out + + +def test_load_queries_parses_jsonl(tmp_path): + path = tmp_path / "queries.jsonl" + path.write_text( + '{"query": "a", "repo": "r", "path": "p"}\n' + "\n" + '{"query": "b", "repo": "r2", "path": "p2", "symbol": "Thing"}\n' + ) + + queries = score.load_queries(str(path)) + + assert queries == [ + {"query": "a", "repo": "r", "path": "p"}, + {"query": "b", "repo": "r2", "path": "p2", "symbol": "Thing"}, + ] -- knotmirror 0.0.1