Inferensys

Prompt

Test Environment Contamination Detection Prompt Template

A practical prompt playbook for detecting environment contamination between tests in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

This prompt is for platform engineers and test infrastructure teams debugging state-dependent test failures caused by shared resource contamination between test runs.

Use this prompt when tests pass in isolation but fail in specific execution orders, when shared resources like databases, file systems, or environment variables appear corrupted between test runs, or when failure patterns correlate with test sequence rather than code changes. The prompt analyzes test execution order, shared resource access patterns, and failure correlation to detect environment contamination. It outputs contamination evidence with isolation recommendations. This is not a general-purpose test failure debugger—it targets the specific class of failures caused by leaked state, unreset fixtures, and cross-test pollution.

Do not use this prompt for simple assertion failures, code logic bugs, or performance regressions that are independent of test ordering. It assumes you have access to test execution logs, failure traces, and resource access patterns. Without execution order data and resource access logs, the prompt cannot establish causal links between test sequence and failure. If you only have isolated failure traces without ordering context, start with the Flaky Test Root Cause Analysis Prompt Template instead. This prompt also assumes a shared test environment—if your tests run in fully isolated containers with no shared state, contamination is unlikely and this analysis will produce false positives.

Before running this prompt, gather: a list of test executions with pass/fail status and timestamps, the execution order for failing runs, failure stack traces or error messages, and any available logs showing database state, file system contents, or environment variable values between tests. The more granular your resource access logs, the stronger the contamination evidence the prompt can produce. After receiving the output, validate contamination claims by attempting to reproduce the failure in the identified order, then verify that resetting the suspected shared resource between tests eliminates the failure. Use the isolation recommendations to add teardown hooks, transaction rollbacks, or resource scoping to your test harness.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Understand the operational boundaries before integrating it into your test infrastructure pipeline.

01

Good Fit: CI/CD Pipeline Analysis

Use when: You have structured test execution logs with timestamps, resource access patterns, and failure data across multiple test runs. Guardrail: Feed the prompt sequential test run data rather than aggregated summaries to preserve ordering evidence.

02

Bad Fit: Single Test Run Diagnosis

Avoid when: You only have one test run's output or a single failure without execution history. Guardrail: Contamination detection requires cross-run correlation. Use a flaky test root cause prompt for isolated failures instead.

03

Required Input: Execution Order and Resource Traces

What to watch: The prompt needs test execution order, shared resource access logs (databases, files, environment variables, ports), and failure timestamps. Guardrail: Validate that your log pipeline captures resource-level access before deploying this prompt. Missing resource data produces false negatives.

04

Operational Risk: False Contamination Attribution

What to watch: The model may attribute failures to contamination when the real cause is flaky infrastructure, timeouts, or non-deterministic code. Guardrail: Require human review of contamination evidence before acting on isolation recommendations. Cross-reference with infrastructure health metrics.

05

Operational Risk: Incomplete Resource Tracking

What to watch: Tests may share state through unlogged channels—shared memory, temp files, kernel resources, or external services. Guardrail: Document known blind spots in your resource tracking. Flag contamination findings with a confidence score and note unmonitored resource categories.

06

Variant: Pre-Merge Contamination Check

Use when: You want to detect whether new tests introduce contamination risk before merging. Guardrail: Run this prompt against the proposed test suite execution plan and existing test order data. Gate merges on contamination-free results for critical test suites.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A ready-to-use prompt for detecting test environment contamination from execution logs and shared resource access patterns.

This prompt template is designed to be pasted directly into your AI harness. It instructs the model to analyze test execution order, shared resource access, and failure correlation data to identify environment contamination between tests. Before using it, you must replace every square-bracket placeholder with real data from your test infrastructure. The prompt expects structured input—execution logs, resource access records, and failure histories—and returns a contamination evidence report with isolation recommendations. Do not run this prompt on raw, unprocessed logs; pre-process your data into the expected input format first.

text
You are a test environment contamination analyst. Your task is to examine test execution data and identify evidence of environment contamination—where one test's side effects cause another test to fail or pass incorrectly.

## INPUT
[EXECUTION_LOG]: A JSON array of test execution records. Each record includes: test_name, start_time, end_time, status (PASS/FAIL/ERROR/SKIP), and execution_order_index.

[RESOURCE_ACCESS_LOG]: A JSON array of shared resource interactions. Each record includes: test_name, resource_type (FILE/DATABASE/ENV_VAR/NETWORK_PORT/MEMORY_CACHE/QUEUE), resource_identifier, operation (READ/WRITE/CREATE/DELETE/LOCK/UNLOCK), and timestamp.

[FAILURE_CORRELATION_DATA]: A JSON array of failure patterns. Each record includes: failing_test, co_failing_tests (tests that fail in the same run), historical_pass_rate, and recent_changes (list of recent code or config changes).

[CONSTRAINTS]:
- Only flag contamination when there is direct evidence of shared resource mutation followed by dependent behavior.
- Distinguish between correlation and causation. Do not claim causation without a clear resource dependency chain.
- If no contamination is detected, return an empty findings array with a summary explanation.
- Prioritize findings by severity: HIGH (causes false positives or false negatives in production-critical tests), MEDIUM (causes intermittent failures), LOW (causes only local or non-deterministic ordering effects).

[OUTPUT_SCHEMA]:
Return a JSON object with this exact structure:
{
  "summary": "string describing overall contamination assessment",
  "findings": [
    {
      "contamination_pair": {
        "source_test": "string",
        "affected_test": "string"
      },
      "resource_chain": ["ordered list of resource interactions showing contamination path"],
      "evidence": "string describing the specific evidence from the logs",
      "failure_pattern": "string describing how contamination manifests (false positive, false negative, flaky failure)",
      "severity": "HIGH|MEDIUM|LOW",
      "isolation_recommendation": "string describing how to isolate the tests (e.g., reset shared state, use unique namespaces, mock the resource, reorder test execution)"
    }
  ],
  "uncontaminated_failures": ["list of test names that failed but showed no contamination evidence"],
  "global_recommendations": ["list of environment-level isolation improvements"]
}

## ANALYSIS STEPS
1. Parse the execution log and identify all test failures.
2. For each failing test, trace backward through the resource access log to find tests that mutated resources the failing test later accessed.
3. Cross-reference with failure correlation data to confirm whether the pattern is consistent across runs.
4. For each contamination candidate, construct the resource chain showing the exact sequence of mutations and accesses.
5. Classify severity based on impact and reproducibility.
6. Generate specific isolation recommendations for each finding.
7. Identify failures that cannot be explained by contamination.

## IMPORTANT
- Base every finding on explicit evidence from the provided logs. Do not speculate.
- If the resource access log is incomplete, note this limitation in the summary.
- If execution order was randomized and contamination still occurs, flag this as a high-severity finding because randomization did not prevent it.

After pasting this template, replace each placeholder with real data. The [EXECUTION_LOG] should come from your CI/CD test runner (e.g., JUnit XML, pytest JSON report). The [RESOURCE_ACCESS_LOG] requires instrumentation—you may need to add logging around shared file handles, database transactions, environment variable mutations, and port allocations. If you lack resource access data, the prompt will still analyze execution order and failure correlation, but its findings will be limited to correlation rather than causation. Always validate the output against the [OUTPUT_SCHEMA] before surfacing results to your team. For high-severity findings, require human review before acting on isolation recommendations.

IMPLEMENTATION TABLE

Prompt Variables

Each placeholder the Test Environment Contamination Detection prompt expects. Use these to wire the prompt into your test infrastructure harness before sending it to the model.

PlaceholderPurposeExampleValidation Notes

[TEST_EXECUTION_LOG]

Ordered list of test cases with pass/fail status, timestamps, and execution order index

test_1: PASS (order=0), test_2: FAIL (order=1), test_3: PASS (order=2)

Must contain at least 2 test records with execution order. Parse check: confirm each entry has status and order fields. Null not allowed.

[SHARED_RESOURCE_MANIFEST]

Declared shared resources accessed by tests—databases, files, environment variables, caches, ports, temp directories

DB: test_db_1, File: /tmp/cache.db, Env: APP_MODE, Port: 5432

Each resource must have a type label and identifier. Schema check: validate type is one of DB, File, Env, Cache, Port, Dir, Queue. Empty manifest allowed if no shared resources declared.

[FAILURE_CORRELATION_WINDOW]

Number of preceding tests to examine for contamination influence on a given failure

5

Must be a positive integer. Range check: 1-50. Default to 10 if unset. Null not allowed.

[RESOURCE_ACCESS_LOG]

Per-test record of which shared resources were read, written, created, or deleted during execution

test_2: WRITE /tmp/cache.db, test_3: READ /tmp/cache.db

Each entry must map a test identifier to an operation and resource. Schema check: operation must be READ, WRITE, CREATE, or DELETE. Null allowed if access logging is unavailable.

[FAILURE_SIGNATURE_PATTERNS]

Known failure signatures to match against—error messages, stack trace fragments, timeout thresholds, assertion patterns

ConnectionRefusedError, LockTimeout > 30s, AssertionError on user_count

Each pattern must be a non-empty string. Parse check: at least one pattern required. Used for signature matching in contamination hypothesis generation.

[ISOLATION_BOUNDARY_RULES]

Declared expectations for test isolation—which resources should be reset, which state should be independent

DB must be reset between tests, /tmp/cache.db must not persist writes across test boundaries

Each rule must be a declarative statement with a resource and an expectation. Schema check: rule format is RESOURCE must MUST_NOT SHOULD behavior. At least one rule required.

[OUTPUT_CONFIDENCE_THRESHOLD]

Minimum confidence score for including a contamination finding in the output

0.7

Must be a float between 0.0 and 1.0. Default to 0.6 if unset. Findings below threshold are suppressed or flagged as low-confidence.

[MAX_CONTAMINATION_CHAINS]

Maximum number of contamination chains to report in the output

10

Must be a positive integer. Range check: 1-50. Default to 15 if unset. Prevents output bloat in large test suites.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the contamination detection prompt into a CI pipeline or test analysis workflow with validation, retries, and human review gates.

The contamination detection prompt is designed to operate as a post-execution analysis step in your CI pipeline, not as a real-time test runner. Wire it to trigger after test suite completion when failure patterns suggest state-dependent issues—typically when tests pass in isolation but fail in specific execution orders. The prompt expects structured input containing test execution logs, failure timestamps, shared resource access patterns, and the execution order. Feed this data from your test runner (e.g., pytest with --durations and --last-failed, JUnit XML reports, or custom harness output) into the [TEST_EXECUTION_DATA] placeholder. For large suites, pre-filter to only include failed tests and their immediate neighbors in the execution order to stay within context windows.

Validation and grounding requirements: The prompt output must be validated before any automated action is taken. Implement a post-processing validator that checks: (1) every claimed contamination pair includes specific evidence from the provided execution data—reject pairs that cite file paths, resource names, or timestamps not present in the input; (2) confidence scores are present and within 0.0–1.0 range; (3) isolation recommendations reference concrete mechanisms (e.g., database transaction rollback, temp directory cleanup, mock reset) rather than vague advice. If validation fails, retry once with the validation errors appended to the [CONSTRAINTS] field. On second failure, route to a human reviewer with the raw execution data and partial findings. Model choice: Use a model with strong reasoning capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent) for this task—contamination detection requires correlating patterns across multiple test cases, and smaller models frequently hallucinate causal links. Tool integration: If your test infrastructure exposes APIs for resource provisioning history or database state snapshots, include that data in [SHARED_RESOURCE_CONTEXT] to ground the analysis. For teams using Docker or Kubernetes test environments, include container lifecycle events and volume mount configurations.

Logging and observability: Log every prompt invocation with: test run ID, number of failures analyzed, contamination pairs found, validation pass/fail status, and reviewer assignment if escalated. Store these logs alongside your test result artifacts for post-incident review. Human review gate: Always require human approval before applying isolation fixes suggested by the prompt—changing test isolation strategies (e.g., adding database cleanup hooks, modifying shared fixture scopes) can mask real bugs or introduce new flakiness. The prompt's output should create a review ticket, not a direct commit. Avoid: Do not run this prompt on every CI build—reserve it for suites where flaky failure rates exceed a threshold (e.g., >5% of runs) or when on-call engineers explicitly trigger contamination investigation. Running it indiscriminately burns tokens and generates noise for stable suites.

IMPLEMENTATION TABLE

Expected Output Contract

Validation rules and type constraints for the JSON output produced by the Test Environment Contamination Detection prompt. Use this contract to build a post-processing validator before the output enters any automated pipeline or dashboard.

Field or ElementType or FormatRequiredValidation Rule

contamination_evidence

array

Must be a non-empty array. Each element must be a valid object matching the evidence_item schema.

evidence_item.pair

array[string]

Must contain exactly two test identifiers. Each identifier must match the pattern [TEST_ID_REGEX].

evidence_item.shared_resource

string

Must be a non-empty string describing the shared state (e.g., file path, env var, DB table). Must not be 'null' or 'unknown'.

evidence_item.contamination_type

enum

Must be one of: 'state_mutation', 'resource_exhaustion', 'configuration_leak', 'time_dependency', 'network_side_effect'.

evidence_item.confidence

number

Must be a float between 0.0 and 1.0 inclusive. Values below [CONFIDENCE_THRESHOLD] should trigger a human review flag.

evidence_item.evidence_log_lines

array[string]

Must contain at least one log line or error snippet. Each string must be non-empty. Null entries are not allowed.

isolation_recommendations

array

Must be an array of objects. Each object must have a non-empty 'action' string and a 'target_resource' string.

analysis_metadata.analysis_timestamp

ISO 8601 string

Must be a valid ISO 8601 datetime string. Parse check required; reject if unparseable.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when detecting test environment contamination and how to guard against it.

01

False Positives from Coincidental Timing

What to watch: The prompt attributes failures to test order when failures are actually caused by external factors like CI runner load, network blips, or time-based flakiness that happen to correlate with execution sequence. Guardrail: Require the prompt to cross-reference failure timestamps with system metrics (CPU, memory, I/O) and flag correlation-versus-causation uncertainty. Add a confidence field that drops when external factors cannot be ruled out.

02

Shared Resource Misattribution

What to watch: The prompt identifies a database or file as contaminated but fails to distinguish between tests that share a resource by design (read-only fixtures) and tests that mutate shared state. This produces contamination alerts for safe sharing patterns. Guardrail: Include a resource access mode classifier in the prompt instructions—categorize each access as read-only, write, or append—and only flag write-after-write or write-after-read conflicts as contamination candidates.

03

Incomplete Execution Order Graph

What to watch: The prompt analyzes only the failing test and its immediate predecessor, missing contamination chains where test A contaminates state, test B passes but mutates it further, and test C fails. The root cause (test A) is invisible. Guardrail: Instruct the prompt to build a full directed graph of test execution order and trace contamination backward through all transitive predecessors, not just the immediate prior test. Output the full contamination chain.

04

Silent State Leak Blindness

What to watch: The prompt relies on explicit test failures to detect contamination, but some state leaks cause silent corruption—tests pass but produce incorrect results, or contamination only surfaces under specific data conditions. Guardrail: Add a pre-check step that compares post-test state snapshots (database rows, file contents, environment variables) against expected clean state, even for passing tests. Flag discrepancies as latent contamination risks.

05

Overfitting to a Single Failure Signature

What to watch: The prompt latches onto one failure pattern (e.g., database connection exhaustion) and explains all failures through that lens, ignoring other contamination vectors like environment variable leakage, file handle exhaustion, or clock skew. Guardrail: Require the prompt to enumerate all possible shared resource categories before analysis and produce a differential diagnosis—explain why each resource type is or isn't implicated with specific evidence.

06

Isolation Recommendation Without Feasibility Check

What to watch: The prompt recommends ideal isolation strategies (e.g., full container per test) that are impractical for the team's infrastructure, producing advice that gets ignored. Guardrail: Include infrastructure constraints in the prompt input—test framework, CI environment, resource limits—and require the prompt to rank isolation recommendations by implementation effort and operational impact, not just theoretical correctness.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of contamination detection outputs before integrating the prompt into a production test diagnostics pipeline. Each criterion targets a specific failure mode common in environment contamination analysis.

CriterionPass StandardFailure SignalTest Method

Evidence Grounding

Every contamination claim cites a specific test pair, shared resource, or execution-order observation from the input data

Output contains unsupported claims like 'likely state leak' without referencing concrete test names, timestamps, or resource paths

Parse output for claim statements; verify each has at least one source reference from [TEST_EXECUTION_LOG] or [RESOURCE_ACCESS_TRACE]

False Positive Rate

No contamination flagged for test pairs with zero shared resource access and non-overlapping execution windows

Output flags contamination between tests that ran in isolated processes with no shared files, env vars, databases, or memory

Run prompt on a synthetic clean-suite log with known isolation; assert zero contamination findings returned

Isolation Recommendation Specificity

Each contamination finding includes a concrete isolation fix: specific resource to reset, teardown step to add, or execution order constraint

Recommendations are generic like 'improve test isolation' or 'fix state leak' without naming the resource, cleanup method, or affected test

Extract recommendation text; check for presence of resource name, action verb, and target test identifier in each recommendation block

Severity Ranking Coherence

Contamination findings are ordered by impact: tests causing cascading failures ranked higher than isolated pairwise contamination

Output ranks a single-test-impact finding above a finding that breaks 15 downstream tests, or severity scores are inconsistent with failure counts

Parse severity scores or ordinal positions; correlate with downstream failure counts from [TEST_EXECUTION_LOG]; assert monotonic relationship

Resource Type Classification

Each finding classifies the contamination vector: file system, environment variable, database state, in-memory singleton, network port, or external service

Output uses vague categories like 'state issue' or 'dependency problem' without identifying the resource type

Extract resource type field from each finding; validate against allowed enum: file, env, db, memory, port, external_service; assert non-null

False Negative Coverage

Prompt detects contamination when a test writes to a shared temp directory and a subsequent test reads from that directory without explicit setup

Output reports 'no contamination detected' for a log where test A writes to /tmp/shared-cache and test B reads /tmp/shared-cache with no intervening cleanup

Run prompt on a synthetic log with known shared-file contamination; assert at least one finding with resource type 'file' and both test names

Output Schema Compliance

Output matches the [OUTPUT_SCHEMA] exactly: all required fields present, no extra top-level keys, correct types for arrays and objects

Output is missing 'contamination_pairs' array, adds unsolicited 'summary' field, or uses string where array is expected

Validate output against [OUTPUT_SCHEMA] using JSON Schema validator; assert no schema violations

Confidence Calibration

High-confidence findings (score >= 0.8) correspond to direct evidence: same resource path, sequential execution, and state modification observed

Output assigns confidence 0.95 to a finding based solely on test execution order with no resource access data

Parse confidence scores; for each score >= 0.8, verify presence of resource path match AND execution order proximity in source data

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add strict JSON output schema with contamination evidence fields: test_pair, shared_resource_type, contamination_direction, evidence_signals, confidence_score. Include retry logic for schema validation failures. Add logging for every contamination detection run with input hash, output hash, and model version.

Prompt snippet

code
Analyze the following test execution data for environment contamination.

Test execution log: [TEST_EXECUTION_LOG]
Shared resource inventory: [RESOURCE_INVENTORY]

Output a JSON array of contamination findings. Each finding must include:
- "test_pair": [preceding_test, affected_test]
- "shared_resource_type": one of ["file_system", "database", "environment_variable", "in_memory_state", "network_port", "external_service"]
- "contamination_direction": "preceding_affects_subsequent" | "bidirectional" | "unknown"
- "evidence_signals": list of specific log lines or state observations
- "confidence_score": 0.0 to 1.0
- "isolation_recommendation": string

If no contamination is detected, return an empty array.

Watch for

  • Silent format drift when model returns extra fields or renames keys
  • Missing human review for high-confidence contamination flagged in production-critical test suites
  • Schema validation must run before contamination findings are surfaced to dashboards or alerts
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.