Ingestion Pipeline
How ingest reconciles a client's pgvector index with its corpus folder and corpus config — hash, plan, rebuild, prune.
Ingest makes a client’s index match its config. The corpus block in the client YAML is the spec. The documents table is the status. Each run reconciles the two, so re-running it is always safe.
corpora/<client_id>/ corpus: (client YAML)
├── manual.pdf embedding.model, chunking.*
├── runbook.md │
└── sub/spec.html ▼ fingerprint()
│ │
▼ sha256(raw bytes) │
└──────────────► plan() ◄─────────┘ vs. documents (content_hash, ingest_fingerprint)
│
┌─────────────────┼──────────────────┐
▼ unchanged ▼ new / changed ▼ file gone
skip parse → chunk → prune
(never parsed) embed → replace
commit per document
- Preflight. Parse and chunk every file in the folder and account for each one: will ingest, will skip (unsupported extension), will fail (with the error).
--checkstops here. The real ingest prints the same table, from the samepreflight()call. - Hash every supported file’s raw bytes.
- Plan. Rebuild a file whose content hash or ingest fingerprint differs from the stored row. Prune a stored document whose file is gone. Skip the rest.
- Rebuild each planned file: parse, chunk, embed, then replace the old row. Each document commits on its own.
- Prune, then commit.
A failed file does not stop the run. It is recorded as {path, reason}, the rest still commit, and the CLI exits non-zero so a script or CI step notices. A failed embed leaves the previous version of that document indexed. A file that fails to parse is not pruned if it was indexed before.
Stage 1 — Parse
retrieval/parsers.py maps file extensions to parsers:
| Extension | Parser | Title extraction |
|---|---|---|
.pdf | pypdf page extraction | path.stem (titlecased) |
.md, .markdown | plain text read, front matter stripped | title: front matter → first # heading → path.stem |
.docx | python-docx; “Heading N” styles become # levels | First heading, else path.stem |
.txt | plain text read | path.stem (titlecased) |
.html, .htm | BeautifulSoup, strips <script>/<style> | <title> → <h1> → path.stem |
- Every file is accounted for.
iter_corpus()returns all files; the preflight sorts them..xlsx,.csv,.pptxand the rest are listed as unsupported by name, not dropped. - Front matter (
---block at the top of a Markdown file):title:overrides the heading,url:becomes the document’s link. The block is stripped fromtext, or it would be embedded as content. - Scanned PDFs (under ~50 characters of text per page) fail with “needs OCR, not supported” instead of becoming empty documents.
- Flags, not decisions: documents under ~50 tokens (stubs) and files with identical text (the
.md+.pdfdouble-index) are named in the report but still ingested. - Estimates: total chunks, embedding tokens, cost (a dated constant in
ingest.py) and a free-tier worst-case time, so the operator hears it before starting.
All parsers return a ParsedDocument(title, text, source_path, url, pages, markdown).
Stage 2 — Chunk
retrieval/chunker.py splits text into token-aware overlapping chunks using tiktoken (cl100k_base):
Split strategy (in priority order):
- Double-newline (paragraph boundaries)
- Sentence boundaries, if a paragraph exceeds
chunk_size - Hard token split, if a single sentence still exceeds
chunk_size
The last overlap tokens from the previous chunk are prepended to the next, ensuring sentences that straddle a boundary appear in full in at least one chunk.
corpus:
chunking:
chunk_size: 800 # tokens per chunk (default: 800)
overlap: 100 # overlap tokens between chunks (default: 100)
prefix_title: false # default: off
prefix_title: true starts every chunk with <document title> — <heading path>, before it is embedded and before the keyword index sees it. The heading path is the Markdown (and .docx) headings in force where the chunk starts, joined with ›; other formats get the title alone. It changes vectors and the tsvector, so it joins the fingerprint and turning it on rebuilds the index.
Stage 3 — Embed
retrieval/embed.py calls the Voyage AI model named in corpus.embedding.model (default voyage-3, 1024 dimensions).
corpus:
embedding:
model: voyage-3 # voyage-3 | voyage-3-large | voyage-3.5
The model is the one hard contract between ingest and retrieval. Retrieval embeds the question with the same configured model. Two different models give cosine similarities that mean nothing, and every threshold in agent stops meaning anything.
- Allowed models: only ones that emit 1024 dimensions, the width of
chunks.embedding. Any other model fails at config load. - Changing the model: the fingerprint moves, so the next ingest rebuilds every document.
Why Voyage AI?
Embeddings are a supporting component here, not the focus — the bar is “good enough for a demo”, not best-in-class retrieval.
- Anthropic has no embeddings API — a third-party embedder is required regardless. Voyage avoids a second OpenAI dependency alongside the Anthropic SDK.
- Free tier covers POC traffic — no credit card needed for ingest and demo volume.
input_typeis a free quality win — Voyage accepts"document"at ingest and"query"at search, improving recall at no extra cost. Most providers don’t expose this.
Model choice — Voyage has three general-purpose tiers:
| Model | Dims | |
|---|---|---|
voyage-3-lite | 512 | Too much quality loss for a demo |
voyage-3 | 1024 | Picked — balanced quality and cost |
voyage-3-large | 1024 | No perceptible gain at POC scale |
Downside: free tier caps at 3 RPM — hence the retry loop below.
Voyage AI vs pgvector
They solve different problems and neither knows about the other:
| Voyage AI | pgvector | |
|---|---|---|
| Role | Converts text → vectors | Stores vectors, finds nearest neighbours |
| Language understanding | Yes — semantic meaning | No — pure math (cosine distance) |
| Where | External API call | Postgres extension, same DB |
| Invoked | Ingest + every query | Every query |
[text] → Voyage AI → [1024 floats] → pgvector (stored)
[query] → Voyage AI → [1024 floats] → pgvector (<=> cosine) → top-k chunks
pgvector accepts vectors from any embedding model. The only coupling is in embed.py and search.py. A dedicated vector DB (Pinecone, Qdrant) was not used because pgvector runs inside the existing Postgres instance, keeping the stack to one service.
Implementation
- Documents use
input_type="document", queries useinput_type="query". - Batches of up to 128 texts per API call.
- 429 and 5xx errors retry with exponential backoff, up to 6 attempts starting at 21s (respects Voyage’s per-minute window).
Stage 4 — Reconcile
Each document carries two hashes:
| Column | Hash of | Moves when |
|---|---|---|
content_hash | the file’s raw bytes | the file is edited |
ingest_fingerprint | corpus.embedding.model, chunk_size, overlap, and prefix_title / source_url_template when set | a setting that shapes the index changes |
plan() compares both against the stored row:
| State | Action |
|---|---|
| New file | Insert |
| Both hashes match | Skip, without parsing |
| Content or fingerprint differs | Delete and re-insert (chunks cascade) |
| Stored, but the file is gone | Prune |
- Edit one file: that file is rebuilt.
- Change a setting: every file is rebuilt. No
--forceneeded. prefix_titleandsource_url_templatejoin the spec only when non-default, so an existing config keeps its fingerprint and nothing rebuilds on deploy.source_url_templatemoves no vector, but the URL is stored per document, so editing it must rebuild.corpus.sourceis not in the fingerprint. Moving the folder changes no vector.
The index guard
The chat endpoints refuse a client whose stored fingerprints differ from its config’s. They answer 409 index_out_of_date and name the command to run. An index that was never ingested gets the same 409. The check is one SELECT DISTINCT per chat request.
What this replaced
| Before | After | |
|---|---|---|
| Skip test | sha256(parsed text) | sha256(raw bytes) and fingerprint |
| Settings change | Silently skipped; needed --force | Rebuilds every document |
| Deleted file | Stayed retrievable | Pruned |
source_uri | corpus://<client_id>/<stem> | corpus://<client_id>/<relative path> |
| Commit | Once per run | Once per document |
| Embedding model | Hardcoded voyage-3 | corpus.embedding.model |
The previous design is recoverable from 498355c, the last commit before it changed:
git show 498355c:apps/api/app/ingest.py # hash-only skip, no prune
git show 498355c:apps/api/app/retrieval/embed.py # hardcoded voyage-3
When ingest runs
| Trigger | How | Use it for |
|---|---|---|
| API startup | reconcile_all() in a background task | Deploys and restarts. Edit files or settings, restart, done |
| CLI | make ingest CLIENT=<id> | Local work without a restart, and --force |
- Startup runs in the background. A full rebuild on Voyage’s free tier takes minutes. Chat answers
409for that client until it finishes, and the web app shows “The knowledge base isn’t ready.” - A normal restart costs nothing. Unchanged files are skipped by hash, so no embedding calls are made.
- One replica reconciles. A Postgres advisory lock, held on a dedicated connection, makes a second replica skip.
- Stopping mid-run is safe. Documents commit one at a time, so the next start picks up the rest.
- An empty corpus folder is refused. A folder that mounted empty would otherwise prune the whole index, so ingest raises instead.
RECONCILE_ON_STARTUP=0turns the startup run off, for a restart that must not spend embedding budget. Ingest is then the CLI’s job.- No UI trigger. The API has no auth, so a public button would let anyone spend the embedding budget. The corpus is repo files, so whoever edits them can restart. A button belongs with document upload, if that is ever built.
The Docker image copies corpora/ so the container can reconcile itself.
Running the CLI
make ingest CLIENT=gcp-platform-support # ingest
make ingest CLIENT=gcp-platform-support CHECK=1 # preflight only: embeds nothing, writes nothing
make ingest CLIENT=gcp-platform-support FORCE=1 # rebuild every document
make ingest runs cd apps/api && uv run python -m app.cli --client <id> [--check] [--force]. Both modes print the file accounting and exit non-zero if any file failed.
The CLI has one command, so it takes no ingest subcommand.
Sample output:
Ingesting corpus for gcp-platform-support...
┌─────────────────────────────────┬───────┐
│ Metric │ Count │
├─────────────────────────────────┼───────┤
│ Documents added │ 4 │
│ Documents replaced │ 1 │
│ Documents skipped (unchanged) │ 2 │
│ Documents removed (file deleted)│ 1 │
│ Total chunks upserted │ 312 │
└─────────────────────────────────┴───────┘
Search
Retrieval is the mirror of this pipeline: embed_query() embeds the question with the
same corpus.embedding.model, with input_type="query" instead of "document".
pgvector then scans by cosine similarity, scoped to client_id.
The rest — the k×2 over-fetch, the similarity floor, the Hit shape — belongs to the
stage that uses it. See Retrieval.
Database schema
documents
id VARCHAR(64) PK — MD5(client_id:source_uri)[:8]
client_id VARCHAR(64) — foreign key → clients.id
source_uri VARCHAR(512) — corpus://<client_id>/<path relative to corpus.source>
title VARCHAR(512)
content_hash VARCHAR(64) — SHA256(raw bytes)[:32]
ingest_fingerprint VARCHAR(16) — CorpusConfig.fingerprint(); null on pre-0006 rows
url VARCHAR(1024) — front matter `url:` or source_url_template; null = no link
ingested_at DATETIME
chunks
id INTEGER PK autoincrement
document_id VARCHAR(64) — FK → documents.id (CASCADE DELETE)
client_id VARCHAR(64) — denormalized for index-scoped search
text TEXT
embedding VECTOR(1024) — pgvector column
chunk_index INTEGER
metadata JSON — { document_title, source_uri, position }
client_id on chunks is denormalized intentionally — pgvector similarity queries filter on it directly, avoiding a join to documents on the hot path.