"""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=("" "" + body + "").encode(), extra=extra) def p(text): return "" + text + "" @pytest.mark.parametrize("body", [ "" + p("ماده 12: استثنا") + "", "" + p("ماده 12") + "", "" + p("ماده 12") + "", ]) 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("140301" "02 قرارداد‌"), 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("1234"), 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 = """ """ numpr = '' extra = {"word/numbering.xml": numbering.encode()} if inherited: attrs = ' w:default="1"' if inherited == "default" else "" styles = '' + numpr + '' extra["word/styles.xml"] = styles.encode() pr = '' if inherited == "default" else '' else: pr = numpr content = docx('' + pr + 'قرارداد شامل استثنا نیست.', 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 = """ """ 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)