# Durable ingestion worker Phase 5 adds the worker, complete-extraction attachment, atomic publication and trusted operator retry to the existing Phases 1-4 services. Extended Phase 5 now retains exact review candidates, records evidence-bound decisions, resumes approved output and applies whole-group factual FAQ inclusion. D06/D07 backend services are implemented; their HTTP transport remains blocked on authenticated admin/session, organization, Origin and CSRF integration. No unsafe public review route was added. HTTP upload, selection and uploaded-document search remain separate work. ## Run Use the configuration and isolated database instructions in [foundation setup](ingestion-foundation-setup.md). Apply the forward migration: ~~~powershell .venv/Scripts/alembic upgrade head .venv/Scripts/python -m app.worker --once .venv/Scripts/python -m app.worker ~~~ --once processes at most one eligible queued/expired job; an empty poll exits successfully. Continuous polling uses INGEST_POLL_SECONDS and exits on Ctrl+C. A job failure is reported durably through the existing status CLI. Unexpected database/programming errors are redacted on stderr and leave ownership for lease recovery. A worker restart always starts extraction/staging again; there are no embedding batch checkpoints. Worker configuration already present in IngestionSettings controls heartbeat, lease, automatic attempts and capped retry backoff with jitter. The serial worker uses an independent heartbeat thread throughout extraction, storage validation and provider waits. Claim transactions lock only jobs with SKIP LOCKED and commit quickly. All later transactions lock document then job and verify the current token and unexpired database clock lease, including a final conditional write. Recovery claims increment attempts; an exhausted recovery claim terminally fails without running extraction or providers. Operational durations are validated before threads/claims and before lease/retry SQL: at least one PostgreSQL microsecond and at most min(threading.TIMEOUT_MAX, 2147483.647 seconds). Heartbeat < lease and retry-base <= retry-cap remain required. Nonfinite and overflow-prone finite values fail with redacted errors. These bounds establish representability, not capacity. Providers use the document's frozen extraction/embedding identities and request limits, with current server-side credentials. Vision is constructed lazily from the frozen profile when actually needed; its secret is checked independently of current model/provider defaults. Direct extraction needs no unused vision credentials. Changing deployment defaults does not rewrite old profiles. Token-unit embedding profiles require the optional embedding extra and a supported explicit tiktoken: identity. Legacy extractor profiles fail explicitly rather than being interpreted as page-block OCR. ## Complete extraction and publication 0002_worker_artifact adds documents.extraction_state JSONB with complete_artifact holding a trusted candidate key, digest, document/original and extraction identity. Forward 0003_extraction_review adds the extraction_review action and mandatory actor/target/key/hash/saved-response audit check. Both 0001 and 0002 remain immutable. Extended workers/review services require head 0003, the extraction_state column and review audit/replay checks. Foundation intake/bootstrap still accepts 0001/0002. Existing table and embedding profile identities are retained. Artifacts remain bounded files in the separate, non-nested extraction namespace, created atomically without replacement. Attachment validates the candidate digest, original checksum, frozen extraction identity, completeness, order, source coverage and warnings outside long transactions, then checks current ownership and immutable metadata under locks. An existing successful attachment is never replaced. Inventory scanning does not grant attachment/reuse authority. Recovery accepts only the database-attached complete artifact, never an orphan discovered by scanning. Reuse revalidates bytes and source coverage. Direct text/DOCX coverage is compared with deterministic direct extraction; PDF coverage requires all original pages and reviewed output; images require reviewed evidence. These checks do not repeat OCR. Chunk/embedding changes alone do not invalidate the extraction identity. Corrupt, partial or unreviewed output cannot reach publication. Embedding batches check ownership before and after the provider response. Full staging is validated against faithful chunks derived from the trusted extraction. Publication verifies source/profile compatibility, ownership, lease, eligible undeleted state and empty existing chunks, then inserts every chunk and commits ready/inactive document plus succeeded job together. Failure or mid-publication lease loss rolls back all chunk/state writes. Interrupted commit acknowledgement is reconciled through a fresh durable-state read; an unreadable outcome leaves recovery to a later poll. A committed ready document is never republished. ## Retry and reconciliation ~~~powershell .venv/Scripts/python -m app.ingest retry --administrator-id --idempotency-key .venv/Scripts/python -m app.ingest reconcile ~~~ Retry requires a currently enabled administrator and an eligible failed, undeleted document/job with a valid retained original. It reuses both IDs, resets attempts, increments retry_generation once per key and stores the audit/replay response in the same transaction. Replay is resolved after authorization and before new eligibility/storage checks. Review-required jobs requeue only after all current evidence-bound approvals exist and retained source/candidates validate. A rejection stays failed and returns DOCUMENT_NOT_RETRYABLE; pending decisions return EXTRACTION_REVIEW_PENDING. Approval itself never queues, activates or marks ready. Ready/running/removed documents cannot be requeued. Reconcile still compares only original keys against original references. It adds extraction_inventory as a report of candidate/temp/unexpected entries; it never deletes, attaches, repairs or mutates files. ## Validation Provider-free command: ~~~powershell .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short ~~~ PostgreSQL acceptance requires a dedicated TEST_DATABASE_URL ending in _test: ~~~powershell .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short ~~~ Worker regressions are in tests/unit/test_phase5.py and tests/integration/test_phase5.py. They exercise actual PostgreSQL claims/locks, expiry, stale/late writes, slow-call heartbeats, exhausted recovery, publication rollback including lease loss after inserts, lost commit acknowledgement, unreadable commit recovery, attachment races, orphan/complete-artifact recovery, source/profile/digest/coverage/warning checks, rechunk reuse and retry replay. Real extraction/embedding providers and Persian semantic quality are separate validation; these tests do not establish them. Executed on 2026-10-07: full provider-free suite **1004 passed, 3 existing Windows symlink privilege skips**; full PostgreSQL suite **160 passed, no skips**; final pointer-validation rerun **43 worker database tests passed**. The isolated rag_phase5_test container used PostgreSQL 16.15 / pgvector 0.8.7 on localhost:54933. Inspection found zero leftover disposable schemas and public tables. Dependency and whitespace checks passed. The initial migration checksum is unchanged. ## Retained review and factual authority ReviewRequired is handled separately from ordinary processing errors. The worker writes bounded immutable .review.json files containing exact image/blocks, source and frozen extraction identity, locator, reasons and recomputed evidence digest. It attaches only trusted key/digest references and progress under the current token and valid lease, then atomically fails document/job with EXTRACTION_REVIEW_REQUIRED and releases ownership. Zero chunks are published. Partial review candidates are never complete artifacts and orphan inventory never grants trust. SqlReviewRepository exposes read, preview and decide as trusted backend services. They require AdministratorIdentity from a trusted authentication/operator boundary and independently validate current enabled admin and organization in PostgreSQL. Decisions recheck authorization under document-before-job locks; no client reviewer, block text, path, profile or provider arguments are accepted. ReviewDecision rejects extra fields, duplicate checks/groups, invalid digests and empty/invalid notes. Notes are trimmed and limited to 2000 characters; required checks are returned by read. The service reports pending candidates with bounded pagination (1-20 items), returns no raw storage keys, and provides preview bytes/MIME through preview. preview_path is null until an authenticated HTTP adapter supplies the real route. Read/preview recheck authorization, source and attached evidence before output. Decision plus extraction_review audit receipt commit together. Authorized replay is resolved before new eligibility/source checks; changed payload conflicts. Canonical hashes include digest, decision, sorted checks/exclusions and note. A new key cannot replace a decided candidate. Stale evidence/source/profile is rejected. Rejection leaves the document failed; approval does not enqueue it. After all current approvals, the existing retry CLI requeues the same document/job. The extractor looks up the exact approved retained output by source location before any OCR call. Each page and each provider result checks ownership. A later page can require another review while earlier approved pages remain reusable across restart. Source/rendering, candidate digest, profile and required checks are revalidated; approval cannot transfer to a different response. Only full approved coverage can assemble a validated complete extraction artifact. For FAQs, extract_for_review is an explicit faithful-retention boundary: it may retain placeholder text only inside whole Q&A source groups, including associated context. Standalone extract/chunk defaults retain their existing protections. Complete faithful extraction stays attached independently of factual authority. A factual_corpus candidate binds the exact artifact digest and existing Q&A IDs. Approval records reviewer and whole excluded group IDs separately; required checks are factual_authority, whole_pair_association, behavioral_separation, placeholders. Unknown groups, an empty eligible set or included placeholders are rejected. Excluded behavioral/placeholder Q&A and their associated context remain in the artifact/original and never enter chunks. prepare_chunks is shared by worker staging and publication validation; it preserves complete pairs/locators and contiguous chunk ordinals. Publication rechecks the manifest and full retained state under its original ownership/lease/atomicity guarantees. The repository currently has no authenticated HTTP admin/session/Origin/CSRF boundary. Therefore D06/D07 routes and authenticated preview endpoints are not exposed, and users cannot yet complete this flow through a browser. Integrate the services after that prerequisite exists; a request-supplied administrator UUID is not a replacement. Do not treat backend acceptance as full extended Phase 5 or Live MVP completion. ## Extended Phase 5 backend repair acceptance (2026-10-07) Implemented durable partial review retention, current-claim attachment and progress, failed ownership release, trusted administrator read/preview/decide services, evidence-bound atomic audit decisions/replay, exact approved-output restart/resume, and whole-group factual authority/inclusion. Worker staging and publication use one validated preparation boundary. Standalone extraction/chunking protections, immutable complete artifacts, original files, atomic publication and ambiguous commit recovery remain enabled. Vision now constructs lazily from frozen profile identity/policy with independently checked current server credentials. Operational poll/heartbeat/lease/retry durations reject runtime/SQL-unrepresentable values. Affected application sources: app/worker.py; modules/documents/{worker,extraction, chunking,settings,review,operational_limits}.py; infrastructure/{database, worker_repository,extraction_candidates,review_candidates,review_repository}.py. New forward migration: migrations/versions/0003_extraction_review.py. Tests: unit/test_phase5_review.py, integration/test_phase5.py and unit/test_imports.py. Current README, worker guide, plan and reference-map inventory describe these changes. Exact final checks: - .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: **1050 passed, 3 skipped, 186 deselected**. Skips are existing Windows symlink privilege cases. No real providers were called. - .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short: **186 passed, 1053 deselected**, no failures/errors/skips. This includes all **69 worker/review database cases**, compared with the previous 43 worker cases. - Dedicated container rag-phase5-review-20261007; database rag_phase5_review_test; localhost:54934; PostgreSQL **16.15**, pgvector **0.8.7**. Only disposable test schemas were migrated/written. No production database was migrated or modified. - .venv/Scripts/python -m pip check: no broken requirements. - git diff --check and separate AST/whitespace checks for all 16 affected Python files passed. Applied revision 0001 SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567; applied revision 0002 SHA-256 remains 0BFFBA5014A136E3FD251DB8870395FAA056A6277B317506CCF91812C6748ECE. D06/D07 HTTP transport and authenticated preview still depend on the absent administrator/session/organization/Origin/CSRF boundary. No unsafe route trusting a request administrator ID was introduced. Full extended Phase 5 is **not complete** until that integration exists. Real providers, Persian OCR quality, semantic factual authority, browser integration and Live release acceptance were not validated. ## Remaining backend defect repairs (2026-10-07) Factual preparation now preserves governing context through explicit Markdown heading ancestry and existing whole-group relationships. Shared ancestor conditions are repeated with each affected pair; section-specific conditions, negation and exceptions remain with their answers and actual source locators. Excluded pairs and their exclusive context never enter chunks. Unheaded preambles, detached prose after pairs, unresolved/noncontiguous groups and unsupported context hierarchy fail visibly before filtering. Context with no associated pair is not silently indexed. Oversized atomic drafts still fail rather than splitting off conditions. Standalone chunking protections remain enabled. DOCX/visual context already inside a whole group stays supported; unassociated context without a supported explicit heading hierarchy fails. Factual review now exposes governing context once in original source order. New candidates include it; existing immutable candidates with only grouped blocks remain readable by deriving context from their already digest-bound complete artifact. Candidate files, evidence/group identities, decisions, faithful artifacts and originals are never rewritten. Worker preparation and publication use the same context-preserving drafts; mismatched staging is rejected without chunk/status changes. Approved extraction notes are recorded once per location in the bounded envelope review_annotations collection, with evidence digest, reviewer and checked items. They are not block warnings or chunk text. Existing retained candidate/decision shapes still resume exact approved OCR. Original provider/evidence warnings stay strict: genuine unreadability still fails. Note limits and full artifact byte limits include the annotations. This optional file field requires no database migration; applied revisions 0001, 0002 and 0003 remain unchanged. Complete-artifact attachment now compares the existing pointer with the validated candidate under document-before-job locks. Identical attachment preserves review, factual and progress metadata. A conflicting pointer, expired lease or stale token cannot attach or replace anything. Reproductions before fixes: eligibility lost its heading/condition; the approved English note "No unreadable regions; checked all fields." failed source quality; real PostgreSQL identical attachment raised NameError for undefined state. Regression sources: tests/unit/test_phase5_repairs.py and the expanded tests/integration/test_phase5.py. Tests use fake providers only. Verified checks for this repair: - .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: **1064 passed, 3 skipped, 196 deselected** (52.49 seconds). The three existing skips are Windows symlink privilege checks. - .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short: **196 passed, 1067 deselected**, zero failures/errors/skips (128.54 seconds). Includes 79 worker/review cases and 10 new database regressions. - Dedicated rag-phase5-context-20261007 container, rag_phase5_context_test database on 127.0.0.1:54935; PostgreSQL 16.15 / pgvector 0.8.7. Only disposable isolated test schemas were written; no production DB access. - pip check, git diff --check, and AST/whitespace checks of the nine affected Python files passed. No broken requirements. - All three applied migrations and unrelated baseline files remain unchanged. Affected sources: app/modules/documents/{chunking,extraction,review,types}.py; app/infrastructure/{review_candidates,review_repository,worker_repository}.py; tests/unit/test_phase5_repairs.py and tests/integration/test_phase5.py. The workflow/API/database contracts and operations/reference/plan docs describe the context-preserving review/preparation boundary and metadata distinction. No real providers, Persian OCR quality, HTTP/browser or Live acceptance was run. D06/D07 transport still requires trusted admin/session/organization, Origin and CSRF integration and remains outside this repair. ## Phase 6 operator handoff See [integration validation and operator handoff](ingestion-operator-handoff.md) for the consolidated command sequence, JSON heartbeat/stage/error reporting, end-to-end PostgreSQL acceptance and opt-in app.ingestion_smoke command. Existing chat remains on Chroma; scoped pgvector search/selection is next.