Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test(A10): GBRAIN_TEST_WAIT_MULTIPLIER scales waitFor deadlines in coverage lanes

garrytan4221ac6b7a8b
diff --git a/scripts/lib/test-env.sh b/scripts/lib/test-env.sh
index 08497a57a3..b39df9d0ca 100644
--- a/scripts/lib/test-env.sh
+++ b/scripts/lib/test-env.sh
@@ -104,3 +104,17 @@ ensure_default_pglite_snapshot() {
esac
echo "[$label] default PGLite snapshot active: $GBRAIN_TEST_DEFAULT_SNAPSHOT" >&2
}
+
+# ──────────────────────────────────────────────────────────────────────────
+# Coverage wait multiplier: bun's lcov instrumentation slows the code under
+# test while test deadlines stay wall-clock, so a coverage lane (COVERAGE_DIR
+# set) exports GBRAIN_TEST_WAIT_MULTIPLIER=2 unless the caller chose a value.
+# test/helpers/wait-for.ts scales every waitFor deadline by it and keeps the
+# result below bun's 60s per-test timeout. The bun preload keeps GBRAIN_TEST_*
+# and run-e2e.sh's env scrub keep-lists the name.
+# ──────────────────────────────────────────────────────────────────────────
+export_coverage_wait_multiplier() {
+ if [ -n "${COVERAGE_DIR:-}" ] && [ -z "${GBRAIN_TEST_WAIT_MULTIPLIER:-}" ]; then
+ export GBRAIN_TEST_WAIT_MULTIPLIER=2
+ fi
+}
diff --git a/scripts/run-e2e.sh b/scripts/run-e2e.sh
index 0742151e14..f3a260d49e 100755
--- a/scripts/run-e2e.sh
+++ b/scripts/run-e2e.sh
@@ -151,6 +151,7 @@ for _e2e_var in $(env | grep -oE '^(CONDUCTOR_|MCP_|OPENCLAW_|HERMES_|GROK_|OPEN
GBRAIN_TEST_DB) ;; # explicit schema-reset opt-in for service hosts; schema-drift still requires a test-shaped DB name
GBRAIN_PGBOUNCER_URL|GBRAIN_PGBOUNCER_DIRECT_URL|GBRAIN_CI_REQUIRE_PGBOUNCER) ;; # explicit pooler test target and execution requirement
GBRAIN_PGBOUNCER_E2E_URL|GBRAIN_PGBOUNCER_E2E_DB) ;; # backend-matrix pooled target (scripts/e2e-backend-matrix.txt)
+ GBRAIN_TEST_WAIT_MULTIPLIER) ;; # coverage deadline multiplier read by test/helpers/wait-for.ts — keep
GBRAIN_E2E_FILE_TIMEOUT) ;; # per-file cap override — read AFTER this scrub, so it must survive it
GBRAIN_E2E_ALLOW_DB) ;; # #3485 name-floor opt-in — the guard's own error
# message tells operators to set it; stripping it
@@ -235,6 +236,7 @@ fi
# Files asserting the path TO post-initSchema state carry their own per-file
# `delete process.env.GBRAIN_PGLITE_SNAPSHOT` opt-out.
. scripts/lib/test-env.sh
+export_coverage_wait_multiplier
ensure_pglite_snapshot "run-e2e"
# Absolutize: e2e tests spawn CLI subprocesses with varying cwd; a relative
# path would silently miss the tar there (cold-init fallback, benefit lost).
diff --git a/scripts/run-serial-tests.sh b/scripts/run-serial-tests.sh
index 91bcb131bf..318fcd307d 100755
--- a/scripts/run-serial-tests.sh
+++ b/scripts/run-serial-tests.sh
@@ -73,6 +73,7 @@ case "${1:-}" in
esac
. scripts/lib/test-env.sh
+export_coverage_wait_multiplier
# ──────────────────────────────────────────────────────────────────────────
# EXCLUSIVE_FILES: files that must never run concurrently with anything else
diff --git a/scripts/test-shard.sh b/scripts/test-shard.sh
index 21d29dbb94..0e576157a9 100755
--- a/scripts/test-shard.sh
+++ b/scripts/test-shard.sh
@@ -58,6 +58,7 @@ fi
cd "$(dirname "$0")/.."
. scripts/lib/test-env.sh
+export_coverage_wait_multiplier
# Collect non-E2E, non-serial unit test files. Slow files INCLUDED — see
# header comment. Local run-unit-shard.sh excludes slow files (different
diff --git a/test/helpers/wait-for.test.ts b/test/helpers/wait-for.test.ts
index cb7ecfdfa9..809ee9908c 100644
--- a/test/helpers/wait-for.test.ts
+++ b/test/helpers/wait-for.test.ts
@@ -1,5 +1,6 @@
import { describe, test, expect } from 'bun:test';
-import { waitFor, waitForValue } from './wait-for.ts';
+import { testWaitMs, waitFor, waitForValue } from './wait-for.ts';
+import { withEnv } from './with-env.ts';
describe('waitFor', () => {
test('immediate-true fast path: single check, no interval sleep', async () => {
@@ -99,3 +100,36 @@ describe('waitForValue', () => {
).rejects.toThrow('never-value');
});
});
+
+describe('GBRAIN_TEST_WAIT_MULTIPLIER', () => {
+ test('unset leaves deadlines unchanged', async () => {
+ await withEnv({ GBRAIN_TEST_WAIT_MULTIPLIER: undefined }, () => {
+ expect(testWaitMs(5000)).toBe(5000);
+ });
+ });
+
+ test('scales deadlines and names the scaling in the timeout error', async () => {
+ await withEnv({ GBRAIN_TEST_WAIT_MULTIPLIER: '2' }, async () => {
+ expect(testWaitMs(5000)).toBe(10_000);
+ const started = Date.now();
+ const error = await waitFor(() => false, { timeoutMs: 40, intervalMs: 5, label: 'scaled' }).then(() => new Error('resolved'), (e: unknown) => e as Error);
+ expect(Date.now() - started).toBeGreaterThanOrEqual(80);
+ expect(error.message).toContain('timeout 40ms scaled to 80ms by GBRAIN_TEST_WAIT_MULTIPLIER');
+ });
+ });
+
+ test('a scaled deadline stays below bun\'s 60s per-test timeout; a larger base is kept', async () => {
+ await withEnv({ GBRAIN_TEST_WAIT_MULTIPLIER: '4' }, () => {
+ expect(testWaitMs(20_000)).toBe(50_000);
+ expect(testWaitMs(120_000)).toBe(120_000);
+ });
+ });
+
+ test('an out-of-range value fails with the fix command', async () => {
+ for (const value of ['0.5', '9', 'fast']) {
+ await withEnv({ GBRAIN_TEST_WAIT_MULTIPLIER: value }, () => {
+ expect(() => testWaitMs(10)).toThrow(/Why: .*\nFix: unset GBRAIN_TEST_WAIT_MULTIPLIER/s);
+ });
+ }
+ });
+});
diff --git a/test/helpers/wait-for.ts b/test/helpers/wait-for.ts
index 9f3a64a28f..c23ba26021 100644
--- a/test/helpers/wait-for.ts
+++ b/test/helpers/wait-for.ts
@@ -7,7 +7,7 @@
* The predicate is checked at least once even with timeoutMs <= 0.
*/
export interface WaitForOpts {
- /** Deadline. Default 5000ms. */
+ /** Deadline. Default 5000ms. Scaled by GBRAIN_TEST_WAIT_MULTIPLIER (see testWaitMs). */
timeoutMs?: number;
/** Poll interval. Default 10ms. */
intervalMs?: number;
@@ -15,11 +15,47 @@ export interface WaitForOpts {
label?: string;
}
+/**
+ * GBRAIN_TEST_WAIT_MULTIPLIER (default 1) scales every test deadline for
+ * instrumented lanes: scripts/lib/test-env.sh sets 2 when COVERAGE_DIR is
+ * set, because coverage slows the code under test while the deadlines stay
+ * wall-clock. Accepted range 1..4; anything else fails the test loudly.
+ */
+export function testWaitMultiplier(): number {
+ const raw = process.env.GBRAIN_TEST_WAIT_MULTIPLIER;
+ if (raw === undefined || raw === '') return 1;
+ const value = Number(raw);
+ if (!Number.isFinite(value) || value < 1 || value > 4) {
+ throw new Error(
+ `GBRAIN_TEST_WAIT_MULTIPLIER=${JSON.stringify(raw)} is not a number from 1 to 4.\n`
+ + 'Why: it scales test wait deadlines (test/helpers/wait-for.ts); a bad value would make every deadline meaningless.\n'
+ + 'Fix: unset GBRAIN_TEST_WAIT_MULTIPLIER, or set it to a value from 1 to 4 (coverage lanes use 2).\n'
+ + 'Docs: docs/TESTING.md#speed--environment-helpers-testhelpers',
+ );
+ }
+ return value;
+}
+
+/**
+ * Bun's per-test timeout in every runner is 60s; a scaled deadline stays at
+ * or below this ceiling (or its unscaled base, if larger) so a slow condition
+ * fails as a labeled waitFor error, never as an anonymous bun timeout.
+ */
+const SCALED_DEADLINE_CEILING_MS = 50_000;
+
+/** `ms` scaled by GBRAIN_TEST_WAIT_MULTIPLIER, capped below bun's per-test timeout. */
+export function testWaitMs(ms: number): number {
+ const multiplier = testWaitMultiplier();
+ if (multiplier === 1) return ms;
+ return Math.max(ms, Math.min(Math.round(ms * multiplier), SCALED_DEADLINE_CEILING_MS));
+}
+
export async function waitFor(
predicate: () => boolean | Promise<boolean>,
opts: WaitForOpts = {},
): Promise<void> {
- const timeoutMs = opts.timeoutMs ?? 5000;
+ const baseTimeoutMs = opts.timeoutMs ?? 5000;
+ const timeoutMs = testWaitMs(baseTimeoutMs);
const intervalMs = opts.intervalMs ?? 10;
const start = Date.now();
for (;;) {
@@ -27,8 +63,9 @@ export async function waitFor(
const elapsed = Date.now() - start;
if (elapsed >= timeoutMs) {
const label = opts.label ? `${opts.label}: ` : '';
+ const scaled = timeoutMs === baseTimeoutMs ? '' : ` scaled to ${timeoutMs}ms by GBRAIN_TEST_WAIT_MULTIPLIER`;
throw new Error(
- `waitFor: ${label}condition still false after ${elapsed}ms (timeout ${timeoutMs}ms)`,
+ `waitFor: ${label}condition still false after ${elapsed}ms (timeout ${baseTimeoutMs}ms${scaled})`,
);
}
// Clamp the final sleep to the remaining deadline so a coarse interval
diff --git a/test/scripts/e2e-runner.test.ts b/test/scripts/e2e-runner.test.ts
index 8a99a456e4..c49c849c6d 100644
--- a/test/scripts/e2e-runner.test.ts
+++ b/test/scripts/e2e-runner.test.ts
@@ -115,6 +115,20 @@ test('fresh process',()=>{
for (const [file, contents] of Object.entries(prior)) expect(readFileSync(join(coverage, file), 'utf8')).toBe(contents);
} finally { rmSync(root, { recursive: true, force: true }); }
});
+ test('coverage runs default GBRAIN_TEST_WAIT_MULTIPLIER to 2 and keep an explicit value through the env scrub', () => {
+ const root = setup();
+ try {
+ writeFileSync(join(root, 'bin/git'), '#!/bin/sh\nprintf fixture-commit\n', { mode: 0o755 });
+ writeFileSync(join(root, 'test/e2e/a.test.ts'), "import {test,expect} from 'bun:test'; test('multiplier',()=>expect(process.env.GBRAIN_TEST_WAIT_MULTIPLIER).toBe(process.env.EXPECTED_MULTIPLIER));");
+ const path = `${join(root, 'bin')}:${process.env.PATH}`;
+ for (const [coverage, multiplier, expected] of [['coverage-a', '', '2'], ['coverage-b', '3', '3'], ['', '1.5', '1.5']]) {
+ const result = spawnSync('bash', ['scripts/run-e2e.sh', 'test/e2e/a.test.ts'], {
+ cwd: root, encoding: 'utf8', env: { ...env, COVERAGE_DIR: coverage, GBRAIN_TEST_WAIT_MULTIPLIER: multiplier, EXPECTED_MULTIPLIER: expected, PATH: path },
+ });
+ expect(result.status, result.stdout + result.stderr).toBe(0);
+ }
+ } finally { rmSync(root, { recursive: true, force: true }); }
+ });
test('a fully skipped file has execution evidence but need not emit LCOV', () => {
const root = setup();
try {