Inferensys

Prompt

Deadlock Reproduction Test Prompt

A practical prompt playbook for generating minimal, reproducible deadlock test scenarios from transaction patterns and lock ordering analysis.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Deadlock Reproduction Test Prompt.

This prompt is for backend engineers and SREs who have strong evidence of a deadlock in production—stack traces, thread dumps, or database lock graphs—but cannot yet reproduce it locally or in a staging environment. The job-to-be-done is to generate a minimal, repeatable test scenario that triggers the same circular wait condition observed in production, using the transaction patterns, lock ordering, and isolation levels extracted from the codebase and incident artifacts. The ideal user has access to the relevant source code, database schema, and production diagnostic data (e.g., SHOW ENGINE INNODB STATUS, pg_locks, or thread dump files). Do not use this prompt for general concurrency testing, load testing, or performance tuning; it is specifically designed to isolate and reproduce a deadlock, not to measure throughput or latency.

The prompt requires several concrete inputs to be effective. You must provide the transaction code paths involved in the deadlock, including the order of statements and any conditional branching. Include the database isolation level configuration and any explicit locking hints (e.g., SELECT ... FOR UPDATE, LOCK TABLE). Supply the production deadlock graph or equivalent diagnostic output that shows which transactions were waiting on which locks. If available, include the application's connection pooling settings and transaction timeout values, as these often mask or exacerbate deadlock timing. The prompt works best when you can isolate two or three specific transactions that form a cycle; avoid dumping entire service codebases without first narrowing the suspect transactions through log analysis or thread dump inspection.

This prompt is not a substitute for production deadlock analysis. It assumes you have already identified the candidate transactions and need help constructing a deterministic reproduction. The generated test will include explicit lock acquisition ordering, timing controls (e.g., Thread.sleep or await barriers), and assertions that validate the deadlock occurs as expected. After generating the test, you must run it in an environment that matches the production database version and configuration. If the test does not reproduce the deadlock, re-examine your isolation level assumptions and the completeness of the transaction code paths you provided. The next step is to use the generated test as a regression anchor: once you apply a fix, the test must pass by demonstrating that the deadlock no longer occurs.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Deadlock Reproduction Test Prompt works and where it introduces risk. Use these cards to decide if this prompt fits your current investigation before wiring it into an automated pipeline.

01

Good Fit: Concurrency Bug Investigation

Use when: You have a stack trace, log evidence, or a bug report pointing to a specific deadlock. The prompt excels at generating minimal reproduction steps from known lock-ordering patterns. Guardrail: Always provide the relevant code paths and isolation level. Without them, the model will guess, producing low-value generic scenarios.

02

Bad Fit: Proactive Deadlock Scanning

Avoid when: You want to scan an entire codebase for potential deadlocks without a specific incident. The prompt is designed for targeted reproduction, not static analysis. Guardrail: Use a static analysis tool or a dedicated Codebase Audit prompt for broad discovery. Reserve this prompt for confirmed or highly-suspected issues.

03

Required Inputs

Risk: Garbage in, garbage out. The prompt's output is only as good as the transaction traces, lock acquisition order, and isolation level you provide. Guardrail: Mandate at least two of the following: a stack trace, a lock-ordering diagram, or the specific database transaction blocks. Reject the prompt's output if it cannot cite the provided inputs.

04

Operational Risk: Flaky Test Introduction

Risk: The generated test might rely on precise timing (Thread.sleep), making it flaky in CI/CD pipelines. A test that passes 80% of the time erodes trust. Guardrail: Add a post-generation validation step. The test must use synchronization primitives like CountDownLatch or CyclicBarrier to guarantee ordering, not timing heuristics.

05

Operational Risk: Production-Like State Dependency

Risk: The reproduction test may require a specific data shape to trigger the deadlock, which might not exist in a clean test database. Guardrail: The prompt's output must include explicit data setup steps (fixtures or factories). If the setup is too complex to be deterministic, flag the test for manual review and do not gate deployments on it.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template with square-bracket placeholders for generating deadlock reproduction test scenarios from concurrency context.

This section provides a copy-ready prompt template that you can adapt for your own deadlock reproduction workflows. The template is designed to accept structured inputs about your system's transaction patterns, lock ordering, and isolation levels, then produce a minimal, reproducible test case. Use the square-bracket placeholders to inject your specific code snippets, database schemas, and configuration details before sending the prompt to the model.

text
You are a concurrency testing specialist. Your task is to generate a minimal, reproducible test case that triggers a deadlock condition based on the provided context.

## INPUT
[TRANSACTION_PATTERNS]

[LOCK_ORDERING_ANALYSIS]

[ISOLATION_LEVEL_CONFIGURATION]

## CONSTRAINTS
- Produce a self-contained test that can run in isolation.
- Use the same database driver, ORM, or connection library already present in the repository.
- The test must fail reliably when the deadlock condition exists and pass when it is resolved.
- Include explicit setup, execution, assertion, and teardown steps.
- Do not introduce new dependencies or test frameworks unless absolutely necessary.

## OUTPUT_SCHEMA
Return a JSON object with the following fields:
{
  "test_name": "string, descriptive name for the test case",
  "language": "string, programming language of the test",
  "framework": "string, test framework to use",
  "setup_code": "string, code to prepare the required state (tables, rows, connections)",
  "test_code": "string, the concurrent execution code that triggers the deadlock",
  "assertions": ["string, list of assertions that verify deadlock behavior"],
  "teardown_code": "string, code to clean up resources after the test",
  "reproduction_steps": ["string, ordered list of human-readable steps to reproduce"],
  "expected_deadlock_graph": "string, description of the expected wait-for cycle",
  "risk_notes": "string, any assumptions or environmental dependencies"
}

## EXAMPLES
[EXAMPLES]

## RISK_LEVEL
[RISK_LEVEL]

Generate the test case now.

To adapt this template, replace each placeholder with concrete information from your investigation. For [TRANSACTION_PATTERNS], paste the relevant code blocks or pseudocode showing how transactions acquire and release locks. For [LOCK_ORDERING_ANALYSIS], include your findings on which resources are locked in which order across concurrent sessions. For [ISOLATION_LEVEL_CONFIGURATION], specify the database isolation level, any lock hints, and connection pool settings. The [EXAMPLES] placeholder should contain one or two existing test patterns from your repository so the model can match your team's conventions. Set [RISK_LEVEL] to "low", "medium", or "high" to control how conservative the generated assertions should be. After generating the test, always validate that the output matches the OUTPUT_SCHEMA before integrating it into your test suite, and run the test in an isolated environment to confirm reproducibility.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Deadlock Reproduction Test Prompt. Each placeholder must be populated with concrete values from the target system to produce a reliable, reproducible deadlock scenario.

PlaceholderPurposeExampleValidation Notes

[TRANSACTION_LOG_SNIPPET]

Raw log excerpt showing two or more transactions contending for locks, including timestamps and session IDs

2025-01-15 14:32:01.123 | sess_a | UPDATE accounts SET balance = balance - 100 WHERE id = 1 | waiting on lock

Must contain at least two distinct session identifiers and explicit lock-wait events. Reject if only single-session activity is present.

[DATABASE_SCHEMA_DDL]

DDL statements for all tables involved in the contention, including indexes and constraints

CREATE TABLE accounts (id INT PRIMARY KEY, balance DECIMAL); CREATE INDEX idx_balance ON accounts(balance);

Must include primary key, foreign key, and unique constraint definitions. Null allowed if schema is inferred from ORM models.

[ISOLATION_LEVEL]

Transaction isolation level configured for the database connection or session

REPEATABLE READ

Must be one of: READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE. Reject ambiguous values like 'default'.

[LOCK_TIMEOUT_CONFIG]

Lock timeout and deadlock timeout settings from database configuration

innodb_lock_wait_timeout = 50; deadlock_timeout = 5s

Must include numeric timeout values with units. Null allowed if using database defaults, but must be explicitly declared as null with a note.

[APPLICATION_CODE_PATH]

File path or code block containing the transaction logic that participates in the lock ordering

src/services/transfer_service.go lines 45-78

Must resolve to an actual file path or be a verbatim code block under 200 lines. Reject if path does not exist in the repository.

[CONNECTION_POOL_CONFIG]

Connection pool size, max connections, and session assignment strategy

pool_size: 10; max_overflow: 5; pool_timeout: 30s

Must include pool_size and max_connections. Null allowed for single-connection test harnesses, but must be declared.

[EXPECTED_LOCK_ORDER]

Documented or inferred lock acquisition order that the application intends to follow

accounts table row lock, then transactions table row lock

Must be a sequence of at least two lock targets. If unknown, use null and the prompt will infer from code analysis.

[REPRODUCIBILITY_TARGET]

Minimum number of consecutive successful reproductions required to consider the test valid

5 out of 5 runs within 30 seconds each

Must specify a count and a time bound. Reject targets below 3 runs as insufficient for deadlock reproducibility confidence.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the deadlock reproduction prompt into a concurrency testing pipeline with validation, retries, and safety checks.

The deadlock reproduction prompt is designed to be called from a backend testing harness, not run manually in a chat interface. The harness should supply the prompt with a structured [TRANSACTION_PATTERNS] payload extracted from database logs, lock-monitoring tools, or ORM query traces. The model returns a structured test scenario that the harness then executes in an isolated test environment. Because deadlock reproduction involves running concurrent transactions that intentionally contend for locks, the harness must enforce strict isolation: never run generated tests against production databases, and always use a dedicated test instance with snapshot or restore capability.

Wire the prompt into your application with a validate → execute → verify loop. First, parse the model's JSON output and validate that the reproduction_steps array contains executable SQL or ORM operations, that expected_deadlock_point identifies a specific lock resource, and that isolation_level matches a supported value in your test environment. If validation fails, retry the prompt once with the validation errors appended to [CONSTRAINTS]. Before execution, the harness must snapshot the test database state. Execute the generated steps using two or more concurrent sessions as specified in the concurrency_model field. After execution, verify that the deadlock actually occurred by checking database deadlock logs, lock-wait timeouts, or the error codes returned to the sessions. If the deadlock does not reproduce within the specified timeout, capture the actual lock-wait graph and feed it back to the model as [OBSERVED_BEHAVIOR] for a refinement pass.

For model choice, prefer models with strong SQL and concurrency reasoning. The prompt's structured output schema and step-by-step lock-ordering analysis benefit from models that can reason about transaction interleaving. Set temperature low (0.0–0.2) to maximize reproducibility of the generated test steps. Log every generated scenario, execution outcome, and reproduction success rate to build a regression suite over time. Never allow the harness to execute generated tests that include DROP, TRUNCATE, or unqualified DELETE statements—add a pre-execution safety filter that rejects destructive operations. If the prompt is used in a CI pipeline, gate deployment on successful deadlock reproduction for known lock-ordering bugs, and require human review for any generated test that proposes changing isolation levels in production configuration.

IMPLEMENTATION TABLE

Expected Output Contract

Validate the structure and content of the AI-generated deadlock reproduction test. Use this contract to programmatically parse the output, confirm required fields are present, and enforce quality gates before the test is executed.

Field or ElementType or FormatRequiredValidation Rule

test_name

string

Must be a non-empty string under 120 characters. Should describe the deadlock scenario, e.g., 'Two transactions updating accounts in reverse order'.

test_file_path

string

Must be a valid relative path ending in a recognized test file extension (e.g., '_test.py', '.spec.ts'). Path must exist in the repository map.

setup_steps

array of strings

Array must contain at least one step. Each step must be a non-empty string describing a prerequisite action (e.g., 'Create two bank accounts with a balance of 100').

concurrent_operations

array of objects

Array must contain exactly two objects. Each object must have 'thread_name' (string) and 'steps' (array of strings) fields. The 'steps' arrays must describe a transaction sequence with at least one lock-acquiring operation.

expected_deadlock_graph

object

If present, must contain 'nodes' (array of strings) and 'edges' (array of arrays). Each edge must represent a 'waits-for' relationship between two nodes, forming a cycle.

isolation_level

string

Must be one of the supported database isolation levels: 'READ_COMMITTED', 'REPEATABLE_READ', or 'SERIALIZABLE'. Value must match the database configuration in the provided context.

timeout_seconds

integer

Must be a positive integer between 1 and 60. This is the maximum time to wait for the deadlock to occur before marking the test as failed.

assertion_type

string

Must be one of: 'exception_match', 'log_pattern', or 'metric_check'. Describes how the test confirms a deadlock occurred. If 'exception_match', the 'expected_exception' field is required.

PRACTICAL GUARDRAILS

Common Failure Modes

Deadlock reproduction tests are high-signal but brittle. These are the most common ways they fail in production pipelines and how to prevent them.

01

Non-Deterministic Reproduction

What to watch: The generated test passes locally but fails in CI or vice versa due to timing sensitivity, CPU count, or scheduler differences. The prompt may produce a test that relies on a specific interleaving that isn't guaranteed. Guardrail: Require the prompt to generate a test that uses a deterministic scheduler, explicit lock ordering, or a controlled concurrency harness (e.g., CountDownLatch, CyclicBarrier) rather than raw Thread.sleep() calls.

02

False Positive Deadlock Detection

What to watch: The test times out and reports a deadlock, but the system is merely slow under load. The prompt conflates a long wait with a circular wait, producing a test that fails on resource-constrained CI runners. Guardrail: Add a constraint in the prompt to differentiate between a true deadlock (thread dump showing BLOCKED cycles) and a performance timeout. The generated test must include a thread state assertion, not just a time-bound assertion.

03

Incomplete Transaction Context

What to watch: The prompt generates a test from a single code path but misses the enclosing transaction scope, connection pool settings, or isolation level that is required to trigger the deadlock. The test runs but never hits the actual contention point. Guardrail: The prompt template must require [TRANSACTION_CONTEXT] as a mandatory input, including isolation level, pool size, and auto-commit settings. The output test must explicitly configure these in the setup phase.

04

Over-Simplified Lock Graph

What to watch: The prompt infers a two-thread, two-lock deadlock but the real system involves a chain of three or more resources, or a lock plus a channel operation. The generated reproduction misses the actual cycle. Guardrail: Instruct the prompt to output a lock dependency graph as a comment block before generating the test code. If the graph has fewer nodes than the [LOCK_ORDERING_ANALYSIS] input, flag it for human review before execution.

05

State Leakage Between Runs

What to watch: The generated test mutates shared database rows, file handles, or in-memory state without cleanup. The first run reproduces the deadlock, but subsequent runs fail or deadlock in a different place due to residual data. Guardrail: The prompt must include a [CLEANUP_CONSTRAINT] that requires explicit @BeforeEach/@AfterEach teardown logic. The eval step must verify that the test can run twice in a row without manual intervention.

06

Environment-Specific Lock Behavior

What to watch: The test relies on database-specific locking semantics (e.g., PostgreSQL advisory locks vs. MySQL gap locks) but the prompt wasn't given the target environment. The test passes on one DB engine and fails silently on another. Guardrail: Add a required [DATABASE_ENGINE] and [VERSION] input to the prompt template. The generated test must include an assertion on the engine type or use only ANSI-standard locking behavior documented in the input context.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality and safety of a Deadlock Reproduction Test Prompt output before integrating it into a CI pipeline or test suite.

CriterionPass StandardFailure SignalTest Method

Reproducibility

Test consistently deadlocks within 5 runs on the target isolation level

Test passes or times out without deadlock in 10 consecutive runs

Execute test in isolated environment with target database config; count deadlock occurrences

Minimal Reproduction

Test involves 2-3 concurrent transactions with minimal schema and data

Test requires more than 5 tables or complex multi-statement transactions

Schema diff check: count tables, indexes, and transaction statements in generated test

Lock Ordering Accuracy

Generated lock acquisition order matches the inverted lock ordering identified in analysis

Test acquires locks in the same order for both transactions or misses a documented lock

Parse generated SQL for LOCK/SELECT FOR UPDATE statements; compare sequence against analysis report

Isolation Level Correctness

Test uses the exact isolation level specified in [ISOLATION_LEVEL] placeholder

Test uses a different isolation level or omits SET TRANSACTION ISOLATION LEVEL

Grep generated test for isolation level directive; assert exact match with input parameter

Resource Contention Clarity

Test targets exactly 2 specific resources with clear lock escalation path

Test locks entire tables or uses broad predicates that obscure the contention point

Review lock target granularity: row-level locks preferred; flag full-table locks

Teardown Safety

Test includes cleanup that releases all locks and rolls back transactions

Test leaves open transactions or requires manual lock termination

Run test and immediately query pg_locks or equivalent; assert zero residual locks

Assertion Precision

Test asserts on deadlock error code or timeout, not on generic exception

Test catches all exceptions or asserts on success without deadlock detection

Inspect exception handling: must catch specific deadlock error code (e.g., PostgreSQL 40P01)

Documentation Completeness

Test includes comments explaining the deadlock scenario and reproduction steps

Test has no comments or comments that don't describe the deadlock mechanism

Check for presence of multi-line comment block describing lock ordering, resources, and expected outcome

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single database dialect and lighter reproducibility constraints. Replace [DATABASE_SYSTEM] with a concrete target (e.g., PostgreSQL 15). Drop the [ISOLATION_LEVEL_MATRIX] placeholder and hardcode one level. Accept a single lock-ordering trace instead of requiring multiple transaction patterns.

Watch for

  • Generated tests that deadlock only under ideal conditions, not real load
  • Missing cleanup steps that leave test databases in locked states
  • Overly broad SETUP blocks that mask the actual deadlock trigger
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.