mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-27 22:15:33 +00:00
* fix(serve): clean up stdio MCP server on client disconnect
The PGLite write lock leaked indefinitely when the parent of `gbrain serve`
disconnected. Three root causes: serve.ts never called engine.disconnect()
after startMcpServer() resolved; cli.ts short-circuited with a "serve doesn't
disconnect" comment; and the MCP SDK's StdioServerTransport only listens for
'data'/'error' on stdin, never 'end'/'close', so even a clean stdin EOF never
reached the SDK.
Net effect: the next `gbrain serve` waited for the in-process 5-minute stale-
lock check or hung indefinitely.
stdio path now installs a unified lifecycle:
- SIGTERM/SIGINT/SIGHUP all funnel into one idempotent shutdown path
(SIGHUP coverage matters for Claude Desktop on macOS / MCP gateway
restarts; SIGINT for Ctrl-C; SIGTERM for daemon shutdown).
- stdin 'end' (clean EOF) and 'close' (parent SIGKILL with pipe still
open) both trigger the same graceful path. TTY stdin skips the watchers
so interactive `gbrain serve` is unaffected.
- Parent-process watchdog polls the live kernel parent PID via spawnSync
('ps','-o','ppid=','-p',PID) every 5s. process.ppid is cached at process
creation by Bun (and Node) and never refreshes on re-parent — empirical
evidence on macOS shows ps reports the new parent within one tick while
process.ppid stays at the original PID indefinitely (oven-sh/bun#30305).
- Watchdog fires on `getParentPid() !== initialParentPid` (any reparent),
not just `=== 1`. Catches launchd / systemd / tmux / parent-shell-with-
PR_SET_CHILD_SUBREAPER cases where the kernel re-anchors us to a non-1
subreaper PID. Codex review caught the original `=== 1` was incomplete.
- One-shot startup probe verifies `spawnSync('ps')` actually works on this
host. If the probe fails (stripped containers / busybox without procps),
we skip installing the watchdog interval entirely AND emit a loud stderr
line — the operator sees "watchdog disabled" instead of an installed-
but-never-fires phantom that silently falls back to cached process.ppid.
- 5-second cleanup deadline: if engine.disconnect() wedges (PGLite WASM
stall, etc.), the process still calls process.exit(0). The abandoned
lock dir is reclaimed on the next start by the existing stale-lock
check in pglite-lock.ts.
- Optional `--stdio-idle-timeout <sec>`: default OFF safety net for
parents that leak the pipe but never close it. Strict parsing rejects
`abc` / `30junk` / `-1` / `1.5` / blank values explicitly so a typo
doesn't silently disable the safety net (closes #446).
Test seam: ServeOptions { stdin, signals, exit, log, startMcpServer,
getParentPid, setInterval, clearInterval, probeWatchdog } lets the
lifecycle be unit-tested deterministically without spawning a real Bun
child or booting the MCP SDK.
22 test cases covering signals, stdin EOF, TTY skip, watchdog reparent
(both PID-1 and subreaper-PID-N cases), ps-unavailable degraded mode,
idle timeout, idempotent shutdown, and cleanup-deadline behavior.
Closes #413, #446. Supersedes #591.
Co-Authored-By: Aragorn2046 <noreply@github.com>
Co-Authored-By: seungsu-kr <noreply@github.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(auth): route HTTP auth/admin SQL through active engine
`gbrain auth` and `gbrain serve --http` previously routed every SQL
through the postgres.js singleton in src/core/db.ts, which silently fell
back to a file-backed PGLite when DATABASE_URL was set but the config
file disagreed. The HTTP transport's verbatim use of the singleton also
made `gbrain serve --http` Postgres-only, even though the
`access_tokens` and `mcp_request_log` tables exist in both engine
schemas.
Auth, OAuth, admin, file uploads, and HTTP-transport SQL now run through
`engine.executeRaw` via a deliberately narrow tagged-template adapter
(`src/core/sql-query.ts`). The contract is scalar-binds-only — adding
JSONB or fragment composition would invite the adapter to drift into a
partial postgres.js clone. JSONB writes use a separate
`executeRawJsonb(engine, sql, scalarParams, jsonbParams)` helper that
composes positional `$N::jsonb` casts and passes objects through
`engine.executeRaw`. The CI guard at `scripts/check-jsonb-pattern.sh`
doesn't fire because the helper is a method call, not the banned
`${JSON.stringify(x)}::jsonb` template-literal interpolation, and the
v0.12.0 double-encode bug class doesn't apply to positional binding via
`postgres.js`'s `unsafe()` (verified by
`test/e2e/auth-permissions.test.ts:67` on Postgres and the new
`test/sql-query.test.ts` on PGLite).
Migrated call sites:
- src/commands/auth.ts: takes-holders writes (lines 52, 86) →
executeRawJsonb. List, revoke, register-client, revoke-client →
SqlQuery via withConfiguredSql() helper that opens an engine, runs
the callback, disconnects.
- src/commands/serve-http.ts: ~25 call sites including the four
mcp_request_log.params INSERTs (now write real JSONB objects, not
JSON-encoded strings — the read side `params->>'op'` returns the
operation name, closing CLAUDE.md's outstanding "JSON-string-into-
JSONB" note as a side effect). The /admin/api/requests dynamic
filter pattern (postgres.js fragment composition) is rewritten as
parametrized SQL string + params array.
- src/mcp/http-transport.ts: legacy bearer-auth path. The
Postgres-only fail-fast at startup is removed because both schemas
now carry access_tokens + mcp_request_log.
- src/core/oauth-provider.ts: SqlQuery / SqlValue types relocated
from here to sql-query.ts as the canonical home (Codex finding #8).
- src/commands/files.ts: all 5 db.getConnection() sites (lines 104,
139, 252, 326, 355). The line-256 INSERT into files.metadata uses
executeRawJsonb; the other four are scalar-only SqlQuery (Codex
finding #6 — scope was bigger than the plan's "lone INSERT" framing).
- src/core/config.ts: env-var DATABASE_URL inference. When dbUrl is
set, infer Postgres engine and clear the stale database_path.
Engine-internal sql.json() sites in src/core/postgres-engine.ts (5
sites: lines 520, 1689, 1728, 1790, 2313) STAY UNCHANGED. They live
inside PostgresEngine itself, where the postgres.js template-tag
sql.json() pattern is correct — those methods are only loaded when
Postgres is the active engine, so there's no PGLite-routing concern.
Migration v45 (mcp_request_log_params_jsonb_normalize): one-shot UPDATE
that lifts pre-v0.31 string-shaped JSONB rows to objects so the
/admin/api/requests endpoint at serve-http.ts:605 returns one
consistent shape to the admin SPA. Idempotent (subsequent runs find no
rows where jsonb_typeof = 'string'). Closes the mixed-shape window
that would otherwise have made post-deploy admin reads break.
Tests:
- test/sql-query.test.ts: 7 cases covering scalar binds, the
.json() rejection (defense in depth — SqlQuery is scalar-only),
JSONB round-trip with `jsonb_typeof = 'object'` and `->>`
semantics, the v0.12.0 double-encode regression guard, null
JSONB handling, and the scalars-then-jsonb call shape.
- test/config-env.test.ts: migrated from PR's manual `restoreEnv()`
in afterEach to the canonical `withEnv()` helper at
test/helpers/with-env.ts (CLAUDE.md R1 / codex finding D3).
Five cases covering DATABASE_URL precedence, GBRAIN_DATABASE_URL
operator override, file-only config, env-only config, and the
no-config null path.
- test/e2e/auth-takes-holders-pglite.test.ts: 6 cases against
in-memory PGLite (no DATABASE_URL gate). Covers create / update /
read of access_tokens.permissions, mcp_request_log.params object
+ null writes, and the migration v45 normalizer (seed
string-shaped row, run UPDATE, assert object shape; second-run
no-op for idempotency).
- test/http-transport.test.ts: mock updated to intercept
engine.executeRaw (the new code path) instead of the postgres.js
template tag. 24 cases pass.
Plan reference: ~/.claude/plans/system-instruction-you-are-working-peppy-moore.md.
Codex outside-voice review applied: D-codex-1, D-codex-2, D-codex-5,
D-codex-8, D-codex-9, D-codex-10 (and D1, D5 reversed by codex).
Closes the architectural intent of #681. Supersedes its branch.
Co-Authored-By: codex-bot <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: update CLAUDE.md key files for v0.31.3
Annotate the v0.31.3 changes in the canonical Key Files section:
new src/core/sql-query.ts adapter (#681), src/commands/serve.ts stdio
cleanup (#676), v0.31.3 amendments to auth.ts / serve-http.ts /
oauth-provider.ts surfaces, and migration v46 normalizer in migrate.ts.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
* chore: regenerate llms-full.txt for v0.31.3 docs sync
CI's build-llms test asserts the committed llms.txt + llms-full.txt
match what scripts/build-llms.ts produces from current source state.
CLAUDE.md was amended by /document-release post-merge (new entries for
src/core/sql-query.ts and src/commands/serve.ts; amended notes on
auth.ts / serve-http.ts / migrate.ts), so the inlined-bundle fell out
of sync. Regenerated via `bun run build:llms`.
llms.txt unchanged (curated index — no new web URLs added).
llms-full.txt updated to inline the new CLAUDE.md content.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Aragorn2046 <noreply@github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
443 lines
16 KiB
TypeScript
443 lines
16 KiB
TypeScript
import { describe, test, expect } from 'bun:test';
|
|
import { EventEmitter } from 'events';
|
|
import { runServe, type ServeOptions } from '../src/commands/serve';
|
|
import type { BrainEngine } from '../src/core/engine';
|
|
|
|
// These tests cover the stdio lifecycle hooks added to runServe so that the
|
|
// PGLite write lock is released when the parent disconnects. We don't spawn
|
|
// a real Bun child or boot the real MCP SDK; we inject a stub `engine`, a
|
|
// fake stdin Readable (EventEmitter is enough — only on/once/emit are
|
|
// touched), an injected exit() that resolves a promise instead of
|
|
// terminating the process, and (per Codex Layer 2 review feedback) a
|
|
// no-op startMcpServer stub so the real MCP SDK never attaches a 'data'
|
|
// listener to the test runner's actual process.stdin.
|
|
|
|
class StubEngine implements Partial<BrainEngine> {
|
|
// Track whether disconnect was called; the lock-release behavior we care
|
|
// about here is "did the lifecycle path actually invoke disconnect?".
|
|
disconnectCalls = 0;
|
|
disconnect = async (): Promise<void> => {
|
|
this.disconnectCalls += 1;
|
|
};
|
|
}
|
|
|
|
class StubSignals {
|
|
private handlers = new Map<string, Array<(...a: unknown[]) => void>>();
|
|
on(signal: string, handler: (...a: unknown[]) => void): this {
|
|
const list = this.handlers.get(signal) ?? [];
|
|
list.push(handler);
|
|
this.handlers.set(signal, list);
|
|
return this;
|
|
}
|
|
emit(signal: string): void {
|
|
for (const h of this.handlers.get(signal) ?? []) h();
|
|
}
|
|
}
|
|
|
|
// Stub timer pair: `setInterval` returns a numeric handle; `tickAll()`
|
|
// fires every registered fn once, mirroring 1 real-time tick. Lets the
|
|
// test drive the parent-watchdog deterministically without 5s of wall
|
|
// clock and without leaving real timers active across the suite.
|
|
interface TimerStub {
|
|
setInterval: (fn: () => void, ms: number) => unknown;
|
|
clearInterval: (h: unknown) => void;
|
|
tickAll: () => void;
|
|
active: () => number;
|
|
}
|
|
|
|
function makeTimerStub(): TimerStub {
|
|
const fns = new Map<number, () => void>();
|
|
let next = 1;
|
|
return {
|
|
setInterval(fn) {
|
|
const id = next++;
|
|
fns.set(id, fn);
|
|
return id;
|
|
},
|
|
clearInterval(h) {
|
|
if (typeof h === 'number') fns.delete(h);
|
|
},
|
|
tickAll() {
|
|
for (const fn of fns.values()) fn();
|
|
},
|
|
active() {
|
|
return fns.size;
|
|
},
|
|
};
|
|
}
|
|
|
|
interface Harness {
|
|
engine: StubEngine;
|
|
stdin: EventEmitter & { isTTY?: boolean; on: any; once: any };
|
|
signals: StubSignals;
|
|
logs: string[];
|
|
exited: Promise<number>;
|
|
opts: ServeOptions;
|
|
timers: TimerStub;
|
|
setParentPid: (pid: number) => void;
|
|
}
|
|
|
|
function makeHarness(opts: {
|
|
isTTY?: boolean;
|
|
initialParentPid?: number;
|
|
probeWatchdog?: boolean;
|
|
} = {}): Harness {
|
|
const engine = new StubEngine();
|
|
const stdin = new EventEmitter() as EventEmitter & { isTTY?: boolean };
|
|
if (opts.isTTY) stdin.isTTY = true;
|
|
const signals = new StubSignals();
|
|
const logs: string[] = [];
|
|
|
|
let resolveExit!: (code: number) => void;
|
|
const exited = new Promise<number>(r => { resolveExit = r; });
|
|
let exitCalled = false;
|
|
|
|
// Mutable parent-pid the test can flip; defaults to a non-1 sentinel
|
|
// so the watchdog *will* install (`initialParentPid !== 1` guard).
|
|
// Tests that want "we were spawned under PID 1" pass `initialParentPid: 1`.
|
|
let parentPid = opts.initialParentPid ?? 12345;
|
|
const timers = makeTimerStub();
|
|
|
|
// probeWatchdog defaults to true so tests run with watchdog installed.
|
|
// Set probeWatchdog: false to simulate stripped-container ps unavailability.
|
|
const probeWatchdogResult = opts.probeWatchdog ?? true;
|
|
|
|
const serveOpts: ServeOptions = {
|
|
stdin: stdin as any,
|
|
signals: signals as any,
|
|
exit: (code?: number) => {
|
|
if (exitCalled) return;
|
|
exitCalled = true;
|
|
resolveExit(code ?? 0);
|
|
},
|
|
log: (msg: string) => { logs.push(msg); },
|
|
// Replace the real MCP SDK boot with a no-op so we never touch the
|
|
// test runner's real process.stdin. The lifecycle hooks under test
|
|
// are installed *before* this is awaited, so all behaviors are still
|
|
// exercised end-to-end.
|
|
startMcpServer: async () => {},
|
|
getParentPid: () => parentPid,
|
|
setInterval: timers.setInterval,
|
|
clearInterval: timers.clearInterval,
|
|
probeWatchdog: () => probeWatchdogResult,
|
|
};
|
|
|
|
return {
|
|
engine,
|
|
stdin: stdin as any,
|
|
signals,
|
|
logs,
|
|
exited,
|
|
opts: serveOpts,
|
|
timers,
|
|
setParentPid: (pid: number) => { parentPid = pid; },
|
|
};
|
|
}
|
|
|
|
// runServe in tests resolves quickly because the injected startMcpServer
|
|
// is a no-op. The lifecycle hooks were installed synchronously before
|
|
// that no-op was awaited, so they're already wired by the time runServe
|
|
// returns. We start runServe and `await` it (so any setup error surfaces
|
|
// immediately), then drive the test-controlled events.
|
|
async function startInBackground(
|
|
engine: StubEngine,
|
|
args: string[],
|
|
opts: ServeOptions,
|
|
): Promise<void> {
|
|
await runServe(engine as unknown as BrainEngine, args, opts);
|
|
}
|
|
|
|
describe('runServe stdio lifecycle', () => {
|
|
test('stdin end triggers engine.disconnect() and process exit(0)', async () => {
|
|
const h = makeHarness();
|
|
await startInBackground(h.engine, [], h.opts);
|
|
|
|
h.stdin.emit('end');
|
|
const code = await h.exited;
|
|
|
|
expect(code).toBe(0);
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
expect(h.logs.some(l => l.includes('graceful exit (stdin-end)'))).toBe(true);
|
|
});
|
|
|
|
test('SIGTERM triggers graceful exit', async () => {
|
|
const h = makeHarness();
|
|
await startInBackground(h.engine, [], h.opts);
|
|
|
|
h.signals.emit('SIGTERM');
|
|
const code = await h.exited;
|
|
|
|
expect(code).toBe(0);
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
expect(h.logs.some(l => l.includes('graceful exit (SIGTERM)'))).toBe(true);
|
|
});
|
|
|
|
test('SIGINT triggers graceful exit', async () => {
|
|
const h = makeHarness();
|
|
await startInBackground(h.engine, [], h.opts);
|
|
|
|
h.signals.emit('SIGINT');
|
|
const code = await h.exited;
|
|
|
|
expect(code).toBe(0);
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
expect(h.logs.some(l => l.includes('graceful exit (SIGINT)'))).toBe(true);
|
|
});
|
|
|
|
test('SIGHUP triggers graceful exit (terminal disconnect / daemon reload)', async () => {
|
|
// Per Aragorn (#591): real-world hosts (Claude Desktop on macOS,
|
|
// hermes-agent restart) sometimes send SIGHUP instead of closing
|
|
// stdin or sending SIGTERM. The handler converges on the same
|
|
// graceful path as the other signals.
|
|
const h = makeHarness();
|
|
await startInBackground(h.engine, [], h.opts);
|
|
|
|
h.signals.emit('SIGHUP');
|
|
const code = await h.exited;
|
|
|
|
expect(code).toBe(0);
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
expect(h.logs.some(l => l.includes('graceful exit (SIGHUP)'))).toBe(true);
|
|
});
|
|
|
|
test('stdin close (parent SIGKILL leaves pipe destroyed) triggers graceful exit', async () => {
|
|
// 'end' fires on a clean EOF; 'close' fires when the underlying
|
|
// handle is destroyed (e.g. parent SIGKILL'd while pipe still open).
|
|
// We must observe both — observing only 'end' would miss the
|
|
// hard-kill path that #591's reporter hit on macOS.
|
|
const h = makeHarness();
|
|
await startInBackground(h.engine, [], h.opts);
|
|
|
|
h.stdin.emit('close');
|
|
const code = await h.exited;
|
|
|
|
expect(code).toBe(0);
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
expect(h.logs.some(l => l.includes('graceful exit (stdin-close)'))).toBe(true);
|
|
});
|
|
|
|
test('parent watchdog fires shutdown when ppid flips to 1 (orphaned to init)', async () => {
|
|
// Some hosts (launchd, cron, certain MCP gateways) terminate
|
|
// without closing stdin and without sending a signal — the kernel
|
|
// re-parents us. The watchdog polls the live ppid on an interval;
|
|
// when it differs from the initial captured ppid, we detect "parent
|
|
// died" and shut down.
|
|
const h = makeHarness({ initialParentPid: 4242 });
|
|
await startInBackground(h.engine, [], h.opts);
|
|
|
|
// Watchdog should have installed (we passed initialParentPid !== 1
|
|
// and probeWatchdog defaulted to true).
|
|
expect(h.timers.active()).toBe(1);
|
|
|
|
// Simulate parent death: our process gets re-parented to init.
|
|
h.setParentPid(1);
|
|
h.timers.tickAll();
|
|
|
|
const code = await h.exited;
|
|
expect(code).toBe(0);
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
expect(h.logs.some(l => l.includes('graceful exit (parent-died)'))).toBe(true);
|
|
|
|
// beginShutdown clears the watchdog interval as part of cleanup so
|
|
// a duplicate tick can't queue a redundant shutdown.
|
|
expect(h.timers.active()).toBe(0);
|
|
});
|
|
|
|
test('parent watchdog fires shutdown when ppid flips to a SUBREAPER PID > 1 (codex finding #3)', async () => {
|
|
// Reparent-to-PID-1 is the easy case. Real hosts under launchd /
|
|
// systemd / tmux / a parent-shell-with-PR_SET_CHILD_SUBREAPER will
|
|
// re-parent us to that subreaper's PID, NOT to 1. The PR-#676
|
|
// author's original `=== 1` check missed this. The fix is to fire
|
|
// on `current !== initialParentPid` so any reparent triggers the
|
|
// shutdown, regardless of where the kernel re-anchors us.
|
|
const h = makeHarness({ initialParentPid: 8500 });
|
|
await startInBackground(h.engine, [], h.opts);
|
|
|
|
expect(h.timers.active()).toBe(1);
|
|
|
|
// Parent died; kernel re-parented to a launchd subreaper (PID 47).
|
|
h.setParentPid(47);
|
|
h.timers.tickAll();
|
|
|
|
const code = await h.exited;
|
|
expect(code).toBe(0);
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
expect(h.logs.some(l => l.includes('graceful exit (parent-died)'))).toBe(true);
|
|
expect(h.timers.active()).toBe(0);
|
|
});
|
|
|
|
test('parent watchdog NOT installed when initial ppid is already 1 (legitimate init child)', async () => {
|
|
// Spawned directly under PID 1 (e.g. systemd unit, Docker entrypoint):
|
|
// ppid=1 is the documented steady state, not "parent died". We must
|
|
// NOT install the watchdog or we'd shut down immediately.
|
|
const h = makeHarness({ initialParentPid: 1 });
|
|
await startInBackground(h.engine, [], h.opts);
|
|
|
|
expect(h.timers.active()).toBe(0);
|
|
|
|
// Sanity: the other lifecycle paths still work.
|
|
h.signals.emit('SIGTERM');
|
|
await h.exited;
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
});
|
|
|
|
test('parent watchdog NOT installed when ps probe fails (codex finding #4 / D2-revisited)', async () => {
|
|
// Stripped containers / busybox-without-procps environments lack ps.
|
|
// The original PR's per-tick fallback would silently return cached
|
|
// process.ppid, never detect a change, and never fire the shutdown
|
|
// — while still claiming to be active.
|
|
//
|
|
// The fix: a one-shot startup probe. When it returns false, we skip
|
|
// installing the watchdog interval AND emit a loud stderr line so
|
|
// the operator sees the degraded mode at startup.
|
|
const h = makeHarness({ initialParentPid: 4242, probeWatchdog: false });
|
|
await startInBackground(h.engine, [], h.opts);
|
|
|
|
// Watchdog NOT installed — message matches behavior.
|
|
expect(h.timers.active()).toBe(0);
|
|
expect(h.logs.some(l => l.includes('[gbrain serve] watchdog disabled: ps unavailable'))).toBe(true);
|
|
|
|
// Sanity: the other lifecycle paths still work — the shutdown still
|
|
// funnels through stdin EOF / signals, just not via the watchdog.
|
|
h.signals.emit('SIGTERM');
|
|
await h.exited;
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
});
|
|
|
|
test('parent watchdog tick with ppid still alive does NOT fire shutdown', async () => {
|
|
// The watchdog must only fire on the *transition* away from the
|
|
// initial ppid; a healthy tick (ppid still equal to the original)
|
|
// is a no-op.
|
|
const h = makeHarness({ initialParentPid: 4242 });
|
|
await startInBackground(h.engine, [], h.opts);
|
|
|
|
expect(h.timers.active()).toBe(1);
|
|
// Tick with ppid unchanged.
|
|
h.timers.tickAll();
|
|
h.timers.tickAll();
|
|
h.timers.tickAll();
|
|
expect(h.engine.disconnectCalls).toBe(0);
|
|
|
|
// ... and signal-driven shutdown still works after several quiet ticks.
|
|
h.signals.emit('SIGTERM');
|
|
await h.exited;
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
});
|
|
|
|
test('shutdown is idempotent — multiple signals only disconnect once', async () => {
|
|
const h = makeHarness();
|
|
await startInBackground(h.engine, [], h.opts);
|
|
|
|
h.signals.emit('SIGTERM');
|
|
h.signals.emit('SIGTERM');
|
|
h.signals.emit('SIGINT');
|
|
h.stdin.emit('end');
|
|
|
|
await h.exited;
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
});
|
|
|
|
test('TTY stdin does NOT install end watcher (interactive use unaffected)', async () => {
|
|
const h = makeHarness({ isTTY: true });
|
|
await startInBackground(h.engine, [], h.opts);
|
|
|
|
// Emit 'end' on TTY stdin — no listener should be wired so this is a
|
|
// no-op. The test passes by simply not exiting; we give the runtime a
|
|
// beat to confirm nothing fires. Signals must still work.
|
|
h.stdin.emit('end');
|
|
await new Promise(r => setTimeout(r, 10));
|
|
expect(h.engine.disconnectCalls).toBe(0);
|
|
|
|
// Sanity: signals still wired regardless of TTY-ness.
|
|
h.signals.emit('SIGTERM');
|
|
await h.exited;
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
});
|
|
|
|
test('--stdio-idle-timeout 0 disarms the idle hook (sanity)', async () => {
|
|
const h = makeHarness();
|
|
await startInBackground(h.engine, ['--stdio-idle-timeout', '0'], h.opts);
|
|
|
|
// 0 is the documented opt-out. No idle hook should be armed; drive a
|
|
// different exit path to confirm flow still works.
|
|
h.signals.emit('SIGTERM');
|
|
await h.exited;
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
expect(h.logs.every(l => !l.includes('idle timeout'))).toBe(true);
|
|
});
|
|
|
|
test('--stdio-idle-timeout > 0 logs the configured value', async () => {
|
|
const h = makeHarness();
|
|
await startInBackground(h.engine, ['--stdio-idle-timeout', '60'], h.opts);
|
|
|
|
expect(h.logs.some(l => l.includes('stdio idle timeout = 60s'))).toBe(true);
|
|
|
|
h.signals.emit('SIGTERM');
|
|
await h.exited;
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
});
|
|
|
|
test('idle timer is reset on every stdin data chunk', async () => {
|
|
const h = makeHarness();
|
|
// Use a very short timeout so we can observe the firing/resetting
|
|
// without slowing the suite. 50ms is enough to be measurable but
|
|
// short enough that the suite finishes promptly.
|
|
await startInBackground(
|
|
h.engine,
|
|
['--stdio-idle-timeout', '1'], // 1 second; we reset it before it fires
|
|
h.opts,
|
|
);
|
|
|
|
// Pulse 'data' a few times to keep the timer reset.
|
|
for (let i = 0; i < 3; i++) {
|
|
h.stdin.emit('data', Buffer.from('{"jsonrpc":"2.0"}'));
|
|
await new Promise(r => setTimeout(r, 100));
|
|
}
|
|
expect(h.engine.disconnectCalls).toBe(0);
|
|
|
|
// Now stop pulsing and wait for the timer to actually fire end-to-end
|
|
// (it ought to elapse within ~1s of the last reset). Awaiting
|
|
// h.exited rather than a wall-clock race makes this deterministic.
|
|
await h.exited;
|
|
expect(h.engine.disconnectCalls).toBe(1);
|
|
expect(h.logs.some(l => l.includes('stdio-idle-timeout (1s)'))).toBe(true);
|
|
}, 5000);
|
|
|
|
test.each([
|
|
['abc', /--stdio-idle-timeout/],
|
|
['30junk', /--stdio-idle-timeout/],
|
|
['-1', /--stdio-idle-timeout/],
|
|
['1.5', /--stdio-idle-timeout/],
|
|
['', /--stdio-idle-timeout/],
|
|
])('--stdio-idle-timeout rejects invalid value %p (typo is a CLI error)', async (bad, msgRe) => {
|
|
// Per Codex Layer 2 review P1: silent fallback on typo turns the
|
|
// opt-in safety net into a no-op. Strict parsing throws so the
|
|
// operator sees the mistake immediately.
|
|
const h = makeHarness();
|
|
expect(
|
|
runServe(h.engine as unknown as BrainEngine, ['--stdio-idle-timeout', bad], h.opts),
|
|
).rejects.toThrow(msgRe);
|
|
});
|
|
|
|
test('--stdio-idle-timeout with no following value also throws', async () => {
|
|
const h = makeHarness();
|
|
// Flag at end of args — no value to consume.
|
|
expect(
|
|
runServe(h.engine as unknown as BrainEngine, ['--stdio-idle-timeout'], h.opts),
|
|
).rejects.toThrow(/missing value/);
|
|
});
|
|
|
|
test('engine.disconnect throwing still results in exit(0) and logged error', async () => {
|
|
const h = makeHarness();
|
|
h.engine.disconnect = async () => {
|
|
throw new Error('synthetic disconnect failure');
|
|
};
|
|
await startInBackground(h.engine, [], h.opts);
|
|
|
|
h.signals.emit('SIGTERM');
|
|
const code = await h.exited;
|
|
expect(code).toBe(0);
|
|
expect(h.logs.some(l => l.includes('cleanup error: synthetic disconnect failure'))).toBe(true);
|
|
});
|
|
});
|