Skip to main content
Back to Blog
Automation TutorialsCI and Test Infrastructure · Part 2

Eliminate CI Test Data Collisions Across Jobs, Shards and Re-runs

Playwright's workerIndex, xdist's gw0 and JEST_WORKER_ID restart in every CI job, so matrix legs sharing a database collide. Build namespaces from run ID, attempt, job and worker, stay under PostgreSQL's 63-byte limit, claim each with an advisory lock, and sweep leaks.

Shashank Rawlani

Engineering Leader | Builder | Problem Solver | AI Engineer

Published Nov 14, 202619 min read
View AI-ready Markdown
Three identical panels on the left each hold a stack of green worker pills. Dashed orange paths rise from all three, run in parallel across the top and converge on a single orange slot at the top right and end at a crossed-out circle. Below, a solid green flow leaves each panel, passes through a row of five joined pills whose fourth segment has a different length in every lane, and arrives in its own dashed compartment of one large panel on the right, where each compartment carries a ringed node.
Quick answer: The per-worker IDs that test runners hand you are unique only inside one process tree. Playwright's workerIndex, pytest-xdist's gw0 and JEST_WORKER_ID all restart in every CI job, so three matrix jobs pointed at one database produce three "worker 0"s. Build each namespace from the repository, run, attempt, job and matrix index first, and the worker last. Keep it under PostgreSQL's 63-byte identifier limit, register it in a claim table so a duplicate fails at setup, and hold a session advisory lock as proof that its owner is alive. Clean up in a step that runs even after cancellation, and sweep whatever that step misses by checking the lock and the claim's age.

The suite is green on every branch until two pull requests run at the same time. Then the checkout job on one of them fails with a duplicate key on users_email_key, and its re-run passes. A week later a search test asserts five results and gets seven, because another job's fixtures landed in the same tenant during the four seconds between seeding and querying.

Both tests followed the documented advice. Playwright's fixtures guide generates unique accounts from workerInfo.workerIndex, and pytest-xdist's documentation shows a user_account fixture returning "account_%s" % worker_id. That advice is correct for what it covers: workers inside one runner process. A CI matrix starts a new runner process per job, and every one of them counts its workers from the same starting value.

The fix lives one layer above the test runner, where jobs, shards and re-runs meet a resource none of them owns. The examples use GitHub Actions; GitLab differs in one useful way, noted below.

Versions checked on 2026-11-09: Playwright Test 1.65.0, Jest 30.5.2, pytest-xdist 3.8.0, psycopg 3.3.8, PostgreSQL 18 documentation, actions/checkout v7.0.1. The GitHub Actions behaviour cited here comes from the variables, contexts, expressions and workflow cancellation references read on the same date.

Which resources outlive a single job

Namespacing costs setup time and code, so spend it only where two owners can actually meet. A service container is the case where they cannot. GitHub's documentation says it "creates a fresh Docker container for each service configured in the workflow, and destroys the service container when the job completes." A PostgreSQL declared under services: is therefore private to its job. Inside that job you still have to separate workers, which the pytest-xdist worker isolation guide covers, but no other job can reach it.

Everything outside the job is shared: a staging database, a deployed application and its tenants, a SaaS sandbox account, an email inbox, a bucket, a broker. They are shared between matrix legs, between overlapping runs on different branches, and between attempts of one run. List them first; a resource that is not on the list needs no namespace.

Every counter restarts somewhere

Each identifier available to a test is unique at exactly one level. The bug in the opening is a namespace built from an identifier one level too low.

IdentifierUnique acrossWhere it repeats
github.repository_idRepositoriesEvery run of the same repository; it is a numeric ID, distinct from the owner/name string
GITHUB_RUN_IDWorkflow runs "within a repository"Another repository's runs; it "does not change if you re-run the workflow run"
GITHUB_RUN_ATTEMPTAttempts of one runStarts at 1 for every run
GITHUB_JOB and strategy.job-indexJobs in one runEvery run; the index is zero-based and only distinguishes matrix legs of the same job
TEST_PARALLEL_INDEX, PYTEST_XDIST_WORKER, JEST_WORKER_IDWorkers in one runner processEvery job and shard; Jest's starts at 1, the others at 0

Two rows deserve a second look. The run ID survives a re-run, so a namespace built from it alone hands attempt 2 the same tenant, schema and inbox that attempt 1 left behind, including whatever its failed teardown did not delete. And strategy.job-index is 0 for any job that is not a matrix, so an api job and an e2e job in the same run share index 0 unless the job ID is part of the name.

GitLab removes most of this table. Its CI_JOB_ID is documented as "unique across all jobs in the GitLab instance", so one value replaces the run, attempt and job columns, and only the worker needs adding. On GitHub you compose five values because no single one covers the job level.

Compose the name from the top down

Pass the CI identifiers into the test process as environment variables at job level, where the strategy context is available. The worked example runs three pytest suites as matrix legs, each with four xdist workers, against one shared PostgreSQL.

jobs:
  integration:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        suite: [api, checkout, search]
    env:
      NS_REPO: ${{ github.repository_id }}
      NS_RUN: ${{ github.run_id }}
      NS_ATTEMPT: ${{ github.run_attempt }}
      NS_JOB: ${{ github.job }}
      NS_INDEX: ${{ strategy.job-index }}
      TEST_DATABASE_URL: ${{ secrets.SHARED_TEST_DATABASE_URL }}
    steps:
      - uses: actions/checkout@v7
      - run: pip install -r requirements-test.txt
      - run: pytest tests/${{ matrix.suite }} -n 4
      - name: Release this job's namespaces
        if: ${{ always() }}
        timeout-minutes: 3
        run: python -m ci.sweep --own-job

The obvious way to join those values into a name produces something readable and subtly broken:

def naive_namespace(env):
    return "e2e_{repo}_{run}_{attempt}_{job}_{index}_{worker}".format(**env)

PostgreSQL "uses no more than NAMEDATALEN-1 bytes of an identifier; longer names can be written in commands, but they will be truncated", and the default leaves 63 bytes. Descriptive job IDs push the name past that, and truncation removes the end of the string, which is where the worker and matrix index sit. Running the naive version on Python 3.14 for matrix legs 0 and 1 of a job called checkout-chromium-logged-in-buyers, then cutting each name to 63 bytes:

66 e2e_812345678_18234567890_1_checkout-chromium-logged-in-buyers_0_0 -> e2e_812345678_18234567890_1_checkout-chromium-logged-in-buyers_
66 e2e_812345678_18234567890_1_checkout-chromium-logged-in-buyers_1_0 -> e2e_812345678_18234567890_1_checkout-chromium-logged-in-buyers_

Two jobs, one schema. If setup uses CREATE SCHEMA IF NOT EXISTS, nothing errors: the documented behaviour for an existing name is to "do nothing (except issuing a notice)", and a notice in a CI log is read by nobody. The version below hashes the one free-text component, puts a letter after every number, and refuses to return a name the database would shorten:

import hashlib
import os

MAX_IDENTIFIER_BYTES = 63


def job_prefix(env=os.environ):
    job = hashlib.sha256(env["NS_JOB"].encode()).hexdigest()[:6]
    return f"t{env['NS_REPO']}r{env['NS_RUN']}a{env['NS_ATTEMPT']}j{job}i{env['NS_INDEX']}w"


def worker_namespace(env=os.environ):
    worker = env.get("PYTEST_XDIST_WORKER", "gw0").removeprefix("gw")
    ns = job_prefix(env) + worker
    if len(ns.encode()) > MAX_IDENTIFIER_BYTES:
        raise ValueError(f"{ns!r} is {len(ns.encode())} bytes; PostgreSQL keeps 63")
    return ns

The same inputs now give t812345678r18234567890a1j9a30b1i0w0 and t812345678r18234567890a1j9a30b1i1w0, 35 bytes each. Only lowercase letters and digits appear, because unquoted identifiers "are always folded to lower case" and a sweeper that quotes differently from the creator will miss mixed-case names. No underscore appears, because in a LIKE pattern an underscore "stands for (matches) any single character". And each number is followed by a letter, so the prefix for matrix index 1, ending in i1w, cannot match index 10.

Playwright shards have the same shape. The fixtures guide's account example reads workerInfo.workerIndex, which starts at 0 in each shard's process, so it needs the CI prefix in front of it. Use parallelIndex for the last segment: the WorkerInfo reference guarantees "workers running at the same time have a different parallelIndex", and a restarted worker keeps it, which bounds the number of namespaces a run can create. The Playwright worker isolation guide covers the two indexes in depth.

import { createHash } from 'node:crypto';
import { test as base } from '@playwright/test';

const e = process.env;
const job = createHash('sha256').update(e.NS_JOB ?? '').digest('hex').slice(0, 6);
const jobPrefix = `t${e.NS_REPO}r${e.NS_RUN}a${e.NS_ATTEMPT}j${job}i${e.NS_INDEX}w`;

export const test = base.extend<{}, { ns: string }>({
  ns: [async ({}, use, workerInfo) => {
    await use(jobPrefix + workerInfo.parallelIndex);
  }, { scope: 'worker' }],
});

Claim the namespace before touching it

A careful name still depends on every job computing it the same way. Someone hard-codes NS_INDEX=0 in a reusable workflow, or a second repository shares the database without the repository segment. Neither produces an error; both produce the intermittent failures from the opening. A claim table turns that into a setup failure that names the other owner.

CREATE TABLE IF NOT EXISTS ci_claim (
  id         bigserial PRIMARY KEY,
  namespace  text NOT NULL UNIQUE,
  owner      text NOT NULL,
  claimed_at timestamptz NOT NULL DEFAULT now()
);

Create it once, in a migration or in a step before the matrix starts, not from every worker at once. Then each worker claims its name with INSERT ... ON CONFLICT DO NOTHING RETURNING id. The documentation says RETURNING computes values "based on each row actually inserted", so an empty result is an unambiguous signal that someone else holds the name.

The claim alone cannot tell a live holder from a dead one, and that is the second half of the design. The worker takes a session-level advisory lock keyed on the claim's ID inside the same INSERT, in its RETURNING list, so the lock exists before the new row becomes visible to anyone else. Taking it in a second statement would leave an instant in which a committed claim looks unowned and another worker could take it over. The worker then keeps that connection open for the whole session. PostgreSQL holds a session-level advisory lock "until explicitly released or the session ends", and the explicit-locking chapter adds that advisory locks are "automatically cleaned up by the server at the end of the session". So the lock is free exactly when its owner's connection is gone, and anyone can test that without waiting by calling pg_try_advisory_lock, which returns false "without waiting if the lock cannot be acquired immediately".

import psycopg
from psycopg import sql


def release_resources(conn, ns):
    conn.execute(sql.SQL("DROP SCHEMA IF EXISTS {} CASCADE").format(sql.Identifier(ns)))
    # Delete this namespace's objects, mail and tenants here too. Each delete must
    # treat "already gone" as success, because cleanup can run more than once.


def claim(conn, ns, owner):
    row = conn.execute(
        "INSERT INTO ci_claim (namespace, owner) VALUES (%s, %s) "
        "ON CONFLICT (namespace) DO NOTHING "
        "RETURNING id, pg_try_advisory_lock(id)",
        (ns, owner),
    ).fetchone()
    if row:
        assert row[1], "a brand-new claim id cannot already be locked"
        return row[0]

    found = conn.execute("SELECT id, owner FROM ci_claim WHERE namespace = %s", (ns,)).fetchone()
    if found is None:
        return claim(conn, ns, owner)
    claim_id, holder = found
    if not conn.execute("SELECT pg_try_advisory_lock(%s)", (claim_id,)).fetchone()[0]:
        raise RuntimeError(f"namespace {ns} is held by a live session: {holder}")
    release_resources(conn, ns)
    conn.execute("UPDATE ci_claim SET owner = %s, claimed_at = now() WHERE id = %s", (owner, claim_id))
    return claim_id

The takeover branch is what makes a reused parallelIndex safe: a replacement worker finds its predecessor's claim, sees the lock is free, deletes the leftovers and carries on. Two live workers with the same name still fail at once.

The session-scoped fixture ties it together. Under xdist it runs once per worker, and the connection opened here is the one holding the lock, so it must stay open until teardown. Point the code under test at the new schema through search_path, as the xdist guide linked above shows. Setting application_name to the namespace means pg_stat_activity shows which namespace each of these connections belongs to, and the value fits because it must be "less than NAMEDATALEN characters".

import os
import psycopg
import pytest
from psycopg import sql

from ci.claims import claim, release_resources
from ci.names import worker_namespace


@pytest.fixture(scope="session")
def namespace():
    ns = worker_namespace()
    e = os.environ
    owner = (f"{e['GITHUB_SERVER_URL']}/{e['GITHUB_REPOSITORY']}/actions/runs/{e['NS_RUN']} "
             f"attempt={e['NS_ATTEMPT']} job={e['NS_JOB']}[{e['NS_INDEX']}] ns={ns}")
    conn = psycopg.connect(e["TEST_DATABASE_URL"], autocommit=True, application_name=ns)
    claim(conn, ns, owner)
    conn.execute(sql.SQL("CREATE SCHEMA {}").format(sql.Identifier(ns)))
    yield ns
    release_resources(conn, ns)
    conn.execute("DELETE FROM ci_claim WHERE namespace = %s", (ns,))
    conn.close()

Teardown order is the invariant to protect: resources are deleted before the claim row, so a namespace's resources never outlive its claim. Every leak is then findable from the claim table alone. Note also the plain CREATE SCHEMA: if a schema with this name already exists without a claim, the invariant has been broken somewhere, and you want that error rather than a quiet reuse.

When the data lives behind a deployed app

A schema per namespace only works when the tests own the connection. End-to-end tests against a deployed staging application cannot choose the schema the application writes to, so the namespace has to travel inside the data instead. The claim table and the lock still work, because they live on a connection the test process opens to the side.

from dataclasses import dataclass


@dataclass(frozen=True)
class Owned:
    ns: str

    def tenant(self):
        return f"ci-{self.ns}"

    def email(self, role):
        return f"{self.ns}-{role}@mail.example.test"

    def object_key(self, name):
        return f"ci/{self.ns}/{name}"


def message_for(messages, recipient):
    matches = [m for m in messages if recipient in m["to"]]
    if len(matches) != 1:
        raise AssertionError(f"expected one message to {recipient}, got {len(matches)}")
    return matches[0]

The .test domain is reserved for testing by RFC 2606, and RFC 6761 tells caching DNS servers not to look such names up by default, so a misrouted password-reset email cannot land in a stranger's mailbox. Reading "the newest message" from a shared inbox is a collision by construction, whatever the recipient address; filtering on the exact recipient and asserting there is exactly one match turns a cross-job delivery into a named failure instead of a wrong token. The same rule applies to object storage and queues: the key prefix or a message attribute carries the namespace, consumers in tests filter on it, and release_resources deletes by it.

Cleanup that survives a cancelled run

Fixture teardown is the first line of cleanup and the least reliable one in CI. When a run is cancelled, the runner sends SIGINT to the step's process; "if the process doesn't exit within 7500 ms, the runner will send SIGTERM", waits another 2500 ms, then "kills the process tree". A suite that drops several schemas and calls a storage API may not finish inside ten seconds. Cancellation is also routine rather than rare: fail-fast "defaults to true", and when set GitHub "will cancel all in-progress and queued jobs in the matrix if any job in the matrix fails". One red leg interrupts the teardown of every sibling.

That is why the workflow above has a separate release step. always() "returns true, even when canceled", so the step runs after the test step has been killed. Give it a short timeout-minutes: the server forcibly terminates anything still running "after the 5 minute cancellation timeout period", and the documentation warns against always() on tasks that could hang the workflow.

import sys
import os
import psycopg

from ci.claims import release_resources
from ci.names import job_prefix


def sweep(conn, prefix, min_age):
    released, alive = [], []
    rows = conn.execute(
        "SELECT id, namespace FROM ci_claim "
        "WHERE namespace LIKE %s AND claimed_at < now() - %s::interval",
        (prefix + "%", min_age),
    ).fetchall()
    for claim_id, ns in rows:
        if not conn.execute("SELECT pg_try_advisory_lock(%s)", (claim_id,)).fetchone()[0]:
            alive.append(ns)
            continue
        release_resources(conn, ns)
        conn.execute("DELETE FROM ci_claim WHERE id = %s", (claim_id,))
        conn.execute("SELECT pg_advisory_unlock(%s)", (claim_id,))
        released.append(ns)
    return released, alive


if __name__ == "__main__":
    own_job = "--own-job" in sys.argv
    prefix, min_age = (job_prefix(), "0 seconds") if own_job else ("t", "7 hours")
    with psycopg.connect(os.environ["TEST_DATABASE_URL"], autocommit=True) as conn:
        released, alive = sweep(conn, prefix, min_age)
        left = conn.execute(
            "SELECT nspname FROM pg_namespace WHERE nspname LIKE %s", (prefix + "%",)
        ).fetchall() if own_job else []
    print(f"released={released} still_locked={alive} unclaimed_schemas={left}")
    sys.exit(1 if alive or left else 0)

In --own-job mode it releases only this job's namespaces, ignores age, and fails the job if anything with its prefix survives. That exit code is the leak detector: a job that leaves data behind goes red where its owner will see it, instead of leaving a mystery for someone else's run.

A runner that disappears runs no further steps at all, so the same script also runs on a schedule with an empty-job prefix and an age floor. Seven hours is not arbitrary: a job's timeout-minutes defaults to 360, and anything older than that plus the cancellation window cannot belong to a running job unless you raised the timeout. There is a gap the lock alone does not cover. A vanished machine does not close its socket, and PostgreSQL documents that without connection checks "the server will detect the loss of the connection only at the next interaction with the socket". An idle session holding a lock may linger until TCP keepalives expire it, which is governed by tcp_keepalives_idle and the operating system's defaults. When the scheduled sweep reports a namespace as still locked after seven hours, look it up in pg_stat_activity by application_name and terminate that session deliberately; do not teach the sweeper to ignore locks.

Evidence that two jobs never met

"No failures this week" is not evidence of isolation, because collisions need overlapping timing and most weeks do not provide it.

First, a negative control. It needs a test that holds its namespace long enough for two processes to overlap, otherwise the first can finish and release before the second claims, and the control passes for the wrong reason:

import time


def test_holds_namespace(namespace):
    time.sleep(10)
    assert namespace.startswith("t")

Start PostgreSQL bound to the loopback address only, so the lab is unreachable from the network, and run two simulated jobs against it at the same time:

docker run --rm -d --name ns-lab -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=lab postgres:18
export TEST_DATABASE_URL="postgresql://postgres:[email protected]:55432/postgres"
export NS_REPO=1 NS_RUN=100 NS_ATTEMPT=1 NS_JOB=integration GITHUB_SERVER_URL=http://127.0.0.1 GITHUB_REPOSITORY=lab/lab
until docker exec ns-lab pg_isready -U postgres -q; do sleep 1; done
psql "$TEST_DATABASE_URL" -f ci/claim_table.sql

NS_INDEX=0 pytest tests/lab &  NS_INDEX=1 pytest tests/lab &  wait
NS_INDEX=0 pytest tests/lab &  NS_INDEX=0 pytest tests/lab &  wait
docker rm -f ns-lab

The first pair must pass. The second pair is the deliberate mistake: whichever process claims second must error in setup with namespace ... is held by a live session and the first owner's details. If the second pair passes, the claim is not being checked, and the guarantee you think you have does not exist. Docker's documentation notes that before release 28.0.0, hosts on the same L2 segment could reach ports published to localhost, so check your Docker version before trusting the bind on a shared network.

Second, keep the release step's output line from every job. released=[] means teardown worked; any namespace listed there names a suite whose teardown did not. Third, count what the scheduled sweep reclaims per day. That is your leak rate, and a sudden rise usually means a new suite skipped the fixture.

What the scheme costs

The claim table is itself shared, and it is now a dependency of every test session: if it is missing or locked by a long migration, every job fails at setup. That is the right failure, but it is a new one. Each worker also holds one extra connection for its whole life, which matters against a database with a tight max_connections and many matrix legs. Sizing that is a capacity question for later in this series.

Some things cannot be namespaced at all: a sandbox account with one global settings page, a single webhook endpoint, an API rate limit shared by every caller. A unique name does nothing for them. Tests that change global state need to run one at a time, through a lock or a dedicated serial job, and the claim table can provide that lock if you claim a fixed name such as global-billing-settings instead of a derived one.

And if every resource on your list turns out to be a service container, you need none of this beyond worker isolation. Moving a test to a stage where it gets a private database, a choice the first part of this series is about, is cheaper than namespacing it.

Apply this now

Write down every resource your CI tests touch that is not created inside the job. For each one, find the code that names the data it creates, and check which row of the identifier table that name is built from. Any name built only from a worker index is a collision waiting for two overlapping runs.

Then add the claim table, the session lock and the always() release step to the one suite that shares the busiest resource, and run the negative control against a local database before merging. Capture three things as evidence: the error from the duplicate-claim run, the release line from the first ten CI jobs, and the scheduled sweep's count after its first week.

Questions about CI data isolation

Why not use a random UUID per worker instead?

A random name avoids collisions but cannot be reclaimed. Nothing can compute it after the process dies, so a sweeper cannot tell which job it belonged to, and a 36-character UUID uses most of the 63-byte budget on its own. A derived name can be recomputed by the release step from the same environment variables.

Does "re-run failed jobs" reuse the first attempt's data?

Only if the namespace omits the attempt. GITHUB_RUN_ID stays the same across re-runs and GITHUB_RUN_ATTEMPT increments, so including the attempt gives the re-run fresh namespaces while the scheduled sweep reclaims the first attempt's leftovers.

Can wrapping each test in a rolled-back transaction replace all this?

Only for tests that do all their work on that one connection. PostgreSQL treats Read Uncommitted as Read Committed, so no other session ever sees uncommitted rows, including the application server a browser test is driving. Rollback isolates tests that share a connection; namespaces isolate jobs that do not.

Two repositories share one staging database. Is the run ID enough?

No. The run ID is documented as unique only within a repository, so two repositories can produce the same value. Keep github.repository_id as the first segment. Prefer it to github.repository: it is purely numeric, while the owner/name string contains a slash and usually a hyphen, and would need hashing like the job ID.

How old must a claim be before the scheduled sweep may touch it?

Older than the longest job can run, plus the cancellation window. With the default 360-minute job timeout that is just over six hours; raise the floor if you have raised any job's timeout. The lock check is what protects live jobs. The floor keeps the scheduled sweep away from anything a running job could still own, and it marks the point after which a claim that is still locked is a stuck session to investigate.

Primary references

CI and Test Infrastructure

Get part 3: Debug CI-Only Test Failures with Environment Evidence

It is live now: read part 3. The form below subscribes you to The Automation Brief, the site newsletter.

No spam, no sending cadence promised. Unsubscribe any time.