Mental model
A production query understanding layer raises retrieval recall on vague, conversational, or multi-part questions by resolving pronouns, expanding internal acronyms, decomposing compound queries, and routing intents to specialized indexes—while strictly preserving user negations, exact IDs, metadata filters, and immutable raw-to-rewritten audit traces.
Learning outcomes
- Combine fast deterministic normalization (acronym lookup, exact SKU/error-code regexes) ahead of bounded LLM rewriting or HyDE expansion.
- Route queries selectively across heterogeneous backends (SQL/metrics warehouse, AST code search, hybrid policy docs) with low-latency fallbacks.
- Preserve strict negation predicates, time ranges, and exact identifiers while tracing every rewrite step for debugging.
Theory
Real enterprise queries rarely arrive cleanly phrased for BM25 or dense embeddings: users type "why did Q3 APAC renewals drop compared to last year without EU exclusions?" or "ERR-4092 timeout after upgrade". Passing an un-rewritten pronoun query ("does it apply in Germany?") loses retrieval recall, whereas unleashing an unconstrained LLM rewriter often deletes exact error tokens (ERR-4092), flips without EU into positive EU, or invents nonexistent product versions. Production routers organize query transformation as a constrained multi-stage pipeline:
| Transformation Technique | Latency Tax | Best Problem Class | Mandatory Guardrail |
|---|---|---|---|
| Deterministic Regex + Acronym Map | < 2 ms | Exact ticket codes, error strings, known org acronyms | Bypass neural rewrite entirely on exact ID lookup |
| Conversational Coreference Rewrite | 150–350 ms | Follow-up turns ("what about tier 2 limits?") | Inject only bounded last 2–3 turns; emit structured JSON filters |
| Multi-Query / Step-Back Split | 200–450 ms | Compound comparisons ("compare SOC2 vs HIPAA retention") | Cap sub-queries <= 3; execute concurrently behind global timeout |
| Store / Metadata Router | 5–250 ms | Structured SQL vs. code symbol index vs. hybrid prose corpus | Retain dual-route fallback onto general docs when confidence < 0.7 |
pythonimport refrom dataclasses import dataclassEXACT_ID_RE = re.compile(r"\b(?:ERR-\d+|INC-\d+|CVE-\d{4}-\d+)\b")DOMAIN_GLOSSARY = {"k8s": "Kubernetes","kv": "key-value cache","soc2": "SOC 2 Type II compliance",}@dataclass(frozen=True)class QueryPlan:raw_query: strlocked_tokens: tuple[str, ...]expanded_queries: tuple[str, ...]target_stores: tuple[str, ...]exclude_terms: tuple[str, ...]def plan_deterministic_query(raw_query: str) -> QueryPlan:"""Lock exact identifiers and negations cleanly before invoking optional neural expansion."""locked = tuple(EXACT_ID_RE.findall(raw_query))negations = tuple(re.findall(r"\b(?:without|excluding|not)\s+([A-Za-z0-9_-]+)", raw_query, flags=re.I))tokens = raw_query.split()expanded_words = [DOMAIN_GLOSSARY.get(tok.lower(), tok) for tok in tokens]glossary_query = " ".join(expanded_words)stores: list[str] = ["hybrid_docs"]if locked:stores.insert(0, "incident_exact_bm25")if any(k in raw_query.lower() for k in ("revenue", "latency p95", "count", "how many")):stores.append("metrics_sql_warehouse")candidates = [raw_query]if glossary_query != raw_query:candidates.append(glossary_query)return QueryPlan(raw_query=raw_query,locked_tokens=locked,expanded_queries=tuple(dict.fromkeys(candidates)),target_stores=tuple(dict.fromkeys(stores)),exclude_terms=negations,)
Trade-offs
LLM-based query decomposition and hypothetical document embeddings (HyDE) deliver large recall gains on underspecified conceptual queries and ambiguous cross-document comparisons, yet add 200–500 ms TTFT overhead ahead of vector retrieval and risk drifting away from terse literal identifiers. Deterministic dictionary expansion plus fast structured small-model routing adds minimal latency (< 80 ms) and guarantees zero identifier mutation, while failing when conversational intent genuinely shifts mid-thread across implicit topics. Always running the literal original raw_query cleanly alongside any neural sub-queries guarantees deterministic lexical precision never regresses.
Failure modes and misconceptions
- Dropping Negations and Metadata Predicates: Summarizing
"policies excluding contractor accounts after 2025"into"contractor account policies"retrieves strictly false-positive matches. - Rewriting Exact Identifiers: Neural query expanders routinely normalize
SKU-884AorERR-4092into generic English phrases, breaking sparse BM25 exact matching. - Unbounded Sub-Query Fan-Out: Letting an agent emit 10 parallel sub-queries per turn multiplies vector DB load
10xand overflows context budgets with redundant paragraphs. - Opaque Trace Loss: Logging only rewritten queries hides why downstream synthesis hallucinated; traces must store raw input, extracted filters, and per-route rank contributions.
Decision scenario
An internal developer portal mixes Jira incident tickets (INC-1042), structured latency telemetry SQL tables, and Markdown runbooks. Users report that queries containing exact kernel flags or "excluding staging" frequently miss obvious runbooks. Architect a deterministic-first query planner locking identifiers and negations before selective sub-query decomposition.
What constraints and trace artifacts must be preserved whenever a query rewriting layer modifies user input before retrieval?