"""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 queries used for that are synthetic: what is asserted is that the scorer counts hits and misses correctly against a fixed index, not that any real query set retrieves well. The one exception is the committed example set, whose answers name files in this repository and so can be checked for still existing. """ 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"}, ] def test_queries_path_prefers_the_local_set(tmp_path, monkeypatch): local = tmp_path / "queries.local.jsonl" local.write_text('{"query": "a", "repo": "r", "path": "p"}\n') monkeypatch.setattr(score, "EVAL_QUERIES", str(local)) monkeypatch.setattr(score, "EVAL_QUERIES_EXAMPLE", str(tmp_path / "example.jsonl")) assert score.queries_path() == str(local) def test_queries_path_falls_back_to_the_example_when_there_is_no_local_set( tmp_path, monkeypatch ): example = tmp_path / "example.jsonl" monkeypatch.setattr(score, "EVAL_QUERIES", str(tmp_path / "absent.jsonl")) monkeypatch.setattr(score, "EVAL_QUERIES_EXAMPLE", str(example)) assert score.queries_path() == str(example) def test_example_query_set_answers_point_at_files_that_exist(): """The committed example scores this repository, so its answers can be checked. A renamed file would otherwise turn into a permanent miss that reads as a retrieval failure. """ root = os.path.join(os.path.dirname(__file__), "..") for query in score.load_queries(score.EVAL_QUERIES_EXAMPLE): assert query["repo"] == "code-index" assert os.path.exists(os.path.join(root, query["path"])), query["path"]