Skip to content

Acknowledge daemon heartbeats without touching SQLite - #7760

Merged
ymichael merged 2 commits into
mainfrom
bb/6499-heartbeats-off-sqlite
Nov 18, 2026
Merged

ymichael merged 2 commits into
mainfrom
bb/6499-heartbeats-off-sqlite

Conversation

@ymichael

@ymichael ymichael commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

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 Let a host daemon session outlive its WebSocket #7764: pnpm exec turbo run typecheck --filter=@bb/server, plus test/hosts (including Let a host daemon session outlive its WebSocket #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

ymichael added a commit that referenced this pull request Nov 18, 2026
## 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/open` again
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_VERSION` 267 → 268)**
- Every WebSocket message in both directions is now wrapped in
`{"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:
- it numbers outgoing frames and keeps the unacknowledged ones (capped
at 16M chars)
  - it trims kept frames when the peer's cumulative ack arrives
  - it drops duplicates and reports a sequence gap
- Acks ride on every frame, and a standalone ack goes out after 64
messages or 256K chars, so kept frames stay small.
- The session-open response gains `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
reason `daemon-shutdown` means "I'm going away, end the session now".

**Experiment (`resumeDaemonSessions`, off by default, on for early
adopters)**
- The hold-and-resume behaviour below is behind this experiment, as a
kill switch. While it is off, the server ends the session as soon as the
socket closes, as on main, and session open returns `reconnectGraceMs:
0`. A daemon that gets 0 opens a new session after a drop and does not
try to resume.
- The sequenced frame format and the daemon's send queue ship to
everyone either way.
- The server reads the flag at each socket close and session open, so a
toggle applies from the next disconnect. It appears in Settings →
Experiments and `bb settings experiment resumeDaemonSessions`, and is
documented in `docs/configuration.md` and 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 for `HOST_RECONNECT_GRACE_MS` (30 s, unchanged). Terminals,
host RPC waiters, connect capability and the hub registration all stay.
`hasDaemonForHost` stays true during the grace period, as the UI already
showed.
- A resume that arrives in time takes over the channel. The server sends
its ack, replays the frames the daemon hasn't seen, and cancels the
grace timer. If the old socket is somehow still attached, it is closed,
which covers a reconnect after an ack blackout where the server never
saw the close.
- If the grace period runs out, the session ends as `expired`, the same
as a silent daemon. The quiet-check liveness sweep skips detached
sessions so it cannot end them early.
- A resume the server can't honor (unknown session, closed session, or
frames it already dropped) is accepted and then closed with 4409.
- `closeWebSockets` ends all daemon channels before closing sockets, so
server shutdown doesn't start grace timers.
- `onDaemonSocketMessage` now takes the decoded `message` from the frame
instead of a raw string. That is why the server test call sites changed
from `raw: JSON.stringify(x)` to `message: x`.

**Daemon (`ServerConnection`)**
- On a socket close, the daemon keeps its session. It does not call
`setSession(null)`, so the next tunnel and the desktop broker see no
session loss. It reconnects with `resumeFrom` and replays unacknowledged
frames.
- Messages sent while disconnected queue in order, under the existing 32
MB cap, and flush after the resume.
- The heartbeat ack timeout, the 30 s lease and the suspension handling
are unchanged. A timeout now leads to a resume instead of a new session.
- The daemon opens a fresh session only when the server returns 4409,
the grace period passes locally, the frame buffer overflowed, a gap is
detected, or the server sends `session-close`.
- Recoverable messages (`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.
- A send failure now reconnects and replays. Queue overflow opens a new
session. Both used to call partysocket `close()`, which turns off
auto-reconnect for good.
- `shutdown()` closes with reason `daemon-shutdown`.
- Messages queued while disconnected are sent in full as soon as the
socket opens or resumes, so a newer message can't overtake them. An
acknowledgement clears only the exact recoverable message sent at that
sequence, not a newer pending one with the same key.

**Tests and harness**
- `tests/integration/helpers/harness.ts` gains an `experiments` option
and a `proxyDaemonConnection` option: a TCP proxy between daemon and
server that `dropDaemonConnections()` resets, which simulates a tunnel
cut.
- `qa/manual-runbook.md` has 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

- **Real daemon, real server**:
`tests/integration/fake/recovery/resume-dropped-connection.test.ts`
starts 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'`).
- **Real server, real `ws` client**:
`apps/server/test/hosts/daemon-session-resume.test.ts`.
- The first case terminates the socket, starts a host RPC while the
daemon is gone, and resumes. The server replays only frames after
`resumeFrom` and the RPC request exactly once, the RPC resolves, and the
session stays active.
- The second case shows that a resume from a sequence the server never
sent gets close code 4409.
- The third case checks that a detached session survives the grace
period (the liveness sweep doesn't end it), then closes as `expired`.
- The fourth case checks that `daemon-shutdown` ends the session at
once.
- `server-connection.test.ts` covers 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).
- Experiment off: `daemon-session-resume.test.ts` checks that session
open offers no grace and a socket close ends the session at once, and
`server-connection.test.ts` checks that a daemon offered no grace opens
a new session without `resumeFrom`. Both fail with the gating removed.
The resume tests turn the experiment on.
- **Daemon unit tests** (`server-connection.test.ts`):
- The SlopCop acceptance test, adapted: three connections, a 32 s ack
blackout. Each one still detects the dead peer and reconnects at 35 s,
and each resumes `session-1` without a second `openSession`, without
`setSession(null)`, and with `resumeFrom=1`. Acks then keep each one up.
  - Replayed server frames are ignored.
- An unacknowledged recoverable message is re-sent in a new session, and
an acknowledged one is not.
  - The local grace deadline works.
  - Shutdown closes with `daemon-shutdown`.
  - Existing heartbeat, suspension and dead-peer tests pass unchanged.
- `packages/host-daemon-contract/test/ws-channel.test.ts` covers 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.
- I ran `pnpm exec turbo run typecheck` for `@bb/server`,
`@bb/host-daemon`, `@bb/host-daemon-contract` and
`@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 daemon
`server-connection`, `app`, `server-client` and 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

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael and others added 2 commits November 18, 2026 11:39
Every daemon heartbeat used to read the session row and run a write
transaction (heartbeatSession + markHostSeen) before the server sent
heartbeat-ack, so a busy database delayed every host's acknowledgement.

The server now acknowledges a heartbeat as soon as it arrives on the
socket the hub has registered for that session, and persists the lease
at most once per lease period. Liveness stays in the hub's in-memory
tracking. The Connect shared-ports "is this host online" check now asks
the hub instead of the persisted lease, which can lag by up to one
heartbeat interval between renewals.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Renewing only after a full lease period let the persisted lease lapse for
up to one heartbeat before each renewal. Heartbeats are phase-locked to
the renewal, so a lease-minus-one-heartbeat threshold also lapses whenever
jitter brings that heartbeat in early.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/6499-heartbeats-off-sqlite branch from b56976d to 07b7be0 Compare November 18, 2026 19:39
@ymichael
ymichael merged commit 60af38a into main Nov 18, 2026
32 checks passed
@ymichael
ymichael deleted the bb/6499-heartbeats-off-sqlite branch November 18, 2026 20:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant