From 8f1231fdd2456261dfc6819eb88a949c98329270 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 1 Oct 2026 16:10:14 +0200 Subject: [PATCH 1/3] feat(gateway): a worker that answers NO_CAPACITY is asked once per change of its state (#190) --- docs/internal/ARCHITECTURE.md | 12 +- docs/internal/KNOWN-PITFALLS.md | 3 +- src/gateway/fleet-coordinator.test.ts | 158 +++++++++++++++++++------ src/gateway/fleet-coordinator.ts | 76 ++++++++++-- src/gateway/routing/view-state.test.ts | 56 +++++++++ src/gateway/routing/view-state.ts | 28 +++++ 6 files changed, 282 insertions(+), 51 deletions(-) create mode 100644 src/gateway/routing/view-state.test.ts create mode 100644 src/gateway/routing/view-state.ts diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 85d8e0390..71402c20f 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -521,8 +521,16 @@ gateway sends it `lease.request` with **`noWait: true`**: request belongs to that worker and dispatch stops considering it; - an **immediate `NO_CAPACITY`** is the only answer that leaves it queued: it means the view was stale, so the gateway refreshes that worker's view and - the request waits, no worse off than before. A failure *after* work has - begun is the request's own terminal failure, not a return to the queue; + the request waits, no worse off than before. The gateway remembers the + refusal for that request against a key built from the worker's view + (capacity, queue depth, health, devices, lease ids; not timestamps), and + does not pick that worker for that request again while the key is + unchanged: another worker is tried instead, and the refusing worker is + asked once per change of its state, not on every refresh (ADR 0009 §5). A + `noWait` request refused this way gets one more walk without that worker, + and fails with `NO_CAPACITY` if no worker is picked in it. A failure + *after* work has begun is the request's own terminal failure, not a return + to the queue; - a request no worker can serve right now is **passed over, not blocked on**, so an Android request behind an iOS one proceeds the moment Android capacity frees. diff --git a/docs/internal/KNOWN-PITFALLS.md b/docs/internal/KNOWN-PITFALLS.md index f90367ede..5fbe72391 100644 --- a/docs/internal/KNOWN-PITFALLS.md +++ b/docs/internal/KNOWN-PITFALLS.md @@ -882,7 +882,8 @@ gateway is trying to dispatch into — so a machine that `simlock worker list` shows as part of the fleet can be, from the gateway's point of view, persistently full for reasons no one looking at the gateway can see. The gateway's dispatch handles it correctly (a `NO_CAPACITY` answer is treated as -a stale view, the request stays queued and goes elsewhere), so this is a +a stale view: the request stays queued, another worker is tried, and the full +one is asked again only once its reported state changes), so this is a visibility and fairness problem rather than a correctness one. **Why it is accepted:** the worker's own capacity accounting is the single diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 673a20e00..55fdca688 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -445,36 +445,133 @@ describe("FleetLeaseCoordinator dispatch", () => { expect(coordinator.queueDepth).toBe(0); }); - it("leaves a request queued after a stale-view NO_CAPACITY even when the caller asked noWait: true, and refreshes that worker's view", async () => { + it("leaves a request queued after NO_CAPACITY, refreshes that worker's view, and tries it once more when a refresh changes its capacity", async () => { const { coordinator, directory, workers } = harness(); const client = new ScriptedWorkerClient(); directory.add("wrk_a", client); connectWorker(workers, "wrk_a"); client.requestLeaseQueue.push({ error: noCapacityError(), kind: "error" }); - const grantPromise = coordinator.request(REQUEST, requestOptions({ noWait: true })); - let settled = false; - void grantPromise.then( - () => { - settled = true; - }, - () => { - settled = true; - }, - ); - + const grantPromise = coordinator.request(REQUEST, requestOptions()); await tick(); - expect(settled).toBe(false); expect(coordinator.queueDepth).toBe(1); expect(directory.refreshCalls).toEqual(["wrk_a"]); // The refreshed view now has capacity, and this time the worker grants it. + const capacity = statusFixture().capacity; client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); - workers.refresh("wrk_a", {}); // any refresh re-runs dispatch, exactly as a real one would + workers.refresh("wrk_a", { + capacity: { ...capacity, ios: { ...capacity.ios, maxRunning: 3 } }, + }); + + const grant = await grantPromise; + expect(grant.lease.worker?.id).toBe("wrk_a"); + expect(client.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(2); + }); + + it("sends a worker that keeps answering NO_CAPACITY with an unchanged view one lease.request for that request", async () => { + const { clock, coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + + void coordinator.request(REQUEST, requestOptions()); + await tick(); + for (let refresh = 0; refresh < 3; refresh += 1) { + clock.advance(1_000); // a new lastSeenAt on every refresh, as a real one has + workers.refresh("wrk_a", { capacity: statusFixture().capacity }); + await tick(); + } + + expect(client.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + expect(coordinator.queueDepth).toBe(1); + }); + + it("tries another eligible worker in the pass that follows a refusal", async () => { + const { coordinator, directory, workers } = harness(); + const preferred = new ScriptedWorkerClient(); + const other = new ScriptedWorkerClient(); + directory.add("wrk_a", preferred); + directory.add("wrk_b", other); + const capacity = statusFixture().capacity; + // wrk_a has more free slots, so free-capacity picks it first. + connectWorker(workers, "wrk_a", { + capacity: { ...capacity, ios: { ...capacity.ios, maxRunning: 4 } }, + }); + connectWorker(workers, "wrk_b"); + other.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + const grantPromise = coordinator.request(REQUEST, requestOptions()); + await tick(); + expect(other.calls.filter((call) => call.startsWith("lease.request"))).toEqual([]); + + // A refresh of wrk_a that changes nothing load-bearing runs the next pass. + workers.refresh("wrk_a", {}); const grant = await grantPromise; + expect(grant.lease.worker?.id).toBe("wrk_b"); + expect(preferred.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + }); + + it("does not exclude a worker for another request because it refused one", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + + void coordinator.request(REQUEST, requestOptions()); + await tick(); + expect(coordinator.queueDepth).toBe(1); + + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const grant = await coordinator.request( + REQUEST, + requestOptions({ ownerId: "agent-2", requesterId: "agent-2" }), + ); + expect(grant.lease.worker?.id).toBe("wrk_a"); + expect(client.calls.filter((call) => call.startsWith("lease.request"))).toEqual([ + `lease.request:${GATEWAY_PREFIX}agent-1`, + `lease.request:${GATEWAY_PREFIX}agent-2`, + ]); + expect(coordinator.queueDepth).toBe(1); + }); + + it("rejects a noWait request refused by its only worker with NO_CAPACITY after one more walk, and reports lease.rejected no-wait", async () => { + const { coordinator, directory, eventBus, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + const rejected: unknown[] = []; + eventBus.subscribe("lease.rejected", (envelope) => rejected.push(envelope.payload)); + + await expect( + coordinator.request(REQUEST, requestOptions({ noWait: true })), + ).rejects.toMatchObject({ code: "NO_CAPACITY" }); + + expect(rejected).toEqual([expect.objectContaining({ reason: "no-wait" })]); + expect(client.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + expect(coordinator.queueDepth).toBe(0); + }); + + it("grants a noWait request refused by one worker from another in the next walk", async () => { + const { coordinator, directory, workers } = harness(); + const preferred = new ScriptedWorkerClient(); + const other = new ScriptedWorkerClient(); + directory.add("wrk_a", preferred); + directory.add("wrk_b", other); + const capacity = statusFixture().capacity; + connectWorker(workers, "wrk_a", { + capacity: { ...capacity, ios: { ...capacity.ios, maxRunning: 4 } }, + }); + connectWorker(workers, "wrk_b"); + other.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + const grant = await coordinator.request(REQUEST, requestOptions({ noWait: true })); + + expect(grant.lease.worker?.id).toBe("wrk_b"); + expect(preferred.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); }); it("terminally rejects, rather than re-queuing, a NO_CAPACITY that arrives after progress already fired (P1, round 2 review)", async () => { @@ -891,7 +988,7 @@ describe("FleetLeaseCoordinator dispatch", () => { const dispatched: unknown[] = []; eventBus.subscribe("request.dispatched", (envelope) => dispatched.push(envelope.payload)); - void coordinator.request(REQUEST, requestOptions({ noWait: true })); + void coordinator.request(REQUEST, requestOptions()); await tick(); expect(dispatched).toEqual([]); @@ -1061,17 +1158,16 @@ describe("FleetLeaseCoordinator dispatch", () => { expect(coordinator.queueDepth).toBe(1); }); - it("a noWait request bounced back by a stale view stays queued even with other requests queued -- §11's exception does not depend on queue depth", async () => { - // §11: "an immediate NO_CAPACITY is the only answer that leaves it queued", and `#staleView` - // applies that unconditionally, "even for a caller that asked noWait: true". Deciding on - // `waiter.state === "queued"` could not tell "never attempted" from "attempted and bounced - // back inside the same pass", so the answer flipped with unrelated queue depth. + it("a noWait request refused by its only worker is rejected even with other requests queued -- the answer does not depend on queue depth", async () => { + // Deciding on `waiter.state === "queued"` could not tell "never attempted" from "attempted + // and refused inside the same pass", so the answer used to flip with unrelated queue depth. 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" }); await coordinator.request(REQUEST, requestOptions()); + // Refused by wrk_a and left queued, so the queue is non-empty. void coordinator.request( REQUEST, requestOptions({ ownerId: "agent-2", requesterId: "agent-2" }), @@ -1079,25 +1175,15 @@ describe("FleetLeaseCoordinator dispatch", () => { await tick(); expect(coordinator.queueDepth).toBe(1); - // A second worker the views advertise but the directory cannot resolve: routing picks it, - // `#attempt` finds no client, and `#staleView` bounces the waiter straight back -- all - // synchronously, inside the admission's own pass. - connectWorker(workers, "wrk_b"); - - let settled = "pending"; - void coordinator - .request( + await expect( + coordinator.request( REQUEST, requestOptions({ noWait: true, ownerId: "agent-3", requesterId: "agent-3" }), - ) - .then( - () => (settled = "granted"), - () => (settled = "rejected"), - ); - await tick(); + ), + ).rejects.toMatchObject({ code: "NO_CAPACITY" }); - expect(settled).toBe("pending"); - expect(coordinator.queueDepth).toBe(2); + expect(client.calls).toContain(`lease.request:${GATEWAY_PREFIX}agent-3`); + expect(coordinator.queueDepth).toBe(1); }); it("relays the worker's own started push for a silent, long-running command -- no output, no answer, still a 200 through a gateway (ADR §19a/§19b/§19e)", async () => { diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index af4bc91cb..d0447d7fd 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -18,7 +18,7 @@ * (it runs once, at admission, before either RPC). `#beginAttempt` calls `queue.markProcessing` * *before* issuing the RPC, taking the waiter out of `queued` state, so `#dispatch`'s own * `queue.list()` scan skips it for the whole in-flight window; the waiter only becomes `queued` - * again (via `#enqueue`, from `#staleView`) once that attempt has fully settled. There used to be + * again (via `#enqueue`, from `#staleView`) once that attempt has fully settled, or is rejected. There used to be * a second guard here too -- a `Map` keyed by in-flight target -- but once * every exit from `#attempt` clears its waiter's processing state in exactly one place (the * `finally` below), the two checks can never disagree: nothing can observe a waiter that is both @@ -70,6 +70,7 @@ import { type LeaseRequestOptions, } from "./queue.js"; import type { RoutableRequest, RoutingDecision, RoutingPolicy } from "./routing.js"; +import { viewLoadKey } from "./routing/view-state.js"; export interface FleetExecInput { readonly leaseId: string; @@ -135,6 +136,10 @@ export class FleetLeaseCoordinator { * explicit clean-up call on every one of those exits to avoid an unbounded leak; the entry is * reclaimable the moment nothing else still references the waiter. */ readonly #createdAt = new WeakMap(); + /** ADR 0009 §5: per waiter, each worker that answered it an immediate `NO_CAPACITY`, and that + * worker's `viewLoadKey` at the time. The worker is not picked again for that waiter while its + * key is unchanged. A `WeakMap` so the memo dies with the waiter. */ + readonly #refusals = new WeakMap>(); /** C1 (round 3 review): re-entrancy guard for `#dispatch` -- see its own doc comment. */ #dispatchDepth = 0; /** Set when a pass is requested while one is already running; the running pass then repeats @@ -581,8 +586,8 @@ export class FleetLeaseCoordinator { * module graph into ordinary worker startup with no boundary test covering that direction. */ #admit(waiter: FleetWaiter): void { - // Attempted -- including attempted and bounced straight back by a stale view, which §11 - // keeps queued even for a `noWait` caller (`#staleView` has already re-enqueued it). + // Attempted. If that attempt is refused, `#attempt` decides the rest: one more walk for a + // `noWait` caller (ADR 0009 §5). A target that turned out unreachable re-queues it. if (this.#dispatch(waiter)) return; if (waiter.options.noWait === true) { this.#reject( @@ -672,21 +677,28 @@ export class FleetLeaseCoordinator { * **last**, because it is the newest: that is what keeps ADR §10's single fleet FIFO honest, * since an admission can never take a slot an already-queued waiter would have had. Returns * whether the candidate was attempted, which is what lets `#admit` tell "nothing could serve - * it" from "it was attempted and bounced straight back by a stale view" -- §11 keeps the - * second one queued even for a `noWait` caller, and `waiter.state` alone cannot distinguish - * them (round 4 review, finding 2). + * it" from "it was attempted" -- the attempt, not `#admit`, settles a `noWait` caller whose + * worker refuses it, and `waiter.state` alone cannot distinguish the two (round 4 review, + * finding 2). `candidate` may also be a waiter whose attempt was just refused (`#attempt`'s + * one more walk for a `noWait` caller); it is not walked twice if it is already queued. + * + * A worker that refused a waiter is left out of that waiter's views while its view is + * unchanged (`#refused`, ADR 0009 §5). This is the one place that exclusion is applied, the + * same place as the per-pass claim set. */ #dispatchPass(candidate?: FleetWaiter): boolean { let candidateAttempted = false; const claimedThisPass = new Set(); const waiters = - candidate === undefined ? this.#queue.list() : [...this.#queue.list(), candidate]; + candidate === undefined || this.#queue.isQueued(candidate) + ? this.#queue.list() + : [...this.#queue.list(), candidate]; for (const waiter of waiters) { // The candidate is not in the queue yet, so it has no `queued` state to check. if (waiter !== candidate && waiter.state !== "queued") continue; const eligibleWorkers = this.options.views .views() - .filter((worker) => !claimedThisPass.has(worker.id)); + .filter((worker) => !claimedThisPass.has(worker.id) && !this.#refused(waiter, worker)); const decision = this.options.routing.select(routable(waiter), eligibleWorkers); if (decision === undefined) continue; claimedThisPass.add(decision.workerId); @@ -725,8 +737,12 @@ export class FleetLeaseCoordinator { * the catch block's own `queue.reject` -- also each call `#dispatch()` themselves, right after. * `#staleView`'s own branches (the unreachable-target check above, and the catch's immediate * `NO_CAPACITY`) do not need to: both already call a worker's `refresh()`, and a real snapshot - * landing for it fires `#onViewsChanged` -> `#dispatch()` regardless of whether the numbers - * actually changed. The terminal branches have no such follow-up of their own -- a worker this + * landing for it fires `#onViewsChanged` -> `#dispatch()`. That pass offers the waiter to every + * other worker; it offers it to a worker that answered `NO_CAPACITY` only once that worker's + * view has changed (ADR 0009 §5), so a worker that keeps refusing is asked once per change of + * its state, not on every refresh. A `noWait` waiter refused with `NO_CAPACITY` is not + * re-queued: it gets one more walk here, and is rejected if no worker is picked in it. The + * terminal branches have no such follow-up of their own -- a worker this * class gave up on (`WORKER_UNREACHABLE`, `INTERNAL`) or was refused for a reason genuinely * unrelated to capacity (any other worker-side code) may still be exactly the worker a different * queued waiter needs, and nothing else would ever schedule that second look. @@ -826,6 +842,23 @@ export class FleetLeaseCoordinator { // work already started means the request was this worker's (§11's own wording). Re-queuing // it anyway silently reversed a dispatch the caller had already been told about. if (isSimlockError(error) && error.code === "NO_CAPACITY" && !announced) { + this.#rememberRefusal(waiter, workerId); + if (waiter.options.noWait === true) { + this.#refreshView(workerId); + // ADR 0009 §5: one more walk, with this worker left out until its view changes. A + // `noWait` caller never asked to wait for that change. + if (!this.#dispatch(waiter)) { + this.#reject( + waiter, + new DispatchError( + "NO_CAPACITY", + "No worker in the fleet can currently serve this request", + ), + "no-wait", + ); + } + return; + } this.#staleView(waiter, workerId); return; } @@ -878,10 +911,15 @@ export class FleetLeaseCoordinator { } /** ADR §11: "an immediate `NO_CAPACITY` is the only answer that leaves it queued ... the - * request waits" -- unconditionally, even for a caller that asked `noWait: true` (the one - * explicit exception the ADR calls out), because this is a stale view, not a real refusal. */ + * request waits", because this is a stale view, not a real refusal. A `noWait` caller reaches + * this only from a target that turned out unreachable; a `noWait` caller refused with + * `NO_CAPACITY` is settled in `#attempt` instead (ADR 0009 §5). */ #staleView(waiter: FleetWaiter, workerId: string): void { this.#enqueue(waiter); + this.#refreshView(workerId); + } + + #refreshView(workerId: string): void { const target = this.options.directory.target(workerId); void target?.refresh().catch((error: unknown) => { this.#logger.debug("Failed to refresh a worker's view after a stale-view NO_CAPACITY", { @@ -891,6 +929,20 @@ export class FleetLeaseCoordinator { }); } + #rememberRefusal(waiter: FleetWaiter, workerId: string): void { + const view = this.options.views.views().find((worker) => worker.id === workerId); + if (view === undefined) return; + const refusals = this.#refusals.get(waiter) ?? new Map(); + refusals.set(workerId, viewLoadKey(view)); + this.#refusals.set(waiter, refusals); + } + + /** Whether `worker` refused `waiter` and its view has not changed since. */ + #refused(waiter: FleetWaiter, worker: WorkerView): boolean { + const key = this.#refusals.get(waiter)?.get(worker.id); + return key !== undefined && key === viewLoadKey(worker); + } + /** * H6 (round 2 review): the entry's `ownerId` comes from `waiter.options.ownerId` -- what this * gateway itself forwarded as `owner` in the `lease.request` a moment ago -- never from the diff --git a/src/gateway/routing/view-state.test.ts b/src/gateway/routing/view-state.test.ts new file mode 100644 index 000000000..aa2929bf0 --- /dev/null +++ b/src/gateway/routing/view-state.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vitest"; + +import { deviceFixture, leaseFixture, statusFixture } from "../test-support.js"; +import type { WorkerView } from "../worker-registry.js"; +import { viewLoadKey } from "./view-state.js"; + +function view(overrides: Partial = {}): WorkerView { + return { + capacity: statusFixture().capacity, + catalog: [], + connection: "connected", + devices: [{ ...deviceFixture("dev_1", "leased"), transitionAgeMs: 10 }], + drained: false, + health: "running", + id: "wrk_a", + lastSeenAt: 1_000, + leases: [leaseFixture("lse_1", "dev_1")], + queueDepth: 0, + ...overrides, + }; +} + +describe("viewLoadKey", () => { + it("gives two views that differ only in lastSeenAt or transitionAgeMs the same key", () => { + const base = view(); + const later = view({ + devices: [{ ...deviceFixture("dev_1", "leased"), transitionAgeMs: 5_000 }], + lastSeenAt: 9_000, + }); + + expect(viewLoadKey(later)).toBe(viewLoadKey(base)); + }); + + it("gives views that differ in capacity, queue depth, health, a device's state, or lease ids different keys", () => { + const base = viewLoadKey(view()); + const capacity = statusFixture().capacity; + const changed = [ + view({ capacity: { ...capacity, ios: { ...capacity.ios, running: 1 } } }), + view({ queueDepth: 1 }), + view({ health: "failed" }), + view({ devices: [deviceFixture("dev_1", "ready")] }), + view({ leases: [leaseFixture("lse_2", "dev_1")] }), + ]; + + for (const other of changed) expect(viewLoadKey(other)).not.toBe(base); + }); + + it("does not depend on the order fields were written in", () => { + const base = view(); + const capacity = Object.fromEntries( + Object.entries(statusFixture().capacity).reverse(), + ) as WorkerView["capacity"]; + + expect(viewLoadKey(view({ capacity }))).toBe(viewLoadKey(base)); + }); +}); diff --git a/src/gateway/routing/view-state.ts b/src/gateway/routing/view-state.ts new file mode 100644 index 000000000..ef7448538 --- /dev/null +++ b/src/gateway/routing/view-state.ts @@ -0,0 +1,28 @@ +/** + * What a worker's `NO_CAPACITY` refusal is remembered against (ADR 0009 §5): the part of its + * view that decides whether it can take one more request. A refusal holds while this key is + * unchanged, so it leaves out what changes on every read -- `lastSeenAt` on the view and + * `transitionAgeMs` on each device -- or the memo would never hold. + */ +import type { WorkerView } from "../worker-registry.js"; + +export function viewLoadKey(view: WorkerView): string { + return canonicalJson({ + capacity: view.capacity, + devices: view.devices.map(({ transitionAgeMs: _transitionAgeMs, ...device }) => device), + health: view.health, + leases: view.leases.map((lease) => lease.id), + queueDepth: view.queueDepth, + }); +} + +/** JSON with object keys sorted, so two views built in a different field order agree. */ +function canonicalJson(value: unknown): string { + return JSON.stringify(value, (_key, nested: unknown) => + nested !== null && typeof nested === "object" && !Array.isArray(nested) + ? Object.fromEntries( + Object.entries(nested).sort(([left], [right]) => (left < right ? -1 : 1)), + ) + : nested, + ); +} From d04a7a407de16fb9a40ef27dfd1e93618994500b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 1 Oct 2026 16:21:37 +0200 Subject: [PATCH 2/3] fix(gateway): one place rejects a noWait request; cover the queued-candidate guard and the refresh --- src/gateway/fleet-coordinator.test.ts | 41 +++++++++++++++++++++++++- src/gateway/fleet-coordinator.ts | 30 ++++++++----------- src/gateway/routing/view-state.test.ts | 2 +- 3 files changed, 53 insertions(+), 20 deletions(-) diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 55fdca688..76ab1232a 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -538,7 +538,7 @@ describe("FleetLeaseCoordinator dispatch", () => { expect(coordinator.queueDepth).toBe(1); }); - it("rejects a noWait request refused by its only worker with NO_CAPACITY after one more walk, and reports lease.rejected no-wait", async () => { + it("rejects a noWait request refused by its only worker with NO_CAPACITY, reports lease.rejected no-wait, and refreshes that worker's view", async () => { const { coordinator, directory, eventBus, workers } = harness(); const client = new ScriptedWorkerClient(); directory.add("wrk_a", client); @@ -551,10 +551,49 @@ describe("FleetLeaseCoordinator dispatch", () => { ).rejects.toMatchObject({ code: "NO_CAPACITY" }); expect(rejected).toEqual([expect.objectContaining({ reason: "no-wait" })]); + expect(directory.refreshCalls).toEqual(["wrk_a"]); expect(client.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); expect(coordinator.queueDepth).toBe(0); }); + it("sends a queued noWait request refused by one worker to only one other worker in the next walk", async () => { + // The refused waiter is already in the queue (it first met a worker with no client yet), so + // the walk must not offer it twice: once in its queue position and once as the candidate. + const { coordinator, directory, workers } = harness(); + const first = new ScriptedWorkerClient(); + const second = new ScriptedWorkerClient(); + const third = new ScriptedWorkerClient(); + directory.add("wrk_a", first); + directory.add("wrk_b", second); + directory.add("wrk_c", third); + const capacity = statusFixture().capacity; + connectWorker(workers, "wrk_a", { + capacity: { ...capacity, ios: { ...capacity.ios, maxRunning: 6 } }, + }); + connectWorker(workers, "wrk_b", { + capacity: { ...capacity, ios: { ...capacity.ios, maxRunning: 4 } }, + }); + connectWorker(workers, "wrk_c", { + capacity: { ...capacity, ios: { ...capacity.ios, maxRunning: 4 } }, + }); + directory.reachableButNoClient.add("wrk_a"); + second.requestLeaseQueue.push({ kind: "hang" }); + third.requestLeaseQueue.push({ kind: "hang" }); + + void coordinator.request(REQUEST, requestOptions({ noWait: true })); + await tick(); + expect(coordinator.queueDepth).toBe(1); + + directory.reachableButNoClient.delete("wrk_a"); + workers.refresh("wrk_a", {}); + await tick(); + + const leaseRequests = (client: ScriptedWorkerClient) => + client.calls.filter((call) => call.startsWith("lease.request")).length; + expect(leaseRequests(first)).toBe(1); + expect(leaseRequests(second) + leaseRequests(third)).toBe(1); + }); + it("grants a noWait request refused by one worker from another in the next walk", async () => { const { coordinator, directory, workers } = harness(); const preferred = new ScriptedWorkerClient(); diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index d0447d7fd..69c43534e 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -563,7 +563,9 @@ export class FleetLeaseCoordinator { /** * A brand-new waiter's admission. **Architecture rule 10: `noWait` is enforced in exactly one * place.** Every admission goes through `#dispatch`'s one ordered walk, carrying this waiter - * as its `candidate` -- there is no second, out-of-order look of its own. + * as its `candidate` -- there is no second, out-of-order look of its own. A `noWait` waiter + * whose worker answered `NO_CAPACITY` comes back through here too, for its one more walk + * (ADR 0009 §5), so that rejection is decided here as well. * * There used to be two paths here: a direct `routing.select` when the queue was empty, and an * enqueue-then-dispatch when it was not. They answered the same question and drifted, exactly @@ -635,8 +637,8 @@ export class FleetLeaseCoordinator { * recursion -- the outer walk iterates a snapshot and has already claimed workers, so a waiter * freed mid-pass would never be reconsidered (round 4 review, finding 6). * - * `candidate` is a brand-new waiter with no queue membership yet; it walks last and the return - * value says whether it was attempted. See `#dispatchPass`. + * `candidate` is the waiter `#admit` is admitting; it walks last and the return value says + * whether it was attempted. See `#dispatchPass`. * * The deferred passes above deliberately carry **no** candidate, and that is not a dropped * one (round 5 review): a nested `#dispatch` can only be raised from inside a `#beginAttempt`, @@ -673,14 +675,14 @@ export class FleetLeaseCoordinator { /** * One ordered, oldest-first walk -- the single place a waiter is matched to a worker. * - * `candidate` is a brand-new waiter that has no queue membership yet (`#admit`'s). It walks + * `candidate` is `#admit`'s waiter, usually brand new with no queue membership yet. It walks * **last**, because it is the newest: that is what keeps ADR §10's single fleet FIFO honest, * since an admission can never take a slot an already-queued waiter would have had. Returns * whether the candidate was attempted, which is what lets `#admit` tell "nothing could serve * it" from "it was attempted" -- the attempt, not `#admit`, settles a `noWait` caller whose * worker refuses it, and `waiter.state` alone cannot distinguish the two (round 4 review, - * finding 2). `candidate` may also be a waiter whose attempt was just refused (`#attempt`'s - * one more walk for a `noWait` caller); it is not walked twice if it is already queued. + * finding 2). `candidate` may also be a `noWait` waiter whose attempt was just refused, on its + * one more walk; if it is already queued it walks in its queue position only, never twice. * * A worker that refused a waiter is left out of that waiter's views while its view is * unchanged (`#refused`, ADR 0009 §5). This is the one place that exclusion is applied, the @@ -694,7 +696,7 @@ export class FleetLeaseCoordinator { ? this.#queue.list() : [...this.#queue.list(), candidate]; for (const waiter of waiters) { - // The candidate is not in the queue yet, so it has no `queued` state to check. + // The candidate is mid-admission, not `queued`, even when it holds a queue position. if (waiter !== candidate && waiter.state !== "queued") continue; const eligibleWorkers = this.options.views .views() @@ -846,17 +848,9 @@ export class FleetLeaseCoordinator { if (waiter.options.noWait === true) { this.#refreshView(workerId); // ADR 0009 §5: one more walk, with this worker left out until its view changes. A - // `noWait` caller never asked to wait for that change. - if (!this.#dispatch(waiter)) { - this.#reject( - waiter, - new DispatchError( - "NO_CAPACITY", - "No worker in the fleet can currently serve this request", - ), - "no-wait", - ); - } + // `noWait` caller never asked to wait for that change, so `#admit` rejects it if no + // worker is picked. + this.#admit(waiter); return; } this.#staleView(waiter, workerId); diff --git a/src/gateway/routing/view-state.test.ts b/src/gateway/routing/view-state.test.ts index aa2929bf0..aa52b227c 100644 --- a/src/gateway/routing/view-state.test.ts +++ b/src/gateway/routing/view-state.test.ts @@ -45,7 +45,7 @@ describe("viewLoadKey", () => { for (const other of changed) expect(viewLoadKey(other)).not.toBe(base); }); - it("does not depend on the order fields were written in", () => { + it("does not depend on the order the capacity fields were written in", () => { const base = view(); const capacity = Object.fromEntries( Object.entries(statusFixture().capacity).reverse(), From 5b8f7038f8ed42d25e87c97653e376d9bd4c7658 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 1 Oct 2026 16:47:33 +0200 Subject: [PATCH 3/3] fix(gateway): cover a refusal from a worker that left the views; docs say what a refusal now does --- docs/EVENTS.md | 2 +- docs/internal/EVENTS.md | 2 +- src/bus/index.ts | 3 ++- src/gateway/fleet-coordinator.test.ts | 29 +++++++++++++++++++++++++++ src/gateway/fleet-coordinator.ts | 4 +++- 5 files changed, 36 insertions(+), 4 deletions(-) diff --git a/docs/EVENTS.md b/docs/EVENTS.md index a77cacd55..44fa4ab57 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -91,7 +91,7 @@ above on its own behalf, because it owns no devices. | `worker.removed` | worker id, label, reason (operator/retention) | a disconnected worker's view was forgotten: by `simlock worker remove`, or because every lease on it had expired and `gateway.disconnectedRetentionMs` elapsed. Never emitted for a connected worker | WorkerRegistry | implemented | | `worker.drain-started` | worker id, label | `simlock worker drain` flagged a worker: it keeps its leases and receives no new dispatches | WorkerRegistry | implemented | | `worker.drain-ended` | worker id, label | `simlock worker undrain` cleared that flag. The flag lives in the gateway's persisted worker registry, so it survives both a worker reconnect and a gateway restart | WorkerRegistry | implemented | -| `request.dispatched` | request id, worker id, requester id, platform, model, reason (warm-hit/free-capacity), the routing stage that decided, queued duration | the gateway's fleet queue sent a queued request to a worker, and the worker took it — the grant itself, or its first `progress` push, whichever arrives first. An immediate `NO_CAPACITY` is a stale view, not a dispatch, and emits nothing — the request stays queued and is retried on the next pass | FleetLeaseCoordinator | implemented | +| `request.dispatched` | request id, worker id, requester id, platform, model, reason (warm-hit/free-capacity), the routing stage that decided, queued duration | the gateway's fleet queue sent a queued request to a worker, and the worker took it — the grant itself, or its first `progress` push, whichever arrives first. An immediate `NO_CAPACITY` is a stale view, not a dispatch, and emits nothing — the request stays queued, and that worker is not sent it again until its reported state changes; a `--no-wait` request fails with `NO_CAPACITY` instead, unless another worker takes it at once | FleetLeaseCoordinator | implemented | Drain and undrain are idempotent, and an event is a fact about a *change*: draining an already-drained worker succeeds and emits nothing. diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 502157c18..b274fd4e0 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -118,7 +118,7 @@ because it owns no devices. | `worker.removed` | worker id, label, reason (operator/retention) | a disconnected worker's view was forgotten: by `simlock worker remove`, or because every gateway-issued lease on it had expired and `gateway.disconnectedRetentionMs` elapsed. Never emitted for a connected worker (`WORKER_CONNECTED` refuses that) | WorkerRegistry | implemented | | `worker.drain-started` | worker id, label | `simlock worker drain` flagged a worker: it keeps its leases and receives no new dispatches | WorkerRegistry | implemented | | `worker.drain-ended` | worker id, label | `simlock worker undrain` cleared that flag. Nothing else ends a drain: the flag lives in the gateway's persisted worker registry, so it survives both a worker reconnect and a gateway restart | WorkerRegistry | implemented | -| `request.dispatched` | `{ requestId, workerId, requesterId, platform, model, reason, stage, queuedMs }` — `reason` is the routing policy's own `warm-hit`/`free-capacity` distinction (ADR 0005 §13): `warm-hit` when the deciding stage is `warm-hit`, `free-capacity` otherwise; `stage` names the routing stage that decided (ADR 0009 §1, §8); `queuedMs` how long the request sat queued before this dispatch | the gateway's fleet queue sent a queued request to a worker with `noWait: true`, and the worker took it — the grant itself, or its first `progress` push, whichever arrives first (ADR 0005 §11: device work having started means the request is that worker's now). An immediate `NO_CAPACITY` is a stale view, not a dispatch, and emits nothing — the request stays queued and is retried on the next pass | FleetLeaseCoordinator | implemented | +| `request.dispatched` | `{ requestId, workerId, requesterId, platform, model, reason, stage, queuedMs }` — `reason` is the routing policy's own `warm-hit`/`free-capacity` distinction (ADR 0005 §13): `warm-hit` when the deciding stage is `warm-hit`, `free-capacity` otherwise; `stage` names the routing stage that decided (ADR 0009 §1, §8); `queuedMs` how long the request sat queued before this dispatch | the gateway's fleet queue sent a queued request to a worker with `noWait: true`, and the worker took it — the grant itself, or its first `progress` push, whichever arrives first (ADR 0005 §11: device work having started means the request is that worker's now). An immediate `NO_CAPACITY` is a stale view, not a dispatch, and emits nothing — the request stays queued, and that worker is not sent it again until its reported state changes (ADR 0009 §5); a `noWait` request fails with `NO_CAPACITY` instead, unless another worker takes it at once | FleetLeaseCoordinator | implemented | Drain and undrain are idempotent, and an event is a fact about a *change*: draining an already-drained worker succeeds and emits nothing. diff --git a/src/bus/index.ts b/src/bus/index.ts index 40b63a21b..7cb12f580 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -240,7 +240,8 @@ export interface EventMap { * ADR 0005 §11/§22 (#118): the gateway's own dispatch sent a queued request to a worker and * the worker took it (a grant, or the first `progress` push, whichever came first -- device * work having started means the request is that worker's now). A `NO_CAPACITY` refusal is a - * stale view, not a dispatch, and emits nothing -- the request stays queued. + * stale view, not a dispatch, and emits nothing -- the request stays queued, or a `noWait` + * request gets one more walk without that worker (ADR 0009 §5). * * C2 (round 2 review): widened back to what `docs/internal/EVENTS.md` always specified for this row -- * `requesterId`/`platform`/`model` so the fact is self-contained (events rule 6) rather than diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 76ab1232a..40f00b58f 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -538,6 +538,35 @@ describe("FleetLeaseCoordinator dispatch", () => { expect(coordinator.queueDepth).toBe(1); }); + it("leaves a request queued when the worker that refused it left the views before the refusal arrived", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + connectWorker(workers, "wrk_a"); + // The worker goes away between routing and its answer: its view is gone by the time the + // NO_CAPACITY lands, so there is no view left to remember the refusal against. + const target = directory.target.bind(directory); + directory.target = (workerId) => { + const found = target(workerId); + if (found === undefined) return undefined; + return { + ...found, + client: () => { + workers.disconnected(workerId); + void workers.remove(workerId); + return found.client(); + }, + }; + }; + + void coordinator.request(REQUEST, requestOptions()); + await tick(); + + expect(workers.views()).toEqual([]); + expect(client.calls.filter((call) => call.startsWith("lease.request"))).toHaveLength(1); + expect(coordinator.queueDepth).toBe(1); + }); + it("rejects a noWait request refused by its only worker with NO_CAPACITY, reports lease.rejected no-wait, and refreshes that worker's view", async () => { const { coordinator, directory, eventBus, workers } = harness(); const client = new ScriptedWorkerClient(); diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index 69c43534e..f77155f33 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -725,7 +725,9 @@ export class FleetLeaseCoordinator { /** * Every exit from this method leaves `waiter` either terminal (`resolve`/`reject`, inside - * `#settleGrant`/the catch below) or back in `queued` (`#staleView`'s `#enqueue`) -- never + * `#settleGrant`/the catch below), back in `queued` (`#staleView`'s `#enqueue`), or -- a + * `noWait` waiter refused with `NO_CAPACITY` -- handed back to `#admit`, which leaves it + * terminal or `processing` in a new attempt that these same rules govern -- never * stuck `processing` with nothing left to drive it, and never in two places disagreeing about * which. C1 (round 2 review): the first early return used to skip straight to `#staleView` * without first clearing a separate `#dispatchTargets` mark this method used to set -- the mark