Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

ci(test-shard): run shard files in the planned order (#6095)

time-attack0c1456aa265a
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 4450f0dad4..73b907c110 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -1241,7 +1241,7 @@ there even though they pass on Linux and macOS.
### CI vs local: intentionally divergent file sets
-- **CI matrix** (`.github/workflows/test.yml`) runs `scripts/test-shard.sh` across 8 shards partitioned by weight-aware LPT bin-packing (`scripts/sharding.ts`; unweighted files get the p75 weight) and includes `*.slow.test.ts` files without a dedicated job (`eval-longmemeval-e2e.slow.test.ts` runs inside the shards; entity-resolve-perf, entity-card-perf, export-scale and brainbench-e2e have dedicated jobs, and `reconcile-crash.slow.test.ts` runs only in persistence-validation) plus keyless-allowlisted `evals/**/*.test.ts` (`test/scripts/evals-collection.test.ts`). Every Bun job activates the PGLite schema snapshot (built in-runner, cached across jobs with the runner's hash check authoritative). Serial files run across four `serial-tests` workers via `bun run test:serial`; `verify` and the BrainBench memory-conformance gate (`scripts/ci-brainbench-gate.sh`, compared against `evals/brainbench/baselines/main.json`) have their own jobs, all aggregated by `test-status`. `e2e.yml` aggregates through `e2e-status`, with jsonb-parity gating Tier 2's token spend; scheduled runs also require the full-corpus lanes. Both aggregates reject failures, cancellations and unexpected skips, and successful test results are never reused. CI is the ground truth for "did everything pass."
+- **CI matrix** (`.github/workflows/test.yml`) runs `scripts/test-shard.sh` across 8 shards partitioned by weight-aware LPT bin-packing (`scripts/sharding.ts`; unweighted files get the p75 weight) and includes `*.slow.test.ts` files without a dedicated job (`eval-longmemeval-e2e.slow.test.ts` runs inside the shards; entity-resolve-perf, entity-card-perf, export-scale and brainbench-e2e have dedicated jobs, and `reconcile-crash.slow.test.ts` runs only in persistence-validation) plus keyless-allowlisted `evals/**/*.test.ts` (`test/scripts/evals-collection.test.ts`). A shard runs its files in the planned order, passed as `./` paths because Bun treats bare paths as name filters and runs them in directory-scan order, so `scripts/test-shard.sh --dry-run-list <i> 8` is the order to replay a cross-file failure in. Every Bun job activates the PGLite schema snapshot (built in-runner, cached across jobs with the runner's hash check authoritative). Serial files run across four `serial-tests` workers via `bun run test:serial`; `verify` and the BrainBench memory-conformance gate (`scripts/ci-brainbench-gate.sh`, compared against `evals/brainbench/baselines/main.json`) have their own jobs, all aggregated by `test-status`. `e2e.yml` aggregates through `e2e-status`, with jsonb-parity gating Tier 2's token spend; scheduled runs also require the full-corpus lanes. Both aggregates reject failures, cancellations and unexpected skips, and successful test results are never reused. CI is the ground truth for "did everything pass."
- **Local fast loop** (`scripts/run-unit-shard.sh` via the parallel wrapper) uses the same weighted partitioner as CI and EXCLUDES `*.slow.test.ts` AND `*.serial.test.ts`. Each shard runs its complete ordered selection with a fresh Bun process per file, without adding workers. Later groups still run after failures; missing summaries or file-completion evidence fail the shard. Local trades coverage for inner-loop speed; CI catches what local skips.
This divergence is intentional; the two scripts solve different problems.
diff --git a/scripts/test-shard.sh b/scripts/test-shard.sh
index 9fff38a018..353c25e111 100755
--- a/scripts/test-shard.sh
+++ b/scripts/test-shard.sh
@@ -27,7 +27,8 @@
# wrong shard until next regen, never silently dropped.
#
# Stable partitioning: same `(files, weights, N)` always produces the
-# same assignment, so retries are reproducible.
+# same assignment, so retries are reproducible. Files also run in the
+# planned order (see the `./` prefix at the bun invocation below).
set -euo pipefail
unset SHARD # Routing belongs to this wrapper, never to nested test runners.
@@ -156,8 +157,14 @@ receipt_begin primary "s${SHARD_INDEX}of${TOTAL_SHARDS}" "$SHARD_INDEX" "$TOTAL_
# --max-concurrency mirrors the local runner: unbounded intra-process
# concurrency under parallel PGLite boots produced real shard deaths (the
# 22-minute matrix timeout in test.yml records 13 of them).
+#
+# The `./` prefix makes each argument a path, not a name filter: Bun runs
+# bare `test/x.test.ts` arguments in directory-scan order (filesystem
+# dependent, so CI on ext4 and a Mac disagree), and explicit paths in the
+# order given. Bun still reports them as `test/x.test.ts`, so the log and
+# JUnit parsers see the same names.
rc=0
-printf '%s\n' "$SHARD_FILES" | xargs ${XARGS_FLAGS[@]+"${XARGS_FLAGS[@]}"} bun test --timeout=60000 --max-concurrency="${GBRAIN_TEST_MAX_CONCURRENCY:-4}" ${COVERAGE_ARGS[@]+"${COVERAGE_ARGS[@]}"} ${RECEIPT_ARGS[@]+"${RECEIPT_ARGS[@]}"} || rc=$?
+printf '%s\n' "$SHARD_FILES" | sed 's#^#./#' | xargs ${XARGS_FLAGS[@]+"${XARGS_FLAGS[@]}"} bun test --timeout=60000 --max-concurrency="${GBRAIN_TEST_MAX_CONCURRENCY:-4}" ${COVERAGE_ARGS[@]+"${COVERAGE_ARGS[@]}"} ${RECEIPT_ARGS[@]+"${RECEIPT_ARGS[@]}"} || rc=$?
receipt_end "$rc"
# Lane manifest: written ONLY on a fully green run (complete:true means the
diff --git a/test/scripts/test-shard.slow.test.ts b/test/scripts/test-shard.slow.test.ts
index 2434a0349b..f6231526b6 100644
--- a/test/scripts/test-shard.slow.test.ts
+++ b/test/scripts/test-shard.slow.test.ts
@@ -229,3 +229,71 @@ describe('test-shard.sh — LPT balance contract', () => {
expect(fresh).toEqual(cached);
});
});
+
+describe('test-shard.sh — execution order contract', () => {
+ // Bun treats a bare `test/x.test.ts` argument as a name filter and runs
+ // the matches in directory-scan order, so the planned LPT order never
+ // reached the shard process and cross-file pollution depended on the
+ // runner's filesystem. Drive the real script with a fake partitioner
+ // that reverses the sorted list, and the real Bun on tiny fixture files.
+ it('runs the shard files in the planned order', () => {
+ const { chmodSync, copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } = require('fs');
+ const { tmpdir } = require('os');
+ const { join } = require('path');
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-test-shard-order-'));
+ try {
+ for (const dir of ['scripts/lib', 'test', 'evals', 'bin']) mkdirSync(join(root, dir), { recursive: true });
+ copyFileSync(SHARD_SH, join(root, 'scripts/test-shard.sh'));
+ copyFileSync(resolve(REPO_ROOT, 'scripts/lib/test-env.sh'), join(root, 'scripts/lib/test-env.sh'));
+ const names = ['alpha', 'bravo', 'charlie', 'delta', 'echo', 'foxtrot'];
+ for (const name of names) {
+ writeFileSync(join(root, `test/${name}.test.ts`),
+ `import { test } from 'bun:test';\nimport { appendFileSync } from 'fs';\n` +
+ `test('${name}', () => { appendFileSync(process.env.ORDER_LOG!, '${name}\\n'); });\n`);
+ }
+ writeFileSync(join(root, 'bin/bun'), `#!/usr/bin/env bash
+set -eu
+if [ "$1" = run ] && [ "$2" = scripts/sharding.ts ]; then
+ awk '{ lines[NR] = $0 } END { for (i = NR; i > 0; i--) print lines[i] }'
+ exit 0
+fi
+[ "$1" = test ] || exit 1
+printf '%s\\n' "$@" > "$ARGV_LOG"
+exec "$REAL_BUN" "$@"
+`);
+ chmodSync(join(root, 'bin/bun'), 0o755);
+ const env = {
+ ...process.env,
+ PATH: `${join(root, 'bin')}:${process.env.PATH}`,
+ REAL_BUN: process.execPath,
+ ORDER_LOG: join(root, 'order.log'),
+ ARGV_LOG: join(root, 'argv.log'),
+ GBRAIN_NO_SNAPSHOT: '1',
+ GBRAIN_TEST_RECEIPT_DIR: join(root, 'receipts'),
+ COVERAGE_DIR: '',
+ };
+ const planned = execFileSync('bash', [join(root, 'scripts/test-shard.sh'), '--dry-run-list', '1', '1'], { cwd: root, encoding: 'utf-8', env })
+ .split('\n').filter(Boolean);
+ expect(planned).toEqual([...names].reverse().map(n => `test/${n}.test.ts`));
+ execFileSync('bash', [join(root, 'scripts/test-shard.sh'), '1', '1'], { cwd: root, encoding: 'utf-8', env, stdio: 'pipe' });
+ const argv = readFileSync(join(root, 'argv.log'), 'utf-8').split('\n').filter((a: string) => a.endsWith('.test.ts'));
+ expect(argv).toEqual(planned.map(f => `./${f}`));
+ expect(readFileSync(join(root, 'order.log'), 'utf-8').split('\n').filter(Boolean)).toEqual([...names].reverse());
+ // Receipt mode forces the single-invocation xargs tripwire, and the
+ // receipt `.files` plus Bun's JUnit report keep the canonical bare
+ // names in planned order, so the ledger matches assigned to executed.
+ const rawArgv = readFileSync(join(root, 'argv.log'), 'utf-8').split('\n');
+ expect(rawArgv.some((a: string) => a.startsWith('--reporter-outfile='))).toBe(true);
+ const receiptDir = join(root, 'receipts');
+ const id = 'unit--s1of1--primary';
+ expect(readFileSync(join(receiptDir, `${id}.files`), 'utf-8').split('\n').filter(Boolean)).toEqual(planned);
+ expect(readFileSync(join(receiptDir, `${id}.receipt`), 'utf-8')).toContain('exit=0');
+ const junit = readFileSync(join(receiptDir, `${id}.junit.xml`), 'utf-8');
+ const suites = [...junit.matchAll(/<testsuite name="([^"]+)"[^>]*file="([^"]+)"/g)].map(m => m[2]);
+ expect(suites).toEqual(planned);
+ expect([...junit.matchAll(/<testcase /g)]).toHaveLength(names.length);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ }, 60_000);
+});