- Add direct text, DOCX, and PDF text extraction with visual OCR fallback - Implement Gemini and OpenRouter vision adapters with strict bounded retry - Implement extraction envelopes, artifacts, and Unicode/Persian normalization - Add human review workflow, candidate staging, and review repositories - Add migration 0003_extraction_review for audit events and review tracking - Add comprehensive unit and integration tests covering extraction and review contracts
78 lines
4.4 KiB
Python
78 lines
4.4 KiB
Python
"""Real PostgreSQL isolation: Phase 3 candidates/drafts cannot alter intake lifecycle."""
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import hashlib
|
|
from uuid import uuid4
|
|
|
|
import pytest
|
|
from sqlalchemy import text
|
|
|
|
from app.infrastructure.extraction_candidates import LocalExtractionCandidates
|
|
from app.infrastructure.file_store import LocalFileStore
|
|
from app.infrastructure.intake_repository import SqlIntakeRepository
|
|
from app.modules.documents.extraction import PageBlockExtractor, ExtractionError
|
|
from app.modules.documents.intake import import_document, status
|
|
from app.modules.documents.processing import prepare_extraction
|
|
from tests.support.extraction import faq_docx
|
|
|
|
|
|
@pytest.fixture
|
|
def imported(migrated_db, settings, tmp_path):
|
|
engine, _ = migrated_db
|
|
organization, administrator = uuid4(), uuid4()
|
|
with engine.begin() as conn:
|
|
conn.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'phase3')"), {"id": organization})
|
|
conn.execute(text("""INSERT INTO users(id,organization_id,username,password_hash,role)
|
|
VALUES (:id,:org,:name,'fixture-only','admin')"""),
|
|
{"id": administrator, "org": organization, "name": str(administrator)})
|
|
store = LocalFileStore(tmp_path / "originals")
|
|
candidates = LocalExtractionCandidates(tmp_path / "extractions", original_directory=store.directory)
|
|
return engine, administrator, store, candidates
|
|
|
|
|
|
@pytest.mark.parametrize("extension", [".md", ".docx"])
|
|
def test_concurrent_preparation_retains_original_profile_and_zero_published_chunks(imported, settings, tmp_path, extension):
|
|
engine, administrator, store, candidates = imported
|
|
content = faq_docx() if extension == ".docx" else "ماده 12\n1403/01/02 شامل استثنا نمیشود\n".encode()
|
|
path = tmp_path / ("sample" + extension)
|
|
path.write_bytes(content)
|
|
result = import_document(SqlIntakeRepository(engine), store, settings, path=path,
|
|
administrator_id=administrator, request_id=uuid4())
|
|
document = result["document"]
|
|
before = status(SqlIntakeRepository(engine), administrator_id=administrator, document_id=document["id"])
|
|
purpose = "approved_factual" if extension == ".docx" else "source_document"
|
|
def process(_):
|
|
return prepare_extraction(store, candidates, PageBlockExtractor(), document=document, corpus_purpose=purpose)
|
|
with ThreadPoolExecutor(max_workers=2) as pool:
|
|
prepared = list(pool.map(process, range(2)))
|
|
assert prepared[0].chunks == prepared[1].chunks
|
|
assert prepared[0].candidate.key != prepared[1].candidate.key
|
|
after = status(SqlIntakeRepository(engine), administrator_id=administrator, document_id=document["id"])
|
|
assert after == before
|
|
assert after["status"] == after["job"]["status"] == "queued"
|
|
assert after["job"]["attempt_count"] == 0 and after["chunk_count"] == 0 and not after["is_active"]
|
|
assert after["processing_profile"] == settings.processing_profile()
|
|
assert store.read(document["storage_key"]) == content
|
|
with engine.connect() as conn:
|
|
assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0
|
|
assert conn.execute(text("SELECT count(*) FROM ingestion_jobs")).scalar_one() == 1
|
|
assert conn.execute(text("SELECT count(*) FROM audit_events")).scalar_one() == 1
|
|
for value in prepared:
|
|
assert candidates.inspect(value.candidate, processing_profile=document["processing_profile"]) == value.envelope
|
|
|
|
|
|
def test_unreliable_extraction_has_no_database_effect_or_candidate(imported, settings, tmp_path):
|
|
engine, administrator, store, candidates = imported
|
|
path = tmp_path / "bad.md"
|
|
path.write_bytes("破損 \ufffd".encode())
|
|
document = import_document(SqlIntakeRepository(engine), store, settings, path=path,
|
|
administrator_id=administrator, request_id=uuid4())["document"]
|
|
with pytest.raises(ExtractionError):
|
|
prepare_extraction(store, candidates, PageBlockExtractor(), document=document)
|
|
with engine.connect() as conn:
|
|
row = conn.execute(text("SELECT status,is_active,chunk_count,file_sha256 FROM documents WHERE id=:id"),
|
|
{"id": document["id"]}).one()
|
|
assert tuple(row[:3]) == ("queued", False, 0)
|
|
assert row.file_sha256 == hashlib.sha256(path.read_bytes()).hexdigest()
|
|
assert conn.execute(text("SELECT count(*) FROM document_chunks")).scalar_one() == 0
|
|
assert candidates.inventory()["candidates"] == []
|