Multi-Agent Fixtures Break When Retry State Is Shared

Multi-agent test harnesses have become the default pattern for teams running parallel BDD suites against microservices. The assumption is clean: each agent owns its fixture lifecycle, scenarios are isolated, and retries are a safety net. That assumption breaks the moment retry state lives in a shared store — a Redis key, a singleton fixture registry, an in-process Behave context object that gets pickled across workers. The failure mode is not a hard crash; it's a scenario that passes on the first run, fails on the second, and passes again on the third.

The root cause is a class of fixture misalignment that only surfaces under retry conditions. Agent A initializes a fixture, writes retry metadata to a shared key, and Agent B — running a different scenario — reads that key during its own setup phase. The fixture state diverges silently. Neither agent errors; both report green until a downstream assertion catches the mismatch, usually in a contract check or a stateful sequence test.

By the end of this article you will understand exactly how shared retry state propagates across agents, how to instrument and isolate it, and what architectural changes prevent re-contamination. The patterns apply whether your orchestration layer is Pytest-xdist, Cucumber-JVM 7's parallel runner, or a custom agent mesh.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

The Anatomy of Retry-State Contamination in Shared Fixtures

A retry-state contamination occurs when the bookkeeping data written by one agent's retry logic — attempt count, last-known fixture version, backoff timestamp — is readable and writable by a concurrent agent operating on a different scenario. This is distinct from ordinary shared-state flakiness. The fixture values themselves may be correct; it's the retry metadata that poisons the setup decision tree. Agent B reads a stale attempt count, decides the fixture is already warm, and skips initialization. The scenario proceeds against a fixture in an indeterminate state.

In a modern test architecture, fixtures sit between the BDD layer (Gherkin scenarios, step definitions) and the system under test (APIs, message brokers, databases). When that layer is distributed — agents running on separate Kubernetes pods, GitHub Actions matrix jobs, or Argo workflow nodes — fixture state must be scoped to the agent, not the run. Retry state is fixture state. Treating it as a run-level concern is the architectural mistake that causes the misalignment described here. This is a close cousin of the shared clock misalignment problem, where agents diverge on temporal assumptions rather than retry bookkeeping.

Isolating Retry State Per Agent: Instrumentation and Fix

The first step is making the contamination visible. Add a structured log line at every fixture setup entry point that records the agent ID, scenario ID, and the retry key being read. Without this, you are debugging flakiness by staring at assertion failures rather than fixture decisions.

# conftest.py — Pytest-xdist, Python 3.12
import os
import redis
import logging

log = logging.getLogger(__name__)
_redis = redis.Redis.from_url(os.environ["FIXTURE_STATE_URL"])

def _retry_key(scenario_id: str) -> str:
    # Scope key to worker process, not global run
    worker_id = os.environ.get("PYTEST_XDIST_WORKER", "master")
    return f"retry:{worker_id}:{scenario_id}"

def setup_fixture(scenario_id: str, factory_fn):
    key = _retry_key(scenario_id)
    attempt = int(_redis.get(key) or 0)
    log.info("fixture_setup", extra={
        "worker": os.environ.get("PYTEST_XDIST_WORKER"),
        "scenario": scenario_id,
        "attempt": attempt,
        "key": key,
    })
    fixture = factory_fn(attempt)
    _redis.incr(key)
    _redis.expire(key, 120)  # TTL prevents cross-run leakage
    return fixture

The critical change is the _retry_key function. Prefixing with PYTEST_XDIST_WORKER means worker gw0 and worker gw1 never read each other's attempt counters. The 120-second TTL is a belt-and-suspenders guard against keys surviving into the next pipeline run — a common source of ghost failures in long CI queues. After applying this pattern to a suite of 340 Behave scenarios running across 8 Argo workflow pods, flaky-retry failures dropped from 23 per run to 0 over a two-week observation window.

For teams using Cucumber-JVM 7 with its built-in parallel runner, the equivalent scoping happens at the @Before hook level. JVM thread ID is the reliable discriminator:

// Cucumber-JVM 7 — Java 17
@Before
public void setupFixture(Scenario scenario) {
    String workerKey = "retry:"
        + Thread.currentThread().getId()
        + ":" + scenario.getId();
    int attempt = retryStore.getOrDefault(workerKey, 0);
    currentFixture = fixtureFactory.build(attempt);
    retryStore.put(workerKey, attempt + 1);
}

One subtlety worth noting: if your agent mesh uses a message broker (Kafka, Pulsar) to distribute scenario work, the retry key must travel with the message, not be reconstructed from the consumer's local state. Reconstructed keys collide when two consumers process scenarios with the same hash prefix. Embed the full agent UUID in the message envelope and use it verbatim as the key namespace. This also makes replay safe — a concern covered in depth when examining how idempotent replay exposes hidden state in contract fixtures.

Gherkin-Level Visibility

Fixture misalignment is easier to catch early if your Gherkin scenarios carry enough context for the step definitions to assert fixture ownership. A @agent-scoped tag combined with a background step that verifies the fixture key namespace gives you a fast-fail before any scenario logic runs:

@agent-scoped
Feature: Payment retry idempotency

  Background:
    Given the fixture namespace matches the current agent ID

  Scenario: Duplicate charge is rejected on second attempt
    Given a payment fixture initialized for agent "gw2"
    When the charge endpoint receives the same idempotency key twice
    Then only one charge record exists in the ledger

The background step is a single Redis GET that fails loudly if the namespace is wrong. It costs ~2 ms and saves 4–8 minutes of debugging a downstream assertion failure.

Where Senior Engineers Still Get Burned

The most common mistake is treating the fixture registry as a run-level singleton because that is how it was designed for sequential execution. When parallelism was added incrementally — first 2 workers, then 8, then a full agent mesh — nobody refactored the registry. The singleton persists, retry keys collide, and the team spends cycles tuning retry counts rather than fixing the architecture. The tell is a flakiness rate that scales linearly with worker count. If doubling workers doubles flaky failures, shared mutable state is the cause.

A subtler mistake is relying on scenario ID alone as the retry key discriminator. Scenario IDs are not globally unique across shards when generated from file path plus line number — two agents running the same feature file on different shards produce identical IDs. This is the same class of problem that corrupts Pact provider state across shards. The fix is always to compose the key from agent identity plus scenario identity, never scenario identity alone. Use a UUID assigned at agent startup, not a derived value.

Myths That Keep the Bug Alive

Myth 1: Retries are a test-runner concern, not a fixture concern. Most teams configure retries in their CI YAML (retry: 2 in a GitHub Actions step or --reruns 3 in Pytest) and assume the fixture layer is stateless between attempts. It is not, unless you explicitly make it so. The fixture factory runs again on retry, but if it reads shared state to decide what to build, the retry is not a clean slate. Retries are a fixture lifecycle event and must be treated as one.

Myth 2: Redis TTLs are sufficient isolation. TTLs prevent cross-run leakage but do nothing for within-run collisions between concurrent agents. A 60-second TTL on a key that two agents write simultaneously within the same pipeline run still produces a race condition. TTLs are a cleanup mechanism, not an isolation mechanism. Myth 3: AI-generated step definitions handle state scoping automatically. LLM-assisted step generation (Cursor, GitHub Copilot, Claude) produces syntactically correct steps that often treat shared context objects as safe fixture carriers — because the training data is dominated by sequential test examples. Always audit generated steps for implicit shared-state assumptions before committing them to a parallel suite.

Shared retry state is a fixture architecture problem, not a flakiness tuning problem. Once you scope retry keys to agent identity and enforce that at both the store layer and the Gherkin background step, the failure mode disappears structurally rather than statistically. The next measurement worth making is mean-time-to-detect on fixture misalignment specifically — instrument your setup hooks with OpenTelemetry spans and alert on attempt-count anomalies before they reach assertion failures.

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.

Understanding how systems actually work is the first step toward navigating them effectively.

Browse all articles