From f82bddcb4068497ce7ae1459097377bcae5aafb7 Mon Sep 17 00:00:00 2001 From: David East Date: Wed, 14 Oct 2026 18:50:44 -0700 Subject: [PATCH 1/3] fix(remote): the Node remote client sends a heartbeat and treats 45 s of silence as a drop (#973) connectRemoteSandbox, and the lazy remoteSandbox handle that @pyric/cli/register installs, now follow ADR-0019's heartbeat amendment. After attach-ack the client pings at once, which starts the host's watch, then every HOSTED_HEARTBEAT_INTERVAL_MS. Before each ping it checks how long the host has been silent; after 45 s with no frame of any kind it terminates the socket, so the existing close path runs: the eager handle ends its listeners with unavailable, and the lazy handle reconnects on the ADR backoff and resubscribes them. The watch lives in remote/host-liveness.ts. It belongs to one socket and stops on close and on client close, pings bypass the operation budget, and every timer is unref'd so an idle script still exits. The 45 s value is local until the shared HOSTED_CLIENT_LIVENESS_TIMEOUT_MS lands in bridge/protocol.ts. Tests: host-liveness.test.ts (fake timers); reconnect.test.ts over a real ws server that stops answering without closing (fails on main: no loss is reported and the listener never resubscribes); loop-hold.test.ts spawns a real Node process on the built client that stays idle through several heartbeats and exits. Refs #973 --- packages/cli/src/remote/host-liveness.ts | 93 +++++++++++++++ packages/cli/src/remote/index.ts | 27 ++++- .../cli/test/remote/host-liveness.test.ts | 101 ++++++++++++++++ packages/cli/test/remote/loop-hold.test.ts | 77 ++++++++++++ packages/cli/test/remote/reconnect.test.ts | 111 +++++++++++++++++- 5 files changed, 404 insertions(+), 5 deletions(-) create mode 100644 packages/cli/src/remote/host-liveness.ts create mode 100644 packages/cli/test/remote/host-liveness.test.ts diff --git a/packages/cli/src/remote/host-liveness.ts b/packages/cli/src/remote/host-liveness.ts new file mode 100644 index 0000000000..571e2ee456 --- /dev/null +++ b/packages/cli/src/remote/host-liveness.ts @@ -0,0 +1,93 @@ +/** + * Client-side heartbeat for the Node remote client (ADR-0019, #973). + * + * The client pings once at attach, which starts the host's own watch, then + * every {@link HOSTED_HEARTBEAT_INTERVAL_MS} while attached. Before each ping + * it checks how long the host has been silent: once no frame of any kind has + * arrived for {@link HOST_SILENCE_TIMEOUT_MS}, the socket is treated as + * dropped and `onSilent` runs once instead of pinging a socket the host has + * already closed. The watch belongs to one socket and never outlives it. + * + * Every timer is unref'd, so an idle attached client never keeps a finished + * script alive. + */ +import { HOSTED_HEARTBEAT_INTERVAL_MS, type BridgeMessage } from '../bridge/protocol.js'; + +/** + * Silence that counts as a drop: three heartbeats, as the web client uses. + * ADR-0019's heartbeat amendment names this value; the shared constant in + * `bridge/protocol.ts` replaces this one once both land. + */ +export const HOST_SILENCE_TIMEOUT_MS = 45_000; + +export interface HostLivenessOptions { + /** Send one frame on the watched socket; a throw counts as a drop. */ + send(message: BridgeMessage): void; + /** Called once when the host has gone silent or the ping cannot be sent. */ + onSilent(): void; + intervalMs?: number; + timeoutMs?: number; +} + +export interface HostLiveness { + /** Record a frame from the host. */ + heard(): void; + /** Stop the watch; called when the socket closes. Idempotent. */ + stop(): void; +} + +/** Ping now and on every interval; call `onSilent` once the host stops answering. */ +export function watchHostLiveness(options: HostLivenessOptions): HostLiveness { + const intervalMs = options.intervalMs ?? HOSTED_HEARTBEAT_INTERVAL_MS; + const timeoutMs = options.timeoutMs ?? HOST_SILENCE_TIMEOUT_MS; + let lastHeardAt = Date.now(); + let pings = 0; + let timer: ReturnType | undefined; + let stopped = false; + + function stop(): void { + stopped = true; + clearTimeout(timer); + timer = undefined; + } + + function drop(): void { + stop(); + options.onSilent(); + } + + function ping(): void { + pings += 1; + try { + options.send({ type: 'ping', id: `heartbeat-${pings}` }); + } catch { + drop(); + return; + } + schedule(); + } + + function schedule(): void { + if (stopped) return; + const remainingMs = timeoutMs - (Date.now() - lastHeardAt); + timer = setTimeout(beat, Math.max(0, Math.min(intervalMs, remainingMs))); + timer.unref?.(); + } + + function beat(): void { + const hasGoneSilent = Date.now() - lastHeardAt >= timeoutMs; + if (hasGoneSilent) { + drop(); + return; + } + ping(); + } + + ping(); + return { + heard: () => { + lastHeardAt = Date.now(); + }, + stop, + }; +} diff --git a/packages/cli/src/remote/index.ts b/packages/cli/src/remote/index.ts index 4960e80fa5..5bc04362c4 100644 --- a/packages/cli/src/remote/index.ts +++ b/packages/cli/src/remote/index.ts @@ -55,6 +55,7 @@ import type { import { isBridgeMessage, MAX_BRIDGE_FRAME_BYTES, NO_SANDBOX_ERROR_MESSAGE, STORAGE_BYTE_ROUTE_CAPABILITY } from '../bridge/protocol.js'; import { encodeBridgeMessage } from '../bridge/frame-output.js'; import { createOperationBudget } from '../bridge/operation-budget.js'; +import { HOST_SILENCE_TIMEOUT_MS, watchHostLiveness, type HostLiveness } from './host-liveness.js'; import { cliVersion } from '../pkg-version.js'; import { MAX_STORAGE_OP_BYTES, storagePayloadTooLarge } from '../serve/worker/protocol.js'; import { hasValidAttachFields } from '../bridge/attach-validation.js'; @@ -133,6 +134,10 @@ export interface ConnectRemoteSandboxOptions { * them; when absent, the close ends every listener with `unavailable`. */ onConnectionLost?: (reason: string) => void; + /** Heartbeat interval in ms (ADR-0019). Default: 15 s. Tests pass shorter values. */ + heartbeatIntervalMs?: number; + /** Silence from the host, in ms, that counts as a drop (ADR-0019). Default: 45 s. */ + hostSilenceTimeoutMs?: number; } /** @@ -1007,7 +1012,10 @@ export async function connectRemoteSandbox( { serveUrl, opTimeoutMs: options.opTimeoutMs }, ); + let liveness: HostLiveness | undefined; + let silenceReason: string | undefined; ws.on('message', (raw) => { + liveness?.heard(); let parsed: unknown; try { parsed = JSON.parse(raw.toString()); @@ -1065,6 +1073,7 @@ export async function connectRemoteSandbox( onConnectionLost(reason); }; ws.on('close', (code) => { + liveness?.stop(); // A policy close (1008) is the host refusing this client, not a restart: // it is final, as ADR 0019 rules, so retrying would only be refused again. // Its `permission-denied` code tells the lazy handle not to retry. @@ -1073,7 +1082,7 @@ export async function connectRemoteSandbox( core.fail('remote sandbox connection closed by the host for a policy violation', REFUSED_CODE); return; } - loseConnection('remote sandbox connection closed (serve stopped or connection lost)'); + loseConnection(silenceReason ?? 'remote sandbox connection closed (serve stopped or connection lost)'); }); ws.on('error', (err) => loseConnection(`remote sandbox connection failed: ${err.message}`)); @@ -1106,6 +1115,21 @@ export async function connectRemoteSandbox( throw err; } attached = true; + // Pings go straight to the socket: they bypass the operation budget and + // never ref it, so an idle script still exits. A silent host is a drop. + const silenceTimeoutMs = options.hostSilenceTimeoutMs ?? HOST_SILENCE_TIMEOUT_MS; + const startHeartbeat = (): HostLiveness => + watchHostLiveness({ + send: (message) => ws.send(JSON.stringify(message)), + onSilent: () => { + silenceReason = `the remote sandbox sent nothing for ${silenceTimeoutMs / 1000}s`; + ws.terminate(); + }, + intervalMs: options.heartbeatIntervalMs, + timeoutMs: silenceTimeoutMs, + }); + const isOpen = ws.readyState === WebSocket.OPEN; + if (isOpen) liveness = startHeartbeat(); // A host with a byte route takes Storage bytes over HTTP, authorized by the // session token its init.json hands a local process. @@ -1118,6 +1142,7 @@ export async function connectRemoteSandbox( channel: { ...core.channel, byteRoute: async () => byteRoute }, close() { closedByClient = true; + liveness?.stop(); core.dispose('remote sandbox connection closed by the client'); try { ws.close(); diff --git a/packages/cli/test/remote/host-liveness.test.ts b/packages/cli/test/remote/host-liveness.test.ts new file mode 100644 index 0000000000..a389fa6bca --- /dev/null +++ b/packages/cli/test/remote/host-liveness.test.ts @@ -0,0 +1,101 @@ +/** + * The Node remote client's heartbeat (ADR-0019, #973). Unit evidence with + * faked timers; `reconnect.test.ts` drives the same watch over a real `ws` + * server that stops answering without closing. + */ +import { afterEach, beforeEach, describe, expect, it, jest } from 'bun:test'; +import { HOSTED_HEARTBEAT_INTERVAL_MS, type BridgeMessage } from '../../src/bridge/protocol.js'; +import { HOST_SILENCE_TIMEOUT_MS, watchHostLiveness } from '../../src/remote/host-liveness.js'; + +function startWatch(send: (message: BridgeMessage) => void = () => {}) { + const sent: BridgeMessage[] = []; + let silences = 0; + const liveness = watchHostLiveness({ + send: message => { + sent.push(message); + send(message); + }, + onSilent: () => { + silences += 1; + }, + }); + return { liveness, sent, silences: () => silences }; +} + +beforeEach(() => { + jest.useFakeTimers(); +}); + +afterEach(() => { + jest.useRealTimers(); +}); + +describe('watchHostLiveness', () => { + it('pings at start, then once per interval while the host answers', () => { + const { liveness, sent } = startWatch(); + expect(sent).toEqual([{ type: 'ping', id: 'heartbeat-1' }]); + for (let beat = 2; beat <= 6; beat += 1) { + jest.advanceTimersByTime(HOSTED_HEARTBEAT_INTERVAL_MS - 1); + expect(sent).toHaveLength(beat - 1); + jest.advanceTimersByTime(1); + expect(sent).toHaveLength(beat); + liveness.heard(); + } + expect(new Set(sent.map(message => message.type === 'ping' && message.id)).size).toBe(sent.length); + liveness.stop(); + }); + + it('reports silence once, at the first check after the timeout, instead of pinging', () => { + const { sent, silences } = startWatch(); + jest.advanceTimersByTime(HOST_SILENCE_TIMEOUT_MS - 1); + expect(silences()).toBe(0); + const pingsBeforeTimeout = sent.length; + jest.advanceTimersByTime(1); + expect(silences()).toBe(1); + expect(sent).toHaveLength(pingsBeforeTimeout); + jest.advanceTimersByTime(10 * HOST_SILENCE_TIMEOUT_MS); + expect(silences()).toBe(1); + expect(sent).toHaveLength(pingsBeforeTimeout); + }); + + it('counts any frame from the host, so a host that keeps sending is never silent', () => { + const { liveness, silences } = startWatch(); + for (let elapsed = 0; elapsed < 4 * HOST_SILENCE_TIMEOUT_MS; elapsed += HOST_SILENCE_TIMEOUT_MS / 3) { + jest.advanceTimersByTime(HOST_SILENCE_TIMEOUT_MS / 3); + liveness.heard(); + } + expect(silences()).toBe(0); + liveness.stop(); + }); + + it('measures silence from the last frame, not from the last ping', () => { + const { liveness, silences } = startWatch(); + jest.advanceTimersByTime(HOST_SILENCE_TIMEOUT_MS - 5_000); + liveness.heard(); + jest.advanceTimersByTime(HOST_SILENCE_TIMEOUT_MS - 1); + expect(silences()).toBe(0); + jest.advanceTimersByTime(1); + expect(silences()).toBe(1); + }); + + it('sends nothing and reports nothing once stopped', () => { + const { liveness, sent, silences } = startWatch(); + liveness.stop(); + jest.advanceTimersByTime(10 * HOST_SILENCE_TIMEOUT_MS); + expect(sent).toHaveLength(1); + expect(silences()).toBe(0); + }); + + it('treats a ping the socket refuses as a drop', () => { + let refuses = false; + const { sent, silences } = startWatch(() => { + if (refuses) throw new Error('socket closed'); + }); + refuses = true; + jest.advanceTimersByTime(HOSTED_HEARTBEAT_INTERVAL_MS); + expect(silences()).toBe(1); + jest.advanceTimersByTime(10 * HOST_SILENCE_TIMEOUT_MS); + expect(sent).toHaveLength(2); + expect(silences()).toBe(1); + }); +}); diff --git a/packages/cli/test/remote/loop-hold.test.ts b/packages/cli/test/remote/loop-hold.test.ts index c2a86b0037..62a7bd88b5 100644 --- a/packages/cli/test/remote/loop-hold.test.ts +++ b/packages/cli/test/remote/loop-hold.test.ts @@ -11,10 +11,19 @@ * * 2. Version skew: a live tab whose SharedWorker predates a new op returns * a raw "Unknown method: …" — the client appends restart/reload guidance. + * + * 3. Heartbeat (#973): a real Node process attached over `ws` keeps pinging + * while idle and still exits when its script ends. It runs the built CLI, + * so build first. PYRIC_TEST_NODE optionally selects the Node executable. */ import 'fake-indexeddb/auto'; import { describe, it, expect } from 'bun:test'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { WebSocketServer } from 'ws'; import { initializeSandbox } from 'pyric/sandbox'; import { getFirestore } from 'pyric/firestore'; import { createBridge, type Bridge } from '../../src/bridge/server/bridge.js'; @@ -343,3 +352,71 @@ describe('remote core — version-skew guidance on Unknown method', () => { } }); }); + +// ─── Heartbeat timers never hold the loop (#973) ─────────────────────────── + +/** A bridge host that acknowledges attach, answers ops, and counts pings. */ +async function startPingCountingHost(): Promise<{ url: string; pings: () => number; stop: () => Promise }> { + const http = createServer(); + const server = new WebSocketServer({ server: http, path: '/__pyric/sandbox' }); + http.listen(0, '127.0.0.1'); + await once(http, 'listening'); + let pings = 0; + server.on('connection', (socket) => { + socket.on('message', (raw) => { + const msg = JSON.parse(raw.toString()) as BridgeMessage; + const reply = (frame: BridgeMessage): void => socket.send(JSON.stringify(frame)); + if (msg.type === 'attach') { + reply({ type: 'attach-ack', protocol: 1, bridgeVersion: 'test', peerConnected: true, clientSessionId: 's' }); + } else if (msg.type === 'ping') { + pings += 1; + reply({ type: 'pong', id: msg.id }); + } else if (msg.type === 'worker-op') { + reply({ type: 'worker-res', id: msg.id, ok: true, value: { key: null, exists: true, value: 1, size: 1 } }); + } + }); + }); + const stop = async (): Promise => { + for (const client of server.clients) client.terminate(); + server.close(); + http.closeAllConnections(); + await new Promise((resolve) => http.close(() => resolve())); + }; + return { url: `http://127.0.0.1:${(http.address() as AddressInfo).port}`, pings: () => pings, stop }; +} + +/** Attach, run one op, stay idle long enough for several heartbeats, and end without closing. */ +const IDLE_SCRIPT = ` +const { connectRemoteSandbox } = await import(process.argv[1]); +const remote = await connectRemoteSandbox({ url: process.argv[2], heartbeatIntervalMs: 50 }); +await remote.rtdb.get('a'); +await new Promise((resolve) => setTimeout(resolve, 400)); +process.stdout.write('idle'); +`; + +describe('remote client — heartbeat and the event loop (#973)', () => { + it('an idle attached process keeps pinging and still exits when its script ends', async () => { + const host = await startPingCountingHost(); + try { + const entry = new URL('../../dist/remote/index.js', import.meta.url).href; + const child = spawn( + process.env.PYRIC_TEST_NODE ?? 'node', + ['--input-type=module', '-e', IDLE_SCRIPT, entry, host.url], + { stdio: ['ignore', 'pipe', 'pipe'] }, + ); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => (stdout += chunk)); + child.stderr.on('data', (chunk) => (stderr += chunk)); + const exited = once(child, 'exit').then(([code]) => code as number | null); + const deadline = new Promise<'hung'>((resolve) => setTimeout(() => resolve('hung'), 10_000)); + const outcome = await Promise.race([exited, deadline]); + if (outcome === 'hung') child.kill('SIGKILL'); + expect(outcome, stderr).toBe(0); + expect(stdout).toBe('idle'); + expect(host.pings()).toBeGreaterThanOrEqual(3); + } finally { + await host.stop(); + } + }, 20_000); +}); diff --git a/packages/cli/test/remote/reconnect.test.ts b/packages/cli/test/remote/reconnect.test.ts index a103ff1c7c..d18fb5b8a7 100644 --- a/packages/cli/test/remote/reconnect.test.ts +++ b/packages/cli/test/remote/reconnect.test.ts @@ -11,6 +11,7 @@ import type { AddressInfo } from 'node:net'; import { WebSocketServer } from 'ws'; import type { BridgeMessage } from '../../src/bridge/protocol.js'; import { + connectRemoteSandbox, createLazyRemoteSandbox, createRemoteSandboxHandle, remoteSandbox, @@ -21,9 +22,12 @@ import { /** * A bridge host that acknowledges attach, answers every op with `generation` - * (or none, with `answersOps: false`), and sends one snap per subscription. - * With `refusesAttach`, it refuses every attach with a policy close (1008), - * as the bridge does when it declines a hosted session. + * (or none, with `answersOps: false`), sends one snap per subscription, and + * answers `ping` with `pong`, as the bridge does. With `refusesAttach`, it + * refuses every attach with a policy close (1008), as the bridge does when it + * declines a hosted session. `muteClients` makes the sockets open now go + * silent without closing, as a paused host does; later sockets answer + * `generation`, which `setGeneration` changes. */ async function startFakeHost( port: number, @@ -34,6 +38,8 @@ async function startFakeHost( port: number; stop: () => Promise; closeClients: (code: number, reason: string) => void; + muteClients: () => void; + setGeneration: (next: string) => void; subs: string[]; ops: string[]; attaches: () => number; @@ -45,8 +51,10 @@ async function startFakeHost( const subs: string[] = []; const ops: string[] = []; let attaches = 0; + const muted = new WeakSet(); server.on('connection', socket => { socket.on('message', raw => { + if (muted.has(socket)) return; const msg = JSON.parse(raw.toString()) as BridgeMessage; const reply = (frame: BridgeMessage): void => socket.send(JSON.stringify(frame)); if (msg.type === 'attach') { @@ -59,6 +67,8 @@ async function startFakeHost( } else if (msg.type === 'worker-op') { ops.push(msg.id); if (answersOps) reply({ type: 'worker-res', id: msg.id, ok: true, value: { key: null, exists: true, value: generation, size: 1 } }); + } else if (msg.type === 'ping') { + reply({ type: 'pong', id: msg.id }); } else if (msg.type === 'worker-sub') { subs.push(msg.subId); reply({ type: 'worker-snap', subId: msg.subId, value: { key: null, exists: true, value: generation, size: 1 } }); @@ -74,7 +84,22 @@ async function startFakeHost( const closeClients = (code: number, reason: string): void => { for (const client of server.clients) client.close(code, reason); }; - return { port: (http.address() as AddressInfo).port, stop, closeClients, subs, ops, attaches: () => attaches }; + const muteClients = (): void => { + for (const client of server.clients) muted.add(client); + }; + const setGeneration = (next: string): void => { + generation = next; + }; + return { + port: (http.address() as AddressInfo).port, + stop, + closeClients, + muteClients, + setGeneration, + subs, + ops, + attaches: () => attaches, + }; } const cleanups: Array<() => unknown> = []; @@ -233,6 +258,84 @@ describe('remoteSandbox after its host restarts on the same url', () => { }); }); +/** A heartbeat short enough for a test: ping every 50 ms, 300 ms of silence is a drop. */ +const fastHeartbeat = { heartbeatIntervalMs: 50, hostSilenceTimeoutMs: 300 }; + +describe('remoteSandbox when its host stops answering without closing the socket (#973)', () => { + it('stays attached past the silence timeout while the host answers its pings', async () => { + const host = await startFakeHost(0, 'first'); + cleanups.push(host.stop); + const warnings: string[] = []; + const lazy = remoteSandbox({ url: `http://127.0.0.1:${host.port}`, warn: message => warnings.push(message), ...fastHeartbeat }); + cleanups.push(() => lazy.close()); + const values: unknown[] = []; + lazy.rtdb.onValue('ticks', snapshot => values.push(snapshot.value)); + await waitFor(() => values.length === 1); + + await Bun.sleep(3 * fastHeartbeat.hostSilenceTimeoutMs); + expect(warnings).toEqual([]); + expect(host.attaches()).toBe(1); + }); + + it('reports one loss, reconnects, and resubscribes a live listener', async () => { + const host = await startFakeHost(0, 'first'); + cleanups.push(host.stop); + const warnings: string[] = []; + const lazy = remoteSandbox({ url: `http://127.0.0.1:${host.port}`, warn: message => warnings.push(message), ...fastHeartbeat }); + cleanups.push(() => lazy.close()); + const values: unknown[] = []; + const errors: unknown[] = []; + lazy.rtdb.onValue('ticks', snapshot => values.push(snapshot.value), error => errors.push(error)); + await waitFor(() => values.length === 1); + + host.setGeneration('second'); + host.muteClients(); + await waitFor(() => values.length === 2); + expect(values).toEqual(['first', 'second']); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain('the remote sandbox sent nothing for 0.3s'); + expect(host.attaches()).toBe(2); + expect(host.subs).toHaveLength(2); + expect(errors).toEqual([]); + }); + + it('fails an op sent on the silent socket once and runs an op issued while reconnecting once', async () => { + const host = await startFakeHost(0, 'first'); + cleanups.push(host.stop); + const warnings: string[] = []; + const lazy = remoteSandbox({ url: `http://127.0.0.1:${host.port}`, warn: message => warnings.push(message), ...fastHeartbeat }); + cleanups.push(() => lazy.close()); + expect(await lazy.rtdb.get('a')).toBe('first'); + + host.muteClients(); + const unanswered = await lazy.rtdb.set('a', 1).catch((error: Error & { code?: string }) => error); + expect((unanswered as Error & { code?: string }).code).toBe('unavailable'); + expect(warnings).toHaveLength(1); + + host.setGeneration('second'); + const opsBefore = host.ops.length; + expect(await lazy.rtdb.get('a')).toBe('second'); + expect(host.ops.length - opsBefore).toBe(1); + expect(host.attaches()).toBe(2); + }); + + it('ends the eager handle\'s listeners with unavailable', async () => { + const host = await startFakeHost(0, 'first'); + cleanups.push(host.stop); + const remote = await connectRemoteSandbox({ url: `http://127.0.0.1:${host.port}`, ...fastHeartbeat }); + cleanups.push(() => remote.close()); + const values: unknown[] = []; + const errors: Array<{ code?: string }> = []; + remote.rtdb.onValue('ticks', snapshot => values.push(snapshot.value), error => errors.push(error)); + await waitFor(() => values.length === 1); + + host.muteClients(); + await waitFor(() => errors.length === 1); + expect(errors[0]!.code).toBe('unavailable'); + expect(host.attaches()).toBe(1); + }); +}); + describe('createLazyRemoteSandbox when the connection is lost', () => { function fakeConnection(serveUrl = 'http://127.0.0.1:5000'): { handle: RemoteSandbox; subscriptions: () => number } { let subscriptions = 0; From 95aa62d794216e1e6491e19b5732429757b2dd17 Mon Sep 17 00:00:00 2001 From: David East Date: Wed, 14 Oct 2026 19:44:25 -0700 Subject: [PATCH 2/3] refactor(remote): the heartbeat timing is a test seam, not a public option (#973) ADR-0019 fixes the 15 s heartbeat and the 45 s silence window in each client, as it fixes the hold deadline. Drop heartbeatIntervalMs and hostSilenceTimeoutMs from ConnectRemoteSandboxOptions, which @pyric/cli/remote exports, and let tests shorten the timing through setHeartbeatForTesting in remote/host-liveness.ts, which no package entry exports, as the web client's setHoldDeadlineForTesting does. Refs #973 --- packages/cli/src/remote/host-liveness.ts | 28 ++++++++++++++++------ packages/cli/src/remote/index.ts | 13 +++------- packages/cli/test/remote/loop-hold.test.ts | 4 +++- packages/cli/test/remote/reconnect.test.ts | 18 ++++++++------ 4 files changed, 38 insertions(+), 25 deletions(-) diff --git a/packages/cli/src/remote/host-liveness.ts b/packages/cli/src/remote/host-liveness.ts index 571e2ee456..ba0491b1b6 100644 --- a/packages/cli/src/remote/host-liveness.ts +++ b/packages/cli/src/remote/host-liveness.ts @@ -20,13 +20,28 @@ import { HOSTED_HEARTBEAT_INTERVAL_MS, type BridgeMessage } from '../bridge/prot */ export const HOST_SILENCE_TIMEOUT_MS = 45_000; +interface HeartbeatTiming { + intervalMs: number; + timeoutMs: number; +} + +const DEFAULT_TIMING: HeartbeatTiming = { intervalMs: HOSTED_HEARTBEAT_INTERVAL_MS, timeoutMs: HOST_SILENCE_TIMEOUT_MS }; +let timing = DEFAULT_TIMING; + +/** + * Shorten the heartbeat for a test; `undefined` restores it. The 15 and 45 + * seconds are fixed by ADR-0019; this is not a user setting and no public + * entry point exports it. + */ +export function setHeartbeatForTesting(next: HeartbeatTiming | undefined): void { + timing = next ?? DEFAULT_TIMING; +} + export interface HostLivenessOptions { /** Send one frame on the watched socket; a throw counts as a drop. */ send(message: BridgeMessage): void; - /** Called once when the host has gone silent or the ping cannot be sent. */ - onSilent(): void; - intervalMs?: number; - timeoutMs?: number; + /** Called once, with the silence window, when the host has gone silent or the ping cannot be sent. */ + onSilent(timeoutMs: number): void; } export interface HostLiveness { @@ -38,8 +53,7 @@ export interface HostLiveness { /** Ping now and on every interval; call `onSilent` once the host stops answering. */ export function watchHostLiveness(options: HostLivenessOptions): HostLiveness { - const intervalMs = options.intervalMs ?? HOSTED_HEARTBEAT_INTERVAL_MS; - const timeoutMs = options.timeoutMs ?? HOST_SILENCE_TIMEOUT_MS; + const { intervalMs, timeoutMs } = timing; let lastHeardAt = Date.now(); let pings = 0; let timer: ReturnType | undefined; @@ -53,7 +67,7 @@ export function watchHostLiveness(options: HostLivenessOptions): HostLiveness { function drop(): void { stop(); - options.onSilent(); + options.onSilent(timeoutMs); } function ping(): void { diff --git a/packages/cli/src/remote/index.ts b/packages/cli/src/remote/index.ts index 5bc04362c4..f6836fd7c6 100644 --- a/packages/cli/src/remote/index.ts +++ b/packages/cli/src/remote/index.ts @@ -55,7 +55,7 @@ import type { import { isBridgeMessage, MAX_BRIDGE_FRAME_BYTES, NO_SANDBOX_ERROR_MESSAGE, STORAGE_BYTE_ROUTE_CAPABILITY } from '../bridge/protocol.js'; import { encodeBridgeMessage } from '../bridge/frame-output.js'; import { createOperationBudget } from '../bridge/operation-budget.js'; -import { HOST_SILENCE_TIMEOUT_MS, watchHostLiveness, type HostLiveness } from './host-liveness.js'; +import { watchHostLiveness, type HostLiveness } from './host-liveness.js'; import { cliVersion } from '../pkg-version.js'; import { MAX_STORAGE_OP_BYTES, storagePayloadTooLarge } from '../serve/worker/protocol.js'; import { hasValidAttachFields } from '../bridge/attach-validation.js'; @@ -134,10 +134,6 @@ export interface ConnectRemoteSandboxOptions { * them; when absent, the close ends every listener with `unavailable`. */ onConnectionLost?: (reason: string) => void; - /** Heartbeat interval in ms (ADR-0019). Default: 15 s. Tests pass shorter values. */ - heartbeatIntervalMs?: number; - /** Silence from the host, in ms, that counts as a drop (ADR-0019). Default: 45 s. */ - hostSilenceTimeoutMs?: number; } /** @@ -1117,16 +1113,13 @@ export async function connectRemoteSandbox( attached = true; // Pings go straight to the socket: they bypass the operation budget and // never ref it, so an idle script still exits. A silent host is a drop. - const silenceTimeoutMs = options.hostSilenceTimeoutMs ?? HOST_SILENCE_TIMEOUT_MS; const startHeartbeat = (): HostLiveness => watchHostLiveness({ send: (message) => ws.send(JSON.stringify(message)), - onSilent: () => { - silenceReason = `the remote sandbox sent nothing for ${silenceTimeoutMs / 1000}s`; + onSilent: (timeoutMs) => { + silenceReason = `the remote sandbox sent nothing for ${timeoutMs / 1000}s`; ws.terminate(); }, - intervalMs: options.heartbeatIntervalMs, - timeoutMs: silenceTimeoutMs, }); const isOpen = ws.readyState === WebSocket.OPEN; if (isOpen) liveness = startHeartbeat(); diff --git a/packages/cli/test/remote/loop-hold.test.ts b/packages/cli/test/remote/loop-hold.test.ts index 62a7bd88b5..6771d003b8 100644 --- a/packages/cli/test/remote/loop-hold.test.ts +++ b/packages/cli/test/remote/loop-hold.test.ts @@ -387,8 +387,10 @@ async function startPingCountingHost(): Promise<{ url: string; pings: () => numb /** Attach, run one op, stay idle long enough for several heartbeats, and end without closing. */ const IDLE_SCRIPT = ` +const { setHeartbeatForTesting } = await import(new URL('host-liveness.js', process.argv[1]).href); +setHeartbeatForTesting({ intervalMs: 50, timeoutMs: 45_000 }); const { connectRemoteSandbox } = await import(process.argv[1]); -const remote = await connectRemoteSandbox({ url: process.argv[2], heartbeatIntervalMs: 50 }); +const remote = await connectRemoteSandbox({ url: process.argv[2] }); await remote.rtdb.get('a'); await new Promise((resolve) => setTimeout(resolve, 400)); process.stdout.write('idle'); diff --git a/packages/cli/test/remote/reconnect.test.ts b/packages/cli/test/remote/reconnect.test.ts index d18fb5b8a7..8f38aaa737 100644 --- a/packages/cli/test/remote/reconnect.test.ts +++ b/packages/cli/test/remote/reconnect.test.ts @@ -4,7 +4,7 @@ * stopped sandbox: later ops reconnect, and live listeners are resubscribed * once the host answers again (#949). */ -import { afterEach, describe, expect, it } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; import { once } from 'node:events'; import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; @@ -19,6 +19,7 @@ import { type RemoteSandbox, type RemoteSandboxChannel, } from '../../src/remote/index.js'; +import { setHeartbeatForTesting } from '../../src/remote/host-liveness.js'; /** * A bridge host that acknowledges attach, answers every op with `generation` @@ -259,20 +260,23 @@ describe('remoteSandbox after its host restarts on the same url', () => { }); /** A heartbeat short enough for a test: ping every 50 ms, 300 ms of silence is a drop. */ -const fastHeartbeat = { heartbeatIntervalMs: 50, hostSilenceTimeoutMs: 300 }; +const fastHeartbeat = { intervalMs: 50, timeoutMs: 300 }; describe('remoteSandbox when its host stops answering without closing the socket (#973)', () => { + beforeEach(() => setHeartbeatForTesting(fastHeartbeat)); + afterEach(() => setHeartbeatForTesting(undefined)); + it('stays attached past the silence timeout while the host answers its pings', async () => { const host = await startFakeHost(0, 'first'); cleanups.push(host.stop); const warnings: string[] = []; - const lazy = remoteSandbox({ url: `http://127.0.0.1:${host.port}`, warn: message => warnings.push(message), ...fastHeartbeat }); + const lazy = remoteSandbox({ url: `http://127.0.0.1:${host.port}`, warn: message => warnings.push(message) }); cleanups.push(() => lazy.close()); const values: unknown[] = []; lazy.rtdb.onValue('ticks', snapshot => values.push(snapshot.value)); await waitFor(() => values.length === 1); - await Bun.sleep(3 * fastHeartbeat.hostSilenceTimeoutMs); + await Bun.sleep(3 * fastHeartbeat.timeoutMs); expect(warnings).toEqual([]); expect(host.attaches()).toBe(1); }); @@ -281,7 +285,7 @@ describe('remoteSandbox when its host stops answering without closing the socket const host = await startFakeHost(0, 'first'); cleanups.push(host.stop); const warnings: string[] = []; - const lazy = remoteSandbox({ url: `http://127.0.0.1:${host.port}`, warn: message => warnings.push(message), ...fastHeartbeat }); + const lazy = remoteSandbox({ url: `http://127.0.0.1:${host.port}`, warn: message => warnings.push(message) }); cleanups.push(() => lazy.close()); const values: unknown[] = []; const errors: unknown[] = []; @@ -303,7 +307,7 @@ describe('remoteSandbox when its host stops answering without closing the socket const host = await startFakeHost(0, 'first'); cleanups.push(host.stop); const warnings: string[] = []; - const lazy = remoteSandbox({ url: `http://127.0.0.1:${host.port}`, warn: message => warnings.push(message), ...fastHeartbeat }); + const lazy = remoteSandbox({ url: `http://127.0.0.1:${host.port}`, warn: message => warnings.push(message) }); cleanups.push(() => lazy.close()); expect(await lazy.rtdb.get('a')).toBe('first'); @@ -322,7 +326,7 @@ describe('remoteSandbox when its host stops answering without closing the socket it('ends the eager handle\'s listeners with unavailable', async () => { const host = await startFakeHost(0, 'first'); cleanups.push(host.stop); - const remote = await connectRemoteSandbox({ url: `http://127.0.0.1:${host.port}`, ...fastHeartbeat }); + const remote = await connectRemoteSandbox({ url: `http://127.0.0.1:${host.port}` }); cleanups.push(() => remote.close()); const values: unknown[] = []; const errors: Array<{ code?: string }> = []; From 4c34d05560bd2936de433fe2a48ae6d784118de6 Mon Sep 17 00:00:00 2001 From: David East Date: Wed, 14 Oct 2026 20:03:29 -0700 Subject: [PATCH 3/3] refactor(remote): the heartbeat uses the shared HOSTED_CLIENT_LIVENESS_TIMEOUT_MS (#973) Refs #973 --- packages/cli/src/remote/host-liveness.ts | 13 +++--------- .../cli/test/remote/host-liveness.test.ts | 20 +++++++++---------- 2 files changed, 13 insertions(+), 20 deletions(-) diff --git a/packages/cli/src/remote/host-liveness.ts b/packages/cli/src/remote/host-liveness.ts index ba0491b1b6..4010ebe4f0 100644 --- a/packages/cli/src/remote/host-liveness.ts +++ b/packages/cli/src/remote/host-liveness.ts @@ -4,28 +4,21 @@ * The client pings once at attach, which starts the host's own watch, then * every {@link HOSTED_HEARTBEAT_INTERVAL_MS} while attached. Before each ping * it checks how long the host has been silent: once no frame of any kind has - * arrived for {@link HOST_SILENCE_TIMEOUT_MS}, the socket is treated as + * arrived for {@link HOSTED_CLIENT_LIVENESS_TIMEOUT_MS}, the socket is treated as * dropped and `onSilent` runs once instead of pinging a socket the host has * already closed. The watch belongs to one socket and never outlives it. * * Every timer is unref'd, so an idle attached client never keeps a finished * script alive. */ -import { HOSTED_HEARTBEAT_INTERVAL_MS, type BridgeMessage } from '../bridge/protocol.js'; - -/** - * Silence that counts as a drop: three heartbeats, as the web client uses. - * ADR-0019's heartbeat amendment names this value; the shared constant in - * `bridge/protocol.ts` replaces this one once both land. - */ -export const HOST_SILENCE_TIMEOUT_MS = 45_000; +import { HOSTED_CLIENT_LIVENESS_TIMEOUT_MS, HOSTED_HEARTBEAT_INTERVAL_MS, type BridgeMessage } from '../bridge/protocol.js'; interface HeartbeatTiming { intervalMs: number; timeoutMs: number; } -const DEFAULT_TIMING: HeartbeatTiming = { intervalMs: HOSTED_HEARTBEAT_INTERVAL_MS, timeoutMs: HOST_SILENCE_TIMEOUT_MS }; +const DEFAULT_TIMING: HeartbeatTiming = { intervalMs: HOSTED_HEARTBEAT_INTERVAL_MS, timeoutMs: HOSTED_CLIENT_LIVENESS_TIMEOUT_MS }; let timing = DEFAULT_TIMING; /** diff --git a/packages/cli/test/remote/host-liveness.test.ts b/packages/cli/test/remote/host-liveness.test.ts index a389fa6bca..7a628a8af8 100644 --- a/packages/cli/test/remote/host-liveness.test.ts +++ b/packages/cli/test/remote/host-liveness.test.ts @@ -4,8 +4,8 @@ * server that stops answering without closing. */ import { afterEach, beforeEach, describe, expect, it, jest } from 'bun:test'; -import { HOSTED_HEARTBEAT_INTERVAL_MS, type BridgeMessage } from '../../src/bridge/protocol.js'; -import { HOST_SILENCE_TIMEOUT_MS, watchHostLiveness } from '../../src/remote/host-liveness.js'; +import { HOSTED_CLIENT_LIVENESS_TIMEOUT_MS, HOSTED_HEARTBEAT_INTERVAL_MS, type BridgeMessage } from '../../src/bridge/protocol.js'; +import { watchHostLiveness } from '../../src/remote/host-liveness.js'; function startWatch(send: (message: BridgeMessage) => void = () => {}) { const sent: BridgeMessage[] = []; @@ -47,21 +47,21 @@ describe('watchHostLiveness', () => { it('reports silence once, at the first check after the timeout, instead of pinging', () => { const { sent, silences } = startWatch(); - jest.advanceTimersByTime(HOST_SILENCE_TIMEOUT_MS - 1); + jest.advanceTimersByTime(HOSTED_CLIENT_LIVENESS_TIMEOUT_MS - 1); expect(silences()).toBe(0); const pingsBeforeTimeout = sent.length; jest.advanceTimersByTime(1); expect(silences()).toBe(1); expect(sent).toHaveLength(pingsBeforeTimeout); - jest.advanceTimersByTime(10 * HOST_SILENCE_TIMEOUT_MS); + jest.advanceTimersByTime(10 * HOSTED_CLIENT_LIVENESS_TIMEOUT_MS); expect(silences()).toBe(1); expect(sent).toHaveLength(pingsBeforeTimeout); }); it('counts any frame from the host, so a host that keeps sending is never silent', () => { const { liveness, silences } = startWatch(); - for (let elapsed = 0; elapsed < 4 * HOST_SILENCE_TIMEOUT_MS; elapsed += HOST_SILENCE_TIMEOUT_MS / 3) { - jest.advanceTimersByTime(HOST_SILENCE_TIMEOUT_MS / 3); + for (let elapsed = 0; elapsed < 4 * HOSTED_CLIENT_LIVENESS_TIMEOUT_MS; elapsed += HOSTED_CLIENT_LIVENESS_TIMEOUT_MS / 3) { + jest.advanceTimersByTime(HOSTED_CLIENT_LIVENESS_TIMEOUT_MS / 3); liveness.heard(); } expect(silences()).toBe(0); @@ -70,9 +70,9 @@ describe('watchHostLiveness', () => { it('measures silence from the last frame, not from the last ping', () => { const { liveness, silences } = startWatch(); - jest.advanceTimersByTime(HOST_SILENCE_TIMEOUT_MS - 5_000); + jest.advanceTimersByTime(HOSTED_CLIENT_LIVENESS_TIMEOUT_MS - 5_000); liveness.heard(); - jest.advanceTimersByTime(HOST_SILENCE_TIMEOUT_MS - 1); + jest.advanceTimersByTime(HOSTED_CLIENT_LIVENESS_TIMEOUT_MS - 1); expect(silences()).toBe(0); jest.advanceTimersByTime(1); expect(silences()).toBe(1); @@ -81,7 +81,7 @@ describe('watchHostLiveness', () => { it('sends nothing and reports nothing once stopped', () => { const { liveness, sent, silences } = startWatch(); liveness.stop(); - jest.advanceTimersByTime(10 * HOST_SILENCE_TIMEOUT_MS); + jest.advanceTimersByTime(10 * HOSTED_CLIENT_LIVENESS_TIMEOUT_MS); expect(sent).toHaveLength(1); expect(silences()).toBe(0); }); @@ -94,7 +94,7 @@ describe('watchHostLiveness', () => { refuses = true; jest.advanceTimersByTime(HOSTED_HEARTBEAT_INTERVAL_MS); expect(silences()).toBe(1); - jest.advanceTimersByTime(10 * HOST_SILENCE_TIMEOUT_MS); + jest.advanceTimersByTime(10 * HOSTED_CLIENT_LIVENESS_TIMEOUT_MS); expect(sent).toHaveLength(2); expect(silences()).toBe(1); });