MemOS icon indicating copy to clipboard operation
MemOS copied to clipboard

fix(bridge): add 20s timeout guard to core.shutdown() to prevent orphaned processes

Open chiefmojo opened this issue 6 months ago • 0 comments

Problem

When the Hermes gateway dies abnormally (SIGKILL, OOM, crash), the --no-viewer bridge process calls core.shutdown() which chains through flush() → L2/L3 LLM calls that can block indefinitely. With the parent gone, nobody remains to send SIGKILL. Over 36 hours, 19 orphaned bridges accumulated consuming 299% CPU and writing duplicate traces (6,572 copies of a single turn).

Fixes #1798.

Changes

Adds a withShutdownTimeout() helper that races core.shutdown() against a 20-second deadline. Wraps all six core.shutdown() call sites:

  1. Daemon SIGTERM handler (bridge.cts)
  2. Non-daemon SIGTERM handler (bridge/stdio.ts)
  3. Headless stdin-EOF exit (bridge/stdio.ts)
  4. EADDRINUSE exit (×2) — daemon cannot bind viewer port
  5. Viewer-running keepalive path — stdin closes while viewer is still serving

Also adds bridge-shutdown-audit.md documenting the full call chain through flush() → L2/L3/skill, confirming all async operations yield the event loop and the 20s timeout is effective on every path.

const SHUTDOWN_TIMEOUT_MS = 20_000;
function withShutdownTimeout(p: Promise<void>): Promise<void> {
  return Promise.race([p, new Promise<void>((r) => setTimeout(r, SHUTDOWN_TIMEOUT_MS))]);
}

Verification

  • Code audit — traced every shutdown path, confirmed no sync blocking ops prevent the timeout from firing
  • Stress test — kill gateway with SIGKILL, verify bridges exit within 20s, zero orphans
  • Watchdog — cron job monitors bridge count across companions, alerts on accumulation

Co-Authored-By: Claude Sonnet 4.6 [email protected]

chiefmojo avatar May 24 '26 20:05 chiefmojo