A document changes while its previous revision is still being embedded. The new job is smaller and finishes first. Retrieval begins serving revision 12. Then the slower job for revision 11 completes and overwrites the active document.
Both jobs can report success. Each may have replaced its document’s chunks atomically. The corpus still moved backwards.
I would require a source-order check at the publication boundary. A worker finishing later should not gain the right to replace newer content. That check belongs in the write that changes active state, with a revision supplied by a trusted ordering authority.
The example below is an application-owned Python and SQLite fixture. It reproduces completion-order regression and tests a monotonic revision guard. It is not a report of a vendor incident, a vector database integration or a distributed ingestion benchmark.
Atomic replacement can still publish the wrong revision
The stale-chunk article covers a different failure: updating a shorter document while leaving its obsolete tail searchable. Replacing the complete chunk set fixes that defect, but an old job can still replace the complete set with old content.
Consider this execution order:
- The source assigns revision 11 to a document and starts ingestion.
- The source assigns revision 12 to an edit and starts another job.
- Job 12 finishes and publishes its complete result.
- Job 11 finishes and tries to publish its complete result.
An unconditional upsert accepts the final write. The fixture’s weak-path test runs revisions 12 and 11 in that order, then reads revision 11 back. The database did what the statement requested.
SQLite’s UPSERT documentation describes a conditional alternative. A WHERE clause after DO UPDATE can turn the update into a no-op after comparing proposed and existing values. The documented example compares dates; this fixture compares trusted integer revisions:
INSERT INTO active VALUES (?, ?, ?, ?)
ON CONFLICT(tenant, document) DO UPDATE SET
revision=excluded.revision,
payload=excluded.payload
WHERE excluded.revision > active.revision;
excluded.revision is the proposed revision. active.revision is the existing one. The composite primary key scopes the comparison to one tenant and document. Revision 200 for another document has no bearing on whether this document may advance from 11 to 12.
The fixture stores the entire chunk list as JSON in the same row as its revision. That deliberately small representation lets the test examine publication ordering without pretending to implement embeddings or search. A successful update changes the revision and payload together.
The revision must describe source order
A completion timestamp would reproduce the original bug: the slow old job really did complete later. A counter allocated when a worker finishes would do the same. Random job IDs identify attempts but provide no source ordering.
The fixture therefore assumes a nonnegative integer revision assigned before processing by a trusted source or ingestion coordinator. It rejects booleans, strings and values outside SQLite’s signed 64-bit integer range. These checks constrain representation; they cannot prove that the supplied revision is truthful.
Do not let an untrusted worker select a large revision to override the corpus. The service accepting publication must bind the revision to the source document and the job’s authorised input. In a real pipeline, retain the source version, extraction configuration and embedding configuration alongside that binding.
If the source exposes only opaque ETags, do not compare them lexicographically. Use an application ordering protocol or a conditional active-pointer update with a well-defined expected predecessor. A source with branches or concurrent edits may need explicit conflict resolution before any single integer can represent its intended publication order.
There is also a limit to the policy being tested. It keeps the active document at the highest revision that has successfully published. It does not stop revision 11 publishing while revision 12 is still processing and no newer result is active. If your policy forbids serving any superseded revision once an edit is known, you need a separate authoritative desired-revision check and a rule for what retrieval serves while that revision is unavailable.
Distinguish a stale job from a duplicate
A no-op deserves a precise outcome. The download returns stale for an older revision and duplicate for an equal revision with identical content. Neither result counts as a new publication.
Equal revision with different content raises an error. Otherwise a retry could quietly change the meaning of an allegedly immutable revision. Here, equality compares the serialised chunk list, including chunk order. A production pipeline that intentionally rebuilds a source revision with a different extraction or embedding configuration needs a separate build identity and an explicit promotion policy.
The equal-revision check reads the current row inside BEGIN IMMEDIATE, before the conditional upsert. SQLite’s transaction documentation states that it allows only one simultaneous write transaction and that BEGIN IMMEDIATE starts one immediately. That protects this read-and-write sequence against another SQLite writer interleaving its own publication. Lock contention can still produce SQLITE_BUSY; the fixture does not implement a retry scheduler.
The function owns its transaction and expects an idle connection. On a conflict or injected failure, it rolls back if the connection remains in a transaction. It returns published only after commit succeeds. This is a local database acknowledgement, not evidence that a remote search index has refreshed.
Keep deletion ordered too
Deleting the active row removes the revision guard along with the content. A delayed retry could then insert an old revision as though the document had never existed.
The fixture instead publishes revision 13 with a null payload as a deletion tombstone. A retry of revision 12 is stale because the key and revision remain present. Retrieval must interpret the tombstone as unavailable content; the fixture’s read helper exposes it for inspection rather than acting as a search endpoint.
An empty chunk list has a different meaning: the document exists but currently has no chunks. This distinction avoids accidentally treating an empty extraction as an authorised deletion.
Keeping tombstones forever may be unsuitable for your retention policy. Removing one safely needs evidence that older jobs, replay streams and restored backups cannot reintroduce the deleted document, or another durable high-water mark that still rejects them. This fixture has no garbage collector. It also does not erase historical copies or satisfy a privacy-deletion obligation merely by changing one active row.
Run the publication-order tests
Download and inspect rag-generation-order.py. It requires Python 3.9 or later and SQLite 3.24 or later. It uses an in-memory database, with no network requests, model calls or file writes.
python3 rag-generation-order.py
python3 rag-generation-order.py --test
python3 -O rag-generation-order.py --test
Executed demonstration output:
completion 12 -> published
completion 11 -> stale
active: (12, ['current policy'])
deletion: published
late retry: stale
active: (13, None)
Ten tests cover the unconditional regression, both revision arrival orders, an identical retry, conflicting content for one revision, deletion followed by an old retry, tenant and document separation, revision validation, payload and identity validation, and rollback before commit. The unittest checks remain active under optimisation.
The arrival-order tests are deterministic serial executions. They establish the stale-result failure and the conditional repair without relying on lucky thread timing. They do not establish distributed linearizability, crash durability, concurrent-reader behaviour or vector-index readiness. The SQLite transaction semantics support the local implementation; a different storage adapter needs tests for its own conditional-write contract.
Promote a complete generation before retiring the old one
For a large corpus, rewriting one JSON row is not a practical storage layout. A possible application design is to stage immutable chunks under a generation ID, verify that generation is complete and queryable, then conditionally advance an active pointer. Readers must pin that generation for the request. Retire old chunks only after the reader and retention policies allow it.
That design is a next implementation step, not a capability of this download. A pointer update alone cannot make an asynchronously refreshed vector index ready. The bulk-receipt article separates batch acknowledgement from item success and search visibility. Authorisation also remains a separate gate: a current document can still be forbidden to the requesting user.
For the broader approach to tool contracts and review evidence, see my Claude Code book, available as a Kindle edition on Amazon UK.
Add a reversed-completion test to your actual ingestion adapter. Publish a newer revision, then release a paused older job. Check both the recorded publication outcome and the content retrieval returns. Repeat after a deletion, before allowing failed jobs to replay against the live corpus.