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
+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.