{"title":"Eliminate CI Test Data Collisions Across Jobs, Shards and Re-runs","excerpt":"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.","canonicalUrl":"https://automationtester.in/blog/automation-tutorials/eliminate-ci-test-data-collisions","category":{"name":"Automation Tutorials","slug":"automation-tutorials"},"tags":["ci-cd","github-actions","test-data","parallel-testing","postgresql","test-isolation"],"author":{"name":"Shashank Rawlani","url":"https://shashank.rawlani.com","linkedin":"https://www.linkedin.com/in/shashankrawlani/"},"datePublished":"2026-11-14T13:30:00.000Z","dateModified":"2026-11-14T13:30:00.000Z","coverImage":{"url":"https://ik.imagekit.io/automationtester/automationtester-in/blog/covers/v3/eliminate-ci-test-data-collisions.webp","alt":"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."},"contentHtml":"<div class=\"callout callout-info\"><strong>Quick answer:</strong> The per-worker IDs that test runners hand you are unique only inside one process tree. Playwright's <code class=\"language-text\">workerIndex</code>, pytest-xdist's <code class=\"language-text\">gw0</code> and <code class=\"language-text\">JEST_WORKER_ID</code> 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.</div>\n\n<p>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 <code class=\"language-text\">users_email_key</code>, 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.</p>\n\n<p>Both tests followed the documented advice. Playwright's fixtures guide generates unique accounts from <code class=\"language-text\">workerInfo.workerIndex</code>, and pytest-xdist's documentation shows a <code class=\"language-text\">user_account</code> fixture returning <code class=\"language-text\">\"account_%s\" % worker_id</code>. 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.</p>\n\n<p>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.</p>\n\n<div class=\"callout callout-warning\"><strong>Versions checked on 2026-11-09:</strong> Playwright Test 1.65.0, Jest 30.5.2, pytest-xdist 3.8.0, psycopg 3.3.8, PostgreSQL 18 documentation, <code class=\"language-text\">actions/checkout</code> v7.0.1. The GitHub Actions behaviour cited here comes from the variables, contexts, expressions and workflow cancellation references read on the same date.</div>\n\n<h2 id=\"which-resources-outlive-a-single-job\">Which resources outlive a single job</h2>\n\n<p>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 <code class=\"language-text\">services:</code> is therefore private to its job. Inside that job you still have to separate workers, which the <a href=\"/blog/automation-tutorials/pytest-parallel-workers-shared-state-isolation\">pytest-xdist worker isolation guide</a> covers, but no other job can reach it.</p>\n\n<p>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.</p>\n\n<h2 id=\"every-counter-restarts-somewhere\">Every counter restarts somewhere</h2>\n\n<p>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.</p>\n\n<table>\n<thead>\n<tr><th>Identifier</th><th>Unique across</th><th>Where it repeats</th></tr>\n</thead>\n<tbody>\n<tr><td><code class=\"language-text\">github.repository_id</code></td><td>Repositories</td><td>Every run of the same repository; it is a numeric ID, distinct from the owner/name string</td></tr>\n<tr><td><code class=\"language-text\">GITHUB_RUN_ID</code></td><td>Workflow runs \"within a repository\"</td><td>Another repository's runs; it \"does not change if you re-run the workflow run\"</td></tr>\n<tr><td><code class=\"language-text\">GITHUB_RUN_ATTEMPT</code></td><td>Attempts of one run</td><td>Starts at 1 for every run</td></tr>\n<tr><td><code class=\"language-text\">GITHUB_JOB</code> and <code class=\"language-text\">strategy.job-index</code></td><td>Jobs in one run</td><td>Every run; the index is zero-based and only distinguishes matrix legs of the same job</td></tr>\n<tr><td><code class=\"language-text\">TEST_PARALLEL_INDEX</code>, <code class=\"language-text\">PYTEST_XDIST_WORKER</code>, <code class=\"language-text\">JEST_WORKER_ID</code></td><td>Workers in one runner process</td><td>Every job and shard; Jest's starts at 1, the others at 0</td></tr>\n</tbody>\n</table>\n\n<p>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 <code class=\"language-text\">strategy.job-index</code> is <code class=\"language-text\">0</code> for any job that is not a matrix, so an <code class=\"language-text\">api</code> job and an <code class=\"language-text\">e2e</code> job in the same run share index 0 unless the job ID is part of the name.</p>\n\n<p>GitLab removes most of this table. Its <code class=\"language-text\">CI_JOB_ID</code> 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.</p>\n\n<h2 id=\"compose-the-name-from-the-top-down\">Compose the name from the top down</h2>\n\n<p>Pass the CI identifiers into the test process as environment variables at job level, where the <code class=\"language-text\">strategy</code> context is available. The worked example runs three pytest suites as matrix legs, each with four xdist workers, against one shared PostgreSQL.</p>\n\n<pre class=\"language-yaml\"><code class=\"language-yaml\">jobs:\n  integration:\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        suite: [api, checkout, search]\n    env:\n      NS_REPO: ${{ github.repository_id }}\n      NS_RUN: ${{ github.run_id }}\n      NS_ATTEMPT: ${{ github.run_attempt }}\n      NS_JOB: ${{ github.job }}\n      NS_INDEX: ${{ strategy.job-index }}\n      TEST_DATABASE_URL: ${{ secrets.SHARED_TEST_DATABASE_URL }}\n    steps:\n      - uses: actions/checkout@v7\n      - run: pip install -r requirements-test.txt\n      - run: pytest tests/${{ matrix.suite }} -n 4\n      - name: Release this job's namespaces\n        if: ${{ always() }}\n        timeout-minutes: 3\n        run: python -m ci.sweep --own-job</code></pre>\n\n<p>The obvious way to join those values into a name produces something readable and subtly broken:</p>\n\n<pre class=\"language-python\"><code class=\"language-python\">def naive_namespace(env):\n    return \"e2e_{repo}_{run}_{attempt}_{job}_{index}_{worker}\".format(**env)</code></pre>\n\n<p>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 <code class=\"language-text\">checkout-chromium-logged-in-buyers</code>, then cutting each name to 63 bytes:</p>\n\n<pre class=\"language-text\"><code class=\"language-text\">66 e2e_812345678_18234567890_1_checkout-chromium-logged-in-buyers_0_0 -&gt; e2e_812345678_18234567890_1_checkout-chromium-logged-in-buyers_\n66 e2e_812345678_18234567890_1_checkout-chromium-logged-in-buyers_1_0 -&gt; e2e_812345678_18234567890_1_checkout-chromium-logged-in-buyers_</code></pre>\n\n<p>Two jobs, one schema. If setup uses <code class=\"language-text\">CREATE SCHEMA IF NOT EXISTS</code>, 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:</p>\n\n<pre class=\"language-python\"><code class=\"language-python\">import hashlib\nimport os\n\nMAX_IDENTIFIER_BYTES = 63\n\n\ndef job_prefix(env=os.environ):\n    job = hashlib.sha256(env[\"NS_JOB\"].encode()).hexdigest()[:6]\n    return f\"t{env['NS_REPO']}r{env['NS_RUN']}a{env['NS_ATTEMPT']}j{job}i{env['NS_INDEX']}w\"\n\n\ndef worker_namespace(env=os.environ):\n    worker = env.get(\"PYTEST_XDIST_WORKER\", \"gw0\").removeprefix(\"gw\")\n    ns = job_prefix(env) + worker\n    if len(ns.encode()) &gt; MAX_IDENTIFIER_BYTES:\n        raise ValueError(f\"{ns!r} is {len(ns.encode())} bytes; PostgreSQL keeps 63\")\n    return ns</code></pre>\n\n<p>The same inputs now give <code class=\"language-text\">t812345678r18234567890a1j9a30b1i0w0</code> and <code class=\"language-text\">t812345678r18234567890a1j9a30b1i1w0</code>, 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 <code class=\"language-text\">LIKE</code> 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 <code class=\"language-text\">i1w</code>, cannot match index 10.</p>\n\n<p>Playwright shards have the same shape. The fixtures guide's account example reads <code class=\"language-text\">workerInfo.workerIndex</code>, which starts at 0 in each shard's process, so it needs the CI prefix in front of it. Use <code class=\"language-text\">parallelIndex</code> 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 <a href=\"/blog/automation-tutorials/playwright-fixtures-parallel-test-isolation\">Playwright worker isolation guide</a> covers the two indexes in depth.</p>\n\n<pre class=\"language-typescript\"><code class=\"language-typescript\">import { createHash } from 'node:crypto';\nimport { test as base } from '@playwright/test';\n\nconst e = process.env;\nconst job = createHash('sha256').update(e.NS_JOB ?? '').digest('hex').slice(0, 6);\nconst jobPrefix = `t${e.NS_REPO}r${e.NS_RUN}a${e.NS_ATTEMPT}j${job}i${e.NS_INDEX}w`;\n\nexport const test = base.extend&lt;{}, { ns: string }&gt;({\n  ns: [async ({}, use, workerInfo) =&gt; {\n    await use(jobPrefix + workerInfo.parallelIndex);\n  }, { scope: 'worker' }],\n});</code></pre>\n\n<h2 id=\"claim-the-namespace-before-touching-it\">Claim the namespace before touching it</h2>\n\n<p>A careful name still depends on every job computing it the same way. Someone hard-codes <code class=\"language-text\">NS_INDEX=0</code> 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.</p>\n\n<pre class=\"language-sql\"><code class=\"language-sql\">CREATE TABLE IF NOT EXISTS ci_claim (\n  id         bigserial PRIMARY KEY,\n  namespace  text NOT NULL UNIQUE,\n  owner      text NOT NULL,\n  claimed_at timestamptz NOT NULL DEFAULT now()\n);</code></pre>\n\n<p>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 <code class=\"language-text\">INSERT ... ON CONFLICT DO NOTHING RETURNING id</code>. The documentation says <code class=\"language-text\">RETURNING</code> computes values \"based on each row actually inserted\", so an empty result is an unambiguous signal that someone else holds the name.</p>\n\n<p>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 <code class=\"language-text\">INSERT</code>, in its <code class=\"language-text\">RETURNING</code> 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 <code class=\"language-text\">pg_try_advisory_lock</code>, which returns <code class=\"language-text\">false</code> \"without waiting if the lock cannot be acquired immediately\".</p>\n\n<pre class=\"language-python\"><code class=\"language-python\">import psycopg\nfrom psycopg import sql\n\n\ndef release_resources(conn, ns):\n    conn.execute(sql.SQL(\"DROP SCHEMA IF EXISTS {} CASCADE\").format(sql.Identifier(ns)))\n    # Delete this namespace's objects, mail and tenants here too. Each delete must\n    # treat \"already gone\" as success, because cleanup can run more than once.\n\n\ndef claim(conn, ns, owner):\n    row = conn.execute(\n        \"INSERT INTO ci_claim (namespace, owner) VALUES (%s, %s) \"\n        \"ON CONFLICT (namespace) DO NOTHING \"\n        \"RETURNING id, pg_try_advisory_lock(id)\",\n        (ns, owner),\n    ).fetchone()\n    if row:\n        assert row[1], \"a brand-new claim id cannot already be locked\"\n        return row[0]\n\n    found = conn.execute(\"SELECT id, owner FROM ci_claim WHERE namespace = %s\", (ns,)).fetchone()\n    if found is None:\n        return claim(conn, ns, owner)\n    claim_id, holder = found\n    if not conn.execute(\"SELECT pg_try_advisory_lock(%s)\", (claim_id,)).fetchone()[0]:\n        raise RuntimeError(f\"namespace {ns} is held by a live session: {holder}\")\n    release_resources(conn, ns)\n    conn.execute(\"UPDATE ci_claim SET owner = %s, claimed_at = now() WHERE id = %s\", (owner, claim_id))\n    return claim_id</code></pre>\n\n<p>The takeover branch is what makes a reused <code class=\"language-text\">parallelIndex</code> 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.</p>\n\n<p>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 <code class=\"language-text\">search_path</code>, as the xdist guide linked above shows. Setting <code class=\"language-text\">application_name</code> to the namespace means <code class=\"language-text\">pg_stat_activity</code> shows which namespace each of these connections belongs to, and the value fits because it must be \"less than NAMEDATALEN characters\".</p>\n\n<pre class=\"language-python\"><code class=\"language-python\">import os\nimport psycopg\nimport pytest\nfrom psycopg import sql\n\nfrom ci.claims import claim, release_resources\nfrom ci.names import worker_namespace\n\n\n@pytest.fixture(scope=\"session\")\ndef namespace():\n    ns = worker_namespace()\n    e = os.environ\n    owner = (f\"{e['GITHUB_SERVER_URL']}/{e['GITHUB_REPOSITORY']}/actions/runs/{e['NS_RUN']} \"\n             f\"attempt={e['NS_ATTEMPT']} job={e['NS_JOB']}[{e['NS_INDEX']}] ns={ns}\")\n    conn = psycopg.connect(e[\"TEST_DATABASE_URL\"], autocommit=True, application_name=ns)\n    claim(conn, ns, owner)\n    conn.execute(sql.SQL(\"CREATE SCHEMA {}\").format(sql.Identifier(ns)))\n    yield ns\n    release_resources(conn, ns)\n    conn.execute(\"DELETE FROM ci_claim WHERE namespace = %s\", (ns,))\n    conn.close()</code></pre>\n\n<p>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 <code class=\"language-text\">CREATE SCHEMA</code>: 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.</p>\n\n<h2 id=\"when-the-data-lives-behind-a-deployed-app\">When the data lives behind a deployed app</h2>\n\n<p>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.</p>\n\n<pre class=\"language-python\"><code class=\"language-python\">from dataclasses import dataclass\n\n\n@dataclass(frozen=True)\nclass Owned:\n    ns: str\n\n    def tenant(self):\n        return f\"ci-{self.ns}\"\n\n    def email(self, role):\n        return f\"{self.ns}-{role}@mail.example.test\"\n\n    def object_key(self, name):\n        return f\"ci/{self.ns}/{name}\"\n\n\ndef message_for(messages, recipient):\n    matches = [m for m in messages if recipient in m[\"to\"]]\n    if len(matches) != 1:\n        raise AssertionError(f\"expected one message to {recipient}, got {len(matches)}\")\n    return matches[0]</code></pre>\n\n<p>The <code class=\"language-text\">.test</code> 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 <code class=\"language-text\">release_resources</code> deletes by it.</p>\n\n<h2 id=\"cleanup-that-survives-a-cancelled-run\">Cleanup that survives a cancelled run</h2>\n\n<p>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: <code class=\"language-text\">fail-fast</code> \"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.</p>\n\n<p>That is why the workflow above has a separate release step. <code class=\"language-text\">always()</code> \"returns true, even when canceled\", so the step runs after the test step has been killed. Give it a short <code class=\"language-text\">timeout-minutes</code>: the server forcibly terminates anything still running \"after the 5 minute cancellation timeout period\", and the documentation warns against <code class=\"language-text\">always()</code> on tasks that could hang the workflow.</p>\n\n<pre class=\"language-python\"><code class=\"language-python\">import sys\nimport os\nimport psycopg\n\nfrom ci.claims import release_resources\nfrom ci.names import job_prefix\n\n\ndef sweep(conn, prefix, min_age):\n    released, alive = [], []\n    rows = conn.execute(\n        \"SELECT id, namespace FROM ci_claim \"\n        \"WHERE namespace LIKE %s AND claimed_at &lt; now() - %s::interval\",\n        (prefix + \"%\", min_age),\n    ).fetchall()\n    for claim_id, ns in rows:\n        if not conn.execute(\"SELECT pg_try_advisory_lock(%s)\", (claim_id,)).fetchone()[0]:\n            alive.append(ns)\n            continue\n        release_resources(conn, ns)\n        conn.execute(\"DELETE FROM ci_claim WHERE id = %s\", (claim_id,))\n        conn.execute(\"SELECT pg_advisory_unlock(%s)\", (claim_id,))\n        released.append(ns)\n    return released, alive\n\n\nif __name__ == \"__main__\":\n    own_job = \"--own-job\" in sys.argv\n    prefix, min_age = (job_prefix(), \"0 seconds\") if own_job else (\"t\", \"7 hours\")\n    with psycopg.connect(os.environ[\"TEST_DATABASE_URL\"], autocommit=True) as conn:\n        released, alive = sweep(conn, prefix, min_age)\n        left = conn.execute(\n            \"SELECT nspname FROM pg_namespace WHERE nspname LIKE %s\", (prefix + \"%\",)\n        ).fetchall() if own_job else []\n    print(f\"released={released} still_locked={alive} unclaimed_schemas={left}\")\n    sys.exit(1 if alive or left else 0)</code></pre>\n\n<p>In <code class=\"language-text\">--own-job</code> 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.</p>\n\n<p>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 <code class=\"language-text\">timeout-minutes</code> 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 <code class=\"language-text\">tcp_keepalives_idle</code> and the operating system's defaults. When the scheduled sweep reports a namespace as still locked after seven hours, look it up in <code class=\"language-text\">pg_stat_activity</code> by <code class=\"language-text\">application_name</code> and terminate that session deliberately; do not teach the sweeper to ignore locks.</p>\n\n<h2 id=\"evidence-that-two-jobs-never-met\">Evidence that two jobs never met</h2>\n\n<p>\"No failures this week\" is not evidence of isolation, because collisions need overlapping timing and most weeks do not provide it.</p>\n\n<p>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:</p>\n\n<pre class=\"language-python\"><code class=\"language-python\">import time\n\n\ndef test_holds_namespace(namespace):\n    time.sleep(10)\n    assert namespace.startswith(\"t\")</code></pre>\n\n<p>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:</p>\n\n<pre class=\"language-bash\"><code class=\"language-bash\">docker run --rm -d --name ns-lab -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=lab postgres:18\nexport TEST_DATABASE_URL=\"postgresql://postgres:lab@127.0.0.1:55432/postgres\"\nexport NS_REPO=1 NS_RUN=100 NS_ATTEMPT=1 NS_JOB=integration GITHUB_SERVER_URL=http://127.0.0.1 GITHUB_REPOSITORY=lab/lab\nuntil docker exec ns-lab pg_isready -U postgres -q; do sleep 1; done\npsql \"$TEST_DATABASE_URL\" -f ci/claim_table.sql\n\nNS_INDEX=0 pytest tests/lab &amp;  NS_INDEX=1 pytest tests/lab &amp;  wait\nNS_INDEX=0 pytest tests/lab &amp;  NS_INDEX=0 pytest tests/lab &amp;  wait\ndocker rm -f ns-lab</code></pre>\n\n<p>The first pair must pass. The second pair is the deliberate mistake: whichever process claims second must error in setup with <code class=\"language-text\">namespace ... is held by a live session</code> 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.</p>\n\n<p>Second, keep the release step's output line from every job. <code class=\"language-text\">released=[]</code> 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.</p>\n\n<h2 id=\"what-the-scheme-costs\">What the scheme costs</h2>\n\n<p>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 <code class=\"language-text\">max_connections</code> and many matrix legs. Sizing that is a capacity question for later in this series.</p>\n\n<p>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 <code class=\"language-text\">global-billing-settings</code> instead of a derived one.</p>\n\n<p>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 <a href=\"/blog/automation-tutorials/ci-test-pyramid-feedback-cost\">first part of this series</a> is about, is cheaper than namespacing it.</p>\n\n<h2 id=\"apply-this-now\">Apply this now</h2>\n\n<p>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.</p>\n\n<p>Then add the claim table, the session lock and the <code class=\"language-text\">always()</code> 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.</p>\n\n<h2 id=\"questions-about-ci-data-isolation\">Questions about CI data isolation</h2>\n\n<h3 id=\"why-not-a-random-uuid-per-worker\">Why not use a random UUID per worker instead?</h3>\n\n<p>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.</p>\n\n<h3 id=\"does-a-rerun-of-failed-jobs-get-new-data\">Does \"re-run failed jobs\" reuse the first attempt's data?</h3>\n\n<p>Only if the namespace omits the attempt. <code class=\"language-text\">GITHUB_RUN_ID</code> stays the same across re-runs and <code class=\"language-text\">GITHUB_RUN_ATTEMPT</code> increments, so including the attempt gives the re-run fresh namespaces while the scheduled sweep reclaims the first attempt's leftovers.</p>\n\n<h3 id=\"can-transactions-replace-namespaces\">Can wrapping each test in a rolled-back transaction replace all this?</h3>\n\n<p>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.</p>\n\n<h3 id=\"two-repositories-share-one-staging-database\">Two repositories share one staging database. Is the run ID enough?</h3>\n\n<p>No. The run ID is documented as unique only within a repository, so two repositories can produce the same value. Keep <code class=\"language-text\">github.repository_id</code> as the first segment. Prefer it to <code class=\"language-text\">github.repository</code>: it is purely numeric, while the owner/name string contains a slash and usually a hyphen, and would need hashing like the job ID.</p>\n\n<h3 id=\"how-long-should-claims-live-before-sweeping\">How old must a claim be before the scheduled sweep may touch it?</h3>\n\n<p>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.</p>\n\n<h2 id=\"primary-references\">Primary references</h2>\n\n<ul>\n<li><a href=\"https://docs.github.com/en/actions/reference/workflows-and-actions/variables\">GitHub Actions variables reference</a>. That <code class=\"language-text\">GITHUB_RUN_ID</code> is unique \"within a repository\" and \"does not change if you re-run the workflow run\", that <code class=\"language-text\">GITHUB_RUN_ATTEMPT</code> begins at 1 and increments with each re-run, that <code class=\"language-text\">GITHUB_JOB</code> is the job_id, and the run URL formed from <code class=\"language-text\">GITHUB_SERVER_URL</code>, <code class=\"language-text\">GITHUB_REPOSITORY</code> and the run ID.</li>\n<li><a href=\"https://docs.github.com/en/actions/reference/workflows-and-actions/contexts\">GitHub Actions contexts reference</a>. <code class=\"language-text\">strategy.job-index</code> as a zero-based matrix index, <code class=\"language-text\">github.repository_id</code> as distinct from the repository name, and the availability table showing <code class=\"language-text\">strategy</code> usable in <code class=\"language-text\">jobs.&lt;job_id&gt;.env</code>.</li>\n<li><a href=\"https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-cancellation\">GitHub Actions workflow cancellation reference</a>. The SIGINT, 7500 ms, SIGTERM, 2500 ms, process-tree kill sequence for cancelled steps, and the 5-minute timeout after which the server forcibly terminates jobs.</li>\n<li><a href=\"https://docs.github.com/en/actions/reference/workflows-and-actions/expressions\">GitHub Actions expressions reference</a>. That <code class=\"language-text\">always()</code> returns true even when the run is cancelled, and the warning against using it for tasks that could hang.</li>\n<li><a href=\"https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax\">Workflow syntax for GitHub Actions</a>. The <code class=\"language-text\">fail-fast</code> default of true and its cancellation of sibling matrix jobs, step-level <code class=\"language-text\">timeout-minutes</code>, and the 360-minute default job timeout.</li>\n<li><a href=\"https://docs.github.com/en/actions/tutorials/use-containerized-services/use-docker-service-containers\">About service containers in GitHub Actions</a>. That a fresh container is created per configured service and destroyed when the job completes, which is why a service database needs no cross-job namespace.</li>\n<li><a href=\"https://docs.gitlab.com/ci/variables/predefined_variables/\">GitLab CI/CD predefined variables</a>. That <code class=\"language-text\">CI_JOB_ID</code> is unique across all jobs in the GitLab instance, which collapses the run, attempt and job segments into one value.</li>\n<li><a href=\"https://pytest-xdist.readthedocs.io/en/stable/how-to.html\">pytest-xdist how-to guide</a>. The <code class=\"language-text\">worker_id</code> account example, the <code class=\"language-text\">PYTEST_XDIST_WORKER</code> value format such as <code class=\"language-text\">gw2</code>, and that the id is per session rather than per CI job.</li>\n<li><a href=\"https://playwright.dev/docs/test-parallel\">Playwright Test parallelism and worker indexes</a>. <code class=\"language-text\">TEST_WORKER_INDEX</code> and <code class=\"language-text\">TEST_PARALLEL_INDEX</code>, and that a restarted worker keeps its parallelIndex and gets a new workerIndex.</li>\n<li><a href=\"https://playwright.dev/docs/api/class-workerinfo\">Playwright WorkerInfo API</a>. The guarantee that concurrently running workers have different <code class=\"language-text\">parallelIndex</code> values between 0 and workers minus 1.</li>\n<li><a href=\"https://playwright.dev/docs/test-fixtures\">Playwright fixtures guide</a>. The worker-scoped account fixture built from <code class=\"language-text\">workerInfo.workerIndex</code> and the <code class=\"language-text\">{scope: 'worker'}</code> tuple syntax.</li>\n<li><a href=\"https://playwright.dev/docs/test-sharding\">Playwright sharding guide</a>. The <code class=\"language-text\">--shard=x/y</code> option and running each shard as a separate GitHub Actions matrix job.</li>\n<li><a href=\"https://jestjs.io/docs/environment-variables\">Jest environment variables</a>. That <code class=\"language-text\">JEST_WORKER_ID</code> is index-based and starts at 1, and is 1 for every test under runInBand.</li>\n<li><a href=\"https://www.postgresql.org/docs/current/sql-syntax-lexical.html\">PostgreSQL lexical structure</a>. The NAMEDATALEN-1 truncation rule with its 63-byte default, and lower-case folding of unquoted identifiers.</li>\n<li><a href=\"https://www.postgresql.org/docs/current/functions-matching.html\">PostgreSQL pattern matching</a>. That an underscore in a <code class=\"language-text\">LIKE</code> pattern matches any single character, the reason the namespace contains none.</li>\n<li><a href=\"https://www.postgresql.org/docs/current/sql-createschema.html\">PostgreSQL CREATE SCHEMA</a>. That <code class=\"language-text\">IF NOT EXISTS</code> does nothing except issue a notice when the schema already exists, which is how a truncated name collides silently.</li>\n<li><a href=\"https://www.postgresql.org/docs/current/sql-insert.html\">PostgreSQL INSERT</a>. <code class=\"language-text\">ON CONFLICT DO NOTHING</code> as an alternative to raising a unique violation, and <code class=\"language-text\">RETURNING</code> computed only for rows actually inserted.</li>\n<li><a href=\"https://www.postgresql.org/docs/current/explicit-locking.html\">PostgreSQL explicit locking: advisory locks</a>. Session-level advisory locks held until released or the session ends, and their automatic cleanup at session end.</li>\n<li><a href=\"https://www.postgresql.org/docs/current/functions-admin.html\">PostgreSQL system administration functions</a>. <code class=\"language-text\">pg_try_advisory_lock</code> returning false without waiting, and the transaction-level variants.</li>\n<li><a href=\"https://www.postgresql.org/docs/current/runtime-config-connection.html\">PostgreSQL connection settings</a>. That without connection checks the server detects a lost connection only at the next socket interaction, and the <code class=\"language-text\">tcp_keepalives_idle</code> setting.</li>\n<li><a href=\"https://www.postgresql.org/docs/current/runtime-config-logging.html\">PostgreSQL logging settings: application_name</a>. The length limit of less than NAMEDATALEN characters and its display in <code class=\"language-text\">pg_stat_activity</code>.</li>\n<li><a href=\"https://www.postgresql.org/docs/current/transaction-iso.html\">PostgreSQL transaction isolation</a>. That Read Uncommitted behaves like Read Committed, so uncommitted test data is never visible to another session.</li>\n<li><a href=\"https://www.psycopg.org/psycopg3/docs/api/connections.html\">psycopg 3 Connection class</a>. The <code class=\"language-text\">connect()</code> signature with <code class=\"language-text\">autocommit</code> and extra connection parameters as keyword arguments.</li>\n<li><a href=\"https://www.psycopg.org/psycopg3/docs/api/sql.html\">psycopg 3 sql module</a>. Why identifiers such as schema names must be composed with the <code class=\"language-text\">sql</code> module rather than passed as query parameters.</li>\n<li><a href=\"https://www.rfc-editor.org/rfc/rfc2606.html\">RFC 2606, Reserved Top Level DNS Names</a>. The reservation of <code class=\"language-text\">.test</code> for testing.</li>\n<li><a href=\"https://www.rfc-editor.org/rfc/rfc6761.html\">RFC 6761, Special-Use Domain Names</a>. That caching DNS servers should not, by default, look up names under <code class=\"language-text\">.test</code>.</li>\n<li><a href=\"https://docs.docker.com/engine/network/port-publishing/\">Docker port publishing</a>. Publishing to <code class=\"language-text\">127.0.0.1</code> only, and the warning that before 28.0.0 hosts on the same L2 segment could reach localhost-published ports.</li>\n</ul>\n"}