From 7a11c4f2a70cd481867e164472a4adf362844399 Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Tue, 17 Nov 2026 21:48:17 +0530 Subject: [PATCH] feat(retrieval): rrf fusion with hybrid_rrf mode wiring (T10) --- src/caliper/retrieval/__init__.py | 179 +++++++++++++++-- src/caliper/retrieval/fuse.py | 41 ++++ tests/unit/test_fuse.py | 112 +++++++++++ tests/unit/test_retrieval.py | 10 +- tests/unit/test_retrieval_hybrid.py | 286 ++++++++++++++++++++++++++++ 5 files changed, 606 insertions(+), 22 deletions(-) create mode 100644 src/caliper/retrieval/fuse.py create mode 100644 tests/unit/test_fuse.py create mode 100644 tests/unit/test_retrieval_hybrid.py diff --git a/src/caliper/retrieval/__init__.py b/src/caliper/retrieval/__init__.py index 23835b2..9b7d32b 100644 --- a/src/caliper/retrieval/__init__.py +++ b/src/caliper/retrieval/__init__.py @@ -1,18 +1,24 @@ """Retrieval core (§7.5, §9.3): question → final bounded passage set. -T09 implements `mode = "vector"`: cosine KNN top-`cfg.retrieval.final_k` over -the per-fingerprint `chunks__vec` table, using the stable brute-force +`mode = "vector"` (T09): cosine KNN top-`cfg.retrieval.final_k` over the +per-fingerprint `chunks__vec` table, using the stable brute-force sqlite-vec path (`WHERE embedding MATCH ? AND k = ?`) — no ANN indexes -(§7.5). `mode = "hybrid_rrf"` (vector + FTS5 fusion in T10's `fuse.py`) and -cross-encoder reranking (T18) are not wired here and raise until they are. +(§7.5). `mode = "hybrid_rrf"` (T10): the same brute-force KNN at candidate +depth `vector_top_k` plus an FTS5 BM25 query at depth `fts_top_k`, fused by +Reciprocal Rank Fusion (`fuse.rrf`, k = `rrf_k`) and cut to `final_k`; +`score` is then the fused RRF score (higher = more relevant) and every +passage carries `stage = "rrf"`. Cross-encoder reranking (T18) is not wired +here; `retrieval.rerank` is passed through untouched. Contract (§9.3): exactly `final_k` passages sorted by descending relevance — -ascending cosine distance, so LOWER `score` means MORE similar (the schema's -`distance_metric=cosine` yields ≈0 for identical vectors, per T03's tests) — -`rank` 1-based with 1 = best, and `stage = "vector"` on every passage. If the -index holds fewer rows than `final_k`, fewer passages come back and the -caller refuses (§9.3, §11.5); an empty or never-ingested index returns []. -No sentinel scores are ever fabricated. +in vector mode ascending cosine distance, so LOWER `score` means MORE +similar (the schema's `distance_metric=cosine` yields ≈0 for identical +vectors, per T03's tests); in hybrid_rrf mode descending RRF score, so +HIGHER `score` means MORE relevant — `rank` 1-based with 1 = best, and the +per-mode `stage` tag on every passage. If the index holds fewer rows than +`final_k`, fewer passages come back and the caller refuses (§9.3, §11.5); +an empty or never-ingested index returns []. No sentinel scores are ever +fabricated. """ from __future__ import annotations @@ -27,6 +33,7 @@ from caliper.db import get_chunks from caliper.providers import EmbeddingBackend, get_embeddings from caliper.providers.base import EMBEDDING_DIMENSIONS +from caliper.retrieval.fuse import rrf class RetrievalError(Exception): @@ -108,6 +115,135 @@ def _knn( return [(int(row[0]), float(row[1])) for row in rows] +def _fts_table_exists(conn: sqlite3.Connection, suffix: str) -> bool: + """True when the per-fingerprint FTS5 table exists (created at ingest, §8.3).""" + row = conn.execute( + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", + (f"chunks_{suffix}_fts",), + ).fetchone() + return row is not None + + +def _fts_escape(question: str) -> str | None: + """Escape a raw question into a safe FTS5 MATCH query string (§7.5). + + Each whitespace-separated term is wrapped in double quotes (FTS5 quoted + strings, so punctuation cannot form query syntax) and embedded double + quotes are stripped, so user input can never break the MATCH or inject + operators. A term kept only if it still contains a word character — a + purely punctuation term would tokenize to an empty phrase. Returns None + when no queryable term survives, which the caller treats as "no keyword + candidates" (graceful), never as an error. + """ + terms = [ + f'"{stripped}"' + for term in question.split() + if (stripped := term.replace('"', "")) and any(ch.isalnum() for ch in stripped) + ] + return " ".join(terms) if terms else None + + +def _bm25(conn: sqlite3.Connection, suffix: str, question: str, k: int) -> list[int]: + """Best-first chunk ids from the FTS5 BM25 keyword query (§7.5). + + External-content FTS5 (content='chunks_', content_rowid='chunk_id', + trigger-synced, T03), so bm25() reads the live bodies and the FTS rowid + IS the chunk id — selected as `rowid AS chunk_id` (the FTS table has no + chunk_id column of its own). `bm25()` returns negative values where + MORE negative = MORE relevant, so ascending score is best-first; the + `chunk_id` tie-break mirrors the vector mode's deterministic rule — both + ties (identical bm25, e.g. duplicate bodies) and FTS's internal order + must not leak nondeterminism into the fused ranking. Fewer rows than + `k` (or zero rows) simply return fewer hits — graceful (§9.3). sqlite + errors surface as RetrievalError with the message attached. + """ + _check_suffix(suffix) + query = _fts_escape(question) + if query is None: + return [] + try: + rows = conn.execute( + f"SELECT rowid AS chunk_id, bm25(chunks_{suffix}_fts) AS score" + f" FROM chunks_{suffix}_fts" + f" WHERE chunks_{suffix}_fts MATCH ? ORDER BY score, chunk_id LIMIT ?", + (query, k), + ).fetchall() + except sqlite3.Error as exc: + raise RetrievalError(f"FTS query failed on chunks_{suffix}_fts: {exc}") from exc + return [int(row[0]) for row in rows] + + +def _retrieve_hybrid_rrf( + question: str, + conn: sqlite3.Connection, + cfg: CaliperConfig, + embeddings: EmbeddingBackend | None, +) -> list[Passage]: + """hybrid_rrf mode (§7.5 binding): vector + FTS5 candidates fused by RRF. + + Vector KNN at candidate depth `vector_top_k` (20 in §9.7) + FTS5 BM25 at + depth `fts_top_k` (20), fused by `fuse.rrf` with k = `rrf_k` (60), then + cut to `final_k` (5). Each returned passage's `score` is its fused RRF + score — HIGHER = MORE relevant, the opposite polarity of vector mode's + cosine distance — and `stage = "rrf"`; `rerank` is T18's stage on top of + this list and is deliberately untouched here. + + A missing candidate source degrades gracefully (§9.3): a never-ingested + fingerprint (neither table) returns [], a missing vec0 or FTS5 table + contributes an empty list so the fused result is the other list alone + re-scored by RRF, and a MATCH with zero keyword hits does the same. An + empty fusion returns []. No new hard failures are introduced beyond the + config guard below and the shared question/embedding checks. + """ + # Config guard (§11.4): a v1/v2-shaped config turned to hybrid_rrf without + # the fusion knobs is a config error, raised as a RetrievalError like the + # other hard failures here (RetrievalConfig's model validator already + # rejects this at load time; this is defense in depth for bypassed models). + if cfg.retrieval.fts_top_k < 1 or cfg.retrieval.rrf_k < 1: + raise RetrievalError( + "hybrid_rrf requires retrieval.fts_top_k > 0 and retrieval.rrf_k >= 1" + " (a v1/v2 preset lacks the fusion knobs; §11.4)" + ) + backend = embeddings if embeddings is not None else get_embeddings(cfg) + query_vector = backend.embed_query(question) + if len(query_vector) != EMBEDDING_DIMENSIONS: + raise RetrievalError( + f"query embedding has dimension {len(query_vector)}, expected {EMBEDDING_DIMENSIONS}" + ) + suffix = fp8(cfg) + has_vec = _vec_table_exists(conn, suffix) + has_fts = _fts_table_exists(conn, suffix) + if not has_vec and not has_fts: + # Never-ingested fingerprint ≡ empty index (§11.5): graceful [] — the + # caller refuses; distinguishing §9's `index_missing` from a plain + # refusal is the caller's edge decision. No sentinel passages. + return [] + vector_ids: list[int] = [] + if has_vec: + # Same deterministic order as vector mode: ascending distance (= more + # similar first), ascending chunk_id on ties. + hits = _knn(conn, suffix, query_vector, cfg.retrieval.vector_top_k) + hits.sort(key=lambda hit: (hit[1], hit[0])) + vector_ids = [chunk_id for chunk_id, _ in hits] + fts_ids = _bm25(conn, suffix, question, cfg.retrieval.fts_top_k) if has_fts else [] + fused = rrf(vector_ids, fts_ids, k=cfg.retrieval.rrf_k)[: cfg.retrieval.final_k] + if not fused: + return [] + chunks = get_chunks(conn, suffix, [chunk_id for chunk_id, _ in fused]) + return [ + Passage( + chunk_id=chunk.chunk_id, + page_url=chunk.page_url, + heading_path=chunk.heading_path, + body=chunk.body, + score=score, + rank=rank, + stage="rrf", + ) + for rank, (chunk, (_, score)) in enumerate(zip(chunks, fused, strict=True), start=1) + ] + + def retrieve( question: str, conn: sqlite3.Connection, @@ -125,25 +261,32 @@ def retrieve( more similar), `stage = "vector"`; deterministic on fixed input (ties are broken by ascending chunk_id). + hybrid_rrf mode (T10, §7.5): the same embedding seam, then vector KNN top + `cfg.retrieval.vector_top_k` + FTS5 BM25 top `cfg.retrieval.fts_top_k` + fused by `fuse.rrf` (k = `cfg.retrieval.rrf_k`) and cut to `final_k`. + `score` = the fused RRF score (higher is more relevant), `stage = "rrf"`; + keyword candidates are RRF-scored even when the FTS side is empty. + The embedding backend is built with the provider factory (`get_embeddings`, which owns session setup per T04's `keepalive` pattern). Tests inject a backend through the keyword-only `embeddings` seam — the suite's fakes, §15 — so the positional §9.3 contract `retrieve(question, conn, cfg)` is unchanged. - Failure modes (§16): empty question, unimplemented mode, or a - non-768-dim query embedding raise RetrievalError. An index with fewer - rows than `final_k`, an empty index, or a missing (never-ingested) index - return fewer passages or [] — the caller refuses per §9.3/§11.5; no - sentinel `score` value is introduced. + Failure modes (§16): empty question, unimplemented mode, a hybrid_rrf + config missing the fusion knobs (§11.4 config guard), or a non-768-dim + query embedding raise RetrievalError. An index with fewer rows than + `final_k`, an empty index, or a missing (never-ingested) index return + fewer passages or [] — the caller refuses per §9.3/§11.5; no sentinel + `score` value is introduced. """ if not question.strip(): raise RetrievalError("question must be a non-empty string") mode = cfg.retrieval.mode + if mode == "hybrid_rrf": + return _retrieve_hybrid_rrf(question, conn, cfg, embeddings) if mode != "vector": - raise RetrievalError( - f"retrieval mode {mode!r} is not implemented here (hybrid_rrf is T10, rerank is T18)" - ) + raise RetrievalError(f"retrieval mode {mode!r} is not implemented here (rerank is T18)") backend = embeddings if embeddings is not None else get_embeddings(cfg) query_vector = backend.embed_query(question) if len(query_vector) != EMBEDDING_DIMENSIONS: diff --git a/src/caliper/retrieval/fuse.py b/src/caliper/retrieval/fuse.py new file mode 100644 index 0000000..654db49 --- /dev/null +++ b/src/caliper/retrieval/fuse.py @@ -0,0 +1,41 @@ +"""Reciprocal Rank Fusion (§7.5): combine two ranked candidate lists. + +Pure module: no I/O, no config, no db access (§7.5 "rrf ... in fuse.py"). The +hybrid_rrf wiring in `caliper.retrieval` calls `rrf` with the vector KNN +top-`vector_top_k` and the FTS5 BM25 top-`fts_top_k` candidate lists and +stamps the fused passages `stage="rrf"`; the cross-encoder stage (T18) sits +on top of this fused list. +""" + +from __future__ import annotations + +from collections.abc import Sequence + + +def rrf( + vector_list: Sequence[int], fts_list: Sequence[int], k: int = 60 +) -> list[tuple[int, float]]: + """Fuse two best-first ranked lists with Reciprocal Rank Fusion (§7.5). + + Textbook RRF: a document's fused score is the sum, over each input list + that contains it, of `1 / (k + rank)` with 1-based ranks — a document in + both lists collects both contributions, a document in one list only gets + one. `k` dampens top ranks: with small `k` the first position dominates, + while the preset `k = 60` (§9.7) makes appearing in both lists matter + more than ranking first in one. + + Inputs are ordered best-first and must not repeat a document within one + list (ranked candidate lists never do). Identity is the chunk id, so a + document present in both lists is deduplicated into a single fused entry. + + Returns (chunk_id, fused_score) pairs sorted by descending fused score, + ties broken by ascending chunk_id — the same deterministic tie rule as + vector mode (T09). An empty pair of inputs yields []; one empty input + degrades to the other list re-scored by RRF. No sentinel scores are + fabricated; the fused score is always a positive float. + """ + fused: dict[int, float] = {} + for ranked in (vector_list, fts_list): + for rank, chunk_id in enumerate(ranked, start=1): + fused[chunk_id] = fused.get(chunk_id, 0.0) + 1.0 / (k + rank) + return sorted(fused.items(), key=lambda item: (-item[1], item[0])) diff --git a/tests/unit/test_fuse.py b/tests/unit/test_fuse.py new file mode 100644 index 0000000..fdc74f2 --- /dev/null +++ b/tests/unit/test_fuse.py @@ -0,0 +1,112 @@ +"""T10 unit tests: the pure Reciprocal Rank Fusion function (§7.5). + +Hand-computed fixtures against the textbook formula +`score(d) = Σ 1/(k + rank_i(d))` over each input list containing d, ranks +1-based, lists ordered best-first. No db, no config, no fakes — fuse.py is +pure, so these tests are too. +""" + +import pytest + +from caliper.retrieval.fuse import rrf + +K = 60 + + +def _score(rank: int, k: int = K) -> float: + """One list's RRF contribution for a 1-based rank.""" + return 1.0 / (k + rank) + + +# --- the textbook formula -------------------------------------------------------- + + +def test_doc_in_both_lists_collects_both_contributions() -> None: + # vector: 1st, 2nd, 3rd; fts: 3rd, 2nd, 4th — every fused score by hand. + fused = rrf([1, 2, 3], [3, 2, 4], k=K) + + expected = { + 1: _score(1), # vector rank 1 only + 2: _score(2) + _score(2), # vector rank 2 + fts rank 2 + 3: _score(3) + _score(1), # vector rank 3 + fts rank 1 + 4: _score(3), # fts rank 3 only + } + assert [doc for doc, _ in fused] == [3, 2, 1, 4] + for doc, score in fused: + assert score == pytest.approx(expected[doc]) + + +def test_doc_in_one_list_only_keeps_one_contribution() -> None: + fused = rrf([7, 3, 5], [], k=K) + + assert [doc for doc, _ in fused] == [7, 3, 5] + assert fused[0][1] == pytest.approx(_score(1)) + assert fused[1][1] == pytest.approx(_score(2)) + assert fused[2][1] == pytest.approx(_score(3)) + + +def test_ranks_are_one_based_positions_of_the_input_lists() -> None: + # Only the position in each list matters — not any upstream score. + fused = rrf([100, 200], [300], k=K) + by_doc = dict(fused) + assert by_doc[100] == pytest.approx(_score(1)) + assert by_doc[200] == pytest.approx(_score(2)) + assert by_doc[300] == pytest.approx(_score(1)) + + +# --- k semantics ------------------------------------------------------------------ + + +def test_k_dampens_top_ranks_appearing_twice_beats_ranking_first_once() -> None: + # doc 2: rank 2 in BOTH lists; docs 1 and 9: rank 1 in one list each; + # doc 3: rank 3 in the vector list only. k = 60 (preset): two mid-rank + # contributions outweigh one top rank → doc 2 first, docs 1/9 tie behind + # it, and the vector-only doc 3 trails them all. + fused = rrf([1, 2, 3], [9, 2], k=K) + assert [doc for doc, _ in fused] == [2, 1, 9, 3] + assert fused[0][1] == pytest.approx(2.0 / (K + 2)) + assert fused[1][1] == pytest.approx(1.0 / (K + 1)) + assert fused[2][1] == pytest.approx(1.0 / (K + 1)) + assert fused[3][1] == pytest.approx(1.0 / (K + 3)) + + # k = 0: 1/rank makes a single first place worth 1.0, so docs 1/2/9 all + # tie (doc 2 collects 1/2 + 1/2) — the same lists flip to id order. k is + # what breaks the tie towards the document appearing in both lists. + fused_k0 = rrf([1, 2, 3], [9, 2], k=0) + assert [doc for doc, _ in fused_k0] == [1, 2, 9, 3] + + +def test_preset_k_60_default_matches_explicit_k() -> None: + assert rrf([1, 2, 3], [3, 2, 4]) == rrf([1, 2, 3], [3, 2, 4], k=60) + + +# --- ties and determinism --------------------------------------------------------- + + +def test_ties_break_by_ascending_chunk_id() -> None: + # Both documents collect identical contributions (1st + 2nd in reverse + # lists) → identical fused scores → ascending chunk_id stabilizes order. + fused = rrf([5, 2], [2, 5], k=K) + assert [doc for doc, _ in fused] == [2, 5] + assert fused[0][1] == pytest.approx(_score(1) + _score(2)) + assert fused[1][1] == pytest.approx(_score(1) + _score(2)) + + +def test_rrf_is_deterministic_on_fixed_input() -> None: + assert rrf([4, 8, 15], [16, 8], k=K) == rrf([4, 8, 15], [16, 8], k=K) + + +# --- graceful edges ---------------------------------------------------------------- + + +def test_both_lists_empty_yields_empty() -> None: + assert rrf([], []) == [] + + +def test_empty_list_degrades_to_the_other_list_reranked() -> None: + # One candidate source missing (e.g. zero FTS hits) is graceful: the other + # list's order is kept, re-scored with RRF contributions (§9.3). + fused = rrf([11, 22], [], k=K) + assert [doc for doc, _ in fused] == [11, 22] + assert fused[0][1] == pytest.approx(_score(1)) + assert fused[1][1] == pytest.approx(_score(2)) diff --git a/tests/unit/test_retrieval.py b/tests/unit/test_retrieval.py index 7444fb4..2fb8bf6 100644 --- a/tests/unit/test_retrieval.py +++ b/tests/unit/test_retrieval.py @@ -201,10 +201,12 @@ def test_retrieve_rejects_empty_question( def test_retrieve_rejects_unimplemented_mode(conn: sqlite3.Connection, tmp_path: Path) -> None: - cfg = _load_cfg( - tmp_path, - '[retrieval]\nmode = "hybrid_rrf"\nvector_top_k = 20\nfts_top_k = 20\n', - ) + # hybrid_rrf is wired since T10; a mode outside the §7.5 pair still raises. + # RetrievalConfig's Literal rejects bogus modes at load time (§11.4), so + # this injects one past validation with pydantic's bypassing model_copy. + cfg = _load_cfg(tmp_path) + bogus = cfg.retrieval.model_copy(update={"mode": "semantic"}) + cfg = cfg.model_copy(update={"retrieval": bogus}) with pytest.raises(RetrievalError, match="not implemented"): retrieve(QUESTION, conn, cfg, embeddings=FakeEmbeddings()) diff --git a/tests/unit/test_retrieval_hybrid.py b/tests/unit/test_retrieval_hybrid.py new file mode 100644 index 0000000..8fafa26 --- /dev/null +++ b/tests/unit/test_retrieval_hybrid.py @@ -0,0 +1,286 @@ +"""T10 unit tests: hybrid_rrf mode wiring in `retrieve` (§7.5, §9.3). + +Mirrors test_retrieval's fixture style (T09): a per-fingerprint index seeded +through T03's accessors, exercised only through the public `retrieve` with +FakeEmbeddings — fakes are the only mocks (§15): no network, no patch(). + +The bodies are chosen so both candidate rankings are hand-derivable with the +FakeEmbeddings hashing trick: the question "timer trigger retry" shares all +three tokens with bodies 0/1 (0 identical → vector rank 1), one token with +body 2, none with bodies 3+. FTS5's default tokenizer has no stemming and the +escaped MATCH query ANDs the terms, so only bodies containing *all three* +question tokens ("timer", "trigger", "retry") become keyword candidates — +body 0 (shortest full match) then body 1, by bm25's length normalization. +""" + +import hashlib +import sqlite3 +from collections.abc import Iterator +from pathlib import Path + +import pytest +from fakes import FakeEmbeddings + +from caliper.config import CaliperConfig, fp8, load_config +from caliper.db import ( + ChunkRow, + connect, + ensure_chunks_tables, + ensure_schema, + insert_chunk_embeddings, + insert_chunks, +) +from caliper.retrieval import RetrievalError, retrieve + +REPO_ROOT = Path(__file__).resolve().parents[2] +CONFIGS = REPO_ROOT / "configs" + +QUESTION = "timer trigger retry" + +BODIES = [ + "timer trigger retry", # vector rank 1, FTS rank 1 (all 3 terms, shortest) + "timer trigger retry soon", # vector rank 2, FTS rank 2 (all 3 terms, longer) + "retry", # vector rank 3 (1 token), FTS: no (missing 2 terms) + "blob storage account tiers", # no overlap with the question at all + "service bus queue lock", + "deployment slots staging", +] + + +@pytest.fixture() +def conn() -> Iterator[sqlite3.Connection]: + """A connected, schema-initialized in-memory database (as in test_db).""" + connection = connect(":memory:") + ensure_schema(connection) + yield connection + connection.close() + + +def _load_cfg(tmp_path: Path, user_toml: str = "") -> CaliperConfig: + """The v3 preset (hybrid_rrf, 20/20/60, rerank=cross-encoder), overridable.""" + user = tmp_path / "user.toml" + user.write_text(user_toml, encoding="utf-8") + return load_config(user, CONFIGS / "v3.toml") + + +def _seed_index(conn: sqlite3.Connection, cfg: CaliperConfig, bodies: list[str]) -> list[int]: + """Create the per-fingerprint trio and fill it the way ingest would (§7.4).""" + suffix = fp8(cfg) + ensure_chunks_tables(conn, suffix) + chunk_ids = insert_chunks( + conn, + suffix, + [ + ChunkRow( + page_url=f"https://learn.microsoft.com/en-us/azure/azure-functions/page-{i}", + heading_path=f"Docs > Section {i}", + body=body, + body_tokens=len(body.split()), + chunk_hash=hashlib.sha256(body.encode("utf-8")).hexdigest(), + ordinal=i - 1, + ) + for i, body in enumerate(bodies, start=1) + ], + ) + vectors = FakeEmbeddings().embed_documents(bodies) + insert_chunk_embeddings(conn, suffix, list(zip(chunk_ids, vectors, strict=True))) + return chunk_ids + + +def _rrf_score(rank: int, k: int = 60) -> float: + """One candidate list's RRF contribution at a 1-based rank.""" + return 1.0 / (k + rank) + + +# --- end-to-end fusion on the v3 preset (§9.7) ------------------------------------ + + +def test_hybrid_rrf_end_to_end_on_v3_preset(conn: sqlite3.Connection, tmp_path: Path) -> None: + cfg = _load_cfg(tmp_path) + assert cfg.retrieval.mode == "hybrid_rrf" + assert cfg.retrieval.rerank == "cross-encoder" # T18's stage: passed through untouched + chunk_ids = _seed_index(conn, cfg, BODIES) + + passages = retrieve(QUESTION, conn, cfg, embeddings=FakeEmbeddings()) + + assert len(passages) == cfg.retrieval.final_k + assert [p.rank for p in passages] == [1, 2, 3, 4, 5] + assert all(p.stage == "rrf" for p in passages) + # Top 3 are exactly the hand-derived fusion: body 0 wins both lists + # (1/61 + 1/61), body 1 is second in both (1/62 + 1/62), body 2 is + # vector-only rank 3 (1/63). k = 60 semantics: appearing in both lists + # beats a single top rank, and both-list bodies outrank vector-only ones. + assert passages[0].chunk_id == chunk_ids[0] + assert passages[0].score == pytest.approx(2.0 / 61.0, abs=1e-9) + assert passages[1].chunk_id == chunk_ids[1] + assert passages[1].score == pytest.approx(2.0 / 62.0, abs=1e-9) + assert passages[2].chunk_id == chunk_ids[2] + assert passages[2].score == pytest.approx(1.0 / 63.0, abs=1e-9) + # Slots 4-5 come from the no-overlap tie group (vector ranks 4-6 only); + # only their identity domain and the strictly descending fused order + # are asserted — the k-boundary membership is vec0's choice (cf. T09). + scores = [p.score for p in passages] + assert scores == sorted(scores, reverse=True) + assert set(p.chunk_id for p in passages[3:]) <= set(chunk_ids[3:]) + assert all(p.score < passages[2].score for p in passages[3:]) + + +def test_hybrid_rrf_is_deterministic_on_fixed_input( + conn: sqlite3.Connection, tmp_path: Path +) -> None: + cfg = _load_cfg(tmp_path) + _seed_index(conn, cfg, BODIES) + + first = retrieve(QUESTION, conn, cfg, embeddings=FakeEmbeddings()) + second = retrieve(QUESTION, conn, cfg, embeddings=FakeEmbeddings()) + + assert first == second # identical ids, scores, ranks, stage + + +# --- candidate depths and fusion degradation (§9.3 graceful) ----------------------- + + +def test_vector_top_k_is_the_fusion_candidate_depth( + conn: sqlite3.Connection, tmp_path: Path +) -> None: + # vector_top_k = 1: only body 0 is a vector candidate, so bodies 2+ drop + # out of the fusion entirely (FTS AND-semantics excludes them anyway); + # body 1 survives on its FTS rank alone — fused result has fewer than + # final_k rows, returned gracefully (§9.3: the caller refuses). + cfg = _load_cfg(tmp_path, "[retrieval]\nvector_top_k = 1\n") + chunk_ids = _seed_index(conn, cfg, BODIES) + + passages = retrieve(QUESTION, conn, cfg, embeddings=FakeEmbeddings()) + + assert [p.chunk_id for p in passages] == chunk_ids[:2] + assert [p.rank for p in passages] == [1, 2] + assert all(p.stage == "rrf" for p in passages) + assert passages[0].score == pytest.approx(2.0 / 61.0, abs=1e-9) # rank 1 in both lists + assert passages[1].score == pytest.approx(_rrf_score(2), abs=1e-9) # FTS rank 2 only + + +def test_fts_zero_hits_falls_back_to_vector_only_with_rrf_scores( + conn: sqlite3.Connection, tmp_path: Path +) -> None: + # No body contains these tokens: the FTS MATCH returns zero rows — NOT a + # hard failure; the fused result is the vector list alone, still + # RRF-scored: consecutive ranks 1..6 → 1/61 .. 1/66, cut to final_k = 5. + cfg = _load_cfg(tmp_path) + _seed_index(conn, cfg, BODIES) + + passages = retrieve("zzz qqq", conn, cfg, embeddings=FakeEmbeddings()) + + assert len(passages) == 5 + assert [p.rank for p in passages] == [1, 2, 3, 4, 5] + assert all(p.stage == "rrf" for p in passages) + for passage, rank in zip(passages, range(1, 6), strict=True): + assert passage.score == pytest.approx(_rrf_score(rank), abs=1e-9) + + +def test_fts_match_gracefully_absent_for_punctuation_only_question( + conn: sqlite3.Connection, tmp_path: Path +) -> None: + # "???" leaves no queryable FTS term after escaping — the keyword side is + # skipped (never a FTS5 syntax error) and vector-only fusion still runs. + cfg = _load_cfg(tmp_path) + _seed_index(conn, cfg, BODIES) + + passages = retrieve("???", conn, cfg, embeddings=FakeEmbeddings()) + + assert len(passages) == 5 + assert all(p.stage == "rrf" for p in passages) + + +# --- FTS escaping (§7.5 safety) ----------------------------------------------------- + + +def test_question_with_quotes_matches_its_clean_equivalent( + conn: sqlite3.Connection, tmp_path: Path +) -> None: + # Embedded double quotes are stripped before quoting each term, so the + # escaped MATCH query (and the hash-tokenized query embedding) are + # identical to the plain question's — same fused result, byte for byte. + cfg = _load_cfg(tmp_path) + _seed_index(conn, cfg, BODIES) + + nasty = retrieve('"timer trigger" retry?', conn, cfg, embeddings=FakeEmbeddings()) + clean = retrieve(QUESTION, conn, cfg, embeddings=FakeEmbeddings()) + + assert nasty == clean + + +def test_question_with_fts_syntax_characters_does_not_raise( + conn: sqlite3.Connection, tmp_path: Path +) -> None: + # Operators and injection attempts must never reach MATCH as syntax: each + # whitespace term is quoted, so this degrades to a keyword query matching + # nothing ANDed with terms no body holds — zero FTS hits, graceful. + cfg = _load_cfg(tmp_path) + _seed_index(conn, cfg, BODIES) + + passages = retrieve('timer" OR 1=1 --', conn, cfg, embeddings=FakeEmbeddings()) + + assert all(p.stage == "rrf" for p in passages) + assert len(passages) <= cfg.retrieval.final_k + + +# --- graceful empty/missing index (§11.5) ------------------------------------------- + + +def test_hybrid_rrf_returns_empty_list_for_missing_index( + conn: sqlite3.Connection, tmp_path: Path +) -> None: + cfg = _load_cfg(tmp_path) # never ingested: no per-fingerprint trio at all + + assert retrieve(QUESTION, conn, cfg, embeddings=FakeEmbeddings()) == [] + + +def test_hybrid_rrf_returns_empty_list_for_empty_index( + conn: sqlite3.Connection, tmp_path: Path +) -> None: + cfg = _load_cfg(tmp_path) + ensure_chunks_tables(conn, fp8(cfg)) # trio exists, no chunks/embeddings + + assert retrieve(QUESTION, conn, cfg, embeddings=FakeEmbeddings()) == [] + + +# --- config guard (§11.4) ------------------------------------------------------------ + + +@pytest.mark.parametrize( + ("zeroed", "offending"), + [ + ({"fts_top_k": 0}, "fts_top_k"), + ({"rrf_k": 0}, "rrf_k"), + ], +) +def test_hybrid_rrf_without_fusion_knobs_is_a_config_error( + conn: sqlite3.Connection, tmp_path: Path, zeroed: dict[str, int], offending: str +) -> None: + # RetrievalConfig's model validator rejects these at load time (§11.4); + # inject them past validation to pin the defense-in-depth guard in + # retrieve, raised as a RetrievalError like the other hard failures. + cfg = _load_cfg(tmp_path) + bypassed = cfg.retrieval.model_copy(update=zeroed) + cfg = cfg.model_copy(update={"retrieval": bypassed}) + + with pytest.raises(RetrievalError, match=offending): + retrieve(QUESTION, conn, cfg, embeddings=FakeEmbeddings()) + + +# --- provider seam usage (§7.5) ------------------------------------------------------- + + +def test_hybrid_rrf_embeds_query_once_with_query_task_type( + conn: sqlite3.Connection, tmp_path: Path +) -> None: + cfg = _load_cfg(tmp_path) + _seed_index(conn, cfg, BODIES) + embeddings = FakeEmbeddings() + + retrieve(QUESTION, conn, cfg, embeddings=embeddings) + + assert len(embeddings.calls) == 1 + (call,) = embeddings.calls + assert call.texts == (QUESTION,) + assert call.task_type == "query"