"""SQLite fingerprint index for decontamination (``docs/02`` §5, ``docs/07`` §5). Two indexes are produced by the ``fingerprint`` command: - ``eval.sqlite`` — fingerprints of the frozen evaluation registry - ``train_candidates.sqlite`` — fingerprints of every normalized train source The schema is intentionally simple and deterministic: one ``fingerprints`` row per base_id plus one ``images`` row per (base_id, image) so exact-image and pHash near-duplicate joins are plain indexed SQL. The ``decontaminate`` command reads both indexes and never mutates them. OCR MinHash is stored as a nullable column populated later by the P5 OCR pass (:func:`update_ocr_minhash`); at P3 it is empty for every row. """ from __future__ import annotations import json import sqlite3 from collections.abc import Iterable, Iterator, Mapping, Sequence from dataclasses import dataclass from pathlib import Path from typing import Any from .fingerprints import Fingerprints _SCHEMA = """ CREATE TABLE IF NOT EXISTS fingerprints ( base_id TEXT PRIMARY KEY, source TEXT NOT NULL, source_revision TEXT NOT NULL, config TEXT NOT NULL, split TEXT NOT NULL, native_id TEXT NOT NULL, policy TEXT NOT NULL, question_sha256 TEXT NOT NULL, choices_sha256 TEXT NOT NULL, question_canonical_sha256 TEXT NOT NULL, question_minhash TEXT NOT NULL, choice_minhash TEXT NOT NULL, ocr_minhash TEXT NOT NULL DEFAULT '[]', derived_from_eval INTEGER NOT NULL DEFAULT 0, raw_json TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS images ( base_id TEXT NOT NULL, image_sha256 TEXT NOT NULL, phash TEXT NOT NULL, PRIMARY KEY (base_id, image_sha256) ); CREATE INDEX IF NOT EXISTS idx_images_sha ON images(image_sha256); CREATE INDEX IF NOT EXISTS idx_images_phash ON images(phash); CREATE INDEX IF NOT EXISTS idx_fp_source ON fingerprints(source); """ def _connect(db_path: str | Path) -> sqlite3.Connection: path = Path(db_path) path.parent.mkdir(parents=True, exist_ok=True) conn = sqlite3.connect(str(path)) conn.execute("PRAGMA journal_mode=WAL") conn.executescript(_SCHEMA) return conn def _signature_json(sig: Sequence[int]) -> str: return json.dumps(list(sig)) def write_fingerprints(db_path: str | Path, fingerprints: Iterable[Fingerprints]) -> int: """(Re)build the index from ``fingerprints``; return the row count. The index is a derived artifact, so this overwrites any prior contents. """ conn = _connect(db_path) try: with conn: conn.execute("DELETE FROM fingerprints") conn.execute("DELETE FROM images") count = 0 for fp in fingerprints: conn.execute( """INSERT INTO fingerprints (base_id, source, source_revision, config, split, native_id, policy, question_sha256, choices_sha256, question_canonical_sha256, question_minhash, choice_minhash, ocr_minhash, derived_from_eval, raw_json) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", ( fp.base_id, fp.source, fp.source_revision, fp.config, fp.split, fp.native_id, fp.policy, fp.question_sha256, fp.choices_sha256, fp.question_canonical_sha256, _signature_json(fp.question_minhash), _signature_json(fp.choice_minhash), _signature_json(fp.ocr_minhash), int(fp.derived_from_eval), json.dumps(fp.raw, sort_keys=True), ), ) for sha, phash in zip(fp.image_sha256, fp.image_phash, strict=True): conn.execute( "INSERT OR REPLACE INTO images (base_id, image_sha256, phash) " "VALUES (?,?,?)", (fp.base_id, sha, phash), ) # Text-only items still get one placeholder image row keyed by their # (single) sha so nothing is silently dropped; text items have none. count += 1 return count finally: conn.close() def update_ocr_minhash(db_path: str | Path, base_id: str, ocr_signature: Sequence[int]) -> bool: """Set the OCR MinHash for one base_id (P5 OCR enrichment). Returns whether updated.""" conn = _connect(db_path) try: with conn: cur = conn.execute( "UPDATE fingerprints SET ocr_minhash = ? WHERE base_id = ?", (_signature_json(ocr_signature), base_id), ) return cur.rowcount > 0 finally: conn.close() @dataclass(frozen=True) class LoadedFingerprints: base_id: str source: str source_revision: str config: str split: str native_id: str policy: str question_sha256: str choices_sha256: str question_canonical_sha256: str image_sha256: tuple[str, ...] image_phash: tuple[str, ...] question_minhash: tuple[int, ...] choice_minhash: tuple[int, ...] ocr_minhash: tuple[int, ...] derived_from_eval: bool def _load_images(conn: sqlite3.Connection, base_id: str) -> tuple[tuple[str, ...], tuple[str, ...]]: rows = conn.execute( "SELECT image_sha256, phash FROM images WHERE base_id = ?", (base_id,) ).fetchall() shas = tuple(r[0] for r in rows) phashes = tuple(r[1] for r in rows) return shas, phashes def _parse_sig(value: str) -> tuple[int, ...]: if not value: return () return tuple(int(x) for x in json.loads(value)) def load_all(db_path: str | Path) -> list[LoadedFingerprints]: """Load every fingerprint from the index, keyed by base_id (sorted).""" conn = sqlite3.connect(str(db_path)) try: rows = conn.execute( """SELECT base_id, source, source_revision, config, split, native_id, policy, question_sha256, choices_sha256, question_canonical_sha256, question_minhash, choice_minhash, ocr_minhash, derived_from_eval FROM fingerprints ORDER BY base_id""" ).fetchall() result: list[LoadedFingerprints] = [] for r in rows: shas, phashes = _load_images(conn, r[0]) result.append( LoadedFingerprints( base_id=r[0], source=r[1], source_revision=r[2], config=r[3], split=r[4], native_id=r[5], policy=r[6], question_sha256=r[7], choices_sha256=r[8], question_canonical_sha256=r[9], image_sha256=shas, image_phash=phashes, question_minhash=_parse_sig(r[10]), choice_minhash=_parse_sig(r[11]), ocr_minhash=_parse_sig(r[12]), derived_from_eval=bool(r[13]), ) ) return result finally: conn.close() def eval_image_shas(db_path: str | Path) -> set[str]: """All image SHA-256 present in an index (for exact-image reject).""" conn = sqlite3.connect(str(db_path)) try: return {row[0] for row in conn.execute("SELECT DISTINCT image_sha256 FROM images")} finally: conn.close() def row_count(db_path: str | Path) -> int: conn = sqlite3.connect(str(db_path)) try: return int(conn.execute("SELECT COUNT(*) FROM fingerprints").fetchone()[0]) finally: conn.close() def iter_rows(db_path: str | Path) -> Iterator[Mapping[str, Any]]: """Yield raw source rows (the ``raw_json`` column) for audit/rebuild.""" conn = sqlite3.connect(str(db_path)) try: for raw in conn.execute("SELECT raw_json FROM fingerprints ORDER BY base_id"): yield json.loads(raw[0]) finally: conn.close()