Files
rag-technical-docs-assistant/docs/guides/ingestion-foundation-setup.md
amirhosein mazaheri ca8833dd2f 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
2026-10-07 16:19:24 +03:30

106 KiB

Ingestion foundation setup

Current ingestion Phases 1-6 include foundation/intake, real extraction and QC, embedding/staging, fenced worker/publication/retry, retained review/resume backend services and integration/operator handoff. Use the current operator handoff and worker operations for current commands and evidence. Authenticated D06/D07 transport still requires identity/organization/Origin/CSRF. Existing chat uses Chroma and separate credentials; scoped pgvector search and authorized selection are next. Real-provider/Persian quality, browser integration and Live acceptance remain separate unverified gates.

Install

Use Python 3.11+ and PostgreSQL with pgvector installed on the server. The migration role needs CREATE EXTENSION privileges (or a DBA must preinstall vector), plus schema/table creation privileges.

python -m venv .venv
.venv/Scripts/python -m pip install -e ".[test]"

Optional prototype dependencies: pip install -e ".[prototype]". Foundation installation neither imports the prototype nor downloads an embedding model. This manifest uses bounded dependency ranges, not a reproducible lockfile.

Configure and migrate

Copy .env.example to .env. Supply INGEST_DATABASE_URL with the postgresql+psycopg:// scheme and explicitly select provider, endpoint, model and dimension. No production embedding model or dimension is supplied by default. Keep secrets out of shell history and source control. Foundation/bootstrap need no embedding API key; the hosted adapter requires its separate key.

.venv/Scripts/alembic upgrade head

The initial migration explicitly creates vector(D) using the configured positive dimension and stores the full provider/endpoint/model/dimension/preprocessing identity as a column comment. Applied migration files are never regenerated when configuration changes. Subsequent upgrade head verifies the pinned profile; changing environment settings cannot alter an existing schema. Model changes require an explicit new migration/reindexing design, even for equal dimensions. Do not manually edit the comment to bypass compatibility checks. The worker calls check_compatibility before processing. SQLAlchemy connections can call register_vector_types after migration for native Psycopg pgvector values.

Migration downgrade drops these tables and their content; use forward migrations once data exists. The extension is retained.

Initial trusted administrator

Run from an interactive terminal; the password is prompted twice without echo:

.venv/Scripts/python -m app.bootstrap --organization-name "Example" --username admin --assistant-name "Assistant" --instruction "Answer from organization documents."

For automation, --password-stdin reads one line from a securely supplied pipe. There is deliberately no password argument or password environment variable. Bootstrap creates organization, enabled lowercase administrator (Argon2id hash), and settings with all three revisions at 1 in one transaction. A transaction advisory lock serializes concurrent bootstrap. It refuses an existing organization and never resets credentials. Output contains only the new organization/admin IDs. This is operator tooling, not HTTP authentication.

Tests

Ordinary tests are deterministic and do not call providers:

.venv/Scripts/python -m pytest -m "not postgres"

Database tests require a dedicated disposable PostgreSQL database whose name ends in _test; never point them at production. They create a randomly named schema for each test, migrate it, use independent connections for concurrency checks, and remove only that schema on teardown. They install vector into the dedicated test_vector namespace, never relocate an existing extension, and refuse a database with vector in another namespace. Use a fresh dedicated test database if vector was previously installed in public. The application search path contains the disposable schema and test_vector only; it never includes public. Every test connection checks relation ownership before use, and migrations explicitly qualify their version table and validate relation resolution before downgrade. The extension namespace must contain no foundation relations.

Example local service (requires working Docker):

docker run --name rag-foundation-test -e POSTGRES_PASSWORD=test-only -e POSTGRES_DB=rag_foundation_test -p 127.0.0.1:55432:5432 -d pgvector/pgvector:pg16
$env:TEST_DATABASE_URL = "postgresql+psycopg://postgres:test-only@127.0.0.1:55432/rag_foundation_test"
.venv/Scripts/python -m tests.postgres_prerequisites
.venv/Scripts/python -m pytest -m postgres --require-postgres

Wait for PostgreSQL readiness before tests. Stop/remove the explicitly named test container after use. The acceptance command fails if TEST_DATABASE_URL is missing; it must never be interpreted as successful acceptance from skips. Running the general suite without this flag skips PostgreSQL tests with an explicit non-acceptance reason. A configured unavailable database fails rather than replacing it with mocks. The public-table preservation regression also needs CREATEDB permission: it creates its own UUID-named database ending in _test, installs pre-existing public foundation tables/data there, exercises disposable-schema setup, writes, downgrade/upgrade and normal/exception teardown, compares public OIDs/rows/constraints/profile comments, then drops only that generated database. Required evidence covers scoped foreign keys, state/counter checks, vector dimension, duplicate requests/jobs/chunk ordinals/audit replay under concurrency, profile compatibility and serialized bootstrap.

INGEST_ACCEPTED_FORMATS is a JSON array, for example [".md"]. All configured limits are validated when IngestionSettings is explicitly constructed. Worker concurrency is constrained to one document for this milestone. The worker implements bounded exponential backoff with jitter using the validated base/cap/attempt settings. The processing snapshot uses character units, retains extraction/chunking/embedding metadata and excludes credentials. Staging validates complete results; the fenced worker publishes them atomically. Immutable original storage now has a local FileStore adapter with Phase 2 intake; original contents are never overwritten.

Endpoint structure and secret handling

Supported endpoints are absolute HTTP or HTTPS URLs with an ASCII DNS/IP host, optional valid nonzero port, and an optional path made of ASCII letters, digits, slashes, dots, underscores, tildes and hyphens. For example https://api.example.invalid/v1 or http://localhost:8080/tenant/deployment-01/v1. IPv6 literals use brackets. Host casing, explicit ports and path identity are preserved; the existing profile convention strips trailing slashes only. User information, query strings (including an empty query marker), fragments, path parameters, percent-encoded components, backslashes, control characters and whitespace are rejected rather than stripped or persisted. Supply authentication only through INGEST_EMBEDDING_API_KEY (SecretStr). Printed and structured settings validation errors omit input values. Snapshots contain no credentials. All duration settings require finite positive numbers; NaN and both infinities are invalid in direct construction and environment configuration.

Existing applied profile comments/document profiles are not silently rewritten. No affected historical deployment has been identified or remediated by this work. Do not change existing profile comments, document profiles or original files merely because they could contain a historical credential. If a deployment is identified: first record a redacted inventory and obtain explicit remediation authorization. Then rotate the exposed credential through the deployment's secret-management process. With that authorization, prepare a reviewed forward migration targeting only affected profile metadata and the matching pinned comment. Preserve provider, model, dimensions, preprocessing identity, original bytes and unrelated revisions; agree the credential-free endpoint identity explicitly rather than stripping URL components silently. If the service/model identity changes, design reindexing before claiming compatibility. Restrict affected backup/log access and handle their cleanup only under an authorized retention policy. Verify compatibility and absence of credentials afterward. Never edit the initial migration or claim rotation/metadata cleanup occurred without evidence.

Declared pgvector compatibility

The manifest retains pgvector >=0.3.6,<1. Native vector acceptance handles the NumPy loader in 0.3.6 and the Vector loader in 0.5.0, preserving equal numeric round-trip assertions. Run the same PostgreSQL tests in both environments:

python -m venv .venv/minimum
.venv/minimum/Scripts/python -m pip install -e ".[test]" "pgvector==0.3.6"
.venv/minimum/Scripts/python -m tests.postgres_prerequisites
.venv/minimum/Scripts/python -m pytest -m postgres --require-postgres
.venv/Scripts/python -m tests.postgres_prerequisites
.venv/Scripts/python -m pytest -m postgres --require-postgres

Native vector round trips have now passed against real PostgreSQL in both versions. The 0.3.6 test uses its supported NumPy input/output adapter; 0.5.0 uses native Vector. The numeric assertions are identical. Package imports alone are not adaptation evidence.

Historical validation records

The dated Phases 1-4 records below preserve the implementation state and exact results at each checkpoint. Statements that workers/attachment/publication were absent describe those checkpoints, not the current Phases 5-6 implementation. Use the current operator handoff and reference map for later acceptance.

Historical acceptance status (2026-10-05)

Docker is now operational. A dedicated localhost-only temporary pgvector/pgvector:pg16 container provided PostgreSQL 16.15 and extension 0.8.7. Both prerequisite commands passed, including actual CREATE/DROP DATABASE and extension installation privileges. The database was rag_foundation_test on the temporary localhost port 54918. Test credentials belonged only to this container.

Exact checks (all final test runs have zero failures/errors/skips):

  • .venv/Scripts/python -m pytest -m "not postgres" -q: 115 passed, 48 deselected.
  • .venv/minimum/Scripts/python -m pytest -m "not postgres" -q: 115 passed, 48 deselected.
  • .venv/Scripts/python -m pytest -m postgres --require-postgres -q: 48 passed, 115 deselected (pgvector Python 0.5.0).
  • .venv/minimum/Scripts/python -m pytest -m postgres --require-postgres -q: 48 passed, 115 deselected (pgvector Python 0.3.6).
  • .venv/Scripts/python -m pytest --require-postgres -q: 163 passed.
  • Both environments' python -m tests.postgres_prerequisites: passed.
  • Both environments' python -m pip check: no broken requirements.
  • .venv/Scripts/alembic history: unchanged initial revision discovered.

Database tests prove empty-schema upgrade, scoped FKs, state/uniqueness constraints, full profile compatibility, concurrent bootstrap, native vectors, pre-existing public-table/data preservation and scoped downgrade/upgrade. Initial real-DB runs exposed test defects: inline JSON was mistaken for a bind parameter; deparsed constraints varied with search_path; 0.3.6 lacked the root Vector export. JSON now uses a bind, public constraints are compared through stable complete catalog rows, and native vector inputs match each supported adapter. No assertion was weakened.

Malformed database URLs now produce one generic settings validation error; raw SQLAlchemy parser exceptions are discarded before raising. str/repr/json, structured errors and exposed context/cause chains are checked with dummy credentials in direct and environment construction. Valid Psycopg URLs retain their identity. Tests clear ambient INGEST_* overrides (case-insensitively) per test while preserving TEST_DATABASE_URL. Explicit environment tests install their own values, and the ordinary suite is also rerun under external valid limit/duration overrides. Production environment loading is unchanged.

The initial migration's bytes and SHA-256 remain unchanged. These repairs require no persisted schema changes or forward migration. No historical metadata was changed. Test acceptance is local evidence only: no deployment, real-provider quality, HTTP authentication or later ingestion phase is validated.

Final cleanup/inspection: the dedicated database reported zero leftover disposable schemas, zero generated foundation_*_test databases and zero public application tables. The temporary acceptance container and its anonymous test volume were removed; no other container was touched. git diff --check passed, syntax and new-file whitespace checks passed, and the original migration hash was preserved.

Test organization: tests/unit contains provider-free configuration, endpoint, database URL, import and test-environment cases. tests/integration contains PostgreSQL migrations/profile, constraints, concurrency, vector and isolation cases, with database-only fixtures and a directory-wide postgres marker. tests/support contains reusable PostgreSQL and row helpers; tests never import helpers from another test module. Shared settings fixtures remain in root conftest.py. The tests.postgres_prerequisites command remains unchanged.

Organization validation: .venv/Scripts/python -m pytest --require-postgres -q: 163 passed. .venv/minimum/Scripts/python -m pytest -m postgres --require-postgres -q: 48 passed, 115 deselected. Both prerequisite commands passed on a temporary dedicated PostgreSQL/pgvector container. Final runs had no failures/errors/skips. The first moved-helper run exposed a repository-root path error, which was fixed before these final checks. Initial migration hash, test syntax/whitespace and git diff --check passed. See test layout.

Phase 2: trusted local intake

The local intake CLI is independent of prototype chat initialization and needs no embedding API key. Use the migrated embedding identity and enabled administrator UUID returned by bootstrap. The persisted administrator supplies organization scope; these operator commands do not replace HTTP authentication.

.venv/Scripts/python -m app.ingest import "D:/corpus/manual.md" --administrator-id <administrator-uuid> --idempotency-key <new-request-uuid> --title "Manual"
.venv/Scripts/python -m app.ingest status <document-uuid> --administrator-id <administrator-uuid>
.venv/Scripts/python -m app.ingest reconcile

Successful import emits JSON with replayed and document, including the nested job and their stable IDs. Status emits the same document/job shape with current state. Success JSON escapes Unicode, so redirected ASCII/CP1252 streams preserve exact decoded titles and filenames. Domain failures emit a structured error to stderr and exit 1; configuration, storage and unexpected database errors are redacted. No success output is produced until the transaction commits. An uncertain result must be retried with the same key and payload, never a fresh key.

For new uploads, formats are the configured subset of .md/.pdf/.docx/.jpg/.jpeg/.png (case-insensitive), at most the configured original-byte cap (default 20 MiB), nonempty and regular files. Markdown must be UTF-8 (optional BOM) without binary controls or a PDF signature; PDF intake checks its header signature. Full PDF parsing, encryption/scanned-content checks and extraction limits belong to Phase 3; a valid header does not establish extractability. Unsafe display names (path delimiters, reserved device names, controls/bidi overrides and trailing dots/spaces) are rejected. Persian and ZWNJ are retained. Title defaults to the display filename stem, is NFC-normalized with whitespace trimmed/collapsed, and must contain 1-200 display characters.

The SHA-256 replay digest covers original-byte SHA-256 and normalized title, serialized canonically. Display filename, operator identity and fresh processing settings are not replay-payload fields. Keys are organization-scoped. Same key and payload replays the existing document/job, original filename and processing profile; changed bytes/title conflicts. Existing request keys are resolved before new-upload size/format policy checks: lowering the size cap or disabling a format does not invalidate an accepted replay. Comparison streams at most the recorded accepted size plus one byte, in blocks of at most 64 KiB, outside database transactions, and creates no new candidate. Administrator validation, organization scoping and embedding compatibility still apply. New keys obey the current acceptance policy; concurrent first imports still resolve through database uniqueness. Distinct keys create independent originals even for identical bytes. Each new document is queued, inactive and has zero chunks. Document, queued job and upload audit commit together; no migration was required.

Set INGEST_ORIGINAL_DIRECTORY to persistent, operator-owned local storage with sufficient space and hard-link support (e.g. NTFS or a normal POSIX filesystem). The store generates opaque UUID keys, flushes temporary bytes with fsync, atomically publishes a no-replace hard link, and removes the temporary name. POSIX also fsyncs the directory. Unsupported hard links fail before any database job is acknowledged. Keep the directory writable only by trusted processes; filename/key checks do not protect against a hostile process replacing directory contents. Process restart durability is covered; power-loss behavior depends on OS/filesystem guarantees.

Known-unused candidates from first-import races are cleaned on a best-effort basis. A cleanup failure preserves the confirmed replay success or IDEMPOTENCY_CONFLICT. The CLI emits a separate redacted JSON warning line on stderr with code UNUSED_CANDIDATE_CLEANUP_FAILED; stdout remains one success JSON object (or empty on conflict), and error envelopes retain their original code and exit status. The unused candidate remains visible to report-only reconciliation. Diagnostics contain no exception details, paths, file keys or payloads. Normal temporary-write failures are cleaned. Database errors, uncertain commits or a process crash may leave an unused original or temporary file: retaining it prevents deleting a possibly committed document. Reconciliation is a global trusted-operator, report-only inventory of orphan keys, missing originals, temporary files and unexpected entries. It performs no deletion, grace-period cleanup or document purging. A concurrent intake can transiently appear as an orphan before its database commit; reports are observations, not deletion authorization. Retain original bytes for every referenced document. Missing files need operator investigation/restoration; reconciliation does not fabricate bytes.

Phase 2 tests:

.venv/Scripts/python -m pytest tests/unit/test_intake.py tests/unit/test_imports.py -q
.venv/Scripts/python -m pytest tests/integration/test_intake.py --require-postgres -q

Use the isolated PostgreSQL configuration described above. Ordinary tests call no real providers. Worker, retry CLI, extraction and publication remain later phases.

Initial Phase 2 validation: provider-free suite 137 passed/1 symlink-privilege skip; PostgreSQL acceptance 65 passed with no failures/errors/skips on isolated PostgreSQL 16.15/pgvector 0.8.7. Exact commands, fixture corrections and limits are recorded in the Phase 2 section of the reference map.

Phase 2 repair validation: .venv/Scripts/python -m pytest -m "not postgres" -q reported 140 passed and 1 Windows symlink-privilege skip; .venv/Scripts/python -m pytest -m postgres --require-postgres -q reported 74 passed with no failures/errors/skips on isolated PostgreSQL 16.15/pgvector 0.8.7. The skip is not acceptance evidence. See the repair section of the reference map for all executed checks and limits.

MVP documentation direction — 2026-10-06

The Phase 1 plan now includes representative DOCX/image extraction, per-page PDF quality fallback and direct Gemini Live with backend-managed WSS. These are future implementation gates. This guide's commands/configuration and existing acceptance records describe foundation/intake only. The documentation update itself implemented no new format or provider behavior; the alignment implementation below adds format validation. PDF header validation remains insufficient evidence of usable extraction. Do not change an applied embedding profile/migration to match proposed examples.

Page/block foundation and intake alignment ? 2026-10-06

Foundation/intake now accepts PDF, UTF-8 Markdown, DOCX, JPEG (.jpg/.jpeg) and PNG through an explicit configurable allowlist. PNG is the additional engineering-supported image format; GIF, TIFF, WebP, SVG and arbitrary binary extensions are unsupported. Animated PNG is rejected. No OCR, production extraction, chunking, embedding, worker, retry or HTTP upload is added here. Acceptance of a file proves intake validity only, never extractability or quality.

DOCX inspection requires content types, the root office-document relationship, and word/document.xml with a Word document/body. Transitional and strict Word namespaces are recognized. XML DTDs/entities/external resolution are forbidden. ZIP64, multidisk, encrypted and unsupported compression archives, duplicate or unsafe member paths and symlinks are rejected. Member validation reads raw STORED or DEFLATED streams within physical spans determined by adjacent local headers and the central-directory boundary. It independently counts actual expanded bytes, checks the entire CRC and declared length, requires DEFLATE end-of-stream with no trailing/concatenated bytes, and verifies ZIP32 signed/unsigned data descriptors. Per-member, aggregate and ratio limits use actual expansion and the validated physical compressed length. Output reads are capped at 64 KiB or the remaining budget plus one byte, so oversize members stop promptly. Local/central agreement alone is insufficient; ZipExtFile's declared-length truncation is not used. No archive member becomes a filesystem path. JPEG/PNG use Pillow's format-restricted identification, dimension checks, verification and bounded pixel decode; decompression-bomb warnings are errors. These checks do not establish readable text or factual correctness.

New defaults are deployment engineering choices, not product-owner approvals:

Resource Default
DOCX entries / individual expanded member 2,048 / 16 MiB
DOCX total expanded bytes / compression ratio 64 MiB / 200
Image width / height / total pixels 12,000 / 12,000 / 40,000,000
Render DPI / pixels per rendered page 144 / 20,000,000
Complete extraction artifact bytes / blocks 32 MiB / 10,000
Vision request deadline 60 seconds

All are INGEST_* settings shown in .env.example. Intake byte limits still apply first. Image validation may decode up to the permitted pixels in memory; choose deployment memory budgets accordingly. No rendering occurs at intake. Pillow and defusedxml are the only added dependencies. Format-restricted open, verify/load and bomb handling follow Pillow's API and security guidance.

SqlIntakeRepository owns short transactions and intake SQL. The service uses its small injected IntakeRepository port for import, status and reconciliation. These application functions never import or construct SQL infrastructure. app.ingest constructs SqlIntakeRepository(engine) at the composition boundary; CLI arguments, JSON output and diagnostics are unchanged. The boundary preserves SHARE-locked administrator revalidation, scoped uniqueness, atomic document/job/audit creation and returned-after-commit outcomes. An administrator changing organization during file I/O is rejected. All file reading, writes and confirmed-unused cleanup remain outside transactions; ambiguous commits retain candidates, and cleanup failures emit redacted warnings.

New processing snapshots have profile_schema=2, extractor page-block-v1, extraction strategy, optional vision provider/endpoint/model identity and deadline, fallback/quality policies, render/extraction resource limits, intake policy, normalization/chunking identities and the full pinned embedding profile. Identity labels describe planned processing paths; no adapter is implied by configuration. vision_api_key and embedding_api_key remain separate SecretStr values omitted from snapshots. Bootstrap and intake do not require them or contact providers. Vision identity is optional, but when supplied provider/endpoint/model must all be present; later hosted adapters explicitly call credential validation when needed.

The existing unicode-line-endings-v1 normalization and embedding preprocessing identity retain their semantics. Persian character folding is still planned. Selecting another normalization identity currently fails with a migration/reindex requirement, rather than silently changing vector inputs under the pinned identity. Image-derived text will use this same compatible text embedding profile. Exact funded models, account eligibility, limits and quality thresholds remain release decisions; no production provider/model is selected by these defaults.

Snapshots without profile_schema and with pypdf-markdown-v1 are explicitly classified as legacy. They remain unchanged and replay returns original document, job and profile identities even under changed format/size/processing policies. The new extraction fingerprint refuses legacy dispatch. Phase 3 must implement an explicit legacy path or fail safely as unsupported; it must never reinterpret that label as the new OCR implementation or rewrite the snapshot. Unknown profile schemas fail processing classification, but intake replay does not rewrite them.

Retained extraction boundary (engineering choice)

ExtractionEnvelope schema 1 is a frozen, provider-neutral JSON value containing document UUID/title, original SHA-256, extraction-profile fingerprint, completeness, quality decision, normalization identity, warnings and ordered blocks. Blocks hold faithful text separately from optional derived search_text, method and actual model when applicable, page/section/source locator, type/heading, warnings, a group ID and an optional earlier parent-block ID. Contiguous ordinals and unique block IDs preserve source order; FAQ question/answer blocks share a group and cannot lose their counterpart; infographic children reference a parent in the same group. DOCX/image pages stay null unless reliable source pagination exists. No confidence percentage or provider-native response is represented.

Artifact validation cross-checks methods and actual models with the frozen profile. The supported strategy is direct-quality-fallback-v1. Direct PDF/DOCX/readable-text blocks carry no provider model. OCR/vision blocks require a configured frozen vision provider, endpoint and model, with actual_model exactly equal to the configured model (case-sensitive). Requested and resolved IDs must match; model aliases, implicit routing and arbitrary resolved IDs are unsupported. A future alias design needs an explicit frozen resolution rule. These checks validate compatibility of recorded metadata, not proof of provider execution or extraction quality.

The chosen future file namespace is a separate persistent INGEST_EXTRACTION_DIRECTORY (default data/extractions), outside the originals root. Candidate paths are <document-uuid>/<original-sha256>/<claim-token>/<candidate-uuid>.json; all identifiers must be generated/validated, never source filenames. Originals remain immutable. Write complete candidates with a bounded temporary write and atomic no-replace promotion. This phase implements no candidate writes or attachment/finalization operation, so it provides no unfenced shortcut.

Later workers must rehash the stored original, check trusted candidate SHA-256, validate the envelope's document/original/profile/completeness/source relationships and bounds, and account for warnings plus source-unit coverage/QC before attachment. validate_artifact implements bounded JSON/integrity/identity/relationship checks; it cannot prove that the producer transcribed every source region accurately. The trusted artifact digest must come from an authorized attachment, never just from the untrusted candidate itself. Extractor/model/fallback/quality/resource identity is fingerprinted independently of chunking and embedding, allowing faithful extraction reuse without rerunning OCR. If normalization changes, derive fresh search text from faithful blocks; never reuse stale normalized input. The current validator requires matching normalization identity and a valid derivation before returning the artifact. normalization.py provides the shared v1 implementation: Unicode NFC plus CRLF/CR to LF only. It preserves spaces/indentation, Persian/Arabic variants, ZWNJ, numbers, dates, negation and exclusions. Stored search_text must match that exact derivation. Faithful-only artifacts may leave it null; normalized_inputs rederives all block inputs and checks the aggregate frozen max_normalized_characters budget before returning any inputs. It never mutates faithful evidence or silently truncates. No Persian character folding or embedding preprocessing/profile change is introduced.

Attachment and finalization require a transactionally checked current claim token, unexpired lease and undeleted document under document/job locks. Candidate inventory alone is never attachment authority. Phase 5 must implement that durable attachment mechanism and crash/lease-race tests before reuse is enabled; if it needs a persisted pointer, use a reviewed forward revision rather than modifying the applied initial revision. No new schema, block/page/staging tables or content versions are needed for the present contract/validation work. Retained extraction is independent of chunk/vector publication and never makes a queued document searchable.

Original reconciliation still scans only originals and remains report-only. Extraction candidates belong to the separate namespace, cannot appear as original orphans, and require their own later report-only inventory. Do not configure the artifact root within/over the originals root. Settings enforce separation after canonical path resolution, following existing symlink aliases and native path semantics. Equal roots and either direction of nesting are rejected, including relative/absolute aliases and Windows case/extended-drive aliases. This validation creates no directories and mutates no storage. Roots still require trusted ownership; configuration validation does not authorize later directory replacement. No physical purge policy is added. The initial migration and schema-revision/embedding compatibility checks are intact.

Final alignment validation (2026-10-06):

  • .venv/Scripts/python -m pytest -m "not postgres" -q: 196 passed, 1 skipped, 92 deselected. The skip is the existing Windows symlink-creation privilege check; it is not acceptance evidence. Supplied DOCX/JPEG intake checks passed. No providers, model downloads or prototype indexing ran.
  • .venv/Scripts/python -m tests.postgres_prerequisites: passed on dedicated rag_intake_formats_test, temporary container rag-intake-formats-acceptance-20261006, localhost:54921, PostgreSQL 16.15 / pgvector 0.8.7 (Python adapter 0.5.0).
  • .venv/Scripts/python -m pytest -m postgres --require-postgres -q: 92 passed, 197 deselected, zero failures/errors/skips. Includes all existing embedding/schema/isolation checks plus new-format document/job/audit, races, rollback, frozen profile and legacy replay cases.
  • .venv/Scripts/python -m pip check: no broken requirements.
  • git diff --check: passed. All 13 affected/new Python files also passed AST syntax and trailing-whitespace inspection, including untracked files.
  • Initial migration SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567; no schema revision or embedding compatibility check changed.
  • Database cleanup inspection found zero leftover disposable foundation schemas, generated foundation test databases or public application tables. Only the named temporary acceptance container/anonymous volume was removed afterward.

The initial alignment PostgreSQL run also passed 92 cases; final rerun followed additional forged-central-directory and provenance/normalization guards. Earlier provider-free runs passed 191 cases before those additional regressions. Docker was initially stopped; checks failed before Docker Desktop was started from its user-local installation. Final database evidence above supersedes that temporary availability limitation. Existing unrelated containers were preserved.

Not validated: unavailable symlink privilege, production storage/power-loss behavior, minimum pgvector 0.3.6 rerun for this change, OCR/provider transcription quality, account/model access, deployment and later pipeline phases. Remaining decisions include deployment format/resource budgets, funded model/QC policy and incompatible Persian preprocessing migration/reindex design. Durable artifact attachment and its persistence mechanism remain explicit Phase 5 implementation work, not an implemented or accepted unfenced finalizer.

Reviewed foundation/intake repairs - 2026-10-06

The reviewed defects were reproduced before repair: a DEFLATED member with both headers declaring a short prefix and its CRC passed the earlier intake checks even when actual output exceeded member, aggregate or ratio budgets. Earlier artifact checks accepted incompatible/unconfigured models and unrelated search text, and settings accepted overlapping roots. The initial regression run reported 47 failed, 26 passed and 2 symlink-privilege skips. Those failures document missing guarantees; the earlier alignment acceptance above did not prove them.

Current raw-stream checks also reject truncated streams, trailing/concatenated streams, forged full CRCs, short STORED lengths and corrupt data descriptors. Generated fixtures cover STORED/DEFLATED with signed and unsigned ZIP32 descriptors, multiple input/output blocks and bounded early stopping. Existing directory-count, path, encryption, package XML and image protections remain covered. Supplied DOCX and JPEG intake checks passed; none of this proves source extractability.

Frozen model compatibility and exact v1 normalized derivation are now checked in artifact validation. Positive fixtures use configured compatible identities and retain mixed direct/vision/OCR PDF-page metadata, FAQ groups and infographic links. Canonical root validation passes native Windows case and extended-drive alias tests; actual directory symlink tests skip when this host denies creation. The injected application services are exercised with concrete SQL imports blocked, while all transaction/locking/concurrency evidence still uses real PostgreSQL repositories. No persisted profile, vector schema, provider credential or initial revision changed. Final commands and acceptance evidence follow.

Final repair validation (2026-10-06):

  • .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: 285 passed, 3 skipped, 102 deselected. Skips are the existing file-symlink creation case and two new directory-symlink aliases; this Windows account denies creation. Those cases are not claimed as verified. Native Windows case and extended-drive alias tests passed. Supplied DOCX/JPEG and generated DOCX/JPEG/PNG acceptance and import isolation passed; no provider calls or model downloads.
  • .venv/Scripts/python -m tests.postgres_prerequisites: passed on dedicated rag_intake_repair_test in temporary container rag-intake-repair-acceptance-20261006, localhost:54922, PostgreSQL 16.15 / pgvector 0.8.7, Python adapter 0.5.0.
  • .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short: 102 passed, 288 deselected, zero failures/errors/skips. Existing real transaction/concurrency, SHARE-lock revalidation, scoped replay/conflict, rollback, ambiguous commit, cleanup warning, policy-independent replay, schema/vector and frozen legacy-profile assertions remain. Ten new cases cover dishonest DOCX rejection before candidate/row creation and atomic descriptor- based STORED/DEFLATED intake/replay. Application tests use SQL repository injection.
  • .venv/Scripts/python -m pip check: no broken requirements.
  • git diff --check: passed. AST syntax and trailing-whitespace inspection passed for all 13 affected/new Python files, including untracked files. Local links and whitespace in the three affected documents passed inspection.
  • Initial migration SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567. No persisted processing profile, migration or vector schema was changed.
  • Cleanup inspection found zero leftover disposable schemas, generated foundation test databases or public application tables. Only the named acceptance container and its anonymous volume were removed; unrelated containers were retained.

The first repair run exposed one existing invalid partial-vision test fixture after positive artifact fixtures were configured correctly. A later SQL-free port test initially also blocked the existing configuration URL parser; its setup now validates configuration first, clears cached SQL modules and forbids SQL infrastructure during application import/execution. Both test issues were corrected before final acceptance. These are separate from the original 47 reproduced product failures.

Limits: no real-provider/OCR quality, factual completeness, production deployment or power-loss guarantee is established. Actual symlink alias validation remains unrun under this account, and this repair did not rerun minimum pgvector 0.3.6 or non-Windows platforms. Model aliases/implicit resolution are deliberately unsupported. Future artifact writes/attachment still require a worker-fenced implementation; no such path, worker, retry, embedding, HTTP, chat or Live behavior was added. Deployment budgets, funded provider models and QC thresholds remain existing release decisions.

Phase 3 extraction, QC and chunk drafts (2026-10-06)

Install the updated manifest with .venv/Scripts/python -m pip install -e ".[test]". PyMuPDF is the one added PDF dependency (tested locally with 1.28.2). Its page text/block extraction and rendering APIs are documented in PyMuPDF text extraction and page rendering. Ingestion imports do not load it, initialize prototype retrieval or contact providers.

Implemented application entry points:

  • PageBlockExtractor in app/modules/documents/extraction.py implements the extraction port against a frozen schema-2 profile; legacy-v1 raises LegacyProcessingProfile before provider work. Unknown strategies, fallback/ quality policies and normalization/chunk policies fail explicitly.
  • prepare_extraction in app/modules/documents/processing.py receives a FileStore, candidate store, extractor and persisted document mapping. It verifies original byte length/hash, extracts and validates a complete envelope, retains an immutable candidate, then makes bounded chunk drafts.
  • chunk_extraction in app/modules/documents/chunking.py also consumes validated envelopes directly, permitting future fenced artifact reuse without another OCR call. It never changes the extraction digest when only chunk/embedding settings change.
  • LocalExtractionCandidates in app/infrastructure/extraction_candidates.py writes only to the separate configured extraction root. Generated keys contain document ID plus a random candidate ID; no-replace hard-link finalization, flush/fsync, checksum, bounded integrity inspection and report-only inventory mirror original-store guarantees. All candidates remain unreferenced. Its inspection method checks evidence; it does not authorize attachment/reuse.
  • GeminiVision in app/infrastructure/gemini_vision.py is an opt-in REST adapter. Explicit provider gemini, HTTPS base endpoint (for example https://generativelanguage.googleapis.com/v1beta), exact funded Flash model ID, server secret and frozen timeout are required. No model is selected automatically.

The existing import/status/reconcile CLI is unchanged. There is no Phase 3 worker or extraction CLI. Compose processing from an authorized document mapping:

from app.infrastructure.extraction_candidates import LocalExtractionCandidates
from app.modules.documents.extraction import PageBlockExtractor
from app.modules.documents.processing import prepare_extraction

candidates = LocalExtractionCandidates(
    settings.extraction_directory, original_directory=settings.original_directory)
prepared = prepare_extraction(
    original_store, candidates, PageBlockExtractor(),
    document=persisted_document, corpus_purpose="source_document")
# prepared.envelope, prepared.chunks and prepared.candidate are unindexed results.

For optional vision, construct GeminiVision using the document's frozen processing_profile["extraction"]["vision"] identity/timeout and a separately supplied deployment secret; inject it into PageBlockExtractor. Validate credentials with settings.require_vision_credentials() at composition. The model-reported modelVersion and every block model must equal the exact requested ID. Aliases, omitted model identity, non-STOP completion, incomplete transcription, unreadable regions, response byte overflow and incompatible locations fail safely. No provider-native responses or keys enter the envelope. The REST contract is Gemini generateContent.

PDF processing attempts direct extraction in creator source order on every page. Empty/garbled text, invisible text, images or vector drawing content cause affected-page rendering and vision fallback. A nonempty text layer never passes on its own. Every remaining direct page also needs inspection of its bounded rendering against extracted blocks for readability, order, completeness, numbers, dates, negation and exceptions. This conservative gate avoids claiming that simple checks can prove Persian numeric/visual fidelity. A rejected direct reading order can route to vision; no reversal or guessed correction is applied. Page count, rendered pixel count, original/provider image bytes, extracted block count, artifact/response bytes and aggregate normalized characters are bounded by the frozen profile. Native images also retain their intake dimension/pixel bounds. No limit silently truncates source text or provider output.

QC is immediate: ReviewRequired carries locator, exact blocks, rendered image, reasons and an evidence SHA-256 binding original hash, extraction profile, image and candidate text/metadata. Processing fails without an indexable envelope. A trusted operator may supply precompleted ReviewApproval records with that digest, reviewer, note and all seven REVIEW_CHECKS. Never automatically approve these records in production or accept a model's own approval. Records with a different original, profile or transcription do not match. Review waits/polling, calibrated confidence numbers and new lifecycle states are absent. A review cannot occupy a worker lease: no interactive reviewer is invoked, and later Phase 5 must map these permanent QC failures into its fenced existing failed lifecycle. The extractor alone does not update database/job state. For provider samples, changed transcription on a rerun needs a fresh inspection; there is no trusted runtime reuse/attachment path before Phase 5.

DOCX preserves paragraph/tab/break content and cells in XML source order, including labelled Q/A across adjacent rows, cells and adjacent tables. The supplied sample splits its first pair between two adjacent tables; all 100 pairs are retained. Q/A column headers and multiple labelled paragraphs within a cell are supported. Every locator includes actual paragraph or table/row/cell identity; page is null. Nested tables, auxiliary headers/footnotes/images, tracked changes and unsupported body/text representations fail rather than disappear. These restrictions are explicit scope limits, not assertions that every valid DOCX is extractable. Infographic parents and descriptions share groups with earlier-parent references; vision unreadable-region warnings fail QC instead of producing authoritative text.

Artifacts retain faithful text and NFC/CRLF-or-CR-to-LF search text separately. No Persian/Arabic folding, whitespace collapsing, digit/date correction or ZWNJ removal occurs. Stored search text is validated/rederived against faithful text, and the aggregate normalized-character budget is checked before consumption. Chunk text stays faithful; a newline separates adjacent blocks when the source blocks do not already contain a line ending. FAQ/visual groups and article/clause rules with notes, conditions/exclusions remain indivisible. Oversized semantic units fail explicitly; generic text uses deterministic character windows with the configured bounded overlap. Ordinals start at zero. A group spanning known PDF pages has page=null and a page range in section; no DOCX/image pages are invented. Token counts remain null. paragraph-v1 and semantic-boundaries-v1 are supported; the frozen schema-2 defaults and legacy profiles are not rewritten.

corpus_purpose is trusted application input. Only source_document or approved_factual can produce drafts; FAQ groups require approved_factual. Behavioral evaluation and live-data-placeholder purposes fail. Recognized explicit placeholder markers (for example [TBD], {{tariff}}, <current-value>) also fail; this is a simple safety check, not a universal classifier. Curate/approve factual Q&A independently and separate mixed behavioral/live-data entries before intake. The supplied 100-pair bank is extraction evidence, not approved authority.

Candidate files survive restart and chunk failure. No database artifact pointer, attachment, reuse authorization, claim, failure finalizer, chunk insert, embedding or publication is added. Phase 5 must provide durable current-token/unexpired-lease fencing before any candidate can become attached or reused at runtime. Originals, applied migrations and embedding preprocessing remain unchanged. Reconciliation of originals continues to see originals only; candidate inventory is separate. Production storage/power-loss guarantees remain unverified.

Provider-free checks:

.venv/Scripts/python -m pytest tests/unit/test_phase3.py tests/unit/test_gemini_vision.py tests/unit/test_imports.py -q --tb=short
.venv/Scripts/python -m pytest -m "not postgres" -q --tb=short

PostgreSQL acceptance uses the same dedicated-database prerequisite and -m postgres --require-postgres commands above. New cases prove concurrent preparation retains original/profile/job identity and zero published chunks; existing real constraint, isolation and intake race cases still run. These are preparation/isolation checks, not worker-claim/publication-fencing evidence.

Real provider quality remains a separate opt-in sample evaluation: explicitly choose an approved sample and funded exact model identity, compose GeminiVision, inspect each rendering/transcription/critical field and record observed defects. Ordinary tests use deterministic fake vision and generated review attestations; those attestations prove QC mechanics only, not manual/source/provider quality. No real extraction-provider evaluation has been executed for Phase 3.

Final executed Phase 3 checks (2026-10-06):

  • .venv/Scripts/python -m tests.postgres_prerequisites: passed on dedicated rag_phase3_test, temporary rag-phase3-acceptance-20261006 container, localhost:54923, PostgreSQL 16.15 / pgvector 0.8.7.
  • .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: 344 passed, 3 skipped, 105 deselected. The three skips are the existing file/directory symlink privilege cases. No real providers or prototype indexing.
  • .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short: 105 passed, 341 deselected, zero skips/failures/errors. This full run preceded the final provider-order/error-category correction; no database code changed.
  • After that correction, .venv/Scripts/python -m pytest tests/integration/test_phase3.py --require-postgres -q --tb=short: 3 passed. The final ordinary suite above includes six additional REST cases.
  • Earlier targeted .venv/Scripts/python -m pytest tests/unit/test_phase3.py tests/unit/test_gemini_vision.py tests/unit/test_imports.py -q --tb=short: 54 passed, before those final six cases.
  • .venv/Scripts/python -m pip check: no broken requirements.
  • git diff --check: passed; syntax/whitespace/local-link inspection includes all 16 affected files, including untracked files.
  • Initial revision SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
  • Cleanup inspection found zero disposable test schemas, generated foundation databases or public application tables. The named temporary acceptance container and its anonymous volume were removed; unrelated containers remain.

The first targeted run reported two failures (cross-table first FAQ pair and adapter unreadable-region handling); both were fixed. A later collection run was blocked by an unused incorrect test import; corrected before successful full checks. Final inspection also added dependent-heading grouping, provider ordinal validation and redacted transient/permanent provider errors. Timeouts/network/ 408/429/5xx failures are retryable; ordinary HTTP rejections and QC failures are permanent. The adapter itself never retries.

Not validated: funded real-provider extraction/transcription quality, real manual PDF/image fidelity acceptance, unavailable symlink privileges, production storage/ power-loss behavior, minimum pgvector 0.3.6 rerun or non-Windows deployment. Supplied DOCX structural extraction is verified; its factual authority is not. Unsupported/blank PDF pages and unsupported DOCX structures fail instead of being silently omitted. Worker, artifact attachment/reuse authorization, embeddings and publication remain later phases.

Confirmed Phase 3 repairs (2026-10-06)

This section supersedes the earlier Phase 3 behavior descriptions where they differ. Repair regressions use generated DOCX/PDF/text inputs and fake provider transports. The first run reproduced 31 failed, 8 passed, before any implementation correction. Follow-up regressions separately reproduced document-default numbering, conflicting article references, duplicate block separators, explicit conditional prose and ambiguous source-group transitions.

Final supported/rejected behavior:

  • DOCX content controls, custom XML wrappers, alternate content, unsupported table/ row/cell children and unsupported text-bearing run children fail explicitly before a complete envelope. Supported plain paragraphs/cells retain XML source order, locators, tabs and breaks. w:noBreakHyphen is retained as U+2011 and w:softHyphen as U+00AD; neither disappears from dates/identifiers. Symbols, fields, references, ruby and unknown run children are rejected.
  • Automatic DOCX numbering is not resolved. Affected paragraphs fail for direct numPr, used/default paragraph styles, basedOn inheritance and document paragraph defaults. Cyclic/missing referenced paragraph styles and ambiguous defaults fail. Explicit numId=0 cancels inherited numbering. Valid numbering that supplies an article identifier is tested as rejected instead of losing that identifier. Unused numbering definitions do not by themselves make a paragraph numbered. The supplied sample's 100 Q&A pairs remain preserved, including the cross-table pair.
  • Labelled readable-text FAQs support Persian سؤال/سوال/پرسش and پاسخ/جواب, English Question/Answer/Q/A, colon/fullwidth-colon, optional Markdown heading markers and bold label markers. Faithful spaces, line endings and continuation text are retained. Answers without questions and incomplete pairs fail. Groups require trusted approved_factual purpose to chunk; oversized pairs remain indivisible and fail.
  • Dependent headings recognize Notes/Note, Conditions, Exceptions, Exclusions and representative Persian تبصره/تبصره‌ها/تبصره‌های, یادداشت/یادداشت‌ها, استثنا/استثنائات, شرایط/شروط/ملاحظات without folding source characters. Notebook, NotesArchive, یادداشت‌برداری, شرایط‌سازی and unrelated headings remain independent boundaries.
  • Separate dependent units, including explicit Except/Unless/Provided that/Only if and Persian به شرط/مشروط/مگر prose, retain the one adjacent explicit governing article/clause/circular/numbered decision across PDF pages, direct/vision methods and source-group IDs. Source order and every block locator are retained. Orphan dependencies, multiple possible governing rules, conflicting explicit article/clause references and unlabelled continuations at a source-group transition fail rather than being guessed. Clearly independent headed visual groups remain independent. No general automatic semantic association classifier is claimed. Combined semantic units still fail explicitly if oversized.
  • PDF cumulative normalized-text/block and artifact-byte budgets run after every completed direct or fallback page, before another provider page. Metadata, review notes, UTF-8 width and JSON escaping count against the artifact bound. All artifact assembly boundaries preflight exact UTF-8 JSON size before allocating the serialized artifact. Oversized provider metadata cannot reach a candidate.
  • Gemini uses a single absolute request deadline. Remaining time bounds request opening; supervision bounds the caller during DNS/connect/TLS/upload and reads. Checks after opening and every read include EOF and late complete responses. Expiry is a redacted retryable provider error and there are no adapter retries. A daemon performs the single blocking request: an uninterruptible underlying operation can outlive the caller until the transport returns, but its late result cannot be accepted. This is not a guarantee of immediate OS-level DNS cancellation.
  • A separator is inserted only between blocks lacking an existing line ending at either boundary. No trailing newline is invented; exact-boundary single-block text remains one chunk.

NFC/CRLF-or-CR-to-LF v1, Persian/Arabic variants, meaningful spacing, numbers, dates, negation, exceptions and ZWNJ remain unchanged. Originals, document IDs, frozen profiles and the applied initial migration are preserved. No worker, attachment/reuse authorization, embedding, publication, HTTP/chat/Live or content version feature was added. Candidate attachment/runtime reuse still requires Phase 5 durable current-claim fencing. Real extraction-provider quality and manual Persian PDF/image fidelity acceptance remain unverified.

Final executed repair evidence (2026-10-06):

  • .venv/Scripts/python -m tests.postgres_prerequisites: passed on dedicated rag_phase3_repairs_test, temporary container rag-phase3-repairs-20261006, localhost:54924, PostgreSQL 16.15 / pgvector 0.8.7.
  • .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: 399 passed, 3 skipped, 105 deselected. Skips are the existing file/directory symlink-creation privilege cases, not acceptance evidence. The supplied DOCX's 100 pairs, frozen provenance/normalization contracts and import isolation pass.
  • .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short: 105 passed, 402 deselected, zero failures/errors/skips. Existing real constraints, intake races, scoped rollback and Phase 3 preparation isolation pass.
  • Last targeted run before final full suites: .venv/Scripts/python -m pytest tests/unit/test_phase3_repairs.py tests/unit/test_phase3.py tests/unit/test_gemini_vision.py -q --tb=short: 114 passed. The repair file contains 55 generated cases.
  • .venv/Scripts/python -m pip check: no broken requirements.
  • git diff --check: passed; all 11 affected files also passed AST (Python), trailing-whitespace and local Markdown link inspection, including untracked files.
  • Initial migration SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
  • Database cleanup inspection found zero disposable schemas, generated foundation databases and public application tables. The named temporary container and its anonymous volume were removed; unrelated containers were preserved.

An intermediate full provider-free run reported one blocking-fixture failure: the 50 ms deadline expired before its test thread entered the fake operation. The fixture now allows a 300 ms deadline and a 3-second fake block, still requiring return before 1.5 seconds; open/read/EOF cases pass in the final full suite. The production absolute deadline was not relaxed. Earlier reproduced product failures were corrected before final acceptance.

Affected files: extraction.py, chunking.py, extraction_artifacts.py, processing.py, extraction_candidates.py, gemini_vision.py, test_phase3_repairs.py, test_gemini_vision.py, this setup guide, the reference map and the pipeline plan. No dependencies, schemas, originals, frozen profiles or unrelated files were changed. No real-provider quality or manual Persian PDF/image fidelity acceptance was run. Minimum pgvector 0.3.6, unavailable symlink creation, production transport/storage and OS-level cancellation remain unverified. Phase 5 attachment/reuse fencing is still required; these repairs provide no worker or unfenced finalizer.

Six additional Phase 3 context/transport repairs (2026-10-06)

This section supersedes earlier supported/rejected behavior where it differs. Generated regressions reproduce the mathematical-content, tracked-move, FAQ hierarchy, whole dependency, circular-boundary and outstanding-transport defects before correction.

  • DOCX paragraphs accept supported WordprocessingML paragraphs/runs, hyperlinks, bookmarks and proof/permission markers. Paragraph and hyperlink children are checked in addition to run children; text inside formatting/marker metadata is rejected. Foreign paragraph namespaces, mathematical structures (including numerator 1 / denominator 2), and unknown visible wrappers fail explicitly. Equations are not flattened or interpreted as ordinary text.
  • Tracked moves, move range markers, custom XML revision ranges, property changes, cell revisions and numbering changes are rejected alongside existing unsupported insertions/deletions. Ordinary untracked paragraphs, hyperlinks, meaningful run characters and the supplied DOCX's 100 pairs remain supported. Automatic numbering and unsupported auxiliary/table content retain the prior explicit rejection policy.
  • Readable Markdown FAQ headings may use standalone Question/Answer or the supported Persian labels as well as existing colon labels. Question and answer heading depths must agree. Deeper answer subsections, including Required documents and nested Exceptions, retain the same contiguous Q&A group and line locators. A peer/shallower independent heading closes the pair. Nested FAQ labels, mismatched pair depths and unanswered questions fail rather than guessing. Trusted approved_factual purpose and oversized indivisible-pair failures remain required.
  • Dependency validation inspects every dependent line, including subsequent blocks and dependencies already inside a source group or a FAQ answer with an explicit rule. Explicit targets must match the single governing rule; conflicting/multiple/unclassified other-rule references fail. Explicit incidental citation sentences (See, Refer to, According to, For background, مطابق/طبق/رجوع/مراجعه/ارجاع) are allowed when they do not also state applicability. A dependency group containing another governing heading is ambiguous and rejected. No arbitrary prose classifier is claimed. Explicit FAQ hierarchy and infographic parent/child relationships remain valid contexts.
  • Plain Circular/Decision and بخشنامه/تصمیم headings are now semantic boundaries as well as governing rules. Independent decisions keep only their own adjacent conditions/exceptions across pages, extraction methods and groups. Source order, every locator and zero-based deterministic ordinals are preserved. Combined oversized semantic units still fail explicitly.
  • Gemini allows one outstanding blocking transport per process, shared across calls and adapter instances. A timeout does not free capacity until its underlying operation exits. Occupied capacity returns a redacted retryable provider error immediately. Capacity recovers after completion; late results are never accepted. The existing absolute deadline checks after opening, every read and EOF remain.

These six repairs change extraction.py, chunking.py, gemini_vision.py, test_phase3_context_repairs.py, this setup guide and the reference map. They do not change original files, document references, frozen profiles, NFC/LF v1 normalization, source variants/spacing/ZWNJ, schema or the applied migration. Worker orchestration, embeddings, publication, attachment/reuse authorization, HTTP/chat/Live and document-content versions remain outside this work.

Executed checks for the six additional repairs (2026-10-06):

  • Before corrections: .venv/Scripts/python -m pytest tests/unit/test_phase3_context_repairs.py -q --tb=short reproduced 28 failed, 8 passed, covering all six defects. Additional cross-adapter capacity and hidden-rule regressions subsequently reproduced 2 failed, 36 passed before their corrections. The final explicit-rule conflict within FAQ context separately reproduced 1 failed before correction.
  • Final targeted check: .venv/Scripts/python -m pytest tests/unit/test_phase3_context_repairs.py tests/unit/test_phase3_repairs.py tests/unit/test_phase3.py tests/unit/test_gemini_vision.py -q --tb=short: 153 passed. The new regression file has 39 generated cases; existing tests preserve the supplied DOCX's 100 FAQ pairs, including its cross-table pair.
  • .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: 438 passed, 3 skipped, 105 deselected. Skips concern unavailable Windows file/directory symlink privileges; they do not prove that behavior.
  • .venv/Scripts/python -m tests.postgres_prerequisites: passed on isolated rag_phase3_context_repairs_test, dedicated container rag-phase3-context-repairs-20261006, localhost:54925, PostgreSQL 16.15 / pgvector 0.8.7.
  • .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short: 105 passed, 441 deselected, no failures/errors/skips. TEST_DATABASE_URL pointed only to the isolated database above.
  • .venv/Scripts/python -m pip check: No broken requirements found.
  • git diff --check: passed (Git reports existing LF/CRLF conversion notices). The six affected files also passed Python AST, trailing-whitespace and local Markdown-link checks, including untracked files.
  • Initial migration SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
  • Database cleanup inspection returned zero disposable test schemas, public application tables and generated foundation databases. Only the dedicated temporary container and its anonymous volume were removed.

Real-provider quality and manual Persian fidelity acceptance were not executed. Generated fixtures and fake transports are not evidence for either. OS cancellation of blocking DNS/network operations remains unsupported: an operation may occupy the single process-wide slot indefinitely until it returns; capacity failures remain visible and retryable. No adapter retries or late-result consumption are added. Attachment and runtime reuse still require Phase 5 durable current-claim fencing.

Four Phase 3 visibility/scope/completion repairs (2026-10-06)

This section supersedes earlier behavior descriptions where they differ. Generated regressions cover hidden negation, multiple rules within atomic FAQ/visual groups, supported line endings and deterministic completion scheduling.

  • DOCX extraction rejects effective active w:vanish before returning a complete envelope. It resolves document run defaults, used/default paragraph and character styles, and their basedOn chains. Style hiding toggles its inherited state; disabled style hiding leaves that state unchanged. Direct run properties set an absolute state, so explicit 0/false/off can disable inherited hiding. These rules follow Microsoft's Word hidden-text description. Ordinary visible text and unused hidden styles are accepted. Unsupported contextual/table hiding, direct hidden paragraph marks and unresolved/ambiguous visibility styles fail explicitly. No hidden characters are discarded or rewritten, and normalization is unchanged.
  • A complete FAQ can retain multiple article rules with nested conditions and exceptions when Markdown heading ancestry identifies each governing article. An unrelated heading closes the prior scope; an unowned dependency or conflicting explicit target fails. Multiple plain rule lines without sufficient hierarchy remain rejected. Trusted approved_factual purpose is still mandatory.
  • Multiple rules in an infographic retain the entire parent/child group. Dependencies follow explicit ancestor links, including through a conditions node, even when another article is more recent in source order. Missing ancestry, sibling targets and ambiguous rule/dependency nodes fail. Existing incidental-citation checks remain in force. Neither FAQ nor visual groups are split to satisfy the chunk bound: oversized complete groups still fail explicitly.
  • Paragraph splitting recognizes LF, CRLF and CR without changing faithful text or splitting a CRLF pair. Equivalent sources preserve article boundaries and stable paragraph locators/zero-based ordinals; their NFC/LF v1 search text is equivalent. Mixed endings, whitespace separators, exact reconstruction and per-chunk bounds have generated coverage.
  • Gemini finishes response cleanup and releases the process-wide transport slot before publishing either success or failure. A deterministic scheduling test pauses the first worker immediately after result publication and verifies that the next sequential call, using a different adapter, succeeds before it resumes. Timeouts continue to retain capacity while the underlying transport is running. Late results remain rejected, errors redacted/retryable, and adapters add no retries.

Affected files: extraction.py, chunking.py, gemini_vision.py, test_phase3_visibility_scope_repairs.py, this guide and the reference map. Originals, direct document references, frozen profiles, the applied migration, source variants/spacing/numbers/dates/negation/exceptions/ZWNJ and unrelated working-tree changes are preserved. No worker, embeddings, publication, attachment/reuse authorization, HTTP/chat/Live or content-version work is included.

Executed evidence for these four repairs (2026-10-06):

  • Initial .venv/Scripts/python -m pytest tests/unit/test_phase3_visibility_scope_repairs.py -q --tb=short: 22 failed, 21 passed, before implementation changes. All four defects reproduced; visible/disabled-hiding and conflicting-scope controls were included.
  • Combined Phase 3 regression run: .venv/Scripts/python -m pytest tests/unit/test_phase3_visibility_scope_repairs.py tests/unit/test_phase3_context_repairs.py tests/unit/test_phase3_repairs.py tests/unit/test_phase3.py tests/unit/test_gemini_vision.py -q --tb=short: 196 passed. After adding three style-toggle/mixed-ending controls, .venv/Scripts/python -m pytest tests/unit/test_phase3_visibility_scope_repairs.py -q --tb=short passed 46 cases. The final full suite includes all of them.
  • .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: 484 passed, 3 skipped, 105 deselected. The three existing skips concern unavailable Windows file/directory symlink privileges. The supplied DOCX's 100 pairs, previous regression cases and import isolation pass.
  • .venv/Scripts/python -m tests.postgres_prerequisites: the first attempt on the newly started isolated instance failed. After pg_isready reported accepting connections, the retry passed: PostgreSQL 16.15 / pgvector 0.8.7.
  • .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short: 105 passed, 487 deselected, no failures/errors/skips, using isolated TEST_DATABASE_URL for rag_phase3_visibility_repairs_test on localhost:54926 in dedicated container rag-phase3-visibility-repairs-20261006.
  • .venv/Scripts/python -m pip check: No broken requirements found.
  • git diff --check: passed with existing LF/CRLF conversion notices. Separate checks of the six affected files passed Python AST, trailing whitespace and local Markdown links, including untracked files.
  • Initial migration SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
  • Database cleanup inspection found zero disposable test schemas, public application tables and generated foundation databases. Only the named temporary container and its anonymous volume were removed; unrelated containers were preserved.

Real-provider extraction quality and manual Persian fidelity acceptance remain unverified. Fake transports and generated sources provide regression evidence only. OS-level cancellation remains unsupported: a blocking operation can retain the one process-wide transport slot after caller timeout until cleanup finishes. Attachment/runtime reuse still requires Phase 5 durable current-claim fencing.

Phase 3 semantic evidence, identifiers, scopes and HTTP cleanup (2026-10-06)

This section supersedes earlier behavior descriptions where they differ. Generated regressions reproduce semantic formatting loss, identifier-prefix collisions, single-rule scope leakage and unclosed HTTP-error response streams.

  • PageBlockExtractor._reject_docx_semantic_formatting extends the existing effective-property resolver. Active superscript/subscript w:vertAlign, w:strike and w:dstrike are rejected before a complete envelope, alongside hidden text. It resolves direct properties, used/default paragraph and character styles, inherited styles and document run defaults. Superscript 10³ cannot become passed plain text 103, and struck negation cannot lose its deletion semantics. The supplied source XML is unchanged.
  • Baseline alignment and direct disabled strike properties are explicit resets. Single strike uses style-toggle semantics; double strike and vertical alignment inherit absolute values. See Microsoft's single-strike, double-strike and vertical-alignment descriptions. Ordinary bold/italic/color/font-size formatting, unused semantic styles and effective explicit resets remain supported. This is explicit rejection of unsupported semantic formatting, not a faithful formatted-text renderer. Active contextual/table/paragraph-mark semantic formatting also fails safely.
  • Governing references compare complete compact identifiers: decimal digit sequences, dot/slash-separated numeric components and parenthesized suffixes such as 12.1, 1403/100, 1(a), 1(الف) and 1(2). Article/Clause/Circular/Decision and ماده/بند/بخشنامه/تصمیم are supported. Digit-script equivalence is used only for association keys; source text, search normalization, separators, suffixes and leading zeros are preserved.
  • Dotted identifiers are validated before sentence segmentation and are not split at internal dots. Mismatched suffixes/segments fail even when numeric prefixes match. Unsupported compact forms (Roman numerals, hyphens/ranges, square-bracket suffixes, malformed repeated separators) and spaced continuations such as 12 .1, 1403 /100, 1 (a) fail explicitly instead of using a prefix. Explicit dated/مورخ qualifiers describe metadata, not rule identity.
  • FAQ heading ancestry applies even with one explicit Markdown rule. A sibling Background section closes the preceding Conditions scope, so its historical reference to Article 99 does not become an Article 12 applicability target. Visual dependencies use their parent/ancestor branch regardless of rule count; unrelated sibling captions stay outside it. Complete FAQ/visual groups remain faithful and indivisible. Conflicting/unowned dependencies, oversized groups and unapproved FAQ purpose remain rejected; multi-rule behavior is retained.
  • Gemini explicitly closes the stream owned by HTTPError, which bypasses the successful-response context manager. Cleanup completes before transport capacity is released or a worker result is published, including expired requests. Deterministic blocked-close tests prove that another adapter receives a redacted retryable capacity error during cleanup. The caller may still reach its absolute deadline first; late worker results cannot be consumed. Normal HTTP retryability, successful capacity recovery and the no-retry policy are preserved.

Only extraction.py, chunking.py, gemini_vision.py, test_phase3_semantic_repairs.py, this guide and the reference map are affected. Direct document references, immutable originals, frozen profiles, NFC/LF v1, Persian/Arabic variants, spacing, numbers/dates/negation/exceptions/ZWNJ, locators and source ordering remain governed by the existing contracts. No worker, embedding, publication, attachment/reuse authorization, HTTP/chat/Live or content version capability was added.

Executed evidence for these four semantic repairs (2026-10-06):

  • Before implementation changes: .venv/Scripts/python -m pytest tests/unit/test_phase3_semantic_repairs.py -q --tb=short reproduced 61 failed, 33 passed, covering all four defects.
  • Final inspection separately reproduced unsupported spaced identifiers: .venv/Scripts/python -m pytest tests/unit/test_phase3_semantic_repairs.py -k unsupported_spaced -q --tb=short: 3 failed, 94 deselected before the narrow rejection was added.
  • Final targeted command: .venv/Scripts/python -m pytest tests/unit/test_phase3_semantic_repairs.py tests/unit/test_phase3_visibility_scope_repairs.py tests/unit/test_phase3_context_repairs.py tests/unit/test_phase3_repairs.py tests/unit/test_phase3.py tests/unit/test_gemini_vision.py -q --tb=short: 296 passed. The new file contains 97 cases. The supplied DOCX's 100 pairs and all previous Phase 3 regressions pass.
  • .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: 581 passed, 3 skipped, 105 deselected. The existing skips are Windows file/directory symlink-creation privilege cases, not acceptance evidence.
  • After pg_isready reported accepting connections, .venv/Scripts/python -m tests.postgres_prerequisites passed on dedicated rag_phase3_semantic_repairs_test, container rag-phase3-semantic-repairs-20261006, localhost:54927: PostgreSQL 16.15 / pgvector 0.8.7.
  • .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short: 105 passed, 584 deselected, zero failures/errors/skips. TEST_DATABASE_URL was configured only for the dedicated isolated instance above.
  • .venv/Scripts/python -m pip check: No broken requirements found.
  • git diff --check: passed, with existing LF/CRLF conversion notices. Separate AST, trailing-whitespace and local Markdown-link checks passed for all six affected files, including untracked files.
  • A baseline hash comparison of existing tracked/untracked working-tree files confirms that only extraction.py, chunking.py, gemini_vision.py and these two documentation files changed; test_phase3_semantic_repairs.py is the only new file. Originals, frozen-profile/normalization code and unrelated changes were preserved.
  • The applied initial migration SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
  • Cleanup inspection returned zero disposable test schemas, public application tables and generated foundation databases. Only the dedicated test container and its anonymous volume were removed; unrelated containers were preserved.

An intermediate corrected targeted run had one compatibility failure: Decision dated 1403/01/02 was being treated as an identifier. The final parser recognizes the explicit dated/مورخ metadata qualifier; the existing control passes.

Real-provider extraction quality and manual Persian fidelity acceptance remain unverified. These generated fixtures and fake providers do not establish either. OS-level cancellation remains unsupported: a blocked transport or cleanup can outlive the caller and retain process-wide capacity until it finishes. No adapter retries were added. Candidate attachment/runtime reuse remain gated on Phase 5 durable current-claim fencing.

Phase 3 bounded closure repair (2026-10-06)

The fixes are in extraction, chunking and artifact validation. The closure regressions contain 111 generated cases; ordinary tests call no real providers.

Supported/rejected boundaries:

  • Effective DOCX properties resolve direct formatting, used/inherited paragraph/character styles and defaults. Active nonzero position, caps, smallCaps, webHidden and specVanish now fail explicitly, alongside previous hidden/strike/vertical-alignment checks. Raised/lowered digits and displayed case are never guessed or flattened. Direct resets, unused styles and harmless bold/italic/color/font-size formatting remain accepted.
  • Labelled DOCX FAQ answers retain deeper answer headings, paragraphs, tables and table continuations as one atomic group. Standalone Question/Answer headings work with resolved source outline levels. Direct/used/inherited outline hierarchy supplies parent links; peer/higher headings close a pair. A table boundary alone does not close an answer. Incomplete pairs, nested questions, unequal Q/A heading levels and duplicate answers fail explicitly. Paragraph/table/row/cell locators and page=null remain; factual approval and oversized indivisible-group failures still apply.
  • Dependencies match complete dotted/slashed/parenthesized IDs with local digit-script equivalence. English singular/plural labels and Persian ماده/مواد support comma lists, and/or/&/و/یا conjunctions and bare subsequent IDs. Ascending simple-integer through/to/تا/الی ranges retain endpoints: distinct endpoints prove multiple targets without expanding every integer. Multiple distinct targets cannot attach to one rule. Roman/malformed IDs, hyphen/spaced IDs, descending ranges and complex-ID ranges fail explicitly. Incidental citations remain separate from applicability; “The decision is final” is ordinary prose. This is a bounded grammar, not a prose classifier.
  • Plain-text, FAQ and DOCX construction enforce incremental block, normalized-character and artifact-byte counters. Pending FAQ/run/cell text is checked before assembly; labelled cell limits stop before later paragraphs. NFC and CR/LF fragment seams retain faithful evidence. Completed block metadata and ordinals are counted exactly; final artifact validation remains required. PDF checks remain cumulative after direct/fallback pages before provider calls. Budget checks count JSON size without serializing accumulated output. Original decode and ZIP/XML parsing retain their separate existing intake bounds; these counters bound constructed extraction output.

Executed evidence:

  • Initial regressions before fixes: 60 failed, 38 passed. One cell block-count fixture was corrected to produce actual multiple blocks; an additional early-stop regression independently failed with 600 fragment visits. Heading-label and alternative-target cases also failed before their fixes.
  • .venv/Scripts/python -m pytest tests/unit/test_phase3_closure.py tests/unit/test_phase3.py tests/unit/test_phase3_repairs.py tests/unit/test_phase3_context_repairs.py tests/unit/test_phase3_visibility_scope_repairs.py tests/unit/test_phase3_semantic_repairs.py -q --tb=short: 388 passed, including all 111 closure cases, previous Phase 3 regressions and the supplied DOCX's 100 matching Q&A pairs.
  • .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: 692 passed, 3 skipped, 105 deselected. Skips are existing Windows file/directory symlink-creation privilege cases.
  • After pg_isready, .venv/Scripts/python -m tests.postgres_prerequisites passed on dedicated temporary rag-phase3-closure-20261006, database rag_phase3_closure_test, localhost:54928: PostgreSQL 16.15 / pgvector 0.8.7.
  • With TEST_DATABASE_URL scoped only to that isolated instance, .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short: 105 passed, 693 deselected, zero failures/errors/skips. This run preceded two final provider-free early-stop parameter cases; DB code did not change.
  • .venv/Scripts/python -m pip check: No broken requirements found.
  • git diff --check: passed with existing LF/CRLF conversion notices. Separate affected-file AST, whitespace, local Markdown-link and baseline hash checks cover untracked sources too.
  • The prior adjacent-table assertion now keeps continuation text in the last answer: three complete chunks instead of a detached fourth chunk. Originals, frozen profiles, normalization and unrelated files were preserved. Cleanup returned zero disposable test schemas, public application tables and generated foundation databases. Only the dedicated container and temporary volume were removed; unrelated containers were preserved. Applied migration SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.

Material boundaries remain: unsupported DOCX semantics/structures/automatic numbering require explicit extraction support. Real-provider quality and manual Persian fidelity acceptance are unverified. OS cancellation cannot stop a blocked transport/cleanup; capacity stays occupied until completion. Candidate attachment/runtime reuse remain gated on Phase 5 durable current-claim fencing. No worker, embeddings, publication, new services or adapter retries were added.

Minor backlog only: consolidate repeated style-package reads and expand fixtures for additional explicitly supported list grammars.

Phase 4 embedding adapter and bounded staging (2026-10-06)

Source: hosted adapter, application staging, lifecycle type, fake-provider tests and PostgreSQL isolation test.

Phase 4 adds no worker, claims, publication, upload routes or chat integration. Use the adapter only outside database transactions. Phase 5 must consume complete staging in a short claim/lease-fenced publication transaction. A failed batch yields no staged document; concurrent final-batch failures leave the persisted document, job, original and zero chunk rows unchanged.

Configure the independent INGEST_EMBEDDING_ENDPOINT (HTTPS base URL, with /embeddings appended), API_KEY, PROVIDER, MODEL, DIMENSIONS and TIMEOUT_SECONDS. The secret is required only when composing the adapter and never enters profiles. INGEST_EMBEDDING_LIMITS is an explicit JSON object with unit (tokens or utf8_bytes), max_input_units, max_batch_units, max_batch_inputs and tokenizer. Byte units are appropriate only when the selected endpoint's actual contract uses byte limits. For token limits, specify a compatible tokenizer identity and supply a counter with exactly that identity; no token count is estimated from characters. The endpoint/model owner must establish compatibility and limits. No production model or tokenizer is selected automatically.

Optional operator setup for tiktoken: .venv/Scripts/python -m pip install -e ".[test,embedding]". Construct TiktokenCounter("<approved-encoding>"), then OpenAICompatibleEmbeddings.from_settings(settings, token_counter=counter). The identity is tiktoken:<approved-encoding>. Encoding assets may need an initial network/cache preparation; imports and ordinary tests do not initialize tiktoken or download assets. This optional installation and real tokenizer compatibility have not been validated against a hosted endpoint.

New intake snapshots preserve an embedding_request object with limits, timeout, send_dimensions and max_response_bytes, independently of embedding identity. Limits may remain null for provider-free intake/bootstrap. Staging rejects absent or null request limits, mismatched identity/policy and incompatible token counting. Earlier snapshots are not rewritten or assigned guessed limits; embedding those documents requires an explicit future compatibility decision. Retries must use the frozen snapshot. INGEST_EMBEDDING_SEND_DIMENSIONS defaults false and should be enabled only for a model/endpoint supporting that request parameter. INGEST_EMBEDDING_MAX_RESPONSE_BYTES defaults to 16 MiB.

Call stage_document(provider, document_id=..., chunks=..., processing_profile=..., token_counter=counter) as a context manager. It validates contiguous ordinals and metadata, normalizes only embedding inputs with the pinned policy, records actual token counts when available, partitions batches by both count and aggregate units, and yields only complete results. Retained chunk evidence stays faithful. The yielded StagedDocument holds a copy of the frozen profile and read-only views of packed float32 vectors. Consume it inside the context; exit or consumer failure releases the owned profile/chunks/ vectors and further access fails. Consumers must not retain exported views after exit; Python cannot revoke references already copied by consumers.

The staged payload budget includes UTF-8 profile/chunk JSON metadata, normalized input bytes, the document UUID and reserved packed float32 vectors. It is a conservative payload-byte bound, not an OS RSS limit: Python object overhead, bounded batch JSON parsing and transport buffers are additional memory. All draft payload is budget-checked before the first provider request. There is no disk staging, batch checkpoint or document_chunks write in this phase.

Response indexes restore input order. Validation rejects missing/duplicate/ out-of-range/noninteger indexes, incompatible returned model identities, wrong dimensions, nonnumeric/bool, NaN/infinite, float32 overflow/underflow-to-zero and zero vectors. Alias resolution is not implemented. Each batch makes one request with no adapter retries; HTTP 408/429/5xx and network/deadline/capacity failures are transient, other HTTP statuses and invalid inputs/responses/budgets are permanent. Provider bodies, request URLs and secrets are absent from error messages. The worker will own bounded automatic retries in Phase 5.

Redirects are rejected. Response bytes and absolute request duration are bounded. One process-wide embedding transport slot remains occupied until blocking transport/cleanup exits, even after caller timeout; late results cannot be used. OS-level interruption of blocking DNS/I/O/cleanup is unavailable, so a blocked transport can retain this slot indefinitely. Vision has its own independent slot. No real hosted-provider or semantic retrieval-quality validation was executed.

Executed Phase 4 checks (2026-10-06):

  • Initial targeted command: .venv/Scripts/python -m pytest tests/unit/test_phase4.py tests/unit/test_imports.py -q --tb=short: 58 passed. Five further controls were added before the final full suite.
  • Final .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: 754 passed, 3 skipped, 106 deselected. Existing skips concern Windows file/directory symlink privileges; no real providers were contacted.
  • .venv/Scripts/python -m tests.postgres_prerequisites: passed after docker exec rag-phase4-20261006 pg_isready -U postgres -d rag_phase4_test reported accepting connections. Dedicated container rag-phase4-20261006, database rag_phase4_test, localhost:54929, PostgreSQL 16.15 / pgvector 0.8.7.
  • Final .venv/Scripts/python -m pytest -m postgres --require-postgres -q --tb=short: 106 passed, 757 deselected, zero failures/errors/skips. TEST_DATABASE_URL targeted only the isolated instance above. Existing database constraints/races and the new concurrent final-batch failure/zero-chunk invariant pass.
  • .venv/Scripts/python -m pip check: No broken requirements found.
  • git diff --check: passed, with existing LF/CRLF notices. Separate inspection of all 13 affected files, including untracked files, passed Python AST, trailing whitespace and local Markdown links.
  • The applied initial migration SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
  • Dedicated database cleanup inspection found zero disposable schemas, public tables and generated foundation databases. The named temporary container and its anonymous volume were removed; unrelated containers remain.

Affected files: openai_embeddings.py, embeddings.py, settings.py, types.py, ports.py, test_phase4.py (unit and integration), test_imports.py, pyproject.toml, .env.example, this setup guide, the reference map and the ingestion pipeline plan. Unrelated existing changes/specifications and immutable original files were not edited. No schema migration or persisted profile rewrite was introduced.

Real hosted-provider validation, production tokenizer/endpoint compatibility, optional tiktoken installation and retrieval-quality evaluation were not run. Worker claims, retry scheduling and atomic publication remain Phase 5 work. Staging is bounded by payload bytes rather than total RSS; OS cancellation and consumer-retained references have the limitations described above.

Phase 4 reviewed repairs (2026-10-06)

Repair regressions cover the four reviewed defects and controls. The embedding service and hosted adapter now enforce:

  • Float32 multiplication and accumulation for the squared cosine norm, matching the operations relevant to pgvector cosine distance. Both [1e-30, 0, 0] and [1e20, 0, 0] fail permanently, as does aggregate float32 norm overflow. Accepted vectors retain their original float32 bytes; no scaling or normalization is introduced. Real PostgreSQL tests validate all 49 ordered pairs of seven accepted packed vectors, including self, opposite, orthogonal, mixed and small/large magnitudes. The two reviewed extremes produce nonfinite raw PostgreSQL cosine distances and are rejected by the application.
  • Content-Length completion is checked at EOF using the HTTPResponse's initial declared remaining length. Both truncated JSON and syntactically complete prefixes of incomplete bodies fail transiently before decoding. HTTP protocol/incomplete chunk failures are also transient. Tests construct real http.client.HTTPResponse objects over local byte streams without sockets. Response byte bounds, absolute deadlines, stream cleanup and the shared slot remain enforced, with no retries or late-result consumption. A blocked cleanup retains capacity after caller timeout until it exits.
  • UTF-8 JSON (optional BOM) is limited to 64 object/array nesting levels before decoding. Brackets inside quoted/escaped strings do not count. Excess depth and decoder RecursionError failures become redacted permanent EmbeddingError outcomes. Malformed or incomplete responses never return partial vectors.
  • Staging validates required profile mappings, the pinned normalization policy, raw strictly positive integer staging limits before batch-size capping, and ChunkDraft/text/metadata types before use. Expected key/type/attribute/value/ recursion failures become redacted permanent EmbeddingError outcomes. Already-classified provider errors retain their identity and retry category. Consumer exceptions raised inside the context are propagated unchanged while staging is released.

The existing shuffled indexes, complete-document publication boundary, exact payload-budget limits, faithful chunk text, frozen identity/policy checks and context cleanup are preserved. No document_chunks writes, retries, worker, schema changes, persisted-profile rewriting, content versions or chat/Live changes were added. Phase 5 publication fencing remains required.

Real-provider/tokenizer compatibility remains unverified. Generated vector cosine tests are database arithmetic evidence, not semantic embedding quality. The payload budget is not total RSS, and OS cancellation/consumer-retained view limitations from the Phase 4 section remain unchanged.

Executed repair evidence (2026-10-06):

  • Before production fixes, .venv/Scripts/python -m pytest tests/unit/test_phase4_repairs.py -q --tb=short: 36 failed, 25 passed, reproducing all four reviewed defects. Five additional cleanup/depth/request-limit controls were added after the fixes.
  • Final targeted command, .venv/Scripts/python -m pytest tests/unit/test_phase4_repairs.py tests/unit/test_phase4.py tests/unit/test_imports.py -q --tb=short: 129 passed. The new file contains 66 cases.
  • Final .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: 820 passed, 3 skipped, 109 deselected. The three existing skips concern Windows file/directory symlink privileges and provide no acceptance evidence.
  • After docker exec rag-phase4-repairs-20261006 pg_isready -U postgres -d rag_phase4_repairs_test reported accepting connections, .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: 109 passed, 818 deselected, no errors/failures/skips. This run used only TEST_DATABASE_URL for dedicated rag_phase4_repairs_test, container rag-phase4-repairs-20261006, localhost:54930. It preceded the five final provider-free controls; production code did not change afterward.
  • .venv/Scripts/python -m pip check: No broken requirements found.
  • git diff --check: passed with existing LF/CRLF notices. Separate checks of all seven affected files passed Python AST, trailing whitespace and local Markdown links, including the untracked repair test and specifications.
  • Baseline hash comparison confirms exactly six intended existing files changed: embeddings.py, openai_embeddings.py, integration/test_phase4.py, the setup guide, reference map and pipeline plan. unit/test_phase4_repairs.py is the only new file. All other tracked/untracked baseline files and immutable originals are unchanged.
  • Applied initial migration SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
  • Dedicated database cleanup inspection found zero disposable schemas, public tables and generated foundation databases. Only the named temporary test container and its anonymous volume were removed; unrelated containers remain.

No real-provider calls or production tokenizer compatibility checks were made. PostgreSQL arithmetic and constraint evidence is separate from provider quality.

Phase 4 closure (2026-10-07)

Closure regressions exercise fake providers and local HTTP byte streams; PostgreSQL checks provide separate database evidence. The embedding service and hosted adapter now:

  • Capture provider identity and request policy before consuming drafts or counting tokens. Account using the captured dimension, and recheck before requests, after responses/result consumption, and before yielding complete staging. Preparation-time drift fails permanently without provider calls.
  • Reject NUL and invalid UTF-8 in retained text/location strings before embedding, including section metadata passed through a vision extraction envelope, artifact validation and chunking. Evidence is never stripped or rewritten. Persian, ZWNJ and newline controls retain their original text/location values.
  • Inspect only complete, bounded 429 error bodies: at most the smaller of the configured response limit and 64 KiB, with 64 structural nesting levels. Official OpenAI codes credit_balance_exhausted, organization_spend_limit_exceeded, project_spend_limit_exceeded and organization_usage_limit_exceeded, plus the broader insufficient_quota category, are permanent. Temporary rate limits and unknown, empty, malformed, oversized or incomplete bodies retain the status fallback (429 transient). Messages are never used to infer billing status or exposed in errors. See official error codes.
  • Validate direct constructor/configuration types, profile/endpoint values, counter shape/identity, UTF-8 inputs and visible-ASCII authorization keys before transport. Expected validation failures are redacted permanent errors; classified provider errors keep their category. Unrelated programming failures propagate. Inputs require a bounded sequence; iteration is also capped so a dishonest reported length cannot bypass the batch limit.
  • Reject duplicate JSON fields/nonstandard numbers and dishonest vector-result cardinality. Counter identity is rechecked after counting; actual token counts must fit PostgreSQL's positive integer range. Invalid tokenizer identities, raw transport exception context and error-stream cleanup failures are handled safely. Each batch still makes exactly one request with no adapter retries.

The full review retained input/batch unit limits, shuffled-index mapping, model/dimension checks, float32 cosine safety, complete HTTP framing, absolute transport deadlines, payload/depth bounds, shared capacity, cleanup after failure or context exit, faithful evidence and exact staging-budget boundaries. No document_chunks writes, original changes, applied-migration edits, persisted profile rewrites, worker/Phase 5 implementation, content versions or chat/Live changes were introduced. CLI initialization remains independent of the prototype.

Executed checks:

  • Before fixes, .venv/Scripts/python -m pytest tests/unit/test_phase4_closure.py -q --tb=short: 63 failed, 31 passed, reproducing the four requested defects. Subsequent full-contract regressions first produced 5 failed, 110 passed, then the five selected counter/sequence/integer/identity cases produced 5 failed, 115 deselected, before their respective fixes.
  • Final targeted command: .venv/Scripts/python -m pytest tests/unit/test_phase4_closure.py tests/unit/test_phase4_repairs.py tests/unit/test_phase4.py tests/unit/test_imports.py -q --tb=short: 249 passed (120 closure cases).
  • .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: 940 passed, 3 skipped, 113 deselected. The existing Windows symlink privilege skips provide no database acceptance evidence.
  • docker exec rag-phase4-closure-20261007 pg_isready -U postgres -d rag_phase4_closure_test: accepting connections. .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: 113 passed, 943 deselected, no failures/errors/skips. Only the isolated TEST_DATABASE_URL for rag_phase4_closure_test in dedicated container rag-phase4-closure-20261007 (127.0.0.1:54931) was used. New checks prove JSONB rejects NUL, valid Unicode round-trips faithfully and out-of-range token counts fail before provider work. Existing accepted-vector cosine pairs, unsafe norms, concurrency and failed-final-batch zero-publication checks remain included.
  • .venv/Scripts/python -m pip check: No broken requirements found.

Real-provider/production-tokenizer compatibility and semantic quality were not tested. Fake-provider tests and PostgreSQL arithmetic do not establish them. No remaining concrete defect was identified in the reviewed Phase 4 paths. The staging budget measures payload bytes, not total RSS; consumer-retained references and OS-level cancellation/blocking cleanup retain the previously documented limitations. Phase 5 lease fencing and atomic publication remain necessary before a worker can publish staging.

Final preservation/cleanup checks:

  • git diff --check passed (existing LF/CRLF conversion notices only). Separate AST, trailing-whitespace and local Markdown-link checks passed for all seven affected files, including the untracked closure tests.
  • Baseline SHA-256 comparison confirmed exactly six existing files changed: embeddings.py, openai_embeddings.py, integration/test_phase4.py, this setup guide, reference map and pipeline plan. unit/test_phase4_closure.py is the only new file. All other tracked/untracked baseline files, specifications and originals are unchanged. The applied initial migration hash remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
  • Dedicated database inspection found zero disposable schemas, public tables and generated foundation databases. Only rag-phase4-closure-20261007 and its anonymous volume were removed. The three unrelated containers remain.

Phase 4 vector validation, float32 cosine safety, timeout, and endpoint hostname repairs (2026-10-07)

New unit regressions cover all four repaired areas together with positive and negative controls; PostgreSQL tests supply real pgvector arithmetic and multidimensional reference evidence. The service and adapter now enforce:

  • Bounded and consistent vector validation and packing: packed_vector consumes no more than D+1 elements from iterables, never trusting __len__ alone. It validates and packs the same captured elements exactly once into storage requiring actual dimension D and packed storage exactly 4*D bytes. Dishonest sequences (forged length), changing sequences across traversals, and endless generators are stopped boundingly and rejected without bypassing dimension validation or staging budget accounting. Failed final batches trigger complete staging cleanup.
  • Float32 cosine safety without rescaling: pgvector accumulates products and squared norms in float32. Rejecting only subnormal accumulated norms was insufficient: vectors like [1e-21] * 16000 accumulate a normal sum of squares even though every component squared is subnormal with degraded precision, while [3e-23, 0, 0] suffers ~20% cosine distortion against [1, 0, 0]. The precision-safety rule requires that the accumulated float32 squared norm is normal (at least FLT_MIN = 2**-126 ~ 1.17549435e-38) AND at least one component has a normal float32 square (max_i(v_i**2) >= FLT_MIN, or max_i(|v_i|) >= 2**-63). Safe mixed-scale vectors such as [1e-30, 1, 0] are preserved unscaled. Isolated PostgreSQL comparisons against high-precision float64 references validate boundary magnitudes (1e-18, 1e18, 1e19, 1.0), dimensions (1D, 2D, 4D), signs, and directions (self, orthogonal, opposing, oblique, mixed-scale).
  • Runtime-unrepresentable timeout rejection: Synchronization (PY_TIMEOUT_T_MAX) and platform socket timeval bounds (e.g. 32-bit microsecond/millisecond limits fitting in 2**31 - 1) are preflighted upfront. timeout_seconds=1e20 and unrepresentable values are rejected directly in the constructor and from_settings as redacted permanent EmbeddingError outcomes (retryable=False) without starting a thread, making a request, or occupying _CAPACITY. Ordinary deadlines and transport capacity cleanup are preserved. Frozen profiles are never silently clamped.
  • Locally invalid endpoint hostname rejection: Validates runtime hostname syntax and IDNA encoding without DNS or network calls. Rejects empty interior DNS labels (example..com), leading/trailing dots, labels longer than 63 characters, label-boundary hyphens, and malformed IPv4/IPv6 spellings. Preserves valid DNS names (api.openai.com, Example.invalid), IPv4, IPv6 ([::1], [2001:db8::1]), ports, paths, and exact frozen profile identity. Redacted permanent errors propagate through direct construction and settings paths. Unrelated programming failures propagate without a blanket exception handler.

Executed validation:

  • .venv/Scripts/python -m pytest tests/unit/test_phase4_vector_timeout_repairs.py -q: 50 passed.
  • Combined Phase 4 targeted tests: .venv/Scripts/python -m pytest tests/unit/test_phase4_vector_timeout_repairs.py tests/unit/test_phase4_closure.py tests/unit/test_phase4_repairs.py tests/unit/test_phase4.py tests/unit/test_imports.py -q: 299 passed.
  • .venv/Scripts/python -m pytest -m "not postgres" -q --tb=short: 990 passed, 3 skipped, 117 deselected. The three skips are Windows symlink privileges, providing no database evidence.
  • docker exec rag-phase4-repairs-20261007 pg_isready -U postgres -d rag_phase4_repairs_test: accepting connections. .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: 117 passed, 993 deselected, zero failures/errors/skips. Used isolated TEST_DATABASE_URL on localhost:54932 in temporary container rag-phase4-repairs-20261007.
  • .venv/Scripts/python -m pip check: No broken requirements found.
  • git diff --check: passed (existing LF/CRLF conversion notices only).
  • Initial migration SHA-256 remains 9B33C32CB7CC8AB67DDD523D8FF3DA3AB6D1CB3B8D986C3652DADAD3764EE567.
  • Dedicated database inspection found zero disposable schemas, public tables, and generated foundation databases. Only temporary container rag-phase4-repairs-20261007 and its anonymous volume were removed; unrelated containers remain.

Limitations: Real hosted model compatibility, retrieval quality, and tokenizer distributions remain unverified by mock and arithmetic tests. Phase 5 worker claim fencing and publication remain required before staged vectors can be published.