Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(backup): retry the Windows private-path PowerShell once after a cold-start timeout; ci(e2e): nightly order hunt runs E2E files in a seeded random order on one database
garrytan7c564afdbc18
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.ymlindex b4315e9019..ada6692d56 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e.yml@@ -20,6 +20,14 @@ on:description: Run the complete scheduled coverage profiletype: booleandefault: false+ order_hunt:+ description: Run the order hunt (E2E files in a seeded random order on one shared database)+ type: boolean+ default: false+ order_seed:+ description: Order hunt seed (empty = the UTC day number)+ type: string+ default: ''permissions:contents: read@@ -699,6 +707,71 @@ jobs:if-no-files-found: ignoreoverwrite: true+ # Order hunt: every E2E file in a seeded random order, sequential on one+ # shared database per shard, to catch a file that leaks state into the next+ # (per-iteration fresh databases in the stress gate and race hunt cannot).+ # Keyless, outside e2e-status. Docs: docs/ci-red-runbook.md#order-hunt+ order-hunt:+ # Named exception: nightly E2E schedule and order_hunt dispatch only (docs/TESTING.md#event-parity).+ if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.order_hunt)+ runs-on: ubicloud-standard-4-ubuntu-2404+ timeout-minutes: 75+ strategy:+ fail-fast: false+ matrix:+ shard: [1, 2, 3, 4]+ services:+ postgres:+ image: pgvector/pgvector:pg16+ env:+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: gbrain_test+ ports:+ - 5432:5432+ options: >-+ --health-cmd pg_isready+ --health-interval 10s+ --health-timeout 5s+ --health-retries 5+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2+ with:+ bun-version: 1.4.2+ - run: bun install --frozen-lockfile+ - name: Plan this shard's order+ shell: bash+ env:+ ORDER_SEED: ${{ inputs.order_seed }}+ SHARD: ${{ matrix.shard }}+ run: |+ seed="${ORDER_SEED:-$(( $(date -u +%s) / 86400 ))}"+ case "$seed" in ''|*[!0-9]*) echo "::error::order_seed must be digits, got '$seed'"; exit 2 ;; esac+ seed=$(( seed * 4 + SHARD ))+ bun scripts/order-hunt.ts plan --seed "$seed" --shard "$SHARD" --of 4 > "$RUNNER_TEMP/order.txt"+ echo "order hunt: seed $seed, shard $SHARD/4, $(wc -l < "$RUNNER_TEMP/order.txt") files" | tee -a "$GITHUB_STEP_SUMMARY"+ - name: Run the files in that order on one database+ id: run+ continue-on-error: true+ shell: bash+ env:+ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'+ GBRAIN_CI_DISABLE_TEST_ENV_FILE: '1'+ GBRAIN_MODEL_DISCOVERY: 'off'+ run: |+ mapfile -t files < "$RUNNER_TEMP/order.txt"+ bash scripts/run-e2e.sh "${files[@]}" 2>&1 | tee "$RUNNER_TEMP/order-hunt.log"+ - name: Classify failures (order-dependent vs failing alone)+ if: steps.run.outcome == 'failure'+ shell: bash+ env:+ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/gbrain_test+ GBRAIN_TEST_ALLOW_DATABASE_URL: '1'+ GBRAIN_CI_DISABLE_TEST_ENV_FILE: '1'+ GBRAIN_MODEL_DISCOVERY: 'off'+ run: bun scripts/order-hunt.ts classify --order "$RUNNER_TEMP/order.txt" --log "$RUNNER_TEMP/order-hunt.log"+coverage-full-serial:# Named exception: nightly E2E schedule only (docs/TESTING.md#event-parity).if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && inputs.full_corpus)diff --git a/docs/ci-event-parity.md b/docs/ci-event-parity.mdindex e47ba98199..a85d7b1a2f 100644--- a/docs/ci-event-parity.md+++ b/docs/ci-event-parity.md@@ -24,6 +24,7 @@ and `e2e-status` aggregators, never on per-cell matrix names.| `test.yml` | `export-scale` pages, 10,001 vs 100,001 | Named exception | Every push to master and the nightly Test schedule || `test.yml`, `stress.yml` | `stress-changed-tests` file set | Named exception: PR-only gate; succeeds with "not a PR event" elsewhere | Push and nightly runs run every file; the nightly race hunt repeats the Postgres arms || `test.yml` | `race-hunt` | Named exception: schedule and dispatch only, outside `test-status` | Itself (nightly Test schedule) |+| `e2e.yml` | `order-hunt` | Named exception: schedule and `order_hunt` dispatch only, outside `e2e-status` | Itself (nightly E2E schedule) || `test.yml` | `native_only`, `race_hunt`, `stress_*` dispatch inputs; concurrency suffixes | Parity: manual modes and run grouping, never applied to PR, push or schedule events | — || `persistence-validation.yml` | Bun matrix of read latency, deployment matrix, unit-lane PostgreSQL arms, soak, crash robot, reconciliation | Parity: both Bun versions on every event | — || `persistence-validation.yml` | `SOAK_OPERATIONS` 2,500 vs 10,000 | Named exception | Every push to master and the nightly Test schedule |diff --git a/docs/ci-red-runbook.md b/docs/ci-red-runbook.mdindex 539436c809..7aa94ff892 100644--- a/docs/ci-red-runbook.md+++ b/docs/ci-red-runbook.md@@ -74,6 +74,14 @@ find the race, and open a repair PR with `Fixes #<issue>`. Never widen atimeout or weaken an assertion. When the signature names a runner, disk orsecret problem, ask the repository owner for that fix instead of a code PR.+## Order hunt++The nightly E2E workflow's `order-hunt` job (also `gh workflow run e2e.yml -f order_hunt=true`, optionally `-f order_seed=N`) runs every E2E file in a seeded random order, sequentially, on one shared Postgres database per shard. It catches a file that leaves state behind (a config row, a session setting, leftover rows) that breaks the next file, which the stress gate and race hunt cannot see because each of their iterations gets a fresh database.++- **Seed:** the UTC day number by default, so each night tries a different order; the seed and shard are in the step summary.+- **A failure** is rerun alone. A file that passes alone is reported as `order-dependent test` with `bash scripts/run-e2e.sh <the files before it, in order> <file>` to replay it; bisect the files before it to find the one that leaks, and fix that file's teardown. A file that also fails alone is only a warning here, since the full E2E lanes report it.+- The job is keyless and outside `e2e-status`, so it never blocks a PR; a red order hunt turns the E2E nightly red.+## CI failure manifestThe `executed-receipts` job of test.yml and e2e.yml runs `scripts/ci-manifest.ts`diff --git a/scripts/order-hunt.ts b/scripts/order-hunt.tsnew file mode 100644index 0000000000..ef7404e33e--- /dev/null+++ b/scripts/order-hunt.ts@@ -0,0 +1,116 @@+#!/usr/bin/env bun+/**+ * Order hunt: run the E2E corpus in a seeded random order on one shared+ * Postgres database to catch tests that leak state into the next file (a+ * config row left at teardown, a session setting, leftover pages). Per-iteration+ * fresh databases (the stress gate, the race hunt) cannot see this class.+ *+ * bun scripts/order-hunt.ts plan --seed N --shard K --of M+ * prints this shard's files, one per line, in run order: the run-e2e.sh+ * corpus shuffled by the seed, then dealt round-robin into M shards.+ * bun scripts/order-hunt.ts classify --order FILE --log FILE+ * reads the ordered file list and run-e2e.sh's log, reruns each failing+ * file alone, and reports a file that passes alone as order-dependent with+ * the exact reproduce command. Exit 1 only for order-dependent failures; a+ * file that also fails alone is a plain failure the other lanes report.+ *+ * Docs: docs/ci-red-runbook.md#order-hunt+ */+import { readFileSync } from 'node:fs';+import { spawnSync } from 'node:child_process';++const DOCS = 'docs/ci-red-runbook.md#order-hunt';++/** mulberry32: small, deterministic, good enough to shuffle a file list. */+export function seededRandom(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6D2B79F5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++export function planShard(files: readonly string[], seed: number, shard: number, of: number): string[] {+ const order = [...files].sort();+ const random = seededRandom(seed);+ for (let i = order.length - 1; i > 0; i--) {+ const j = Math.floor(random() * (i + 1));+ [order[i], order[j]] = [order[j]!, order[i]!];+ }+ return order.filter((_, i) => i % of === shard - 1);+}++/** The `Failing files:` block run-e2e.sh prints, as basenames. */+export function failingFiles(log: string): string[] {+ const start = log.lastIndexOf('\nFailing files:\n');+ if (start < 0) return [];+ const out: string[] = [];+ for (const line of log.slice(start + '\nFailing files:\n'.length).split('\n')) {+ const m = /^ {2}- (\S+)$/.exec(line);+ if (!m) break;+ out.push(m[1]!);+ }+ return out;+}++export function reproduceCommand(order: readonly string[], file: string): string {+ const idx = order.indexOf(file);+ return `bash scripts/run-e2e.sh ${order.slice(0, idx + 1).join(' ')}`;+}++function arg(argv: string[], name: string): string {+ const i = argv.indexOf(name);+ const v = i >= 0 ? argv[i + 1] : undefined;+ if (!v) throw new Error(`missing ${name}`);+ return v;+}++function positiveInt(value: string, name: string): number {+ const n = Number(value);+ if (!Number.isInteger(n) || n < 0) throw new Error(`${name} must be a non-negative integer, got ${value}`);+ return n;+}++function plan(argv: string[]): number {+ const seed = positiveInt(arg(argv, '--seed'), '--seed');+ const of = positiveInt(arg(argv, '--of'), '--of');+ const shard = positiveInt(arg(argv, '--shard'), '--shard');+ if (of < 1 || shard < 1 || shard > of) throw new Error(`--shard must be 1..${of}`);+ const listed = spawnSync('bash', ['scripts/run-e2e.sh', '--dry-run-list'], { encoding: 'utf8' });+ if (listed.status !== 0) throw new Error(`run-e2e.sh --dry-run-list failed: ${listed.stderr.trim()}`);+ const files = listed.stdout.split('\n').filter(Boolean);+ for (const f of planShard(files, seed, shard, of)) console.log(f);+ return 0;+}++function classify(argv: string[]): number {+ const order = readFileSync(arg(argv, '--order'), 'utf8').split('\n').filter(Boolean);+ const failing = failingFiles(readFileSync(arg(argv, '--log'), 'utf8'));+ let orderDependent = 0;+ for (const name of failing) {+ const file = order.find(f => f.endsWith(`/${name}`) || f === name);+ if (!file) { console.log(`::warning title=order hunt::${name} failed but is not in this shard's order list; read the run-e2e.sh log. Docs: ${DOCS}`); continue; }+ const alone = spawnSync('bash', ['scripts/run-e2e.sh', file], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+ if (alone.status === 0) {+ orderDependent++;+ console.log(`::error file=${file},title=order-dependent test::${file} fails after the files before it in this order but passes alone, so an earlier file leaks state into it. Why: a test that leaves a config row, setting or rows behind breaks the next file on a shared database. Reproduce: ${reproduceCommand(order, file)} (then bisect the files before it). Fix the leaking file's teardown, not this file. Docs: ${DOCS}`);+ } else {+ console.log(`::warning file=${file},title=order hunt::${file} also fails on its own, so it is not an order leak; the full E2E lanes report it. Reproduce: bash scripts/run-e2e.sh ${file}. Docs: ${DOCS}`);+ }+ }+ if (!failing.length) console.log('order hunt: no failing files in this order.');+ return orderDependent ? 1 : 0;+}++if (import.meta.main) {+ const [cmd, ...rest] = process.argv.slice(2);+ try {+ process.exit(cmd === 'plan' ? plan(rest) : cmd === 'classify' ? classify(rest) : (console.error('usage: bun scripts/order-hunt.ts plan --seed N --shard K --of M | classify --order FILE --log FILE'), 2));+ } catch (e) {+ console.error(`order-hunt: ${(e as Error).message}. Docs: ${DOCS}`);+ process.exit(2);+ }+}diff --git a/src/core/backup/private-path.ts b/src/core/backup/private-path.tsindex e0f2b078d4..b2d56748a0 100644--- a/src/core/backup/private-path.ts+++ b/src/core/backup/private-path.ts@@ -42,24 +42,40 @@ foreach ($rule in $rules) {[Console]::Write('private')`;+/**+ * PowerShell's first start on a cold Windows machine can take longer than the+ * 15 s bound (measured 3.3-27.7 s on fresh CI runners; later starts take+ * 0.2-1.5 s), which failed a user's first backup. A run killed by that bound is+ * retried once; any other failure, or a second timeout, is final. The script+ * only sets and verifies the ACL of the same new empty path, so a rerun is safe.+ */+export async function withColdStartRetry<T>(run: () => Promise<T>): Promise<T> {+ try {+ return await run();+ } catch (error) {+ if ((error as { killed?: boolean } | null)?.killed !== true) throw error;+ return await run();+ }+}+export async function protectNewBackupPath(path: string, kind: 'directory' | 'file'): Promise<void> {if (process.platform !== 'win32') return;try {assertNoSymlinks(path);const before = lstatSync(path, { bigint: true });if (!before.ino || (kind === 'directory' ? !before.isDirectory() || readdirSync(path).length !== 0 : !before.isFile() || before.size !== 0n || before.nlink !== 1n)) throw new Error('Expected a new empty path with stable identity');- const result = await new Promise<string>((resolve, reject) => {+ const result = await withColdStartRetry(() => new Promise<string>((resolve, reject) => {let inputFailed = false;const child = execFile(join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(protect, 'utf16le').toString('base64')], {env: { ...process.env, GBRAIN_BACKUP_PRIVATE_PATH: path, GBRAIN_BACKUP_PRIVATE_KIND: kind },encoding: 'utf8', timeout: 15_000, maxBuffer: 64 * 1024, windowsHide: true,- }, (error, stdout) => error || inputFailed ? reject(error ?? new Error('Private path input failed')) : resolve(stdout));+ }, (error, stdout) => inputFailed ? reject(new Error('Private path input failed')) : error ? reject(error) : resolve(stdout));const inputFailure = () => { inputFailed = true; child.kill(); };if (!child.stdin) { inputFailure(); return; }child.stdin.once('error', inputFailure);try { child.stdin.end(); } catch { inputFailure(); }- });+ }));assertNoSymlinks(path);const after = lstatSync(path, { bigint: true });if (result !== 'private' || before.dev !== after.dev || before.ino !== after.inodiff --git a/test/backup-private-path-retry.test.ts b/test/backup-private-path-retry.test.tsnew file mode 100644index 0000000000..945ce7b963--- /dev/null+++ b/test/backup-private-path-retry.test.ts@@ -0,0 +1,36 @@+import { describe, expect, test } from 'bun:test';+import { withColdStartRetry } from '../src/core/backup/private-path.ts';++// A PowerShell cold start can outrun the 15 s bound on a fresh Windows machine+// (protectNewBackupPath). These cases pin the retry policy on every platform;+// the Windows ACL path itself runs in backup-portability-native.serial.test.ts.+const timedOut = () => Object.assign(new Error('Command failed: powershell.exe'), { killed: true, signal: 'SIGTERM' });++describe('withColdStartRetry', () => {+ test('a run killed by the timeout is retried once and its second result returned', async () => {+ let calls = 0;+ const result = await withColdStartRetry(async () => { calls++; if (calls === 1) throw timedOut(); return 'private'; });+ expect(result).toBe('private');+ expect(calls).toBe(2);+ });++ test('a second timeout is final', async () => {+ let calls = 0;+ await expect(withColdStartRetry(async () => { calls++; throw timedOut(); })).rejects.toMatchObject({ killed: true });+ expect(calls).toBe(2);+ });++ test('any other failure is not retried', async () => {+ for (const failure of [new Error('Access rule mismatch'), new Error('Private path input failed'), Object.assign(new Error('exit 1'), { killed: false, code: 1 })]) {+ let calls = 0;+ await expect(withColdStartRetry(async () => { calls++; throw failure; })).rejects.toBe(failure);+ expect(calls).toBe(1);+ }+ });++ test('a first success runs once', async () => {+ let calls = 0;+ expect(await withColdStartRetry(async () => { calls++; return 'private'; })).toBe('private');+ expect(calls).toBe(1);+ });+});diff --git a/test/scripts/order-hunt.test.ts b/test/scripts/order-hunt.test.tsnew file mode 100644index 0000000000..cbb1b58691--- /dev/null+++ b/test/scripts/order-hunt.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from 'bun:test';+import { failingFiles, planShard, reproduceCommand } from '../../scripts/order-hunt.ts';++const files = Array.from({ length: 40 }, (_, i) => `test/e2e/f${String(i).padStart(2, '0')}.test.ts`);++describe('order hunt plan', () => {+ test('shards partition the corpus exactly once, deterministically per seed', () => {+ const shards = [1, 2, 3, 4].map(k => planShard(files, 7, k, 4));+ expect(shards.flat().sort()).toEqual([...files].sort());+ expect(new Set(shards.flat()).size).toBe(files.length);+ expect(planShard(files, 7, 2, 4)).toEqual(shards[1]);+ expect(planShard([...files].reverse(), 7, 2, 4)).toEqual(shards[1]);+ });++ test('a different seed gives a different order', () => {+ expect(planShard(files, 1, 1, 1)).not.toEqual(planShard(files, 2, 1, 1));+ expect(planShard(files, 1, 1, 1)).not.toEqual([...files].sort());+ });+});++describe('order hunt classify helpers', () => {+ test('reads run-e2e.sh failing-file block', () => {+ const log = 'noise\n\nFailing files:\n - a.test.ts\n - b.test.ts\n\ntrailer\n';+ expect(failingFiles(log)).toEqual(['a.test.ts', 'b.test.ts']);+ expect(failingFiles('all green\n')).toEqual([]);+ });++ test('the reproduce command replays the exact order up to the failing file', () => {+ expect(reproduceCommand(['test/e2e/x.test.ts', 'test/e2e/y.test.ts', 'test/e2e/z.test.ts'], 'test/e2e/y.test.ts'))+ .toBe('bash scripts/run-e2e.sh test/e2e/x.test.ts test/e2e/y.test.ts');+ });+});