feat(ingestion): implement Phase 3 text extraction, OCR, and human review

- Add direct text, DOCX, and PDF text extraction with visual OCR fallback
- Implement Gemini and OpenRouter vision adapters with strict bounded retry
- Implement extraction envelopes, artifacts, and Unicode/Persian normalization
- Add human review workflow, candidate staging, and review repositories
- Add migration 0003_extraction_review for audit events and review tracking
- Add comprehensive unit and integration tests covering extraction and review contracts
This commit is contained in:
amirhosein mazaheri
2026-10-07 16:21:01 +03:30
parent b036912293
commit 5ef02d39a9
20 changed files with 4048 additions and 0 deletions
+209
View File
@@ -0,0 +1,209 @@
"""Provider-free faithful metadata and retained artifact integrity contracts."""
import hashlib
import json
from uuid import uuid4
import pytest
from pydantic import ValidationError
from app.modules.documents.types import ExtractedBlock, ExtractionEnvelope
from app.modules.documents.extraction_artifacts import (
LegacyProcessingProfile, extraction_profile_digest, processing_profile_kind, validate_artifact)
from app.modules.documents.settings import IngestionSettings
from app.modules.documents.normalization import normalize_search_text, normalized_inputs
@pytest.fixture
def settings(settings):
return settings.model_copy(update={"vision_provider": "test-vision",
"vision_endpoint": "https://vision.invalid/v1", "vision_model": "actual-model"})
def envelope(settings):
text = " \u067e\u0627\u0633\u062e\u200c 1403/01/02\r\n\u0646\u0647 12.5% "
return ExtractionEnvelope(document_id=uuid4(), title="\u0633\u0646\u062f",
original_sha256="a" * 64, extraction_profile_sha256=extraction_profile_digest(settings.processing_profile()),
normalization_policy="unicode-line-endings-v1", complete=True, quality_decision="reviewed",
warnings=("Manually reviewed numeric fields",), blocks=(
ExtractedBlock(ordinal=0, block_id="q", text="Question?", source_locator="table/1/row/1",
section="FAQ/1", block_type="question", group_id="faq1", method="docx"),
ExtractedBlock(ordinal=1, block_id="a", text=text, search_text=normalize_search_text(text),
source_locator="table/1/row/2", section="FAQ/1", block_type="answer", group_id="faq1", method="docx"),
ExtractedBlock(ordinal=2, block_id="parent", text="Parent heading", source_locator="image/group/1",
block_type="visual_group", group_id="visual1", heading="Heading", method="vision", actual_model="actual-model"),
ExtractedBlock(ordinal=3, block_id="child", text="Child description", source_locator="image/group/1/child/1",
group_id="visual1", parent_block_id="parent", method="vision", actual_model="actual-model", warnings=("Region reviewed",)),
ExtractedBlock(ordinal=4, block_id="pdf", text="PDF page", source_locator="pdf/page/2/block/1", page=2, method="direct_pdf")))
def validate(value, settings, **overrides):
content = value.model_dump_json().encode()
args = dict(artifact_sha256=hashlib.sha256(content).hexdigest(), document_id=value.document_id,
original_sha256=value.original_sha256, processing_profile=settings.processing_profile())
args.update(overrides)
return validate_artifact(content, **args)
def test_round_trip_preserves_faithful_text_and_relationships(settings):
value = envelope(settings)
result = validate(value, settings)
assert result == value
assert result.blocks[1].text != result.blocks[1].search_text
assert result.blocks[0].page is result.blocks[2].page is None
assert result.blocks[3].parent_block_id == "parent" and result.blocks[4].page == 2
with pytest.raises(ValidationError):
result.title = "mutated"
@pytest.mark.parametrize("change", ["document", "original", "digest", "profile", "size", "blocks", "normalization"])
def test_artifact_reuse_rejects_mismatch_and_limits(settings, change):
value = envelope(settings)
overrides = {}
if change == "normalization": value = value.model_copy(update={"normalization_policy": "incompatible"})
if change == "document": overrides["document_id"] = uuid4()
if change == "original": overrides["original_sha256"] = "b" * 64
if change == "digest": overrides["artifact_sha256"] = "b" * 64
if change == "profile":
overrides["processing_profile"] = settings.model_copy(update={"quality_policy": "new-policy"}).processing_profile()
if change in ("size", "blocks"):
key = "max_extraction_artifact_bytes" if change == "size" else "max_extracted_blocks"
overrides["processing_profile"] = settings.model_copy(update={key: 1}).processing_profile()
with pytest.raises(ValueError): validate(value, settings, **overrides)
@pytest.mark.parametrize("change", ["incomplete", "order", "duplicate", "parent", "group", "faq", "page"])
def test_reject_invalid_source_relationships(settings, change):
data = envelope(settings).model_dump()
if change == "incomplete": data["complete"] = False
if change == "order": data["blocks"][0]["ordinal"] = 1
if change == "duplicate": data["blocks"][1]["block_id"] = "q"
if change == "parent": data["blocks"][3]["parent_block_id"] = "missing"
if change == "group": data["blocks"][3]["group_id"] = "different"
if change == "faq": data["blocks"][1]["group_id"] = "unpaired"
if change == "page": data["blocks"][0]["page"] = 0
with pytest.raises(ValidationError): ExtractionEnvelope.model_validate(data)
def test_chunk_and_embedding_changes_reuse_faithful_extraction(settings):
changed = settings.model_copy(update={"chunk_size_characters": 1500, "embedding_model": "other"})
assert extraction_profile_digest(settings.processing_profile()) == extraction_profile_digest(changed.processing_profile())
assert validate(envelope(settings), changed)
def test_legacy_profile_is_explicit_and_never_reinterpreted(settings):
profile = {"extractor": "pypdf-markdown-v1", "normalizer": "unicode-line-endings-v1"}
before = json.dumps(profile)
assert processing_profile_kind(profile) == "legacy-v1"
with pytest.raises(LegacyProcessingProfile): extraction_profile_digest(profile)
assert json.dumps(profile) == before
with pytest.raises(ValueError): processing_profile_kind({"extractor": "unknown"})
def test_snapshot_secrets_identity_and_independence(settings):
values = settings.model_dump()
values.update(vision_provider="configured", vision_endpoint="https://vision.invalid/v1",
vision_model="chosen", vision_api_key="dummy-vision-secret", embedding_api_key="dummy-embedding-secret")
configured = IngestionSettings(_env_file=None, **values)
profile = configured.processing_profile()
assert "dummy-" not in json.dumps(profile) and "api_key" not in json.dumps(profile)
assert configured.embedding_profile == settings.embedding_profile
profile["extraction"]["vision"]["model"] = "mutated"
assert configured.processing_profile()["extraction"]["vision"]["model"] == "chosen"
assert configured.require_vision_credentials() is None
with pytest.raises(ValueError): settings.require_vision_credentials()
for changes in ({"vision_provider": "partial", "vision_endpoint": None, "vision_model": None}, {"normalization_policy": "persian-new-v1"},
{"vision_endpoint": "https://user:dummy-secret@vision.invalid"}, {"max_image_pixels": 0},
{"vision_timeout_seconds": float("inf")}):
with pytest.raises(ValidationError) as error:
IngestionSettings(_env_file=None, **(settings.model_dump() | changes))
assert "dummy-secret" not in str(error.value.errors())
def test_vision_requires_actual_model_and_rejects_native_response_fields(settings):
data = envelope(settings).model_dump()
data["blocks"][2]["actual_model"] = None
with pytest.raises(ValidationError): ExtractionEnvelope.model_validate(data)
data = envelope(settings).model_dump()
data["blocks"][2]["provider_response"] = {"api_key": "dummy-secret"}
with pytest.raises(ValidationError): ExtractionEnvelope.model_validate(data)
@pytest.mark.parametrize("method,model,configured", [
("vision", "other-model", True), ("vision", "actual-model", False),
("ocr", "other-model", True), ("ocr", None, True), ("ocr", "actual-model", False),
("direct_pdf", "actual-model", True), ("docx", "actual-model", True),
("readable_text", "actual-model", True), ("vision", "ACTUAL-MODEL", True)])
def test_frozen_profile_rejects_incompatible_provenance(settings, method, model, configured):
if not configured:
settings = settings.model_copy(update={"vision_provider": None, "vision_endpoint": None, "vision_model": None})
if configured:
settings = settings.model_copy(update={"vision_provider": "test-vision",
"vision_endpoint": "https://vision.invalid/v1", "vision_model": "actual-model"})
data = envelope(settings).model_dump()
for block in data["blocks"]: block["search_text"] = None
data["blocks"][2]["method"] = method
data["blocks"][2]["actual_model"] = model
value = ExtractionEnvelope.model_validate(data)
with pytest.raises(ValueError): validate(value, settings)
@pytest.mark.parametrize("faithful,forged", [
("Rate 12.5%", "Rate 15.5%"), ("Date 1403/01/02", "Date 1403/02/01"),
("Does not apply", "Does apply"), ("Except temporary staff", "All staff"),
("No Persian folding: \u064a", "No Persian folding: \u06cc"),
(" preserve spaces ", "preserve spaces")])
def test_stored_search_text_cannot_rewrite_evidence(settings, faithful, forged):
value = envelope(settings)
blocks = list(value.blocks)
blocks[1] = blocks[1].model_copy(update={"text": faithful, "search_text": forged})
value = value.model_copy(update={"blocks": tuple(blocks)})
with pytest.raises(ValueError): validate(value, settings)
def test_artifact_normalized_character_budget(settings):
settings = settings.model_copy(update={"max_normalized_characters": 1})
with pytest.raises(ValueError): validate(envelope(settings), settings)
@pytest.mark.parametrize("method", ["vision", "ocr"])
def test_configured_model_identity_with_mixed_pdf_pages(settings, method):
value = envelope(settings)
blocks = list(value.blocks)
blocks[2] = blocks[2].model_copy(update={"page": 1, "source_locator": "pdf/page/1/visual", "method": method})
blocks[3] = blocks[3].model_copy(update={"page": 1, "source_locator": "pdf/page/1/visual/child", "method": method})
result = validate(value.model_copy(update={"blocks": tuple(blocks)}), settings)
assert result.blocks[2].method == method and result.blocks[2].actual_model == settings.vision_model
assert result.blocks[2].page == 1 and result.blocks[4].page == 2
assert result.blocks[4].method == "direct_pdf" and result.blocks[4].actual_model is None
def test_faithful_only_normalized_inputs_are_rederived_without_mutation(settings):
value = envelope(settings)
value = value.model_copy(update={"blocks": tuple(block.model_copy(update={"search_text": None}) for block in value.blocks)})
before = value.model_dump_json()
result = validate(value, settings)
assert result.model_dump_json() == before
inputs = normalized_inputs(result, settings.processing_profile())
assert inputs[1] == normalize_search_text(result.blocks[1].text)
assert result.blocks[1].search_text is None and "\r\n" in result.blocks[1].text
@pytest.mark.parametrize("text,expected", [
("Cafe\u0301\r\nLine\rLast", "Caf\u00e9\nLine\nLast"),
(" 12.5% 1403/01/02 not applicable except X\t ", " 12.5% 1403/01/02 not applicable except X\t "),
("\u064a\u0643\u200c\u06cc", "\u064a\u0643\u200c\u06cc")])
def test_v1_normalization_is_canonical_unicode_and_line_endings_only(text, expected):
assert normalize_search_text(text) == expected
@pytest.mark.parametrize("stored", [False, True])
def test_aggregate_normalized_budget_is_enforced_before_return(settings, stored):
value = envelope(settings)
blocks = tuple(block.model_copy(update={"search_text": normalize_search_text(block.text) if stored else None}) for block in value.blocks)
value = value.model_copy(update={"blocks": blocks})
actual = sum(len(normalize_search_text(block.text)) for block in blocks)
profile = settings.model_copy(update={"max_normalized_characters": actual}).processing_profile()
assert len(normalized_inputs(value, profile)) == len(blocks)
profile["limits"]["max_normalized_characters"] = actual - 1
with pytest.raises(ValueError, match="character budget"):
normalized_inputs(value, profile)
with pytest.raises(ValueError, match="character budget"):
validate(value, settings, processing_profile=profile)
+114
View File
@@ -0,0 +1,114 @@
"""REST boundary fixtures; never real provider-quality evidence."""
from io import BytesIO
import json
import pytest
from app.infrastructure.gemini_vision import GeminiVision, INSTRUCTION
from app.modules.documents.extraction import ExtractionError
from tests.support.extraction import FakeVision
from tests.support.formats import image_bytes
@pytest.fixture
def profile(settings):
return settings.model_copy(update={"vision_provider": "gemini", "vision_endpoint": "https://example.invalid/v1beta",
"vision_model": "fixture-flash"}).processing_profile()
def native(profile):
blocks = FakeVision().transcribe(b"image", page=None, section="image", processing_profile=profile)
return dict(modelVersion="fixture-flash", candidates=[dict(finishReason="STOP", content=dict(parts=[
dict(text=json.dumps(dict(complete=True, warnings=[], blocks=[b.model_dump(mode="json") for b in blocks])))]))])
def run(profile, payload, monkeypatch, *, capture=None):
class Opener:
def open(self, request, *, timeout):
if capture is not None:
capture.append((request, timeout))
return BytesIO(json.dumps(payload).encode())
monkeypatch.setattr("urllib.request.build_opener", lambda *a: Opener())
adapter = GeminiVision(endpoint="https://example.invalid/v1beta", model="fixture-flash",
api_key="test-secret", timeout_seconds=60)
return adapter.transcribe(image_bytes(), page=None, section="image", processing_profile=profile)
def test_complete_ordered_native_conversion_and_prompt(profile, monkeypatch):
captured = []
blocks = run(profile, native(profile), monkeypatch, capture=captured)
assert len(blocks) == 2 and blocks[1].parent_block_id == blocks[0].block_id
assert blocks[1].search_text == blocks[1].text
request, timeout = captured[0]
assert 0 < timeout <= 60 and request.get_header("X-goog-api-key") == "test-secret"
body = json.loads(request.data)
assert "ALL visible" in body["contents"][0]["parts"][0]["text"]
assert body["generationConfig"]["responseMimeType"] == "application/json"
@pytest.mark.parametrize("change", ["alias", "missing_model", "truncated", "empty", "incomplete", "warnings", "unreadable", "wrong_page", "wrong_method", "wrong_block_model"])
def test_invalid_native_response_fails_safely(profile, monkeypatch, change):
value = native(profile)
if change == "alias":
value["modelVersion"] = "fixture-flash-resolved"
elif change == "missing_model":
del value["modelVersion"]
elif change == "truncated":
value["candidates"][0]["finishReason"] = "MAX_TOKENS"
else:
part = value["candidates"][0]["content"]["parts"][0]
transcript = json.loads(part["text"])
if change == "empty": transcript["blocks"] = []
if change == "incomplete": transcript["complete"] = False
if change == "warnings": transcript["warnings"] = ["missing region"]
if change == "unreadable": transcript["blocks"][1]["warnings"] = ["unreadable"]
if change == "wrong_page": transcript["blocks"][0]["page"] = 2
if change == "wrong_method": transcript["blocks"][0]["method"] = "direct_pdf"
if change == "wrong_block_model": transcript["blocks"][0]["actual_model"] = "other"
part["text"] = json.dumps(transcript)
with pytest.raises(ExtractionError):
run(profile, value, monkeypatch)
def test_provider_response_byte_limit(profile, monkeypatch):
profile["extraction"]["max_extraction_artifact_bytes"] = 10
with pytest.raises(ExtractionError, match="byte limit"):
run(profile, native(profile), monkeypatch)
def test_provider_failures_redacted(profile, monkeypatch):
class Opener:
def open(self, *a, **kw):
raise TimeoutError("test-secret")
monkeypatch.setattr("urllib.request.build_opener", lambda *a: Opener())
adapter = GeminiVision(endpoint="https://example.invalid/v1beta", model="fixture-flash",
api_key="test-secret", timeout_seconds=60)
with pytest.raises(ExtractionError) as error:
adapter.transcribe(image_bytes(), page=None, section="image", processing_profile=profile)
assert "test-secret" not in str(error.value)
assert error.value.retryable is True
@pytest.mark.parametrize("status,retryable", [(400, False), (401, False), (408, True), (429, True), (503, True)])
def test_provider_http_errors_preserve_retry_category_without_stacked_retries(profile, monkeypatch, status, retryable):
from urllib.error import HTTPError
calls = []
class Opener:
def open(self, *args, **kwargs):
calls.append(1)
raise HTTPError("https://example.invalid", status, "test-secret", {}, None)
monkeypatch.setattr("urllib.request.build_opener", lambda *a: Opener())
adapter = GeminiVision(endpoint="https://example.invalid/v1beta", model="fixture-flash",
api_key="test-secret", timeout_seconds=60)
with pytest.raises(ExtractionError) as error:
adapter.transcribe(image_bytes(), page=None, section="image", processing_profile=profile)
assert error.value.retryable == retryable and len(calls) == 1
assert error.value.code == "EXTRACTION_PROVIDER_FAILED" and "test-secret" not in str(error.value)
def test_provider_malformed_ordinals_are_rejected(profile, monkeypatch):
value = native(profile)
part = value["candidates"][0]["content"]["parts"][0]
transcript = json.loads(part["text"])
transcript["blocks"][0]["ordinal"] = 1
part["text"] = json.dumps(transcript)
with pytest.raises(ExtractionError):
run(profile, value, monkeypatch)
+313
View File
@@ -0,0 +1,313 @@
"""Phase 3 extraction/QC/chunk/artifact acceptance, all provider-free."""
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
import hashlib
from pathlib import Path
from uuid import uuid4
import pytest
from app.infrastructure.extraction_candidates import LocalExtractionCandidates
from app.infrastructure.file_store import LocalFileStore
from app.modules.documents.chunking import chunk_extraction
from app.modules.documents.extraction import (ExtractionError, PageBlockExtractor,
ReviewApproval, REVIEW_CHECKS, ReviewRequired)
from app.modules.documents.extraction_artifacts import LegacyProcessingProfile, validate_artifact
from app.modules.documents.formats import DOCX_MIME
from app.modules.documents.normalization import normalize_search_text
from app.modules.documents.processing import prepare_extraction
from tests.support.extraction import extract, inspected_extract, faq_docx, pdf_bytes, FakeVision
from tests.support.formats import image_bytes, docx_bytes
@pytest.fixture
def profile(settings):
return settings.model_copy(update={"vision_provider": "fixture",
"vision_endpoint": "https://fixture.invalid/v1", "vision_model": "fixture-flash"}).processing_profile()
def test_readable_faithful_and_normalized_text(profile):
text = "\n ماده 12\r\nقیمت 12.5% در 1403/01/02 نیست؛ ي ك ی ک نیم‌فاصله\r\n\r\nتبصره: مگر استثنا. \r"
value = extract(text.encode(), profile)
assert "".join(b.text for b in value.blocks) == text
assert "".join(b.search_text for b in value.blocks) == normalize_search_text(text)
chunks = chunk_extraction(value, profile)
assert len(chunks) == 1
assert all(s in chunks[0].text for s in ("12.5%", "1403/01/02", "نیست", "مگر", "ي ك ی ک", "‌"))
assert chunks[0].page is chunks[0].token_count is None
assert chunks == chunk_extraction(value, profile)
def test_frozen_legacy_fails_without_provider_or_rewrite():
profile = {"extractor": "pypdf-markdown-v1", "normalizer": "unicode-line-endings-v1"}
before = deepcopy(profile)
vision = FakeVision()
with pytest.raises(LegacyProcessingProfile):
extract(b"text", profile, vision=vision)
assert profile == before and not vision.calls
@pytest.mark.parametrize("mime,content", [("text/plain", b"\xff"), ("text/plain", b""),
("text/plain", "ناخوانا \ufffd".encode()), ("application/pdf", b"%PDF-1.7\nbroken"),
("bad/type", b"text")])
def test_invalid_extraction_fails(profile, mime, content):
with pytest.raises((ExtractionError, ValueError)):
extract(content, profile, mime)
def test_docx_adjacent_rows_pair_and_preserve_original_order(profile):
value = extract(faq_docx(), profile, DOCX_MIME)
assert [b.block_type for b in value.blocks] == ["paragraph", "question", "answer", "question", "answer", "answer"]
# A table boundary does not establish an end to the last answer.
assert value.blocks[-1].group_id == value.blocks[-2].group_id
q1, a1, q2, a2 = value.blocks[1:5]
assert q1.group_id == a1.group_id != q2.group_id == a2.group_id
assert "/row/1/" in q1.source_locator and "/row/2/" in a1.source_locator
assert all(b.page is None and b.method == "docx" and b.actual_model is None for b in value.blocks)
with pytest.raises(ExtractionError, match="approved"):
chunk_extraction(value, profile)
chunks = chunk_extraction(value, profile, corpus_purpose="approved_factual")
assert len(chunks) == 3 and "سؤال" in chunks[1].text and "پاسخ" in chunks[1].text
assert "پنجشنبه تا 12" in chunks[1].text and "1403/01/02" in chunks[2].text
def test_docx_two_columns_with_header_and_continuation(profile):
body = """<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:tbl>
<w:tr><w:tc><w:p><w:r><w:t>سؤال</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>پاسخ</w:t></w:r></w:p></w:tc></w:tr>
<w:tr><w:tc><w:p><w:r><w:t>تاریخ؟</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>1403/01/02</w:t></w:r></w:p><w:p><w:r><w:t>مگر استثنا</w:t></w:r></w:p></w:tc></w:tr>
</w:tbl></w:body></w:document>"""
value = extract(docx_bytes(document=body.encode()), profile, DOCX_MIME)
assert len(value.blocks) == 4 and value.blocks[2].group_id == value.blocks[3].group_id
assert value.blocks[3].text == "1403/01/02\nمگر استثنا\n"
@pytest.mark.parametrize("body", [
"<w:p><w:r><w:t>سؤال: بی پاسخ؟</w:t></w:r></w:p>",
"<w:p><w:r><w:t>پاسخ: بدون سوال</w:t></w:r></w:p>",
"<w:p><w:r><w:drawing/></w:r></w:p>",
"<w:sdt><w:p><w:r><w:t>hidden</w:t></w:r></w:p></w:sdt>"])
def test_docx_incomplete_or_unsupported_fails(profile, body):
xml = "<w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'><w:body>" + body + "</w:body></w:document>"
with pytest.raises(ExtractionError):
extract(docx_bytes(document=xml.encode()), profile, DOCX_MIME)
def test_supplied_docx_preserves_all_100_pairs_without_authority_claim(profile):
path = next(Path("data/documents").glob("*.docx"))
value = extract(path.read_bytes(), profile, DOCX_MIME)
questions = [b for b in value.blocks if b.block_type == "question"]
answers = [b for b in value.blocks if b.block_type == "answer"]
assert len(questions) == len(answers) == 100
assert [b.group_id for b in questions] == [b.group_id for b in answers]
with pytest.raises(ExtractionError, match="approved"):
chunk_extraction(value, profile)
def test_pdf_mixed_pages_direct_and_vision_with_numeric_exclusions(profile):
content = pdf_bytes([[("text", "Article 12\nDate 1403/01/02\n12.5% not eligible except note", 30, 40)],
[("image", image_bytes(), 30, 40)]])
vision = FakeVision()
value = inspected_extract(content, profile, "application/pdf", vision=vision)
assert {b.method for b in value.blocks if b.page == 1} == {"direct_pdf"}
assert {b.method for b in value.blocks if b.page == 2} == {"vision"}
assert all(b.actual_model is None for b in value.blocks if b.page == 1)
assert value.quality_decision == "reviewed" and len({call[1] for call in vision.calls}) == 1
direct = "".join(b.text for b in value.blocks if b.page == 1)
assert "1403/01/02" in direct and "12.5%" in direct and "not eligible except" in direct
chunks = chunk_extraction(value, profile)
assert [c.ordinal for c in chunks] == list(range(len(chunks)))
assert any("عنوان اصلی" in c.text and "نمی‌شود" in c.text for c in chunks)
def test_nonempty_pdf_layer_does_not_prove_complete(profile):
content = pdf_bytes([[("text", "Visible text", 30, 40), ("image", image_bytes(), 30, 70)]])
with pytest.raises(ExtractionError, match="vision"):
extract(content, profile, "application/pdf")
def test_manual_qc_immediate_and_bound_to_exact_evidence(profile):
content = pdf_bytes([[("text", "Article 12\n1403/01/02 not except", 30, 40)]])
with pytest.raises(ReviewRequired) as error:
extract(content, profile, "application/pdf")
request = error.value
assert request.image.startswith(b"\x89PNG") and len(request.evidence_sha256) == 64
approval = ReviewApproval(request.evidence_sha256, "reviewer", "Matched visible order and all critical fields", REVIEW_CHECKS)
assert extract(content, profile, "application/pdf", reviews=(approval,)).quality_decision == "reviewed"
altered = pdf_bytes([[("text", "Article 12\n1403/01/03 not except", 30, 40)]])
with pytest.raises(ReviewRequired):
extract(altered, profile, "application/pdf", reviews=(approval,))
incomplete = ReviewApproval(request.evidence_sha256, "reviewer", "numbers only", ("numbers",))
with pytest.raises(ReviewRequired):
extract(content, profile, "application/pdf", reviews=(incomplete,))
def test_rejected_direct_reading_order_falls_back_without_guessing(profile):
content = pdf_bytes([[("text", "Answer below", 30, 150), ("text", "Question above", 30, 40)]])
with pytest.raises(ReviewRequired) as error:
extract(content, profile, "application/pdf")
approval = ReviewApproval(error.value.evidence_sha256, "reviewer", "Creator order differs from page", REVIEW_CHECKS, approved=False)
vision = FakeVision()
with pytest.raises(ReviewRequired) as fallback:
extract(content, profile, "application/pdf", reviews=(approval,), vision=vision)
assert vision.calls and all(b.method == "vision" for b in fallback.value.blocks)
assert "rejected" in fallback.value.reasons[0]
@pytest.mark.parametrize("warning", ["unreadable region/right/2", "ناخوانا: گروه 2"])
def test_image_unreadable_regions_fail_before_chunks(profile, warning):
with pytest.raises(ExtractionError, match="unreadable"):
extract(image_bytes(), profile, "image/jpeg", vision=FakeVision(warnings=(warning,)))
def test_infographic_parent_children_and_order(profile):
value = inspected_extract(image_bytes(), profile, "image/jpeg", vision=FakeVision())
assert all(b.page is None for b in value.blocks)
assert value.blocks[1].parent_block_id == value.blocks[0].block_id
chunks = chunk_extraction(value, profile)
assert len(chunks) == 1 and "عنوان اصلی" in chunks[0].text and "12.5%" in chunks[0].text
assert value.blocks[0].warnings and value.blocks[1].warnings
def test_vision_model_alias_mismatch_fails(profile):
vision = FakeVision(actual_model="resolved-other")
with pytest.raises(ExtractionError, match="identity"):
extract(image_bytes(), profile, "image/jpeg", vision=vision)
@pytest.mark.parametrize("limit", ["max_pdf_pages", "max_rendered_page_pixels", "max_extracted_blocks",
"max_normalized_characters", "max_extraction_artifact_bytes"])
def test_extraction_limits_no_silent_truncation(profile, limit):
profile = deepcopy(profile)
if limit in profile["extraction"]:
profile["extraction"][limit] = 1
else:
profile["limits"][limit] = 1
content = pdf_bytes([[("text", "Article 12\nDate 1403/01/02 except", 30, 40)],
[("text", "Article 13\nnot eligible", 30, 40)]])
with pytest.raises(ValueError):
inspected_extract(content, profile, "application/pdf")
def test_deterministic_bounded_generic_chunks_and_atomic_rule_failure(profile):
profile = deepcopy(profile)
profile["chunk_size"], profile["overlap"] = 100, 15
value = extract(("آغاز‌ " * 50).encode(), profile)
chunks = chunk_extraction(value, profile)
assert len(chunks) > 1 and all(len(normalize_search_text(c.text)) <= 100 for c in chunks)
assert chunks == chunk_extraction(value, profile)
assert [c.ordinal for c in chunks] == list(range(len(chunks)))
rule = extract(("ماده 12\n" + "شرط " * 40 + "\nتبصره: مگر استثنا").encode(), profile)
with pytest.raises(ExtractionError, match="Semantic"):
chunk_extraction(rule, profile)
profile["limits"]["max_chunks"] = 1
with pytest.raises(ExtractionError, match="count"):
chunk_extraction(value, profile)
@pytest.mark.parametrize("purpose", ["behavioral_evaluation", "live_data_placeholder"])
def test_corpus_separation(profile, purpose):
value = extract(b"Source text", profile)
with pytest.raises(ExtractionError, match="knowledge"):
chunk_extraction(value, profile, corpus_purpose=purpose)
@pytest.mark.parametrize("text", ["Price <current-value>", "Rate [TBD]", "مقدار {{tariff}}"])
def test_placeholder_is_not_indexable(profile, text):
with pytest.raises(ExtractionError, match="placeholder"):
extract(text.encode(), profile)
def test_original_and_candidate_retention_concurrent_no_replace(profile, tmp_path):
content = "ماده 12\r\nنرخ 12.5% نیست مگر استثنا\r\n".encode()
store = LocalFileStore(tmp_path / "originals")
key = store.put(content)
document = dict(id=uuid4(), title="Original", storage_key=key, size_bytes=len(content),
file_sha256=hashlib.sha256(content).hexdigest(), mime_type="text/markdown",
processing_profile=profile)
candidates = LocalExtractionCandidates(tmp_path / "extractions", original_directory=store.directory)
prepared = prepare_extraction(store, candidates, PageBlockExtractor(), document=document)
reloaded = LocalExtractionCandidates(candidates.directory, original_directory=store.directory)
assert reloaded.inspect(prepared.candidate, processing_profile=profile) == prepared.envelope
changed = deepcopy(profile)
changed["chunk_size"] = 1500
changed["embedding"]["model"] = "other"
assert reloaded.inspect(prepared.candidate, processing_profile=changed) == prepared.envelope
with ThreadPoolExecutor(max_workers=3) as pool:
records = list(pool.map(lambda _: candidates.put(prepared.envelope, processing_profile=profile), range(3)))
assert len({c.key for c in records}) == 3
assert len(candidates.inventory()["candidates"]) == 4
assert not candidates.inventory()["temporary_files"]
assert LocalFileStore(store.directory).read(key) == content
assert store.inventory()["originals"] == [key]
path = candidates.directory / prepared.candidate.key
path.write_bytes(path.read_bytes().replace(b"12.5", b"99.5"))
with pytest.raises(ValueError, match="integrity"):
reloaded.inspect(prepared.candidate, processing_profile=profile)
def test_original_hash_checked_before_provider_and_candidate(profile, tmp_path):
store = LocalFileStore(tmp_path / "originals")
candidates = LocalExtractionCandidates(tmp_path / "extractions", original_directory=store.directory)
key = store.put(image_bytes())
vision = FakeVision()
with pytest.raises(ExtractionError, match="integrity"):
prepare_extraction(store, candidates, PageBlockExtractor(vision), document=dict(
id=uuid4(), title="Original", storage_key=key, size_bytes=len(image_bytes()),
file_sha256="a" * 64, mime_type="image/jpeg", processing_profile=profile))
assert not vision.calls and not candidates.directory.exists()
def test_candidate_namespaces_and_unsafe_keys(profile, tmp_path):
original = tmp_path / "originals"
with pytest.raises(ValueError, match="namespace"):
LocalExtractionCandidates(original / "extractions", original_directory=original)
candidates = LocalExtractionCandidates(tmp_path / "extractions", original_directory=original)
with pytest.raises(ValueError, match="key"):
candidates._path("../escape")
def test_docx_question_answer_inside_single_cell(profile):
xml = """<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:tbl><w:tr><w:tc>
<w:p><w:r><w:t>سؤال: تاریخ؟</w:t></w:r></w:p>
<w:p><w:r><w:t>پاسخ: 1403/01/02 نیست مگر استثنا</w:t></w:r></w:p>
</w:tc></w:tr></w:tbl></w:body></w:document>"""
value = extract(docx_bytes(document=xml.encode()), profile, DOCX_MIME)
assert [b.block_type for b in value.blocks] == ["question", "answer"]
assert value.blocks[0].group_id == value.blocks[1].group_id
assert "/paragraph/2" in value.blocks[1].source_locator
def test_valid_artifact_retained_even_if_chunk_bound_fails(profile, tmp_path):
content = ("ماده 12\n" + "شرط " * 40 + "مگر استثنا").encode()
profile = deepcopy(profile)
profile["chunk_size"], profile["overlap"] = 50, 10
store = LocalFileStore(tmp_path / "originals")
key = store.put(content)
candidates = LocalExtractionCandidates(tmp_path / "extractions", original_directory=store.directory)
with pytest.raises(ExtractionError, match="Semantic"):
prepare_extraction(store, candidates, PageBlockExtractor(), document=dict(
id=uuid4(), title="Source", storage_key=key, size_bytes=len(content),
file_sha256=hashlib.sha256(content).hexdigest(), mime_type="text/markdown", processing_profile=profile))
assert len(candidates.inventory()["candidates"]) == 1
assert store.read(key) == content
def test_cross_page_rule_note_stays_together_without_fake_page(profile):
from app.modules.documents.types import ExtractedBlock, ExtractionEnvelope
from app.modules.documents.extraction_artifacts import extraction_profile_digest
value = ExtractionEnvelope(document_id=uuid4(), title="Rule", original_sha256="a" * 64,
extraction_profile_sha256=extraction_profile_digest(profile), normalization_policy=profile["normalizer"],
complete=True, quality_decision="reviewed", blocks=(
ExtractedBlock(ordinal=0, block_id="rule", text="ماده 12\n1403/01/02", source_locator="pdf/page/1/block/1",
section="Article 12", page=1, method="direct_pdf"),
ExtractedBlock(ordinal=1, block_id="note", text="تبصره: شامل استثنا نمی‌شود", source_locator="pdf/page/2/block/1",
section="Article 12 note", page=2, method="direct_pdf")))
chunks = chunk_extraction(value, profile)
assert len(chunks) == 1 and chunks[0].page is None
assert "pages/1,2" in chunks[0].section and "استثنا" in chunks[0].text
def test_circular_conditions_and_exclusion_headings_do_not_split_rule(profile):
text = "# Circular 125\nDecision dated 1403/01/02.\n\n# Conditions\nOnly 12.5% subject to approval.\n\n# Exclusions\nNot available for excluded cases.\n"
value = extract(text.encode(), profile)
chunks = chunk_extraction(value, profile)
assert len(chunks) == 1
assert all(term in chunks[0].text for term in ("Circular 125", "Conditions", "Exclusions", "Not available", "12.5%"))
+193
View File
@@ -0,0 +1,193 @@
"""Bounded Phase 3 closure regressions; generated sources, no providers."""
from copy import deepcopy
import pytest
from app.modules.documents.extraction import ExtractionError, PageBlockExtractor
from app.modules.documents.chunking import chunk_extraction, rule_references
from app.modules.documents.formats import DOCX_MIME
from tests.support.formats import docx_bytes
from tests.support.extraction import extract
NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
@pytest.fixture
def profile(settings):
return settings.processing_profile()
def formatted(prop, location, reset=False):
value = {"position-up": "<w:position w:val='6'/>", "position-down": "<w:position w:val='-6'/>"}.get(prop, f"<w:{prop}/>")
reset_xml = "<w:position w:val='0'/>" if prop.startswith("position") else f"<w:{prop} w:val='false'/>"
styles, ps, rs, direct = "", "", "", ""
if location == "direct":
direct = value
elif location == "defaults":
styles = f"<w:docDefaults><w:rPrDefault><w:rPr>{value}</w:rPr></w:rPrDefault></w:docDefaults>"
else:
kind = "character" if "character" in location else "paragraph"
styles = f"<w:style w:type='{kind}' w:styleId='Base'><w:rPr>{value}</w:rPr></w:style>"
name = "Base"
if location.startswith("inherited"):
styles += f"<w:style w:type='{kind}' w:styleId='Child'><w:basedOn w:val='Base'/></w:style>"
name = "Child"
if location != "unused":
if kind == "paragraph": ps = f"<w:pStyle w:val='{name}'/>"
else: rs = f"<w:rStyle w:val='{name}'/>"
if reset: direct = reset_xml
body = f"<w:p><w:pPr>{ps}</w:pPr><w:r><w:rPr>{rs}{direct}</w:rPr><w:t>10 3 not abc</w:t></w:r></w:p>"
return document(body, styles)
def document(body, styles=""):
extras = {"word/styles.xml": f"<w:styles xmlns:w='{NS}'>{styles}</w:styles>".encode()} if styles else None
return docx_bytes(extras, f"<w:document xmlns:w='{NS}'><w:body>{body}</w:body></w:document>".encode())
@pytest.mark.parametrize("prop", ["position-up", "position-down", "caps", "smallCaps", "webHidden", "specVanish"])
@pytest.mark.parametrize("location", ["direct", "defaults", "paragraph", "inherited-paragraph", "character", "inherited-character"])
def test_semantic_transforms(profile, prop, location):
with pytest.raises(ExtractionError, match="semantic"):
extract(formatted(prop, location), profile, DOCX_MIME)
@pytest.mark.parametrize("prop", ["position-up", "caps", "smallCaps", "webHidden", "specVanish"])
@pytest.mark.parametrize("location", ["direct", "defaults", "inherited-paragraph", "inherited-character"])
def test_semantic_resets(profile, prop, location):
assert extract(formatted(prop, location, True), profile, DOCX_MIME).blocks[0].text == "10 3 not abc\n"
@pytest.mark.parametrize("prop", ["position-up", "caps", "smallCaps", "webHidden", "specVanish", "b", "i"])
def test_unused_and_harmless(profile, prop):
assert extract(formatted(prop, "unused"), profile, DOCX_MIME).complete
if prop in ("b", "i"):
assert extract(formatted(prop, "direct"), profile, DOCX_MIME).complete
def p(text, level=None):
props = f"<w:pPr><w:pStyle w:val='Heading{level}'/></w:pPr>" if level else ""
return f"<w:p>{props}<w:r><w:t>{text}</w:t></w:r></w:p>"
STYLES = "".join(f"<w:style w:type='paragraph' w:styleId='Heading{i}'><w:pPr><w:outlineLvl w:val='{i-1}'/></w:pPr></w:style>" for i in range(1, 5))
def table(text):
return "<w:tbl><w:tr><w:tc>" + p(text) + "</w:tc></w:tr></w:tbl>"
def faq_source():
return p("Question: What?", 2) + p("Answer: Rule.", 2) + p("Required documents", 3) + p("Passport.") + table("Proof.") + p("Exceptions", 4) + p("Unless exempt.") + table("No guessed numbers.") + p("Second paragraph.") + p("Question: When?", 2) + p("Answer: Now.", 2) + p("Background", 1) + p("Separate.")
def test_docx_answer_hierarchy_and_tables(profile):
envelope = extract(document(faq_source(), STYLES), profile, DOCX_MIME)
group = envelope.blocks[0].group_id
expected = ["Question: What?\n", "Answer: Rule.\n", "Required documents\n", "Passport.\n", "Proof.\n", "Exceptions\n", "Unless exempt.\n", "No guessed numbers.\n", "Second paragraph.\n"]
assert [b.text for b in envelope.blocks if b.group_id == group] == expected
assert all(b.page is None for b in envelope.blocks)
assert "table/1/row/1/cell/1" in envelope.blocks[4].source_locator
chunks = chunk_extraction(envelope, profile, corpus_purpose="approved_factual")
assert chunks[0].text == "".join(expected)
assert len(chunks) == 3
assert [c.ordinal for c in chunks] == list(range(3))
small = deepcopy(profile); small["chunk_size"] = 80; small["overlap"] = 0
with pytest.raises(ExtractionError, match="Semantic group"):
chunk_extraction(envelope, small, corpus_purpose="approved_factual")
@pytest.mark.parametrize("body", [p("Question: What?", 2)+p("Required documents", 3), p("Question: What?", 2)+p("Answer: Now.", 3), p("Question: What?", 2)+p("Answer: Now.", 2)+p("Question: nested?", 3)])
def test_docx_ambiguous_pairs_rejected(profile, body):
with pytest.raises(ExtractionError, match="FAQ"):
extract(document(body, STYLES), profile, DOCX_MIME)
@pytest.mark.parametrize("phrase", ["Articles 13 and 14", "Article 12 and 13", "Article 12, 13", "Article 12 through 13", "مواد ۱۳ و ۱۴", "ماده ۱۲ و ۱۳", "Clauses 1(a), 1(b)", "Circulars 1403/100 and 1403/200"])
def test_complete_dependency_targets(profile, phrase):
envelope = extract(("Article 12\nRule.\n\n# Notes\nApplies only to "+phrase+".\n").encode(), profile)
with pytest.raises(ExtractionError, match="reference|identifier"):
chunk_extraction(envelope, profile)
@pytest.mark.parametrize("phrase", ["Article 12 and 12", "Article ۱۲, 12", "ماده ۱۲ و 12", "Article 12 through 12"])
def test_matching_list_targets(profile, phrase):
envelope = extract(("Article 12\nRule.\n\n# Notes\nApplies only to "+phrase+".\n").encode(), profile)
assert len(chunk_extraction(envelope, profile)) == 1
def test_incidental_lists_and_ordinary_decision(profile):
text = "Article 12\nThe decision is final.\n\n# Notes\nSee Articles 13 and 14.\n"
assert len(chunk_extraction(extract(text.encode(), profile), profile)) == 1
@pytest.mark.parametrize("phrase", ["Article XII", "Article 12-13", "Article 12 and XIII", "Article 12 through 13.1", "Articles", "ماده ۱۲ الی سیزده"])
def test_unsupported_targets(phrase):
with pytest.raises(ExtractionError, match="identifier"):
rule_references(phrase)
@pytest.mark.parametrize("source", ["plain", "faq", "docx", "cell"])
@pytest.mark.parametrize("limit", ["blocks", "characters", "bytes"])
def test_incremental_output_stops(profile, monkeypatch, source, limit):
if limit == "blocks": profile["extraction"]["max_extracted_blocks"] = 2
elif limit == "characters": profile["limits"]["max_normalized_characters"] = 65
else: profile["extraction"]["max_extraction_artifact_bytes"] = 1500
count = []
original = PageBlockExtractor._block
def observed(self, text, *args, **kwargs):
count.append(text)
return original(self, text, *args, **kwargs)
monkeypatch.setattr(PageBlockExtractor, "_block", observed)
if source == "plain": data = ("ordinary visible text\n\n"*100).encode(); mime="text/plain"
elif source == "faq": data = ("Question: What?\nAnswer: ordinary visible text\n"*100).encode(); mime="text/plain"
elif source == "docx": data=document(p("ordinary visible text")*100); mime=DOCX_MIME
else:
paragraphs = (p("Question: What?")+p("Answer: ordinary visible text"))*100 if limit == "blocks" else p("ordinary visible text")*100
data=document("<w:tbl><w:tr><w:tc>"+paragraphs+"</w:tc></w:tr></w:tbl>"); mime=DOCX_MIME
with pytest.raises(ValueError, match="limit|budget"):
extract(data, profile, mime)
assert len(count) <= 5
@pytest.mark.parametrize("limit", ["blocks", "characters", "bytes"])
def test_cell_block_budget_stops_before_later_paragraphs(profile, monkeypatch, limit):
from app.modules.documents import extraction
if limit == "blocks": profile["extraction"]["max_extracted_blocks"] = 2
elif limit == "characters": profile["limits"]["max_normalized_characters"] = 65
else: profile["extraction"]["max_extraction_artifact_bytes"] = 1500
calls = []
original = extraction._TextCounter.add
def observed(self, text):
calls.append(text)
return original(self, text)
monkeypatch.setattr(extraction._TextCounter, "add", observed)
source = document("<w:tbl><w:tr><w:tc>"+(p("Question: What?")+p("Answer: ordinary visible text"))*100+"</w:tc></w:tr></w:tbl>")
with pytest.raises(ValueError, match="limit|budget"):
extract(source, profile, DOCX_MIME)
assert len(calls) < 20 if limit == "blocks" else len(calls) < 100
@pytest.mark.parametrize("prop,value", [("position", "6"), ("position", "-6"), ("caps", "true")])
def test_actual_digit_and_case_evidence(profile, prop, value):
body = "<w:p><w:r><w:t>10</w:t></w:r><w:r><w:rPr>"+f"<w:{prop} w:val='{value}'/>"+"</w:rPr><w:t>3 abc</w:t></w:r></w:p>"
with pytest.raises(ExtractionError, match="semantic"):
extract(document(body), profile, DOCX_MIME)
def test_docx_structural_dependency_interactions(profile):
body = p("Question: What?",2)+p("Answer: Rules.",2)+p("Article 12",3)+p("Rule one.")+p("Conditions",4)+table("Applies only to Article ۱۲ and 12.")+p("Article 13",3)+p("Rule two.")+p("Exceptions",4)+p("Applies only to Article 13.")+p("Background",3)+p("Historical context concerns Article 99.")
value = extract(document(body, STYLES), profile, DOCX_MIME)
assert len({b.group_id for b in value.blocks}) == 1
assert value.blocks[5].parent_block_id == value.blocks[4].block_id
chunks = chunk_extraction(value, profile, corpus_purpose="approved_factual")
assert len(chunks) == 1 and chunks[0].text == "".join(b.text for b in value.blocks)
assert chunk_extraction(value, profile, corpus_purpose="approved_factual") == chunks
with pytest.raises(ExtractionError, match="reference"):
bad=extract(document(body.replace("Article ۱۲ and 12", "Article 12 and 13"), STYLES),profile,DOCX_MIME)
chunk_extraction(bad,profile,corpus_purpose="approved_factual")
with pytest.raises(ExtractionError,match="semantic"):
extract(document(body.replace("<w:t>Rule one.</w:t>", "<w:rPr><w:caps/></w:rPr><w:t>Rule one.</w:t>"), STYLES),profile,DOCX_MIME)
def test_heading_labels_without_colons(profile):
value = extract(document(p("Question",2)+p("What?")+p("Answer",2)+p("Now.")+table("No exceptions."), STYLES),profile,DOCX_MIME)
assert {b.block_type for b in value.blocks} == {"question", "answer"}
assert len(chunk_extraction(value,profile,corpus_purpose="approved_factual")) == 1
@pytest.mark.parametrize("source", ["plain","faq","docx"])
def test_exact_artifact_and_normalized_budgets(profile, source):
from app.modules.documents.extraction_artifacts import serialize_artifact
data = {"plain": "e\u0301\r\n Persian‌\r text".encode(), "faq": "Question: e\u0301?\r\nAnswer: ۱۲.۵ نیست‌\r".encode(), "docx": document("<w:p><w:r><w:t>e</w:t></w:r><w:r><w:t>\u0301</w:t></w:r></w:p>")}[source]
mime=DOCX_MIME if source=="docx" else "text/plain"
value=extract(data,profile,mime)
count=sum(len(b.search_text) for b in value.blocks)
exact=len(serialize_artifact(value,profile))
bounded=deepcopy(profile); bounded["limits"]["max_normalized_characters"]=count; bounded["extraction"]["max_extraction_artifact_bytes"]=exact
assert extract(data,bounded,mime).blocks == value.blocks
bounded["extraction"]["max_extraction_artifact_bytes"]-=1
with pytest.raises(ValueError,match="byte limit"):
extract(data,bounded,mime)
@pytest.mark.parametrize("phrase", ["Article 12 or 13", "ماده ۱۲ یا ۱۳"])
def test_alternative_targets_rejected(profile,phrase):
value=extract(("Article 12\nRule.\n\n# Notes\nApplies only to "+phrase+".").encode(),profile)
with pytest.raises(ExtractionError,match="reference|identifier"):
chunk_extraction(value,profile)
+231
View File
@@ -0,0 +1,231 @@
"""Generated regressions for the six scoped Phase 3 context/transport repairs."""
from copy import deepcopy
from io import BytesIO
import json
from threading import Event
import time
from uuid import uuid4
import pytest
from app.infrastructure.gemini_vision import GeminiVision
from app.modules.documents.chunking import chunk_extraction
from app.modules.documents.extraction import ExtractionError, ExtractionProviderError
from app.modules.documents.extraction_artifacts import extraction_profile_digest
from app.modules.documents.formats import DOCX_MIME
from app.modules.documents.types import ExtractedBlock, ExtractionEnvelope
from tests.support.extraction import extract
from tests.support.formats import docx_bytes, image_bytes
@pytest.fixture
def profile(settings):
return settings.model_copy(update={"vision_provider": "gemini",
"vision_endpoint": "https://fixture.invalid/v1beta", "vision_model": "fixture-flash"}).processing_profile()
def docx(body):
return docx_bytes(document=("<w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' "
"xmlns:m='http://schemas.openxmlformats.org/officeDocument/2006/math' "
"xmlns:x='urn:unsupported'><w:body>" + body + "</w:body></w:document>").encode())
def p(text):
return "<w:p><w:r><w:t>" + text + "</w:t></w:r></w:p>"
def block(i, text, *, page=1, method="direct_pdf", group=None):
locator = f"pdf/page/{page}/block/{i}"
return ExtractedBlock(ordinal=i, block_id=locator, text=text, source_locator=locator,
section=locator, page=page, method=method, group_id=group,
actual_model="fixture-flash" if method == "vision" else None)
def envelope(profile, blocks):
return ExtractionEnvelope(document_id=uuid4(), title="Fixture", original_sha256="a" * 64,
extraction_profile_sha256=extraction_profile_digest(profile),
normalization_policy=profile["normalizer"], complete=True, quality_decision="reviewed",
blocks=tuple(blocks))
@pytest.mark.parametrize("body", [
"<w:p><m:oMath><m:f><m:num><m:r><m:t>1</m:t></m:r></m:num>"
"<m:den><m:r><m:t>2</m:t></m:r></m:den></m:f></m:oMath></w:p>",
"<w:p><m:oMathPara><m:oMath><m:r><m:t>12</m:t></m:r></m:oMath></m:oMathPara></w:p>",
"<w:p><x:r><x:t>12</x:t></x:r></w:p>",
"<w:p><w:unknownVisible><w:r><w:t>12</w:t></w:r></w:unknownVisible></w:p>",
])
def test_equations_and_unsupported_paragraph_namespaces_rejected(profile, body):
with pytest.raises(ExtractionError):
extract(docx(p("Ordinary prefix") + body), profile, DOCX_MIME)
@pytest.mark.parametrize("revision", [
"moveFrom", "moveTo", "moveFromRangeStart", "moveFromRangeEnd",
"moveToRangeStart", "moveToRangeEnd", "customXmlMoveFromRangeStart",
"customXmlMoveToRangeEnd", "pPrChange", "rPrChange",
])
def test_tracked_moves_and_revision_structures_rejected(profile, revision):
body = "<w:p><w:" + revision + "><w:r><w:t>Moved 12</w:t></w:r></w:" + revision + "></w:p>"
with pytest.raises(ExtractionError):
extract(docx(p("Untracked 1403/01/02") + body), profile, DOCX_MIME)
def test_ordinary_docx_runs_hyperlinks_and_bookmarks_preserved(profile):
body = "<w:p><w:pPr><w:keepNext/></w:pPr><w:bookmarkStart w:id='0' w:name='a'/>"
body += "<w:r><w:t>1403</w:t><w:noBreakHyphen/><w:t>01</w:t></w:r>"
body += "<w:hyperlink><w:r><w:t> قرارداد‌ نیست</w:t></w:r></w:hyperlink><w:bookmarkEnd w:id='0'/></w:p>"
value = extract(docx(body + p("Independent paragraph")), profile, DOCX_MIME)
assert [b.text for b in value.blocks] == ["1403\u201101 قرارداد‌ نیست\n", "Independent paragraph\n"]
@pytest.mark.parametrize("labels", [("## Question", "## Answer"), ("## Question: Date?", "## Answer: 1403/01/02")])
def test_nested_faq_answer_sections_keep_pair_and_dependencies(profile, labels):
text = labels[0] + "\nWhat is needed?\n" + labels[1] + "\nComplete answer.\n"
text += "### Required documents\nID 12 and form 2.\n#### Exceptions\nNot required unless approved.\n"
text += "## Independent topic\nOrdinary information.\n"
value = extract(text.encode(), profile)
qa = [b for b in value.blocks if b.group_id]
assert qa and {b.block_type for b in qa} == {"question", "answer"}
assert len({b.group_id for b in qa}) == 1
assert "Required documents" in "".join(b.text for b in qa)
assert "Exceptions" in "".join(b.text for b in qa)
assert "".join(b.text for b in value.blocks) == text
with pytest.raises(ExtractionError):
chunk_extraction(value, profile)
chunks = chunk_extraction(value, profile, corpus_purpose="approved_factual")
assert len(chunks) == 2
assert "Exceptions" in chunks[0].text and "Independent topic" not in chunks[0].text
small = deepcopy(profile); small["chunk_size"] = 60; small["overlap"] = 5
with pytest.raises(ExtractionError, match="Semantic"):
chunk_extraction(value, small, corpus_purpose="approved_factual")
@pytest.mark.parametrize("text", [
"## Question\nFirst?\n### Answer\nUnclear hierarchy.",
"## Question\nFirst?\n## Answer\nComplete.\n### Question\nNested question?\n### Answer\nNested answer.",
"## Question\nNo answer.\n### Required documents\nNot an answer.",
])
def test_ambiguous_or_incomplete_faq_hierarchy_rejected(profile, text):
with pytest.raises(ExtractionError):
extract(text.encode(), profile)
@pytest.mark.parametrize("same_group", [False, True])
@pytest.mark.parametrize("body", ["Applies only to Article 13.", "Applies to Article 12 and Article 13."])
def test_whole_dependency_reference_conflict_rejected(profile, same_group, body):
value = envelope(profile, [
block(0, "Article 12: governing rule.", group="rule"),
block(1, "# Notes", page=2, method="vision", group="rule" if same_group else "note"),
block(2, body, page=2, method="vision", group="rule" if same_group else "note")])
with pytest.raises(ExtractionError):
chunk_extraction(value, profile)
@pytest.mark.parametrize("body", [
"Applies only to Article 12. See Article 13 for background.",
"See Article 13 for background. Not applicable to excluded cases.",
"Applies only to ماده ۱۲. Refer to Article 13.",
])
def test_dependency_valid_targets_and_incidental_citations_preserved(profile, body):
value = envelope(profile, [block(0, "Article 12: rule.", group="rule"),
block(1, "# Notes\n" + body, page=2, method="vision", group="notes")])
chunks = chunk_extraction(value, profile)
assert len(chunks) == 1 and body in chunks[0].text
assert "pages/1,2" in chunks[0].section
@pytest.mark.parametrize("name", ["Circular", "Decision", "بخشنامه", "تصمیم"])
@pytest.mark.parametrize("grouped", [False, True])
def test_independent_numbered_decisions_keep_own_dependencies(profile, name, grouped):
blocks = []
for i, number in enumerate([12, 13]):
group = f"rule-{number}" if grouped else None
blocks.extend([block(3*i, f"{name} {number}: rule {number}.", page=2*i+1, group=group),
block(3*i+1, f"Conditions: approved for {number}.", page=2*i+2, method="vision", group=group),
block(3*i+2, f"Exceptions: excluded for {number}.", page=2*i+2, method="vision", group=group)])
chunks = chunk_extraction(envelope(profile, blocks), profile)
assert len(chunks) == 2
for i, number in enumerate([12, 13]):
assert f"{name} {number}" in chunks[i].text
assert f"approved for {number}" in chunks[i].text and f"excluded for {number}" in chunks[i].text
assert f"{name} {25-number}" not in chunks[i].text
assert f"pages/{2*i+1},{2*i+2}" in chunks[i].section
assert [c.ordinal for c in chunks] == [0, 1]
small = deepcopy(profile); small["chunk_size"] = 35; small["overlap"] = 5
with pytest.raises(ExtractionError, match="Semantic"):
chunk_extraction(envelope(profile, blocks), small)
def native_response(text):
value = block(0, text, page=None, method="vision").model_copy(update={"source_locator": "image/block"})
transcript = {"complete": True, "warnings": [], "blocks": [value.model_dump(mode="json")]}
return json.dumps({"modelVersion": "fixture-flash", "candidates": [{"finishReason": "STOP",
"content": {"parts": [{"text": json.dumps(transcript)}]}}]}).encode()
@pytest.mark.parametrize("new_adapter", [False, True])
def test_transport_capacity_survives_timeout_and_recovers_without_late_results(profile, monkeypatch, new_adapter):
release, entered, completed = Event(), Event(), Event()
calls = []
class Response(BytesIO):
def close(self):
super().close()
completed.set()
class Opener:
def open(self, *args, **kwargs):
calls.append(1)
if len(calls) == 1:
entered.set()
release.wait(3)
return Response(native_response("Late result must never be accepted"))
return BytesIO(native_response("Fresh successful call"))
monkeypatch.setattr("urllib.request.build_opener", lambda *args: Opener())
profile = deepcopy(profile); profile["extraction"]["vision"]["timeout_seconds"] = .1
adapter = GeminiVision(endpoint="https://fixture.invalid/v1beta", model="fixture-flash",
api_key="private-secret", timeout_seconds=.1)
def call():
return adapter.transcribe(image_bytes(), page=None, section="image", processing_profile=profile)
try:
with pytest.raises(ExtractionProviderError) as first:
call()
assert entered.is_set() and first.value.retryable
for _ in range(3):
if new_adapter:
adapter = GeminiVision(endpoint="https://fixture.invalid/v1beta", model="fixture-flash",
api_key="private-secret", timeout_seconds=.1)
with pytest.raises(ExtractionProviderError, match="capacity") as error:
call()
assert error.value.retryable and "private-secret" not in str(error.value)
assert len(calls) == 1
finally:
release.set()
assert completed.wait(1)
# Event is set by response.close just before transport releases its slot.
deadline = time.monotonic() + 1
while True:
try:
result = call()
break
except ExtractionProviderError as error:
assert "capacity" in str(error) and time.monotonic() < deadline
time.sleep(.005)
assert [b.text for b in result] == ["Fresh successful call"]
assert len(calls) == 2
def test_dependency_cannot_hide_another_rule_heading_in_its_source_group(profile):
value = envelope(profile, [block(0, "Article 12: governing rule.", group="rule"),
block(1, "# Notes", group="note"), block(2, "Article 13: excluded cases.", group="note")])
with pytest.raises(ExtractionError):
chunk_extraction(value, profile)
def test_faq_context_does_not_exempt_explicit_rule_dependency_conflicts(profile):
blocks = [
block(0, "Question: What does Article 12 require?", group="faq").model_copy(update={"block_type": "question"}),
block(1, "Answer: Details follow.", group="faq").model_copy(update={"block_type": "answer"}),
block(2, "Article 12: governing rule.", group="faq").model_copy(update={"block_type": "answer"}),
block(3, "# Notes\nApplies only to Article 13.", group="faq").model_copy(update={"block_type": "answer"})]
with pytest.raises(ExtractionError):
chunk_extraction(envelope(profile, blocks), profile, corpus_purpose="approved_factual")
+311
View File
@@ -0,0 +1,311 @@
"""Regressions for the nine confirmed Phase 3 defects; generated inputs only."""
from copy import deepcopy
from io import BytesIO
import json
from threading import Event
import time
from uuid import uuid4
import pytest
from app.modules.documents.chunking import chunk_extraction
from app.modules.documents.extraction import ExtractionError, ExtractionProviderError, PageBlockExtractor
from app.modules.documents.extraction_artifacts import extraction_profile_digest
from app.modules.documents.formats import DOCX_MIME
from app.modules.documents.types import ExtractedBlock, ExtractionEnvelope
from app.infrastructure.gemini_vision import GeminiVision
from tests.support.extraction import extract, inspected_extract, pdf_bytes
from tests.support.formats import docx_bytes, image_bytes
@pytest.fixture
def profile(settings):
return settings.model_copy(update={"vision_provider": "gemini",
"vision_endpoint": "https://fixture.invalid/v1beta", "vision_model": "fixture-flash"}).processing_profile()
def docx(body, extra=None):
return docx_bytes(document=("<w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>"
"<w:body>" + body + "</w:body></w:document>").encode(), extra=extra)
def p(text):
return "<w:p><w:r><w:t>" + text + "</w:t></w:r></w:p>"
@pytest.mark.parametrize("body", [
"<w:tbl><w:tr><w:tc><w:sdt><w:sdtContent>" + p("ماده 12: استثنا") + "</w:sdtContent></w:sdt></w:tc></w:tr></w:tbl>",
"<w:tbl><w:sdt><w:sdtContent><w:tr><w:tc>" + p("ماده 12") + "</w:tc></w:tr></w:sdtContent></w:sdt></w:tbl>",
"<w:tbl><w:tr><w:customXml><w:tc>" + p("ماده 12") + "</w:tc></w:customXml></w:tr></w:tbl>",
])
def test_visible_wrapped_table_content_never_disappears(profile, body):
# Explicit rejection is allowed; returning only the prefix is not.
try:
value = extract(docx(p("Prefix") + body), profile, DOCX_MIME)
except ExtractionError:
return
assert "ماده 12" in "".join(b.text for b in value.blocks)
def test_no_break_hyphen_retained_in_date_identifier(profile):
value = extract(docx("<w:p><w:r><w:t>1403</w:t><w:noBreakHyphen/><w:t>01</w:t>"
"<w:noBreakHyphen/><w:t>02 قرارداد‌</w:t></w:r></w:p>"), profile, DOCX_MIME)
assert value.blocks[0].text == "1403\u201101\u201102 قرارداد‌\n"
@pytest.mark.parametrize("element", ["softHyphen", "ptab", "footnoteReference", "ruby", "unknownVisible"])
def test_run_character_is_preserved_or_document_rejected(profile, element):
try:
value = extract(docx("<w:p><w:r><w:t>12</w:t><w:" + element + "/><w:t>34</w:t></w:r></w:p>"), profile, DOCX_MIME)
except ExtractionError:
return
assert element == "softHyphen" and value.blocks[0].text == "12\u00ad34\n"
@pytest.mark.parametrize("inherited", [False, True, "default"])
def test_valid_automatic_article_number_never_disappears(profile, inherited):
numbering = """<w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:start w:val="12"/><w:numFmt w:val="decimal"/>
<w:lvlText w:val="ماده %1"/></w:lvl></w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>"""
numpr = '<w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr>'
extra = {"word/numbering.xml": numbering.encode()}
if inherited:
attrs = ' w:default="1"' if inherited == "default" else ""
styles = '<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:style w:type="paragraph" w:styleId="Base"' + attrs + '><w:pPr>' + numpr + '</w:pPr></w:style><w:style w:type="paragraph" w:styleId="Child"><w:basedOn w:val="Base"/></w:style></w:styles>'
extra["word/styles.xml"] = styles.encode()
pr = '' if inherited == "default" else '<w:pStyle w:val="Child"/>'
else:
pr = numpr
content = docx('<w:p><w:pPr>' + pr + '</w:pPr><w:r><w:t>قرارداد شامل استثنا نیست.</w:t></w:r></w:p>', extra)
try:
value = extract(content, profile, DOCX_MIME)
except ExtractionError:
return
assert "ماده 12" in value.blocks[0].text
def envelope(profile, blocks):
return ExtractionEnvelope(document_id=uuid4(), title="Fixture", original_sha256="a" * 64,
extraction_profile_sha256=extraction_profile_digest(profile), normalization_policy=profile["normalizer"],
complete=True, quality_decision="reviewed", blocks=tuple(blocks))
def block(ordinal, text, *, page=1, method="direct_pdf", group=None, parent=None, kind="paragraph"):
locator = f"pdf/page/{page}/block/{ordinal}"
return ExtractedBlock(ordinal=ordinal, block_id=locator, text=text, page=page, section=locator,
source_locator=locator, method=method, actual_model="fixture-flash" if method == "vision" else None,
group_id=group, parent_block_id=parent, block_type=kind)
@pytest.mark.parametrize("methods", [("direct_pdf", "vision"), ("vision", "direct_pdf"), ("vision", "vision")])
def test_rule_dependency_crosses_pages_methods_and_groups(profile, methods):
first = block(0, "Article 12: decision 1403/01/02; 12.5%.", method=methods[0], group="rule")
note = block(1, "Notes: not eligible for excluded cases.", page=2, method=methods[1], group="note")
value = envelope(profile, [first, note])
chunks = chunk_extraction(value, profile)
assert len(chunks) == 1 and chunks[0].page is None
assert all(b.source_locator in chunks[0].section for b in value.blocks)
assert chunks[0].text.index("Article 12") < chunks[0].text.index("Notes")
small = deepcopy(profile); small["chunk_size"] = 70; small["overlap"] = 10
with pytest.raises(ExtractionError, match="Semantic"):
chunk_extraction(value, small)
def test_orphan_note_association_fails(profile):
value = envelope(profile, [block(0, "Notes: not available.", group="note", method="vision")])
with pytest.raises(ExtractionError):
chunk_extraction(value, profile)
@pytest.mark.parametrize("heading", ["Notes", "یادداشت‌ها", "تبصره‌های ماده 12", "استثنائات", "شرایط و استثناها"])
def test_dependent_heading_stays_with_rule(profile, heading):
value = extract(("# Article 12\nRule applies.\n\n# " + heading + "\nExcluded 12.5% is not eligible.").encode(), profile)
assert len(chunk_extraction(value, profile)) == 1
@pytest.mark.parametrize("heading", ["Notebook", "NotesArchive", "یادداشت‌برداری", "شرایط‌سازی", "New article"])
def test_unrelated_headings_remain_boundaries(profile, heading):
value = extract(("# Article 12\nRule applies.\n\n# " + heading + "\nOther topic.").encode(), profile)
assert len(chunk_extraction(value, profile)) == 2
class ManyPageVision:
def __init__(self, text="سلام"):
self.calls = []; self.text = text
def transcribe(self, image, *, page, section, processing_profile):
self.calls.append(page)
return (ExtractedBlock(ordinal=0, block_id=section + "/block", text=self.text,
source_locator=section + "/block", section=section, page=page,
method="vision", actual_model="fixture-flash"),)
@pytest.mark.parametrize("limit", ["max_normalized_characters", "max_extracted_blocks"])
def test_cumulative_fallback_budget_stops_before_next_provider_page(profile, monkeypatch, limit):
# Test fixture bypasses manual review only, isolating cumulative page budgeting.
monkeypatch.setattr(PageBlockExtractor, "_review", lambda self, blocks, *a: blocks)
profile = deepcopy(profile)
if limit == "max_extracted_blocks":
profile["extraction"][limit] = 1
else:
profile["limits"][limit] = 6
content = pdf_bytes([[("image", image_bytes(), 30, 40)]] * 3)
vision = ManyPageVision()
with pytest.raises(ExtractionError):
extract(content, profile, "application/pdf", vision=vision)
assert vision.calls == [1, 2]
@pytest.mark.parametrize("metadata", ["x" * 3000, '"' * 1000, "😀" * 600])
def test_oversized_page_metadata_fails_before_next_provider(profile, monkeypatch, metadata):
monkeypatch.setattr(PageBlockExtractor, "_review", lambda self, blocks, *a: blocks)
profile = deepcopy(profile); profile["extraction"]["max_extraction_artifact_bytes"] = 2000
class HugeMetadata(ManyPageVision):
def transcribe(self, *a, **kw):
value = super().transcribe(*a, **kw)[0]
return (value.model_copy(update={"heading": metadata}),)
vision = HugeMetadata()
content = pdf_bytes([[("image", image_bytes(), 30, 40)]] * 2)
with pytest.raises(ValueError):
extract(content, profile, "application/pdf", vision=vision)
assert vision.calls == [1]
@pytest.mark.parametrize("mime,text", [
("text/plain", "سؤال: تاریخ؟\r\nپاسخ: 1403/01/02 نیست مگر استثنا.\r\n"),
("text/markdown", "**Question:** Date?\n\n**Answer:** 1403/01/02; not excluded.\n")])
def test_labelled_readable_faq_preserves_pair_and_purpose(profile, mime, text):
value = extract(text.encode(), profile, mime)
assert [b.block_type for b in value.blocks] == ["question", "answer"]
assert "".join(b.text for b in value.blocks) == text
assert value.blocks[0].group_id == value.blocks[1].group_id
with pytest.raises(ExtractionError):
chunk_extraction(value, profile)
assert len(chunk_extraction(value, profile, corpus_purpose="approved_factual")) == 1
small = deepcopy(profile); small["chunk_size"] = 25; small["overlap"] = 5
with pytest.raises(ExtractionError, match="Semantic"):
chunk_extraction(value, small, corpus_purpose="approved_factual")
@pytest.mark.parametrize("text", ["سؤال: تنها؟", "Answer: no question", "Q: First?\nQ: second?\nA: answer"])
def test_incomplete_readable_faq_fails(profile, text):
with pytest.raises(ExtractionError):
extract(text.encode(), profile)
@pytest.mark.parametrize("late_phase", ["open", "read", "eof"])
def test_absolute_provider_deadline_checked_after_blocking_operations(profile, monkeypatch, late_phase):
# Both first data read and EOF can return after the absolute deadline.
clock = [0.]
monkeypatch.setattr("app.infrastructure.gemini_vision.time.monotonic", lambda: clock[0])
native = {"modelVersion": "fixture-flash", "candidates": [{"finishReason": "STOP", "content": {"parts": [
{"text": json.dumps({"complete": True, "warnings": [], "blocks": [
block(0, "Text", page=None, method="vision").model_copy(update={"source_locator": "image/block"}).model_dump(mode="json")]})}]}}]}
class Response(BytesIO):
def read(self, amount=-1):
result = super().read(amount)
if late_phase == "read" or (late_phase == "eof" and not result):
clock[0] = 61.
return result
class Opener:
def open(self, *a, **kw):
if late_phase == "open": clock[0] = 61.
return Response(json.dumps(native).encode())
monkeypatch.setattr("urllib.request.build_opener", lambda *a: Opener())
adapter = GeminiVision(endpoint="https://fixture.invalid/v1beta", model="fixture-flash", api_key="secret", timeout_seconds=60)
with pytest.raises(ExtractionProviderError) as error:
adapter.transcribe(image_bytes(), page=None, section="image", processing_profile=profile)
assert error.value.retryable and "secret" not in str(error.value)
@pytest.mark.parametrize("phase", ["open", "read", "eof"])
def test_absolute_deadline_returns_during_blocked_open(profile, monkeypatch, phase):
release, entered = Event(), Event()
class Opener:
def open(self, *a, **kw):
if phase == "open":
entered.set()
release.wait(3)
raise TimeoutError("secret")
class Response(BytesIO):
def read(self, amount=-1):
entered.set()
release.wait(3)
return b"" if phase == "eof" else b"late data"
return Response()
monkeypatch.setattr("urllib.request.build_opener", lambda *a: Opener())
profile = deepcopy(profile); profile["extraction"]["vision"]["timeout_seconds"] = .3
adapter = GeminiVision(endpoint="https://fixture.invalid/v1beta", model="fixture-flash", api_key="secret", timeout_seconds=.3)
started = time.monotonic()
try:
with pytest.raises(ExtractionProviderError) as error:
adapter.transcribe(image_bytes(), page=None, section="image", processing_profile=profile)
elapsed = time.monotonic() - started
finally:
release.set()
assert entered.is_set() and elapsed < 1.5 and error.value.retryable
def test_exact_chunk_boundary_single_block_no_trailing_newline(profile):
profile = deepcopy(profile); profile["chunk_size"] = 10; profile["overlap"] = 2
value = extract(b"0123456789", profile)
chunks = chunk_extraction(value, profile)
assert len(chunks) == 1 and chunks[0].text == "0123456789"
def test_note_explicitly_referring_to_another_article_is_ambiguous(profile):
value = envelope(profile, [block(0, "Article 12: rule.", group="rule"),
block(1, "Notes for Article 11: excluded.", page=2, group="note")])
with pytest.raises(ExtractionError):
chunk_extraction(value, profile)
def test_note_after_unrelated_group_cannot_be_attached_to_earlier_rule(profile):
value = envelope(profile, [block(0, "Article 12: rule.", group="rule"),
block(1, "Unrelated topic.", group="unrelated"),
block(2, "Notes: excluded.", page=2, group="note")])
with pytest.raises(ExtractionError):
chunk_extraction(value, profile)
def test_numbered_doc_defaults_cannot_disappear(profile):
styles = """<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:docDefaults><w:pPrDefault><w:pPr><w:numPr><w:numId w:val="1"/></w:numPr></w:pPr></w:pPrDefault></w:docDefaults>
</w:styles>"""
with pytest.raises(ExtractionError):
extract(docx(p("Rule"), {"word/styles.xml": styles.encode()}), profile, DOCX_MIME)
@pytest.mark.parametrize("limit", ["max_normalized_characters", "max_extracted_blocks"])
def test_direct_page_and_fallback_share_cumulative_budget(profile, monkeypatch, limit):
monkeypatch.setattr(PageBlockExtractor, "_review", lambda self, blocks, *a: blocks)
profile = deepcopy(profile)
if limit == "max_extracted_blocks":
profile["extraction"][limit] = 1
else:
profile["limits"][limit] = 6
content = pdf_bytes([[("text", "Text", 30, 40)],
[("image", image_bytes(), 30, 40)],
[("image", image_bytes(), 30, 40)]])
vision = ManyPageVision()
with pytest.raises(ExtractionError):
extract(content, profile, "application/pdf", vision=vision)
assert vision.calls == [2]
@pytest.mark.parametrize("leading", ["\n", "\r\n"])
def test_existing_following_block_separator_is_not_duplicated(profile, leading):
value = envelope(profile, [block(0, "abc"), block(1, leading + "def")])
chunks = chunk_extraction(value, profile)
assert len(chunks) == 1 and chunks[0].text == "abc" + leading + "def"
@pytest.mark.parametrize("condition", ["Conditions: only approved cases.", "Exceptions: excluded cases.",
"Provided that 12.5% is approved.", "به شرط تأیید؛ مگر استثنا."])
def test_conditions_and_exclusions_cross_source_group_boundary(profile, condition):
value = envelope(profile, [block(0, "Article 12: rule.", group="rule"),
block(1, condition, page=2, method="vision", group="conditions")])
chunks = chunk_extraction(value, profile)
assert len(chunks) == 1 and condition in chunks[0].text
def test_unlabelled_continuation_at_source_group_boundary_is_ambiguous(profile):
value = envelope(profile, [block(0, "Article 12: rule.", group="rule"),
block(1, "Additional text with no governing locator.", page=2, group="unknown")])
with pytest.raises(ExtractionError):
chunk_extraction(value, profile)
+297
View File
@@ -0,0 +1,297 @@
"""Scoped semantic evidence, full identifiers, structural scope and HTTP cleanup regressions."""
from copy import deepcopy
from io import BytesIO
import json
from queue import Queue
from threading import Event, Thread
from urllib.error import HTTPError
from uuid import uuid4
import pytest
from app.infrastructure.gemini_vision import GeminiVision
from app.modules.documents.chunking import chunk_extraction
from app.modules.documents.extraction import ExtractionError, ExtractionProviderError
from app.modules.documents.extraction_artifacts import extraction_profile_digest
from app.modules.documents.formats import DOCX_MIME
from app.modules.documents.types import ExtractedBlock, ExtractionEnvelope
from tests.support.extraction import extract, FakeVision
from tests.support.formats import docx_bytes, image_bytes
@pytest.fixture
def profile(settings):
return settings.model_copy(update={"vision_provider": "gemini",
"vision_endpoint": "https://fixture.invalid/v1beta", "vision_model": "fixture-flash"}).processing_profile()
NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
def semantic_docx(prop, location, *, reset=False):
resets = {"super": "<w:vertAlign w:val='baseline'/>", "sub": "<w:vertAlign w:val='baseline'/>",
"strike": "<w:strike w:val='false'/>", "dstrike": "<w:dstrike w:val='0'/>"}
formats = {"super": "<w:vertAlign w:val='superscript'/>", "sub": "<w:vertAlign w:val='subscript'/>",
"strike": "<w:strike/>", "dstrike": "<w:dstrike/>",
"ordinary": "<w:b/><w:i/><w:color w:val='123456'/><w:sz w:val='24'/>"}
formatting = formats[prop]
direct, ps, rs, styles = "", "", "", ""
if location == "direct":
direct = formatting
elif location == "defaults":
styles = f"<w:docDefaults><w:rPrDefault><w:rPr>{formatting}</w:rPr></w:rPrDefault></w:docDefaults>"
else:
kind = "character" if "character" in location else "paragraph"
default = " w:default='1'" if location.startswith("default-") else ""
styles = f"<w:style w:type='{kind}' w:styleId='Base'{default}><w:rPr>{formatting}</w:rPr></w:style>"
identity = "Base"
if location.startswith("inherited-"):
styles += f"<w:style w:type='{kind}' w:styleId='Child'><w:basedOn w:val='Base'/></w:style>"
identity = "Child"
if not location.startswith(("default-", "unused-")):
if kind == "paragraph": ps = f"<w:pStyle w:val='{identity}'/>"
else: rs = f"<w:rStyle w:val='{identity}'/>"
if reset:
direct = resets[prop]
# Only the last run is superscript in the direct fixture: displayed 10 cubed.
prefix = "10" if prop in ("super", "sub") else "مجاز "
suffix = "3" if prop in ("super", "sub") else "نیست"
body = (f"<w:p><w:pPr>{ps}</w:pPr><w:r><w:t>{prefix}</w:t></w:r>"
f"<w:r><w:rPr>{rs}{direct}</w:rPr><w:t>{suffix}</w:t></w:r></w:p>")
# Resets on both runs ensure inherited formatting is wholly disabled.
if reset and location != "direct":
body = body.replace(f"<w:r><w:t>{prefix}", f"<w:r><w:rPr>{resets[prop]}</w:rPr><w:t>{prefix}")
extra = {"word/styles.xml": f"<w:styles xmlns:w='{NS}'>{styles}</w:styles>".encode()} if styles else None
return docx_bytes(document=f"<w:document xmlns:w='{NS}'><w:body>{body}</w:body></w:document>".encode(), extra=extra)
@pytest.mark.parametrize("prop", ["super", "sub", "strike", "dstrike"])
@pytest.mark.parametrize("location", ["direct", "defaults", "paragraph", "character",
"inherited-paragraph", "inherited-character", "default-paragraph", "default-character"])
def test_semantic_run_formatting_cannot_be_flattened_into_passed_text(profile, prop, location):
with pytest.raises(ExtractionError):
extract(semantic_docx(prop, location), profile, DOCX_MIME)
@pytest.mark.parametrize("prop", ["super", "sub", "strike", "dstrike"])
@pytest.mark.parametrize("location", ["direct", "defaults", "inherited-paragraph", "inherited-character"])
def test_explicit_semantic_resets_allow_faithful_plain_text(profile, prop, location):
value = extract(semantic_docx(prop, location, reset=True), profile, DOCX_MIME)
assert value.blocks[0].text == ("103\n" if prop in ("super", "sub") else "مجاز نیست\n")
@pytest.mark.parametrize("prop", ["super", "strike"])
def test_unused_semantic_styles_do_not_reject_visible_text(profile, prop):
value = extract(semantic_docx(prop, "unused-character"), profile, DOCX_MIME)
assert value.complete
@pytest.mark.parametrize("location", ["direct", "inherited-paragraph", "defaults"])
def test_harmless_ordinary_formatting_remains_supported(profile, location):
value = extract(semantic_docx("ordinary", location), profile, DOCX_MIME)
assert value.blocks[0].text == "مجاز نیست\n"
IDENTIFIERS = [
("Circular 1403/100", "Circular 1403/200"),
("Article 12.1", "Article 12.2"),
("Clause 1(a)", "Clause 1(b)"),
("بخشنامه ۱۴۰۳/۱۰۰", "بخشنامه ۱۴۰۳/۲۰۰"),
("ماده ۱۲.۱", "ماده ۱۲.۲"),
("بند ۱(الف)", "بند ۱(ب)"),
]
@pytest.mark.parametrize("governing,target", IDENTIFIERS)
def test_complete_identifiers_reject_numeric_prefix_collisions(profile, governing, target):
value = extract((governing + ": rule.\n\nNotes\nApplies only to " + target + ".").encode(), profile)
with pytest.raises(ExtractionError):
chunk_extraction(value, profile)
@pytest.mark.parametrize("governing,target", IDENTIFIERS)
def test_matching_complete_identifiers_preserve_dots_slashes_and_suffixes(profile, governing, target):
source = governing + ": rule.\n\nNotes\nApplies only to " + governing + ". See Article 99 for background."
value = extract(source.encode(), profile)
chunks = chunk_extraction(value, profile)
assert len(chunks) == 1 and chunks[0].text == source
@pytest.mark.parametrize("identifier", ["Article 12-1", "Article XII", "Article 12..1",
"Article 12.a", "Clause 1[a]", "Clause 1(a/b)", "Circular 1403//100", "ماده ۱۲ـ۱"])
def test_unsupported_identifier_forms_fail_explicitly(profile, identifier):
source = identifier + ": rule.\n\nNotes\nApplies only to " + identifier + "."
with pytest.raises(ExtractionError):
chunk_extraction(extract(source.encode(), profile), profile)
def test_identifier_digit_equivalence_does_not_rewrite_evidence(profile):
source = "ماده ۱۲.۱: قانون.\n\nNotes\nApplies only to Article 12.1."
chunks = chunk_extraction(extract(source.encode(), profile), profile)
assert len(chunks) == 1 and chunks[0].text == source
FAQ = ("## Question\nWhat does Article 12 require?\n## Answer\n"
"### Article 12\nRule one.\n#### Conditions\nApplies only to Article 12.\n"
"### Background\nHistorical context concerns Article 99.\n")
def test_single_rule_faq_background_is_outside_dependency_scope(profile):
value = extract(FAQ.encode(), profile)
chunks = chunk_extraction(value, profile, corpus_purpose="approved_factual")
assert len(chunks) == 1 and chunks[0].text == FAQ
assert all(b.source_locator in chunks[0].section for b in value.blocks)
with pytest.raises(ExtractionError):
chunk_extraction(value, profile)
small = deepcopy(profile); small["chunk_size"] = 100; small["overlap"] = 10
with pytest.raises(ExtractionError, match="Semantic"):
chunk_extraction(value, small, corpus_purpose="approved_factual")
@pytest.mark.parametrize("source", [
FAQ.replace("Applies only to Article 12", "Applies only to Article 13"),
FAQ + "#### Exceptions\nApplies only to Article 12.\n",
])
def test_single_rule_faq_conflicting_and_unowned_dependencies_still_fail(profile, source):
with pytest.raises(ExtractionError):
chunk_extraction(extract(source.encode(), profile), profile, corpus_purpose="approved_factual")
def visual(profile, *, target=12, unowned=False):
rows = [("Guide", None, "visual_group"), ("Article 12: rule.", 0, "heading"),
("Conditions", 0 if unowned else 1, "heading"),
(f"Applies only to Article {target}.", 2, "caption"),
("Historical context concerns Article 99.", 0, "caption")]
blocks = tuple(ExtractedBlock(ordinal=i, block_id=f"image/{i}", text=text,
source_locator=f"image/{i}", section=f"image/{i}", method="vision",
actual_model="fixture-flash", group_id="visual", block_type=kind,
heading=text if kind in ("heading", "visual_group") else None,
parent_block_id=f"image/{parent}" if parent is not None else None)
for i, (text,parent,kind) in enumerate(rows))
return ExtractionEnvelope(document_id=uuid4(), title="Fixture", original_sha256="a"*64,
extraction_profile_sha256=extraction_profile_digest(profile),
normalization_policy=profile["normalizer"], complete=True, quality_decision="reviewed", blocks=blocks)
def test_single_rule_visual_background_caption_is_outside_dependency_scope(profile):
value = visual(profile)
chunks = chunk_extraction(value, profile)
assert len(chunks) == 1 and chunks[0].text == "\n".join(b.text for b in value.blocks)
assert all(b.source_locator in chunks[0].section for b in value.blocks)
@pytest.mark.parametrize("target,unowned", [(13, False), (12, True)])
def test_single_rule_visual_dependencies_require_their_ancestor(profile, target, unowned):
with pytest.raises(ExtractionError):
chunk_extraction(visual(profile, target=target, unowned=unowned), profile)
def successful_response(profile):
blocks = FakeVision().transcribe(b"", page=None, section="image", processing_profile=profile)
return json.dumps({"modelVersion":"fixture-flash", "candidates":[{"finishReason":"STOP",
"content":{"parts":[{"text":json.dumps({"complete":True,"warnings":[],
"blocks":[b.model_dump(mode="json") for b in blocks]})}]}}]}).encode()
def adapter_call(profile):
adapter = GeminiVision(endpoint="https://fixture.invalid/v1beta", model="fixture-flash",
api_key="private-secret", timeout_seconds=profile["extraction"]["vision"]["timeout_seconds"])
return adapter.transcribe(image_bytes(), page=None, section="image", processing_profile=profile)
@pytest.mark.parametrize("status,retryable", [(400,False),(401,False),(408,True),(429,True),(503,True)])
@pytest.mark.parametrize("expired", [False,True])
def test_http_error_stream_closed_before_visible_error_even_after_deadline(profile, monkeypatch, status, retryable, expired):
clock = [0.]
if expired:
monkeypatch.setattr("app.infrastructure.gemini_vision.time.monotonic", lambda: clock[0])
stream = BytesIO(b"private provider body")
published, closed_at_publication = Event(), []
class CompletionQueue(Queue):
def put(self, item, *a, **kw):
closed_at_publication.append(stream.closed)
super().put(item, *a, **kw)
published.set()
monkeypatch.setattr("app.infrastructure.gemini_vision.Queue", CompletionQueue)
error = HTTPError("https://fixture.invalid/private-secret", status, "private-secret", {}, stream)
calls = []
class Opener:
def open(self, *a, **kw):
calls.append(1)
if expired: clock[0] = 61.
raise error
monkeypatch.setattr("urllib.request.build_opener", lambda *a: Opener())
try:
with pytest.raises(ExtractionProviderError) as result:
adapter_call(profile)
# Deadline return may precede cleanup; worker publication must not.
assert published.wait(1) and stream.closed and closed_at_publication == [True]
assert result.value.retryable == (True if expired else retryable)
assert "private-secret" not in str(result.value) and len(calls) == 1
finally:
stream.close()
@pytest.mark.parametrize("status,retryable", [(401,False),(429,True)])
@pytest.mark.parametrize("expire_during_cleanup", [False,True])
def test_http_cleanup_retains_capacity_until_stream_close_finishes(profile, monkeypatch, status, retryable, expire_during_cleanup):
entered, release, published, returned = Event(), Event(), Event(), Event()
results, calls = Queue(), []
timeout = .3 if expire_during_cleanup else 60
profile = deepcopy(profile); profile["extraction"]["vision"]["timeout_seconds"] = timeout
class TrackedStream(BytesIO):
def close(self):
if not self.closed:
entered.set()
assert release.wait(4)
super().close()
stream = TrackedStream(b"private body")
error = HTTPError("https://fixture.invalid/private-secret", status, "private-secret", {}, stream)
class Opener:
def open(self, *a, **kw):
calls.append(1)
if len(calls) == 1: raise error
return BytesIO(successful_response(profile))
class CompletionQueue(Queue):
def put(self, item, *a, **kw):
super().put(item, *a, **kw)
published.set()
monkeypatch.setattr("urllib.request.build_opener", lambda *a: Opener())
monkeypatch.setattr("app.infrastructure.gemini_vision.Queue", CompletionQueue)
def first():
try:
results.put(adapter_call(profile))
except Exception as exc:
results.put(exc)
finally:
returned.set()
caller = Thread(target=first)
caller.start()
try:
assert entered.wait(1), "HTTP response cleanup never began"
assert not published.is_set()
if expire_during_cleanup:
assert returned.wait(1), "Caller deadline must bound blocked cleanup"
else:
assert not returned.is_set()
with pytest.raises(ExtractionProviderError, match="capacity") as occupied:
adapter_call(profile)
assert occupied.value.retryable and len(calls) == 1
release.set()
assert published.wait(1) and returned.wait(1)
result = results.get_nowait()
assert isinstance(result, ExtractionProviderError) and stream.closed
assert result.retryable == (True if expire_during_cleanup else retryable)
assert "private-secret" not in str(result)
assert adapter_call(profile) and len(calls) == 2
finally:
release.set()
caller.join(2)
stream.close()
@pytest.mark.parametrize("identifier", ["Circular 1403 /100", "Article 12 .1", "Clause 1 (a)"])
def test_unsupported_spaced_identifier_cannot_collapse_to_numeric_prefix(profile, identifier):
source = identifier + ": rule.\n\nNotes\nApplies only to " + identifier + "."
with pytest.raises(ExtractionError):
chunk_extraction(extract(source.encode(), profile), profile)
@@ -0,0 +1,253 @@
"""Four Phase 3 regressions: visibility, atomic scopes, line endings, completion."""
from copy import deepcopy
from io import BytesIO
import json
from queue import Queue
from threading import Event
from uuid import uuid4
import pytest
from app.infrastructure.gemini_vision import GeminiVision
from app.modules.documents.chunking import chunk_extraction
from app.modules.documents.extraction import ExtractionError, ExtractionProviderError
from app.modules.documents.extraction_artifacts import extraction_profile_digest
from app.modules.documents.formats import DOCX_MIME
from app.modules.documents.normalization import normalize_search_text
from app.modules.documents.types import ExtractedBlock, ExtractionEnvelope
from tests.support.extraction import extract
from tests.support.formats import docx_bytes, image_bytes
@pytest.fixture
def profile(settings):
return settings.model_copy(update={"vision_provider": "gemini",
"vision_endpoint": "https://fixture.invalid/v1beta",
"vision_model": "fixture-flash"}).processing_profile()
NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
def hidden_docx(location, value="", *, direct_override=None):
hide = "<w:vanish" + (f" w:val='{value}'" if value else "") + "/>"
direct, pstyle, rstyle, styles = "", "", "", ""
if location == "direct":
direct = hide
elif location == "defaults":
styles = "<w:docDefaults><w:rPrDefault><w:rPr>" + hide + "</w:rPr></w:rPrDefault></w:docDefaults>"
else:
kind = "character" if "character" in location else "paragraph"
default = " w:default='1'" if location.startswith("default") else ""
styles = f"<w:style w:type='{kind}' w:styleId='Base'{default}><w:rPr>{hide}</w:rPr></w:style>"
style_id = "Base"
if location.startswith("inherited"):
styles += f"<w:style w:type='{kind}' w:styleId='Child'><w:basedOn w:val='Base'/></w:style>"
style_id = "Child"
if not location.startswith(("default", "unused")):
if kind == "paragraph":
pstyle = f"<w:pStyle w:val='{style_id}'/>"
else:
rstyle = f"<w:rStyle w:val='{style_id}'/>"
if direct_override is not None:
direct = f"<w:vanish w:val='{direct_override}'/>"
body = f"<w:p><w:pPr>{pstyle}</w:pPr><w:r><w:rPr>{rstyle}{direct}</w:rPr>"
body += "<w:t xml:space='preserve'>ماده 12: مجاز نیست؛ ي ك ی ک نیم‌فاصله 1403/01/02 </w:t></w:r></w:p>"
extra = {"word/styles.xml": f"<w:styles xmlns:w='{NS}'>{styles}</w:styles>".encode()} if styles else None
return docx_bytes(document=f"<w:document xmlns:w='{NS}'><w:body>{body}</w:body></w:document>".encode(), extra=extra)
@pytest.mark.parametrize("location", ["direct", "defaults", "paragraph", "character",
"inherited-paragraph", "inherited-character", "default-paragraph", "default-character"])
@pytest.mark.parametrize("value", ["", "true"])
def test_effective_hidden_negation_rejected(profile, location, value):
with pytest.raises(ExtractionError):
extract(hidden_docx(location, value), profile, DOCX_MIME)
@pytest.mark.parametrize("value", ["0", "false", "off"])
@pytest.mark.parametrize("location", ["direct", "defaults", "paragraph", "character"])
def test_explicit_disabled_hiding_preserves_faithful_text(profile, location, value):
result = extract(hidden_docx(location, value), profile, DOCX_MIME)
assert result.blocks[0].text == "ماده 12: مجاز نیست؛ ي ك ی ک نیم‌فاصله 1403/01/02 \n"
@pytest.mark.parametrize("location", ["defaults", "inherited-paragraph", "inherited-character"])
def test_direct_disabled_hiding_overrides_inherited_hidden(profile, location):
result = extract(hidden_docx(location, direct_override="false"), profile, DOCX_MIME)
assert "مجاز نیست" in result.blocks[0].text
def test_unused_hidden_style_does_not_hide_ordinary_text(profile):
result = extract(hidden_docx("unused-paragraph"), profile, DOCX_MIME)
assert result.complete and "مجاز نیست" in result.blocks[0].text
def faq_text(target=12, *, ambiguous=False):
middle = "### Independent subsection\n" if ambiguous else ""
return ("## Question\nWhat do Articles 12 and 13 require?\n## Answer\nDetails follow.\n"
"### Article 12\nRule one.\n" + middle +
f"#### Conditions\nApplies only to Article {target}. See Article 99 for background.\n"
"### Article 13\nRule two.\n#### Exceptions\nApplies only to Article 13; not excluded.\n")
def test_multiple_faq_rules_scope_nested_dependencies_and_stay_atomic(profile):
text = faq_text()
value = extract(text.encode(), profile)
chunks = chunk_extraction(value, profile, corpus_purpose="approved_factual")
assert len(chunks) == 1 and chunks[0].text == text
assert chunks == chunk_extraction(value, profile, corpus_purpose="approved_factual")
assert all(b.source_locator in chunks[0].section for b in value.blocks)
with pytest.raises(ExtractionError):
chunk_extraction(value, profile)
small = deepcopy(profile); small["chunk_size"] = 100; small["overlap"] = 10
with pytest.raises(ExtractionError, match="Semantic"):
chunk_extraction(value, small, corpus_purpose="approved_factual")
@pytest.mark.parametrize("target,ambiguous", [(13, False), (12, True)])
def test_faq_scopes_reject_conflicts_and_unowned_dependencies(profile, target, ambiguous):
value = extract(faq_text(target, ambiguous=ambiguous).encode(), profile)
with pytest.raises(ExtractionError):
chunk_extraction(value, profile, corpus_purpose="approved_factual")
def visual(profile, *, target=12, unowned=False):
rows = [("Guide", None, "visual_group"),
("Article 12: rule one.", 0, "heading"),
("Article 13: rule two.", 0, "heading"),
("Conditions", 0 if unowned else 1, "heading"),
(f"Applies only to Article {target}. See Article 99 for background.", 3, "caption"),
("Exceptions: Applies only to Article 13.", 2, "caption")]
blocks = tuple(ExtractedBlock(ordinal=i, block_id=f"image/{i}", text=text,
source_locator=f"image/{i}", section=f"image/{i}", page=None,
method="vision", actual_model="fixture-flash", block_type=kind,
heading=text if kind in ("heading", "visual_group") else None,
group_id="visual", parent_block_id=f"image/{parent}" if parent is not None else None)
for i, (text, parent, kind) in enumerate(rows))
return ExtractionEnvelope(document_id=uuid4(), title="Fixture", original_sha256="a"*64,
extraction_profile_sha256=extraction_profile_digest(profile),
normalization_policy=profile["normalizer"], complete=True, quality_decision="reviewed", blocks=blocks)
def test_visual_tree_uses_explicit_ancestor_not_last_rule_and_stays_atomic(profile):
value = visual(profile)
chunks = chunk_extraction(value, profile)
assert len(chunks) == 1
assert chunks[0].text == "\n".join(b.text for b in value.blocks)
assert all(b.source_locator in chunks[0].section for b in value.blocks)
assert chunks == chunk_extraction(value, profile)
small = deepcopy(profile); small["chunk_size"] = 60; small["overlap"] = 10
with pytest.raises(ExtractionError, match="Semantic"):
chunk_extraction(value, small)
@pytest.mark.parametrize("target,unowned", [(13, False), (12, True)])
def test_visual_dependencies_cannot_cross_sibling_branches(profile, target, unowned):
with pytest.raises(ExtractionError):
chunk_extraction(visual(profile, target=target, unowned=unowned), profile)
@pytest.mark.parametrize("ending", ["\n", "\r\n", "\r"])
def test_article_paragraph_boundaries_preserve_all_supported_line_endings(profile, ending):
lf = "Article 12\n نیست؛ ي ك 1403/01/02 نیم‌فاصله\n\nArticle 13\n شرط 12.5% محفوظ است.\n"
profile = deepcopy(profile); profile["chunk_size"] = 55; profile["overlap"] = 5
source = lf.replace("\n", ending)
value = extract(source.encode(), profile)
reference = extract(lf.encode(), profile)
chunks = chunk_extraction(value, profile)
assert len(chunks) == 2
assert "".join(b.text for b in value.blocks) == source
assert "".join(c.text for c in chunks) == source
assert "".join(b.search_text for b in value.blocks) == normalize_search_text(lf)
assert [b.source_locator for b in value.blocks] == [b.source_locator for b in reference.blocks]
assert [normalize_search_text(c.text) for c in chunks] == [
normalize_search_text(c.text) for c in chunk_extraction(reference, profile)]
assert [c.ordinal for c in chunks] == [0, 1]
assert all(len(normalize_search_text(c.text)) <= 55 for c in chunks)
assert all(c.page is None for c in chunks)
assert chunks == chunk_extraction(value, profile)
def response_bytes():
block = ExtractedBlock(ordinal=0, block_id="image/0", text="Successful transcription",
source_locator="image/0", method="vision", actual_model="fixture-flash")
transcript = {"complete": True, "warnings": [], "blocks": [block.model_dump(mode="json")]}
return json.dumps({"modelVersion": "fixture-flash", "candidates": [{"finishReason": "STOP",
"content": {"parts": [{"text": json.dumps(transcript)}]}}]}).encode()
@pytest.mark.parametrize("first_fails", [False, True])
def test_transport_releases_before_publishing_completion(profile, monkeypatch, first_fails):
# Pause the first worker immediately after the result becomes observable.
# The next sequential call must succeed before that worker resumes.
resume, exited, closed = Event(), Event(), Event()
calls, queues = [], []
class ScheduledQueue(Queue):
def __init__(self, *a, **kw):
super().__init__(*a, **kw)
self.first = not queues
queues.append(self)
def put(self, value, *a, **kw):
super().put(value, *a, **kw)
if self.first:
try:
assert resume.wait(5)
finally:
exited.set()
class Response(BytesIO):
def close(self):
super().close()
closed.set()
class Opener:
def open(self, *a, **kw):
calls.append(1)
if first_fails and len(calls) == 1:
raise TimeoutError("private-secret")
return Response(response_bytes())
monkeypatch.setattr("app.infrastructure.gemini_vision.Queue", ScheduledQueue)
monkeypatch.setattr("urllib.request.build_opener", lambda *a: Opener())
def call():
adapter = GeminiVision(endpoint="https://fixture.invalid/v1beta", model="fixture-flash",
api_key="private-secret", timeout_seconds=60)
return adapter.transcribe(image_bytes(), page=None, section="image", processing_profile=profile)
try:
if first_fails:
with pytest.raises(ExtractionProviderError) as error:
call()
assert error.value.retryable and "private-secret" not in str(error.value)
else:
assert call()[0].text == "Successful transcription"
assert closed.is_set()
assert not exited.is_set()
assert call()[0].text == "Successful transcription"
assert len(calls) == 2
finally:
resume.set()
assert exited.wait(1)
@pytest.mark.parametrize("child_value,hidden", [("false", True), ("true", False)])
def test_style_vanish_is_a_toggle_but_false_does_not_cancel_inheritance(profile, child_value, hidden):
body = "<w:p><w:r><w:rPr><w:rStyle w:val='Child'/></w:rPr><w:t>Not allowed</w:t></w:r></w:p>"
styles = (f"<w:styles xmlns:w='{NS}'><w:style w:type='character' w:styleId='Base'>"
"<w:rPr><w:vanish/></w:rPr></w:style><w:style w:type='character' w:styleId='Child'>"
f"<w:basedOn w:val='Base'/><w:rPr><w:vanish w:val='{child_value}'/></w:rPr></w:style></w:styles>")
content = docx_bytes(document=f"<w:document xmlns:w='{NS}'><w:body>{body}</w:body></w:document>".encode(),
extra={"word/styles.xml": styles.encode()})
if hidden:
with pytest.raises(ExtractionError):
extract(content, profile, DOCX_MIME)
else:
assert extract(content, profile, DOCX_MIME).blocks[0].text == "Not allowed\n"
def test_mixed_line_endings_never_split_crlf_or_rewrite_faithful_evidence(profile):
source = "Article 12\r\n Not allowed.\r\n \rArticle 13\r Unless approved.\n"
profile = deepcopy(profile); profile["chunk_size"] = 35; profile["overlap"] = 5
result = extract(source.encode(), profile)
chunks = chunk_extraction(result, profile)
assert len(chunks) == 2 and "".join(c.text for c in chunks) == source
assert "".join(b.search_text for b in result.blocks) == normalize_search_text(source)
assert all(b.search_text == normalize_search_text(b.text) for b in result.blocks)
assert all(len(normalize_search_text(c.text)) <= 35 for c in chunks)