diff --git a/e2e/capacity-cleanup-nuke.test.ts b/e2e/capacity-cleanup-nuke.test.ts index 26dc82cae..da31fa724 100644 --- a/e2e/capacity-cleanup-nuke.test.ts +++ b/e2e/capacity-cleanup-nuke.test.ts @@ -36,7 +36,8 @@ async function deviceRows( return result.json as { id: string; driverDeviceId: string; state: string }[]; } -function leaseHeld( +/** Starts a `simlock lease` that stays alive, renewing its own lease (ADR 0004 §2). */ +function leaseHolder( env: Awaited>, agentId: string, ): CliBackgroundHandle { @@ -57,11 +58,13 @@ async function releaseAndForget( env: Awaited>, agentId: string, ): Promise { - const held = leaseHeld(env, agentId); - const grant = JSON.parse(await held.firstStdoutLine()) as { lease: { id: string } }; + const holder = leaseHolder(env, agentId); + const grant = JSON.parse(await holder.firstStdoutLine()) as { lease: { id: string } }; + // Released explicitly, before the process is killed: a SIGKILLed holder frees nothing + // (ADR 0004 §3), so the release has to be its own step for the device to come back. await env.cli(["release", grant.lease.id]); - held.kill("SIGKILL"); - await held.waitForExit(15_000).catch(() => undefined); + holder.kill("SIGKILL"); + await holder.waitForExit(15_000).catch(() => undefined); } /** @@ -96,7 +99,7 @@ describe("capacity, warm pool, cleanup, and nuke", () => { ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, }); - const first = leaseHeld(env, "cap-a"); + const first = leaseHolder(env, "cap-a"); const grantA = JSON.parse(await first.firstStdoutLine()) as { lease: { id: string }; device: { driverDeviceId: string }; @@ -104,7 +107,7 @@ describe("capacity, warm pool, cleanup, and nuke", () => { // maxRunning (2) has room, but maxDevices (1) does not: a second requester must // still queue, because there is no second device to provision. - const second = leaseHeld(env, "cap-b"); + const second = leaseHolder(env, "cap-b"); await waitFor(() => second.progressEvents().some((event) => isQueuedAt(event, 1)), { label: "second requester queues on the managed-device limit, not the running limit", }); @@ -142,12 +145,16 @@ describe("capacity, warm pool, cleanup, and nuke", () => { }; expect(grantB.device.driverDeviceId).toBe(grantA.device.driverDeviceId); + // `second` still holds `grantB`, and a SIGKILL would leave it standing for the whole + // TTL (ADR 0004 §3), so it is released explicitly before the processes are torn down. + await env.cli(["release", grantB.lease.id]); first.kill("SIGKILL"); second.kill("SIGKILL"); await Promise.all([ first.waitForExit(15_000).catch(() => undefined), second.waitForExit(15_000).catch(() => undefined), ]); + await waitForLeaseCount(env, 0); }); it("reports overLimit when a lowered running limit can't yet be met, without evicting existing leases", async () => { @@ -158,11 +165,10 @@ describe("capacity, warm pool, cleanup, and nuke", () => { ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, }); - // Detached, not held: a graceful `daemon stop` (which `withConfig` triggers to - // pick up the new limit) releases every held-mode lease as part of closing its - // owning connection -- exactly like a normal held-mode client disconnecting. A - // detached lease has no owning connection, so it survives the restart, which is - // what actually exercises "a lowered limit doesn't evict an existing lease". + // `--detach`, so no holder process has to stay alive across the `daemon stop` that + // `withConfig` triggers to pick up the new limit. The leases themselves survive that + // stop either way now (ADR 0004 §3), which is what lets this exercise "a lowered limit + // doesn't evict an existing lease" against a genuinely still-leased device. const leaseOne = await env.cli([ "lease", "--platform", @@ -219,14 +225,14 @@ describe("capacity, warm pool, cleanup, and nuke", () => { ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, }); - const heldX = leaseHeld(env, "idle-x"); - const grantX = JSON.parse(await heldX.firstStdoutLine()) as { + const holderX = leaseHolder(env, "idle-x"); + const grantX = JSON.parse(await holderX.firstStdoutLine()) as { lease: { id: string }; device: { driverDeviceId: string }; }; await env.cli(["release", grantX.lease.id]); - heldX.kill("SIGKILL"); - await heldX.waitForExit(15_000).catch(() => undefined); + holderX.kill("SIGKILL"); + await holderX.waitForExit(15_000).catch(() => undefined); await waitForDeviceState(env, grantX.device.driverDeviceId, "ready"); await waitForCleanupToReach(env, grantX.device.driverDeviceId, "shutdown"); @@ -259,14 +265,14 @@ describe("capacity, warm pool, cleanup, and nuke", () => { "--dry-run must never call a destructive/state-changing driver verb", ).toEqual([]); - // nuke: force-releases held leases, clears the queue, destroys registry devices, + // nuke: force-releases every lease, clears the queue, destroys registry devices, // and must never touch a device the driver reports but the registry doesn't know // about (safety.md: registry-only destruction). - const heldForNuke = leaseHeld(env, "nuke-held"); + const heldForNuke = leaseHolder(env, "nuke-held"); await heldForNuke.firstStdoutLine(); // Managed devices are already at 2/2 and running at 1/1 from the idle/dry-run // phase above, so this requester has no device to reuse or provision and queues. - const queuedForNuke = leaseHeld(env, "nuke-queued"); + const queuedForNuke = leaseHolder(env, "nuke-queued"); await waitFor(() => queuedForNuke.progressEvents().some((event) => isQueuedAt(event, 1)), { label: "a waiter is queued before nuke", }); diff --git a/e2e/doctor-drift.test.ts b/e2e/doctor-drift.test.ts index 21252159a..f13d16595 100644 --- a/e2e/doctor-drift.test.ts +++ b/e2e/doctor-drift.test.ts @@ -24,7 +24,7 @@ async function deviceRows(env: Awaited>): Promise< return result.json as DeviceRow[]; } -/** Launches a held-mode lease for `agentId`; caller launches every agent it needs +/** Launches a `simlock lease` holder for `agentId`; caller launches every agent it needs * before awaiting any of their grants, so none is warm-pool reused for the next * (a sequential lease/release/lease would just reuse the same warm device). */ function leaseHeld( diff --git a/e2e/error-exit-codes.test.ts b/e2e/error-exit-codes.test.ts index c4d6df30b..5b8631c72 100644 --- a/e2e/error-exit-codes.test.ts +++ b/e2e/error-exit-codes.test.ts @@ -84,13 +84,13 @@ describe("error and exit-code table", () => { expectStructuredFailure(result, 1, "UNKNOWN_LEASE"); }); - it("lease renew on a held-mode lease -> exit 0 with a later deadline", async () => { + it("lease renew on a running holder's lease -> exit 0 with a later deadline", async () => { const env = await withDaemon(); await env.driverScript.set({ ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, }); - const held = env.cliBackground([ + const holder = env.cliBackground([ "lease", "--platform", "ios", @@ -99,9 +99,11 @@ describe("error and exit-code table", () => { "--os", "18.4", "--agent-id", - "flow4-held", + "flow4-holder", ]); - const grant = JSON.parse(await held.firstStdoutLine()) as { lease: { id: string } }; + const grant = JSON.parse(await holder.firstStdoutLine()) as { + lease: { id: string; ttlMs: number }; + }; try { const rows = await waitForLeaseCount(env, 1); @@ -114,15 +116,15 @@ describe("error and exit-code table", () => { const result = await env.cli(["lease", "renew", grant.lease.id]); expect(result.code).toBe(0); expect(result.stderr).toBe(""); - const renewed = result.json as { id: string; mode: string; ttlDeadline: number }; + const renewed = result.json as { id: string; ttlMs: number; ttlDeadline: number }; expect(renewed.id).toBe(grant.lease.id); - expect(renewed.mode).toBe("held"); - // A held-mode lease used to have no escape hatch: renewal now resets its - // backstop deadline exactly like a detached lease's, instead of rejecting. + // ADR 0004: one kind of lease, and a body-less renew re-applies its own stored width + // rather than any mode-shaped default. + expect(renewed.ttlMs).toBe(grant.lease.ttlMs); expect(renewed.ttlDeadline).toBeGreaterThan(beforeDeadline); } finally { - held.kill("SIGTERM"); - await held.waitForExit(15_000); + holder.kill("SIGTERM"); + await holder.waitForExit(15_000); } }); }); diff --git a/e2e/heartbeat-ttl.test.ts b/e2e/heartbeat-ttl.test.ts deleted file mode 100644 index b5ff0f1f0..000000000 --- a/e2e/heartbeat-ttl.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { readFile } from "node:fs/promises"; -import { describe, expect, it } from "vitest"; - -import { waitFor, withDaemon } from "./helpers/index.js"; - -interface LeaseRow { - readonly id: string; - readonly requesterId: string; - readonly ttlDeadline: number; -} - -async function leaseRows(env: Awaited>): Promise { - const result = await env.cli(["list", "--leases"]); - if (result.code !== 0) throw new Error(`simlock list --leases failed: ${result.stderr}`); - return result.json as LeaseRow[]; -} - -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", - configOverrides: { lease: { heldTtlBackstopMs: 4_000, heartbeatIntervalMs: 2_000 } }, - }); - - // Every command auto-starts on demand; the daemon process crashes on the bad - // config before it ever opens its socket, so the CLI retries for its startup - // window and then gives up -- surfaced as an INTERNAL timeout, not a specific - // config error code (the CLI never got a response to relay). - const result = await env.cli(["catalog", "--json"], { timeout: 15_000 }); - expect(result.code).toBe(1); - expect(result.error?.code).toBe("INTERNAL"); - - await waitFor( - async () => { - try { - const log = await readFile(env.logPath, "utf8"); - return log.includes("lease.heartbeatIntervalMs"); - } catch { - return false; - } - }, - { timeout: 10_000, label: "daemon.log names the offending config key" }, - ); - }); - - 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 -- 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 }, - }, - }); - await env.driverScript.set({ - ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, - }); - - const mcp = await env.mcpClient({ env: { SIMLOCK_AGENT_ID: "flow6-mcp" } }); - const cliHeld = env.cliBackground([ - "lease", - "--platform", - "ios", - "--device", - "iPhone 16", - "--os", - "18.4", - "--agent-id", - "flow6-cli", - ]); - - try { - const leaseResult = await mcp.client.callTool({ - name: "lease_simulator", - arguments: { model: "iPhone 16", osVersion: "18.4", platform: "ios" }, - }); - const mcpLease = leaseResult.structuredContent as { - lease: { id: string; ttlDeadline: number }; - }; - - const cliGrant = JSON.parse(await cliHeld.firstStdoutLine()) as { - lease: { id: string; ttlDeadline: number }; - }; - - const detachedResult = await env.cli([ - "lease", - "--platform", - "ios", - "--device", - "iPhone 16", - "--os", - "18.4", - "--agent-id", - "flow6-detached", - "--detach", - ]); - const detachedGrant = detachedResult.json as { lease: { id: string } }; - - // 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 (unrenewed) lease expires at its TTL" }, - ); - - const rowsAfterExpiry = await leaseRows(env); - const mcpRow = rowsAfterExpiry.find((row) => row.id === mcpLease.lease.id); - const cliRow = rowsAfterExpiry.find((row) => row.id === cliGrant.lease.id); - expect( - mcpRow, - "MCP lease should have survived past the detached lease's expiry", - ).toBeDefined(); - expect( - cliRow, - "CLI held lease should have survived past the detached lease's expiry", - ).toBeDefined(); - expect(mcpRow?.ttlDeadline).toBeGreaterThan(mcpLease.lease.ttlDeadline); - expect(cliRow?.ttlDeadline).toBeGreaterThan(cliGrant.lease.ttlDeadline); - - const statusResult = await mcp.client.callTool({ name: "lease_status", arguments: {} }); - const statusExpiry = (statusResult.structuredContent as { ttlDeadline: number }).ttlDeadline; - expect(statusExpiry).toBeGreaterThan(mcpLease.lease.ttlDeadline); - - const recorded = await env.events(); - expect( - recorded.filter( - (entry) => - entry.event === "lease.renewed" && - (entry.payload as { leaseId?: string }).leaseId === mcpLease.lease.id, - ).length, - "expected repeated lease.renewed events for the renewing MCP lease", - ).toBeGreaterThan(1); - expect( - recorded.filter( - (entry) => - entry.event === "lease.renewed" && - (entry.payload as { leaseId?: string }).leaseId === cliGrant.lease.id, - ).length, - "expected repeated lease.renewed events for the renewing CLI lease", - ).toBeGreaterThan(1); - expect(recorded).toContainEqual( - expect.objectContaining({ - event: "lease.expired", - payload: expect.objectContaining({ leaseId: detachedGrant.lease.id }), - }), - ); - - await mcp.client.callTool({ - name: "release_simulator", - arguments: { leaseId: mcpLease.lease.id }, - }); - } finally { - cliHeld.kill("SIGKILL"); - await cliHeld.waitForExit(15_000).catch(() => undefined); - await mcp.close(); - } - }); -}); diff --git a/e2e/held-lease-liveness.test.ts b/e2e/held-lease-liveness.test.ts index dfb0e778d..0a4b7d5a9 100644 --- a/e2e/held-lease-liveness.test.ts +++ b/e2e/held-lease-liveness.test.ts @@ -2,14 +2,22 @@ import { describe, expect, it } from "vitest"; import { waitForDeviceState, waitForLeaseCount, withDaemon } from "./helpers/index.js"; -describe("held-lease liveness & restart", () => { - it("killing the held CLI process releases its lease", async () => { - const env = await withDaemon(); +/** + * Lease liveness end to end under ADR 0004: a lease is TTL-bound, a client-initiated + * `lease.renew` is the only thing that keeps it alive, and nothing about a connection -- + * its close, its daemon's death, or a restart -- ends one. + */ +describe("lease liveness & restart", () => { + it("keeps a SIGKILLed holder's lease until it expires, then frees the device", async () => { + // The one behaviour change a local user notices (ADR 0004's Consequences): a holder that + // cannot run its own release path holds its device until `ttlDeadline`. A short TTL is + // the bound, which is why this env sets one. + const env = await withDaemon({ configOverrides: { lease: { defaultTtlMs: 5_000 } } }); await env.driverScript.set({ ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, }); - const held = env.cliBackground([ + const holder = env.cliBackground([ "lease", "--platform", "ios", @@ -20,27 +28,33 @@ describe("held-lease liveness & restart", () => { "--agent-id", "flow5-killed", ]); - const grant = JSON.parse(await held.firstStdoutLine()) as { + const grant = JSON.parse(await holder.firstStdoutLine()) as { lease: { id: string }; device: { driverDeviceId: string }; }; await waitForLeaseCount(env, 1); - held.kill("SIGKILL"); - await held.waitForExit(15_000); + holder.kill("SIGKILL"); + await holder.waitForExit(15_000); - await waitForLeaseCount(env, 0); + // Killed outright, so nothing released: the lease is still there right after the holder + // is gone, with its device still leased. + const leases = (await env.cli(["list", "--leases"])).json as { id: string }[]; + expect(leases.map((lease) => lease.id)).toContain(grant.lease.id); + + // Its own deadline is what ends it -- nothing renews it any more. + await waitForLeaseCount(env, 0, { timeout: 30_000 }); await waitForDeviceState(env, grant.device.driverDeviceId, "ready"); - await env.expectEvents(["lease.granted", "lease.released"]); + await env.expectEvents(["lease.granted", "lease.expired"]); }); - it("orphan-sweeps a held lease still persisted across a daemon restart", async () => { - const env = await withDaemon(); + it("releases at once when a holder exits gracefully, without waiting for the TTL", async () => { + const env = await withDaemon({ configOverrides: { lease: { defaultTtlMs: 600_000 } } }); await env.driverScript.set({ ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, }); - const held = env.cliBackground([ + const holder = env.cliBackground([ "lease", "--platform", "ios", @@ -49,44 +63,87 @@ describe("held-lease liveness & restart", () => { "--os", "18.4", "--agent-id", - "flow5-orphaned", + "flow5-sigterm", ]); - const grant = JSON.parse(await held.firstStdoutLine()) as { + const grant = JSON.parse(await holder.firstStdoutLine()) as { lease: { id: string }; device: { driverDeviceId: string }; }; await waitForLeaseCount(env, 1); - // Kill the daemon out from under the holder (not a graceful `daemon stop`) so the - // lease is left `held` in the persisted registry with no live connection -- - // exactly the case StartupConverger's orphan sweep exists for. - await env.killDaemon("SIGKILL"); - await env.startDaemon(); + // Release-on-exit is the holder's own policy (ADR 0004 §2), and it is what makes a + // normal exit still free the device immediately -- the ten-minute TTL above never + // comes into it. + holder.kill("SIGTERM"); + const exit = await holder.waitForExit(15_000); + expect(exit.code).toBe(0); await waitForLeaseCount(env, 0); await waitForDeviceState(env, grant.device.driverDeviceId, "ready"); - - const recorded = await env.events(); + const recorded = await env.expectEvents(["lease.granted", "lease.released"]); expect(recorded).toContainEqual( expect.objectContaining({ event: "lease.released", - payload: expect.objectContaining({ leaseId: grant.lease.id, reason: "orphaned" }), + payload: expect.objectContaining({ leaseId: grant.lease.id, reason: "explicit" }), }), ); - - held.kill("SIGKILL"); - await held.waitForExit(15_000).catch(() => undefined); }); - it("a detached lease survives a restart with its TTL timer restored", async () => { - const env = await withDaemon({ - // Generous relative to the default (900_000ms) but still short enough to keep the - // test fast; needs enough headroom that a restart (which now waits, best-effort, - // for the previous daemon process to fully exit -- see helpers/env.ts) can't - // itself eat into the TTL window before the "still there right after restart" - // check below runs. - configOverrides: { lease: { detachedTtlMs: 15_000, heartbeatIntervalMs: 500 } }, + it("keeps a lease across an ungraceful daemon restart, with its TTL timer restored", async () => { + // 30s, not 15: a kill-and-restart sits inside this window (and waits, best-effort, for the + // old process to be gone), so a tighter TTL could expire the lease before the "still there + // right after the restart" check runs and turn a real regression into a flake. + const env = await withDaemon({ configOverrides: { lease: { defaultTtlMs: 30_000 } } }); + await env.driverScript.set({ + ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, }); + + const holder = env.cliBackground([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--agent-id", + "flow5-restart", + ]); + const grant = JSON.parse(await holder.firstStdoutLine()) as { + lease: { id: string }; + device: { driverDeviceId: string }; + }; + await waitForLeaseCount(env, 1); + + // Kill the daemon out from under the holder (not a graceful `daemon stop`), leaving the + // lease persisted with no live connection. Pre-ADR-0004 this is exactly what + // `StartupConverger`'s orphan sweep released; it no longer exists, because a restart + // proves nothing about whether a holder is alive. + await env.killDaemon("SIGKILL"); + await env.startDaemon(); + + const afterRestart = (await env.cli(["list", "--leases"])).json as { id: string }[]; + expect(afterRestart.map((lease) => lease.id)).toContain(grant.lease.id); + + // The holder itself does not survive the restart -- the CLI never reconnects (ADR 0003 + // §10) -- so it writes one DAEMON_CONNECTION_LOST line naming the still-standing lease + // and exits 1, releasing nothing. + const exit = await holder.waitForExit(15_000); + expect(exit.code).toBe(1); + expect(exit.error?.code).toBe("DAEMON_CONNECTION_LOST"); + // The message names the lease and the deadline a later invocation has to beat. + expect(exit.error?.message).toContain(grant.lease.id); + expect(exit.error?.message).toContain("ttlDeadline"); + + // With nothing left renewing it, the restored timer expires the lease on its own + // deadline: the record persisted, and so did the deadline it carried. + await waitForLeaseCount(env, 0, { timeout: 45_000 }); + await waitForDeviceState(env, grant.device.driverDeviceId, "ready"); + await env.expectEvents(["lease.expired"]); + }); + + it("survives a graceful daemon stop and can be renewed from a later invocation", async () => { + const env = await withDaemon({ configOverrides: { lease: { defaultTtlMs: 120_000 } } }); await env.driverScript.set({ ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, }); @@ -104,29 +161,28 @@ describe("held-lease liveness & restart", () => { "--detach", ]); expect(lease.code).toBe(0); - const grant = lease.json as { - lease: { id: string }; - device: { driverDeviceId: string }; - }; + const grant = lease.json as { lease: { id: string; ttlDeadline: number } }; - // The event ring buffer resets on restart (documented behaviour, ARCHITECTURE.md), - // so check "granted" happened before the restart wipes it, and only look for - // "expired" afterwards. + // The event ring buffer resets on restart (documented behaviour, ARCHITECTURE.md), so + // check "granted" happened before the restart wipes it. await env.expectEvents(["lease.requested", "lease.granted"]); + // ADR 0004 §3: `daemon stop` does not touch leases -- they persist, and the next daemon + // restores each one's timer from its own deadline. await env.restartDaemon(); - // Still there immediately after restart -- the lease was not dropped. - const leasesAfterRestart = await env.cli(["list", "--leases"]); - expect(leasesAfterRestart.json).toEqual( - expect.arrayContaining([expect.objectContaining({ id: grant.lease.id })]), - ); + const leasesAfterRestart = (await env.cli(["list", "--leases"])).json as { id: string }[]; + expect(leasesAfterRestart.map((row) => row.id)).toContain(grant.lease.id); - // If the TTL timer were not restored (rather than merely the lease record - // persisting), it would never expire and this would time out. - await waitForLeaseCount(env, 0, { timeout: 30_000 }); - await waitForDeviceState(env, grant.device.driverDeviceId, "ready"); + // And it is still renewable across that restart, which is the whole point of the lease + // outliving the connection that asked for it. + const renewed = await env.cli(["lease", "renew", grant.lease.id]); + expect(renewed.code).toBe(0); + expect((renewed.json as { ttlDeadline: number }).ttlDeadline).toBeGreaterThan( + grant.lease.ttlDeadline, + ); - await env.expectEvents(["lease.expired"]); + await env.cli(["release", grant.lease.id]); + await waitForLeaseCount(env, 0); }); }); diff --git a/e2e/http-api.test.ts b/e2e/http-api.test.ts index b30034fac..df3d83201 100644 --- a/e2e/http-api.test.ts +++ b/e2e/http-api.test.ts @@ -207,4 +207,105 @@ describe("HTTP API", () => { const afterRelease = await fetch(`${baseUrl}/v1/leases/${lease.id}`, { headers: agentAuth }); expect(afterRelease.status).toBe(404); }); + + it("refuses a ttlMs above lease.maxTtlMs on both routes, whatever shape the request takes", async () => { + // ADR 0004 §4 and docs/HTTP-API.md: over the cap is `400 BAD_REQUEST`, never a silent + // clamp and never a `201` that fails later on the request resource. + const port = await reservePort(); + const env = await withDaemon({ + configOverrides: { + http: { enabled: true, host: "127.0.0.1", port }, + lease: { defaultTtlMs: 60_000, maxTtlMs: 120_000 }, + }, + }); + await env.driverScript.set({ + ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, + }); + const baseUrl = `http://127.0.0.1:${port}`; + + const token = await env.cli(["token", "create", "--role", "agent"]); + expect(token.code).toBe(0); + const agentAuth = { + authorization: `Bearer ${(token.json as { secret: string }).secret}`, + }; + const postJson = (path: string, body: unknown): Promise => + fetch(`${baseUrl}${path}`, { + method: "POST", + headers: { ...agentAuth, "content-type": "application/json" }, + body: JSON.stringify(body), + }); + + const overCap = await postJson("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/v1/lease-requests", { + platform: "ios", + device: "iPhone 16", + os: "18.4", + ttlMs: 120_001, + }); + expect(overCap.status).toBe(400); + expect((await overCap.json()) as { error: { code: string } }).toMatchObject({ + error: { code: "BAD_REQUEST" }, + }); + + // The same request with `allowDownload: true`, which settles its own `201` synchronously + // rather than waiting on the dispatch -- the case that used to slip past the cap and fail + // later on the request resource instead. + const overCapWithDownload = await postJson("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/v1/lease-requests", { + platform: "ios", + device: "iPhone 16", + os: "18.4", + allowDownload: true, + ttlMs: 120_001, + }); + expect(overCapWithDownload.status).toBe(400); + expect((await overCapWithDownload.json()) as { error: { code: string } }).toMatchObject({ + error: { code: "BAD_REQUEST" }, + }); + + // Nothing was admitted by either refusal. + expect((await env.cli(["list", "--leases"])).json).toEqual([]); + + // At the cap it is granted, and the width it asked for is what the lease carries. + const granted = await postJson("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/v1/lease-requests", { + platform: "ios", + device: "iPhone 16", + os: "18.4", + ttlMs: 120_000, + }); + expect(granted.status).toBe(201); + const requestId = ((await granted.json()) as { request: { id: string } }).request.id; + let lease: LeasePayload | undefined; + await waitFor( + async () => { + const response = await fetch(`${baseUrl}/v1/lease-requests/${requestId}?wait=10`, { + headers: agentAuth, + }); + const body = (await response.json()) as { + request: { state: string; lease?: LeasePayload }; + }; + lease = body.request.lease; + return body.request.state === "granted"; + }, + { timeout: 30_000, label: "the at-cap request is granted" }, + ); + expect(lease?.ttlMs).toBe(120_000); + + // And the renew route answers the cap the same way. + const renewOverCap = await postJson(`/v1/leases/${lease?.id ?? ""}/renew`, { ttlMs: 120_001 }); + expect(renewOverCap.status).toBe(400); + expect((await renewOverCap.json()) as { error: { code: string } }).toMatchObject({ + error: { code: "BAD_REQUEST" }, + }); + + // A body-less renew still re-applies the lease's own width. + const renewed = await fetch(`${baseUrl}/v1/leases/${lease?.id ?? ""}/renew`, { + method: "POST", + headers: agentAuth, + }); + expect(renewed.status).toBe(200); + expect((await env.cli(["list", "--leases"])).json).toEqual([ + expect.objectContaining({ id: lease?.id, ttlMs: 120_000 }), + ]); + + await env.cli(["release", lease?.id ?? ""]); + }); }); diff --git a/e2e/mcp-session.test.ts b/e2e/mcp-session.test.ts index 33224441d..2ab06d8e4 100644 --- a/e2e/mcp-session.test.ts +++ b/e2e/mcp-session.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { withDaemon } from "./helpers/index.js"; +import { waitFor, withDaemon } from "./helpers/index.js"; interface McpErrorPayload { readonly code: string; @@ -92,10 +92,12 @@ describe("MCP session semantics", () => { }); expect(warning.logger).toBe("simlock"); expect(warning.level).toBe("warning"); + // `killed`: an operator took the lease away, which is not the same fact as its holder + // releasing it (docs/EVENTS.md, and `Dispatcher#leaseReleaseAll`). expect(warning.data).toMatchObject({ deviceId: expect.any(String), leaseId: leased.lease.id, - reason: "explicit", + reason: "killed", }); const statusAfter = await mcp.client.callTool({ name: "lease_status", arguments: {} }); @@ -126,12 +128,16 @@ describe("MCP session semantics", () => { } }); - // Regression for PR #35 ("reconnect the session after a daemon restart"): before - // that fix, an MCP server whose daemon connection died mid-session would surface - // the *next* tool call as an opaque INTERNAL error instead of transparently - // reconnecting. - it("reconnects after the daemon restarts under a live MCP server process (PR #35)", async () => { - const env = await withDaemon(); + // Regression for PR #35 ("reconnect the session after a daemon restart"), now covering + // ADR 0004's second reconnect trigger as well: before #35 an MCP server whose daemon + // connection died mid-session surfaced the *next* tool call as an opaque INTERNAL error + // instead of reconnecting; before ADR 0004 the restart also cost it the lease outright. + it("keeps its lease across a daemon restart, renewing it over a connection of its own", async () => { + // ADR 0004: a restart releases nothing, so the session's lease is still granted + // afterwards -- and its renew timer reconnects to the daemon that is listening again and + // renews it, without waiting for a tool call that may never come (§2's second reconnect + // trigger). The short TTL is what makes the timer fire inside this test. + const env = await withDaemon({ configOverrides: { lease: { defaultTtlMs: 6_000 } } }); await env.driverScript.set({ ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, }); @@ -144,22 +150,45 @@ describe("MCP session semantics", () => { }); const leased = leaseResult.structuredContent as { lease: { id: string } }; - const lostNotice = mcp.waitForNotification((notification) => { - if (notification.kind !== "logging") return undefined; - const data = notification.params.data as { leaseId?: string; reason?: string } | undefined; - return data?.leaseId === leased.lease.id ? data.reason : undefined; - }); - await env.restartDaemon(); - expect(await lostNotice).toBe("daemon-connection-lost"); + const leaseRow = async (): Promise<{ ttlDeadline: number } | undefined> => { + const rows = (await env.cli(["list", "--leases"])).json as { + id: string; + ttlDeadline: number; + }[]; + return rows.find((row) => row.id === leased.lease.id); + }; + + // Still granted the moment the new daemon is up: nothing swept it, and its timer was + // restored from the persisted deadline. + const afterRestart = await leaseRow(); + expect(afterRestart, "the lease should have survived the restart").toBeDefined(); + const deadlineAfterRestart = afterRestart?.ttlDeadline ?? 0; + + // No tool call in between: the only thing that can push this deadline out is the + // session's own renew timer, over a connection it built for itself. + await waitFor(async () => ((await leaseRow())?.ttlDeadline ?? 0) > deadlineAfterRestart, { + timeout: 20_000, + label: "the MCP session renews its lease after the restart", + }); + + // And the session still knows the lease is its own. const statusAfterRestart = await mcp.client.callTool({ name: "lease_status", arguments: {} }); expect(statusAfterRestart.isError).toBeFalsy(); - expect(statusAfterRestart.structuredContent).toEqual({ held: false }); + expect(statusAfterRestart.structuredContent).toMatchObject({ + held: true, + id: leased.lease.id, + }); const devices = await mcp.client.callTool({ name: "list_devices", arguments: {} }); expect(devices.isError, "expected a clean reconnect, not an INTERNAL error").toBeFalsy(); expect(devices.structuredContent).toMatchObject({ platforms: expect.any(Array) }); + + await mcp.client.callTool({ + name: "release_simulator", + arguments: { leaseId: leased.lease.id }, + }); } finally { await mcp.close(); } diff --git a/e2e/parallel-contention.test.ts b/e2e/parallel-contention.test.ts index 93922b547..e922cfeb4 100644 --- a/e2e/parallel-contention.test.ts +++ b/e2e/parallel-contention.test.ts @@ -36,14 +36,22 @@ describe("parallel contention invariant", () => { const servedDeviceByAgent = new Map(); - // As soon as each holder is granted, immediately kill it -- releasing capacity so - // the remaining queued agents can be served in turn. All eight are started - // concurrently; none is awaited before the next starts. + // As soon as each holder is granted, stop it -- releasing capacity so the remaining + // queued agents can be served in turn. All eight are started concurrently; none is + // awaited before the next starts. + // + // `SIGTERM`, not `SIGKILL`: under ADR 0004 §3 the daemon releases nothing when a + // connection closes, so only the holder's own release-on-exit path frees the device + // this quickly. A `SIGKILL`ed holder would hold its device until the TTL expired, and + // eight agents queueing behind that is a different (and much slower) test. const releaseChains = handles.map(async (handle, index) => { const line = await handle.firstStdoutLine(60_000); - const grant = JSON.parse(line) as { lease: string; udid: string }; - servedDeviceByAgent.set(AGENT_IDS[index] as string, grant.udid); - handle.kill("SIGKILL"); + const grant = JSON.parse(line) as { + lease: { id: string }; + device: { driverDeviceId: string }; + }; + servedDeviceByAgent.set(AGENT_IDS[index] as string, grant.device.driverDeviceId); + handle.kill("SIGTERM"); await handle.waitForExit(15_000).catch(() => undefined); }); @@ -75,6 +83,14 @@ describe("parallel contention invariant", () => { expect(servedDeviceByAgent.size, "every requester was eventually served").toBe( AGENT_IDS.length, ); + // Eight agents, but only ever two devices to go round: the point of the cap is that the + // pool is *reused* as holders exit, not quietly grown past `ios.maxDevices` to serve + // everyone at once. The poll above can miss a moment; the set of devices actually handed + // out cannot. + expect( + new Set(servedDeviceByAgent.values()).size, + `eight requesters were served from more than the two devices the config allows: ${JSON.stringify([...servedDeviceByAgent])}`, + ).toBeLessThanOrEqual(2); await waitForLeaseCount(env, 0); const finalStatus = await env.cli(["status", "--json"]); diff --git a/e2e/parent-watch.test.ts b/e2e/parent-watch.test.ts index c47e018d3..1e85834a5 100644 --- a/e2e/parent-watch.test.ts +++ b/e2e/parent-watch.test.ts @@ -4,7 +4,8 @@ import { describe, expect, it } from "vitest"; import { waitForLeaseCount, withDaemon } from "./helpers/index.js"; -/** Stands in for the agent process a held CLI lease watches, without pulling in a real one. */ +/** Stands in for the agent process a running `simlock lease` watches, without pulling in a + * real one. */ async function spawnFakeAgent(): Promise { const child = spawn(process.execPath, ["-e", "setTimeout(() => {}, 120_000)"], { stdio: "ignore", @@ -18,7 +19,10 @@ async function spawnFakeAgent(): Promise { describe("parent-watch", () => { it("self-terminates and releases when its --bind-pid parent dies, without itself being signaled", async () => { - const env = await withDaemon(); + // A long TTL on purpose: ADR 0004 leaves an unreleased lease standing until its + // deadline, so a lease freed within seconds here can only be the holder's own release + // path running -- which is exactly what this test is about. Nothing waits on expiry. + const env = await withDaemon({ configOverrides: { lease: { defaultTtlMs: 600_000 } } }); await env.driverScript.set({ ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, }); @@ -47,9 +51,10 @@ describe("parent-watch", () => { fakeAgent.kill("SIGKILL"); - // Nothing signals the holder itself -- it must notice on its own that the pid - // it is bound to is gone, then release and exit through the same path a - // SIGTERM would take. + // Nothing signals the holder itself -- it must notice on its own that the pid it is + // bound to is gone, then release and exit through the same path a SIGTERM would take. + // Under ADR 0004 that release is the only thing that can free the device this quickly: + // the daemon releases nothing when the connection closes. const result = await held.waitForExit(15_000); expect(result.code).toBe(0); diff --git a/e2e/renew-ttl.test.ts b/e2e/renew-ttl.test.ts new file mode 100644 index 000000000..0d72a61b3 --- /dev/null +++ b/e2e/renew-ttl.test.ts @@ -0,0 +1,221 @@ +import { readFile } from "node:fs/promises"; +import { describe, expect, it } from "vitest"; + +import { waitFor, withDaemon } from "./helpers/index.js"; + +interface LeaseRow { + readonly id: string; + readonly requesterId: string; + readonly ttlMs: number; + readonly ttlDeadline: number; + readonly lastRenewedAt: number; +} + +async function leaseRows(env: Awaited>): Promise { + const result = await env.cli(["list", "--leases"]); + if (result.code !== 0) throw new Error(`simlock list --leases failed: ${result.stderr}`); + return result.json as LeaseRow[]; +} + +describe("TTL leases and client-side renewal (ADR 0004)", () => { + it("refuses to start when lease.defaultTtlMs exceeds lease.maxTtlMs, naming the key", async () => { + const env = await withDaemon({ + mode: "auto", + configOverrides: { lease: { defaultTtlMs: 60_000, maxTtlMs: 30_000 } }, + }); + + // Every command auto-starts on demand; the daemon process fails the config load before + // it ever opens its socket, so the CLI retries for its startup window and then gives up + // -- surfaced as an INTERNAL timeout, not a specific config error code (the CLI never + // got a response to relay). + const result = await env.cli(["catalog", "--json"], { timeout: 15_000 }); + expect(result.code).toBe(1); + expect(result.error?.code).toBe("INTERNAL"); + + await waitFor( + async () => { + try { + const log = await readFile(env.logPath, "utf8"); + return log.includes("lease.defaultTtlMs"); + } catch { + return false; + } + }, + { timeout: 10_000, label: "daemon.log names the offending config key" }, + ); + }); + + it("keeps a renewing holder's lease alive (MCP and CLI) while an unrenewed lease expires", async () => { + const env = await withDaemon({ + // Short enough that the unrenewed lease's expiry lands inside the test's own timeline; + // both holders renew at a third of it, so they slide well past it (ADR 0004 §2). + configOverrides: { lease: { defaultTtlMs: 4_000 } }, + }); + await env.driverScript.set({ + ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, + }); + + const mcp = await env.mcpClient({ env: { SIMLOCK_AGENT_ID: "flow6-mcp" } }); + const cliHolder = env.cliBackground([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--agent-id", + "flow6-cli", + ]); + + try { + const leaseResult = await mcp.client.callTool({ + name: "lease_simulator", + arguments: { model: "iPhone 16", osVersion: "18.4", platform: "ios" }, + }); + const mcpLease = leaseResult.structuredContent as { + lease: { id: string; ttlDeadline: number }; + }; + + const cliGrant = JSON.parse(await cliHolder.firstStdoutLine()) as { + lease: { id: string; ttlDeadline: number }; + }; + + const detachedResult = await env.cli([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--agent-id", + "flow6-detached", + "--detach", + ]); + const detachedGrant = detachedResult.json as { lease: { id: string } }; + + // Both holders -- MCP and CLI -- renew on their own timer at a third of the TTL (ADR + // 0004 §2), pushing their deadline well past the grant-time one. The `--detach` lease + // has no holder process at all, so nothing renews it and it expires exactly at its own + // deadline. + await waitFor( + async () => { + const rows = await leaseRows(env); + return rows.every((row) => row.id !== detachedGrant.lease.id); + }, + { timeout: 15_000, label: "the unrenewed --detach lease expires at its TTL" }, + ); + + const rowsAfterExpiry = await leaseRows(env); + const mcpRow = rowsAfterExpiry.find((row) => row.id === mcpLease.lease.id); + const cliRow = rowsAfterExpiry.find((row) => row.id === cliGrant.lease.id); + expect(mcpRow, "the MCP lease should have outlived the unrenewed one").toBeDefined(); + expect(cliRow, "the CLI holder's lease should have outlived the unrenewed one").toBeDefined(); + expect(mcpRow?.ttlDeadline).toBeGreaterThan(mcpLease.lease.ttlDeadline); + expect(cliRow?.ttlDeadline).toBeGreaterThan(cliGrant.lease.ttlDeadline); + // A body-less renew re-applies the lease's own width, so neither deadline drifted off + // some other default, and `lastRenewedAt` moved with it. + expect(mcpRow?.ttlMs).toBe(4_000); + expect(cliRow?.ttlMs).toBe(4_000); + expect(cliRow?.lastRenewedAt).toBeGreaterThan(cliGrant.lease.ttlDeadline - 4_000); + + const statusResult = await mcp.client.callTool({ name: "lease_status", arguments: {} }); + const statusExpiry = (statusResult.structuredContent as { ttlDeadline: number }).ttlDeadline; + expect(statusExpiry).toBeGreaterThan(mcpLease.lease.ttlDeadline); + + const recorded = await env.events(); + expect( + recorded.filter( + (entry) => + entry.event === "lease.renewed" && + (entry.payload as { leaseId?: string }).leaseId === mcpLease.lease.id, + ).length, + "expected repeated lease.renewed events for the MCP session's own timer", + ).toBeGreaterThan(1); + expect( + recorded.filter( + (entry) => + entry.event === "lease.renewed" && + (entry.payload as { leaseId?: string }).leaseId === cliGrant.lease.id, + ).length, + "expected repeated lease.renewed events for the CLI holder's own timer", + ).toBeGreaterThan(1); + expect(recorded).toContainEqual( + expect.objectContaining({ + event: "lease.expired", + payload: expect.objectContaining({ leaseId: detachedGrant.lease.id }), + }), + ); + + await mcp.client.callTool({ + name: "release_simulator", + arguments: { leaseId: mcpLease.lease.id }, + }); + } finally { + cliHolder.kill("SIGKILL"); + await cliHolder.waitForExit(15_000).catch(() => undefined); + await mcp.close(); + } + }); + + it("renews a --detach lease by hand, keeping its own width, and caps what may be asked for", async () => { + const env = await withDaemon({ + configOverrides: { lease: { defaultTtlMs: 60_000, maxTtlMs: 120_000 } }, + }); + await env.driverScript.set({ + ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, + }); + + // `--ttl` replaces `lease.defaultTtlMs` for this lease, and the width is stored on it. + const granted = await env.cli([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--agent-id", + "renew-by-hand", + "--detach", + "--ttl", + "90s", + ]); + expect(granted.code).toBe(0); + const grant = granted.json as { lease: { id: string; ttlMs: number; ttlDeadline: number } }; + expect(grant.lease.ttlMs).toBe(90_000); + + // A renew with no `--ttl` re-applies that 90s width rather than the 60s default. + const renewed = await env.cli(["lease", "renew", grant.lease.id]); + expect(renewed.code).toBe(0); + const renewedLease = renewed.json as { ttlMs: number; ttlDeadline: number }; + expect(renewedLease.ttlMs).toBe(90_000); + expect(renewedLease.ttlDeadline).toBeGreaterThanOrEqual(grant.lease.ttlDeadline); + + // Above `lease.maxTtlMs` is a BAD_REQUEST, not a silent clamp -- on a renew... + const tooLong = await env.cli(["lease", "renew", grant.lease.id, "--ttl", "5m"]); + expect(tooLong.code).toBe(2); + expect(tooLong.error?.code).toBe("BAD_REQUEST"); + + // ...and on a request. + const tooLongRequest = await env.cli([ + "lease", + "--platform", + "ios", + "--device", + "iPhone 16", + "--os", + "18.4", + "--agent-id", + "asks-too-much", + "--detach", + "--ttl", + "5m", + ]); + expect(tooLongRequest.code).toBe(2); + expect(tooLongRequest.error?.code).toBe("BAD_REQUEST"); + + await env.cli(["release", grant.lease.id]); + }); +}); diff --git a/src/admin/index.ts b/src/admin/index.ts index defba7379..cb5a4b9eb 100644 --- a/src/admin/index.ts +++ b/src/admin/index.ts @@ -30,7 +30,6 @@ export type { LeaseCancelInput, LeaseCancelOutput, LeaseGrant, - LeaseHeartbeatOutput, LeaseListOutput, LeaseLostPush, LeaseProgress, @@ -67,7 +66,6 @@ export interface ConnectSimlockAdminOptions { readonly ipc?: IpcConnector; readonly principal?: string; readonly credential?: string; - readonly heartbeat?: boolean; } /** Opens one connection to the daemon and completes the `hello` handshake, requesting the @@ -83,7 +81,6 @@ export async function connectSimlockAdmin( ...(options.endpoint === undefined ? {} : { endpoint: options.endpoint }), ...(options.principal === undefined ? {} : { principal: options.principal }), ...(options.credential === undefined ? {} : { credential: options.credential }), - ...(options.heartbeat === undefined ? {} : { heartbeat: options.heartbeat }), }; return connectSimlockClient(resolved, true); } diff --git a/src/bus/index.ts b/src/bus/index.ts index 1b22233f8..4e6e04526 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -7,21 +7,33 @@ export interface EventMap { readonly waitPolicy: string; }; "lease.queued": { readonly requestId: string; readonly queuePosition: number }; + /** ADR 0004's Consequences: `mode` left this payload, a deliberate one-off exception to + * events rule 6 (additive changes only) taken while the package is 0.x -- there is one kind + * of lease now, so there is nothing to report. `EVENTS.md` records the exception. */ "lease.granted": { readonly leaseId: string; readonly deviceId: string; readonly requester: string; - readonly mode: "held" | "detached"; }; "lease.renewed": { readonly leaseId: string; readonly newDeadline: number }; "lease.released": { readonly leaseId: string; readonly deviceId: string; - readonly reason: "closed" | "explicit" | "killed" | "orphaned" | "device-lost"; + /** + * Who ended this lease, and whether its holder asked: `explicit` is a `lease.release` the + * holder itself sent (including the one a `simlock lease` sends on its way out), `killed` + * an operator taking it away (`release --all`, `nuke`), `device-lost` crash recovery + * giving up. Expiry is not in this union at all -- it has its own event. + * + * ADR 0004's Consequences: `closed` and `orphaned` are gone from it, the same deliberate + * 0.x exception to events rule 6. Closing a connection is not a release any more (§3), and + * there is no startup sweep left to orphan anything. + */ + readonly reason: "explicit" | "killed" | "device-lost"; /** ADR 0003 §8: the released lease's owner, so a `lease-lost` push can be routed to every - * live connection whose principal owns it (in either mode), not just the held-lease - * holder -- the registry no longer has the lease to look this up from by the time this - * event fires (`beginRelease` already removed it), so it travels on the event instead. */ + * live connection whose principal owns it -- the registry no longer has the lease to look + * this up from by the time this event fires (`beginRelease` already removed it), so it + * travels on the event instead. */ readonly ownerId: string; }; "lease.expired": { diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index b7dc3ceb3..dfbfdef17 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -55,6 +55,13 @@ import { } from "./index.js"; const gibibyte = 1024 ** 3; + +/** + * Yields to the macrotask queue, so `runLease` gets past `requestLease` and reaches its wait + * point -- its push listeners registered and its renew timer armed -- before a test fires a + * push or advances the clock. + */ +const settle = (): Promise => new Promise((resolve) => setTimeout(resolve, 0)); /** A minimal daemon lease response, for the tests that only care what the CLI prints. */ const detachedGrant: LeaseGrant = { device: { @@ -68,8 +75,9 @@ const detachedGrant: LeaseGrant = { deviceId: "device-1", requesterId: "test-requester", ownerId: "test-requester", - mode: "detached", grantedAt: 0, + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 61_000, }, timing: { @@ -373,7 +381,7 @@ describe("CLI: exit codes", () => { const parentWatch = new FakeParentWatch(); const heldGrant: LeaseGrant = { ...detachedGrant, - lease: { ...detachedGrant.lease, id: "lse_parent_death", mode: "held" }, + lease: { ...detachedGrant.lease, id: "lse_parent_death" }, }; const released: unknown[] = []; @@ -406,7 +414,7 @@ describe("CLI: exit codes", () => { const parentWatch = new FakeParentWatch(); const heldGrant: LeaseGrant = { ...detachedGrant, - lease: { ...detachedGrant.lease, id: "lse_bind_pid", mode: "held" }, + lease: { ...detachedGrant.lease, id: "lse_bind_pid" }, }; const released: unknown[] = []; @@ -889,14 +897,14 @@ describe("CLI: config set validates before writing (ADR 0003 §11)", () => { let wrote = false; await expect( runCli( - ["config", "set", "lease.heldTtlBackstopMs", "not-a-number"], + ["config", "set", "lease.defaultTtlMs", "not-a-number"], output.environmentWith({ readConfigFile: async () => ({}), writeConfigFile: async () => { wrote = true; }, validateConfig: async () => { - throw new Error("lease.heldTtlBackstopMs must be a number"); + throw new Error("lease.defaultTtlMs must be a number"); }, }), ), @@ -946,7 +954,7 @@ describe("CLI: config set validates with the real config loader (ADR 0003 §11, const output = outputCapture(realCliEnvironmentPorts()); let wrote = false; const exitCode = await runCli( - ["config", "set", "lease.heldTtlBackstop", "60000"], + ["config", "set", "lease.defaultTtl", "60000"], output.environmentWith({ readConfigFile: async () => ({}), writeConfigFile: async () => { @@ -962,9 +970,9 @@ describe("CLI: config set validates with the real config loader (ADR 0003 §11, const output = outputCapture(realCliEnvironmentPorts()); let written: Record | undefined; const exitCode = await runCli( - // Well above the default heartbeat interval (5 min) * 4, so this doesn't also trip - // `validateHeartbeatInterval` -- this test is only about the key itself validating clean. - ["config", "set", "lease.heldTtlBackstopMs", "2400000"], + // Comfortably under the default `lease.maxTtlMs` (4h), so this doesn't also trip the + // TTL pair rule -- this test is only about the key itself validating clean. + ["config", "set", "lease.defaultTtlMs", "2400000"], output.environmentWith({ readConfigFile: async () => ({}), writeConfigFile: async (contents) => { @@ -973,7 +981,7 @@ describe("CLI: config set validates with the real config loader (ADR 0003 §11, }), ); expect(exitCode).toBe(0); - expect(written).toEqual({ lease: { heldTtlBackstopMs: 2400000 } }); + expect(written).toEqual({ lease: { defaultTtlMs: 2400000 } }); }); it("does not let a stray file at the scratch validation path change the outcome", async () => { @@ -1140,7 +1148,7 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( ); // Let requestLease resolve and runLease reach the `Promise.race` wait point before firing // the push -- otherwise the listener registered by `client.onLeaseLost` may not exist yet. - await new Promise((resolve) => setTimeout(resolve, 0)); + await settle(); leaseLostListener?.({ leaseId: "lse_1", deviceId: "dev_1", reason: "ttl-backstop" }); const exitCode = await runPromise; expect(exitCode).toBe(14); @@ -1172,11 +1180,11 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( signals: signals as unknown as CliEnvironment["signals"], }), ); - await new Promise((resolve) => setTimeout(resolve, 0)); + await settle(); // A push for another lease this same principal owns (e.g. an earlier `--detach`'d lease) -- // must not be treated as this invocation's own lease being lost. leaseLostListener?.({ leaseId: "some-other-lease", deviceId: "dev_2", reason: "ttl-backstop" }); - await new Promise((resolve) => setTimeout(resolve, 0)); + await settle(); signals.emit("SIGINT"); const exitCode = await runPromise; expect(exitCode).toBe(0); @@ -1213,8 +1221,9 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( deviceId: "dev_1", requesterId: "test-requester", ownerId: "test-requester", - mode: "detached", grantedAt: 0, + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 60_000, }, timing: { @@ -1266,8 +1275,9 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( deviceId: "dev_1", requesterId: "test-requester", ownerId: "test-requester", - mode: "detached", grantedAt: 0, + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 60_000, }, timing: { @@ -1314,8 +1324,9 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( deviceId: "dev_1", requesterId: "test-requester", ownerId: "test-requester", - mode: "detached", grantedAt: 0, + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 60_000, }, timing: { @@ -1337,15 +1348,12 @@ 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. + * ADR 0004 §2/§3: holding is a client policy -- this process renews on a timer at a third of + * the remaining TTL and releases explicitly, and the daemon does neither on its behalf. There + * is no mode on the wire any more, so what is asserted here is entirely the CLI's own + * behaviour while it holds, and what it does when the connection under it dies. */ -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)); - +describe("CLI: holder renew and release (ADR 0004 §2)", () => { 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(); @@ -1360,9 +1368,10 @@ describe("CLI: held-mode renew and release (ADR 0004 §2)", () => { deviceId: "dev_1", grantedAt: 0, id: input.leaseId, - mode: "held", ownerId: "test-requester", requesterId: "test-requester", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: clock.now() + 30_000, }); }, @@ -1408,34 +1417,176 @@ describe("CLI: held-mode renew and release (ADR 0004 §2)", () => { expect(renewals).toHaveLength(2); }); - it("declares no heartbeat capability at hello, in either mode (ADR 0004 §4)", async () => { + it("exits 1 on a dead connection, naming the lease that outlived it, and releases nothing", async () => { + // ADR 0004 §3: the daemon released nothing when the socket died, so the lease is still + // granted -- the holder says so, says until when, and does not pretend to release it. + const output = outputCapture(); + let connectionLostListener: ((error: AnySimlockError) => void) | undefined; + let released = false; + const client = fakeClient({ + onConnectionLost: (listener) => { + connectionLostListener = listener; + return () => {}; + }, + releaseLease: () => { + released = true; + return Promise.resolve({ leaseId: "lse_1" }); + }, + }); + const runPromise = runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro"], + output.environmentWith({ connectAdmin: async () => client }), + ); + // Let `requestLease` resolve and `runLease` reach its wait point, so the listener exists. + await settle(); + connectionLostListener?.( + new SimlockError("DAEMON_CONNECTION_LOST", "transport", "socket closed", {}), + ); + + expect(await runPromise).toBe(1); + const line = JSON.parse(output.stderr.trim().split("\n").at(-1) as string) as { + error: { code: string; message: string }; + }; + expect(line.error.code).toBe("DAEMON_CONNECTION_LOST"); + expect(line.error.message).toContain("lse_1"); + expect(line.error.message).toContain("60000"); + // Nothing to release over a connection that is already gone -- and nothing that should be. + expect(released).toBe(false); + }); + + it("names the latest deadline in that line, not the one the grant carried", async () => { + // The deadline moves on every renewal, and this line is the only place a holder reports + // it. Quoting the grant-time one would, after about a TTL of uptime, name a moment in the + // past on a lease that is perfectly alive. + const clock = new FakeClock(0); + const output = outputCapture(); + let connectionLostListener: ((error: AnySimlockError) => void) | undefined; + const client = fakeClient({ + onConnectionLost: (listener) => { + connectionLostListener = listener; + return () => {}; + }, + renewLease: (input) => + Promise.resolve({ + deviceId: "dev_1", + grantedAt: 0, + id: input.leaseId, + ownerId: "test-requester", + requesterId: "test-requester", + lastRenewedAt: clock.now(), + ttlMs: 60_000, + ttlDeadline: clock.now() + 60_000, + }), + }); + const runPromise = runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro"], + output.environmentWith({ clock, connectAdmin: async () => client }), + ); + await settle(); + + // Two renewals: the grant's deadline was 60_000, so they land at 20_000 and 40_000, each + // answering with a deadline a full TTL further out. + clock.advance(20_000); + await settle(); + clock.advance(20_000); + await settle(); + + connectionLostListener?.( + new SimlockError("DAEMON_CONNECTION_LOST", "transport", "socket closed", {}), + ); + expect(await runPromise).toBe(1); + + const line = JSON.parse(output.stderr.trim().split("\n").at(-1) as string) as { + error: { message: string }; + }; + expect(line.error.message).toContain("100000"); + // The grant-time deadline (60_000) is not what it reports any more. + expect(line.error.message).not.toContain("60000"); + }); + + it("writes one line for a lost connection, even with a renewal in flight when it dies", async () => { + // The same socket carries both: the connection-lost listener writes the line that names + // the lease and its deadline, and the `lease.renew` that was in flight rejects with + // `DAEMON_CONNECTION_LOST`. That rejection is a retryable failure as far as + // `startLeaseRenewal` knows -- not a `lease-lost` -- so the holder must not answer it with + // a second line saying the daemon is gone, this one without the lease id a reader needs. + // Two things stop that, and this pins the outcome rather than either mechanism: the + // `finally` stops renewal (nothing is reported after `stop()`), and `onError` checks + // `connectionLost` so the answer does not depend on which of the two microtask chains + // wins. + const clock = new FakeClock(0); + const output = outputCapture(); + let connectionLostListener: ((error: AnySimlockError) => void) | undefined; + let rejectRenew: ((error: unknown) => void) | undefined; + const client = fakeClient({ + onConnectionLost: (listener) => { + connectionLostListener = listener; + return () => {}; + }, + renewLease: () => + new Promise((_resolve, reject) => { + rejectRenew = reject; + }), + }); + const runPromise = runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro"], + output.environmentWith({ clock, connectAdmin: async () => client }), + ); + await settle(); + + // The grant's deadline is 60_000: the first renewal starts at 20_000 and never answers. + clock.advance(20_000); + await settle(); + expect(rejectRenew).toBeDefined(); + + // The socket dies. In that order, deliberately: `SimlockClient.onConnectionLost` promises + // that "every in-flight call has already rejected `DAEMON_CONNECTION_LOST` by the time + // this listener runs", so the renewal's rejection is queued first and its handler runs + // after the listener has had its say. + rejectRenew?.(new SimlockError("DAEMON_CONNECTION_LOST", "transport", "socket closed", {})); + connectionLostListener?.( + new SimlockError("DAEMON_CONNECTION_LOST", "transport", "socket closed", {}), + ); + + expect(await runPromise).toBe(1); + const errorLines = output.stderr + .trim() + .split("\n") + .filter((line) => line.length > 0) + .map((line) => JSON.parse(line) as { error?: { code: string; message: string } }) + .filter((line) => line.error !== undefined); + expect(errorLines).toHaveLength(1); + expect(errorLines[0]?.error?.code).toBe("DAEMON_CONNECTION_LOST"); + expect(errorLines[0]?.error?.message).toContain("lse_1"); + }); + + it("sends --ttl as the request's own ttlMs, and nothing when it is not given", async () => { const output = outputCapture(); const signals = new EventEmitter(); - const declared: Array = []; + const requested: Array = []; const environment = output.environmentWith({ clock: new FakeClock(0), - connectAdmin: async (_resolveCredential, options) => { - declared.push(options?.heartbeat); - return fakeClient(); - }, + connectAdmin: async () => + fakeClient({ + requestLease: (input) => { + requested.push(input.ttlMs); + return Promise.resolve(detachedGrant); + }, + }), signals: signals as unknown as CliEnvironment["signals"], }); await runCli( - ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--detach"], + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--detach", "--ttl", "30m"], 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"], + await runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--detach"], environment, ); - await settle(); - signals.emit("SIGINT"); - expect(await heldRun).toBe(0); - expect(declared).toEqual([false, false]); + // ADR 0004 §4: `--ttl` replaces `lease.defaultTtlMs` for this lease; omitting it sends no + // TTL at all, so the daemon's own default applies rather than a number the CLI invented. + expect(requested).toEqual([30 * 60_000, undefined]); }); it.each(["SIGINT", "SIGTERM"] as const)( @@ -1673,8 +1824,9 @@ describe("CLI: held-mode renew and release (ADR 0004 §2)", () => { deviceId: "dev_1", requesterId: "test-requester", ownerId: "test-requester", - mode: "held" as const, grantedAt: 0, + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 60_000, }, timing: { @@ -1741,9 +1893,10 @@ describe("CLI: held-mode renew and release (ADR 0004 §2)", () => { deviceId: "dev_1", grantedAt: 0, id: input.leaseId, - mode: "held", ownerId: "test-requester", requesterId: "test-requester", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: clock.now() + 60_000, }); }, @@ -1885,7 +2038,8 @@ describe("CLI smoke test (ADR 0003 §12: one per frontend)", () => { ); expect(leaseExit).toBe(0); const grant = JSON.parse(leaseOut.stdout) as LeaseGrant; - expect(grant.lease.mode).toBe("detached"); + // ADR 0004: one kind of lease -- what `--detach` changes is this process, not the grant. + expect(grant.lease).toMatchObject({ ttlMs: expect.any(Number) }); const statusOut = outputCapture(); await runCli( @@ -2043,8 +2197,9 @@ function fakeClient(overrides: Partial = {}): SimlockAdminCl deviceId: "dev_1", requesterId: "test-requester", ownerId: "test-requester", - mode: "held", grantedAt: 0, + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 60_000, }, timing: { @@ -2066,7 +2221,6 @@ function fakeClient(overrides: Partial = {}): SimlockAdminCl renewLease: () => Promise.resolve(grant.lease as LeaseRecord), releaseLease: (input) => Promise.resolve({ leaseId: input.leaseId }), listLeases: () => Promise.resolve(emptyLeaseList), - heartbeat: () => Promise.resolve({ leases: [] }), runDoctor: () => Promise.resolve(emptyDoctor), onLeaseLost: () => () => {}, onDeviceUnhealthy: () => () => {}, @@ -2359,7 +2513,7 @@ function testConfig(): Config { http: { enabled: false, host: "127.0.0.1", port: 4700 }, ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, - lease: { detachedTtlMs: 60_000, heldTtlBackstopMs: 60_000, heartbeatIntervalMs: 5_000 }, + lease: { defaultTtlMs: 60_000, maxTtlMs: 3_600_000 }, capacity: { strategy: "resource", config: { diff --git a/src/cli/index.ts b/src/cli/index.ts index 5f4891bb7..6e78652b6 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -59,10 +59,11 @@ explicitly; see docs/CLI.md#admin-credential-resolution for the default resolution order.`; /** - * Held mode ends with the lease already gone: the daemon released it without - * the holder asking (a TTL backstop, an operator `release`, or a leased device - * that could not be recovered). Distinct from 0, which means the holder ended - * its own lease. + * A `lease` that stayed alive ends with the lease already gone: the daemon ended it without + * the holder asking (TTL expiry, an operator `release`, or a leased device that could not be + * recovered). Distinct from 0, which means the holder ended its own lease, and from 1 on a + * dead connection, which means nothing ended the lease at all -- it is still granted and still + * counting down (ADR 0004 §3). */ const LEASE_LOST_EXIT_CODE = 14; @@ -115,7 +116,7 @@ type McpStdioRunner = () => Promise; */ export interface CliEnvironment { /** - * The `Clock` port (architecture rule 9). Held mode's renew timer runs on it, so a test can + * The `Clock` port (architecture rule 9). A holder'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; @@ -136,13 +137,11 @@ export interface CliEnvironment { */ readonly connectAdmin: ( resolveCredential: () => Promise, - options?: { readonly heartbeat?: boolean }, ) => Promise; /** Same as `connectAdmin` but never auto-launches -- `daemon stop`/`daemon status` must not * start a daemon just to ask whether one is running. */ readonly connectExistingAdmin: ( resolveCredential: () => Promise, - options?: { readonly heartbeat?: boolean }, ) => Promise; /** `SIMLOCK_ADMIN_TOKEN`, ADR §5's second resolution source. */ readonly adminTokenFromEnv?: string; @@ -160,7 +159,7 @@ export interface CliEnvironment { readonly loadMcpStdio?: () => Promise; readonly runMcpStdio?: () => Promise; readonly signals: Signals; - /** The pid `lease` held mode watches by default -- the parent captured at CLI startup. */ + /** The pid a running `lease` watches by default -- the parent captured at CLI startup. */ readonly parentPid?: number; readonly parentWatch?: ParentWatch; readonly stderr: Output; @@ -254,11 +253,10 @@ function writeAgentFallbackNotice(environment: CliEnvironment, source: Credentia async function connectDaemonClient( environment: CliEnvironment, tokenFlag: string | undefined, - options: { readonly launch?: boolean; readonly heartbeat?: boolean } = {}, + options: { readonly launch?: boolean } = {}, ): Promise { const connect = options.launch === false ? environment.connectExistingAdmin : environment.connectAdmin; - const connectOptions = options.heartbeat === undefined ? {} : { heartbeat: options.heartbeat }; let source: CredentialSource = "none"; const resolveCredential = async (): Promise => { @@ -276,13 +274,13 @@ async function connectDaemonClient( }; try { - const client = await connect(resolveCredential, connectOptions); + const client = await connect(resolveCredential); if (source === "none") writeAgentFallbackNotice(environment, "none"); return client; } catch (error: unknown) { if (!isAdminAuthFailure(error) || source === "none") throw error; writeAgentFallbackNotice(environment, source); - return connect(async () => undefined, connectOptions); + return connect(async () => undefined); } } @@ -376,7 +374,6 @@ export function buildCliEnvironment( const connect = async ( connector: IpcConnector, resolveCredential: () => Promise, - options?: { readonly heartbeat?: boolean }, ): Promise => { // Resolved here rather than once during construction, because it can throw: a // `SIMLOCK_HOME` whose socket path exceeds the platform limit is a `SocketPathTooLongError`. @@ -392,7 +389,6 @@ export function buildCliEnvironment( connection, principal: requesterId, ...(credential === undefined ? {} : { credential }), - ...(options?.heartbeat === undefined ? {} : { heartbeat: options.heartbeat }), }); }; @@ -400,9 +396,8 @@ export function buildCliEnvironment( clock, configPath, requesterId, - connectAdmin: (resolveCredential, options) => - connect(autoLaunchIpc, resolveCredential, options), - connectExistingAdmin: (resolveCredential, options) => connect(ipc, resolveCredential, options), + connectAdmin: (resolveCredential) => connect(autoLaunchIpc, resolveCredential), + connectExistingAdmin: (resolveCredential) => connect(ipc, resolveCredential), ...(env.SIMLOCK_ADMIN_TOKEN === undefined ? {} : { adminTokenFromEnv: env.SIMLOCK_ADMIN_TOKEN }), @@ -688,12 +683,14 @@ async function runLease( os: { type: "string" }, platform: { type: "string" }, timeout: { type: "string" }, + ttl: { type: "string" }, }); if (values.help) { environment.stdout.write( "Usage: simlock lease --platform --device [--os ]\n" + " [--agent-id ] [--timeout ] [--no-wait] [--detach]\n" + - " [--allow-download] [--full] [--export-env] [--bind-pid ]\n", + " [--ttl ] [--allow-download] [--full] [--export-env]\n" + + " [--bind-pid ]\n", ); return 0; } @@ -706,29 +703,34 @@ async function runLease( const requesterId = (values["agent-id"] as string | undefined) ?? environment.requesterId; const detached = values.detach ?? false; const timeoutMs = typeof values.timeout === "string" ? parseDuration(values.timeout) : undefined; - // Held mode watches its parent so a crashed agent's backgrounded holder - // self-terminates instead of surviving reparenting (docs/known-pitfalls.md). - // `--bind-pid` overrides which pid that is, for a holder spawned from a - // short-lived subshell whose immediate parent dies before the agent does. + // ADR 0004 §4: this lease's initial TTL, in place of `lease.defaultTtlMs`. Sent as-is -- the + // cap against `lease.maxTtlMs` is the daemon's to apply, and asking for more comes back as + // `BAD_REQUEST` rather than being clamped here to a value the caller did not write. + const ttlMs = typeof values.ttl === "string" ? parseDuration(values.ttl) : undefined; + // A holder watches its parent so a crashed agent's backgrounded `simlock lease` + // self-terminates instead of surviving reparenting (docs/known-pitfalls.md) -- the one + // failure a TTL cannot bound, because a reparented holder keeps renewing. `--bind-pid` + // overrides which pid that is, for a holder spawned from a short-lived subshell whose + // immediate parent dies before the agent does. const bindPid = parseBindPid(values["bind-pid"]); const watchedPid = bindPid ?? environment.parentPid; const termination = detached ? undefined : waitForTermination(environment.signals, environment.parentWatch, watchedPid); - // 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 }); + // ADR 0004 §2: holding is this process's own policy -- it renews on its own timer (below). + // There is no capability to declare and no daemon-initiated push to answer. + const client = await connectDaemonClient(environment, token); // 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 - // pre-typed-client CLI did, since a second CLI invocation sharing this principal (e.g. a - // detached lease from an earlier `--detach`) can otherwise deliver a push for a lease this - // process never held. + // lease-scoped pushes go to every live connection sharing the lease's owner -- filtered below + // against this connection's own granted lease id, the same way the pre-typed-client CLI did, + // since a second CLI invocation sharing this principal (a lease from an earlier `--detach`, + // say) can otherwise deliver a push for a lease this process never held. let leaseLost = false; let ourLeaseId: string | undefined; + /** Reported in the `DAEMON_CONNECTION_LOST` line below, so a reader knows how long the + * still-standing lease has left to be renewed in. */ + let ourLeaseDeadline: number | undefined; let notifyLeaseLost: (() => void) | undefined; const leaseLostSignal = new Promise((resolve) => { notifyLeaseLost = resolve; @@ -757,6 +759,33 @@ async function runLease( if (push.leaseId !== ourLeaseId) return; markLeaseLost(push); }); + /** + * ADR 0004 §3: a dead connection is not a dead lease. The daemon released nothing, so the + * lease is still granted, still counting down, and a later `simlock lease renew ` picks + * it straight back up -- but this process can neither renew nor release it, and the CLI + * deliberately does not reconnect (ADR 0003 §10). So it says exactly that, naming the lease + * and the deadline the next invocation has to beat, and exits 1. Distinct from exit 14, which + * means the daemon *ended* the lease while the connection was alive. + */ + let connectionLost = false; + let notifyConnectionLost: (() => void) | undefined; + const connectionLostSignal = new Promise((resolve) => { + notifyConnectionLost = resolve; + }); + const offConnectionLost = client.onConnectionLost(() => { + connectionLost = true; + if (ourLeaseId !== undefined) { + environment.stderr.write( + `${JSON.stringify({ + error: { + code: "DAEMON_CONNECTION_LOST", + message: `lost the daemon connection; lease ${ourLeaseId} is still yours until its ttlDeadline ${String(ourLeaseDeadline)} -- renew it with \`simlock lease renew ${ourLeaseId}\` or let it expire`, + }, + })}\n`, + ); + } + notifyConnectionLost?.(); + }); const offUnhealthy = client.onDeviceUnhealthy((push) => { environment.stderr.write(`${JSON.stringify({ push: "device-unhealthy", ...push })}\n`); }); @@ -764,19 +793,23 @@ async function runLease( 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. + * ADR 0004 §2/§3: the release a 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 now the *only* thing that frees the device + * before the deadline: the daemon releases nothing when this connection closes. * - * 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). + * Set only for a holder, and cleared as it runs, so it happens exactly once and never for + * `--detach` (whose lease deliberately outlives this process), for a lease the daemon has + * already ended (`leaseLost` -- asking again would only raise UNKNOWN_LEASE), or over a + * connection that is already gone (`connectionLost`). */ let heldLeaseId: string | undefined; const releaseHeldLease = async (): Promise => { - if (heldLeaseId === undefined || leaseLost) return; + // A dead connection can neither carry the release nor needs to: the lease outlives this + // process either way, and `client.releaseLease` would only reject `DAEMON_CONNECTION_LOST` + // a second time. + if (heldLeaseId === undefined || leaseLost || connectionLost) return; const leaseId = heldLeaseId; heldLeaseId = undefined; try { @@ -800,7 +833,6 @@ async function runLease( const grant = await client.requestLease( { allowDownload: values["allow-download"] === true, - mode: detached ? "detached" : "held", noWait: values["no-wait"] === true, requesterId, model: values.device, @@ -808,6 +840,7 @@ async function runLease( platform, ...(values.full === true ? { full: true } : {}), ...(timeoutMs === undefined ? {} : { timeoutMs }), + ...(ttlMs === undefined ? {} : { ttlMs }), }, { onProgress: (progress) => { @@ -816,30 +849,52 @@ async function runLease( }, ); ourLeaseId = grant.lease.id; + ourLeaseDeadline = grant.lease.ttlDeadline; // 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 }; - // Held mode still holds after this line, whichever shape it took: `--export-env` only - // changes what stdout carries, never how long the lease lives. + // A holder keeps holding after this line, whichever shape its output took: `--export-env` + // only changes what stdout carries, never how long the lease lives. if (values["export-env"] === true) writeExportEnv(environment, result); else writeResult(environment, result); // `--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. + // The connection can die between the grant and the wait below; the listener above has + // already written its line, so this only has to reach the same exit. + if (connectionLost) return ERROR_TABLE.DAEMON_CONNECTION_LOST.cliExitCode; + // ADR 0004 §2: what a 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. Each renew names no TTL of its own, so the daemon re-applies the lease's + // stored width and the deadline keeps moving out at its original width. renewal = startLeaseRenewal({ clock: environment.clock, leaseId: grant.lease.id, + // Both, and they do different jobs: the width sets the cadence (a duration needs no + // shared clock), the deadline bounds it. + ttlMs: grant.lease.ttlMs, ttlDeadline: grant.lease.ttlDeadline, renew: (leaseId) => client.renewLease({ leaseId }), + // Every renewal moves the deadline, and the `DAEMON_CONNECTION_LOST` line above names + // it: without this the line would keep quoting the grant-time deadline, which after + // about one TTL of uptime is a moment in the past on a lease that is perfectly alive. + onRenewed: (renewed) => { + ourLeaseDeadline = renewed.ttlDeadline; + }, // 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), + // + // Except once the connection is gone: a `lease.renew` in flight when the socket dies + // rejects with `DAEMON_CONNECTION_LOST` too, and that would print a second line saying + // the same thing right after the one the listener above already wrote -- the one that + // names the lease and its deadline. A holder loses its daemon once, so it says so once. + onError: (error) => { + if (connectionLost) return; + 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` @@ -851,9 +906,14 @@ async function runLease( writeError(environment, error); }, }); - await Promise.race([termination.settled, leaseLostSignal]); - // The daemon already released a lost lease; `releaseHeldLease` skips it for that reason. - return leaseLost ? LEASE_LOST_EXIT_CODE : 0; + await Promise.race([termination.settled, leaseLostSignal, connectionLostSignal]); + // Three ways to get here, three answers: the daemon ended the lease (14, and + // `releaseHeldLease` skips a lease that is already gone), the connection died while the + // lease stood (1, nothing released), or this process was asked to stop (0, and it releases + // on the way out). + if (leaseLost) return LEASE_LOST_EXIT_CODE; + if (connectionLost) return ERROR_TABLE.DAEMON_CONNECTION_LOST.cliExitCode; + return 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. @@ -863,6 +923,7 @@ async function runLease( offLeaseLost(); offUnhealthy(); offRecovered(); + offConnectionLost(); await client.close(); } } @@ -1518,11 +1579,12 @@ function formatStatus(status: StatusGetOutput): string { const suffix = markers.length === 0 ? "" : ` (${markers.join(", ")})`; return `Device ${device.id}: ${device.state}${suffix}`; }); - const leaseLines = leases.map((lease) => { - const heartbeatSuffix = - lease.lastHeartbeatAt === undefined ? "" : `, last heartbeat ${lease.lastHeartbeatAt}`; - return `Lease ${lease.id}: ${lease.requesterId} since ${lease.grantedAt}${heartbeatSuffix}`; - }); + // ADR 0004: `lastRenewedAt` is a stored field written at grant and on every renew, so unlike + // the derived `lastHeartbeatAt` it replaces, every lease has one to render. + const leaseLines = leases.map( + (lease) => + `Lease ${lease.id}: ${lease.requesterId} since ${lease.grantedAt}, last renewed ${lease.lastRenewedAt}`, + ); return [ `Daemon: ${health}`, globalLine, diff --git a/src/client/index.ts b/src/client/index.ts index 5436d5192..46f697513 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -27,7 +27,6 @@ export type { LeaseCancelInput, LeaseCancelOutput, LeaseGrant, - LeaseHeartbeatOutput, LeaseListOutput, LeaseLostPush, LeaseProgress, @@ -56,7 +55,6 @@ export interface ConnectSimlockOptions { readonly endpoint?: string; readonly ipc?: IpcConnector; readonly principal?: string; - readonly heartbeat?: boolean; } /** Opens one connection to the daemon and completes the `hello` handshake as an agent-role @@ -72,7 +70,6 @@ export async function connectSimlock(options: ConnectSimlockOptions): Promise { deviceId: "device_1", grantedAt: 0, id: "lease_1", - mode: "held", ownerId: "agent-smoke", requesterId: "agent-smoke", ttlDeadline: 1_000, diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 79d490bf1..9858ea2d5 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -35,7 +35,6 @@ const ROLE_MATRIX: ReadonlyArray<{ { name: "lease.renew", input: { leaseId: "lease_1" }, role: "agent" }, { name: "lease.release", input: { leaseId: "lease_1" }, role: "agent" }, { name: "lease.list", input: {}, role: "agent" }, - { name: "lease.heartbeat", input: {}, role: "agent" }, { name: "doctor.run", input: { fix: false }, role: "agent" }, { name: "doctor.run", input: {}, role: "agent" }, { name: "doctor.run", input: { fix: true }, role: "admin" }, @@ -75,7 +74,7 @@ describe("operation role matrix", () => { }); describe("operation input/output round trips", () => { - it("lease.request: round-trips a representative held request and rejects legacy aliases", () => { + it("lease.request: round-trips a representative request and rejects legacy aliases", () => { const input = OPERATIONS["lease.request"].input.parse({ model: "iPhone 17 Pro", platform: "ios", @@ -93,26 +92,37 @@ describe("operation input/output round trips", () => { ).toThrow(); }); - it("lease.request: rejects ttlMs on a held lease as a schema-level BAD_REQUEST", () => { - expect(() => + it("lease.request: accepts ttlMs on any request (ADR 0004 §4)", () => { + expect( OPERATIONS["lease.request"].input.parse({ model: "iPhone 17 Pro", platform: "ios", - mode: "held", ttlMs: 60_000, }), + ).toMatchObject({ ttlMs: 60_000 }); + }); + + it("lease.request: rejects mode, which ADR 0004 removed from the contract", () => { + expect(() => + OPERATIONS["lease.request"].input.parse({ + model: "iPhone 17 Pro", + mode: "held", + platform: "ios", + }), ).toThrow(); }); - it("lease.request: accepts ttlMs on a detached lease", () => { + it("lease.request/lease.renew: a non-positive ttlMs is a schema-level BAD_REQUEST", () => { + // The upper bound (`lease.maxTtlMs`) is the dispatcher's to enforce -- it is a daemon + // config value this module cannot see -- but "a TTL is a positive number" is shape. expect(() => OPERATIONS["lease.request"].input.parse({ model: "iPhone 17 Pro", platform: "ios", - mode: "detached", - ttlMs: 60_000, + ttlMs: 0, }), - ).not.toThrow(); + ).toThrow(); + expect(() => OPERATIONS["lease.renew"].input.parse({ leaseId: "lse_1", ttlMs: -1 })).toThrow(); }); it("lease.request: round-trips a representative output grant", () => { @@ -131,8 +141,9 @@ describe("operation input/output round trips", () => { deviceId: "dev_1", requesterId: "req_1", ownerId: "req_1", - mode: "held", grantedAt: 1, + lastRenewedAt: 1, + ttlMs: 1, ttlDeadline: 2, }, timing: { @@ -207,7 +218,7 @@ describe("operation input/output round trips", () => { maxRetryBackoffMs: 1, }, }, - lease: { heldTtlBackstopMs: 1, detachedTtlMs: 1, heartbeatIntervalMs: 1 }, + lease: { defaultTtlMs: 1, maxTtlMs: 1 }, diskPressure: { freeBytesThreshold: 1 }, eventBuffer: { capacity: 1 }, log: { level: "info", rotateBytes: 1 }, diff --git a/src/contract/operations.ts b/src/contract/operations.ts index aeb9edbb7..8f395bd70 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -18,7 +18,6 @@ import { doctorReportSchema, eventEnvelopeSchema, leaseGrantSchema, - leaseModeSchema, leaseRecordSchema, nukeReportSchema, passthroughCommandSchema, @@ -89,11 +88,11 @@ export const statusGet = defineOperation({ // ---- lease.request -------------------------------------------------------------------------- /** - * No `device`/`os` legacy aliases and no nested `request` wrapper -- both accepted by today's - * daemon (`server.ts:559-565`), neither carried forward. The wire moves to protocol 3 with no - * compatibility shim (ADR "Consequences"); this is a deliberate break, called out in the PR - * description. `.strict()` on top of dropping the fields: an old client sending `device`/`os`/ - * `request` now gets a clear `BAD_REQUEST` instead of those keys silently vanishing. + * No `device`/`os` legacy aliases and no nested `request` wrapper -- both accepted by the + * pre-ADR-0003 daemon, neither carried forward. `.strict()` on top of dropping the fields: an + * old client sending `device`/`os`/`request` gets a clear `BAD_REQUEST` instead of those keys + * silently vanishing. `mode` leaves the same way under ADR 0004 -- there is one kind of lease, + * so a request that still names a mode is a `BAD_REQUEST` rather than a value silently ignored. */ const leaseRequestInputSchema = z .object({ @@ -101,29 +100,20 @@ const leaseRequestInputSchema = z platform: platformSchema, osVersion: z.string().optional(), full: z.boolean().optional(), - mode: leaseModeSchema.optional(), requesterId: z.string().optional(), allowDownload: z.boolean().optional(), noWait: z.boolean().optional(), timeoutMs: z.number().finite().positive().optional(), - /** ADR §9: initial TTL for a detached lease. Supplying it for a held lease is - * `BAD_REQUEST` -- held TTL is the backstop, not the caller's to shorten -- enforced below - * via `superRefine` rather than left to the handler, so the rule is part of the contract - * itself. Wired through to `LeaseRequestOptions.ttlMs` (src/core/wait-queue.ts) by the - * dispatcher's `lease.request` handler. */ + /** + * ADR 0004 §4: this lease's initial TTL, accepted on **every** request now (it used to be + * `BAD_REQUEST` for a held lease). Omitting it means `lease.defaultTtlMs`; a value above + * `lease.maxTtlMs` is `BAD_REQUEST`, enforced by the dispatcher's handler rather than here + * because the cap is a daemon config value this module deliberately cannot see. Wired + * through to `LeaseRequestOptions.ttlMs` (src/core/wait-queue.ts) by that same handler. + */ ttlMs: z.number().finite().positive().optional(), }) - .strict() - .superRefine((value, ctx) => { - if (value.ttlMs !== undefined && (value.mode ?? "held") === "held") { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: - "ttlMs is BAD_REQUEST for a held lease: held TTL is the backstop, not the caller's to shorten", - path: ["ttlMs"], - }); - } - }); + .strict(); export const leaseRequest = defineOperation({ name: "lease.request", @@ -178,6 +168,13 @@ export const leaseCancel = defineOperation({ // ---- lease.renew ---------------------------------------------------------------------------- +/** + * ADR 0004 §1: the only thing that keeps a lease alive, on every transport. An omitted `ttlMs` + * re-applies the lease's own stored width -- never `lease.defaultTtlMs` -- so a lease granted + * for four hours does not shrink to fifteen minutes the first time something renews it. A + * `ttlMs` above `lease.maxTtlMs` is `BAD_REQUEST`, checked in the dispatcher's handler where + * that config value is visible. + */ // fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. export const leaseRenew = defineOperation({ name: "lease.renew", @@ -229,18 +226,6 @@ export const leaseList = defineOperation({ output: z.object({ leases: z.array(leaseRecordSchema) }), }); -// ---- lease.heartbeat ------------------------------------------------------------------------ - -// fallow-ignore-next-line unused-export -- consumed only through the OPERATIONS registry, not by name; still public contract surface. -export const leaseHeartbeat = defineOperation({ - name: "lease.heartbeat", - role: "agent", - input: z.object({}), - output: z.object({ - leases: z.array(z.object({ leaseId: z.string(), ttlDeadline: z.number() })), - }), -}); - // ---- doctor.run ------------------------------------------------------------------------------- const doctorRunInputSchema = z.object({ @@ -417,7 +402,6 @@ export const OPERATIONS = { "lease.renew": leaseRenew, "lease.release": leaseRelease, "lease.list": leaseList, - "lease.heartbeat": leaseHeartbeat, "driver.passthrough": driverPassthrough, "doctor.run": doctorRun, "lease.release-all": leaseReleaseAll, diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index c491ea919..6bc795f7f 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -14,12 +14,15 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** - * The range this contract's daemon speaks. Both ends are 3 today: the socket wire moves to - * protocol 3 with no compatibility shim (ADR "Consequences") -- the range widens only once a - * second version is actually kept alive side by side with the first, which nothing here does - * yet. + * The range this contract's daemon speaks. Both ends are 4: ADR 0004 removes `lease.heartbeat` + * and `mode` from the wire with no compatibility shim behind them, so under ADR 0003 §6's + * honesty rule the range does not widen -- it only ever would once a second version is + * actually kept alive side by side with the first, which nothing here does. A protocol-3 + * client and this daemon simply do not overlap, and `hello` fails with + * `PROTOCOL_VERSION_UNSUPPORTED` naming both ranges; `daemon.stop` stays the frozen exception + * so the upgrade path (stop, then start the new daemon) exists at all. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 3, max: 3 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 4, max: 4 }; /** * The one protocol version that ever existed before ranges did. Used only to build the @@ -74,7 +77,6 @@ export const helloRequestSchema = z * only ever compares this field) still answers intelligibly. */ protocolVersion: z.number().int().optional(), protocolRange: protocolRangeSchema.optional(), - capabilities: z.object({ heartbeat: z.boolean().optional() }).optional(), principal: z.string().optional(), credential: z.string().optional(), }) diff --git a/src/contract/pushes.ts b/src/contract/pushes.ts index d1f2c4cfd..b70b6c3a2 100644 --- a/src/contract/pushes.ts +++ b/src/contract/pushes.ts @@ -3,16 +3,13 @@ * schema: * * - Request-scoped (`progress`): carries the originating request's frame id. - * - Lease-scoped (`lease-lost`, `device-unhealthy`, `device-recovered`): carries the lease id. - * - Connection-scoped (`lease.heartbeat`, `event` -- `event` carries a subscription id). + * - Lease-scoped (`lease-lost`, `device-unhealthy`, `device-recovered`): carries the lease id, + * and goes to every live connection whose principal owns that lease (ADR 0004 §5 keeps + * these; they are facts about the device, not a liveness channel). + * - Connection-scoped (`event`, which carries a subscription id). * - * Today's `progress` push carries no correlation id at all (see the daemon inventory); adding - * one to the schema is this PR's job. Actually routing a push to "every live connection whose - * principal owns the lease" (§8) is not -- that needs the `ownerId`/principal work in PR 2. The - * schemas here describe the target shape; `src/daemon/server.ts` is updated in this PR to - * populate the two ids that don't need ownership at all (`progress`'s request id, `event`'s - * subscription id) but still routes lease-scoped pushes the old way (single - * `heldLeaseIds`-membership lookup) until PR 2. + * ADR 0004 removes the fourth kind: `lease.heartbeat` was a daemon-initiated liveness push, + * and nothing replaces it -- a client-initiated `lease.renew` is the whole mechanism now. */ import { z } from "zod"; @@ -49,8 +46,6 @@ const deviceRecoveredPushSchema = z.object({ attempts: z.number(), }); -const heartbeatPushSchema = z.object({ nonce: z.number() }); - const eventPushSchema = z.object({ subscriptionId: z.string(), event: eventEnvelopeSchema, @@ -61,6 +56,5 @@ export const PUSH_SCHEMAS = { "lease-lost": leaseLostPushSchema, "device-unhealthy": deviceUnhealthyPushSchema, "device-recovered": deviceRecoveredPushSchema, - "lease.heartbeat": heartbeatPushSchema, event: eventPushSchema, } as const; diff --git a/src/contract/schemas.test.ts b/src/contract/schemas.test.ts index 92f9627e6..a62c64e65 100644 --- a/src/contract/schemas.test.ts +++ b/src/contract/schemas.test.ts @@ -64,8 +64,9 @@ describe("leaseGrantSchema's device projection", () => { deviceId: "device-1", requesterId: "req", ownerId: "req", - mode: "held", grantedAt: 0, + lastRenewedAt: 0, + ttlMs: 1000, ttlDeadline: 1000, }, timing: { diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 250a8b02e..b8266720b 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -148,23 +148,29 @@ export const grantedDeviceSchema = z.object({ featureProfile: featureProfileSchema.optional(), }); -export const leaseModeSchema = z.enum(["held", "detached"]); - /** - * Mirrors `LeaseRecord` (src/core/domain.ts) plus the `status`/`list` decoration's derived - * `lastHeartbeatAt` (see `DaemonServer#decorateLease`). Includes `ownerId` (ADR §4): the - * session principal that requested the lease, distinct from `requesterId` (attribution, - * defaults to the principal but may differ per request on the same connection). + * Mirrors `LeaseRecord` (src/core/domain.ts) field for field -- there is no decoration on top + * of it any more. Includes `ownerId` (ADR 0003 §4): the session principal that requested the + * lease, distinct from `requesterId` (attribution, defaults to the principal but may differ + * per request on the same connection). + * + * ADR 0004: there is one kind of lease, so `mode` is gone; `ttlMs` and `lastRenewedAt` are + * stored fields of the record rather than anything derived. `ttlMs` is the width this lease + * was granted with, or last renewed with when a renew named one -- what a body-less + * `lease.renew` re-applies, which is why it travels with the record instead of the caller + * having to remember it. `lastRenewedAt` is written at grant and on every renew; it replaces + * the old derived `lastHeartbeatAt` decoration, which was computed as `ttlDeadline - + * heldTtlBackstopMs` and has no answer once every lease carries its own TTL. */ export const leaseRecordSchema = z.object({ id: z.string(), deviceId: z.string(), requesterId: z.string(), ownerId: z.string(), - mode: leaseModeSchema, grantedAt: z.number(), + ttlMs: z.number(), ttlDeadline: z.number(), - lastHeartbeatAt: z.number().optional(), + lastRenewedAt: z.number(), }); const leaseTimingSchema = z.object({ @@ -394,9 +400,8 @@ export const configSchema = z.object({ }), }), lease: z.object({ - heldTtlBackstopMs: z.number(), - detachedTtlMs: z.number(), - heartbeatIntervalMs: z.number(), + defaultTtlMs: z.number(), + maxTtlMs: z.number(), }), diskPressure: z.object({ freeBytesThreshold: z.number() }), eventBuffer: z.object({ capacity: z.number() }), diff --git a/src/core/acquisition-planner.test.ts b/src/core/acquisition-planner.test.ts index 3c50aaab7..ba0540e72 100644 --- a/src/core/acquisition-planner.test.ts +++ b/src/core/acquisition-planner.test.ts @@ -34,7 +34,7 @@ const config: Config = { retryBackoffMultiplier: 2, }, }, - lease: { detachedTtlMs: 100, heldTtlBackstopMs: 100, heartbeatIntervalMs: 25 }, + lease: { defaultTtlMs: 100, maxTtlMs: 100 }, capacity: { strategy: "resource", config: { @@ -157,9 +157,10 @@ describe("AcquisitionPlanner", () => { deviceId: leased.id, grantedAt: 1, id: "lease", - mode: "held" as const, requesterId: "holder", ownerId: "holder", + lastRenewedAt: 1, + ttlMs: 60_000, ttlDeadline: 100, }, ]; diff --git a/src/core/cleanup-executor.test.ts b/src/core/cleanup-executor.test.ts index da637d330..f23e0c507 100644 --- a/src/core/cleanup-executor.test.ts +++ b/src/core/cleanup-executor.test.ts @@ -59,9 +59,9 @@ describe("CleanupExecutor", () => { const device = await seedReady(harness); await harness.registry.createLease({ deviceId: device.id, - mode: "held", requesterId: "agent-1", ownerId: "agent-1", + ttlMs: 60_000, ttlDeadline: 2_000, }); diff --git a/src/core/cleanup/idle-destroy.test.ts b/src/core/cleanup/idle-destroy.test.ts index cb3b25ddb..4cd71a1e0 100644 --- a/src/core/cleanup/idle-destroy.test.ts +++ b/src/core/cleanup/idle-destroy.test.ts @@ -30,7 +30,7 @@ const config: Config = { retryBackoffMultiplier: 2, }, }, - lease: { detachedTtlMs: 1, heldTtlBackstopMs: 1, heartbeatIntervalMs: 1 }, + lease: { defaultTtlMs: 60_000, maxTtlMs: 3_600_000 }, capacity: { strategy: "resource", config: { @@ -116,9 +116,10 @@ describe("idleDestroyRule", () => { deviceId: "dev_1", grantedAt: 0, id: "lse_1", - mode: "held", requesterId: "agent-1", ownerId: "agent-1", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 1, }, ], diff --git a/src/core/cleanup/idle-shutdown.test.ts b/src/core/cleanup/idle-shutdown.test.ts index ecd61167e..df694fb48 100644 --- a/src/core/cleanup/idle-shutdown.test.ts +++ b/src/core/cleanup/idle-shutdown.test.ts @@ -28,7 +28,7 @@ const config: Config = { retryBackoffMultiplier: 2, }, }, - lease: { detachedTtlMs: 1, heldTtlBackstopMs: 1, heartbeatIntervalMs: 1 }, + lease: { defaultTtlMs: 60_000, maxTtlMs: 3_600_000 }, capacity: { strategy: "resource", config: { diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 16a2106c4..6ae8d4b9f 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -73,11 +73,7 @@ describe("loadConfig", () => { maxConcurrentRecoveries: 1, }, idle: { deleteAfterMs: 60 * 60_000, shutdownAfterMs: 10 * 60_000 }, - lease: { - detachedTtlMs: 15 * 60_000, - heldTtlBackstopMs: 60 * 60_000, - heartbeatIntervalMs: 5 * 60_000, - }, + lease: { defaultTtlMs: 15 * 60_000, maxTtlMs: 4 * 60 * 60_000 }, capacity: { strategy: "resource", config: { @@ -184,7 +180,7 @@ describe("loadConfig", () => { configPath, JSON.stringify({ limits: { ios: { maxDevices: 3, maxRunning: 2 }, maxRunning: 4 }, - lease: { detachedTtlMs: 123 }, + lease: { defaultTtlMs: 123 }, }), ); @@ -192,7 +188,7 @@ describe("loadConfig", () => { configPath, filesystem, overrides: { - lease: { detachedTtlMs: 456 }, + lease: { defaultTtlMs: 456 }, limits: { android: { maxRunning: 1 } }, }, systemStats: createStats(), @@ -205,7 +201,7 @@ describe("loadConfig", () => { ios: { maxRunning: 2 }, maxRunning: 4, }); - expect(config.lease.detachedTtlMs).toBe(456); + expect(config.lease.defaultTtlMs).toBe(456); }); it("deeply merges a partial config file", async () => { @@ -255,43 +251,84 @@ describe("loadConfig", () => { ).rejects.toThrow(path); }); - it("accepts a heartbeat interval at the boundary of a quarter of the backstop", async () => { + it("accepts a lease TTL pair at the boundary, where the default equals the cap", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); await filesystem.writeFileAtomic( configPath, - JSON.stringify({ lease: { heldTtlBackstopMs: 40_000, heartbeatIntervalMs: 10_000 } }), + JSON.stringify({ lease: { defaultTtlMs: 40_000, maxTtlMs: 40_000 } }), ); const config = await loadConfig({ configPath, filesystem, systemStats: createStats() }); - expect(config.lease).toMatchObject({ heartbeatIntervalMs: 10_000, heldTtlBackstopMs: 40_000 }); + expect(config.lease).toMatchObject({ defaultTtlMs: 40_000, maxTtlMs: 40_000 }); + }); + + it.each([ + [{ lease: { defaultTtlMs: 0 } }, "lease.defaultTtlMs"], + [{ lease: { maxTtlMs: -1 } }, "lease.maxTtlMs"], + [{ lease: { defaultTtlMs: "soon" } }, "lease.defaultTtlMs"], + ])("rejects a non-positive lease TTL, naming the offending key (%#)", async (contents, path) => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic(configPath, JSON.stringify(contents)); + + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).rejects.toThrow(path); }); - it("rejects a non-positive-integer heartbeat interval", async () => { + it("rejects a defaultTtlMs above maxTtlMs, naming the offending key (ADR 0004)", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); await filesystem.writeFileAtomic( configPath, - JSON.stringify({ lease: { heartbeatIntervalMs: 0 } }), + JSON.stringify({ lease: { defaultTtlMs: 40_001, maxTtlMs: 40_000 } }), ); await expect( loadConfig({ configPath, filesystem, systemStats: createStats() }), - ).rejects.toThrow("lease.heartbeatIntervalMs"); + ).rejects.toThrow("lease.defaultTtlMs"); }); - it("rejects a heartbeat interval that exceeds a quarter of the backstop", async () => { + it("catches the pair rule across layers, not just within one file", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); await filesystem.writeFileAtomic( configPath, - JSON.stringify({ lease: { heldTtlBackstopMs: 40_000, heartbeatIntervalMs: 10_001 } }), + JSON.stringify({ lease: { defaultTtlMs: 60_000 } }), ); + // The file's default is fine against the *default* cap; only the merged config is wrong. await expect( - loadConfig({ configPath, filesystem, systemStats: createStats() }), - ).rejects.toThrow("lease.heartbeatIntervalMs"); - }); + loadConfig({ + configPath, + filesystem, + overrides: { lease: { maxTtlMs: 30_000 } }, + systemStats: createStats(), + }), + ).rejects.toThrow("lease.defaultTtlMs"); + }); + + it.each([["detachedTtlMs"], ["heldTtlBackstopMs"], ["heartbeatIntervalMs"]])( + "warns about the retired lease.%s and ignores it, carrying no value over (ADR 0004)", + async (retired) => { + const filesystem = new MemoryFilesystem(); + const warn = vi.fn(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic(configPath, JSON.stringify({ lease: { [retired]: 1 } })); + + const config = await loadConfig({ + configPath, + filesystem, + systemStats: createStats(), + warn, + }); + + expect(warn).toHaveBeenCalledWith(`Unknown config key: "lease.${retired}"`); + // Not aliased onto anything: the new keys keep their own defaults. + expect(config.lease).toEqual({ defaultTtlMs: 15 * 60_000, maxTtlMs: 4 * 60 * 60_000 }); + }, + ); it("warns about unknown keys without rejecting the file", async () => { const filesystem = new MemoryFilesystem(); diff --git a/src/core/config.ts b/src/core/config.ts index a99e6467c..600434071 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -31,6 +31,17 @@ import { const DEFAULT_CONFIG_PATH = "~/.simlock/config.json"; +/** + * `lease.defaultTtlMs`'s default (ADR 0004 §4): the width a request that names no `ttlMs` is + * granted. Exported because `Registry` needs the same number to migrate a lease record written + * before ADR 0004, which has no stored width of its own -- one definition, read from both + * places, rather than the same fifteen minutes spelled twice. + */ +export const DEFAULT_LEASE_TTL_MS = 15 * 60_000; + +/** `lease.maxTtlMs`'s default: the largest TTL any request or renew may ask for. */ +const DEFAULT_LEASE_MAX_TTL_MS = 4 * 60 * 60_000; + /** * `never` forbids installs even when a request passes `--allow-download` (locked-down * machines/CI). `on-request` (default) preserves today's contract: install only when the @@ -70,9 +81,16 @@ export interface Config { }; }; readonly lease: { - readonly heldTtlBackstopMs: number; - readonly detachedTtlMs: number; - readonly heartbeatIntervalMs: number; + /** + * ADR 0004 §4: the TTL applied to a lease whose `lease.request` carried no `ttlMs` -- that + * request only. It is deliberately *not* the renew fallback: a `lease.renew` given no + * explicit TTL re-applies the lease's own stored width, so a lease granted for longer + * keeps it. + */ + readonly defaultTtlMs: number; + /** The largest TTL a request or a renew may ask for; more is `BAD_REQUEST`, never a + * silent clamp, so a caller is never left believing it has more time than it does. */ + readonly maxTtlMs: number; }; readonly diskPressure: { readonly freeBytesThreshold: number }; readonly eventBuffer: { readonly capacity: number }; @@ -167,7 +185,7 @@ export async function loadConfig({ mergeConfig(defaultConfig(systemStats, strategy), fileConfig), overrideConfig, ) as unknown as Config; - validateHeartbeatInterval(merged); + validateLeaseTtls(merged); return deepFreeze(merged); } @@ -185,13 +203,16 @@ export function effectiveAllowDownload(policy: DownloadPolicy, requested: boolea } /** - * Cross-field check: the heartbeat cadence must be frequent enough, relative to the - * backstop, that a few missed beats (context compaction, a slow tick) still land well - * before the backstop deadline rather than racing it. + * Cross-field check (ADR 0004's Consequences): the default TTL a request falls back to cannot + * exceed the cap every request is measured against, or every defaulted request would be born + * asking for more than the daemon will grant. A violating config fails the daemon start naming + * the offending key rather than being clamped to a value the operator never wrote -- the + * opposite treatment from a retired key, which is a leftover with a safe reading ("ignore it") + * where a self-contradicting TTL pair has none. */ -function validateHeartbeatInterval(config: Config): void { - if (config.lease.heartbeatIntervalMs > config.lease.heldTtlBackstopMs / 4) { - throw invalidValue("lease.heartbeatIntervalMs", "at most lease.heldTtlBackstopMs / 4"); +function validateLeaseTtls(config: Config): void { + if (config.lease.defaultTtlMs > config.lease.maxTtlMs) { + throw invalidValue("lease.defaultTtlMs", "at most lease.maxTtlMs"); } } @@ -292,9 +313,8 @@ function defaultConfig(systemStats: SystemStats, strategy: CapacityStrategyName) }, }, lease: { - heldTtlBackstopMs: 60 * 60_000, - detachedTtlMs: 15 * 60_000, - heartbeatIntervalMs: 5 * 60_000, + defaultTtlMs: DEFAULT_LEASE_TTL_MS, + maxTtlMs: DEFAULT_LEASE_MAX_TTL_MS, }, diskPressure: { freeBytesThreshold: 10 * 1024 ** 3 }, eventBuffer: { capacity: 1_000 }, @@ -392,10 +412,13 @@ function configValidators(strategy: CapacityStrategyName): Record { }); await registry.createLease({ deviceId: registered.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 9_000, }); const driver = new FakeDriver({ clock, platform: "ios" }); @@ -156,9 +156,9 @@ describe("Doctor", () => { }); await registry.createLease({ deviceId: device.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 99_000, }); const driver = new FakeDriver({ clock, platform: "ios" }); @@ -285,9 +285,9 @@ describe("Doctor", () => { }); const lease = await registry.createLease({ deviceId: device.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 99_000, }); await registry.beginRelease(lease.id); @@ -401,9 +401,9 @@ describe("Doctor", () => { }); await registry.createLease({ deviceId: device.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 9_000, }); const driver = new FakeDriver({ clock, platform: "ios" }); @@ -672,9 +672,9 @@ describe("Doctor", () => { const reclaiming = await readyDevice(registry, "simlock-reclaiming", "ios"); const lease = await registry.createLease({ deviceId: reclaiming.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 999_999, }); await registry.beginRelease(lease.id); @@ -868,9 +868,9 @@ describe("Doctor", () => { const device = await readyDevice(registry, "simlock-killed", "ios"); const lease = await registry.createLease({ deviceId: device.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 999_999, }); await registry.beginRelease(lease.id); @@ -921,9 +921,9 @@ describe("Doctor", () => { const device = await readyDevice(registry, "simlock-slow-clean", "ios"); const lease = await registry.createLease({ deviceId: device.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 999_999, }); await registry.beginRelease(lease.id); @@ -1080,7 +1080,6 @@ describe("Doctor", () => { deviceId: "dev_1", grantedAt: 1, id: "lse_1", - mode: "held", requesterId: "agent", ownerId: "agent", ttlDeadline: 999_999, @@ -1173,9 +1172,9 @@ describe("Doctor", () => { const device = await readyDevice(registry, "simlock-leased", "ios"); await registry.createLease({ deviceId: device.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 999_999, }); @@ -1699,9 +1698,9 @@ describe("Doctor with a platform it cannot observe", () => { const device = registry.snapshot.devices[0]!; await registry.createLease({ deviceId: device.id, - mode: "held", ownerId: "agent", requesterId: "agent", + ttlMs: 60_000, ttlDeadline: 90_000, }); @@ -1864,7 +1863,7 @@ function config(stalledTransitionOverrides: Partial stableObservations: 2, }, idle: { deleteAfterMs: 10, shutdownAfterMs: 5 }, - lease: { detachedTtlMs: 60_000, heldTtlBackstopMs: 60_000, heartbeatIntervalMs: 15_000 }, + lease: { defaultTtlMs: 60_000, maxTtlMs: 3_600_000 }, capacity: { strategy: "resource", config: { diff --git a/src/core/domain.ts b/src/core/domain.ts index 1f549ee16..3c5f6c886 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -85,9 +85,23 @@ export interface LeaseRecord { * to `requesterId` -- see `parseLease` in `registry.ts`. */ readonly ownerId: string; - readonly mode: "held" | "detached"; readonly grantedAt: number; + /** + * The width this lease was granted with, or last renewed with when a renew named one (ADR + * 0004 §4). Stored, not derived: a `lease.renew` carrying no `ttlMs` re-applies exactly this, + * rather than falling back to `lease.defaultTtlMs`, so a lease granted for four hours does + * not shrink to fifteen minutes the first time something renews it. A record written before + * ADR 0004 loads with `lease.defaultTtlMs` here -- see `parseLease` in `registry.ts`. + */ + readonly ttlMs: number; readonly ttlDeadline: number; + /** + * When this lease was last renewed -- written at grant and on every renew. It replaces the + * old `lastHeartbeatAt`, which was never stored at all: the dispatcher derived it as + * `ttlDeadline - heldTtlBackstopMs`, arithmetic that only worked while every held lease + * shared one backstop width. A record written before ADR 0004 loads with `grantedAt` here. + */ + readonly lastRenewedAt: number; } /** diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index 36138d1ef..d85e891f1 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -41,7 +41,7 @@ function config(maxDevices = 1): Config { }, stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, - lease: { detachedTtlMs: 100, heldTtlBackstopMs: 100, heartbeatIntervalMs: 25 }, + lease: { defaultTtlMs: 100, maxTtlMs: 100 }, capacity: { strategy: "resource", config: { @@ -103,7 +103,7 @@ async function createHarness( eventBus: bus, expiryScheduler: expiry, registry, - ttl: { detachedMs: 100, heldBackstopMs: 100 }, + ttl: { defaultMs: 100 }, }); let coordinator: LeaseAcquisitionCoordinator | undefined; const queue = new WaitQueue({ @@ -155,14 +155,12 @@ describe("LeaseAcquisitionCoordinator", () => { it("admits one requester and rejects an active or pending duplicate", async () => { const harness = await createHarness(); const granted = await harness.coordinator.request(request, { - mode: "held", ownerId: "agent", requesterId: "agent", }); await expect( harness.coordinator.request(request, { - mode: "held", ownerId: "agent", requesterId: "agent", }), @@ -190,7 +188,6 @@ describe("LeaseAcquisitionCoordinator", () => { if (path === "ready") await seedReady(harness); const granted = await harness.coordinator.request(request, { - mode: "held", ownerId: "agent", requesterId: "agent", }); @@ -205,7 +202,6 @@ describe("LeaseAcquisitionCoordinator", () => { const harness = await createHarness(); const granted = await harness.coordinator.request(request, { - mode: "held", ownerId: "agent", requesterId: "agent", }); @@ -217,7 +213,6 @@ describe("LeaseAcquisitionCoordinator", () => { const empty = await createHarness({ drivers: [] }); await expect( empty.coordinator.request(request, { - mode: "held", ownerId: "missing-driver", requesterId: "missing-driver", }), @@ -228,7 +223,7 @@ describe("LeaseAcquisitionCoordinator", () => { await expect( harness.coordinator.request( { ...request, osVersion: "99" }, - { mode: "held", ownerId: "bad-spec", requesterId: "bad-spec" }, + { ownerId: "bad-spec", requesterId: "bad-spec" }, ), ).rejects.toThrow("Runtime missing"); expect(harness.coordinator.queueDepth).toBe(0); @@ -237,25 +232,21 @@ describe("LeaseAcquisitionCoordinator", () => { it("enforces FIFO, rejects no-wait demand, and skips timed-out waiters", async () => { const harness = await createHarness(); const first = await harness.coordinator.request(request, { - mode: "held", requesterId: "first", ownerId: "first", }); const timedOut = harness.coordinator.request(request, { - mode: "held", requesterId: "timed-out", ownerId: "timed-out", timeoutMs: 10, }); const next = harness.coordinator.request(request, { - mode: "held", ownerId: "next", requesterId: "next", }); await flush(); await expect( harness.coordinator.request(request, { - mode: "held", noWait: true, ownerId: "no-wait", requesterId: "no-wait", @@ -281,7 +272,6 @@ describe("LeaseAcquisitionCoordinator", () => { const progress: string[] = []; const grant = await harness.coordinator.request(request, { - mode: "held", onProgress: (update) => progress.push(update.stage), requesterId: "agent", ownerId: "agent", @@ -295,7 +285,6 @@ describe("LeaseAcquisitionCoordinator", () => { const harness = await createHarness(); harness.driver.failOn("provision", 1, new DriverCrashError("temporary")); const grant = await harness.coordinator.request(request, { - mode: "held", requesterId: "retry", ownerId: "retry", }); @@ -306,7 +295,6 @@ describe("LeaseAcquisitionCoordinator", () => { failing.driver.failOn("makeReady", 1, new DriverCrashError("boot failure")); await expect( failing.coordinator.request(request, { - mode: "held", ownerId: "boot-failure", requesterId: "boot-failure", }), @@ -328,7 +316,6 @@ describe("LeaseAcquisitionCoordinator", () => { const progress: string[] = []; await expect( bootHarness.coordinator.request(request, { - mode: "held", onProgress: (update) => progress.push(update.stage), requesterId: "boot", ownerId: "boot", @@ -340,7 +327,6 @@ describe("LeaseAcquisitionCoordinator", () => { const old = await seedReady(eviction, { ...request, model: "iPhone SE" }); await expect( eviction.coordinator.request(request, { - mode: "held", ownerId: "new-spec", requesterId: "new-spec", }), @@ -368,7 +354,6 @@ describe("LeaseAcquisitionCoordinator", () => { ).length; const acquisition = harness.coordinator.request(request, { - mode: "held", requesterId: "drained", ownerId: "drained", }); @@ -386,7 +371,6 @@ describe("LeaseAcquisitionCoordinator", () => { expect(harness.registry.snapshot.leases).toEqual([]); await expect( harness.coordinator.request(request, { - mode: "held", ownerId: "during-maintenance", requesterId: "during-maintenance", }), @@ -403,7 +387,6 @@ describe("LeaseAcquisitionCoordinator", () => { it("coalesces simultaneous kicks for the same queued waiter", async () => { const harness = await createHarness({ maxDevices: 2 }); const first = await harness.coordinator.request(request, { - mode: "held", requesterId: "first", ownerId: "first", }); @@ -419,7 +402,6 @@ describe("LeaseAcquisitionCoordinator", () => { }); const queued = harness.coordinator.request(request, { - mode: "held", ownerId: "queued", requesterId: "queued", }); @@ -460,12 +442,10 @@ describe("LeaseAcquisitionCoordinator", () => { it("cancels a queued request, emits lease.rejected(cancelled), and frees the requester immediately", async () => { const harness = await createHarness(); await harness.coordinator.request(request, { - mode: "held", ownerId: "first", requesterId: "first", }); const queued = harness.coordinator.request(request, { - mode: "held", ownerId: "queued", requesterId: "queued", }); @@ -484,7 +464,6 @@ describe("LeaseAcquisitionCoordinator", () => { // not RequesterAlreadyLeasedError -- the cancelled requester is no longer pending. await expect( harness.coordinator.request(request, { - mode: "held", noWait: true, ownerId: "queued", requesterId: "queued", @@ -512,7 +491,6 @@ describe("LeaseAcquisitionCoordinator", () => { harness.driver.hangMakeReady(); const acquisition = harness.coordinator.request(request, { - mode: "held", requesterId: "booting", ownerId: "booting", }); @@ -532,7 +510,6 @@ describe("LeaseAcquisitionCoordinator", () => { await expect( harness.coordinator.request(request, { - mode: "held", ownerId: "still-maintained", requesterId: "still-maintained", }), @@ -541,7 +518,6 @@ describe("LeaseAcquisitionCoordinator", () => { await harness.coordinator.endMaintenance(); await expect( harness.coordinator.request(request, { - mode: "held", ownerId: "reopened", requesterId: "reopened", }), @@ -561,7 +537,7 @@ describe("LeaseAcquisitionCoordinator", () => { }); const granted = await harness.coordinator.request( { ...request, full: true }, - { mode: "held", ownerId: "agent", requesterId: "agent" }, + { ownerId: "agent", requesterId: "agent" }, ); expect(granted.device.spec).toMatchObject({ full: true }); @@ -570,7 +546,6 @@ describe("LeaseAcquisitionCoordinator", () => { it("never stamps full: false onto a spec for a plain request", async () => { const harness = await createHarness(); const granted = await harness.coordinator.request(request, { - mode: "held", requesterId: "agent", ownerId: "agent", }); @@ -594,7 +569,7 @@ describe("LeaseAcquisitionCoordinator", () => { const granted = await harness.coordinator.request( { ...request, full: true }, - { mode: "held", ownerId: "agent", requesterId: "agent" }, + { ownerId: "agent", requesterId: "agent" }, ); // A fresh device was provisioned rather than the warm slim one being handed out. @@ -607,7 +582,7 @@ describe("LeaseAcquisitionCoordinator", () => { const fullRequest = await harness.coordinator.request( { ...request, full: true }, - { mode: "held", ownerId: "agent-full", requesterId: "agent-full" }, + { ownerId: "agent-full", requesterId: "agent-full" }, ); expect(fullRequest.device.spec).not.toHaveProperty("full"); diff --git a/src/core/lease-acquisition-coordinator.ts b/src/core/lease-acquisition-coordinator.ts index 1624cf9af..d802c471a 100644 --- a/src/core/lease-acquisition-coordinator.ts +++ b/src/core/lease-acquisition-coordinator.ts @@ -419,7 +419,6 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { async #grant(waiter: AcquisitionWaiter, deviceId: string): Promise { const { device, lease } = await this.options.leases.grant({ deviceId, - mode: waiter.options.mode, ownerId: waiter.options.ownerId, requesterId: waiter.options.requesterId, ...(waiter.options.ttlMs === undefined ? {} : { ttlMs: waiter.options.ttlMs }), diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index 409dc58ab..8ab117081 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -38,7 +38,7 @@ function config(overrides: Partial = {}): Config { }, stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, - lease: { detachedTtlMs: 100, heldTtlBackstopMs: 100, heartbeatIntervalMs: 25, ...overrides }, + lease: { defaultTtlMs: 100, maxTtlMs: 14_400_000, ...overrides }, capacity: { strategy: "resource", config: { @@ -152,14 +152,12 @@ describe("LeaseEngine", () => { }); const harness = await createHarness({ driver }); const first = await harness.engine.request(request, { - mode: "held", ownerId: "first", requesterId: "first", }); const release = harness.engine.release(first.lease.id, "explicit"); const second = harness.engine.request(request, { - mode: "held", ownerId: "second", requesterId: "second", }); @@ -189,7 +187,6 @@ describe("LeaseEngine", () => { }); const harness = await createHarness({ driver }); const first = await harness.engine.request(request, { - mode: "held", ownerId: "first", requesterId: "first", }); @@ -197,7 +194,6 @@ describe("LeaseEngine", () => { await harness.engine.release(first.lease.id, "explicit"); const progress: LeaseProgress[] = []; const second = harness.engine.request(request, { - mode: "held", onProgress: (update) => progress.push(update), requesterId: "second", ownerId: "second", @@ -225,13 +221,11 @@ describe("LeaseEngine", () => { }); const harness = await createHarness({ driver }); await harness.engine.request(request, { - mode: "held", ownerId: "holder", requesterId: "holder", }); const progress: LeaseProgress[] = []; void harness.engine.request(request, { - mode: "held", onProgress: (update) => progress.push(update), requesterId: "queued", ownerId: "queued", @@ -251,7 +245,6 @@ describe("LeaseEngine", () => { }, }); const first = await harness.engine.request(request, { - mode: "held", ownerId: "first", requesterId: "first", }); @@ -283,7 +276,6 @@ describe("LeaseEngine", () => { const different = { ...request, model: "iPhone SE" }; const grant = await harness.engine.request(different, { - mode: "held", noWait: true, requesterId: "new-spec", ownerId: "new-spec", @@ -326,7 +318,6 @@ describe("LeaseEngine", () => { await expect( harness.engine.request(request, { - mode: "held", ownerId: "ios-demand", requesterId: "ios-demand", }), @@ -355,7 +346,6 @@ describe("LeaseEngine", () => { harness.engine.request( { ...request, model: "iPhone SE" }, { - mode: "held", noWait: true, requesterId: "new-spec", ownerId: "new-spec", @@ -377,7 +367,6 @@ describe("LeaseEngine", () => { const grant = await harness.engine.request( { ...request, model: "iPhone SE" }, { - mode: "held", requesterId: "new-spec", ownerId: "new-spec", }, @@ -396,7 +385,6 @@ describe("LeaseEngine", () => { driver.failOn("reclaim", 1, new DriverCrashError("purge exploded")); const harness = await createHarness({ driver }); const first = await harness.engine.request(request, { - mode: "held", ownerId: "first", requesterId: "first", }); @@ -427,7 +415,6 @@ describe("LeaseEngine", () => { // one, which is exactly the bug quarantine exists to prevent (#21). await expect( harness.engine.request(request, { - mode: "held", noWait: true, ownerId: "second", requesterId: "second", @@ -446,7 +433,6 @@ describe("LeaseEngine", () => { driver.failOn("makeReady", 2, new Error("not ready")); const harness = await createHarness({ driver }); const first = await harness.engine.request(request, { - mode: "held", ownerId: "first", requesterId: "first", }); @@ -475,7 +461,6 @@ describe("LeaseEngine", () => { }, }); const holder = await harness.engine.request(request, { - mode: "held", requesterId: "ios-holder", ownerId: "ios-holder", }); @@ -483,7 +468,6 @@ describe("LeaseEngine", () => { await expect( harness.engine.request(androidRequest, { - mode: "held", noWait: true, requesterId: "android-no-wait", ownerId: "android-no-wait", @@ -495,7 +479,6 @@ describe("LeaseEngine", () => { await harness.engine.release(holder.lease.id, "explicit"); await expect( harness.engine.request(androidRequest, { - mode: "held", ownerId: "android", requesterId: "android", }), @@ -514,9 +497,9 @@ describe("LeaseEngine", () => { const unleasedDevice = await seedReady(harness); await harness.registry.createLease({ deviceId: leasedDevice.id, - mode: "detached", requesterId: "active", ownerId: "active", + ttlMs: 60_000, ttlDeadline: 2_000, }); @@ -563,9 +546,9 @@ describe("LeaseEngine", () => { const device = await seedReady(harness); const lease = await harness.registry.createLease({ deviceId: device.id, - mode: "held", requesterId: "former", ownerId: "former", + ttlMs: 60_000, ttlDeadline: 2_000, }); await harness.registry.beginRelease(lease.id); @@ -588,9 +571,9 @@ describe("LeaseEngine", () => { const device = await seedReady(harness); await harness.registry.createLease({ deviceId: device.id, - mode: "detached", ownerId: requesterId, requesterId, + ttlMs: 60_000, ttlDeadline: 2_000, }); } @@ -601,7 +584,6 @@ describe("LeaseEngine", () => { expect(harness.engine.runningCapacity.global.overLimit).toBe(true); await expect( harness.engine.request(request, { - mode: "held", noWait: true, ownerId: "three", requesterId: "three", @@ -621,12 +603,10 @@ describe("LeaseEngine", () => { const harness = await createHarness({ driver }); const first = harness.engine.request(request, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); const second = harness.engine.request(request, { - mode: "held", ownerId: "agent-2", requesterId: "agent-2", }); @@ -659,12 +639,10 @@ describe("LeaseEngine", () => { driver.hangMakeReady(); void harness.engine.request(request, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); void harness.engine.request(request, { - mode: "held", ownerId: "agent-2", requesterId: "agent-2", }); @@ -686,12 +664,10 @@ describe("LeaseEngine", () => { const harness = await createHarness({ driver }); const first = harness.engine.request(request, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); const second = harness.engine.request(request, { - mode: "held", ownerId: "agent-2", requesterId: "agent-2", }); @@ -717,7 +693,6 @@ describe("LeaseEngine", () => { const progress: string[] = []; const grant = await harness.engine.request(request, { - mode: "held", onProgress: (update) => progress.push(update.stage), requesterId: "agent-1", ownerId: "agent-1", @@ -740,7 +715,6 @@ describe("LeaseEngine", () => { const progress: string[] = []; const grant = await harness.engine.request(request, { - mode: "held", onProgress: (update) => progress.push(update.stage), requesterId: "agent-1", ownerId: "agent-1", @@ -776,7 +750,6 @@ describe("LeaseEngine", () => { await seedReady(harness); const grant = await harness.engine.request(request, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); @@ -801,7 +774,6 @@ describe("LeaseEngine", () => { const provisioned: string[] = []; const provisionedGrant = await harness.engine.request(request, { - mode: "held", onProgress: (progress) => provisioned.push(progress.stage), requesterId: "provisioned", ownerId: "provisioned", @@ -818,7 +790,6 @@ describe("LeaseEngine", () => { }); const booted: string[] = []; await harness.engine.request(request, { - mode: "held", onProgress: (progress) => booted.push(progress.stage), requesterId: "shutdown", ownerId: "shutdown", @@ -831,13 +802,11 @@ describe("LeaseEngine", () => { const driver = new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" }); const harness = await createHarness({ driver }); const holder = await harness.engine.request(request, { - mode: "held", ownerId: "holder", requesterId: "holder", }); const progress: string[] = []; const queued = harness.engine.request(request, { - mode: "held", onProgress: (update) => progress.push(update.stage), requesterId: "queued", ownerId: "queued", @@ -847,7 +816,6 @@ describe("LeaseEngine", () => { await expect( harness.engine.request(request, { - mode: "held", noWait: true, onProgress: () => progress.push("unexpected"), requesterId: "no-wait", @@ -862,7 +830,6 @@ describe("LeaseEngine", () => { const callbackFailure = await createHarness(); await expect( callbackFailure.engine.request(request, { - mode: "held", onProgress: () => { throw new Error("client disconnected"); }, @@ -876,13 +843,11 @@ describe("LeaseEngine", () => { it("detaches progress from a queued request without cancelling its lease", async () => { const harness = await createHarness(); const holder = await harness.engine.request(request, { - mode: "held", ownerId: "holder", requesterId: "holder", }); const progress: string[] = []; const queued = harness.engine.request(request, { - mode: "held", onProgress: (update) => progress.push(update.stage), requesterId: "queued", ownerId: "queued", @@ -900,12 +865,10 @@ describe("LeaseEngine", () => { it("cancels a queued request through the QueueControl facade and frees the requester for a later grant", async () => { const harness = await createHarness(); const holder = await harness.engine.request(request, { - mode: "held", ownerId: "holder", requesterId: "holder", }); const queued = harness.engine.request(request, { - mode: "held", ownerId: "queued", requesterId: "queued", }); @@ -917,29 +880,25 @@ describe("LeaseEngine", () => { await harness.engine.release(holder.lease.id, "explicit"); await expect( - harness.engine.request(request, { mode: "held", ownerId: "queued", requesterId: "queued" }), + harness.engine.request(request, { ownerId: "queued", requesterId: "queued" }), ).resolves.toMatchObject({ lease: { ownerId: "queued", requesterId: "queued" } }); }); it("queues at capacity in FIFO order across three waiters", async () => { const harness = await createHarness(); const first = await harness.engine.request(request, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); const second = harness.engine.request(request, { - mode: "held", ownerId: "agent-2", requesterId: "agent-2", }); const third = harness.engine.request(request, { - mode: "held", ownerId: "agent-3", requesterId: "agent-3", }); const fourth = harness.engine.request(request, { - mode: "held", ownerId: "agent-4", requesterId: "agent-4", }); @@ -962,17 +921,14 @@ describe("LeaseEngine", () => { it("wakes exactly the queue head on release and reuses its reclaimed ready device", async () => { const harness = await createHarness(); const first = await harness.engine.request(request, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); const second = harness.engine.request(request, { - mode: "held", ownerId: "agent-2", requesterId: "agent-2", }); const third = harness.engine.request(request, { - mode: "held", ownerId: "agent-3", requesterId: "agent-3", }); @@ -1002,12 +958,10 @@ describe("LeaseEngine", () => { }); const harness = await createHarness({ driver }); const first = await harness.engine.request(request, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); const queued = harness.engine.request(request, { - mode: "held", ownerId: "agent-2", requesterId: "agent-2", }); @@ -1023,14 +977,12 @@ describe("LeaseEngine", () => { it("rejects a no-wait request at capacity with a typed error", async () => { const harness = await createHarness(); await harness.engine.request(request, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); await expect( harness.engine.request(request, { - mode: "held", noWait: true, ownerId: "agent-2", requesterId: "agent-2", @@ -1041,20 +993,17 @@ describe("LeaseEngine", () => { it("rejects a timed-out queue entry and skips it on a later release", async () => { const harness = await createHarness(); const first = await harness.engine.request(request, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); const progress: string[] = []; const timedOut = harness.engine.request(request, { - mode: "held", onProgress: (update) => progress.push(update.stage), requesterId: "agent-2", ownerId: "agent-2", timeoutMs: 10, }); const next = harness.engine.request(request, { - mode: "held", ownerId: "agent-3", requesterId: "agent-3", }); @@ -1070,15 +1019,13 @@ describe("LeaseEngine", () => { }); }); - it("expires an un-renewed held lease, serves the queue, and extends detached leases", async () => { - const harness = await createHarness({ lease: { detachedTtlMs: 20, heldTtlBackstopMs: 10 } }); + it("expires an un-renewed lease at its deadline and serves the queue with its device", async () => { + const harness = await createHarness({ lease: { defaultTtlMs: 10 } }); await harness.engine.request(request, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); const queued = harness.engine.request(request, { - mode: "held", ownerId: "agent-2", requesterId: "agent-2", }); @@ -1089,35 +1036,35 @@ describe("LeaseEngine", () => { await expect(queued).resolves.toMatchObject({ lease: { ownerId: "agent-2", requesterId: "agent-2" }, }); + }); - const detachedHarness = await createHarness({ lease: { detachedTtlMs: 20 } }); - const detached = await detachedHarness.engine.request(request, { - mode: "detached", + it("keeps a renewed lease past the deadline it was granted with", async () => { + const harness = await createHarness({ lease: { defaultTtlMs: 20 } }); + const granted = await harness.engine.request(request, { requesterId: "agent-3", ownerId: "agent-3", }); - const renewed = await detachedHarness.engine.renew(detached.lease.id, 30); - detachedHarness.clock.advance(20); + const renewed = await harness.engine.renew(granted.lease.id, 30); + harness.clock.advance(20); await flush(); expect(renewed.ttlDeadline).toBe(1_030); - expect(detachedHarness.registry.snapshot.leases).toHaveLength(1); + expect(harness.registry.snapshot.leases).toHaveLength(1); }); - it("renews a held lease via the engine, keeping it alive past its original backstop", async () => { - const harness = await createHarness({ lease: { detachedTtlMs: 20, heldTtlBackstopMs: 10 } }); - const held = await harness.engine.request(request, { - mode: "held", + it("renews via the engine, re-arming the expiry timer at the new deadline", async () => { + const harness = await createHarness({ lease: { defaultTtlMs: 10 } }); + const granted = await harness.engine.request(request, { ownerId: "agent-1", requesterId: "agent-1", }); harness.clock.advance(6); - const renewed = await harness.engine.renew(held.lease.id, 20); + const renewed = await harness.engine.renew(granted.lease.id, 20); expect(renewed.ttlDeadline).toBe(1_026); - // The original backstop deadline (1_010) has now passed, but the renewal re-armed - // the expiry timer at the new deadline, so the lease must still be alive. + // The grant-time deadline (1_010) has now passed, but the renewal re-armed the expiry + // timer at the new one, so the lease must still be alive. harness.clock.advance(4); await flush(); expect(harness.registry.snapshot.leases).toHaveLength(1); @@ -1127,16 +1074,33 @@ describe("LeaseEngine", () => { expect(harness.registry.snapshot.leases).toHaveLength(0); }); + it("grants at the request's own ttlMs, and re-applies that width on a body-less renew", async () => { + const harness = await createHarness({ lease: { defaultTtlMs: 10 } }); + const granted = await harness.engine.request(request, { + ownerId: "agent-1", + requesterId: "agent-1", + ttlMs: 40, + }); + expect(granted.lease).toMatchObject({ ttlMs: 40, ttlDeadline: 1_040 }); + + harness.clock.advance(5); + // No TTL named: the lease keeps its own 40ms width rather than snapping back to the + // 10ms `lease.defaultTtlMs` (ADR 0004 §4). + await expect(harness.engine.renew(granted.lease.id)).resolves.toMatchObject({ + ttlMs: 40, + ttlDeadline: 1_045, + }); + }); + it("enforces one active request or lease per requester, then permits another after release", async () => { const harness = await createHarness(); const first = await harness.engine.request(request, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); await expect( - harness.engine.request(request, { mode: "held", ownerId: "agent-1", requesterId: "agent-1" }), + harness.engine.request(request, { ownerId: "agent-1", requesterId: "agent-1" }), ).rejects.toMatchObject({ existingLeaseId: first.lease.id, message: expect.stringContaining(first.lease.id), @@ -1146,7 +1110,7 @@ describe("LeaseEngine", () => { await harness.engine.settle(); expect(harness.clock.pendingTimerCount).toBe(0); await expect( - harness.engine.request(request, { mode: "held", ownerId: "agent-1", requesterId: "agent-1" }), + harness.engine.request(request, { ownerId: "agent-1", requesterId: "agent-1" }), ).resolves.toMatchObject({ lease: { ownerId: "agent-1", requesterId: "agent-1" } }); }); @@ -1157,7 +1121,6 @@ describe("LeaseEngine", () => { const harness = await createHarness({ driver }); const grant = await harness.engine.request(request, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); @@ -1176,7 +1139,7 @@ describe("LeaseEngine", () => { const harness = await createHarness({ driver }); await expect( - harness.engine.request(request, { mode: "held", ownerId: "agent-1", requesterId: "agent-1" }), + harness.engine.request(request, { ownerId: "agent-1", requesterId: "agent-1" }), ).rejects.toBeInstanceOf(BootTimeoutError); expect(harness.registry.snapshot.devices).toMatchObject([{ state: "deleted" }]); @@ -1188,7 +1151,6 @@ describe("LeaseEngine", () => { const harness = await createHarness(); await harness.engine.request(request, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); @@ -1208,7 +1170,7 @@ describe("LeaseEngine", () => { // that replaced it: the lease is released registry-only on the convergence path, // and its reclaim proceeds in the background. describe("LeaseEngine startup reclaim backgrounding (#43)", () => { - it("converges without waiting for an orphaned held lease's reclaim, and a fresh request is served immediately after", async () => { + it("converges without waiting for an in-flight reclaim, and a fresh request is served immediately after", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ availableOsVersions: ["26.5"], @@ -1226,14 +1188,14 @@ describe("LeaseEngine startup reclaim backgrounding (#43)", () => { maxRunning: 2, }, }); - // A held lease with no live holder: exactly what an ungraceful restart leaves in - // the registry (nothing renews or releases it -- the daemon process it lived on - // is gone). - const orphan = await harness.engine.request(request, { - mode: "held", - ownerId: "orphan", - requesterId: "orphan", + // Under ADR 0004 convergence itself releases nothing -- there is no orphan sweep left -- + // so the in-flight reclaim it must not block on is produced the way one actually arises: + // a release commits the registry half and hands the 34s purge off to the background. + const released = await harness.engine.request(request, { + ownerId: "previous-holder", + requesterId: "previous-holder", }); + await harness.engine.release(released.lease.id, "explicit"); const convergeStartedAt = harness.clock.now(); await harness.engine.convergeRunningCapacity(); @@ -1241,18 +1203,17 @@ describe("LeaseEngine startup reclaim backgrounding (#43)", () => { // the 34s reclaim above. expect(harness.clock.now()).toBe(convergeStartedAt); expect( - harness.registry.snapshot.devices.find((device) => device.id === orphan.device.id)?.state, + harness.registry.snapshot.devices.find((device) => device.id === released.device.id)?.state, ).toBe("reclaiming"); expect(harness.registry.snapshot.leases).toEqual([]); - // A fresh request is servable right away -- capacity allows a second device, and - // the orphaned one being mid-reclaim never blocks it. Still 0ms elapsed. + // A fresh request is servable right away -- capacity allows a second device, and the + // one still mid-reclaim never blocks it. Still 0ms elapsed. const granted = await harness.engine.request(request, { - mode: "held", requesterId: "new-agent", ownerId: "new-agent", }); - expect(granted.device.id).not.toBe(orphan.device.id); + expect(granted.device.id).not.toBe(released.device.id); expect(harness.clock.now()).toBe(convergeStartedAt); }); @@ -1272,11 +1233,11 @@ describe("LeaseEngine startup reclaim backgrounding (#43)", () => { maxRunning: 1, }, }); - const orphan = await harness.engine.request(request, { - mode: "held", - ownerId: "orphan", - requesterId: "orphan", + const released = await harness.engine.request(request, { + ownerId: "previous-holder", + requesterId: "previous-holder", }); + await harness.engine.release(released.lease.id, "explicit"); await harness.engine.convergeRunningCapacity(); expect(harness.registry.snapshot.devices).toMatchObject([{ state: "reclaiming" }]); @@ -1287,7 +1248,6 @@ describe("LeaseEngine startup reclaim backgrounding (#43)", () => { // one still mid-reclaim. await expect( harness.engine.request(request, { - mode: "held", noWait: true, ownerId: "new-agent", requesterId: "new-agent", @@ -1301,11 +1261,10 @@ describe("LeaseEngine startup reclaim backgrounding (#43)", () => { // Once the reclaim genuinely finishes, the same device becomes grantable again. await expect( harness.engine.request(request, { - mode: "held", ownerId: "new-agent", requesterId: "new-agent", }), - ).resolves.toMatchObject({ device: { id: orphan.device.id } }); + ).resolves.toMatchObject({ device: { id: released.device.id } }); }); it("shuts down already-ready excess capacity during convergence without waiting on an in-flight reclaim, and the reclaim settles inside the same limit", async () => { @@ -1328,11 +1287,11 @@ describe("LeaseEngine startup reclaim backgrounding (#43)", () => { maxRunning: 1, }, }); - const orphan = await harness.engine.request(request, { - mode: "held", - ownerId: "orphan", - requesterId: "orphan", + const released = await harness.engine.request(request, { + ownerId: "previous-holder", + requesterId: "previous-holder", }); + await harness.engine.release(released.lease.id, "explicit"); const extraReady = await seedReady(harness); await harness.engine.convergeRunningCapacity(); @@ -1348,7 +1307,7 @@ describe("LeaseEngine startup reclaim backgrounding (#43)", () => { harness.registry.snapshot.devices.find((device) => device.id === extraReady.id)?.state, ).toBe("shutdown"); expect( - harness.registry.snapshot.devices.find((device) => device.id === orphan.device.id)?.state, + harness.registry.snapshot.devices.find((device) => device.id === released.device.id)?.state, ).toBe("reclaiming"); // The background reclaim settles afterward. Its own capacity check @@ -1358,7 +1317,7 @@ describe("LeaseEngine startup reclaim backgrounding (#43)", () => { clock.advance(34_000); await flush(); expect( - harness.registry.snapshot.devices.find((device) => device.id === orphan.device.id)?.state, + harness.registry.snapshot.devices.find((device) => device.id === released.device.id)?.state, ).toBe("ready"); expect(harness.engine.runningCapacity.ios.overLimit).toBe(false); }); @@ -1403,12 +1362,13 @@ describe("LeaseEngine startup reclaim backgrounding (#43)", () => { systemStats: systemStats(), }); const granted = await engine1.request(request, { - mode: "held", - ownerId: "orphan", - requesterId: "orphan", + ownerId: "previous-holder", + requesterId: "previous-holder", }); + // The holder released, so the purge behind it is running in the background... + await engine1.release(granted.lease.id, "explicit"); - // Ungraceful restart of the *same* process: convergence backgrounds the reclaim... + // ...convergence leaves it alone (it is claimed by this process)... await engine1.convergeRunningCapacity(); expect(registry1.snapshot.devices).toMatchObject([ { id: granted.device.id, state: "reclaiming" }, @@ -1450,24 +1410,23 @@ describe("LeaseEngine startup reclaim backgrounding (#43)", () => { expect(driver.calls.filter((call) => call.operation === "shutdown")).toHaveLength(1); }); - it("leaves no armed timer behind for a detached lease it is disposed with", async () => { - const harness = await createHarness({ lease: { detachedTtlMs: 900_000 } }); + it("leaves no armed timer behind for a lease it is disposed with", async () => { + const harness = await createHarness({ lease: { defaultTtlMs: 900_000 } }); await harness.engine.request(request, { - mode: "detached", - ownerId: "detached-holder", - requesterId: "detached-holder", + ownerId: "holder", + requesterId: "holder", }); expect(harness.clock.pendingTimerCount).toBeGreaterThan(0); harness.engine.dispose(); // A real `setTimeout` holds the event loop open, so a timer surviving disposal is a - // daemon that has decided to stop and cannot: `daemon stop` used to hang for the - // fifteen minutes of an outstanding detached lease's TTL. Held leases hid it, because - // shutdown releases them and releasing cancels the timer. + // daemon that has decided to stop and cannot: `daemon stop` used to hang for the whole + // of an outstanding lease's TTL. Under ADR 0004 that is every lease, since a stop + // releases none of them. expect(harness.clock.pendingTimerCount).toBe(0); // The lease itself is untouched -- disposal cancels a timer, it does not expire a - // lease, which is what lets a detached lease survive the restart. + // lease, which is what lets a lease survive the restart with its deadline intact. expect(harness.registry.snapshot.leases).toHaveLength(1); }); }); diff --git a/src/core/lease-engine.ts b/src/core/lease-engine.ts index bbea23558..fc66acfb6 100644 --- a/src/core/lease-engine.ts +++ b/src/core/lease-engine.ts @@ -117,10 +117,7 @@ export class LeaseEngine { eventBus: options.eventBus, expiryScheduler: this.#expiry, registry: options.registry, - ttl: { - detachedMs: options.config.lease.detachedTtlMs, - heldBackstopMs: options.config.lease.heldTtlBackstopMs, - }, + ttl: { defaultMs: options.config.lease.defaultTtlMs }, }); this.#queue = new WaitQueue({ clock: options.clock, @@ -203,11 +200,6 @@ export class LeaseEngine { }, quarantineRestore: { restore: () => this.#quarantine.restore() }, registry: options.registry, - releases: { - releaseOrphaned: async (leaseId) => { - await this.#releaseCoordinator.release(leaseId, "orphaned"); - }, - }, timers: this.#leases, }); this.healthMonitor = new LeaseHealthMonitor({ @@ -229,7 +221,7 @@ export class LeaseEngine { return this.#acquisition.request(request, options); } - async release(leaseId: string, reason: "closed" | "explicit" | "killed"): Promise { + async release(leaseId: string, reason: "explicit" | "killed"): Promise { await this.#releaseCoordinator.release(leaseId, reason); } @@ -265,18 +257,15 @@ export class LeaseEngine { } /** - * Cancels every timer this engine armed, so the process can actually exit. + * Cancels every timer this engine armed, so the process can actually exit. A lease's TTL is + * a `setTimeout` that outlives the decision to shut down, so without this a daemon with an + * outstanding lease keeps running long after `daemon stop` -- up to that lease's whole TTL. * - * The expiry timers matter as much as the quarantine ones and were missed: a lease's - * TTL is a `setTimeout` that outlives the decision to shut down, so a daemon with an - * outstanding *detached* lease kept running long after `daemon stop` -- up to the - * fifteen minutes of its own TTL. Held leases hid it, because releasing them on the way - * out cancels their timers; detached leases are deliberately left alone, since their - * liveness is the TTL rather than a connection. - * - * Cancelling expires nothing early and loses nothing: `ttlDeadline` is persisted with - * the lease, and `LeaseExpiryScheduler.restore` re-arms it on the next start, which is - * also what makes a detached lease survive a restart intact. + * Cancelling expires nothing early and loses nothing, and under ADR 0004 releases nothing + * either: `ttlDeadline` is persisted with the lease, and `LeaseExpiryScheduler.restore` + * re-arms it on the next start. That is exactly what makes a lease survive a daemon restart + * intact, and a lease whose deadline passed while no daemon was running expire as soon as + * one is there to expire it. */ dispose(): void { this.#quarantine.dispose(); @@ -334,17 +323,11 @@ export class LeaseEngine { return this.#acquisition.pendingRequestOwner(requesterId); } - // fallow-ignore-next-line unused-class-member -- reached through the LeaseCommands port by DaemonServer (same as the sibling heartbeat). + // fallow-ignore-next-line unused-class-member -- reached through the LeaseCommands port by DaemonServer, which structural typing hides from the analyzer. async renew(leaseId: string, ttlMs?: number): Promise { return this.#releaseCoordinator.renew(leaseId, ttlMs); } - /** Slides a held lease's TTL back out to a full backstop from now. */ - // fallow-ignore-next-line unused-class-member -- reached through the LeaseCommands port, which structural typing hides from the analyzer (same as the sibling renew). - async heartbeat(leaseId: string): Promise { - return this.#releaseCoordinator.heartbeat(leaseId); - } - /** * Runs one cleanup action through the same decision queue as leasing. The * reservation prevents a concurrent lease decision from selecting the diff --git a/src/core/lease-expiry-scheduler.test.ts b/src/core/lease-expiry-scheduler.test.ts index 0d8dec97e..6993e4d8a 100644 --- a/src/core/lease-expiry-scheduler.test.ts +++ b/src/core/lease-expiry-scheduler.test.ts @@ -7,9 +7,10 @@ const lease = (id: string, ttlDeadline: number) => ({ deviceId: `dev_${id}`, grantedAt: 0, id, - mode: "detached" as const, + lastRenewedAt: 0, requesterId: "agent", ownerId: "agent", + ttlMs: ttlDeadline, ttlDeadline, }); diff --git a/src/core/lease-health-monitor.test.ts b/src/core/lease-health-monitor.test.ts index 2bff4827c..53e135884 100644 --- a/src/core/lease-health-monitor.test.ts +++ b/src/core/lease-health-monitor.test.ts @@ -38,7 +38,7 @@ function config(overrides: Partial = {}): Config { ...overrides, }, idle: { deleteAfterMs: 30_000, shutdownAfterMs: 10_000 }, - lease: { detachedTtlMs: 100, heldTtlBackstopMs: 100, heartbeatIntervalMs: 25 }, + lease: { defaultTtlMs: 100, maxTtlMs: 100 }, capacity: { strategy: "resource", config: { @@ -129,9 +129,9 @@ async function seedLeased( }); const lease = await harness.registry.createLease({ deviceId: device.id, - mode: "held", requesterId: options.requesterId ?? "agent-1", ownerId: options.requesterId ?? "agent-1", + ttlMs: 60_000, ttlDeadline: 10_000_000, }); return { device, lease }; diff --git a/src/core/lease-lifecycle.test.ts b/src/core/lease-lifecycle.test.ts index b225f33f5..8f4c3188f 100644 --- a/src/core/lease-lifecycle.test.ts +++ b/src/core/lease-lifecycle.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it, vi } from "vitest"; import { EventBus } from "../bus/index.js"; import { FakeClock, MemoryFilesystem, type Filesystem } from "../ports/index.js"; import { LeaseExpiryScheduler } from "./lease-expiry-scheduler.js"; -import { DetachedLeaseHeartbeatError, LeaseLifecycle } from "./lease-lifecycle.js"; +import { LeaseLifecycle } from "./lease-lifecycle.js"; import { Registry } from "./registry.js"; const statePath = "/home/agent/.simlock/state.json"; @@ -39,114 +39,108 @@ async function createHarness(options: { readonly filesystem?: Filesystem } = {}) eventBus, expiryScheduler, registry, - ttl: { detachedMs: 20, heldBackstopMs: 10 }, + ttl: { defaultMs: 20 }, }); return { clock, device, eventBus, expiryScheduler, lifecycle, registry }; } describe("LeaseLifecycle", () => { - it("grants held and detached leases with their respective TTLs after committing", async () => { - const held = await createHarness(); - const heldGrant = await held.lifecycle.grant({ - deviceId: held.device.id, - mode: "held", - requesterId: "held-agent", - ownerId: "held-agent", + it("grants a lease at lease.defaultTtlMs, storing that width and lastRenewedAt", async () => { + const harness = await createHarness(); + const grant = await harness.lifecycle.grant({ + deviceId: harness.device.id, + requesterId: "agent", + ownerId: "agent", }); - expect(heldGrant.lease.ttlDeadline).toBe(1_010); - expect(held.registry.snapshot.devices).toMatchObject([{ id: held.device.id, state: "leased" }]); - expect(held.eventBus.replay()).toContainEqual( + expect(grant.lease).toMatchObject({ lastRenewedAt: 1_000, ttlMs: 20, ttlDeadline: 1_020 }); + expect(harness.registry.snapshot.devices).toMatchObject([ + { id: harness.device.id, state: "leased" }, + ]); + expect(harness.eventBus.replay()).toContainEqual( expect.objectContaining({ event: "lease.granted", - payload: expect.objectContaining({ leaseId: heldGrant.lease.id }), + payload: expect.objectContaining({ leaseId: grant.lease.id }), }), ); - - const detached = await createHarness(); - const detachedGrant = await detached.lifecycle.grant({ - deviceId: detached.device.id, - mode: "detached", - requesterId: "detached-agent", - ownerId: "detached-agent", - }); - expect(detachedGrant.lease.ttlDeadline).toBe(1_020); }); - it("renews detached leases and replaces their timer", async () => { + it("grants a lease at the width the request asked for, and stores that instead", async () => { const harness = await createHarness(); - const detached = await harness.lifecycle.grant({ + const grant = await harness.lifecycle.grant({ deviceId: harness.device.id, - mode: "detached", requesterId: "agent", ownerId: "agent", + ttlMs: 50, }); - const renewed = await harness.lifecycle.renew(detached.lease.id, 30); - expect(renewed.ttlDeadline).toBe(1_030); - harness.clock.advance(20); - await Promise.resolve(); - expect(harness.registry.snapshot.leases).toHaveLength(1); - expect(harness.eventBus.replay()).toContainEqual( - expect.objectContaining({ - event: "lease.renewed", - payload: { leaseId: detached.lease.id, newDeadline: 1_030 }, - }), - ); + expect(grant.lease).toMatchObject({ ttlMs: 50, ttlDeadline: 1_050 }); }); - it("renews a held lease, extending its deadline and re-arming the expiry timer", async () => { - const held = await createHarness(); - const grant = await held.lifecycle.grant({ - deviceId: held.device.id, - mode: "held", + it("renews with an explicit ttlMs, re-arming the timer and storing the new width", async () => { + const harness = await createHarness(); + const grant = await harness.lifecycle.grant({ + deviceId: harness.device.id, requesterId: "agent", ownerId: "agent", }); - expect(grant.lease.ttlDeadline).toBe(1_010); + expect(grant.lease.ttlDeadline).toBe(1_020); - // Renew with an explicit TTL just before the original (grant-time) deadline would fire. - held.clock.advance(8); - const renewed = await held.lifecycle.renew(grant.lease.id, 30); - expect(renewed.ttlDeadline).toBe(1_038); - expect(held.eventBus.replay()).toContainEqual( + // Renew just before the grant-time deadline would have fired. + harness.clock.advance(8); + const renewed = await harness.lifecycle.renew(grant.lease.id, 30); + expect(renewed).toMatchObject({ lastRenewedAt: 1_008, ttlMs: 30, ttlDeadline: 1_038 }); + expect(harness.eventBus.replay()).toContainEqual( expect.objectContaining({ event: "lease.renewed", payload: { leaseId: grant.lease.id, newDeadline: 1_038 }, }), ); - // The original deadline has now passed, but the timer was re-armed at the new - // deadline, so the lease must not have expired. - held.clock.advance(2); + // The grant-time deadline has now passed, but the timer was re-armed at the new one. + harness.clock.advance(12); await Promise.resolve(); - expect(held.registry.snapshot.leases).toHaveLength(1); + expect(harness.registry.snapshot.leases).toHaveLength(1); // The new deadline still fires. - held.clock.advance(28); - await vi.waitFor(() => expect(held.registry.snapshot.leases).toEqual([])); + harness.clock.advance(18); + await vi.waitFor(() => expect(harness.registry.snapshot.leases).toEqual([])); + }); + + it("renews with no ttlMs by re-applying the lease's own width, never lease.defaultTtlMs", async () => { + const harness = await createHarness(); + // Granted wider than the 20ms default, exactly the case ADR 0004 §4 exists for: a lease + // asked for a long TTL and must not shrink to the default the first time it is renewed. + const grant = await harness.lifecycle.grant({ + deviceId: harness.device.id, + requesterId: "agent", + ownerId: "agent", + ttlMs: 60, + }); + + harness.clock.advance(5); + const renewed = await harness.lifecycle.renew(grant.lease.id); + expect(renewed).toMatchObject({ ttlMs: 60, ttlDeadline: 1_065 }); }); - it("renews a held lease with no explicit ttlMs using the held backstop, not the detached TTL", async () => { + it("keeps re-applying a width a previous renew set, not the grant-time one", async () => { const harness = await createHarness(); const grant = await harness.lifecycle.grant({ deviceId: harness.device.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60, }); - expect(grant.lease.ttlDeadline).toBe(1_010); + harness.clock.advance(5); + await harness.lifecycle.renew(grant.lease.id, 40); harness.clock.advance(5); const renewed = await harness.lifecycle.renew(grant.lease.id); - // heldBackstopMs is 10 in this harness, detachedMs is 20 -- a deadline of 1_025 would - // mean the (wrong) detached default was used instead of the held backstop. - expect(renewed.ttlDeadline).toBe(1_015); + expect(renewed).toMatchObject({ ttlMs: 40, ttlDeadline: 1_050 }); }); it("emits release and expiry facts only after a registry release commit", async () => { const released = await createHarness(); const grant = await released.lifecycle.grant({ deviceId: released.device.id, - mode: "held", requesterId: "agent", ownerId: "agent", }); @@ -167,7 +161,6 @@ describe("LeaseLifecycle", () => { const expired = await createHarness(); await expired.lifecycle.grant({ deviceId: expired.device.id, - mode: "held", requesterId: "agent", ownerId: "agent", }); @@ -175,7 +168,7 @@ describe("LeaseLifecycle", () => { expired.eventBus.subscribe("lease.expired", () => { expiredLeaseCountAtEvent = expired.registry.snapshot.leases.length; }); - expired.clock.advance(10); + expired.clock.advance(20); await vi.waitFor(() => expect(expired.registry.snapshot.leases).toEqual([])); expect(expiredLeaseCountAtEvent).toBe(0); expect(expired.eventBus.replay()).toContainEqual( @@ -183,71 +176,19 @@ describe("LeaseLifecycle", () => { ); }); - it("slides a held lease's deadline on heartbeat, emits lease.renewed, and replaces its timer", async () => { - const harness = await createHarness(); - const grant = await harness.lifecycle.grant({ - deviceId: harness.device.id, - mode: "held", - requesterId: "agent", - ownerId: "agent", - }); - expect(grant.lease.ttlDeadline).toBe(1_010); - - harness.clock.advance(6); - const renewed = await harness.lifecycle.heartbeat(grant.lease.id); - expect(renewed.ttlDeadline).toBe(1_016); - expect(harness.registry.snapshot.leases).toEqual([ - expect.objectContaining({ id: grant.lease.id, ttlDeadline: 1_016 }), - ]); - expect(harness.eventBus.replay()).toContainEqual( - expect.objectContaining({ - event: "lease.renewed", - payload: { leaseId: grant.lease.id, newDeadline: 1_016 }, - }), - ); - - // The original (un-slid) deadline has now passed, but the timer was replaced, so the - // lease must not have expired. - harness.clock.advance(4); - await Promise.resolve(); - expect(harness.registry.snapshot.leases).toHaveLength(1); - - // The slid deadline, however, still fires. - harness.clock.advance(6); - await vi.waitFor(() => expect(harness.registry.snapshot.leases).toEqual([])); - }); - - it("refuses to heartbeat a detached lease, whose TTL is not the held backstop", async () => { - const harness = await createHarness(); - const grant = await harness.lifecycle.grant({ - deviceId: harness.device.id, - mode: "detached", - requesterId: "agent", - ownerId: "agent", - }); - - await expect(harness.lifecycle.heartbeat(grant.lease.id)).rejects.toBeInstanceOf( - DetachedLeaseHeartbeatError, - ); - expect(harness.registry.snapshot.leases).toEqual([ - expect.objectContaining({ id: grant.lease.id, ttlDeadline: grant.lease.ttlDeadline }), - ]); - }); - - it("restores the heartbeat-slid deadline (not the grant-time one) after a restart", async () => { + it("restores the renewed deadline (not the grant-time one) after a restart", async () => { const filesystem = new MemoryFilesystem(); const before = await createHarness({ filesystem }); const grant = await before.lifecycle.grant({ deviceId: before.device.id, - mode: "held", requesterId: "agent", ownerId: "agent", }); - expect(grant.lease.ttlDeadline).toBe(1_010); + expect(grant.lease.ttlDeadline).toBe(1_020); before.clock.advance(5); - const renewed = await before.lifecycle.heartbeat(grant.lease.id); - expect(renewed.ttlDeadline).toBe(1_015); + const renewed = await before.lifecycle.renew(grant.lease.id, 30); + expect(renewed.ttlDeadline).toBe(1_035); // Simulate a daemon restart: a fresh clock/event bus/scheduler/lifecycle reload the // same persisted registry state and restore timers from it. @@ -269,18 +210,18 @@ describe("LeaseLifecycle", () => { eventBus: afterEventBus, expiryScheduler: afterScheduler, registry: afterRegistry, - ttl: { detachedMs: 20, heldBackstopMs: 10 }, + ttl: { defaultMs: 20 }, }); await afterLifecycle.restoreExpiryTimers(); // Advance to (and past) the original grant-time deadline: a restart that restored the - // stale grant-time deadline instead of the slid one would have expired the lease here. - afterClock.advance(5); + // stale grant-time deadline instead of the renewed one would have expired the lease here. + afterClock.advance(20); await Promise.resolve(); expect(afterRegistry.snapshot.leases).toHaveLength(1); - // The slid deadline still fires. - afterClock.advance(5); + // The renewed deadline still fires. + afterClock.advance(15); await vi.waitFor(() => expect(afterRegistry.snapshot.leases).toEqual([])); }); }); diff --git a/src/core/lease-lifecycle.ts b/src/core/lease-lifecycle.ts index 9327e945b..b516f65b9 100644 --- a/src/core/lease-lifecycle.ts +++ b/src/core/lease-lifecycle.ts @@ -13,10 +13,10 @@ export interface LeaseLifecycleRegistry { readonly deviceId: string; readonly requesterId: string; readonly ownerId: string; - readonly mode: LeaseRecord["mode"]; + readonly ttlMs: number; readonly ttlDeadline: number; }): Promise; - renewLease(leaseId: string, ttlDeadline: number): Promise; + renewLease(leaseId: string, ttlDeadline: number, ttlMs: number): Promise; beginRelease(leaseId: string): Promise; } @@ -25,7 +25,12 @@ export interface LeaseLifecycleOptions { readonly eventBus: EventBus; readonly expiryScheduler: LeaseExpiryScheduler; readonly registry: LeaseLifecycleRegistry; - readonly ttl: { readonly detachedMs: number; readonly heldBackstopMs: number }; + /** + * ADR 0004 §4: `defaultMs` is `lease.defaultTtlMs`, and it applies in exactly one place -- a + * grant whose request named no `ttlMs`. A renew never falls back to it; it re-applies the + * lease's own stored width instead. + */ + readonly ttl: { readonly defaultMs: number }; } export interface LeaseLifecycleGrant { @@ -33,14 +38,6 @@ export interface LeaseLifecycleGrant { readonly lease: LeaseRecord; } -/** A heartbeat slides to the *held* backstop, so it must never be applied to a detached lease. */ -export class DetachedLeaseHeartbeatError extends Error { - constructor(readonly leaseId: string) { - super(`Detached lease cannot be heartbeated: ${leaseId}`); - this.name = "DetachedLeaseHeartbeatError"; - } -} - /** Registry-backed lease state changes, deliberately excluding reclaiming and queue wakeups. */ export class LeaseLifecycle { constructor(private readonly options: LeaseLifecycleOptions) {} @@ -48,16 +45,19 @@ export class LeaseLifecycle { // fallow-ignore-next-line unused-class-member -- reached through LeaseAcquisitionCoordinator's leases port. async grant(input: { readonly deviceId: string; - readonly mode: LeaseRecord["mode"]; readonly ownerId: string; readonly requesterId: string; - /** ADR 0003 §9: overrides the mode-aware default for a detached lease's initial TTL. */ + /** ADR 0004 §4: this lease's initial width; `lease.defaultTtlMs` when the request named + * none. Whatever it resolves to is stored on the record, because that is what a later + * body-less renew re-applies. */ readonly ttlMs?: number; }): Promise { const { ttlMs, ...createInput } = input; + const effectiveTtlMs = ttlMs ?? this.options.ttl.defaultMs; const lease = await this.options.registry.createLease({ ...createInput, - ttlDeadline: this.options.clock.now() + (ttlMs ?? this.#ttlFor(input.mode)), + ttlMs: effectiveTtlMs, + ttlDeadline: this.options.clock.now() + effectiveTtlMs, }); const device = this.options.registry.snapshot.devices.find( (candidate) => candidate.id === lease.deviceId, @@ -65,12 +65,14 @@ export class LeaseLifecycle { if (device === undefined) throw new Error(`Granted device disappeared from registry: ${lease.deviceId}`); + // ADR 0004's Consequences: `mode` leaves this payload, a deliberate one-off exception to + // events rule 6 (additive payloads only) taken while the package is 0.x -- there is no mode + // left to report. `EVENTS.md` records the exception. this.options.eventBus.emit( "lease.granted", { deviceId: lease.deviceId, leaseId: lease.id, - mode: lease.mode, requester: lease.requesterId, }, "lease-lifecycle", @@ -79,14 +81,23 @@ export class LeaseLifecycle { return { device, lease }; } + /** + * The one thing that keeps a lease alive (ADR 0004 §1). An omitted `ttlMs` re-applies the + * lease's own stored width, never `lease.defaultTtlMs`: a lease granted for four hours keeps + * its four hours through renewals that do not ask for anything different. A named `ttlMs` + * changes that width from this renewal on, which is why it is written back to the record. + * The fallback to `defaultMs` is unreachable for a live lease -- it only covers a lease the + * snapshot no longer has, whose `renewLease` below is about to throw `UnknownLeaseError`. + */ // fallow-ignore-next-line unused-class-member -- reached through LeaseReleaseCoordinator's lifecycle port. async renew(leaseId: string, ttlMs?: number): Promise { const current = this.options.registry.snapshot.leases.find((lease) => lease.id === leaseId); - const effectiveTtlMs = ttlMs ?? this.#ttlFor(current?.mode ?? "detached"); + const effectiveTtlMs = ttlMs ?? current?.ttlMs ?? this.options.ttl.defaultMs; const renewed = await this.options.registry.renewLease( leaseId, this.options.clock.now() + effectiveTtlMs, + effectiveTtlMs, ); this.options.eventBus.emit( "lease.renewed", @@ -98,38 +109,13 @@ export class LeaseLifecycle { } /** - * Slides a held lease's deadline back out to a full backstop from now, driven by an - * application-level heartbeat from its holder. Goes through the registry (not a direct - * `expiryScheduler.replace`) so the persisted `ttlDeadline` stays truthful for readers within - * this daemon's lifetime: `status` / `list --leases` derive `lastHeartbeatAt` from it - * (`DaemonServer#decorateLease`), and a stale in-memory-only slide would make that reading - * wrong immediately, not just after a restart. It does *not* mean the slid deadline survives - * a restart -- a held lease's liveness is its daemon connection, so `StartupConverger` - * releases every held lease as orphaned on startup regardless of how recently it was slid; - * see `startup-converger.ts`. + * ADR 0004's Consequences: `closed` and `orphaned` are gone from the reasons a lease can end + * with. Neither concept survives -- a closing connection is not a release (§3), and there is + * no startup sweep left to orphan anything. */ - // fallow-ignore-next-line unused-class-member -- called by LeaseReleaseCoordinator through the lifecycle port (same as the sibling renew). - async heartbeat(leaseId: string): Promise { - const current = this.options.registry.snapshot.leases.find((lease) => lease.id === leaseId); - if (current !== undefined && current.mode !== "held") - throw new DetachedLeaseHeartbeatError(leaseId); - - const renewed = await this.options.registry.renewLease( - leaseId, - this.options.clock.now() + this.options.ttl.heldBackstopMs, - ); - this.options.eventBus.emit( - "lease.renewed", - { leaseId: renewed.id, newDeadline: renewed.ttlDeadline }, - "lease-lifecycle", - ); - this.options.expiryScheduler.replace(renewed); - return renewed; - } - async beginRelease( leaseId: string, - reason: "closed" | "explicit" | "killed" | "orphaned" | "expired" | "device-lost", + reason: "explicit" | "killed" | "expired" | "device-lost", ): Promise { const released = await this.options.registry.beginRelease(leaseId); this.options.expiryScheduler.cancel(leaseId); @@ -158,11 +144,10 @@ export class LeaseLifecycle { return released; } + /** Re-arms every persisted lease's TTL timer from its own deadline (ADR 0004: startup + * restores all of them, and sweeps none -- nothing about a restart proves a holder is + * dead). */ restoreExpiryTimers(): Promise { return this.options.expiryScheduler.restore(this.options.registry.snapshot.leases); } - - #ttlFor(mode: LeaseRecord["mode"]): number { - return mode === "held" ? this.options.ttl.heldBackstopMs : this.options.ttl.detachedMs; - } } diff --git a/src/core/lease-ports.ts b/src/core/lease-ports.ts index 067c02d12..a1813e03b 100644 --- a/src/core/lease-ports.ts +++ b/src/core/lease-ports.ts @@ -4,17 +4,18 @@ import type { DeviceRequest, PassthroughCommand } from "./driver.js"; import type { PlatformCatalog } from "./driver-catalog.js"; import type { LeaseGrant, LeaseRequestOptions } from "./wait-queue.js"; -/** Client-requestable subset only -- deliberately excludes internally-originated reasons - * like `orphaned` (startup orphan cleanup), which no client can ask for. */ -export type LeaseReleaseReason = "closed" | "explicit" | "killed"; +/** Client-requestable subset only -- deliberately excludes the internally-originated + * `device-lost` (crash recovery giving up), which no client can ask for. Narrowed with + * `LeaseReleaseCoordinator`'s own union under ADR 0004 §3: `closed` is gone because a closing + * connection is not a release, and `orphaned` because there is no startup sweep left. */ +export type LeaseReleaseReason = "explicit" | "killed"; /** Lease commands used by daemon request handlers. */ export interface LeaseCommands { request(request: DeviceRequest, options: LeaseRequestOptions): Promise; release(leaseId: string, reason: LeaseReleaseReason): Promise; - releaseAll(reason: Exclude): Promise; + releaseAll(reason: LeaseReleaseReason): Promise; renew(leaseId: string, ttlMs?: number): Promise; - heartbeat(leaseId: string): Promise; } /** Pending-demand operations used by status and connection cleanup. */ diff --git a/src/core/lease-release-coordinator.test.ts b/src/core/lease-release-coordinator.test.ts index de2b03863..d652620d0 100644 --- a/src/core/lease-release-coordinator.test.ts +++ b/src/core/lease-release-coordinator.test.ts @@ -35,7 +35,7 @@ async function createHarness() { eventBus, expiryScheduler: scheduler, registry, - ttl: { detachedMs: 20, heldBackstopMs: 10 }, + ttl: { defaultMs: 20 }, }); const reclaims: ReleasedLease[] = []; const warmPool = { @@ -74,7 +74,7 @@ async function createHarness() { async function grant( harness: Awaited>, - mode: LeaseRecord["mode"] = "held", + ttlMs?: number, ): Promise<{ readonly device: DeviceRecord; readonly lease: LeaseRecord }> { const device = await harness.registry.registerDevice({ driverData: {}, @@ -88,9 +88,9 @@ async function grant( }); const result = await harness.lifecycle.grant({ deviceId: device.id, - mode, requesterId: `agent_${device.id}`, ownerId: `agent_${device.id}`, + ...(ttlMs === undefined ? {} : { ttlMs }), }); return result; } @@ -98,7 +98,6 @@ async function grant( describe("LeaseReleaseCoordinator", () => { it.each([ ["explicit", "lease.released"], - ["closed", "lease.released"], ["killed", "lease.released"], ["expired", "lease.expired"], ] as const)("commits %s release attribution before warm reclaim", async (reason, event) => { @@ -137,35 +136,30 @@ describe("LeaseReleaseCoordinator", () => { ); }); - it("delegates renewal to the lifecycle for both detached and held leases", async () => { + it("delegates renewal to the lifecycle, applying the TTL the caller named", async () => { const harness = await createHarness(); - const detached = await grant(harness, "detached"); - await expect(harness.coordinator.renew(detached.lease.id, 30)).resolves.toMatchObject({ - ttlDeadline: 1_030, - }); - - const heldHarness = await createHarness(); - const held = await grant(heldHarness, "held"); - await expect(heldHarness.coordinator.renew(held.lease.id, 30)).resolves.toMatchObject({ + const granted = await grant(harness); + await expect(harness.coordinator.renew(granted.lease.id, 30)).resolves.toMatchObject({ ttlDeadline: 1_030, + ttlMs: 30, }); }); - it("delegates heartbeat to the lifecycle and slides the held lease's deadline", async () => { + it("delegates a body-less renewal, which re-applies the lease's own stored width", async () => { const harness = await createHarness(); - const held = await grant(harness, "held"); - expect(held.lease.ttlDeadline).toBe(1_010); + const granted = await grant(harness, 50); harness.clock.advance(3); - await expect(harness.coordinator.heartbeat(held.lease.id)).resolves.toMatchObject({ - ttlDeadline: 1_013, + await expect(harness.coordinator.renew(granted.lease.id)).resolves.toMatchObject({ + ttlDeadline: 1_053, + ttlMs: 50, }); - expect(harness.registry.snapshot.leases).toMatchObject([{ ttlDeadline: 1_013 }]); + expect(harness.registry.snapshot.leases).toMatchObject([{ ttlDeadline: 1_053 }]); }); it("ignores an expiry delivery for a deadline replaced by renewal", async () => { const harness = await createHarness(); - const granted = await grant(harness, "detached"); + const granted = await grant(harness); const staleDeadline = granted.lease.ttlDeadline; await harness.coordinator.renew(granted.lease.id, 30); @@ -290,7 +284,7 @@ describe("LeaseReleaseCoordinator", () => { it("retries an expiry after maintenance reopens", async () => { const harness = await createHarness(); - const granted = await grant(harness, "detached"); + const granted = await grant(harness); await harness.coordinator.beginMaintenance(); const expiry = harness.coordinator.expire(granted.lease.id, granted.lease.ttlDeadline); @@ -313,7 +307,7 @@ describe("LeaseReleaseCoordinator", () => { }); describe("backgrounded reclaim", () => { - it.each(["explicit", "closed", "device-lost", "orphaned"] as const)( + it.each(["explicit", "device-lost", "killed"] as const)( "commits the registry-only %s release and resolves without waiting for the reclaim", async (reason) => { const harness = await createHarness(); @@ -328,10 +322,10 @@ describe("LeaseReleaseCoordinator", () => { }; // The registry-only half (device -> reclaiming, lease gone, `lease.released` - // emitted) is the whole of what the releasing caller needs -- an agent's MCP - // or CLI release, a closing connection, or startup's orphan sweep. The - // driver-side reclaim is still stuck on `blocked` and none of them may wait - // for it, or nothing was gained over the old inline-await shape. + // emitted) is the whole of what the releasing caller needs -- an agent's MCP or CLI + // release, an operator `release --all`, or a device recovery giving up. The + // driver-side reclaim is still stuck on `blocked` and none of them may wait for it, + // or nothing was gained over the old inline-await shape. if (reason === "device-lost") await harness.coordinator.releaseDeviceLost(granted.lease.id); else await harness.coordinator.release(granted.lease.id, reason); @@ -354,7 +348,7 @@ describe("LeaseReleaseCoordinator", () => { it("resolves an expiry without waiting for the reclaim either", async () => { const harness = await createHarness(); - const granted = await grant(harness, "detached"); + const granted = await grant(harness); let unblockReclaim!: () => void; const blocked = new Promise((resolve) => { unblockReclaim = resolve; diff --git a/src/core/lease-release-coordinator.ts b/src/core/lease-release-coordinator.ts index df710c902..1ef1eb71e 100644 --- a/src/core/lease-release-coordinator.ts +++ b/src/core/lease-release-coordinator.ts @@ -5,13 +5,12 @@ import type { ReleasedLease } from "./registry.js"; import type { SerializedDecision } from "./serialized-decision.js"; import type { WarmPoolCoordinator } from "./warm-pool-coordinator.js"; -export type LeaseReleaseReason = "closed" | "explicit" | "killed" | "orphaned" | "device-lost"; +export type LeaseReleaseReason = "explicit" | "killed" | "device-lost"; export interface LeaseReleaseCommands { release(leaseId: string, reason: LeaseReleaseReason): Promise; - releaseAll(reason: Exclude): Promise; + releaseAll(reason: Exclude): Promise; renew(leaseId: string, ttlMs?: number): Promise; - heartbeat(leaseId: string): Promise; } export interface LeaseExpirationAdmin { @@ -28,7 +27,6 @@ export interface LeaseReleaseMaintenance { export interface LeaseReleaseLifecycle { beginRelease(leaseId: string, reason: LeaseReleaseReason | "expired"): Promise; renew(leaseId: string, ttlMs?: number): Promise; - heartbeat(leaseId: string): Promise; } export interface LeaseReleaseRegistry { @@ -138,12 +136,6 @@ export class LeaseReleaseCoordinator ); } - async heartbeat(leaseId: string): Promise { - return this.#runNormal(() => - this.options.decisions.run(() => this.options.lifecycle.heartbeat(leaseId)), - ); - } - // fallow-ignore-next-line unused-class-member -- called through LeaseMaintenance by NukeService. async beginMaintenance(): Promise { await this.options.decisions.run(() => { @@ -203,9 +195,10 @@ export class LeaseReleaseCoordinator // information the caller can act on, so it proceeds in the background and the // caller gets its turn back immediately. That matters most for an agent // releasing through MCP or the CLI, which would otherwise sit on a tool call - // waiting for a device it has already given up, and for startup convergence - // (StartupConverger#releaseOrphanedHeldLeases), where N orphaned leases used - // to cost N serial erases on the critical path (#43). + // waiting for a device it has already given up, and for an operator's + // `release --all` or `nuke`, where N leases would otherwise cost N serial + // erases before the command answers (#43). Startup used to be the third such + // caller, through an orphan sweep ADR 0004 deleted. // // Kicked off here rather than queued, so every device's reclaim starts // immediately (not one-after-another): queuing would let a healthy reclaim sit diff --git a/src/core/managed-device-lifecycle.test.ts b/src/core/managed-device-lifecycle.test.ts index cff78384c..35e1eefad 100644 --- a/src/core/managed-device-lifecycle.test.ts +++ b/src/core/managed-device-lifecycle.test.ts @@ -134,9 +134,9 @@ describe("ManagedDeviceLifecycle", () => { const ready = await readyDevice(harness); await harness.registry.createLease({ deviceId: ready.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 2_000, }); expect(await harness.lifecycle.shutdown(ready, "test", "cleanup")).toBeUndefined(); @@ -210,9 +210,9 @@ describe("ManagedDeviceLifecycle", () => { const ready = await readyDevice(harness); const lease = await harness.registry.createLease({ deviceId: ready.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 10_000, }); await harness.driver.shutdown({ @@ -234,9 +234,9 @@ describe("ManagedDeviceLifecycle", () => { const ready = await readyDevice(harness); await harness.registry.createLease({ deviceId: ready.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 10_000, }); const makeReadyCallsBefore = harness.driver.calls.filter( @@ -277,9 +277,9 @@ describe("ManagedDeviceLifecycle", () => { const ready = await readyDevice(harness); const lease = await harness.registry.createLease({ deviceId: ready.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 10_000, }); harness.driver.hangMakeReady(); @@ -302,9 +302,9 @@ describe("ManagedDeviceLifecycle", () => { const ready = await readyDevice(harness); const lease = await harness.registry.createLease({ deviceId: ready.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 10_000, }); const claim = harness.claims.tryClaim(ready.id, "cleanup"); @@ -328,9 +328,9 @@ describe("ManagedDeviceLifecycle", () => { const ready = await readyDevice(harness); const lease = await harness.registry.createLease({ deviceId: ready.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 10_000, }); harness.driver.failOn("makeReady", 2, new DriverCrashError("boot failed")); @@ -352,9 +352,9 @@ describe("ManagedDeviceLifecycle", () => { const ready = await readyDevice(harness); const lease = await harness.registry.createLease({ deviceId: ready.id, - mode: "held", requesterId: "agent", ownerId: "agent", + ttlMs: 60_000, ttlDeadline: 10_000, }); diff --git a/src/core/nuke-service.test.ts b/src/core/nuke-service.test.ts index 0860acf8b..6435d99a1 100644 --- a/src/core/nuke-service.test.ts +++ b/src/core/nuke-service.test.ts @@ -139,9 +139,10 @@ describe("NukeService", () => { deviceId: leased.id, grantedAt: 0, id: "lse_live", - mode: "held", requesterId: "agent", ownerId: "agent", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 1, }, ]; diff --git a/src/core/nuke.test.ts b/src/core/nuke.test.ts index 67b0ef4d6..50360aa92 100644 --- a/src/core/nuke.test.ts +++ b/src/core/nuke.test.ts @@ -103,7 +103,7 @@ describe("Nuke", () => { }); const grant = await engine.request( { model: "Phone", osVersion: "1", platform: "ios" }, - { mode: "held", ownerId: "agent", requesterId: "agent" }, + { ownerId: "agent", requesterId: "agent" }, ); const release = engine.release(grant.lease.id, "explicit"); @@ -161,7 +161,7 @@ function config(): Config { http: { enabled: false, host: "127.0.0.1", port: 4700 }, ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, idle: { deleteAfterMs: 10, shutdownAfterMs: 5 }, - lease: { detachedTtlMs: 60_000, heldTtlBackstopMs: 60_000, heartbeatIntervalMs: 15_000 }, + lease: { defaultTtlMs: 60_000, maxTtlMs: 3_600_000 }, capacity: { strategy: "resource", config: { diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index be2f1fe91..a09748203 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -60,7 +60,7 @@ function config(): Config { http: { enabled: false, host: "127.0.0.1", port: 4700 }, ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, idle: { deleteAfterMs: 30_000, shutdownAfterMs: 10_000 }, - lease: { detachedTtlMs: 100, heldTtlBackstopMs: 100, heartbeatIntervalMs: 25 }, + lease: { defaultTtlMs: 100, maxTtlMs: 100 }, capacity: { strategy: "resource", config: { @@ -174,9 +174,9 @@ async function seedLeased(harness: Awaited>) { const device = await seedReady(harness); await harness.registry.createLease({ deviceId: device.id, - mode: "held", requesterId: "agent-1", ownerId: "agent-1", + ttlMs: 60_000, ttlDeadline: 2_000, }); return device; @@ -365,7 +365,6 @@ describe("CleanupReaper", () => { it("shuts down after T1 and destroys after T2 on periodic ticks following a release", async () => { const harness = await createHarness(automaticCleanupRules, {}, { tickMs: 10_000 }); const grant = await harness.engine.request(spec, { - mode: "held", ownerId: "agent-1", requesterId: "agent-1", }); @@ -404,7 +403,6 @@ describe("CleanupReaper", () => { const cleanup = harness.reaper.run(); await flush(); const request = harness.engine.request(spec, { - mode: "held", ownerId: "agent-2", requesterId: "agent-2", }); diff --git a/src/core/registry.test.ts b/src/core/registry.test.ts index a9daecd3c..02303e71c 100644 --- a/src/core/registry.test.ts +++ b/src/core/registry.test.ts @@ -244,9 +244,9 @@ describe("Registry", () => { const lease = await registry.createLease({ deviceId: device.id, - mode: "held", requesterId: "agent-1", ownerId: "agent-1", + ttlMs: 60_000, ttlDeadline: 2_000, }); const reloaded = await Registry.load(options); @@ -288,9 +288,9 @@ describe("Registry", () => { }); const lease = await registry.createLease({ deviceId: device.id, - mode: "detached", requesterId: "agent-1", ownerId: "agent-1", + ttlMs: 60_000, ttlDeadline: 2_000, }); await registry.beginRelease(lease.id); @@ -356,9 +356,9 @@ describe("Registry", () => { }); await registry.createLease({ deviceId: device.id, - mode: "detached", requesterId: "agent-1", ownerId: "agent-1", + ttlMs: 60_000, ttlDeadline: 2_000, }); @@ -387,9 +387,9 @@ describe("Registry", () => { }); const lease = await registry.createLease({ deviceId: device.id, - mode: "detached", requesterId: "agent-1", ownerId: "agent-1", + ttlMs: 60_000, ttlDeadline: 2_000, }); await registry.beginRelease(lease.id); @@ -428,9 +428,9 @@ describe("Registry", () => { }); const lease = await registry.createLease({ deviceId: device.id, - mode: "detached", requesterId: "agent-1", ownerId: "agent-1", + ttlMs: 60_000, ttlDeadline: 2_000, }); await registry.beginRelease(lease.id); @@ -476,9 +476,9 @@ describe("Registry", () => { }); const lease = await registry.createLease({ deviceId: device.id, - mode: "detached", requesterId: "agent-1", ownerId: "agent-1", + ttlMs: 60_000, ttlDeadline: 2_000, }); await registry.beginRelease(lease.id); @@ -755,9 +755,9 @@ describe("Registry", () => { }); const lease = await registry.createLease({ deviceId: device.id, - mode: "held", requesterId: "agent-1", ownerId: "agent-1", + ttlMs: 60_000, ttlDeadline: 2_000, }); await registry.markRecoveryAttempt(device.id, 1_200); @@ -791,8 +791,9 @@ describe("Registry", () => { id: "lse_1", deviceId: "dev_1", requesterId: "agent-1", - mode: "held", grantedAt: 1_000, + lastRenewedAt: 1_000, + ttlMs: 60_000, ttlDeadline: 2_000, // No `ownerId` -- exactly what a pre-ADR-0003 daemon wrote. }, @@ -814,8 +815,9 @@ describe("Registry", () => { deviceId: "dev_1", requesterId: "agent-1", ownerId: "agent-1", - mode: "held", grantedAt: 1_000, + lastRenewedAt: 1_000, + ttlMs: 60_000, ttlDeadline: 2_000, }, ]); @@ -824,7 +826,7 @@ describe("Registry", () => { // written file now carries `ownerId` explicitly (it is no longer an "unknown field" // preserved verbatim -- see `#unknownLeaseFields` -- but the registry's own understanding // of the record). - await registry.renewLease("lse_1", 3_000); + await registry.renewLease("lse_1", 3_000, 60_000); const reloaded = await Registry.load({ clock, eventBus: new EventBus(clock), @@ -836,6 +838,187 @@ describe("Registry", () => { expect(reloaded.snapshot.leases[0]?.ownerId).toBe("agent-1"); }); + it("migrates a lease record written before ADR 0004's ttlMs/lastRenewedAt, dropping mode", async () => { + const filesystem = new MemoryFilesystem(); + const clock = new FakeClock(5_000); + await filesystem.mkdirp("/home/agent/.simlock"); + // Exactly what a pre-ADR-0004 daemon persisted: a `mode`, and neither of the two fields a + // record carries now. Neither is recoverable from what is on disk -- `ttlDeadline - + // grantedAt` is the grant-time width only until the first renewal moved the deadline -- so + // each takes its documented default rather than a guess dressed up as arithmetic. + await filesystem.writeFileAtomic( + statePath, + JSON.stringify({ + devices: [ + { + createdAt: 0, + driverData: {}, + driverDeviceId: "driver_1", + id: "dev_1", + spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, + state: "leased", + }, + ], + leases: [ + { + deviceId: "dev_1", + grantedAt: 1_000, + id: "lse_1", + mode: "held", + ownerId: "agent-1", + requesterId: "agent-1", + ttlDeadline: 2_000, + }, + ], + }), + ); + + const registry = await Registry.load({ + clock, + defaultTtlMs: 900_000, + eventBus: new EventBus(clock), + filesystem, + idGenerator: { generate: () => "unexpected" }, + statePath, + }); + + expect(registry.snapshot.leases).toEqual([ + { + id: "lse_1", + deviceId: "dev_1", + requesterId: "agent-1", + ownerId: "agent-1", + grantedAt: 1_000, + // `lease.defaultTtlMs`, which the daemon passes in from its own config. + ttlMs: 900_000, + ttlDeadline: 2_000, + // A lease that has never been renewed reports the moment it was granted. + lastRenewedAt: 1_000, + }, + ]); + + // `mode` is a retired concept, not a field from a newer schema, so the next write drops it + // rather than preserving it through the unknown-field forward-compatibility path. + await registry.renewLease("lse_1", 9_000, 7_000); + const written = JSON.parse(await filesystem.readFile(statePath)) as { + leases: Record[]; + }; + expect(written.leases[0]).toEqual({ + deviceId: "dev_1", + grantedAt: 1_000, + id: "lse_1", + lastRenewedAt: 5_000, + ownerId: "agent-1", + requesterId: "agent-1", + ttlDeadline: 9_000, + ttlMs: 7_000, + }); + }); + + it.each([ + ["zero", 0], + ["negative", -1], + ["not a number", "soon"], + ["not finite", Number.POSITIVE_INFINITY], + ])("falls back to the default width for a %s ttlMs on disk", async (_label, stored) => { + // A stored width has to be a positive, finite duration: `0` or a negative one would make + // every renewal of this lease resolve to a deadline in the past, which the expiry + // scheduler reads as "expire immediately". An unusable value takes the same default an + // absent one does -- refusing the whole registry over one field would cost the operator + // every device Simlock knows about. + const filesystem = new MemoryFilesystem(); + const clock = new FakeClock(5_000); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic( + statePath, + JSON.stringify({ + devices: [ + { + createdAt: 0, + driverData: {}, + driverDeviceId: "driver_1", + id: "dev_1", + spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, + state: "leased", + }, + ], + leases: [ + { + deviceId: "dev_1", + grantedAt: 1_000, + id: "lse_1", + lastRenewedAt: 1_500, + ownerId: "agent-1", + requesterId: "agent-1", + ttlDeadline: 2_000, + ttlMs: stored, + }, + ], + }), + ); + + const registry = await Registry.load({ + clock, + defaultTtlMs: 900_000, + eventBus: new EventBus(clock), + filesystem, + idGenerator: { generate: () => "unexpected" }, + statePath, + }); + + expect(registry.snapshot.leases).toMatchObject([{ id: "lse_1", ttlMs: 900_000 }]); + // A `lastRenewedAt` that is usable is kept as it is -- only the unusable field migrates. + expect(registry.snapshot.leases[0]?.lastRenewedAt).toBe(1_500); + }); + + it("falls back to grantedAt for an unusable lastRenewedAt on disk", async () => { + const filesystem = new MemoryFilesystem(); + const clock = new FakeClock(5_000); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic( + statePath, + JSON.stringify({ + devices: [ + { + createdAt: 0, + driverData: {}, + driverDeviceId: "driver_1", + id: "dev_1", + spec: { model: "iPhone 16", osVersion: "26.5", platform: "ios" }, + state: "leased", + }, + ], + leases: [ + { + deviceId: "dev_1", + grantedAt: 1_000, + id: "lse_1", + lastRenewedAt: null, + ownerId: "agent-1", + requesterId: "agent-1", + ttlDeadline: 2_000, + ttlMs: 60_000, + }, + ], + }), + ); + + const registry = await Registry.load({ + clock, + defaultTtlMs: 900_000, + eventBus: new EventBus(clock), + filesystem, + idGenerator: { generate: () => "unexpected" }, + statePath, + }); + + // Unlike a width, a timestamp of `0` is a legitimate answer, so only non-numbers and + // non-finite values migrate -- and the stored width is untouched. + expect(registry.snapshot.leases).toMatchObject([ + { id: "lse_1", lastRenewedAt: 1_000, ttlMs: 60_000 }, + ]); + }); + it("rejects a lease record whose ownerId is present but not a string", async () => { const clock = new FakeClock(1_000); const filesystem = new MemoryFilesystem(); @@ -850,8 +1033,9 @@ describe("Registry", () => { deviceId: "dev_1", requesterId: "agent-1", ownerId: 42, - mode: "held", grantedAt: 1_000, + lastRenewedAt: 1_000, + ttlMs: 60_000, ttlDeadline: 2_000, }, ], diff --git a/src/core/registry.ts b/src/core/registry.ts index cdada04f4..0988a6b2a 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -1,5 +1,6 @@ import type { EventBus, EventMap } from "../bus/index.js"; import type { Clock, Filesystem, IdGenerator } from "../ports/index.js"; +import { DEFAULT_LEASE_TTL_MS } from "./config.js"; import { type DeviceRecord, type DeviceSpec, @@ -18,6 +19,13 @@ export interface RegistryOptions { readonly idGenerator: IdGenerator; readonly eventBus: EventBus; readonly statePath?: string; + /** + * The width a lease record written before ADR 0004 loads with, since it has none of its own + * (`lease.defaultTtlMs`; the daemon passes the configured value, and `DEFAULT_LEASE_TTL_MS` + * stands in for a caller that has no config to hand). Only ever read during that migration -- + * a granted lease's width always comes from the grant itself. + */ + readonly defaultTtlMs?: number; } export interface RegistrySnapshot { @@ -41,7 +49,8 @@ export interface CreateLeaseInput { readonly deviceId: string; readonly requesterId: string; readonly ownerId: string; - readonly mode: LeaseRecord["mode"]; + /** The width this lease is granted with; stored on the record, see `LeaseRecord.ttlMs`. */ + readonly ttlMs: number; readonly ttlDeadline: number; } @@ -91,6 +100,7 @@ export class Registry { static async load(options: RegistryOptions): Promise { const registry = new Registry({ ...options, + defaultTtlMs: options.defaultTtlMs ?? DEFAULT_LEASE_TTL_MS, statePath: options.statePath ?? DEFAULT_REGISTRY_PATH, }); @@ -394,9 +404,9 @@ export class Registry { async createLease({ deviceId, - mode, ownerId, requesterId, + ttlMs, ttlDeadline, }: CreateLeaseInput): Promise { const index = this.#devices.findIndex((device) => device.id === deviceId); @@ -413,13 +423,17 @@ export class Registry { } const leasedDevice = transition(device, "leased"); + const grantedAt = this.options.clock.now(); const lease: LeaseRecord = { deviceId, - grantedAt: this.options.clock.now(), + grantedAt, id: `lse_${this.options.idGenerator.generate()}`, - mode, + // ADR 0004: set at grant, then again on every renew -- a lease that has never been + // renewed reports the moment it was granted rather than nothing at all. + lastRenewedAt: grantedAt, ownerId, requesterId, + ttlMs, ttlDeadline, }; const devices = [...this.#devices]; @@ -458,15 +472,20 @@ export class Registry { return { device: cloneDevice(reclaiming), lease: cloneLease(lease) }; } + /** + * Commits a renewal: the new deadline, the width it was applied at (which becomes what the + * *next* body-less renew re-applies), and `lastRenewedAt`. All three are persisted together, + * so a daemon restart mid-lease restores the renewed deadline rather than the grant-time one. + */ // fallow-ignore-next-line unused-class-member -- called through LeaseLifecycle's registry port. - async renewLease(leaseId: string, ttlDeadline: number): Promise { + async renewLease(leaseId: string, ttlDeadline: number, ttlMs: number): Promise { const index = this.#leases.findIndex((lease) => lease.id === leaseId); const lease = this.#leases[index]; if (index === -1 || lease === undefined) { throw new UnknownLeaseError(leaseId); } - const renewed = { ...lease, ttlDeadline }; + const renewed = { ...lease, lastRenewedAt: this.options.clock.now(), ttlDeadline, ttlMs }; const leases = [...this.#leases]; leases[index] = renewed; await this.#commit(this.#devices, leases); @@ -524,8 +543,11 @@ export class Registry { return record; }); this.#leases = parsed.leases.map((lease) => { - const record = parseLease(lease); - this.#unknownLeaseFields.set(record.id, unknownFields(lease, leaseRecordKeys)); + const record = parseLease(lease, this.options.defaultTtlMs); + this.#unknownLeaseFields.set( + record.id, + unknownFields(lease, [...leaseRecordKeys, ...retiredLeaseRecordKeys]), + ); return record; }); } @@ -570,10 +592,18 @@ const leaseRecordKeys = [ "deviceId", "requesterId", "ownerId", - "mode", "grantedAt", + "ttlMs", "ttlDeadline", + "lastRenewedAt", ] as const; +/** + * Fields a lease record written before ADR 0004 carries that this daemon neither reads nor + * keeps. Listed here so they are stripped on load rather than preserved through the + * unknown-field forward-compatibility path -- `mode` is not a field from a *newer* schema this + * daemon should hand back untouched, it is a concept that no longer exists. + */ +const retiredLeaseRecordKeys = ["mode"] as const; function cloneDevice(device: DeviceRecord): DeviceRecord { return { ...device, spec: { ...device.spec } }; @@ -695,12 +725,14 @@ function isValidOwnerId(value: unknown): value is string | undefined { /** The required-string and timing fields every lease record has always had -- split out of * `parseLease` so that function's own branch count reflects only what changes per schema - * version (today: the `ownerId` migration), not the whole record shape at once. */ + * version (the `ownerId` migration, and ADR 0004's `ttlMs`/`lastRenewedAt` one), not the whole + * record shape at once. `mode` is deliberately not checked any more: a record written before + * ADR 0004 still carries one, and it is simply dropped on load rather than being a reason to + * refuse the whole registry. */ function hasValidLeaseCore(value: Record): value is Record & { id: string; deviceId: string; requesterId: string; - mode: "held" | "detached"; grantedAt: number; ttlDeadline: number; } { @@ -708,26 +740,50 @@ function hasValidLeaseCore(value: Record): value is Record 0 ? value : fallback; +} + +function parseLease(value: unknown, defaultTtlMs: number): LeaseRecord { if (!isObject(value) || !hasValidLeaseCore(value) || !isValidOwnerId(value.ownerId)) { throw new RegistryLoadError("Invalid lease record in registry state"); } - const { deviceId, grantedAt, id, mode, ownerId, requesterId, ttlDeadline } = value; + const { deviceId, grantedAt, id, lastRenewedAt, ownerId, requesterId, ttlDeadline, ttlMs } = + value; return { deviceId, grantedAt, id, - mode, + lastRenewedAt: finiteTimestampOr(lastRenewedAt, grantedAt), ownerId: ownerId ?? requesterId, requesterId, ttlDeadline, + ttlMs: positiveDurationOr(ttlMs, defaultTtlMs), }; } diff --git a/src/core/startup-converger.test.ts b/src/core/startup-converger.test.ts index 3584b9e78..caf4c2f7c 100644 --- a/src/core/startup-converger.test.ts +++ b/src/core/startup-converger.test.ts @@ -55,7 +55,6 @@ function createHarness( const order: string[] = []; const claimed = new Set(); const cleanupCalls: string[] = []; - const releasedLeaseIds: string[] = []; let leaseIdsAtTimerRestore: string[] | undefined; const timers = { restoreExpiryTimers: vi.fn(async () => { @@ -79,17 +78,6 @@ function createHarness( return true; }), }; - const releases = { - releaseOrphaned: vi.fn(async (leaseId: string) => { - order.push(`release:${leaseId}`); - releasedLeaseIds.push(leaseId); - const leaseIndex = leases.findIndex((lease) => lease.id === leaseId); - const lease = leases[leaseIndex]; - if (lease === undefined) return; - leases.splice(leaseIndex, 1); - updateState(lease.deviceId, "ready"); - }), - }; const quarantineRestore = { restore: vi.fn(() => void order.push("quarantine-restore")) }; const converger = new StartupConverger({ capacity: { @@ -109,7 +97,6 @@ function createHarness( return { devices, leases }; }, }, - releases, timers, }); @@ -132,8 +119,6 @@ function createHarness( order, quarantineRestore, recovery, - releasedLeaseIds, - releases, timers, }; } @@ -193,18 +178,20 @@ describe("StartupConverger", () => { deviceId: first.id, grantedAt: 0, id: "lease-1", - mode: "detached" as const, requesterId: "a", ownerId: "a", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 10, }, { deviceId: second.id, grantedAt: 0, id: "lease-2", - mode: "detached" as const, requesterId: "b", ownerId: "b", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 10, }, ]; @@ -268,79 +255,71 @@ describe("StartupConverger", () => { expect(harness.timers.restoreExpiryTimers).toHaveBeenCalledTimes(2); }); - it("releases an orphaned held lease before timers are restored, freeing its device", async () => { - const held = device("held-device", "ios", "leased", 1); + it("restores the timer of every lease it finds, sweeping none (ADR 0004)", async () => { + // Pre-ADR-0004 this device's lease would have been released as orphaned before timers + // were restored, on the theory that a restart proves its holder is dead. It proves + // nothing of the sort: the lease is TTL-bound, its holder may reconnect and renew it, + // and if nobody does it expires on its own deadline through the restored timer. + const leasedDevice = device("leased-device", "ios", "leased", 1); const leases = [ { - deviceId: held.id, + deviceId: leasedDevice.id, grantedAt: 0, - id: "lease-held", - mode: "held" as const, + id: "lease-1", requesterId: "a", ownerId: "a", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 1000, }, ]; - const harness = createHarness([held], leases, { android: 1, global: 1, ios: 1 }); + const harness = createHarness([leasedDevice], leases, { android: 1, global: 1, ios: 1 }); await harness.converger.converge(); - expect(harness.releases.releaseOrphaned).toHaveBeenCalledTimes(1); - expect(harness.releases.releaseOrphaned).toHaveBeenCalledWith("lease-held"); - expect(harness.order.indexOf("release:lease-held")).toBeLessThan( - harness.order.indexOf("timers"), - ); - // The orphaned lease is gone from the registry by the time timers are restored, so its - // timer is never re-armed. - expect(harness.leaseIdsAtTimerRestore).toEqual([]); - expect(harness.devices.find((item) => item.id === held.id)?.state).toBe("ready"); + expect(harness.leaseIdsAtTimerRestore).toEqual(["lease-1"]); + expect(harness.leases).toHaveLength(1); + expect(harness.devices.find((item) => item.id === leasedDevice.id)?.state).toBe("leased"); + expect(harness.cleanupCalls).toEqual([]); }); - it("keeps a detached lease's timer restoration untouched", async () => { - const detachedDevice = device("detached-device", "ios", "leased", 1); + it("leaves a leased device leased even when the running limit is now zero", async () => { + // The device the lease holds is over the (lowered) limit, and stays exactly where it is: + // there is no sweep left that could free it, and the capacity pass never touches a + // leased device. It goes back to the pool when the lease expires or is released. + const leasedDevice = device("leased-device", "ios", "leased", 1); const leases = [ { - deviceId: detachedDevice.id, + deviceId: leasedDevice.id, grantedAt: 0, - id: "lease-detached", - mode: "detached" as const, + id: "lease-1", requesterId: "a", ownerId: "a", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 1000, }, ]; - const harness = createHarness([detachedDevice], leases, { android: 1, global: 1, ios: 1 }); + const harness = createHarness([leasedDevice], leases, { android: 1, global: 0, ios: 0 }); await harness.converger.converge(); - expect(harness.releases.releaseOrphaned).not.toHaveBeenCalled(); - expect(harness.leaseIdsAtTimerRestore).toEqual(["lease-detached"]); - expect(harness.devices.find((item) => item.id === detachedDevice.id)?.state).toBe("leased"); + expect(harness.cleanupCalls).toEqual([]); + expect(harness.devices.find((item) => item.id === leasedDevice.id)?.state).toBe("leased"); }); - it("frees the orphaned lease's device before running-capacity convergence, making it a shutdown candidate", async () => { - const held = device("held-device", "ios", "leased", 1); - const leases = [ - { - deviceId: held.id, - grantedAt: 0, - id: "lease-held", - mode: "held" as const, - requesterId: "a", - ownerId: "a", - ttlDeadline: 1000, - }, - ]; - // maxRunning for ios is 0, so once the device is freed to "ready" it is over capacity - // and must be visible to the excess-capacity sweep that follows. - const harness = createHarness([held], leases, { android: 1, global: 0, ios: 0 }); + it("restores timers before quarantine and interrupted-reclaim recovery", async () => { + const reclaiming = device("reclaiming", "ios", "reclaiming", 1); + const harness = createHarness([reclaiming], [], { android: 1, global: 3, ios: 3 }); await harness.converger.converge(); - const releaseIndex = harness.order.indexOf("release:lease-held"); - const cleanupIndex = harness.order.indexOf("cleanup:held-device"); - expect(releaseIndex).toBeGreaterThanOrEqual(0); - expect(cleanupIndex).toBeGreaterThan(releaseIndex); - expect(harness.cleanupCalls).toEqual(["held-device"]); + expect(harness.order.indexOf("timers")).toBe(0); + expect(harness.order.indexOf("quarantine-restore")).toBeGreaterThan( + harness.order.indexOf("timers"), + ); + expect(harness.order.indexOf("recover:reclaiming")).toBeGreaterThan( + harness.order.indexOf("quarantine-restore"), + ); }); }); diff --git a/src/core/startup-converger.ts b/src/core/startup-converger.ts index 419edea78..9010f5d09 100644 --- a/src/core/startup-converger.ts +++ b/src/core/startup-converger.ts @@ -11,7 +11,7 @@ export interface StartupRegistry { }; } -/** Restores persisted lease deadlines before any startup device work begins. */ +/** Restores every persisted lease's TTL timer before any startup device work begins. */ export interface LeaseTimerRestorer { restoreExpiryTimers(): Promise; } @@ -26,16 +26,6 @@ export interface QuarantineRestorer { restore(): void; } -/** - * Releases a lease orphaned by a daemon restart. A held lease's liveness is - * its daemon connection, so any held lease found at startup has no holder by - * definition; this port drives it through the normal release path (reason - * `orphaned`) so the device is reclaimed and `lease.released` is emitted. - */ -export interface OrphanedLeaseRelease { - releaseOrphaned(leaseId: string): Promise; -} - /** Read-only operation claim view used to avoid an in-flight device operation. */ export interface DeviceClaimReader { isClaimed(deviceId: string): boolean; @@ -55,7 +45,6 @@ export interface StartupConvergerOptions { readonly interruptedReclaimRecovery: InterruptedReclaimRecovery; readonly quarantineRestore: QuarantineRestorer; readonly registry: StartupRegistry; - readonly releases: OrphanedLeaseRelease; readonly timers: LeaseTimerRestorer; } @@ -83,7 +72,10 @@ export class StartupConverger { constructor(private readonly options: StartupConvergerOptions) {} async converge(): Promise { - await this.#releaseOrphanedHeldLeases(); + // ADR 0004: every lease's timer is restored from its own persisted deadline, and nothing + // is swept -- a restart does not prove a holder is dead, so no lease is released on the + // strength of one. A lease whose deadline already passed while no daemon was running + // expires here, through the ordinary expiry path `restore` drives. await this.options.timers.restoreExpiryTimers(); // Independent of lease/reclaim recovery above: a `quarantined` device already // finished its release-time reclaim, so re-arming its retry timer never races @@ -106,25 +98,6 @@ export class StartupConverger { } } - /** - * A held lease's liveness is its daemon connection, so any lease still in - * `held` mode at startup is orphaned by definition — it cannot have a live - * holder across a restart. Release it (reason `orphaned`) before timers are - * restored, so its timer is never re-armed, and before capacity - * convergence, so the freed device is visible to it. Detached leases are - * untouched here; their liveness is the TTL, not a connection. - */ - async #releaseOrphanedHeldLeases(): Promise { - const orphanedLeaseIds = await this.options.decisions.run(() => - this.options.registry.snapshot.leases - .filter((lease) => lease.mode === "held") - .map((lease) => lease.id), - ); - for (const leaseId of orphanedLeaseIds) { - await this.options.releases.releaseOrphaned(leaseId); - } - } - async #recoverInterruptedReclaims(): Promise { const interrupted = await this.options.decisions.run(() => { const snapshot = this.options.registry.snapshot; diff --git a/src/core/wait-queue.test.ts b/src/core/wait-queue.test.ts index a98560b96..4ba4c52eb 100644 --- a/src/core/wait-queue.test.ts +++ b/src/core/wait-queue.test.ts @@ -41,7 +41,6 @@ function grant(): LeaseGrant { function createWaiter(queue: WaitQueue, requesterId: string, options: { timeoutMs?: number } = {}) { return queue.create(request satisfies DeviceRequest, { - mode: "held", ownerId: requesterId, requesterId, ...options, @@ -128,7 +127,6 @@ describe("WaitQueue", () => { const reattached: LeaseProgress[] = []; const { queue } = createQueue(); const waiter = queue.create(request, { - mode: "held", onProgress: (progress) => received.push(progress), requesterId: "agent", ownerId: "agent", diff --git a/src/core/wait-queue.ts b/src/core/wait-queue.ts index 5c0bc7a8b..19c8e783e 100644 --- a/src/core/wait-queue.ts +++ b/src/core/wait-queue.ts @@ -9,14 +9,13 @@ export interface LeaseRequestOptions { * something else per request. Required: every caller of `LeaseCommands.request` (the daemon * dispatcher) always knows its own session's principal. */ readonly ownerId: string; - readonly mode: "held" | "detached"; readonly timeoutMs?: number; readonly noWait?: boolean; readonly allowDownload?: boolean; readonly onProgress?: (progress: LeaseProgress) => void; - /** ADR 0003 §9: initial TTL for a *detached* lease. The contract rejects this for a `held` - * lease as `BAD_REQUEST` before it ever reaches here (held TTL is the backstop, not the - * caller's to shorten) -- this type does not re-enforce that, it trusts the caller. */ + /** ADR 0004 §4: this lease's initial TTL, accepted on every request. Omitted means + * `lease.defaultTtlMs`; the cap against `lease.maxTtlMs` is applied at the daemon boundary + * before a request ever reaches here, so this type trusts what it is given. */ readonly ttlMs?: number; } diff --git a/src/core/warm-pool-coordinator.test.ts b/src/core/warm-pool-coordinator.test.ts index 4a02a62e3..0e820a836 100644 --- a/src/core/warm-pool-coordinator.test.ts +++ b/src/core/warm-pool-coordinator.test.ts @@ -39,7 +39,7 @@ const config: Config = { retryBackoffMultiplier: 2, }, }, - lease: { detachedTtlMs: 100, heldTtlBackstopMs: 100, heartbeatIntervalMs: 25 }, + lease: { defaultTtlMs: 100, maxTtlMs: 100 }, capacity: { strategy: "resource", config: { @@ -180,9 +180,10 @@ function released(device: DeviceRecord): ReleasedLease { deviceId: device.id, grantedAt: 1, id: "lease-1", - mode: "held", requesterId: "agent", ownerId: "agent", + lastRenewedAt: 1, + ttlMs: 60_000, ttlDeadline: 100, }, }; diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index ffd084841..a9c67c504 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,8 +9,10 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - // ADR 0003 §6: protocol 3, no compatibility shim. - expect(DAEMON_PROTOCOL_VERSION).toBe(3); + // ADR 0004: protocol 4, no compatibility shim -- `lease.heartbeat` and `mode` left the + // wire with nothing behind them, so under ADR 0003 §6's honesty rule the range does not + // widen to keep speaking 3. + expect(DAEMON_PROTOCOL_VERSION).toBe(4); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index b3153ab24..e00896dc0 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -49,6 +49,8 @@ async function buildDispatcher( /** Gives the fake driver a `simlock ` wrapper so `driver.passthrough` has something * to route to; off by default so no other test's catalog output changes shape. */ readonly passthroughTool?: string; + /** Narrows the lease TTL knobs (ADR 0004), for the cap and default-width rules. */ + readonly lease?: Partial; } = {}, ) { const clock = new FakeClock(1_000); @@ -76,7 +78,7 @@ async function buildDispatcher( passthroughTool: overrides.passthroughTool, }), }); - const config = testConfig(overrides.downloadsPolicy); + const config = testConfig(overrides.downloadsPolicy, overrides.lease ?? {}); const engine = new LeaseEngine({ clock, config, @@ -137,8 +139,6 @@ async function buildDispatcher( function session(overrides: Partial = {}): DispatchSession { return { - heartbeatCapability: false, - heldLeaseIds: new Set(), manageEventSubscription: () => undefined, principal: "tok_agent", role: "agent", @@ -154,17 +154,38 @@ describe("Dispatcher: parsing", () => { ).rejects.toMatchObject({ code: "BAD_REQUEST" }); }); - it("rejects ttlMs on a held lease.request with BAD_REQUEST (contract-level rule)", async () => { - const { dispatcher } = await buildDispatcher(); + it("rejects a ttlMs above lease.maxTtlMs on a request, rather than clamping it", async () => { + // ADR 0004 §4: the cap is enforced here rather than in the contract schema, because + // `lease.maxTtlMs` is a daemon config value the contract module cannot see -- and every + // transport reaches leases through this one dispatcher, so HTTP inherits the same answer. + const { dispatcher } = await buildDispatcher({ lease: { maxTtlMs: 1_000 } }); await expect( dispatcher.dispatch( "lease.request", - { model: "iPhone 17 Pro", platform: "ios", ttlMs: 1_000 }, + { model: "iPhone 17 Pro", platform: "ios", ttlMs: 1_001 }, session(), ), ).rejects.toMatchObject({ code: "BAD_REQUEST" }); }); + it("rejects a ttlMs above lease.maxTtlMs on a renew too", async () => { + const { dispatcher } = await buildDispatcher({ lease: { maxTtlMs: 1_000 } }); + await expect( + dispatcher.dispatch("lease.renew", { leaseId: "lse_1", ttlMs: 1_001 }, session()), + ).rejects.toMatchObject({ code: "BAD_REQUEST" }); + }); + + it("accepts a ttlMs at the cap on a request (ADR 0004 §4)", async () => { + const { dispatcher } = await buildDispatcher({ lease: { maxTtlMs: 1_000 } }); + await expect( + dispatcher.dispatch( + "lease.request", + { model: "iPhone 17 Pro", platform: "ios", ttlMs: 1_000 }, + session(), + ), + ).resolves.toMatchObject({ lease: { ttlMs: 1_000 } }); + }); + it("rejects an operation this dispatcher has no handler for with UNKNOWN_REQUEST", async () => { const { dispatcher } = await buildDispatcher(); // "daemon.stop" is ADR §6's frozen exception -- `DaemonServer#dispatchLine` intercepts it @@ -291,7 +312,7 @@ describe("Dispatcher: ownership", () => { async function grantLease(dispatcher: Awaited>["dispatcher"]) { const grant = await dispatcher.dispatch( "lease.request", - { model: "iPhone 17 Pro", mode: "detached", osVersion: "26.5", platform: "ios" }, + { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, session({ principal: "tok_owner" }), ); return (grant as { lease: { id: string } }).lease.id; @@ -396,7 +417,6 @@ describe("Dispatcher: ownership", () => { "lease.request", { model: "iPhone 17 Pro", - mode: "detached", requesterId: "tok_owner1", osVersion: "26.5", platform: "ios", @@ -407,7 +427,6 @@ describe("Dispatcher: ownership", () => { "lease.request", { model: "iPhone 17 Pro", - mode: "detached", requesterId: "tok_owner2", osVersion: "26.5", platform: "ios", @@ -421,7 +440,6 @@ describe("Dispatcher: ownership", () => { "lease.request", { model: "iPhone 17 Pro", - mode: "held", requesterId: "agent-7", osVersion: "26.5", platform: "ios", @@ -467,7 +485,7 @@ describe("Dispatcher: lease.release-all", () => { const { dispatcher, registry } = await buildDispatcher(); await dispatcher.dispatch( "lease.request", - { mode: "detached", model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, session({ principal: "tok_owner" }), ); @@ -479,16 +497,16 @@ describe("Dispatcher: lease.release-all", () => { expect(registry.snapshot.leases).toHaveLength(1); }); - it("admin releases every held lease, regardless of owner, and reports every released id", async () => { - const { dispatcher, registry } = await buildDispatcher(); + it("admin releases every lease, regardless of owner, and reports every released id", async () => { + const { dispatcher, eventBus, registry } = await buildDispatcher(); const first = await dispatcher.dispatch( "lease.request", - { mode: "detached", model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, session({ principal: "tok_owner_1" }), ); const second = await dispatcher.dispatch( "lease.request", - { mode: "detached", model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, session({ principal: "tok_owner_2" }), ); expect(registry.snapshot.leases).toHaveLength(2); @@ -501,6 +519,14 @@ describe("Dispatcher: lease.release-all", () => { expect(new Set(result.leaseIds)).toEqual(new Set([first.lease.id, second.lease.id])); expect(registry.snapshot.leases).toHaveLength(0); + // `killed`, not `explicit`: nobody's holder asked for this (docs/EVENTS.md), and that is + // the distinction a `lease-lost` reader acts on. + expect( + eventBus + .replay() + .filter((event) => event.event === "lease.released") + .map((event) => (event.payload as { reason: string }).reason), + ).toEqual(["killed", "killed"]); }); }); @@ -509,7 +535,7 @@ describe("Dispatcher: nuke.run", () => { const { dispatcher, registry } = await buildDispatcher({ includeNuke: true }); await dispatcher.dispatch( "lease.request", - { mode: "detached", model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, session({ principal: "tok_owner" }), ); @@ -523,7 +549,7 @@ describe("Dispatcher: nuke.run", () => { const { dispatcher, registry } = await buildDispatcher({ includeNuke: true }); await dispatcher.dispatch( "lease.request", - { mode: "detached", model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, + { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios" }, session({ principal: "tok_owner" }), ); expect(registry.snapshot.leases).toHaveLength(1); @@ -670,7 +696,10 @@ function sequence() { return { generate: () => `${next++}` }; } -function testConfig(downloadsPolicy: Config["downloads"]["policy"] = "on-request"): Config { +function testConfig( + downloadsPolicy: Config["downloads"]["policy"] = "on-request", + leaseOverrides: Partial = {}, +): Config { return { drivers: {}, diskPressure: { freeBytesThreshold: 10 * gibibyte }, @@ -688,7 +717,7 @@ function testConfig(downloadsPolicy: Config["downloads"]["policy"] = "on-request http: { enabled: false, host: "127.0.0.1", port: 4700 }, ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, - lease: { detachedTtlMs: 60_000, heldTtlBackstopMs: 60_000, heartbeatIntervalMs: 5_000 }, + lease: { defaultTtlMs: 60_000, maxTtlMs: 3_600_000, ...leaseOverrides }, capacity: { strategy: "resource", config: { diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 10e9ce433..1dfa1023e 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -8,13 +8,11 @@ import { type DeviceRequest, type Doctor, type LeaseProgress, - type LeaseRecord, type Nuke, type Registry, effectiveAllowDownload, RuntimeMissingError, transitionEnteredAt, - UnknownLeaseError, } from "../core/index.js"; import type { CapacityReader, @@ -41,12 +39,11 @@ import type { TokenStore } from "../http/token-store.js"; * * `principal`/`role` are the ADR §4/§5 identity: fixed for the connection's lifetime once * `hello` resolves them (see `session.ts`'s `SessionRoleResolver` seam -- PR 2's credential - * handshake replaces how `role` is computed, not this shape). `heldLeaseIds`/ - * `heartbeatCapability` are connection-scoped facts `DaemonServer` already owns (ADR §2: the - * dispatcher does not do "held-lease tracking" or "connection lifecycle", the transport does); - * they are threaded in read-only because `lease.heartbeat`'s ownership rule ("this connection's - * held leases") needs them. `onProgress` and `manageEventSubscription` are the two places a - * request-scoped or connection-scoped push actually reaches the wire -- `DaemonServer` supplies + * handshake replaces how `role` is computed, not this shape). ADR 0004 removes the two + * connection-scoped fields that used to sit beside them (`heldLeaseIds`, + * `heartbeatCapability`): the daemon keeps no per-connection lease state at all any more, and + * the one operation that read them is gone. `onProgress` and `manageEventSubscription` are the + * two places a request-scoped or connection-scoped push actually reaches the wire -- `DaemonServer` supplies * closures that write socket frames; an HTTP session (next PR) can leave `onProgress` unset and * fail loudly (or no-op) on `events.subscribe`, since HTTP has no open connection to push * through even in principle (ADR §8's "the HTTP notice buffer stays"). @@ -54,8 +51,6 @@ import type { TokenStore } from "../http/token-store.js"; export interface DispatchSession { readonly principal: string; readonly role: Role; - readonly heldLeaseIds: ReadonlySet; - readonly heartbeatCapability: boolean; /** Called for each progress update while this specific `lease.request` call is in flight. * Ignored by every other operation. */ readonly onProgress?: (progress: LeaseProgress) => void; @@ -185,7 +180,6 @@ export class Dispatcher { "lease.renew": this.#leaseRenew, "lease.release": this.#leaseRelease, "lease.list": this.#leaseList, - "lease.heartbeat": this.#leaseHeartbeat, "driver.passthrough": this.#driverPassthrough, "doctor.run": this.#doctorRun, "lease.release-all": this.#leaseReleaseAll, @@ -288,7 +282,7 @@ export class Dispatcher { capacity: { ...capacity, global: { ...running.global, warm: warmDevices.length } }, devices: snapshot.devices.map((device) => this.#decorateDevice(device)), health: this.options.health(), - leases: snapshot.leases.map((lease) => this.#decorateLease(lease)), + leases: [...snapshot.leases], queueDepth: this.options.queue.queueDepth, }; }; @@ -301,14 +295,13 @@ export class Dispatcher { ...(input.osVersion === undefined ? {} : { osVersion: input.osVersion }), ...(input.full ? { full: true } : {}), }; - const mode = input.mode ?? "held"; + this.#requireTtlWithinCap(input.ttlMs); const requesterId = input.requesterId ?? session.principal; const requestedAllowDownload = input.allowDownload ?? false; const downloadsPolicy = this.options.config.downloads.policy; try { return await this.options.leases.request(request, { allowDownload: effectiveAllowDownload(downloadsPolicy, requestedAllowDownload), - mode, noWait: input.noWait ?? false, // ADR §4: the lease's owner is always the session principal -- never client-supplied, // unlike `requesterId`. @@ -340,42 +333,58 @@ export class Dispatcher { return { result }; }; - #leaseRenew: Handler<"lease.renew"> = async (input) => - this.options.leases.renew(input.leaseId, input.ttlMs); + /** + * ADR 0004 §1: the one keep-alive, on every transport. An omitted `ttlMs` re-applies the + * lease's own stored width (`LeaseLifecycle#renew`), never `lease.defaultTtlMs`. + */ + #leaseRenew: Handler<"lease.renew"> = async (input) => { + this.#requireTtlWithinCap(input.ttlMs); + return this.options.leases.renew(input.leaseId, input.ttlMs); + }; + + /** + * ADR 0004 §4's cap, applied identically to a request and a renew. It lives here rather than + * in the contract schema because `lease.maxTtlMs` is a daemon config value, and the contract + * module cannot see one; it lives in the dispatcher rather than in each transport because + * every transport reaches leases through this one shared object (ADR 0003 §2), so HTTP gets + * the same `400 BAD_REQUEST` the socket gets from the same line of code. Rejecting rather + * than clamping is the point: a caller silently given less time than it asked for would go + * on believing it had the time it named. + */ + #requireTtlWithinCap(ttlMs: number | undefined): void { + const maxTtlMs = this.options.config.lease.maxTtlMs; + if (ttlMs !== undefined && ttlMs > maxTtlMs) { + throw new DispatchError( + "BAD_REQUEST", + `ttlMs ${String(ttlMs)} exceeds lease.maxTtlMs (${String(maxTtlMs)})`, + ); + } + } #leaseRelease: Handler<"lease.release"> = async (input) => { await this.options.leases.release(input.leaseId, "explicit"); return { leaseId: input.leaseId }; }; + /** + * `killed`, not `explicit`: `docs/EVENTS.md` splits the two by who ended the lease and + * whether its holder asked. An operator's `simlock release --all` (and `nuke`, which already + * reports `killed` through `NukeService`) takes leases away from holders that never asked -- + * which is exactly what a `lease-lost` reader needs to tell apart from the holder's own + * `lease.release` on its way out. + */ #leaseReleaseAll: Handler<"lease.release-all"> = async () => { - const leaseIds = await this.options.leases.releaseAll("explicit"); + const leaseIds = await this.options.leases.releaseAll("killed"); return { leaseIds: [...leaseIds] }; }; #leaseList: Handler<"lease.list"> = (_input, session) => { - const leases = this.options.registry.snapshot.leases - .filter((lease) => session.role === "admin" || lease.ownerId === session.principal) - .map((lease) => this.#decorateLease(lease)); + const leases = this.options.registry.snapshot.leases.filter( + (lease) => session.role === "admin" || lease.ownerId === session.principal, + ); return { leases }; }; - #leaseHeartbeat: Handler<"lease.heartbeat"> = async (_input, session) => { - if (!session.heartbeatCapability) { - throw new DispatchError("BAD_REQUEST", "Connection did not declare the heartbeat capability"); - } - const acked: Array<{ readonly leaseId: string; readonly ttlDeadline: number }> = []; - for (const leaseId of session.heldLeaseIds) { - try { - const renewed = await this.options.leases.heartbeat(leaseId); - acked.push({ leaseId: renewed.id, ttlDeadline: renewed.ttlDeadline }); - } catch (error: unknown) { - if (!(error instanceof UnknownLeaseError)) throw error; - } - } - return { leases: acked }; - }; - /** * Resolution only: the daemon builds the command and never runs it. Spawning it here would * attach a user's interactive `adb shell` to the daemon's stdio, and the CLI is the process @@ -408,7 +417,7 @@ export class Dispatcher { const snapshot = this.options.registry.snapshot; switch (input.kind) { case "leases": - return snapshot.leases.map((lease) => this.#decorateLease(lease)); + return [...snapshot.leases]; case "rules": return this.options.reaper.rules; case "devices": @@ -469,20 +478,6 @@ export class Dispatcher { return this.options.tokens; } - /** - * Adds a derived `lastHeartbeatAt` for held leases, without a new `LeaseRecord` field: since - * `heartbeat()` writes through the registry, `ttlDeadline - heldTtlBackstopMs` is exactly the - * moment of the most recent slide (or grant, if there hasn't been one yet). Moved verbatim - * from `DaemonServer`. - */ - #decorateLease(lease: LeaseRecord): LeaseRecord & { readonly lastHeartbeatAt?: number } { - if (lease.mode !== "held") return lease; - return { - ...lease, - lastHeartbeatAt: lease.ttlDeadline - this.options.config.lease.heldTtlBackstopMs, - }; - } - /** Moved verbatim from `DaemonServer`; see its former comment there. */ #decorateDevice(device: DeviceRecord): DeviceRecord & { readonly transitionAgeMs?: number } { const enteredAt = transitionEnteredAt(device); diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index 0604f4279..dfbe84ad2 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -201,7 +201,6 @@ describe("startDaemon startup readiness", () => { expect(starting.payload).toMatchObject({ health: "starting" }); const parkedLease = client.request("lease.request", { - mode: "detached", model: "iPhone 16", osVersion: "26.5", platform: "ios", diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 58f5313b4..67392f664 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -116,7 +116,17 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise void) | undefined; let rejectGatewayStarted: ((error: unknown) => void) | undefined; /** Whether `onSocketClaimed` ever fired, i.e. whether anything will ever settle @@ -268,9 +278,10 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise { await Promise.all([doctor.reconcile(), leaseEngine.convergeRunningCapacity()]); }, @@ -294,12 +305,13 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise { await gatewayStarted.catch(() => undefined); await stopHttpGateway?.(); diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 8c14263d8..3ddd551fd 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -71,8 +71,11 @@ afterEach(async () => { }); describe("DaemonServer", () => { - it("releases a held lease when its client connection closes", async () => { - const harness = await createHarness(); + it("keeps a lease when its client connection closes, and ends it at its own deadline", async () => { + // ADR 0004 §3: connection close means nothing to a lease. The daemon keeps no + // per-connection lease state and releases nothing on close, on any transport -- the TTL + // is the only thing that ends a lease nobody released. + const harness = await createHarness({ lease: { defaultTtlMs: 40 } }); const holder = await createClient(harness.socketPath); await holder.request("hello", { @@ -80,21 +83,28 @@ describe("DaemonServer", () => { protocolVersion: DAEMON_PROTOCOL_VERSION, }); const grant = await holder.request("lease.request", { - mode: "held", requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", platform: "ios", }); expect(grant.ok).toBe(true); + const leaseId = leaseIdOf(grant); expect(harness.registry.snapshot.leases).toHaveLength(1); await holder.close(); - await expect.poll(() => harness.registry.snapshot.leases).toHaveLength(0); - expect(harness.registry.snapshot.devices[0]?.state).toBe("ready"); const observer = await createClient(harness.socketPath); await hello(observer); + // Still granted, still leasing its device, with nothing renewing it. + await expect(observer.request("status.get", {})).resolves.toMatchObject({ + payload: { devices: [{ state: "leased" }], leases: [{ id: leaseId }] }, + }); + + // The deadline is what ends it. + harness.clock.advance(40); + await expect.poll(() => harness.registry.snapshot.leases).toHaveLength(0); + await expect.poll(() => harness.registry.snapshot.devices[0]?.state).toBe("ready"); await expect(observer.request("status.get", {})).resolves.toMatchObject({ payload: { capacity: { global: { warm: 1 }, ios: { warm: 1 } }, @@ -104,6 +114,26 @@ describe("DaemonServer", () => { await observer.close(); }); + it("releases on an explicit lease.release, which is what a holder does on its way out", async () => { + const harness = await createHarness(); + const holder = await createClient(harness.socketPath); + await hello(holder); + const grant = await holder.request("lease.request", { + requesterId: "agent-1", + model: "iPhone 16", + osVersion: "26.5", + platform: "ios", + }); + + await expect( + holder.request("lease.release", { leaseId: leaseIdOf(grant) }), + ).resolves.toMatchObject({ ok: true }); + + await expect.poll(() => harness.registry.snapshot.leases).toHaveLength(0); + await expect.poll(() => harness.registry.snapshot.devices[0]?.state).toBe("ready"); + await holder.close(); + }); + it("requires a compatible hello before serving requests", async () => { const harness = await createHarness(); const missingHello = await createClient(harness.socketPath); @@ -138,12 +168,12 @@ describe("DaemonServer", () => { }); }); - // Protocol 2 added the `heartbeat` capability and the sliding held-lease TTL that - // depends on it, and shipped without back-compat shims. Rejecting v1 is therefore a - // deliberate product decision, not just arithmetic on the current constant. Protocol 3 - // (ADR 0003) widened the rejection to a range check, but a v1 client (no overlap with - // `PROTOCOL_VERSION_RANGE`) is still rejected outright, now as `PROTOCOL_VERSION_UNSUPPORTED`. - it("rejects a protocol v1 client outright rather than serving it without heartbeats", async () => { + // Every protocol bump so far shipped without a back-compat shim, so rejecting an older + // client outright is a deliberate product decision, not just arithmetic on the current + // constant. Protocol 3 (ADR 0003) turned the rejection into a range check; protocol 4 + // (ADR 0004) removed `lease.heartbeat` and `mode` behind that same no-shim rule, so a v1 + // client has no overlap with `PROTOCOL_VERSION_RANGE` and is still rejected outright. + it("rejects a protocol v1 client outright rather than serving it a wire it cannot speak", async () => { const harness = await createHarness(); const legacy = await createClient(harness.socketPath); @@ -155,14 +185,20 @@ describe("DaemonServer", () => { }); }); - it("releases a holder and grants the queued client when the holder disconnects", async () => { - const harness = await createHarness(); + it("grants the queued client when the holder's lease expires, not when it disconnects", async () => { + // A log sink rather than a sleep: "the waiter stays queued" is a negative assertion, and + // the only honest way to make one is to wait for the daemon to have actually processed + // the close first. `Connection closed` is that receipt. + const sink = new MemoryLogSink(); + const harness = await createHarness({ + lease: { defaultTtlMs: 40 }, + logger: new JsonLinesLogger({ clock: new FakeClock(1_000), level: "debug", sink }), + }); const holder = await createClient(harness.socketPath); const waiter = await createClient(harness.socketPath); await hello(holder); await hello(waiter); await holder.request("lease.request", { - mode: "held", requesterId: "holder", model: "iPhone 16", osVersion: "26.5", @@ -170,7 +206,6 @@ describe("DaemonServer", () => { }); const queuedGrant = waiter.request("lease.request", { - mode: "held", requesterId: "waiter", model: "iPhone 16", osVersion: "26.5", @@ -180,10 +215,19 @@ describe("DaemonServer", () => { .poll(() => harness.eventBus.replay().some((event) => event.event === "lease.queued")) .toBe(true); + // The holder's socket dying frees nothing (ADR 0004 §3) -- the waiter stays queued. await holder.close(); + await expect + .poll(() => sink.records.some((record) => record.message === "Connection closed")) + .toBe(true); + expect(harness.registry.snapshot.leases.map((lease) => lease.requesterId)).toEqual(["holder"]); + // Its deadline does free it, and the queue is served from there. + harness.clock.advance(40); await expect(queuedGrant).resolves.toMatchObject({ ok: true }); - expect(harness.registry.snapshot.leases.map((lease) => lease.requesterId)).toEqual(["waiter"]); + await expect + .poll(() => harness.registry.snapshot.leases.map((lease) => lease.requesterId)) + .toEqual(["waiter"]); }); it("keeps lease progress on its requesting connection", async () => { @@ -191,8 +235,7 @@ describe("DaemonServer", () => { const holder = await createClient(harness.socketPath); const waiter = await createClient(harness.socketPath); await Promise.all([hello(holder), hello(waiter)]); - await holder.request("lease.request", { - mode: "held", + const holderGrant = await holder.request("lease.request", { requesterId: "holder", model: "iPhone 16", osVersion: "26.5", @@ -200,7 +243,6 @@ describe("DaemonServer", () => { }); const queuedGrant = waiter.request("lease.request", { - mode: "held", requesterId: "waiter", model: "iPhone 16", osVersion: "26.5", @@ -223,8 +265,10 @@ describe("DaemonServer", () => { ?.progress?.stage === "queued", ), ).toEqual([]); - await holder.close(); + // Closing the holder frees nothing (ADR 0004 §3); releasing does. + await holder.request("lease.release", { leaseId: leaseIdOf(holderGrant) }); await expect(queuedGrant).resolves.toMatchObject({ ok: true }); + await holder.close(); await waiter.close(); }); @@ -255,7 +299,6 @@ describe("DaemonServer", () => { let requestSettled = false; const grant = client .request("lease.request", { - mode: "detached", requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", @@ -345,7 +388,6 @@ describe("DaemonServer", () => { await expect(client.request("events.unsubscribe", {})).resolves.toMatchObject({ ok: true }); const grant = await client.request("lease.request", { - mode: "detached", requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", @@ -551,24 +593,26 @@ describe("DaemonServer", () => { await client.close(); }); - it("gracefully stops by releasing held leases and persisting the final registry", async () => { + it("gracefully stops without touching leases, persisting them with their deadlines", async () => { const harness = await createHarness(); const client = await createClient(harness.socketPath); await hello(client); - await client.request("lease.request", { - mode: "held", + const grant = await client.request("lease.request", { requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", platform: "ios", }); + const leaseId = leaseIdOf(grant); await expect(client.request("daemon.stop", {})).resolves.toMatchObject({ ok: true }); - await expect.poll(() => harness.registry.snapshot.leases).toEqual([]); - expect(harness.registry.snapshot.leases).toEqual([]); - await expect(harness.stateFilesystem.readFile("/state.json")).resolves.toContain('"leases":[]'); + // ADR 0004 §3: a stop ends connections, not leases -- they persist and the next daemon + // restores each one's timer from its deadline. + expect(harness.registry.snapshot.leases).toMatchObject([{ id: leaseId }]); + await expect(harness.stateFilesystem.readFile("/state.json")).resolves.toContain(leaseId); expect(harness.eventBus.replay().map((event) => event.event)).toContain("daemon.stopping"); + expect(harness.eventBus.replay().map((event) => event.event)).not.toContain("lease.released"); }); it("pushes a lease-lost notification to the holding connection when its lease's TTL backstop expires", async () => { @@ -576,7 +620,6 @@ describe("DaemonServer", () => { const holder = await createClient(harness.socketPath); await hello(holder); const grant = await holder.request("lease.request", { - mode: "held", requesterId: "holder", model: "iPhone 16", osVersion: "26.5", @@ -609,7 +652,6 @@ describe("DaemonServer", () => { const releaser = await createClient(harness.socketPath); await Promise.all([hello(holder), hello(releaser)]); const grant = await holder.request("lease.request", { - mode: "held", requesterId: "holder", model: "iPhone 16", osVersion: "26.5", @@ -641,7 +683,6 @@ describe("DaemonServer", () => { const holder = await createClient(harness.socketPath); await hello(holder); const grant = await holder.request("lease.request", { - mode: "held", requesterId: "holder", model: "iPhone 16", osVersion: "26.5", @@ -683,7 +724,6 @@ describe("DaemonServer", () => { const holder = await createClient(harness.socketPath); await hello(holder); const grant = await holder.request("lease.request", { - mode: "held", requesterId: "holder", model: "iPhone 16", osVersion: "26.5", @@ -706,11 +746,12 @@ describe("DaemonServer", () => { push: "device-unhealthy", }); - // The lease is still held after the notice: closing the connection still - // releases it, same as any other held lease, proving `heldLeaseIds` was never - // touched by the push (unlike `#notifyLeaseLost`). - await holder.close(); + // The lease is untouched by the notice: it is a fact about the device, not about the + // lease, and it is still there to be released the normal way. + expect(harness.registry.snapshot.leases).toMatchObject([{ id: leaseId }]); + await holder.request("lease.release", { leaseId }); await expect.poll(() => harness.registry.snapshot.leases).toEqual([]); + await holder.close(); }); it("pushes a device-recovered notification on device.recovered without releasing the lease", async () => { @@ -718,7 +759,6 @@ describe("DaemonServer", () => { const holder = await createClient(harness.socketPath); await hello(holder); const grant = await holder.request("lease.request", { - mode: "held", requesterId: "holder", model: "iPhone 16", osVersion: "26.5", @@ -741,8 +781,11 @@ describe("DaemonServer", () => { push: "device-recovered", }); - await holder.close(); + // The lease survived the crash and the recovery both, and ends the normal way. + expect(harness.registry.snapshot.leases).toMatchObject([{ id: leaseId }]); + await holder.request("lease.release", { leaseId }); await expect.poll(() => harness.registry.snapshot.leases).toEqual([]); + await holder.close(); }); it("ignores device-unhealthy/device-recovered facts for leases with no currently connected holder", async () => { @@ -769,7 +812,6 @@ describe("DaemonServer", () => { const holder = await createClient(harness.socketPath); await hello(holder); const grant = await holder.request("lease.request", { - mode: "held", requesterId: "holder", model: "iPhone 16", osVersion: "26.5", @@ -920,7 +962,6 @@ describe("DaemonServer startup readiness", () => { const holder = await createClientRetrying(harness.socketPath); await hello(holder); const parkedGrant = holder.request("lease.request", { - mode: "held", requesterId: "holder", model: "iPhone 16", osVersion: "26.5", @@ -1018,7 +1059,6 @@ describe("DaemonServer driver rejections", () => { await hello(client); const response = await client.request("lease.request", { - mode: "held", requesterId: "agent-1", model: "Pixel 8", platform: "android", @@ -1046,7 +1086,6 @@ describe("DaemonServer driver rejections", () => { await hello(client); const response = await client.request("lease.request", { - mode: "held", requesterId: "agent-1", model: "Pixel 8", platform: "android", @@ -1134,15 +1173,12 @@ describe("DaemonServer driver rejections", () => { }); }); -describe("DaemonServer lease heartbeat", () => { - it("slides a held lease's deadline past the backstop while its holder keeps ponging, and stops sliding once it stops", async () => { - const harness = await createHarness({ - lease: { heartbeatIntervalMs: 10, heldTtlBackstopMs: 40 }, - }); +describe("DaemonServer lease liveness (ADR 0004)", () => { + it("keeps a lease alive only while something renews it, and expires it when nothing does", async () => { + const harness = await createHarness({ lease: { defaultTtlMs: 40 } }); const holder = await createClient(harness.socketPath); - await hello(holder, { heartbeat: true }); + await hello(holder); const grant = await holder.request("lease.request", { - mode: "held", requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", @@ -1151,26 +1187,23 @@ describe("DaemonServer lease heartbeat", () => { const leaseId = leaseIdOf(grant); expect((grant.payload as { lease: { ttlDeadline: number } }).lease.ttlDeadline).toBe(1_040); - // Pong every tick, well past the original backstop (40ms from grant). + // Renew on the client's own cadence, well past the grant-time deadline. Each renew names + // no TTL, so each re-applies the lease's own 40ms width from now. let expectedDeadline = 1_040; for (let cycle = 0; cycle < 6; cycle += 1) { harness.clock.advance(10); - const push = await holder.nextFrame((frame) => frame.push === "lease.heartbeat"); - const nonce = (push.payload as { nonce: number }).nonce; - expectedDeadline += 10; - await expect(holder.request("lease.heartbeat", { nonce })).resolves.toMatchObject({ + expectedDeadline = harness.clock.now() + 40; + await expect(holder.request("lease.renew", { leaseId })).resolves.toMatchObject({ ok: true, - payload: { leases: [{ leaseId, ttlDeadline: expectedDeadline }] }, + payload: { id: leaseId, ttlDeadline: expectedDeadline, ttlMs: 40 }, }); } - // 60ms have passed since grant, exceeding the 40ms backstop, yet the lease is alive. + // 60ms have passed since the grant, well past the deadline it carried, and the lease is + // alive because something kept renewing it. expect(harness.registry.snapshot.leases).toMatchObject([{ id: leaseId }]); - // Now stop ponging: pure sliding window means no fail-fast, just the existing backstop - // eventually catching up from the last slid deadline. - harness.clock.advance(10); // one more push arrives, but is never answered - await holder.nextFrame((frame) => frame.push === "lease.heartbeat"); - harness.clock.advance(40); // the last slid deadline (expectedDeadline) elapses + // Stop renewing and the deadline catches up, with no separate backstop behind it. + harness.clock.advance(40); await expect.poll(() => harness.registry.snapshot.leases).toEqual([]); await expect(holder.nextFrame((frame) => frame.push === "lease-lost")).resolves.toMatchObject({ payload: { leaseId, reason: "expired" }, @@ -1179,14 +1212,11 @@ describe("DaemonServer lease heartbeat", () => { await holder.close(); }); - it("never pings a connection that did not declare the heartbeat capability, and it expires exactly as before", async () => { - const harness = await createHarness({ - lease: { heartbeatIntervalMs: 10, heldTtlBackstopMs: 40 }, - }); + it("never pushes anything to a connection to prove liveness", async () => { + const harness = await createHarness({ lease: { defaultTtlMs: 40 } }); const holder = await createClient(harness.socketPath); - await hello(holder); // no capabilities declared + await hello(holder); const grant = await holder.request("lease.request", { - mode: "held", requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", @@ -1204,25 +1234,58 @@ describe("DaemonServer lease heartbeat", () => { await holder.close(); }); - it("rejects a lease.heartbeat request from a connection that never declared the capability", async () => { + it("no longer answers lease.heartbeat at all", async () => { const harness = await createHarness(); const client = await createClient(harness.socketPath); await hello(client); await expect(client.request("lease.heartbeat", { nonce: 1 })).resolves.toMatchObject({ + error: { code: "UNKNOWN_REQUEST" }, + ok: false, + }); + await client.close(); + }); + + it("rejects a ttlMs above lease.maxTtlMs on a request and on a renew, rather than clamping", async () => { + const harness = await createHarness({ lease: { defaultTtlMs: 40, maxTtlMs: 100 } }); + const client = await createClient(harness.socketPath); + await hello(client); + + await expect( + client.request("lease.request", { + requesterId: "agent-1", + model: "iPhone 16", + osVersion: "26.5", + platform: "ios", + ttlMs: 101, + }), + ).resolves.toMatchObject({ error: { code: "BAD_REQUEST" }, ok: false }); + expect(harness.registry.snapshot.leases).toEqual([]); + + const grant = await client.request("lease.request", { + requesterId: "agent-1", + model: "iPhone 16", + osVersion: "26.5", + platform: "ios", + ttlMs: 100, + }); + const leaseId = leaseIdOf(grant); + expect((grant.payload as { lease: { ttlMs: number } }).lease.ttlMs).toBe(100); + + await expect(client.request("lease.renew", { leaseId, ttlMs: 101 })).resolves.toMatchObject({ error: { code: "BAD_REQUEST" }, ok: false, }); + expect(harness.registry.snapshot.leases).toMatchObject([{ ttlDeadline: 1_100 }]); await client.close(); }); - it("releases a held lease as orphaned across a daemon restart, even with a heartbeat-slid deadline", async () => { - const leaseOverrides = { heartbeatIntervalMs: 10, heldTtlBackstopMs: 40 }; + it("keeps a lease across a daemon restart and restores its timer from the persisted deadline", async () => { + const leaseOverrides = { defaultTtlMs: 40 }; const first = await createHarness({ lease: leaseOverrides }); const holder = await createClient(first.socketPath); - await hello(holder, { heartbeat: true }); + await hello(holder); const grant = await holder.request("lease.request", { - mode: "held", requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", @@ -1232,24 +1295,20 @@ describe("DaemonServer lease heartbeat", () => { const deviceId = (grant.payload as { device: { id: string } }).device.id; first.clock.advance(10); - const push = await holder.nextFrame((frame) => frame.push === "lease.heartbeat"); - const nonce = (push.payload as { nonce: number }).nonce; - await expect(holder.request("lease.heartbeat", { nonce })).resolves.toMatchObject({ + await expect(holder.request("lease.renew", { leaseId })).resolves.toMatchObject({ ok: true, - payload: { leases: [{ leaseId, ttlDeadline: 1_050 }] }, + payload: { ttlDeadline: 1_050 }, }); - // Simulate an abrupt daemon crash (not a graceful `daemon stop`, which would itself - // release the held connection's leases): the first daemon's process just disappears, - // leaving the last persisted registry state — the post-heartbeat slid deadline — - // on disk. It is intentionally left running here; the afterEach hook tears it down. + // Simulate an abrupt daemon crash: the first daemon's process just disappears, leaving + // the last persisted registry state -- the renewed deadline -- on disk. It is + // intentionally left running here; the afterEach hook tears it down. - // "Restart": a fresh daemon reloads that persisted registry state. A held lease's - // liveness is its daemon connection, so it cannot have survived the restart regardless - // of how recently its deadline was slid — the real startup path (src/daemon/main.ts) - // releases it as orphaned before any timer would otherwise be restored. - // The underlying device itself (unlike the daemon process) survives a restart, so the - // "restarted" harness is wired to the same fake driver instance as the crashed one. + // "Restart": a fresh daemon reloads that persisted state. ADR 0004 removed the orphan + // sweep that used to release this lease on the theory that a restart proves its holder + // is dead -- it proves nothing of the sort, so the lease stands and its timer is + // restored from the renewed deadline. The underlying device (unlike the daemon process) + // survives a restart, so the "restarted" harness shares the same fake driver instance. const second = await createHarness({ clock: new FakeClock(1_010), driver: first.driver, @@ -1258,43 +1317,102 @@ describe("DaemonServer lease heartbeat", () => { }); await second.engine.convergeRunningCapacity(); - expect(second.registry.snapshot.leases).toEqual([]); - // The freed device is reclaimed and available to the next requester, not left shutdown. - expect(second.registry.snapshot.devices).toMatchObject([{ id: deviceId, state: "ready" }]); + expect(second.registry.snapshot.leases).toMatchObject([{ id: leaseId, ttlDeadline: 1_050 }]); + expect(second.registry.snapshot.devices).toMatchObject([{ id: deviceId, state: "leased" }]); + + // The restored timer is the renewed one, not the grant-time one: nothing expires at + // 1_040, and the lease ends at 1_050 with no client left to renew it. + second.clock.advance(30); + await expect.poll(() => second.registry.snapshot.leases).toHaveLength(1); + second.clock.advance(10); + await expect.poll(() => second.registry.snapshot.leases).toEqual([]); + await expect.poll(() => second.registry.snapshot.devices[0]?.state).toBe("ready"); await holder.close(); }); - it("surfaces a derived lastHeartbeatAt for held leases in status and list --leases", async () => { - const harness = await createHarness({ - lease: { heartbeatIntervalMs: 10, heldTtlBackstopMs: 40 }, + it("expires a lease whose deadline passed while no daemon was running, as soon as one is", async () => { + const leaseOverrides = { defaultTtlMs: 40 }; + const first = await createHarness({ lease: leaseOverrides }); + const holder = await createClient(first.socketPath); + await hello(holder); + const grant = await holder.request("lease.request", { + requesterId: "agent-1", + model: "iPhone 16", + osVersion: "26.5", + platform: "ios", + }); + const deviceId = (grant.payload as { device: { id: string } }).device.id; + await holder.close(); + + // The next daemon starts well after the persisted deadline (1_040). + const second = await createHarness({ + clock: new FakeClock(2_000), + driver: first.driver, + lease: leaseOverrides, + stateFilesystem: first.stateFilesystem, }); + await second.engine.convergeRunningCapacity(); + + await expect.poll(() => second.registry.snapshot.leases).toEqual([]); + await expect + .poll(() => second.registry.snapshot.devices) + .toMatchObject([{ id: deviceId, state: "ready" }]); + }); + + it("surfaces the stored lastRenewedAt and ttlMs in status and list --leases", async () => { + const harness = await createHarness({ lease: { defaultTtlMs: 40 } }); const holder = await createClient(harness.socketPath); - await hello(holder, { heartbeat: true }); + await hello(holder); const grant = await holder.request("lease.request", { - mode: "held", requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", platform: "ios", }); const leaseId = leaseIdOf(grant); + // Written at grant, before any renew -- it is a stored field, not a derived one, so + // there is always an answer. + expect((grant.payload as { lease: { lastRenewedAt: number } }).lease.lastRenewedAt).toBe(1_000); harness.clock.advance(10); - const push = await holder.nextFrame((frame) => frame.push === "lease.heartbeat"); - const nonce = (push.payload as { nonce: number }).nonce; - await holder.request("lease.heartbeat", { nonce }); + await holder.request("lease.renew", { leaseId }); await expect(holder.request("status.get", {})).resolves.toMatchObject({ ok: true, - payload: { leases: [{ id: leaseId, lastHeartbeatAt: 1_010 }] }, + payload: { leases: [{ id: leaseId, lastRenewedAt: 1_010, ttlMs: 40 }] }, }); await expect(holder.request("list.get", { kind: "leases" })).resolves.toMatchObject({ ok: true, - payload: [{ id: leaseId, lastHeartbeatAt: 1_010 }], + payload: [{ id: leaseId, lastRenewedAt: 1_010, ttlMs: 40 }], + }); + await holder.close(); + }); + + it("leaves leases alone on a daemon stop", async () => { + const harness = await createHarness({ lease: { defaultTtlMs: 40 } }); + const holder = await createClient(harness.socketPath); + await hello(holder); + const grant = await holder.request("lease.request", { + requesterId: "agent-1", + model: "iPhone 16", + osVersion: "26.5", + platform: "ios", }); + const leaseId = leaseIdOf(grant); await holder.close(); + + await harness.daemon.stop("test"); + + // ADR 0004 §3: a stop ends connections, not leases. The record persists with its + // deadline for the next daemon to restore a timer from. + expect(harness.registry.snapshot.leases).toMatchObject([{ id: leaseId }]); + expect(harness.eventBus.replay().filter((event) => event.event === "lease.released")).toEqual( + [], + ); }); +}); +describe("DaemonServer decorations", () => { it("surfaces a derived transitionAgeMs for a mid-transition device in status and list --devices", async () => { const harness = await createHarness(); const device = await harness.registry.registerDevice({ @@ -1347,23 +1465,30 @@ describe("DaemonServer lease heartbeat", () => { ); }); - it("logs a connection opening with its declared capabilities and closing afterward", async () => { + it("logs a connection opening with its principal and role, and closing afterward", async () => { const { logger: log, sink } = logger(); const harness = await createHarness({ logger: log }); const client = await createClient(harness.socketPath); - await hello(client, { heartbeat: true }); + await helloAs(client, "agent-7"); expect(sink.records).toContainEqual( expect.objectContaining({ level: "info", message: "Connection opened", - fields: expect.objectContaining({ heartbeatCapability: true }), + fields: expect.objectContaining({ principal: "agent-7", role: "admin" }), }), ); await client.close(); + // ADR 0004 §3: there is no held-lease count to log any more, because there is no + // per-connection lease state to count. await expect - .poll(() => sink.records.some((record) => record.message === "Connection closed")) + .poll(() => + sink.records.some( + (record) => + record.message === "Connection closed" && record.fields?.principal === "agent-7", + ), + ) .toBe(true); }); @@ -1385,22 +1510,22 @@ describe("DaemonServer lease heartbeat", () => { }); const holder = await createClient(harness.socketPath); await hello(holder); - await holder.request("lease.request", { - mode: "held", + const grant = await holder.request("lease.request", { requesterId: "holder", model: "iPhone 16", osVersion: "26.5", platform: "ios", }); + // The stop itself releases nothing (ADR 0004 §3), so the reclaim `stop` has to drain + // is one somebody else started: the holder releasing on its way out, which commits + // the registry half and hands the purge off. + await holder.request("lease.release", { leaseId: leaseIdOf(grant) }); + expect(harness.registry.snapshot.leases).toHaveLength(0); + const stopping = harness.daemon.stop("test-drain"); await expect.poll(() => order).toEqual(["settle-start"]); - // The held lease is already gone -- that half of the release is synchronous -- - // but the purge it handed off is not, and `stop` waits for it so the pool is - // left settled rather than `reclaiming` for the next startup to recover. - expect(harness.registry.snapshot.leases).toHaveLength(0); - finishSettle(); await stopping; // Disposal last: a reclaim that settles into a purge failure arms a quarantine @@ -1448,7 +1573,6 @@ describe("DaemonServer lease heartbeat", () => { const holder = await createClient(harness.socketPath); await hello(holder); await holder.request("lease.request", { - mode: "held", requesterId: "holder", model: "iPhone 16", osVersion: "26.5", @@ -1458,9 +1582,9 @@ describe("DaemonServer lease heartbeat", () => { await harness.daemon.stop("test-stop-auxiliary"); expect(order).toEqual(["stopAuxiliary", "settle", "dispose"]); - // The held lease was still released as part of the same stop -- stopping the - // auxiliary frontend first doesn't skip the socket protocol's own teardown. - expect(harness.registry.snapshot.leases).toHaveLength(0); + // The lease is untouched: ADR 0004 §3 -- a stop tears down connections and timers, + // and leaves every lease standing with its deadline for the next daemon. + expect(harness.registry.snapshot.leases).toHaveLength(1); }); it("reports health via the public accessor across the startup/stop lifecycle", async () => { @@ -1554,7 +1678,6 @@ describe("DaemonServer download policy", () => { await hello(client); const grant = await client.request("lease.request", { - mode: "held", requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", @@ -1578,7 +1701,6 @@ describe("DaemonServer download policy", () => { const response = await client.request("lease.request", { allowDownload: true, - mode: "held", requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", @@ -1606,7 +1728,6 @@ describe("DaemonServer download policy", () => { // did before the policy existed -- and, unlike the never-policy case above, the message // is not attributed to configuration, since nothing in config forced the outcome. const response = await client.request("lease.request", { - mode: "held", requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", @@ -1630,7 +1751,6 @@ describe("DaemonServer download policy", () => { // `--allow-download`, which under the never policy can never help, so the suffix must // still attach as the correction. const response = await client.request("lease.request", { - mode: "held", requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", @@ -1659,7 +1779,6 @@ describe("DaemonServer download policy", () => { const response = await client.request("lease.request", { allowDownload: true, - mode: "held", requesterId: "agent-1", model: "iPhone 16", osVersion: "12.0", @@ -1683,7 +1802,6 @@ describe("DaemonServer full request flag", () => { await hello(client); const grant = await client.request("lease.request", { - mode: "held", requesterId: "agent-1", full: true, model: "iPhone 16", @@ -1704,7 +1822,6 @@ describe("DaemonServer full request flag", () => { await hello(client); const grant = await client.request("lease.request", { - mode: "held", requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", @@ -1729,7 +1846,6 @@ describe("DaemonServer error code mapping", () => { await hello(client); const response = await client.request("lease.request", { - mode: "held", requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", @@ -1754,7 +1870,6 @@ describe("DaemonServer error code mapping", () => { await hello(client); const response = await client.request("lease.request", { - mode: "held", requesterId: "agent-1", model: "Pixel 8", osVersion: "35", @@ -1974,7 +2089,6 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { const owner = await createClient(harness.socketPath); await helloAs(owner, "alice"); const grant = await owner.request("lease.request", { - mode: "held", model: "iPhone 16", osVersion: "26.5", platform: "ios", @@ -2006,7 +2120,6 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { const owner = await createClient(harness.socketPath); await helloAs(owner, "alice"); const grant = await owner.request("lease.request", { - mode: "held", model: "iPhone 16", osVersion: "26.5", platform: "ios", @@ -2028,7 +2141,6 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { const alice = await createClient(harness.socketPath); await helloAs(alice, "alice"); const aliceGrant = await alice.request("lease.request", { - mode: "detached", model: "iPhone 16", osVersion: "26.5", platform: "ios", @@ -2036,7 +2148,6 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { const bob = await createClient(harness.socketPath); await helloAs(bob, "bob"); await bob.request("lease.request", { - mode: "detached", requesterId: "bob-2", model: "iPhone 16", osVersion: "26.5", @@ -2059,33 +2170,32 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { await admin.close(); }); - it("forwards ttlMs as the initial TTL for a detached lease, and rejects it for a held one", async () => { + it("forwards ttlMs as the initial TTL of any lease, and stores it as the lease's width", async () => { const harness = await createHarness({ resolveRole: { resolve: () => "agent" } }); const client = await createClient(harness.socketPath); await hello(client); - const detached = await client.request("lease.request", { - mode: "detached", + const granted = await client.request("lease.request", { ttlMs: 30_000, model: "iPhone 16", osVersion: "26.5", platform: "ios", }); - expect(detached.ok).toBe(true); + expect(granted.ok).toBe(true); + // ADR 0004 §4: `ttlMs` is accepted on every request -- it used to be `BAD_REQUEST` unless + // the request also named `mode: "detached"` -- and the width it asks for is stored on the + // record, which is what a later body-less renew re-applies. expect( - (detached.payload as { lease: { grantedAt: number; ttlDeadline: number } }).lease, - ).toMatchObject({ grantedAt: 1_000, ttlDeadline: 1_000 + 30_000 }); + (granted.payload as { lease: { grantedAt: number; ttlMs: number; ttlDeadline: number } }) + .lease, + ).toMatchObject({ grantedAt: 1_000, ttlMs: 30_000, ttlDeadline: 1_000 + 30_000 }); - const held = await client.request("lease.request", { - mode: "held", - ttlMs: 30_000, - requesterId: "held-with-ttl", - model: "iPhone 16", - osVersion: "26.5", - platform: "ios", + const leaseId = leaseIdOf(granted); + harness.clock.advance(5_000); + await expect(client.request("lease.renew", { leaseId })).resolves.toMatchObject({ + ok: true, + payload: { ttlMs: 30_000, ttlDeadline: 6_000 + 30_000 }, }); - expect(held.ok).toBe(false); - expect(held.error).toMatchObject({ code: "BAD_REQUEST" }); await client.close(); }); @@ -2096,7 +2206,6 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { const holder = await createClient(harness.socketPath); await hello(holder); const held = await holder.request("lease.request", { - mode: "held", requesterId: "holder", model: "iPhone 16", osVersion: "26.5", @@ -2107,7 +2216,6 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { const waiter = await createClient(harness.socketPath); await hello(waiter); const queuedRequest = waiter.request("lease.request", { - mode: "held", requesterId: "waiter", model: "iPhone 16", osVersion: "26.5", @@ -2132,7 +2240,6 @@ describe("DaemonServer roles and ownership (ADR 0003 §2-4)", () => { const requester = await createClient(harness.socketPath); await helloAs(requester, "alice"); const grant = await requester.request("lease.request", { - mode: "detached", model: "iPhone 16", osVersion: "26.5", platform: "ios", @@ -2419,9 +2526,8 @@ function testConfig( ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, lease: { - detachedTtlMs: 60_000, - heldTtlBackstopMs: 60_000, - heartbeatIntervalMs: 5_000, + defaultTtlMs: 60_000, + maxTtlMs: 3_600_000, ...leaseOverrides, }, capacity: { diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 10606a347..1746f960d 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -11,7 +11,6 @@ import { type LeaseHealthMonitor, NoDriverError, type Nuke, - UnknownLeaseError, UnknownPassthroughToolError, } from "../core/index.js"; import type { @@ -21,7 +20,7 @@ import type { PassthroughResolver, QueueControl, } from "../core/lease-ports.js"; -import type { Clock, IpcConnection, Logger, TimerHandle } from "../ports/index.js"; +import type { Clock, IpcConnection, Logger } from "../ports/index.js"; import { NoopLogger } from "../ports/index.js"; import { parseRequestFrame, serializeFrame, type RequestFrame } from "../daemon-protocol/index.js"; import { @@ -50,12 +49,10 @@ type RequestId = string | number; interface Connection { readonly socket: IpcConnection; - readonly heldLeaseIds: Set; readonly progressDisposers: Set<() => void>; readonly progressRequesters: Set; buffer: string; helloReceived: boolean; - heartbeatCapability: boolean; closed: boolean; /** ADR 0003 §4: fixed at `hello` for the connection's lifetime. `principal` defaults to * `options.defaultRequesterId` when `hello` omits one (today's CLI/MCP -- PR 4 moves them @@ -66,14 +63,13 @@ interface Connection { /** * Lease ids this connection is *currently* explicitly releasing (`lease.release`/ * `lease.release-all`), added right before the dispatched call and consumed by - * `#notifyLeaseLost`. ADR §8 says a client "never fires `onLeaseLost` for a release the same - * client asked for" -- stated as the *client's* dedup rule (a future PR), but with pushes now - * owner-routed to every connection sharing a principal (not just the single held-lease - * holder), the daemon can no longer rely on `heldLeaseIds` membership alone to skip the - * asking connection: that would also wrongly skip every *other* live connection with the - * same principal, which is exactly the fan-out this PR adds. So the daemon still suppresses - * the self-push for the one connection that asked, by connection identity rather than by - * principal, and lets every other owning connection's push through undisturbed. + * `#notifyLeaseLost`. ADR 0003 §8 says a client "never fires `onLeaseLost` for a release the + * same client asked for", and pushes are owner-routed to every connection sharing a + * principal, so the suppression has to be by connection identity: skipping by principal + * would wrongly skip every *other* live connection owning the lease. This is the only + * lease-shaped state a connection still keeps, and it lives for the duration of one + * dispatched call rather than for the lease's lifetime -- ADR 0004 §3 deletes the held set + * that used to sit beside it. */ readonly selfInitiatedReleases: Set; /** Set by `#handleHello` only when this connection's `hello` failed protocol-version @@ -90,7 +86,6 @@ interface Connection { * `DaemonServer` has no `IdGenerator` dependency today, and this only needs to be unique per * connection lifetime, not globally unpredictable. */ subscriptionId: string | undefined; - releasing: Promise | undefined; } export interface DaemonServerOptions { @@ -144,7 +139,9 @@ export interface DaemonServerOptions { * Awaits lease work the subsystem is finishing off its callers' paths — today the * backgrounded device reclaims a release hands off (see `LeaseReleaseCoordinator`). * A graceful stop drains it so the pool is left settled; an ungraceful death leaves - * it for startup recovery. Runs after held leases are released and before `dispose`. + * it for startup recovery. The stop itself releases nothing (ADR 0004 §3), so what this + * drains is work somebody else's release already handed off; it runs before `dispose`, so a + * quarantine retry timer armed by a reclaim settling late is still cancelled. */ readonly settle?: () => Promise; /** @@ -181,8 +178,6 @@ export class DaemonServer { readonly #protocolRange: ProtocolRange; readonly #unsubscribeLeaseLost: Array<() => void> = []; readonly #logger: Logger; - #heartbeatTimer: TimerHandle | undefined; - #heartbeatNonce = 0; #eventSubscriptionSeq = 0; #stopping = false; #stopPromise: Promise | undefined; @@ -327,7 +322,7 @@ export class DaemonServer { // flight -- `daemon.stop` is accepted during startup (see `#dispatchLine`), and an // auxiliary frontend that fails to start asks for a stop of its own. Everything below // this point arms live machinery: it subscribes to the fact bus, emits `daemon.started`, - // schedules the heartbeat tick, and starts the health monitor. Running any of that + // and starts the health monitor. Running any of that // against an already-disposed engine would leave timers armed on a dead daemon and would // emit `daemon.started` after `daemon.stopping` -- a fact that is not true when emitted, // which `docs/agent-rules/events.md` rule 3 forbids. Bail out instead; the stop that @@ -339,13 +334,21 @@ export class DaemonServer { return; } - // Subscribed only now, after convergence, not before `start()` claimed the - // socket: the only thing that emits `lease.released` during convergence is - // `convergeRunningCapacity()`'s own orphaned-held-lease release, and by - // definition no live connection holds an orphaned lease on a daemon that has - // just started (a held lease's liveness is its daemon connection, which cannot - // have survived the restart). So nothing emitted during the window needs a - // `lease-lost` push. A parked `lease.request` is safe too: `start()`'s own + // Subscribed only now, after convergence, not before `start()` claimed the socket. Under + // ADR 0004 convergence releases nothing at all (the orphan sweep is gone), so the only + // lease fact it can still emit is a `lease.expired` for a lease whose deadline passed + // while no daemon was running. + // + // Such a `lease-lost` push can genuinely be missed, and that is accepted rather than + // assumed away: the socket has been accepting connections since the claim, `hello` is + // answered throughout the window, and a client's renew timer may well be connected while + // `restore()` expires its overdue lease. What that client loses is the push, not the + // fact -- its next `lease.renew` answers `UNKNOWN_LEASE`, which every holder already + // treats as the end of the lease (`onLeaseGone`, `src/lease-policy/index.ts`). Wiring the + // subscription earlier would instead push from a daemon that has not finished converging, + // which is the worse trade. + // + // A parked `lease.request` is safe: `start()`'s own // continuation is registered on `#readyPromise` before any later request's (the // client can only reach the gate after `host.start()`'s callback is wired, well // after `start()` began awaiting), so on the shared microtask queue this @@ -394,7 +397,6 @@ export class DaemonServer { socketPath: this.options.host.endpoint, version: this.options.version, }); - this.#scheduleHeartbeatTick(); // Armed only here, after convergence: a probe tick shells out per platform, and // convergence is already doing that per driver and device. Starting it late is // also what keeps the subscriptions above safe -- nothing can emit @@ -437,26 +439,23 @@ export class DaemonServer { } async #stop(reason: string): Promise { - // Awaited first, before anything below: an auxiliary frontend calls the role - // interfaces directly rather than parking on `#awaitReady`/this method's own - // teardown order, so it must be shut off before held-lease release and - // lease/queue teardown begin -- otherwise a request arriving through it mid-stop - // could run against an engine already being torn down. + // Awaited first, before anything below: an auxiliary frontend calls the role interfaces + // directly rather than parking on `#awaitReady`/this method's own teardown order, so it + // must be shut off before lease/queue teardown begins -- otherwise a request arriving + // through it mid-stop could run against an engine already being torn down. await this.options.stopAuxiliary?.(); this.#logger.info("Daemon stopping", { reason }); this.options.eventBus.emit("daemon.stopping", { reason }, "daemon"); - if (this.#heartbeatTimer !== undefined) { - this.options.clock.cancel(this.#heartbeatTimer); - this.#heartbeatTimer = undefined; - } for (const unsubscribe of this.#unsubscribeLeaseLost.splice(0)) unsubscribe(); this.#ownerRoutedFacts.dispose(); this.options.reaper.dispose(); this.options.healthMonitor?.dispose(); - await Promise.all([...this.#connections].map((connection) => this.#releaseHeld(connection))); - // Those releases only commit the registry half and hand the purge off; draining it - // here keeps `daemon stop` finishing on a settled pool, as it did when the reclaim - // was inline. Disposal follows rather than precedes it, so a retry timer armed by a + // ADR 0004 §3: a stop releases nothing. Every lease persists with its deadline, and the + // next daemon restores its timer from that deadline (`StartupConverger`); one whose + // deadline passed in between expires as soon as a daemon is there to expire it. What is + // drained here is only work already in flight -- a release someone else asked for commits + // the registry half and hands its purge off, so draining keeps `daemon stop` finishing on + // a settled pool. Disposal follows rather than precedes it, so a retry timer armed by a // reclaim that settles into quarantine is still cancelled. await this.options.settle?.(); await this.options.dispose?.(); @@ -481,8 +480,6 @@ export class DaemonServer { buffer: "", closed: false, helloReceived: false, - heartbeatCapability: false, - heldLeaseIds: new Set(), // Overwritten by `#handleHello` before any dispatched request can read them -- every // path that reaches `#handleRequest` has `connection.helloReceived === true` by // construction (`#dispatchLine` routes to `#handleHello` until then). @@ -493,7 +490,6 @@ export class DaemonServer { protocolMismatch: undefined, selfInitiatedReleases: new Set(), socket, - releasing: undefined, subscriptionId: undefined, unsubscribeEvents: undefined, }; @@ -707,7 +703,6 @@ export class DaemonServer { await connection.socket.close(); return; } - connection.heartbeatCapability = payload.capabilities?.heartbeat === true; // ADR §4: the principal is fixed for the connection's lifetime from here on. Falls back to // `defaultRequesterId` when `hello` omits one -- today's CLI/MCP frontends don't send a // principal yet (PR 4 moves them onto the typed client, which always will). @@ -746,7 +741,6 @@ export class DaemonServer { connection.helloReceived = true; this.#logger.info("Connection opened", { clientVersion: payload.clientVersion, - heartbeatCapability: connection.heartbeatCapability, principal: connection.principal, protocolVersion: negotiated, role: connection.role, @@ -770,23 +764,23 @@ export class DaemonServer { } /** - * The request switch that used to live here moved to `Dispatcher` (ADR §2): this method now - * only does what the ADR says stays with `DaemonServer` around the shared `dispatch()` call -- - * held-lease tracking (`lease.request`/`lease.release`/`lease.release-all`) and building the - * per-call `DispatchSession` (ADR §2/§4) from this connection's fixed principal/role plus - * whatever is call-specific (progress delivery, event-subscription management). + * The request switch that used to live here moved to `Dispatcher` (ADR 0003 §2): this method + * now only does what stays with `DaemonServer` around the shared `dispatch()` call -- + * building the per-call `DispatchSession` (ADR §2/§4) from this connection's fixed + * principal/role plus whatever is call-specific (progress delivery, event-subscription + * management), and marking a release this connection asked for so its own `lease-lost` push + * is suppressed. ADR 0004 §3 deleted the held-lease tracking that used to live here too: the + * daemon keeps no per-connection lease state, so a release is no longer bookkeeping to undo + * on failure, only a push to suppress while it is in flight. */ - // fallow-ignore-next-line complexity -- held-lease bookkeeping around each dispatched operation is one transaction per case. + // fallow-ignore-next-line complexity -- one case per request type; the switch is the transport's whole surface. async #handleRequest(connection: Connection, frame: RequestFrame): Promise { switch (frame.type) { case "lease.request": return this.#requestLease(connection, frame.id, frame.payload); case "lease.release": { const input = parseInput(leaseRelease.input, frame.payload); - // Clear before the request commits so held-lease bookkeeping does not try to release - // this lease again on a later connection close. Marked in `selfInitiatedReleases` too, - // for `#notifyLeaseLost` to suppress the self-push -- see that set's comment. - const wasHeld = connection.heldLeaseIds.delete(input.leaseId); + // Marked for `#notifyLeaseLost` to suppress the self-push -- see that set's comment. connection.selfInitiatedReleases.add(input.leaseId); try { return await this.#dispatcher.dispatch( @@ -794,28 +788,34 @@ export class DaemonServer { frame.payload, this.#session(connection), ); - } catch (error: unknown) { - if (wasHeld) connection.heldLeaseIds.add(input.leaseId); - throw error; } finally { connection.selfInitiatedReleases.delete(input.leaseId); } } case "lease.release-all": { - const previouslyHeld = [...connection.heldLeaseIds]; - connection.heldLeaseIds.clear(); - for (const leaseId of previouslyHeld) connection.selfInitiatedReleases.add(leaseId); + // Every lease this principal owns is about to end, and this connection asked for it, + // so suppress the self-push for each. Read from the registry rather than from + // per-connection state, which no longer exists (ADR 0004 §3). + // + // The snapshot can skew either way against what the dispatched call actually + // releases, and both ways are acceptable: a lease that expires inside the window is + // suppressed here even though its `lease-lost` was the daemon's own doing (the caller + // asked for that lease to end and is about to be told every lease of theirs is gone), + // and one granted inside the window is not suppressed, so its holder gets the push it + // would have got for any other force-release. Neither can suppress a push for a lease + // this principal does not own, which is the property that matters. + const releasing = this.options.registry.snapshot.leases + .filter((lease) => connection.role === "admin" || lease.ownerId === connection.principal) + .map((lease) => lease.id); + for (const leaseId of releasing) connection.selfInitiatedReleases.add(leaseId); try { return await this.#dispatcher.dispatch( "lease.release-all", frame.payload ?? {}, this.#session(connection), ); - } catch (error: unknown) { - for (const leaseId of previouslyHeld) connection.heldLeaseIds.add(leaseId); - throw error; } finally { - for (const leaseId of previouslyHeld) connection.selfInitiatedReleases.delete(leaseId); + for (const leaseId of releasing) connection.selfInitiatedReleases.delete(leaseId); } } case "lease.renew": @@ -832,12 +832,6 @@ export class DaemonServer { frame.payload ?? {}, this.#session(connection), ); - case "lease.heartbeat": - return this.#dispatcher.dispatch( - "lease.heartbeat", - frame.payload ?? {}, - this.#session(connection), - ); case "status.get": return this.#dispatcher.dispatch( "status.get", @@ -926,14 +920,13 @@ export class DaemonServer { } } - /** Builds the ADR §2/§4 session for one dispatched call from this connection's fixed - * principal/role plus its currently-held leases and heartbeat capability. `onProgress` is - * unset here -- only `#requestLease` needs one, and builds its own session inline so the - * closure can see that specific call's `requestId`. */ + /** Builds the ADR 0003 §2/§4 session for one dispatched call from this connection's fixed + * principal and role -- all that is left of it, since ADR 0004 removed the per-connection + * lease state that used to travel alongside. `onProgress` is unset here: only `#requestLease` + * needs one, and builds its own session inline so the closure can see that specific call's + * `requestId`. */ #session(connection: Connection): DispatchSession { return { - heartbeatCapability: connection.heartbeatCapability, - heldLeaseIds: connection.heldLeaseIds, manageEventSubscription: (subscribe) => this.#manageEventSubscription(connection, subscribe), principal: connection.principal, role: connection.role, @@ -960,11 +953,12 @@ export class DaemonServer { } /** - * The held-lease tracking and progress-delivery wiring ADR §2 keeps in `DaemonServer` - * ("DaemonServer keeps framing, connection lifecycle, held-lease tracking, and pushes; it - * loses the request switch"). The actual lease acquisition is `Dispatcher`'s - * `lease.request` handler; this method's job is everything around that call that depends on - * *this connection* rather than on the operation itself. + * The progress-delivery wiring ADR 0003 §2 keeps in `DaemonServer` ("DaemonServer keeps + * framing, connection lifecycle, and pushes; it loses the request switch"). The actual lease + * acquisition is `Dispatcher`'s `lease.request` handler; this method's job is what is left + * around that call that depends on *this connection* rather than on the operation itself, + * which since ADR 0004 is progress routing and nothing else -- a granted lease is not + * attached to the connection that asked for it in any way. */ async #requestLease( connection: Connection, @@ -1002,11 +996,10 @@ export class DaemonServer { connection.progressRequesters.delete(requesterId); disposeProgress(); } - if (grant.lease.mode === "held" && (connection.closed || this.#stopping)) { - await this.options.leases.release(grant.lease.id, "closed"); - } else if (grant.lease.mode === "held") { - connection.heldLeaseIds.add(grant.lease.id); - } + // A grant that lands after its requester's connection died (or during a stop) is left + // standing on purpose: ADR 0004 §3 -- connection close means nothing to a lease, so the + // client that reconnects can renew it, and if none does it expires at its deadline like + // any other. return grant; } @@ -1060,56 +1053,15 @@ export class DaemonServer { }); } - /** - * Pushes `lease.heartbeat` every `lease.heartbeatIntervalMs` to every connection that - * both declared the capability at `hello` and currently holds at least one lease. - * Reschedules itself each tick since `Clock` has no `setInterval`. - */ - #scheduleHeartbeatTick(): void { - if (this.#stopping) return; - this.#heartbeatTimer = this.options.clock.setTimer( - this.options.config.lease.heartbeatIntervalMs, - () => { - this.#sendHeartbeatPushes(); - this.#scheduleHeartbeatTick(); - }, - ); - } - - #sendHeartbeatPushes(): void { - for (const connection of this.#connections) { - if (!connection.heartbeatCapability || connection.heldLeaseIds.size === 0) continue; - this.#heartbeatNonce += 1; - void this.#pushHeartbeat(connection.socket, this.#heartbeatNonce); - } - } - - async #pushHeartbeat(socket: IpcConnection, nonce: number): Promise { - await writeFrame(socket, { - push: "lease.heartbeat", - payload: this.#parseOutput( - PUSH_SCHEMAS["lease.heartbeat"], - { nonce }, - "push:lease.heartbeat", - ), - }); - } - /** * Pushes a lease-ended fact to every live connection whose principal owns `leaseId` (ADR - * §8: "every live connection whose principal owns the lease, in either mode" -- not just the - * held-lease holder, which is the bug this PR fixes: a detached holder used to learn of a - * crash only when a renew failed). Also stops tracking the lease as held on whichever - * connection had it in `heldLeaseIds` (there is at most one), so a later connection close - * does not try to release it again -- the held set survives this PR for exactly that - * bookkeeping, nothing else (ADR §8: "The held set is kept only for release-on-close"). + * 0003 §8, kept by ADR 0004 §5: these are facts about the device, not a liveness channel). * Reacts to the existing post-commit lease.expired / lease.released facts (observer-only; no * transaction waits on this). `ownerId` comes from the event payload, not a registry lookup: * by the time this fires the lease has already been removed from the registry. */ #notifyLeaseLost(leaseId: string, deviceId: string, reason: string, ownerId: string): void { for (const connection of this.#connections) { - connection.heldLeaseIds.delete(leaseId); // Suppresses the push for exactly the connection that asked for this release itself // (see `selfInitiatedReleases`'s comment) -- every other connection sharing the owner // still gets pushed, which is the owner-routed fan-out this PR adds. @@ -1202,7 +1154,10 @@ export class DaemonServer { } connection.closed = true; if (connection.helloReceived) { - this.#logger.info("Connection closed", { heldLeaseCount: connection.heldLeaseIds.size }); + // ADR 0004 §3: closing a connection is not a lease event. Whatever this principal held + // is still granted, still counting down its TTL, and still renewable by whatever + // connects next -- there is nothing to release here and nothing to count. + this.#logger.info("Connection closed", { principal: connection.principal }); } for (const disposeProgress of connection.progressDisposers) { disposeProgress(); @@ -1215,38 +1170,6 @@ export class DaemonServer { this.#connections.delete(connection); connection.unsubscribeEvents?.(); connection.unsubscribeEvents = undefined; - void this.#releaseHeld(connection).catch(() => undefined); - } - - #releaseHeld(connection: Connection): Promise { - if (connection.releasing !== undefined) { - return connection.releasing; - } - const leaseIds = [...connection.heldLeaseIds]; - connection.heldLeaseIds.clear(); - const releasing = Promise.all( - leaseIds.map(async (leaseId) => { - try { - await this.options.leases.release(leaseId, "closed"); - } catch (error: unknown) { - if (!(error instanceof UnknownLeaseError)) { - throw error; - } - } - }), - ).then(() => undefined); - connection.releasing = releasing; - void releasing.then( - () => this.#clearReleasing(connection, releasing), - () => this.#clearReleasing(connection, releasing), - ); - return releasing; - } - - #clearReleasing(connection: Connection, releasing: Promise): void { - if (connection.releasing === releasing) { - connection.releasing = undefined; - } } } diff --git a/src/http/app.test.ts b/src/http/app.test.ts index ac1439f87..f53a5d322 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -376,11 +376,50 @@ describe("POST /v1/lease-requests", () => { expect(secondBody.request.id).toBe(firstId); }); + it("refuses a ttlMs above lease.maxTtlMs with 400, before the request resource exists", async () => { + const { app, dispatcher } = buildHarness({ + config: testConfig({ defaultTtlMs: 60_000, maxTtlMs: 120_000 }), + }); + + const response = await postLeaseRequest(app, { ...defaultBody, ttlMs: 120_001 }); + + expect(response.status).toBe(400); + expect((await response.json()) as { error: { code: string } }).toMatchObject({ + error: { code: "BAD_REQUEST" }, + }); + expect( + dispatcher.calls.filter((call) => call.operation === "lease.request"), + "nothing was admitted, so there is no request resource to poll either", + ).toHaveLength(0); + }); + + it("refuses it the same way when allowDownload makes the 201 settle without waiting", async () => { + // The shape that made this route need its own cap check: with `allowDownload: true` the + // tracker answers `201 Created` as soon as the dispatch is *started*, so a rejection the + // dispatcher raises afterwards would land on the request resource instead of on this + // response -- a 201 for a TTL `docs/HTTP-API.md` promises is a 400. + const { app, dispatcher } = buildHarness({ + config: testConfig({ defaultTtlMs: 60_000, maxTtlMs: 120_000 }), + }); + + const response = await postLeaseRequest(app, { + ...defaultBody, + allowDownload: true, + ttlMs: 120_001, + }); + + expect(response.status).toBe(400); + expect((await response.json()) as { error: { code: string } }).toMatchObject({ + error: { code: "BAD_REQUEST" }, + }); + expect(dispatcher.calls.filter((call) => call.operation === "lease.request")).toHaveLength(0); + }); + it("passes a caller-supplied ttlMs straight onto the dispatch input -- no separate renew call (ADR §9)", async () => { const { app, dispatcher } = buildHarness(); const responsePromise = postLeaseRequest(app, { ...defaultBody, ttlMs: 60_000 }); const call = await waitForDispatch(dispatcher, "lease.request"); - expect(call.input).toMatchObject({ mode: "detached", ttlMs: 60_000 }); + expect(call.input).toMatchObject({ ttlMs: 60_000 }); call.resolve(makeGrant({ lease: { grantedAt: 1_000, id: "lse_1", ttlDeadline: 61_000 } })); await responsePromise; expect(dispatcher.calls.filter((c) => c.operation === "lease.renew")).toHaveLength(0); @@ -552,7 +591,6 @@ describe("lease routes", () => { deviceId: "dev_1", grantedAt: 1_000, id: (input as { leaseId: string }).leaseId, - mode: "detached", ownerId: "tok_agent", requesterId: "tok_agent", ttlDeadline: 2_000 + ((input as { ttlMs?: number }).ttlMs ?? 900_000), @@ -593,7 +631,6 @@ describe("lease routes", () => { deviceId: "dev_1", grantedAt: 1_000, id: "lse_1", - mode: "detached", ownerId: "tok_agent", requesterId: "tok_agent", ttlDeadline: 2_000, @@ -829,13 +866,18 @@ describe("hardening from review", () => { ); }); - it("reports the mode-default ttlMs for a lease the tracker has no record of", async () => { - const { app, config, registry } = buildHarness(); + it("reports the lease's own stored ttlMs, with nothing gateway-side to remember", async () => { + // ADR 0004: the width lives on the lease record, so a payload served by a gateway that + // never saw the request (after a daemon restart, say) still reports the real width + // instead of a mode default standing in for one. + const { app, registry } = buildHarness(); registry.devices = [makeDevice({ id: "dev_1" })]; - registry.leases = [makeLease({ deviceId: "dev_1", id: "lse_1", ownerId: "tok_agent" })]; + registry.leases = [ + makeLease({ deviceId: "dev_1", id: "lse_1", ownerId: "tok_agent", ttlMs: 123_000 }), + ]; const response = await app.request("/v1/leases/lse_1", { headers: agentAuth }); const body = (await response.json()) as { lease: { ttlMs: number } }; - expect(body.lease.ttlMs).toBe(config.lease.detachedTtlMs); + expect(body.lease.ttlMs).toBe(123_000); }); }); diff --git a/src/http/app.ts b/src/http/app.ts index 685385896..a0c04db34 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -83,6 +83,28 @@ function toLeaseRequestInput(body: z.infer): Leas }; } +/** + * ADR 0004 §4's cap, for the one route that cannot wait for the dispatcher's answer. The + * dispatcher enforces it for every transport, and every route that *awaits* its dispatch + * inherits that answer -- but `POST /v1/lease-requests` is an async resource, and an + * `allowDownload: true` request settles its `201` synchronously (a driver install can run for + * minutes before the first progress callback, see `LeaseRequestTracker#submit`), so a + * rejection landing afterwards would surface as a failed request resource rather than the + * `400 BAD_REQUEST` `docs/HTTP-API.md` promises. + * + * Deliberately not used on `POST /v1/leases/{id}/renew`: that route awaits its dispatch, so + * the shared cap already answers it -- and answers it *after* `ownsLease`, which is what keeps + * another requester's lease a `403` instead of a `400` about a TTL that caller could never + * have set anyway. + */ +function requireTtlWithinCap(ttlMs: number | undefined, config: Config): void { + if (ttlMs !== undefined && ttlMs > config.lease.maxTtlMs) { + throw badRequest( + `ttlMs ${String(ttlMs)} exceeds lease.maxTtlMs (${String(config.lease.maxTtlMs)})`, + ); + } +} + /** The gateway-owned subscriptions `createHttpApp` starts, attached to the returned app so a caller can dispose them on shutdown without this module exposing the tracker/notices instances themselves. */ export interface HttpAppDisposable { readonly dispose: () => void; @@ -103,7 +125,6 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa const logger = deps.logger.child("http"); const tracker = new LeaseRequestTracker({ clock: deps.clock, - defaultTtlMs: deps.config.lease.detachedTtlMs, dispatch: deps.dispatch, idGenerator: deps.idGenerator, logger, @@ -186,6 +207,8 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa ); } + requireTtlWithinCap(body.ttlMs, deps.config); + const outcome = await tracker.submit(identity, toLeaseRequestInput(body), idempotencyKey); if (outcome.kind === "rejected") { return errorResponse(c, outcome.error); @@ -266,13 +289,13 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa const lease = await findOwnedLease(deps, session, c.req.param("id")); const device = findDevice(deps, lease.deviceId); if (device === undefined) throw unknownLease(lease.id); + // ADR 0004: `ttlMs` comes off the lease record itself, so a payload served after a daemon + // restart reports the lease's real width rather than a mode default standing in for a + // per-request value this gateway no longer remembers. `requestId` is still gateway-side + // bookkeeping, and is still the one field a restart can drop. const requestId = tracker.requestIdForLease(lease.id); - const ttlMs = tracker.effectiveTtlMs(lease.id) ?? modeDefaultTtlMs(lease, deps.config); return c.json({ - lease: buildLeasePayload(device, lease, { - ...(requestId === undefined ? {} : { requestId }), - ttlMs, - }), + lease: buildLeasePayload(device, lease, requestId === undefined ? {} : { requestId }), }); }); @@ -289,13 +312,18 @@ export function createHttpApp(deps: HttpGatewayDeps): Hono & HttpAppDisposa // Dispatched directly (not via `findOwnedLease`/`lease.list`) so `lease.renew`'s own // `ownsLease` authorize hook answers -- an unowned lease is `FORBIDDEN`/403, matching the // socket transport, rather than the `UNKNOWN_LEASE`/404 a `lease.list` filter would produce - // (S6). An unknown id still surfaces as `UNKNOWN_LEASE`/404 from the handler itself. + // (S6). An unknown id still surfaces as `UNKNOWN_LEASE`/404 from the handler itself, and a + // `ttlMs` above `lease.maxTtlMs` as `BAD_REQUEST`/400 -- the cap lives in the shared + // dispatcher, and this route awaits it, so there is nothing to restate here. Answering it + // earlier would answer it *before* `ownsLease` and turn another requester's lease into a + // 400 about its TTL where the socket and `docs/HTTP-API.md` both say 403. An omitted + // `ttlMs` re-applies the lease's own stored width (ADR 0004 §4), which is why nothing is + // recorded here afterwards. const renewed = await deps.dispatch( "lease.renew", { leaseId: id, ...(ttlMs === undefined ? {} : { ttlMs }) }, session, ); - tracker.recordLeaseTtl(id, ttlMs ?? modeDefaultTtlMs(renewed, deps.config)); return c.json({ expiresAt: new Date(renewed.ttlDeadline).toISOString(), @@ -473,11 +501,6 @@ function serializeRequest( } } -/** The interval a default (body-less) renew of this lease applies -- its mode's configured TTL. */ -function modeDefaultTtlMs(lease: { readonly mode: "held" | "detached" }, config: Config): number { - return lease.mode === "held" ? config.lease.heldTtlBackstopMs : config.lease.detachedTtlMs; -} - function findDevice(deps: HttpGatewayDeps, id: string): DeviceRecord | undefined { return deps.registry.snapshot.devices.find((device) => device.id === id); } diff --git a/src/http/dispatcher-session.ts b/src/http/dispatcher-session.ts index 37d69a16c..4132a6f41 100644 --- a/src/http/dispatcher-session.ts +++ b/src/http/dispatcher-session.ts @@ -17,13 +17,6 @@ export type HttpDispatch = ( session: DispatchSession, ) => Promise>; -/** No HTTP request ever holds a lease across calls (every HTTP lease is detached, ADR 0003 - * §2/§9's "the HTTP tracker and notice buffer remain the known stateful leftovers in a - * frontend" -- held-lease bookkeeping stays a socket-connection concept), so every - * `DispatchSession` built for an HTTP request shares this same empty, frozen set rather than - * allocating one per call. */ -const NO_HELD_LEASES: ReadonlySet = new Set(); - /** ADR §5's socket roles map onto HTTP's pre-existing bearer-token roles one for one: an * `operator` token is what already grants HTTP's admin-only routes (`/v1/leases`, * `/v1/devices`, `/v1/events`...), so it resolves to the contract's `"admin"`; an `agent` @@ -55,8 +48,6 @@ export function buildHttpSession( }, ): DispatchSession { return { - heartbeatCapability: false, - heldLeaseIds: NO_HELD_LEASES, manageEventSubscription: extra?.manageEventSubscription ?? (() => undefined), principal: identity.requesterId, role: toRole(identity.role), diff --git a/src/http/test-fakes.ts b/src/http/test-fakes.ts index 61a6b3d37..51c256151 100644 --- a/src/http/test-fakes.ts +++ b/src/http/test-fakes.ts @@ -37,9 +37,8 @@ export function testConfig(overrides: Partial = {}): Config { idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, lease: { - detachedTtlMs: 900_000, - heartbeatIntervalMs: 5_000, - heldTtlBackstopMs: 3_600_000, + defaultTtlMs: 900_000, + maxTtlMs: 14_400_000, ...overrides, }, log: { level: "info", rotateBytes: 5 * 1024 * 1024 }, @@ -82,9 +81,10 @@ export function makeLease(overrides: Partial = {}): LeaseRecord { deviceId: "dev_1", grantedAt: 1_000, id: "lse_1", - mode: "detached", ownerId: "tok_agent", requesterId: "tok_agent", + lastRenewedAt: 1_000, + ttlMs: 60_000, ttlDeadline: 1_000 + 900_000, ...overrides, }; diff --git a/src/http/tracker.test.ts b/src/http/tracker.test.ts index e3b3332f5..8ae882381 100644 --- a/src/http/tracker.test.ts +++ b/src/http/tracker.test.ts @@ -5,12 +5,11 @@ import { FakeClock } from "../ports/index.js"; import { FakeDispatcher, makeGrant, sequenceIdGenerator, waitForDispatch } from "./test-fakes.js"; import { isTerminalStage, LeaseRequestTracker, type TrackedRequestView } from "./tracker.js"; -function buildTracker(overrides: { readonly defaultTtlMs?: number } = {}) { +function buildTracker() { const clock = new FakeClock(1_000); const dispatcher = new FakeDispatcher(); const tracker = new LeaseRequestTracker({ clock, - defaultTtlMs: overrides.defaultTtlMs ?? 900_000, dispatch: (op, input, session) => dispatcher.dispatch(op, input, session) as never, idGenerator: sequenceIdGenerator("req"), }); @@ -114,10 +113,10 @@ describe("LeaseRequestTracker.submit", () => { }); it("passes a caller-supplied ttlMs directly on the lease.request input -- no separate renew call", async () => { - const { dispatcher, tracker } = buildTracker({ defaultTtlMs: 900_000 }); + const { dispatcher, tracker } = buildTracker(); const outcomePromise = tracker.submit(identity, { ...body, ttlMs: 60_000 }); const call = await waitForDispatch(dispatcher, "lease.request"); - expect(call.input).toMatchObject({ mode: "detached", ttlMs: 60_000 }); + expect(call.input).toMatchObject({ ttlMs: 60_000 }); call.resolve( makeGrant({ lease: { grantedAt: 1_000, id: "lse_1", ttlDeadline: 1_000 + 60_000 } }), diff --git a/src/http/tracker.ts b/src/http/tracker.ts index 6f5610959..34fb38844 100644 --- a/src/http/tracker.ts +++ b/src/http/tracker.ts @@ -34,12 +34,13 @@ export interface LeasePayload { } /** - * `LeaseRecord` has no `createdAt` -- `grantedAt` is its equivalent. `ttlMs` must be supplied - * by the caller (the tracker's record of what was applied at grant, or the lease's mode - * default when that record is gone, e.g. after a daemon restart). It is never derived as - * `ttlDeadline - grantedAt`: `grantedAt` never moves on renewal, so that arithmetic reports - * grant-age plus TTL rather than the interval actually in force -- `expiresAt` is the - * authoritative deadline either way. Parameter types are deliberately narrower than the full + * `LeaseRecord` has no `createdAt` -- `grantedAt` is its equivalent. `ttlMs` is read straight + * off the lease record (ADR 0004: the daemon stores the width a lease was granted with, or + * last renewed with), so it survives a daemon restart along with the deadline and this gateway + * remembers nothing per request to produce it. It is never derived as `ttlDeadline - + * grantedAt`: `grantedAt` never moves on renewal, so that arithmetic reports grant-age plus + * TTL rather than the width actually in force -- `expiresAt` is the authoritative deadline + * either way. Parameter types are deliberately narrower than the full * `DeviceRecord`/`LeaseRecord` (only the fields this function reads): both the dispatcher's * `lease.request` output and the core's own `LeaseGrant` satisfy this shape, so this function * works unchanged whether the tracker is fed directly or through `dispatch()`. @@ -47,7 +48,7 @@ export interface LeasePayload { export function buildLeasePayload( device: HttpLeaseDevice, lease: HttpLeaseRecord, - extra: { readonly requestId?: string; readonly ttlMs: number }, + extra: { readonly requestId?: string } = {}, ): LeasePayload { return { id: lease.id, @@ -59,7 +60,7 @@ export function buildLeasePayload( deviceId: device.id, createdAt: new Date(lease.grantedAt).toISOString(), expiresAt: new Date(lease.ttlDeadline).toISOString(), - ttlMs: extra.ttlMs, + ttlMs: lease.ttlMs, dataPlane: null, slim: device.featureProfile === "reduced", }; @@ -126,8 +127,6 @@ export interface LeaseRequestTrackerOptions { readonly dispatch: HttpDispatch; readonly clock: Clock; readonly idGenerator: IdGenerator; - /** `lease.detachedTtlMs` -- every HTTP lease is detached, so this is the one mode default that applies. */ - readonly defaultTtlMs: number; readonly logger?: Logger; } @@ -142,7 +141,6 @@ export class LeaseRequestTracker { readonly #requests = new Map(); readonly #idempotency = new Map(); readonly #leaseRequestId = new Map(); - readonly #leaseTtlMs = new Map(); /** * The retention/idempotency-TTL timers `#setState`/`#registerIdempotency` arm below, * tracked so `dispose()` can cancel whichever are still outstanding. Without this, a @@ -210,19 +208,18 @@ export class LeaseRequestTracker { platform: body.platform, ...(body.os === undefined ? {} : { osVersion: body.os }), ...(body.full === undefined ? {} : { full: body.full }), - mode: "detached", ...(body.noWait === undefined ? {} : { noWait: body.noWait }), ...(body.allowDownload === undefined ? {} : { allowDownload: body.allowDownload }), ...(body.timeoutMs === undefined ? {} : { timeoutMs: body.timeoutMs }), - // ADR §9: the initial TTL travels on the request itself now -- this deletes the old - // grant-then-immediately-renew hack (`#applyGrant` below just records what was - // actually granted, it never issues a second call to apply it). + // ADR 0003 §9: the initial TTL travels on the request itself -- this deletes the + // old grant-then-immediately-renew hack. Under ADR 0004 the daemon then stores + // that width on the lease, so nothing here has to remember it either. ...(body.ttlMs === undefined ? {} : { ttlMs: body.ttlMs }), }, session, ) .then((grant) => { - this.#applyGrant(record, grant, body.ttlMs); + this.#applyGrant(record, grant); settleCreated(); }) .catch((error: unknown) => { @@ -329,26 +326,17 @@ export class LeaseRequestTracker { return { kind: "not-cancellable" }; } - /** The tracker's own record of the ttl actually applied to a lease it granted (grant or renew). */ - effectiveTtlMs(leaseId: string): number | undefined { - return this.#leaseTtlMs.get(leaseId); - } - - /** Updates the tracked ttl after a direct (non-tracker) renew, e.g. `POST /v1/leases/:id/renew`. */ - recordLeaseTtl(leaseId: string, ttlMs: number): void { - this.#leaseTtlMs.set(leaseId, ttlMs); - } - requestIdForLease(leaseId: string): string | undefined { return this.#leaseRequestId.get(leaseId); } - /** Drops the tracked ttl/request-id bookkeeping for a lease that just ended -- called from the - * HTTP app on the same owner-routed fact stream (`OwnerRoutedFacts`, `lease-lost`) - * `LeaseNoticeBuffer` consumes, not from a direct `eventBus.subscribe` on this class. */ + /** Drops the request-id bookkeeping for a lease that just ended -- called from the HTTP app + * on the same owner-routed fact stream (`OwnerRoutedFacts`, `lease-lost`) `LeaseNoticeBuffer` + * consumes, not from a direct `eventBus.subscribe` on this class. ADR 0004 left this map + * alone but deleted the per-lease TTL one that used to sit beside it: the width is on the + * lease record now, so there is nothing gateway-side left to forget about it. */ forgetLease(leaseId: string): void { this.#leaseRequestId.delete(leaseId); - this.#leaseTtlMs.delete(leaseId); } dispose(): void { @@ -413,15 +401,10 @@ export class LeaseRequestTracker { } } - #applyGrant(record: TrackedRequest, grant: HttpLeaseGrant, ttlMs: number | undefined): void { - const effectiveTtlMs = ttlMs ?? this.options.defaultTtlMs; + #applyGrant(record: TrackedRequest, grant: HttpLeaseGrant): void { this.#leaseRequestId.set(grant.lease.id, record.id); - this.#leaseTtlMs.set(grant.lease.id, effectiveTtlMs); this.#setState(record, { - lease: buildLeasePayload(grant.device, grant.lease, { - requestId: record.id, - ttlMs: effectiveTtlMs, - }), + lease: buildLeasePayload(grant.device, grant.lease, { requestId: record.id }), stage: "granted", }); } @@ -480,8 +463,8 @@ interface HttpLeaseDevice { interface HttpLeaseRecord { readonly id: string; readonly grantedAt: number; + readonly ttlMs: number; readonly ttlDeadline: number; - readonly mode?: "held" | "detached"; } interface HttpLeaseGrant { diff --git a/src/lease-policy/index.test.ts b/src/lease-policy/index.test.ts index f4eac5c9c..900b7f8f6 100644 --- a/src/lease-policy/index.test.ts +++ b/src/lease-policy/index.test.ts @@ -1,12 +1,13 @@ /** * 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()`. + * the lease's own `ttlMs`, bounded by the deadline the daemon returned, recomputed from every + * answer, 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 type { LeaseRenewal } from "./index.js"; import { awaitWithin, RELEASE_TIMEOUT_MS, startLeaseRenewal } from "./index.js"; /** Lets the awaited `renew` call settle; the fake clock never moves on its own. */ @@ -62,6 +63,121 @@ describe("startLeaseRenewal", () => { renewal.stop(); }); + it("takes the cadence from the lease's own width, not from the time left on the deadline", async () => { + // The two disagree on purpose: a third of the width is 20_000, a third of the remaining + // time is 30_000. ADR 0004 stores the width on the record precisely so a client can renew + // at the right *rate* without sharing a clock with the daemon, so the width is what the + // cadence follows -- and the deadline stays what it is, the bound. + const clock = new FakeClock(0); + const renewedAt: number[] = []; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + renew: () => { + renewedAt.push(clock.now()); + return Promise.resolve({ ttlMs: 60_000, ttlDeadline: clock.now() + 90_000 }); + }, + ttlMs: 60_000, + ttlDeadline: 90_000, + }); + + clock.advance(19_999); + await flushMicrotasks(); + expect(renewedAt).toEqual([]); + clock.advance(1); + await flushMicrotasks(); + expect(renewedAt).toEqual([20_000]); + + // And again off the answer's own width, not off its (further out) deadline. + clock.advance(20_000); + await flushMicrotasks(); + expect(renewedAt).toEqual([20_000, 40_000]); + }); + + it("clamps the cadence to the deadline when the width would overshoot it", async () => { + // A lease whose deadline is closer than its width -- a renewal that came back short, a + // clock that jumped -- must not sleep a full third of the width straight past the moment + // it is renewing towards. + const clock = new FakeClock(0); + const renewedAt: number[] = []; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + renew: () => { + renewedAt.push(clock.now()); + return Promise.resolve({ ttlMs: 60_000, ttlDeadline: clock.now() + 60_000 }); + }, + ttlMs: 60_000, + // 9_000 left, not 60_000: the first attempt is due at 3_000, well before it. + ttlDeadline: 9_000, + }); + + clock.advance(3_000); + await flushMicrotasks(); + expect(renewedAt).toEqual([3_000]); + + // Once the answer restores a full-width deadline, the width sets the pace again. + clock.advance(20_000); + await flushMicrotasks(); + expect(renewedAt).toEqual([3_000, 23_000]); + }); + + it("falls back to the remaining time when an answer carries no width", async () => { + // A caller with an older record shape (or a test double scripting one field) still gets + // the pre-width behaviour rather than no cadence at all. + const clock = new FakeClock(0); + const renewedAt: number[] = []; + startLeaseRenewal({ + clock, + leaseId: "lse_1", + renew: () => { + renewedAt.push(clock.now()); + return Promise.resolve({ ttlDeadline: clock.now() + 9_000 }); + }, + ttlDeadline: 9_000, + }); + + clock.advance(3_000); + await flushMicrotasks(); + expect(renewedAt).toEqual([3_000]); + clock.advance(3_000); + await flushMicrotasks(); + expect(renewedAt).toEqual([3_000, 6_000]); + }); + + it("says nothing more after a holder stops renewal from inside onError", async () => { + // A holder that hears a failed attempt and decides it is done with the lease (the CLI's + // `finally`, an MCP session ending) calls `stop()` from inside the handler. The very next + // line of `tick` would otherwise notice the deadline has passed and announce the lease + // gone -- news about a lease nobody is holding any more, delivered after the loop was + // promised to be silent. + const clock = new FakeClock(0); + const errors: unknown[] = []; + const gone: string[] = []; + const renewal: LeaseRenewal = startLeaseRenewal({ + clock, + leaseId: "lse_1", + onError: (error) => { + errors.push(error); + renewal.stop(); + }, + onLeaseGone: (reason) => gone.push(reason), + renew: () => Promise.reject(new Error("INTERNAL")), + // The first (and only) attempt is due at 250, exactly when the lease runs out: the + // rejection is reported, and the give-up test right after it would fire. + ttlDeadline: 250, + }); + + clock.advance(250); + await flushMicrotasks(); + + expect(errors).toHaveLength(1); + expect(gone, "stopped means stopped, including the ending it was about to announce").toEqual( + [], + ); + expect(clock.pendingTimerCount).toBe(0); + }); + it("stops cleanly: the pending timer is cancelled and no renewal follows", async () => { const clock = new FakeClock(0); let calls = 0; @@ -513,8 +629,9 @@ describe("startLeaseRenewal", () => { 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. + // A daemon answering with a deadline that is not in the future. `lease.defaultTtlMs` + // must be positive (ADR 0004), so this is a clock jump or a daemon bug rather than a + // configuration -- and either way a cadence derived from it would be a hot loop. return Promise.resolve({ ttlDeadline: clock.now() }); }, // Already expired at the grant: the floor keeps even this from being an instant loop. diff --git a/src/lease-policy/index.ts b/src/lease-policy/index.ts index 13cb2e398..7e967f50b 100644 --- a/src/lease-policy/index.ts +++ b/src/lease-policy/index.ts @@ -6,27 +6,30 @@ * 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 + * - the CLI's holder 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. + * Everything here comes from what the daemon actually answered -- the lease's own `ttlMs` and + * `ttlDeadline`, from the grant and from every renewal since -- never from a TTL config value: + * a client does not have the daemon's config, and the daemon is free to grant a narrower width + * than the one asked for. * - * Two things follow from deriving the interval as `ttlDeadline - clock.now()`: + * The two are used for different things, deliberately: * - * - 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. + * - **`ttlMs` sets the cadence**: renew every `ttlMs / 3`. It is a duration, so it needs no + * shared epoch, and a client whose clock sits minutes from the daemon's still renews at the + * right rate. That is what makes this loop correct across a network hop (ADR 0004's own + * reason for storing the width on the record), not just on the unix socket. + * - **`ttlDeadline` bounds it**: it is when this holder stops having a lease, so it caps each + * scheduled wait (never schedule past the moment being scheduled for) and it is what the + * give-up test reads. That one comparison is the only place a shared wall clock is assumed, + * and it fails safe in both directions -- a client running fast gives up early on a lease it + * could have kept, one running slow keeps trying against a lease the daemon has expired, + * and neither can extend a lease the daemon did not. */ import { isSimlockError } from "../contract/index.js"; import type { Clock, TimerHandle } from "../ports/index.js"; @@ -84,8 +87,14 @@ export async function awaitWithin( } } -/** The subset of a `LeaseRecord` renewal needs back: the daemon's new deadline. */ +/** + * The subset of a `LeaseRecord` renewal needs back: the width the lease now has, and when it + * ends. `ttlMs` is optional only so a caller with an older record shape (or a test double + * scripting one answer) still type-checks -- when it is absent the cadence falls back to the + * remaining time, which is what this module did before the width existed. + */ export interface RenewedLease { + readonly ttlMs?: number; readonly ttlDeadline: number; } @@ -106,8 +115,24 @@ export interface LeaseRenewalOptions { readonly leaseId: string; /** The deadline the grant (or a previous renewal) returned, in `clock.now()`'s epoch. */ readonly ttlDeadline: number; + /** The width the grant (or a previous renewal) returned -- `LeaseRecord.ttlMs`, the thing + * the cadence is a third of. Optional for the same reason it is optional on `RenewedLease`. */ + readonly ttlMs?: number; /** Calls `lease.renew` for this lease -- `client.renewLease({ leaseId })`, in practice. */ readonly renew: (leaseId: string) => Promise; + /** + * Reports each answer this renewal adopts, so a holder that shows the deadline to somebody + * can keep saying something true. The CLI's `DAEMON_CONNECTION_LOST` line names it, to say + * how long the lease that outlived the connection has left; without this hook that line + * would still quote the grant-time deadline, which after roughly one TTL of uptime is a + * moment in the past on a lease that is perfectly alive. + * + * Called on every adopted answer -- which is every answer from the newest attempt, and whose + * deadline may be equal to or *earlier* than the previous one, since the daemon's newest + * word wins in both directions (a body-less renew re-applying a narrower stored width, say). + * Never called after `stop()`. + */ + readonly onRenewed?: (renewed: RenewedLease) => void; /** * 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` @@ -135,9 +160,16 @@ export interface LeaseRenewal { 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)); +/** + * The delay before the next renewal: a third of the lease's own width, clamped so an attempt + * still starts before the deadline it is renewing towards. The clamp matters whenever the two + * disagree -- a lease renewed to a shorter deadline than its width (a daemon restart mid-TTL, + * a clock that jumped), where scheduling a full `ttlMs / 3` would sleep straight past the + * moment the lease ends. + */ +function renewDelayMs(remainingMs: number, ttlMs: number | undefined): number { + const fromWidth = ttlMs === undefined ? remainingMs : Math.min(ttlMs, remainingMs); + const delay = Math.max(MINIMUM_RENEW_DELAY_MS, Math.floor(fromWidth / RENEW_DIVISOR)); return Math.min(MAXIMUM_RENEW_DELAY_MS, delay); } @@ -178,9 +210,11 @@ function isLeaseGone(error: unknown): boolean { * 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. */ + const { clock, leaseId, onError, onLeaseGone, onRenewed, renew } = options; + /** The last deadline the daemon actually gave us: the bound this renewal races. */ let deadline = options.ttlDeadline; + /** The lease's own width, as of the same answer: what the cadence is derived from. */ + let ttlMs = options.ttlMs; /** Whichever timer is armed right now: the wait between renewals, or an attempt's bound. */ let timer: TimerHandle | undefined; let stopped = false; @@ -205,9 +239,17 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { // it -- see the `void tick()` below, which nothing awaits. } }; - /** Ends renewal and says why, once. Isolated for the same reason `report` is. */ + /** + * Ends renewal and says why, once. Isolated for the same reason `report` is, and silent once + * renewal has stopped for any other reason -- including a `stop()` the holder made from + * inside `onError` a moment ago, which is a holder saying it is done with this lease and + * must not be answered with news about it. Cancels the armed timer for the same reason + * `stop()` does: this is the end of the loop, and nothing may outlive it. + */ const giveUp = (reason: LeaseGoneReason, error: unknown): void => { + if (stopped) return; stopped = true; + cancelTimer(); if (onLeaseGone === undefined) return; try { onLeaseGone(reason, error); @@ -216,9 +258,23 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { } }; + /** The one place `deadline` moves, so `onRenewed` can never drift from what the cadence + * itself is scheduling against. Callers apply the newest-answer-wins rule before calling it; + * this only records the answer and reports it, isolated for the same reason `report` is. */ + const adoptDeadline = (renewed: RenewedLease): void => { + deadline = renewed.ttlDeadline; + ttlMs = renewed.ttlMs; + if (onRenewed === undefined) return; + try { + onRenewed(renewed); + } catch { + // A holder that cannot record the new deadline must still keep renewing towards it. + } + }; + const schedule = (): void => { if (stopped) return; - timer = clock.setTimer(renewDelayMs(deadline - clock.now()), () => { + timer = clock.setTimer(renewDelayMs(deadline - clock.now(), ttlMs), () => { timer = undefined; // Nothing awaits this: an unhandled rejection here would take the whole process down, // and with it the release the holder still owes. @@ -253,7 +309,7 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { // deadline the daemon has already replaced. if (stopped || attemptId <= newestAnswered) return; newestAnswered = attemptId; - deadline = renewed.ttlDeadline; + adoptDeadline(renewed); }, () => undefined, ); @@ -263,7 +319,7 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { (error: unknown) => ({ attemptId, error, ok: false }), ), new Promise((resolve) => { - timer = clock.setTimer(renewDelayMs(deadline - clock.now()), () => { + timer = clock.setTimer(renewDelayMs(deadline - clock.now(), ttlMs), () => { timer = undefined; resolve({ attemptId, @@ -305,10 +361,11 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { } // 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). + // has usually already done it for this very answer; both paths agree, and both go through + // `adoptDeadline`, so `onRenewed` sees each adopted answer exactly once). if (attempt.attemptId > newestAnswered) { newestAnswered = attempt.attemptId; - deadline = attempt.renewed.ttlDeadline; + adoptDeadline(attempt.renewed); } if (attempt.renewed.ttlDeadline <= clock.now()) { // A deadline that is not in the future cannot be renewed towards -- scheduling off it @@ -320,8 +377,8 @@ export function startLeaseRenewal(options: LeaseRenewalOptions): LeaseRenewal { 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. + // *shorter* deadline than the one asked for -- a body-less renew re-applying a narrower + // stored width, say -- and a longer, older belief does not override it. schedule(); }; diff --git a/src/mcp/connect.ts b/src/mcp/connect.ts index 4e32392c5..0e3898c20 100644 --- a/src/mcp/connect.ts +++ b/src/mcp/connect.ts @@ -16,16 +16,19 @@ import { } from "../client/index.js"; import { IpcError, type Clock, type DaemonLauncher, type IpcConnector } from "../ports/index.js"; -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; +/** What it takes to reach a daemon that is already listening -- no launcher anywhere in it, + * which is the whole point of the type existing separately. The `heartbeat` option that used + * to sit here is gone with the daemon's push (ADR 0004 §4). */ +export interface ConnectToRunningDaemonOptions { readonly ipc: IpcConnector; - readonly launcher: DaemonLauncher; readonly principal: string; - readonly retryIntervalMs?: number; readonly socketPath: string; +} + +export interface ConnectWithAutoLaunchOptions extends ConnectToRunningDaemonOptions { + readonly clock: Clock; + readonly launcher: DaemonLauncher; + readonly retryIntervalMs?: number; readonly startupTimeoutMs?: number; } @@ -40,7 +43,7 @@ export async function connectWithAutoLaunch( options: ConnectWithAutoLaunchOptions, ): Promise { try { - return await attempt(options); + return await connectToRunningDaemon(options); } catch (error: unknown) { if (!isUnavailable(error)) throw error; } @@ -49,7 +52,7 @@ export async function connectWithAutoLaunch( let lastError: unknown; while (options.clock.now() < deadline) { try { - return await attempt(options); + return await connectToRunningDaemon(options); } catch (error: unknown) { if (!isUnavailable(error)) throw error; lastError = error; @@ -64,12 +67,22 @@ export async function connectWithAutoLaunch( ); } -function attempt(options: ConnectWithAutoLaunchOptions): Promise { +/** + * Connects only to a daemon that is already listening, and never launches one -- which is + * exactly `connectWithAutoLaunch` minus its one extra power, so the latter is written in terms + * of this rather than beside it. + * + * ADR 0004 §2 gives it a caller of its own: the session's renew timer. An idle session should + * not lose its lease waiting for a tool call that may never come, but an operator's `simlock + * daemon stop` must not be undone by that same idle session -- so auto-launch stays a tool-call + * concern, and a lease held across a stopped daemon expires unless the daemon is back before + * its deadline. + */ +export function connectToRunningDaemon( + options: ConnectToRunningDaemonOptions, +): Promise { return connectSimlock({ endpoint: options.socketPath, - // 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/contracts.test.ts b/src/mcp/contracts.test.ts index a379cbe6d..6697afe17 100644 --- a/src/mcp/contracts.test.ts +++ b/src/mcp/contracts.test.ts @@ -17,19 +17,41 @@ describe("MCP contracts", () => { }); }); - it("rejects requesterId, mode, and ttlMs -- those are the session's job, not the caller's", () => { - for (const extra of [{ requesterId: "someone-else" }, { mode: "detached" }, { ttlMs: 1_000 }]) { - expect(() => - leaseSimulatorInputSchema.parse({ model: "iPhone 17 Pro", platform: "ios", ...extra }), - ).toThrow(); - } + it("rejects requesterId -- the session's identity is not the caller's to name", () => { + expect(() => + leaseSimulatorInputSchema.parse({ + model: "iPhone 17 Pro", + platform: "ios", + requesterId: "someone-else", + }), + ).toThrow(); }); - it("is the same schema the contract validates lease.request input against, minus those fields", () => { - const full = OPERATIONS["lease.request"].input.innerType(); + it("rejects mode, which ADR 0004 removed from the contract entirely", () => { + expect(() => + leaseSimulatorInputSchema.parse({ + model: "iPhone 17 Pro", + platform: "ios", + mode: "detached", + }), + ).toThrow(); + }); + + it("accepts ttlMs, which ADR 0004 allows on every lease request", () => { + expect( + leaseSimulatorInputSchema.parse({ + model: "iPhone 17 Pro", + platform: "ios", + ttlMs: 1_000, + }), + ).toEqual({ model: "iPhone 17 Pro", platform: "ios", ttlMs: 1_000 }); + }); + + it("is the same schema the contract validates lease.request input against, minus requesterId", () => { + const full = OPERATIONS["lease.request"].input; expect(Object.keys(leaseSimulatorInputSchema.shape).sort()).toEqual( Object.keys(full.shape) - .filter((key) => !["mode", "requesterId", "ttlMs"].includes(key)) + .filter((key) => key !== "requesterId") .sort(), ); }); @@ -49,9 +71,10 @@ describe("MCP contracts", () => { deviceId: "device-1", grantedAt: 0, id: "lease-1", - mode: "held", + lastRenewedAt: 0, ownerId: "mcp:1", requesterId: "mcp:1", + ttlMs: 60_000, ttlDeadline: 61_000, }, timing: { diff --git a/src/mcp/contracts.ts b/src/mcp/contracts.ts index 29d804608..3c98149aa 100644 --- a/src/mcp/contracts.ts +++ b/src/mcp/contracts.ts @@ -18,17 +18,17 @@ import { leaseRecordSchema, OPERATIONS } from "../contract/index.js"; // ---- lease_simulator --------------------------------------------------------------------- /** - * `lease.request`'s input, minus the three fields this tool never lets the caller set: - * `requesterId` (session-controlled -- see `session.ts`'s `#requesterId`, never caller-supplied, - * for the same reason the daemon never lets a request rename its own principal), `mode` (this - * tool always leases `"held"`), and `ttlMs` (only meaningful for a detached lease, which this - * tool never requests -- and is `BAD_REQUEST` for a held one per the contract's own - * `superRefine`). `.innerType()` unwraps the contract schema's `superRefine` wrapper down to - * the plain (still `.strict()`) object so `.omit()` is available -- see zod's `ZodEffects`. + * `lease.request`'s input, minus the one field this tool never lets the caller set: + * `requesterId` (session-controlled -- see `main.ts`'s requester resolution, never + * caller-supplied, for the same reason the daemon never lets a request rename its own + * principal). `ttlMs` is no longer omitted: ADR 0004 accepts it on every request, so this tool + * inherits it from the contract like every other field -- `lease.defaultTtlMs` when the caller + * names none, `BAD_REQUEST` above `lease.maxTtlMs`. `mode` is gone from the contract itself, + * and with it the `superRefine` wrapper that used to need unwrapping before `.omit()`. */ -export const leaseSimulatorInputSchema = OPERATIONS["lease.request"].input - .innerType() - .omit({ mode: true, requesterId: true, ttlMs: true }); +export const leaseSimulatorInputSchema = OPERATIONS["lease.request"].input.omit({ + requesterId: true, +}); /** `lease.request`'s output verbatim -- the device/lease/timing grant. */ export const leaseSimulatorOutputSchema = OPERATIONS["lease.request"].output; @@ -57,9 +57,10 @@ export const leaseStatusInputSchema = OPERATIONS["lease.list"].input; * principal only -- it can include leases this session never requested (see * `McpSession#status`'s doc comment). `session.ts` narrows that array down to at most one * entry -- the lease this session's own `lease()` call obtained, if any -- before this schema - * flattens it onto a `held` discriminant. Flat and all-optional -- not a discriminated union -- - * because the MCP SDK validates `structuredContent` against `outputSchema` as a plain object - * shape. + * flattens it onto a `held` discriminant. `held` is this tool's own word for "the lease this + * session is renewing", not a daemon-side lease mode; there is only one kind of lease (ADR + * 0004). Flat and all-optional -- not a discriminated union -- because the MCP SDK validates + * `structuredContent` against `outputSchema` as a plain object shape. */ export const leaseStatusOutputSchema = leaseRecordSchema.partial().extend({ held: z.boolean() }); diff --git a/src/mcp/main.test.ts b/src/mcp/main.test.ts index 8acdff2a5..929c395b6 100644 --- a/src/mcp/main.test.ts +++ b/src/mcp/main.test.ts @@ -4,11 +4,15 @@ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js"; import { describe, expect, it, vi } from "vitest"; +import { FakeClock } from "../ports/index.js"; import { FakeSimlockClient, sampleGrant } from "./test-support.js"; import { startMcpStdio, type McpTransport } from "./main.js"; -const { connectWithAutoLaunch } = vi.hoisted(() => ({ connectWithAutoLaunch: vi.fn() })); -vi.mock("./connect.js", () => ({ connectWithAutoLaunch })); +const { connectToRunningDaemon, connectWithAutoLaunch } = vi.hoisted(() => ({ + connectToRunningDaemon: vi.fn(), + connectWithAutoLaunch: vi.fn(), +})); +vi.mock("./connect.js", () => ({ connectToRunningDaemon, connectWithAutoLaunch })); describe("MCP stdio lifecycle", () => { it.each(["transport", "SIGINT", "SIGTERM"])("closes once on %s", async (cause) => { @@ -95,6 +99,55 @@ describe("MCP stdio lifecycle", () => { await mcpClient.close(); }); + it("never renews over an embedder's connect, which may launch a daemon", async () => { + // ADR 0004 §2: the renew timer reaches only a daemon that is already listening, so an + // operator's `simlock daemon stop` is not undone by an idle session. An embedder that + // supplies just `connect` must therefore get the non-launching default for renewals rather + // than a second use of the one it supplied -- there is no way to tell whether *that* one + // launches anything. + const clock = new FakeClock(0); + const toolCallClient = new FakeSimlockClient(); + toolCallClient.requestLeaseImpl = () => Promise.resolve(sampleGrant()); + const renewClient = new FakeSimlockClient(); + renewClient.renewLeaseImpl = (input) => + Promise.resolve({ ...sampleGrant().lease, id: input.leaseId }); + renewClient.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); + connectToRunningDaemon.mockReset().mockResolvedValue(renewClient); + let embedderConnects = 0; + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const runner = await startMcpStdio({ + clock, + connect: async () => { + embedderConnects += 1; + return toolCallClient; + }, + createTransport: () => serverTransport, + requesterId: "mcp-test", + signals: new FakeSignals(), + }); + const mcpClient = new Client({ name: "test", version: "1.0.0" }); + await mcpClient.connect(clientTransport); + await mcpClient.request( + { + method: "tools/call", + params: { arguments: { model: "iPhone", platform: "ios" }, name: "lease_simulator" }, + }, + CallToolResultSchema, + ); + + // The connection dies with no tool call in sight, and the renew timer comes due. + toolCallClient.emitConnectionLost(); + clock.advance(4_115); + for (let index = 0; index < 10; index += 1) await Promise.resolve(); + + expect(embedderConnects, "the timer did not reach for the connect it was not given").toBe(1); + expect(connectToRunningDaemon).toHaveBeenCalledTimes(1); + expect(renewClient.calls.map((call) => call.method)).toEqual(["renewLease"]); + + await mcpClient.close(); + await runner.shutdown(); + }); + it("sources the connection principal from SIMLOCK_AGENT_ID when no requesterId is given explicitly", async () => { connectWithAutoLaunch.mockReset().mockResolvedValue(new FakeSimlockClient()); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); diff --git a/src/mcp/main.ts b/src/mcp/main.ts index 002f176e4..3eddacc38 100644 --- a/src/mcp/main.ts +++ b/src/mcp/main.ts @@ -12,7 +12,7 @@ import { SystemClock, type Clock, } from "../ports/index.js"; -import { connectWithAutoLaunch } from "./connect.js"; +import { connectToRunningDaemon, connectWithAutoLaunch } from "./connect.js"; import { McpSession } from "./session.js"; import { createMcpServer } from "./server.js"; @@ -37,6 +37,10 @@ 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; + /** The renew timer's connect (ADR 0004 §2) -- never launches a daemon. Falls back only to + * the non-launching default, never to `connect`, so injecting `connect` alone cannot hand + * the timer an auto-launching path; a test that wants both usually injects both. */ + readonly connectForRenew?: () => Promise; readonly createServer?: (session: McpSession) => McpServer; readonly createTransport?: () => McpTransport; /** Source for `SIMLOCK_AGENT_ID` when `requesterId` is not given explicitly. */ @@ -75,6 +79,10 @@ export async function startMcpStdio( const session = new McpSession({ clock, connect: environment.connect ?? defaults.connect, + // Never falls back to `connect`: that one may auto-launch a daemon, and ADR 0004 §2 is + // explicit that the renew timer must not -- an embedder supplying only `connect` gets the + // non-launching default rather than a timer that could undo an operator's `daemon stop`. + connectForRenew: environment.connectForRenew ?? defaults.connectForRenew, }); const server = (environment.createServer ?? createMcpServer)(session); const transport = (environment.createTransport ?? defaults.createTransport)(); @@ -148,19 +156,18 @@ export async function startMcpStdio( function defaultEnvironment( requesterId: string, clock: Clock, -): Required> { +): Required> { const dataDirectory = resolveSimlockHome(); const ipc = new NodeIpcTransport(); const logPath = join(dataDirectory, "daemon.log"); return { + // The tool-call trigger: auto-launches a daemon that is not running, exactly as the CLI + // does. 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 + // declares no daemon-initiated heartbeat -- there is none left to declare. connect: () => connectWithAutoLaunch({ clock, - // 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")], @@ -175,6 +182,10 @@ function defaultEnvironment( // trace on the stdio channel an MCP client is trying to speak protocol over. socketPath: resolveDaemonSocketPath(dataDirectory), }), + // The renew timer's trigger: connects to a daemon that is already listening and never + // launches one, so an operator's `simlock daemon stop` is not undone by an idle session + // (ADR 0004 §2). + connectForRenew: () => connectToRunningDaemon({ ipc, principal: requesterId, socketPath }), createTransport: () => new StdioServerTransport(), }; } diff --git a/src/mcp/server.test.ts b/src/mcp/server.test.ts index 1c9be32da..f7316c1f4 100644 --- a/src/mcp/server.test.ts +++ b/src/mcp/server.test.ts @@ -43,9 +43,10 @@ describe("MCP server (smoke)", () => { deviceId: grant.device.id, grantedAt: grant.lease.grantedAt, id: grant.lease.id, - mode: grant.lease.mode, ownerId: grant.lease.ownerId, requesterId: grant.lease.requesterId, + lastRenewedAt: grant.lease.grantedAt, + ttlMs: 60_000, ttlDeadline: grant.lease.ttlDeadline, }, ], @@ -70,7 +71,7 @@ describe("MCP server (smoke)", () => { platform: "ios", }); expect(lease.isError).not.toBe(true); - expect(lease.structuredContent).toMatchObject({ lease: { id: "lease-1", mode: "held" } }); + expect(lease.structuredContent).toMatchObject({ lease: { id: "lease-1" } }); const devices = await call(mcpClient, "list_devices", {}); expect(devices.isError).not.toBe(true); @@ -293,7 +294,11 @@ describe("MCP server (smoke)", () => { }); async function connectedServer(client: FakeSimlockClient) { - const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); + const session = new McpSession({ + clock: new FakeClock(), + connect: async () => client, + connectForRenew: 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 69cfc8d6e..69c1b4e02 100644 --- a/src/mcp/session.test.ts +++ b/src/mcp/session.test.ts @@ -22,7 +22,11 @@ describe("McpSession", () => { seenOptions = options; return Promise.resolve(grant); }; - const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); + const session = new McpSession({ + clock: new FakeClock(), + connect: async () => client, + connectForRenew: async () => client, + }); const signal = new AbortController().signal; const onProgress = () => undefined; @@ -33,7 +37,7 @@ describe("McpSession", () => { ); expect(result).toBe(grant); - expect(seenInput).toEqual({ model: "iPhone 17 Pro", mode: "held", platform: "ios" }); + expect(seenInput).toEqual({ model: "iPhone 17 Pro", platform: "ios" }); expect(seenOptions).toEqual({ onProgress, signal }); }); @@ -41,7 +45,11 @@ describe("McpSession", () => { const client = new FakeSimlockClient(); client.releaseLeaseImpl = () => Promise.reject(new SimlockError("FORBIDDEN", "protocol", "not your lease", {})); - const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); + const session = new McpSession({ + clock: new FakeClock(), + connect: async () => client, + connectForRenew: async () => client, + }); await expect(session.release({ leaseId: "someone-elses-lease" })).rejects.toMatchObject({ code: "FORBIDDEN", @@ -54,7 +62,11 @@ 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({ clock: new FakeClock(), connect: async () => client }); + const session = new McpSession({ + clock: new FakeClock(), + connect: async () => client, + connectForRenew: async () => client, + }); await expect(session.release({ leaseId: "lease-1" })).resolves.toEqual({ leaseId: "lease-1", @@ -65,7 +77,11 @@ describe("McpSession", () => { it("forwards list_devices straight to getCatalog", async () => { const client = new FakeSimlockClient(); client.getCatalogImpl = () => Promise.resolve({ platforms: [] }); - const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); + const session = new McpSession({ + clock: new FakeClock(), + connect: async () => client, + connectForRenew: async () => client, + }); await session.listDevices({ platform: "ios" }); expect(client.calls).toEqual([{ input: { platform: "ios" }, method: "getCatalog" }]); @@ -86,16 +102,21 @@ describe("McpSession", () => { deviceId: "device-1", grantedAt: 0, id: "lease-1", - mode: "held" as const, ownerId: "mcp-test", requesterId: "mcp-test", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 5_000, }, ], }, ); }; - const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); + const session = new McpSession({ + clock: new FakeClock(), + connect: async () => client, + connectForRenew: async () => client, + }); await expect(session.status()).resolves.toEqual({ held: false }); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); @@ -104,9 +125,10 @@ describe("McpSession", () => { grantedAt: 0, held: true, id: "lease-1", - mode: "held", ownerId: "mcp-test", requesterId: "mcp-test", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 5_000, }); expect(client.calls.filter((c) => c.method === "listLeases")).toHaveLength(2); @@ -125,14 +147,19 @@ describe("McpSession", () => { deviceId: "device-9", grantedAt: 0, id: "lse_foreign", - mode: "detached" as const, ownerId: "mcp-test", requesterId: "mcp-test", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 99_999, }, ], }); - const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); + const session = new McpSession({ + clock: new FakeClock(), + connect: async () => client, + connectForRenew: async () => client, + }); await expect(session.status()).resolves.toEqual({ held: false }); }); @@ -147,14 +174,19 @@ describe("McpSession", () => { deviceId: "device-1", grantedAt: 0, id: "lease-1", - mode: "held" as const, ownerId: "mcp-test", requesterId: "mcp-test", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 5_000, }, ], }); - const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); + const session = new McpSession({ + clock: new FakeClock(), + connect: async () => client, + connectForRenew: async () => client, + }); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); await expect(session.status()).resolves.toMatchObject({ held: true, id: "lease-1" }); @@ -173,7 +205,7 @@ describe("McpSession", () => { clients.push(client); return client; }; - const session = new McpSession({ clock: new FakeClock(), connect }); + const session = new McpSession({ clock: new FakeClock(), connect, connectForRenew: connect }); await session.listDevices({}); await session.listDevices({}); @@ -200,7 +232,11 @@ describe("McpSession", () => { order.push("release"); return Promise.resolve({ leaseId: input.leaseId }); }; - const session = new McpSession({ clock: new FakeClock(), connect: async () => client }); + const session = new McpSession({ + clock: new FakeClock(), + connect: async () => client, + connectForRenew: async () => client, + }); const leaseCall = session.lease({ model: "iPhone 17 Pro", platform: "ios" }); const releaseCall = session.release({ leaseId: "lease-1" }); @@ -217,7 +253,11 @@ describe("McpSession", () => { const pendingClient = new Promise((resolve) => { resolveConnect = resolve; }); - const session = new McpSession({ clock: new FakeClock(), connect: () => pendingClient }); + const session = new McpSession({ + clock: new FakeClock(), + connect: () => pendingClient, + connectForRenew: () => pendingClient, + }); const listDevicesCall = session.listDevices({}); await Promise.resolve(); // let the queued mutation reach #clientForUse() and start connecting @@ -236,7 +276,11 @@ 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({ clock: new FakeClock(), connect: async () => client }); + const session = new McpSession({ + clock: new FakeClock(), + connect: async () => client, + connectForRenew: async () => client, + }); await session.close(); await expect(session.lease({ model: "x", platform: "ios" })).rejects.toMatchObject({ @@ -265,13 +309,18 @@ describe("McpSession", () => { deviceId: "device-1", grantedAt: 0, id: input.leaseId, - mode: "held" as const, ownerId: "mcp-test", requesterId: "mcp-test", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: clock.now() + 3_000, }); }; - const session = new McpSession({ clock, connect: async () => client }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: 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" }); @@ -291,12 +340,54 @@ describe("McpSession", () => { await session.close(); }); + it("renews on the lease's own width, not on the time left to its deadline", async () => { + // The session passes `ttlMs` as well as `ttlDeadline` (see `startLeaseRenewal`): the width + // sets the cadence, the deadline only bounds it. A lease granted narrow against a distant + // deadline is where the two visibly differ -- 10_000 apart, not 100_000. + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + const grant = sampleGrant({ leaseId: "lease-1" }); + client.requestLeaseImpl = () => + Promise.resolve({ + ...grant, + lease: { ...grant.lease, ttlDeadline: 300_000, ttlMs: 30_000 }, + }); + const renewedAt: number[] = []; + client.renewLeaseImpl = (input) => { + renewedAt.push(clock.now()); + return Promise.resolve({ + ...grant.lease, + id: input.leaseId, + lastRenewedAt: clock.now(), + ttlDeadline: clock.now() + 300_000, + ttlMs: 30_000, + }); + }; + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + clock.advance(10_000); + await flushMicrotasks(); + expect(renewedAt).toEqual([10_000]); + + client.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); + 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 }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); await session.close(); @@ -313,7 +404,11 @@ describe("McpSession", () => { 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 }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); await expect(session.close()).resolves.toBeUndefined(); @@ -325,7 +420,11 @@ describe("McpSession", () => { 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 }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); await session.release({ leaseId: "lease-1" }); @@ -351,14 +450,19 @@ describe("McpSession", () => { deviceId: "device-1", grantedAt: 0, id: input.leaseId, - mode: "held" as const, + lastRenewedAt: clock.now(), ownerId: "mcp-test", requesterId: "mcp-test", + ttlMs: 12_345, ttlDeadline: clock.now() + 12_345, }); }; client.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); - const session = new McpSession({ clock, connect: async () => client }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: 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 @@ -389,7 +493,11 @@ describe("McpSession", () => { new Promise<{ leaseId: string }>((resolve) => { pending.push(resolve); }); - const session = new McpSession({ clock, connect: async () => client }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: 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 @@ -421,7 +529,11 @@ describe("McpSession", () => { // would follow it ever comes back. client.listLeasesImpl = () => new Promise(() => {}); client.releaseLeaseImpl = () => new Promise(() => {}); - const session = new McpSession({ clock, connect: async () => client }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); void session.status().catch(() => undefined); // in flight, never answered await flushMicrotasks(); @@ -445,6 +557,46 @@ describe("McpSession", () => { expect(clock.pendingTimerCount).toBe(0); }); + it("stops releasing when the shutdown budget runs out, rather than calling a closed client", async () => { + // `awaitWithin` stops *waiting*; it cannot stop the loop it was waiting on. Without a + // check the abandoned loop would carry on down the remaining leases against the client the + // `finally` has already closed -- one rejection per lease, after the session was over. + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + let granted = 0; + client.requestLeaseImpl = () => { + granted += 1; + return Promise.resolve(sampleGrant({ leaseId: `lease-${String(granted)}` })); + }; + let answerFirstRelease!: (result: { leaseId: string }) => void; + client.releaseLeaseImpl = (input) => + input.leaseId === "lease-1" + ? new Promise((resolve) => { + answerFirstRelease = resolve; + }) + : Promise.resolve({ leaseId: input.leaseId }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + const closing = session.close(); + await flushMicrotasks(); + clock.advance(RELEASE_TIMEOUT_MS); + await closing; + expect(client.closeCalls).toBe(1); + + // The first release finally answers, long after the budget was spent. The loop is over. + answerFirstRelease({ leaseId: "lease-1" }); + await flushMicrotasks(); + expect(client.calls.filter((call) => call.method === "releaseLease")).toEqual([ + { input: { leaseId: "lease-1" }, method: "releaseLease" }, + ]); + }); + 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(); @@ -454,7 +606,11 @@ describe("McpSession", () => { answerGrant = resolve; }); client.releaseLeaseImpl = (input) => Promise.resolve({ leaseId: input.leaseId }); - const session = new McpSession({ clock, connect: async () => client }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); const leasing = session.lease({ model: "iPhone 17 Pro", platform: "ios" }); await flushMicrotasks(); @@ -476,6 +632,123 @@ describe("McpSession", () => { expect(clock.pendingTimerCount, "a closed session must leave no timer behind").toBe(0); }); + it("stops renewing before it asks to release, so a renew cannot overtake the answer", async () => { + // ADR 0003 §8: `onLeaseLost` never fires for a release this same client asked for. A timer + // left armed across an in-flight release breaks that -- the renew lands after + // `Registry#beginRelease` has dropped the record, comes back UNKNOWN_LEASE, and renewal + // reports the agent's own release to it as a lost device. Ordering hides it on a unix + // socket; a gateway hop (ADR 0003 §12) would not. + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + let answerRelease!: (result: { leaseId: string }) => void; + client.releaseLeaseImpl = () => + new Promise((resolve) => { + answerRelease = resolve; + }); + client.renewLeaseImpl = () => + Promise.reject( + new SimlockError("UNKNOWN_LEASE", "domain", "no such lease", { leaseId: "lease-1" }), + ); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); + const notices: unknown[] = []; + session.onLeaseLost((notice) => notices.push(notice)); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + const releasing = session.release({ leaseId: "lease-1" }); + await flushMicrotasks(); + + // The daemon has the release and has not answered yet. This is exactly the window a renew + // would land in -- and there is no timer left to send one. + expect(clock.pendingTimerCount).toBe(0); + clock.advance(600_000); + await flushMicrotasks(); + expect(client.calls.filter((call) => call.method === "renewLease")).toEqual([]); + + answerRelease({ leaseId: "lease-1" }); + await expect(releasing).resolves.toEqual({ leaseId: "lease-1", released: true }); + expect(notices, "the agent asked for this; it is not news of a lost device").toEqual([]); + + await session.close(); + }); + + it("does not put the timer back for a lease that was lost while the release was in flight", async () => { + // A failed release usually means the session still holds the device, so the timer goes + // back. Not here: the daemon ended this lease (an expiry, an operator) while the release + // was on the wire, so there is nothing left to renew and the retry would run a ladder + // against a record that no longer exists. + const clock = new FakeClock(0); + const client = new FakeSimlockClient(); + client.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + let failRelease!: (error: unknown) => void; + client.releaseLeaseImpl = () => + new Promise((_resolve, reject) => { + failRelease = reject; + }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); + const notices: unknown[] = []; + session.onLeaseLost((notice) => notices.push(notice)); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + const releasing = session.release({ leaseId: "lease-1" }); + await flushMicrotasks(); + client.emitLeaseLost({ deviceId: "device-1", leaseId: "lease-1", reason: "expired" }); + + // Transient on its face -- the daemon may serve the next one -- but the lease it was about + // is gone regardless. + failRelease(new SimlockError("INTERNAL", "domain", "could not release", {})); + await expect(releasing).rejects.toMatchObject({ code: "INTERNAL" }); + + expect(clock.pendingTimerCount).toBe(0); + clock.advance(600_000); + await flushMicrotasks(); + expect(client.calls.filter((call) => call.method === "renewLease")).toEqual([]); + expect(notices).toEqual([{ deviceId: "device-1", leaseId: "lease-1", reason: "expired" }]); + + await session.close(); + }); + + it("leaves the timer stopped when the release fails because the lease is already gone", async () => { + // The other side of restarting a stopped timer: an UNKNOWN_LEASE means there is nothing + // left to renew, so putting the timer back would only produce the same answer on a ladder + // until the deadline -- and announce it as a lease lost. + 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", "no such lease", { leaseId: "lease-1" }), + ); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); + const notices: unknown[] = []; + session.onLeaseLost((notice) => notices.push(notice)); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + + await expect(session.release({ leaseId: "lease-1" })).rejects.toMatchObject({ + code: "UNKNOWN_LEASE", + }); + + expect(clock.pendingTimerCount).toBe(0); + clock.advance(600_000); + await flushMicrotasks(); + expect(client.calls.filter((call) => call.method === "renewLease")).toEqual([]); + expect(notices).toEqual([]); + + await session.close(); + }); + it("keeps renewing when a release fails, because the session still holds the device", async () => { const clock = new FakeClock(0); const client = new FakeSimlockClient(); @@ -489,13 +762,18 @@ describe("McpSession", () => { deviceId: "device-1", grantedAt: 0, id: input.leaseId, - mode: "held" as const, ownerId: "mcp-test", requesterId: "mcp-test", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: clock.now() + 12_000, }); }; - const session = new McpSession({ clock, connect: async () => client }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); await expect(session.release({ leaseId: "lease-1" })).rejects.toMatchObject({ @@ -519,7 +797,11 @@ describe("McpSession", () => { Promise.reject( new SimlockError("UNKNOWN_LEASE", "domain", "no such lease", { leaseId: "lease-1" }), ); - const session = new McpSession({ clock, connect: async () => client }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); const notices: unknown[] = []; session.onLeaseLost((notice) => notices.push(notice)); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); @@ -546,7 +828,11 @@ describe("McpSession", () => { // 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 session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); const notices: unknown[] = []; session.onLeaseLost((notice) => notices.push(notice)); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); @@ -574,7 +860,11 @@ describe("McpSession", () => { Promise.reject( new SimlockError("UNKNOWN_LEASE", "domain", "no such lease", { leaseId: "lease-1" }), ); - const session = new McpSession({ clock, connect: async () => client }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); const notices: unknown[] = []; session.onLeaseLost((notice) => notices.push(notice)); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); @@ -592,11 +882,192 @@ describe("McpSession", () => { await session.close(); }); + it("renews over connectForRenew after a dead connection, and never over connect", async () => { + // ADR 0004 §2's named safety property: the renew timer reconnects so an idle session does + // not lose its lease waiting for a tool call, but it reaches only a daemon that is already + // listening. `connect` is the trigger that may auto-launch one, so an operator's `simlock + // daemon stop` staying done depends on the timer never reaching for it. + const clock = new FakeClock(0); + const first = new FakeSimlockClient(); + first.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + const second = new FakeSimlockClient(); + second.renewLeaseImpl = (input) => + Promise.resolve({ + deviceId: "device-1", + grantedAt: 0, + id: input.leaseId, + lastRenewedAt: clock.now(), + ownerId: "agent-1", + requesterId: "agent-1", + ttlMs: 1_000, + ttlDeadline: clock.now() + 1_000, + }); + + let toolCallConnects = 0; + let renewConnects = 0; + const session = new McpSession({ + clock, + connect: async () => { + toolCallConnects += 1; + // Reached a second time only by a timer taking the launching path -- which would be + // the bug, so it fails loudly here rather than quietly handing back a client. + if (toolCallConnects > 1) throw new Error("the renew timer reached the launching connect"); + return first; + }, + connectForRenew: async () => { + renewConnects += 1; + return second; + }, + }); + const notices: unknown[] = []; + session.onLeaseLost((notice) => notices.push(notice)); + + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + expect(toolCallConnects).toBe(1); + expect(renewConnects).toBe(0); + + // The connection under the session dies with no tool call in sight. + first.emitConnectionLost(); + + // The renew tick fires against it: one reconnect, through the non-launching path only. + clock.advance(4_115); + await flushMicrotasks(); + expect(renewConnects).toBe(1); + expect(toolCallConnects).toBe(1); + expect(second.calls.map((call) => call.method)).toEqual(["renewLease"]); + + // And the session listens to the connection it just built, not only to the one it started + // with: a lease-lost over the new wire is the agent's only warning that the device is + // gone, and a session that forgot to re-wire would sit silent through it. + second.emitLeaseLost({ deviceId: "device-1", leaseId: "lease-1", reason: "expired" }); + expect(notices).toEqual([{ deviceId: "device-1", leaseId: "lease-1", reason: "expired" }]); + + await session.close(); + }); + + it("retries alone with the launching connect when a tool call joined a renew's attempt", async () => { + // `docs/CLI.md` and `docs/CLIENT.md` promise a tool call may start a daemon that is not + // running. Sharing `#connecting` with the renew timer is free in the other direction, but + // here it would hand the tool call the timer's weaker attempt -- and "nothing is + // listening" for something it was allowed to fix. + const clock = new FakeClock(0); + const first = new FakeSimlockClient(); + first.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + const second = new FakeSimlockClient(); + second.getCatalogImpl = () => Promise.resolve({ platforms: [] }); + let toolCallConnects = 0; + let failRenewConnect!: (error: unknown) => void; + const session = new McpSession({ + clock, + connect: async () => { + toolCallConnects += 1; + return toolCallConnects === 1 ? first : second; + }, + connectForRenew: () => + new Promise((_resolve, reject) => { + failRenewConnect = reject; + }), + }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + first.emitConnectionLost(); + + // The renew timer starts a connect that cannot launch anything, and a tool call arrives + // while it is still in flight and joins it. + clock.advance(4_115); + await flushMicrotasks(); + const listing = session.listDevices({}); + await flushMicrotasks(); + expect(toolCallConnects).toBe(1); + + // Nothing is listening, so that attempt fails -- for the timer, which will try again on + // its own cadence, and for the tool call, which instead tries once more with the connect + // that may start a daemon. + failRenewConnect( + new SimlockError("DAEMON_CONNECTION_LOST", "transport", "nothing is listening", {}), + ); + + await expect(listing).resolves.toEqual({ platforms: [] }); + expect(toolCallConnects, "the tool call's own attempt, made alone").toBe(2); + + await session.close(); + }); + + it("lets a renew tick share a tool call's connect, which is the direction that costs nothing", async () => { + // The timer wanted a connection and got one. That the tool call was going to launch a + // daemon anyway is the tool call's business, not the timer's doing -- so this direction + // stays shared, and the session ends up with one connection rather than two. + const clock = new FakeClock(0); + const first = new FakeSimlockClient(); + first.requestLeaseImpl = () => Promise.resolve(sampleGrant({ leaseId: "lease-1" })); + const second = new FakeSimlockClient(); + second.getCatalogImpl = () => Promise.resolve({ platforms: [] }); + second.renewLeaseImpl = (input) => + Promise.resolve({ + deviceId: "device-1", + grantedAt: 0, + id: input.leaseId, + lastRenewedAt: clock.now(), + ownerId: "mcp-test", + requesterId: "mcp-test", + ttlMs: 60_000, + ttlDeadline: clock.now() + 60_000, + }); + let toolCallConnects = 0; + let renewConnects = 0; + let answerToolCallConnect!: (client: FakeSimlockClient) => void; + const session = new McpSession({ + clock, + connect: () => { + toolCallConnects += 1; + if (toolCallConnects === 1) return Promise.resolve(first); + return new Promise((resolve) => { + answerToolCallConnect = resolve; + }); + }, + connectForRenew: async () => { + renewConnects += 1; + return second; + }, + }); + await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); + first.emitConnectionLost(); + + // A tool call reconnects first, and is still waiting when the renew tick comes due. + const listing = session.listDevices({}); + await flushMicrotasks(); + expect(toolCallConnects).toBe(2); + clock.advance(4_115); + await flushMicrotasks(); + expect(renewConnects, "it joined the attempt already in flight").toBe(0); + + answerToolCallConnect(second); + await expect(listing).resolves.toEqual({ platforms: [] }); + await flushMicrotasks(); + + expect(renewConnects).toBe(0); + expect(toolCallConnects).toBe(2); + expect(second.calls.filter((call) => call.method === "renewLease")).toHaveLength(1); + + // Both callers came back holding this client, and exactly one of them may wire it up: a + // second set of push relays would strand the first (only the latest can be unsubscribed), + // and every push would reach the agent twice for one thing that happened. + const deviceHealth: unknown[] = []; + session.onDeviceHealth((notice) => deviceHealth.push(notice)); + second.emitDeviceUnhealthy({ deviceId: "device-1", leaseId: "lease-1" }); + expect(deviceHealth).toHaveLength(1); + + 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 }); + const session = new McpSession({ + clock, + connect: async () => client, + connectForRenew: async () => client, + }); await session.lease({ model: "iPhone 17 Pro", platform: "ios" }); client.emitLeaseLost({ deviceId: "device-1", leaseId: "lease-1", reason: "expired" }); @@ -611,10 +1082,54 @@ describe("McpSession", () => { expect(client.calls.filter((call) => call.method === "releaseLease")).toEqual([]); }); + it("remembers the endings it announced up to a cap, dropping the oldest first", async () => { + // The dedupe memory of a long-lived session cannot grow without bound. It is a fixed + // window over the most recent endings, which is where duplicates actually live: a + // renewal's answer and the daemon's push about one lease arrive moments apart, never + // dozens of leases later. + const client = new FakeSimlockClient(); + client.getCatalogImpl = () => Promise.resolve({ platforms: [] }); + const session = new McpSession({ + clock: new FakeClock(), + connect: async () => client, + connectForRenew: async () => client, + }); + await session.listDevices({}); // wires the push relays up + const notices: Array<{ leaseId: string }> = []; + session.onLeaseLost((notice) => notices.push(notice)); + + // One past the cap, so the very first id has been dropped by the end of it. + const announced = 65; + for (let index = 0; index < announced; index += 1) { + client.emitLeaseLost({ + deviceId: "device-1", + leaseId: `lease-${String(index)}`, + reason: "expired", + }); + } + expect(notices).toHaveLength(announced); + + // The newest endings still dedupe, which is the whole point of remembering them. + client.emitLeaseLost({ deviceId: "device-1", leaseId: "lease-64", reason: "expired" }); + expect(notices).toHaveLength(announced); + + // The oldest has aged out of the window, so its duplicate -- if one ever came, long after + // everything else -- would be announced again. That is the trade the cap makes. + client.emitLeaseLost({ deviceId: "device-1", leaseId: "lease-0", reason: "expired" }); + expect(notices).toHaveLength(announced + 1); + expect(notices.at(-1)?.leaseId).toBe("lease-0"); + + await session.close(); + }); + 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({ clock: new FakeClock(), connect: async () => client }); + const session = new McpSession({ + clock: new FakeClock(), + connect: async () => client, + connectForRenew: async () => client, + }); await session.listDevices({}); // forces the client to connect and wire up push relays const leaseLost: unknown[] = []; @@ -655,22 +1170,57 @@ describe("toMcpErrorResult", () => { * 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 () => { + it("answers before it is closed", 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", }); + }); + + /** + * Every operation, not a sample of them: a fake that guards two methods and forgets a third + * lets a test pass on the one call the real session makes over a wire it has already closed. + * Each entry stubs its own implementation so a rejection can only be the dead guard's, never + * `notStubbed`'s. + */ + it.each([ + ["getCatalog", (client: FakeSimlockClient) => client.getCatalog({})], + ["getStatus", (client: FakeSimlockClient) => client.getStatus()], + [ + "requestLease", + (client: FakeSimlockClient) => + client.requestLease({ model: "iPhone 17 Pro", platform: "ios" }), + ], + ["cancelLease", (client: FakeSimlockClient) => client.cancelLease({})], + ["renewLease", (client: FakeSimlockClient) => client.renewLease({ leaseId: "lease-1" })], + ["releaseLease", (client: FakeSimlockClient) => client.releaseLease({ leaseId: "lease-1" })], + ["listLeases", (client: FakeSimlockClient) => client.listLeases()], + ["runDoctor", (client: FakeSimlockClient) => client.runDoctor({})], + [ + "resolvePassthrough", + (client: FakeSimlockClient) => client.resolvePassthrough({ args: ["devices"], tool: "adb" }), + ], + ] as const)("rejects %s once closed, the way the wire does", async (_method, call) => { + const client = new FakeSimlockClient(); + client.getCatalogImpl = () => Promise.resolve({ platforms: [] }); + client.getStatusImpl = notReached; + client.requestLeaseImpl = notReached; + client.cancelLeaseImpl = notReached; + client.renewLeaseImpl = notReached; + client.releaseLeaseImpl = notReached; + client.listLeasesImpl = notReached; + client.runDoctorImpl = notReached; + client.resolvePassthroughImpl = notReached; 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", - }); + await expect(call(client)).rejects.toMatchObject({ code: "DAEMON_CONNECTION_LOST" }); }); }); + +/** Any stub reached after `close()` is the guard failing, so every one of them says so. */ +function notReached(): never { + throw new Error("the fake answered a call over a closed connection"); +} diff --git a/src/mcp/session.ts b/src/mcp/session.ts index a825fce7e..c07fc1402 100644 --- a/src/mcp/session.ts +++ b/src/mcp/session.ts @@ -38,11 +38,20 @@ export interface McpSessionOptions { 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 - * reusing or repairing the dead one -- on lazy reconnect: the typed client "does not - * reconnect and does not retry" (ADR §10), so that policy has to live here. + * for the connection's lifetime (ADR 0003 §4). Called again -- building a brand new client, + * never reusing or repairing the dead one -- on reconnect: the typed client "does not + * reconnect and does not retry" (ADR §10), so that policy has to live here. This is the + * tool-call trigger, and it may auto-launch a daemon that is not running. */ readonly connect: () => Promise; + /** + * The renew timer's own connect (ADR 0004 §2): same handshake, but it only ever reaches a + * daemon that is **already listening** and never launches one. An idle session should not + * lose its lease waiting for a tool call that may never come; an operator's `simlock daemon + * stop` must not be undone by that same idle session. Both are true only because the two + * triggers have deliberately different powers -- see `#renewHeldLease`. + */ + readonly connectForRenew: () => Promise; } export interface McpErrorResult { @@ -112,11 +121,23 @@ export function toMcpErrorResult(error: unknown): McpErrorResult { * 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. */ +/** One lease this session holds: its live renew timer, and the freshest record it renewed to. */ +interface HeldLease { + readonly renewal: LeaseRenewal; + lease: LeaseRecord; +} + export class McpSession { readonly #clock: Clock; readonly #connect: () => Promise; + readonly #connectForRenew: () => Promise; #client: SimlockClient | undefined; #connecting: Promise | undefined; + /** Whether `#connecting` was started by the auto-launching `connect` (a tool call) or by the + * non-launching `connectForRenew` (the renew timer). A tool call that joined the weaker one + * has to be able to tell, so it can still exercise the power it was promised -- see + * `#clientForUse`. */ + #connectingCanLaunch = false; #closed = false; readonly #closedClients = new Set(); #closePromise: Promise | undefined; @@ -136,8 +157,12 @@ export class McpSession { * 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. + * + * Each entry keeps the lease record its timer is renewing, refreshed from every renewal, so + * a timer stopped for a release that then failed can be started again against the lease as + * it actually stands rather than as it stood at grant time -- see `release()`. */ - readonly #renewals = new Map(); + readonly #renewals = new Map(); /** Lease ids already announced as lost, so one ending never reaches a listener twice -- see * `#announceLeaseLost`. */ readonly #announcedLost = new Set(); @@ -145,6 +170,7 @@ export class McpSession { constructor(options: McpSessionOptions) { this.#clock = options.clock; this.#connect = options.connect; + this.#connectForRenew = options.connectForRenew; } lease( @@ -155,7 +181,9 @@ export class McpSession { return this.#mutate(async () => { this.#throwIfClosed(); const client = await this.#clientForUse(); - const request: LeaseRequestInput = { ...input, mode: "held" }; + // ADR 0004: no `mode` to ask for, and `ttlMs` (if the caller named one) travels through + // from the tool's contract-derived schema untouched. + const request: LeaseRequestInput = { ...input }; const grant = await client.requestLease(request, { ...(onProgress === undefined ? {} : { onProgress }), ...(signal === undefined ? {} : { signal }), @@ -166,11 +194,14 @@ export class McpSession { // 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); + // Inside `#endSession`'s budget (`close()` waits on this call), so it needs no bound + // of its own -- and must not add one: a nested timer would only extend the wait an + // ending session already bounds. + await client.releaseLease({ leaseId: grant.lease.id }).catch(() => undefined); this.#throwIfClosed(); } this.#heldLeaseId = grant.lease.id; - this.#startRenewal(client, grant.lease); + this.#startRenewal(grant.lease); return grant; }); } @@ -179,13 +210,40 @@ export class McpSession { return this.#mutate(async () => { this.#throwIfClosed(); const client = await this.#clientForUse(); - const result = await client.releaseLease(input); - // Stopped only once the daemon has actually let the lease go. A release that fails - // (anything but a dead connection) leaves the session still holding the device, and a - // session that has stopped renewing a lease it still holds loses that device at the - // deadline. A renew that overtakes a *successful* release cannot resurrect anything: - // `Registry#beginRelease` drops the record, so `lease.renew` can only answer - // UNKNOWN_LEASE. + // Stopped *before* the release is sent, not after it answers. A renew dispatched into + // the same window lands after `Registry#beginRelease` has dropped the record and comes + // back `UNKNOWN_LEASE` -- a terminal answer, so `onLeaseGone` would announce a + // `lease-lost` for the very release this agent asked for, which ADR 0003 §8 says must + // never happen. Today the two answers arrive in an order that hides it; a gateway hop + // (ADR 0003 §12) would not be so kind. + const held = this.#renewals.get(input.leaseId); + // Only the timer stops; the lease stays this session's until the daemon answers. That is + // what keeps `close()`'s farewell release owed for a release still in flight (see + // `close()`), which is the difference between one duplicate `UNKNOWN_LEASE` and a device + // nobody hands back. + held?.renewal.stop(); + let result; + try { + result = await client.releaseLease(input); + } catch (error: unknown) { + // The daemon did not take the lease: this session is still holding the device, and a + // holder that has stopped renewing loses it at the deadline. So the timer goes back -- + // unless the lease is not this session's any more. That is the answers where there is + // nothing left to renew (`UNKNOWN_LEASE`, or `FORBIDDEN` for a lease that was never + // ours) and a dead connection, where the agent has asked to be rid of this lease and + // reconnecting a timer to keep it alive would be the opposite of what it asked; and it + // is also a `lease-lost` push that arrived while the release was in flight, which drops + // the lease from `#renewals` -- restarting on that would renew towards a lease the + // daemon has already ended. + if (held !== undefined) { + if (endsRenewal(error) || !this.#renewals.has(input.leaseId)) { + this.#forgetLease(input.leaseId); + } else { + this.#startRenewal(held.lease); + } + } + throw error; + } this.#forgetLease(result.leaseId); return { ...result, released: true }; }); @@ -201,24 +259,22 @@ export class McpSession { /** * This session's current lease, or an explicit "no lease held" result -- one `lease.list` - * call (ADR §9), never a cache of lease state. `lease.list` filters by **owner principal - * only** (no mode filter, no connection filter -- see `src/daemon/dispatcher.ts`'s - * `lease.list` handler), so it can return leases this connection never requested: a - * `detached` lease the CLI holds under the same `SIMLOCK_AGENT_ID` principal, or a stale - * `held` lease left over from an earlier session under that principal. Taking `leases[0]` - * unconditionally would report a lease this session neither holds nor will release on close. - * Filtering to `mode === "held"` **and** `id === #heldLeaseId` scopes the answer to the one - * lease this session's own `lease()` call actually obtained; `leases` itself is always - * re-fetched, never cached. + * call (ADR 0003 §9), never a cache of lease state. `lease.list` filters by **owner principal + * only** (see `src/daemon/dispatcher.ts`'s `lease.list` handler), so it can return leases + * this connection never requested: one a `simlock lease --detach` left behind under the same + * `SIMLOCK_AGENT_ID` principal, or one left over from an earlier session under that + * principal. Taking `leases[0]` unconditionally would report a lease this session neither + * renews nor will release on close. Matching on `id === #heldLeaseId` scopes the answer to + * the one lease this session's own `lease()` call actually obtained -- the only filter left, + * since ADR 0004 removed the `mode` the old one also checked, and the only one that was ever + * load-bearing anyway. `leases` itself is always re-fetched, never cached. */ status(): Promise { return this.#mutate(async () => { this.#throwIfClosed(); const client = await this.#clientForUse(); const { leases } = await client.listLeases(); - const lease = leases.find((candidate) => { - return candidate.mode === "held" && candidate.id === this.#heldLeaseId; - }); + const lease = leases.find((candidate) => candidate.id === this.#heldLeaseId); return lease === undefined ? { held: false } : { ...lease, held: true }; }); } @@ -241,8 +297,8 @@ export class McpSession { /** * 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. + * its own call rather than a side effect of the socket going away: nothing else will free the + * device before its deadline. * * 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 @@ -250,6 +306,11 @@ export class McpSession { * 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. + * + * With no client at all -- the connection died and `#wireClient` cleared it -- there is + * nothing to release and nothing is reconnected to try: ADR 0004 §3 leaves those leases + * granted and counting down, and an ending session is the one moment it is right to let them + * run out rather than reach for one more connection on the way out. */ close(): Promise { if (this.#closePromise !== undefined) return this.#closePromise; @@ -287,6 +348,10 @@ export class McpSession { heldLeaseIds: readonly string[], inFlight: Promise, ): Promise { + // `awaitWithin` stops *waiting* on the budget; it cannot stop the work. Without this the + // abandoned loop would go on calling `releaseLease` on a client the `finally` has closed, + // one rejection per remaining lease, after the session was supposed to be over. + let budgetSpent = false; try { await awaitWithin( this.#clock, @@ -295,6 +360,7 @@ export class McpSession { // `#mutations` never rejects (see `#mutate`), but a caller-supplied queue might. await inFlight.catch(() => undefined); for (const leaseId of heldLeaseIds) { + if (budgetSpent) return; // One lease the daemon refuses (already expired, force-released) must not cost the // rest of them their release. await client.releaseLease({ leaseId }).catch(() => undefined); @@ -304,42 +370,18 @@ export class McpSession { ); } catch { // Bounded by design -- see above. + budgetSpent = true; } 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. + * Starts (or restarts) the renew timer for one lease this session obtained. No client is + * captured: each tick resolves one through `#renewHeldLease`, so a connection that died + * between ticks costs the lease nothing (ADR 0004 §2) instead of ending its renewal. */ - 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 { + #startRenewal(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 @@ -348,6 +390,18 @@ export class McpSession { const renewal = startLeaseRenewal({ clock: this.#clock, leaseId: lease.id, + // Keeps the record this session would restart renewal from in step with the daemon's + // newest answer: a restart (see `release()`) must not renew towards a deadline and a + // width the lease has not had for hours. + onRenewed: (renewed) => { + const held = this.#renewals.get(lease.id); + if (held === undefined) return; + held.lease = { + ...held.lease, + ttlDeadline: renewed.ttlDeadline, + ...(renewed.ttlMs === undefined ? {} : { ttlMs: renewed.ttlMs }), + }; + }, 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 @@ -355,10 +409,26 @@ export class McpSession { // 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 }), + renew: (id) => this.#renewHeldLease(id), + // The width drives the cadence, the deadline bounds it -- see `startLeaseRenewal`. ttlDeadline: lease.ttlDeadline, + ttlMs: lease.ttlMs, }); - this.#renewals.set(lease.id, renewal); + this.#renewals.set(lease.id, { lease, renewal }); + } + + /** + * One renewal, against whatever connection this session has -- reconnecting first if the + * current one died (ADR 0004 §2's second reconnect trigger). It connects only to a daemon + * that is already listening: an idle session keeps its lease across a daemon it can still + * reach, and an operator's `simlock daemon stop` is not undone by one that it cannot. A + * failure here is not fatal to the lease; `startLeaseRenewal` retries on the next tick, with + * the whole remaining TTL as its runway -- except for the one failure that is fatal, which + * `onLeaseGone` handles above. + */ + async #renewHeldLease(leaseId: string): Promise<{ readonly ttlDeadline: number }> { + const client = await this.#clientForUse(this.#connectForRenew); + return client.renewLease({ leaseId }); } /** @@ -394,12 +464,12 @@ export class McpSession { /** Stops and forgets one lease's renew timer. */ #stopRenewal(leaseId: string): void { - this.#renewals.get(leaseId)?.stop(); + this.#renewals.get(leaseId)?.renewal.stop(); this.#renewals.delete(leaseId); } #stopAllRenewals(): void { - for (const renewal of this.#renewals.values()) renewal.stop(); + for (const held of this.#renewals.values()) held.renewal.stop(); this.#renewals.clear(); } @@ -416,53 +486,86 @@ export class McpSession { /** * 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 - * client itself never reconnects (ADR §10), so constructing a fresh one here on every dead - * connection is what keeps MCP's process-outlives-a-connection lifecycle working. + * makes the next caller build a brand new `SimlockClient` -- the typed client itself never + * reconnects (ADR 0003 §10), so constructing a fresh one here on every dead connection is + * what keeps MCP's process-outlives-a-connection lifecycle working. + * + * Which `connect` runs is the caller's decision, and ADR 0004 §2 makes it a meaningful one: a + * tool call passes the auto-launching one (the default), the renew timer passes the one that + * only reaches an already-listening daemon. The two share `#connecting` so a race produces + * one connection rather than two -- but only in the direction where sharing costs nothing. + * A renew tick joining a tool call's connect is fine: it wanted a connection, and gets one + * (the tool call was going to launch a daemon either way, which is not the timer's doing). A + * tool call joining a *renew's* connect is not: `docs/CLIENT.md` and `docs/CLI.md` promise a + * tool call may start a daemon that is not running, and it would instead fail with the + * weaker attempt. So it retries once, alone, with the launching connect -- which is exactly + * what it would have done had it arrived a moment later. */ - async #clientForUse(): Promise { + async #clientForUse( + connect: () => Promise = this.#connect, + ): Promise { if (this.#client !== undefined) return this.#client; - this.#connecting ??= this.#connect(); + const canLaunch = connect === this.#connect; + if (this.#connecting === undefined) { + this.#connecting = connect(); + this.#connectingCanLaunch = canLaunch; + } const connecting = this.#connecting; + const joinedWeakerAttempt = canLaunch && !this.#connectingCanLaunch; try { - const client = await connecting; - if (this.#closed) { - await this.#closeClient(client); - this.#throwIfClosed(); - } - this.#client = client; - this.#wireClient(client); - return client; + return await this.#adoptClient(await connecting); } catch (error: unknown) { this.#throwIfClosed(); - // `#connect` is expected to reject with a `SimlockError` (the real implementation always - // does -- see `main.ts`'s `connectWithAutoLaunch`), but this is a defensive fallback for - // any other injected `connect` so a caller never sees a bare, un-coded exception. - throw isSimlockError(error) - ? error - : new SimlockError( - "DAEMON_CONNECTION_LOST", - "transport", - error instanceof Error ? error.message : String(error), - {}, - ); + // The attempt this caller joined could not launch a daemon and this caller may: try + // again on its own terms rather than reporting "nothing is listening" to a tool call + // that is allowed to fix that. Only in this direction -- and the failed attempt is + // cleared first (whichever joined caller's `finally` has not run yet would only clear + // it again, harmlessly) so the retry starts a connection rather than re-joining the one + // that just failed. + if (joinedWeakerAttempt) { + if (this.#connecting === connecting) this.#connecting = undefined; + return this.#clientForUse(connect); + } + throw asSimlockError(error); } finally { if (this.#connecting === connecting) this.#connecting = undefined; } } + /** + * Takes ownership of a freshly-connected client: it becomes this session's, and its pushes + * start reaching this session's listeners. A session that closed while the connection was + * being made takes ownership of nothing -- it closes the client instead, so a connection + * built for a session that no longer exists cannot outlive it. + */ + async #adoptClient(client: SimlockClient): Promise { + if (this.#closed) { + await this.#closeClient(client); + this.#throwIfClosed(); + } + // Every caller that shared `#connecting` arrives here with the same client, and only the + // first of them may wire it: a second `#wireClient` would strand the first set of + // unsubscribers (`#unwireClient` only knows the latest), leaving two live relays for one + // connection and an agent reading every push twice. + if (this.#client === client) return client; + this.#client = client; + this.#wireClient(client); + return client; + } + /** * Relays a freshly-connected client's pushes to this session's own listeners (which survive * across a reconnect, unlike the client itself), and drops `#client` the moment this - * connection dies so the next call reconnects. The client already synthesizes `onLeaseLost` - * for every lease it held when its connection dies (ADR §10), so nothing extra is needed - * here for that case. + * connection dies so the next caller reconnects. A dead connection is deliberately *not* + * treated as a lost lease (ADR 0004 §3, which is why the client no longer synthesizes one): + * the lease is still granted, and the renew timer picks it back up over the next connection. */ #wireClient(client: SimlockClient): void { this.#clientUnsubscribers = [ client.onLeaseLost((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). + // Nothing left to renew for that lease: the daemon ended it (expiry, or a + // force-release). A dead connection is not one of those any more -- ADR 0004 §3, which + // is why the client no longer synthesizes a push for it. this.#stopRenewal(push.leaseId); if (this.#heldLeaseId === push.leaseId) this.#heldLeaseId = undefined; this.#announceLeaseLost(push); @@ -522,3 +625,34 @@ export class McpSession { } function noop(): void {} + +/** + * `#connect` is expected to reject with a `SimlockError` (the real implementation always does + * -- see `main.ts`'s `connectWithAutoLaunch`); this is the defensive fallback for any other + * injected `connect`, so a caller never sees a bare, un-coded exception. + */ +function asSimlockError(error: unknown): unknown { + return isSimlockError(error) + ? error + : new SimlockError( + "DAEMON_CONNECTION_LOST", + "transport", + error instanceof Error ? error.message : String(error), + {}, + ); +} + +/** + * Whether a failed `lease.release` is a reason to leave the lease's renew timer stopped: the + * lease is already gone or was never this principal's, or the connection carrying the answer + * died. Anything else (an `INTERNAL` the daemon may serve on the next try, say) leaves a lease + * this session still holds and still has to keep alive. + */ +function endsRenewal(error: unknown): boolean { + return ( + isSimlockError(error) && + (error.code === "UNKNOWN_LEASE" || + error.code === "FORBIDDEN" || + error.code === "DAEMON_CONNECTION_LOST") + ); +} diff --git a/src/mcp/test-support.ts b/src/mcp/test-support.ts index 312461c0f..3a6732769 100644 --- a/src/mcp/test-support.ts +++ b/src/mcp/test-support.ts @@ -16,7 +16,6 @@ import { type LeaseCancelInput, type LeaseCancelOutput, type LeaseGrant, - type LeaseHeartbeatOutput, type LeaseListOutput, type LeaseLostPush, type LeaseReleaseInput, @@ -67,7 +66,6 @@ export class FakeSimlockClient implements SimlockClient { releaseLeaseImpl: (input: LeaseReleaseInput) => Promise = notStubbed("releaseLease"); listLeasesImpl: () => Promise = notStubbed("listLeases"); - heartbeatImpl: () => Promise = notStubbed("heartbeat"); runDoctorImpl: (input: DoctorRunInput) => Promise = notStubbed("runDoctor"); resolvePassthroughImpl: (input: DriverPassthroughInput) => Promise = notStubbed("resolvePassthrough"); @@ -120,12 +118,6 @@ export class FakeSimlockClient implements SimlockClient { 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.#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" }); @@ -211,9 +203,10 @@ export function sampleGrant(overrides: { readonly leaseId?: string } = {}): Leas deviceId: "device-1", grantedAt: 0, id: leaseId, - mode: "held", ownerId: "mcp-test", requesterId: "mcp-test", + lastRenewedAt: 0, + ttlMs: 60_000, ttlDeadline: 12_345, }, timing: { diff --git a/src/simlock-client/client.test.ts b/src/simlock-client/client.test.ts index a878b51b7..ce48d5c41 100644 --- a/src/simlock-client/client.test.ts +++ b/src/simlock-client/client.test.ts @@ -10,11 +10,7 @@ async function flushMicrotasks(times = 10): Promise { } function sampleGrant( - overrides: { - readonly leaseId?: string; - readonly deviceId?: string; - readonly mode?: "held" | "detached"; - } = {}, + overrides: { readonly leaseId?: string; readonly deviceId?: string } = {}, ): LeaseGrant { const leaseId = overrides.leaseId ?? "lease_1"; const deviceId = overrides.deviceId ?? "device_1"; @@ -29,9 +25,10 @@ function sampleGrant( deviceId, grantedAt: 0, id: leaseId, - mode: overrides.mode ?? "held", + lastRenewedAt: 0, ownerId: "agent-1", requesterId: "agent-1", + ttlMs: 1_000, ttlDeadline: 1_000, }, timing: { @@ -105,16 +102,14 @@ 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 () => { + it("declares no capabilities at all, 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, - }); + // ADR 0004 §4 removed the daemon-initiated heartbeat and the capability that gated it; + // a lease stays alive because a client calls `lease.renew`, and nothing else. + expect((hello.payload as { capabilities?: unknown }).capabilities).toBeUndefined(); completeHello(connection); const client = await connectPromise; @@ -125,18 +120,6 @@ describe("connectSimlock: handshake", () => { 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" }); @@ -217,7 +200,7 @@ describe("connectSimlock: handshake", () => { }); describe("connection death", () => { - it("rejects in-flight calls and fires onLeaseLost for held leases", async () => { + it("rejects in-flight calls, fires onConnectionLost, and reports no lost lease", async () => { const connection = new ScriptedConnection(); const connectPromise = connectSimlock({ connection }); await flushMicrotasks(); @@ -241,11 +224,11 @@ describe("connection death", () => { connection.simulateDeath(); await expect(statusPromise).rejects.toMatchObject({ code: "DAEMON_CONNECTION_LOST" }); - expect(leaseLost).toHaveBeenCalledWith({ - deviceId: "device_1", - leaseId: "lease_held", - reason: "daemon-connection-lost", - }); + // ADR 0004 §3 narrows ADR 0003 §10: a dead connection is not a dead lease. The daemon + // released nothing, so `lease_held` is still granted and still counting down -- there is + // nothing to report through `onLeaseLost`, which now only ever carries a lease the daemon + // actually ended. + expect(leaseLost).not.toHaveBeenCalled(); expect(connectionLost).toHaveBeenCalledTimes(1); await expect(client.getStatus()).rejects.toMatchObject({ code: "DAEMON_CONNECTION_LOST" }); @@ -450,19 +433,20 @@ describe("pushes", () => { }); }); - it("answers a lease.heartbeat push with a fire-and-forget request frame carrying the same payload", async () => { + it("ignores an unknown push kind such as a protocol-3 daemon's lease.heartbeat", async () => { const connection = new ScriptedConnection(); const connectPromise = connectSimlock({ connection }); await flushMicrotasks(); completeHello(connection); - await connectPromise; + const client = await connectPromise; + // Not reachable against a protocol-4 daemon (the ranges do not overlap, so `hello` fails + // first), but the wire must not answer a push it no longer understands. connection.push("lease.heartbeat", { nonce: 12345 }); await flushMicrotasks(); - const pong = connection.lastSentOf("lease.heartbeat")!; - expect(pong).toBeDefined(); - expect(pong.payload).toEqual({ nonce: 12345 }); + expect(connection.lastSentOf("lease.heartbeat")).toBeUndefined(); + await client.close(); }); it("silently drops malformed lease-scoped and event pushes instead of throwing", async () => { diff --git a/src/simlock-client/client.ts b/src/simlock-client/client.ts index 15c24274b..ddb03af19 100644 --- a/src/simlock-client/client.ts +++ b/src/simlock-client/client.ts @@ -43,7 +43,6 @@ import type { LeaseCancelOutput, PassthroughCommand, LeaseGrant, - LeaseHeartbeatOutput, LeaseListOutput, LeaseLostPush, LeaseProgress, @@ -86,7 +85,6 @@ export type { LeaseCancelInput, LeaseCancelOutput, LeaseGrant, - LeaseHeartbeatOutput, LeaseListOutput, LeaseLostPush, LeaseProgress, @@ -132,16 +130,6 @@ 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 `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; } /** The full agent-visible method surface (ADR §3's operation matrix, `agent` rows) plus the @@ -159,18 +147,24 @@ export interface SimlockClient { renewLease(input: LeaseRenewInput): Promise; releaseLease(input: LeaseReleaseInput): Promise; listLeases(): Promise; - heartbeat(): Promise; runDoctor(input?: DoctorRunInput): Promise; /** Resolves the scoped command behind `simlock simctl` / `simlock adb` (ADR 0001, decision * 7). Resolution only -- the caller is the process with a terminal, so it runs it. */ resolvePassthrough(input: DriverPassthroughInput): Promise; + /** + * Reports a lease the *daemon* ended -- an expiry, an operator release, an unrecoverable + * device. ADR 0004 §3 narrows ADR 0003 §10 here: a dead connection is not a dead lease, so + * this no longer fires with a synthesized `daemon-connection-lost` when the socket dies. The + * leases this client held are still granted and still counting down; `onConnectionLost` is + * what reports the connection, and reconnecting and renewing is the frontend's call. + */ onLeaseLost(listener: (push: LeaseLostPush) => void): () => void; onDeviceUnhealthy(listener: (push: DeviceUnhealthyPush) => void): () => void; onDeviceRecovered(listener: (push: DeviceRecoveredPush) => void): () => void; /** Fires exactly once, when the connection dies for any reason (including a deliberate - * `close()`). Every in-flight call has already rejected `DAEMON_CONNECTION_LOST` and every - * `onLeaseLost` for a held lease has already fired by the time this listener runs. */ + * `close()`). Every in-flight call has already rejected `DAEMON_CONNECTION_LOST` by the time + * this listener runs. Any lease this client was holding is still alive on the daemon. */ onConnectionLost(listener: (error: AnySimlockError) => void): () => void; close(): Promise; @@ -218,7 +212,6 @@ export async function connectSimlockClient( hello = await wire.hello({ ...(options.principal === undefined ? {} : { principal: options.principal }), ...(options.credential === undefined ? {} : { credential: options.credential }), - capabilities: { heartbeat: options.heartbeat ?? false }, }); } catch (error: unknown) { // ADR §6: a `PROTOCOL_VERSION_UNSUPPORTED` `hello` rejection is the one handshake failure @@ -274,7 +267,6 @@ function buildDegradedClient( renewLease: () => rejected(), releaseLease: () => rejected(), listLeases: () => rejected(), - heartbeat: () => rejected(), runDoctor: () => rejected(), resolvePassthrough: () => rejected(), @@ -334,12 +326,12 @@ async function resolveConnection(options: ConnectOptions): Promise(); // leaseId -> deviceId readonly #leaseLostListeners = new Set<(push: LeaseLostPush) => void>(); readonly #deviceUnhealthyListeners = new Set<(push: DeviceUnhealthyPush) => void>(); readonly #deviceRecoveredListeners = new Set<(push: DeviceRecoveredPush) => void>(); @@ -383,10 +375,9 @@ class SimlockClientImpl { if (signal?.aborted === true) throw cancelledError(); - const requestPromise = this.#callRaw("lease.request", parsed, onProgress).then((grant) => { - this.#trackGrant(grant as LeaseGrant); - return grant as LeaseGrant; - }); + const requestPromise = this.#callRaw("lease.request", parsed, onProgress).then( + (grant) => grant as LeaseGrant, + ); if (signal === undefined) return requestPromise; return this.#requestLeaseWithAbort(requestPromise, signal, requesterId); @@ -404,19 +395,13 @@ class SimlockClientImpl { const parsed = this.#parseInput("lease.release", input); // The daemon suppresses the matching `lease-lost` push to this connection itself (ADR // §8) -- see the comment on `SimlockWire`'s `#deliveredLeaseLost`. Nothing to mark here. - const result = await this.#call("lease.release", parsed); - this.#heldLeaseIds.delete(parsed.leaseId); - return result; + return this.#call("lease.release", parsed); } listLeases(): Promise { return this.#call("lease.list", {}); } - heartbeat(): Promise { - return this.#call("lease.heartbeat", {}); - } - runDoctor(input: DoctorRunInput = {}): Promise { return this.#call("doctor.run", input); } @@ -452,10 +437,7 @@ class SimlockClientImpl { // ---- admin-only operations ------------------------------------------------------------------ releaseAllLeases(): Promise { - return this.#call("lease.release-all", {}).then((result) => { - this.#heldLeaseIds.clear(); - return result; - }); + return this.#call("lease.release-all", {}); } list(input: ListGetInput = {}): Promise { @@ -611,7 +593,6 @@ class SimlockClientImpl { #handleLeaseScopedPush(push: LeaseScopedPush): void { switch (push.kind) { case "lease-lost": - this.#heldLeaseIds.delete(push.leaseId); for (const listener of this.#leaseLostListeners) { listener({ deviceId: push.deviceId, leaseId: push.leaseId, reason: push.reason }); } @@ -629,21 +610,16 @@ class SimlockClientImpl { } } + /** + * ADR 0004 §3: a dead connection ends no lease, so nothing is synthesized here. The daemon + * releases nothing on close, so every lease this client was holding is still granted, still + * counting down its own TTL, and still renewable by whatever connects next -- which is the + * frontend's decision to make, not this client's (ADR 0003 §10). + */ #handleConnectionLost(error: AnySimlockError): void { - const held = [...this.#heldLeaseIds.entries()]; - this.#heldLeaseIds.clear(); - for (const [leaseId, deviceId] of held) { - for (const listener of this.#leaseLostListeners) { - listener({ deviceId, leaseId, reason: "daemon-connection-lost" }); - } - } for (const listener of this.#connectionLostListeners) listener(error); } - #trackGrant(grant: LeaseGrant): void { - if (grant.lease.mode === "held") this.#heldLeaseIds.set(grant.lease.id, grant.lease.deviceId); - } - // ---- call plumbing -------------------------------------------------------------------------- #parseInput( diff --git a/src/simlock-client/types.ts b/src/simlock-client/types.ts index 53a487b6c..547630530 100644 --- a/src/simlock-client/types.ts +++ b/src/simlock-client/types.ts @@ -32,7 +32,6 @@ export type LeaseRecord = OpOutput<"lease.renew">; export type LeaseReleaseInput = OpInput<"lease.release">; export type LeaseReleaseOutput = OpOutput<"lease.release">; export type LeaseListOutput = OpOutput<"lease.list">; -export type LeaseHeartbeatOutput = OpOutput<"lease.heartbeat">; export type DoctorRunInput = OpInput<"doctor.run">; export type DoctorReport = OpOutput<"doctor.run">; export type DriverPassthroughInput = OpInput<"driver.passthrough">; @@ -68,9 +67,13 @@ export type EventPush = z.infer<(typeof PUSH_SCHEMAS)["event"]>; export interface LeaseLostPush { readonly leaseId: string; readonly deviceId: string; - /** A server-reported reason (`"expired"`, `"explicit"`, `"closed"`, ...) or, when this - * client's own connection died, the client-synthesized `"daemon-connection-lost"` (ADR - * §10). Not a closed enum on the wire, so kept as `string` here rather than invented. */ + /** + * Why the daemon ended this lease: `"expired"`, `"explicit"`, `"killed"`, or + * `"device-lost"`. Always server-reported -- ADR 0004 §3 removed the client-synthesized + * `"daemon-connection-lost"`, because a dead connection ends no lease, and `"closed"` left + * the daemon's own vocabulary with it. Not a closed enum on the wire, so kept as `string` + * here rather than invented. + */ readonly reason: string; } diff --git a/src/simlock-client/wire.ts b/src/simlock-client/wire.ts index 4270d3015..c431f4954 100644 --- a/src/simlock-client/wire.ts +++ b/src/simlock-client/wire.ts @@ -29,7 +29,6 @@ const LEGACY_MISMATCH_CODE = "PROTOCOL_VERSION_MISMATCH"; export interface HelloOptions { readonly principal?: string; readonly credential?: string; - readonly capabilities?: { readonly heartbeat?: boolean }; } export interface HelloResult { @@ -126,7 +125,6 @@ export class SimlockWire { protocolRange: PROTOCOL_VERSION_RANGE, ...(options.principal === undefined ? {} : { principal: options.principal }), ...(options.credential === undefined ? {} : { credential: options.credential }), - ...(options.capabilities === undefined ? {} : { capabilities: options.capabilities }), }); } catch (error: unknown) { throw this.#toHelloError(error); @@ -314,13 +312,6 @@ export class SimlockWire { }); return; } - case "lease.heartbeat": { - // Reactive pong: answer with an ordinary request frame carrying the same payload - // (nonce), fire-and-forget. Only a connection that declared the heartbeat capability - // at `hello` ever receives this push, so this handler is otherwise inert. - void this.#send("lease.heartbeat", payload).catch(() => undefined); - return; - } case "event": { const parsed = PUSH_SCHEMAS.event.safeParse(payload); if (!parsed.success) return;