feat(ingestion): implement Phase 5 background worker, orchestration, and publication
- Add background worker daemon for job lease acquisition and heartbeat maintenance - Implement atomic document publication, failed job retry backoff, and review resume - Add WorkerRepository for atomic database claims and lease fencing - Add migration 0002_worker_artifact for extraction state tracking - Add extensive unit and integration test coverage for worker orchestration and review resumes
This commit is contained in:
@@ -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.'
|
||||||
|
""")
|
||||||
@@ -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
|
||||||
+111
@@ -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())
|
||||||
@@ -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")
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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={})
|
||||||
@@ -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: <current placeholder>\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 "<current placeholder>" 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 <current placeholder>.\n",
|
||||||
|
"search_text": normalize_search_text("## Eligibility\nOnly <current placeholder>.\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)
|
||||||
@@ -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: <current placeholder>\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 "<current placeholder>" 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)
|
||||||
Reference in New Issue
Block a user