Inferensys

Prompt

Flaky Test Reproduction Step Generation Prompt

A practical prompt playbook for using Flaky Test Reproduction Step Generation 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

Understand the exact scenario, required inputs, and boundaries for using the Flaky Test Reproduction Step Generation Prompt.

This prompt is for developers and QA engineers who have moved past initial triage and are stuck in the investigation phase. You have a flaky test failure log—stack traces, failure messages, environment metadata—but the failure refuses to reproduce with a simple ./gradlew test --tests FlakyTest or equivalent. The prompt's job is to generate a concrete, repeatable local reproduction script that maximizes the probability of triggering the intermittent failure. It is not a root cause analysis tool, a fix generator, or a test rewriter. Use it when you need to turn a ghost failure into a reproducible event you can debug.

The ideal input includes the full test failure log, the test code itself, any relevant configuration files (e.g., application.properties, CI environment variables), and a description of the conditions under which the failure was observed (CI worker type, concurrency level, test order, recent dependency changes). The prompt works best when the failure is suspected to be environmental, timing-related, or order-dependent. It is less effective for failures caused by truly random external service outages or one-off infrastructure blips that leave no trace in logs. Do not use this prompt when you have no failure evidence at all, or when the test failure is deterministic and already reproducible—in those cases, skip directly to debugging or fixing.

Before running the generated script, validate that it does not introduce destructive side effects (e.g., wiping a shared database, modifying production configs). The script should be treated as a diagnostic tool, not a permanent test fixture. After execution, compare the reproduction rate against the baseline failure rate in CI. If the script fails to reproduce the issue after the recommended number of iterations, you may need to gather additional context—such as thread dumps, database state snapshots, or network capture logs—and re-run the prompt with that expanded evidence. The next section provides the exact prompt template you can adapt and paste into your investigation workflow.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if the Flaky Test Reproduction Step Generation Prompt fits your current situation.

01

Good Fit: Deterministic Flakes with Log Evidence

Use when: You have a flaky test that fails intermittently in CI and you possess the raw failure logs, stack traces, and test code. The prompt excels at converting this evidence into a targeted local reproduction script. Guardrail: Provide the full failure log, not just a summary. The prompt needs the exact error message and surrounding context to generate accurate environment setup and stress conditions.

02

Bad Fit: Novel or Undiagnosed Flakes

Avoid when: The flaky test has no clear error signature or you haven't yet run any initial investigation. This prompt generates a reproduction script from a known failure mode, not a root cause hypothesis. Guardrail: Use the 'Flaky Test Failure Log Analysis Prompt' first to produce a structured hypothesis. Feed that hypothesis into this prompt to generate the reproduction steps.

03

Required Input: Test Code and Failure Artifacts

What to watch: The prompt requires the actual test source code and the full CI failure output to be effective. Without both, the generated script will be generic and unlikely to reproduce the issue. Guardrail: Implement a pre-check in your harness that verifies both [TEST_CODE] and [FAILURE_LOG] placeholders are populated before calling the model. If either is missing, route to a human for evidence gathering.

04

Operational Risk: Over-Reliance on Local Reproduction

What to watch: Successfully reproducing a flake locally can create a false sense of resolution. The underlying environmental or concurrency issue may still exist in CI. Guardrail: Treat the generated script as a diagnostic tool, not a fix. After reproduction, use the 'Race Condition Hypothesis Generation Prompt' or 'Test Environment Dependency Audit Prompt' to identify and address the root cause. Never close a flaky test ticket based solely on a local reproduction.

05

Operational Risk: Script Drift and Maintenance

What to watch: The generated reproduction script is a point-in-time artifact. As the codebase, dependencies, and CI environment evolve, the script will become stale and fail to reproduce the issue. Guardrail: Add a comment header to the generated script with a generation timestamp and a link to the original CI failure. Schedule a review of active reproduction scripts every sprint to ensure they still work against the current main branch.

06

Bad Fit: Infrastructure-Level Flakes

Avoid when: The failure is caused by an external CI infrastructure issue, such as network partitions, disk I/O contention, or a misconfigured Kubernetes node. A local reproduction script cannot replicate these conditions. Guardrail: Use the 'Test Suite Flakiness Attribution Prompt' first to distinguish infrastructure flakiness from code flakiness. If the failure is attributed to infrastructure, route the incident to the platform team instead of using this prompt.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

Paste this prompt into your AI tool. Replace the square-bracket placeholders with your specific failure context.

This prompt template is designed to ingest raw flaky test failure logs and produce a targeted, executable reproduction script. Its primary job is to translate intermittent failure signals—stack traces, timing data, environment variables, and test code—into a concrete local reproduction strategy. The template assumes you have already captured the failure context and are ready to generate a script that maximizes the probability of surfacing the defect on a developer machine or dedicated debugging environment.

text
You are a test reliability engineer specializing in reproducing intermittent test failures. Your task is to generate a targeted reproduction script from the provided failure context. The script must maximize the probability of triggering the flaky failure locally.

## INPUT
- Failure Logs: [FAILURE_LOGS]
- Test Code: [TEST_CODE]
- Environment Context: [ENVIRONMENT_CONTEXT]
- Historical Flakiness Data (optional): [HISTORICAL_DATA]

## OUTPUT_SCHEMA
Return a JSON object with the following structure:
{
  "reproduction_script": "string (a complete, runnable shell script or test runner command)",
  "environment_setup": ["list of prerequisite setup steps"],
  "execution_count": "integer (recommended number of repetitions)",
  "randomization_flags": ["list of flags to introduce non-determinism"],
  "stress_conditions": ["list of system conditions to simulate (e.g., CPU load, network latency)"],
  "key_observations": ["list of specific log patterns or metrics to monitor during reproduction"],
  "confidence_rationale": "string (explain why this strategy targets the hypothesized root cause)"
}

## CONSTRAINTS
- The reproduction script must be self-contained and idempotent.
- Do not suggest modifying production code or CI pipeline configuration.
- If the failure log suggests a race condition, include flags to randomize execution order or introduce artificial delays.
- If the failure log suggests an environmental dependency, include explicit version pinning and cleanup steps.
- Base all recommendations strictly on the provided logs and code. Do not invent failure modes not present in the evidence.
- If the evidence is insufficient to form a hypothesis, set "reproduction_script" to an empty string and explain the missing information in "confidence_rationale".

## EXAMPLES
[EXAMPLES]

## RISK_LEVEL
[RISK_LEVEL]

To adapt this template, start by populating the [FAILURE_LOGS] placeholder with the raw output from your CI runner, including the full stack trace, test name, and any captured stdout/stderr. The [TEST_CODE] placeholder should contain the complete test function and any relevant helper or fixture code. For [ENVIRONMENT_CONTEXT], include details such as the operating system, language runtime version, container image digest, and any environment variables that differ between CI and local runs. The optional [HISTORICAL_DATA] field can accept a summary of past flakiness occurrences for this test, including timestamps and failure frequencies, which helps the model distinguish between a one-off glitch and a systemic pattern.

The [EXAMPLES] placeholder is critical for steering output quality. Provide one or two few-shot examples showing a failure log paired with a high-quality reproduction script. This teaches the model the expected level of detail in the stress_conditions and randomization_flags arrays. The [RISK_LEVEL] placeholder should be set to "low", "medium", or "high" based on the blast radius of the flaky test. For high-risk tests guarding critical release paths, the prompt should be followed by a human review step before the generated script is executed, and the output should be logged for auditability. After generating the script, always validate the JSON structure against the schema before passing it to an automated harness, and discard any output that invents root causes not grounded in the provided logs.

IMPLEMENTATION TABLE

Prompt Variables

Placeholders required by the Flaky Test Reproduction Step Generation Prompt. Each variable must be populated before the prompt is sent. Missing or malformed inputs degrade reproduction accuracy.

PlaceholderPurposeExampleValidation Notes

[FAILURE_LOG]

Raw test failure output including stack trace, assertion errors, and log lines captured during the flaky run

java.lang.AssertionError: expected 200 but got 503 at ApiTest.java:47

Must contain at least one stack frame or assertion message. Null or empty string causes the prompt to refuse generation.

[TEST_CODE]

Full source code of the failing test method and any helper methods it calls directly

@Test public void shouldReturnOrder() { ... }

Must include the complete test method body. Partial snippets reduce hypothesis accuracy. Validate with AST parser for method boundaries.

[EXECUTION_ENVIRONMENT]

Structured description of CI runner OS, CPU count, memory, containerization, and any resource limits

Linux x86_64, 4 vCPU, 16 GB RAM, Docker 24.0, --memory=8g

Must include OS and memory limit at minimum. Missing fields default to 'unknown' and reduce stress-condition precision.

[FAILURE_FREQUENCY]

Observed failure rate as a fraction or percentage across recent runs with total run count

12 failures out of 50 runs (24%)

Must be parseable as a ratio. Values like 'sometimes' or 'often' are rejected. Prompt requires numeric frequency to calibrate reproduction loop count.

[DEPENDENCY_VERSIONS]

List of external service, database, library, and API versions the test interacts with

PostgreSQL 15.3, Redis 7.2, payment-mock 2.1.0

Each entry must follow name-version format. Unpinned versions flagged as environment drift risk. Empty list allowed if test has no external dependencies.

[RANDOMIZATION_FLAGS]

Any random seeds, fuzz parameters, or non-deterministic inputs configured in the test framework

randomized-testing-seed=42, order=random

List each flag with its current value. Unknown randomization settings produce a warning in the generated reproduction script.

[TIMEOUT_CONFIGURATION]

Test-level and suite-level timeout values, including any per-operation timeout settings

testTimeout=30s, httpClientTimeout=5s, dbQueryTimeout=10s

Must include units. Missing timeout values cause the prompt to assume defaults and note the assumption in output.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the reproduction step generation prompt into a CI observability pipeline or developer CLI tool.

This prompt is designed to be called programmatically after a flaky test failure is detected in CI. The typical integration point is a post-failure hook in your test runner (e.g., Jest, Pytest, JUnit) or a webhook from your CI platform (GitHub Actions, Jenkins, Buildkite). When a test fails with a known flaky signature—intermittent pass/fail on retry, timeout variance, or non-deterministic assertion—the harness extracts the failure log, test code, and relevant environment metadata, then calls the LLM with this prompt to generate a local reproduction script. The output is not a fix; it is a diagnostic artifact that reduces the mean time to reproduce the failure locally.

The implementation harness should enforce a strict input contract before calling the model. Required inputs include: the full failure stack trace, the test source code (or at minimum the test method body), the CI execution command, and any environment variables that differ between CI and local defaults. If any required field is missing, the harness should return a structured error rather than calling the model with incomplete context—partial inputs produce unreliable reproduction scripts. After the model returns, validate the output against a schema that requires at minimum a reproduction_command string, a setup_steps array, and a confidence float between 0.0 and 1.0. Reject outputs that lack executable commands or that claim confidence above 0.9 without citing specific log evidence. For high-risk code paths (payment processing, auth, data deletion), route the generated reproduction script to a human for review before execution, and log the full prompt-response pair for audit.

Model choice matters here. Use a model with strong code generation and structured output capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent). Set temperature to 0.2 or lower to reduce variance in the reproduction logic. Enable JSON mode or structured outputs if your provider supports it, binding the response to a schema with reproduction_command, setup_steps, execution_count, randomization_flags, stress_conditions, expected_failure_signature, and confidence. Implement a retry loop with up to two retries if the output fails schema validation; on the second retry, append the validation error to the prompt as additional context. Log every generation attempt with the test name, CI run ID, model version, prompt hash, and validation result. This trace data becomes invaluable when debugging why a reproduction script didn't work—you can compare the generated steps against what actually reproduced the failure and feed that delta back into prompt improvements.

IMPLEMENTATION TABLE

Expected Output Contract

Each field the prompt must return, its type, whether it is required, and the validation rule to apply before accepting the output into the application harness.

Field or ElementType or FormatRequiredValidation Rule

reproduction_script

string (code block)

Must contain executable commands, not pseudocode. Parse check: script must include at least one run command with a loop or repeat count.

environment_setup

array of strings

Each entry must be a valid shell command or environment variable assignment. Schema check: array length >= 1. Null entries not allowed.

execution_count

integer

Must be a positive integer between 10 and 1000. If the prompt suggests a value outside this range, flag for human review.

randomization_flags

array of strings

Each flag must match a known test framework option (e.g., --random, --seed, --shuffle). Unknown flags trigger a retry with framework constraint.

stress_conditions

object

If present, must contain valid keys: cpu_limit, memory_limit, io_delay_ms, network_latency_ms. Each value must be a positive number or null. Unknown keys rejected.

expected_failure_signature

string

Must include a substring from the original failure log. Citation check: compare against [FAILURE_LOG] input. If no match found, output confidence drops and human review is required.

reproduction_probability_estimate

string

Must be one of: low, medium, high. Enum check. If the field is missing or contains an unlisted value, reject the output.

warnings

array of strings

If present, each warning must reference a specific risk (e.g., resource exhaustion, data mutation, port conflict). Generic warnings like 'be careful' trigger a retry for specificity.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when generating reproduction steps for flaky tests and how to guard against it.

01

Hallucinated Reproduction Commands

What to watch: The model invents plausible-sounding but non-existent CLI flags, test runner arguments, or environment variables that don't exist in your framework. Guardrail: Constrain the prompt with an explicit [TEST_RUNNER_SPEC] that lists valid commands, flags, and their signatures. Validate generated commands against this spec before execution.

02

Missing Environment Bootstrap Steps

What to watch: The generated script assumes databases are seeded, services are running, or auth tokens exist without including setup commands. The reproduction fails before reaching the actual test. Guardrail: Require the prompt to output a distinct setup block separate from execution. Add a pre-flight check that verifies each dependency referenced in the execution block has a corresponding setup step.

03

Insufficient Iteration Count for Intermittent Failures

What to watch: The model suggests running the test 2-3 times, which is statistically inadequate for failures with low reproduction rates (e.g., 5% failure rate). Developers waste time with false confidence. Guardrail: Include a [FAILURE_RATE] input and enforce a minimum iteration count based on statistical power. For unknown rates, default to a stress-run of at least 100 iterations with a clear pass/fail threshold.

04

Ignoring Test Order Dependencies

What to watch: The reproduction script runs the target test in isolation, but the flakiness only manifests when it runs after specific predecessor tests due to shared state contamination. Guardrail: When [FAILURE_LOG] shows order-dependent patterns, require the prompt to generate a sequenced execution plan that includes suspected predecessor tests. Flag any reproduction script that only runs the target test in isolation as incomplete.

05

Overfitting to a Single Failure Signature

What to watch: The model latches onto one stack trace or error message and generates reproduction steps for only that failure mode, missing that the test flakes for multiple distinct reasons (e.g., both timeout and data race). Guardrail: Instruct the prompt to cluster distinct failure signatures from [FAILURE_LOG] first, then generate separate reproduction strategies for each cluster. Validate that the output addresses all high-frequency signatures.

06

Unsafe Production-Like Configuration in Local Scripts

What to watch: The generated script copies environment variables or connection strings from CI logs directly into local reproduction commands, risking accidental writes to production services. Guardrail: Add a [SAFETY_RULES] constraint that requires all connection strings and environment values to use clearly marked placeholder tokens. Include a pre-execution scan that blocks scripts containing non-placeholder URIs or secrets.

IMPLEMENTATION TABLE

Evaluation Rubric

How to test output quality before shipping the reproduction step generation prompt. Each criterion targets a specific failure mode common in flaky test reproduction scripts.

CriterionPass StandardFailure SignalTest Method

Environment Setup Completeness

All required environment variables, service dependencies, database states, and configuration flags from [FAILURE_LOG] are explicitly set in the reproduction script

Script references environment values without setting them; assumes global state; omits a dependency mentioned in logs

Diff extracted environment dependencies against script setup commands; flag any dependency present in logs but absent in script

Reproduction Probability Estimate

Script includes a concrete probability estimate (e.g., 'expected to reproduce in 5-15% of runs') grounded in failure frequency from [FAILURE_LOG] and [CI_HISTORY]

No probability estimate provided; estimate is '100%' without justification; estimate contradicts observed failure rate in logs

Parse output for numeric probability range; verify it falls within 2x of failure rate in [CI_HISTORY]; reject if absent or ungrounded

Execution Count Specification

Script specifies minimum number of execution iterations needed to observe the failure at least once with >95% confidence, given the estimated reproduction probability

Script runs test once; iteration count is arbitrary (e.g., 'run 10 times') without statistical justification; no iteration guidance at all

Extract iteration count; verify it satisfies binomial probability calculation for at least one failure observation at stated reproduction rate; flag if missing or uncalculated

Randomization and Stress Controls

Script includes explicit flags for random seed variation, test order randomization, parallel execution, CPU/memory stress, or network latency injection when [FAILURE_LOG] indicates timing or concurrency involvement

Script uses default test runner settings with no randomization; stress conditions mentioned in logs are not replicated; fixed seed used without variation

Check script for presence of flags matching failure category from [FAILURE_LOG]: --random-seed, --shuffle, --parallel, --stress-cpu, --network-latency; flag missing controls

Assertion and Observation Instrumentation

Script includes additional logging, assertion detail, or observation points at the specific code locations identified in [FAILURE_LOG] stack traces to capture intermediate state during reproduction

Script runs test verbatim without added instrumentation; no mechanism to capture state at failure point beyond default test output

Verify script adds logging or debug output at each stack trace location from [FAILURE_LOG]; flag if instrumentation is absent at any failure-relevant code point

Cleanup and Isolation Guarantees

Script includes explicit pre-run cleanup and post-run teardown steps that prevent state leakage between iterations, matching the isolation boundaries identified in [TEST_ENVIRONMENT_CONTEXT]

Script reuses state across iterations; no cleanup between runs; assumes database or file system state resets automatically

Check for presence of setup/teardown blocks per iteration; verify cleanup targets match shared resources in [TEST_ENVIRONMENT_CONTEXT]; flag missing isolation

Failure Signature Matching

Script includes a verification step that confirms reproduced failures match the original failure signature from [FAILURE_LOG] (same exception type, assertion message, or error pattern)

Script treats any test failure as successful reproduction; no comparison against original failure signature; false positive reproduction accepted

Verify output includes a diff or match step comparing reproduction failure output to [FAILURE_LOG] signature; flag if reproduction acceptance criteria are absent or too loose

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single failure log and minimal output constraints. Skip the environment setup and stress condition sections. Focus on getting a basic reproduction script that runs the failing test N times.

code
Generate a reproduction script for this flaky test failure log:
[FAILURE_LOG]

Run the test [REPETITION_COUNT] times and report pass/fail counts.

Watch for

  • Scripts that only run the test once and miss the intermittent nature
  • Missing language or test framework specification
  • No guidance on how to interpret pass/fail results
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.