Search Tutorials
--Ads--Data Freshness, Versioning and Audit Trails
Know which version of which document produced every answer.
Three months after launch, a manager asks: "Why did the assistant tell my team on 14 August that the travel limit was 5,000 rupees?" To answer, you need to know which document versions were in the index that day, which chunks were retrieved, what prompt and model were used, and what the model said. This lesson covers the governance side of RAG: keeping data fresh, versioning everything that affects answers, and keeping an audit trail.
Freshness
A stale index produces confidently wrong answers. Treat freshness as a measurable service level:
- Indexing lag: the time between a document changing at the source and the change being searchable. Set a target (for example, under one hour for policies) and monitor it.
- Document age: track
effective_dateorlast_reviewedfor each document and report documents that have not been reviewed for, say, a year. - Expiry: some content has an end date (a promotion, a temporary policy). Store
valid_untiland filter expired chunks out of searches.
from datetime import date
def freshness_filter(today: date | None = None) -> dict:
"""Chroma-style filter that hides expired and archived content.
Range operators compare numbers, so dates are stored as integers like 20261126."""
today_int = int((today or date.today()).strftime("%Y%m%d"))
return {"$and": [{"status": {"$ne": "archived"}},
{"valid_until": {"$gte": today_int}}]} # store 99991231 when there is no end date
def stale_documents(records: list[dict], max_age_days: int = 365) -> list[str]:
today = date.today()
return sorted({r["metadata"]["doc_id"] for r in records
if (today - date.fromisoformat(r["metadata"]["last_reviewed"])).days > max_age_days})
Versioning: everything that can change an answer
An answer depends on more than the documents. Record versions for all of these:
| Component | What to record | Where |
|---|---|---|
| Source document | Document ID, version or content hash, effective date | Chunk metadata |
| Processing | Parser, chunker and embedding model versions, indexing time | Chunk metadata |
| Index | Index version (incremented on every sync) | Configuration, trace |
| Prompt | Prompt template version or hash | Code repository, trace |
| Model | Model ID and settings (effort, max tokens) | Trace |
| Application | Release version | Trace |
import hashlib
def chunk_metadata(doc: dict, chunk_index: int) -> dict:
return {
"doc_id": doc["id"],
"doc_version": doc.get("version") or hashlib.sha256(doc["text"].encode()).hexdigest()[:12],
"effective_date": doc.get("effective_date", ""),
"last_reviewed": doc.get("last_reviewed", ""),
"chunk_index": chunk_index,
"chunker": "recursive-1000-v2",
"embedding_model": "BAAI/bge-small-en-v1.5",
"indexed_at": date.today().isoformat(),
}
Keep previous versions of source documents in storage (an object store with versioning works well). With old versions available, any past answer can be reproduced and explained.
The audit record
For each answer, write an audit record that links the question to everything that produced the answer. Audit records are stricter than debugging traces: they are append-only, access-controlled and kept for a defined retention period.
import json
from datetime import date, datetime, timezone
PROMPT_VERSION = "policy-assistant-v7"
def audit_record(trace_id: str, user_id: str, question: str, hits, response, index_version: str) -> dict:
return {
"trace_id": trace_id,
"timestamp": datetime.now(timezone.utc).isoformat(),
"user_id": user_id, # pseudonymised ID, not a name
"question": question, # redact PII before storing
"index_version": index_version,
"prompt_version": PROMPT_VERSION,
"model": response.model,
"sources": [{"chunk_id": h.id,
"doc_id": h.metadata["doc_id"],
"doc_version": h.metadata["doc_version"],
"score": round(h.score, 4)} for h in hits],
"answer": "".join(b.text for b in response.content if b.type == "text"),
"stop_reason": response.stop_reason,
}
def write_audit(record: dict, path: str = "audit.jsonl") -> None:
with open(path, "a", encoding="utf-8") as f: # production: append-only, access-controlled storage
f.write(json.dumps(record) + "\n")
Now the manager's question has an answer: look up the records from 14 August, see that the cited chunk came from version 2.1 of the travel policy, effective before the April update, and see that the index sync had failed for three days. The fix (alerting on sync failures) follows directly.
Governance practices
- Document owners: every indexed source has a named owner responsible for accuracy and review dates.
- Change review: prompt and model changes go through the regression tests (A/B and Regression Testing) and are recorded with their release.
- Disclosure: tell users they are reading AI-generated answers, show sources and dates, and provide a route to a human.
- Retention and access: define how long audit records are kept and who may read them, in line with your legal and privacy obligations.
Key takeaways
- Measure freshness with indexing lag and document age, and filter expired or archived content.
- Version documents, processing, index, prompt, model and application, and keep old document versions.
- Write an append-only audit record per answer linking question, sources, versions and answer.
- Assign document owners, review changes through tests, and disclose sources and dates to users.