"""Operator-to-publication proof on disposable PostgreSQL and real extraction.""" from concurrent.futures import ThreadPoolExecutor import json import logging from threading import Event 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.infrastructure.worker_repository import SqlWorkerRepository from app.modules.documents.chunking import chunk_extraction from app.modules.documents.embeddings import EmbeddingLimits from app.modules.documents.extraction import PageBlockExtractor from app.modules.documents.intake import import_document, reconcile, status from app.modules.documents.normalization import normalize_search_text from app.modules.documents.worker import Worker from tests.support.embedding import DeterministicEmbeddings from tests.support.formats import docx_bytes FIXTURE_PARAGRAPHS = ['Article 1\n' 'Pump pressure is 25 bar only when temperature is below 60 C. Do not open the bypass except ' 'during shutdown.', 'Article 2\n' 'Flow is 40 liters per minute unless the inlet is blocked. Inspect seals every 30 days.', 'Article 3\nTorque is 15 Nm. Do not restart when leakage is present, except after inspection.'] # Literal rendered evidence, including paragraph separators; no chunker calls. FIXTURE_ROWS = {'.md': [{'ordinal': 0, 'text': 'Article 1\n' 'Pump pressure is 25 bar only when temperature is below 60 C. Do not open the ' 'bypass except during shutdown.\n', 'location': {'page': None, 'section': 'Article 1 | text/paragraph/1'}}, {'ordinal': 1, 'text': '\n' 'Article 2\n' 'Flow is 40 liters per minute unless the inlet is blocked. Inspect seals every ' '30 days.\n', 'location': {'page': None, 'section': 'text/paragraph/2'}}, {'ordinal': 2, 'text': '\n' 'Article 3\n' 'Torque is 15 Nm. Do not restart when leakage is present, except after ' 'inspection.', 'location': {'page': None, 'section': 'text/paragraph/3'}}], '.docx': [{'ordinal': 0, 'text': 'Article 1\n' 'Pump pressure is 25 bar only when temperature is below 60 C. Do not open the ' 'bypass except during shutdown.\n', 'location': {'page': None, 'section': 'docx/paragraph/1'}}, {'ordinal': 1, 'text': 'Article 2\n' 'Flow is 40 liters per minute unless the inlet is blocked. Inspect seals every ' '30 days.\n', 'location': {'page': None, 'section': 'docx/paragraph/2'}}, {'ordinal': 2, 'text': 'Article 3\n' 'Torque is 15 Nm. Do not restart when leakage is present, except after ' 'inspection.\n', 'location': {'page': None, 'section': 'docx/paragraph/3'}}]} @pytest.fixture def pipeline(migrated_db, settings, tmp_path): engine, _ = migrated_db settings = settings.model_copy(update=dict( chunk_size_characters=256, chunk_overlap_characters=5, embedding_batch_size=2, embedding_limits=EmbeddingLimits(unit="utf8_bytes", max_input_units=4096, max_batch_units=8192, max_batch_inputs=2))) org, actor = uuid4(), uuid4() with engine.begin() as conn: conn.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'phase6')"), dict(id=org)) conn.execute(text("""INSERT INTO users(id,organization_id,username,password_hash,role) VALUES (:id,:org,:name,'test-only','admin')"""), dict(id=actor, org=org, name=str(actor))) store = LocalFileStore(tmp_path / "originals") candidates = LocalExtractionCandidates(tmp_path / "extractions", original_directory=store.directory) intake = SqlIntakeRepository(engine) repo = SqlWorkerRepository(engine, settings) return dict(engine=engine, settings=settings, store=store, candidates=candidates, intake=intake, repo=repo, actor=actor, root=tmp_path) def upload(p, suffix=".md", key=None): source = p["root"] / ("corpus" + suffix) paragraphs = FIXTURE_PARAGRAPHS if suffix == ".docx": xml = ('' '' + ''.join('' + value + '' for value in paragraphs) + '') source.write_bytes(docx_bytes(document=xml.encode())) else: source.write_bytes("\n\n".join(paragraphs).encode("utf-8")) return import_document(p["intake"], p["store"], p["settings"], path=source, administrator_id=p["actor"], request_id=key or uuid4())["document"] def snapshot(p, document): # All publication invariants are observed in one SQL statement/snapshot. with p["engine"].connect() as conn: value = conn.execute(text("""SELECT d.*, j.id AS job_id, j.status AS job_status, j.stage AS job_stage, j.attempt_count, j.retry_generation, pg_backend_pid() AS observer_pid, COALESCE((SELECT jsonb_agg(jsonb_build_object( 'ordinal',c.ordinal,'text',c.text,'location',c.location, 'dimension',vector_dims(c.embedding),'vector',c.embedding::text) ORDER BY c.ordinal) FROM document_chunks c WHERE c.document_id=d.id),'[]'::jsonb) AS chunks, (SELECT count(*) FROM document_chunks c WHERE c.document_id=d.id) AS actual_count FROM documents d JOIN ingestion_jobs j ON j.document_id=d.id WHERE d.id=:id"""), dict(id=document["id"])).mappings().one() return dict(value) def expected(p, document): envelope = PageBlockExtractor().extract(document_id=document["id"], title=document["title"], original_sha256=document["file_sha256"], content=p["store"].read(document["storage_key"]), mime_type=document["mime_type"], processing_profile=document["processing_profile"]) drafts = tuple(chunk_extraction(envelope, document["processing_profile"])) assert len(drafts) == 3 return drafts def worker(p, provider): return Worker(p["repo"], p["store"], p["candidates"], lambda _: PageBlockExtractor(), lambda _: (provider, None), p["settings"]) def assert_fixed_fixture(state, document): suffix = ".docx" if document["mime_type"].endswith("document") else ".md" fixed = FIXTURE_ROWS[suffix] observed = [{key: row[key] for key in ("ordinal", "text", "location")} for row in state["chunks"]] assert observed == fixed, "Published rows differ from fixed fixture evidence" # These requirements come from the source evidence, independently of drafts. for phrase in ("25 bar", "below 60 C", "only when", "Do not open", "except during shutdown"): assert phrase in observed[0]["text"] for phrase in ("40 liters per minute", "unless the inlet is blocked", "30 days"): assert phrase in observed[1]["text"] for phrase in ("15 Nm", "Do not restart", "when leakage is present", "except after inspection"): assert phrase in observed[2]["text"] for row, evidence in zip(state["chunks"], fixed): assert row["dimension"] == 3 assert json.loads(row["vector"]) == DeterministicEmbeddings.vector(evidence["text"]) def assert_published(p, document, drafts): state = snapshot(p, document) assert state["status"] == "ready" and state["job_status"] == "succeeded" assert state["ready_at"] is not None and not state["is_active"] assert state["actual_count"] == state["chunk_count"] == len(drafts) assert state["processing_profile"] == document["processing_profile"] assert_fixed_fixture(state, document) rows = state["chunks"] assert [row["ordinal"] for row in rows] == list(range(len(drafts))) for row, draft in zip(rows, drafts): assert row["text"] == draft.text assert row["location"] == dict(page=draft.page, section=draft.section) assert draft.section # actual source locators survive publication assert row["dimension"] == document["processing_profile"]["embedding"]["dimensions"] == 3 assert json.loads(row["vector"]) == DeterministicEmbeddings.vector(normalize_search_text(draft.text)) @pytest.mark.parametrize("suffix", [".md", ".docx"]) def test_incomplete_batches_are_invisible_then_publish_exact_source_rows(pipeline, suffix, caplog): p = pipeline doc = upload(p, suffix) drafts = expected(p, doc) assert len(drafts) > 2 entered, release, heartbeat = Event(), Event(), Event() class HeartbeatHandler(logging.Handler): def emit(self, record): if json.loads(record.getMessage())["category"] == "renewed": heartbeat.set() handler = HeartbeatHandler() logger = logging.getLogger("app.modules.documents.worker") logger.addHandler(handler) p["settings"] = p["settings"].model_copy(update=dict(heartbeat_seconds=0.05, lease_seconds=5)) p["repo"].settings = p["settings"] def observe(batch): state = snapshot(p, doc) assert state["actual_count"] == state["chunk_count"] == 0 assert state["status"] != "ready" and state["job_status"] == "processing" assert state["ready_at"] is None and not state["is_active"] if batch == 2: entered.set() assert release.wait(10) provider = DeterministicEmbeddings(p["settings"], observe=observe) caplog.set_level(logging.INFO, logger=logger.name) try: with ThreadPoolExecutor(max_workers=1) as pool: future = pool.submit(worker(p, provider).run_once, "phase6") try: assert entered.wait(10) assert heartbeat.wait(5) assert snapshot(p, doc)["actual_count"] == 0 finally: release.set() assert future.result(timeout=15) finally: logger.removeHandler(handler) assert len(provider.calls) == (len(drafts) + 1) // 2 assert_published(p, doc, drafts) records = [json.loads(r.getMessage()) for r in caplog.records if r.name == logger.name] assert all(r["document_id"] == str(doc["id"]) for r in records) assert all(r["job_id"] == str(snapshot(p, doc)["job_id"]) for r in records) assert {r["stage"] for r in records} >= {"claim", "extract", "chunk", "embed", "publish", "heartbeat"} assert records[-1]["category"] == "succeeded" def test_failed_final_batch_retry_and_duplicate_imports(pipeline, caplog): p = pipeline key = uuid4() doc = upload(p, key=key) assert upload(p, key=key)["id"] == doc["id"] independent = upload(p) assert independent["id"] != doc["id"] assert independent["file_sha256"] == doc["file_sha256"] assert independent["storage_key"] != doc["storage_key"] # Hold the independent upload out of the worker's eligible queue. with p["engine"].begin() as conn: conn.execute(text("UPDATE documents SET deleted_at=clock_timestamp() WHERE id=:id"), dict(id=independent["id"])) drafts = expected(p, doc) provider = DeterministicEmbeddings(p["settings"], fail_at=(len(drafts) + 1) // 2, observe=lambda _: assert_empty(p, doc)) caplog.set_level(logging.INFO, logger="app.modules.documents.worker") assert worker(p, provider).run_once("failing") state = snapshot(p, doc) assert state["status"] == state["job_status"] == "failed" assert state["job_stage"] == "embed" and state["actual_count"] == 0 assert len(provider.calls) == provider.fail_at > 1 assert "injected secret" not in caplog.text and "embedding_error" in caplog.text retry_key = uuid4() response = p["repo"].retry(administrator_id=p["actor"], document_id=doc["id"], request_id=retry_key, store=p["store"]) replay = p["repo"].retry(administrator_id=p["actor"], document_id=doc["id"], request_id=retry_key, store=p["store"]) assert not response["replayed"] and replay["replayed"] queued = snapshot(p, doc) assert queued["job_id"] == state["job_id"] assert queued["retry_generation"] == 1 and queued["attempt_count"] == 0 assert worker(p, DeterministicEmbeddings(p["settings"])).run_once("retried") assert_published(p, doc, drafts) assert p["repo"].retry(administrator_id=p["actor"], document_id=doc["id"], request_id=retry_key, store=p["store"])["replayed"] with p["engine"].connect() as conn: assert conn.execute(text("SELECT count(*) FROM audit_events WHERE action='ingestion_retry'")).scalar_one() == 1 assert status(p["intake"], administrator_id=p["actor"], document_id=doc["id"])["status"] == "ready" def assert_empty(p, doc): state = snapshot(p, doc) assert state["actual_count"] == state["chunk_count"] == 0 and state["status"] != "ready" @pytest.mark.parametrize("boundary", ["before_publish", "after_commit", "expired", "deleted"]) def test_crash_and_late_publication_boundaries(pipeline, monkeypatch, boundary): p = pipeline doc = upload(p) drafts = expected(p, doc) original = p["repo"].publish def intercepted(claim, staged, candidates, store): assert_empty(p, doc) if boundary == "before_publish": raise RuntimeError("simulated process death") if boundary in ("expired", "deleted"): with p["engine"].begin() as conn: conn.execute(text("UPDATE ingestion_jobs SET lease_expires_at=clock_timestamp()-interval '1 second'" if boundary == "expired" else "UPDATE documents SET deleted_at=clock_timestamp()")) result = original(claim, staged, candidates, store) if boundary == "after_commit": raise RuntimeError("simulated death after committed publication") return result monkeypatch.setattr(p["repo"], "publish", intercepted) if boundary in ("before_publish", "after_commit"): with pytest.raises(RuntimeError, match="simulated"): worker(p, DeterministicEmbeddings(p["settings"])).run_once("crashed") else: assert worker(p, DeterministicEmbeddings(p["settings"])).run_once("late") monkeypatch.setattr(p["repo"], "publish", original) if boundary == "after_commit": assert_published(p, doc, drafts) assert not worker(p, DeterministicEmbeddings(p["settings"])).run_once("restart") assert_published(p, doc, drafts) elif boundary == "deleted": assert_empty(p, doc) assert not worker(p, DeterministicEmbeddings(p["settings"])).run_once("restart") else: assert_empty(p, doc) with p["engine"].begin() as conn: conn.execute(text("UPDATE ingestion_jobs SET lease_expires_at=clock_timestamp()-interval '1 second'")) assert worker(p, DeterministicEmbeddings(p["settings"])).run_once("reclaimed") assert_published(p, doc, drafts) assert snapshot(p, doc)["attempt_count"] == 2 def test_missing_original_is_reported_and_never_published(pipeline): p = pipeline doc = upload(p) p["store"]._path(doc["storage_key"]).unlink() provider = DeterministicEmbeddings(p["settings"]) assert worker(p, provider).run_once("missing") assert_empty(p, doc) assert not provider.calls report = reconcile(p["intake"], p["store"]) assert report["report_only"] assert [r["document_id"] for r in report["missing_originals"]] == [str(doc["id"])] @pytest.mark.parametrize("suffix", [".md", ".docx"]) def test_shared_chunker_number_mutation_is_detected(pipeline, monkeypatch, suffix): # Both worker preparation and publication validation use the same altered # chunker; an implementation-derived oracle alone accepts the wrong number. from dataclasses import replace from app.modules.documents import review p = pipeline doc = upload(p, suffix) real_chunker = chunk_extraction def changed_number(*args, **kwargs): return tuple(replace(d, text=d.text.replace("25 bar", "26 bar")) for d in real_chunker(*args, **kwargs)) monkeypatch.setattr(review, "chunk_extraction", changed_number) drafts = tuple(replace(d, text=d.text.replace("25 bar", "26 bar")) for d in expected(p, doc)) assert worker(p, DeterministicEmbeddings(p["settings"])).run_once("mutated") state = snapshot(p, doc) assert state["status"] == "ready" and state["job_status"] == "succeeded" assert state["chunks"][0]["text"] == drafts[0].text with pytest.raises(AssertionError, match="fixed fixture"): assert_published(p, doc, drafts) @pytest.mark.parametrize("suffix", [".md", ".docx"]) def test_publication_is_invisible_after_inserts_and_completion_updates(pipeline, suffix): from sqlalchemy import event p = pipeline doc = upload(p, suffix) drafts = expected(p, doc) after_inserts, release_inserts, after_updates, release_updates = (Event() for _ in range(4)) inserted = [] publisher_pid = [] # Bounded barriers finish well before the first heartbeat; no background # heartbeat needs to queue behind the intentionally paused document lock. p["settings"] = p["settings"].model_copy(update=dict(heartbeat_seconds=60, lease_seconds=120)) p["repo"].settings = p["settings"] def pause(conn, cursor, statement, parameters, context, executemany): if statement.lstrip().startswith("INSERT INTO document_chunks"): inserted.append(1) if len(inserted) == len(drafts): publisher_pid.append(conn.execute(text("SELECT pg_backend_pid()")).scalar_one()) after_inserts.set() assert release_inserts.wait(10), "insert barrier timed out" elif "UPDATE ingestion_jobs" in statement and "status='succeeded'" in statement: # This callback runs after both document and job completion writes, # still inside the production publication transaction. after_updates.set() assert release_updates.wait(10), "completion barrier timed out" event.listen(p["engine"], "after_cursor_execute", pause) try: with ThreadPoolExecutor(max_workers=1) as pool: future = pool.submit(worker(p, DeterministicEmbeddings(p["settings"])).run_once, "atomic") try: assert after_inserts.wait(10), "publisher did not reach insert barrier" before = snapshot(p, doc) assert before["observer_pid"] != publisher_pid[0] assert before["chunks"] == [] and before["actual_count"] == before["chunk_count"] == 0 assert before["status"] == before["job_status"] == "processing" assert before["ready_at"] is None and not before["is_active"] release_inserts.set() assert after_updates.wait(10), "publisher did not reach completion barrier" uncommitted = snapshot(p, doc) assert uncommitted["observer_pid"] != publisher_pid[0] assert uncommitted["chunks"] == [] and uncommitted["actual_count"] == uncommitted["chunk_count"] == 0 assert uncommitted["status"] == uncommitted["job_status"] == "processing" assert uncommitted["ready_at"] is None and not uncommitted["is_active"] finally: release_inserts.set() release_updates.set() assert future.result(timeout=15) finally: release_inserts.set() release_updates.set() event.remove(p["engine"], "after_cursor_execute", pause) assert len(inserted) == len(drafts) assert_published(p, doc, drafts)