Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions packages/cli/src/remote/host-liveness.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/**
* 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 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_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: HOSTED_CLIENT_LIVENESS_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, with the silence window, when the host has gone silent or the ping cannot be sent. */
onSilent(timeoutMs: number): void;
}

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, timeoutMs } = timing;
let lastHeardAt = Date.now();
let pings = 0;
let timer: ReturnType<typeof setTimeout> | undefined;
let stopped = false;

function stop(): void {
stopped = true;
clearTimeout(timer);
timer = undefined;
}

function drop(): void {
stop();
options.onSilent(timeoutMs);
}

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,
};
}
20 changes: 19 additions & 1 deletion packages/cli/src/remote/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 { 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';
Expand Down Expand Up @@ -1007,7 +1008,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());
Expand Down Expand Up @@ -1065,6 +1069,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.
Expand All @@ -1073,7 +1078,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}`));

Expand Down Expand Up @@ -1106,6 +1111,18 @@ 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 startHeartbeat = (): HostLiveness =>
watchHostLiveness({
send: (message) => ws.send(JSON.stringify(message)),
onSilent: (timeoutMs) => {
silenceReason = `the remote sandbox sent nothing for ${timeoutMs / 1000}s`;
ws.terminate();
},
});
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.
Expand All @@ -1118,6 +1135,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();
Expand Down
101 changes: 101 additions & 0 deletions packages/cli/test/remote/host-liveness.test.ts
Original file line number Diff line number Diff line change
@@ -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_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[] = [];
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(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 * 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 * 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);
liveness.stop();
});

it('measures silence from the last frame, not from the last ping', () => {
const { liveness, silences } = startWatch();
jest.advanceTimersByTime(HOSTED_CLIENT_LIVENESS_TIMEOUT_MS - 5_000);
liveness.heard();
jest.advanceTimersByTime(HOSTED_CLIENT_LIVENESS_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 * HOSTED_CLIENT_LIVENESS_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 * HOSTED_CLIENT_LIVENESS_TIMEOUT_MS);
expect(sent).toHaveLength(2);
expect(silences()).toBe(1);
});
});
79 changes: 79 additions & 0 deletions packages/cli/test/remote/loop-hold.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -343,3 +352,73 @@ 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<void> }> {
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<void> => {
for (const client of server.clients) client.terminate();
server.close();
http.closeAllConnections();
await new Promise<void>((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 { 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] });
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);
});
Loading
Loading