How to Fix Context Bleeding in BDD + AI Tests
AI-assisted test generation has made it trivially easy to produce hundreds of Gherkin scenarios in an afternoon. The problem most teams hit by week two isn't coverage — it's context bleeding: state from one scenario leaking into the next, producing failures that are real but non-deterministic, and successes that are false. The failure mode is subtle enough that engineers often blame flakiness tooling before they blame architecture.
Context bleed in BDD + AI testing happens at multiple layers simultaneously: the browser session, the step-definition registry, the AI agent's in-flight conversation window, and the test runner's hook lifecycle. Fixing one layer while ignoring the others just moves the problem. This article maps each layer, shows where isolation breaks, and gives you concrete patterns to seal each boundary.
By the end, you'll know exactly where to instrument, what to reset, and which architectural choices make context bleed structurally impossible rather than just unlikely. The urgency is real: Playwright 1.40+, Cucumber-JVM 7, and LLM-backed test agents all introduced new shared-state surfaces in the last 18 months that older isolation advice doesn't cover.
Securely manage keys for 60+ AI providers in one encrypted vault instead of juggling them across apps.
What Context Bleed Actually Is (and Where It Lives)
Context bleed is the unintended persistence of mutable state across a scenario boundary. In classical BDD this means a browser cookie, a database row, or an in-memory step registry carrying data from Scenario A into Scenario B. In AI-augmented pipelines the surface area doubles: an LLM agent also carries a conversation window, tool-call history, and inferred intent that can silently influence how it interprets the next scenario's steps. The two failure modes look identical in a test report — intermittent assertion errors — but have completely different root causes and fixes.
Architecturally, context lives in four distinct layers: (1) browser/session state (cookies, localStorage, active page handles), (2) step-definition scope (world objects, dependency-injected containers, shared fixtures), (3) hook execution order (Before/After hooks that mutate shared objects), and (4) AI agent memory (prompt history, tool-call buffers, retrieved embeddings). Most teams have reasonable hygiene at layer 1 and almost none at layer 4. As covered in detail when examining context bleed in AI-generated BDD steps, the agent layer is where isolation assumptions collapse fastest.
Sealing Every Boundary: A Layer-by-Layer Fix
Layer 1 — Browser Session Isolation
The most common mistake with Playwright is reusing a BrowserContext across scenarios for performance. It works until a scenario sets a cookie or modifies localStorage, at which point every downstream scenario in that worker inherits dirty state. The correct pattern is a fresh context per scenario, created inside the Before hook and torn down in After:
# conftest.py (Pytest-BDD / Behave)
import pytest
from playwright.sync_api import sync_playwright
@pytest.fixture(scope="function")
def browser_context():
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
ctx = browser.new_context() # fresh context, every scenario
yield ctx
ctx.close()
browser.close()
Pooling contexts for speed is a real trade-off — cold context creation adds ~120 ms per scenario — but the isolation cost is higher. The architecture decision around browser context pooling and scenario isolation is worth reading before you optimise for throughput at this layer.
Layer 2 — Step-Definition Scope and World Objects
In Cucumber-JVM 7 and Behave, the World object (or PicoContainer-injected dependencies) must be instantiated fresh per scenario. A static field or a module-level singleton will bleed. In Behave, context is reset between scenarios only if you explicitly clean it in after_scenario; attributes added dynamically in a step persist by default.
# environment.py (Behave)
def after_scenario(context, scenario):
# Explicitly purge dynamic attributes set during the scenario
for attr in ("auth_token", "cart_id", "last_response"):
if hasattr(context, attr):
delattr(context, attr)
The deeper issue is that how scenario context passes between hooks and step definitions is often implicit — engineers assume the framework handles it and never audit what's actually on the object at teardown. Logging context.__dict__ in after_scenario for one full suite run will usually surface three or four attributes that should never have survived.
Layer 3 — AI Agent Conversation Window
This is the layer most teams haven't instrumented yet. When an LLM agent (GPT-4o, Claude 3.5 Sonnet, or a Cursor-generated test runner) executes a multi-step scenario, each tool call appends to a growing message thread. If the agent is reused across scenarios — common in frameworks that initialise agents at session scope for cost reasons — the prior scenario's tool-call results sit in the prompt context and bias step interpretation for the next scenario.
// TypeScript — reset agent context between scenarios (Playwright + LangChain)
import { BeforeEach, AfterEach } from "@cucumber/cucumber";
import { ChatOpenAI } from "@langchain/openai";
import { BufferMemory } from "langchain/memory";
let agentMemory: BufferMemory;
BeforeEach(function () {
// New memory buffer per scenario — do NOT hoist this to module scope
agentMemory = new BufferMemory({ returnMessages: true });
this.agent = new ChatOpenAI({ model: "gpt-4o", temperature: 0 });
this.agentMemory = agentMemory;
});
AfterEach(async function () {
await this.agentMemory.clear();
});
The cost of a fresh memory buffer is negligible. The cost of not resetting it is an agent that "remembers" a login token from Scenario 12 and skips the authentication step in Scenario 13 — passing silently. This specific failure pattern, where ambient context in AI test agents corrupts step boundaries, is the hardest to catch in CI because the scenario reports green.
Layer 4 — Hook Execution Order Under Parallel Runners
GitHub Actions matrix builds and pytest-xdist workers each run a subset of scenarios, but shared fixtures at the session or module scope can still bleed across worker boundaries if they write to a shared resource (a database schema, a Redis key, an S3 bucket). The fix is namespace isolation: prefix every resource key with the worker ID.
# pytest conftest.py — worker-namespaced DB schema
import os
@pytest.fixture(scope="session")
def db_schema(worker_id):
schema = f"test_{worker_id}_{os.getpid()}"
create_schema(schema)
yield schema
drop_schema(schema)
Run time for a 400-scenario suite dropped from 18 minutes to 4 minutes with four parallel workers once namespace isolation was in place — previously, workers were clobbering each other's seed data and retrying failed scenarios serially.
Where Senior Engineers Still Get Burned
Fixture scope creep is the most common trap. A fixture starts at function scope, gets promoted to session scope during a performance sprint to cut setup time, and nobody audits which scenarios now share mutable state through it. The promotion is a one-line change in Pytest or a single annotation in JUnit 5 — easy to make, hard to notice in review. The fix is a lint rule or a pre-commit hook that flags any fixture returning a mutable object at session or module scope.
AI agent tool-call caching is the newer trap. Teams running Claude or GPT-4o with tool use often enable response caching to reduce API costs. Cached tool responses are correct for idempotent reads but catastrophic for stateful actions — a cached "navigate to checkout" response may replay a stale page URL from a prior scenario. Disable caching for any tool that mutates state or returns a URL, session token, or timestamp. The org-level reason this happens is that cost optimisation and isolation correctness are owned by different teams who never talk.
What Most Teams Get Wrong About BDD + AI Context
The most persistent myth is that stateless Gherkin implies stateless execution. A scenario written with no explicit state dependencies ("Given I am on the homepage") looks stateless on paper. But if the browser context, the World object, or the AI agent's memory buffer carries state from a prior scenario, the execution is stateful regardless of what the Gherkin says. Isolation is an infrastructure property, not a scenario-authoring property. You cannot write your way out of a shared-state architecture.
The second misunderstanding is that AI-generated tests are inherently more isolated than hand-written ones because the LLM "doesn't know" what ran before. In practice, the opposite is true when agents are reused across scenarios: the model's context window is a shared-state surface that hand-written frameworks don't have at all. Teams that adopt AI test agents without auditing the agent lifecycle end up with a new class of context bleed that their existing flakiness dashboards in Grafana or Allure can't even categorise. Before wiring up an agent-driven suite, review how AI test agents lose scenario context across tool boundaries — the failure taxonomy there maps directly to what you'll instrument.
Context bleed is an architecture problem, not a test-authoring problem. Audit your fixture scopes, enforce per-scenario browser context creation, and treat AI agent memory as mutable shared state that requires explicit teardown. Once those boundaries are sealed, the next metric worth tracking is mean-time-to-detect on cross-scenario contamination — a custom tag on your flakiness dashboard that flags scenarios whose failure rate correlates with execution order is a good starting point.
Note: This article is for informational purposes only and is not a substitute for professional advice. If you need guidance on specific situations described in this article, consider consulting a qualified professional.