InterviewsVector
Arc 7
Design reviewAdvanced105 min estimateOriginal publication

Retrieval Security, Deletion, and Freshness

Retrieval is an authorization and data-lifecycle boundary before it is a relevance feature. A plausible citation is still unsafe when the caller lacks access, the source was deleted, or the content is adversarial.

Authorship
InterviewsVector
Published / updated
2026-09-20 / 2026-09-20
Review status
Artifact tests passing · primary sources recorded

Original InterviewsVector material. Executable illustrative contracts have focused tests and recorded primary sources. No named human reviewer, benchmark result, or security certification is claimed.

The decision in one pass

A retrieval pipeline must carry authorization, lifecycle, provenance, and freshness metadata from source through every derived chunk, embedding, index, cache, rank, and context. Bind each request to an authenticated tenant, principal, groups, purpose, query, and policy revision; enforce the same ACL at candidate generation and again before context disclosure; fail closed on unknown state. Propagate source updates and tombstones to every replica with measurable watermarks and deletion service levels. Treat retrieved content as untrusted data that grants no instruction or tool authority, even when its provenance is known. A local audit can validate declarations and deterministic policy order, but it cannot authenticate identities, prove deletion, detect every injection, or certify security.

Why this matters

RAG can turn a ranking bug into a data disclosure, preserve a document after its source deletion, or amplify attacker-controlled text through trusted model output. Relevance metrics rarely expose these failures. Explicit request, chunk, policy, and watermark identities let a team block unsafe evidence, investigate the first breached boundary, and prove what a rollback or purge must cover.

You will be able to

  • Model retrieval as an authorization and lifecycle decision over resources, not only a similarity search.
  • Carry tenant, principal/group ACL, deletion, source revision, provenance, and freshness state through derived indexes.
  • Separate authenticated identity and policy enforcement from model reasoning.
  • Treat retrieved documents as untrusted data without instruction or tool authority.
  • Define freshness and deletion watermarks with observable lag and fail-closed behavior.
  • Bound what a content-bound local audit can and cannot establish about production security.

Your Vector Loop for this lab

  1. 01

    Model

    Trace subject identity, source ACLs, ingestion, chunks, embeddings, indexes, caches, ranking, prompt context, citations, deletion, and audit logs as one data-flow boundary.

  2. 02

    Derive

    Derive access predicates and freshness/deletion invariants independently of relevance scores; state which timestamp and revision each comparison uses.

  3. 03

    Build

    Capture immutable request and candidate declarations, fail the whole result on the first crossed boundary, and expose only review-eligible chunk identities.

  4. 04

    Stress

    Inject cross-tenant hits, remove group membership, leave tombstones indexed, forge provenance, age watermarks, and place adversarial instructions in retrieved data.

  5. 05

    Operate

    Observe authorization denials, stale/tombstoned hit rates, replication lag, purge completion, provenance gaps, injection tests, and downstream tool attempts.

  6. 06

    Defend

    Defend local policy evidence as a narrow review gate while requiring real identity, storage, incident-response, and adversarial-security controls.

Authorize the resource, not the generated prose

A vector match does not grant permission. The subject making the request, the tenant and resource identities, device or session posture where applicable, policy revision, and current resource ACL must be resolved by trusted application code. The model must not infer that an employee may read a document, and a generated answer must not launder inaccessible content into an apparently ordinary summary.

eligible(c, u, t) = tenant(c)=tenant(u) ∧ [u∈principals(c) ∨ groups(u)∩groups(c)≠∅] ∧ active(c,t)

This teaching predicate combines tenant isolation, principal-or-group authorization, and active lifecycle state. Real policies may add purpose, device, region, classification, legal hold, and relationship constraints.

Make lifecycle state propagate to every derivative

Source eventDerived obligationEvidence to retain
content updatere-chunk and re-embed affected revisionsource and index watermarks, replaced content IDs
ACL changeinvalidate or reauthorize cached/indexed candidatespolicy revision and enforcement timestamp
deletion/tombstoneremove or block chunks, vectors, caches, and excerptstombstone ID, purge status, replica acknowledgments
restore or legal holdapply a separately authorized lifecycle transitionowner, reason, source revision, and audit event

Freshness is not one timestamp. Source-updated time tells when authoritative content changed; indexed time tells when a derived representation was built; request time sets the decision point. The artifact checks that the index is not older than its source revision, that ingestion lag stays within a declared limit, and that the indexed record is not too old at request time. Production systems also need a monotonic source/change sequence so clock skew cannot conceal a gap.

Deletion is a distributed workflow, not a boolean on one row. Search replicas, vector stores, reranker caches, prompt caches, observability payloads, evaluation corpora, and backups may have separate retention and purge semantics. Define which stores are in the serving path, how tombstones block reads while physical deletion completes, the service-level objective, and who can verify or escalate a missed purge.

Known provenance does not make instructions trusted

Provenance should identify the source system, object, revision, ingestion event, transformations, and content digest. This supports replay, citation, revocation, and incident scope. It does not make every claim in the source true, prove that upstream authentication was uncompromised, or neutralize adversarial text.

Indirect prompt injection exploits the fact that an LLM can interpret retrieved data as instructions. Mark external content as untrusted, frame it separately, minimize available privileges, validate model outputs in code, and require user or policy approval for consequential actions. Never let a document grant itself tool permission. These controls reduce impact; they do not make prompt injection impossible.

  • Rank relevance and source trust separately. High similarity is not authority or truth.
  • Preserve citation identity through the final answer, but do not treat a citation as sanitization.
  • Restrict retrieval ingestion rights and monitor unusual additions, duplicates, targeted query matches, and source-revision churn.
  • Test poisoning and injection with realistic permissions and tools; a text-only sandbox misses the impact of excessive agency.

Fail closed in an explainable order

The teaching audit checks tenant, principal-or-group access, deletion, provenance, content/tool authority, then freshness for each ranked candidate. A malformed schema, stale digest, invalid timestamp, duplicate candidate, or mismatched request raises an exception before any policy report. A well-formed boundary failure blocks the entire result and returns no eligible chunk IDs; silently dropping one cross-tenant hit would hide an upstream enforcement defect.

Predict the first retrieval boundary

Inspect request identity, candidate ACLs, deletion state, provenance, content authority, and watermarks. Predict the first fail-closed reason and safe action before revealing the audit decision.

Find the first failed retrieval boundary

Read one original synthetic trace in execution order. Later symptoms may also violate contracts; identify the earliest boundary where the record stops satisfying its declared requirement.

Recorded retrieval trace

The table exposes contract evidence without a graded state. These are diagnostic replay records, not live tenant data or production measurements.

Boundary evidence, earliest to latest
BoundaryContractObserved
1. Corpus admissionOnly current, approved document revisions are searchableDeletion watermark trails the corpus ledger by one committed revision
2. Index projectionEmbed every chunk with index model emb-v4 and normalize onceIndex manifest records emb-v4, width 768, normalized vectors
3. Query projectionEmbed the query with the same model and preprocessing contractQuery uses emb-v4, width 768, normalized vector
4. Policy filteringApply authenticated tenant and document ACL before rankingResolved principal t-17; filter requires tenant t-17 and read access
5. Candidate searchReturn answer-bearing candidates within the measured recall boundTop 20 contains the document revision marked deleted
6. RerankingRerank only the supplied candidates with feature revision rr-6Feature and model manifests both resolve to rr-6
7. Context assemblyAssemble cited, deduplicated spans within the token budgetContext cites the deleted revision
Which boundary fails first?

Select a prediction, then check it against the recorded evidence.

Deterministic ordering makes replays and incident comparisons stable, but it does not imply later failures are harmless. After containing the first breach, continue the investigation across every relevant boundary and derived store.

Run the local governance audit

retrieval_governance_audit.py
1def audit_retrieval(
2 contract: GovernanceContract,
3 request: RetrievalRequest,
4 evidence: RetrievalEvidence,
5) -> GovernanceReport:
6 """Fail the whole candidate set when retrieval crosses a declared boundary."""
7 contract = validate_record(contract, GovernanceContract)
8 request = validate_record(request, RetrievalRequest)
9 evidence = validate_record(evidence, RetrievalEvidence)

Expected output

example=illustrative_only
status=ELIGIBLE_FOR_CONTEXT_REVIEW
first_failure=none;action=review
eligible=chunk-a,chunk-b
claim=LOCAL_AUDIT_NOT_SECURITY_CERTIFICATION

Verify: python3 -m unittest discover courses/ai-engineering/reference-impl/retrieval_governance

The fixture contains one principal-authorized chunk and one group-authorized chunk inside a single tenant. All content, request, candidate, policy, source, and timestamp declarations are sealed. Focused tests cover cross-tenant retrieval, denied access, tombstones, unknown provenance, instruction/tool authority, stale indexes, future timestamps, request mismatch, duplicates, rank gaps, string subclasses, numeric type attacks, and recursive constructor bypass.

Operate with revocation and incident scope

  1. 01ContainDisable the affected index, tenant, source, tool, or release path; revoke credentials and block suspect content IDs without waiting for perfect root cause.
  2. 02ScopeTrace source revisions through chunks, embeddings, replicas, caches, prompts, outputs, and tool calls. Preserve minimal authenticated evidence.
  3. 03Purge and rebuildApply tombstones and ACL fixes, verify every serving replica and cache, then rebuild from an authoritative revision rather than editing one index in place.
  4. 04RequalifyReplay authorization, freshness, poisoning, injection, and answer-grounding tests under exact repaired revisions before restoring traffic.

Operational dashboards should distinguish policy denials from malformed evidence, index lag from source lag, requested deletion from verified purge, and suspicious content from confirmed compromise. A reduction in retrieved results can be a healthy security response or a broken ingestion pipeline; keep denominators and cohort identities so the signal remains interpretable.

Operate at three altitudes

Production lens

  • — Enforce tenant and resource authorization in trusted code at retrieval and again before context disclosure; never delegate access decisions to the model.
  • — Track source, index, ACL, tombstone, replica, and cache watermarks with explicit lag and purge service levels.
  • — Treat retrieved bytes as untrusted data, minimize tool privileges, validate outputs, and rehearse poisoning/injection incidents with real authority boundaries.

Staff lens

  • — Define shared ownership across identity, source systems, ingestion, search, model serving, security response, privacy, and data lifecycle; gaps between those teams become leakage paths.
  • — Require a threat model, deletion inventory, provenance contract, revocation procedure, and auditable exception process before expanding retrieval to higher-sensitivity sources.

Interview defense

A RAG assistant cites a relevant internal document, but the requesting user should not have access and the source was deleted yesterday. How do you respond and redesign the system?

I would treat this as a data-access incident: contain the serving path, preserve authenticated request/index evidence, revoke and purge the document across chunks, vectors, caches, prompts, and replicas, and assess exposure. The redesign binds authenticated tenant/principal/groups and current ACL/lifecycle revisions to every request and chunk, filters before retrieval and rechecks before context, propagates tombstones with measurable watermarks, and fails closed on unknown state. Retrieved content remains untrusted and cannot grant tool authority. Relevance or a citation does not override authorization or deletion.

Expect the interviewer to press on

  • — Why is post-filtering alone insufficient?
  • — How do you prove a deletion reached every serving path?
  • — What does provenance fail to prove about prompt injection?

Misconceptions to remove

“If a document is in the vector index, the model may use it.”

Index membership is not authorization. A trusted policy decision must bind the current subject and resource state before disclosure.

“Deleting the source row removes it from RAG.”

Chunks, embeddings, search replicas, caches, prompts, logs, and backups can persist. Deletion needs end-to-end tombstone and purge evidence.

“Verified provenance makes retrieved instructions safe.”

Provenance identifies origin and revision; trusted or compromised sources can still contain misleading or adversarial instructions. Retrieved content receives no authority by itself.

Check your model

1. Why does the audit block the whole result after one cross-tenant candidate instead of returning the other authorized chunks?

The candidate already demonstrates an upstream authorization-boundary failure. Silently filtering it would hide a potential identity, score, timing, log, or cache leak.

2. Which timestamps are needed for the artifact's freshness decision?

The authoritative source-updated time, derived index time, and request time, all under a bound freshness policy. Production systems should also use ordered change/watermark identities.

3. What does marking a chunk untrusted-data accomplish?

It declares that the chunk cannot grant instruction or tool authority. Real isolation, least privilege, output validation, approval, and adversarial testing must enforce that boundary.

Prove the mechanism

Add a monotonic source change sequence and per-replica watermark. Create fixtures for clock skew, an out-of-order tombstone, and a replica that reports a recent timestamp while missing one change; fail closed without trusting wall-clock freshness alone.

Add a production constraint

Design an end-to-end deletion and prompt-injection incident exercise spanning source, ingestion, vector replicas, caches, prompts, outputs, and tools. Specify containment authority, authenticated evidence, purge proof, requalification tests, and residual limits.

Artifact: Retrieval governance audit

courses/ai-engineering/reference-impl/retrieval_governance/retrieval_governance_audit.py

Download reference implementation

Primary references and next links

References

  1. 1. NIST SP 800-207: Zero Trust Architecture

    NIST. Official guidance for explicit subject/resource authorization without implicit trust based on network location.

  2. 2. LLM01:2025 Prompt Injection

    OWASP GenAI Security Project. Official guidance on indirect prompt injection, least privilege, content segregation, output validation, and human approval.

  3. 3. Not What You've Signed Up For: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection

    Greshake et al.. Primary demonstration of adversarial instructions delivered through external data used by LLM-integrated applications.

  4. 4. PoisonedRAG: Knowledge Corruption Attacks to Retrieval-Augmented Generation of Large Language Models

    Zou et al.. Primary study of poisoning the retrieval knowledge base; reported attacks do not define a universal production rate.

Continue through the graph

Glossary: tenant isolation · resource authorization · tombstone · freshness watermark · provenance · indirect prompt injection · knowledge poisoning · least privilege