This prompt is designed for test infrastructure engineers and SDETs who need to diagnose timing-dependent test failures that pass or fail unpredictably across runs. The core job-to-be-done is classifying whether a flaky failure is a true race condition—where two or more operations access shared state without proper synchronization—or a deterministic timing issue such as a fixed but insufficient sleep, a missing await, or a slow resource that always resolves given enough time. The distinction matters because race conditions require synchronization fixes (locks, mutexes, atomic operations, ordered queues), while deterministic timing issues require wait-strategy corrections (explicit awaits, polling with timeouts, event-driven triggers). Using the wrong fix class wastes engineering time and can mask real concurrency bugs.
Prompt
Race Condition Flakiness Identification Prompt

When to Use This Prompt
Understand the ideal conditions, required inputs, and boundaries for the Race Condition Flakiness Identification Prompt.
You should use this prompt when you have collected execution logs from multiple test runs—ideally five or more—that include timestamps with at least millisecond precision, thread or process identifiers, and resource access sequences such as lock acquisitions, database transactions, file writes, or shared memory operations. The prompt expects structured evidence: thread interleaving patterns, synchronization point logs, and timing deltas between dependent operations. Without this data, the model cannot distinguish between a race condition and a slow operation. Do not use this prompt for failures where no timing or concurrency data is available, for simple assertion failures with no interleaving evidence, or for failures in purely sequential single-threaded test suites. The prompt produces a structured classification with confidence scores and fix recommendations, but these recommendations require code-level verification before implementation—the model cannot see your actual synchronization primitives or memory model.
Before running this prompt, ensure your log collection captures the right signals: thread IDs or goroutine names, entry and exit timestamps for critical sections, lock acquisition and release events, and the order of operations on shared resources. If your test framework does not log these by default, instrument the code paths under test with structured logging before collecting evidence. The prompt's classification accuracy depends on the granularity and completeness of this timing data. After receiving the output, validate the classification by reproducing the failure under controlled concurrency stress (e.g., running with -race flags, increasing thread count, or injecting artificial delays at suspected race points). The prompt's fix recommendations are starting points for investigation, not production-ready patches.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if the Race Condition Flakiness Identification Prompt is the right tool for your current investigation.
Good Fit: Timing-Dependent Failures
Use when: Tests fail intermittently with timing-related errors (deadlocks, timeouts, stale reads) and you have access to thread/process logs, timestamps, and synchronization point records. Guardrail: The prompt requires structured timing data as input; do not use it on failures lacking concurrency evidence.
Bad Fit: Deterministic Logic Errors
Avoid when: Failures reproduce consistently regardless of timing or concurrency. The prompt is designed to isolate race conditions, not to debug algorithmic bugs, assertion logic errors, or configuration mistakes. Guardrail: Run a simple reproducibility check before invoking this prompt—if the failure is 100% reproducible, use a standard debugging prompt instead.
Required Inputs
What you must provide: Failure timing patterns (timestamps, durations, interleaving), thread/process logs showing concurrent execution, synchronization point records (locks, semaphores, barriers), and test environment details. Guardrail: Missing any of these inputs will produce low-confidence classifications. The prompt includes explicit confidence scoring that degrades when evidence is incomplete.
Operational Risk: False Attribution
Risk: The prompt may classify environmental timing issues (slow CI runners, network jitter) as code-level race conditions, leading to unnecessary code changes. Guardrail: All classifications require code-level verification. The prompt outputs confidence scores and explicit verification steps. Never apply lock/retry recommendations without confirming the synchronization point in source code.
Operational Risk: Over-Engineering Fixes
Risk: The prompt may recommend heavy synchronization (distributed locks, serialization) when simpler fixes (retry with backoff, idempotency keys) would suffice. Guardrail: Review fix recommendations against system latency requirements and throughput targets. Prefer the least invasive fix that resolves the race condition. The prompt ranks recommendations by implementation complexity.
When to Escalate
Risk: Distributed race conditions spanning multiple services, databases, and message queues may exceed the prompt's analysis scope. Guardrail: If the prompt produces low-confidence classifications (<0.7) or the failure involves more than three concurrent systems, escalate to a distributed systems review with full distributed tracing data. The prompt is designed for single-system or tightly-coupled concurrency analysis.
Copy-Ready Prompt Template
A copy-ready prompt for classifying timing-dependent test failures as race conditions or deterministic timing issues, with fix recommendations.
This prompt template is designed to be pasted directly into your AI workflow. It expects structured evidence from test execution logs, thread/process traces, and synchronization point data. Replace every square-bracket placeholder with your actual data before execution. The prompt instructs the model to act as a senior concurrency engineer, analyze the provided evidence, and output a structured JSON classification with fix recommendations and confidence scores. The output is designed to be machine-readable for integration into your test triage pipeline.
textYou are a senior concurrency engineer analyzing a timing-dependent test failure. Your task is to classify the failure as a Race Condition or a Deterministic Timing Issue and propose specific code-level fixes. ## INPUT DATA ### Test Failure Context - Test Name: [TEST_NAME] - Test Suite: [TEST_SUITE] - Failure Rate: [FAILURE_RATE] (e.g., "~30% of runs") - Last Stable Run: [LAST_STABLE_TIMESTAMP] ### Execution Logs (Relevant Snippets)
[THREAD_PROCESS_LOGS]
code### Synchronization Points Identified [Synchronization_POINTS] ### Code Context (Optional) ```[LANGUAGE] [RELEVANT_CODE_SNIPPETS]
OUTPUT SCHEMA
You must respond with a single JSON object conforming to this structure: { "classification": "race_condition" | "deterministic_timing", "confidence": 0.0-1.0, "evidence_summary": "string", "root_cause_hypothesis": "string", "fix_recommendations": [ { "category": "lock" | "retry" | "async_await" | "refactor" | "environment", "description": "string", "code_snippet": "string or null", "complexity": "low" | "medium" | "high" } ], "requires_code_verification": true }
CONSTRAINTS
- Base your analysis strictly on the provided logs and code context. Do not invent external factors.
- If the evidence is insufficient for a high-confidence classification, set confidence below 0.5 and state what additional data is needed in the evidence_summary.
- For race conditions, focus on unsynchronized access to shared mutable state.
- For deterministic timing issues, focus on fixed sleeps, missing await/join, or assumptions about execution order without explicit synchronization.
- All fix recommendations must be actionable by a developer and require code-level verification.
To adapt this template, replace the placeholders with data extracted from your CI/CD pipeline or test runner. The [THREAD_PROCESS_LOGS] placeholder should contain the raw log lines surrounding the failure, including timestamps and thread IDs. The [SYNCHRONIZATION_POINTS] field can be a list of known locks, semaphores, or async operations in the code under test. If you have access to the source code, include the relevant sections in [RELEVANT_CODE_SNIPPETS] to improve classification accuracy. The output JSON can be parsed by your test triage automation to automatically route the failure to the appropriate team or create a ticket with the fix recommendations pre-filled.
Prompt Variables
Each placeholder required by the Race Condition Flakiness Identification Prompt, its purpose, an example value, and actionable validation notes for integration into a test analysis harness.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TEST_FAILURE_LOG] | Raw log output from a single flaky test run capturing timestamps, thread IDs, and assertion errors. | 2025-01-15T10:32:01.123Z [thread-7] FAIL: expected 'ready' to be 'processing' | Must be a non-empty string. Validate it contains at least one timestamp and one assertion failure line. Reject if only a stack trace with no timing context is provided. |
[PASSING_RUN_LOG] | Log output from a recent passing run of the same test for differential analysis. | 2025-01-15T10:30:00.000Z [thread-7] PASS: state transition verified. | Must be a non-empty string. Validate it contains a PASS assertion for the same test case name. If null, the analysis must be flagged as 'degraded confidence'. |
[SYNCHRONIZATION_PRIMITIVES] | A list of known locks, mutexes, semaphores, or barriers used in the code path under test. | ['user_cache_mutex', 'db_write_lock', 'session_semaphore'] | Must be a valid JSON array of strings. Validate each string matches a known symbol in the codebase. An empty array is allowed but triggers a note that no synchronization analysis was performed. |
[CODE_DIFF] | The unified diff of the recent code change suspected of introducing the flakiness. | diff --git a/src/session.py b/src/session.py
| Must be a string in unified diff format. Validate it contains at least one file header. If null, the prompt must be instructed to skip change-based correlation and rely solely on log analysis. |
[EXECUTION_ENVIRONMENT] | A structured description of the CI environment, including OS, CPU count, and containerization details. | {'os': 'linux', 'cpus': 4, 'containerized': true, 'orchestrator': 'k8s'} | Must be a valid JSON object. Validate the presence of the 'os' and 'cpus' keys. If 'containerized' is true, the analysis must consider container startup races as a primary hypothesis. |
[OUTPUT_SCHEMA] | The strict JSON schema the model must use to return its classification and fix recommendations. | {'type': 'object', 'properties': {'classification': {'type': 'string', 'enum': ['race_condition', 'deterministic_timing', 'environmental']}}} | Must be a valid JSON Schema object. Validate it defines a 'classification' field with a controlled enum. Reject schemas that allow free-text classification without a fixed vocabulary. |
Implementation Harness Notes
How to wire the race condition identification prompt into a test analysis pipeline with validation, retries, and human review gates.
This prompt is designed to operate as a classification and recommendation step inside a broader flaky test triage pipeline. It expects structured input—failure timing patterns, thread or process logs, and identified synchronization points—and returns a structured classification with confidence scores and fix recommendations. The output is not a final verdict; it is a hypothesis generator that must be verified against code before any remediation is applied. Wire this prompt after log extraction and before any automated fix application.
Input assembly is the first integration point. Before calling the model, assemble the [FAILURE_TIMING_DATA], [THREAD_PROCESS_LOGS], and [SYNCHRONIZATION_POINTS] placeholders from your test execution artifacts. Timing data should include timestamps of failures, pass/fail boundaries, and any retry intervals. Thread logs must capture interleaving across concurrent workers, not just sequential dumps. Synchronization points should list known locks, semaphores, barriers, or async await boundaries in the code under test. If your CI system doesn't capture these signals, add instrumentation before relying on this prompt—the model cannot identify race conditions from generic stack traces alone.
Validation and retry logic must surround the model call. Parse the JSON output and validate that classification is one of the expected enum values (race_condition, deterministic_timing, insufficient_evidence), that confidence_score is a float between 0.0 and 1.0, and that fix_recommendations is a non-empty array when classification is race_condition. If validation fails, retry once with the validation error appended to the prompt as additional [CONSTRAINTS]. If the second attempt also fails validation, log the raw output and escalate for manual review rather than silently accepting a malformed classification.
Human review gates are mandatory for high-risk classifications. Any output where confidence_score exceeds 0.7 and classification is race_condition should create a review task for a senior engineer before the recommended fix (lock addition, retry logic, async await restructuring) is implemented. The prompt's fix recommendations are syntactically plausible but may be semantically wrong for your specific concurrency model. The review should verify that the identified synchronization point actually governs the contended resource and that the proposed fix doesn't introduce deadlocks or starvation. For insufficient_evidence classifications, route the test to enhanced logging rather than closing the investigation.
Model choice and tool use affect reliability. Use a model with strong code reasoning capabilities—GPT-4, Claude 3.5 Sonnet, or equivalent. This prompt does not require tool calling or RAG unless you want to ground fix recommendations against your internal concurrency patterns library. If you maintain a knowledge base of known race condition fixes, add a retrieval step that injects relevant examples into the [EXAMPLES] placeholder before the model call. For production pipelines processing hundreds of flaky tests, batch similar failure signatures and deduplicate before calling the model to avoid redundant API costs on identical timing patterns.
Logging and observability are critical for trust. Log every model call with the input hash, output classification, confidence score, and whether the classification was later confirmed or rejected by human review. Track the false positive rate of race_condition classifications over time—if the model consistently flags patterns that engineers dismiss, adjust the confidence threshold or add counterexamples to the prompt. Also monitor the insufficient_evidence rate; a rising trend indicates your log extraction pipeline is not capturing the signals this prompt needs, and you should improve instrumentation before blaming the prompt.
Expected Output Contract
Defines the required fields, types, and validation rules for the structured JSON output of the Race Condition Flakiness Identification Prompt. Use this contract to build a parser and validator in your application harness.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
classification | string enum | Must be one of: 'race_condition', 'deterministic_timing', 'environmental_contention', 'unknown'. No other values allowed. | |
confidence_score | number | Float between 0.0 and 1.0. Values outside this range must trigger a retry or repair prompt. | |
evidence | array of objects | Array must contain at least 1 item. Each item must have 'timestamp', 'source', and 'observation' string fields. Empty array is a validation failure. | |
evidence[].timestamp | ISO 8601 string | Must parse to a valid datetime. Null or unparseable strings fail validation. | |
evidence[].source | string | Must be one of: 'thread_log', 'process_log', 'network_capture', 'test_output', 'system_metric'. Unknown sources should be flagged for human review. | |
synchronization_points | array of strings | If present, each string must describe a code location or API call. Null is acceptable. Empty array is acceptable. | |
recommended_fix | object | Must contain 'strategy' (string), 'code_snippet' (string or null), and 'verification_steps' (array of strings). Missing keys fail schema validation. | |
recommended_fix.strategy | string enum | Must be one of: 'add_lock', 'add_retry', 'add_async_await', 'restructure_order', 'increase_timeout', 'manual_review_required'. |
Common Failure Modes
Race condition flakiness is notoriously difficult to reproduce and diagnose. These cards cover the most common failure patterns when using prompts to analyze timing-dependent test failures, and how to build guardrails that prevent misclassification and false confidence.
False Attribution to Code Logic
Risk: The model attributes a failure to a code defect when the root cause is an environmental timing issue (e.g., slow CI runner, network jitter). This leads developers on a wild goose chase. Guardrail: Require the prompt to cross-reference failure timing with environment metrics (CPU steal, I/O wait, network latency percentiles). If environment variance exceeds a threshold, the model must classify the root cause as 'environmental' and recommend re-running under controlled conditions before suggesting code changes.
Confusing Correlation with Causation in Thread Logs
Risk: The model observes two threads accessing a shared resource at similar timestamps and declares a race condition, even when the access pattern is safely synchronized via a lock or concurrent data structure. Guardrail: The prompt must instruct the model to explicitly search for synchronization primitives (locks, mutexes, semaphores, channels) in the provided logs or code context before classifying. If synchronization is present, the model must explain why it believes the mechanism failed, not just that access was concurrent.
Overlooking Async/Await Mismatches
Risk: The model correctly identifies a timing issue but recommends a generic 'add a retry' or 'increase timeout' fix, missing that the root cause is a missing await or an unhandled promise rejection in the test setup. Guardrail: The prompt must require the model to check for specific async/await patterns in the provided code snippets. The output schema should include a dedicated field for 'async hygiene issues' that flags missing awaits, floating promises, or incorrect promise chaining before suggesting retry logic.
High-Confidence Output Without Code Verification
Risk: The model produces a confident-sounding fix recommendation with a high confidence score, but the recommendation is syntactically incorrect or incompatible with the project's concurrency primitives. Guardrail: The prompt must include a mandatory disclaimer that all fix recommendations require code-level verification. The output schema should separate 'analysis confidence' from 'fix confidence,' and the prompt should instruct the model to lower fix confidence when it cannot see the full implementation of synchronization points.
Ignoring Test Framework Retry Logic
Risk: The model analyzes a failure trace and proposes a complex synchronization fix, but the failure is actually caused by the test framework's own retry mechanism creating a nested race condition (e.g., a retried test conflicting with its own previous run's cleanup). Guardrail: The prompt must instruct the model to first check for test framework retry configurations (e.g., Jest retryTimes, pytest-rerunfailures) in the provided context. If retries are enabled, the analysis must account for inter-retry state conflicts before proposing application-level fixes.
Misclassifying Deterministic Timing as a Race Condition
Risk: A test fails consistently on a specific OS or under a specific resource limit due to a deterministic ordering assumption (e.g., relying on filesystem order), but the model classifies it as a non-deterministic race condition. Guardrail: The prompt must require the model to calculate a reproducibility rate from the provided failure history. If the failure is 100% reproducible under a specific configuration, the model must classify it as a 'deterministic timing dependency' and recommend fixing the ordering assumption rather than adding synchronization.
Evaluation Rubric
Criteria for evaluating the quality of race condition flakiness identification outputs before integrating this prompt into a production CI analysis pipeline. Each row defines a pass standard, a failure signal, and a test method to validate the prompt's performance against a curated set of known race condition and deterministic timing failure logs.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Race Condition Classification Accuracy | Correctly classifies >= 90% of known race condition failures as 'Race Condition' in a golden dataset of 50 labeled test failures. | Misclassifies a race condition as 'Deterministic Timing Issue' or 'Environmental Flakiness' more than 10% of the time. | Run prompt against a golden dataset of 50 pre-labeled test failure logs (25 race conditions, 25 non-race conditions). Calculate precision and recall for the 'Race Condition' label. |
Synchronization Point Identification | Identifies the specific code location (file:line) of the synchronization gap for >= 80% of true positive race condition detections. | Outputs a generic root cause like 'timing issue' without a specific file:line reference, or points to the wrong code block. | For each true positive classification, parse the output for a [SYNC_POINT] field. Validate that the file:line exists in the provided [CODE_CONTEXT] and is a synchronization primitive (lock, channel, wait group, etc.). |
Confidence Score Calibration | The [CONFIDENCE_SCORE] is >= 0.8 for true positives and <= 0.5 for false positives, with no high-confidence (>=0.9) false positives. | A false positive classification is assigned a [CONFIDENCE_SCORE] >= 0.9, indicating severe miscalibration. | Plot a histogram of [CONFIDENCE_SCORE] values for all true positives and false positives. Verify that the distributions are well-separated and that no false positive exceeds 0.9. |
Fix Recommendation Actionability | The [FIX_RECOMMENDATION] for a true positive includes a specific, code-level strategy (e.g., 'Add mutex lock around sharedMap access at handler.go:42') and not just a general category (e.g., 'add a lock'). | The fix recommendation is a vague category like 'use async/await' or 'add retries' without referencing the specific shared resource or code location from the analysis. | Manually review the [FIX_RECOMMENDATION] for the first 10 true positives. The recommendation must contain a concrete code action and reference a specific identifier from the [SYNC_POINT] or [THREAD_LOG] evidence. |
Deterministic Timing Distinction | Correctly classifies a test that fails consistently due to a short timeout as 'Deterministic Timing Issue' and not a 'Race Condition'. | Classifies a failure caused by a fixed | Include 10 deterministic timing failures in the golden dataset (e.g., fixed delays, missing await without concurrency). Verify the prompt outputs the 'Deterministic Timing Issue' classification for >= 9 of them. |
Evidence Grounding | Every classification is supported by at least one direct quote from the provided [THREAD_LOG] or [FAILURE_TIMING_DATA] in the [EVIDENCE] field. | The [EVIDENCE] field contains a hallucinated log line or a generic statement like 'timestamps indicate overlap' without a direct quote. | For 20 random outputs, use a script to check if the string in the [EVIDENCE] field is a substring of the provided [THREAD_LOG] or [FAILURE_TIMING_DATA] input. Pass standard: 100% match rate. |
Output Schema Compliance | The output is valid JSON that strictly conforms to the [OUTPUT_SCHEMA] with all required fields present and correctly typed. | The output is missing the [ROOT_CAUSE_CLASS] field, or [CONFIDENCE_SCORE] is a string instead of a number. | Validate the raw model output against the [OUTPUT_SCHEMA] using a JSON schema validator. The test passes if the validator returns zero errors. |
Abstention on Insufficient Data | When [THREAD_LOG] is empty or contains only a single thread, the output correctly abstains with [ROOT_CAUSE_CLASS] set to 'Insufficient Data' and [CONFIDENCE_SCORE] set to 0. | The prompt hallucinates a race condition or provides a fix recommendation when no concurrency data is available. | Run the prompt with 5 test cases where [THREAD_LOG] is an empty string. Verify that all 5 outputs have [ROOT_CAUSE_CLASS] equal to 'Insufficient Data' and [CONFIDENCE_SCORE] equal to 0. |
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
Use the base prompt with a frontier model (GPT-4o, Claude 3.5 Sonnet) and minimal validation. Focus on getting a useful classification and fix recommendation from a single representative log sample before building pipeline integration.
- Remove strict output schema requirements; accept a structured but unvalidated markdown response.
- Use a single example failure log rather than batch processing.
- Skip confidence score calibration and eval assertions.
Watch for
- Overconfident race condition classifications when evidence is thin.
- Fix recommendations that suggest code changes without seeing the actual code.
- Missing distinction between application-level races and test-harness timing issues.

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