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:
@@ -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 uuid import UUID
|
||||
|
||||
from .types import EmbeddingProfile
|
||||
from .types import EmbeddingProfile, ExtractedBlock, ExtractionEnvelope
|
||||
|
||||
|
||||
class FileStore(Protocol):
|
||||
@@ -12,12 +12,30 @@ class FileStore(Protocol):
|
||||
|
||||
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):
|
||||
@property
|
||||
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):
|
||||
@@ -28,3 +46,31 @@ class DocumentRepository(Protocol):
|
||||
def get_enabled_administrator(self, user_id: UUID) -> Mapping[str, object] | None:
|
||||
"""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): ...
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Explicitly constructed ingestion settings; unrelated to prototype chat credentials."""
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
import os
|
||||
import re
|
||||
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 .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):
|
||||
@@ -22,9 +36,34 @@ class IngestionSettings(BaseSettings):
|
||||
embedding_api_key: SecretStr | None = None
|
||||
embedding_preprocessing_version: str = Field(default="v1", min_length=1)
|
||||
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")
|
||||
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_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_normalized_characters: int = Field(default=1_000_000, 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_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(
|
||||
"embedding_model", "embedding_provider",
|
||||
"embedding_preprocessing_version"
|
||||
"embedding_preprocessing_version", "extraction_strategy", "fallback_policy",
|
||||
"quality_policy", "normalization_policy", "chunking_policy"
|
||||
)
|
||||
@classmethod
|
||||
def nonblank(cls, value):
|
||||
@@ -52,9 +98,11 @@ class IngestionSettings(BaseSettings):
|
||||
return value
|
||||
|
||||
|
||||
@field_validator("embedding_endpoint", mode="before")
|
||||
@field_validator("embedding_endpoint", "vision_endpoint", mode="before")
|
||||
@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"
|
||||
if not isinstance(value, str) or not value or any(
|
||||
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
|
||||
or parsed.username is not None or parsed.password is not None
|
||||
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)):
|
||||
raise ValueError(message)
|
||||
if not re.fullmatch(r"[A-Za-z0-9.:-]+", parsed.hostname):
|
||||
raise ValueError(message)
|
||||
if parsed.netloc.endswith(":"):
|
||||
raise ValueError(message)
|
||||
except ValueError:
|
||||
except (ValueError, TypeError, UnicodeError, OverflowError):
|
||||
raise ValueError(message) from None
|
||||
# Preserve scheme, host casing, explicit ports and path identity.
|
||||
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")
|
||||
@classmethod
|
||||
def postgres_only(cls, value):
|
||||
@@ -97,12 +152,39 @@ class IngestionSettings(BaseSettings):
|
||||
@field_validator("accepted_formats")
|
||||
@classmethod
|
||||
def supported_formats(cls, value):
|
||||
if not value or len(set(value)) != len(value) or not set(value) <= {".pdf", ".md"}:
|
||||
raise ValueError("Accepted formats must be a nonempty subset of .pdf and .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, .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
|
||||
|
||||
@model_validator(mode="after")
|
||||
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:
|
||||
raise ValueError("Chunk overlap must be smaller than chunk size")
|
||||
if self.heartbeat_seconds >= self.lease_seconds:
|
||||
@@ -122,12 +204,34 @@ class IngestionSettings(BaseSettings):
|
||||
def processing_profile(self) -> dict:
|
||||
"""Snapshot settings; retries must use this persisted snapshot, not fresh defaults."""
|
||||
return {
|
||||
"extractor": "pypdf-markdown-v1",
|
||||
"normalizer": "unicode-line-endings-v1",
|
||||
"chunker": "paragraph-v1", "size_unit": "characters",
|
||||
"profile_schema": 2,
|
||||
"extractor": "page-block-v1",
|
||||
"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,
|
||||
"overlap": self.chunk_overlap_characters,
|
||||
"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": {
|
||||
name: getattr(self, name) for name in (
|
||||
"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:
|
||||
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")
|
||||
|
||||
+106
-11
@@ -1,6 +1,8 @@
|
||||
"""Provider-neutral ingestion values. Importing this module performs no I/O."""
|
||||
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
|
||||
|
||||
|
||||
@@ -20,11 +22,74 @@ class EmbeddingProfile:
|
||||
raise ValueError("Embedding profile requires explicit identity and dimension")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExtractedBlock:
|
||||
text: str
|
||||
page: int | None = None
|
||||
class ExtractedBlock(BaseModel):
|
||||
"""Faithful evidence and separately derived search input, in source order."""
|
||||
model_config = ConfigDict(frozen=True, extra="forbid")
|
||||
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
|
||||
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)
|
||||
@@ -36,10 +101,40 @@ class ChunkDraft:
|
||||
token_count: int | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StagedDocument:
|
||||
document_id: UUID
|
||||
processing_profile: Mapping[str, object]
|
||||
chunks: tuple[ChunkDraft, ...]
|
||||
vectors: tuple[tuple[float, ...], ...]
|
||||
embedding_profile: EmbeddingProfile
|
||||
"""Complete owned payload, valid only inside stage_document's context."""
|
||||
def __init__(self, document_id, processing_profile, chunks, vectors, embedding_profile, payload_bytes):
|
||||
self.document_id = document_id
|
||||
self.embedding_profile = embedding_profile
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user