Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(smoke): our own implementation of the #5248 fix (#5248)

time-attack9d6d7341d468
diff --git a/scripts/smoke-test.sh b/scripts/smoke-test.sh
index fcfa5bf1aa..66f51e339a 100755
--- a/scripts/smoke-test.sh
+++ b/scripts/smoke-test.sh
@@ -22,45 +22,38 @@ FIXES=0
TOTAL=0
SKIPPED=0
-# Bounded command runner. GNU coreutils ships `timeout`; Homebrew installs it
-# as `gtimeout`; stock macOS has neither. Without one, a background watchdog
-# polls once a second, sends TERM (then KILL) at the deadline, and exits as
-# soon as the command does. The command's exit status is returned as-is.
-# GBRAIN_TEST_SMOKE_TIMEOUT_BIN=none forces the watchdog; it exists only for
-# test/smoke-test-worker.test.ts.
-TIMEOUT_BIN=""
-if [ "${GBRAIN_TEST_SMOKE_TIMEOUT_BIN:-}" != "none" ]; then
- if command -v gtimeout >/dev/null 2>&1; then TIMEOUT_BIN="gtimeout"
- elif command -v timeout >/dev/null 2>&1; then TIMEOUT_BIN="timeout"
- fi
-fi
-
-run_with_timeout() {
- local seconds="$1"
+# with_deadline SECONDS CMD [ARG...]: run CMD, stopping it once SECONDS pass.
+# Linux has coreutils `timeout` and Homebrew installs it as `gtimeout`, but
+# stock macOS ships neither (#5248). Without either, CMD runs as a background
+# child that this shell polls; at the deadline it gets TERM and, if still
+# alive a second later, KILL. Only that child pid is ever signalled, and CMD
+# is run from "$@" as given, never re-parsed. The return value is CMD's own
+# status, or 124 when the deadline stopped it, as `timeout` reports.
+with_deadline() {
+ local limit="$1" tool
shift
- if [ -n "$TIMEOUT_BIN" ]; then
- "$TIMEOUT_BIN" "$seconds" "$@"
- return $?
- fi
+ for tool in timeout gtimeout; do
+ if command -v "$tool" >/dev/null 2>&1; then
+ "$tool" "$limit" "$@"
+ return
+ fi
+ done
"$@" &
- local command_pid=$!
- (
- elapsed=0
- while [ "$elapsed" -lt "$seconds" ]; do
+ local child=$! give_up=$((SECONDS + limit + 1)) expired=0 status
+ while kill -0 "$child" 2>/dev/null; do
+ if [ "$SECONDS" -ge "$give_up" ]; then
+ expired=1
+ kill -TERM "$child" 2>/dev/null
sleep 1
- kill -0 "$command_pid" 2>/dev/null || exit 0
- elapsed=$((elapsed + 1))
- done
- kill -TERM "$command_pid" 2>/dev/null || exit 0
- sleep 1
- kill -KILL "$command_pid" 2>/dev/null || true
- ) >/dev/null 2>&1 &
- local watchdog_pid=$!
- wait "$command_pid"
- local result=$?
- kill "$watchdog_pid" 2>/dev/null || true
- wait "$watchdog_pid" 2>/dev/null || true
- return "$result"
+ kill -0 "$child" 2>/dev/null && kill -KILL "$child" 2>/dev/null
+ break
+ fi
+ sleep 0.2 2>/dev/null || sleep 1
+ done
+ wait "$child"
+ status=$?
+ if [ "$expired" = 1 ]; then return 124; fi
+ return "$status"
}
timestamp() { date -u '+%Y-%m-%d %H:%M:%S'; }
@@ -116,12 +109,12 @@ fi
# ── 2. GBrain CLI loads ────────────────────────────────────
if [ -n "$GBRAIN_DIR" ] && [ -n "$BUN_PATH" ]; then
- if run_with_timeout 15 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" --help >/dev/null 2>&1; then
+ if with_deadline 15 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" --help >/dev/null 2>&1; then
pass "GBrain CLI ($GBRAIN_DIR)"
else
# Auto-fix: reinstall deps
cd "$GBRAIN_DIR" && "$BUN_PATH" install --frozen-lockfile 2>/dev/null
- if run_with_timeout 15 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" --help >/dev/null 2>&1; then
+ if with_deadline 15 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" --help >/dev/null 2>&1; then
fixed "GBrain deps reinstalled"
pass "GBrain CLI (after dep fix)"
else
@@ -140,7 +133,7 @@ fi
# works with the DB down), then branch on doctor --json's connection check,
# with `gbrain db-repair --yes` as the auto-fix arm.
if [ -n "$GBRAIN_DIR" ] && [ -n "$BUN_PATH" ]; then
- ENGINE_JSON=$(DATABASE_URL="$DB_URL" GBRAIN_DATABASE_URL="$DB_URL" run_with_timeout 15 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" engine status --json 2>/dev/null)
+ ENGINE_JSON=$(DATABASE_URL="$DB_URL" GBRAIN_DATABASE_URL="$DB_URL" with_deadline 15 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" engine status --json 2>/dev/null)
# #4182: BSD grep (macOS) has no -P; keep this shipped smoke test POSIX-portable.
ENGINE_KIND=$(printf '%s\n' "$ENGINE_JSON" | sed -n 's/.*"effective_engine": *"\([a-z]*\)".*/\1/p' | head -1)
ENGINE_SRC=$(printf '%s\n' "$ENGINE_JSON" | sed -n 's/.*"db_url_source": *"\([^"]*\)".*/\1/p' | head -1)
@@ -149,7 +142,7 @@ if [ -n "$GBRAIN_DIR" ] && [ -n "$BUN_PATH" ]; then
if [ -z "$DB_URL" ] && [ "$ENGINE_KIND" != "pglite" ] && [ -z "$ENGINE_SRC" ]; then
fail "GBrain database — no DATABASE_URL, GBRAIN_DATABASE_URL or configured database URL (and the engine is not pglite)"
else
- run_doctor_json() { DATABASE_URL="$DB_URL" GBRAIN_DATABASE_URL="$DB_URL" run_with_timeout 30 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" doctor --json 2>/dev/null; }
+ run_doctor_json() { DATABASE_URL="$DB_URL" GBRAIN_DATABASE_URL="$DB_URL" with_deadline 30 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" doctor --json 2>/dev/null; }
DOCTOR_JSON=$(run_doctor_json)
CONN_STATUS=$(printf '%s\n' "$DOCTOR_JSON" | sed -n 's/.*"name": *"connection", *"status": *"\([a-z]*\)".*/\1/p' | head -1)
if [ "$CONN_STATUS" = "ok" ]; then
@@ -161,7 +154,7 @@ if [ -n "$GBRAIN_DIR" ] && [ -n "$BUN_PATH" ]; then
# 240s: the docker conn_refused arm's readiness poll alone can run
# ~165s worst-case; a 60s cap would SIGTERM the repair mid-poll and
# report failure while the container it just started is still warming.
- DATABASE_URL="$DB_URL" GBRAIN_DATABASE_URL="$DB_URL" run_with_timeout 240 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" db-repair --yes >> "$LOG" 2>&1
+ DATABASE_URL="$DB_URL" GBRAIN_DATABASE_URL="$DB_URL" with_deadline 240 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" db-repair --yes >> "$LOG" 2>&1
DOCTOR_JSON=$(run_doctor_json)
CONN_STATUS=$(printf '%s\n' "$DOCTOR_JSON" | sed -n 's/.*"name": *"connection", *"status": *"\([a-z]*\)".*/\1/p' | head -1)
if [ "$CONN_STATUS" = "ok" ]; then
@@ -181,7 +174,7 @@ if [ -n "$GBRAIN_DIR" ] && [ -n "$BUN_PATH" ] && [ -n "$DB_URL" ]; then
SUPERVISOR_RUNNING=0
LEGACY_WORKER_RUNNING=0
if DATABASE_URL="$DB_URL" GBRAIN_DATABASE_URL="$DB_URL" \
- run_with_timeout 15 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" jobs supervisor status --json >/dev/null 2>&1; then
+ with_deadline 15 "$BUN_PATH" run "$GBRAIN_DIR/src/cli.ts" jobs supervisor status --json >/dev/null 2>&1; then
SUPERVISOR_RUNNING=1
fi
if [ -f "$WORKER_PID_FILE" ] && kill -0 "$(cat "$WORKER_PID_FILE")" 2>/dev/null; then
diff --git a/test/smoke-test-worker.test.ts b/test/smoke-test-worker.test.ts
index 065e8bb10b..dd78ff4614 100644
--- a/test/smoke-test-worker.test.ts
+++ b/test/smoke-test-worker.test.ts
@@ -8,7 +8,7 @@ const REPO = resolve(import.meta.dir, '..');
const SCRIPT = join(REPO, 'scripts', 'smoke-test.sh');
const tempDirs: string[] = [];
-function runSmoke(opts: { supervisorRunning: boolean; legacyPid?: number; configUrlOnly?: boolean; embeddingStatus?: string; forceWatchdog?: boolean; withoutTimeoutBinary?: boolean }) {
+function runSmoke(opts: { supervisorRunning: boolean; legacyPid?: number; configUrlOnly?: boolean; embeddingStatus?: string; path?: string }) {
const dir = mkdtempSync(join(tmpdir(), 'gbrain-smoke-worker-'));
tempDirs.push(dir);
const fakeBun = join(dir, 'bun');
@@ -39,7 +39,6 @@ exit 0
`);
chmodSync(fakeBun, 0o755);
if (opts.legacyPid) writeFileSync(workerPid, `${opts.legacyPid}\n`);
- const path = opts.withoutTimeoutBinary ? pathWithout(dir, ['timeout', 'gtimeout']) : process.env.PATH;
const result = spawnSync('bash', [SCRIPT], {
cwd: REPO,
@@ -62,43 +61,12 @@ exit 0
SMOKE_BUN_CALLS: calls,
SMOKE_WORKER_STARTED: workerStarted,
SMOKE_SUPERVISOR_RUNNING: opts.supervisorRunning ? '1' : '0',
- PATH: path,
- GBRAIN_TEST_SMOKE_TIMEOUT_BIN: opts.forceWatchdog ? 'none' : '',
+ PATH: opts.path ?? process.env.PATH,
},
});
return { ...result, calls, workerStarted, workerPid };
}
-/** A PATH that resolves every current binary except `names`, like a stock macOS host without GNU coreutils. */
-function pathWithout(dir: string, names: string[]): string {
- const bin = join(dir, 'path-bin');
- mkdirSync(bin);
- const seen = new Set(names);
- for (const entry of (process.env.PATH ?? '').split(':')) {
- if (!entry || !existsSync(entry)) continue;
- for (const name of readdirSync(entry)) {
- if (seen.has(name)) continue;
- seen.add(name);
- symlinkSync(join(entry, name), join(bin, name));
- }
- }
- return bin;
-}
-
-/** The smoke script's own timeout prelude and run_with_timeout, run in bash with the watchdog forced. */
-function runWatchdog(body: string) {
- const script = readFileSync(SCRIPT, 'utf8');
- const start = script.indexOf('TIMEOUT_BIN=""');
- const end = script.indexOf('\n}\n', script.indexOf('run_with_timeout() {')) + 3;
- const started = Date.now();
- const result = spawnSync('bash', ['-c', `${script.slice(start, end)}\n${body}`], {
- encoding: 'utf8',
- timeout: 20_000,
- env: { ...process.env, GBRAIN_TEST_SMOKE_TIMEOUT_BIN: 'none' },
- });
- return { ...result, elapsedMs: Date.now() - started };
-}
-
afterEach(() => {
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
@@ -147,32 +115,99 @@ describe('smoke-test database and embedding sources (#5063)', () => {
}, 30_000);
});
-describe('smoke-test bounded checks without GNU timeout (#5248)', () => {
- test('a host with neither timeout nor gtimeout still runs every bounded check', () => {
- const result = runSmoke({ supervisorRunning: true, withoutTimeoutBinary: true });
+const NO_TIMEOUT_TOOLS = ['timeout', 'gtimeout'];
+
+/**
+ * process.env.PATH with the named tools made unreachable, the way a stock
+ * macOS host looks without GNU coreutils: a directory that holds any of them
+ * is swapped for a mirror of symlinks to everything else in it.
+ */
+function pathHiding(hidden: string[], extraFront: string[] = []): string {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-smoke-path-'));
+ tempDirs.push(root);
+ const dirs = (process.env.PATH ?? '').split(':').filter(Boolean).map((dir, index) => {
+ if (!existsSync(dir)) return dir;
+ const names = readdirSync(dir);
+ if (!names.some(name => hidden.includes(name))) return dir;
+ const mirror = join(root, `mirror-${index}`);
+ mkdirSync(mirror);
+ for (const name of names) if (!hidden.includes(name)) symlinkSync(join(dir, name), join(mirror, name));
+ return mirror;
+ });
+ return [...extraFront, ...dirs].join(':');
+}
+
+/** Run a bash snippet with the smoke script's with_deadline function defined, in a scratch cwd. */
+function withDeadlineShell(snippet: string, path: string) {
+ const fn = readFileSync(SCRIPT, 'utf8').match(/^with_deadline\(\) \{\n[\s\S]*?\n\}\n/m);
+ expect(fn, 'scripts/smoke-test.sh defines with_deadline').not.toBeNull();
+ const cwd = mkdtempSync(join(tmpdir(), 'gbrain-smoke-deadline-'));
+ tempDirs.push(cwd);
+ const begin = performance.now();
+ const out = spawnSync('bash', ['-c', `${fn![0]}\n${snippet}`], { cwd, encoding: 'utf8', timeout: 25_000, env: { ...process.env, PATH: path } });
+ return { ...out, cwd, ms: performance.now() - begin };
+}
+
+function alive(pid: number): boolean {
+ try { process.kill(pid, 0); return true; } catch { return false; }
+}
+
+describe('smoke-test checks stay bounded without a timeout binary (#5248)', () => {
+ test('the whole smoke run passes on a PATH with neither timeout nor gtimeout', () => {
+ const path = pathHiding(NO_TIMEOUT_TOOLS);
+ expect(spawnSync('bash', ['-c', 'command -v timeout || command -v gtimeout'], { env: { PATH: path } }).status).not.toBe(0);
+ const result = runSmoke({ supervisorRunning: true, path });
expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
- expect(result.stderr).not.toContain('command not found');
- expect(result.stdout).toContain('GBrain CLI');
+ expect(`${result.stdout}${result.stderr}`).not.toContain('not found');
expect(result.stdout).toContain('health score: 97/100');
expect(result.stdout).toContain('GBrain worker (supervisor-managed)');
- expect(readFileSync(result.calls, 'utf8')).toContain('jobs supervisor status --json');
+ const calls = readFileSync(result.calls, 'utf8');
+ for (const bounded of ['--help', 'engine status --json', 'doctor --json', 'jobs supervisor status --json']) {
+ expect(calls).toContain(bounded);
+ }
}, 30_000);
- test('the forced watchdog path passes the same healthy run', () => {
- const result = runSmoke({ supervisorRunning: true, forceWatchdog: true });
- expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0);
- expect(result.stdout).toContain('GBrain worker (supervisor-managed)');
+ test('a command still running at the deadline is stopped and reported as 124', () => {
+ const run = withDeadlineShell(`with_deadline 1 sh -c 'echo $$ > child.pid; exec sleep 30'; echo "rc=$?"`, pathHiding(NO_TIMEOUT_TOOLS));
+ expect(run.stdout.trim()).toBe('rc=124');
+ expect(run.ms).toBeLessThan(5_000);
+ expect(alive(Number(readFileSync(join(run.cwd, 'child.pid'), 'utf8')))).toBe(false);
+ }, 30_000);
+
+ test('a command that ignores TERM is killed', () => {
+ const run = withDeadlineShell(`with_deadline 1 sh -c 'trap "" TERM; echo $$ > child.pid; exec sleep 30'; echo "rc=$?"`, pathHiding(NO_TIMEOUT_TOOLS));
+ expect(run.stdout.trim()).toBe('rc=124');
+ expect(run.ms).toBeLessThan(6_000);
+ expect(alive(Number(readFileSync(join(run.cwd, 'child.pid'), 'utf8')))).toBe(false);
}, 30_000);
- test('the watchdog stops a hanging command at its deadline', () => {
- const result = runWatchdog('run_with_timeout 1 sleep 30; echo "rc=$?"');
- expect(result.stdout.trim()).toBe('rc=143');
- expect(result.elapsedMs).toBeLessThan(6_000);
+ test('a command that finishes in time returns its own status at once, even close to the limit', () => {
+ const run = withDeadlineShell(
+ `with_deadline 20 sh -c 'exit 7'; echo "a=$?"; with_deadline 20 true; echo "b=$?"; with_deadline 2 sh -c 'sleep 1; exit 5'; echo "c=$?"`,
+ pathHiding(NO_TIMEOUT_TOOLS),
+ );
+ expect(run.stdout.trim().split('\n')).toEqual(['a=7', 'b=0', 'c=5']);
+ expect(run.ms).toBeLessThan(4_000);
}, 30_000);
- test('the watchdog returns a quick command\'s own exit status without waiting for the deadline', () => {
- const result = runWatchdog('run_with_timeout 30 sh -c "exit 3"; echo "rc=$?"; run_with_timeout 30 true; echo "rc=$?"');
- expect(result.stdout.trim().split('\n')).toEqual(['rc=3', 'rc=0']);
- expect(result.elapsedMs).toBeLessThan(6_000);
+ test('arguments reach the command exactly as given and are never evaluated', () => {
+ const run = withDeadlineShell(`with_deadline 5 printf '%s|' 'two words' '$(touch injected)' '; touch injected2' '*'`, pathHiding(NO_TIMEOUT_TOOLS));
+ expect(run.stdout).toBe('two words|$(touch injected)|; touch injected2|*|');
+ expect(existsSync(join(run.cwd, 'injected'))).toBe(false);
+ expect(existsSync(join(run.cwd, 'injected2'))).toBe(false);
+ }, 30_000);
+
+ test('an installed timeout or gtimeout does the bounding instead of the fallback', () => {
+ const fakes = mkdtempSync(join(tmpdir(), 'gbrain-smoke-fake-timeout-'));
+ tempDirs.push(fakes);
+ for (const tool of NO_TIMEOUT_TOOLS) {
+ mkdirSync(join(fakes, tool));
+ writeFileSync(join(fakes, tool, tool), `#!/bin/sh\necho "${tool}:$*"\n`);
+ chmodSync(join(fakes, tool, tool), 0o755);
+ }
+ const both = withDeadlineShell('with_deadline 9 echo hi', pathHiding(NO_TIMEOUT_TOOLS, [join(fakes, 'timeout'), join(fakes, 'gtimeout')]));
+ expect(both.stdout.trim()).toBe('timeout:9 echo hi');
+ const homebrewOnly = withDeadlineShell('with_deadline 9 echo hi', pathHiding(NO_TIMEOUT_TOOLS, [join(fakes, 'gtimeout')]));
+ expect(homebrewOnly.stdout.trim()).toBe('gtimeout:9 echo hi');
}, 30_000);
});