This prompt is designed for a backend or systems engineer reviewing a code change that introduces or modifies access to shared mutable state. The primary job-to-be-done is to catch unsynchronized writes, read-modify-write races, and missing memory barriers before they merge into a main branch, where they become exponentially more expensive and difficult to debug. The ideal user is a developer or tech lead who understands the concurrency primitives of their language (e.g., sync.Mutex in Go, threading.Lock in Python, or std::mutex in C++) but wants a structured, automated second pair of eyes to ensure no access path was overlooked. The required context is a code diff, the language specification, and any known design intent or architectural constraints for the component under review.
Prompt
Shared State Mutation Review Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Shared State Mutation Review Prompt.
You should use this prompt when the code change touches fields or data structures that are reachable from multiple goroutines, threads, or asynchronous tasks. It is particularly valuable for changes to in-memory caches, connection pools, shared configuration objects, or any state held between requests. The prompt is designed to produce a mutation safety report that maps each shared variable to its synchronization mechanism and flags any gaps. Do not use this prompt for single-threaded, purely functional transformations, or for code that only reads immutable state after initialization. It is also not a replacement for the Go race detector, tsan, or similar dynamic analysis tools; it is a static review aid that complements runtime instrumentation.
Before running this prompt, ensure the diff is isolated to the concurrency-relevant changes. Feeding an entire multi-thousand-line PR will dilute the analysis and may cause the model to miss subtle interleavings. Instead, extract the files and functions that touch shared state. The prompt expects a clear [CODE_DIFF] input and an optional [CONCURRENCY_MODEL] description (e.g., 'goroutine-per-request', 'thread pool', 'asyncio event loop'). The output is a structured report you can attach directly to a PR comment. If the report identifies a high-severity unsynchronized mutation, block the merge and request a fix; do not treat the model's output as a final security sign-off without human verification of the suggested synchronization strategy.
Use Case Fit
Where the Shared State Mutation Review Prompt delivers high-signal findings and where it creates noise or false confidence.
Good Fit: Pre-Merge Concurrency Review
Use when: a PR modifies shared mutable state, introduces new goroutines or threads, or changes synchronization primitives. The prompt excels at catching unsynchronized writes and read-modify-write gaps before they reach production. Guardrail: pair with a language-aware static analyzer (e.g., go test -race) and treat the prompt as a second reviewer, not the sole gate.
Bad Fit: High-Level Architecture Review
Avoid when: the task is evaluating overall system design, choosing between message-passing and shared-memory architectures, or assessing distributed consistency models. The prompt focuses on code-level mutation safety, not architectural trade-offs. Guardrail: route architecture questions to a dedicated design review prompt and keep this prompt scoped to concrete code diffs.
Required Inputs
Must have: the code diff or file content with line numbers, the language and concurrency model (e.g., Go goroutines, Java threads, Python asyncio), and any existing synchronization annotations or comments. Optional but valuable: runtime race detector output, lock tracing data, or known production incident context. Guardrail: if line numbers are missing, the prompt cannot produce actionable location references—require them in your input schema.
Operational Risk: False Confidence
Risk: the prompt may miss races that depend on specific interleavings, CPU memory models, or compiler optimizations. Reviewers might trust a clean report and skip dynamic analysis. Guardrail: always run a race detector under load before closing the review. Treat a negative prompt finding as 'no obvious static pattern detected,' not 'proven safe.'
Operational Risk: Language Model Blindness
Risk: the model may not understand language-specific memory models (e.g., Go's happens-before, Java's volatile semantics, C++ std::memory_order) deeply enough to catch subtle ordering bugs. Guardrail: for lock-free code or memory-ordering-dependent logic, require a senior systems engineer to sign off. The prompt is a triage tool, not a formal verifier.
Integration Point: CI/CD Pipeline
Use when: wiring the prompt into an automated PR review pipeline. It can generate structured findings that your CI system surfaces as inline comments or review checklist items. Guardrail: never auto-block a merge based solely on this prompt's output. Always require human acknowledgment for severity findings above 'low' and gate on passing race detector runs.
Copy-Ready Prompt Template
A reusable prompt template for reviewing code that mutates shared state across concurrent execution contexts.
This prompt template is designed to be dropped into a code review pipeline or used manually by a developer before merging a pull request. It instructs the model to act as a concurrency reviewer, focusing exclusively on shared state mutation risks. The template uses square-bracket placeholders so you can inject the specific code diff, language context, and risk tolerance for your review. The output is structured as a mutation safety report, making it easy to parse in automated CI/CD checks or to read as a pre-merge checklist.
textYou are a senior systems engineer specializing in concurrent and parallel programming. Your task is to review the provided code change for shared state mutation safety. ## INPUT Code Diff: [CODE_DIFF] Target Language and Runtime: [LANGUAGE_AND_RUNTIME] ## REVIEW CONSTRAINTS - Focus exclusively on shared state mutation risks: unsynchronized writes, read-modify-write races, missing memory barriers, and incorrect use of synchronization primitives. - Do not comment on style, naming, algorithmic complexity, or non-concurrency logic unless it directly causes a mutation bug. - For each finding, provide a severity rating (CRITICAL, HIGH, MEDIUM, LOW) based on the likelihood and impact of data corruption or undefined behavior. - If no shared state mutation issues are found, explicitly state that and explain why the synchronization is sufficient. ## OUTPUT SCHEMA Return a single JSON object with the following structure: { "summary": "A one-sentence overall assessment of mutation safety.", "findings": [ { "severity": "CRITICAL|HIGH|MEDIUM|LOW", "location": "File path and line range or function name from the diff.", "category": "unsynchronized_write|read_modify_write_race|missing_barrier|incorrect_primitive|other", "description": "A clear, technical explanation of the race condition or mutation bug.", "reproduction_scenario": "A concise description of the concurrent interleaving that triggers the bug.", "fix_suggestion": "A specific, actionable code change or synchronization strategy to resolve the issue." } ], "safe_patterns_identified": ["List any correctly synchronized patterns observed in the diff."] } ## RISK LEVEL [RISK_LEVEL] If RISK_LEVEL is "high", apply stricter scrutiny: flag any shared mutable state without explicit synchronization as CRITICAL, even if it appears safe under low contention.
To adapt this template, replace the placeholders before sending it to the model. [CODE_DIFF] should contain the unified diff of the code change. [LANGUAGE_AND_RUNTIME] should specify the language and memory model (e.g., "Go 1.22 with goroutines", "Java 21 with virtual threads", or "Python 3.12 with asyncio"). [RISK_LEVEL] can be set to "standard" or "high" depending on the blast radius of the component under review. For automated pipelines, parse the output JSON and fail the check if any finding has a severity of CRITICAL or HIGH. For manual review, use the safe_patterns_identified field to build team knowledge of correct concurrency patterns.
Prompt Variables
Required and optional inputs for the Shared State Mutation Review Prompt. Map these placeholders to your CI/CD context, code review tooling, or manual review workflow before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CODE_DIFF] | The unified diff or code snippet containing shared state mutations to review | diff --git a/pkg/cache/store.go b/pkg/cache/store.go @@ -45,7 +45,9 @@ func (s *Store) Set(key string, val interface{}) {
| Must be non-empty. Parse check: valid diff format or recognizable code block. If empty, abort with 'missing input' error. |
[LANGUAGE] | Target programming language for synchronization primitive recommendations | go | Must match a supported language identifier. Validate against allowed list: go, java, python, rust, cpp, csharp, javascript, typescript. Default to 'go' if null. |
[CONCURRENCY_MODEL] | Concurrency model used in the code under review | goroutines with channels and mutexes | Must be one of: goroutines, threads, async-await, actors, event-loop, fork-join, null. If null, prompt should infer from [LANGUAGE] and [CODE_DIFF]. |
[REVIEW_DEPTH] | Controls how exhaustively the prompt searches for mutation risks | comprehensive | Must be one of: quick-scan, standard, comprehensive. Default to 'standard' if null. 'quick-scan' skips interleaving analysis; 'comprehensive' adds formal happens-before reasoning. |
[KNOWN_FALSE_POSITIVES] | List of previously reviewed and dismissed patterns to suppress in output | ["pkg/metrics/counter.go:42: atomic.AddUint64 already safe", "pkg/session/cleaner.go:108: single-goroutine context"] | Optional. If provided, must be a JSON array of strings. Each entry should include file path and dismissal reason. Null allowed. |
[OUTPUT_FORMAT] | Desired structure for the mutation safety report | json | Must be one of: json, markdown, sarif. Default to 'json' if null. 'sarif' requires valid SARIF 2.1.0 schema compliance in output validation. |
[SEVERITY_THRESHOLD] | Minimum severity level to include in findings | medium | Must be one of: info, low, medium, high, critical. Default to 'low' if null. Findings below threshold are omitted from output but counted in summary statistics. |
[CONTEXT_WINDOW_LINES] | Number of surrounding lines to include per finding for reviewer orientation | 5 | Must be a positive integer between 1 and 20. Default to 5 if null. Controls how much surrounding code is quoted in each finding's evidence block. |
Implementation Harness Notes
How to wire the Shared State Mutation Review Prompt into a CI/CD pipeline, code review tool, or manual review workflow with validation, retries, and human approval gates.
The Shared State Mutation Review Prompt is designed to operate as a pre-merge safety gate in a CI/CD pipeline or as an assistive tool within a code review platform. The prompt expects a structured diff, the target language, and a risk tolerance level as inputs. The output is a machine-readable mutation safety report that includes a severity classification, a list of unsynchronized access points, and concrete synchronization recommendations. Because concurrency defects can cause data corruption in production, the implementation harness must treat this prompt's output as a signal for human review, not as an automated merge blocker by itself. The harness should parse the structured output, attach findings to the relevant lines in the pull request, and route high-severity findings to a mandatory reviewer queue.
To wire this into an application, construct a pre-processing step that extracts the code diff from the version control system (e.g., git diff origin/main...HEAD), identifies the primary language from the changed files, and packages it alongside a risk tolerance parameter (e.g., [RISK_LEVEL: high] for financial or safety-critical paths, medium for backend services, low for internal tools). The prompt should be called with a structured output request (e.g., JSON mode or function calling) to enforce the expected schema. The harness must then validate the output against the schema: check that severity is one of the allowed enum values, that findings contain valid line references, and that synchronization_recommendations are non-empty for any finding above low severity. If validation fails, retry once with the validation error appended to the prompt as a correction hint. If the retry also fails, log the raw output and escalate to a human reviewer with a note that automated analysis was inconclusive.
For high-risk repositories (e.g., payment processing, auth systems, safety-critical control loops), the harness should enforce a human approval gate on any finding with severity: critical or severity: high. The approval gate should present the original code, the model's finding, and a required checkbox for the reviewer to confirm or dismiss each finding. Dismissed findings should be logged with the reviewer's identity and rationale for auditability. For model selection, prefer models with strong code reasoning capabilities and long context windows to handle large diffs. If the diff exceeds the model's context window, chunk the diff by file or function boundary and run the prompt on each chunk independently, then merge and deduplicate findings by file path and line range. Avoid running this prompt on generated files, vendored dependencies, or lock files; filter those out in the pre-processing step to reduce noise and token cost.
The harness should also implement basic evals before deployment. Maintain a small golden dataset of known concurrency bugs (e.g., unsynchronized map writes in Go, missing synchronized blocks in Java, unprotected shared state in Python async code) and their expected findings. Run the prompt against this dataset and measure recall (did it catch the known bug?) and precision (did it flag benign code?). A reasonable target is >90% recall on critical bugs and <20% false positive rate on clean code. If the prompt's performance degrades after a model update or prompt change, the eval harness will catch it before it reaches production. Finally, log every invocation with the prompt version, model, diff size, output summary, and review outcome. This trace data is essential for debugging false positives, tuning the risk tolerance parameter, and demonstrating review coverage to compliance auditors.
Expected Output Contract
Defines the structure, types, and validation rules for the Shared State Mutation Review Prompt output. Use this contract to parse, validate, and integrate the model response into downstream CI/CD or review tooling.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
mutation_report | object | Top-level JSON object. Schema check: must contain findings, summary, and metadata keys. | |
findings | array[object] | Array length >= 0. Each element must conform to the finding object schema. Empty array allowed if no issues found. | |
findings[].id | string | Format: FINDING-[0-9]{3}. Must be unique within the findings array. Regex validation required. | |
findings[].severity | string | Enum check: must be one of CRITICAL, HIGH, MEDIUM, LOW, INFO. Case-sensitive. | |
findings[].location.file | string | Must be a relative file path matching repository structure. Path existence check recommended but not required in schema validation. | |
findings[].location.line_range | string | Format: L[0-9]+-L[0-9]+. Start line must be <= end line. Regex: ^L\d+-L\d+$. | |
summary.risk_score | integer | Range: 0-100. Integer only. 0 indicates no risk detected. Score must correlate with finding count and severity distribution. | |
metadata.review_timestamp | string | ISO 8601 UTC format. Example: 2025-01-15T14:30:00Z. Parse check required. |
Common Failure Modes
Shared state mutation review is brittle when the model lacks execution context or the code is too complex. These are the most common failure modes and how to prevent them.
False Negatives on Complex Interleavings
What to watch: The model misses races that require reasoning about specific thread interleavings or timing windows. It correctly identifies obvious unsynchronized writes but fails on subtle happens-before relationships. Guardrail: Pair the prompt with a static analysis tool (e.g., Go race detector, ThreadSanitizer) and use the model only to interpret and prioritize the tool's output, not as the sole detector.
Context Window Truncation of Critical Paths
What to watch: Large diffs or multi-file changes exceed the context window, causing the model to review only a partial call graph. A mutation in file A and a read in file C are never analyzed together. Guardrail: Implement a pre-processing step that extracts only functions touching shared state and their callers. If the extracted context still exceeds the budget, split the review by resource (e.g., review all mutations to userCache separately from sessionMap).
Language-Specific Memory Model Confusion
What to watch: The model applies Go's memory model to Java code, or misses C++ atomic ordering requirements. It suggests a sync.Mutex in Python or fails to recognize that a Java volatile does not guarantee atomicity for compound operations. Guardrail: Explicitly state the language and concurrency primitives in the prompt's [CONTEXT] block. For high-risk reviews, include a brief memory model reference (e.g., "Go: slices are not safe for concurrent writes even with mutex on the slice header").
Hallucinated Synchronization Primitives
What to watch: The model invents a ConcurrentSafeMap class that doesn't exist in the standard library or suggests a lock-free algorithm with a subtle ABA bug. The fix looks plausible but introduces a new, harder-to-detect defect. Guardrail: Require the model to cite specific standard library types or project-internal abstractions. Add a post-processing validation step that checks suggested types against the language's actual API surface before the suggestion reaches the developer.
Over-Flagging of Intentional Unsynchronized Access
What to watch: The model flags a variable that is provably confined to a single goroutine, initialized before any concurrent access, or protected by an external synchronization mechanism like a sync.Once. This creates noise and erodes reviewer trust. Guardrail: Instruct the model to classify findings as
Ignoring Transaction Boundaries in Database Code
What to watch: The model focuses on in-memory mutexes and misses a read-modify-write race on a database row because the code lacks a SELECT ... FOR UPDATE or uses a weak isolation level. Guardrail: Extend the prompt to explicitly request analysis of database transaction boundaries. Include the isolation level in the [CONTEXT] block. If the code touches a database, require the output schema to include a dedicated database_race_risk field.
Evaluation Rubric
Criteria for evaluating the quality and safety of the Shared State Mutation Review Prompt output before integrating it into a CI/CD pipeline or code review workflow.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Synchronization Gap Detection | All unsynchronized reads/writes to shared mutable state in the diff are flagged with a file path and line range. | A known unsynchronized mutation from a golden test case is omitted from the findings. | Run against a curated set of 10 diffs with known, labeled race conditions and confirm 100% recall. |
False Positive Rate | No more than 1 false positive per review on a clean codebase sample of 20 diffs. | Flags a thread-safe access pattern (e.g., correct mutex lock, atomic operation) as a vulnerability. | Run against a golden dataset of 20 clean, correctly synchronized diffs and count false findings. |
Severity Classification Accuracy | Data corruption risks are classified as 'Critical' or 'High'. Non-functional timing issues are 'Low' or 'Info'. | A read-modify-write race on a financial ledger is classified as 'Low' severity. | Validate severity against a pre-labeled set of 15 findings covering data integrity, performance, and logging races. |
Fix Suggestion Actionability | Each finding includes a concrete, language-idiomatic fix pattern (e.g., 'use sync.Mutex', 'wrap in transaction'). | Suggestion is generic ('add synchronization') without specifying the primitive or scope. | Manual review by a senior engineer of fix suggestions for 5 diverse findings to confirm they are directly implementable. |
Output Schema Compliance | Output is valid JSON matching the [OUTPUT_SCHEMA] contract with all required fields present. | JSON parsing fails, or the 'findings' array is missing the 'severity' field. | Automated schema validation in CI using a JSON Schema validator against the defined output contract. |
Deadlock Risk Identification | All lock acquisition sequences in the diff are analyzed; circular wait conditions are flagged. | A known lock ordering violation from a test case is not reported. | Run against a golden set of 5 diffs with injected lock ordering violations and confirm detection. |
Transaction Boundary Analysis | Missing transaction scopes for multi-step state mutations are flagged with a rollback risk note. | A two-step database update without a transaction is not flagged. | Test against 5 diffs with missing transaction boundaries and confirm all are detected. |
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 lighter validation. Drop the structured output schema requirement and ask for a free-text analysis first. This helps you calibrate what the model catches before locking down the format.
codeAnalyze this code for shared state mutation risks. Focus on unsynchronized writes, read-modify-write races, and missing memory barriers. Give me a plain-text summary of what you find. [CODE_DIFF]
Watch for
- Model missing language-specific synchronization primitives (e.g., confusing
sync.Mutexwithsync.RWMutexsemantics) - Overly broad findings that flag every shared variable without assessing actual concurrent access paths
- No severity differentiation—everything looks critical

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