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
+120 -12
View File
@@ -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")