Skip to content
Closed
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
30 changes: 27 additions & 3 deletions docs/adr/0006-daemon-rpc-protocol-version.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,16 @@ Accepted
- Before remote JSON-RPC requests, compare the daemon's `rpcProtocolVersion` from `/health`.
- Package `version` is diagnostic only and must not be used as a compatibility gate.
- Allow a missing `rpcProtocolVersion` unless a later security or protocol decision explicitly retires legacy compatibility.
- A persistent client may cache a successful probe if `/health` advertises an instance ID for the daemon endpoint and, for a proxy, for its upstream daemon.
- A client may cache a successful probe if `/health` advertises an instance ID for the daemon endpoint and, for a proxy, for its upstream daemon.
- The cache may outlive the client process in the state directory. Name the entry by a digest of the client version, RPC protocol version, base URL, and token. Do not write the token or the URL.
- Read a persisted entry only from a bounded regular file that the current user owns and that nobody else can write. Otherwise, probe `/health`.
- Persist only the instance IDs and capabilities. Cache an instance ID only when it is a valid HTTP header value that does not contain the token or the URL. Cache a proxy answer only with its upstream instance ID.
- If a cached RPC fails or times out before its connection opens, clear the cache. After a failure, probe `/health` live as on first contact, within the remaining budget, then send the RPC once more. Do this for every send that carries the cached instance IDs, lease heartbeats included. Take this evidence only from the client's own transport, never from a reply.
- A forced refresh always probes `/health` live, even when the cache cannot be cleared.
- Clear the cache on a remote HTTP 5xx. Do not resend the RPC.
- Before you refuse a command for a capability that only the cache lacks, probe `/health` again.
- Send those instance IDs as conditional headers on every cached RPC. Peers without complete instance IDs retain per-command probes.
- After a stale-instance refusal, clear the cache and probe `/health` again. Retry the refused RPC once, and only if the new peer's protocol is compatible.
- After a stale-instance refusal, clear the cache and probe `/health` again. Retry the refused RPC once, and only if the new peer's protocol is compatible. Act only on a 409 with the mismatch header that the client's transport read. Clear the cache again if the retry is refused too.
- A peer that advertises an instance ID must continue to honor the conditional RPC headers in future versions.
- Change `rpcProtocolVersion` only when older and newer peers cannot safely communicate over the HTTP RPC boundary for existing commands.
- Do not change `rpcProtocolVersion` for additive changes.
Expand Down Expand Up @@ -39,14 +46,29 @@ Package `version` is diagnostic only and must not be used as a compatibility gat
A missing `rpcProtocolVersion` is treated as a legacy remote daemon.
A legacy remote daemon is allowed unless a later security or protocol decision explicitly retires legacy compatibility.

A persistent client may cache a successful probe if `/health` advertises an instance ID for both the daemon endpoint and, if proxied, its upstream daemon.
A client may cache a successful probe if `/health` advertises an instance ID for both the daemon endpoint and, if proxied, its upstream daemon.
The CLI starts a new process for each command, so the cache also persists in the state directory.
Without it, each remote command pays one extra network round trip for `/health`.
The persisted entry is named by a digest of the client version, RPC protocol version, base URL, and token, and holds neither the token nor the URL.
A different token, URL, client version, or RPC protocol version reads as a miss, so a client upgrade always probes again.
The client sends those IDs as conditional headers on every cached RPC.
Before dispatch, a daemon refuses a stale instance with a typed HTTP 409 response.
Before it forwards a request, a proxy refuses its own stale instance.
The proxy passes the expected upstream instance to the daemon, which makes the same pre-dispatch check.
On a mismatch, the client clears the cache and probes `/health` again.
The client then retries the refused RPC once, and only if the new peer's protocol is compatible.
Peers without complete instance IDs retain per-command probes.
The state directory can be shared, so a persisted entry counts only when it is a bounded regular file that the current user owns and that nobody else can write.
A cached RPC whose connection never opened proves that nothing was dispatched.
Only the client's own transport supplies that evidence; a reply can carry the same error details after the command ran.
The client then clears the cache and probes `/health` as on first contact, with the recovery and typed refusal of that path, and sends the RPC once more, all within the command's remaining budget.
A cached RPC that fails after its connection opened is not resent.
A timeout before the connection opened also clears the cache; its budget is spent, so nothing is resent.
Only a 409 with the mismatch header that the client's transport read counts as a stale-instance refusal; the same reason in an error body does not.
The persisted record holds only the instance IDs and capabilities, and only header-valid IDs that echo neither the token nor the URL.
A remote HTTP 5xx clears the cache, whatever its framing, because a proxy answers that way while its upstream daemon restarts.
A timeout leaves the decision to the timeout route, which clears the cache only when its `/health` probe finds the daemon gone or replaced.
A capability that only the cached answer lacks is checked against a fresh probe before the client refuses the command, because the daemon may have been upgraded.
A peer that advertises an instance ID must continue to honor the conditional RPC headers in future versions.
The reason is that older clients may hold a cached identity across a restart.
Such clients must receive a pre-dispatch refusal before they retry a mutating command.
Expand Down Expand Up @@ -76,6 +98,8 @@ This preference does not apply if the change also affects the shared transport c
It also makes proxy use brittle across frequent releases.
- **Do not check compatibility.** This maximizes compatibility.
However, it fails later, after the client has sent an RPC payload that a remote daemon may parse incorrectly.
- **Send `/rpc` without a probe on first contact.** This saves the round trip without a cache.
However, the client then cannot refuse an incompatible protocol before it sends the payload.
- **Negotiate full schemas.** This is more precise, but it is too much machinery for the current JSON-RPC boundary.

## Consequences
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -708,6 +708,36 @@ describe('buildUploadLeaseHeartbeat', () => {
assert.equal('ttlMs' in first!.params, false);
});

test('a beat from cached health that never connects re-probes once within its own budget', async () => {
// Nothing listens, so the beat provably never left. A beat relying on a cached `/health`
// answer gets the same single refresh a command gets, under the beat's own budget and signal.
const closed = net.createServer();
const port = await listenOnLoopback(closed);
await closeLoopbackServer(closed);
const gateCalls: { budgetMs: number | undefined; signal: AbortSignal | undefined }[] = [];
const signal = new AbortController().signal;
const beat = buildUploadLeaseHeartbeat(
{ baseUrl: `http://127.0.0.1:${String(port)}`, token: 'remote-token', pid: 0 },
{ ...settings, transportPreference: 'auto' },
installRequest,
async (budgetMs, gateSignal) => {
gateCalls.push({ budgetMs, signal: gateSignal });
throw new AppError('COMMAND_FAILED', 'Remote daemon is unavailable', {
reason: 'remote_daemon_unavailable',
});
},
);
assert.ok(beat);
await assert.rejects(beat!(1_000, signal), (error: unknown) => {
assert.ok(error instanceof AppError);
assert.equal(error.details?.reason, 'remote_daemon_unavailable');
return true;
});
assert.equal(gateCalls.length, 1);
assert.equal(gateCalls[0]!.signal, signal);
assert.ok(gateCalls[0]!.budgetMs! > 0 && gateCalls[0]!.budgetMs! <= 1_000);
});

test('a beat that never answers dies at its budget, not at the heartbeat policy', async () => {
vi.useFakeTimers();
// The daemon accepts the connection and never answers — a half-open pipe. The beat exists to
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,24 @@
// and `details.dispatched` instead of comparing the message.

import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import { test } from 'vitest';
import {
closeLoopbackServer,
listenOnLoopback,
mkdtempForTestSync,
skipWhenLoopbackUnavailable,
} from '@agent-device/test-kit';
import { AppError } from '@agent-device/kernel/errors';
import { PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog';
import { DAEMON_UNAVAILABLE_REASONS } from '../daemon-lifecycle-errors.ts';
import { sendToDaemon } from '../index.ts';
import { cachedRemoteDaemonHealth } from '../daemon-client-transport.ts';
import {
probeRemoteDaemonHealth,
readCachedRemoteDaemonHealth,
refreshRemoteDaemonHealth,
} from '../daemon-client-remote-health-gate.ts';

// A press, so the refusal states the fact a caller needs before resending a mutating command.
function remotePress(baseUrl: string) {
Expand Down Expand Up @@ -152,6 +158,7 @@ test('a remote press whose health probe answers 4xx is sent and is not the unava
async function slowHealthyRemote(delayMs: number): Promise<{
handler: http.Server;
info: { baseUrl: string; token: string; pid: number };
stateDir: string;
probes: () => number;
}> {
let probes = 0;
Expand All @@ -165,7 +172,8 @@ async function slowHealthyRemote(delayMs: number): Promise<{
});
const port = await listenOnLoopback(handler);
const info = { baseUrl: `http://127.0.0.1:${port}`, token: `probe-${port}`, pid: 0 };
return { handler, info, probes: () => probes };
const stateDir = mkdtempForTestSync('agent-device-remote-health-');
return { handler, info, stateDir, probes: () => probes };
}

// Each caller probes under its own bound; only a settled, usable answer is shared through the cache,
Expand All @@ -174,15 +182,18 @@ test('a health caller probes on its own bound, and a settled answer is cached',
if (await skipWhenLoopbackUnavailable(t)) return;
const remote = await slowHealthyRemote(300);
try {
const unbounded = cachedRemoteDaemonHealth(remote.info);
const bounded = await cachedRemoteDaemonHealth(remote.info, 50);
const unbounded = probeRemoteDaemonHealth(remote.info, remote.stateDir);
const bounded = await probeRemoteDaemonHealth(remote.info, remote.stateDir, 50);

assert.equal(bounded.reachable, false);
assert.equal(bounded.timedOut, true);
assert.equal((await unbounded).reachable, true);
assert.equal(remote.probes(), 2, 'each caller sent its own probe');
// The settled answer is cached, so a later bounded caller reads it without probing.
assert.equal((await cachedRemoteDaemonHealth(remote.info, 50)).reachable, true);
// The settled answer is cached, so a later caller reads it without probing.
assert.equal(
(await readCachedRemoteDaemonHealth(remote.info, remote.stateDir))?.reachable,
true,
);
assert.equal(remote.probes(), 2);
} finally {
await closeLoopbackServer(remote.handler);
Expand All @@ -194,13 +205,37 @@ test('an aborted or budgetless health caller sends no probe', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const remote = await slowHealthyRemote(0);
try {
assert.equal((await cachedRemoteDaemonHealth(remote.info, 0)).reachable, false);
assert.equal((await probeRemoteDaemonHealth(remote.info, remote.stateDir, 0)).reachable, false);
assert.equal(
(await cachedRemoteDaemonHealth(remote.info, undefined, AbortSignal.abort())).reachable,
(await probeRemoteDaemonHealth(remote.info, remote.stateDir, undefined, AbortSignal.abort()))
.reachable,
false,
);
assert.equal(remote.probes(), 0);
} finally {
await closeLoopbackServer(remote.handler);
}
});

// A forced refresh asks the daemon even when the saved entry cannot be removed, so it never reuses
// the answer it was asked to verify.
test.skipIf(process.platform === 'win32')(
'a forced refresh probes live whatever is saved',
async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const remote = await slowHealthyRemote(0);
try {
await probeRemoteDaemonHealth(remote.info, remote.stateDir);
assert.equal(remote.probes(), 1);
fs.chmodSync(remote.stateDir, 0o500);
try {
await refreshRemoteDaemonHealth(remote.info, remote.stateDir, undefined);
} finally {
fs.chmodSync(remote.stateDir, 0o700);
}
assert.equal(remote.probes(), 2);
} finally {
await closeLoopbackServer(remote.handler);
}
},
);
Loading
Loading