Repository navigation
Let a host daemon session outlive its WebSocket - #7764
Merged
Merged
Conversation
Every daemon socket close used to end the session on the server: terminals closed, in-flight host RPCs failed, and the daemon had to POST /internal/session/open again through the Connect tunnel, which answers 502/504 while the tunnel is down. A server stall or a routine Cloudflare tunnel cut therefore turned into a full reconnect of every machine. Daemon and server now wrap every WebSocket message in a frame carrying a sequence number and a cumulative acknowledgement (HostDaemonWsSequencer in the contract). Each side keeps unacknowledged frames, capped at 16M chars, and drops duplicates by sequence number. When a socket closes, the server holds the session for HOST_RECONNECT_GRACE_MS and buffers what it sends. The daemon keeps its session and reconnects with ?resumeFrom=<last received seq>. Both sides then replay what the other has not acknowledged, so nothing is lost or delivered twice, and terminals, RPC waiters and running turns carry on. The server answers a resume it cannot honor with close code 4409, and the daemon then opens a fresh session as before. A daemon that is shutting down closes with reason daemon-shutdown, so its session ends at once. Server shutdown ends all channels before closing the sockets. Dead-peer and suspension detection are unchanged: the 30 s lease and the ack-timeout reconnect stay, and the timeout now leads to a resume instead of a new session. The session-open response gains reconnectGraceMs, and HOST_DAEMON_PROTOCOL_VERSION goes to 268. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Messages queued while the socket was down drained under the 1 MB high-water mark after a resume, so a newer message that skips the terminal queue could reach the server first and leave it with stale state. Drain the whole queue when the socket opens or resumes. An acknowledgement for an older recoverable message also dropped a newer pending one with the same key, so a fallback to a new session never re-sent it. Track which message was sent at each sequence and prune only that one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The experiment is off by default and on for early adopters. While it is off, the server ends a daemon's session as soon as its socket closes, as before, and session open returns reconnectGraceMs 0 so the daemon opens a new session after a drop instead of trying to resume. The sequenced frame format ships either way. The flag is read at each socket close and session open, so a toggle applies from the next disconnect. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 18, 2026
## Human comments ## What was wrong Part 1 of 2 for #6499. Every host daemon heartbeat (one per machine every 5 s) made the server read the session row and run a write transaction (`heartbeatSession` + `markHostSeen`) before it sent `heartbeat-ack` (`apps/server/src/ws/daemon-protocol.ts`). That write runs synchronously on the server's main thread ahead of the acknowledgement that keeps each daemon's 30 s lease alive. In production server logs it usually takes about 3 ms, but it is the most common longest-running task in event-loop stall records and has reached 748 ms. If the write fails, for example `database is locked` after the 5 s busy timeout, the server closes the daemon's socket instead of acknowledging it. Report: https://get-bb.github.io/reports/issues/6499.html This does not keep acknowledgements flowing through a server stall. Any other synchronous work, including other writes waiting on a locked database, still blocks the event loop and delays every daemon's ack. With a 45 s external write lock on `bb.db`, main closed the daemon after its heartbeat write failed, and this branch still lost the daemon to `heartbeat-ack-timeout` during a 39 s stall caused by other writes. ## What changed - `onDaemonSocketMessage` sends `heartbeat-ack` as soon as a heartbeat arrives on the socket the hub has registered for that session, with no database work. Liveness stays where it already was: the hub's in-memory quiet-check counter. - The lease row (`leaseExpiresAt`, `hosts.lastSeenAt`) is persisted at most once every 20 s, the lease minus two heartbeat intervals (`NotificationHub.takeDaemonLeaseRenewal`), on whichever daemon message arrives first after that. Renewing two heartbeats early keeps the persisted lease valid between renewals: heartbeats arrive at multiples of 5 s after a renewal, so a one-heartbeat margin would miss its cutoff whenever jitter brings that heartbeat in early, and the lease would lapse. Before, every heartbeat wrote, and so did any other message once 5 s had passed. - A heartbeat that triggers that renewal also re-checks the session row, so a session closed in the database while the hub still holds its socket gets closed at the next renewal check, within about 25 s. Other daemon messages still check the session row every time, as before. - `HostSharedPortCoordinator` decides whether a host is online for Connect by asking whether the hub holds that session's socket, not by reading the persisted lease, which is now renewed only every 20 s. There are no wire changes, so `HOST_DAEMON_PROTOCOL_VERSION` is unchanged. Part 2, #7764 (sessions that survive a dropped socket), has landed and this branch is rebased onto it. The "hub holds this session's socket" check now compares against the session's `DaemonChannel` (`getDaemonSessionSocket`), so a heartbeat arriving on a resumed socket is acked the same way. The resume path checks only the session's status, not the persisted lease, so the 20 s renewal does not affect resuming. ## How you verified - `test/hosts/daemon-liveness.test.ts`: 40 heartbeats and 40 RPC responses inside one 20 s renewal interval produce 40 acks and zero SQLite changes (`total_changes()`). Crossing the interval renews the lease exactly once. Heartbeats every 5 s with alternating ±20 ms jitter for 5 minutes never find the persisted lease expired; this test fails with a 30 s or 25 s renewal interval. A backwards clock still renews monotonically. A heartbeat on a session closed in the database is acked until the next renewal check, which then closes the socket with `inactive-session`. A non-heartbeat message on a closed session is still rejected immediately. The existing silent-daemon expiry tests are unchanged and pass. - `test/app/host-shared-ports.test.ts`: a host with a lapsed persisted lease counts as connected while the hub holds its socket and as offline once the hub drops it. - After rebasing onto #7764: `pnpm exec turbo run typecheck --filter=@bb/server`, plus `test/hosts` (including #7764's `daemon-session-resume.test.ts`), `test/internal`, `test/server-move` and shared ports: 42 files, 302 tests pass. CI runs the full suites. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
Every time a daemon's WebSocket closed, the server ended that daemon's session on the spot. Open terminals were marked disconnected until the new session reattached them, live terminal attaches and in-flight host RPCs failed, and the daemon had to POST
/internal/session/openagain before it could reconnect. That request goes through the Connect tunnel, which answers 502/504 while it is down. So every tunnel cut (Cloudflare restarts Connect tunnels roughly every 27 minutes) and every heartbeat-lease expiry after a server stall made every machine drop and reopen its session at the same moment, with work interrupted. Report: https://get-bb.github.io/reports/issues/6499.html. Part 1, which takes heartbeat acks off SQLite, is #7760. This PR does not depend on it.What changed
Wire (
HOST_DAEMON_PROTOCOL_VERSION267 → 268){"seq":N,"ack":M,"message":{…}}, or sent as an ack-only frame{"ack":M}.HostDaemonWsSequencer(packages/host-daemon-contract/src/ws-channel.ts) implements this for both ends:reconnectGraceMs. A reconnect asks to resume with/internal/ws?sessionId=…&resumeFrom=<last received seq>. Close code 4409 means "can't resume, open a new session". Close reasondaemon-shutdownmeans "I'm going away, end the session now".Experiment (
resumeDaemonSessions, off by default, on for early adopters)reconnectGraceMs: 0. A daemon that gets 0 opens a new session after a drop and does not try to resume.bb settings experiment resumeDaemonSessions, and is documented indocs/configuration.mdand the customization guide.Server
DaemonChannel(apps/server/src/ws/daemon-channel.ts) is the session's long-lived socket in the hub. When the raw socket closes, the channel detaches, keeps buffering what the server sends, and the session stays active forHOST_RECONNECT_GRACE_MS(30 s, unchanged). Terminals, host RPC waiters, connect capability and the hub registration all stay.hasDaemonForHoststays true during the grace period, as the UI already showed.expired, the same as a silent daemon. The quiet-check liveness sweep skips detached sessions so it cannot end them early.closeWebSocketsends all daemon channels before closing sockets, so server shutdown doesn't start grace timers.onDaemonSocketMessagenow takes the decodedmessagefrom the frame instead of a raw string. That is why the server test call sites changed fromraw: JSON.stringify(x)tomessage: x.Daemon (
ServerConnection)setSession(null), so the next tunnel and the desktop broker see no session loss. It reconnects withresumeFromand replays unacknowledged frames.session-close.terminal.exited,environment-change, tunnel identity, and the rest) now stay pending until the server acknowledges them, not just until they are sent. If the daemon has to fall back to a new session, it re-sends only the ones the old session never acknowledged.close(), which turns off auto-reconnect for good.shutdown()closes with reasondaemon-shutdown.Tests and harness
tests/integration/helpers/harness.tsgains anexperimentsoption and aproxyDaemonConnectionoption: a TCP proxy between daemon and server thatdropDaemonConnections()resets, which simulates a tunnel cut.qa/manual-runbook.mdhas a short check for the new log lines.Deviation from the issue's suggestion: the lease and tunnel deadlines are not raised. The daemon still treats 30 s without acks as a dead peer. That reconnect now costs a 1–2 s resume instead of a new session.
How you verified
tests/integration/fake/recovery/resume-dropped-connection.test.tsstarts a delayed turn, resets the daemon's TCP connection mid-turn through the proxy, and checks that the turn finishes, the daemon keeps the same session id, and the host still has exactly one session row (active). I disabled daemon-side resume temporarily to confirm the test fails without this change (expected 'hses_anb7777sw4' to be 'hses_gppnkxnka5').wsclient:apps/server/test/hosts/daemon-session-resume.test.ts.resumeFromand the RPC request exactly once, the RPC resolves, and the session stays active.expired.daemon-shutdownends the session at once.server-connection.test.tscovers both follow-up fixes: a message queued during a drop reaches the server before one sent after the resume (fails without the full drain), and the newest recoverable message is re-sent in a new session when only an older one with its key was acknowledged (fails without either fix).daemon-session-resume.test.tschecks that session open offers no grace and a socket close ends the session at once, andserver-connection.test.tschecks that a daemon offered no grace opens a new session withoutresumeFrom. Both fail with the gating removed. The resume tests turn the experiment on.server-connection.test.ts):session-1without a secondopenSession, withoutsetSession(null), and withresumeFrom=1. Acks then keep each one up.daemon-shutdown.packages/host-daemon-contract/test/ws-channel.test.tscovers dedupe across a replay, gap detection, overflow blocking a resume until the peer acknowledges the dropped frames, and an ack beyond what was sent being treated as invalid.pnpm exec turbo run typecheckfor@bb/server,@bb/host-daemon,@bb/host-daemon-contractand@bb/integration-tests. I also ran the targeted server tests (hosts, internal, server-move, shared ports, desktop browsers, public terminals and host management, websocket compression), the daemonserver-connection,app,server-clientand terminal tests, the contract suite, and the integration recovery tests (resume-dropped-connection,reconnect-open-work,active-crash-recovery). CI runs the full suites.Fixes #6499
🤖 Generated with Claude Code