diff --git a/app/infrastructure/worker_repository.py b/app/infrastructure/worker_repository.py new file mode 100644 index 0000000..739d844 --- /dev/null +++ b/app/infrastructure/worker_repository.py @@ -0,0 +1,359 @@ +"""Short PostgreSQL worker transactions and durable replay.""" +from dataclasses import asdict, replace +import json +from uuid import uuid4 + +from sqlalchemy import text + +from app.infrastructure.database import check_compatibility +from app.infrastructure.intake_repository import administrator +from app.modules.documents.embeddings import packed_vector +from app.modules.documents.errors import IntakeError +from app.modules.documents.worker import Claim, LostClaim, read_original, validate_source +from app.modules.documents.chunking import chunk_extraction +from app.modules.documents.review import prepare_chunks, reviews_approved +from app.modules.documents.operational_limits import validate_duration + + +class PublicationUncertain(RuntimeError): + """Do not schedule retries while a commit outcome cannot be read.""" + + +class SqlWorkerRepository: + def __init__(self, engine, settings): + self.engine, self.settings = engine, settings + + def claim(self, worker_id, lease_seconds): + validate_duration(lease_seconds) + token = uuid4() + with self.engine.begin() as connection: + row = connection.execute(text(""" + SELECT j.id FROM ingestion_jobs j JOIN documents d ON d.id=j.document_id + AND d.organization_id=j.organization_id + WHERE d.deleted_at IS NULL AND d.content_purged_at IS NULL + AND d.status IN ('queued','processing') AND NOT d.is_active + AND ((j.status='queued' AND j.next_attempt_at<=clock_timestamp()) + OR (j.status='processing' AND j.lease_expires_at<=clock_timestamp())) + ORDER BY j.next_attempt_at,j.id FOR UPDATE OF j SKIP LOCKED LIMIT 1 + """)).scalar_one_or_none() + if row is None: + return None + job = connection.execute(text(""" + UPDATE ingestion_jobs SET status='processing', stage='extract', + claim_token=:token, claimed_by=:worker, + lease_expires_at=clock_timestamp()+:lease*interval '1 second', + attempt_count=attempt_count+1, updated_at=clock_timestamp() + WHERE id=:id RETURNING * + """), dict(token=token, worker=worker_id, lease=lease_seconds, id=row)).mappings().one() + document = dict(connection.execute(text( + "SELECT * FROM documents WHERE id=:id AND organization_id=:org"), + dict(id=job["document_id"], org=job["organization_id"])).mappings().one()) + return Claim(document, job["id"], token, job["attempt_count"], job["retry_generation"]) + + def _lock(self, connection, claim): + document = connection.execute(text(""" + SELECT * FROM documents WHERE id=:id AND organization_id=:org FOR UPDATE + """), dict(id=claim.document["id"], org=claim.document["organization_id"])).mappings().one_or_none() + job = connection.execute(text(""" + SELECT * FROM ingestion_jobs WHERE id=:id AND document_id=:document FOR UPDATE + """), dict(id=claim.job_id, document=claim.document["id"])).mappings().one_or_none() + if (document is None or job is None or document["deleted_at"] is not None + or document["content_purged_at"] is not None or document["is_active"] + or document["status"] not in ("queued", "processing") + or job["status"] != "processing" or job["claim_token"] != claim.token + or job["retry_generation"] != claim.generation + or job["organization_id"] != document["organization_id"]): + raise LostClaim("Ineligible document or stale claim") + for key in ("file_sha256", "storage_key", "size_bytes", "mime_type", "title", "processing_profile"): + if document[key] != claim.document[key]: + raise LostClaim("Immutable source/profile changed") + self._valid(connection, claim) + return document, job + + def _valid(self, connection, claim): + valid = connection.execute(text(""" + SELECT EXISTS (SELECT 1 FROM ingestion_jobs + WHERE id=:id AND status='processing' AND claim_token=:token + AND lease_expires_at>clock_timestamp()) + """), dict(id=claim.job_id, token=claim.token)).scalar_one() + if not valid: + raise LostClaim("Claim expired") + + def _update_job(self, connection, claim, assignments, parameters=None): + # assignments are internal SQL constants, never caller/model input. + result = connection.execute(text(""" + UPDATE ingestion_jobs SET """ + assignments + """, updated_at=clock_timestamp() + WHERE id=:id AND status='processing' AND claim_token=:token + AND lease_expires_at>clock_timestamp() + """), dict(id=claim.job_id, token=claim.token, **(parameters or {}))) + if result.rowcount != 1: + raise LostClaim("Claim expired during update") + + def check(self, claim): + with self.engine.begin() as connection: + self._lock(connection, claim) + + def progress(self, claim, stage): + if stage not in ("extract", "chunk", "embed", "publish"): + raise ValueError("Unknown ingestion stage") + with self.engine.begin() as connection: + self._lock(connection, claim) + connection.execute(text(""" + UPDATE documents SET status='processing', updated_at=clock_timestamp() WHERE id=:id + """), dict(id=claim.document["id"])) + self._update_job(connection, claim, "stage=:stage", dict(stage=stage)) + + def heartbeat(self, claim, lease_seconds): + validate_duration(lease_seconds) + with self.engine.begin() as connection: + self._lock(connection, claim) + self._update_job(connection, claim, + "lease_expires_at=clock_timestamp()+:lease*interval '1 second'", dict(lease=lease_seconds)) + + def attach(self, claim, candidate, candidates, store): + envelope = candidates.inspect(candidate, processing_profile=claim.document["processing_profile"]) + if (candidate.document_id != claim.document["id"] + or candidate.original_sha256 != claim.document["file_sha256"] + or candidate.extraction_profile_sha256 != envelope.extraction_profile_sha256): + raise ValueError("Extraction candidate source mismatch") + validate_source(envelope, claim.document, read_original(store, claim.document)) + pointer = asdict(candidate) + pointer["document_id"] = str(pointer["document_id"]) + with self.engine.begin() as connection: + document, _ = self._lock(connection, claim) + if document["extraction_state"].get("complete_artifact") is not None: + if document["extraction_state"]["complete_artifact"] != pointer: + raise LostClaim("Complete extraction already attached") + else: + connection.execute(text(""" + UPDATE documents SET extraction_state=jsonb_set(extraction_state,'{complete_artifact}',CAST(:artifact AS jsonb)), + updated_at=clock_timestamp() WHERE id=:id + """), dict(id=document["id"], artifact=json.dumps(pointer))) + self._update_job(connection, claim, "stage='chunk'") + + def fail(self, claim, *, code, retryable, delay): + retryable = bool(retryable and claim.attempt < self.settings.max_automatic_attempts) + if retryable: + validate_duration(delay) + with self.engine.begin() as connection: + document, _ = self._lock(connection, claim) + connection.execute(text(""" + UPDATE documents SET status=:status, is_active=false, updated_at=clock_timestamp() + WHERE id=:id + """), dict(id=document["id"], status="queued" if retryable else "failed")) + self._update_job(connection, claim, """ + status=:status, claim_token=NULL, lease_expires_at=NULL, claimed_by=NULL, + error_code=:code, error_message='Ingestion failed; inspect the error category.', + error_retryable=:retryable, + next_attempt_at=clock_timestamp()+:delay*interval '1 second' + """, dict(status="queued" if retryable else "failed", code=code, + retryable=retryable, delay=delay if retryable else 0)) + + def completed(self, claim): + with self.engine.connect() as connection: + row = connection.execute(text(""" + SELECT d.status, d.chunk_count, j.status AS job_status, j.retry_generation, + (SELECT count(*) FROM document_chunks c WHERE c.document_id=d.id) AS actual + FROM documents d JOIN ingestion_jobs j ON j.document_id=d.id + WHERE d.id=:document AND j.id=:job + """), dict(document=claim.document["id"], job=claim.job_id)).mappings().one_or_none() + return bool(row and row["status"] == "ready" and row["job_status"] == "succeeded" + and row["chunk_count"] == row["actual"] and row["actual"] > 0 + and row["retry_generation"] == claim.generation) + + def publish(self, claim, staged, candidates, store): + # All storage/provider work and complete-staging validation precede locks. + with self.engine.connect() as connection: + state = connection.execute(text( + "SELECT extraction_state FROM documents WHERE id=:id"), + dict(id=claim.document["id"])).scalar_one() + pointer = state.get("complete_artifact") + if pointer is None: + raise ValueError("Complete extraction is not durably attached") + envelope = candidates.inspect_pointer(pointer, document=claim.document) + validate_source(envelope, claim.document, read_original(store, claim.document)) + drafts = prepare_chunks(envelope, claim.document["processing_profile"], state, pointer["sha256"]) + chunks, vectors = staged.chunks, staged.vectors + if (staged.document_id != claim.document["id"] + or staged.processing_profile != claim.document["processing_profile"] + or asdict(staged.embedding_profile) != claim.document["processing_profile"]["embedding"] + or len(chunks) != len(drafts) or len(vectors) != len(chunks) + or tuple(replace(c, token_count=None) for c in chunks) != drafts): + raise ValueError("Incomplete or incompatible staged results") + # Recheck vectors even if a caller did not use the staging service. + for vector in vectors: + packed_vector(vector, staged.embedding_profile.dimensions) + try: + with self.engine.begin() as connection: + document, _ = self._lock(connection, claim) + check_compatibility(connection, staged.embedding_profile, require_worker=True) + if document["extraction_state"] != state: + raise LostClaim("Extraction attachment changed") + if connection.execute(text("SELECT EXISTS (SELECT 1 FROM document_chunks WHERE document_id=:id)"), + dict(id=document["id"])).scalar_one(): + raise ValueError("Document already contains chunks") + for chunk, vector in zip(chunks, vectors): + connection.execute(text(""" + INSERT INTO document_chunks + (id, organization_id, document_id, ordinal, text, location, token_count, embedding) + VALUES (:id,:org,:document,:ordinal,:text,CAST(:location AS jsonb),:tokens,CAST(:vector AS vector)) + """), dict(id=uuid4(), org=document["organization_id"], document=document["id"], + ordinal=chunk.ordinal, text=chunk.text, tokens=chunk.token_count, + location=json.dumps(dict(page=chunk.page, section=chunk.section)), + vector="[" + ",".join(map(str, vector)) + "]")) + connection.execute(text(""" + UPDATE documents SET status='ready', chunk_count=:count, ready_at=clock_timestamp(), + is_active=false, updated_at=clock_timestamp() WHERE id=:id + """), dict(id=document["id"], count=len(chunks))) + self._update_job(connection, claim, """ + status='succeeded',stage='publish',claim_token=NULL,lease_expires_at=NULL, + claimed_by=NULL,error_code=NULL,error_message=NULL,error_retryable=false + """) + except Exception: + # The commit may have succeeded despite an interrupted acknowledgement. + # Re-read before any retry. If this read fails, leave recovery to a later poll. + try: + completed = self.completed(claim) + except Exception: + raise PublicationUncertain("Publication outcome requires durable reconciliation") from None + if completed: + return True + raise + return True + + def retry(self, *, administrator_id, document_id, request_id, store, candidates=None): + # Resolve authorized replay before touching storage or checking new state. + with self.engine.begin() as connection: + org = administrator(connection, administrator_id) + snapshot = connection.execute(text( + "SELECT * FROM documents WHERE id=:id AND organization_id=:org"), + dict(id=document_id, org=org)).mappings().one_or_none() + if snapshot is None or snapshot["deleted_at"] is not None: + raise IntakeError("DOCUMENT_NOT_FOUND", "Document not found") + previous = connection.execute(text(""" + SELECT response_json FROM audit_events + WHERE organization_id=:org AND actor_user_id=:actor AND action='ingestion_retry' + AND target_id=:document AND idempotency_key=:request + """), dict(org=org, actor=administrator_id, document=document_id, request=request_id)).scalar_one_or_none() + if previous is not None: + return dict(replayed=True, **previous) + try: + read_original(store, snapshot) + except (OSError, ValueError, KeyError): + raise IntakeError("DOCUMENT_NOT_RETRYABLE", "Retained original is unavailable or incompatible") from None + review_state = snapshot.get("extraction_state", {}) + if review_state.get("candidates"): + if any((p.get("decision") or {}).get("decision") == "reject" for p in review_state["candidates"]): + raise IntakeError("DOCUMENT_NOT_RETRYABLE", "Rejected evidence cannot be retried") + if not reviews_approved(review_state): + raise IntakeError("EXTRACTION_REVIEW_PENDING", "All current evidence must be approved before retry") + if candidates is None: + from .extraction_candidates import LocalExtractionCandidates + candidates = LocalExtractionCandidates(self.settings.extraction_directory, original_directory=store.directory) + from .review_repository import SqlReviewRepository + service = SqlReviewRepository(self.engine, self.settings, candidates, store) + for pointer in review_state["candidates"]: + service._body(pointer, snapshot) + with self.engine.begin() as connection: + check_compatibility(connection, self.settings.embedding_profile) + org = administrator(connection, administrator_id) + document = connection.execute(text(""" + SELECT * FROM documents WHERE id=:id AND organization_id=:org FOR UPDATE + """), dict(id=document_id, org=org)).mappings().one_or_none() + if document is None or document["deleted_at"] is not None: + raise IntakeError("DOCUMENT_NOT_FOUND", "Document not found") + previous = connection.execute(text(""" + SELECT response_json FROM audit_events + WHERE organization_id=:org AND actor_user_id=:actor AND action='ingestion_retry' + AND target_id=:document AND idempotency_key=:request + """), dict(org=org, actor=administrator_id, document=document_id, request=request_id)).scalar_one_or_none() + if previous is not None: + return dict(replayed=True, **previous) + job = connection.execute(text(""" + SELECT * FROM ingestion_jobs WHERE document_id=:id AND organization_id=:org FOR UPDATE + """), dict(id=document_id, org=org)).mappings().one() + if (any(document[k] != snapshot[k] for k in ("storage_key", "file_sha256", "size_bytes", "processing_profile")) + or document.get("extraction_state") != snapshot.get("extraction_state") + or document["status"] != "failed" or job["status"] != "failed" + or document["deleted_at"] is not None or document["content_purged_at"] is not None + or document["is_active"] or document["chunk_count"] != 0): + raise IntakeError("DOCUMENT_NOT_RETRYABLE", "Only eligible failed documents can be retried") + if job["error_code"] in ("EXTRACTION_REVIEW_REQUIRED", "EXTRACTION_REVIEW_REJECTED") and not reviews_approved(document["extraction_state"]): + raise IntakeError("EXTRACTION_REVIEW_PENDING", "Exact extraction inspection is required before retry") + connection.execute(text(""" + UPDATE documents SET status='queued',updated_at=clock_timestamp() WHERE id=:id + """), dict(id=document_id)) + connection.execute(text(""" + UPDATE ingestion_jobs SET status='queued',stage='extract',attempt_count=0, + retry_generation=retry_generation+1,next_attempt_at=clock_timestamp(), + claim_token=NULL,lease_expires_at=NULL,claimed_by=NULL, + error_code=NULL,error_message=NULL,error_retryable=false,updated_at=clock_timestamp() + WHERE id=:id + """), dict(id=job["id"])) + response = dict(document_id=str(document_id), job_id=str(job["id"]), status="queued", + retry_generation=job["retry_generation"] + 1) + connection.execute(text(""" + INSERT INTO audit_events + (id,organization_id,actor_user_id,action,target_id,idempotency_key,response_json) + VALUES (:id,:org,:actor,'ingestion_retry',:document,:request,CAST(:response AS jsonb)) + """), dict(id=uuid4(), org=org, actor=administrator_id, document=document_id, + request=request_id, response=json.dumps(response))) + return dict(replayed=False, **response) + + def review_resume(self, claim, candidates, store): + from .review_repository import SqlReviewRepository + service = SqlReviewRepository(self.engine, self.settings, candidates, store) + pointers = claim.document["extraction_state"].get("candidates", ()) + + def retained(locator): + self.check(claim) + pointer = next((p for p in pointers if p["review_kind"] == "extraction" and p["locator"] == locator), None) + if pointer is None: + return None + body = service._body(pointer, claim.document) + self.check(claim) + return body, pointer.get("decision") or {} + + return retained + + def retain_review(self, claim, candidates, store, *, error=None, envelope=None): + from .review_candidates import LocalReviewCandidates + from .review_repository import SqlReviewRepository + from app.modules.documents.extraction_artifacts import bounded_json_bytes + read_original(store, claim.document) + with self.engine.connect() as connection: + snapshot = dict(connection.execute(text("SELECT * FROM documents WHERE id=:id"), + dict(id=claim.document["id"])).mappings().one()) + review_store = LocalReviewCandidates(candidates) + pointer = review_store.put(claim.document, error=error, envelope=envelope, + artifact=snapshot["extraction_state"].get("complete_artifact")) + service = SqlReviewRepository(self.engine, self.settings, candidates, store) + service._body(pointer, snapshot) + with self.engine.begin() as connection: + document, _ = self._lock(connection, claim) + state = document["extraction_state"] + if error is None and state.get("complete_artifact") != snapshot["extraction_state"].get("complete_artifact"): + raise LostClaim("Complete extraction changed during review retention") + items = state.setdefault("candidates", []) + previous = next((p for p in items if p["review_kind"] == pointer["review_kind"] + and p["locator"] == pointer["locator"]), None) + if previous is not None: + if previous["evidence_sha256"] != pointer["evidence_sha256"] or previous.get("decision") is not None: + raise LostClaim("Retained evidence cannot be overwritten") + else: + limit = document["processing_profile"]["extraction"]["max_pdf_pages"] + 1 + if len(items) >= limit: + raise ValueError("Review reference count exceeded") + items.append(pointer) + state["progress"] = dict(next_locator=pointer["locator"], + retained_locations=[p["locator"] for p in items if p["review_kind"] == "extraction"]) + encoded = bounded_json_bytes(state, document["processing_profile"]["extraction"]["max_extraction_artifact_bytes"]) + connection.execute(text(""" + UPDATE documents SET extraction_state=CAST(:state AS jsonb),status='failed',is_active=false, + updated_at=clock_timestamp() WHERE id=:id + """), dict(id=document["id"], state=encoded.decode())) + self._update_job(connection, claim, """ + status='failed',claim_token=NULL,lease_expires_at=NULL,claimed_by=NULL, + error_code='EXTRACTION_REVIEW_REQUIRED',error_retryable=false, + error_message='Exact retained evidence requires administrator review.' + """) diff --git a/app/modules/documents/worker.py b/app/modules/documents/worker.py new file mode 100644 index 0000000..f85612a --- /dev/null +++ b/app/modules/documents/worker.py @@ -0,0 +1,249 @@ +"""Single-job orchestration. Remote work never holds database transactions.""" +from contextlib import contextmanager +from dataclasses import dataclass +import hashlib +import json +import logging +import random +from threading import Event, Thread + +from .chunking import chunk_extraction +from .embeddings import EmbeddingError, stage_document +from .extraction import ExtractionError, ReviewRequired +from .extraction_artifacts import extraction_profile_digest +from .review import FactualReviewRequired, prepare_chunks +from .operational_limits import validate_worker_durations + + +logger = logging.getLogger(__name__) + + +def report(claim, stage, category): + """Only internal categories and durable IDs; never exception/provider text.""" + logger.info(json.dumps(dict(document_id=str(claim.document.get("id")), + job_id=str(claim.job_id), stage=stage, category=category))) + + +class LostClaim(RuntimeError): + """Ownership was lost; discard results without changing durable state.""" + + +@dataclass(frozen=True) +class Claim: + document: dict + job_id: object + token: object + attempt: int + generation: int + + +def retry_delay(attempt, base, cap, *, uniform=random.uniform): + # Saturation before exponentiation prevents overflow for corrupt/large counts. + delay = base + for _ in range(min(max(0, attempt - 1), 64)): + delay = min(cap, delay * 2) + if delay >= cap: + break + return uniform(min(base, delay), min(cap, delay)) + + +def read_original(store, document): + limit = document["processing_profile"]["limits"]["max_original_bytes"] + if document["size_bytes"] > limit: + raise ExtractionError("Original exceeds frozen byte limit") + content = store.read_bounded(document["storage_key"], limit) + if (len(content) != document["size_bytes"] + or hashlib.sha256(content).hexdigest() != document["file_sha256"]): + raise ExtractionError("Immutable original integrity mismatch") + return content + + +def validate_source(envelope, document, content): + """Coverage checks independent of chunking and embedding settings.""" + if envelope.title != document["title"]: + raise ExtractionError("Extraction title differs from immutable source") + warnings = (*envelope.warnings, *(w for b in envelope.blocks for w in b.warnings)) + if warnings and envelope.quality_decision != "reviewed": + raise ExtractionError("Unreviewed extraction warnings") + if any("unreadable" in w.lower() or "\u0646\u0627\u062e\u0648\u0627\u0646\u0627" in w for w in warnings): + raise ExtractionError("Unreadable retained evidence") + mime = document["mime_type"] + if mime == "application/pdf": + import pymupdf + with pymupdf.open(stream=content, filetype="pdf") as source: + if (source.page_count > document["processing_profile"]["extraction"]["max_pdf_pages"] + or {b.page for b in envelope.blocks} != set(range(1, source.page_count + 1))): + raise ExtractionError("Incomplete PDF source coverage") + if envelope.quality_decision != "reviewed": + raise ExtractionError("PDF extraction requires inspection") + elif mime in ("image/jpeg", "image/png"): + if envelope.quality_decision != "reviewed" or any( + b.page is not None or b.method not in ("vision", "ocr") for b in envelope.blocks): + raise ExtractionError("Image extraction requires inspected complete evidence") + elif mime in ("text/markdown", "text/plain", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document"): + # Direct extraction is deterministic and cheap; verify complete source coverage + # without repeating OCR or running the chunker with potentially changed limits. + from .extraction import PageBlockExtractor + expected = PageBlockExtractor().extract_for_review(document_id=document["id"], title=document["title"], + original_sha256=document["file_sha256"], content=content, mime_type=mime, + processing_profile=document["processing_profile"]) + if envelope.blocks != expected.blocks: + raise ExtractionError("Incomplete direct source coverage") + else: + raise ExtractionError("Unsupported source MIME") + + +@contextmanager +def heartbeats(repository, claim, settings): + stop, lost = Event(), Event() + + def beat(): + while not stop.wait(settings.heartbeat_seconds): + try: + repository.heartbeat(claim, settings.lease_seconds) + report(claim, "heartbeat", "renewed") + except Exception: + # A database outage is not proof of continuing ownership. + lost.set() + report(claim, "heartbeat", "ownership_unavailable") + return + + thread = Thread(target=beat, name="ingestion-heartbeat", daemon=True) + thread.start() + + def check(): + if lost.is_set(): + raise LostClaim("Heartbeat ownership unavailable") + + try: + yield check + finally: + stop.set() + thread.join() + + +class FencedProvider: + """Preserve adapter identity while rejecting late responses before staging.""" + def __init__(self, provider, owned): + self.provider, self.owned = provider, owned + + @property + def profile(self): + return self.provider.profile + + @property + def request_policy(self): + return self.provider.request_policy + + def embed(self, texts): + self.owned() + result = self.provider.embed(texts) + self.owned() + return result + + +class Worker: + def __init__(self, repository, store, candidates, extractor_factory, provider_factory, settings): + validate_worker_durations(settings) + self.repository, self.store, self.candidates = repository, store, candidates + self.extractor_factory, self.provider_factory = extractor_factory, provider_factory + self.settings = settings + + def run_once(self, worker_id): + claim = self.repository.claim(worker_id, self.settings.lease_seconds) + if claim is None: + return False + stage = "claim" + report(claim, stage, "claimed") + + def progress(value): + nonlocal stage + stage = value + self.repository.progress(claim, value) + report(claim, stage, "started") + + try: + with heartbeats(self.repository, claim, self.settings) as check: + progress("extract") + if claim.attempt > self.settings.max_automatic_attempts: + self.repository.fail(claim, code="ATTEMPTS_EXHAUSTED", retryable=False, delay=0) + report(claim, stage, "attempts_exhausted") + return True + def owned(): + check() + self.repository.check(claim) + + document = claim.document + content = read_original(self.store, document) + artifact = document["extraction_state"].get("complete_artifact") + if artifact is not None: + envelope = self.candidates.inspect_pointer(artifact, document=document) + validate_source(envelope, document, content) + else: + extraction_profile_digest(document["processing_profile"]) + extractor = self.extractor_factory(document["processing_profile"]) + kwargs = dict(document_id=document["id"], title=document["title"], + original_sha256=document["file_sha256"], content=content, + mime_type=document["mime_type"], processing_profile=document["processing_profile"]) + try: + if hasattr(extractor, "extract_for_review"): + retained = self.repository.review_resume(claim, self.candidates, self.store) + envelope = extractor.extract_for_review(retained=retained, owned=owned, **kwargs) + else: + envelope = extractor.extract(**kwargs) + except ReviewRequired as error: + owned() + self.repository.retain_review(claim, self.candidates, self.store, error=error) + report(claim, stage, "review_required") + return True + owned() + candidate = self.candidates.put(envelope, processing_profile=document["processing_profile"]) + # Attachment verifies bounded bytes, trusted digest, source and ownership. + self.repository.attach(claim, candidate, self.candidates, self.store) + envelope = self.candidates.inspect(candidate, processing_profile=document["processing_profile"]) + artifact = dict(sha256=candidate.sha256) + check() + progress("chunk") + try: + chunks = prepare_chunks(envelope, document["processing_profile"], document["extraction_state"], artifact["sha256"]) + except FactualReviewRequired: + owned() + self.repository.retain_review(claim, self.candidates, self.store, envelope=envelope) + report(claim, stage, "review_required") + return True + check() + progress("embed") + provider, counter = self.provider_factory(document["processing_profile"]) + provider = FencedProvider(provider, owned) + with stage_document(provider, document_id=document["id"], chunks=chunks, + processing_profile=document["processing_profile"], token_counter=counter) as staged: + check() + progress("publish") + self.repository.publish(claim, staged, self.candidates, self.store) + report(claim, stage, "succeeded") + except LostClaim: + report(claim, stage, "ownership_lost") + except (ExtractionError, EmbeddingError, OSError, ValueError) as exc: + retryable = isinstance(exc, OSError) or getattr(exc, "retryable", False) + code = ("EXTRACTION_REVIEW_REQUIRED" if isinstance(exc, ReviewRequired) + else getattr(exc, "code", "STORAGE_UNAVAILABLE" if isinstance(exc, OSError) else "PROCESSING_INVALID")) + delay = retry_delay(claim.attempt, self.settings.retry_base_seconds, self.settings.retry_cap_seconds) + try: + self.repository.fail(claim, code=code, + retryable=retryable and claim.attempt < self.settings.max_automatic_attempts, delay=delay) + category = ("embedding_error" if isinstance(exc, EmbeddingError) + else "extraction_error" if isinstance(exc, ExtractionError) + else "storage_error" if isinstance(exc, OSError) else "validation_error") + report(claim, stage, category) + except LostClaim: + report(claim, stage, "ownership_lost") + except Exception: + report(claim, stage, "interrupted") + raise + except Exception: + report(claim, stage, "interrupted") + raise + # Unexpected/database errors leave the lease for durable recovery. In + # particular, uncertain commits must not become a new failure/retry write. + return True diff --git a/app/worker.py b/app/worker.py new file mode 100644 index 0000000..0aef887 --- /dev/null +++ b/app/worker.py @@ -0,0 +1,111 @@ +"""Run durable ingestion, independently of the prototype application.""" +import argparse +import json +import logging +import os +import sys +from threading import Event +from uuid import uuid4 + +from app.infrastructure.database import create_database, check_compatibility +from app.infrastructure.extraction_candidates import LocalExtractionCandidates +from app.infrastructure.file_store import LocalFileStore +from app.infrastructure.worker_repository import SqlWorkerRepository +from app.modules.documents.extraction import PageBlockExtractor +from app.modules.documents.settings import IngestionSettings +from app.modules.documents.worker import Worker, logger as worker_logger +from app.modules.documents.types import EmbeddingProfile + + +def factories(settings): + def extractor(profile): + from copy import deepcopy + vision = deepcopy(profile["extraction"]["vision"]) + + class LazyVision: + def transcribe(self, image, **kwargs): + key = settings.vision_api_key + if key is None or not key.get_secret_value().strip(): + raise ValueError("INGEST_VISION_API_KEY is required for vision work") + if vision.get("provider") == "openrouter": + from app.infrastructure.openrouter_vision import OpenRouterVision + adapter = OpenRouterVision(provider=vision["provider"], endpoint=vision["endpoint"], + model=vision["model"], timeout_seconds=vision["timeout_seconds"], + api_key=key.get_secret_value()) + else: + from app.infrastructure.gemini_vision import GeminiVision + adapter = GeminiVision(provider=vision["provider"], endpoint=vision["endpoint"], + model=vision["model"], timeout_seconds=vision["timeout_seconds"], + api_key=key.get_secret_value()) + return adapter.transcribe(image, **kwargs) + + return PageBlockExtractor(LazyVision() if vision["model"] is not None else None) + + def provider(profile): + from app.infrastructure.openai_embeddings import OpenAICompatibleEmbeddings, TiktokenCounter + settings.require_embedding_credentials() + policy = profile["embedding_request"] + counter = None + if policy["limits"] and policy["limits"]["unit"] == "tokens": + identity = policy["limits"]["tokenizer"] + if not identity.startswith("tiktoken:"): + raise ValueError("Unsupported frozen tokenizer") + counter = TiktokenCounter(identity.removeprefix("tiktoken:")) + return OpenAICompatibleEmbeddings(profile=EmbeddingProfile(**profile["embedding"]), + api_key=settings.embedding_api_key.get_secret_value(), token_counter=counter, **policy), counter + + return extractor, provider + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--once", action="store_true", help="Process at most one eligible job") + args = parser.parse_args(argv) + engine = None + handler = logging.StreamHandler(sys.stderr) + handler.setFormatter(logging.Formatter("%(message)s")) + old_level, old_propagate = worker_logger.level, worker_logger.propagate + worker_logger.addHandler(handler) + worker_logger.setLevel(logging.INFO) + worker_logger.propagate = False + try: + settings = IngestionSettings() + engine = create_database(settings.database_url.get_secret_value()) + with engine.connect() as connection: + check_compatibility(connection, settings.embedding_profile, require_worker=True) + repository = SqlWorkerRepository(engine, settings) + store = LocalFileStore(settings.original_directory) + candidates = LocalExtractionCandidates(settings.extraction_directory, + original_directory=settings.original_directory) + worker = Worker(repository, store, candidates, *factories(settings), settings) + worker_id = str(os.getpid()) + ":" + uuid4().hex + stop = Event() + while True: + try: + processed = worker.run_once(worker_id) + except Exception: + print(json.dumps({"error": {"code": "WORKER_INTERRUPTED", + "message": "Durable state will be reconciled on the next poll."}}), file=sys.stderr) + if args.once: + return 1 + processed = False + if args.once: + return 0 + if not processed: + stop.wait(settings.poll_seconds) + except KeyboardInterrupt: + return 0 + except Exception: + print(json.dumps({"error": {"code": "WORKER_FAILED", + "message": "Verify configuration, migration and storage."}}), file=sys.stderr) + return 1 + finally: + worker_logger.removeHandler(handler) + worker_logger.setLevel(old_level) + worker_logger.propagate = old_propagate + if engine is not None: + engine.dispose() + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/migrations/versions/0002_worker_artifact.py b/migrations/versions/0002_worker_artifact.py new file mode 100644 index 0000000..94af82e --- /dev/null +++ b/migrations/versions/0002_worker_artifact.py @@ -0,0 +1,26 @@ +"""Trusted complete-extraction attachment; foundation revision remains immutable.""" +from alembic import op + +revision = "0002_worker_artifact" +down_revision = "0001_ingestion_foundation" +branch_labels = None +depends_on = None + + +def upgrade(**kwargs): + op.execute(""" + ALTER TABLE documents ADD COLUMN extraction_state jsonb NOT NULL DEFAULT '{}', + ADD CONSTRAINT documents_extraction_state_object CHECK ( + jsonb_typeof(extraction_state) = 'object' + AND (NOT extraction_state ? 'complete_artifact' OR ( + jsonb_typeof(extraction_state->'complete_artifact') = 'object' + AND (extraction_state->'complete_artifact') ?& ARRAY['key','sha256','document_id', + 'original_sha256','extraction_profile_sha256'] + AND extraction_state->'complete_artifact'->>'sha256' ~ '^[0-9a-f]{64}$' + )) + ) + """) + + +def downgrade(**kwargs): + op.execute("ALTER TABLE documents DROP COLUMN extraction_state") diff --git a/tests/integration/test_phase5.py b/tests/integration/test_phase5.py new file mode 100644 index 0000000..e94f501 --- /dev/null +++ b/tests/integration/test_phase5.py @@ -0,0 +1,1225 @@ +"""Actual PostgreSQL locks, fencing, replay and crash/commit recovery.""" +from concurrent.futures import ThreadPoolExecutor +from contextlib import contextmanager +from dataclasses import replace +import hashlib +from threading import Event +from uuid import uuid4 + +import pytest +from sqlalchemy import event, 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 EmbeddingProviderError, stage_document +from app.modules.documents.errors import IntakeError +from app.modules.documents.extraction import PageBlockExtractor, ExtractionProviderError +from app.modules.documents.intake import import_document, reconcile +from app.modules.documents.worker import LostClaim, Worker +from tests.unit.test_phase4 import FakeProvider + + +@pytest.fixture +def work(migrated_db, settings, tmp_path): + engine, _ = migrated_db + provider = FakeProvider(settings) + from app.modules.documents.embeddings import EmbeddingLimits + settings = settings.model_copy(update={"embedding_limits": EmbeddingLimits(**provider.request_policy["limits"]), + "chunk_size_characters": 80, "chunk_overlap_characters": 5}) + org, actor = uuid4(), uuid4() + with engine.begin() as conn: + conn.execute(text("INSERT INTO organizations(id,name) VALUES (:id,'worker-test')"), 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) + + def upload(content="alpha " * 420): + source = tmp_path / (uuid4().hex + ".md") + source.write_text(content, encoding="utf-8") + return import_document(intake, store, settings, path=source, administrator_id=actor, + request_id=uuid4())["document"] + + document = upload() + return dict(engine=engine, settings=settings, repo=repo, store=store, + candidates=candidates, actor=actor, document=document, upload=upload) + + +def rows(work): + with work["engine"].connect() as conn: + doc = dict(conn.execute(text("SELECT * FROM documents WHERE id=:id"), + dict(id=work["document"]["id"])).mappings().one()) + job = dict(conn.execute(text("SELECT * FROM ingestion_jobs WHERE document_id=:id"), + dict(id=doc["id"])).mappings().one()) + count = conn.execute(text("SELECT count(*) FROM document_chunks WHERE document_id=:id"), + dict(id=doc["id"])).scalar_one() + return doc, job, count + + +def expire(work): + with work["engine"].begin() as conn: + conn.execute(text("UPDATE ingestion_jobs SET lease_expires_at=clock_timestamp()-interval '1 second'")) + + +def attach(work, claim): + doc = claim.document + envelope = PageBlockExtractor().extract(document_id=doc["id"], title=doc["title"], + original_sha256=doc["file_sha256"], content=work["store"].read(doc["storage_key"]), + mime_type=doc["mime_type"], processing_profile=doc["processing_profile"]) + candidate = work["candidates"].put(envelope, processing_profile=doc["processing_profile"]) + work["repo"].attach(claim, candidate, work["candidates"], work["store"]) + return envelope, candidate + + +def worker(work, extractor=None, provider=None): + return Worker(work["repo"], work["store"], work["candidates"], + lambda profile: extractor or PageBlockExtractor(), + lambda profile: (provider or FakeProvider(work["settings"]), None), work["settings"]) + + +def test_concurrent_claims_single_winner_and_skip_locked(work): + repo = work["repo"] + with ThreadPoolExecutor(max_workers=2) as pool: + claims = list(pool.map(lambda name: repo.claim(name, 120), ["one", "two"])) + assert sum(c is not None for c in claims) == 1 + claim = next(c for c in claims if c is not None) + assert claim.attempt == 1 and claim.token is not None + assert rows(work)[1]["claim_token"] == claim.token + # An independent locked eligible job is skipped, not waited on. + other = work["upload"]() + with work["engine"].begin() as conn: + conn.execute(text("SELECT id FROM ingestion_jobs WHERE document_id=:id FOR UPDATE"), + dict(id=other["id"])) + assert repo.claim("skip", 120) is None + + +def test_claim_does_not_lock_document(work): + with work["engine"].begin() as conn: + conn.execute(text("SELECT id FROM documents FOR UPDATE")) + with ThreadPoolExecutor(max_workers=1) as pool: + future = pool.submit(work["repo"].claim, "quick", 120) + assert future.result(timeout=5) is not None + + +@pytest.mark.parametrize("field", ["deleted_at", "content_purged_at"]) +def test_claim_excludes_removed_originals(work, field): + with work["engine"].begin() as conn: + conn.execute(text("UPDATE documents SET " + field + "=clock_timestamp()")) + assert work["repo"].claim("no", 120) is None + + +@pytest.mark.parametrize("operation", ["progress", "heartbeat", "failure", "attachment", "publication"]) +def test_expired_token_cannot_write_even_before_reclaim(work, operation): + repo = work["repo"] + claim = repo.claim("old", 120) + envelope, candidate = attach(work, claim) + expire(work) + before = rows(work) + with pytest.raises(LostClaim): + if operation == "progress": + repo.progress(claim, "embed") + elif operation == "heartbeat": + repo.heartbeat(claim, 120) + elif operation == "failure": + repo.fail(claim, code="TEST", retryable=True, delay=2) + elif operation == "attachment": + repo.attach(claim, candidate, work["candidates"], work["store"]) + else: + with stage_document(FakeProvider(work["settings"]), document_id=claim.document["id"], + chunks=chunk_extraction(envelope, claim.document["processing_profile"]), + processing_profile=claim.document["processing_profile"]) as staged: + repo.publish(claim, staged, work["candidates"], work["store"]) + assert rows(work) == before + + +def test_reclaim_has_new_token_and_fences_previous_worker(work): + old = work["repo"].claim("old", 120) + expire(work) + current = work["repo"].claim("new", 120) + assert current.token != old.token and current.attempt == 2 + with pytest.raises(LostClaim): + work["repo"].progress(old, "chunk") + work["repo"].progress(current, "extract") + assert rows(work)[0]["status"] == "processing" + + +def test_success_is_atomic_inactive_and_never_republished(work): + assert worker(work).run_once("worker") + doc, job, count = rows(work) + assert doc["status"] == "ready" and job["status"] == "succeeded" + assert count == doc["chunk_count"] > 1 and doc["ready_at"] is not None + assert not doc["is_active"] and job["claim_token"] is None and job["lease_expires_at"] is None + assert not worker(work).run_once("again") + assert rows(work) == (doc, job, count) + + +def test_publication_failure_rolls_back_every_chunk_and_ready_state(work): + claim = work["repo"].claim("worker", 120) + envelope, _ = attach(work, claim) + inserts = [] + + def fail_second(conn, cursor, statement, parameters, context, executemany): + if statement.lstrip().startswith("INSERT INTO document_chunks"): + inserts.append(1) + if len(inserts) == 2: + raise RuntimeError("injected publication failure") + + event.listen(work["engine"], "after_cursor_execute", fail_second) + try: + with stage_document(FakeProvider(work["settings"]), document_id=claim.document["id"], + chunks=chunk_extraction(envelope, claim.document["processing_profile"]), + processing_profile=claim.document["processing_profile"]) as staged: + with pytest.raises(RuntimeError): + work["repo"].publish(claim, staged, work["candidates"], work["store"]) + finally: + event.remove(work["engine"], "after_cursor_execute", fail_second) + doc, job, count = rows(work) + assert count == 0 and doc["chunk_count"] == 0 and doc["ready_at"] is None + assert job["status"] == "processing" and doc["status"] != "ready" + + +def test_lost_commit_acknowledgement_is_reconciled_without_duplicate_chunks(work): + claim = work["repo"].claim("worker", 120) + envelope, _ = attach(work, claim) + engine = work["engine"] + + class LostAcknowledgement: + connect = engine.connect + + @contextmanager + def begin(self): + with engine.begin() as conn: + yield conn + raise OSError("commit acknowledgement interrupted") + + work["repo"].engine = LostAcknowledgement() + with stage_document(FakeProvider(work["settings"]), document_id=claim.document["id"], + chunks=chunk_extraction(envelope, claim.document["processing_profile"]), + processing_profile=claim.document["processing_profile"]) as staged: + assert work["repo"].publish(claim, staged, work["candidates"], work["store"]) + work["repo"].engine = engine + before = rows(work) + assert work["repo"].completed(claim) + assert not worker(work).run_once("restart") + assert rows(work) == before and before[2] > 0 + + +def test_attached_extraction_survives_crash_without_repeating_extractor(work): + claim = work["repo"].claim("crash", 120) + _, candidate = attach(work, claim) + expire(work) + + class MustNotExtract: + def extract(self, **kwargs): + pytest.fail("Validated complete extraction should survive crash") + + assert worker(work, extractor=MustNotExtract()).run_once("recovery") + doc, job, count = rows(work) + assert doc["extraction_state"].get("complete_artifact")["sha256"] == candidate.sha256 + assert job["attempt_count"] == 2 and count > 0 and doc["status"] == "ready" + + +def test_attachment_lease_race_retains_only_unreferenced_candidate(work, monkeypatch): + claim = work["repo"].claim("worker", 120) + doc = claim.document + envelope = PageBlockExtractor().extract(document_id=doc["id"], title=doc["title"], + original_sha256=doc["file_sha256"], content=work["store"].read(doc["storage_key"]), + mime_type=doc["mime_type"], processing_profile=doc["processing_profile"]) + candidate = work["candidates"].put(envelope, processing_profile=doc["processing_profile"]) + inspect = work["candidates"].inspect + + def racing_inspect(*args, **kwargs): + result = inspect(*args, **kwargs) + expire(work) + return result + + monkeypatch.setattr(work["candidates"], "inspect", racing_inspect) + with pytest.raises(LostClaim): + work["repo"].attach(claim, candidate, work["candidates"], work["store"]) + assert rows(work)[0]["extraction_state"].get("complete_artifact") is None + assert work["candidates"].inventory()["candidates"] == [candidate.key] + report = reconcile(SqlIntakeRepository(work["engine"]), work["store"]) + assert report["orphan_files"] == [] and report["missing_originals"] == [] + + +def test_stale_attachment_cannot_replace_successful_extraction(work): + old = work["repo"].claim("old", 120) + _, candidate = attach(work, old) + pointer = rows(work)[0]["extraction_state"].get("complete_artifact") + expire(work) + new = work["repo"].claim("new", 120) + with pytest.raises(LostClaim): + work["repo"].attach(old, candidate, work["candidates"], work["store"]) + assert rows(work)[0]["extraction_state"].get("complete_artifact") == pointer + work["repo"].heartbeat(new, 120) + + +@pytest.mark.parametrize("corruption", ["digest", "original", "profile", "coverage", "warnings"]) +def test_corrupt_or_incomplete_artifact_is_never_reused(work, corruption): + claim = work["repo"].claim("old", 120) + envelope, candidate = attach(work, claim) + expire(work) + path = work["candidates"].directory / candidate.key + if corruption == "original": + work["store"]._path(claim.document["storage_key"]).write_bytes(b"changed original") + else: + import json + payload = json.loads(path.read_bytes()) + if corruption == "digest": + path.write_bytes(b"untrusted bytes") + else: + if corruption == "profile": + payload["extraction_profile_sha256"] = "b" * 64 + elif corruption == "coverage": + payload["blocks"] = payload["blocks"][:1] + payload["blocks"][0]["text"] = "plausible but incomplete" + else: + payload["warnings"] = ["unreviewed source coverage"] + content = json.dumps(payload, ensure_ascii=False).encode() + path.write_bytes(content) + with work["engine"].begin() as conn: + conn.execute(text(""" + UPDATE documents SET extraction_state=jsonb_set( + extraction_state,'{complete_artifact,sha256}',CAST(:digest AS jsonb)) + """), dict(digest=json.dumps(hashlib.sha256(content).hexdigest()))) + assert worker(work).run_once("recovery") + doc, job, count = rows(work) + assert doc["status"] == job["status"] == "failed" and count == 0 + + +def test_heartbeats_continue_during_slow_provider_wait(work): + work["settings"] = work["settings"].model_copy(update={"heartbeat_seconds": 0.02, "lease_seconds": 2.0}) + work["repo"].settings = work["settings"] + entered, release = Event(), Event() + + class SlowProvider(FakeProvider): + def embed(self, texts): + entered.set() + assert release.wait(5) + return super().embed(texts) + + with ThreadPoolExecutor(max_workers=1) as pool: + future = pool.submit(worker(work, provider=SlowProvider(work["settings"])).run_once, "slow") + try: + assert entered.wait(5) + with work["engine"].connect() as conn: + conn.execute(text("SELECT pg_sleep(2.3)")) + assert work["repo"].claim("competitor", 0.3) is None + finally: + release.set() + assert future.result(timeout=5) + assert rows(work)[0]["status"] == "ready" + + +def test_heartbeats_continue_during_extraction(work): + work["settings"] = work["settings"].model_copy(update={"heartbeat_seconds": 0.02, "lease_seconds": 2.0}) + entered, release = Event(), Event() + + class SlowExtractor: + def extract(self, **kwargs): + entered.set() + assert release.wait(5) + return PageBlockExtractor().extract(**kwargs) + + with ThreadPoolExecutor(max_workers=1) as pool: + future = pool.submit(worker(work, extractor=SlowExtractor()).run_once, "slow") + try: + assert entered.wait(5) + with work["engine"].connect() as conn: + conn.execute(text("SELECT pg_sleep(2.3)")) + assert work["repo"].claim("competitor", 0.3) is None + finally: + release.set() + assert future.result(timeout=5) + assert rows(work)[0]["status"] == "ready" + + +def test_late_provider_response_after_reclaim_cannot_publish_or_fail_new_owner(work): + entered, release = Event(), Event() + + class LateProvider(FakeProvider): + def embed(self, texts): + entered.set() + assert release.wait(5) + return super().embed(texts) + + provider = LateProvider(work["settings"]) + with ThreadPoolExecutor(max_workers=1) as pool: + future = pool.submit(worker(work, provider=provider).run_once, "old") + try: + assert entered.wait(5) + expire(work) + current = work["repo"].claim("new", 120) + before = rows(work) + finally: + release.set() + assert future.result(timeout=5) + assert rows(work) == before and rows(work)[1]["claim_token"] == current.token + assert rows(work)[2] == 0 + assert len(provider.calls) == 1 + + +@pytest.mark.parametrize("retryable", [True, False]) +def test_failure_classification_and_durable_stage(work, retryable): + class BrokenProvider(FakeProvider): + def embed(self, texts): + raise EmbeddingProviderError("sensitive provider detail", retryable=retryable) + + assert worker(work, provider=BrokenProvider(work["settings"])).run_once("fail") + doc, job, count = rows(work) + assert count == 0 and job["stage"] == "embed" + assert doc["status"] == job["status"] == ("queued" if retryable else "failed") + assert job["error_retryable"] == retryable and job["claim_token"] is None + assert "sensitive" not in job["error_message"] + assert job["next_attempt_at"] > job["created_at"] + + +def test_expired_exhausted_job_is_terminal_without_provider_calls(work): + work["repo"].claim("crashed-final-attempt", 120) + expire(work) + with work["engine"].begin() as conn: + conn.execute(text("UPDATE ingestion_jobs SET attempt_count=:n"), + dict(n=work["settings"].max_automatic_attempts)) + + class MustNotExtract: + def extract(self, **kwargs): + pytest.fail("Exhausted recovery cannot call providers") + + assert worker(work, extractor=MustNotExtract()).run_once("exhausted") + doc, job, count = rows(work) + assert doc["status"] == job["status"] == "failed" + assert job["error_code"] == "ATTEMPTS_EXHAUSTED" and count == 0 + + +def test_retry_replay_is_atomic_and_uses_same_document_and_job(work): + claim = work["repo"].claim("worker", 120) + work["repo"].fail(claim, code="PROVIDER", retryable=False, delay=0) + request = uuid4() + + def retry(_): + return work["repo"].retry(administrator_id=work["actor"], + document_id=claim.document["id"], request_id=request, store=work["store"]) + + with ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(retry, range(2))) + assert sorted(r["replayed"] for r in results) == [False, True] + assert all(r["retry_generation"] == 1 and r["job_id"] == str(claim.job_id) for r in results) + doc, job, count = rows(work) + assert doc["status"] == job["status"] == "queued" and job["attempt_count"] == 0 and count == 0 + current = work["repo"].claim("new", 120) + assert current.generation == 1 and current.attempt == 1 + assert retry(0)["replayed"] + with work["engine"].connect() as conn: + assert conn.execute(text("SELECT count(*) FROM audit_events WHERE action='ingestion_retry'")).scalar_one() == 1 + with pytest.raises(IntakeError, match="eligible failed"): + work["repo"].retry(administrator_id=work["actor"], document_id=doc["id"], + request_id=uuid4(), store=work["store"]) + + +@pytest.mark.parametrize("reason", ["disabled", "removed", "missing", "review"]) +def test_retry_validates_administrator_original_and_review_gate(work, reason): + claim = work["repo"].claim("worker", 120) + work["repo"].fail(claim, code="EXTRACTION_REVIEW_REQUIRED" if reason == "review" else "TEST", + retryable=False, delay=0) + if reason == "missing": + work["store"]._path(claim.document["storage_key"]).unlink() + elif reason in ("disabled", "removed"): + with work["engine"].begin() as conn: + conn.execute(text("UPDATE users SET is_enabled=false" if reason == "disabled" + else "UPDATE documents SET deleted_at=clock_timestamp()")) + before = rows(work) + with pytest.raises(IntakeError): + work["repo"].retry(administrator_id=work["actor"], document_id=claim.document["id"], + request_id=uuid4(), store=work["store"]) + assert rows(work) == before + +def test_publication_lease_expiry_after_chunk_inserts_rolls_back(work): + claim = work["repo"].claim("worker", 120) + envelope, _ = attach(work, claim) + + def expire_during_insert(conn, cursor, statement, parameters, context, executemany): + if statement.lstrip().startswith("INSERT INTO document_chunks"): + conn.execute(text("UPDATE ingestion_jobs SET lease_expires_at=clock_timestamp()-interval '1 second'")) + + event.listen(work["engine"], "after_cursor_execute", expire_during_insert) + try: + with stage_document(FakeProvider(work["settings"]), document_id=claim.document["id"], + chunks=chunk_extraction(envelope, claim.document["processing_profile"]), + processing_profile=claim.document["processing_profile"]) as staged: + with pytest.raises(LostClaim): + work["repo"].publish(claim, staged, work["candidates"], work["store"]) + finally: + event.remove(work["engine"], "after_cursor_execute", expire_during_insert) + doc, job, count = rows(work) + assert count == 0 and doc["status"] != "ready" and job["status"] == "processing" + + +def test_lease_is_checked_after_waiting_for_document_lock(work): + claim = work["repo"].claim("worker", 0.5) + with ThreadPoolExecutor(max_workers=1) as pool: + with work["engine"].begin() as conn: + conn.execute(text("SELECT id FROM documents FOR UPDATE")) + future = pool.submit(work["repo"].progress, claim, "embed") + conn.execute(text("SELECT pg_sleep(0.7)")) + with pytest.raises(LostClaim): + future.result(timeout=5) + assert rows(work)[0]["status"] == "queued" + + +def test_rechunking_reuses_attached_extraction(work): + claim = work["repo"].claim("crash", 120) + attach(work, claim) + expire(work) + import json + profile = claim.document["processing_profile"] + profile["chunk_size"] = 64 + with work["engine"].begin() as conn: + conn.execute(text("UPDATE documents SET processing_profile=CAST(:profile AS jsonb)"), + dict(profile=json.dumps(profile))) + + class MustNotExtract: + def extract(self, **kwargs): + pytest.fail("Rechunking cannot repeat provider extraction") + + assert worker(work, extractor=MustNotExtract()).run_once("rechunk") + assert rows(work)[0]["status"] == "ready" + + +@pytest.mark.parametrize("mutation", ["deletion", "profile", "original"]) +def test_changed_source_or_eligibility_prevents_publication(work, mutation): + claim = work["repo"].claim("worker", 120) + envelope, _ = attach(work, claim) + if mutation == "original": + work["store"]._path(claim.document["storage_key"]).write_bytes(b"changed") + else: + with work["engine"].begin() as conn: + conn.execute(text("UPDATE documents SET deleted_at=clock_timestamp()" if mutation == "deletion" + else "UPDATE documents SET processing_profile=jsonb_set(processing_profile,'{chunk_size}','64')")) + with stage_document(FakeProvider(work["settings"]), document_id=claim.document["id"], + chunks=chunk_extraction(envelope, claim.document["processing_profile"]), + processing_profile=claim.document["processing_profile"]) as staged: + with pytest.raises((LostClaim, ValueError)): + work["repo"].publish(claim, staged, work["candidates"], work["store"]) + assert rows(work)[2] == 0 and rows(work)[0]["status"] != "ready" + + +def test_failed_last_embedding_batch_has_no_publication_and_reuses_extraction(work): + provider = FakeProvider(work["settings"], fail_at=2) + assert worker(work, provider=provider).run_once("fail") + doc, job, count = rows(work) + assert len(provider.calls) == 2 and count == 0 and job["status"] == "queued" + assert doc["extraction_state"].get("complete_artifact") is not None + with work["engine"].begin() as conn: + conn.execute(text("UPDATE ingestion_jobs SET next_attempt_at=clock_timestamp()")) + assert worker(work).run_once("recovery") + assert rows(work)[0]["status"] == "ready" + +def test_unknown_commit_outcome_is_not_converted_to_failure_or_retry(work, monkeypatch): + from app.infrastructure.worker_repository import PublicationUncertain + claim = work["repo"].claim("worker", 120) + envelope, _ = attach(work, claim) + engine = work["engine"] + + class LostAcknowledgement: + connect = engine.connect + + @contextmanager + def begin(self): + with engine.begin() as conn: + yield conn + raise OSError("commit acknowledgement lost") + + def unavailable_read(claim): + raise OSError("database unavailable") + + work["repo"].engine = LostAcknowledgement() + monkeypatch.setattr(work["repo"], "completed", unavailable_read) + with stage_document(FakeProvider(work["settings"]), document_id=claim.document["id"], + chunks=chunk_extraction(envelope, claim.document["processing_profile"]), + processing_profile=claim.document["processing_profile"]) as staged: + with pytest.raises(PublicationUncertain): + work["repo"].publish(claim, staged, work["candidates"], work["store"]) + work["repo"].engine = engine + assert rows(work)[0]["status"] == "ready" and rows(work)[1]["status"] == "succeeded" + assert not worker(work).run_once("recovery") + + +def test_attaching_candidate_verifies_original_checksum(work): + claim = work["repo"].claim("worker", 120) + doc = claim.document + envelope = PageBlockExtractor().extract(document_id=doc["id"], title=doc["title"], + original_sha256=doc["file_sha256"], content=work["store"].read(doc["storage_key"]), + mime_type=doc["mime_type"], processing_profile=doc["processing_profile"]) + candidate = work["candidates"].put(envelope, processing_profile=doc["processing_profile"]) + work["store"]._path(doc["storage_key"]).write_bytes(b"changed") + with pytest.raises(ValueError): + work["repo"].attach(claim, candidate, work["candidates"], work["store"]) + assert rows(work)[0]["extraction_state"] == {} and rows(work)[2] == 0 + + +def test_uncommitted_candidate_is_not_discovered_as_a_trusted_attachment(work): + claim = work["repo"].claim("crash", 120) + doc = claim.document + envelope = PageBlockExtractor().extract(document_id=doc["id"], title=doc["title"], + original_sha256=doc["file_sha256"], content=work["store"].read(doc["storage_key"]), + mime_type=doc["mime_type"], processing_profile=doc["processing_profile"]) + orphan = work["candidates"].put(envelope, processing_profile=doc["processing_profile"]) + expire(work) + + class CountsExtraction: + calls = 0 + + def extract(self, **kwargs): + self.calls += 1 + return PageBlockExtractor().extract(**kwargs) + + extractor = CountsExtraction() + assert worker(work, extractor=extractor).run_once("recover") + assert extractor.calls == 1 + pointer = rows(work)[0]["extraction_state"]["complete_artifact"] + assert pointer["key"] != orphan.key + assert orphan.key in work["candidates"].inventory()["candidates"] + + +def test_forward_migration_requires_worker_column_but_preserves_foundation(work, migrated_db, settings): + from alembic import command + from app.infrastructure.database import check_compatibility, CompatibilityError + engine, config = migrated_db + with engine.begin() as conn: + config.attributes["connection"] = conn + command.downgrade(config, "0001_ingestion_foundation") + check_compatibility(conn, settings.embedding_profile) + with pytest.raises(CompatibilityError): + check_compatibility(conn, settings.embedding_profile, require_worker=True) + command.upgrade(config, "head") + check_compatibility(conn, settings.embedding_profile, require_worker=True) + assert conn.execute(text("SELECT extraction_state FROM documents")).scalar_one() == {} + +# Extended Phase 5: actual review persistence, exact-output resume and FAQ inclusion. +def review_service(work): + from app.infrastructure.review_repository import SqlReviewRepository + from app.modules.documents.review import AdministratorIdentity + service = SqlReviewRepository(work["engine"], work["settings"], work["candidates"], work["store"]) + identity = AdministratorIdentity(work["actor"], work["document"]["organization_id"]) + return service, identity + + +def review_source(work, kind="image", *, pages=1, direct=False): + import json + from io import BytesIO + from PIL import Image + import pymupdf + if kind == "image": + stream = BytesIO() + Image.new("RGB", (40, 40), "white").save(stream, "PNG") + content, mime = stream.getvalue(), "image/png" + elif kind == "pdf": + source = pymupdf.open() + for i in range(pages): + page = source.new_page(width=150, height=150) + if direct: + page.insert_text((20, 40), "Evidence page " + str(i + 1)) + else: + page.draw_rect(pymupdf.Rect(20, 20, 60, 60), fill=(1, 0, 0)) + content, mime = source.tobytes(), "application/pdf" + source.close() + else: + content = b"Question: fee\nAnswer: 5%\nQuestion: greeting\nAnswer: scripted welcome\nQuestion: balance\nAnswer: \n" + mime = "text/markdown" + profile = work["document"]["processing_profile"] + profile["extraction"]["vision"] = dict(provider="gemini", endpoint="https://frozen.invalid", + model="frozen-model", timeout_seconds=7) + # Fixture setup pins a supported source/profile before the first worker claim. + key = work["store"].put(content) + with work["engine"].begin() as conn: + conn.execute(text(""" + UPDATE documents SET storage_key=:key,size_bytes=:size,file_sha256=:sha, + mime_type=:mime,processing_profile=CAST(:profile AS jsonb) WHERE id=:id + """), dict(id=work["document"]["id"], key=key, size=len(content), sha=hashlib.sha256(content).hexdigest(), + mime=mime, profile=json.dumps(profile))) + work["document"] = rows(work)[0] + return content + + +class ReviewedVision: + def __init__(self): + self.calls = [] + def transcribe(self, image, *, page, section, processing_profile): + from app.modules.documents.types import ExtractedBlock + self.calls.append(page) + locator = section + "/block/1" + return (ExtractedBlock(ordinal=0, block_id=locator, source_locator=locator, + section=locator, page=page, text="Retained evidence " + str(page or "image"), + method="vision", actual_model="frozen-model"),) + + +def review_worker(work, vision): + return Worker(work["repo"], work["store"], work["candidates"], + lambda profile: PageBlockExtractor(vision), + lambda profile: (FakeProvider(work["settings"]), None), work["settings"]) + + +def approve(work, *, request_id=None, decision="approve", excluded=()): + service, identity = review_service(work) + item = service.read(identity, work["document"]["id"])["items"][-1] + result = service.decide(identity, work["document"]["id"], request_id=request_id or uuid4(), + payload=dict(evidence_sha256=item["evidence_sha256"], decision=decision, + checked=item["required_checks"], note="Inspected exact retained evidence", + excluded_group_ids=list(excluded))) + return item, result + + +def resume_retry(work, request=None): + return work["repo"].retry(administrator_id=work["actor"], document_id=work["document"]["id"], + request_id=request or uuid4(), store=work["store"], candidates=work["candidates"]) + + +@pytest.mark.parametrize("kind,direct", [("image", False), ("pdf", False), ("pdf", True)]) +def test_review_retained_failed_approval_and_exact_resume(work, kind, direct): + original = review_source(work, kind, direct=direct) + vision = ReviewedVision() + assert review_worker(work, vision).run_once("first") + doc, job, count = rows(work) + assert doc["status"] == job["status"] == "failed" and count == 0 + assert job["error_code"] == "EXTRACTION_REVIEW_REQUIRED" and job["claim_token"] is None + assert doc["extraction_state"].get("complete_artifact") is None + service, identity = review_service(work) + item = service.read(identity, doc["id"])["items"][0] + preview, mime = service.preview(identity, doc["id"], item["evidence_sha256"]) + assert preview and mime == "image/png" + with pytest.raises(IntakeError): + resume_retry(work) + approve(work) + before = list(vision.calls) + resume_retry(work) + assert review_worker(work, vision).run_once("restart") + ready, succeeded, count = rows(work) + assert ready["status"] == "ready" and succeeded["status"] == "succeeded" + assert count > 0 and not ready["is_active"] and vision.calls == before + assert work["store"].read(ready["storage_key"]) == original + + +def test_multipage_review_progress_survives_restart_without_repeating_approved_ocr(work): + review_source(work, "pdf", pages=3) + vision = ReviewedVision() + for page in (1, 2, 3): + assert review_worker(work, vision).run_once("restart-" + str(page)) + assert vision.calls == list(range(1, page + 1)) + assert rows(work)[2] == 0 + doc = rows(work)[0] + assert len(doc["extraction_state"]["candidates"]) == page + assert doc["extraction_state"]["progress"]["next_locator"] == "pdf/page/" + str(page) + approve(work) + resume_retry(work) + assert review_worker(work, vision).run_once("final") + assert vision.calls == [1, 2, 3] and rows(work)[0]["status"] == "ready" + assert len(rows(work)[0]["extraction_state"]["candidates"]) == 3 + + +def test_rejected_review_stays_failed_and_never_calls_provider_again(work): + review_source(work) + vision = ReviewedVision() + review_worker(work, vision).run_once("review") + _, response = approve(work, decision="reject") + assert not response["review_required"] + with pytest.raises(IntakeError): + resume_retry(work) + assert not review_worker(work, vision).run_once("rejected") + assert vision.calls == [None] and rows(work)[2] == 0 + assert rows(work)[1]["error_code"] == "EXTRACTION_REVIEW_REJECTED" + + +def test_concurrent_review_decision_and_retry_replays_are_atomic(work): + review_source(work) + review_worker(work, ReviewedVision()).run_once("review") + service, identity = review_service(work) + item = service.read(identity, work["document"]["id"])["items"][0] + request = uuid4() + payload = dict(evidence_sha256=item["evidence_sha256"], decision="approve", + checked=item["required_checks"], note="Inspected exact source", excluded_group_ids=[]) + def decide(_): + return service.decide(identity, work["document"]["id"], request_id=request, payload=payload) + with ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(decide, range(2))) + assert sorted(r["replayed"] for r in results) == [False, True] + retry_key = uuid4() + with ThreadPoolExecutor(max_workers=2) as pool: + retries = list(pool.map(lambda _: resume_retry(work, retry_key), range(2))) + assert sorted(r["replayed"] for r in retries) == [False, True] + assert rows(work)[1]["retry_generation"] == 1 + assert decide(0)["replayed"] # replay precedes running eligibility. + with pytest.raises(IntakeError) as error: + service.decide(identity, work["document"]["id"], request_id=request, + payload={**payload, "note": "changed payload"}) + assert error.value.code == "IDEMPOTENCY_CONFLICT" + with work["engine"].connect() as conn: + assert conn.execute(text("SELECT count(*) FROM audit_events WHERE action='extraction_review'")).scalar_one() == 1 + assert conn.execute(text("SELECT count(*) FROM audit_events WHERE action='ingestion_retry'")).scalar_one() == 1 + + +@pytest.mark.parametrize("mutation", ["digest", "profile", "source", "candidate"]) +def test_stale_evidence_or_source_cannot_be_approved(work, mutation): + import json + review_source(work) + review_worker(work, ReviewedVision()).run_once("review") + service, identity = review_service(work) + item = service.read(identity, work["document"]["id"])["items"][0] + digest = item["evidence_sha256"] + if mutation == "digest": + digest = "b" * 64 + elif mutation == "source": + work["store"]._path(rows(work)[0]["storage_key"]).write_bytes(b"changed source") + else: + with work["engine"].begin() as conn: + if mutation == "profile": + conn.execute(text("UPDATE documents SET processing_profile=jsonb_set(processing_profile,'{extraction,render_dpi}','72')")) + else: + conn.execute(text("UPDATE documents SET extraction_state=jsonb_set(extraction_state,'{candidates}','[]')")) + with pytest.raises(IntakeError) as error: + service.decide(identity, work["document"]["id"], request_id=uuid4(), + payload=dict(evidence_sha256=digest, decision="approve", checked=item["required_checks"], note="review")) + assert error.value.code == "REVIEW_STALE" and rows(work)[2] == 0 + + +def test_already_decided_review_cannot_be_overwritten_by_new_key(work): + review_source(work) + review_worker(work, ReviewedVision()).run_once("review") + item, _ = approve(work) + service, identity = review_service(work) + assert service.read(identity, work["document"]["id"])["items"] == [] + with pytest.raises(IntakeError) as error: + service.decide(identity, work["document"]["id"], request_id=uuid4(), + payload=dict(evidence_sha256=item["evidence_sha256"], decision="reject", + checked=item["required_checks"], note="New conflicting decision")) + assert error.value.code == "REVIEW_ALREADY_DECIDED" + assert rows(work)[0]["extraction_state"]["candidates"][0]["decision"]["decision"] == "approve" + + +def test_revoked_administrator_cannot_read_preview_decide_or_replay(work): + review_source(work) + review_worker(work, ReviewedVision()).run_once("review") + key = uuid4() + item, _ = approve(work, request_id=key) + service, identity = review_service(work) + with work["engine"].begin() as conn: + conn.execute(text("UPDATE users SET is_enabled=false")) + with pytest.raises(IntakeError): + service.read(identity, work["document"]["id"]) + with pytest.raises(IntakeError): + service.preview(identity, work["document"]["id"], item["evidence_sha256"]) + with pytest.raises(IntakeError): + service.decide(identity, work["document"]["id"], request_id=key, + payload=dict(evidence_sha256=item["evidence_sha256"], decision="approve", + checked=item["required_checks"], note="Inspected exact retained evidence")) + with pytest.raises(IntakeError): + resume_retry(work) + + +def test_revocation_during_review_validation_prevents_decision_commit(work, monkeypatch): + review_source(work) + review_worker(work, ReviewedVision()).run_once("review") + service, identity = review_service(work) + item = service.read(identity, work["document"]["id"])["items"][0] + body = service._body + def revoke(*args): + result = body(*args) + with work["engine"].begin() as conn: + conn.execute(text("UPDATE users SET role='user'")) + return result + monkeypatch.setattr(service, "_body", revoke) + with pytest.raises(IntakeError): + service.decide(identity, work["document"]["id"], request_id=uuid4(), + payload=dict(evidence_sha256=item["evidence_sha256"], decision="approve", + checked=item["required_checks"], note="review")) + assert rows(work)[0]["extraction_state"]["candidates"][0].get("decision") is None + + +def test_decision_and_audit_roll_back_together(work): + review_source(work) + review_worker(work, ReviewedVision()).run_once("review") + before = rows(work) + def reject_audit(conn, cursor, statement, parameters, context, executemany): + if statement.lstrip().startswith("INSERT INTO audit_events"): + raise RuntimeError("injected audit failure") + event.listen(work["engine"], "before_cursor_execute", reject_audit) + try: + with pytest.raises(RuntimeError): + approve(work) + finally: + event.remove(work["engine"], "before_cursor_execute", reject_audit) + assert rows(work) == before + with work["engine"].connect() as conn: + assert conn.execute(text("SELECT count(*) FROM audit_events WHERE action='extraction_review'")).scalar_one() == 0 + + +def test_review_attachment_lease_race_cannot_attach_untrusted_orphan(work, monkeypatch): + from app.infrastructure.review_candidates import LocalReviewCandidates + review_source(work) + original_put = LocalReviewCandidates.put + def put_then_expire(self, *args, **kwargs): + pointer = original_put(self, *args, **kwargs) + expire(work) + return pointer + monkeypatch.setattr(LocalReviewCandidates, "put", put_then_expire) + assert review_worker(work, ReviewedVision()).run_once("stale") + assert rows(work)[0]["extraction_state"] == {} and rows(work)[2] == 0 + assert len(list(work["candidates"].directory.glob("*.review.json"))) == 1 + service, identity = review_service(work) + assert service.read(identity, work["document"]["id"])["items"] == [] + + +def test_late_vision_response_after_reclaim_does_not_attach_or_start_more_provider_work(work): + review_source(work, "pdf", pages=2) + entered, release = Event(), Event() + class LateVision(ReviewedVision): + def transcribe(self, *args, **kwargs): + entered.set() + assert release.wait(5) + return super().transcribe(*args, **kwargs) + vision = LateVision() + with ThreadPoolExecutor(max_workers=1) as pool: + future = pool.submit(review_worker(work, vision).run_once, "old") + try: + assert entered.wait(5) + expire(work) + current = work["repo"].claim("new", 120) + before = rows(work) + finally: + release.set() + assert future.result(timeout=5) + assert vision.calls == [1] and rows(work) == before + assert current.token == rows(work)[1]["claim_token"] + + +def test_mixed_faq_authority_and_exclusion_preserve_faithful_complete_artifact(work): + review_source(work, "faq") + assert worker(work).run_once("extract-faq") + doc, job, count = rows(work) + assert job["error_code"] == "EXTRACTION_REVIEW_REQUIRED" and count == 0 + pointer = doc["extraction_state"]["complete_artifact"] + envelope = work["candidates"].inspect_pointer(pointer, document=doc) + assert "" in "".join(b.text for b in envelope.blocks) + service, identity = review_service(work) + item = service.read(identity, doc["id"])["items"][0] + assert item["review_kind"] == "factual_corpus" and not item["preview_available"] + groups = {b.group_id for b in envelope.blocks if b.block_type in ("question", "answer")} + keep = next(b.group_id for b in envelope.blocks if "fee" in b.text) + # The authority decision cannot approve a placeholder or split a pair. + with pytest.raises(IntakeError): + approve(work) + with pytest.raises(IntakeError): + approve(work, excluded=list(groups)) + with pytest.raises(IntakeError): + approve(work, excluded=["client-invented-group"]) + approve(work, excluded=list(groups - {keep})) + resume_retry(work) + assert worker(work).run_once("approved-facts") + ready, job, count = rows(work) + assert ready["status"] == "ready" and count == 1 + assert ready["extraction_state"]["complete_artifact"] == pointer + retained = work["candidates"].inspect_pointer(pointer, document=ready) + assert retained == envelope + with work["engine"].connect() as conn: + chunk = conn.execute(text("SELECT text FROM document_chunks")).scalar_one() + assert "fee" in chunk and "5%" in chunk and "greeting" not in chunk and "placeholder" not in chunk + + +def test_publication_revalidates_factual_manifest_and_rolls_back(work): + from app.modules.documents.review import prepare_chunks + review_source(work, "faq") + worker(work).run_once("faq") + doc = rows(work)[0] + pointer = doc["extraction_state"]["complete_artifact"] + envelope = work["candidates"].inspect_pointer(pointer, document=doc) + groups = {b.group_id for b in envelope.blocks if b.block_type in ("question", "answer")} + keep = next(b.group_id for b in envelope.blocks if "fee" in b.text) + approve(work, excluded=list(groups - {keep})) + resume_retry(work) + claim = work["repo"].claim("stage", 120) + drafts = prepare_chunks(envelope, doc["processing_profile"], claim.document["extraction_state"], pointer["sha256"]) + with stage_document(FakeProvider(work["settings"]), document_id=doc["id"], chunks=drafts, + processing_profile=doc["processing_profile"]) as staged: + with work["engine"].begin() as conn: + conn.execute(text("UPDATE documents SET extraction_state=jsonb_set(extraction_state,'{factual_inclusion,artifact_sha256}',to_jsonb(CAST(:digest AS text)))"), + dict(digest="b" * 64)) + with pytest.raises(ValueError): + work["repo"].publish(claim, staged, work["candidates"], work["store"]) + assert rows(work)[2] == 0 and rows(work)[0]["status"] != "ready" + + +def test_review_audit_requires_identity_target_key_hash_and_saved_response(work): + from sqlalchemy.exc import IntegrityError + for field in ("actor", "target", "key", "hash", "response"): + values = dict(id=uuid4(), org=work["document"]["organization_id"], actor=work["actor"], + target=work["document"]["id"], key=uuid4(), hash="a" * 64, response="{}") + values[field] = None + with pytest.raises(IntegrityError): + with work["engine"].begin() as conn: + conn.execute(text(""" + INSERT INTO audit_events(id,organization_id,actor_user_id,action,target_id,idempotency_key,request_hash,response_json) + VALUES (:id,:org,:actor,'extraction_review',:target,:key,:hash,CAST(:response AS jsonb)) + """), values) + +@pytest.mark.parametrize("mutation", ["source", "profile"]) +def test_approved_evidence_is_revalidated_before_manual_retry(work, mutation): + review_source(work) + review_worker(work, ReviewedVision()).run_once("review") + approve(work) + if mutation == "source": + work["store"]._path(rows(work)[0]["storage_key"]).write_bytes(b"changed") + else: + with work["engine"].begin() as conn: + conn.execute(text("UPDATE documents SET processing_profile=jsonb_set(processing_profile,'{extraction,render_dpi}','72')")) + before = rows(work) + with pytest.raises(IntakeError): + resume_retry(work) + assert rows(work) == before + + +def test_cross_organization_identity_cannot_read_or_decide(work): + from app.modules.documents.review import AdministratorIdentity + review_source(work) + review_worker(work, ReviewedVision()).run_once("review") + service, identity = review_service(work) + forged = AdministratorIdentity(identity.user_id, uuid4()) + with pytest.raises(IntakeError): + service.read(forged, work["document"]["id"]) + with pytest.raises(IntakeError): + service.decide(forged, work["document"]["id"], request_id=uuid4(), payload={}) + + +def test_runtime_duration_rejected_before_database_claim_or_heartbeat(work): + before = rows(work) + with pytest.raises(ValueError): + work["repo"].claim("overflow", 1e20) + assert rows(work) == before + claim = work["repo"].claim("valid", 120) + before = rows(work) + with pytest.raises(ValueError): + work["repo"].heartbeat(claim, 1e20) + assert rows(work) == before + + +def test_factual_faq_all_pairs_can_be_approved_without_global_chunk_flag(work): + import json + content = b"Question: fee\nAnswer: 5%\n" + key = work["store"].put(content) + with work["engine"].begin() as conn: + conn.execute(text(""" + UPDATE documents SET storage_key=:key,size_bytes=:size,file_sha256=:sha WHERE id=:id + """), dict(id=work["document"]["id"], key=key, size=len(content), sha=hashlib.sha256(content).hexdigest())) + work["document"] = rows(work)[0] + assert worker(work).run_once("faq") + assert rows(work)[2] == 0 + approve(work) + resume_retry(work) + assert worker(work).run_once("approved") + assert rows(work)[0]["status"] == "ready" and rows(work)[2] == 1 + + +def test_preview_rechecks_candidate_attachment_after_file_validation(work, monkeypatch): + review_source(work) + review_worker(work, ReviewedVision()).run_once("review") + service, identity = review_service(work) + item = service.read(identity, work["document"]["id"])["items"][0] + body = service._body + def removed(*args): + value = body(*args) + with work["engine"].begin() as conn: + conn.execute(text("UPDATE documents SET extraction_state=jsonb_set(extraction_state,'{candidates}','[]')")) + return value + monkeypatch.setattr(service, "_body", removed) + with pytest.raises(IntakeError) as error: + service.preview(identity, work["document"]["id"], item["evidence_sha256"]) + assert error.value.code == "REVIEW_STALE" + +def test_whole_faq_context_with_placeholder_is_retained_but_never_included(work): + from app.modules.documents.types import ExtractedBlock + review_source(work) + class FaqVision: + calls = 0 + def transcribe(self, image, *, page, section, processing_profile): + self.calls += 1 + values = [] + for group, texts in [("image/qa-placeholder", ["Question: balance", "Answer: unavailable", ""]), + ("image/qa-factual", ["Question: fee", "Answer: 5%"])]: + for i, text_value in enumerate(texts): + locator = group + "/block/" + str(i + 1) + values.append(ExtractedBlock(ordinal=len(values), block_id=locator, source_locator=locator, + section=locator, text=text_value, group_id=group, method="vision", actual_model="frozen-model", + block_type=("question", "answer", "caption")[i])) + return tuple(values) + vision = FaqVision() + assert review_worker(work, vision).run_once("image-review") + approve(work) + resume_retry(work) + assert review_worker(work, vision).run_once("authority-review") + assert rows(work)[0]["status"] == "failed" and rows(work)[2] == 0 + pointer = rows(work)[0]["extraction_state"]["complete_artifact"] + envelope = work["candidates"].inspect_pointer(pointer, document=rows(work)[0]) + assert any(b.block_type == "caption" and "placeholder" in b.text for b in envelope.blocks) + approve(work, excluded=["image/qa-placeholder"]) + resume_retry(work) + assert review_worker(work, vision).run_once("publish") + assert vision.calls == 1 and rows(work)[0]["status"] == "ready" and rows(work)[2] == 1 + with work["engine"].connect() as conn: + value = conn.execute(text("SELECT text FROM document_chunks")).scalar_one() + assert "5%" in value and "placeholder" not in value and "balance" not in value + +# Scoped Phase 5 backend repair regression evidence. +def test_complete_attachment_replay_preserves_all_metadata(work): + import json + claim = work["repo"].claim("attach", 120) + _, candidate = attach(work, claim) + with work["engine"].begin() as conn: + conn.execute(text("UPDATE documents SET extraction_state=extraction_state || CAST(:extra AS jsonb)"), + dict(extra=json.dumps(dict(candidates=[{"retained": "evidence", "decision": {"note": "checked"}}], + factual_inclusion={"retained": "manifest"}, progress={"next": "page/2"})))) + before = rows(work)[0]["extraction_state"] + work["repo"].attach(claim, candidate, work["candidates"], work["store"]) + assert rows(work)[0]["extraction_state"] == before + + +@pytest.mark.parametrize("lease_state", ["current", "expired", "reclaimed"]) +def test_conflicting_complete_attachment_never_replaces_metadata(work, lease_state): + import json + claim = work["repo"].claim("first", 120) + envelope, candidate = attach(work, claim) + extra = dict(candidates=[{"retained": "evidence", "decision": {"reviewer": str(work["actor"]), "note": "approved"}}], + factual_inclusion={"retained": "manifest"}, progress={"next": "page/2"}) + with work["engine"].begin() as conn: + conn.execute(text("UPDATE documents SET extraction_state=extraction_state || CAST(:extra AS jsonb)"), + dict(extra=json.dumps(extra))) + before = rows(work)[0]["extraction_state"] + other = work["candidates"].put(envelope, processing_profile=claim.document["processing_profile"]) + assert other.key != candidate.key + if lease_state != "current": + expire(work) + if lease_state == "reclaimed": + assert work["repo"].claim("replacement", 120) + with pytest.raises(LostClaim): + work["repo"].attach(claim, other, work["candidates"], work["store"]) + assert rows(work)[0]["extraction_state"] == before + if lease_state != "current": + with pytest.raises(LostClaim): + work["repo"].attach(claim, candidate, work["candidates"], work["store"]) + assert rows(work)[0]["extraction_state"] == before + assert rows(work)[2] == 0 + + +def factual_context_source(work): + import json + original = b"## Eligibility\nThese answers apply only to permanent employees.\nQuestion: allowance?\nAnswer: The allowance is 5%.\nQuestion: leave?\nAnswer: 10 days.\n" + profile = work["document"]["processing_profile"] + profile["chunk_size"] = 2000 + profile["embedding_request"]["limits"].update(max_input_units=1000, max_batch_units=2000) + key = work["store"].put(original) + with work["engine"].begin() as conn: + conn.execute(text("""UPDATE documents SET storage_key=:key, size_bytes=:size, + file_sha256=:sha, processing_profile=CAST(:profile AS jsonb) WHERE id=:id"""), + dict(id=work["document"]["id"], key=key, size=len(original), + sha=hashlib.sha256(original).hexdigest(), profile=json.dumps(profile))) + work["document"] = rows(work)[0] + return original + + +@pytest.mark.parametrize("legacy_candidate", [False, True]) +def test_factual_review_exposes_context_and_publishes_same_validated_drafts(work, monkeypatch, legacy_candidate): + from app.modules.documents.review import prepare_chunks, factual_groups + from app.modules.documents.types import ChunkDraft + if legacy_candidate: + # Generate the previously supported candidate shape in its own immutable + # file; never rewrite an attached file to make it pass validation. + monkeypatch.setattr("app.infrastructure.review_candidates.factual_review_blocks", + lambda envelope: tuple(b for b in envelope.blocks if b.group_id in factual_groups(envelope))) + original = factual_context_source(work) + worker(work).run_once("factual") + doc, job, count = rows(work) + assert job["error_code"] == "EXTRACTION_REVIEW_REQUIRED" and count == 0 + artifact = doc["extraction_state"]["complete_artifact"] + pointer = doc["extraction_state"]["candidates"][0] + retained_bytes = (work["candidates"].directory / pointer["key"]).read_bytes() + envelope = work["candidates"].inspect_pointer(artifact, document=doc) + service, identity = review_service(work) + item = service.read(identity, doc["id"])["items"][0] + assert item["review_kind"] == "factual_corpus" + assert item["blocks"] == [b.model_dump(mode="json") for b in envelope.blocks] + assert "permanent employees" in item["blocks"][0]["text"] + approve(work) + resume_retry(work) + claim = work["repo"].claim("publish", 120) + drafts = prepare_chunks(envelope, claim.document["processing_profile"], + claim.document["extraction_state"], artifact["sha256"]) + assert len(drafts) == 2 and all("permanent employees" in d.text for d in drafts) + wrong = tuple(ChunkDraft(d.ordinal, d.text.replace("These answers apply only to permanent employees.\n", ""), + d.page, d.section) for d in drafts) + before = rows(work) + provider = FakeProvider(work["settings"]) + provider.request_policy = claim.document["processing_profile"]["embedding_request"] + with stage_document(provider, document_id=doc["id"], chunks=wrong, + processing_profile=claim.document["processing_profile"]) as staged: + with pytest.raises(ValueError): + work["repo"].publish(claim, staged, work["candidates"], work["store"]) + assert rows(work) == before + with stage_document(provider, document_id=doc["id"], chunks=drafts, + processing_profile=claim.document["processing_profile"]) as staged: + work["repo"].publish(claim, staged, work["candidates"], work["store"]) + ready, succeeded, count = rows(work) + assert ready["status"] == "ready" and succeeded["status"] == "succeeded" and count == 2 + assert not ready["is_active"] and work["store"].read(ready["storage_key"]) == original + with work["engine"].connect() as conn: + chunks = conn.execute(text("SELECT text,location->>'section' FROM document_chunks ORDER BY ordinal")).all() + assert chunks == [(d.text, d.section) for d in drafts] + assert ready["extraction_state"]["complete_artifact"] == artifact + assert work["candidates"].inspect_pointer(artifact, document=ready) == envelope + assert (work["candidates"].directory / pointer["key"]).read_bytes() == retained_bytes + + +@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."]) +def test_negated_unreadability_notes_resume_approved_ocr_without_repeating_it(work, note): + review_source(work) + vision = ReviewedVision() + review_worker(work, vision).run_once("review") + doc = rows(work)[0] + pointer = doc["extraction_state"]["candidates"][0] + candidate_bytes = (work["candidates"].directory / pointer["key"]).read_bytes() + service, identity = review_service(work) + item = service.read(identity, doc["id"])["items"][0] + service.decide(identity, doc["id"], request_id=uuid4(), + payload=dict(evidence_sha256=item["evidence_sha256"], decision="approve", + checked=item["required_checks"], note=note)) + resume_retry(work) + review_worker(work, vision).run_once("fresh-process") + ready, succeeded, count = rows(work) + assert ready["status"] == "ready" and succeeded["status"] == "succeeded" and count == 1 + assert not ready["is_active"] and vision.calls == [None] + envelope = work["candidates"].inspect_pointer(ready["extraction_state"]["complete_artifact"], document=ready) + annotation, = envelope.review_annotations + assert annotation.note == note and annotation.reviewer == str(work["actor"]) + assert annotation.evidence_sha256 == item["evidence_sha256"] + assert set(annotation.checked) == set(item["required_checks"]) + assert all(note not in b.warnings for b in envelope.blocks) + assert (work["candidates"].directory / pointer["key"]).read_bytes() == candidate_bytes + + +@pytest.mark.parametrize("warning", ["unreadable source region", "\u0646\u0627\u062e\u0648\u0627\u0646\u0627"]) +def test_genuine_unreadable_provider_warning_remains_terminal(work, warning): + review_source(work) + class UnreadableVision(ReviewedVision): + def transcribe(self, *args, **kwargs): + return tuple(b.model_copy(update={"warnings": (warning,)}) + for b in super().transcribe(*args, **kwargs)) + review_worker(work, UnreadableVision()).run_once("unreadable") + doc, job, count = rows(work) + assert doc["status"] == job["status"] == "failed" and count == 0 + assert job["error_code"] == "EXTRACTION_QUALITY_FAILED" + assert not doc["extraction_state"].get("candidates") + assert not doc["extraction_state"].get("complete_artifact") diff --git a/tests/unit/test_phase5.py b/tests/unit/test_phase5.py new file mode 100644 index 0000000..998b5f5 --- /dev/null +++ b/tests/unit/test_phase5.py @@ -0,0 +1,67 @@ +"""Provider-free worker controls and independent command help.""" +import subprocess +import sys +from uuid import uuid4 + +import pytest + +from app.modules.documents.worker import Claim, Worker, LostClaim, retry_delay, read_original + + +@pytest.mark.parametrize("attempt", [1, 2, 3, 100, 2**31]) +def test_retry_backoff_is_bounded(attempt): + low = retry_delay(attempt, 2, 300, uniform=lambda a, b: a) + high = retry_delay(attempt, 2, 300, uniform=lambda a, b: b) + assert 2 <= low <= high <= 300 + if attempt == 3: + assert high == 8 + + +@pytest.mark.parametrize("command", [["app.worker", "--help"], ["app.ingest", "retry", "--help"]]) +def test_command_help_needs_no_configuration_or_providers(command): + result = subprocess.run([sys.executable, "-m", *command], capture_output=True, text=True) + assert result.returncode == 0 + assert "idempotency" in result.stdout or "--once" in result.stdout + + +def test_once_empty_poll_does_not_construct_providers(settings): + class Repository: + def claim(self, *args): + return None + + def forbidden(*args): + pytest.fail("No providers without a claim") + + assert not Worker(Repository(), None, None, forbidden, forbidden, settings).run_once("worker") + + +def test_lost_claim_discards_results_without_failure_write(settings): + class Repository: + def claim(self, *args): + return Claim({}, uuid4(), uuid4(), 1, 0) + + def progress(self, *args): + raise LostClaim() + + def fail(self, *args, **kwargs): + pytest.fail("Stale worker must not write failure") + + assert Worker(Repository(), None, None, None, None, settings).run_once("worker") + + +def test_read_original_uses_frozen_limit_and_verifies_checksum(): + class Store: + def read_bounded(self, key, limit): + assert key == "trusted" and limit == 7 + return b"changed" + + with pytest.raises(ValueError, match="integrity"): + read_original(Store(), dict(processing_profile={"limits": {"max_original_bytes": 7}}, + size_bytes=7, file_sha256="a" * 64, storage_key="trusted")) + +@pytest.mark.parametrize("pointer", [None, {}, {"key": None}, {"extra": "field"}]) +def test_invalid_trusted_pointer_fails_permanently_without_storage_io(tmp_path, pointer): + from app.infrastructure.extraction_candidates import LocalExtractionCandidates + candidates = LocalExtractionCandidates(tmp_path / "extract", original_directory=tmp_path / "original") + with pytest.raises(ValueError, match="Invalid trusted"): + candidates.inspect_pointer(pointer, document={}) diff --git a/tests/unit/test_phase5_repairs.py b/tests/unit/test_phase5_repairs.py new file mode 100644 index 0000000..70c260f --- /dev/null +++ b/tests/unit/test_phase5_repairs.py @@ -0,0 +1,164 @@ +"""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", [ + "These answers apply only to permanent employees.\nQuestion: fee?\nAnswer: 5%.\n", + "## 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]["warnings"] = ["unreadable source region"] + decision["note"] = note + broken = PageBlockExtractor(vision).extract_for_review(retained=lambda _: (body, decision), **kwargs) + with pytest.raises(ExtractionError, match="Unreadable"): + validate_source(broken, dict(title="review", mime_type="image/png", processing_profile=profile), raw) diff --git a/tests/unit/test_phase5_review.py b/tests/unit/test_phase5_review.py new file mode 100644 index 0000000..1ded092 --- /dev/null +++ b/tests/unit/test_phase5_review.py @@ -0,0 +1,159 @@ +"""Provider-free regression checks for configuration and factual preparation.""" +import hashlib +from io import BytesIO +from uuid import uuid4 + +import pytest +from PIL import Image +from pydantic import SecretStr, ValidationError + +from app.modules.documents.extraction import PageBlockExtractor, ExtractionError +from app.modules.documents.chunking import chunk_extraction +from app.modules.documents.operational_limits import MAX_OPERATIONAL_SECONDS +from app.modules.documents.review import ( + ReviewDecision, FactualReviewRequired, factual_digest, factual_groups, prepare_chunks, +) +from app.modules.documents.worker import Worker, LostClaim +from app.worker import factories + + +def extract_faq(settings): + content = b"Question: fee\nAnswer: 5%\nQuestion: greeting\nAnswer: scripted welcome\nQuestion: balance\nAnswer: \n" + profile = settings.processing_profile() + envelope = PageBlockExtractor().extract_for_review(document_id=uuid4(), title="facts", + original_sha256=hashlib.sha256(content).hexdigest(), content=content, + mime_type="text/markdown", processing_profile=profile) + return content, profile, envelope + + +def manifest(envelope, excluded, digest="a" * 64): + return dict(decision="approve", reviewer=str(uuid4()), artifact_sha256=digest, + evidence_sha256=factual_digest(digest, envelope), excluded_group_ids=excluded) + + +def test_faithful_mixed_faq_retention_and_only_whole_approved_pairs(settings): + content, profile, envelope = extract_faq(settings) + assert "" in "".join(b.text for b in envelope.blocks) + groups = sorted(factual_groups(envelope)) + selected = next(b.group_id for b in envelope.blocks if "fee" in b.text) + state = {"factual_inclusion": manifest(envelope, list(set(groups) - {selected}))} + chunks = prepare_chunks(envelope, profile, state, "a" * 64) + assert len(chunks) == 1 and chunks[0].ordinal == 0 + assert "Question: fee" in chunks[0].text and "Answer: 5%" in chunks[0].text + assert "greeting" not in chunks[0].text and "placeholder" not in chunks[0].text + with pytest.raises(ExtractionError): + PageBlockExtractor().extract(document_id=envelope.document_id, title="facts", + original_sha256=envelope.original_sha256, content=content, + mime_type="text/markdown", processing_profile=profile) + with pytest.raises(ExtractionError): + chunk_extraction(envelope, profile, corpus_purpose="approved_factual") + + +@pytest.mark.parametrize("failure", ["missing", "digest", "unknown_group", "all_excluded", "placeholder"]) +def test_manifest_approval_cannot_make_invalid_groups_authoritative(settings, failure): + _, profile, envelope = extract_faq(settings) + groups = list(factual_groups(envelope)) + value = manifest(envelope, []) + if failure == "missing": + state = {} + else: + if failure == "digest": + value["artifact_sha256"] = "b" * 64 + elif failure == "unknown_group": + value["excluded_group_ids"] = ["client-invented-group"] + elif failure == "all_excluded": + value["excluded_group_ids"] = groups + state = {"factual_inclusion": value} + with pytest.raises(ExtractionError): + prepare_chunks(envelope, profile, state, "a" * 64) + + +@pytest.mark.parametrize("field", ["poll_seconds", "heartbeat_seconds", "lease_seconds", + "retry_base_seconds", "retry_cap_seconds"]) +@pytest.mark.parametrize("value", [1e20, float("inf"), float("nan"), 0, 1e-12, MAX_OPERATIONAL_SECONDS + 1]) +def test_operational_duration_is_rejected_during_settings_validation(settings, field, value): + values = settings.model_dump() + values[field] = value + with pytest.raises(ValidationError): + type(settings)(_env_file=None, **values) + + +def test_unchecked_settings_cannot_start_worker_or_claim(settings, monkeypatch): + class ForbiddenRepository: + def claim(self, *args): + pytest.fail("Invalid duration reached claiming") + monkeypatch.setattr("app.modules.documents.worker.Thread", + lambda *a, **k: pytest.fail("Invalid duration started heartbeat")) + invalid = settings.model_copy(update={"lease_seconds": 1e20}) + with pytest.raises(ValueError, match="representable"): + Worker(ForbiddenRepository(), None, None, None, None, invalid) + + +def test_frozen_vision_identity_and_secret_independent_of_current_defaults(settings, monkeypatch): + profile = settings.processing_profile() + frozen = dict(provider="gemini", endpoint="https://frozen.invalid", model="frozen-model", + timeout_seconds=7) + profile["extraction"]["vision"] = frozen + current = settings.model_copy(update={"vision_api_key": SecretStr("server-only-secret")}) + received = [] + + class Vision: + def __init__(self, **kwargs): + received.append(kwargs) + def transcribe(self, *args, **kwargs): + return () + + monkeypatch.setattr("app.infrastructure.gemini_vision.GeminiVision", Vision) + extractor = factories(current)[0](profile) + assert received == [] + extractor.vision.transcribe(b"not-real-provider", page=None, section="image", processing_profile=profile) + assert received == [{**frozen, "api_key": "server-only-secret"}] + assert current.vision_model is None and profile["extraction"]["vision"] == frozen + + +def test_direct_extraction_does_not_need_unused_vision_credentials(settings, monkeypatch): + profile = settings.processing_profile() + profile["extraction"]["vision"] = dict(provider="gemini", endpoint="https://frozen.invalid", + model="frozen-model", timeout_seconds=7) + monkeypatch.setattr("app.infrastructure.gemini_vision.GeminiVision", + lambda **k: pytest.fail("Direct extraction constructed vision")) + content = b"direct evidence" + result = factories(settings)[0](profile).extract_for_review( + document_id=uuid4(), title="direct", original_sha256=hashlib.sha256(content).hexdigest(), + content=content, mime_type="text/markdown", processing_profile=profile) + assert result.complete and result.blocks[0].text == "direct evidence" + + +@pytest.mark.parametrize("payload", [ + {"note": " "}, {"note": "\u0000"}, {"checked": ["readability", "readability"]}, + {"reviewer": "client-forged"}, {"decision": "force"}, {"excluded_group_ids": ["x", "x"]}, +]) +def test_decision_validation_rejects_invalid_or_client_identity_fields(payload): + value = dict(evidence_sha256="a" * 64, decision="approve", checked=["readability"], note="review") + value.update(payload) + with pytest.raises(ValueError): + ReviewDecision.model_validate(value) + + +def test_late_vision_result_is_rejected_before_review_candidate_construction(settings): + from app.modules.documents.types import ExtractedBlock + stream = BytesIO() + Image.new("RGB", (20, 20)).save(stream, "PNG") + content = stream.getvalue() + profile = settings.processing_profile() + profile["extraction"]["vision"] = dict(provider="gemini", endpoint="https://frozen.invalid", + model="frozen-model", timeout_seconds=7) + late = False + def owned(): + if late: + raise LostClaim() + class Vision: + def transcribe(self, image, *, page, section, processing_profile): + nonlocal late + late = True + return (ExtractedBlock(ordinal=0, block_id="image/1", source_locator="image/1", + text="evidence", method="vision", actual_model="frozen-model"),) + with pytest.raises(LostClaim): + PageBlockExtractor(Vision()).extract_for_review(owned=owned, + document_id=uuid4(), title="image", original_sha256=hashlib.sha256(content).hexdigest(), + content=content, mime_type="image/png", processing_profile=profile)