On this page
A developer asks an API documentation assistant, "Why did our batch embedding job hit an HTTP 429?" After reading the reply, they follow up with, "What about the synchronous one?" If the retriever embeds that second message alone, it searches for "What about the synchronous one?". The HNSW graph returns nearest neighbors in 4 milliseconds: generic SDK overviews that miss synchronous rate limits completely.
The index worked fine; the query vector aimed at the wrong neighborhood. The previous chapter built fast HNSW and IVF indexes; this chapter handles queries that omit context, clash with corpus vocabulary, demand multiple facts, or pull back unsupportive passages. We trace one API docs assistant through four repair families: query transforms, HyDE, Self-RAG, and CRAG.
Why naive RAG misses
Single-shot RAG embeds the latest user message, pulls top-k chunks from a vector index, and generates. Misses cluster into four failure modes:
- Missing conversational context: "What about the synchronous one?" needs the prior turn's rate-limit subject.
- Query-document style mismatch: Informal questions ("Can we push more traffic during launch week?") use different vocabulary from formal docs ("Temporary tokens-per-minute quota increases require approval").
- Noisy retrieval: Chunk boundaries or tight ANN settings rank an SDK install guide above quota rules.
- Unnecessary retrieval: Searching on greetings or self-contained arithmetic wastes latency and prompt tokens.
Measure which miss actually appears in logs before adding complexity.
Query rewriting and decomposition
Four lightweight transforms run before search: rewriting restores chat context, expansion widens vocabulary, decomposition splits multi-fact requests, and step-back prompting pairs a concrete error with its governing rule.

1. Conversational query rewriting
Rewrite-Retrieve-Read places a rewriter ahead of a frozen retriever and reader.[1] Given Turn 1 ("Why did our batch embedding job hit an HTTP 429?") and Turn 2 ("What about the synchronous one?"), the rewriter emits "What are the HTTP 429 rate limits for the synchronous embedding endpoint?". Keep the raw message for answer generation so tone stays natural, and send the rewritten string to retrieval. Treat prior retrieved text in history as untrusted data: restrict the rewriter strictly to disambiguation, strip secrets, and enforce caller ACLs outside the rewriter (RAG Security & Access Control).
2. Multi-query expansion and Reciprocal Rank Fusion
When one phrasing misses target pages, multi-query expansion generates 2 to 4 variants, searches them in parallel, and merges ranked lists. Because cosine similarities across different queries and unbounded BM25 scores are not on one comparable scale, RAG-Fusion merges lists via Reciprocal Rank Fusion (RRF):[2][3]
Here is document 's 1-based rank in list , and damps rank swings.[3] At , rank 1 scores vs. for rank 2; at , rank 1 scores vs. (a 1.6% gap), rewarding passages that appear consistently near the top across phrasings. Keep the original query alongside capped, non-duplicate variants so near-identical rewrites do not double-count hits:
import re
def clean_variants(raw_lines: str, fallback: str, max_n: int = 3) -> list[str]:
cleaned = [re.sub(r"^(?:[-*]|\d+[.)])\s+", "", s.strip()).strip() for s in raw_lines.splitlines()]
return list(dict.fromkeys(x for x in cleaned if x))[:max_n] or [fallback]
def rrf(rankings: list[list[str]], k: int = 60) -> list[tuple[str, float]]:
scores: dict[str, float] = {}
for ranking in rankings:
for rank, doc_id in enumerate(dict.fromkeys(ranking), start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return sorted(scores.items(), key=lambda pair: (-pair[1], pair[0]))
raw = "1. Rate-limit burst limits during launch traffic\n2. Queue backpressure controls\n3. Autoscaling for traffic spikes"
print("variants:", clean_variants(raw, "How do we handle peak traffic throttling?"))
ranked = [
["rate-limit-guide", "quota-increase", "autoscaling"],
["autoscaling", "rate-limit-guide", "backpressure"],
["rate-limit-guide", "batch-api", "autoscaling"],
]
for doc_id, score in rrf(ranked)[:3]:
print(f"{doc_id}: {score:.4f}")variants: ['Rate-limit burst limits during launch traffic', 'Queue backpressure controls', 'Autoscaling for traffic spikes']
rate-limit-guide: 0.0489
autoscaling: 0.0481
batch-api: 0.01613. Query decomposition and step-back prompting
Some requests span multiple pages at once: "Compare synchronous and batch embedding API latency, limits, and retry behavior." No single chunk holds all six cells of that comparison, so one vector query returns partial facts and tempts the generator to invent the missing ones. Query decomposition breaks the request into focused sub-queries:
- "What latency does the synchronous embedding endpoint target?"
- "What throughput and completion limits apply to the batch embedding endpoint?"
- "What retry behavior applies to each endpoint?"
Execution follows two topologies: parallel scatter-gather when every entity is already known (taking plus planning and synthesis), or sequential least-to-most chains when a later hop depends on an earlier result ("Find the endpoint with the highest error rate last week, then fetch its circuit-breaker settings").[4] Whenever a sub-query returns nothing, pass that missing-evidence marker explicitly to the synthesizer so it reports the gap instead of fabricating a plausible answer.
When narrow runtime details obscure the underlying rule, step-back prompting abstracts the concrete question into its governing concept and retrieves both queries together:[5]
- Specific query: "Why did our client hit HTTP 429 at 120 requests/minute on the tier 2 embedding endpoint?"
- Step-back query: "What are the rate limits, burst thresholds, and quota rules for tier 2 embedding endpoints?"
Searching both queries preserves the concrete error context while pulling in the foundational quota rules.
When should you rewrite a query instead of searching the raw user message?
Answer
Rewrite when chat history holds a missing referent ("the synchronous one"). Expand for vocabulary gaps, decompose multi-fact comparisons, and step back when a specific error needs its governing rule.
HyDE (Hypothetical Document Embeddings)
All four transforms still search with a question. HyDE (Hypothetical Document Embeddings) bridges question-vs-document asymmetry in dense retrieval in three steps:[6]
- Generate: Prompt an instruction-tuned LLM zero-shot to draft hypothetical answer passages.
- Embed: Encode each hypothetical passage with the corpus document encoder and average the vectors:
- Retrieve: Search with (normalized for cosine similarity), discard the hypothetical text, and pass only real retrieved passages to the generator.
Even when the hypothetical draft invents details, the dense encoder bottleneck preserves topical geometry.[6] On TREC DL19 with InstructGPT + Contriever, HyDE lifted nDCG@10 from 44.5 to 61.3, and on DL20 from 42.1 to 57.9, with similar zero-shot gains on BEIR and Mr. TyDi.[6]

Watch for hallucination drift: HyDE hurts on exact identifiers (error codes like E-9410, dates, CVE numbers, commit hashes, prices) because a fabricated proxy drags search toward the wrong subsystem. Route exact-identifier lookups straight to hybrid dense + sparse search:
import reimport numpy as np
EXACT_LOOKUP = re.compile(r"\b(?:[A-Z]+-\d+|(?:HTTP|error)\s+[A-Z0-9-]+|\d{4}-\d{2}-\d{2})\b|[$€£]\s*\d", re.I)
def tokens(text: str) -> set[str]:
return set(re.findall(r"[a-z0-9-]+", text.lower()))
chunks = [
("generic-embeddings", "The embedding API converts text into vectors for search."),
("throughput-quota", "Launch traffic needs a temporary tokens-per-minute quota request and approval."),
("batch-embeddings", "Batch embedding jobs support offline workloads with retry backoff."),
]
required = {"throughput-quota", "batch-embeddings"}
cases = [
("raw question", "Can we increase embedding throughput during a launch week?"),
("useful proxy", "Embedding throughput increases need a temporary tokens-per-minute quota request, batch embedding jobs, and retry backoff."),
("drifting proxy", "The embedding API converts text into vectors for search."),
]
for label, text in cases:
q = tokens(text)
hits = [cid for cid, body in sorted(chunks, key=lambda c: len(q & tokens(c[1])), reverse=True)[:2]]
print(f"{label:14s}: {hits} | Recall@2={len(required & set(hits)) / len(required):.1f}")
print("mean proxy vec:", np.round(np.array([[0.2, 0.8, 0.1], [0.4, 0.6, 0.3]]).mean(axis=0), 2).tolist())
for q in ["What caused error E-9410?", "How should we plan embedding throughput for launch traffic?"]:
print(f"{'hybrid_exact' if EXACT_LOOKUP.search(q) else 'hyde_candidate':14s}: {q}")raw question : ['throughput-quota', 'generic-embeddings'] | Recall@2=0.5
useful proxy : ['throughput-quota', 'batch-embeddings'] | Recall@2=1.0
drifting proxy: ['generic-embeddings', 'batch-embeddings'] | Recall@2=0.5
mean proxy vec: [0.3, 0.7, 0.2]
hybrid_exact : What caused error E-9410?
hyde_candidate: How should we plan embedding throughput for launch traffic?Self-RAG (Self-reflective RAG)
Self-RAG fine-tunes the generator itself to emit four reflection token families during autoregressive decoding:[7]
Retrieve(Yes,No,Continue): skips search on self-contained turns or triggers on-demand lookup before a segment.ISREL(Relevant,Irrelevant): rates passage relevance before drafting from it.ISSUP(Fully,Partially,No support): checks whether the passage entails the draft segment.ISUSE(1through5): rates usefulness, mapped linearly onto .
Trace our launch-week throughput question through one Self-RAG step:
[Retrieve=Yes]-> fetch candidate passages from the index.- Retrieved passage: "Temporary tokens-per-minute (TPM) increases require approval. Clients must use exponential backoff after rate-limit errors."
[ISREL=Relevant]-> passage directly addresses the launch-week quota question.- Candidate segment: "For launch traffic, request a temporary TPM increase and keep exponential backoff enabled."
[ISSUP=Fully Supported]-> every claim in the segment is entailed by the passage.[ISUSE=4]-> direct, actionable answer.
When the model emits [Retrieve=Yes], Self-RAG decodes one continuation per top- passage in parallel and ranks branches via segment-level beam search (default width 2):[7]
Normalized within each family: , , and with . Because can be negative or zero, critique terms add linearly rather than inside a log.[7] Raising favors strict grounding over fluent speculation.[8]

import numpy as np
def family_score(probs: list[float], weights: list[float]) -> float:
p, w = np.asarray(probs, dtype=np.float64), np.asarray(weights, dtype=np.float64)
return float(np.dot(p, w) / np.sum(p))
def critique_score(rel: list[float], sup: list[float], use: list[float]) -> float:
return (
0.2 * family_score(rel, [1.0, 0.0])
+ 0.6 * family_score(sup, [1.0, 0.5, 0.0])
+ 0.2 * family_score(use, [-1.0, -0.5, 0.0, 0.5, 1.0])
)
branches = [
("temporary TPM increase requires approval", [0.92, 0.08], [0.94, 0.04, 0.02], [0.01, 0.02, 0.04, 0.20, 0.73]),
("all launch traffic is unlimited", [0.95, 0.05], [0.20, 0.16, 0.64], [0.0, 0.0, 0.04, 0.16, 0.80]),
]
scored = [(critique_score(r, s, u), text) for text, r, s, u in branches]
for score, text in scored:
print(f"{score:.3f} | {text}")
best_score, best_text = max(scored)
print(f"winner: {best_text} ({best_score:.3f})")0.922 | temporary TPM increase requires approval
0.534 | all launch traffic is unlimited
winner: temporary TPM increase requires approval (0.922)Distinguish true Self-RAG (a fine-tuned generator emitting reflection tokens inline[7]) from a prompted critique loop (application code calling an off-the-shelf LLM to grade passages and drafts). Prompted loops work immediately with frontier APIs; trained reflection tokens skip extra round-trips at the cost of hosting a custom model.
CRAG (Corrective RAG)
CRAG requires no generator retraining: a lightweight retrieval evaluator (fine-tuned T5-large in Yan et al.) scores each retrieved document and routes the set by its maximum score:[9]
- Correct (): Refine surviving internal documents and generate.
- Incorrect (): Discard internal hits and fall back to external search (or refuse if external search is disallowed).
- Ambiguous (): Refine internal hits, fetch external evidence, and merge both.

Before generation, CRAG runs decompose-then-recompose: split surviving passages into 1-to-3-sentence strips, drop strips below threshold , and recompose survivors in original order to cut boilerplate noise.[9]
import numpy as np
def crag_route(scores: list[float], lower: float = 0.2, upper: float = 0.7) -> str:
if not scores:
return "incorrect"
best = float(np.max(scores))
return "correct" if best > upper else ("incorrect" if best < lower else "ambiguous")
def refine_strips(docs: list[tuple[str, str]], keywords: set[str], limit: int = 6) -> list[tuple[str, str]]:
kept = []
for src, text in docs:
for sent in (s.strip() for s in text.split(".")):
if sent and (keywords & set(sent.lower().split())):
kept.append((src, sent))
return kept[:limit]
def run_crag(internal_docs, scores, public_docs, approved_public_query: str | None = None):
kw = {"quota", "tpm", "backoff"}
route = crag_route(scores)
ctx = refine_strips(internal_docs, kw) if route != "incorrect" else []
if route != "correct":
if not approved_public_query:
return "needs_internal_evidence", ctx
ext = refine_strips(public_docs, kw)
ctx = ctx[:3] + ext[:3] if ctx and ext else ctx + ext
return ("ready" if ctx else "no_evidence"), ctx[:6]
internal = [("internal:quota-v3", "TPM increases need approval. Old SDK install notes.")]
public = [("public:retry-v2", "Use exponential backoff after rate limits.")]
for label, scores in [("strong", [0.81, 0.15]), ("weak", [0.10, 0.17]), ("uncertain", [0.45, 0.09])]:
status, ctx = run_crag(internal, scores, public, approved_public_query="public retry guide")
print(f"{label:9s} ({crag_route(scores):9s}) -> {status}: {[s for s, _ in ctx]}")
print("private missing ->", run_crag([], [], public, approved_public_query=None))strong (correct ) -> ready: ['internal:quota-v3']
weak (incorrect) -> ready: ['public:retry-v2']
uncertain (ambiguous) -> ready: ['internal:quota-v3', 'public:retry-v2']
private missing -> ('needs_internal_evidence', [])Note that keyword strip filtering checks topic overlap rather than negation ("No TPM increase is permitted" matches "tpm" too); trained evaluators or cross-encoder rerankers handle polarity reliably.
Iterative retrieval, latency waterfalls, and failure modes
Self-RAG and CRAG still center on a single retrieval pass or one fallback step. When hop 2 depends on what hop 1 uncovers ("Which embedding endpoint had the highest p95 latency last week, and what retry budget applies to it?"), IRCoT (Interleaving Retrieval with Chain-of-Thought) alternates retrieval and reasoning one hop at a time until the evidence chain is complete.[10] If hop 1 returns ambiguous metrics, stop and surface the ambiguity rather than guessing an endpoint name.
A question needs two facts where the second cannot be searched until the first resolves. Why does naive RAG miss, and what replaces it?
Answer
Naive RAG executes a single search pass, so it cannot feed hop 1's discovered entity into hop 2's query. Iterative or agentic retrieval (such as IRCoT) interleaves search and reasoning so each hop guides the next.
Pick the lightest tier that resolves your measured failure:
| Feature | Naive RAG | HyDE | Self-RAG | CRAG |
|---|---|---|---|---|
| When retrieval runs | Always | Always | Dynamic ([Retrieve]) | Always |
| Search input | Raw query | Hypothetical passage | Raw query + partial draft | Raw query |
| Quality check | None | None (shifts query vector) | Inline reflection tokens | Separate retrieval evaluator |
| Extra training | None | None | Fine-tuned generator | Fine-tuned evaluator |
| Best fit | Direct single-fact lookups | Vocabulary/style mismatch | Strict-grounding custom serving | Uneven internal recall |
| Added work per turn | None | Proxy LLM call + embedding | On-demand retrieval + branching | Evaluator + strip filter (+ web) |
Every rewrite, proxy generation, or evaluator call extends time to first token (TTFT). Suppose an uncached serial rewrite-plus-rerank pipeline spends 120 ms rewriting, 20 ms embedding, 25 ms searching, 50 ms reranking, and 180 ms until the generator emits its first token: 395 ms total TTFT. Never estimate end-to-end p95 by summing per-stage p95s: because stalls in Stage A and Stage B land on different requests, sum durations per request first, then take the percentile:
from math import ceil
import numpy as np
def nearest_rank(values: np.ndarray, p: float) -> int:
return int(np.sort(values)[ceil(p * len(values)) - 1])
traces = [(10, 10)] * 18 + [(100, 10), (10, 100)]
a, b = np.array([x for x, _ in traces]), np.array([y for _, y in traces])
print(f"sum of stage p95s: {nearest_rank(a, 0.95) + nearest_rank(b, 0.95)} ms")
print(f"p95 of request totals: {nearest_rank(a + b, 0.95)} ms")sum of stage p95s: 20 ms
p95 of request totals: 110 msParallel fan-out amplifies tail latency too: three independent searches that each clear 25 ms with probability all finish within 25 ms only of the time, pushing 14.3% past 25 ms.
Guard five production failure modes:
- Prompt injection in rewrite history: Treat retrieved chunks and tool outputs strictly as data and enforce ACLs at the retriever.
- Cross-tenant cache bleed: Key rewrite and HyDE caches by
(tenant, scope, permission_version, history_digest, normalized_query, technique, model_version)and recheck permissions on hits. - SSRF on web fallback: Allowlist public domains, block private IPs, isolate fetches in a network sandbox, and require citations to stop SSRF and injected pages.
- Unbounded fan-out: Enforce hard per-request caps on variants, sub-queries, web fetches, and token budgets.
- Stacking stages blindly: Start with hybrid search + reranker; add HyDE, CRAG, or iterative loops only when held-out accuracy improves inside your end-to-end p95 budget.