feat(ingestion): add opt-in best-effort document admission

Freeze temporary partial-extraction admission in new uploads. Bypass manual approval, retain recognition warnings, and accept ambiguous legal references during bounded chunking. Preserve strict defaults, immutable evidence and atomic publication. Expose effective policy and safe failure categories with regression coverage.
This commit is contained in:
amirhosein mazaheri
2026-10-13 14:09:21 +03:30
parent 18e595ac93
commit 90a164f5a6
18 changed files with 301 additions and 31 deletions
+5 -3
View File
@@ -4,7 +4,7 @@ import re
import unicodedata
from .extraction import ExtractionError, RULE, PLACEHOLDER, HEADING
from .extraction_artifacts import validate_artifact, serialize_artifact
from .extraction_artifacts import validate_artifact, serialize_artifact, allow_partial_extraction
from .normalization import normalize_search_text
from .types import ChunkDraft
@@ -348,7 +348,9 @@ def chunk_extraction(envelope, processing_profile, *, corpus_purpose="source_doc
if any(PLACEHOLDER.search(b.text) for b in blocks):
raise ExtractionError("Placeholder is not authoritative knowledge")
chunks = []
for group, blocks, atomic in associate_dependencies(units):
# Temporary admission keeps source order without rejecting ambiguous legal references.
associated = units if allow_partial_extraction(profile) else associate_dependencies(units)
for group, blocks, atomic in associated:
parts = []
for index, block in enumerate(blocks):
if (index and not blocks[index - 1].text.endswith(("\n", "\r"))
@@ -370,7 +372,7 @@ def chunk_extraction(envelope, processing_profile, *, corpus_purpose="source_doc
r"تبصره|استثنا|مگر|مشروط|به\s+شرط|نمی|نباید|نیست|"
r"\b(?:except|unless|provided|condition|not|exclusion|note)\b", text, re.I))
normalized = normalize_search_text(text, profile["normalizer"])
if protected and len(normalized) > size:
if protected and len(normalized) > size and not allow_partial_extraction(profile):
raise ExtractionError("Semantic group exceeds chunk bound; cannot separate required context")
if len(normalized) <= size:
chunks.append(ChunkDraft(len(chunks), text, page, section))
+23 -7
View File
@@ -11,7 +11,7 @@ import unicodedata
from uuid import UUID
from zipfile import ZipFile
from .extraction_artifacts import extraction_profile_digest, validate_artifact, bounded_json_bytes, bounded_json_size, serialize_artifact, ocr_review_required
from .extraction_artifacts import extraction_profile_digest, validate_artifact, bounded_json_bytes, bounded_json_size, serialize_artifact, ocr_review_required, allow_partial_extraction
from .formats import DOCX_MIME, validate_docx, validate_image
from .normalization import normalize_search_text, normalized_inputs
from .types import ExtractedBlock, ExtractionEnvelope, ExtractionReviewAnnotation
@@ -22,6 +22,18 @@ class ExtractionError(ValueError):
code = "EXTRACTION_QUALITY_FAILED"
retryable = False
def __init__(self, message):
super().__init__(message)
# Only fixed categories enter logs; never exception/provider payload text.
self.reason_code = {
"Invalid vision transcription response": "invalid_vision_schema",
"Vision reports unreadable source regions": "unreadable_vision_regions",
"Vision evidence identity, location or readability mismatch": "invalid_vision_evidence",
"Vision transcription incomplete or blocked": "incomplete_or_blocked_vision",
"Vision transcription has no candidate blocks": "empty_vision_output",
"Vision returned no complete transcription": "empty_vision_output",
}.get(message, "extraction_validation")
class ExtractionProviderError(ExtractionError):
code = "EXTRACTION_PROVIDER_FAILED"
@@ -169,6 +181,8 @@ class PageBlockExtractor:
def _review(self, blocks, image, locator, reasons):
self._budget(blocks)
if allow_partial_extraction(self.profile):
return [b.model_copy(update={"warnings": b.warnings + ("Automatic admission; manual visual inspection bypassed",)}) for b in blocks]
digest = review_digest(original_sha256=self.original_hash,
profile_digest=self.profile_digest, locator=locator,
image=image, blocks=blocks)
@@ -263,7 +277,7 @@ class PageBlockExtractor:
raise ExtractionError("Unsupported extraction MIME")
if not blocks or len(blocks) > extraction["max_extracted_blocks"]:
raise ExtractionError("Empty extraction or block limit exceeded")
if any(unreadable(b.text) for b in blocks):
if any(unreadable(b.text) and not (allow_partial_extraction(profile) and any(c.isalnum() for c in b.text)) for b in blocks):
raise ExtractionError("Unreadable extracted evidence")
faq_groups = {b.group_id for b in blocks if b.block_type in ("question", "answer")}
if any(PLACEHOLDER.search(b.text) and not (self.factual_retention and b.group_id
@@ -275,7 +289,7 @@ class PageBlockExtractor:
envelope = ExtractionEnvelope(document_id=document_id, title=title, original_sha256=original_hash,
extraction_profile_sha256=self.profile_digest, normalization_policy=profile["normalizer"],
complete=True, quality_decision=("partially_reviewed" if self.reviewed and self.automatic_ocr
else "reviewed" if self.reviewed else "passed"),
else "reviewed" if self.reviewed else "accepted_with_warnings" if allow_partial_extraction(profile) and any(b.warnings for b in blocks) else "passed"),
review_annotations=tuple(self.annotations), blocks=blocks)
normalized_inputs(envelope, profile)
payload = serialize_artifact(envelope, profile)
@@ -549,8 +563,8 @@ class PageBlockExtractor:
planned_blocks += len(paragraphs) if labelled > 1 else 1
cell_paragraphs.append(paragraphs)
texts.append("".join(paragraphs))
labels = [t.strip().rstrip("::").lower() for t in texts]
if labels in (["سؤال", "پاسخ"], ["سوال", "پاسخ"], ["question", "answer"]):
labels = [t.strip().rstrip(":أ¯آ¼ع‘").lower() for t in texts]
if labels in (["ط·آ³ط·آ¤ط·آ§ط¸â€‍", "ط¸آ¾ط·آ§ط·آ³ط·آ®"], ["ط·آ³ط¸ث†ط·آ§ط¸â€‍", "ط¸آ¾ط·آ§ط·آ³ط·آ®"], ["question", "answer"]):
header_columns = True
for col, value in enumerate(texts, 1):
result.append(self._block(value, f"docx/table/{table_index}/row/{row_index}/cell/{col}",
@@ -819,20 +833,22 @@ class PageBlockExtractor:
if len(response) > self.profile["extraction"]["max_extracted_blocks"]:
raise ExtractionError("Vision block limit exceeded")
blocks = list(response)
if allow_partial_extraction(self.profile):
blocks = [b.model_copy(update={"warnings": b.warnings + (("Unrecognized characters retained",) if unreadable(b.text) else ())}) for b in blocks]
self._budget(blocks)
if not blocks:
raise ExtractionError("Vision returned no complete transcription")
for index, b in enumerate(blocks):
if (b.ordinal != index or b.method not in ("vision", "ocr") or b.actual_model != identity["model"]
or b.page != page or not b.source_locator.startswith(locator + "/")
or unreadable(b.text)):
or (unreadable(b.text) and not (allow_partial_extraction(self.profile) and any(c.isalnum() for c in b.text)))):
raise ExtractionError("Vision evidence identity, location or readability mismatch")
# Validate local source relationships before manually attesting to the result.
ExtractionEnvelope(document_id=UUID(int=0), title="validation", original_sha256=self.original_hash,
extraction_profile_sha256=self.profile_digest, normalization_policy=self.profile["normalizer"],
complete=True, quality_decision="passed",
blocks=tuple(blocks))
if not ocr_review_required(self.profile) and not any(b.warnings for b in blocks):
if allow_partial_extraction(self.profile) or (not ocr_review_required(self.profile) and not any(b.warnings for b in blocks)):
self.automatic_ocr = True
return blocks
return self._review(blocks, image, locator, reasons + ("Vision completeness and critical fields inspected",))
@@ -27,6 +27,14 @@ def factual_review_required(profile: Mapping) -> bool:
return value
def allow_partial_extraction(profile: Mapping) -> bool:
"""Explicit temporary admission policy; existing snapshots remain strict."""
value = profile.get("extraction", {}).get("allow_partial_extraction", False)
if type(value) is not bool:
raise ValueError("Invalid frozen partial extraction policy")
return value
def processing_profile_kind(profile: Mapping) -> str:
if "profile_schema" not in profile and profile.get("extractor") == "pypdf-markdown-v1":
return "legacy-v1"
@@ -38,6 +46,7 @@ def processing_profile_kind(profile: Mapping) -> str:
def extraction_profile_digest(profile: Mapping) -> str:
ocr_review_required(profile)
factual_review_required(profile)
allow_partial_extraction(profile)
if processing_profile_kind(profile) == "legacy-v1":
raise LegacyProcessingProfile("Legacy extractor requires explicit legacy dispatch; OCR reinterpretation is forbidden")
# Faithful extraction is reusable across chunk/embedding/normalization changes.
+2 -2
View File
@@ -10,7 +10,7 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
from .chunking import chunk_extraction, factual_context_units
from .embeddings import validate_database_string
from .extraction import ExtractionError, PLACEHOLDER, REVIEW_CHECKS
from .extraction_artifacts import factual_review_required
from .extraction_artifacts import factual_review_required, allow_partial_extraction
FACTUAL_CHECKS = ("factual_authority", "whole_pair_association", "behavioral_separation", "placeholders")
@@ -106,7 +106,7 @@ def prepare_chunks(envelope, processing_profile, state, artifact_sha256):
"""One boundary for worker staging and publication; faithful artifact stays whole."""
if not factual_groups(envelope):
return chunk_extraction(envelope, processing_profile)
if not factual_review_required(processing_profile) and state.get("factual_inclusion") is None:
if (allow_partial_extraction(processing_profile) or not factual_review_required(processing_profile)) and state.get("factual_inclusion") is None:
groups = factual_groups(envelope)
included = {group for group, blocks, _ in factual_context_units(envelope.blocks)
if not any(PLACEHOLDER.search(b.text) for b in blocks) and group in groups}
+2
View File
@@ -60,6 +60,7 @@ class IngestionSettings(BaseSettings):
quality_policy: str = Field(default="bounded-checks-manual-review-v1", min_length=1)
ocr_review_required: bool = True
factual_review_required: bool = True
allow_partial_extraction: bool = False
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)
@@ -215,6 +216,7 @@ class IngestionSettings(BaseSettings):
"fallback_policy": self.fallback_policy, "quality_policy": self.quality_policy,
"ocr_review_required": self.ocr_review_required,
"factual_review_required": self.factual_review_required,
"allow_partial_extraction": self.allow_partial_extraction,
"render_dpi": self.render_dpi,
"max_rendered_page_pixels": self.max_rendered_page_pixels,
"max_pdf_pages": self.max_pdf_pages,
+1 -1
View File
@@ -67,7 +67,7 @@ class ExtractionEnvelope(BaseModel):
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", "partially_reviewed"]
quality_decision: Literal["passed", "reviewed", "partially_reviewed", "accepted_with_warnings"]
warnings: tuple[str, ...] = ()
review_annotations: tuple[ExtractionReviewAnnotation, ...] = ()
blocks: tuple[ExtractedBlock, ...] = Field(min_length=1)
+15 -9
View File
@@ -10,7 +10,7 @@ from threading import Event, Thread
from .chunking import chunk_extraction
from .embeddings import EmbeddingError, stage_document
from .extraction import ExtractionError, ReviewRequired
from .extraction_artifacts import extraction_profile_digest, ocr_review_required
from .extraction_artifacts import extraction_profile_digest, ocr_review_required, allow_partial_extraction
from .review import FactualReviewRequired, prepare_chunks
from .operational_limits import validate_worker_durations
@@ -18,10 +18,13 @@ from .operational_limits import validate_worker_durations
logger = logging.getLogger(__name__)
def report(claim, stage, category):
def report(claim, stage, category, *, reason=None):
"""Only internal categories and durable IDs; never exception/provider text."""
logger.info(json.dumps(dict(document_id=str(claim.document.get("id")),
job_id=str(claim.job_id), stage=stage, category=category)))
event = dict(document_id=str(claim.document.get("id")),
job_id=str(claim.job_id), stage=stage, category=category)
if reason is not None:
event["reason"] = reason
logger.info(json.dumps(event))
class LostClaim(RuntimeError):
@@ -62,14 +65,17 @@ def validate_source(envelope, document, content):
"""Coverage checks independent of chunking and embedding settings."""
if envelope.title != document["title"]:
raise ExtractionError("Extraction title differs from immutable source")
partial = allow_partial_extraction(document["processing_profile"])
if envelope.quality_decision == "accepted_with_warnings" and not partial:
raise ExtractionError("Partial admission requires the frozen opt-in policy")
warnings = (*envelope.warnings, *(w for b in envelope.blocks for w in b.warnings))
from .extraction import unreadable, PLACEHOLDER
from .review import factual_groups
groups = factual_groups(envelope)
if any(unreadable(b.text) or (PLACEHOLDER.search(b.text) and b.group_id not in groups)
if any((unreadable(b.text) and not (partial and any(c.isalnum() for c in b.text))) or (PLACEHOLDER.search(b.text) and b.group_id not in groups)
for b in envelope.blocks):
raise ExtractionError("Unreadable or placeholder extracted evidence")
if warnings and envelope.quality_decision not in ("reviewed", "partially_reviewed"):
if warnings and not partial and envelope.quality_decision not in ("reviewed", "partially_reviewed"):
raise ExtractionError("Unreviewed extraction warnings")
mime = document["mime_type"]
if envelope.quality_decision == "partially_reviewed":
@@ -89,10 +95,10 @@ def validate_source(envelope, document, content):
if (source.page_count > document["processing_profile"]["extraction"]["max_pdf_pages"]
or {b.page for b in envelope.blocks} != set(range(1, source.page_count + 1))):
raise ExtractionError("Incomplete PDF source coverage")
if envelope.quality_decision not in ("reviewed", "partially_reviewed") and not automatic_ocr:
if envelope.quality_decision not in ("reviewed", "partially_reviewed") and not automatic_ocr and not partial:
raise ExtractionError("PDF extraction requires inspection")
elif mime in ("image/jpeg", "image/png"):
if (envelope.quality_decision != "reviewed" and not automatic_ocr) or any(
if (envelope.quality_decision != "reviewed" and not automatic_ocr and not partial) or any(
b.page is not None or b.method not in ("vision", "ocr") for b in envelope.blocks):
raise ExtractionError("Image extraction requires inspected complete evidence")
elif mime in ("text/markdown", "text/plain",
@@ -250,7 +256,7 @@ class Worker:
category = ("embedding_error" if isinstance(exc, EmbeddingError)
else "extraction_error" if isinstance(exc, ExtractionError)
else "storage_error" if isinstance(exc, OSError) else "validation_error")
report(claim, stage, category)
report(claim, stage, category, reason=getattr(exc, "reason_code", None))
except LostClaim:
report(claim, stage, "ownership_lost")
except Exception: