Inferensys

Prompt

Lock-Free Code Correctness Review Prompt

A practical prompt playbook for using Lock-Free Code Correctness Review Prompt in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

A structured correctness review for lock-free and wait-free data structure implementations before they reach production.

This prompt is for systems engineers and performance-focused teams who need a rigorous, pre-production correctness review of lock-free and wait-free data structure implementations. It is designed to accelerate the discovery of subtle concurrency defects—specifically memory ordering violations, ABA problem vulnerabilities, and linearizability breaks—that are notoriously difficult to reproduce under test and catastrophic in production. The ideal user has already written or is reviewing a complete implementation in a language like C++, Rust, or Java, and can supply the full source code along with the target memory model (e.g., x86-TSO, ARM weak ordering). The prompt acts as a reasoning accelerator, not a replacement for formal verification tools like TLA+ or Spin, dynamic race detectors like ThreadSanitizer, or stress testing under high contention. Use it during pre-merge code review, architecture review, or when hardening a concurrent data structure that cannot afford the latency or liveness risks of lock-based synchronization.

To use this prompt effectively, you must provide the complete, unredacted implementation source code and explicitly state the target memory model. The prompt assumes the reviewer has already isolated the data structure in question and is not asking the model to search a large codebase for concurrency primitives. It works best on self-contained structures like lock-free queues, stacks, hazard pointers, epoch-based reclamation schemes, or custom atomic state machines. Do not use this prompt for general multi-threaded code that uses locks, for I/O-bound asynchronous code, or for high-level architectural patterns. The output is a structured analysis, not a binary pass/fail, so you should expect to find a ranked list of potential issues, each tied to a specific line range, a formal concern (e.g., 'missing acquire barrier on line 47'), and a suggested remediation. Because the domain is high-risk, every finding should be treated as a hypothesis to be validated with a model checker or targeted stress test before the review is closed.

Before running this prompt, ensure you have a baseline understanding of the implementation's linearization points and intended memory ordering guarantees. The prompt will challenge these assumptions, so if you cannot articulate them, the review will be less effective. After receiving the output, map each finding to a concrete test case or formal check. For memory ordering issues, construct a litmus test. For ABA problems, verify that your tag or pointer-width assumptions hold under the target architecture. For linearizability concerns, define the sequential specification and check whether every concurrent execution maps to a valid sequential history. The prompt is a starting point for this verification work, not the final word. If the review surfaces a potential data corruption bug, escalate to a human review with domain expertise in lock-free programming before any production deployment.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Lock-free code review requires deep systems knowledge; the prompt amplifies expertise but cannot replace it.

01

Good Fit: Expert Review of New Lock-Free Structures

Use when: a systems engineer is implementing a new lock-free stack, queue, or ring buffer and needs a structured correctness review against memory ordering and ABA problem criteria. Guardrail: The reviewer must supply the full implementation, target architecture memory model, and any existing stress test results.

02

Bad Fit: Novice Debugging Without Formal Training

Avoid when: a developer unfamiliar with linearizability, happens-before relationships, or CAS loops pastes code and expects a simple yes/no answer. Guardrail: Require the user to annotate the code with intended invariants and memory ordering assumptions before the prompt runs.

03

Required Inputs: Code, Memory Model, and Invariants

What to watch: The prompt produces generic advice when given only raw code without context. Guardrail: The template requires [LOCK_FREE_CODE], [TARGET_ARCH_MEMORY_MODEL], and [INTENDED_LINEARIZABILITY_INVARIANTS] as mandatory inputs. Missing inputs should abort or escalate.

04

Operational Risk: False Confidence in Unverified Analysis

What to watch: A model-generated correctness proof may miss subtle bugs that only manifest under specific interleavings. Guardrail: Every output must include a stress_test_recommendations block and a disclaimer that formal verification or tools like CDSChecker are required before production use.

05

Operational Risk: Architecture-Specific Memory Ordering

What to watch: x86, ARM, and RISC-V have different memory ordering guarantees. A review assuming x86-TSO may miss bugs on weakly-ordered architectures. Guardrail: The prompt must explicitly reference the target architecture's memory model and flag when the code relies on architecture-specific guarantees.

06

Bad Fit: High-Level Concurrency Without Lock-Free Primitives

Avoid when: the code uses mutexes, channels, or async/await patterns without any lock-free primitives. This prompt is specialized for atomic operations, CAS loops, and memory barriers. Guardrail: Route to the Thread Safety Review or Deadlock Potential Analysis prompts instead.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for reviewing lock-free code correctness, ready to copy and adapt with your own code, constraints, and output format.

This template provides the core instruction set for an AI-assisted lock-free code correctness review. It is designed to be used as a system prompt or a single-turn task prompt. The placeholders in square brackets must be replaced with your specific code, language, memory model, and risk tolerance before use. The prompt instructs the model to act as a systems engineering reviewer, focusing on memory ordering, ABA problems, and linearizability—not general code style.

text
You are a systems engineering reviewer specializing in lock-free and wait-free concurrent data structures. Your task is to perform a rigorous correctness review of the provided code.

## Input Code
[CODE_SNIPPET]

## Language and Memory Model
- Language: [LANGUAGE]
- Target memory model: [MEMORY_MODEL, e.g., C11, C++11, Java, Rust]
- Target architecture(s): [ARCHITECTURE, e.g., x86-64, ARM64]

## Review Constraints
- Focus exclusively on concurrency correctness: memory ordering, ABA problems, linearizability, and progress guarantees.
- Do not comment on naming, style, or general code organization unless it directly impacts concurrency correctness.
- Assume a multi-core environment with a weakly consistent memory model unless specified otherwise.
- [ADDITIONAL_CONSTRAINTS, e.g., "Ignore memory reclamation scheme for now."]

## Required Output Format
Return a JSON object with the following schema:
{
  "findings": [
    {
      "severity": "CRITICAL | HIGH | MEDIUM | LOW",
      "category": "MEMORY_ORDERING | ABA | LINEARIZABILITY | PROGRESS | OTHER",
      "location": "function_name or line range",
      "description": "Concise explanation of the issue.",
      "formal_reference": "Reference to a relevant formal model, paper, or language spec section.",
      "suggested_fix": "Concrete code change or design adjustment.",
      "stress_test_recommendation": "Specific scenario or tool to surface this bug."
    }
  ],
  "linearizability_assessment": "Brief verdict on whether the data structure appears linearizable.",
  "overall_risk": "LOW | MEDIUM | HIGH | CRITICAL",
  "summary": "One-paragraph summary of the review."
}

## Evaluation Criteria
- Every finding must cite a specific code location.
- Severity must be justified by potential impact (data corruption, deadlock, livelock).
- If no issues are found, return an empty findings array and state why.

To adapt this template, start by replacing [CODE_SNIPPET] with the exact function or data structure you are reviewing. Specify the [LANGUAGE] and [MEMORY_MODEL] precisely—a review for C11 atomics on ARM64 will differ significantly from one for Java on x86. Use the [ADDITIONAL_CONSTRAINTS] field to scope the review, for example, to exclude memory reclamation if you are using a known scheme like hazard pointers or epoch-based reclamation. The output schema is designed to be machine-readable for integration into CI pipelines; you can parse the JSON to block a merge if any CRITICAL findings are present. For high-risk code paths, always follow the AI review with a human expert review and runtime validation under a tool like rr or a model checker.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Lock-Free Code Correctness Review Prompt. Each placeholder must be populated with concrete values before execution to ensure reliable analysis of memory ordering, ABA problems, and linearizability.

PlaceholderPurposeExampleValidation Notes

[CODE_SNIPPET]

The lock-free or wait-free data structure implementation to review

A C++ implementation of a Michael-Scott queue with CAS loops

Must be non-empty; parse check for valid source code; reject pseudocode or plain-English descriptions

[LANGUAGE]

Target programming language and memory model version

C++20, Rust (with C++20 memory model), Java 17

Must match an approved language list; reject unsupported or ambiguous language labels

[MEMORY_ORDERING_CONSTRAINTS]

Explicit memory ordering annotations or fences used in the code

std::memory_order_acquire, std::memory_order_release, SeqCst fences

Parse check for valid ordering primitives in the declared language; flag missing or inconsistent annotations

[DATA_STRUCTURE_SPEC]

Expected abstract data type and operations with linearizability requirements

FIFO queue with enqueue and dequeue; must be linearizable under concurrent access

Must describe at least one operation and its correctness condition; reject empty or vague specs

[ABA_PROTECTION_MECHANISM]

Technique used to prevent ABA problems, if any

Tagged pointers, hazard pointers, RCU, or none

Must be one of the known mechanisms or 'none'; flag 'none' as high-risk for CAS-based structures

[STRESS_TEST_SCENARIO]

Concurrent workload description for stress test recommendations

2 writers, 4 readers, 1M operations per thread, x86-64 TSO machine

Must specify thread counts, operation mix, and target architecture; reject scenarios missing thread counts

[KNOWN_FAILURE_LOG]

Optional: logs from prior crashes, hangs, or incorrect outputs

Segfault at line 47 under high contention; lost element after 500K enqueues

Null allowed; if provided, must contain actionable symptom descriptions, not just 'it broke'

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the lock-free correctness review prompt into a CI pipeline or manual review workflow with validation, retries, and model selection guidance.

This prompt is designed to operate as a pre-merge correctness gate for lock-free and wait-free data structure implementations. It expects a complete source file or a focused diff containing the lock-free algorithm, plus optional context about the target memory model (e.g., x86-TSO, ARM weak ordering). The typical integration point is a CI job triggered on pull requests that touch files in paths like src/concurrent/, lockfree/, or directories flagged by a CODEOWNERS rule. Because lock-free bugs are notoriously difficult to reproduce and often survive standard unit tests, this prompt should run before human review begins, surfacing formal correctness concerns that a reviewer might miss during a standard code read.

Wire the prompt into your application by constructing a request that includes the full source code of the lock-free implementation, the target architecture's memory model, and a structured output schema. The model should be instructed to produce a JSON object with fields for correctness_verdict, memory_ordering_issues, aba_risk, linearizability_gaps, and stress_test_recommendations. Validation is critical: after receiving the model response, validate that the JSON schema matches, that all line references fall within the submitted code's line range, and that any claimed violation includes a concrete interleaving scenario. If validation fails, retry once with the validation errors appended as feedback. For high-risk code paths (e.g., memory allocators, garbage collector internals, or networking fast paths), route the validated output to a senior systems engineer for human sign-off before the PR can merge. Log every invocation with the commit SHA, model version, and validation result for auditability.

Model choice matters here. This task requires strong reasoning about memory ordering, happens-before relationships, and abstract state machines. Use a model with demonstrated strength in formal reasoning and code analysis, such as Claude 3.5 Sonnet or GPT-4o, rather than a smaller or faster model optimized for latency. Set the temperature low (0.0–0.1) to maximize deterministic, repeatable analysis. If your CI pipeline has a latency budget, consider running this as an asynchronous check that posts results back to the PR as a comment, rather than blocking the merge queue. Avoid using this prompt on partial diffs that lack the full algorithm context—lock-free correctness often depends on invariants spread across multiple functions. When in doubt, include the entire file or module. Finally, pair this prompt with a concurrency stress test runner (e.g., a tool that exercises the code under thread-sanitizer or equivalent dynamic analysis) and cross-reference the model's stress test recommendations with the runner's findings to catch issues neither approach would find alone.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required fields, types, and validation rules for the lock-free correctness review output. Use this contract to parse, validate, and integrate the model's response into downstream tooling or review dashboards.

Field or ElementType or FormatRequiredValidation Rule

overall_assessment

String (enum)

Must be one of: 'Likely Correct', 'Requires Investigation', 'Incorrect'. No free text allowed.

summary

String

Non-empty string between 50 and 500 characters. Must not contain unresolved placeholders.

findings

Array of objects

Array length must be >= 0. If empty, overall_assessment must be 'Likely Correct'.

findings[].id

String

Unique within the findings array. Format: 'FINDING-###'.

findings[].severity

String (enum)

Must be one of: 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW'. CRITICAL findings require human approval before merge.

findings[].location

String

Must match the pattern 'file_path:line_number' or 'file_path:line_start-line_end'. File path must exist in the provided [CODE_DIFF].

findings[].category

String (enum)

Must be one of: 'Memory Ordering', 'ABA Problem', 'Linearizability Violation', 'Memory Reclamation', 'Starvation/Livelock', 'Other'. If 'Other', a justification is required in the description.

findings[].description

String

Non-empty string. Must reference a specific memory ordering constraint or algorithm invariant from the provided [CONTEXT].

PRACTICAL GUARDRAILS

Common Failure Modes

Lock-free code review is brittle. The model can miss subtle memory ordering violations, hallucinate formal model citations, or produce analysis that looks rigorous but is dangerously wrong. These cards cover the most common failure modes and how to guard against them.

01

Missed Memory Ordering Violations

What to watch: The model fails to identify incorrect or missing memory barriers (e.g., relaxed where acquire/release is required). It may accept sequentially consistent reasoning for code that runs on a weakly ordered architecture. Guardrail: Always require the model to annotate every load and store with its ordering semantics and cross-reference against the target architecture's memory model (x86-TSO, ARM, etc.). If the model cannot produce a valid happens-before graph, flag the analysis as incomplete.

02

ABA Problem Oversight

What to watch: The model reviews a CAS loop and declares it correct without checking for the ABA problem. A pointer or value can change from A to B and back to A between the read and the CAS, causing silent corruption. Guardrail: Explicitly instruct the prompt to check for ABA vulnerabilities whenever a CAS operates on a value that can be recycled. Require the model to state whether hazard pointers, RCU, or tagged pointers are in use and whether they are correctly applied.

03

Linearizability Claim Without Proof

What to watch: The model asserts a data structure is linearizable without identifying the linearization point for each operation. This is a hallucination pattern that sounds authoritative but provides no verifiable reasoning. Guardrail: Require the output to explicitly list the linearization point (a specific instruction or atomic operation) for every public method. If the model cannot identify one, the correctness claim must be downgraded to 'unverified'.

04

Stress Test Recommendations Are Too Weak

What to watch: The model suggests generic stress tests (e.g., 'run with many threads') that will not reliably expose subtle concurrency bugs. Weak interleaving coverage provides a false sense of security. Guardrail: Require the model to recommend specific interleaving scenarios to test, such as a thread being preempted between a load and a CAS. Prefer recommendations that include systematic testing tools like rr chaos modes or model checkers, not just soak tests.

05

Formal Model Citation Hallucination

What to watch: The model invents or misattributes formal model references to sound credible. It may cite a non-existent paper or misrepresent a known algorithm's guarantees. Guardrail: Add a constraint requiring all formal model references to be verifiable against a provided list of canonical sources or to be omitted entirely. Instruct the model to state 'no formal model reference available' rather than guessing.

06

Ignoring Compiler and Hardware Reordering

What to watch: The model analyzes the source code as if it executes in program order, ignoring that both the compiler and the CPU can reorder memory operations. This leads to a 'correct' analysis that is wrong for the compiled binary. Guardrail: Instruct the model to assume a weakly ordered hardware model unless explicitly told otherwise. Require the analysis to distinguish between source-level ordering and the actual memory order enforced by atomics and barriers.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the correctness, completeness, and safety of the lock-free code review output before integrating it into a CI pipeline or accepting it as a review comment.

CriterionPass StandardFailure SignalTest Method

Memory Ordering Constraint Verification

Every identified memory ordering constraint is mapped to a specific line range and the correct C++11 memory order or equivalent language primitive is specified.

Output mentions a constraint without a line reference, or suggests a memory order that is weaker than required for the algorithm's correctness.

Static check: Parse output for line references. Semantic check: Verify the suggested memory order against a known-correct reference implementation of the algorithm.

ABA Problem Detection

For every CAS loop identified, the output explicitly states whether the ABA problem is possible and, if so, proposes a concrete mitigation (e.g., tagged pointers, RCU).

A CAS loop is identified but the ABA problem is not mentioned, or the mitigation is generic ('use a tag') without a code-level suggestion.

Unit test: Provide a code snippet with a known ABA vulnerability. Assert that the output's aba_risk field is true and the mitigation field is not null.

Linearizability Analysis

The output identifies the linearization point for each public operation and states whether the implementation is linearizable, providing a counterexample sequence if it is not.

The output claims linearizability without identifying a linearization point, or fails to provide a concrete interleaving as a counterexample when claiming non-linearizability.

Golden dataset: Use a set of 5 known-linearizable and 5 known-non-linearizable data structure implementations. Assert the output's is_linearizable boolean matches the ground truth.

Stress Test Recommendation Specificity

Stress test recommendations include specific interleavings to target, the number of threads, and the duration or iteration count.

Recommendations are vague, such as 'run under high load' or 'test with multiple threads', without specifying the concurrent operation mix.

Schema check: Assert that the stress_test_recommendations array contains objects with non-null thread_count, operation_mix, and duration fields.

Formal Model Reference Correctness

If a formal model or algorithm name is cited (e.g., 'Michael-Scott queue'), the core invariants of that model are correctly stated and checked against the code.

The output misstates a core invariant of a cited algorithm, or cites an algorithm that is clearly not the one being implemented.

Expert review: Maintain a list of known algorithm invariants. For a given input, assert that the output's invariants_checked list contains the correct invariants for the cited model.

False Positive Rate on Safe Constructs

The output does not flag standard, correctly-used language-level safe concurrency constructs (e.g., a correctly initialized std::atomic with memory_order_seq_cst) as errors.

The output flags a std::atomic load/store with sequentially consistent ordering as a 'potential race condition' without justification.

Regression test: Run the prompt against a curated set of 20 safe lock-free code snippets. Assert that the severity of all findings is none or info.

Output Schema Compliance

The output is valid JSON that strictly matches the expected [OUTPUT_SCHEMA], including all required fields and correct enum values.

The output is missing a required field like linearization_point, contains an invalid enum value for severity, or is not parseable JSON.

Automated validation: Pipe the model's raw output through a JSON schema validator configured with the expected [OUTPUT_SCHEMA]. Assert validation passes.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single code snippet and ask for a high-level correctness opinion. Drop formal model references and stress test recommendations. Replace structured output schema with a simple markdown report.

Prompt snippet:

code
Review this lock-free [DATA_STRUCTURE] implementation for correctness issues:
[CODE]
Focus on memory ordering, ABA problems, and linearizability. Give a bulleted summary.

Watch for

  • Overconfident correctness claims without formal backing
  • Missing memory barrier analysis when the model skips low-level details
  • False positives when the model doesn't understand the specific lock-free algorithm
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.