"""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 = "" direct, pstyle, rstyle, styles = "", "", "", "" if location == "direct": direct = hide elif location == "defaults": styles = "" + hide + "" else: kind = "character" if "character" in location else "paragraph" default = " w:default='1'" if location.startswith("default") else "" styles = f"{hide}" style_id = "Base" if location.startswith("inherited"): styles += f"" style_id = "Child" if not location.startswith(("default", "unused")): if kind == "paragraph": pstyle = f"" else: rstyle = f"" if direct_override is not None: direct = f"" body = f"{pstyle}{rstyle}{direct}" body += "ماده 12: مجاز نیست؛ ي ك ی ک نیم‌فاصله 1403/01/02 " extra = {"word/styles.xml": f"{styles}".encode()} if styles else None return docx_bytes(document=f"{body}".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 = "Not allowed" styles = (f"" "" f"") content = docx_bytes(document=f"{body}".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)