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
@@ -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)