"""Index storage and ranking. Vectors live in a file matrix and their metadata in SQLite, joined by row number. If those two ever disagree, search returns the wrong source for the right vector — a silent corruption rather than an error — so the alignment is what these check. """ from __future__ import annotations import os import time import numpy as np import pytest from code_index.store import Store def store_dir(store: Store) -> str: """The directory holding this store's generation files.""" return os.path.dirname(store._generation_path(1)) @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")) return Store(dim=4) def unit(*values) -> np.ndarray: vec = np.asarray(values, dtype=np.float32) return vec / np.linalg.norm(vec) def build(store, rows): """rows: (repo, rel, start, end, text, vector)""" 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) store.rebuild(records, vectors) def test_search_ranks_by_similarity(store): build(store, [ ("/w/a", "one.ts", 1, 10, "first", unit(1, 0, 0, 0)), ("/w/a", "two.ts", 1, 10, "second", unit(0, 1, 0, 0)), ("/w/a", "three.ts", 1, 10, "third", unit(0.9, 0.1, 0, 0)), ]) hits = store.search(unit(1, 0, 0, 0), k=3) assert [h.rel for h in hits] == ["one.ts", "three.ts", "two.ts"] assert hits[0].score > hits[1].score > hits[2].score def test_a_query_from_a_different_model_is_refused(store): """A model swap changes the vector width, and the two spaces cannot be mixed.""" build(store, [("/w/a", "one.ts", 1, 10, "first", unit(1, 0, 0, 0))]) with pytest.raises(ValueError, match="dimensional"): store.search(unit(1, 0, 0, 0, 0, 0), k=1) def test_hit_metadata_matches_its_vector(store): """The join between matrix row and metadata row must not drift.""" rows = [ ("/w/a", f"file{i}.ts", i * 10 + 1, i * 10 + 9, f"body {i}", unit(*[ 1.0 if j == i % 4 else 0.0 for j in range(4) ])) for i in range(12) ] build(store, rows) for i, (_, rel, start, end, text, vec) in enumerate(rows): hits = store.search(vec, k=12) match = [h for h in hits if h.rel == rel] assert match, f"{rel} not returned for its own vector" assert match[0].start_line == start assert match[0].end_line == end assert match[0].text == text def test_repo_filter_restricts_results(store): build(store, [ ("/w/alpha", "one.ts", 1, 5, "a", unit(1, 0, 0, 0)), ("/w/beta", "two.ts", 1, 5, "b", unit(1, 0, 0, 0.01)), ]) hits = store.search(unit(1, 0, 0, 0), k=5, repo="beta") assert [h.rel for h in hits] == ["two.ts"] def test_path_filter_restricts_results(store): build(store, [ ("/w/a", "src/main/app.ts", 1, 5, "a", unit(1, 0, 0, 0)), ("/w/a", "src/test/app.ts", 1, 5, "b", unit(1, 0, 0, 0.01)), ]) hits = store.search(unit(1, 0, 0, 0), k=5, path_filter="test/") assert [h.rel for h in hits] == ["src/test/app.ts"] def test_filter_does_not_starve_results(store): """A filtered search must reach past a large block of non-matching top hits.""" rows = [ ("/w/noise", f"n{i}.ts", 1, 5, "noise", unit(1, 0, 0, 0)) for i in range(500) ] rows.append(("/w/wanted", "target.ts", 1, 5, "wanted", unit(0.99, 0.01, 0, 0))) build(store, rows) hits = store.search(unit(1, 0, 0, 0), k=3, repo="wanted") assert [h.rel for h in hits] == ["target.ts"] def test_rebuild_replaces_rather_than_appends(store): build(store, [("/w/a", "old.ts", 1, 5, "old", unit(1, 0, 0, 0))]) build(store, [("/w/a", "new.ts", 1, 5, "new", unit(1, 0, 0, 0))]) assert store.stats()["chunks"] == 1 assert store.vector_count() == 1 assert [h.rel for h in store.search(unit(1, 0, 0, 0), k=5)] == ["new.ts"] def test_mismatched_vector_count_is_rejected(store): """Silently accepting this would misalign every hit after the gap.""" now = time.time() records = [("/w/a", "one.ts", "sha", 1, 5, "x", now)] with pytest.raises(ValueError): store.rebuild(records, np.zeros((2, 4), dtype=np.float32)) def test_search_on_empty_index_returns_nothing(store): assert store.search(unit(1, 0, 0, 0), k=5) == [] def test_stats_counts_files_not_chunks(store): build(store, [ ("/w/a", "one.ts", 1, 5, "a", unit(1, 0, 0, 0)), ("/w/a", "one.ts", 6, 10, "b", unit(0, 1, 0, 0)), ("/w/a", "two.ts", 1, 5, "c", unit(0, 0, 1, 0)), ]) stats = store.stats() assert stats["files"] == 2 assert stats["chunks"] == 3 def test_meta_round_trips(store): store.set_meta("model", "nomic") store.set_meta("model", "nomic-v2") assert store.get_meta("model") == "nomic-v2" assert store.get_meta("absent") is None def test_each_rebuild_writes_a_new_generation(store): """Overwriting one matrix in place is what let a reader see a mismatched pair.""" build(store, [("/w/a", "one.ts", 1, 5, "first", unit(1, 0, 0, 0))]) gen1 = int(store.get_meta("vector_generation")) path1 = store._generation_path(gen1) build(store, [("/w/a", "two.ts", 1, 5, "second", unit(0, 1, 0, 0))]) gen2 = int(store.get_meta("vector_generation")) assert gen2 > gen1 assert store._generation_path(gen2) != path1 # The superseded matrix survives, so a reader mid-search can still open it. assert os.path.exists(path1) def test_a_reader_holding_an_old_generation_still_reads_it(store): """A search resolves its generation, then reads rows; a checkpoint between the two must not leave it pointing at a file that has been deleted.""" build(store, [("/w/a", "one.ts", 1, 5, "first", unit(1, 0, 0, 0))]) old_gen = int(store.get_meta("vector_generation")) old = store._load_vectors(old_gen) assert old is not None build(store, [("/w/a", "two.ts", 1, 5, "second", unit(0, 1, 0, 0))]) still_there = store._load_vectors(old_gen) assert still_there is not None assert np.allclose(np.asarray(still_there), np.asarray(old)) def test_old_generations_are_eventually_pruned(store): """Otherwise a long-lived index accumulates a matrix per checkpoint.""" for i in range(6): build(store, [("/w/a", f"f{i}.ts", 1, 5, f"body {i}", unit(1, 0, 0, 0))]) remaining = [n for n in os.listdir(store_dir(store)) if n.startswith("vectors.")] assert len(remaining) <= 2 def test_search_uses_the_generation_the_metadata_names(store): """A stale matrix left on disk must never be the one that gets searched.""" build(store, [("/w/a", "old.ts", 1, 5, "old body", unit(1, 0, 0, 0))]) build(store, [("/w/a", "new.ts", 1, 5, "new body", unit(1, 0, 0, 0))]) hits = store.search(unit(1, 0, 0, 0), k=5) assert [h.text for h in hits] == ["new body"] def test_search_with_zero_k_returns_nothing(store): build(store, [("/w/a", "one.ts", 1, 5, "x", unit(1, 0, 0, 0))]) assert store.search(unit(1, 0, 0, 0), k=0) == [] def source_store(tmp_path) -> Store: """A second store on its own files, standing in for the shadow a build writes.""" return Store( dim=4, db_path=str(tmp_path / "source" / "index.sqlite3"), vec_dir=str(tmp_path / "source" / "vectors"), ) def test_replace_from_publishes_the_whole_source_index(store, tmp_path): build(store, [("/w/a", "old.ts", 1, 5, "old body", unit(1, 0, 0, 0))]) source = source_store(tmp_path) build(source, [ ("/w/a", "new.ts", 1, 5, "new body", unit(1, 0, 0, 0)), ("/w/b", "extra.ts", 1, 5, "extra body", unit(0, 1, 0, 0)), ]) source.set_meta("built_at", "2026-01-01 00:00:00") store.replace_from(source) assert store.stats()["chunks"] == 2 assert store.vector_count() == 2 assert [h.text for h in store.search(unit(1, 0, 0, 0), k=5)][0] == "new body" assert store.get_meta("built_at") == "2026-01-01 00:00:00" def test_replace_from_keeps_every_row_paired_with_its_vector(store, tmp_path): """Taking rows from one store and a matrix from another is where the join between the two could drift, and drift here returns a plausible wrong answer.""" source = source_store(tmp_path) rows = [ ("/w/a", f"file{i}.ts", i * 10 + 1, i * 10 + 9, f"body {i}", unit(*[ 1.0 if j == i % 4 else 0.0 for j in range(4) ])) for i in range(12) ] build(source, rows) store.replace_from(source) for _, rel, start, end, text, vec in rows: hits = store.search(vec, k=12) match = [h for h in hits if h.rel == rel] assert match, f"{rel} not returned for its own vector" assert match[0].start_line == start assert match[0].text == text def test_replace_from_drops_whole_files_a_short_matrix_cannot_cover(store, tmp_path): """A source that died between writing its rows and its matrix must not hand over a file with only some of its chunks: it would match on sha next run and stay truncated for good.""" source = source_store(tmp_path) build(source, [ ("/w/a", "one.ts", 1, 5, "one only chunk", unit(1, 0, 0, 0)), ("/w/a", "two.ts", 1, 5, "two first chunk", unit(0, 1, 0, 0)), ("/w/a", "two.ts", 6, 10, "two second chunk", unit(0, 0, 1, 0)), ]) path = source._generation_path(int(source.get_meta("vector_generation"))) np.save(path, np.load(path)[:2]) # the last vector never reached disk store.replace_from(source) assert {r["rel"] for r in store.all_chunks()} == {"one.ts"} assert store.vector_count() == 1 def test_replace_from_a_source_that_published_nothing_changes_nothing(store, tmp_path): """A run killed before its first checkpoint must not empty the live index.""" build(store, [("/w/a", "one.ts", 1, 5, "one", unit(1, 0, 0, 0))]) generation = store.get_meta("vector_generation") store.replace_from(source_store(tmp_path)) assert store.get_meta("vector_generation") == generation assert store.stats()["chunks"] == 1 assert [h.text for h in store.search(unit(1, 0, 0, 0), k=5)] == ["one"] def add(store, rows): """Append rows the way a checkpoint publishes what it embedded since the last one. Same tuple shape as `build`.""" 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) store.append(records, vectors) def test_append_keeps_what_was_already_there(store): build(store, [("/w/a", "one.ts", 1, 5, "one", unit(1, 0, 0, 0))]) add(store, [("/w/a", "two.ts", 1, 5, "two", unit(0, 1, 0, 0))]) assert store.stats()["chunks"] == 2 assert store.vector_count() == 2 assert [h.text for h in store.search(unit(1, 0, 0, 0), k=1)] == ["one"] assert [h.text for h in store.search(unit(0, 1, 0, 0), k=1)] == ["two"] def test_append_keeps_every_row_paired_with_its_vector(store): """Rows added at the end take row numbers that have to land on the vectors written at the same offset, or a search answers with someone else's text.""" rows = [ ("/w/a", f"file{i}.ts", i * 10 + 1, i * 10 + 9, f"body {i}", unit(*[ 1.0 if j == i % 4 else 0.0 for j in range(4) ])) for i in range(12) ] build(store, rows[:3]) add(store, rows[3:7]) add(store, rows[7:]) for _, rel, start, end, text, vec in rows: match = [h for h in store.search(vec, k=12) if h.rel == rel] assert match, f"{rel} not returned for its own vector" assert match[0].start_line == start assert match[0].text == text def test_append_grows_the_matrix_it_already_has(store): """The point of appending: what is already stored is not written again.""" build(store, [("/w/a", "one.ts", 1, 5, "one", unit(1, 0, 0, 0))]) generation = int(store.get_meta("vector_generation")) before = os.stat(store._generation_path(generation)) add(store, [("/w/a", "two.ts", 1, 5, "two", unit(0, 1, 0, 0))]) after = os.stat(store._generation_path(generation)) assert int(store.get_meta("vector_generation")) == generation assert after.st_ino == before.st_ino, "the matrix was rewritten, not extended" assert after.st_size > before.st_size def test_append_does_not_reach_into_an_index_it_handed_over(store, tmp_path): """A matrix published by replace_from is one file under two names. A build that went on appending to its own name would be writing inside an index that is being searched.""" source = source_store(tmp_path) build(source, [("/w/a", "one.ts", 1, 5, "one", unit(1, 0, 0, 0))]) store.replace_from(source) generation = int(source.get_meta("vector_generation")) shared = store._generation_path(int(store.get_meta("vector_generation"))) before = os.stat(shared).st_size add(source, [("/w/a", "two.ts", 1, 5, "two", unit(0, 1, 0, 0))]) assert int(source.get_meta("vector_generation")) != generation assert os.stat(shared).st_size == before assert store.stats()["chunks"] == 1 assert store.vector_count() == 1 assert source.stats()["chunks"] == 2 assert source.vector_count() == 2 def test_append_of_a_mismatched_vector_count_is_rejected(store): build(store, [("/w/a", "one.ts", 1, 5, "one", unit(1, 0, 0, 0))]) now = time.time() with pytest.raises(ValueError): store.append( [("/w/a", "two.ts", "sha", 1, 5, "two", now)], np.zeros((2, 4), dtype=np.float32), ) def test_truncate_drops_the_tail_and_the_files_that_held_it(store): build(store, [ ("/w/a", "one.ts", 1, 5, "one", unit(1, 0, 0, 0)), ("/w/a", "two.ts", 1, 5, "two first", unit(0, 1, 0, 0)), ("/w/a", "two.ts", 6, 10, "two second", unit(0, 0, 1, 0)), ]) store.truncate(1) assert {r["rel"] for r in store.all_chunks()} == {"one.ts"} assert store.stats()["files"] == 1 # The dropped vectors are still in the matrix; nothing may return them. assert [h.text for h in store.search(unit(0, 1, 0, 0), k=5)] == ["one"] def test_append_after_a_truncate_writes_over_what_it_freed(store): """The matrix keeps its length across a truncate, so the next append has to land on the abandoned vectors rather than after them.""" build(store, [ ("/w/a", "one.ts", 1, 5, "one", unit(1, 0, 0, 0)), ("/w/b", "gone.ts", 1, 5, "abandoned", unit(0, 1, 0, 0)), ]) store.truncate(1) add(store, [("/w/c", "three.ts", 1, 5, "three", unit(0, 0, 1, 0))]) assert store.stats()["chunks"] == 2 assert store.vector_count() == 2 assert [h.text for h in store.search(unit(0, 0, 1, 0), k=1)] == ["three"] assert "abandoned" not in [h.text for h in store.search(unit(0, 1, 0, 0), k=2)]