Inferensys

Prompt

Synchronization Primitive Misuse Detection Prompt

A practical prompt playbook for using Synchronization Primitive Misuse Detection Prompt 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

Defines the ideal job-to-be-done, user profile, required context, and explicit boundaries for the synchronization primitive misuse detection prompt.

This prompt is designed for systems engineers and platform teams who need to detect incorrect usage of synchronization primitives—mutexes, semaphores, condition variables, and barriers—in code changes. The core job-to-be-done is to receive a code snippet or diff and produce a structured misuse report that identifies specific bugs, rates their severity, and provides the correct usage pattern for the target language. It is intended to be embedded in pre-merge code review pipelines, static analysis triage workflows, or as a dedicated step in a concurrency bug detection harness where a human reviewer needs a reliable, structured second opinion before code reaches production.

The prompt assumes the input code is syntactically valid for the target language and that the reviewer requires a report with concrete findings, not a general code quality assessment. It is optimized for detecting double-lock risks, signal-before-wait bugs, incorrect unlock patterns (e.g., unlocking a mutex from a thread that does not own it), and spurious wakeup vulnerabilities. The output is expected to be a structured JSON report containing a list of findings, each with a severity rating, the offending code location, an explanation of the misuse, and the correct synchronization pattern. For high-risk domains, the prompt's output should be treated as a triage aid, not a final verdict; a human reviewer must confirm findings before blocking a merge or filing a bug.

Do not use this prompt for general code style review, performance profiling, or security vulnerability assessment outside of synchronization primitive misuse. It is not designed to reason about algorithmic correctness, business logic errors, or memory safety issues unrelated to concurrency control. If the input code does not contain any synchronization primitives, the prompt will return an empty finding set, which is the expected behavior. Before integrating this prompt into a CI/CD pipeline, validate its output against a golden dataset of known concurrency bugs and benign code samples to calibrate your acceptable false positive rate and ensure the severity ratings align with your team's risk tolerance.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Understand the operational boundaries before integrating it into a CI pipeline or review workflow.

01

Good Fit: Pre-Merge Code Review

Use when: A developer submits a PR that introduces or modifies mutex, semaphore, or condition variable usage in C, C++, Go, or Rust. Guardrail: Run the prompt as a required CI check, but treat its output as advisory. A senior engineer must confirm findings before blocking the merge.

02

Bad Fit: Runtime Production Debugging

Avoid when: You are analyzing a live heap dump or crash log to find an active deadlock. Guardrail: This prompt analyzes static code structure, not dynamic traces. Pair it with a runtime analysis tool like gdb or rr to confirm lock ordering hypotheses before taking action.

03

Required Inputs

What to watch: The prompt fails silently if given only a partial diff without the lock acquisition and release sites. Guardrail: Ensure the input includes the full function context for every lock() and unlock() call. If the diff is large, pre-filter it to only files touching synchronization primitives.

04

Operational Risk: False Positives

What to watch: The model may flag correct, non-trivial lock patterns (e.g., try-lock loops, lock-free algorithms) as misuse. Guardrail: Track the false positive rate over 50 reviews. If it exceeds 20%, add a few-shot example of the correct pattern to the prompt or implement a suppression list for known-safe idioms.

05

Operational Risk: Language-Specific Semantics

What to watch: A generic prompt may misdiagnose a Go sync.Mutex or a Rust std::sync::Mutex by applying POSIX-thread semantics. Guardrail: Always set the [LANGUAGE] variable explicitly. For Rust, add a constraint to check for Send and Sync trait violations. For Go, add a check for goroutine leaks via channel misuse.

06

When Not to Use: High-Level Design Review

What to watch: The prompt is designed for primitive misuse, not for evaluating whether a lock-free queue is a better architectural choice than a mutex. Guardrail: Do not use this prompt for architecture decisions. Use a separate "Software Architecture and Design Review" prompt to evaluate concurrency models before writing code.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for detecting synchronization primitive misuse in code, ready to copy and adapt with your own inputs.

This prompt template is designed to be dropped into your code review pipeline, IDE, or CI harness. It expects a code snippet, the target language, and a set of synchronization primitives to inspect. The placeholders let you control the scope of analysis, the output format, and the risk tolerance. Adapt the [CONSTRAINTS] block to match your team's coding standards, and replace [OUTPUT_SCHEMA] with the exact JSON schema your review tooling expects. The template is self-contained: a developer can paste it into a chat interface with a code block and get a structured misuse report without needing the rest of the playbook.

text
You are a systems concurrency reviewer. Analyze the provided code for synchronization primitive misuse.

## Input
[CODE]

## Target Language
[LANGUAGE]

## Primitives to Inspect
[PRIMITIVES]

## Constraints
- Flag only confirmed or highly likely misuse patterns. Do not flag correct but unusual usage.
- For each finding, cite the exact line or line range.
- If the code is correct, return an empty findings list.
- [CONSTRAINTS]

## Output Schema
Return a JSON object matching this schema exactly:
[OUTPUT_SCHEMA]

## Examples
[EXAMPLES]

## Risk Level
[RISK_LEVEL]

To adapt this template, start by defining [PRIMITIVES] as a comma-separated list: mutex, semaphore, condition_variable, barrier. Set [RISK_LEVEL] to high if you want the model to flag even subtle anti-patterns like spurious wakeup vulnerabilities, or medium for a focus on clear-cut bugs like double-lock attempts. The [OUTPUT_SCHEMA] should be a strict JSON schema including fields like findings, severity, line_range, misuse_type, explanation, and fix_suggestion. If you have known good and bad examples from your codebase, add them to [EXAMPLES] as few-shot pairs to calibrate the model to your team's conventions. After generating the report, always validate the JSON structure and run the findings through a human reviewer when the code touches production data paths or security boundaries.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Synchronization Primitive Misuse Detection Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to programmatically verify the input before execution.

PlaceholderPurposeExampleValidation Notes

[CODE_SNIPPET]

The source code block to analyze for synchronization primitive misuse

func (c *Cache) Set(k string, v any) { c.mu.Lock(); defer c.mu.Unlock(); c.items[k] = v }

Must be non-empty string. Validate length > 0 and < 8000 tokens. Reject binary or non-text content.

[LANGUAGE]

Target programming language for correct usage pattern generation

Go

Must match a supported language enum: Go, Java, C++, Rust, Python, C. Reject unsupported values with clear error message.

[PRIMITIVE_TYPES]

List of synchronization primitives to check for misuse

["sync.Mutex", "sync.RWMutex", "sync.WaitGroup", "sync.Cond"]

Must be valid JSON array of strings. Each string must match known primitive names for the target language. Empty array triggers all-primitives scan.

[CONTEXT_SCOPE]

Surrounding code context including imports, struct definitions, and caller patterns

type Cache struct { mu sync.Mutex; items map[string]any }

Optional string. When provided, must be valid code syntax for the target language. Null allowed. If null, analysis is limited to the snippet only.

[KNOWN_PATTERNS]

Organization-specific misuse patterns or anti-patterns to prioritize

["Unlock without defer", "Lock outside constructor"]

Optional JSON array of strings. Each entry must match a pattern name from the organization's concurrency pattern catalog. Null or empty array uses default pattern set.

[SEVERITY_THRESHOLD]

Minimum severity level to include in output

medium

Must be one of: low, medium, high, critical. Findings below this threshold are excluded from the report. Defaults to medium if null.

[OUTPUT_FORMAT]

Desired output structure for downstream consumption

json

Must be one of: json, markdown, sarif. JSON is required for automated pipeline integration. SARIF enables direct ingestion into code scanning platforms.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Synchronization Primitive Misuse Detection Prompt into a code review pipeline or developer workflow.

This prompt is designed to operate as a pre-merge analysis gate in a CI/CD pipeline or as an on-demand review tool in a developer's IDE. The core integration pattern is: extract a code diff or file content, inject it into the [CODE_INPUT] placeholder along with the [LANGUAGE] and [PRIMITIVE_TYPES] constraints, run the model, and parse the structured JSON output for actionable findings. Because concurrency bugs are high-severity and hard to reproduce, the harness must treat model output as advisory evidence rather than a blocking verdict—every finding should be linked to a specific line range and require human confirmation before a PR is blocked.

Validation and retry logic is critical. The prompt requests a strict JSON array of finding objects with fields like severity, line_range, primitive, misuse_type, and fix_suggestion. The harness must validate that the response parses as valid JSON, that each finding contains the required fields, and that line_range values map to actual lines in the input code. If validation fails, implement a single retry with the error message appended to the prompt context. If the retry also fails, log the raw output and surface it for manual review rather than silently dropping findings. For high-risk code paths (e.g., payment processing, safety-critical systems), route all `severity:

critical"` findings to a human approval queue before the PR can merge."

Model choice and tool integration should match the risk profile. For routine PR review, a fast model like Claude 3.5 Haiku or GPT-4o-mini works well with a temperature of 0.1 to keep output deterministic. For security-sensitive or kernel-level code, use a more capable model (Claude 3.5 Sonnet or GPT-4o) and consider pairing the prompt with a static analysis tool like ThreadSanitizer or Helgrind—use the model to interpret and deduplicate the tool's raw output rather than scanning code from scratch. If your codebase has runtime lock tracing data, inject it into the [RUNTIME_TRACE] placeholder to ground the model's analysis in observed behavior. Log every invocation with the prompt version, model, input hash, and output findings to enable prompt regression testing and audit trails.

What to avoid in production: Do not use this prompt as the sole gate for blocking merges without human review. Do not skip validation of line ranges—models can hallucinate line numbers. Do not run on entire repositories in a single call; chunk by file or diff to stay within context windows and keep findings localized. Do not ignore false positive feedback—maintain a suppression list of known false-positive patterns and feed them back into the prompt's [KNOWN_FALSE_POSITIVES] placeholder to improve precision over time. Start with a shadow mode deployment where findings are logged but not blocking, calibrate against your team's manual review accuracy, and only then promote to a soft gate with human escalation for critical findings.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the synchronization primitive misuse detection report. Use this contract to parse, validate, and integrate the model's output into downstream tooling or review queues.

Field or ElementType or FormatRequiredValidation Rule

misuse_report

JSON Object

Top-level object must parse as valid JSON. Schema check: contains 'findings', 'summary', and 'metadata' keys.

findings

Array of Objects

Must be a non-null array. If no misuses are detected, return an empty array. Schema check: each element must match the 'finding' object schema.

findings[].id

String (kebab-case)

Must match pattern ^[a-z]+(-[a-z]+)*$. Must be unique within the findings array. Parse check: no duplicate IDs.

findings[].severity

Enum String

Must be one of: 'critical', 'high', 'medium', 'low'. Enum check: reject any other value. Critical is reserved for guaranteed deadlock or data corruption with no workaround.

findings[].location

Object

Must contain 'file_path' (String), 'line_start' (Integer), and 'line_end' (Integer). Parse check: line_end >= line_start.

findings[].misuse_type

Enum String

Must be one of: 'double_lock', 'missing_unlock', 'signal_before_wait', 'spurious_wakeup_vulnerability', 'incorrect_barrier_usage', 'lock_ordering_violation', 'deadlock_cycle'. Enum check: reject unknown types.

findings[].description

String

Must be a non-empty string under 500 characters. Content check: must reference the specific primitive and code context, not a generic definition.

findings[].correct_usage_pattern

String

Must be a non-empty string containing a language-specific code snippet or step-by-step pattern. Content check: must be syntactically valid for the target language specified in metadata.

PRACTICAL GUARDRAILS

Common Failure Modes

Concurrency prompts fail in predictable ways. These are the most common failure modes when using an LLM to detect synchronization primitive misuse, along with practical mitigations to catch them before they reach production.

01

False Positives on Guarded State

What to watch: The model flags a shared variable access as unsafe because it cannot see that a higher-level lock (e.g., a class-level mutex or transaction) already protects it. This leads to noisy reports that erode trust. Guardrail: Require the prompt to request the full class or module context, not just the diff. Add an explicit instruction: 'Before flagging a field access, verify whether any enclosing method or struct holds a synchronization primitive that covers it.'

02

Language-Specific Primitive Confusion

What to watch: The model applies Java synchronized semantics to Go sync.Mutex or confuses Python threading.Lock with asyncio.Lock. This produces technically incorrect guidance that a junior engineer might follow blindly. Guardrail: Bind the prompt to a single target language. Include a [LANGUAGE] variable that selects the correct concurrency model and a short reference table of primitives and their semantics in the system prompt.

03

Missing Signal-Before-Wait Bugs

What to watch: The model overlooks a condition variable signal() or notify() call that occurs before the corresponding wait(), causing a thread to block forever. This is a classic deadlock that static analysis often misses. Guardrail: Add a dedicated check step in the prompt: 'For every wait() call, trace the control flow to confirm that signal() or notifyAll() is guaranteed to execute after the wait begins. Flag any path where the signal may be lost.'

04

Spurious Wakeup Vulnerability Oversight

What to watch: The model accepts a bare wait() call without a surrounding while loop that rechecks the condition. This is a latent bug that only surfaces under rare timing conditions, making it extremely hard to reproduce. Guardrail: Include a pattern-matching rule in the prompt: 'Any call to wait() or await() must be inside a loop that re-tests the condition variable. Flag all bare waits as HIGH severity.'

05

Double-Lock and Unlock Mismatch Hallucination

What to watch: The model reports a double-lock or missing unlock on a complex control flow path (e.g., early returns, exceptions) where the locking discipline is actually correct. This happens because the model loses track of state across branches. Guardrail: Instruct the model to output a lock-state trace for each reported violation. Pair the prompt with a deterministic static analysis tool (e.g., ThreadSanitizer) and use the LLM only to explain and prioritize the tool's findings, not to perform the raw analysis.

06

Ignoring Memory Ordering and Barriers

What to watch: The model focuses exclusively on lock/unlock pairs and misses memory ordering bugs in lock-free code, such as missing volatile, atomic, or memory fence instructions. This gives a false sense of security for low-latency code paths. Guardrail: Add a secondary analysis pass in the prompt: 'After reviewing lock usage, inspect any shared variable accessed without a lock. Verify that it is either declared with the correct atomic/volatile qualifier or accessed exclusively through atomic operations. Flag any non-atomic unprotected access.'

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Synchronization Primitive Misuse Detection Prompt before integrating it into a CI pipeline or code review harness. Each criterion targets a specific failure mode common in concurrency analysis prompts.

CriterionPass StandardFailure SignalTest Method

Double-Lock Detection

Identifies all code paths where a mutex lock is acquired without a corresponding unlock in the same scope, including early returns and exception paths.

Output misses a lock without a paired unlock in a conditional branch; false positive on a correctly scoped lock_guard or defer.

Run against a synthetic diff containing a mutex.lock() followed by an early return before mutex.unlock(). Verify the finding includes the exact line and a severity of 'high'.

Signal-Before-Wait Ordering

Flags any pattern where a condition variable is signaled before the corresponding wait is guaranteed to be active, indicating a lost wakeup risk.

Output fails to flag a notify_one() call placed before a wait() call in a different thread; or incorrectly flags a signal correctly placed inside the lock before the wait predicate is checked.

Test with a producer-consumer snippet where notify() is called outside the lock before the consumer thread starts. Check that the finding explains the lost wakeup scenario.

Spurious Wakeup Vulnerability

Detects wait() calls on condition variables that are not wrapped in a predicate loop, leaving the code vulnerable to spurious wakeups.

Output passes a plain cv.wait(lk) without a lambda or while-loop predicate; or incorrectly flags a correctly implemented cv.wait(lk, []{ return ready; }).

Provide a snippet with cv.wait(lock) and no predicate. Verify the finding recommends a predicate loop and cites the spurious wakeup risk.

Language-Specific Primitive Mapping

Correctly identifies the synchronization primitives for the target language specified in [LANGUAGE] and uses the correct terminology in findings.

Output uses Java synchronized terminology for a Go code block, or references POSIX semaphores for a Rust snippet.

Run the prompt with [LANGUAGE]="Go" on a Go snippet using sync.Mutex. Check that findings reference sync.Mutex, defer, and Go-specific patterns, not generic C++ or Java terms.

Severity Classification Accuracy

Assigns severity levels consistent with the [SEVERITY_RUBRIC]: deadlock risks are 'critical', race conditions are 'high', and suboptimal patterns are 'medium' or 'low'.

A deadlock scenario is labeled 'medium'; a minor style nit is labeled 'critical'.

Feed a known deadlock pattern. Assert that the output severity is 'critical' and the justification mentions system halt risk. Feed a missing try_lock optimization. Assert severity is 'low'.

False Positive Rate on Safe Patterns

Does not flag well-known safe patterns such as RAII lock guards, scoped mutex wrappers, or correctly ordered hierarchical locking.

Output flags a std::lock_guard as a missing unlock; flags a correctly ordered multi-lock acquisition as a deadlock risk.

Run against a clean code sample using std::scoped_lock or synchronized blocks. Verify zero findings are generated, or that any findings are explicitly marked as informational with a confidence score below 0.3.

Output Schema Compliance

Returns a valid JSON object matching the [OUTPUT_SCHEMA], with all required fields present and no extra top-level keys.

Output is missing the findings array; contains a markdown preamble before the JSON; uses risk instead of severity.

Parse the raw model output with a JSON validator against the expected schema. Check that findings is an array, each item has file, line, severity, and description.

Fix Suggestion Actionability

Each finding includes a concrete, compilable fix suggestion in the target language, not just a description of the problem.

Fix suggestion says 'add proper synchronization' without code; suggestion uses a different language syntax than the input.

Review the fix_suggestion field for a deadlock finding. Verify it contains a code block with valid syntax for [LANGUAGE] and directly addresses the lock ordering issue.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single code snippet and lighter validation. Drop the structured output schema initially and ask for a plain-text misuse report. Focus on one primitive type (e.g., mutex only) to test detection quality before expanding scope.

code
Analyze this [LANGUAGE] code for synchronization primitive misuse.
Focus only on [PRIMITIVE_TYPE] usage.

[CODE_SNIPPET]

List each misuse with line number, issue, and suggested fix.

Watch for

  • Missing schema checks leading to inconsistent report formats
  • Overly broad instructions causing the model to flag correct patterns as misuse
  • No severity ranking, making it hard to prioritize findings
  • Model hallucinating line numbers when code is not line-numbered in the prompt
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.