Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(serve): keep serve --http running when its log pipe closes (#5079)

garrytan3b141ffabe6d
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index 9e274b3918..88c0ecaf81 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten.
-- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`).
+- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/cli-force-exit.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`.
- `src/core/process-watchdog.ts` — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+. `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests, and pure exported `clampWatchdogTimers(deadlineMs, graceMs)` + `MAX_WATCHDOG_TIMER_MS` clamp BOTH worker timers so the deadline AND the `deadline+grace` SUM stay ≤ 2^31−1 — `setTimeout` overflow-fires above that at ~1ms, which for the sum timer would be an instant SIGKILL of a healthy process (unit-tested as pure arithmetic only; never arm a real max-deadline worker in-suite — its firing SIGTERMs the test runner itself). Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Two adopters: `gbrain sync` (below) and the opt-in PGLite disconnect watchdog (`pglite-engine.ts` entry above); autopilot/cycle are follow-up candidates. Pinned by `test/process-watchdog.test.ts` (pure decision matrix + clamp arithmetic + handle contract) + `test/process-watchdog.serial.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too); deadline resolved by `resolveSyncHardDeadline` in `sync.ts` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none).
diff --git a/src/cli.ts b/src/cli.ts
index 37f90faeb1..75acba6596 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -34,7 +34,7 @@ import { operations, OperationError } from './core/operations.ts';
import { resolveSourceIdEngineFree } from './core/source-resolver.ts';
import { formatVolunteeredPage } from './core/context/volunteer.ts';
import type { Operation, OperationContext } from './core/operations.ts';
-import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal, installStdoutPipeDelivery } from './core/cli-force-exit.ts';
+import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal, installStdoutPipeDelivery, isHttpServeInvocation } from './core/cli-force-exit.ts';
import { serializeMarkdown } from './core/markdown.ts';
import { parseGlobalFlags, setCliOptions, getCliOptions } from './core/cli-options.ts';
import { runCliPreflight } from './core/cli-preflight.ts';
@@ -3108,7 +3108,7 @@ if (import.meta.main) {
// SIGTERM→exit(143) handler into any process that merely IMPORTS this module
// (bun test runners died mid-suite when a test emitted a synthetic SIGTERM).
// Spawned/compiled CLI processes are entrypoints, so they still install.
- installCleanupSignalHandlers();
+ installCleanupSignalHandlers({ keepServingOnLogEpipe: isHttpServeInvocation() });
// #4383: CLI_ONLY payloads (console.log / bare process.stdout.write) get
// delivery-exact serialized writes; `serve` keeps native streaming stdout.
if (shouldForceExitAfterMain()) installStdoutPipeDelivery();
diff --git a/src/core/cli-force-exit.ts b/src/core/cli-force-exit.ts
index ab991d5e8b..efb7f11e55 100644
--- a/src/core/cli-force-exit.ts
+++ b/src/core/cli-force-exit.ts
@@ -85,6 +85,17 @@ export function shouldForceExitAfterMain(
return !DAEMON_COMMANDS.has(command);
}
+/** #5079: is this `serve --http`, whose stdout/stderr are log streams only? */
+export function isHttpServeInvocation(argv: string[] = process.argv.slice(2)): boolean {
+ let rest: string[];
+ try {
+ rest = parseGlobalFlags(argv).rest;
+ } catch {
+ rest = argv;
+ }
+ return rest[0] === 'serve' && rest.includes('--http');
+}
+
/** Floor for the computed backstop deadline (the historical hard deadline). */
export const TEARDOWN_DEADLINE_FLOOR_MS = 10_000;
/** Allowance for the facts sink's awaited abort() (shutdown of an in-flight job). */
diff --git a/src/core/process-cleanup.ts b/src/core/process-cleanup.ts
index e5ec19518c..b3be1e55d2 100644
--- a/src/core/process-cleanup.ts
+++ b/src/core/process-cleanup.ts
@@ -143,9 +143,14 @@ async function runCleanupCallbacks(): Promise<void> {
* SIGTERM). The SIGINT AbortController path in cli.ts stays untouched —
* we don't listen to SIGINT here.
*/
-export function installSignalHandlers(): void {
+export function installSignalHandlers(opts: { keepServingOnLogEpipe?: boolean } = {}): void {
if (installed) return;
installed = true;
+ // #5079: for `serve --http`, stdout/stderr are only log streams (the MCP
+ // transport is the HTTP socket), so a closed log pipe must not stop the
+ // server: the log write is dropped and it keeps serving. Everywhere else a
+ // broken pipe still exits (for stdio `serve` it means the client left).
+ const keepServing = opts.keepServingOnLogEpipe === true;
const handleSignal = (signal: NodeJS.Signals) => {
void runCleanupPass().finally(() => {
@@ -171,7 +176,7 @@ export function installSignalHandlers(): void {
attach(process, 'SIGHUP', () => handleSignal('SIGHUP'));
// Bun delivers SIGPIPE on a broken pipe (Node ignores it by default and
// surfaces only an EPIPE write error on the stream, handled below).
- attach(process, 'SIGPIPE', () => handleSignal('SIGPIPE'));
+ attach(process, 'SIGPIPE', () => { if (!keepServing) handleSignal('SIGPIPE'); });
attach(process, 'uncaughtException', (err: unknown) => {
try { process.stderr.write(`[uncaughtException] ${err instanceof Error ? err.stack ?? err.message : err}\n`); }
@@ -187,14 +192,14 @@ export function installSignalHandlers(): void {
// EPIPE on stdout — the canonical `gbrain sync | head -N` case. Route
// through the cleanup pass so locks release BEFORE we exit.
attach(process.stdout, 'error', (err: NodeJS.ErrnoException) => {
- if (err.code === 'EPIPE') {
+ if (err.code === 'EPIPE' && !keepServing) {
void triggerCleanupAndExit(0);
}
});
// Same for stderr — less common but possible (e.g. `2>&1 | head` after
// stderr was rerouted to stdout).
attach(process.stderr, 'error', (err: NodeJS.ErrnoException) => {
- if (err.code === 'EPIPE') {
+ if (err.code === 'EPIPE' && !keepServing) {
// No stderr means no useful logs on the way out; still cleanup.
void triggerCleanupAndExit(0);
}
diff --git a/test/serve-http-log-epipe.test.ts b/test/serve-http-log-epipe.test.ts
new file mode 100644
index 0000000000..e5bda5a631
--- /dev/null
+++ b/test/serve-http-log-epipe.test.ts
@@ -0,0 +1,76 @@
+/**
+ * #5079: `serve --http` exited when its stdout/stderr pipe closed (a
+ * hand-written systemd unit or a log pipeline that restarts), because the
+ * CLI-wide broken-pipe handling (SIGPIPE under Bun, EPIPE stream errors)
+ * stops the process. For `serve --http` those streams only carry logs, so it
+ * now drops the write and keeps serving; stdio `serve` and every other
+ * command still exit, since there a broken stdout means the reader left.
+ *
+ * The broken pipe is real: a child installs the handlers, keeps logging on a
+ * timer, and the parent destroys the child's stdout/stderr pipes.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { spawn } from 'child_process';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { join, resolve } from 'path';
+import { tmpdir } from 'os';
+
+import { isHttpServeInvocation } from '../src/core/cli-force-exit.ts';
+
+const CLEANUP = resolve(import.meta.dir, '..', 'src', 'core', 'process-cleanup.ts');
+
+async function logThroughClosedPipe(keepServing: boolean): Promise<{ exit: number | string | null; ticksAfterClose: number }> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-5079-'));
+ try {
+ const marker = join(dir, 'ticks.log');
+ const script = join(dir, 'child.ts');
+ writeFileSync(script, `
+const { installSignalHandlers } = await import(${JSON.stringify(CLEANUP)});
+const { appendFileSync } = await import('fs');
+installSignalHandlers({ keepServingOnLogEpipe: ${keepServing} });
+let n = 0;
+setInterval(() => {
+ n++;
+ console.log('request log ' + n);
+ console.error('request err ' + n);
+ appendFileSync(${JSON.stringify(marker)}, n + '\\n');
+}, 50);
+`);
+ const child = spawn(process.execPath, [script], { stdio: ['ignore', 'pipe', 'pipe'] });
+ let exit: number | string | null = 'alive';
+ child.on('exit', (code, signal) => { exit = code ?? signal; });
+ const ticks = () => (existsSync(marker) ? readFileSync(marker, 'utf-8').trim().split('\n').length : 0);
+ for (let i = 0; i < 100 && ticks() < 5; i++) await new Promise(r => setTimeout(r, 50));
+ child.stdout!.destroy();
+ child.stderr!.destroy();
+ const atClose = ticks();
+ await new Promise(r => setTimeout(r, 1500));
+ const after = ticks() - atClose;
+ child.kill('SIGKILL');
+ return { exit, ticksAfterClose: after };
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+describe('#5079 serve --http survives a closed log pipe', () => {
+ test('with the serve --http setting the process keeps running and logging', async () => {
+ const r = await logThroughClosedPipe(true);
+ expect(r.exit).toBe('alive');
+ expect(r.ticksAfterClose).toBeGreaterThan(5);
+ }, 30_000);
+
+ test('every other command (stdio serve included) still exits on a broken pipe', async () => {
+ const r = await logThroughClosedPipe(false);
+ expect(r.exit).not.toBe('alive');
+ }, 30_000);
+
+ test('only `serve --http` gets the setting', () => {
+ expect(isHttpServeInvocation(['serve', '--http', '--port', '3131'])).toBe(true);
+ expect(isHttpServeInvocation(['--timeout', '30s', 'serve', '--http'])).toBe(true);
+ expect(isHttpServeInvocation(['serve'])).toBe(false);
+ expect(isHttpServeInvocation(['sync', '--http'])).toBe(false);
+ expect(isHttpServeInvocation([])).toBe(false);
+ });
+});