diff --git a/src/agent-device/AGENTS.md b/src/agent-device/AGENTS.md index 2fe578123..db2e7402a 100644 --- a/src/agent-device/AGENTS.md +++ b/src/agent-device/AGENTS.md @@ -8,29 +8,29 @@ Off unless `capabilities.agent-device.enabled` (false). Off: nothing mounted, no ## Files -| File | Role | -| ------------------------------------------------------------- | -------------------------------------------------------------------------------- | -| `definition.ts` | `agentDeviceModule`: config, defaults, cap check; loads `worker.ts` only when on | -| `worker.ts` | `createWorker`: supervisor, edge parts, capability, relay target, mount, hooks | -| `host/agent-device-supervisor.ts` | Reap, start, watch, stop the daemon; availability state | -| `host/install.ts` | `findAgentDevice`: command → install root → daemon entry | -| `host/health.ts` | `NodeAgentDeviceHealthProbe`: `GET /health`, 5 s | -| `host/availability-findings.ts` | `agentDeviceFindings` for `simlock doctor` | -| `host/upstream.ts` | `AgentDeviceUpstream` port; `SupervisorAgentDeviceUpstream` | -| `host/host.ts` | `AgentDeviceHost`: `@agent-device/proxy`, tenant, 2 GiB download cap | -| `host/lease-end.ts` | `ReleaseScopeRecord`, `AgentDeviceLeaseEnd` (lease-end participant) | -| `front/front.ts` | The mount: role check, routes, `/rpc` dispatch by call class | -| `front/request-rules.ts` | Refusals and rewrites before anything is forwarded | -| `front/allocate.ts`, `front/heartbeat.ts`, `front/release.ts` | Lease calls ↔ simlock `lease.*` | -| `front/renewals.ts` | Renews the simlock lease while a command runs | -| `front/front-map.ts` | In-memory leases this front made, and who ended each | -| `front/devices-filter.ts`, `front/token-devices.ts` | `devices` cut to the token's leases | -| `front/host-link.ts` | `HostLink` port; `InProcessHostLink` (worker) | -| `front/relay-host-link.ts` | `RelayHostLink` (gateway); `FleetPort` | -| `front/edge-parts.ts` | Front parts, dispose and cancel steps, `createAgentDeviceFront` | -| `gateway.ts` | Gateway side: `FleetPort` from the gateway context, the mount, `beforeDrain` | -| `shared/` | Paths, routes, RPC reader, replies, compatibility, daemon env, release scope | -| `testing.ts` | `FakeAgentDevice` (in-memory daemon), `FakeAgentDeviceHealth` | +| File | Role | +| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `definition.ts` | `agentDeviceModule`: config, defaults, cap check; loads `worker.ts` only when on | +| `worker.ts` | `createWorker`: supervisor, edge parts, capability, relay target, mount, hooks | +| `host/agent-device-supervisor.ts` | Reap, start, watch, stop the daemon; availability state | +| `host/install.ts` | `findAgentDevice`: command → install root → daemon entry | +| `host/health.ts` | `NodeAgentDeviceHealthProbe`: `GET /health`, 5 s | +| `host/availability-findings.ts` | `agentDeviceFindings` for `simlock doctor` | +| `host/upstream.ts` | `AgentDeviceUpstream` port; `SupervisorAgentDeviceUpstream` | +| `host/host.ts` | `AgentDeviceHost`: `@agent-device/proxy`, tenant, 2 GiB download cap | +| `host/lease-end.ts` | `ReleaseScopeRecord`, `AgentDeviceLeaseEnd` (lease-end participant) | +| `front/front.ts` | The mount: role check, routes, `/rpc` dispatch by call class | +| `front/request-rules.ts` | Refusals and rewrites before anything is forwarded | +| `front/allocate.ts`, `front/heartbeat.ts`, `front/release.ts` | Lease calls ↔ simlock `lease.*` | +| `front/renewals.ts` | Renews the simlock lease while a command runs | +| `front/front-map.ts` | In-memory leases this front made, and who ended each | +| `front/devices-filter.ts`, `front/token-devices.ts` | `devices` cut to the token's leases | +| `front/host-link.ts` | `HostLink` port (`stillHeld`: gateway only, a lease its `lease.list` omits is ended only when the index lost it); `InProcessHostLink` (worker) | +| `front/relay-host-link.ts` | `RelayHostLink` (gateway); `FleetPort` | +| `front/edge-parts.ts` | Front parts, dispose and cancel steps, `createAgentDeviceFront` | +| `gateway.ts` | Gateway side: `FleetPort` from the gateway context, the mount, `beforeDrain` | +| `shared/` | Paths, routes, RPC reader, replies, compatibility, daemon env, release scope | +| `testing.ts` | `FakeAgentDevice` (in-memory daemon), `FakeAgentDeviceHealth` | ## How it works diff --git a/src/agent-device/front/allocate.ts b/src/agent-device/front/allocate.ts index deec2d04c..470e7b634 100644 --- a/src/agent-device/front/allocate.ts +++ b/src/agent-device/front/allocate.ts @@ -274,7 +274,10 @@ export async function allocate( const refused = refusalFor(call.params); if (refused !== undefined) return frontReply(refused, call); const plan = planOf(call.params, context.leaseTtlCapMs); - await context.map.refresh((who) => listLeases(context, who)); + await context.map.refresh( + (who) => listLeases(context, who), + (leaseId) => context.link.stillHeld?.(leaseId) === true, + ); if (request.signal.aborted) return undefined; const outcome = await requestLease(context, identity, plan, request.signal); if (outcome.kind === "gone") return undefined; diff --git a/src/agent-device/front/front-map.ts b/src/agent-device/front/front-map.ts index de0b86fa3..e4a2504c0 100644 --- a/src/agent-device/front/front-map.ts +++ b/src/agent-device/front/front-map.ts @@ -112,7 +112,10 @@ export class FrontMap { held.releasing = false; } - async refresh(list: (identity: Identity) => Promise): Promise { + async refresh( + list: (identity: Identity) => Promise, + stillHeld: (leaseId: string) => boolean = () => false, + ): Promise { this.#prune(); const now = this.clock.now(); const byPrincipal = new Map(); @@ -145,8 +148,9 @@ export class FrontMap { const held = this.#held.get(id); if (held === undefined) continue; const found = listed.find((lease) => lease.id === id); - if (found === undefined) this.markEnded(id); - else held.deadline = found.ttlDeadline; + if (found === undefined) { + if (!stillHeld(id)) this.markEnded(id); + } else held.deadline = found.ttlDeadline; } }), ); diff --git a/src/agent-device/front/host-link.ts b/src/agent-device/front/host-link.ts index 1fe4ad368..f5ff27734 100644 --- a/src/agent-device/front/host-link.ts +++ b/src/agent-device/front/host-link.ts @@ -35,6 +35,8 @@ export interface HostLink { adoptable?(identity: Identity): readonly AdoptableLease[]; // why: a lease the front asked for in this process is its allocate's to keep or release, never to adopt. asked?(leaseId: string): void; + // why: only a link that serves many hosts can tell a lease its list left out for a moment from one the host ended; a worker's list is the source, so a lease missing there is final. + stillHeld?(leaseId: string): boolean; dispose?(): void; } diff --git a/src/agent-device/front/relay-host-link.ts b/src/agent-device/front/relay-host-link.ts index 7d0785da4..4d5b13d30 100644 --- a/src/agent-device/front/relay-host-link.ts +++ b/src/agent-device/front/relay-host-link.ts @@ -231,6 +231,10 @@ export class RelayHostLink implements HostLink { return this.options.fleet.relay(worker.id, request, tenant); } + stillHeld(leaseId: string): boolean { + return this.options.fleet.leaseOf(leaseId) !== undefined; + } + #place(leaseId: string): PlacedLease | undefined { this.#expire(); return this.options.fleet.leaseOf(leaseId) ?? this.#kept.get(leaseId); diff --git a/src/agent-device/front/renewals.ts b/src/agent-device/front/renewals.ts index de3830c98..a017d167c 100644 --- a/src/agent-device/front/renewals.ts +++ b/src/agent-device/front/renewals.ts @@ -23,7 +23,10 @@ export async function renewLease( try { const { leases } = await context.dispatch("lease.list", {}, session); const listed = leases.find((lease) => lease.id === leaseId); - if (listed === undefined) return { kind: "gone" }; + if (listed === undefined) { + if (context.link.stillHeld?.(leaseId) !== true) return { kind: "gone" }; + return { kind: "failed", message: "the gateway's lease list left the lease out; will retry" }; + } if (context.clock.now() + ttlMs > listed.ttlDeadline) { await context.dispatch("lease.renew", { leaseId, ttlMs }, session); } diff --git a/src/agent-device/front/token-devices.ts b/src/agent-device/front/token-devices.ts index 5b306d184..e3df32978 100644 --- a/src/agent-device/front/token-devices.ts +++ b/src/agent-device/front/token-devices.ts @@ -23,7 +23,10 @@ export async function tokenDevices( throw new LeaseCheckFailed(); } for (const entry of held) { - if (!listed.some((lease) => lease.id === entry.leaseId)) context.map.markEnded(entry.leaseId); + if (listed.some((lease) => lease.id === entry.leaseId)) continue; + if (context.link.stillHeld?.(entry.leaseId) !== true) context.map.markEnded(entry.leaseId); } - return context.map.liveOf(identity.principal); + return context.map + .liveOf(identity.principal) + .filter((entry) => listed.some((lease) => lease.id === entry.leaseId)); } diff --git a/src/agent-device/gateway-front.test.ts b/src/agent-device/gateway-front.test.ts index d838edd4f..579aef05e 100644 --- a/src/agent-device/gateway-front.test.ts +++ b/src/agent-device/gateway-front.test.ts @@ -1333,8 +1333,74 @@ describe("the agent-device front, through a gateway", { timeout: 60_000 }, () => expect(beat.error?.message).toBe(`${notAvailable}no relay target agent-device on this worker`); expect((await fleetLeases(rig)).map((lease) => lease.id)).toContain(hex(2)); }); + + it("a lease the gateway's `lease.list` leaves out of one answer, read by a `devices` call, an allocate, a renewal while a command runs, or a heartbeat, is not ended: the next heartbeat succeeds and renews the simlock lease", async () => { + const triggers: Record Promise> = { + allocate: async (rig) => { + await granted(rig, 2); + }, + devices: async (rig) => { + await command(rig, "devices", undefined); + }, + heartbeat: async (rig) => { + await heartbeat(rig, 1); + }, + renewal: async (rig, member) => { + const running = await runningCommand(rig, member, 1); + await advance(rig, 10_000, 5_000); + member.fake.releaseCommand(); + await running.promise; + }, + }; + const outcomes: Record = {}; + + for (const [name, trigger] of Object.entries(triggers)) { + const rig = await setUp({ workers: [{ label: "w1", maxRunning: 2 }] }); + const member = first(rig); + await granted(rig, 1, { ttlMs: 30_000 }); + await listedByGateway(rig, 1); + // why: the front's own record of the deadline is only the grant's, so an allocate re-reads lease 1 only once that has passed; a heartbeat keeps the simlock lease alive meanwhile. + await advance(rig, 20_000, 5_000); + expect((await envelopeOf(await heartbeat(rig, 1, { ttlMs: 30_000 }))).result).toMatchObject({ + ok: true, + }); + await advance(rig, 15_000, 5_000); + const listing = leaveOutOfNextListing(rig.gateway, hex(1)); + + await trigger(rig, member); + await expect.poll(() => listing.cut()).toBe(1); + await advance(rig, 1_000, 1_000); + const answer = await envelopeOf(await heartbeat(rig, 1, { ttlMs: 60_000 })); + + outcomes[name] = { + answer: answer.result ?? answer.error?.data, + cut: listing.cut(), + leftMs: ((await deadlineOf(member, 1)) ?? Number.NaN) - rig.clock.now(), + }; + await Promise.all(runningDaemons.splice(0).map((daemon) => daemon.stop("test"))); + } + + const live = { answer: expect.objectContaining({ ok: true }), cut: 1, leftMs: 60_000 }; + expect(outcomes).toEqual({ allocate: live, devices: live, heartbeat: live, renewal: live }); + }); }); +// why: on a gateway, `lease.list` skips a lease whose worker view is missing for a moment (a reconnect, a starting worker), so the test cuts one lease from exactly one answer to stand for that. +function leaveOutOfNextListing(daemon: DaemonServer, leaseId: string): { cut: () => number } { + const target = daemon as unknown as { dispatch: RawDispatch }; + const original = target.dispatch.bind(target); + let cut = 0; + target.dispatch = async (operation, input, session) => { + const result = await original(operation, input, session); + if (operation !== "lease.list" || cut > 0) return result; + const { leases } = result as { leases: readonly { id: string }[] }; + if (!leases.some((lease) => lease.id === leaseId)) return result; + cut += 1; + return { ...(result as object), leases: leases.filter((lease) => lease.id !== leaseId) }; + }; + return { cut: () => cut }; +} + const LEASE_HEADER = "x-agent-device-lease-id"; const notYoursOnGateway = (n: number): string => `refused: lease ${hex(n)} is not one of yours on this gateway`; @@ -1625,6 +1691,37 @@ describe("the agent-device front, through a gateway: the lease header", { timeou ]); }); + it("through the gateway, `devices` leaves out a lease that was released, and a lease the gateway's `lease.list` omits from that one answer while still holding it", async () => { + const rig = await setUp({ workers: [{ label: "w1", maxRunning: 3 }] }); + for (const n of [1, 2, 3]) await granted(rig, n); + await listedByGateway(rig, 3); + first(rig).fake.listDevices( + [1, 2, 3].map((n) => ({ id: addressOfLease(rig, n), name: `lease-${String(n)}` })), + ); + expect((await envelopeOf(await release(rig, 1))).result).toMatchObject({ ok: true }); + const listing = leaveOutOfNextListing(rig.gateway, hex(2)); + + expect(await listedNames(await command(rig, "devices", undefined))).toEqual(["lease-3"]); + expect(listing.cut()).toBe(1); + expect(await listedNames(await command(rig, "devices", undefined))).toEqual([ + "lease-2", + "lease-3", + ]); + }); + + it("through the gateway, `devices` after `simlock release --all` on the gateway leaves the ended lease out and ends it for the front, so the next heartbeat answers the ended-by-simlock reply without reaching the worker", async () => { + const rig = await setUp({ workers: [{ label: "w1", maxRunning: 2 }] }); + await granted(rig, 1); + await listedByGateway(rig, 1); + first(rig).fake.listDevices([{ id: addressOfLease(rig, 1), name: "lease-1" }]); + await rig.gateway.dispatch("lease.release-all", {}, adminSession); + + expect(await listedNames(await command(rig, "devices", undefined))).toEqual([]); + const received = heartbeatsReceived(first(rig)); + expectEndedBySimlock(await envelopeOf(await heartbeat(rig, 1))); + expect(heartbeatsReceived(first(rig))).toBe(received); + }); + it("through the gateway, `devices` when W2's agent-device answers an error passes that error on; when W2 answers a body with no list, it answers `could not read the device list from the worker holding lease ` with status 502", async () => { const rig = await twoLeasesOnTwoWorkers(); holderOf(rig, 1).fake.listDevices([{ id: addressOfLease(rig, 1), name: "first" }]);