Inferensys

Prompt

PR Diff Race Condition Detection Prompt Template

A practical prompt playbook for using PR Diff Race Condition Detection Prompt Template in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Deploy this prompt in CI/CD pipelines and code review tools to automatically detect concurrency defects in pull request diffs before they reach production.

This prompt is built for backend engineers, platform teams, and CI/CD pipelines that need automated, structured detection of race conditions, data races, and unsafe concurrent access patterns in pull request diffs. It ingests a unified diff or a set of changed files with clear before/after context and produces file-and-line-specific findings that can be fed directly into review comments, CI check annotations, or triage queues. The core job-to-be-done is shifting concurrency defect detection left—catching the class of bugs that are notoriously difficult to reproduce, diagnose, and fix after deployment.

Use this prompt when you have a concrete code change to review and you want findings scoped exclusively to concurrency risks: unsynchronized shared state mutations, lock ordering violations, missing memory barriers, goroutine or thread lifecycle bugs, channel operation deadlocks, and transaction boundary gaps. The prompt assumes the input is a well-formed diff with sufficient context lines to reason about synchronization scope. It is not a general-purpose code reviewer, style checker, or security scanner. Do not use it for reviewing documentation changes, configuration-only diffs with no concurrent execution paths, or codebases where the concurrency model is entirely external to the submitted code (e.g., a single-threaded event loop with no shared state).

Before wiring this into an automated pipeline, validate the output against a golden set of known concurrency bugs and benign changes to calibrate your false positive tolerance. The prompt produces structured severity classifications—always require human review for CRITICAL and HIGH findings that involve data corruption risks or production exposure. For lower-severity findings, you can configure auto-commenting on the PR, but maintain a feedback loop where developers can dispute or confirm findings to improve your eval dataset over time. The next section provides the copy-ready prompt template you can adapt with your language, framework, and output schema requirements.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if the PR Diff Race Condition Detection template fits your current review workflow.

01

Good Fit: Backend PRs with Shared State

Use when: the diff modifies shared variables, caches, connection pools, or in-memory data structures accessed by multiple goroutines, threads, or async tasks. Why: the prompt is tuned to spot unsynchronized reads/writes and compound non-atomic operations that static analyzers often miss.

02

Bad Fit: Frontend or Single-Threaded Scripts

Avoid when: reviewing UI component code, single-threaded CLI tools, or simple CRUD endpoints with no concurrent execution path. Risk: the model will hallucinate race conditions where none exist, wasting reviewer time on false positives. Use a standard code review prompt instead.

03

Required Inputs: Diff, Language, and Concurrency Model

What you must provide: a unified diff with file paths, the target language, and the concurrency model in use (goroutines, async/await, threads, actors). Guardrail: without the concurrency model, the prompt cannot distinguish intentional async patterns from dangerous ones. Add a [CONCURRENCY_MODEL] placeholder.

04

Operational Risk: High False Positive Rate on Unfamiliar Frameworks

What to watch: the model may flag framework-managed lifecycle code as unsafe when the framework guarantees thread safety. Guardrail: always pair this prompt with a [FRAMEWORK_CONTEXT] field listing known-safe abstractions. Run findings through a suppression list before surfacing to developers.

05

Pipeline Integration: Pre-Merge CI, Not Post-Deploy Forensics

Use when: blocking or commenting on PRs before merge. Avoid when: investigating production incidents where runtime traces and logs are available. Guardrail: for production debugging, switch to the Concurrency Bug Triage and Routing Prompt, which expects runtime evidence rather than static diffs.

06

Scale Limit: Diff Size and Review Latency

What to watch: diffs over 2000 lines or 50 files can exceed context windows or produce shallow analysis. Guardrail: chunk large diffs by module or file group, run the prompt per chunk, and deduplicate findings. Set a CI timeout and fall back to a summary-only mode for oversized PRs.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

Paste this prompt into your AI system to analyze a PR diff for race conditions and receive structured JSON findings.

This prompt instructs the model to act as a concurrency review specialist. It is designed to be dropped into a CI/CD pipeline, a code review agent, or a developer's local toolchain. The model receives a unified diff, a language context, and a risk tolerance level, then returns a structured JSON array of findings. Each finding includes the file path, line range, severity, a description of the potential race, and a suggested fix. The prompt enforces a strict output schema to ensure downstream systems can parse and act on the results without additional transformation.

text
You are a senior systems engineer specializing in concurrency and race condition detection. Your task is to analyze the provided code diff for potential race conditions, data races, deadlock risks, and unsafe concurrent access patterns.

## INPUT
- **Diff**: [DIFF]
- **Language**: [LANGUAGE]
- **Risk Tolerance**: [RISK_LEVEL] (Options: "strict", "moderate", "permissive")
- **Context**: [CONTEXT] (Optional: architectural notes, known concurrency models, or related file summaries)

## CONSTRAINTS
- Only report findings with a clear concurrency root cause. Do not flag style issues, general code smells, or non-concurrency bugs.
- For each finding, you must cite the specific file path and line range from the diff.
- If the diff contains no concurrency issues, return an empty findings array.
- Do not hallucinate line numbers or file paths that are not present in the diff.
- For "strict" risk tolerance, flag even theoretical races with low probability. For "permissive", only flag high-confidence, high-impact races.

## OUTPUT SCHEMA
Return ONLY a valid JSON object with the following structure. Do not include any text outside the JSON object.

{
  "findings": [
    {
      "file": "string (relative path from diff)",
      "line_range": "string (e.g., 'L45-L52')",
      "severity": "string (Options: 'critical', 'high', 'medium', 'low')",
      "category": "string (Options: 'data_race', 'deadlock', 'atomicity_violation', 'ordering_violation', 'unsafe_publication', 'thread_confinement_violation', 'goroutine_leak', 'channel_deadlock', 'lock_contention', 'other')",
      "description": "string (concise explanation of the race condition and why it is unsafe)",
      "reproduction_scenario": "string (brief description of the interleaving or condition that triggers the bug)",
      "fix_suggestion": "string (concrete, actionable fix with code pattern or synchronization primitive recommendation)",
      "confidence": "number (0.0 to 1.0, indicating how confident you are that this is a real bug)"
    }
  ],
  "summary": {
    "total_findings": "number",
    "critical_count": "number",
    "high_count": "number",
    "medium_count": "number",
    "low_count": "number",
    "overall_risk_assessment": "string (one-sentence summary of the diff's concurrency risk profile)"
  }
}

## EXAMPLES
[EXAMPLES]

Analyze the diff now. Return only the JSON object.

To adapt this template, replace the square-bracket placeholders with real values before execution. The [DIFF] placeholder should contain the full unified diff text. The [LANGUAGE] field helps the model apply language-specific concurrency rules—for example, Go's goroutine and channel semantics differ from Java's synchronized blocks or Python's asyncio. The [RISK_LEVEL] parameter controls the sensitivity of the analysis: use "strict" for security-critical or financial transaction code, and "permissive" for low-risk utility scripts to reduce false positives. The optional [CONTEXT] field can include architectural notes, such as "this service uses a shared-nothing worker pool" or "all database access goes through a connection pool with serializable isolation," which helps the model avoid flagging patterns that are safe in context. The [EXAMPLES] placeholder should be replaced with one or two few-shot examples of correct input-output pairs to improve output consistency, especially for the category and severity fields.

Before integrating this prompt into a production pipeline, you must add validation and evaluation layers. Validate the output JSON against the schema to catch malformed responses. Run the prompt against a golden dataset of known concurrency bugs and confirmed clean diffs to measure false positive and false negative rates. For high-risk code paths, route findings with severity: 'critical' or confidence below 0.7 to a human reviewer. Log every invocation with the diff hash, model version, and output for auditability. Do not use this prompt as the sole gate for merge decisions on critical infrastructure or security-sensitive code paths without human review.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the PR Diff Race Condition Detection prompt needs to work reliably. Validate each before sending to the model to prevent hallucinated file paths, missed severity signals, and false positives.

PlaceholderPurposeExampleValidation Notes

[DIFF_CONTENT]

Unified diff of the pull request to analyze for race conditions

diff --git a/pkg/queue/worker.go b/pkg/queue/worker.go @@ -45,7 +45,8 @@ func (w *Worker) Process() {

  • w.mu.Lock()
  • defer w.mu.Unlock()
  • w.count++ }

Parse check: must be valid unified diff format. Reject empty diffs. Reject diffs exceeding model context window (truncate with warning). Strip binary file diffs before sending.

[LANGUAGE]

Programming language of the code under review to activate language-specific concurrency rules

Go

Enum check: must match supported languages (Go, Java, Python, C++, Rust, C#, JavaScript/TypeScript, Kotlin). Reject unsupported languages with clear error. Default concurrency model selection depends on this value.

[CONCURRENCY_MODEL]

Concurrency primitives and patterns in use to narrow detection scope

goroutines, channels, sync.Mutex

Null allowed: if null, model infers from code. If provided, validate against known primitives for [LANGUAGE]. Mismatch between model and code patterns degrades precision.

[SEVERITY_THRESHOLD]

Minimum severity level to include in output to control noise

medium

Enum check: must be low, medium, high, or critical. Default to medium if null. Lower thresholds increase false positive rate. Higher thresholds risk missing data corruption bugs.

[KNOWN_FALSE_POSITIVE_PATTERNS]

Patterns or file paths to suppress from output to reduce reviewer fatigue

pkg/sync/atomic_counter.go: safe atomic increment pattern

Null allowed. If provided, each entry must include file path and justification. Model must cite which suppression rule it applied for each suppressed finding. Validate suppression rules don't mask real bugs.

[CONTEXT_WINDOW_LINES]

Number of surrounding lines to include per finding for reviewer comprehension

15

Integer check: range 5-50. Default 20 if null. Values below 10 may omit critical synchronization context. Values above 30 increase token cost without proportional benefit.

[OUTPUT_SCHEMA]

Expected JSON schema for structured findings to enable CI/CD integration

{"findings": [{"file": "string", "line_start": int, "line_end": int, "severity": "string", "category": "string", "description": "string", "fix_suggestion": "string"}]}

Schema check: validate against JSON Schema before sending. Reject missing required fields. Category must be from allowed enum: data_race, deadlock, atomicity_violation, ordering_violation, thread_safety, channel_misuse, lock_misuse, other.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the PR Diff Race Condition Detection prompt into a CI/CD pipeline or review automation system with validation, retries, and human review gates.

Integrating the PR Diff Race Condition Detection prompt into a CI/CD pipeline requires treating it as a deterministic analysis step with structured output, not a conversational assistant. The prompt expects a code diff, a target language, and a risk tolerance level as inputs, and it returns a JSON array of findings with file paths, line ranges, severity scores, and fix suggestions. The implementation harness must validate this output schema before any finding reaches a developer or blocks a merge. Because concurrency bugs are high-severity defects that can cause data corruption, the harness should default to conservative behavior: when the model returns low-confidence results, when the output fails schema validation, or when the diff exceeds the model's context window, the system must escalate for human review rather than silently passing the change.

A production-grade harness for this prompt typically includes: (1) a diff preprocessor that chunks large diffs by file or hunk and respects the model's token limit, (2) a model invocation layer with retry logic for transient failures and a timeout appropriate to the diff size, (3) a JSON schema validator that rejects malformed findings and logs schema violations for prompt debugging, (4) a severity filter that routes CRITICAL and HIGH findings to a blocking review queue while allowing LOW findings to pass with annotations, and (5) an audit log that records the prompt version, model version, input diff hash, raw output, and validation result for every run. For teams using GitHub Actions or GitLab CI, the harness can run as a required status check that posts findings as inline review comments mapped to the relevant lines. For teams with existing code review tools like Gerrit or Phabricator, the harness should emit findings in the tool's native review format.

Model choice matters here. Concurrency analysis requires precise reasoning about execution order, memory visibility, and language-specific memory models. Claude 3.5 Sonnet and GPT-4o currently produce the most reliable structured findings for this task, but they still require validation. Open-weight models like Llama 3.1 70B can work for this prompt when run with structured output constraints, but expect higher false positive rates and plan for a human triage step on all findings. Do not use this prompt with models below roughly 30B parameters for production concurrency review—smaller models lack the reasoning depth to distinguish true races from benign concurrent access patterns. Always pin the model version in your harness configuration and re-baseline your eval set when upgrading models. The eval set should include known concurrency bugs from your own codebase history plus curated examples from concurrency bug databases to measure both recall and false positive rate before deployment.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required structure for the model's JSON response when analyzing a PR diff for race conditions. Use this contract to validate outputs before they enter your CI pipeline or review dashboard.

Field or ElementType or FormatRequiredValidation Rule

findings

Array of objects

Must be present even if empty. Schema check: validate each element against the finding object contract.

findings[].id

String (UUID v4)

Must match UUID v4 regex. Uniqueness check: no duplicate IDs within the array.

findings[].severity

Enum: CRITICAL, HIGH, MEDIUM, LOW

Must be one of the four defined values. No free-text or null allowed.

findings[].file_path

String

Must be a non-empty string. Parse check: verify the path exists in the provided [DIFF_CONTEXT] if available.

findings[].line_range

Object with start and end integers

start and end must be positive integers with start <= end. Schema check: validate integer types.

findings[].category

Enum: DATA_RACE, DEADLOCK, ATOMICITY_VIOLATION, ORDERING_VIOLATION, LOCK_CONTENTION, THREAD_SAFETY

Must be one of the defined enum values. No null or generic strings allowed.

findings[].confidence

Number (0.0 to 1.0)

Must be a float between 0.0 and 1.0 inclusive. Retry condition: if confidence < 0.7, flag for human review.

findings[].description

String

Must be a non-empty string between 20 and 500 characters. Length check: enforce min/max bounds.

PRACTICAL GUARDRAILS

Common Failure Modes

Race condition detection prompts fail in predictable ways. Here are the most common failure modes when analyzing PR diffs for concurrency bugs, and how to guard against them.

01

False Positives on Safe Patterns

What to watch: The prompt flags thread-safe patterns like read-only shared state, properly synchronized lazy initialization, or immutable data structures as race conditions. This erodes reviewer trust and creates alert fatigue. Guardrail: Include explicit safe-pattern examples in the prompt's few-shot demonstrations. Add a pre-classification step that checks whether shared state is actually mutated before flagging. Require the model to cite the specific variable and access path, not just the file.

02

Missed Races Across File Boundaries

What to watch: The prompt only analyzes the diff in isolation and misses races where a shared variable is mutated in one file and read in another, because neither file alone shows the full concurrent access pattern. Guardrail: Expand the analysis context to include cross-file references for shared state. Use a retrieval step to pull in the declaration and all access sites of shared variables before running the race detection prompt. Flag any shared variable whose full access graph isn't visible in the diff.

03

Channel and Async Misinterpretation

What to watch: The prompt misinterprets channel sends, async/await patterns, or promise chains as race conditions when they actually enforce ordering. Conversely, it misses races hidden in complex async control flow where ordering isn't guaranteed. Guardrail: Include language-specific concurrency model documentation in the system prompt. For Go, explicitly define channel happens-before semantics. For JavaScript, define the microtask vs macrotask ordering rules. Test against known async race examples and known safe async patterns.

04

Severity Inflation on Low-Risk Races

What to watch: The prompt assigns critical severity to races on non-critical paths, such as a race on a debug log counter or a metrics increment, distracting from genuinely dangerous races on data integrity or security paths. Guardrail: Add a severity calibration step that considers the blast radius of the shared state. Require the prompt to classify whether the race affects data correctness, security boundaries, or only observability. Use a structured severity rubric with explicit criteria for each level.

05

Lock Granularity Over-Correction

What to watch: The prompt suggests adding locks to every shared access without considering whether a broader lock scope, a lock-free alternative, or a design change would be better. This produces correct but performance-degrading suggestions. Guardrail: Include a post-detection analysis step that evaluates whether the suggested fix introduces contention risk. Require the prompt to consider lock-free alternatives and design-level fixes before recommending additional synchronization. Test fix suggestions against throughput benchmarks.

06

Context Window Truncation on Large Diffs

What to watch: Large PRs with many files cause the prompt to exceed context limits, leading to truncated analysis where only the first N files are reviewed and races in later files are silently missed. Guardrail: Chunk the diff by file or by shared-state cluster before analysis. Run the detection prompt independently on each chunk with overlapping context for shared variables. Implement a coverage check that verifies every file in the diff was analyzed and report gaps explicitly.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the PR Diff Race Condition Detection Prompt before production deployment. Each row defines a pass standard, a failure signal, and a concrete test method to validate output quality against known concurrency bug patterns.

CriterionPass StandardFailure SignalTest Method

True Positive Detection

Prompt identifies >= 90% of seeded race conditions in a golden diff set derived from known concurrency bug databases

Misses known data races or unsafe concurrent access patterns present in the diff

Run prompt against a curated set of 20+ diffs containing confirmed race conditions; compare structured findings against ground truth labels

False Positive Rate

Prompt flags no more than 1 false positive per 500 lines of diff code reviewed

Flags synchronized blocks, thread-safe collections, or correctly ordered lock acquisitions as race conditions

Run prompt against a set of 10+ diffs with known thread-safe code; count false positives and calculate rate per lines reviewed

File Path and Line Range Accuracy

Every finding includes a file path and line range that matches the actual location of the risky code in the diff

Line ranges point to unrelated code, fall outside the diff hunk, or reference files not in the change set

Parse output JSON; for each finding, verify file path exists in the diff and line range intersects the changed lines using a scripted validator

Severity Classification Consistency

Severity levels (e.g., Critical, High, Medium, Low) align with a predefined rubric based on data corruption risk, reproducibility, and production exposure

A benign logging race is marked Critical or a data-corrupting write-write race is marked Low

Apply a severity rubric to 15+ known findings; compare prompt-assigned severity to rubric-expected severity; require >= 85% agreement

Fix Suggestion Actionability

Each finding includes a concrete fix suggestion with a specific synchronization primitive, lock ordering change, or atomic operation recommendation

Fix suggestions are generic (e.g., 'add synchronization') without naming the primitive, scope, or code location

Review fix suggestions for 10+ findings; each must reference a language-appropriate primitive (e.g., sync.Mutex, AtomicInteger, synchronized block) and the target code location

Output Schema Compliance

Every response parses as valid JSON matching the defined [OUTPUT_SCHEMA] with all required fields present and correctly typed

Missing required fields, incorrect types (e.g., string instead of array for line_range), or unparseable JSON

Validate each response against the JSON Schema using a programmatic validator; reject any response that fails schema validation

Cross-File Race Detection

Prompt identifies race conditions that span multiple files when shared state is accessed across file boundaries in the diff

Only detects races within a single file and misses cross-file shared state access patterns

Include 5+ diffs with cross-file race conditions in the test set; verify prompt findings reference both files involved in the shared state access

Non-Atomic Operation Recognition

Prompt flags compound operations (check-then-act, read-modify-write) that lack transactional or synchronization protection

Misses check-then-act patterns or incorrectly flags atomic compare-and-swap operations as non-atomic

Test against 8+ diffs containing known non-atomic compound operations; verify each is detected and each atomic operation is not falsely flagged

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add strict JSON schema validation, retry logic on malformed output, structured logging of each finding, and eval cases drawn from known concurrency bug databases. Integrate with CI/CD to block merges on high-severity findings.

Prompt modification

  • Enforce [OUTPUT_SCHEMA] with required fields: file_path, line_range, severity, race_type, description, fix_suggestion, confidence_score.
  • Add [CONSTRAINTS]: "Return ONLY valid JSON matching the schema. If no race conditions are found, return an empty findings array. Do not include explanations outside the JSON."
  • Include language-specific concurrency model documentation in [CONTEXT].
  • Add a retry wrapper: if JSON parse fails, resubmit with the parse error message appended to [CONSTRAINTS].

Watch for

  • Silent format drift where the model adds extra fields or commentary outside the JSON.
  • False positives on idiomatic patterns that are thread-safe by convention (e.g., Go's sync.Once, Python's GIL-protected operations).
  • Missing human review gate for critical-path code changes.
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.