From e5a4dc8bbb8ac9ceb91e552ff049772d4443503b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 5 Oct 2026 18:24:09 +0200 Subject: [PATCH 1/3] test: through a gateway, a class or range request is served by a worker that fits (#336) --- e2e/gateway-fast-fail.test.ts | 39 +++++ e2e/gateway-fleet.test.ts | 127 ++++++++++++++- src/gateway/dispatcher.test.ts | 53 +++---- src/gateway/fleet-coordinator.test.ts | 164 ++++++++++++++++++++ src/gateway/routing/request-match.test.ts | 78 +++++++++- src/gateway/routing/serviceability.test.ts | 48 ++++++ src/gateway/routing/stages/warm-hit.test.ts | 69 ++++++++ 7 files changed, 550 insertions(+), 28 deletions(-) diff --git a/e2e/gateway-fast-fail.test.ts b/e2e/gateway-fast-fail.test.ts index ae7345096..107b53e84 100644 --- a/e2e/gateway-fast-fail.test.ts +++ b/e2e/gateway-fast-fail.test.ts @@ -194,6 +194,45 @@ describe("a gateway fails a request no worker can serve at once", () => { expect((await gateway.cli(["release", held.id], FAST)).code).toBe(0); }); + it("fails a class or range request nothing in the fleet can serve at once, with the code a single worker gives", async () => { + const { gateway, join } = await startGateway(); + await join("worker-a", { + ios: { + availableOsVersions: ["18.4", "26.0"], + defaultModels: { phone: ["iPhone 17"] }, + knownModels: ["iPhone 17"], + modelClasses: { "iPhone 17": "phone" }, + }, + }); + await waitForWorkers(gateway, ["worker-a"]); + const ask = (...args: string[]) => + gateway.cli( + ["lease", "--platform", "ios", ...args, "--agent-id", "agent-1", "--detach"], + FAST, + ); + + // No worker lists a model of the class. + const watch = await ask("--class", "watch"); + expectFailure(watch, "UNKNOWN_MODEL", EXIT_UNSERVABLE); + expect(watch.stderr).toContain("watch"); + // Every model of the class pairs with a runtime outside the range, with or without a download. + expectFailure( + await ask("--class", "phone", "--os", "<=17"), + "RUNTIME_MISSING", + EXIT_UNSERVABLE, + ); + expectFailure( + await ask("--class", "phone", "--os", "<=17", "--allow-download"), + "RUNTIME_MISSING", + EXIT_UNSERVABLE, + ); + // A request that names neither model nor class means phone, and the fleet has one. + const granted = await ask(); + expect(granted.code, granted.stderr).toBe(0); + const { lease: held } = granted.json as { lease: { id: string } }; + expect((await gateway.cli(["release", held.id], FAST)).code).toBe(0); + }); + it("fails the HTTP POST of a request no worker can serve, with allowDownload too", async () => { const { baseUrl, gateway, join } = await startGateway(); await join("worker-a", { ios: IPHONE_17 }); diff --git a/e2e/gateway-fleet.test.ts b/e2e/gateway-fleet.test.ts index bf5e2050f..746c278c2 100644 --- a/e2e/gateway-fleet.test.ts +++ b/e2e/gateway-fleet.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { freeLoopbackPort, waitFor, withDaemon } from "./helpers/index.js"; +import { freeLoopbackPort, waitFor, waitForDeviceState, withDaemon } from "./helpers/index.js"; import type { TestEnv } from "./helpers/env.js"; /** @@ -573,6 +573,131 @@ describe("gateway fleet", () => { await expect(lease("android", "pixel_7")).resolves.toBe("Pixel 7"); }); + it("grants an Android --class phone request on the worker holding a warm Pixel, not on one with free capacity", async () => { + const port = await freeLoopbackPort(); + const gateway = await withDaemon({ + configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + driver: "none", + }); + const minted = await gateway.cli(["token", "create", "--role", "worker"]); + const { secret } = minted.json as { secret: string }; + const pixels = { + android: { + availableOsVersions: ["34"], + defaultModels: { phone: ["Pixel 8"] }, + knownModels: ["Pixel 8"], + modelClasses: { "Pixel 8": "phone" }, + }, + } as const; + const join = (label: string) => + withDaemon({ + configOverrides: { gateway: { label, token: secret, url: `ws://127.0.0.1:${port}` } }, + driverScript: pixels, + fakeDriverPlatforms: ["android"], + }); + const warmWorker = await join("worker-warm"); + const freeWorker = await join("worker-free"); + await waitForWorkers( + gateway, + (views) => + views.length === 2 && + views.every((view) => view.connection === "connected" && view.catalog.length > 0), + "both workers connected with their catalogs", + ); + + // Warm one device on the first worker through its own socket, and let it go idle. + const warmed = await warmWorker.cli([ + "lease", + "--platform", + "android", + "--device", + "Pixel 8", + "--detach", + ]); + expect(warmed.code, warmed.stderr).toBe(0); + const { device: warmDevice, lease: warmLease } = warmed.json as { + device: { id: string; driverDeviceId: string }; + lease: { id: string }; + }; + await warmWorker.cli(["release", warmLease.id]); + await waitForDeviceState(warmWorker, warmDevice.driverDeviceId, "ready"); + // Until the gateway's view shows that device ready, a request could miss it. + await waitFor( + async () => { + const status = await gateway.cli(["status", "--json"]); + const devices = (status.json as { devices?: { id: string; state: string }[] }).devices; + return devices?.some((device) => device.state === "ready") === true; + }, + { label: "the warm device ready in the gateway's view", timeout: 30_000 }, + ); + await freeWorker.driverLog.clear(); + + const leased = await gateway.cli( + ["lease", "--platform", "android", "--class", "phone", "--detach"], + { timeout: 30_000 }, + ); + + expect(leased.code, leased.stderr).toBe(0); + const grant = leased.json as { + device: { id: string }; + lease: { worker?: { label?: string } }; + }; + expect(grant.device.id).toBe(warmDevice.id); + expect(grant.lease.worker?.label).toBe("worker-warm"); + const work = (await freeWorker.driverLog.calls()).filter((call) => + ["provision", "makeReady"].includes(call.operation), + ); + expect(work).toEqual([]); + }); + + it("grants --class phone with --os '>=18' through a gateway on a worker whose runtime is in the range, and nothing else", async () => { + const port = await freeLoopbackPort(); + const gateway = await withDaemon({ + configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + driver: "none", + }); + const minted = await gateway.cli(["token", "create", "--role", "worker"]); + const { secret } = minted.json as { secret: string }; + const join = (label: string, osVersion: string) => + withDaemon({ + configOverrides: { + gateway: { label, token: secret, url: `ws://127.0.0.1:${port}` }, + }, + driverScript: { + ios: { + availableOsVersions: [osVersion], + defaultModels: { phone: ["iPhone 17"] }, + knownModels: ["iPhone 17"], + modelClasses: { "iPhone 17": "phone" }, + }, + }, + fakeDriverPlatforms: ["ios"], + }); + // Sorted either way by id, only the range can send the request to the newer worker. + await join("worker-old", "17.5"); + await join("worker-new", "26.0"); + await waitForWorkers( + gateway, + (views) => + views.length === 2 && + views.every((view) => view.connection === "connected" && view.catalog.length > 0), + "both workers connected with their catalogs", + ); + + const leased = await gateway.cli( + ["lease", "--platform", "ios", "--class", "phone", "--os", ">=18", "--detach"], + { timeout: 30_000 }, + ); + + expect(leased.code, leased.stderr).toBe(0); + const grant = leased.json as { + device: { spec: { osVersion: string } }; + lease: { worker?: { label?: string } }; + }; + expect(grant.device.spec.osVersion).toBe("26.0"); + expect(grant.lease.worker?.label).toBe("worker-new"); + }); + it("refuses an uplink whose token is not a worker join token", async () => { const port = await freeLoopbackPort(); const gateway = await withDaemon({ diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index 4a17b7983..d37d72df8 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -840,40 +840,41 @@ describe("GatewayDispatcher", () => { it.each([ ["a class", { class: "phone", platform: "ios" }], ["neither a model nor a class", { platform: "ios" }], + ["a class and an OS range", { class: "phone", osVersion: ">=18", platform: "ios" }], + ["a model and an OS range", { model: "iPhone 17", osVersion: ">=18", platform: "ios" }], ] as const)( - "answers a lease.request naming %s BAD_REQUEST, as a gateway does not route class requests yet", + "serves a lease.request naming %s through a worker that fits, forwarding it as it arrived", async (_label, input) => { - const { directory, dispatcher } = harness(); + const { directory, dispatcher, workers } = harness(); const client = new ScriptedWorkerClient(); directory.add("wrk_1", client); - - await expect( - dispatcher.dispatch("lease.request", input, session({ role: "agent" })), - ).rejects.toMatchObject({ - code: "BAD_REQUEST", - message: expect.stringContaining("does not route class requests yet"), + workers.connected("wrk_1", undefined, "0.3.0"); + workers.refresh("wrk_1", { + capacity: statusFixture().capacity, + health: "running", + queueDepth: 0, + catalog: catalogFixture([ + { + modelClasses: { "iPhone 17": "phone" }, + models: ["iPhone 17"], + platform: "ios", + runtimes: ["26.0"], + }, + ]).platforms, + downloads: { policy: "on-request" }, }); - expect(client.lastRequestLeaseInput).toBeUndefined(); - }, - ); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); - it("answers a lease.request whose osVersion is a range BAD_REQUEST, as a gateway does not route OS ranges yet", async () => { - const { directory, dispatcher } = harness(); - const client = new ScriptedWorkerClient(); - directory.add("wrk_1", client); - - await expect( - dispatcher.dispatch( + await dispatcher.dispatch( "lease.request", - { model: "iPhone 17", osVersion: ">=18", platform: "ios" }, + { ...input, noWait: true }, session({ role: "agent" }), - ), - ).rejects.toMatchObject({ - code: "BAD_REQUEST", - message: expect.stringContaining("does not route OS ranges yet"), - }); - expect(client.lastRequestLeaseInput).toBeUndefined(); - }); + ); + + expect(client.lastRequestLeaseInput).toMatchObject(input); + if (!("model" in input)) expect(client.lastRequestLeaseInput).not.toHaveProperty("model"); + }, + ); it("forwards a lease.request's exact osVersion to the worker unchanged", async () => { const { directory, dispatcher, workers } = harness(); diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index a404d2ca1..adb169d8e 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -3229,3 +3229,167 @@ describe("FleetLeaseCoordinator: queue.changed", () => { ).toEqual(["fleet-lease-coordinator", "fleet-lease-coordinator", "fleet-lease-coordinator"]); }); }); + +describe("FleetLeaseCoordinator routes a class or range request (ADR 0015 §8)", () => { + const phones = { + modelClasses: { "iPhone 16": "phone", "iPhone 17": "phone" }, + models: ["iPhone 16", "iPhone 17"], + platform: "ios" as const, + runtimes: ["18.0", "26.0"], + }; + + function connectWith( + workers: WorkerRegistry, + workerId: string, + entry: Parameters[0][number], + options: { + readonly capacity?: ReturnType["capacity"]; + readonly devices?: ReturnType[]; + } = {}, + ): void { + workers.connected(workerId, undefined, "0.3.0"); + workers.refresh(workerId, { + capacity: options.capacity ?? statusFixture().capacity, + catalog: catalogFixture([entry]).platforms, + devices: options.devices ?? [], + downloads: { policy: "on-request" }, + health: "running", + leases: [], + queueDepth: 0, + }); + } + + function leaseRequests(client: ScriptedWorkerClient): string[] { + return client.calls.filter((call) => call.startsWith("lease.request")); + } + + function single() { + const fleet = harness(); + const client = new ScriptedWorkerClient(); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + fleet.directory.add("wrk_a", client); + connectWith(fleet.workers, "wrk_a", phones); + return { ...fleet, client }; + } + + it("forwards the class and the range as they arrived, with no model", async () => { + const { client, coordinator } = single(); + + await coordinator.request( + { class: "phone", osVersion: ">=18 <26", platform: "ios" }, + requestOptions({ noWait: true }), + ); + + expect(client.lastRequestLeaseInput).toMatchObject({ + class: "phone", + osVersion: ">=18 <26", + platform: "ios", + }); + expect(client.lastRequestLeaseInput).not.toHaveProperty("model"); + }); + + it("forwards a request naming neither model nor class with neither", async () => { + const { client, coordinator } = single(); + + await coordinator.request({ platform: "ios" }, requestOptions({ noWait: true })); + + expect(client.lastRequestLeaseInput).not.toHaveProperty("model"); + expect(client.lastRequestLeaseInput).not.toHaveProperty("class"); + }); + + it("still forwards an exact model under the worker's own name, with no class", async () => { + const { client, coordinator } = single(); + + await coordinator.request( + { model: "iphone 17", platform: "ios" }, + requestOptions({ noWait: true }), + ); + + expect(client.lastRequestLeaseInput?.model).toBe("iPhone 17"); + expect(client.lastRequestLeaseInput).not.toHaveProperty("class"); + }); + + it("emits request.dispatched with class and no model for a class request, and model and no class for an exact one", async () => { + const byClass = single(); + const dispatchedByClass: object[] = []; + byClass.eventBus.subscribe("request.dispatched", (envelope) => + dispatchedByClass.push(envelope.payload), + ); + await byClass.coordinator.request( + { class: "phone", platform: "ios" }, + requestOptions({ noWait: true }), + ); + const exact = single(); + const dispatchedExact: object[] = []; + exact.eventBus.subscribe("request.dispatched", (envelope) => + dispatchedExact.push(envelope.payload), + ); + await exact.coordinator.request( + { model: "iPhone 17", platform: "ios" }, + requestOptions({ noWait: true }), + ); + + expect(dispatchedByClass).toEqual([expect.objectContaining({ class: "phone" })]); + expect(dispatchedByClass[0]).not.toHaveProperty("model"); + expect(dispatchedExact).toEqual([expect.objectContaining({ model: "iPhone 17" })]); + expect(dispatchedExact[0]).not.toHaveProperty("class"); + }); + + it("retries a worker's UNKNOWN_MODEL for a class request, before any progress, on another worker", async () => { + const { coordinator, directory, workers } = harness(); + const a = new ScriptedWorkerClient(); + const b = new ScriptedWorkerClient(); + directory.add("wrk_a", a); + directory.add("wrk_b", b); + connectWith(workers, "wrk_a", phones); + connectWith(workers, "wrk_b", phones); + a.requestLeaseQueue.push({ + error: new SimlockError("UNKNOWN_MODEL", "domain", "no model of class phone", { + class: "phone", + platform: "ios", + }), + kind: "error", + }); + b.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + const grant = await coordinator.request( + { class: "phone", platform: "ios" }, + requestOptions({ noWait: true }), + ); + + expect(leaseRequests(a)).toHaveLength(1); + expect(leaseRequests(b)).toHaveLength(1); + expect(grant.lease.worker?.id).toBe("wrk_b"); + }); + + it("dispatches an Android phone request to the worker with a warm Pixel over one with free capacity", async () => { + const { coordinator, directory, workers } = harness(); + const free = new ScriptedWorkerClient(); + const warm = new ScriptedWorkerClient(); + directory.add("wrk_a", free); + directory.add("wrk_b", warm); + warm.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + const pixels = { + modelClasses: { "Pixel 8": "phone" }, + models: ["Pixel 8"], + platform: "android" as const, + runtimes: ["35"], + }; + const ready = deviceFixture("dev_1", "ready"); + // wrk_a sorts first and has the same room, so only the warm device can send it to wrk_b. + connectWith(workers, "wrk_a", pixels); + connectWith(workers, "wrk_b", pixels, { + devices: [ + { ...ready, spec: { model: "Pixel 8", osVersion: "35", platform: "android" as const } }, + ], + }); + + await coordinator.request( + { class: "phone", platform: "android" }, + requestOptions({ noWait: true }), + ); + + expect(leaseRequests(warm)).toHaveLength(1); + expect(leaseRequests(free)).toEqual([]); + }); +}); diff --git a/src/gateway/routing/request-match.test.ts b/src/gateway/routing/request-match.test.ts index 65022f557..26c30126e 100644 --- a/src/gateway/routing/request-match.test.ts +++ b/src/gateway/routing/request-match.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import { catalogFixture, statusFixture } from "../test-support.js"; import type { WorkerView } from "../worker-registry.js"; -import { matchRequest } from "./request-match.js"; +import { listsModel, matchRequest } from "./request-match.js"; function worker(entry: Parameters[0][number]): WorkerView { return { @@ -149,4 +149,80 @@ describe("matchRequest", () => { ).toBeUndefined(); }); }); + + describe("with a class", () => { + const PHONES = { + modelClasses: { "iPad Pro": "tablet", "iPhone 16": "phone", "iPhone 17": "phone" }, + modelRuntimes: { "iPad Pro": ["26.0"], "iPhone 16": ["18.0"], "iPhone 17": ["26.0"] }, + models: ["iPad Pro", "iPhone 16", "iPhone 17"], + platform: "ios" as const, + runtimes: ["18.0", "26.0"], + }; + const phone = { class: "phone" as const, platform: "ios" as const }; + + it("matches a worker whose catalog lists a model of the class paired with a runtime that satisfies the constraint", () => { + expect(matchRequest(worker(PHONES), phone)).toBeDefined(); + expect(matchRequest(worker(PHONES), { ...phone, osVersion: ">=26" })).toBeDefined(); + expect(matchRequest(worker(PHONES), { ...phone, osVersion: "18.0" })).toBeDefined(); + }); + + it("does not match a worker whose models of the class pair only with runtimes outside the range", () => { + expect(matchRequest(worker(PHONES), { ...phone, osVersion: "<18" })).toBeUndefined(); + expect(matchRequest(worker(PHONES), { ...phone, osVersion: "27.0" })).toBeUndefined(); + // The tablet pairs with 26.0, but the class asked for is phone and no phone pairs with 19. + expect(matchRequest(worker(PHONES), { ...phone, osVersion: "19 - 25" })).toBeUndefined(); + }); + + it("does not match a worker with no model of the class", () => { + expect(matchRequest(worker(PHONES), { class: "watch", platform: "ios" })).toBeUndefined(); + expect( + matchRequest(worker(PHONES), { class: "tablet", osVersion: "18.0", platform: "ios" }), + ).toBeUndefined(); + }); + + it("matches a request with neither model nor class as phone", () => { + expect(matchRequest(worker(PHONES), { platform: "ios" })).toBeDefined(); + const tablets = worker({ + ...PHONES, + modelClasses: { "iPad Pro": "tablet" }, + models: ["iPad Pro"], + }); + expect(matchRequest(tablets, { platform: "ios" })).toBeUndefined(); + }); + + it("counts only runtimes with an image of the tag for a class request", () => { + const tagged = worker({ + ...PHONES, + images: [{ abi: "arm64-v8a", runtime: "18.0", tag: "x" }], + }); + + expect(matchRequest(tagged, { ...phone, imageTag: "x", osVersion: ">=18" })).toBeDefined(); + expect(matchRequest(tagged, { ...phone, imageTag: "x", osVersion: ">=26" })).toBeUndefined(); + }); + + it("lists a class when any model of it is listed, whatever it pairs with", () => { + expect(listsModel(worker(PHONES), { ...phone, osVersion: "99" })).toBe(true); + expect(listsModel(worker(PHONES), { class: "watch", platform: "ios" })).toBe(false); + expect(listsModel(worker(PHONES), { platform: "ios" })).toBe(true); + }); + + it("reads no inherited key as a class", () => { + const view = worker({ ...PHONES, modelClasses: {}, models: ["constructor"] }); + + expect(matchRequest(view, phone)).toBeUndefined(); + }); + }); + + it("matches an exact model with a range when one of its paired runtimes is in it", () => { + const view = worker({ + modelRuntimes: { "iPhone 17": ["18.0", "26.0"] }, + models: ["iPhone 17"], + platform: "ios", + runtimes: ["18.0", "26.0"], + }); + const request = { model: "iPhone 17", platform: "ios" as const }; + + expect(matchRequest(view, { ...request, osVersion: ">=26" })).toBe("iPhone 17"); + expect(matchRequest(view, { ...request, osVersion: ">26" })).toBeUndefined(); + }); }); diff --git a/src/gateway/routing/serviceability.test.ts b/src/gateway/routing/serviceability.test.ts index 02ddb3041..5bb9e30c6 100644 --- a/src/gateway/routing/serviceability.test.ts +++ b/src/gateway/routing/serviceability.test.ts @@ -169,4 +169,52 @@ describe("assess", () => { expect(rejectionOf([incompatible, other], REQUEST).code).toBe("UNKNOWN_MODEL"); }); + + describe("a class request", () => { + const PHONE: CatalogEntry = { + modelClasses: { "iPhone 17": "phone" }, + models: ["iPhone 17"], + platform: "ios", + runtimes: ["26.0"], + }; + const request = { class: "phone" as const, platform: "ios" as const }; + + it("row 3: when no known worker lists a model of the class, says UNKNOWN_MODEL with the class in its details", () => { + expect(rejectionOf([view("wrk_a", PHONE)], { ...request, class: "watch" })).toMatchObject({ + code: "UNKNOWN_MODEL", + details: { class: "watch", platform: "ios" }, + reason: "unresolvable-spec", + }); + const details = rejectionOf([view("wrk_a", PHONE)], { ...request, class: "watch" }).details; + expect(details).not.toHaveProperty("model"); + }); + + it("row 3: treats a request naming neither model nor class as phone", () => { + const tablets: CatalogEntry = { + modelClasses: { "iPad Pro": "tablet" }, + models: ["iPad Pro"], + platform: "ios", + runtimes: ["26.0"], + }; + + expect(rejectionOf([view("wrk_a", tablets)], { platform: "ios" })).toMatchObject({ + code: "UNKNOWN_MODEL", + details: { class: "phone", platform: "ios" }, + }); + }); + + it("row 4: when models of the class pair with no runtime in the range, says RUNTIME_MISSING with the range as typed", () => { + expect(rejectionOf([view("wrk_a", PHONE)], { ...request, osVersion: "<=17" })).toMatchObject({ + code: "RUNTIME_MISSING", + details: { downloadable: false, osVersion: "<=17", platform: "ios" }, + message: "Runtime missing for ios <=17", + }); + }); + + it("row 6: routes a class request a worker can serve", () => { + expect(assess({ ...request, osVersion: ">=18" }, [view("wrk_a", PHONE)]).kind).toBe( + "route-or-wait", + ); + }); + }); }); diff --git a/src/gateway/routing/stages/warm-hit.test.ts b/src/gateway/routing/stages/warm-hit.test.ts index d533c1f76..ceeeaa036 100644 --- a/src/gateway/routing/stages/warm-hit.test.ts +++ b/src/gateway/routing/stages/warm-hit.test.ts @@ -228,4 +228,73 @@ describe("warm-hit", () => { expect(warmHit.score(view(catalog, "18.0"), request)).toBe(0); }); }); + + describe("a class or range request", () => { + const catalog = { + defaultRuntime: "26.0", + modelClasses: { "iPad Pro": "tablet", "iPhone 15": "phone", "iPhone 17": "phone" }, + models: ["iPad Pro", "iPhone 15", "iPhone 17"], + platform: "ios" as const, + runtimes: ["18.0", "26.0"], + }; + const view = ( + spec: Partial, + device: Partial> = {}, + ): WorkerView => { + const ready = deviceFixture("d", "ready"); + return { + capacity: statusFixture().capacity, + catalog: catalogFixture([catalog]).platforms, + connection: "connected", + devices: [{ ...ready, ...device, spec: { ...ready.spec, ...spec } }], + drained: false, + id: "wrk_a", + lastSeenAt: 1, + leases: [], + }; + }; + const phone = { class: "phone" as const, platform: "ios" as const }; + + it("counts a ready device of another model in the requested class as warm, and one of another class as not", () => { + expect(warmHit.score(view({ model: "iPhone 15" }), phone)).toBe(1); + expect(warmHit.score(view({ model: "iPad Pro" }), phone)).toBe(0); + expect(warmHit.score(view({ model: "iPad Pro" }), { ...phone, class: "tablet" })).toBe(1); + expect(warmHit.score(view({ model: "iPhone 15" }), { platform: "ios" })).toBe(1); + expect(warmHit.score(view({ model: "iPad Pro" }), { platform: "ios" })).toBe(0); + }); + + it("counts a ready device on any version as warm for a class request naming none", () => { + expect(warmHit.score(view({ osVersion: "18.0" }), phone)).toBe(1); + expect(warmHit.score(view({ osVersion: "26.0" }), phone)).toBe(1); + }); + + it("does not count a ready device whose OS is outside the range as warm", () => { + expect(warmHit.score(view({ osVersion: "18.0" }), { ...phone, osVersion: ">=26" })).toBe(0); + expect(warmHit.score(view({ osVersion: "26.0" }), { ...phone, osVersion: ">=26" })).toBe(1); + expect(warmHit.score(view({ osVersion: "26.0" }), { ...phone, osVersion: "<=18" })).toBe(0); + expect(warmHit.score(view({ osVersion: "18.0" }), { ...phone, osVersion: "18 - 19" })).toBe( + 1, + ); + }); + + it("does not count a device in a mode the request refuses as warm", () => { + const slim = deviceFixture("d", "ready", "slim", false); + + expect(warmHit.score(view({}, slim), { ...phone, mode: "full" })).toBe(0); + expect(warmHit.score(view({}, slim), phone)).toBe(0); + expect(warmHit.score(view({}, slim), { ...phone, mode: "slim" })).toBe(1); + }); + + it("does not count a device of another image tag as warm for a class request", () => { + expect(warmHit.score(view({ imageTag: "x" }), phone)).toBe(0); + }); + + it("counts a ready device of the model a request names as warm inside a range, and none outside it", () => { + const exact = { model: "iPhone 17", platform: "ios" as const }; + + expect(warmHit.score(view({}), { ...exact, osVersion: ">=26" })).toBe(1); + expect(warmHit.score(view({}), { ...exact, osVersion: "<26" })).toBe(0); + expect(warmHit.score(view({ model: "iPhone 15" }), { ...exact, osVersion: ">=18" })).toBe(0); + }); + }); }); From 31452031c94ba7b23108c0005e7979f8777fae02 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 5 Oct 2026 18:31:55 +0200 Subject: [PATCH 2/3] feat(gateway): a class or range request is served by a worker that fits 6 failing -> 0 failing --- docs/CLI.md | 20 ++- docs/CLIENT.md | 6 +- docs/EVENTS.md | 2 +- docs/HTTP-API.md | 14 +- docs/internal/ARCHITECTURE.md | 42 ++++-- docs/internal/EVENTS.md | 6 +- src/bus/index.ts | 5 +- src/gateway/boundary.test.ts | 5 +- src/gateway/dispatcher.test.ts | 4 +- src/gateway/dispatcher.ts | 19 +-- src/gateway/fleet-coordinator.test.ts | 6 +- src/gateway/fleet-coordinator.ts | 34 +++-- src/gateway/queue.ts | 10 +- src/gateway/routing/pipeline.ts | 7 +- src/gateway/routing/request-match.test.ts | 10 +- src/gateway/routing/request-match.ts | 152 +++++++++++++------- src/gateway/routing/serviceability.test.ts | 4 +- src/gateway/routing/serviceability.ts | 38 +++-- src/gateway/routing/stages/warm-hit.test.ts | 2 +- src/gateway/routing/stages/warm-hit.ts | 38 +++-- 20 files changed, 271 insertions(+), 153 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index be35bc29c..ecbcc296e 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -478,8 +478,10 @@ got. A class is a claim about the device type the platform's tools report: on iOS the product family, on Android the profile's tag, and every untagged Android profile is a `phone`, so `tablet` holds no Android model. -Through a gateway, a lease that names no model is refused with `BAD_REQUEST` -for now. +Through a gateway the same requests work: a class, no model at all, and an +`--os` range are served by any worker that has something fitting, and the +gateway passes them on to that worker as they arrived (see +[Against a gateway](#against-a-gateway)). ### `simlock lease renew [--ttl ]` @@ -731,6 +733,16 @@ is preferred over one at it, and the one with the most free capacity gets the request. You do not name a machine and there is no flag to; where a device lives is the gateway's decision. +A request with `--class`, or with neither `--device` nor `--class` (which means +`--class phone`), is served by a worker whose catalog lists a model of that +class paired with an installed runtime that satisfies `--os` (any installed +runtime when you give none). With `--os` as a range, a model matches when one of +its paired runtimes is in the range. A warm device matches a class request when +its model is of that class on that worker, its runtime is in the range (any +installed runtime with no `--os`), and its mode and image tag fit as above. The +gateway does not pick the model or the runtime: the worker does, by its own +rules, so the grant names what you got. + ### A request no worker can serve A lease through a gateway never waits for something that cannot arrive. A @@ -745,8 +757,8 @@ catalog has not arrived, is neither. | --- | --- | | No worker takes requests | `NO_CAPACITY` (exit 11) at once | | At least one worker takes requests, and no known worker has the platform | `NO_DRIVER` (exit 12) at once | -| ... and no known worker lists the model | `UNKNOWN_MODEL` (exit 12) at once | -| ... and no known worker has the runtime, or can pair it with the model | `RUNTIME_MISSING` (exit 12) at once; `downloadable` is `false`, and `osVersion` is `default` when you named none | +| ... and no known worker lists the model, or, for a class, a model of it | `UNKNOWN_MODEL` (exit 12) at once | +| ... and no known worker has the runtime, or can pair it with the model (or with a model of the class) | `RUNTIME_MISSING` (exit 12) at once; `downloadable` is `false`, and `osVersion` is the range as you typed it, or `default` when you named none | | A known worker could serve it, but none that takes requests can | `NO_CAPACITY` (exit 11) at once | | A worker that takes requests can serve it but is busy | Waits in the queue; `NO_CAPACITY` only with `--no-wait` | diff --git a/docs/CLIENT.md b/docs/CLIENT.md index 4c687f9ec..5b2e673d7 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -50,7 +50,9 @@ await client.requestLease({ platform: "ios", class: "tablet" }); await client.requestLease({ platform: "android" }); // a phone ``` -Through a gateway, a request that names no `model` is a `BAD_REQUEST` for now. +Through a gateway the same requests work: any worker that has something fitting +serves one, a warm device first, and one nothing in the fleet can serve fails at +once with the code a single machine gives. `requestLease` takes an optional `mode`, `"slim"` or `"full"`: the device mode the lease asks for. Without it the lease gets the default mode of the @@ -83,7 +85,7 @@ or a hyphen range (`"18 - 26"`). A short version covers everything under it, so by an idle device whose OS satisfies it or by a new device on the newest installed runtime in it, and when none is installed it fails at once with `RUNTIME_MISSING`, whatever `allowDownload` says. Through a gateway a range is -`BAD_REQUEST` for now. A request with `imageTag` never downloads: +served by any worker with a paired runtime in it. A request with `imageTag` never downloads: when no image of that tag is installed for the API level it fails with `RUNTIME_MISSING`, whatever `allowDownload` says. On iOS it is a `BAD_REQUEST`, and so is a tag that is not 1 to 64 letters, digits, `_`, `.` diff --git a/docs/EVENTS.md b/docs/EVENTS.md index 0e53c702c..5e58aefe6 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -105,7 +105,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, the mode when the request named one, 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 | +| `request.dispatched` | request id, worker id, requester id, platform, model when the request named one, device class when the request named one, the mode when the request named one, 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/HTTP-API.md b/docs/HTTP-API.md index 9338e85ce..4eeb7a57d 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -363,8 +363,7 @@ class's preference list that the machine lists (see with no listed model fails with `422 UNKNOWN_MODEL`, naming the config key, and one whose listed models pair with no installed runtime fails with `RUNTIME_MISSING`. The granted lease's `device`, `os`, `mode` and `imageTag` always name the device -you got. Through a gateway a request that names no `device`, or whose `os` is a -range, is `400 BAD_REQUEST` for now. `os` is an exact version (`"18.4"`) or a +you got. `os` is an exact version (`"18.4"`) or a range: one or more of `>=`, `>`, `<=`, `<` followed by a version, joined by single spaces (`">=18 <26"`), or a hyphen range (`"18 - 26"`); a short version covers everything under it, so `">=18"` is 18.0 and newer and `"<=26"` includes every @@ -433,6 +432,17 @@ and pairs that model with `os` (or, without `os`, with at least one installed runtime). With `imageTag`, the worker's catalog must also list an image of that tag, for `os` when it is given. The worker is sent its own name for the model. +A request with `class`, or with neither `device` nor `class` (which means +`phone`), goes to a worker whose catalog lists a model of that class paired with +an installed runtime that satisfies `os`, or, without `os`, with at least one +installed runtime. An `os` range is forwarded as you wrote it, and so is the +class: the worker picks the model and the runtime by its own rules. A worker +holding a ready device of that class, in the range and in the mode the request +needs, is preferred over one that would create a device. A class no worker +lists a model of fails at once with `422 UNKNOWN_MODEL`, and a range none of +their models of the class pair with an installed runtime in fails at once with +`422 RUNTIME_MISSING` carrying the range as `osVersion`. + A gateway fails a request no worker can serve at once, with or without `noWait` and `timeoutMs`, instead of queueing it. A worker *takes requests* when it is connected, not drained, and the gateway has read its catalog since diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 34f226feb..fe5f3ce34 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -655,10 +655,14 @@ The v1 policy (`warm-then-free`) is eight stages: 2. `can-serve` (filter): drop workers whose catalog cannot serve the request (ADR 0009 §3, `routing/request-match.ts`). The model is the first entry of the worker's `models` whose name or `modelAliases` entry equals the - requested name, ignoring letter case. A named runtime must be in that - model's `modelRuntimes`; with none named the list must be non-empty. Only - installed runtimes count, so a download never makes a worker able to - serve; + requested name, ignoring letter case (`findCatalogModel`, the core's one + matcher). A class request (the class `requestedClass` gives, `phone` for + neither a model nor a class, ADR 0015 §8) matches when the catalog's + `modelClasses` puts any model in that class. Either way a model needs a + paired runtime in `modelRuntimes` that satisfies the request's OS + constraint (`os-range`, the contract's one grammar: an exact version or a + range); with none named the list must be non-empty. Only installed + runtimes count, so a download never makes a worker able to serve; 3. `healthy` (filter): keep a worker whose health is `running`; 4. `idle-queue` (filter): keep a worker whose own `queueDepth` is zero, since a worker with a local waiter refuses every `noWait` request (ADR 0005 @@ -666,11 +670,14 @@ The v1 policy (`warm-then-free`) is eight stages: not known to be healthy or idle, so it is dropped. Stages 3 and 4 drop a worker that is busy, not unable: its requests wait; 5. `warm-hit` (rank, settles): prefer a worker with an unleased `ready` device - matching the request, compared against the worker's own name for the - model — a **warm hit**, and a sub-second grant. The runtime must be the - one requested or, with none requested, the one the worker would pick (the - catalog's `defaultRuntime` when the model pairs with it, otherwise its only - paired runtime; none when several pair and no default does). The mode must + matching the request — a **warm hit**, and a sub-second grant. "Matching" + is the core's `fits` (ADR 0015 §6, §8) over a requirement built from the + worker's own catalog: its own name for an exact model, or the class with + the worker's `modelClasses` as `classOf`. The OS is the one requested or + the range requested; with none requested, an exact model needs the runtime + the worker would pick (the catalog's `defaultRuntime` when the model pairs + with it, otherwise its only paired runtime; none when several pair and no + default does) and a class accepts any installed runtime. The mode must fit (ADR 0009 §6): `full` needs a device reporting `mode: "full"`, `slim` one reporting `slim`, and a request naming none a device reporting `servesDefaultMode`, which the worker computes in @@ -692,9 +699,12 @@ same function `tryReserveProvisioning` calls, so status and the planner cannot disagree. The same matcher gives the name the gateway forwards: the worker is sent its -own name for the model, so it resolves exactly what routing matched, and -`allowDownload` is always forwarded as `false`. `lease.requested` keeps the -name the client sent. +own name for an exact model, so it resolves exactly what routing matched, and +`allowDownload` is always forwarded as `false`. A class and an OS range are +forwarded as they arrived, with no `model` for a class request: the worker +resolves them by its own rules (ADR 0015 §5), and the gateway compares no +versions. `lease.requested` keeps the request as the client sent it, and +`request.dispatched` carries `model` or `class`, whichever the request named. #### A request that cannot be served @@ -706,9 +716,11 @@ arriving request on rows 1 to 5 is rejected without entering the queue (no `lease.queued`, no `queued` progress), and a drain or a lost uplink re-runs the walk, which rejects a waiting request that has moved onto those rows. In order: no worker takes requests, `NO_CAPACITY` (reason `no-worker`); no known -worker has the platform, `NO_DRIVER`; none lists the model, `UNKNOWN_MODEL`; -none has the runtime or pairs it with the model, `RUNTIME_MISSING` with -`downloadable: false` and `osVersion: "default"` for an unnamed runtime (the +worker has the platform, `NO_DRIVER`; none lists the model, or for a class +request any model of it, `UNKNOWN_MODEL` (its details carry `class` instead of +`model`); none has the runtime or pairs it with the model, or with a model of +the class, `RUNTIME_MISSING` with `downloadable: false` and `osVersion` the +constraint as typed, `"default"` for an unnamed runtime (the last three with reason `unresolvable-spec`); a known worker can serve it but none that takes requests can, `NO_CAPACITY` (`no-worker`); otherwise route or wait. A worker *takes requests* when it passes `takes-requests`; the gateway diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 0cd733e20..a5ef647d1 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -32,7 +32,9 @@ in short: `subject.past-tense-fact`, emitted post-commit, facts not commands. > it a third time: `lease.requested` and `lease.rejected` carry the request > as it arrived, so `requestSpec.model` becomes optional (a request naming a > class or nothing has none) and `requestSpec.class` enters. Making a -> required key optional is not additive. +> required key optional is not additive. The exception covers +> `request.dispatched` too, which names the same request: `model` becomes +> optional and `class` enters, for the same reason. ## Lease lifecycle @@ -154,7 +156,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, mode?, reason, stage, queuedMs }` — `mode` is the device mode the request named, `slim` or `full`, and absent when it named none (ADR 0009 §8); `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 | +| `request.dispatched` | `{ requestId, workerId, requesterId, platform, model?, class?, mode?, reason, stage, queuedMs }` — `model` is the exact model the request named and `class` the class it named; a request names at most one, and one naming neither carries neither (ADR 0015 §9); `mode` is the device mode the request named, `slim` or `full`, and absent when it named none (ADR 0009 §8); `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 4c92b6818..005c2c935 100644 --- a/src/bus/index.ts +++ b/src/bus/index.ts @@ -314,7 +314,10 @@ export interface EventMap { readonly workerId: string; readonly requesterId: string; readonly platform: string; - readonly model: string; + /** The exact model the request named; absent for a class request (ADR 0015 §9). */ + readonly model?: string; + /** The class the request named; absent for an exact one or one naming neither. */ + readonly class?: string; /** The mode the request named (ADR 0009 §8); absent when it named none. */ readonly mode?: "slim" | "full"; readonly reason: "warm-hit" | "free-capacity"; diff --git a/src/gateway/boundary.test.ts b/src/gateway/boundary.test.ts index 8f15ecb77..2ec2f7261 100644 --- a/src/gateway/boundary.test.ts +++ b/src/gateway/boundary.test.ts @@ -56,7 +56,9 @@ const ALLOWED_DAEMON_IMPORTS = ["daemon/dispatch.js"]; * `DeviceRequest`), which the fleet queue and coordinator need to name the same shapes wait-queue * itself is typed against rather than redeclaring them. Neither module is the registry, capacity, * or lifecycle engine §33 keeps off limits -- `domain.js` is pure data shapes and a spec-equality - * predicate, `driver.js` is interface declarations only. + * predicate, `driver.js` is interface declarations only. `catalog-match.js` is the one place a + * request's model or class is read against a catalog (ADR 0015 §8; architecture rule 10): pure + * functions over a catalog entry, so the gateway matches exactly as a worker does. */ const ALLOWED_CORE_IMPORTS = [ "core/wait-queue.js", @@ -64,6 +66,7 @@ const ALLOWED_CORE_IMPORTS = [ "core/serialized-decision.js", "core/domain.js", "core/driver.js", + "core/catalog-match.js", ]; describe("gateway module boundary", () => { diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index d37d72df8..880eacafb 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -351,7 +351,7 @@ describe("GatewayDispatcher", () => { { modelAliases: {}, classDefaults: {}, - modelClasses: {}, + modelClasses: {} as const, modelRuntimes: { "iPhone 17": ["26.0"] }, models: ["iPhone 17"], platform: "ios", @@ -855,7 +855,7 @@ describe("GatewayDispatcher", () => { queueDepth: 0, catalog: catalogFixture([ { - modelClasses: { "iPhone 17": "phone" }, + modelClasses: { "iPhone 17": "phone" } as const, models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"], diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index 93fb4909f..4825b91cd 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -41,7 +41,6 @@ import { type OperationName, type tokenRecordSchema, } from "../contract/index.js"; -import { parseOsConstraint } from "../contract/os-range.js"; import { DispatchError, runDispatch, @@ -433,20 +432,10 @@ export class GatewayDispatcher { "Only the gateway's own uplink session may set lease.request's `owner` field", ); } - // ADR 0015 §8 is a later task: until the gateway matches a class against its workers, a - // request that names no exact model is refused here rather than routed on a guess. - if (input.model === undefined) { - throw new DispatchError("BAD_REQUEST", "a gateway does not route class requests yet"); - } - // The same stub for an OS range: matching one against workers is the next task. - if (input.osVersion !== undefined && isRange(input.osVersion)) { - throw new DispatchError("BAD_REQUEST", "a gateway does not route OS ranges yet"); - } - const { model } = input; return this.options.coordinator.request( // Forwarded as it arrived (ADR 0007 §2): the gateway has no default mode of its own, and // relays an image tag unread. - { ...requestedDevice(input), model }, + requestedDevice(input), { // `input.allowDownload` stays accepted and is not passed on: only installed runtimes // count through a gateway (ADR 0009 §3). @@ -537,9 +526,3 @@ function unsupportedByDesign( throw new DispatchError("UNSUPPORTED_IN_GATEWAY_MODE", message, { operation }); }; } - -/** Whether an `osVersion` is a range rather than an exact version. */ -function isRange(osVersion: string): boolean { - const parsed = parseOsConstraint(osVersion); - return parsed.ok && parsed.constraint.kind === "range"; -} diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index adb169d8e..72438276b 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -3232,7 +3232,7 @@ describe("FleetLeaseCoordinator: queue.changed", () => { describe("FleetLeaseCoordinator routes a class or range request (ADR 0015 §8)", () => { const phones = { - modelClasses: { "iPhone 16": "phone", "iPhone 17": "phone" }, + modelClasses: { "iPhone 16": "phone", "iPhone 17": "phone" } as const, models: ["iPhone 16", "iPhone 17"], platform: "ios" as const, runtimes: ["18.0", "26.0"], @@ -3244,7 +3244,7 @@ describe("FleetLeaseCoordinator routes a class or range request (ADR 0015 §8)", entry: Parameters[0][number], options: { readonly capacity?: ReturnType["capacity"]; - readonly devices?: ReturnType[]; + readonly devices?: ReturnType[number]["devices"]; } = {}, ): void { workers.connected(workerId, undefined, "0.3.0"); @@ -3370,7 +3370,7 @@ describe("FleetLeaseCoordinator routes a class or range request (ADR 0015 §8)", directory.add("wrk_b", warm); warm.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); const pixels = { - modelClasses: { "Pixel 8": "phone" }, + modelClasses: { "Pixel 8": "phone" } as const, models: ["Pixel 8"], platform: "android" as const, runtimes: ["35"], diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index 1ae06e524..17631fc1e 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -52,7 +52,7 @@ import { } from "../contract/index.js"; import { DispatchError, type DispatchSession } from "../daemon/dispatch.js"; import type { LeaseRequestFailure } from "../core/domain.js"; -import type { ExactDeviceRequest } from "../core/driver.js"; +import type { DeviceRequest } from "../core/driver.js"; import { InMemoryLeaseRequestStore, LeaseRequestBook, @@ -238,7 +238,7 @@ export class FleetLeaseCoordinator { * Everything past admission -- reaching a worker at all -- is I/O and stays outside it. */ async request( - deviceRequest: ExactDeviceRequest, + deviceRequest: DeviceRequest, options: LeaseRequestOptions, ): Promise { const admitted = await this.#decisions.run(async () => { @@ -268,7 +268,7 @@ export class FleetLeaseCoordinator { /** One lease or pending request per requester, fleet-wide (§14). */ #refuseIfAlreadyLeased( - deviceRequest: ExactDeviceRequest, + deviceRequest: DeviceRequest, requesterId: string, requestId: string, ): void { @@ -821,7 +821,7 @@ export class FleetLeaseCoordinator { * `#settleGrant` while `queue.resolve` quietly answers `false`, leaving an orphan lease no * client holds a reference to release. */ - #beginAttempt(waiter: FleetWaiter, decision: RoutingDecision, model: string): void { + #beginAttempt(waiter: FleetWaiter, decision: RoutingDecision, model: string | undefined): void { if (!this.#queue.markProcessing(waiter)) return; void this.#attempt(waiter, decision, model); } @@ -856,7 +856,11 @@ export class FleetLeaseCoordinator { * queued waiter needs, and nothing else would ever schedule that second look. */ // fallow-ignore-next-line complexity -- one attempt, every exit of which is named in the doc comment above. - async #attempt(waiter: FleetWaiter, decision: RoutingDecision, model: string): Promise { + async #attempt( + waiter: FleetWaiter, + decision: RoutingDecision, + model: string | undefined, + ): Promise { const workerId = decision.workerId; const client = liveClient(this.options.directory.target(workerId)); if (client === undefined) { @@ -875,7 +879,8 @@ export class FleetLeaseCoordinator { // see `bus/index.ts`'s own doc comment on why it was narrowed and then restored. const createdAt = this.#createdAt.get(waiter); this.#emit("request.dispatched", { - model: waiter.request.model, + ...(waiter.request.model === undefined ? {} : { model: waiter.request.model }), + ...(waiter.request.class === undefined ? {} : { class: waiter.request.class }), ...(waiter.request.mode === undefined ? {} : { mode: waiter.request.mode }), platform: waiter.request.platform, queuedMs: createdAt === undefined ? 0 : Math.max(0, this.options.clock.now() - createdAt), @@ -903,8 +908,8 @@ export class FleetLeaseCoordinator { grant = await this.#withLeaseRequestTimeout( client.requestLease( { - // The request as it arrived, under the worker's own name for the model. - ...requestedDevice({ ...waiter.request, model }), + // The request as it arrived, under the worker's own name for an exact model. + ...requestedDevice(model === undefined ? waiter.request : { ...waiter.request, model }), requesterId: namespacedRequesterId, // ADR §27a (narrowed, round 3 review, H3): only the worker's own gateway-uplink // session may set `owner` -- and this RPC always travels over exactly that @@ -1245,15 +1250,17 @@ export class FleetLeaseCoordinator { } /** - * ADR 0009 §3: the worker is sent its own name for the model, so it resolves exactly what routing - * matched. The client's name is kept only for a worker the catalog does not match, which no - * registered policy picks. + * ADR 0009 §3: the worker is sent its own name for an exact model, so it resolves exactly what + * routing matched. The client's name is kept only for a worker the catalog does not match, which + * no registered policy picks. A class request has no model to send (ADR 0015 §8): the worker + * applies its own rules to the class, so it stays as it arrived. */ function forwardedModel( request: RoutableRequest, views: readonly WorkerView[], decision: RoutingDecision, -): string { +): string | undefined { + if (request.model === undefined) return undefined; const view = views.find((worker) => worker.id === decision.workerId); return (view === undefined ? undefined : matchRequest(view, request)) ?? request.model; } @@ -1261,7 +1268,8 @@ function forwardedModel( function routable(waiter: FleetWaiter): RoutableRequest { return { platform: waiter.request.platform as Platform, - model: waiter.request.model, + ...(waiter.request.model === undefined ? {} : { model: waiter.request.model }), + ...(waiter.request.class === undefined ? {} : { class: waiter.request.class }), ...(waiter.request.osVersion === undefined ? {} : { osVersion: waiter.request.osVersion }), ...(waiter.request.imageTag === undefined ? {} : { imageTag: waiter.request.imageTag }), ...(waiter.request.mode === undefined ? {} : { mode: waiter.request.mode }), diff --git a/src/gateway/queue.ts b/src/gateway/queue.ts index dc58f872b..46ecf82e9 100644 --- a/src/gateway/queue.ts +++ b/src/gateway/queue.ts @@ -5,17 +5,17 @@ * `LeaseRequestOptions` (`requesterId`, `ownerId`, `timeoutMs`, `noWait`, `allowDownload`, * `onProgress`, `ttlMs`) are already the fields a fleet request carries. This module only * narrows `WaitQueue`'s generic `Waiter`/`LeaseGrant` shapes to what the fleet actually produces - * (a `ExactDeviceRequest` for the request, and a lease record that may additionally carry `worker` + * (a `DeviceRequest` for the request, and a lease record that may additionally carry `worker` * once it names a machine) and forwards every method through. * - * `ExactDeviceRequest`/`DeviceRecord`/`LeaseRecord`/`WaiterState` are `wait-queue.js`'s own transitive + * `DeviceRequest`/`DeviceRecord`/`LeaseRecord`/`WaiterState` are `wait-queue.js`'s own transitive * type imports (`core/domain.js`, `core/driver.js`) -- see `boundary.test.ts`'s * `ALLOWED_CORE_IMPORTS` -- not a reach into the registry, capacity, or lifecycle engine ADR 0005 * §33 keeps off limits. */ import type { Clock, IdGenerator } from "../ports/index.js"; import type { LeaseRecord } from "../core/domain.js"; -import type { ExactDeviceRequest } from "../core/driver.js"; +import type { DeviceRequest } from "../core/driver.js"; import { WaitQueue, type LeaseProgress, @@ -52,7 +52,7 @@ export interface FleetLeaseGrant { export interface FleetWaiter { readonly id: string; - readonly request: ExactDeviceRequest; + readonly request: DeviceRequest; readonly options: LeaseRequestOptions; readonly promise: Promise; readonly state: WaiterState; @@ -122,7 +122,7 @@ export class FleetQueue { return asFleet(this.#queue.findPendingWaiter(requesterId)); } - create(request: ExactDeviceRequest, options: LeaseRequestOptions, id?: string): FleetWaiter { + create(request: DeviceRequest, options: LeaseRequestOptions, id?: string): FleetWaiter { return asFleet(this.#queue.create(request, options, id)); } diff --git a/src/gateway/routing/pipeline.ts b/src/gateway/routing/pipeline.ts index aacf11481..fc9316ceb 100644 --- a/src/gateway/routing/pipeline.ts +++ b/src/gateway/routing/pipeline.ts @@ -5,11 +5,16 @@ * touches that stage and the list in `routing.ts`, and no other stage. */ import type { Platform } from "../../contract/index.js"; +import type { DeviceClass } from "../../core/domain.js"; import type { WorkerView } from "../worker-registry.js"; export interface RoutableRequest { readonly platform: Platform; - readonly model: string; + /** The exact model the request names; absent for a class request or one naming neither. */ + readonly model?: string; + /** The class the request names; with no `model` either, the request means `phone`. */ + readonly class?: DeviceClass; + /** The OS constraint as typed: an exact version or a range (`os-range`). */ readonly osVersion?: string; /** The image tag the request names, matched against the catalog's `images`; absent for none. */ readonly imageTag?: string; diff --git a/src/gateway/routing/request-match.test.ts b/src/gateway/routing/request-match.test.ts index 26c30126e..a708d04e8 100644 --- a/src/gateway/routing/request-match.test.ts +++ b/src/gateway/routing/request-match.test.ts @@ -85,7 +85,7 @@ describe("matchRequest", () => { it("reads no inherited key as a pairing or an alias", () => { const view = worker({ modelAliases: {}, - modelClasses: {}, + modelClasses: {} as const, modelRuntimes: {}, models: ["constructor"], platform: "ios", @@ -98,7 +98,7 @@ describe("matchRequest", () => { // alias list for the model and moves on to the next one. const withNext = worker({ modelAliases: {}, - modelClasses: {}, + modelClasses: {} as const, models: ["constructor", "iPhone 17"], platform: "ios", runtimes: ["26.0"], @@ -152,7 +152,7 @@ describe("matchRequest", () => { describe("with a class", () => { const PHONES = { - modelClasses: { "iPad Pro": "tablet", "iPhone 16": "phone", "iPhone 17": "phone" }, + modelClasses: { "iPad Pro": "tablet", "iPhone 16": "phone", "iPhone 17": "phone" } as const, modelRuntimes: { "iPad Pro": ["26.0"], "iPhone 16": ["18.0"], "iPhone 17": ["26.0"] }, models: ["iPad Pro", "iPhone 16", "iPhone 17"], platform: "ios" as const, @@ -184,7 +184,7 @@ describe("matchRequest", () => { expect(matchRequest(worker(PHONES), { platform: "ios" })).toBeDefined(); const tablets = worker({ ...PHONES, - modelClasses: { "iPad Pro": "tablet" }, + modelClasses: { "iPad Pro": "tablet" } as const, models: ["iPad Pro"], }); expect(matchRequest(tablets, { platform: "ios" })).toBeUndefined(); @@ -207,7 +207,7 @@ describe("matchRequest", () => { }); it("reads no inherited key as a class", () => { - const view = worker({ ...PHONES, modelClasses: {}, models: ["constructor"] }); + const view = worker({ ...PHONES, modelClasses: {} as const, models: ["constructor"] }); expect(matchRequest(view, phone)).toBeUndefined(); }); diff --git a/src/gateway/routing/request-match.ts b/src/gateway/routing/request-match.ts index ed9add9cc..dd9fcdde5 100644 --- a/src/gateway/routing/request-match.ts +++ b/src/gateway/routing/request-match.ts @@ -3,58 +3,133 @@ * only the worker's catalog (ADR 0008 §1): the `can-serve` stage, the `warm-hit` stage, and the * forwarded `lease.request` all ask it, so the worker resolves exactly what the gateway matched. */ +import { requestedClass } from "../../contract/index.js"; +import { type OsConstraint, parseOsConstraint, satisfies } from "../../contract/os-range.js"; +import { findCatalogModel, modelClass, pairedRuntimes } from "../../core/catalog-match.js"; +import type { DeviceClass, DeviceRequirement } from "../../core/domain.js"; import type { WorkerView } from "../worker-registry.js"; import type { RoutableRequest } from "./pipeline.js"; /** - * The worker's own name for the requested model, or `undefined` when it cannot serve the request. + * The worker's own name for a model that can serve the request, or `undefined` when none can. * - * The model is the first entry of `models` whose name or `modelAliases` entry equals the requested - * name, ignoring letter case. A named runtime must be among that model's `modelRuntimes`; an - * unnamed one needs the list to be non-empty. Only installed runtimes are listed, so a request - * that would need a download never matches. A request naming an image tag counts only the - * runtimes for which the catalog's `images` lists an image of that tag. + * An exact request: the first entry of `models` whose name or `modelAliases` entry equals the + * requested name, ignoring letter case. A class request (the class `requestedClass` gives, `phone` + * for neither): the first model the catalog classes as that class. Either way the model must pair + * with an installed runtime that satisfies the request's OS constraint (`os-range`); with none + * named, one runtime is enough. Only installed runtimes are listed, so a request that would need + * a download never matches. A request naming an image tag counts only the runtimes for which the + * catalog's `images` lists an image of that tag. */ export function matchRequest(worker: WorkerView, request: RoutableRequest): string | undefined { const catalog = catalogOf(worker, request); if (catalog === undefined) return undefined; - const model = findModel(catalog, request); - if (model === undefined) return undefined; - const runtimes = pairedRuntimes(catalog, model, request); - const pairs = - request.osVersion === undefined ? runtimes.length > 0 : runtimes.includes(request.osVersion); - return pairs ? model : undefined; + return candidates(catalog, request).find((model) => + pairedRuntimesOf(catalog, model, request).some((runtime) => osFits(runtime, request)), + ); } /** - * The runtime the worker would pick for the request, or `undefined` when the gateway cannot say - * (ADR 0009 §6). The one the request names, when it names one. With none named: the catalog's - * `defaultRuntime` when the model pairs with it, otherwise the model's only paired runtime. - * A model with several paired runtimes and no paired default has no answer: the worker's choice - * then depends on what it would boot, and the gateway compares no versions. + * The runtime the worker would pick for an exact request, or `undefined` when the gateway cannot + * say (ADR 0009 §6). The one the request names, when it names an exact version. With none named: + * the catalog's `defaultRuntime` when the model pairs with it, otherwise the model's only paired + * runtime. A model with several paired runtimes and no paired default has no answer: the worker's + * choice then depends on what it would boot, and the gateway compares no versions. */ export function pickedRuntime(worker: WorkerView, request: RoutableRequest): string | undefined { - if (request.osVersion !== undefined) return request.osVersion; + const constraint = osConstraintOf(request); + if (constraint?.kind === "exact") return constraint.version; + if (constraint !== undefined) return undefined; const catalog = catalogOf(worker, request); - if (catalog === undefined) return undefined; - const model = findModel(catalog, request); + if (catalog === undefined || request.model === undefined) return undefined; + const model = findCatalogModel(catalog, request.model); if (model === undefined) return undefined; - const runtimes = pairedRuntimes(catalog, model, request); + const runtimes = pairedRuntimesOf(catalog, model, request); const paired = runtimes.find((runtime) => runtime === catalog.defaultRuntime); return paired ?? (runtimes.length === 1 ? runtimes[0] : undefined); } +/** + * The requirement a ready device must `fit` to serve the request on this worker (ADR 0015 §6), or + * `undefined` when the gateway cannot say which runtime the worker would pick. A class request + * with no OS accepts any installed runtime; an exact one with no OS, the runtime the worker would + * pick. The mode is not part of it. + */ +export function requirementOf( + worker: WorkerView, + request: RoutableRequest, +): DeviceRequirement | undefined { + const catalog = catalogOf(worker, request); + const model = matchRequest(worker, request); + if (catalog === undefined || model === undefined) return undefined; + const target: DeviceRequirement["target"] = + request.model === undefined + ? { class: wantedClass(request), kind: "class" } + : { kind: "model", model }; + const constraint = osConstraintOf(request); + let osVersion: DeviceRequirement["osVersion"] | undefined; + if (constraint !== undefined) osVersion = constraint; + else if (request.model === undefined) + osVersion = { kind: "installed", versions: catalog.runtimes }; + else { + const picked = pickedRuntime(worker, request); + osVersion = picked === undefined ? undefined : { kind: "exact", version: picked }; + } + if (osVersion === undefined) return undefined; + return { imageTag: request.imageTag, osVersion, platform: request.platform, target }; +} + +/** The class a model is listed under on this worker, for `fits`. */ +export function classOfModel( + worker: WorkerView, + request: RoutableRequest, +): (model: string) => DeviceClass | undefined { + const catalog = catalogOf(worker, request); + return (model) => (catalog === undefined ? undefined : modelClass(catalog, model)); +} + +/** + * The models that could serve the request, before pairing: the one an exact request names, or + * every model of the requested class, in catalog order. + */ +function candidates(catalog: PlatformEntry, request: RoutableRequest): readonly string[] { + if (request.model !== undefined) { + const model = findCatalogModel(catalog, request.model); + return model === undefined ? [] : [model]; + } + const wanted = wantedClass(request); + return catalog.models.filter((model) => modelClass(catalog, model) === wanted); +} + +/** The class a request without a model means: the one it names, `phone` for neither. */ +export function wantedClass(request: RoutableRequest): DeviceClass { + return requestedClass({ class: request.class }); +} + +/** The OS constraint a request names, or `undefined` for none. A string the grammar refuses can + * never reach here through the contract; it is read as exact, which no runtime matches. */ +function osConstraintOf(request: RoutableRequest): OsConstraint | undefined { + if (request.osVersion === undefined) return undefined; + const parsed = parseOsConstraint(request.osVersion); + return parsed.ok ? parsed.constraint : { kind: "exact", version: request.osVersion }; +} + +function osFits(runtime: string, request: RoutableRequest): boolean { + const constraint = osConstraintOf(request); + return constraint === undefined || satisfies(runtime, constraint); +} + /** * The runtimes the model pairs with. A request naming an image tag counts only the runtimes for * which the catalog's `images` lists an image of that tag. */ -function pairedRuntimes( +function pairedRuntimesOf( catalog: PlatformEntry, model: string, request: RoutableRequest, ): readonly string[] { const { imageTag } = request; - const runtimes = ownList(catalog.modelRuntimes, model); + const runtimes = pairedRuntimes(catalog, model); if (imageTag === undefined) return runtimes; return runtimes.filter((runtime) => (catalog.images ?? []).some((image) => image.tag === imageTag && image.runtime === runtime), @@ -67,13 +142,13 @@ export function hasPlatform(worker: WorkerView, request: RoutableRequest): boole } /** - * Whether the worker lists the requested model, by name or alias in any letter case, whatever - * runtimes it pairs with. The table of ADR 0009 §4 tells a missing model from a missing runtime - * with it. + * Whether the worker lists the requested model, by name or alias in any letter case, or, for a + * class request, any model of the class, whatever runtimes it pairs with. The table of ADR 0009 + * §4 tells a missing model from a missing runtime with it. */ export function listsModel(worker: WorkerView, request: RoutableRequest): boolean { const catalog = catalogOf(worker, request); - return catalog !== undefined && findModel(catalog, request) !== undefined; + return catalog !== undefined && candidates(catalog, request).length > 0; } type PlatformEntry = WorkerView["catalog"][number]; @@ -81,26 +156,3 @@ type PlatformEntry = WorkerView["catalog"][number]; function catalogOf(worker: WorkerView, request: RoutableRequest): PlatformEntry | undefined { return worker.catalog.find((entry) => entry.platform === request.platform); } - -/** The first entry of `models` whose name or alias is the requested name. */ -function findModel(catalog: PlatformEntry, request: RoutableRequest): string | undefined { - const wanted = fold(request.model); - return catalog.models.find( - (name) => - fold(name) === wanted || - ownList(catalog.modelAliases, name).some((alias) => fold(alias) === wanted), - ); -} - -/** Locale-independent, so a gateway and a worker on different locales fold a name alike. */ -function fold(name: string): string { - return name.toLowerCase(); -} - -/** A record lookup that ignores inherited keys, so a model named `constructor` reads nothing. */ -function ownList( - record: Readonly>, - key: string, -): readonly string[] { - return Object.hasOwn(record, key) ? (record[key] ?? []) : []; -} diff --git a/src/gateway/routing/serviceability.test.ts b/src/gateway/routing/serviceability.test.ts index 5bb9e30c6..8a239e110 100644 --- a/src/gateway/routing/serviceability.test.ts +++ b/src/gateway/routing/serviceability.test.ts @@ -172,7 +172,7 @@ describe("assess", () => { describe("a class request", () => { const PHONE: CatalogEntry = { - modelClasses: { "iPhone 17": "phone" }, + modelClasses: { "iPhone 17": "phone" } as const, models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"], @@ -191,7 +191,7 @@ describe("assess", () => { it("row 3: treats a request naming neither model nor class as phone", () => { const tablets: CatalogEntry = { - modelClasses: { "iPad Pro": "tablet" }, + modelClasses: { "iPad Pro": "tablet" } as const, models: ["iPad Pro"], platform: "ios", runtimes: ["26.0"], diff --git a/src/gateway/routing/serviceability.ts b/src/gateway/routing/serviceability.ts index 56ae75f88..8ec2cf85e 100644 --- a/src/gateway/routing/serviceability.ts +++ b/src/gateway/routing/serviceability.ts @@ -4,9 +4,10 @@ * it and acts on the answer, and the stages never see a request this table has rejected. */ import type { Platform } from "../../contract/index.js"; +import type { DeviceClass } from "../../core/domain.js"; import type { WorkerView } from "../worker-registry.js"; import type { RoutableRequest } from "./pipeline.js"; -import { hasPlatform, listsModel, matchRequest } from "./request-match.js"; +import { hasPlatform, listsModel, matchRequest, wantedClass } from "./request-match.js"; import { takesRequests } from "./stages/takes-requests.js"; export type RejectionCode = "NO_CAPACITY" | "NO_DRIVER" | "UNKNOWN_MODEL" | "RUNTIME_MISSING"; @@ -20,6 +21,7 @@ export interface Rejection { readonly details?: { readonly platform: Platform; readonly model?: string; + readonly class?: DeviceClass; readonly osVersion?: string; readonly downloadable?: false; }; @@ -52,15 +54,7 @@ export function assess(request: RoutableRequest, views: readonly WorkerView[]): reason: "unresolvable-spec", }; } - if (!known.some((worker) => listsModel(worker, request))) { - return { - code: "UNKNOWN_MODEL", - details: { model: request.model, platform }, - kind: "reject", - message: `Unknown ${platform} model: ${request.model}`, - reason: "unresolvable-spec", - }; - } + if (!known.some((worker) => listsModel(worker, request))) return unknownModel(request); if (!known.some((worker) => matchRequest(worker, request) !== undefined)) { const osVersion = request.osVersion ?? "default"; return { @@ -81,6 +75,30 @@ function isKnown(worker: WorkerView): boolean { return worker.connection !== "incompatible"; } +/** A model no worker lists, or, for a class request, a class none lists a model of. */ +function unknownModel(request: RoutableRequest): Rejection { + const { platform } = request; + if (request.model === undefined) { + const deviceClass = wantedClass(request); + return { + code: "UNKNOWN_MODEL", + details: { class: deviceClass, platform }, + kind: "reject", + message: + `No ${platform} model of class ${deviceClass} is listed by any worker in the fleet; ` + + `name one in ${platform}.defaultModels.${deviceClass} on a worker`, + reason: "unresolvable-spec", + }; + } + return { + code: "UNKNOWN_MODEL", + details: { model: request.model, platform }, + kind: "reject", + message: `Unknown ${platform} model: ${request.model}`, + reason: "unresolvable-spec", + }; +} + function noWorker(): Rejection { return { code: "NO_CAPACITY", diff --git a/src/gateway/routing/stages/warm-hit.test.ts b/src/gateway/routing/stages/warm-hit.test.ts index ceeeaa036..7372b4a17 100644 --- a/src/gateway/routing/stages/warm-hit.test.ts +++ b/src/gateway/routing/stages/warm-hit.test.ts @@ -232,7 +232,7 @@ describe("warm-hit", () => { describe("a class or range request", () => { const catalog = { defaultRuntime: "26.0", - modelClasses: { "iPad Pro": "tablet", "iPhone 15": "phone", "iPhone 17": "phone" }, + modelClasses: { "iPad Pro": "tablet", "iPhone 15": "phone", "iPhone 17": "phone" } as const, models: ["iPad Pro", "iPhone 15", "iPhone 17"], platform: "ios" as const, runtimes: ["18.0", "26.0"], diff --git a/src/gateway/routing/stages/warm-hit.ts b/src/gateway/routing/stages/warm-hit.ts index 9ad4a7f45..050b0638d 100644 --- a/src/gateway/routing/stages/warm-hit.ts +++ b/src/gateway/routing/stages/warm-hit.ts @@ -1,32 +1,40 @@ -import { matchRequest, pickedRuntime } from "../request-match.js"; +import { type DeviceSpec, fits } from "../../../core/domain.js"; +import type { WorkerView } from "../../worker-registry.js"; +import { classOfModel, requirementOf } from "../request-match.js"; import type { RankStage } from "../pipeline.js"; /** - * Prefers a worker with an unleased `ready` device that fits the request (ADR 0009 §6): the - * worker's own name for the model, the runtime the worker would pick (the one requested, else its - * default), and the mode. A `full` request needs a device reporting `full`, a `slim` one a device - * reporting `slim`, and one naming no mode a device that serves the worker's default mode. The - * device's image tag must be the request's, or both absent: the worker would not hand any other - * device to the request. A worker the catalog does not match has no warm device for it. A miss - * costs a cold boot, never a wrong device -- the worker still applies its own rules. Settles: - * once a warm worker exists, no later stage looks at capacity. + * Prefers a worker with an unleased `ready` device that fits the request (ADR 0009 §6, ADR 0015 + * §8): the core's `fits` over the worker's own catalog, for the requirement the request has on + * that worker -- the worker's own name for an exact model or the class, the runtime the worker + * would pick (an exact request naming none: the one it requested, else its default) or any + * installed one (a class request naming none), the range when the request has one, and the image + * tag. The mode is the one rule kept here: a `full` request needs a device reporting `full`, a + * `slim` one a device reporting `slim`, and one naming no mode a device that serves the worker's + * default mode. A worker the catalog does not match has no warm device for it. A miss costs a + * cold boot, never a wrong device -- the worker still applies its own rules. Settles: once a warm + * worker exists, no later stage looks at capacity. */ export const warmHit: RankStage = { kind: "rank", name: "warm-hit", score(worker, request) { - const model = matchRequest(worker, request); - const runtime = pickedRuntime(worker, request); + const requirement = requirementOf(worker, request); + if (requirement === undefined) return 0; + const classOf = classOfModel(worker, request); const warm = worker.devices.some( (device) => device.state === "ready" && - device.spec.platform === request.platform && - device.spec.model === model && - device.spec.imageTag === request.imageTag && - device.spec.osVersion === runtime && + fits(requirement, deviceSpec(device.spec), classOf) && (request.mode === undefined ? device.servesDefaultMode : device.mode === request.mode), ); return warm ? 1 : 0; }, settles: true, }; + +/** The view's device spec in the core's shape, which leaves an absent image tag out. */ +function deviceSpec(spec: WorkerView["devices"][number]["spec"]): DeviceSpec { + const { imageTag, ...rest } = spec; + return imageTag === undefined ? rest : { ...rest, imageTag }; +} From ee4f13c6fcbcd7b2b468d9187b49e4ab89d42a85 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 5 Oct 2026 18:40:47 +0200 Subject: [PATCH 3/3] refactor(gateway): one requirement for a warm hit; tests for the class paths mutate: 24 alive -> 5 alive, all equivalent --- src/gateway/fleet-coordinator.test.ts | 24 ++++++ src/gateway/fleet-coordinator.ts | 23 +++--- src/gateway/routing/request-match.test.ts | 4 + src/gateway/routing/request-match.ts | 94 +++++++++++----------- src/gateway/routing/serviceability.test.ts | 7 +- src/gateway/routing/stages/warm-hit.ts | 11 ++- 6 files changed, 95 insertions(+), 68 deletions(-) diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 72438276b..bed73792c 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -3335,6 +3335,30 @@ describe("FleetLeaseCoordinator routes a class or range request (ADR 0015 §8)", expect(dispatchedExact[0]).not.toHaveProperty("class"); }); + it("sends a request for a class only one worker lists a model of to that worker", async () => { + const { coordinator, directory, workers } = harness(); + const phonesOnly = new ScriptedWorkerClient(); + const withTablet = new ScriptedWorkerClient(); + directory.add("wrk_a", phonesOnly); + directory.add("wrk_b", withTablet); + withTablet.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + // wrk_a sorts first and has the same room, so only the class can send it to wrk_b. + connectWith(workers, "wrk_a", phones); + connectWith(workers, "wrk_b", { + ...phones, + modelClasses: { ...phones.modelClasses, "iPad Pro": "tablet" }, + models: [...phones.models, "iPad Pro"], + }); + + await coordinator.request( + { class: "tablet", platform: "ios" }, + requestOptions({ noWait: true }), + ); + + expect(leaseRequests(phonesOnly)).toEqual([]); + expect(withTablet.lastRequestLeaseInput).toMatchObject({ class: "tablet" }); + }); + it("retries a worker's UNKNOWN_MODEL for a class request, before any progress, on another worker", async () => { const { coordinator, directory, workers } = harness(); const a = new ScriptedWorkerClient(); diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index 17631fc1e..bb43c93ad 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -821,9 +821,9 @@ export class FleetLeaseCoordinator { * `#settleGrant` while `queue.resolve` quietly answers `false`, leaving an orphan lease no * client holds a reference to release. */ - #beginAttempt(waiter: FleetWaiter, decision: RoutingDecision, model: string | undefined): void { + #beginAttempt(waiter: FleetWaiter, decision: RoutingDecision, rename: ModelName): void { if (!this.#queue.markProcessing(waiter)) return; - void this.#attempt(waiter, decision, model); + void this.#attempt(waiter, decision, rename); } /** @@ -856,11 +856,7 @@ export class FleetLeaseCoordinator { * queued waiter needs, and nothing else would ever schedule that second look. */ // fallow-ignore-next-line complexity -- one attempt, every exit of which is named in the doc comment above. - async #attempt( - waiter: FleetWaiter, - decision: RoutingDecision, - model: string | undefined, - ): Promise { + async #attempt(waiter: FleetWaiter, decision: RoutingDecision, rename: ModelName): Promise { const workerId = decision.workerId; const client = liveClient(this.options.directory.target(workerId)); if (client === undefined) { @@ -909,7 +905,7 @@ export class FleetLeaseCoordinator { client.requestLease( { // The request as it arrived, under the worker's own name for an exact model. - ...requestedDevice(model === undefined ? waiter.request : { ...waiter.request, model }), + ...requestedDevice({ ...waiter.request, ...rename }), requesterId: namespacedRequesterId, // ADR §27a (narrowed, round 3 review, H3): only the worker's own gateway-uplink // session may set `owner` -- and this RPC always travels over exactly that @@ -1259,10 +1255,15 @@ function forwardedModel( request: RoutableRequest, views: readonly WorkerView[], decision: RoutingDecision, -): string | undefined { - if (request.model === undefined) return undefined; +): ModelName { + if (request.model === undefined) return {}; const view = views.find((worker) => worker.id === decision.workerId); - return (view === undefined ? undefined : matchRequest(view, request)) ?? request.model; + return { model: (view === undefined ? undefined : matchRequest(view, request)) ?? request.model }; +} + +/** The `model` a forward overrides the request's own with: none for a class request. */ +interface ModelName { + readonly model?: string; } function routable(waiter: FleetWaiter): RoutableRequest { diff --git a/src/gateway/routing/request-match.test.ts b/src/gateway/routing/request-match.test.ts index a708d04e8..896b5358d 100644 --- a/src/gateway/routing/request-match.test.ts +++ b/src/gateway/routing/request-match.test.ts @@ -206,6 +206,10 @@ describe("matchRequest", () => { expect(listsModel(worker(PHONES), { platform: "ios" })).toBe(true); }); + it("matches no runtime for a string the OS grammar refuses", () => { + expect(matchRequest(worker(PHONES), { ...phone, osVersion: "^18" })).toBeUndefined(); + }); + it("reads no inherited key as a class", () => { const view = worker({ ...PHONES, modelClasses: {} as const, models: ["constructor"] }); diff --git a/src/gateway/routing/request-match.ts b/src/gateway/routing/request-match.ts index dd9fcdde5..0c95c0ec4 100644 --- a/src/gateway/routing/request-match.ts +++ b/src/gateway/routing/request-match.ts @@ -6,7 +6,12 @@ import { requestedClass } from "../../contract/index.js"; import { type OsConstraint, parseOsConstraint, satisfies } from "../../contract/os-range.js"; import { findCatalogModel, modelClass, pairedRuntimes } from "../../core/catalog-match.js"; -import type { DeviceClass, DeviceRequirement } from "../../core/domain.js"; +import { + type DeviceClass, + type DeviceRequirement, + type DeviceSpec, + fits, +} from "../../core/domain.js"; import type { WorkerView } from "../worker-registry.js"; import type { RoutableRequest } from "./pipeline.js"; @@ -23,69 +28,60 @@ import type { RoutableRequest } from "./pipeline.js"; */ export function matchRequest(worker: WorkerView, request: RoutableRequest): string | undefined { const catalog = catalogOf(worker, request); - if (catalog === undefined) return undefined; + return catalog === undefined ? undefined : servingModel(catalog, request); +} + +/** The first model of the entry that could serve the request: a pairing in the OS constraint. */ +function servingModel(catalog: PlatformEntry, request: RoutableRequest): string | undefined { return candidates(catalog, request).find((model) => pairedRuntimesOf(catalog, model, request).some((runtime) => osFits(runtime, request)), ); } /** - * The runtime the worker would pick for an exact request, or `undefined` when the gateway cannot - * say (ADR 0009 §6). The one the request names, when it names an exact version. With none named: - * the catalog's `defaultRuntime` when the model pairs with it, otherwise the model's only paired - * runtime. A model with several paired runtimes and no paired default has no answer: the worker's - * choice then depends on what it would boot, and the gateway compares no versions. + * What a ready device must satisfy, on this worker, to serve the request (ADR 0015 §6, §8): the + * core's `fits` over a requirement built from the worker's own catalog. `undefined` when the + * worker cannot serve the request. The mode is not part of it; `warm-hit` keeps that rule. */ -export function pickedRuntime(worker: WorkerView, request: RoutableRequest): string | undefined { - const constraint = osConstraintOf(request); - if (constraint?.kind === "exact") return constraint.version; - if (constraint !== undefined) return undefined; +export function deviceFit( + worker: WorkerView, + request: RoutableRequest, +): ((spec: DeviceSpec) => boolean) | undefined { const catalog = catalogOf(worker, request); - if (catalog === undefined || request.model === undefined) return undefined; - const model = findCatalogModel(catalog, request.model); + if (catalog === undefined) return undefined; + const model = servingModel(catalog, request); if (model === undefined) return undefined; - const runtimes = pairedRuntimesOf(catalog, model, request); - const paired = runtimes.find((runtime) => runtime === catalog.defaultRuntime); - return paired ?? (runtimes.length === 1 ? runtimes[0] : undefined); + const requirement: DeviceRequirement = { + imageTag: request.imageTag, + osVersion: osRequirement(catalog, model, request), + platform: request.platform, + target: + request.model === undefined + ? { class: wantedClass(request), kind: "class" } + : { kind: "model", model }, + }; + return (spec) => fits(requirement, spec, (listed) => modelClass(catalog, listed)); } /** - * The requirement a ready device must `fit` to serve the request on this worker (ADR 0015 §6), or - * `undefined` when the gateway cannot say which runtime the worker would pick. A class request - * with no OS accepts any installed runtime; an exact one with no OS, the runtime the worker would - * pick. The mode is not part of it. + * The OS a device must have. What the request names, exact or a range. With none named: a class + * accepts any installed runtime, and an exact model needs the runtime the worker would pick -- the + * catalog's `defaultRuntime` when the model pairs with it, otherwise its only paired runtime. A + * model with several paired runtimes and no paired default has no answer: the worker's choice then + * depends on what it would boot, and the gateway compares no versions, so no device fits. */ -export function requirementOf( - worker: WorkerView, +function osRequirement( + catalog: PlatformEntry, + model: string, request: RoutableRequest, -): DeviceRequirement | undefined { - const catalog = catalogOf(worker, request); - const model = matchRequest(worker, request); - if (catalog === undefined || model === undefined) return undefined; - const target: DeviceRequirement["target"] = - request.model === undefined - ? { class: wantedClass(request), kind: "class" } - : { kind: "model", model }; +): DeviceRequirement["osVersion"] { const constraint = osConstraintOf(request); - let osVersion: DeviceRequirement["osVersion"] | undefined; - if (constraint !== undefined) osVersion = constraint; - else if (request.model === undefined) - osVersion = { kind: "installed", versions: catalog.runtimes }; - else { - const picked = pickedRuntime(worker, request); - osVersion = picked === undefined ? undefined : { kind: "exact", version: picked }; - } - if (osVersion === undefined) return undefined; - return { imageTag: request.imageTag, osVersion, platform: request.platform, target }; -} - -/** The class a model is listed under on this worker, for `fits`. */ -export function classOfModel( - worker: WorkerView, - request: RoutableRequest, -): (model: string) => DeviceClass | undefined { - const catalog = catalogOf(worker, request); - return (model) => (catalog === undefined ? undefined : modelClass(catalog, model)); + if (constraint !== undefined) return constraint; + if (request.model === undefined) return { kind: "installed", versions: catalog.runtimes }; + const runtimes = pairedRuntimesOf(catalog, model, request); + const picked = runtimes.find((runtime) => runtime === catalog.defaultRuntime); + const versions = picked === undefined ? (runtimes.length === 1 ? runtimes : []) : [picked]; + return { kind: "installed", versions }; } /** diff --git a/src/gateway/routing/serviceability.test.ts b/src/gateway/routing/serviceability.test.ts index 8a239e110..06956c761 100644 --- a/src/gateway/routing/serviceability.test.ts +++ b/src/gateway/routing/serviceability.test.ts @@ -185,8 +185,11 @@ describe("assess", () => { details: { class: "watch", platform: "ios" }, reason: "unresolvable-spec", }); - const details = rejectionOf([view("wrk_a", PHONE)], { ...request, class: "watch" }).details; - expect(details).not.toHaveProperty("model"); + const rejection = rejectionOf([view("wrk_a", PHONE)], { ...request, class: "watch" }); + expect(rejection.details).not.toHaveProperty("model"); + expect(rejection.message).toBe( + "No ios model of class watch is listed by any worker in the fleet; name one in ios.defaultModels.watch on a worker", + ); }); it("row 3: treats a request naming neither model nor class as phone", () => { diff --git a/src/gateway/routing/stages/warm-hit.ts b/src/gateway/routing/stages/warm-hit.ts index 050b0638d..007fdb1c4 100644 --- a/src/gateway/routing/stages/warm-hit.ts +++ b/src/gateway/routing/stages/warm-hit.ts @@ -1,6 +1,6 @@ -import { type DeviceSpec, fits } from "../../../core/domain.js"; +import type { DeviceSpec } from "../../../core/domain.js"; import type { WorkerView } from "../../worker-registry.js"; -import { classOfModel, requirementOf } from "../request-match.js"; +import { deviceFit } from "../request-match.js"; import type { RankStage } from "../pipeline.js"; /** @@ -19,13 +19,12 @@ export const warmHit: RankStage = { kind: "rank", name: "warm-hit", score(worker, request) { - const requirement = requirementOf(worker, request); - if (requirement === undefined) return 0; - const classOf = classOfModel(worker, request); + const fitsRequest = deviceFit(worker, request); + if (fitsRequest === undefined) return 0; const warm = worker.devices.some( (device) => device.state === "ready" && - fits(requirement, deviceSpec(device.spec), classOf) && + fitsRequest(deviceSpec(device.spec)) && (request.mode === undefined ? device.servesDefaultMode : device.mode === request.mode), ); return warm ? 1 : 0;