Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
ci(test): run two unit shards per 4-vCPU runner (GBRA-135 E2b): 9 jobs, same 18-shard partition, coverage lanes and per-shard artifacts
garrytanab087cb1f4e6
diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex 61c988108d..774820ea8c 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -815,11 +815,19 @@ jobs:# head before merge (merge-train requires full-suite), on every push to master# and on the nightly schedule.test:+ name: test (${{ join(matrix.shards, ', ') }})needs: [changes]if: ${{ needs.changes.outputs.reuse != 'true' && (github.event_name != 'pull_request' && (github.event_name != 'workflow_dispatch' || (inputs.native_only != true && inputs.race_hunt != true && !inputs.stress_files && !inputs.stress_base))) }}# Pure matrix shard — no verify, no serial. Each shard runs its slice# of the unit test set under one `bun test` invocation.#+ # Two shards per runner (UNIT_SHARDS_PER_JOB, scripts/test-shard-pack.sh):+ # one shard keeps 1.1-1.5 of the 4 vCPUs busy, so a runner runs two at+ # once, each with its own coverage lane, receipts and timing log under the+ # per-shard artifact names. GBRA-135 pilot (two matched runs): 42% fewer+ # vCPU-minutes, each shard 1.13-1.28x its solo time, at most 12.4 of 16 GB+ # in use. Weights mined from these jobs include that contention.+ ## 18 shards (UNIT_SHARDS in scripts/sharding.ts): ~10,200s of mined file# time (run 39121354115) is ~567s per shard. A shard's mined weight must# fit this job's 22 minutes twice over, after a minute of setup, with a@@ -845,7 +853,7 @@ jobs:strategy:fail-fast: falsematrix:- shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]+ shards: [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14], [15, 16], [17, 18]]steps:- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2@@ -872,6 +880,7 @@ jobs:# predicted weight (test-shard.sh prints it) with high steal or a# different model name is a slow or silently downgraded runner draw,# not a test regression; the same shard at low steal is the tests.+ # The memory sampler runs until the job ends: two shards share 16 GB.- name: Runner diagnostics (before shard)shell: bashrun: |@@ -879,12 +888,12 @@ jobs:echo "loadavg: $(cat /proc/loadavg)"awk '/^cpu /{print "steal_jiffies", $9}' /proc/statlscpu | grep -m1 'Model name'- - name: Run test shard ${{ matrix.shard }}/18+ (while true; do free -m | awk '/^Mem:/{print $3, $7}' >> "$RUNNER_TEMP/mem.log"; sleep 5; done) > /dev/null 2>&1 &+ - name: Run test shards ${{ join(matrix.shards, ' and ') }} of 18shell: bash- run: bun scripts/capture-test-log.ts --job 'test (${{ matrix.shard }})' --out "$RUNNER_TEMP/unit.log" -- bash scripts/test-shard.sh ${{ matrix.shard }} 18+ run: bash scripts/test-shard-pack.sh 18 ${{ join(matrix.shards, ' ') }}env:- COVERAGE_DIR: ${{ runner.temp }}/coverage- GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts+ GBRAIN_SHARD_PACK_DIR: ${{ runner.temp }}/shards- name: Runner diagnostics (after shard)if: always()shell: bash@@ -893,30 +902,57 @@ jobs:echo "loadavg: $(cat /proc/loadavg)"awk '/^cpu /{print "steal_jiffies", $9}' /proc/statlscpu | grep -m1 'Model name'- - name: Upload receipts+ echo "memory MB: peak used $(sort -n -k1 "$RUNNER_TEMP/mem.log" | tail -1 | cut -d' ' -f1), least available $(sort -n -k2 "$RUNNER_TEMP/mem.log" | head -1 | cut -d' ' -f2), total $(free -m | awk '/^Mem:/{print $2}')"+ - name: Upload receipts (shard ${{ matrix.shards[0] }})if: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4with:- name: receipts-unit-${{ matrix.shard }}- path: ${{ runner.temp }}/receipts+ name: receipts-unit-${{ matrix.shards[0] }}+ path: ${{ runner.temp }}/shards/${{ matrix.shards[0] }}/receiptsretention-days: 14if-no-files-found: warnoverwrite: true- - name: Upload coverage (shard lane)+ - name: Upload coverage (shard lane ${{ matrix.shards[0] }})if: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4with:- name: coverage-shard-${{ matrix.shard }}- path: ${{ runner.temp }}/coverage+ name: coverage-shard-${{ matrix.shards[0] }}+ path: ${{ runner.temp }}/shards/${{ matrix.shards[0] }}/coverage+ retention-days: 14+ if-no-files-found: ignore+ overwrite: true+ - name: Upload unit timing log (shard ${{ matrix.shards[0] }})+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: timings-unit-${{ matrix.shards[0] }}+ path: ${{ runner.temp }}/shards/${{ matrix.shards[0] }}/unit.log+ retention-days: 14+ overwrite: true+ - name: Upload receipts (shard ${{ matrix.shards[1] }})+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: receipts-unit-${{ matrix.shards[1] }}+ path: ${{ runner.temp }}/shards/${{ matrix.shards[1] }}/receipts+ retention-days: 14+ if-no-files-found: warn+ overwrite: true+ - name: Upload coverage (shard lane ${{ matrix.shards[1] }})+ if: always()+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4+ with:+ name: coverage-shard-${{ matrix.shards[1] }}+ path: ${{ runner.temp }}/shards/${{ matrix.shards[1] }}/coverageretention-days: 14if-no-files-found: ignoreoverwrite: true- - name: Upload unit timing log+ - name: Upload unit timing log (shard ${{ matrix.shards[1] }})if: always()uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4with:- name: timings-unit-${{ matrix.shard }}- path: ${{ runner.temp }}/unit.log+ name: timings-unit-${{ matrix.shards[1] }}+ path: ${{ runner.temp }}/shards/${{ matrix.shards[1] }}/unit.logretention-days: 14overwrite: truediff --git a/docs/TESTING.md b/docs/TESTING.mdindex 6486ed5be1..312d1326ce 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -66,8 +66,8 @@ Sizes come from measured CPU use, not guesses. Each Ubicloud project shares onevCPU quota between pull-request CI and agent `ci:ubicloud` VMs, so an oversizedrunner makes every other job wait, and an undersized one lengthens the PRcritical path. A unit shard is one Bun process that averages 1.1-1.5 busy-cores, yet on 2 vCPUs the unit shard mean rose from 542s to 608s on a full PR-run and made Test the critical path, so unit shards stay on 4 vCPUs. On matched+cores, so two shards share each 4-vCPU runner; on 2 vCPUs one shard's mean+rose from 542s to 608s and made Test the critical path. On matchedVMs a unit shard takes the same time on 4, 8 and 16 vCPUs; the serial pool and`verify` take the same time on 8 and 16 vCPUs (serial shard 2: 222s and 224s;277s on 4); the 2,500-write PGLite soak averages 1.3-1.8 busy cores and takes@@ -1269,7 +1269,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 18 shards split 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, plus keyless-allowlisted `evals/**/*.test.ts` (`test/scripts/evals-collection.test.ts`). Shards keep planned file order (`test-shard.sh --dry-run-list <i> 18`) and print their predicted weight (`sharding.ts --sum`). Every Bun job activates the PGLite schema snapshot (built in-runner, cached across jobs; the runner's hash check is authoritative). Serial files run across four `serial-tests` workers via `bun run test:serial`; `verify`, `typecheck` 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. Only a master push reuses results: those of a passed full-suite run of its exact tree (`scripts/ci-reuse.ts`). CI is the ground truth for "did everything pass."+- **CI matrix** (`.github/workflows/test.yml`) runs 18 `scripts/test-shard.sh` shards, two per runner, split 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, plus keyless-allowlisted `evals/**/*.test.ts` (`test/scripts/evals-collection.test.ts`). Shards keep planned file order (`test-shard.sh --dry-run-list <i> 18`) and print their predicted weight (`sharding.ts --sum`). Every Bun job activates the PGLite schema snapshot (built in-runner, cached across jobs; the runner's hash check is authoritative). Serial files run across four `serial-tests` workers via `bun run test:serial`; `verify`, `typecheck` 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. Only a master push reuses results: those of a passed full-suite run of its exact tree (`scripts/ci-reuse.ts`). 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.`test/scripts/run-unit-shard.test.ts` pins what the local loop includes, anddiff --git a/docs/architecture/key-files/tooling-and-tests.md b/docs/architecture/key-files/tooling-and-tests.mdindex 83dd8c4b07..1146fcee50 100644--- a/docs/architecture/key-files/tooling-and-tests.md+++ b/docs/architecture/key-files/tooling-and-tests.md@@ -80,7 +80,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `scripts/select-e2e.ts` + `scripts/ci-changed-files.sh` + `scripts/ci-doc-checks.sh` — E2E selection. `select-e2e.ts` classifies the changed files (git: committed `origin/master...HEAD`, working tree and untracked-unignored files; or `--changed-files <path|->`) as EMPTY / DOC_ONLY / SRC: DOC_ONLY (root `*.md`, `docs/`, LICENSE, VERSION) selects nothing, everything else selects every `test/e2e/*.test.ts` and prints "E2E narrowing is retired" (a diff map selected all files on 40 of 40 merged PRs). `ci-changed-files.sh` lists a PR's or merge-group entry's files from the GitHub API for `prepare-e2e` and exits 1 on a capped (3000 PR / 300 compare), short or failed list or with no PR context, so the workflow falls back to the whole corpus. `ci-doc-checks.sh` is the doc-only gate `ci:local:diff` and `ci:ubicloud:diff` run (llms freshness, `check:doc-history`, `test/docs-repo-paths.test.ts`, skill refs, privacy guards). Tests: `test/select-e2e.test.ts`, `test/scripts/e2e-wiring.test.ts`, `test/scripts/ci-local-rendering.test.ts`.-- `scripts/sharding.ts` + `scripts/mine-shard-weights.ts` + `scripts/capture-test-log.ts` — shared deterministic weighted partitioning and timing refresh. CLI accepts lane-specific weights; missing entries use p75, equal loads prefer fewer files then shard index, and serial may explicitly opt into warning/fallback on bad advisory weights. `UNIT_SHARDS` sizes both unit matrices under `UNIT_SHARD_BUDGET_MS` (`test/scripts/unit-shard-budget.test.ts`). `--sum` prints a shard's predicted weight (test-shard.sh logs it; the unit job logs nproc, load, steal and CPU model, so a slow draw is told apart from slow tests). `weights:mine --lane unit|serial|e2e` validates completed lane logs before replacement and records run/commit/unit metadata. A GitHub refresh reads one job at a time (a whole-run `gh run view --log` is refused above gh's job cap): unit from each shard's `timings-unit-N` capture artifact, which must record one capture start and a final `complete exit=0`; serial from `gh run view --job <id> --log`. E2E defaults to merging selected-job observations; explicit `--e2e-profile full --run ID` requires a successful source-matched run, pins its attempt/job IDs, resolves basename headers against committed default discovery including the outside-directory parity entry, and replaces the map only after exact disjoint corpus validation. Metadata retains log/corpus hashes; file/stdin sources cannot claim full-profile provenance. Capture preserves stdout/stderr, records timestamped GitHub-format artifacts, forwards cancellation to its owned process group and marks failed runs unmineable. On a failed run under Actions it appends the last 50 failures to the step summary: file, test, backend arm, the first error block and a reproduction command (or the last log lines when no `(fail)` line was printed). Unit and E2E artifact retention is 14 days. `scripts/check-weight-coverage.ts` (`check:weight-coverage`, in verify) fails on a unit/serial/E2E/Ubicloud weight entry naming a missing file and on an unweighted lane share above 5% (unit) or 10% (serial, E2E) only when `GITHUB_EVENT_NAME=schedule`; otherwise the share warns (stdout + step summary) with the lane's miner command. Tests: `test/scripts/check-weight-coverage.test.ts` plus guard self-test fixtures.+- `scripts/sharding.ts` + `scripts/mine-shard-weights.ts` + `scripts/capture-test-log.ts` — deterministic weighted partitioning and timing refresh. CLI takes lane-specific weights; missing entries use p75, equal loads prefer fewer files then shard index, and serial may explicitly opt into warning/fallback on bad advisory weights. `UNIT_SHARDS` sizes both unit matrices under `UNIT_SHARD_BUDGET_MS` (`test/scripts/unit-shard-budget.test.ts`); test.yml runs `UNIT_SHARDS_PER_JOB` per runner via `scripts/test-shard-pack.sh` (job `test (N, M)`, artifacts per shard). `--sum` prints a shard's predicted weight (test-shard.sh logs it with nproc, load, steal, CPU model: slow draw or slow tests). `weights:mine --lane unit|serial|e2e` validates complete lane logs before replacing and records run/commit/unit metadata. A GitHub refresh reads one job at a time (gh refuses a whole-run `--log` above its job cap): unit from each shard's `timings-unit-N` capture artifact, which must record one capture start and a final `complete exit=0`; serial from `gh run view --job <id> --log`. E2E defaults to merging selected-job observations; explicit `--e2e-profile full --run ID` requires a successful source-matched run, pins its attempt/job IDs, resolves basename headers against committed default discovery including the outside-directory parity entry, and replaces the map only after exact disjoint corpus validation. Metadata retains log/corpus hashes; file/stdin sources cannot claim full-profile provenance. Capture keeps stdout/stderr, records timestamped GitHub-format artifacts, forwards cancellation to its process group and marks failed runs unmineable. A failed Actions run appends its last 50 failures to the step summary: file, test, backend arm, first error block and a reproduction command (or the last log lines when no `(fail)` line printed). Unit and E2E artifacts keep 14 days. `scripts/check-weight-coverage.ts` (`check:weight-coverage`, in verify) fails on a unit/serial/E2E/Ubicloud weight naming a missing file and on an unweighted lane share above 5% (unit) or 10% (serial, E2E) only when `GITHUB_EVENT_NAME=schedule`; else the share warns (stdout + step summary) with the lane's miner command. Tests: `test/scripts/check-weight-coverage.test.ts` plus guard self-test fixtures.- `test/e2e/codex-plugin-install-real.serial.test.ts` + `test/e2e/claude-plugin-install-real.serial.test.ts` — the plugin doors: clean-tree staging (`git archive HEAD`), real marketplace add/plugin add, snapshot + exec-bit + non-root-mcp.json pins, tools/list starter-surface oracle, cold-home fast-fail, --source-guard block/allow, coexistence + removal probes, auth-gated SMOKE turns. CI: the `plugin-doors` job in heavy-tests.yml (pinned binary provisioning + expected-pass-count refuse-green).diff --git a/scripts/ci-health-report.ts b/scripts/ci-health-report.tsindex c1ee1edc11..9d9ba32af5 100644--- a/scripts/ci-health-report.ts+++ b/scripts/ci-health-report.ts@@ -51,7 +51,7 @@ export const TARGETS = { master: 0.95, pr: 0.9 };export const STRESS_JOB = 'stress-changed-tests';const AGGREGATORS = new Set(['test-status', 'e2e-status']);const WORKFLOWS = [- { file: 'test.yml', name: 'Test', shard: /^test \(\d+\)$/, lane: 'unit' },+ { file: 'test.yml', name: 'Test', shard: /^test \(\d+(?:, \d+)*\)$/, lane: 'unit' },{ file: 'e2e.yml', name: 'E2E Tests', shard: /^Selected E2E \(diff-relevant\)/, lane: 'e2e' },] as const;const WATCHED = ['test.yml', 'e2e.yml', 'heavy-tests.yml', 'scale-tier.yml', 'macos-validation.yml', 'semgrep.yml', 'osv-scanner.yml', 'ci-health.yml'];diff --git a/scripts/mine-shard-weights.ts b/scripts/mine-shard-weights.tsindex 0a5dfeb0a4..c0e8423543 100644--- a/scripts/mine-shard-weights.ts+++ b/scripts/mine-shard-weights.ts@@ -27,8 +27,12 @@ function logLines(raw: string): LogLine[] {return [{ job: m[1]!.trim(), step: m[2]!.trim(), timestampMs: Date.parse(m[3]!), text: m[4]!.replace(/\x1b\[[0-9;]*m/g, "") }];});}+/** The shards a test.yml unit job ran: `test (3)` alone, `test (3, 4)` packed by scripts/test-shard-pack.sh. */+function unitJobShards(job: string): string[] | undefined {+ return /^test \((\d+(?:, \d+)*)\)$/.exec(job)?.[1]!.split(", ");+}function isJob(job: string, lane: Lane, e2eProfile: E2EProfile = "selected"): boolean {- if (lane === "unit") return /^test \(\d+\)$/.test(job);+ if (lane === "unit") return unitJobShards(job) !== undefined;if (lane === "serial") return /^serial-tests(?: \(\d+\))?$/.test(job);if (e2eProfile === "full") return /^coverage-full-e2e(?: \(\d+\))?$/.test(job);return /^Selected E2E \(diff-relevant\)(?: \(\d+\)| \d+)?$/.test(job);@@ -267,7 +271,9 @@ async function main(): Promise<void> {if (info.conclusion !== "success") throw new Error(`run ${run} is not successful`);const jobs = info.jobs.filter((j: { name: string }) => isJob(j.name, lane, e2eProfile));if (!jobs.length || jobs.some((j: { conclusion: string }) => j.conclusion !== "success")) throw new Error(`run ${run} has no complete ${lane} lane`);- expectedJobs = jobs.map((j: { name: string }) => j.name);+ // A packed unit job captured each of its shards as job `test (N)`.+ expectedJobs = lane === "unit" ? jobs.flatMap((j: { name: string }) => unitJobShards(j.name)!.map(shard => `test (${shard})`))+ : jobs.map((j: { name: string }) => j.name);commit = info.headSha;if (lane === "serial") {if (jobs.some((j: { databaseId: number }) => !Number.isInteger(j.databaseId) || j.databaseId < 1)) throw new Error("serial: missing job identity");diff --git a/scripts/sharding.ts b/scripts/sharding.tsindex 1057d93fa3..ca3cf4dd95 100644--- a/scripts/sharding.ts+++ b/scripts/sharding.ts@@ -55,6 +55,8 @@ const DEFAULT_WEIGHTS_PATH = resolve(REPO_ROOT, "scripts/test-weights.json");* test/scripts/unit-shard-budget.test.ts pins both workflows to it.*/export const UNIT_SHARDS = 18;+/** Unit shards each test.yml `test` job runs at once (scripts/test-shard-pack.sh); test/scripts/ci-gates.test.ts pins the matrix to it. */+export const UNIT_SHARDS_PER_JOB = 2;/** test.yml's `test` job `timeout-minutes: 22`: the only bound on a unit shard, its setup steps included. */export const UNIT_JOB_TIMEOUT_MS = 22 * 60 * 1000;/** The job's steps before the shard (checkout, Bun, cache restores, install): 10-20 s measured on a warm cache. */diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsvindex 16ce428c9d..351efea47c 100644--- a/scripts/structural-suites.tsv+++ b/scripts/structural-suites.tsv@@ -289,7 +289,7 @@ test/scripts/check-item-allowlist-catches.test.ts CLI 2 readFileSynctest/scripts/chunk-visibility-ratchet.test.ts check-chunk-visibility.ts 6 readFileSynctest/scripts/ci-bounded-run.test.ts (file-level) 7 readFileSynctest/scripts/ci-executed-counts.test.ts CLI 2 readFileSync-test/scripts/ci-gates.test.ts CI execution evidence 9 readFileSync+test/scripts/ci-gates.test.ts CI execution evidence 10 readFileSynctest/scripts/ci-gates.test.ts test:full exit status 0 readFileSynctest/scripts/ci-hydrate-admin-dist.test.ts #6756 ci:local hydrates the admin/dist volume from the worktree 7 readFileSynctest/scripts/ci-local-rendering.test.ts ci-local command rendering 1 readFileSyncdiff --git a/scripts/test-shard-pack.sh b/scripts/test-shard-pack.shnew file mode 100755index 0000000000..ba7bb03bc8--- /dev/null+++ b/scripts/test-shard-pack.sh@@ -0,0 +1,77 @@+#!/usr/bin/env bash+# Run several unit shards of one partition at once on one runner.+#+# Usage: scripts/test-shard-pack.sh <total-shards> <shard-index>...+#+# test.yml's `test` job runs UNIT_SHARDS_PER_JOB (scripts/sharding.ts) of the+# UNIT_SHARDS shards on one 4-vCPU runner: a shard is one bun process that+# keeps 1.1-1.5 cores busy, so a lone shard leaves most of the runner idle.+# The partition, the coverage lanes and the artifacts stay per shard. Shard s+# writes everything under $GBRAIN_SHARD_PACK_DIR/<s>/:+# coverage/ its COVERAGE_DIR (lcov and lane-manifest.json, lane shard-<s>)+# receipts/ its GBRAIN_TEST_RECEIPT_DIR+# unit.log its timing capture as job "test (<s>)" (scripts/capture-test-log.ts)+# console.txt its console output, printed as soon as the shard ends so two+# shards never interleave their lines or Bun's annotations+# exit its exit code, written when it ends+#+# Exit status: 0 only when every shard exited 0, else the first failing+# shard's code. Each failing shard gets an ::error line naming the command+# that reproduces it. Bash 3.2 compatible (no wait -n, no associative arrays).++set -euo pipefail++if [ "$#" -lt 2 ]; then+ echo "usage: scripts/test-shard-pack.sh <total-shards> <shard-index>..." >&2+ exit 2+fi+: "${GBRAIN_SHARD_PACK_DIR:?set GBRAIN_SHARD_PACK_DIR to the directory for the per-shard outputs}"++cd "$(dirname "$0")/.."++total="$1"+shift+for s in "$@"; do+ if ! [[ "$s" =~ ^[0-9]+$ ]] || [ "$s" -lt 1 ] || [ "$s" -gt "$total" ]; then+ echo "error: shard index $s out of range 1..$total" >&2+ exit 2+ fi+done++for s in "$@"; do+ dir="$GBRAIN_SHARD_PACK_DIR/$s"+ mkdir -p "$dir"+ rm -f "$dir/exit"+ (+ rc=0+ COVERAGE_DIR="$dir/coverage" GBRAIN_TEST_RECEIPT_DIR="$dir/receipts" \+ bun scripts/capture-test-log.ts --job "test ($s)" --out "$dir/unit.log" -- \+ bash scripts/test-shard.sh "$s" "$total" > "$dir/console.txt" 2>&1 || rc=$?+ echo "$rc" > "$dir/exit"+ ) &+done++status=0+pending=("$@")+while [ "${#pending[@]}" -gt 0 ]; do+ running=()+ for s in "${pending[@]}"; do+ dir="$GBRAIN_SHARD_PACK_DIR/$s"+ if [ ! -f "$dir/exit" ]; then+ running+=("$s")+ continue+ fi+ rc=$(cat "$dir/exit")+ echo "=== unit shard $s/$total exited $rc ==="+ cat "$dir/console.txt"+ echo "=== end of unit shard $s/$total ==="+ if [ "$rc" -ne 0 ]; then+ echo "::error title=unit shard $s/$total failed::exit $rc; reproduce with: bash scripts/test-shard.sh $s $total (full log: artifact timings-unit-$s)"+ [ "$status" -ne 0 ] || status="$rc"+ fi+ done+ pending=(${running[@]+"${running[@]}"})+ [ "${#pending[@]}" -eq 0 ] || sleep 1+done+wait+exit "$status"diff --git a/test/scripts/ci-gates.test.ts b/test/scripts/ci-gates.test.tsindex 4b9b4f2142..97db545aa2 100644--- a/test/scripts/ci-gates.test.ts+++ b/test/scripts/ci-gates.test.ts@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { spawnSync } from 'node:child_process';import { load } from 'js-yaml';-import { UNIT_SHARDS } from '../../scripts/sharding.ts';+import { UNIT_SHARDS, UNIT_SHARDS_PER_JOB } from '../../scripts/sharding.ts';const root = join(import.meta.dir, '..', '..');type Job = { needs?: string | string[]; if?: string; steps: Array<{ name?: string; run?: string; uses?: string; env?: Record<string, string>; if?: string; with?: Record<string, string>; 'timeout-minutes'?: number }> };@@ -127,17 +127,31 @@ describe('CI execution evidence', () => {});test('unit shard count agrees across the matrix, the shard step and the coverage manifest', () => {- const job = unit.jobs.test as Job & { strategy: { matrix: { shard: number[] } } };- const shards = job.strategy.matrix.shard;+ const job = unit.jobs.test as Job & { strategy: { matrix: { shards: number[][] } } };+ const packs = job.strategy.matrix.shards;+ expect(packs.map(pack => pack.length)).toEqual(packs.map(() => UNIT_SHARDS_PER_JOB));+ const shards = packs.flat();expect(shards).toEqual(Array.from({ length: UNIT_SHARDS }, (_, i) => i + 1));- const run = job.steps.find(step => step.run?.includes('scripts/test-shard.sh'))!;- expect(run.name).toBe(`Run test shard \${{ matrix.shard }}/${shards.length}`);- expect(run.run).toContain(`scripts/test-shard.sh \${{ matrix.shard }} ${shards.length}`);+ const run = job.steps.find(step => step.run?.includes('scripts/test-shard-pack.sh'))!;+ expect(run.name).toBe(`Run test shards \${{ join(matrix.shards, ' and ') }} of ${shards.length}`);+ expect(run.run).toBe(`bash scripts/test-shard-pack.sh ${shards.length} \${{ join(matrix.shards, ' ') }}`);const merge = unit.jobs['coverage-report'].steps.find(step => step.name === 'Merge lanes')!.run!;const expected = /--manifest-expect (\S+)/.exec(merge)![1].split(',').filter(lane => lane.startsWith('shard-'));expect(expected).toEqual(shards.map(shard => `shard-${shard}`));});+ test('each packed unit shard uploads its own receipts, coverage lane and timing log', () => {+ const job = unit.jobs.test as Job;+ const pack = job.steps.find(step => step.run?.includes('scripts/test-shard-pack.sh'))!;+ expect(pack.env).toEqual({ GBRAIN_SHARD_PACK_DIR: '${{ runner.temp }}/shards' });+ const uploads = job.steps.filter(step => step.uses?.startsWith('actions/upload-artifact@')).map(step => [step.with!.name, step.with!.path]);+ expect(uploads).toEqual(Array.from({ length: UNIT_SHARDS_PER_JOB }, (_, i) => `\${{ matrix.shards[${i}] }}`).flatMap(shard => [+ [`receipts-unit-${shard}`, `\${{ runner.temp }}/shards/${shard}/receipts`],+ [`coverage-shard-${shard}`, `\${{ runner.temp }}/shards/${shard}/coverage`],+ [`timings-unit-${shard}`, `\${{ runner.temp }}/shards/${shard}/unit.log`],+ ]));+ });+test('the nightly coverage-full-unit lane runs the same unit partition', () => {const job = e2e.jobs['coverage-full-unit'] as Job & { strategy: { matrix: { shard: number[] } } };const shards = job.strategy.matrix.shard;diff --git a/test/scripts/ci-health-report.test.ts b/test/scripts/ci-health-report.test.tsindex 901f4da265..50240c98e8 100644--- a/test/scripts/ci-health-report.test.ts+++ b/test/scripts/ci-health-report.test.ts@@ -48,7 +48,7 @@ describe('ci-health-report', () => {const W = { since: '2026-09-27T00:00:00.000Z', until: '2026-10-04T00:00:00.000Z' };const decoded = (path: string) => decodeURIComponent(path);- function fakeApi(opts: { pr?: (page: number, path: string) => { workflow_runs: Run[]; total_count: number }; push?: Run[]; issues?: unknown[]; comments?: Record<number, unknown[]>; timeline?: Record<number, unknown[]>; failJobs?: boolean }) {+ function fakeApi(opts: { pr?: (page: number, path: string) => { workflow_runs: Run[]; total_count: number }; push?: Run[]; issues?: unknown[]; comments?: Record<number, unknown[]>; timeline?: Record<number, unknown[]>; failJobs?: boolean; unitJobs?: [string, string] }) {const calls: string[] = [];const client: GitHubClient = {async request<T>(_m: string, path: string): Promise<T> {@@ -67,7 +67,8 @@ describe('ci-health-report', () => {const id = Number(/runs\/(\d+)\//.exec(path)![1]);if (id % 7 === 0) return { jobs: [{ id: 9, name: 'stress-changed-tests', conclusion: 'failure' }, { id: 10, name: 'test-status', conclusion: 'failure' }] } as T;if (id % 7 === 1) return { jobs: [{ id: 11, name: 'verify', conclusion: 'timed_out' }] } as T;- return { jobs: [shard(1, 'test (1)', 100), shard(2, 'test (2)', 300, 'failure'), shard(3, 'Selected E2E (diff-relevant) 1', 50)] } as T;+ const [first, second] = opts.unitJobs ?? ['test (1)', 'test (2)'];+ return { jobs: [shard(1, first, 100), shard(2, second, 300, 'failure'), shard(3, 'Selected E2E (diff-relevant) 1', 50)] } as T;}if (path.includes('/annotations')) return [{ annotation_level: 'failure', path: 'test/flaky.test.ts', title: 'error: timeout', message: '' }] as T;if (path.includes('issues?labels=master-red')) return (opts.issues ?? []) as T;@@ -102,6 +103,12 @@ describe('ci-health-report', () => {expect(body).toContain('Docs: docs/ci-red-runbook.md#ci-health-report');});+ test('unit shard spread reads the packed jobs test.yml runs two shards in (`test (1, 2)`)', async () => {+ const { client } = fakeApi({ unitJobs: ['test (1, 2)', 'test (3, 4)'], pr: p => ({ workflow_runs: p === 1 ? [run(2, 'success')] : [], total_count: 1 }) });+ const unit = (await collectHealth(client, W)).workflows.find(w => w.workflow === 'test.yml')!;+ expect(unit.spread.mean_ratio).toBeCloseTo(1.5);+ });+test('a window over the 1000-result search cap is split in halves until every slice fits; a slice that cannot fit is indeterminate, never satisfied', async () => {const big = fakeApi({ pr: (p, path) => {const [from, to] = decoded(path).match(/created=([^&]+)/)![1]!.split('..').map(Date.parse);diff --git a/test/scripts/mine-shard-weights.test.ts b/test/scripts/mine-shard-weights.test.tsindex 7de83d4329..64519b769e 100644--- a/test/scripts/mine-shard-weights.test.ts+++ b/test/scripts/mine-shard-weights.test.ts@@ -440,3 +440,33 @@ esac});} finally { rmSync(dir, { recursive: true, force: true }); }}, 30000);++it('GitHub refresh mines every shard of a packed unit job (test.yml runs two per runner)', () => {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-mine-packed-'));+ try {+ const bin = join(dir, 'bin');+ const artifacts = join(dir, 'artifacts');+ mkdirSync(bin);+ mkdirSync(artifacts);+ writeFileSync(join(bin, 'gh'), '#!/bin/sh\ncase "$*" in\n "run view 123 --json conclusion,headSha,jobs") cat "$FIXTURE_GH_INFO" ;;\n "run download 123 --name timings-unit-"*) [ -f "$FIXTURE_GH_ARTIFACTS/$5.log" ] && cp "$FIXTURE_GH_ARTIFACTS/$5.log" "$7/unit.log" ;;\n *) exit 2 ;;\nesac\n');+ chmodSync(join(bin, 'gh'), 0o755);+ const info = join(dir, 'run.json');+ const out = join(dir, 'weights.json');+ const line = (job: string, text: string) => `${job}\tcapture\t2026-05-25T11:26:50.000Z ${text}\n`;+ const complete = (job: string, file: string) => line(job, '##[gbrain-capture-start]') + line(job, `::group::${file}:`) + line(job, '0 fail')+ + line(job, 'Ran 1 test across 1 file. [1ms]') + line(job, '##[gbrain-capture-complete] exit=0');+ writeFileSync(join(artifacts, 'timings-unit-1.log'), complete('test (1)', 'test/one.test.ts'));+ writeFileSync(join(artifacts, 'timings-unit-3.log'), complete('test (3)', 'test/three.test.ts'));+ writeFileSync(join(artifacts, 'timings-unit-4.log'), complete('test (4)', 'test/four.test.ts'));+ writeFileSync(info, JSON.stringify({ conclusion: 'success', headSha: 'fixture-commit', jobs: [{ name: 'test (1, 2)', conclusion: 'success' }, { name: 'test (3, 4)', conclusion: 'success' }] }));+ writeFileSync(out, '{"test/old.test.ts":42}\n');+ const args = [join(import.meta.dir, '../../scripts/mine-shard-weights.ts'), '--run', '123', '--out', out];+ const env = { ...process.env, PATH: `${bin}:${process.env.PATH}`, FIXTURE_GH_INFO: info, FIXTURE_GH_ARTIFACTS: artifacts };+ expect(spawnSync(process.execPath, args, { env, encoding: 'utf8' }).status).not.toBe(0);+ expect(readFileSync(out, 'utf8')).toBe('{"test/old.test.ts":42}\n');+ writeFileSync(join(artifacts, 'timings-unit-2.log'), complete('test (2)', 'test/two.test.ts'));+ const result = spawnSync(process.execPath, args, { env, encoding: 'utf8' });+ expect(result.status, result.stderr).toBe(0);+ expect(Object.keys(JSON.parse(readFileSync(out, 'utf8')))).toEqual(['test/four.test.ts', 'test/one.test.ts', 'test/three.test.ts', 'test/two.test.ts']);+ } finally { rmSync(dir, { recursive: true, force: true }); }+});diff --git a/test/scripts/test-shard-pack.test.ts b/test/scripts/test-shard-pack.test.tsnew file mode 100644index 0000000000..bb93d37acc--- /dev/null+++ b/test/scripts/test-shard-pack.test.ts@@ -0,0 +1,113 @@+/**+ * scripts/test-shard-pack.sh runs UNIT_SHARDS_PER_JOB unit shards at once on+ * one test.yml runner. Each shard must keep its own coverage dir, receipt dir,+ * timing capture and console, the shards must really run concurrently, and+ * the job must fail when any shard fails.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';++const REPO = join(import.meta.dir, '..', '..');+const roots: string[] = [];+afterEach(() => {+ for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });+});++// A stand-in for scripts/test-shard.sh: writes into the dirs it was handed,+// then waits until every shard of the pack has started (so a sequential run+// fails with 97), and exits with FIXTURE_EXIT_<shard>.+const FAKE_SHARD = String.raw`#!/usr/bin/env bash+set -euo pipefail+s=$1+mkdir -p "$COVERAGE_DIR" "$GBRAIN_TEST_RECEIPT_DIR"+echo "lane shard-$s" > "$COVERAGE_DIR/lane-manifest.json"+echo "receipt $s of $2" > "$GBRAIN_TEST_RECEIPT_DIR/unit.receipt"+echo "start $s"+touch "$FIXTURE_SYNC/$s"+for _ in $(seq 1 200); do+ [ "$(ls "$FIXTURE_SYNC" | wc -l)" -ge "$FIXTURE_EXPECT" ] && break+ sleep 0.05+done+[ "$(ls "$FIXTURE_SYNC" | wc -l)" -ge "$FIXTURE_EXPECT" ] || { echo "shard $s ran alone"; exit 97; }+echo "middle $s"+sleep 0.1+echo "end $s"+exit "$(printenv "FIXTURE_EXIT_$s" || echo 0)"+`;++function fixture() {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-shard-pack-'));+ roots.push(root);+ mkdirSync(join(root, 'scripts'));+ for (const file of ['scripts/test-shard-pack.sh', 'scripts/capture-test-log.ts']) copyFileSync(join(REPO, file), join(root, file));+ writeFileSync(join(root, 'scripts/test-shard.sh'), FAKE_SHARD);+ chmodSync(join(root, 'scripts/test-shard.sh'), 0o755);+ mkdirSync(join(root, 'sync'));+ return root;+}++function pack(root: string, args: string[], env: Record<string, string> = {}) {+ const out = join(root, 'out');+ const r = Bun.spawnSync(['bash', join(root, 'scripts/test-shard-pack.sh'), ...args], {+ cwd: root,+ env: {+ PATH: `${dirname(process.execPath)}:${process.env.PATH ?? '/usr/bin:/bin'}`,+ GBRAIN_SHARD_PACK_DIR: out,+ FIXTURE_SYNC: join(root, 'sync'),+ FIXTURE_EXPECT: String(args.length - 1),+ ...env,+ },+ timeout: 30_000,+ });+ return { out, code: r.exitCode, stdout: r.stdout.toString(), stderr: r.stderr.toString() };+}++describe('scripts/test-shard-pack.sh', () => {+ test('runs the shards at once, each with its own coverage, receipts, timing capture and console', () => {+ const root = fixture();+ const r = pack(root, ['18', '3', '4']);+ expect(r.stderr).toBe('');+ expect(r.code).toBe(0);+ for (const s of ['3', '4']) {+ expect(readFileSync(join(r.out, s, 'coverage/lane-manifest.json'), 'utf8')).toBe(`lane shard-${s}\n`);+ expect(readFileSync(join(r.out, s, 'receipts/unit.receipt'), 'utf8')).toBe(`receipt ${s} of 18\n`);+ const capture = readFileSync(join(r.out, s, 'unit.log'), 'utf8').trimEnd().split('\n');+ expect(capture.every(line => line.startsWith(`test (${s})\tcapture\t`))).toBe(true);+ expect(capture.at(-1)).toEndWith('##[gbrain-capture-complete] exit=0');+ const block = `=== unit shard ${s}/18 exited 0 ===\nstart ${s}\nmiddle ${s}\nend ${s}\n=== end of unit shard ${s}/18 ===\n`;+ expect(r.stdout).toContain(block);+ }+ expect(r.stdout).not.toContain('::error');+ });++ test('fails with the first failing shard\'s code, names it, and still lets the other shard finish', () => {+ const root = fixture();+ const r = pack(root, ['18', '5', '6'], { FIXTURE_EXIT_6: '3' });+ expect(r.code).toBe(3);+ expect(r.stdout).toContain('=== unit shard 5/18 exited 0 ===');+ expect(r.stdout).toContain('=== unit shard 6/18 exited 3 ===');+ expect(r.stdout).toContain('::error title=unit shard 6/18 failed::exit 3; reproduce with: bash scripts/test-shard.sh 6 18');+ expect(r.stdout).not.toContain('unit shard 5/18 failed');+ expect(readFileSync(join(r.out, '5', 'unit.log'), 'utf8').trimEnd()).toEndWith('##[gbrain-capture-complete] exit=0');+ expect(existsSync(join(r.out, '6', 'receipts/unit.receipt'))).toBe(true);+ });++ test('every failing shard gets its own error line', () => {+ const root = fixture();+ const r = pack(root, ['18', '7', '8'], { FIXTURE_EXIT_7: '1', FIXTURE_EXIT_8: '1' });+ expect(r.code).toBe(1);+ for (const s of ['7', '8']) expect(r.stdout).toContain(`::error title=unit shard ${s}/18 failed::`);+ });++ test('refuses a shard outside the partition and a missing output directory', () => {+ const root = fixture();+ const outside = pack(root, ['18', '18', '19']);+ expect(outside.code).toBe(2);+ expect(outside.stderr).toContain('shard index 19 out of range 1..18');+ const noDir = pack(root, ['18', '1', '2'], { GBRAIN_SHARD_PACK_DIR: '' });+ expect(noDir.code).not.toBe(0);+ expect(noDir.stderr).toContain('GBRAIN_SHARD_PACK_DIR');+ });+});