"""Persistent exact-search vector store backed by the Python standard library."""
from __future__ import annotations
import json
import math
import sqlite3
import threading
from collections.abc import Sequence
from pathlib import Path
from typing import Self
from ..transformation.models import DocumentChunk
from .models import chunk_identity
from .stores import cosine_similarity
[docs]
class SQLiteVectorStore:
"""Persist chunk vectors in SQLite and perform exact cosine search.
This adapter has no third-party runtime dependencies. It is useful for
durable local deployments and modest collections; it is not an approximate
nearest-neighbour index or a substitute for a distributed vector database.
A store owns one SQLite connection and serializes access with a re-entrant
lock. Use it as a context manager or call :meth:`close` when finished.
"""
[docs]
def __init__(
self,
database: str | Path,
*,
timeout: float = 5.0,
) -> None:
if timeout <= 0 or not math.isfinite(timeout):
raise ValueError("timeout must be a finite positive number")
self.database = str(database)
self._lock = threading.RLock()
self._connection = sqlite3.connect(
self.database, timeout=timeout, check_same_thread=False
)
self._connection.execute("PRAGMA foreign_keys = ON")
if self.database != ":memory:":
self._connection.execute("PRAGMA journal_mode = WAL")
self._connection.execute(
"""
CREATE TABLE IF NOT EXISTS document_vectors (
chunk_id TEXT PRIMARY KEY,
content TEXT NOT NULL,
chunk_index INTEGER NOT NULL,
source TEXT NOT NULL,
start_offset INTEGER NOT NULL,
end_offset INTEGER NOT NULL,
page_numbers TEXT NOT NULL,
element_indices TEXT NOT NULL,
element_types TEXT NOT NULL,
metadata TEXT NOT NULL,
embedding TEXT NOT NULL,
dimensions INTEGER NOT NULL CHECK (dimensions > 0)
)
"""
)
self._connection.execute(
"CREATE INDEX IF NOT EXISTS idx_document_vectors_source "
"ON document_vectors(source)"
)
self._connection.commit()
self._closed = False
def _ensure_open(self) -> None:
if self._closed:
raise RuntimeError("SQLiteVectorStore is closed")
@staticmethod
def _validated_vector(vector: Sequence[float]) -> tuple[float, ...]:
try:
values = tuple(float(value) for value in vector)
except (TypeError, ValueError, OverflowError) as exc:
raise ValueError("Embedding vectors must contain numeric values") from exc
if not values:
raise ValueError("Embedding vectors must not be empty")
if any(not math.isfinite(value) for value in values):
raise ValueError("Embedding vectors must contain only finite values")
return values
[docs]
def add(
self,
chunks: Sequence[DocumentChunk],
vectors: Sequence[Sequence[float]],
) -> None:
"""Insert or replace chunks and vectors in one atomic transaction."""
if len(chunks) != len(vectors):
raise ValueError("Each chunk must have exactly one vector")
with self._lock:
self._ensure_open()
if not chunks:
return
prepared = []
dimensions: int | None = None
for chunk, vector in zip(chunks, vectors, strict=True):
values = self._validated_vector(vector)
if dimensions is None:
dimensions = len(values)
elif len(values) != dimensions:
raise ValueError("All vectors must have the same dimensions")
prepared.append(
(
chunk_identity(chunk),
chunk.content,
chunk.chunk_index,
chunk.source,
chunk.start_offset,
chunk.end_offset,
json.dumps(chunk.page_numbers),
json.dumps(chunk.element_indices),
json.dumps(chunk.element_types),
json.dumps(chunk.metadata, ensure_ascii=False, allow_nan=False),
json.dumps(values, allow_nan=False),
len(values),
)
)
with self._lock:
self._ensure_open()
existing = self._connection.execute(
"SELECT DISTINCT dimensions FROM document_vectors"
).fetchall()
if existing and any(row[0] != dimensions for row in existing):
raise ValueError(
"Embedding dimensions must match the existing SQLite index"
)
try:
self._connection.executemany(
"""
INSERT INTO document_vectors (
chunk_id, content, chunk_index, source, start_offset,
end_offset, page_numbers, element_indices, element_types,
metadata, embedding, dimensions
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(chunk_id) DO UPDATE SET
content=excluded.content,
chunk_index=excluded.chunk_index,
source=excluded.source,
start_offset=excluded.start_offset,
end_offset=excluded.end_offset,
page_numbers=excluded.page_numbers,
element_indices=excluded.element_indices,
element_types=excluded.element_types,
metadata=excluded.metadata,
embedding=excluded.embedding,
dimensions=excluded.dimensions
""",
prepared,
)
self._connection.commit()
except Exception:
self._connection.rollback()
raise
[docs]
def replace_source(
self,
chunks: Sequence[DocumentChunk],
vectors: Sequence[Sequence[float]],
*,
source: str,
) -> None:
"""Atomically replace one source and its vectors.
Existing rows for other sources retain their embedding dimension. A
source can be replaced with a new dimension only when no other indexed
source depends on the previous dimension.
"""
if len(chunks) != len(vectors):
raise ValueError("Each chunk must have exactly one vector")
if any(chunk.source != source for chunk in chunks):
raise ValueError("all replacement chunks must belong to source")
prepared = []
dimensions: int | None = None
for chunk, vector in zip(chunks, vectors, strict=True):
values = self._validated_vector(vector)
if dimensions is None:
dimensions = len(values)
elif len(values) != dimensions:
raise ValueError("All vectors must have the same dimensions")
prepared.append(
(
chunk_identity(chunk),
chunk.content,
chunk.chunk_index,
chunk.source,
chunk.start_offset,
chunk.end_offset,
json.dumps(chunk.page_numbers),
json.dumps(chunk.element_indices),
json.dumps(chunk.element_types),
json.dumps(chunk.metadata, ensure_ascii=False, allow_nan=False),
json.dumps(values, allow_nan=False),
len(values),
)
)
with self._lock:
self._ensure_open()
try:
self._connection.execute("BEGIN IMMEDIATE")
existing = self._connection.execute(
"SELECT DISTINCT dimensions FROM document_vectors WHERE source != ?",
(source,),
).fetchall()
if (
dimensions is not None
and existing
and any(row[0] != dimensions for row in existing)
):
raise ValueError(
"Embedding dimensions must match vectors for other sources"
)
self._connection.execute(
"DELETE FROM document_vectors WHERE source = ?", (source,)
)
if prepared:
self._connection.executemany(
"""
INSERT INTO document_vectors (
chunk_id, content, chunk_index, source, start_offset,
end_offset, page_numbers, element_indices, element_types,
metadata, embedding, dimensions
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(chunk_id) DO UPDATE SET
content=excluded.content, chunk_index=excluded.chunk_index,
source=excluded.source, start_offset=excluded.start_offset,
end_offset=excluded.end_offset, page_numbers=excluded.page_numbers,
element_indices=excluded.element_indices, element_types=excluded.element_types,
metadata=excluded.metadata, embedding=excluded.embedding,
dimensions=excluded.dimensions
""",
prepared,
)
self._connection.commit()
except Exception:
self._connection.rollback()
raise
[docs]
def list_chunks(self, *, source: str | None = None) -> tuple[DocumentChunk, ...]:
"""Load indexed chunk records without their embedding payloads."""
query = (
"SELECT content, chunk_index, source, start_offset, end_offset, "
"page_numbers, element_indices, element_types, metadata "
"FROM document_vectors"
)
parameters: tuple[str, ...] = ()
if source is not None:
query += " WHERE source = ?"
parameters = (source,)
query += " ORDER BY source, chunk_index"
with self._lock:
self._ensure_open()
rows = self._connection.execute(query, parameters).fetchall()
return tuple(
DocumentChunk(
content=row[0],
chunk_index=row[1],
source=row[2],
start_offset=row[3],
end_offset=row[4],
page_numbers=tuple(json.loads(row[5])),
element_indices=tuple(json.loads(row[6])),
element_types=tuple(json.loads(row[7])),
metadata=json.loads(row[8]),
)
for row in rows
)
[docs]
def search(
self,
vector: Sequence[float],
k: int,
) -> list[tuple[DocumentChunk, float]]:
"""Return the top-k chunks ranked by exact cosine similarity."""
if k < 1:
raise ValueError("k must be at least 1")
query = self._validated_vector(vector)
with self._lock:
self._ensure_open()
rows = self._connection.execute(
"""SELECT content, chunk_index, source, start_offset, end_offset,
page_numbers, element_indices, element_types, metadata,
embedding, dimensions
FROM document_vectors"""
).fetchall()
ranked: list[tuple[DocumentChunk, float]] = []
for row in rows:
if row[10] != len(query):
raise ValueError(
"Query embedding dimension does not match indexed vectors"
)
chunk = DocumentChunk(
content=row[0],
chunk_index=row[1],
source=row[2],
start_offset=row[3],
end_offset=row[4],
page_numbers=tuple(json.loads(row[5])),
element_indices=tuple(json.loads(row[6])),
element_types=tuple(json.loads(row[7])),
metadata=json.loads(row[8]),
)
stored = json.loads(row[9])
ranked.append((chunk, cosine_similarity(query, stored)))
ranked.sort(key=lambda item: item[1], reverse=True)
return ranked[:k]
[docs]
def health_check(self) -> bool:
"""Run a lightweight database round-trip without scanning indexed content."""
with self._lock:
self._ensure_open()
self._connection.execute("SELECT 1").fetchone()
return True
def __len__(self) -> int:
with self._lock:
self._ensure_open()
return int(
self._connection.execute(
"SELECT COUNT(*) FROM document_vectors"
).fetchone()[0]
)
[docs]
def close(self) -> None:
"""Close the underlying SQLite connection; safe to call more than once."""
with self._lock:
if not self._closed:
self._connection.close()
self._closed = True
def __enter__(self) -> Self:
with self._lock:
self._ensure_open()
return self
def __exit__(self, exc_type, exc_value, traceback) -> None:
self.close()