This prompt is designed for reliability engineers and SREs who need to audit production trace data for race conditions in agent executions. You should use it when you have structured traces from an agent that executes multiple tool calls in parallel and you suspect non-deterministic outcomes caused by two or more tool calls operating on the same resource without proper synchronization. The ideal input is a trace containing timestamps, tool names, arguments, target resource identifiers, and return values. The prompt performs a post-execution forensic analysis, correlating overlapping time windows with shared resource access to surface likely race condition candidates. It does not replace real-time concurrency controls, locking mechanisms, or transactional boundaries in your tool implementations.
Prompt
Tool-Call Race Condition Detection Prompt

When to Use This Prompt
Diagnose state corruption in parallel agent traces by identifying tool calls with overlapping side effects and missing synchronization.
To use this effectively, you must provide traces with sufficient granularity. Each tool-call record should include a precise start and end timestamp, the resource or entity ID being mutated, the operation type (create, update, delete), and the final state or return value. The prompt works by grouping calls by target resource, then identifying pairs or groups with overlapping execution windows where at least one call is a write operation. It flags cases where the final state is inconsistent with any valid serial ordering of the calls. For example, if Tool A updates a record at T1 and Tool B reads the same record at T2 where T1 and T2 overlap, the prompt will flag this as a read-write race. If both calls are writes with overlapping windows and the final state reflects only one, it flags a write-write conflict. The output is a structured race condition report keyed by resource, with an affected timeline and a severity classification.
Do not use this prompt for single-threaded sequential traces where ordering is guaranteed by design. Do not use it as a substitute for idempotency keys, optimistic locking, or transactional boundaries in your tool implementations. The prompt is a diagnostic tool, not a prevention mechanism. After receiving the race condition report, your next step should be to correlate the flagged resources with user-reported incidents or data integrity alerts. For high-severity findings affecting critical data, always require human review of the trace evidence before taking remediation actions such as state repair or tool-level synchronization fixes.
Use Case Fit
This prompt is designed for deep forensic analysis of agent traces to detect race conditions. It is not a real-time guard, a general-purpose audit, or a replacement for deterministic concurrency testing.
Good Fit: Post-Incident Forensics
Use when: you have a complete production trace where state corruption or an unexpected final state occurred, and you suspect overlapping tool calls are the cause. Guardrail: Feed the prompt the full, unredacted trace log and the expected final state to produce a timeline of conflicting side effects.
Bad Fit: Real-Time Execution Guard
Avoid when: you need to block a race condition before it happens. This prompt analyzes historical logs; it cannot interrupt an active agent run. Guardrail: Pair this diagnostic prompt with a deterministic lock manager or idempotency key requirement in your agent harness for runtime prevention.
Required Inputs
What you must provide: a raw agent trace with timestamps, tool names, full arguments, and return values for parallel steps. Guardrail: If your trace system truncates arguments or omits sub-second timestamps, the prompt's race condition analysis will be incomplete. Validate log fidelity first.
Operational Risk: False Positives
What to watch: the model may flag independent, non-conflicting parallel calls as a race condition if they share a resource ID. Guardrail: Always require the output to cite specific conflicting argument fields. Have a human reviewer confirm the report before filing a bug against the agent logic.
Operational Risk: Non-Deterministic Ordering
What to watch: the model may assume a causal order that wasn't guaranteed by the execution environment, leading to an incorrect root-cause analysis. Guardrail: Instruct the prompt to distinguish between 'observed order' and 'guaranteed order' in the trace. Flag any assumption as a finding, not a conclusion.
Variant: Idempotency Key Absence
Use when: the primary symptom is a duplicate side effect (e.g., double charge) rather than a corrupted state. Guardrail: Use the sibling 'Tool-Call Idempotency Violation Audit Prompt' for that specific pattern. Reserve this race-condition prompt for conflicts between different tool calls on the same resource.
Copy-Ready Prompt Template
A reusable prompt for detecting race conditions in parallel agent tool-call traces. Replace bracketed values with your trace data before sending to the model.
The prompt below is designed to analyze a production agent trace where multiple tool calls were executed in parallel or rapid succession. It identifies overlapping side effects, missing synchronization, and non-deterministic ordering that could have caused state corruption. Use this template as the core of a trace review harness—feed it structured trace data, tool manifests, and resource identifiers, and it will produce a structured race condition report.
textYou are a reliability engineer reviewing an agent execution trace for race conditions. Your task is to identify tool calls that accessed or mutated shared resources without proper synchronization, leading to potential state corruption. ## INPUT **Trace Data:** [TRACE_DATA] **Tool Manifest:** [TOOL_MANIFEST] **Shared Resource Definitions:** [SHARED_RESOURCES] **Expected Execution Model:** [EXECUTION_MODEL] ## OUTPUT_SCHEMA Return a JSON object with the following structure: { "trace_id": "string", "analysis_timestamp": "string (ISO 8601)", "findings": [ { "finding_id": "string", "severity": "HIGH | MEDIUM | LOW", "race_type": "WRITE_AFTER_READ | WRITE_AFTER_WRITE | READ_AFTER_WRITE | MISSING_SYNCHRONIZATION | NON_DETERMINISTIC_ORDERING", "affected_resource": "string", "tool_calls_involved": [ { "tool_call_id": "string", "tool_name": "string", "timestamp": "string (ISO 8601)", "operation": "READ | WRITE | DELETE | UPDATE", "arguments_summary": "string" } ], "timeline_description": "string describing the overlapping execution", "expected_behavior": "string describing correct synchronized behavior", "observed_behavior": "string describing what actually occurred", "impact_assessment": "string describing potential state corruption", "recommendation": "string describing fix (e.g., idempotency key, lock, sequential execution)" } ], "summary": { "total_tool_calls_reviewed": "integer", "parallel_execution_groups_identified": "integer", "race_conditions_found": "integer", "high_severity_count": "integer", "resources_affected": ["string"] }, "no_findings": "boolean (set to true only if zero race conditions found)" } ## CONSTRAINTS 1. Only flag tool calls that actually overlap in execution time or lack ordering guarantees. 2. Do not flag sequential tool calls that have explicit dependency ordering. 3. For each finding, cite specific timestamps and tool call IDs from the trace. 4. If the trace contains idempotency keys or version vectors, note whether they were used correctly. 5. Distinguish between true race conditions and acceptable concurrent reads. 6. If no race conditions are found, return an empty findings array with no_findings set to true and a brief explanation. ## EXAMPLES **Example Race Condition:** - Tool A reads resource X at T1 - Tool B writes resource X at T2 (T2 overlaps with T1's execution window) - Tool A's read may have captured stale or partially-written state - Severity: HIGH if the read result was used for a subsequent write **Example Non-Issue:** - Tool A reads resource X at T1 - Tool B reads resource X at T2 (concurrent reads, no mutation) - No race condition; do not flag ## RISK_LEVEL: [RISK_LEVEL] If RISK_LEVEL is HIGH, require explicit evidence of state corruption before flagging. If RISK_LEVEL is MEDIUM, flag potential races with clear impact descriptions. If RISK_LEVEL is LOW, flag all concurrent access to mutable resources.
To adapt this template, replace [TRACE_DATA] with a structured representation of your agent's tool-call log—ideally JSON with timestamps, tool names, arguments, and return values. Replace [TOOL_MANIFEST] with the list of available tools and their side-effect profiles (read-only vs. mutating). Replace [SHARED_RESOURCES] with the identifiers of resources that multiple tools can access, such as database rows, file paths, or API endpoints. Replace [EXECUTION_MODEL] with a description of how your agent schedules parallel calls—whether it uses a task graph, promises, or fire-and-forget. Set [RISK_LEVEL] to HIGH for financial or healthcare workflows where false positives waste review time, or LOW for debugging sessions where you want maximum coverage.
After running this prompt, validate the output against your trace data: every tool_call_id in the findings must exist in the original trace, timestamps must be consistent, and severity classifications should match your incident response thresholds. For production use, wire this prompt into a scheduled trace-sampling job that pulls recent parallel-execution traces, runs detection, and routes HIGH-severity findings to an on-call channel. Always log the raw model output and the validated finding count for observability. If the model returns findings for resources you know are immutable, adjust your [SHARED_RESOURCES] input to exclude them in the next run.
Prompt Variables
Inputs the prompt needs to work reliably. Validate each before sending to avoid false positives or incomplete race condition analysis.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TRACE_LOG] | Raw agent execution trace containing parallel tool-call events with timestamps | {"trace_id": "abc123", "events": [{"tool": "update_db", "timestamp": "2025-01-01T00:00:00.001Z", "args": {"id": "x"}}]} | Must be valid JSON with an events array. Each event requires tool name, timestamp, and args. Reject if timestamp field is missing or unparseable. |
[RESOURCE_MANIFEST] | Declared resources and their expected serialization boundaries from the agent's system design | {"resources": [{"name": "user_profile", "mutations": ["update_db", "cache_set"]}]} | Must map each resource to its mutating tool set. Reject if a tool appears in multiple resource mutation lists without explicit synchronization annotations. |
[SYNC_POLICY] | Expected synchronization primitives or ordering guarantees for the agent runtime | {"policy": "per-resource serial", "exceptions": ["read_only_tools"]} | Must specify whether execution is serial, parallel-with-locks, or fire-and-forget. Reject if policy is null or conflicts with observed trace parallelism. |
[TIME_WINDOW_MS] | Maximum time window in milliseconds for considering two tool calls as concurrent | 50 | Must be a positive integer. Default to 50 if not provided. Values above 500 should trigger a warning about over-inclusive race detection. |
[OUTPUT_SCHEMA] | Expected structure for the race condition report | {"races": [{"resource": "string", "call_a": "string", "call_b": "string", "overlap_ms": "number"}]} | Must define a races array with resource, conflicting call pair, and overlap duration. Reject if schema lacks resource-level grouping. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score for reporting a race condition | 0.85 | Must be a float between 0.0 and 1.0. Default to 0.85. Values below 0.7 should trigger a note that false positive rate may increase. |
[AGENT_VERSION] | Version identifier for the agent that produced the trace | v2.3.1 | Must be a non-empty string. Used to correlate race condition patterns with specific agent releases. Reject if null or empty. |
Implementation Harness Notes
How to wire the race condition detection prompt into an observability pipeline or incident review workflow.
The Tool-Call Race Condition Detection Prompt is designed to be integrated into an automated trace analysis pipeline, not run as a one-off chat interaction. The primary integration point is your existing observability platform (e.g., Datadog, Grafana, Arize, LangSmith) where agent traces are stored. When an incident is declared or an anomaly detector flags a state corruption event, a webhook should trigger a job that fetches the relevant trace spans, formats them into the [TRACE_DATA] placeholder, and sends the assembled prompt to a capable reasoning model. The model's structured output is then parsed and written back as an annotation on the incident timeline or as a structured finding in your security information and event management (SIEM) system.
The implementation must enforce a strict contract around the prompt's output. Because the prompt produces a JSON report with a race_conditions array, your harness should validate this schema immediately upon receiving the model's response. Use a JSON Schema validator to confirm the presence of required fields (affected_resources, timeline, root_cause_classification) and reject malformed responses. If validation fails, implement a single retry with a more forceful instruction appended to the prompt: 'You MUST respond with valid JSON matching the provided schema. Do not include any text outside the JSON object.' If the retry also fails, log the raw response and escalate to a human reviewer via your incident management tool (e.g., PagerDuty, Opsgenie). For high-severity production environments, consider routing the prompt to a model with strong JSON mode support, such as GPT-4o or Claude 3.5 Sonnet, and enabling structured output features to guarantee schema compliance on the first attempt.
To avoid false positives, the harness should pre-filter traces before invoking the LLM. Only send traces that contain parallel or concurrent tool calls—sequential traces with no overlapping execution windows cannot contain race conditions by definition. Your trace query should filter for spans where concurrency > 1 or where multiple tool calls share the same start_time and resource_id. This pre-filtering reduces token costs and prevents the model from hallucinating race conditions in purely sequential workflows. Additionally, maintain an audit log of every detection run: store the trace IDs, the prompt version, the model used, the raw LLM output, and the final validated finding. This log is essential for tuning the prompt over time and for defending false-positive detections during post-incident review. Never allow the model's output to automatically remediate or roll back state—always require a human operator to approve corrective actions based on the race condition report.
Expected Output Contract
Fields, format, and validation rules for the race condition report generated by the prompt. Use this contract to parse, validate, and store the model response in your observability pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
race_conditions | Array of objects | Must be a JSON array. If no race conditions are found, return an empty array, not null or a string. | |
race_conditions[].id | String (kebab-case) | Must match pattern | |
race_conditions[].severity | Enum string | Must be one of: | |
race_conditions[].affected_resources | Array of strings | Each string must reference a concrete resource ID, table name, or file path visible in the trace. Minimum 1 entry. | |
race_conditions[].overlapping_tool_calls | Array of objects | Each object must contain | |
race_conditions[].timeline | Array of objects | Ordered chronologically. Each object must contain | |
race_conditions[].synchronization_gap | String | Must describe the missing lock, transaction, idempotency key, or ordering guarantee. Cannot be empty or a generic placeholder like 'none'. | |
race_conditions[].state_corruption_description | String | Must explain the resulting inconsistent state with reference to specific resources. Must cite trace evidence. If no corruption occurred but risk exists, state 'No corruption observed; latent risk identified.' | |
trace_id | String | Must match the trace ID provided in [TRACE_ID]. Used for correlation in the observability platform. | |
analysis_timestamp | String (ISO 8601) | Must be the UTC timestamp when the analysis was generated. Must be parseable by standard datetime libraries. | |
human_review_required | Boolean | Must be |
Common Failure Modes
Race conditions in agent tool calls are subtle and dangerous. These cards cover the most common failure patterns when parallel tool execution leads to state corruption, and how to detect them before they reach production.
Overlapping Write Conflicts
What to watch: Two parallel tool calls write to the same resource (database row, file, API object) without coordination, causing last-write-wins corruption. The trace shows both calls succeeding but the final state is wrong. Guardrail: Scan traces for tool calls targeting the same resource ID within the same execution window. Flag any pair where both calls perform mutations without an explicit ordering constraint or lock acquisition call preceding them.
Read-Then-Write Stale Data
What to watch: Tool A reads a resource value, Tool B updates that same resource before Tool A writes back a computed result based on the stale read. The trace shows correct individual calls but the final state reflects an overwritten intermediate value. Guardrail: Identify read-write pairs on the same resource where another write interleaves between them. Require traces to show either a version check, ETag, or optimistic concurrency token in the write call arguments.
Non-Deterministic Execution Order
What to watch: Two tool calls that depend on each other are dispatched in parallel, but the model or runtime does not enforce ordering. The trace shows variable execution order across sessions, producing different outcomes for the same input. Guardrail: Compare tool-call start timestamps across multiple traces for the same workflow. Flag any pair where the temporal order differs between sessions and at least one call depends on the other's output. Require explicit sequential dispatch or a dependency declaration in the agent's tool schema.
Missing Synchronization Barrier
What to watch: A tool call that should wait for a set of parallel calls to complete before executing runs before all predecessors finish. The trace shows the dependent call starting before one or more prerequisite calls have returned. Guardrail: Check that any tool call consuming outputs from multiple upstream calls has a start timestamp strictly after all upstream call end timestamps. Flag violations where the gap is negative or zero, indicating no synchronization point was enforced.
Side-Effect Duplication Without Idempotency
What to watch: A tool call with external side effects (payment, email, ticket creation) executes twice in parallel because the agent retried without an idempotency key. The trace shows two identical calls with different trace IDs but the same arguments and no deduplication token. Guardrail: Audit traces for duplicate tool calls within a session that share the same target resource and mutation arguments. Flag any pair where neither call includes an idempotency key, request ID, or conditional header. Require idempotency tokens in the tool schema for all mutating external calls.
Partial Failure Cascades
What to watch: One parallel tool call fails while others succeed, but the agent continues as if all succeeded. The trace shows a mix of success and failure statuses with no rollback or compensation logic triggered. Guardrail: For any trace where parallel calls include at least one failure, verify that the agent either halts, retries, or invokes a compensating action before proceeding. Flag traces where subsequent calls depend on outputs from the failed call without error handling.
Evaluation Rubric
Use this rubric to test the Tool-Call Race Condition Detection Prompt before shipping it to production. Each criterion targets a specific failure mode common in race condition analysis. Run these tests against a curated set of known-good and known-bad agent traces.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Overlapping Side-Effect Detection | Prompt identifies all tool calls in the trace that write to the same resource without explicit synchronization. | Prompt misses a pair of concurrent writes to the same database row or file path that are visible in the trace timeline. | Run against a trace with two parallel tool calls writing to the same [RESOURCE_ID] with overlapping timestamps. Verify both calls appear in the report. |
Non-Deterministic Ordering Flag | Prompt correctly flags tool-call pairs whose execution order is not guaranteed and whose outcome depends on that order. | Prompt reports a deterministic sequential chain as a race condition, or fails to flag a true non-deterministic pair. | Test with a trace containing a read-before-write dependency across parallel branches. Confirm the report labels the ordering as non-deterministic and explains the dependency. |
Affected Resource Enumeration | Report includes a complete, deduplicated list of all resources (e.g., file paths, database keys, API endpoints) affected by the race condition. | Report omits a resource that was clearly involved in a flagged race condition, or includes resources not present in the trace. | Validate the resource list against a manually annotated trace. Every resource in the annotation must appear in the report; no hallucinated resources allowed. |
Timeline Reconstruction Accuracy | Report provides a correct chronological sequence of the conflicting tool calls with start and end times extracted from the trace. | Timestamps are misordered, missing, or attributed to the wrong tool call. Timeline contradicts the raw trace log. | Compare the report's timeline against the raw trace timestamps. All events must be in correct temporal order with times matching the source trace exactly. |
Severity Classification | Prompt assigns a severity level (e.g., CRITICAL, HIGH, MEDIUM, LOW) based on whether the race condition caused actual state corruption or remains a latent risk. | Prompt classifies a state-corrupting race as LOW severity, or labels a harmless parallel read as CRITICAL. | Test with two traces: one where the race caused a double-write and data loss, and one where parallel reads completed safely. Verify severity labels match the actual impact. |
Root-Cause Identification | Report identifies the missing synchronization mechanism (e.g., no lock, no idempotency key, no transaction) that allowed the race condition. | Report describes the symptom but does not name the missing guard, or blames an unrelated tool for the failure. | Run against a trace where a missing idempotency key caused a duplicate write. The report must explicitly state 'missing idempotency key' as the root cause, not just 'duplicate call detected.' |
False Positive Rate on Sequential Traces | Prompt returns an empty or explicitly 'no race conditions found' result for traces with purely sequential tool execution. | Prompt flags a race condition in a trace where all tool calls executed in a guaranteed sequential order with no parallelism. | Feed a trace with a single linear chain of tool calls. The output must contain zero findings or an explicit negative result with no fabricated issues. |
Output Schema Compliance | Report matches the declared [OUTPUT_SCHEMA] exactly: all required fields present, correct types, no extra fields. | Output is missing required fields like 'affected_resources' or 'timeline', contains malformed timestamps, or adds undeclared fields. | Validate the JSON output against the [OUTPUT_SCHEMA] using a schema validator. All required fields must be present and correctly typed. Reject on schema mismatch. |
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 single trace and lighter validation. Focus on identifying obvious overlapping side effects and non-deterministic ordering without requiring full dependency graph analysis. Accept free-text output instead of strict JSON schema.
Prompt modification
- Remove strict [OUTPUT_SCHEMA] requirement; accept narrative race condition descriptions
- Reduce [CONSTRAINTS] to only flag calls within 500ms of each other
- Replace formal timeline with simple chronological listing of tool calls
Watch for
- False positives from intentionally parallel but independent calls
- Missing detection of slow-burn race conditions that span longer intervals
- Overly broad instructions that flag any concurrent call as a race condition

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