This prompt is designed for platform engineers and QA automation leads who need to identify test pollution caused by execution order. The core job-to-be-done is analyzing test execution logs from both randomized and sequential runs to surface dependency pairs—tests that pass in isolation but fail when run after a specific predecessor. The ideal user has access to CI logs with timestamps, test outcome data, and ideally, execution order metadata from test runners that support shuffling (e.g., pytest-randomly, rspec --order random). You should use this prompt when you have evidence of order-dependent failures (a test that fails only in certain CI shards or after a full suite run) but haven't yet isolated the contaminating predecessor. The prompt requires structured input: a list of test cases with their outcomes across multiple runs, the execution order for each run, and any relevant failure messages or stack traces.
Prompt
Test Order Dependency Detection Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Test Order Dependency Detection Prompt.
Do not use this prompt when you lack execution order data or when failures are clearly caused by external factors like network timeouts, resource exhaustion, or infrastructure flakiness. This prompt is not a general flaky test classifier—it specifically targets state leakage between tests (e.g., shared mutable state, uncleaned database records, modified environment variables, or global singleton mutations). If your test framework doesn't randomize order, you'll need to first collect data from at least one randomized run and one sequential run to provide the necessary contrast. The prompt also assumes tests are independent by design; if your suite intentionally relies on ordered execution, this analysis will produce false positives. For high-risk codebases (e.g., financial transaction processing, healthcare data pipelines), always pair the prompt's output with a manual review of the identified dependency pairs before refactoring, as the prompt may miss subtle contamination through indirect side effects or external services.
Before using this prompt, gather your test execution data into a structured format: each run should include the test name, outcome (pass/fail/error), duration, and the ordered list of tests executed before it. If you have multiple CI runs, include at least one randomized run and one sequential run to provide the contrast needed for dependency detection. The prompt will output dependency pairs with supporting evidence, but you should validate each pair by attempting to reproduce the failure locally with the suspected predecessor. After receiving the output, prioritize remediation by focusing on tests that contaminate multiple downstream tests or that affect critical path coverage. Avoid the temptation to simply reorder tests as a fix—this masks the underlying state leakage and will cause failures to resurface unpredictably.
Use Case Fit
Where the Test Order Dependency Detection Prompt works, where it fails, and what you must provide before using it in a CI pipeline.
Good Fit: Randomized vs. Sequential Run Comparison
Use when: You have execution logs from both randomized and sequential test runs for the same suite. The prompt excels at comparing passing/failing status across orderings to isolate dependency pairs. Guardrail: Provide full test names and pass/fail status per run, not just stack traces.
Bad Fit: Single-Run Failure Diagnosis
Avoid when: You only have logs from one failed CI run with no ordering variation data. The prompt cannot infer order dependencies from a single execution trace. Guardrail: Use the Flaky Test Failure Log Analysis Prompt for single-run root cause analysis instead.
Required Input: Execution Order Matrices
Risk: Without explicit before/after ordering data, the model will hallucinate dependency relationships. Guardrail: Provide a structured matrix mapping each test to its execution position and pass/fail status across at least two runs with different orderings. Include test class names and method signatures.
Operational Risk: False Dependency Chains
Risk: The model may infer transitive dependencies (A→B, B→C, therefore A→C) that don't exist in practice. Guardrail: Require the output to include direct evidence for each dependency pair. Flag transitive inferences as hypotheses requiring manual verification before acceptance.
Operational Risk: Shared Fixture Confusion
Risk: Tests sharing database fixtures or mutable state may appear order-dependent when the real cause is fixture contamination, not test-to-test pollution. Guardrail: Pair this prompt with the Database State Contamination Detection Prompt. Cross-reference dependency pairs against shared fixture usage before concluding test order is the root cause.
Scale Limit: Large Test Suite Noise
Risk: In suites with hundreds of tests, random pass/fail noise from unrelated flakiness can produce spurious dependency correlations. Guardrail: Pre-filter tests to those with consistent pass-in-isolation, fail-in-sequence patterns. Require a minimum of three ordering variations before declaring a dependency. Output confidence scores per pair.
Copy-Ready Prompt Template
A reusable prompt template for detecting test order dependencies from execution logs across randomized and sequential runs.
The following prompt template is designed to analyze test execution logs from both randomized and sequential runs to identify test order dependency (TOD) pairs. TOD occurs when a test passes in isolation but fails when run after a specific predecessor due to shared mutable state, unreset singletons, or leaked side effects. This template expects structured log input and produces a dependency pair report with evidence, confidence levels, and remediation suggestions. Use it as the core analysis step in a broader pipeline that includes log collection, randomization, and human review of high-confidence findings.
textYou are a test reliability engineer analyzing test execution logs to detect test order dependencies (TOD). A TOD exists when Test B passes in isolation or randomized runs but consistently fails when executed immediately after Test A. This indicates Test A is polluting shared state that Test B depends on. ## INPUT [TEST_EXECUTION_LOGS] Provide execution logs in the following structure: - Randomized run results: multiple runs with randomized test order, including pass/fail status, duration, and failure messages per test. - Sequential run results: at least one run with a fixed, known order, including pass/fail status, duration, and failure messages per test. - Test code snippets for any failing tests (optional but recommended for higher confidence). - Shared resource inventory: list of known shared resources (databases, files, environment variables, singletons, caches) accessible to the test suite. ## OUTPUT_SCHEMA Return a JSON object with the following structure: { "dependency_pairs": [ { "polluter_test": "string (test that causes the failure)", "victim_test": "string (test that fails due to pollution)", "confidence": "high | medium | low", "evidence": { "randomized_runs": "string (summary of pass/fail pattern in randomized runs)", "sequential_runs": "string (summary of pass/fail pattern in sequential runs)", "failure_signature": "string (consistent error message or exception type)", "shared_resource_suspected": "string (which shared resource is likely polluted)" }, "remediation": "string (specific cleanup, isolation, or ordering fix suggestion)", "requires_human_review": true } ], "no_dependency_found": false, "analysis_notes": "string (summary of overall findings, limitations, and recommendations for further investigation)" } ## CONSTRAINTS - Only report a dependency pair when there is evidence from both randomized and sequential runs. A failure in sequential runs alone is insufficient; you must observe the test passing in randomized runs where the suspected polluter runs after the victim or not at all. - Confidence must be "high" only when the failure is reproducible across multiple randomized and sequential runs with the same polluter-victim ordering and the same failure signature. - If no dependency pairs meet the evidence threshold, set "no_dependency_found" to true and explain why in "analysis_notes". - Do not speculate about code you cannot see. If test code snippets are not provided, note this limitation in "analysis_notes" and reduce confidence accordingly. - Flag all findings with "requires_human_review": true. This analysis is a starting point for investigation, not a final determination. ## EXAMPLES Example input (abbreviated): Randomized run 1: TestA PASS, TestC PASS, TestB FAIL (NullPointerException at line 42) Randomized run 2: TestC PASS, TestB PASS, TestA PASS Sequential run: TestA PASS, TestB FAIL (NullPointerException at line 42), TestC PASS Shared resources: DatabaseConnectionPool (singleton), /tmp/test_uploads/ directory Example output: { "dependency_pairs": [ { "polluter_test": "TestA", "victim_test": "TestB", "confidence": "high", "evidence": { "randomized_runs": "TestB failed in 3 of 4 randomized runs, always when TestA executed immediately before it. TestB passed in the one run where TestA ran after TestB.", "sequential_runs": "TestB consistently fails in sequential runs where TestA precedes it.", "failure_signature": "NullPointerException at DatabaseConnectionPool.getConnection line 42", "shared_resource_suspected": "DatabaseConnectionPool singleton not reset after TestA" }, "remediation": "Add @AfterEach cleanup in TestA to reset DatabaseConnectionPool to its initial state, or use a test-specific connection pool instance.", "requires_human_review": true } ], "no_dependency_found": false, "analysis_notes": "One high-confidence dependency pair identified. Recommend reviewing TestA's teardown logic and TestB's connection pool assumptions." } ## RISK_LEVEL [RISK_LEVEL] If RISK_LEVEL is "high" (e.g., tests cover payment processing, authentication, or data integrity): - Require human review of all findings before any code changes. - Do not suggest automated fixes; only suggest investigation paths. - Flag any finding where the failure signature involves data corruption or security-sensitive paths. If RISK_LEVEL is "medium" or "low": - Still require human review but allow broader remediation suggestions. - Include specific code patterns for cleanup if test code is provided.
To adapt this template for your environment, replace [TEST_EXECUTION_LOGS] with your actual log data in the specified structure. If your test framework produces logs in a different format, preprocess them into the expected structure before passing them to the model. The [RISK_LEVEL] placeholder should be set based on the domain of the tests under analysis—use "high" for security, financial, or data integrity tests, and "medium" or "low" for less critical paths. If you have access to test source code, include it in the input to improve confidence and remediation specificity. Always treat the model's output as an investigation starting point, not a final verdict; every dependency pair requires human verification before any code change is applied.
Prompt Variables
Inputs required for the Test Order Dependency Detection Prompt. Each variable must be populated from CI logs and test metadata before the prompt is assembled. Missing or malformed inputs will degrade detection accuracy.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[SEQUENTIAL_RUN_LOG] | Test execution log from a run where tests executed in a fixed, known order | pytest output with --tb=short and test order preserved | Must contain at least one failure. Parse check: valid UTF-8 text, non-empty, includes test function names and pass/fail status per test |
[RANDOMIZED_RUN_LOG] | Test execution log from a run where test order was randomized or shuffled | pytest output with --random-order flag enabled | Must contain at least one failure. Parse check: valid UTF-8 text, non-empty. Run timestamp must differ from [SEQUENTIAL_RUN_LOG] to confirm separate execution |
[TEST_SUITE_MANIFEST] | List of all test functions in the suite with file paths and class/module membership | JSON array of {test_name, file_path, class_name, module} objects | Schema check: valid JSON array, each object has required fields. Must include all tests referenced in both run logs. Null allowed for class_name on standalone functions |
[EXECUTION_ENVIRONMENT] | Environment details where tests ran: OS, Python version, dependency versions, environment variables | Key-value map or structured block with os, python_version, env_vars, dependencies | Parse check: must include os and python_version fields. Dependencies should be pinned versions, not ranges. Approval required if production secrets appear in env_vars |
[FAILURE_THRESHOLD] | Minimum number of sequential-run failures required before a test pair is flagged as order-dependent | 3 | Parse check: positive integer. Default 2 if not specified. Lower values increase sensitivity but may produce false positives from non-deterministic failures |
[CONFIDENCE_MINIMUM] | Minimum confidence score (0.0-1.0) for including a dependency pair in output | 0.7 | Parse check: float between 0.0 and 1.0 inclusive. Default 0.6. Pairs below threshold are excluded from output but logged for review |
[KNOWN_FLAKY_TESTS] | List of tests already known to be flaky for reasons unrelated to order dependency | JSON array of test function names | Schema check: valid JSON array of strings. Used to suppress false positives. Null allowed if no known flaky tests exist. Tests in this list are excluded from dependency pair output |
Implementation Harness Notes
How to wire the test order dependency detection prompt into a CI pipeline or investigation workflow.
This prompt is designed to be called programmatically after a test suite has been executed in both randomized and sequential orders. The implementation harness should collect the raw test execution logs from both runs, normalize timestamps and test names, and pass them into the prompt as structured inputs. Because the output identifies specific dependency pairs, the harness must validate that every returned predecessor-successor pair references tests that actually exist in the input logs. A test name that appears in the output but not in the input is a hallucination and must trigger a retry or human review before the finding is surfaced to a developer.
Wire the prompt into a CI post-execution step or an on-demand investigation tool. The harness should: (1) collect the randomized-run log and sequential-run log as separate text inputs; (2) inject them into the [RANDOMIZED_RUN_LOG] and [SEQUENTIAL_RUN_LOG] placeholders; (3) set [OUTPUT_SCHEMA] to require a JSON array of objects with fields predecessor_test, successor_test, evidence_summary, and confidence; (4) parse the model response and validate that each predecessor_test and successor_test string matches a test name found in the input logs using exact or fuzzy matching; (5) discard or flag any pair where the model's confidence is below a configurable threshold (start with 0.7); and (6) log the full prompt, response, and validation results for auditability. For high-risk codebases such as payments or auth, add a human-in-the-loop gate that requires a platform engineer to confirm each dependency pair before it is filed as a bug.
Model choice matters here. Use a model with strong reasoning capabilities and a context window large enough to hold both full test logs. If logs exceed the context window, preprocess them by extracting only failed test cases and their immediate neighbors from each run, or chunk by test class and run the prompt per class. Do not truncate logs arbitrarily—missing context causes false dependency claims. For retry logic, if validation fails due to hallucinated test names or malformed JSON, retry once with a stricter [CONSTRAINTS] block that explicitly forbids inventing test names and requires line-number citations from the input logs. If the second attempt also fails, escalate to a human with the raw logs and both model responses attached. Avoid wiring this prompt directly into an auto-quarantine action; dependency detection is probabilistic and false positives can waste developer trust.
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.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
dependency_pairs | Array of objects | Array length > 0. Each element must be a valid object with required sub-fields. | |
dependency_pairs[].dependent_test | String | Must match a test name present in the provided [TEST_EXECUTION_LOG]. Non-empty string. | |
dependency_pairs[].predecessor_test | String | Must match a test name present in the provided [TEST_EXECUTION_LOG]. Must not equal dependent_test. | |
dependency_pairs[].evidence | Object | Must contain exactly three keys: sequential_run_failure, isolation_run_success, and shared_state_hypothesis. | |
dependency_pairs[].evidence.sequential_run_failure | String | Must contain a direct quote or log line from [TEST_EXECUTION_LOG] showing the dependent test failing after the predecessor. Non-empty string. | |
dependency_pairs[].evidence.isolation_run_success | String | Must contain a direct quote or log line from [TEST_EXECUTION_LOG] showing the dependent test passing when run independently. Non-empty string. | |
dependency_pairs[].evidence.shared_state_hypothesis | String | Must describe the specific shared resource or state (e.g., database row, file, env var) suspected of causing the pollution. Non-empty string. | |
unresolved_candidates | Array of objects | If present, each object must contain test_name and failure_signature fields. Used when a test fails only in sequential runs but no clear predecessor is identified. |
Common Failure Modes
Test order dependency detection fails in predictable ways. These cards cover the most common failure modes when analyzing test execution logs for pollution and ordering effects, along with concrete mitigations.
Insufficient Randomization History
What to watch: The prompt identifies false positives or misses real dependencies because the log history contains too few randomized runs. Without enough order permutations, statistical confidence in dependency pairs collapses. Guardrail: Require a minimum of 10 randomized runs before claiming a dependency. Flag any finding backed by fewer than 3 observations as low-confidence and suppress it from automated blocking.
Shared Mutable State Misattribution
What to watch: The model attributes a failure to test ordering when the real cause is a shared database, file system, or in-memory cache that persists across tests regardless of order. The dependency pair is a symptom, not the root cause. Guardrail: Add a pre-processing step that extracts state reset points from logs. Require the prompt to distinguish between order-dependent pollution and global state leakage before emitting a dependency pair.
Setup-Teardown Asymmetry Blindness
What to watch: The prompt misses dependencies where the predecessor's teardown is incomplete rather than its setup being polluting. The model only looks at what the predecessor creates, not what it fails to clean. Guardrail: Include explicit instructions to analyze teardown completeness for each candidate predecessor. Require the output to note whether the dependency is setup-driven or teardown-driven.
Transitive Dependency Collapse
What to watch: Test C fails after Test A, but only when Test B runs between them. The prompt reports a direct A→C dependency, missing the transitive chain. Fixing A→C without addressing B leaves the flakiness intact. Guardrail: Instruct the prompt to check for intermediate tests in failure sequences. When a dependency pair only appears with specific intermediate tests present, flag it as a candidate transitive dependency and request deeper analysis.
Log Volume Overwhelm and Truncation
What to watch: Large test suites produce logs that exceed context windows. The prompt silently operates on truncated input, missing failure patterns in the dropped portion and producing incomplete or misleading dependency lists. Guardrail: Pre-process logs to extract only test names, pass/fail status, execution order, and timestamps. Strip stack traces and assertion details before dependency analysis. If the suite exceeds 500 tests, split by module and merge findings with a deduplication pass.
False Dependency from Environmental Drift
What to watch: A test fails after another test not because of pollution, but because both are sensitive to an environmental variable that changed mid-run—CPU throttling, network latency, or disk I/O contention. The prompt reports an ordering dependency where none exists. Guardrail: Require the prompt to cross-reference failure timestamps with environmental metrics when available. Add a constraint that dependency pairs must survive environment variance checks before being treated as actionable. Flag time-correlated failures separately from order-correlated failures.
Evaluation Rubric
Use this rubric to evaluate the quality of Test Order Dependency Detection outputs before integrating the prompt into a CI pipeline or developer workflow. Each criterion includes a pass standard, a failure signal, and a concrete test method.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Dependency Pair Completeness | Every reported dependency pair includes both a predecessor test and a dependent test, identified by fully qualified test name. | Output contains orphaned references, unnamed tests, or dependency pairs with only one test identified. | Parse output for dependency pair objects. Assert each object has non-null |
Evidence Grounding | Each dependency pair cites at least one specific log line, timestamp, or execution-order artifact from [INPUT_LOGS] that demonstrates the failure pattern. | Dependency pairs lack citations, cite generic categories instead of specific evidence, or reference log lines not present in [INPUT_LOGS]. | For each dependency pair, extract the evidence reference. Verify the referenced log line or artifact exists in [INPUT_LOGS] via substring or exact match. Fail if any reference is absent. |
Isolation vs. Sequential Pass/Fail Accuracy | For every dependency pair, the output correctly states that the dependent test passes in isolation and fails only after the predecessor. No false positives where both tests fail in isolation. | Output claims a dependency where the dependent test also fails in isolation, or where the predecessor has no effect on the dependent test outcome. | Cross-reference each dependency pair against the [ISOLATION_RUN_RESULTS] and [SEQUENTIAL_RUN_RESULTS] inputs. Assert that the dependent test status is PASS in isolation and FAIL in sequential runs following the predecessor. |
Failure Mode Classification | Each dependency pair includes a classified failure mode from the allowed taxonomy: STATE_CONTAMINATION, RESOURCE_LEAK, CONFIG_MUTATION, ORDERED_DATA_DEPENDENCY, or GLOBAL_SINGLETON_SIDE_EFFECT. | Failure mode is missing, uses a value outside the allowed taxonomy, or defaults to a generic catch-all without evidence. | Validate the |
Confidence Calibration | Each dependency pair includes a confidence score between 0.0 and 1.0. High-confidence pairs (>=0.8) have multiple corroborating log lines. Low-confidence pairs (<=0.5) include explicit uncertainty notes. | Confidence scores are missing, uniformly 1.0 without evidence variation, or inversely correlated with evidence strength. | Parse confidence scores as floats. Assert 0.0 <= score <= 1.0. For pairs with score >=0.8, assert at least two distinct evidence references. For pairs with score <=0.5, assert the presence of an |
Output Schema Compliance | The entire output is valid JSON conforming to [OUTPUT_SCHEMA] with all required fields present and no extra top-level keys. | Output is not valid JSON, is missing required fields such as | Run JSON schema validation against [OUTPUT_SCHEMA]. Assert no validation errors. Assert the |
False Positive Rate Control | The output reports zero dependency pairs for test suites with no order dependencies, or explicitly states NO_DEPENDENCIES_FOUND with a brief justification. | Output invents dependency pairs for a test suite known to have no order dependencies, or fabricates evidence to justify a finding. | Run the prompt against a [GOLDEN_NO_DEPENDENCY_SUITE] input. Assert the output contains an empty |
Remediation Hint Relevance | Each dependency pair includes a | Remediation hints are generic ('fix the test'), missing, or suggest actions unrelated to the classified failure mode. | For each dependency pair, assert |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Add strict JSON output schema with field validation. Include retry logic for malformed outputs. Wire in eval assertions: every dependency pair must cite a specific log line or timestamp as evidence.
Prompt additions:
code[OUTPUT_SCHEMA]: { "dependencies": [ { "dependent_test": "string", "predecessor_test": "string", "failure_signature": "string", "evidence_log_lines": ["string"], "confidence": 0.0-1.0 } ], "analysis_notes": "string" } [CONSTRAINTS]: - Every dependency pair MUST include at least one evidence log line. - Confidence below 0.5 MUST be flagged as speculative. - If no dependencies found, return empty array with explanation.
Watch for
- Silent format drift where the model drops
evidence_log_linesunder token pressure. - Missing human review gate for dependencies affecting critical path tests.
- Large log inputs exceeding context windows; chunk by test class or module.

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us