"""Neon Postgres persistence for documents, chunks, and embeddings.""" from __future__ import annotations import contextlib import os from collections.abc import Iterator, Mapping, Sequence from dataclasses import dataclass, field from datetime import date, datetime, timezone from typing import Any import numpy as np import psycopg from pgvector.psycopg import register_vector from psycopg import sql from psycopg.rows import DictRow, dict_row from infrastructure.logger import get_logger _logger = get_logger() TOK_VER = int(os.getenv("TOK_VER", "2")) SEG_VER = int(os.getenv("SEG_VER", "1")) @dataclass class Document: """Stored document metadata.""" doc_id: int sha256: str title: str | None = None source_path: str | None = None object_key: str | None = None created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) doc_type: str | None = None jurisdiction: str | None = None governing_law: str | None = None party_roles: str | None = None industry: str | None = None effective_date: date | datetime | None = None chunks: list[Chunk] = field(default_factory=list) @dataclass class Chunk: """Stored document chunk and its searchable metadata.""" chunk_id: int doc_id: int chunk_index: int text: str token_count: int | None = None page_start: int | None = None page_end: int | None = None section_number: str | None = None section_title: str | None = None path: str | None = None numbers_present: bool | None = None definition_terms: str | None = None clause_type: str | None = None tok_ver: int = TOK_VER seg_ver: int = SEG_VER embedding_input_version: int | None = None embedding_input_sha256: str | None = None embedding_model: str | None = None embedding_dim: int | None = None has_embedding: bool = False document: Document | None = None embedding: Embedding | None = None @dataclass class Embedding: """Embedding associated one-to-one with a chunk.""" id: int chunk_id: int model: str dim: int vector: list[float] chunk: Chunk | None = None @dataclass(frozen=True) class RawDocumentRecord: """Storage metadata for an original uploaded document.""" object_key: str | None source_filename: str content_type: str | None legacy_content: bytes | None = None def _database_url() -> str: """Return the configured Neon connection string. Raises: RuntimeError: If no database connection string is configured. """ value = os.getenv("DATABASE_URL") or os.getenv("NEON_DATABASE_URL") if not value: raise RuntimeError( "DATABASE_URL is required; set it to the Neon Postgres connection string" ) return value def _connect(*, register_types: bool = True) -> psycopg.Connection[DictRow]: """Open a short-lived Neon connection suitable for pooled URLs.""" timeout = int(os.getenv("DATABASE_CONNECT_TIMEOUT", "10")) connection = psycopg.Connection[DictRow].connect( _database_url(), connect_timeout=timeout, prepare_threshold=None, row_factory=dict_row, ) if register_types: register_vector(connection) return connection @contextlib.contextmanager def session_scope() -> Iterator[psycopg.Connection[DictRow]]: """Provide a committing transaction with automatic rollback on failure.""" with _connect() as connection, connection.transaction(): yield connection def get_session() -> psycopg.Connection[DictRow]: """Return a new database connection owned by the caller.""" return _connect() def get_db() -> psycopg.Connection[DictRow]: """Return a new database connection owned by the caller.""" return _connect() def init_db() -> None: """Create the pgvector extension and application tables when absent.""" with _connect(register_types=False) as connection: with connection.cursor() as cursor: cursor.execute("CREATE EXTENSION IF NOT EXISTS vector") cursor.execute( """ CREATE TABLE IF NOT EXISTS documents ( doc_id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, sha256 TEXT NOT NULL UNIQUE, title TEXT, source_path TEXT, source_filename TEXT, content_type TEXT, size_bytes BIGINT, object_key TEXT, raw_content BYTEA, clean_text TEXT, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), doc_type TEXT, jurisdiction TEXT, governing_law TEXT, party_roles TEXT, industry TEXT, effective_date DATE ) """ ) cursor.execute( "ALTER TABLE documents ADD COLUMN IF NOT EXISTS object_key TEXT" ) cursor.execute( f""" CREATE TABLE IF NOT EXISTS chunks ( chunk_id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, doc_id BIGINT NOT NULL REFERENCES documents(doc_id) ON DELETE CASCADE, chunk_index INTEGER NOT NULL, text TEXT NOT NULL, token_count INTEGER, page_start INTEGER, page_end INTEGER, section_number TEXT, section_title TEXT, path TEXT, numbers_present BOOLEAN, definition_terms TEXT, clause_type TEXT, tok_ver INTEGER NOT NULL DEFAULT {TOK_VER}, seg_ver INTEGER NOT NULL DEFAULT 1, embedding_model TEXT, embedding_dim INTEGER, embedding vector, embedding_input_version SMALLINT DEFAULT 1, embedding_input_sha256 TEXT, search_tsv TSVECTOR GENERATED ALWAYS AS ( setweight( to_tsvector('simple', COALESCE(section_title, '')), 'A' ) || setweight( to_tsvector('simple', COALESCE(clause_type, '')), 'A' ) || setweight( to_tsvector('simple', COALESCE(definition_terms, '')), 'A' ) || setweight( to_tsvector( 'simple', COALESCE(section_number, '') || ' ' || COALESCE(path, '') ), 'B' ) || setweight(to_tsvector('simple', text), 'D') ) STORED, UNIQUE (doc_id, chunk_index) ) """ ) cursor.execute( "ALTER TABLE chunks ADD COLUMN IF NOT EXISTS " "embedding_input_version SMALLINT DEFAULT 1" ) cursor.execute( "ALTER TABLE chunks ADD COLUMN IF NOT EXISTS " "embedding_input_sha256 TEXT" ) cursor.execute( f"ALTER TABLE chunks ALTER COLUMN tok_ver SET DEFAULT {TOK_VER}" ) cursor.execute( """ ALTER TABLE chunks ADD COLUMN IF NOT EXISTS search_tsv TSVECTOR GENERATED ALWAYS AS ( setweight( to_tsvector('simple', COALESCE(section_title, '')), 'A' ) || setweight( to_tsvector('simple', COALESCE(clause_type, '')), 'A' ) || setweight( to_tsvector('simple', COALESCE(definition_terms, '')), 'A' ) || setweight( to_tsvector( 'simple', COALESCE(section_number, '') || ' ' || COALESCE(path, '') ), 'B' ) || setweight(to_tsvector('simple', text), 'D') ) STORED """ ) cursor.execute( "CREATE INDEX IF NOT EXISTS chunks_doc_id_idx ON chunks (doc_id)" ) cursor.execute( "CREATE INDEX IF NOT EXISTS chunks_search_tsv_idx " "ON chunks USING GIN (search_tsv)" ) cursor.execute( "CREATE INDEX IF NOT EXISTS documents_created_at_idx " "ON documents (created_at DESC)" ) connection.commit() _logger.info("Neon Postgres schema initialized") def reset_database() -> bool: """Delete all application data while retaining the schema.""" try: with session_scope() as connection: connection.execute("TRUNCATE TABLE chunks, documents RESTART IDENTITY") return True except (psycopg.Error, RuntimeError, ValueError) as exc: _logger.error("Failed to reset Neon database: %s", exc) return False def full_reset_database() -> bool: """Delete all persistent application records.""" return reset_database() def _normalize_text_value(value: Any) -> Any: """Normalize list metadata to the comma-delimited representation used by the UI.""" if isinstance(value, list): return ", ".join(str(item) for item in value) return value def _normalize_effective_date(value: Any) -> date | None: """Coerce supported effective-date values into a Postgres date.""" if value is None or value == "" or str(value).lower() == "none": return None if isinstance(value, datetime): return value.date() if isinstance(value, date): return value try: return date.fromisoformat(str(value)[:10]) except ValueError: _logger.warning("Ignoring invalid effective date: %s", value) return None def _document_from_row(row: Mapping[str, Any]) -> Document: """Convert a database row into a document domain object.""" return Document( doc_id=int(row["doc_id"]), sha256=str(row["sha256"]), title=row.get("title"), source_path=row.get("source_path"), object_key=row.get("object_key"), created_at=row.get("created_at") or datetime.now(timezone.utc), doc_type=row.get("doc_type"), jurisdiction=row.get("jurisdiction"), governing_law=row.get("governing_law"), party_roles=row.get("party_roles"), industry=row.get("industry"), effective_date=row.get("effective_date"), ) def _chunk_from_row(row: Mapping[str, Any]) -> Chunk: """Convert a database row into a chunk domain object.""" return Chunk( chunk_id=int(row["chunk_id"]), doc_id=int(row["doc_id"]), chunk_index=int(row["chunk_index"]), text=str(row.get("text") or ""), token_count=row.get("token_count"), page_start=row.get("page_start"), page_end=row.get("page_end"), section_number=row.get("section_number"), section_title=row.get("section_title"), path=row.get("path"), numbers_present=row.get("numbers_present"), definition_terms=row.get("definition_terms"), clause_type=row.get("clause_type"), tok_ver=int(row.get("tok_ver") or TOK_VER), seg_ver=int(row.get("seg_ver") or SEG_VER), embedding_input_version=row.get("embedding_input_version"), embedding_input_sha256=row.get("embedding_input_sha256"), embedding_model=row.get("embedding_model"), embedding_dim=row.get("embedding_dim"), has_embedding=bool(row.get("has_embedding", False)), ) _DOCUMENT_COLUMNS = """ doc_id, sha256, title, source_path, object_key, created_at, doc_type, jurisdiction, governing_law, party_roles, industry, effective_date """ _CHUNK_COLUMNS = """ chunk_id, doc_id, chunk_index, text, token_count, page_start, page_end, section_number, section_title, path, numbers_present, definition_terms, clause_type, tok_ver, seg_ver, embedding_input_version, embedding_input_sha256, embedding_model, embedding_dim, (embedding IS NOT NULL) AS has_embedding """ def add_document( *, sha256: str, title: str | None = None, source_path: str | None = None, doc_type: str | list[str] | None = None, jurisdiction: str | list[str] | None = None, industry: str | list[str] | None = None, party_roles: str | list[str] | None = None, governing_law: str | list[str] | None = None, effective_date: Any = None, ) -> Document: """Insert a document or enrich missing metadata for an existing hash.""" values = { "sha256": sha256, "title": _normalize_text_value(title), "source_path": source_path, "doc_type": _normalize_text_value(doc_type), "jurisdiction": _normalize_text_value(jurisdiction), "industry": _normalize_text_value(industry), "party_roles": _normalize_text_value(party_roles), "governing_law": _normalize_text_value(governing_law), "effective_date": _normalize_effective_date(effective_date), } with session_scope() as connection: row = connection.execute( f""" INSERT INTO documents ( sha256, title, source_path, doc_type, jurisdiction, industry, party_roles, governing_law, effective_date ) VALUES ( %(sha256)s, %(title)s, %(source_path)s, %(doc_type)s, %(jurisdiction)s, %(industry)s, %(party_roles)s, %(governing_law)s, %(effective_date)s ) ON CONFLICT (sha256) DO UPDATE SET title = COALESCE(documents.title, EXCLUDED.title), source_path = COALESCE(documents.source_path, EXCLUDED.source_path), doc_type = COALESCE(documents.doc_type, EXCLUDED.doc_type), jurisdiction = COALESCE(documents.jurisdiction, EXCLUDED.jurisdiction), industry = COALESCE(documents.industry, EXCLUDED.industry), party_roles = COALESCE(documents.party_roles, EXCLUDED.party_roles), governing_law = COALESCE( documents.governing_law, EXCLUDED.governing_law ), effective_date = COALESCE( documents.effective_date, EXCLUDED.effective_date ) RETURNING {_DOCUMENT_COLUMNS} """, values, ).fetchone() if row is None: raise RuntimeError("Neon did not return the inserted document") return _document_from_row(row) def store_document_content( doc_id: int, *, source_filename: str, content_type: str | None, object_key: str, size_bytes: int, clean_text: str, ) -> Document: """Persist object metadata and extracted text in Neon Postgres.""" source_path = f"/api/raw/{doc_id}/{source_filename}" with session_scope() as connection: row = connection.execute( f""" UPDATE documents SET source_path = %s, source_filename = %s, content_type = %s, size_bytes = %s, object_key = %s, raw_content = NULL, clean_text = %s WHERE doc_id = %s RETURNING {_DOCUMENT_COLUMNS} """, ( source_path, source_filename, content_type, size_bytes, object_key, clean_text, doc_id, ), ).fetchone() if row is None: raise KeyError(f"Document {doc_id} does not exist") return _document_from_row(row) def get_raw_document(doc_id: int) -> RawDocumentRecord | None: """Return object metadata or legacy database bytes for an original upload.""" with _connect() as connection: row = connection.execute( """ SELECT object_key, raw_content, source_filename, content_type FROM documents WHERE doc_id = %s AND (object_key IS NOT NULL OR raw_content IS NOT NULL) """, (doc_id,), ).fetchone() if row is None: return None legacy_content = row["raw_content"] return RawDocumentRecord( object_key=row["object_key"], source_filename=str(row["source_filename"] or "document"), content_type=row["content_type"], legacy_content=bytes(legacy_content) if legacy_content is not None else None, ) def add_chunk( doc_id: int, chunk_id: int | None, text: str, chunk_index: int, token_count: int | None = None, page_start: int | None = None, page_end: int | None = None, section_number: str | None = None, section_title: str | None = None, path: str | None = None, numbers_present: bool | None = None, definition_terms: str | list[str] | None = None, clause_type: str | None = None, tok_ver: int = TOK_VER, seg_ver: int = SEG_VER, ) -> Chunk: """Insert or replace the chunk at a document-relative index.""" definition_terms_value = _normalize_text_value(definition_terms) columns = [ "doc_id", "chunk_index", "text", "token_count", "page_start", "page_end", "section_number", "section_title", "path", "numbers_present", "definition_terms", "clause_type", "tok_ver", "seg_ver", ] values: list[Any] = [ doc_id, chunk_index, text, token_count, page_start, page_end, section_number, section_title, path, numbers_present, definition_terms_value, clause_type, tok_ver, seg_ver, ] if chunk_id is not None: columns.insert(0, "chunk_id") values.insert(0, chunk_id) insert = sql.SQL( """ INSERT INTO chunks ({columns}) VALUES ({placeholders}) ON CONFLICT (doc_id, chunk_index) DO UPDATE SET text = EXCLUDED.text, token_count = EXCLUDED.token_count, page_start = EXCLUDED.page_start, page_end = EXCLUDED.page_end, section_number = EXCLUDED.section_number, section_title = EXCLUDED.section_title, path = EXCLUDED.path, numbers_present = EXCLUDED.numbers_present, definition_terms = EXCLUDED.definition_terms, clause_type = EXCLUDED.clause_type, tok_ver = EXCLUDED.tok_ver, seg_ver = EXCLUDED.seg_ver, embedding = CASE WHEN ROW( chunks.text, chunks.section_number, chunks.section_title, chunks.clause_type, chunks.definition_terms, chunks.path ) IS NOT DISTINCT FROM ROW( EXCLUDED.text, EXCLUDED.section_number, EXCLUDED.section_title, EXCLUDED.clause_type, EXCLUDED.definition_terms, EXCLUDED.path ) THEN chunks.embedding ELSE NULL END, embedding_model = CASE WHEN ROW( chunks.text, chunks.section_number, chunks.section_title, chunks.clause_type, chunks.definition_terms, chunks.path ) IS NOT DISTINCT FROM ROW( EXCLUDED.text, EXCLUDED.section_number, EXCLUDED.section_title, EXCLUDED.clause_type, EXCLUDED.definition_terms, EXCLUDED.path ) THEN chunks.embedding_model ELSE NULL END, embedding_dim = CASE WHEN ROW( chunks.text, chunks.section_number, chunks.section_title, chunks.clause_type, chunks.definition_terms, chunks.path ) IS NOT DISTINCT FROM ROW( EXCLUDED.text, EXCLUDED.section_number, EXCLUDED.section_title, EXCLUDED.clause_type, EXCLUDED.definition_terms, EXCLUDED.path ) THEN chunks.embedding_dim ELSE NULL END, embedding_input_version = CASE WHEN ROW( chunks.text, chunks.section_number, chunks.section_title, chunks.clause_type, chunks.definition_terms, chunks.path ) IS NOT DISTINCT FROM ROW( EXCLUDED.text, EXCLUDED.section_number, EXCLUDED.section_title, EXCLUDED.clause_type, EXCLUDED.definition_terms, EXCLUDED.path ) THEN chunks.embedding_input_version ELSE NULL END, embedding_input_sha256 = CASE WHEN ROW( chunks.text, chunks.section_number, chunks.section_title, chunks.clause_type, chunks.definition_terms, chunks.path ) IS NOT DISTINCT FROM ROW( EXCLUDED.text, EXCLUDED.section_number, EXCLUDED.section_title, EXCLUDED.clause_type, EXCLUDED.definition_terms, EXCLUDED.path ) THEN chunks.embedding_input_sha256 ELSE NULL END RETURNING {returning} """ ).format( columns=sql.SQL(", ").join(map(sql.Identifier, columns)), placeholders=sql.SQL(", ").join(sql.Placeholder() for _ in columns), returning=sql.SQL(_CHUNK_COLUMNS), ) with session_scope() as connection: row = connection.execute(insert, values).fetchone() if chunk_id is not None: connection.execute( """ SELECT setval( pg_get_serial_sequence('chunks', 'chunk_id'), GREATEST((SELECT COALESCE(MAX(chunk_id), 1) FROM chunks), 1), true ) """ ) if row is None: raise RuntimeError("Neon did not return the inserted chunk") return _chunk_from_row(row) def upsert_embedding( chunk_id: int, model: str, dim: int, vector_bytes: bytes | Sequence[float], *, input_version: int = 1, input_sha256: str | None = None, ) -> Embedding | None: """Persist an embedding in the pgvector column for a chunk.""" if isinstance(vector_bytes, bytes): vector = np.frombuffer(vector_bytes, dtype=np.float32).tolist() else: vector = [float(value) for value in vector_bytes] if len(vector) != dim: raise ValueError(f"Embedding dimension {len(vector)} does not match {dim}") database_vector = np.asarray(vector, dtype=np.float32) with session_scope() as connection: row = connection.execute( """ UPDATE chunks SET embedding = %s, embedding_model = %s, embedding_dim = %s, embedding_input_version = %s, embedding_input_sha256 = %s WHERE chunk_id = %s RETURNING chunk_id """, ( database_vector, model, dim, input_version, input_sha256, chunk_id, ), ).fetchone() if row is None: _logger.error("Cannot upsert embedding for missing chunk_id=%s", chunk_id) return None return Embedding( id=chunk_id, chunk_id=chunk_id, model=model, dim=dim, vector=vector, ) def upsert_embeddings(records: Sequence[Mapping[str, Any]]) -> int: """Atomically replace a batch of successfully generated embeddings.""" if not records: return 0 with session_scope() as connection: for record in records: vector = [float(value) for value in record["vector"]] dim = int(record["dim"]) if len(vector) != dim: raise ValueError( f"Embedding dimension {len(vector)} does not match {dim}" ) row = connection.execute( """ UPDATE chunks SET embedding = %s, embedding_model = %s, embedding_dim = %s, embedding_input_version = %s, embedding_input_sha256 = %s, token_count = COALESCE(%s, token_count), tok_ver = COALESCE(%s, tok_ver) WHERE chunk_id = %s RETURNING chunk_id """, ( np.asarray(vector, dtype=np.float32), str(record["model"]), dim, int(record["input_version"]), str(record["input_sha256"]), record.get("token_count"), record.get("tok_ver"), int(record["chunk_id"]), ), ).fetchone() if row is None: raise RuntimeError( f"Cannot upsert embedding for missing chunk_id={record['chunk_id']}" ) return len(records) def get_document(doc_id: int) -> Document | None: """Return one document by identifier.""" with _connect() as connection: row = connection.execute( f"SELECT {_DOCUMENT_COLUMNS} FROM documents WHERE doc_id = %s", (doc_id,), ).fetchone() return _document_from_row(row) if row else None def get_document_by_sha(sha256: str) -> Document | None: """Return one document by its cleaned-content hash.""" with _connect() as connection: row = connection.execute( f"SELECT {_DOCUMENT_COLUMNS} FROM documents WHERE sha256 = %s", (sha256,), ).fetchone() return _document_from_row(row) if row else None def get_chunks_for_doc(doc_id: int) -> list[Chunk]: """Return all chunks for a document in source order.""" with _connect() as connection: rows = connection.execute( f""" SELECT {_CHUNK_COLUMNS} FROM chunks WHERE doc_id = %s ORDER BY chunk_index """, (doc_id,), ).fetchall() return [_chunk_from_row(row) for row in rows] def get_chunks_by_ids(chunk_ids: list[int]) -> list[Chunk]: """Return chunks with parent document metadata, preserving requested order.""" if not chunk_ids: return [] with _connect() as connection: rows = connection.execute( f""" SELECT {_CHUNK_COLUMNS} FROM chunks WHERE chunk_id = ANY(%s) """, (chunk_ids,), ).fetchall() chunks = [_chunk_from_row(row) for row in rows] document_ids = list({chunk.doc_id for chunk in chunks}) document_rows = connection.execute( f""" SELECT {_DOCUMENT_COLUMNS} FROM documents WHERE doc_id = ANY(%s) """, (document_ids,), ).fetchall() documents = {int(row["doc_id"]): _document_from_row(row) for row in document_rows} chunks_by_id = {chunk.chunk_id: chunk for chunk in chunks} for chunk in chunks: chunk.document = documents.get(chunk.doc_id) return [ chunks_by_id[chunk_id] for chunk_id in chunk_ids if chunk_id in chunks_by_id ] def get_documents(limit: int = 100, offset: int = 0) -> list[Document]: """Return a newest-first page of documents.""" with _connect() as connection: rows = connection.execute( f""" SELECT {_DOCUMENT_COLUMNS} FROM documents ORDER BY created_at DESC, doc_id DESC LIMIT %s OFFSET %s """, (limit, offset), ).fetchall() return [_document_from_row(row) for row in rows] def get_document_chunk_counts(doc_ids: list[int]) -> dict[int, int]: """Return chunk counts for the supplied document identifiers.""" counts = {doc_id: 0 for doc_id in doc_ids} if not doc_ids: return counts with _connect() as connection: rows = connection.execute( """ SELECT doc_id, count(*) AS chunk_count FROM chunks WHERE doc_id = ANY(%s) GROUP BY doc_id """, (doc_ids,), ).fetchall() for row in rows: counts[int(row["doc_id"])] = int(row["chunk_count"]) return counts def get_max_document_id() -> int: """Return the greatest assigned document identifier.""" with _connect() as connection: row = connection.execute( "SELECT COALESCE(MAX(doc_id), 0) AS max_id FROM documents" ).fetchone() return int(row["max_id"]) if row else 0 def get_all_chunks(limit: int = 200, offset: int = 0) -> list[Chunk]: """Return an identifier-ordered page of chunks.""" with _connect() as connection: rows = connection.execute( f""" SELECT {_CHUNK_COLUMNS} FROM chunks ORDER BY chunk_id LIMIT %s OFFSET %s """, (limit, offset), ).fetchall() return [_chunk_from_row(row) for row in rows] def get_embedding_backfill_batch( *, after_chunk_id: int = 0, limit: int = 64 ) -> list[Chunk]: """Return a stable chunk-ID batch for resumable embedding backfills.""" with _connect() as connection: rows = connection.execute( f""" SELECT {_CHUNK_COLUMNS} FROM chunks WHERE chunk_id > %s ORDER BY chunk_id LIMIT %s """, (after_chunk_id, limit), ).fetchall() return [_chunk_from_row(row) for row in rows] def get_max_chunk_id() -> int: """Return the greatest assigned chunk identifier.""" with _connect() as connection: row = connection.execute( "SELECT COALESCE(MAX(chunk_id), -1) AS max_id FROM chunks" ).fetchone() return int(row["max_id"]) if row else -1 def _embedding_values(value: Any) -> list[float] | None: """Normalize pgvector wrappers and sequence-like vectors to plain floats.""" if value is None: return None to_list = getattr(value, "to_list", None) if callable(to_list): value = to_list() return [float(item) for item in value] def get_embedding_for_chunk(chunk_id: int) -> Embedding | None: """Return a chunk embedding if one has been generated.""" with _connect() as connection: row = connection.execute( """ SELECT chunk_id, embedding_model, embedding_dim, embedding FROM chunks WHERE chunk_id = %s AND embedding IS NOT NULL """, (chunk_id,), ).fetchone() if row is None: return None vector = _embedding_values(row["embedding"]) or [] return Embedding( id=chunk_id, chunk_id=chunk_id, model=str(row["embedding_model"] or "unknown"), dim=int(row["embedding_dim"] or len(vector)), vector=vector, ) def get_embedding_counts_for_chunks(chunk_ids: list[int]) -> dict[int, int]: """Return zero-or-one embedding counts for supplied chunks.""" counts = {chunk_id: 0 for chunk_id in chunk_ids} if not chunk_ids: return counts with _connect() as connection: rows = connection.execute( """ SELECT chunk_id FROM chunks WHERE chunk_id = ANY(%s) AND embedding IS NOT NULL """, (chunk_ids,), ).fetchall() for row in rows: counts[int(row["chunk_id"])] = 1 return counts _SEARCH_FILTER_FIELDS = {"doc_type", "jurisdiction", "governing_law", "industry"} def _search_conditions( filters: Mapping[str, Any] | None, ) -> tuple[list[sql.Composable], list[Any]]: """Build parameterized document-filter conditions for candidate searches.""" conditions: list[sql.Composable] = [] parameters: list[Any] = [] if not filters: return conditions, parameters if filters.get("doc_id") is not None: conditions.append(sql.SQL("c.doc_id = %s")) parameters.append(int(filters["doc_id"])) for metadata_field in sorted(_SEARCH_FILTER_FIELDS): value = filters.get(metadata_field) if value is None: continue conditions.append( sql.SQL( "%s = ANY(regexp_split_to_array(" "lower(trim(COALESCE(d.{field}, ''))), '\\s*,\\s*'))" ).format(field=sql.Identifier(metadata_field)) ) parameters.append(str(value).strip().lower()) return conditions, parameters def _candidate_from_row(row: Mapping[str, Any]) -> dict[str, Any]: """Normalize a database candidate for rank fusion.""" vector = _embedding_values(row.get("embedding")) candidate = { "chunk_id": int(row["chunk_id"]), "doc_id": int(row["doc_id"]), "chunk_index": int(row["chunk_index"]), "text": str(row.get("text") or ""), "token_count": row.get("token_count"), "page_start": row.get("page_start"), "page_end": row.get("page_end"), "section_number": row.get("section_number"), "section_title": row.get("section_title"), "clause_type": row.get("clause_type"), "path": row.get("path"), "definition_terms": row.get("definition_terms"), "document_sha256": str(row.get("document_sha256") or ""), "title": row.get("title"), "doc_type": row.get("doc_type"), "jurisdiction": row.get("jurisdiction"), "governing_law": row.get("governing_law"), "industry": row.get("industry"), "embedding": vector, } if row.get("distance") is not None: candidate["distance"] = float(row["distance"]) if row.get("lexical_score") is not None: candidate["lexical_score"] = float(row["lexical_score"]) return candidate _CANDIDATE_COLUMNS = """ c.chunk_id, c.doc_id, c.chunk_index, c.text, c.token_count, c.page_start, c.page_end, c.section_number, c.section_title, c.clause_type, c.path, c.definition_terms, c.embedding, d.sha256 AS document_sha256, d.title, d.doc_type, d.jurisdiction, d.governing_law, d.industry """ def search_vector_candidates( query_vector: Sequence[float], *, model: str, limit: int, filters: Mapping[str, Any] | None = None, ) -> list[dict[str, Any]]: """Return an exact cosine-ranked candidate pool with document filters.""" vector = [float(value) for value in query_vector] database_vector = np.asarray(vector, dtype=np.float32) filter_conditions, filter_parameters = _search_conditions(filters) conditions = [ sql.SQL("c.embedding IS NOT NULL"), sql.SQL("c.embedding_model = %s"), sql.SQL("c.embedding_dim = %s"), *filter_conditions, ] statement = sql.SQL( """ SELECT {columns}, c.embedding <=> %s AS distance FROM chunks c JOIN documents d ON d.doc_id = c.doc_id WHERE {conditions} ORDER BY c.embedding <=> %s, c.chunk_id LIMIT %s """ ).format( columns=sql.SQL(_CANDIDATE_COLUMNS), conditions=sql.SQL(" AND ").join(conditions), ) parameters = [ database_vector, model, len(vector), *filter_parameters, database_vector, limit, ] with _connect() as connection: rows = connection.execute(statement, parameters).fetchall() return [_candidate_from_row(row) for row in rows] def search_lexical_candidates( query: str, *, limit: int, filters: Mapping[str, Any] | None = None, ) -> list[dict[str, Any]]: """Return a weighted Postgres full-text candidate pool.""" filter_conditions, filter_parameters = _search_conditions(filters) conditions = [sql.SQL("c.search_tsv @@ query.value"), *filter_conditions] statement = sql.SQL( """ WITH query AS ( SELECT websearch_to_tsquery('simple', %s) AS value ) SELECT {columns}, ts_rank_cd(c.search_tsv, query.value, 32) AS lexical_score FROM chunks c JOIN documents d ON d.doc_id = c.doc_id CROSS JOIN query WHERE {conditions} ORDER BY lexical_score DESC, c.chunk_id LIMIT %s """ ).format( columns=sql.SQL(_CANDIDATE_COLUMNS), conditions=sql.SQL(" AND ").join(conditions), ) parameters = [query, *filter_parameters, limit] with _connect() as connection: rows = connection.execute(statement, parameters).fetchall() return [_candidate_from_row(row) for row in rows] def search_chunks( query_vector: Sequence[float], *, model: str, limit: int, doc_id: int | None = None, ) -> list[dict[str, Any]]: """Run exact cosine-distance search over compatible pgvector rows.""" vector = [float(value) for value in query_vector] database_vector = np.asarray(vector, dtype=np.float32) conditions = [ sql.SQL("embedding IS NOT NULL"), sql.SQL("embedding_model = %s"), sql.SQL("embedding_dim = %s"), ] filter_params: list[Any] = [model, len(vector)] if doc_id is not None: conditions.append(sql.SQL("doc_id = %s")) filter_params.append(doc_id) statement = sql.SQL( """ SELECT chunk_id, text, doc_id, embedding <=> %s AS distance FROM chunks WHERE {conditions} ORDER BY embedding <=> %s LIMIT %s """ ).format(conditions=sql.SQL(" AND ").join(conditions)) params = [database_vector, *filter_params, database_vector, limit] with _connect() as connection: rows = connection.execute(statement, params).fetchall() return [ { "id": str(row["chunk_id"]), "distance": float(row["distance"]), "document": row["text"], "metadata": {"doc_id": int(row["doc_id"])}, } for row in rows ] def delete_document(doc_id: int) -> bool: """Delete a document and all cascading chunks and embeddings.""" with session_scope() as connection: result = connection.execute( "DELETE FROM documents WHERE doc_id = %s", (doc_id,) ) return result.rowcount > 0 def update_chunk(chunk_id: int, updates: Mapping[str, Any]) -> Chunk | None: """Update editable chunk fields and invalidate a changed-text embedding.""" allowed = { "text", "section_number", "section_title", "clause_type", "definition_terms", "page_start", "page_end", "path", "numbers_present", } normalized: dict[str, Any] = {} for key, value in updates.items(): if key not in allowed: continue if key in {"page_start", "page_end"}: normalized[key] = int(value) if value is not None and value != "" else None elif key == "numbers_present" and isinstance(value, str): normalized[key] = value.strip().lower() in {"1", "true", "yes"} elif key == "definition_terms": normalized[key] = _normalize_text_value(value) elif value is None: normalized[key] = None else: normalized[key] = str(value) if not normalized: chunks = get_chunks_by_ids([chunk_id]) return chunks[0] if chunks else None if "text" in normalized: from infrastructure.retrieval_text import count_tokens normalized["token_count"] = count_tokens(str(normalized["text"] or "")) normalized["tok_ver"] = TOK_VER assignments: list[sql.Composable] = [ sql.SQL("{} = %s").format(sql.Identifier(key)) for key in normalized ] values = list(normalized.values()) retrieval_fields = { "text", "section_number", "section_title", "clause_type", "definition_terms", "path", } if retrieval_fields.intersection(normalized): assignments.extend( [ sql.SQL("embedding = NULL"), sql.SQL("embedding_model = NULL"), sql.SQL("embedding_dim = NULL"), sql.SQL("embedding_input_version = NULL"), sql.SQL("embedding_input_sha256 = NULL"), ] ) statement = sql.SQL( "UPDATE chunks SET {assignments} WHERE chunk_id = %s RETURNING {columns}" ).format( assignments=sql.SQL(", ").join(assignments), columns=sql.SQL(_CHUNK_COLUMNS), ) values.append(chunk_id) with session_scope() as connection: row = connection.execute(statement, values).fetchone() return _chunk_from_row(row) if row else None def update_document(doc_id: int, updates: Mapping[str, Any]) -> Document | None: """Update editable document metadata.""" allowed = { "title", "doc_type", "jurisdiction", "governing_law", "party_roles", "industry", "effective_date", "source_path", } normalized = { key: ( _normalize_effective_date(value) if key == "effective_date" else _normalize_text_value(value) ) for key, value in updates.items() if key in allowed } if not normalized: return get_document(doc_id) assignments = sql.SQL(", ").join( sql.SQL("{} = %s").format(sql.Identifier(key)) for key in normalized ) statement = sql.SQL( "UPDATE documents SET {assignments} WHERE doc_id = %s RETURNING {columns}" ).format(assignments=assignments, columns=sql.SQL(_DOCUMENT_COLUMNS)) values = [*normalized.values(), doc_id] with session_scope() as connection: row = connection.execute(statement, values).fetchone() return _document_from_row(row) if row else None def get_manifest_records() -> list[dict[str, Any]]: """Return the document manifest directly from durable database records.""" with _connect() as connection: rows = connection.execute( """ SELECT doc_id, title, sha256, source_path, size_bytes, content_type, doc_type, party_roles, jurisdiction, governing_law, industry, effective_date, created_at FROM documents ORDER BY created_at DESC, doc_id DESC """ ).fetchall() records: list[dict[str, Any]] = [] for row in rows: effective_date_value = row["effective_date"] created_at_value = row["created_at"] records.append( { "doc_id": str(row["doc_id"]), "title": row["title"], "sha256": row["sha256"], "source_path": row["source_path"], "clean_path": f"database://documents/{row['doc_id']}/clean_text", "bytes": str(row["size_bytes"] or 0), "content_type": row["content_type"], "doc_type": row["doc_type"], "party_roles": row["party_roles"], "jurisdiction": row["jurisdiction"], "governing_law": row["governing_law"], "industry": row["industry"], "effective_date": ( effective_date_value.isoformat() if effective_date_value else None ), "created_at": created_at_value.isoformat(), } ) return records def clear_database() -> None: """Delete all application data.""" if not reset_database(): raise RuntimeError("Failed to clear Neon database") def ping() -> None: """Verify that Neon accepts a query.""" with _connect() as connection: connection.execute("SELECT 1").fetchone() __all__ = [ "SEG_VER", "TOK_VER", "Chunk", "Document", "Embedding", "RawDocumentRecord", "add_chunk", "add_document", "clear_database", "delete_document", "full_reset_database", "get_all_chunks", "get_chunks_by_ids", "get_chunks_for_doc", "get_db", "get_document", "get_document_by_sha", "get_document_chunk_counts", "get_documents", "get_embedding_backfill_batch", "get_embedding_counts_for_chunks", "get_embedding_for_chunk", "get_manifest_records", "get_max_chunk_id", "get_max_document_id", "get_raw_document", "get_session", "init_db", "ping", "reset_database", "search_chunks", "search_lexical_candidates", "search_vector_candidates", "session_scope", "store_document_content", "update_chunk", "update_document", "upsert_embedding", "upsert_embeddings", ]