Fixture Teardown Races in Parallel Shards

GitHub Actions parallel testing with a matrix strategy is straightforward to configure and brutal to debug when it goes wrong. Shard A finishes its last scenario and starts tearing down a shared database schema at the exact moment Shard B is mid-assertion against a row that schema owns. The test fails. You re-run it. It passes. You ship. Two weeks later, a customer hits the race in production because your test suite was lying to you.

Fixture teardown races are distinct from ordinary shared-state flakiness. They're timing-dependent collisions between cleanup logic running in one process and active assertions running in another — often across different machines, containers, or GitHub Actions runner instances. The window is narrow, which is why the failure rate is low enough to dismiss as noise but high enough to erode confidence over months.

By the end of this article you'll be able to identify the structural conditions that produce these races, instrument your fixture lifecycle to expose them, and apply shard-aware teardown patterns that eliminate the collision window in Pytest, Behave, and Cucumber-JVM 7 pipelines.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

What a Teardown Race Actually Looks Like at the Shard Boundary

A teardown race is a happens-before violation between fixture finalization in one shard and fixture consumption in another. In a typical matrix run, each shard owns a subset of scenarios but may reference shared infrastructure — a Postgres schema seeded by a session-scoped fixture, a Kafka topic created in a BeforeAll hook, a Redis keyspace populated by a Behave environment.py before-feature block. When shard counts increase past the point where each shard gets its own isolated resource, you get contention. The teardown in shard N-1 doesn't know shard N is still reading.

This is architecturally different from the inconsistent pass rates that come from scenarios sharing external state within a single process. Cross-shard races involve OS-level process boundaries, separate network connections, and no shared memory — which means no mutex, no lock, and no framework-level guard rails. The only signal is a flaky assertion that correlates weakly with shard count and run duration, which is exactly the kind of signal most teams attribute to environment noise and ignore.

Instrumenting and Isolating the Race in GitHub Actions Parallel Testing

Start by making the race visible. Add OpenTelemetry spans around your fixture setup and teardown so you can correlate timestamps across shards in Grafana. Without this, you're debugging from test names alone, which is insufficient when the failure window is under 200ms.

# conftest.py — Pytest with OpenTelemetry fixture tracing
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
import pytest

provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("fixture.lifecycle")

@pytest.fixture(scope="session")
def db_schema(request):
    shard_id = request.config.getoption("--shard-id", default="0")
    with tracer.start_as_current_span(f"fixture.setup.db_schema.shard-{shard_id}"):
        _create_schema(shard_id)
    yield
    with tracer.start_as_current_span(f"fixture.teardown.db_schema.shard-{shard_id}"):
        _drop_schema(shard_id)

The shard_id in every span attribute is the key: once you have it in your trace backend, you can filter for teardown spans that overlap with setup or assertion spans on a different shard ID. A Grafana trace comparison between two shards that collided will show the teardown span from shard 0 starting before the last assertion span on shard 1 completes. That's your race, timestamped and attributable.

The structural fix is shard-namespaced resources. Every shared resource — schema name, Kafka topic, Redis key prefix, S3 bucket prefix — gets the shard ID appended at creation time. Teardown then only ever touches the namespace it owns.

# GitHub Actions matrix config — passing shard ID into Pytest
jobs:
  test:
    strategy:
      matrix:
        shard: [0, 1, 2, 3]
    runs-on: ubuntu-22.04
    steps:
      - uses: actions/checkout@v4
      - name: Run shard
        run: |
          pytest tests/ \
            --shard-id=${{ matrix.shard }} \
            --num-shards=4 \
            -p no:randomly \
            --addopts="--otel-service-name=ci-shard-${{ matrix.shard }}"
        env:
          DB_SCHEMA_PREFIX: "test_shard_${{ matrix.shard }}"

With DB_SCHEMA_PREFIX injected as an environment variable, your fixture reads it at setup time and every SQL statement, migration, and teardown call operates on an isolated namespace. Shard 0 creates and drops test_shard_0; shard 3 never touches it. This pattern eliminated a class of intermittent failures on a 4-shard Behave pipeline where run time dropped from 18 minutes to 4 — the original 18 minutes included retry overhead from flaky teardown collisions. The same namespace-isolation principle applies when teardown order silently corrupts shared state within a single runner, but the cross-shard variant requires the environment variable injection layer since there's no shared fixture graph to enforce ordering across processes.

Handling Session-Scoped Fixtures in Cucumber-JVM 7

Cucumber-JVM 7 doesn't have a native session scope, so teams typically use a JUnit 5 extension or a static initializer for expensive shared setup. Static state is the worst possible choice in a sharded run because the JVM teardown hook (@AfterAll on a static field) fires per-JVM — and if your CI system runs multiple JVMs on the same host with shared external state, you get the same race. Use a BeforeAllCallback / AfterAllCallback extension that reads a shard ID from a system property and namespaces its external resource identically to the Pytest pattern above.

Where Senior Engineers Still Get This Wrong

Relying on test framework ordering guarantees across process boundaries. Pytest's fixture finalization order is well-defined within a single process. It means nothing once you're in a matrix job. Engineers who understand Pytest's scope hierarchy deeply sometimes assume that a session-scoped fixture teardown will complete before any other process touches the resource. It won't — there is no cross-process coordination unless you build it. The fix is namespacing, not ordering.

Using shared fixture state in AI-assisted test generation without auditing scope. Tools like Cursor and GitHub Copilot generate fixture references that look structurally correct but inherit scope assumptions from the surrounding code context. A generated conftest.py will happily emit a session-scoped database fixture that's identical to an existing one — and if your shard count later increases past the isolation boundary, you now have two fixtures competing for the same external resource. This is a specific instance of the broader problem where fixture scope mismatches corrupt parallel scenario state; the AI-generated path just makes it harder to catch in review because the code looks intentional.

Myths About Parallel Shard Isolation That Cost Teams Weeks

"Docker Compose gives us isolation." It gives you network namespace isolation and process isolation. It does not give you data isolation unless your fixture explicitly creates separate schemas, topics, or keyspaces per shard. Two containers connecting to the same Postgres instance with the same credentials and the same schema name are not isolated — they're sharing state with extra latency. The container boundary is irrelevant to the teardown race; the resource namespace is what matters. Teams that spin up one Docker Compose stack per matrix shard and still share a single Postgres service are solving the wrong problem.

"Flaky tests at low rates are acceptable noise." A 2% flake rate across 500 scenarios is 10 failures per run. At 20 runs per day, that's 200 false signals your team learns to ignore. The cost isn't the reruns — it's the desensitization. When a real regression produces a 3% failure rate, nobody investigates. Teardown races are particularly insidious here because they're not random; they correlate with shard count, infrastructure load, and test suite growth. As your suite scales, the race window widens and the flake rate climbs. Treating it as noise means you're building a test suite that becomes less reliable as it grows — the opposite of what parallelism is supposed to deliver.

If you apply shard-namespaced resources and OpenTelemetry fixture tracing, the next metric worth instrumenting is mean-time-to-detect on teardown-related failures — specifically, how long between a race occurring and a developer investigating it rather than re-running. That gap is where the real cost lives. For teams running AI-assisted test generation at scale, also audit how generated fixtures handle tool handoffs; the same race conditions appear in a different form when AI test agents mishandle fixture state during tool handoffs.

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