Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

ci(pg-arms): two files at a time per job, each worker on its own PostgreSQL service, 10 shards

garrytanefe55b5c420c
diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.yml
index 215d0de6a9..1cfd29732f 100644
--- a/.github/workflows/persistence-validation.yml
+++ b/.github/workflows/persistence-validation.yml
@@ -186,22 +186,27 @@ jobs:
# file; the PGLite arm also runs in the unit lane). The list is test/postgres-unit-arms.txt;
# scripts/check-postgres-lane-coverage.ts fails a new DATABASE_URL-gated arm
# until it is listed there or wrapped in a test/e2e registerPostgresTests
- # file. The nineteen shards (ARM_SHARDS in scripts/postgres-unit-arms.ts) are
- # balanced by measured runtime (scripts/postgres-arm-weights.json, mined from
- # this job's logs); each shard's measured sum, doubled for a slow runner, must
- # end a minute inside the step's 20 minutes (ARM_SHARD_BUDGET_MS).
+ # file. The ten shards (ARM_SHARDS in scripts/postgres-unit-arms.ts) are
+ # balanced by measured runtime (scripts/postgres-arm-weights.json, and
+ # scripts/postgres-arm-weights-postgres-only.json for the Bun 1.4.3 cell, mined
+ # from this job's ARM_FILE lines). Each job runs two files at a time, each
+ # worker against its own PostgreSQL service; a shard's two-worker makespan,
+ # doubled for a slow runner, must end a minute inside the step's 20 minutes
+ # (ARM_SHARD_BUDGET_MS). The Bun 1.4.3 cell runs only the PostgreSQL side of
+ # testBackends() suites (--postgres-only); their PGLite side runs in the unit
+ # and serial lanes on Bun 1.4.3, and the Bun 1.4.0 cell keeps both sides.
# Event parity (docs/ci-event-parity.md#full-ci-on-pull-requests): full profile only; a
# pull request (cheap tier) runs only the crash robot and convergence here. The
# full-ci dispatch on its head, every push and the nightly run this lane.
unit-postgres-arms:
- name: Unit-lane PostgreSQL arms ${{ matrix.shard }}/19 / Bun ${{ matrix.bun }}
+ name: Unit-lane PostgreSQL arms ${{ matrix.shard }}/10 / Bun ${{ matrix.bun }}
if: ${{ github.event_name != 'pull_request' }}
runs-on: ubicloud-standard-4-ubuntu-2404
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
- shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
+ shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
bun: ['1.4.0', '1.4.3']
# Event parity: every event, pull requests and merge-queue runs
# included, runs both supported Bun versions (docs/TESTING.md#event-parity).
@@ -216,6 +221,16 @@ jobs:
options: >-
--health-cmd "pg_isready -U gbrain_test -d gbrain_test"
--health-interval 5s --health-timeout 5s --health-retries 20
+ postgres2:
+ image: pgvector/pgvector:pg16
+ env:
+ POSTGRES_USER: gbrain_test
+ POSTGRES_PASSWORD: gbrain_test
+ POSTGRES_DB: gbrain_test
+ ports: ['5433:5432']
+ options: >-
+ --health-cmd "pg_isready -U gbrain_test -d gbrain_test"
+ --health-interval 5s --health-timeout 5s --health-retries 20
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6
@@ -224,50 +239,22 @@ jobs:
- name: Install dependencies (bounded, retried once)
timeout-minutes: 8
run: bun scripts/ci-bun-install.ts --frozen-lockfile --ignore-scripts
+ # One Bun process per file (*.serial.test.ts files require their own
+ # process, and a test that fails while its body keeps running would
+ # otherwise leak process.env into later files), two at a time, each worker
+ # against its own service. Each file writes its own executed-test receipt
+ # (JUnit included) for the executed-receipts ledger and nightly-watch's
+ # failure manifest, and its output prints whole inside one ::group:: block.
- name: Require PostgreSQL arms of unit-lane suites
timeout-minutes: 20
- shell: bash
env:
- DATABASE_URL: postgres://gbrain_test:[email protected]:5432/gbrain_test
+ GBRAIN_ARM_DATABASE_URLS: >-
+ postgres://gbrain_test:[email protected]:5432/gbrain_test
+ postgres://gbrain_test:[email protected]:5433/gbrain_test
GBRAIN_TEST_ALLOW_DATABASE_URL: '1'
- SHARD: ${{ matrix.shard }}
GBRAIN_TEST_RECEIPT_DIR: ${{ runner.temp }}/receipts
GBRAIN_TEST_RECEIPT_LANE: pg-arms-bun-${{ matrix.bun }}
- run: |
- : "${DATABASE_URL:?unit-lane PostgreSQL arms require the explicit test database}"
- # Executed-test receipts (one per file, JUnit included) feed the
- # executed-receipts ledger and nightly-watch's failure manifest, so a
- # master-red issue from this lane names the failing test.
- . scripts/lib/test-env.sh
- receipts_init pg-arms || exit 2
- # The list lives in test/postgres-unit-arms.txt (one path per line);
- # shards balance by measured runtime (scripts/postgres-arm-weights.json).
- selected=$(bun scripts/postgres-unit-arms.ts shard "$SHARD" 19)
- files=()
- while IFS= read -r file; do [ -n "$file" ] && files+=("$file"); done <<< "$selected"
- if [ "${#files[@]}" -eq 0 ]; then
- echo "::error::shard $SHARD/19 selected no files from test/postgres-unit-arms.txt. Why: an empty shard would pass without running any PostgreSQL arm. Fix: run 'bun scripts/postgres-unit-arms.ts shard $SHARD 19' locally and correct the list. Docs: docs/TESTING.md#postgres-arm-lanes" >&2
- exit 1
- fi
- # One bun process per file: *.serial.test.ts files require their own
- # process, and a test that fails while its body keeps running would
- # otherwise leak process.env into every later file (one such leak
- # deleted DATABASE_URL for the rest of a shard and silently dropped
- # those files' PostgreSQL arms).
- failed=()
- for file in "${files[@]}"; do
- echo "::group::$file"
- receipt_begin primary "s$SHARD-$(basename "$file" .ts)" "$SHARD" 8 postgres "$file"
- rc=0
- bun --no-env-file test --timeout=120000 ${RECEIPT_ARGS[@]+"${RECEIPT_ARGS[@]}"} "$file" || rc=$?
- receipt_end "$rc"
- [ "$rc" -eq 0 ] || failed+=("$file")
- echo "::endgroup::"
- done
- for file in ${failed[@]+"${failed[@]}"}; do
- echo "::error file=$file::PostgreSQL arm failed. Reproduce: DATABASE_URL=<pgvector test database> GBRAIN_TEST_ALLOW_DATABASE_URL=1 bun test --timeout=120000 $file"
- done
- [ "${#failed[@]}" -eq 0 ]
+ run: bun scripts/postgres-unit-arms.ts run ${{ matrix.shard }} 10
- name: Upload receipts
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
diff --git a/scripts/ci-ubicloud.ts b/scripts/ci-ubicloud.ts
index a42a8f99c8..25ea877627 100755
--- a/scripts/ci-ubicloud.ts
+++ b/scripts/ci-ubicloud.ts
@@ -73,7 +73,7 @@ import {
import { runScript, type RunScriptOpts } from "./ubicloud/run-script.ts";
import { expiringVmName } from "./ubicloud/reap-expired.ts";
import { buildTypecheckState, portableBuildInfo, typecheckBuildInfo } from "./ubicloud/typecheck-state.ts";
-import { ARM_SHARDS, ARM_STEP_TIMEOUT_MS, ARM_WEIGHTS, armShards, readArmsList } from "./postgres-unit-arms.ts";
+import { ARM_SHARDS, ARM_STEP_TIMEOUT_MS, ARM_WEIGHTS, ARM_WORKERS, armMakespan, armShards, readArmsList } from "./postgres-unit-arms.ts";
import { UNIT_JOB_TIMEOUT_MS, UNIT_SETUP_ALLOWANCE_MS, UNIT_SHARDS, unitShards } from "./sharding.ts";
const ROOT = resolve(import.meta.dir, "..");
@@ -542,16 +542,17 @@ async function main() {
for (const r of [...all].sort((a, b) => b.ms - a.ms).slice(0, 8)) console.log(` ${Math.round(r.ms / 1000)}s ${r.lane} ${r.file}`);
// The pg-arms lane's proof that unit-postgres-arms fits: each shard of the
- // workflow's own partition, summed from this run's measured file durations.
+ // workflow's own partition, its ARM_WORKERS workers' makespan over this run's
+ // measured file durations (both arms, as the Bun 1.4.0 cell runs them).
const armShardReport = opts.lanes.has("pg-arms")
? armShards(ROOT, arms.files, ARM_SHARDS).map((files, i) => ({
shard: i + 1,
files: files.length,
- ms: files.reduce((sum, file) => sum + (results.get(weightKey("pg-arms", file))?.ms ?? 0), 0),
+ ms: armMakespan(files, (file) => results.get(weightKey("pg-arms", file))?.ms ?? 0),
}))
: [];
if (armShardReport.length) {
- console.log(` pg-arms shards (unit-postgres-arms partition, ${ARM_SHARDS} shards, step timeout ${ARM_STEP_TIMEOUT_MS / 1000}s each):`);
+ console.log(` pg-arms shards (unit-postgres-arms partition, ${ARM_SHARDS} shards of ${ARM_WORKERS} workers, step timeout ${ARM_STEP_TIMEOUT_MS / 1000}s each):`);
for (const s of armShardReport) console.log(` ${s.shard}/${ARM_SHARDS}: ${Math.round(s.ms / 1000)}s across ${s.files} files`);
}
const overBudget = armShardReport.filter((s) => s.ms > ARM_STEP_TIMEOUT_MS);
diff --git a/scripts/postgres-unit-arms.ts b/scripts/postgres-unit-arms.ts
index 8c8a3b6f3c..491a88b7c1 100644
--- a/scripts/postgres-unit-arms.ts
+++ b/scripts/postgres-unit-arms.ts
@@ -3,35 +3,63 @@
* test/postgres-unit-arms.txt: the unit-lane suites whose PostgreSQL arm runs
* only in persistence-validation's `unit-postgres-arms` job and the race hunt.
*
- * bun scripts/postgres-unit-arms.ts list every listed path
- * bun scripts/postgres-unit-arms.ts shard <n> <m> shard n of m, balanced by measured runtime
- * bun scripts/postgres-unit-arms.ts mine <job.log>… rewrite scripts/postgres-arm-weights.json
- * from unit-postgres-arms job logs
+ * bun scripts/postgres-unit-arms.ts list every listed path
+ * bun scripts/postgres-unit-arms.ts shard <n> <m> [--postgres-only]
+ * shard n of m, balanced by measured runtime
+ * bun scripts/postgres-unit-arms.ts run <n> <m> [--postgres-only]
+ * run shard n of m, one file per worker at a time
+ * bun scripts/postgres-unit-arms.ts mine [--postgres-only] <job.log>…
+ * rewrite the cell's weights from unit-postgres-arms job logs
*
- * Weights are milliseconds per file (both arms, one Bun process) mined from
- * the job's `::group::<file>` timestamps; a file without a weight gets the
- * p75 (scripts/sharding.ts). The job runs ARM_SHARDS shards, each inside an
- * ARM_STEP_TIMEOUT_MS step; re-mine after adding heavy files.
- * test/scripts/postgres-unit-arms.test.ts fails when a shard's weighted sum
- * passes ARM_SHARD_BUDGET_MS, and ci:ubicloud's pg-arms lane fails when a
- * shard's measured sum passes the step timeout (scripts/ubicloud/README.md).
+ * `run` starts one worker per URL in GBRAIN_ARM_DATABASE_URLS (space-separated,
+ * one PostgreSQL server each; the job runs ARM_WORKERS). Workers take files
+ * heaviest first from one queue, one Bun process per file with DATABASE_URL set
+ * to the worker's server; each file's output is buffered and printed in queue
+ * order inside a `::group::` block that ends with an `ARM_FILE` line carrying
+ * its measured duration. With GBRAIN_TEST_RECEIPT_DIR set, each file writes its
+ * own executed-test receipt (scripts/lib/test-env.sh describes the format).
+ * `--postgres-only` (the Bun 1.4.3 cell) sets GBRAIN_TEST_BACKEND=postgres, so
+ * testBackends() suites run only their PostgreSQL side; their PGLite side runs
+ * in the unit and serial lanes, and files that read DATABASE_URL directly keep
+ * both arms.
+ *
+ * Weights are milliseconds per file mined from the `ARM_FILE` lines (older
+ * logs: each `::group::<file>` timestamp to the next group or endgroup); the
+ * both-arms cell reads ARM_WEIGHTS, the PostgreSQL-only cell
+ * ARM_WEIGHTS_POSTGRES_ONLY. A file without a weight gets the p75
+ * (scripts/sharding.ts). test/scripts/postgres-unit-arms.test.ts fails when a
+ * shard's two-worker makespan, scaled by ARM_CONCURRENCY_FACTOR, passes
+ * ARM_SHARD_BUDGET_MS, and ci:ubicloud's pg-arms lane fails when a shard's
+ * measured makespan passes the step timeout (scripts/ubicloud/README.md).
* Docs: docs/TESTING.md#postgres-arm-lanes.
*/
-import { existsSync, readFileSync, writeFileSync } from 'node:fs';
-import { join } from 'node:path';
-import { loadWeights, partition } from './sharding.ts';
+import { spawn } from 'node:child_process';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { basename, join } from 'node:path';
+import { loadWeights, partition, type WeightMap } from './sharding.ts';
export const ARMS_LIST = 'test/postgres-unit-arms.txt';
export const ARM_WEIGHTS = 'scripts/postgres-arm-weights.json';
+export const ARM_WEIGHTS_POSTGRES_ONLY = 'scripts/postgres-arm-weights-postgres-only.json';
/** persistence-validation's unit-postgres-arms matrix size; test/scripts/postgres-unit-arms.test.ts pins the workflow to it. */
-export const ARM_SHARDS = 19;
+export const ARM_SHARDS = 10;
+/** Files run at once per job, each against its own PostgreSQL service; the workflow lists one URL per worker. */
+export const ARM_WORKERS = 2;
/** The workflow step's `timeout-minutes: 20`: a shard whose files run longer is cut off mid-list. */
export const ARM_STEP_TIMEOUT_MS = 20 * 60 * 1000;
/**
- * A shard's weighted sum may be at most this: on a runner twice as slow as the mined weights (Bun 1.4.0 runners
- * measured 1.3-2x) it still ends a minute inside the step timeout.
+ * A shard's two-worker makespan may be at most this: on a runner twice as slow as the mined weights (Bun 1.4.0
+ * runners measured 1.3-2x) it still ends a minute inside the step timeout.
*/
export const ARM_SHARD_BUDGET_MS = (ARM_STEP_TIMEOUT_MS - 60_000) / 2;
+/**
+ * How much longer a file runs beside another file than alone, summed over a shard: two workers on a 4-vCPU
+ * runner measured 1.04x (GBRA-135 pilot: 8,777 s against 8,465 s of file time). Weights mined from solo runs
+ * are scaled by it before the budget check.
+ */
+export const ARM_CONCURRENCY_FACTOR = 1.04;
+/** Each file's command; ci:ubicloud's pg-arms lane (scripts/ubicloud/ci-item.sh) runs the same one. */
+export const ARM_TEST_COMMAND = ['bun', '--no-env-file', 'test', '--timeout=120000'];
const DOCS = 'docs/TESTING.md#postgres-arm-lanes';
const PATH_RE = /^test\/[\w./-]+\.test\.ts$/;
@@ -60,14 +88,23 @@ export function readArmsList(root: string): ArmsList {
}
/**
- * Per-file durations from GitHub job logs: each `##[group]<file>` line to the
- * next group or endgroup, the median across logs. The median balances shards
- * on a typical run; one slow runner's outlier would otherwise set a file's
- * weight (a max did, and pushed most of the slow suites into one shard).
+ * Per-file durations from GitHub job logs, the median across logs. A log with
+ * `ARM_FILE file=… ms=…` lines is read from those alone: its groups print when a
+ * file's buffered output is flushed, so their timestamps time nothing. An older
+ * log times each `##[group]<file>` line to the next group or endgroup. The
+ * median balances shards on a typical run; one slow runner's outlier would
+ * otherwise set a file's weight (a max did, and pushed most of the slow suites
+ * into one shard).
*/
export function mineArmWeights(logs: string[]): Map<string, number> {
const samples = new Map<string, number[]>();
+ const add = (file: string, ms: number) => samples.set(file, [...(samples.get(file) ?? []), ms]);
for (const log of logs) {
+ const explicit = [...log.matchAll(/ARM_FILE file=(test\/[\w./-]+\.test\.ts) worker=\d+ ms=(\d+) rc=\d+/g)];
+ if (explicit.length) {
+ for (const m of explicit) add(m[1]!, Number(m[2]));
+ continue;
+ }
let open: { file: string; at: number } | undefined;
for (const line of log.split('\n')) {
const m = /^(\d{4}-\d{2}-\d{2}T[\d:.]+Z)\s+(?:##\[group\]|::group::)(test\/[\w./-]+\.test\.ts)\s*$/.exec(line);
@@ -75,7 +112,7 @@ export function mineArmWeights(logs: string[]): Map<string, number> {
const at = m ? Date.parse(m[1]!) : end ? Date.parse(end[1]!) : NaN;
if (!Number.isFinite(at) || (!m && !open)) continue;
if (open && (m || end)) {
- samples.set(open.file, [...(samples.get(open.file) ?? []), at - open.at]);
+ add(open.file, at - open.at);
open = undefined;
}
if (m) open = { file: m[2]!, at };
@@ -88,14 +125,126 @@ export function mineArmWeights(logs: string[]): Map<string, number> {
}));
}
+/** The cell's weights: the PostgreSQL-only cell falls back to the both-arms weights until its own are mined. */
+export function armWeights(root: string, postgresOnly: boolean): WeightMap {
+ const own = join(root, ARM_WEIGHTS_POSTGRES_ONLY);
+ return loadWeights(postgresOnly && existsSync(own) ? own : join(root, ARM_WEIGHTS));
+}
+
/** Shard n of m (1-based), as persistence-validation's unit-postgres-arms matrix runs it and ci:ubicloud's pg-arms lane reports it. */
-export function armShards(root: string, files: string[], m: number): string[][] {
- return partition(files, loadWeights(join(root, ARM_WEIGHTS)), m).map(shard => [...shard].sort());
+export function armShards(root: string, files: string[], m: number, postgresOnly = false): string[][] {
+ return partition(files, armWeights(root, postgresOnly), m).map(shard => [...shard].sort());
+}
+
+/** A shard's files in the order the workers take them: heaviest first (LPT), ties by path. */
+export function armQueue(files: string[], weight: (file: string) => number): string[] {
+ return [...files].sort((a, b) => weight(b) - weight(a) || (a < b ? -1 : 1));
+}
+
+/** When the last of `workers` workers finishes `files`, each taking the next queued file when it frees up. */
+export function armMakespan(files: string[], weight: (file: string) => number, workers = ARM_WORKERS): number {
+ const busy = new Array<number>(workers).fill(0);
+ for (const file of armQueue(files, weight)) busy[busy.indexOf(Math.min(...busy))] += weight(file);
+ return Math.max(...busy);
+}
+
+interface FileRun { file: string; worker: number; ms: number; rc: number; out: string }
+
+/** One executed-test receipt per file, as scripts/lib/test-env.sh receipt_begin writes it. */
+function beginReceipt(dir: string, lane: string, shard: number, of: number, file: string): string {
+ const base = `${lane}--s${shard}-${basename(file, '.ts')}--primary`;
+ let id = base;
+ for (let n = 2; existsSync(join(dir, `${id}.receipt`)); n++) id = `${base}-${n}`;
+ const sha = process.env.GITHUB_SHA || (Bun.spawnSync(['git', 'rev-parse', 'HEAD']).stdout.toString().trim() || 'unknown');
+ const meta = {
+ version: 1, lane, kind: 'primary', tag: `s${shard}-${basename(file, '.ts')}`, shard, of, arm: 'postgres', sha, root: process.cwd(),
+ run_id: process.env.GITHUB_RUN_ID ?? '', run_attempt: process.env.GITHUB_RUN_ATTEMPT ?? '', job: process.env.GITHUB_JOB ?? '',
+ started: Math.floor(Date.now() / 1000),
+ };
+ writeFileSync(join(dir, `${id}.receipt`), Object.entries(meta).map(([k, v]) => `${k}=${v}\n`).join(''));
+ writeFileSync(join(dir, `${id}.files`), `${file}\n`);
+ return id;
+}
+
+async function run(root: string, shard: number, of: number, postgresOnly: boolean): Promise<number> {
+ const urls = (process.env.GBRAIN_ARM_DATABASE_URLS ?? '').split(/\s+/).filter(Boolean);
+ if (!urls.length) {
+ console.error(`::error::GBRAIN_ARM_DATABASE_URLS is empty. Why: each worker runs its files against its own PostgreSQL server. Fix: list one URL per worker (the job runs ${ARM_WORKERS}). Docs: ${DOCS}`);
+ return 2;
+ }
+ const weights = armWeights(root, postgresOnly);
+ const fallback = [...weights.values()].sort((a, b) => a - b)[Math.floor(weights.size * 0.75)] ?? 1;
+ const files = armQueue(armShards(root, readArmsList(root).files, of, postgresOnly)[shard - 1] ?? [], f => weights.get(f) ?? fallback);
+ if (!files.length) {
+ console.error(`::error::shard ${shard}/${of} selected no files from ${ARMS_LIST}. Why: an empty shard would pass without running any PostgreSQL arm. Fix: run 'bun scripts/postgres-unit-arms.ts shard ${shard} ${of}' locally and correct the list. Docs: ${DOCS}`);
+ return 1;
+ }
+ const receiptDir = process.env.GBRAIN_TEST_RECEIPT_DIR ?? '';
+ if (receiptDir) mkdirSync(receiptDir, { recursive: true });
+ const lane = process.env.GBRAIN_TEST_RECEIPT_LANE || 'pg-arms';
+ const env: Record<string, string | undefined> = { ...process.env, ...(postgresOnly ? { GBRAIN_TEST_BACKEND: 'postgres' } : {}) };
+ for (const name of ['GBRAIN_TEST_RECEIPT_DIR', 'GBRAIN_TEST_RECEIPT_LANE', 'GBRAIN_ARM_DATABASE_URLS']) delete env[name];
+ const workers = Math.min(urls.length, files.length);
+ console.log(`postgres-unit-arms: shard ${shard}/${of}, ${files.length} files, ${workers} workers${postgresOnly ? ', PostgreSQL side only (GBRAIN_TEST_BACKEND=postgres)' : ''}`);
+
+ const results: Array<FileRun | undefined> = new Array(files.length);
+ const running = new Map<number, { file: string; worker: number; chunks: Buffer[] }>();
+ let next = 0;
+ let printed = 0;
+ const started = Date.now();
+ const busy = new Array<number>(workers).fill(0);
+ const flush = () => {
+ for (; printed < files.length && results[printed]; printed++) {
+ const r = results[printed]!;
+ process.stdout.write(`::group::${r.file}\n${r.out}${r.out.endsWith('\n') || !r.out ? '' : '\n'}ARM_FILE file=${r.file} worker=${r.worker} ms=${r.ms} rc=${r.rc}\n::endgroup::\n`);
+ }
+ };
+ const runFile = (i: number, worker: number) => new Promise<FileRun>(resolve => {
+ const file = files[i]!;
+ const id = receiptDir ? beginReceipt(receiptDir, lane, shard, of, file) : '';
+ const args = [...ARM_TEST_COMMAND.slice(1), ...(id ? ['--reporter=junit', `--reporter-outfile=${join(receiptDir, `${id}.junit.xml`)}`] : []), file];
+ const chunks: Buffer[] = [];
+ running.set(i, { file, worker, chunks });
+ const t0 = Date.now();
+ const child = spawn(process.execPath, args, { env: { ...env, DATABASE_URL: urls[worker] }, stdio: ['ignore', 'pipe', 'pipe'] });
+ child.stdout.on('data', c => chunks.push(c));
+ child.stderr.on('data', c => chunks.push(c));
+ const done = (rc: number, note = '') => {
+ running.delete(i);
+ if (id) writeFileSync(join(receiptDir, `${id}.receipt`), `exit=${rc}\n`, { flag: 'a' });
+ resolve({ file, worker, ms: Date.now() - t0, rc, out: Buffer.concat(chunks).toString('utf8') + note });
+ };
+ child.on('error', error => done(127, `postgres-unit-arms: could not start bun: ${error.message}\n`));
+ child.on('close', (code, signal) => done(code ?? 1, signal ? `postgres-unit-arms: bun ended on ${signal}\n` : ''));
+ });
+ for (const signal of ['SIGINT', 'SIGTERM'] as const) {
+ process.on(signal, () => {
+ flush();
+ for (const r of running.values()) process.stdout.write(`::group::${r.file} (interrupted)\n${Buffer.concat(r.chunks).toString('utf8')}\n::endgroup::\n`);
+ console.log(`::error::shard ${shard}/${of} stopped on ${signal} with ${files.length - printed} file(s) unfinished; the step timeout (${ARM_STEP_TIMEOUT_MS / 60_000} minutes) or a cancellation ended it.`);
+ process.exit(130);
+ });
+ }
+ await Promise.all(Array.from({ length: workers }, async (_, worker) => {
+ while (next < files.length) {
+ const i = next++;
+ const r = await runFile(i, worker);
+ busy[worker] += r.ms;
+ results[i] = r;
+ flush();
+ }
+ }));
+ const failed = results.filter(r => r!.rc !== 0).map(r => r!.file);
+ const backend = postgresOnly ? 'GBRAIN_TEST_BACKEND=postgres ' : '';
+ for (const file of failed) console.log(`::error file=${file}::PostgreSQL arm failed. Reproduce: DATABASE_URL=<pgvector test database> GBRAIN_TEST_ALLOW_DATABASE_URL=1 ${backend}${ARM_TEST_COMMAND.join(' ')} ${file}`);
+ console.log(`ARM_SHARD shard=${shard}/${of} workers=${workers} files=${files.length} wall_ms=${Date.now() - started} busy_ms=${busy.join(',')} failed=${failed.length}`);
+ return failed.length ? 1 : 0;
}
-function main(argv: string[]): number {
+async function main(argv: string[]): Promise<number> {
const root = join(import.meta.dir, '..');
- const [command, ...rest] = argv;
+ const postgresOnly = argv.includes('--postgres-only');
+ const [command, ...rest] = argv.filter(a => a !== '--postgres-only');
const list = readArmsList(root);
if (command !== 'mine' && list.errors.length) {
console.error(`${list.errors.join('\n')}\n Why: the Postgres-arm lanes read this list; a bad row would drop or duplicate an arm.\n Fix: correct the named line in ${ARMS_LIST}\n Docs: ${DOCS}`);
@@ -105,25 +254,27 @@ function main(argv: string[]): number {
console.log(list.files.join('\n'));
return 0;
}
- if (command === 'shard') {
+ if (command === 'shard' || command === 'run') {
const [n, m] = rest.map(Number);
- if (!Number.isInteger(n) || !Number.isInteger(m) || n! < 1 || n! > m!) {
- console.error('usage: bun scripts/postgres-unit-arms.ts shard <n> <m> (1 <= n <= m)');
+ if (rest.length !== 2 || !Number.isInteger(n) || !Number.isInteger(m) || n! < 1 || n! > m!) {
+ console.error(`usage: bun scripts/postgres-unit-arms.ts ${command} <n> <m> [--postgres-only] (1 <= n <= m)`);
return 2;
}
- console.log(armShards(root, list.files, m!)[n! - 1]!.join('\n'));
+ if (command === 'run') return run(root, n!, m!, postgresOnly);
+ console.log(armShards(root, list.files, m!, postgresOnly)[n! - 1]!.join('\n'));
return 0;
}
if (command === 'mine' && rest.length) {
+ const target = postgresOnly ? ARM_WEIGHTS_POSTGRES_ONLY : ARM_WEIGHTS;
const mined = mineArmWeights(rest.map(path => readFileSync(path, 'utf8')));
const sorted = Object.fromEntries([...mined].sort(([a], [b]) => (a < b ? -1 : 1)));
- writeFileSync(join(root, ARM_WEIGHTS), `${JSON.stringify(sorted, null, 2)}\n`);
+ writeFileSync(join(root, target), `${JSON.stringify(sorted, null, 2)}\n`);
const missing = list.files.filter(f => !mined.has(f));
- console.log(`postgres-arm weights: ${mined.size} files mined into ${ARM_WEIGHTS}${missing.length ? `; no timing for ${missing.join(', ')}` : ''}`);
+ console.log(`postgres-arm weights: ${mined.size} files mined into ${target}${missing.length ? `; no timing for ${missing.join(', ')}` : ''}`);
return 0;
}
- console.error('usage: bun scripts/postgres-unit-arms.ts list | shard <n> <m> | mine <job.log>…');
+ console.error('usage: bun scripts/postgres-unit-arms.ts list | shard <n> <m> [--postgres-only] | run <n> <m> [--postgres-only] | mine [--postgres-only] <job.log>…');
return 2;
}
-if (import.meta.main) process.exit(main(process.argv.slice(2)));
+if (import.meta.main) process.exit(await main(process.argv.slice(2)));
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 16ce428c9d..1724e8a1c8 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -324,7 +324,7 @@ test/scripts/nightly-issue.test.ts nightly-watch incidents 9 readFileSync
test/scripts/nightly-issue.test.ts nightly-watch routing and guard 9 readFileSync
test/scripts/nightly-issue.test.ts operator messages carry docs anchors that resolve 1 readFileSync
test/scripts/postgres-lane-coverage.test.ts check-postgres-lane-coverage.ts 9 readFileSync
-test/scripts/postgres-unit-arms.test.ts postgres-unit-arms list 9 readFileSync
+test/scripts/postgres-unit-arms.test.ts postgres-unit-arms list 12 readFileSync
test/scripts/regen-all.test.ts regen:all 5 readFileSync
test/scripts/run-verify-parallel.test.ts guard registration ⇒ execution coverage 1 readFileSync
test/scripts/run-verify-parallel.test.ts run-verify-parallel.sh — no-timeout-binary fallback rc capture (regression) 7 readFileSync
diff --git a/test/scripts/postgres-unit-arms.test.ts b/test/scripts/postgres-unit-arms.test.ts
index 8a3e14cdf1..d0a86ff28e 100644
--- a/test/scripts/postgres-unit-arms.test.ts
+++ b/test/scripts/postgres-unit-arms.test.ts
@@ -1,15 +1,20 @@
/**
* test/postgres-unit-arms.txt is the one list persistence-validation's
* unit-postgres-arms job, the race hunt and the lane guard read. Its shards
- * must cover every row exactly once, and the weight miner must read the
- * job's per-file group timestamps.
+ * must cover every row exactly once, each shard's two workers must finish
+ * inside the step, and the weight miner must read the runner's per-file
+ * durations.
*/
import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'node:child_process';
-import { readFileSync } from 'node:fs';
+import { copyFileSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { ARM_SHARD_BUDGET_MS, ARM_SHARDS, ARM_STEP_TIMEOUT_MS, ARM_WEIGHTS, mineArmWeights, parseArmsList, readArmsList } from '../../scripts/postgres-unit-arms.ts';
-import { computeQuantile, loadWeights, partition } from '../../scripts/sharding.ts';
+import {
+ ARM_CONCURRENCY_FACTOR, ARM_SHARD_BUDGET_MS, ARM_SHARDS, ARM_STEP_TIMEOUT_MS, ARM_TEST_COMMAND, ARM_WORKERS,
+ armMakespan, armShards, armWeights, mineArmWeights, parseArmsList, readArmsList,
+} from '../../scripts/postgres-unit-arms.ts';
+import { computeQuantile } from '../../scripts/sharding.ts';
const REPO = join(import.meta.dir, '..', '..');
const cli = (...args: string[]) => spawnSync(process.execPath, [join(REPO, 'scripts', 'postgres-unit-arms.ts'), ...args], { encoding: 'utf8', cwd: REPO });
@@ -29,33 +34,49 @@ describe('postgres-unit-arms list', () => {
expect(shards.every(s => s.length > 0)).toBe(true);
});
- test('the workflow runs ARM_SHARDS shards inside the ARM_STEP_TIMEOUT_MS step timeout', () => {
+ test('the workflow runs ARM_SHARDS shards of ARM_WORKERS workers, each with its own PostgreSQL service, inside the ARM_STEP_TIMEOUT_MS step timeout', () => {
const workflow = readFileSync(join(REPO, '.github', 'workflows', 'persistence-validation.yml'), 'utf8');
const job = workflow.slice(workflow.indexOf(' unit-postgres-arms:'), workflow.indexOf('\n invariants:'));
const shards = Array.from({ length: ARM_SHARDS }, (_, i) => i + 1);
expect(job).toContain(`shard: [${shards.join(', ')}]`);
expect(job).toContain(`Unit-lane PostgreSQL arms \${{ matrix.shard }}/${ARM_SHARDS}`);
- expect(job).toContain(`postgres-unit-arms.ts shard "$SHARD" ${ARM_SHARDS})`);
- expect(job).toContain(`shard $SHARD/${ARM_SHARDS} selected no files`);
- expect(job).toContain(`postgres-unit-arms.ts shard $SHARD ${ARM_SHARDS}' locally`);
+ expect(job).toContain(`run: bun scripts/postgres-unit-arms.ts run \${{ matrix.shard }} ${ARM_SHARDS}\n`);
expect(job).toMatch(new RegExp(`- name: Require PostgreSQL arms of unit-lane suites\\n\\s+timeout-minutes: ${ARM_STEP_TIMEOUT_MS / 60_000}\\n`));
+ const ports = [...job.matchAll(/ports: \['(\d+):5432'\]/g)].map(m => m[1]);
+ const urls = [...job.matchAll(/postgres:\/\/gbrain_test:gbrain_test@127\.0\.0\.1:(\d+)\/gbrain_test/g)].map(m => m[1]);
+ expect(ports.length).toBe(ARM_WORKERS);
+ expect(new Set(ports).size).toBe(ARM_WORKERS);
+ expect(urls).toEqual(ports);
});
- test('every CI shard\'s measured weight fits the step twice over, with a minute to spare', () => {
+ test('every CI shard\'s two-worker makespan fits the step twice over, with a minute to spare, in both Bun cells', () => {
const files = readArmsList(REPO).files;
- const weights = loadWeights(join(REPO, ARM_WEIGHTS));
- const p75 = computeQuantile(files.filter(f => weights.has(f)).map(f => weights.get(f)!), 0.75);
- const sums = partition(files, weights, ARM_SHARDS).map(shard => shard.reduce((ms, f) => ms + (weights.get(f) ?? p75), 0));
expect(2 * ARM_SHARD_BUDGET_MS + 60_000).toBe(ARM_STEP_TIMEOUT_MS);
- expect(sums.filter(ms => ms > ARM_SHARD_BUDGET_MS)).toEqual([]);
+ for (const postgresOnly of [false, true]) {
+ const weights = armWeights(REPO, postgresOnly);
+ const p75 = computeQuantile(files.filter(f => weights.has(f)).map(f => weights.get(f)!), 0.75);
+ const makespans = armShards(REPO, files, ARM_SHARDS, postgresOnly).map(shard => armMakespan(shard, f => weights.get(f) ?? p75) * ARM_CONCURRENCY_FACTOR);
+ expect({ postgresOnly, over: makespans.filter(ms => ms > ARM_SHARD_BUDGET_MS).map(Math.round) }).toEqual({ postgresOnly, over: [] });
+ }
});
- test('ci:ubicloud\'s pg-arms lane runs each file with the workflow step\'s own command', () => {
- const command = 'bun --no-env-file test --timeout=120000';
- const workflow = readFileSync(join(REPO, '.github', 'workflows', 'persistence-validation.yml'), 'utf8');
+ test('a shard\'s makespan is the busiest worker when each takes the next heaviest file as it frees up', () => {
+ const w: Record<string, number> = { 'test/a.test.ts': 50, 'test/b.test.ts': 40, 'test/c.test.ts': 30, 'test/d.test.ts': 20, 'test/e.test.ts': 10 };
+ expect(armMakespan(Object.keys(w), f => w[f]!, 2)).toBe(80);
+ expect(armMakespan(Object.keys(w), f => w[f]!, 1)).toBe(150);
+ });
+
+ test('no listed file is machine-exclusive: two files share each runner', () => {
+ const exclusive = spawnSync('bash', ['scripts/run-serial-tests.sh', '--dry-run-list-exclusive'], { encoding: 'utf8', cwd: REPO }).stdout.trim().split('\n').filter(Boolean);
+ expect(exclusive.length).toBeGreaterThan(0);
+ expect(readArmsList(REPO).files.filter(f => exclusive.includes(f))).toEqual([]);
+ });
+
+ test('ci:ubicloud\'s pg-arms lane runs each file with the workflow runner\'s own command', () => {
+ const command = ARM_TEST_COMMAND.join(' ');
+ expect(command).toBe('bun --no-env-file test --timeout=120000');
const item = readFileSync(join(REPO, 'scripts', 'ubicloud', 'ci-item.sh'), 'utf8');
const lane = item.slice(item.indexOf(' pg-arms)'), item.indexOf(';;', item.indexOf(' pg-arms)')));
- expect(workflow).toContain(command);
expect(lane).toContain(`${command} "$1"`);
expect(lane).toContain('GBRAIN_TEST_ALLOW_DATABASE_URL=1');
expect(lane).toContain('-u GBRAIN_TEST_TIMEOUT_MULTIPLIER');
@@ -82,6 +103,19 @@ describe('postgres-unit-arms list', () => {
expect(Object.fromEntries(mineArmWeights([log]))).toEqual({ 'test/a.test.ts': 10000, 'test/b.serial.test.ts': 1500 });
});
+ test('a log with ARM_FILE lines is mined from those alone, since its groups print at flush time', () => {
+ const log = [
+ '2026-10-05T18:50:00.0000000Z ##[group]test/a.test.ts',
+ '2026-10-05T18:50:00.0100000Z (pass) a',
+ '2026-10-05T18:50:00.0200000Z ARM_FILE file=test/a.test.ts worker=0 ms=41000 rc=0',
+ '2026-10-05T18:50:00.0300000Z ##[endgroup]',
+ '2026-10-05T18:50:00.0400000Z ##[group]test/b.serial.test.ts',
+ '2026-10-05T18:50:00.0500000Z ARM_FILE file=test/b.serial.test.ts worker=1 ms=7500 rc=1',
+ '2026-10-05T18:50:00.0600000Z ##[endgroup]',
+ ].join('\n');
+ expect(Object.fromEntries(mineArmWeights([log]))).toEqual({ 'test/a.test.ts': 41000, 'test/b.serial.test.ts': 7500 });
+ });
+
test('a file timed in several logs weighs its median, so one slow runner does not set it', () => {
const log = (seconds: number) => [
`2026-10-05T18:44:00.0000000Z ##[group]test/a.test.ts`,
@@ -91,3 +125,79 @@ describe('postgres-unit-arms list', () => {
expect(mineArmWeights([log(10), log(50), log(12), log(14)]).get('test/a.test.ts')).toBe(13000);
});
});
+
+describe('postgres-unit-arms run', () => {
+ /** A copy of the runner in a scratch repo whose listed files only report what they saw and sleep. */
+ function scratchRepo(files: Record<string, string>): string {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-arms-run-'));
+ mkdirSync(join(root, 'scripts'), { recursive: true });
+ for (const name of ['postgres-unit-arms.ts', 'sharding.ts']) copyFileSync(join(REPO, 'scripts', name), join(root, 'scripts', name));
+ writeFileSync(join(root, 'scripts', 'postgres-arm-weights.json'), JSON.stringify(Object.fromEntries(Object.keys(files).map((f, i) => [f, 1000 * (i + 1)]))));
+ mkdirSync(join(root, 'test'), { recursive: true });
+ writeFileSync(join(root, 'test', 'postgres-unit-arms.txt'), `${Object.keys(files).sort().join('\n')}\n`);
+ for (const [file, body] of Object.entries(files)) writeFileSync(join(root, file), body);
+ return root;
+ }
+ const probe = (name: string, extra = '') => `import { test, expect } from 'bun:test';
+test('${name}', async () => {
+ console.log('saw ' + JSON.stringify({ url: process.env.DATABASE_URL, backend: process.env.GBRAIN_TEST_BACKEND ?? '', receipts: process.env.GBRAIN_TEST_RECEIPT_DIR ?? '' }));
+ await Bun.sleep(1500);
+ ${extra}
+});
+`;
+
+ test('two workers run files at once against their own URLs, print each file whole in queue order and write a receipt per file', () => {
+ const root = scratchRepo({
+ 'test/a.test.ts': probe('a'),
+ 'test/b.test.ts': probe('b'),
+ 'test/c.serial.test.ts': probe('c', "expect('c').toBe('fails');"),
+ });
+ try {
+ const receipts = join(root, 'receipts');
+ const t0 = Date.now();
+ const r = spawnSync(process.execPath, [join(root, 'scripts', 'postgres-unit-arms.ts'), 'run', '1', '1', '--postgres-only'], {
+ cwd: root, encoding: 'utf8',
+ env: { ...process.env, GBRAIN_ARM_DATABASE_URLS: 'postgres://one/db postgres://two/db', GBRAIN_TEST_RECEIPT_DIR: receipts, GBRAIN_TEST_RECEIPT_LANE: 'pg-arms-bun-test', GITHUB_SHA: 'abc' },
+ });
+ const wall = Date.now() - t0;
+ expect(r.status).toBe(1);
+ const groups = [...r.stdout.matchAll(/::group::(\S+)\n([\s\S]*?)ARM_FILE file=(\S+) worker=(\d) ms=(\d+) rc=(\d+)\n::endgroup::/g)];
+ expect(groups.map(g => g[1])).toEqual(['test/c.serial.test.ts', 'test/b.test.ts', 'test/a.test.ts']);
+ expect(groups.every(g => g[1] === g[3])).toBe(true);
+ expect(groups.map(g => g[6])).toEqual(['1', '0', '0']);
+ const saw = groups.map(g => JSON.parse(/saw (\{.*\})/.exec(g[2]!)![1]!));
+ expect(new Set(saw.map(s => s.url))).toEqual(new Set(['postgres://one/db', 'postgres://two/db']));
+ expect(saw.map(s => s.url)).toEqual(groups.map(g => (g[4] === '0' ? 'postgres://one/db' : 'postgres://two/db')));
+ expect(saw.every(s => s.backend === 'postgres' && s.receipts === '')).toBe(true);
+ expect(wall).toBeLessThan(groups.reduce((ms, g) => ms + Number(g[5]), 0));
+ expect(r.stdout).toContain('::error file=test/c.serial.test.ts::PostgreSQL arm failed. Reproduce: DATABASE_URL=<pgvector test database> GBRAIN_TEST_ALLOW_DATABASE_URL=1 GBRAIN_TEST_BACKEND=postgres bun --no-env-file test --timeout=120000 test/c.serial.test.ts');
+ const ids = readdirSync(receipts).filter(n => n.endsWith('.receipt')).map(n => n.slice(0, -'.receipt'.length)).sort();
+ expect(ids).toEqual(['pg-arms-bun-test--s1-a.test--primary', 'pg-arms-bun-test--s1-b.test--primary', 'pg-arms-bun-test--s1-c.serial.test--primary']);
+ for (const id of ids) {
+ const meta = readFileSync(join(receipts, `${id}.receipt`), 'utf8');
+ expect(meta).toContain('lane=pg-arms-bun-test\n');
+ expect(meta).toContain('shard=1\nof=1\narm=postgres\n');
+ expect(meta).toMatch(/\nexit=[01]\n$/);
+ expect(readFileSync(join(receipts, `${id}.files`), 'utf8').trim().split('\n')).toHaveLength(1);
+ expect(readFileSync(join(receipts, `${id}.junit.xml`), 'utf8')).toContain('<testcase');
+ }
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ }, 60_000);
+
+ test('without --postgres-only the files keep both arms, and no URL is a usage error', () => {
+ const root = scratchRepo({ 'test/a.test.ts': probe('a') });
+ try {
+ const run = (urls: string) => spawnSync(process.execPath, [join(root, 'scripts', 'postgres-unit-arms.ts'), 'run', '1', '1'], { cwd: root, encoding: 'utf8', env: { ...process.env, GBRAIN_ARM_DATABASE_URLS: urls, GBRAIN_TEST_BACKEND: '' } });
+ const ok = run('postgres://one/db');
+ expect(ok.status).toBe(0);
+ expect(JSON.parse(/saw (\{.*\})/.exec(ok.stdout)![1]!).backend).toBe('');
+ const none = run('');
+ expect(none.status).toBe(2);
+ expect(none.stderr).toContain('GBRAIN_ARM_DATABASE_URLS is empty');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ }, 60_000);
+});