diff --git a/docs/TASKS.md b/docs/TASKS.md index 0b24167..c1879a8 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -17,7 +17,10 @@ Statuses: ✅ done · 🔄 doing · ⬜ remaining · ✂️ cut (stretch only, p ## Doing -_(none — next up: **T03**, pending review; T04 is parallelizable with it per §14.3)_ +| ID | Branch | Status | +|---|---|---| +| T03 | `arch/caliper/t03` | Implemented + verified (commit `2409b2a`); awaiting review before PR | +| T04 | `arch/caliper/t04` (worktree) | Implemented + verified (`e6b5517`, `89e5423`); PR raised; **Ollama smoke leg deferred** (user decision 2026-11-16): Gemini leg passed live, Ollama leg re-run when Ollama is installed | ## Remaining @@ -91,3 +94,18 @@ _(none — next up: **T03**, pending review; T04 is parallelizable with it per - **T02 — merge order (§11.2 ambiguity):** the version preset is loaded first and the user config is deep-merged *over* it (user wins on conflicts). Rationale: this is the only reading consistent with A2's fallback path ("flip `CALIPER_PROVIDER=ollama`" requires overriding `answer.model`/`embeddings.model`, which preset-wins would forbid since presets are committed). FR-10 comparability is not weakened: identity is enforced by the fingerprint gate (§7.8), computed from the resolved config, not by the merge order. - **T02 — `answer.prompt_template_sha256`:** presets carry the SHA-256 of the empty string as a placeholder until T11 stores the frozen prompt template file; T11 must replace it in all four TOML files (and in `PROMPT_TEMPLATE_SHA256_PLACEHOLDER` in `config.py`'s default) — the change is fingerprint-visible by construction. - **T02 — `high_confidence_threshold`:** not pinned in §9.7; initialized to 0.60 in all presets. To be re-verified alongside the refusal threshold at T16 before the V1 baseline run freezes it. +- **T03 — FTS5 flavor (§8.3 wording ambiguity):** §8.3's "contentless external-content rowid-mapped to `chunk_id`" mixes two FTS5 flavors. Implemented as an **external-content** FTS5 table (`content='chunks_'`, `content_rowid='chunk_id'`) — it stores no text itself (contentless in effect) but can serve `snippet()` from the content table, and AFTER INSERT/DELETE triggers keep it in sync with orphan removal (FR-02/T07). Smallest choice consistent with §7.4's "rowid-mapped" requirement; recorded here rather than re-derived later. +- **T03 — `runs` lifecycle enforcement:** beyond §8.9's literal triggers, `ensure_schema` also installs `runs_insert_must_start_running` (INSERTs must use status `running`) so the §8.7 lifecycle ("running → terminal is the only permitted UPDATE") cannot be bypassed from row zero. `finish_run()` performs the single legal UPDATE (status + finished_at + summary_json in one statement while `OLD.status = 'running'`). +- **T03 — `ingest_runs` upsert semantics:** "idempotent upsert" (§8.3) implemented as one row per fingerprint (UNIQUE) with `ON CONFLICT DO UPDATE` that resets `finished_at`/`pages_*` until the new run finishes; matches §8.1's "latest per fingerprint". +- **T03 — chunk/embedding accessors added for T07/T08:** `insert_chunks` (returns ids, row-by-row since ids are reported), `get_chunks` (order-preserving, raises on missing id), `delete_chunks` (also deletes the vec rows; FTS follows via trigger), `insert_chunk_embeddings` (serializes via `sqlite_vec.serialize_float32`; validates 768 dims). No business logic added (§7.3). +- **T03 — `db` is a leaf (§7.3):** it imports nothing from `config`; callers pass fingerprints/`fp8` suffixes as strings. Suffix is validated as 8 lowercase hex chars before any SQL interpolation. +- **T03 — sqlite-vec binding detail:** embeddings must be bound as serialized float32 (the package's `serialize_float32`), not Python lists; `connect()` enables extension loading around `sqlite_vec.load()`. +- **T04 — `tests/conftest.py` added (outside the T04 file list):** puts `tests/` on `sys.path` so `tests/fakes.py` is importable from every test directory (§15's "fakes are the suite's only mocks"); smallest mechanism that avoids editing T01-owned `pyproject.toml`. Owned by T04 from here on. +- **T04 — `get_embeddings` rejects `embeddings.dimensions != 768` up front:** 768 is binding (§7.2, vec0 table in §8.3); failing before any model call is cheaper than corrupting the index. +- **T04 — smoke 429 demo is simulated:** a live 429 can't be forced deterministically, so `scripts/smoke.py` exercises the real `call_with_backoff` against a scripted twice-429 op with no-op sleeps; the live retry path is covered by injection-seam tests. Live leg still requires the human smoke run (§15). +- **T04 — `ChatResult.model` echoes the requested model** (not `response.model_version`) so the fingerprint stays consistent when the API appends a version suffix. +- **T04 — unknown price entries raise `ProviderError`:** A3 covers wrong figures, not absent ones — a missing entry must fail loudly. ⚠ `gemini-3.1-flash-lite` (OQ1 fallback) has **no price entry yet**; add its figure to `prices.json` when OQ1 resolves, or `estimate_cost` will raise if it is ever used. +- **T04 — frozen seams:** `tests/fakes.py` API (`FakeChat`, `FakeEmbeddings`, helpers) is the mock foundation for T09–T14; Ollama model pins `qwen2.5:7b-instruct` / `nomic-embed-text` are constants in `providers/ollama.py` (§7.2). +- **T04 — OQ1 still open:** free-tier RPD for `gemini-3.5-flash-lite` must be verified live (AI Studio) at the smoke run and logged in §18. +- **T04 — live smoke result (2026-11-16):** Gemini leg PASSED live — chat OK on `gemini-3.5-flash-lite` (26/18 tokens), embed OK 768-dim norm 1.000000, cost estimated from `prices.json`, 429 backoff demo logged. Ollama leg deferred: Ollama not installed; re-run `uv run python scripts/smoke.py` after `ollama pull qwen2.5:7b-instruct` + `nomic-embed-text`. User decision recorded 2026-11-16. +- **T04 — bug found by the live smoke:** google-genai's `Models` holds only a weak reference to its `Client`; dropping the Client fails every request ("client has been closed"). Fixed in `89e5423`: `GeminiSession` owns the `genai.Client`, factories and smoke pass it to the backends (`keepalive` slot). This would have broken the production ask path at T11/T12 — worth remembering when reading T04's diff. diff --git a/src/caliper/db.py b/src/caliper/db.py new file mode 100644 index 0000000..c0375e2 --- /dev/null +++ b/src/caliper/db.py @@ -0,0 +1,1067 @@ +"""SQLite storage: connection setup, schema management, typed accessors (§7.3, §8). + +Owns the single SQLite file. Responsibilities (§7.3): connection setup with +`sqlite-vec` loaded, schema creation/versioning (including the per-fingerprint +index tables, created on demand at ingest time, §8.9), typed accessors for +every table, and append-only enforcement helpers. + +This module is a leaf: it depends on nothing (§7.3) — callers hand in +fingerprints, hashes, and timestamps as plain strings — and it contains no +business logic: no ranking, no prompt building, no metrics. + +Transaction discipline: accessors execute statements but never commit; the +caller owns transaction boundaries (commit/rollback). + +Append-only tables (§8.9): `runs`, `run_results`, `spot_checks`, `feedback` +are protected by triggers in schema.sql. `finish_run()` performs the single +permitted UPDATE (running → complete | failed). `requests` and its children +are deliberately updatable (corrective edits, §8.9); the chunks trio is +deliberately upsert/delete-able (FR-02). +""" + +from __future__ import annotations + +import re +import sqlite3 +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import Literal + +# sqlite_vec ships no py.typed marker; its API is tiny and used only here. +import sqlite_vec # type: ignore[import-untyped] + +SCHEMA_VERSION = 1 +_SCHEMA_PATH = Path(__file__).with_name("schema.sql") + +# §8.3: the embedding table is `embedding float[768] distance_metric=cosine`. +EMBEDDING_DIMENSIONS = 768 + +_SUFFIX_RE = re.compile(r"[0-9a-f]{8}") + + +class DbError(Exception): + """A database operation failed (§16 typed component exception). + + Wraps sqlite3 errors and schema/lifecycle violations; mapped to the + §9 error envelope at the CLI/web edges. + """ + + +def _now_iso() -> str: + """ISO-8601 UTC timestamp (§8 column convention).""" + return datetime.now(UTC).isoformat() + + +def _execute(conn: sqlite3.Connection, sql: str, params: Sequence[object] = ()) -> sqlite3.Cursor: + """Execute one statement, wrapping sqlite3 errors as DbError (§16).""" + try: + return conn.execute(sql, params) + except sqlite3.Error as exc: + raise DbError(f"sqlite error: {exc}") from exc + + +def _executemany(conn: sqlite3.Connection, sql: str, rows: Sequence[Sequence[object]]) -> None: + """Execute one statement over many parameter tuples, wrapped as DbError (§16).""" + try: + conn.executemany(sql, rows) + except sqlite3.Error as exc: + raise DbError(f"sqlite error: {exc}") from exc + + +# --------------------------------------------------------------------------- +# Connection + schema +# --------------------------------------------------------------------------- + + +def connect(path: str | Path) -> sqlite3.Connection: + """Open the Caliper database with `sqlite-vec` loaded (§7.3). + + Sets WAL journal mode and turns foreign keys on. Raises DbError if the + sqlite-vec extension cannot be loaded (e.g. a Python build without + extension support). + """ + try: + conn = sqlite3.connect(path) + except sqlite3.Error as exc: + raise DbError(f"could not open database at {path}: {exc}") from exc + conn.row_factory = sqlite3.Row + try: + conn.enable_load_extension(True) + sqlite_vec.load(conn) + except Exception as exc: # noqa: BLE001 - any load failure is a DbError + conn.close() + raise DbError(f"could not load sqlite-vec extension: {exc}") from exc + finally: + # Whatever happened above, extension loading must end up disabled. + try: + conn.enable_load_extension(False) + except (AttributeError, sqlite3.Error): + pass + _execute(conn, "PRAGMA journal_mode=WAL") + _execute(conn, "PRAGMA foreign_keys=ON") + return conn + + +def ensure_schema(conn: sqlite3.Connection) -> None: + """Apply the global schema idempotently and check the version (§8.9). + + Safe to call on every connection. If the file already carries a schema + version other than the one this code ships, raise DbError — there are no + downgrades and no forward migrations in v1. + """ + try: + conn.executescript(_SCHEMA_PATH.read_text(encoding="utf-8")) + except sqlite3.Error as exc: + raise DbError(f"could not apply schema: {exc}") from exc + _execute( + conn, + "INSERT OR IGNORE INTO schema_meta (schema_version) VALUES (?)", + (SCHEMA_VERSION,), + ) + row = _execute(conn, "SELECT MAX(schema_version) FROM schema_meta").fetchone() + if row is None or int(row[0]) != SCHEMA_VERSION: + found = int(row[0]) if row is not None else None + raise DbError(f"unexpected schema_version {found!r} (this code ships v{SCHEMA_VERSION})") + + +# --------------------------------------------------------------------------- +# Per-fingerprint index tables (§8.3), created on demand at ingest time +# --------------------------------------------------------------------------- + + +def _check_suffix(suffix: str) -> None: + if _SUFFIX_RE.fullmatch(suffix) is None: + raise DbError(f"invalid table suffix {suffix!r}: expected 8 lowercase hex chars") + + +def ensure_chunks_tables(conn: sqlite3.Connection, suffix: str) -> None: + """Create the per-fingerprint trio + FTS sync triggers, idempotently (§8.3). + + `suffix` is `config.fp8(cfg)` — the first 8 hex chars of the fingerprint. + FTS flavor: §8.3's "contentless external-content" is implemented as an + external-content FTS5 table (content=chunks_, content_rowid=chunk_id), + which stores no text itself (contentless in that sense) but can serve + snippet() from the content table; AFTER INSERT/DELETE triggers keep the + index in sync with orphan removal (FR-02). + """ + _check_suffix(suffix) + try: + conn.executescript( + f""" + CREATE TABLE IF NOT EXISTS chunks_{suffix} ( + chunk_id INTEGER PRIMARY KEY, + page_url TEXT NOT NULL, + heading_path TEXT NOT NULL, + body TEXT NOT NULL, + body_tokens INTEGER NOT NULL, + chunk_hash TEXT NOT NULL UNIQUE, + ordinal INTEGER NOT NULL + ); + CREATE VIRTUAL TABLE IF NOT EXISTS chunks_{suffix}_fts USING fts5( + body, + content='chunks_{suffix}', + content_rowid='chunk_id' + ); + CREATE VIRTUAL TABLE IF NOT EXISTS chunks_{suffix}_vec USING vec0( + embedding float[{EMBEDDING_DIMENSIONS}] distance_metric=cosine + ); + CREATE TRIGGER IF NOT EXISTS chunks_{suffix}_fts_ai + AFTER INSERT ON chunks_{suffix} + BEGIN + INSERT INTO chunks_{suffix}_fts (rowid, body) VALUES (new.chunk_id, new.body); + END; + CREATE TRIGGER IF NOT EXISTS chunks_{suffix}_fts_ad + AFTER DELETE ON chunks_{suffix} + BEGIN + INSERT INTO chunks_{suffix}_fts (chunks_{suffix}_fts, rowid, body) + VALUES ('delete', old.chunk_id, old.body); + END; + """ + ) + except sqlite3.Error as exc: + raise DbError(f"could not create chunk tables for {suffix}: {exc}") from exc + + +# --------------------------------------------------------------------------- +# Row types +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True, slots=True) +class RequestRow: + """Insert payload for `requests` (§8.4). `ts=None` means "now".""" + + question: str + fingerprint: str + run_id: int | None + answer_type: str + answer_text: str + confidence: str + latency_ms: int + prompt_tokens: int + completion_tokens: int + embed_tokens: int + cost_usd: float + refusal_stage: str | None + payload_json: str + ts: str | None = None + + +@dataclass(frozen=True, slots=True) +class RequestRecord: + """A stored `requests` row (§8.4).""" + + request_id: int + ts: str + question: str + fingerprint: str + run_id: int | None + answer_type: str + answer_text: str + confidence: str + latency_ms: int + prompt_tokens: int + completion_tokens: int + embed_tokens: int + cost_usd: float + refusal_stage: str | None + payload_json: str + + +@dataclass(frozen=True, slots=True) +class RetrievalRow: + """Insert payload for one `request_retrievals` row (§8.5).""" + + ordinal: int + chunk_id: int + score: float + stage: str + + +@dataclass(frozen=True, slots=True) +class RetrievalRecord: + """A stored `request_retrievals` row (§8.5).""" + + request_id: int + ordinal: int + chunk_id: int + score: float + stage: str + + +@dataclass(frozen=True, slots=True) +class CitationRow: + """Insert payload for one `request_citations` row (§8.5).""" + + ordinal: int + chunk_id: int + page_url: str + heading_path: str + quote: str + verified: int + + +@dataclass(frozen=True, slots=True) +class CitationRecord: + """A stored `request_citations` row (§8.5).""" + + request_id: int + ordinal: int + chunk_id: int + page_url: str + heading_path: str + quote: str + verified: int + + +@dataclass(frozen=True, slots=True) +class TraceRecord: + """Everything logged for one request, reconstructable (NFR-01, A7).""" + + request: RequestRecord + retrievals: list[RetrievalRecord] + citations: list[CitationRecord] + + +@dataclass(frozen=True, slots=True) +class RunRow: + """Insert payload for `runs` (§8.7). Rows always start in status 'running'; + `summary_json` holds a '{}' placeholder until finish_run() writes the + §9.6 summary in the same statement as the status transition.""" + + version_label: str + fingerprint: str + golden_hash: str + seed: int + started_at: str | None = None + summary_json: str = "{}" + + +@dataclass(frozen=True, slots=True) +class RunRecord: + """A stored `runs` row (§8.7).""" + + run_id: int + version_label: str + fingerprint: str + golden_hash: str + seed: int + started_at: str | None + finished_at: str | None + status: str + summary_json: str + + +@dataclass(frozen=True, slots=True) +class RunResultRow: + """Insert payload for one `run_results` row (§8.7).""" + + question_id: str + answer_type: str + answer_text: str + confidence: str + hit: int + refusal_expected: int + latency_ms: int + cost_usd: float + retrieval_json: str + + +@dataclass(frozen=True, slots=True) +class RunResultRecord: + """A stored `run_results` row (§8.7).""" + + run_id: int + question_id: str + answer_type: str + answer_text: str + confidence: str + hit: int + refusal_expected: int + latency_ms: int + cost_usd: float + retrieval_json: str + + +@dataclass(frozen=True, slots=True) +class SpotCheckRow: + """Insert payload for `spot_checks` (§8.8).""" + + run_id: int + question_id: str + verdict: str + judged_at: str + judge: str + note: str | None = None + + +@dataclass(frozen=True, slots=True) +class SpotCheckRecord: + """A stored `spot_checks` row (§8.8).""" + + spot_check_id: int + run_id: int + question_id: str + verdict: str + note: str | None + judged_at: str + judge: str + + +@dataclass(frozen=True, slots=True) +class FeedbackRow: + """Insert payload for `feedback` (§8.8).""" + + request_id: int + helpful: int + created_at: str + note: str | None = None + + +@dataclass(frozen=True, slots=True) +class FeedbackRecord: + """A stored `feedback` row (§8.8).""" + + feedback_id: int + request_id: int + helpful: int + note: str | None + created_at: str + + +@dataclass(frozen=True, slots=True) +class IngestRunRow: + """Insert/update payload for `ingest_runs` (§8.3), upserted per fingerprint.""" + + fingerprint: str + source_ref: str + summary_json: str + started_at: str | None = None + + +@dataclass(frozen=True, slots=True) +class IngestRunRecord: + """A stored `ingest_runs` row (§8.3).""" + + ingest_run_id: int + fingerprint: str + source_ref: str + started_at: str | None + finished_at: str | None + pages_ok: int | None + pages_skipped: int | None + summary_json: str + + +@dataclass(frozen=True, slots=True) +class ChunkRow: + """Insert payload for one `chunks_` row (§8.3).""" + + page_url: str + heading_path: str + body: str + body_tokens: int + chunk_hash: str + ordinal: int + + +@dataclass(frozen=True, slots=True) +class ChunkRecord: + """A stored `chunks_` row (§8.3).""" + + chunk_id: int + page_url: str + heading_path: str + body: str + body_tokens: int + chunk_hash: str + ordinal: int + + +# --------------------------------------------------------------------------- +# Accessors: config_fingerprints (§8.2) +# --------------------------------------------------------------------------- + + +def record_fingerprint( + conn: sqlite3.Connection, *, fingerprint: str, config_json: str, created_at: str | None = None +) -> bool: + """Insert the fingerprint row on first sight; idempotent no-op after (§8.2). + + Returns True only when a new row was created. Rows are never updated or + deleted (§8.2 lifecycle). + """ + cursor = _execute( + conn, + """ + INSERT INTO config_fingerprints (fingerprint, config_json, created_at) + VALUES (?, ?, ?) + ON CONFLICT (fingerprint) DO NOTHING + """, + (fingerprint, config_json, created_at or _now_iso()), + ) + return cursor.rowcount == 1 + + +# --------------------------------------------------------------------------- +# Accessors: ingest_runs (§8.3) — NOT append-only (idempotent upsert, §8.3) +# --------------------------------------------------------------------------- + + +def upsert_ingest_run(conn: sqlite3.Connection, row: IngestRunRow) -> int: + """Insert or replace the ingest run for the row's fingerprint (§8.3). + + Replaces the prior row for the same fingerprint ("latest per fingerprint", + §8.1), keeping FR-02's double-ingest idempotent. Returns the id of the + upserted row — the existing row's id when it was replaced, since an + UPDATE keeps the rowid. + """ + cursor = _execute( + conn, + """ + INSERT INTO ingest_runs (fingerprint, source_ref, summary_json, started_at) + VALUES (?, ?, ?, ?) + ON CONFLICT (fingerprint) DO UPDATE SET + source_ref = excluded.source_ref, + summary_json = excluded.summary_json, + started_at = excluded.started_at, + finished_at = NULL, + pages_ok = NULL, + pages_skipped = NULL + """, + (row.fingerprint, row.source_ref, row.summary_json, row.started_at or _now_iso()), + ) + if cursor.lastrowid is None: + raise DbError("ingest_runs upsert did not yield a rowid") + return int(cursor.lastrowid) + + +def finish_ingest_run( + conn: sqlite3.Connection, + ingest_run_id: int, + *, + finished_at: str, + pages_ok: int, + pages_skipped: int, +) -> None: + """Fill in the summary fields when an ingest completes (§8.3).""" + _execute( + conn, + """ + UPDATE ingest_runs + SET finished_at = ?, pages_ok = ?, pages_skipped = ? + WHERE ingest_run_id = ? + """, + (finished_at, pages_ok, pages_skipped, ingest_run_id), + ) + + +def get_ingest_run(conn: sqlite3.Connection, fingerprint: str) -> IngestRunRecord | None: + """The latest ingest run for a fingerprint, or None (§8.1).""" + row = _execute( + conn, + """ + SELECT ingest_run_id, fingerprint, source_ref, started_at, finished_at, + pages_ok, pages_skipped, summary_json + FROM ingest_runs WHERE fingerprint = ? + """, + (fingerprint,), + ).fetchone() + if row is None: + return None + return IngestRunRecord( + ingest_run_id=int(row[0]), + fingerprint=str(row[1]), + source_ref=str(row[2]), + started_at=row[3], + finished_at=row[4], + pages_ok=row[5], + pages_skipped=row[6], + summary_json=str(row[7]), + ) + + +# --------------------------------------------------------------------------- +# Accessors: runs + run_results (§8.7) — append-only +# --------------------------------------------------------------------------- + + +def create_run(conn: sqlite3.Connection, row: RunRow) -> int: + """Create a run in status 'running' and return its id (§8.7). + + The only permitted follow-up UPDATE is finish_run()'s transition to a + terminal status; the schema triggers reject everything else (§8.9). + """ + cursor = _execute( + conn, + """ + INSERT INTO runs (version_label, fingerprint, golden_hash, seed, + started_at, status, summary_json) + VALUES (?, ?, ?, ?, ?, 'running', ?) + """, + ( + row.version_label, + row.fingerprint, + row.golden_hash, + row.seed, + row.started_at or _now_iso(), + row.summary_json, + ), + ) + if cursor.lastrowid is None: + raise DbError("runs insert did not yield a rowid") + return int(cursor.lastrowid) + + +def finish_run( + conn: sqlite3.Connection, + run_id: int, + *, + status: Literal["complete", "failed"], + finished_at: str, + summary_json: str, +) -> None: + """The single permitted UPDATE: running → complete | failed (§8.7, §8.9). + + Writes the terminal status, finished_at, and the §9.6 summary_json in one + statement. Raises DbError if the run does not exist or is already + terminal (the schema trigger would abort the UPDATE otherwise). + """ + cursor = _execute( + conn, + """ + UPDATE runs + SET status = ?, finished_at = ?, summary_json = ? + WHERE run_id = ? AND status = 'running' + """, + (status, finished_at, summary_json, run_id), + ) + if cursor.rowcount != 1: + raise DbError(f"run {run_id} is not in status 'running' (append-only once terminal, §8.9)") + + +def get_run(conn: sqlite3.Connection, run_id: int) -> RunRecord | None: + """One run by id, or None (§8.7).""" + row = _execute( + conn, + """ + SELECT run_id, version_label, fingerprint, golden_hash, seed, + started_at, finished_at, status, summary_json + FROM runs WHERE run_id = ? + """, + (run_id,), + ).fetchone() + return _run_record(row) if row is not None else None + + +def list_runs(conn: sqlite3.Connection) -> list[RunRecord]: + """All runs, oldest first (§7.3).""" + rows = _execute( + conn, + """ + SELECT run_id, version_label, fingerprint, golden_hash, seed, + started_at, finished_at, status, summary_json + FROM runs ORDER BY run_id + """, + ).fetchall() + return [_run_record(row) for row in rows] + + +def _run_record(row: sqlite3.Row) -> RunRecord: + return RunRecord( + run_id=int(row[0]), + version_label=str(row[1]), + fingerprint=str(row[2]), + golden_hash=str(row[3]), + seed=int(row[4]), + started_at=row[5], + finished_at=row[6], + status=str(row[7]), + summary_json=str(row[8]), + ) + + +def insert_run_results(conn: sqlite3.Connection, run_id: int, rows: Sequence[RunResultRow]) -> None: + """Append eval results for a run, batched (§8.7).""" + _executemany( + conn, + """ + INSERT INTO run_results (run_id, question_id, answer_type, answer_text, + confidence, hit, refusal_expected, latency_ms, + cost_usd, retrieval_json) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + [ + ( + run_id, + row.question_id, + row.answer_type, + row.answer_text, + row.confidence, + row.hit, + row.refusal_expected, + row.latency_ms, + row.cost_usd, + row.retrieval_json, + ) + for row in rows + ], + ) + + +def list_run_results(conn: sqlite3.Connection, run_id: int) -> list[RunResultRecord]: + """All results for one run, ordered by question_id (§8.7).""" + rows = _execute( + conn, + """ + SELECT run_id, question_id, answer_type, answer_text, confidence, + hit, refusal_expected, latency_ms, cost_usd, retrieval_json + FROM run_results WHERE run_id = ? ORDER BY question_id + """, + (run_id,), + ).fetchall() + return [ + RunResultRecord( + run_id=int(row[0]), + question_id=str(row[1]), + answer_type=str(row[2]), + answer_text=str(row[3]), + confidence=str(row[4]), + hit=int(row[5]), + refusal_expected=int(row[6]), + latency_ms=int(row[7]), + cost_usd=float(row[8]), + retrieval_json=str(row[9]), + ) + for row in rows + ] + + +# --------------------------------------------------------------------------- +# Accessors: spot_checks (§8.8) — append-only +# --------------------------------------------------------------------------- + + +def insert_spot_check(conn: sqlite3.Connection, row: SpotCheckRow) -> int: + """Append a spot-check judgment; never updated or deleted (§8.8). + + An erroneous judgment is corrected by a new row with a later judged_at; + metrics use the latest row per (run_id, question_id). Returns its id. + """ + cursor = _execute( + conn, + """ + INSERT INTO spot_checks (run_id, question_id, verdict, note, judged_at, judge) + VALUES (?, ?, ?, ?, ?, ?) + """, + (row.run_id, row.question_id, row.verdict, row.note, row.judged_at, row.judge), + ) + if cursor.lastrowid is None: + raise DbError("spot_checks insert did not yield a rowid") + return int(cursor.lastrowid) + + +def list_spot_checks(conn: sqlite3.Connection, run_id: int) -> list[SpotCheckRecord]: + """All judgments for one run, oldest first (§8.8; callers pick the latest).""" + rows = _execute( + conn, + """ + SELECT spot_check_id, run_id, question_id, verdict, note, judged_at, judge + FROM spot_checks WHERE run_id = ? ORDER BY spot_check_id + """, + (run_id,), + ).fetchall() + return [ + SpotCheckRecord( + spot_check_id=int(row[0]), + run_id=int(row[1]), + question_id=str(row[2]), + verdict=str(row[3]), + note=row[4], + judged_at=str(row[5]), + judge=str(row[6]), + ) + for row in rows + ] + + +# --------------------------------------------------------------------------- +# Accessors: requests + children (§8.4, §8.5) — deliberately not append-only +# --------------------------------------------------------------------------- + + +def insert_request(conn: sqlite3.Connection, row: RequestRow) -> int: + """Log one question (interactive or eval-driven) and return its id (§8.4).""" + cursor = _execute( + conn, + """ + INSERT INTO requests (ts, question, fingerprint, run_id, answer_type, + answer_text, confidence, latency_ms, prompt_tokens, + completion_tokens, embed_tokens, cost_usd, + refusal_stage, payload_json) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + row.ts or _now_iso(), + row.question, + row.fingerprint, + row.run_id, + row.answer_type, + row.answer_text, + row.confidence, + row.latency_ms, + row.prompt_tokens, + row.completion_tokens, + row.embed_tokens, + row.cost_usd, + row.refusal_stage, + row.payload_json, + ), + ) + if cursor.lastrowid is None: + raise DbError("requests insert did not yield a rowid") + return int(cursor.lastrowid) + + +def insert_retrievals( + conn: sqlite3.Connection, request_id: int, rows: Sequence[RetrievalRow] +) -> None: + """Append the final retrieval set for one request (§8.5).""" + _executemany( + conn, + """ + INSERT INTO request_retrievals (request_id, ordinal, chunk_id, score, stage) + VALUES (?, ?, ?, ?, ?) + """, + [(request_id, row.ordinal, row.chunk_id, row.score, row.stage) for row in rows], + ) + + +def insert_citations( + conn: sqlite3.Connection, request_id: int, rows: Sequence[CitationRow] +) -> None: + """Append the citations for one request; refusals write none (§8.5).""" + _executemany( + conn, + """ + INSERT INTO request_citations (request_id, ordinal, chunk_id, page_url, + heading_path, quote, verified) + VALUES (?, ?, ?, ?, ?, ?, ?) + """, + [ + ( + request_id, + row.ordinal, + row.chunk_id, + row.page_url, + row.heading_path, + row.quote, + row.verified, + ) + for row in rows + ], + ) + + +def get_request_trace(conn: sqlite3.Connection, request_id: int) -> TraceRecord | None: + """Reconstruct one request's full trace, or None (§7.3, A7).""" + request_row = _execute( + conn, + """ + SELECT request_id, ts, question, fingerprint, run_id, answer_type, + answer_text, confidence, latency_ms, prompt_tokens, + completion_tokens, embed_tokens, cost_usd, refusal_stage, payload_json + FROM requests WHERE request_id = ? + """, + (request_id,), + ).fetchone() + if request_row is None: + return None + request = RequestRecord( + request_id=int(request_row[0]), + ts=str(request_row[1]), + question=str(request_row[2]), + fingerprint=str(request_row[3]), + run_id=request_row[4], + answer_type=str(request_row[5]), + answer_text=str(request_row[6]), + confidence=str(request_row[7]), + latency_ms=int(request_row[8]), + prompt_tokens=int(request_row[9]), + completion_tokens=int(request_row[10]), + embed_tokens=int(request_row[11]), + cost_usd=float(request_row[12]), + refusal_stage=request_row[13], + payload_json=str(request_row[14]), + ) + retrievals = [ + RetrievalRecord( + request_id=int(row[0]), + ordinal=int(row[1]), + chunk_id=int(row[2]), + score=float(row[3]), + stage=str(row[4]), + ) + for row in _execute( + conn, + """ + SELECT request_id, ordinal, chunk_id, score, stage + FROM request_retrievals WHERE request_id = ? ORDER BY ordinal + """, + (request_id,), + ).fetchall() + ] + citations = [ + CitationRecord( + request_id=int(row[0]), + ordinal=int(row[1]), + chunk_id=int(row[2]), + page_url=str(row[3]), + heading_path=str(row[4]), + quote=str(row[5]), + verified=int(row[6]), + ) + for row in _execute( + conn, + """ + SELECT request_id, ordinal, chunk_id, page_url, heading_path, quote, verified + FROM request_citations WHERE request_id = ? ORDER BY ordinal + """, + (request_id,), + ).fetchall() + ] + return TraceRecord(request=request, retrievals=retrievals, citations=citations) + + +# --------------------------------------------------------------------------- +# Accessors: feedback (§8.8) — append-only, idempotent insert (§9.2) +# --------------------------------------------------------------------------- + + +def insert_feedback(conn: sqlite3.Connection, row: FeedbackRow) -> tuple[int, bool]: + """Store feedback; repeats for the same request return the existing row. + + Returns (feedback_id, created). Idempotency is per §9.2: max one row per + request (UNIQUE in §8.8), so repeat POSTs are no-ops, not errors. + """ + cursor = _execute( + conn, + """ + INSERT INTO feedback (request_id, helpful, note, created_at) + VALUES (?, ?, ?, ?) + ON CONFLICT (request_id) DO NOTHING + """, + (row.request_id, row.helpful, row.note, row.created_at), + ) + if cursor.rowcount == 1: + if cursor.lastrowid is None: + raise DbError("feedback insert did not yield a rowid") + return int(cursor.lastrowid), True + existing = _execute( + conn, "SELECT feedback_id FROM feedback WHERE request_id = ?", (row.request_id,) + ).fetchone() + if existing is None: + raise DbError( + f"feedback insert for request {row.request_id} reported no row and no conflict" + ) + return int(existing[0]), False + + +def get_feedback(conn: sqlite3.Connection, request_id: int) -> FeedbackRecord | None: + """The feedback row for one request, or None (§8.8).""" + row = _execute( + conn, + """ + SELECT feedback_id, request_id, helpful, note, created_at + FROM feedback WHERE request_id = ? + """, + (request_id,), + ).fetchone() + if row is None: + return None + return FeedbackRecord( + feedback_id=int(row[0]), + request_id=int(row[1]), + helpful=int(row[2]), + note=row[3], + created_at=str(row[4]), + ) + + +# --------------------------------------------------------------------------- +# Accessors: chunks_ (§8.3) — NOT append-only (FR-02 repeatability) +# --------------------------------------------------------------------------- + + +def insert_chunks(conn: sqlite3.Connection, suffix: str, rows: Sequence[ChunkRow]) -> list[int]: + """Insert chunk rows in order and return their ids (§8.3). + + `chunk_hash` is UNIQUE in §8.3, so re-ingesting identical content into a + fresh (empty) table reproduces identical ids; a genuine duplicate within + one batch raises DbError via the UNIQUE constraint. Rows are inserted + one by one because the ids must be reported back to the caller. + """ + _check_suffix(suffix) + ids: list[int] = [] + for row in rows: + cursor = _execute( + conn, + f"INSERT INTO chunks_{suffix} (page_url, heading_path, body, body_tokens," + " chunk_hash, ordinal) VALUES (?, ?, ?, ?, ?, ?)", + ( + row.page_url, + row.heading_path, + row.body, + row.body_tokens, + row.chunk_hash, + row.ordinal, + ), + ) + if cursor.lastrowid is None: + raise DbError("chunks insert did not yield a rowid") + ids.append(int(cursor.lastrowid)) + return ids + + +def get_chunks( + conn: sqlite3.Connection, suffix: str, chunk_ids: Sequence[int] +) -> list[ChunkRecord]: + """Fetch chunk rows by id, preserving the caller's order (§8.3). + + Raises DbError if any id is missing — callers never reference chunks + that are not in the index. + """ + _check_suffix(suffix) + if not chunk_ids: + return [] + placeholders = ", ".join("?" for _ in chunk_ids) + rows = _execute( + conn, + f""" + SELECT chunk_id, page_url, heading_path, body, body_tokens, chunk_hash, ordinal + FROM chunks_{suffix} WHERE chunk_id IN ({placeholders}) + """, + list(chunk_ids), + ).fetchall() + by_id = { + int(row[0]): ChunkRecord( + chunk_id=int(row[0]), + page_url=str(row[1]), + heading_path=str(row[2]), + body=str(row[3]), + body_tokens=int(row[4]), + chunk_hash=str(row[5]), + ordinal=int(row[6]), + ) + for row in rows + } + missing = [chunk_id for chunk_id in chunk_ids if chunk_id not in by_id] + if missing: + raise DbError(f"chunks_{suffix} is missing chunk ids {missing}") + return [by_id[chunk_id] for chunk_id in chunk_ids] + + +def delete_chunks(conn: sqlite3.Connection, suffix: str, chunk_ids: Sequence[int]) -> None: + """Delete chunk rows; the FTS sync trigger keeps the index aligned (§8.3). + + Used by ingest's orphan removal (FR-02/T07). Embedding rows for the same + ids are removed first: the vec0 table is keyed by rowid = chunk_id. + """ + _check_suffix(suffix) + if not chunk_ids: + return + placeholders = ", ".join("?" for _ in chunk_ids) + _execute( + conn, + f"DELETE FROM chunks_{suffix}_vec WHERE rowid IN ({placeholders})", + list(chunk_ids), + ) + _execute( + conn, + f"DELETE FROM chunks_{suffix} WHERE chunk_id IN ({placeholders})", + list(chunk_ids), + ) + + +def insert_chunk_embeddings( + conn: sqlite3.Connection, suffix: str, embeddings: Sequence[tuple[int, list[float]]] +) -> None: + """Store L2-normalized embeddings keyed by rowid = chunk_id (§8.3). + + `embeddings` pairs each chunk_id with its float[768] vector (already + normalized client-side by providers, §7.2 — db stores, never transforms). + """ + _check_suffix(suffix) + for chunk_id, vector in embeddings: + if len(vector) != EMBEDDING_DIMENSIONS: + raise DbError( + f"embedding for chunk {chunk_id} has dimension {len(vector)}, " + f"expected {EMBEDDING_DIMENSIONS}" + ) + _executemany( + conn, + f"INSERT INTO chunks_{suffix}_vec (rowid, embedding) VALUES (?, ?)", + [(chunk_id, sqlite_vec.serialize_float32(vector)) for chunk_id, vector in embeddings], + ) diff --git a/src/caliper/schema.sql b/src/caliper/schema.sql new file mode 100644 index 0000000..07bf7f8 --- /dev/null +++ b/src/caliper/schema.sql @@ -0,0 +1,203 @@ +-- Caliper database schema (T03; owner: src/caliper/db.py, §6.3). +-- +-- Global tables per docs/ARCHITECTURE.md §8. The per-fingerprint index tables +-- (chunks_, chunks__fts, chunks__vec, §8.3) are NOT defined +-- here: they are created on demand at ingest time by +-- db.ensure_chunks_tables() (§8.9), because their names depend on the +-- config fingerprint. +-- +-- Append-only enforcement (§8.9): runs / run_results / spot_checks / feedback +-- are protected by BEFORE UPDATE / BEFORE DELETE triggers below. `requests` +-- and its children are deliberately NOT protected (corrective edits to a +-- mis-logged interactive request are permitted; §8.9). The chunks_* trio is +-- deliberately NOT protected (FR-02 repeatability requires upsert/delete). +-- +-- DDL is idempotent (IF NOT EXISTS everywhere) so ensure_schema() can be +-- applied repeatedly. + +CREATE TABLE IF NOT EXISTS schema_meta ( + -- Single-row table versioning the schema (§8.9). Managed by db.py. + schema_version INTEGER NOT NULL +); + +-- §8.2 — created when an ingest or eval first sees a new fingerprint; +-- never updated or deleted. +CREATE TABLE IF NOT EXISTS config_fingerprints ( + fingerprint TEXT PRIMARY KEY, + config_json TEXT NOT NULL, + created_at TEXT NOT NULL +); + +-- §8.3 — NOT append-only: repeatability (FR-02) requires upsert/delete. +-- One row per fingerprint ("latest per fingerprint", §8.1). +CREATE TABLE IF NOT EXISTS ingest_runs ( + ingest_run_id INTEGER PRIMARY KEY, + fingerprint TEXT NOT NULL UNIQUE, + source_ref TEXT NOT NULL, + started_at TEXT, + finished_at TEXT, + pages_ok INTEGER, + pages_skipped INTEGER, + summary_json TEXT NOT NULL +); + +-- §8.7 — status lifecycle: running → complete | failed. The only permitted +-- UPDATE is that transition (enforced by the trigger below); rows are +-- created in status 'running' only, and never deleted. +CREATE TABLE IF NOT EXISTS runs ( + run_id INTEGER PRIMARY KEY, + version_label TEXT NOT NULL CHECK (version_label IN ('v1', 'v2', 'v3')), + fingerprint TEXT NOT NULL, + golden_hash TEXT NOT NULL, + seed INTEGER NOT NULL, + started_at TEXT, + finished_at TEXT, + status TEXT NOT NULL CHECK (status IN ('running', 'complete', 'failed')), + summary_json TEXT NOT NULL +); + +-- §8.7 — append-only. +CREATE TABLE IF NOT EXISTS run_results ( + run_id INTEGER NOT NULL REFERENCES runs(run_id), + question_id TEXT NOT NULL, + answer_type TEXT NOT NULL CHECK (answer_type IN ('answer', 'refusal')), + answer_text TEXT NOT NULL, + confidence TEXT NOT NULL CHECK (confidence IN ('high', 'medium', 'low')), + hit INTEGER NOT NULL CHECK (hit IN (0, 1)), + refusal_expected INTEGER NOT NULL CHECK (refusal_expected IN (0, 1)), + latency_ms INTEGER NOT NULL, + cost_usd REAL NOT NULL, + retrieval_json TEXT NOT NULL +); + +-- §8.8 — append-only; an erroneous judgment is corrected by a later row, +-- and metrics use the latest row per (run_id, question_id). +CREATE TABLE IF NOT EXISTS spot_checks ( + spot_check_id INTEGER PRIMARY KEY, + run_id INTEGER NOT NULL REFERENCES runs(run_id), + question_id TEXT NOT NULL, + verdict TEXT NOT NULL CHECK (verdict IN ('correct', 'incorrect')), + note TEXT, + judged_at TEXT NOT NULL, + judge TEXT NOT NULL +); + +-- §8.4 — every question, interactive or eval-driven. Deliberately NOT +-- append-only (corrective edits permitted, §8.9). payload_json holds the +-- exact prompts; it never contains secrets (§8.9 retention/privacy). +CREATE TABLE IF NOT EXISTS requests ( + request_id INTEGER PRIMARY KEY, + ts TEXT NOT NULL, + question TEXT NOT NULL, + fingerprint TEXT NOT NULL, + run_id INTEGER REFERENCES runs(run_id), + answer_type TEXT NOT NULL CHECK (answer_type IN ('answer', 'refusal')), + answer_text TEXT NOT NULL, + confidence TEXT NOT NULL CHECK (confidence IN ('high', 'medium', 'low')), + latency_ms INTEGER NOT NULL, + prompt_tokens INTEGER NOT NULL, + completion_tokens INTEGER NOT NULL, + embed_tokens INTEGER NOT NULL, + cost_usd REAL NOT NULL, + refusal_stage TEXT CHECK (refusal_stage IN ('threshold', 'model')), + payload_json TEXT NOT NULL +); + +-- §8.5 — final-set observability (FR-06/FR-09). ordinal is 1..final_k. +-- chunk_id has no FOREIGN KEY: the chunks table it points into is created +-- on demand per fingerprint (§8.3), so integrity is enforced by callers. +CREATE TABLE IF NOT EXISTS request_retrievals ( + request_id INTEGER NOT NULL REFERENCES requests(request_id), + ordinal INTEGER NOT NULL CHECK (ordinal >= 1), + chunk_id INTEGER NOT NULL, + score REAL NOT NULL, + stage TEXT NOT NULL CHECK (stage IN ('vector', 'fts', 'rrf', 'rerank')) +); + +-- §8.5 — refusal rows write no citations. +CREATE TABLE IF NOT EXISTS request_citations ( + request_id INTEGER NOT NULL REFERENCES requests(request_id), + ordinal INTEGER NOT NULL CHECK (ordinal >= 1), + chunk_id INTEGER NOT NULL, + page_url TEXT NOT NULL, + heading_path TEXT NOT NULL, + quote TEXT NOT NULL, + verified INTEGER NOT NULL CHECK (verified IN (0, 1)) +); + +-- §8.8 — max one row per request; repeat writes return the existing row +-- (§9.2 idempotency, enforced in db.insert_feedback). +CREATE TABLE IF NOT EXISTS feedback ( + feedback_id INTEGER PRIMARY KEY, + request_id INTEGER NOT NULL UNIQUE REFERENCES requests(request_id), + helpful INTEGER NOT NULL CHECK (helpful IN (0, 1)), + note TEXT, + created_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_requests_fingerprint ON requests(fingerprint); +CREATE INDEX IF NOT EXISTS idx_requests_run ON requests(run_id); +CREATE INDEX IF NOT EXISTS idx_request_retrievals_request ON request_retrievals(request_id, ordinal); +CREATE INDEX IF NOT EXISTS idx_request_citations_request ON request_citations(request_id, ordinal); +CREATE INDEX IF NOT EXISTS idx_run_results_run ON run_results(run_id); +CREATE INDEX IF NOT EXISTS idx_spot_checks_run_question ON spot_checks(run_id, question_id); + +-- §8.9 — append-only enforcement. A runs row may only be updated while its +-- stored status is non-terminal, i.e. the single permitted UPDATE is the +-- running → complete | failed transition (which also sets finished_at / +-- summary_json in the same statement). Everything else is rejected. +CREATE TRIGGER IF NOT EXISTS runs_immutable_after_terminal +BEFORE UPDATE ON runs +WHEN OLD.status IN ('complete', 'failed') +BEGIN + SELECT RAISE(ABORT, 'run is append-only once terminal'); +END; + +CREATE TRIGGER IF NOT EXISTS runs_insert_must_start_running +BEFORE INSERT ON runs +WHEN NEW.status != 'running' +BEGIN + SELECT RAISE(ABORT, 'runs rows are created in status running'); +END; + +CREATE TRIGGER IF NOT EXISTS runs_append_only_delete +BEFORE DELETE ON runs +BEGIN + SELECT RAISE(ABORT, 'runs is append-only'); +END; + +CREATE TRIGGER IF NOT EXISTS run_results_append_only_update +BEFORE UPDATE ON run_results +BEGIN + SELECT RAISE(ABORT, 'run_results is append-only'); +END; + +CREATE TRIGGER IF NOT EXISTS run_results_append_only_delete +BEFORE DELETE ON run_results +BEGIN + SELECT RAISE(ABORT, 'run_results is append-only'); +END; + +CREATE TRIGGER IF NOT EXISTS spot_checks_append_only_update +BEFORE UPDATE ON spot_checks +BEGIN + SELECT RAISE(ABORT, 'spot_checks is append-only'); +END; + +CREATE TRIGGER IF NOT EXISTS spot_checks_append_only_delete +BEFORE DELETE ON spot_checks +BEGIN + SELECT RAISE(ABORT, 'spot_checks is append-only'); +END; + +CREATE TRIGGER IF NOT EXISTS feedback_append_only_update +BEFORE UPDATE ON feedback +BEGIN + SELECT RAISE(ABORT, 'feedback is append-only'); +END; + +CREATE TRIGGER IF NOT EXISTS feedback_append_only_delete +BEFORE DELETE ON feedback +BEGIN + SELECT RAISE(ABORT, 'feedback is append-only'); +END; diff --git a/tests/integration/test_append_only.py b/tests/integration/test_append_only.py new file mode 100644 index 0000000..0e0a500 --- /dev/null +++ b/tests/integration/test_append_only.py @@ -0,0 +1,162 @@ +"""T03 integration test: append-only trigger enforcement (§8.9, §15). + +The four protected tables — runs, run_results, spot_checks, feedback — must +reject UPDATE and DELETE at the schema level. The one legal UPDATE is the +runs status transition running → complete | failed (§8.7). `requests` and +its children are deliberately NOT protected (corrective edits permitted, +§8.9); the chunks trio is not protected either (FR-02). +""" + +import sqlite3 + +import pytest + +from caliper.db import ( + CitationRow, + FeedbackRow, + RequestRow, + RetrievalRow, + RunResultRow, + RunRow, + SpotCheckRow, + connect, + create_run, + ensure_schema, + finish_run, + insert_citations, + insert_feedback, + insert_request, + insert_retrievals, + insert_run_results, + insert_spot_check, +) + +TS = "2026-11-16T00:00:00+00:00" + + +@pytest.fixture() +def db(): + conn = connect(":memory:") + ensure_schema(conn) + yield conn + conn.close() + + +@pytest.fixture() +def seeded(db): + """A run in 'running' status plus one row in each protected table.""" + run_id = create_run( + db, RunRow(version_label="v1", fingerprint="a" * 64, golden_hash="b" * 64, seed=7) + ) + insert_run_results( + db, + run_id, + [ + RunResultRow( + question_id="q001", + answer_type="answer", + answer_text="ok", + confidence="high", + hit=1, + refusal_expected=0, + latency_ms=100, + cost_usd=0.0, + retrieval_json="[]", + ) + ], + ) + insert_spot_check( + db, + SpotCheckRow( + run_id=run_id, question_id="q001", verdict="correct", judged_at=TS, judge="owner" + ), + ) + request_id = insert_request( + db, + RequestRow( + question="q?", + fingerprint="a" * 64, + run_id=run_id, + answer_type="answer", + answer_text="ok", + confidence="high", + latency_ms=100, + prompt_tokens=10, + completion_tokens=5, + embed_tokens=3, + cost_usd=0.0, + refusal_stage=None, + payload_json="{}", + ), + ) + insert_retrievals( + db, request_id, [RetrievalRow(ordinal=1, chunk_id=1, score=0.5, stage="vector")] + ) + insert_citations( + db, + request_id, + [CitationRow(ordinal=1, chunk_id=1, page_url="u", heading_path="h", quote="t", verified=1)], + ) + insert_feedback(db, FeedbackRow(request_id=request_id, helpful=1, created_at=TS)) + return run_id + + +def _assert_update_blocked(conn, table: str, column: str) -> None: + with pytest.raises(sqlite3.IntegrityError, match="append-only"): + conn.execute(f"UPDATE {table} SET {column} = 'tampered'") + + +def _assert_delete_blocked(conn, table: str, where: str, params: tuple = ()) -> None: + with pytest.raises(sqlite3.IntegrityError, match="append-only"): + conn.execute(f"DELETE FROM {table} WHERE {where}", params) + + +def test_run_results_reject_update_and_delete(db, seeded): + _assert_update_blocked(db, "run_results", "answer_text") + _assert_delete_blocked(db, "run_results", "run_id = ?", (seeded,)) + + +def test_spot_checks_reject_update_and_delete(db, seeded): + _assert_update_blocked(db, "spot_checks", "verdict") + _assert_delete_blocked(db, "spot_checks", "run_id = ?", (seeded,)) + + +def test_feedback_reject_update_and_delete(db, seeded): + _assert_update_blocked(db, "feedback", "helpful") + _assert_delete_blocked(db, "feedback", "request_id IS NOT NULL") + + +def test_runs_reject_delete_and_terminal_update(db, seeded): + _assert_delete_blocked(db, "runs", "run_id = ?", (seeded,)) + finish_run(db, seeded, status="complete", finished_at=TS, summary_json="{}") + with pytest.raises(sqlite3.IntegrityError, match="append-only once terminal"): + db.execute("UPDATE runs SET summary_json = '{}' WHERE run_id = ?", (seeded,)) + + +def test_runs_only_permitted_update_is_running_to_terminal(db, seeded): + # The legal transition: status + finished_at + summary_json in one statement. + db.execute( + "UPDATE runs SET status = 'failed', finished_at = ?, summary_json = ? WHERE run_id = ?", + (TS, "{}", seeded), + ) + status = db.execute("SELECT status FROM runs WHERE run_id = ?", (seeded,)).fetchone()[0] + assert status == "failed" + + +def test_runs_insert_must_start_running(db): + with pytest.raises(sqlite3.IntegrityError, match="status running"): + db.execute( + "INSERT INTO runs (version_label, fingerprint, golden_hash, seed," + " started_at, status, summary_json)" + " VALUES ('v1', ?, ?, 7, ?, 'complete', '{}')", + ("a" * 64, "b" * 64, TS), + ) + + +def test_requests_and_children_stay_editable(db, seeded): + # §8.9: corrective edits to a mis-logged interactive request are permitted. + db.execute("UPDATE requests SET answer_text = 'corrected'") + db.execute("DELETE FROM request_citations") + db.execute("DELETE FROM request_retrievals") + count = db.execute("SELECT COUNT(*) FROM requests").fetchone()[0] + assert count == 1 diff --git a/tests/unit/test_db.py b/tests/unit/test_db.py new file mode 100644 index 0000000..34a62e4 --- /dev/null +++ b/tests/unit/test_db.py @@ -0,0 +1,406 @@ +"""T03 unit tests: connection setup, schema management, and accessors (§7.3, §8).""" + +import json + +import pytest +import sqlite_vec + +from caliper.db import ( + EMBEDDING_DIMENSIONS, + SCHEMA_VERSION, + ChunkRow, + CitationRow, + DbError, + FeedbackRow, + IngestRunRow, + RequestRow, + RetrievalRow, + RunResultRow, + RunRow, + SpotCheckRow, + connect, + create_run, + delete_chunks, + ensure_chunks_tables, + ensure_schema, + finish_ingest_run, + finish_run, + get_chunks, + get_feedback, + get_ingest_run, + get_request_trace, + get_run, + insert_chunk_embeddings, + insert_chunks, + insert_citations, + insert_feedback, + insert_request, + insert_retrievals, + insert_run_results, + insert_spot_check, + list_run_results, + list_runs, + list_spot_checks, + record_fingerprint, + upsert_ingest_run, +) + +NO_TS = "2026-11-16T00:00:00+00:00" + + +@pytest.fixture() +def db(): + """A connected, schema-initialized in-memory database.""" + conn = connect(":memory:") + ensure_schema(conn) + yield conn + conn.close() + + +# --------------------------------------------------------------------------- +# connect + ensure_schema (§7.3, §8.9) +# --------------------------------------------------------------------------- + + +def test_connect_loads_sqlite_vec(): + conn = connect(":memory:") + try: + version = conn.execute("SELECT vec_version()").fetchone() + assert version is not None + finally: + conn.close() + + +def test_connect_sets_wal_and_foreign_keys(tmp_path): + conn = connect(tmp_path / "caliper.db") + try: + assert conn.execute("PRAGMA journal_mode").fetchone()[0] == "wal" + assert conn.execute("PRAGMA foreign_keys").fetchone()[0] == 1 + finally: + conn.close() + + +def test_ensure_schema_is_idempotent(db): + ensure_schema(db) + row = db.execute("SELECT schema_version FROM schema_meta").fetchone() + assert int(row[0]) == SCHEMA_VERSION + + +def test_ensure_schema_rejects_newer_version(tmp_path): + conn = connect(tmp_path / "caliper.db") + try: + conn.execute("CREATE TABLE schema_meta (schema_version INTEGER NOT NULL)") + conn.execute("INSERT INTO schema_meta (schema_version) VALUES (999)") + with pytest.raises(DbError, match="schema_version"): + ensure_schema(conn) + finally: + conn.close() + + +# --------------------------------------------------------------------------- +# config_fingerprints (§8.2) +# --------------------------------------------------------------------------- + + +def test_record_fingerprint_is_idempotent(db): + assert record_fingerprint(db, fingerprint="a" * 64, config_json="{}") is True + assert record_fingerprint(db, fingerprint="a" * 64, config_json="{}") is False + count = db.execute("SELECT COUNT(*) FROM config_fingerprints").fetchone()[0] + assert count == 1 + + +# --------------------------------------------------------------------------- +# ingest_runs (§8.3) +# --------------------------------------------------------------------------- + + +def test_upsert_ingest_run_replaces_per_fingerprint(db): + upsert_ingest_run(db, _ingest_row()) + finish_ingest_run(db, 1, finished_at=NO_TS, pages_ok=10, pages_skipped=2) + upsert_ingest_run(db, _ingest_row(summary_json='{"pages": 3}')) + record = get_ingest_run(db, "f" * 64) + assert record is not None + assert record.ingest_run_id == 1 # one row per fingerprint; upsert keeps the rowid + assert record.summary_json == '{"pages": 3}' + assert record.finished_at is None # reset until the new run finishes + + +def _ingest_row(summary_json: str = "{}"): + return IngestRunRow( + fingerprint="f" * 64, + source_ref="MicrosoftDocs/azure-docs@abc1234", + summary_json=summary_json, + ) + + +# --------------------------------------------------------------------------- +# runs + run_results (§8.7) +# --------------------------------------------------------------------------- + + +def test_create_run_and_finish_run_roundtrip(db): + run_id = create_run( + db, RunRow(version_label="v1", fingerprint="a" * 64, golden_hash="b" * 64, seed=7) + ) + assert get_run(db, run_id).status == "running" + finish_run(db, run_id, status="complete", finished_at=NO_TS, summary_json='{"ok": true}') + run = get_run(db, run_id) + assert run.status == "complete" + assert run.finished_at == NO_TS + assert json.loads(run.summary_json) == {"ok": True} + + +def test_finish_run_rejects_unknown_run(db): + with pytest.raises(DbError, match="not in status 'running'"): + finish_run(db, 404, status="failed", finished_at=NO_TS, summary_json="{}") + + +def test_list_runs_orders_oldest_first(db): + first = create_run( + db, RunRow(version_label="v1", fingerprint="a" * 64, golden_hash="b" * 64, seed=7) + ) + second = create_run( + db, RunRow(version_label="v2", fingerprint="a" * 64, golden_hash="b" * 64, seed=7) + ) + assert [r.run_id for r in list_runs(db)] == [first, second] + + +def test_insert_run_results_roundtrip(db): + run_id = create_run( + db, RunRow(version_label="v1", fingerprint="a" * 64, golden_hash="b" * 64, seed=7) + ) + insert_run_results( + db, + run_id, + [ + RunResultRow( + question_id="q001", + answer_type="answer", + answer_text="Use the retryPolicy setting.", + confidence="high", + hit=1, + refusal_expected=0, + latency_ms=1200, + cost_usd=0.0, + retrieval_json="[]", + ) + ], + ) + results = list_run_results(db, run_id) + assert len(results) == 1 + assert results[0].question_id == "q001" + assert results[0].hit == 1 + + +# --------------------------------------------------------------------------- +# spot_checks (§8.8) +# --------------------------------------------------------------------------- + + +def test_spot_check_judgments_append_with_latest_wins(db): + run_id = create_run( + db, RunRow(version_label="v1", fingerprint="a" * 64, golden_hash="b" * 64, seed=7) + ) + first = insert_spot_check( + db, + SpotCheckRow( + run_id=run_id, question_id="q001", verdict="correct", judged_at=NO_TS, judge="owner" + ), + ) + second = insert_spot_check( + db, + SpotCheckRow( + run_id=run_id, + question_id="q001", + verdict="incorrect", + judged_at="2026-11-16T01:00:00+00:00", + judge="owner", + note="quote was paraphrased", + ), + ) + records = list_spot_checks(db, run_id) + assert [r.spot_check_id for r in records] == [first, second] + # Metrics pick the latest row per (run_id, question_id); both rows persist. + assert records[-1].verdict == "incorrect" + + +# --------------------------------------------------------------------------- +# requests + children (§8.4, §8.5) +# --------------------------------------------------------------------------- + + +def test_request_trace_roundtrip(db): + request_id = insert_request(db, _request_row()) + insert_retrievals( + db, + request_id, + [ + RetrievalRow(ordinal=1, chunk_id=11, score=0.91, stage="vector"), + RetrievalRow(ordinal=2, chunk_id=12, score=0.72, stage="vector"), + ], + ) + insert_citations( + db, + request_id, + [ + CitationRow( + ordinal=1, + chunk_id=11, + page_url="https://x/y", + heading_path="A > B", + quote="q", + verified=1, + ) + ], + ) + trace = get_request_trace(db, request_id) + assert trace is not None + assert trace.request.question == "How do I set retryPolicy?" + assert [r.chunk_id for r in trace.retrievals] == [11, 12] # ordinal order + assert trace.citations[0].verified == 1 + assert get_request_trace(db, 999) is None + + +def test_request_refusal_has_no_citations(db): + request_id = insert_request( + db, + _request_row( + answer_type="refusal", + refusal_stage="threshold", + answer_text="I don't know.", + ), + ) + trace = get_request_trace(db, request_id) + assert trace.request.answer_type == "refusal" + assert trace.request.refusal_stage == "threshold" + assert trace.citations == [] + + +def _request_row(**overrides): + fields = dict( + question="How do I set retryPolicy?", + fingerprint="a" * 64, + run_id=None, + answer_type="answer", + answer_text="Set functions retryPolicy.", + confidence="high", + latency_ms=1500, + prompt_tokens=900, + completion_tokens=120, + embed_tokens=40, + cost_usd=0.0, + refusal_stage=None, + payload_json='{"system": "s", "user": "u"}', + ts=NO_TS, + ) + return RequestRow(**{**fields, **overrides}) + + +# --------------------------------------------------------------------------- +# feedback (§8.8, §9.2) +# --------------------------------------------------------------------------- + + +def test_feedback_insert_is_idempotent_per_request(db): + request_id = insert_request(db, _request_row()) + feedback_id, created = insert_feedback( + db, FeedbackRow(request_id=request_id, helpful=1, created_at=NO_TS) + ) + assert created is True + same_id, created_again = insert_feedback( + db, FeedbackRow(request_id=request_id, helpful=0, created_at=NO_TS) + ) + assert created_again is False + assert same_id == feedback_id + stored = get_feedback(db, request_id) + assert stored.helpful == 1 # the first write wins; repeats are no-ops + + +# --------------------------------------------------------------------------- +# chunks_ trio (§8.3) — created on demand, FTS synced by triggers +# --------------------------------------------------------------------------- + + +def test_ensure_chunks_tables_rejects_bad_suffix(db): + with pytest.raises(DbError, match="suffix"): + ensure_chunks_tables(db, "NOT-HEX") + with pytest.raises(DbError, match="suffix"): + ensure_chunks_tables(db, "a" * 64) + + +def test_chunk_tables_roundtrip_with_fts_and_vec(db): + ensure_chunks_tables(db, "0123abcd") + ensure_chunks_tables(db, "0123abcd") # idempotent + ids = insert_chunks( + db, + "0123abcd", + [ + ChunkRow( + page_url="https://learn.microsoft.com/en-us/azure/azure-functions/timer", + heading_path="Functions > Timer trigger", + body="Set the schedule with a CRON expression.", + body_tokens=9, + chunk_hash="c" * 64, + ordinal=0, + ), + ChunkRow( + page_url="https://learn.microsoft.com/en-us/azure/azure-functions/timer", + heading_path="Functions > Timer trigger > Retry", + body="retryPolicy controls failed invocation retries.", + body_tokens=8, + chunk_hash="d" * 64, + ordinal=1, + ), + ], + ) + assert ids == [1, 2] + fetched = get_chunks(db, "0123abcd", [2, 1]) + assert [c.chunk_id for c in fetched] == [2, 1] # caller order preserved + assert fetched[0].heading_path.endswith("Retry") + + # FTS rowid-mapped to chunk_id, kept in sync by triggers (§8.3). + fts_hits = db.execute( + "SELECT rowid FROM chunks_0123abcd_fts WHERE chunks_0123abcd_fts MATCH 'retryPolicy'" + ).fetchall() + assert [int(row[0]) for row in fts_hits] == [2] + + # vec0: float[768] cosine, rowid = chunk_id (§8.3). + vector = [1.0 / (EMBEDDING_DIMENSIONS**0.5)] * EMBEDDING_DIMENSIONS # L2 norm 1.0 + insert_chunk_embeddings(db, "0123abcd", [(1, vector)]) + stored = db.execute( + "SELECT rowid, vec_distance_cosine(embedding, ?) FROM chunks_0123abcd_vec", + (sqlite_vec.serialize_float32(vector),), + ).fetchone() + assert int(stored[0]) == 1 + assert stored[1] == pytest.approx(0.0, abs=1e-6) + + +def test_delete_chunks_removes_fts_rows(db): + ensure_chunks_tables(db, "0123abcd") + (chunk_id,) = insert_chunks( + db, + "0123abcd", + [ + ChunkRow( + page_url="https://x", + heading_path="H", + body="retryPolicy controls retries.", + body_tokens=5, + chunk_hash="c" * 64, + ordinal=0, + ) + ], + ) + delete_chunks(db, "0123abcd", [chunk_id]) + with pytest.raises(DbError, match="missing"): + get_chunks(db, "0123abcd", [chunk_id]) + fts_hits = db.execute( + "SELECT rowid FROM chunks_0123abcd_fts WHERE chunks_0123abcd_fts MATCH 'retryPolicy'" + ).fetchall() + assert fts_hits == [] + + +def test_insert_chunk_embeddings_rejects_wrong_dimension(db): + ensure_chunks_tables(db, "0123abcd") + with pytest.raises(DbError, match="dimension"): + insert_chunk_embeddings(db, "0123abcd", [(1, [0.1] * (EMBEDDING_DIMENSIONS - 1))])