Validate RAG document withdrawal on DGX Spark with revision fences

Validate RAG document withdrawal on DGX Spark with revision fences

Validate RAG document withdrawal on DGX Spark with revision fences

An internal operating procedure has been withdrawn from the knowledge base, and its entries have been deleted from the vector index. Yet an answer cached a few minutes earlier still returns the original content. Another request has already sent an old chunk to the model; generation may continue even though retrieval no longer returns the document. Validating document withdrawal in RAG means checking the entire data path, not just confirming that the deletion API reported success.

This article uses a RAG prototype on DGX Spark to build withdrawal tests with the Python standard library and SQLite. The example does not load a model: it tests the control logic that runs before retrieved results enter the context. Once a model is connected, additional tests must cover in-flight requests.

1. Keep document state independent of the index

DGX Spark provides NVIDIA DGX OS and uses the ARM64 architecture. The following experiment does not depend on GPU libraries, so it can run in an existing Python environment before being connected to a real retrieval service. Its 128 GB LPDDR5x unified memory and 4 TB NVMe provide runtime resources; they do not replace application-level data lifecycle controls.

Each document needs a stable doc_id, a monotonically increasing revision, and an active flag. In addition to its text, every chunk must carry the document ID, chunk ID, and source revision. The vector index is derived data. An authoritative ledger determines whether content may be used.

When withdrawing a document, commit the ledger update first, then clean up vectors, source text, and caches asynchronously. Reversing that order leaves a window in which content can still be retrieved before index deletion finishes. If the ledger cannot be read, reject the affected evidence rather than treating the error as confirmation that the document is valid.

Withdrawal means content is no longer permitted in new answers. It does not mean every copy has already been physically deleted. Record these two acceptance criteria separately; they must not share a single success flag.

Identifiers also need to include the knowledge-base or tenant boundary to prevent documents with the same name in different collections from being mixed up. This example uses only one collection; a production implementation should use composite keys.

2. Run a minimal revision-fence test

Save the code as withdrawal_check.py and run python3 withdrawal_check.py as a regular user. The script uses a temporary database and does not touch existing indexes. A failed assertion causes a nonzero exit status, making the script suitable for a test pipeline.

import sqlite3
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as work:
    db = sqlite3.connect(Path(work) / "ledger.sqlite")
    db.executescript("""
        CREATE TABLE documents (
            doc_id TEXT PRIMARY KEY,
            revision INTEGER NOT NULL,
            active INTEGER NOT NULL CHECK(active IN (0, 1))
        );
        CREATE TABLE catalog (
            singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
            epoch INTEGER NOT NULL
        );
        INSERT INTO catalog VALUES (1, 1);
        INSERT INTO documents VALUES ('handbook-a', 1, 1);
    """)

    def epoch():
        return db.execute(
            "SELECT epoch FROM catalog WHERE singleton = 1"
        ).fetchone()[0]

    def permitted(evidence):
        row = db.execute(
            "SELECT revision, active FROM documents WHERE doc_id = ?",
            (evidence["doc_id"],)
        ).fetchone()
        return row is not None and row == (evidence["revision"], 1)

    def withdraw(doc_id):
        with db:
            changed = db.execute(
                "UPDATE documents SET active = 0, revision = revision + 1 "
                "WHERE doc_id = ? AND active = 1",
                (doc_id,)
            ).rowcount
            if changed:
                db.execute(
                    "UPDATE catalog SET epoch = epoch + 1 WHERE singleton = 1"
                )

    old = {"doc_id": "handbook-a", "revision": 1, "chunk_id": "part-1"}
    cache = {}
    old_key = ("kb-a", epoch(), "question-a")
    cache[old_key] = {"answer": "old answer", "sources": [old]}

    assert permitted(old)
    withdraw("handbook-a")
    assert not permitted(old)
    assert ("kb-a", epoch(), "question-a") not in cache
    assert not all(permitted(s) for s in cache[old_key]["sources"])

    withdraw("handbook-a")
    assert epoch() == 2

    with db:
        db.execute(
            "UPDATE documents SET active = 1, revision = revision + 1 "
            "WHERE doc_id = ?",
            ("handbook-a",)
        )
        db.execute("UPDATE catalog SET epoch = epoch + 1 WHERE singleton = 1")

    current = dict(old, revision=3)
    assert permitted(current)
    assert not permitted(old)
    assert not permitted({"doc_id": "unknown", "revision": 1})
    db.close()

This verifies four boundaries: stale chunks are rejected, the cache namespace changes, repeated withdrawal does not advance state again, and republication cannot reuse an old revision. The last point is particularly important: otherwise, chunks left in an old index could become permitted again when the active flag is restored.

The script does not simulate cross-process consistency. In a real service, all worker processes must access the same authoritative state rather than each maintaining an in-memory list of valid documents.

3. Check both retrieval results and cache hits

At a minimum, check revisions before candidate chunks enter the model context. Retrieve candidates, query the ledger in a batch, then discard chunks whose documents have been withdrawn or whose revisions do not match. A one-time check when writing vectors is not enough.

Filtering may leave fewer candidates than requested. You can retrieve more candidates and filter again, but set a limit on how many are scanned. If all candidates are invalid, report insufficient evidence; do not restore rejected chunks just to fill the context. This test concerns permission to use content, not retrieval distance or ranking quality.

Caches must retain source provenance

The example includes the collection generation, epoch, in the cache key so that new requests after withdrawal no longer hit old answers. This is a simple collection-wide invalidation scheme: it is easy to implement, but any document update reduces the cache hit rate.

Whether invalidation uses generations or per-document cleanup, the answer cache must retain the complete set of sources, including document revisions. On a cache hit, revalidate the sources. If any source is invalid, discard the entire answer and generate it again. Removing citation footnotes alone does not establish that the answer body is free of old information.

Cache keys should also include identifiers for the access scope, model configuration, and retrieval configuration. A generation change only determines which cache namespace new requests use. It does not automatically delete old cache entries, so cleanup still needs to be scheduled separately.

4. Use concurrency tests to expose the post-check window

Prepare a request that retrieves a valid chunk and then pauses at a controllable barrier. Use another connection to withdraw the document and commit the change, then release the first request. The expected outcome is that revalidation before sending data to the model rejects the stale chunk instead of allowing generation to continue.

Next, move the barrier to a point after revalidation but before the request is sent to the model. This reveals that adding another query still does not eliminate every race condition. A correct database check does not make the subsequent network send atomic with the withdrawal transaction.

For a basic prototype, the contract can be: requests that start after the withdrawal commits must not use old content, while in-flight requests are handled through cancellation. For content that requires a strict cutover, pause the relevant request entry points, cancel or drain generation tasks holding old chunks, then update the state, clear caches, and resume those entry points.

Streaming output needs its own acceptance tests. Text already sent cannot be taken back, and stopping subsequent output does not erase earlier responses. If the business requires historical conversations to become inaccessible after withdrawal as well, conversation storage must be included in scope; changing only the inference endpoint is not enough.

5. Retain test evidence and check derived copies

A complete acceptance test must cover six input cases: valid documents, withdrawn documents, unknown IDs, revision mismatches, repeated withdrawal, and republication. Record the expected outcome and actual result for each case. Add a failure test with the ledger unavailable to confirm that the system does not fall back to an unchecked path.

Audit records need only contain the request ID, document ID, revision, collection generation, and rejection reason. Avoid writing sensitive source text into debug logs, or the withdrawal process itself will create another copy that needs to be handled.

Finally, check the processing status of the source-text directory, chunk storage, vector index, answer cache, and conversation history. Data on DGX Spark is deleted when the service term expires, so export experimental results and any acceptance records that must be retained beforehand. Expiration rules are not a substitute for an application-level withdrawal mechanism during operation.

The acceptance report should clearly distinguish between “stale evidence blocked,” “in-flight requests handled,” and “derived copies cleaned up.” Only with explicit boundaries does withdrawal become a repeatable engineering process rather than an unexplained deletion request.

Frequently asked questions

Is deleting a document from the vector index enough?

No. Retrieved evidence, cached answers, and active generation requests may still contain it. Record withdrawal and increment the authoritative revision first, validate evidence against that ledger, then remove derived copies.

Does a final check before sending guarantee no stale output?

No. A race remains between checking and sending, and streamed content cannot be recalled. A strict cutover requires pausing affected requests, cancelling or draining active generation, updating withdrawal state, and invalidating caches before reopening access.

Dedicated AMD EPYC 7543P server from $467/month

Choose a dedicated server configuration to match the workload

Check memory and storage first, then choose the operating system and access method.