fix(desktop,pty-daemon): reap wedged host-service children and bound pty pause

Merged
KI
3mo ago
+993-30

Summary

  • A host-service child orphaned by a Squirrel auto-update relaunch (PPID 1, ~98% CPU, ignores SIGTERM) froze terminal sessions 1-2x/week. Three defects combined; this fixes all three.
  • The child now exits under a deadline and hard-kills itself if dispose() wedges; the coordinator escalates SIGTERM to SIGKILL and reaps a wedged manifest holder before spawning beside it; pty-daemon bounds how long one non-reading subscriber can hold a PTY paused for everyone.

Why / Context

On the update path the Electron parent quits seconds after before-quit and leaves the child to self-terminate. Every orphan in main.log + DiagnosticReports lines up with an update relaunch. [host-service] shutdown (SIGTERM), draining connections is logged, sometimes 2-3 times for the same pid, and a completion line never follows.

  1. Child shutdown could hang forever. shutdown() did server.close() then process.exit(0). It never called the dispose() from createApp(), and process.exit() joins every worker_threads Worker. A host-worker wedged in native code (hung spawnSync git, long SQLite call) blocks that join, and if (shuttingDown) return made every later SIGTERM a no-op.
  2. Coordinator never escalated or reaped. stop() sent one SIGTERM. startOrAdopt() health-probed the manifest pid, and on a miss just spawned a new child next to the wedged one (on a fallback port when the old one still held the socket, e.g. listening on port 63847 instead of 48046). Only the explicit reset() path ever SIGKILLed.
  3. pty-daemon pause was unbounded. When any subscriber's socket buffered past 1 MB the PTY was paused for every subscriber, and only that socket's drain or close resumed it. The 8 MB destroy cap was never reached because a paused PTY produces nothing. A wedged-but-alive orphan kept its socket open, never read, and froze those terminals for the live host-service too.

How It Works

  • apps/desktop/src/main/host-service/shutdown.ts (new): shutdown sequencing with injected deps, same style as quit-sequence.ts. Log reason, clear the reclaim timer, server.close(), after the 3 s grace closeAllConnections() then await dispose() bounded by 2 s. Resolves → process.exit(0). Times out → process.kill(process.pid, "SIGKILL"), a kernel-delivered kill that needs no cooperation from V8. A second signal while shutting down hard-exits immediately. A signal before serve() returned goes through the same bounded dispose (no drain window).
  • host-service-coordinator.ts: stop() schedules an unref'd SIGKILL 5 s after SIGTERM through the existing scheduleRespawnTimer seam; handleChildExit() cancels it so a recycled pid is never signalled. Under the spawn lock, after the adopt re-check misses, a manifest pid that is alive, failed the probe, and has startedAt after this boot (Date.now() - os.uptime()*1000, guards recycled pids from before a reboot) is SIGKILLed and its manifest removed before spawn(). Exit log line now includes the pid.
  • packages/pty-daemon/src/Server/Server.ts: ServerOptions.pausedConnTimeoutMs (default 30 s). Armed once per conn when it first causes a pause, cleared on drain and in dropConn. On fire, socket.destroy() that conn; its close → dropConn resumes the PTYs for everyone else. If the host-service is the one dropped, its existing daemon-disconnect path closes every terminal WS with 1011, the renderer reconnects, and the next getDaemonClient() rebuilds the client and re-subscribes with ring replay. Shells survive in the daemon.

Manual QA (before / after reproductions)

1. Child shutdown hang. Real Node child with an HTTP server plus a Worker blocked in native spawnSync. Driver sends SIGTERM like the coordinator.

Before (pre-fix shutdown code):

+  239ms driver: sending SIGTERM #1
+  239ms child: [host-service] shutdown (SIGTERM), draining connections
+ 3240ms driver: still alive after 3s, sending SIGTERM #2
  PID STAT  %CPU COMMAND
43086 S      0.0 node .../wedged-child.mjs old
+ 6244ms driver: RESULT=old: ORPHAN — child ignored two SIGTERMs; SIGKILLing it by hand

After (createShutdown):

+  235ms child: [host-service] shutdown (SIGTERM), draining connections
+ 1537ms child: [host-service] dispose did not finish within 1000ms (worker wedged?); hard-exiting
+ 1539ms driver: child exited code=null signal=SIGKILL

After, second SIGTERM while dispose is still pending:

+ 3244ms child: [host-service] shutdown (SIGTERM) while already shutting down; hard-exiting
+ 3246ms driver: child exited code=null signal=SIGKILL

2. Coordinator. New coordinator tests run against the pre-fix coordinator: 48 pass, 2 fail (reaps an alive-but-unhealthy manifest holder, escalates to SIGKILL after the grace). Against the fixed coordinator: 50 pass.

3. Terminal freeze. Real pty-daemon, PTY running yes, two subscribers. "stuck" stops reading at t=2s. Live subscriber's throughput per second:

Before:

t= 3s live subscriber received 132 KB this second
t= 4s ... 0 KB   t= 5s ... 0 KB   t= 6s ... 0 KB   t= 7s ... 0 KB   t= 8s ... 0 KB   t= 9s ... 0 KB
t=10s RESULT: live subscriber is FROZEN

After (timeout 3 s for the demo; shipped default 30 s):

t= 4s live subscriber received 0 KB this second
[pty-daemon] subscriber stopped reading for 3000ms while holding 1 session(s) paused; disconnecting it
t= 6s live subscriber received 69195 KB this second
t=10s RESULT: live subscriber is receiving output again

Edge cases driven:

  • Slow-but-draining subscriber (pause 600 ms, resume, drain, repeat, with a 1 s timeout): 11 cycles over 8 s, never dropped. A busy-but-healthy host-service on a loaded machine is not disconnected.
  • Second SIGTERM while dispose is pending: hard-exits immediately (above).
  • Signal before serve() bound: disposes under the deadline, no drain window.
  • pty-daemon signal-recovery (daemon SIGKILL, clients receive close events) still passes.

Testing

  • bun test src/main/host-service/shutdown.test.ts src/main/lib/host-service-coordinator.test.ts (apps/desktop): 59 pass
  • bun test src/main/lib src/main/host-service (apps/desktop): 637 pass
  • bun run test + bun run test:integration (packages/pty-daemon): 81 + 57 pass (signal-recovery needs bun run build:daemon first)
  • New pty test proven to fail without the fix (live subscriber's wait times out)
  • host-service node tests (after the better-sqlite3 ABI flip): terminal.daemon-stall-retry, terminal.adoption, DaemonClient, test:integration:terminal all pass. DaemonSupervisor has one failure, auto-update defers when live sessions exist, which fails identically against the pre-fix daemon bundle, so it is pre-existing on main and not from this change.
  • bun run typecheck in apps/desktop and packages/pty-daemon
  • bunx biome check on all touched files

Design Decisions

  • Self-SIGKILL instead of process.exit past the deadline: process.exit() is the thing that hangs (worker join). process.kill(process.pid, "SIGKILL") is delivered by the kernel and works regardless of V8 state. SQLite is journaled, so a hard exit past a 5 s budget is safe.
  • Reap under the spawn lock, after two probe misses: the outer tryAdopt and the under-lock re-check each probe for 2.5 s, so a holder must be unresponsive for ~5 s before it is killed. Same probe the child's own shouldYieldManifest already trusts.
  • Boot-time guard on startedAt: pids recycle across reboots, and a manifest left from before a reboot could name anything. os.uptime() comes from kern.boottime, so sleep does not move it.
  • 30 s pause timeout: a subscriber that cannot drain a ≤1 MB buffer in 30 s is not serving anyone. The cost of a false positive is one terminal WS reconnect through the existing daemon-disconnect path, not lost shells.

Known Limitations

  • The coordinator's SIGKILL escalation is unref'd, so on app quit or update it never fires; the child-side hard exit and the startup reap are what cover that path. quit-sequence.ts is deliberately untouched: the app cannot wait for children on the update path.
  • A CLI-spawned host-service that is stalled for >5 s at app start will be reaped and replaced by an app-owned one (the CLI then reads the new manifest).
  • The field orphans sat at ~98% CPU; the synthetic wedge (worker blocked in spawnSync) hangs at 0%. The exit path exercised is the same, but the CPU burn itself was not reproduced. Next time one appears, sample <pid> would show which thread is spinning.

Rollback

  • Revert the PR. No data or schema changes. The pty-daemon option is server-side only; no protocol change, so mixed daemon/host-service versions are fine.

https://claude.ai/code/session_01Nrm3XYbYud255QumC9vJeb


Summary by cubic

Fixes terminal sessions freezing 1–2x/week after Squirrel auto-updates, caused by a host-service child orphaned at ~98% CPU that ignored SIGTERM. The child now hard-exits under a deadline, the coordinator escalates to SIGKILL and reaps wedged children, and pty-daemon drops a subscriber that holds a PTY paused too long. A CLI-spawned host-service stalled more than 5s at app start is now reaped and replaced.

Bug Fixes

  • Child shutdown now awaits dispose() (including retiring the host-worker pool) under a 2s deadline and SIGKILLs itself on timeout; a second signal while shutting down hard-exits immediately.
  • Coordinator stop() escalates SIGTERM to SIGKILL after 5s (cancelled on child exit) and, before spawning beside a holder, reaps it only if it is alive, unhealthy, started this boot, and its process identity matches the manifest (command line and age).
  • pty-daemon disconnects a subscriber still congested after 30s (pausedConnTimeoutMs), resuming paused PTYs for the remaining subscribers; a pause timer is cleared when the congested subscriber's sessions exit.

Summary by CodeRabbit

  • Bug Fixes
    • Improved desktop service shutdown reliability by ensuring active connections close gracefully and resources are released within a defined time.
    • Added force-termination safeguards for services or child processes that become unresponsive during shutdown or recovery.
    • Improved recovery of unhealthy service instances while preserving healthy running instances.
    • Prevented stalled PTY subscribers from blocking output delivery indefinitely; congested connections are now disconnected automatically so other sessions can resume.
    • Improved cleanup of background worker processes during application shutdown.