diff --git a/e2e/heartbeat-ttl.test.ts b/e2e/heartbeat-ttl.test.ts index c5d0176e9..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", @@ -44,12 +43,16 @@ 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 - // 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 + // still requires it to be at most heldTtlBackstopMs / 4, and 4_000ms is short. configOverrides: { lease: { detachedTtlMs: 4_000, heldTtlBackstopMs: 4_000, heartbeatIntervalMs: 800 }, }, @@ -98,16 +101,17 @@ 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); 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); @@ -122,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; @@ -137,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( @@ -145,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 acb63f63a..b7dc3ceb3 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, @@ -1335,6 +1336,437 @@ 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 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, + ); + + // 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.each(["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(); + 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("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); + + // 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" }, + }); + }); + + 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(); + 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(); + 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 () => { + 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,9 +2116,10 @@ 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, connectAdmin: async () => fakeClient(), connectExistingAdmin: async () => fakeClient(), readAdminTokenFile: async () => undefined, diff --git a/src/cli/index.ts b/src/cli/index.ts index 71da3c480..5f4891bb7 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -35,6 +35,12 @@ import { } from "../admin/index.js"; import type { Role } from "../contract/index.js"; import type { PassthroughCommand } from "../client/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"; @@ -108,12 +114,16 @@ 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 * 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. @@ -387,9 +397,9 @@ export function buildCliEnvironment( }; return { + clock, configPath, requesterId, - now: () => clock.now(), connectAdmin: (resolveCredential, options) => connect(autoLaunchIpc, resolveCredential, options), connectExistingAdmin: (resolveCredential, options) => connect(ipc, resolveCredential, options), @@ -706,7 +716,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 @@ -719,11 +733,29 @@ async function runLease( const leaseLostSignal = new Promise((resolve) => { notifyLeaseLost = resolve; }); - const offLeaseLost = client.onLeaseLost((push) => { - if (push.leaseId !== ourLeaseId) return; - environment.stderr.write(`${JSON.stringify({ push: "lease-lost", ...push })}\n`); + /** + * 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; + markLeaseLost(push); }); const offUnhealthy = client.onDeviceUnhealthy((push) => { environment.stderr.write(`${JSON.stringify({ push: "device-unhealthy", ...push })}\n`); @@ -731,6 +763,39 @@ 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 { + // 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 + // line rather than reverting to prose. + writeError(environment, error); + } + }; + let renewal: LeaseRenewal | undefined; try { const grant = await client.requestLease( { @@ -751,6 +816,8 @@ async function runLease( }, ); ourLeaseId = grant.lease.id; + // Owed from here on, whatever happens next -- see `releaseHeldLease`. + 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 }; @@ -758,22 +825,40 @@ 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. + renewal = startLeaseRenewal({ + clock: environment.clock, + leaseId: grant.lease.id, + ttlDeadline: grant.lease.ttlDeadline, + renew: (leaseId) => client.renewLease({ leaseId }), + // 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: 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); + }, + }); await Promise.race([termination.settled, leaseLostSignal]); - if (leaseLost) { - // The daemon already released it; asking again would only raise UNKNOWN_LEASE. - return LEASE_LOST_EXIT_CODE; - } - try { - 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; + // 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(); @@ -1052,7 +1137,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); diff --git a/src/lease-policy/index.test.ts b/src/lease-policy/index.test.ts new file mode 100644 index 000000000..f4eac5c9c --- /dev/null +++ b/src/lease-policy/index.test.ts @@ -0,0 +1,588 @@ +/** + * 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 { SimlockError } from "../contract/index.js"; +import { FakeClock } from "../ports/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); + 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 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, + }); + + 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"]); + + // 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, 5_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.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: Array<{ reason: string; error: unknown }> = []; + const errors: unknown[] = []; + let calls = 0; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + onError: (error) => errors.push(error), + onLeaseGone: (reason, error) => gone.push({ error, reason }), + renew: () => { + calls += 1; + return Promise.reject(leaseGoneError(code)); + }, + ttlDeadline: 30_000, + }); + + clock.advance(10_000); + await flushMicrotasks(); + + expect(gone).toHaveLength(1); + 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); + + 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"); + const errors: unknown[] = []; + const attemptsAt: number[] = []; + let failuresLeft = 1; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + onError: (error) => errors.push(error), + renew: () => { + 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]); + + 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("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")); + }, + ttlDeadline: 3_000, + }); + + // 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. 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(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); + await flushMicrotasks(); + 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 () => { + 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 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); + expect(calls).toBe(1); + + clock.advance(1_333); + await flushMicrotasks(); + 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[] = []; + 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) + 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(gone.at(-1)?.reason).toBe("renew-failed"); + }); + + 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("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; + 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("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 gone: Array<{ reason: string }> = []; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + onLeaseGone: (reason) => gone.push({ reason }), + renew: () => { + renewedAt.push(clock.now()); + // 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, + }); + + clock.advance(249); + await flushMicrotasks(); + expect(renewedAt).toEqual([]); + clock.advance(1); + await flushMicrotasks(); + expect(renewedAt).toEqual([1_250]); + + // 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(gone).toEqual([{ reason: "renew-failed" }]); + clock.advance(600_000); + await flushMicrotasks(); + 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 new file mode 100644 index 000000000..13cb2e398 --- /dev/null +++ b/src/lease-policy/index.ts @@ -0,0 +1,336 @@ +/** + * 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. + * + * 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"; + +/** 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 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; + +/** + * 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 + * 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; +} + +/** + * 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; + /** 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 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, 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?: (reason: LeaseGoneReason, error: unknown) => void; +} + +export interface LeaseRenewal { + /** + * 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; +} + +/** The delay before the next renewal, given how much of the TTL is left. */ +function renewDelayMs(remainingMs: number): number { + const delay = Math.max(MINIMUM_RENEW_DELAY_MS, Math.floor(remainingMs / RENEW_DIVISOR)); + return Math.min(MAXIMUM_RENEW_DELAY_MS, delay); +} + +type Attempt = + | { 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 + * 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()`. + * + * 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 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, 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. */ + let timer: TimerHandle | undefined; + let stopped = false; + /** 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; + + const cancelTimer = (): void => { + if (timer === undefined) return; + clock.cancel(timer); + 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. + } + }; + /** 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; + timer = clock.setTimer(renewDelayMs(deadline - clock.now()), () => { + timer = undefined; + // 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 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()`. + // 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 + // a late rejection from surfacing as an unhandled rejection.) + request.then( + (renewed) => { + // 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; + newestAnswered = attemptId; + deadline = renewed.ttlDeadline; + }, + () => undefined, + ); + return Promise.race([ + request.then( + (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, + }); + }); + }), + ]); + }; + + const tick = async (): Promise => { + if (stopped) return; + const attempt = await attemptRenew(); + cancelTimer(); + 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. + giveUp("renew-rejected", attempt.error); + return; + } + report(attempt.error); + // 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) { + giveUp( + "renew-failed", + new Error(`Gave up renewing lease ${leaseId}: its deadline has passed`), + ); + return; + } + schedule(); + return; + } + + // 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, 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 + // *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(); + }; + + schedule(); + + return { + stop: (): void => { + stopped = true; + cancelTimer(); + }, + }; +} diff --git a/src/mcp/connect.ts b/src/mcp/connect.ts index 81404d7ad..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; @@ -65,7 +67,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..002f176e4 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; @@ -65,8 +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, connect: environment.connect ?? defaults.connect, }); const server = (environment.createServer ?? createMcpServer)(session); @@ -140,19 +147,20 @@ 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 { 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..69cfc8d6e 100644 --- a/src/mcp/session.test.ts +++ b/src/mcp/session.test.ts @@ -1,9 +1,16 @@ 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"; +/** 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 +22,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 +41,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 +54,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 +65,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 +95,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 +132,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 +154,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 +173,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 +200,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 +217,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 +236,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 +250,371 @@ 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("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 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<(result: { leaseId: string }) => void> = []; + client.releaseLeaseImpl = () => + new Promise<{ leaseId: string }>((resolve) => { + pending.push(resolve); + }); + const session = new McpSession({ clock, connect: async () => client }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + // `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); + + 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]?.({ leaseId: "lease-1" }); + await closing; + 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(); + 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 flushMicrotasks(); + + // 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" }, + ]); + 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 () => { + 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("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("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(); + 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(); + 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[] = []; @@ -280,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 3cc956f6a..a825fce7e 100644 --- a/src/mcp/session.ts +++ b/src/mcp/session.ts @@ -2,9 +2,17 @@ import { isSimlockError, SimlockError, type LeaseProgress, + type LeaseRecord, type LeaseRequestInput, type SimlockClient, } from "../client/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, @@ -15,7 +23,19 @@ 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 + * 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 +104,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 `#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; readonly #connect: () => Promise; #client: SimlockClient | undefined; #connecting: Promise | undefined; @@ -107,8 +130,20 @@ 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" -- 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. + */ + readonly #renewals = new Map(); + /** 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; this.#connect = options.connect; } @@ -125,7 +160,17 @@ 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: 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(); + } this.#heldLeaseId = grant.lease.id; + this.#startRenewal(client, grant.lease); return grant; }); } @@ -135,7 +180,13 @@ export class McpSession { this.#throwIfClosed(); const client = await this.#clientForUse(); 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. + this.#forgetLease(result.leaseId); return { ...result, released: true }; }); } @@ -187,19 +238,182 @@ 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. + * + * 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; this.#closed = true; + // 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 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.#closeClient(client); + this.#closePromise = + client === undefined ? Promise.resolve() : this.#endSession(client, heldLeaseIds, inFlight); return this.#closePromise; } + /** + * `close()`'s tail: let the last tool call finish on a live wire, hand every lease back, then + * 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, + heldLeaseIds: readonly string[], + inFlight: Promise, + ): Promise { + try { + await awaitWithin( + this.#clock, + RELEASE_TIMEOUT_MS, + (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); + } + } + + /** + * 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. + * + * 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 { + 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 + * quietly reconnecting behind the tool surface -- reconnect stays a decision the next tool + * call makes (`#clientForUse`). + */ + #startRenewal(client: SimlockClient, lease: LeaseRecord): void { + 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. + const renewal = startLeaseRenewal({ + clock: this.#clock, + leaseId: lease.id, + 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), 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, + }); + this.#renewals.set(lease.id, renewal); + } + + /** + * 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 (!this.#renewals.has(notice.leaseId)) return; + this.#stopRenewal(notice.leaseId); + if (this.#heldLeaseId === notice.leaseId) 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); + // 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); + } + + /** 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; + } + /** * 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,8 +461,11 @@ export class McpSession { #wireClient(client: SimlockClient): void { this.#clientUnsubscribers = [ client.onLeaseLost((push) => { - if (push.leaseId === this.#heldLeaseId) this.#heldLeaseId = undefined; - for (const listener of this.#leaseLostListeners) listener(push); + // 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) => { for (const listener of this.#deviceHealthListeners) { diff --git a/src/mcp/test-support.ts b/src/mcp/test-support.ts index 8a8e5fcaa..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,58 +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); } - // 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); + 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 { @@ -181,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 { 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