feat(ingestion): add Phase 1 database and application foundation

Add the scoped PostgreSQL/pgvector schema, independent ingestion settings and ports, embedding profile checks, and trusted administrator bootstrap.

Include repository contracts and guidance, organized provider-free and PostgreSQL tests, deployment setup, and byte-preserving migration attributes.

Validation: 163 tests passed; all 48 PostgreSQL cases passed with pgvector Python 0.5.0 and 0.3.6. No production schema or historical metadata was changed.
This commit is contained in:
amirhosein mazaheri
2026-10-05 16:38:28 +03:30
parent cb54a35c90
commit baf58da562
50 changed files with 4628 additions and 3 deletions
+316
View File
@@ -0,0 +1,316 @@
# Document ingestion pipeline: six implementation phases
## 1. Target and boundaries
Build this pipeline:
```mermaid
flowchart LR
A["Import PDF or Markdown"] --> B["Save immutable original + queued job"]
B --> C["Worker claims job"]
C --> D["Extract and normalize"]
D --> E["Chunk"]
E --> F["Embed batches"]
F --> G["Stage all results in memory"]
G --> H{"Every chunk valid?"}
H -->|Yes| I["One transaction: insert chunks + mark ready"]
H -->|No| J["Discard staging; retry or fail"]
I --> K["PostgreSQL + pgvector"]
```
**Publication is atomic per document.** If a document produces 100 chunks, all 100 embeddings must succeed before any chunk is committed to `document_chunks`.
Document metadata and its ingestion job are persisted before processing. After publication, the document is `ready` but remains inactive.
This milestone includes a local import/status/retry CLI and a separate worker. Authenticated upload APIs, selection controls, and replacing the existing Chroma chat retriever are later milestones. Completing this pipeline will not yet make chat search pgvector.
The prototype has Markdown loading, character chunking, and Chroma/FastEmbed indexing. Ingestion Phase 1 now has a pyproject.toml manifest, Alembic foundation migration, independent settings/ports/database access, trusted bootstrap, and pytest regressions. Local PostgreSQL foundation acceptance has now passed in both supported pgvector Python environments; see the setup guide for exact results and remaining deployment/provider limitations. There is no ingestion intake CLI or worker yet; Phases 2-6 remain planned. See [foundation setup](ingestion-foundation-setup.md).
## 2. Shared implementation decisions
Use the repository's database and workflow contracts through [the reference map](../data/documents/agent-reference-map.md).
- Implement application services under `app/modules/documents/`, storage/database/provider adapters under `app/infrastructure/`, and worker orchestration in `app/worker.py`.
- Use PostgreSQL jobs, SQLAlchemy, Alembic, Psycopg, and pgvector. No message broker or staging table.
- Use a PDF parser such as `pypdf` for text-based PDFs; UTF-8 decoding for Markdown. OCR and complex table reconstruction remain excluded.
- Define small internal types: extracted blocks, chunk drafts, embedding profile, and a complete staged document. Keep provider response objects inside the embedding adapter.
- Preserve immutable originals and direct `document_id` references. Do not add document-content versions.
- Record extraction, normalization, chunking, and embedding settings in `documents.processing_profile`. Retries use that recorded profile.
- Keep the new ingestion entry points independent of the prototype retriever and its import-time indexing.
**Configuration defaults**
All limits are environment-configurable, validated at startup, and documented in `.env.example`.
| Setting | Initial default |
| --- | --- |
| Accepted formats | `.pdf`, `.md` |
| Maximum original size | 20 MiB |
| Maximum PDF pages | 200 |
| Maximum normalized characters | 1,000,000 |
| Maximum chunks per document | 2,000 |
| Chunk size / overlap | 1,000 / 200 characters |
| Embedding batch size | 32 chunks |
| Maximum staged payload | 128 MiB, measured using text bytes and packed vector storage |
| Worker concurrency | One document |
| Poll / heartbeat / lease | 2 / 20 / 120 seconds |
| Maximum automatic attempts | 3 |
| Retry delay | Exponential backoff with jitter, capped at 300 seconds |
Keep character units explicit; leave `token_count` null unless actually calculated. The adapter must additionally enforce the selected model's input and batch limits.
Embedding endpoint, API key, model, and vector dimension are required deployment configuration, with no silently chosen production model. Freeze dimension before creating `vector(D)`; worker startup must reject schema/profile incompatibility. Equal dimensions alone do not establish model compatibility.
The hosted adapter must map returned vectors using response indexes and only send optional dimension parameters when supported. These requirements follow the [official embedding API contract](https://developers.openai.com/api/reference/resources/embeddings/methods/create). Other compatible endpoints require their own compatibility check.
## 3. Phases and implementation prompts
Run these phases sequentially. For each phase, use the following shared instruction followed by its phase prompt.
**Shared instruction**
```text
Use $implement-feature. Read AGENTS.md, applicable nested instructions, and
data/documents/agent-reference-map.md. Follow the referenced Phase 1
database and ingestion workflow contracts.
Implement only the requested phase and its necessary tests. Inspect the
current repository and previous phase outputs first. Preserve unrelated
working-tree changes, including untracked specifications.
Keep original documents immutable, use direct document_id references,
and preserve processing-profile metadata. Keep the ingestion CLI and
worker independent of the prototype chat/retriever initialization.
Do not add upload APIs, selection UI, a broker, document versions, or
chat/Live changes. Ordinary tests must not call real providers. Test
database constraints and concurrency against isolated PostgreSQL with
pgvector.
Update setup instructions and the reference map when commands or source
locations change. Report implemented behavior, exact checks and results,
and remaining limitations. Do not claim unexecuted checks passed.
```
### Phase 1 — Database and application foundation
**Outcome:** A reproducible database schema and isolated ingestion configuration.
```text
Implement Phase 1: ingestion foundation.
Create a dependency manifest and pytest setup. Add SQLAlchemy/Psycopg
database access, Alembic migrations, and pgvector support.
Create the contract-defined organizations, users, organization_settings,
documents, ingestion_jobs, document_chunks, and audit_events tables in
dependency order. Include scoped foreign keys, state checks, request-key
uniqueness, one job per document, and unique document/ordinal chunks.
Do not create conversation or Live tables for this milestone.
Require the embedding model and dimension as deployment inputs. Configure
vector(D) explicitly at initial migration; never rewrite applied migrations
when environment settings change. Add schema/profile compatibility checks.
Implement the configurable limits from this plan and separate ingestion
settings from prototype chat credentials. Add provider-neutral processing
types and narrow repository/FileStore/EmbeddingProvider interfaces.
Provide a trusted operator bootstrap command for the initial organization
and administrator, using a securely supplied password and maintained
password hashing. Do not implement HTTP authentication yet.
Acceptance: migrations work on an empty PostgreSQL/pgvector database;
invalid states, cross-organization references, and duplicate chunk
ordinals are rejected. Ingestion modules import without provider calls,
model downloads, corpus scanning, or chat credentials.
```
### Phase 2 — Durable document intake
**Outcome:** Importing a file safely creates one immutable original and one queued job.
```text
Implement Phase 2: local document intake.
Add `python -m app.ingest import`, accepting an explicit file path,
administrator ID, UUID idempotency key, and optional title. Resolve the
organization from the enabled administrator record. This is a trusted
operator command, not an HTTP authorization substitute.
Validate size, supported format, safe display filename, and content/type
consistency. Store originals using generated keys, temporary writes,
and atomic finalization. Hash original bytes and normalized title.
Create document, queued job, and upload audit in one short transaction.
Snapshot the processing profile. Same key and payload returns the same
document/job IDs; changed payload conflicts. Different keys create
independent documents even for identical bytes.
Add `python -m app.ingest status` with structured document/job output.
New documents are inactive, with zero published chunks.
Handle duplicate-import races and unused temporary files. Provide a
report-only reconciliation command for orphan files and missing originals;
do not introduce physical document purging.
Acceptance: originals survive restart, replay is stable under concurrency,
changed-payload conflicts work, filenames cannot escape storage, and
failed database writes cannot create acknowledged jobs.
```
### Phase 3 — Extraction, normalization, and chunking
**Outcome:** A stored original produces deterministic, traceable chunk drafts.
```text
Implement Phase 3: PDF/Markdown processing.
Read originals through FileStore. Verify retained bytes against the stored
hash. Extract PDF text page by page and decode Markdown as UTF-8.
Normalize line endings and Unicode conservatively. Preserve Persian
characters and ZWNJ, Markdown code indentation, paragraphs, and headings.
Avoid destructive whitespace collapsing or rewriting document meaning.
Create extracted blocks with page/section metadata. PDF pages are 1-based;
Markdown has page=null. Never invent unavailable locations. Fail empty,
corrupt, encrypted, and detected unsupported scanned content visibly.
Report extraction limitations instead of claiming OCR or table fidelity.
Chunk deterministically within page/section boundaries, preferring
paragraph and line boundaries. Default to 1000 characters with 200
characters overlap; validate overlap < size. Split oversized blocks,
discard empty output, and assign contiguous zero-based ordinals.
Preserve heading context and source location.
Enforce configured page, extracted-character, and chunk limits during
processing. Exceeding a limit fails the document; never silently truncate.
Acceptance: fixtures cover Markdown headings/code, English and Persian,
text PDFs, blank/scanned PDFs, malformed input, overlap, oversized
paragraphs, deterministic ordering, and configurable limits.
```
### Phase 4 — Embeddings and memory staging
**Outcome:** Every chunk has a validated vector before publication is possible.
```text
Implement Phase 4: embedding adapter and staging.
Implement one OpenAI-compatible hosted embedding adapter with separately
configured endpoint, secret, model, dimension, timeout, and batch limits.
Keep credentials server-side and provider objects inside the adapter.
Implement profile-specific input/batch limit validation. Require compatible
token counting where the selected endpoint uses token limits. Do not
assume character count equals token count or silently truncate inputs.
Embed batches outside database transactions. Map responses by returned
index and validate completeness, unique indexes, dimension, finite values,
and nonzero vectors suitable for cosine distance.
Accumulate chunk text, metadata, and vectors in a bounded in-memory staged
document. Require exactly one vector per ordinal and one consistent
profile. Exceeding the memory budget fails explicitly.
Do not write document_chunks here. Any failed batch makes the staged
document unpublishable. Release staging after completion or failure.
Normalize provider errors into transient and permanent categories; leave
automatic job retries to the worker to avoid stacked retry budgets.
Acceptance: fake-provider tests cover shuffled responses, missing and
duplicate indexes, wrong dimensions, NaN/infinite/zero vectors, timeouts,
rate limits, permanent errors, and staging limits. A failed final batch
must leave zero published chunks.
```
### Phase 5 — Durable worker and atomic publication
**Outcome:** The full pipeline runs safely across failures and restarts.
```text
Implement Phase 5: worker orchestration and atomic publication.
Add `python -m app.worker`, with continuous polling and a --once mode
that processes at most one eligible job.
Claim eligible queued or expired jobs with SKIP LOCKED, a fresh claim
token, lease, and incremented attempt count. Exclude deleted documents.
Commit claims quickly and use the documented document-before-job lock
order for subsequent updates.
Run extract -> chunk -> embed -> publish with durable stage reporting.
Maintain heartbeats during extraction and provider waits. Fence all
progress, heartbeat, retry, failure, and publication writes by the claim
token and valid lease. A stale worker must discard its results.
Publish in one transaction: lock document then job; verify ownership,
unexpired lease, eligible document state, non-deletion, original/profile
compatibility, and complete staged results; insert all chunks; update
chunk_count/ready_at/status and mark the job succeeded. Keep is_active=false.
Never republish a ready document.
Rollback everything on publication failure. Recover ambiguous commit
outcomes by re-reading durable state before retrying. A successful commit
followed by a worker crash must not duplicate chunks.
Schedule transient failures with bounded backoff/jitter. Fail permanent
errors immediately and exhausted jobs terminally. Crash recovery reruns
the entire document; no batch checkpoints.
Add `python -m app.ingest retry` for eligible failed documents, with an
idempotency key and administrator validation. Reuse the same document/job,
reset attempts, increment retry_generation once, and audit atomically.
Acceptance: real database tests cover concurrent claims, lease expiry,
stale worker writes, late provider responses, exhausted recovery,
publication rollback, ambiguous completion, and retry replay.
```
### Phase 6 — Integration proof and handoff
**Outcome:** A reproducible demonstration proves the pipeline's guarantees.
```text
Implement Phase 6: integration validation and operator handoff.
Build end-to-end tests using isolated PostgreSQL/pgvector, a temporary
original-file directory, real extractors, and a deterministic fake
embedding provider.
Prove that chunks remain absent while embedding batches are incomplete,
then appear together with ready/succeeded state after publication.
Verify exact row count, contiguous ordinals, source locations, profile,
and vector dimension. Confirm documents remain inactive.
Exercise crashes before publication and after commit, a failed final
embedding batch, expired claims, deletion before publication, missing
originals, duplicate imports, and idempotent manual retry.
Add worker heartbeat reporting and redacted logs containing document/job
IDs and stage/error categories. Document setup, migration, bootstrap,
import, status, retry, worker, and reconciliation commands.
Provide a separate opt-in real-provider smoke command requiring explicit
corpus and provider configuration. Keep it out of ordinary tests and
report provider compatibility and extraction quality separately.
Update README and the reference map. Clearly document that the existing
chat retriever still uses Chroma and that pgvector search/selection is
the next milestone.
```
## 4. Final acceptance criteria
This milestone is complete when:
- A PDF or Markdown import creates a durable, independent document and job.
- Extraction and chunking preserve usable evidence locations.
- **Every chunk is embedded before any chunk is published.**
- Publication commits all chunks and completion state together.
- Failures, restarts, duplicate requests, and stale workers cannot create partial or duplicate publication.
- Configuration overrides work and processing profiles remain traceable.
- Published documents remain inactive until a later authorized selection workflow.
- Automated PostgreSQL evidence and documented operator commands support these claims; real-provider validation is reported separately.