Inferensys

Prompt

Synonym Expansion Failure Mode Analysis Prompt

A practical prompt playbook for diagnosing and categorizing production synonym expansion failures in RAG and search systems.
Developer building agentic RAG system, retrieval pipeline diagram on laptop, technical workspace with notes.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for diagnosing production synonym expansion failures.

This prompt is for RAG operators and search engineers who are diagnosing why a synonym expansion pipeline is degrading retrieval quality in production. The job-to-be-done is not generating synonyms, but analyzing a specific failure trace—a user query, the expanded terms that were produced, and the resulting retrieval outcome—to produce a categorized root-cause analysis. The ideal user has access to production logs, understands their retrieval architecture, and needs to move from 'recall dropped' to a concrete remediation ticket. Required context includes the original user query, the full set of expanded terms with any confidence scores or sources, the retrieval results before and after expansion, and the domain or taxonomy the system is expected to operate within.

Do not use this prompt for initial synonym generation, for evaluating expansion quality against a golden dataset, or for building the expansion prompt itself. Those are separate workflows covered by sibling playbooks in this pillar. This prompt is specifically for post-mortem analysis of a failure that has already occurred. It assumes you have a concrete trace to inspect. If you are still designing your expansion strategy or running offline evals, start with the Synonym Expansion Eval Check Prompt Template or the Synonym Expansion with Golden Query Set Evaluation Prompt instead. Using this failure analysis prompt without a real production trace will produce speculative categories that do not reflect actual system behavior.

The prompt requires a structured input payload—do not paste raw logs and expect the model to parse them reliably. Pre-process your trace into the [FAILURE_TRACE] placeholder fields: the original query, the expansion output, the retrieval results with relevance judgments, and any metadata about the retrieval backend and domain. The model will produce a categorized failure analysis with trace annotations and remediation suggestions. This output is designed to be consumed by an engineering team, not an end user, so it includes technical categories like over-expansion, term collision, domain mismatch, and context loss. After running the analysis, validate that each identified failure mode is backed by specific evidence from the trace before opening a remediation ticket.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Synonym Expansion Failure Mode Analysis Prompt delivers value and where it introduces risk. Use this to decide if the prompt fits your operational workflow before integrating it into a production RAG pipeline.

01

Good Fit: Post-Deployment Expansion Tuning

Use when: you have a live RAG system and need to diagnose why specific queries return poor results. This prompt excels at analyzing production traces where expansion logic is already in place. Guardrail: Feed it real query- expansion-result triples, not synthetic examples. The analysis is only as good as the production data it receives.

02

Good Fit: Pre-Release Expansion Regression Testing

Use when: you are changing synonym expansion prompts, models, or domain glossaries and need to catch new failure patterns before they hit users. Guardrail: Run this analysis against a golden query set with known-good expansions. Compare failure signatures across prompt versions to detect regressions early.

03

Bad Fit: Real-Time Query Rewriting

Avoid when: you need a prompt that rewrites queries in the hot path. This is a diagnostic prompt, not a rewriting prompt. It analyzes failures after they happen. Guardrail: Use the Synonym Expansion Prompt Template or Hybrid Synonym and Concept Expansion Prompt for runtime rewriting. Reserve this prompt for offline analysis and debugging.

04

Bad Fit: Replacing Retrieval Quality Metrics

Avoid when: you need quantitative precision-recall numbers. This prompt produces categorized failure descriptions and remediation suggestions, not statistical metrics. Guardrail: Pair this analysis with the Synonym Expansion Eval Check Prompt Template for quantitative measurement. Use the failure mode analysis to interpret metric drops, not to replace them.

05

Required Inputs: Trace Data with Ground Truth

What to watch: the prompt needs query strings, expansion outputs, retrieval results, and relevance judgments to produce useful analysis. Missing any of these degrades the output to speculation. Guardrail: Validate that each trace includes the original query, expanded terms, retrieved document IDs, and human or evaluator relevance labels before calling the analysis prompt.

06

Operational Risk: Analysis Drift Over Time

What to watch: failure patterns change as your corpus, user behavior, and expansion logic evolve. A one-time analysis becomes stale quickly. Guardrail: Schedule recurring analysis runs (weekly or per deployment) and track failure category distributions over time. Alert on sudden shifts in over-expansion or domain mismatch rates.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for diagnosing production synonym expansion failures with structured trace annotation and remediation guidance.

This prompt template is designed for RAG operators and search engineers who need to systematically analyze why a synonym expansion step degraded retrieval quality in production. It expects a specific failure trace as input and produces a categorized analysis identifying over-expansion, term collision, domain mismatch, and context loss patterns. The output includes a structured trace annotation schema and actionable remediation suggestions. Use this template when you have a concrete example of a query where expansion hurt recall or precision, not for general expansion quality monitoring.

text
You are a search quality analyst specializing in synonym expansion failure diagnosis for RAG systems.

Analyze the provided query expansion trace and identify the root cause of the retrieval degradation. Categorize the failure into one or more of the following patterns:
- **Over-Expansion**: Too many synonyms were added, diluting query intent or exceeding the retrieval engine's effective term budget.
- **Term Collision**: An expanded term matched a different concept in the target corpus, pulling in irrelevant documents.
- **Domain Mismatch**: The generated synonyms belong to a different domain, register, or context than the target knowledge base.
- **Context Loss**: The expansion ignored negation, temporal constraints, entity boundaries, or prior conversation context present in the original query.
- **Entity Corruption**: A recognized entity, proper noun, or product name was inappropriately replaced or expanded.

For each identified failure pattern, provide:
1. The specific expanded term or terms that caused the issue.
2. A brief explanation of the mechanism of failure.
3. A severity rating (CRITICAL, HIGH, MEDIUM, LOW).
4. A concrete remediation suggestion (e.g., add a stop-word, adjust a weight, introduce an entity guard, apply a domain constraint).

Annotate the original trace by marking each expansion term with its failure category and severity. Use the following annotation schema:
- `[OK]` for terms that did not contribute to the failure.
- `[FAIL:<CATEGORY>:<SEVERITY>]` for problematic terms.

Finally, provide a summary assessment with an overall severity and a prioritized list of remediation actions.

# INPUT

**Original Query:** [ORIGINAL_QUERY]

**Expanded Terms (with weights/scores):** [EXPANDED_TERMS]

**Retrieval Impact Evidence:** [RETRIEVAL_IMPACT]

**Domain Context (optional):** [DOMAIN_CONTEXT]

**Conversation History (optional):** [CONVERSATION_HISTORY]

# OUTPUT_SCHEMA

Return a JSON object with the following structure:
{
  "analysis": {
    "primary_failure_pattern": "string",
    "secondary_patterns": ["string"],
    "overall_severity": "CRITICAL|HIGH|MEDIUM|LOW",
    "summary": "string"
  },
  "failures": [
    {
      "term": "string",
      "category": "string",
      "severity": "string",
      "mechanism": "string",
      "remediation": "string"
    }
  ],
  "annotated_trace": [
    {
      "term": "string",
      "original_weight": number,
      "annotation": "OK|[FAIL:<CATEGORY>:<SEVERITY>]",
      "notes": "string"
    }
  ],
  "remediation_plan": [
    {
      "priority": number,
      "action": "string",
      "expected_impact": "string",
      "implementation_effort": "LOW|MEDIUM|HIGH"
    }
  ]
}

# CONSTRAINTS

- Do not invent failures. Only flag terms where the provided evidence supports a causal link to retrieval degradation.
- If the evidence is insufficient to determine a root cause, state that explicitly and suggest what additional data would be needed.
- Preserve all original terms in the annotated trace. Do not drop terms.
- Remediation suggestions must be actionable and specific to the failure mechanism. Avoid generic advice like "improve the prompt."
- If domain context is provided, use it to assess domain mismatch. If absent, note that domain mismatch assessment is limited.

To adapt this template, replace the square-bracket placeholders with your production data. [ORIGINAL_QUERY] should contain the exact user query that triggered the expansion. [EXPANDED_TERMS] should include the full list of generated synonyms with their associated weights or confidence scores. [RETRIEVAL_IMPACT] is the critical evidence field: provide before-and-after retrieval metrics, specific irrelevant documents that were pulled in, or user feedback indicating degradation. The [DOMAIN_CONTEXT] and [CONVERSATION_HISTORY] fields are optional but significantly improve diagnosis accuracy when available. For high-stakes production systems, always pair this analysis with a human review step before applying remediation changes to the expansion pipeline. The output JSON schema is designed to be machine-readable so you can aggregate failure patterns across multiple traces and identify systemic issues in your expansion strategy.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Synonym Expansion Failure Mode Analysis Prompt. Each variable must be populated before the prompt can produce a reliable failure analysis. Missing or malformed inputs are the most common cause of low-quality diagnostic output.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The original user query that was submitted to the retrieval system before any expansion was applied.

how do I reset my router password

Must be a non-empty string. Validate that the query is exactly as received, not a cleaned or normalized version. Truncation or sanitization before analysis hides root causes.

[EXPANDED_QUERY]

The full expanded query output produced by the synonym expansion prompt or pipeline, including all added terms, weights, and structure.

how do I reset my router password gateway login credentials wifi access point admin

Must include all expansion terms and any metadata the expansion prompt produced. If the expansion output is structured JSON, pass the raw object. Validate that this is the exact output, not a post-processed version.

[RETRIEVED_DOCUMENT_IDS]

A list of document identifiers returned by the retrieval system after executing the expanded query. Used to detect term collision and over-expansion patterns.

["doc-442", "doc-891", "doc-103", "doc-556", "doc-203"]

Must be an array of strings or integers. Validate that the list is ordered as returned by the retriever. An empty array is a valid signal and must be passed as [] not null.

[RELEVANCE_JUDGMENTS]

Ground-truth relevance labels for each retrieved document, indicating whether the document is actually relevant to the original user query.

{"doc-442": "relevant", "doc-891": "not_relevant", "doc-103": "relevant"}

Must be a map of document ID to label. Accepted labels: relevant, not_relevant, partially_relevant. Validate that every document ID in [RETRIEVED_DOCUMENT_IDS] has a judgment. Missing judgments cause the analysis to skip documents silently.

[DOMAIN_GLOSSARY]

A controlled vocabulary or taxonomy for the target domain, used to detect domain mismatch and term collision with unrelated concepts.

{"router": ["gateway", "access point"], "password": ["credentials", "passphrase"]}

Must be a JSON object mapping canonical terms to arrays of valid synonyms. If no glossary exists, pass an empty object {}. Validate that glossary terms are scoped to the domain; cross-domain glossaries produce false collision flags.

[EXPANSION_CONFIG]

The configuration parameters used by the synonym expansion prompt, including expansion strategy, max terms, confidence threshold, and any domain constraints.

{"strategy": "hybrid", "max_terms": 8, "confidence_threshold": 0.7, "domain": "consumer_networking"}

Must include at minimum the strategy field and confidence_threshold. Validate that the config matches what was actually used at runtime. Config mismatch between analysis and execution produces misleading failure attributions.

[SESSION_CONTEXT]

Prior conversation turns or session state available when the query was expanded, used to detect context loss and anaphora resolution failures.

"Previous turn: User asked about wifi connectivity issues. Agent suggested checking router settings."

Can be null if no session context existed. If provided, must be a string or structured object. Validate that the context is from the same session and timestamp as the query; stale context causes false context-loss flags.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the failure analysis prompt into a production RAG observability pipeline.

This prompt is not a real-time query rewriter. It is a diagnostic tool for operators and search engineers investigating why a specific synonym expansion degraded retrieval quality. The harness should be triggered by a monitoring alert—such as a recall drop, a spike in null results, or user-reported irrelevance—rather than called on every query. The prompt expects a structured trace object containing the original query, the expanded query, the retrieved document set, and relevance judgments. Without this trace data, the analysis will be speculative and low-value.

Wire the prompt into an incident review workflow or a scheduled batch analysis job. The input trace should be assembled from your retrieval logs, embedding the [ORIGINAL_QUERY], [EXPANDED_QUERY], [EXPANSION_TERMS] with their sources and confidence scores, [RETRIEVED_DOCUMENTS] with their ranks and scores, and [RELEVANCE_JUDGMENTS] (human or LLM-as-judge). Validate the trace object against the expected schema before calling the model. If the trace is incomplete, abort the analysis and log a data quality error rather than generating a misleading report. Use a low-temperature model setting (0.1–0.2) to ensure deterministic, repeatable failure categorization. The output should be parsed as JSON and validated against the [OUTPUT_SCHEMA]—specifically checking that each failure category includes at least one concrete example from the trace and that the remediation suggestions are actionable (e.g., 'add domain constraint to expansion prompt' rather than 'improve expansion').

Log every analysis result alongside the trace ID, model version, and prompt version for auditability. If the analysis flags a critical failure mode like semantic inversion from negation mishandling or entity collision, route the finding to a human review queue before applying any automated remediation. Do not use this prompt's output to automatically modify production expansion prompts or term weights without human approval. The remediation suggestions are advisory. The next step is to correlate failure patterns across multiple traces to identify systemic prompt or retrieval pipeline issues, then use the Synonym Expansion Eval Check Prompt to validate any proposed fix against your golden query set before deployment.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first in synonym expansion pipelines and how to guard against it.

01

Over-Expansion and Query Drift

What to watch: Adding too many synonyms dilutes the original intent, causing the retrieval system to return irrelevant documents that match expanded terms but miss the core question. Guardrail: Cap expansion terms per query (e.g., 5-7), apply a minimum relevance threshold, and run a semantic similarity check between the original and expanded query to detect drift before retrieval.

02

Term Collision and Entity Confusion

What to watch: Common words with domain-specific meanings (e.g., 'apple' the fruit vs. the company) get expanded with synonyms for the wrong sense, polluting results. Guardrail: Protect recognized named entities and domain terms from expansion. Use a provided entity list or glossary to lock terms before synonym generation, and flag ambiguous terms for disambiguation rather than expanding blindly.

03

Negation Scope Violation

What to watch: Expanding a negated term with a synonym inverts the user's exclusionary intent (e.g., 'without batteries' expands to 'without power cells' but also retrieves documents about power cells). Guardrail: Detect negation boundaries in the query before expansion. Exclude terms inside negation scope from synonym generation, or append explicit exclusion operators to expanded terms that fall within negated clauses.

04

Domain Mismatch and Jargon Gap

What to watch: General-purpose synonym models produce consumer-grade alternatives that don't match the target corpus vocabulary, so expanded queries still miss internal documents written in precise technical language. Guardrail: Ground expansion in a provided domain glossary, taxonomy, or controlled vocabulary. Validate expanded terms against the target corpus term frequency and flag terms with zero corpus matches.

05

Confidence Threshold Failures

What to watch: Low-confidence synonyms are included without scoring, injecting noise that degrades precision without improving recall. Guardrail: Require per-term confidence scores in the expansion output. Set a minimum confidence threshold (e.g., 0.7) and route low-confidence suggestions to a human review queue or discard them entirely in automated pipelines.

06

Context Loss in Conversational Queries

What to watch: Follow-up questions with anaphora or ellipsis (e.g., 'What about the other one?') are expanded without resolving the prior turn reference, producing synonyms for the wrong entity. Guardrail: Resolve session context before expansion. Inject the resolved entity or topic from prior turns into the query before generating synonyms, and validate that expanded terms align with the session topic.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality and safety of a synonym expansion failure mode analysis before deploying the prompt into a production RAG pipeline.

CriterionPass StandardFailure SignalTest Method

Failure Mode Coverage

Output identifies at least 3 distinct failure categories (e.g., over-expansion, term collision, domain mismatch) for the provided [QUERY] and [EXPANDED_TERMS].

Output lists only 1-2 categories or provides generic categories not specific to the input terms.

Run prompt on 10 known-bad expansion sets. Check that category count >= 3 and categories are input-specific.

Root Cause Attribution

Each identified failure is linked to a specific root cause from the [EXPANSION_TRACE] (e.g., source ambiguity, vector proximity error).

Failure descriptions are vague or attribute issues to 'model error' without trace evidence.

Parse output for trace references. Validate that each failure block cites a trace step ID or source field.

Severity Classification

Each failure is assigned a severity level (CRITICAL, HIGH, MEDIUM, LOW) consistent with the [SEVERITY_RUBRIC] provided.

Severity labels are missing, inconsistent with the rubric, or default to a single level for all failures.

Automated check: extract severity labels, map to rubric definitions, flag mismatches.

Remediation Suggestion Quality

Each failure includes a concrete, actionable remediation step (e.g., 'add stopword filter for term X', 'reduce traversal depth to 1').

Suggestions are generic ('improve the prompt'), missing, or impossible to execute without further clarification.

Human review of 5 analyses. Check that >80% of suggestions are specific and executable by an engineer.

Trace Annotation Schema Adherence

Output strictly conforms to the [OUTPUT_SCHEMA] JSON structure, including all required fields for each failure.

Output is missing required fields (e.g., 'failure_id', 'evidence_span'), or uses incorrect types.

Schema validation script. Run against 20 outputs. Pass standard: 100% schema compliance.

Hallucination Check

All cited terms, trace steps, and source identifiers exist in the provided [EXPANDED_TERMS] and [EXPANSION_TRACE] inputs.

Output references a term, step ID, or source that is not present in the input payload.

Automated diff: extract all referenced terms and IDs, check set membership against input. Flag any foreign keys.

Over-Expansion Detection Accuracy

Correctly flags terms that broadened the query scope beyond the original [USER_INTENT] with a precision >= 0.9.

Fails to flag a known over-expansion term from the golden test set, or flags a correct expansion as a failure.

Run against a golden set of 15 queries with pre-labeled over-expansion terms. Measure precision and recall.

Context Loss Identification

Identifies cases where original query constraints (e.g., negation, date ranges) were dropped or weakened during expansion.

Misses a dropped negation or date filter that is present in the [QUERY] but absent in [EXPANDED_TERMS].

Use 10 test cases with injected constraint drops. Check that output flags the missing constraint with a specific evidence span.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a small sample of known failure traces. Remove the structured trace annotation schema and ask for a free-text failure summary instead. Reduce the output to three categories: over-expansion, term collision, and context loss. Skip remediation suggestions.

Prompt modification

Replace [OUTPUT_SCHEMA] with: "Return a bulleted list of failure categories with one example each." Remove [TRACE_ANNOTATION_SCHEMA] entirely. Set [CONSTRAINTS] to: "Keep analysis under 300 words."

Watch for

  • Missing structured fields when you later need machine-readable output
  • Overly broad categorizations that merge distinct failure modes
  • No per-trace annotation, making it hard to map failures back to specific queries
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.