Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

P4.12 #5332: keep endPoolBounded's guard timer ref'd and bound the spawned-CLI persistence test

garrytan0c08bbd7c164
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index fe0452a086..6e301a4373 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -209,6 +209,8 @@ jobs:
run: bun test --timeout 60000 test/colon-slug-windows-5032.test.ts test/cross-lane-5081-5032.test.ts
- name: Windows durability, skill bundles and local-writer flags (#5595, #5475)
run: bun test --timeout 60000 test/fs-durable.test.ts test/persistence-windows-flush-5595.test.ts test/bundle-files-windows-5475.test.ts test/init-packaged-skills-native.test.ts test/auth-local-writer-dry-run.test.ts test/scripts/durable-flush-guard.test.ts test/binary-self-update-durable-download.test.ts
+ - name: Teardown bounds that used to park bun test on Windows (#5332)
+ run: bun test --timeout 120000 test/postgres-disconnect-bounded.test.ts test/persistence-administration.test.ts
# bun audit blocks on pushes, schedules, manual runs, and pull requests or
# merge-queue entries that change bun.lock, admin/bun.lock, patches/ or a
diff --git a/src/core/db.ts b/src/core/db.ts
index 2f90fbc38c..f20b946889 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -39,9 +39,13 @@ export async function endPoolBounded(
pool: { end: (opts?: { timeout?: number }) => Promise<void> },
): Promise<void> {
let timer: ReturnType<typeof setTimeout> | undefined;
+ // The guard timer stays ref'd while the race is pending (#5332): an unref'd
+ // timer is dropped by a runtime with nothing else to wait on (and parked
+ // under `bun test` on Windows), so the never-settling .end() it exists for
+ // was the one case it did not bound. The finally clears it, so a healthy
+ // drain never holds the process open past the race.
const guard = new Promise<void>((resolve) => {
timer = setTimeout(resolve, POOL_END_TIMEOUT_SECONDS * 1000 + 500);
- timer.unref?.();
});
try {
await Promise.race([
diff --git a/test/helpers/end-pool-bounded-probe.ts b/test/helpers/end-pool-bounded-probe.ts
new file mode 100644
index 0000000000..b55c8724b6
--- /dev/null
+++ b/test/helpers/end-pool-bounded-probe.ts
@@ -0,0 +1,13 @@
+/**
+ * #5332 probe child: awaits endPoolBounded against a pool whose end() never
+ * settles and reports when the await came back. Spawned by
+ * test/postgres-disconnect-bounded.test.ts. No top-level await on purpose:
+ * the only thing keeping this process alive is the guard timer itself, so a
+ * runtime that drops an unref'd timer exits before the line below is printed
+ * (and `bun test` on Windows parked on it forever).
+ */
+import { endPoolBounded } from '../../src/core/db.ts';
+
+const t0 = Date.now();
+void endPoolBounded({ end: () => new Promise<void>(() => { /* never settles */ }) })
+ .then(() => console.log(`settled ${Date.now() - t0}`));
diff --git a/test/persistence-administration.test.ts b/test/persistence-administration.test.ts
index a6d4bdfe75..94aa9daba4 100644
--- a/test/persistence-administration.test.ts
+++ b/test/persistence-administration.test.ts
@@ -26,6 +26,33 @@ beforeAll(async () => {
}, 60_000);
afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+/**
+ * #5332: a spawned CLI that never exits (or whose pipes a grandchild holds
+ * open) must FAIL this file with its teardown run, never park it. The whole
+ * drain races one timer; on expiry the child is SIGKILLed and the await
+ * rejects with the argv, so the caller's finally still closes the IPC server
+ * and releases the lock.
+ */
+async function spawnCliBounded(args: string[], cwd: string, wallMs: number) {
+ const child = Bun.spawn([process.execPath, join(import.meta.dir, '../src/cli.ts'), ...args], {
+ cwd, env: { ...process.env, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0' }, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',
+ });
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const expiry = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ try { child.kill(9); } catch { /* already exited */ }
+ reject(new Error(`gbrain ${args.join(' ')} did not exit within ${wallMs}ms (#5332)`));
+ }, wallMs);
+ });
+ try {
+ const [stdout, stderr, code] = await Promise.race([
+ Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]),
+ expiry,
+ ]);
+ return { stdout, stderr, code };
+ } finally { clearTimeout(timer); }
+}
+
async function isolated<T>(run: (dir: string) => Promise<T>): Promise<T> {
const dir = mkdtempSync(join(tmpdir(), 'gbrain-admin-test-'));
try {
@@ -146,10 +173,7 @@ describe('local writer administration', () => {
['auth', 'local-writer', 'list', '--json'],
['sources', 'writer', 'claim', 'default', '--path', dir, '--dry-run', '--json'],
]) {
- const child = Bun.spawn([process.execPath, join(import.meta.dir, '../src/cli.ts'), ...args], {
- cwd: dir, env: { ...process.env, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0' }, stdout: 'pipe', stderr: 'pipe',
- });
- const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ const { stdout, stderr, code } = await spawnCliBounded(args, dir, 60_000);
expect({ code, stderr }).toMatchObject({ code: 0 });
const result = JSON.parse(stdout);
if (args.includes('--probe')) expect(result.native_lock).toMatchObject({ acquired: true, released: true });
@@ -159,6 +183,15 @@ describe('local writer administration', () => {
} finally { const closed = once(binding.server, 'close'); binding.close(); await closed; await releaseLock(lock); }
}));
+ test('the spawned-CLI bound fails with teardown instead of parking (forced 1 ms probe, #5332)', () => isolated(async dir => {
+ const config = { engine: 'pglite' as const, database_path: join(dir, 'db') };
+ mkdirSync(config.database_path);
+ const lock = await acquireLock(config.database_path);
+ try {
+ await expect(spawnCliBounded(['sources', 'writer', 'status', '--json'], dir, 1)).rejects.toThrow(/did not exit within 1ms \(#5332\)/);
+ } finally { await releaseLock(lock); }
+ }));
+
test('CLI parser preserves exact grant/epoch intent and rejects malformed flag combinations', () => {
expect(parsePersistenceAdminArgs('local-writer', ['register', 'stdio', '--allowed-operations=', '--source-ids', 'default', '--replace'])).toMatchObject({
operation: 'local_writer_register', params: { lane: 'stdio', allowed_operations: [], source_ids: ['default'], replace: true },
diff --git a/test/postgres-disconnect-bounded.test.ts b/test/postgres-disconnect-bounded.test.ts
index 68dea784fa..aa8f58410b 100644
--- a/test/postgres-disconnect-bounded.test.ts
+++ b/test/postgres-disconnect-bounded.test.ts
@@ -10,6 +10,7 @@
*/
import { describe, test, expect } from 'bun:test';
+import { join } from 'node:path';
import { endPoolBounded, POOL_END_TIMEOUT_SECONDS } from '../src/core/db.ts';
describe('endPoolBounded', () => {
@@ -37,4 +38,34 @@ describe('endPoolBounded', () => {
const pool = { end: async () => { throw new Error('pool boom'); } };
await expect(endPoolBounded(pool)).resolves.toBeUndefined();
});
+
+ // #5332: the guard timer used to be unref'd, so a runtime with nothing else
+ // pending dropped it and the await never came back (under `bun test` on
+ // Windows the file parked forever). A separate bun process is the only
+ // honest witness: it must print the settled line and exit by itself.
+ test('a child process awaiting the bound against a never-settling .end() settles and exits on its own (#5332)', async () => {
+ const wall = POOL_END_TIMEOUT_SECONDS * 1000 + 10_000;
+ const child = Bun.spawn([process.execPath, '--no-env-file', join(import.meta.dir, 'helpers', 'end-pool-bounded-probe.ts')], {
+ stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: { ...process.env, GBRAIN_NO_BANNER: '1' },
+ });
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const expiry = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ try { child.kill(9); } catch { /* already exited */ }
+ reject(new Error(`endPoolBounded probe child did not exit within ${wall}ms (#5332)`));
+ }, wall);
+ });
+ try {
+ const [stdout, stderr, code] = await Promise.race([
+ Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]),
+ expiry,
+ ]);
+ expect({ code, stderr }).toMatchObject({ code: 0 });
+ const settled = /settled (\d+)/.exec(stdout);
+ expect(settled).not.toBeNull();
+ expect(Number(settled![1])).toBeGreaterThanOrEqual(POOL_END_TIMEOUT_SECONDS * 1000);
+ } finally {
+ clearTimeout(timer);
+ }
+ }, 30_000);
});