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

Debug CI-Only Test Failures with Environment Evidence

A date test passed in India and failed on ubuntu-latest because the code asked the host what day it was. Record a fingerprint on both machines, diff it, and replay each CI value locally until one flips the result. Covers time zone, locale, the CI variable, shallow clones, case sensitivity and CPU count.

Shashank Rawlani

Engineering Leader | Builder | Problem Solver | AI Engineer

Published Nov 15, 202617 min read
View AI-ready Markdown
Dark technical illustration: two tall side-by-side panels hold matching columns of green pills, one row per line, with most rows equal in length and a few rows visibly different. From each differing row a lane runs right through a dashed vertical gate. Three lanes continue as dashed green lines ending in small green dots, while one lane, starting from an orange pill in the second column, turns solid orange and ends at a ringed orange node near the right edge. Faint rules and grey pills extend across both edges.
Quick answer: A test that passes on your machine and fails in CI is reporting a difference between two machines. Before you edit the assertion, record the same fingerprint on both sides (runtime and data versions, time zone, locale, CPU count, the CI variable, clone depth, filesystem case sensitivity), diff the two, then replay the CI values locally one at a time. The difference that flips the result is the cause, and it usually lives in the code under test, not in the test.

The failure looks like this. On a laptop in India the suite is green. On ubuntu-latest the same commit fails with the output below, reproduced here on the laptop under the runner's time zone:

✖ an order at 01:30 IST counts toward that IST day (2.169458ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
  + actual - expected

  + '2026-11-15'
  - '2026-11-16'
              ^

The quickest way to a green build is to change '2026-11-16' to '2026-11-15'. That edit would ship a daily report that files every Indian order placed between midnight and 05:30 local time under the previous day. The expected value was correct. The code under test asked the host machine what day it was, and the two hosts gave different answers.

This part of the series is about finding that kind of difference with evidence instead of guesswork. The platform throughout is GitHub Actions on GitHub-hosted runners; self-hosted runners have whatever you installed on them, which makes the fingerprint below more useful, not less.

What a hosted runner changes before your first step runs

Several differences are fixed by the platform, and each one has broken real suites. All of these are documented, so you can check them rather than guess:

  • CPU and memory depend on repository visibility. A standard ubuntu-latest runner has 4 CPUs and 16 GB of RAM for a public repository, and 2 CPUs and 8 GB for a private one. macos-latest is a 3-core M1 with 7 GB in both cases. A laptop with ten cores runs several times more test workers than the private-repo runner.
  • The clock reads UTC. The macOS image build runs ln -sf /usr/share/zoneinfo/UTC /etc/localtime and the Windows build calls Set-TimeZone -Id "UTC". The Ubuntu build scripts contain no time zone step, so the base image decides; print it rather than assume it.
  • CI is always true. GitHub sets it on every job, and test runners read it to change behaviour.
  • The checkout holds one commit. actions/checkout fetches only the triggering commit by default (fetch-depth: 1), so tags and history are absent.
  • ubuntu-latest is moving. GitHub announced that the label moves from Ubuntu 24.04 to 26.04 in a rollout beginning 19 October 2026 and planned to finish by 19 November 2026. During that window, two runs of one commit can land on different operating systems. In the 20261101 image builds, the default node on PATH is 22.23.4 on 24.04 and 24.22.2 on 26.04; Python goes from 3.12.3 to 3.14.4, and OpenSSL from 3.0.13 to 3.5.5.
  • The image changes weekly even on a pinned label. The runner-images project typically deploys software updates every week. The exact image version for a run is printed in the Set up job step, and the Ubuntu images also export it as ImageVersion, alongside ImageOS.
Versions checked on 2026-11-09: Ubuntu 24.04 image 20261101.360.1 and Ubuntu 26.04 image 20261101.186.1 from the actions/runner-images READMEs; actions/checkout v7.0.1 and actions/setup-node v7.1.0 are the latest releases. The outputs below were produced with Node.js v26.12.1 on an arm64 Mac. The scripts also run on Node 22.

Record the same fingerprint on both machines

A fingerprint is a short JSON document of the facts that change test behaviour. The script has to run unchanged on a laptop and on a runner, so it uses only Node's standard library. It prints environment values only for an allowlist, and reports every other variable by name. GitHub redacts secret values it recognises in logs, but its own documentation says that redaction is not guaranteed once a value has been transformed, so a full env dump in a log is a leak waiting to happen.

// scripts/fingerprint.mjs
import { execFileSync } from "node:child_process";
import { existsSync, rmSync, writeFileSync } from "node:fs";
import { lookup } from "node:dns/promises";
import os from "node:os";

const SHOW_VALUES = [
  "CI", "TZ", "LANG", "LC_ALL", "LC_TIME", "NODE_OPTIONS", "NODE_ENV",
  "ImageOS", "ImageVersion", "RUNNER_OS", "RUNNER_ARCH", "RUNNER_ENVIRONMENT",
];
const PRESENCE_ONLY = ["HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "no_proxy"];

function caseSensitive(dir) {
  const probe = `${dir}/.Case-Probe-${process.pid}`;
  writeFileSync(probe, "");
  const sensitive = !existsSync(`${dir}/.case-probe-${process.pid}`);
  rmSync(probe);
  return sensitive;
}

function git(...args) {
  try {
    return execFileSync("git", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
  } catch {
    return null;
  }
}

const intl = Intl.DateTimeFormat().resolvedOptions();
const probeInstant = new Date("2026-11-15T20:00:00Z");

console.log(JSON.stringify({
  runtime: { node: process.version, icu: process.versions.icu, tzdata: process.versions.tz },
  host: {
    platform: process.platform,
    arch: process.arch,
    release: os.release(),
    parallelism: os.availableParallelism(),
    memoryGiB: Math.round(os.totalmem() / 2 ** 30),
  },
  intl: {
    timeZone: intl.timeZone,
    locale: intl.locale,
    offsetMinutes: -probeInstant.getTimezoneOffset(),
    sample: probeInstant.toLocaleString(),
  },
  fs: { caseSensitive: caseSensitive(process.cwd()) },
  git: {
    shallow: git("rev-parse", "--is-shallow-repository"),
    describe: git("describe", "--tags", "--always"),
  },
  network: {
    localhost: (await lookup("localhost", { all: true })).map((a) => a.address),
    proxies: PRESENCE_ONLY.filter((name) => name in process.env),
  },
  env: Object.fromEntries(SHOW_VALUES.map((name) => [name, process.env[name] ?? null])),
  envNames: Object.keys(process.env).sort(),
}, null, 2));

Two fields carry more weight than they look. intl.sample formats one fixed instant with the machine's defaults, so it captures the combined effect of zone, locale and ICU data in a single string you can compare by eye. runtime.tzdata is the version of the time zone rules bundled with Node, worth comparing whenever a failure involves a zone whose rules changed recently.

In the workflow, run it as a step before the tests. It then runs whether or not the tests later fail, so you do not need if: always(), and the fingerprint sits in the log of every run, green or red:

      - name: Environment fingerprint
        run: node scripts/fingerprint.mjs
      - name: Tests
        run: node --test

Keeping that output after the job ends, alongside traces and reports, is a retention question this series takes up separately. For diagnosis, copying the JSON from the log is enough.

Diff the two fingerprints before forming a theory

Reading two 40-line JSON blobs side by side is how a difference gets missed. Flatten them and print only what differs:

// scripts/diff-fingerprints.mjs local.json ci.json
import { readFileSync } from "node:fs";

const [a, b] = process.argv.slice(2).map((f) => JSON.parse(readFileSync(f, "utf8")));

function flatten(obj, prefix = "", out = {}) {
  for (const [key, value] of Object.entries(obj)) {
    const path = prefix ? `${prefix}.${key}` : key;
    if (value && typeof value === "object" && !Array.isArray(value)) flatten(value, path, out);
    else out[path] = JSON.stringify(value);
  }
  return out;
}

const { envNames: namesA, ...restA } = a;
const { envNames: namesB, ...restB } = b;
const fa = flatten(restA);
const fb = flatten(restB);

for (const key of [...new Set([...Object.keys(fa), ...Object.keys(fb)])].sort()) {
  if (fa[key] !== fb[key]) console.log(`${key.padEnd(22)} local=${fa[key]}  ci=${fb[key]}`);
}
const onlyCi = namesB.filter((n) => !namesA.includes(n));
console.log(`env only in ci (${onlyCi.length}): ${onlyCi.join(" ")}`);

To keep this example reproducible without a real runner, the CI side below was produced on the same laptop from a shallow local clone, with CI=true, TZ=Etc/UTC and LANG=C.UTF-8 injected. On a real run, you paste the JSON from the job log instead, and the host fields (platform, CPU count, memory, Node version) will differ too.

env.CI                 local=null  ci="true"
env.LANG               local="en_IN.UTF-8"  ci="C.UTF-8"
env.TZ                 local=null  ci="Etc/UTC"
git.describe           local="v1.4.0-1-gdf1792d"  ci="df1792d"
git.shallow            local="false"  ci="true"
intl.locale            local="en-IN"  ci="en-US"
intl.offsetMinutes     local=330  ci=0
intl.sample            local="16/11/2026, 1:30:00 AM"  ci="11/15/2026, 8:00:00 PM"
intl.timeZone          local="Asia/Calcutta"  ci="UTC"
env only in ci (2): CI TZ

Nine differences, and nothing yet says which of them matters. The intl.sample line already shows the shape of the bug: the same instant is the 16th on one machine and the 15th on the other. A theory still has to be tested, because the locale and CI differences are plausible culprits too.

Replay one difference at a time

The next script reads the CI fingerprint, picks the variables you can reproduce in a shell, and reruns the failing command once per difference, then once with all of them. It is a bisection over the environment instead of over commits:

// scripts/bisect-env.mjs ci.json -- <test command...>
import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";

const sep = process.argv.indexOf("--");
const ci = JSON.parse(readFileSync(process.argv[2], "utf8"));
const [cmd, ...args] = process.argv.slice(sep + 1);

const candidates = {
  TZ: ci.env.TZ ?? ci.intl.timeZone,
  LANG: ci.env.LANG,
  LC_ALL: ci.env.LC_ALL,
  CI: ci.env.CI,
  NODE_OPTIONS: ci.env.NODE_OPTIONS,
};
const diffs = Object.entries(candidates).filter(
  ([name, value]) => value != null && process.env[name] !== value,
);

function run(label, overrides) {
  const r = spawnSync(cmd, args, { env: { ...process.env, ...overrides }, stdio: "ignore" });
  console.log(`${r.status === 0 ? "pass" : "FAIL"}  ${label}`);
}

run("baseline (this shell)", {});
for (const [name, value] of diffs) run(`${name}=${value}`, { [name]: value });
run("all CI values together", Object.fromEntries(diffs));

Note the fallback on TZ: a runner usually has no TZ variable at all, because its zone comes from the system clock configuration. The fingerprint's resolved intl.timeZone is what you replay. Running node scripts/bisect-env.mjs ci.json -- node --test prints:

pass  baseline (this shell)
FAIL  TZ=Etc/UTC
pass  LANG=C.UTF-8
pass  CI=true
FAIL  all CI values together

The time zone alone reproduces it; the locale and CI do not. The "all together" line is the control: if it passed while CI still failed, the cause would be outside what a shell can replay, such as CPU count, the Node version or the clone depth, and you would move to the next section's checks.

One more sweep is worth the ten seconds. Here is the code under test, and the same two tests run under three zones:

// src/day-key.mjs (the version that fails in CI)
export function dayKey(input) {
  const d = new Date(input);
  const pad = (n) => String(n).padStart(2, "0");
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
}
TZ=Asia/Kolkata
  ✔ a date-only string keeps its own day
  ✔ an order at 01:30 IST counts toward that IST day
TZ=Etc/UTC
  ✔ a date-only string keeps its own day
  ✖ an order at 01:30 IST counts toward that IST day
TZ=America/Los_Angeles
  ✖ a date-only string keeps its own day
  ✖ an order at 01:30 IST counts toward that IST day

The second test, dayKey("2026-11-15"), passes in India and in UTC and fails in California, returning 2026-11-14. That follows from a rule in the ECMAScript specification that surprises people who have used Date for years: when a string has no UTC offset, date-only forms are interpreted as UTC and date-time forms as local time. "2026-11-15" is midnight UTC, which is still the 14th west of Greenwich, and getDate() reads it in local time. A contributor in California would have hit a different failure from the same function, and CI would never have shown it.

Remove the host from the answer, then prove it

The fix belongs in the code. A business day is defined in the business's zone, so name that zone instead of inheriting one from whichever machine runs the code:

// src/day-key.mjs (fixed)
const parts = new Intl.DateTimeFormat("en", {
  timeZone: "Asia/Kolkata",
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
});

export function dayKey(input) {
  if (/^\d{4}-\d{2}-\d{2}$/.test(input)) return input; // already a day
  const p = Object.fromEntries(
    parts.formatToParts(new Date(input)).map(({ type, value }) => [type, value]),
  );
  return `${p.year}-${p.month}-${p.day}`;
}

formatToParts is used instead of formatting with a locale whose pattern happens to look like YYYY-MM-DD, because that pattern comes from CLDR data, and the fingerprint already showed that locale data varies between machines.

The tempting alternative is "test": "TZ=UTC node --test" in package.json. That makes every machine agree, which feels like a fix, and it removes the only signal you had: production servers and users' browsers do not run with your test script's environment. Pin the zone if you must, but also run the suite under zones far from UTC in both directions so a host dependency cannot hide. Pacific/Kiritimati runs at UTC+14, so it catches the mistakes that UTC-8 misses:

jobs:
  test:
    runs-on: ubuntu-24.04
    strategy:
      fail-fast: false
      matrix:
        tz: [Etc/UTC, Asia/Kolkata, America/Los_Angeles, Pacific/Kiritimati]
    env:
      TZ: ${{ matrix.tz }}
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 24
      - name: Environment fingerprint
        run: node scripts/fingerprint.mjs
      - name: Tests
        run: node --test

fail-fast: false matters here. The default is true, which cancels the rest of the matrix on the first failure, and the point of this job is to see which zones fail. With the fixed code, all four zones pass locally:

TZ=Asia/Kolkata ℹ pass 2 ℹ fail 0
TZ=Etc/UTC ℹ pass 2 ℹ fail 0
TZ=America/Los_Angeles ℹ pass 2 ℹ fail 0
TZ=Pacific/Kiritimati ℹ pass 2 ℹ fail 0

The runs-on and node-version pins are deliberate as well. actions/setup-node documents that without node-version it uses whatever Node is on PATH, which on ubuntu-latest changed major version during the 26.04 migration. If you want a preview of the next label, add ubuntu-26.04 as a second runs-on value; matrix shapes like that are easier to check before you push with the matrix include and exclude preview.

Other differences, and the check that singles each one out

The time zone was this failure. Each cause below shows up in a different fingerprint field and needs its own check, so you can rule it in or out in one command.

The default locale follows LANG

Node ships with full ICU data by default, so every locale is available, and in practice the default one follows the locale variables. The same Node v26.12.1 binary on macOS prints the resolved locale and formats one instant like this, with only LANG changed and the zone left at IST:

C.UTF-8      en-US  11/16/2026
en_IN.UTF-8  en-IN  16/11/2026
de_DE.UTF-8  de-DE  16.11.2026

The tell is a failure that mentions number or date formatting rather than a different value: commas against full stops, day and month swapped, or a sort order that changed. Check by replaying LANG and LC_ALL from the CI fingerprint. The fix is to pass an explicit locale to every toLocale*, Intl.* and localeCompare call whose output a test asserts.

The CI variable changes what your tools do

Jest's default for its ci option is the result of the ci-info package's detection, so on a runner it is on without any flag. In that mode a missing snapshot is a failure instead of a new file:

New snapshot was not written. The update flag must be explicitly passed to write a new snapshot.

This is likely because this test is run in a continuous integration (CI) environment in which snapshots are not written by default.

Locally the same test writes the snapshot and passes, so the snapshot file was never committed. Check with CI=true in your shell. Fix by committing the snapshot. Search your own config for process.env.CI as well. The example configuration in Playwright's documentation uses it three times: forbidOnly: !!process.env.CI, retries: process.env.CI ? 2 : 0 and workers: process.env.CI ? 1 : undefined, so a copied config runs one worker with retries on CI and the default worker count without retries on the laptop.

Imports that only resolve on a case-insensitive disk

Apple's Disk Utility documentation describes case sensitivity as a separate APFS variant, so a default Mac volume ignores case, and Microsoft documents the same default for Windows. Linux filesystems are case-sensitive. On a Mac, import("./src/Day-Key.mjs") loads day-key.mjs without complaint; on a Linux runner the ESM loader cannot resolve it and throws ERR_MODULE_NOT_FOUND. The fingerprint's fs.caseSensitive tells you whether this class of bug is even possible on a machine. Check with git ls-files src, which shows the name git actually tracks, and fix the import to match.

A checkout with no tags or history

Anything that derives a version from git breaks on the default checkout. A depth-1 clone of a tagged repository gives:

$ git describe --tags
fatal: No names found, cannot describe anything.

The tell is git.shallow: "true" and a git.describe that is a bare hash. Set fetch-depth: 0 on actions/checkout for the job that needs history, rather than for every job, because a full clone costs time on large repositories.

Fewer CPUs means fewer, different workers

Runners size their parallelism from the CPU count unless told otherwise. node --test runs os.availableParallelism() - 1 files at once, Jest uses the available cores minus one, and Playwright defaults to half the logical cores. On a 10-core laptop that is 9 concurrent test files under node --test; on a private-repo runner with 2 CPUs it is 1. A suite whose timeouts were tuned on the laptop, or whose tests only pass in a particular order, behaves differently on the runner. Compare host.parallelism, then reproduce with --test-concurrency=1, --maxWorkers=1 or --workers=1. If the failure appears only when more workers share a database or account, that is a collision problem, covered in eliminating CI test data collisions.

Name resolution and proxies

network.localhost records the order in which localhost resolves. On the laptop above it is ::1 before 127.0.0.1. A test server that binds only one of those, contacted by a client that tries only the other, fails with a refused connection on one machine and works on the next. Bind the server and point the client at the same literal address, such as 127.0.0.1. A non-empty network.proxies list on either side explains timeouts to services that answer fine from the other machine.

Apply this now

Add scripts/fingerprint.mjs and a fingerprint step before your test step today, on the branch whose CI is red. Run the script on your machine and save the JSON next to the CI copy from the job log. Then:

  1. Run the diff script and write down every line it prints. That list is your set of suspects.
  2. Run the bisect script against the failing command. If one variable flips the result, fix the code that depends on it, not the expected value.
  3. If nothing in the shell reproduces it, check runtime.node, host.parallelism, git.shallow and fs.caseSensitive against the sections above, and check the Set up job log for the image version.
  4. Pin runs-on and node-version, and add a time zone matrix to the job that covers date logic.

The evidence to keep is the two fingerprints and the bisect output. Together they tell the next person why the fix is in the code, and they make the next CI-only failure a diff instead of an argument.

Questions about failures that only happen in CI

Can I run the GitHub runner image on my machine?

Not as a ready-made container. The actions/runner-images repository holds the source used to build the hosted runners' virtual machine images, with instructions for building one in Azure. For day-to-day reproduction, replay the fingerprint's values in your shell, and confirm the fix in CI with a pinned runs-on label.

Does pinning ubuntu-24.04 freeze the environment?

It freezes the operating system version, not the software on it. Images are typically updated weekly. Compare env.ImageVersion between a passing and a failing run; if it changed, read that image's release notes in the runner-images repository before reading your own diff.

The test fails in CI only some of the time. Is this the same problem?

Sometimes. Diff the fingerprints of a passing and a failing run of the same commit first. If they differ, you have an environment cause; during a label migration that can be the OS itself. If they are identical, the failure is nondeterministic, and the approach in failing CI on flaky tests without hiding evidence applies instead.

Will re-running with debug logging show me this?

Partly. Debug logging adds step debug output and runner diagnostic logs, and sets RUNNER_DEBUG=1, but it describes the runner's own work, not what your tests saw. You can use RUNNER_DEBUG as a switch to print a longer fingerprint, still with values limited to the allowlist.

Primary references

CI and Test Infrastructure

Get part 4: Cache CI Dependencies Without Hiding Lockfile Drift

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

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