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.'
|
||||
""")
|
||||
Reference in New Issue
Block a user