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
+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",))