docs: restructure documentation hierarchy and update agent reference map

- Organize architecture, specifications, plans, and guides into dedicated subdirectories under docs/
- Remove legacy and duplicate documents from data/documents/
- Update AGENTS.md, README.md, and agent skills to target canonical docs paths
This commit is contained in:
amirhosein mazaheri
2026-10-07 16:19:24 +03:30
parent baf58da562
commit ca8833dd2f
30 changed files with 6121 additions and 2768 deletions
File diff suppressed because it is too large Load Diff
+331
View File
@@ -0,0 +1,331 @@
# Ingestion integration validation and operator handoff
Phase 6 validates import -> real extraction -> chunking -> deterministic embedding
batches -> atomic PostgreSQL publication. It adds structured worker diagnostics
and a separate opt-in provider probe. This is ingestion acceptance; it does not
certify the complete Live MVP.
**The existing chat retriever still uses Chroma and FastEmbed.** It does not read
uploaded PostgreSQL chunks. Scoped pgvector search and authorized knowledge
selection are the next milestone: only ready, active, undeleted documents
authorized for the caller may be searched. Publication deliberately leaves
documents inactive. Do not set is_active manually to connect the two pipelines.
## Setup and configuration
From the repository root, install the ingestion/test dependencies:
~~~powershell
python -m venv .venv
.venv/Scripts/python -m pip install -e ".[test]"
~~~
Use PostgreSQL with pgvector available. Configure the deployment through .env
or INGEST_ environment variables; see [.env.example](../../.env.example) and
[foundation setup](ingestion-foundation-setup.md). Set INGEST_DATABASE_URL using
postgresql+psycopg://, and explicitly select INGEST_EMBEDDING_PROVIDER,
INGEST_EMBEDDING_ENDPOINT, INGEST_EMBEDDING_MODEL and INGEST_EMBEDDING_DIMENSIONS.
Supply INGEST_EMBEDDING_API_KEY separately on the server. Specify
INGEST_EMBEDDING_LIMITS as JSON with unit, max_input_units, max_batch_units and
max_batch_inputs. Token units also require an explicit compatible tokenizer and
the embedding extra (pip install -e ".[embedding]"). Do not assume a provider's
limits or supported dimension.
Set INGEST_ORIGINAL_DIRECTORY and INGEST_EXTRACTION_DIRECTORY to separate,
non-nested writable directories. Originals are immutable independent uploads;
extraction candidates have their own namespace. Preserve both across worker
restarts. Storage, deployment credentials and frozen document processing profiles
must remain compatible. Vision work additionally requires the explicit
INGEST_VISION_PROVIDER, ENDPOINT, MODEL and API_KEY settings. PDF/image output
requires inspection; factual FAQ inclusion has its own authority decision.
## Migrate and bootstrap
Apply head with the chosen embedding identity and dimension before importing:
~~~powershell
.venv/Scripts/alembic upgrade head
.venv/Scripts/alembic current
.venv/Scripts/python -m app.bootstrap --organization-name "Example" --username admin --assistant-name "Assistant" --instruction "Answer from organization documents."
~~~
Bootstrap prompts for the initial password without echo and returns organization
and administrator IDs. It refuses an existing organization. Automation may use
--password-stdin through a securely supplied pipe. These commands are trusted
operator tools, not HTTP authentication. Applied revisions 0001-0003 remain
immutable; no Phase 6 schema migration is needed. Model/profile changes do not
silently alter vector(D) or rewrite existing processing profiles.
## Import, status, worker and retry
Use the returned administrator ID. Generate a UUID idempotency key once per
intended import and retain it for replay; the same key and payload returns the
same document. A new key creates an independent document even for identical bytes.
~~~powershell
.venv/Scripts/python -m app.ingest import <approved-file> --administrator-id <admin-id> --idempotency-key <import-uuid>
.venv/Scripts/python -m app.ingest status <document-id> --administrator-id <admin-id>
.venv/Scripts/python -m app.worker --once
.venv/Scripts/python -m app.worker
.venv/Scripts/python -m app.ingest retry <document-id> --administrator-id <admin-id> --idempotency-key <retry-uuid>
.venv/Scripts/python -m app.ingest reconcile
~~~
Replace angle-bracket placeholders. --once processes at most one eligible job;
an empty queue exits successfully. Continuous polling stops on Ctrl+C. A handled
job failure can also exit successfully: use status to inspect the durable outcome.
A successful publication has ready document, succeeded job, exact chunk_count,
ready_at and is_active=false. Before publication there are zero chunk rows, even
when some embedding batches have already completed.
Manual retry requires an eligible failed document/job, enabled administrator and
valid original. It preserves document/job IDs, resets attempts and increments
retry_generation once per key. Replaying that key returns the saved receipt,
including after successful completion. Pending/rejected review evidence cannot
be bypassed with retry. Use the trusted review services described in
[worker operations](worker-orchestration.md); authenticated D06/D07 HTTP transport
still awaits identity/organization/Origin/CSRF integration.
After interruption, allow the old lease to expire and restart the worker.
Complete attached extraction may be reused after validation. Embedding batches
restart from scratch; there are no batch checkpoints. An expired/stale claim
cannot publish. Publication rolls back chunk/state changes together; a committed
ready document is never republished, including after a lost commit acknowledgement.
Reconcile is report-only: missing originals, orphan originals, temporary files
and extraction inventory. It never deletes files, attaches orphan evidence,
requeues jobs or repairs durable state. A missing original must be investigated;
do not replace an original in place or manually change profile metadata.
## Worker diagnostics
The worker CLI emits JSON lines on stderr for claimed jobs, stage starts
(extract, chunk, embed, publish), periodic heartbeat renewal, success, review
requirements, ownership loss and error categories. Each job diagnostic carries
document_id, job_id, stage and category. No document text, filename, storage path,
endpoint, API key, claim token, raw exception or provider response is logged.
The library logger is app.modules.documents.worker; the CLI installs/removes its
handler without changing application-wide logging.
heartbeat/renewed confirms a successful fenced lease renewal during extraction
and provider waits. heartbeat/ownership_unavailable means renewal failed and the
worker cannot assume ownership. At terminal completion a concurrent heartbeat
may observe the released claim; the final publish/succeeded event and durable
status establish completion. Error categories distinguish embedding_error,
extraction_error, storage_error, validation_error, interrupted and ownership_lost.
The status CLI supplies durable error codes/stage. Inspect it after an interrupted
event before taking action; uncertain commits are resolved from database state.
Poll/heartbeat/lease/backoff limits remain documented in worker operations.
## Deterministic PostgreSQL acceptance
Ordinary tests are provider-free and do not require PostgreSQL:
~~~powershell
.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short
~~~
For actual database acceptance, start a fresh dedicated test database whose name
ends in _test. For example:
~~~powershell
docker run --name rag-phase6-test -e POSTGRES_PASSWORD=test-only -e POSTGRES_DB=rag_phase6_test -p 127.0.0.1:55436:5432 -d pgvector/pgvector:pg16
docker exec rag-phase6-test pg_isready -U postgres -d rag_phase6_test
$env:TEST_DATABASE_URL = "postgresql+psycopg://postgres:test-only@127.0.0.1:55436/rag_phase6_test"
.venv/Scripts/python -m tests.postgres_prerequisites
.venv/Scripts/python -m pytest tests/integration/test_phase6.py -q --require-postgres --tb=short
.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short
~~~
Wait for readiness. Missing TEST_DATABASE_URL fails --require-postgres acceptance.
The fixture uses disposable schemas without public fallback, migrates head, checks
relation scope on every connection and requires vector in test_vector. It refuses
a pre-existing vector extension in another schema instead of relocating it.
Tests use temporary original/extraction directories and real Markdown/DOCX
extractors with hash-derived, three-dimensional fake embeddings. They make no
provider requests and use no production database or corpus.
The new tests observe each incomplete batch from an independent database
connection and read completion/chunk count in one SQL snapshot. They verify exact
row count, contiguous ordinals, faithful text/locations, frozen profile, dimension
and deterministic vector correspondence, ready/succeeded state and inactivity.
Literal fixture evidence supplies independent expected rows, including 25 bar,
40 liters per minute, 15 Nm, temperature/blocked-inlet conditions, negation and
exceptions. A shared-chunker mutation of 25 bar to 26 bar is detected for both
Markdown and DOCX, even when implementation-derived drafts agree.
Publication barriers pause after every chunk has been inserted and again after
document/job completion writes, before commit. An independent connection reads
rows and completion together in one SQL snapshot: zero chunks and no completion
are visible at either barrier; all expected rows and ready/succeeded state are
visible after commit. Event waits are bounded and released during cleanup;
these checks use no sleep-based race assertions.
They exercise final-batch failure, duplicate-request replay versus independent
imports, manual retry/replay, pre-publication and post-commit interruption,
expired ownership, deletion before publication, missing originals/reconciliation
and heartbeat reporting during a blocked batch. Existing Phase 5 acceptance adds
actual lock/lease races, partial-insert rollback, ambiguous commit outcomes and
inspected PDF/image/FAQ resume. A simulated crash throws at the named boundary;
the suite does not claim operating-system power-loss or storage-durability proof.
After acceptance, remove only the test container you created and its anonymous
volume: docker rm -f -v rag-phase6-test. Never clean unrelated services.
## Separate opt-in real-provider smoke
This command is outside pytest and never migrates, imports, publishes or activates
documents. It requires explicit approved file paths and authorization to send
their contents to configured embedding/vision providers. It does not infer the
sample corpus or load .env. Export all six required environment settings:
INGEST_EMBEDDING_PROVIDER, ENDPOINT, MODEL, DIMENSIONS, API_KEY and LIMITS (each
with the INGEST_EMBEDDING_ prefix). Supply vision configuration if needed.
Install the embedding extra when the selected policy uses tiktoken token counts.
~~~powershell
.venv/Scripts/python -m app.ingestion_smoke --corpus <approved-file> --corpus <another-approved-file> --allow-provider-calls
~~~
The first JSON result reports provider_compatibility from a small embedding
probe: endpoint/model/dimension, vector validity and configured request-policy
compatibility. The probe is a public one-character ASCII value from a bounded
candidate set, measured against the actual input/batch policy and the configured
compatible token counter. A valid one-byte input and batch policy is supported.
No limits or frozen profile are relaxed and no unreviewed corpus content is used
as a substitute probe.
Local configuration failures return configuration=failed with the redacted
invalid_configuration category. Local probe/counter/staging validation failures
report provider_compatibility=not_run and probe_validation_failed. After adapter
invocation, failed checks report provider_error (classified transport/provider
error), provider_response_invalid (returned vectors rejected by staging), or
provider_check_failed (adapter invocation failed). The last category does not
prove a remote request was transmitted; use provider diagnostics separately.
No raw exception, response, counter identity or credentials are printed. This is not semantic retrieval quality or persisted-database
compatibility. Each subsequent result identifies corpus_index and separately
reports extraction_quality, factual_authority, corpus_embedding and semantic_quality. Automated
extraction checks do not establish Persian OCR accuracy, table completeness,
numeric/negation fidelity or factual authority; semantic_quality remains
manual_review_required. Review-required PDF/image/FAQ content is reported without
bypassing review or embedding unapproved content. Factual authority can require
review even when faithful extraction passes; failed provider compatibility skips
corpus embeddings while continuing independent extraction checks. Nonzero exit means invalid
configuration, failed compatibility, failed input/extraction/embedding, or a
review gate. Reports omit contents, paths, secrets and raw errors. This transient
smoke command does not retain or approve review candidates.
Use the durable operator import/review workflow to inspect exact output against
the approved originals and record extraction quality separately from provider
compatibility. Real-provider results require an approved corpus, funded model
access and independently recorded quality decisions. Fake-provider acceptance
does not establish any of them. No real-provider call is part of ordinary tests.
## Executed Phase 6 acceptance (2026-10-07)
- .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short:
**1076 passed, 3 skipped, 204 deselected**. The three skips are existing
Windows symlink-privilege checks. No real providers were called.
- .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short:
**204 passed, 1077 deselected**, no failures/errors/skips.
- Final worker/publication rerun:
.venv/Scripts/python -m pytest tests/integration/test_phase5.py tests/integration/test_phase6.py -q --require-postgres --tb=short:
**87 passed**. This verifies the final exact row/source assertions and reporting
changes after the full database run.
- Isolated container rag-phase6-20261007, database rag_phase6_test,
127.0.0.1:54936; prerequisite command passed on PostgreSQL **16.15** /
pgvector **0.8.7**. Only disposable test schemas were migrated/written.
- pip check passed. git diff --check passed; separate AST/whitespace checks
covered all seven affected Python files and the new handoff guide, whose local
links passed. Inherited README whitespace was preserved.
- Applied 0001/0002 SHA-256 values remain
9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567 and
0BFFBA5014A136E3FD251DB8870395FAA056A6277B317506CCF91812C6748ECE.
No migration was changed.
- Post-test inspection found zero leftover disposable schemas and zero public
tables. The verified Phase 6 container and its anonymous volume were removed;
the three pre-existing containers were preserved.
Real-provider smoke, production model/tokenizer compatibility, Persian
extraction/semantic quality, HTTP/browser and Live acceptance were not run.
The separate opt-in command is available; successful deterministic/database
acceptance does not certify those gates.
## Phase 6 findings repair acceptance (2026-10-07)
The current repair changes app/ingestion_smoke.py, tests/unit/test_phase6.py and
tests/integration/test_phase6.py, plus current status/operator documentation.
Production publication code, all applied migrations, immutable originals,
frozen profiles and unrelated mixed working-tree changes are unchanged.
The harmless compatibility probe uses a bounded set of one-byte ASCII candidates
and measures the actual frozen input/batch policy with the compatible token
counter. Restrictive byte/token policies and one-input batches now succeed;
the one-byte regression reaches the hosted adapter's fake HTTP request boundary.
Local probe/counter/staging failures are reported as not_run/probe_validation_failed,
separately from adapter/provider failures and invalid returned vectors. No real
provider is contacted by any ordinary test.
Independent literal Markdown/DOCX evidence expects exactly three rows and their
original paragraph locators. Exact text, ordinals, vector correspondence, profile,
ready/succeeded state and inactivity are checked together. Critical evidence
includes 25 bar, 60 C, 40 liters per minute, 30 days, 15 Nm, conditions, negation
and exceptions. A shared-chunker 25-to-26 bar mutation is detected for both formats,
even though implementation-derived expected and actual drafts otherwise agree.
The originals are not changed by this mutation test.
Deterministic event barriers pause production publication after all chunk
inserts and after both completion updates, before commit. An independent
PostgreSQL connection observes rows/count and document/job state in one SQL
snapshot at both barriers: zero visible rows and no ready/succeeded state.
After commit the entire expected publication is visible in one snapshot.
All event/future waits are bounded; cleanup releases both barriers and removes
the listener. There are no sleep-based assertions in the new visibility tests.
The existing Phase 5 rollback, claim/lease fencing and ambiguous-commit coverage
still passes; no production publication defect was exposed.
Reproduction before fixes:
~~~powershell
.venv/Scripts/python -m pytest tests/unit/test_phase6.py -k "restrictive or one_byte or local_probe or bad_provider_vectors" -q --tb=short
# 9 failed, 12 deselected: restrictive-policy rejection and insufficient error categories.
.venv/Scripts/python -m pytest tests/integration/test_phase6.py -k shared_chunker -q --require-postgres --tb=short
# 2 failed, 10 deselected: the shared-chunker numeric mutation was not detected.
~~~
Final executed checks from the repository root:
~~~powershell
$env:TEST_DATABASE_URL = "postgresql+psycopg://postgres:repair-test-only@127.0.0.1:54937/rag_phase6_repair_test"
.venv/Scripts/python -m pytest tests/unit/test_phase6.py tests/integration/test_phase6.py -q --require-postgres --tb=short
# 34 passed.
.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short
# 1086 passed, 3 skipped, 208 deselected.
.venv/Scripts/python -m pytest tests/integration/test_phase5.py tests/integration/test_phase6.py -q --require-postgres --tb=short
# 91 passed.
.venv/Scripts/python -m tests.postgres_prerequisites
# Passed: PostgreSQL 16.15, pgvector 0.8.7.
.venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short
# 208 passed, 1089 deselected; no failures/errors/skips.
.venv/Scripts/python -m pip check
# No broken requirements found.
git diff --check
# Passed (existing LF/CRLF notices only).
~~~
The three ordinary-suite skips are existing Windows symlink-privilege checks.
Database acceptance used only the fresh rag-phase6-repair-20261007 container and
rag_phase6_repair_test database, disposable scoped schemas and temporary file
directories. Missing PostgreSQL configuration is not acceptance. Separate
Python AST/whitespace and documentation local-link checks covered affected
untracked files. Baseline SHA-256 comparisons confirm preservation of unrelated
files and applied migrations; publication code was not changed.
Earlier exact validation records above remain historical evidence. Phase 5
worker/review/resume backend services and Phase 6 validation/handoff are
implemented. Authenticated D06/D07 transport still requires trusted
identity/organization/Origin/CSRF integration. Chroma still serves existing chat;
scoped pgvector search and authorized selection are next. Real-provider smoke,
funded production model/tokenizer compatibility, Persian extraction/semantic
quality, browser integration and Live acceptance were not run or certified.
Repair cleanup: inspection found zero leftover disposable schemas and zero public
tables. Only the verified rag-phase6-repair-20261007 container and its anonymous
volume were removed; all three pre-existing containers were preserved.
+302
View File
@@ -0,0 +1,302 @@
# 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:<encoding> 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 <document-id> --administrator-id <admin-id> --idempotency-key <uuid>
.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.