Inferensys

Prompt

Non-Atomic Operation Review Prompt

A practical prompt playbook for using the Non-Atomic Operation Review Prompt in production AI workflows to detect compound operations that break atomicity guarantees.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Non-Atomic Operation Review Prompt.

This prompt is for backend engineers and code reviewers who need to identify atomicity violations in compound operations before they merge into the main branch. The job-to-be-done is systematic detection of check-then-act races, read-modify-write gaps, and multi-step operations that lack transactional protection. The ideal user has access to a code diff, understands the language's concurrency model, and needs structured findings that map to specific synchronization primitives—not generic warnings about thread safety.

Use this prompt when reviewing code that spans multiple statements where correctness depends on all-or-nothing execution. Concrete triggers include: database updates preceded by a separate read to check current state, increment operations that read then write without atomic primitives, file system operations that check existence before creating, and any sequence where an external actor could mutate state between steps. The prompt requires [CODE_DIFF] as input and produces an atomicity violation report with violation type, location, risk severity, and suggested synchronization primitives. It is designed to work with diffs from any language but produces the most precise guidance when [LANGUAGE] is specified to select the correct concurrency primitives.

Do not use this prompt for single-statement operations, code that already uses appropriate atomic primitives, or pure functions with no shared state. It is not a general code quality reviewer—it focuses narrowly on atomicity boundaries. For broader concurrency review, pair it with the Thread Safety Review Prompt or Deadlock Potential Analysis Prompt. For production use, always route high-severity findings to human review before accepting fix suggestions, and validate the prompt's output against known atomicity bug patterns in your codebase to calibrate false positive tolerance.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Non-Atomic Operation Review Prompt delivers high-signal findings and where it wastes review cycles or creates false confidence.

01

Good Fit: Compound State Transitions

Use when: code changes include multi-step operations on shared state (e.g., check-then-act, read-modify-write, increment-and-store). The prompt excels at tracing the gap between the check and the action. Guardrail: provide the full function or method context, not just the diff, so the model can see the complete interleaving window.

02

Good Fit: Transaction-Boundary Gaps

Use when: database or storage operations span multiple statements without an explicit transaction wrapper. The prompt identifies where partial failure leaves inconsistent state. Guardrail: include the transaction isolation level in the prompt context so the analysis accounts for the actual guarantees, not just the code structure.

03

Bad Fit: Single-Statement Atomic Operations

Avoid when: the code change is a single atomic database UPDATE, INSERT, or DELETE with a WHERE clause. The prompt will generate false positives by flagging operations that are already atomic at the storage layer. Guardrail: pre-filter diffs to exclude single-statement mutations before running this prompt.

04

Bad Fit: Purely Read-Only Code Paths

Avoid when: the change only adds or modifies read queries, reporting logic, or analytics pipelines with no write side effects. The prompt will hallucinate atomicity concerns where none exist. Guardrail: route this prompt only to diffs containing write operations or state mutations.

05

Required Input: Synchronization Context

Risk: without knowing the locking strategy, transaction manager, or concurrency framework in use, the model defaults to generic advice that may conflict with the codebase's actual synchronization patterns. Guardrail: always include a brief note on the concurrency model (e.g., 'PostgreSQL SERIALIZABLE', 'Redis WATCH/MULTI', 'Go mutex') in the prompt context.

06

Operational Risk: False Confidence in Review

Risk: reviewers may treat the prompt's output as exhaustive, missing atomicity violations the model didn't flag due to context truncation or unfamiliar synchronization primitives. Guardrail: position the prompt as a first-pass scanner, not a replacement for human concurrency review. Require a second reviewer sign-off for any code paths touching financial, inventory, or user permission state.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for reviewing compound operations that should be atomic, identifying check-then-act races, read-modify-write gaps, and multi-step operations lacking transactional protection.

The following prompt template is designed to be dropped into a code review pipeline, CI/CD check, or manual review workflow. It expects a code diff or function body as input and produces a structured atomicity violation report. Every placeholder is enclosed in square brackets so you can wire in your own diff source, language context, risk tolerance, and output schema without modifying the core instruction logic.

text
You are a systems code reviewer specializing in concurrency safety and atomicity guarantees. Your task is to analyze the provided code for non-atomic operations that should be atomic.

## INPUT
[CODE_DIFF_OR_FUNCTION_BODY]

## CONTEXT
- Language: [LANGUAGE]
- Framework/ORM: [FRAMEWORK]
- Transaction model: [TRANSACTION_MODEL] (e.g., database transactions, software transactional memory, compare-and-swap loops)
- Concurrency model: [CONCURRENCY_MODEL] (e.g., multi-threaded, async event loop, goroutines, actors)
- Risk tolerance: [RISK_LEVEL] (low/medium/high; high means flag even unlikely interleavings)

## REVIEW INSTRUCTIONS
1. Identify every compound operation that reads state and then acts on that state without atomic protection.
2. For each finding, classify the pattern:
   - CHECK-THEN-ACT: A condition is checked and then an action is taken based on that condition, with a window where the condition can change.
   - READ-MODIFY-WRITE: A value is read, modified, and written back without synchronization, allowing lost updates.
   - MULTI-STEP WITHOUT TRANSACTION: Multiple operations that must succeed or fail together but lack a transactional boundary.
   - NON-ATOMIC COUNTER/ACCUMULATOR: Increment, decrement, or accumulation operations that are not atomic.
3. For each finding, provide:
   - The exact line range where the violation occurs.
   - A description of the interleaving that would cause incorrect behavior.
   - The data integrity risk (corruption, lost update, duplicate, inconsistent read).
   - A severity rating (CRITICAL, HIGH, MEDIUM, LOW) based on [RISK_LEVEL].
   - A suggested synchronization primitive or refactoring (e.g., database transaction, mutex, atomic operation, compare-and-swap, optimistic locking with version field, SELECT FOR UPDATE).
4. If no violations are found, explicitly state that and explain why the operations appear safe under the given concurrency model.
5. Do not flag operations that are already protected by an enclosing transaction, mutex, or atomic primitive visible in the provided code.

## OUTPUT FORMAT
Return a JSON object with this exact schema:
{
  "review_summary": {
    "total_findings": <integer>,
    "critical_count": <integer>,
    "high_count": <integer>,
    "medium_count": <integer>,
    "low_count": <integer>,
    "assessment": "<one sentence overall assessment>"
  },
  "findings": [
    {
      "id": "<ATOM-001, sequential>",
      "pattern": "<CHECK-THEN-ACT | READ-MODIFY-WRITE | MULTI-STEP_WITHOUT_TRANSACTION | NON-ATOMIC_COUNTER>",
      "severity": "<CRITICAL | HIGH | MEDIUM | LOW>",
      "line_range": "<start_line-end_line>",
      "description": "<what the code does and why it's non-atomic>",
      "interleaving_scenario": "<step-by-step description of a problematic concurrent execution>",
      "data_integrity_risk": "<corruption | lost_update | duplicate | inconsistent_read>",
      "suggested_fix": "<concrete synchronization primitive or refactoring approach>",
      "code_sketch": "<optional brief pseudocode or pattern name for the fix>"
    }
  ],
  "safe_operations_note": "<explanation if no findings, otherwise null>"
}

## CONSTRAINTS
- Do not hallucinate synchronization primitives that don't exist in [LANGUAGE].
- If the code uses an ORM, consider its built-in optimistic locking or transaction support before suggesting raw SQL.
- For MEDIUM and LOW severity findings, note whether the risk is theoretical or practically exploitable under typical load.
- If [RISK_LEVEL] is "high," flag even single-instruction windows where a context switch could cause inconsistency.

To adapt this template, replace the square-bracket placeholders with values from your review context. For CI/CD integration, wire [CODE_DIFF_OR_FUNCTION_BODY] to the output of git diff or a pull request API. Set [RISK_LEVEL] to "high" for payment, inventory, or auth code paths; use "medium" for most backend services; reserve "low" for read-heavy or idempotent operations. The output schema is designed to be machine-readable so you can post findings directly to review tools, block merges on CRITICAL findings, or aggregate severity counts into dashboards. Always validate the JSON output against the schema before surfacing results to developers—malformed JSON or missing required fields should trigger a retry or fallback to a simpler text-only prompt.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Non-Atomic Operation Review Prompt. Provide these placeholders to ensure the model has enough context to detect check-then-act races, read-modify-write gaps, and missing transactional boundaries.

PlaceholderPurposeExampleValidation Notes

[CODE_SNIPPET]

The compound operation or multi-step function to review for atomicity violations

def transfer(from, to, amount): if balance[from] >= amount: balance[from] -= amount balance[to] += amount

Required. Must be a complete function, method, or code block. Reject if empty or contains only comments.

[LANGUAGE]

Target programming language to tailor synchronization primitive suggestions

Python

Required. Must be a recognized language identifier. Validate against supported language list before prompt assembly.

[OPERATION_DESCRIPTION]

Natural language description of what the code is intended to do

Transfer funds between two accounts atomically

Required. Helps the model distinguish intentional non-atomicity from bugs. Reject if missing or under 10 characters.

[CONCURRENCY_MODEL]

Concurrency model in use: threads, async, multiprocess, distributed, or unknown

threads

Required. Accepted values: threads, async, multiprocess, distributed, unknown. Defaults to unknown if not specified.

[SHARED_STATE]

Description of shared resources accessed by the operation

In-memory dictionary balance shared across threads

Required. List all shared resources: databases, caches, files, in-memory structures. Null allowed if truly stateless.

[TRANSACTION_CONTEXT]

Existing transaction boundaries or isolation levels already in place

No transaction wrapping; each statement auto-commits

Optional. Provide if known. Helps model avoid suggesting redundant protections. Null allowed.

[CONSTRAINTS]

Specific synchronization primitives or patterns to prefer or avoid

Prefer async-compatible locks; avoid blocking I/O in critical sections

Optional. Use to align suggestions with team standards or framework limitations. Null allowed.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Non-Atomic Operation Review Prompt into a CI/CD pipeline or code review application.

Integrating the Non-Atomic Operation Review Prompt into a production workflow requires treating it as a deterministic analysis step within a larger pipeline, not a standalone chat interaction. The prompt should be triggered automatically on pull request creation or code push, receiving a structured diff as input. The application layer is responsible for chunking large diffs into logical units (e.g., by file or function) to stay within context limits and for enriching the prompt with language-specific context, such as the primary concurrency primitives and transaction models in use. The model's output must be parsed as structured JSON and validated against a strict schema before any findings are surfaced to a developer, ensuring that only well-formed, actionable reports enter the review queue.

A robust implementation requires a validation and retry layer. After receiving the model's JSON response, validate that every finding includes the required fields: file_path, line_range, atomicity_violation_type (e.g., 'check-then-act', 'read-modify-write'), description, and suggested_primitive. If validation fails, implement a retry loop with a maximum of two attempts, feeding the validation error back into the model's context to guide self-correction. For high-risk repositories, route all validated findings to a human review queue rather than posting them directly as inline comments. Log every prompt version, input diff hash, raw model output, and validation result to an observability platform. This audit trail is critical for tuning the prompt, diagnosing false positives, and defending review decisions. Choose a model with strong code reasoning capabilities and low latency, as this check sits on the critical path for developer feedback; a fast instructor-tuned model is often a better fit than a largest frontier model if it meets accuracy thresholds on your eval set.

To prevent alert fatigue, implement a severity filter in the application harness. Only surface findings classified as HIGH or CRITICAL as blocking review comments, while routing LOW severity notes to a non-blocking informational report. Before enabling the check as a required status for merges, run it silently against a historical dataset of known atomicity bugs and clean code to calibrate precision and recall. The next step is to integrate the prompt's output with your existing static analysis dashboard, correlating atomicity findings with test gap reports to prioritize where new concurrency stress tests are needed most.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the fields, types, and validation rules for the structured atomicity violation report. Use this contract to parse and validate the model's output before integrating it into your CI/CD or review pipeline.

Field or ElementType or FormatRequiredValidation Rule

violations

Array of objects

Must be a non-empty array if violations are found. Validate array length > 0.

violations[].id

String (kebab-case)

Must match pattern ^ATOM-\d{3}$. Must be unique within the array.

violations[].severity

Enum: CRITICAL, HIGH, MEDIUM, LOW

Must be one of the defined enum values. CRITICAL reserved for data corruption or irreversible state loss.

violations[].file_path

String (relative path)

Must be a non-empty string. Should be validated as a valid relative path format, not an absolute path.

violations[].line_range

String (format: start-end)

Must match regex ^\d+-\d+$. Start line must be less than or equal to end line.

violations[].anti_pattern

String

Must be one of: check-then-act, read-modify-write, multi-step-no-txn, missing-synchronization, or compound-non-atomic.

violations[].description

String

Must be a non-empty string between 50 and 300 characters. Describes the specific race condition scenario.

violations[].suggested_fix

String

Must be a non-empty string. Should contain a concrete synchronization primitive name such as mutex, transaction, or atomic operation.

PRACTICAL GUARDRAILS

Common Failure Modes

Non-atomic operations fail silently and are hard to reproduce. These are the most common failure patterns when the prompt misses a race condition or misjudges severity, and the specific guardrails to prevent each one.

01

Check-Then-Act Blind Spots

What to watch: The model identifies the obvious if (exists) then update pattern but misses the time-of-check-to-time-of-use (TOCTOU) gap when the check and act are separated by a network call, a yield point, or an external state read. Guardrail: Require the prompt to output a 'temporal distance' score for each flagged operation, measuring the instruction count between the guard condition and the guarded action.

02

Transaction Boundary Overreach

What to watch: The model suggests wrapping an entire multi-service workflow in a single distributed transaction, ignoring the latency, contention, and partial failure costs that make long-lived transactions a worse problem than the race they solve. Guardrail: Add a constraint that any suggested transaction must include a maximum hold-duration estimate, and flag suggestions exceeding 100ms for human review.

03

Language-Level Primitive Mismatch

What to watch: The prompt recommends a synchronized block for Python async code, a Mutex for a single-goroutine context, or a read-write lock where an atomic reference would suffice. The model defaults to the most familiar primitive rather than the correct one for the runtime. Guardrail: Include the target language and concurrency model explicitly in the prompt's [CONTEXT] block, and instruct the model to justify why the suggested primitive matches that specific runtime's memory model.

04

False Positive Fatigue

What to watch: The prompt flags every compound assignment as a potential read-modify-write race, including operations on thread-local variables, stack-allocated structs, or single-threaded event loop contexts. Reviewers begin ignoring the output. Guardrail: Require the model to first classify the variable's sharing domain (thread-local, goroutine-local, shared-immutable, shared-mutable) and suppress findings for non-shared state.

05

Compound Operation Atomicity Gap

What to watch: The model correctly identifies that map[key] += 1 is non-atomic but fails to recognize that the same pattern applies to list.append() followed by a length check, or a database SELECT followed by an UPDATE in a different service. The pattern recognition is too literal. Guardrail: Provide a few-shot example that demonstrates the same atomicity violation across three different domains (in-memory collection, database, distributed cache) so the model learns the abstract pattern rather than the concrete syntax.

06

Severity Inflation on Cold Paths

What to watch: The prompt assigns a 'Critical' severity to a race condition in a debug logging statement or a metrics counter where the worst-case outcome is a slightly inaccurate dashboard number. This desensitizes the team to real critical findings. Guardrail: Add a severity calibration step that requires the model to describe the concrete business impact in one sentence, and downgrade findings where the impact is limited to observability artifacts or non-durable side effects.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the Non-Atomic Operation Review Prompt's output before integrating it into a CI/CD pipeline or code review workflow. Each criterion targets a specific failure mode common in concurrency analysis.

CriterionPass StandardFailure SignalTest Method

Atomicity Violation Identification

Output correctly identifies all check-then-act, read-modify-write, and multi-step gaps in the provided [CODE_SNIPPET].

A known violation from the golden dataset is missing from the findings list.

Run against a golden dataset of 10 code snippets with known, labeled atomicity violations. Require 100% recall on high-severity items.

Severity Classification Accuracy

Each finding's severity is correctly classified as 'High', 'Medium', or 'Low' according to the [SEVERITY_RUBRIC].

A data-corrupting read-modify-write race is classified as 'Low' severity.

Validate severity labels against a pre-labeled test set. Measure F1 score for 'High' severity classification; target > 0.9.

Synchronization Primitive Suggestion

The suggested primitive (e.g., mutex, transaction, atomic operation) is the most idiomatic and correct choice for the language and context in [CODE_SNIPPET].

A suggestion to use a distributed lock for an in-process single-instance race condition.

Manual review by a senior systems engineer on a sample of 20 outputs. Acceptable if > 85% of suggestions are deemed optimal.

False Positive Rate

The output does not flag thread-safe operations or already-atomic database writes as violations.

A single atomic compare-and-swap operation is incorrectly flagged as a check-then-act race.

Run against a dataset of 15 code snippets known to be concurrency-safe. The pass standard is zero false positives.

Output Schema Compliance

The output is valid JSON that strictly conforms to the defined [OUTPUT_SCHEMA], including all required fields and enum values.

The JSON fails to parse, or a required field like file_path or line_range is missing from a finding.

Automated JSON Schema validation check. The test passes if the output is valid JSON and schema validation returns zero errors.

Fix Suggestion Concreteness

Each fix suggestion includes a specific, actionable code change or refactoring step, not just a general principle.

A fix suggestion states 'use a mutex' without specifying which variable or code block to protect.

Check that each fix_suggestion field in the output contains a code-like token (e.g., synchronized, lock, BEGIN TRANSACTION) or a specific structural change.

Root Cause Explanation Clarity

The explanation field for each finding clearly describes the interleaving of operations that triggers the race.

The explanation is a generic statement like 'this code is not thread-safe' without describing the conflicting thread schedules.

Verify that each explanation field contains a temporal sequence keyword (e.g., 'before', 'after', 'while', 'during') linking two or more operations.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single code snippet and ask for a plain-text finding list. Skip formal severity scoring and structured output schemas. Focus on getting the model to correctly identify check-then-act gaps and read-modify-write patterns.

Prompt modification

Remove the [OUTPUT_SCHEMA] placeholder and replace with: List each atomicity violation as a bullet point with the operation name and a one-sentence explanation.

Watch for

  • Model flagging thread-safe wrappers as violations without understanding the synchronization
  • Over-reporting on idempotent operations where atomicity isn't required
  • Missing compound operations that span multiple functions or files
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.