"""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": "", "sub": "", "strike": "", "dstrike": ""} formats = {"super": "", "sub": "", "strike": "", "dstrike": "", "ordinary": ""} formatting = formats[prop] direct, ps, rs, styles = "", "", "", "" if location == "direct": direct = formatting elif location == "defaults": styles = f"{formatting}" else: kind = "character" if "character" in location else "paragraph" default = " w:default='1'" if location.startswith("default-") else "" styles = f"{formatting}" identity = "Base" if location.startswith("inherited-"): styles += f"" identity = "Child" if not location.startswith(("default-", "unused-")): if kind == "paragraph": ps = f"" else: rs = f"" 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"{ps}{prefix}" f"{rs}{direct}{suffix}") # Resets on both runs ensure inherited formatting is wholly disabled. if reset and location != "direct": body = body.replace(f"{prefix}", f"{resets[prop]}{prefix}") extra = {"word/styles.xml": f"{styles}".encode()} if styles else None return docx_bytes(document=f"{body}".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)