This prompt is designed for reliability engineers, test infrastructure teams, and developers who are responsible for maintaining the stability of a continuous integration pipeline. The job-to-be-done is to move from a raw signal—a flaky test failure log—to a concrete, actionable root cause hypothesis and a code repair suggestion. The ideal user has access to the test's source code, its recent change history, and the execution logs from multiple runs, including both passing and failing instances. The prompt works by forcing the model to correlate failure patterns with timing, test ordering, and state dependencies, rather than just paraphrasing the error message.
Prompt
Flaky Test Diagnosis and Repair Prompt

When to Use This Prompt
Define the job, the required inputs, and the operational boundaries for diagnosing and repairing flaky tests with an AI coding agent.
You should use this prompt when a test exhibits non-deterministic behavior that cannot be immediately explained by a single code change. It is most effective when you can provide a rich [CONTEXT] that includes the test code, the code it is testing, and structured failure logs with timestamps. Do not use this prompt for deterministic test failures that are clearly caused by a known breaking change; those are better served by a standard debugging workflow. This prompt is also not a replacement for a flaky test quarantine system—it is a diagnostic tool to repair a test that has already been flagged, not a detector for identifying which tests are flaky in the first place.
Before executing this prompt, ensure you have assembled the necessary evidence. The model will need to reason about state leakage, race conditions, and external dependency instability. If you cannot provide multi-run logs or the relevant source code, the output will be speculative and low-value. The next step after receiving the diagnosis is to treat the model's output as a hypothesis to be validated, not a patch to be blindly applied. You should run the suggested repair locally, verify it against the historical failure logs, and ensure it does not weaken the test's assertion strength.
Use Case Fit
Where the Flaky Test Diagnosis and Repair Prompt works, where it fails, and what you must provide before trusting the output.
Good Fit: CI Signal with Rich Artifacts
Use when: you have a test that fails intermittently in CI, and you can provide the failing test code, recent production logs, and the stack trace. Why: the model needs concrete failure evidence to correlate timing, ordering, and state dependencies rather than guessing from the test name alone.
Bad Fit: Environment-Specific Heisenbugs
Avoid when: the failure only reproduces in a specific staging environment with external dependencies that are not described in code or logs. Risk: the model will hallucinate a plausible root cause based on code patterns without access to the live dependency state, leading to an incorrect fix that masks the real issue.
Required Input: Failure Corpus
Mandatory: at least three failure logs from separate runs, the test source code, and any shared fixtures or setup helpers. Why: a single failure is noise; a pattern across multiple runs reveals whether the root cause is ordering, timing, shared state, or environmental drift. Without a corpus, the diagnosis is speculation.
Required Input: Green-Run Baseline
Mandatory: a passing run log from the same test under similar conditions. Why: the model needs to contrast the passing execution path against the failing path to isolate the divergence point. Without a baseline, the prompt cannot distinguish a flaky test from a consistently broken one.
Operational Risk: Suggested Fix Introduces New Flakiness
What to watch: the model proposes a fix that adds sleep() calls, loosens assertions, or reorders tests without addressing the underlying state leak. Guardrail: require the output to explain the root cause before proposing a fix, and run the repaired test in a loop (e.g., --repeat=50) before merging.
Operational Risk: Diagnosis Without Codebase Context
What to watch: the model blames a helper function or fixture without seeing its implementation because the prompt only included the test file. Guardrail: always include the full call graph of shared fixtures, database seeds, and mock setups referenced by the failing test. If the codebase is too large, use a repository exploration prompt first to assemble the relevant context.
Copy-Ready Prompt Template
A reusable prompt template for diagnosing flaky tests, ready to be copied, adapted, and wired into your test reliability pipeline.
This prompt template is designed to be the core instruction set you send to an AI coding agent. It forces structured reasoning about failure patterns, timing dependencies, and state corruption—the three most common root causes of flaky tests. The square-bracket placeholders are intentional injection points for your application to supply the specific test log, relevant code diffs, and execution history before each run. Do not treat this as a static prompt; it must be hydrated with real data from your CI system to be effective.
codeYou are a senior reliability engineer specializing in test infrastructure. Your task is to diagnose a flaky test and propose a concrete, safe repair. ## INPUT **Test Log (failed run):** [FAILED_TEST_LOG] **Test Log (recent passing run, if available):** [PASSING_TEST_LOG] **Test Source Code:** [TEST_SOURCE_CODE] **Code Under Test (relevant diff or full file):** [CODE_UNDER_TEST] **Execution Environment:** - CI Runner OS: [RUNNER_OS] - Test Framework & Version: [TEST_FRAMEWORK] - Parallelism Settings: [PARALLELISM_CONFIG] **Recent Git History for relevant files:** [GIT_LOG] ## CONSTRAINTS - Do not suggest adding arbitrary `sleep()` or fixed-time waits. - Do not weaken assertions to make the test pass. - Prefer fixes that address the root cause (ordering, state leakage, time dependency) over retry mechanisms. - If the root cause is in production code, flag it clearly and do not suggest masking it in the test. - If insufficient data is available, state what specific information is missing instead of guessing. ## OUTPUT SCHEMA Respond in strict JSON with the following structure: { "diagnosis": { "root_cause_category": "RACE_CONDITION | STATE_LEAKAGE | TIME_DEPENDENCY | EXTERNAL_SERVICE | INFRASTRUCTURE | UNKNOWN", "confidence": "HIGH | MEDIUM | LOW", "summary": "A concise, evidence-backed explanation of the failure mechanism.", "evidence": ["List of specific log lines, code patterns, or timing signals that support the diagnosis."] }, "repair": { "target": "TEST_CODE | PRODUCTION_CODE | INFRASTRUCTURE | TEST_DATA", "description": "A step-by-step repair plan.", "code_fix": "A unified diff or code block showing the exact change, or null if no code fix is applicable.", "risk_of_fix": "LOW | MEDIUM | HIGH", "verification_steps": ["Steps to validate the fix prevents the flake without introducing new issues."] }, "requires_human_review": true or false, "missing_information": ["List of data points that would increase diagnostic confidence, or an empty array."] }
To adapt this template, start by mapping your CI system's output to the [FAILED_TEST_LOG] and [PASSING_TEST_LOG] placeholders. The [CODE_UNDER_TEST] should be populated by a git diff between the current failing commit and the last stable commit for that test file. The strict JSON output schema is non-negotiable; it allows your harness to parse the diagnosis programmatically and route a requires_human_review: true response to an on-call engineer while auto-applying low-risk test code fixes. Before deploying, run this prompt against a golden dataset of 10–20 previously diagnosed flaky tests to calibrate the confidence and risk_of_fix accuracy.
Prompt Variables
Required inputs for the Flaky Test Diagnosis and Repair Prompt. Each variable must be populated before execution to ensure reliable root-cause analysis and actionable repair suggestions.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TEST_FAILURE_LOG] | Raw output from the test runner showing the failure, including stack traces, assertion errors, and timestamps. | FAIL: test_user_login (tests/auth/test_session.py:142) AssertionError: Expected 200, got 503 Runtime: 2.3s | Must contain at least one stack trace or assertion error. Null or empty input should abort the prompt and return an error. Validate with regex for common test framework output patterns (pytest, JUnit, Jest). |
[TEST_CODE] | The full source code of the failing test case, including setup, teardown, and any shared fixtures or helpers it calls. | def test_user_login(db_session): user = create_test_user(db_session) client = TestClient(app) response = client.post('/login', json={'email': user.email, 'password': 'test123'}) assert response.status_code == 200 | Must be parseable source code. If the file path is provided instead of inline code, the harness must read the file before calling the model. Validate that the function name matches the failure log. |
[RECENT_CODE_CHANGES] | A unified diff of recent commits to the repository, filtered to files that the failing test depends on or imports. | diff --git a/src/auth/session.py b/src/auth/session.py @@ -45,7 +45,7 @@ def create_session(user_id):
| Must be a valid unified diff. If empty, the model should note the absence of recent changes as a signal. Validate that the diff applies cleanly to the target branch to avoid hallucinated context. |
[TEST_EXECUTION_HISTORY] | A structured log of the last N runs of this specific test, including pass/fail status, duration, and the CI environment or machine ID. | Run 1: PASS (2.1s) on ci-worker-3 Run 2: FAIL (2.3s) on ci-worker-3 Run 3: PASS (2.0s) on ci-worker-1 Run 4: FAIL (2.4s) on ci-worker-3 | Must include at least 3 runs to establish a pattern. If fewer than 3 runs are available, the model should flag low confidence. Validate that timestamps are sequential and durations are positive numbers. |
[DEPENDENCY_GRAPH] | A mapping of the failing test's dependencies: functions it calls, fixtures it uses, and external services it touches. | { 'test_user_login': { 'calls': ['create_test_user', 'app.test_client'], 'fixtures': ['db_session'], 'external': ['POST /login', 'database: users table'] } } | Must be a valid JSON object. If generated automatically, validate that all referenced functions exist in the codebase. Null is allowed if the graph cannot be constructed, but the model must note this as a limitation. |
[ENVIRONMENT_CONFIG] | The runtime configuration for the environment where the failure occurred, including database versions, feature flags, and resource limits. | Database: PostgreSQL 15.2 Python: 3.11.4 Feature Flags: new_auth_flow=enabled CPU Limit: 2 cores Memory Limit: 4GB | Must be a non-empty string or structured key-value object. Validate that critical fields (database type, language version) are present. If the failure is environment-specific, missing config will degrade diagnosis quality. |
[KNOWN_FLAKY_PATTERNS] | A library of previously identified flaky test patterns in this codebase, used to match against the current failure. | [ {'pattern': 'database connection pool exhaustion', 'signature': 'OperationalError: too many connections'}, {'pattern': 'race condition on user creation', 'signature': 'IntegrityError: duplicate key value violates unique constraint'} ] | Must be a valid JSON array. Can be empty if no patterns are cataloged. Validate that each entry has a 'pattern' and 'signature' field. The model should prioritize matching known patterns before generating novel hypotheses. |
[REPOSITORY_CONTEXT] | A summary of the repository structure, testing conventions, and any relevant architectural notes that inform repair suggestions. | This project uses pytest with fixtures defined in conftest.py. Database sessions are scoped to 'function' and use transactional rollback. CI runs tests in parallel with 4 workers. Shared state between tests is discouraged. | Must be a non-empty string. If unavailable, the model should request it or note reduced confidence in repair suggestions. Validate that the context includes testing framework and concurrency model. |
Implementation Harness Notes
How to wire the flaky test diagnosis prompt into a CI/CD pipeline or investigation workflow with validation, retries, and human review.
This prompt is designed to be called programmatically as part of an automated flaky test investigation pipeline, not as a one-off chat interaction. The typical integration point is a CI/CD webhook or a scheduled job that triggers when a test suite exhibits non-deterministic failures. The harness should collect the required inputs—the failing test log, the test source code, recent git diff for the test file and its dependencies, and a history of recent execution results for the same test—and assemble them into the [TEST_LOG], [TEST_CODE], [RECENT_DIFF], and [EXECUTION_HISTORY] placeholders. Because flaky test diagnosis is sensitive to timing and ordering, the harness must ensure that the execution history includes timestamps and enough context to correlate failures with external state changes.
Wire the prompt into an application using a structured LLM call with a defined output schema. The expected output is a JSON object containing a root_cause_category enum (RACE_CONDITION, ORDERING_DEPENDENCY, EXTERNAL_STATE_LEAK, TIMING_SENSITIVITY, NON_DETERMINISTIC_INPUT, INFRASTRUCTURE_FLAKE, UNKNOWN), a confidence_score between 0.0 and 1.0, a diagnosis_summary string, and a suggested_fix object with description and code_patch fields. Validate the output against this schema immediately. If the model returns an invalid root_cause_category or a missing code_patch when one is expected, retry with a repair prompt that includes the validation error. Log every diagnosis attempt—including the prompt version, model, input hashes, raw output, and validation result—so that diagnosis accuracy can be audited over time.
For high-risk codebases where a misdiagnosis could lead to a bad production deploy, route all diagnoses with a confidence_score below 0.7 or a category of UNKNOWN to a human review queue. The harness should create a ticket or notification with the full prompt context and the model's output, allowing a reliability engineer to accept, reject, or refine the diagnosis. Avoid applying suggested code patches automatically unless the test suite is strictly non-critical and the patch is limited to test code only. Even then, require that the patched test passes N consecutive runs (where N is configurable, defaulting to 10) in an isolated environment before the change is merged. The most common production failure mode is a diagnosis that correctly identifies a symptom—like a test that fails after 500ms—but misattributes the root cause to a hardcoded timeout when the real issue is a slow CI runner, so always correlate the model's output with infrastructure metrics before acting.
Expected Output Contract
Defines the required fields, types, and validation rules for the structured JSON output of the Flaky Test Diagnosis and Repair prompt. Use this contract to parse and validate the model's response before integrating it into your CI/CD pipeline or ticketing system.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
diagnosis_id | string (UUID v4) | Must match UUID v4 regex pattern. Generate a new one if missing. | |
test_identifier | string | Must match the format of a fully qualified test name from the input log (e.g., 'path/to/test_file.py::TestClassName::test_method_name'). | |
root_cause_category | enum string | Must be one of: 'RACE_CONDITION', 'ORDER_DEPENDENCY', 'STATE_LEAK', 'TIMING_ASSUMPTION', 'NETWORK_FLAKE', 'DATA_CONTENTION', 'ENVIRONMENT_DRIFT', 'UNKNOWN'. Reject any other value. | |
confidence_score | number (0.0 - 1.0) | Must be a float between 0.0 and 1.0 inclusive. If the model outputs a percentage or integer, normalize it. If missing, set to null and flag for human review. | |
evidence_log_snippets | array of strings | Each string must be a verbatim line or block copied from the provided failure log. If the array is empty, the diagnosis must be rejected as ungrounded. | |
state_dependency_hypothesis | string or null | If root_cause_category is 'STATE_LEAK' or 'ORDER_DEPENDENCY', this field is required and must be a non-empty string. Otherwise, it must be null. | |
suggested_code_fix | object | Must contain 'file_path' (string) and 'patch_hunk' (string). 'patch_hunk' must be valid unified diff format. If no fix is possible, 'patch_hunk' must be an empty string and a 'rationale' field must be present. | |
requires_human_approval | boolean | Must be true if confidence_score < 0.8 or root_cause_category is 'UNKNOWN'. Otherwise, can be false. A false value here does not bypass organizational review policies. |
Common Failure Modes
Flaky test diagnosis prompts fail in predictable ways. These are the most common failure modes, why they happen, and how to guard against them before the prompt reaches production.
Correlation Mistaken for Causation
What to watch: The model attributes flakiness to the most visible recent change (a code diff, a dependency bump) without evidence that the change actually causes the non-determinism. Guardrail: Require the prompt to list alternative hypotheses and explicitly ask for evidence that would rule out each one. Pair with a second pass that critiques the initial causal claim.
Ignoring Ordering and State Dependencies
What to watch: The model focuses on assertion logic but misses that the test fails only when run after a specific other test, or when a shared fixture is in a dirty state. Guardrail: Include test execution order and shared resource access in the required analysis context. Add a checklist item: 'Does this failure depend on test execution order or mutable shared state?'
Overfitting to a Single Log Sample
What to watch: The prompt receives one failure log and produces a plausible but wrong diagnosis that doesn't hold across other failure instances. Guardrail: Require multiple failure logs as input. Instruct the model to identify patterns that are consistent across failures and flag any diagnosis that only fits one sample.
Proposing a Fix That Introduces New Flakiness
What to watch: The suggested repair replaces one source of non-determinism with another—adding arbitrary timeouts, changing assertion tolerance without justification, or introducing retries that mask real failures. Guardrail: Add a constraint: 'For any proposed fix, explain what new failure modes it could introduce and why the trade-off is acceptable.' Require a deterministic alternative before accepting a timing-based fix.
Missing Async and Concurrency Root Causes
What to watch: The model treats a race condition, deadlock, or async timing issue as a logic error because it doesn't reason about concurrent execution. Guardrail: Explicitly instruct the model to check for async patterns, promise handling, thread safety, and event loop behavior. Include concurrency primitives from the codebase in the analysis context.
Hallucinating Non-Existent Test Infrastructure
What to watch: The model invents test hooks, mocking utilities, or framework features that don't exist in the actual codebase, producing a repair that can't be implemented. Guardrail: Ground every suggested repair in the actual test framework, mocking library, and helper utilities found in the repository. Require the model to cite the specific import or API it intends to use.
Evaluation Rubric
Use this rubric to evaluate the quality of a flaky test diagnosis and repair output before merging the suggested fix. Each criterion targets a specific failure mode common in automated test repair.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Root Cause Identification | Output identifies a specific root cause category (e.g., race condition, test ordering dependency, network timeout) with supporting evidence from logs or code. | Output provides only a generic symptom description (e.g., 'test failed') or blames the test runner without evidence. | Parse output for a root cause label and verify it is backed by at least one log line, timestamp, or code reference. |
Repair Determinism | The suggested code change eliminates non-deterministic waits (e.g., fixed sleep) and replaces them with deterministic synchronization (e.g., polling, callbacks, or mocks). | The repair introduces a new fixed | Scan the suggested diff for |
State Isolation | The repair ensures the test does not depend on shared mutable state from other tests. It includes explicit setup or teardown logic to reset the environment. | The test reads from a global variable, static field, or database table that is not reset in a | Check the diff for missing setup/teardown blocks if the root cause involves shared state. Verify no cross-test dependencies remain. |
Assertion Stability | Assertions are relaxed to be order-independent or time-tolerant where appropriate, or tightened to check specific invariants rather than exact system state. | The repair weakens an assertion to | Review the assertion diff. Flag any removed assertions or assertions that now trivially pass regardless of system behavior. |
Resource Cleanup | The repair includes explicit cleanup of files, database records, or network connections in a | The test creates resources without corresponding deletion logic, causing subsequent runs to fail due to naming conflicts or resource exhaustion. | Trace resource creation calls in the diff. Confirm a corresponding deletion or cleanup call exists and is executed on both success and failure paths. |
Time and Ordering Robustness | The test logic is robust to slow CI environments. It uses dynamic timeouts or event-driven triggers instead of assuming execution speed. | The test passes locally but fails in CI. The repair does not address the CI-specific timing constraint (e.g., a hardcoded 1-second timeout). | Simulate a slow environment by mocking a delayed response. The test should still pass if the repair is correct. |
Mock Fidelity | Mocks simulate the specific failure mode identified in the logs (e.g., timeout, 500 error, malformed response) to prevent future regressions. | Mocks are overly permissive or return hardcoded success values that would not catch the original flaky failure condition. | Inject the original failure condition into the mocked dependency. Verify the test fails against the old code and passes with the repair. |
Logging and Debugability | The repair adds a diagnostic log statement that would help debug a future recurrence of this flake (e.g., timing delta, resource ID). | The repair removes existing logging or adds no context to help an on-call engineer diagnose a future failure. | Check the diff for a new log statement containing a variable relevant to the root cause. Fail if no diagnostic information is added. |
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
Add strict schema validation, require evidence from at least two sources (test log, git blame, CI timing data), and include a retry loop for malformed outputs.
codeAnalyze the flaky test [TEST_NAME] using: - Failure logs from last [N] runs: [FAILURE_LOGS] - Recent code changes touching this test or its dependencies: [GIT_DIFF] - CI execution timing and ordering data: [CI_TRACE] Return valid JSON matching [OUTPUT_SCHEMA]. For each root cause, cite the specific log line, commit SHA, or timing anomaly as evidence. If evidence is insufficient, set confidence to "uncertain" and request additional data.
Watch for
- Silent format drift when the model adds extra fields
- Missing evidence citations on high-confidence findings
- Retry loops masking real failures instead of surfacing them

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