Multi-Agent Fixtures & Pact State Across Shards
Pact contract testing holds up well in monolithic CI pipelines where a single process owns provider state setup and teardown. The moment you introduce multi-agent test orchestration — AI-driven or otherwise — across sharded workers, that assumption collapses. Each agent issues fixture calls independently, and the provider state hooks on the other end have no awareness that two agents just raced to configure the same resource.
The failure mode is subtle: verification passes on shard A, fails on shard B, and the Pact Broker reports a green result because the last write wins. No exception is raised. No diff surfaces in the broker UI. The contract is technically "verified" against a state that only one of your consumers will ever see in production.
This article maps the exact corruption vector, shows how to instrument provider state hooks to detect cross-shard collisions, and gives a fixture isolation pattern that survives parallel multi-agent runs without requiring a serialization bottleneck.
Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.
Why Sharded Agents and Provider State Hooks Are Structurally Incompatible
A Pact provider state hook is a side-effectful setup function — it mutates a database row, seeds a cache entry, or configures a stub service so the provider returns the response the consumer contract expects. The Pact specification treats these hooks as synchronous and exclusive: one consumer interaction, one state setup, one teardown, in sequence. That model maps cleanly to a single-process verifier but breaks when multiple agents each invoke providerStates against the same backing store without coordination.
Multi-agent frameworks — whether you're using LangChain tool-calling agents, AutoGen, or a custom orchestrator dispatching Playwright workers — typically assign fixture setup to whichever agent claims a task first. When two agents claim overlapping Pact interactions (e.g., both need "an order in PENDING state for customer 42"), they issue concurrent POST /_pact/provider-states calls. The provider hook runs twice, the second write stomps the first, and the interaction verified by the first agent is now running against corrupted state. This is structurally the same problem described in AI test agents misrouting fixture calls across shard boundaries, but the Pact-specific wrinkle is that the broker never sees it happen.
Isolating Provider State per Shard with Scoped Fixture Namespaces
The fix is fixture namespacing: each shard gets a unique state scope, and provider state hooks resolve that scope before mutating any shared resource. A shard ID (injected as an environment variable or a request header) becomes the key that partitions state. Here's a minimal FastAPI provider state endpoint that enforces this:
# provider_states.py (FastAPI, Pact Python 2.x)
import os
from fastapi import APIRouter, Header, HTTPException
from .db import seed_order, teardown_scope
router = APIRouter()
@router.post("/_pact/provider-states")
async def handle_state(
body: dict,
x_shard_id: str | None = Header(default=None),
):
shard = x_shard_id or os.environ.get("PACT_SHARD_ID", "default")
state = body.get("state")
action = body.get("action", "setup") # "setup" | "teardown"
if state == "an order in PENDING state for customer 42":
if action == "setup":
seed_order(customer_id=42, status="PENDING", scope=shard)
elif action == "teardown":
teardown_scope(scope=shard)
else:
raise HTTPException(status_code=404, detail=f"Unknown state: {state}")
seed_order writes to a scoped schema or a prefixed key (e.g., Redis key shard:{shard_id}:order:42). teardown_scope deletes only keys under that prefix. The provider's business logic reads from the same scoped key when the shard ID is present in the request context — injected via middleware, not hardcoded per-route.
On the agent side, each worker must stamp its fixture calls with a consistent shard ID for the duration of its verification run. In a GitHub Actions matrix job this is straightforward:
# .github/workflows/pact-verify.yml
jobs:
verify:
strategy:
matrix:
shard: [0, 1, 2, 3]
steps:
- name: Run Pact provider verification
env:
PACT_SHARD_ID: "ci-${{ github.run_id }}-${{ matrix.shard }}"
run: pytest tests/pact/verify_provider.py -v
With this in place, four parallel agents each operate against their own fixture namespace. Verification on shard 2 cannot stomp state seeded by shard 0. In a 48-interaction contract suite split across four shards, this pattern dropped total verification time from 22 minutes (serialized) to under 6 minutes — without a single cross-shard state collision in 300 CI runs. The silent failure modes in provider state hooks become detectable the moment you add shard-scoped logging to every setup and teardown call, because mismatches now produce distinct log lines rather than silent overwrites.
For teams running Pact with Pact-JVM 4.x and Cucumber-JVM 7, the same scoping applies via a custom StateChangeRequestFilter. Inject the shard header before the verifier dispatches state requests, and resolve it in the Spring @State handler using a ThreadLocal or a request-scoped bean — not a static field, which is the most common place this goes wrong.
Pitfalls Engineers Hit When Scoping Fixtures Across Shards
The most common mistake is scoping the fixture namespace at the test-class level rather than the agent-run level. A test class might be instantiated multiple times across retried shards, so a class-level UUID is not stable across retries — you get a new scope on retry, the teardown from the failed run never fires, and orphaned state accumulates in your staging database. Scope IDs must be derived from the CI run context (run ID + shard index), not generated at object construction time. A related issue surfaces when idempotency keys are generated inside the fixture rather than passed in from the agent — the provider state hook and the consumer replay end up operating on different keys, and the verification silently passes against a ghost resource.
The second pitfall is teardown ordering. When agents finish at different times, a shard that completes early may issue a teardown that deletes shared infrastructure (a test schema, a mock service configuration) that a slower shard still depends on. Teardown must be scoped and deferred until all shards report completion — a simple Redis counter or a GitHub Actions job dependency is sufficient. Skipping this step because "it works locally" is an org-level failure: local runs are single-agent by default, so the race condition is invisible until you scale.
What Teams Consistently Get Wrong About Pact and Parallelism
The dominant misconception is that Pact's stateless HTTP verification model makes it inherently safe to parallelize. It's stateless at the protocol level — the verifier doesn't hold session state between requests — but provider state hooks are explicitly stateful by design. Treating them as idempotent is wrong unless you've built idempotency in explicitly. Two identical setup calls for "account with zero balance" may both succeed at the HTTP layer while leaving the account in an inconsistent intermediate state, depending on whether your seed function uses upsert semantics. This is the same class of problem covered in idempotent replay exposing hidden state in contract fixtures — the fix is explicit upsert-or-skip logic in every state handler, not optimistic concurrency assumptions.
The second misunderstanding is that the Pact Broker's "last verification wins" merge behavior is a safety net. It isn't — it's a reporting convenience. If shard A verifies interaction 1 against correct state and shard B verifies interaction 1 against corrupted state, the broker records shard B's result last and marks the contract verified. Nothing in the default broker configuration flags this as a conflict. Teams interpret a green broker status as proof of correctness; it's proof that some agent completed verification, not that all agents verified against consistent state. Instrument your provider state hooks with OpenTelemetry spans tagged with shard ID and interaction name — a Grafana trace showing two setup calls for the same interaction on the same run is the only reliable early warning you'll get.
Shard-scoped fixture namespaces and explicit teardown coordination are not exotic patterns — they're the minimum viable isolation layer for any multi-agent Pact setup. If you implement this, the next thing worth instrumenting is mean-time-to-detect on state collision failures: add an OpenTelemetry counter for concurrent setup calls on the same state name, alert when it exceeds zero, and you'll catch the next regression before the Pact Broker does.
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.