"""Regression evidence for the three scoped Phase 5 backend repairs.""" import hashlib from uuid import uuid4 import pytest from app.modules.documents.extraction import PageBlockExtractor, ReviewApproval, REVIEW_CHECKS, ReviewRequired from app.modules.documents.review import factual_groups, factual_digest, prepare_chunks from app.modules.documents.worker import validate_source from tests.support.extraction import FakeVision from tests.support.formats import image_bytes def factual(content, settings): profile = settings.model_copy(update={"chunk_size_characters": 2000}).processing_profile() raw = content.encode() envelope = PageBlockExtractor().extract_for_review(document_id=uuid4(), title="facts", original_sha256=hashlib.sha256(raw).hexdigest(), content=raw, mime_type="text/markdown", processing_profile=profile) state = {"factual_inclusion": dict(decision="approve", reviewer=str(uuid4()), artifact_sha256="a" * 64, evidence_sha256=factual_digest("a" * 64, envelope), excluded_group_ids=[])} return raw, profile, envelope, state def test_eligibility_context_survives_all_pairs_approved(settings): raw, profile, envelope, state = factual("## Eligibility\nThese answers apply only to permanent employees.\nQuestion: allowance?\nAnswer: The allowance is 5%.\n", settings) chunks = prepare_chunks(envelope, profile, state, "a" * 64) assert len(chunks) == 1 assert "## Eligibility" in chunks[0].text assert "only to permanent employees" in chunks[0].text assert all(b.source_locator in chunks[0].section for b in envelope.blocks) assert "".join(b.text for b in envelope.blocks).encode() == raw def test_negated_unreadability_review_note_is_not_quality_flag(settings): profile = settings.model_copy(update={"vision_provider": "fixture", "vision_endpoint": "https://fixture.invalid/v1", "vision_model": "fixture-flash"}).processing_profile() raw = image_bytes("PNG") kwargs = dict(document_id=uuid4(), title="review", original_sha256=hashlib.sha256(raw).hexdigest(), content=raw, mime_type="image/png", processing_profile=profile) vision = FakeVision(text="Readable evidence") with pytest.raises(ReviewRequired) as required: PageBlockExtractor(vision).extract(**kwargs) approval = ReviewApproval(required.value.evidence_sha256, "trusted-reviewer", "No unreadable regions; checked all fields.", REVIEW_CHECKS) envelope = PageBlockExtractor(vision, reviews=(approval,)).extract(**kwargs) validate_source(envelope, dict(id=kwargs["document_id"], title="review", mime_type="image/png", processing_profile=profile), raw) def test_multiple_pairs_share_the_governing_condition(settings): _, profile, envelope, state = factual("## Eligibility\nThese answers apply only to permanent employees.\nQuestion: allowance?\nAnswer: 5%.\nQuestion: leave?\nAnswer: 10 days.\n", settings) chunks = prepare_chunks(envelope, profile, state, "a" * 64) assert len(chunks) == 2 for chunk in chunks: assert "## Eligibility" in chunk.text and "only to permanent employees" in chunk.text assert envelope.blocks[0].source_locator in chunk.section assert "allowance" in chunks[0].text and "leave" in chunks[1].text def test_section_conditions_and_exceptions_do_not_leak_to_siblings(settings): raw, profile, envelope, state = factual("# Benefits\nApplies only to permanent employees.\n## Allowances\nContractors are not eligible; except approved interns.\nQuestion: rate?\nAnswer: 5%.\n## Leave\nOnly after one year; unless probation continues.\nQuestion: days?\nAnswer: 10.\n", settings) first, second = prepare_chunks(envelope, profile, state, "a" * 64) assert "permanent employees" in first.text and "permanent employees" in second.text assert "Contractors are not eligible" in first.text and "except approved interns" in first.text assert "probation" not in first.text and "Contractors" not in second.text assert "Only after one year; unless probation continues." in second.text assert "".join(b.text for b in envelope.blocks).encode() == raw def test_excluded_pairs_and_exclusive_context_are_absent(settings): _, profile, envelope, state = factual("# Benefits\nOnly permanent employees.\n## Factual\nOnly after one year.\nQuestion: fee?\nAnswer: 5%.\n## Behavioral\nUse scripted welcoming tone.\nQuestion: greeting?\nAnswer: scripted welcome.\n## Balance\nQuestion: amount?\nAnswer: \n", settings) excluded = [b.group_id for b in envelope.blocks if b.block_type == "question" and "fee" not in b.text] state["factual_inclusion"]["excluded_group_ids"] = excluded chunk, = prepare_chunks(envelope, profile, state, "a" * 64) assert "Only permanent employees" in chunk.text and "Only after one year" in chunk.text assert all(x not in chunk.text for x in ("Behavioral", "scripted", "Balance", "placeholder")) assert "" in "".join(b.text for b in envelope.blocks) @pytest.mark.parametrize("content", [ "## Eligibility\nQuestion: fee?\nAnswer: 5%.\n## Exceptions\nContractors are not eligible.\n", "Question: fee?\nAnswer: 5%.\nArticle 2\nOnly permanent employees.\nQuestion: leave?\nAnswer: 10.\n", ]) def test_ambiguous_context_fails_visibly_even_when_all_pairs_approved(settings, content): from app.modules.documents.extraction import ExtractionError _, profile, envelope, state = factual(content, settings) with pytest.raises(ExtractionError): prepare_chunks(envelope, profile, state, "a" * 64) def test_selection_cannot_hide_noncontiguous_groups(settings): from app.modules.documents.extraction import ExtractionError _, profile, envelope, state = factual("Question: fee?\nAnswer: 5%.\nQuestion: greeting?\nAnswer: scripted.\n", settings) first, answer, second, other = envelope.blocks # Both pairs remain complete, but the first pair is no longer contiguous. reordered = tuple(b.model_copy(update={"ordinal": i}) for i, b in enumerate((first, second, other, answer))) bad = envelope.model_copy(update={"blocks": reordered}) state["factual_inclusion"]["excluded_group_ids"] = [first.group_id] with pytest.raises(ExtractionError, match="Noncontiguous"): prepare_chunks(bad, profile, state, "a" * 64) def test_selection_cannot_hide_unresolved_dependency(settings): from app.modules.documents.extraction import ExtractionError _, profile, envelope, state = factual("Question: fee?\nAnswer: 5%.\nQuestion: greeting?\nAnswer: scripted.\n", settings) group = envelope.blocks[-1].group_id bad_answer = envelope.blocks[-1].model_copy(update={"text": "Article 1\nException: Article 2 applies.\n", "search_text": None}) bad = envelope.model_copy(update={"blocks": (*envelope.blocks[:-1], bad_answer)}) state["factual_inclusion"]["excluded_group_ids"] = [group] with pytest.raises(ExtractionError, match="Ambiguous"): prepare_chunks(bad, profile, state, "a" * 64) def test_governing_placeholder_cannot_be_approved(settings): from app.modules.documents.extraction import ExtractionError from app.modules.documents.normalization import normalize_search_text _, profile, envelope, state = factual("## Eligibility\nOnly permanent employees.\nQuestion: fee?\nAnswer: 5%.\n", settings) changed = envelope.blocks[0].model_copy(update={"text": "## Eligibility\nOnly .\n", "search_text": normalize_search_text("## Eligibility\nOnly .\n")}) bad = envelope.model_copy(update={"blocks": (changed, *envelope.blocks[1:])}) with pytest.raises(ExtractionError, match="Placeholder"): prepare_chunks(bad, profile, state, "a" * 64) @pytest.mark.parametrize("note", ["No unreadable regions; checked all fields.", "\u0647\u06cc\u0686 \u0628\u062e\u0634 \u0646\u0627\u062e\u0648\u0627\u0646\u0627 \u0646\u06cc\u0633\u062a.", "checked " * 249]) def test_resume_keeps_note_once_as_bounded_metadata(settings, note): from app.modules.documents.extraction import ExtractionError from app.modules.documents.extraction_artifacts import serialize_artifact profile = settings.model_copy(update={"vision_provider": "fixture", "vision_endpoint": "https://fixture.invalid/v1", "vision_model": "fixture-flash"}).processing_profile() raw = image_bytes("PNG") kwargs = dict(document_id=uuid4(), title="review", original_sha256=hashlib.sha256(raw).hexdigest(), content=raw, mime_type="image/png", processing_profile=profile) vision = FakeVision(text="Readable evidence") with pytest.raises(ReviewRequired) as required: PageBlockExtractor(vision).extract(**kwargs) evidence = required.value body = dict(evidence_sha256=evidence.evidence_sha256, blocks=[b.model_dump(mode="json") for b in evidence.blocks], reasons=list(evidence.reasons)) decision = dict(decision="approve", reviewer="trusted-reviewer", checked=list(REVIEW_CHECKS), note=note, evidence_sha256=evidence.evidence_sha256) calls = len(vision.calls) envelope = PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs) assert len(vision.calls) == calls annotation, = envelope.review_annotations assert annotation.note == note and annotation.reviewer == "trusted-reviewer" assert annotation.checked == REVIEW_CHECKS and annotation.evidence_sha256 == evidence.evidence_sha256 assert all(note not in b.warnings for b in envelope.blocks) validate_source(envelope, dict(title="review", mime_type="image/png", processing_profile=profile), raw) serialized = serialize_artifact(envelope, profile) limited = {**profile, "extraction": {**profile["extraction"], "max_extraction_artifact_bytes": len(serialized) - 1}} with pytest.raises(ValueError, match="byte limit"): serialize_artifact(envelope, limited) decision["note"] = "x" * 2001 with pytest.raises(ValueError): PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs) body["blocks"][0]["text"] = "\ufffd" decision["note"] = note with pytest.raises(ExtractionError, match="Unreadable"): PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs)