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:
amirhosein mazaheri
2026-10-07 16:21:34 +03:30
parent 39ed0422c5
commit 9663caf48e
8 changed files with 2360 additions and 0 deletions
+359
View File
@@ -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.'
""")
+249
View File
@@ -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
View File
@@ -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())