Skip to content
Visual explainer 3h 30m to learn 5 steps

Keep a RAG index fresh with upserts and deletions

Run repeatable ingest, re-index and delete jobs that handle failed parsing and stale versions and remove deleted sources from retrieval.

By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 11 minutes to read.

Topic 9 of 34

In short

A RAG index goes stale the moment a source changes, so ingestion must be a repeatable job, not a one-off script. Idempotent upserts mean running the job twice leaves the same result. The job also records parse failures, marks old versions as superseded and makes deleted sources disappear from search while keeping provenance for audit.

Think of it like this: Keeping an index fresh is like restocking a shop shelf: add the new stock, pull expired items and keep the delivery notes.

Explained simply

Documents change. Policies get updated, pages get deleted and new articles appear. If the search index still holds the old text, the assistant will confidently quote a rule that no longer applies. Keeping the index fresh is a regular job, not a one-time import.

The job should be idempotent. That word means running it twice gives the same result as running it once. If the job crashes halfway and you run it again, you should not end up with duplicate chunks or missing documents. Databases help with this through upserts and transactions.

Things go wrong. A file might be badly formatted and fail to parse. The job should write down the failure, keep serving the last good version and try again later. It should never throw away good data because new data was broken.

When a source is deleted, it must stop appearing in answers. But you still want to know it existed and when it left, for audits and for explaining old answers. So the job marks it as deleted, which hides it from search, and keeps a small record called a tombstone.

Press Play on a diagram to walk through it one step at a time.

CycleThe ingest loop
  1. 1
    Scan sources

    List files with hash and modified time

  2. 2
    Diff

    New, changed, unchanged or deleted

  3. 3
    Parse and chunk

    Failures go to a retry table

  4. 4
    Upsert in a transaction

    New version active, old superseded

  5. 5
    Verify

    Counts, orphans and a sample query

  6. Back to step 1
CompareUnsafe versus safe re-indexing
Unsafe
  • Delete all chunks, then reload
  • Search empty during reload
  • Parse error loses the document
  • Second run duplicates rows
Safe
  • Diff by hash, touch only changes
  • One transaction per document
  • Last good version kept on error
  • Deterministic IDs make reruns no-ops

In depth

Diffing sources before doing any work

Each run starts by listing every source with its doc_id, version and content hash, then compares that list with the database. Four outcomes are possible. New: the doc_id is unknown, so ingest it. Changed: the hash or version differs, so add a new version. Unchanged: skip it, which keeps runs cheap. Missing: the doc_id is in the database but not in the sources, so it may be deleted.

Be careful with missing. If the scan failed, for example because a network share was unavailable, every document looks missing. Guard against this: require the scan to succeed, and refuse to delete more than a set fraction of the corpus in one run without a manual override.

  • New: insert version 1
  • Changed: insert the next version, supersede the old one
  • Unchanged: skip, no embedding cost
  • Missing: delete only if the scan succeeded
  • Cap deletions per run, for example 10 percent

Idempotent upserts in one transaction

PostgreSQL's INSERT ... ON CONFLICT DO UPDATE writes a row or updates the existing one in a single atomic statement. Combine it with a WHERE on the update so unchanged rows are left alone. Because chunk IDs are deterministic, upserting chunks twice gives the same rows.

Wrap one document's work in a transaction: insert the new document version, its sections, chunks and embeddings, then mark older versions superseded. Readers see either the old version or the new one, never a half-written mix. If anything fails, ROLLBACK leaves the previous state in place. Compute embeddings before opening the transaction, so a slow model call does not hold locks.

SequenceOne document update
Ingest job
Embedder
PostgreSQL
  1. 1Embed new chunks (outside transaction)
    Ingest job to Embedder: Embed new chunks (outside transaction)
  2. 2Vectors with model name
    Embedder to Ingest job: Vectors with model name
  3. 3BEGIN
    Ingest job to PostgreSQL: BEGIN
  4. 4Upsert version, sections, chunks, vectors
    Ingest job to PostgreSQL: Upsert version, sections, chunks, vectors
  5. 5Mark old version superseded
    Ingest job to PostgreSQL: Mark old version superseded
  6. 6COMMIT
    Ingest job to PostgreSQL: COMMIT

Failed parses, retries and the last good version

Record every failure in an ingest_errors table with the doc_id, source URI, run ID, error message, attempt count and time. The next run retries those first, with a limit so a permanently broken file does not retry forever. After the limit, the error stays visible on a report for a person to fix.

The key rule is that failure never removes what already works. If version 5 cannot be parsed, version 4 stays active and searchable. Decide and document one exception: if the source was deliberately removed and the file that remains is junk, a person can mark the document deleted by hand.

  • ingest_errors: doc_id, run_id, error, attempts, last_tried
  • Retry with a limit, for example 3 attempts
  • Old version stays active on failure
  • Report unresolved errors after every run

Deletion, tombstones and provenance

To delete a source, set every version's status to deleted in one transaction, delete or deactivate its chunks so they leave retrieval, and record a tombstone with the time, run ID and reason. If your retrieval query joins on status = 'active', deleted chunks vanish at once even before cleanup runs. Physically removing rows and vectors can happen later in a separate job.

Provenance means every chunk can be traced to its doc_id, version, section, source URI and the ingest run that wrote it. Keep an ingest_runs table with start and end times, counts of new, changed, skipped, failed and deleted documents, and the embedding model used. When someone asks why the assistant said something last Tuesday, provenance is how you answer.

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Make upserts idempotent~40m
  2. 2
    Record failed parses and retry~40m
  3. 3
    Supersede stale versions~40m
  4. 4
    Remove deleted sources from results~40m
  5. 5
    Keep provenance for every chunk~40m

Key points

  • Compare content hashes first; unchanged documents should cost nothing to re-run.
  • Write a new version, its chunks and embeddings in one transaction, then flip the old version to superseded.
  • A parse failure must never delete the last good version; record it and keep serving the old one.
  • Deletion means the source is gone: mark it deleted so retrieval excludes it, and keep a tombstone row.
  • Every chunk keeps doc_id, version, source URI and ingest run ID, so any answer can be traced back.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
INSERT INTO documents (doc_id, version, title, source_uri, visibility,
                       effective_from, content_hash, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, 'active')
ON CONFLICT (doc_id, version) DO UPDATE
  SET content_hash = EXCLUDED.content_hash,
      status       = 'active'
  WHERE documents.content_hash IS DISTINCT FROM EXCLUDED.content_hash
     OR documents.status <> 'active';

UPDATE documents SET status = 'superseded'
 WHERE doc_id = $1 AND version < $2 AND status = 'active';

Run inside one transaction with the chunk writes. A second run with the same input changes nothing.

Proving the job is idempotent

Prerequisites: the local database with your three documents ingested. Step 1: run the ingest job and save row counts and a checksum of chunk IDs. Step 2: run it again with no source changes. Expected evidence: the second run reports 0 new, 0 changed, 3 skipped, and the counts and checksum match exactly. Step 3: edit one sentence in KB-0042 and run again. Expect 1 changed, version 2 active, version 1 superseded.

sql
SELECT status, count(*) FROM documents GROUP BY status;

SELECT md5(string_agg(chunk_id, ',' ORDER BY chunk_id)) AS chunk_checksum,
       count(*) AS chunks
FROM chunks WHERE status = 'active';

SELECT run_id, new, changed, skipped, failed, deleted
FROM ingest_runs ORDER BY started_at DESC LIMIT 2;

Removing a deleted source from retrieval

Contoso retires its old fax-support page, KB-0107. Step 1: delete the file from Git. Step 2: the next run sees KB-0107 as missing and checks that the scan succeeded and deletions are under the cap. Step 3: in one transaction it marks all versions deleted, deactivates the chunks and writes a tombstone. Expected evidence: a search for 'fax' no longer returns KB-0107, while the tombstone row shows when and why it left. Rollback: restore the file and re-run.

sql
BEGIN;
UPDATE documents SET status = 'deleted' WHERE doc_id = 'KB-0107';
UPDATE chunks    SET status = 'deleted' WHERE doc_id = 'KB-0107';
INSERT INTO tombstones (doc_id, deleted_at, run_id, reason)
VALUES ('KB-0107', now(), $1, 'source file removed');
COMMIT;

Quick reference

  • Diff by content hash first; unchanged documents cost nothing
  • INSERT ... ON CONFLICT (key) DO UPDATE ... WHERE changed = idempotent upsert
  • Embed outside the transaction; write rows inside it
  • On parse failure, log to ingest_errors and keep the last good version active
  • Never delete when the source scan failed; cap deletions per run
  • Deleted = status change plus tombstone; physical cleanup can come later
  • Every chunk: doc_id, version, section_id, source_uri, run_id

Common mistakes

  • Deleting old chunks before the new ones are written, leaving a window where the document cannot be found.
  • Treating a missing file as deleted when the scan itself failed, which wipes the index after a network blip.
  • Filtering deleted documents in the application only, so a second code path still returns them.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1The ingest job crashes halfway and you run it again. What property makes this safe?

Question 2

2Version 5 of a document fails to parse. What should search return for that document?

Question 3

3A run finds that all 18 documents are missing from the source folder. What is the safest action?

Question 4

4Why compute embeddings before opening the database transaction?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Run your ingest job twice with no changes and record the evidence that the second run did nothing.

  2. Exercise 2medium

    Break the front matter of one file on purpose and show that the job logs the error, keeps the old version searchable and succeeds after you fix it.

  3. Exercise 3hard

    Implement deletion with a safety cap: refuse to delete more than 10 percent of active documents in one run unless --allow-mass-delete is passed, and write tombstones for what is deleted.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

How often should the ingest job run?
As often as your sources change and your users need. A nightly run is common; a webhook or file watcher can trigger it sooner for urgent changes.
Should I hard-delete old versions?
Keep them while past answers may need explaining. Remove them later with a retention job once your audit period has passed.
What is the difference between superseded and deleted?
Superseded means a newer version replaced it; deleted means the source itself is gone. Neither is retrieved, but they mean different things in an audit.

Go deeper

ShareXLinkedInWhatsApp