Inferensys

Prompt

Deadlock Potential Analysis Prompt

A practical prompt playbook for using Deadlock Potential Analysis Prompt in production AI workflows.
Elegant overhead shot of a polished wooden communal table in a sun-drenched WeWork lounge, laptops and tablets displaying AI workflow dashboards, plants and pendant lights in background.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, the ideal user, and the constraints for the Deadlock Potential Analysis Prompt.

This prompt is designed for systems engineers and platform teams reviewing code changes that introduce or modify lock acquisition patterns. Its primary job is to detect circular wait conditions, lock ordering violations, and nested lock risks across multiple resources before they reach production. The ideal user is a developer or reviewer who understands the codebase's concurrency model but needs a structured, automated second pair of eyes to trace lock dependencies that are difficult to hold in memory. The required context is a code diff or a set of code paths that explicitly show lock acquisition and release sequences. Without this, the analysis is speculative and unreliable.

Do not use this prompt for general code review, style checks, or performance profiling. It is not a substitute for runtime lock tracing tools like lockstat or perf lock, nor can it reason about lock contention under real load. Its value is in static, pre-merge analysis of lock ordering. The prompt works best when the input is scoped to a single, coherent change—a pull request, a patch file, or a specific module. Providing an entire repository will dilute the analysis and increase the risk of hallucinated lock graphs. The output is a dependency graph and a ranked risk list, not a definitive proof of deadlock. Every high-severity finding must be validated against runtime lock tracing data when available, and a human reviewer must confirm the feasibility of the reported circular wait before blocking a merge.

Before using this prompt, ensure you have a clear, text-based representation of the lock acquisitions in the target code. If the code uses implicit locking through language constructs or frameworks, you must first extract and document the effective lock paths. After receiving the output, treat the ranked risk list as a triage guide: investigate high-severity items first, attempt to reproduce the deadlock scenario in a test harness, and use the generated dependency graph to communicate the risk to the team. Avoid the temptation to accept the model's reasoning without verification, especially for complex lock hierarchies where the model may miss context from outside the provided diff.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Deadlock Potential Analysis Prompt delivers value and where it introduces risk. Use these cards to decide whether to run this prompt on a given code change.

01

Good Fit: Multi-Resource Locking

Use when: The code change acquires locks on multiple resources (database rows, mutexes, files, distributed locks) in a single request path. Guardrail: Run the prompt on every PR that touches more than one lock acquisition site. The prompt's dependency graph output is most reliable when lock sites are explicit and scoped to a single function or transaction.

02

Bad Fit: Dynamic Locking Patterns

Avoid when: Lock targets are determined at runtime from user input, configuration, or dynamic lookups. The prompt cannot statically analyze runtime-determined resource identifiers. Guardrail: Pair with runtime lock tracing or instrumentation. Use the prompt only to flag that dynamic locking exists and requires manual review, not to produce a definitive deadlock verdict.

03

Required Inputs

What you must provide: The full diff of the code change, the function or method containing lock acquisitions, and the lock acquisition order as it appears in the code. Guardrail: If the diff spans multiple files, include all files that share lock dependencies. Missing context produces false negatives where the prompt cannot see the full wait-for graph.

04

Operational Risk: False Confidence

What to watch: The prompt may produce a clean report for code that contains deadlock risks from indirect dependencies, callback chains, or async continuations it cannot trace. Guardrail: Never use this prompt as the sole gate for merge. Require human review for any code path that crosses thread, goroutine, or transaction boundaries. Treat a clean report as 'no static evidence found,' not 'proven safe.'

05

Operational Risk: Language Blind Spots

What to watch: The prompt's lock ordering analysis assumes standard library synchronization primitives. Custom locking wrappers, framework-managed transactions, or ORM-level locking may be invisible to the analysis. Guardrail: Maintain a registry of known locking abstractions in your codebase and verify that the prompt recognizes them. If not, add explicit comments or annotations before running the prompt.

06

When to Escalate

What to watch: The prompt flags a circular wait condition, or the dependency graph shows a cycle, or the code change touches a component with a history of production deadlocks. Guardrail: Escalate to a senior systems engineer for manual lock ordering review. Do not attempt to auto-fix deadlock findings without understanding the full call graph and runtime behavior under load.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for analyzing lock acquisition patterns and detecting deadlock potential in code changes.

This prompt template is designed to be dropped into a code review harness, a CI/CD pipeline, or a developer's local analysis workflow. It expects a code diff, a language specification, and optional runtime lock tracing data. The output is a structured dependency graph and a ranked list of deadlock risks, making it suitable for automated gating decisions or manual review triage.

text
You are a systems concurrency analyst. Your task is to review the provided code change for deadlock potential. Analyze lock acquisition patterns, identify circular wait conditions, detect lock ordering violations, and flag nested lock risks across multiple resources.

## INPUTS
[CODE_DIFF]
[LANGUAGE]
[OPTIONAL_RUNTIME_LOCK_TRACES]

## ANALYSIS STEPS
1. Parse the code diff to identify all lock acquisition and release sites. Note the lock type (mutex, read/write lock, semaphore, etc.) and the resource it protects.
2. For each function or code path modified, construct an ordered list of locks acquired.
3. Compare lock acquisition orders across all paths to detect inconsistencies. Flag any path where lock A is acquired before lock B in one location but after lock B in another.
4. Identify nested lock acquisitions. For each nested pair, check if the inner lock is ever acquired independently elsewhere, creating a potential circular wait.
5. If [OPTIONAL_RUNTIME_LOCK_TRACES] are provided, cross-reference static findings with observed lock wait events to confirm or refute deadlock risks.
6. For each detected risk, assess whether the deadlock is theoretically possible, practically reachable under concurrent execution, or confirmed by runtime data.

## OUTPUT SCHEMA
Return a JSON object with the following structure:
{
  "analysis_metadata": {
    "language": "string",
    "total_locks_identified": "integer",
    "total_risk_findings": "integer",
    "runtime_data_used": "boolean"
  },
  "lock_dependency_graph": {
    "nodes": [{"id": "string", "type": "lock_type", "resource": "string"}],
    "edges": [{"from": "string", "to": "string", "code_path": "string"}]
  },
  "findings": [
    {
      "id": "string",
      "severity": "CRITICAL | HIGH | MEDIUM | LOW",
      "type": "CIRCULAR_WAIT | LOCK_ORDERING_VIOLATION | NESTED_LOCK_RISK | CONFIRMED_DEADLOCK",
      "description": "string",
      "involved_locks": ["string"],
      "code_locations": [{"file": "string", "line": "integer", "function": "string"}],
      "reproduction_scenario": "string",
      "runtime_confirmation": "CONFIRMED | SUGGESTIVE | NONE | NOT_APPLICABLE",
      "fix_suggestion": "string"
    }
  ],
  "overall_risk_score": "CRITICAL | HIGH | MEDIUM | LOW",
  "requires_human_review": "boolean"
}

## CONSTRAINTS
- Do not flag lock acquisitions that are always serialized by an external guarantee (e.g., single-threaded initialization).
- Distinguish between read locks and write locks when the language supports them. Multiple read locks do not constitute a deadlock risk.
- If the code uses a lock-free data structure, note it but do not apply lock-based analysis.
- If runtime traces are provided and contradict a static finding, prioritize the runtime evidence and explain the discrepancy.
- Mark `requires_human_review` as true if any finding is CRITICAL or HIGH severity, or if the analysis confidence is low due to incomplete information.

To adapt this template, replace the square-bracket placeholders with your actual inputs. The [CODE_DIFF] should be a unified diff or a complete file with changes highlighted. The [LANGUAGE] field should be a standard language identifier (e.g., go, java, python, rust, c++). The [OPTIONAL_RUNTIME_LOCK_TRACES] can be omitted entirely if no runtime data is available; the model will skip cross-referencing. For production use, wrap this prompt in a harness that validates the output JSON against the schema before accepting results. If the model returns malformed JSON, retry with a stricter format instruction or fall back to a repair prompt. Always log the full prompt and response for auditability, especially when the analysis gates a merge decision.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the Deadlock Potential Analysis Prompt needs to produce a reliable dependency graph and ranked risk list. Validate each input before calling the model to prevent garbage-in-garbage-out analysis.

PlaceholderPurposeExampleValidation Notes

[CODE_DIFF]

The code change to analyze for lock acquisition patterns

diff --git a/src/db/transaction.go b/src/db/transaction.go ...

Must be a valid unified diff format. Reject if empty or contains only whitespace changes. Parse check: verify diff hunks have @@ headers.

[LANGUAGE]

Target programming language for lock primitive recognition

Go

Must match a supported language enum: Go, Java, Python, Rust, C++, C#. Reject unknown values. Controls which lock primitives the model searches for.

[LOCK_PRIMITIVES]

Custom lock acquisition functions or patterns to detect beyond defaults

["db.Mutex.Lock()", "cache.RLock()", "semaphore.Acquire()"]

Optional JSON array of strings. If provided, each entry must be a valid function signature pattern. Null allowed. Validate JSON parse before passing to prompt.

[RESOURCE_NAMES]

Human-readable names for resources protected by locks

["user_table", "order_cache", "config_map"]

Optional JSON array of strings mapping to lock primitives. Length must match [LOCK_PRIMITIVES] if both provided. Null allowed. Validate array alignment.

[KNOWN_LOCK_ORDER]

Existing lock ordering convention the codebase follows

["user_table", "order_cache", "config_map"]

Optional JSON array defining expected acquisition order. If provided, model checks for violations against this sequence. Null allowed. Validate array has no duplicates.

[CONTEXT]

Surrounding code or architectural constraints not visible in the diff

This code runs inside a transaction handler with a 30-second timeout. All locks must be released before the transaction commits.

Optional string. If provided, model uses this to assess timeout risks and transaction boundary violations. Null allowed. No length limit but keep under 2000 tokens for cost efficiency.

[OUTPUT_SCHEMA]

Expected structure for the dependency graph and risk list

{"lock_graph": [...], "risks": [...], "deadlock_cycles": [...]}

Required JSON schema definition. Must include fields for lock_graph (nodes and edges), risks (ranked list with severity), and deadlock_cycles (circular wait paths). Validate schema is parseable JSON before passing.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Deadlock Potential Analysis Prompt into a CI/CD pipeline or code review tool with validation, retries, and human escalation.

The Deadlock Potential Analysis Prompt is designed to be integrated into a pre-merge code review pipeline, not as a standalone chat tool. The primary integration point is a CI/CD system (e.g., GitHub Actions, GitLab CI) that triggers on pull requests containing changes to files matching lock-acquisition patterns. The application harness should extract the relevant diff, identify the programming language, and inject any available runtime lock-tracing data (e.g., from a testing or staging environment) into the [RUNTIME_TRACE] placeholder. Without this runtime data, the analysis is purely static and carries a higher false-positive rate for complex, dynamic dispatch scenarios.

The harness must enforce a strict validation loop on the model's output. The expected output is a JSON object containing a dependency_graph (nodes and edges representing lock acquisition order) and a risk_list (ranked findings with severity, code locations, and reproduction scenarios). After receiving the model response, the application must validate the JSON schema, confirm that every file path and line number in the output exists in the current diff, and discard any finding that references code outside the change set. If validation fails, the harness should retry the prompt once with the validation errors appended to the [CONSTRAINTS] field. If the retry also fails, the analysis should be flagged for human review rather than silently posting an incomplete or misleading report. For high-risk repositories, implement a mandatory human approval gate: any finding with a severity of critical or high must block the merge and require a senior engineer to acknowledge the risk.

Model choice matters for this workflow. The prompt requires strong reasoning over code structure and temporal ordering, making it a good fit for models with large context windows and advanced code understanding, such as Claude 3.5 Sonnet or GPT-4o. Avoid using smaller, faster models for this task unless you have a robust fine-tuning dataset of deadlock examples, as they tend to hallucinate circular dependencies in linear code. Log every analysis result, including the full prompt, model response, and validation outcome, to an observability platform. This creates an audit trail for false-positive tuning and allows you to compare static analysis findings against production deadlock incidents over time. Do not use this prompt as the sole gate for deployment; it is a detection tool that complements, but does not replace, stress testing and runtime deadlock detection.

IMPLEMENTATION TABLE

Expected Output Contract

Schema contract for the Deadlock Potential Analysis Prompt. Use this table to validate the model's structured output before merging findings into your review pipeline. Each field must satisfy the listed validation rule or trigger a retry or repair step.

Field or ElementType or FormatRequiredValidation Rule

analysis_id

string (UUID v4)

Must match UUID v4 regex. Generate if absent.

dependency_graph

object (adjacency list)

Must contain 'nodes' (array of resource IDs) and 'edges' (array of {from, to, lock_type}). All node IDs referenced in edges must exist in nodes array.

circular_wait_cycles

array of arrays

Each cycle must be an array of resource IDs forming a closed loop. Empty array if no cycles detected. Validate that each cycle path exists in dependency_graph edges.

lock_ordering_violations

array of objects

Each object must have fields: 'code_path_a' (string), 'code_path_b' (string), 'resource_a' (string), 'resource_b' (string), 'observed_order_a' (string), 'observed_order_b' (string). Both code paths must reference the same two resources in opposite order.

nested_lock_risks

array of objects

Each object must have fields: 'outer_lock' (string), 'inner_lock' (string), 'location' (string: file:line), 'risk' (enum: HIGH, MEDIUM, LOW). 'outer_lock' and 'inner_lock' must differ.

ranked_risk_list

array of objects

Each object must have fields: 'rank' (integer, starting at 1), 'finding_type' (enum: CIRCULAR_WAIT, ORDERING_VIOLATION, NESTED_LOCK, OTHER), 'severity' (enum: CRITICAL, HIGH, MEDIUM, LOW), 'description' (string), 'location' (string: file:line). Array must be sorted by rank ascending.

analysis_confidence

number (0.0-1.0)

Must be a float between 0.0 and 1.0 inclusive. If below 0.7, flag for human review. If null or out of range, retry prompt.

requires_runtime_validation

boolean

Must be true or false. If true, the 'runtime_validation_notes' field must be non-empty.

PRACTICAL GUARDRAILS

Common Failure Modes

Deadlock potential analysis is a high-stakes prompt pattern. The model must reason about temporal logic, resource ordering, and concurrent execution paths from static code alone. These are the most common ways the analysis breaks and how to build guardrails that catch failures before they reach production.

01

False Negatives from Incomplete Call Graphs

Risk: The model analyzes only the code in the diff and misses lock acquisitions in functions called deeper in the call stack, producing a clean report for code that contains a real deadlock. Guardrail: Require the prompt to ingest a pre-computed static analysis call graph or explicitly list all functions in the critical section's transitive closure. If the call graph is incomplete, the output must flag uncertainty rather than claiming safety.

02

Language-Specific Lock Semantics Confusion

Risk: The model applies generic deadlock rules and misinterprets reentrant locks, read-write lock compatibility, or async/await synchronization contexts. A correct lock ordering in one language's memory model may be flagged as a violation, or a real violation may be missed. Guardrail: Include the target language, runtime version, and concurrency model in the prompt context. Validate findings against language-specific documentation and, when available, runtime lock tracing data.

03

Conditional Lock Paths Masked by Simplification

Risk: The model assumes all code paths execute and reports deadlocks that are impossible due to mutually exclusive conditions, or misses deadlocks that only trigger under rare error-handling branches. Guardrail: Instruct the model to enumerate distinct execution paths separately and mark each finding with the specific preconditions required. Require a confidence score per path and flag paths where condition analysis is incomplete.

04

Output Drift Toward Generic Concurrency Advice

Risk: The model produces a long list of general concurrency best practices instead of a specific dependency graph and ranked risk list tied to the submitted code. The output becomes a textbook summary rather than an actionable review. Guardrail: Enforce a strict output schema that requires a lock dependency graph, a ranked list of specific circular wait candidates with line references, and a separate section for non-blocking observations. Reject outputs that lack graph structure.

05

Timeout and Retry Logic Misinterpreted as Deadlock

Risk: The model flags code that uses try-lock with timeout or retry as a deadlock risk, failing to distinguish between blocking deadlocks and recoverable contention patterns. This generates false positives that waste reviewer time. Guardrail: Include explicit definitions in the prompt that distinguish deadlock (unrecoverable circular wait) from livelock, starvation, and contention. Require the model to classify each finding into one of these categories with justification.

06

Transaction Boundary and Database Lock Confusion

Risk: The model conflates application-level lock ordering with database row, table, or advisory locks, producing a dependency graph that mixes abstraction levels and misses cross-resource deadlocks between application locks and database transactions. Guardrail: Require separate analysis sections for application-level synchronization and database transaction locks. When both are present, the prompt must include a cross-resource dependency analysis that traces lock acquisition across both domains.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the Deadlock Potential Analysis Prompt's output before integrating it into a CI/CD pipeline. Each criterion targets a specific failure mode common in concurrency analysis.

CriterionPass StandardFailure SignalTest Method

Dependency Graph Completeness

All lock acquisitions in the provided [CODE_DIFF] are represented as nodes, and all observed acquisition orders are represented as directed edges.

A known lock from the diff is missing from the graph, or a documented acquisition sequence has no corresponding edge.

Parse the output's graph description (e.g., Mermaid or DOT) and compare the set of nodes and edges against a manually verified list from the input diff.

Circular Wait Detection

Every cycle in the generated dependency graph is explicitly listed in the 'Ranked Risk List' with a severity of 'High' or 'Critical'.

A cycle is present in the graph but is missing from the risk list, or a non-existent cycle is reported.

Use a graph cycle-detection algorithm on the generated graph. Assert that the set of cycles found algorithmically matches the set of cycles in the risk list exactly.

Lock Ordering Violation Identification

For every pair of locks acquired in a different order across two or more code paths, a specific violation is reported with file paths and line numbers.

A known inconsistent ordering from the test case is not flagged, or a violation is reported for locks that are always acquired in the same global order.

Provide a diff with a planted lock-ordering violation. Assert that the output's violation list contains an entry with the exact file and line range of the planted bug.

Risk Ranking Accuracy

Findings are ranked 'Critical', 'High', 'Medium', or 'Low' based on the provided [SEVERITY_RUBRIC]. A deadlock cycle must be 'Critical'.

A deadlock cycle is ranked 'Medium' or 'Low', or a purely stylistic finding is ranked 'High'.

Validate that the severity label for each finding matches the definition in the [SEVERITY_RUBRIC] using a keyword-matching script. Flag any mismatches.

Nested Lock Risk Flagging

Any function that acquires Lock A while already holding Lock B is flagged as a 'Nested Lock Risk', even if no cycle is formed.

A clear nested lock acquisition in the diff is not mentioned in the output's risk list or graph annotations.

Inject a function with a synchronous nested lock. Check that the output contains a finding with the type 'Nested Lock Risk' referencing that function's location.

Output Schema Validity

The output is a single valid JSON object that strictly conforms to the provided [OUTPUT_SCHEMA], including all required fields.

The output is not valid JSON, is missing a required field like 'dependency_graph' or 'risk_list', or contains extra unexpected top-level keys.

Validate the raw model output against the [OUTPUT_SCHEMA] using a JSON schema validator. The test fails if the validator returns any errors.

Absence of Hallucinated Code

All file paths, line numbers, and code snippets in the output are directly traceable to the provided [CODE_DIFF] input.

The output references a file, function, or line number that does not exist in the input diff.

Extract all file path and line number pairs from the output. For each pair, verify that the location exists in the input diff using a script. Fail if any location is not found.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single code snippet and minimal output schema. Drop the dependency graph requirement and ask for a plain-text ranked list of lock ordering concerns. Accept informal lock names without requiring full resource path notation.

Prompt snippet:

code
Analyze this code for deadlock potential. List any lock ordering concerns you find, ranked by risk.

[CODE_SNIPPET]

Watch for

  • Model hallucinating locks that don't exist in the code
  • Missing nested lock detection when locks are acquired through helper functions
  • Overly broad warnings that flag every synchronized block as risky
  • No distinction between actual circular wait potential and safe nested acquisition
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.