This prompt is for developers and QA engineers who have already captured a concrete flaky test failure signature—a stack trace, an assertion error, or a timeout message—and need to move from diagnosis to remediation. It is a diagnostic and prescriptive tool, not a root cause analysis engine. The job-to-be-done is generating a ranked list of concrete, code-level fix candidates, each mapped to a specific flakiness category (timing, assertion, cleanup, isolation, or concurrency) with a clear rationale. The ideal user has the failing test's source code and a representative failure log in hand and wants to short-circuit hours of manual debugging by getting structured, actionable suggestions.
Prompt
Flaky Test Automated Fix Suggestion Prompt

When to Use This Prompt
Understand the job-to-be-done, the ideal user, required inputs, and the boundaries where this prompt should not be applied.
Use this prompt when you have a known flaky test pattern and a captured failure signature. It is most effective for common categories of flakiness: race conditions in asynchronous waits, non-deterministic assertions on unordered collections or timestamps, test pollution from shared mutable state, and missing cleanup between cases. The prompt requires two mandatory inputs: the full test source code and the failure log. Without both, the suggestions will be speculative and low-quality. Do not use this prompt for initial flakiness discovery, for tests that have never failed, or for root cause analysis when the failure mechanism is completely unknown. It is also not a replacement for a full test suite audit; for that, use the Test Isolation Boundary Audit or Flaky Test Classification and Severity Triage prompts.
The output is a ranked list of fix suggestions, each containing a specific code change, the flakiness category it addresses, and a rationale. This output requires mandatory human review before any code is committed. The suggestions are fix candidates, not verified patches. A developer must evaluate each suggestion for correctness, potential side effects, and fit with the codebase's testing patterns. After review, apply the selected fix, run the test in a loop with order randomization and environment variance, and verify the fix using the Flaky Test Fix Verification Prompt Template. If the prompt produces low-confidence or irrelevant suggestions, the failure likely requires deeper root cause analysis using the Flaky Test Failure Log Analysis or Race Condition Hypothesis Generation prompts before returning here for fix generation.
Use Case Fit
Where the Flaky Test Automated Fix Suggestion Prompt works and where it introduces risk. Use these cards to decide whether this prompt fits your current workflow or whether you need a different approach.
Good Fit: Known Flaky Patterns
Use when: the flaky test exhibits a well-understood failure pattern such as fixed waits, missing cleanup, unordered collection assertions, or shared mutable state. Why it works: the prompt can map failure signatures to proven fix templates without requiring deep architectural reasoning.
Bad Fit: Novel Concurrency Bugs
Avoid when: the root cause involves a novel race condition, complex distributed system interaction, or infrastructure-level timing issue that has not been characterized. Risk: the prompt may suggest superficial fixes that mask rather than resolve the underlying defect, increasing future debugging cost.
Required Inputs
Minimum inputs: test code, failure log with stack trace, and execution context (environment variables, test order, parallelization settings). Without these: the prompt cannot distinguish between timeout-induced failures and logic failures, producing generic or incorrect fix suggestions.
Operational Risk: Blind Application
Risk: applying suggested fixes without human review can introduce new flakiness, reduce test coverage, or mask real regressions. Guardrail: every fix suggestion must pass through code review, local rerun verification, and a defined fix acceptance checklist before merge.
Operational Risk: Fix Drift
Risk: repeated automated fix suggestions can cause the test suite to drift away from its original intent, weakening assertions or removing valuable coverage. Guardrail: track fix history per test and periodically audit modified tests to confirm they still validate the original behavior.
When to Escalate Instead
Escalate when: the failure pattern does not match a known flaky test category, the fix suggestion introduces a new dependency, or the test covers a critical path where failure would block releases. Action: route to a senior developer for manual root cause analysis rather than relying on automated fix generation.
Copy-Ready Prompt Template
A ready-to-adapt prompt template that analyzes test code and failure signatures to suggest concrete, pattern-matched fixes for flaky tests.
This prompt template is designed to be dropped into your AI harness—whether that's a CLI tool, a CI/CD pipeline step, or an internal developer bot. It expects two primary inputs: the flaky test's source code and a representative failure log or signature. The model's job is not to guess, but to match the failure against known flaky test patterns (e.g., race conditions, fixed waits, shared mutable state, non-deterministic assertions) and propose a concrete, code-level fix. The output is a structured suggestion that a developer can review, test, and apply. Do not use this prompt for tests where the failure cause is unknown or the log is empty; it requires a failure signature to ground its analysis.
textYou are a senior test reliability engineer. Your task is to analyze a flaky test and propose a concrete, code-level fix. ## INPUT - Test Code:
[TEST_CODE]
code- Failure Log / Signature:
[FAILURE_LOG]
code- Additional Context (e.g., framework, known constraints): [CONTEXT] ## INSTRUCTIONS 1. Identify the most likely flaky test pattern from the failure log and test code. Use these categories: - Race Condition / Timing - Fixed Wait / Sleep - Non-Deterministic Assertion (e.g., unordered collection, timestamp, UUID, floating point) - Shared Mutable State / Test Pollution - External Dependency / Environment - Missing Cleanup / Data Leak 2. Explain *why* this pattern causes the observed failure, citing specific lines from the test code and log. 3. Propose a specific, actionable fix. Provide the modified code snippet. Prefer standard library or framework-native solutions (e.g., `await` conditions, `assertEventually`, ordered collections, test isolation fixtures). 4. If the fix requires a change outside the test file (e.g., a fixture, helper, or configuration), describe it explicitly. 5. Rate your confidence in the fix as HIGH, MEDIUM, or LOW. 6. If confidence is MEDIUM or LOW, list the additional information or experiments needed to increase confidence. ## OUTPUT SCHEMA Return a single JSON object with this exact structure: { "pattern_identified": "string", "explanation": "string", "suggested_fix": { "description": "string", "code_diff": "string", "external_changes": ["string"] }, "confidence": "HIGH" | "MEDIUM" | "LOW", "next_steps_if_uncertain": ["string"] } ## CONSTRAINTS - Do not invent failure causes not present in the log. - Do not suggest deleting the test unless it is truly redundant and that redundancy is provable from the input. - Prefer minimal, targeted fixes over broad refactors. - If the test uses a specific framework (e.g., Jest, pytest, JUnit), your fix must use that framework's idioms.
After pasting this template, replace [TEST_CODE] with the full source of the flaky test, [FAILURE_LOG] with the stack trace or error output from a failed CI run, and [CONTEXT] with any relevant details like the test framework, known environmental quirks, or links to related bugs. The output schema is strict JSON, making it straightforward to parse in an automated pipeline. The next step after receiving the suggestion is always human review: a developer should evaluate the proposed diff, run the test repeatedly to verify the fix, and ensure the change doesn't mask a deeper design problem. For high-risk code paths, consider requiring a second reviewer or running the fix through your full test suite with a flaky-test detector enabled.
Prompt Variables
Required and optional inputs for the Flaky Test Automated Fix Suggestion Prompt. Validate each input before calling the model to avoid garbage-in/garbage-out behavior and ensure the fix candidate is grounded in real failure evidence.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TEST_CODE] | Full source code of the flaky test method including imports, setup, teardown, and helper methods | def test_user_login(): ... | Must be non-empty and parseable as valid source code. Reject if only a test name or partial snippet is provided. |
[FAILURE_LOG] | Raw failure output from the test runner including stack trace, assertion error, and any stdout/stderr | AssertionError: expected 200 got 503 at test_api.py:42 | Must contain a stack trace or assertion message. Reject if log is empty or contains only a pass message. |
[EXECUTION_CONTEXT] | Environment details: CI platform, OS, test runner, parallelization settings, and any relevant configuration | GitHub Actions, ubuntu-latest, pytest-xdist with 4 workers | Must include test runner name and parallelization flag if applicable. Null allowed for local-only debugging. |
[FAILURE_FREQUENCY] | Number of failures and total runs in the recent execution window to establish flakiness rate | Failed 3 of last 10 runs on main branch | Must be a ratio or count pair. Reject if frequency is 100% (likely a deterministic failure, not flaky). |
[DEPENDENCY_MAP] | List of external services, databases, file systems, or network calls the test touches | ['postgres:test_db', 'redis:cache', 'stripe API mock'] | Must be a list. Null allowed if test has no external dependencies. Each entry should be a named resource. |
[ASSERTION_BLOCK] | The specific assertion or set of assertions that failed, extracted from the test code | assert response.status_code == 200 | Must match a line in [TEST_CODE]. Reject if the assertion cannot be located in the provided test source. |
[RECENT_CHANGES] | Diff or summary of recent code changes to the test file or the code under test within the last N commits | Changed wait from time.sleep(5) to time.sleep(2) in setup | Null allowed if no recent changes. If provided, must reference specific lines or commit hashes for traceability. |
Implementation Harness Notes
How to wire the flaky test fix suggestion prompt into a CI pipeline or developer workflow with validation, retries, and human review gates.
This prompt is designed to be called programmatically from a CI failure handler or a developer CLI tool, not as a one-off chat interaction. The harness should extract the failing test code and the relevant failure log snippet automatically from the test runner output (JUnit XML, JSON reports, or raw console logs) and inject them into the [TEST_CODE] and [FAILURE_LOG] placeholders. The [LANGUAGE] and [TEST_FRAMEWORK] fields should be derived from repository metadata or build configuration files to avoid manual entry errors. The prompt returns a structured JSON array of fix candidates, each with a fix_description, code_diff, confidence_score, and rationale field, which the harness must parse and validate before presenting to the developer.
Validation and Post-Processing: After receiving the model response, validate the JSON structure against a strict schema. Reject any fix candidate where code_diff does not apply cleanly to the original test code (use a dry-run patch application in a temporary checkout). Discard suggestions with confidence_score below a configurable threshold (default 0.7) or where the rationale does not reference specific lines or patterns from the failure log. For high-risk test suites (e.g., payment, auth, data integrity), route all suggestions with confidence below 0.9 to a manual review queue. Log every suggestion, the applied threshold, and the human decision (accepted, modified, rejected) to build a feedback dataset for future prompt tuning.
Model Choice and Retries: Use a model with strong code generation capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent). Set temperature to 0.1 for deterministic suggestions. If the model returns malformed JSON or fewer than the requested number of candidates, retry once with an explicit error message appended to the prompt: The previous response was invalid. Ensure the output is a valid JSON array with at least [MIN_CANDIDATES] objects matching the schema. Do not retry more than twice; escalate to a human with the raw failure context if the model cannot produce a valid response. Never automatically apply a suggested fix to the main branch. The harness must create a branch, apply the selected diff, and trigger the test suite to rerun N times (where N is configurable, typically 10-50) to verify the flakiness is resolved before a human merges the PR.
Expected Output Contract
The model must return a structured JSON object. Each field below must be present and pass the specified validation rule before the output is accepted by the application harness.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
fix_suggestions | Array of objects | Array length >= 1. Each element must be an object matching the fix_suggestion schema. | |
fix_suggestions[].id | String (kebab-case) | Must match pattern | |
fix_suggestions[].category | Enum string | Must be one of: | |
fix_suggestions[].description | String | Non-empty string between 20 and 500 characters. Must reference a specific line or code block from [TEST_CODE]. | |
fix_suggestions[].code_diff | String (unified diff) | Must be a valid unified diff format string. Must apply cleanly to [TEST_CODE] when tested with | |
fix_suggestions[].confidence | Number (0.0-1.0) | Must be a float between 0.0 and 1.0 inclusive. Values below 0.7 require human review before application. | |
fix_suggestions[].requires_human_review | Boolean | Must be | |
fix_suggestions[].failure_signature_match | String or null | If [FAILURE_SIGNATURE] is provided, must quote the specific substring matched. Otherwise must be |
Common Failure Modes
Flaky test fix prompts fail in predictable ways. Here are the most common failure modes, why they happen, and how to guard against them before shipping the prompt into a CI pipeline or developer workflow.
Hallucinated Fixes Without Evidence
What to watch: The model confidently suggests a fix pattern (e.g., 'add a waitFor selector') that doesn't exist in the test framework or codebase. It invents API methods, assertion matchers, or cleanup hooks that look plausible but won't compile. Guardrail: Require the prompt to cite specific line numbers and existing imports before suggesting new calls. Add a post-generation validation step that checks suggested methods against the framework's actual API surface.
Overfitting to a Single Failure Signature
What to watch: The prompt sees a timeout stack trace and suggests increasing the timeout constant without checking whether the root cause is a missing wait condition, a slow CI worker, or a resource leak from a prior test. The fix masks the symptom instead of resolving the cause. Guardrail: Include a differential diagnosis step in the prompt that requires the model to list at least two alternative root causes before selecting a fix. Weight fixes that address root causes over symptom suppression.
Ignoring Test Isolation Boundaries
What to watch: The prompt suggests adding cleanup or reset logic that modifies shared state in a way that breaks other tests in the suite. The fix passes in isolation but introduces new flakiness downstream. Guardrail: Include the test file's setup/teardown blocks and any shared fixture files in the prompt context. Add an explicit constraint: 'Do not modify shared state that other tests depend on without flagging the change for suite-wide impact review.'
Race Condition Misdiagnosis as Timeout
What to watch: The failure log shows a timeout, but the actual cause is a race condition where two async operations complete in an unexpected order. The prompt suggests a longer wait, which reduces failure frequency but doesn't eliminate the race. Guardrail: Require the prompt to analyze execution order from logs before classifying the failure. If ordering is non-deterministic, the fix must address synchronization (e.g., await ordering, Promise.all, event sequencing), not timing.
Environment-Specific Fixes That Break in CI
What to watch: The prompt suggests a fix that works locally (e.g., relying on a file path, env var, or service that exists on the developer's machine) but fails in the CI environment where those dependencies are absent or configured differently. Guardrail: Include CI environment configuration in the prompt context. Add a constraint: 'Any fix that introduces a dependency on local state must include a fallback or explicit CI configuration check.' Validate suggested fixes against a CI environment spec before merging.
Assertion Weakening Instead of Hardening
What to watch: The prompt suggests relaxing an assertion (e.g., changing exact equality to approximate match, or removing a timing-sensitive check) to make the test pass reliably. This reduces test value and lets real regressions slip through. Guardrail: Add a constraint that assertion changes must preserve or increase test specificity. If a timing-sensitive assertion is genuinely flaky, the fix must replace it with a deterministic equivalent (e.g., wait for state, then assert), not remove the check.
Evaluation Rubric
Use this rubric to evaluate the quality of fix suggestions before merging or applying them. Each criterion maps to a concrete pass standard, a failure signal, and a test method that can be automated in CI or run manually during code review.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Fix Pattern Match | Suggested fix matches a known flaky test pattern (wait condition, cleanup, assertion hardening, isolation) with explicit reference to the pattern name | Fix is generic ('add retry', 'increase timeout') without linking to a specific pattern or the pattern is misapplied to the wrong failure signature | Pattern classification check: compare suggested fix category against failure log classification from [FAILURE_CATEGORY] input |
Code Applicability | Suggested code change applies to the exact test file and line range referenced in the failure log; no unrelated files or methods are modified | Fix modifies helper functions, shared fixtures, or unrelated test files without justification; fix targets lines not present in the stack trace | Diff scope validation: verify all modified lines fall within [FAILURE_STACK_TRACE] file paths and line ranges |
Root Cause Addressing | Fix addresses the root cause identified in [ROOT_CAUSE_HYPOTHESIS], not just the symptom; explanation connects the code change to the failure mechanism | Fix suppresses the symptom (e.g., wraps assertion in try-catch, increases timeout without analyzing why timing varies) without resolving the underlying race, leak, or dependency | Causal chain check: trace the fix logic from code change through failure mechanism to expected stable behavior; flag if any link is missing |
Non-Determinism Elimination | Fix removes the source of non-determinism: replaces fixed waits with await conditions, sorts unordered collections before assertion, mocks time sources, or isolates shared state | Fix preserves non-deterministic behavior (e.g., retains Thread.sleep, keeps unordered list comparison, leaves random seed unseeded) and relies on probability of passing | Determinism audit: scan suggested code for known non-deterministic patterns (sleep, random, unordered comparison, system clock dependency) and flag any that remain |
Isolation Guarantee | Fix ensures the test does not depend on execution order, shared mutable state, or side effects from other tests; cleanup is added if state leakage was the cause | Fix adds state that persists beyond test teardown, relies on test execution order, or assumes a specific database row ID or global variable value set by another test | Isolation check: verify suggested code includes proper setup/teardown, does not read unowned state, and passes a randomized-order test run simulation |
Regression Risk | Fix is scoped to the flaky test only and does not alter production code paths, shared test utilities, or CI configuration without explicit approval flag | Fix modifies production code to accommodate test timing, changes shared test base classes, or alters CI parallelism settings as a side effect | Blast radius check: verify diff touches only the target test file; if shared code is modified, require [HUMAN_APPROVAL] flag and separate review |
Verification Completeness | Fix includes or references a verification plan: number of reruns, environment variance, order randomization, and acceptance threshold for declaring the fix successful | Fix has no verification guidance; assumes a single green run is sufficient; no mention of rerun count or stress conditions | Verification plan presence check: confirm output includes [VERIFICATION_PLAN] with explicit rerun count, randomization flags, and pass threshold |
Human Review Readiness | Fix is presented with clear before/after diff, rationale summary, confidence score, and explicit flag for any assumption that needs human validation | Fix is presented as authoritative without uncertainty markers; hides assumptions about environment state or test behavior; confidence is overclaimed | Reviewability check: verify output contains [CONFIDENCE_SCORE], [ASSUMPTIONS] list, and [HUMAN_REVIEW_REQUIRED] boolean; flag if confidence is high but assumptions are unvalidated |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Start with the base prompt and a single test file. Replace [TEST_CODE] with the flaky test source and [FAILURE_SIGNATURE] with the stack trace or error message. Skip structured output enforcement initially—accept a plain text suggestion list. Run 5–10 known flaky tests through the prompt manually and review whether the suggested fixes are directionally correct.
Watch for
- The model suggesting
sleep()or fixed waits instead of proper wait conditions - Overly broad refactors that touch unrelated test logic
- Suggestions that would weaken assertions rather than harden them
- No indication of confidence or uncertainty in the fix candidate

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us