Inferensys

Prompt

Test Isolation Boundary Audit Prompt

A practical prompt playbook for using the Test Isolation Boundary Audit Prompt to detect shared mutable state, global singletons, and cross-test side effects in production CI workflows.
Elegant overhead shot of a polished wooden communal table in a sun-drenched WeWork lounge, laptops and tablets displaying AI workflow dashboards, plants and pendant lights in background.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the precise conditions, required inputs, and boundaries for using the Test Isolation Boundary Audit Prompt.

This prompt is designed for platform engineers and QA architects who need to systematically enforce test independence at scale. The core job-to-be-done is converting a suspicion of shared mutable state into a structured, actionable audit report. You should use this prompt when your team is experiencing unexplained flaky tests, test order dependency bugs, or CI failures that disappear on retry. The ideal user has access to the test source code, the relevant production source code, and optionally, test execution logs that can provide runtime evidence of cross-test contamination. The prompt is not a general code review tool; it is a targeted forensic instrument for identifying violations of test isolation boundaries.

To use this prompt effectively, you must provide concrete source code as the [TEST_CODE] and [SOURCE_CODE] inputs. The prompt assumes these are provided as plain text or markdown code blocks. For best results, include the specific test files that are failing and the production modules they exercise. If you have execution logs, provide them in the [EXECUTION_LOGS] placeholder to ground the analysis in runtime behavior, such as unexpected values in static fields or singletons. The prompt is designed to reason about common isolation-breaking patterns: global singletons, static caches, mutable class-level state, shared database records without cleanup, and file system side effects. It will not be effective if the root cause is an infrastructure issue like network timeouts, disk exhaustion, or CI worker resource contention; for those problems, use a dedicated log analysis or environment audit prompt instead.

Before using this prompt, ensure you have ruled out simple environmental failures and that the flaky behavior is correlated with test execution order or parallel execution. The prompt's value is in its ability to trace side effects across test boundaries and produce a ranked violation report with specific refactoring recommendations. Do not use this prompt when you lack access to the source code, as the analysis depends entirely on static code review augmented by log evidence. After running the audit, the output should be reviewed by a senior engineer who can validate the findings and decide on the appropriate refactoring strategy, such as introducing test fixtures with proper setup and teardown, resetting singletons, or moving to dependency injection.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Test Isolation Boundary Audit Prompt delivers value and where it creates noise. This prompt is designed for systematic detection of shared mutable state, not for general code review or performance analysis.

01

Good Fit: CI Pipeline Gate Enforcement

Use when: You want to block merges that introduce new shared mutable state, static caches, or global singletons into the test suite. The prompt produces a structured isolation violation report that can be parsed by CI tooling. Guardrail: Run this audit on the diff, not the entire repository, to keep token usage bounded and findings relevant to the change under review.

02

Good Fit: Pre-Refactor Baseline Audit

Use when: A platform team plans to parallelize test execution or introduce test sharding. The prompt identifies all existing isolation boundaries that will break under concurrency. Guardrail: Pair the audit output with a test order dependency detection run to catch both static state contamination and sequential coupling.

03

Bad Fit: General Code Quality Review

Avoid when: You need a broad code review covering naming, complexity, or design patterns. This prompt is laser-focused on test isolation violations and will miss non-isolation issues. Guardrail: Use a dedicated PR diff review prompt for general feedback and reserve this prompt for the specific isolation audit step in your pipeline.

04

Bad Fit: Performance Profiling

Avoid when: You are investigating slow tests or memory pressure. Static state detection does not surface time complexity, allocation patterns, or I/O bottlenecks. Guardrail: Combine with a dedicated performance analysis prompt if you need both isolation and performance insights from the same test suite.

05

Required Inputs: Source Code Access

Risk: The prompt cannot detect isolation violations from test logs alone. It needs the actual test source code, setup/teardown hooks, and any shared fixture or helper modules. Guardrail: Provide file paths and relevant source snippets as [INPUT]. If source access is limited, scope the audit to known shared-state hotspots like database helpers, singleton factories, and static configuration modules.

06

Operational Risk: False Positives on Intentional Shared State

Risk: The prompt may flag intentional shared state such as read-only caches, connection pools, or test fixtures designed for reuse as isolation violations. Guardrail: Maintain an allowlist of approved shared-state patterns and feed it as [CONSTRAINTS]. Require human review before blocking CI on findings that match known acceptable patterns.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A ready-to-use prompt for auditing a test suite's isolation boundaries, identifying shared mutable state, and generating a ranked violation report with concrete refactoring recommendations.

This prompt template is designed to be dropped into your AI workflow when you have a set of test files and their execution context ready for analysis. It instructs the model to act as a platform engineering auditor, systematically scanning for the most common vectors of test pollution: global singletons, static caches, shared file systems, environment variable mutations, and database state leakage. The output is not a generic warning but a structured, actionable report that maps each violation to a specific file and line, explains the cross-test side effect, and proposes a concrete cleanup or refactoring strategy.

markdown
You are a senior platform engineer auditing a test suite for isolation violations. Your goal is to identify any shared mutable state that could cause one test to affect the outcome of another, leading to flaky or order-dependent failures.

Analyze the provided test code and any supplied execution logs. For each violation found, you must produce a structured report entry with the following fields:
- `violation_id`: A unique identifier for the finding (e.g., `ISO-001`).
- `severity`: One of `CRITICAL`, `HIGH`, `MEDIUM`, or `LOW`.
- `category`: The type of violation (`GLOBAL_SINGLETON`, `STATIC_CACHE`, `SHARED_FILESYSTEM`, `ENV_VAR_MUTATION`, `DATABASE_STATE_LEAK`, `OTHER`).
- `source_location`: The exact file path and line number where the shared state is defined or mutated.
- `affected_tests`: A list of test names or functions that read or write this shared state.
- `side_effect_description`: A clear, one-sentence explanation of how this state causes cross-test interference.
- `recommended_fix`: A specific, code-level suggestion for isolating the state (e.g., use a fixture with teardown, reset a singleton in `beforeEach`, use unique temp directories).

[TEST_CODE]
[EXECUTION_LOGS]

Before the report, include a brief summary stating the total number of violations found and the most common category. If no violations are found, state that explicitly and do not fabricate issues.

Output the final report as a JSON object with a `summary` string and a `violations` array.

To adapt this prompt, replace the [TEST_CODE] placeholder with the full source of your test files, ensuring you include any imported modules or utility functions that might contain global state. The [EXECUTION_LOGS] placeholder should be filled with the output from a test run that exhibited flaky or order-dependent failures; logs from a randomized test run (e.g., using pytest-randomly or a similar tool) are particularly valuable. For high-risk CI pipelines, always route the model's output through a validation step that checks the JSON schema and verifies that every source_location points to a real line in the provided code. A human platform engineer should review all CRITICAL and HIGH severity findings before any automated refactoring is applied.

IMPLEMENTATION TABLE

Prompt Variables

Each placeholder the Test Isolation Boundary Audit Prompt requires. Validate these before sending the prompt to prevent hallucinated file paths, missing source context, or ambiguous scope.

PlaceholderPurposeExampleValidation Notes

[TEST_SUITE_PATH]

Root directory or glob pattern for the test files to audit

src/tests/**/test_*.py

Must resolve to at least one file. Reject if path does not exist or returns zero files.

[SOURCE_CODE_PATH]

Root directory for the application source code under test

src/app/

Must be a valid directory. Required for cross-referencing singletons and global state in source.

[TEST_FRAMEWORK]

The test framework or runner in use

pytest

Must be one of: pytest, unittest, jest, JUnit, RSpec, xUnit, or custom. Controls assertion and fixture pattern detection.

[LANGUAGE]

Programming language of the test suite and source code

Python

Must be a supported language identifier. Determines static analysis patterns for global state, singletons, and shared caches.

[ISOLATION_RULES]

Team-specific isolation requirements or known acceptable shared state

Database fixtures must use transaction rollback; in-memory cache allowed if reset in teardown

Optional. If provided, use to suppress false positives for explicitly allowed patterns. If null, apply strict isolation defaults.

[OUTPUT_FORMAT]

Desired output structure for the violation report

json

Must be one of: json, markdown, sarif. Controls report schema. Default to json if not specified.

[MAX_VIOLATIONS]

Maximum number of isolation violations to report before truncation

50

Must be a positive integer. Prevents unbounded output for large suites. Default to 50 if not specified.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Test Isolation Boundary Audit Prompt into a CI pipeline or developer workflow with validation, retries, and human review gates.

The Test Isolation Boundary Audit Prompt is designed to run as a pre-merge or nightly CI gate, not as a real-time lint step. Because it requires access to the full test suite source code, execution logs, and optionally runtime state snapshots, it should be invoked after test execution completes and artifacts are available. The prompt expects [TEST_SUITE_CODE] (the test files themselves), [EXECUTION_LOGS] (sequential and randomized run output), and [RUNTIME_STATE_SNAPSHOTS] (optional database dumps, cache contents, or singleton state captures). Wire this into your CI platform (GitHub Actions, GitLab CI, Jenkins) as a post-test job that collects these artifacts, assembles the prompt, and calls your model API.

Validation and retry logic is critical because the output is a structured isolation violation report. Implement a JSON schema validator that checks for the required fields: violation_id, shared_state_type (one of global_singleton, static_cache, database_row, file_system, environment_variable, in_memory_collection), affected_tests (array of test names), evidence (log excerpts or state diffs), severity (one of critical, high, medium, low), and remediation. If the model output fails schema validation, retry once with the validation errors appended to [CONSTRAINTS]. If the retry also fails, log the raw output and escalate to a platform engineer via a Slack webhook or ticketing system. Do not silently accept malformed reports—an unparseable audit is worse than no audit because it creates a false sense of security.

Model choice and context window matter here. Test suites can be large, and execution logs even larger. Use a model with at least a 128K context window (Claude 3.5 Sonnet, GPT-4 Turbo, or Gemini 1.5 Pro) and consider chunking large test suites by module or directory. If chunking, run the prompt independently per chunk and then run a second cross-chunk reconciliation pass that looks for shared state violations spanning module boundaries (e.g., a global singleton mutated in one module and read in another). Store each audit report as a versioned artifact in your CI run so you can track isolation health over time and detect regressions when a previously clean module starts showing violations.

Human review is required before auto-applying remediations. The prompt produces refactoring recommendations, but these can be destructive—suggesting a test order dependency fix might mask a real bug, and recommending singleton teardown might break production code that relies on that state. Configure the harness to post the audit report as a comment on the pull request (if pre-merge) or as a ticket in your issue tracker (if nightly). Require a platform engineer or test owner to acknowledge each critical or high severity finding before the remediation is applied. For medium and low findings, you can auto-create backlog tickets but should not auto-apply fixes. Log every audit run, validation result, retry, and human decision for auditability and to measure the prompt's precision and recall over time.

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.

Field or ElementType or FormatRequiredValidation Rule

isolation_violations

Array of objects

Must be a JSON array. Empty array is valid if no violations found. Schema check: each element must match the violation object contract.

isolation_violations[].test_name

String

Must match a test function name present in the provided [TEST_SUITE_CODE]. Regex: ^test_\w+$ or equivalent naming convention from input.

isolation_violations[].violation_category

Enum string

Must be one of: shared_mutable_state, global_singleton, static_cache, cross_test_side_effect, file_system_contamination, database_state_leak, environment_variable_mutation, network_resource_conflict.

isolation_violations[].shared_resource

String

Must name the specific variable, singleton, file path, table, or resource. Cannot be empty or 'unknown'. Must reference an identifier traceable in [TEST_SUITE_CODE].

isolation_violations[].affected_tests

Array of strings

Must contain at least one test name. Each name must appear in [TEST_SUITE_CODE]. Cannot include the violating test itself unless cross-contamination is bidirectional.

isolation_violations[].evidence_snippet

String

Must be a verbatim code line or block from [TEST_SUITE_CODE] demonstrating the shared state access. Truncate to 3 lines max. Must not be fabricated.

isolation_violations[].severity

Enum string

Must be one of: critical, high, medium, low. Critical reserved for violations affecting test results deterministically. Low for potential but unconfirmed impact.

isolation_violations[].remediation

String

Must contain a concrete, actionable recommendation. Must reference specific cleanup method, refactoring pattern, or isolation primitive. Cannot be 'fix the test' or similarly vague.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when auditing test isolation boundaries and how to guard against it.

01

False Positives from Static Analysis

What to watch: The model flags test fixtures or intentional shared setup (e.g., database seed data) as isolation violations. Guardrail: Provide explicit allowlist patterns for known-safe shared resources and require the model to distinguish between mutable contamination and immutable reference data.

02

Incomplete Dependency Graph Traversal

What to watch: The audit misses cross-test contamination because it only analyzes direct imports, ignoring transitive dependencies, global singleton initialization order, or module-level state mutations. Guardrail: Include a dependency graph or import tree in the input context and instruct the model to trace state mutations through all transitive paths.

03

Misclassifying Test Order Dependencies

What to watch: The model confuses correlation with causation, attributing a failure to the wrong predecessor test when multiple tests mutate the same shared state. Guardrail: Require the prompt to output a confidence score for each identified dependency pair and flag pairs with multiple candidate predecessors for manual investigation.

04

Overlooking Environment-Level Shared State

What to watch: The audit focuses on in-process state (static variables, singletons) but misses external shared resources like temporary files, environment variables, or test database transactions that leak across test boundaries. Guardrail: Explicitly enumerate external resource categories in the prompt and require the model to check for cleanup gaps in teardown hooks.

05

Hallucinated Refactoring Recommendations

What to watch: The model suggests isolation fixes that introduce new problems—removing a shared cache without providing a replacement, or recommending test doubles that don't match the real contract. Guardrail: Require every refactoring recommendation to include a verification step and flag suggestions that modify production code paths for human review.

06

Token Limit Truncation on Large Suites

What to watch: Large test suites with many files exceed context windows, causing the model to audit only a subset and miss cross-file contamination. Guardrail: Chunk the audit by module or service boundary, run multiple passes, and include a cross-pass reconciliation step to catch contamination that spans chunk boundaries.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the Test Isolation Boundary Audit Prompt's output before integrating it into your CI pipeline. Each criterion targets a specific failure mode common in automated code analysis.

CriterionPass StandardFailure SignalTest Method

Shared State Identification

Output lists all concrete instances of shared mutable state (global singletons, static caches, class-level mutable fields) with exact file paths and line numbers.

Output misses a known shared singleton or reports a false positive on a thread-local or effectively-immutable object.

Run against a known test suite with pre-identified shared state. Compare detected instances against the ground truth list. Require 100% recall on pre-identified critical instances.

Cross-Test Side Effect Detection

Output correctly identifies tests that modify shared state without cleanup, with evidence of the specific state mutation and the affected downstream test.

Output claims a side effect exists but cannot cite the specific variable or resource modified, or misses a side effect that causes a documented order-dependent failure.

Execute a test suite with a known order-dependent failure. Verify the output names the exact source test, the mutated state, and the victim test. Check for false positives by running the reported source test in isolation.

Cleanup Recommendation Actionability

Each cleanup recommendation includes a specific code change (e.g., add @AfterEach reset, use a test-specific instance, inject a mock) and the location where it should be applied.

Recommendation is vague (e.g., 'improve isolation') or suggests a pattern that does not resolve the identified violation (e.g., suggesting a mock when a static reset is required).

Review each recommendation manually against the source code. A recommendation passes if a developer can implement it without additional investigation. Fail if the recommendation requires further debugging.

Severity Classification Accuracy

Output assigns a severity (CRITICAL, HIGH, MEDIUM, LOW) that matches a predefined matrix: CRITICAL for cross-test data leaks, HIGH for global singleton mutations, MEDIUM for static cache pollution, LOW for non-deterministic reads of shared config.

A cross-test data leak is marked as LOW, or a non-deterministic read of an immutable config is marked as CRITICAL.

Validate the severity against a pre-defined severity matrix. Check a sample of 10 findings for correct classification. Require >90% accuracy.

False Positive Rate

Output contains zero false positives for shared state and side effect detection on a clean, well-isolated test suite.

Output reports a violation in a test suite known to have no shared mutable state or cross-test side effects.

Run the prompt against a 'golden' test suite with no isolation violations. The output must be empty or explicitly state 'No isolation violations found.' Any reported violation is a failure.

Output Schema Compliance

Output is valid JSON matching the expected schema: a top-level 'violations' array with objects containing 'source_test', 'violation_type', 'shared_resource', 'affected_tests', 'severity', and 'recommendation' fields.

Output is missing required fields, contains extra untyped fields, or is not parseable JSON.

Validate the raw output against the JSON Schema using a programmatic validator. Fail on any schema violation.

Evidence Grounding

Every violation includes a direct code snippet or log excerpt as evidence. The evidence demonstrates the mutable access or side effect.

A violation is reported with a hallucinated code snippet that does not exist in the source files, or the evidence does not demonstrate mutability.

Cross-reference each evidence snippet against the actual source code. Fail if any snippet cannot be located or does not support the violation claim.

Performance on Large Suites

Prompt completes analysis on a test suite of 500+ test files within a reasonable token budget and without truncation.

Output is truncated mid-analysis, or the model loses coherence and begins repeating findings or hallucinating after processing many files.

Run against a large, known test suite. Check for output completeness (no truncation markers) and deduplication of findings. Fail if the output is incomplete or contains duplicate violation reports.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single test file or small test class. Drop the structured output schema requirement and ask for a plain-text isolation violation list. Accept informal input: paste test code directly into the prompt without pre-parsing.

code
Analyze this test file for shared mutable state, global singletons, static caches, and cross-test side effects. List each isolation violation with the affected test names and the shared resource.

[PASTE_TEST_CODE]

Watch for

  • Missing violations in setup/teardown methods that aren't obviously stateful
  • Over-reporting of read-only shared fixtures as violations
  • No severity ranking, making it hard to prioritize fixes
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.