Short answer: keep an append-only decision record for every retrieval, but store full document evidence only for sampled or disputed searches. That split makes an e-commerce PDF answer system auditable without multiplying index and logging costs as the catalog grows.
I run a small SaaS, so I measure infrastructure in revenue per engineering hour. A marketplace support team may ask, “Which return rule applies to this listing?” The source is often a folder of PDFs: seller agreements, shipping schedules, and category policies. The hard part is not making one plausible answer. It is proving which chunks were eligible, which ones were retrieved, and why the final answer used them six weeks later.
The useful unit is a retrieval decision, not a chat transcript. A transcript tells you what a user typed. An audit record tells you the query representation, index generation, filters, ranked chunk IDs, and policy version that produced the evidence set. Those are different debugging jobs.
How should an e-commerce retrieval architecture record audit logs?
Start with two retention tiers. The first is a compact event for every request. The second is a larger evidence bundle for a small, explicit sample: failed evaluations, customer disputes, and a rotating percentage of normal traffic. This is the same separation I use for application metrics and request traces. Keeping everything forever feels safe until storage and privacy reviews become the product.
An event needs stable identifiers rather than copied PDF text. For example:
type RetrievalAudit = { requestId: string; occurredAt: string; tenantId: string; queryHash: string; indexVersion: string; embedderId: string; filter: { marketplace: string; locale: string }; candidates: Array<{ chunkId: string; rank: number; score: number }>; answerCitations: string[]; policyVersion: string; outcome: "answered" | "abstained" | "escalated"; evidenceRef?: string; }; The hash lets an operator group repeated questions without retaining raw personal text. It is not anonymization by itself: a guessed query can be hashed and compared. Apply access controls and a retention period, and treat the log as sensitive data.
Keep it boring.
The record also makes replays deterministic enough to be useful. Save the index version, chunking policy, embedding model identifier, and filter values. If any of those are missing, a later replay silently tests a different system. The original Retrieval-Augmented Generation paper describes retrieval plus generation as separate stages; logging their boundary keeps evaluation honest.
Ship it.
The smallest working build
For a folder of PDFs, I would begin with one ingestion job and one query path. Ingestion extracts text, keeps page numbers and source checksums, then writes immutable chunks to an index. Querying writes the compact audit event after ranking and before generation. A failed generation must not erase the retrieval record.
type Retriever = (input: { text: string; marketplace: string; locale: string; }) => Promise<Array<{ chunkId: string; score: number; page: number }>>; async function answerQuestion( input: { text: string; marketplace: string; locale: string }, retrieve: Retriever, writeAudit: (event: RetrievalAudit) => Promise<void>, ) { const requestId = crypto.randomUUID(); const started = Date.now(); const hits = await retrieve(input); const event: RetrievalAudit = { requestId, occurredAt: new Date().toISOString(), tenantId: "marketplace-demo", queryHash: await sha256(input.text), indexVersion: "catalog-2026-08-01", embedderId: "embedding-production-1", filter: { marketplace: input.marketplace, locale: input.locale }, candidates: hits.map((hit, rank) => ({ chunkId: hit.chunkId, rank: rank + 1, score: hit.score, })), answerCitations: hits.slice(0, 3).map((hit) => hit.chunkId), policyVersion: "answer-policy-3", outcome: hits.length ? "answered" : "abstained", }; await writeAudit(event); return { requestId, hits, latencyMs: Date.now() - started }; } That snippet intentionally does not put PDF contents in the hot-path event. An evidence writer can fetch the cited pages when outcome is abstained, when a human flags the answer, or when a sampling rule matches. The fetch should use the source checksum recorded at ingestion; otherwise a seller replacing a PDF can change the meaning of an old citation.
One practical trap: ranking scores are not portable across index implementations. OpenSearch, Elasticsearch, and Vespa expose different query and scoring controls, so store rank and the opaque chunk ID as the contract. Treat the score as diagnostic metadata, not as a cross-engine business threshold. Switching engines then requires a replay comparison, not a mass rewrite of audit history.
Here is the failure that forced me to make the checksum a first-class field. A seller uploaded returns.pdf on Monday, then replaced it on Friday without changing the filename. The ingestion job correctly produced a new chunk set, but an analyst searching by filename found the Friday copy and assumed it explained a Monday answer. The audit event still had the old index version, yet the evidence viewer resolved the mutable filename. We changed the viewer to resolve by content checksum and page, and added a test that swaps files under the same name. That is a small amount of metadata and a surprisingly large reduction in arguments about what the system saw.
What should be indexed, retained, and redacted?
Index cost is mostly a function of chunk count, vector dimensions, replicas, and refresh behavior. Audit cost is a separate curve. Mixing the two leads teams to delete useful evidence to save index space, or to retain every token forever because the logger is already running.
| Data | Every request | Sampled or disputed requests | Retention decision |
|---|---|---|---|
| Query hash and filters | Yes | Yes | Short, bounded window |
| Chunk IDs, ranks, scores | Yes | Yes | Longer than raw text |
| PDF page text | No | Yes | Encrypted, shortest useful window |
| Prompt and model output | No | When policy permits | Separate privacy review |
| Source checksum and index version | Yes | Yes | Keep with audit lineage |
Redact before persistence, not during a later export. Seller contracts can contain addresses, rates, or private contact details even when the user question looks harmless. A retention job should delete evidence bundles by policy while leaving aggregate counts and a tombstone that explains the missing payload. Your mileage may vary because legal retention rules differ by marketplace and region; get the data owner to sign off on the exact window.
The failure modes worth replaying
Most audit bugs are selection bugs. A filter may be applied at ingestion but omitted at query time. A PDF can be re-chunked with the same filename. A reranker can reorder evidence after the compact event is written. Each case produces a convincing answer with an incomplete explanation.
Build a replay fixture from a handful of de-identified PDFs. Pin the source checksums, index version, filter, and expected citation IDs. Run it in CI after changing chunk size, embedding configuration, or ranking logic. I would rather catch a one-page policy leak in a pull request than discover it through a merchant escalation.
Keep an explicit abstain path. If no chunk clears the configured relevance policy, the system should say it lacks evidence and send the request to review. A fabricated answer is an audit failure even when its prose sounds polished.
Metrics should answer operational questions: citation coverage, abstention rate, duplicate retrievals, evidence-bundle volume, and index bytes per active listing. Alert on a change from the service's own baseline, not on a universal score copied from another corpus. There is no single threshold that fits shipping policies and electronics specifications alike.
What changes when the catalog reaches millions of chunks?
At scale, keep the compact event on cheap append-only storage and partition it by tenant and day. Put evidence bundles behind a separate access path with encryption and an expiry queue. A pointer from the event to the bundle is enough for an investigator; duplicating text into every log record is not.
The catch is that this design is not suitable when auditors require every generated token and full source text to be retained for years. In that case, choose a regulated archive and budget for its access controls, review process, and slower replay. Stick with a full-fidelity trace when legal defensibility matters more than index cost; use the two-tier scheme when most incidents can be resolved from IDs, versions, and ranks.
I would also change the ingestion boundary. Store a content-addressed PDF object once, then let multiple index versions reference the same checksum. Rebuilding embeddings should create a new index version, never mutate the one named by historical events. That single rule keeps a product manager's “why did this answer change?” question answerable without keeping every intermediate vector.
The payoff is boring and measurable: fewer mystery answers, bounded evidence storage, and a retrieval layer you can replace without losing its paper trail. That is enough to ship weekly while outsourcing the undifferentiated storage mechanics to whichever standards-compliant components fit the workload.