From 5ff4c5d979effaeb0a294cf4b6c441f7e56c2c8c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 19:36:14 +0000 Subject: [PATCH 1/7] feat(cli,mcp): clients renew their own leases (ADR 0004, PR A) ADR 0004 makes a client-initiated `lease.renew` the only thing that keeps a lease alive, and turns "held" into a client policy rather than a daemon mode. This is the first slice: the client side starts behaving that way while the daemon, the contract, the core, and the HTTP gateway stay exactly as they are. - new `src/lease-policy`: a renew timer that fires at a third of the remaining TTL, recomputed from the deadline the daemon returned with every grant and renewal (never from a config value the client does not have), stops on the first failure, and guarantees nothing runs after `stop()`. - `simlock lease` (held mode) runs that timer through the `Clock` port and releases explicitly on exit, parent death, or SIGINT/SIGTERM, before the connection closes. `--detach` is untouched: print, exit, no timer. - the MCP session does the same for its own lease, and releases it on session end (bounded, best-effort) instead of letting the socket do it. - neither frontend declares the `heartbeat` capability any more, and `simlock/client`'s `heartbeat` connect option defaults to `false`. The client still starts no renew loop of its own: that stays a frontend concern (ADR 0003 section 10). `mode: "held"` still goes over the wire, and the daemon still releases on connection close; PR B removes both. Part of #114 Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- e2e/heartbeat-ttl.test.ts | 9 +- src/cli/index.test.ts | 156 +++++++++++++++++++++++++ src/cli/index.ts | 40 ++++++- src/lease-policy/index.test.ts | 186 ++++++++++++++++++++++++++++++ src/lease-policy/index.ts | 113 ++++++++++++++++++ src/mcp/connect.ts | 4 +- src/mcp/main.ts | 13 ++- src/mcp/server.test.ts | 3 +- src/mcp/session.test.ts | 135 ++++++++++++++++++++-- src/mcp/session.ts | 116 ++++++++++++++++++- src/mcp/test-support.ts | 1 - src/simlock-client/client.test.ts | 32 +++++ src/simlock-client/client.ts | 13 ++- 13 files changed, 788 insertions(+), 33 deletions(-) create mode 100644 src/lease-policy/index.test.ts create mode 100644 src/lease-policy/index.ts diff --git a/e2e/heartbeat-ttl.test.ts b/e2e/heartbeat-ttl.test.ts index c5d0176e9..704bf9948 100644 --- a/e2e/heartbeat-ttl.test.ts +++ b/e2e/heartbeat-ttl.test.ts @@ -44,7 +44,7 @@ describe("sliding TTL and heartbeat", () => { ); }); - it("slides every heartbeat-capable held lease (MCP and CLI) past the backstop while a detached lease expires at it", async () => { + it("slides every held lease (MCP and CLI) past the backstop while a detached lease expires at it", async () => { const env = await withDaemon({ // detachedTtlMs is pinned to the same value as heldTtlBackstopMs purely so the // detached lease's own (unrelated) TTL knob expires it on the timeline this @@ -98,9 +98,10 @@ describe("sliding TTL and heartbeat", () => { ]); const detachedGrant = detachedResult.json as { lease: { id: string } }; - // Both held leases -- MCP and CLI -- declare the heartbeat capability and - // slide their deadline on every ping; the detached lease holds no connection - // at all, never heartbeats, and expires exactly at its grant-time TTL. + // Both held holders -- MCP and CLI -- renew on their own timer at a third of the + // TTL (ADR 0004 §2), sliding their deadline well past the backstop; the detached + // lease has no holder process at all, renews never, and expires exactly at its + // grant-time TTL. await waitFor( async () => { const rows = await leaseRows(env); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index acb63f63a..2b4778595 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1335,6 +1335,160 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( }); }); +/** + * ADR 0004 §2: held mode is a client policy -- this process renews on a timer at a third of the + * remaining TTL and releases explicitly, rather than ponging a daemon push and relying on the + * socket closing. The wire is untouched in this slice (`mode: "held"` still goes out); what is + * asserted here is the CLI's own behaviour while it holds. + */ +describe("CLI: held-mode renew and release (ADR 0004 §2)", () => { + /** Lets `runLease` get past `requestLease` and arm its timer before the clock is advanced. */ + const settle = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)); + + it("renews at a third of the TTL the daemon returned, re-deriving the cadence from each renewal", async () => { + const clock = new FakeClock(0); + const output = outputCapture(); + const signals = new EventEmitter(); + const renewals: Array<{ leaseId: string; at: number }> = []; + let released: string | undefined; + const client = fakeClient({ + renewLease: (input) => { + renewals.push({ at: clock.now(), leaseId: input.leaseId }); + // Half the grant's TTL comes back, so the next renewal must be half as far out too. + return Promise.resolve({ + deviceId: "dev_1", + grantedAt: 0, + id: input.leaseId, + mode: "held", + ownerId: "test-requester", + requesterId: "test-requester", + ttlDeadline: clock.now() + 30_000, + }); + }, + releaseLease: (input) => { + released = input.leaseId; + return Promise.resolve({ leaseId: input.leaseId }); + }, + }); + const runPromise = runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro"], + output.environmentWith({ + clock, + connectAdmin: async () => client, + signals: signals as unknown as CliEnvironment["signals"], + }), + ); + await settle(); + + // The grant's deadline is 60_000, so the first renewal is due at 20_000 -- and not before. + clock.advance(19_999); + await settle(); + expect(renewals).toEqual([]); + clock.advance(1); + await settle(); + expect(renewals).toEqual([{ at: 20_000, leaseId: "lse_1" }]); + + // 30_000ms of TTL came back at 20_000, so the next renewal is at 30_000, not at 40_000. + clock.advance(10_000); + await settle(); + expect(renewals).toEqual([ + { at: 20_000, leaseId: "lse_1" }, + { at: 30_000, leaseId: "lse_1" }, + ]); + + signals.emit("SIGINT"); + expect(await runPromise).toBe(0); + // The release is the CLI's own call, not a side effect of the socket closing. + expect(released).toBe("lse_1"); + // And the timer is gone with it: no renewal can race the release, and nothing keeps the + // process alive after the command returns. + expect(clock.pendingTimerCount).toBe(0); + clock.advance(600_000); + expect(renewals).toHaveLength(2); + }); + + it("declares no heartbeat capability at hello, in either mode (ADR 0004 §4)", async () => { + const output = outputCapture(); + const declared: Array = []; + const environment = output.environmentWith({ + connectAdmin: async (_resolveCredential, options) => { + declared.push(options?.heartbeat); + return fakeClient(); + }, + }); + await runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--detach"], + environment, + ); + expect(declared).toEqual([false]); + }); + + it("arms no renew timer for --detach: it prints and exits, exactly as before", async () => { + const clock = new FakeClock(0); + const output = outputCapture(); + let renewed = 0; + const client = fakeClient({ + renewLease: () => { + renewed += 1; + return Promise.reject(new Error("--detach must not renew")); + }, + }); + const exitCode = await runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--detach"], + output.environmentWith({ clock, connectAdmin: async () => client }), + ); + + expect(exitCode).toBe(0); + expect(clock.pendingTimerCount).toBe(0); + clock.advance(600_000); + expect(renewed).toBe(0); + }); + + it("stops renewing when the lease is lost, and still does not re-release it", async () => { + const clock = new FakeClock(0); + const output = outputCapture(); + let leaseLostListener: + | ((push: { leaseId: string; deviceId: string; reason: string }) => void) + | undefined; + let renewed = 0; + let released = false; + const client = fakeClient({ + onLeaseLost: (listener) => { + leaseLostListener = listener; + return () => {}; + }, + renewLease: (input) => { + renewed += 1; + return Promise.resolve({ + deviceId: "dev_1", + grantedAt: 0, + id: input.leaseId, + mode: "held", + ownerId: "test-requester", + requesterId: "test-requester", + ttlDeadline: clock.now() + 60_000, + }); + }, + releaseLease: () => { + released = true; + return Promise.resolve({ leaseId: "lse_1" }); + }, + }); + const runPromise = runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro"], + output.environmentWith({ clock, connectAdmin: async () => client }), + ); + await settle(); + leaseLostListener?.({ deviceId: "dev_1", leaseId: "lse_1", reason: "ttl-backstop" }); + + expect(await runPromise).toBe(14); + expect(released).toBe(false); + expect(clock.pendingTimerCount).toBe(0); + clock.advance(600_000); + expect(renewed).toBe(0); + }); +}); + describe("CLI: mcp command (ADR 0003 §11 -- lazy module load)", () => { it("does not load the MCP stdio module unless the mcp command runs", async () => { const output = outputCapture(); @@ -1684,6 +1838,8 @@ function outputCapture(ports?: CliEnvironmentPorts): OutputCapture { const stdoutOut = { write: (value: string) => (capture.stdout += value) }; if (ports === undefined) { return { + // Overridable through `environmentWith({ clock })` -- see the renew-cadence suite. + clock: new FakeClock(0), configPath: "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/simlock/config.json", requesterId: "test-requester", now: () => 0, diff --git a/src/cli/index.ts b/src/cli/index.ts index 71da3c480..eb4919b98 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -35,6 +35,7 @@ import { } from "../admin/index.js"; import type { Role } from "../contract/index.js"; import type { PassthroughCommand } from "../client/index.js"; +import { startLeaseRenewal } from "../lease-policy/index.js"; import { spawnPassthrough } from "./passthrough.js"; import { ERROR_TABLE } from "../contract/index.js"; @@ -108,6 +109,11 @@ type McpStdioRunner = () => Promise; * one connection helper instead of two. */ export interface CliEnvironment { + /** + * The `Clock` port (architecture rule 9). Held mode's renew timer runs on it, so a test can + * drive the cadence by hand instead of waiting out a real TTL. + */ + readonly clock: Clock; readonly configPath: string; /** ADR §4's requester default and this connection's fixed principal -- see §9's * "SIMLOCK_AGENT_ID and --agent-id still set the requester id ... they are not the @@ -387,6 +393,7 @@ export function buildCliEnvironment( }; return { + clock, configPath, requesterId, now: () => clock.now(), @@ -706,7 +713,11 @@ async function runLease( ? undefined : waitForTermination(environment.signals, environment.parentWatch, watchedPid); - const client = await connectDaemonClient(environment, token, { heartbeat: !detached }); + // ADR 0004 §2/§4: held mode is a client policy now -- this process renews on its own timer + // (below) instead of ponging the daemon's push, so neither mode declares the heartbeat + // capability any more. The daemon still has the push, and still slides a lease for any + // connection that asks for it; this one no longer asks. + const client = await connectDaemonClient(environment, token, { heartbeat: false }); // Set once the daemon says this connection's lease ended without us asking. ADR 0003 §8: // lease-scoped pushes go to every live connection sharing the lease's owner, in either mode // -- filtered below against this connection's own granted lease id, the same way the @@ -759,12 +770,37 @@ async function runLease( if (values["export-env"] === true) writeExportEnv(environment, result); else writeResult(environment, result); if (detached || termination === undefined) return 0; - await Promise.race([termination.settled, leaseLostSignal]); + // ADR 0004 §2: what a held holder does while alive is renew on a timer at a third of the + // TTL -- computed from the deadline the daemon just returned, not from a config value this + // process does not have. `--detach` returned above: it stays exactly as it was, printing + // and exiting with no timer at all. + const renewal = startLeaseRenewal({ + clock: environment.clock, + leaseId: grant.lease.id, + ttlDeadline: grant.lease.ttlDeadline, + renew: (leaseId) => client.renewLease({ leaseId }), + // A renewal that fails has ended this holder's claim (see `startLeaseRenewal`); it is + // diagnostic output, on the same structured stderr channel as a failed release, and it + // does not by itself end the process -- the lease-lost push or the daemon's own expiry + // is what decides that. + onError: (error) => writeError(environment, error), + }); + try { + await Promise.race([termination.settled, leaseLostSignal]); + } finally { + // Before the release below, and before any early return: a renew must never race the + // release of the lease it is renewing. + renewal.stop(); + } if (leaseLost) { // The daemon already released it; asking again would only raise UNKNOWN_LEASE. return LEASE_LOST_EXIT_CODE; } try { + // ADR 0004 §2/§3: the release a held holder owes on exit, parent death, or a catchable + // signal is this call -- not the socket closing in the `finally` below. The daemon still + // releases on close today (PR B removes that), so this is the path that will still be + // here when nothing else is. await client.releaseLease({ leaseId: grant.lease.id }); } catch (error: unknown) { // Non-fatal: the process still exits 0 after a signal, but the release diff --git a/src/lease-policy/index.test.ts b/src/lease-policy/index.test.ts new file mode 100644 index 000000000..86d378102 --- /dev/null +++ b/src/lease-policy/index.test.ts @@ -0,0 +1,186 @@ +/** + * The renew cadence ADR 0004 §2 specifies, exercised on a hand-advanced `FakeClock`: a third of + * the *remaining* TTL, recomputed from the deadline the daemon returned every time, and nothing + * at all after `stop()`. + */ +import { describe, expect, it } from "vitest"; + +import { FakeClock } from "../ports/index.js"; +import { startLeaseRenewal } from "./index.js"; + +/** Lets the awaited `renew` call settle; the fake clock never moves on its own. */ +async function flushMicrotasks(times = 10): Promise { + for (let index = 0; index < times; index += 1) await Promise.resolve(); +} + +describe("startLeaseRenewal", () => { + it("renews at a third of the remaining TTL and reschedules off each renewal's own deadline", async () => { + const clock = new FakeClock(1_000); + const renewedAt: number[] = []; + const seenLeaseIds: string[] = []; + const renewal = startLeaseRenewal({ + clock, + leaseId: "lse_1", + renew: (leaseId) => { + renewedAt.push(clock.now()); + seenLeaseIds.push(leaseId); + // The daemon's answer -- deliberately a *different* TTL than the grant's, so a + // cadence computed from anything but this deadline shows up as a wrong timestamp. + return Promise.resolve({ ttlDeadline: clock.now() + 6_000 }); + }, + ttlDeadline: 1_000 + 9_000, + }); + + clock.advance(2_999); + await flushMicrotasks(); + expect(renewedAt, "must not renew before a third of the TTL has passed").toEqual([]); + + clock.advance(1); + await flushMicrotasks(); + expect(renewedAt).toEqual([4_000]); + expect(seenLeaseIds).toEqual(["lse_1"]); + + // 6_000ms of TTL came back, so the next renewal is 2_000ms out -- not the 3_000ms the + // grant's own TTL would imply, and not 3_000ms after the previous *scheduled* time either. + clock.advance(1_999); + await flushMicrotasks(); + expect(renewedAt).toEqual([4_000]); + clock.advance(1); + await flushMicrotasks(); + expect(renewedAt).toEqual([4_000, 6_000]); + + renewal.stop(); + }); + + it("stops cleanly: the pending timer is cancelled and no renewal follows", async () => { + const clock = new FakeClock(0); + let calls = 0; + const renewal = startLeaseRenewal({ + clock, + leaseId: "lse_1", + renew: () => { + calls += 1; + return Promise.resolve({ ttlDeadline: clock.now() + 3_000 }); + }, + ttlDeadline: 3_000, + }); + expect(clock.pendingTimerCount).toBe(1); + + renewal.stop(); + + expect(clock.pendingTimerCount, "a stopped renewal leaves no timer behind").toBe(0); + clock.advance(60_000); + await flushMicrotasks(); + expect(calls).toBe(0); + }); + + it("does not reschedule when a renewal that was already in flight comes back after stop()", async () => { + const clock = new FakeClock(0); + let resolveRenew!: (renewed: { ttlDeadline: number }) => void; + let calls = 0; + const renewal = startLeaseRenewal({ + clock, + leaseId: "lse_1", + renew: () => { + calls += 1; + return new Promise<{ ttlDeadline: number }>((resolve) => { + resolveRenew = resolve; + }); + }, + ttlDeadline: 3_000, + }); + + clock.advance(1_000); + await flushMicrotasks(); + expect(calls).toBe(1); + + renewal.stop(); + resolveRenew({ ttlDeadline: 60_000 }); + await flushMicrotasks(); + + expect(clock.pendingTimerCount, "a late renewal must not re-arm a stopped timer").toBe(0); + clock.advance(60_000); + await flushMicrotasks(); + expect(calls).toBe(1); + }); + + it("ends renewal on the first failure, reporting it exactly once", async () => { + const clock = new FakeClock(0); + const failure = new Error("UNKNOWN_LEASE"); + const errors: unknown[] = []; + let calls = 0; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + onError: (error) => errors.push(error), + renew: () => { + calls += 1; + return Promise.reject(failure); + }, + ttlDeadline: 3_000, + }); + + clock.advance(1_000); + await flushMicrotasks(); + expect(errors).toEqual([failure]); + expect(clock.pendingTimerCount).toBe(0); + + clock.advance(60_000); + await flushMicrotasks(); + expect(calls, "a failed renewal is not retried on a timer").toBe(1); + expect(errors).toHaveLength(1); + }); + + it("never reports a failure that arrives after stop()", async () => { + const clock = new FakeClock(0); + let rejectRenew!: (error: Error) => void; + const errors: unknown[] = []; + const renewal = startLeaseRenewal({ + clock, + leaseId: "lse_1", + onError: (error) => errors.push(error), + renew: () => + new Promise<{ ttlDeadline: number }>((_resolve, reject) => { + rejectRenew = reject; + }), + ttlDeadline: 3_000, + }); + + clock.advance(1_000); + await flushMicrotasks(); + renewal.stop(); + rejectRenew(new Error("connection lost")); + await flushMicrotasks(); + + expect(errors).toEqual([]); + }); + + it("still renews a deadline that is already in the past, without becoming a hot loop", async () => { + const clock = new FakeClock(1_000); + const renewedAt: number[] = []; + const renewal = startLeaseRenewal({ + clock, + leaseId: "lse_1", + renew: () => { + renewedAt.push(clock.now()); + // A daemon that keeps answering with an expired deadline: without the floor this + // would renew once per tick forever. + return Promise.resolve({ ttlDeadline: clock.now() }); + }, + ttlDeadline: 500, + }); + + clock.advance(249); + await flushMicrotasks(); + expect(renewedAt).toEqual([]); + clock.advance(1); + await flushMicrotasks(); + expect(renewedAt).toEqual([1_250]); + + clock.advance(250); + await flushMicrotasks(); + expect(renewedAt).toEqual([1_250, 1_500]); + + renewal.stop(); + }); +}); diff --git a/src/lease-policy/index.ts b/src/lease-policy/index.ts new file mode 100644 index 000000000..432bec678 --- /dev/null +++ b/src/lease-policy/index.ts @@ -0,0 +1,113 @@ +/** + * Client-side lease renewal: the timer half of ADR 0004 §2 ("'Held' is a client policy, not a + * daemon mode ... what it does while alive is renew on a timer (one third of the TTL) and + * release on exit, parent death, or a catchable signal"). + * + * It lives in its own module, outside both frontends and outside `simlock/client`, for two + * reasons: + * + * - the CLI's held mode and the MCP session follow the *same* policy, and a second copy of a + * liveness loop is exactly the duplication ADR 0004 exists to remove; + * - the typed client deliberately owns no renew loop (ADR 0003 §10, `docs/CLIENT.md`): renew + * and reconnect policy is a frontend concern, so this is a helper frontends *choose*, never + * something `connectSimlock` starts on their behalf. Nothing here is exported from + * `simlock/client` or `simlock/admin`. + * + * The cadence is computed only from the deadline the daemon returned with the grant (and with + * every renewal since), never from a TTL config value: a client does not have the daemon's + * config, and the daemon is free to hand back a shorter deadline than the one asked for. + */ +import type { Clock, TimerHandle } from "../ports/index.js"; + +/** ADR 0004 §2's "one third of the TTL". */ +const RENEW_DIVISOR = 3; + +/** + * Floor on the scheduled delay. Only reachable when the daemon returns a deadline that is + * already very close (or in the past) -- a misconfigured `lease.heldTtlBackstopMs`, a clock + * that jumped, or a renewal that raced its own expiry. Without it, a non-positive remaining + * TTL would turn the timer into an unbounded renew-per-tick loop against the daemon. The + * renewal still happens; it is only kept from becoming a hot loop. + */ +const MINIMUM_RENEW_DELAY_MS = 250; + +/** The subset of a `LeaseRecord` renewal needs back: the daemon's new deadline. */ +export interface RenewedLease { + readonly ttlDeadline: number; +} + +export interface LeaseRenewalOptions { + readonly clock: Clock; + readonly leaseId: string; + /** The deadline the grant (or a previous renewal) returned, in `clock.now()`'s epoch. */ + readonly ttlDeadline: number; + /** Calls `lease.renew` for this lease -- `client.renewLease({ leaseId })`, in practice. */ + readonly renew: (leaseId: string) => Promise; + /** + * Reports the failure that stopped renewal (see `LeaseRenewal#stop` for why renewal ends + * there). Never called after `stop()`. + */ + readonly onError?: (error: unknown) => void; +} + +export interface LeaseRenewal { + /** + * Cancels the pending timer and guarantees no further `renew` call, `onError` call, or + * reschedule -- including from a renewal that is already in flight. Idempotent, and the one + * thing a holder must do before releasing, so a renew cannot race its own release. + */ + stop(): void; +} + +/** The delay before the next renewal, given how much of the TTL is left. */ +function renewDelayMs(remainingMs: number): number { + return Math.max(MINIMUM_RENEW_DELAY_MS, Math.floor(remainingMs / RENEW_DIVISOR)); +} + +/** + * Starts renewing `leaseId` at a third of the remaining TTL, rescheduling off each renewal's + * own returned deadline, until `stop()`. + * + * A failed renewal ends renewal rather than retrying: the typed client never reconnects (ADR + * 0003 §10), so a rejection is either a dead connection -- on which no later call would + * succeed either -- or the daemon saying this lease is no longer renewable (it expired, or + * was force-released). Both end this holder's claim; retrying would only turn one honest + * error into a stream of them. The caller learns through `onError` and through the + * `lease-lost` push that accompanies the second case. + */ +export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { + const { clock, leaseId, onError, renew } = options; + let timer: TimerHandle | undefined; + let stopped = false; + + const schedule = (ttlDeadline: number): void => { + if (stopped) return; + timer = clock.setTimer(renewDelayMs(ttlDeadline - clock.now()), () => { + timer = undefined; + void tick(); + }); + }; + + const tick = async (): Promise => { + if (stopped) return; + try { + const renewed = await renew(leaseId); + schedule(renewed.ttlDeadline); + } catch (error: unknown) { + if (stopped) return; + stopped = true; + onError?.(error); + } + }; + + schedule(options.ttlDeadline); + + return { + stop: (): void => { + stopped = true; + if (timer === undefined) return; + clock.cancel(timer); + timer = undefined; + }, + }; +} diff --git a/src/mcp/connect.ts b/src/mcp/connect.ts index 81404d7ad..bc4994008 100644 --- a/src/mcp/connect.ts +++ b/src/mcp/connect.ts @@ -65,7 +65,9 @@ export async function connectWithAutoLaunch( function attempt(options: ConnectWithAutoLaunchOptions): Promise { return connectSimlock({ endpoint: options.socketPath, - heartbeat: options.heartbeat ?? true, + // ADR 0004 §2/§4: the session renews its own lease on a timer, so it declares no heartbeat + // capability unless a caller explicitly asks for one. + heartbeat: options.heartbeat ?? false, ipc: options.ipc, principal: options.principal, }); diff --git a/src/mcp/main.ts b/src/mcp/main.ts index d6de604de..cd6746c0f 100644 --- a/src/mcp/main.ts +++ b/src/mcp/main.ts @@ -10,6 +10,7 @@ import { resolveDaemonSocketPath, resolveSimlockHome, SystemClock, + type Clock, } from "../ports/index.js"; import { connectWithAutoLaunch } from "./connect.js"; import { McpSession } from "./session.js"; @@ -33,6 +34,8 @@ export interface McpTransport { } export interface McpStdioEnvironment { + /** The `Clock` the session's renew timer runs on; a real one unless a test injects otherwise. */ + readonly clock?: Clock; readonly connect?: () => Promise; readonly createServer?: (session: McpSession) => McpServer; readonly createTransport?: () => McpTransport; @@ -67,6 +70,7 @@ export async function startMcpStdio( const requesterId = environment.requesterId ?? env.SIMLOCK_AGENT_ID ?? `mcp:${process.pid}`; const defaults = defaultEnvironment(requesterId); const session = new McpSession({ + clock: environment.clock ?? new SystemClock(), connect: environment.connect ?? defaults.connect, }); const server = (environment.createServer ?? createMcpServer)(session); @@ -149,10 +153,11 @@ function defaultEnvironment( connect: () => connectWithAutoLaunch({ clock, - // MCP's holder process dies with its agent (stdin EOF -> session.close()), so a - // sliding TTL is safe here. CLI held mode declares the same capability now that - // it self-terminates on parent death too — see docs/known-pitfalls.md. - heartbeat: true, + // ADR 0004 §2/§4: the session keeps its lease alive with its own `lease.renew` timer + // and releases explicitly when the agent goes away (stdin EOF -> session.close()), so + // it no longer declares the daemon-initiated heartbeat. CLI held mode dropped the same + // capability in the same change. + heartbeat: false, ipc, launcher: new NodeDaemonLauncher({ args: [join(dirname(fileURLToPath(import.meta.url)), "../daemon/main.js")], diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index 87f9b971d..1c9be32da 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -9,6 +9,7 @@ import { import { describe, expect, it } from "vitest"; import { SimlockError } from "../client/index.js"; +import { FakeClock } from "../ports/index.js"; import { FakeSimlockClient, sampleGrant } from "./test-support.js"; import { McpSession } from "./session.js"; import { createMcpServer } from "./server.js"; @@ -292,7 +293,7 @@ describe("MCP server (smoke)", () => { }); async function connectedServer(client: FakeSimlockClient) { - const session = new McpSession({ connect: async () => client }); + const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); const server = createMcpServer(session); const mcpClient = new Client({ name: "mcp-test-client", version: "1.0.0" }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/src/mcp/session.test.ts b/src/mcp/session.test.ts index 27a14609e..a38465714 100644 --- a/src/mcp/session.test.ts +++ b/src/mcp/session.test.ts @@ -1,9 +1,15 @@ import { describe, expect, it } from "vitest"; import { SimlockError } from "../client/index.js"; +import { FakeClock } from "../ports/index.js"; import { FakeSimlockClient, sampleGrant } from "./test-support.js"; import { McpSession, toMcpErrorResult } from "./session.js"; +/** Lets an awaited renewal settle; the fake clock never moves on its own. */ +async function flushMicrotasks(times = 10): Promise { + for (let index = 0; index < times; index += 1) await Promise.resolve(); +} + describe("McpSession", () => { it("requests a held lease with the tool input as-is, and returns the grant unchanged", async () => { const client = new FakeSimlockClient(); @@ -15,7 +21,7 @@ describe("McpSession", () => { seenOptions = options; return Promise.resolve(grant); }; - const session = new McpSession({ connect: async () => client }); + const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); const signal = new AbortController().signal; const onProgress = () => undefined; @@ -34,7 +40,7 @@ describe("McpSession", () => { const client = new FakeSimlockClient(); client.releaseLeaseImpl = () => Promise.reject(new SimlockError("FORBIDDEN", "protocol", "not your lease", {})); - const session = new McpSession({ connect: async () => client }); + const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); await expect(session.release({ leaseId: "someone-elses-lease" })).rejects.toMatchObject({ code: "FORBIDDEN", @@ -47,7 +53,7 @@ describe("McpSession", () => { it("adds released: true to a successful release without otherwise reshaping the result", async () => { const client = new FakeSimlockClient(); client.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); - const session = new McpSession({ connect: async () => client }); + const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); await expect(session.release({ leaseId: "lease-1" })).resolves.toEqual({ leaseId: "lease-1", @@ -58,7 +64,7 @@ describe("McpSession", () => { it("forwards list_devices straight to getCatalog", async () => { const client = new FakeSimlockClient(); client.getCatalogImpl = () => Promise.resolve({ platforms: [] }); - const session = new McpSession({ connect: async () => client }); + const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); await session.listDevices({ platform: "ios" }); expect(client.calls).toEqual([{ input: { platform: "ios" }, method: "getCatalog" }]); @@ -88,7 +94,7 @@ describe("McpSession", () => { }, ); }; - const session = new McpSession({ connect: async () => client }); + const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); await expect(session.status()).resolves.toEqual({ held: false }); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); @@ -125,7 +131,7 @@ describe("McpSession", () => { }, ], }); - const session = new McpSession({ connect: async () => client }); + const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); await expect(session.status()).resolves.toEqual({ held: false }); }); @@ -147,7 +153,7 @@ describe("McpSession", () => { }, ], }); - const session = new McpSession({ connect: async () => client }); + const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); await expect(session.status()).resolves.toMatchObject({ held: true, id: "lease-1" }); @@ -166,7 +172,7 @@ describe("McpSession", () => { clients.push(client); return client; }; - const session = new McpSession({ connect }); + const session = new McpSession({ clock: new FakeClock(), connect }); await session.listDevices({}); await session.listDevices({}); @@ -193,7 +199,7 @@ describe("McpSession", () => { order.push("release"); return Promise.resolve({ leaseId: input.leaseId }); }; - const session = new McpSession({ connect: async () => client }); + const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); const leaseCall = session.lease({ model: "iPhone 17 Pro", platform: "ios" }); const releaseCall = session.release({ leaseId: "lease-1" }); @@ -210,7 +216,7 @@ describe("McpSession", () => { const pendingClient = new Promise((resolve) => { resolveConnect = resolve; }); - const session = new McpSession({ connect: () => pendingClient }); + const session = new McpSession({ clock: new FakeClock(), connect: () => pendingClient }); const listDevicesCall = session.listDevices({}); await Promise.resolve(); // let the queued mutation reach #clientForUse() and start connecting @@ -229,7 +235,7 @@ describe("McpSession", () => { it("rejects every tool call with SESSION_CLOSED, without contacting the client, once closed", async () => { const client = new FakeSimlockClient(); - const session = new McpSession({ connect: async () => client }); + const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); await session.close(); await expect(session.lease({ model: "x", platform: "ios" })).rejects.toMatchObject({ @@ -243,10 +249,115 @@ describe("McpSession", () => { expect(client.calls).toEqual([]); }); + /** + * ADR 0004 §2: the session's lease lives on its own `lease.renew` timer, at a third of the + * remaining TTL, and is released explicitly when the session ends -- not left to the socket. + */ + it("renews its lease at a third of the TTL, re-deriving the cadence from each renewal", async () => { + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + const renewals: Array<{ leaseId: string; at: number }> = []; + client.renewLeaseImpl = (input) => { + renewals.push({ at: clock.now(), leaseId: input.leaseId }); + return Promise.resolve({ + deviceId: "device-1", + grantedAt: 0, + id: input.leaseId, + mode: "held" as const, + ownerId: "mcp-test", + requesterId: "mcp-test", + ttlDeadline: clock.now() + 3_000, + }); + }; + const session = new McpSession({ clock, connect: async () => client }); + + // `sampleGrant`'s deadline is 12_345, so the first renewal is due at 4_115. + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + clock.advance(4_114); + await flushMicrotasks(); + expect(renewals).toEqual([]); + clock.advance(1); + await flushMicrotasks(); + expect(renewals).toEqual([{ at: 4_115, leaseId: "lease-1" }]); + + // 3_000ms came back, so the next one is 1_000ms later -- off the renewal's own deadline. + clock.advance(1_000); + await flushMicrotasks(); + expect(renewals).toHaveLength(2); + expect(renewals[1]).toEqual({ at: 5_115, leaseId: "lease-1" }); + + await session.close(); + }); + + it("releases the session's lease explicitly on close, before closing the connection", async () => { + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + client.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); + const session = new McpSession({ clock, connect: async () => client }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + await session.close(); + + expect(client.calls.map((call) => call.method)).toEqual(["requestLease", "releaseLease"]); + expect(client.calls.at(-1)?.input).toEqual({ leaseId: "lease-1" }); + expect(client.closeCalls).toBe(1); + expect(clock.pendingTimerCount, "the renew timer must not outlive the session").toBe(0); + }); + + it("closes cleanly even when the farewell release fails", async () => { + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + client.releaseLeaseImpl = () => + Promise.reject(new SimlockError("UNKNOWN_LEASE", "domain", "gone", { leaseId: "lease-1" })); + const session = new McpSession({ clock, connect: async () => client }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + await expect(session.close()).resolves.toBeUndefined(); + expect(client.closeCalls).toBe(1); + }); + + it("does not release on close when the lease was already released by a tool call", async () => { + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + client.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); + const session = new McpSession({ clock, connect: async () => client }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + await session.release({ leaseId: "lease-1" }); + // The timer goes with the lease, so nothing can renew what was just given up. + expect(clock.pendingTimerCount).toBe(0); + + await session.close(); + expect(client.calls.filter((call) => call.method === "releaseLease")).toHaveLength(1); + }); + + it("stops renewing a lease that ended elsewhere", async () => { + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + const session = new McpSession({ clock, connect: async () => client }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + client.emitLeaseLost({ deviceId: "device-1", leaseId: "lease-1", reason: "expired" }); + + expect(clock.pendingTimerCount).toBe(0); + clock.advance(600_000); + await flushMicrotasks(); + expect(client.calls.filter((call) => call.method === "renewLease")).toEqual([]); + + await session.close(); + // Nothing to release either: the daemon already ended it. + expect(client.calls.filter((call) => call.method === "releaseLease")).toEqual([]); + }); + it("relays the client's lease-lost, device-unhealthy, and device-recovered pushes to session listeners", async () => { const client = new FakeSimlockClient(); client.getCatalogImpl = () => Promise.resolve({ platforms: [] }); - const session = new McpSession({ connect: async () => client }); + const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); await session.listDevices({}); // forces the client to connect and wire up push relays const leaseLost: unknown[] = []; diff --git a/src/mcp/session.ts b/src/mcp/session.ts index 3cc956f6a..21ad89b15 100644 --- a/src/mcp/session.ts +++ b/src/mcp/session.ts @@ -5,6 +5,8 @@ import { type LeaseRequestInput, type SimlockClient, } from "../client/index.js"; +import { startLeaseRenewal, type LeaseRenewal } from "../lease-policy/index.js"; +import type { Clock, TimerHandle } from "../ports/index.js"; import type { LeaseSimulatorInput, LeaseSimulatorOutput, @@ -15,7 +17,21 @@ import type { ReleaseSimulatorOutput, } from "./contracts.js"; +/** + * How long `close()` waits for its farewell `lease.release` before closing the connection + * anyway. The daemon is a local process answering a local socket, so this is not a latency + * budget -- it is the bound that keeps an unresponsive daemon from holding an MCP server's + * shutdown open forever. Exceeding it costs nothing but the wait: the lease then ends the way + * every unreleased lease ends, at its deadline. + */ +const RELEASE_ON_CLOSE_TIMEOUT_MS = 5_000; + export interface McpSessionOptions { + /** + * The `Clock` port (architecture rule 9): the session's renew timer and `close()`'s release + * bound both run on it, so tests drive them by hand. + */ + readonly clock: Clock; /** * Opens one connection and completes the `hello` handshake, fixing this session's principal * for the connection's lifetime (ADR §4). Called again -- building a brand new client, never @@ -84,13 +100,16 @@ export function toMcpErrorResult(error: unknown): McpErrorResult { * session does not own surfaces the daemon's own `FORBIDDEN` rather than a client-side guard * pre-empting it (ADR §11). * - * `#heldLeaseId` is the one piece of state this class keeps between calls, and it is not a - * cache of lease *state* (§11's point): it is only the id of the lease this session's own + * `#heldLeaseId` is the one piece of lease *data* this class keeps between calls, and it is not + * a cache of lease *state* (§11's point): it is only the id of the lease this session's own * `lease()` last obtained, kept so `status()` can tell that lease apart from any other lease * `lease.list` happens to return under the same owner principal -- see `status()`'s doc - * comment for why that distinction is load-bearing. + * comment for why that distinction is load-bearing. Alongside it sits `#renewal`, the timer + * that keeps that lease alive (ADR 0004 §2); the two are started, stopped, and cleared + * together. */ export class McpSession { + readonly #clock: Clock; readonly #connect: () => Promise; #client: SimlockClient | undefined; #connecting: Promise | undefined; @@ -107,8 +126,15 @@ export class McpSession { * none is outstanding. See the class doc comment and `status()` for why `lease.list` alone * cannot answer `lease_status` correctly. */ #heldLeaseId: string | undefined; + /** + * ADR 0004 §2: the session's half of "held is a client policy" -- the timer that renews + * `#heldLeaseId` at a third of its remaining TTL. Non-`undefined` exactly while this session + * holds a lease it obtained itself. + */ + #renewal: LeaseRenewal | undefined; constructor(options: McpSessionOptions) { + this.#clock = options.clock; this.#connect = options.connect; } @@ -126,6 +152,7 @@ export class McpSession { ...(signal === undefined ? {} : { signal }), }); this.#heldLeaseId = grant.lease.id; + this.#startRenewal(client, grant.lease.id, grant.lease.ttlDeadline); return grant; }); } @@ -134,6 +161,9 @@ export class McpSession { return this.#mutate(async () => { this.#throwIfClosed(); const client = await this.#clientForUse(); + // Stopped before the call, not after it: a renew that overtook its own release would + // resurrect the lease the caller just gave up. + if (input.leaseId === this.#heldLeaseId) this.#stopRenewal(); const result = await client.releaseLease(input); if (result.leaseId === this.#heldLeaseId) this.#heldLeaseId = undefined; return { ...result, released: true }; @@ -187,19 +217,90 @@ export class McpSession { return () => this.#deviceHealthListeners.delete(listener); } + /** + * Ends the session: stops renewing, releases this session's lease explicitly, then closes the + * connection. ADR 0004 §3 ("connection close means nothing to a lease") is why the release is + * its own call now rather than a side effect of the socket going away -- the daemon still + * releases on close today, and will not once PR B lands. + * + * One race is deliberately left: a `lease()` still in flight here can set `#heldLeaseId` + * after this method read it, and that lease is not released explicitly. It is not reachable + * from the MCP frontend (`close()` runs on shutdown, after the transport is gone) and + * blocking shutdown on an in-flight provisioning request -- minutes, potentially -- would be + * a worse trade than the daemon's own expiry handling it. + */ close(): Promise { if (this.#closePromise !== undefined) return this.#closePromise; this.#closed = true; + this.#stopRenewal(); this.#unwireClient(); const client = this.#client; + const heldLeaseId = this.#heldLeaseId; + this.#heldLeaseId = undefined; this.#client = undefined; if (this.#connecting !== undefined) { void this.#connecting.then((next) => this.#closeClient(next)).catch(noop); } - this.#closePromise = client === undefined ? Promise.resolve() : this.#closeClient(client); + this.#closePromise = + client === undefined ? Promise.resolve() : this.#endSession(client, heldLeaseId); return this.#closePromise; } + /** `close()`'s tail: the farewell release (best-effort, bounded), then the connection. */ + async #endSession(client: SimlockClient, heldLeaseId: string | undefined): Promise { + if (heldLeaseId !== undefined) { + try { + await this.#withReleaseTimeout(client.releaseLease({ leaseId: heldLeaseId })); + } catch { + // Best-effort by design: the lease may already be gone (expired, force-released), the + // connection may be dead, or the daemon may not answer. Shutdown continues either way, + // and an unreleased lease still ends at its deadline. + } + } + await this.#closeClient(client); + } + + /** Rejects once `RELEASE_ON_CLOSE_TIMEOUT_MS` passes, so a dead-but-open socket cannot pin an + * MCP server open. The timer is always cancelled, so it never holds the process open itself. */ + async #withReleaseTimeout(release: Promise): Promise { + let timer: TimerHandle | undefined; + const expiry = new Promise((_resolve, reject) => { + timer = this.#clock.setTimer(RELEASE_ON_CLOSE_TIMEOUT_MS, () => { + timer = undefined; + reject(new McpSessionError("RELEASE_TIMEOUT", "Timed out releasing the session's lease")); + }); + }); + try { + await Promise.race([release, expiry]); + } finally { + if (timer !== undefined) this.#clock.cancel(timer); + } + } + + /** + * Starts (or restarts) the renew timer for the lease this session just obtained. The client + * is captured deliberately: if that connection dies, the renewal fails and stops rather than + * quietly reconnecting behind the tool surface -- reconnect stays a decision the next tool + * call makes (`#clientForUse`). + */ + #startRenewal(client: SimlockClient, leaseId: string, ttlDeadline: number): void { + this.#stopRenewal(); + // No `onError`: this frontend owns stdout (it is the protocol) and has no side channel a + // failed renewal could be written to. Every failure that matters to the agent surfaces as + // the `lease-lost` notice that follows it, or as the next tool call's own error. + this.#renewal = startLeaseRenewal({ + clock: this.#clock, + leaseId, + renew: (id) => client.renewLease({ leaseId: id }), + ttlDeadline, + }); + } + + #stopRenewal(): void { + this.#renewal?.stop(); + this.#renewal = undefined; + } + /** * Reconnects lazily: a dead `#client` (cleared by the client's own `onConnectionLost`, below) * makes the next call re-run `#connect()`, building a brand new `SimlockClient` -- the typed @@ -247,7 +348,12 @@ export class McpSession { #wireClient(client: SimlockClient): void { this.#clientUnsubscribers = [ client.onLeaseLost((push) => { - if (push.leaseId === this.#heldLeaseId) this.#heldLeaseId = undefined; + if (push.leaseId === this.#heldLeaseId) { + // Nothing left to renew: the lease ended elsewhere (expiry, a force-release, or this + // connection dying -- the client synthesizes the push for that last one). + this.#stopRenewal(); + this.#heldLeaseId = undefined; + } for (const listener of this.#leaseLostListeners) listener(push); }), client.onDeviceUnhealthy((push) => { diff --git a/src/mcp/test-support.ts b/src/mcp/test-support.ts index 8a8e5fcaa..8c300c940 100644 --- a/src/mcp/test-support.ts +++ b/src/mcp/test-support.ts @@ -101,7 +101,6 @@ export class FakeSimlockClient implements SimlockClient { return this.cancelLeaseImpl(input); } - // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP itself never calls lease.renew. renewLease(input: LeaseRenewInput): Promise { this.calls.push({ input, method: "renewLease" }); return this.renewLeaseImpl(input); diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index f1c79b681..a878b51b7 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -105,6 +105,38 @@ describe("connectSimlock: handshake", () => { expect(connection.sent).toHaveLength(1); }); + it("declares no heartbeat capability by default, and starts no renew timer of its own (ADR 0004 §2/§4)", async () => { + const connection = new ScriptedConnection(); + const connectPromise = connectSimlock({ connection }); + await flushMicrotasks(); + const hello = connection.lastSentOf("hello")!; + // The daemon-initiated heartbeat is what ADR 0004 §4 removes; a client that does not + // declare it is never pushed one, and keeps its leases alive with `lease.renew` instead. + expect((hello.payload as { capabilities?: { heartbeat?: boolean } }).capabilities).toEqual({ + heartbeat: false, + }); + completeHello(connection); + const client = await connectPromise; + + // Renew policy stays a frontend's (ADR 0003 §10): connecting alone sends nothing further. + const sentAfterHello = connection.sent.length; + await flushMicrotasks(); + expect(connection.sent).toHaveLength(sentAfterHello); + await client.close(); + }); + + it("still declares the heartbeat capability when a caller explicitly asks for one", async () => { + const connection = new ScriptedConnection(); + const connectPromise = connectSimlock({ connection, heartbeat: true }); + await flushMicrotasks(); + const hello = connection.lastSentOf("hello")!; + expect((hello.payload as { capabilities?: { heartbeat?: boolean } }).capabilities).toEqual({ + heartbeat: true, + }); + completeHello(connection); + await (await connectPromise).close(); + }); + it("a bad admin credential causes zero requests after hello, and closes the connection", async () => { const connection = new ScriptedConnection(); const connectPromise = connectSimlockAdmin({ connection, credential: "wrong" }); diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index 260dcc37e..15c24274b 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -132,8 +132,15 @@ export interface ConnectOptions { * option (programmatic client)". Only meaningful via `connectSimlockAdmin` -- the base * `connectSimlock` does not accept one, by design (ADR §10: "the split is by import path"). */ readonly credential?: string; - /** Declares heartbeat support at `hello`; defaults to `true` so held leases keep sliding - * without the caller doing anything. */ + /** + * Declares heartbeat support at `hello`. Defaults to `false`: ADR 0004 §1/§2 makes a + * client-initiated `lease.renew` the only thing that keeps a lease alive, and §4 removes the + * daemon-initiated heartbeat outright, so a frontend that wants its lease to survive renews + * on its own timer (`src/lease-policy`) rather than declaring a capability. The flag is still + * accepted -- the daemon still speaks the push until PR B deletes it -- but nothing in this + * repository asks for it any more. This client starts no timer of its own either way: renew + * and reconnect policy is the frontend's (ADR 0003 §10, `docs/CLIENT.md`). + */ readonly heartbeat?: boolean; } @@ -211,7 +218,7 @@ export async function connectSimlockClient( hello = await wire.hello({ ...(options.principal === undefined ? {} : { principal: options.principal }), ...(options.credential === undefined ? {} : { credential: options.credential }), - capabilities: { heartbeat: options.heartbeat ?? true }, + capabilities: { heartbeat: options.heartbeat ?? false }, }); } catch (error: unknown) { // ADR §6: a `PROTOCOL_VERSION_UNSUPPORTED` `hello` rejection is the one handshake failure From fe1dce6fdc15c31d94b7b70ab2b18234533684f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 19:57:13 +0000 Subject: [PATCH 2/7] fix(lease-policy,cli,mcp): make client renewal survive a bad answer Findings from the adversarial review of the first commit: - a single failed renewal ended liveness for good, which is worse than the daemon push it replaces (that one retried every interval, forever). An attempt is now retried on the same one-third cadence until the lease's own last known deadline has passed, and every attempt is reported. - a renewal the daemon accepts and never answers is now bounded by the interval it was scheduled on: the wire has no request timeout, so a hung daemon used to cost the whole lease in silence. - a deadline that comes back not in the future ends renewal instead of spinning at the 250ms floor. - the CLI's release moved into the `finally`: a throw between the grant and the wait (a `--export-env` key that is not a shell identifier, an EPIPE on a closed pipe) skipped it, and only the daemon's release-on-close -- which PR B removes -- was covering that. - the MCP session stops renewing only once a release has actually succeeded. Stopping before the call left a session that still held the device with no timer keeping it; a renew that overtakes a successful release cannot resurrect anything, since the registry has already dropped the record. Tests: retry, give-up-at-the-deadline, unanswered-renewal and expired-answer cadences; the CLI's stderr report for a failed renewal, its release on a throwing print, and its held-mode `heartbeat: false` at hello (the previous test only covered `--detach`); the MCP session's renewal surviving a failed release. Part of #114 Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- src/cli/index.test.ts | 104 ++++++++++++++++++++++++++++++- src/cli/index.ts | 71 +++++++++++++--------- src/lease-policy/index.test.ts | 104 ++++++++++++++++++++++++++----- src/lease-policy/index.ts | 108 +++++++++++++++++++++++++-------- src/mcp/session.test.ts | 35 +++++++++++ src/mcp/session.ts | 14 +++-- 6 files changed, 361 insertions(+), 75 deletions(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 2b4778595..6bc2bf8b5 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1409,18 +1409,120 @@ describe("CLI: held-mode renew and release (ADR 0004 §2)", () => { it("declares no heartbeat capability at hello, in either mode (ADR 0004 §4)", async () => { const output = outputCapture(); + const signals = new EventEmitter(); const declared: Array = []; const environment = output.environmentWith({ + clock: new FakeClock(0), connectAdmin: async (_resolveCredential, options) => { declared.push(options?.heartbeat); return fakeClient(); }, + signals: signals as unknown as CliEnvironment["signals"], }); await runCli( ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--detach"], environment, ); - expect(declared).toEqual([false]); + + // Held mode is the case ADR 0004 §4 is actually about: it is the mode the daemon's push + // keys off, and the one that used to declare the capability. + const heldRun = runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro"], + environment, + ); + await settle(); + signals.emit("SIGINT"); + expect(await heldRun).toBe(0); + + expect(declared).toEqual([false, false]); + }); + + it("reports a failed renewal on stderr and keeps holding the lease", async () => { + const clock = new FakeClock(0); + const output = outputCapture(); + const signals = new EventEmitter(); + let released: string | undefined; + const client = fakeClient({ + renewLease: () => + Promise.reject(new SimlockError("INTERNAL", "domain", "could not persist the lease", {})), + releaseLease: (input) => { + released = input.leaseId; + return Promise.resolve({ leaseId: input.leaseId }); + }, + }); + const runPromise = runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro"], + output.environmentWith({ + clock, + connectAdmin: async () => client, + signals: signals as unknown as CliEnvironment["signals"], + }), + ); + await settle(); + clock.advance(20_000); + await settle(); + + const errorLines = output.stderr + .trim() + .split("\n") + .map((line) => JSON.parse(line) as Record) + .filter((line) => line.error !== undefined); + expect(errorLines).toContainEqual({ + error: { code: "INTERNAL", message: "could not persist the lease" }, + }); + + // A failed renewal is not an exit condition: the holder still holds, and still releases. + signals.emit("SIGINT"); + expect(await runPromise).toBe(0); + expect(released).toBe("lse_1"); + }); + + it("still releases the lease when printing the grant throws (--export-env with a bad key)", async () => { + const clock = new FakeClock(0); + const output = outputCapture(); + let released: string | undefined; + const client = fakeClient({ + requestLease: () => + Promise.resolve({ + device: { + id: "dev_1", + driverDeviceId: "dev_1", + spec: { platform: "ios", model: "x", osVersion: "26.5" }, + }, + // A driver-supplied key that is not a shell identifier fails the command rather than + // being silently dropped -- and that throw must not cost the device. + environment: { "NOT A KEY": "value" }, + lease: { + id: "lse_1", + deviceId: "dev_1", + requesterId: "test-requester", + ownerId: "test-requester", + mode: "held" as const, + grantedAt: 0, + ttlDeadline: 60_000, + }, + timing: { + estimatedProvisionMs: 0, + estimatedBootMs: 0, + estimatedReclaimMs: 0, + estimatedReadyMs: 0, + }, + }), + releaseLease: (input) => { + released = input.leaseId; + return Promise.resolve({ leaseId: input.leaseId }); + }, + }); + const exitCode = await runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--export-env"], + output.environmentWith({ clock, connectAdmin: async () => client }), + ); + + expect(exitCode).toBe(1); + expect(released, "an exit through a throw is still an exit, and still owes a release").toBe( + "lse_1", + ); + expect(clock.pendingTimerCount).toBe(0); }); it("arms no renew timer for --detach: it prints and exits, exactly as before", async () => { diff --git a/src/cli/index.ts b/src/cli/index.ts index eb4919b98..7ab47f71b 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -35,7 +35,7 @@ import { } from "../admin/index.js"; import type { Role } from "../contract/index.js"; import type { PassthroughCommand } from "../client/index.js"; -import { startLeaseRenewal } from "../lease-policy/index.js"; +import { startLeaseRenewal, type LeaseRenewal } from "../lease-policy/index.js"; import { spawnPassthrough } from "./passthrough.js"; import { ERROR_TABLE } from "../contract/index.js"; @@ -742,6 +742,32 @@ async function runLease( const offRecovered = client.onDeviceRecovered((push) => { environment.stderr.write(`${JSON.stringify({ push: "device-recovered", ...push })}\n`); }); + /** + * ADR 0004 §2/§3: the release a held holder owes when it stops holding -- an exit, parent + * death, a catchable signal, or a throw on the way to any of them. It runs from the `finally` + * below so no exit path can skip it (a broken `--export-env` key or an EPIPE on a closed pipe + * both throw between the grant and the wait), and it is the call that will still be here when + * the daemon stops releasing on connection close in PR B. + * + * Set only for held mode, and cleared as it runs, so it happens exactly once and never for + * `--detach` (whose lease deliberately outlives this process) or for a lease the daemon has + * already ended (`leaseLost` -- asking again would only raise UNKNOWN_LEASE). + */ + let heldLeaseId: string | undefined; + const releaseHeldLease = async (): Promise => { + if (heldLeaseId === undefined || leaseLost) return; + const leaseId = heldLeaseId; + heldLeaseId = undefined; + try { + await client.releaseLease({ leaseId }); + } catch (error: unknown) { + // Non-fatal: the process still exits 0 after a signal, but the release + // failure is still diagnostic output, so it stays a structured stderr + // line rather than reverting to prose. + writeError(environment, error); + } + }; + let renewal: LeaseRenewal | undefined; try { const grant = await client.requestLease( { @@ -762,6 +788,8 @@ async function runLease( }, ); ourLeaseId = grant.lease.id; + // Owed from here on, whatever happens next -- see `releaseHeldLease`. + if (!detached && termination !== undefined) heldLeaseId = grant.lease.id; // ADR §5: "simlock lease output includes the resolved role" -- the one field this CLI // adds on top of the contract's `LeaseGrant` shape, everything else passed through as-is. const result = { ...grant, role: client.role }; @@ -774,42 +802,25 @@ async function runLease( // TTL -- computed from the deadline the daemon just returned, not from a config value this // process does not have. `--detach` returned above: it stays exactly as it was, printing // and exiting with no timer at all. - const renewal = startLeaseRenewal({ + renewal = startLeaseRenewal({ clock: environment.clock, leaseId: grant.lease.id, ttlDeadline: grant.lease.ttlDeadline, renew: (leaseId) => client.renewLease({ leaseId }), - // A renewal that fails has ended this holder's claim (see `startLeaseRenewal`); it is - // diagnostic output, on the same structured stderr channel as a failed release, and it - // does not by itself end the process -- the lease-lost push or the daemon's own expiry - // is what decides that. + // A failed attempt is retried until the lease's deadline (see `startLeaseRenewal`), so + // this is diagnostic output on the same structured stderr channel as a failed release, + // not an exit condition: the lease-lost push or the daemon's own expiry is what decides + // when this process stops holding. onError: (error) => writeError(environment, error), }); - try { - await Promise.race([termination.settled, leaseLostSignal]); - } finally { - // Before the release below, and before any early return: a renew must never race the - // release of the lease it is renewing. - renewal.stop(); - } - if (leaseLost) { - // The daemon already released it; asking again would only raise UNKNOWN_LEASE. - return LEASE_LOST_EXIT_CODE; - } - try { - // ADR 0004 §2/§3: the release a held holder owes on exit, parent death, or a catchable - // signal is this call -- not the socket closing in the `finally` below. The daemon still - // releases on close today (PR B removes that), so this is the path that will still be - // here when nothing else is. - await client.releaseLease({ leaseId: grant.lease.id }); - } catch (error: unknown) { - // Non-fatal: the process still exits 0 after a signal, but the release - // failure is still diagnostic output, so it stays a structured stderr - // line rather than reverting to prose. - writeError(environment, error); - } - return 0; + await Promise.race([termination.settled, leaseLostSignal]); + // The daemon already released a lost lease; `releaseHeldLease` skips it for that reason. + return leaseLost ? LEASE_LOST_EXIT_CODE : 0; } finally { + // Stopped before the release, always: a renew must never race the release of the lease it + // is renewing, and no timer may outlive this command. + renewal?.stop(); + await releaseHeldLease(); termination?.dispose(); offLeaseLost(); offUnhealthy(); diff --git a/src/lease-policy/index.test.ts b/src/lease-policy/index.test.ts index 86d378102..1b3bea1e1 100644 --- a/src/lease-policy/index.test.ts +++ b/src/lease-policy/index.test.ts @@ -104,31 +104,101 @@ describe("startLeaseRenewal", () => { expect(calls).toBe(1); }); - it("ends renewal on the first failure, reporting it exactly once", async () => { + it("retries a failed renewal while the lease can still be saved, and reports every attempt", async () => { const clock = new FakeClock(0); - const failure = new Error("UNKNOWN_LEASE"); + const failure = new Error("INTERNAL"); const errors: unknown[] = []; - let calls = 0; + const attemptsAt: number[] = []; + let failuresLeft = 1; startLeaseRenewal({ clock, leaseId: "lse_1", onError: (error) => errors.push(error), renew: () => { - calls += 1; - return Promise.reject(failure); + attemptsAt.push(clock.now()); + if (failuresLeft > 0) { + failuresLeft -= 1; + return Promise.reject(failure); + } + return Promise.resolve({ ttlDeadline: clock.now() + 3_000 }); }, ttlDeadline: 3_000, }); + // A daemon that failed to persist one renewal is still willing to serve the next, and the + // one-third cadence exists precisely to leave room for the retry. clock.advance(1_000); await flushMicrotasks(); + expect(attemptsAt).toEqual([1_000]); expect(errors).toEqual([failure]); - expect(clock.pendingTimerCount).toBe(0); + clock.advance(666); + await flushMicrotasks(); + expect(attemptsAt).toEqual([1_000, 1_666]); + expect(errors).toHaveLength(1); + // The successful retry put the lease back on a full TTL: renewal continues from there. + expect(clock.pendingTimerCount).toBe(1); + }); + + it("gives up once the lease's own deadline has passed", async () => { + const clock = new FakeClock(0); + const errors: unknown[] = []; + let calls = 0; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + onError: (error) => errors.push(error), + renew: () => { + calls += 1; + return Promise.reject(new Error("DAEMON_CONNECTION_LOST")); + }, + ttlDeadline: 3_000, + }); + + // Retries keep shrinking with what is left of the TTL; once the deadline is behind us + // there is nothing left to save, and the timer is gone for good. clock.advance(60_000); await flushMicrotasks(); - expect(calls, "a failed renewal is not retried on a timer").toBe(1); + expect(clock.pendingTimerCount).toBe(0); + const attemptsBefore = calls; + expect(errors).toHaveLength(attemptsBefore); + + clock.advance(600_000); + await flushMicrotasks(); + expect(calls).toBe(attemptsBefore); + }); + + it("abandons a renewal the daemon never answers, and retries it", async () => { + const clock = new FakeClock(0); + const errors: unknown[] = []; + let calls = 0; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + onError: (error) => errors.push(error), + renew: () => { + calls += 1; + // Accepted and never answered: the wire has no request timeout of its own. + return new Promise<{ ttlDeadline: number }>(() => {}); + }, + ttlDeadline: 9_000, + }); + + clock.advance(3_000); + await flushMicrotasks(); + expect(calls).toBe(1); + expect(errors).toEqual([]); + + // The attempt is bounded by the interval it was scheduled on (2_000ms of the 6_000ms + // left), so it does not swallow the rest of the TTL in silence. + clock.advance(2_000); + await flushMicrotasks(); expect(errors).toHaveLength(1); + expect(calls).toBe(1); + + clock.advance(1_333); + await flushMicrotasks(); + expect(calls).toBe(2); }); it("never reports a failure that arrives after stop()", async () => { @@ -155,18 +225,21 @@ describe("startLeaseRenewal", () => { expect(errors).toEqual([]); }); - it("still renews a deadline that is already in the past, without becoming a hot loop", async () => { + it("tries a deadline that is already in the past once, then stops instead of hot-looping", async () => { const clock = new FakeClock(1_000); const renewedAt: number[] = []; - const renewal = startLeaseRenewal({ + const errors: unknown[] = []; + startLeaseRenewal({ clock, leaseId: "lse_1", + onError: (error) => errors.push(error), renew: () => { renewedAt.push(clock.now()); - // A daemon that keeps answering with an expired deadline: without the floor this - // would renew once per tick forever. + // A daemon answering with a deadline that is not in the future -- reachable with + // `lease.heldTtlBackstopMs: 0`, which the config validator allows. return Promise.resolve({ ttlDeadline: clock.now() }); }, + // Already expired at the grant: the floor keeps even this from being an instant loop. ttlDeadline: 500, }); @@ -177,10 +250,11 @@ describe("startLeaseRenewal", () => { await flushMicrotasks(); expect(renewedAt).toEqual([1_250]); - clock.advance(250); + // Nothing to renew towards: renewal ends rather than spinning at the floor forever. + expect(clock.pendingTimerCount).toBe(0); + expect(errors).toHaveLength(1); + clock.advance(600_000); await flushMicrotasks(); - expect(renewedAt).toEqual([1_250, 1_500]); - - renewal.stop(); + expect(renewedAt).toEqual([1_250]); }); }); diff --git a/src/lease-policy/index.ts b/src/lease-policy/index.ts index 432bec678..0f0838720 100644 --- a/src/lease-policy/index.ts +++ b/src/lease-policy/index.ts @@ -26,8 +26,7 @@ const RENEW_DIVISOR = 3; * Floor on the scheduled delay. Only reachable when the daemon returns a deadline that is * already very close (or in the past) -- a misconfigured `lease.heldTtlBackstopMs`, a clock * that jumped, or a renewal that raced its own expiry. Without it, a non-positive remaining - * TTL would turn the timer into an unbounded renew-per-tick loop against the daemon. The - * renewal still happens; it is only kept from becoming a hot loop. + * TTL would turn the timer into an unbounded renew-per-tick loop against the daemon. */ const MINIMUM_RENEW_DELAY_MS = 250; @@ -44,17 +43,18 @@ export interface LeaseRenewalOptions { /** Calls `lease.renew` for this lease -- `client.renewLease({ leaseId })`, in practice. */ readonly renew: (leaseId: string) => Promise; /** - * Reports the failure that stopped renewal (see `LeaseRenewal#stop` for why renewal ends - * there). Never called after `stop()`. + * Reports every failed attempt, and the failure that finally ends renewal. Never called + * after `stop()`. */ readonly onError?: (error: unknown) => void; } export interface LeaseRenewal { /** - * Cancels the pending timer and guarantees no further `renew` call, `onError` call, or - * reschedule -- including from a renewal that is already in flight. Idempotent, and the one - * thing a holder must do before releasing, so a renew cannot race its own release. + * Cancels whatever timer is armed -- the wait between renewals, or the bound on an attempt + * already in flight -- and guarantees no further `renew` call, `onError` call, or reschedule. + * Idempotent, and the one thing a holder must do before releasing, so a renew cannot race its + * own release. */ stop(): void; } @@ -64,50 +64,108 @@ function renewDelayMs(remainingMs: number): number { return Math.max(MINIMUM_RENEW_DELAY_MS, Math.floor(remainingMs / RENEW_DIVISOR)); } +type Attempt = + | { readonly ok: true; readonly renewed: RenewedLease } + | { readonly ok: false; readonly error: unknown }; + /** * Starts renewing `leaseId` at a third of the remaining TTL, rescheduling off each renewal's * own returned deadline, until `stop()`. * - * A failed renewal ends renewal rather than retrying: the typed client never reconnects (ADR - * 0003 §10), so a rejection is either a dead connection -- on which no later call would - * succeed either -- or the daemon saying this lease is no longer renewable (it expired, or - * was force-released). Both end this holder's claim; retrying would only turn one honest - * error into a stream of them. The caller learns through `onError` and through the - * `lease-lost` push that accompanies the second case. + * Renewing at a third of the TTL exists to leave room for two more tries before the deadline, + * so a failed attempt is retried on the same cadence rather than ending the lease: the daemon + * may have failed to persist one renewal (`INTERNAL`) and still be perfectly willing to serve + * the next. Renewal ends only when the lease can no longer be saved -- its last known deadline + * has passed, or the daemon answered with one that is not in the future. A holder whose + * connection died, or whose lease was force-released, stops sooner than that through its + * `lease-lost` handler (ADR 0003 §10), which is the signal that actually means "this lease is + * over"; the retries in between are cheap and bounded by the deadline. + * + * Each attempt is bounded by the same interval it was scheduled on, so a daemon that accepts + * `lease.renew` and never answers costs one interval rather than the whole lease: the wire has + * no request timeout of its own, and an abandoned request cannot slide the deadline anywhere + * but forward. */ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { const { clock, leaseId, onError, renew } = options; + /** The last deadline the daemon actually gave us -- the only input to the cadence. */ + let deadline = options.ttlDeadline; + /** Whichever timer is armed right now: the wait between renewals, or an attempt's bound. */ let timer: TimerHandle | undefined; let stopped = false; - const schedule = (ttlDeadline: number): void => { + const cancelTimer = (): void => { + if (timer === undefined) return; + clock.cancel(timer); + timer = undefined; + }; + + const schedule = (): void => { if (stopped) return; - timer = clock.setTimer(renewDelayMs(ttlDeadline - clock.now()), () => { + timer = clock.setTimer(renewDelayMs(deadline - clock.now()), () => { timer = undefined; void tick(); }); }; + /** One renewal attempt, bounded by the interval it was scheduled on. */ + const attemptRenew = async (): Promise => { + const request = renew(leaseId); + // Attached unconditionally: an abandoned request still settles later, and a rejection + // nobody awaits would surface as an unhandled rejection. + request.catch(() => undefined); + return Promise.race([ + request.then( + (renewed) => ({ ok: true, renewed }), + (error: unknown) => ({ error, ok: false }), + ), + new Promise((resolve) => { + timer = clock.setTimer(renewDelayMs(deadline - clock.now()), () => { + timer = undefined; + resolve({ + error: new Error(`Timed out renewing lease ${leaseId}`), + ok: false, + }); + }); + }), + ]); + }; + const tick = async (): Promise => { if (stopped) return; - try { - const renewed = await renew(leaseId); - schedule(renewed.ttlDeadline); - } catch (error: unknown) { - if (stopped) return; + const attempt = await attemptRenew(); + cancelTimer(); + if (stopped) return; + + if (!attempt.ok) { + onError?.(attempt.error); + // Out of runway: the lease is gone (or about to be), and another attempt would only + // produce another error. + if (clock.now() >= deadline) { + stopped = true; + return; + } + schedule(); + return; + } + + if (attempt.renewed.ttlDeadline <= clock.now()) { + // A deadline that is not in the future cannot be renewed towards -- scheduling off it + // would be a hot loop against a lease that is already over. stopped = true; - onError?.(error); + onError?.(new Error(`Lease ${leaseId} was renewed to a deadline that has already passed`)); + return; } + deadline = attempt.renewed.ttlDeadline; + schedule(); }; - schedule(options.ttlDeadline); + schedule(); return { stop: (): void => { stopped = true; - if (timer === undefined) return; - clock.cancel(timer); - timer = undefined; + cancelTimer(); }, }; } diff --git a/src/mcp/session.test.ts b/src/mcp/session.test.ts index a38465714..923365e44 100644 --- a/src/mcp/session.test.ts +++ b/src/mcp/session.test.ts @@ -335,6 +335,41 @@ describe("McpSession", () => { expect(client.calls.filter((call) => call.method === "releaseLease")).toHaveLength(1); }); + it("keeps renewing when a release fails, because the session still holds the device", async () => { + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + client.releaseLeaseImpl = () => + Promise.reject(new SimlockError("INTERNAL", "domain", "could not release", {})); + let renewals = 0; + client.renewLeaseImpl = (input) => { + renewals += 1; + return Promise.resolve({ + deviceId: "device-1", + grantedAt: 0, + id: input.leaseId, + mode: "held" as const, + ownerId: "mcp-test", + requesterId: "mcp-test", + ttlDeadline: clock.now() + 12_000, + }); + }; + const session = new McpSession({ clock, connect: async () => client }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + await expect(session.release({ leaseId: "lease-1" })).rejects.toMatchObject({ + code: "INTERNAL", + }); + + // The daemon still has the lease, so the timer that keeps it must still be running -- + // otherwise the device is reclaimed at the deadline under a session that was told its + // release failed. + clock.advance(4_115); + await flushMicrotasks(); + expect(renewals).toBe(1); + await session.close(); + }); + it("stops renewing a lease that ended elsewhere", async () => { const clock = new FakeClock(0); const client = new FakeSimlockClient(); diff --git a/src/mcp/session.ts b/src/mcp/session.ts index 21ad89b15..7fc409056 100644 --- a/src/mcp/session.ts +++ b/src/mcp/session.ts @@ -161,11 +161,17 @@ export class McpSession { return this.#mutate(async () => { this.#throwIfClosed(); const client = await this.#clientForUse(); - // Stopped before the call, not after it: a renew that overtook its own release would - // resurrect the lease the caller just gave up. - if (input.leaseId === this.#heldLeaseId) this.#stopRenewal(); const result = await client.releaseLease(input); - if (result.leaseId === this.#heldLeaseId) this.#heldLeaseId = undefined; + // Stopped only once the daemon has actually let the lease go. A release that fails + // (anything but a dead connection) leaves the session still holding the device, and a + // session that has stopped renewing a lease it still holds loses that device at the + // deadline. A renew that overtakes a *successful* release cannot resurrect anything: + // `Registry#beginRelease` drops the record, so `lease.renew` can only answer + // UNKNOWN_LEASE. + if (result.leaseId === this.#heldLeaseId) { + this.#stopRenewal(); + this.#heldLeaseId = undefined; + } return { ...result, released: true }; }); } From c0ca4fe54e197ecd8c13a82e5a5bfdda10e996b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 20:28:44 +0000 Subject: [PATCH 3/7] fix(lease-policy,cli,mcp): close the second review round's gaps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - an abandoned renewal that turns out to have reached the daemon now contributes its deadline, so the give-up check can no longer fire against a deadline the daemon has already moved. - a throwing `onError` can no longer take the process down through the timer's own `void tick()`, which would have skipped the release the holder still owes; giving up permanently now reports itself distinctly from the attempt that failed. - the CLI's farewell release is bounded exactly like MCP's, through one shared helper rather than two opposite decisions in one change. - `SIGHUP` joins SIGINT/SIGTERM: ADR 0004 §2 says "a catchable signal", and a closing terminal is the likeliest way a backgrounded holder dies. - `close()` no longer sends a second `lease.release` for a lease whose release a tool call already has in flight. - `CliEnvironment.now` is gone: `clock` is required now, and the old field's `Date.now` fallback was a standing architecture-rule-9 violation. Tests: the cadence test now answers a deadline the grant's own could never produce (it passed with the reschedule deleted); the give-up test walks the retry ladder instead of one attempt; new coverage for a late answer moving the deadline, for release-on-SIGHUP/SIGINT/SIGTERM, and for the release-in-flight guard on close. Part of #114 Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- e2e/heartbeat-ttl.test.ts | 4 ++ src/cli/index.test.ts | 29 ++++++++++- src/cli/index.ts | 39 +++++++++++---- src/lease-policy/index.test.ts | 91 +++++++++++++++++++++++++++------- src/lease-policy/index.ts | 78 ++++++++++++++++++++++++++--- src/mcp/session.test.ts | 24 +++++++++ src/mcp/session.ts | 59 +++++++++++----------- 7 files changed, 255 insertions(+), 69 deletions(-) diff --git a/e2e/heartbeat-ttl.test.ts b/e2e/heartbeat-ttl.test.ts index 704bf9948..5ac77aad8 100644 --- a/e2e/heartbeat-ttl.test.ts +++ b/e2e/heartbeat-ttl.test.ts @@ -50,6 +50,10 @@ describe("sliding TTL and heartbeat", () => { // detached lease's own (unrelated) TTL knob expires it on the timeline this // test already waits on -- detached mode never heartbeats regardless of TTL, // it just isn't naturally this short by default. + // + // heartbeatIntervalMs is no longer what keeps the held leases alive (their holders + // renew on their own timer, ADR 0004 §2); it stays here because the config validator + // still requires it to be at most heldTtlBackstopMs / 4, and 4_000ms is short. configOverrides: { lease: { detachedTtlMs: 4_000, heldTtlBackstopMs: 4_000, heartbeatIntervalMs: 800 }, }, diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 6bc2bf8b5..52186c352 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1437,6 +1437,34 @@ describe("CLI: held-mode renew and release (ADR 0004 §2)", () => { expect(declared).toEqual([false, false]); }); + it.each(["SIGHUP", "SIGINT", "SIGTERM"] as const)( + "releases explicitly on %s (ADR 0004 §2's catchable signals)", + async (signal) => { + const output = outputCapture(); + const signals = new EventEmitter(); + let released: string | undefined; + const client = fakeClient({ + releaseLease: (input) => { + released = input.leaseId; + return Promise.resolve({ leaseId: input.leaseId }); + }, + }); + const runPromise = runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro"], + output.environmentWith({ + clock: new FakeClock(0), + connectAdmin: async () => client, + signals: signals as unknown as CliEnvironment["signals"], + }), + ); + await settle(); + signals.emit(signal); + + expect(await runPromise).toBe(0); + expect(released).toBe("lse_1"); + }, + ); + it("reports a failed renewal on stderr and keeps holding the lease", async () => { const clock = new FakeClock(0); const output = outputCapture(); @@ -1944,7 +1972,6 @@ function outputCapture(ports?: CliEnvironmentPorts): OutputCapture { clock: new FakeClock(0), configPath: "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/simlock/config.json", requesterId: "test-requester", - now: () => 0, connectAdmin: async () => fakeClient(), connectExistingAdmin: async () => fakeClient(), readAdminTokenFile: async () => undefined, diff --git a/src/cli/index.ts b/src/cli/index.ts index 7ab47f71b..e215cd674 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -35,7 +35,12 @@ import { } from "../admin/index.js"; import type { Role } from "../contract/index.js"; import type { PassthroughCommand } from "../client/index.js"; -import { startLeaseRenewal, type LeaseRenewal } from "../lease-policy/index.js"; +import { + awaitWithin, + RELEASE_TIMEOUT_MS, + startLeaseRenewal, + type LeaseRenewal, +} from "../lease-policy/index.js"; import { spawnPassthrough } from "./passthrough.js"; import { ERROR_TABLE } from "../contract/index.js"; @@ -90,9 +95,18 @@ interface Output { write(value: string): unknown; } +/** + * ADR 0004 §2's "a catchable signal", enumerated: the two a holder is asked to stop with, plus + * `SIGHUP` -- what a closing terminal sends, and the likeliest way a backgrounded holder dies + * short of `SIGKILL`. All three take the same path: stop renewing, release, exit. + */ +const TERMINATION_SIGNALS = ["SIGHUP", "SIGINT", "SIGTERM"] as const; + +type TerminationSignal = (typeof TERMINATION_SIGNALS)[number]; + interface Signals { - on(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown; - off(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown; + on(signal: TerminationSignal, listener: () => void): unknown; + off(signal: TerminationSignal, listener: () => void): unknown; } type McpStdioRunner = () => Promise; @@ -119,7 +133,6 @@ export interface CliEnvironment { * "SIMLOCK_AGENT_ID and --agent-id still set the requester id ... they are not the * principal": `--agent-id` overrides `lease.request`'s `requesterId` field, never this. */ readonly requesterId: string; - readonly now?: () => number; /** * Connects (auto-launching the daemon if it is not already running) and completes `hello` * with whatever `resolveCredential` resolves to. @@ -396,7 +409,6 @@ export function buildCliEnvironment( clock, configPath, requesterId, - now: () => clock.now(), connectAdmin: (resolveCredential, options) => connect(autoLaunchIpc, resolveCredential, options), connectExistingAdmin: (resolveCredential, options) => connect(ipc, resolveCredential, options), @@ -759,7 +771,14 @@ async function runLease( const leaseId = heldLeaseId; heldLeaseId = undefined; try { - await client.releaseLease({ leaseId }); + // Bounded like MCP's farewell release: a daemon that accepts the frame and never answers + // must not leave `simlock lease` hanging after a Ctrl-C. + await awaitWithin( + environment.clock, + RELEASE_TIMEOUT_MS, + client.releaseLease({ leaseId }), + `Timed out releasing lease ${leaseId}`, + ); } catch (error: unknown) { // Non-fatal: the process still exits 0 after a signal, but the release // failure is still diagnostic output, so it stays a structured stderr @@ -1099,7 +1118,7 @@ async function runEvents( try { const sinceTs = typeof values.since === "string" - ? (environment.now ?? Date.now)() - parseDuration(values.since) + ? environment.clock.now() - parseDuration(values.since) : undefined; for (const event of await client.replayEvents(sinceTs === undefined ? {} : { sinceTs })) { writeResult(environment, event); @@ -1555,12 +1574,10 @@ function waitForTermination( resolve(); }; detach = () => { - signals.off("SIGINT", finish); - signals.off("SIGTERM", finish); + for (const signal of TERMINATION_SIGNALS) signals.off(signal, finish); watchHandle?.stop(); }; - signals.on("SIGINT", finish); - signals.on("SIGTERM", finish); + for (const signal of TERMINATION_SIGNALS) signals.on(signal, finish); watchHandle = parentWatch !== undefined && parentPid !== undefined && parentPid > 0 ? parentWatch.watch(parentPid, finish) diff --git a/src/lease-policy/index.test.ts b/src/lease-policy/index.test.ts index 1b3bea1e1..0352e8c75 100644 --- a/src/lease-policy/index.test.ts +++ b/src/lease-policy/index.test.ts @@ -24,9 +24,10 @@ describe("startLeaseRenewal", () => { renew: (leaseId) => { renewedAt.push(clock.now()); seenLeaseIds.push(leaseId); - // The daemon's answer -- deliberately a *different* TTL than the grant's, so a - // cadence computed from anything but this deadline shows up as a wrong timestamp. - return Promise.resolve({ ttlDeadline: clock.now() + 6_000 }); + // The daemon's answer -- deliberately a shorter TTL than the grant's, and a + // deadline the grant's own (10_000) could never produce, so a cadence derived from + // anything but this value shows up as a wrong timestamp below. + return Promise.resolve({ ttlDeadline: clock.now() + 3_000 }); }, ttlDeadline: 1_000 + 9_000, }); @@ -40,14 +41,15 @@ describe("startLeaseRenewal", () => { expect(renewedAt).toEqual([4_000]); expect(seenLeaseIds).toEqual(["lse_1"]); - // 6_000ms of TTL came back, so the next renewal is 2_000ms out -- not the 3_000ms the - // grant's own TTL would imply, and not 3_000ms after the previous *scheduled* time either. - clock.advance(1_999); + // 3_000ms of TTL came back at 4_000, so the next renewal is 1_000ms out -- not the + // 2_000ms the grant's own deadline would still imply, and not 3_000ms after the previous + // scheduled time either. + clock.advance(999); await flushMicrotasks(); expect(renewedAt).toEqual([4_000]); clock.advance(1); await flushMicrotasks(); - expect(renewedAt).toEqual([4_000, 6_000]); + expect(renewedAt).toEqual([4_000, 5_000]); renewal.stop(); }); @@ -140,32 +142,85 @@ describe("startLeaseRenewal", () => { expect(clock.pendingTimerCount).toBe(1); }); - it("gives up once the lease's own deadline has passed", async () => { + it("retries on a shrinking ladder, then gives up once the lease's own deadline has passed", async () => { const clock = new FakeClock(0); - const errors: unknown[] = []; - let calls = 0; + const errors: Error[] = []; + const attemptsAt: number[] = []; startLeaseRenewal({ clock, leaseId: "lse_1", - onError: (error) => errors.push(error), + onError: (error) => errors.push(error as Error), renew: () => { - calls += 1; - return Promise.reject(new Error("DAEMON_CONNECTION_LOST")); + attemptsAt.push(clock.now()); + return Promise.reject(new Error("INTERNAL")); }, ttlDeadline: 3_000, }); - // Retries keep shrinking with what is left of the TTL; once the deadline is behind us - // there is nothing left to save, and the timer is gone for good. + // Every retry is a third of what is *left* of the TTL, so the ladder shrinks towards the + // deadline instead of marching past it at a fixed interval. + clock.advance(1_000); + await flushMicrotasks(); + expect(attemptsAt).toEqual([1_000]); + clock.advance(666); + await flushMicrotasks(); + expect(attemptsAt).toEqual([1_000, 1_666]); + clock.advance(444); + await flushMicrotasks(); + expect(attemptsAt).toEqual([1_000, 1_666, 2_110]); + expect(errors.map((error) => error.message)).toEqual(["INTERNAL", "INTERNAL", "INTERNAL"]); + + // Once the deadline is behind us there is nothing left to save: renewal ends, with its own + // final report, distinct from the attempt failure that preceded it. clock.advance(60_000); await flushMicrotasks(); expect(clock.pendingTimerCount).toBe(0); - const attemptsBefore = calls; - expect(errors).toHaveLength(attemptsBefore); + expect(errors.at(-1)?.message).toContain("Gave up renewing lease lse_1"); + const attempts = attemptsAt.length; clock.advance(600_000); await flushMicrotasks(); - expect(calls).toBe(attemptsBefore); + expect(attemptsAt).toHaveLength(attempts); + }); + + it("keeps a deadline an abandoned renewal turns out to have moved", async () => { + const clock = new FakeClock(0); + const attemptsAt: number[] = []; + let answerFirst!: (renewed: { ttlDeadline: number }) => void; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + renew: () => { + attemptsAt.push(clock.now()); + if (attemptsAt.length > 1) return Promise.reject(new Error("INTERNAL")); + return new Promise<{ ttlDeadline: number }>((resolve) => { + answerFirst = resolve; + }); + }, + ttlDeadline: 3_000, + }); + + clock.advance(1_000); + await flushMicrotasks(); + expect(attemptsAt).toEqual([1_000]); + + // The attempt is abandoned at its bound (a third of the 2_000ms left), and only then does + // the daemon answer it. The request still reached the daemon, so that deadline is real. + clock.advance(666); + await flushMicrotasks(); + answerFirst({ ttlDeadline: 30_000 }); + await flushMicrotasks(); + + clock.advance(444); + await flushMicrotasks(); + expect(attemptsAt).toEqual([1_000, 2_110]); + + // Working towards 30_000 now, not the stale 3_000: a retry lands long after the deadline + // this renewal would otherwise have given up at, because the lease has not expired. + clock.advance(9_296); + await flushMicrotasks(); + expect(attemptsAt).toEqual([1_000, 2_110, 11_406]); + expect(clock.pendingTimerCount).toBe(1); }); it("abandons a renewal the daemon never answers, and retries it", async () => { diff --git a/src/lease-policy/index.ts b/src/lease-policy/index.ts index 0f0838720..4d64df847 100644 --- a/src/lease-policy/index.ts +++ b/src/lease-policy/index.ts @@ -24,12 +24,47 @@ const RENEW_DIVISOR = 3; /** * Floor on the scheduled delay. Only reachable when the daemon returns a deadline that is - * already very close (or in the past) -- a misconfigured `lease.heldTtlBackstopMs`, a clock + * already very close (or in the past) -- a daemon configured with a zero-length TTL, a clock * that jumped, or a renewal that raced its own expiry. Without it, a non-positive remaining * TTL would turn the timer into an unbounded renew-per-tick loop against the daemon. */ const MINIMUM_RENEW_DELAY_MS = 250; +/** + * How long a holder waits for its farewell `lease.release` before giving up and closing the + * connection anyway. The daemon is a local process answering a local socket, so this is not a + * latency budget -- it is the bound that keeps an unresponsive daemon from hanging the exit of + * a CLI holder or an MCP server. Exceeding it costs nothing but the wait: the lease then ends + * the way every unreleased lease ends, at its deadline. + */ +export const RELEASE_TIMEOUT_MS = 5_000; + +/** + * Resolves with `work`, or rejects once `timeoutMs` has passed on `clock`. The timer is always + * cancelled, so it never holds a process open by itself, and a rejection from an abandoned + * `work` is swallowed rather than surfacing as an unhandled rejection. + */ +export async function awaitWithin( + clock: Clock, + timeoutMs: number, + work: Promise, + timeoutMessage: string, +): Promise { + work.catch(() => undefined); + let timer: TimerHandle | undefined; + const expiry = new Promise((_resolve, reject) => { + timer = clock.setTimer(timeoutMs, () => { + timer = undefined; + reject(new Error(timeoutMessage)); + }); + }); + try { + return await Promise.race([work, expiry]); + } finally { + if (timer !== undefined) clock.cancel(timer); + } +} + /** The subset of a `LeaseRecord` renewal needs back: the daemon's new deadline. */ export interface RenewedLease { readonly ttlDeadline: number; @@ -100,20 +135,42 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { timer = undefined; }; + /** Isolated: a holder that cannot report a failure must still keep holding. */ + const report = (error: unknown): void => { + if (onError === undefined) return; + try { + onError(error); + } catch { + // A `stderr` that throws (a closed pipe, say) must not take the release path down with + // it -- see the `void tick()` below, which nothing awaits. + } + }; + const schedule = (): void => { if (stopped) return; timer = clock.setTimer(renewDelayMs(deadline - clock.now()), () => { timer = undefined; - void tick(); + // Nothing awaits this: an unhandled rejection here would take the whole process down, + // and with it the release the holder still owes. + void tick().catch(() => undefined); }); }; /** One renewal attempt, bounded by the interval it was scheduled on. */ const attemptRenew = async (): Promise => { const request = renew(leaseId); - // Attached unconditionally: an abandoned request still settles later, and a rejection - // nobody awaits would surface as an unhandled rejection. - request.catch(() => undefined); + // An abandoned request still reaches the daemon: if it succeeds after this attempt has + // been given up on, its deadline is real and worth keeping -- discarding it would let the + // give-up test below fire against a deadline the daemon has already moved. (It also keeps + // a late rejection from surfacing as an unhandled rejection.) + request.then( + (renewed) => { + // `Math.max`, not a plain assignment: this answer belongs to a request older than + // whatever has happened since, so it may only ever push the deadline forward. + if (!stopped) deadline = Math.max(deadline, renewed.ttlDeadline); + }, + () => undefined, + ); return Promise.race([ request.then( (renewed) => ({ ok: true, renewed }), @@ -138,11 +195,14 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { if (stopped) return; if (!attempt.ok) { - onError?.(attempt.error); + report(attempt.error); // Out of runway: the lease is gone (or about to be), and another attempt would only - // produce another error. + // produce another error. Reported separately from the attempt that failed, because + // "this one did not work" and "this lease will not be renewed again" are different + // things for a holder to read. if (clock.now() >= deadline) { stopped = true; + report(new Error(`Gave up renewing lease ${leaseId}: its deadline has passed`)); return; } schedule(); @@ -153,9 +213,11 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { // A deadline that is not in the future cannot be renewed towards -- scheduling off it // would be a hot loop against a lease that is already over. stopped = true; - onError?.(new Error(`Lease ${leaseId} was renewed to a deadline that has already passed`)); + report(new Error(`Lease ${leaseId} was renewed to a deadline that has already passed`)); return; } + // The daemon's answer is authoritative, in both directions: it may hand back a shorter + // deadline than the one that was asked for, and the cadence follows it. deadline = attempt.renewed.ttlDeadline; schedule(); }; diff --git a/src/mcp/session.test.ts b/src/mcp/session.test.ts index 923365e44..7a58bce90 100644 --- a/src/mcp/session.test.ts +++ b/src/mcp/session.test.ts @@ -335,6 +335,30 @@ describe("McpSession", () => { expect(client.calls.filter((call) => call.method === "releaseLease")).toHaveLength(1); }); + it("does not send a second release for a lease whose release is already in flight", async () => { + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + let answerRelease!: (result: { leaseId: string }) => void; + client.releaseLeaseImpl = () => + new Promise<{ leaseId: string }>((resolve) => { + answerRelease = resolve; + }); + const session = new McpSession({ clock, connect: async () => client }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + // `close()` deliberately does not queue behind the tool-call serializer, so it can land + // while a `release_simulator` call is still waiting on the daemon. + const releasing = session.release({ leaseId: "lease-1" }); + await flushMicrotasks(); + const closing = session.close(); + answerRelease({ leaseId: "lease-1" }); + await expect(releasing).resolves.toMatchObject({ leaseId: "lease-1", released: true }); + await closing; + + expect(client.calls.filter((call) => call.method === "releaseLease")).toHaveLength(1); + }); + it("keeps renewing when a release fails, because the session still holds the device", async () => { const clock = new FakeClock(0); const client = new FakeSimlockClient(); diff --git a/src/mcp/session.ts b/src/mcp/session.ts index 7fc409056..1be770fc2 100644 --- a/src/mcp/session.ts +++ b/src/mcp/session.ts @@ -5,8 +5,13 @@ import { type LeaseRequestInput, type SimlockClient, } from "../client/index.js"; -import { startLeaseRenewal, type LeaseRenewal } from "../lease-policy/index.js"; -import type { Clock, TimerHandle } from "../ports/index.js"; +import { + awaitWithin, + RELEASE_TIMEOUT_MS, + startLeaseRenewal, + type LeaseRenewal, +} from "../lease-policy/index.js"; +import type { Clock } from "../ports/index.js"; import type { LeaseSimulatorInput, LeaseSimulatorOutput, @@ -17,15 +22,6 @@ import type { ReleaseSimulatorOutput, } from "./contracts.js"; -/** - * How long `close()` waits for its farewell `lease.release` before closing the connection - * anyway. The daemon is a local process answering a local socket, so this is not a latency - * budget -- it is the bound that keeps an unresponsive daemon from holding an MCP server's - * shutdown open forever. Exceeding it costs nothing but the wait: the lease then ends the way - * every unreleased lease ends, at its deadline. - */ -const RELEASE_ON_CLOSE_TIMEOUT_MS = 5_000; - export interface McpSessionOptions { /** * The `Clock` port (architecture rule 9): the session's renew timer and `close()`'s release @@ -132,6 +128,9 @@ export class McpSession { * holds a lease it obtained itself. */ #renewal: LeaseRenewal | undefined; + /** The lease a `release()` call has in flight right now, so `close()` never sends a second + * release for the same lease (it does not queue behind `#mutations`). */ + #releaseInFlight: string | undefined; constructor(options: McpSessionOptions) { this.#clock = options.clock; @@ -161,7 +160,16 @@ export class McpSession { return this.#mutate(async () => { this.#throwIfClosed(); const client = await this.#clientForUse(); - const result = await client.releaseLease(input); + // `close()` does not queue behind `#mutations` (see its doc comment), so it can read + // `#heldLeaseId` while this release is still in flight. This is how it knows the lease + // already has a release on the way and must not get a second one. + this.#releaseInFlight = input.leaseId; + let result; + try { + result = await client.releaseLease(input); + } finally { + this.#releaseInFlight = undefined; + } // Stopped only once the daemon has actually let the lease go. A release that fails // (anything but a dead connection) leaves the session still holding the device, and a // session that has stopped renewing a lease it still holds loses that device at the @@ -241,7 +249,8 @@ export class McpSession { this.#stopRenewal(); this.#unwireClient(); const client = this.#client; - const heldLeaseId = this.#heldLeaseId; + // A lease whose release is already in flight is not released again. + const heldLeaseId = this.#heldLeaseId === this.#releaseInFlight ? undefined : this.#heldLeaseId; this.#heldLeaseId = undefined; this.#client = undefined; if (this.#connecting !== undefined) { @@ -256,7 +265,12 @@ export class McpSession { async #endSession(client: SimlockClient, heldLeaseId: string | undefined): Promise { if (heldLeaseId !== undefined) { try { - await this.#withReleaseTimeout(client.releaseLease({ leaseId: heldLeaseId })); + await awaitWithin( + this.#clock, + RELEASE_TIMEOUT_MS, + client.releaseLease({ leaseId: heldLeaseId }), + `Timed out releasing lease ${heldLeaseId}`, + ); } catch { // Best-effort by design: the lease may already be gone (expired, force-released), the // connection may be dead, or the daemon may not answer. Shutdown continues either way, @@ -266,23 +280,6 @@ export class McpSession { await this.#closeClient(client); } - /** Rejects once `RELEASE_ON_CLOSE_TIMEOUT_MS` passes, so a dead-but-open socket cannot pin an - * MCP server open. The timer is always cancelled, so it never holds the process open itself. */ - async #withReleaseTimeout(release: Promise): Promise { - let timer: TimerHandle | undefined; - const expiry = new Promise((_resolve, reject) => { - timer = this.#clock.setTimer(RELEASE_ON_CLOSE_TIMEOUT_MS, () => { - timer = undefined; - reject(new McpSessionError("RELEASE_TIMEOUT", "Timed out releasing the session's lease")); - }); - }); - try { - await Promise.race([release, expiry]); - } finally { - if (timer !== undefined) this.#clock.cancel(timer); - } - } - /** * Starts (or restarts) the renew timer for the lease this session just obtained. The client * is captured deliberately: if that connection dies, the renewal fails and stops rather than From 9447a428da3cf168c305238063a34d8aed07d70a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 22:31:58 +0000 Subject: [PATCH 4/7] fix(lease-policy,cli,mcp): treat UNKNOWN_LEASE on renew as the end of the lease MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A renewal answered `UNKNOWN_LEASE` or `FORBIDDEN` is the daemon's final word, not a failed attempt: the record is gone, or was never this principal's. Retrying it printed the same rejection on every step of the ladder, gave up at the deadline, and left the holder alive -- with a doomed farewell release still to come. `startLeaseRenewal` now stops on those two codes and calls a new `onLeaseGone`; the CLI ends exactly as it does for a `lease-lost` push (exit 14, no release), and the MCP session clears its held lease and fans out a lease-lost notice, which is the only signal an agent gets when the lease expired while its connection was idle. Also from the same review: - `McpSession.release` marks the release in flight before `#clientForUse()`, which can reconnect: `close()` landing in that window no longer sends a second release. - a `renew` that throws synchronously is a failed attempt like any other, rather than a silent end swallowed by the unawaited tick. - SIGHUP is dropped again. It changes behaviour a user can see (`nohup simlock lease … &` would start dying on hangup) and MCP does not trap it, so the parity it claimed was not real. SIGINT/SIGTERM only, as before. - comment and test-description fixes: an attempt is bounded by a third of what is left of the TTL when it starts, not "the interval it was scheduled on"; `e2e/heartbeat-ttl.test.ts` says renew where it meant heartbeat, and drops a `lastHeartbeatAt > 0` assertion that never discriminated anything. Tests: the terminal answer per frontend and in the timer itself (both codes), a synchronously throwing renew, `awaitWithin`'s three outcomes on a fake clock, and a CLI farewell release the daemon never answers. Part of #114 Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- e2e/heartbeat-ttl.test.ts | 15 ++-- src/cli/index.test.ts | 62 +++++++++++++++- src/cli/index.ts | 42 ++++++----- src/lease-policy/index.test.ts | 125 ++++++++++++++++++++++++++++++++- src/lease-policy/index.ts | 59 ++++++++++++---- src/mcp/session.test.ts | 27 +++++++ src/mcp/session.ts | 46 +++++++++--- 7 files changed, 322 insertions(+), 54 deletions(-) diff --git a/e2e/heartbeat-ttl.test.ts b/e2e/heartbeat-ttl.test.ts index 5ac77aad8..b5ff0f1f0 100644 --- a/e2e/heartbeat-ttl.test.ts +++ b/e2e/heartbeat-ttl.test.ts @@ -7,7 +7,6 @@ interface LeaseRow { readonly id: string; readonly requesterId: string; readonly ttlDeadline: number; - readonly lastHeartbeatAt?: number; } async function leaseRows(env: Awaited>): Promise { @@ -16,7 +15,7 @@ async function leaseRows(env: Awaited>): Promise { +describe("sliding TTL and renewal", () => { it("refuses to start with a heartbeat interval that isn't at most backstop / 4, naming the key", async () => { const env = await withDaemon({ mode: "auto", @@ -48,8 +47,8 @@ describe("sliding TTL and heartbeat", () => { const env = await withDaemon({ // detachedTtlMs is pinned to the same value as heldTtlBackstopMs purely so the // detached lease's own (unrelated) TTL knob expires it on the timeline this - // test already waits on -- detached mode never heartbeats regardless of TTL, - // it just isn't naturally this short by default. + // test already waits on -- a detached lease has no holder renewing it regardless + // of TTL, it just isn't naturally this short by default. // // heartbeatIntervalMs is no longer what keeps the held leases alive (their holders // renew on their own timer, ADR 0004 §2); it stays here because the config validator @@ -112,7 +111,7 @@ describe("sliding TTL and heartbeat", () => { const detachedRow = rows.find((row) => row.id === detachedGrant.lease.id); return detachedRow === undefined; }, - { timeout: 15_000, label: "detached (non-heartbeating) lease expires at its TTL" }, + { timeout: 15_000, label: "detached (unrenewed) lease expires at its TTL" }, ); const rowsAfterExpiry = await leaseRows(env); @@ -127,9 +126,7 @@ describe("sliding TTL and heartbeat", () => { "CLI held lease should have survived past the detached lease's expiry", ).toBeDefined(); expect(mcpRow?.ttlDeadline).toBeGreaterThan(mcpLease.lease.ttlDeadline); - expect(mcpRow?.lastHeartbeatAt).toBeGreaterThan(0); expect(cliRow?.ttlDeadline).toBeGreaterThan(cliGrant.lease.ttlDeadline); - expect(cliRow?.lastHeartbeatAt).toBeGreaterThan(0); const statusResult = await mcp.client.callTool({ name: "lease_status", arguments: {} }); const statusExpiry = (statusResult.structuredContent as { ttlDeadline: number }).ttlDeadline; @@ -142,7 +139,7 @@ describe("sliding TTL and heartbeat", () => { entry.event === "lease.renewed" && (entry.payload as { leaseId?: string }).leaseId === mcpLease.lease.id, ).length, - "expected repeated lease.renewed events for the heartbeating MCP lease", + "expected repeated lease.renewed events for the renewing MCP lease", ).toBeGreaterThan(1); expect( recorded.filter( @@ -150,7 +147,7 @@ describe("sliding TTL and heartbeat", () => { entry.event === "lease.renewed" && (entry.payload as { leaseId?: string }).leaseId === cliGrant.lease.id, ).length, - "expected repeated lease.renewed events for the heartbeating CLI lease", + "expected repeated lease.renewed events for the renewing CLI lease", ).toBeGreaterThan(1); expect(recorded).toContainEqual( expect.objectContaining({ diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 52186c352..f6d4a9a7b 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -42,6 +42,7 @@ import type { TokenListOutput, } from "../simlock-client/client.js"; import { connectSimlockAdmin } from "../admin/index.js"; +import { RELEASE_TIMEOUT_MS } from "../lease-policy/index.js"; import { buildCliEnvironment, errorExitCode, @@ -1437,7 +1438,7 @@ describe("CLI: held-mode renew and release (ADR 0004 §2)", () => { expect(declared).toEqual([false, false]); }); - it.each(["SIGHUP", "SIGINT", "SIGTERM"] as const)( + it.each(["SIGINT", "SIGTERM"] as const)( "releases explicitly on %s (ADR 0004 §2's catchable signals)", async (signal) => { const output = outputCapture(); @@ -1505,6 +1506,65 @@ describe("CLI: held-mode renew and release (ADR 0004 §2)", () => { expect(released).toBe("lse_1"); }); + it("exits 14 without a farewell release when a renewal is answered UNKNOWN_LEASE", async () => { + const clock = new FakeClock(0); + const output = outputCapture(); + let released = false; + let renewals = 0; + const client = fakeClient({ + renewLease: () => { + renewals += 1; + return Promise.reject( + new SimlockError("UNKNOWN_LEASE", "domain", "no such lease", { leaseId: "lse_1" }), + ); + }, + releaseLease: () => { + released = true; + return Promise.resolve({ leaseId: "lse_1" }); + }, + }); + const runPromise = runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro"], + output.environmentWith({ clock, connectAdmin: async () => client }), + ); + await settle(); + clock.advance(20_000); + + // The daemon's answer is final: this ends the same way the lease-lost push does, rather + // than repeating the rejection until the deadline and then sitting alive. + expect(await runPromise).toBe(14); + expect(released, "asking again would only raise UNKNOWN_LEASE").toBe(false); + expect(renewals).toBe(1); + expect(clock.pendingTimerCount).toBe(0); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "{}")).toEqual({ + error: { code: "UNKNOWN_LEASE", message: "no such lease" }, + }); + }); + + it("gives up on a farewell release the daemon never answers, instead of hanging", async () => { + const clock = new FakeClock(0); + const output = outputCapture(); + const signals = new EventEmitter(); + const client = fakeClient({ releaseLease: () => new Promise(() => {}) }); + const runPromise = runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro"], + output.environmentWith({ + clock, + connectAdmin: async () => client, + signals: signals as unknown as CliEnvironment["signals"], + }), + ); + await settle(); + signals.emit("SIGINT"); + await settle(); + + clock.advance(RELEASE_TIMEOUT_MS); + + expect(await runPromise).toBe(0); + expect(output.stderr).toContain("Timed out releasing lease lse_1"); + expect(clock.pendingTimerCount).toBe(0); + }); + it("still releases the lease when printing the grant throws (--export-env with a bad key)", async () => { const clock = new FakeClock(0); const output = outputCapture(); diff --git a/src/cli/index.ts b/src/cli/index.ts index e215cd674..6ed98af55 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -95,18 +95,9 @@ interface Output { write(value: string): unknown; } -/** - * ADR 0004 §2's "a catchable signal", enumerated: the two a holder is asked to stop with, plus - * `SIGHUP` -- what a closing terminal sends, and the likeliest way a backgrounded holder dies - * short of `SIGKILL`. All three take the same path: stop renewing, release, exit. - */ -const TERMINATION_SIGNALS = ["SIGHUP", "SIGINT", "SIGTERM"] as const; - -type TerminationSignal = (typeof TERMINATION_SIGNALS)[number]; - interface Signals { - on(signal: TerminationSignal, listener: () => void): unknown; - off(signal: TerminationSignal, listener: () => void): unknown; + on(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown; + off(signal: "SIGINT" | "SIGTERM", listener: () => void): unknown; } type McpStdioRunner = () => Promise; @@ -742,11 +733,16 @@ async function runLease( const leaseLostSignal = new Promise((resolve) => { notifyLeaseLost = resolve; }); + /** The lease ended without this process asking: stop waiting, skip the release it can no + * longer perform, and exit with the lost-lease code. */ + const markLeaseLost = (): void => { + leaseLost = true; + notifyLeaseLost?.(); + }; const offLeaseLost = client.onLeaseLost((push) => { if (push.leaseId !== ourLeaseId) return; environment.stderr.write(`${JSON.stringify({ push: "lease-lost", ...push })}\n`); - leaseLost = true; - notifyLeaseLost?.(); + markLeaseLost(); }); const offUnhealthy = client.onDeviceUnhealthy((push) => { environment.stderr.write(`${JSON.stringify({ push: "device-unhealthy", ...push })}\n`); @@ -826,11 +822,17 @@ async function runLease( leaseId: grant.lease.id, ttlDeadline: grant.lease.ttlDeadline, renew: (leaseId) => client.renewLease({ leaseId }), - // A failed attempt is retried until the lease's deadline (see `startLeaseRenewal`), so - // this is diagnostic output on the same structured stderr channel as a failed release, - // not an exit condition: the lease-lost push or the daemon's own expiry is what decides - // when this process stops holding. + // A retryable attempt failed (see `startLeaseRenewal`): diagnostic output on the same + // structured stderr channel as a failed release, and not an exit condition -- the lease + // is still this process's until something says otherwise. onError: (error) => writeError(environment, error), + // Something did say otherwise: the daemon answered that this lease is gone or not ours. + // Same ending as the `lease-lost` push -- exit 14, and no farewell release for a lease + // that would only answer UNKNOWN_LEASE again. + onLeaseGone: (error) => { + writeError(environment, error); + markLeaseLost(); + }, }); await Promise.race([termination.settled, leaseLostSignal]); // The daemon already released a lost lease; `releaseHeldLease` skips it for that reason. @@ -1574,10 +1576,12 @@ function waitForTermination( resolve(); }; detach = () => { - for (const signal of TERMINATION_SIGNALS) signals.off(signal, finish); + signals.off("SIGINT", finish); + signals.off("SIGTERM", finish); watchHandle?.stop(); }; - for (const signal of TERMINATION_SIGNALS) signals.on(signal, finish); + signals.on("SIGINT", finish); + signals.on("SIGTERM", finish); watchHandle = parentWatch !== undefined && parentPid !== undefined && parentPid > 0 ? parentWatch.watch(parentPid, finish) diff --git a/src/lease-policy/index.test.ts b/src/lease-policy/index.test.ts index 0352e8c75..5cebf1074 100644 --- a/src/lease-policy/index.test.ts +++ b/src/lease-policy/index.test.ts @@ -5,14 +5,22 @@ */ import { describe, expect, it } from "vitest"; +import { SimlockError } from "../contract/index.js"; import { FakeClock } from "../ports/index.js"; -import { startLeaseRenewal } from "./index.js"; +import { awaitWithin, RELEASE_TIMEOUT_MS, startLeaseRenewal } from "./index.js"; /** Lets the awaited `renew` call settle; the fake clock never moves on its own. */ async function flushMicrotasks(times = 10): Promise { for (let index = 0; index < times; index += 1) await Promise.resolve(); } +/** The daemon's two "this lease is not yours to renew" answers, with their real detail shapes. */ +function leaseGoneError(code: "UNKNOWN_LEASE" | "FORBIDDEN"): SimlockError { + return code === "UNKNOWN_LEASE" + ? new SimlockError("UNKNOWN_LEASE", "domain", "no such lease", { leaseId: "lse_1" }) + : new SimlockError("FORBIDDEN", "protocol", "not your lease", {}); +} + describe("startLeaseRenewal", () => { it("renews at a third of the remaining TTL and reschedules off each renewal's own deadline", async () => { const clock = new FakeClock(1_000); @@ -106,6 +114,68 @@ describe("startLeaseRenewal", () => { expect(calls).toBe(1); }); + it.each(["UNKNOWN_LEASE", "FORBIDDEN"] as const)( + "treats %s as the end of the lease, not a failed attempt", + async (code) => { + const clock = new FakeClock(0); + const gone: unknown[] = []; + const errors: unknown[] = []; + let calls = 0; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + onError: (error) => errors.push(error), + onLeaseGone: (error) => gone.push(error), + renew: () => { + calls += 1; + return Promise.reject(leaseGoneError(code)); + }, + ttlDeadline: 30_000, + }); + + clock.advance(10_000); + await flushMicrotasks(); + + expect(gone).toHaveLength(1); + expect(gone[0]).toMatchObject({ code }); + expect(errors, "a lease that is over is not a retryable failure").toEqual([]); + expect(clock.pendingTimerCount).toBe(0); + + clock.advance(600_000); + await flushMicrotasks(); + expect(calls, "and it is never retried").toBe(1); + }, + ); + + it("reports and retries a renew that throws synchronously", async () => { + const clock = new FakeClock(0); + const errors: unknown[] = []; + const attemptsAt: number[] = []; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + onError: (error) => errors.push(error), + renew: () => { + attemptsAt.push(clock.now()); + // A client that validates its input before it ever reaches the wire throws here + // rather than rejecting; that must not escape into the unawaited tick. + if (attemptsAt.length === 1) throw new Error("BAD_REQUEST"); + return Promise.resolve({ ttlDeadline: clock.now() + 3_000 }); + }, + ttlDeadline: 3_000, + }); + + clock.advance(1_000); + await flushMicrotasks(); + expect(attemptsAt).toEqual([1_000]); + expect((errors[0] as Error).message).toBe("BAD_REQUEST"); + + clock.advance(666); + await flushMicrotasks(); + expect(attemptsAt).toEqual([1_000, 1_666]); + expect(clock.pendingTimerCount).toBe(1); + }); + it("retries a failed renewal while the lease can still be saved, and reports every attempt", async () => { const clock = new FakeClock(0); const failure = new Error("INTERNAL"); @@ -244,8 +314,8 @@ describe("startLeaseRenewal", () => { expect(calls).toBe(1); expect(errors).toEqual([]); - // The attempt is bounded by the interval it was scheduled on (2_000ms of the 6_000ms - // left), so it does not swallow the rest of the TTL in silence. + // The attempt is bounded by a third of what is left of the TTL when it starts (2_000ms of + // the 6_000ms remaining at 3_000), so it does not swallow the rest of the TTL in silence. clock.advance(2_000); await flushMicrotasks(); expect(errors).toHaveLength(1); @@ -313,3 +383,52 @@ describe("startLeaseRenewal", () => { expect(renewedAt).toEqual([1_250]); }); }); + +/** + * The bound both frontends put on their farewell `lease.release`: an unresponsive daemon may + * cost a holder the wait, never its exit. + */ +describe("awaitWithin", () => { + it("resolves with the work and leaves no timer behind", async () => { + const clock = new FakeClock(0); + + await expect( + awaitWithin(clock, RELEASE_TIMEOUT_MS, Promise.resolve({ leaseId: "lse_1" }), "too slow"), + ).resolves.toEqual({ leaseId: "lse_1" }); + // A live timer here would keep a real process alive for the whole bound after the work + // it was guarding had already finished. + expect(clock.pendingTimerCount).toBe(0); + }); + + it("rejects with the given message once the bound passes, and cleans up after itself", async () => { + const clock = new FakeClock(0); + const bounded = awaitWithin( + clock, + RELEASE_TIMEOUT_MS, + new Promise(() => {}), + "Timed out releasing lease lse_1", + ); + await flushMicrotasks(); + expect(clock.pendingTimerCount).toBe(1); + + clock.advance(RELEASE_TIMEOUT_MS - 1); + await flushMicrotasks(); + expect(clock.pendingTimerCount).toBe(1); + + clock.advance(1); + await expect(bounded).rejects.toThrow("Timed out releasing lease lse_1"); + expect(clock.pendingTimerCount).toBe(0); + }); + + it("propagates the work's own rejection rather than waiting out the bound", async () => { + const clock = new FakeClock(0); + const failure = new SimlockError("UNKNOWN_LEASE", "domain", "no such lease", { + leaseId: "lse_1", + }); + + await expect( + awaitWithin(clock, RELEASE_TIMEOUT_MS, Promise.reject(failure), "too slow"), + ).rejects.toBe(failure); + expect(clock.pendingTimerCount).toBe(0); + }); +}); diff --git a/src/lease-policy/index.ts b/src/lease-policy/index.ts index 4d64df847..cf1ac46fd 100644 --- a/src/lease-policy/index.ts +++ b/src/lease-policy/index.ts @@ -17,6 +17,7 @@ * every renewal since), never from a TTL config value: a client does not have the daemon's * config, and the daemon is free to hand back a shorter deadline than the one asked for. */ +import { isSimlockError } from "../contract/index.js"; import type { Clock, TimerHandle } from "../ports/index.js"; /** ADR 0004 §2's "one third of the TTL". */ @@ -78,10 +79,19 @@ export interface LeaseRenewalOptions { /** Calls `lease.renew` for this lease -- `client.renewLease({ leaseId })`, in practice. */ readonly renew: (leaseId: string) => Promise; /** - * Reports every failed attempt, and the failure that finally ends renewal. Never called - * after `stop()`. + * Reports every failed attempt that is worth retrying, and the failure that finally ends + * renewal. Never called after `stop()`, and never for the terminal answers `onLeaseGone` + * covers. */ readonly onError?: (error: unknown) => void; + /** + * The lease is over: the daemon answered that it does not exist (`UNKNOWN_LEASE`) or is not + * this principal's (`FORBIDDEN`). Renewal has already stopped by the time this runs, and + * retrying would only repeat the same answer -- so a holder should treat this exactly like + * the `lease-lost` push (ADR 0003 §8) it may or may not also receive: stop holding, and do + * not try to release what is no longer there. Called at most once. + */ + readonly onLeaseGone?: (error: unknown) => void; } export interface LeaseRenewal { @@ -103,6 +113,17 @@ type Attempt = | { readonly ok: true; readonly renewed: RenewedLease } | { readonly ok: false; readonly error: unknown }; +/** + * A rejection that answers "this lease is not yours to renew" rather than "that attempt did + * not work". Both codes are the daemon's final word: `UNKNOWN_LEASE` means the record is gone + * (expired, released, force-released), `FORBIDDEN` that it belongs to another principal + * (`ownsLease` in `src/contract/operations.ts`). Retrying either just prints the same answer + * until the deadline. + */ +function isLeaseGone(error: unknown): boolean { + return isSimlockError(error) && (error.code === "UNKNOWN_LEASE" || error.code === "FORBIDDEN"); +} + /** * Starts renewing `leaseId` at a third of the remaining TTL, rescheduling off each renewal's * own returned deadline, until `stop()`. @@ -116,13 +137,16 @@ type Attempt = * `lease-lost` handler (ADR 0003 §10), which is the signal that actually means "this lease is * over"; the retries in between are cheap and bounded by the deadline. * - * Each attempt is bounded by the same interval it was scheduled on, so a daemon that accepts - * `lease.renew` and never answers costs one interval rather than the whole lease: the wire has - * no request timeout of its own, and an abandoned request cannot slide the deadline anywhere - * but forward. + * Each attempt is bounded by a third of what is left of the TTL when it starts, so a daemon + * that accepts `lease.renew` and never answers costs one interval rather than the whole lease: + * the wire has no request timeout of its own, and an abandoned request cannot slide the + * deadline anywhere but forward. + * + * A daemon answering `UNKNOWN_LEASE` or `FORBIDDEN` is not a failed attempt at all -- the lease + * is over, or was never this holder's -- so renewal stops at once and `onLeaseGone` says so. */ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { - const { clock, leaseId, onError, renew } = options; + const { clock, leaseId, onError, onLeaseGone, renew } = options; /** The last deadline the daemon actually gave us -- the only input to the cadence. */ let deadline = options.ttlDeadline; /** Whichever timer is armed right now: the wait between renewals, or an attempt's bound. */ @@ -136,15 +160,16 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { }; /** Isolated: a holder that cannot report a failure must still keep holding. */ - const report = (error: unknown): void => { - if (onError === undefined) return; + const notify = (listener: ((error: unknown) => void) | undefined, error: unknown): void => { + if (listener === undefined) return; try { - onError(error); + listener(error); } catch { // A `stderr` that throws (a closed pipe, say) must not take the release path down with // it -- see the `void tick()` below, which nothing awaits. } }; + const report = (error: unknown): void => notify(onError, error); const schedule = (): void => { if (stopped) return; @@ -156,9 +181,12 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { }); }; - /** One renewal attempt, bounded by the interval it was scheduled on. */ + /** One renewal attempt, bounded by a third of what is left of the TTL when it starts. */ const attemptRenew = async (): Promise => { - const request = renew(leaseId); + // `Promise.resolve().then` rather than a bare call: a `renew` that throws *synchronously* + // (a client that rejects a malformed input before it ever reaches the wire) is a failed + // attempt like any other, not something that should escape into the unawaited `tick()`. + const request = Promise.resolve().then(() => renew(leaseId)); // An abandoned request still reaches the daemon: if it succeeds after this attempt has // been given up on, its deadline is real and worth keeping -- discarding it would let the // give-up test below fire against a deadline the daemon has already moved. (It also keeps @@ -195,6 +223,13 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { if (stopped) return; if (!attempt.ok) { + if (isLeaseGone(attempt.error)) { + // Terminal, not transient: this lease is over, and the holder needs to hear that once + // rather than read the same rejection on every retry until the deadline. + stopped = true; + notify(onLeaseGone, attempt.error); + return; + } report(attempt.error); // Out of runway: the lease is gone (or about to be), and another attempt would only // produce another error. Reported separately from the attempt that failed, because diff --git a/src/mcp/session.test.ts b/src/mcp/session.test.ts index 7a58bce90..a22ae205d 100644 --- a/src/mcp/session.test.ts +++ b/src/mcp/session.test.ts @@ -394,6 +394,33 @@ describe("McpSession", () => { await session.close(); }); + it("reports a lease the daemon says is gone as lease-lost, and releases nothing on close", async () => { + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + client.renewLeaseImpl = () => + Promise.reject( + new SimlockError("UNKNOWN_LEASE", "domain", "no such lease", { leaseId: "lease-1" }), + ); + const session = new McpSession({ clock, connect: async () => client }); + const notices: unknown[] = []; + session.onLeaseLost((notice) => notices.push(notice)); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + // A lease that expired while this session was idle may never produce a push -- the + // renewal's own answer is what tells the agent. + clock.advance(4_115); + await flushMicrotasks(); + expect(notices).toEqual([ + { deviceId: "device-1", leaseId: "lease-1", reason: "renew-rejected" }, + ]); + expect(clock.pendingTimerCount).toBe(0); + + await session.close(); + expect(client.calls.filter((call) => call.method === "releaseLease")).toEqual([]); + expect(client.calls.filter((call) => call.method === "renewLease")).toHaveLength(1); + }); + it("stops renewing a lease that ended elsewhere", async () => { const clock = new FakeClock(0); const client = new FakeSimlockClient(); diff --git a/src/mcp/session.ts b/src/mcp/session.ts index 1be770fc2..07a9f6fd8 100644 --- a/src/mcp/session.ts +++ b/src/mcp/session.ts @@ -2,6 +2,7 @@ import { isSimlockError, SimlockError, type LeaseProgress, + type LeaseRecord, type LeaseRequestInput, type SimlockClient, } from "../client/index.js"; @@ -151,7 +152,7 @@ export class McpSession { ...(signal === undefined ? {} : { signal }), }); this.#heldLeaseId = grant.lease.id; - this.#startRenewal(client, grant.lease.id, grant.lease.ttlDeadline); + this.#startRenewal(client, grant.lease); return grant; }); } @@ -159,13 +160,14 @@ export class McpSession { release(input: ReleaseSimulatorInput): Promise { return this.#mutate(async () => { this.#throwIfClosed(); - const client = await this.#clientForUse(); - // `close()` does not queue behind `#mutations` (see its doc comment), so it can read - // `#heldLeaseId` while this release is still in flight. This is how it knows the lease - // already has a release on the way and must not get a second one. + // Marked before `#clientForUse()`, not after: that call can reconnect, which takes as + // long as a daemon launch, and `close()` does not queue behind `#mutations` (see its doc + // comment). This is how it knows the lease already has a release on the way -- from the + // moment this call commits to sending one -- and must not get a second one. this.#releaseInFlight = input.leaseId; let result; try { + const client = await this.#clientForUse(); result = await client.releaseLease(input); } finally { this.#releaseInFlight = undefined; @@ -286,19 +288,43 @@ export class McpSession { * quietly reconnecting behind the tool surface -- reconnect stays a decision the next tool * call makes (`#clientForUse`). */ - #startRenewal(client: SimlockClient, leaseId: string, ttlDeadline: number): void { + #startRenewal(client: SimlockClient, lease: LeaseRecord): void { this.#stopRenewal(); // No `onError`: this frontend owns stdout (it is the protocol) and has no side channel a - // failed renewal could be written to. Every failure that matters to the agent surfaces as - // the `lease-lost` notice that follows it, or as the next tool call's own error. + // retryable failure could be written to. What the agent has to know is that the lease is + // over, and that arrives as the `lease-lost` notice `onLeaseGone` raises below (or as the + // daemon's own push, whichever comes first) rather than as a stream of attempt failures. this.#renewal = startLeaseRenewal({ clock: this.#clock, - leaseId, + leaseId: lease.id, + onLeaseGone: () => { + // The daemon says this lease is gone or not ours: the same ending as the push, which + // may never arrive (a lease that expired while this connection was away has nothing + // left to push about). + this.#reportLeaseLost({ + deviceId: lease.deviceId, + leaseId: lease.id, + reason: "renew-rejected", + }); + }, renew: (id) => client.renewLease({ leaseId: id }), - ttlDeadline, + ttlDeadline: lease.ttlDeadline, }); } + /** + * This session's own lease has ended, as told by a renewal rather than by a push: drop the + * timer, forget the id, and deliver the same notice a push would have. (The push relay in + * `#wireClient` stays separate because it forwards every lease-lost push to listeners, + * including ones for leases this session never held; this only ever fires for its own.) + */ + #reportLeaseLost(notice: LeaseLostNotice): void { + if (notice.leaseId !== this.#heldLeaseId) return; + this.#stopRenewal(); + this.#heldLeaseId = undefined; + for (const listener of this.#leaseLostListeners) listener(notice); + } + #stopRenewal(): void { this.#renewal?.stop(); this.#renewal = undefined; From 5c7ae4860876f1b50587259b86990fe4efe7f194 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 23:10:12 +0000 Subject: [PATCH 5/7] fix(mcp): close a session without leaking a renew timer or losing the release Two ways `close()` could go wrong while a tool call was in flight, both found by review: - a `lease()` whose grant landed after `close()` set `#heldLeaseId` and armed a renew timer on a session that was already gone. Nothing stopped it again, and since the MCP runner never calls `process.exit`, `simlock mcp` could sit alive renewing a lease on a dead client until the backstop. A grant that arrives after the session closed is now handed straight back (bounded, best-effort) and the call fails `SESSION_CLOSED`. - the release-in-flight guard added last round turned "two releases" into none: `close()` skipped its farewell release because a tool call had one on the way, then closed the wire, which rejected that very request. The guard is gone -- `close()` always sends its own release, and a duplicate costs one `UNKNOWN_LEASE` it already swallows. Under PR A the daemon's release-on-close hid this; PR B removes that crutch. Also: - lease-lost notices are deduplicated by lease id, so a lease that a renewal found gone and the daemon then pushed is one ending, not two. - the CLI writes the same `{"push":"lease-lost",...,"reason":"renew-rejected"}` stderr line for a renewal the daemon rejects as it does for the push, with the error line after it as detail: a script tailing for `push: "lease-lost"` sees both ways of losing a lease. - an abandoned renewal's late answer may only move the deadline while nothing newer has been answered, which is what its own comment claimed; a fresh answer stays authoritative in both directions. - the module doc says what deriving the cadence from `ttlDeadline - now()` assumes (one clock, true on the unix socket) and how PR B's stored `ttlMs` turns it into `ttlMs / 3` with the deadline as a bound. - the two dead `termination !== undefined` conditions collapse to one, and `mcp/connect.ts`'s now-inert `heartbeat` option is labelled for PR B. Part of #114 Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- src/cli/index.test.ts | 15 ++++- src/cli/index.ts | 21 +++++-- src/lease-policy/index.test.ts | 42 ++++++++++++++ src/lease-policy/index.ts | 33 +++++++++-- src/mcp/connect.ts | 2 + src/mcp/session.test.ts | 101 ++++++++++++++++++++++++++++++--- src/mcp/session.ts | 91 +++++++++++++++++------------ 7 files changed, 249 insertions(+), 56 deletions(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index f6d4a9a7b..58f3fc3ae 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1536,7 +1536,20 @@ describe("CLI: held-mode renew and release (ADR 0004 §2)", () => { expect(released, "asking again would only raise UNKNOWN_LEASE").toBe(false); expect(renewals).toBe(1); expect(clock.pendingTimerCount).toBe(0); - expect(JSON.parse(output.stderr.trim().split("\n").at(-1) ?? "{}")).toEqual({ + + // The same stderr line the push path writes, so a script tailing for `push: "lease-lost"` + // sees this way of losing a lease too, with the error line after it as the detail. + const lines = output.stderr + .trim() + .split("\n") + .map((line) => JSON.parse(line) as Record); + expect(lines).toContainEqual({ + push: "lease-lost", + deviceId: "dev_1", + leaseId: "lse_1", + reason: "renew-rejected", + }); + expect(lines.at(-1)).toEqual({ error: { code: "UNKNOWN_LEASE", message: "no such lease" }, }); }); diff --git a/src/cli/index.ts b/src/cli/index.ts index 6ed98af55..f0f7444dd 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -804,7 +804,7 @@ async function runLease( ); ourLeaseId = grant.lease.id; // Owed from here on, whatever happens next -- see `releaseHeldLease`. - if (!detached && termination !== undefined) heldLeaseId = grant.lease.id; + if (!detached) heldLeaseId = grant.lease.id; // ADR §5: "simlock lease output includes the resolved role" -- the one field this CLI // adds on top of the contract's `LeaseGrant` shape, everything else passed through as-is. const result = { ...grant, role: client.role }; @@ -812,11 +812,12 @@ async function runLease( // changes what stdout carries, never how long the lease lives. if (values["export-env"] === true) writeExportEnv(environment, result); else writeResult(environment, result); - if (detached || termination === undefined) return 0; + // `--detach` is the only invocation without a termination watch: it prints and exits, + // with no timer and no release, exactly as it did before ADR 0004. + if (termination === undefined) return 0; // ADR 0004 §2: what a held holder does while alive is renew on a timer at a third of the // TTL -- computed from the deadline the daemon just returned, not from a config value this - // process does not have. `--detach` returned above: it stays exactly as it was, printing - // and exiting with no timer at all. + // process does not have. renewal = startLeaseRenewal({ clock: environment.clock, leaseId: grant.lease.id, @@ -828,8 +829,18 @@ async function runLease( onError: (error) => writeError(environment, error), // Something did say otherwise: the daemon answered that this lease is gone or not ours. // Same ending as the `lease-lost` push -- exit 14, and no farewell release for a lease - // that would only answer UNKNOWN_LEASE again. + // that would only answer UNKNOWN_LEASE again -- and the same stderr line, so a script + // watching for `push: "lease-lost"` sees this way of losing a lease too. The error line + // follows it as the detail of why. onLeaseGone: (error) => { + environment.stderr.write( + `${JSON.stringify({ + push: "lease-lost", + deviceId: grant.lease.deviceId, + leaseId: grant.lease.id, + reason: "renew-rejected", + })}\n`, + ); writeError(environment, error); markLeaseLost(); }, diff --git a/src/lease-policy/index.test.ts b/src/lease-policy/index.test.ts index 5cebf1074..46b471c1d 100644 --- a/src/lease-policy/index.test.ts +++ b/src/lease-policy/index.test.ts @@ -326,6 +326,48 @@ describe("startLeaseRenewal", () => { expect(calls).toBe(2); }); + it("ignores an abandoned renewal's answer once a newer one has come back", async () => { + const clock = new FakeClock(0); + const errors: Error[] = []; + let answerFirst!: (renewed: { ttlDeadline: number }) => void; + let attempts = 0; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + onError: (error) => errors.push(error as Error), + renew: () => { + attempts += 1; + if (attempts === 1) + return new Promise<{ ttlDeadline: number }>((resolve) => { + answerFirst = resolve; + }); + // The second attempt is the daemon's newest word: 3_000ms from now. + if (attempts === 2) return Promise.resolve({ ttlDeadline: clock.now() + 3_000 }); + return Promise.reject(new Error("INTERNAL")); + }, + ttlDeadline: 3_000, + }); + + clock.advance(1_000); // attempt 1, abandoned at its bound below + await flushMicrotasks(); + clock.advance(666); + await flushMicrotasks(); + clock.advance(444); // attempt 2 at 2_110, answering 5_110 + await flushMicrotasks(); + expect(attempts).toBe(2); + + // Attempt 1 finally answers, with a far longer deadline -- but it is older than attempt 2, + // whose answer is the daemon's current word. Adopting it would have this holder renewing + // towards a deadline the daemon never promised. + answerFirst({ ttlDeadline: 999_999 }); + await flushMicrotasks(); + + clock.advance(60_000); + await flushMicrotasks(); + expect(clock.pendingTimerCount, "renewal works towards 5_110, so it gives up past it").toBe(0); + expect(errors.at(-1)?.message).toContain("Gave up renewing lease lse_1"); + }); + it("never reports a failure that arrives after stop()", async () => { const clock = new FakeClock(0); let rejectRenew!: (error: Error) => void; diff --git a/src/lease-policy/index.ts b/src/lease-policy/index.ts index cf1ac46fd..a794f2ded 100644 --- a/src/lease-policy/index.ts +++ b/src/lease-policy/index.ts @@ -16,6 +16,17 @@ * The cadence is computed only from the deadline the daemon returned with the grant (and with * every renewal since), never from a TTL config value: a client does not have the daemon's * config, and the daemon is free to hand back a shorter deadline than the one asked for. + * + * Two things follow from deriving the interval as `ttlDeadline - clock.now()`: + * + * - it assumes the daemon and this client read the same wall clock. True on the unix socket, + * where they are processes on one machine, and the reason `ttlDeadline` is usable as-is + * today. It is not true across a network hop, where a client's clock may sit minutes from + * the daemon's and this arithmetic would renew far too early or far too late. + * - the fix for that is ADR 0004's own: once a lease record carries `ttlMs` (PR B), the + * cadence becomes `ttlMs / 3` -- a duration, which needs no shared epoch -- and the deadline + * is left as what it really is, a bound to stop renewing at rather than a clock to schedule + * from. This module is where that change lands; nothing above it has to move. */ import { isSimlockError } from "../contract/index.js"; import type { Clock, TimerHandle } from "../ports/index.js"; @@ -152,6 +163,10 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { /** Whichever timer is armed right now: the wait between renewals, or an attempt's bound. */ let timer: TimerHandle | undefined; let stopped = false; + /** Attempts are numbered so a late answer can tell whether anything newer has been answered + * since (attempts never overlap: one is in flight at a time, by construction). */ + let attempts = 0; + let newestAnswered = 0; const cancelTimer = (): void => { if (timer === undefined) return; @@ -183,6 +198,8 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { /** One renewal attempt, bounded by a third of what is left of the TTL when it starts. */ const attemptRenew = async (): Promise => { + attempts += 1; + const attemptId = attempts; // `Promise.resolve().then` rather than a bare call: a `renew` that throws *synchronously* // (a client that rejects a malformed input before it ever reaches the wire) is a failed // attempt like any other, not something that should escape into the unawaited `tick()`. @@ -193,9 +210,11 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { // a late rejection from surfacing as an unhandled rejection.) request.then( (renewed) => { - // `Math.max`, not a plain assignment: this answer belongs to a request older than - // whatever has happened since, so it may only ever push the deadline forward. - if (!stopped) deadline = Math.max(deadline, renewed.ttlDeadline); + // Only while no *newer* attempt has been answered, and then only forward: this answer + // is older than anything that has happened since, so it may raise a deadline nobody + // has since improved on, and never overwrite a fresher one. + if (stopped || attemptId <= newestAnswered) return; + deadline = Math.max(deadline, renewed.ttlDeadline); }, () => undefined, ); @@ -244,6 +263,9 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { return; } + // This attempt is now the newest answer there is, so no request older than it may move the + // deadline again (see `attemptRenew`). + newestAnswered = attempts; if (attempt.renewed.ttlDeadline <= clock.now()) { // A deadline that is not in the future cannot be renewed towards -- scheduling off it // would be a hot loop against a lease that is already over. @@ -251,8 +273,9 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { report(new Error(`Lease ${leaseId} was renewed to a deadline that has already passed`)); return; } - // The daemon's answer is authoritative, in both directions: it may hand back a shorter - // deadline than the one that was asked for, and the cadence follows it. + // The daemon's answer is authoritative, in both directions: it may hand back a *shorter* + // deadline than the one that was asked for -- a lowered `lease.heldTtlBackstopMs`, a + // `ttlMs` it clamped -- and the cadence follows it rather than an older, longer belief. deadline = attempt.renewed.ttlDeadline; schedule(); }; diff --git a/src/mcp/connect.ts b/src/mcp/connect.ts index bc4994008..4e32392c5 100644 --- a/src/mcp/connect.ts +++ b/src/mcp/connect.ts @@ -18,6 +18,8 @@ import { IpcError, type Clock, type DaemonLauncher, type IpcConnector } from ".. export interface ConnectWithAutoLaunchOptions { readonly clock: Clock; + /** Dead as of ADR 0004 §4 -- nothing passes `true` any more, and the capability itself goes + * away with the daemon's push in PR B, which removes this option with it. */ readonly heartbeat?: boolean; readonly ipc: IpcConnector; readonly launcher: DaemonLauncher; diff --git a/src/mcp/session.test.ts b/src/mcp/session.test.ts index a22ae205d..f86d7419f 100644 --- a/src/mcp/session.test.ts +++ b/src/mcp/session.test.ts @@ -335,28 +335,87 @@ describe("McpSession", () => { expect(client.calls.filter((call) => call.method === "releaseLease")).toHaveLength(1); }); - it("does not send a second release for a lease whose release is already in flight", async () => { + it("still releases on close when a tool call's own release is in flight and dies with the wire", async () => { const clock = new FakeClock(0); const client = new FakeSimlockClient(); client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); - let answerRelease!: (result: { leaseId: string }) => void; + const pending: Array<{ + resolve: (result: { leaseId: string }) => void; + reject: (error: Error) => void; + settled: boolean; + }> = []; client.releaseLeaseImpl = () => - new Promise<{ leaseId: string }>((resolve) => { - answerRelease = resolve; + new Promise<{ leaseId: string }>((resolve, reject) => { + const entry = { + reject: (error: Error) => { + entry.settled = true; + reject(error); + }, + resolve: (result: { leaseId: string }) => { + entry.settled = true; + resolve(result); + }, + settled: false, + }; + pending.push(entry); }); + // What the real wire does when the connection closes: every request still waiting for an + // answer rejects (ADR 0003 §10). + client.onConnectionLost(() => { + for (const entry of pending) { + if (!entry.settled) + entry.reject(new SimlockError("DAEMON_CONNECTION_LOST", "transport", "gone", {})); + } + }); const session = new McpSession({ clock, connect: async () => client }); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); // `close()` deliberately does not queue behind the tool-call serializer, so it can land - // while a `release_simulator` call is still waiting on the daemon. + // while a `release_simulator` call is still waiting on the daemon. Skipping the farewell + // release because that one exists would mean *no* release at all: the wire kills it a + // moment later. const releasing = session.release({ leaseId: "lease-1" }); await flushMicrotasks(); const closing = session.close(); - answerRelease({ leaseId: "lease-1" }); - await expect(releasing).resolves.toMatchObject({ leaseId: "lease-1", released: true }); + await flushMicrotasks(); + expect(client.calls.filter((call) => call.method === "releaseLease")).toHaveLength(2); + + pending[1]?.resolve({ leaseId: "lease-1" }); // the daemon answers the farewell release await closing; + await expect(releasing).rejects.toMatchObject({ code: "DAEMON_CONNECTION_LOST" }); - expect(client.calls.filter((call) => call.method === "releaseLease")).toHaveLength(1); + // Exactly one release actually completed -- and the lease really is released. + expect(pending.filter((entry) => entry.settled)).toHaveLength(2); + expect(pending[0]?.settled).toBe(true); // rejected with the wire + expect(client.closeCalls).toBe(1); + }); + + it("releases a grant that lands after the session closed, and arms no timer for it", async () => { + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + let answerGrant!: (grant: ReturnType) => void; + client.requestLeaseImpl = () => + new Promise((resolve) => { + answerGrant = resolve; + }); + client.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); + const session = new McpSession({ clock, connect: async () => client }); + + const leasing = session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + await flushMicrotasks(); + const closing = session.close(); + await closing; + + // The daemon finished provisioning after the session ended: the device goes straight back + // rather than being renewed by a session that no longer exists. + answerGrant(sampleGrant({ leaseId: "lease-1" })); + await expect(leasing).rejects.toMatchObject({ code: "SESSION_CLOSED" }); + + expect(client.calls.filter((call) => call.method === "releaseLease")).toEqual([ + { input: { leaseId: "lease-1" }, method: "releaseLease" }, + ]); + expect(client.calls.filter((call) => call.method === "renewLease")).toEqual([]); + expect(clock.pendingTimerCount, "a closed session must leave no timer behind").toBe(0); }); it("keeps renewing when a release fails, because the session still holds the device", async () => { @@ -421,6 +480,32 @@ describe("McpSession", () => { expect(client.calls.filter((call) => call.method === "renewLease")).toHaveLength(1); }); + it("announces one ending once, even when the renewal and the daemon both report it", async () => { + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + client.renewLeaseImpl = () => + Promise.reject( + new SimlockError("UNKNOWN_LEASE", "domain", "no such lease", { leaseId: "lease-1" }), + ); + const session = new McpSession({ clock, connect: async () => client }); + const notices: unknown[] = []; + session.onLeaseLost((notice) => notices.push(notice)); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + clock.advance(4_115); + await flushMicrotasks(); + // The daemon's own push for the same lease arrives a moment later; an agent must not read + // that as a second device lost. + client.emitLeaseLost({ deviceId: "device-1", leaseId: "lease-1", reason: "expired" }); + + expect(notices).toEqual([ + { deviceId: "device-1", leaseId: "lease-1", reason: "renew-rejected" }, + ]); + + await session.close(); + }); + it("stops renewing a lease that ended elsewhere", async () => { const clock = new FakeClock(0); const client = new FakeSimlockClient(); diff --git a/src/mcp/session.ts b/src/mcp/session.ts index 07a9f6fd8..87e24ac54 100644 --- a/src/mcp/session.ts +++ b/src/mcp/session.ts @@ -129,9 +129,9 @@ export class McpSession { * holds a lease it obtained itself. */ #renewal: LeaseRenewal | undefined; - /** The lease a `release()` call has in flight right now, so `close()` never sends a second - * release for the same lease (it does not queue behind `#mutations`). */ - #releaseInFlight: string | undefined; + /** Lease ids already announced as lost, so one ending never reaches a listener twice -- see + * `#announceLeaseLost`. */ + readonly #announcedLost = new Set(); constructor(options: McpSessionOptions) { this.#clock = options.clock; @@ -151,6 +151,15 @@ export class McpSession { ...(onProgress === undefined ? {} : { onProgress }), ...(signal === undefined ? {} : { signal }), }); + if (this.#closed) { + // The session ended while the daemon was provisioning. `close()` does not queue behind + // `#mutations`, so it has already stopped renewing and closed the connection: arming a + // timer now would leave a closed session renewing on a dead client until the backstop, + // and `simlock mcp` (which never calls `process.exit`) alive with it. Hand the device + // straight back instead, and fail the call that can no longer be honoured. + await this.#releaseQuietly(client, grant.lease.id); + this.#throwIfClosed(); + } this.#heldLeaseId = grant.lease.id; this.#startRenewal(client, grant.lease); return grant; @@ -160,18 +169,8 @@ export class McpSession { release(input: ReleaseSimulatorInput): Promise { return this.#mutate(async () => { this.#throwIfClosed(); - // Marked before `#clientForUse()`, not after: that call can reconnect, which takes as - // long as a daemon launch, and `close()` does not queue behind `#mutations` (see its doc - // comment). This is how it knows the lease already has a release on the way -- from the - // moment this call commits to sending one -- and must not get a second one. - this.#releaseInFlight = input.leaseId; - let result; - try { - const client = await this.#clientForUse(); - result = await client.releaseLease(input); - } finally { - this.#releaseInFlight = undefined; - } + const client = await this.#clientForUse(); + const result = await client.releaseLease(input); // Stopped only once the daemon has actually let the lease go. A release that fails // (anything but a dead connection) leaves the session still holding the device, and a // session that has stopped renewing a lease it still holds loses that device at the @@ -239,11 +238,12 @@ export class McpSession { * its own call now rather than a side effect of the socket going away -- the daemon still * releases on close today, and will not once PR B lands. * - * One race is deliberately left: a `lease()` still in flight here can set `#heldLeaseId` - * after this method read it, and that lease is not released explicitly. It is not reachable - * from the MCP frontend (`close()` runs on shutdown, after the transport is gone) and - * blocking shutdown on an in-flight provisioning request -- minutes, potentially -- would be - * a worse trade than the daemon's own expiry handling it. + * It does not queue behind `#mutations`: blocking shutdown on an in-flight provisioning + * request -- minutes, potentially -- would be a worse trade than ending now. A `lease()` that + * lands after this point releases its own grant instead (see `lease()`), and a `release()` + * still in flight is *not* a reason to skip the farewell one: the wire rejects every pending + * request when the connection closes below, so skipping would mean no release at all. A + * duplicate costs one `UNKNOWN_LEASE` this method already swallows. */ close(): Promise { if (this.#closePromise !== undefined) return this.#closePromise; @@ -251,8 +251,7 @@ export class McpSession { this.#stopRenewal(); this.#unwireClient(); const client = this.#client; - // A lease whose release is already in flight is not released again. - const heldLeaseId = this.#heldLeaseId === this.#releaseInFlight ? undefined : this.#heldLeaseId; + const heldLeaseId = this.#heldLeaseId; this.#heldLeaseId = undefined; this.#client = undefined; if (this.#connecting !== undefined) { @@ -265,23 +264,30 @@ export class McpSession { /** `close()`'s tail: the farewell release (best-effort, bounded), then the connection. */ async #endSession(client: SimlockClient, heldLeaseId: string | undefined): Promise { - if (heldLeaseId !== undefined) { - try { - await awaitWithin( - this.#clock, - RELEASE_TIMEOUT_MS, - client.releaseLease({ leaseId: heldLeaseId }), - `Timed out releasing lease ${heldLeaseId}`, - ); - } catch { - // Best-effort by design: the lease may already be gone (expired, force-released), the - // connection may be dead, or the daemon may not answer. Shutdown continues either way, - // and an unreleased lease still ends at its deadline. - } - } + if (heldLeaseId !== undefined) await this.#releaseQuietly(client, heldLeaseId); await this.#closeClient(client); } + /** + * A release nobody is waiting on an answer to: bounded, and silent whatever happens. The + * lease may already be gone (expired, force-released, or released by a tool call whose own + * answer never arrived), the connection may be dead, or the daemon may not answer at all -- + * none of which should hold up an ending session, and all of which end the same way in the + * daemon regardless, at the lease's deadline. + */ + async #releaseQuietly(client: SimlockClient, leaseId: string): Promise { + try { + await awaitWithin( + this.#clock, + RELEASE_TIMEOUT_MS, + client.releaseLease({ leaseId }), + `Timed out releasing lease ${leaseId}`, + ); + } catch { + // Best-effort by design -- see above. + } + } + /** * Starts (or restarts) the renew timer for the lease this session just obtained. The client * is captured deliberately: if that connection dies, the renewal fails and stops rather than @@ -322,6 +328,17 @@ export class McpSession { if (notice.leaseId !== this.#heldLeaseId) return; this.#stopRenewal(); this.#heldLeaseId = undefined; + this.#announceLeaseLost(notice); + } + + /** + * Tells the listeners a lease ended, once per lease. A lease that a renewal found gone is + * very often also pushed as `lease-lost` a moment later (or the other way round) -- two + * accounts of one ending, which would read to an agent as two devices lost. + */ + #announceLeaseLost(notice: LeaseLostNotice): void { + if (this.#announcedLost.has(notice.leaseId)) return; + this.#announcedLost.add(notice.leaseId); for (const listener of this.#leaseLostListeners) listener(notice); } @@ -383,7 +400,7 @@ export class McpSession { this.#stopRenewal(); this.#heldLeaseId = undefined; } - for (const listener of this.#leaseLostListeners) listener(push); + this.#announceLeaseLost(push); }), client.onDeviceUnhealthy((push) => { for (const listener of this.#deviceHealthListeners) { From 3579b058419aa1770f0317abef8d9c0738493be8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Sep 2026 23:44:26 +0000 Subject: [PATCH 6/7] fix(mcp,lease-policy): renew every lease a session holds, apply answers newest-first Three findings from the third isolated review: - two abandoned renewals that both answered late were merged by taking the larger deadline, so a stale 900_000 could override a newer, shorter 12_000 and leave the holder renewing long after the lease was gone. Every attempt is numbered now and every answer -- late or in time -- is applied by that number, newest wins, in both directions. - a second `lease()` overwrote the session's single renewal, leaving the first lease neither renewed nor released: a regression against the daemon heartbeat, which slid every held lease on the connection. Renewals are keyed by lease id, every one is renewed, and every one is released on close. No client-side "one lease per session" rule is added: the daemon's one-lease-per-requester check is the authority (ADR 0003 section 11), and if it refuses the second request the map simply holds one entry. - `close()` ran straight into the wire close, so a grant landing from an in-flight `lease()` had no live connection to be handed back on. It now waits for the tool call in flight, bounded by the release timeout, before releasing and closing. `FakeSimlockClient` rejects every call after `close()` the way the wire does, so a test cannot pass on a dead connection any more. Also: the scheduled delay is capped at the largest delay a Node timer can express, so a deadline more than ~24 days out cannot truncate into a hot loop; `#announcedLost` entries are dropped with the lease they belong to; the CLI's single `lease-lost` line is now a flag both paths share rather than an ordering accident; and the MCP frontend builds one `Clock` for the session and the auto-launch retry loop. BREAKING CHANGE: `simlock/client` and `simlock/admin` default the `heartbeat` connect option to `false`, so a held lease is kept alive only by its holder's own `lease.renew` (ADR 0004 sections 1, 2 and 4), and `client.heartbeat()` answers `BAD_REQUEST` unless the caller opts back in. Part of #114 Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- src/cli/index.ts | 37 +++++++----- src/lease-policy/index.test.ts | 50 ++++++++++++++++ src/lease-policy/index.ts | 49 ++++++++++------ src/mcp/main.ts | 9 ++- src/mcp/session.test.ts | 73 +++++++++++++++++++---- src/mcp/session.ts | 103 +++++++++++++++++++++++---------- src/mcp/test-support.ts | 32 ++++++---- 7 files changed, 266 insertions(+), 87 deletions(-) diff --git a/src/cli/index.ts b/src/cli/index.ts index f0f7444dd..d887c2cc2 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -733,16 +733,29 @@ async function runLease( const leaseLostSignal = new Promise((resolve) => { notifyLeaseLost = resolve; }); - /** The lease ended without this process asking: stop waiting, skip the release it can no - * longer perform, and exit with the lost-lease code. */ - const markLeaseLost = (): void => { + /** + * The lease ended without this process asking, from either of the two places that can find + * out -- the daemon's push, or a renewal it rejects. Both write the one `lease-lost` line a + * script tails for (whichever gets there first; the flag is what makes that structural + * rather than a matter of ordering), stop the wait, skip the release this process can no + * longer perform, and leave `runLease` returning the lost-lease code. + */ + let wroteLeaseLost = false; + const markLeaseLost = (notice: { + readonly deviceId: string; + readonly leaseId: string; + readonly reason: string; + }): void => { + if (!wroteLeaseLost) { + wroteLeaseLost = true; + environment.stderr.write(`${JSON.stringify({ push: "lease-lost", ...notice })}\n`); + } leaseLost = true; notifyLeaseLost?.(); }; const offLeaseLost = client.onLeaseLost((push) => { if (push.leaseId !== ourLeaseId) return; - environment.stderr.write(`${JSON.stringify({ push: "lease-lost", ...push })}\n`); - markLeaseLost(); + markLeaseLost(push); }); const offUnhealthy = client.onDeviceUnhealthy((push) => { environment.stderr.write(`${JSON.stringify({ push: "device-unhealthy", ...push })}\n`); @@ -833,16 +846,12 @@ async function runLease( // watching for `push: "lease-lost"` sees this way of losing a lease too. The error line // follows it as the detail of why. onLeaseGone: (error) => { - environment.stderr.write( - `${JSON.stringify({ - push: "lease-lost", - deviceId: grant.lease.deviceId, - leaseId: grant.lease.id, - reason: "renew-rejected", - })}\n`, - ); + markLeaseLost({ + deviceId: grant.lease.deviceId, + leaseId: grant.lease.id, + reason: "renew-rejected", + }); writeError(environment, error); - markLeaseLost(); }, }); await Promise.race([termination.settled, leaseLostSignal]); diff --git a/src/lease-policy/index.test.ts b/src/lease-policy/index.test.ts index 46b471c1d..f7697e46b 100644 --- a/src/lease-policy/index.test.ts +++ b/src/lease-policy/index.test.ts @@ -368,6 +368,56 @@ describe("startLeaseRenewal", () => { expect(errors.at(-1)?.message).toContain("Gave up renewing lease lse_1"); }); + it("applies two late answers newest-first, not largest-first", async () => { + const clock = new FakeClock(0); + const attemptsAt: number[] = []; + const answers: Array<(renewed: { ttlDeadline: number }) => void> = []; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + renew: () => { + attemptsAt.push(clock.now()); + // The first two attempts are accepted and left unanswered until the end of the test; + // everything after fails, so the schedule is driven purely by `deadline`. + if (attemptsAt.length <= 2) + return new Promise<{ ttlDeadline: number }>((resolve) => { + answers.push(resolve); + }); + return Promise.reject(new Error("INTERNAL")); + }, + ttlDeadline: 9_000, + }); + + clock.advance(3_000); // attempt 1 starts, bound 2_000 + await flushMicrotasks(); + clock.advance(2_000); // abandoned at 5_000; next attempt at 6_333 + await flushMicrotasks(); + clock.advance(1_333); // attempt 2 starts, bound 889 + await flushMicrotasks(); + clock.advance(889); // abandoned at 7_222; next attempt at 7_814 + await flushMicrotasks(); + expect(attemptsAt).toEqual([3_000, 6_333]); + + // Both abandoned requests did reach the daemon, and answer out of order. Attempt 2 is the + // newer request, so its 12_000 is the truth; attempt 1's 900_000 is stale, and being the + // larger number does not make it newer -- adopting it would leave this holder renewing + // long after the lease was gone. + answers[1]?.({ ttlDeadline: 12_000 }); + await flushMicrotasks(); + answers[0]?.({ ttlDeadline: 900_000 }); + await flushMicrotasks(); + + clock.advance(592); // attempt 3 at 7_814, which fails and reschedules off the deadline + await flushMicrotasks(); + expect(attemptsAt).toEqual([3_000, 6_333, 7_814]); + + // A third of what is left of 12_000 at 7_814 is 1_395ms -- so the next attempt lands at + // 9_209. Against the stale 900_000 it would not have come for another five minutes. + clock.advance(1_395); + await flushMicrotasks(); + expect(attemptsAt).toEqual([3_000, 6_333, 7_814, 9_209]); + }); + it("never reports a failure that arrives after stop()", async () => { const clock = new FakeClock(0); let rejectRenew!: (error: Error) => void; diff --git a/src/lease-policy/index.ts b/src/lease-policy/index.ts index a794f2ded..1858a8774 100644 --- a/src/lease-policy/index.ts +++ b/src/lease-policy/index.ts @@ -42,6 +42,13 @@ const RENEW_DIVISOR = 3; */ const MINIMUM_RENEW_DELAY_MS = 250; +/** + * Ceiling on the scheduled delay: the largest delay a Node timer can express (~24.9 days). + * Anything above it silently truncates to 1ms, which would turn a very distant deadline into + * exactly the hot loop the floor above exists to prevent. Renewing early costs one round trip. + */ +const MAXIMUM_RENEW_DELAY_MS = 2_147_483_647; + /** * How long a holder waits for its farewell `lease.release` before giving up and closing the * connection anyway. The daemon is a local process answering a local socket, so this is not a @@ -117,12 +124,13 @@ export interface LeaseRenewal { /** The delay before the next renewal, given how much of the TTL is left. */ function renewDelayMs(remainingMs: number): number { - return Math.max(MINIMUM_RENEW_DELAY_MS, Math.floor(remainingMs / RENEW_DIVISOR)); + const delay = Math.max(MINIMUM_RENEW_DELAY_MS, Math.floor(remainingMs / RENEW_DIVISOR)); + return Math.min(MAXIMUM_RENEW_DELAY_MS, delay); } type Attempt = - | { readonly ok: true; readonly renewed: RenewedLease } - | { readonly ok: false; readonly error: unknown }; + | { readonly attemptId: number; readonly ok: true; readonly renewed: RenewedLease } + | { readonly attemptId: number; readonly ok: false; readonly error: unknown }; /** * A rejection that answers "this lease is not yours to renew" rather than "that attempt did @@ -163,8 +171,8 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { /** Whichever timer is armed right now: the wait between renewals, or an attempt's bound. */ let timer: TimerHandle | undefined; let stopped = false; - /** Attempts are numbered so a late answer can tell whether anything newer has been answered - * since (attempts never overlap: one is in flight at a time, by construction). */ + /** Every attempt is numbered, and every *answer* is applied by that number: two abandoned + * attempts can answer in either order, and only the newer one's deadline is the truth. */ let attempts = 0; let newestAnswered = 0; @@ -210,23 +218,26 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { // a late rejection from surfacing as an unhandled rejection.) request.then( (renewed) => { - // Only while no *newer* attempt has been answered, and then only forward: this answer - // is older than anything that has happened since, so it may raise a deadline nobody - // has since improved on, and never overwrite a fresher one. + // Newest answer wins, by attempt number rather than by arrival order or by which + // deadline is larger: an older attempt's answer is not "better" for being further + // out, it is out of date, and taking it would leave this holder renewing towards a + // deadline the daemon has already replaced. if (stopped || attemptId <= newestAnswered) return; - deadline = Math.max(deadline, renewed.ttlDeadline); + newestAnswered = attemptId; + deadline = renewed.ttlDeadline; }, () => undefined, ); return Promise.race([ request.then( - (renewed) => ({ ok: true, renewed }), - (error: unknown) => ({ error, ok: false }), + (renewed) => ({ attemptId, ok: true, renewed }), + (error: unknown) => ({ attemptId, error, ok: false }), ), new Promise((resolve) => { timer = clock.setTimer(renewDelayMs(deadline - clock.now()), () => { timer = undefined; resolve({ + attemptId, error: new Error(`Timed out renewing lease ${leaseId}`), ok: false, }); @@ -263,9 +274,12 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { return; } - // This attempt is now the newest answer there is, so no request older than it may move the - // deadline again (see `attemptRenew`). - newestAnswered = attempts; + // Applied by this attempt's own number, exactly as a late answer is (`attemptRenew` above + // has usually already done it for this very answer; both paths agree). + if (attempt.attemptId > newestAnswered) { + newestAnswered = attempt.attemptId; + deadline = attempt.renewed.ttlDeadline; + } if (attempt.renewed.ttlDeadline <= clock.now()) { // A deadline that is not in the future cannot be renewed towards -- scheduling off it // would be a hot loop against a lease that is already over. @@ -273,10 +287,9 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { report(new Error(`Lease ${leaseId} was renewed to a deadline that has already passed`)); return; } - // The daemon's answer is authoritative, in both directions: it may hand back a *shorter* - // deadline than the one that was asked for -- a lowered `lease.heldTtlBackstopMs`, a - // `ttlMs` it clamped -- and the cadence follows it rather than an older, longer belief. - deadline = attempt.renewed.ttlDeadline; + // The cadence follows the newest answer in both directions: the daemon may hand back a + // *shorter* deadline than the one asked for -- a lowered `lease.heldTtlBackstopMs`, a + // `ttlMs` it clamped -- and a longer, older belief does not override it. schedule(); }; diff --git a/src/mcp/main.ts b/src/mcp/main.ts index cd6746c0f..002f176e4 100644 --- a/src/mcp/main.ts +++ b/src/mcp/main.ts @@ -68,9 +68,12 @@ export async function startMcpStdio( ): Promise { const env = environment.env ?? process.env; const requesterId = environment.requesterId ?? env.SIMLOCK_AGENT_ID ?? `mcp:${process.pid}`; - const defaults = defaultEnvironment(requesterId); + // One `Clock` for the whole frontend: the session's renew timer and the auto-launch retry + // loop must not be able to disagree about what time it is (architecture rule 9). + const clock = environment.clock ?? new SystemClock(); + const defaults = defaultEnvironment(requesterId, clock); const session = new McpSession({ - clock: environment.clock ?? new SystemClock(), + clock, connect: environment.connect ?? defaults.connect, }); const server = (environment.createServer ?? createMcpServer)(session); @@ -144,9 +147,9 @@ export async function startMcpStdio( function defaultEnvironment( requesterId: string, + clock: Clock, ): Required> { const dataDirectory = resolveSimlockHome(); - const clock = new SystemClock(); const ipc = new NodeIpcTransport(); const logPath = join(dataDirectory, "daemon.log"); return { diff --git a/src/mcp/session.test.ts b/src/mcp/session.test.ts index f86d7419f..402115b4c 100644 --- a/src/mcp/session.test.ts +++ b/src/mcp/session.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { SimlockError } from "../client/index.js"; +import { RELEASE_TIMEOUT_MS } from "../lease-policy/index.js"; import { FakeClock } from "../ports/index.js"; import { FakeSimlockClient, sampleGrant } from "./test-support.js"; import { McpSession, toMcpErrorResult } from "./session.js"; @@ -335,6 +336,50 @@ describe("McpSession", () => { expect(client.calls.filter((call) => call.method === "releaseLease")).toHaveLength(1); }); + it("renews and releases every lease it obtained, not only the latest", async () => { + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + let granted = 0; + client.requestLeaseImpl = () => { + granted += 1; + return Promise.resolve(sampleGrant({ leaseId: `lease-${granted}` })); + }; + const renewed: string[] = []; + client.renewLeaseImpl = (input) => { + renewed.push(input.leaseId); + return Promise.resolve({ + deviceId: "device-1", + grantedAt: 0, + id: input.leaseId, + mode: "held" as const, + ownerId: "mcp-test", + requesterId: "mcp-test", + ttlDeadline: clock.now() + 12_345, + }); + }; + client.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); + const session = new McpSession({ clock, connect: async () => client }); + + // Nothing here limits a session to one lease -- the daemon's one-lease-per-requester rule + // is the authority (ADR 0003 §11). Whatever it grants, this session has to keep alive and + // hand back; the second grant must not silently strand the first. + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + clock.advance(4_115); + await flushMicrotasks(); + expect(renewed.slice().sort()).toEqual(["lease-1", "lease-2"]); + + await session.close(); + expect( + client.calls + .filter((call) => call.method === "releaseLease") + .map((call) => (call.input as { leaseId: string }).leaseId) + .sort(), + ).toEqual(["lease-1", "lease-2"]); + expect(clock.pendingTimerCount).toBe(0); + }); + it("still releases on close when a tool call's own release is in flight and dies with the wire", async () => { const clock = new FakeClock(0); const client = new FakeSimlockClient(); @@ -370,24 +415,29 @@ describe("McpSession", () => { const session = new McpSession({ clock, connect: async () => client }); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); - // `close()` deliberately does not queue behind the tool-call serializer, so it can land - // while a `release_simulator` call is still waiting on the daemon. Skipping the farewell - // release because that one exists would mean *no* release at all: the wire kills it a - // moment later. + // `close()` deliberately does not queue behind the tool-call serializer: it waits for the + // call in flight, but only so long. Here the daemon never answers that release, so the + // wait times out -- and skipping the farewell release because a tool call "has one on the + // way" would mean *no* release at all, since the wire kills that one a moment later. const releasing = session.release({ leaseId: "lease-1" }); await flushMicrotasks(); const closing = session.close(); await flushMicrotasks(); + expect(client.calls.filter((call) => call.method === "releaseLease")).toHaveLength(1); + + clock.advance(RELEASE_TIMEOUT_MS); + await flushMicrotasks(); expect(client.calls.filter((call) => call.method === "releaseLease")).toHaveLength(2); pending[1]?.resolve({ leaseId: "lease-1" }); // the daemon answers the farewell release await closing; await expect(releasing).rejects.toMatchObject({ code: "DAEMON_CONNECTION_LOST" }); - // Exactly one release actually completed -- and the lease really is released. - expect(pending.filter((entry) => entry.settled)).toHaveLength(2); - expect(pending[0]?.settled).toBe(true); // rejected with the wire + // Exactly one release completed -- the farewell one -- and the lease really is released. + expect(pending[1]?.settled, "the farewell release was answered").toBe(true); + expect(pending[0]?.settled, "the tool call's release died with the wire").toBe(true); expect(client.closeCalls).toBe(1); + expect(clock.pendingTimerCount, "no bound outlives the close").toBe(0); }); it("releases a grant that lands after the session closed, and arms no timer for it", async () => { @@ -404,12 +454,15 @@ describe("McpSession", () => { const leasing = session.lease({ model: "iPhone 17 Pro", platform: "ios" }); await flushMicrotasks(); const closing = session.close(); - await closing; + await flushMicrotasks(); - // The daemon finished provisioning after the session ended: the device goes straight back - // rather than being renewed by a session that no longer exists. + // The daemon finishes provisioning just after the session ended. `close()` is still + // waiting on that call (bounded), so the wire is alive: the device goes straight back + // rather than being renewed by a session that no longer exists -- or stranded until its + // deadline because the connection was already gone. answerGrant(sampleGrant({ leaseId: "lease-1" })); await expect(leasing).rejects.toMatchObject({ code: "SESSION_CLOSED" }); + await closing; expect(client.calls.filter((call) => call.method === "releaseLease")).toEqual([ { input: { leaseId: "lease-1" }, method: "releaseLease" }, diff --git a/src/mcp/session.ts b/src/mcp/session.ts index 87e24ac54..b9811e5f7 100644 --- a/src/mcp/session.ts +++ b/src/mcp/session.ts @@ -124,11 +124,13 @@ export class McpSession { * cannot answer `lease_status` correctly. */ #heldLeaseId: string | undefined; /** - * ADR 0004 §2: the session's half of "held is a client policy" -- the timer that renews - * `#heldLeaseId` at a third of its remaining TTL. Non-`undefined` exactly while this session - * holds a lease it obtained itself. + * ADR 0004 §2: the session's half of "held is a client policy" -- one renew timer per lease + * this session obtained, keyed by lease id. Keyed rather than single because nothing here + * limits a session to one lease: the daemon's one-lease-per-requester rule is the authority + * (ADR 0003 §11), and if it starts allowing two, both have to be kept alive and both have to + * be handed back on close. An entry lives exactly as long as this session holds that lease. */ - #renewal: LeaseRenewal | undefined; + readonly #renewals = new Map(); /** Lease ids already announced as lost, so one ending never reaches a listener twice -- see * `#announceLeaseLost`. */ readonly #announcedLost = new Set(); @@ -153,10 +155,10 @@ export class McpSession { }); if (this.#closed) { // The session ended while the daemon was provisioning. `close()` does not queue behind - // `#mutations`, so it has already stopped renewing and closed the connection: arming a - // timer now would leave a closed session renewing on a dead client until the backstop, - // and `simlock mcp` (which never calls `process.exit`) alive with it. Hand the device - // straight back instead, and fail the call that can no longer be honoured. + // `#mutations`, so it has already stopped renewing: arming a timer now would leave a + // closed session renewing on a client nobody owns any more, and `simlock mcp` (which + // never calls `process.exit`) alive with it. Hand the device straight back instead -- + // `close()` waits, bounded, for exactly this -- and fail the call it cannot honour. await this.#releaseQuietly(client, grant.lease.id); this.#throwIfClosed(); } @@ -177,10 +179,7 @@ export class McpSession { // deadline. A renew that overtakes a *successful* release cannot resurrect anything: // `Registry#beginRelease` drops the record, so `lease.renew` can only answer // UNKNOWN_LEASE. - if (result.leaseId === this.#heldLeaseId) { - this.#stopRenewal(); - this.#heldLeaseId = undefined; - } + this.#forgetLease(result.leaseId); return { ...result, released: true }; }); } @@ -248,23 +247,47 @@ export class McpSession { close(): Promise { if (this.#closePromise !== undefined) return this.#closePromise; this.#closed = true; - this.#stopRenewal(); + // Whatever a tool call has in flight right now. `#endSession` waits on it (bounded) before + // touching the connection, so a `lease()` that lands in that window still has a live wire + // to hand its device back on. + const inFlight = this.#mutations; this.#unwireClient(); const client = this.#client; - const heldLeaseId = this.#heldLeaseId; + const heldLeaseIds = [...this.#renewals.keys()]; + this.#stopAllRenewals(); this.#heldLeaseId = undefined; + this.#announcedLost.clear(); this.#client = undefined; if (this.#connecting !== undefined) { void this.#connecting.then((next) => this.#closeClient(next)).catch(noop); } this.#closePromise = - client === undefined ? Promise.resolve() : this.#endSession(client, heldLeaseId); + client === undefined ? Promise.resolve() : this.#endSession(client, heldLeaseIds, inFlight); return this.#closePromise; } - /** `close()`'s tail: the farewell release (best-effort, bounded), then the connection. */ - async #endSession(client: SimlockClient, heldLeaseId: string | undefined): Promise { - if (heldLeaseId !== undefined) await this.#releaseQuietly(client, heldLeaseId); + /** + * `close()`'s tail: let the last tool call finish on a live wire, hand every lease back, then + * close. The wait is bounded because an in-flight `lease.request` can take minutes and an + * ending session cannot wait that long; past the bound the connection closes, the daemon + * rejects what was still pending, and any lease that slipped through ends at its deadline. + */ + async #endSession( + client: SimlockClient, + heldLeaseIds: readonly string[], + inFlight: Promise, + ): Promise { + try { + await awaitWithin( + this.#clock, + RELEASE_TIMEOUT_MS, + inFlight, + "Timed out waiting for the last tool call to finish", + ); + } catch { + // Bounded by design -- see above. + } + for (const leaseId of heldLeaseIds) await this.#releaseQuietly(client, leaseId); await this.#closeClient(client); } @@ -295,12 +318,12 @@ export class McpSession { * call makes (`#clientForUse`). */ #startRenewal(client: SimlockClient, lease: LeaseRecord): void { - this.#stopRenewal(); + this.#stopRenewal(lease.id); // No `onError`: this frontend owns stdout (it is the protocol) and has no side channel a // retryable failure could be written to. What the agent has to know is that the lease is // over, and that arrives as the `lease-lost` notice `onLeaseGone` raises below (or as the // daemon's own push, whichever comes first) rather than as a stream of attempt failures. - this.#renewal = startLeaseRenewal({ + const renewal = startLeaseRenewal({ clock: this.#clock, leaseId: lease.id, onLeaseGone: () => { @@ -316,6 +339,7 @@ export class McpSession { renew: (id) => client.renewLease({ leaseId: id }), ttlDeadline: lease.ttlDeadline, }); + this.#renewals.set(lease.id, renewal); } /** @@ -325,9 +349,9 @@ export class McpSession { * including ones for leases this session never held; this only ever fires for its own.) */ #reportLeaseLost(notice: LeaseLostNotice): void { - if (notice.leaseId !== this.#heldLeaseId) return; - this.#stopRenewal(); - this.#heldLeaseId = undefined; + if (!this.#renewals.has(notice.leaseId)) return; + this.#stopRenewal(notice.leaseId); + if (this.#heldLeaseId === notice.leaseId) this.#heldLeaseId = undefined; this.#announceLeaseLost(notice); } @@ -342,9 +366,26 @@ export class McpSession { for (const listener of this.#leaseLostListeners) listener(notice); } - #stopRenewal(): void { - this.#renewal?.stop(); - this.#renewal = undefined; + /** Stops and forgets one lease's renew timer. */ + #stopRenewal(leaseId: string): void { + this.#renewals.get(leaseId)?.stop(); + this.#renewals.delete(leaseId); + } + + #stopAllRenewals(): void { + for (const renewal of this.#renewals.values()) renewal.stop(); + this.#renewals.clear(); + } + + /** + * This session no longer holds `leaseId`: stop renewing it, drop it from `status()`'s answer + * if it was the latest, and let its lost-notice bookkeeping go (nothing can announce a lease + * that is no longer ours). + */ + #forgetLease(leaseId: string): void { + this.#stopRenewal(leaseId); + this.#announcedLost.delete(leaseId); + if (this.#heldLeaseId === leaseId) this.#heldLeaseId = undefined; } /** @@ -394,12 +435,10 @@ export class McpSession { #wireClient(client: SimlockClient): void { this.#clientUnsubscribers = [ client.onLeaseLost((push) => { - if (push.leaseId === this.#heldLeaseId) { - // Nothing left to renew: the lease ended elsewhere (expiry, a force-release, or this - // connection dying -- the client synthesizes the push for that last one). - this.#stopRenewal(); - this.#heldLeaseId = undefined; - } + // Nothing left to renew for that lease: it ended elsewhere (expiry, a force-release, + // or this connection dying -- the client synthesizes the push for that last one). + this.#stopRenewal(push.leaseId); + if (this.#heldLeaseId === push.leaseId) this.#heldLeaseId = undefined; this.#announceLeaseLost(push); }), client.onDeviceUnhealthy((push) => { diff --git a/src/mcp/test-support.ts b/src/mcp/test-support.ts index 8c300c940..312461c0f 100644 --- a/src/mcp/test-support.ts +++ b/src/mcp/test-support.ts @@ -50,6 +50,10 @@ export class FakeSimlockClient implements SimlockClient { readonly daemonVersion: string; closeCalls = 0; readonly calls: Array<{ readonly method: string; readonly input: unknown }> = []; + /** Set by `close()`. Every operation after it rejects, the way `SimlockWire` does once the + * connection is gone (ADR 0003 §10) -- a fake that stayed usable would let a test pass on a + * dead wire. */ + #dead = false; getCatalogImpl: (input: CatalogGetInput) => Promise = notStubbed("getCatalog"); getStatusImpl: () => Promise = notStubbed("getStatus"); @@ -81,57 +85,57 @@ export class FakeSimlockClient implements SimlockClient { getCatalog(input: CatalogGetInput = {}): Promise { this.calls.push({ input, method: "getCatalog" }); - return this.getCatalogImpl(input); + return this.#dead ? this.#deadConnection() : this.getCatalogImpl(input); } // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP itself never calls status.get. getStatus(): Promise { this.calls.push({ input: undefined, method: "getStatus" }); - return this.getStatusImpl(); + return this.#dead ? this.#deadConnection() : this.getStatusImpl(); } requestLease(input: LeaseRequestInput, options: RequestLeaseOptions = {}): Promise { this.calls.push({ input, method: "requestLease" }); - return this.requestLeaseImpl(input, options); + return this.#dead ? this.#deadConnection() : this.requestLeaseImpl(input, options); } // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP itself never calls lease.cancel. cancelLease(input: LeaseCancelInput = {}): Promise { this.calls.push({ input, method: "cancelLease" }); - return this.cancelLeaseImpl(input); + return this.#dead ? this.#deadConnection() : this.cancelLeaseImpl(input); } renewLease(input: LeaseRenewInput): Promise { this.calls.push({ input, method: "renewLease" }); - return this.renewLeaseImpl(input); + return this.#dead ? this.#deadConnection() : this.renewLeaseImpl(input); } releaseLease(input: LeaseReleaseInput): Promise { this.calls.push({ input, method: "releaseLease" }); - return this.releaseLeaseImpl(input); + return this.#dead ? this.#deadConnection() : this.releaseLeaseImpl(input); } listLeases(): Promise { this.calls.push({ input: undefined, method: "listLeases" }); - return this.listLeasesImpl(); + return this.#dead ? this.#deadConnection() : this.listLeasesImpl(); } // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP itself never calls lease.heartbeat (the client handles it internally). heartbeat(): Promise { this.calls.push({ input: undefined, method: "heartbeat" }); - return this.heartbeatImpl(); + return this.#dead ? this.#deadConnection() : this.heartbeatImpl(); } // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP itself never calls doctor.run. runDoctor(input: DoctorRunInput = {}): Promise { this.calls.push({ input, method: "runDoctor" }); - return this.runDoctorImpl(input); + return this.#dead ? this.#deadConnection() : this.runDoctorImpl(input); } // fallow-ignore-next-line unused-class-member -- part of the SimlockClient interface this fake implements; MCP itself never resolves a passthrough. resolvePassthrough(input: DriverPassthroughInput): Promise { this.calls.push({ input, method: "resolvePassthrough" }); - return this.resolvePassthroughImpl(input); + return this.#dead ? this.#deadConnection() : this.resolvePassthroughImpl(input); } onLeaseLost(listener: (push: LeaseLostPush) => void): () => void { @@ -180,10 +184,18 @@ export class FakeSimlockClient implements SimlockClient { async close(): Promise { this.closeCalls += 1; + this.#dead = true; this.emitConnectionLost( new SimlockError("DAEMON_CONNECTION_LOST", "transport", "Client closed the connection", {}), ); } + + /** The rejection every operation gets once this connection is closed. */ + #deadConnection(): Promise { + return Promise.reject( + new SimlockError("DAEMON_CONNECTION_LOST", "transport", "Connection is closed", {}), + ); + } } export function sampleGrant(overrides: { readonly leaseId?: string } = {}): LeaseGrant { From e58c9efa1765652f522b5cb3976bbccf55268e46 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 6 Sep 2026 00:26:53 +0000 Subject: [PATCH 7/7] fix(mcp,lease-policy): one shutdown budget, and tell the holder when renewal gives up Two findings from the fourth isolated review: - `McpSession#endSession` bounded each step of the shutdown separately -- the wait for the in-flight tool call, then one more per lease -- so an MCP server facing a dead daemon could sit for a multiple of the budget after stdin EOF. The whole tail now runs inside one `RELEASE_TIMEOUT_MS`: wait for the call in flight, release every lease, and close the wire in a `finally`, whichever comes first. - renewal's two "this lease cannot be saved" endings -- the deadline passing mid-ladder, and a daemon answering with a deadline already behind us -- were reported through `onError` and left the holder alive with no timer: the CLI printed an INTERNAL line and exited 0 on Ctrl-C, and MCP raised no notice, leaked the renewal entry, and released a dead lease on close. Both now end through `onLeaseGone`, which carries a reason: `renew-rejected` when the daemon said the lease is gone or not ours, `renew-failed` when renewal ran out of runway. The CLI writes its one `lease-lost` line with that reason and exits 14 either way; the MCP session raises the matching notice and stops counting the lease as its own. Also: `stop()` now prevents the renewal call itself when it lands in the microtask between the timer firing and the request going out, and `#announcedLost` is capped rather than growing with every lease a long session loses. Tests: the total shutdown budget (one `RELEASE_TIMEOUT_MS`, not two); a grant that lands late in that window still released before the wire closes; the give-up ending per frontend; one `lease-lost` line when a rejected renewal and the daemon's push both arrive; a stop that beats the request to the wire; a 90-day deadline clamped to the largest delay a timer can express; and the fake client rejecting calls after `close()` the way the wire does. Part of #114 Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01XsDU7hQcEDhK6kpH8M2YUz --- src/cli/index.test.ts | 75 ++++++++++++++++++ src/cli/index.ts | 19 ++--- src/lease-policy/index.test.ts | 84 +++++++++++++++++--- src/lease-policy/index.ts | 76 +++++++++++++------ src/mcp/session.test.ts | 135 +++++++++++++++++++++++---------- src/mcp/session.ts | 62 ++++++++++----- 6 files changed, 351 insertions(+), 100 deletions(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 58f3fc3ae..b7dc3ceb3 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1554,6 +1554,81 @@ describe("CLI: held-mode renew and release (ADR 0004 §2)", () => { }); }); + it("exits 14 when renewal gives up, rather than holding a lease it cannot keep", async () => { + const clock = new FakeClock(0); + const output = outputCapture(); + let released = false; + const client = fakeClient({ + // Never terminal, never successful: the ladder retries until the lease's own deadline + // passes, and then there is nothing left to hold. + renewLease: () => + Promise.reject(new SimlockError("INTERNAL", "domain", "could not persist", {})), + releaseLease: () => { + released = true; + return Promise.resolve({ leaseId: "lse_1" }); + }, + }); + const runPromise = runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro"], + output.environmentWith({ clock, connectAdmin: async () => client }), + ); + await settle(); + clock.advance(20_000); // first attempt, fails, retries + await settle(); + clock.advance(60_000); // the retry lands past the lease's 60_000 deadline + + expect(await runPromise).toBe(14); + expect(released, "a lease that expired is not this process's to release").toBe(false); + const lines = output.stderr + .trim() + .split("\n") + .map((line) => JSON.parse(line) as Record); + expect(lines).toContainEqual({ + push: "lease-lost", + deviceId: "dev_1", + leaseId: "lse_1", + reason: "renew-failed", + }); + }); + + it("writes one lease-lost line when a rejected renewal and the daemon's push both arrive", async () => { + const clock = new FakeClock(0); + const output = outputCapture(); + let leaseLostListener: + | ((push: { leaseId: string; deviceId: string; reason: string }) => void) + | undefined; + const client = fakeClient({ + onLeaseLost: (listener) => { + leaseLostListener = listener; + return () => {}; + }, + renewLease: () => + Promise.reject( + new SimlockError("UNKNOWN_LEASE", "domain", "no such lease", { leaseId: "lse_1" }), + ), + }); + const runPromise = runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro"], + output.environmentWith({ clock, connectAdmin: async () => client }), + ); + await settle(); + clock.advance(20_000); + await settle(); + // The daemon's own push for the same lease follows the renewal's answer. One ending, one + // line: a script tailing stderr must not read this as two devices lost. + leaseLostListener?.({ deviceId: "dev_1", leaseId: "lse_1", reason: "expired" }); + + expect(await runPromise).toBe(14); + const leaseLostLines = output.stderr + .trim() + .split("\n") + .map((line) => JSON.parse(line) as Record) + .filter((line) => line.push === "lease-lost"); + expect(leaseLostLines).toEqual([ + { push: "lease-lost", deviceId: "dev_1", leaseId: "lse_1", reason: "renew-rejected" }, + ]); + }); + it("gives up on a farewell release the daemon never answers, instead of hanging", async () => { const clock = new FakeClock(0); const output = outputCapture(); diff --git a/src/cli/index.ts b/src/cli/index.ts index d887c2cc2..5f4891bb7 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -840,17 +840,14 @@ async function runLease( // structured stderr channel as a failed release, and not an exit condition -- the lease // is still this process's until something says otherwise. onError: (error) => writeError(environment, error), - // Something did say otherwise: the daemon answered that this lease is gone or not ours. - // Same ending as the `lease-lost` push -- exit 14, and no farewell release for a lease - // that would only answer UNKNOWN_LEASE again -- and the same stderr line, so a script - // watching for `push: "lease-lost"` sees this way of losing a lease too. The error line - // follows it as the detail of why. - onLeaseGone: (error) => { - markLeaseLost({ - deviceId: grant.lease.deviceId, - leaseId: grant.lease.id, - reason: "renew-rejected", - }); + // Something did say otherwise: renewal ended, either because the daemon answered that + // this lease is gone or not ours (`renew-rejected`) or because it could not be kept + // alive to its deadline (`renew-failed`). Both are the same ending as the `lease-lost` + // push -- the same stderr line, so a script watching for `push: "lease-lost"` sees every + // way of losing a lease; exit 14; and no farewell release for a lease this process can + // no longer speak for. The error line follows as the detail of why. + onLeaseGone: (reason, error) => { + markLeaseLost({ deviceId: grant.lease.deviceId, leaseId: grant.lease.id, reason }); writeError(environment, error); }, }); diff --git a/src/lease-policy/index.test.ts b/src/lease-policy/index.test.ts index f7697e46b..f4eac5c9c 100644 --- a/src/lease-policy/index.test.ts +++ b/src/lease-policy/index.test.ts @@ -118,14 +118,14 @@ describe("startLeaseRenewal", () => { "treats %s as the end of the lease, not a failed attempt", async (code) => { const clock = new FakeClock(0); - const gone: unknown[] = []; + const gone: Array<{ reason: string; error: unknown }> = []; const errors: unknown[] = []; let calls = 0; startLeaseRenewal({ clock, leaseId: "lse_1", onError: (error) => errors.push(error), - onLeaseGone: (error) => gone.push(error), + onLeaseGone: (reason, error) => gone.push({ error, reason }), renew: () => { calls += 1; return Promise.reject(leaseGoneError(code)); @@ -137,7 +137,10 @@ describe("startLeaseRenewal", () => { await flushMicrotasks(); expect(gone).toHaveLength(1); - expect(gone[0]).toMatchObject({ code }); + expect(gone[0]?.reason, "the daemon's answer, not a failure to reach it").toBe( + "renew-rejected", + ); + expect(gone[0]?.error).toMatchObject({ code }); expect(errors, "a lease that is over is not a retryable failure").toEqual([]); expect(clock.pendingTimerCount).toBe(0); @@ -215,11 +218,13 @@ describe("startLeaseRenewal", () => { it("retries on a shrinking ladder, then gives up once the lease's own deadline has passed", async () => { const clock = new FakeClock(0); const errors: Error[] = []; + const gone: Array<{ reason: string; error: Error }> = []; const attemptsAt: number[] = []; startLeaseRenewal({ clock, leaseId: "lse_1", onError: (error) => errors.push(error as Error), + onLeaseGone: (reason, error) => gone.push({ error: error as Error, reason }), renew: () => { attemptsAt.push(clock.now()); return Promise.reject(new Error("INTERNAL")); @@ -240,12 +245,15 @@ describe("startLeaseRenewal", () => { expect(attemptsAt).toEqual([1_000, 1_666, 2_110]); expect(errors.map((error) => error.message)).toEqual(["INTERNAL", "INTERNAL", "INTERNAL"]); - // Once the deadline is behind us there is nothing left to save: renewal ends, with its own - // final report, distinct from the attempt failure that preceded it. + // Once the deadline is behind us there is nothing left to save. That is the end of the + // lease, not one more failed attempt, so it is reported as such -- a holder that only + // watched `onError` would sit alive holding nothing. clock.advance(60_000); await flushMicrotasks(); expect(clock.pendingTimerCount).toBe(0); - expect(errors.at(-1)?.message).toContain("Gave up renewing lease lse_1"); + expect(gone).toHaveLength(1); + expect(gone[0]?.reason).toBe("renew-failed"); + expect(gone[0]?.error.message).toContain("Gave up renewing lease lse_1"); const attempts = attemptsAt.length; clock.advance(600_000); @@ -329,12 +337,14 @@ describe("startLeaseRenewal", () => { it("ignores an abandoned renewal's answer once a newer one has come back", async () => { const clock = new FakeClock(0); const errors: Error[] = []; + const gone: Array<{ reason: string }> = []; let answerFirst!: (renewed: { ttlDeadline: number }) => void; let attempts = 0; startLeaseRenewal({ clock, leaseId: "lse_1", onError: (error) => errors.push(error as Error), + onLeaseGone: (reason) => gone.push({ reason }), renew: () => { attempts += 1; if (attempts === 1) @@ -365,7 +375,7 @@ describe("startLeaseRenewal", () => { clock.advance(60_000); await flushMicrotasks(); expect(clock.pendingTimerCount, "renewal works towards 5_110, so it gives up past it").toBe(0); - expect(errors.at(-1)?.message).toContain("Gave up renewing lease lse_1"); + expect(gone.at(-1)?.reason).toBe("renew-failed"); }); it("applies two late answers newest-first, not largest-first", async () => { @@ -418,6 +428,57 @@ describe("startLeaseRenewal", () => { expect(attemptsAt).toEqual([3_000, 6_333, 7_814, 9_209]); }); + it("does not send a renewal that stop() beat to the wire", async () => { + const clock = new FakeClock(0); + let calls = 0; + const renewal = startLeaseRenewal({ + clock, + leaseId: "lse_1", + renew: () => { + calls += 1; + return Promise.resolve({ ttlDeadline: clock.now() + 3_000 }); + }, + ttlDeadline: 3_000, + }); + + // The timer has fired -- the tick is running -- but `stop()` lands before the request + // leaves. "No further `renew` call" has to mean this too, or a released lease gets one + // last renewal after its release. + clock.advance(1_000); + renewal.stop(); + await flushMicrotasks(); + + expect(calls).toBe(0); + expect(clock.pendingTimerCount).toBe(0); + }); + + it("clamps the delay to what a timer can express, for a deadline months away", async () => { + const clock = new FakeClock(0); + const renewedAt: number[] = []; + const ninetyDays = 90 * 24 * 60 * 60 * 1_000; + const renewal = startLeaseRenewal({ + clock, + leaseId: "lse_1", + renew: () => { + renewedAt.push(clock.now()); + return Promise.resolve({ ttlDeadline: clock.now() + ninetyDays }); + }, + ttlDeadline: ninetyDays, + }); + + // A third of 90 days is past what `setTimeout` can hold, and a truncated delay would fire + // in a millisecond -- the hot loop the floor exists to prevent, from the other end. + clock.advance(2_147_483_646); + await flushMicrotasks(); + expect(renewedAt).toEqual([]); + + clock.advance(1); + await flushMicrotasks(); + expect(renewedAt).toEqual([2_147_483_647]); + + renewal.stop(); + }); + it("never reports a failure that arrives after stop()", async () => { const clock = new FakeClock(0); let rejectRenew!: (error: Error) => void; @@ -445,11 +506,11 @@ describe("startLeaseRenewal", () => { it("tries a deadline that is already in the past once, then stops instead of hot-looping", async () => { const clock = new FakeClock(1_000); const renewedAt: number[] = []; - const errors: unknown[] = []; + const gone: Array<{ reason: string }> = []; startLeaseRenewal({ clock, leaseId: "lse_1", - onError: (error) => errors.push(error), + onLeaseGone: (reason) => gone.push({ reason }), renew: () => { renewedAt.push(clock.now()); // A daemon answering with a deadline that is not in the future -- reachable with @@ -467,9 +528,10 @@ describe("startLeaseRenewal", () => { await flushMicrotasks(); expect(renewedAt).toEqual([1_250]); - // Nothing to renew towards: renewal ends rather than spinning at the floor forever. + // Nothing to renew towards: renewal ends -- and says so, rather than spinning at the floor + // forever or leaving the holder to infer it. expect(clock.pendingTimerCount).toBe(0); - expect(errors).toHaveLength(1); + expect(gone).toEqual([{ reason: "renew-failed" }]); clock.advance(600_000); await flushMicrotasks(); expect(renewedAt).toEqual([1_250]); diff --git a/src/lease-policy/index.ts b/src/lease-policy/index.ts index 1858a8774..13cb2e398 100644 --- a/src/lease-policy/index.ts +++ b/src/lease-policy/index.ts @@ -89,6 +89,18 @@ export interface RenewedLease { readonly ttlDeadline: number; } +/** + * Why renewal ended for good. Both mean "this holder no longer has a lease", and both are told + * to `onLeaseGone`; they differ in what a reader should conclude: + * + * - `renew-rejected`: the daemon answered `UNKNOWN_LEASE`/`FORBIDDEN` -- the lease is gone, or + * was never this principal's. Nothing was lost by this client. + * - `renew-failed`: renewal never got an answer it could use before the lease's own deadline + * passed (or the daemon answered with a deadline already behind us). The lease may still be + * alive on the daemon for a moment, but nothing here can keep it, and it will expire. + */ +export type LeaseGoneReason = "renew-rejected" | "renew-failed"; + export interface LeaseRenewalOptions { readonly clock: Clock; readonly leaseId: string; @@ -103,13 +115,14 @@ export interface LeaseRenewalOptions { */ readonly onError?: (error: unknown) => void; /** - * The lease is over: the daemon answered that it does not exist (`UNKNOWN_LEASE`) or is not - * this principal's (`FORBIDDEN`). Renewal has already stopped by the time this runs, and - * retrying would only repeat the same answer -- so a holder should treat this exactly like - * the `lease-lost` push (ADR 0003 §8) it may or may not also receive: stop holding, and do - * not try to release what is no longer there. Called at most once. + * The lease is over, for either of the reasons `LeaseGoneReason` names. Renewal has already + * stopped by the time this runs, and nothing it could do would bring the lease back -- so a + * holder should treat this exactly like the `lease-lost` push (ADR 0003 §8) it may or may + * not also receive: stop holding, and do not try to release what is no longer there. Called + * at most once, and it is the *only* end-of-lease signal this module raises: `onError` + * reports attempts that failed while the lease was still savable. */ - readonly onLeaseGone?: (error: unknown) => void; + readonly onLeaseGone?: (reason: LeaseGoneReason, error: unknown) => void; } export interface LeaseRenewal { @@ -183,16 +196,25 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { }; /** Isolated: a holder that cannot report a failure must still keep holding. */ - const notify = (listener: ((error: unknown) => void) | undefined, error: unknown): void => { - if (listener === undefined) return; + const report = (error: unknown): void => { + if (onError === undefined) return; try { - listener(error); + onError(error); } catch { // A `stderr` that throws (a closed pipe, say) must not take the release path down with // it -- see the `void tick()` below, which nothing awaits. } }; - const report = (error: unknown): void => notify(onError, error); + /** Ends renewal and says why, once. Isolated for the same reason `report` is. */ + const giveUp = (reason: LeaseGoneReason, error: unknown): void => { + stopped = true; + if (onLeaseGone === undefined) return; + try { + onLeaseGone(reason, error); + } catch { + // A holder that cannot handle the news still has to stop renewing, which it now has. + } + }; const schedule = (): void => { if (stopped) return; @@ -211,7 +233,14 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { // `Promise.resolve().then` rather than a bare call: a `renew` that throws *synchronously* // (a client that rejects a malformed input before it ever reaches the wire) is a failed // attempt like any other, not something that should escape into the unawaited `tick()`. - const request = Promise.resolve().then(() => renew(leaseId)); + // The `stopped` check inside it is what makes `stop()`'s "no further `renew` call" + // guarantee true even for a stop that lands in the microtask between the timer firing and + // the request going out. + const request = Promise.resolve().then(() => + stopped + ? Promise.reject(new Error(`Renewal of lease ${leaseId} was stopped before it was sent`)) + : renew(leaseId), + ); // An abandoned request still reaches the daemon: if it succeeds after this attempt has // been given up on, its deadline is real and worth keeping -- discarding it would let the // give-up test below fire against a deadline the daemon has already moved. (It also keeps @@ -256,18 +285,19 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { if (isLeaseGone(attempt.error)) { // Terminal, not transient: this lease is over, and the holder needs to hear that once // rather than read the same rejection on every retry until the deadline. - stopped = true; - notify(onLeaseGone, attempt.error); + giveUp("renew-rejected", attempt.error); return; } report(attempt.error); - // Out of runway: the lease is gone (or about to be), and another attempt would only - // produce another error. Reported separately from the attempt that failed, because - // "this one did not work" and "this lease will not be renewed again" are different - // things for a holder to read. + // Out of runway: the deadline has passed, so another attempt would only produce another + // error against a lease that is expiring. That is the end of this lease as far as any + // holder is concerned -- reported as such, not as one more failed attempt, so a frontend + // stops holding instead of sitting alive with no timer. if (clock.now() >= deadline) { - stopped = true; - report(new Error(`Gave up renewing lease ${leaseId}: its deadline has passed`)); + giveUp( + "renew-failed", + new Error(`Gave up renewing lease ${leaseId}: its deadline has passed`), + ); return; } schedule(); @@ -282,9 +312,11 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { } if (attempt.renewed.ttlDeadline <= clock.now()) { // A deadline that is not in the future cannot be renewed towards -- scheduling off it - // would be a hot loop against a lease that is already over. - stopped = true; - report(new Error(`Lease ${leaseId} was renewed to a deadline that has already passed`)); + // would be a hot loop against a lease that is already over, so this is an ending too. + giveUp( + "renew-failed", + new Error(`Lease ${leaseId} was renewed to a deadline that has already passed`), + ); return; } // The cadence follows the newest answer in both directions: the daemon may hand back a diff --git a/src/mcp/session.test.ts b/src/mcp/session.test.ts index 402115b4c..69cfc8d6e 100644 --- a/src/mcp/session.test.ts +++ b/src/mcp/session.test.ts @@ -380,66 +380,71 @@ describe("McpSession", () => { expect(clock.pendingTimerCount).toBe(0); }); - it("still releases on close when a tool call's own release is in flight and dies with the wire", async () => { + it("still sends its own release when a tool call's release is already in flight", async () => { const clock = new FakeClock(0); const client = new FakeSimlockClient(); client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); - const pending: Array<{ - resolve: (result: { leaseId: string }) => void; - reject: (error: Error) => void; - settled: boolean; - }> = []; + const pending: Array<(result: { leaseId: string }) => void> = []; client.releaseLeaseImpl = () => - new Promise<{ leaseId: string }>((resolve, reject) => { - const entry = { - reject: (error: Error) => { - entry.settled = true; - reject(error); - }, - resolve: (result: { leaseId: string }) => { - entry.settled = true; - resolve(result); - }, - settled: false, - }; - pending.push(entry); + new Promise<{ leaseId: string }>((resolve) => { + pending.push(resolve); }); - // What the real wire does when the connection closes: every request still waiting for an - // answer rejects (ADR 0003 §10). - client.onConnectionLost(() => { - for (const entry of pending) { - if (!entry.settled) - entry.reject(new SimlockError("DAEMON_CONNECTION_LOST", "transport", "gone", {})); - } - }); const session = new McpSession({ clock, connect: async () => client }); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); - // `close()` deliberately does not queue behind the tool-call serializer: it waits for the - // call in flight, but only so long. Here the daemon never answers that release, so the - // wait times out -- and skipping the farewell release because a tool call "has one on the - // way" would mean *no* release at all, since the wire kills that one a moment later. + // `close()` does not queue behind the tool-call serializer, so it can land while a + // `release_simulator` call is still waiting on the daemon. It waits for that call, then + // sends its own release anyway: deferring to the in-flight one would mean no release at + // all if the wire died first, and a duplicate only costs an `UNKNOWN_LEASE` it swallows. const releasing = session.release({ leaseId: "lease-1" }); await flushMicrotasks(); const closing = session.close(); await flushMicrotasks(); expect(client.calls.filter((call) => call.method === "releaseLease")).toHaveLength(1); - clock.advance(RELEASE_TIMEOUT_MS); + pending[0]?.({ leaseId: "lease-1" }); // the tool call's own release is answered + await expect(releasing).resolves.toMatchObject({ leaseId: "lease-1", released: true }); await flushMicrotasks(); expect(client.calls.filter((call) => call.method === "releaseLease")).toHaveLength(2); - pending[1]?.resolve({ leaseId: "lease-1" }); // the daemon answers the farewell release + pending[1]?.({ leaseId: "lease-1" }); await closing; - await expect(releasing).rejects.toMatchObject({ code: "DAEMON_CONNECTION_LOST" }); - - // Exactly one release completed -- the farewell one -- and the lease really is released. - expect(pending[1]?.settled, "the farewell release was answered").toBe(true); - expect(pending[0]?.settled, "the tool call's release died with the wire").toBe(true); expect(client.closeCalls).toBe(1); expect(clock.pendingTimerCount, "no bound outlives the close").toBe(0); }); + it("spends one shutdown budget in total, not one per step", async () => { + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + // A daemon that answers nothing: neither the tool call in flight nor the release that + // would follow it ever comes back. + client.listLeasesImpl = () => new Promise(() => {}); + client.releaseLeaseImpl = () => new Promise(() => {}); + const session = new McpSession({ clock, connect: async () => client }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + void session.status().catch(() => undefined); // in flight, never answered + await flushMicrotasks(); + + let closed = false; + const closing = session.close().then(() => { + closed = true; + }); + await flushMicrotasks(); + + // A budget per step -- one for the in-flight call, then one more for the lease -- would + // leave `simlock mcp` sitting here for a multiple of this after stdin EOF. + clock.advance(RELEASE_TIMEOUT_MS - 1); + await flushMicrotasks(); + expect(closed).toBe(false); + + clock.advance(1); + await closing; + expect(closed).toBe(true); + expect(client.closeCalls, "the wire closes when the budget is spent").toBe(1); + expect(clock.pendingTimerCount).toBe(0); + }); + it("releases a grant that lands after the session closed, and arms no timer for it", async () => { const clock = new FakeClock(0); const client = new FakeSimlockClient(); @@ -533,6 +538,34 @@ describe("McpSession", () => { expect(client.calls.filter((call) => call.method === "renewLease")).toHaveLength(1); }); + it("reports a lease it could not keep alive as lost, and releases nothing for it on close", async () => { + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + // Never terminal, never successful: the ladder retries until `sampleGrant`'s own 12_345 + // deadline passes and renewal gives up. + client.renewLeaseImpl = () => + Promise.reject(new SimlockError("INTERNAL", "domain", "could not persist", {})); + const session = new McpSession({ clock, connect: async () => client }); + const notices: unknown[] = []; + session.onLeaseLost((notice) => notices.push(notice)); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + clock.advance(4_115); + await flushMicrotasks(); + clock.advance(20_000); // the retry lands past the deadline + await flushMicrotasks(); + + expect(notices).toEqual([{ deviceId: "device-1", leaseId: "lease-1", reason: "renew-failed" }]); + expect(clock.pendingTimerCount).toBe(0); + + await session.close(); + expect( + client.calls.filter((call) => call.method === "releaseLease"), + "a lease that expired is not the session's to release", + ).toEqual([]); + }); + it("announces one ending once, even when the renewal and the daemon both report it", async () => { const clock = new FakeClock(0); const client = new FakeSimlockClient(); @@ -615,3 +648,29 @@ describe("toMcpErrorResult", () => { }); }); }); + +/** + * The double itself: MCP's tests are only worth what it is faithful to, and the one thing it + * has to get right is that a closed connection is dead (ADR 0003 §10) -- a fake that kept + * answering would let a test pass on a wire the real session had already closed. + */ +describe("FakeSimlockClient", () => { + it("rejects every call once closed, the way the wire does", async () => { + const client = new FakeSimlockClient(); + client.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); + client.getCatalogImpl = () => Promise.resolve({ platforms: [] }); + + await expect(client.releaseLease({ leaseId: "lease-1" })).resolves.toEqual({ + leaseId: "lease-1", + }); + + await client.close(); + + await expect(client.releaseLease({ leaseId: "lease-1" })).rejects.toMatchObject({ + code: "DAEMON_CONNECTION_LOST", + }); + await expect(client.getCatalog({})).rejects.toMatchObject({ + code: "DAEMON_CONNECTION_LOST", + }); + }); +}); diff --git a/src/mcp/session.ts b/src/mcp/session.ts index b9811e5f7..a825fce7e 100644 --- a/src/mcp/session.ts +++ b/src/mcp/session.ts @@ -23,6 +23,13 @@ import type { ReleaseSimulatorOutput, } from "./contracts.js"; +/** + * How many ended leases `#announceLeaseLost` remembers, to keep one ending from reaching a + * listener twice. Generous: a session holds one lease at a time in practice, so this is only + * ever reached by a session that has churned through many. + */ +const ANNOUNCED_LOST_LIMIT = 64; + export interface McpSessionOptions { /** * The `Clock` port (architecture rule 9): the session's renew timer and `close()`'s release @@ -101,9 +108,9 @@ export function toMcpErrorResult(error: unknown): McpErrorResult { * a cache of lease *state* (§11's point): it is only the id of the lease this session's own * `lease()` last obtained, kept so `status()` can tell that lease apart from any other lease * `lease.list` happens to return under the same owner principal -- see `status()`'s doc - * comment for why that distinction is load-bearing. Alongside it sits `#renewal`, the timer - * that keeps that lease alive (ADR 0004 §2); the two are started, stopped, and cleared - * together. + * comment for why that distinction is load-bearing. Alongside it sits `#renewals`, one timer + * per lease this session obtained (ADR 0004 §2): a lease enters it when `lease()` returns and + * leaves it the moment the session stops holding that lease, by release, by loss, or by close. */ export class McpSession { readonly #clock: Clock; @@ -268,9 +275,12 @@ export class McpSession { /** * `close()`'s tail: let the last tool call finish on a live wire, hand every lease back, then - * close. The wait is bounded because an in-flight `lease.request` can take minutes and an - * ending session cannot wait that long; past the bound the connection closes, the daemon - * rejects what was still pending, and any lease that slipped through ends at its deadline. + * close -- all inside **one** `RELEASE_TIMEOUT_MS` budget for the whole tail, not one per + * step. A session ending against an unresponsive daemon must cost a bounded wait, and "one + * timeout for the in-flight call plus one per lease" would let a dead daemon hold an MCP + * server open for a multiple of it. Whatever has not finished when the budget runs out is + * abandoned; the connection closes in the `finally`, the daemon rejects what was pending, + * and any lease that did not make it ends at its own deadline. */ async #endSession( client: SimlockClient, @@ -281,14 +291,22 @@ export class McpSession { await awaitWithin( this.#clock, RELEASE_TIMEOUT_MS, - inFlight, - "Timed out waiting for the last tool call to finish", + (async () => { + // `#mutations` never rejects (see `#mutate`), but a caller-supplied queue might. + await inFlight.catch(() => undefined); + for (const leaseId of heldLeaseIds) { + // One lease the daemon refuses (already expired, force-released) must not cost the + // rest of them their release. + await client.releaseLease({ leaseId }).catch(() => undefined); + } + })(), + "Timed out ending the session", ); } catch { // Bounded by design -- see above. + } finally { + await this.#closeClient(client); } - for (const leaseId of heldLeaseIds) await this.#releaseQuietly(client, leaseId); - await this.#closeClient(client); } /** @@ -297,6 +315,10 @@ export class McpSession { * answer never arrived), the connection may be dead, or the daemon may not answer at all -- * none of which should hold up an ending session, and all of which end the same way in the * daemon regardless, at the lease's deadline. + * + * Used by the grant-after-close path in `lease()`, which runs *inside* `#endSession`'s own + * budget: this bound is the fallback for a caller that is not already bounded, and the outer + * one wins whenever it is shorter. */ async #releaseQuietly(client: SimlockClient, leaseId: string): Promise { try { @@ -326,15 +348,12 @@ export class McpSession { const renewal = startLeaseRenewal({ clock: this.#clock, leaseId: lease.id, - onLeaseGone: () => { - // The daemon says this lease is gone or not ours: the same ending as the push, which + onLeaseGone: (reason) => { + // Renewal is over -- the daemon says the lease is gone or not ours, or it could not be + // kept alive to its deadline. Either way this is the same ending as the push, which // may never arrive (a lease that expired while this connection was away has nothing - // left to push about). - this.#reportLeaseLost({ - deviceId: lease.deviceId, - leaseId: lease.id, - reason: "renew-rejected", - }); + // left to push about), and the session must stop counting the lease as its own. + this.#reportLeaseLost({ deviceId: lease.deviceId, leaseId: lease.id, reason }); }, renew: (id) => client.renewLease({ leaseId: id }), ttlDeadline: lease.ttlDeadline, @@ -363,6 +382,13 @@ export class McpSession { #announceLeaseLost(notice: LeaseLostNotice): void { if (this.#announcedLost.has(notice.leaseId)) return; this.#announcedLost.add(notice.leaseId); + // Capped: a long-lived session that loses many leases must not accumulate their ids + // forever. A `Set` keeps insertion order, so this drops the oldest -- whose duplicate + // push, if it were ever coming, arrived long ago. + if (this.#announcedLost.size > ANNOUNCED_LOST_LIMIT) { + const oldest = this.#announcedLost.values().next().value; + if (oldest !== undefined) this.#announcedLost.delete(oldest); + } for (const listener of this.#leaseLostListeners) listener(notice); }