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
+3
View File
@@ -132,6 +132,9 @@ LIVE_DIAGNOSTIC_TRACE_ENABLED=0
# Sessions expose calibration_status=uncalibrated. Production default remains false.
VOICE_TRANSPORT_TESTING=false
# Temporary best-effort admission: bypass all manual approval and retain recognition warnings.
# New uploads only; existing snapshots remain unchanged.
INGEST_ALLOW_PARTIAL_EXTRACTION=false
# OCR supervisor gate for NEW jobs only; false admits only automatically validated OCR.
# Existing/legacy jobs keep their frozen policy. Factual/non-OCR review remains required.
INGEST_OCR_REVIEW_REQUIRED=true
+3 -2
View File
@@ -109,8 +109,9 @@ def configuration(user=Depends(get_current_user), engine=Depends(get_engine),
calibration_status=calibration_status, voice_transport_testing=voice.voice_transport_testing,
supported_upload_types=list(dict.fromkeys(mime_types[e] for e in ingest.accepted_formats)),
max_upload_bytes=ingest.max_original_bytes, max_pdf_pages=ingest.max_pdf_pages,
ocr_review_required=ingest.ocr_review_required,
factual_review_required=ingest.factual_review_required,
ocr_review_required=ingest.ocr_review_required and not ingest.allow_partial_extraction,
allow_partial_extraction=ingest.allow_partial_extraction,
factual_review_required=ingest.factual_review_required and not ingest.allow_partial_extraction,
supported_structure_notes='Readable Markdown and supported DOCX structures; bounded PDF/image extraction. Factual Q&A requires separate approval.',
input_sample_rate=24000, output_sample_rate=24000, channels=1, audio_encoding='pcm16le',
max_binary_message_bytes=limits.max_binary_message_bytes,
+4 -3
View File
@@ -9,7 +9,7 @@ from app.infrastructure.intake_repository import administrator, document_status
from app.infrastructure.worker_repository import SqlWorkerRepository
from app.modules.documents.errors import IntakeError
from app.modules.documents.review import pending_review, reviews_approved
from app.modules.documents.extraction_artifacts import ocr_review_required, factual_review_required
from app.modules.documents.extraction_artifacts import ocr_review_required, factual_review_required, allow_partial_extraction
def encode_cursor(document):
@@ -56,8 +56,9 @@ class DocumentQueries:
created_at=row['created_at'], chunk_count=row['chunk_count'],
review_required=pending_review(state), review_state=review_state,
extraction_quality_decision=quality,
ocr_review_required=ocr_review_required(row['processing_profile']),
factual_review_required=factual_review_required(row['processing_profile']),
ocr_review_required=ocr_review_required(row['processing_profile']) and not allow_partial_extraction(row['processing_profile']),
allow_partial_extraction=allow_partial_extraction(row['processing_profile']),
factual_review_required=factual_review_required(row['processing_profile']) and not allow_partial_extraction(row['processing_profile']),
job=dict(id=job['id'], status=job['status'], stage=job['stage'],
attempt_count=job['attempt_count'], retry_generation=job['retry_generation'],
can_retry=can_retry, error=(dict(code=job['error_code'],
+4 -1
View File
@@ -13,6 +13,7 @@ from urllib.error import HTTPError, URLError
from pydantic import BaseModel, ConfigDict
from app.modules.documents.extraction import ExtractionError, ExtractionProviderError, unreadable
from app.modules.documents.normalization import normalize_search_text
from app.modules.documents.extraction_artifacts import allow_partial_extraction
from app.modules.documents.types import ExtractedBlock
@@ -174,7 +175,7 @@ class GeminiVision:
if (block.ordinal != index or block.method != "vision" or block.actual_model != self.model or block.page != page
or not block.source_locator.startswith(section + "/")):
raise ExtractionError("Vision returned incompatible evidence provenance")
if unreadable(block.text):
if unreadable(block.text) and not (allow_partial_extraction(processing_profile) and any(c.isalnum() for c in block.text)):
raise ExtractionError("Vision reports unreadable source regions")
blocks.append(block.model_copy(update={"search_text":
normalize_search_text(block.text, processing_profile["normalizer"])}))
@@ -182,6 +183,8 @@ class GeminiVision:
warnings = transcript.warnings + (() if transcript.complete else ("Vision recognition incomplete; completeness review required",))
if warnings:
blocks = [b.model_copy(update={"warnings": b.warnings + warnings}) for b in blocks]
if allow_partial_extraction(processing_profile):
blocks = [b.model_copy(update={"warnings": b.warnings + (("Unrecognized characters retained",) if unreadable(b.text) else ())}) for b in blocks]
return tuple(blocks)
except (KeyError, TypeError, ValueError, AttributeError) as exc:
if isinstance(exc, ExtractionError):
+4 -1
View File
@@ -13,6 +13,7 @@ from urllib.error import HTTPError, URLError
from pydantic import BaseModel, ConfigDict
from app.modules.documents.extraction import ExtractionError, ExtractionProviderError, unreadable
from app.modules.documents.normalization import normalize_search_text
from app.modules.documents.extraction_artifacts import allow_partial_extraction
from app.modules.documents.types import ExtractedBlock
from app.infrastructure.gemini_vision import Transcription, INSTRUCTION, _TRANSPORT_CAPACITY
@@ -177,7 +178,7 @@ class OpenRouterVision:
blocks = []
for index, block in enumerate(transcript.blocks):
locator = block.source_locator if block.source_locator and block.source_locator.startswith(section + "/") else f"{section}/block/{index + 1}"
if unreadable(block.text):
if unreadable(block.text) and not (allow_partial_extraction(processing_profile) and any(c.isalnum() for c in block.text)):
raise ExtractionError("Vision reports unreadable source regions")
blocks.append(block.model_copy(update={
"ordinal": index,
@@ -191,6 +192,8 @@ class OpenRouterVision:
warnings = transcript.warnings + (() if transcript.complete else ("Vision recognition incomplete; completeness review required",))
if warnings:
blocks = [b.model_copy(update={"warnings": b.warnings + warnings}) for b in blocks]
if allow_partial_extraction(processing_profile):
blocks = [b.model_copy(update={"warnings": b.warnings + (("Unrecognized characters retained",) if unreadable(b.text) else ())}) for b in blocks]
return tuple(blocks)
except (KeyError, TypeError, ValueError, AttributeError) as exc:
if isinstance(exc, ExtractionError):
+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:
+37
View File
@@ -2241,3 +2241,40 @@ identical later search args coalesce, different queries discard the old topic.
See API/implementation retained-search amendment and
`tests/unit/test_voice_retained_search.py` plus PostgreSQL runtime cases in
`tests/integration/test_voice_evidence_reuse.py`. No persistence migration.
## Temporary best-effort ingestion admission (2026-10-13)
User-authorized `INGEST_ALLOW_PARTIAL_EXTRACTION=true` is frozen in NEW upload
profiles as `extraction.allow_partial_extraction`. Default false and missing
legacy fields retain strict admission; existing profiles/digests are not rewritten.
This temporary mode bypasses PDF visual, OCR and factual manual approval without
fabricating reviewer identities or annotations. Usable recognition with incomplete
regions, warnings or unknown glyphs proceeds to chunking/embedding. Warnings remain
in the retained artifact; `extraction_quality_decision=accepted_with_warnings`
identifies unreviewed admission. Artifact `complete=true` denotes completion of
the extraction attempt, not a claim of perfect recognition. No measured 90%
accuracy threshold is available. Empty/unusable output, malformed provider JSON,
identity/checksum mismatch, invalid relationships and resource bounds remain
errors. Publication remains atomic, ready and inactive until selection.
F01 capabilities add `allow_partial_extraction` and report effective review gates.
Failed existing documents require a new upload to use this new frozen policy.
Regression source: `tests/unit/test_partial_extraction.py`.
Best-effort admission verification: 196 focused provider-free checks passed;
7 isolated PostgreSQL upload/polling/configuration checks passed, zero skips.
Both Gemini and OpenRouter incomplete/warning response fixtures are covered.
API and worker rebuilt; local INGEST_ALLOW_PARTIAL_EXTRACTION=true confirmed
and /health/ready reports ingestion available. Actual failed photo re-upload
has not been run; prior failed snapshots remain strict. Worker failure logs
now include fixed extraction reason categories without provider response text.
Best-effort chunking follow-up (2026-10-13): the retained 89-block PDF
34930b1a-b341-46c1-adca-67d247d579e2 failed at chunking, not extraction,
with Unsupported governing-rule identifier. In the explicit partial-admission
mode, source-document units bypass strict legal-reference association and large
protected units may split with the existing overlap and character/chunk limits.
Source order, text and locations are preserved; strict mode remains unchanged.
This mode does not guarantee complete legal context within each chunk.
117 focused regression checks passed, including malformed legal identifiers
and bounded splitting.
@@ -837,3 +837,22 @@ status does not declare cancellation of the separately retained backend search.
Gemini continues to use its native interruption transport. New reservations use
`evidence_policy_revision=same-session-evidence-retained-v5`; existing pins are
not rewritten. No schema/table migration or new public endpoint is introduced.
## Temporary best-effort ingestion admission (2026-10-13)
User-authorized `INGEST_ALLOW_PARTIAL_EXTRACTION=true` is frozen in NEW upload
profiles as `extraction.allow_partial_extraction`. Default false and missing
legacy fields retain strict admission; existing profiles/digests are not rewritten.
This temporary mode bypasses PDF visual, OCR and factual manual approval without
fabricating reviewer identities or annotations. Usable recognition with incomplete
regions, warnings or unknown glyphs proceeds to chunking/embedding. Warnings remain
in the retained artifact; `extraction_quality_decision=accepted_with_warnings`
identifies unreviewed admission. Artifact `complete=true` denotes completion of
the extraction attempt, not a claim of perfect recognition. No measured 90%
accuracy threshold is available. Empty/unusable output, malformed provider JSON,
identity/checksum mismatch, invalid relationships and resource bounds remain
errors. Publication remains atomic, ready and inactive until selection.
F01 capabilities add `allow_partial_extraction` and report effective review gates.
Failed existing documents require a new upload to use this new frozen policy.
Regression source: `tests/unit/test_partial_extraction.py`.
@@ -470,3 +470,32 @@ status does not declare cancellation of the separately retained backend search.
Gemini continues to use its native interruption transport. New reservations use
`evidence_policy_revision=same-session-evidence-retained-v5`; existing pins are
not rewritten. No schema/table migration or new public endpoint is introduced.
## Temporary best-effort ingestion admission (2026-10-13)
User-authorized `INGEST_ALLOW_PARTIAL_EXTRACTION=true` is frozen in NEW upload
profiles as `extraction.allow_partial_extraction`. Default false and missing
legacy fields retain strict admission; existing profiles/digests are not rewritten.
This temporary mode bypasses PDF visual, OCR and factual manual approval without
fabricating reviewer identities or annotations. Usable recognition with incomplete
regions, warnings or unknown glyphs proceeds to chunking/embedding. Warnings remain
in the retained artifact; `extraction_quality_decision=accepted_with_warnings`
identifies unreviewed admission. Artifact `complete=true` denotes completion of
the extraction attempt, not a claim of perfect recognition. No measured 90%
accuracy threshold is available. Empty/unusable output, malformed provider JSON,
identity/checksum mismatch, invalid relationships and resource bounds remain
errors. Publication remains atomic, ready and inactive until selection.
F01 capabilities add `allow_partial_extraction` and report effective review gates.
Failed existing documents require a new upload to use this new frozen policy.
Regression source: `tests/unit/test_partial_extraction.py`.
Best-effort chunking follow-up (2026-10-13): the retained 89-block PDF
34930b1a-b341-46c1-adca-67d247d579e2 failed at chunking, not extraction,
with Unsupported governing-rule identifier. In the explicit partial-admission
mode, source-document units bypass strict legal-reference association and large
protected units may split with the existing overlap and character/chunk limits.
Source order, text and locations are preserved; strict mode remains unchanged.
This mode does not guarantee complete legal context within each chunk.
117 focused regression checks passed, including malformed legal identifiers
and bounded splitting.
@@ -138,3 +138,34 @@ def test_configuration_reports_testing_availability_without_claiming_calibration
# A malformed embedding request policy still prevents configured availability.
e.settings=e.settings.model_copy(update={'embedding_limits':None})
assert not client.get('/api/v1/configuration').json()['capabilities']['voice']
@pytest.mark.parametrize('kind', ['image', 'direct_pdf', 'factual'])
def test_best_effort_upload_publishes_without_manual_approval(document_api, kind):
from tests.support.extraction import pdf_bytes
client, _, _, e = document_api
headers = login(client, e)
e.settings = e.settings.model_copy(update={'allow_partial_extraction': True,
'vision_provider': 'gemini', 'vision_endpoint': 'https://test.invalid',
'vision_model': 'fixture-flash'})
if kind == 'image':
content, name = image_bytes('PNG'), 'best-effort.png'
elif kind == 'direct_pdf':
content, name = pdf_bytes([[('text', 'Article 1: fee is 5%', 10, 20)]]), 'best-effort.pdf'
else:
content, name = b'Question: fee?\nAnswer: 5%\n', 'best-effort.md'
response = upload(client, headers, content, name)
assert response.status_code == 202, response.text
identifier = response.json()['document_id']
# Later deployment toggles must not reinterpret the admitted document.
e.settings = e.settings.model_copy(update={'allow_partial_extraction': False})
process(e, FakeVision(warnings=('Small unrecognized region',)))
detail = polling(client, identifier)
assert detail['status'] == 'ready' and not detail['review_required']
assert not detail['is_active'] and not detail['searchable']
if kind != 'factual':
assert detail['extraction_quality_decision'] == 'accepted_with_warnings'
with e.engine.connect() as conn:
assert conn.execute(text('SELECT count(*) FROM document_chunks WHERE document_id=:id'), {'id': UUID(identifier)}).scalar_one() > 0
snapshot = conn.execute(text('SELECT processing_profile FROM documents WHERE id=:id'), {'id': UUID(identifier)}).scalar_one()
assert snapshot['extraction']['allow_partial_extraction'] is True
@@ -43,8 +43,9 @@ def test_unstyled_word_title_preserves_all_pairs(settings):
@pytest.mark.parametrize('provider', ['gemini', 'openrouter'])
@pytest.mark.parametrize('diagnostic', ['incomplete', 'warning', 'region'])
def test_native_recognition_diagnostics_preserve_candidate_and_force_review(settings, monkeypatch, provider, diagnostic):
profile = settings.model_copy(update={'ocr_review_required': False, 'vision_provider': provider,
@pytest.mark.parametrize('partial', [False, True])
def test_native_recognition_diagnostics_preserve_candidate_and_force_review(settings, monkeypatch, provider, diagnostic, partial):
profile = settings.model_copy(update={'ocr_review_required': False, 'allow_partial_extraction': partial, 'vision_provider': provider,
'vision_endpoint': 'https://example.invalid/v1beta', 'vision_model': 'fixture-flash'}).processing_profile()
payload = native(profile)
transcript = json.loads(payload['candidates'][0]['content']['parts'][0]['text'])
@@ -69,6 +70,12 @@ def test_native_recognition_diagnostics_preserve_candidate_and_force_review(sett
class RetainedVision:
def transcribe(self, *args, **kw): return blocks
raw = image_bytes('PNG')
if partial:
result = PageBlockExtractor(RetainedVision()).extract_for_review(document_id=uuid4(),title='Image',
original_sha256=hashlib.sha256(raw).hexdigest(),content=raw,mime_type='image/png', processing_profile=profile)
assert result.quality_decision == 'accepted_with_warnings' and not result.review_annotations
assert result.blocks == blocks
return
with pytest.raises(ReviewRequired) as pending:
PageBlockExtractor(RetainedVision()).extract_for_review(document_id=uuid4(),title='Image',
original_sha256=hashlib.sha256(raw).hexdigest(),content=raw,mime_type='image/png', processing_profile=profile)
+101
View File
@@ -0,0 +1,101 @@
"""Temporary best-effort admission keeps warnings without inventing human review."""
import hashlib
from uuid import uuid4
import pytest
from app.modules.documents.extraction import PageBlockExtractor, ReviewRequired, ExtractionError
from app.modules.documents.extraction_artifacts import allow_partial_extraction, extraction_profile_digest
from app.modules.documents.worker import validate_source
from app.modules.documents.review import prepare_chunks
from tests.support.extraction import FakeVision, pdf_bytes
from tests.support.formats import image_bytes
def extract(settings, content, mime, *, enabled=True, vision=None):
profile = settings.model_copy(update={"allow_partial_extraction": enabled,
"vision_provider": "gemini", "vision_endpoint": "https://test.invalid",
"vision_model": "fixture-flash"}).processing_profile()
doc = dict(id=uuid4(), title="Test", mime_type=mime, processing_profile=profile,
file_sha256=hashlib.sha256(content).hexdigest())
envelope = PageBlockExtractor(vision).extract_for_review(document_id=doc["id"], title=doc["title"],
original_sha256=doc["file_sha256"], content=content, mime_type=mime, processing_profile=profile)
validate_source(envelope, doc, content)
return envelope, doc
@pytest.mark.parametrize("kind", ["png", "jpeg", "scan", "direct"])
def test_no_manual_gate_even_when_both_review_flags_are_true(settings, kind):
content = image_bytes("JPEG" if kind == "jpeg" else "PNG")
mime = "image/jpeg" if kind == "jpeg" else "image/png"
if kind in ("scan", "direct"):
content = pdf_bytes([[('image', content, 10, 20)]]) if kind == "scan" else pdf_bytes([[('text', 'Article 1: fee is 5%', 10, 20)]])
mime = "application/pdf"
vision = FakeVision(warnings=("A small region could not be recognized",))
envelope, doc = extract(settings, content, mime, vision=vision)
assert envelope.quality_decision == "accepted_with_warnings"
assert not envelope.review_annotations
assert any(b.warnings for b in envelope.blocks)
assert prepare_chunks(envelope, doc["processing_profile"], {}, "a" * 64)
def test_usable_text_with_unknown_characters_is_retained(settings):
envelope, _ = extract(settings, image_bytes("PNG"), "image/png", vision=FakeVision(text="Readable content with \ufffd unknown glyph"))
assert any("Readable content" in b.text for b in envelope.blocks)
def test_factual_review_is_bypassed_without_fake_approvals(settings):
envelope, doc = extract(settings, b"Question: fee?\nAnswer: 5%\n", "text/markdown")
assert prepare_chunks(envelope, doc["processing_profile"], {}, "a" * 64)
assert not envelope.review_annotations
def test_strict_snapshot_keeps_manual_gate(settings):
with pytest.raises(ReviewRequired):
extract(settings, image_bytes("PNG"), "image/png", enabled=False, vision=FakeVision(warnings=("missing region",)))
@pytest.mark.parametrize("change", ["wrong_model", "no_readable_content", "checksum"])
def test_best_effort_preserves_integrity_and_useful_content_requirements(settings, change):
if change == "checksum":
profile = settings.model_copy(update={"allow_partial_extraction": True}).processing_profile()
with pytest.raises(ExtractionError, match="checksum"):
PageBlockExtractor().extract(document_id=uuid4(), title="Test", original_sha256="a" * 64,
content=b"text", mime_type="text/markdown", processing_profile=profile)
else:
vision = FakeVision(actual_model="wrong") if change == "wrong_model" else FakeVision(text="\ufffd")
with pytest.raises(ValueError):
extract(settings, image_bytes("PNG"), "image/png", vision=vision)
def test_policy_is_opt_in_validated_and_bound_to_artifact_digest(settings):
strict = settings.processing_profile()
permissive = settings.model_copy(update={"allow_partial_extraction": True}).processing_profile()
assert not allow_partial_extraction(strict)
assert extraction_profile_digest(strict) != extraction_profile_digest(permissive)
strict["extraction"].pop("allow_partial_extraction")
assert not allow_partial_extraction(strict)
strict["extraction"]["allow_partial_extraction"] = "true"
with pytest.raises(ValueError):
extraction_profile_digest(strict)
def test_best_effort_chunking_keeps_unsupported_rule_references(settings):
from app.modules.documents.chunking import chunk_extraction
content = b"Article X: fee is 5%.\n\nExcept when another condition applies.\n"
envelope, doc = extract(settings, content, "text/markdown")
chunks = prepare_chunks(envelope, doc['processing_profile'], {}, 'a' * 64)
assert 'Article X' in ''.join(c.text for c in chunks)
strict = settings.processing_profile()
strict_envelope = PageBlockExtractor().extract_for_review(document_id=uuid4(), title='Test',
original_sha256=hashlib.sha256(content).hexdigest(), content=content,
mime_type='text/markdown', processing_profile=strict)
with pytest.raises(ExtractionError, match='governing-rule identifier'):
chunk_extraction(strict_envelope, strict)
def test_best_effort_splits_large_legal_text_within_existing_bounds(settings):
content = ('Article X: ' + 'condition ' * 60).encode()
settings = settings.model_copy(update={'chunk_size_characters': 100, 'chunk_overlap_characters': 10})
envelope, doc = extract(settings, content, 'text/markdown')
chunks = prepare_chunks(envelope, doc['processing_profile'], {}, 'a' * 64)
assert len(chunks) > 1
assert all(len(c.text) <= 100 for c in chunks)