Compose a concurrency safety review template covering locks, async flows, and invariants.
- User
Compose a concurrency safety review template covering locks, async flows, and invariants.
Assistant
The user wants a "concurrency safety review template." This template needs to cover three specific areas:
- Locks (mutual exclusion, deadlocks, lock granularity).
- Async Flows (race conditions, ordering, cancellation, futures/promises).
- Invariants (data integrity, atomic operations, visibility).
Target Audience: Software engineers conducting code reviews or architectural reviews where concurrent code is involved.
Structure of the Template: I should organize it logically, likely by the categories requested, plus a general "Setup" section and a "Conclusion/Risk Assessment" section.
- Header: Basic metadata (Reviewer, Date, Component, Language/Framework).
- Section 1: Shared State & Invariants (The "What"): Start here because concurrency problems usually stem from shared state. If there's no shared state, we don't need locks.
- Section 2: Locking Strategy (The "How" - Synchronous): Cover mutexes, spinlocks, reentrancy, deadlocks.
- Section 3: Asynchronous Flows (The "How" - Asynchronous): Cover event loops, race conditions in callbacks, context switching, cancellation.
- Section 4: Memory Model & Visibility (The "When"): CPU cache coherency, volatile, memory barriers (crucial for systems languages like C++/Rust/Java).
- Section 5: Testing & Observability (The "Proof"): How do we know it works? Thread sanitizers, stress tests.
Drafting the Content (Iterative refinement):
- Invariants: Are variables immutable? If mutable, are they atomic? Do we rely on complex state transitions that might break halfway?
- Locks: Are we locking the right thing? Is the scope too big (performance) or too small (safety)? Liveness checks (deadlock, livelock). Priority inversion?
- Async: This is tricky because it varies by language (JavaScript vs. Go vs. Rust vs. C#). I should use general terminology but acknowledge specific pitfalls like "callback hell" or "unawaited futures." Crucial point: What happens if an async task fails or gets cancelled? Resource cleanup?
- General: Is the concurrency actually necessary? Can we simplify?
Refining the format: A checklist format is best for a template. It allows for "Pass/Fail/NA" or just ticking boxes.
Self-Correction during drafting:
- Initial thought: Just list questions.
- Correction: Group them by "Severity" or "Category." Let's stick to the user's requested categories (Locks, Async, Invariants) but expand slightly to include Memory Visibility as a sub-point of Invariants/Locks because it's often the root cause of "spooky action at a distance."
Detailed Checklist Items:
-
Locks:
- Double-checked locking (is it broken?)
- Lock ordering (A before B always?)
- Exceptions while holding a lock (RAII/finally blocks?)
-
Async:
- Captured variables in closures (are they valid when the callback runs?)
- Sequential consistency (does the code assume line A finishes before line B when they are actually concurrent?)
-
Invariants:
- Time-of-check to time-of-use (TOCTOU).
- Compound actions (check-then-act).
Final Polish: Make it look professional. Use Markdown. Add a "Red Flags" section for quick scanning.
Let's assemble the template.
Structure:
- Metadata
- Executive Summary (Risk Level)
- Part 1: Shared State & Invariants (The "What")
- Part 2: Locking & Synchronization (The "How")
- Part 3: Asynchronous Flows & Messaging
- Part 4: Error Handling & Resource Management
- Part 5: Testing & Diagnostics
Self-Correction on "Invariants": Ensure I define what an invariant is in this context (e.g., "Account balance never < 0").
Let's write the prompt response based on this structure. I will ensure the tone is technical and precise. Here is a comprehensive Concurrency Safety Review Template. It is designed to be language-agnostic but includes specific considerations for common paradigms (Thread-based locks and Event-loop/Async await).
Concurrency Safety Review Template
Ticket/PR ID: [Link]
Reviewer: [Name]
Date: [Date]
Component: [Service/Module Name]1. High-Level Assessment
- Concurrency Model: (e.g., Multi-threaded, Actor Model, Event Loop/Single-threaded, Multi-process)
- Risk Level: [Low / Medium / High / Critical]
- Summary: [Brief description of what the code is doing concurrently]
2. Shared State & Invariants (The "What")
Focus: Identifying what data is being accessed and ensuring logical consistency.
Check Status Notes Identify Shared State [ ] Have all variables/objects shared between execution contexts been identified? Immutability [ ] Is shared data immutable? (Read-only data is thread-safe). Atomic Invariants [ ] Are class invariants maintained even if execution switches threads halfway through a method? Compound Actions [ ] Are operations that rely on a sequence of state changes (e.g., "check-then-act") atomic? Thread-Safe Types [ ] Are thread-safe collections/primitives used correctly (e.g., ConcurrentHashMap,AtomicInteger)?Escaping References [ ] Does the constructor publish a reference to thisbefore the object is fully constructed?Invariant Analysis:
- List specific logical constraints here (e.g., "Balance must never be negative across simultaneous withdrawals").
3. Locking Strategy (Synchronization)
Focus: Managing exclusive access to shared mutable state.
Check Status Notes Granularity [ ] Is the lock scope minimized? (Avoid holding locks during I/O or long computations). Deadlock Risk [ ] Is locking strictly hierarchical? (Do multiple locks always acquire in the same order?) Lock Object [ ] Are we locking on the correct object? (Avoid locking on String literals or boxed primitives). Reentrancy [ ] Does the lock support re-entrancy if a synchronized method calls another synchronized method on the same lock? Spurious Wakeups [ ] Are wait()/sleep()calls inside a while-loop (checking the condition) rather than an if-statement?RAII / Dispose [ ] Are locks guaranteed to be released even if exceptions occur (e.g., try...finallyorusingblocks)?Deadlock Dependency Map:
- If complex, list lock acquisition order here (e.g., DB Connection -> Cache -> Logger).
4. Asynchronous Flows & Context
Focus: Race conditions in async/await, callbacks, and message passing.
Check Status Notes Context Switching [ ] Is state accessed safely after an awaitor yield? (The thread context may have changed).Closure Capture [ ] Do closures capture variables by reference correctly? Are they mutated unexpectedly? Sequential Assumptions [ ] Does code assume Statement B runs strictly after Statement A? (In async, B might run on a different thread). Cancellation [ ] Is cancellation token propagation handled correctly? (e.g., Operation Aborted vs. Completed). Fire-and-Forget [ ] Are un-awaited tasks handled? (Who catches exceptions in un-awaited async methods?) Queue Backpressure [ ] Is there a bound on message queues/channels? (Risk of OutOfMemory if producer > consumer).
5. Memory Model & Visibility
Focus: Ensuring changes are seen by other threads/tasks immediately and correctly.
Check Status Notes Visibility [ ] Are changes to shared state visible to other threads immediately? (Volatile/Memory Barriers). Instruction Reordering [ ] Could the compiler or CPU reorder instructions in a way that breaks the logic? False Sharing [ ] Are frequently written variables padded to prevent cache-line thrashing (performance/stability)?
6. Error Handling & Resilience
Focus: State recovery when things go wrong.
Check Status Notes Rollback Logic [ ] If a transaction fails halfway, is the state rolled back to the previous consistent state? Exception Safety [ ] Are corrupted states prevented if an error occurs inside a critical section? Timeouts [ ] Do blocking calls (lock acquisition, HTTP calls) have timeouts to prevent hangs?
7. Verification
- Stress Testing: Has this been tested under high load?
- Sanitizers: Have ThreadSanitizer (TSAN) or similar dynamic analysis tools been run?
- Linter: Did the static analyzer catch any concurrency warnings?
Final Sign-off
- Approved: Concurrency logic is sound.
- Request Changes: Issues identified regarding [Deadlocks/Invariants/Async].
- Discuss: Needs further clarification on [Specific Section].
Comments:
- [Detailed feedback here]
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.