From 28c46f1d1e405906bce0d012f0031d7325619329 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 09:31:54 +0200 Subject: [PATCH 1/3] test(gateway): a worker view read before a release must not refuse the next lease (#898) --- e2e/gateway-smoke.test.ts | 2 +- src/gateway/fleet-coordinator.test.ts | 25 +++++++++++++++++++++++++ src/gateway/lease-index.test.ts | 13 +++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/e2e/gateway-smoke.test.ts b/e2e/gateway-smoke.test.ts index fa9b4888b..4efa8d5f7 100644 --- a/e2e/gateway-smoke.test.ts +++ b/e2e/gateway-smoke.test.ts @@ -448,7 +448,7 @@ describe("gateway smoke", () => { headers: auth, method: "POST", }); - expect(created.status).toBe(201); + expect(created.status, await created.clone().text()).toBe(201); return (await created.json()) as RequestBody; }; const readGranted = async (requestId: string): Promise => { diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index fae0112f0..74ebc1476 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -1619,6 +1619,31 @@ describe("FleetLeaseCoordinator dispatch", () => { expect((retry as RequesterAlreadyLeasedError).existingLeaseId).toBe(grant.lease.id); }); + it("grants a requester's next lease when a worker view read before its release lands after it (#898)", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const first = await coordinator.request(REQUEST, requestOptions()); + client.releaseLeaseQueue.push({ kind: "ok" }); + await coordinator.release(first.lease.id); + + workers.refresh("wrk_a", { + leases: [{ ...leaseFixture("lse_1", "dev_1"), requesterId: `${GATEWAY_PREFIX}agent-1` }], + }); + workers.refresh("wrk_a", { leases: [] }); + + client.requestLeaseQueue.push({ + grant: grantFixture({ lease: leaseFixture("lse_2", "dev_1") as LeaseRecord }), + kind: "grant", + }); + const second = await coordinator + .request(REQUEST, requestOptions({ noWait: true })) + .catch((error: unknown) => error); + expect(second).toMatchObject({ lease: { id: "wrk_a.lse_2" } }); + }); + it("release-all attaches the leases it already released to a later failure's own details (H8)", async () => { const { coordinator, directory, workers, leaseIndex } = harness(); const clientA = new ScriptedWorkerClient(); diff --git a/src/gateway/lease-index.test.ts b/src/gateway/lease-index.test.ts index 0bb7d162f..32fc87d67 100644 --- a/src/gateway/lease-index.test.ts +++ b/src/gateway/lease-index.test.ts @@ -392,6 +392,19 @@ describe("FleetLeaseIndex", () => { expect(index.resolve("wrk_1.ad-7f3a")).toBeUndefined(); }); + it("a caller-chosen ID released and granted again is rebuilt from a later snapshot (#898)", () => { + const index = new FleetLeaseIndex(PREFIX); + const bare = entry({ gatewayLeaseId: "ad-7f3a", workerLeaseId: "ad-7f3a" }); + index.add(bare); + index.remove("ad-7f3a"); + index.add(bare); + index.forgetWorker("wrk_1"); + + index.rebuildFromWorker("wrk_1", [chosen("ad-7f3a")]); + + expect(index.resolve("ad-7f3a")).toMatchObject({ workerId: "wrk_1" }); + }); + it("a rebuilt lease flagged idChosenByRequester whose ID does not match the leaseId pattern is prefixed and logged", () => { const logger = new RecordingLogger(); const index = new FleetLeaseIndex(PREFIX, logger); From 72751f877ecd28d264b834457596ea1b0c307959 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 09:32:49 +0200 Subject: [PATCH 2/3] fix(gateway): a stale worker view no longer brings back a lease the worker released (#898) --- src/gateway/AGENTS.md | 1 + src/gateway/lease-index.ts | 46 ++++++++++++++++++-------------------- 2 files changed, 23 insertions(+), 24 deletions(-) diff --git a/src/gateway/AGENTS.md b/src/gateway/AGENTS.md index 560569dfb..1a0d02729 100644 --- a/src/gateway/AGENTS.md +++ b/src/gateway/AGENTS.md @@ -89,6 +89,7 @@ no TTL timer. Relayed `lease.expired`/`lease.released` remove the entry and push Exec forwards the namespaced requester; `gateway.execTimeoutMs` is a backstop over the worker's `exec.timeoutMs`. The lease index is in memory, rebuilt from each view's leases whose requester starts `gw::`; missing from 2 snapshots in a row → dropped; kept across a disconnect, forgotten with the view. +A lease the worker answered released or `UNKNOWN_LEASE` is not added back by a later snapshot that still lists it. **HTTP relay** (`GatewayRelay.relay`, used by `../agent-device/front/relay-host-link.ts` and `../stream/`): diff --git a/src/gateway/lease-index.ts b/src/gateway/lease-index.ts index 35ad2b867..6c40238b5 100644 --- a/src/gateway/lease-index.ts +++ b/src/gateway/lease-index.ts @@ -73,19 +73,14 @@ export class FleetLeaseIndex { * again by the *next* `rebuildFromWorker` call for that worker: still absent one full * generation later is what promotes "missing" to "gone" (see `rebuildFromWorker`'s own doc). */ readonly #missingSince = new Map(); - /** C1 (round 2 review): gateway lease ids `removeByWorkerLease` just forgot -- an ordinary - * worker-relayed `lease.expired`/`lease.released` -- kept around only long enough to flag the - * one thing that should never legitimately happen next: the *same* id reappearing in a - * `rebuildFromWorker` snapshot moments later. That can only mean a snapshot that started - * gathering data before the relayed fact landed is completing after it, stale by the time it - * arrives; a worker never reissues a lease id, so this is not a real re-grant to admit - * quietly. Bounded (see `#noteRemovedByEvent`) so a long-running gateway's memory does not grow - * with every release it has ever relayed. */ + /** why: an id a relayed `lease.expired`/`lease.released` just forgot that reappears in a + * snapshot means that snapshot is stale, which `#addReported` logs. Bounded so a long-running + * gateway does not remember every release it ever relayed. */ readonly #removedByEvent = new Map(); - /** How many recently-event-removed ids `#removedByEvent` remembers before evicting the - * oldest -- generous relative to how many leases could plausibly be mid-flight across the - * fleet at once, small relative to a gateway's uptime. */ - static readonly #removedByEventCapacity = 200; + /** why: a worker view read before the worker answered a release can land after it and still + * list the lease; re-adding it refuses the requester's next lease until two more views miss it. + * The answer is newer than that view, so `#addReported` skips these ids. */ + readonly #endedByWorkerAnswer = new Map(); constructor( private readonly gatewayRequesterPrefix: string, @@ -158,6 +153,7 @@ export class FleetLeaseIndex { add(entry: FleetLeaseEntry): boolean { const existing = this.#byGatewayId.get(entry.gatewayLeaseId); if (existing !== undefined && existing.workerId !== entry.workerId) return false; + this.#endedByWorkerAnswer.delete(entry.gatewayLeaseId); this.#byGatewayId.set(entry.gatewayLeaseId, entry); const ids = this.#byRequester.get(entry.requesterId) ?? new Set(); ids.add(entry.gatewayLeaseId); @@ -171,6 +167,7 @@ export class FleetLeaseIndex { const entry = this.#byGatewayId.get(gatewayLeaseId); if (entry === undefined) return undefined; this.#forget(entry); + remember(this.#endedByWorkerAnswer, gatewayLeaseId); return entry; } @@ -187,20 +184,10 @@ export class FleetLeaseIndex { const entry = this.findByWorkerLease(workerId, workerLeaseId); if (entry === undefined) return undefined; this.#forget(entry); - this.#noteRemovedByEvent(entry.gatewayLeaseId); + remember(this.#removedByEvent, entry.gatewayLeaseId); return entry; } - /** Records `gatewayLeaseId` as just forgotten by a relayed worker event, for `#addReported`'s - * resurrection check -- see `#removedByEvent`'s own doc. Evicts the oldest entry once the - * bound is hit; `Map` iterates insertion order, so its first key is always the oldest. */ - #noteRemovedByEvent(gatewayLeaseId: string): void { - this.#removedByEvent.set(gatewayLeaseId, true); - if (this.#removedByEvent.size <= FleetLeaseIndex.#removedByEventCapacity) return; - const oldest = this.#removedByEvent.keys().next().value; - if (oldest !== undefined) this.#removedByEvent.delete(oldest); - } - /** * Adds every gateway-issued lease a worker's current view reports that this index does not * already know (ADR §30's reconnect rebuild; also the ordinary per-refresh path, since @@ -256,7 +243,7 @@ export class FleetLeaseIndex { } reported.add(gatewayLeaseId); this.#missingSince.delete(gatewayLeaseId); - if (existing !== undefined) continue; + if (existing !== undefined || this.#endedByWorkerAnswer.has(gatewayLeaseId)) continue; // C1 (round 2 review): this id was forgotten moments ago by the worker's own relayed // `lease.expired`/`lease.released` -- reappearing in a snapshot now means that snapshot // was gathered before the relayed fact landed and is only completing late (see @@ -369,6 +356,17 @@ export class FleetLeaseIndex { } } +// why: generous next to how many leases can be mid-flight at once, small next to a gateway's uptime. +const REMOVED_IDS_CAPACITY = 200; + +// why: a Map iterates in insertion order, so its first key is the oldest to evict. +function remember(ids: Map, gatewayLeaseId: string): void { + ids.set(gatewayLeaseId, true); + if (ids.size <= REMOVED_IDS_CAPACITY) return; + const oldest = ids.keys().next().value; + if (oldest !== undefined) ids.delete(oldest); +} + function workerKey(workerId: string, workerLeaseId: string): string { return `${workerId} ${workerLeaseId}`; } From 5463be2052481d0ad57d0f1de1ea2c918c86328c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 23 Oct 2026 11:26:50 +0200 Subject: [PATCH 3/3] fix(gateway): mark a release as answered even when its relayed event already forgot the lease (#898) --- src/gateway/AGENTS.md | 3 +-- src/gateway/fleet-coordinator.test.ts | 29 +++++++++++++++++++++++++++ src/gateway/lease-index.test.ts | 11 ++++++++++ src/gateway/lease-index.ts | 4 +++- src/gateway/test-support.ts | 4 ++++ 5 files changed, 48 insertions(+), 3 deletions(-) diff --git a/src/gateway/AGENTS.md b/src/gateway/AGENTS.md index 1a0d02729..64a5ffe42 100644 --- a/src/gateway/AGENTS.md +++ b/src/gateway/AGENTS.md @@ -88,8 +88,7 @@ no live link → `WORKER_UNREACHABLE`; a worker `UNKNOWN_LEASE` drops the entry. no TTL timer. Relayed `lease.expired`/`lease.released` remove the entry and push `lease-lost`. Exec forwards the namespaced requester; `gateway.execTimeoutMs` is a backstop over the worker's `exec.timeoutMs`. The lease index is in memory, rebuilt from each view's leases whose requester starts `gw::`; -missing from 2 snapshots in a row → dropped; kept across a disconnect, forgotten with the view. -A lease the worker answered released or `UNKNOWN_LEASE` is not added back by a later snapshot that still lists it. +missing from 2 snapshots in a row → dropped; kept across a disconnect, forgotten with the view. A lease the worker answered released or `UNKNOWN_LEASE` (even if its relayed event already forgot it) is not added back by a later snapshot that still lists it. **HTTP relay** (`GatewayRelay.relay`, used by `../agent-device/front/relay-host-link.ts` and `../stream/`): diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 74ebc1476..da0d973e6 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -1644,6 +1644,35 @@ describe("FleetLeaseCoordinator dispatch", () => { expect(second).toMatchObject({ lease: { id: "wrk_a.lse_2" } }); }); + it.each(["release", "releaseAll"] as const)( + "grants the next lease when %s's relayed event came before the worker's answer and a stale view follows (#898)", + async (how) => { + const { coordinator, directory, workers, leaseIndex } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const first = await coordinator.request(REQUEST, requestOptions()); + client.onReleaseLease = (leaseId) => leaseIndex.removeByWorkerLease("wrk_a", leaseId); + if (how === "release") await coordinator.release(first.lease.id); + else await coordinator.releaseAll(); + + workers.refresh("wrk_a", { + leases: [{ ...leaseFixture("lse_1", "dev_1"), requesterId: `${GATEWAY_PREFIX}agent-1` }], + }); + workers.refresh("wrk_a", { leases: [] }); + + client.requestLeaseQueue.push({ + grant: grantFixture({ lease: leaseFixture("lse_2", "dev_1") as LeaseRecord }), + kind: "grant", + }); + const second = await coordinator + .request(REQUEST, requestOptions({ noWait: true })) + .catch((error: unknown) => error); + expect(second).toMatchObject({ lease: { id: "wrk_a.lse_2" } }); + }, + ); + it("release-all attaches the leases it already released to a later failure's own details (H8)", async () => { const { coordinator, directory, workers, leaseIndex } = harness(); const clientA = new ScriptedWorkerClient(); diff --git a/src/gateway/lease-index.test.ts b/src/gateway/lease-index.test.ts index 32fc87d67..85d0bee75 100644 --- a/src/gateway/lease-index.test.ts +++ b/src/gateway/lease-index.test.ts @@ -392,6 +392,17 @@ describe("FleetLeaseIndex", () => { expect(index.resolve("wrk_1.ad-7f3a")).toBeUndefined(); }); + it("a stale snapshot does not re-add a lease whose relayed release event arrived before the worker's answer (#898)", () => { + const index = new FleetLeaseIndex(PREFIX); + index.add(entry()); + index.removeByWorkerLease("wrk_1", "lse_1"); + index.remove("wrk_1.lse_1"); + + index.rebuildFromWorker("wrk_1", [reported("lse_1")]); + + expect(index.leaseCount("alice")).toBe(0); + }); + it("a caller-chosen ID released and granted again is rebuilt from a later snapshot (#898)", () => { const index = new FleetLeaseIndex(PREFIX); const bare = entry({ gatewayLeaseId: "ad-7f3a", workerLeaseId: "ad-7f3a" }); diff --git a/src/gateway/lease-index.ts b/src/gateway/lease-index.ts index 6c40238b5..1f3a658d7 100644 --- a/src/gateway/lease-index.ts +++ b/src/gateway/lease-index.ts @@ -165,9 +165,11 @@ export class FleetLeaseIndex { /** Forgets one lease by its gateway id -- the gateway's own `lease.release` completing. */ remove(gatewayLeaseId: string): FleetLeaseEntry | undefined { const entry = this.#byGatewayId.get(gatewayLeaseId); + // why: the worker's `lease.released` event travels the uplink before the RPC reply, so the + // relayed event may already have forgotten the entry; the answer still ends the lease. + remember(this.#endedByWorkerAnswer, gatewayLeaseId); if (entry === undefined) return undefined; this.#forget(entry); - remember(this.#endedByWorkerAnswer, gatewayLeaseId); return entry; } diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index 191de6320..eeab6f2a5 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -329,6 +329,9 @@ export class ScriptedWorkerClient { requestLeaseDefault: RequestLeaseOutcome = { kind: "error", error: noCapacityError() }; readonly renewLeaseQueue: RenewLeaseOutcome[] = []; readonly releaseLeaseQueue: ReleaseLeaseOutcome[] = []; + /** why: a real worker's `lease.released` event reaches the gateway before the release reply; + * a test sets this to relay that event from inside the call. */ + onReleaseLease: ((leaseId: string) => void) | undefined; readonly execQueue: ExecOutcome[] = []; /** * H4 (round 3 review): the `options` most recently passed to `exec` -- captured before @@ -475,6 +478,7 @@ export class ScriptedWorkerClient { this.#throwIfFailing(); const outcome = this.releaseLeaseQueue.shift(); if (outcome?.kind === "error") throw outcome.error; + this.onReleaseLease?.(input.leaseId); return { leaseId: input.leaseId }; }