跳到正文
DEV Community· KendrickBerg5327·· 7 小時前AI 評分68

RAG 答案過時:更新文件後如何排查重新索引失敗

Stale RAG Answers: Debugging Reindex Failures After Updating Docs

AI 導讀

KendrickBerg5327提出以版本化交付管線排查文件更新後 RAG 答案仍過時的問題,逐段核對修訂版本以定位失效邊界。方法是讓同一修訂版本貫穿頁面擷取、佇列工作、索引提交、檢索結果和答案引用,並以可重複執行的方式只重新索引受影響文件。驗證時先確認檢索結果包含預期文件及修訂版本,並在檢查通過前保留上一個索引版本。

正文

When RAG answers stay stale after updating docs, debug the reindex as a versioned delivery pipeline: attach one revision ID to the page fetch, running queue job, index commit, retrieval result, and answer citation. If a property-management wiki assistant still quotes an old leasing-policy page, find the first stage whose recorded revision falls behind. Do not start by tuning prompts or rebuilding the entire corpus.

TL;DR: prove that the watcher observed the changed page, the queue accepted one durable job, workers committed the new chunks, and queries can see that commit. A newer source revision paired with an older retrieved revision localizes the fault quickly. Reindex only the affected document, make that operation idempotent, and keep the prior revision available until verification passes.

Why are RAG answers stale after updating docs?

A RAG answer depends on retrieved external memory, not just model behavior. The original RAG paper describes generation conditioned on retrieved passages; if retrieval returns an old passage, a fluent answer can faithfully repeat stale material. Freshness is a data-delivery property.

For a property manager, the symptom might be an assistant citing yesterday's pet policy after the public policy page changed this morning. Several failures look identical from the chat box: the watcher missed the change, normalization erased the meaningful diff, a queue job was lost, an older job overwrote a newer one, the index commit was not visible, or a cache served an earlier retrieval result. The answer alone cannot distinguish them.

I use the same reflex that applies to scheduled work: a trigger is not evidence of completion. A watcher log saying changed=true proves observation, not indexing. An acknowledged queue message proves acceptance under the queue's contract, not that a searchable commit exists.

This is why a blind full rebuild is a poor first response. It may restore freshness, but it destroys evidence and spends indexing capacity on unchanged leases, notices, and building pages. At portfolio scale, that cost becomes the operational constraint.

Start there.

Carry one revision across every boundary

Derive a stable source revision from the content that should affect retrieval. Normalize intentionally: remove volatile page furniture such as a generated timestamp, but retain policy text and headings. Hash the normalized bytes, then carry that hash through every event and stored record. The URL identifies the document; the revision identifies its state.

The worker below shows the important properties without depending on a particular queue or index. It rejects an obsolete delivery, skips an already committed revision, and swaps the document's chunks as one logical commit.

package indexing

import (
    "context"
    "errors"
)

type Job struct {
    DocumentID string
    Revision   string
    Body       []byte
}

type Chunk struct {
    DocumentID string
    Revision   string
    Position   int
    Text       string
    Vector     []float32
}

type Index interface {
    CurrentRevision(context.Context, string) (string, error)
    ReplaceDocument(context.Context, string, string, []Chunk) error
}

type RevisionOrder interface {
    Older(candidate, current string) bool
}

type Embedder interface {
    Chunks(context.Context, Job) ([]Chunk, error)
}

func Apply(ctx context.Context, idx Index, order RevisionOrder, emb Embedder, job Job) error {
    current, err := idx.CurrentRevision(ctx, job.DocumentID)
    if err != nil {
        return err
    }
    if current == job.Revision {
        return nil // Redelivery is already complete.
    }
    if current != "" && order.Older(job.Revision, current) {
        return nil // A delayed job must not roll the index backward.
    }

    chunks, err := emb.Chunks(ctx, job)
    if err != nil {
        return err
    }
    if len(chunks) == 0 {
        return errors.New("refusing to replace a document with no chunks")
    }
    return idx.ReplaceDocument(ctx, job.DocumentID, job.Revision, chunks)
}

A content hash cannot order two different revisions, so the job also needs an ordering value from the source system, such as a monotonically increasing version. Keep the hash for equality and integrity. Do not use wall-clock arrival time as truth: retries and concurrent workers can arrive out of order.

Replacement matters. Appending new chunks while leaving old ones searchable lets both revisions compete. Deleting first creates a window with no document. A staged write followed by an atomic generation switch is cleaner: build the new generation, validate it, expose it, then retire the previous one.

This design has a real limitation: keeping two generations consumes extra storage, while atomic switching requires index support or an indirection layer. For a tiny wiki with rare edits, a synchronous fetch-and-replace path may be easier to operate. For a large property portfolio, the extra storage is usually a better trade-off than paying the compute cost and recovery delay of full-corpus reindexing. The threshold depends on measured update volume, chunk count, and acceptable freshness lag; no universal document count settles it.

Trace the failure before replaying work

Start with one known page and a sentence whose change is unambiguous. Record its document ID, expected source revision, and a query that should retrieve the changed passage. Then walk the evidence in order.

One page. One revision. One probe.

  1. Fetch the page and compute the normalized revision. Confirm the changed sentence survived normalization.
  2. Find the watcher observation for that revision, including its prior revision and enqueue decision.
  3. Find the durable job by document ID and revision. Check attempts, acknowledgements, and dead-letter state.
  4. Find the worker commit. Compare requested revision, committed revision, chunk count, and generation.
  5. Query retrieval with answer generation disabled. Inspect returned document IDs and revisions.
  6. Only after retrieval is current, inspect answer caches and prompt assembly.

Stop at the first mismatch. If the source hash is new but no event exists, inspect scheduling and watcher checkpoints. If the event exists but no job does, the enqueue boundary failed. If a worker reports success but the committed revision is absent, the write acknowledgement is too weak. If direct retrieval is fresh and chat is stale, indexing is innocent; inspect cache keys and conversation state.

This sequence is deliberately narrow. Replaying one idempotent job preserves the failure signal and limits load. Rebuilding everything can saturate embedding workers, deepen the queue, and delay genuinely new policy changes.

Queue depth alone is a trap. A depth of zero can mean all work completed, but it can also mean jobs were never published, were dead-lettered, or were acknowledged before commit. Track age of the oldest pending job, lag from source observation to searchable commit, and counts by terminal outcome. Alert on sustained freshness lag against an explicit objective, not one transient backlog.

During debugging, resist changing chunk size, embedding configuration, and queue behavior together. A successful reindex with three moving inputs does not reveal which input repaired stale answers, and it makes rollback ambiguous. Hold retrieval configuration fixed, replay the one expected revision, and widen the investigation only when its boundary evidence is internally consistent. This slower-looking method usually reduces total recovery work because each observation can falsify a specific failure hypothesis.

Verify the repair and keep rollback boring

Verification should test the contract, not merely the worker process. After replaying the affected revision, issue a retrieval-only query and require the expected document ID and revision in the result metadata. Then run the full assistant query and confirm its citation points to the current page. Test a second query for unchanged text on that page; a bad chunk replacement can fix the edited sentence while dropping neighboring material.

Keep the previous index generation until those checks pass. If retrieval quality falls, switch the document pointer back and preserve both generations for analysis. Rollback should not require re-fetching a page that may have changed again.

The deployment check is small but consequential: send duplicate jobs, reverse their delivery order, interrupt a worker before commit, and interrupt it after commit but before acknowledgement. The expected result is one visible latest revision in every case. This is where idempotency earns its keep.

For operations, expose four linked measurements: source observations, queued revisions, committed revisions, and revisions returned by retrieval. Logs need the document ID and revision as structured fields. Metrics show fleet-level lag; correlated records explain one page. Avoid putting page bodies into telemetry because property documentation can contain tenant or operational details.

The decision rule is simple: repair the earliest broken boundary, replay the smallest idempotent unit, and declare recovery only when retrieval returns the intended revision. This keeps index cost proportional to changed documents while giving the on-call engineer evidence stronger than "the reindex ran."

References

來源:DEV Community · dev.to