Inferensys

Prompt

Race Condition Diagnosis Prompt from Logs

A practical prompt playbook for using a Race Condition Diagnosis Prompt from Logs in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the precise conditions, required inputs, and anti-patterns for using the race condition diagnosis prompt.

This prompt is designed for backend and reliability engineers who are actively investigating an intermittent concurrency bug that has manifested in production or staging logs. The core job-to-be-done is reconstructing a coherent, interleaved execution timeline from dozens of noisy, distributed log lines across multiple services, threads, or goroutines. The ideal user has already collected raw log evidence showing a race condition—such as corrupted shared state, inconsistent reads, or deadlocks—but cannot visually parse the exact ordering of events that led to the failure. The prompt requires three non-negotiable inputs: the raw log lines with their timestamps and service/thread identifiers, the relevant source code files that manage the shared state in question, and a brief description of the observed symptom (e.g., 'counter underflow' or 'duplicate transaction'). Without all three, the model cannot ground its analysis in evidence.

Use this prompt when you have a high-confidence signal that a race condition exists but need a structured hypothesis to guide a code fix. It is particularly effective for debugging lock contention, channel deadlocks, non-atomic read-modify-write sequences, and missing synchronization in multi-threaded or distributed workflows. The prompt works best with logs that include precise timestamps (millisecond granularity or finer), consistent correlation IDs, and thread or goroutine identifiers. If your logs lack these fields, the reconstruction will be speculative and should be treated as a starting point for adding instrumentation, not a definitive diagnosis. The prompt also assumes the relevant source code is available and can be provided in full; partial or obfuscated code will degrade the sequence diagram accuracy and may produce unsafe locking recommendations.

Do not use this prompt for deterministic bugs, single-threaded failures, or incidents where no relevant source code is available. It is not a substitute for a debugger or a race detector tool like ThreadSanitizer; rather, it complements those tools by synthesizing evidence you already have into a testable hypothesis. Avoid using this prompt when the log volume is so high that it exceeds the model's context window—pre-filter logs to the relevant time window and services before invoking the prompt. Finally, never deploy a locking fix generated by this prompt directly to production without human code review, concurrency testing, and preferably a targeted stress test that attempts to reproduce the original race condition under load. The prompt's output is a diagnostic aid, not a verified patch.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Race Condition Diagnosis Prompt delivers value and where it introduces risk. Use this to decide if the prompt fits your incident before you run it.

01

Good Fit: Intermittent Concurrency Bugs

Use when: You have distributed logs showing non-deterministic failures, and you need to reconstruct an interleaved execution timeline. Guardrail: Provide logs from all participating services and nodes; missing a participant's perspective will produce an incomplete hypothesis.

02

Bad Fit: Single-Threaded Deterministic Failures

Avoid when: The error is reproducible in a single-threaded context or is clearly a null-pointer or logic error. Guardrail: Run a stack trace root cause prompt first. If the failure is deterministic, a race condition diagnosis will hallucinate spurious concurrency conflicts.

03

Required Inputs

What you must provide: Timestamped log excerpts from multiple services, the relevant source code files for shared-state access, and the specific error signature. Guardrail: Redact PII and secrets before pasting logs. Missing source code forces the model to guess about locking mechanisms.

04

Operational Risk: False Confidence in Timeline

What to watch: The model may produce a visually convincing sequence diagram that misorders events due to clock skew or incomplete log sampling. Guardrail: Treat the output as an investigation hypothesis, not a confirmed root cause. Validate the proposed interleaving against raw timestamps manually.

05

Operational Risk: Incorrect Locking Fix

What to watch: The proposed code fix may introduce deadlocks or fail to account for non-obvious state dependencies. Guardrail: Never apply the suggested patch directly to production. Require peer review, deadlock analysis, and concurrency-specific test cases before merging.

06

Operational Risk: Log Volume Overload

What to watch: Dumping raw, unfiltered logs into the prompt can exceed context windows and bury the relevant interleaving in noise. Guardrail: Pre-filter logs to a narrow time window around the incident and grep for the specific error signature, thread IDs, or resource locks involved.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt that reconstructs race condition execution timelines from distributed logs and proposes a locking fix grounded in repository source code.

This prompt is designed to be pasted directly into your AI coding agent or LLM interface. It instructs the model to act as a concurrency-focused backend investigator, correlating interleaved log entries from multiple services or threads with the shared-state access patterns found in your repository's source code. The goal is to move beyond symptom description and produce a testable hypothesis: a sequence diagram of the suspected race and a concrete code change proposal.

text
You are a senior backend engineer specializing in distributed concurrency bugs. Your task is to diagnose a suspected race condition using application logs and the corresponding source code.

## INPUTS
- **Incident Description:** [INCIDENT_SUMMARY]
- **Logs (interleaved, with timestamps and service/thread IDs):**

[INTERLEAVED_LOGS]

code
- **Relevant Source Files:**
- `[FILE_PATH_1]`:
  ```[LANGUAGE_1]
  [SOURCE_CODE_1]
  ```
- `[FILE_PATH_2]`:
  ```[LANGUAGE_2]
  [SOURCE_CODE_2]
  ```
- **Known Shared State:** [SHARED_RESOURCE_DESCRIPTION] (e.g., database row, cache key, in-memory map)

## CONSTRAINTS
- Ground every claim in a specific log timestamp or a specific line of source code.
- If the evidence is insufficient to confirm a single root cause, state the uncertainty and list the top competing hypotheses.
- Do not propose a fix that introduces a new deadlock risk without noting it.

## OUTPUT SCHEMA
Respond with a JSON object containing the following keys:
- `execution_timeline_hypothesis`: An array of ordered steps describing the interleaved execution you believe occurred. Each step must include `timestamp`, `actor` (service/thread), `action`, and `source_evidence` (log line or code reference).
- `sequence_diagram_mermaid`: A string containing a valid Mermaid sequence diagram representing the hypothesis.
- `race_window_analysis`: A string explaining the exact lines of code where the critical section was entered without proper synchronization, and the duration of the vulnerability window.
- `locking_fix_proposal`: An object with keys `strategy` (e.g., 'pessimistic lock', 'compare-and-swap', 'queue'), `code_diff` (a unified diff string), and `trade_offs` (a list of strings noting performance impact or new risks).
- `confidence_score`: A string ('High', 'Medium', 'Low') with a one-sentence justification.
- `further_investigation`: A list of specific log statements or metrics to add to improve future diagnosability.

To adapt this template, replace the square-bracket placeholders with your actual incident data. The [INTERLEAVED_LOGS] placeholder is critical: you must merge logs from all participating services or threads and sort them by timestamp before insertion. The quality of the diagnosis depends heavily on accurate clock synchronization and complete log coverage of the shared resource access. If your logs lack thread or request IDs, add a note in the [INCIDENT_SUMMARY] so the model accounts for ambiguity. For high-severity production incidents, always have a senior engineer review the proposed locking_fix_proposal before merging any code change.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Race Condition Diagnosis Prompt from Logs. Each variable must be populated before execution to ensure reliable interleaving reconstruction and source-code correlation.

PlaceholderPurposeExampleValidation Notes

[LOG_SOURCE]

Raw distributed log entries from multiple services involved in the suspected race

service-a.log, service-b.log, kafka-consumer.log

Must contain timestamps with millisecond or microsecond precision. Parse check: confirm at least two distinct service identifiers present in the log stream.

[TIME_WINDOW]

Start and end bounds for the incident window to scope log analysis

2025-03-14T14:30:00Z to 2025-03-14T14:31:30Z

Must be ISO 8601 format. Validation: window must be narrow enough to exclude unrelated traffic but wide enough to capture full interleaving. Reject if window exceeds 5 minutes without justification.

[SHARED_RESOURCE]

Identifier for the contended resource suspected in the race condition

user_profile_cache:user_48291, orders_table:row_lock, payment_ledger:account_773

Must be a concrete resource path, not a class name. Schema check: resource identifier must match the format used in log entries and source code references. Null not allowed.

[REPOSITORY_PATH]

Absolute path to the repository containing source code for the services involved

/home/ci/projects/checkout-service

Must be a valid directory path accessible to the agent. Validation: confirm repository contains source files matching service names found in [LOG_SOURCE]. Reject if path is empty or inaccessible.

[SERVICE_MAP]

Mapping of log-origin service names to their source code directories and entry points

{"order-service": "src/orders", "payment-worker": "src/payments"}

Must be valid JSON object. Schema check: every service name appearing in [LOG_SOURCE] must have a corresponding entry. Missing mapping triggers a retry request for the unmapped service.

[LOCKING_PATTERNS]

Known locking primitives or concurrency controls used in the codebase for pattern matching

["Redis SETNX", "Postgres advisory lock", "DynamoDB conditional write"]

Must be a non-empty array. Validation: each entry must be a concrete primitive name searchable via grep or AST query. If null, the prompt will attempt discovery but confidence degrades.

[OUTPUT_SCHEMA]

Expected structure for the sequence diagram hypothesis and fix proposal

{"interleaving": [...], "root_cause": "...", "fix": {...}}

Must be a valid JSON Schema or example object. Validation: schema must include interleaving array, root_cause string, and fix object with strategy and code_patch fields. Reject malformed schemas before prompt execution.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the race condition diagnosis prompt into a production incident response workflow with validation, tool integration, and human review gates.

This prompt is designed to operate as a diagnostic step within an incident response pipeline, not as a standalone chat interaction. The implementation harness must ingest distributed log fragments, correlate them with source code from the repository, and produce a structured hypothesis that an on-call engineer can validate before acting. The prompt expects three input channels: a [LOG_FRAGMENTS] block containing timestamped log lines from multiple services or threads, a [SHARED_STATE_ACCESS_PATTERNS] block extracted from source code analysis of mutexes, locks, atomic operations, or database transactions, and a [REPOSITORY_CONTEXT] block with relevant file paths and recent commits. Wire these inputs through a pre-processing layer that deduplicates log lines, normalizes timestamps to a common timezone, and filters noise before assembly into the prompt.

The output schema must be enforced through a validation layer before the hypothesis reaches a human reviewer. Expect a JSON response with interleaving_timeline (an ordered array of events with service, thread, timestamp, and action fields), race_window_candidates (time ranges where conflicting access likely occurred), shared_state_analysis (mapping each contended resource to its locking discipline and violation evidence), and fix_proposal (a structured recommendation with code-level changes and locking strategy). Implement a schema validator that rejects responses missing required fields, containing timestamps outside the input range, or proposing fixes that reference files not present in the repository context. On validation failure, retry once with a more constrained prompt that includes the specific validation error. After two failures, escalate to a human with the partial output and error log.

Model choice matters for this workflow. Use a model with strong reasoning capabilities and a context window large enough to hold interleaved log traces from multiple services—typically 100K+ tokens for production incidents. Claude 3.5 Sonnet or GPT-4o are suitable defaults. Avoid smaller or faster models that may conflate thread identities or miss subtle ordering violations. If the log volume exceeds the context window, implement a pre-processing step that samples representative time slices around error spikes or uses log pattern clustering to reduce redundancy before prompt assembly. Do not truncate arbitrarily; missing log segments can hide the interleaving that reveals the race.

Grounding is the highest-risk failure mode. The prompt must never fabricate file paths, function names, or locking primitives that do not exist in the repository. Implement a post-processing grounding check that verifies every file path and function name in the fix_proposal against the repository's symbol index. Flag any hallucinated references for human review. Additionally, log every prompt invocation with the input hash, output hash, validation result, grounding check result, and reviewer decision. This audit trail is essential for post-incident review and for improving the prompt over time. Store these records in the incident management system, not in ephemeral chat logs.

Human review is mandatory before applying any fix proposal. The prompt output is a diagnostic hypothesis, not a verified root cause. The review interface should display the interleaving timeline as a swimlane diagram, highlight the race window candidates on a shared timeline, and show the proposed code changes as a diff against the current repository state. The reviewer must confirm or reject each race window candidate and approve or modify the fix before it enters the deployment pipeline. Never automate code changes from this prompt without human approval—race condition fixes can introduce deadlocks or performance regressions if applied without understanding the full concurrency model.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured output schema for the race condition diagnosis prompt. Each field must be validated before the output is accepted by downstream tooling or human review. Use this contract to build a parser, validator, or retry condition in your AI harness.

Field or ElementType or FormatRequiredValidation Rule

race_condition_hypothesis

string

Must be non-empty and contain a specific concurrency bug description, not a generic statement like 'a race condition exists'.

confidence_score

float

Must be between 0.0 and 1.0. If below 0.5, the diagnosis should be routed for human review before any fix is proposed.

interleaved_timeline

array of objects

Array must contain at least 2 entries. Each entry must have 'timestamp' (ISO 8601), 'thread_or_pod_id' (string), and 'event' (string) fields.

shared_state_accesses

array of objects

Each object must include 'variable_or_resource' (string), 'access_type' (enum: READ | WRITE), and 'source_file' (string with path). Source file must exist in the provided repository context.

sequence_diagram_mermaid

string

If provided, must be valid Mermaid.js sequence diagram syntax. Parse check required. If null, the output is still valid but less actionable.

locking_fix_proposal

object

Must contain 'strategy' (string), 'target_resource' (string), and 'code_snippet' (string). Code snippet must be parseable by the target language's AST parser.

evidence_log_lines

array of strings

Each string must be an exact, unaltered line from the provided log input. A citation check must confirm each line exists in the source material.

requires_human_review

boolean

Must be true if confidence_score < 0.7 or if the locking_fix_proposal modifies more than 3 files. This flag gates automatic patch application in the harness.

PRACTICAL GUARDRAILS

Common Failure Modes

Race condition diagnosis from logs is inherently probabilistic. The model must reconstruct interleaved timelines from incomplete evidence. These are the most common failure modes and how to guard against them before the diagnosis reaches an on-call engineer.

01

Hallucinated Timeline Events

What to watch: The model invents log entries or event ordering to fill gaps in the evidence, creating a plausible but fictional execution sequence. Guardrail: Require every timeline event to cite a specific log line or source-code line. Add a validator that rejects events without a source_evidence field.

02

Spurious Lock Attribution

What to watch: The model blames a specific mutex, semaphore, or database row lock without sufficient evidence, often defaulting to the most visible lock in the codebase. Guardrail: Require the prompt to list all candidate shared-state access points and rank them by contention evidence. Flag diagnoses that name only one lock without alternatives.

03

Ignoring Clock Skew and Timestamp Drift

What to watch: The model treats log timestamps as globally ordered ground truth, missing that distributed nodes may have seconds of clock skew that invert the true causal order. Guardrail: Include a pre-processing step that flags timestamp anomalies and instructs the model to treat near-simultaneous events as unordered unless a causal link is proven.

04

Confirmation Bias Toward Recent Changes

What to watch: The model overweights recent commits or deployments as the root cause, even when the race condition existed latently for months and was only surfaced by a traffic shift. Guardrail: Require the prompt to evaluate both recent changes and long-standing code paths. Add a counterfactual check: 'Would this race exist before the recent change?'

05

Sequence Diagram Over-Specification

What to watch: The model produces a single, high-confidence sequence diagram that hides alternative interleavings, making the diagnosis look more certain than the evidence supports. Guardrail: Require the output to include at least two plausible interleaving hypotheses with confidence scores. Flag any output that presents only one timeline without uncertainty language.

06

Missing Read-Modify-Write Detection

What to watch: The model identifies write-write conflicts but misses read-modify-write races where a stale read leads to an incorrect update, which are harder to spot in logs. Guardrail: Explicitly instruct the model to scan for patterns where a read and subsequent write are separated by an intervening write from another thread or request. Include a checklist item for this pattern.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the Race Condition Diagnosis Prompt's output quality before shipping. Each row defines a pass standard, a failure signal, and a concrete test method to validate correctness, grounding, and actionability.

CriterionPass StandardFailure SignalTest Method

Source Code Grounding

Every shared-state access point in the sequence diagram is linked to a specific file path and line number from the repository.

Sequence diagram references generic variable names or functions without file paths; hallucinated code locations.

Parse output for all code references. Assert each reference exists in the provided repository context using a grep or AST lookup script.

Timeline Reconstruction Accuracy

The interleaved execution timeline correctly orders log entries from multiple services based on their timestamps, accounting for clock skew.

Events from Service A appear after Service B events they are known to have caused; timeline ignores explicit clock skew warnings in the prompt.

Provide a synthetic log set with a known race condition. Compare the model's event ordering against the ground-truth causal order.

Locking Fix Proposal Validity

The proposed locking strategy (e.g., mutex, DB row lock) is syntactically correct for the target language and protects the identified critical section.

Proposed fix introduces a deadlock, uses a lock type unavailable in the language, or locks a resource unrelated to the diagnosed race.

Extract the proposed code patch. Run a static analysis tool (e.g., deadlock or language-specific linter) against it. Verify the lock guards the exact code block identified in the sequence diagram.

Hallucination Resistance

The output does not invent log entries, timestamps, or code functions not present in the provided [INPUT_LOGS] or [REPO_CONTEXT].

The diagnosis cites a 'missing log line' as evidence or references a function not found in the repository.

Tokenize the output claims. Cross-reference each claim of fact (log presence, function name) against the input data. Flag any claim with zero matches as a hallucination.

Output Schema Compliance

The response is valid JSON matching the [OUTPUT_SCHEMA] exactly, including the sequence_diagram, shared_state_accesses, and fix_proposal objects.

JSON is malformed, missing required fields, or contains extra untyped fields that break downstream parsers.

Validate the raw output string against the expected JSON Schema using a programmatic validator (e.g., ajv, jsonschema). Reject on any schema violation.

Concurrency Terminology Precision

The diagnosis correctly uses terms like 'race condition', 'deadlock', 'critical section', and 'mutual exclusion' in the correct technical context.

The output mislabels a deadlock as a race condition, or uses 'semaphore' when a 'mutex' is the correct primitive for the described scenario.

Maintain a glossary of correct definitions. Use an LLM-as-judge with a targeted rubric to check if each term's usage matches its definition in the context of the described bug.

Fix Actionability

The fix_proposal includes a concrete code diff or step-by-step refactoring instructions that an engineer can apply directly.

The proposal contains vague advice like 'add better locking' or 'review the code for thread safety' without specifying where or how.

Present the fix_proposal text to a developer not involved in the prompt design. Ask them to rate if they could implement the fix without additional information. Pass if rating is >= 4/5.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single service's logs. Remove multi-service correlation requirements and focus on one shared resource (e.g., a single database row or counter). Use a simplified output: just a timeline hypothesis and one locking fix suggestion.

code
Analyze these logs from [SERVICE_NAME] for evidence of race conditions on [SHARED_RESOURCE].

Logs:
[LOG_SNIPPETS]

Output a timeline of interleaved operations and one locking recommendation.

Watch for

  • Single-service analysis misses cross-service races
  • Timestamps may lack sufficient precision for ordering
  • No validation that the shared resource is actually contended
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.