Language-aware retrieval and failure analysis
Language coverage is an empirical question
Multilingual retrieval may search same-language documents or cross-language documents; these are different tasks. A model advertised as multilingual does not guarantee equal recall for all languages, scripts, domains or dialects. This synthetic bilingual corpus contains a return receipt policy (A), shipping rule (B), and irrelevant receipt-printer passage (C). English and Persian query strings are data only; all instruction is English. The baseline uses Unicode normalization, case folding, a small explicit mapping of Arabic yeh/kaf to Persian yeh/kaf, and Unicode word runs. NFC alone does not unify those variants. It is not a full Persian tokenizer, stemmer or translation system; zero-width joiners and morphology require deliberate testing. Both receipt queries match A then C. The English paraphrase proof of purchase has no exact token match and yields an empty list. No embedding model is executed.
import reimport unicodedata
def terms(text): text = unicodedata.normalize("NFC", text).casefold() text = text.translate(str.maketrans({"ي": "ی", "ك": "ک"})) return set(re.findall(r"[^\W_]+", text))
def lexical(query, eligible, k): if type(k) is not int or k < 1: raise ValueError("positive k required") q = terms(query) scores = [(len(q & terms(text)), key) for key, text in eligible.items()] return [key for score, key in sorted(scores, key=lambda x: (-x[0], x[1]))[:k] if score > 0]
corpus = {"A": "Receipt required for returns. رسید برای مرجوعی لازم است.", "B": "Shipping takes five days. ارسال پنج روز طول می کشد.", "C": "Receipt printer maintenance. تعمیر چاپگر رسید."}print(lexical("receipt returns", corpus, 2))print(lexical("رسيد مرجوعي", corpus, 2))print(lexical("proof of purchase", corpus, 2))Compare three pipelines, not three promises
For the bilingual corpus, judge A relevant for the receipt-policy questions, C irrelevant despite shared terminology. Record English literal, Persian literal and English paraphrase separately. A hypothetical dense ranking C,A,B for each literal and A,B,C for the paraphrase illustrates a semantic retriever; these lists are manually supplied fixtures, not measured model results. At k=1 lexical recall is 1,1,0; dense fixture recall is 0,0,1. With full lexical lists and these dense lists, RRF with c=60 places A before C for the literal queries (their contributions tie and ID breaks the tie), and A first for the paraphrase. This gives toy recall 1,1,1, not evidence that hybrid search is better on real Persian. A hypothetical reranker trained to distinguish purchase policy from printer maintenance might prioritize A, but must be measured independently. Add cross-language-only passages and queries before claiming cross-language performance. Track counts, latency and recall/MRR per language and query type; avoid a global mean hiding a small or poorly served language.
Enforce authorization and freshness outside the model
Use authenticated tenant and access policy from trusted application state, not a generated query filter. Scope every lexical and dense search, including rewrites and rerankers, before candidate text is exposed. Check IDs again against the current authoritative state before context assembly; reject stale, missing and unauthorized revisions, and invalidate dependent caches after a deletion or permission change. The local eligible_ids function simulates only this second ID-level check with a trusted mapping of immutable revision IDs and tenant/active flags. It is not real authentication, physical deletion or concurrent-revocation enforcement. In the example the stale A-r1 and other tenant X-r1 are removed, while A-r2 and C-r1 remain. Use independently annotated facts for the toy answer: it returns days=5, then None for an incomplete two-field answer, then None when current passages disagree. In production, trusted authority and effective dates may resolve conflicts; otherwise abstain or ask for review. Retrieved instruction-like text is untrusted data and cannot grant tools or change the contract.
def eligible_ids(candidates, records, tenant): # Trusted server metadata: ID -> (tenant, active revision). # IDs identify immutable revisions, not just document names. return list(dict.fromkeys(key for key in candidates if records.get(key) == (tenant, True)))
def decide(required, facts, selected): # Facts are independently annotated (ID, field, value) triples. # Return only complete, consistent required fields, never execute text. if not required: return None allowed = set(selected) answer = {} for field in sorted(set(required)): matches = [(key, value) for key, name, value in facts if key in allowed and name == field] if len({value for _, value in matches}) != 1: return None answer[field] = (matches[0][1], sorted({key for key, _ in matches})) return answer
records = {"A-r2": ("shop", True), "A-r1": ("shop", False), "X-r1": ("other", True), "C-r1": ("shop", True)}selected = eligible_ids(["X-r1", "A-r1", "A-r2", "C-r1"], records, "shop")print(selected)facts = [("A-r2", "days", "5"), ("A-r1", "days", "9"), ("X-r1", "days", "1")]print(decide(["days"], facts, selected))print(decide(["days", "fee"], facts, selected))print(decide(["days"], facts + [("C-r1", "days", "7")], selected))Separate answer coverage from citation support
A citation is supported if the cited passage at the recorded revision actually supports the material claim; a valid ID alone is insufficient. Coverage asks whether every required claim has been addressed, including exceptions and conditions. An answer can have perfect citation support for one fact while omitting another required fact. The toy decide function returns all required fields only when each has exactly one value in the selected authorized annotations, with a unique list of supporting IDs. It does not interpret free text or prove natural-language entailment. Evaluate per-claim support and coverage independently of recall; evaluate unanswerable cases for correct abstention and answerable cases for unnecessary refusals. Use reviewed malicious-looking passages as inert fixtures, with no tool execution. Actual prompt injection resistance requires a separate model-level adversarial evaluation and restricted permissions; a deterministic fact selector cannot demonstrate it.
Practice: record a failure matrix
For each query store corpus revision, authorized relevance labels, original and transformed query, eligible ranks, fused ranks, reranked IDs, selected context IDs, citation support and coverage. Include a deleted A revision, an unauthorized duplicate, a conflicting current shipping statement, and a harmless passage containing instruction-like text without a trusted annotation. Assert unauthorized and stale IDs never reach context; assert incomplete and conflicting evidence causes abstention. Compare candidate recall with context recall to separate retrieval failure from budget failure. Do not log restricted text or identifiers to user-facing reports. Review source-evidence.json for rank fusion, reranking and vector security sources. The next chapter moves from retrieval evidence to explicitly authorized tool execution.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Language-aware retrieval and failure analysis quiz
Apply retrieval evaluation and evidence controls.
Both literal queries succeed in a tiny bilingual fixture. What is established?
A stale candidate is returned by an index. What should the application do?
An answer supports shipping duration but omits a required fee. What is wrong?
A retrieved passage contains an instruction to change the tenant. What authority does it have?
A paraphrase has no lexical matches. What is a useful next step?