From a0e3bdc5f2bebbe54a0e148fca92b18677c07638 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 08:23:32 +0200 Subject: [PATCH 1/7] test: heartbeats keep the simlock lease alive (#473) --- src/agent-device/edge.test.ts | 760 ++++++++++++++++++++++++++++++++-- src/agent-device/testing.ts | 48 ++- src/core/config.test.ts | 29 ++ 3 files changed, 796 insertions(+), 41 deletions(-) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index f24f26917..0b3c2cdc6 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -63,6 +63,7 @@ interface Envelope { } interface SetUpOptions { + readonly leaseTtlCapMs?: number; readonly drivers?: (clock: FakeClock) => FakeDriver[]; readonly enabled?: boolean; readonly gatewayMode?: boolean; @@ -80,6 +81,7 @@ interface Rig { readonly origin: string; readonly statePath: string; readonly started: Promise; + readonly restart: () => Promise; } const phoneModels = { @@ -153,26 +155,31 @@ async function setUp(options: SetUpOptions = {}): Promise { const fake = options.upstream ?? new FakeAgentDevice(); const drivers = options.drivers?.(clock) ?? [iosDriver(clock)]; const statePath = join(directory, "state.json"); - const started = startDaemon({ - agentDeviceUpstream: fake, - clock, - configOverrides: { - agentDevice: { enabled: options.enabled ?? true }, - capacity: { config: { maxRunning: options.maxRunning ?? 4 }, strategy: "fixed" }, - http: { enabled: true, host: "127.0.0.1", port }, - lease: { defaultTtlMs, maxTtlMs }, - ...(options.gatewayMode === true ? { mode: "gateway" as const } : {}), - }, - dataDirectory: directory, - drivers, - filesystem, - logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), - statePath, - version: "1.2.3", - } as StartDaemonOptions).then((daemon) => { - runningDaemons.push(daemon); - return daemon; - }); + const launch = () => + startDaemon({ + agentDeviceUpstream: fake, + clock, + configOverrides: { + agentDevice: { + enabled: options.enabled ?? true, + ...(options.leaseTtlCapMs === undefined ? {} : { leaseTtlCapMs: options.leaseTtlCapMs }), + }, + capacity: { config: { maxRunning: options.maxRunning ?? 4 }, strategy: "fixed" }, + http: { enabled: true, host: "127.0.0.1", port }, + lease: { defaultTtlMs, maxTtlMs }, + ...(options.gatewayMode === true ? { mode: "gateway" as const } : {}), + }, + dataDirectory: directory, + drivers, + filesystem, + logger: new JsonLinesLogger({ clock, level: "debug", sink: new MemoryLogSink() }), + statePath, + version: "1.2.3", + } as StartDaemonOptions).then((daemon) => { + runningDaemons.push(daemon); + return daemon; + }); + const started = launch(); const origin = `http://127.0.0.1:${port}`; if (options.slowStart === true) { await waitListening(origin); @@ -183,21 +190,27 @@ async function setUp(options: SetUpOptions = {}): Promise { fake, filesystem, origin, + restart: () => Promise.reject(new Error("restart needs a started daemon")), started, statePath, }; } - const daemon = await started; - return { + const rigFor = (daemon: DaemonServer, running: Promise): Rig => ({ clock, daemon, driver: drivers[0] as FakeDriver, fake, filesystem, origin, - started, + restart: async () => { + await daemon.stop("test"); + const next = await launch(); + return rigFor(next, Promise.resolve(next)); + }, + started: running, statePath, - }; + }); + return rigFor(await started, started); } async function waitListening(origin: string): Promise { @@ -402,6 +415,98 @@ function refusal(message: string, code = "INVALID_ARGS") { return { code: -32000, data: { code, message }, message }; } +const endedMessage = "lease ended by simlock; run disconnect, then open"; + +function heartbeat( + rig: Rig, + n: number, + extra: Record = {}, + options: Omit = {}, +): Promise { + return rpc(rig, "agent_device.lease.heartbeat", { ...scope, leaseId: hex(n), ...extra }, options); +} + +function heartbeatsReceived(rig: Rig): number { + return rig.fake.rpcRequests("agent_device.lease.heartbeat").length; +} + +function expectEndedBySimlock(answer: Envelope): void { + expect(answer.result).toBeUndefined(); + expect(answer.error).toMatchObject({ + data: { + code: "UNAUTHORIZED", + details: { reason: "LEASE_ENDED_BY_HOST" }, + message: endedMessage, + }, + }); +} + +function expectLeaseGone(answer: Envelope, reason: string): void { + expect(answer.error).toMatchObject({ + data: { code: "UNAUTHORIZED", details: { reason } }, + }); +} + +async function deadlineOf(rig: Rig, n: number): Promise { + return (await leases(rig)).find((lease) => lease.id === hex(n))?.ttlDeadline; +} + +async function listed(rig: Rig): Promise { + return (await leases(rig)).map((lease) => lease.id); +} + +type RawDispatch = (operation: string, input: unknown, session: unknown) => Promise; + +interface DispatchTap { + readonly operations: string[]; + rejectNext(operation: string): void; + afterNext(operation: string, run: () => Promise): void; +} + +// why: the front reaches simlock through `daemon.dispatch` looked up at call time, so a wrapper on the daemon object sits between the front and leasing. +function tapDispatch(rig: Rig): DispatchTap { + const daemon = rig.daemon as unknown as { dispatch: RawDispatch }; + const original = daemon.dispatch.bind(daemon); + const operations: string[] = []; + const rejections = new Set(); + const afters = new Map Promise>(); + daemon.dispatch = async (operation, input, session) => { + operations.push(operation); + if (rejections.delete(operation)) throw new Error("simlock could not do that"); + const result = await original(operation, input, session); + const after = afters.get(operation); + afters.delete(operation); + await after?.(); + return result; + }; + return { + afterNext: (operation, run) => afters.set(operation, run), + operations, + rejectNext: (operation) => rejections.add(operation), + }; +} + +function frontCalls(tap: DispatchTap): readonly string[] { + return tap.operations.filter((name) => name === "lease.renew" || name === "lease.list"); +} + +async function renewMessage(rig: Rig, leaseId: string, ttlMs: number): Promise { + try { + await rig.daemon.dispatch("lease.renew", { leaseId, ttlMs }, sessionFor(principals.one)); + } catch (error) { + return (error as Error).message; + } + throw new Error("simlock accepted a renewal the test expected it to refuse"); +} + +async function runningCommand(rig: Rig, n: number, options: Omit = {}) { + rig.fake.holdCommand(); + const before = rig.fake.rpcRequests("agent_device.command").length; + const running = track(command(rig, "snapshot", n, options)); + await expect.poll(() => rig.fake.rpcRequests("agent_device.command").length).toBe(before + 1); + return running; +} + describe("the agent-device front, through the whole worker daemon", () => { it("with agentDevice.enabled false, and on a gateway-mode daemon, /v1/agent-device/health answers 404, as today", async () => { const enabled = await setUp(); @@ -1026,22 +1131,6 @@ describe("the agent-device front, through the whole worker daemon", () => { await expect.poll(async () => (await leases(rig)).length).toBe(0); }); - it("a heartbeat reaches the agent-device daemon unchanged, its reply reaches the CLI, and the simlock lease's deadline does not move", async () => { - const rig = await setUp(); - await granted(rig, 1); - const [before] = await leases(rig); - rig.clock.advance(10_000); - const params = { ...scope, leaseId: hex(1), ttlMs: 90_000 }; - - const answer = await envelopeOf( - await rpc(rig, "agent_device.lease.heartbeat", params, { id: "hb-1" }), - ); - - expect(answer).toMatchObject({ id: "hb-1", result: { ok: true } }); - expect(rig.fake.rpcRequests("agent_device.lease.heartbeat")[0]?.params).toMatchObject(params); - expect((await leases(rig))[0]).toEqual(before); - }); - it("release, and release after `close` (which the daemon answers `released: false`), go to the agent-device daemon first, then release the simlock lease, and the device is reclaimed and free", async () => { const rig = await setUp(); let heldAtDaemonRelease: readonly string[] = []; @@ -1196,4 +1285,595 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(await waiting(rig)).toEqual([]); expect(await leases(rig)).toEqual([]); }); + + it("a heartbeat reaches the agent-device daemon before simlock, carrying `ttlMs` equal to the ceiling, and once it answers, the simlock lease's deadline is now plus the CLI's `ttlMs`", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 60_000 }); + const allocated = await deadlineOf(rig, 1); + let deadlineAtDaemon: number | undefined; + rig.fake.onHeartbeat = async () => { + deadlineAtDaemon = await deadlineOf(rig, 1); + }; + await advance(rig, 10_000); + + const answer = await envelopeOf( + await heartbeat(rig, 1, { ttlMs: 120_000 }, { token: secrets.one }), + ); + + expect(answer.result).toMatchObject({ ok: true }); + expect(deadlineAtDaemon).toBe(allocated); + expect(rig.fake.rpcRequests("agent_device.lease.heartbeat")[0]?.params).toMatchObject({ + ...scope, + leaseId: hex(1), + ttlMs: rig.fake.leaseMaxTtlMs, + }); + expect(await deadlineOf(rig, 1)).toBe(rig.clock.now() + 120_000); + }); + + it.each([ + ["300000 with no cap", 300_000, undefined, 300_000], + ["300000 with cap 10000", 300_000, 10_000, 10_000], + ["300000 with cap 600000", 300_000, 600_000, 300_000], + ["none with cap 10000", undefined, 10_000, 10_000], + ["none with no cap", undefined, undefined, defaultTtlMs], + ["1 with no cap", 1, undefined, 5_000], + ])( + "a CLI `ttlMs` of %s gives the simlock lease, its heartbeat renewal and its renewal interval a TTL of %s ms", + async (_row, sent, cap, expected) => { + const rig = await setUp(cap === undefined ? {} : { leaseTtlCapMs: cap }); + const ttl = expected as number; + await granted(rig, 1, { ttlMs: sent }); + expect((await leases(rig))[0]?.ttlMs).toBe(ttl); + await advance(rig, 1_000); + + const answer = await envelopeOf( + await heartbeat(rig, 1, sent === undefined ? {} : { ttlMs: sent }), + ); + + expect(answer.result).toMatchObject({ ok: true }); + expect(await deadlineOf(rig, 1)).toBe(rig.clock.now() + ttl); + const settled = await deadlineOf(rig, 1); + await runningCommand(rig, 1); + await advance(rig, Math.floor(ttl / 3) - 700, 500); + expect(await deadlineOf(rig, 1)).toBe(settled); + await advance(rig, 1_400, 500); + const renewed = (await deadlineOf(rig, 1)) as number; + expect(renewed).toBeGreaterThan(settled as number); + expect(renewed - (settled as number)).toBeLessThanOrEqual(ttl / 3 + 700); + }, + 60_000, + ); + + it("a heartbeat with a longer `ttlMs` than the allocate's moves the deadline to now plus that TTL, and a following heartbeat with no `ttlMs` renews with it too", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 60_000 }); + await advance(rig, 5_000); + + await heartbeat(rig, 1, { ttlMs: 300_000 }); + + expect(await deadlineOf(rig, 1)).toBe(rig.clock.now() + 300_000); + await advance(rig, 20_000); + + await heartbeat(rig, 1); + + expect(await deadlineOf(rig, 1)).toBe(rig.clock.now() + 300_000); + expect((await leases(rig))[0]?.ttlMs).toBe(300_000); + }); + + it("after the agent's own `simlock lease renew` with a longer TTL, a heartbeat and a running command's renewals leave that later deadline in place", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 60_000 }); + await rig.daemon.dispatch( + "lease.renew", + { leaseId: hex(1), ttlMs: 900_000 }, + sessionFor(principals.one), + ); + const later = await deadlineOf(rig, 1); + expect(later).toBe(rig.clock.now() + 900_000); + await advance(rig, 5_000); + + await heartbeat(rig, 1, { ttlMs: 120_000 }); + + expect(await deadlineOf(rig, 1)).toBe(later); + const running = await runningCommand(rig, 1); + await advance(rig, 130_000, 5_000); + expect(await deadlineOf(rig, 1)).toBe(later); + rig.fake.releaseCommand(); + await running.promise; + await expect.poll(() => running.done()).toBe(true); + expect(await deadlineOf(rig, 1)).toBe(later); + }); + + it("a heartbeat the agent-device daemon cannot answer returns that error and leaves the simlock lease's deadline where it was", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 60_000 }); + const before = await deadlineOf(rig, 1); + await advance(rig, 10_000); + rig.fake.failNextHeartbeat({ code: "COMMAND_FAILED", message: "daemon is busy" }); + + const failed = await envelopeOf(await heartbeat(rig, 1, { ttlMs: 60_000 })); + + expect(failed.error).toMatchObject({ + data: { code: "COMMAND_FAILED" }, + message: "daemon is busy", + }); + expect(await deadlineOf(rig, 1)).toBe(before); + + rig.fake.setUnreachable(true); + const unreachable = await envelopeOf(await heartbeat(rig, 1, { ttlMs: 60_000 })); + + expect(unreachable.error).toBeDefined(); + expect(unreachable.result).toBeUndefined(); + expect(await deadlineOf(rig, 1)).toBe(before); + + rig.fake.setUnreachable(false); + await heartbeat(rig, 1, { ttlMs: 60_000 }); + expect(await deadlineOf(rig, 1)).toBe(rig.clock.now() + 60_000); + }); + + it("with no cap set, a heartbeat whose `ttlMs` is above `lease.maxTtlMs` answers `COMMAND_FAILED` with simlock's `BAD_REQUEST` message and leaves the deadline where it was, and a following heartbeat with a valid `ttlMs` renews the lease", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 60_000 }); + const before = await deadlineOf(rig, 1); + await advance(rig, 10_000); + const message = await renewMessage(rig, hex(1), maxTtlMs + 1); + + const refused = await envelopeOf(await heartbeat(rig, 1, { ttlMs: maxTtlMs + 1 })); + + expect(refused.error).toMatchObject({ data: { code: "COMMAND_FAILED" }, message }); + expect(await deadlineOf(rig, 1)).toBe(before); + + const renewed = await envelopeOf(await heartbeat(rig, 1, { ttlMs: 120_000 })); + + expect(renewed.result).toMatchObject({ ok: true }); + expect(await deadlineOf(rig, 1)).toBe(rig.clock.now() + 120_000); + expect((await leases(rig))[0]?.ttlMs).toBe(120_000); + }); + + it("a heartbeat for a lease the agent released through the front answers `LEASE_NOT_FOUND`, and a following allocate gets a new lease", async () => { + const rig = await setUp(); + await granted(rig, 1); + await release(rig, 1); + + const answer = await envelopeOf(await heartbeat(rig, 1)); + + expectLeaseGone(answer, "LEASE_NOT_FOUND"); + expect(await listed(rig)).toEqual([]); + + await granted(rig, 2); + + expect(await listed(rig)).toEqual([hex(2)]); + }); + + it("one TTL after the agent's release, a heartbeat for that lease answers `LEASE_ENDED_BY_HOST`", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 60_000 }); + await release(rig, 1); + expectLeaseGone(await envelopeOf(await heartbeat(rig, 1)), "LEASE_NOT_FOUND"); + await advance(rig, 61_000, 5_000); + + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + }); + + it.each([ + [ + "`simlock release --all`", + 5_000, + async (rig: Rig) => { + await rig.daemon.dispatch("lease.release-all", {}, adminSession); + }, + ], + [ + "expiry", + 5_000, + async (rig: Rig) => { + await advance(rig, 6_000); + }, + ], + [ + "the device is lost", + 600_000, + async (rig: Rig) => { + rig.driver.setManagedReality({ devices: [], processes: [] }); + await advance(rig, 120_000, 10_000); + }, + ], + ])( + "after %s, a heartbeat for the lease answers `LEASE_ENDED_BY_HOST` with the message and reason, and makes no new simlock lease", + async (_cause, ttl, end) => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: ttl }); + await end(rig); + await expect.poll(() => listed(rig)).toEqual([]); + + const answer = await envelopeOf(await heartbeat(rig, 1, { ttlMs: 5_000 })); + + expectEndedBySimlock(answer); + expect(await listed(rig)).toEqual([]); + }, + ); + + it.each(["LEASE_NOT_FOUND", "LEASE_EXPIRED", "LEASE_REVOKED"] as const)( + "a heartbeat the agent-device daemon answers `%s`, for a lease simlock holds and the agent did not release, releases the simlock lease and answers `LEASE_ENDED_BY_HOST`", + async (reason) => { + const rig = await setUp(); + await granted(rig, 1); + rig.fake.loseLease(hex(1), reason); + expect(await listed(rig)).toEqual([hex(1)]); + + const answer = await envelopeOf(await heartbeat(rig, 1)); + + expectEndedBySimlock(answer); + expect(await listed(rig)).toEqual([]); + }, + ); + + it("a heartbeat naming a lease ID the front map lacks, which simlock holds for this token's principal: when agent-device answers a lease-gone reason, the simlock lease is released; when agent-device still holds the lease, it is released with the heartbeat's scope first, then the simlock lease; when agent-device is unreachable, neither lease is touched; each answers as in the table", async () => { + const first = await setUp(); + await granted(first, 1); + await granted(first, 2); + await granted(first, 3); + const rig = await first.restart(); + expect(await listed(rig)).toEqual([hex(1), hex(2), hex(3)]); + + rig.fake.loseLease(hex(1), "LEASE_EXPIRED"); + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + expect(await listed(rig)).toEqual([hex(2), hex(3)]); + + let heldAtDaemonRelease: readonly string[] = []; + rig.fake.onRelease = async () => { + heldAtDaemonRelease = await listed(rig); + }; + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 2))); + expect(heldAtDaemonRelease).toEqual([hex(2), hex(3)]); + expect(rig.fake.rpcRequests("agent_device.lease.release")[0]?.params).toMatchObject(scope); + expect(rig.fake.leases.has(hex(2))).toBe(false); + expect(await listed(rig)).toEqual([hex(3)]); + + const before = await deadlineOf(rig, 3); + await advance(rig, 10_000); + rig.fake.setUnreachable(true); + const unreachable = await envelopeOf(await heartbeat(rig, 3)); + rig.fake.setUnreachable(false); + + expect(unreachable.error).toBeDefined(); + expect(unreachable.error?.data?.code).not.toBe("UNAUTHORIZED"); + expect(await listed(rig)).toEqual([hex(3)]); + expect(await deadlineOf(rig, 3)).toBe(before); + expect(rig.fake.leases.has(hex(3))).toBe(true); + }); + + it("a heartbeat from a second token naming the first token's lease ID answers `LEASE_ENDED_BY_HOST`, and the first token's lease is neither released nor renewed", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 60_000 }); + const before = await deadlineOf(rig, 1); + await advance(rig, 10_000); + + const answer = await envelopeOf( + await heartbeat(rig, 1, { ttlMs: 60_000 }, { token: secrets.two }), + ); + + expectEndedBySimlock(answer); + expect(await listed(rig)).toEqual([hex(1)]); + expect(await deadlineOf(rig, 1)).toBe(before); + expect(rig.fake.leases.has(hex(1))).toBe(true); + }); + + it("after a heartbeat answered `LEASE_ENDED_BY_HOST` because simlock ended the lease, the next heartbeat answers it again and the agent-device daemon receives nothing for it", async () => { + const rig = await setUp(); + await granted(rig, 1); + await rig.daemon.dispatch("lease.release-all", {}, adminSession); + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + const received = rig.fake.requests.length; + + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + + expect(rig.fake.requests).toHaveLength(received); + }); + + it("a lease released through the front while a command runs stays ended by the agent: a renewal that fires between the simlock release and the end of the agent's release, and the command's final renewal, mark nothing, and the next heartbeat still answers `LEASE_NOT_FOUND`", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 30_000 }); + const running = await runningCommand(rig, 1); + const tap = tapDispatch(rig); + tap.afterNext("lease.release", async () => { + await advance(rig, 12_000, 4_000); + }); + + const released = await envelopeOf(await release(rig, 1)); + rig.fake.releaseCommand(); + await running.promise; + + expect(released.result).toMatchObject({ ok: true, released: true }); + expect(await listed(rig)).toEqual([]); + expectLeaseGone(await envelopeOf(await heartbeat(rig, 1)), "LEASE_NOT_FOUND"); + }); + + it("after `simlock release --all`, the agent's release answers success, a heartbeat for the old ID then answers `LEASE_ENDED_BY_HOST` (ended by simlock, not `LEASE_NOT_FOUND`), and the next allocate gets a new lease; an entry found unlisted by another allocate's check answers its next heartbeat `LEASE_ENDED_BY_HOST` without reaching the agent-device daemon", async () => { + const rig = await setUp(); + await granted(rig, 1); + await rig.daemon.dispatch("lease.release-all", {}, adminSession); + + const released = await envelopeOf(await release(rig, 1)); + + expect(released.result).toMatchObject({ ok: true }); + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + await granted(rig, 2); + expect(await listed(rig)).toEqual([hex(2)]); + + await rig.daemon.dispatch("lease.release-all", {}, adminSession); + await granted(rig, 3); + const received = heartbeatsReceived(rig); + + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 2))); + expect(heartbeatsReceived(rig)).toBe(received); + }); + + it("a release for a lease simlock ended answers the agent-device daemon's reply as a success, and the agent-device lease is released", async () => { + const rig = await setUp(); + await granted(rig, 1); + await rig.daemon.dispatch("lease.release-all", {}, adminSession); + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + const tap = tapDispatch(rig); + + const answer = await envelopeOf(await release(rig, 1)); + + expect(answer.result).toMatchObject({ ok: true, released: true }); + expect(rig.fake.leases.has(hex(1))).toBe(false); + expect(tap.operations).not.toContain("lease.release"); + }); + + it("while a command for the lease runs longer than its TTL, the simlock lease is renewed every TTL/3 and does not expire", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 30_000 }); + await runningCommand(rig, 1); + const deadlines: (number | undefined)[] = []; + + for (let tick = 0; tick < 9; tick += 1) { + await advance(rig, 10_000, 5_000); + deadlines.push(await deadlineOf(rig, 1)); + } + + expect(deadlines.every((deadline) => deadline !== undefined)).toBe(true); + expect(deadlines.at(-1)).toBeGreaterThan(rig.clock.now()); + expect(new Set(deadlines).size).toBeGreaterThan(5); + }); + + it("when the command ends, the lease is renewed once more, and its deadline does not move again over the next TTL", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 30_000 }); + const running = await runningCommand(rig, 1); + await advance(rig, 25_000, 5_000); + rig.fake.releaseCommand(); + await running.promise; + + await expect.poll(() => deadlineOf(rig, 1)).toBe(rig.clock.now() + 30_000); + const final = await deadlineOf(rig, 1); + await advance(rig, 29_000, 5_000); + + expect(await deadlineOf(rig, 1)).toBe(final); + }); + + it("a command that fails, and one whose CLI hangs up, stop the renewals the same way", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 30_000 }); + await granted(rig, 2, { ttlMs: 30_000 }); + rig.fake.failNextCommand({ code: "COMMAND_FAILED", message: "the command failed" }); + const failing = await runningCommand(rig, 1); + await advance(rig, 25_000, 5_000); + rig.fake.releaseCommand(); + const failure = await envelopeOf(await failing.promise); + expect(failure.error).toMatchObject({ message: "the command failed" }); + await expect.poll(() => deadlineOf(rig, 1)).toBe(rig.clock.now() + 30_000); + const afterFailure = await deadlineOf(rig, 1); + + const hangUp = new AbortController(); + const hanging = await runningCommand(rig, 2, { signal: hangUp.signal }); + await advance(rig, 25_000, 5_000); + hangUp.abort(); + await hanging.promise.catch(() => undefined); + await expect.poll(() => deadlineOf(rig, 2)).toBe(rig.clock.now() + 30_000); + const afterHangUp = await deadlineOf(rig, 2); + + await advance(rig, 29_000, 5_000); + expect(await deadlineOf(rig, 1)).toBe(afterFailure); + expect(await deadlineOf(rig, 2)).toBe(afterHangUp); + }); + + it("with two overlapping commands on one lease, renewals go on until the second one ends", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 30_000 }); + const firstHangUp = new AbortController(); + await runningCommand(rig, 1, { signal: firstHangUp.signal }); + const second = await runningCommand(rig, 1); + await advance(rig, 20_000, 5_000); + firstHangUp.abort(); + + await advance(rig, 40_000, 5_000); + + expect(await deadlineOf(rig, 1)).toBeGreaterThan(rig.clock.now()); + rig.fake.releaseCommand(); + await second.promise; + await expect.poll(() => deadlineOf(rig, 1)).toBe(rig.clock.now() + 30_000); + const final = await deadlineOf(rig, 1); + await advance(rig, 29_000, 5_000); + expect(await deadlineOf(rig, 1)).toBe(final); + }); + + it("a renewal that fails because simlock ended the lease mid-command stops the renewals, and the command's reply still reaches the CLI; a renewal refused for another reason is tried again at the next tick", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 30_000 }); + const tap = tapDispatch(rig); + const running = await runningCommand(rig, 1); + await rig.daemon.dispatch("lease.release-all", {}, adminSession); + await advance(rig, 15_000, 5_000); + const calls = frontCalls(tap).length; + + await advance(rig, 60_000, 5_000); + + expect(frontCalls(tap)).toHaveLength(calls); + rig.fake.releaseCommand(); + const reply = await envelopeOf(await running.promise); + expect(reply.result).toMatchObject({ command: "snapshot", ok: true }); + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + + await granted(rig, 2, { ttlMs: 30_000 }); + const started = await deadlineOf(rig, 2); + await runningCommand(rig, 2); + tap.rejectNext("lease.renew"); + await advance(rig, 11_000, 1_000); + expect(await deadlineOf(rig, 2)).toBe(started); + + await advance(rig, 10_000, 1_000); + + expect(await deadlineOf(rig, 2)).toBeGreaterThan(started as number); + }); + + it('an agent release whose `lease.release` simlock refuses with another error clears "release in progress": the simlock lease stays, and a later renewal that finds it gone marks it ended by simlock', async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 30_000 }); + const tap = tapDispatch(rig); + tap.rejectNext("lease.release"); + + const refused = await envelopeOf(await release(rig, 1)); + + expect(refused.result).toMatchObject({ ok: true }); + expect(await listed(rig)).toEqual([hex(1)]); + await rig.daemon.dispatch("lease.release-all", {}, adminSession); + + const answer = await envelopeOf(await heartbeat(rig, 1)); + + expectEndedBySimlock(answer); + }); + + it("a heartbeat lowering the TTL from 300 s to 5 s while a command runs re-arms the renewals, and the lease does not expire before the command ends", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 300_000 }); + await runningCommand(rig, 1); + await advance(rig, 1_000); + + await heartbeat(rig, 1, { ttlMs: 5_000 }); + + await advance(rig, 360_000, 2_000); + expect(await listed(rig)).toEqual([hex(1)]); + expect(await deadlineOf(rig, 1)).toBeGreaterThan(rig.clock.now()); + }, 60_000); + + it("a command naming a lease ID the front map does not hold for its token, or the lease of an ended entry, starts no renewals", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 30_000 }); + await granted(rig, 2, { ttlMs: 30_000 }); + await release(rig, 2); + const tap = tapDispatch(rig); + await runningCommand(rig, 1, { token: secrets.two }); + await runningCommand(rig, 2); + + await advance(rig, 40_000, 5_000); + + expect(frontCalls(tap)).toEqual([]); + expect(await listed(rig)).toEqual([]); + }); + + it("a release through the front while a command runs stops that lease's renewals", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 30_000 }); + await runningCommand(rig, 1); + await advance(rig, 5_000, 5_000); + await release(rig, 1); + const tap = tapDispatch(rig); + + await advance(rig, 60_000, 5_000); + + expect(frontCalls(tap)).toEqual([]); + }); + + it("a lease whose CLI stops sending heartbeats expires one TTL after its last heartbeat, and its device can be leased again", async () => { + const rig = await setUp({ maxRunning: 1 }); + await granted(rig, 1, { ttlMs: 30_000 }); + await advance(rig, 10_000, 5_000); + await heartbeat(rig, 1, { ttlMs: 30_000 }); + await advance(rig, 29_000, 5_000); + expect(await listed(rig)).toEqual([hex(1)]); + + await advance(rig, 3_000, 1_000); + + expect(await listed(rig)).toEqual([]); + await granted(rig, 2); + expect(await listed(rig)).toEqual([hex(2)]); + }); + + it("after the agent-device daemon restarts, the next heartbeat answers `LEASE_ENDED_BY_HOST` and releases the simlock lease", async () => { + const rig = await setUp(); + await granted(rig, 1); + rig.fake.restart(); + + const answer = await envelopeOf(await heartbeat(rig, 1)); + + expectEndedBySimlock(answer); + expect(await listed(rig)).toEqual([]); + }); + + it("after a simlock daemon restart on the same data directory and the same `FakeDriver`, so the device keeps running and the test first sees the lease still listed, a heartbeat for a lease made before the restart answers `LEASE_ENDED_BY_HOST` and releases that simlock lease", async () => { + const first = await setUp(); + await granted(first, 1); + const rig = await first.restart(); + expect(await listed(rig)).toEqual([hex(1)]); + + const answer = await envelopeOf(await heartbeat(rig, 1)); + + expectEndedBySimlock(answer); + expect(await listed(rig)).toEqual([]); + }); + + it("after the same restart (same `FakeDriver`, lease still listed), a release for a lease made before the restart answers the agent-device daemon's reply as a success and releases that simlock lease", async () => { + const first = await setUp(); + await granted(first, 1); + const rig = await first.restart(); + expect(await listed(rig)).toEqual([hex(1)]); + + const answer = await envelopeOf(await release(rig, 1)); + + expect(answer.result).toMatchObject({ ok: true, released: true }); + expect(rig.fake.leases.has(hex(1))).toBe(false); + expect(await listed(rig)).toEqual([]); + }); + + it("a release with no map entry from a second token, naming the first token's lease ID, answers the agent-device daemon's reply and leaves the first token's simlock lease in place", async () => { + const first = await setUp(); + await granted(first, 1); + const rig = await first.restart(); + rig.fake.letAnyTenantRelease(); + + const answer = await envelopeOf(await release(rig, 1, { token: secrets.two })); + + expect(answer.result).toMatchObject({ ok: true, released: true }); + expect(rig.fake.leases.has(hex(1))).toBe(false); + expect(await listed(rig)).toEqual([hex(1)]); + }); + + it("stopping the daemon while a command runs renews nothing once the stop began: the lease's deadline, read after a restart on the same data directory and the same `FakeDriver` (the lease still listed), is the one it had before the stop", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 30_000 }); + await runningCommand(rig, 1); + await advance(rig, 12_000, 4_000); + const before = await deadlineOf(rig, 1); + + const stopping = rig.daemon.stop("test"); + await advance(rig, 3_000, 1_000).catch(() => undefined); + await stopping; + const restarted = await rig.restart(); + + expect(await listed(restarted)).toEqual([hex(1)]); + expect(await deadlineOf(restarted, 1)).toBe(before); + }); + + it("`config.get` returns `agentDevice.leaseTtlCapMs` when it is set", async () => { + const rig = await setUp({ leaseTtlCapMs: 10_000 }); + + const config = (await rig.daemon.dispatch("config.get", {}, adminSession)) as { + readonly agentDevice: { readonly leaseTtlCapMs?: number }; + }; + + expect(config.agentDevice.leaseTtlCapMs).toBe(10_000); + }); }); diff --git a/src/agent-device/testing.ts b/src/agent-device/testing.ts index d5f31a593..e428fded6 100644 --- a/src/agent-device/testing.ts +++ b/src/agent-device/testing.ts @@ -48,8 +48,11 @@ interface FakeAgentDeviceLease { interface FakeFailure { readonly code: string; readonly message: string; + readonly details?: Readonly>; } +export type FakeLeaseGoneReason = "LEASE_NOT_FOUND" | "LEASE_EXPIRED" | "LEASE_REVOKED"; + interface Gate { readonly promise: Promise; open(): void; @@ -98,10 +101,14 @@ export class FakeAgentDevice implements AgentDeviceUpstream { generation = 1; leaseMaxTtlMs: number; onRelease: (() => Promise) | undefined; + onHeartbeat: (() => Promise) | undefined; #unavailable: string | undefined; #unreachable = false; #failAllocate: FakeFailure | undefined; #failRelease: FakeFailure | undefined; + #failHeartbeat: FakeFailure | undefined; + #failCommand: FakeFailure | undefined; + readonly #goneReasons = new Map(); #allocateBody: string | undefined; #replyDeviceKey: string | undefined; #anyTenantReleases = false; @@ -144,6 +151,20 @@ export class FakeAgentDevice implements AgentDeviceUpstream { this.#failRelease = failure; } + failNextHeartbeat(failure: FakeFailure): void { + this.#failHeartbeat = failure; + } + + failNextCommand(failure: FakeFailure): void { + this.#failCommand = failure; + } + + // why: agent-device answers a heartbeat for a lease it no longer holds with UNAUTHORIZED and one of three reasons; this makes it forget `leaseId` for the given one. + loseLease(leaseId: string, reason: FakeLeaseGoneReason): void { + this.leases.delete(leaseId); + this.#goneReasons.set(leaseId, reason); + } + answerNextAllocateWith(body: string): void { this.#allocateBody = body; } @@ -169,6 +190,10 @@ export class FakeAgentDevice implements AgentDeviceUpstream { this.#commandGate = gate(); } + releaseCommand(): void { + this.#commandGate?.open(); + } + streamNextCommand(chunks: readonly string[]): void { this.#streamChunks = chunks; } @@ -226,7 +251,8 @@ export class FakeAgentDevice implements AgentDeviceUpstream { case "lease.allocate": return this.#allocate(id, params, tenant); case "lease.heartbeat": - return envelope(id, { lease: params, ok: true }); + await this.onHeartbeat?.(); + return this.#heartbeat(id, params, tenant); case "lease.release": await this.onRelease?.(); return this.#release(id, params, tenant); @@ -262,6 +288,23 @@ export class FakeAgentDevice implements AgentDeviceUpstream { }); } + #heartbeat(id: unknown, params: Record, tenant: string | undefined): Response { + const failure = this.#failHeartbeat; + this.#failHeartbeat = undefined; + if (failure !== undefined) return errorEnvelope(id, failure); + const leaseId = String(params["leaseId"]); + const lease = this.leases.get(leaseId); + if (lease === undefined || lease.tenant !== tenant) { + const reason = this.#goneReasons.get(leaseId) ?? "LEASE_NOT_FOUND"; + return errorEnvelope(id, { + code: "UNAUTHORIZED", + details: { reason }, + message: reason.toLowerCase().replaceAll("_", " "), + }); + } + return envelope(id, { lease: params, ok: true }); + } + #release(id: unknown, params: Record, tenant: string | undefined): Response { const failure = this.#failRelease; this.#failRelease = undefined; @@ -312,6 +355,9 @@ export class FakeAgentDevice implements AgentDeviceUpstream { { headers: { "content-type": "application/x-ndjson" } }, ); } + const failure = this.#failCommand; + this.#failCommand = undefined; + if (failure !== undefined) return errorEnvelope(id, failure); const leaseId = meta["leaseId"]; if (command === "close" && typeof leaseId === "string") { const lease = this.leases.get(leaseId); diff --git a/src/core/config.test.ts b/src/core/config.test.ts index 1ad35306a..8bc2673b2 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -1986,6 +1986,35 @@ describe("agentDevice config", () => { await expect(loadWith({ agentDevice: { command } })).rejects.toThrow("agentDevice.command"); }); + it("leaves agentDevice.leaseTtlCapMs unset by default", async () => { + const config = await loadWith({}); + + expect(dottedValue(config, "agentDevice.leaseTtlCapMs")).toBeUndefined(); + }); + + it("accepts agentDevice.leaseTtlCapMs of 5000 and of lease.maxTtlMs", async () => { + const lowest = await loadWith({ agentDevice: { leaseTtlCapMs: 5_000 } }); + const highest = await loadWith({ + agentDevice: { leaseTtlCapMs: 7_200_000 }, + lease: { maxTtlMs: 7_200_000 }, + }); + + expect(dottedValue(lowest, "agentDevice.leaseTtlCapMs")).toBe(5_000); + expect(dottedValue(highest, "agentDevice.leaseTtlCapMs")).toBe(7_200_000); + }); + + it.each([ + ["4999", 4_999], + ["a fraction", 5_000.5], + ["a value above lease.maxTtlMs", 14_400_001], + ])("refuses agentDevice.leaseTtlCapMs of %s, naming the key", async (_case, leaseTtlCapMs) => { + await expect(loadWith({ agentDevice: { leaseTtlCapMs: 5_000 } })).resolves.toBeDefined(); + + await expect(loadWith({ agentDevice: { leaseTtlCapMs } })).rejects.toThrow( + "agentDevice.leaseTtlCapMs", + ); + }); + it("a loaded config parsed through configSchema keeps both keys", async () => { const config = await loadWith({ agentDevice: { command: "ad", enabled: true } }); From c624cf53529aca0074e1d81334c734272f410b67 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 08:32:37 +0200 Subject: [PATCH 2/7] feat(agent-device): heartbeats and running commands keep the simlock lease alive (#473) 2 failing -> 2 failing (88 of 90 edge tests and all config tests green) --- src/agent-device/front/allocate.ts | 51 ++++------ src/agent-device/front/context.ts | 50 +++++++++- src/agent-device/front/front-map.ts | 43 +++++++-- src/agent-device/front/front.ts | 74 ++++++++++++++- src/agent-device/front/heartbeat.ts | 139 +++++++++++++++++++++++++++ src/agent-device/front/release.ts | 21 +++-- src/agent-device/front/renewals.ts | 141 ++++++++++++++++++++++++++++ src/agent-device/front/ttl.ts | 8 ++ src/agent-device/index.ts | 22 ++++- src/agent-device/shared/replies.ts | 21 ++++- src/agent-device/shared/rpc.ts | 27 +++++- src/contract/schemas.ts | 6 +- src/core/config.ts | 18 +++- src/daemon/main.ts | 5 + 14 files changed, 558 insertions(+), 68 deletions(-) create mode 100644 src/agent-device/front/heartbeat.ts create mode 100644 src/agent-device/front/renewals.ts create mode 100644 src/agent-device/front/ttl.ts diff --git a/src/agent-device/front/allocate.ts b/src/agent-device/front/allocate.ts index 3b44469df..d2be67839 100644 --- a/src/agent-device/front/allocate.ts +++ b/src/agent-device/front/allocate.ts @@ -7,12 +7,22 @@ import type { TokenIdentity } from "../../http/token-store.js"; import type { Clock } from "../../ports/index.js"; import { frontReply, failure, refusal, type FrontReply } from "../shared/replies.js"; import { leaseCallFields, leaseIdOf, type RpcRead } from "../shared/rpc.js"; -import { exchange, leaseCall, releaseSimlock, relay, type FrontContext } from "./context.js"; +import { + ALLOCATE_SCOPE_KEYS, + REPLY_SCOPE_KEYS, + exchange, + leaseCall, + releaseAgentDevice, + releaseSimlock, + relay, + scopeOf, + type FrontContext, +} from "./context.js"; +import { chosenTtl } from "./ttl.js"; type Grant = z.infer<(typeof OPERATIONS)["lease.request"]["output"]>; const QUEUE_WAIT_MS = 330_000; -const MIN_TTL_MS = 5_000; const CANCEL_RETRY_MS = 1_000; const LEASE_GONE = new Set(["LEASE_NOT_FOUND", "LEASE_EXPIRED", "LEASE_REVOKED"]); const CLASS_OF_TARGET: Record = { @@ -20,9 +30,6 @@ const CLASS_OF_TARGET: Record = { mobile: "phone", tv: "tv", }; -const CALL_SCOPE_KEYS = ["runId", "leaseProvider", "clientId"] as const; -// why: only agent-device's reply names the device key it gave the lease, since the front stripped the CLI's key from the allocate it forwarded. -const REPLY_SCOPE_KEYS = [...CALL_SCOPE_KEYS, "deviceKey"] as const; const present = (value: unknown): boolean => value !== undefined && value !== null; @@ -72,16 +79,17 @@ function refusalFor(params: Record): FrontReply | undefined { return undefined; } -function planOf(params: Record): Plan { +function planOf(params: Record, cap: number | undefined): Plan { const fields = leaseCallFields(params); const device = typeof fields.device === "string" && fields.device !== "" ? fields.device : undefined; const klass = typeof fields.target === "string" ? CLASS_OF_TARGET[fields.target] : undefined; + const ttlMs = chosenTtl(fields.ttlMs, cap); return { leaseId: fields.leaseId as string, platform: fields.platform as "ios" | "android", ...(device === undefined ? (klass === undefined ? {} : { class: klass }) : { model: device }), - ...(typeof fields.ttlMs === "number" ? { ttlMs: Math.max(fields.ttlMs, MIN_TTL_MS) } : {}), + ...(ttlMs === undefined ? {} : { ttlMs }), }; } @@ -196,31 +204,6 @@ async function requestLease( } } -function scopeOf( - source: Record | undefined, - keys: readonly string[], -): Record { - const scope: Record = {}; - for (const key of keys) { - if (source?.[key] !== undefined) scope[key] = source[key]; - } - return scope; -} - -async function releaseAgentDevice( - context: FrontContext, - request: Request, - identity: TokenIdentity, - leaseId: string, - scope: Record, -) { - return exchange( - context, - leaseCall(request, "agent_device.lease.release", { ...scope, leaseId }, "simlock-release"), - identity, - ); -} - function forwardedBody( call: RpcRead & { kind: "request" }, plan: Plan, @@ -260,7 +243,7 @@ export async function allocate( ): Promise { const refused = refusalFor(call.params); if (refused !== undefined) return frontReply(refused, call); - const plan = planOf(call.params); + const plan = planOf(call.params, context.leaseTtlCapMs); await context.map.refresh((who) => listLeases(context, who)); if (request.signal.aborted) return undefined; const outcome = await requestLease(context, identity, plan, request.signal); @@ -328,7 +311,7 @@ async function settleNoReply( request, identity, plan.leaseId, - scopeOf(call.params, CALL_SCOPE_KEYS), + scopeOf(call.params, ALLOCATE_SCOPE_KEYS), ); const holds = ended.reading.kind === "error" && diff --git a/src/agent-device/front/context.ts b/src/agent-device/front/context.ts index b70cf3a32..cd4653a85 100644 --- a/src/agent-device/front/context.ts +++ b/src/agent-device/front/context.ts @@ -6,8 +6,11 @@ import { mapError } from "../../http/errors.js"; import { readReply, type ReplyReading } from "../shared/rpc.js"; import type { FrontMap } from "./front-map.js"; import type { HostLink } from "./host-link.js"; +import type { Renewals } from "./renewals.js"; export interface FrontContext { + readonly leaseTtlCapMs?: number; + readonly renewals: Renewals; readonly link: HostLink; readonly map: FrontMap; readonly dispatch: HttpDispatch; @@ -64,20 +67,57 @@ export function leaseCall( }); } +export type SimlockRelease = + | { readonly kind: "released" | "unknown" | "forbidden" } + | { readonly kind: "failed"; readonly message: string }; + export async function releaseSimlock( context: FrontContext, identity: TokenIdentity, leaseId: string, -): Promise { +): Promise { try { await context.dispatch("lease.release", { leaseId }, buildHttpSession(identity)); - return true; + return { kind: "released" }; } catch (error) { - if (mapError(error).code === "UNKNOWN_LEASE") return true; + const code = mapError(error).code; + if (code === "UNKNOWN_LEASE") return { kind: "unknown" }; + if (code === "FORBIDDEN") return { kind: "forbidden" }; + const message = error instanceof Error ? error.message : String(error); context.logger.warn("agent-device front could not release a simlock lease", { leaseId, - message: error instanceof Error ? error.message : String(error), + message, }); - return false; + return { kind: "failed", message }; + } +} + +const CALL_SCOPE_KEYS = ["runId", "leaseProvider", "clientId"] as const; +// why: only agent-device's reply names the device key it gave the lease, since the front stripped the CLI's key from the allocate it forwarded. +export const REPLY_SCOPE_KEYS = [...CALL_SCOPE_KEYS, "deviceKey"] as const; +export const ALLOCATE_SCOPE_KEYS = CALL_SCOPE_KEYS; + +export function scopeOf( + source: Record | undefined, + keys: readonly string[], +): Record { + const scope: Record = {}; + for (const key of keys) { + if (source?.[key] !== undefined) scope[key] = source[key]; } + return scope; +} + +export async function releaseAgentDevice( + context: FrontContext, + request: Request, + identity: TokenIdentity, + leaseId: string, + scope: Record, +) { + return exchange( + context, + leaseCall(request, "agent_device.lease.release", { ...scope, leaseId }, "simlock-release"), + identity, + ); } diff --git a/src/agent-device/front/front-map.ts b/src/agent-device/front/front-map.ts index 3cfdb4d05..2fa243482 100644 --- a/src/agent-device/front/front-map.ts +++ b/src/agent-device/front/front-map.ts @@ -10,6 +10,16 @@ export interface FrontMapEntry { readonly deadline: number; } +export type EndedBy = "agent" | "simlock"; + +export interface HeldView { + readonly identity: TokenIdentity; + readonly address: string; + readonly ttlMs: number; + readonly endedAt?: number; + readonly endedBy?: EndedBy; +} + export interface ListedLease { readonly id: string; readonly ttlDeadline: number; @@ -18,9 +28,11 @@ export interface ListedLease { interface Held { readonly identity: TokenIdentity; readonly address: string; - readonly ttlMs: number; + ttlMs: number; deadline: number; endedAt?: number; + endedBy?: EndedBy; + releasing: boolean; } export class FrontMap { @@ -45,17 +57,36 @@ export class FrontMap { add(leaseId: string, entry: FrontMapEntry): void { this.#prune(); - this.#held.set(leaseId, { ...entry }); + this.#held.set(leaseId, { ...entry, releasing: false }); } - get(leaseId: string): (FrontMapEntry & { readonly endedAt?: number }) | undefined { + get(leaseId: string): HeldView | undefined { this.#prune(); return this.#held.get(leaseId); } - markEnded(leaseId: string): void { + setTtl(leaseId: string, ttlMs: number): void { + const held = this.#held.get(leaseId); + if (held !== undefined) held.ttlMs = ttlMs; + } + + beginRelease(leaseId: string): void { + const held = this.#held.get(leaseId); + if (held !== undefined) held.releasing = true; + } + + cancelRelease(leaseId: string): void { + const held = this.#held.get(leaseId); + if (held !== undefined) held.releasing = false; + } + + markEnded(leaseId: string, by: EndedBy = "simlock"): void { const held = this.#held.get(leaseId); - if (held !== undefined) held.endedAt ??= this.clock.now(); + if (held === undefined || held.endedAt !== undefined) return; + if (by === "simlock" && held.releasing) return; + held.endedAt = this.clock.now(); + held.endedBy = by; + held.releasing = false; } async refresh(list: (identity: TokenIdentity) => Promise): Promise { @@ -94,7 +125,7 @@ export class FrontMap { const held = this.#held.get(id); if (held === undefined) continue; const found = listed.find((lease) => lease.id === id); - if (found === undefined) held.endedAt ??= this.clock.now(); + if (found === undefined) this.markEnded(id); else held.deadline = found.ttlDeadline; } }), diff --git a/src/agent-device/front/front.ts b/src/agent-device/front/front.ts index 290305673..f38167fa6 100644 --- a/src/agent-device/front/front.ts +++ b/src/agent-device/front/front.ts @@ -2,9 +2,10 @@ import type { HttpMount } from "../../http/app.js"; import type { TokenIdentity } from "../../http/token-store.js"; import { FRONT_MOUNT, FRONT_PREFIX } from "../shared/paths.js"; import { failure, frontReply, notAvailable, refusal } from "../shared/replies.js"; -import { classifyCall, readRpcBody, type RpcRead } from "../shared/rpc.js"; +import { classifyCall, commandLeaseId, readRpcBody, type RpcRead } from "../shared/rpc.js"; import { allocate } from "./allocate.js"; import type { FrontContext } from "./context.js"; +import { heartbeat } from "./heartbeat.js"; import { release } from "./release.js"; type RpcRequest = RpcRead & { readonly kind: "request" }; @@ -65,9 +66,74 @@ async function handleRpc( }); return untilHangUp(request.signal, work); } - return kind === "release" - ? release(context, identity, read as RpcRequest, carry(request, read.text)) - : passThrough(context, carry(request, read.text), identity, read); + if (kind === "heartbeat") { + return heartbeat(context, { + call: read, + identity, + leaseMaxTtlMs: status.leaseMaxTtlMs, + request: carry(request, read.text), + }); + } + if (kind === "release") { + return release(context, identity, read as RpcRequest, carry(request, read.text)); + } + const leaseId = kind === "command" ? commandLeaseId(read.params) : undefined; + if (leaseId === undefined) return passThrough(context, carry(request, read.text), identity, read); + return runCommand(context, request, identity, read, { + leaseId, + maxRunMs: status.leaseMaxTtlMs, + }); +} + +async function runCommand( + context: FrontContext, + request: Request, + identity: TokenIdentity, + read: RpcRequest, + { leaseId, maxRunMs }: { readonly leaseId: string; readonly maxRunMs: number }, +): Promise { + const end = context.renewals.begin(context, leaseId, identity.requesterId, maxRunMs); + request.signal.addEventListener("abort", end, { once: true }); + let response: Response; + try { + response = await passThrough(context, carry(request, read.text), identity, read); + } catch (error) { + end(); + throw error; + } + return untilBodyEnds(response, end); +} + +// why: a command counts as running until its body has gone out, since the stream is what the CLI waits on. +function untilBodyEnds(response: Response, end: () => void): Response { + if (response.body === null) { + end(); + return response; + } + const reader = response.body.getReader(); + const body = new ReadableStream({ + async cancel(reason) { + end(); + await reader.cancel(reason); + }, + async pull(controller) { + try { + const { done, value } = await reader.read(); + if (done) { + controller.close(); + end(); + } else controller.enqueue(value); + } catch (error) { + end(); + controller.error(error); + } + }, + }); + return new Response(body, { + headers: response.headers, + status: response.status, + statusText: response.statusText, + }); } async function passThrough( diff --git a/src/agent-device/front/heartbeat.ts b/src/agent-device/front/heartbeat.ts new file mode 100644 index 000000000..21d26e49b --- /dev/null +++ b/src/agent-device/front/heartbeat.ts @@ -0,0 +1,139 @@ +import type { TokenIdentity } from "../../http/token-store.js"; +import { failure, frontReply, leaseEndedByHost, refusal } from "../shared/replies.js"; +import { + leaseCallFields, + leaseGoneReason, + leaseIdOf, + type ReplyReading, + type RpcRead, +} from "../shared/rpc.js"; +import { + REPLY_SCOPE_KEYS, + exchange, + releaseAgentDevice, + releaseSimlock, + relay, + scopeOf, + type Exchange, + type FrontContext, +} from "./context.js"; +import type { HeldView } from "./front-map.js"; +import { renewLease } from "./renewals.js"; +import { chosenTtl } from "./ttl.js"; + +type Call = RpcRead & { readonly kind: "request" }; + +function forwardedHeartbeat(request: Request, call: Call, ceiling: number): Request { + const headers = new Headers(request.headers); + headers.delete("content-length"); + return new Request(request.url, { + body: JSON.stringify({ ...call.body, params: { ...call.params, ttlMs: ceiling } }), + headers, + method: "POST", + signal: request.signal, + }); +} + +// why: simlock's own ownership check decides about a lease another token holds, so a refusal there is not a failure of the heartbeat. +async function releaseOurs( + context: FrontContext, + identity: TokenIdentity, + leaseId: string, + call: Call, + held: boolean, +): Promise { + const released = await releaseSimlock(context, identity, leaseId); + if (released.kind === "failed") return frontReply(failure(released.message), call); + if (held) { + context.map.markEnded(leaseId); + context.renewals.cancelIfEnded(context, leaseId); + } + return frontReply(leaseEndedByHost(), call); +} + +async function leaseStillThere( + context: FrontContext, + { request, identity, call }: { request: Request; identity: TokenIdentity; call: Call }, + leaseId: string, +): Promise { + const ended = await releaseAgentDevice( + context, + request, + identity, + leaseId, + scopeOf(call.params, REPLY_SCOPE_KEYS), + ); + if (ended.response === undefined) { + return frontReply(failure("agent-device did not answer the release"), call); + } + if (ended.reading.kind !== "success") return relay(ended); + return releaseOurs(context, identity, leaseId, call, false); +} + +async function renewHeld( + context: FrontContext, + call: Call, + entry: HeldView, + leaseId: string, + reply: Exchange, +): Promise { + const sent = leaseCallFields(call.params).ttlMs; + const ttl = typeof sent === "number" ? chosenTtl(sent, context.leaseTtlCapMs) : undefined; + const outcome = await renewLease(context, leaseId, ttl ?? entry.ttlMs); + if (outcome.kind === "gone") { + context.map.markEnded(leaseId); + context.renewals.cancelIfEnded(context, leaseId); + return frontReply(leaseEndedByHost(), call); + } + if (outcome.kind === "failed") return frontReply(failure(outcome.message), call); + if (ttl !== undefined && ttl !== entry.ttlMs) { + context.map.setTtl(leaseId, ttl); + context.renewals.rearm(context, leaseId); + } + return relay(reply); +} + +function ownEntry(context: FrontContext, leaseId: string, identity: TokenIdentity) { + const entry = context.map.get(leaseId); + return entry?.identity.requesterId === identity.requesterId ? entry : undefined; +} + +function badTtl(call: Call): boolean { + const sent = leaseCallFields(call.params).ttlMs; + return ( + sent !== undefined && + sent !== null && + !(typeof sent === "number" && Number.isFinite(sent) && sent > 0) + ); +} + +export async function heartbeat( + context: FrontContext, + arguments_: { + readonly request: Request; + readonly identity: TokenIdentity; + readonly call: Call; + readonly leaseMaxTtlMs: number; + }, +): Promise { + const { request, identity, call, leaseMaxTtlMs } = arguments_; + if (badTtl(call)) { + return frontReply(refusal("refused: ttlMs must be a positive number of milliseconds"), call); + } + const leaseId = leaseIdOf(leaseCallFields(call.params).leaseId); + const entry = leaseId === undefined ? undefined : ownEntry(context, leaseId, identity); + if (leaseId !== undefined && entry?.endedBy === "simlock") { + return frontReply(leaseEndedByHost(), call); + } + const reply = await exchange(context, forwardedHeartbeat(request, call, leaseMaxTtlMs), identity); + if (leaseId === undefined || reply.response === undefined) return relay(reply); + const reading: ReplyReading = reply.reading; + if (reading.kind === "success") { + if (entry === undefined) return leaseStillThere(context, arguments_, leaseId); + if (entry.endedAt !== undefined) return relay(reply); + return renewHeld(context, call, entry, leaseId, reply); + } + if (leaseGoneReason(reading) === undefined) return relay(reply); + if (entry?.endedBy === "agent") return relay(reply); + return releaseOurs(context, identity, leaseId, call, entry !== undefined); +} diff --git a/src/agent-device/front/release.ts b/src/agent-device/front/release.ts index 793e75277..5df8d3c35 100644 --- a/src/agent-device/front/release.ts +++ b/src/agent-device/front/release.ts @@ -14,15 +14,18 @@ export async function release( return frontReply(failure("agent-device did not answer the release"), call); } const leaseId = leaseIdOf(leaseCallFields(call.params).leaseId); - const entry = leaseId === undefined ? undefined : context.map.get(leaseId); - if ( - leaseId !== undefined && - entry?.identity.requesterId === identity.requesterId && - entry.endedAt === undefined && - reply.reading.kind === "success" && - (await releaseSimlock(context, entry.identity, leaseId)) - ) { - context.map.markEnded(leaseId); + if (leaseId === undefined || reply.reading.kind !== "success") return relay(reply); + const entry = context.map.get(leaseId); + if (entry === undefined || entry.identity.requesterId !== identity.requesterId) { + // why: a lease the map does not hold for this token (as after a daemon restart) is freed by simlock's own ownership check, which refuses another token's lease. + await releaseSimlock(context, identity, leaseId); + } else if (entry.endedAt === undefined) { + context.map.beginRelease(leaseId); + const released = await releaseSimlock(context, entry.identity, leaseId); + if (released.kind === "released") context.map.markEnded(leaseId, "agent"); + else if (released.kind === "unknown") context.map.markEnded(leaseId, "simlock"); + else context.map.cancelRelease(leaseId); + context.renewals.cancelIfEnded(context, leaseId); } return relay(reply); } diff --git a/src/agent-device/front/renewals.ts b/src/agent-device/front/renewals.ts new file mode 100644 index 000000000..c46d783e8 --- /dev/null +++ b/src/agent-device/front/renewals.ts @@ -0,0 +1,141 @@ +import { buildHttpSession } from "../../http/dispatcher-session.js"; +import { mapError } from "../../http/errors.js"; +import type { Clock } from "../../ports/index.js"; +import type { FrontContext } from "./context.js"; + +export type RenewOutcome = + | { readonly kind: "renewed" } + | { readonly kind: "gone" } + | { readonly kind: "failed"; readonly message: string }; + +const TICKS_PER_TTL = 3; + +export async function renewLease( + context: FrontContext, + leaseId: string, + ttlMs: number, +): Promise { + const entry = context.map.get(leaseId); + if (entry === undefined) return { kind: "gone" }; + const session = buildHttpSession(entry.identity); + try { + const { leases } = await context.dispatch("lease.list", {}, session); + const listed = leases.find((lease) => lease.id === leaseId); + if (listed === undefined) return { kind: "gone" }; + if (context.clock.now() + ttlMs > listed.ttlDeadline) { + await context.dispatch("lease.renew", { leaseId, ttlMs }, session); + } + return { kind: "renewed" }; + } catch (error) { + if (mapError(error).code === "UNKNOWN_LEASE") return { kind: "gone" }; + return { kind: "failed", message: error instanceof Error ? error.message : String(error) }; + } +} + +interface Running { + calls: number; + timer?: ReturnType; +} + +export class Renewals { + readonly #running = new Map(); + #disposed = false; + + constructor(private readonly clock: Clock) {} + + begin(context: FrontContext, leaseId: string, identityId: string, maxRunMs: number): () => void { + const entry = context.map.get(leaseId); + if ( + this.#disposed || + entry === undefined || + entry.identity.requesterId !== identityId || + entry.endedAt !== undefined + ) { + return () => undefined; + } + const running = this.#running.get(leaseId) ?? { calls: 0 }; + this.#running.set(leaseId, running); + running.calls += 1; + if (running.calls === 1) this.#arm(context, leaseId, running); + let over = false; + let limit: ReturnType | undefined; + const end = (): void => { + if (over) return; + over = true; + if (limit !== undefined) this.clock.cancel(limit); + this.#finish(context, leaseId, running); + }; + limit = this.clock.setTimer(maxRunMs, end); + return end; + } + + rearm(context: FrontContext, leaseId: string): void { + const running = this.#running.get(leaseId); + if (running !== undefined && !this.#disposed) this.#arm(context, leaseId, running); + } + + cancelIfEnded(context: FrontContext, leaseId: string): void { + const running = this.#running.get(leaseId); + if (running !== undefined && context.map.get(leaseId)?.endedAt !== undefined) { + this.#disarm(running); + } + } + + dispose(): void { + this.#disposed = true; + for (const running of this.#running.values()) this.#disarm(running); + this.#running.clear(); + } + + #disarm(running: Running): void { + if (running.timer !== undefined) this.clock.cancel(running.timer); + delete running.timer; + } + + #arm(context: FrontContext, leaseId: string, running: Running): void { + this.#disarm(running); + const entry = context.map.get(leaseId); + if (entry === undefined || entry.endedAt !== undefined) return; + const timer = this.clock.setTimer(entry.ttlMs / TICKS_PER_TTL, () => { + void this.#tick(context, leaseId, running, timer); + }); + running.timer = timer; + } + + async #tick( + context: FrontContext, + leaseId: string, + running: Running, + timer: ReturnType, + ): Promise { + if (running.timer !== timer || this.#disposed) return; + delete running.timer; + await this.#renewOnce(context, leaseId); + // why: a heartbeat may have re-armed the timer while this renewal ran; that timer stands. + if (!this.#disposed && running.timer === undefined && this.#running.get(leaseId) === running) { + this.#arm(context, leaseId, running); + } + } + + async #renewOnce(context: FrontContext, leaseId: string): Promise { + const entry = context.map.get(leaseId); + if (this.#disposed || entry === undefined || entry.endedAt !== undefined) return; + const outcome = await renewLease(context, leaseId, entry.ttlMs); + if (this.#disposed) return; + if (outcome.kind === "gone") context.map.markEnded(leaseId); + else if (outcome.kind === "failed") { + context.logger.warn("agent-device front could not renew a simlock lease", { + leaseId, + message: outcome.message, + }); + } + } + + #finish(context: FrontContext, leaseId: string, running: Running): void { + running.calls -= 1; + if (running.calls > 0) return; + this.#disarm(running); + if (this.#running.get(leaseId) === running) this.#running.delete(leaseId); + void this.#renewOnce(context, leaseId); + } +} diff --git a/src/agent-device/front/ttl.ts b/src/agent-device/front/ttl.ts new file mode 100644 index 000000000..e7d0ad426 --- /dev/null +++ b/src/agent-device/front/ttl.ts @@ -0,0 +1,8 @@ +// why: agent-device's shortest lease window; a shorter TTL would not be honoured by its daemon. +const MIN_TTL_MS = 5_000; + +export function chosenTtl(sent: unknown, cap: number | undefined): number | undefined { + if (typeof sent === "number") + return Math.max(cap === undefined ? sent : Math.min(sent, cap), MIN_TTL_MS); + return cap; +} diff --git a/src/agent-device/index.ts b/src/agent-device/index.ts index f4be9891b..dc9f217f4 100644 --- a/src/agent-device/index.ts +++ b/src/agent-device/index.ts @@ -4,6 +4,7 @@ import type { Clock, Logger } from "../ports/index.js"; import { FrontMap } from "./front/front-map.js"; import { createFront } from "./front/front.js"; import { InProcessHostLink, type HostLink } from "./front/host-link.js"; +import { Renewals } from "./front/renewals.js"; import { AgentDeviceHost } from "./host/host.js"; import type { AgentDeviceUpstream } from "./host/upstream.js"; @@ -18,13 +19,23 @@ export { type AgentDeviceHealthProbe, NodeAgentDeviceHealthProbe } from "./host/ export interface AgentDeviceEdgeParts { readonly link: HostLink; readonly map: FrontMap; + readonly renewals: Renewals; } export function createAgentDeviceEdgeParts( upstream: AgentDeviceUpstream, clock: Clock, ): AgentDeviceEdgeParts { - return { link: new InProcessHostLink(new AgentDeviceHost(upstream)), map: new FrontMap(clock) }; + return { + link: new InProcessHostLink(new AgentDeviceHost(upstream)), + map: new FrontMap(clock), + renewals: new Renewals(clock), + }; +} + +// why: a stop ends the gateway's sockets, so the calls that end then must send no renewal that races leasing teardown. +export function disposeAgentDeviceEdge(parts: AgentDeviceEdgeParts): void { + parts.renewals.dispose(); } // why: a stop refuses every dispatch, so waiting allocates' lease requests are cancelled through leasing directly, before the gateway stops; otherwise they stay open across a restart. @@ -37,7 +48,12 @@ export async function cancelWaitingAllocates( export function createAgentDeviceFront( parts: AgentDeviceEdgeParts, - deps: { readonly dispatch: HttpDispatch; readonly clock: Clock; readonly logger: Logger }, + deps: { + readonly dispatch: HttpDispatch; + readonly clock: Clock; + readonly logger: Logger; + readonly leaseTtlCapMs?: number; + }, ): HttpMount { - return createFront({ ...deps, link: parts.link, map: parts.map }); + return createFront({ ...deps, link: parts.link, map: parts.map, renewals: parts.renewals }); } diff --git a/src/agent-device/shared/replies.ts b/src/agent-device/shared/replies.ts index 241b7d9fc..304f64ad7 100644 --- a/src/agent-device/shared/replies.ts +++ b/src/agent-device/shared/replies.ts @@ -1,9 +1,22 @@ -export type ReplyCode = "INVALID_ARGS" | "COMMAND_FAILED"; +export type ReplyCode = "INVALID_ARGS" | "COMMAND_FAILED" | "UNAUTHORIZED"; export interface FrontReply { readonly message: string; readonly code: ReplyCode; readonly status: number; + readonly details?: { readonly reason: string }; +} + +const LEASE_ENDED_MESSAGE = "lease ended by simlock; run disconnect, then open"; + +/** why: the CLI allocates a new lease only for agent-device's own lease-gone reasons, so this one fails the command and prints the message. */ +export function leaseEndedByHost(): FrontReply { + return { + code: "UNAUTHORIZED", + details: { reason: "LEASE_ENDED_BY_HOST" }, + message: LEASE_ENDED_MESSAGE, + status: 200, + }; } export function notAvailable(reason: string): FrontReply { @@ -33,7 +46,11 @@ export function frontReply(reply: FrontReply, rpc: { readonly id: unknown } | un { error: { code: -32000, - data: { code: reply.code, message: reply.message }, + data: { + code: reply.code, + ...(reply.details === undefined ? {} : { details: reply.details }), + message: reply.message, + }, message: reply.message, }, id: rpc.id, diff --git a/src/agent-device/shared/rpc.ts b/src/agent-device/shared/rpc.ts index 603584251..9f0c3cfd4 100644 --- a/src/agent-device/shared/rpc.ts +++ b/src/agent-device/shared/rpc.ts @@ -111,7 +111,11 @@ export function commandLeaseId(params: unknown): string | undefined { export type ReplyReading = | { readonly kind: "success"; readonly result: Record } - | { readonly kind: "error"; readonly code: string | undefined } + | { + readonly kind: "error"; + readonly code: string | undefined; + readonly reason: string | undefined; + } | { readonly kind: "unusable" }; export function readReply(text: string): ReplyReading { @@ -125,8 +129,14 @@ export function readReply(text: string): ReplyReading { if (body === undefined || body["jsonrpc"] !== "2.0") return { kind: "unusable" }; const error = record(body["error"]); if (error !== undefined) { - const code = record(error["data"])?.["code"]; - return { code: typeof code === "string" ? code : undefined, kind: "error" }; + const data = record(error["data"]); + const code = data?.["code"]; + const reason = record(data?.["details"])?.["reason"]; + return { + code: typeof code === "string" ? code : undefined, + kind: "error", + reason: typeof reason === "string" ? reason : undefined, + }; } const result = record(body["result"]); if (result !== undefined && result["ok"] === true && body["error"] === undefined) { @@ -134,3 +144,14 @@ export function readReply(text: string): ReplyReading { } return { kind: "unusable" }; } + +const LEASE_GONE_REASONS = new Set(["LEASE_NOT_FOUND", "LEASE_EXPIRED", "LEASE_REVOKED"]); + +export function leaseGoneReason(reading: ReplyReading): string | undefined { + return reading.kind === "error" && + reading.code === "UNAUTHORIZED" && + reading.reason !== undefined && + LEASE_GONE_REASONS.has(reading.reason) + ? reading.reason + : undefined; +} diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index c1b4ee913..62af4b4e1 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -845,7 +845,11 @@ export const configSchema = z.object({ host: z.string(), port: z.number(), }), - agentDevice: z.object({ enabled: z.boolean(), command: z.string() }), + agentDevice: z.object({ + enabled: z.boolean(), + command: z.string(), + leaseTtlCapMs: z.number().optional(), + }), health: z.object({ enabled: z.boolean(), probeIntervalMs: z.number(), diff --git a/src/core/config.ts b/src/core/config.ts index 604044d21..58167d532 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -253,6 +253,7 @@ export interface Config { readonly agentDevice: { readonly enabled: boolean; readonly command: string; + readonly leaseTtlCapMs?: number; }; /** * ADR 0005 §3/§6. Both sides of the fleet live under one key, and which half is read depends @@ -406,6 +407,7 @@ export async function loadConfig({ overrideConfig, ) as unknown as Config; validateLeaseTtls(merged); + validateAgentDeviceTtlCap(merged); validateEventLogBounds(merged); if (mode === "gateway") { warnWorkerOnlyKeys([fromFile, fromOverrides], warn); @@ -446,6 +448,16 @@ function validateLeaseTtls(config: Config): void { } } +/** why: agent-device's shortest lease window, so a cap below it would shorten leases past what agent-device keeps. */ +const MIN_AGENT_DEVICE_LEASE_TTL_MS = 5_000; + +function validateAgentDeviceTtlCap(config: Config): void { + const cap = config.agentDevice.leaseTtlCapMs; + if (cap !== undefined && cap > config.lease.maxTtlMs) { + throw invalidValue("agentDevice.leaseTtlCapMs", "at most lease.maxTtlMs"); + } +} + /** * Cross-field check: the size cap has to hold the current file and at least one full rotated * generation, or the sweep would delete the history the moment it rotates. @@ -875,7 +887,11 @@ function configValidators(strategy: CapacityStrategyName): Record { if (agentDeviceParts !== undefined) { + disposeAgentDeviceEdge(agentDeviceParts); await cancelWaitingAllocates(agentDeviceParts, (id) => leasing.cancelPending(id)); } await gatewayStarted.catch(() => undefined); @@ -582,6 +584,9 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise Date: Tue, 13 Oct 2026 08:32:59 +0200 Subject: [PATCH 3/7] docs(agent-device): heartbeats renew the simlock lease; agentDevice.leaseTtlCapMs (#473) 2 failing -> 2 failing --- docs/CONFIGURATION.md | 1 + docs/HTTP-API.md | 25 ++++++++++++++++++++----- docs/internal/COMPONENTS.md | 2 +- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 697d33741..d9e8b2f01 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -36,6 +36,7 @@ edit yourself keeps the mode you give it until the next `config set`; run | `gateway.token` | **Worker side.** The join token (`simlock token create --role worker`, minted on the gateway) this worker presents when it opens its uplink. Required whenever `gateway.url` is set. `simlock config` shows it; the daemon log and the `daemon.started` event show `[redacted]`. It is stored in plain text in `config.json`, which `simlock config set` writes owner-only. | unset | | `gateway.label` | **Worker side.** Display name for this worker in `simlock worker list`, `status`, the console, and on the lease's `worker` block. Display-only: nothing routes on it and it need not be unique. | the worker's own id | | `agentDevice.enabled` | **Worker side.** Run one agent-device daemon on this worker, started and watched by Simlock. It sees Simlock's devices and no others, refuses `boot` and `shutdown`, and keeps its files in `~/.simlock/agent-device`. If agent-device is missing, older than 0.21.25, speaks another RPC protocol or needs a newer Node than Simlock runs on, it is not started and Simlock runs on without it. A daemon a killed Simlock left behind is stopped at the next start. With `http.enabled` also `true`, the agent-device CLI reaches it at `/v1/agent-device` (see [HTTP-API.md](HTTP-API.md#v1agent-device)). | `false` | +| `agentDevice.leaseTtlCapMs` | **Worker side.** Caps the TTL of the leases the agent-device CLI makes and renews through Simlock: a longer `ttlMs` is lowered to it, and a lease that sends none gets it. A whole number of milliseconds from `5000` to `lease.maxTtlMs`; a value outside that range stops the daemon at start. Used only when `agentDevice.enabled` is `true`. | unset (no cap) | | `agentDevice.command` | **Worker side.** The agent-device executable: a name looked up on `PATH`, or a path. Used only when `agentDevice.enabled` is `true`. | `agent-device` | | `exec.timeoutMs` | **Worker side.** How long one `device.exec` command (`simlock simctl` / `simlock adb` against a gateway or over HTTP) may run before the worker kills it and the operation fails with `EXEC_TIMEOUT`. Authoritative: it bounds the process that actually runs. | `10 minutes` | | `gateway.routing` | **Gateway side.** Which routing policy places a queued request on a worker. `warm-then-free` is the only policy in v1. Among the workers that can serve the request, in order: a worker whose health is not `running`, or that has requests of its own waiting, is left out; a worker holding a ready device that fits goes first (the device's mode must fit the request, a request with no mode fits a device that serves the worker's default mode, and its runtime must be the one requested or, with none requested, the one the worker would pick: its default runtime if the model pairs with it, otherwise the only runtime the model pairs with); otherwise a worker with no free running slot for the platform or overall is left out (a running device that is not leased counts as free: the worker shuts it down to make room), a worker under its RAM budget for the platform is preferred over one at it (a worker at its budget is still asked when it is the only one left), and the one with the most free running capacity for the platform wins. A worker that is left out is busy, not unable: the request waits for it. Ties go to the lowest worker id. | `warm-then-free` | diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index e8d26a5a3..262d89d3f 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -1481,9 +1481,21 @@ URL answers `404`. token's principal, and the lease ID is the 32-hex ID the CLI chose. `close` ends the agent-device lease and then frees the Simlock lease, so Simlock wipes the device for the next agent. -- **Heartbeats** reach agent-device unchanged. They do not renew the Simlock - lease yet, so a Simlock lease ends at its own TTL; pass `ttlMs` on `open` - for a longer one. +- **Heartbeats keep the lease.** The CLI sends one before every command except + `devices`. Once agent-device answers it, Simlock renews the lease to now plus + its TTL, unless the lease already runs longer (a longer renewal by the agent + stands). A heartbeat's `ttlMs` changes that TTL, at least 5 seconds and at + most `agentDevice.leaseTtlCapMs` when that is set. While a command runs, the + lease is renewed every third of its TTL, and once more when the command ends. + An agent that stops sending heartbeats loses the device one TTL later. +- **A lease Simlock ended is not replaced quietly.** When the lease is gone + because Simlock ended it (`simlock release`, `release --all`, expiry, a lost + device, a restart of the agent-device daemon or of Simlock), the next + heartbeat answers `lease ended by simlock; run disconnect, then open`, as an + `UNAUTHORIZED` error with `details.reason` `LEASE_ENDED_BY_HOST`. A lease the + agent ended through `close` or `disconnect` answers agent-device's own + `LEASE_NOT_FOUND`, so `close` then `open` works. A heartbeat Simlock cannot + renew for another reason answers `COMMAND_FAILED` with Simlock's message. What `open` asks Simlock for: @@ -1492,7 +1504,7 @@ What `open` asks Simlock for: | `--platform ios` or `android` | that platform, any device Simlock grants | | `--target mobile`, `tv`, `desktop` | the class `phone`, `tv`, `desktop` | | `--device "iPhone 17 Pro"` | that model, and no class: the model wins over `--target` | -| `ttlMs` | that TTL, at least 5 seconds; none sent means `lease.defaultTtlMs` | +| `ttlMs` | that TTL, at least 5 seconds and at most `agentDevice.leaseTtlCapMs` when set; none sent means that cap, or `lease.defaultTtlMs` without one | Messages the route prints. The agent-device CLI reads the message in the body (a JSON-RPC error on `/rpc`, `{ "ok": false, "error", "code" }` elsewhere), not @@ -1510,7 +1522,10 @@ the status. sent no lease ID. - `refused: send lease calls as lease RPCs`: a lease call inside `agent_device.command`. -- `refused: ttlMs must be a positive number of milliseconds`. +- `refused: ttlMs must be a positive number of milliseconds`: on `open` and on + a heartbeat. +- `lease ended by simlock; run disconnect, then open`: a heartbeat for a lease + Simlock ended. - `refused: simlock leases only plain devices`: `backend`, `retainOnClose: true`, a `provider*` or `aws*` key, or a `leaseProvider` other than `proxy`. diff --git a/docs/internal/COMPONENTS.md b/docs/internal/COMPONENTS.md index a8d506f29..8741b15a2 100644 --- a/docs/internal/COMPONENTS.md +++ b/docs/internal/COMPONENTS.md @@ -114,7 +114,7 @@ modules with. | `AgentDeviceSupervisor` | `src/agent-device/host/agent-device-supervisor.ts` | Starting, watching and stopping the one agent-device daemon: reaping one a killed simlock left (by a pid record and an identity check), the private state dir and policy file, the daemon's environment, readiness through `daemon.json`, the port and `/health`, restart on death, and the availability state (`off`, `starting`, `running`, `unavailable` with a reason and remedy). | Serve agent-device traffic; report to `simlock doctor`; decide which devices exist (the drivers' environments do). | | Install lookup, compatibility, daemon environment | `src/agent-device/host/install.ts`, `src/agent-device/shared/` | Finding the agent-device install and its daemon entry; the minimum versions and RPC protocol; the environment and policy data. | Run a process. | | `AgentDeviceHealthProbe` | `src/agent-device/host/health.ts` | The `GET /health` read, with a time limit. | Judge the answer. | -| Front | `src/agent-device/front/` | The `/v1/agent-device/*` mount: the role check, the `/rpc` body check, turning an agent-device `allocate` into a simlock `lease.request` (and its cancel when the CLI leaves) and a `release` into a `lease.release`, and the front map of the leases it made. | Check a token (the app does); run the proxy; renew leases (#473). | +| Front | `src/agent-device/front/` | The `/v1/agent-device/*` mount: the role check, the `/rpc` body check, turning an agent-device `allocate` into a simlock `lease.request` (and its cancel when the CLI leaves) and a `release` into a `lease.release`, the front map of the leases it made, and who ended each; the heartbeat, which renews the simlock lease after agent-device answers, and the renewals while a command runs. | Check a token (the app does); run the proxy. | | `AgentDeviceHost`, `AgentDeviceUpstream` | `src/agent-device/host/host.ts`, `host/upstream.ts` | `@agent-device/proxy` in front of the daemon, one proxy per daemon start; the tenant each request acts as; the port the daemon is reached through and its supervisor adapter. | Know simlock leases. | | Wire rules | `src/agent-device/shared/` | The path prefixes, the `/rpc` body reader, the call classifier, the lease-call field reader, the reply reader and the front's replies. | Decide what a call means. | | `FakeAgentDevice` | `src/agent-device/testing.ts` | The in-memory agent-device daemon the proxy sits in front of in tests. | Appear in production code. | From e7a5acdc461e74d2e0c29a7ad85f8124f105d1c9 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 08:33:59 +0200 Subject: [PATCH 4/7] refactor(agent-device): route front calls in one function (#473) 2 failing -> 2 failing --- src/agent-device/front/front.ts | 61 +++++++++++++++++++-------------- 1 file changed, 35 insertions(+), 26 deletions(-) diff --git a/src/agent-device/front/front.ts b/src/agent-device/front/front.ts index f38167fa6..2d7bb3d5f 100644 --- a/src/agent-device/front/front.ts +++ b/src/agent-device/front/front.ts @@ -2,7 +2,13 @@ import type { HttpMount } from "../../http/app.js"; import type { TokenIdentity } from "../../http/token-store.js"; import { FRONT_MOUNT, FRONT_PREFIX } from "../shared/paths.js"; import { failure, frontReply, notAvailable, refusal } from "../shared/replies.js"; -import { classifyCall, commandLeaseId, readRpcBody, type RpcRead } from "../shared/rpc.js"; +import { + classifyCall, + commandLeaseId, + readRpcBody, + type CallClass, + type RpcRead, +} from "../shared/rpc.js"; import { allocate } from "./allocate.js"; import type { FrontContext } from "./context.js"; import { heartbeat } from "./heartbeat.js"; @@ -10,6 +16,14 @@ import { release } from "./release.js"; type RpcRequest = RpcRead & { readonly kind: "request" }; +interface Routed { + readonly identity: TokenIdentity; + readonly kind: CallClass; + readonly leaseMaxTtlMs: number; + readonly read: RpcRequest; + readonly request: Request; +} + const AGENT_TOKEN_ONLY = "refused: agent-device through simlock needs an agent token"; const CLIENT_GONE = 499; @@ -52,37 +66,32 @@ async function handleRpc( if (kind === "wrapped-lease") { return frontReply(refusal("refused: send lease calls as lease RPCs"), read); } + return routeCall(context, { identity, kind, leaseMaxTtlMs: status.leaseMaxTtlMs, read, request }); +} + +async function routeCall( + context: FrontContext, + { identity, kind, leaseMaxTtlMs, read, request }: Routed, +): Promise { if (kind === "allocate") { - const work = allocate(context, { - call: read, - identity, - leaseMaxTtlMs: status.leaseMaxTtlMs, - request, - }).catch((error: unknown) => { - context.logger.error("agent-device allocate failed", { - message: error instanceof Error ? error.message : String(error), - }); - return frontReply(failure("agent-device allocate failed"), read); - }); + const work = allocate(context, { call: read, identity, leaseMaxTtlMs, request }).catch( + (error: unknown) => { + context.logger.error("agent-device allocate failed", { + message: error instanceof Error ? error.message : String(error), + }); + return frontReply(failure("agent-device allocate failed"), read); + }, + ); return untilHangUp(request.signal, work); } + const forwarded = carry(request, read.text); if (kind === "heartbeat") { - return heartbeat(context, { - call: read, - identity, - leaseMaxTtlMs: status.leaseMaxTtlMs, - request: carry(request, read.text), - }); - } - if (kind === "release") { - return release(context, identity, read as RpcRequest, carry(request, read.text)); + return heartbeat(context, { call: read, identity, leaseMaxTtlMs, request: forwarded }); } + if (kind === "release") return release(context, identity, read, forwarded); const leaseId = kind === "command" ? commandLeaseId(read.params) : undefined; - if (leaseId === undefined) return passThrough(context, carry(request, read.text), identity, read); - return runCommand(context, request, identity, read, { - leaseId, - maxRunMs: status.leaseMaxTtlMs, - }); + if (leaseId === undefined) return passThrough(context, forwarded, identity, read); + return runCommand(context, request, identity, read, { leaseId, maxRunMs: leaseMaxTtlMs }); } async function runCommand( From bb8cc2dae707a854139bf6e888a743835dd4ac72 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 08:35:47 +0200 Subject: [PATCH 5/7] fix(agent-device): protocol 31 -> 32, and two heartbeat tests that proved the wrong thing (#473) 0 failing -> 0 failing --- src/agent-device/edge.test.ts | 7 ++++--- src/contract/protocol.ts | 2 +- src/daemon-protocol/index.test.ts | 2 +- src/daemon/server.test.ts | 4 ++-- src/gateway/service.test.ts | 2 +- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 0b3c2cdc6..1d2cc2252 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -1602,6 +1602,7 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(await listed(rig)).toEqual([hex(2)]); await rig.daemon.dispatch("lease.release-all", {}, adminSession); + await advance(rig, 125_000, 25_000); await granted(rig, 3); const received = heartbeatsReceived(rig); @@ -1660,7 +1661,7 @@ describe("the agent-device front, through the whole worker daemon", () => { await granted(rig, 2, { ttlMs: 30_000 }); rig.fake.failNextCommand({ code: "COMMAND_FAILED", message: "the command failed" }); const failing = await runningCommand(rig, 1); - await advance(rig, 25_000, 5_000); + await advance(rig, 15_000, 5_000); rig.fake.releaseCommand(); const failure = await envelopeOf(await failing.promise); expect(failure.error).toMatchObject({ message: "the command failed" }); @@ -1669,13 +1670,13 @@ describe("the agent-device front, through the whole worker daemon", () => { const hangUp = new AbortController(); const hanging = await runningCommand(rig, 2, { signal: hangUp.signal }); - await advance(rig, 25_000, 5_000); + await advance(rig, 15_000, 5_000); hangUp.abort(); await hanging.promise.catch(() => undefined); await expect.poll(() => deadlineOf(rig, 2)).toBe(rig.clock.now() + 30_000); const afterHangUp = await deadlineOf(rig, 2); - await advance(rig, 29_000, 5_000); + await advance(rig, 14_000, 2_000); expect(await deadlineOf(rig, 1)).toBe(afterFailure); expect(await deadlineOf(rig, 2)).toBe(afterHangUp); }); diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index a11ac0b66..ceab5b3f5 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 31, max: 31 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 32, max: 32 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index 88ba00748..df045eb4e 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -9,7 +9,7 @@ import { describe("daemon protocol", () => { it("keeps the current protocol version and newline framing", () => { - expect(DAEMON_PROTOCOL_VERSION).toBe(31); + expect(DAEMON_PROTOCOL_VERSION).toBe(32); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index 93eb37163..c73d49309 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -194,7 +194,7 @@ describe("DaemonServer", () => { [29, "cannot read config.get's agentDevice"], [30, "cannot read the agent-device-unavailable finding in doctor.run"], ])( - "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 31, to a client on protocol %i, which %s", + "answers PROTOCOL_VERSION_UNSUPPORTED, naming protocol 32, to a client on protocol %i, which %s", async (version) => { const harness = await createHarness(); const previous = await createClient(harness.socketPath); @@ -204,7 +204,7 @@ describe("DaemonServer", () => { ).resolves.toMatchObject({ error: { code: "PROTOCOL_VERSION_UNSUPPORTED", - details: { client: { min: version, max: version }, daemon: { min: 31, max: 31 } }, + details: { client: { min: version, max: version }, daemon: { min: 32, max: 32 } }, }, ok: false, }); diff --git a/src/gateway/service.test.ts b/src/gateway/service.test.ts index edbbfee9c..c18fed184 100644 --- a/src/gateway/service.test.ts +++ b/src/gateway/service.test.ts @@ -1207,7 +1207,7 @@ describe("GatewayService", () => { min: PROTOCOL_VERSION_RANGE.max - 1, max: PROTOCOL_VERSION_RANGE.max - 1, }; - expect(PROTOCOL_VERSION_RANGE.max).toBe(31); + expect(PROTOCOL_VERSION_RANGE.max).toBe(32); expect(negotiateProtocolVersion(PROTOCOL_VERSION_RANGE, previous)).toBeUndefined(); const harness = fleet(); await harness.service.start(); From 1b60b029b128a19a158f2495f5f361d246f42046 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 13 Oct 2026 08:51:37 +0200 Subject: [PATCH 6/7] fix(agent-device): a release after release --all marks the entry ended; a running call is capped at lease.maxTtlMs; tests for the surviving mutations (#473) --- src/agent-device/edge.test.ts | 113 +++++++++++++++++++++++++++--- src/agent-device/front/context.ts | 2 + src/agent-device/front/front.ts | 6 +- src/agent-device/front/release.ts | 6 +- src/agent-device/index.ts | 1 + src/daemon/main.ts | 1 + 6 files changed, 116 insertions(+), 13 deletions(-) diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 1d2cc2252..5e2e21c0d 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -245,6 +245,8 @@ function send(rig: Rig, path: string, options: SendOptions = {}): Promise { }); it.each([ - ["300000 with no cap", 300_000, undefined, 300_000], - ["300000 with cap 10000", 300_000, 10_000, 10_000], - ["300000 with cap 600000", 300_000, 600_000, 300_000], - ["none with cap 10000", undefined, 10_000, 10_000], - ["none with no cap", undefined, undefined, defaultTtlMs], - ["1 with no cap", 1, undefined, 5_000], + { cap: undefined, expected: 300_000, row: "300000 with no cap", sent: 300_000 }, + { cap: 10_000, expected: 10_000, row: "300000 with cap 10000", sent: 300_000 }, + { cap: 600_000, expected: 300_000, row: "300000 with cap 600000", sent: 300_000 }, + { cap: 10_000, expected: 10_000, row: "none with cap 10000", sent: undefined }, + { cap: undefined, expected: defaultTtlMs, row: "none with no cap", sent: undefined }, + { cap: undefined, expected: 5_000, row: "1 with no cap", sent: 1 }, ])( - "a CLI `ttlMs` of %s gives the simlock lease, its heartbeat renewal and its renewal interval a TTL of %s ms", - async (_row, sent, cap, expected) => { + "a CLI `ttlMs` of $row gives the simlock lease, its heartbeat renewal and its renewal interval a TTL of $expected ms", + async ({ cap, expected, sent }) => { const rig = await setUp(cap === undefined ? {} : { leaseTtlCapMs: cap }); const ttl = expected as number; await granted(rig, 1, { ttlMs: sent }); @@ -1557,8 +1559,66 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(await listed(rig)).toEqual([hex(1)]); expect(await deadlineOf(rig, 1)).toBe(before); expect(rig.fake.leases.has(hex(1))).toBe(true); + + const own = await envelopeOf(await heartbeat(rig, 1, { ttlMs: 60_000 })); + + expect(own.result).toMatchObject({ ok: true }); + expect(await deadlineOf(rig, 1)).toBe(rig.clock.now() + 60_000); }); + it("a heartbeat naming a lease ID the front map lacks, when the agent-device daemon fails to release its lease, answers that error and leaves the simlock lease in place", async () => { + const first = await setUp(); + await granted(first, 1); + const rig = await first.restart(); + rig.fake.failNextRelease({ code: "COMMAND_FAILED", message: "daemon cannot release" }); + + const failed = await envelopeOf(await heartbeat(rig, 1)); + + expect(failed.error).toMatchObject({ + data: { code: "COMMAND_FAILED" }, + message: "daemon cannot release", + }); + expect(await listed(rig)).toEqual([hex(1)]); + }); + + it("a heartbeat for a lease the agent-device daemon lost, when simlock cannot release its lease, answers `COMMAND_FAILED` with simlock's message and marks nothing, and the next heartbeat releases it and answers `LEASE_ENDED_BY_HOST`", async () => { + const rig = await setUp(); + await granted(rig, 1); + rig.fake.loseLease(hex(1), "LEASE_EXPIRED"); + const tap = tapDispatch(rig); + tap.rejectNext("lease.release"); + + const failed = await envelopeOf(await heartbeat(rig, 1)); + + expect(failed.error).toMatchObject({ + data: { code: "COMMAND_FAILED" }, + message: "simlock could not do that", + }); + expect(await listed(rig)).toEqual([hex(1)]); + + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + expect(await listed(rig)).toEqual([]); + }); + + it.each([0, -5, "soon", true])( + "a heartbeat with a `ttlMs` of %j is refused with `ttlMs must be a positive number of milliseconds`, and neither daemon is reached", + async (ttlMs) => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 60_000 }); + const before = await deadlineOf(rig, 1); + const received = heartbeatsReceived(rig); + await advance(rig, 10_000); + + const refused = await envelopeOf(await heartbeat(rig, 1, { ttlMs })); + + expect(refused.error).toMatchObject( + refusal("refused: ttlMs must be a positive number of milliseconds"), + ); + expect(heartbeatsReceived(rig)).toBe(received); + expect(await deadlineOf(rig, 1)).toBe(before); + }, + ); + it("after a heartbeat answered `LEASE_ENDED_BY_HOST` because simlock ended the lease, the next heartbeat answers it again and the agent-device daemon receives nothing for it", async () => { const rig = await setUp(); await granted(rig, 1); @@ -1610,6 +1670,19 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(heartbeatsReceived(rig)).toBe(received); }); + it("after `simlock release --all` and the agent's release, a heartbeat answers `LEASE_ENDED_BY_HOST` without reaching the agent-device daemon, and a running command's renewals stop", async () => { + const rig = await setUp(); + await granted(rig, 1, { ttlMs: 30_000 }); + await runningCommand(rig, 1); + await rig.daemon.dispatch("lease.release-all", {}, adminSession); + await release(rig, 1); + const received = rig.fake.requests.length; + + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + + expect(rig.fake.requests).toHaveLength(received); + }); + it("a release for a lease simlock ended answers the agent-device daemon's reply as a success, and the agent-device lease is released", async () => { const rig = await setUp(); await granted(rig, 1); @@ -1628,6 +1701,7 @@ describe("the agent-device front, through the whole worker daemon", () => { const rig = await setUp(); await granted(rig, 1, { ttlMs: 30_000 }); await runningCommand(rig, 1); + const tap = tapDispatch(rig); const deadlines: (number | undefined)[] = []; for (let tick = 0; tick < 9; tick += 1) { @@ -1638,8 +1712,26 @@ describe("the agent-device front, through the whole worker daemon", () => { expect(deadlines.every((deadline) => deadline !== undefined)).toBe(true); expect(deadlines.at(-1)).toBeGreaterThan(rig.clock.now()); expect(new Set(deadlines).size).toBeGreaterThan(5); + const checks = tap.operations.filter((name) => name === "lease.list").length; + expect(checks).toBeGreaterThanOrEqual(8); + expect(checks).toBeLessThanOrEqual(9); }); + it("a command that runs on past `lease.maxTtlMs` stops counting as running: its renewals stop, and the lease is no longer kept", async () => { + const rig = await setUp(); + await granted(rig, 1); + const tap = tapDispatch(rig); + await runningCommand(rig, 1); + + await advance(rig, maxTtlMs + 400_000, 100_000); + const calls = frontCalls(tap).length; + await advance(rig, 1_000_000, 100_000); + + expect(calls).toBeGreaterThan(0); + expect(frontCalls(tap)).toHaveLength(calls); + expect(await listed(rig)).toEqual([]); + }, 60_000); + it("when the command ends, the lease is renewed once more, and its deadline does not move again over the next TTL", async () => { const rig = await setUp(); await granted(rig, 1, { ttlMs: 30_000 }); @@ -1745,6 +1837,9 @@ describe("the agent-device front, through the whole worker daemon", () => { const answer = await envelopeOf(await heartbeat(rig, 1)); expectEndedBySimlock(answer); + const received = heartbeatsReceived(rig); + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + expect(heartbeatsReceived(rig)).toBe(received); }); it("a heartbeat lowering the TTL from 300 s to 5 s while a command runs re-arms the renewals, and the lease does not expire before the command ends", async () => { @@ -1858,10 +1953,12 @@ describe("the agent-device front, through the whole worker daemon", () => { await runningCommand(rig, 1); await advance(rig, 12_000, 4_000); const before = await deadlineOf(rig, 1); + const tap = tapDispatch(rig); const stopping = rig.daemon.stop("test"); await advance(rig, 3_000, 1_000).catch(() => undefined); await stopping; + expect(frontCalls(tap)).toEqual([]); const restarted = await rig.restart(); expect(await listed(restarted)).toEqual([hex(1)]); diff --git a/src/agent-device/front/context.ts b/src/agent-device/front/context.ts index cd4653a85..bdd3fb6e6 100644 --- a/src/agent-device/front/context.ts +++ b/src/agent-device/front/context.ts @@ -10,6 +10,8 @@ import type { Renewals } from "./renewals.js"; export interface FrontContext { readonly leaseTtlCapMs?: number; + // why: the longest a lease may live (`lease.maxTtlMs`); a running call stops counting as running after it. + readonly maxRunMs: number; readonly renewals: Renewals; readonly link: HostLink; readonly map: FrontMap; diff --git a/src/agent-device/front/front.ts b/src/agent-device/front/front.ts index 2d7bb3d5f..209acbe50 100644 --- a/src/agent-device/front/front.ts +++ b/src/agent-device/front/front.ts @@ -91,7 +91,7 @@ async function routeCall( if (kind === "release") return release(context, identity, read, forwarded); const leaseId = kind === "command" ? commandLeaseId(read.params) : undefined; if (leaseId === undefined) return passThrough(context, forwarded, identity, read); - return runCommand(context, request, identity, read, { leaseId, maxRunMs: leaseMaxTtlMs }); + return runCommand(context, request, identity, read, leaseId); } async function runCommand( @@ -99,9 +99,9 @@ async function runCommand( request: Request, identity: TokenIdentity, read: RpcRequest, - { leaseId, maxRunMs }: { readonly leaseId: string; readonly maxRunMs: number }, + leaseId: string, ): Promise { - const end = context.renewals.begin(context, leaseId, identity.requesterId, maxRunMs); + const end = context.renewals.begin(context, leaseId, identity.requesterId, context.maxRunMs); request.signal.addEventListener("abort", end, { once: true }); let response: Response; try { diff --git a/src/agent-device/front/release.ts b/src/agent-device/front/release.ts index 5df8d3c35..ff0ccca93 100644 --- a/src/agent-device/front/release.ts +++ b/src/agent-device/front/release.ts @@ -23,8 +23,10 @@ export async function release( context.map.beginRelease(leaseId); const released = await releaseSimlock(context, entry.identity, leaseId); if (released.kind === "released") context.map.markEnded(leaseId, "agent"); - else if (released.kind === "unknown") context.map.markEnded(leaseId, "simlock"); - else context.map.cancelRelease(leaseId); + else { + context.map.cancelRelease(leaseId); + if (released.kind === "unknown") context.map.markEnded(leaseId, "simlock"); + } context.renewals.cancelIfEnded(context, leaseId); } return relay(reply); diff --git a/src/agent-device/index.ts b/src/agent-device/index.ts index dc9f217f4..d58f6baad 100644 --- a/src/agent-device/index.ts +++ b/src/agent-device/index.ts @@ -53,6 +53,7 @@ export function createAgentDeviceFront( readonly clock: Clock; readonly logger: Logger; readonly leaseTtlCapMs?: number; + readonly maxRunMs: number; }, ): HttpMount { return createFront({ ...deps, link: parts.link, map: parts.map, renewals: parts.renewals }); diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 7a0342209..c7fdd566c 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -584,6 +584,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise Date: Tue, 13 Oct 2026 08:57:59 +0200 Subject: [PATCH 7/7] fix(agent-device): clamp renewal timer delays to the setTimeout range; prove renewals stop after release (#473) --- src/agent-device/edge.test.ts | 4 +++ src/agent-device/front/renewals.test.ts | 48 +++++++++++++++++++++++++ src/agent-device/front/renewals.ts | 13 ++++--- 3 files changed, 61 insertions(+), 4 deletions(-) create mode 100644 src/agent-device/front/renewals.test.ts diff --git a/src/agent-device/edge.test.ts b/src/agent-device/edge.test.ts index 5e2e21c0d..823bdc109 100644 --- a/src/agent-device/edge.test.ts +++ b/src/agent-device/edge.test.ts @@ -1677,10 +1677,14 @@ describe("the agent-device front, through the whole worker daemon", () => { await rig.daemon.dispatch("lease.release-all", {}, adminSession); await release(rig, 1); const received = rig.fake.requests.length; + const tap = tapDispatch(rig); expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + await advance(rig, 120_000, 10_000); expect(rig.fake.requests).toHaveLength(received); + expect(tap.operations).not.toContain("lease.list"); + expect(tap.operations).not.toContain("lease.renew"); }); it("a release for a lease simlock ended answers the agent-device daemon's reply as a success, and the agent-device lease is released", async () => { diff --git a/src/agent-device/front/renewals.test.ts b/src/agent-device/front/renewals.test.ts new file mode 100644 index 000000000..0f86d74d2 --- /dev/null +++ b/src/agent-device/front/renewals.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, it } from "vitest"; + +import type { TokenIdentity } from "../../http/token-store.js"; +import { FakeClock } from "../../ports/index.js"; +import type { FrontContext } from "./context.js"; +import { FrontMap } from "./front-map.js"; +import { Renewals } from "./renewals.js"; + +const agent: TokenIdentity = { requesterId: "tok_a", role: "agent" }; +const longestTimerDelayMs = 2 ** 31 - 1; + +describe("the renewals", () => { + it("never asks the clock for a delay past the longest a timer can run, so a huge `lease.maxTtlMs` does not end a running call at once", () => { + const clock = new FakeClock(1_000); + const delays: number[] = []; + const setTimer = clock.setTimer.bind(clock); + clock.setTimer = (ms, callback) => { + delays.push(ms); + return setTimer(ms, callback); + }; + const map = new FrontMap(clock); + map.add("lease-a", { address: "addr", deadline: 9e12, identity: agent, ttlMs: 2 ** 33 }); + const renewals = new Renewals(clock); + const context = { map } as unknown as FrontContext; + + renewals.begin(context, "lease-a", agent.requesterId, 2 ** 40); + + expect(delays.length).toBeGreaterThanOrEqual(2); + expect(Math.max(...delays)).toBeLessThanOrEqual(longestTimerDelayMs); + renewals.dispose(); + }); + + it("stops the renewal timer of a lease that ended, leaving only the running call's own limit timer", () => { + const clock = new FakeClock(1_000); + const map = new FrontMap(clock); + map.add("lease-a", { address: "addr", deadline: 9e12, identity: agent, ttlMs: 60_000 }); + const renewals = new Renewals(clock); + const context = { map } as unknown as FrontContext; + renewals.begin(context, "lease-a", agent.requesterId, 1_800_000); + expect(clock.pendingTimerCount).toBe(2); + + map.markEnded("lease-a"); + renewals.cancelIfEnded(context, "lease-a"); + + expect(clock.pendingTimerCount).toBe(1); + renewals.dispose(); + }); +}); diff --git a/src/agent-device/front/renewals.ts b/src/agent-device/front/renewals.ts index c46d783e8..f64f2581e 100644 --- a/src/agent-device/front/renewals.ts +++ b/src/agent-device/front/renewals.ts @@ -9,6 +9,8 @@ export type RenewOutcome = | { readonly kind: "failed"; readonly message: string }; const TICKS_PER_TTL = 3; +// why: a timer delay above this overflows and fires at once. +const LONGEST_TIMER_DELAY_MS = 2 ** 31 - 1; export async function renewLease( context: FrontContext, @@ -65,7 +67,7 @@ export class Renewals { if (limit !== undefined) this.clock.cancel(limit); this.#finish(context, leaseId, running); }; - limit = this.clock.setTimer(maxRunMs, end); + limit = this.clock.setTimer(Math.min(maxRunMs, LONGEST_TIMER_DELAY_MS), end); return end; } @@ -96,9 +98,12 @@ export class Renewals { this.#disarm(running); const entry = context.map.get(leaseId); if (entry === undefined || entry.endedAt !== undefined) return; - const timer = this.clock.setTimer(entry.ttlMs / TICKS_PER_TTL, () => { - void this.#tick(context, leaseId, running, timer); - }); + const timer = this.clock.setTimer( + Math.min(entry.ttlMs / TICKS_PER_TTL, LONGEST_TIMER_DELAY_MS), + () => { + void this.#tick(context, leaseId, running, timer); + }, + ); running.timer = timer; }