From 9122c5232937d1969f0fb9b2fd3c4bc60dfcbb05 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 5 Nov 2026 22:13:28 +0100 Subject: [PATCH 1/3] refactor(leasing): split lease-acquisition-coordinator.test.ts into parts (ADR 0063) --- src/leasing/AGENTS.md | 32 +- src/leasing/lease-acquisition-class.test.ts | 774 +++++++ .../lease-acquisition-coordinator.test.ts | 1946 +---------------- .../lease-acquisition-resolution.test.ts | 767 +++++++ src/leasing/test-lease-acquisition.ts | 295 +++ src/source-hygiene.test.ts | 1 - 6 files changed, 1921 insertions(+), 1894 deletions(-) create mode 100644 src/leasing/lease-acquisition-class.test.ts create mode 100644 src/leasing/lease-acquisition-resolution.test.ts create mode 100644 src/leasing/test-lease-acquisition.ts diff --git a/src/leasing/AGENTS.md b/src/leasing/AGENTS.md index 4f9781d28..e94e2cc89 100644 --- a/src/leasing/AGENTS.md +++ b/src/leasing/AGENTS.md @@ -8,22 +8,22 @@ Flows: [device selection](../../docs/internal/flows/device-selection.md), [start ## Files -| File | Role | -| ----------------------------------------- | ------------------------------------------------------------------------------------------------- | -| `create-leasing.ts` | Composition root; builds `corePorts` for `core.connect` | -| `lease-acquisition-coordinator.ts` | Admission, spec resolution, plan → perform loop, grant | -| `acquisition-planner.ts` | Read-only plan; takes the claim or reservation it hands back | -| `wait-queue.ts` | FIFO, two lines (virtual, physical), timeouts, cancel; `requesterLimitDecision` | -| `lease-request-book.ts` | Request records: store before queue, idempotent replay, settle once | -| `lease-lifecycle.ts` | Registry half of grant, renew, release | -| `lease-expiry-scheduler.ts` | TTL timers | -| `lease-release-coordinator.ts` | Every lease ending; lease-end participants; background reclaim | -| `lease-health-monitor.ts` | Reboots a crashed leased virtual device under its lease | -| `physical-device-watcher.ts` | Presence polling of enrolled physical devices | -| `lease-startup.ts`, `lease-reconciler.ts` | Lease half of startup | -| `lease-refusal.ts` | `lease.rejected`, or `lease.declined` for a gateway request | -| `lease-ports.ts` | `LeaseCommands`, `QueueControl`, `LeaseEndParticipant` | -| `testing.ts` | Builds core + leasing for other modules' tests; `TestEngineConfig` is the config slice that takes | +| File | Role | +| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `create-leasing.ts` | Composition root; builds `corePorts` for `core.connect` | +| `lease-acquisition-coordinator.ts` | Admission, spec resolution, plan → perform loop, grant | +| `acquisition-planner.ts` | Read-only plan; takes the claim or reservation it hands back | +| `wait-queue.ts` | FIFO, two lines (virtual, physical), timeouts, cancel; `requesterLimitDecision` | +| `lease-request-book.ts` | Request records: store before queue, idempotent replay, settle once | +| `lease-lifecycle.ts` | Registry half of grant, renew, release | +| `lease-expiry-scheduler.ts` | TTL timers | +| `lease-release-coordinator.ts` | Every lease ending; lease-end participants; background reclaim | +| `lease-health-monitor.ts` | Reboots a crashed leased virtual device under its lease | +| `physical-device-watcher.ts` | Presence polling of enrolled physical devices | +| `lease-startup.ts`, `lease-reconciler.ts` | Lease half of startup | +| `lease-refusal.ts` | `lease.rejected`, or `lease.declined` for a gateway request | +| `lease-ports.ts` | `LeaseCommands`, `QueueControl`, `LeaseEndParticipant` | +| `testing.ts`, `test-lease-acquisition.ts` | Builds core + leasing for other modules' tests; `TestEngineConfig` is the config slice that takes; the harness the `lease-acquisition*.test.ts` parts share | ## The update hold diff --git a/src/leasing/lease-acquisition-class.test.ts b/src/leasing/lease-acquisition-class.test.ts new file mode 100644 index 000000000..ea66487cb --- /dev/null +++ b/src/leasing/lease-acquisition-class.test.ts @@ -0,0 +1,774 @@ +import { describe, expect, it } from "vitest"; + +import { FakeClock } from "../ports/index.js"; +import { type ModelPreferences, RuntimeMissingError, type VirtualSpec } from "../core/index.js"; +import { FakeDriver } from "../core/testing.js"; +import { IdempotencyConflictError } from "./lease-request-book.js"; +import { + createHarness, + seedReady, + flush, + settle, + seedShutdown, + installs, +} from "./test-lease-acquisition.js"; + +// why: drives the coordinator on its own, so a test can script the catalog and the devices a class request finds in ways the leasing surface cannot force. +describe("LeaseAcquisitionCoordinator: class requests", () => { + const owner = (id: string) => ({ ownerId: id, requesterId: id }); + const iosModels = ["iPhone 15", "iPhone 16", "iPhone 17", "Apple Watch", "iPad Pro"]; + const iosClasses = { + "Apple Watch": "watch", + "iPad Pro": "tablet", + "iPhone 15": "phone", + "iPhone 16": "phone", + "iPhone 17": "phone", + } as const; + const iosPreferences: ModelPreferences = { + ios: { + phone: ["iPhone 17", "iPhone 16", "iPhone 15"], + tablet: ["iPad Pro"], + watch: ["Apple Watch"], + }, + }; + const phone = { class: "phone", platform: "ios" } as const; + const iphone15 = { + physical: false, + model: "iPhone 15", + osVersion: "18.4", + platform: "ios", + } as const; + + function iosDriver(options: Partial[0]> = {}) { + return new FakeDriver({ + availableOsVersions: ["18.4", "26.5"], + clock: new FakeClock(1_000), + knownModels: iosModels, + modelClasses: iosClasses, + platform: "ios", + ...options, + }); + } + + function deviceWork(driver: FakeDriver): number { + return driver.calls.filter((call) => ["provision", "makeReady"].includes(call.operation)) + .length; + } + + function provisioned(harness: Awaited>) { + return harness.bus + .replay() + .filter((event) => event.event === "device.provisioned") + .map((event) => (event.payload as { spec: VirtualSpec }).spec); + } + + async function classHarness(driver = iosDriver(), preferences = iosPreferences) { + return createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2, preferences }); + } + + it("resolves a request with neither model nor class as the phone class, and lease.requested carries neither", async () => { + const harness = await classHarness(); + + const granted = await harness.coordinator.request({ platform: "ios" }, owner("agent")); + + expect(granted.device.spec).toMatchObject({ model: "iPhone 17", osVersion: "26.5" }); + const requested = harness.bus.replay().filter((event) => event.event === "lease.requested"); + expect( + requested.map((event) => (event.payload as { requestSpec: unknown }).requestSpec), + ).toEqual([{ platform: "ios" }]); + }); + + it("grants a phone request one ready idle iPhone 15 with no boot and no provision", async () => { + const driver = iosDriver(); + const harness = await classHarness(driver); + const warm = await seedReady(harness, iphone15); + const before = deviceWork(driver); + + const granted = await harness.coordinator.request(phone, owner("agent")); + + expect(granted.device.id).toBe(warm.id); + expect(deviceWork(driver)).toBe(before); + }); + + it("does not grant an exact iPhone 16 request a ready idle iPhone 15", async () => { + const harness = await classHarness(); + const warm = await seedReady(harness, { ...iphone15, osVersion: "26.5" }); + + const granted = await harness.coordinator.request( + { model: "iPhone 16", platform: "ios" }, + owner("agent"), + ); + + expect(granted.device.id).not.toBe(warm.id); + expect(granted.device.spec.model).toBe("iPhone 16"); + }); + + it("does not grant a request with no class a ready idle Apple Watch, and grants a watch request it", async () => { + const watch = { + physical: false, + model: "Apple Watch", + osVersion: "26.5", + platform: "ios", + } as const; + const first = await classHarness(); + const warm = await seedReady(first, watch); + + const noClass = await first.coordinator.request({ platform: "ios" }, owner("agent")); + expect(noClass.device.id).not.toBe(warm.id); + + const second = await classHarness(); + const warmWatch = await seedReady(second, watch); + const granted = await second.coordinator.request( + { class: "watch", platform: "ios" }, + owner("agent"), + ); + expect(granted.device.id).toBe(warmWatch.id); + }); + + it("boots a shut-down device of the class before creating any device", async () => { + const driver = iosDriver(); + const harness = await classHarness(driver); + const cold = await seedShutdown(harness, iphone15); + const provisions = () => driver.calls.filter((call) => call.operation === "provision").length; + const before = provisions(); + + const granted = await harness.coordinator.request(phone, owner("agent")); + + expect(granted.device.id).toBe(cold.id); + expect(provisions()).toBe(before); + }); + + describe("device mode", () => { + const slimming = () => + iosDriver({ availableOsVersions: ["26.5"], slimmableOsVersions: ["26.5"] }); + const full15 = { ...iphone15, osVersion: "26.5" } as const; + const slim15 = { ...full15, mode: "slim" } as const; + + it("never grants a full request a slim device of the class", async () => { + const harness = await classHarness(slimming()); + const slim = await seedReady(harness, slim15); + + const granted = await harness.coordinator.request({ ...phone, mode: "full" }, owner("agent")); + + expect(granted.device.id).not.toBe(slim.id); + expect(granted.device.mode).toBe("full"); + }); + + it.each([ + { defaultMode: "full", seeded: slim15, name: "a slim device when the default mode is full" }, + { defaultMode: "slim", seeded: full15, name: "a full device when the default mode is slim" }, + ] as const)("does not grant a request with no mode $name", async ({ defaultMode, seeded }) => { + const harness = await createHarness({ + defaultModes: { ios: defaultMode }, + drivers: [slimming()], + maxDevices: 2, + preferences: iosPreferences, + }); + const idle = await seedReady(harness, seeded); + + const granted = await harness.coordinator.request(phone, owner("agent")); + + expect(granted.device.id).not.toBe(idle.id); + expect(granted.device.mode).toBe(defaultMode); + }); + }); + + describe("image tags", () => { + const pixel = { + physical: false, + model: "Pixel 8", + osVersion: "34", + platform: "android", + } as const; + const androidPhone = { class: "phone", platform: "android" } as const; + const androidPreferences: ModelPreferences = { android: { phone: ["Pixel 9", "Pixel 8"] } }; + const androidDriver = () => + new FakeDriver({ + availableOsVersions: ["34", "35"], + clock: new FakeClock(1_000), + images: [ + { abi: "arm64-v8a", runtime: "34", tag: "google_apis" }, + { abi: "arm64-v8a", runtime: "34", tag: "google_apis_playstore" }, + { abi: "arm64-v8a", runtime: "35", tag: "google_apis" }, + ], + knownModels: ["Pixel 8", "Pixel 9"], + modelClasses: { "Pixel 8": "phone", "Pixel 9": "phone" }, + modelRuntimes: { "Pixel 8": ["34"], "Pixel 9": ["35"] }, + platform: "android", + }); + + it.each([ + ["of another tag", { imageTag: "google_apis" }, "google_apis_playstore"], + ["with no tag", {}, "google_apis_playstore"], + ] as const)( + "does not grant a request naming a tag an idle device %s", + async (_label, seeded, asked) => { + const harness = await classHarness(androidDriver(), androidPreferences); + const other = await seedReady(harness, { ...pixel, ...seeded }); + + const granted = await harness.coordinator.request( + { ...androidPhone, imageTag: asked }, + owner("agent"), + ); + + expect(granted.device.id).not.toBe(other.id); + expect(granted.device.spec.imageTag).toBe(asked); + }, + ); + + it("does not grant a request naming no tag an idle device with a tag", async () => { + const harness = await classHarness(androidDriver(), androidPreferences); + const tagged = await seedReady(harness, { ...pixel, imageTag: "google_apis_playstore" }); + + const granted = await harness.coordinator.request(androidPhone, owner("agent")); + + expect(granted.device.id).not.toBe(tagged.id); + expect(granted.device.spec).not.toHaveProperty("imageTag"); + }); + + it("grants a request naming a tag an idle device of that tag", async () => { + const harness = await classHarness(androidDriver(), androidPreferences); + const tagged = await seedReady(harness, { ...pixel, imageTag: "google_apis_playstore" }); + + const granted = await harness.coordinator.request( + { ...androidPhone, imageTag: "google_apis_playstore" }, + owner("agent"), + ); + + expect(granted.device.id).toBe(tagged.id); + }); + + it("skips a candidate whose only pairings carry another tag", async () => { + const harness = await classHarness(androidDriver(), androidPreferences); + + const granted = await harness.coordinator.request( + { ...androidPhone, imageTag: "google_apis_playstore" }, + owner("agent"), + ); + + expect(granted.device.spec).toMatchObject({ model: "Pixel 8", osVersion: "34" }); + }); + }); + + describe("OS", () => { + it("fits a class request with no OS to a device on a listed runtime, and not one on a runtime no longer listed", async () => { + const listed = await classHarness(); + const old = await seedReady(listed, iphone15); + const grantedListed = await listed.coordinator.request(phone, owner("agent")); + expect(grantedListed.device.id).toBe(old.id); + + const gone = await classHarness(); + const stale = await seedReady(gone, { ...iphone15, osVersion: "17.0" }); + const grantedGone = await gone.coordinator.request(phone, owner("agent")); + expect(grantedGone.device.id).not.toBe(stale.id); + expect(grantedGone.device.spec.osVersion).toBe("26.5"); + }); + + it("fits an exact request with no OS only to the runtime the driver picks, as on main", async () => { + const harness = await classHarness(); + const old = await seedReady(harness, iphone15); + + const granted = await harness.coordinator.request( + { model: "iPhone 15", platform: "ios" }, + owner("agent"), + ); + + expect(granted.device.id).not.toBe(old.id); + expect(granted.device.spec.osVersion).toBe("26.5"); + }); + }); + + describe("OS ranges", () => { + const rangeDriver = (options: Partial[0]> = {}) => + iosDriver({ + availableOsVersions: ["18.0", "18.4", "26.5"], + modelRuntimes: { + "iPhone 15": ["18.0", "18.4", "26.5"], + "iPhone 16": ["18.0", "18.4", "26.5"], + "iPhone 17": ["26.5"], + }, + ...options, + }); + + it("sends a class request with no osVersion to the driver without pinning a runtime", async () => { + const driver = rangeDriver(); + const harness = await classHarness(driver); + + await harness.coordinator.request({ platform: "ios" }, owner("agent")); + + const resolve = driver.calls.find((call) => call.operation === "resolveSpec"); + expect(resolve?.arguments[0]).toEqual({ mode: "full", model: "iPhone 17", platform: "ios" }); + }); + + it("grants a ready idle device whose OS satisfies the range, and not one outside it", async () => { + const inside = await classHarness(rangeDriver()); + const warm = await seedReady(inside, { ...iphone15, osVersion: "18.0" }); + const grantedInside = await inside.coordinator.request( + { ...phone, osVersion: ">=18 <26" }, + owner("agent"), + ); + expect(grantedInside.device.id).toBe(warm.id); + + const outside = await classHarness(rangeDriver()); + const stale = await seedReady(outside, { ...iphone15, osVersion: "26.5" }); + const grantedOutside = await outside.coordinator.request( + { ...phone, osVersion: ">=18 <26" }, + owner("agent"), + ); + expect(grantedOutside.device.id).not.toBe(stale.id); + expect(grantedOutside.device.spec.osVersion).toBe("18.4"); + }); + + it("fails an exact model the catalog does not list, sent with a range, at once with UnknownModelError", async () => { + const driver = rangeDriver(); + const harness = await classHarness(driver); + + await expect( + harness.coordinator.request( + { model: "iPhone 99", osVersion: ">=18", platform: "ios" }, + owner("agent"), + ), + ).rejects.toMatchObject({ model: "iPhone 99", name: "UnknownModelError" }); + expect(deviceWork(driver)).toBe(0); + }); + + it("grants an exact model with a range a ready idle device of that model in range, and not one of another model", async () => { + const harness = await classHarness(rangeDriver()); + const other = await seedReady(harness, { ...iphone15, osVersion: "18.0" }); + const same = await seedReady(harness, { + physical: false, + model: "iPhone 16", + osVersion: "18.0", + platform: "ios", + }); + const before = deviceWork(harness.driver); + + const granted = await harness.coordinator.request( + { model: "iPhone 16", osVersion: ">=18 <26", platform: "ios" }, + owner("agent"), + ); + + expect(granted.device.id).toBe(same.id); + expect(granted.device.id).not.toBe(other.id); + expect(deviceWork(harness.driver)).toBe(before); + }); + + it("fails an exact model with a range at once with UnknownModelError when the platform lists no catalog", async () => { + const harness = await createHarness({ + catalogReader: { listCatalog: async () => [] }, + drivers: [rangeDriver()], + }); + + await expect( + harness.coordinator.request( + { model: "iPhone 16", osVersion: ">=18", platform: "ios" }, + owner("agent"), + ), + ).rejects.toMatchObject({ model: "iPhone 16", name: "UnknownModelError" }); + }); + + it("never installs for a range even when the driver then reports a downloadable runtime missing", async () => { + class Racing extends FakeDriver { + override async resolveSpec(): Promise { + throw new RuntimeMissingError("ios", "18.4", { component: "18.4" }); + } + } + const asked: unknown[] = []; + const harness = await createHarness({ + components: { + install: async (call) => { + asked.push(call); + return { outcome: "installed", version: "18.4" }; + }, + }, + drivers: [ + new Racing({ + availableOsVersions: ["18.4"], + clock: new FakeClock(1_000), + knownModels: ["iPhone 16"], + modelClasses: { "iPhone 16": "phone" }, + platform: "ios", + }), + ], + }); + + await expect( + harness.coordinator.request( + { model: "iPhone 16", osVersion: ">=18", platform: "ios" }, + { ...owner("agent"), allowDownload: true }, + ), + ).rejects.toMatchObject({ name: "RuntimeMissingError" }); + expect(asked).toEqual([]); + }); + + it("creates an exact model with a range on the newest listed pairing in range", async () => { + const harness = await classHarness(rangeDriver()); + + const granted = await harness.coordinator.request( + { model: "iPhone 16", osVersion: "<26", platform: "ios" }, + owner("agent"), + ); + + expect(granted.device.spec).toMatchObject({ model: "iPhone 16", osVersion: "18.4" }); + expect(provisioned(harness).map((spec) => spec.osVersion)).toEqual(["18.4"]); + }); + + it.each([ + ["without allowDownload", false], + ["with allowDownload", true], + ])( + "fails an exact model with a range nothing installed satisfies at once with RuntimeMissingError, not downloadable, naming the range, and never installs, %s", + async (_label, allowDownload) => { + const driver = rangeDriver(); + const harness = await classHarness(driver); + + await expect( + harness.coordinator.request( + { model: "iPhone 16", osVersion: "<=17", platform: "ios" }, + { ...owner("agent"), allowDownload }, + ), + ).rejects.toMatchObject({ + downloadable: false, + name: "RuntimeMissingError", + osVersion: "<=17", + }); + expect(installs(driver)).toEqual([]); + expect(deviceWork(driver)).toBe(0); + }, + ); + + it.each([["Baklava"], ["34-ext12"]])( + "reaches resolveSpec with the bare version %s exact, as without ranges, and a range never picks it", + async (name) => { + const driver = rangeDriver({ + availableOsVersions: ["18.4", name], + modelRuntimes: { "iPhone 16": ["18.4", name] }, + }); + const harness = await classHarness(driver); + + await harness.coordinator.request( + { model: "iPhone 16", osVersion: name, platform: "ios" }, + owner("agent"), + ); + const resolved = driver.calls.find((call) => call.operation === "resolveSpec"); + expect(resolved?.arguments[0]).toMatchObject({ osVersion: name }); + + const ranged = await classHarness(driver); + const granted = await ranged.coordinator.request( + { model: "iPhone 16", osVersion: ">=18", platform: "ios" }, + owner("agent"), + ); + expect(granted.device.spec.osVersion).toBe("18.4"); + }, + ); + + it("picks the newest in-range runtime whatever order the catalog lists them in", async () => { + const harness = await classHarness( + rangeDriver({ + availableOsVersions: ["18.4", "26.5", "9.3", "18.0"], + modelRuntimes: { "iPhone 16": ["18.4", "26.5", "9.3", "18.0"] }, + }), + ); + + const granted = await harness.coordinator.request( + { model: "iPhone 16", osVersion: "<26", platform: "ios" }, + owner("agent"), + ); + + expect(granted.device.spec.osVersion).toBe("18.4"); + }); + + it("takes the first class candidate that has an in-range pairing and its newest such runtime: <=18 creates an iPhone 16 on the newest 18.x", async () => { + const harness = await classHarness(rangeDriver()); + + const granted = await harness.coordinator.request( + { ...phone, osVersion: "<=18" }, + owner("agent"), + ); + + expect(granted.device.spec).toMatchObject({ model: "iPhone 16", osVersion: "18.4" }); + }); + + it.each([ + ["without allowDownload", false], + ["with allowDownload", true], + ])( + "fails a class with a range no candidate pairs with at once with RuntimeMissingError and never installs, %s", + async (_label, allowDownload) => { + const driver = rangeDriver(); + const harness = await classHarness(driver); + + await expect( + harness.coordinator.request( + { ...phone, osVersion: "<=17" }, + { ...owner("agent"), allowDownload }, + ), + ).rejects.toMatchObject({ + downloadable: false, + name: "RuntimeMissingError", + osVersion: "<=17", + }); + expect(installs(driver)).toEqual([]); + }, + ); + + it("does not pick a runtime in range whose only images carry another tag: API 35 default only and API 34 google_apis, >=33 with tag google_apis creates on 34", async () => { + const driver = new FakeDriver({ + availableOsVersions: ["34", "35"], + clock: new FakeClock(1_000), + images: [ + { abi: "arm64-v8a", runtime: "34", tag: "google_apis" }, + { abi: "arm64-v8a", runtime: "35", tag: "default" }, + ], + knownModels: ["Pixel 8"], + modelClasses: { "Pixel 8": "phone" }, + modelRuntimes: { "Pixel 8": ["34", "35"] }, + platform: "android", + }); + const harness = await classHarness(driver, { android: { phone: ["Pixel 8"] } }); + + const byModel = await harness.coordinator.request( + { + imageTag: "google_apis", + model: "Pixel 8", + osVersion: ">=33", + platform: "android", + }, + owner("agent"), + ); + expect(byModel.device.spec).toMatchObject({ imageTag: "google_apis", osVersion: "34" }); + }); + }); + + describe("creating a device for a class", () => { + it("creates the first name on the class's list the catalog lists, and device.provisioned carries that model", async () => { + const harness = await classHarness(); + + const granted = await harness.coordinator.request(phone, owner("agent")); + + expect(granted.device.spec.model).toBe("iPhone 17"); + expect(provisioned(harness).map((spec) => spec.model)).toEqual(["iPhone 17"]); + }); + + it.each([ + ["a name the catalog does not list", "Unlisted Phone", {}], + ["a name of another class", "iPad Pro", {}], + ["a name with no pairing", "Orphan", { modelRuntimes: { Orphan: [] } }], + ] as const)("skips %s for the next on the list", async (_label, skipped, driverOptions) => { + const driver = iosDriver({ + ...driverOptions, + knownModels: [...iosModels, "Orphan"], + modelClasses: { ...iosClasses, Orphan: "phone" }, + }); + const harness = await classHarness(driver, { + ios: { phone: [skipped, "iPhone 16"] }, + }); + + const granted = await harness.coordinator.request(phone, owner("agent")); + + expect(granted.device.spec.model).toBe("iPhone 16"); + }); + + it.each([ + ["without allowDownload", false], + ["with allowDownload", true], + ])( + "fails a class whose listed models pair with no installed runtime at once with RuntimeMissingError, not downloadable, %s", + async (_label, allowDownload) => { + const asked: unknown[] = []; + const driver = iosDriver({ modelRuntimes: { "iPhone 16": [] } }); + const harness = await createHarness({ + components: { + install: async (call) => { + asked.push(call); + return { outcome: "installed", version: "27.0" }; + }, + }, + drivers: [driver], + preferences: { ios: { phone: ["iPhone 16"] } }, + }); + + await expect( + harness.coordinator.request(phone, { ...owner("agent"), allowDownload }), + ).rejects.toMatchObject({ downloadable: false, name: "RuntimeMissingError" }); + expect(asked).toEqual([]); + expect(deviceWork(driver)).toBe(0); + }, + ); + + it.each([ + ["ios", "ios.defaultModels.phone", { ...phone }], + ["android", "android.defaultModels.tablet", { class: "tablet", platform: "android" }], + ] as const)( + "fails a class with no listed name at once with UnknownModelError naming the class and %s, whatever is idle", + async (platform, key, asked) => { + const driver = new FakeDriver({ + availableOsVersions: ["18.4"], + clock: new FakeClock(1_000), + knownModels: ["iPhone 15"], + modelClasses: { "iPhone 15": "phone" }, + platform, + }); + const harness = await classHarness(driver, { + [platform]: { phone: ["Unlisted Phone"], tablet: ["Unlisted Tablet"] }, + }); + await seedReady( + harness, + platform === "ios" + ? iphone15 + : { model: "Pixel 8", osVersion: "34", physical: false, platform: "android" }, + ); + + await expect(harness.coordinator.request(asked, owner("agent"))).rejects.toMatchObject({ + class: asked.class, + message: expect.stringContaining(key), + name: "UnknownModelError", + platform, + }); + }, + ); + + it("fails a class request at once with UnknownModelError when the platform has no preference list at all", async () => { + const harness = await classHarness(iosDriver(), {}); + + await expect(harness.coordinator.request(phone, owner("agent"))).rejects.toMatchObject({ + class: "phone", + name: "UnknownModelError", + message: expect.stringContaining("ios.defaultModels.phone"), + }); + }); + + it("lists a queued class request's class requirement and the catalog's class lookup", async () => { + const harness = await createHarness({ + drivers: [iosDriver()], + maxDevices: 1, + maxRunning: 1, + preferences: iosPreferences, + }); + await harness.coordinator.request(phone, owner("holder")); + void harness.coordinator.request(phone, owner("waiter")).catch(() => undefined); + await settle(); + + const [demand] = harness.coordinator.waitingDemand(); + + expect(demand).toMatchObject({ + inFlight: false, + mode: "full", + platform: "ios", + requirement: { platform: "ios", target: { class: "phone", kind: "class" } }, + }); + expect(demand?.classOf("iPhone 15")).toBe("phone"); + }); + + it("lists no waiting demand for a request whose class is still being resolved", async () => { + let open: () => void = () => undefined; + const gate = new Promise((resolve) => { + open = resolve; + }); + const harness = await createHarness({ + catalogReader: { + listCatalog: async () => { + await gate; + return []; + }, + }, + drivers: [iosDriver()], + preferences: iosPreferences, + }); + + const pending = harness.coordinator.request(phone, owner("agent")); + const settled = pending.catch(() => undefined); + await flush(); + const whileResolving = harness.coordinator.waitingDemand(); + open(); + await settled; + + expect(whileResolving).toEqual([]); + await expect(pending).rejects.toMatchObject({ name: "UnknownModelError" }); + }); + + it.each([ + ["names none", undefined, "default"], + ["names a version", "18.4", "18.4"], + ])( + "names the OS in the RuntimeMissingError of a class whose models pair with no runtime when the request %s", + async (_label, osVersion, named) => { + const driver = iosDriver({ modelRuntimes: { "iPhone 16": [] } }); + const harness = await classHarness(driver, { ios: { phone: ["iPhone 16"] } }); + + await expect( + harness.coordinator.request( + { ...phone, ...(osVersion === undefined ? {} : { osVersion }) }, + owner("agent"), + ), + ).rejects.toMatchObject({ name: "RuntimeMissingError", osVersion: named }); + }, + ); + + it("fits a class request naming an OS only a device on that OS, and creates a device on it otherwise", async () => { + const harness = await classHarness(); + const newest = await seedReady(harness, { ...iphone15, osVersion: "26.5" }); + + const older = await harness.coordinator.request( + { ...phone, osVersion: "18.4" }, + owner("agent"), + ); + + expect(older.device.id).not.toBe(newest.id); + expect(older.device.spec.osVersion).toBe("18.4"); + + const sameOs = await classHarness(); + const warm = await seedReady(sameOs, iphone15); + const granted = await sameOs.coordinator.request( + { ...phone, osVersion: "18.4" }, + owner("agent"), + ); + expect(granted.device.id).toBe(warm.id); + }); + + it("fails a class request naming an image tag on a driver with no images with RuntimeMissingError, not downloadable", async () => { + const harness = await classHarness(); + + await expect( + harness.coordinator.request({ ...phone, imageTag: "google_apis" }, owner("agent")), + ).rejects.toMatchObject({ downloadable: false, name: "RuntimeMissingError" }); + }); + + it("passes the driver an exact model, never a class", async () => { + const driver = iosDriver(); + const harness = await classHarness(driver); + + await harness.coordinator.request(phone, owner("agent")); + + const resolved = driver.calls.find((call) => call.operation === "resolveSpec"); + expect(resolved?.arguments[0]).toMatchObject({ model: "iPhone 17" }); + expect(resolved?.arguments[0]).not.toHaveProperty("class"); + }); + }); + + describe("idempotency", () => { + const keyed = { ...owner("agent"), idempotencyKey: "key-1" }; + + it("returns the stored grant to a repeat of the same class request", async () => { + const harness = await classHarness(); + const first = await harness.coordinator.request(phone, keyed); + + const second = await harness.coordinator.request(phone, keyed); + + expect(second.lease.id).toBe(first.lease.id); + }); + + it.each([ + ["an exact request", { model: "iPhone 17", platform: "ios" }], + ["a request of another class", { class: "watch", platform: "ios" }], + ["a request with neither field", { platform: "ios" }], + ] as const)("refuses the key of a class request used for %s", async (_label, other) => { + const harness = await classHarness(); + await harness.coordinator.request(phone, keyed); + + await expect(harness.coordinator.request(other, keyed)).rejects.toBeInstanceOf( + IdempotencyConflictError, + ); + }); + }); +}); diff --git a/src/leasing/lease-acquisition-coordinator.test.ts b/src/leasing/lease-acquisition-coordinator.test.ts index c2e8e2bda..0031391c6 100644 --- a/src/leasing/lease-acquisition-coordinator.test.ts +++ b/src/leasing/lease-acquisition-coordinator.test.ts @@ -1,273 +1,28 @@ import { describe, expect, it, vi } from "vitest"; -import { EventBus } from "../bus/index.js"; -import { - FakeClock, - FakeSystemStats, - JsonLinesLogger, - type Logger, - MemoryFilesystem, - MemoryLogSink, -} from "../ports/index.js"; +import { FakeClock, JsonLinesLogger, type Logger, MemoryLogSink } from "../ports/index.js"; import type { StateDatabase } from "../state/index.js"; import { promiseState } from "../test-support/promise-state.js"; -import { AcquisitionPlanner } from "./acquisition-planner.js"; import { - CapacityCoordinator, capacityDevice, capacityDevices, - type Config, - DeviceOperationClaims, - DeviceProvisioner, - ComponentInstaller, - DriverCatalog, - type ModelPreferences, - DiskSpaceGuard, - type Driver, DriverCrashError, - RuntimeMissingError, - UnsupportedRequestOptionError, type DeviceMode, type VirtualSpec, - type Platform, specMode, - type BaselineService, - type CatalogReader, - ManagedDeviceLifecycle, - type Registry, - SerializedDecision, } from "../core/index.js"; -import { - createCapacityStrategy, - loadTestRegistry, - openTestState, - readyTransitionUpdate, -} from "../core/testing.js"; import { FakeDriver } from "../core/testing.js"; -import { QuarantineCoordinator } from "../core/testing.js"; +import { NoCapacityError } from "./lease-acquisition-coordinator.js"; +import { IdempotencyConflictError, LeaseRequestForbiddenError } from "./lease-request-book.js"; +import { RequesterAlreadyLeasedError } from "./wait-queue.js"; import { - LeaseAcquisitionCoordinator, - type LeaseAcquisitionCoordinatorOptions, - NoCapacityError, -} from "./lease-acquisition-coordinator.js"; -import { LeaseExpiryScheduler } from "./lease-expiry-scheduler.js"; -import { - IdempotencyConflictError, - LeaseRequestBook, - LeaseRequestForbiddenError, -} from "./lease-request-book.js"; -import { LeaseLifecycle } from "./lease-lifecycle.js"; -import { type LeaseRequestOptions, RequesterAlreadyLeasedError, WaitQueue } from "./wait-queue.js"; - -const gibibyte = 1024 ** 3; -const request = { - physical: false, - model: "iPhone 16", - osVersion: "26.5", - platform: "ios", -} as const; - -function config(maxDevices = 1, maxRunning = 1): Pick { - return { - capacity: { - strategy: "resource", - config: { - limits: { - android: { maxDevices, maxRunning }, - ios: { maxDevices, maxRunning }, - maxRunning, - }, - ramBudget: { androidBytesPerDevice: 4 * gibibyte, iosBytesPerDevice: gibibyte }, - }, - }, - warmPool: { - enabled: true, - maxConcurrentBoots: 1, - reserveRunning: { android: 0, ios: 0 }, - targets: [], - quarantine: { - maxRetries: 3, - maxRetryBackoffMs: 300_000, - retryBackoffMs: 30_000, - retryBackoffMultiplier: 2, - }, - }, - }; -} - -// fallow-ignore-next-line complexity -- one test harness builder; each option is a plain pass-through to a collaborator. -async function createHarness( - options: { - /** why: stands in for the baselines a request names, when a test scripts the versions. */ - readonly baselines?: Pick; - /** Stands in for the installer, when a test needs to see whether it was reached at all. */ - readonly components?: Pick; - readonly defaultModes?: Readonly>>; - readonly drivers?: readonly Driver[]; - /** Free disk the installer sees; unlimited unless a test says otherwise. */ - readonly freeDiskBytes?: number; - /** Stands between the coordinator and the real lifecycle, when a test interleaves other work. */ - readonly lifecycle?: ( - lifecycle: ManagedDeviceLifecycle, - collaborators: { - readonly capacity: CapacityCoordinator; - readonly claims: DeviceOperationClaims; - readonly registry: Registry; - }, - ) => LeaseAcquisitionCoordinatorOptions["lifecycle"]; - readonly logger?: Logger; - readonly maxDevices?: number; - readonly maxRunning?: number; - readonly quarantine?: LeaseAcquisitionCoordinatorOptions["quarantine"]; - /** The class preference lists the daemon would build from config and the drivers. */ - readonly preferences?: ModelPreferences; - /** Stands in for the catalog reader a class request reads, when a test scripts it. */ - readonly catalogReader?: Pick; - } = {}, -) { - const clock = new FakeClock(1_000); - const bus = new EventBus(clock); - const driver = - (options.drivers?.[0] as FakeDriver | undefined) ?? - new FakeDriver({ clock, platform: "ios", availableOsVersions: ["26.5"] }); - const drivers = options.drivers ?? [driver]; - let nextId = 0; - const state = await openTestState(); - const registry = await loadTestRegistry({ - clock, - eventBus: bus, - idGenerator: { generate: () => `${nextId++}` }, - state, - }); - const decisions = new SerializedDecision(); - const claims = new DeviceOperationClaims(); - const catalog = new DriverCatalog(drivers, { preferences: options.preferences ?? {} }); - const appConfig = config(options.maxDevices, options.maxRunning); - const capacity = new CapacityCoordinator( - createCapacityStrategy( - appConfig.capacity, - new FakeSystemStats({ - cpuCount: 8, - totalRamBytes: 32 * gibibyte, - }), - ), - ); - const lifecycle = new ManagedDeviceLifecycle(catalog, registry, decisions, claims, clock); - // why: quarantine's kick wakes this coordinator's queue, and `coordinator` is only assigned below. - const quarantine = - options.quarantine ?? - new QuarantineCoordinator({ - claims, - clock, - config: appConfig.warmPool.quarantine, - decisions, - drivers: catalog, - eventBus: bus, - notifyAvailability: () => coordinator?.kick(), - registry, - }); - const provisioner = new DeviceProvisioner({ - baselines: () => ({ current: () => undefined, hold: () => () => undefined }), - catalog, - claims, - clock, - // Never refuses: what a removal does to provisioning is `DeviceProvisioner`'s own test. - components: { claimProvision: () => () => undefined }, - decisions, - lifecycle, - registry, - }); - const expiry = new LeaseExpiryScheduler(clock, async () => undefined); - const leases = new LeaseLifecycle({ - clock, - eventBus: bus, - expiryScheduler: expiry, - registry, - ttl: { defaultMs: 100 }, - }); - let coordinator: LeaseAcquisitionCoordinator | undefined; - /** Every id minted for a request, in order. */ - const requestIds: string[] = []; - const idGenerator = { - generate: () => { - const id = `request-${nextId++}`; - requestIds.push(id); - return id; - }, - }; - const queue = new WaitQueue({ - clock, - idGenerator, - onTimeout: (waiter) => { - bus.emit( - "lease.rejected", - { - requestId: waiter.id, - requester: waiter.options.requesterId, - requestSpec: waiter.request, - reason: "timeout", - }, - "wait-queue", - ); - coordinator?.kick(); - }, - }); - const components = - options.components ?? - new ComponentInstaller({ - clock, - decisions, - diskSpace: new DiskSpaceGuard(), - drivers: catalog, - eventBus: bus, - filesystem: new MemoryFilesystem(options.freeDiskBytes), - registry, - timeoutMs: 1_200_000, - }); - coordinator = new LeaseAcquisitionCoordinator({ - baselines: options.baselines ?? { current: () => undefined }, - catalog: options.catalogReader ?? catalog, - claims, - components, - decisions, - defaultModes: options.defaultModes ?? {}, - drivers: catalog, - eventBus: bus, - idGenerator, - leases, - lifecycle: options.lifecycle?.(lifecycle, { capacity, claims, registry }) ?? lifecycle, - ...(options.logger === undefined ? {} : { logger: options.logger }), - modelPreferences: options.preferences ?? {}, - planner: new AcquisitionPlanner(capacity, claims), - provisioner, - queue, - quarantine, - registry, - requests: new LeaseRequestBook({ - decisions, - // The daemon's classifier, cut down to the codes these tests read back. - describeFailure: (error) => ({ - code: error instanceof NoCapacityError ? "NO_CAPACITY" : "INTERNAL", - message: error instanceof Error ? error.message : String(error), - }), - store: registry, - }), - }); - return { - bus, - capacity, - claims, - clock, - components, - coordinator, - driver, - provisioner, - queue, - registry, - requestIds, - state, - }; -} + request, + createHarness, + seedReady, + flush, + settle, + seedShutdown, +} from "./test-lease-acquisition.js"; interface StoredByCommit { readonly leaseRequesters: readonly string[]; @@ -300,408 +55,12 @@ function inspectCommits( ); } -async function seedReady( - harness: Awaited>, - spec: VirtualSpec = request, -) { - const driverDevice = await harness.driver.provision(spec); - const provisioned = await harness.registry.registerDevice({ - driverData: driverDevice.driverData, - driverDeviceId: driverDevice.deviceId, - provisionDuration: 0, - spec, - }); - const ready = await harness.driver.makeReady(driverDevice, { - mode: specMode(spec), - purpose: "prepare", - }); - return harness.registry.transitionDevice( - provisioned.id, - "ready", - { event: "device.ready", payload: { bootDuration: 0, deviceId: provisioned.id } }, - readyTransitionUpdate(ready), - ); -} - -async function flush(): Promise { - for (let count = 0; count < 50; count += 1) await Promise.resolve(); -} - -/** Lets fire-and-forget device work that crosses several registry writes run to rest. */ -async function settle(): Promise { - for (let count = 0; count < 20; count += 1) await new Promise((resolve) => setImmediate(resolve)); -} - function capturingLogger(): { readonly logger: Logger; readonly sink: MemoryLogSink } { const sink = new MemoryLogSink(); return { logger: new JsonLinesLogger({ clock: new FakeClock(1_000), sink }), sink }; } -async function seedShutdown( - harness: Awaited>, - spec: VirtualSpec = request, -) { - const ready = await seedReady(harness, spec); - await harness.driver.shutdown({ - address: ready.address ?? "", - deviceId: ready.driverDeviceId, - driverData: ready.driverData, - }); - return harness.registry.transitionDevice(ready.id, "shutdown", { - event: "device.shutdown", - payload: { deviceId: ready.id, initiator: "test" }, - }); -} - -function installs(driver: FakeDriver): readonly unknown[] { - return driver.calls - .filter((call) => call.operation === "installComponent") - .map((call) => call.arguments[0]); -} - -describe("LeaseAcquisitionCoordinator: missing runtimes", () => { - it("installs once for two lease requests for the same missing runtime, and grants both", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); - driver.holdInstalls(); - const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); - - const first = harness.coordinator.request(request, { - allowDownload: true, - ownerId: "a", - requesterId: "a", - }); - const second = harness.coordinator.request(request, { - allowDownload: true, - ownerId: "b", - requesterId: "b", - }); - await flush(); - driver.releaseInstalls(); - - const grants = await Promise.all([first, second]); - expect(grants.map((grant) => grant.device.spec.osVersion)).toEqual(["26.5", "26.5"]); - expect(installs(driver)).toEqual(["26.5"]); - }); - - it("starts the install for a second missing runtime on the same platform only after the first one has ended", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); - driver.holdInstalls(); - const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); - - const first = harness.coordinator.request(request, { - allowDownload: true, - ownerId: "a", - requesterId: "a", - }); - const second = harness.coordinator.request( - { ...request, osVersion: "27.0" }, - { allowDownload: true, ownerId: "b", requesterId: "b" }, - ); - await flush(); - expect(installs(driver)).toEqual(["26.5"]); - - driver.releaseInstalls(); - await first; - await settle(); - expect(installs(driver)).toEqual(["26.5", "27.0"]); - await expect(second).resolves.toMatchObject({ device: { spec: { osVersion: "27.0" } } }); - }); - - it("attributes the install a lease request starts to that request's requester", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); - const harness = await createHarness({ drivers: [driver] }); - const started: unknown[] = []; - harness.bus.subscribe("component.install-started", (envelope) => { - started.push(envelope.payload); - }); - - await harness.coordinator.request(request, { - allowDownload: true, - ownerId: "owner", - requesterId: "agent-7", - }); - - expect(started).toEqual([{ componentId: "26.5", platform: "ios", requesterId: "agent-7" }]); - }); - - it("starts no install when resolving again fails some other way by the time the request reaches the front, and fails with that error", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); - const broken = new DriverCrashError("simctl list failed"); - // The first resolve finds the runtime missing; the check at the front of the queue breaks. - driver.failOn("resolveSpec", 2, broken); - driver.failOn("resolveSpec", 3, broken); - const harness = await createHarness({ drivers: [driver] }); - - await expect( - harness.coordinator.request(request, { allowDownload: true, ownerId: "a", requesterId: "a" }), - ).rejects.toBe(broken); - expect(installs(driver)).toEqual([]); - }); - - it("fails a request without allowDownload for a missing runtime with RuntimeMissingError, and never calls the installer", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); - const asked: unknown[] = []; - const harness = await createHarness({ - components: { - install: async (call) => { - asked.push(call); - return { outcome: "installed", version: "26.5" }; - }, - }, - drivers: [driver], - }); - - await expect( - harness.coordinator.request(request, { ownerId: "a", requesterId: "a" }), - ).rejects.toMatchObject({ component: "26.5", name: "RuntimeMissingError" }); - expect(asked).toEqual([]); - }); - - it("fails the request with InsufficientDiskSpaceError when the install does not fit, and never calls installComponent", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ - availableOsVersions: [], - clock, - componentFootprint: { bytes: 8 * gibibyte, path: "/" }, - platform: "ios", - }); - const harness = await createHarness({ drivers: [driver], freeDiskBytes: gibibyte }); - - await expect( - harness.coordinator.request(request, { allowDownload: true, ownerId: "a", requesterId: "a" }), - ).rejects.toMatchObject({ name: "InsufficientDiskSpaceError" }); - expect(installs(driver)).toEqual([]); - }); -}); - -describe("LeaseAcquisitionCoordinator: download progress", () => { - type Progress = Parameters>[0]; - - function downloading(progress: readonly Progress[]): readonly Progress[] { - return progress.filter((report) => report.stage === "downloading"); - } - - it("tells a request that starts a download downloading, naming the component and not waiting, before provisioning", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); - const harness = await createHarness({ drivers: [driver] }); - const progress: Progress[] = []; - - await harness.coordinator.request(request, { - allowDownload: true, - onProgress: (report) => progress.push(report), - ownerId: "a", - requesterId: "a", - }); - - expect(progress[0]).toEqual({ component: "26.5", stage: "downloading", waiting: false }); - const provisioning = progress.findIndex((report) => report.stage === "provisioning"); - expect(provisioning).toBeGreaterThan(0); - expect(progress.slice(provisioning).some((report) => report.stage === "downloading")).toBe( - false, - ); - }); - - it("tells a request behind another download on its platform that it is waiting, then not waiting when its own install starts", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); - driver.holdInstalls(); - const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); - const progress: Progress[] = []; - - const first = harness.coordinator.request(request, { - allowDownload: true, - ownerId: "a", - requesterId: "a", - }); - const second = harness.coordinator.request( - { ...request, osVersion: "27.0" }, - { - allowDownload: true, - onProgress: (report) => progress.push(report), - ownerId: "b", - requesterId: "b", - }, - ); - await flush(); - expect(progress).toEqual([{ component: "27.0", stage: "downloading", waiting: true }]); - - driver.releaseInstalls(); - await first; - await settle(); - expect(installs(driver)).toEqual(["26.5", "27.0"]); - expect(downloading(progress)).toEqual([ - { component: "27.0", stage: "downloading", waiting: true }, - { component: "27.0", stage: "downloading", waiting: false }, - { component: "27.0", percent: 100, stage: "downloading", waiting: false }, - ]); - await expect(second).resolves.toMatchObject({ device: { spec: { osVersion: "27.0" } } }); - }); - - it("tells a request that joins a download already running its latest percentage at once", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ - availableOsVersions: [], - clock, - installProgress: [12, 41], - platform: "ios", - }); - driver.holdInstalls(); - const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); - const joined: Progress[] = []; - - const first = harness.coordinator.request(request, { - allowDownload: true, - ownerId: "a", - requesterId: "a", - }); - await flush(); - expect(installs(driver)).toEqual(["26.5"]); - const second = harness.coordinator.request(request, { - allowDownload: true, - onProgress: (report) => joined.push(report), - ownerId: "b", - requesterId: "b", - }); - await flush(); - - // The driver is still holding: this is the replay, not a later report. - expect(joined).toEqual([ - { component: "26.5", percent: 41, stage: "downloading", waiting: false }, - ]); - driver.releaseInstalls(); - await Promise.all([first, second]); - expect(installs(driver)).toEqual(["26.5"]); - }); - - it.each([ - { - name: "a percentage the driver reports twice is sent once", - installProgress: [30, 30, 60], - percents: [undefined, 30, 60, 100], - }, - { - name: "41.7 is sent as 41, and one that rounds down to the last sent is not sent", - installProgress: [41.7, 41.9], - percents: [undefined, 41, 100], - }, - { - name: "a percentage outside 0 to 100 is sent as the nearest bound, and one that is not a number as no percent", - installProgress: [10, Number.NaN, -5, 150], - percents: [undefined, 10, undefined, 0, 100], - }, - ])( - "maps the installer's progress to the percentages the requester sees: $name", - async ({ installProgress, percents }) => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ - availableOsVersions: [], - clock, - installProgress, - platform: "ios", - }); - const harness = await createHarness({ drivers: [driver] }); - const progress: Progress[] = []; - - await harness.coordinator.request(request, { - allowDownload: true, - onProgress: (report) => progress.push(report), - ownerId: "a", - requesterId: "a", - }); - - expect(downloading(progress)).toEqual( - percents.map((percent) => ({ - component: "26.5", - ...(percent === undefined ? {} : { percent }), - stage: "downloading", - waiting: false, - })), - ); - const complete = progress.findIndex( - (report) => report.stage === "downloading" && report.percent === 100, - ); - const provisioning = progress.findIndex((report) => report.stage === "provisioning"); - expect(provisioning).toBeGreaterThan(complete); - expect(progress.slice(provisioning).some((report) => report.stage === "downloading")).toBe( - false, - ); - }, - ); - - it("sends no downloading stage to a request whose runtime is installed", async () => { - const harness = await createHarness(); - const progress: Progress[] = []; - - await harness.coordinator.request(request, { - allowDownload: true, - onProgress: (report) => progress.push(report), - ownerId: "a", - requesterId: "a", - }); - - expect(progress.map((report) => report.stage)).toContain("provisioning"); - expect(downloading(progress)).toEqual([]); - }); - - it("sends no downloading stage to a request without allowDownload for a missing runtime", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); - const harness = await createHarness({ drivers: [driver] }); - const progress: Progress[] = []; - - await expect( - harness.coordinator.request(request, { - onProgress: (report) => progress.push(report), - ownerId: "a", - requesterId: "a", - }), - ).rejects.toMatchObject({ name: "RuntimeMissingError" }); - expect(progress).toEqual([]); - }); - - it("tells a request that waited and then needed no install that it was waiting, then provisioning, and never not waiting", async () => { - const clock = new FakeClock(1_000); - const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); - driver.holdInstalls(); - const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); - const progress: Progress[] = []; - - const byVersion = harness.coordinator.request(request, { - allowDownload: true, - ownerId: "a", - requesterId: "a", - }); - // No version: the fake names its word for newest, a different component that waits its turn - // and finds, at the front, that the first install made its runtime available. - const newest = harness.coordinator.request( - { model: "iPhone 16", platform: "ios" }, - { - allowDownload: true, - onProgress: (report) => progress.push(report), - ownerId: "b", - requesterId: "b", - }, - ); - await flush(); - driver.releaseInstalls(); - await expect(byVersion).resolves.toMatchObject({ device: { spec: { osVersion: "26.5" } } }); - await expect(newest).resolves.toMatchObject({ device: { spec: { osVersion: "26.5" } } }); - - expect(installs(driver)).toEqual(["26.5"]); - expect(progress[0]).toMatchObject({ stage: "downloading", waiting: true }); - expect( - downloading(progress).every((report) => report.stage === "downloading" && report.waiting), - ).toBe(true); - expect(progress[1]).toMatchObject({ stage: "provisioning" }); - }); -}); - +// why: drives the coordinator on its own, so a test can interleave its lifecycle, queue and clock in orders the leasing surface cannot force. describe("LeaseAcquisitionCoordinator", () => { it("rejects a second request from a requester whose first is still pending, under no key or a new idempotency key, with lease.rejected already-leased", async () => { // why: the one-lease-or-pending-request-per-requester rule is enforced here, inside the admission @@ -2140,990 +1499,72 @@ describe("LeaseAcquisitionCoordinator stored requests", () => { }); }); -describe("LeaseAcquisitionCoordinator: image tags", () => { - const android = { - physical: false, - model: "Pixel 8", - osVersion: "34", - platform: "android", - } as const; - const playstore = { ...android, imageTag: "google_apis_playstore" } as const; +describe("LeaseAcquisitionCoordinator: what lease.granted reports", () => { const owner = (id: string) => ({ ownerId: id, requesterId: id }); - /** API 34 has a google_apis and a google_apis_playstore image; API 35 only google_apis. */ - function taggedDriver(): FakeDriver { - return new FakeDriver({ - availableOsVersions: ["34", "35"], - clock: new FakeClock(1_000), - images: [ - { abi: "arm64-v8a", runtime: "34", tag: "google_apis" }, - { abi: "arm64-v8a", runtime: "34", tag: "google_apis_playstore" }, - { abi: "arm64-v8a", runtime: "35", tag: "google_apis" }, - ], - platform: "android", - }); + function granted(harness: Awaited>) { + const events: Array<{ requestId: string; source: string; leaseId: string }> = []; + harness.bus.subscribe("lease.granted", (envelope) => events.push(envelope.payload)); + const requested: string[] = []; + harness.bus.subscribe("lease.requested", (envelope) => + requested.push(envelope.payload.requestId), + ); + return { events, requested }; } - it("grants a request naming a tag a device whose spec carries that tag, and one naming none a spec without one", async () => { - const driver = taggedDriver(); - const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); - - const tagged = await harness.coordinator.request(playstore, owner("tagged")); - const untagged = await harness.coordinator.request(android, owner("untagged")); - - expect(tagged.device.spec).toEqual(playstore); - expect(untagged.device.spec).toEqual(android); - const provisioned = driver.calls - .filter((call) => call.operation === "provision") - .map((call) => call.arguments[0]); - expect(provisioned).toEqual([playstore, android]); - }); - it.each([ - ["without allowDownload", false], - ["with allowDownload", true], - ])( - "fails a tag not installed for the API level with a RuntimeMissingError %s, and never asks the installer", - async (_label, allowDownload) => { - const asked: unknown[] = []; - const harness = await createHarness({ - components: { - install: async (call) => { - asked.push(call); - return { outcome: "installed", version: "35" }; - }, - }, - drivers: [taggedDriver()], - }); - - await expect( - harness.coordinator.request( - { ...playstore, osVersion: "35" }, - { ...owner("agent"), allowDownload }, - ), - ).rejects.toMatchObject({ downloadable: false, name: "RuntimeMissingError" }); - expect(asked).toEqual([]); + { + name: "warm for a lease granted from a ready device", + source: "warm", + seed: async (harness) => { + await seedReady(harness); + }, + }, + { + name: "booted for a lease granted after booting a shut-down device", + source: "booted", + seed: async (harness) => { + await seedShutdown(harness); + }, + }, + { + name: "provisioned for a lease granted on a device provisioned for it", + source: "provisioned", + seed: async () => undefined, + }, + { + name: "provisioned when an eviction deleted a device and a new one was created", + source: "provisioned", + seed: async (harness) => { + await seedReady(harness, { ...request, model: "iPhone SE" }); + }, }, - ); - - it.each([ { - name: "of another tag", - seeded: { ...android, imageTag: "google_apis" }, - requested: playstore, + // why: with one running slot taken by a ready device of another model, the shut-down device + // of the requested model can boot only after an eviction gives the slot back. + name: "booted when an eviction shut a device down and a shut-down device was then booted", + source: "booted", + limits: { maxDevices: 2, maxRunning: 1 }, + seed: async (harness) => { + await seedShutdown(harness); + return seedReady(harness, { ...request, model: "iPhone SE" }); + }, + evictedLeavesReady: true, }, - { name: "with no tag", seeded: android, requested: playstore }, - { name: "with a tag when it names none", seeded: playstore, requested: android }, - ] as const)("does not give a request an idle device $name", async ({ seeded, requested }) => { - const harness = await createHarness({ drivers: [taggedDriver()], maxDevices: 2 }); - const idle = await seedReady(harness, seeded); + ] satisfies ReadonlyArray<{ + name: string; + source: "warm" | "booted" | "provisioned"; + limits?: { maxDevices: number; maxRunning: number }; + seed: (harness: Awaited>) => Promise<{ id: string } | void>; + evictedLeavesReady?: boolean; + }>)( + "emits lease.granted with exactly the grant's device, lease, requester, request and platform, and source $name", + async ({ source, limits, seed, evictedLeavesReady }) => { + const harness = await createHarness(limits); + const evicted = await seed(harness); + const { events, requested } = granted(harness); - const granted = await harness.coordinator.request(requested, owner("agent")); - - expect(granted.device.id).not.toBe(idle.id); - expect(granted.device.spec).toEqual(requested); - }); - - it("gives a request naming a tag an idle device of that tag", async () => { - const harness = await createHarness({ drivers: [taggedDriver()], maxDevices: 2 }); - const tagged = await seedReady(harness, playstore); - - const granted = await harness.coordinator.request(playstore, owner("agent")); - - expect(granted.device.id).toBe(tagged.id); - }); - - it("rejects a request whose driver refuses the image tag as unresolvable-spec, with the driver's error", async () => { - class NoTagsDriver extends FakeDriver { - override async resolveSpec( - ...args: Parameters - ): Promise { - if (args[0].imageTag !== undefined) { - throw new UnsupportedRequestOptionError(this.platform, "imageTag"); - } - return super.resolveSpec(...args); - } - } - const driver = new NoTagsDriver({ - availableOsVersions: ["26.5"], - clock: new FakeClock(1_000), - platform: "ios", - }); - const harness = await createHarness({ drivers: [driver] }); - - await expect( - harness.coordinator.request({ ...request, imageTag: "google_apis" }, owner("agent")), - ).rejects.toBeInstanceOf(UnsupportedRequestOptionError); - expect( - harness.bus - .replay() - .filter((event) => event.event === "lease.rejected") - .map((event) => event.payload), - ).toEqual([ - { - reason: "unresolvable-spec", - requestId: expect.stringMatching(/^req_/), - requester: "agent", - requestSpec: { ...request, imageTag: "google_apis" }, - }, - ]); - expect(driver.calls.map((call) => call.operation)).not.toContain("provision"); - }); - - it.each([ - ["another tag than the one the request named", playstore, { imageTag: "default" }], - ["a tag for a request that named none", android, { imageTag: "google_apis" }], - ] as const)( - "refuses a spec the driver resolves with %s, and provisions nothing", - async (_label, asked, returned) => { - class WrongTagDriver extends FakeDriver { - override async resolveSpec( - ...args: Parameters - ): Promise { - return { ...(await super.resolveSpec(...args)), ...returned }; - } - } - const driver = new WrongTagDriver({ - availableOsVersions: ["34"], - clock: new FakeClock(1_000), - images: [{ abi: "arm64-v8a", runtime: "34", tag: "google_apis_playstore" }], - platform: "android", - }); - const harness = await createHarness({ drivers: [driver] }); - - await expect(harness.coordinator.request(asked, owner("agent"))).rejects.toThrow( - /driver resolved image tag .* for a request naming/, - ); - expect(driver.calls.map((call) => call.operation)).not.toContain("provision"); - }, - ); -}); - -describe("LeaseAcquisitionCoordinator: class requests", () => { - const owner = (id: string) => ({ ownerId: id, requesterId: id }); - const iosModels = ["iPhone 15", "iPhone 16", "iPhone 17", "Apple Watch", "iPad Pro"]; - const iosClasses = { - "Apple Watch": "watch", - "iPad Pro": "tablet", - "iPhone 15": "phone", - "iPhone 16": "phone", - "iPhone 17": "phone", - } as const; - const iosPreferences: ModelPreferences = { - ios: { - phone: ["iPhone 17", "iPhone 16", "iPhone 15"], - tablet: ["iPad Pro"], - watch: ["Apple Watch"], - }, - }; - const phone = { class: "phone", platform: "ios" } as const; - const iphone15 = { - physical: false, - model: "iPhone 15", - osVersion: "18.4", - platform: "ios", - } as const; - - function iosDriver(options: Partial[0]> = {}) { - return new FakeDriver({ - availableOsVersions: ["18.4", "26.5"], - clock: new FakeClock(1_000), - knownModels: iosModels, - modelClasses: iosClasses, - platform: "ios", - ...options, - }); - } - - function deviceWork(driver: FakeDriver): number { - return driver.calls.filter((call) => ["provision", "makeReady"].includes(call.operation)) - .length; - } - - function provisioned(harness: Awaited>) { - return harness.bus - .replay() - .filter((event) => event.event === "device.provisioned") - .map((event) => (event.payload as { spec: VirtualSpec }).spec); - } - - async function classHarness(driver = iosDriver(), preferences = iosPreferences) { - return createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2, preferences }); - } - - it("resolves a request with neither model nor class as the phone class, and lease.requested carries neither", async () => { - const harness = await classHarness(); - - const granted = await harness.coordinator.request({ platform: "ios" }, owner("agent")); - - expect(granted.device.spec).toMatchObject({ model: "iPhone 17", osVersion: "26.5" }); - const requested = harness.bus.replay().filter((event) => event.event === "lease.requested"); - expect( - requested.map((event) => (event.payload as { requestSpec: unknown }).requestSpec), - ).toEqual([{ platform: "ios" }]); - }); - - it("grants a phone request one ready idle iPhone 15 with no boot and no provision", async () => { - const driver = iosDriver(); - const harness = await classHarness(driver); - const warm = await seedReady(harness, iphone15); - const before = deviceWork(driver); - - const granted = await harness.coordinator.request(phone, owner("agent")); - - expect(granted.device.id).toBe(warm.id); - expect(deviceWork(driver)).toBe(before); - }); - - it("does not grant an exact iPhone 16 request a ready idle iPhone 15", async () => { - const harness = await classHarness(); - const warm = await seedReady(harness, { ...iphone15, osVersion: "26.5" }); - - const granted = await harness.coordinator.request( - { model: "iPhone 16", platform: "ios" }, - owner("agent"), - ); - - expect(granted.device.id).not.toBe(warm.id); - expect(granted.device.spec.model).toBe("iPhone 16"); - }); - - it("does not grant a request with no class a ready idle Apple Watch, and grants a watch request it", async () => { - const watch = { - physical: false, - model: "Apple Watch", - osVersion: "26.5", - platform: "ios", - } as const; - const first = await classHarness(); - const warm = await seedReady(first, watch); - - const noClass = await first.coordinator.request({ platform: "ios" }, owner("agent")); - expect(noClass.device.id).not.toBe(warm.id); - - const second = await classHarness(); - const warmWatch = await seedReady(second, watch); - const granted = await second.coordinator.request( - { class: "watch", platform: "ios" }, - owner("agent"), - ); - expect(granted.device.id).toBe(warmWatch.id); - }); - - it("boots a shut-down device of the class before creating any device", async () => { - const driver = iosDriver(); - const harness = await classHarness(driver); - const cold = await seedShutdown(harness, iphone15); - const provisions = () => driver.calls.filter((call) => call.operation === "provision").length; - const before = provisions(); - - const granted = await harness.coordinator.request(phone, owner("agent")); - - expect(granted.device.id).toBe(cold.id); - expect(provisions()).toBe(before); - }); - - describe("device mode", () => { - const slimming = () => - iosDriver({ availableOsVersions: ["26.5"], slimmableOsVersions: ["26.5"] }); - const full15 = { ...iphone15, osVersion: "26.5" } as const; - const slim15 = { ...full15, mode: "slim" } as const; - - it("never grants a full request a slim device of the class", async () => { - const harness = await classHarness(slimming()); - const slim = await seedReady(harness, slim15); - - const granted = await harness.coordinator.request({ ...phone, mode: "full" }, owner("agent")); - - expect(granted.device.id).not.toBe(slim.id); - expect(granted.device.mode).toBe("full"); - }); - - it.each([ - { defaultMode: "full", seeded: slim15, name: "a slim device when the default mode is full" }, - { defaultMode: "slim", seeded: full15, name: "a full device when the default mode is slim" }, - ] as const)("does not grant a request with no mode $name", async ({ defaultMode, seeded }) => { - const harness = await createHarness({ - defaultModes: { ios: defaultMode }, - drivers: [slimming()], - maxDevices: 2, - preferences: iosPreferences, - }); - const idle = await seedReady(harness, seeded); - - const granted = await harness.coordinator.request(phone, owner("agent")); - - expect(granted.device.id).not.toBe(idle.id); - expect(granted.device.mode).toBe(defaultMode); - }); - }); - - describe("image tags", () => { - const pixel = { - physical: false, - model: "Pixel 8", - osVersion: "34", - platform: "android", - } as const; - const androidPhone = { class: "phone", platform: "android" } as const; - const androidPreferences: ModelPreferences = { android: { phone: ["Pixel 9", "Pixel 8"] } }; - const androidDriver = () => - new FakeDriver({ - availableOsVersions: ["34", "35"], - clock: new FakeClock(1_000), - images: [ - { abi: "arm64-v8a", runtime: "34", tag: "google_apis" }, - { abi: "arm64-v8a", runtime: "34", tag: "google_apis_playstore" }, - { abi: "arm64-v8a", runtime: "35", tag: "google_apis" }, - ], - knownModels: ["Pixel 8", "Pixel 9"], - modelClasses: { "Pixel 8": "phone", "Pixel 9": "phone" }, - modelRuntimes: { "Pixel 8": ["34"], "Pixel 9": ["35"] }, - platform: "android", - }); - - it.each([ - ["of another tag", { imageTag: "google_apis" }, "google_apis_playstore"], - ["with no tag", {}, "google_apis_playstore"], - ] as const)( - "does not grant a request naming a tag an idle device %s", - async (_label, seeded, asked) => { - const harness = await classHarness(androidDriver(), androidPreferences); - const other = await seedReady(harness, { ...pixel, ...seeded }); - - const granted = await harness.coordinator.request( - { ...androidPhone, imageTag: asked }, - owner("agent"), - ); - - expect(granted.device.id).not.toBe(other.id); - expect(granted.device.spec.imageTag).toBe(asked); - }, - ); - - it("does not grant a request naming no tag an idle device with a tag", async () => { - const harness = await classHarness(androidDriver(), androidPreferences); - const tagged = await seedReady(harness, { ...pixel, imageTag: "google_apis_playstore" }); - - const granted = await harness.coordinator.request(androidPhone, owner("agent")); - - expect(granted.device.id).not.toBe(tagged.id); - expect(granted.device.spec).not.toHaveProperty("imageTag"); - }); - - it("grants a request naming a tag an idle device of that tag", async () => { - const harness = await classHarness(androidDriver(), androidPreferences); - const tagged = await seedReady(harness, { ...pixel, imageTag: "google_apis_playstore" }); - - const granted = await harness.coordinator.request( - { ...androidPhone, imageTag: "google_apis_playstore" }, - owner("agent"), - ); - - expect(granted.device.id).toBe(tagged.id); - }); - - it("skips a candidate whose only pairings carry another tag", async () => { - const harness = await classHarness(androidDriver(), androidPreferences); - - const granted = await harness.coordinator.request( - { ...androidPhone, imageTag: "google_apis_playstore" }, - owner("agent"), - ); - - expect(granted.device.spec).toMatchObject({ model: "Pixel 8", osVersion: "34" }); - }); - }); - - describe("OS", () => { - it("fits a class request with no OS to a device on a listed runtime, and not one on a runtime no longer listed", async () => { - const listed = await classHarness(); - const old = await seedReady(listed, iphone15); - const grantedListed = await listed.coordinator.request(phone, owner("agent")); - expect(grantedListed.device.id).toBe(old.id); - - const gone = await classHarness(); - const stale = await seedReady(gone, { ...iphone15, osVersion: "17.0" }); - const grantedGone = await gone.coordinator.request(phone, owner("agent")); - expect(grantedGone.device.id).not.toBe(stale.id); - expect(grantedGone.device.spec.osVersion).toBe("26.5"); - }); - - it("fits an exact request with no OS only to the runtime the driver picks, as on main", async () => { - const harness = await classHarness(); - const old = await seedReady(harness, iphone15); - - const granted = await harness.coordinator.request( - { model: "iPhone 15", platform: "ios" }, - owner("agent"), - ); - - expect(granted.device.id).not.toBe(old.id); - expect(granted.device.spec.osVersion).toBe("26.5"); - }); - }); - - describe("OS ranges", () => { - const rangeDriver = (options: Partial[0]> = {}) => - iosDriver({ - availableOsVersions: ["18.0", "18.4", "26.5"], - modelRuntimes: { - "iPhone 15": ["18.0", "18.4", "26.5"], - "iPhone 16": ["18.0", "18.4", "26.5"], - "iPhone 17": ["26.5"], - }, - ...options, - }); - - it("sends a class request with no osVersion to the driver without pinning a runtime", async () => { - const driver = rangeDriver(); - const harness = await classHarness(driver); - - await harness.coordinator.request({ platform: "ios" }, owner("agent")); - - const resolve = driver.calls.find((call) => call.operation === "resolveSpec"); - expect(resolve?.arguments[0]).toEqual({ mode: "full", model: "iPhone 17", platform: "ios" }); - }); - - it("grants a ready idle device whose OS satisfies the range, and not one outside it", async () => { - const inside = await classHarness(rangeDriver()); - const warm = await seedReady(inside, { ...iphone15, osVersion: "18.0" }); - const grantedInside = await inside.coordinator.request( - { ...phone, osVersion: ">=18 <26" }, - owner("agent"), - ); - expect(grantedInside.device.id).toBe(warm.id); - - const outside = await classHarness(rangeDriver()); - const stale = await seedReady(outside, { ...iphone15, osVersion: "26.5" }); - const grantedOutside = await outside.coordinator.request( - { ...phone, osVersion: ">=18 <26" }, - owner("agent"), - ); - expect(grantedOutside.device.id).not.toBe(stale.id); - expect(grantedOutside.device.spec.osVersion).toBe("18.4"); - }); - - it("fails an exact model the catalog does not list, sent with a range, at once with UnknownModelError", async () => { - const driver = rangeDriver(); - const harness = await classHarness(driver); - - await expect( - harness.coordinator.request( - { model: "iPhone 99", osVersion: ">=18", platform: "ios" }, - owner("agent"), - ), - ).rejects.toMatchObject({ model: "iPhone 99", name: "UnknownModelError" }); - expect(deviceWork(driver)).toBe(0); - }); - - it("grants an exact model with a range a ready idle device of that model in range, and not one of another model", async () => { - const harness = await classHarness(rangeDriver()); - const other = await seedReady(harness, { ...iphone15, osVersion: "18.0" }); - const same = await seedReady(harness, { - physical: false, - model: "iPhone 16", - osVersion: "18.0", - platform: "ios", - }); - const before = deviceWork(harness.driver); - - const granted = await harness.coordinator.request( - { model: "iPhone 16", osVersion: ">=18 <26", platform: "ios" }, - owner("agent"), - ); - - expect(granted.device.id).toBe(same.id); - expect(granted.device.id).not.toBe(other.id); - expect(deviceWork(harness.driver)).toBe(before); - }); - - it("fails an exact model with a range at once with UnknownModelError when the platform lists no catalog", async () => { - const harness = await createHarness({ - catalogReader: { listCatalog: async () => [] }, - drivers: [rangeDriver()], - }); - - await expect( - harness.coordinator.request( - { model: "iPhone 16", osVersion: ">=18", platform: "ios" }, - owner("agent"), - ), - ).rejects.toMatchObject({ model: "iPhone 16", name: "UnknownModelError" }); - }); - - it("never installs for a range even when the driver then reports a downloadable runtime missing", async () => { - class Racing extends FakeDriver { - override async resolveSpec(): Promise { - throw new RuntimeMissingError("ios", "18.4", { component: "18.4" }); - } - } - const asked: unknown[] = []; - const harness = await createHarness({ - components: { - install: async (call) => { - asked.push(call); - return { outcome: "installed", version: "18.4" }; - }, - }, - drivers: [ - new Racing({ - availableOsVersions: ["18.4"], - clock: new FakeClock(1_000), - knownModels: ["iPhone 16"], - modelClasses: { "iPhone 16": "phone" }, - platform: "ios", - }), - ], - }); - - await expect( - harness.coordinator.request( - { model: "iPhone 16", osVersion: ">=18", platform: "ios" }, - { ...owner("agent"), allowDownload: true }, - ), - ).rejects.toMatchObject({ name: "RuntimeMissingError" }); - expect(asked).toEqual([]); - }); - - it("creates an exact model with a range on the newest listed pairing in range", async () => { - const harness = await classHarness(rangeDriver()); - - const granted = await harness.coordinator.request( - { model: "iPhone 16", osVersion: "<26", platform: "ios" }, - owner("agent"), - ); - - expect(granted.device.spec).toMatchObject({ model: "iPhone 16", osVersion: "18.4" }); - expect(provisioned(harness).map((spec) => spec.osVersion)).toEqual(["18.4"]); - }); - - it.each([ - ["without allowDownload", false], - ["with allowDownload", true], - ])( - "fails an exact model with a range nothing installed satisfies at once with RuntimeMissingError, not downloadable, naming the range, and never installs, %s", - async (_label, allowDownload) => { - const driver = rangeDriver(); - const harness = await classHarness(driver); - - await expect( - harness.coordinator.request( - { model: "iPhone 16", osVersion: "<=17", platform: "ios" }, - { ...owner("agent"), allowDownload }, - ), - ).rejects.toMatchObject({ - downloadable: false, - name: "RuntimeMissingError", - osVersion: "<=17", - }); - expect(installs(driver)).toEqual([]); - expect(deviceWork(driver)).toBe(0); - }, - ); - - it.each([["Baklava"], ["34-ext12"]])( - "reaches resolveSpec with the bare version %s exact, as without ranges, and a range never picks it", - async (name) => { - const driver = rangeDriver({ - availableOsVersions: ["18.4", name], - modelRuntimes: { "iPhone 16": ["18.4", name] }, - }); - const harness = await classHarness(driver); - - await harness.coordinator.request( - { model: "iPhone 16", osVersion: name, platform: "ios" }, - owner("agent"), - ); - const resolved = driver.calls.find((call) => call.operation === "resolveSpec"); - expect(resolved?.arguments[0]).toMatchObject({ osVersion: name }); - - const ranged = await classHarness(driver); - const granted = await ranged.coordinator.request( - { model: "iPhone 16", osVersion: ">=18", platform: "ios" }, - owner("agent"), - ); - expect(granted.device.spec.osVersion).toBe("18.4"); - }, - ); - - it("picks the newest in-range runtime whatever order the catalog lists them in", async () => { - const harness = await classHarness( - rangeDriver({ - availableOsVersions: ["18.4", "26.5", "9.3", "18.0"], - modelRuntimes: { "iPhone 16": ["18.4", "26.5", "9.3", "18.0"] }, - }), - ); - - const granted = await harness.coordinator.request( - { model: "iPhone 16", osVersion: "<26", platform: "ios" }, - owner("agent"), - ); - - expect(granted.device.spec.osVersion).toBe("18.4"); - }); - - it("takes the first class candidate that has an in-range pairing and its newest such runtime: <=18 creates an iPhone 16 on the newest 18.x", async () => { - const harness = await classHarness(rangeDriver()); - - const granted = await harness.coordinator.request( - { ...phone, osVersion: "<=18" }, - owner("agent"), - ); - - expect(granted.device.spec).toMatchObject({ model: "iPhone 16", osVersion: "18.4" }); - }); - - it.each([ - ["without allowDownload", false], - ["with allowDownload", true], - ])( - "fails a class with a range no candidate pairs with at once with RuntimeMissingError and never installs, %s", - async (_label, allowDownload) => { - const driver = rangeDriver(); - const harness = await classHarness(driver); - - await expect( - harness.coordinator.request( - { ...phone, osVersion: "<=17" }, - { ...owner("agent"), allowDownload }, - ), - ).rejects.toMatchObject({ - downloadable: false, - name: "RuntimeMissingError", - osVersion: "<=17", - }); - expect(installs(driver)).toEqual([]); - }, - ); - - it("does not pick a runtime in range whose only images carry another tag: API 35 default only and API 34 google_apis, >=33 with tag google_apis creates on 34", async () => { - const driver = new FakeDriver({ - availableOsVersions: ["34", "35"], - clock: new FakeClock(1_000), - images: [ - { abi: "arm64-v8a", runtime: "34", tag: "google_apis" }, - { abi: "arm64-v8a", runtime: "35", tag: "default" }, - ], - knownModels: ["Pixel 8"], - modelClasses: { "Pixel 8": "phone" }, - modelRuntimes: { "Pixel 8": ["34", "35"] }, - platform: "android", - }); - const harness = await classHarness(driver, { android: { phone: ["Pixel 8"] } }); - - const byModel = await harness.coordinator.request( - { - imageTag: "google_apis", - model: "Pixel 8", - osVersion: ">=33", - platform: "android", - }, - owner("agent"), - ); - expect(byModel.device.spec).toMatchObject({ imageTag: "google_apis", osVersion: "34" }); - }); - }); - - describe("creating a device for a class", () => { - it("creates the first name on the class's list the catalog lists, and device.provisioned carries that model", async () => { - const harness = await classHarness(); - - const granted = await harness.coordinator.request(phone, owner("agent")); - - expect(granted.device.spec.model).toBe("iPhone 17"); - expect(provisioned(harness).map((spec) => spec.model)).toEqual(["iPhone 17"]); - }); - - it.each([ - ["a name the catalog does not list", "Unlisted Phone", {}], - ["a name of another class", "iPad Pro", {}], - ["a name with no pairing", "Orphan", { modelRuntimes: { Orphan: [] } }], - ] as const)("skips %s for the next on the list", async (_label, skipped, driverOptions) => { - const driver = iosDriver({ - ...driverOptions, - knownModels: [...iosModels, "Orphan"], - modelClasses: { ...iosClasses, Orphan: "phone" }, - }); - const harness = await classHarness(driver, { - ios: { phone: [skipped, "iPhone 16"] }, - }); - - const granted = await harness.coordinator.request(phone, owner("agent")); - - expect(granted.device.spec.model).toBe("iPhone 16"); - }); - - it.each([ - ["without allowDownload", false], - ["with allowDownload", true], - ])( - "fails a class whose listed models pair with no installed runtime at once with RuntimeMissingError, not downloadable, %s", - async (_label, allowDownload) => { - const asked: unknown[] = []; - const driver = iosDriver({ modelRuntimes: { "iPhone 16": [] } }); - const harness = await createHarness({ - components: { - install: async (call) => { - asked.push(call); - return { outcome: "installed", version: "27.0" }; - }, - }, - drivers: [driver], - preferences: { ios: { phone: ["iPhone 16"] } }, - }); - - await expect( - harness.coordinator.request(phone, { ...owner("agent"), allowDownload }), - ).rejects.toMatchObject({ downloadable: false, name: "RuntimeMissingError" }); - expect(asked).toEqual([]); - expect(deviceWork(driver)).toBe(0); - }, - ); - - it.each([ - ["ios", "ios.defaultModels.phone", { ...phone }], - ["android", "android.defaultModels.tablet", { class: "tablet", platform: "android" }], - ] as const)( - "fails a class with no listed name at once with UnknownModelError naming the class and %s, whatever is idle", - async (platform, key, asked) => { - const driver = new FakeDriver({ - availableOsVersions: ["18.4"], - clock: new FakeClock(1_000), - knownModels: ["iPhone 15"], - modelClasses: { "iPhone 15": "phone" }, - platform, - }); - const harness = await classHarness(driver, { - [platform]: { phone: ["Unlisted Phone"], tablet: ["Unlisted Tablet"] }, - }); - await seedReady( - harness, - platform === "ios" - ? iphone15 - : { model: "Pixel 8", osVersion: "34", physical: false, platform: "android" }, - ); - - await expect(harness.coordinator.request(asked, owner("agent"))).rejects.toMatchObject({ - class: asked.class, - message: expect.stringContaining(key), - name: "UnknownModelError", - platform, - }); - }, - ); - - it("fails a class request at once with UnknownModelError when the platform has no preference list at all", async () => { - const harness = await classHarness(iosDriver(), {}); - - await expect(harness.coordinator.request(phone, owner("agent"))).rejects.toMatchObject({ - class: "phone", - name: "UnknownModelError", - message: expect.stringContaining("ios.defaultModels.phone"), - }); - }); - - it("lists a queued class request's class requirement and the catalog's class lookup", async () => { - const harness = await createHarness({ - drivers: [iosDriver()], - maxDevices: 1, - maxRunning: 1, - preferences: iosPreferences, - }); - await harness.coordinator.request(phone, owner("holder")); - void harness.coordinator.request(phone, owner("waiter")).catch(() => undefined); - await settle(); - - const [demand] = harness.coordinator.waitingDemand(); - - expect(demand).toMatchObject({ - inFlight: false, - mode: "full", - platform: "ios", - requirement: { platform: "ios", target: { class: "phone", kind: "class" } }, - }); - expect(demand?.classOf("iPhone 15")).toBe("phone"); - }); - - it("lists no waiting demand for a request whose class is still being resolved", async () => { - let open: () => void = () => undefined; - const gate = new Promise((resolve) => { - open = resolve; - }); - const harness = await createHarness({ - catalogReader: { - listCatalog: async () => { - await gate; - return []; - }, - }, - drivers: [iosDriver()], - preferences: iosPreferences, - }); - - const pending = harness.coordinator.request(phone, owner("agent")); - const settled = pending.catch(() => undefined); - await flush(); - const whileResolving = harness.coordinator.waitingDemand(); - open(); - await settled; - - expect(whileResolving).toEqual([]); - await expect(pending).rejects.toMatchObject({ name: "UnknownModelError" }); - }); - - it.each([ - ["names none", undefined, "default"], - ["names a version", "18.4", "18.4"], - ])( - "names the OS in the RuntimeMissingError of a class whose models pair with no runtime when the request %s", - async (_label, osVersion, named) => { - const driver = iosDriver({ modelRuntimes: { "iPhone 16": [] } }); - const harness = await classHarness(driver, { ios: { phone: ["iPhone 16"] } }); - - await expect( - harness.coordinator.request( - { ...phone, ...(osVersion === undefined ? {} : { osVersion }) }, - owner("agent"), - ), - ).rejects.toMatchObject({ name: "RuntimeMissingError", osVersion: named }); - }, - ); - - it("fits a class request naming an OS only a device on that OS, and creates a device on it otherwise", async () => { - const harness = await classHarness(); - const newest = await seedReady(harness, { ...iphone15, osVersion: "26.5" }); - - const older = await harness.coordinator.request( - { ...phone, osVersion: "18.4" }, - owner("agent"), - ); - - expect(older.device.id).not.toBe(newest.id); - expect(older.device.spec.osVersion).toBe("18.4"); - - const sameOs = await classHarness(); - const warm = await seedReady(sameOs, iphone15); - const granted = await sameOs.coordinator.request( - { ...phone, osVersion: "18.4" }, - owner("agent"), - ); - expect(granted.device.id).toBe(warm.id); - }); - - it("fails a class request naming an image tag on a driver with no images with RuntimeMissingError, not downloadable", async () => { - const harness = await classHarness(); - - await expect( - harness.coordinator.request({ ...phone, imageTag: "google_apis" }, owner("agent")), - ).rejects.toMatchObject({ downloadable: false, name: "RuntimeMissingError" }); - }); - - it("passes the driver an exact model, never a class", async () => { - const driver = iosDriver(); - const harness = await classHarness(driver); - - await harness.coordinator.request(phone, owner("agent")); - - const resolved = driver.calls.find((call) => call.operation === "resolveSpec"); - expect(resolved?.arguments[0]).toMatchObject({ model: "iPhone 17" }); - expect(resolved?.arguments[0]).not.toHaveProperty("class"); - }); - }); - - describe("idempotency", () => { - const keyed = { ...owner("agent"), idempotencyKey: "key-1" }; - - it("returns the stored grant to a repeat of the same class request", async () => { - const harness = await classHarness(); - const first = await harness.coordinator.request(phone, keyed); - - const second = await harness.coordinator.request(phone, keyed); - - expect(second.lease.id).toBe(first.lease.id); - }); - - it.each([ - ["an exact request", { model: "iPhone 17", platform: "ios" }], - ["a request of another class", { class: "watch", platform: "ios" }], - ["a request with neither field", { platform: "ios" }], - ] as const)("refuses the key of a class request used for %s", async (_label, other) => { - const harness = await classHarness(); - await harness.coordinator.request(phone, keyed); - - await expect(harness.coordinator.request(other, keyed)).rejects.toBeInstanceOf( - IdempotencyConflictError, - ); - }); - }); -}); - -describe("LeaseAcquisitionCoordinator: what lease.granted reports", () => { - const owner = (id: string) => ({ ownerId: id, requesterId: id }); - - function granted(harness: Awaited>) { - const events: Array<{ requestId: string; source: string; leaseId: string }> = []; - harness.bus.subscribe("lease.granted", (envelope) => events.push(envelope.payload)); - const requested: string[] = []; - harness.bus.subscribe("lease.requested", (envelope) => - requested.push(envelope.payload.requestId), - ); - return { events, requested }; - } - - it.each([ - { - name: "warm for a lease granted from a ready device", - source: "warm", - seed: async (harness) => { - await seedReady(harness); - }, - }, - { - name: "booted for a lease granted after booting a shut-down device", - source: "booted", - seed: async (harness) => { - await seedShutdown(harness); - }, - }, - { - name: "provisioned for a lease granted on a device provisioned for it", - source: "provisioned", - seed: async () => undefined, - }, - { - name: "provisioned when an eviction deleted a device and a new one was created", - source: "provisioned", - seed: async (harness) => { - await seedReady(harness, { ...request, model: "iPhone SE" }); - }, - }, - { - // why: with one running slot taken by a ready device of another model, the shut-down device - // of the requested model can boot only after an eviction gives the slot back. - name: "booted when an eviction shut a device down and a shut-down device was then booted", - source: "booted", - limits: { maxDevices: 2, maxRunning: 1 }, - seed: async (harness) => { - await seedShutdown(harness); - return seedReady(harness, { ...request, model: "iPhone SE" }); - }, - evictedLeavesReady: true, - }, - ] satisfies ReadonlyArray<{ - name: string; - source: "warm" | "booted" | "provisioned"; - limits?: { maxDevices: number; maxRunning: number }; - seed: (harness: Awaited>) => Promise<{ id: string } | void>; - evictedLeavesReady?: boolean; - }>)( - "emits lease.granted with exactly the grant's device, lease, requester, request and platform, and source $name", - async ({ source, limits, seed, evictedLeavesReady }) => { - const harness = await createHarness(limits); - const evicted = await seed(harness); - const { events, requested } = granted(harness); - - const grant = await harness.coordinator.request(request, owner("agent")); + const grant = await harness.coordinator.request(request, owner("agent")); expect(requested[0]).toMatch(/^req_/); expect(events).toEqual([ @@ -3330,255 +1771,6 @@ describe("LeaseAcquisitionCoordinator waiting demand", () => { }); }); -describe("LeaseAcquisitionCoordinator: resolve", () => { - const installer = () => { - const asked: unknown[] = []; - return { - asked, - components: { - install: async (call: unknown) => { - asked.push(call); - return { outcome: "installed" as const, version: "26.5" }; - }, - }, - }; - }; - const iphone17 = { model: "iPhone 17", platform: "ios" } as const; - const driverOf = (options: Partial[0]> = {}) => - new FakeDriver({ - availableOsVersions: ["18.0", "18.4", "26.0"], - clock: new FakeClock(1_000), - knownModels: ["iPhone 17"], - platform: "ios", - ...options, - }); - - it("resolves a target naming a model and an installed OS to the spec a request for it is granted a device of", async () => { - const harness = await createHarness({ drivers: [driverOf()] }); - - const resolved = await harness.coordinator.resolve({ ...iphone17, osVersion: "26.0" }); - const granted = await harness.coordinator.request( - { ...iphone17, osVersion: "26.0" }, - { ownerId: "a", requesterId: "a" }, - ); - - expect(resolved).toEqual({ - spec: { physical: false, model: "iPhone 17", osVersion: "26.0", platform: "ios" }, - }); - expect(granted.device.spec).toEqual( - "spec" in resolved ? resolved.spec : { model: "never matches" }, - ); - }); - - it("resolves an OS range to the newest installed runtime in it", async () => { - const harness = await createHarness({ drivers: [driverOf()] }); - - const resolved = await harness.coordinator.resolve({ ...iphone17, osVersion: ">=18 <26" }); - - expect(resolved).toEqual({ - spec: { physical: false, model: "iPhone 17", osVersion: "18.4", platform: "ios" }, - }); - }); - - it("queues nothing, reserves nothing and creates nothing", async () => { - const driver = driverOf(); - const harness = await createHarness({ drivers: [driver] }); - - await harness.coordinator.resolve({ ...iphone17, osVersion: "26.0" }); - - expect(harness.coordinator.queueDepth).toBe(0); - expect(harness.registry.snapshot.devices).toEqual([]); - expect( - driver.calls.filter((call) => ["provision", "makeReady"].includes(call.operation)), - ).toEqual([]); - await expect( - harness.coordinator.request( - { ...iphone17, osVersion: "26.0" }, - { noWait: true, ownerId: "next", requesterId: "next" }, - ), - ).resolves.toMatchObject({ lease: { requesterId: "next" } }); - }); - - it("answers runtime-missing for an OS that is not installed, and never calls the installer though a request could download it", async () => { - const { asked, components } = installer(); - const driver = driverOf({ availableOsVersions: [] }); - const harness = await createHarness({ components, drivers: [driver] }); - - const resolved = await harness.coordinator.resolve({ ...iphone17, osVersion: "27.0" }); - - expect(resolved).toMatchObject({ refusal: "runtime-missing" }); - expect(resolved).toHaveProperty("message", expect.stringContaining("27.0")); - expect(asked).toEqual([]); - expect(driver.calls.filter((call) => call.operation === "installComponent")).toEqual([]); - }); - - it("answers runtime-missing for an OS range no installed runtime is in", async () => { - const harness = await createHarness({ drivers: [driverOf()] }); - - const resolved = await harness.coordinator.resolve({ ...iphone17, osVersion: ">=30" }); - - expect(resolved).toMatchObject({ refusal: "runtime-missing" }); - }); - - it("answers unknown-model for a model the catalog does not list, exact or in a range", async () => { - const harness = await createHarness({ drivers: [driverOf()] }); - - const exact = await harness.coordinator.resolve({ - model: "iPhone 99", - osVersion: "26.0", - platform: "ios", - }); - const ranged = await harness.coordinator.resolve({ - model: "iPhone 99", - osVersion: ">=18", - platform: "ios", - }); - - expect(exact).toMatchObject({ refusal: "unknown-model" }); - expect(ranged).toMatchObject({ refusal: "unknown-model" }); - }); - - it("answers no-driver for a platform this machine has no driver for", async () => { - const harness = await createHarness({ drivers: [driverOf()] }); - - const resolved = await harness.coordinator.resolve({ model: "Pixel 9", platform: "android" }); - - expect(resolved).toMatchObject({ refusal: "no-driver" }); - expect(resolved).toHaveProperty("message", expect.stringContaining("android")); - }); - - it("answers unresolvable with the driver's message when the driver throws any other error", async () => { - const driver = driverOf(); - driver.failOn("resolveSpec", 1, new Error("the simulator service is down")); - const harness = await createHarness({ drivers: [driver] }); - - const resolved = await harness.coordinator.resolve({ ...iphone17, osVersion: "26.0" }); - - expect(resolved).toEqual({ - message: "the simulator service is down", - refusal: "unresolvable", - }); - }); - - it("gives a slim target on a runtime the driver can slim a slim spec, and one it cannot a full spec", async () => { - const driver = driverOf({ - availableOsVersions: ["17.5", "26.5"], - slimmableOsVersions: ["26.5"], - }); - const harness = await createHarness({ drivers: [driver] }); - - const slimmable = await harness.coordinator.resolve({ - ...iphone17, - mode: "slim", - osVersion: "26.5", - }); - const below = await harness.coordinator.resolve({ - ...iphone17, - mode: "slim", - osVersion: "17.5", - }); - - expect(slimmable).toEqual({ - spec: { - physical: false, - mode: "slim", - model: "iPhone 17", - osVersion: "26.5", - platform: "ios", - }, - }); - expect(below).toEqual({ - spec: { physical: false, model: "iPhone 17", osVersion: "17.5", platform: "ios" }, - }); - }); - - it("gives a target naming no mode the worker's default mode, and a full one a full spec", async () => { - const driver = driverOf({ availableOsVersions: ["26.5"], slimmableOsVersions: ["26.5"] }); - const harness = await createHarness({ defaultModes: { ios: "slim" }, drivers: [driver] }); - - const defaulted = await harness.coordinator.resolve({ ...iphone17, osVersion: "26.5" }); - const full = await harness.coordinator.resolve({ - ...iphone17, - mode: "full", - osVersion: "26.5", - }); - - expect(defaulted).toMatchObject({ spec: { mode: "slim" } }); - expect(full).toEqual({ - spec: { physical: false, model: "iPhone 17", osVersion: "26.5", platform: "ios" }, - }); - }); -}); - -describe("LeaseAcquisitionCoordinator: levels a model no longer pairs with", () => { - const pixel = { model: "Pixel 8", physical: false, platform: "android" } as const; - const owner = (id: string) => ({ ownerId: id, requesterId: id }); - - class PairingDriver extends FakeDriver { - override async resolveSpec( - ...args: Parameters - ): Promise { - const catalog = await this.listCatalog(); - const { model, osVersion } = args[0]; - if (osVersion !== undefined && !(catalog.modelRuntimes[model] ?? []).includes(osVersion)) { - throw new RuntimeMissingError("android", osVersion); - } - return super.resolveSpec(...args); - } - } - - function pairing(): PairingDriver { - return new PairingDriver({ - availableOsVersions: ["34", "35"], - clock: new FakeClock(1_000), - knownModels: ["Pixel 8"], - modelRuntimes: { "Pixel 8": ["35"] }, - platform: "android", - }); - } - - it("reuses an idle device on a level the catalog pairs for an exact request", async () => { - const harness = await createHarness({ drivers: [pairing()], maxDevices: 2 }); - const idle = await seedReady(harness, { ...pixel, osVersion: "35" }); - - const granted = await harness.coordinator.request( - { ...pixel, osVersion: "35" }, - owner("agent"), - ); - - expect(granted.device.id).toBe(idle.id); - }); - - it("does not pick an idle device on a level the catalog no longer pairs for an exact request", async () => { - const harness = await createHarness({ drivers: [pairing()], maxDevices: 2 }); - const idle = await seedReady(harness, { ...pixel, osVersion: "34" }); - - const outcome = await harness.coordinator - .request({ ...pixel, osVersion: "34" }, owner("agent")) - .then( - (granted) => ({ granted: granted.device.id }), - (error: unknown) => ({ failed: (error as Error).name }), - ); - - expect(outcome).toEqual({ failed: "RuntimeMissingError" }); - expect(harness.registry.snapshot.devices.find((device) => device.id === idle.id)?.state).toBe( - "ready", - ); - }); - - it("still picks an idle device on a level the catalog no longer pairs for a range request", async () => { - const harness = await createHarness({ drivers: [pairing()], maxDevices: 2 }); - const idle = await seedReady(harness, { ...pixel, osVersion: "34" }); - - const granted = await harness.coordinator.request( - { model: "Pixel 8", osVersion: ">=34", platform: "android" }, - owner("agent"), - ); - - expect(granted.device.id).toBe(idle.id); - }); -}); - describe("LeaseAcquisitionCoordinator: a request naming a baseline", () => { it("plans against the version current at its decision, so a save between the resolve and the plan grants an idle device of the new version", async () => { const current = (version: number) => ({ diff --git a/src/leasing/lease-acquisition-resolution.test.ts b/src/leasing/lease-acquisition-resolution.test.ts new file mode 100644 index 000000000..394b34407 --- /dev/null +++ b/src/leasing/lease-acquisition-resolution.test.ts @@ -0,0 +1,767 @@ +import { describe, expect, it } from "vitest"; + +import { FakeClock } from "../ports/index.js"; +import { + DriverCrashError, + RuntimeMissingError, + UnsupportedRequestOptionError, + type VirtualSpec, +} from "../core/index.js"; +import { FakeDriver } from "../core/testing.js"; +import { type LeaseRequestOptions } from "./wait-queue.js"; +import { + gibibyte, + request, + createHarness, + seedReady, + flush, + settle, + installs, +} from "./test-lease-acquisition.js"; + +// why: drives the coordinator on its own, so a test can order installs, catalog reads and the queue in ways the leasing surface cannot force. +describe("LeaseAcquisitionCoordinator: missing runtimes", () => { + it("installs once for two lease requests for the same missing runtime, and grants both", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + driver.holdInstalls(); + const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); + + const first = harness.coordinator.request(request, { + allowDownload: true, + ownerId: "a", + requesterId: "a", + }); + const second = harness.coordinator.request(request, { + allowDownload: true, + ownerId: "b", + requesterId: "b", + }); + await flush(); + driver.releaseInstalls(); + + const grants = await Promise.all([first, second]); + expect(grants.map((grant) => grant.device.spec.osVersion)).toEqual(["26.5", "26.5"]); + expect(installs(driver)).toEqual(["26.5"]); + }); + + it("starts the install for a second missing runtime on the same platform only after the first one has ended", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + driver.holdInstalls(); + const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); + + const first = harness.coordinator.request(request, { + allowDownload: true, + ownerId: "a", + requesterId: "a", + }); + const second = harness.coordinator.request( + { ...request, osVersion: "27.0" }, + { allowDownload: true, ownerId: "b", requesterId: "b" }, + ); + await flush(); + expect(installs(driver)).toEqual(["26.5"]); + + driver.releaseInstalls(); + await first; + await settle(); + expect(installs(driver)).toEqual(["26.5", "27.0"]); + await expect(second).resolves.toMatchObject({ device: { spec: { osVersion: "27.0" } } }); + }); + + it("attributes the install a lease request starts to that request's requester", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + const harness = await createHarness({ drivers: [driver] }); + const started: unknown[] = []; + harness.bus.subscribe("component.install-started", (envelope) => { + started.push(envelope.payload); + }); + + await harness.coordinator.request(request, { + allowDownload: true, + ownerId: "owner", + requesterId: "agent-7", + }); + + expect(started).toEqual([{ componentId: "26.5", platform: "ios", requesterId: "agent-7" }]); + }); + + it("starts no install when resolving again fails some other way by the time the request reaches the front, and fails with that error", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + const broken = new DriverCrashError("simctl list failed"); + driver.failOn("resolveSpec", 2, broken); + driver.failOn("resolveSpec", 3, broken); + const harness = await createHarness({ drivers: [driver] }); + + await expect( + harness.coordinator.request(request, { allowDownload: true, ownerId: "a", requesterId: "a" }), + ).rejects.toBe(broken); + expect(installs(driver)).toEqual([]); + }); + + it("fails a request without allowDownload for a missing runtime with RuntimeMissingError, and never calls the installer", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + const asked: unknown[] = []; + const harness = await createHarness({ + components: { + install: async (call) => { + asked.push(call); + return { outcome: "installed", version: "26.5" }; + }, + }, + drivers: [driver], + }); + + await expect( + harness.coordinator.request(request, { ownerId: "a", requesterId: "a" }), + ).rejects.toMatchObject({ component: "26.5", name: "RuntimeMissingError" }); + expect(asked).toEqual([]); + }); + + it("fails the request with InsufficientDiskSpaceError when the install does not fit, and never calls installComponent", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ + availableOsVersions: [], + clock, + componentFootprint: { bytes: 8 * gibibyte, path: "/" }, + platform: "ios", + }); + const harness = await createHarness({ drivers: [driver], freeDiskBytes: gibibyte }); + + await expect( + harness.coordinator.request(request, { allowDownload: true, ownerId: "a", requesterId: "a" }), + ).rejects.toMatchObject({ name: "InsufficientDiskSpaceError" }); + expect(installs(driver)).toEqual([]); + }); +}); + +describe("LeaseAcquisitionCoordinator: download progress", () => { + type Progress = Parameters>[0]; + + function downloading(progress: readonly Progress[]): readonly Progress[] { + return progress.filter((report) => report.stage === "downloading"); + } + + it("tells a request that starts a download downloading, naming the component and not waiting, before provisioning", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + const harness = await createHarness({ drivers: [driver] }); + const progress: Progress[] = []; + + await harness.coordinator.request(request, { + allowDownload: true, + onProgress: (report) => progress.push(report), + ownerId: "a", + requesterId: "a", + }); + + expect(progress[0]).toEqual({ component: "26.5", stage: "downloading", waiting: false }); + const provisioning = progress.findIndex((report) => report.stage === "provisioning"); + expect(provisioning).toBeGreaterThan(0); + expect(progress.slice(provisioning).some((report) => report.stage === "downloading")).toBe( + false, + ); + }); + + it("tells a request behind another download on its platform that it is waiting, then not waiting when its own install starts", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + driver.holdInstalls(); + const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); + const progress: Progress[] = []; + + const first = harness.coordinator.request(request, { + allowDownload: true, + ownerId: "a", + requesterId: "a", + }); + const second = harness.coordinator.request( + { ...request, osVersion: "27.0" }, + { + allowDownload: true, + onProgress: (report) => progress.push(report), + ownerId: "b", + requesterId: "b", + }, + ); + await flush(); + expect(progress).toEqual([{ component: "27.0", stage: "downloading", waiting: true }]); + + driver.releaseInstalls(); + await first; + await settle(); + expect(installs(driver)).toEqual(["26.5", "27.0"]); + expect(downloading(progress)).toEqual([ + { component: "27.0", stage: "downloading", waiting: true }, + { component: "27.0", stage: "downloading", waiting: false }, + { component: "27.0", percent: 100, stage: "downloading", waiting: false }, + ]); + await expect(second).resolves.toMatchObject({ device: { spec: { osVersion: "27.0" } } }); + }); + + it("tells a request that joins a download already running its latest percentage at once", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ + availableOsVersions: [], + clock, + installProgress: [12, 41], + platform: "ios", + }); + driver.holdInstalls(); + const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); + const joined: Progress[] = []; + + const first = harness.coordinator.request(request, { + allowDownload: true, + ownerId: "a", + requesterId: "a", + }); + await flush(); + expect(installs(driver)).toEqual(["26.5"]); + const second = harness.coordinator.request(request, { + allowDownload: true, + onProgress: (report) => joined.push(report), + ownerId: "b", + requesterId: "b", + }); + await flush(); + + expect(joined).toEqual([ + { component: "26.5", percent: 41, stage: "downloading", waiting: false }, + ]); + driver.releaseInstalls(); + await Promise.all([first, second]); + expect(installs(driver)).toEqual(["26.5"]); + }); + + it.each([ + { + name: "a percentage the driver reports twice is sent once", + installProgress: [30, 30, 60], + percents: [undefined, 30, 60, 100], + }, + { + name: "41.7 is sent as 41, and one that rounds down to the last sent is not sent", + installProgress: [41.7, 41.9], + percents: [undefined, 41, 100], + }, + { + name: "a percentage outside 0 to 100 is sent as the nearest bound, and one that is not a number as no percent", + installProgress: [10, Number.NaN, -5, 150], + percents: [undefined, 10, undefined, 0, 100], + }, + ])( + "maps the installer's progress to the percentages the requester sees: $name", + async ({ installProgress, percents }) => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ + availableOsVersions: [], + clock, + installProgress, + platform: "ios", + }); + const harness = await createHarness({ drivers: [driver] }); + const progress: Progress[] = []; + + await harness.coordinator.request(request, { + allowDownload: true, + onProgress: (report) => progress.push(report), + ownerId: "a", + requesterId: "a", + }); + + expect(downloading(progress)).toEqual( + percents.map((percent) => ({ + component: "26.5", + ...(percent === undefined ? {} : { percent }), + stage: "downloading", + waiting: false, + })), + ); + const complete = progress.findIndex( + (report) => report.stage === "downloading" && report.percent === 100, + ); + const provisioning = progress.findIndex((report) => report.stage === "provisioning"); + expect(provisioning).toBeGreaterThan(complete); + expect(progress.slice(provisioning).some((report) => report.stage === "downloading")).toBe( + false, + ); + }, + ); + + it("sends no downloading stage to a request whose runtime is installed", async () => { + const harness = await createHarness(); + const progress: Progress[] = []; + + await harness.coordinator.request(request, { + allowDownload: true, + onProgress: (report) => progress.push(report), + ownerId: "a", + requesterId: "a", + }); + + expect(progress.map((report) => report.stage)).toContain("provisioning"); + expect(downloading(progress)).toEqual([]); + }); + + it("sends no downloading stage to a request without allowDownload for a missing runtime", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + const harness = await createHarness({ drivers: [driver] }); + const progress: Progress[] = []; + + await expect( + harness.coordinator.request(request, { + onProgress: (report) => progress.push(report), + ownerId: "a", + requesterId: "a", + }), + ).rejects.toMatchObject({ name: "RuntimeMissingError" }); + expect(progress).toEqual([]); + }); + + it("tells a request that waited and then needed no install that it was waiting, then provisioning, and never not waiting", async () => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); + driver.holdInstalls(); + const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); + const progress: Progress[] = []; + + const byVersion = harness.coordinator.request(request, { + allowDownload: true, + ownerId: "a", + requesterId: "a", + }); + const newest = harness.coordinator.request( + { model: "iPhone 16", platform: "ios" }, + { + allowDownload: true, + onProgress: (report) => progress.push(report), + ownerId: "b", + requesterId: "b", + }, + ); + await flush(); + driver.releaseInstalls(); + await expect(byVersion).resolves.toMatchObject({ device: { spec: { osVersion: "26.5" } } }); + await expect(newest).resolves.toMatchObject({ device: { spec: { osVersion: "26.5" } } }); + + expect(installs(driver)).toEqual(["26.5"]); + expect(progress[0]).toMatchObject({ stage: "downloading", waiting: true }); + expect( + downloading(progress).every((report) => report.stage === "downloading" && report.waiting), + ).toBe(true); + expect(progress[1]).toMatchObject({ stage: "provisioning" }); + }); +}); + +describe("LeaseAcquisitionCoordinator: image tags", () => { + const android = { + physical: false, + model: "Pixel 8", + osVersion: "34", + platform: "android", + } as const; + const playstore = { ...android, imageTag: "google_apis_playstore" } as const; + const owner = (id: string) => ({ ownerId: id, requesterId: id }); + + function taggedDriver(): FakeDriver { + return new FakeDriver({ + availableOsVersions: ["34", "35"], + clock: new FakeClock(1_000), + images: [ + { abi: "arm64-v8a", runtime: "34", tag: "google_apis" }, + { abi: "arm64-v8a", runtime: "34", tag: "google_apis_playstore" }, + { abi: "arm64-v8a", runtime: "35", tag: "google_apis" }, + ], + platform: "android", + }); + } + + it("grants a request naming a tag a device whose spec carries that tag, and one naming none a spec without one", async () => { + const driver = taggedDriver(); + const harness = await createHarness({ drivers: [driver], maxDevices: 2, maxRunning: 2 }); + + const tagged = await harness.coordinator.request(playstore, owner("tagged")); + const untagged = await harness.coordinator.request(android, owner("untagged")); + + expect(tagged.device.spec).toEqual(playstore); + expect(untagged.device.spec).toEqual(android); + const provisioned = driver.calls + .filter((call) => call.operation === "provision") + .map((call) => call.arguments[0]); + expect(provisioned).toEqual([playstore, android]); + }); + + it.each([ + ["without allowDownload", false], + ["with allowDownload", true], + ])( + "fails a tag not installed for the API level with a RuntimeMissingError %s, and never asks the installer", + async (_label, allowDownload) => { + const asked: unknown[] = []; + const harness = await createHarness({ + components: { + install: async (call) => { + asked.push(call); + return { outcome: "installed", version: "35" }; + }, + }, + drivers: [taggedDriver()], + }); + + await expect( + harness.coordinator.request( + { ...playstore, osVersion: "35" }, + { ...owner("agent"), allowDownload }, + ), + ).rejects.toMatchObject({ downloadable: false, name: "RuntimeMissingError" }); + expect(asked).toEqual([]); + }, + ); + + it.each([ + { + name: "of another tag", + seeded: { ...android, imageTag: "google_apis" }, + requested: playstore, + }, + { name: "with no tag", seeded: android, requested: playstore }, + { name: "with a tag when it names none", seeded: playstore, requested: android }, + ] as const)("does not give a request an idle device $name", async ({ seeded, requested }) => { + const harness = await createHarness({ drivers: [taggedDriver()], maxDevices: 2 }); + const idle = await seedReady(harness, seeded); + + const granted = await harness.coordinator.request(requested, owner("agent")); + + expect(granted.device.id).not.toBe(idle.id); + expect(granted.device.spec).toEqual(requested); + }); + + it("gives a request naming a tag an idle device of that tag", async () => { + const harness = await createHarness({ drivers: [taggedDriver()], maxDevices: 2 }); + const tagged = await seedReady(harness, playstore); + + const granted = await harness.coordinator.request(playstore, owner("agent")); + + expect(granted.device.id).toBe(tagged.id); + }); + + it("rejects a request whose driver refuses the image tag as unresolvable-spec, with the driver's error", async () => { + class NoTagsDriver extends FakeDriver { + override async resolveSpec( + ...args: Parameters + ): Promise { + if (args[0].imageTag !== undefined) { + throw new UnsupportedRequestOptionError(this.platform, "imageTag"); + } + return super.resolveSpec(...args); + } + } + const driver = new NoTagsDriver({ + availableOsVersions: ["26.5"], + clock: new FakeClock(1_000), + platform: "ios", + }); + const harness = await createHarness({ drivers: [driver] }); + + await expect( + harness.coordinator.request({ ...request, imageTag: "google_apis" }, owner("agent")), + ).rejects.toBeInstanceOf(UnsupportedRequestOptionError); + expect( + harness.bus + .replay() + .filter((event) => event.event === "lease.rejected") + .map((event) => event.payload), + ).toEqual([ + { + reason: "unresolvable-spec", + requestId: expect.stringMatching(/^req_/), + requester: "agent", + requestSpec: { ...request, imageTag: "google_apis" }, + }, + ]); + expect(driver.calls.map((call) => call.operation)).not.toContain("provision"); + }); + + it.each([ + ["another tag than the one the request named", playstore, { imageTag: "default" }], + ["a tag for a request that named none", android, { imageTag: "google_apis" }], + ] as const)( + "refuses a spec the driver resolves with %s, and provisions nothing", + async (_label, asked, returned) => { + class WrongTagDriver extends FakeDriver { + override async resolveSpec( + ...args: Parameters + ): Promise { + return { ...(await super.resolveSpec(...args)), ...returned }; + } + } + const driver = new WrongTagDriver({ + availableOsVersions: ["34"], + clock: new FakeClock(1_000), + images: [{ abi: "arm64-v8a", runtime: "34", tag: "google_apis_playstore" }], + platform: "android", + }); + const harness = await createHarness({ drivers: [driver] }); + + await expect(harness.coordinator.request(asked, owner("agent"))).rejects.toThrow( + /driver resolved image tag .* for a request naming/, + ); + expect(driver.calls.map((call) => call.operation)).not.toContain("provision"); + }, + ); +}); + +describe("LeaseAcquisitionCoordinator: resolve", () => { + const installer = () => { + const asked: unknown[] = []; + return { + asked, + components: { + install: async (call: unknown) => { + asked.push(call); + return { outcome: "installed" as const, version: "26.5" }; + }, + }, + }; + }; + const iphone17 = { model: "iPhone 17", platform: "ios" } as const; + const driverOf = (options: Partial[0]> = {}) => + new FakeDriver({ + availableOsVersions: ["18.0", "18.4", "26.0"], + clock: new FakeClock(1_000), + knownModels: ["iPhone 17"], + platform: "ios", + ...options, + }); + + it("resolves a target naming a model and an installed OS to the spec a request for it is granted a device of", async () => { + const harness = await createHarness({ drivers: [driverOf()] }); + + const resolved = await harness.coordinator.resolve({ ...iphone17, osVersion: "26.0" }); + const granted = await harness.coordinator.request( + { ...iphone17, osVersion: "26.0" }, + { ownerId: "a", requesterId: "a" }, + ); + + expect(resolved).toEqual({ + spec: { physical: false, model: "iPhone 17", osVersion: "26.0", platform: "ios" }, + }); + expect(granted.device.spec).toEqual( + "spec" in resolved ? resolved.spec : { model: "never matches" }, + ); + }); + + it("resolves an OS range to the newest installed runtime in it", async () => { + const harness = await createHarness({ drivers: [driverOf()] }); + + const resolved = await harness.coordinator.resolve({ ...iphone17, osVersion: ">=18 <26" }); + + expect(resolved).toEqual({ + spec: { physical: false, model: "iPhone 17", osVersion: "18.4", platform: "ios" }, + }); + }); + + it("queues nothing, reserves nothing and creates nothing", async () => { + const driver = driverOf(); + const harness = await createHarness({ drivers: [driver] }); + + await harness.coordinator.resolve({ ...iphone17, osVersion: "26.0" }); + + expect(harness.coordinator.queueDepth).toBe(0); + expect(harness.registry.snapshot.devices).toEqual([]); + expect( + driver.calls.filter((call) => ["provision", "makeReady"].includes(call.operation)), + ).toEqual([]); + await expect( + harness.coordinator.request( + { ...iphone17, osVersion: "26.0" }, + { noWait: true, ownerId: "next", requesterId: "next" }, + ), + ).resolves.toMatchObject({ lease: { requesterId: "next" } }); + }); + + it("answers runtime-missing for an OS that is not installed, and never calls the installer though a request could download it", async () => { + const { asked, components } = installer(); + const driver = driverOf({ availableOsVersions: [] }); + const harness = await createHarness({ components, drivers: [driver] }); + + const resolved = await harness.coordinator.resolve({ ...iphone17, osVersion: "27.0" }); + + expect(resolved).toMatchObject({ refusal: "runtime-missing" }); + expect(resolved).toHaveProperty("message", expect.stringContaining("27.0")); + expect(asked).toEqual([]); + expect(driver.calls.filter((call) => call.operation === "installComponent")).toEqual([]); + }); + + it("answers runtime-missing for an OS range no installed runtime is in", async () => { + const harness = await createHarness({ drivers: [driverOf()] }); + + const resolved = await harness.coordinator.resolve({ ...iphone17, osVersion: ">=30" }); + + expect(resolved).toMatchObject({ refusal: "runtime-missing" }); + }); + + it("answers unknown-model for a model the catalog does not list, exact or in a range", async () => { + const harness = await createHarness({ drivers: [driverOf()] }); + + const exact = await harness.coordinator.resolve({ + model: "iPhone 99", + osVersion: "26.0", + platform: "ios", + }); + const ranged = await harness.coordinator.resolve({ + model: "iPhone 99", + osVersion: ">=18", + platform: "ios", + }); + + expect(exact).toMatchObject({ refusal: "unknown-model" }); + expect(ranged).toMatchObject({ refusal: "unknown-model" }); + }); + + it("answers no-driver for a platform this machine has no driver for", async () => { + const harness = await createHarness({ drivers: [driverOf()] }); + + const resolved = await harness.coordinator.resolve({ model: "Pixel 9", platform: "android" }); + + expect(resolved).toMatchObject({ refusal: "no-driver" }); + expect(resolved).toHaveProperty("message", expect.stringContaining("android")); + }); + + it("answers unresolvable with the driver's message when the driver throws any other error", async () => { + const driver = driverOf(); + driver.failOn("resolveSpec", 1, new Error("the simulator service is down")); + const harness = await createHarness({ drivers: [driver] }); + + const resolved = await harness.coordinator.resolve({ ...iphone17, osVersion: "26.0" }); + + expect(resolved).toEqual({ + message: "the simulator service is down", + refusal: "unresolvable", + }); + }); + + it("gives a slim target on a runtime the driver can slim a slim spec, and one it cannot a full spec", async () => { + const driver = driverOf({ + availableOsVersions: ["17.5", "26.5"], + slimmableOsVersions: ["26.5"], + }); + const harness = await createHarness({ drivers: [driver] }); + + const slimmable = await harness.coordinator.resolve({ + ...iphone17, + mode: "slim", + osVersion: "26.5", + }); + const below = await harness.coordinator.resolve({ + ...iphone17, + mode: "slim", + osVersion: "17.5", + }); + + expect(slimmable).toEqual({ + spec: { + physical: false, + mode: "slim", + model: "iPhone 17", + osVersion: "26.5", + platform: "ios", + }, + }); + expect(below).toEqual({ + spec: { physical: false, model: "iPhone 17", osVersion: "17.5", platform: "ios" }, + }); + }); + + it("gives a target naming no mode the worker's default mode, and a full one a full spec", async () => { + const driver = driverOf({ availableOsVersions: ["26.5"], slimmableOsVersions: ["26.5"] }); + const harness = await createHarness({ defaultModes: { ios: "slim" }, drivers: [driver] }); + + const defaulted = await harness.coordinator.resolve({ ...iphone17, osVersion: "26.5" }); + const full = await harness.coordinator.resolve({ + ...iphone17, + mode: "full", + osVersion: "26.5", + }); + + expect(defaulted).toMatchObject({ spec: { mode: "slim" } }); + expect(full).toEqual({ + spec: { physical: false, model: "iPhone 17", osVersion: "26.5", platform: "ios" }, + }); + }); +}); + +describe("LeaseAcquisitionCoordinator: levels a model no longer pairs with", () => { + const pixel = { model: "Pixel 8", physical: false, platform: "android" } as const; + const owner = (id: string) => ({ ownerId: id, requesterId: id }); + + class PairingDriver extends FakeDriver { + override async resolveSpec( + ...args: Parameters + ): Promise { + const catalog = await this.listCatalog(); + const { model, osVersion } = args[0]; + if (osVersion !== undefined && !(catalog.modelRuntimes[model] ?? []).includes(osVersion)) { + throw new RuntimeMissingError("android", osVersion); + } + return super.resolveSpec(...args); + } + } + + function pairing(): PairingDriver { + return new PairingDriver({ + availableOsVersions: ["34", "35"], + clock: new FakeClock(1_000), + knownModels: ["Pixel 8"], + modelRuntimes: { "Pixel 8": ["35"] }, + platform: "android", + }); + } + + it("reuses an idle device on a level the catalog pairs for an exact request", async () => { + const harness = await createHarness({ drivers: [pairing()], maxDevices: 2 }); + const idle = await seedReady(harness, { ...pixel, osVersion: "35" }); + + const granted = await harness.coordinator.request( + { ...pixel, osVersion: "35" }, + owner("agent"), + ); + + expect(granted.device.id).toBe(idle.id); + }); + + it("does not pick an idle device on a level the catalog no longer pairs for an exact request", async () => { + const harness = await createHarness({ drivers: [pairing()], maxDevices: 2 }); + const idle = await seedReady(harness, { ...pixel, osVersion: "34" }); + + const outcome = await harness.coordinator + .request({ ...pixel, osVersion: "34" }, owner("agent")) + .then( + (granted) => ({ granted: granted.device.id }), + (error: unknown) => ({ failed: (error as Error).name }), + ); + + expect(outcome).toEqual({ failed: "RuntimeMissingError" }); + expect(harness.registry.snapshot.devices.find((device) => device.id === idle.id)?.state).toBe( + "ready", + ); + }); + + it("still picks an idle device on a level the catalog no longer pairs for a range request", async () => { + const harness = await createHarness({ drivers: [pairing()], maxDevices: 2 }); + const idle = await seedReady(harness, { ...pixel, osVersion: "34" }); + + const granted = await harness.coordinator.request( + { model: "Pixel 8", osVersion: ">=34", platform: "android" }, + owner("agent"), + ); + + expect(granted.device.id).toBe(idle.id); + }); +}); diff --git a/src/leasing/test-lease-acquisition.ts b/src/leasing/test-lease-acquisition.ts new file mode 100644 index 000000000..180678309 --- /dev/null +++ b/src/leasing/test-lease-acquisition.ts @@ -0,0 +1,295 @@ +import { EventBus } from "../bus/index.js"; +import { FakeClock, FakeSystemStats, type Logger, MemoryFilesystem } from "../ports/index.js"; +import { AcquisitionPlanner } from "./acquisition-planner.js"; +import { + CapacityCoordinator, + type Config, + DeviceOperationClaims, + DeviceProvisioner, + ComponentInstaller, + DriverCatalog, + type ModelPreferences, + DiskSpaceGuard, + type Driver, + type DeviceMode, + type VirtualSpec, + type Platform, + specMode, + type BaselineService, + type CatalogReader, + ManagedDeviceLifecycle, + type Registry, + SerializedDecision, +} from "../core/index.js"; +import { + createCapacityStrategy, + loadTestRegistry, + openTestState, + readyTransitionUpdate, +} from "../core/testing.js"; +import { FakeDriver } from "../core/testing.js"; +import { QuarantineCoordinator } from "../core/testing.js"; +import { + LeaseAcquisitionCoordinator, + type LeaseAcquisitionCoordinatorOptions, + NoCapacityError, +} from "./lease-acquisition-coordinator.js"; +import { LeaseExpiryScheduler } from "./lease-expiry-scheduler.js"; +import { LeaseRequestBook } from "./lease-request-book.js"; +import { LeaseLifecycle } from "./lease-lifecycle.js"; +import { WaitQueue } from "./wait-queue.js"; + +export const gibibyte = 1024 ** 3; +export const request = { + physical: false, + model: "iPhone 16", + osVersion: "26.5", + platform: "ios", +} as const; + +function config(maxDevices = 1, maxRunning = 1): Pick { + return { + capacity: { + strategy: "resource", + config: { + limits: { + android: { maxDevices, maxRunning }, + ios: { maxDevices, maxRunning }, + maxRunning, + }, + ramBudget: { androidBytesPerDevice: 4 * gibibyte, iosBytesPerDevice: gibibyte }, + }, + }, + warmPool: { + enabled: true, + maxConcurrentBoots: 1, + reserveRunning: { android: 0, ios: 0 }, + targets: [], + quarantine: { + maxRetries: 3, + maxRetryBackoffMs: 300_000, + retryBackoffMs: 30_000, + retryBackoffMultiplier: 2, + }, + }, + }; +} + +// fallow-ignore-next-line complexity -- one test harness builder; each option is a plain pass-through to a collaborator. +export async function createHarness( + options: { + /** why: stands in for the baselines a request names, when a test scripts the versions. */ + readonly baselines?: Pick; + readonly components?: Pick; + readonly defaultModes?: Readonly>>; + readonly drivers?: readonly Driver[]; + readonly freeDiskBytes?: number; + readonly lifecycle?: ( + lifecycle: ManagedDeviceLifecycle, + collaborators: { + readonly capacity: CapacityCoordinator; + readonly claims: DeviceOperationClaims; + readonly registry: Registry; + }, + ) => LeaseAcquisitionCoordinatorOptions["lifecycle"]; + readonly logger?: Logger; + readonly maxDevices?: number; + readonly maxRunning?: number; + readonly quarantine?: LeaseAcquisitionCoordinatorOptions["quarantine"]; + readonly preferences?: ModelPreferences; + readonly catalogReader?: Pick; + } = {}, +) { + const clock = new FakeClock(1_000); + const bus = new EventBus(clock); + const driver = + (options.drivers?.[0] as FakeDriver | undefined) ?? + new FakeDriver({ clock, platform: "ios", availableOsVersions: ["26.5"] }); + const drivers = options.drivers ?? [driver]; + let nextId = 0; + const state = await openTestState(); + const registry = await loadTestRegistry({ + clock, + eventBus: bus, + idGenerator: { generate: () => `${nextId++}` }, + state, + }); + const decisions = new SerializedDecision(); + const claims = new DeviceOperationClaims(); + const catalog = new DriverCatalog(drivers, { preferences: options.preferences ?? {} }); + const appConfig = config(options.maxDevices, options.maxRunning); + const capacity = new CapacityCoordinator( + createCapacityStrategy( + appConfig.capacity, + new FakeSystemStats({ + cpuCount: 8, + totalRamBytes: 32 * gibibyte, + }), + ), + ); + const lifecycle = new ManagedDeviceLifecycle(catalog, registry, decisions, claims, clock); + // why: quarantine's kick wakes this coordinator's queue, and `coordinator` is only assigned below. + const quarantine = + options.quarantine ?? + new QuarantineCoordinator({ + claims, + clock, + config: appConfig.warmPool.quarantine, + decisions, + drivers: catalog, + eventBus: bus, + notifyAvailability: () => coordinator?.kick(), + registry, + }); + const provisioner = new DeviceProvisioner({ + baselines: () => ({ current: () => undefined, hold: () => () => undefined }), + catalog, + claims, + clock, + components: { claimProvision: () => () => undefined }, + decisions, + lifecycle, + registry, + }); + const expiry = new LeaseExpiryScheduler(clock, async () => undefined); + const leases = new LeaseLifecycle({ + clock, + eventBus: bus, + expiryScheduler: expiry, + registry, + ttl: { defaultMs: 100 }, + }); + let coordinator: LeaseAcquisitionCoordinator | undefined; + const requestIds: string[] = []; + const idGenerator = { + generate: () => { + const id = `request-${nextId++}`; + requestIds.push(id); + return id; + }, + }; + const queue = new WaitQueue({ + clock, + idGenerator, + onTimeout: (waiter) => { + bus.emit( + "lease.rejected", + { + requestId: waiter.id, + requester: waiter.options.requesterId, + requestSpec: waiter.request, + reason: "timeout", + }, + "wait-queue", + ); + coordinator?.kick(); + }, + }); + const components = + options.components ?? + new ComponentInstaller({ + clock, + decisions, + diskSpace: new DiskSpaceGuard(), + drivers: catalog, + eventBus: bus, + filesystem: new MemoryFilesystem(options.freeDiskBytes), + registry, + timeoutMs: 1_200_000, + }); + coordinator = new LeaseAcquisitionCoordinator({ + baselines: options.baselines ?? { current: () => undefined }, + catalog: options.catalogReader ?? catalog, + claims, + components, + decisions, + defaultModes: options.defaultModes ?? {}, + drivers: catalog, + eventBus: bus, + idGenerator, + leases, + lifecycle: options.lifecycle?.(lifecycle, { capacity, claims, registry }) ?? lifecycle, + ...(options.logger === undefined ? {} : { logger: options.logger }), + modelPreferences: options.preferences ?? {}, + planner: new AcquisitionPlanner(capacity, claims), + provisioner, + queue, + quarantine, + registry, + requests: new LeaseRequestBook({ + decisions, + describeFailure: (error) => ({ + code: error instanceof NoCapacityError ? "NO_CAPACITY" : "INTERNAL", + message: error instanceof Error ? error.message : String(error), + }), + store: registry, + }), + }); + return { + bus, + capacity, + claims, + clock, + components, + coordinator, + driver, + provisioner, + queue, + registry, + requestIds, + state, + }; +} + +export async function seedReady( + harness: Awaited>, + spec: VirtualSpec = request, +) { + const driverDevice = await harness.driver.provision(spec); + const provisioned = await harness.registry.registerDevice({ + driverData: driverDevice.driverData, + driverDeviceId: driverDevice.deviceId, + provisionDuration: 0, + spec, + }); + const ready = await harness.driver.makeReady(driverDevice, { + mode: specMode(spec), + purpose: "prepare", + }); + return harness.registry.transitionDevice( + provisioned.id, + "ready", + { event: "device.ready", payload: { bootDuration: 0, deviceId: provisioned.id } }, + readyTransitionUpdate(ready), + ); +} + +export async function flush(): Promise { + for (let count = 0; count < 50; count += 1) await Promise.resolve(); +} + +export async function settle(): Promise { + for (let count = 0; count < 20; count += 1) await new Promise((resolve) => setImmediate(resolve)); +} + +export async function seedShutdown( + harness: Awaited>, + spec: VirtualSpec = request, +) { + const ready = await seedReady(harness, spec); + await harness.driver.shutdown({ + address: ready.address ?? "", + deviceId: ready.driverDeviceId, + driverData: ready.driverData, + }); + return harness.registry.transitionDevice(ready.id, "shutdown", { + event: "device.shutdown", + payload: { deviceId: ready.id, initiator: "test" }, + }); +} + +export function installs(driver: FakeDriver): readonly unknown[] { + return driver.calls + .filter((call) => call.operation === "installComponent") + .map((call) => call.arguments[0]); +} diff --git a/src/source-hygiene.test.ts b/src/source-hygiene.test.ts index 9bd8e964d..a4aec0598 100644 --- a/src/source-hygiene.test.ts +++ b/src/source-hygiene.test.ts @@ -39,7 +39,6 @@ const SHRINK_ONLY: Record = { "src/gateway/fleet-coordinator.ts": 1659, "src/http/app.test.ts": 3488, "src/leasing/create-leasing.test.ts": 5276, - "src/leasing/lease-acquisition-coordinator.test.ts": 3691, "src/leasing/lease-acquisition-coordinator.ts": 1643, }; From 20a9a84e13853b62d1b2f31e65518acf93133bf4 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 5 Nov 2026 22:14:32 +0100 Subject: [PATCH 2/3] refactor(leasing): allow the shared lease-acquisition harness in the provision guard, and type a lifecycle Fallow cannot follow --- src/core/device-provisioner.test.ts | 4 ++++ src/leasing/lease-acquisition-coordinator.test.ts | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/core/device-provisioner.test.ts b/src/core/device-provisioner.test.ts index fe34b9543..9bbda6eb6 100644 --- a/src/core/device-provisioner.test.ts +++ b/src/core/device-provisioner.test.ts @@ -446,6 +446,8 @@ describe("DeviceProvisioner and a component removal (ADR 0010 §8)", () => { // doctor and registry tests split out of one file (ADR 0063). [join("core", "test-doctor.ts")]: 2, [join("core", "test-registry.ts")]: 1, + // why: the harness the lease-acquisition coordinator tests split out of one file share (ADR 0063). + [join("leasing", "test-lease-acquisition.ts")]: 1, }); expect(callSites(/\.provision\(/g)).toEqual({ // The driver call itself. @@ -458,6 +460,8 @@ describe("DeviceProvisioner and a component removal (ADR 0010 §8)", () => { // part, and its test helpers (never loaded in production) drive the driver to build fixtures. [join("drivers", "android", "index.ts")]: 1, [join("drivers", "android", "testing.ts")]: 2, + // why: the harness's fixture devices, as for registerDevice above. + [join("leasing", "test-lease-acquisition.ts")]: 1, }); }); diff --git a/src/leasing/lease-acquisition-coordinator.test.ts b/src/leasing/lease-acquisition-coordinator.test.ts index 0031391c6..8166b997c 100644 --- a/src/leasing/lease-acquisition-coordinator.test.ts +++ b/src/leasing/lease-acquisition-coordinator.test.ts @@ -10,6 +10,7 @@ import { type DeviceMode, type VirtualSpec, specMode, + type ManagedDeviceLifecycle, } from "../core/index.js"; import { FakeDriver } from "../core/testing.js"; import { NoCapacityError } from "./lease-acquisition-coordinator.js"; @@ -673,7 +674,8 @@ describe("LeaseAcquisitionCoordinator", () => { it("performs no provisioning for a waiter the queue times out during its eviction", async () => { let deadlineDue = false; const harness = await createHarness({ - lifecycle: (lifecycle) => ({ + // why: Fallow does not follow the type through the imported harness, and reports dispose unused. + lifecycle: (lifecycle: ManagedDeviceLifecycle) => ({ bootForLease: (...args) => lifecycle.bootForLease(...args), dispose: (...args) => { // why: an eviction is the waiter's own device work, so this is where a real one spends From c8f2da01168ca8f0e53ea366a22248ecef28098c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 5 Nov 2026 22:26:11 +0100 Subject: [PATCH 3/3] test(leasing): the resolution tests cite ADR 0063 for testing internals, and four lost reasons come back Co-Authored-By: Claude --- src/leasing/lease-acquisition-resolution.test.ts | 7 ++++++- src/leasing/test-lease-acquisition.ts | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/leasing/lease-acquisition-resolution.test.ts b/src/leasing/lease-acquisition-resolution.test.ts index 394b34407..fb97147e5 100644 --- a/src/leasing/lease-acquisition-resolution.test.ts +++ b/src/leasing/lease-acquisition-resolution.test.ts @@ -19,7 +19,8 @@ import { installs, } from "./test-lease-acquisition.js"; -// why: drives the coordinator on its own, so a test can order installs, catalog reads and the queue in ways the leasing surface cannot force. +// why: a test of the coordinator, a part of the decomposed leasing module (ADR 0063 §2), split +// from its own test file. describe("LeaseAcquisitionCoordinator: missing runtimes", () => { it("installs once for two lease requests for the same missing runtime, and grants both", async () => { const clock = new FakeClock(1_000); @@ -92,6 +93,7 @@ describe("LeaseAcquisitionCoordinator: missing runtimes", () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ availableOsVersions: [], clock, platform: "ios" }); const broken = new DriverCrashError("simctl list failed"); + // why: the first resolve finds the runtime missing; the check at the front of the queue breaks. driver.failOn("resolveSpec", 2, broken); driver.failOn("resolveSpec", 3, broken); const harness = await createHarness({ drivers: [driver] }); @@ -230,6 +232,7 @@ describe("LeaseAcquisitionCoordinator: download progress", () => { }); await flush(); + // why: the driver is still holding, so this is the replay, not a later report. expect(joined).toEqual([ { component: "26.5", percent: 41, stage: "downloading", waiting: false }, ]); @@ -336,6 +339,8 @@ describe("LeaseAcquisitionCoordinator: download progress", () => { ownerId: "a", requesterId: "a", }); + // why: no version: the fake names its word for newest, a different component that waits its + // turn and finds, at the front, that the first install made its runtime available. const newest = harness.coordinator.request( { model: "iPhone 16", platform: "ios" }, { diff --git a/src/leasing/test-lease-acquisition.ts b/src/leasing/test-lease-acquisition.ts index 180678309..37d9c6f35 100644 --- a/src/leasing/test-lease-acquisition.ts +++ b/src/leasing/test-lease-acquisition.ts @@ -146,6 +146,7 @@ export async function createHarness( catalog, claims, clock, + // why: never refuses: what a removal does to provisioning is `DeviceProvisioner`'s own test. components: { claimProvision: () => () => undefined }, decisions, lifecycle,