On this page
A developer asks an internal search engine: "Which parser-v2 migration window applies to service accounts?" Four documents sit in the corpus. The current migration standard requires starting within 30 days. A separate exception allows 60 days for service accounts, only with security approval. An obsolete revision says 90 days, and a private roadmap in another workspace shares almost the exact same keywords. A fluent answer built from either wrong document is worse than returning no answer at all.
Traditional search hands back ten links and lets the reader judge freshness and caveats. An LLM-powered search engine synthesizes a direct statement that users act on, so the architecture must enforce document identity, freshness, access rights, and claim verification across every hop from ingestion to streaming tokens.
In the multi-tenant serving lesson, we kept one workspace from reading another's model state. Here we trace those controls through embeddings, chunking, reranking, context packing, citation checks, and streaming.
Decide what counts as an answer
For CodeAtlas, a complete answer must include both the general 30-day rule and the conditional 60-day exception. Saying "service accounts get 60 days" drops the approval qualifier. Citing only the 30-day rule omits the exception that answers the developer's actual question. Pulling text from another workspace's private roadmap leaks confidential data even if the number happens to be right.
Retrieval-augmented generation conditions an LLM on retrieved passages.[1] Around that core mechanism, the search system enforces three explicit answer rules:
- Use only current, authorized sources and preserve qualifying clauses such as "only with security approval."
- When two current sources disagree without an explicit supersession link, surface the conflict rather than letting the model invent precedence.
- When required evidence is missing or stale, return an incomplete-answer notice or authorized source links instead of guessing.
Size the architecture around this target envelope:
| Dimension | Design target | Pre-deployment check |
|---|---|---|
| Access control | Zero unauthorized text, titles, citations, or cached replies leave retrieval | Cross-tenant and live revocation tests |
| Freshness | Serve only the active published revision with its effective date | Ingest lag, deletion, and supersession checks |
| Latency | Track progress, first draft token, first checked claim, and completion separately | End-to-end traces and tail percentiles |
| Coverage | Include both the base rule and its applicable conditional exception | Held-out queries with required passage and claim labels |
| Peak load | 1,000 requests/s peak; 60% require LLM synthesis | Measured route mix, stage times, and GPU throughput |
A progress spinner at 100 ms reassures the user that work has started, and a draft token at 800 ms can arrive before verification completes. Both clocks matter only once every passage in the index carries an exact revision, byte span, and reader list.
Make evidence identifiable before it becomes searchable
Ingestion fetches source revisions, parses them into chunks, and updates lexical and vector indexes. Every chunk needs an immutable (doc_id, revision) key, tenant ID, source URL, character offsets tied to a specific text-normalization version, SHA-256 content digest, effective timestamp, and access metadata.
Updating or deleting a document cannot wait for an overnight re-embedding job. Maintain a lightweight current-revision registry alongside the indexes so the query path rejects superseded, unpublished, or revoked chunks immediately while vector indexes catch up asynchronously.
![Architecture of an LLM-powered search engine flowing left to right: offline ingestion hashes policy@2 [0-80] and exception@1 [0-101] with SHA-256 digests into BM25 lexical and dense HNSW indexes scoped to workspace-a, followed by RRF fusion, reranking, grounded synthesis, and an online verification gate checking RBAC, current revision, and exact spans before streaming verified citations. A current-revision registry feeds invalidation updates directly into both retrieval and the verification gate.](https://assets.leetllm.com/v1/66660a12774a/system-design/design-llm-powered-search-engine/illustrations/_generated/llm_search_dark.png)
Authorization belongs to the service, not the query planner
Derive tenant and group membership exclusively from authenticated server-side credentials. Apply that scope to every retrieval call, speculative rewrite, parent-chunk fetch, external reranker, citation preview, log line, and cache lookup.
Filter candidates inside the index query before top- truncation. Vector engines like Qdrant support filtered search directly and recommend payload indexes on access-control fields.[2] Post-filtering a global top- list wastes candidate slots on forbidden or stale hits, potentially leaving zero usable passages.
Even when forbidden hits are hidden, shared corpus statistics such as global IDF weights can leak subtle score or timing signals. Elasticsearch explicitly notes that document-level security does not alter global relevance statistics.[3] When strict statistical noninterference is required, place tenants in isolated indexes.
Freshness isn't a timestamp boost
Re-crawling an obsolete document gives it a brand-new crawl timestamp without making it current. Store source publication time, effective date, crawl time, and index publication time as separate fields, and rely on explicit revision supersession rather than exponential time decay. Hot and warm index tiers shorten ingestion lag for fast-changing release notes, while live mutable state (like whether a CI build is running right now) belongs behind an authorized live API rather than a search index.
Route the question without weakening its constraints
"Which parser-v2 migration window applies to service accounts?" belongs on hybrid document search. "Is build-1042 running now?" belongs on a live job-status API. A combined question needs both branches concurrently.
Query expansion techniques like Hypothetical Document Embeddings (HyDE) generate a synthetic passage whose embedding can boost recall.[4] Keep generated expansions strictly inside retrieval: never cite a synthetic HyDE passage as source evidence, and never let query rewriting drop identifiers, dates, or negations.
The compact router below keeps freshness independent of route selection, so asking for the "latest" rule or combining a live build check with a migration question preserves both constraints:
from dataclasses import dataclass
@dataclass(frozen=True)
class Plan:
routes: tuple[str, ...]
requires_current_revision: bool
def plan_query(query: str) -> Plan:
text = query.lower().replace("service-account", "service account")
fresh = any(term in text for term in ("latest", "current", "right now"))
live = any(term in text for term in ("build-", "job status", "quota remaining"))
rule_doc = any(term in text for term in ("policy", "migration", "exception"))
routes = []
if live:
routes.append("authorized_live_api")
if rule_doc or not live:
routes.append("authorized_hybrid_search")
return Plan(tuple(routes), fresh or rule_doc)
assert plan_query("Latest parser-v2 policy for service-accounts").requires_current_revision
assert plan_query("Is build-1042 running right now?").routes == ("authorized_live_api",)
assert len(plan_query("build-1042 status and current migration policy").routes) == 2
print(plan_query("Latest parser-v2 migration policy for service accounts"))
print(plan_query("build-1042 status and current migration policy"))Plan(routes=('authorized_hybrid_search',), requires_current_revision=True)
Plan(routes=('authorized_live_api', 'authorized_hybrid_search'), requires_current_revision=True)
If the query planner fails or times out, fall back to a narrower authorized search or ask for clarification; never widen tenant scope. Treat raw query logs as sensitive data too, since queries often contain internal identifiers.
Retrieve broadly within the permitted corpus
BM25 excels at exact identifiers like parser-v2 using term frequency, inverse document frequency, and length normalization.[5] Dense vector search catches paraphrases and conceptual matches. Run both branches concurrently and merge them with reciprocal rank fusion (RRF):
Ranks start at 1, and each document contributes at most once per list so duplicate chunks cannot inflate a document's score. Using provides a standard starting balance without assuming BM25 and cosine similarities share a numerical scale.[6]

After fusion, a cross-encoder jointly scores the query and top candidate passages, while late-interaction models like ColBERT keep per-token embeddings to balance precision and speed.[7] Tune candidate counts against measured recall and latency rather than hardcoding arbitrary funnels.
![Side-by-side narrowing retrieval funnels at K = 2 over the four-document ranking [roadmap@1, policy@1, policy@2, exception@1]. Left: post-filtering truncates to Top-2 first, capturing forbidden roadmap@1 and obsolete policy@1, then drops both at eligibility check leaving 0 usable passages. Right: pre-filtering enforces workspace-a access and current revision before Top-2, preserving both policy@2 and exception@1.](https://assets.leetllm.com/v1/bd46224863f6/system-design/design-llm-powered-search-engine/illustrations/_generated/retrieval_funnel_dark.png)
Run a miniature evidence pipeline
Let's wire the entire corpus into an executable pipeline: pre-filtered BM25 and cosine retrieval, RRF fusion, budget-aware packing, and exact span publication. Watch how the checks handle five real failure modes: empty budget, tenant mismatch, duplicate hits, truncated qualifiers, and mid-flight permission or revision changes.
import hashlib
import math
import re
from collections import Counter, defaultdict
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Principal:
tenant: str
groups: frozenset[str]
@dataclass(frozen=True)
class Document:
doc_id: str
revision: int
tenant: str
text: str
vector: tuple[float, float]
@property
def key(self):
return (self.doc_id, self.revision)
@property
def digest(self):
return hashlib.sha256(self.text.encode()).hexdigest()
@dataclass(frozen=True)
class Access:
current_revision: int
readers: frozenset[str]
published: bool = True
@dataclass(frozen=True)
class Quote:
key: tuple[str, int]
start: int
end: int
text: str
digest: str
alice = Principal("workspace-a", frozenset({"engineering"}))
corpus = [
Document("policy", 1, "workspace-a", "Parser-v2 migrations may start within 90 days.", (1.0, 1.0)),
Document("policy", 2, "workspace-a", "Parser-v2 SDK migrations must start within 30 days after the deprecation notice.", (1.0, 0.5)),
Document("exception", 1, "workspace-a", "Service-account SDK migrations may start within 60 days after the notice only with security approval.", (0.5, 1.0)),
Document("roadmap", 1, "workspace-b", "Private parser-v2 service-account SDK migration roadmap.", (1.0, 1.0)),
]
store = {doc.key: doc for doc in corpus}
registry = {
"policy": Access(2, frozenset({"engineering"})),
"exception": Access(1, frozenset({"engineering"})),
"roadmap": Access(1, frozenset({"engineering"})),
}
def eligible(doc, principal, access):
rule = access.get(doc.doc_id)
return bool(rule and rule.published
and doc.tenant == principal.tenant
and doc.revision == rule.current_revision
and principal.groups & rule.readers)
def words(text):
return re.findall(r"[a-z0-9]+(?:-[a-z0-9]+)*", text.lower())
def lexical_ranking(query, docs):
if not docs:
return []
counts = {doc.key: Counter(words(doc.text)) for doc in docs}
avg_len = sum(sum(c.values()) for c in counts.values()) / len(docs)
scores = {}
for doc in docs:
score = 0.0
for term in set(words(query)):
df = sum(term in c for c in counts.values())
idf = math.log(1 + (len(docs) - df + 0.5) / (df + 0.5))
tf = counts[doc.key][term]
length = sum(counts[doc.key].values())
score += idf * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * length / avg_len))
scores[doc.key] = score
return sorted(scores, key=lambda key: (-scores[key], key))
def vector_ranking(query_vector, docs):
def cosine(doc):
dot = sum(a * b for a, b in zip(query_vector, doc.vector))
norm = math.sqrt(sum(a * a for a in query_vector) * sum(b * b for b in doc.vector))
return dot / norm if norm else 0.0
return [doc.key for doc in sorted(docs, key=lambda doc: (-cosine(doc), doc.key))]
def rrf(rankings, k=60):
if k < 0:
raise ValueError("k must be nonnegative")
scores = defaultdict(float)
for ranking in rankings:
for rank, key in enumerate(dict.fromkeys(ranking), 1):
scores[key] += 1 / (k + rank)
return sorted(scores, key=lambda key: (-scores[key], key))
def retrieve(principal, access):
docs = [doc for doc in corpus if eligible(doc, principal, access)]
query = "parser-v2 SDK migration policy for service-account exceptions"
return rrf([lexical_ranking(query, docs), vector_ranking((1.0, 1.0), docs)])
def pack(keys, word_budget):
if word_budget < 0:
raise ValueError("budget must be nonnegative")
selected, used = [], 0
for key in dict.fromkeys(keys):
doc = store[key]
cost = len(words(doc.text))
if used + cost <= word_budget:
selected.append(Quote(key, 0, len(doc.text), doc.text, doc.digest))
used += cost
return selected
def publish(quotes, principal, access):
if len(quotes) != 2 or {q.key[0] for q in quotes} != {"policy", "exception"}:
return "Insufficient current, authorized evidence."
for quote in quotes:
doc = store.get(quote.key)
if (doc is None or not eligible(doc, principal, access)
or quote.digest != doc.digest
or quote.start != 0 or quote.end != len(doc.text)
or doc.text[quote.start:quote.end] != quote.text):
return "Insufficient current, authorized evidence."
return "\n".join(f'"{q.text}" [{q.key[0]}@{q.key[1]}:{q.start}-{q.end}]'
for q in sorted(quotes, key=lambda q: q.key))
ranked = retrieve(alice, registry)
assert set(ranked) == {("policy", 2), ("exception", 1)}
assert rrf([ranked + ranked]) == rrf([ranked])
assert retrieve(Principal("workspace-c", alice.groups), registry) == []
packed = pack(ranked, word_budget=40)
answer = publish(packed, alice, registry)
assert "only with security approval" in answer
assert "Insufficient" in publish(pack(ranked, 0), alice, registry)
corrupted = [replace(packed[0], text="Approval is not required."), *packed[1:]]
assert "Insufficient" in publish(corrupted, alice, registry)
exc = next(q for q in packed if q.key[0] == "exception")
short_text = exc.text.split(" only with security approval.")[0]
truncated = [replace(exc, end=len(short_text), text=short_text) if q.key[0] == "exception" else q for q in packed]
assert "Insufficient" in publish(truncated, alice, registry)
revoked = {**registry, "exception": replace(registry["exception"], readers=frozenset())}
assert "Insufficient" in publish(packed, alice, revoked)
advanced = {**registry, "policy": replace(registry["policy"], current_revision=3)}assert retrieve(alice, advanced) == [("exception", 1)]
assert "Insufficient" in publish(packed, alice, advanced)
print("eligible ranked keys:", ranked)
print(answer)
print("Revocation, missing evidence, stale revision, and changed-span checks passed.")
print("condition-truncated exact quotation rejected:", "Insufficient" in publish(truncated, alice, registry))
print("revision advanced before reindex:", publish(packed, alice, advanced))eligible ranked keys: [('exception', 1), ('policy', 2)]
"Service-account SDK migrations may start within 60 days after the notice only with security approval." [exception@1:0-101]
"Parser-v2 SDK migrations must start within 30 days after the deprecation notice." [policy@2:0-80]
Revocation, missing evidence, stale revision, and changed-span checks passed.
condition-truncated exact quotation rejected: True
revision advanced before reindex: Insufficient current, authorized evidence.Look closely at the two edge cases caught at the end of that run. First, a substring [0, 72) of exception@1 matches the document's SHA-256 digest and is a verbatim prefix, yet drops "only with security approval." Checking full clause integrity prevents silent truncation of qualifying conditions.

Second, when the registry advances policy to revision 3 while the search index still holds revision 2, retrieve excludes policy@2 and publish blocks even a previously complete quote pack. Availability pauses briefly until revision 3 lands rather than silently serving an obsolete 30-day rule.

Pack evidence without changing its meaning
Packing turns ranked passages into a prompt budget counted with the serving model's actual tokenizer (reserving space for system instructions, the user query, tool schemas, and output tokens). Pure relevance sorting can fill the entire window with ten near-duplicate chunks of the general 30-day rule and crowd out the single exception chunk. Add document-diversity and coverage constraints so secondary rules survive packing.
Position matters too: Liu et al.'s Lost in the Middle study showed that models can overlook relevant facts buried in the middle of long contexts.[8] Measure recall sensitivity across prompt positions on your serving model before tuning chunk order. If you apply prompt compression such as LLMLingua, run it strictly after authorization and passage selection, verify that numbers and negations survive, and keep mappings back to exact original spans for verification.[9]
Verify that citations support their claims
Split citation verification into three independent checks:
| Check | What it verifies | Failure caught |
|---|---|---|
| Resolution | Citation ID maps to a current, authorized revision and span | Link points to a deleted or cross-tenant document |
| Support | The cited span entails the claim, including numbers and conditions | Model drops "only with security approval" |
| Coverage | Every material part of the question has backing evidence | General rule cited, relevant exception omitted |
Verbatim quotes can be checked deterministically; paraphrased claims require semantic verification via natural language inference (NLI) models or calibrated verifier LLMs (as studied in TRUE and FActScore).[10][11] Never confuse keyword overlap with semantic entailment:
import re
def terms(text):
return set(re.findall(r"[a-z0-9]+", text.lower()))
claim = "Security approval is required"
negated_source = "Security approval is not required"
paraphrased_source = "Authorization from the security team is mandatory"
assert terms(claim) <= terms(negated_source)
assert not terms(claim) <= terms(paraphrased_source)
print("Negated source passes lexical check:", terms(claim) <= terms(negated_source))
print("Paraphrase passes lexical check:", terms(claim) <= terms(paraphrased_source))Negated source passes lexical check: True
Paraphrase passes lexical check: False
Treat every retrieved passage as untrusted data, never as instructions. Delimit retrieved chunks clearly, block tool calls triggered solely by retrieved text, and keep secrets out of the generation context to defend against indirect prompt injection.[12]

Stream progress before policy claims
Users want fast visual feedback, yet you cannot un-show a leaked or wrong rule after a reader copies it. Stream safe progress updates and authorized source citations immediately, while holding factual claims until their verification verdict arrives.
Server-Sent Events (SSE) provide simple HTTP streaming with Last-Event-ID reconnect cursors, though authentication, authorization, and replay deduplication remain application responsibilities.[13] One subtle browser quirk breaks naive deduplication: if an SSE event omits an id: line, the browser silently inherits the previous event's lastEventId:
id: 12
data: {"type":"progress"}
data: {"type":"checked_claim"}
Both callbacks receive lastEventId == "12". Deduplicating solely on lastEventId drops the second frame! Always emit monotonic explicit IDs (12, 13, ...) on every replayable frame. Also note that native browser EventSource only supports GET requests, so create the search job separately or stream via fetch instead of stuffing secrets into query strings.[14]

The state machine below shows how to bind every verification verdict to (request_id, draft_hash, source_revision) with strict boolean checking so a string "false" or integer 1 never accidentally releases an unverified claim:
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Event:
event_id: int
request_id: str
kind: str
draft_hash: str
source_revision: int
accepted: bool = False
def apply_events(events):
state = "pending"
emitted = []
seen = set()
for ev in events:
if ev.request_id != "request-a" or ev.event_id in seen:
continue
if ev.event_id < 0 or ev.source_revision < 0:
continue
if ev.accepted is True:
verdict = "checked"
elif ev.accepted is False:
verdict = "blocked"
else:
continue
seen.add(ev.event_id)
if ev.draft_hash != "draft-2" or ev.source_revision != 2:
continue
if state != "pending" or ev.kind != "check":
continue
state = verdict
if state == "checked":
emitted.append("checked policy claim")
return state, emitted
accepted = Event(1, "request-a", "check", "draft-2", 2, True)
rejected = Event(2, "request-a", "check", "draft-2", 2, False)
stale = Event(3, "request-a", "check", "draft-1", 1, True)
assert apply_events([stale]) == ("pending", [])
assert apply_events([rejected]) == ("blocked", [])
assert apply_events([accepted, accepted]) == ("checked", ["checked policy claim"])
assert apply_events([rejected, accepted]) == ("blocked", [])
for bad in (replace(accepted, accepted="false"), replace(accepted, accepted=1)): assert apply_events([bad]) == ("pending", [])
print("stale result:", apply_events([stale]))
print("rejected claim:", apply_events([rejected]))
print("accepted replay:", apply_events([accepted, accepted]))
print("malformed verdict:", apply_events([replace(accepted, accepted="false")]))stale result: ('pending', [])
rejected claim: ('blocked', [])
accepted replay: ('checked', ['checked policy claim'])
malformed verdict: ('pending', [])Matching ev.accepted is True and ev.accepted is False by identity rejects truthy strings like "false" and numeric flags like 1 before a malformed payload can release unverified text.
Measure the useful response from request to verification
You can overlap query planning (40 ms) with an independent retrieval branch that searches the raw query (260 ms). A branch that depends on a rewritten query must wait for planning to finish first. Adding reranking (90 ms), packing (20 ms), model TTFT (430 ms), first claim completion (100 ms), and claim verification (80 ms) gives the critical path:
| Milestone | Critical-path sum | Latency |
|---|---|---|
| Raw-branch draft TTFT | 800 ms | |
| Rewrite-dependent draft TTFT | 840 ms | |
| First checked claim | 980 ms |

Always compute end-to-end percentiles from complete request traces (including timeouts, cancellations, and retries) rather than adding individual stage p95s. Optimizations like PagedAttention and speculative decoding speed up the generation slice, not slow upstream retrievals or claim checks.[15][16]
Count KV-resident requests separately
By Little's Law (), mean concurrency equals arrival rate times residence time. Crucially, a search request only occupies GPU KV cache during the model-resident portion of its life, not while waiting on retrieval or post-generation CPU checks.
At 1,000 peak QPS with 60% synthesis traffic (600 synthesis requests/s), suppose each synthesis request spends 0.37 s in retrieval/packing, 1.93 s holding GPU KV cache, and 0.20 s in final checks (2.50 s total), with 120 mean output tokens and 1,560 mean cached positions. For a 32-layer GQA decoder with 8 KV heads, head dimension 128, and 2-byte FP16/BF16 entries, each cached position takes bytes (128 KiB). Let's size both KV memory and decode throughput lower bounds with a 12 GiB net KV budget and 6,000 output tokens/s per GPU:
from math import ceil
all_qps, synthesis_fraction = 1000, 0.60
synthesis_qps = all_qps * synthesis_fraction
before_model, model_resident, after_model = 0.37, 1.93, 0.20
in_flight = synthesis_qps * (before_model + model_resident + after_model)
kv_resident = synthesis_qps * model_resident
kv_bytes_per_position = 2 * 32 * 8 * 128 * 2
mean_cached_positions = 1560
kv_gib = kv_resident * mean_cached_positions * kv_bytes_per_position / 2**30
kv_devices = ceil(kv_gib / 12)
decode_devices = ceil(synthesis_qps * 120 / 6000)
assert round(in_flight) == 1500 and round(kv_resident) == 1158
assert kv_devices == 19 and decode_devices == 12
print("synthesis in flight:", round(in_flight))
print("KV-resident requests:", round(kv_resident))
print("mean KV GiB:", round(kv_gib, 2))
print("KV / decode device lower bounds:", kv_devices, "/", decode_devices)synthesis in flight: 1500
KV-resident requests: 1158
mean KV GiB: 220.52
KV / decode device lower bounds: 19 / 12
Price the route mix, including the cheap routes
Full synthesis pays for retrieval, reranking, prompt + output tokens, and claim verification. Cache hits and structured API lookups are far cheaper, though they still pay for auth, storage, and formatting. With a 60% synthesis / 30% validated cache / 10% structured lookup split (using a 1,500-token prompt and 400-token answer at $3 per million tokens):
prompt_tokens, output_tokens = 1500, 400
rate_per_million = 3.0
synthesis_usd = (prompt_tokens + output_tokens) * rate_per_million / 1_000_000
full_usd = 0.002 + 0.001 + synthesis_usd + 0.001
cache_usd, structured_usd = 0.0003, 0.001
mean_usd = 0.60 * full_usd + 0.30 * cache_usd + 0.10 * structured_usd
assert round(full_usd, 4) == 0.0097 and round(mean_usd, 5) == 0.00601
print(f"full route: ${full_usd:.4f}")
print(f"weighted mean: ${mean_usd:.5f}")
print(f"1,000 QPS: ${mean_usd * 1000 * 60:.2f} per minute")full route: $0.0097
weighted mean: $0.00601
1,000 QPS: $360.60 per minute
A semantic cache match is only a candidate lookup. Before returning a cached answer, revalidate the caller's tenant scope, prompt/model version, and every cited document revision against the live registry. If freshness or access cannot be verified, take the miss path instead of serving stale private text.
Evaluate each kind of failure separately
Measure each stage independently on held-out labeled queries containing deletions, conflicting rules, mid-stream revocations, indirect prompt injections, and conditional exceptions:
| Layer | Primary metric | What it misses alone |
|---|---|---|
| Retrieval | Recall@K, MRR, nDCG over current authorized docs | Whether the generator actually used the retrieved exception |
| Packing | Fraction of required evidence surviving token budget | Multi-document coverage when one topic dominates ranking |
| Citations | Resolution, semantic support, and claim coverage | Each of the three can fail while the other two pass |
| Answer | Task correctness and calibrated abstention | Faithfulness to a stale source still produces a wrong answer |
| Service | Checked-claim p95/p99, error rate, cost, KV occupancy | Averages over successful requests hide timeouts and overload |
| Security | Zero unauthorized leaks across revocation tests | High relevance never offsets an access breach |
Reference-free LLM-as-a-judge frameworks like RAGAS help track faithfulness trends when labeled sets are small, while click-through and reformulation rates supply useful online signals; neither replaces labeled retrieval and security regression suites.[17]
When computing Recall@K and nDCG@K, deduplicate by document identity first so two chunks from the same document do not earn double credit, and return None for empty gold sets (unanswerable queries):
from math import log2
def metrics(ranked, relevant, k):
if k <= 0:
raise ValueError("k must be positive")
if not relevant:
return {"recall": None, "ndcg": None}
unique = list(dict.fromkeys(ranked))[:k]
recall = len(set(unique) & relevant) / len(relevant)
dcg = sum((doc in relevant) / log2(rank + 1) for rank, doc in enumerate(unique, 1))
ideal = sum(1 / log2(rank + 1) for rank in range(1, min(k, len(relevant)) + 1))
return {"recall": round(recall, 4), "ndcg": round(dcg / ideal, 4)}
gold = {"policy@2", "exception@1"}assert metrics(["policy@2", "policy@2"], gold, 2)["recall"] == 0.5
assert metrics([], set(), 2)["recall"] is None
print("missing exception:", metrics(["policy@2", "faq"], gold, 2))
print("both required sources:", metrics(["policy@2", "exception@1"], gold, 2))missing exception: {'recall': 0.5, 'ndcg': 0.6131}
both required sources: {'recall': 1.0, 'ndcg': 1.0}![Retrieval evaluation comparing three top-2 rankings against gold set {policy@2, exception@1} on a 0.0 to 1.0 scale. Duplicate chunks [policy@2, policy@2] deduplicate to one hit and score 0.50 recall and 0.6131 nDCG, identical to [policy@2, faq]. Retrieving both unique required documents [policy@2, exception@1] scores 1.00 recall and 1.0000 nDCG.](https://assets.leetllm.com/v1/afef05ffad8b/system-design/design-llm-powered-search-engine/illustrations/_generated/retrieval_coverage_metrics_dark.png)
Keep stage-level attribution in traces so regressions point straight to their cause: a missing active revision points to ingestion or retrieval, a dropped exception points to packing, a stripped qualifier points to synthesis or NLI verification, and any cross-tenant hit points directly to access control.
Mastery check
Evaluation rubric
- Trace both the base rule and its conditional exception through revision tracking, pre-filtered hybrid retrieval, RRF, packing, and span verification, explaining why stale or forbidden hits cannot occupy top- slots.
- Separate citation resolution, semantic support, and coverage, and show how composite event binding stops stale verdicts or live revocations from releasing text.
- Derive the 980 ms checked-claim path, 1,158 KV-resident requests, and route-weighted cost, distinguishing memory lower bounds from decode lower bounds.
Follow-up questions
The source publishes policy revision 3, but its embeddings aren't ready. The registry knows revision 3 is current. Should the service answer from indexed revision 2?
Answer
Not as the current rule. The service can fetch and authorize revision 3 through a direct fallback, wait within a tight deadline, or report that current evidence is temporarily unavailable. Silently serving revision 2 turns indexing lag into an incorrect answer.
Packing the exception improves labeled coverage but lengthens the prompt. Which capacity and latency assumptions need another measurement?
Answer
Remeasure prefill latency, mean cached KV positions, KV-residence time, and joint GPU throughput under the longer prompt distribution. Holding output length fixed does not keep the 1,560-position or 1.93-second numbers valid once prompt sizes grow.
How would you evaluate an automated support checker when deploying NLI verifiers in production?
Answer
Test on held-out claim-and-span pairs covering negations, dropped conditions, mismatched dates, contradictions, unsupported extrapolations, and valid paraphrases. Track false acceptances and false rejections separately against human labels, tune abstention thresholds to domain risk, and test event binding independently.