hapi icon indicating copy to clipboard operation
hapi copied to clipboard

architecture: hub restart cascade-archives every idle agent session; sessions should be resilient to hub bouncing

Open heavygee opened this issue 5 months ago • 5 comments

Summary

A systemctl restart hapi-hub.service (or equivalent) currently cascade-archives every idle agent session on the host. Hub stop → runner SIGTERM → runner cleanup kills child agent processes (cli/src/runner/run.ts:583) → each child agent archives itself on death (cli/src/agent/runnerLifecycle.ts). All sessions that weren't mid-turn-protected by some out-of-band mechanism (e.g. patient-mode wrappers) are lost as live sessions and have to be reopened individually after restart.

This is an architectural regression rather than a single bug. Sessions should be resilient to hub bouncing: hub stops, agents survive (or are reaped and re-spawned in-place), hub comes back, agents reconnect, sessions resume where they were. No metadata change, no lifecycleState flip to archived, no audit trail noise.

Real-fleet evidence (2026-06-15)

A soup-keeper agent ran hapi-restart-hub at 15:50:27 UTC to pick up a new soup binary. The wrapper counted 1 WORKING (itself), subtracted self, and proceeded with the systemd restart on the assumption that no other sessions were mid-turn.

23 sessions were auto-archived between 15:50:27 and 15:53:11 UTC, all with archivedBy: 'cli', archiveReason: 'User terminated' (the wrong reason is filed separately). All 23 were idle/inactive at restart time - the wrapper's patient-mode check was working as designed. The architecture itself archives idle agents on parent-runner death.

22 of 23 had cursorSessionId properly persisted and were sweep-recoverable by flipping lifecycleState to inactive post-hoc. 1 of 23 lost cursorSessionId to the persistence race (filed separately) and required manual sqlite surgery.

This cycle repeats every soup rebuild. Sessions accumulate as "archived" entries that the operator never chose to archive.

Why the current pattern exists

The runner manages a fleet of child agent processes (one per session). When systemd stops the hub, the runner gets SIGTERM, processes it in cli/src/runner/run.ts:66-69 → requestShutdown('os-signal'), and the shutdown path tears down the per-session children via killProcess (SIGTERM → SIGKILL escalation, run.ts:583-586). Children archive themselves on termination because that's the contract for "agent process exiting." There's no signal to the children that this is a temporary parent-bounce rather than a permanent kill.

Operator workaround hapi-restart-hub --patient only protects sessions mid-turn (WORKING state); idle sessions still die. This is a coverage gap by design - the patient check is necessary-but-not-sufficient.

Why this is genuinely architectural, not just a bug

The cascade is correct given the current process tree. Any fix has to change the process tree or the death contract:

  • Hub and agents share a process tree where hub-stop ⇒ children-die
  • Agents archive on death because death is treated as terminal
  • No "pause / restore" semantics exist for the runner→agent relationship

Possible upstream-side fixes (none small):

Fix direction Sketch Cost
a) Agents survive runner restart Detach agent children from the runner process tree (systemd-style, or setsid + reparent to PID 1). Agents stay alive when runner dies; reconnect to new runner on restart. High - requires reconnect protocol, agent-side discovery, lifetime management outside runner
b) Runner restart doesn't cascade through agents Hub restart preserves the runner; only hub-side state recycles. Runner stays alive across hub bounces with cached agent handles. Medium - decouple hub-runner lifetime; runner becomes long-lived
c) Runner signals "pause" before kill Runner sends a pause RPC to each agent before SIGTERM. Agent serializes its state, exits with archiveReason='Hub restart - resumable', hub holds the resume token, hub-restart UI re-spawns agents transparently. Medium - new protocol surface; agents become checkpoint-aware
d) Idempotent "archived-but-resumable" lifecycle Treat hub-restart-induced archive differently in DB + UI: don't show as terminated, auto-resume on next hub-up, retain all live-session signals. Low-medium - changes lifecycle state machine; UX clearer

(b) is probably the highest-leverage architectural change. (d) is the least invasive while still removing the audit-trail noise.

Acceptance criteria (umbrella - any fix counts as progress)

  • [ ] After systemctl restart hapi-hub.service, the number of sessions in lifecycleState='archived' is unchanged (modulo any that were actively being archived at restart time)
  • [ ] Live sessions visible in the web UI before restart are visible after restart (modulo a brief disconnected indicator during the bounce)
  • [ ] No DB writes flipping idle sessions to archived as a side effect of restart
  • [ ] Mid-turn sessions either complete their turn after reconnect, or surface a clear "interrupted by restart" message (NOT silently archived)

Related

  • #842 (open) - metadata.lifecycleState='running' never reconciled against active=0 - the cousin issue. #842 is about zombie sessions appearing live after host outage; this issue is about sessions being killed-by-design when the hub bounces. Together they delineate the "we don't have a good model for hub/agent lifetime independence" problem.
  • #709 (closed) - persist permissionMode to SQLite so YOLO/mode survives hub restart - precedent that hub-restart-survival of session state is a recognized concern; that fix is for permissionMode specifically, not the broader pattern.
  • #461 (closed) - Reduce per-session memory overhead by sharing the Node.js runtime - related runtime architecture discussion.
  • Sibling: forthcoming issue on the cursorSessionId persistence race during hub-restart (variant #1).
  • Sibling: forthcoming issue on the wrong archiveReason label applied during cascade-archive.
  • Sibling: forthcoming issue on POST /archive 500 when CLI is gone (which compounds this: even the manual cleanup after a cascade-archive incident fails).

Why upstream

The cascade applies to every HAPI installation, not just our fork's soup workflow. Anyone running systemctl restart hapi-hub.service or pkill hub or any process-manager-driven restart hits this. The pain scales with session fleet size; small-fleet users see 1-2 sessions die per restart and may not notice. Heavy-use fleets (20+ active) see this every time.

Operator words (for the record)

"we did not CHOOSE to archive ANYTHING just by virtue of a goddamn hub restart."

Aligns with the architectural framing above.

Environment

  • HAPI upstream/main 93d00414 (codepath verified)
  • Linux, hub + runner under systemd, restart via systemctl restart hapi-hub.service
  • Fleet of 24+ cursor ACP sessions

Disclosure: this issue was drafted by Claude Sonnet 4.6 (model claude-sonnet-4-5) acting as the upstream-discovery peer agent in a multi-agent HAPI fork workflow. Operator soup-keeper agent identified the incident and handed off for triage. Per the AI-assisted contributions policy in CONTRIBUTING.md.

heavygee avatar Jun 15 '26 16:06 heavygee

Sibling issues from same 2026-06-15 hub-restart incident (filed as a bundle):

  • #913 - cursor ACP fresh-session: cursorSessionId persistence race
  • #914 - wrong archiveReason "User terminated" applied to SIGTERM cascade
  • #915 - architectural: hub restart cascade-archives every idle session
  • #916 - POST /archive returns 500 when CLI is gone

#915 is the root cause; #913, #914, #916 are the user-facing consequences.

heavygee avatar Jun 15 '26 16:06 heavygee

I verified this against 93d00414. The code confirms the child-agent death contract, but I do not find the direct hub stop -> runner SIGTERM -> runner cleanup kills tracked sessions path in this checkout.

What I found:

  • Runner-spawned session wrappers are spawned detached, with an inline comment saying they should stay alive when the runner stops.
  • Runner shutdown cleanup updates runner state, shuts down the machine socket/control server, cleans runner state, releases the lock, and exits. I do not see it iterating pidToTrackedSession or killing tracked children in that shutdown path.
  • If a session wrapper does receive SIGTERM/SIGINT, it does archive itself, with default archiveReason = 'User terminated'. So the observed DB writes are consistent with the wrappers receiving termination signals; the missing link is what is sending those signals in the reported deployment.
  • The documented Linux setup uses separate hapi-hub.service and hapi-runner.service; the runner unit is After=network.target hapi-hub.service, not PartOf=/BindsTo= the hub in the docs.

So: the architecture concern is valid if the runner/session wrappers are in the hub service cgroup or otherwise receive SIGTERM during the hub restart, but I cannot verify that from repo code alone. In upstream 93d00414, runner shutdown itself does not appear to cascade-kill tracked sessions.

Relevant code:

  • cli/src/runner/run.ts:453 - runner-spawned session wrapper uses spawnHappyCLI(..., { detached: true }).
  • cli/src/runner/run.ts:1049 - runner shutdown cleanup path starts; no tracked-session kill in this block.
  • cli/src/agent/runnerLifecycle.ts:26 - default archive reason is User terminated.
  • cli/src/agent/runnerLifecycle.ts:33 - cleanup writes lifecycleState: 'archived', archivedBy: 'cli', and archiveReason.
  • cli/src/agent/runnerLifecycle.ts:107 - SIGTERM handler calls cleanup/archive/exit.
  • docs/guide/installation.md:513 - documented hapi-hub.service example.
  • docs/guide/installation.md:530 - documented separate hapi-runner.service example.

Need more info:

  • The exact hapi-hub.service and hapi-runner.service unit files/drop-ins, including KillMode, PartOf, BindsTo, ExecStart, and any wrapper script.
  • Whether runner/session wrapper PIDs are in the same systemd cgroup as hapi-hub.service before restart (systemctl status or systemd-cgls output is enough).
  • Runner log lines around the restart showing whether it received SIGTERM and what shutdownSource was.
  • One archived session wrapper log around its SIGTERM/cleanup, if available.

HAPI Bot

github-actions[bot] avatar Jun 15 '26 16:06 github-actions[bot]

Bundle addendum (2026-06-15 17:27 BST follow-up): also filed #917 - POST /reopen on archived cursor ACP session: spawned cursor-agent dies ~90s after successful ACP load and merges away the original. The reopen path is the cleanup story for #915's cascade-archive, so a failed reopen leaves the operator strictly worse off than before. Hypothesis (1) in #917 (cursor-agent idle exit post-resume) is the easiest to falsify in isolation.

heavygee avatar Jun 15 '26 16:06 heavygee

Bundle addendum (round 3, 2026-06-15 17:40 BST):

  • #918 - web: text-only send to inactive session silently restores composer with no error UI
  • #919 - sessionCache: renameSession / clearSessionArchiveMetadata / restoreSessionArchiveMetadata throw on version-mismatch without refresh

#918 makes the cascade-archive (#915) much more painful (operator can't tell sessions are dead). #919 is the missing self-heal that forced the soup-keeper to use a CLI-socket workaround to recover sovereignty (#913).

heavygee avatar Jun 15 '26 16:06 heavygee

2026-06-16 follow-up - the diagnosis is narrower than I thought when I filed this.

After the second cascade event in 12 hours (operator's HAPI hub stayed dark for 7 hours overnight after a soup-keeper agent's stack-switch tooling timed out), I traced the actual mechanism on a live system. Posting because it changes the recommended fix from "architectural decoupling (option b)" to "two-line systemd unit fix":

What the runner code already does correctly

  • cli/src/runner/run.ts:454 spawns child agents with detached: true. Comment: "Sessions stay alive when runner stops".
  • cli/src/runner/run.ts:1049-1075 (cleanupAndShutdown) does NOT iterate pidToTrackedSession or kill any tracked children. The runner exits cleanly without touching its descendants.
  • cli/src/api/apiMachine.ts:385-387 configures socket.io with reconnection: true, reconnectionDelay: 1000, reconnectionDelayMax: 5000. The disconnect handler on line 434 does NOT call requestShutdown or process.exit.

So the runner is already a long-lived process designed to survive hub bounces and to leave its children alone when it itself exits. The HAPI Bot pointed this out in the previous comment - the "missing link" was what was sending SIGTERM to children.

What's actually killing them

It's the systemd unit cgroup, ignoring detached: true.

detached: true in Node's child_process calls setsid() (new process session) and detaches from the controlling TTY. It does NOT escape the parent's systemd cgroup. Cgroup membership is set by systemd, not by the application. When a unit is stopped with the default KillMode=control-group, systemd sends SIGTERM (then SIGKILL) to every PID in the cgroup, regardless of any setsid the application did.

Live evidence from this host's systemd-cgls /system.slice/hapi-runner.service right now shows ~6 cursor-agent processes, 1 claude process, multiple bun runner workers, and assorted tool-call shells, all under the runner unit's cgroup. The reference unit in docs/guide/installation.md:530 doesn't set KillMode, so the default control-group applies. Every operator who follows the install guide has this same pattern - hub-restart does NOT directly kill them (the docs don't have Requires=hapi-hub.service), but systemctl restart hapi-runner.service definitely does.

The fix

Two changes to docs/guide/installation.md's reference systemd unit for the runner:

[Service]
Type=simple
KillMode=process    # NEW - only kill the main runner PID, not the cgroup
ExecStart=/usr/local/bin/hapi runner start-sync
Restart=always
RestartSec=5

With KillMode=process:

  • systemctl stop hapi-runner.service SIGTERMs only the main runner PID
  • The runner's cleanup runs (does not touch children)
  • Children stay alive in their detached sessions
  • Runner exits
  • New runner starts (Restart=always), reconnects to hub via socket.io, re-discovers existing children via control protocol

This makes (b) "Hub restart preserves the runner; only hub-side state recycles" work as already-coded, with a one-line systemd config change rather than the larger surgery the original sketch implied.

What this still doesn't fix (Tier B - separate issue forthcoming)

If the runner itself crashes/dies before children, on next runner start the children are orphans (no parent control protocol). They'll continue running, but the runner won't know about them. Acceptance criteria #2 (live sessions still visible after restart) needs the runner to scan for orphaned children on startup and re-establish control - or scan the sessions table for active=1 AND startedBy=runner and respawn with --resume. Filing that as a complementary issue; it's a smaller scope once Tier A lands.

Local incident sequence (for the record)

This morning's incident:

  1. 02:55:10 BST - operator-blessed agent ran hapi-use-driver → hapi-use-worktree → patient_drain (10min budget)
  2. 9 active runners in the drain count, including the agent's own session - deadlock by self-reference
  3. 03:05:10 BST - patient_drain timed out at 600s, proceeded to sudo systemctl stop hapi-hub.service
  4. Local unit had Requires=hapi-hub.service (not in upstream's reference, our local drift) - hub-stop cascade-triggered runner-stop
  5. KillMode=control-group killed the entire runner cgroup, including the cursor-agent process running hapi-use-worktree
  6. The script was killed mid-execution before reaching systemctl restart hapi-hub.service - hub stayed orphaned-stopped
  7. ~7 hours dark until operator manually restarted

Both layers of this (the local Requires= drift AND the upstream-default KillMode=control-group) need fixing. PR for the upstream piece incoming.

heavygee avatar Jun 16 '26 09:06 heavygee