feat(ingestion): extend domain types, ports, and configuration for ingestion pipeline

- Add ExtractedBlock, ExtractionEnvelope, and StagedDocument data models in types.py
- Define ingestion repository, file store, vision, and extraction ports in ports.py
- Extend IngestionSettings with limits, policies, vision, and embedding configuration
- Update database compatibility verification to support worker and review schema revisions
- Add PyMuPDF, Pillow, defusedxml, and tiktoken dependencies to pyproject.toml
This commit is contained in:
amirhosein mazaheri
2026-10-07 16:20:19 +03:30
parent ca8833dd2f
commit 0a998ac94a
6 changed files with 333 additions and 31 deletions
+34 -2
View File
@@ -24,12 +24,12 @@ INGEST_EMBEDDING_PROVIDER=""
INGEST_EMBEDDING_ENDPOINT="" INGEST_EMBEDDING_ENDPOINT=""
INGEST_EMBEDDING_MODEL="" INGEST_EMBEDDING_MODEL=""
INGEST_EMBEDDING_DIMENSIONS= INGEST_EMBEDDING_DIMENSIONS=
# Not needed for schema/bootstrap; required by the future hosted adapter. # Not needed for schema/bootstrap; required by the hosted embedding adapter.
INGEST_EMBEDDING_API_KEY="" INGEST_EMBEDDING_API_KEY=""
INGEST_EMBEDDING_PREPROCESSING_VERSION="v1" INGEST_EMBEDDING_PREPROCESSING_VERSION="v1"
INGEST_EMBEDDING_TIMEOUT_SECONDS=60 INGEST_EMBEDDING_TIMEOUT_SECONDS=60
INGEST_ORIGINAL_DIRECTORY="data/originals" INGEST_ORIGINAL_DIRECTORY="data/originals"
INGEST_ACCEPTED_FORMATS='[".pdf", ".md"]' INGEST_ACCEPTED_FORMATS='[".pdf", ".md", ".docx", ".jpg", ".jpeg", ".png"]'
INGEST_MAX_ORIGINAL_BYTES=20971520 INGEST_MAX_ORIGINAL_BYTES=20971520
INGEST_MAX_PDF_PAGES=200 INGEST_MAX_PDF_PAGES=200
INGEST_MAX_NORMALIZED_CHARACTERS=1000000 INGEST_MAX_NORMALIZED_CHARACTERS=1000000
@@ -45,3 +45,35 @@ INGEST_LEASE_SECONDS=120
INGEST_MAX_AUTOMATIC_ATTEMPTS=3 INGEST_MAX_AUTOMATIC_ATTEMPTS=3
INGEST_RETRY_BASE_SECONDS=2 INGEST_RETRY_BASE_SECONDS=2
INGEST_RETRY_CAP_SECONDS=300 INGEST_RETRY_CAP_SECONDS=300
# Engineering deployment defaults, not product-owner approval. No OCR at intake.
INGEST_EXTRACTION_DIRECTORY="data/extractions"
INGEST_MAX_DOCX_ENTRIES=2048
INGEST_MAX_DOCX_MEMBER_BYTES=16777216
INGEST_MAX_DOCX_EXPANDED_BYTES=67108864
INGEST_MAX_DOCX_COMPRESSION_RATIO=200
INGEST_MAX_IMAGE_WIDTH=12000
INGEST_MAX_IMAGE_HEIGHT=12000
INGEST_MAX_IMAGE_PIXELS=40000000
INGEST_EXTRACTION_STRATEGY="direct-quality-fallback-v1"
# Optional identity: configure all three together; credentials are needed only for opt-in Phase 3 vision.
# INGEST_VISION_PROVIDER="<chosen-provider>"
# INGEST_VISION_ENDPOINT="https://provider.example.invalid/v1"
# INGEST_VISION_MODEL="<chosen-model>"
# INGEST_VISION_API_KEY="<secret>"
INGEST_VISION_TIMEOUT_SECONDS=60
INGEST_FALLBACK_POLICY="affected-pages-v1"
INGEST_QUALITY_POLICY="bounded-checks-manual-review-v1"
# Preserve existing embedding preprocessing. New Persian normalization requires migration/reindex design.
INGEST_NORMALIZATION_POLICY="unicode-line-endings-v1"
INGEST_CHUNKING_POLICY="paragraph-v1"
INGEST_RENDER_DPI=144
INGEST_MAX_RENDERED_PAGE_PIXELS=20000000
INGEST_MAX_EXTRACTION_ARTIFACT_BYTES=33554432
INGEST_MAX_EXTRACTED_BLOCKS=10000
# Phase 4: select endpoint/model limits explicitly; no character-to-token estimate.
# INGEST_EMBEDDING_LIMITS='{"unit":"tokens","max_input_units":8192,"max_batch_units":300000,"max_batch_inputs":2048,"tokenizer":"tiktoken:cl100k_base"}'
# The example is NOT compatibility approval for an arbitrary endpoint/model.
INGEST_EMBEDDING_SEND_DIMENSIONS=false
INGEST_EMBEDDING_MAX_RESPONSE_BYTES=16777216
+22 -3
View File
@@ -9,7 +9,9 @@ from sqlalchemy.orm import sessionmaker
from app.modules.documents.types import EmbeddingProfile from app.modules.documents.types import EmbeddingProfile
SCHEMA_REVISION = "0001_ingestion_foundation" SCHEMA_REVISION = "0003_extraction_review"
WORKER_REVISION = "0002_worker_artifact"
FOUNDATION_REVISION = "0001_ingestion_foundation"
FOUNDATION_TABLES = ( FOUNDATION_TABLES = (
"organizations", "users", "organization_settings", "documents", "organizations", "users", "organization_settings", "documents",
"ingestion_jobs", "document_chunks", "audit_events", "ingestion_jobs", "document_chunks", "audit_events",
@@ -56,12 +58,29 @@ def session_factory(engine: Engine):
return sessionmaker(engine, expire_on_commit=False) return sessionmaker(engine, expire_on_commit=False)
def check_compatibility(connection: Connection, profile: EmbeddingProfile) -> None: def check_compatibility(connection: Connection, profile: EmbeddingProfile, *, require_worker=False) -> None:
"""Fail closed on schema, dimension or full embedding identity mismatch.""" """Fail closed on schema, dimension or full embedding identity mismatch."""
schema = connection.execute(text("SELECT current_schema()")).scalar_one() schema = connection.execute(text("SELECT current_schema()")).scalar_one()
assert_foundation_scope(connection, schema) assert_foundation_scope(connection, schema)
if connection.execute(text("SELECT version_num FROM alembic_version")).scalar_one() != SCHEMA_REVISION: revision = connection.execute(text("SELECT version_num FROM alembic_version")).scalar_one()
allowed = (SCHEMA_REVISION,) if require_worker else (FOUNDATION_REVISION, WORKER_REVISION, SCHEMA_REVISION)
if revision not in allowed:
raise CompatibilityError("Unexpected ingestion schema revision") raise CompatibilityError("Unexpected ingestion schema revision")
if revision in (WORKER_REVISION, SCHEMA_REVISION):
artifact_type = connection.execute(text("""
SELECT format_type(atttypid,atttypmod) FROM pg_attribute
WHERE attrelid=to_regclass('documents') AND attname='extraction_state' AND NOT attisdropped
""")).scalar_one_or_none()
if artifact_type != "jsonb":
raise CompatibilityError("Missing worker artifact attachment column")
if revision == SCHEMA_REVISION:
definitions = connection.execute(text("""
SELECT pg_get_constraintdef(oid) FROM pg_constraint
WHERE conrelid=to_regclass(\'audit_events\')
AND conname IN (\'audit_events_action_check\',\'audit_events_extraction_review_replay\')
""")).scalars().all()
if len(definitions) != 2 or not all("extraction_review" in d for d in definitions):
raise CompatibilityError("Missing review audit/replay checks")
row = connection.execute(text(""" row = connection.execute(text("""
SELECT format_type(a.atttypid,a.atttypmod) AS vector_type, SELECT format_type(a.atttypid,a.atttypmod) AS vector_type,
col_description(a.attrelid,a.attnum) AS profile col_description(a.attrelid,a.attnum) AS profile
+49 -3
View File
@@ -1,8 +1,8 @@
"""Ports only; concrete intake, embedding and publication arrive in later phases.""" """Provider-neutral ports; publication arrives in a later phase."""
from typing import Mapping, Protocol, Sequence from typing import Mapping, Protocol, Sequence
from uuid import UUID from uuid import UUID
from .types import EmbeddingProfile from .types import EmbeddingProfile, ExtractedBlock, ExtractionEnvelope
class FileStore(Protocol): class FileStore(Protocol):
@@ -12,12 +12,30 @@ class FileStore(Protocol):
def read(self, storage_key: str) -> bytes: ... def read(self, storage_key: str) -> bytes: ...
def inventory(self) -> Mapping[str, Sequence[str]]:
"""Report originals, temporary_files and unexpected_entries; never delete."""
...
def discard_unused(self, storage_key: str) -> None:
"""Delete this request's candidate only after a confirmed unused outcome.
Ambiguous commit outcomes must retain it for report-only reconciliation.
"""
...
class EmbeddingProvider(Protocol): class EmbeddingProvider(Protocol):
@property @property
def profile(self) -> EmbeddingProfile: ... def profile(self) -> EmbeddingProfile: ...
def embed(self, texts: Sequence[str]) -> Sequence[Sequence[float]]: ... @property
def request_policy(self) -> Mapping[str, object]:
"""Secret-free, endpoint-specific frozen request limits and capabilities."""
...
def embed(self, texts: Sequence[str]) -> Sequence[Sequence[float]]:
"""One validated batch, input order restored; no internal retries."""
...
class DocumentRepository(Protocol): class DocumentRepository(Protocol):
@@ -28,3 +46,31 @@ class DocumentRepository(Protocol):
def get_enabled_administrator(self, user_id: UUID) -> Mapping[str, object] | None: def get_enabled_administrator(self, user_id: UUID) -> Mapping[str, object] | None:
"""Resolve scope from a trusted operator's persisted administrator identity.""" """Resolve scope from a trusted operator's persisted administrator identity."""
... ...
class ExtractionProvider(Protocol):
def extract(self, *, document_id: UUID, title: str, original_sha256: str,
content: bytes, mime_type: str, processing_profile: Mapping[str, object]) -> ExtractionEnvelope:
"""Faithful ordered evidence; no native responses escape."""
...
class VisionProvider(Protocol):
def transcribe(self, image: bytes, *, page: int | None, section: str | None,
processing_profile: Mapping[str, object]) -> Sequence[ExtractedBlock]: ...
class IntakeRepository(Protocol):
def lookup(self, settings, administrator_id: UUID, request_id: UUID):
"""Short transaction: embedding compatibility, locked admin, scoped key."""
...
def replay(self, org: UUID, administrator_id: UUID, previous, submitted_hash: str): ...
def create(self, settings, prepared, key: str, administrator_id: UUID, request_id: UUID, expected_org: UUID):
"""Locked admin + scoped uniqueness + atomic document/job/audit; returns after commit."""
...
def status(self, administrator_id: UUID, document_id: UUID): ...
def original_references(self): ...
+120 -12
View File
@@ -1,6 +1,7 @@
"""Explicitly constructed ingestion settings; unrelated to prototype chat credentials.""" """Explicitly constructed ingestion settings; unrelated to prototype chat credentials."""
from dataclasses import asdict from dataclasses import asdict
from pathlib import Path from pathlib import Path
import os
import re import re
from urllib.parse import urlsplit from urllib.parse import urlsplit
@@ -8,6 +9,19 @@ from pydantic import Field, SecretStr, ValidationError, field_validator, model_v
from pydantic_settings import BaseSettings, SettingsConfigDict from pydantic_settings import BaseSettings, SettingsConfigDict
from .types import EmbeddingProfile from .types import EmbeddingProfile
from .operational_limits import validate_duration
from .embeddings import EmbeddingLimits, is_representable_timeout, validate_endpoint_hostname
def canonical_storage_root(value: Path) -> Path:
resolved = str(value.resolve(strict=False))
if os.name == "nt":
# Extended drive/UNC spellings identify the same Windows namespace.
if resolved.startswith("\\\\?\\UNC\\"):
resolved = "\\\\" + resolved[8:]
elif resolved.startswith("\\\\?\\") and len(resolved) > 5 and resolved[5] == ":":
resolved = resolved[4:]
return Path(os.path.normcase(resolved))
class IngestionSettings(BaseSettings): class IngestionSettings(BaseSettings):
@@ -22,9 +36,34 @@ class IngestionSettings(BaseSettings):
embedding_api_key: SecretStr | None = None embedding_api_key: SecretStr | None = None
embedding_preprocessing_version: str = Field(default="v1", min_length=1) embedding_preprocessing_version: str = Field(default="v1", min_length=1)
embedding_timeout_seconds: float = Field(default=60, gt=0, allow_inf_nan=False) embedding_timeout_seconds: float = Field(default=60, gt=0, allow_inf_nan=False)
embedding_limits: EmbeddingLimits | None = None
embedding_send_dimensions: bool = False
embedding_max_response_bytes: int = Field(default=16 * 1024 * 1024, gt=0)
original_directory: Path = Path("data/originals") original_directory: Path = Path("data/originals")
accepted_formats: tuple[str, ...] = (".pdf", ".md") extraction_directory: Path = Path("data/extractions")
accepted_formats: tuple[str, ...] = (".pdf", ".md", ".docx", ".jpg", ".jpeg", ".png")
max_original_bytes: int = Field(default=20 * 1024 * 1024, gt=0) max_original_bytes: int = Field(default=20 * 1024 * 1024, gt=0)
max_docx_entries: int = Field(default=2048, gt=0, le=65534)
max_docx_member_bytes: int = Field(default=16 * 1024 * 1024, gt=0)
max_docx_expanded_bytes: int = Field(default=64 * 1024 * 1024, gt=0)
max_docx_compression_ratio: int = Field(default=200, gt=0)
max_image_width: int = Field(default=12000, gt=0)
max_image_height: int = Field(default=12000, gt=0)
max_image_pixels: int = Field(default=40_000_000, gt=0)
extraction_strategy: str = Field(default="direct-quality-fallback-v1", min_length=1)
vision_provider: str | None = None
vision_endpoint: str | None = None
vision_model: str | None = None
vision_api_key: SecretStr | None = None
vision_timeout_seconds: float = Field(default=60, gt=0, allow_inf_nan=False)
fallback_policy: str = Field(default="affected-pages-v1", min_length=1)
quality_policy: str = Field(default="bounded-checks-manual-review-v1", min_length=1)
normalization_policy: str = Field(default="unicode-line-endings-v1", min_length=1)
chunking_policy: str = Field(default="paragraph-v1", min_length=1)
render_dpi: int = Field(default=144, gt=0, le=600)
max_rendered_page_pixels: int = Field(default=20_000_000, gt=0)
max_extraction_artifact_bytes: int = Field(default=32 * 1024 * 1024, gt=0)
max_extracted_blocks: int = Field(default=10000, gt=0)
max_pdf_pages: int = Field(default=200, gt=0) max_pdf_pages: int = Field(default=200, gt=0)
max_normalized_characters: int = Field(default=1_000_000, gt=0) max_normalized_characters: int = Field(default=1_000_000, gt=0)
max_chunks: int = Field(default=2000, gt=0) max_chunks: int = Field(default=2000, gt=0)
@@ -40,9 +79,16 @@ class IngestionSettings(BaseSettings):
retry_base_seconds: float = Field(default=2, gt=0, allow_inf_nan=False) retry_base_seconds: float = Field(default=2, gt=0, allow_inf_nan=False)
retry_cap_seconds: float = Field(default=300, gt=0, allow_inf_nan=False) retry_cap_seconds: float = Field(default=300, gt=0, allow_inf_nan=False)
@field_validator("poll_seconds", "heartbeat_seconds", "lease_seconds",
"retry_base_seconds", "retry_cap_seconds")
@classmethod
def operational_duration(cls, value):
return validate_duration(value)
@field_validator( @field_validator(
"embedding_model", "embedding_provider", "embedding_model", "embedding_provider",
"embedding_preprocessing_version" "embedding_preprocessing_version", "extraction_strategy", "fallback_policy",
"quality_policy", "normalization_policy", "chunking_policy"
) )
@classmethod @classmethod
def nonblank(cls, value): def nonblank(cls, value):
@@ -52,9 +98,11 @@ class IngestionSettings(BaseSettings):
return value return value
@field_validator("embedding_endpoint", mode="before") @field_validator("embedding_endpoint", "vision_endpoint", mode="before")
@classmethod @classmethod
def supported_endpoint(cls, value): def supported_endpoint(cls, value, info):
if value is None and info.field_name == "vision_endpoint":
return None
message = "Endpoint must be an absolute HTTP(S) host/port/path URL without authentication, query, fragment or encoded components" message = "Endpoint must be an absolute HTTP(S) host/port/path URL without authentication, query, fragment or encoded components"
if not isinstance(value, str) or not value or any( if not isinstance(value, str) or not value or any(
character.isspace() or ord(character) < 32 for character in value character.isspace() or ord(character) < 32 for character in value
@@ -65,17 +113,24 @@ class IngestionSettings(BaseSettings):
if (parsed.scheme not in ("http", "https") or not parsed.hostname if (parsed.scheme not in ("http", "https") or not parsed.hostname
or parsed.username is not None or parsed.password is not None or parsed.username is not None or parsed.password is not None
or parsed.query or parsed.fragment or parsed.port == 0 or parsed.query or parsed.fragment or parsed.port == 0
or (":" in parsed.hostname and not parsed.netloc.startswith("["))
or not validate_endpoint_hostname(parsed.hostname)
or not re.fullmatch(r"/[A-Za-z0-9._~/-]*|", parsed.path)): or not re.fullmatch(r"/[A-Za-z0-9._~/-]*|", parsed.path)):
raise ValueError(message) raise ValueError(message)
if not re.fullmatch(r"[A-Za-z0-9.:-]+", parsed.hostname):
raise ValueError(message)
if parsed.netloc.endswith(":"): if parsed.netloc.endswith(":"):
raise ValueError(message) raise ValueError(message)
except ValueError: except (ValueError, TypeError, UnicodeError, OverflowError):
raise ValueError(message) from None raise ValueError(message) from None
# Preserve scheme, host casing, explicit ports and path identity. # Preserve scheme, host casing, explicit ports and path identity.
return value return value
@field_validator("embedding_timeout_seconds", "vision_timeout_seconds")
@classmethod
def representable_timeout(cls, value):
if not is_representable_timeout(value):
raise ValueError("Timeout must be a finite positive number representable by runtime synchronization and sockets")
return float(value)
@field_validator("database_url") @field_validator("database_url")
@classmethod @classmethod
def postgres_only(cls, value): def postgres_only(cls, value):
@@ -97,12 +152,39 @@ class IngestionSettings(BaseSettings):
@field_validator("accepted_formats") @field_validator("accepted_formats")
@classmethod @classmethod
def supported_formats(cls, value): def supported_formats(cls, value):
if not value or len(set(value)) != len(value) or not set(value) <= {".pdf", ".md"}: if not value or len(set(value)) != len(value) or not set(value) <= {".pdf", ".md", ".docx", ".jpg", ".jpeg", ".png"}:
raise ValueError("Accepted formats must be a nonempty subset of .pdf and .md") raise ValueError("Accepted formats must be a nonempty subset of .pdf, .md, .docx, .jpg, .jpeg and .png")
return value
@field_validator("vision_provider", "vision_model")
@classmethod
def optional_identity(cls, value):
if value is not None:
value = value.strip()
if not value:
raise ValueError("Profile identity cannot be blank")
return value return value
@model_validator(mode="after") @model_validator(mode="after")
def coherent_limits(self): def coherent_limits(self):
roots = None
try:
roots = (canonical_storage_root(self.original_directory),
canonical_storage_root(self.extraction_directory))
except (OSError, RuntimeError, ValueError):
pass
if roots is None:
raise ValueError("Storage roots cannot be canonically resolved")
original, extraction = roots
if original == extraction or original in extraction.parents or extraction in original.parents:
raise ValueError("Original and extraction storage roots must be separate, non-nested namespaces")
if any(v is not None for v in (self.vision_provider, self.vision_endpoint, self.vision_model)) and not all(
v is not None for v in (self.vision_provider, self.vision_endpoint, self.vision_model)
):
raise ValueError("Vision provider, endpoint and model must be configured together")
# Additional search normalization requires a reviewed embedding migration.
if self.normalization_policy != "unicode-line-endings-v1":
raise ValueError("New normalization requires an explicit embedding migration/reindex design")
if self.chunk_overlap_characters >= self.chunk_size_characters: if self.chunk_overlap_characters >= self.chunk_size_characters:
raise ValueError("Chunk overlap must be smaller than chunk size") raise ValueError("Chunk overlap must be smaller than chunk size")
if self.heartbeat_seconds >= self.lease_seconds: if self.heartbeat_seconds >= self.lease_seconds:
@@ -122,12 +204,34 @@ class IngestionSettings(BaseSettings):
def processing_profile(self) -> dict: def processing_profile(self) -> dict:
"""Snapshot settings; retries must use this persisted snapshot, not fresh defaults.""" """Snapshot settings; retries must use this persisted snapshot, not fresh defaults."""
return { return {
"extractor": "pypdf-markdown-v1", "profile_schema": 2,
"normalizer": "unicode-line-endings-v1", "extractor": "page-block-v1",
"chunker": "paragraph-v1", "size_unit": "characters", "extraction": {
"strategy": self.extraction_strategy,
"vision": {"provider": self.vision_provider, "endpoint": self.vision_endpoint,
"model": self.vision_model, "timeout_seconds": self.vision_timeout_seconds},
"fallback_policy": self.fallback_policy, "quality_policy": self.quality_policy,
"render_dpi": self.render_dpi,
"max_rendered_page_pixels": self.max_rendered_page_pixels,
"max_pdf_pages": self.max_pdf_pages,
"max_extracted_blocks": self.max_extracted_blocks,
"max_extraction_artifact_bytes": self.max_extraction_artifact_bytes,
},
"intake": {"accepted_formats": list(self.accepted_formats), **{
name: getattr(self, name) for name in (
"max_docx_entries", "max_docx_member_bytes", "max_docx_expanded_bytes",
"max_docx_compression_ratio", "max_image_width", "max_image_height", "max_image_pixels")}},
"normalizer": self.normalization_policy,
"chunker": self.chunking_policy, "size_unit": "characters",
"chunk_size": self.chunk_size_characters, "chunk_size": self.chunk_size_characters,
"overlap": self.chunk_overlap_characters, "overlap": self.chunk_overlap_characters,
"embedding": asdict(self.embedding_profile), "embedding": asdict(self.embedding_profile),
"embedding_request": {
"limits": self.embedding_limits.model_dump() if self.embedding_limits else None,
"timeout_seconds": self.embedding_timeout_seconds,
"send_dimensions": self.embedding_send_dimensions,
"max_response_bytes": self.embedding_max_response_bytes,
},
"limits": { "limits": {
name: getattr(self, name) for name in ( name: getattr(self, name) for name in (
"max_original_bytes", "max_pdf_pages", "max_original_bytes", "max_pdf_pages",
@@ -137,6 +241,10 @@ class IngestionSettings(BaseSettings):
}, },
} }
def require_vision_credentials(self) -> None:
if self.vision_model is None or self.vision_api_key is None or not self.vision_api_key.get_secret_value().strip():
raise ValueError("Configured vision identity and INGEST_VISION_API_KEY are required for a hosted adapter")
def require_embedding_credentials(self) -> None: def require_embedding_credentials(self) -> None:
if self.embedding_api_key is None or not self.embedding_api_key.get_secret_value().strip(): if self.embedding_api_key is None or not self.embedding_api_key.get_secret_value().strip():
raise ValueError("INGEST_EMBEDDING_API_KEY is required for a hosted adapter") raise ValueError("INGEST_EMBEDDING_API_KEY is required for a hosted adapter")
+106 -11
View File
@@ -1,6 +1,8 @@
"""Provider-neutral ingestion values. Importing this module performs no I/O.""" """Provider-neutral ingestion values. Importing this module performs no I/O."""
from dataclasses import dataclass from dataclasses import dataclass
from typing import Mapping from typing import Literal, Mapping
from pydantic import BaseModel, ConfigDict, Field, model_validator
from uuid import UUID from uuid import UUID
@@ -20,11 +22,74 @@ class EmbeddingProfile:
raise ValueError("Embedding profile requires explicit identity and dimension") raise ValueError("Embedding profile requires explicit identity and dimension")
@dataclass(frozen=True) class ExtractedBlock(BaseModel):
class ExtractedBlock: """Faithful evidence and separately derived search input, in source order."""
text: str model_config = ConfigDict(frozen=True, extra="forbid")
page: int | None = None ordinal: int = Field(ge=0)
block_id: str = Field(min_length=1)
text: str = Field(min_length=1)
search_text: str | None = None
page: int | None = Field(default=None, gt=0)
section: str | None = None section: str | None = None
source_locator: str = Field(min_length=1)
block_type: Literal["paragraph", "heading", "table", "question", "answer", "visual_group", "caption"] = "paragraph"
heading: str | None = None
group_id: str | None = None
parent_block_id: str | None = None
method: Literal["direct_pdf", "docx", "readable_text", "ocr", "vision"]
actual_model: str | None = None
warnings: tuple[str, ...] = ()
@model_validator(mode="after")
def model_provenance(self):
if self.method == "vision" and (self.actual_model is None or not self.actual_model.strip()):
raise ValueError("Vision evidence requires the actual model identity")
return self
class ExtractionReviewAnnotation(BaseModel):
"""Inspection prose is metadata, never a machine extraction-quality flag."""
model_config = ConfigDict(frozen=True, extra="forbid")
evidence_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
locator: str = Field(min_length=1)
reviewer: str = Field(min_length=1, max_length=500)
checked: tuple[str, ...] = Field(max_length=16)
note: str = Field(min_length=1, max_length=2000)
class ExtractionEnvelope(BaseModel):
"""Complete retained extraction; no vectors or provider-native objects."""
model_config = ConfigDict(frozen=True, extra="forbid")
artifact_schema: Literal[1] = 1
document_id: UUID
title: str = Field(min_length=1, max_length=200)
original_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
extraction_profile_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
normalization_policy: str = Field(min_length=1)
complete: Literal[True]
quality_decision: Literal["passed", "reviewed"]
warnings: tuple[str, ...] = ()
review_annotations: tuple[ExtractionReviewAnnotation, ...] = ()
blocks: tuple[ExtractedBlock, ...] = Field(min_length=1)
@model_validator(mode="after")
def ordered_relationships(self):
seen, faq = {}, {}
for ordinal, block in enumerate(self.blocks):
if block.ordinal != ordinal or block.block_id in seen:
raise ValueError("Blocks need unique IDs and contiguous source order")
if block.parent_block_id is not None:
parent = seen.get(block.parent_block_id)
if parent is None or block.group_id is None or parent.group_id != block.group_id:
raise ValueError("Child must reference an earlier parent in its source group")
if block.block_type in ("question", "answer"):
if not block.group_id:
raise ValueError("FAQ blocks require a source group")
faq.setdefault(block.group_id, set()).add(block.block_type)
seen[block.block_id] = block
if any(roles != {"question", "answer"} for roles in faq.values()):
raise ValueError("FAQ groups must retain question and answer together")
return self
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -36,10 +101,40 @@ class ChunkDraft:
token_count: int | None = None token_count: int | None = None
@dataclass(frozen=True)
class StagedDocument: class StagedDocument:
document_id: UUID """Complete owned payload, valid only inside stage_document's context."""
processing_profile: Mapping[str, object] def __init__(self, document_id, processing_profile, chunks, vectors, embedding_profile, payload_bytes):
chunks: tuple[ChunkDraft, ...] self.document_id = document_id
vectors: tuple[tuple[float, ...], ...] self.embedding_profile = embedding_profile
embedding_profile: EmbeddingProfile self.payload_bytes = payload_bytes
self._profile = processing_profile
self._chunks = chunks
self._vectors = vectors
self.closed = False
def _require_open(self):
if self.closed:
raise ValueError("Staged document has been released")
@property
def processing_profile(self):
from copy import deepcopy
self._require_open()
return deepcopy(self._profile)
@property
def chunks(self):
self._require_open()
return self._chunks
@property
def vectors(self):
self._require_open()
# Read-only views of packed float32 storage, one per ordinal.
return tuple(memoryview(vector).cast("f") for vector in self._vectors)
def close(self):
self._profile = None
self._chunks = ()
self._vectors = ()
self.closed = True
+2
View File
@@ -9,10 +9,12 @@ requires-python = ">=3.11"
dependencies = [ dependencies = [
"SQLAlchemy>=2.0.36,<2.1", "psycopg[binary]>=3.2.3,<4", "SQLAlchemy>=2.0.36,<2.1", "psycopg[binary]>=3.2.3,<4",
"alembic>=1.14,<2", "pgvector>=0.3.6,<1", "alembic>=1.14,<2", "pgvector>=0.3.6,<1",
"PyMuPDF>=1.26,<2", "Pillow>=12.2,<13", "defusedxml>=0.7.1,<1",
"pydantic-settings>=2.7,<3", "argon2-cffi>=23.1,<26", "pydantic-settings>=2.7,<3", "argon2-cffi>=23.1,<26",
] ]
[project.optional-dependencies] [project.optional-dependencies]
embedding = ["tiktoken>=0.8,<1"]
test = ["pytest>=8.3,<10"] test = ["pytest>=8.3,<10"]
prototype = [ prototype = [
"fastapi>=0.115,<1", "uvicorn>=0.34,<1", "langgraph>=1,<2", "fastapi>=0.115,<1", "uvicorn>=0.34,<1", "langgraph>=1,<2",