From 65cdd2dd3a9ffbcc9e68e5e99f39f789f1fb1dd5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:25:08 +0100 Subject: [PATCH 01/22] test: a client leases slim with except and is granted a device reporting it (#1330) --- src/contract/operations.ts | 9 ++++++++- src/contract/protocol.ts | 2 +- src/contract/schemas.ts | 9 +++++++++ src/daemon/dispatcher.test.ts | 18 ++++++++++++++++++ 4 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 1fbeb1f66..5680b46fb 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -158,6 +158,8 @@ const leaseRequestBaseSchema = z // before the handler, and its error would stand in for `BAD_REQUEST`. osVersion: z.string().optional(), mode: z.enum(["slim", "full"]).optional(), + // why: A plain array of plain strings, bounded by `refuseBadExcept` as the one object-level check, like `osVersion`: a bound on the field itself would be checked by the MCP SDK before the handler. + except: z.array(z.string()).optional(), imageTag: imageTagSchema.optional(), baseline: baselineNameSchema.optional(), physical: z.boolean().optional(), @@ -311,13 +313,18 @@ export const leaseRequest = defineOperation({ // `requesterId` (printable, at most 256 characters), and `owner` is gated by role in the handler (the resource does not exist yet). }); -export function requestedDevice(input: z.infer) { +export function requestedDevice( + input: Omit, "except"> & { + readonly except?: readonly string[] | undefined; + }, +) { return { ...(input.model === undefined ? {} : { model: input.model }), ...(input.class === undefined ? {} : { class: input.class }), platform: input.platform, ...(input.osVersion === undefined ? {} : { osVersion: input.osVersion }), ...(input.mode === undefined ? {} : { mode: input.mode }), + ...(input.except === undefined ? {} : { except: [...input.except] }), ...(input.imageTag === undefined ? {} : { imageTag: input.imageTag }), ...(input.baseline === undefined ? {} : { baseline: input.baseline }), ...(input.physical === true ? { physical: true as const } : {}), diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 06e238a12..7bc675633 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 77, max: 77 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 78, max: 78 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index e51848159..5cad6c1fb 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -34,6 +34,12 @@ const devicePresenceSchema = z.discriminatedUnion("present", [ const deviceModeSchema = z.enum(["slim", "full"]); +/** why: the category names a slim lease kept running (ADR 0066 §1); the same bounds as the request's `except`. */ +export const exceptCategoriesSchema = z + .array(z.string().regex(/^[a-z][a-z0-9-]{0,31}$/)) + .min(1) + .max(16); + const leaseIdentitySchema = z.enum(["reusable", "fresh"]); export const physicalClassSchema = z.enum(["phone", "tablet"]); @@ -258,6 +264,7 @@ export const deviceRecordSchema = z absentReason: absentReasonSchema.optional(), physical: z.boolean(), mode: deviceModeSchema.optional(), + except: exceptCategoriesSchema.optional(), class: physicalClassSchema.optional(), leaseIdentity: leaseIdentitySchema.optional(), transitionAgeMs: z.number().optional(), @@ -279,6 +286,7 @@ export const statusDeviceSchema = z state: deviceStateSchema, physical: z.boolean(), mode: deviceModeSchema.optional(), + except: exceptCategoriesSchema.optional(), class: physicalClassSchema.optional(), driverDeviceId: z.string().optional(), servesDefaultMode: z.boolean(), @@ -317,6 +325,7 @@ export const grantedDeviceSchema = z address: z.string().optional(), physical: z.boolean(), mode: deviceModeSchema.optional(), + except: exceptCategoriesSchema.optional(), class: physicalClassSchema.optional(), }) .superRefine((device, context) => checkDeviceType(device, context, false)); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index f2100e127..f701b558d 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -2867,6 +2867,24 @@ describe("Dispatcher: device mode on every surface", () => { }); }); + it("a client leases slim with except and is granted a device reporting it", async () => { + const { dispatcher, driver } = await buildDispatcher({ + driverOptions: { slimmableOsVersions: ["26.5"] }, + }); + const except = ["store", "other"]; + + const granted = await dispatcher.dispatch( + "lease.request", + { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios", mode: "slim", except }, + session(), + ); + + expect(granted.device).toMatchObject({ except, mode: "slim" }); + expect(driver.calls.find((call) => call.operation === "makeReady")?.arguments[1]).toMatchObject( + { except, mode: "slim", purpose: "prepare" }, + ); + }); + it("status.get and list.get return mode for every device, including one still provisioning", async () => { const { dispatcher, registry } = await buildDispatcher({ driverOptions: { mode: "slim" } }); const granted = await dispatcher.dispatch("lease.request", request, session()); From 1927c0247e34a58d58745eb52ed6a2165c6b974b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:26:56 +0100 Subject: [PATCH 02/22] feat(leasing): a slim lease with except boots the new device with it and the device reports it (#1330) --- src/core/device-provisioner.ts | 8 +++++++- src/core/domain.ts | 3 +++ src/core/fake-driver.ts | 6 +++++- src/core/managed-device-lifecycle.ts | 8 ++++++-- src/core/registry-rows.ts | 7 +++++++ src/core/registry-schema.ts | 8 ++++++-- src/core/registry.ts | 6 +++++- src/leasing/lease-acquisition-coordinator.ts | 8 ++++++++ src/leasing/lease-lifecycle.ts | 3 +++ 9 files changed, 50 insertions(+), 7 deletions(-) diff --git a/src/core/device-provisioner.ts b/src/core/device-provisioner.ts index dd85a6c5b..b79b153e3 100644 --- a/src/core/device-provisioner.ts +++ b/src/core/device-provisioner.ts @@ -49,6 +49,8 @@ export interface ProvisionDeviceOptions { * handoff, so a request planning in between sees a device that is on its way, and whose. */ readonly claim?: { readonly kind: "boot"; readonly owner?: string }; + /** why: the categories a slim lease keeps running, handed to the driver at the boot before the grant (ADR 0066 §2). */ + readonly except?: readonly string[]; readonly onProgress?: (progress: ProvisionProgress) => void; readonly reservation: CapacityReservation; } @@ -168,7 +170,11 @@ export class DeviceProvisioner { ): Promise { try { options.onProgress?.({ stage: "booting", etaMs: bootEstimate() }); - const ready = await this.options.lifecycle.readyProvisionedForLease(device, bootClaim); + const ready = await this.options.lifecycle.readyProvisionedForLease( + device, + bootClaim, + options.except, + ); if (ready === undefined) throw new Error(`Registered device could not be made ready: ${device.id}`); return ready; diff --git a/src/core/domain.ts b/src/core/domain.ts index fb8ab9065..8f88cd511 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -351,6 +351,8 @@ export interface VirtualDevice extends DeviceRecordFields { readonly spec: VirtualSpec; readonly state: VirtualState; readonly mode: DeviceMode; + /** why: the categories the lease this device serves kept running (ADR 0066 §4); written in the grant commit and never cleared, since a virtual device serves one lease. */ + readonly except?: readonly string[]; /** why: a record written before this field existed loads as `reusable`. */ readonly leaseIdentity?: LeaseIdentity; } @@ -364,6 +366,7 @@ export interface PhysicalDevice extends DeviceRecordFields { readonly reclaimingSince?: number; readonly absentReason?: AbsentReason; readonly mode?: undefined; + readonly except?: undefined; readonly leaseIdentity?: undefined; } diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index 1f5aa3a4a..29e8edbfa 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -492,7 +492,11 @@ export class FakeDriver implements Driver { async makeReady( device: DriverDevice, - options: { readonly purpose: "prepare" | "recover"; readonly mode: DeviceMode }, + options: { + readonly purpose: "prepare" | "recover"; + readonly mode: DeviceMode; + readonly except?: readonly string[]; + }, ): Promise { await this.#beforeCall("makeReady", device, options); this.#requireDevice(device); diff --git a/src/core/managed-device-lifecycle.ts b/src/core/managed-device-lifecycle.ts index a6e8460b8..3478e1277 100644 --- a/src/core/managed-device-lifecycle.ts +++ b/src/core/managed-device-lifecycle.ts @@ -71,8 +71,9 @@ export class ManagedDeviceLifecycle { async bootForLease( target: VirtualDevice, claim: DeviceOperationClaim, + except?: readonly string[], ): Promise { - return this.#makeReadyForLease(target, "shutdown", claim); + return this.#makeReadyForLease(target, "shutdown", claim, except); } /** @@ -95,8 +96,9 @@ export class ManagedDeviceLifecycle { async readyProvisionedForLease( target: VirtualDevice, claim?: DeviceOperationClaim, + except?: readonly string[], ): Promise { - return this.#makeReadyForLease(target, "provisioning", claim); + return this.#makeReadyForLease(target, "provisioning", claim, except); } async shutdown( @@ -231,6 +233,7 @@ export class ManagedDeviceLifecycle { target: VirtualDevice, expectedState: "provisioning" | "shutdown", existingClaim?: DeviceOperationClaim, + except?: readonly string[], ): Promise { const claimed = await this.#claim(target, [expectedState], "boot", existingClaim); if (claimed === undefined) return undefined; @@ -242,6 +245,7 @@ export class ManagedDeviceLifecycle { .makeReady(toDriverDevice(claimed.device), { mode: specMode(claimed.device.spec), purpose: "prepare", + ...(except === undefined ? {} : { except }), }); } catch (error: unknown) { await this.#release(claimed); diff --git a/src/core/registry-rows.ts b/src/core/registry-rows.ts index 604a32788..f344abd37 100644 --- a/src/core/registry-rows.ts +++ b/src/core/registry-rows.ts @@ -170,6 +170,7 @@ const DEVICE_COLUMNS = [ "absent_reason", "baseline_name", "baseline_version", + "except_categories", ] as const; const LEASE_COLUMNS = [ @@ -274,6 +275,7 @@ function deviceValues(device: DeviceRecord): SqliteValue[] { device.address ?? null, ...physicalColumns(device), ...baselineColumns(device), + device.except === undefined ? null : device.except.join(","), ]; } @@ -496,6 +498,7 @@ function deviceFromRow( ...shared, driverData: readDeviceData(database, deviceData, platform, id), ...present("leaseIdentity", reader.optOneOf("lease_identity", LEASE_IDENTITIES)), + ...present("except", exceptOf(reader)), mode: reader.oneOf("mode", DEVICE_MODES), physical: false, spec: { @@ -512,6 +515,10 @@ function deviceFromRow( return virtual; } +function exceptOf(reader: RowReader): readonly string[] | undefined { + return reader.optText("except_categories")?.split(","); +} + function baselineOf(reader: RowReader): { baseline?: { name: string; version: number } } { const name = reader.optText("baseline_name"); const version = reader.optInt("baseline_version"); diff --git a/src/core/registry-schema.ts b/src/core/registry-schema.ts index d3a6b15d4..381754674 100644 --- a/src/core/registry-schema.ts +++ b/src/core/registry-schema.ts @@ -124,8 +124,12 @@ const REGISTRY_V3 = ` ALTER TABLE lease_requests ADD COLUMN baseline TEXT; `; +const REGISTRY_V4 = ` +ALTER TABLE devices ADD COLUMN except_categories TEXT; +`; + export const registryOwner: SqliteSchemaOwner = { - migrations: [REGISTRY_V1, REGISTRY_V2, REGISTRY_V3], + migrations: [REGISTRY_V1, REGISTRY_V2, REGISTRY_V3, REGISTRY_V4], name: "registry", - version: 3, + version: 4, }; diff --git a/src/core/registry.ts b/src/core/registry.ts index db2ea06cd..9747f5361 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -114,6 +114,8 @@ export interface CreateLeaseInput { readonly ttlDeadline: number; /** why: the caller has already refused an ID that is in use: one place enforces that rule. */ readonly leaseId?: string; + /** why: the categories the lease keeps running, written to the device in the commit that leases it (ADR 0066 §4). */ + readonly except?: readonly string[]; /** * why: when given, the commit that adds the lease also marks the request `granted`, so no crash can * fall between the two. @@ -745,6 +747,7 @@ export class Registry implements LeaseRequestStore { ttlMs, ttlDeadline, leaseId, + except, request, }: CreateLeaseInput): Promise { const index = this.#devices.findIndex((device) => device.id === deviceId); @@ -760,7 +763,8 @@ export class Registry implements LeaseRequestStore { throw new RegistryEventError(`Device already has an active lease: ${deviceId}`); } - const leasedDevice = this.#transitioned(device, "leased"); + const leased = this.#transitioned(device, "leased"); + const leasedDevice = except === undefined || leased.physical ? leased : { ...leased, except }; const grantedAt = this.options.clock.now(); const lease: LeaseRecord = { deviceId, diff --git a/src/leasing/lease-acquisition-coordinator.ts b/src/leasing/lease-acquisition-coordinator.ts index b1a53ee29..330bc6d4f 100644 --- a/src/leasing/lease-acquisition-coordinator.ts +++ b/src/leasing/lease-acquisition-coordinator.ts @@ -967,6 +967,7 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { try { handoff = await this.options.provisioner.provision(spec, { claim: { kind: "boot", owner: waiter.id }, + ...exceptOption(waiter), onProgress: (progress) => this.options.queue.notifyProgress(waiter, progress), reservation, }); @@ -1110,6 +1111,7 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { requesterId: waiter.options.requesterId, source: GRANT_SOURCE[kind], timing: waiter.timing, + ...(device.mode === "slim" ? exceptOption(waiter) : {}), ...(waiter.options.ttlMs === undefined ? {} : { ttlMs: waiter.options.ttlMs }), ...(waiter.options.leaseId === undefined ? {} : { leaseId: waiter.options.leaseId }), ...(waiter.options.fleetRequestId === undefined @@ -1452,6 +1454,12 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { } } +/** why: a request's `except` reaches the driver and the device only when the resolved spec is slim; on a runtime that cannot be slimmed the lease is granted full with no `except` (ADR 0066 §1). */ +function exceptOption(waiter: AcquisitionWaiter): { readonly except?: readonly string[] } { + const except = waiter.request.except; + return except === undefined || waiter.spec?.mode !== "slim" ? {} : { except }; +} + function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); } diff --git a/src/leasing/lease-lifecycle.ts b/src/leasing/lease-lifecycle.ts index 42ad36301..33efca807 100644 --- a/src/leasing/lease-lifecycle.ts +++ b/src/leasing/lease-lifecycle.ts @@ -21,6 +21,7 @@ export interface LeaseLifecycleRegistry { readonly ttlMs: number; readonly ttlDeadline: number; readonly leaseId?: string; + readonly except?: readonly string[]; readonly request?: { readonly id: string; readonly environment: LeaseGrant["environment"]; @@ -78,6 +79,8 @@ export class LeaseLifecycle { /** ADR 0020: the lease ID the requester chose, when it did. The caller has already refused one * that is in use. */ readonly leaseId?: string; + /** why: the categories a slim lease keeps running, written to the device in the grant commit (ADR 0066 §4). */ + readonly except?: readonly string[]; /** ADR 0021: the gateway's request id, when the request is a gateway dispatch, carried on * `lease.granted`. */ readonly fleetRequestId?: string; From 11d612fcc85cbbed986f9b0aea24f8d3d28ad303 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:29:00 +0100 Subject: [PATCH 03/22] test: a client leases slim with except and a warm ready device is shut down and prepared with it (#1330) --- src/daemon/dispatcher.test.ts | 84 +++++++++++++++++++++++++++++++---- 1 file changed, 76 insertions(+), 8 deletions(-) diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index f701b558d..fb2e20483 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -4,6 +4,7 @@ import { capacityChangedPayload, FakeDriver, loadTestRegistry, + readyTransitionUpdate, openTestState, testComponentWiring, type FakeDriverOptions, @@ -2868,21 +2869,88 @@ describe("Dispatcher: device mode on every surface", () => { }); it("a client leases slim with except and is granted a device reporting it", async () => { - const { dispatcher, driver } = await buildDispatcher({ - driverOptions: { slimmableOsVersions: ["26.5"] }, - }); const except = ["store", "other"]; + const ask = { model: "iPhone 17 Pro", platform: "ios", mode: "slim", except } as const; - const granted = await dispatcher.dispatch( + const slimmed = await buildDispatcher({ driverOptions: { slimmableOsVersions: ["26.5"] } }); + const granted = await slimmed.dispatcher.dispatch( "lease.request", - { model: "iPhone 17 Pro", osVersion: "26.5", platform: "ios", mode: "slim", except }, + { ...ask, osVersion: "26.5" }, session(), ); - + const listed = await slimmed.dispatcher.dispatch( + "list.get", + { kind: "devices" }, + session({ role: "admin" }), + ); + const status = await slimmed.dispatcher.dispatch("status.get", {}, session()); expect(granted.device).toMatchObject({ except, mode: "slim" }); - expect(driver.calls.find((call) => call.operation === "makeReady")?.arguments[1]).toMatchObject( - { except, mode: "slim", purpose: "prepare" }, + expect( + slimmed.driver.calls.find((call) => call.operation === "makeReady")?.arguments[1], + ).toMatchObject({ except, mode: "slim", purpose: "prepare" }); + expect( + (listed as { id: string; except?: string[] }[]).find((d) => d.id === granted.device.id), + ).toMatchObject({ except }); + expect(status.devices?.find((d) => d.id === granted.device.id)).toMatchObject({ except }); + expect( + slimmed.eventBus.replay().find((event) => event.event === "lease.requested")?.payload, + ).toMatchObject({ requestSpec: { except } }); + + const warm = await buildDispatcher({ driverOptions: { slimmableOsVersions: ["26.5"] } }); + const spec = { + model: "iPhone 17 Pro", + osVersion: "26.5", + platform: "ios", + mode: "slim", + } as const; + const seeded = await warm.driver.provision({ ...spec, physical: false }); + const seededReady = await warm.driver.makeReady(seeded, { mode: "slim", purpose: "prepare" }); + const registered = await warm.registry.registerDevice({ + driverData: seeded.driverData, + driverDeviceId: seeded.deviceId, + provisionDuration: 0, + spec: { ...spec, physical: false }, + }); + await warm.registry.transitionDevice( + registered.id, + "ready", + { event: "device.ready", payload: { bootDuration: 0, deviceId: registered.id } }, + readyTransitionUpdate(seededReady), + ); + const seededCalls = warm.driver.calls.length; + const grantedWarm = await warm.dispatcher.dispatch( + "lease.request", + { ...ask, osVersion: "26.5" }, + session(), + ); + expect(grantedWarm.device).toMatchObject({ except, id: registered.id, mode: "slim" }); + expect( + warm.driver.calls + .slice(seededCalls) + .filter((call) => call.operation === "shutdown" || call.operation === "makeReady") + .map((call) => call.operation), + ).toEqual(["shutdown", "makeReady"]); + expect( + warm.driver.calls.slice(seededCalls).find((call) => call.operation === "makeReady") + ?.arguments[1], + ).toMatchObject({ except, mode: "slim", purpose: "prepare" }); + expect( + warm.eventBus.replay().find((event) => event.event === "lease.granted")?.payload, + ).toMatchObject({ source: "booted" }); + + const full = await buildDispatcher({ + driverOptions: { availableOsVersions: ["18.4", "26.5"], slimmableOsVersions: ["26.5"] }, + }); + const grantedFull = await full.dispatcher.dispatch( + "lease.request", + { ...ask, osVersion: "18.4" }, + session(), ); + expect(grantedFull.device.mode).toBe("full"); + expect(grantedFull.device).not.toHaveProperty("except"); + expect( + full.driver.calls.find((call) => call.operation === "makeReady")?.arguments[1], + ).not.toHaveProperty("except"); }); it("status.get and list.get return mode for every device, including one still provisioning", async () => { From 3445650652763008e616cf95d31d6670677542a7 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:31:08 +0100 Subject: [PATCH 04/22] feat(leasing): a ready warm device is rebooted with the except list and granted (#1330) --- src/core/managed-device-lifecycle.ts | 50 +++++++++++++++++++ src/core/registry.ts | 18 +++++++ src/leasing/acquisition-planner.ts | 17 ++++++- .../lease-acquisition-coordinator.test.ts | 3 ++ src/leasing/lease-acquisition-coordinator.ts | 34 ++++++++++++- 5 files changed, 119 insertions(+), 3 deletions(-) diff --git a/src/core/managed-device-lifecycle.ts b/src/core/managed-device-lifecycle.ts index 3478e1277..9dd9d5b0f 100644 --- a/src/core/managed-device-lifecycle.ts +++ b/src/core/managed-device-lifecycle.ts @@ -40,6 +40,10 @@ export interface ManagedDeviceRegistry { }, update?: DeviceTransitionUpdate, ): Promise; + recordRebootedDevice( + deviceId: string, + update: Required>, + ): Promise; } interface ClaimedDevice { @@ -92,6 +96,52 @@ export class ManagedDeviceLifecycle { return handoff.device; } + /** + * why: Shuts a ready device down and prepares it again with a lease's except list under the `boot` + * claim the caller took, and keeps the claim for the handoff. The record stays `ready` + * throughout, so capacity and the warm pool see no change; the new boot is recorded in one + * write with no transition and no event. `undefined` when the device is no longer a ready, + * unleased one. + */ + async rebootForLease( + target: VirtualDevice, + claim: DeviceOperationClaim, + except: readonly string[], + ): Promise { + const claimed = await this.#claim(target, ["ready"], "boot", claim); + if (claimed === undefined) return undefined; + const driver = this.catalog.get(claimed.device.spec.platform); + let ready: DriverDevice; + try { + await driver.shutdown(toDriverDevice(claimed.device)); + ready = await driver.makeReady(toDriverDevice(claimed.device), { + except, + mode: specMode(claimed.device.spec), + purpose: "prepare", + }); + } catch (error: unknown) { + await this.#release(claimed); + throw error; + } + const device = await this.decisions.run(async () => { + const current = this.#registeredTarget(claimed.device, ["ready"]); + if (current === undefined) return undefined; + // why: `mode` defaults to full here as `readyTransitionUpdate` does, so a reboot granted full records full. + return assertVirtual( + await this.registry.recordRebootedDevice(current.id, { + address: ready.address, + driverData: ready.driverData, + mode: ready.mode ?? "full", + }), + ); + }); + if (device === undefined) { + await this.#release(claimed); + return undefined; + } + return { claim: claimed.claim, device }; + } + /** Makes a provisioned device ready while retaining its claim for lease handoff. */ async readyProvisionedForLease( target: VirtualDevice, diff --git a/src/core/registry.ts b/src/core/registry.ts index 9747f5361..6ed071edd 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -296,6 +296,24 @@ export class Registry implements LeaseRequestStore { return this.#committed(deviceId); } + /** + * why: a ready device shut down and prepared again for a lease (ADR 0066 §2) keeps its state, so this is no transition and emits no event (`ready → ready` is no edge); it records only what the new boot produced. + */ + async recordRebootedDevice( + deviceId: string, + update: Required>, + ): Promise { + const { device, index } = this.#requireDeviceRecord(deviceId); + if (device.physical || device.state !== "ready") { + throw new RegistryEventError(`Only a ready virtual device can be rebooted: ${deviceId}`); + } + const updated = { ...device, ...update }; + const devices = [...this.#devices]; + devices[index] = updated; + this.#commit(devices, this.#leases); + return this.#committed(deviceId); + } + async completeReclaimWithoutPurge(deviceId: string): Promise { const { device, index } = this.#requireDeviceRecord(deviceId); if (device.state !== "reclaiming") { diff --git a/src/leasing/acquisition-planner.ts b/src/leasing/acquisition-planner.ts index bb93e2b69..c879de234 100644 --- a/src/leasing/acquisition-planner.ts +++ b/src/leasing/acquisition-planner.ts @@ -38,6 +38,8 @@ export interface AcquisitionPlannerInput { readonly snapshot: AcquisitionPlannerSnapshot; readonly spec: VirtualSpec; readonly requirement?: DeviceRequirement | undefined; + /** why: a slim request with an except list never takes a ready warm device as it is: the device is rebooted with the list first (ADR 0066 §2). */ + readonly rebootReady?: boolean | undefined; readonly classOf?: ((model: string) => DeviceClass | undefined) | undefined; } @@ -74,6 +76,11 @@ export function capacityReasonOf( export type AcquisitionPlan = | { readonly kind: "grant-ready"; readonly device: DeviceRecord } + | { + readonly kind: "reboot-ready"; + readonly claim: DeviceOperationClaim; + readonly device: VirtualDevice; + } | { readonly kind: "grant-physical"; readonly claim: DeviceOperationClaim; @@ -126,7 +133,7 @@ export class AcquisitionPlanner { const ready = snapshot.devices.find( (device) => device.state === "ready" && servesRequest(device), ); - if (ready !== undefined) return { device: ready, kind: "grant-ready" }; + if (ready !== undefined) return this.#planReady(input, ready); // A device the warm pool is booting for nobody in particular will serve this // request when it is ready: waiting for it costs less than starting a second. A device @@ -164,6 +171,14 @@ export class AcquisitionPlanner { return blocked(input.noWait, heldForOlder ? "behind-earlier-request" : "no-free-physical"); } + // why: no capacity reservation: the device keeps its running slot and RAM, because its record stays `ready` through the reboot. + #planReady(input: AcquisitionPlannerInput, ready: DeviceRecord): AcquisitionPlan { + if (input.rebootReady !== true || ready.physical) return { device: ready, kind: "grant-ready" }; + const claim = this.claims.tryClaim(ready.id, "boot", input.owner); + if (claim === undefined) return blocked(input.noWait, "waiting-for-device"); + return { claim, device: ready, kind: "reboot-ready" }; + } + #isOnItsWay(device: VirtualDevice, serves: (device: DeviceRecord) => boolean): boolean { if (device.state !== "provisioning" && device.state !== "shutdown") return false; const claim = this.claims.claim(device.id); diff --git a/src/leasing/lease-acquisition-coordinator.test.ts b/src/leasing/lease-acquisition-coordinator.test.ts index c2e8e2bda..13f484e09 100644 --- a/src/leasing/lease-acquisition-coordinator.test.ts +++ b/src/leasing/lease-acquisition-coordinator.test.ts @@ -1316,6 +1316,7 @@ describe("LeaseAcquisitionCoordinator", () => { const harness = await createHarness({ lifecycle: (lifecycle) => ({ bootForLease: (...args) => lifecycle.bootForLease(...args), + rebootForLease: (...args) => lifecycle.rebootForLease(...args), dispose: (...args) => { // why: an eviction is the waiter's own device work, so this is where a real one spends // the seconds its `timeoutMs` covers. The clock moves here to land the armed deadline @@ -1898,6 +1899,7 @@ describe("LeaseAcquisitionCoordinator", () => { const harness = await createHarness({ lifecycle: (lifecycle) => ({ bootForLease: (device, claim) => lifecycle.bootForLease(device, claim), + rebootForLease: (...args) => lifecycle.rebootForLease(...args), dispose: (...args) => lifecycle.dispose(...args), shutdown: (...args) => lifecycle.shutdown(...args), destroy: () => Promise.reject(new DriverCrashError("simulator would not delete")), @@ -1928,6 +1930,7 @@ describe("LeaseAcquisitionCoordinator", () => { maxRunning: 2, lifecycle: (lifecycle, { capacity, claims, registry }) => ({ bootForLease: (device, claim) => lifecycle.bootForLease(device, claim), + rebootForLease: (...args) => lifecycle.rebootForLease(...args), dispose: (...args) => lifecycle.dispose(...args), shutdown: (...args) => lifecycle.shutdown(...args), destroy: (device, initiator, operation, claim) => { diff --git a/src/leasing/lease-acquisition-coordinator.ts b/src/leasing/lease-acquisition-coordinator.ts index 330bc6d4f..c604ed2a3 100644 --- a/src/leasing/lease-acquisition-coordinator.ts +++ b/src/leasing/lease-acquisition-coordinator.ts @@ -176,7 +176,7 @@ export interface LeaseAcquisitionCoordinatorOptions { readonly leases: Pick; readonly lifecycle: Pick< ManagedDeviceLifecycle, - "bootForLease" | "destroy" | "dispose" | "shutdown" + "bootForLease" | "destroy" | "dispose" | "rebootForLease" | "shutdown" >; /** * The model names to try for each class, per platform, operator's list first (ADR 0015 §4), @@ -201,13 +201,19 @@ interface AcquisitionWaiter extends Waiter { timing: LeaseTiming; } -type GrantingPlanKind = "grant-ready" | "grant-physical" | "boot-shutdown" | "provision"; +type GrantingPlanKind = + | "grant-ready" + | "grant-physical" + | "boot-shutdown" + | "reboot-ready" + | "provision"; const GRANT_SOURCE: Readonly> = { "boot-shutdown": "booted", "grant-physical": "warm", "grant-ready": "warm", provision: "provisioned", + "reboot-ready": "booted", }; type OperationPlan = Exclude< @@ -950,6 +956,14 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { await this.#bootShutdown(waiter, action.device, action.capacityReservation, action.claim); return; } + if (action.kind === "reboot-ready") { + waiter.timing = await estimatedBootTiming( + this.options.drivers.get(action.device.spec.platform), + action.device, + ); + await this.#rebootReady(waiter, action.device, action.claim); + return; + } if (action.kind === "evict-running") { await this.#evictRunning(waiter, action.device, action.claim, action.reason); return; @@ -1082,6 +1096,7 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { spec: waiter.spec, requirement: waiter.requirement, classOf: waiter.classOf, + rebootReady: exceptOption(waiter).except !== undefined, }); } @@ -1207,6 +1222,21 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { }); } + async #rebootReady( + waiter: AcquisitionWaiter, + device: VirtualDevice, + claim: DeviceOperationClaim, + ): Promise { + this.options.queue.notifyProgress(waiter, { + stage: "booting", + etaMs: waiter.timing.estimatedBootMs, + }); + const except = exceptOption(waiter).except ?? []; + const ready = await this.options.lifecycle.rebootForLease(device, claim, except); + if (ready === undefined) throw new Error(`Reboot target is no longer safe: ${device.id}`); + await this.#grantHandoff(waiter, ready, "reboot-ready"); + } + async #bootShutdown( waiter: AcquisitionWaiter, device: VirtualDevice, From 270f5297ebb207f105cb2c72b077022a0954273a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:32:16 +0100 Subject: [PATCH 05/22] test: a client's except request is refused with BAD_REQUEST and the reason (#1330) --- src/core/fake-driver.ts | 2 + src/daemon/dispatcher.test.ts | 85 +++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index 29e8edbfa..e8111a2bc 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -98,6 +98,8 @@ export interface FakeDriverOptions { readonly fullCleanReclaimEstimateMs?: number; readonly mode?: DeviceMode | undefined; readonly slimmableOsVersions?: readonly string[]; + /** why: the categories this worker slims; a request's `except` naming another is refused at resolve, as the iOS driver does. Absent: every name is accepted. */ + readonly slimCategories?: readonly string[]; readonly knownModels?: readonly string[]; readonly modelRuntimes?: Readonly>; readonly modelAliases?: Readonly>; diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index fb2e20483..54fc3ebdf 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -2953,6 +2953,91 @@ describe("Dispatcher: device mode on every surface", () => { ).not.toHaveProperty("except"); }); + it("a client's except request is refused with BAD_REQUEST and the reason, and a slim baseline on a full-default worker is granted", async () => { + const ask = { + except: ["store"], + mode: "slim", + model: "iPhone 17 Pro", + osVersion: "26.5", + platform: "ios", + } as const; + const { mode: _mode, ...noMode } = ask; + const driverOptions = { slimCategories: ["store", "other"], slimmableOsVersions: ["26.5"] }; + const attempt = async (input: unknown, defaultMode: "slim" | "full" = "slim") => { + const built = await buildDispatcher({ + driverOptions, + engine: { defaultModes: { ios: defaultMode } }, + }); + return built.dispatcher.dispatch("lease.request", input as never, session()).then( + () => undefined, + (error: unknown) => error, + ); + }; + + expect(await attempt(ask)).toBeUndefined(); + const refusals: readonly [string, unknown, string, ("slim" | "full")?][] = [ + ["duplicate", { ...ask, except: ["store", "store"] }, 'except names "store" twice'], + ["bad characters", { ...ask, except: ["Store"] }, 'except: "Store" is not a category name'], + ["none named", { ...ask, except: [] }, "except names 1 to 16 categories"], + [ + "too many", + { ...ask, except: Array.from({ length: 17 }, (_, index) => `c${index}`) }, + "except names 1 to 16 categories", + ], + ["mode full", { ...ask, mode: "full" }, "except needs a slim lease (mode is full)"], + [ + "default full", + noMode, + "except needs a slim lease (this worker's default mode is full)", + "full", + ], + ["physical", { ...ask, physical: true }, "except is for iOS simulators"], + ["android", { ...ask, platform: "android" }, "except is for iOS simulators"], + ["a name the driver refuses", { ...ask, except: ["wallet"] }, ""], + ]; + for (const [label, input, message, defaultMode] of refusals) { + const error = await attempt(input, defaultMode); + expect(classifyError(error), label).toBe("BAD_REQUEST"); + expect((error as Error).message, label).toContain(message); + } + + const { dispatcher } = await buildDispatcher({ + driverOptions, + engine: { defaultModes: { ios: "full" } }, + }); + const save = async (name: string, mode: "slim" | "full", principal: string) => { + const lease = await dispatcher.dispatch( + "lease.request", + { model: "iPhone 17 Pro", mode, osVersion: "26.5", platform: "ios" }, + session({ principal }), + ); + await dispatcher.dispatch( + "baseline.save", + { leaseId: lease.lease.id, name }, + session({ principal, role: "admin" }), + ); + }; + await save("slim-base", "slim", "tok_a"); + await save("full-base", "full", "tok_b"); + const fromFull = await dispatcher + .dispatch( + "lease.request", + { baseline: "full-base", except: ["store"], platform: "ios" }, + session({ principal: "tok_c" }), + ) + .catch((error: unknown) => error); + expect(classifyError(fromFull)).toBe("BAD_REQUEST"); + expect((fromFull as Error).message).toContain( + 'except needs a slim lease (baseline "full-base" is full)', + ); + const fromSlim = await dispatcher.dispatch( + "lease.request", + { baseline: "slim-base", except: ["store"], platform: "ios" }, + session({ principal: "tok_d" }), + ); + expect(fromSlim.device).toMatchObject({ except: ["store"], mode: "slim" }); + }); + it("status.get and list.get return mode for every device, including one still provisioning", async () => { const { dispatcher, registry } = await buildDispatcher({ driverOptions: { mode: "slim" } }); const granted = await dispatcher.dispatch("lease.request", request, session()); From 4f938049e69431e4b1a074f856992e16eb4bbd8f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:33:58 +0100 Subject: [PATCH 06/22] feat(leasing): an except request is refused unless it is a slim iOS simulator lease (#1330) --- src/contract/operations.ts | 43 ++++++++++++++++++++ src/contract/schemas.ts | 6 ++- src/core/fake-driver.ts | 8 ++++ src/leasing/lease-acquisition-coordinator.ts | 9 ++++ 4 files changed, 64 insertions(+), 2 deletions(-) diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 5680b46fb..4dbbeecce 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -25,6 +25,8 @@ import { doctorReportSchema, eventEnvelopeSchema, EVENT_ID_PATTERN, + EXCEPT_MAX_NAMES, + EXCEPT_NAME_PATTERN, hostFactsSchema, requesterIdSchema, historyStatusSchema, @@ -265,6 +267,46 @@ function refuseRequiresWithIdempotencyKey(): < }; } +/** why: one object-level check with no path (like `osVersion`), so every transport, MCP included, answers `BAD_REQUEST` with the message as written. */ +function refuseBadExcept(): < + T extends { + readonly except?: readonly string[] | undefined; + readonly mode?: unknown; + readonly physical?: boolean | undefined; + readonly platform: string; + }, +>( + input: T, + context: z.RefinementCtx, +) => void { + return (input, context) => { + const { except } = input; + if (except === undefined) return; + const message = exceptRefusal(input, except); + if (message !== undefined) context.addIssue({ code: "custom", message }); + }; +} + +function exceptRefusal( + input: { + readonly mode?: unknown; + readonly physical?: boolean | undefined; + readonly platform: string; + }, + except: readonly string[], +): string | undefined { + if (except.length < 1 || except.length > EXCEPT_MAX_NAMES) { + return `except names 1 to ${EXCEPT_MAX_NAMES} categories`; + } + const bad = except.find((name) => !EXCEPT_NAME_PATTERN.test(name)); + if (bad !== undefined) return `except: "${bad}" is not a category name`; + const twice = except.find((name, index) => except.indexOf(name) !== index); + if (twice !== undefined) return `except names "${twice}" twice`; + if (input.physical === true || input.platform !== "ios") return "except is for iOS simulators"; + if (input.mode === "full") return "except needs a slim lease (mode is full)"; + return undefined; +} + function refuseBadOsVersion(): ( input: T, context: z.RefinementCtx, @@ -299,6 +341,7 @@ const leaseRequestInputSchema = leaseRequestBaseSchema .superRefine(refuseModelWithClass()) .superRefine(refuseBaselineWithClass()) .superRefine(refuseBadOsVersion()) + .superRefine(refuseBadExcept()) .superRefine(refusePhysicalWithImageFields()) .superRefine(refuseRequiresWithIdempotencyKey()); diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 5cad6c1fb..c91c9a6fa 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -35,10 +35,12 @@ const devicePresenceSchema = z.discriminatedUnion("present", [ const deviceModeSchema = z.enum(["slim", "full"]); /** why: the category names a slim lease kept running (ADR 0066 §1); the same bounds as the request's `except`. */ +export const EXCEPT_NAME_PATTERN = /^[a-z][a-z0-9-]{0,31}$/; +export const EXCEPT_MAX_NAMES = 16; export const exceptCategoriesSchema = z - .array(z.string().regex(/^[a-z][a-z0-9-]{0,31}$/)) + .array(z.string().regex(EXCEPT_NAME_PATTERN)) .min(1) - .max(16); + .max(EXCEPT_MAX_NAMES); const leaseIdentitySchema = z.enum(["reusable", "fresh"]); diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index e8111a2bc..9e47daeb9 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -37,6 +37,7 @@ import { type PresentPhysical, type ReclaimResult, removeListedComponent, + BadDeviceRequestError, RuntimeMissingError, UnknownModelError, uninstallPlan, @@ -162,6 +163,7 @@ export class FakeDriver implements Driver { readonly #estimateMs: FakeDriverOptions["estimateMs"]; readonly #mode: DeviceMode | undefined; readonly #slimmableOsVersions: ReadonlySet; + readonly #slimCategories: ReadonlySet | undefined; readonly #fullCleanReclaimEstimateMs: number | undefined; readonly #failures = new Map(); #hangMakeReady = false; @@ -206,6 +208,8 @@ export class FakeDriver implements Driver { this.#estimateMs = options.estimateMs; this.#mode = options.mode; this.#slimmableOsVersions = new Set(options.slimmableOsVersions ?? []); + this.#slimCategories = + options.slimCategories === undefined ? undefined : new Set(options.slimCategories); this.#fullCleanReclaimEstimateMs = options.fullCleanReclaimEstimateMs; this.#knownModels = options.knownModels === undefined ? undefined : new Set(options.knownModels); @@ -264,6 +268,10 @@ export class FakeDriver implements Driver { if (this.#knownModels !== undefined && !this.#knownModels.has(request.model)) { throw new UnknownModelError(this.platform, request.model); } + const unknownCategory = request.except?.find((name) => !this.#slimCategories?.has(name)); + if (this.#slimCategories !== undefined && unknownCategory !== undefined) { + throw new BadDeviceRequestError(`unknown slim category "${unknownCategory}"`); + } const osVersion = request.imageTag === undefined diff --git a/src/leasing/lease-acquisition-coordinator.ts b/src/leasing/lease-acquisition-coordinator.ts index c604ed2a3..6324ab715 100644 --- a/src/leasing/lease-acquisition-coordinator.ts +++ b/src/leasing/lease-acquisition-coordinator.ts @@ -55,6 +55,7 @@ import { type CurrentBaseline, UnknownBaselineError, BaselineMismatchError, + BadDeviceRequestError, BaselineStaleError, baselineMismatch, type AcquisitionMaintenance, @@ -552,6 +553,11 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { if (request.baseline !== undefined) return this.#resolveBaseline(request.baseline, request); // The one place a request with no mode gets the worker's default (ADR 0007 §2). const mode = request.mode ?? this.defaultMode(request.platform); + if (request.except !== undefined && mode !== "slim") { + throw new BadDeviceRequestError( + "except needs a slim lease (this worker's default mode is full)", + ); + } const range = requestedRange(request); const target = range === undefined @@ -588,6 +594,9 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { } if (current.staleReason !== undefined) throw new BaselineStaleError(name, current.staleReason); const spec = baselineSpec(current); + if (request.except !== undefined && spec.mode !== "slim") { + throw new BadDeviceRequestError(`except needs a slim lease (baseline "${name}" is full)`); + } return { classOf: undefined, requirement: exactRequirement(spec), spec }; } From 97478a9bc64d28d43b2ebeeec2e1e3bc4e930cae Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:36:07 +0100 Subject: [PATCH 07/22] test: an except list reaches the lease request from the CLI and HTTP, and the HTTP lease reports it (#1330) --- src/cli/index.test.ts | 10 +++++++++- src/http/app.test.ts | 1 + src/http/tracker.test.ts | 16 ++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index ca991a17a..8615f0e29 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -6761,6 +6761,14 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( flagArgs: ["--image-tag", "google_apis_playstore"], envOverride: () => ({}), }, + { + flag: "--except", + field: "except", + value: ["store", "other"], + lease: ["lease", "--platform", "ios", "--mode", "slim", "--detach"], + flagArgs: ["--except", "store,other"], + envOverride: () => ({}), + }, { flag: "--baseline", field: "baseline", @@ -9809,7 +9817,7 @@ describe("simlock lease: a request names a model, a class, or nothing", () => { expect(output.stdout).toBe( "Usage: simlock lease --platform [--device | --class ]\n" + " [--os ] [--mode ] [--image-tag ] [--agent-id ]\n" + - " [--baseline ]\n" + + " [--except ] [--baseline ]\n" + " [--timeout ] [--lease-id ] [--physical]\n" + " [--no-wait] [--detach] [--ttl ] [--allow-download]\n" + " [--export-env] [--bind-pid ]\n", diff --git a/src/http/app.test.ts b/src/http/app.test.ts index df71e9ecc..3ac118194 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -829,6 +829,7 @@ describe("POST /v1/lease-requests", () => { it.each<[string, Record, Record?]>([ ["imageTag", { imageTag: "google_apis_playstore" }], ["mode", { mode: "slim" }], + ["except", { except: ["store", "other"] }], ["baseline", { baseline: "checkout" }], ["owner field rather than silently dropping it (ADR §27a, H7)", { owner: "someone-else" }], ["physical true", { physical: true }], diff --git a/src/http/tracker.test.ts b/src/http/tracker.test.ts index f21ed9d2a..b4a7cf11e 100644 --- a/src/http/tracker.test.ts +++ b/src/http/tracker.test.ts @@ -33,6 +33,7 @@ async function createTracked( readonly platform: "ios" | "android"; readonly ttlMs?: number; readonly mode?: "slim" | "full"; + readonly except?: readonly string[]; readonly imageTag?: string; readonly baseline?: string; readonly physical?: boolean; @@ -319,6 +320,7 @@ describe("LeaseRequestTracker.submit with allowDownload on a gateway", () => { describe("LeaseRequestTracker.submit with an optional request field", () => { it.each([ ["mode", { mode: "slim" }], + ["except", { except: ["store", "other"] }], ["imageTag", { imageTag: "google_apis_playstore" }], ["baseline", { baseline: "checkout" }], ["physical", { physical: true }], @@ -348,11 +350,25 @@ describe("LeaseRequestTracker granted lease payload", () => { const state = tracker.get(view.id)?.state; if (state?.stage !== "granted") throw new Error("expected granted"); expect(state.lease.mode).toBe(mode); + expect(state.lease).not.toHaveProperty("except"); expect(state.lease).not.toHaveProperty("slim"); expect(state.lease).not.toHaveProperty("featureProfile"); }, ); + it("reports the granted device's except list beside its mode", async () => { + const { dispatcher, tracker } = buildTracker(); + const { view, callIndex } = await createTracked(tracker, dispatcher); + dispatcher.calls[callIndex]?.resolve( + makeGrant({ device: { except: ["store", "other"], mode: "slim" } }), + ); + await Promise.resolve(); + await Promise.resolve(); + const state = tracker.get(view.id)?.state; + if (state?.stage !== "granted") throw new Error("expected granted"); + expect(state.lease).toMatchObject({ except: ["store", "other"], mode: "slim" }); + }); + it("leaves mode off the lease for a granted physical device, which has none", async () => { const { dispatcher, tracker } = buildTracker(); const { view, callIndex } = await createTracked(tracker, dispatcher); From 966444803e9fcc1fa4c992f5ff61d873f84a193b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:37:35 +0100 Subject: [PATCH 08/22] feat(cli): simlock lease --except, the HTTP body and lease reply carry it, the MCP tool describes it (#1330) --- src/cli/commands/lease.ts | 4 +++- src/cli/index.test.ts | 2 +- src/http/app.ts | 1 + src/http/lease-declarations.ts | 4 ++++ src/http/tracker.ts | 5 +++++ src/mcp/server.ts | 2 +- 6 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/cli/commands/lease.ts b/src/cli/commands/lease.ts index 3bf7040f6..e0026477e 100644 --- a/src/cli/commands/lease.ts +++ b/src/cli/commands/lease.ts @@ -49,6 +49,7 @@ async function runLease( detach: { type: "boolean" }, device: { type: "string" }, "export-env": { type: "boolean" }, + except: { type: "string" }, help: { type: "boolean", short: "h" }, "image-tag": { type: "string" }, "lease-id": { type: "string" }, @@ -64,7 +65,7 @@ async function runLease( environment.stdout.write( "Usage: simlock lease --platform [--device | --class ]\n" + " [--os ] [--mode ] [--image-tag ] [--agent-id ]\n" + - " [--baseline ]\n" + + " [--except ] [--baseline ]\n" + " [--timeout ] [--lease-id ] [--physical]\n" + " [--no-wait] [--detach] [--ttl ] [--allow-download]\n" + " [--export-env] [--bind-pid ]\n", @@ -202,6 +203,7 @@ async function runLease( ...(values.physical === true ? { physical: true } : {}), platform, ...(typeof values.mode === "string" ? { mode: values.mode as "slim" | "full" } : {}), + ...(typeof values.except === "string" ? { except: values.except.split(",") } : {}), ...(typeof values["image-tag"] === "string" ? { imageTag: values["image-tag"] } : {}), ...(baseline === undefined ? {} : { baseline }), ...(typeof values["lease-id"] === "string" ? { leaseId: values["lease-id"] } : {}), diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 8615f0e29..629dd450e 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -6858,7 +6858,7 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( ); await runCli(lease, outputCapture().environmentWith({ connectAdmin: async () => client })); - expect(inputs[0]?.[field]).toBe(value); + expect(inputs[0]?.[field]).toEqual(value); expect(inputs[1]).not.toHaveProperty(field); }, ); diff --git a/src/http/app.ts b/src/http/app.ts index 9053693cf..a05843bc9 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -188,6 +188,7 @@ function leaseRequestOptionFields(body: z.infer) ...(body.noWait === undefined ? {} : { noWait: body.noWait }), ...(body.allowDownload === undefined ? {} : { allowDownload: body.allowDownload }), ...(body.mode === undefined ? {} : { mode: body.mode }), + ...(body.except === undefined ? {} : { except: body.except }), ...(body.physical === undefined ? {} : { physical: body.physical }), ...leaseRequestImageFields(body), }; diff --git a/src/http/lease-declarations.ts b/src/http/lease-declarations.ts index 4f0fcfaa6..19014dab2 100644 --- a/src/http/lease-declarations.ts +++ b/src/http/lease-declarations.ts @@ -5,6 +5,7 @@ import { deviceRecordSchema, baselineNameSchema, imageTagSchema, + exceptCategoriesSchema, EXEC_STDIN_MAX_LENGTH, INPUT_ORIENTATIONS, leaseIdSchema, @@ -29,6 +30,7 @@ const leasePayloadSchema = z.object({ baseline: z.object({ name: z.string(), version: z.number().int() }).optional(), imageTag: z.string().optional(), mode: z.enum(["slim", "full"]).optional(), + except: exceptCategoriesSchema.optional(), os: z.string(), platform: z.string(), requestId: z.string().optional(), @@ -205,6 +207,8 @@ export const leaseRequestBodySchema = z imageTag: imageTagSchema.optional(), leaseId: leaseIdSchema.optional(), mode: z.enum(["slim", "full"]).optional(), + // why: a coarse bound only; `lease.request`'s own check words the refusal (count, characters, repeats), as for the CLI and MCP. + except: z.array(z.string().max(64)).max(64).optional(), noWait: z.boolean().optional(), // why: forwarded, not dropped: the dispatcher's `lease.request` handler alone decides whether this token may set it. owner: z.string().min(1).optional(), diff --git a/src/http/tracker.ts b/src/http/tracker.ts index f4ba09280..ebc2275b6 100644 --- a/src/http/tracker.ts +++ b/src/http/tracker.ts @@ -16,6 +16,7 @@ export interface LeaseRequestInput { readonly noWait?: boolean; readonly allowDownload?: boolean; readonly mode?: "slim" | "full"; + readonly except?: readonly string[]; readonly imageTag?: string; readonly baseline?: string; readonly physical?: boolean; @@ -80,6 +81,7 @@ export function buildLeasePayload( ttlMs: lease.ttlMs, dataPlane: null, ...(device.mode === undefined ? {} : { mode: device.mode }), + ...(device.except === undefined ? {} : { except: device.except }), ...(device.spec.imageTag === undefined ? {} : { imageTag: device.spec.imageTag }), ...(device.spec.baseline === undefined ? {} : { baseline: device.spec.baseline }), // `workerId` derives from `worker` so the two never disagree. @@ -94,6 +96,7 @@ function leaseRequestDispatchInput(body: LeaseRequestInput, idempotencyKey: stri platform: body.platform, ...(body.os === undefined ? {} : { osVersion: body.os }), ...(body.mode === undefined ? {} : { mode: body.mode }), + ...(body.except === undefined ? {} : { except: body.except }), ...(body.imageTag === undefined ? {} : { imageTag: body.imageTag }), ...(body.baseline === undefined ? {} : { baseline: body.baseline }), ...(body.physical === undefined ? {} : { physical: body.physical }), @@ -395,6 +398,8 @@ export interface HttpLeaseDevice { }; /** Absent only for a physical device, which has no mode. */ readonly mode?: "slim" | "full" | undefined; + /** why: absent when the lease keeps no category running. */ + readonly except?: readonly string[] | undefined; } interface HttpLeaseRecord { diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 81162d492..85937c786 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -206,7 +206,7 @@ export function createMcpServer( { title: "Lease simulator", description: - "Lease one simulator or emulator for this MCP session. Name an exact model (`model`), or a device class (`class`: phone, tablet, watch, tv, vision, auto or desktop), or name neither to get a phone; naming both is an error. A class or no-model request is served by a fitting idle device before a new one is created. The lease is held until released or this MCP connection closes; provisioning can block unless noWait is true. `osVersion` is an exact version (`18.4`) or a range: `>=`, `>`, `<=` or `<` followed by a version, joined by single spaces (`>=18 <26`), or a hyphen range (`18 - 26`); a range is served by a fitting device or the newest installed runtime in it, and never downloads. Downloads are disabled by default and require allowDownload: true. On Android, imageTag picks the system image type (a tag from list_devices' images, such as google_apis_playstore); a request with imageTag uses only an installed image and never downloads. Pass `baseline` (a name the operator saved) to get a new copy of that baseline, with the operator's apps, files and settings; it must match any `model`, `osVersion`, `mode` or `imageTag` you also pass (BASELINE_MISMATCH otherwise), cannot be combined with `class`, and fails at once as UNKNOWN_BASELINE or BASELINE_STALE when the baseline is missing or unusable. Pass `leaseId` to choose the lease's ID instead of getting one generated: 1 to 64 ASCII letters, digits, `-` or `_`, starting with a letter or digit; you keep it unique for all time, and an ID that an active lease or a waiting request already holds is refused with LEASE_ID_TAKEN.", + "Lease one simulator or emulator for this MCP session. Name an exact model (`model`), or a device class (`class`: phone, tablet, watch, tv, vision, auto or desktop), or name neither to get a phone; naming both is an error. A class or no-model request is served by a fitting idle device before a new one is created. The lease is held until released or this MCP connection closes; provisioning can block unless noWait is true. `osVersion` is an exact version (`18.4`) or a range: `>=`, `>`, `<=` or `<` followed by a version, joined by single spaces (`>=18 <26`), or a hyphen range (`18 - 26`); a range is served by a fitting device or the newest installed runtime in it, and never downloads. Downloads are disabled by default and require allowDownload: true. On Android, imageTag picks the system image type (a tag from list_devices' images, such as google_apis_playstore); a request with imageTag uses only an installed image and never downloads. Pass `baseline` (a name the operator saved) to get a new copy of that baseline, with the operator's apps, files and settings; it must match any `model`, `osVersion`, `mode` or `imageTag` you also pass (BASELINE_MISMATCH otherwise), cannot be combined with `class`, and fails at once as UNKNOWN_BASELINE or BASELINE_STALE when the baseline is missing or unusable. On iOS, `except` (1 to 16 category names, such as `store`) with `mode` slim keeps those categories running on the slim simulator; it needs a slim lease (BAD_REQUEST on `mode` full, a full default or a full baseline, and for a physical or Android request), and the leased device reports it as `except`. Pass `leaseId` to choose the lease's ID instead of getting one generated: 1 to 64 ASCII letters, digits, `-` or `_`, starting with a letter or digit; you keep it unique for all time, and an ID that an active lease or a waiting request already holds is refused with LEASE_ID_TAKEN.", inputSchema: leaseSimulatorInputSchema, outputSchema: leaseSimulatorOutputSchema, }, From cf05d712a40dea55366d8bcdb04e659c69a1a815 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:39:40 +0100 Subject: [PATCH 09/22] test: a failed except boot is never granted (#1330) --- src/daemon/dispatcher.test.ts | 133 ++++++++++++++++++++++++++++------ 1 file changed, 112 insertions(+), 21 deletions(-) diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 54fc3ebdf..ee2d375ef 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -65,7 +65,7 @@ import { openMemoryStateDatabase } from "../auth/testing.js"; import type { DispatcherOptions, DispatchSession } from "./dispatcher.js"; import { Dispatcher, DispatchError } from "./dispatcher.js"; import { classifyError } from "./error-code.js"; -import { UnknownLeaseError } from "../core/index.js"; +import { DriverCrashError, UnknownLeaseError } from "../core/index.js"; import { RequestCancelledError } from "../leasing/index.js"; import { createTestEngine, type TestEngine } from "../leasing/testing.js"; @@ -421,6 +421,52 @@ async function buildDispatcher( }; } +/** why: the answer of a request that must settle by itself once the event loop has run to rest; a hang fails here, on a named assertion, rather than by the test's timeout. */ +async function grantedOnceSettled(request: Promise): Promise { + const rest = (async () => { + for (let turn = 0; turn < 50; turn += 1) await new Promise((resolve) => setImmediate(resolve)); + return undefined; + })(); + const answer = await Promise.race([request, rest]); + expect(answer, "the request settled").toBeDefined(); + return answer as T; +} + +/** why: a slim device a worker already holds, ready or shut down, as the warm pool or an earlier lease leaves one. */ +async function seedSlimDevice( + built: Awaited>, + state: "ready" | "shutdown", +) { + const spec = { + mode: "slim", + model: "iPhone 17 Pro", + osVersion: "26.5", + physical: false, + platform: "ios", + } as const; + const driverDevice = await built.driver.provision(spec); + const ready = await built.driver.makeReady(driverDevice, { mode: "slim", purpose: "prepare" }); + const registered = await built.registry.registerDevice({ + driverData: driverDevice.driverData, + driverDeviceId: driverDevice.deviceId, + provisionDuration: 0, + spec, + }); + await built.registry.transitionDevice( + registered.id, + "ready", + { event: "device.ready", payload: { bootDuration: 0, deviceId: registered.id } }, + readyTransitionUpdate(ready), + ); + if (state === "ready") return registered; + await built.driver.shutdown(driverDevice); + await built.registry.transitionDevice(registered.id, "shutdown", { + event: "device.shutdown", + payload: { deviceId: registered.id, initiator: "test" }, + }); + return registered; +} + function session(overrides: Partial = {}): DispatchSession { return { manageEventSubscription: () => undefined, @@ -2897,26 +2943,7 @@ describe("Dispatcher: device mode on every surface", () => { ).toMatchObject({ requestSpec: { except } }); const warm = await buildDispatcher({ driverOptions: { slimmableOsVersions: ["26.5"] } }); - const spec = { - model: "iPhone 17 Pro", - osVersion: "26.5", - platform: "ios", - mode: "slim", - } as const; - const seeded = await warm.driver.provision({ ...spec, physical: false }); - const seededReady = await warm.driver.makeReady(seeded, { mode: "slim", purpose: "prepare" }); - const registered = await warm.registry.registerDevice({ - driverData: seeded.driverData, - driverDeviceId: seeded.deviceId, - provisionDuration: 0, - spec: { ...spec, physical: false }, - }); - await warm.registry.transitionDevice( - registered.id, - "ready", - { event: "device.ready", payload: { bootDuration: 0, deviceId: registered.id } }, - readyTransitionUpdate(seededReady), - ); + const registered = await seedSlimDevice(warm, "ready"); const seededCalls = warm.driver.calls.length; const grantedWarm = await warm.dispatcher.dispatch( "lease.request", @@ -3038,6 +3065,70 @@ describe("Dispatcher: device mode on every surface", () => { expect(fromSlim.device).toMatchObject({ except: ["store"], mode: "slim" }); }); + it("a failed except boot is never granted", async () => { + const ask = { + except: ["store"], + mode: "slim", + model: "iPhone 17 Pro", + osVersion: "26.5", + platform: "ios", + } as const; + const crash = new DriverCrashError("simulator never booted"); + const build = () => buildDispatcher({ driverOptions: { slimmableOsVersions: ["26.5"] } }); + + const prepareFails = await build(); + const seededPrepare = await seedSlimDevice(prepareFails, "ready"); + // why: call 1 of makeReady is the seed's own boot; the reboot is call 2. + prepareFails.driver.failOn("makeReady", 2, crash); + const afterPrepare = await grantedOnceSettled( + prepareFails.dispatcher.dispatch("lease.request", ask, session()), + ); + expect(afterPrepare.device.id).not.toBe(seededPrepare.id); + expect(afterPrepare.device).toMatchObject({ except: ask.except, mode: "slim" }); + expect( + prepareFails.registry.snapshot.devices.find((d) => d.id === seededPrepare.id)?.state, + ).toBe("deleted"); + expect( + prepareFails.eventBus + .replay() + .filter((event) => event.event === "lease.granted") + .map((event) => (event.payload as { deviceId: string }).deviceId), + ).toEqual([afterPrepare.device.id]); + + const shutdownFails = await build(); + const seededShutdown = await seedSlimDevice(shutdownFails, "ready"); + shutdownFails.driver.failOn("shutdown", 1, crash); + const afterShutdown = await grantedOnceSettled( + shutdownFails.dispatcher.dispatch("lease.request", ask, session()), + ); + expect(afterShutdown.device.id).not.toBe(seededShutdown.id); + expect( + shutdownFails.registry.snapshot.devices.find((d) => d.id === seededShutdown.id)?.state, + ).toBe("deleted"); + expect( + shutdownFails.eventBus + .replay() + .filter((event) => event.event === "device.shutdown") + .map((event) => event.payload), + ).toContainEqual({ deviceId: seededShutdown.id, initiator: "lease-engine" }); + + const rebooting = await build(); + const seededWarm = await seedSlimDevice(rebooting, "ready"); + const before = (await rebooting.dispatcher.dispatch("status.get", {}, session())).capacity; + rebooting.driver.hangMakeReady(); + const pending = rebooting.dispatcher.dispatch("lease.request", ask, session()); + await vi.waitFor(() => { + expect(rebooting.driver.calls.filter((call) => call.operation === "makeReady")).toHaveLength( + 2, + ); + }); + const during = await rebooting.dispatcher.dispatch("status.get", {}, session()); + expect(during.devices?.find((d) => d.id === seededWarm.id)?.state).toBe("ready"); + expect(during.capacity).toEqual(before); + rebooting.driver.releaseMakeReady(); + expect((await pending).device.id).toBe(seededWarm.id); + }); + it("status.get and list.get return mode for every device, including one still provisioning", async () => { const { dispatcher, registry } = await buildDispatcher({ driverOptions: { mode: "slim" } }); const granted = await dispatcher.dispatch("lease.request", request, session()); From 9d80102c97da7e23f23b68af0a61d012be696b26 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:41:34 +0100 Subject: [PATCH 10/22] feat(leasing): a failed warm reboot destroys the device and counts toward the single retry (#1330) --- src/core/managed-device-lifecycle.ts | 10 +- src/leasing/lease-acquisition-coordinator.ts | 177 ++++++++++++------- 2 files changed, 118 insertions(+), 69 deletions(-) diff --git a/src/core/managed-device-lifecycle.ts b/src/core/managed-device-lifecycle.ts index 9dd9d5b0f..1a0044112 100644 --- a/src/core/managed-device-lifecycle.ts +++ b/src/core/managed-device-lifecycle.ts @@ -120,7 +120,15 @@ export class ManagedDeviceLifecycle { purpose: "prepare", }); } catch (error: unknown) { - await this.#release(claimed); + // why: the device is half way between two boots, so it is recorded as shut down for the caller to destroy; the claim ends either way. + try { + await this.#commitWithoutRelease(claimed, ["ready"], "shutdown", { + event: "device.shutdown", + payload: { deviceId: claimed.device.id, initiator: "lease-engine" }, + }); + } finally { + await this.#release(claimed); + } throw error; } const device = await this.decisions.run(async () => { diff --git a/src/leasing/lease-acquisition-coordinator.ts b/src/leasing/lease-acquisition-coordinator.ts index 6324ab715..00b1c9d57 100644 --- a/src/leasing/lease-acquisition-coordinator.ts +++ b/src/leasing/lease-acquisition-coordinator.ts @@ -995,7 +995,7 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { reservation, }); } catch (error: unknown) { - if (error instanceof BootTimeoutError) { + if (error instanceof BootTimeoutError && exceptOption(waiter).except === undefined) { await this.options.decisions.run(async () => { if (waiter.state !== "rejected") this.#reject(waiter, error, "boot-timeout"); }); @@ -1010,27 +1010,7 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { this.#wakeQueue(); return; } - const retry = await this.options.decisions.run(async () => { - if (waiter.state === "rejected") return false; - waiter.failures += 1; - if (waiter.failures === 1) { - this.options.queue.markNew(waiter); - return true; - } - // why: ADR 0021 §1 declines a probe instead of rejecting it, and its caller (the gateway) reads the code. - this.#reject( - waiter, - new ProvisionFailedError(error), - waiter.options.fleetRequestId === undefined ? "unresolvable-spec" : "no-wait", - ); - return false; - }); - if (retry) { - this.#driving.delete(waiter); - await this.#drive(waiter); - } else { - this.#wakeQueue(); - } + await this.#countFailure(waiter, error); return; } await this.#grantHandoff(waiter, handoff, "provision"); @@ -1236,14 +1216,104 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { device: VirtualDevice, claim: DeviceOperationClaim, ): Promise { - this.options.queue.notifyProgress(waiter, { - stage: "booting", - etaMs: waiter.timing.estimatedBootMs, + let handoff: ReadyDeviceHandoff; + try { + this.options.queue.notifyProgress(waiter, { + stage: "booting", + etaMs: waiter.timing.estimatedBootMs, + }); + const except = exceptOption(waiter).except ?? []; + const ready = await this.options.lifecycle.rebootForLease(device, claim, except); + if (ready === undefined) throw new Error(`Reboot target is no longer safe: ${device.id}`); + handoff = ready; + } catch (error: unknown) { + this.#logFailure( + "rebooting a warm device for a waiter failed", + waiter, + device, + "reboot", + error, + ); + await this.#destroyFailedBoot(waiter, device, "shutdown"); + await this.#countFailure(waiter, error); + return; + } + await this.#grantHandoff(waiter, handoff, "reboot-ready"); + } + + /** why: a device that failed to boot is destroyed, or quarantined when the destroy fails too, before the waiter's slot is freed (see below). */ + async #destroyFailedBoot( + waiter: AcquisitionWaiter, + device: VirtualDevice, + state: VirtualDevice["state"], + ): Promise { + let destroyed = true; + try { + await this.options.lifecycle.destroy(device, "lease-engine", "cleanup"); + } catch (destroyError: unknown) { + this.#logFailure( + "destroying a device that failed to boot failed", + waiter, + device, + "destroy", + destroyError, + ); + destroyed = false; + } + // why: a device the destroy could not retire may still be running, so it is handed to + // quarantine before the waiter's reservation is freed: `quarantined` is the one state that + // retries it, keeps it out of every plan and still counts it as running. Freeing the slot + // first would leave a window where the next planner boots a device that may be running. + if (!destroyed) { + try { + const quarantined = await this.options.quarantine.enterFromStalledTransition( + device.id, + state, + ); + if (!quarantined) { + this.#logger.warn( + "a device that failed to be destroyed was not quarantined: something else owns it now", + { deviceId: device.id, requesterId: waiter.options.requesterId, step: "quarantine" }, + ); + } + } catch (quarantineError: unknown) { + this.#logFailure( + "quarantining a device that failed to boot and to be destroyed failed", + waiter, + device, + "quarantine", + quarantineError, + ); + } + } + } + + /** + * why: a failed boot of an except lease counts like a failed provision (ADR 0066 §3): the first + * plans again, the second rejects `PROVISION_FAILED`, one count for provision, boot and reboot. + */ + async #countFailure(waiter: AcquisitionWaiter, error: unknown): Promise { + const retry = await this.options.decisions.run(async () => { + if (waiter.state === "rejected") return false; + waiter.failures += 1; + if (waiter.failures === 1) { + this.options.queue.markNew(waiter); + return true; + } + // why: ADR 0021 §1 declines a probe instead of rejecting it, and its caller (the gateway) reads the code. + this.#reject( + waiter, + new ProvisionFailedError(error), + waiter.options.fleetRequestId === undefined ? "unresolvable-spec" : "no-wait", + ); + return false; }); - const except = exceptOption(waiter).except ?? []; - const ready = await this.options.lifecycle.rebootForLease(device, claim, except); - if (ready === undefined) throw new Error(`Reboot target is no longer safe: ${device.id}`); - await this.#grantHandoff(waiter, ready, "reboot-ready"); + if (retry) { + this.#driving.delete(waiter); + await this.#drive(waiter); + } else { + this.#wakeQueue(); + } } async #bootShutdown( @@ -1258,7 +1328,11 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { stage: "booting", etaMs: waiter.timing.estimatedBootMs, }); - const ready = await this.options.lifecycle.bootForLease(device, claim); + const ready = await this.options.lifecycle.bootForLease( + device, + claim, + exceptOption(waiter).except, + ); if (ready === undefined) throw new Error(`Boot target is no longer safe: ${device.id}`); handoff = ready; } catch (error: unknown) { @@ -1269,44 +1343,11 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { "boot", error, ); - let destroyed = true; - try { - await this.options.lifecycle.destroy(device, "lease-engine", "cleanup"); - } catch (destroyError: unknown) { - this.#logFailure( - "destroying a device that failed to boot failed", - waiter, - device, - "destroy", - destroyError, - ); - destroyed = false; - } - // why: a device the destroy could not retire may still be running, so it is handed to - // quarantine before the waiter's reservation is freed: `quarantined` is the one state that - // retries it, keeps it out of every plan and still counts it as running. Freeing the slot - // first would leave a window where the next planner boots a device that may be running. - if (!destroyed) { - try { - const quarantined = await this.options.quarantine.enterFromStalledTransition( - device.id, - device.state, - ); - if (!quarantined) { - this.#logger.warn( - "a device that failed to be destroyed was not quarantined: something else owns it now", - { deviceId: device.id, requesterId: waiter.options.requesterId, step: "quarantine" }, - ); - } - } catch (quarantineError: unknown) { - this.#logFailure( - "quarantining a device that failed to boot and to be destroyed failed", - waiter, - device, - "quarantine", - quarantineError, - ); - } + await this.#destroyFailedBoot(waiter, device, device.state); + if (exceptOption(waiter).except !== undefined) { + await this.options.decisions.run(() => capacityReservation.release()); + await this.#countFailure(waiter, error); + return; } await this.options.decisions.run(async () => { capacityReservation.release(); From 2f867b79e5cb16d215c5ec196488c98787045b95 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:42:26 +0100 Subject: [PATCH 11/22] test: a replay with another except is a conflict, and a failed boot or provision with except counts once (#1330) --- src/core/registry.test.ts | 4 ++++ src/daemon/dispatcher.test.ts | 40 +++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/core/registry.test.ts b/src/core/registry.test.ts index 4e306453d..1ea605aa2 100644 --- a/src/core/registry.test.ts +++ b/src/core/registry.test.ts @@ -363,6 +363,7 @@ describe("Registry", () => { ownerId: "agent-1", request: { class: "phone", + except: ["store", "other"], imageTag: "default", mode: "slim", model: "iPhone 16", @@ -380,6 +381,7 @@ describe("Registry", () => { }); const lease = await registry.createLease({ deviceId: full.id, + except: ["store", "other"], leaseId: "lse_chosen", ownerId: "agent-1", request: { environment: { SIMLOCK_UDID: "abc", OTHER: "x" }, id: "req_granted", timing }, @@ -445,6 +447,7 @@ describe("Registry", () => { createdAt: 1_000, driverData: { fakeDeviceId: "fk-full-booted" }, driverDeviceId: "drv-full", + except: ["store", "other"], foreignProvenanceDetectedAt: 1_012, foreignStateDetectedAt: 1_011, id: full.id, @@ -477,6 +480,7 @@ describe("Registry", () => { ownerId: "agent-1", request: { class: "phone", + except: ["store", "other"], imageTag: "default", mode: "slim", model: "iPhone 16", diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index ee2d375ef..d310539c0 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -3112,6 +3112,46 @@ describe("Dispatcher: device mode on every surface", () => { .map((event) => event.payload), ).toContainEqual({ deviceId: seededShutdown.id, initiator: "lease-engine" }); + const booting = await build(); + const seededShut = await seedSlimDevice(booting, "shutdown"); + const bootedShut = await booting.dispatcher.dispatch("lease.request", ask, session()); + expect(bootedShut.device).toMatchObject({ except: ask.except, id: seededShut.id }); + expect( + booting.driver.calls.filter((call) => call.operation === "makeReady").at(-1)?.arguments[1], + ).toMatchObject({ except: ask.except, purpose: "prepare" }); + expect( + booting.eventBus.replay().find((event) => event.event === "lease.granted")?.payload, + ).toMatchObject({ source: "booted" }); + + const bootFails = await build(); + const seededBootFails = await seedSlimDevice(bootFails, "shutdown"); + bootFails.driver.failOn("makeReady", 2, crash); + const afterBoot = await grantedOnceSettled( + bootFails.dispatcher.dispatch("lease.request", ask, session()), + ); + expect(afterBoot.device.id).not.toBe(seededBootFails.id); + expect( + bootFails.registry.snapshot.devices.find((d) => d.id === seededBootFails.id)?.state, + ).toBe("deleted"); + + const twice = await build(); + twice.driver.failOn("provision", 1, crash); + twice.driver.failOn("makeReady", 1, crash); + const refusal = await twice.dispatcher + .dispatch("lease.request", ask, session()) + .catch((error: unknown) => error); + expect(classifyError(refusal)).toBe("PROVISION_FAILED"); + + const replay = await build(); + const keyed = { ...ask, idempotencyKey: "key-1" }; + const first = await replay.dispatcher.dispatch("lease.request", keyed, session()); + const same = await replay.dispatcher.dispatch("lease.request", keyed, session()); + expect(same.lease.id).toBe(first.lease.id); + const conflict = await replay.dispatcher + .dispatch("lease.request", { ...keyed, except: ["other"] }, session()) + .catch((error: unknown) => error); + expect(classifyError(conflict)).toBe("IDEMPOTENCY_CONFLICT"); + const rebooting = await build(); const seededWarm = await seedSlimDevice(rebooting, "ready"); const before = (await rebooting.dispatcher.dispatch("status.get", {}, session())).capacity; From 4bd13026ce51505b727738e099a9495bdf61e0f5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:43:44 +0100 Subject: [PATCH 12/22] feat(leasing): a replay naming another except is a conflict, and the stored request keeps its list (#1330) --- src/core/registry-rows.ts | 3 +++ src/core/registry-schema.ts | 1 + src/leasing/lease-request-book.ts | 1 + 3 files changed, 5 insertions(+) diff --git a/src/core/registry-rows.ts b/src/core/registry-rows.ts index f344abd37..1a66c3f4c 100644 --- a/src/core/registry-rows.ts +++ b/src/core/registry-rows.ts @@ -198,6 +198,7 @@ const REQUEST_COLUMNS = [ "mode", "image_tag", "baseline", + "except_categories", "class", "physical", "created_at", @@ -345,6 +346,7 @@ export function writeLeaseRequest(database: SqliteDatabase, record: LeaseRequest request.mode ?? null, request.imageTag ?? null, request.baseline ?? null, + request.except === undefined ? null : request.except.join(","), request.class ?? null, flagValue(request.physical), record.createdAt, @@ -627,6 +629,7 @@ function requestFromRow(reader: RowReader): DeviceRequest { ...present("mode", reader.optOneOf("mode", DEVICE_MODES)), ...present("imageTag", reader.optText("image_tag")), ...present("baseline", reader.optText("baseline")), + ...present("except", exceptOf(reader)), ...present("class", reader.optOneOf("class", DEVICE_CLASSES)), ...present("physical", reader.optFlag("physical")), }; diff --git a/src/core/registry-schema.ts b/src/core/registry-schema.ts index 381754674..794f2c1a9 100644 --- a/src/core/registry-schema.ts +++ b/src/core/registry-schema.ts @@ -126,6 +126,7 @@ ALTER TABLE lease_requests ADD COLUMN baseline TEXT; const REGISTRY_V4 = ` ALTER TABLE devices ADD COLUMN except_categories TEXT; +ALTER TABLE lease_requests ADD COLUMN except_categories TEXT; `; export const registryOwner: SqliteSchemaOwner = { diff --git a/src/leasing/lease-request-book.ts b/src/leasing/lease-request-book.ts index 2c3bf2f70..e1bb46f10 100644 --- a/src/leasing/lease-request-book.ts +++ b/src/leasing/lease-request-book.ts @@ -418,6 +418,7 @@ function sameDeviceRequest(left: DeviceRequest, right: DeviceRequest): boolean { left.mode === right.mode && left.imageTag === right.imageTag && left.baseline === right.baseline && + (left.except ?? []).join(",") === (right.except ?? []).join(",") && (left.physical === true) === (right.physical === true) ); } From 6b91d9dee350295d17049602fa8f286240206077 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:46:36 +0100 Subject: [PATCH 13/22] docs(leasing): except on the CLI, errors, events and manuals, and its slow-lane cases (#1330) --- docs/internal/EVENTS.md | 6 +- e2e/slow-ios-slim.test.ts | 127 +++++++++++++++++- src/contract/AGENTS.md | 1 + src/core/AGENTS.md | 4 +- src/leasing/AGENTS.md | 9 +- .../getting-started/connect-your-agent.mdx | 2 +- .../src/content/docs/docs/reference/cli.mdx | 3 +- .../content/docs/docs/reference/errors.mdx | 6 +- .../content/docs/docs/reference/events.mdx | 4 +- .../docs/using-devices/choosing-a-device.mdx | 21 +++ .../docs/docs/using-devices/remote-agents.mdx | 2 +- 11 files changed, 168 insertions(+), 17 deletions(-) diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 4d121b978..608f92ffa 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -46,9 +46,9 @@ in short: `subject.past-tense-fact`, emitted post-commit, facts not commands. | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| -| `lease.requested` | request id, request spec (platform, `model` only when the request named one, `class` when it named one -- a request naming neither carries neither, ADR 0015 §9, os version -- an exact version or an OS range as typed, ADR 0015 §2, device `mode` as the request named it -- absent when it named none, since the worker's default is applied after this event, ADR 0007 §2; `imageTag` when the request named one, #214, additive; `physical: true` when the request asked for an enrolled physical device, ADR 0022, additive; `baseline`, the name, when the request named one, #1207, additive), requester, wait policy, `fleetRequestId` on a worker's event for a gateway's dispatch (a probe; ADR 0021 §3, additive, events rule 6) | a lease request is accepted by the daemon and stored; the request id is the stored request's, so an observer can match this event to it (#72 added the id; additive, events rule 6) | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway, ADR 0005 §11 — its own fleet queue's admission, before any worker is chosen) | implemented | +| `lease.requested` | request id, request spec (platform, `model` only when the request named one, `class` when it named one -- a request naming neither carries neither, ADR 0015 §9, os version -- an exact version or an OS range as typed, ADR 0015 §2, device `mode` as the request named it -- absent when it named none, since the worker's default is applied after this event, ADR 0007 §2; `imageTag` when the request named one, #214, additive; `physical: true` when the request asked for an enrolled physical device, ADR 0022, additive; `baseline`, the name, when the request named one, #1207, additive; `except`, the list as the request named it, when it named one, ADR 0066 §1, additive), requester, wait policy, `fleetRequestId` on a worker's event for a gateway's dispatch (a probe; ADR 0021 §3, additive, events rule 6) | a lease request is accepted by the daemon and stored; the request id is the stored request's, so an observer can match this event to it (#72 added the id; additive, events rule 6) | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway, ADR 0005 §11 — its own fleet queue's admission, before any worker is chosen) | implemented | | `lease.queued` | request id, queue position (counted in the request's own line, ADR 0022 §3: a physical request waits apart from simulator and emulator requests) | no capacity; request entered the wait queue | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway) | implemented | -| `lease.granted` | lease id, device id, requester, request id, source (`warm`/`booted`/`provisioned`, ADR 0016 §2: the kind of the plan that granted it -- an eviction never grants by itself, so the plan made after it decides; a physical grant is `warm`, ADR 0022 §3), `fleetRequestId` when the grant served a probe (ADR 0021 §3, additive), the device's `platform` (`ios` or `android`), `baseline: { name, version }` when the device is a copy of a baseline (#1207, additive) | a device was assigned and handed out | LeaseLifecycle | implemented (payload per ADR 0004 pending) | +| `lease.granted` | lease id, device id, requester, request id, source (`warm`/`booted`/`provisioned`, ADR 0016 §2: the kind of the plan that granted it -- an eviction never grants by itself, so the plan made after it decides; a physical grant is `warm`, ADR 0022 §3; a ready warm device shut down and booted again for a request with `except` is `booted`, because the requester waited for a boot, ADR 0066 §2), `fleetRequestId` when the grant served a probe (ADR 0021 §3, additive), the device's `platform` (`ios` or `android`), `baseline: { name, version }` when the device is a copy of a baseline (#1207, additive) | a device was assigned and handed out | LeaseLifecycle | implemented (payload per ADR 0004 pending) | | `lease.renewed` | lease id, new deadline | a `lease.renew` succeeded — whether it came from `simlock lease renew`, `POST /v1/leases/{id}/renew`, or the renew timer a running `simlock lease` / MCP session keeps over its own lease. There is one renew path and this is it | LeaseLifecycle | implemented (payload per ADR 0004 pending) | | `lease.released` | lease id, device id, reason (explicit/killed/device-lost), owner id | an explicit `lease.release` (which is what a `simlock lease` holder does on its way out), (killed) an operator `release --all` or `nuke`, or (device-lost) a leased device could not be recovered after it stopped running outside simlock, or a daemon start found its device not running, or (device-lost, ADR 0022 §7) a physical device was not present for the grace period (`health.stableObservations` reads in a row, `health.probeIntervalMs` apart; emitted by the `PhysicalDeviceWatcher` through `LeaseReleaseCoordinator.endForAbsentDevice`; the device becomes `absent` in the same write and nothing is wiped), and the device of that lease was wiped and returned to the pool, left waiting in `reclaiming` on a platform the daemon could not list, or marked missing. Closing a connection is not a release and never emits this | LeaseLifecycle | implemented (payload per ADR 0004 pending) | | `lease.expired` | lease id, device id, owner id | the lease's deadline passed with no `lease.renew` behind it — the grant-time TTL, or the TTL of the last renew, simply ran out. This is the one way a lease ends without somebody asking, and the only bound on a holder that was killed outright | LeaseLifecycle | implemented (payload per ADR 0004 pending) | @@ -84,7 +84,7 @@ worker is ever contacted. `lease-id-taken` (ADR 0020; widens a published vocabul | `device.quarantine-recovered` | device id, attempts, reclaim strategy (erase/snapshot/wipe/uninstall), `missingApps` for a physical device (additive), the device's `platform` (`ios` or `android`) | a quarantined device's retried purge succeeded; it returned to `ready`/`shutdown` and rejoined the warm pool. Never emitted for a spent `fresh` device (`mayBeGranted` false): its retry is a delete, and a successful one emits `device.deleted` with initiator `lease-end` (`lease-engine` for a device that never served a lease) | QuarantineCoordinator | implemented | | `device.quarantine-abandoned` | device id, attempts, the device's `platform` (`ios` or `android`) | a quarantined device exhausted its configured retry budget (`warmPool.quarantine.maxRetries`) — purge retries, or delete retries for a spent `fresh` device — and was destroyed, or, for a physical device, unenrolled: Simlock never destroys one (safety rule 2, ADR 0022 §4) | QuarantineCoordinator | implemented | | `device.quarantine-stranded` | device id, attempts, stable error summary, the device's `platform` (`ios` or `android`) | a quarantined device exhausted its retry budget (purge or delete retries) and the destroy that should have retired it also failed; it stays `quarantined` with no further retry until an operator intervenes | QuarantineCoordinator | implemented | -| `device.shutdown` | device id, initiator (rule/command; `daemon-stop` when a stopping daemon shut down an idle device, #1056; `warm-pool` when the warm pool shut an idle device down, over the running limit, with `warmPool.enabled: false`, to keep `warmPool.reserveRunning` running slots free, or because a ready device that never served a lease and that no `warmPool.targets` entry and no kind the pool learned from a lease keeps has been idle past `idle.shutdownAfterMs`, or to displace it: an idle device shut down so a newer learned kind, or a configured target, can boot into its slot) | device stopped, still on disk | Registry; ReclaimCoordinator for interrupted reclaim recovery | implemented | +| `device.shutdown` | device id, initiator (rule/command; `daemon-stop` when a stopping daemon shut down an idle device, #1056; `warm-pool` when the warm pool shut an idle device down, over the running limit, with `warmPool.enabled: false`, to keep `warmPool.reserveRunning` running slots free, or because a ready device that never served a lease and that no `warmPool.targets` entry and no kind the pool learned from a lease keeps has been idle past `idle.shutdownAfterMs`, or to displace it: an idle device shut down so a newer learned kind, or a configured target, can boot into its slot; `lease-engine` when a ready warm device failed the reboot a lease with `except` asked of it, ADR 0066 §2) | device stopped, still on disk | Registry; ReclaimCoordinator for interrupted reclaim recovery | implemented | | `device.deleted` | device id, initiator (`lease-end` when a `fresh` device's lease ended and its delete completed — from ReclaimCoordinator, at startup convergence, or retried from quarantine; #75. `doctor` when `doctor --fix` marked a missing device, or startup's lease reconciler found a leased device absent from a platform it could read and ended the lease in the same write, ADR 0019 §2. `operator` when `device remove` unenrolled a physical device, ADR 0022 §2. `quarantine` when a physical device's quarantine retries ran out and it was unenrolled, ADR 0022 §4; `lease-engine` when a device that failed to boot for a lease was destroyed in cleanup, or when quarantine's delete retry removed a device that never served a lease; `cleanup-reaper` when the cleanup reaper destroyed a device; `nuke` when `nuke` destroyed it; `baseline-save` when `baseline save` kept a copy of the device and deleted it; `baseline-remove` when `baseline remove` deleted an idle device made from the baseline; `baseline-replaced` when a newer baseline version replaced the one an idle device was made from and the device was deleted), physical (the record's own flag: `true` for an enrolled physical device, `false` for a simulator or emulator; additive, events rule 6) | device removed from the registry, and from disk for a virtual device; a physical device is only forgotten and nothing is sent to it | Registry | implemented | | `device.enrolled` | device id, platform, driver device id (the canonical ID), model, OS version, class (phone/tablet), app count, reenrolled | an admin's `device add` wrote a physical device `ready` (ADR 0022 §2). `reenrolled` is `true` when the device already had a `ready`, `quarantined` or `absent` record, which kept its registry ID and took a fresh read of model, OS version, class and apps | Registry | implemented | | `device.absence-detected` | device id, previous state (ready/leased/reclaiming), absent reason (locked/untrusted/not-present) | an enrolled physical device became `absent` (ADR 0022 §2, §7, §8): the `PhysicalDeviceWatcher` read it not present `health.stableObservations` times in a row (a leased device's lease ends first, `lease.released` device-lost, in the same write), or `ReclaimCoordinator` found it not present after a failed reclaim (`reclaiming → absent`, no `device.purge-failed`, no `device.quarantined`). Emitted after the commit | Registry (the watcher's writes, the reclaim's failure path) | implemented | diff --git a/e2e/slow-ios-slim.test.ts b/e2e/slow-ios-slim.test.ts index e1fc24c33..ee3556a54 100644 --- a/e2e/slow-ios-slim.test.ts +++ b/e2e/slow-ios-slim.test.ts @@ -17,6 +17,8 @@ interface LeaseGrant { readonly lease: string; readonly udid: string; readonly mode: "slim" | "full"; + /** why: the categories the grant says the lease kept running; absent for a lease with no `--except`. */ + readonly except?: readonly string[]; /** The device set the grant says the device lives in; no simctl call reaches it without. */ readonly deviceSet: string; } @@ -103,6 +105,23 @@ async function catalogModelAndOs(env: TestEnv): Promise<{ model: string; os: str return { model: model as string, os: os as string }; } +/** why: a runtime is picked by version, not by being the newest installed (ADR 0066): the first model the catalog pairs with a runtime `pick` accepts. */ +async function catalogModelWithOs( + env: TestEnv, + pick: (versions: readonly string[]) => string | undefined, +): Promise<{ model: string; os: string }> { + const catalog = await env.cli(["catalog", "--json", "--platform", "ios"]); + expect(catalog.code, `catalog failed: ${catalog.stderr}`).toBe(0); + const iosCatalog = (catalog.json as { platforms: CatalogPlatform[] }).platforms.find( + (platform) => platform.platform === "ios", + ); + for (const model of iosCatalog?.models ?? []) { + const os = pick([...(iosCatalog?.modelRuntimes[model] ?? [])].sort(compareVersionsDescending)); + if (os !== undefined) return { model, os }; + } + throw new Error("simlock catalog pairs no iOS model with the runtime this case needs"); +} + async function leaseDetached( env: TestEnv, model: string, @@ -128,7 +147,7 @@ async function leaseDetached( ); expect(lease.code, `lease failed: ${lease.stderr}`).toBe(0); const grant = lease.json as { - device: { driverDeviceId: string; mode: "slim" | "full" }; + device: { driverDeviceId: string; except?: readonly string[]; mode: "slim" | "full" }; environment: Record; lease: { id: string }; }; @@ -136,6 +155,7 @@ async function leaseDetached( expect(deviceSet, "an iOS grant must name the device set its device lives in").toBeDefined(); return { deviceSet: deviceSet as string, + ...(grant.device.except === undefined ? {} : { except: grant.device.except }), lease: grant.lease.id, mode: grant.device.mode, udid: grant.device.driverDeviceId, @@ -321,6 +341,111 @@ describe.skipIf(process.platform !== "darwin")( }, ); + it.each([ + ["iOS 18.5", (versions: readonly string[]) => versions.find((v) => v === "18.5")], + [ + "the newest iOS 26.x", + (versions: readonly string[]) => versions.find((v) => v.startsWith("26.")), + ], + ])( + "a lease of --mode slim --except store,other on %s finds every store and other label enabled", + { timeout: 900_000 }, + async (_label, pick) => { + const env = await withRealDaemon(); + const { model, os } = await catalogModelWithOs(env, pick); + const except = ["store", "other"]; + + const grant = await leaseDetached(env, model, os, "slim-except", [ + "--mode", + "slim", + "--except", + except.join(","), + ]); + + await expectSlim(env, grant.mode, "a --mode slim lease with --except must be slim"); + expect(grant.except).toEqual(except); + const disabled = await printDisabled(grant); + const kept = labelsFor( + SLIM_CATEGORIES.filter((category) => except.includes(category.name)), + ); + expect( + kept.filter((label) => disabled.has(label)), + "a label of an excepted category is still disabled", + ).toEqual([]); + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); + }, + ); + + it( + "on the newest iOS 26.x, excepting each category in turn finds its labels enabled", + { timeout: 7_200_000 }, + async () => { + const env = await withRealDaemon(); + const { model, os } = await catalogModelWithOs(env, (versions) => + versions.find((version) => version.startsWith("26.")), + ); + for (const category of SLIM_CATEGORIES) { + const grant = await leaseDetached(env, model, os, `slim-except-${category.name}`, [ + "--mode", + "slim", + "--except", + category.name, + ]); + const disabled = await printDisabled(grant); + expect( + labelsFor([category]).filter((label) => disabled.has(label)), + `a label of the excepted category ${category.name} is still disabled`, + ).toEqual([]); + await env.cli(["release", grant.lease]); + } + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); + }, + ); + + it( + "a warm slim device is rebooted with the smaller list and granted", + { timeout: 1_200_000 }, + async () => { + const env = await withRealDaemon({ ios: { defaultMode: "slim" } }); + const { model, os } = await catalogModelWithOs(env, (versions) => + versions.find((version) => version.startsWith("26.")), + ); + // why: the pool learns the kind of a lease and boots a warm replacement once it is released. + const taught = await leaseDetached(env, model, os, "slim-teach"); + await env.cli(["release", taught.lease]); + let warmUdid: string | undefined; + await waitFor( + async () => { + const rows = (await env.cli(["list", "--devices"])).json as { + driverDeviceId: string; + mode: string; + state: string; + }[]; + warmUdid = rows.find( + (row) => row.state === "ready" && row.mode === "slim", + )?.driverDeviceId; + return warmUdid !== undefined; + }, + { timeout: 600_000, label: "a warm slim device is ready" }, + ); + + const grant = await leaseDetached(env, model, os, "slim-warm-except", [ + "--except", + "store", + ]); + + expect(grant.udid, "the warm device is the one granted").toBe(warmUdid); + expect(grant.except).toEqual(["store"]); + const disabled = await printDisabled(grant); + expect( + labelsFor(SLIM_CATEGORIES.filter((category) => category.name === "store")).filter( + (label) => disabled.has(label), + ), + ).toEqual([]); + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); + }, + ); + it( "no simulator from this file's device sets is still running after its flows", { timeout: 60_000 }, diff --git a/src/contract/AGENTS.md b/src/contract/AGENTS.md index 34ce99116..cf1fe722f 100644 --- a/src/contract/AGENTS.md +++ b/src/contract/AGENTS.md @@ -109,6 +109,7 @@ Three identities: - OS constraint: a bare version is exact (string equality). A range is one or more of `>=`, `>`, `<=`, `<` + a dotted version, joined by single spaces, or `A - B`. `^`, `~`, `*`, `||` and `x` read as a range and are refused. +- `lease.request` holds `except` (a slim iOS simulator lease keeping slim categories running, ADR 0066) to one object-level refinement with no path, so every transport answers `BAD_REQUEST` with the message as written: 1 to 16 names matching `EXCEPT_NAME_PATTERN`, none twice, never with `physical`, a platform but iOS or `mode: full`. The worker's default mode and a baseline's mode are checked in leasing. - `lease.request` holds an exact `osVersion` to `componentVersionSchema`'s bound (1 to 64 characters, no whitespace, control character or `;`, no leading `-`): a downloadable missing runtime installs it as a component. diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index b7f8bdad6..8bf83b282 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -77,7 +77,7 @@ Events: → `absent` `device.absence-detected`; `absent` → `reclaiming` `devic ## How it works 1. **Lifecycle** — `bootForLease`, `readyProvisionedForLease` keep the `boot` claim for the - grant; `bootWarm` drops it at `ready`. `shutdown`, `destroy`, `dispose` answer `undefined` for a + grant; `rebootForLease` shuts a `ready` device down and prepares it again with a lease's `except` list under that claim, keeps the record `ready` (one `recordRebootedDevice` write, no event) and, on a failure, commits `ready → shutdown` first; `bootWarm` drops it at `ready`. `shutdown`, `destroy`, `dispose` answer `undefined` for a leased, gone or moved device. `recoverLeased` reboots under the lease: no commit, no event. 2. **Provision** — `claimProvision` (lock) → `driver.provision` → `registerDevice` (`provisioning`, `device.provisioned`, optional `boot` claim) → ready. Boot failure: destroy, `BootTimeoutError` carrying the driver's message. @@ -128,7 +128,7 @@ Events: → `absent` `device.absence-detected`; `absent` → `reclaiming` `devic | Removal, startup read per platform | 5 min, 60 s | `COMPONENT_REMOVAL_TIMEOUT_MS`, `STARTUP_READ_LIMIT_MS` | | Host facts max age, tool read | 60 s, 30 s | none | -`state.db`, owner `registry`: `devices` (a physical device is `physical = 1`, its apps in `device_enrolled_apps`), `leases`, `lease_requests`, `lease_grants` with `lease_grant_environment`, `components` with `component_receipt`. A driver keeps its own `DeviceDataTable` (`driver.ts`) for a virtual device's `driverData`; a physical device has none. A granted request's `grant.device` is read as the device is now. +`state.db`, owner `registry`: `devices` (`except_categories`: the list a lease kept running, written in the grant commit; a physical device is `physical = 1`, its apps in `device_enrolled_apps`), `leases`, `lease_requests`, `lease_grants` with `lease_grant_environment`, `components` with `component_receipt`. A driver keeps its own `DeviceDataTable` (`driver.ts`) for a virtual device's `driverData`; a physical device has none. A granted request's `grant.device` is read as the device is now. ## Rules diff --git a/src/leasing/AGENTS.md b/src/leasing/AGENTS.md index 4f9781d28..e3c5850f0 100644 --- a/src/leasing/AGENTS.md +++ b/src/leasing/AGENTS.md @@ -47,7 +47,7 @@ and registry writers. Read-decide-commit runs under it; driver I/O never does. mismatch (`baselineMismatch`) or stale fails at once, and the spec is the baseline's, with its name and version; no download is attempted. 3. **Plan** (lock) — `AcquisitionPlanner.plan`; first that applies wins: - grant a ready fitting device → wait for one the warm pool is booting → + grant a ready fitting device (a slim request with `except` takes it with a `boot` claim and no capacity reservation instead, `reboot-ready`) → wait for one the warm pool is booting → boot a shut-down one → provision → evict an idle device (device or running limit) → wait, or `NO_CAPACITY` under `noWait`. Only the head of the virtual line plans; every physical waiter plans. @@ -63,11 +63,12 @@ and registry writers. Read-decide-commit runs under it; driver I/O never does. waiter with `ProvisionFailedError` (the driver's message; `PROVISION_FAILED`), a probe included, and wakes the queue. 4. **Perform** (no lock) — provision, boot or evict through core, then plan again. - A boot failure destroys the device and rejects `boot-timeout`; a destroy + A request with `except` (ADR 0066) boots with the list: a ready warm device is shut down and prepared again under its `boot` claim (`ManagedDeviceLifecycle.rebootForLease`; its record stays `ready`, and the grant is `booted`), a shut-down or new device boots with it. Any failure of those boots destroys the device (a failed reboot first records it `shutdown`) and counts one failure with a failed provision: the first plans again, the second rejects `PROVISION_FAILED`. + A boot failure of a request without `except` destroys the device and rejects `boot-timeout`; a destroy that fails hands the device to core's quarantine through a port leasing declares, and the waiter's slot is freed either way. 5. **Grant** (lock) — `LeaseLifecycle.grant` → one registry commit: device - `leased` + lease + request granted. Emits `lease.granted`. Arms the TTL. A grant of a ready + `leased` (with the request's `except` when the device is slim) + lease + request granted. Emits `lease.granted`. Arms the TTL. A grant of a ready device wakes the queue, so the next waiter plans without another event. 6. **Renew** — moves `ttlDeadline`; emits `lease.renewed`. The gateway forwards renews; it runs no timers of its own. @@ -124,6 +125,8 @@ Writes go through core's `Registry` (`state.db`). Request states: `open` → ## Known gaps +- **A crash mid-reboot of a warm device for an `except` lease** leaves the request failed at startup (`daemon-restarted`) and a `ready` record whose simulator may be shut down; startup's reconcile only reports that drift. A later grant of it is caught by the health monitor, which reboots it under the lease. + - **A SIGKILLed holder keeps its device until the TTL.** It runs no release. Bound it with `lease.defaultTtlMs` or `--ttl`; `simlock release ` ends it now. - **Recovery restores the disk, not the session.** Apps, log streams and diff --git a/website/src/content/docs/docs/getting-started/connect-your-agent.mdx b/website/src/content/docs/docs/getting-started/connect-your-agent.mdx index f1da9a78b..b93baf018 100644 --- a/website/src/content/docs/docs/getting-started/connect-your-agent.mdx +++ b/website/src/content/docs/docs/getting-started/connect-your-agent.mdx @@ -123,7 +123,7 @@ The server starts the daemon if it is not running. It renews the agent's lease w | Tool | What it does | | --- | --- | | `list_devices` | Lists the models, OS versions and Android system images you can lease here, and, as `physicalDevices`, the enrolled phones and tablets with their state (`ready`, `leased`, `absent`), why an absent one is absent, and, through a gateway, which worker holds it. It never downloads anything, never says who holds a phone, and `physicalDevices` is empty while the daemon is still starting. | -| `lease_simulator` | Leases one simulator or emulator for this session. Takes `platform` and, optionally, `model` or `class`, `osVersion`, `ttlMs`, `noWait`, `timeoutMs` and `allowDownload`, the same options as `simlock lease`. Returns the same lease the CLI prints. | +| `lease_simulator` | Leases one simulator or emulator for this session. Takes `platform` and, optionally, `model` or `class`, `osVersion`, `mode`, `except`, `ttlMs`, `noWait`, `timeoutMs` and `allowDownload`, the same options as `simlock lease`. Returns the same lease the CLI prints. | | `release_simulator` | Releases this session's lease. | | `lease_status` | Reports this session's lease, or `held: false` when it has none. Safe to call any time, for example after the agent's context was compacted. | | `run_on_device` | Runs one `simctl`, `adb` or `devicectl` command on this session's device. Takes `tool`, `args` and, optionally, `stdin` (at most 8,388,608 characters; a longer one fails the tool's input validation, before Simlock sees it). | diff --git a/website/src/content/docs/docs/reference/cli.mdx b/website/src/content/docs/docs/reference/cli.mdx index dcf2aef13..1b3e7496b 100644 --- a/website/src/content/docs/docs/reference/cli.mdx +++ b/website/src/content/docs/docs/reference/cli.mdx @@ -96,7 +96,7 @@ Lease a device. The command waits for a device, prints the grant, then stays run ```text simlock lease --platform [--device | --class ] [--os ] [--mode ] [--image-tag ] [--agent-id ] - [--baseline ] + [--except ] [--baseline ] [--timeout ] [--lease-id ] [--physical] [--no-wait] [--detach] [--ttl ] [--allow-download] [--export-env] [--bind-pid ] @@ -109,6 +109,7 @@ simlock lease --platform [--device | --class ] | `--class ` | Any model of this class: `phone`, `tablet`, `watch`, `tv`, `vision`, `auto` or `desktop`. | `phone` when `--device` is not given | | `--os ` | An exact OS version (`18.4`, `35`), or a range such as `>=18 <26` or `18 - 26`. A range never downloads. | The newest runtime installed for the platform | | `--mode ` | The device mode. `full` is guaranteed; `slim` is best effort and falls back to `full`. | The serving worker's default mode (`full` unless configured) | +| `--except ` | iOS only: keep these slim categories running on a slim simulator, such as `store,other`. One to 16 names, each lowercase letters, digits and `-`, starting with a letter, none twice. Needs a slim lease: a `--mode full`, a worker whose default mode is `full` with no `--mode`, a full `--baseline`, `--physical` and `--platform android` are each a `BAD_REQUEST`. The grant's `device.except` lists them; on a runtime older than iOS 18.5 you get a `full` device with no `except`. See [Keep a category running](/simlock/docs/using-devices/choosing-a-device#keep-a-category-running). | None: the worker's whole slim set is turned off | | `--image-tag ` | Android only: the system image type, such as `google_apis_playstore`. Never downloads. | Simlock picks an installed image | | `--baseline ` | Start from a saved baseline: the device is a new copy of it, with the operator's apps, files and settings. The `SIMLOCK_BASELINE` environment variable sets it when the flag is absent; an empty value sends nothing. Cannot be combined with `--class` or `--physical`. See [Start from a baseline](/simlock/docs/using-devices/choosing-a-device#start-from-a-baseline). | None: a plain device | | `--agent-id ` | The requester identity for this lease. Must not be empty, hold no control characters, and be at most 256 characters. | See [Requester identity](#requester-identity) | diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index 53fc091d5..419f1a9bd 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -42,14 +42,14 @@ In a script, check `code`, not the message: the wording of a message can change, | `QUEUE_TIMEOUT` | 10 | 500 | The request waited in the queue for its whole `--timeout` and got no device. | Raise `--timeout`, or check `simlock list --requests` for why requests wait. | | `REQUESTER_ALREADY_LEASED` | 13 | 409 | Your requester identity already holds or waits for its limit of leases (`lease.maxPerRequester`, 1 by default, counted per platform when the operator sets a limit for each), or, with a limit per platform, has a request waiting on that platform. The message names your lease. | Release that lease first, or give each agent session its own identity. | | `LEASE_ID_TAKEN` | 13 | 409 | `--lease-id` names an ID that an active lease or a waiting request already holds. | Use a new ID. Never reuse a lease ID. | -| `IDEMPOTENCY_CONFLICT` | 2 | 409 | A lease request reused an idempotency key its requester already sent for a different device or lease ID. | Send a new key for a new request. | -| `PROVISION_FAILED` | 1 | 500 | Creating or booting a device for the request failed twice. The message carries the platform tool's error. | Read the message and `simlock daemon logs`, then run `simlock doctor`. | +| `IDEMPOTENCY_CONFLICT` | 2 | 409 | A lease request reused an idempotency key its requester already sent for a different device, `except` list or lease ID. | Send a new key for a new request. | +| `PROVISION_FAILED` | 1 | 500 | Creating or booting a device for the request failed twice. A request with `--except` counts a failed boot of a device it was given, warm or new, the same way. The message carries the platform tool's error. | Read the message and `simlock daemon logs`, then run `simlock doctor`. | | `UNKNOWN_MODEL` | 12 | 422 | The model is not one this platform offers here, or no model of the requested class exists. | Run `simlock catalog` for the models and their exact names. | | `RUNTIME_MISSING` | 12 | 422 | The OS version, or an image of the `--image-tag`, is not installed. A range or an image tag never downloads. | Add `--allow-download`, install it with `simlock component install`, or pick an installed version from `simlock catalog`. | | `NO_DRIVER` | 12 | 422 | This machine cannot run the platform: iOS on Linux, or a platform whose tools are missing. | Run `simlock doctor` to see what is missing, install it, then restart the daemon. | | `CAPABILITY_MISSING` | 12 | 422 | No worker that could serve the request has every optional module it asks for, such as screen streaming. Only the programmatic client asks for modules. | Ask for fewer, or turn the module on for a worker under `capabilities` in its configuration. | | `UNKNOWN_LEASE` | 1 | 404 | No active lease has this ID: it was released, it expired, or it never existed. | Take a new lease. | -| `BAD_REQUEST` | 2 | 400 | The request has an invalid value: an unknown class or mode, both `--device` and `--class`, a TTL over `lease.maxTtlMs`, `--image-tag` on iOS, `--physical` with `--mode`, and so on. The message names the field. | Fix the value the message names. | +| `BAD_REQUEST` | 2 | 400 | The request has an invalid value: an unknown class or mode, both `--device` and `--class`, a TTL over `lease.maxTtlMs`, `--image-tag` on iOS, `--physical` with `--mode`, `--except` on a lease that is not a slim iOS simulator or naming a category twice, one the worker does not slim or a bad name, and so on. The message names the field. | Fix the value the message names. | | `CANCELLED` | 1 | 499 | The programmatic client gave up a lease request it was waiting on. Never sent by the daemon. | Nothing, unless you did not mean to cancel. | ## Runtimes, images and downloads diff --git a/website/src/content/docs/docs/reference/events.mdx b/website/src/content/docs/docs/reference/events.mdx index 98aa6e99c..484268b0c 100644 --- a/website/src/content/docs/docs/reference/events.mdx +++ b/website/src/content/docs/docs/reference/events.mdx @@ -104,9 +104,9 @@ The **Gateway** column below says what a gateway shows for each event: | Event | When it fires | Payload | Gateway | | --- | --- | --- | --- | -| `lease.requested` | A lease request was accepted and stored. | `requestId`, `requestSpec` (the request as sent, with `baseline` when it named one), `requester`, `waitPolicy` (`wait` or `no-wait`), `fleetRequestId` on a worker when the request came from a gateway | Own and relayed | +| `lease.requested` | A lease request was accepted and stored. | `requestId`, `requestSpec` (the request as sent, with `baseline` and `except` when it named them), `requester`, `waitPolicy` (`wait` or `no-wait`), `fleetRequestId` on a worker when the request came from a gateway | Own and relayed | | `lease.queued` | No device was free, so the request started waiting. | `requestId`, `queuePosition` (counted among requests of the same kind: physical requests wait in a line of their own) | Own and relayed | -| `lease.granted` | A device was handed to a request. | `leaseId`, `deviceId`, `requester`, `requestId`, `source` (`warm`: ready device; `booted`: shut-down device booted; `provisioned`: device created), `platform`, `baseline` (`{ name, version }`) when the device is a copy of a baseline, `fleetRequestId` when it served a gateway | Relayed | +| `lease.granted` | A device was handed to a request. | `leaseId`, `deviceId`, `requester`, `requestId`, `source` (`warm`: ready device; `booted`: shut-down device booted, or a ready device booted again for a request with `except`; `provisioned`: device created), `platform`, `baseline` (`{ name, version }`) when the device is a copy of a baseline, `fleetRequestId` when it served a gateway | Relayed | | `lease.renewed` | A lease was renewed. | `leaseId`, `newDeadline` | Relayed | | `lease.released` | A lease ended because someone or something ended it. | `leaseId`, `deviceId`, `reason` (`explicit`: released; `killed`: `release --all` or `nuke`; `device-lost`: the device crashed and could not be brought back, or a physical device went away), `ownerId` | Relayed | | `lease.expired` | A lease reached its deadline without a renew. | `leaseId`, `deviceId`, `ownerId` | Relayed | diff --git a/website/src/content/docs/docs/using-devices/choosing-a-device.mdx b/website/src/content/docs/docs/using-devices/choosing-a-device.mdx index f5ede8b46..dc500ba52 100644 --- a/website/src/content/docs/docs/using-devices/choosing-a-device.mdx +++ b/website/src/content/docs/docs/using-devices/choosing-a-device.mdx @@ -120,6 +120,27 @@ What to expect: If a test fails because a push notification, a Spotlight result, an App Store sheet or a system picker never appears, check `device.mode`. Ask for `--mode full` when your app needs those features. +### Keep a category running + +When a test needs one part of what slim turns off, name its category with `--except` instead of giving up the whole saving: + +```sh +simlock lease --platform ios --mode slim --except store,other +``` + +The simulator boots with those categories running and the rest of the slim set off, and the grant reports `device.except` beside `device.mode`: + +```json +{ "device": { "mode": "slim", "except": ["store", "other"] } } +``` + +- `--except` needs a slim lease. With `--mode full`, a worker whose default is `full` and no `--mode`, or a full `--baseline`, it is refused with `BAD_REQUEST`. A slim baseline on a worker whose default is `full` is granted. +- A name the worker does not slim is refused with `BAD_REQUEST`, as is a name given twice, a name that is not lowercase letters, digits and `-`, and more than 16 names. +- It is for iOS simulators: `--platform android` and `--physical` are refused. +- On a runtime older than iOS 18.5 you get a `full` device with no `except`. +- A device the worker holds warm is shut down and booted again with your list before you get it, so the lease can take a little longer than one without `--except`. If that boot fails, the device is deleted and Simlock tries once more with another; a second failure is `PROVISION_FAILED`. +- Over HTTP the body takes `except` as a list, and over MCP `lease_simulator` takes the same `except`. + ## Choose the system image (Android) `--image-tag` picks the kind of Android system image, such as `google_apis_playstore` for Google Play or `default` for plain Android. You can use the tags that `simlock catalog --platform android` lists under images. diff --git a/website/src/content/docs/docs/using-devices/remote-agents.mdx b/website/src/content/docs/docs/using-devices/remote-agents.mdx index 172ef7031..e42055635 100644 --- a/website/src/content/docs/docs/using-devices/remote-agents.mdx +++ b/website/src/content/docs/docs/using-devices/remote-agents.mdx @@ -51,7 +51,7 @@ export SIMLOCK_TOKEN=slk_d2FybS1wb29sLWFnZW50LXRva2VuLWV4YW1wbGUtMDM -1. **Ask for a device.** The body takes the same choices as `simlock lease`: `platform` (required), `device` or `class`, `os`, `mode`, `imageTag`, `physical`, `ttlMs`, `timeoutMs`, `noWait` and `allowDownload`. See [Choosing a device](/simlock/docs/using-devices/choosing-a-device). +1. **Ask for a device.** The body takes the same choices as `simlock lease`: `platform` (required), `device` or `class`, `os`, `mode`, `except`, `imageTag`, `physical`, `ttlMs`, `timeoutMs`, `noWait` and `allowDownload`. See [Choosing a device](/simlock/docs/using-devices/choosing-a-device). ```sh curl -sS -X POST "$SIMLOCK_URL/v1/lease-requests" \ From 571458599c692d4b69d740e0e9f49985d95bd25f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:50:33 +0100 Subject: [PATCH 14/22] refactor(leasing): keep the request comparison and the HTTP dispatch input under the complexity bound (#1330) --- src/core/registry.ts | 1 + src/http/tracker.ts | 10 ++++++++-- src/leasing/lease-request-book.ts | 18 +++++++++++------- 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/core/registry.ts b/src/core/registry.ts index 6ed071edd..002be9828 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -299,6 +299,7 @@ export class Registry implements LeaseRequestStore { /** * why: a ready device shut down and prepared again for a lease (ADR 0066 §2) keeps its state, so this is no transition and emits no event (`ready → ready` is no edge); it records only what the new boot produced. */ + // fallow-ignore-next-line unused-class-member -- called through `ManagedDeviceRegistry`, which `Registry` implements. async recordRebootedDevice( deviceId: string, update: Required>, diff --git a/src/http/tracker.ts b/src/http/tracker.ts index ebc2275b6..2117fbdbe 100644 --- a/src/http/tracker.ts +++ b/src/http/tracker.ts @@ -97,11 +97,17 @@ function leaseRequestDispatchInput(body: LeaseRequestInput, idempotencyKey: stri ...(body.os === undefined ? {} : { osVersion: body.os }), ...(body.mode === undefined ? {} : { mode: body.mode }), ...(body.except === undefined ? {} : { except: body.except }), + ...requestImageFields(body), + ...requestOptions(body), + ...(idempotencyKey === undefined ? {} : { idempotencyKey }), + }; +} + +function requestImageFields(body: LeaseRequestInput) { + return { ...(body.imageTag === undefined ? {} : { imageTag: body.imageTag }), ...(body.baseline === undefined ? {} : { baseline: body.baseline }), ...(body.physical === undefined ? {} : { physical: body.physical }), - ...requestOptions(body), - ...(idempotencyKey === undefined ? {} : { idempotencyKey }), }; } diff --git a/src/leasing/lease-request-book.ts b/src/leasing/lease-request-book.ts index e1bb46f10..8714b1dab 100644 --- a/src/leasing/lease-request-book.ts +++ b/src/leasing/lease-request-book.ts @@ -411,14 +411,18 @@ function storedResult(record: LeaseRequestRecord): Promise /** An omitted field equals only an omitted one: a request naming no mode is not one naming the worker's default. */ function sameDeviceRequest(left: DeviceRequest, right: DeviceRequest): boolean { return ( - left.platform === right.platform && - left.model === right.model && - left.class === right.class && - left.osVersion === right.osVersion && - left.mode === right.mode && - left.imageTag === right.imageTag && - left.baseline === right.baseline && + SAME_DEVICE_FIELDS.every((field) => left[field] === right[field]) && (left.except ?? []).join(",") === (right.except ?? []).join(",") && (left.physical === true) === (right.physical === true) ); } + +const SAME_DEVICE_FIELDS = [ + "platform", + "model", + "class", + "osVersion", + "mode", + "imageTag", + "baseline", +] as const; From f04eeef78aa4efa5bd4648e756863215241156c0 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:55:02 +0100 Subject: [PATCH 15/22] refactor(leasing): the acquisition's timing and request helpers move to their own files, and the dispatcher test helpers to test-dispatcher (ADR 0063) (#1330) --- src/core/registry-except.test.ts | 70 ++ src/core/registry.test.ts | 4 - src/daemon/dispatcher-except.test.ts | 309 ++++++++ src/daemon/dispatcher.test.ts | 710 +------------------ src/daemon/test-dispatcher.ts | 414 +++++++++++ src/leasing/acquisition-requests.ts | 95 +++ src/leasing/acquisition-timing.ts | 55 ++ src/leasing/lease-acquisition-coordinator.ts | 152 +--- 8 files changed, 972 insertions(+), 837 deletions(-) create mode 100644 src/core/registry-except.test.ts create mode 100644 src/daemon/dispatcher-except.test.ts create mode 100644 src/daemon/test-dispatcher.ts create mode 100644 src/leasing/acquisition-requests.ts create mode 100644 src/leasing/acquisition-timing.ts diff --git a/src/core/registry-except.test.ts b/src/core/registry-except.test.ts new file mode 100644 index 000000000..6c0567c9d --- /dev/null +++ b/src/core/registry-except.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from "vitest"; + +import { EventBus } from "../bus/index.js"; +import { FakeClock } from "../ports/index.js"; +import { loadTestRegistry, openTestState } from "./testing.js"; +import type { VirtualSpec } from "./index.js"; + +const spec: VirtualSpec = { + mode: "slim", + model: "iPhone 16", + osVersion: "26.5", + physical: false, + platform: "ios", +}; + +describe("Registry: an except list", () => { + it("keeps the list a lease kept running on its device and on its stored request across a reload, and none where none was named", async () => { + const clock = new FakeClock(1_000); + const state = await openTestState(); + let next = 0; + const load = () => + loadTestRegistry({ + clock, + eventBus: new EventBus(clock), + idGenerator: { generate: () => String((next += 1)) }, + state, + }); + const registry = await load(); + const except = ["store", "other"]; + const lease = async (name: string, withExcept: boolean) => { + const device = await registry.registerDevice({ + driverData: { fakeDeviceId: name }, + driverDeviceId: name, + provisionDuration: 0, + spec, + }); + await registry.transitionDevice(device.id, "ready", { + event: "device.ready", + payload: { bootDuration: 0, deviceId: device.id }, + }); + await registry.createLeaseRequest({ + id: `req_${name}`, + ownerId: "agent", + request: { platform: "ios", ...(withExcept ? { except } : {}) }, + requesterId: name, + }); + await registry.createLease({ + deviceId: device.id, + ...(withExcept ? { except } : {}), + ownerId: "agent", + requesterId: name, + ttlDeadline: 5_000, + ttlMs: 4_000, + }); + return device.id; + }; + const kept = await lease("with", true); + const plain = await lease("without", false); + + const reloaded = await load(); + + const deviceOf = (id: string) => reloaded.snapshot.devices.find((d) => d.id === id); + expect(deviceOf(kept)).toMatchObject({ except }); + expect(deviceOf(plain)).not.toHaveProperty("except"); + const requestOf = (name: string) => + reloaded.leaseRequests().find((record) => record.id === `req_${name}`)?.request; + expect(requestOf("with")).toEqual({ except, platform: "ios" }); + expect(requestOf("without")).toEqual({ platform: "ios" }); + }); +}); diff --git a/src/core/registry.test.ts b/src/core/registry.test.ts index 1ea605aa2..4e306453d 100644 --- a/src/core/registry.test.ts +++ b/src/core/registry.test.ts @@ -363,7 +363,6 @@ describe("Registry", () => { ownerId: "agent-1", request: { class: "phone", - except: ["store", "other"], imageTag: "default", mode: "slim", model: "iPhone 16", @@ -381,7 +380,6 @@ describe("Registry", () => { }); const lease = await registry.createLease({ deviceId: full.id, - except: ["store", "other"], leaseId: "lse_chosen", ownerId: "agent-1", request: { environment: { SIMLOCK_UDID: "abc", OTHER: "x" }, id: "req_granted", timing }, @@ -447,7 +445,6 @@ describe("Registry", () => { createdAt: 1_000, driverData: { fakeDeviceId: "fk-full-booted" }, driverDeviceId: "drv-full", - except: ["store", "other"], foreignProvenanceDetectedAt: 1_012, foreignStateDetectedAt: 1_011, id: full.id, @@ -480,7 +477,6 @@ describe("Registry", () => { ownerId: "agent-1", request: { class: "phone", - except: ["store", "other"], imageTag: "default", mode: "slim", model: "iPhone 16", diff --git a/src/daemon/dispatcher-except.test.ts b/src/daemon/dispatcher-except.test.ts new file mode 100644 index 000000000..6168e2c63 --- /dev/null +++ b/src/daemon/dispatcher-except.test.ts @@ -0,0 +1,309 @@ +import { describe, expect, it, vi } from "vitest"; + +import { readyTransitionUpdate } from "../core/testing.js"; +import { DriverCrashError } from "../core/index.js"; +import { classifyError } from "./error-code.js"; +import { buildDispatcher, session } from "./test-dispatcher.js"; + +/** why: the answer of a request that must settle by itself once the event loop has run to rest; a hang fails here, on a named assertion, rather than by the test's timeout. */ +async function grantedOnceSettled(request: Promise): Promise { + const rest = (async () => { + for (let turn = 0; turn < 50; turn += 1) await new Promise((resolve) => setImmediate(resolve)); + return undefined; + })(); + const answer = await Promise.race([request, rest]); + expect(answer, "the request settled").toBeDefined(); + return answer as T; +} + +/** why: a slim device a worker already holds, ready or shut down, as the warm pool or an earlier lease leaves one. */ +async function seedSlimDevice( + built: Awaited>, + state: "ready" | "shutdown", +) { + const spec = { + mode: "slim", + model: "iPhone 17 Pro", + osVersion: "26.5", + physical: false, + platform: "ios", + } as const; + const driverDevice = await built.driver.provision(spec); + const ready = await built.driver.makeReady(driverDevice, { mode: "slim", purpose: "prepare" }); + const registered = await built.registry.registerDevice({ + driverData: driverDevice.driverData, + driverDeviceId: driverDevice.deviceId, + provisionDuration: 0, + spec, + }); + await built.registry.transitionDevice( + registered.id, + "ready", + { event: "device.ready", payload: { bootDuration: 0, deviceId: registered.id } }, + readyTransitionUpdate(ready), + ); + if (state === "ready") return registered; + await built.driver.shutdown(driverDevice); + await built.registry.transitionDevice(registered.id, "shutdown", { + event: "device.shutdown", + payload: { deviceId: registered.id, initiator: "test" }, + }); + return registered; +} + +describe("Dispatcher: lease.request with an except list", () => { + it("a client leases slim with except and is granted a device reporting it", async () => { + const except = ["store", "other"]; + const ask = { model: "iPhone 17 Pro", platform: "ios", mode: "slim", except } as const; + + const slimmed = await buildDispatcher({ driverOptions: { slimmableOsVersions: ["26.5"] } }); + const granted = await slimmed.dispatcher.dispatch( + "lease.request", + { ...ask, osVersion: "26.5" }, + session(), + ); + const listed = await slimmed.dispatcher.dispatch( + "list.get", + { kind: "devices" }, + session({ role: "admin" }), + ); + const status = await slimmed.dispatcher.dispatch("status.get", {}, session()); + expect(granted.device).toMatchObject({ except, mode: "slim" }); + expect( + slimmed.driver.calls.find((call) => call.operation === "makeReady")?.arguments[1], + ).toMatchObject({ except, mode: "slim", purpose: "prepare" }); + expect( + (listed as { id: string; except?: string[] }[]).find((d) => d.id === granted.device.id), + ).toMatchObject({ except }); + expect(status.devices?.find((d) => d.id === granted.device.id)).toMatchObject({ except }); + expect( + slimmed.eventBus.replay().find((event) => event.event === "lease.requested")?.payload, + ).toMatchObject({ requestSpec: { except } }); + + const warm = await buildDispatcher({ driverOptions: { slimmableOsVersions: ["26.5"] } }); + const registered = await seedSlimDevice(warm, "ready"); + const seededCalls = warm.driver.calls.length; + const grantedWarm = await warm.dispatcher.dispatch( + "lease.request", + { ...ask, osVersion: "26.5" }, + session(), + ); + expect(grantedWarm.device).toMatchObject({ except, id: registered.id, mode: "slim" }); + expect( + warm.driver.calls + .slice(seededCalls) + .filter((call) => call.operation === "shutdown" || call.operation === "makeReady") + .map((call) => call.operation), + ).toEqual(["shutdown", "makeReady"]); + expect( + warm.driver.calls.slice(seededCalls).find((call) => call.operation === "makeReady") + ?.arguments[1], + ).toMatchObject({ except, mode: "slim", purpose: "prepare" }); + expect( + warm.eventBus.replay().find((event) => event.event === "lease.granted")?.payload, + ).toMatchObject({ source: "booted" }); + + const full = await buildDispatcher({ + driverOptions: { availableOsVersions: ["18.4", "26.5"], slimmableOsVersions: ["26.5"] }, + }); + const grantedFull = await full.dispatcher.dispatch( + "lease.request", + { ...ask, osVersion: "18.4" }, + session(), + ); + expect(grantedFull.device.mode).toBe("full"); + expect(grantedFull.device).not.toHaveProperty("except"); + expect( + full.driver.calls.find((call) => call.operation === "makeReady")?.arguments[1], + ).not.toHaveProperty("except"); + }); + + it("a client's except request is refused with BAD_REQUEST and the reason, and a slim baseline on a full-default worker is granted", async () => { + const ask = { + except: ["store"], + mode: "slim", + model: "iPhone 17 Pro", + osVersion: "26.5", + platform: "ios", + } as const; + const { mode: _mode, ...noMode } = ask; + const driverOptions = { slimCategories: ["store", "other"], slimmableOsVersions: ["26.5"] }; + const attempt = async (input: unknown, defaultMode: "slim" | "full" = "slim") => { + const built = await buildDispatcher({ + driverOptions, + engine: { defaultModes: { ios: defaultMode } }, + }); + return built.dispatcher.dispatch("lease.request", input as never, session()).then( + () => undefined, + (error: unknown) => error, + ); + }; + + expect(await attempt(ask)).toBeUndefined(); + const refusals: readonly [string, unknown, string, ("slim" | "full")?][] = [ + ["duplicate", { ...ask, except: ["store", "store"] }, 'except names "store" twice'], + ["bad characters", { ...ask, except: ["Store"] }, 'except: "Store" is not a category name'], + ["none named", { ...ask, except: [] }, "except names 1 to 16 categories"], + [ + "too many", + { ...ask, except: Array.from({ length: 17 }, (_, index) => `c${index}`) }, + "except names 1 to 16 categories", + ], + ["mode full", { ...ask, mode: "full" }, "except needs a slim lease (mode is full)"], + [ + "default full", + noMode, + "except needs a slim lease (this worker's default mode is full)", + "full", + ], + ["physical", { ...ask, physical: true }, "except is for iOS simulators"], + ["android", { ...ask, platform: "android" }, "except is for iOS simulators"], + ["a name the driver refuses", { ...ask, except: ["wallet"] }, ""], + ]; + for (const [label, input, message, defaultMode] of refusals) { + const error = await attempt(input, defaultMode); + expect(classifyError(error), label).toBe("BAD_REQUEST"); + expect((error as Error).message, label).toContain(message); + } + + const { dispatcher } = await buildDispatcher({ + driverOptions, + engine: { defaultModes: { ios: "full" } }, + }); + const save = async (name: string, mode: "slim" | "full", principal: string) => { + const lease = await dispatcher.dispatch( + "lease.request", + { model: "iPhone 17 Pro", mode, osVersion: "26.5", platform: "ios" }, + session({ principal }), + ); + await dispatcher.dispatch( + "baseline.save", + { leaseId: lease.lease.id, name }, + session({ principal, role: "admin" }), + ); + }; + await save("slim-base", "slim", "tok_a"); + await save("full-base", "full", "tok_b"); + const fromFull = await dispatcher + .dispatch( + "lease.request", + { baseline: "full-base", except: ["store"], platform: "ios" }, + session({ principal: "tok_c" }), + ) + .catch((error: unknown) => error); + expect(classifyError(fromFull)).toBe("BAD_REQUEST"); + expect((fromFull as Error).message).toContain( + 'except needs a slim lease (baseline "full-base" is full)', + ); + const fromSlim = await dispatcher.dispatch( + "lease.request", + { baseline: "slim-base", except: ["store"], platform: "ios" }, + session({ principal: "tok_d" }), + ); + expect(fromSlim.device).toMatchObject({ except: ["store"], mode: "slim" }); + }); + + it("a failed except boot is never granted", async () => { + const ask = { + except: ["store"], + mode: "slim", + model: "iPhone 17 Pro", + osVersion: "26.5", + platform: "ios", + } as const; + const crash = new DriverCrashError("simulator never booted"); + const build = () => buildDispatcher({ driverOptions: { slimmableOsVersions: ["26.5"] } }); + + const prepareFails = await build(); + const seededPrepare = await seedSlimDevice(prepareFails, "ready"); + // why: call 1 of makeReady is the seed's own boot; the reboot is call 2. + prepareFails.driver.failOn("makeReady", 2, crash); + const afterPrepare = await grantedOnceSettled( + prepareFails.dispatcher.dispatch("lease.request", ask, session()), + ); + expect(afterPrepare.device.id).not.toBe(seededPrepare.id); + expect(afterPrepare.device).toMatchObject({ except: ask.except, mode: "slim" }); + expect( + prepareFails.registry.snapshot.devices.find((d) => d.id === seededPrepare.id)?.state, + ).toBe("deleted"); + expect( + prepareFails.eventBus + .replay() + .filter((event) => event.event === "lease.granted") + .map((event) => (event.payload as { deviceId: string }).deviceId), + ).toEqual([afterPrepare.device.id]); + + const shutdownFails = await build(); + const seededShutdown = await seedSlimDevice(shutdownFails, "ready"); + shutdownFails.driver.failOn("shutdown", 1, crash); + const afterShutdown = await grantedOnceSettled( + shutdownFails.dispatcher.dispatch("lease.request", ask, session()), + ); + expect(afterShutdown.device.id).not.toBe(seededShutdown.id); + expect( + shutdownFails.registry.snapshot.devices.find((d) => d.id === seededShutdown.id)?.state, + ).toBe("deleted"); + expect( + shutdownFails.eventBus + .replay() + .filter((event) => event.event === "device.shutdown") + .map((event) => event.payload), + ).toContainEqual({ deviceId: seededShutdown.id, initiator: "lease-engine" }); + + const booting = await build(); + const seededShut = await seedSlimDevice(booting, "shutdown"); + const bootedShut = await booting.dispatcher.dispatch("lease.request", ask, session()); + expect(bootedShut.device).toMatchObject({ except: ask.except, id: seededShut.id }); + expect( + booting.driver.calls.filter((call) => call.operation === "makeReady").at(-1)?.arguments[1], + ).toMatchObject({ except: ask.except, purpose: "prepare" }); + expect( + booting.eventBus.replay().find((event) => event.event === "lease.granted")?.payload, + ).toMatchObject({ source: "booted" }); + + const bootFails = await build(); + const seededBootFails = await seedSlimDevice(bootFails, "shutdown"); + bootFails.driver.failOn("makeReady", 2, crash); + const afterBoot = await grantedOnceSettled( + bootFails.dispatcher.dispatch("lease.request", ask, session()), + ); + expect(afterBoot.device.id).not.toBe(seededBootFails.id); + expect( + bootFails.registry.snapshot.devices.find((d) => d.id === seededBootFails.id)?.state, + ).toBe("deleted"); + + const twice = await build(); + twice.driver.failOn("provision", 1, crash); + twice.driver.failOn("makeReady", 1, crash); + const refusal = await twice.dispatcher + .dispatch("lease.request", ask, session()) + .catch((error: unknown) => error); + expect(classifyError(refusal)).toBe("PROVISION_FAILED"); + + const replay = await build(); + const keyed = { ...ask, idempotencyKey: "key-1" }; + const first = await replay.dispatcher.dispatch("lease.request", keyed, session()); + const same = await replay.dispatcher.dispatch("lease.request", keyed, session()); + expect(same.lease.id).toBe(first.lease.id); + const conflict = await replay.dispatcher + .dispatch("lease.request", { ...keyed, except: ["other"] }, session()) + .catch((error: unknown) => error); + expect(classifyError(conflict)).toBe("IDEMPOTENCY_CONFLICT"); + + const rebooting = await build(); + const seededWarm = await seedSlimDevice(rebooting, "ready"); + const before = (await rebooting.dispatcher.dispatch("status.get", {}, session())).capacity; + rebooting.driver.hangMakeReady(); + const pending = rebooting.dispatcher.dispatch("lease.request", ask, session()); + await vi.waitFor(() => { + expect(rebooting.driver.calls.filter((call) => call.operation === "makeReady")).toHaveLength( + 2, + ); + }); + const during = await rebooting.dispatcher.dispatch("status.get", {}, session()); + expect(during.devices?.find((d) => d.id === seededWarm.id)?.state).toBe("ready"); + expect(during.capacity).toEqual(before); + rebooting.driver.releaseMakeReady(); + expect((await pending).device.id).toBe(seededWarm.id); + }); +}); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index d310539c0..4ff665bec 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -1,40 +1,23 @@ -import { testConfig as configWithDefaults } from "../core/testing.js"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { - capacityChangedPayload, - FakeDriver, - loadTestRegistry, - readyTransitionUpdate, - openTestState, - testComponentWiring, - type FakeDriverOptions, - testStateOf, -} from "../core/testing.js"; +import { capacityChangedPayload, FakeDriver, type FakeDriverOptions } from "../core/testing.js"; import type { StateDatabase } from "../state/index.js"; - import { EventBus, type EventEnvelope } from "../bus/index.js"; -import type { EventHistoryHandle } from "../history/index.js"; import { fixedEventHistory, HOUR, plainProjection, removeUsageRigs, requested, - ringEventHistory, T0, usageRig, } from "../history/testing.js"; import { - CleanupReaper, ComponentInstaller, type Config, DiskSpaceGuard, - Doctor, DriverCatalog, - type HostFacts, HostFactsReader, type LatestPresence, - Nuke, PassthroughRefusedError, SerializedDecision, RuntimeMissingError, @@ -49,25 +32,27 @@ import { WORKER_VIEW_REFRESH_INTERVAL_MS, } from "../contract/index.js"; import { - CryptoTokenSecrets, ExecOutputDeliveryStalledError, FakeClock, - FakeSystemStats, MemoryFilesystem, NodeProcessRunner, - FakeKeySetFetcher, - NoopLogger, ScriptedProcessRunner, type ProcessRunner, } from "../ports/index.js"; -import { createAuth, tokensOwner } from "../auth/index.js"; -import { openMemoryStateDatabase } from "../auth/testing.js"; import type { DispatcherOptions, DispatchSession } from "./dispatcher.js"; import { Dispatcher, DispatchError } from "./dispatcher.js"; import { classifyError } from "./error-code.js"; -import { DriverCrashError, UnknownLeaseError } from "../core/index.js"; +import { UnknownLeaseError } from "../core/index.js"; import { RequestCancelledError } from "../leasing/index.js"; -import { createTestEngine, type TestEngine } from "../leasing/testing.js"; +import { + HOST_SYSTEM, + type RecordedPassthrough, + SettableClock, + buildDispatcher, + gibibyte, + recordingResolver, + session, +} from "./test-dispatcher.js"; const threads = vi.hoisted(() => ({ crashOnPost: false, @@ -92,391 +77,6 @@ vi.mock("node:worker_threads", async (importOriginal) => { return { ...actual, Worker: CountingWorker }; }); -const gibibyte = 1024 ** 3; -const HOST_SYSTEM = { arch: "arm64", os: "macOS", osVersion: "15.5" }; - -function resolvePassthroughOverride( - engine: TestEngine, - override: PassthroughResolver | undefined, -): PassthroughResolver { - return override ?? engine; -} - -function stallOptions( - engine: TestEngine, - driver: FakeDriver, - overrides: { - readonly claims?: { isClaimed(deviceId: string): boolean }; - readonly otherStallDrivers?: readonly FakeDriver[]; - }, -) { - return { - claims: overrides.claims ?? engine.claimReader, - drivers: [...(overrides.otherStallDrivers ?? []), driver], - }; -} - -function resolveEventHistoryOverride( - eventBus: EventBus, - override: Pick | undefined, -): Pick { - return override ?? ringEventHistory(eventBus); -} - -function fakePassthroughOptions( - tool: string | undefined, - contextSink: unknown[] | undefined, -): Partial { - if (tool === undefined) return {}; - const options = { - passthrough: (_tool: string, _device: unknown, args: readonly string[], context?: unknown) => { - contextSink?.push(context); - if (args.includes("delete")) { - throw new PassthroughRefusedError( - tool, - "Refusing `simlock simctl delete`: use `simlock release` instead.", - ); - } - return { - args: ["--set", "/root", ...args], - command: tool, - env: { SIMLOCK_SCOPED: "1" }, - }; - }, - passthroughTools: [tool], - }; - return options; -} - -interface RecordedPassthrough { - readonly args: readonly string[]; - readonly context: unknown; - readonly device: unknown; - readonly tool: string; -} - -function recordingResolver( - calls: RecordedPassthrough[], - answer: () => Promise = () => - Promise.resolve({ args: ["list", "devices"], command: "simctl", env: {} }), -): PassthroughResolver { - const resolver = { - passthrough: (tool: string, device: unknown, args: readonly string[], context?: unknown) => { - calls.push({ args, context, device, tool }); - return answer(); - }, - }; - return resolver as unknown as PassthroughResolver; -} - -class SettableClock extends FakeClock { - #offset = 0; - - setBack(ms: number): void { - this.#offset -= ms; - } - - override now(): number { - return super.now() + this.#offset; - } -} - -function withGatewayLabel(config: Config, label: string | undefined): Config { - return label === undefined ? config : { ...config, gateway: { ...config.gateway, label } }; -} - -function withHttp(config: Config, http: Config["http"] | undefined): Config { - return http === undefined ? config : { ...config, http }; -} - -interface SeededPhysicalDevice { - readonly createdAt: number; - readonly driverDeviceId: string; - readonly enrolledApps: readonly string[]; - readonly id: string; - readonly lastLeaseEndedAt?: number; - readonly reclaimingSince?: number; - readonly spec: { readonly class: string; readonly model: string; readonly osVersion: string }; - readonly state: string; -} - -function seedPhysicalDevices(state: StateDatabase, devices: readonly SeededPhysicalDevice[]): void { - for (const device of devices) { - state.database - .prepare( - "INSERT INTO devices (id, platform, physical, driver_device_id, state, model, os_version, class, created_at, last_lease_ended_at, reclaiming_since) VALUES (?, 'ios', 1, ?, ?, ?, ?, ?, ?, ?, ?)", - ) - .run( - device.id, - device.driverDeviceId, - device.state, - device.spec.model, - device.spec.osVersion, - device.spec.class, - device.createdAt, - device.lastLeaseEndedAt ?? null, - device.reclaimingSince ?? null, - ); - device.enrolledApps.forEach((app, position) => { - state.database - .prepare("INSERT INTO device_enrolled_apps (device_id, position, app) VALUES (?, ?, ?)") - .run(device.id, position, app); - }); - } -} - -// fallow-ignore-next-line complexity -- one test harness builder; each option is a plain pass-through to a collaborator. -async function buildDispatcher( - overrides: { - readonly downloadsPolicy?: Config["downloads"]["policy"]; - readonly driverOptions?: Partial; - readonly awaitReady?: () => Promise; - readonly catalog?: CatalogReader; - readonly includeNuke?: boolean; - readonly warmKinds?: DispatcherOptions["warmKinds"]; - readonly includeEnrollment?: boolean; - readonly passthroughTool?: string; - readonly lease?: Partial; - readonly processRunner?: ProcessRunner; - readonly exec?: Partial; - readonly passthroughContextSink?: unknown[]; - readonly clock?: FakeClock; - readonly passthroughOverride?: PassthroughResolver; - readonly execEnv?: NodeJS.ProcessEnv; - readonly eventHistory?: Pick; - readonly historyPath?: string; - readonly withoutTokens?: boolean; - /** why: a daemon wired without the baseline service. */ - readonly withoutBaselines?: boolean; - readonly hostFacts?: () => HostFacts; - readonly capacity?: Config["capacity"]; - readonly warmPool?: Partial; - /** why: the two boot deadlines `config.get` reports. */ - readonly bootTimeouts?: { readonly iosFull: number; readonly android: number }; - readonly components?: Pick< - ComponentInstaller, - "claimProvision" | "inProgress" | "install" | "list" | "remove" - >; - readonly health?: "starting" | "running" | "failed"; - readonly gatewayLabel?: string; - readonly http?: Config["http"]; - readonly claims?: { isClaimed(deviceId: string): boolean }; - readonly otherStallDrivers?: readonly FakeDriver[]; - /** why: a second platform's driver for the leasing engine, for a test that leases on both. */ - readonly extraDrivers?: readonly FakeDriver[]; - readonly engine?: Pick[0], "defaultModes">; - readonly physicalDevices?: readonly SeededPhysicalDevice[]; - /** why: rows a test writes to `state.db` before the registry loads. */ - readonly seedState?: (state: StateDatabase) => void; - readonly presence?: (driverDeviceId: string) => LatestPresence | undefined; - readonly capabilitySources?: DispatcherOptions["capabilitySources"]; - readonly load?: DispatcherOptions["load"]; - readonly driverRejections?: ConstructorParameters[0]["driverRejections"]; - } = {}, -) { - const clock = overrides.clock ?? new FakeClock(1_000); - const eventBus = new EventBus(clock); - const filesystem = new MemoryFilesystem(); - const state = await openTestState(); - seedPhysicalDevices(state, overrides.physicalDevices ?? []); - overrides.seedState?.(state); - const registry = await loadTestRegistry({ - clock, - eventBus, - idGenerator: sequence(), - state, - }); - const driver = new FakeDriver({ - availableOsVersions: ["26.5"], - clock, - platform: "ios", - ...overrides.driverOptions, - ...fakePassthroughOptions(overrides.passthroughTool, overrides.passthroughContextSink), - }); - const baseConfig = withHttp( - withGatewayLabel( - testConfig( - overrides.downloadsPolicy, - overrides.lease ?? {}, - overrides.exec ?? {}, - overrides.capacity, - ), - overrides.gatewayLabel, - ), - overrides.http, - ); - const config: Config = { - ...baseConfig, - warmPool: { ...baseConfig.warmPool, ...overrides.warmPool }, - ...(overrides.bootTimeouts === undefined - ? {} - : { - android: { ...baseConfig.android, bootTimeoutMs: overrides.bootTimeouts.android }, - ios: { ...baseConfig.ios, full: { bootTimeoutMs: overrides.bootTimeouts.iosFull } }, - }), - }; - const wiring = testComponentWiring({ - clock: clock, - components: overrides.components, - drivers: [driver, ...(overrides.extraDrivers ?? [])], - eventBus: eventBus, - registry: registry, - }); - const engine = createTestEngine({ - ...wiring, - clock, - config, - ...overrides.engine, - drivers: [driver, ...(overrides.extraDrivers ?? [])], - eventBus, - idGenerator: sequence(), - registry, - state: testStateOf(registry), - systemStats: new FakeSystemStats({ - cpuCount: 8, - totalRamBytes: 32 * gibibyte, - }), - }); - const reaper = new CleanupReaper({ - clock, - config, - eventBus, - executor: engine.cleanup, - filesystem, - registry, - }); - const doctor = new Doctor({ - baselines: engine.core.baselines, - decisions: wiring.decisions, - claims: engine.claimReader, - clock, - config, - drivers: [driver], - ...(overrides.driverRejections === undefined - ? {} - : { driverRejections: overrides.driverRejections }), - eventBus, - leaseExpirer: engine, - quarantine: engine.core.quarantine, - registry, - }); - const { tokens } = createAuth({ - clock, - config: { enabled: false, host: "127.0.0.1", port: 4700 }, - dataDirectory: "/", - database: (await openMemoryStateDatabase([tokensOwner])).database, - filesystem, - idGenerator: sequence(), - keySetFetcher: new FakeKeySetFetcher(), - logger: new NoopLogger(), - secrets: new CryptoTokenSecrets(), - }); - const dispatcher = new Dispatcher({ - awaitReady: overrides.awaitReady ?? (() => Promise.resolve()), - ...(overrides.capabilitySources === undefined - ? {} - : { capabilitySources: overrides.capabilitySources }), - capacity: engine, - warmPool: engine, - ...(overrides.withoutBaselines === true ? {} : { baselines: engine.core.baselines }), - deviceModes: engine, - catalog: overrides.catalog ?? engine, - clock, - components: wiring.components, - config, - doctor, - eventBus, - eventHistory: resolveEventHistoryOverride(eventBus, overrides.eventHistory), - ...(overrides.historyPath === undefined ? {} : { historyPath: overrides.historyPath }), - health: () => overrides.health ?? "running", - hostFacts: overrides.hostFacts ?? (() => ({ ...HOST_SYSTEM, tools: [] })), - instanceId: "instance-1", - leases: engine, - ...(overrides.load === undefined ? {} : { load: overrides.load }), - ...(overrides.includeNuke === true ? { nuke: new Nuke({ executor: engine, registry }) } : {}), - ...(overrides.warmKinds === undefined ? {} : { warmKinds: overrides.warmKinds }), - ...(overrides.includeEnrollment === true ? { enrollment: engine.core.enrollment } : {}), - passthrough: resolvePassthroughOverride(engine, overrides.passthroughOverride), - ...(overrides.processRunner === undefined ? {} : { processRunner: overrides.processRunner }), - execEnv: overrides.execEnv ?? { PATH: "/usr/bin" }, - queue: engine, - ...(overrides.presence === undefined ? {} : { presence: overrides.presence }), - reaper, - registry, - stalls: stallOptions(engine, driver, overrides), - ...(overrides.withoutTokens === true ? {} : { tokens }), - version: "1.2.3", - }); - return { - clock, - components: wiring.components, - dispatcher, - doctor, - driver, - engine, - eventBus, - registry, - state, - tokens, - }; -} - -/** why: the answer of a request that must settle by itself once the event loop has run to rest; a hang fails here, on a named assertion, rather than by the test's timeout. */ -async function grantedOnceSettled(request: Promise): Promise { - const rest = (async () => { - for (let turn = 0; turn < 50; turn += 1) await new Promise((resolve) => setImmediate(resolve)); - return undefined; - })(); - const answer = await Promise.race([request, rest]); - expect(answer, "the request settled").toBeDefined(); - return answer as T; -} - -/** why: a slim device a worker already holds, ready or shut down, as the warm pool or an earlier lease leaves one. */ -async function seedSlimDevice( - built: Awaited>, - state: "ready" | "shutdown", -) { - const spec = { - mode: "slim", - model: "iPhone 17 Pro", - osVersion: "26.5", - physical: false, - platform: "ios", - } as const; - const driverDevice = await built.driver.provision(spec); - const ready = await built.driver.makeReady(driverDevice, { mode: "slim", purpose: "prepare" }); - const registered = await built.registry.registerDevice({ - driverData: driverDevice.driverData, - driverDeviceId: driverDevice.deviceId, - provisionDuration: 0, - spec, - }); - await built.registry.transitionDevice( - registered.id, - "ready", - { event: "device.ready", payload: { bootDuration: 0, deviceId: registered.id } }, - readyTransitionUpdate(ready), - ); - if (state === "ready") return registered; - await built.driver.shutdown(driverDevice); - await built.registry.transitionDevice(registered.id, "shutdown", { - event: "device.shutdown", - payload: { deviceId: registered.id, initiator: "test" }, - }); - return registered; -} - -function session(overrides: Partial = {}): DispatchSession { - return { - manageEventSubscription: () => undefined, - via: "socket", - principal: "tok_agent", - role: "agent", - ...overrides, - }; -} - describe("Dispatcher: parsing", () => { it("rejects a malformed input with BAD_REQUEST before the handler runs", async () => { const { dispatcher, registry } = await buildDispatcher(); @@ -2914,261 +2514,6 @@ describe("Dispatcher: device mode on every surface", () => { }); }); - it("a client leases slim with except and is granted a device reporting it", async () => { - const except = ["store", "other"]; - const ask = { model: "iPhone 17 Pro", platform: "ios", mode: "slim", except } as const; - - const slimmed = await buildDispatcher({ driverOptions: { slimmableOsVersions: ["26.5"] } }); - const granted = await slimmed.dispatcher.dispatch( - "lease.request", - { ...ask, osVersion: "26.5" }, - session(), - ); - const listed = await slimmed.dispatcher.dispatch( - "list.get", - { kind: "devices" }, - session({ role: "admin" }), - ); - const status = await slimmed.dispatcher.dispatch("status.get", {}, session()); - expect(granted.device).toMatchObject({ except, mode: "slim" }); - expect( - slimmed.driver.calls.find((call) => call.operation === "makeReady")?.arguments[1], - ).toMatchObject({ except, mode: "slim", purpose: "prepare" }); - expect( - (listed as { id: string; except?: string[] }[]).find((d) => d.id === granted.device.id), - ).toMatchObject({ except }); - expect(status.devices?.find((d) => d.id === granted.device.id)).toMatchObject({ except }); - expect( - slimmed.eventBus.replay().find((event) => event.event === "lease.requested")?.payload, - ).toMatchObject({ requestSpec: { except } }); - - const warm = await buildDispatcher({ driverOptions: { slimmableOsVersions: ["26.5"] } }); - const registered = await seedSlimDevice(warm, "ready"); - const seededCalls = warm.driver.calls.length; - const grantedWarm = await warm.dispatcher.dispatch( - "lease.request", - { ...ask, osVersion: "26.5" }, - session(), - ); - expect(grantedWarm.device).toMatchObject({ except, id: registered.id, mode: "slim" }); - expect( - warm.driver.calls - .slice(seededCalls) - .filter((call) => call.operation === "shutdown" || call.operation === "makeReady") - .map((call) => call.operation), - ).toEqual(["shutdown", "makeReady"]); - expect( - warm.driver.calls.slice(seededCalls).find((call) => call.operation === "makeReady") - ?.arguments[1], - ).toMatchObject({ except, mode: "slim", purpose: "prepare" }); - expect( - warm.eventBus.replay().find((event) => event.event === "lease.granted")?.payload, - ).toMatchObject({ source: "booted" }); - - const full = await buildDispatcher({ - driverOptions: { availableOsVersions: ["18.4", "26.5"], slimmableOsVersions: ["26.5"] }, - }); - const grantedFull = await full.dispatcher.dispatch( - "lease.request", - { ...ask, osVersion: "18.4" }, - session(), - ); - expect(grantedFull.device.mode).toBe("full"); - expect(grantedFull.device).not.toHaveProperty("except"); - expect( - full.driver.calls.find((call) => call.operation === "makeReady")?.arguments[1], - ).not.toHaveProperty("except"); - }); - - it("a client's except request is refused with BAD_REQUEST and the reason, and a slim baseline on a full-default worker is granted", async () => { - const ask = { - except: ["store"], - mode: "slim", - model: "iPhone 17 Pro", - osVersion: "26.5", - platform: "ios", - } as const; - const { mode: _mode, ...noMode } = ask; - const driverOptions = { slimCategories: ["store", "other"], slimmableOsVersions: ["26.5"] }; - const attempt = async (input: unknown, defaultMode: "slim" | "full" = "slim") => { - const built = await buildDispatcher({ - driverOptions, - engine: { defaultModes: { ios: defaultMode } }, - }); - return built.dispatcher.dispatch("lease.request", input as never, session()).then( - () => undefined, - (error: unknown) => error, - ); - }; - - expect(await attempt(ask)).toBeUndefined(); - const refusals: readonly [string, unknown, string, ("slim" | "full")?][] = [ - ["duplicate", { ...ask, except: ["store", "store"] }, 'except names "store" twice'], - ["bad characters", { ...ask, except: ["Store"] }, 'except: "Store" is not a category name'], - ["none named", { ...ask, except: [] }, "except names 1 to 16 categories"], - [ - "too many", - { ...ask, except: Array.from({ length: 17 }, (_, index) => `c${index}`) }, - "except names 1 to 16 categories", - ], - ["mode full", { ...ask, mode: "full" }, "except needs a slim lease (mode is full)"], - [ - "default full", - noMode, - "except needs a slim lease (this worker's default mode is full)", - "full", - ], - ["physical", { ...ask, physical: true }, "except is for iOS simulators"], - ["android", { ...ask, platform: "android" }, "except is for iOS simulators"], - ["a name the driver refuses", { ...ask, except: ["wallet"] }, ""], - ]; - for (const [label, input, message, defaultMode] of refusals) { - const error = await attempt(input, defaultMode); - expect(classifyError(error), label).toBe("BAD_REQUEST"); - expect((error as Error).message, label).toContain(message); - } - - const { dispatcher } = await buildDispatcher({ - driverOptions, - engine: { defaultModes: { ios: "full" } }, - }); - const save = async (name: string, mode: "slim" | "full", principal: string) => { - const lease = await dispatcher.dispatch( - "lease.request", - { model: "iPhone 17 Pro", mode, osVersion: "26.5", platform: "ios" }, - session({ principal }), - ); - await dispatcher.dispatch( - "baseline.save", - { leaseId: lease.lease.id, name }, - session({ principal, role: "admin" }), - ); - }; - await save("slim-base", "slim", "tok_a"); - await save("full-base", "full", "tok_b"); - const fromFull = await dispatcher - .dispatch( - "lease.request", - { baseline: "full-base", except: ["store"], platform: "ios" }, - session({ principal: "tok_c" }), - ) - .catch((error: unknown) => error); - expect(classifyError(fromFull)).toBe("BAD_REQUEST"); - expect((fromFull as Error).message).toContain( - 'except needs a slim lease (baseline "full-base" is full)', - ); - const fromSlim = await dispatcher.dispatch( - "lease.request", - { baseline: "slim-base", except: ["store"], platform: "ios" }, - session({ principal: "tok_d" }), - ); - expect(fromSlim.device).toMatchObject({ except: ["store"], mode: "slim" }); - }); - - it("a failed except boot is never granted", async () => { - const ask = { - except: ["store"], - mode: "slim", - model: "iPhone 17 Pro", - osVersion: "26.5", - platform: "ios", - } as const; - const crash = new DriverCrashError("simulator never booted"); - const build = () => buildDispatcher({ driverOptions: { slimmableOsVersions: ["26.5"] } }); - - const prepareFails = await build(); - const seededPrepare = await seedSlimDevice(prepareFails, "ready"); - // why: call 1 of makeReady is the seed's own boot; the reboot is call 2. - prepareFails.driver.failOn("makeReady", 2, crash); - const afterPrepare = await grantedOnceSettled( - prepareFails.dispatcher.dispatch("lease.request", ask, session()), - ); - expect(afterPrepare.device.id).not.toBe(seededPrepare.id); - expect(afterPrepare.device).toMatchObject({ except: ask.except, mode: "slim" }); - expect( - prepareFails.registry.snapshot.devices.find((d) => d.id === seededPrepare.id)?.state, - ).toBe("deleted"); - expect( - prepareFails.eventBus - .replay() - .filter((event) => event.event === "lease.granted") - .map((event) => (event.payload as { deviceId: string }).deviceId), - ).toEqual([afterPrepare.device.id]); - - const shutdownFails = await build(); - const seededShutdown = await seedSlimDevice(shutdownFails, "ready"); - shutdownFails.driver.failOn("shutdown", 1, crash); - const afterShutdown = await grantedOnceSettled( - shutdownFails.dispatcher.dispatch("lease.request", ask, session()), - ); - expect(afterShutdown.device.id).not.toBe(seededShutdown.id); - expect( - shutdownFails.registry.snapshot.devices.find((d) => d.id === seededShutdown.id)?.state, - ).toBe("deleted"); - expect( - shutdownFails.eventBus - .replay() - .filter((event) => event.event === "device.shutdown") - .map((event) => event.payload), - ).toContainEqual({ deviceId: seededShutdown.id, initiator: "lease-engine" }); - - const booting = await build(); - const seededShut = await seedSlimDevice(booting, "shutdown"); - const bootedShut = await booting.dispatcher.dispatch("lease.request", ask, session()); - expect(bootedShut.device).toMatchObject({ except: ask.except, id: seededShut.id }); - expect( - booting.driver.calls.filter((call) => call.operation === "makeReady").at(-1)?.arguments[1], - ).toMatchObject({ except: ask.except, purpose: "prepare" }); - expect( - booting.eventBus.replay().find((event) => event.event === "lease.granted")?.payload, - ).toMatchObject({ source: "booted" }); - - const bootFails = await build(); - const seededBootFails = await seedSlimDevice(bootFails, "shutdown"); - bootFails.driver.failOn("makeReady", 2, crash); - const afterBoot = await grantedOnceSettled( - bootFails.dispatcher.dispatch("lease.request", ask, session()), - ); - expect(afterBoot.device.id).not.toBe(seededBootFails.id); - expect( - bootFails.registry.snapshot.devices.find((d) => d.id === seededBootFails.id)?.state, - ).toBe("deleted"); - - const twice = await build(); - twice.driver.failOn("provision", 1, crash); - twice.driver.failOn("makeReady", 1, crash); - const refusal = await twice.dispatcher - .dispatch("lease.request", ask, session()) - .catch((error: unknown) => error); - expect(classifyError(refusal)).toBe("PROVISION_FAILED"); - - const replay = await build(); - const keyed = { ...ask, idempotencyKey: "key-1" }; - const first = await replay.dispatcher.dispatch("lease.request", keyed, session()); - const same = await replay.dispatcher.dispatch("lease.request", keyed, session()); - expect(same.lease.id).toBe(first.lease.id); - const conflict = await replay.dispatcher - .dispatch("lease.request", { ...keyed, except: ["other"] }, session()) - .catch((error: unknown) => error); - expect(classifyError(conflict)).toBe("IDEMPOTENCY_CONFLICT"); - - const rebooting = await build(); - const seededWarm = await seedSlimDevice(rebooting, "ready"); - const before = (await rebooting.dispatcher.dispatch("status.get", {}, session())).capacity; - rebooting.driver.hangMakeReady(); - const pending = rebooting.dispatcher.dispatch("lease.request", ask, session()); - await vi.waitFor(() => { - expect(rebooting.driver.calls.filter((call) => call.operation === "makeReady")).toHaveLength( - 2, - ); - }); - const during = await rebooting.dispatcher.dispatch("status.get", {}, session()); - expect(during.devices?.find((d) => d.id === seededWarm.id)?.state).toBe("ready"); - expect(during.capacity).toEqual(before); - rebooting.driver.releaseMakeReady(); - expect((await pending).device.id).toBe(seededWarm.id); - }); - it("status.get and list.get return mode for every device, including one still provisioning", async () => { const { dispatcher, registry } = await buildDispatcher({ driverOptions: { mode: "slim" } }); const granted = await dispatcher.dispatch("lease.request", request, session()); @@ -5670,39 +5015,6 @@ class SettleOnCueHandle { } } -function sequence() { - let next = 1; - return { generate: () => `${next++}` }; -} - -function testConfig( - downloadsPolicy: Config["downloads"]["policy"] = "on-request", - leaseOverrides: Partial = {}, - execOverrides: Partial = {}, - capacity: Config["capacity"] = { - strategy: "resource", - config: { - limits: { - android: { maxDevices: 1, maxRunning: 1 }, - ios: { maxDevices: 2, maxRunning: 2 }, - maxRunning: 3, - }, - ramBudget: { androidBytesPerDevice: 4 * gibibyte, iosBytesPerDevice: gibibyte }, - }, - }, -): Config { - return configWithDefaults({ - capacity, - downloads: { policy: downloadsPolicy }, - eventBuffer: { capacity: 100 }, - exec: execOverrides, - http: { enabled: false, port: 4700 }, - idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, - lease: { defaultTtlMs: 60_000, maxTtlMs: 3_600_000, ...leaseOverrides }, - warmPool: { maxConcurrentBoots: 1 }, - }); -} - describe("Dispatcher: device.add and device.remove", () => { const admin = () => session({ principal: "tok_operator", role: "admin" }); const UDID = "00008110-001A2B3C4D5E"; diff --git a/src/daemon/test-dispatcher.ts b/src/daemon/test-dispatcher.ts new file mode 100644 index 000000000..f086eeb90 --- /dev/null +++ b/src/daemon/test-dispatcher.ts @@ -0,0 +1,414 @@ +import { testConfig as configWithDefaults } from "../core/testing.js"; +import { + FakeDriver, + loadTestRegistry, + openTestState, + testComponentWiring, + type FakeDriverOptions, + testStateOf, +} from "../core/testing.js"; +import type { StateDatabase } from "../state/index.js"; +import { EventBus } from "../bus/index.js"; +import type { EventHistoryHandle } from "../history/index.js"; +import { ringEventHistory } from "../history/testing.js"; +import { + CleanupReaper, + ComponentInstaller, + type Config, + Doctor, + type HostFacts, + type LatestPresence, + Nuke, + PassthroughRefusedError, + type CatalogReader, + type PassthroughResolver, +} from "../core/index.js"; +import { + CryptoTokenSecrets, + FakeClock, + FakeSystemStats, + MemoryFilesystem, + FakeKeySetFetcher, + NoopLogger, + type ProcessRunner, +} from "../ports/index.js"; +import { createAuth, tokensOwner } from "../auth/index.js"; +import { openMemoryStateDatabase } from "../auth/testing.js"; +import type { DispatcherOptions, DispatchSession } from "./dispatcher.js"; +import { Dispatcher } from "./dispatcher.js"; +import { createTestEngine, type TestEngine } from "../leasing/testing.js"; + +export const gibibyte = 1024 ** 3; +export const HOST_SYSTEM = { arch: "arm64", os: "macOS", osVersion: "15.5" }; + +export function resolvePassthroughOverride( + engine: TestEngine, + override: PassthroughResolver | undefined, +): PassthroughResolver { + return override ?? engine; +} + +export function stallOptions( + engine: TestEngine, + driver: FakeDriver, + overrides: { + readonly claims?: { isClaimed(deviceId: string): boolean }; + readonly otherStallDrivers?: readonly FakeDriver[]; + }, +) { + return { + claims: overrides.claims ?? engine.claimReader, + drivers: [...(overrides.otherStallDrivers ?? []), driver], + }; +} + +export function resolveEventHistoryOverride( + eventBus: EventBus, + override: Pick | undefined, +): Pick { + return override ?? ringEventHistory(eventBus); +} + +export function fakePassthroughOptions( + tool: string | undefined, + contextSink: unknown[] | undefined, +): Partial { + if (tool === undefined) return {}; + const options = { + passthrough: (_tool: string, _device: unknown, args: readonly string[], context?: unknown) => { + contextSink?.push(context); + if (args.includes("delete")) { + throw new PassthroughRefusedError( + tool, + "Refusing `simlock simctl delete`: use `simlock release` instead.", + ); + } + return { + args: ["--set", "/root", ...args], + command: tool, + env: { SIMLOCK_SCOPED: "1" }, + }; + }, + passthroughTools: [tool], + }; + return options; +} + +export interface RecordedPassthrough { + readonly args: readonly string[]; + readonly context: unknown; + readonly device: unknown; + readonly tool: string; +} + +export function recordingResolver( + calls: RecordedPassthrough[], + answer: () => Promise = () => + Promise.resolve({ args: ["list", "devices"], command: "simctl", env: {} }), +): PassthroughResolver { + const resolver = { + passthrough: (tool: string, device: unknown, args: readonly string[], context?: unknown) => { + calls.push({ args, context, device, tool }); + return answer(); + }, + }; + return resolver as unknown as PassthroughResolver; +} + +export class SettableClock extends FakeClock { + #offset = 0; + + setBack(ms: number): void { + this.#offset -= ms; + } + + override now(): number { + return super.now() + this.#offset; + } +} + +export function withGatewayLabel(config: Config, label: string | undefined): Config { + return label === undefined ? config : { ...config, gateway: { ...config.gateway, label } }; +} + +export function withHttp(config: Config, http: Config["http"] | undefined): Config { + return http === undefined ? config : { ...config, http }; +} + +export interface SeededPhysicalDevice { + readonly createdAt: number; + readonly driverDeviceId: string; + readonly enrolledApps: readonly string[]; + readonly id: string; + readonly lastLeaseEndedAt?: number; + readonly reclaimingSince?: number; + readonly spec: { readonly class: string; readonly model: string; readonly osVersion: string }; + readonly state: string; +} + +export function seedPhysicalDevices( + state: StateDatabase, + devices: readonly SeededPhysicalDevice[], +): void { + for (const device of devices) { + state.database + .prepare( + "INSERT INTO devices (id, platform, physical, driver_device_id, state, model, os_version, class, created_at, last_lease_ended_at, reclaiming_since) VALUES (?, 'ios', 1, ?, ?, ?, ?, ?, ?, ?, ?)", + ) + .run( + device.id, + device.driverDeviceId, + device.state, + device.spec.model, + device.spec.osVersion, + device.spec.class, + device.createdAt, + device.lastLeaseEndedAt ?? null, + device.reclaimingSince ?? null, + ); + device.enrolledApps.forEach((app, position) => { + state.database + .prepare("INSERT INTO device_enrolled_apps (device_id, position, app) VALUES (?, ?, ?)") + .run(device.id, position, app); + }); + } +} + +// fallow-ignore-next-line complexity -- one test harness builder; each option is a plain pass-through to a collaborator. +export async function buildDispatcher( + overrides: { + readonly downloadsPolicy?: Config["downloads"]["policy"]; + readonly driverOptions?: Partial; + readonly awaitReady?: () => Promise; + readonly catalog?: CatalogReader; + readonly includeNuke?: boolean; + readonly warmKinds?: DispatcherOptions["warmKinds"]; + readonly includeEnrollment?: boolean; + readonly passthroughTool?: string; + readonly lease?: Partial; + readonly processRunner?: ProcessRunner; + readonly exec?: Partial; + readonly passthroughContextSink?: unknown[]; + readonly clock?: FakeClock; + readonly passthroughOverride?: PassthroughResolver; + readonly execEnv?: NodeJS.ProcessEnv; + readonly eventHistory?: Pick; + readonly historyPath?: string; + readonly withoutTokens?: boolean; + /** why: a daemon wired without the baseline service. */ + readonly withoutBaselines?: boolean; + readonly hostFacts?: () => HostFacts; + readonly capacity?: Config["capacity"]; + readonly warmPool?: Partial; + /** why: the two boot deadlines `config.get` reports. */ + readonly bootTimeouts?: { readonly iosFull: number; readonly android: number }; + readonly components?: Pick< + ComponentInstaller, + "claimProvision" | "inProgress" | "install" | "list" | "remove" + >; + readonly health?: "starting" | "running" | "failed"; + readonly gatewayLabel?: string; + readonly http?: Config["http"]; + readonly claims?: { isClaimed(deviceId: string): boolean }; + readonly otherStallDrivers?: readonly FakeDriver[]; + /** why: a second platform's driver for the leasing engine, for a test that leases on both. */ + readonly extraDrivers?: readonly FakeDriver[]; + readonly engine?: Pick[0], "defaultModes">; + readonly physicalDevices?: readonly SeededPhysicalDevice[]; + /** why: rows a test writes to `state.db` before the registry loads. */ + readonly seedState?: (state: StateDatabase) => void; + readonly presence?: (driverDeviceId: string) => LatestPresence | undefined; + readonly capabilitySources?: DispatcherOptions["capabilitySources"]; + readonly load?: DispatcherOptions["load"]; + readonly driverRejections?: ConstructorParameters[0]["driverRejections"]; + } = {}, +) { + const clock = overrides.clock ?? new FakeClock(1_000); + const eventBus = new EventBus(clock); + const filesystem = new MemoryFilesystem(); + const state = await openTestState(); + seedPhysicalDevices(state, overrides.physicalDevices ?? []); + overrides.seedState?.(state); + const registry = await loadTestRegistry({ + clock, + eventBus, + idGenerator: sequence(), + state, + }); + const driver = new FakeDriver({ + availableOsVersions: ["26.5"], + clock, + platform: "ios", + ...overrides.driverOptions, + ...fakePassthroughOptions(overrides.passthroughTool, overrides.passthroughContextSink), + }); + const baseConfig = withHttp( + withGatewayLabel( + testConfig( + overrides.downloadsPolicy, + overrides.lease ?? {}, + overrides.exec ?? {}, + overrides.capacity, + ), + overrides.gatewayLabel, + ), + overrides.http, + ); + const config: Config = { + ...baseConfig, + warmPool: { ...baseConfig.warmPool, ...overrides.warmPool }, + ...(overrides.bootTimeouts === undefined + ? {} + : { + android: { ...baseConfig.android, bootTimeoutMs: overrides.bootTimeouts.android }, + ios: { ...baseConfig.ios, full: { bootTimeoutMs: overrides.bootTimeouts.iosFull } }, + }), + }; + const wiring = testComponentWiring({ + clock: clock, + components: overrides.components, + drivers: [driver, ...(overrides.extraDrivers ?? [])], + eventBus: eventBus, + registry: registry, + }); + const engine = createTestEngine({ + ...wiring, + clock, + config, + ...overrides.engine, + drivers: [driver, ...(overrides.extraDrivers ?? [])], + eventBus, + idGenerator: sequence(), + registry, + state: testStateOf(registry), + systemStats: new FakeSystemStats({ + cpuCount: 8, + totalRamBytes: 32 * gibibyte, + }), + }); + const reaper = new CleanupReaper({ + clock, + config, + eventBus, + executor: engine.cleanup, + filesystem, + registry, + }); + const doctor = new Doctor({ + baselines: engine.core.baselines, + decisions: wiring.decisions, + claims: engine.claimReader, + clock, + config, + drivers: [driver], + ...(overrides.driverRejections === undefined + ? {} + : { driverRejections: overrides.driverRejections }), + eventBus, + leaseExpirer: engine, + quarantine: engine.core.quarantine, + registry, + }); + const { tokens } = createAuth({ + clock, + config: { enabled: false, host: "127.0.0.1", port: 4700 }, + dataDirectory: "/", + database: (await openMemoryStateDatabase([tokensOwner])).database, + filesystem, + idGenerator: sequence(), + keySetFetcher: new FakeKeySetFetcher(), + logger: new NoopLogger(), + secrets: new CryptoTokenSecrets(), + }); + const dispatcher = new Dispatcher({ + awaitReady: overrides.awaitReady ?? (() => Promise.resolve()), + ...(overrides.capabilitySources === undefined + ? {} + : { capabilitySources: overrides.capabilitySources }), + capacity: engine, + warmPool: engine, + ...(overrides.withoutBaselines === true ? {} : { baselines: engine.core.baselines }), + deviceModes: engine, + catalog: overrides.catalog ?? engine, + clock, + components: wiring.components, + config, + doctor, + eventBus, + eventHistory: resolveEventHistoryOverride(eventBus, overrides.eventHistory), + ...(overrides.historyPath === undefined ? {} : { historyPath: overrides.historyPath }), + health: () => overrides.health ?? "running", + hostFacts: overrides.hostFacts ?? (() => ({ ...HOST_SYSTEM, tools: [] })), + instanceId: "instance-1", + leases: engine, + ...(overrides.load === undefined ? {} : { load: overrides.load }), + ...(overrides.includeNuke === true ? { nuke: new Nuke({ executor: engine, registry }) } : {}), + ...(overrides.warmKinds === undefined ? {} : { warmKinds: overrides.warmKinds }), + ...(overrides.includeEnrollment === true ? { enrollment: engine.core.enrollment } : {}), + passthrough: resolvePassthroughOverride(engine, overrides.passthroughOverride), + ...(overrides.processRunner === undefined ? {} : { processRunner: overrides.processRunner }), + execEnv: overrides.execEnv ?? { PATH: "/usr/bin" }, + queue: engine, + ...(overrides.presence === undefined ? {} : { presence: overrides.presence }), + reaper, + registry, + stalls: stallOptions(engine, driver, overrides), + ...(overrides.withoutTokens === true ? {} : { tokens }), + version: "1.2.3", + }); + return { + clock, + components: wiring.components, + dispatcher, + doctor, + driver, + engine, + eventBus, + registry, + state, + tokens, + }; +} + +export function session(overrides: Partial = {}): DispatchSession { + return { + manageEventSubscription: () => undefined, + via: "socket", + principal: "tok_agent", + role: "agent", + ...overrides, + }; +} + +export function sequence() { + let next = 1; + return { generate: () => `${next++}` }; +} + +export function testConfig( + downloadsPolicy: Config["downloads"]["policy"] = "on-request", + leaseOverrides: Partial = {}, + execOverrides: Partial = {}, + capacity: Config["capacity"] = { + strategy: "resource", + config: { + limits: { + android: { maxDevices: 1, maxRunning: 1 }, + ios: { maxDevices: 2, maxRunning: 2 }, + maxRunning: 3, + }, + ramBudget: { androidBytesPerDevice: 4 * gibibyte, iosBytesPerDevice: gibibyte }, + }, + }, +): Config { + return configWithDefaults({ + capacity, + downloads: { policy: downloadsPolicy }, + eventBuffer: { capacity: 100 }, + exec: execOverrides, + http: { enabled: false, port: 4700 }, + idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, + lease: { defaultTtlMs: 60_000, maxTtlMs: 3_600_000, ...leaseOverrides }, + warmPool: { maxConcurrentBoots: 1 }, + }); +} diff --git a/src/leasing/acquisition-requests.ts b/src/leasing/acquisition-requests.ts new file mode 100644 index 000000000..4fe60797c --- /dev/null +++ b/src/leasing/acquisition-requests.ts @@ -0,0 +1,95 @@ +import { compareVersions, type OsRange, parseOsConstraint, satisfies } from "../contract/index.js"; +import { + type ComponentInstallerProgress, + type LeaseProgress, + type DeviceRequest, + type DeviceRequirement, + type DriverCatalogEntry, + pairedRuntimes, + type PhysicalRequest, + RuntimeMissingError, + type VirtualSpec, +} from "../core/index.js"; + +export function physicalRequestOf(request: DeviceRequest): PhysicalRequest { + return { + platform: request.platform, + ...(request.model === undefined ? {} : { model: request.model }), + ...(request.class === undefined ? {} : { class: request.class }), + ...(request.osVersion === undefined ? {} : { osVersion: request.osVersion }), + }; +} + +export function fullSpec(spec: VirtualSpec): VirtualSpec { + if (spec.mode === undefined) return spec; + const { mode: _mode, ...full } = spec; + return full; +} + +export type DownloadingProgress = Extract; + +export function downloadingProgress( + component: string, + progress: ComponentInstallerProgress, +): DownloadingProgress { + if (progress.stage === "waiting") return { component, stage: "downloading", waiting: true }; + const { percent } = progress; + return percent === undefined + ? { component, stage: "downloading", waiting: false } + : { component, percent: Math.floor(percent), stage: "downloading", waiting: false }; +} + +/** why: both reports are for the one component a `#resolveOrInstall` call downloads. */ +export function sameDownloadingProgress( + left: DownloadingProgress, + right: DownloadingProgress, +): boolean { + return left.waiting === right.waiting && left.percent === right.percent; +} + +export function matchingRuntimes( + entry: DriverCatalogEntry, + model: string, + { imageTag, osVersion }: Pick, + range: OsRange | undefined, +): string[] { + return pairedRuntimes(entry, model).filter( + (runtime) => + (range === undefined + ? osVersion === undefined || runtime === osVersion + : satisfies(runtime, range)) && + (imageTag === undefined || + (entry.images ?? []).some((image) => image.runtime === runtime && image.tag === imageTag)), + ); +} + +/** why: the newest runtime `model` pairs with that the request's range accepts, or none installed. */ +export function newestRuntime( + entry: DriverCatalogEntry, + model: string, + request: DeviceRequest, + range: OsRange, +): string { + const newest = matchingRuntimes(entry, model, request, range).sort(compareVersions).at(-1); + if (newest === undefined) throw new RuntimeMissingError(request.platform, range.text); + return newest; +} + +/** why: what a device's OS must satisfy: the range, the exact version named, or any installed runtime. */ +export function requiredOs( + entry: DriverCatalogEntry, + { osVersion }: DeviceRequest, + range: OsRange | undefined, +): DeviceRequirement["osVersion"] { + if (range !== undefined) return range; + return osVersion === undefined + ? { kind: "installed", versions: entry.runtimes } + : { kind: "exact", version: osVersion }; +} + +/** why: the request's OS range, when its `osVersion` is one rather than an exact version. */ +export function requestedRange(request: DeviceRequest): OsRange | undefined { + if (request.osVersion === undefined) return undefined; + const parsed = parseOsConstraint(request.osVersion); + return parsed.ok && parsed.constraint.kind === "range" ? parsed.constraint : undefined; +} diff --git a/src/leasing/acquisition-timing.ts b/src/leasing/acquisition-timing.ts new file mode 100644 index 000000000..4953f72bd --- /dev/null +++ b/src/leasing/acquisition-timing.ts @@ -0,0 +1,55 @@ +import { + type DeviceRecord, + type DeviceSpec, + type Driver, + type LeaseTiming, + toDriverDevice, +} from "../core/index.js"; + +export function estimatedTiming(driver: Driver, spec: DeviceSpec): LeaseTiming { + const estimatedProvisionMs = driver.estimate({ operation: "provision" }, spec); + const estimatedBootMs = driver.estimate({ operation: "boot" }, spec); + return { + estimatedBootMs, + estimatedProvisionMs, + estimatedReclaimMs: releaseReclaimEstimateMs(driver, spec), + estimatedReadyMs: estimatedProvisionMs + estimatedBootMs, + }; +} + +export async function estimatedBootTiming( + driver: Driver, + device: DeviceRecord, +): Promise { + const spec = device.spec; + // why: The quote is advisory. A driver that cannot read the device's own boot path (a failed + // `emulator -version`, say) must not strand the claim and capacity reservation that the boot + // below releases, so the device-less figure stands in. + const estimatedBootMs = await Promise.resolve( + driver.estimate( + { device: toDriverDevice(device), operation: "boot", purpose: "prepare" }, + spec, + ), + ).catch(() => driver.estimate({ operation: "boot" }, spec)); + return { + estimatedBootMs, + estimatedProvisionMs: 0, + estimatedReclaimMs: releaseReclaimEstimateMs(driver, spec), + estimatedReadyMs: estimatedBootMs, + }; +} + +/** why: a device that is already ready costs nothing to hand over; only its reclaim lies ahead. */ +export function grantReadyTiming(driver: Driver, spec: DeviceSpec): LeaseTiming { + return { + estimatedBootMs: 0, + estimatedProvisionMs: 0, + estimatedReclaimMs: releaseReclaimEstimateMs(driver, spec), + estimatedReadyMs: 0, + }; +} + +/** why: `standard`: every release path asks for it; a holder cannot request another clean level. */ +export function releaseReclaimEstimateMs(driver: Driver, spec: DeviceSpec): number { + return driver.estimate({ clean: "standard", operation: "reclaim" }, spec); +} diff --git a/src/leasing/lease-acquisition-coordinator.ts b/src/leasing/lease-acquisition-coordinator.ts index 00b1c9d57..5e4d878fd 100644 --- a/src/leasing/lease-acquisition-coordinator.ts +++ b/src/leasing/lease-acquisition-coordinator.ts @@ -1,12 +1,23 @@ import type { EventBus, EventMap } from "../bus/index.js"; -import { - compareVersions, - type OsRange, - parseOsConstraint, - requestedClass, - satisfies, -} from "../contract/index.js"; +import { type OsRange, requestedClass } from "../contract/index.js"; import { type IdGenerator, type Logger, NoopLogger } from "../ports/index.js"; +import { + downloadingProgress, + type DownloadingProgress, + fullSpec, + matchingRuntimes, + newestRuntime, + physicalRequestOf, + requestedRange, + requiredOs, + sameDownloadingProgress, +} from "./acquisition-requests.js"; +import { + estimatedBootTiming, + estimatedTiming, + grantReadyTiming, + releaseReclaimEstimateMs, +} from "./acquisition-timing.js"; import { type CapacityReservation, type DeviceOperationClaim, @@ -15,7 +26,6 @@ import { classCandidates, findCatalogModel, modelClass, - pairedRuntimes, type DeviceClass, type DeviceMode, type DeviceRecord, @@ -30,7 +40,6 @@ import { type VirtualSpec, exactRequirement, type LeaseGrant, - type LeaseProgress, type LeaseRecord, type MaxPerRequester, type LeaseTiming, @@ -40,7 +49,6 @@ import { specMode, ComponentBeingRemovedError, type ComponentInstaller, - type ComponentInstallerProgress, BootTimeoutError, type DeviceRequest, type Driver, @@ -1544,51 +1552,6 @@ function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); } -function estimatedTiming(driver: Driver, spec: DeviceSpec): LeaseTiming { - const estimatedProvisionMs = driver.estimate({ operation: "provision" }, spec); - const estimatedBootMs = driver.estimate({ operation: "boot" }, spec); - return { - estimatedBootMs, - estimatedProvisionMs, - estimatedReclaimMs: releaseReclaimEstimateMs(driver, spec), - estimatedReadyMs: estimatedProvisionMs + estimatedBootMs, - }; -} - -async function estimatedBootTiming(driver: Driver, device: DeviceRecord): Promise { - const spec = device.spec; - // why: The quote is advisory. A driver that cannot read the device's own boot path (a failed - // `emulator -version`, say) must not strand the claim and capacity reservation that the boot - // below releases, so the device-less figure stands in. - const estimatedBootMs = await Promise.resolve( - driver.estimate( - { device: toDriverDevice(device), operation: "boot", purpose: "prepare" }, - spec, - ), - ).catch(() => driver.estimate({ operation: "boot" }, spec)); - return { - estimatedBootMs, - estimatedProvisionMs: 0, - estimatedReclaimMs: releaseReclaimEstimateMs(driver, spec), - estimatedReadyMs: estimatedBootMs, - }; -} - -/** A device that is already ready costs nothing to hand over; only its reclaim lies ahead. */ -function grantReadyTiming(driver: Driver, spec: DeviceSpec): LeaseTiming { - return { - estimatedBootMs: 0, - estimatedProvisionMs: 0, - estimatedReclaimMs: releaseReclaimEstimateMs(driver, spec), - estimatedReadyMs: 0, - }; -} - -/** `standard`: every release path asks for it; a holder cannot request another clean level. */ -function releaseReclaimEstimateMs(driver: Driver, spec: DeviceSpec): number { - return driver.estimate({ clean: "standard", operation: "reclaim" }, spec); -} - /** * why: a plan handed out the capacity or device claim its operation needs; dropping the plan has * to give it back, or the resource stays held with nobody left to release it. @@ -1614,39 +1577,6 @@ function operationPlan(plan: AcquisitionPlan): OperationPlan | undefined { : plan; } -function physicalRequestOf(request: DeviceRequest): PhysicalRequest { - return { - platform: request.platform, - ...(request.model === undefined ? {} : { model: request.model }), - ...(request.class === undefined ? {} : { class: request.class }), - ...(request.osVersion === undefined ? {} : { osVersion: request.osVersion }), - }; -} - -function fullSpec(spec: VirtualSpec): VirtualSpec { - if (spec.mode === undefined) return spec; - const { mode: _mode, ...full } = spec; - return full; -} - -type DownloadingProgress = Extract; - -function downloadingProgress( - component: string, - progress: ComponentInstallerProgress, -): DownloadingProgress { - if (progress.stage === "waiting") return { component, stage: "downloading", waiting: true }; - const { percent } = progress; - return percent === undefined - ? { component, stage: "downloading", waiting: false } - : { component, percent: Math.floor(percent), stage: "downloading", waiting: false }; -} - -/** Both reports are for the one component a `#resolveOrInstall` call downloads. */ -function sameDownloadingProgress(left: DownloadingProgress, right: DownloadingProgress): boolean { - return left.waiting === right.waiting && left.percent === right.percent; -} - /** * The spec a driver resolved, held to what the request asked. The image tag is the request's, or * none: a driver that returns another, or one the request did not name, would plan the device @@ -1683,49 +1613,3 @@ interface ResolvedTarget { * in its range, or any when it names none; and only runtimes that have an image of the requested * tag when it names one (the rule the gateway's `matchRequest` applies). */ -function matchingRuntimes( - entry: DriverCatalogEntry, - model: string, - { imageTag, osVersion }: Pick, - range: OsRange | undefined, -): string[] { - return pairedRuntimes(entry, model).filter( - (runtime) => - (range === undefined - ? osVersion === undefined || runtime === osVersion - : satisfies(runtime, range)) && - (imageTag === undefined || - (entry.images ?? []).some((image) => image.runtime === runtime && image.tag === imageTag)), - ); -} - -/** The newest runtime `model` pairs with that the request's range accepts, or none installed. */ -function newestRuntime( - entry: DriverCatalogEntry, - model: string, - request: DeviceRequest, - range: OsRange, -): string { - const newest = matchingRuntimes(entry, model, request, range).sort(compareVersions).at(-1); - if (newest === undefined) throw new RuntimeMissingError(request.platform, range.text); - return newest; -} - -/** What a device's OS must satisfy: the range, the exact version named, or any installed runtime. */ -function requiredOs( - entry: DriverCatalogEntry, - { osVersion }: DeviceRequest, - range: OsRange | undefined, -): DeviceRequirement["osVersion"] { - if (range !== undefined) return range; - return osVersion === undefined - ? { kind: "installed", versions: entry.runtimes } - : { kind: "exact", version: osVersion }; -} - -/** The request's OS range, when its `osVersion` is one rather than an exact version. */ -function requestedRange(request: DeviceRequest): OsRange | undefined { - if (request.osVersion === undefined) return undefined; - const parsed = parseOsConstraint(request.osVersion); - return parsed.ok && parsed.constraint.kind === "range" ? parsed.constraint : undefined; -} From 8592d50fc6c6a5fcecdc714e0b46cfff4a7ad907 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 08:56:10 +0100 Subject: [PATCH 16/22] docs(leasing): list the acquisition parts and the dispatcher test helpers in their manuals (#1330) --- src/daemon/AGENTS.md | 1 + src/daemon/test-dispatcher.ts | 21 +++++++++------------ src/leasing/AGENTS.md | 33 +++++++++++++++++---------------- 3 files changed, 27 insertions(+), 28 deletions(-) diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index db56961b6..6924cc715 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -29,6 +29,7 @@ Flows: [startup](../../docs/internal/flows/startup.md), [device.exec](../../docs | `ios-driver-logging.ts` | `logSilenceFailure`, `logWindowFailure`: the iOS driver's silence and window failures as `warn` lines | | `exec-env.ts` | `execBaseEnvironment`: the allowlisted keys of `process.env` a `device.exec` child starts from | | `test-relay-support.ts` | Test helpers for relay e2e tests | +| `test-dispatcher.ts` | `buildDispatcher`, `session` and the other helpers the dispatcher test files share | ## Composition (`main.ts`) diff --git a/src/daemon/test-dispatcher.ts b/src/daemon/test-dispatcher.ts index f086eeb90..13d167519 100644 --- a/src/daemon/test-dispatcher.ts +++ b/src/daemon/test-dispatcher.ts @@ -41,14 +41,14 @@ import { createTestEngine, type TestEngine } from "../leasing/testing.js"; export const gibibyte = 1024 ** 3; export const HOST_SYSTEM = { arch: "arm64", os: "macOS", osVersion: "15.5" }; -export function resolvePassthroughOverride( +function resolvePassthroughOverride( engine: TestEngine, override: PassthroughResolver | undefined, ): PassthroughResolver { return override ?? engine; } -export function stallOptions( +function stallOptions( engine: TestEngine, driver: FakeDriver, overrides: { @@ -62,14 +62,14 @@ export function stallOptions( }; } -export function resolveEventHistoryOverride( +function resolveEventHistoryOverride( eventBus: EventBus, override: Pick | undefined, ): Pick { return override ?? ringEventHistory(eventBus); } -export function fakePassthroughOptions( +function fakePassthroughOptions( tool: string | undefined, contextSink: unknown[] | undefined, ): Partial { @@ -127,11 +127,11 @@ export class SettableClock extends FakeClock { } } -export function withGatewayLabel(config: Config, label: string | undefined): Config { +function withGatewayLabel(config: Config, label: string | undefined): Config { return label === undefined ? config : { ...config, gateway: { ...config.gateway, label } }; } -export function withHttp(config: Config, http: Config["http"] | undefined): Config { +function withHttp(config: Config, http: Config["http"] | undefined): Config { return http === undefined ? config : { ...config, http }; } @@ -146,10 +146,7 @@ export interface SeededPhysicalDevice { readonly state: string; } -export function seedPhysicalDevices( - state: StateDatabase, - devices: readonly SeededPhysicalDevice[], -): void { +function seedPhysicalDevices(state: StateDatabase, devices: readonly SeededPhysicalDevice[]): void { for (const device of devices) { state.database .prepare( @@ -380,12 +377,12 @@ export function session(overrides: Partial = {}): DispatchSessi }; } -export function sequence() { +function sequence() { let next = 1; return { generate: () => `${next++}` }; } -export function testConfig( +function testConfig( downloadsPolicy: Config["downloads"]["policy"] = "on-request", leaseOverrides: Partial = {}, execOverrides: Partial = {}, diff --git a/src/leasing/AGENTS.md b/src/leasing/AGENTS.md index e3c5850f0..d972e6540 100644 --- a/src/leasing/AGENTS.md +++ b/src/leasing/AGENTS.md @@ -8,22 +8,23 @@ 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 | +| `acquisition-timing.ts`, `acquisition-requests.ts` | Parts of the coordinator (ADR 0063): the timing quotes; the pure request helpers (OS range, runtimes, physical request, download progress) | +| `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 | ## The update hold From 069bf8fdd7dcb127b53bb1a5ad251a68265de6ef Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 09:02:11 +0100 Subject: [PATCH 17/22] test(daemon): the warm reboot's new address reaches the granted device (#1330) --- src/daemon/dispatcher-except.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/daemon/dispatcher-except.test.ts b/src/daemon/dispatcher-except.test.ts index 6168e2c63..4f2000a5d 100644 --- a/src/daemon/dispatcher-except.test.ts +++ b/src/daemon/dispatcher-except.test.ts @@ -89,6 +89,8 @@ describe("Dispatcher: lease.request with an except list", () => { session(), ); expect(grantedWarm.device).toMatchObject({ except, id: registered.id, mode: "slim" }); + // why: the seed's boot was the device's first, so the reboot's address is the second boot's. + expect(grantedWarm.device.address).toBe(`${registered.driverDeviceId}-addr-2`); expect( warm.driver.calls .slice(seededCalls) From 9c12ffb2e56b4c84e6dc938ff23681bdf7add644 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 09:19:28 +0100 Subject: [PATCH 18/22] fix(leasing): a slim baseline's except names reach the driver, and a failed reboot record ends the boot claim (#1330) --- src/core/managed-device-lifecycle.test.ts | 17 +++++++++++ src/core/managed-device-lifecycle.ts | 30 ++++++++++++-------- src/daemon/dispatcher-except.test.ts | 15 +++++++++- src/leasing/AGENTS.md | 3 +- src/leasing/lease-acquisition-coordinator.ts | 16 ++++++++++- 5 files changed, 66 insertions(+), 15 deletions(-) diff --git a/src/core/managed-device-lifecycle.test.ts b/src/core/managed-device-lifecycle.test.ts index ef671aaaf..7974e4cab 100644 --- a/src/core/managed-device-lifecycle.test.ts +++ b/src/core/managed-device-lifecycle.test.ts @@ -315,6 +315,23 @@ describe("ManagedDeviceLifecycle", () => { ).resolves.toMatchObject({ state: "shutdown" }); }); + it("rebootForLease ends its boot claim when recording the rebooted device throws", async () => { + const harness = await createHarness(); + const ready = await readyDevice(harness); + vi.spyOn(harness.registry, "recordRebootedDevice").mockRejectedValueOnce( + new Error("state.db is read-only"), + ); + + const claim = harness.claims.tryClaim(ready.id, "boot"); + if (claim === undefined) throw new Error("the device was already claimed"); + + await expect(harness.lifecycle.rebootForLease(ready, claim, ["store"])).rejects.toThrow( + "state.db is read-only", + ); + + expect(harness.claims.isClaimed(ready.id)).toBe(false); + }); + describe("recoverLeased", () => { it("reboots a leased device under its own lease id without a registry transition", async () => { const harness = await createHarness(); diff --git a/src/core/managed-device-lifecycle.ts b/src/core/managed-device-lifecycle.ts index 1a0044112..9477a0363 100644 --- a/src/core/managed-device-lifecycle.ts +++ b/src/core/managed-device-lifecycle.ts @@ -131,18 +131,24 @@ export class ManagedDeviceLifecycle { } throw error; } - const device = await this.decisions.run(async () => { - const current = this.#registeredTarget(claimed.device, ["ready"]); - if (current === undefined) return undefined; - // why: `mode` defaults to full here as `readyTransitionUpdate` does, so a reboot granted full records full. - return assertVirtual( - await this.registry.recordRebootedDevice(current.id, { - address: ready.address, - driverData: ready.driverData, - mode: ready.mode ?? "full", - }), - ); - }); + let device: VirtualDevice | undefined; + try { + device = await this.decisions.run(async () => { + const current = this.#registeredTarget(claimed.device, ["ready"]); + if (current === undefined) return undefined; + // why: `mode` defaults to full here as `readyTransitionUpdate` does, so a reboot granted full records full. + return assertVirtual( + await this.registry.recordRebootedDevice(current.id, { + address: ready.address, + driverData: ready.driverData, + mode: ready.mode ?? "full", + }), + ); + }); + } catch (error: unknown) { + await this.#release(claimed); + throw error; + } if (device === undefined) { await this.#release(claimed); return undefined; diff --git a/src/daemon/dispatcher-except.test.ts b/src/daemon/dispatcher-except.test.ts index 4f2000a5d..8f287da3e 100644 --- a/src/daemon/dispatcher-except.test.ts +++ b/src/daemon/dispatcher-except.test.ts @@ -160,7 +160,11 @@ describe("Dispatcher: lease.request with an except list", () => { ], ["physical", { ...ask, physical: true }, "except is for iOS simulators"], ["android", { ...ask, platform: "android" }, "except is for iOS simulators"], - ["a name the driver refuses", { ...ask, except: ["wallet"] }, ""], + [ + "a name the driver refuses", + { ...ask, except: ["wallet"] }, + 'unknown slim category "wallet"', + ], ]; for (const [label, input, message, defaultMode] of refusals) { const error = await attempt(input, defaultMode); @@ -203,6 +207,15 @@ describe("Dispatcher: lease.request with an except list", () => { session({ principal: "tok_d" }), ); expect(fromSlim.device).toMatchObject({ except: ["store"], mode: "slim" }); + const unknownFromSlim = await dispatcher + .dispatch( + "lease.request", + { baseline: "slim-base", except: ["wallet"], platform: "ios" }, + session({ principal: "tok_e" }), + ) + .catch((error: unknown) => error); + expect(classifyError(unknownFromSlim)).toBe("BAD_REQUEST"); + expect((unknownFromSlim as Error).message).toContain('unknown slim category "wallet"'); }); it("a failed except boot is never granted", async () => { diff --git a/src/leasing/AGENTS.md b/src/leasing/AGENTS.md index d972e6540..631211791 100644 --- a/src/leasing/AGENTS.md +++ b/src/leasing/AGENTS.md @@ -46,7 +46,8 @@ and registry writers. Read-decide-commit runs under it; driver I/O never does. `allowDownload`. Physical requests skip this. See device selection. A request naming a baseline resolves against `core.baselines` instead: unknown, mismatch (`baselineMismatch`) or stale fails at once, and the spec is the - baseline's, with its name and version; no download is attempted. + baseline's, with its name and version; no download is attempted. A slim baseline's `except` + names go to `driver.resolveSpec` too, so an unknown name is `BAD_REQUEST`. 3. **Plan** (lock) — `AcquisitionPlanner.plan`; first that applies wins: grant a ready fitting device (a slim request with `except` takes it with a `boot` claim and no capacity reservation instead, `reboot-ready`) → wait for one the warm pool is booting → boot a shut-down one → provision → evict an diff --git a/src/leasing/lease-acquisition-coordinator.ts b/src/leasing/lease-acquisition-coordinator.ts index 5e4d878fd..6b83c7cfd 100644 --- a/src/leasing/lease-acquisition-coordinator.ts +++ b/src/leasing/lease-acquisition-coordinator.ts @@ -558,7 +558,9 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { readonly requirement: DeviceRequirement; readonly classOf: ((model: string) => DeviceClass | undefined) | undefined; }> { - if (request.baseline !== undefined) return this.#resolveBaseline(request.baseline, request); + if (request.baseline !== undefined) { + return this.#resolveBaseline(driver, request.baseline, request); + } // The one place a request with no mode gets the worker's default (ADR 0007 §2). const mode = request.mode ?? this.defaultMode(request.platform); if (request.except !== undefined && mode !== "slim") { @@ -586,6 +588,7 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { /** why: a request naming a baseline takes the baseline's own platform, model, OS, mode and image tag; no download is ever attempted. */ async #resolveBaseline( + driver: Driver, name: string, request: DeviceRequest, ): Promise<{ @@ -605,6 +608,17 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { if (request.except !== undefined && spec.mode !== "slim") { throw new BadDeviceRequestError(`except needs a slim lease (baseline "${name}" is full)`); } + if (request.except !== undefined) { + // why: the driver judges the names (ADR 0066 §2); its answer is dropped, the baseline's spec stands. + await driver.resolveSpec({ + except: request.except, + mode: "slim", + model: spec.model, + osVersion: spec.osVersion, + platform: spec.platform, + ...(spec.imageTag === undefined ? {} : { imageTag: spec.imageTag }), + }); + } return { classOf: undefined, requirement: exactRequirement(spec), spec }; } From 2de21c7e1e6e92f41d56da071b870af06ce9a584 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 09:20:59 +0100 Subject: [PATCH 19/22] test(leasing): a slim except boot granted full, the retry count of a failed except boot, its released slot, and the per-category grant (#1330) --- e2e/slow-ios-slim.test.ts | 6 +++ src/daemon/dispatcher-except.test.ts | 66 +++++++++++++++++++++++++++- 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/e2e/slow-ios-slim.test.ts b/e2e/slow-ios-slim.test.ts index ee3556a54..49e65be34 100644 --- a/e2e/slow-ios-slim.test.ts +++ b/e2e/slow-ios-slim.test.ts @@ -391,6 +391,12 @@ describe.skipIf(process.platform !== "darwin")( "--except", category.name, ]); + await expectSlim( + env, + grant.mode, + `a --mode slim lease excepting ${category.name} must be slim`, + ); + expect(grant.except).toEqual([category.name]); const disabled = await printDisabled(grant); expect( labelsFor([category]).filter((label) => disabled.has(label)), diff --git a/src/daemon/dispatcher-except.test.ts b/src/daemon/dispatcher-except.test.ts index 8f287da3e..287eb6748 100644 --- a/src/daemon/dispatcher-except.test.ts +++ b/src/daemon/dispatcher-except.test.ts @@ -29,7 +29,9 @@ async function seedSlimDevice( platform: "ios", } as const; const driverDevice = await built.driver.provision(spec); - const ready = await built.driver.makeReady(driverDevice, { mode: "slim", purpose: "prepare" }); + const driven = await built.driver.makeReady(driverDevice, { mode: "slim", purpose: "prepare" }); + // why: the seed is a slim device whatever the fake reports on its boot, so a test whose driver answers `full` still starts from slim. + const ready = { ...driven, mode: "slim" as const }; const registered = await built.registry.registerDevice({ driverData: driverDevice.driverData, driverDeviceId: driverDevice.deviceId, @@ -218,6 +220,30 @@ describe("Dispatcher: lease.request with an except list", () => { expect((unknownFromSlim as Error).message).toContain('unknown slim category "wallet"'); }); + it("a slim except boot the driver grants full leaves the device full with no except, on a reboot and on a boot", async () => { + const ask = { + except: ["store"], + mode: "slim", + model: "iPhone 17 Pro", + osVersion: "26.5", + platform: "ios", + } as const; + const build = () => + buildDispatcher({ driverOptions: { mode: "full", slimmableOsVersions: ["26.5"] } }); + + for (const state of ["ready", "shutdown"] as const) { + const built = await build(); + const seeded = await seedSlimDevice(built, state); + const granted = await built.dispatcher.dispatch("lease.request", ask, session()); + + expect(granted.device.id, state).toBe(seeded.id); + expect(granted.device, state).not.toHaveProperty("except"); + const record = built.registry.snapshot.devices.find((d) => d.id === seeded.id); + expect(record, state).toMatchObject({ mode: "full", state: "leased" }); + expect(record, state).not.toHaveProperty("except"); + } + }); + it("a failed except boot is never granted", async () => { const ask = { except: ["store"], @@ -305,6 +331,44 @@ describe("Dispatcher: lease.request with an except list", () => { .catch((error: unknown) => error); expect(classifyError(conflict)).toBe("IDEMPOTENCY_CONFLICT"); + // why: each failed boot or reboot counts toward the one retry, so a provision failure after it is the second. + for (const state of ["ready", "shutdown"] as const) { + const counted = await build(); + await seedSlimDevice(counted, state); + // why: call 1 of makeReady and of provision is the seed's own; call 2 of each is the waiter's. + counted.driver.failOn("makeReady", 2, crash); + counted.driver.failOn("provision", 2, crash); + const countedRefusal = await grantedOnceSettled( + counted.dispatcher.dispatch("lease.request", ask, session()).then( + () => undefined, + (error: unknown) => error ?? "granted", + ), + ); + expect(classifyError(countedRefusal), state).toBe("PROVISION_FAILED"); + } + + // why: a worker with one running slot is granted after a failed boot only when that boot released the slot it reserved. + const oneSlot = await buildDispatcher({ + capacity: { + config: { + limits: { + android: { maxDevices: 1, maxRunning: 1 }, + ios: { maxDevices: 1, maxRunning: 1 }, + maxRunning: 1, + }, + ramBudget: { androidBytesPerDevice: 4 * 1024 ** 3, iosBytesPerDevice: 1024 ** 3 }, + }, + strategy: "resource", + }, + driverOptions: { slimmableOsVersions: ["26.5"] }, + }); + await seedSlimDevice(oneSlot, "shutdown"); + oneSlot.driver.failOn("makeReady", 2, crash); + const afterOneSlot = await grantedOnceSettled( + oneSlot.dispatcher.dispatch("lease.request", ask, session()), + ); + expect(afterOneSlot.device).toMatchObject({ except: ask.except, mode: "slim" }); + const rebooting = await build(); const seededWarm = await seedSlimDevice(rebooting, "ready"); const before = (await rebooting.dispatcher.dispatch("status.get", {}, session())).capacity; From 07182483abeca19ae87cc4d386431bb2a982216a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 09:32:35 +0100 Subject: [PATCH 20/22] refactor(daemon): drop the test-dispatcher helpers no test uses after the merge (#1330) --- src/daemon/test-dispatcher.ts | 33 --------------------------------- 1 file changed, 33 deletions(-) diff --git a/src/daemon/test-dispatcher.ts b/src/daemon/test-dispatcher.ts index 1b5e08108..aaeecb295 100644 --- a/src/daemon/test-dispatcher.ts +++ b/src/daemon/test-dispatcher.ts @@ -95,39 +95,6 @@ function fakePassthroughOptions( return options; } -export interface RecordedPassthrough { - readonly args: readonly string[]; - readonly context: unknown; - readonly device: unknown; - readonly tool: string; -} - -export function recordingResolver( - calls: RecordedPassthrough[], - answer: () => Promise = () => - Promise.resolve({ args: ["list", "devices"], command: "simctl", env: {} }), -): PassthroughResolver { - const resolver = { - passthrough: (tool: string, device: unknown, args: readonly string[], context?: unknown) => { - calls.push({ args, context, device, tool }); - return answer(); - }, - }; - return resolver as unknown as PassthroughResolver; -} - -export class SettableClock extends FakeClock { - #offset = 0; - - setBack(ms: number): void { - this.#offset -= ms; - } - - override now(): number { - return super.now() + this.#offset; - } -} - function withGatewayLabel(config: Config, label: string | undefined): Config { return label === undefined ? config : { ...config, gateway: { ...config.gateway, label } }; } From 8c2a41f9feb3e9fe5f5250132c4f267d4f93da53 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 09:33:20 +0100 Subject: [PATCH 21/22] fix(contract): the slim except shapes bump the protocol past main's 78 (#1330) --- src/contract/protocol.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index bb24a0aa4..89a573197 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -10,7 +10,7 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** Widen only once a second version is kept alive side by side with the first; a bump that leaves no shim behind moves both ends. */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 78, max: 78 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 79, max: 79 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; From bf1b920885abab0086abf473ce139dc9a014143d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 6 Nov 2026 11:00:34 +0100 Subject: [PATCH 22/22] docs(leasing): restore the crash-mid-reboot known gap dropped in the merge (#1330) --- src/leasing/AGENTS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/src/leasing/AGENTS.md b/src/leasing/AGENTS.md index 7a01bd068..a579d7fb0 100644 --- a/src/leasing/AGENTS.md +++ b/src/leasing/AGENTS.md @@ -54,6 +54,7 @@ Boundaries: ## Known gaps +- **A crash mid-reboot of a warm device for an `except` lease** leaves the request failed at startup (`daemon-restarted`) and a `ready` record whose simulator may be shut down; startup's reconcile only reports that drift. A later grant of it is caught by the health monitor, which reboots it under the lease. - **A SIGKILLed holder keeps its device until the TTL.** It runs no release. Bound it with `lease.defaultTtlMs` or `--ttl`; `simlock release ` ends it now. - **Recovery restores the disk, not the session.** Apps, log streams and