"""Phase 3 extraction/QC/chunk/artifact acceptance, all provider-free.""" from concurrent.futures import ThreadPoolExecutor from copy import deepcopy import hashlib from pathlib import Path from uuid import uuid4 import pytest from app.infrastructure.extraction_candidates import LocalExtractionCandidates from app.infrastructure.file_store import LocalFileStore from app.modules.documents.chunking import chunk_extraction from app.modules.documents.extraction import (ExtractionError, PageBlockExtractor, ReviewApproval, REVIEW_CHECKS, ReviewRequired) from app.modules.documents.extraction_artifacts import LegacyProcessingProfile, validate_artifact from app.modules.documents.formats import DOCX_MIME from app.modules.documents.normalization import normalize_search_text from app.modules.documents.processing import prepare_extraction from tests.support.extraction import extract, inspected_extract, faq_docx, pdf_bytes, FakeVision from tests.support.formats import image_bytes, docx_bytes @pytest.fixture def profile(settings): return settings.model_copy(update={"vision_provider": "fixture", "vision_endpoint": "https://fixture.invalid/v1", "vision_model": "fixture-flash"}).processing_profile() def test_readable_faithful_and_normalized_text(profile): text = "\n ماده 12\r\nقیمت 12.5% در 1403/01/02 نیست؛ ي ك ی ک نیم‌فاصله\r\n\r\nتبصره: مگر استثنا. \r" value = extract(text.encode(), profile) assert "".join(b.text for b in value.blocks) == text assert "".join(b.search_text for b in value.blocks) == normalize_search_text(text) chunks = chunk_extraction(value, profile) assert len(chunks) == 1 assert all(s in chunks[0].text for s in ("12.5%", "1403/01/02", "نیست", "مگر", "ي ك ی ک", "‌")) assert chunks[0].page is chunks[0].token_count is None assert chunks == chunk_extraction(value, profile) def test_frozen_legacy_fails_without_provider_or_rewrite(): profile = {"extractor": "pypdf-markdown-v1", "normalizer": "unicode-line-endings-v1"} before = deepcopy(profile) vision = FakeVision() with pytest.raises(LegacyProcessingProfile): extract(b"text", profile, vision=vision) assert profile == before and not vision.calls @pytest.mark.parametrize("mime,content", [("text/plain", b"\xff"), ("text/plain", b""), ("text/plain", "ناخوانا \ufffd".encode()), ("application/pdf", b"%PDF-1.7\nbroken"), ("bad/type", b"text")]) def test_invalid_extraction_fails(profile, mime, content): with pytest.raises((ExtractionError, ValueError)): extract(content, profile, mime) def test_docx_adjacent_rows_pair_and_preserve_original_order(profile): value = extract(faq_docx(), profile, DOCX_MIME) assert [b.block_type for b in value.blocks] == ["paragraph", "question", "answer", "question", "answer", "answer"] # A table boundary does not establish an end to the last answer. assert value.blocks[-1].group_id == value.blocks[-2].group_id q1, a1, q2, a2 = value.blocks[1:5] assert q1.group_id == a1.group_id != q2.group_id == a2.group_id assert "/row/1/" in q1.source_locator and "/row/2/" in a1.source_locator assert all(b.page is None and b.method == "docx" and b.actual_model is None for b in value.blocks) with pytest.raises(ExtractionError, match="approved"): chunk_extraction(value, profile) chunks = chunk_extraction(value, profile, corpus_purpose="approved_factual") assert len(chunks) == 3 and "سؤال" in chunks[1].text and "پاسخ" in chunks[1].text assert "پنجشنبه تا 12" in chunks[1].text and "1403/01/02" in chunks[2].text def test_docx_two_columns_with_header_and_continuation(profile): body = """ سؤالپاسخ تاریخ؟1403/01/02مگر استثنا """ value = extract(docx_bytes(document=body.encode()), profile, DOCX_MIME) assert len(value.blocks) == 4 and value.blocks[2].group_id == value.blocks[3].group_id assert value.blocks[3].text == "1403/01/02\nمگر استثنا\n" @pytest.mark.parametrize("body", [ "سؤال: بی پاسخ؟", "پاسخ: بدون سوال", "", "hidden"]) def test_docx_incomplete_or_unsupported_fails(profile, body): xml = "" + body + "" with pytest.raises(ExtractionError): extract(docx_bytes(document=xml.encode()), profile, DOCX_MIME) def test_supplied_docx_preserves_all_100_pairs_without_authority_claim(profile): path = next(Path("data/documents").glob("*.docx")) value = extract(path.read_bytes(), profile, DOCX_MIME) questions = [b for b in value.blocks if b.block_type == "question"] answers = [b for b in value.blocks if b.block_type == "answer"] assert len(questions) == len(answers) == 100 assert [b.group_id for b in questions] == [b.group_id for b in answers] with pytest.raises(ExtractionError, match="approved"): chunk_extraction(value, profile) def test_pdf_mixed_pages_direct_and_vision_with_numeric_exclusions(profile): content = pdf_bytes([[("text", "Article 12\nDate 1403/01/02\n12.5% not eligible except note", 30, 40)], [("image", image_bytes(), 30, 40)]]) vision = FakeVision() value = inspected_extract(content, profile, "application/pdf", vision=vision) assert {b.method for b in value.blocks if b.page == 1} == {"direct_pdf"} assert {b.method for b in value.blocks if b.page == 2} == {"vision"} assert all(b.actual_model is None for b in value.blocks if b.page == 1) assert value.quality_decision == "reviewed" and len({call[1] for call in vision.calls}) == 1 direct = "".join(b.text for b in value.blocks if b.page == 1) assert "1403/01/02" in direct and "12.5%" in direct and "not eligible except" in direct chunks = chunk_extraction(value, profile) assert [c.ordinal for c in chunks] == list(range(len(chunks))) assert any("عنوان اصلی" in c.text and "نمی‌شود" in c.text for c in chunks) def test_nonempty_pdf_layer_does_not_prove_complete(profile): content = pdf_bytes([[("text", "Visible text", 30, 40), ("image", image_bytes(), 30, 70)]]) with pytest.raises(ExtractionError, match="vision"): extract(content, profile, "application/pdf") def test_manual_qc_immediate_and_bound_to_exact_evidence(profile): content = pdf_bytes([[("text", "Article 12\n1403/01/02 not except", 30, 40)]]) with pytest.raises(ReviewRequired) as error: extract(content, profile, "application/pdf") request = error.value assert request.image.startswith(b"\x89PNG") and len(request.evidence_sha256) == 64 approval = ReviewApproval(request.evidence_sha256, "reviewer", "Matched visible order and all critical fields", REVIEW_CHECKS) assert extract(content, profile, "application/pdf", reviews=(approval,)).quality_decision == "reviewed" altered = pdf_bytes([[("text", "Article 12\n1403/01/03 not except", 30, 40)]]) with pytest.raises(ReviewRequired): extract(altered, profile, "application/pdf", reviews=(approval,)) incomplete = ReviewApproval(request.evidence_sha256, "reviewer", "numbers only", ("numbers",)) with pytest.raises(ReviewRequired): extract(content, profile, "application/pdf", reviews=(incomplete,)) def test_rejected_direct_reading_order_falls_back_without_guessing(profile): content = pdf_bytes([[("text", "Answer below", 30, 150), ("text", "Question above", 30, 40)]]) with pytest.raises(ReviewRequired) as error: extract(content, profile, "application/pdf") approval = ReviewApproval(error.value.evidence_sha256, "reviewer", "Creator order differs from page", REVIEW_CHECKS, approved=False) vision = FakeVision() with pytest.raises(ReviewRequired) as fallback: extract(content, profile, "application/pdf", reviews=(approval,), vision=vision) assert vision.calls and all(b.method == "vision" for b in fallback.value.blocks) assert "rejected" in fallback.value.reasons[0] @pytest.mark.parametrize("warning", ["unreadable region/right/2", "ناخوانا: گروه 2"]) def test_image_unreadable_regions_fail_before_chunks(profile, warning): with pytest.raises(ExtractionError, match="unreadable"): extract(image_bytes(), profile, "image/jpeg", vision=FakeVision(warnings=(warning,))) def test_infographic_parent_children_and_order(profile): value = inspected_extract(image_bytes(), profile, "image/jpeg", vision=FakeVision()) assert all(b.page is None for b in value.blocks) assert value.blocks[1].parent_block_id == value.blocks[0].block_id chunks = chunk_extraction(value, profile) assert len(chunks) == 1 and "عنوان اصلی" in chunks[0].text and "12.5%" in chunks[0].text assert value.blocks[0].warnings and value.blocks[1].warnings def test_vision_model_alias_mismatch_fails(profile): vision = FakeVision(actual_model="resolved-other") with pytest.raises(ExtractionError, match="identity"): extract(image_bytes(), profile, "image/jpeg", vision=vision) @pytest.mark.parametrize("limit", ["max_pdf_pages", "max_rendered_page_pixels", "max_extracted_blocks", "max_normalized_characters", "max_extraction_artifact_bytes"]) def test_extraction_limits_no_silent_truncation(profile, limit): profile = deepcopy(profile) if limit in profile["extraction"]: profile["extraction"][limit] = 1 else: profile["limits"][limit] = 1 content = pdf_bytes([[("text", "Article 12\nDate 1403/01/02 except", 30, 40)], [("text", "Article 13\nnot eligible", 30, 40)]]) with pytest.raises(ValueError): inspected_extract(content, profile, "application/pdf") def test_deterministic_bounded_generic_chunks_and_atomic_rule_failure(profile): profile = deepcopy(profile) profile["chunk_size"], profile["overlap"] = 100, 15 value = extract(("آغاز‌ " * 50).encode(), profile) chunks = chunk_extraction(value, profile) assert len(chunks) > 1 and all(len(normalize_search_text(c.text)) <= 100 for c in chunks) assert chunks == chunk_extraction(value, profile) assert [c.ordinal for c in chunks] == list(range(len(chunks))) rule = extract(("ماده 12\n" + "شرط " * 40 + "\nتبصره: مگر استثنا").encode(), profile) with pytest.raises(ExtractionError, match="Semantic"): chunk_extraction(rule, profile) profile["limits"]["max_chunks"] = 1 with pytest.raises(ExtractionError, match="count"): chunk_extraction(value, profile) @pytest.mark.parametrize("purpose", ["behavioral_evaluation", "live_data_placeholder"]) def test_corpus_separation(profile, purpose): value = extract(b"Source text", profile) with pytest.raises(ExtractionError, match="knowledge"): chunk_extraction(value, profile, corpus_purpose=purpose) @pytest.mark.parametrize("text", ["Price ", "Rate [TBD]", "مقدار {{tariff}}"]) def test_placeholder_is_not_indexable(profile, text): with pytest.raises(ExtractionError, match="placeholder"): extract(text.encode(), profile) def test_original_and_candidate_retention_concurrent_no_replace(profile, tmp_path): content = "ماده 12\r\nنرخ 12.5% نیست مگر استثنا\r\n".encode() store = LocalFileStore(tmp_path / "originals") key = store.put(content) document = dict(id=uuid4(), title="Original", storage_key=key, size_bytes=len(content), file_sha256=hashlib.sha256(content).hexdigest(), mime_type="text/markdown", processing_profile=profile) candidates = LocalExtractionCandidates(tmp_path / "extractions", original_directory=store.directory) prepared = prepare_extraction(store, candidates, PageBlockExtractor(), document=document) reloaded = LocalExtractionCandidates(candidates.directory, original_directory=store.directory) assert reloaded.inspect(prepared.candidate, processing_profile=profile) == prepared.envelope changed = deepcopy(profile) changed["chunk_size"] = 1500 changed["embedding"]["model"] = "other" assert reloaded.inspect(prepared.candidate, processing_profile=changed) == prepared.envelope with ThreadPoolExecutor(max_workers=3) as pool: records = list(pool.map(lambda _: candidates.put(prepared.envelope, processing_profile=profile), range(3))) assert len({c.key for c in records}) == 3 assert len(candidates.inventory()["candidates"]) == 4 assert not candidates.inventory()["temporary_files"] assert LocalFileStore(store.directory).read(key) == content assert store.inventory()["originals"] == [key] path = candidates.directory / prepared.candidate.key path.write_bytes(path.read_bytes().replace(b"12.5", b"99.5")) with pytest.raises(ValueError, match="integrity"): reloaded.inspect(prepared.candidate, processing_profile=profile) def test_original_hash_checked_before_provider_and_candidate(profile, tmp_path): store = LocalFileStore(tmp_path / "originals") candidates = LocalExtractionCandidates(tmp_path / "extractions", original_directory=store.directory) key = store.put(image_bytes()) vision = FakeVision() with pytest.raises(ExtractionError, match="integrity"): prepare_extraction(store, candidates, PageBlockExtractor(vision), document=dict( id=uuid4(), title="Original", storage_key=key, size_bytes=len(image_bytes()), file_sha256="a" * 64, mime_type="image/jpeg", processing_profile=profile)) assert not vision.calls and not candidates.directory.exists() def test_candidate_namespaces_and_unsafe_keys(profile, tmp_path): original = tmp_path / "originals" with pytest.raises(ValueError, match="namespace"): LocalExtractionCandidates(original / "extractions", original_directory=original) candidates = LocalExtractionCandidates(tmp_path / "extractions", original_directory=original) with pytest.raises(ValueError, match="key"): candidates._path("../escape") def test_docx_question_answer_inside_single_cell(profile): xml = """ سؤال: تاریخ؟ پاسخ: 1403/01/02 نیست مگر استثنا """ value = extract(docx_bytes(document=xml.encode()), profile, DOCX_MIME) assert [b.block_type for b in value.blocks] == ["question", "answer"] assert value.blocks[0].group_id == value.blocks[1].group_id assert "/paragraph/2" in value.blocks[1].source_locator def test_valid_artifact_retained_even_if_chunk_bound_fails(profile, tmp_path): content = ("ماده 12\n" + "شرط " * 40 + "مگر استثنا").encode() profile = deepcopy(profile) profile["chunk_size"], profile["overlap"] = 50, 10 store = LocalFileStore(tmp_path / "originals") key = store.put(content) candidates = LocalExtractionCandidates(tmp_path / "extractions", original_directory=store.directory) with pytest.raises(ExtractionError, match="Semantic"): prepare_extraction(store, candidates, PageBlockExtractor(), document=dict( id=uuid4(), title="Source", storage_key=key, size_bytes=len(content), file_sha256=hashlib.sha256(content).hexdigest(), mime_type="text/markdown", processing_profile=profile)) assert len(candidates.inventory()["candidates"]) == 1 assert store.read(key) == content def test_cross_page_rule_note_stays_together_without_fake_page(profile): from app.modules.documents.types import ExtractedBlock, ExtractionEnvelope from app.modules.documents.extraction_artifacts import extraction_profile_digest value = ExtractionEnvelope(document_id=uuid4(), title="Rule", original_sha256="a" * 64, extraction_profile_sha256=extraction_profile_digest(profile), normalization_policy=profile["normalizer"], complete=True, quality_decision="reviewed", blocks=( ExtractedBlock(ordinal=0, block_id="rule", text="ماده 12\n1403/01/02", source_locator="pdf/page/1/block/1", section="Article 12", page=1, method="direct_pdf"), ExtractedBlock(ordinal=1, block_id="note", text="تبصره: شامل استثنا نمی‌شود", source_locator="pdf/page/2/block/1", section="Article 12 note", page=2, method="direct_pdf"))) chunks = chunk_extraction(value, profile) assert len(chunks) == 1 and chunks[0].page is None assert "pages/1,2" in chunks[0].section and "استثنا" in chunks[0].text def test_circular_conditions_and_exclusion_headings_do_not_split_rule(profile): text = "# Circular 125\nDecision dated 1403/01/02.\n\n# Conditions\nOnly 12.5% subject to approval.\n\n# Exclusions\nNot available for excluded cases.\n" value = extract(text.encode(), profile) chunks = chunk_extraction(value, profile) assert len(chunks) == 1 assert all(term in chunks[0].text for term in ("Circular 125", "Conditions", "Exclusions", "Not available", "12.5%"))