Add retryable extraction, chunking and ingest worker (I02, #18) #60

Merged
amiryahaya merged 16 commits from feat/18-extraction-chunking into main 2026-10-26 16:28:13 +01:00
Owner

Refs #18

What

Retryable extraction and source-preserving chunking for the first approved formats (UTF-8 plain text and Markdown, OD-07 still proposed), run by a new ingest-worker process.

  • Contract (rag-domain): IngestionJobs, ClaimedJob, ChunkRecord, ExtractionFailure (closed set of 8 safe error codes; only storage_unavailable retries).
  • Extraction (rag-ingestion::extract): verifies profile, SHA-256 digest, UTF-8, control characters and emptiness, in that order, before anything is chunked.
  • Chunker text-chunk-v1: at most 1000 source characters, 150 overlap, fixed break order. Each chunk stores half-open UTF-8 byte offsets into the original, text = NFC(original[start..end]), a text_sha256, a language hint (en/ms/mixed/und, a hint only, never used for policy) and a deterministic UUIDv8 id from (version, profile, ordinal). Golden fixtures cover English, Malay, mixed, combining marks, astral characters and CRLF; an 8 MiB input runs in the tests.
  • Migration 0012_chunks.sql: job lease columns, the document_chunks table, and a NOLOGIN rag_ingest_worker role with column-level grants (it cannot read title, marking or provenance, cannot update versions, cannot touch audit/outbox). Chunks inherit the version's marking by foreign key. rag_app has no access to chunks (default-deny, enforced by the startup guard). The existing 0008 policies are now scoped TO rag_app (they previously applied to PUBLIC).
  • PostgresIngestionJobs: lease plus FOR UPDATE SKIP LOCKED claim, reaping, attempt cap 5 with backoff (30 s x 2^(n-1), capped at 15 min), lease-fenced complete (all chunks and succeeded in one transaction), fenced fail, and backlog counts. Undecodable jobs are retired instead of stalling the queue.
  • Worker loop and metrics, and the ingest-worker binary (crates/api): separate /health/live and /health/ready (reusing F07), /metrics with fixed labels only, payload-free panic hook, SIGTERM drain, loopback bind unless INGEST_WORKER_ALLOW_REMOTE=true. Operator guide: docs/operations/ingestion-worker.md.

Deviations and things to know

  • FR-ING-005: a failed extraction leaves the version quarantined and the job dead with a safe code; the version is not marked unavailable. It is still invisible to rag_app (active versions only), and the success path also leaves the version quarantined. #19-#21 must require job.state = 'succeeded' before a version becomes active.
  • Security: the production single cross-organization worker role needs security-authority acceptance. RLS ties chunk inserts to non-terminal jobs of quarantined versions but not to the caller's lease, and nothing ties chunk text to the source span, so a compromised worker could write unrelated text. #21 must re-verify NFC(original[byte_start..byte_end]) == text before publishing.
  • For #20: Unicode format characters only (BOM-only, zero-width-only input) yield a content-free chunk; the lexical tokenizer must treat them as separators.
  • The worker role also has SELECT (version, success, checksum) on _sqlx_migrations so migrations::verify works; migration 0012 was edited in place during review, so any dev database migrated from earlier #18 commits must be recreated (nothing from this branch is on main).
  • ingest-worker does not read CRYPTO_PROFILE_SET yet (K02 follow-up; see PR #59).
  • Known gaps are listed in the worker guide: memory about 3.5x input while completing, last-resort split can break a grapheme cluster (citations stay exact), lowering the attempt cap strands failed jobs, chunk retention is undecided (OD-07).

Verification

  • cargo test --workspace: 277/277. scripts/test-postgres.sh --local (real PostgreSQL): 276/276. cargo fmt --check and cargo clippy --workspace --all-targets -- -D warnings clean.
  • scripts/coverage.sh rust: 94.50% workspace line coverage (minimum 80%). New/changed files: chunk.rs 97.7%, ingestion/worker.rs 98.6%, storage-postgres ingestion.rs 98.5%, ingest_worker.rs 94.8%, bin/ingest-worker.rs 96.0%, domain ingestion.rs 96.9%. api/src/main.rs is 34.5% (identity wiring never covered; this PR only removes lines from it).
  • 8 MiB document: 11,050 chunks, run_once about 2.6 s in a debug build, of which about 2.4 s is chunking outside any transaction and about 250 ms is the single completion transaction (default statement timeout 5 s).
  • Dual-pass review (Ponytail complexity + opus correctness) over each task and the whole branch. Notable catches, all fixed with tests that failed first: a worker able to revive terminal jobs and write chunks onto live versions; a decode failure stalling the whole queue; the documented re-queue SQL silently updating 0 rows; retry-or-dead decided in two places.

Not in this PR

  • Embedding, Qdrant and FTS indexing, publishing a version as active (#19-#21), PDF/OCR, retrieval, UI.
  • Worker heartbeat/lease extension, alerting rules, a page-mapping column (not applicable to text).

🤖 Generated with Claude Code

Refs #18 ## What Retryable extraction and source-preserving chunking for the first approved formats (UTF-8 plain text and Markdown, OD-07 still `proposed`), run by a new `ingest-worker` process. - **Contract** (`rag-domain`): `IngestionJobs`, `ClaimedJob`, `ChunkRecord`, `ExtractionFailure` (closed set of 8 safe error codes; only `storage_unavailable` retries). - **Extraction** (`rag-ingestion::extract`): verifies profile, SHA-256 digest, UTF-8, control characters and emptiness, in that order, before anything is chunked. - **Chunker `text-chunk-v1`**: at most 1000 source characters, 150 overlap, fixed break order. Each chunk stores half-open UTF-8 byte offsets into the original, `text = NFC(original[start..end])`, a `text_sha256`, a language hint (en/ms/mixed/und, a hint only, never used for policy) and a deterministic UUIDv8 id from (version, profile, ordinal). Golden fixtures cover English, Malay, mixed, combining marks, astral characters and CRLF; an 8 MiB input runs in the tests. - **Migration `0012_chunks.sql`**: job lease columns, the `document_chunks` table, and a NOLOGIN `rag_ingest_worker` role with column-level grants (it cannot read title, marking or provenance, cannot update versions, cannot touch audit/outbox). Chunks inherit the version's marking by foreign key. `rag_app` has no access to chunks (default-deny, enforced by the startup guard). The existing 0008 policies are now scoped `TO rag_app` (they previously applied to PUBLIC). - **`PostgresIngestionJobs`**: lease plus `FOR UPDATE SKIP LOCKED` claim, reaping, attempt cap 5 with backoff (30 s x 2^(n-1), capped at 15 min), lease-fenced `complete` (all chunks and `succeeded` in one transaction), fenced `fail`, and backlog counts. Undecodable jobs are retired instead of stalling the queue. - **Worker loop and metrics**, and the **`ingest-worker` binary** (`crates/api`): separate `/health/live` and `/health/ready` (reusing F07), `/metrics` with fixed labels only, payload-free panic hook, SIGTERM drain, loopback bind unless `INGEST_WORKER_ALLOW_REMOTE=true`. Operator guide: `docs/operations/ingestion-worker.md`. ## Deviations and things to know - **FR-ING-005:** a failed extraction leaves the version `quarantined` and the job `dead` with a safe code; the version is **not** marked `unavailable`. It is still invisible to `rag_app` (active versions only), and the success path also leaves the version `quarantined`. **#19-#21 must require `job.state = 'succeeded'` before a version becomes active.** - **Security:** the production single cross-organization worker role needs security-authority acceptance. RLS ties chunk inserts to non-terminal jobs of quarantined versions but not to the caller's lease, and nothing ties chunk text to the source span, so a compromised worker could write unrelated text. **#21 must re-verify `NFC(original[byte_start..byte_end]) == text` before publishing.** - **For #20:** Unicode format characters only (BOM-only, zero-width-only input) yield a content-free chunk; the lexical tokenizer must treat them as separators. - The worker role also has `SELECT (version, success, checksum)` on `_sqlx_migrations` so `migrations::verify` works; migration 0012 was edited in place during review, so any dev database migrated from earlier #18 commits must be recreated (nothing from this branch is on `main`). - `ingest-worker` does not read `CRYPTO_PROFILE_SET` yet (K02 follow-up; see PR #59). - Known gaps are listed in the worker guide: memory about 3.5x input while completing, last-resort split can break a grapheme cluster (citations stay exact), lowering the attempt cap strands `failed` jobs, chunk retention is undecided (OD-07). ## Verification - `cargo test --workspace`: 277/277. `scripts/test-postgres.sh --local` (real PostgreSQL): 276/276. `cargo fmt --check` and `cargo clippy --workspace --all-targets -- -D warnings` clean. - `scripts/coverage.sh rust`: **94.50% workspace line coverage** (minimum 80%). New/changed files: chunk.rs 97.7%, ingestion/worker.rs 98.6%, storage-postgres ingestion.rs 98.5%, ingest_worker.rs 94.8%, bin/ingest-worker.rs 96.0%, domain ingestion.rs 96.9%. `api/src/main.rs` is 34.5% (identity wiring never covered; this PR only removes lines from it). - 8 MiB document: 11,050 chunks, `run_once` about 2.6 s in a debug build, of which about 2.4 s is chunking outside any transaction and about 250 ms is the single completion transaction (default statement timeout 5 s). - Dual-pass review (Ponytail complexity + opus correctness) over each task and the whole branch. Notable catches, all fixed with tests that failed first: a worker able to revive terminal jobs and write chunks onto live versions; a decode failure stalling the whole queue; the documented re-queue SQL silently updating 0 rows; retry-or-dead decided in two places. ## Not in this PR - Embedding, Qdrant and FTS indexing, publishing a version as active (#19-#21), PDF/OCR, retrieval, UI. - Worker heartbeat/lease extension, alerting rules, a page-mapping column (not applicable to text). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
PostgresIngestionJobs connects as rag_ingest_worker, verifies migrations and
refuses any role outside the 0012 grant set. claim reaps expired jobs at the
cap, picks one with FOR UPDATE SKIP LOCKED and leases it; complete inserts all
chunks and marks succeeded in one transaction fenced by the lease token; fail
backs off 30s x 2^(n-1) capped at 15 min or goes dead.

Migration 0012 now also grants SELECT (version, success, checksum) on
_sqlx_migrations so the worker's startup schema check can run.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
claim decodes before leasing and retires a job it cannot run (version gone:
version_unavailable; undecodable: invalid_content) in the same transaction,
then keeps picking, so one bad row can no longer stall the queue. The reaper
skips locked rows. complete refuses a job whose version id differs from the
locked row. Adds partial-failure and wider role-fitness tests; the stale-lease
test no longer sleeps.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Worker::run_once claims one job, extracts and chunks it, and completes it.
Extraction failures are recorded as dead with their safe code; an unavailable
store during complete becomes fail(storage_unavailable), retried below the cap.
LeaseLost from complete or fail is counted, never retried. run polls every
second while idle or after an error, finishes any claimed job before honouring
stop, and never spins when the stop sender is gone.

WorkerMetrics renders Prometheus text with fixed families and labels drawn only
from ExtractionFailure::ALL and the four backlog states; no ids or content.
Logs carry one job_completed event with the opaque job id only.

PostgreSQL tests cover chunk-once, restart mid-job (identical records,
attempt 2), extraction failure (dead, no chunks), an outage on the last chunk
insert (rolled back, retried to the full set) and an 8 MiB document inside the
default 5 s statement timeout.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
CorruptData from complete is failed as invalid_content at once instead of
being retried to the cap. Extraction and chunking run on spawn_blocking so an
8 MiB document does not stall the runtime, and a panic there is failed as
invalid_content with its payload dropped unread instead of unwinding out of
run. rag_ingest_store_errors_total{operation} counts claim, complete, fail and
backlog errors from a fixed label set.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The worker reuses the F07 probes and adds /metrics, rendered from a backlog
refreshed every 15 s in the background (scrapes never query the database).
SIGINT/SIGTERM sets Draining, stops claiming and waits up to the 60 s lease
for the job in flight; a worker loop that dies flips readiness and exits
non-zero. A payload-free panic hook replaces the default one.

Also: the development bootstrap gives rag_ingest_worker its synthetic login,
and the coverage check now runs the ingestion PostgreSQL suites.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Non-loopback INGEST_WORKER_ADDR needs INGEST_WORKER_ALLOW_REMOTE=true (/metrics is
unauthenticated). main installs the panic hook before building the runtime. The
dead-job requeue must run as an RLS-bypassing administrator, not rag_migrator
(pinned by a test running the documented statement).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
refactor(ingestion): store decides retry, drop dead format, shared shutdown signal (#18)
Some checks failed
CI / Web checks (pull_request) Successful in 1m47s
CI / Web checks (push) Successful in 1m50s
CI / Rust checks (push) Failing after 40m24s
CI / Rust checks (pull_request) Failing after 39m52s
eb3adf6cbe
IngestionJobs::fail returns whether the job was rescheduled (RETURNING
state='failed'), so the worker no longer mirrors the rule. ClaimedJob.format and
the worker's media_type grant are removed (0012 edited in place, unmerged).
rag_api::shutdown_signal is shared by the API and the worker; begin_draining is
private; metrics index by discriminant; a DB test pins Rust failure codes to the
CHECK. Docs state the chunk-insert RLS limits and the remaining known gaps.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Merge remote-tracking branch 'origin/main' into feat/18-extraction-chunking
Some checks failed
CI / Web checks (pull_request) Successful in 45s
CI / Rust checks (pull_request) Failing after 7m14s
2d8650aeac
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Merge remote-tracking branch 'origin/main' into feat/18-extraction-chunking
All checks were successful
CI / Web checks (pull_request) Successful in 38s
CI / Rust checks (pull_request) Successful in 19m7s
ef41ff01a1
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Sign in to join this conversation.
No description provided.