From 1f2beb02c5cfbec214d9a7e441cbeb4a93b47fbf Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Mon, 16 Nov 2026 22:55:54 +0530 Subject: [PATCH 1/2] feat(retrieval): vector-mode retrieve with brute-force cosine knn (T09) --- src/caliper/retrieval/__init__.py | 175 ++++++++++++++++++++++ tests/unit/test_retrieval.py | 237 ++++++++++++++++++++++++++++++ 2 files changed, 412 insertions(+) create mode 100644 src/caliper/retrieval/__init__.py create mode 100644 tests/unit/test_retrieval.py diff --git a/src/caliper/retrieval/__init__.py b/src/caliper/retrieval/__init__.py new file mode 100644 index 0000000..23835b2 --- /dev/null +++ b/src/caliper/retrieval/__init__.py @@ -0,0 +1,175 @@ +"""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 +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. + +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. +""" + +from __future__ import annotations + +import re +import sqlite3 +from dataclasses import dataclass + +import sqlite_vec # type: ignore[import-untyped] + +from caliper.config import CaliperConfig, fp8 +from caliper.db import get_chunks +from caliper.providers import EmbeddingBackend, get_embeddings +from caliper.providers.base import EMBEDDING_DIMENSIONS + + +class RetrievalError(Exception): + """Retrieval failed hard on its inputs or the index (§16 typed exception). + + Raised for caller-contract violations only: an empty question, a + retrieval mode this module does not implement, or a query embedding whose + dimension is not 768. Mapped to the §9 error envelope at the CLI/web + edges (later tasks). Graceful retrieval outcomes — fewer index rows than + `final_k`, an empty index, a missing index — never raise; they return + fewer passages or [] (§9.3, §11.5). Dependency failures keep their own + typed exceptions (`DbError`, `ProviderError`) and propagate unchanged. + """ + + +@dataclass(frozen=True, slots=True) +class Passage: + """One ranked passage with an observable score (§7.5) and stage tag (§9.3). + + §7.5 lists six fields; `stage` — required per passage by §9.3 and by the + `request_retrievals` schema check (`vector`|`fts`|`rrf`|`rerank`, §8.5) — + is the seventh, defaulted to "vector", the only mode this module + implements. Smallest reconciliation; recorded in docs/TASKS.md (T09). + """ + + chunk_id: int + page_url: str + heading_path: str + body: str + score: float + rank: int + stage: str = "vector" + + +_FP8_RE = re.compile(r"[0-9a-f]{8}") + + +def _check_suffix(suffix: str) -> None: + """Validate an fp8 table suffix: 8 lowercase hex chars, like db does. + + Mirrors db's private `_check_suffix` instead of importing it (db.py is a + single-owner file, §14.4): table names are interpolated into SQL, so the + suffix must never be arbitrary text. `retrieve` always derives the suffix + from `config.fp8(cfg)`, making this defense in depth. + """ + if _FP8_RE.fullmatch(suffix) is None: + raise RetrievalError(f"invalid table suffix {suffix!r}: expected 8 lowercase hex chars") + + +def _vec_table_exists(conn: sqlite3.Connection, suffix: str) -> bool: + """True when the per-fingerprint vec0 table exists (created at ingest, §8.3).""" + row = conn.execute( + "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", + (f"chunks_{suffix}_vec",), + ).fetchone() + return row is not None + + +def _knn( + conn: sqlite3.Connection, suffix: str, query_vector: list[float], k: int +) -> list[tuple[int, float]]: + """Brute-force cosine KNN over the vec0 table (§7.5): (chunk_id, distance). + + `MATCH ... AND k = ?` is the stable sqlite-vec path (bound parameters, + verified on the pinned sqlite-vec 0.1.9); no ANN indexes are used or + created. Fewer rows than `k` simply return fewer hits, which is how the + §9.3 fewer-rows contract is served. sqlite errors surface as + RetrievalError with the sqlite message attached (DEBUG detail stays in + the cause chain). + """ + _check_suffix(suffix) + try: + rows = conn.execute( + f"SELECT rowid, distance FROM chunks_{suffix}_vec WHERE embedding MATCH ? AND k = ?", + (sqlite_vec.serialize_float32(query_vector), k), + ).fetchall() + except sqlite3.Error as exc: + raise RetrievalError(f"vector KNN query failed on chunks_{suffix}_vec: {exc}") from exc + return [(int(row[0]), float(row[1])) for row in rows] + + +def retrieve( + question: str, + conn: sqlite3.Connection, + cfg: CaliperConfig, + *, + embeddings: EmbeddingBackend | None = None, +) -> list[Passage]: + """Turn a question into the final bounded passage set (§7.5, §9.3). + + Vector mode: embed the question via the provider seam — `embed_query`, + which carries the retrieval *query* task type inside each backend and + emits 768-dim vectors (§7.2) — then cosine KNN top `cfg.retrieval.final_k` + over the fingerprint's vec0 table. Returns exactly `final_k` passages + ranked 1 (most similar) → `final_k`, `score` = cosine distance (lower is + more similar), `stage = "vector"`; deterministic on fixed input (ties are + broken by ascending chunk_id). + + 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. + """ + if not question.strip(): + raise RetrievalError("question must be a non-empty string") + mode = cfg.retrieval.mode + if mode != "vector": + raise RetrievalError( + f"retrieval mode {mode!r} is not implemented here (hybrid_rrf is T10, 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: + raise RetrievalError( + f"query embedding has dimension {len(query_vector)}, expected {EMBEDDING_DIMENSIONS}" + ) + suffix = fp8(cfg) + if not _vec_table_exists(conn, suffix): + # 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 [] + hits = _knn(conn, suffix, query_vector, cfg.retrieval.final_k) + # Deterministic order regardless of vec0's internal tie handling: + # ascending distance (= descending relevance), chunk_id as tie-break. + hits.sort(key=lambda hit: (hit[1], hit[0])) + chunks = get_chunks(conn, suffix, [chunk_id for chunk_id, _ in hits]) + return [ + Passage( + chunk_id=chunk.chunk_id, + page_url=chunk.page_url, + heading_path=chunk.heading_path, + body=chunk.body, + score=distance, + rank=rank, + stage="vector", + ) + for rank, (chunk, (_, distance)) in enumerate(zip(chunks, hits, strict=True), start=1) + ] diff --git a/tests/unit/test_retrieval.py b/tests/unit/test_retrieval.py new file mode 100644 index 0000000..7444fb4 --- /dev/null +++ b/tests/unit/test_retrieval.py @@ -0,0 +1,237 @@ +"""T09 unit tests: the vector-mode retrieval core (§7.5, §9.3). + +Seeds a per-fingerprint index through T03's accessors and exercises only the +public `retrieve` interface with the suite's FakeEmbeddings — fakes are the +only mocks (§15): no network, no patch()/monkeypatch. +""" + +import hashlib +import sqlite3 +from collections.abc import Iterator +from pathlib import Path + +import pytest +from fakes import FakeEmbeddings, cosine, fake_embedding + +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 = "How do I configure retries on a timer trigger?" + +# Body 0 tokenizes identically to the question (FakeEmbeddings hashes +# [a-z0-9]+ tokens, punctuation ignored) → cosine distance ≈ 0. Body 1 shares +# "timer" → clearly second. Bodies 2+ share no vocabulary with the question → +# distance ≈ 1, forming the tie group the top-2 outrank. +BODIES = [ + "how do i configure retries on a timer trigger", + "retry configuration for timer triggers", + "azure functions hosting plans and scaling", + "service bus queue message lock duration", + "blob storage account properties and tiers", + "deploy to staging slots with github actions", +] + + +@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 v1 preset (vector mode, final_k=5), optionally user-overridden.""" + user = tmp_path / "user.toml" + user.write_text(user_toml, encoding="utf-8") + return load_config(user, CONFIGS / "v1.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). + + Stored embeddings come from the same deterministic hash the question is + embedded with, so similarity between bodies and the question is exact. + """ + 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 _expected_distances(question: str, bodies: list[str]) -> list[float]: + """Oracle distances (1 - cosine) matching the vec0 cosine metric.""" + query = fake_embedding(question) + return [1.0 - cosine(query, fake_embedding(body)) for body in bodies] + + +# --- determinism + shape (§9.3) ------------------------------------------------- + + +def test_retrieve_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 + assert len(first) == 5 + + +def test_retrieve_returns_exactly_final_k_passages( + conn: sqlite3.Connection, tmp_path: Path +) -> None: + cfg = _load_cfg(tmp_path) + chunk_ids = _seed_index(conn, cfg, BODIES) + assert len(chunk_ids) == 6 # one more than final_k + + 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] + scores = [p.score for p in passages] + assert scores == sorted(scores) # distance ascending = relevance descending (§9.3) + assert all(p.stage == "vector" for p in passages) + # The two chunks sharing question vocabulary are guaranteed top-2; the + # remaining slots come from the distance-tied unrelated group, whose + # exact membership at the k-boundary is vec0's choice — only the top-2 + # identities and the strict separation are asserted. + assert passages[0].chunk_id == chunk_ids[0] + assert passages[1].chunk_id == chunk_ids[1] + assert passages[0].score == pytest.approx(0.0, abs=1e-6) + assert passages[1].score < passages[2].score + + +def test_retrieve_ranks_closest_chunk_first_with_cosine_scores( + conn: sqlite3.Connection, tmp_path: Path +) -> None: + cfg = _load_cfg(tmp_path) + chunk_ids = _seed_index(conn, cfg, BODIES[: cfg.retrieval.final_k]) + expected = sorted( + zip(chunk_ids, _expected_distances(QUESTION, BODIES[: cfg.retrieval.final_k]), strict=True), + key=lambda hit: (hit[1], hit[0]), + ) + + passages = retrieve(QUESTION, conn, cfg, embeddings=FakeEmbeddings()) + + # The closest chunk (identical vocabulary) ranks first. + assert passages[0].chunk_id == expected[0][0] + assert passages[0].score == pytest.approx(expected[0][1], abs=1e-6) + # Every score matches the vec0 cosine distance within float32 precision. + for passage, (_, distance) in zip( + sorted(passages, key=lambda p: p.score), + sorted(expected, key=lambda hit: hit[1]), + strict=True, + ): + assert passage.score == pytest.approx(distance, abs=1e-6) + + +def test_retrieve_returns_fewer_passages_when_index_has_fewer_rows( + conn: sqlite3.Connection, tmp_path: Path +) -> None: + cfg = _load_cfg(tmp_path) + chunk_ids = _seed_index(conn, cfg, BODIES[:3]) + + passages = retrieve(QUESTION, conn, cfg, embeddings=FakeEmbeddings()) + + # §9.3: fewer rows than final_k → fewer passages, caller refuses; no + # sentinel scores are fabricated (§11.5). + assert [p.rank for p in passages] == [1, 2, 3] + assert [p.chunk_id for p in passages] == chunk_ids # closest first + assert all(p.stage == "vector" for p in passages) + + +def test_retrieve_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()) == [] + + +def test_retrieve_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()) == [] + + +# --- typed hard failures (§16) -------------------------------------------------- + + +@pytest.mark.parametrize("question", ["", " ", "\t\n"]) +def test_retrieve_rejects_empty_question( + conn: sqlite3.Connection, tmp_path: Path, question: str +) -> None: + cfg = _load_cfg(tmp_path) + + with pytest.raises(RetrievalError, match="non-empty"): + retrieve(question, conn, cfg, embeddings=FakeEmbeddings()) + + +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', + ) + + with pytest.raises(RetrievalError, match="not implemented"): + retrieve(QUESTION, conn, cfg, embeddings=FakeEmbeddings()) + + +def test_retrieve_rejects_wrong_embedding_dimension( + conn: sqlite3.Connection, tmp_path: Path +) -> None: + cfg = _load_cfg(tmp_path) + + with pytest.raises(RetrievalError, match="dimension"): + retrieve(QUESTION, conn, cfg, embeddings=FakeEmbeddings(dimensions=64)) + + +# --- provider seam usage (§7.5) ------------------------------------------------- + + +def test_retrieve_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" # embed_query, the retrieval query task type From 379642ba65ca28defbf7600c58fcce7fa85a0219 Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Mon, 16 Nov 2026 23:15:13 +0530 Subject: [PATCH 2/2] chore(tasks): mark t09 in progress --- docs/TASKS.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/TASKS.md b/docs/TASKS.md index 5338552..8449ab0 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -22,6 +22,7 @@ Statuses: ✅ done · 🔄 doing · ⬜ remaining · ✂️ cut (stretch only, p | ID | Branch | Status | |---|---|---| | T05 | arch/caliper/t05 | implemented, verification below | +| T09 | arch/caliper/t09 | implemented, verification below | ## Remaining @@ -116,3 +117,8 @@ Statuses: ✅ done · 🔄 doing · ⬜ remaining · ✂️ cut (stretch only, p - **T05 — cache layout + pin semantics:** `/azure-docs/<40-hex-sha>.tar.gz` plus a per-branch pin pointer `/azure-docs/main.json` (`branch`, `sha`, `source_ref`, `fetched_at`), written atomically (tmp + `os.replace`). Cache hit = pointer + tarball both present ⇒ zero network calls and the pin stays the first-fetch ref (fulfilling "pinned ref recorded at first ingest"); corrupt pointer raises `SourceError` (loud, never silently refetched); pointer with missing tarball is a repairable miss; a sha-keyed tarball already on disk is reused without redownload. Distinct refs coexist (keyed by sha); `refresh=True` re-resolves + refetches and re-points. - **T05 — mapping/exclusion decisions:** `page_to_url` normalizes `\` → `/` and accepts nested slugs under the two trees (Learn mirrors the docs path); it rejects only out-of-tree paths, non-`.md` extensions, and empty slugs — `_`/`includes` filtering is `discover_pages`' job (segment-based, so a filename like `includes-guide.md` is kept). `discover_pages` raises `SourceError` when the root or either article tree is missing — that is the A1-failure signal for the `_fetch_via_toc_api` fallback seam, which stays deliberately unimplemented (`NotImplementedError`). The 5 URL-mapping test pages (`functions-timer`, `functions-bindings-timer`, `functions-create-first-function-vscode`, `service-bus-messaging-overview`, `service-bus-queues-topics-subscriptions`) are mapping tests per the T05 spec, not existence tests; the first two are the slugs already used in ARCHITECTURE §8 examples. - **T05 — extraction contract handed to T07:** the upstream tarball has one top-level `azure-docs-/` directory (mirrored by the test fixtures); T07 must strip it and pass the inner root — the directory containing `articles/` — to `discover_pages`. +- **T09 — `Passage` carries a 7th field `stage` (§7.5 vs §9.3 reconciliation):** §7.5 lists six Passage fields, but §9.3 requires a per-passage `stage` tag and the `request_retrievals` schema check constrains it (`vector`|`fts`|`rrf`|`rerank`, §8.5). Smallest reconciliation: `stage: str = "vector"` as a defaulted 7th field on the frozen dataclass — the six §7.5 fields are unchanged, and T10 (rrf) / T18 (rerank) override it per passage. +- **T09 — vec0 KNN query lives in `retrieval/__init__.py`, not `db.py`:** no KNN accessor existed and `db.py` is T03-owned (§14.4 single-owner), so `retrieve` runs `SELECT rowid, distance FROM chunks__vec WHERE embedding MATCH ? AND k = ?` directly on the passed conn (verified on the pinned sqlite-vec 0.1.9 / Windows: bound-`k` works, `k` > row count returns all rows, `distance` is the cosine distance ≈ 0 for identical vectors). The fp8-suffix validation is replicated locally (8 lowercase hex, mirroring db's private `_check_suffix` rather than importing the private symbol); the suffix always derives from `config.fp8(cfg)` inside `retrieve`, so the check is defense in depth. `get_chunks` remains the metadata accessor (order-preserving). +- **T09 — "score sentinel handling" resolves to §9.3's fewer-returns:** no sentinel `score` value exists. If the index holds fewer rows than `final_k`, the KNN query returns fewer hits and `retrieve` returns that many passages (ranks still 1..n) — the caller refuses (§9.3, §11.5). A missing (never-ingested) or empty vec0 table likewise returns [] gracefully; distinguishing §9's `index_missing` envelope from a plain refusal is the caller's edge decision, not retrieval's. +- **T09 — public API frozen for T10/T11/T18:** `Passage` (frozen dataclass: `chunk_id`, `page_url`, `heading_path`, `body`, `score`, `rank`, `stage="vector"`), `RetrievalError` (hard failures only: empty question, unimplemented mode, query-embedding dimension ≠ 768 — graceful cases never raise), and `retrieve(question, conn, cfg, *, embeddings=None) -> list[Passage]`: the positional §9.3 signature is unchanged; the keyword-only `embeddings` seam accepts any `EmbeddingBackend` and defaults to the `get_embeddings(cfg)` factory path (T04's session/`keepalive` pattern), which is also how tests inject `FakeEmbeddings` without `patch()` (§15). `score` = cosine distance, **lower = more similar**; ties broken by ascending `chunk_id`; `hybrid_rrf` raises `RetrievalError("not implemented")` until T10 wires `fuse.py`; `vector_top_k` is unused in vector mode (KNN `k = final_k`, §7.5) — it is the hybrid candidate depth for T10. T11 consumes passages sorted by `rank` and must not assume sentinel scores. +- **T09 — verification (2026-11-16):** `uv run pytest -q` — 134 passed when T09 landed alone (122 prior + 12 new retrieval tests: determinism, exactly-`final_k` shape, closest-ranks-first with oracle cosine distances, fewer-rows, empty/missing index → [], typed errors, query-task-type seam); 166 passed on the combined stack with T05; `ruff check` + `ruff format --check` + `mypy` strict clean. Rebuilt onto `main` (post-#8-squash) as `1f2beb0` before PR #7 merge.