Inferensys

Prompt

Flaky Test Concurrency Root Cause Prompt

A practical prompt playbook for using the Flaky Test Concurrency Root Cause Prompt in production QA and platform engineering workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the ideal scenario, required inputs, and boundaries for the flaky test concurrency root cause analysis prompt.

This playbook is for QA engineers and platform teams who have a flaky test that fails intermittently and suspect a concurrency root cause. The prompt is designed to analyze structured evidence—test code, execution logs from at least one failure, and timing data or CI environment details—to produce ranked root cause hypotheses. Each hypothesis includes a confidence score, supporting evidence extracted from the logs, and concrete reproduction guidance. The goal is to replace ad-hoc log scrolling with a systematic, evidence-backed differential diagnosis that points directly to the most likely race condition, ordering dependency, or environmental timing factor.

To use this prompt effectively, you must provide the full test source code, the complete console output or log stream from a failed run, and any available metadata such as CPU timing, thread/goroutine scheduling traces, or CI runner specifications. The prompt is not a magic wand for all test failures. Do not use it for deterministic failures that reproduce reliably in a single-threaded context, pure logic errors with no concurrency involvement, or tests that fail solely due to external service unavailability, network timeouts, or third-party API errors without any local concurrency component. The prompt assumes the failure is non-deterministic and that concurrency is a plausible contributing factor.

Before running this prompt, confirm that you have ruled out simple environmental issues like missing environment variables, stale build artifacts, or disk space exhaustion. The prompt performs best when the failure log contains timestamps, thread or goroutine IDs, and stack traces that allow the model to reconstruct a partial ordering of events. If your logs lack this information, consider enabling verbose logging, race detectors (e.g., Go's -race flag, ThreadSanitizer), or adding structured tracing before submitting the evidence. The output is a set of hypotheses ranked by likelihood, not a single definitive answer. Always validate the top hypothesis by attempting the suggested reproduction steps in a controlled environment before applying a fix.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Flaky Test Concurrency Root Cause Prompt works and where it does not. Use these cards to decide if this prompt fits your investigation before you run it.

01

Strong Fit: Intermittent CI Failures

Use when: A test fails non-deterministically in CI, and retries sometimes pass. The prompt excels at correlating failure timestamps with concurrent operations, thread scheduling, and shared resource access patterns. Avoid when: The failure is deterministic or caused by a known environment outage.

02

Weak Fit: Pure Logic Errors

Avoid when: The test failure is a deterministic assertion error caused by incorrect business logic, a typo, or a static calculation mistake. The concurrency analysis prompt will waste tokens searching for race conditions that do not exist. Guardrail: Run a deterministic replay first; only invoke this prompt if the failure cannot be reliably reproduced.

03

Required Inputs

What you must provide: The flaky test code, the code under test (especially any shared state, channels, or locks), and structured execution logs with timestamps. Guardrail: Without high-resolution timestamps or thread/goroutine IDs in the logs, the prompt cannot perform interleaving analysis and will produce low-confidence, generic hypotheses.

04

Operational Risk: False Confidence

What to watch: The model may produce a highly plausible root cause hypothesis that is completely wrong, especially if the logs are incomplete. Guardrail: Treat every output as a hypothesis to be reproduced, not a diagnosis. Require a developer to reproduce the specific interleaving before accepting the fix. Never auto-merge a concurrency fix based solely on this prompt's output.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for analyzing flaky test failures and generating concurrency root cause hypotheses.

This prompt template is designed to be pasted directly into your AI harness. It accepts structured inputs about a flaky test failure—including the test code, execution logs, and timing data—and instructs the model to act as a senior concurrency engineer. The output is a ranked list of root cause hypotheses, each with a confidence score, supporting evidence, and a concrete reproduction strategy. All dynamic inputs are represented as square-bracket placeholders, which your application must replace before sending the request.

text
You are a senior concurrency engineer specializing in diagnosing flaky tests in distributed and multi-threaded systems. Your task is to analyze a flaky test failure and produce a ranked list of root cause hypotheses, focusing on race conditions, ordering dependencies, and environmental timing factors.

## INPUT DATA

### Test Code
```[LANGUAGE]
[TEST_CODE]

Execution Logs (from a failing run)

text
[FAILURE_LOGS]

Timing Data (if available)

json
[TIMING_DATA]

CI Environment Details

  • OS: [OS]
  • CPU Architecture: [CPU_ARCH]
  • Number of Cores: [CPU_CORES]
  • Memory: [MEMORY]
  • Test Runner: [TEST_RUNNER]
  • Retry Policy: [RETRY_POLICY]

Known Non-Deterministic Factors

[KNOWN_FACTORS]

OUTPUT SCHEMA

Produce a JSON object with the following structure: { "analysis_summary": "A concise summary of the failure pattern and the most likely category of root cause.", "hypotheses": [ { "rank": 1, "category": "race_condition | ordering_dependency | deadlock | resource_exhaustion | environmental_timing | assertion_flakiness | other", "description": "A clear, specific description of the hypothesized root cause.", "confidence": 0.0-1.0, "evidence": ["List of specific log lines, code snippets, or timing anomalies that support this hypothesis."], "reproduction_guidance": "Step-by-step instructions to increase the probability of reproducing this failure, including specific tools (e.g., stress, tc, thread scheduling manipulation) and parameters.", "suggested_fix_approach": "A high-level description of the fix strategy without writing the full patch.", "risk_if_ignored": "What could happen in production if this root cause is not addressed." } ], "excluded_causes": ["List of potential causes that were considered but ruled out, with a brief reason for each."] }

CONSTRAINTS

  • Do not invent log entries or timing data. If evidence is insufficient, lower the confidence score and state what additional data is needed.
  • Prioritize hypotheses that explain the intermittent nature of the failure.
  • If the test code contains shared mutable state, explicitly identify it.
  • If the failure is likely not concurrency-related, state this clearly and rank non-concurrency causes.
  • For Go code, pay special attention to goroutine leaks, channel blocking, and missing context.Context propagation.
  • For async Python, check for missing await keywords and event loop blocking.
  • For Java, inspect synchronized block scope, volatile usage, and thread pool configurations.

To adapt this template, replace each [PLACEHOLDER] with data from your CI pipeline. The [TEST_CODE] block should contain the full test source, not just the assertion that failed. The [FAILURE_LOGS] should include timestamps and thread or goroutine IDs if available. The [TIMING_DATA] field is optional but highly valuable—include JSON profiling output or test duration percentiles if you have them. After receiving the model's response, validate the JSON structure before surfacing it to a developer. If the confidence for the top hypothesis is below 0.5, flag the analysis for human review and consider re-running with additional instrumentation enabled.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Flaky Test Concurrency Root Cause Prompt. Each placeholder must be populated before execution to ensure reliable root cause analysis.

PlaceholderPurposeExampleValidation Notes

[TEST_CODE]

The full source code of the flaky test method and any helper methods it calls

testConcurrentOrderProcessing() with setUp() and tearDown()

Parse check: must contain at least one test method. Null not allowed. Reject if empty or only comments.

[FAILURE_LOGS]

Complete stack traces and error messages from at least 3 flaky test failures

3 separate CI log files showing AssertionError at different lines

Parse check: must contain at least 3 distinct timestamps or run IDs. Null not allowed. Fewer than 3 failures triggers low-confidence warning.

[PASS_LOGS]

Logs from passing runs of the same test for comparison baseline

2-3 passing CI log files from recent successful runs

Null allowed if no passing runs exist. If provided, must contain matching test name. Absence reduces confidence in timing differential analysis.

[TIMING_DATA]

Execution duration per test step or method, ideally with percentile distributions

JSON with step names and p50/p95/p99 durations in milliseconds

Schema check: must be valid JSON with numeric duration fields. Null allowed but eliminates timing-based race detection. Reject if non-numeric values present.

[ENVIRONMENT_CONTEXT]

Details about test execution environment: CPU count, OS, test framework, parallelization settings

JUnit 5 parallel execution mode=concurrent, 4 vCPUs, Linux x86_64

Parse check: must include test framework name and parallelization config. Null not allowed. Incomplete context triggers a missing-information flag in output.

[SHARED_RESOURCES]

List of shared resources accessed by the test: databases, files, caches, queues, external services

Shared Redis instance test-cache-1, PostgreSQL table orders_test

Null allowed if no shared resources identified. If provided, each resource must include type and identifier. Empty list is valid and treated as no shared state.

[CONCURRENCY_CONFIG]

Test framework concurrency settings: thread count, fork count, isolation level, timeout values

forkCount=4, threadPoolSize=8, timeoutSeconds=30

Parse check: must include at least one numeric concurrency parameter. Null not allowed. Missing values reduce reproduction guidance precision.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the flaky test concurrency root cause prompt into an automated CI investigation pipeline or a manual QA debugging workflow.

This prompt is designed to be called programmatically after a test failure is flagged as potentially flaky by your CI system. The implementation harness should gather the required inputs—test code, failure logs, and timing data—and assemble them into the [TEST_CODE], [FAILURE_LOGS], and [TIMING_DATA] placeholders. Because the prompt analyzes concurrency, the quality of the timing data is critical; a single timestamped log line is insufficient. You must capture interleaved event logs from all concurrent actors (threads, goroutines, async tasks) with high-resolution timestamps, or the model will not have enough signal to generate useful root cause hypotheses.

Wire this prompt into a post-failure analysis step in your CI pipeline. On a test failure, a script should extract the test source file, the last N lines of the failure output, and any structured timing logs your test harness produces. If your tests don't produce structured concurrency logs, add a thin instrumentation layer that logs entry/exit of shared resource access (locks, channels, database transactions) with thread IDs and nanosecond timestamps. The harness should then call the LLM with the assembled prompt and parse the JSON output against a strict schema. Validate that the hypotheses array is present, each hypothesis has a non-empty description and a likelihood between 0 and 1, and reproduction_guidance is a non-empty string. If validation fails, retry once with a repair prompt that includes the schema and the malformed output. Log both the raw model response and the parsed result for traceability.

For high-confidence hypotheses (likelihood > 0.7), the harness can automatically create a ticket in your issue tracker with the root cause description and reproduction steps pre-filled. For lower-confidence results, route the analysis to a QA engineer for manual review. Never automatically apply a suggested code fix for a concurrency bug—the risk of introducing a new, subtler race condition is too high. The model's output is a diagnostic aid, not a verified patch. Always require human approval before any code change that alters synchronization logic, lock ordering, or transaction boundaries. Finally, store the prompt version, model version, and input hashes alongside the analysis result so you can audit which analyses were generated under which conditions.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the exact shape, types, and validation rules for the JSON response returned by the Flaky Test Concurrency Root Cause Prompt. Use this contract to parse the model output in your application harness and to validate correctness before surfacing results.

Field or ElementType or FormatRequiredValidation Rule

analysis_id

string (UUID v4)

Must match regex for UUID v4. Reject if missing or malformed.

test_identifier

string

Must not be empty. Should match the [TEST_NAME] or [TEST_FILE_PATH] input.

root_cause_hypotheses

array of objects

Must be a non-empty array. Reject if empty or not an array.

root_cause_hypotheses[].rank

integer

Must be a positive integer starting at 1. Sequence must be contiguous (1,2,3...).

root_cause_hypotheses[].category

enum string

Must be one of: 'race_condition', 'ordering_dependency', 'environmental_timing', 'resource_contention', 'assertion_flakiness', 'test_isolation_violation'.

root_cause_hypotheses[].confidence_score

number (0.0 - 1.0)

Must be a float between 0.0 and 1.0 inclusive. Reject if out of range.

root_cause_hypotheses[].evidence_summary

string

Must be non-empty and reference specific log lines, timestamps, or code paths from [EXECUTION_LOG] or [TEST_CODE].

reproduction_guidance

string

Must be non-empty and include actionable steps or a specific interleaving description. Reject if generic like 'run the test again'.

PRACTICAL GUARDRAILS

Common Failure Modes

Flaky test concurrency analysis is brittle by nature. These are the most common ways the prompt fails and how to guard against them before shipping.

01

Hallucinated Interleavings Without Log Evidence

What to watch: The model invents a plausible race condition or thread interleaving that is not supported by the provided execution logs or timing data. It generates a confident root cause hypothesis based on pattern recognition rather than evidence in the input.

Guardrail: Require the prompt to cite specific log lines, timestamps, or thread IDs for every hypothesis. Add a validator that rejects hypotheses without direct evidence grounding. Include a confidence field that drops to low when evidence is circumstantial.

02

Overfitting to a Single Flaky Test Pattern

What to watch: The model latches onto the first concurrency anti-pattern it recognizes (e.g., a missing lock) and ignores other contributing factors like environment timing, resource contention, or test ordering dependencies. It produces a single high-confidence hypothesis when multiple factors are at play.

Guardrail: Force the output schema to produce at least three ranked hypotheses with distinct root cause categories. Add an eval check that penalizes outputs where all hypotheses share the same underlying mechanism. Include a requires_multiple_factors boolean flag.

03

Ignoring Test Framework and Runner Behavior

What to watch: The model analyzes application concurrency but ignores the test framework's own parallelism, suite ordering, shared fixture state, or test runner configuration. Many flaky tests are caused by the test harness, not the code under test.

Guardrail: Include a dedicated test_harness_analysis section in the output schema. Require the prompt to examine test runner configuration, fixture lifecycle, and suite-level parallelism settings before analyzing application code. Add a checklist item for test framework version and known issues.

04

Confusing Correlation with Causation in Timing Data

What to watch: The model treats temporal proximity as causal relationship. It sees that thread A logged before thread B and assumes A caused B's failure, when both are symptoms of an unrelated resource bottleneck or scheduler behavior.

Guardrail: Require the prompt to explicitly separate observed_sequence from causal_relationship. Add a causality_confidence field that is distinct from reproduction_likelihood. Include a counter-hypothesis that explains the same timing data through an alternative causal chain.

05

Missing Non-Deterministic Reproduction Guidance

What to watch: The model identifies a race condition but fails to provide actionable reproduction steps. It says "this is a race between X and Y" without explaining how to trigger the specific interleaving, what stress conditions are needed, or how many iterations are required for statistical confidence.

Guardrail: Require the output to include a reproduction_plan with specific thread scheduling hints, stress test parameters, iteration counts, and expected success rates. Add a reproducibility_difficulty rating. Validate that the plan includes concrete tools (e.g., stress-ng, tc for network delay, thread pausing).

06

Language and Runtime Model Mismatch

What to watch: The model applies concurrency reasoning from one language ecosystem to another without adjustment. It suggests Java memory model guarantees for Go goroutines, or Python GIL assumptions for Rust async code. The root cause analysis is syntactically plausible but semantically wrong for the target runtime.

Guardrail: Require the prompt to declare the target language and runtime version in the input. Include a runtime_model_checks section that validates synchronization assumptions against the specific language memory model. Add an eval that flags hypotheses using primitives or guarantees not available in the target language.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of the Flaky Test Concurrency Root Cause Prompt's output before integrating it into a CI/CD pipeline or QA workflow. Each row defines a pass standard, a failure signal, and a concrete test method.

CriterionPass StandardFailure SignalTest Method

Hypothesis Actionability

Each root cause hypothesis includes a specific code location, a concurrency primitive, and a reproduction scenario.

Hypothesis is vague (e.g., 'a race condition exists') without a file path, line range, or interleaving description.

Manual review: Check if a developer can write a targeted test from the hypothesis alone.

Likelihood Ranking

Hypotheses are ranked with a clear ordinal scale (e.g., High/Medium/Low) and a one-sentence justification for the rank.

All hypotheses have the same rank, or the ranking contradicts the evidence cited (e.g., a timing-based issue ranked Low with strong log evidence).

Spot-check: Verify that the top-ranked hypothesis has the strongest correlation with the provided [EXECUTION_LOGS] and [TIMING_DATA].

Evidence Grounding

Every hypothesis cites specific evidence from the provided [TEST_CODE], [EXECUTION_LOGS], or [TIMING_DATA] (e.g., log timestamps, thread IDs, assertion messages).

A hypothesis makes a claim about code behavior without quoting or referencing any provided input artifact.

Automated check: Parse output for absence of citation markers or direct quotes from the input context.

Reproduction Guidance

The output includes a concrete, step-by-step method to increase the probability of reproducing the suspected race, such as a stress test loop or a sleep injection point.

Reproduction guidance is generic (e.g., 'run the test multiple times') or missing entirely.

Manual review: Confirm the guidance references a specific code path or tool (e.g., stress-ng, tc for network delay) relevant to the hypothesis.

False Positive Avoidance

The output explicitly flags if a suspected concurrency issue is more likely an environmental flake (e.g., network timeout, disk I/O) and separates these from true code-level races.

All failures are attributed to code-level concurrency bugs, ignoring clear environmental failure signals in the logs.

Adversarial test: Provide a log where the failure is a DNS timeout and check if the output correctly classifies it as non-concurrency.

Output Schema Validity

The output is a valid JSON object matching the [OUTPUT_SCHEMA] with all required fields present and correctly typed.

The output is malformed JSON, missing a required field like hypotheses or severity_assessment, or contains a string where an array is expected.

Automated schema validation: Parse the output with a JSON schema validator against the defined contract.

Concurrency Primitive Identification

The output correctly identifies the specific concurrency primitive involved (e.g., mutex, channel, goroutine, async/await) for each hypothesis.

The output misidentifies the primitive (e.g., calls a channel operation a mutex lock) or uses a generic term like 'synchronization issue' without specifying the mechanism.

Unit test: Provide a code snippet with a known channel deadlock and assert the output identifies 'channel' as the primitive.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single test log and minimal output schema. Focus on getting one plausible root cause hypothesis, not a ranked list. Skip the reproduction guidance section initially.

code
Analyze this flaky test log for concurrency root causes:

[TEST_LOG]

Return ONE likely root cause with supporting evidence from the log.

Watch for

  • Overconfident single-hypothesis output without alternatives
  • Missing timestamps or thread IDs in truncated logs
  • Model hallucinating thread interleavings not present in the evidence
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.