"""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=("" + body + "").encode())
def p(text):
return "" + text + ""
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", [
"1"
"2",
"12",
"12",
"12",
])
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 = "Moved 12"
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 = ""
body += "140301"
body += " قرارداد نیست"
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")