From 98cd52276af5922b6072bbad9d805faf19873d6a Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:08:36 +0100 Subject: [PATCH 01/16] test: an iOS lease whose resolved mode ios.modes does not list is refused with MODE_UNAVAILABLE (#1651) --- src/core/config-defaults.ts | 1 + src/core/config-types.ts | 2 ++ .../dispatcher-leases-served-modes.test.ts | 30 +++++++++++++++++++ src/daemon/driver-discovery.test.ts | 8 ++++- src/daemon/test-dispatcher.ts | 22 ++++++++++++++ src/daemon/worker-composition.ts | 3 ++ src/leasing/acquisition-ports.ts | 2 ++ src/leasing/acquisition-spec-resolver.ts | 1 + src/leasing/create-leasing.ts | 3 ++ src/leasing/test-lease-acquisition.ts | 1 + src/leasing/testing.ts | 2 ++ 11 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 src/daemon/dispatcher-leases-served-modes.test.ts diff --git a/src/core/config-defaults.ts b/src/core/config-defaults.ts index b82526980..d335822d9 100644 --- a/src/core/config-defaults.ts +++ b/src/core/config-defaults.ts @@ -153,6 +153,7 @@ export function defaultConfig( ...driverDefaults(driverSections, "ios"), defaultMode: "full", defaultModels: {}, + modes: ["slim", "full"], virtualDevices: true, }, android: { diff --git a/src/core/config-types.ts b/src/core/config-types.ts index e79bf885f..d36be908c 100644 --- a/src/core/config-types.ts +++ b/src/core/config-types.ts @@ -166,6 +166,8 @@ export interface Config { readonly ios: { readonly defaultMode: DeviceMode; readonly defaultModels: DefaultModels; + /** why: the iOS device modes this worker serves (ADR 0082 §1); a request or target of another mode is refused. */ + readonly modes: readonly DeviceMode[]; /** why: false makes this worker serve only enrolled physical iOS devices (ADR 0084 §1). */ readonly virtualDevices: boolean; } & DriverConfigSection; diff --git a/src/daemon/dispatcher-leases-served-modes.test.ts b/src/daemon/dispatcher-leases-served-modes.test.ts new file mode 100644 index 000000000..b0cf977e9 --- /dev/null +++ b/src/daemon/dispatcher-leases-served-modes.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; +import { buildDispatcher, session } from "./test-dispatcher.js"; + +describe("Dispatcher: the iOS modes a worker serves", () => { + it("refuses an iOS lease whose resolved mode ios.modes does not list with MODE_UNAVAILABLE and its details, and grants a served one", async () => { + const { dispatcher } = await buildDispatcher({ + driverOptions: { slimmableOsVersions: ["26.5"] }, + iosModes: ["slim"], + }); + const request = { model: "iPhone 17 Pro", platform: "ios" } as const; + + const granted = await dispatcher.dispatch( + "lease.request", + { ...request, mode: "slim" }, + session(), + ); + expect(granted.device.mode).toBe("slim"); + + await expect( + dispatcher.dispatch( + "lease.request", + { ...request, mode: "full" }, + session({ principal: "tok_other" }), + ), + ).rejects.toMatchObject({ + code: "MODE_UNAVAILABLE", + details: { mode: "full", platform: "ios", served: ["slim"] }, + }); + }); +}); diff --git a/src/daemon/driver-discovery.test.ts b/src/daemon/driver-discovery.test.ts index 7183cdb00..31b80b68f 100644 --- a/src/daemon/driver-discovery.test.ts +++ b/src/daemon/driver-discovery.test.ts @@ -648,6 +648,7 @@ describe("deviceModeWiring", () => { ios: { defaultMode, defaultModels: {}, + modes: ["slim", "full"], virtualDevices: true, }, }), @@ -659,7 +660,12 @@ describe("deviceModeWiring", () => { ); it("passes android.defaultImageTag to leasing as the Android default tag, and nothing when it is unset", () => { - const ios = { defaultMode: "full", defaultModels: {}, virtualDevices: true } as const; + const ios = { + defaultMode: "full", + defaultModels: {}, + modes: ["slim", "full"], + virtualDevices: true, + } as const; expect( deviceModeWiring({ diff --git a/src/daemon/test-dispatcher.ts b/src/daemon/test-dispatcher.ts index 82e69d6da..71a54db99 100644 --- a/src/daemon/test-dispatcher.ts +++ b/src/daemon/test-dispatcher.ts @@ -42,6 +42,7 @@ import { openMemoryStateDatabase } from "../auth/testing.js"; import type { DispatcherOptions, DispatchSession } from "./dispatcher.js"; import { Dispatcher } from "./dispatcher.js"; import { describeLeaseRequestFailure } from "./error-code.js"; +import { deviceModeWiring } from "./worker-composition.js"; import { createTestEngine, type TestEngine } from "../leasing/testing.js"; export const gibibyte = 1024 ** 3; @@ -187,6 +188,8 @@ export async function buildDispatcher( readonly warmPool?: Partial; /** why: the `ios.defaultMode` `catalog.get` reports. */ readonly iosDefaultMode?: "slim" | "full"; + /** why: the `ios.modes` the worker serves; the default mode and the leasing engine follow it as the loader and the daemon's wiring do (ADR 0082 §1). */ + readonly iosModes?: readonly ("slim" | "full")[]; /** why: the `android.defaultImageTag` `config.get` reports. */ readonly androidDefaultImageTag?: string; /** why: a platform a test turns `.virtualDevices` off for (ADR 0084). */ @@ -263,6 +266,19 @@ export async function buildDispatcher( ...(overrides.iosDefaultMode === undefined ? {} : { ios: { ...baseConfig.ios, defaultMode: overrides.iosDefaultMode } }), + ...(overrides.iosModes === undefined + ? {} + : { + ios: { + ...baseConfig.ios, + defaultMode: + overrides.iosDefaultMode ?? + (overrides.iosModes.length === 1 + ? overrides.iosModes[0]! + : baseConfig.ios.defaultMode), + modes: overrides.iosModes, + }, + }), ...(overrides.bootTimeouts === undefined ? {} : { @@ -284,6 +300,12 @@ export async function buildDispatcher( clock, config, describeFailure: describeLeaseRequestFailure, + ...(overrides.iosModes === undefined + ? {} + : { + defaultModes: deviceModeWiring(config).defaultModes, + servedModes: deviceModeWiring(config).servedModes, + }), ...overrides.engine, drivers: [driver, ...(overrides.extraDrivers ?? [])], eventBus, diff --git a/src/daemon/worker-composition.ts b/src/daemon/worker-composition.ts index 8d0316df6..5cea860da 100644 --- a/src/daemon/worker-composition.ts +++ b/src/daemon/worker-composition.ts @@ -376,6 +376,7 @@ export async function composeWorker( core, defaultImageTags: deviceModeWiring(config).defaultImageTags, defaultModes: deviceModeWiring(config).defaultModes, + servedModes: deviceModeWiring(config).servedModes, describeFailure: describeLeaseRequestFailure, eventBus, idGenerator, @@ -773,6 +774,7 @@ export async function composeWorker( export function deviceModeWiring(config: Pick): { readonly defaultImageTags: Readonly>>; readonly defaultModes: Readonly>>; + readonly servedModes: Readonly>>; readonly slimByDefault: boolean; } { return { @@ -781,6 +783,7 @@ export function deviceModeWiring(config: Pick): { ? {} : { android: config.android.defaultImageTag }, defaultModes: { ios: config.ios.defaultMode }, + servedModes: { ios: config.ios.modes }, slimByDefault: config.ios.defaultMode === "slim", }; } diff --git a/src/leasing/acquisition-ports.ts b/src/leasing/acquisition-ports.ts index ee29a8ebd..7728e3f53 100644 --- a/src/leasing/acquisition-ports.ts +++ b/src/leasing/acquisition-ports.ts @@ -64,6 +64,8 @@ export interface LeaseAcquisitionCoordinatorOptions { readonly components: Pick; readonly decisions: AcquisitionDecision; readonly defaultModes: Readonly>>; + /** why: the modes the worker serves per platform (ADR 0082 §2); silent on a platform means every mode. */ + readonly servedModes: Readonly>>; /** why: the image tag a worker gives an Android lease that names none (ADR 0078 §1). */ readonly defaultImageTags: Readonly>>; readonly drivers: AcquisitionDrivers; diff --git a/src/leasing/acquisition-spec-resolver.ts b/src/leasing/acquisition-spec-resolver.ts index bb01cda48..f1675b07e 100644 --- a/src/leasing/acquisition-spec-resolver.ts +++ b/src/leasing/acquisition-spec-resolver.ts @@ -46,6 +46,7 @@ export type AcquisitionSpecResolverOptions = Pick< | "defaultModes" | "drivers" | "modelPreferences" + | "servedModes" >; /** why: turns a request into the exact spec a driver resolves, and a baseline request into that baseline's spec, so the root and the workflow never resolve a spec themselves. */ diff --git a/src/leasing/create-leasing.ts b/src/leasing/create-leasing.ts index 4e43928aa..19f1d2633 100644 --- a/src/leasing/create-leasing.ts +++ b/src/leasing/create-leasing.ts @@ -55,6 +55,8 @@ export interface LeasingOptions { * (ADR 0007 §2). Omitted, or silent on a platform, means `"full"`. */ readonly defaultModes?: Readonly>> | undefined; + /** why: the device modes the worker serves per platform, built from config by the composition root (ADR 0082 §2). Omitted, or silent on a platform, means every mode. */ + readonly servedModes?: Readonly>> | undefined; /** why: the worker's default image tag per platform, built from config by the composition root (ADR 0078 §1). */ readonly defaultImageTags?: Readonly>> | undefined; readonly modelPreferences?: ModelPreferences | undefined; @@ -158,6 +160,7 @@ export function createLeasing(options: LeasingOptions): Leasing { decisions, defaultImageTags: options.defaultImageTags ?? {}, defaultModes: options.defaultModes ?? {}, + servedModes: options.servedModes ?? {}, drivers: core.drivers, eventBus: options.eventBus, idGenerator: options.idGenerator, diff --git a/src/leasing/test-lease-acquisition.ts b/src/leasing/test-lease-acquisition.ts index 46b34322d..ae1c98708 100644 --- a/src/leasing/test-lease-acquisition.ts +++ b/src/leasing/test-lease-acquisition.ts @@ -213,6 +213,7 @@ export async function createHarness( decisions, defaultImageTags: options.defaultImageTags ?? {}, defaultModes: options.defaultModes ?? {}, + servedModes: {}, drivers: catalog, eventBus: bus, idGenerator, diff --git a/src/leasing/testing.ts b/src/leasing/testing.ts index 15d72bb04..bb50e5aa0 100644 --- a/src/leasing/testing.ts +++ b/src/leasing/testing.ts @@ -55,6 +55,7 @@ export interface TestEngineOptions { readonly describeFailure?: ((error: unknown) => LeaseRequestFailure) | undefined; readonly defaultImageTags?: Readonly>> | undefined; readonly defaultModes?: Readonly>> | undefined; + readonly servedModes?: Readonly>> | undefined; readonly modelPreferences?: ModelPreferences | undefined; readonly leaseEndParticipants?: readonly LeaseEndParticipant[] | undefined; } @@ -110,6 +111,7 @@ export function createTestEngine(options: TestEngineOptions): TestEngine { core, defaultImageTags: options.defaultImageTags, defaultModes: options.defaultModes, + servedModes: options.servedModes, describeFailure: options.describeFailure ?? describeTestFailure, eventBus: options.eventBus, idGenerator: options.idGenerator, From 831ec587426da65c3bb25366c8ec700967dbf2ff Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:11:35 +0100 Subject: [PATCH 02/16] feat(daemon): a worker refuses an iOS lease whose mode ios.modes does not list (#1651) --- src/contract/errors.ts | 8 +++++++ src/contract/protocol.ts | 2 +- ...onfig-platform-and-driver-settings.test.ts | 1 + src/daemon/error-code.ts | 4 ++++ src/daemon/lease-request-refusal.ts | 9 +++++++- src/http/lease-declarations.ts | 2 +- src/http/openapi.test.ts | 2 +- src/leasing/acquisition-errors.ts | 13 ++++++++++++ src/leasing/acquisition-spec-resolver.ts | 21 ++++++++++++++++++- src/leasing/index.ts | 1 + src/leasing/lease-acquisition-coordinator.ts | 1 + .../content/docs/docs/reference/errors.mdx | 3 ++- .../docs/docs/using-devices/errors.mdx | 1 + 13 files changed, 62 insertions(+), 6 deletions(-) diff --git a/src/contract/errors.ts b/src/contract/errors.ts index afdd6d9d2..b51862148 100644 --- a/src/contract/errors.ts +++ b/src/contract/errors.ts @@ -78,6 +78,12 @@ export interface ErrorDetailsMap { readonly model?: string; readonly class?: DeviceClass; }; + /** why: an iOS lease or warm target whose resolved mode the worker's `ios.modes` does not list (ADR 0082 §3). */ + MODE_UNAVAILABLE: { + readonly platform: "ios"; + readonly mode: "slim" | "full"; + readonly served: readonly ("slim" | "full")[]; + }; INSUFFICIENT_DISK_SPACE: { readonly platform: Platform; readonly requiredBytes: number; @@ -243,6 +249,7 @@ const CODES_WITH_DECLARED_DETAILS_BY_CODE: Record RELAY_TARGET_MISSING: true, RUNTIME_MISSING: true, UNKNOWN_MODEL: true, + MODE_UNAVAILABLE: true, HISTORY_NOT_KEPT: true, INSUFFICIENT_DISK_SPACE: true, FILE_TOO_LARGE: true, @@ -398,6 +405,7 @@ export const ERROR_TABLE: { readonly [Code in SimlockErrorCode]: ErrorTableEntry }, RUNTIME_MISSING: { code: "RUNTIME_MISSING", kind: "domain", cliExitCode: 12, httpStatus: 422 }, UNKNOWN_MODEL: { code: "UNKNOWN_MODEL", kind: "domain", cliExitCode: 12, httpStatus: 422 }, + MODE_UNAVAILABLE: { code: "MODE_UNAVAILABLE", kind: "domain", cliExitCode: 12, httpStatus: 422 }, INSUFFICIENT_DISK_SPACE: { code: "INSUFFICIENT_DISK_SPACE", kind: "domain", diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 989fbf07b..49a94bf6b 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: 89, max: 95 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 89, max: 96 }; const LEGACY_DAEMON_PROTOCOL_VERSION = 2; diff --git a/src/core/config-platform-and-driver-settings.test.ts b/src/core/config-platform-and-driver-settings.test.ts index 10acf7903..88e9f73f3 100644 --- a/src/core/config-platform-and-driver-settings.test.ts +++ b/src/core/config-platform-and-driver-settings.test.ts @@ -58,6 +58,7 @@ describe("loadConfig", () => { expect(set.config.ios).toEqual({ defaultMode: "full", defaultModels: {}, + modes: ["slim", "full"], virtualDevices: true, }); }); diff --git a/src/daemon/error-code.ts b/src/daemon/error-code.ts index b3933787a..1ab0857cc 100644 --- a/src/daemon/error-code.ts +++ b/src/daemon/error-code.ts @@ -30,6 +30,7 @@ import { IdempotencyConflictError, LeaseIdTakenError, LeaseRequestForbiddenError, + ModeUnavailableError, NoCapacityError, ProvisionFailedError, QueueTimeoutError, @@ -129,6 +130,9 @@ export function classifyError(error: unknown): SimlockErrorCode | undefined { if (error instanceof UnknownModelError) { return "UNKNOWN_MODEL"; } + if (error instanceof ModeUnavailableError) { + return "MODE_UNAVAILABLE"; + } if (error instanceof UnknownBaselineError) { return "UNKNOWN_BASELINE"; } diff --git a/src/daemon/lease-request-refusal.ts b/src/daemon/lease-request-refusal.ts index 7b2bb8dcd..021ed3cd9 100644 --- a/src/daemon/lease-request-refusal.ts +++ b/src/daemon/lease-request-refusal.ts @@ -1,6 +1,6 @@ import { isSimlockError } from "../contract/index.js"; import { BaselineMismatchError, BaselineStaleError, UnknownBaselineError } from "../core/index.js"; -import { LeaseIdTakenError } from "../leasing/index.js"; +import { LeaseIdTakenError, ModeUnavailableError } from "../leasing/index.js"; import { DispatchError } from "./dispatch.js"; /** why: the refusals of a `lease.request` that carry their own details on the wire, in one place so the dispatcher's catch stays short. */ @@ -11,6 +11,13 @@ export function leaseRequestRefusal(error: unknown): DispatchError | undefined { if (error instanceof LeaseIdTakenError) { return new DispatchError("LEASE_ID_TAKEN", error.message, { leaseId: error.leaseId }); } + if (error instanceof ModeUnavailableError) { + return new DispatchError("MODE_UNAVAILABLE", error.message, { + mode: error.mode, + platform: "ios", + served: error.served, + }); + } if (error instanceof UnknownBaselineError) { return new DispatchError("UNKNOWN_BASELINE", error.message, { name: error.baselineName }); } diff --git a/src/http/lease-declarations.ts b/src/http/lease-declarations.ts index 45b2d7081..fa768ccd6 100644 --- a/src/http/lease-declarations.ts +++ b/src/http/lease-declarations.ts @@ -258,7 +258,7 @@ export const leaseRequestCreateRoute = declareRoute({ 409: ["LEASE_ID_TAKEN", "LEASE_ENDED", "REQUESTER_ALREADY_LEASED"], 403: ["ADMISSION_DENIED"], 404: ["UNKNOWN_BASELINE"], - 422: ["UNKNOWN_MODEL", "BASELINE_MISMATCH", "BASELINE_STALE"], + 422: ["UNKNOWN_MODEL", "MODE_UNAVAILABLE", "BASELINE_MISMATCH", "BASELINE_STALE"], 503: ["NO_CAPACITY", "ADMISSION_FAILED"], }, errorExtras: { diff --git a/src/http/openapi.test.ts b/src/http/openapi.test.ts index 30d827bbd..ea27f049d 100644 --- a/src/http/openapi.test.ts +++ b/src/http/openapi.test.ts @@ -110,7 +110,7 @@ describe("buildOpenApiDocument", () => { "403": ["ADMISSION_DENIED", "FORBIDDEN"], "404": ["UNKNOWN_BASELINE"], "409": ["LEASE_ID_TAKEN", "LEASE_ENDED", "REQUESTER_ALREADY_LEASED"], - "422": ["UNKNOWN_MODEL", "BASELINE_MISMATCH", "BASELINE_STALE"], + "422": ["UNKNOWN_MODEL", "MODE_UNAVAILABLE", "BASELINE_MISMATCH", "BASELINE_STALE"], "503": ["NO_CAPACITY", "ADMISSION_FAILED", "DAEMON_STOPPING", "DAEMON_STARTUP_FAILED"], }); const leaseShape = replySchema(operation("/v1/leases/{id}", "get"), "200").properties diff --git a/src/leasing/acquisition-errors.ts b/src/leasing/acquisition-errors.ts index 294dda87c..5871d5bf5 100644 --- a/src/leasing/acquisition-errors.ts +++ b/src/leasing/acquisition-errors.ts @@ -1,4 +1,5 @@ import { + type DeviceMode, type DeviceRequest, noPhysicalMatch, type PhysicalRequest, @@ -54,6 +55,18 @@ export class VirtualDevicesOffError extends UnknownModelError { } } +/** why: an iOS lease or target whose resolved mode `ios.modes` does not list (ADR 0082 §3); mapped to `MODE_UNAVAILABLE`, and the warm pool reads it as `mode-unavailable`. */ +export class ModeUnavailableError extends Error { + constructor( + readonly mode: DeviceMode, + readonly served: readonly DeviceMode[], + message: string, + ) { + super(message); + this.name = "ModeUnavailableError"; + } +} + export function asError(error: unknown): Error { return error instanceof Error ? error : new Error(String(error)); } diff --git a/src/leasing/acquisition-spec-resolver.ts b/src/leasing/acquisition-spec-resolver.ts index f1675b07e..eb5662299 100644 --- a/src/leasing/acquisition-spec-resolver.ts +++ b/src/leasing/acquisition-spec-resolver.ts @@ -23,7 +23,7 @@ import { UnknownModelError, type VirtualSpec, } from "../core/index.js"; -import { asError, VirtualDevicesOffError } from "./acquisition-errors.js"; +import { asError, ModeUnavailableError, VirtualDevicesOffError } from "./acquisition-errors.js"; import { type LeaseAcquisitionCoordinatorOptions } from "./acquisition-ports.js"; import { downloadingProgress, @@ -57,6 +57,11 @@ export class AcquisitionSpecResolver { return this.options.defaultModes[platform] ?? "full"; } + /** why: the modes this worker serves on a platform; a platform with no `ios.modes` of its own serves both (ADR 0082 §1). */ + servedModes(platform: Platform): readonly DeviceMode[] { + return this.options.servedModes[platform] ?? ["slim", "full"]; + } + async resolveSpec( driver: Driver, request: DeviceRequest, @@ -116,6 +121,7 @@ export class AcquisitionSpecResolver { "except needs a slim lease (this worker's default mode is full)", ); } + this.#requireServed(request.platform, mode); const range = requestedRange(request); const target = range === undefined @@ -135,6 +141,19 @@ export class AcquisitionSpecResolver { }; } + /** why: the asked or default mode is checked before the spec is resolved, so a refused mode downloads nothing (ADR 0082 §2). */ + #requireServed(platform: Platform, mode: DeviceMode): void { + const served = this.servedModes(platform); + if (served.includes(mode)) return; + const other = mode === "full" ? "slim" : "full"; + throw new ModeUnavailableError( + mode, + served, + `This worker does not serve ${mode} iOS simulators (ios.modes is ${JSON.stringify(served)}); ` + + `ask for a ${other} one (--mode ${other}, or mode: "${other}")`, + ); + } + /** 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, diff --git a/src/leasing/index.ts b/src/leasing/index.ts index 837ecd7ea..8fcc3ddeb 100644 --- a/src/leasing/index.ts +++ b/src/leasing/index.ts @@ -2,6 +2,7 @@ export { createLeasing, type UpdateHold } from "./create-leasing.js"; export { capacityReasonOf } from "./acquisition-planner.js"; export { DaemonUpdatingError, + ModeUnavailableError, NoCapacityError, ProvisionFailedError, } from "./lease-acquisition-coordinator.js"; diff --git a/src/leasing/lease-acquisition-coordinator.ts b/src/leasing/lease-acquisition-coordinator.ts index 8fd6c7d0e..90099ce46 100644 --- a/src/leasing/lease-acquisition-coordinator.ts +++ b/src/leasing/lease-acquisition-coordinator.ts @@ -27,6 +27,7 @@ import { WaiterOutcomes } from "./waiter-outcomes.js"; export type { LeaseRequestOptions } from "./wait-queue.js"; export { DaemonUpdatingError, + ModeUnavailableError, NoCapacityError, ProvisionFailedError, } from "./acquisition-errors.js"; diff --git a/website/src/content/docs/docs/reference/errors.mdx b/website/src/content/docs/docs/reference/errors.mdx index 3c69af64b..ac6a8c3f7 100644 --- a/website/src/content/docs/docs/reference/errors.mdx +++ b/website/src/content/docs/docs/reference/errors.mdx @@ -26,7 +26,7 @@ In a script, check `code`, not the message: the wording of a message can change, | 2 | `USAGE`, `BAD_REQUEST`, `BASELINE_MISMATCH`, `BAD_FRAME`, `UNKNOWN_REQUEST`, `IDEMPOTENCY_CONFLICT`, `PASSTHROUGH_REFUSED`, `UNKNOWN_PASSTHROUGH_TOOL`, `SETUP_REFUSED`, `GATEWAY_NOT_PRESENT`, `UPDATE_UNSUPPORTED_INSTALL`, `UPDATE_SHARED_INSTALL`, `UNSUPPORTED_IN_GATEWAY_MODE`, `UNSUPPORTED_IN_WORKER_MODE`, `WORKER_CONNECTED`, `WORKER_NOT_CONNECTED` | The request was wrong. Running it again unchanged fails again. | | 10 | `QUEUE_TIMEOUT`, `EXEC_TIMEOUT`, `DOWNLOAD_TIMEOUT` | A deadline ran out. | | 11 | `NO_CAPACITY`, `DEVICE_BUSY`, `COMPONENT_BUSY` | Busy right now. The same request can pass later. | -| 12 | `NO_DRIVER`, `CAPABILITY_MISSING`, `RUNTIME_MISSING`, `UNKNOWN_MODEL`, `ROTATION_UNSUPPORTED`, `INSUFFICIENT_DISK_SPACE`, `LICENSE_NOT_ACCEPTED`, `DOWNLOADS_DISABLED`, `COMPONENT_NOT_OWNED`, `COMPONENT_IN_USE`, `UNKNOWN_BASELINE`, `BASELINE_STALE`, `BASELINE_IN_USE`, `DEVICE_NOT_ENROLLABLE`, `UNKNOWN_DEVICE`, `HISTORY_NOT_KEPT`, `UNKNOWN_WORKER`, `UNKNOWN_ALERT_DESTINATION` | What you named does not exist here, or this machine cannot provide it. | +| 12 | `NO_DRIVER`, `CAPABILITY_MISSING`, `RUNTIME_MISSING`, `UNKNOWN_MODEL`, `MODE_UNAVAILABLE`, `ROTATION_UNSUPPORTED`, `INSUFFICIENT_DISK_SPACE`, `LICENSE_NOT_ACCEPTED`, `DOWNLOADS_DISABLED`, `COMPONENT_NOT_OWNED`, `COMPONENT_IN_USE`, `UNKNOWN_BASELINE`, `BASELINE_STALE`, `BASELINE_IN_USE`, `DEVICE_NOT_ENROLLABLE`, `UNKNOWN_DEVICE`, `HISTORY_NOT_KEPT`, `UNKNOWN_WORKER`, `UNKNOWN_ALERT_DESTINATION` | What you named does not exist here, or this machine cannot provide it. | | 13 | `REQUESTER_ALREADY_LEASED`, `LEASE_ID_TAKEN`, `LEASE_ENDED` | The request clashes with a lease or request that exists or recently ended. | | 14 | `TUNNEL_LEASE_ENDED` | `simlock lease` without `--detach`: the daemon ended the lease before you did (expiry, an operator's release, or a device that could not be recovered). The `lease-lost` line on stderr gives the reason. | | 15 | — | `simlock component install` with `--worker` or `--all-workers`: at least one worker did not end `installed` or `already-installed`. The result on stdout says which. | @@ -48,6 +48,7 @@ In a script, check `code`, not the message: the wording of a message can change, | `ADMISSION_FAILED` | 16 | 503 | The gateway's admission command could not decide: it exited non-zero, ran past `gateway.admission.timeoutMs`, printed more than 64 KiB or something that is not an answer, was killed, or could not start. The gateway refuses rather than let the request through. The message and the details (`cause`) say which. | Tell the operator: the gateway log names the cause and the command's stderr. The same request can pass once the command is fixed. | | `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. A device that fails to boot, by timing out or by crashing, fails the request at once, unless the request has `--except`. Any other failure is tried again once, and 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`. | +| `MODE_UNAVAILABLE` | 12 | 422 | An iOS lease asks for a device mode this worker does not serve (`ios.modes` lists only the other one), or asks for a slim device on an iOS version below 18.5 that cannot be slimmed. The message names the mode and the setting; the details carry `platform`, `mode` and `served`. | Ask for a mode the worker serves: `--mode slim` or `--mode full`, or `mode: "slim"` or `mode: "full"` over MCP and HTTP. For a version that cannot be slimmed, ask for iOS 18.5 or newer. | | `UNKNOWN_MODEL` | 12 | 422 | The model is not one this platform offers here, no model of the requested class exists, or the worker serves only enrolled devices of the platform (`.virtualDevices` is `false`) and the request did not ask for a physical one. | Run `simlock catalog` for the models and their exact names. When the message names `.virtualDevices`, ask for a physical device: `--physical`, or `physical: true` over MCP and HTTP. | | `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. | diff --git a/website/src/content/docs/docs/using-devices/errors.mdx b/website/src/content/docs/docs/using-devices/errors.mdx index 5cb3e6280..660f66279 100644 --- a/website/src/content/docs/docs/using-devices/errors.mdx +++ b/website/src/content/docs/docs/using-devices/errors.mdx @@ -42,6 +42,7 @@ In a script, check the exit code or `code`, never the message: the message is fo | Code | Exit | What it means | What to do | | --- | --- | --- | --- | | `UNKNOWN_MODEL` | 12 | This machine doesn't know the model, has no model listed for the class, has `ios.virtualDevices` or `android.virtualDevices` set to `false` and the request has no `--physical`, or (with `--physical`) has no enrolled device that could ever match. | Check the spelling against `simlock catalog`. On a phones-only worker the message names the key: ask again with `--physical`. For a class, an admin can name a model in `ios.defaultModels` or `android.defaultModels`. For a physical device, remember `--os` is exact. | +| `MODE_UNAVAILABLE` | 12 | The worker serves only some iOS device modes (`ios.modes`) and the lease needs another: you asked for it, a baseline is that mode, or iOS below 18.5 cannot be slimmed and the worker has no full mode. It fails at once and never waits. | Read the message: it names the mode to ask for instead (`--mode slim` or `--mode full`). For an older iOS, ask for 18.5 or newer. | | `RUNTIME_MISSING` | 12 | The OS version, or the Android image, isn't installed. An OS range or `--image-tag` never downloads. | Pass `--allow-download` for an exact version, or ask an admin to install it. See [Choosing a device](/simlock/docs/using-devices/choosing-a-device#when-the-runtime-is-not-installed). | | `UNKNOWN_BASELINE` | 12 | `--baseline` names a baseline this machine doesn't have. | Check the name with `simlock baseline list`. | | `BASELINE_MISMATCH` | 2 | `--baseline` came with a platform, model, OS, mode or image tag that differs from the baseline. The message names the first one that differs. | Drop that option: the baseline already decides it. | From c19165a7758ee31a4c6cffb564bdffee79a9c4a5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:12:44 +0100 Subject: [PATCH 03/16] test: a slim request below iOS 18.5 is refused on a worker without full (#1651) --- .../dispatcher-leases-served-modes.test.ts | 129 +++++++++++++++--- 1 file changed, 107 insertions(+), 22 deletions(-) diff --git a/src/daemon/dispatcher-leases-served-modes.test.ts b/src/daemon/dispatcher-leases-served-modes.test.ts index b0cf977e9..90ce0c117 100644 --- a/src/daemon/dispatcher-leases-served-modes.test.ts +++ b/src/daemon/dispatcher-leases-served-modes.test.ts @@ -1,30 +1,115 @@ import { describe, expect, it } from "vitest"; import { buildDispatcher, session } from "./test-dispatcher.js"; +type Modes = readonly ("slim" | "full")[] | undefined; + +interface Case { + readonly name: string; + readonly modes: Modes; + readonly request: Record; + readonly granted?: "slim" | "full"; + readonly refused?: { + readonly mode: "slim" | "full"; + readonly message: string; + readonly installs: boolean; + }; +} + +const slimOnly = '["slim"]'; +const askedFull = + `This worker does not serve full iOS simulators (ios.modes is ${slimOnly}); ` + + 'ask for a slim one (--mode slim, or mode: "slim")'; +const cannotSlim = (os: string) => + `iOS ${os} cannot be slimmed, and this worker does not serve full iOS simulators ` + + `(ios.modes is ${slimOnly}); ask for iOS 18.5 or newer`; + +const cases: readonly Case[] = [ + { name: "no mode", modes: ["slim"], request: {}, granted: "slim" }, + { + name: "--mode full", + modes: ["slim"], + request: { mode: "full" }, + refused: { installs: false, message: askedFull, mode: "full" }, + }, + { + name: "--mode slim below 18.5", + modes: ["slim"], + request: { mode: "slim", osVersion: "17.5" }, + refused: { installs: false, message: cannotSlim("17.5"), mode: "full" }, + }, + { + name: "no mode below 18.5", + modes: ["slim"], + request: { osVersion: "17.5" }, + refused: { installs: false, message: cannotSlim("17.5"), mode: "full" }, + }, + { + name: "--mode full --allow-download of a missing version", + modes: ["slim"], + request: { allowDownload: true, mode: "full", osVersion: "26.2" }, + refused: { installs: false, message: askedFull, mode: "full" }, + }, + { + name: "--mode slim --allow-download of a missing version below 18.5", + modes: ["slim"], + request: { allowDownload: true, mode: "slim", osVersion: "17.4" }, + refused: { installs: true, message: cannotSlim("17.4"), mode: "full" }, + }, + { + name: "--mode slim on a full-only worker", + modes: ["full"], + request: { mode: "slim" }, + refused: { + installs: false, + message: + 'This worker does not serve slim iOS simulators (ios.modes is ["full"]); ' + + 'ask for a full one (--mode full, or mode: "full")', + mode: "slim", + }, + }, + { + name: "--mode full with ios.modes unset", + modes: undefined, + request: { mode: "full" }, + granted: "full", + }, +]; + describe("Dispatcher: the iOS modes a worker serves", () => { - it("refuses an iOS lease whose resolved mode ios.modes does not list with MODE_UNAVAILABLE and its details, and grants a served one", async () => { - const { dispatcher } = await buildDispatcher({ - driverOptions: { slimmableOsVersions: ["26.5"] }, - iosModes: ["slim"], - }); - const request = { model: "iPhone 17 Pro", platform: "ios" } as const; + it("refuses an iOS lease whose resolved mode ios.modes does not list with MODE_UNAVAILABLE and its details, before any download unless the version can only be known after it, and grants a served one", async () => { + for (const testCase of cases) { + const { dispatcher, driver, eventBus } = await buildDispatcher({ + driverOptions: { availableOsVersions: ["26.5", "17.5"], slimmableOsVersions: ["26.5"] }, + ...(testCase.modes === undefined ? {} : { iosModes: testCase.modes }), + }); + const request = { model: "iPhone 17 Pro", platform: "ios", ...testCase.request } as const; - const granted = await dispatcher.dispatch( - "lease.request", - { ...request, mode: "slim" }, - session(), - ); - expect(granted.device.mode).toBe("slim"); + const outcome = await dispatcher.dispatch("lease.request", request, session()).then( + (grant) => grant.device.mode, + (error: unknown) => error, + ); - await expect( - dispatcher.dispatch( - "lease.request", - { ...request, mode: "full" }, - session({ principal: "tok_other" }), - ), - ).rejects.toMatchObject({ - code: "MODE_UNAVAILABLE", - details: { mode: "full", platform: "ios", served: ["slim"] }, - }); + if (testCase.granted !== undefined) { + expect(outcome, testCase.name).toBe(testCase.granted); + continue; + } + const refused = testCase.refused!; + expect(outcome, testCase.name).toMatchObject({ + code: "MODE_UNAVAILABLE", + details: { mode: refused.mode, platform: "ios", served: testCase.modes }, + message: refused.message, + }); + const installs = driver.calls.filter((call) => call.operation === "installComponent"); + expect(installs.length > 0, `${testCase.name}: installs`).toBe(refused.installs); + const events = eventBus.replay(); + expect( + events.filter((event) => event.event === "lease.requested"), + `${testCase.name}: stored`, + ).toHaveLength(1); + expect( + events.filter((event) => event.event === "lease.rejected").map((event) => event.payload), + `${testCase.name}: rejected`, + ).toMatchObject([{ reason: "unresolvable-spec" }]); + } }); }); From b9ecbea9e21b483ef531c66176de47ff91adf8c0 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:13:06 +0100 Subject: [PATCH 04/16] feat(leasing): a slim request iOS cannot slim is refused on a worker without full (#1651) --- src/leasing/acquisition-spec-resolver.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/leasing/acquisition-spec-resolver.ts b/src/leasing/acquisition-spec-resolver.ts index eb5662299..8af2f8bde 100644 --- a/src/leasing/acquisition-spec-resolver.ts +++ b/src/leasing/acquisition-spec-resolver.ts @@ -134,6 +134,7 @@ export class AcquisitionSpecResolver { allowDownload: options.allowDownload === true && range === undefined, }); const spec = checkedSpec(resolved, request, mode); + this.#requireNotFallenBack(spec, mode); return { classOf: target.classOf, requirement: target.requirement ?? exactRequirement(spec), @@ -154,6 +155,18 @@ export class AcquisitionSpecResolver { ); } + /** why: a slim request the driver could only answer with a full spec (iOS below 18.5, ADR 0007 §4) is refused on a worker without full, not granted the device the operator turned off (ADR 0082 §2). */ + #requireNotFallenBack(spec: VirtualSpec, asked: DeviceMode): void { + const served = this.servedModes(spec.platform); + if (asked !== "slim" || spec.mode === "slim" || served.includes("full")) return; + throw new ModeUnavailableError( + "full", + served, + `iOS ${spec.osVersion} cannot be slimmed, and this worker does not serve full iOS simulators ` + + `(ios.modes is ${JSON.stringify(served)}); ask for iOS 18.5 or newer`, + ); + } + /** 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, From 8caf54e94ee3ae33eb8127b9a0b142fa04794ba4 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:14:26 +0100 Subject: [PATCH 05/16] test: a baseline of a mode ios.modes does not list is refused, and the other cases stay served (#1651) --- .../dispatcher-leases-served-modes.test.ts | 148 ++++++++++++++++-- 1 file changed, 131 insertions(+), 17 deletions(-) diff --git a/src/daemon/dispatcher-leases-served-modes.test.ts b/src/daemon/dispatcher-leases-served-modes.test.ts index 90ce0c117..b424d4521 100644 --- a/src/daemon/dispatcher-leases-served-modes.test.ts +++ b/src/daemon/dispatcher-leases-served-modes.test.ts @@ -1,13 +1,22 @@ import { describe, expect, it } from "vitest"; +import { FakeDriver } from "../core/testing.js"; +import { FakeClock } from "../ports/index.js"; +import type { StateDatabase } from "../state/index.js"; import { buildDispatcher, session } from "./test-dispatcher.js"; +type Built = Awaited>; +type BuildOptions = NonNullable[0]>; + type Modes = readonly ("slim" | "full")[] | undefined; interface Case { readonly name: string; readonly modes: Modes; readonly request: Record; - readonly granted?: "slim" | "full"; + /** why: the options only this case needs, built with the case's clock so a second driver shares it. */ + readonly setup?: (clock: FakeClock) => BuildOptions; + readonly prepare?: (built: Built) => Promise; + readonly granted?: "slim" | "full" | "physical" | "android"; readonly refused?: { readonly mode: "slim" | "full"; readonly message: string; @@ -23,42 +32,77 @@ const cannotSlim = (os: string) => `iOS ${os} cannot be slimmed, and this worker does not serve full iOS simulators ` + `(ios.modes is ${slimOnly}); ask for iOS 18.5 or newer`; +const phone = { model: "iPhone 17 Pro", platform: "ios" } as const; + +// why: "checkout" is the full baseline a worker made before it switched to slim-only; only its row and source exist, since a refused request never copies it. "quick" is made the way an agent makes one, from a slim lease. +const withBaselines = { + prepare: async ({ dispatcher, driver }: Built) => { + const grant = await dispatcher.dispatch( + "lease.request", + phone, + session({ principal: "maker" }), + ); + await dispatcher.dispatch( + "baseline.save", + { leaseId: grant.lease.id, name: "quick" }, + session({ role: "admin" }), + ); + driver.setSources([ + ...(await driver.listSources()), + { id: "src-checkout", kind: "baseline", model: "iPhone 17 Pro", osVersion: "26.5" }, + ]); + }, + setup: () => ({ + seedState: ({ database }: StateDatabase) => { + database + .prepare( + "INSERT INTO baselines (name, version, platform, model, os_version, mode, saved_at, source_id) VALUES ('checkout', 1, 'ios', 'iPhone 17 Pro', '26.5', 'full', '2026-11-02T13:40:00.000Z', 'src-checkout')", + ) + .run(); + }, + }), +}; + +const baselineRefusal = (mode: string) => + `Baseline "checkout" is ${mode}, and this worker does not serve ${mode} iOS simulators ` + + `(ios.modes is ${slimOnly})`; + const cases: readonly Case[] = [ - { name: "no mode", modes: ["slim"], request: {}, granted: "slim" }, + { name: "no mode", modes: ["slim"], request: phone, granted: "slim" }, { name: "--mode full", modes: ["slim"], - request: { mode: "full" }, + request: { ...phone, mode: "full" }, refused: { installs: false, message: askedFull, mode: "full" }, }, { name: "--mode slim below 18.5", modes: ["slim"], - request: { mode: "slim", osVersion: "17.5" }, + request: { ...phone, mode: "slim", osVersion: "17.5" }, refused: { installs: false, message: cannotSlim("17.5"), mode: "full" }, }, { name: "no mode below 18.5", modes: ["slim"], - request: { osVersion: "17.5" }, + request: { ...phone, osVersion: "17.5" }, refused: { installs: false, message: cannotSlim("17.5"), mode: "full" }, }, { name: "--mode full --allow-download of a missing version", modes: ["slim"], - request: { allowDownload: true, mode: "full", osVersion: "26.2" }, + request: { ...phone, allowDownload: true, mode: "full", osVersion: "26.2" }, refused: { installs: false, message: askedFull, mode: "full" }, }, { name: "--mode slim --allow-download of a missing version below 18.5", modes: ["slim"], - request: { allowDownload: true, mode: "slim", osVersion: "17.4" }, + request: { ...phone, allowDownload: true, mode: "slim", osVersion: "17.4" }, refused: { installs: true, message: cannotSlim("17.4"), mode: "full" }, }, { name: "--mode slim on a full-only worker", modes: ["full"], - request: { mode: "slim" }, + request: { ...phone, mode: "slim" }, refused: { installs: false, message: @@ -70,24 +114,94 @@ const cases: readonly Case[] = [ { name: "--mode full with ios.modes unset", modes: undefined, - request: { mode: "full" }, + request: { ...phone, mode: "full" }, granted: "full", }, + { + name: "a full baseline", + modes: ["slim"], + request: { baseline: "checkout", platform: "ios" }, + ...withBaselines, + refused: { installs: false, message: baselineRefusal("full"), mode: "full" }, + }, + { + name: "a slim baseline", + modes: ["slim"], + request: { baseline: "quick", platform: "ios" }, + ...withBaselines, + granted: "slim", + }, + { + name: "--mode full with --no-wait", + modes: ["slim"], + request: { ...phone, mode: "full", noWait: true }, + refused: { installs: false, message: askedFull, mode: "full" }, + }, + { + name: "--physical", + modes: ["slim"], + request: { model: "iPad Pro", physical: true, platform: "ios" }, + prepare: async ({ driver, engine }) => { + await engine.convergeRunningCapacity(); + driver.setPhysicalPresence("00008110-001A2B3C4D5E", true); + }, + setup: () => ({ + physicalDevices: [ + { + createdAt: 1, + driverDeviceId: "00008110-001A2B3C4D5E", + enrolledApps: [], + id: "dev_phys", + spec: { class: "tablet", model: "iPad Pro", osVersion: "18.4" }, + state: "ready", + }, + ], + }), + granted: "physical", + }, + { + name: "an Android lease", + modes: ["slim"], + request: { model: "Pixel 9", platform: "android" }, + setup: (clock) => ({ + extraDrivers: [ + new FakeDriver({ + availableOsVersions: ["36"], + clock, + knownModels: ["Pixel 9"], + platform: "android", + }), + ], + }), + granted: "android", + }, ]; describe("Dispatcher: the iOS modes a worker serves", () => { it("refuses an iOS lease whose resolved mode ios.modes does not list with MODE_UNAVAILABLE and its details, before any download unless the version can only be known after it, and grants a served one", async () => { for (const testCase of cases) { - const { dispatcher, driver, eventBus } = await buildDispatcher({ + const clock = new FakeClock(1_000); + const built = await buildDispatcher({ + clock, driverOptions: { availableOsVersions: ["26.5", "17.5"], slimmableOsVersions: ["26.5"] }, ...(testCase.modes === undefined ? {} : { iosModes: testCase.modes }), + ...testCase.setup?.(clock), }); - const request = { model: "iPhone 17 Pro", platform: "ios", ...testCase.request } as const; + const { dispatcher, driver, eventBus } = built; + await testCase.prepare?.(built); + const requestedBefore = eventBus.replay().filter((e) => e.event === "lease.requested").length; - const outcome = await dispatcher.dispatch("lease.request", request, session()).then( - (grant) => grant.device.mode, - (error: unknown) => error, - ); + const outcome = await dispatcher + .dispatch("lease.request", testCase.request as never, session()) + .then( + (grant) => + grant.device.physical === true + ? "physical" + : grant.device.spec.platform === "android" + ? "android" + : grant.device.mode, + (error: unknown) => error, + ); if (testCase.granted !== undefined) { expect(outcome, testCase.name).toBe(testCase.granted); @@ -103,9 +217,9 @@ describe("Dispatcher: the iOS modes a worker serves", () => { expect(installs.length > 0, `${testCase.name}: installs`).toBe(refused.installs); const events = eventBus.replay(); expect( - events.filter((event) => event.event === "lease.requested"), + events.filter((event) => event.event === "lease.requested").length - requestedBefore, `${testCase.name}: stored`, - ).toHaveLength(1); + ).toBe(1); expect( events.filter((event) => event.event === "lease.rejected").map((event) => event.payload), `${testCase.name}: rejected`, From 880f0b9121ee14ddb896bbfa8c785ddd5be13dfb Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:14:38 +0100 Subject: [PATCH 06/16] feat(leasing): a baseline of a mode the worker does not serve is refused (#1651) --- src/leasing/acquisition-spec-resolver.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/leasing/acquisition-spec-resolver.ts b/src/leasing/acquisition-spec-resolver.ts index 8af2f8bde..2d9e8672a 100644 --- a/src/leasing/acquisition-spec-resolver.ts +++ b/src/leasing/acquisition-spec-resolver.ts @@ -18,6 +18,7 @@ import { modelClass, type Platform, RuntimeMissingError, + specMode, type TargetResolution, UnknownBaselineError, UnknownModelError, @@ -167,6 +168,19 @@ export class AcquisitionSpecResolver { ); } + /** why: a baseline's own mode is checked as soon as its spec is known, before anything is copied (ADR 0082 §2). */ + #requireBaselineServed(name: string, spec: VirtualSpec): void { + const served = this.servedModes(spec.platform); + const mode = specMode(spec); + if (served.includes(mode)) return; + throw new ModeUnavailableError( + mode, + served, + `Baseline "${name}" is ${mode}, and this worker does not serve ${mode} iOS simulators ` + + `(ios.modes is ${JSON.stringify(served)})`, + ); + } + /** 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, @@ -186,6 +200,7 @@ export class AcquisitionSpecResolver { } if (current.staleReason !== undefined) throw new BaselineStaleError(name, current.staleReason); const spec = baselineSpec(current); + this.#requireBaselineServed(name, spec); if (request.except !== undefined && spec.mode !== "slim") { throw new BadDeviceRequestError(`except needs a slim lease (baseline "${name}" is full)`); } From 9ac33974766265284d4a6ebba3b541d1e7f2b198 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:15:34 +0100 Subject: [PATCH 07/16] test: config set writes ios.modes and refuses what it does not allow (#1651) --- src/cli/index-device-config.test.ts | 43 +++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/src/cli/index-device-config.test.ts b/src/cli/index-device-config.test.ts index 0ad0655b9..4f8ed78ed 100644 --- a/src/cli/index-device-config.test.ts +++ b/src/cli/index-device-config.test.ts @@ -369,6 +369,49 @@ describe("CLI: config set validates with the real config loader (ADR 0003 §11, }, ); + it("config set writes ios.modes as a non-empty list of slim and full each once, and refuses anything else, or a set ios.defaultMode the list leaves out, with the message and exit 2", async () => { + const run = async (key: string, value: string, existing: Record = {}) => { + const output = outputCapture(realCliEnvironmentPorts()); + let written: Record | undefined; + const exitCode = await runCli( + ["config", "set", key, value], + output.environmentWith({ + readConfigFile: async () => structuredClone(existing), + writeConfigFile: async (contents) => { + written = contents; + }, + }), + ); + return { exitCode, stderr: output.stderr, written }; + }; + const shape = + 'Invalid config value for "ios.modes": expected a non-empty list of "slim" and "full", each once'; + + for (const value of ['["slim"]', '["full"]', '["slim","full"]']) { + const accepted = await run("ios.modes", value); + expect([value, accepted.exitCode]).toEqual([value, 0]); + expect(accepted.written).toEqual({ ios: { modes: JSON.parse(value) } }); + } + for (const value of ["[]", '["slim","slim"]', '["fast"]', "slim"]) { + const refused = await run("ios.modes", value); + expect([value, refused.exitCode, refused.written]).toEqual([value, 2, undefined]); + expect(JSON.parse(refused.stderr).error.message, value).toContain(shape); + } + const unlisted = await run("ios.modes", '["slim"]', { ios: { defaultMode: "full" } }); + expect([unlisted.exitCode, unlisted.written]).toEqual([2, undefined]); + expect(JSON.parse(unlisted.stderr).error.message).toContain( + 'Invalid config value for "ios.defaultMode": expected a mode ios.modes lists', + ); + const listed = await run("ios.modes", '["slim"]', { ios: { defaultMode: "slim" } }); + expect([listed.exitCode, listed.written]).toEqual([ + 0, + { ios: { defaultMode: "slim", modes: ["slim"] } }, + ]); + const android = await run("android.modes", '["full"]'); + expect([android.exitCode, android.written]).toEqual([2, undefined]); + expect(android.stderr).toContain('Unknown config key: "android.modes"'); + }); + it("--gateway config set validates against the gateway's rules, not the worker's", async () => { const gatewayHome = { role: "gateway", From 6b7b3fcaf441080948ff43a79aaf63a93976bc8c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:16:39 +0100 Subject: [PATCH 08/16] feat(core): ios.modes lists the iOS modes a worker serves, and a default follows it (#1651) --- src/cli/index-device-config.test.ts | 4 +++- src/contract/config-schemas.ts | 7 ++++++- src/core/config-role-checks.ts | 21 +++++++++++++++++++ src/core/config-validators.ts | 12 +++++++++++ src/core/config.ts | 5 ++++- .../docs/docs/reference/configuration.mdx | 3 ++- 6 files changed, 48 insertions(+), 4 deletions(-) diff --git a/src/cli/index-device-config.test.ts b/src/cli/index-device-config.test.ts index 4f8ed78ed..28903ed8c 100644 --- a/src/cli/index-device-config.test.ts +++ b/src/cli/index-device-config.test.ts @@ -409,7 +409,9 @@ describe("CLI: config set validates with the real config loader (ADR 0003 §11, ]); const android = await run("android.modes", '["full"]'); expect([android.exitCode, android.written]).toEqual([2, undefined]); - expect(android.stderr).toContain('Unknown config key: "android.modes"'); + expect(JSON.parse(android.stderr).error.message).toContain( + 'Unknown config key: "android.modes"', + ); }); it("--gateway config set validates against the gateway's rules, not the worker's", async () => { diff --git a/src/contract/config-schemas.ts b/src/contract/config-schemas.ts index b97c08923..a61ccb8b6 100644 --- a/src/contract/config-schemas.ts +++ b/src/contract/config-schemas.ts @@ -150,7 +150,12 @@ export const configSchema = z.object({ }), // why: a platform's section also holds its driver's own keys, which no client reads: they are carried as the worker's loader validated them, the way a module's `capabilities` section is, so a new driver key changes no wire shape. ios: z - .object({ defaultMode: deviceModeSchema, defaultModels: defaultModelsSchema }) + .object({ + defaultMode: deviceModeSchema, + defaultModels: defaultModelsSchema, + // why: optional, since a worker from before ADR 0082 sends none and serves both. + modes: z.array(deviceModeSchema).min(1).max(2).optional(), + }) .catchall(z.unknown()), android: z .object({ defaultImageTag: imageTagSchema.optional(), defaultModels: defaultModelsSchema }) diff --git a/src/core/config-role-checks.ts b/src/core/config-role-checks.ts index f9f46790b..17dedecd6 100644 --- a/src/core/config-role-checks.ts +++ b/src/core/config-role-checks.ts @@ -49,6 +49,27 @@ export function validateDeletedRetention(config: Config): void { } } +/** + * why: ADR 0082 §1: a worker must serve the mode it gives a request that names none. A default + * the operator wrote must be listed; one they did not write follows a one-mode list. "Wrote" is + * read from the layers, since the merged config holds the built-in `full` either way. + */ +export function applyServedModesDefault(config: Config, layers: readonly unknown[]): Config { + const written = layers.some( + (layer) => asObject(asObject(layer)["ios"])["defaultMode"] !== undefined, + ); + if (written) { + if (!config.ios.modes.includes(config.ios.defaultMode)) { + throw invalidValue("ios.defaultMode", "a mode ios.modes lists"); + } + return config; + } + const [only] = config.ios.modes; + return config.ios.modes.length === 1 && only !== undefined + ? { ...config, ios: { ...config.ios, defaultMode: only } } + : config; +} + export function validateEventLogBounds(config: Config): void { if (config.eventLog.maxBytes < MIN_EVENT_LOG_MAX_BYTES) { throw invalidValue("eventLog.maxBytes", "at least 16 MiB"); diff --git a/src/core/config-validators.ts b/src/core/config-validators.ts index f4eda535b..68a5cedfa 100644 --- a/src/core/config-validators.ts +++ b/src/core/config-validators.ts @@ -256,6 +256,7 @@ export function configValidators( ...driverValidators(driverSections, "ios"), defaultMode: stringUnion(["slim", "full"]), defaultModels: defaultModelsValidator, + modes: modesValidator, virtualDevices: booleanValue, }), android: objectValidator({ @@ -344,6 +345,17 @@ const imageTagValidator: Validator = (value, path) => { return value; }; +/** why: ADR 0082 §1: the iOS modes a worker serves are `slim`, `full` or both, each once; a repeat or an unknown name is refused rather than ignored so the list says what the worker does. */ +const modesValidator: Validator = (value, path) => { + const valid = + Array.isArray(value) && + value.length > 0 && + value.every((mode) => mode === "slim" || mode === "full") && + new Set(value).size === value.length; + if (!valid) throw invalidValue(path, 'a non-empty list of "slim" and "full", each once'); + return value as readonly ("slim" | "full")[]; +}; + /** * why: Each key is a device class and each value one non-empty model name or a non-empty list of * them, stored as a list. Any other key is refused rather than warned about: a misspelled class diff --git a/src/core/config.ts b/src/core/config.ts index 7ecca7f10..1e3b11b31 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -14,6 +14,7 @@ import { resolveStrategyName, runDriverChecks, runModuleChecks, + applyServedModesDefault, validateDeletedRetention, validateEventLogBounds, validateGatewayMembership, @@ -206,6 +207,7 @@ export function configFromLayers( // why: a gateway reads a module's gateway keys, so a bad value stops it too. runModuleChecks(merged, modules); runDriverChecks(merged, driverSections); + let loaded = merged; if (role === "gateway") { warnWorkerOnlyKeys([fromFile, fromOverrides], warn, modules); requireGatewayHttp(merged); @@ -215,8 +217,9 @@ export function configFromLayers( validateGatewayMembership(merged); // why: only a worker keeps device records, so only it reads `devices.deletedRetentionMs`. validateDeletedRetention(merged); + loaded = applyServedModesDefault(merged, layers); } - return { config: deepFreeze(merged), defaulted }; + return { config: deepFreeze(loaded), defaulted }; } async function readConfigFile(filesystem: Filesystem, configPath: string): Promise { diff --git a/website/src/content/docs/docs/reference/configuration.mdx b/website/src/content/docs/docs/reference/configuration.mdx index c057f9878..13760241e 100644 --- a/website/src/content/docs/docs/reference/configuration.mdx +++ b/website/src/content/docs/docs/reference/configuration.mdx @@ -202,7 +202,8 @@ The warm pool never downloads. A gateway never asks a worker to download for a l | Key | Type | Default | Meaning | Applies to | | ---------------------------------- | ---------------------------------- | -------------------------------- | --------------------------------------------------------------------------------------------------------- | ---------- | -| `ios.defaultMode` | `slim` or `full` | `full` | Device mode for an iOS request that names none. The worker makes both kinds either way. | Worker | +| `ios.defaultMode` | `slim` or `full` | `full`, or the one mode `ios.modes` lists when this is not set | Device mode for an iOS request that names none. It must be a mode `ios.modes` lists, or the config fails to load. | Worker | +| `ios.modes` | list of `slim` and `full`, each once | `["slim","full"]` | The iOS device modes this worker serves. A lease, warm target or learned kind of another mode is refused at once with `MODE_UNAVAILABLE`, and a slim request on iOS below 18.5 is refused too when `full` is not listed. Needs a daemon restart. See [Choosing a device](/simlock/docs/using-devices/choosing-a-device#modes-a-worker-serves). | Worker | | `ios.slim.categories` | list of strings | every category | Which groups of simulator services a slim device has turned off: `widgets`, `siri`, `search`, `icloud`, `store`, `pim`, `web`, `family`, `health`, `photos`, `apps`, `messaging`, `connectivity`, `telemetry`, `mdm`, `other`. Narrowing the list turns the dropped services back on the next time a device is prepared. `categories` and `exclude` turn services off; `include` keeps them running. | Worker | | `ios.slim.include` | list of strings | none | Launchd service names, such as `com.apple.apsd`, that a slim device keeps running even when a category turns them off. A name that is no service does nothing, and Simlock does not warn. A name in `exclude` too fails the config load. | Worker | | `ios.slim.exclude` | list of strings | none | Launchd service names, such as `com.apple.diagnosticd`, that a slim device turns off beside its categories. This includes services no category holds and the three that slim never turns off (`assistantd`, `gamed`, `sharingd`). A lease's `--except` category still keeps its own services running. With `categories` set to `[]`, a list here alone makes a device slim. Removing a name turns the service back on the next time a device is prepared, except in a saved baseline made before this key existed; put the name in `include` for those. | Worker | From ac8f48e7c4123c35a1516dd0e27a747e880bc24f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:17:20 +0100 Subject: [PATCH 09/16] test: ios.modes defaults, follows a one-mode list and is ignored on a gateway (#1651) --- ...onfig-platform-and-driver-settings.test.ts | 41 +++++++++++++++++++ src/daemon/dispatcher.test.ts | 9 +++- src/daemon/test-dispatcher.ts | 35 +++++++--------- 3 files changed, 63 insertions(+), 22 deletions(-) diff --git a/src/core/config-platform-and-driver-settings.test.ts b/src/core/config-platform-and-driver-settings.test.ts index 88e9f73f3..88e6422f0 100644 --- a/src/core/config-platform-and-driver-settings.test.ts +++ b/src/core/config-platform-and-driver-settings.test.ts @@ -115,6 +115,47 @@ describe("loadConfig", () => { ); }); + it("loads ios.modes as both when unset, makes ios.defaultMode follow a one-mode list that leaves it unset, and ignores the key with a warning on a gateway", async () => { + const load = async (file: unknown, role: "gateway" | "worker" = "worker") => { + const filesystem = new MemoryFilesystem(); + const warn = vi.fn(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic(configPath, JSON.stringify(file)); + const config = await loadConfig({ + configPath, + filesystem, + role, + systemStats: createStats(), + warn, + }); + return { config, warn }; + }; + + const seen = async (ios: object) => { + const { config } = await load({ ios }); + return [config.ios.modes, config.ios.defaultMode]; + }; + expect([ + await seen({}), + await seen({ modes: ["full"] }), + await seen({ modes: ["slim"] }), + await seen({ modes: ["slim", "full"] }), + await seen({ modes: ["slim", "full"], defaultMode: "slim" }), + await seen({ defaultMode: "slim" }), + ]).toEqual([ + [["slim", "full"], "full"], + [["full"], "full"], + [["slim"], "slim"], + [["slim", "full"], "full"], + [["slim", "full"], "slim"], + [["slim", "full"], "slim"], + ]); + const gateway = await load({ ios: { modes: ["slim"] } }, "gateway"); + expect(gateway.warn).toHaveBeenCalledWith( + 'Ignoring "ios": it configures a worker, and this daemon runs in gateway mode.', + ); + }); + it.each(["fast", "worker", true])( "rejects an ios.defaultMode of %j, naming the key", async (value) => { diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index ebc677eb8..85012cc67 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -408,17 +408,22 @@ describe("Dispatcher: the fleet operations on a worker", () => { expect(workers[0]?.catalog?.flatMap((entry) => entry.runtimes)).toEqual(["26.5"]); }); - it("an admin reads the config and sees ios.full.bootTimeoutMs and android.bootTimeoutMs", async () => { + it("an admin reads the config and sees ios.full.bootTimeoutMs, android.bootTimeoutMs and ios.modes, both when unset", async () => { const configured = await buildDispatcher({ bootTimeouts: { android: 600_000, iosFull: 400_000 }, + iosModes: ["slim"], }); + const unset = await buildDispatcher({}); const config = await configured.dispatcher.dispatch("config.get", {}, admin); + const defaults = await unset.dispatcher.dispatch("config.get", {}, admin); - expect([config.ios["full"], config.android["bootTimeoutMs"]]).toEqual([ + expect([config.ios["full"], config.android["bootTimeoutMs"], config.ios.modes]).toEqual([ { bootTimeoutMs: 400_000 }, 600_000, + ["slim"], ]); + expect(defaults.ios.modes).toEqual(["slim", "full"]); }); it("config.get carries android.defaultImageTag when set and leaves it out when not", async () => { diff --git a/src/daemon/test-dispatcher.ts b/src/daemon/test-dispatcher.ts index 71a54db99..b0da445da 100644 --- a/src/daemon/test-dispatcher.ts +++ b/src/daemon/test-dispatcher.ts @@ -254,6 +254,19 @@ export async function buildDispatcher( ), overrides.http, ); + const modes = overrides.iosModes; + const ios: Config["ios"] = { + ...baseConfig.ios, + ...(modes === undefined ? {} : { modes }), + ...(overrides.iosDefaultMode === undefined + ? modes?.length === 1 + ? { defaultMode: modes[0]! } + : {} + : { defaultMode: overrides.iosDefaultMode }), + ...(overrides.bootTimeouts === undefined + ? {} + : { full: { bootTimeoutMs: overrides.bootTimeouts.iosFull } }), + }; const config: Config = withVirtualDevices( { ...baseConfig, @@ -263,28 +276,10 @@ export async function buildDispatcher( android: { ...baseConfig.android, defaultImageTag: overrides.androidDefaultImageTag }, }), warmPool: { ...baseConfig.warmPool, ...overrides.warmPool }, - ...(overrides.iosDefaultMode === undefined - ? {} - : { ios: { ...baseConfig.ios, defaultMode: overrides.iosDefaultMode } }), - ...(overrides.iosModes === undefined - ? {} - : { - ios: { - ...baseConfig.ios, - defaultMode: - overrides.iosDefaultMode ?? - (overrides.iosModes.length === 1 - ? overrides.iosModes[0]! - : baseConfig.ios.defaultMode), - modes: overrides.iosModes, - }, - }), + ios, ...(overrides.bootTimeouts === undefined ? {} - : { - android: { ...baseConfig.android, bootTimeoutMs: overrides.bootTimeouts.android }, - ios: { ...baseConfig.ios, full: { bootTimeoutMs: overrides.bootTimeouts.iosFull } }, - }), + : { android: { ...baseConfig.android, bootTimeoutMs: overrides.bootTimeouts.android } }), }, overrides.virtualDevices, ); From fc1846e187c7e7732e103a7bc7c35e9f81e6f22c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:19:49 +0100 Subject: [PATCH 10/16] test: a worker without full reports a full warm target mode-unavailable and boots no full device (#1651) --- src/core/doctor-types.ts | 7 +- src/core/doctor-warm-pool-targets.test.ts | 2 +- src/core/nuke.test.ts | 2 +- src/core/reaper.test.ts | 2 +- src/core/test-doctor.ts | 2 +- src/daemon/driver-discovery.test.ts | 3 +- ...ate-leasing-warm-pool-served-modes.test.ts | 147 ++++++++++++++++++ src/leasing/physical-leasing.test.ts | 2 +- src/leasing/test-create-leasing.ts | 17 +- src/leasing/test-lease-end-participants.ts | 2 +- src/leasing/test-physical-device-watcher.ts | 2 +- 11 files changed, 176 insertions(+), 12 deletions(-) create mode 100644 src/leasing/create-leasing-warm-pool-served-modes.test.ts diff --git a/src/core/doctor-types.ts b/src/core/doctor-types.ts index 673f6eca5..b14225fc3 100644 --- a/src/core/doctor-types.ts +++ b/src/core/doctor-types.ts @@ -139,8 +139,11 @@ export interface DoctorQuarantine { enterFromStalledTransition(deviceId: string, findingState: DeviceState): Promise; } -export type DoctorConfig = Pick & - Readonly>>; +export type DoctorConfig = Pick & { + readonly android: Pick; + /** why: `modes` is the list a `mode-unavailable` finding names (ADR 0082 §2). */ + readonly ios: Pick; +}; export interface DoctorOptions { readonly clock: Clock; diff --git a/src/core/doctor-warm-pool-targets.test.ts b/src/core/doctor-warm-pool-targets.test.ts index 30c0b8239..d730ed082 100644 --- a/src/core/doctor-warm-pool-targets.test.ts +++ b/src/core/doctor-warm-pool-targets.test.ts @@ -62,7 +62,7 @@ describe("Doctor: warm pool targets", () => { config: { ...base, android: { virtualDevices: options.virtualDevices?.android ?? true }, - ios: { virtualDevices: options.virtualDevices?.ios ?? true }, + ios: { ...base.ios, virtualDevices: options.virtualDevices?.ios ?? true }, warmPool: { ...base.warmPool, enabled: options.enabled ?? true, diff --git a/src/core/nuke.test.ts b/src/core/nuke.test.ts index 588d4d902..641855d5e 100644 --- a/src/core/nuke.test.ts +++ b/src/core/nuke.test.ts @@ -295,7 +295,7 @@ function config(): TestEngineConfig { return { android: { virtualDevices: true }, devices: { autoEnroll: false, deletedRetentionMs: 3_600_000 }, - ios: { virtualDevices: true }, + ios: { modes: ["slim", "full"], virtualDevices: true }, health: { enabled: true, maxConcurrentRecoveries: 1, diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index cb9723f8d..581314506 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -49,7 +49,7 @@ function config(): ReaperTestConfig { return { android: { virtualDevices: true }, devices: { autoEnroll: false, deletedRetentionMs: 3_600_000 }, - ios: { virtualDevices: true }, + ios: { modes: ["slim", "full"], virtualDevices: true }, diskPressure: { freeBytesThreshold: 10 * gibibyte }, health: { enabled: true, diff --git a/src/core/test-doctor.ts b/src/core/test-doctor.ts index 36bc6e47e..302086fd6 100644 --- a/src/core/test-doctor.ts +++ b/src/core/test-doctor.ts @@ -74,7 +74,7 @@ export function config( return { android: { virtualDevices: true }, devices: { autoEnroll: false, deletedRetentionMs: 3_600_000 }, - ios: { virtualDevices: true }, + ios: { modes: ["slim", "full"], virtualDevices: true }, health: { enabled: true, maxConcurrentRecoveries: 1, diff --git a/src/daemon/driver-discovery.test.ts b/src/daemon/driver-discovery.test.ts index 31b80b68f..bd53624fd 100644 --- a/src/daemon/driver-discovery.test.ts +++ b/src/daemon/driver-discovery.test.ts @@ -640,7 +640,7 @@ async function discoverIos( describe("deviceModeWiring", () => { it.each(["slim", "full"] as const)( - "maps ios.defaultMode %s to the default-mode map and to whether the iOS default is slim", + "maps ios.defaultMode %s to the default-mode map and to whether the iOS default is slim, and ios.modes to the served-mode map", (defaultMode) => { expect( deviceModeWiring({ @@ -654,6 +654,7 @@ describe("deviceModeWiring", () => { }), ).toMatchObject({ defaultModes: { ios: defaultMode }, + servedModes: { ios: ["slim", "full"] }, slimByDefault: defaultMode === "slim", }); }, diff --git a/src/leasing/create-leasing-warm-pool-served-modes.test.ts b/src/leasing/create-leasing-warm-pool-served-modes.test.ts new file mode 100644 index 000000000..86f5552a6 --- /dev/null +++ b/src/leasing/create-leasing-warm-pool-served-modes.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, it, vi } from "vitest"; +import { FakeDriver, openTestState } from "../core/testing.js"; +import { FakeClock } from "../ports/index.js"; +import { createHarness, flush, seedReady } from "./test-create-leasing.js"; + +type Harness = Awaited>; +type Modes = readonly ("slim" | "full")[]; + +const LIMITS = { + android: { maxDevices: 1, maxRunning: 1 }, + ios: { maxDevices: 6, maxRunning: 6 }, + maxRunning: 6, +}; + +const phone = { model: "iPhone 16", platform: "ios" } as const; + +function iosDriver(): FakeDriver { + return new FakeDriver({ + availableOsVersions: ["26.1", "17.5"], + clock: new FakeClock(1_000), + knownModels: ["iPhone 15", "iPhone 16", "iPhone 17"], + platform: "ios", + slimmableOsVersions: ["26.1"], + }); +} + +// why: the engine reads a baseline from `baselines` and copies the source the driver holds, so a row and a saved source stand in for an operator's save. +async function saveFullBaseline(harness: Harness, name: string): Promise { + const spec = { ...phone, osVersion: "26.1", physical: false } as const; + const driverDevice = await harness.driver.provision(spec); + const ready = await harness.driver.makeReady(driverDevice, { mode: "full", purpose: "prepare" }); + const saved = await harness.driver.saveSource({ ...ready, physical: false }); + harness.state.database + .prepare( + `INSERT INTO baselines (name, version, platform, model, os_version, mode, saved_at, source_id) + VALUES (?, 1, 'ios', 'iPhone 16', '26.1', 'full', '2026-11-03T00:00:00.000Z', ?)`, + ) + .run(name, saved.sourceId); +} + +const learnedKinds = (harness: Harness) => + harness.engine.figures().targets.filter((target) => target.origin === "learned"); + +const learnCases: readonly { + readonly kept: boolean; + readonly learn: "full" | "full baseline" | "slim"; + readonly modes: Modes; +}[] = [ + { kept: false, learn: "full", modes: ["slim"] }, + { kept: false, learn: "full baseline", modes: ["slim"] }, + { kept: false, learn: "slim", modes: ["full"] }, + { kept: true, learn: "slim", modes: ["slim"] }, + { kept: true, learn: "full", modes: ["slim", "full"] }, +]; + +// why: a worker that learned a kind while it served both modes, then restarts serving fewer, on the same state. +async function learnedAfterSwitch( + learn: "full" | "full baseline" | "slim", + modes: Modes, +): Promise { + const state = await openTestState(); + const options = { + driver: iosDriver(), + limits: LIMITS, + startPool: true, + state, + warmPool: { baselineLearnAfter: 1 }, + }; + const before = await createHarness(options); + if (learn === "full baseline") await saveFullBaseline(before, "checkout"); + const asked = + learn === "full baseline" + ? { baseline: "checkout", platform: "ios" as const } + : { ...phone, mode: learn, osVersion: "26.1" }; + const grant = await before.engine.request(asked, { ownerId: "learner", requesterId: "learner" }); + await before.engine.release(grant.lease.id, "explicit"); + await flush(); + await before.engine.core.passWarmPool(); + expect(learnedKinds(before), learn).toHaveLength(1); + before.engine.dispose(); + + const after = await createHarness({ ...options, firstId: 5_000, iosModes: modes }); + await after.engine.core.passWarmPool(); + await after.engine.settle(); + return learnedKinds(after).length; +} + +async function idleFullDeviceIsTargeted(modes: Modes): Promise { + const harness = await createHarness({ + driver: iosDriver(), + iosModes: modes, + limits: LIMITS, + startPool: true, + warmPool: { + targets: [{ count: 1, mode: "full", model: "iPhone 16", osVersion: "26.1", platform: "ios" }], + }, + }); + const idle = await seedReady(harness, { ...phone, osVersion: "26.1", physical: false }); + await harness.engine.core.passWarmPool(); + await harness.engine.settle(); + return (await harness.engine.core.targetedDevices()).has(idle.id); +} + +describe("the warm pool on a worker that does not serve every iOS mode", () => { + it("reports a full target, and a mode-less target on iOS below 18.5, short mode-unavailable and boots nothing for them, fills a slim target, forgets a learned kind whose mode is not served, and stops sparing an idle full device", async () => { + const driver = iosDriver(); + const harness = await createHarness({ + driver, + iosModes: ["slim"], + limits: LIMITS, + startPool: true, + warmPool: { + targets: [ + { count: 1, mode: "full", model: "iPhone 16", osVersion: "26.1", platform: "ios" }, + { count: 1, model: "iPhone 15", osVersion: "17.5", platform: "ios" }, + { count: 1, mode: "slim", model: "iPhone 17", osVersion: "26.1", platform: "ios" }, + ], + }, + }); + await harness.engine.core.passWarmPool(); + await vi.waitFor(() => + expect( + harness.engine.figures().targets.find((target) => target.model === "iPhone 17"), + ).toMatchObject({ ready: 1 }), + ); + await harness.engine.settle(); + + const byModel = (model: string) => + harness.engine.figures().targets.find((target) => target.model === model); + expect(byModel("iPhone 16")).toMatchObject({ booting: 0, ready: 0, short: "mode-unavailable" }); + expect(byModel("iPhone 15")).toMatchObject({ booting: 0, ready: 0, short: "mode-unavailable" }); + expect(byModel("iPhone 17")).toMatchObject({ mode: "slim", ready: 1 }); + expect(byModel("iPhone 17")).not.toHaveProperty("short"); + expect(driver.calls.filter((call) => call.operation === "makeReady")).toHaveLength(1); + + for (const { kept, learn, modes } of learnCases) { + expect(await learnedAfterSwitch(learn, modes), `${learn} on ${JSON.stringify(modes)}`).toBe( + kept ? 1 : 0, + ); + } + + expect([ + await idleFullDeviceIsTargeted(["slim", "full"]), + await idleFullDeviceIsTargeted(["slim"]), + ]).toEqual([true, false]); + }); +}); diff --git a/src/leasing/physical-leasing.test.ts b/src/leasing/physical-leasing.test.ts index 48cf049b3..907e37354 100644 --- a/src/leasing/physical-leasing.test.ts +++ b/src/leasing/physical-leasing.test.ts @@ -33,7 +33,7 @@ function config(leaseOverrides: object = {}): TestEngineConfig { return { android: { virtualDevices: true }, devices: { autoEnroll: false, deletedRetentionMs: 3_600_000 }, - ios: { virtualDevices: true }, + ios: { modes: ["slim", "full"], virtualDevices: true }, health: { enabled: true, maxConcurrentRecoveries: 1, diff --git a/src/leasing/test-create-leasing.ts b/src/leasing/test-create-leasing.ts index c184be2e2..00241fe16 100644 --- a/src/leasing/test-create-leasing.ts +++ b/src/leasing/test-create-leasing.ts @@ -40,7 +40,7 @@ export function config( return { android: { virtualDevices: true }, devices: { autoEnroll: false, deletedRetentionMs: 3_600_000 }, - ios: { virtualDevices: true }, + ios: { modes: ["slim", "full"], virtualDevices: true }, health: { enabled: true, maxConcurrentRecoveries: 1, @@ -143,6 +143,8 @@ export async function createHarness( readonly idleShutdownAfterMs?: number; /** why: a platform a test turns `.virtualDevices` off for (ADR 0084). */ readonly virtualDevices?: Readonly>>; + /** why: the iOS modes the worker serves; the default mode follows a one-mode list as the config loader makes it (ADR 0082 §1). */ + readonly iosModes?: readonly DeviceMode[]; /** why: starts the warm pool as the daemon's startup does, so it learns from the leases and reacts to events. */ readonly startPool?: boolean; } = {}, @@ -173,7 +175,10 @@ export async function createHarness( ...baseConfig, android: { virtualDevices: options.virtualDevices?.android ?? true }, capacity: capacityConfig(baseConfig, options), - ios: { virtualDevices: options.virtualDevices?.ios ?? true }, + ios: { + modes: options.iosModes ?? ["slim", "full"], + virtualDevices: options.virtualDevices?.ios ?? true, + }, }; const totalRamBytes = options.totalRamBytes ?? 32 * gibibyte; const drivers = options.drivers ?? [driver]; @@ -193,6 +198,14 @@ export async function createHarness( ? {} : { defaultImageTags: options.defaultImageTags }), ...(options.defaultModes === undefined ? {} : { defaultModes: options.defaultModes }), + ...(options.iosModes === undefined + ? {} + : { + defaultModes: options.defaultModes ?? { + ios: options.iosModes.length === 1 ? options.iosModes[0]! : "full", + }, + servedModes: { ios: options.iosModes }, + }), eventBus: bus, idGenerator: { generate: () => `request-${nextId++}` }, ...(options.leaseEndParticipants === undefined diff --git a/src/leasing/test-lease-end-participants.ts b/src/leasing/test-lease-end-participants.ts index b90165633..1227fa20e 100644 --- a/src/leasing/test-lease-end-participants.ts +++ b/src/leasing/test-lease-end-participants.ts @@ -96,7 +96,7 @@ function config(options: EngineOptions): TestEngineConfig { return { android: { virtualDevices: true }, devices: { autoEnroll: false, deletedRetentionMs: 3_600_000 }, - ios: { virtualDevices: true }, + ios: { modes: ["slim", "full"], virtualDevices: true }, health: { enabled: true, maxConcurrentRecoveries: 1, diff --git a/src/leasing/test-physical-device-watcher.ts b/src/leasing/test-physical-device-watcher.ts index aa6f4ef6d..9e44b5f85 100644 --- a/src/leasing/test-physical-device-watcher.ts +++ b/src/leasing/test-physical-device-watcher.ts @@ -34,7 +34,7 @@ function config(options: HarnessOptions): TestEngineConfig { return { android: { virtualDevices: true }, devices: { autoEnroll: false, deletedRetentionMs: 3_600_000 }, - ios: { virtualDevices: true }, + ios: { modes: ["slim", "full"], virtualDevices: true }, health: { enabled: true, maxConcurrentRecoveries: 1, From 93c4097cb2f6d8f98f09dfb22ca4efe9bea0a283 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:27:48 +0100 Subject: [PATCH 11/16] feat: the catalog names the iOS modes a worker serves, docs for ios.modes (#1651) --- docs/internal/flows/device-selection.md | 5 ++- src/cli/commands/catalog.ts | 3 ++ src/cli/index-catalog-components.test.ts | 42 +++++++++++++++++++ src/contract/report-schemas.ts | 2 +- src/contract/status-schemas.ts | 3 ++ src/core/create-core.ts | 1 + src/core/doctor-findings.ts | 15 +++++++ src/core/doctor-types.ts | 2 +- src/core/doctor.ts | 3 +- src/core/domain.ts | 13 ++++-- src/core/warm-pool/AGENTS.md | 2 +- src/core/warm-pool/catalog-check.ts | 19 ++++++++- src/core/warm-pool/converger.ts | 8 +++- src/daemon/dispatcher-status.ts | 11 ++++- src/daemon/dispatcher.test.ts | 15 ++++++- src/leasing/AGENTS.md | 4 ++ src/leasing/acquisition-spec-resolver.ts | 1 + ...ate-leasing-warm-pool-served-modes.test.ts | 33 +++++++++++++++ .../docs/using-devices/choosing-a-device.mdx | 14 +++++++ .../src/content/docs/docs/worker/capacity.mdx | 4 +- .../docs/docs/worker/configuration.mdx | 1 + .../docs/docs/worker/troubleshooting.mdx | 2 +- 22 files changed, 183 insertions(+), 20 deletions(-) diff --git a/docs/internal/flows/device-selection.md b/docs/internal/flows/device-selection.md index 2739b0db6..fbe5f24ec 100644 --- a/docs/internal/flows/device-selection.md +++ b/docs/internal/flows/device-selection.md @@ -12,7 +12,8 @@ How one lease request becomes one concrete device, virtual or physical. |---|---|---| | Request: `model` or `class`, `osVersion` (exact or range), `mode`, `imageTag`, `physical`, `allowDownload`, `noWait` | `contract/operations.ts` → `DeviceRequest` | Per request | | Download permission | `downloads.policy` (`on-request`), `daemon/dispatcher-leases.ts` | Per request, before leasing | -| Default mode | `ios.defaultMode` (`full`); Android always `full` | Per request with no `mode` | +| Default mode | `ios.defaultMode` (`full`, or the only mode `ios.modes` lists); Android always `full` | Per request with no `mode` | +| Served modes | `ios.modes` (both) | A worker refuses a lease, target or learned kind of an unlisted iOS mode, `MODE_UNAVAILABLE` | | Operator preference lists | `ios.defaultModels`, `android.defaultModels` | Merged once at start | | Built-in preference lists | `Driver.defaultModels` of each driver | Merged once at start, after the operator's | | Catalog | `DriverCatalog.listCatalog` → `Driver.listCatalog` | Per class or range request; built on every read (Android keeps only its `avdmanager list device` answer, below) | @@ -35,7 +36,7 @@ In `AcquisitionSpecResolver` (`leasing/acquisition-spec-resolver.ts`), a part of 1. `physical: true` → skip to the physical branch. A virtual Android request with no `imageTag` on a worker with `android.defaultImageTag` is tried first as if it named that tag, with downloads off and `defaultTag` set so only host-CPU images count; a `RuntimeMissingError` runs steps 2 to 9 again on the request as it came (ADR 0078). -2. Mode = request's, else the platform default. +2. Mode = request's, else the platform default. An iOS mode `ios.modes` leaves out is refused (`ModeUnavailableError`) here, before step 3 reads or downloads anything; a baseline's mode is checked the same way, and the slim-to-full fallback of step 8 is checked once more (ADR 0082). 3. Shape of the request: - exact model, no range → used as is; no catalog read. - no model, no range → class (none named = `phone`). diff --git a/src/cli/commands/catalog.ts b/src/cli/commands/catalog.ts index 024b49519..dd4307202 100644 --- a/src/cli/commands/catalog.ts +++ b/src/cli/commands/catalog.ts @@ -78,6 +78,9 @@ function formatCatalog(response: CatalogGetOutput): string { `Platform: ${entry.platform}`, ...phonesOnlyLine(entry), ` Runtimes: ${entry.runtimes.length > 0 ? esc(entry.runtimes.join(", ")) : "(none)"} (default: ${esc(defaultRuntime)})`, + ...(entry.platform === "ios" + ? [` Modes served: ${(entry.modes ?? ["slim", "full"]).join(", ")}`] + : []), ...(entry.defaultImageTag === undefined ? [] : [` Default image tag: ${esc(entry.defaultImageTag)}`]), diff --git a/src/cli/index-catalog-components.test.ts b/src/cli/index-catalog-components.test.ts index bb7f9f6f9..d9ee13656 100644 --- a/src/cli/index-catalog-components.test.ts +++ b/src/cli/index-catalog-components.test.ts @@ -93,6 +93,46 @@ describe("CLI: catalog", () => { expect(JSON.parse(await run(["catalog", "--json"]))).toEqual({ platforms: [entry] }); }); + it("prints the modes an iOS worker serves after the runtimes line, both when it sends none, and nothing for Android; --json carries what was sent", async () => { + const entryOf = (platform: "android" | "ios", modes?: ("slim" | "full")[]) => ({ + classDefaults: {}, + modelAliases: {}, + modelClasses: {}, + modelRuntimes: {}, + models: [], + platform, + runtimes: [], + ...(modes === undefined ? {} : { modes }), + }); + const run = async (arguments_: string[], entry: ReturnType) => { + const output = outputCapture(); + const environment = output.environmentWith({ + connectAdmin: async () => + fakeClient({ getCatalog: () => Promise.resolve({ platforms: [entry] }) }), + }); + await expect(runCli(arguments_, environment)).resolves.toBe(0); + return output.stdout; + }; + const lines = (platform: string, served?: string) => [ + `Platform: ${platform}`, + " Runtimes: (none) (default: (none))", + ...(served === undefined ? [] : [` Modes served: ${served}`]), + " Models: (none)", + "", + ]; + + expect(await run(["catalog"], entryOf("ios", ["slim"]))).toBe(lines("ios", "slim").join("\n")); + expect(await run(["catalog"], entryOf("ios", ["full"]))).toBe(lines("ios", "full").join("\n")); + expect(await run(["catalog"], entryOf("ios"))).toBe(lines("ios", "slim, full").join("\n")); + expect(await run(["catalog"], entryOf("android"))).toBe(lines("android").join("\n")); + expect(JSON.parse(await run(["catalog", "--json"], entryOf("ios", ["slim"])))).toEqual({ + platforms: [entryOf("ios", ["slim"])], + }); + expect(JSON.parse(await run(["catalog", "--json"], entryOf("ios")))).toEqual({ + platforms: [entryOf("ios")], + }); + }); + it("prints each model with the runtimes it pairs with", async () => { const output = outputCapture(); const environment = output.environmentWith({ @@ -126,6 +166,7 @@ describe("CLI: catalog", () => { [ "Platform: ios", " Runtimes: 18.4, 26.0 (default: 26.0)", + " Modes served: slim, full", " Models:", " (no class):", " iPhone 16: 18.4, 26.0", @@ -180,6 +221,7 @@ describe("CLI: catalog", () => { [ "Platform: ios", " Runtimes: 26.0 (default: 26.0)", + " Modes served: slim, full", " Models:", " phone (default: iPhone 17):", " iPhone 17: 26.0", diff --git a/src/contract/report-schemas.ts b/src/contract/report-schemas.ts index 017a79788..763e27188 100644 --- a/src/contract/report-schemas.ts +++ b/src/contract/report-schemas.ts @@ -98,7 +98,7 @@ const doctorFindingSchema = z.discriminatedUnion("kind", [ kind: z.literal("warm-pool-target-unreachable"), platform: platformSchema.optional(), target: z.string(), - reason: z.enum(["runtime-missing", "unknown-model", "over-limit"]), + reason: z.enum(["runtime-missing", "unknown-model", "mode-unavailable", "over-limit"]), message: z.string(), remedy: z.string(), }), diff --git a/src/contract/status-schemas.ts b/src/contract/status-schemas.ts index 2741e2668..a0d940a44 100644 --- a/src/contract/status-schemas.ts +++ b/src/contract/status-schemas.ts @@ -75,6 +75,7 @@ const warmPoolShortSchema = z.enum([ "no-driver", "runtime-missing", "unknown-model", + "mode-unavailable", "unresolvable", "boot-failed", "device-limit", @@ -305,6 +306,8 @@ export const platformCatalogSchema = z.object({ .max(CATALOG_SLIM_CATEGORIES_MAX) .optional(), defaultMode: deviceModeSchema.optional(), + /** why: ADR 0082 §4: the iOS modes a worker serves, sent only when it serves one; absent means both, which is also what a worker from before this field means. */ + modes: z.array(deviceModeSchema).min(1).max(2).optional(), defaultImageTag: imageTagSchema.optional(), /** why: ADR 0084 §3: `false` says this worker serves only enrolled physical devices of the platform; absent means it makes virtual devices. */ virtualDevices: z.literal(false).optional(), diff --git a/src/core/create-core.ts b/src/core/create-core.ts index 9bc174ebc..c42a027e1 100644 --- a/src/core/create-core.ts +++ b/src/core/create-core.ts @@ -340,6 +340,7 @@ export function createCore(options: CoreOptions): Core { decisions, eventBus: options.eventBus, hasDriver: (platform) => drivers.select(platform).length > 0, + servedModes: options.config.ios.modes, idle: options.config.idle, lifecycle: deviceLifecycle, ...(options.logger === undefined ? {} : { logger: options.logger }), diff --git a/src/core/doctor-findings.ts b/src/core/doctor-findings.ts index 0ab5ca67e..6dc63a4bc 100644 --- a/src/core/doctor-findings.ts +++ b/src/core/doctor-findings.ts @@ -1,6 +1,7 @@ import { boundDriverSummary, DRIVER_DETAIL_MAX, parseOsConstraint } from "../contract/index.js"; import type { Config } from "./config.js"; import { + type DeviceMode, type DeviceRecord, type DeviceSpec, type Platform, @@ -158,6 +159,7 @@ export function unreachableTarget( target: WarmTargetFigures, catalog: DriverCatalogEntry | undefined, virtualDevices: boolean, + servedModes: readonly DeviceMode[], ): DoctorFinding[] { const { model, osVersion, platform, short } = target; const named = [model, osVersion, target.mode].filter((part) => part !== undefined).join(" / "); @@ -219,6 +221,19 @@ export function unreachableTarget( }, ]; } + if (short === "mode-unavailable") { + const mode = target.mode; + return [ + { + kind: "warm-pool-target-unreachable", + message: `${named} cannot be met: this worker does not serve ${mode} iOS simulators (ios.modes is ${JSON.stringify(servedModes)})`, + platform, + reason: short, + remedy: `remove the target from warmPool.targets, or add ${mode} to ios.modes`, + target: named, + }, + ]; + } if (short === "unknown-model") { return [ { diff --git a/src/core/doctor-types.ts b/src/core/doctor-types.ts index b14225fc3..ccdc05b54 100644 --- a/src/core/doctor-types.ts +++ b/src/core/doctor-types.ts @@ -88,7 +88,7 @@ export type DoctorFinding = readonly kind: "warm-pool-target-unreachable"; readonly platform?: Platform; readonly target: string; - readonly reason: "runtime-missing" | "unknown-model" | "over-limit"; + readonly reason: "runtime-missing" | "unknown-model" | "mode-unavailable" | "over-limit"; readonly message: string; readonly remedy: string; } diff --git a/src/core/doctor.ts b/src/core/doctor.ts index 7ac3bedc9..6b5a03d2f 100644 --- a/src/core/doctor.ts +++ b/src/core/doctor.ts @@ -543,14 +543,15 @@ export class Doctor { const limits = warmPool.runningCapacity(); const figures = warmPool.figures().targets.filter((target) => target.origin === "configured"); const catalogs = await this.#catalogsOfMissingRuntimes(figures); + const { android, ios } = this.options.config; const findings = figures.flatMap((target) => unreachableTarget( target, catalogs.get(target.platform), this.options.config[target.platform].virtualDevices, + ios.modes, ), ); - const { android, ios } = this.options.config; const reserves = reservedRunning( { reserveRunning: reserveOnVirtualPlatforms( diff --git a/src/core/domain.ts b/src/core/domain.ts index db39ec693..f47bc2316 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -76,11 +76,16 @@ export interface PhysicalSpec { export type DeviceSpec = VirtualSpec | PhysicalSpec; /** - * Why a warm target did not resolve to a spec: the platform has no driver on this machine, its - * runtime is not installed (and a target never downloads), its model is not listed, or the driver - * refused it some other way. + * why: Why a warm target did not resolve to a spec: the platform has no driver on this machine, its + * runtime is not installed (and a target never downloads), its model is not listed, its mode is + * not one the worker serves (ADR 0082), or the driver refused it some other way. */ -export type TargetRefusal = "no-driver" | "runtime-missing" | "unknown-model" | "unresolvable"; +export type TargetRefusal = + | "no-driver" + | "runtime-missing" + | "unknown-model" + | "mode-unavailable" + | "unresolvable"; /** What the request resolver answers for a request that is not going to be granted a lease. */ export type TargetResolution = diff --git a/src/core/warm-pool/AGENTS.md b/src/core/warm-pool/AGENTS.md index 432f3556f..bdea31066 100644 --- a/src/core/warm-pool/AGENTS.md +++ b/src/core/warm-pool/AGENTS.md @@ -34,7 +34,7 @@ The plan (`evaluate`), in this order: pool off → over budget → the queue → - Only displacement shuts a device down for a target or learned kind, and never one a configured count keeps; what does not fit is reported short. Nothing is displaced when the capacity strategy would still refuse the kind after the shutdown. - At memory pressure `warming-paused` or higher (ADR 0068) the queue, the targets and the learned kinds propose no boot or creation, and a short target reports `memory-pressure` instead of any capacity reason (a target that does not resolve keeps its own). Each reading not yet used sheds one idle device: first one no configured count keeps, then a kept one, least recently used first, never one a waiter would take or one whose shutdown failed recently. `memory.pressure-changed` asks for a pass, so the pool fills again at once when the step lifts. - `reserveRunning` holds slots from idle devices only; it never holds back a request. -- An `unresolvable` target keeps its last spec, so its devices stay spared. +- An `unresolvable` target keeps its last spec, so its devices stay spared. A target whose iOS mode `ios.modes` leaves out is short `mode-unavailable` and keeps none, so its idle devices are no longer spared; a learned kind of an unserved mode is forgotten, and a baseline kind is judged by the baseline's current mode. Learned kinds: diff --git a/src/core/warm-pool/catalog-check.ts b/src/core/warm-pool/catalog-check.ts index 8d5a18771..b86dd4954 100644 --- a/src/core/warm-pool/catalog-check.ts +++ b/src/core/warm-pool/catalog-check.ts @@ -1,5 +1,5 @@ import type { Clock, Logger } from "../../ports/index.js"; -import type { Platform, VirtualSpec } from "../domain.js"; +import { type DeviceMode, type Platform, specMode, type VirtualSpec } from "../domain.js"; import type { DriverCatalog, PlatformCatalog } from "../driver-catalog.js"; import { stableError } from "../stable-error.js"; import type { LearnedKind } from "./learned.js"; @@ -9,12 +9,14 @@ const CATALOG_READ_LIMIT_MS = 30_000; interface CatalogCheckOptions { readonly baselines: { - current(name: string): { readonly staleReason?: string } | undefined; + current(name: string): { readonly mode: DeviceMode; readonly staleReason?: string } | undefined; }; readonly catalog: Pick; readonly clock: Clock; readonly hasDriver: (platform: Platform) => boolean; readonly logger: Logger; + /** why: the iOS modes the worker serves (ADR 0082 §2); a learned kind is planned from its stored spec and never resolved, so this is where its mode is checked. Absent means both. */ + readonly servedModes?: readonly DeviceMode[] | undefined; /** why: a read lists a platform that had no answer, so the kinds waiting on it can be planned now, not at the next tick. A failed or timed out read does not call it: its retry would loop. */ readonly onAnswer: () => void; } @@ -48,11 +50,24 @@ export class CatalogCheck { if (current === undefined || current.staleReason !== undefined) return true; } if (!this.options.hasDriver(platform)) return true; + if (this.modeNotServed(kind)) return true; const answer = this.#answers.get(platform); return answer !== undefined && !lists(answer, kind.spec); }); } + /** why: whether the kind's mode (a baseline kind's from its baseline's current spec) is an iOS mode the worker does not serve. */ + modeNotServed(kind: LearnedKind): boolean { + const { servedModes } = this.options; + const { baseline, platform } = kind.spec; + if (servedModes === undefined || platform !== "ios") return false; + const mode = + baseline === undefined + ? specMode(kind.spec) + : this.options.baselines.current(baseline.name)?.mode; + return mode !== undefined && !servedModes.includes(mode); + } + /** why: the kinds whose platform has a driver and no answer yet: a read pending, failed or timed out. */ unanswered(kinds: readonly LearnedKind[]): LearnedKind[] { return kinds.filter( diff --git a/src/core/warm-pool/converger.ts b/src/core/warm-pool/converger.ts index 5bed31b91..906b93664 100644 --- a/src/core/warm-pool/converger.ts +++ b/src/core/warm-pool/converger.ts @@ -44,6 +44,8 @@ import { type LearnedKind, type LearnedKindMatch, LearnedKinds } from "./learned import { RetrySchedule } from "./retry.js"; export interface WarmPoolOptions { + /** why: the iOS modes the worker serves (ADR 0082); absent means both. */ + readonly servedModes?: readonly DeviceMode[] | undefined; /** why: a learned baseline kind is warmed from the baseline's newest version, and goes when the baseline is removed or stale. */ readonly baselines: { current( @@ -180,6 +182,7 @@ export class WarmPool { clock: options.clock, hasDriver: options.hasDriver, logger: this.#logger, + servedModes: options.servedModes, onAnswer: () => this.#trigger(), }); } @@ -484,7 +487,10 @@ export class WarmPool { const kinds = this.#learnedKinds(); for (const kind of this.#catalogCheck.gone(kinds)) { this.#recording("forget a kind", () => this.#learned.forget(kind.spec)); - this.#logger.info("a warm pool learned kind was forgotten: its model or runtime is gone", { + const why = this.#catalogCheck.modeNotServed(kind) + ? "its mode is not served" + : "its model or runtime is gone"; + this.#logger.info(`a warm pool learned kind was forgotten: ${why}`, { model: kind.spec.model, osVersion: kind.spec.osVersion, platform: kind.spec.platform, diff --git a/src/daemon/dispatcher-status.ts b/src/daemon/dispatcher-status.ts index 79ebf0b8c..75d90869b 100644 --- a/src/daemon/dispatcher-status.ts +++ b/src/daemon/dispatcher-status.ts @@ -18,10 +18,17 @@ export class StatusHandlers { .map((entry) => this.#withDefaults(entry)), }); - /** why: ADR 0066 §5 and ADR 0078 §3: a gateway routes by the worker's default mode (iOS) and default image tag (Android), which only config knows. */ + /** why: ADR 0066 §5 and ADR 0078 §3: a gateway routes by the worker's default mode and served modes (iOS) and default image tag (Android), which only config knows. */ #withDefaults(entry: Entry): Entry { const { ios, android } = this.options.config; - if (entry.platform === "ios") return { ...entry, defaultMode: ios.defaultMode }; + if (entry.platform === "ios") { + // why: sent only when one mode is served, because absent already means both for every older worker (ADR 0082 §4). + return { + ...entry, + defaultMode: ios.defaultMode, + ...(ios.modes.length === 1 ? { modes: ios.modes } : {}), + }; + } if (entry.platform === "android" && android.defaultImageTag !== undefined) { return { ...entry, defaultImageTag: android.defaultImageTag }; } diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 85012cc67..6707be218 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -214,11 +214,17 @@ describe("Dispatcher: the fleet operations on a worker", () => { expect(workers[0]).not.toHaveProperty("protocol"); }); - it("catalog.get reports the iOS slim categories and the default mode", async () => { - for (const defaultMode of ["slim", "full"] as const) { + it("catalog.get reports the iOS slim categories and the default mode, and the modes only when the worker serves one", async () => { + for (const { defaultMode, modes } of [ + { defaultMode: "slim", modes: ["slim"] }, + { defaultMode: "full", modes: ["full"] }, + { defaultMode: "full", modes: undefined }, + { defaultMode: "slim", modes: ["slim", "full"] }, + ] as const) { const { dispatcher } = await buildDispatcher({ driverOptions: { knownModels: ["iPhone 17"], slimCategories: ["store"] }, iosDefaultMode: defaultMode, + ...(modes === undefined ? {} : { iosModes: modes }), }); const { platforms } = await dispatcher.dispatch("catalog.get", {}, admin); @@ -229,6 +235,8 @@ describe("Dispatcher: the fleet operations on a worker", () => { platform: "ios", slimCategories: ["store"], }); + if (modes?.length === 1) expect(platforms[0]?.modes, String(modes)).toEqual(modes); + else expect(platforms[0], String(modes)).not.toHaveProperty("modes"); } }); @@ -238,6 +246,7 @@ describe("Dispatcher: the fleet operations on a worker", () => { const set = await buildDispatcher({ androidDefaultImageTag: "google_apis_playstore", extraDrivers: [android()], + iosModes: ["slim"], }); const unset = await buildDispatcher({ extraDrivers: [android()] }); @@ -249,6 +258,8 @@ describe("Dispatcher: the fleet operations on a worker", () => { "google_apis_playstore", ); expect(withTag.find((entry) => entry.platform === "ios")).not.toHaveProperty("defaultImageTag"); + expect(withTag.find((entry) => entry.platform === "ios")?.modes).toEqual(["slim"]); + expect(withTag.find((entry) => entry.platform === "android")).not.toHaveProperty("modes"); expect(without.find((entry) => entry.platform === "android")).not.toHaveProperty( "defaultImageTag", ); diff --git a/src/leasing/AGENTS.md b/src/leasing/AGENTS.md index 89589297e..cb079b7e9 100644 --- a/src/leasing/AGENTS.md +++ b/src/leasing/AGENTS.md @@ -15,6 +15,10 @@ The lock: - Events go out after the commit that made them true. - A physical device's presence is read outside the lock and checked again inside it before the grant. +Served modes: + +- `servedModes` (from `ios.modes`) is checked in the spec resolver, before any catalog read or download: the asked or default mode, a baseline's mode, and again after the cannot-slim fallback. A miss is `ModeUnavailableError`, and `lease.rejected` keeps reason `unresolvable-spec`. + The queue: - `LeaseRequestBook.admit` stores the request before it queues it. diff --git a/src/leasing/acquisition-spec-resolver.ts b/src/leasing/acquisition-spec-resolver.ts index 2d9e8672a..bc45baadd 100644 --- a/src/leasing/acquisition-spec-resolver.ts +++ b/src/leasing/acquisition-spec-resolver.ts @@ -433,6 +433,7 @@ function checkedSpec(resolved: VirtualSpec, request: DeviceRequest, mode: Device function refusalOf(error: unknown): Exclude["refusal"] { if (error instanceof RuntimeMissingError) return "runtime-missing"; if (error instanceof UnknownModelError) return "unknown-model"; + if (error instanceof ModeUnavailableError) return "mode-unavailable"; return "unresolvable"; } diff --git a/src/leasing/create-leasing-warm-pool-served-modes.test.ts b/src/leasing/create-leasing-warm-pool-served-modes.test.ts index 86f5552a6..ddc261837 100644 --- a/src/leasing/create-leasing-warm-pool-served-modes.test.ts +++ b/src/leasing/create-leasing-warm-pool-served-modes.test.ts @@ -144,4 +144,37 @@ describe("the warm pool on a worker that does not serve every iOS mode", () => { await idleFullDeviceIsTargeted(["slim"]), ]).toEqual([true, false]); }); + + it("doctor reports a warm target the worker cannot meet because it does not serve its mode, naming the mode, the list and the way out, and nothing when the mode is served", async () => { + const findings = async (modes: Modes | undefined, mode: "slim" | "full") => { + const harness = await createHarness({ + driver: iosDriver(), + ...(modes === undefined ? {} : { iosModes: modes }), + limits: LIMITS, + startPool: true, + warmPool: { + targets: [{ count: 1, mode, model: "iPhone 16", osVersion: "26.1", platform: "ios" }], + }, + }); + await harness.engine.core.passWarmPool(); + await harness.engine.settle(); + const report = await harness.engine.core.doctor.reconcile(); + return report.findings.filter((finding) => finding.kind === "warm-pool-target-unreachable"); + }; + const unreachable = (mode: string, list: string) => [ + { + kind: "warm-pool-target-unreachable", + message: `iPhone 16 / 26.1 / ${mode} cannot be met: this worker does not serve ${mode} iOS simulators (ios.modes is ${list})`, + platform: "ios", + reason: "mode-unavailable", + remedy: `remove the target from warmPool.targets, or add ${mode} to ios.modes`, + target: `iPhone 16 / 26.1 / ${mode}`, + }, + ]; + + expect(await findings(["slim"], "full")).toEqual(unreachable("full", '["slim"]')); + expect(await findings(["full"], "slim")).toEqual(unreachable("slim", '["full"]')); + expect(await findings(undefined, "full")).toEqual([]); + expect(await findings(undefined, "slim")).toEqual([]); + }); }); 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 5515301c8..3e037a1ee 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 @@ -115,11 +115,25 @@ A **slim** simulator has background services that agents rarely need turned off, What to expect: - A full lease never gets a slim device. +- A worker may serve only one mode. See [Modes a worker serves](#modes-a-worker-serves). - Slim is best effort. iOS versions older than 18.5, and all Android devices, can't be slimmed, so you get a full device instead. Check `device.mode` in the grant. - A lease only reuses an idle device of the mode it asked for. So your request may wait for a new device even while devices of the other mode sit idle. 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. +### Modes a worker serves + +An admin can limit a worker to one mode with `ios.modes`. The worker then refuses a lease of the other mode at once with `MODE_UNAVAILABLE` (exit 12), before it downloads or boots anything. The error details carry the `mode` you asked for and the modes the worker `served`: + +```json +{"error":{"code":"MODE_UNAVAILABLE","details":{"platform":"ios","mode":"full","served":["slim"]}}} +``` + +- A request with no `--mode` gets the worker's only mode. +- A `--baseline` is checked by the mode it was saved with. +- On iOS older than 18.5 a slim request would get a full device, so a worker that serves only slim refuses it instead. +- `simlock catalog` prints `Modes served` for iOS. + ### 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: diff --git a/website/src/content/docs/docs/worker/capacity.mdx b/website/src/content/docs/docs/worker/capacity.mdx index 3bd96c955..67994e74e 100644 --- a/website/src/content/docs/docs/worker/capacity.mdx +++ b/website/src/content/docs/docs/worker/capacity.mdx @@ -120,11 +120,11 @@ simlock daemon start A slim iOS simulator has background services turned off that most agent work does not need, such as widgets, Siri, Spotlight, iCloud, the App Store, mail, Photos and telemetry. It uses much less RAM. -An agent asks for one with `simlock lease --mode slim`. A lease that names no mode gets `ios.defaultMode`, which is `full`. To turn off only some groups of services, list them in `ios.slim.categories` (`widgets`, `siri`, `search`, `icloud`, `store`, `pim`, `web`, `family`, `health`, `photos`, `apps`, `messaging`, `connectivity`, `telemetry`, `mdm`, `other`). +An agent asks for one with `simlock lease --mode slim`. A lease that names no mode gets `ios.defaultMode`, which is `full` (or the only mode `ios.modes` lists). To limit the worker to one mode, set `ios.modes` to `["slim"]` or `["full"]`; a lease, warm target or learned kind of the other mode is then refused. To turn off only some groups of services, list them in `ios.slim.categories` (`widgets`, `siri`, `search`, `icloud`, `store`, `pim`, `web`, `family`, `health`, `photos`, `apps`, `messaging`, `connectivity`, `telemetry`, `mdm`, `other`). What to expect: -- **A `full` request always gets a full device. A `slim` request may not.** On iOS older than 18.5, and on Android, a slim request gets a full device instead of failing. If Simlock finds after the boot that the services are not off as asked, the lease also gets a full device, and the daemon log says why. The lease always reports the mode the device really has. +- **A `full` request always gets a full device. A `slim` request may not.** On iOS older than 18.5, and on Android, a slim request gets a full device instead of failing, unless `ios.modes` leaves out `full`: then an iOS request that would get a full device is refused with `MODE_UNAVAILABLE`. If Simlock finds after the boot that the services are not off as asked, the lease also gets a full device, and the daemon log says why. The lease always reports the mode the device really has. - **The first boot of a slim simulator can be slow**, up to `ios.slim.bootTimeoutMs` (10 minutes by default). - **Slim and full devices are never mixed up.** A request only reuses an idle device of the mode it asked for. diff --git a/website/src/content/docs/docs/worker/configuration.mdx b/website/src/content/docs/docs/worker/configuration.mdx index 07f21bdd4..0fab2ed46 100644 --- a/website/src/content/docs/docs/worker/configuration.mdx +++ b/website/src/content/docs/docs/worker/configuration.mdx @@ -98,6 +98,7 @@ The output includes secrets from the file, such as `gateway.token`. Do not paste | Run more or fewer devices | `capacity.strategy`, `capacity.config` | `resource`, sized from this machine | | Keep some devices booted and ready | `warmPool.targets` | none | | Make iOS devices slim by default | `ios.defaultMode` | `full` | +| Serve only slim or only full iOS simulators | `ios.modes` | `["slim","full"]` | | Choose which model a class such as `phone` gets | `ios.defaultModels`, `android.defaultModels` | none | | Run Android emulators without a window | `android.emulator.headless` | `false` | | Watch iOS simulators in a window | `ios.simulator.headless`, with `drivers.ios.deviceSet` | `true` (no window) | diff --git a/website/src/content/docs/docs/worker/troubleshooting.mdx b/website/src/content/docs/docs/worker/troubleshooting.mdx index 998db66a6..8e6aae45d 100644 --- a/website/src/content/docs/docs/worker/troubleshooting.mdx +++ b/website/src/content/docs/docs/worker/troubleshooting.mdx @@ -58,7 +58,7 @@ Service broken: com.callstack.simlock.worker (launchd) names missing /Users/dana | `foreign-provenance-change` | A device no longer carries the marks that show Simlock made it, for example after it was erased by hand. | Nothing. Check the device; delete it if it is not yours. | | `orphan-device` | A device sits in Simlock's device folder with no record. | Nothing. See [Orphaned devices](#orphaned-devices). | | `orphan-process` | A simulator or emulator is running that Simlock has no record of. | Nothing. | -| `warm-pool-target-unreachable` | A warm pool target can never be filled: its runtime is not installed, its model is unknown, its platform's `.virtualDevices` is `false`, or it asks for more than capacity allows. | Nothing. Install the runtime, change the target, or remove it or set the key to `true`. | +| `warm-pool-target-unreachable` | A warm pool target can never be filled: its runtime is not installed, its model is unknown, its platform's `.virtualDevices` is `false`, it asks for a mode `ios.modes` does not list (reason `mode-unavailable`), or it asks for more than capacity allows. | Nothing. Install the runtime, change the target, or remove it, set the key to `true`, or add the mode to `ios.modes`. | | `driver-unavailable` | A platform's driver was refused at start, so the platform is off. The finding carries the `reason` (such as `invalid-device-set` or `device-set-changed`) and a `detail` that says what to run; `simlock doctor` also prints it as `Unavailable [] : ` on stderr. | Nothing. Fix it, then restart the daemon. | | `driver-advisory` | A platform tool reported something worth knowing that is not a fault. The code is in the message; see [`default-image-tag-not-installed`](#default-image-tag-not-installed). | Nothing. | | `module-unavailable` | An optional feature that is turned on cannot run on this machine. The remedy says why. | Nothing. | From 87ab99e038d47df2f9539df94a27844ae9e464b0 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:28:05 +0100 Subject: [PATCH 12/16] refactor(cli): the catalog's modes line is its own function (#1651) --- src/cli/commands/catalog.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/cli/commands/catalog.ts b/src/cli/commands/catalog.ts index dd4307202..c6b6654c0 100644 --- a/src/cli/commands/catalog.ts +++ b/src/cli/commands/catalog.ts @@ -41,6 +41,12 @@ function phonesOnlyLine(entry: CatalogGetOutput["platforms"][number]): string[] ]; } +// why: the daemon sends `modes` only when one mode is served, so a missing field means both. +function modesLine(entry: CatalogGetOutput["platforms"][number]): string[] { + if (entry.platform !== "ios") return []; + return [` Modes served: ${(entry.modes ?? ["slim", "full"]).join(", ")}`]; +} + function formatCatalog(response: CatalogGetOutput): string { if (response.platforms.length === 0) return "No platforms available."; return response.platforms @@ -78,9 +84,7 @@ function formatCatalog(response: CatalogGetOutput): string { `Platform: ${entry.platform}`, ...phonesOnlyLine(entry), ` Runtimes: ${entry.runtimes.length > 0 ? esc(entry.runtimes.join(", ")) : "(none)"} (default: ${esc(defaultRuntime)})`, - ...(entry.platform === "ios" - ? [` Modes served: ${(entry.modes ?? ["slim", "full"]).join(", ")}`] - : []), + ...modesLine(entry), ...(entry.defaultImageTag === undefined ? [] : [` Default image tag: ${esc(entry.defaultImageTag)}`]), From ddc5ad11203ae29348aaf876c9222a7292160352 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:36:44 +0100 Subject: [PATCH 13/16] test: ios.modes bounds on the wire, and the docs a mode-unavailable short touches (#1651) Protocol-bump: none (a test and docs only) --- docs/internal/EVENTS.md | 2 +- .../operations-round-trips-catalog-config.test.ts | 14 ++++++++++++-- src/core/warm-pool/AGENTS.md | 2 +- website/src/content/docs/docs/reference/events.mdx | 2 +- website/src/content/docs/docs/worker/capacity.mdx | 1 + 5 files changed, 16 insertions(+), 5 deletions(-) diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 3b8001fa0..6ce19efe4 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -70,7 +70,7 @@ worker is ever contacted. `lease-id-taken` (ADR 0020; widens a published vocabul |---|---|---|---|---| | `capacity.changed` | per platform (`ios`, `android`) and `global`: running, max running, reserved, warm; `ramBudget` (used bytes, limit bytes) only under the `resource` capacity strategy | a worker's capacity figures differ from the last ones emitted: after a registry commit, or after a provisioning or boot reservation is taken or released. Emitted once when the daemon has started, so every run begins with a step; two consecutive events never carry equal figures. The figures are the ones `simlock status` reports | CapacityObserver (worker) | implemented | | `queue.changed` | depth, `physical: true` when the physical line changed (ADR 0022 §3, additive, events rule 6) | the number of requests waiting in a queue changed: a request joined it or left it. A queue has two lines; `depth` is the changed line's, and the event without `physical` is the virtual line's. Emitted once when the daemon has started. A worker emits it for its own queue and a gateway for its fleet queue; a worker's events a gateway relays carry `workerId`, and the gateway's own do not | WaitQueue (worker) / FleetLeaseCoordinator (gateway) | implemented | -| `warm-pool.target-missed` | `{ platform, model, osVersion?, mode, origin, count, ready, reason }` — `origin` is always `configured`: the event is for the `warmPool.targets` entries, never for a kind the pool learned, and `count` is the configured count (ADR 0038 §8); `osVersion` is the resolved one, or the configured one for a target that did not resolve, and absent when it names none and did not resolve; `reason` is the one reason the pool records for the target (`warm-pool/policy.ts` for one that resolved, `warm-pool/converger.ts` for one the resolver refused), the one `short` carries in `status.get` (the one reason `simlock status` shows as the target's `short`, but never `disabled`, since a pool that is off reports no target: `no-driver`, `runtime-missing`, `unknown-model`, `unresolvable`, `boot-failed`, `device-limit`, `running-limit`, `reserve`, `ram-budget` or `memory-pressure`) | a warm pool target went short: after a pass the pool could do nothing for a target that has fewer ready devices than its count, and it was not already missed (ADR 0017 §7). Emitted once the pass's actions have run (events rule 3), once per report on that edge (targets that resolve to one spec are one report and emit one event between them, with their counts added; each target the resolver refuses emits its own), not on each short pass after, nor when a retry or a boot fills it and it is short again; the edge is kept per configured target, and only ready devices reaching its count end the miss, so a target met in between and missed again emits again. A target that is filling, held by `warmPool.maxConcurrentBoots` or waiting behind a queued request the pool could not serve is not short | WarmPool (worker) | implemented | +| `warm-pool.target-missed` | `{ platform, model, osVersion?, mode, origin, count, ready, reason }` — `origin` is always `configured`: the event is for the `warmPool.targets` entries, never for a kind the pool learned, and `count` is the configured count (ADR 0038 §8); `osVersion` is the resolved one, or the configured one for a target that did not resolve, and absent when it names none and did not resolve; `reason` is the one reason the pool records for the target (`warm-pool/policy.ts` for one that resolved, `warm-pool/converger.ts` for one the resolver refused), the one `short` carries in `status.get` (the one reason `simlock status` shows as the target's `short`, but never `disabled`, since a pool that is off reports no target: `no-driver`, `runtime-missing`, `unknown-model`, `mode-unavailable`, `unresolvable`, `boot-failed`, `device-limit`, `running-limit`, `reserve`, `ram-budget` or `memory-pressure`) | a warm pool target went short: after a pass the pool could do nothing for a target that has fewer ready devices than its count, and it was not already missed (ADR 0017 §7). Emitted once the pass's actions have run (events rule 3), once per report on that edge (targets that resolve to one spec are one report and emit one event between them, with their counts added; each target the resolver refuses emits its own), not on each short pass after, nor when a retry or a boot fills it and it is short again; the edge is kept per configured target, and only ready devices reaching its count end the miss, so a target met in between and missed again emits again. A target that is filling, held by `warmPool.maxConcurrentBoots` or waiting behind a queued request the pool could not serve is not short | WarmPool (worker) | implemented | ## Device lifecycle diff --git a/src/contract/operations-round-trips-catalog-config.test.ts b/src/contract/operations-round-trips-catalog-config.test.ts index fa14a8593..ee452b103 100644 --- a/src/contract/operations-round-trips-catalog-config.test.ts +++ b/src/contract/operations-round-trips-catalog-config.test.ts @@ -189,7 +189,7 @@ describe("operation input/output round trips", () => { ]); }); - it("catalog.get bounds every string and list in modelAliases, customModels, images and slimCategories", () => { + it("catalog.get bounds every string and list in modelAliases, customModels, images, slimCategories and modes", () => { const base = { platform: "android", models: ["Pixel 8"], @@ -227,6 +227,9 @@ describe("operation input/output round trips", () => { [{ slimCategories: ["a" + "x".repeat(31)] }, { slimCategories: ["a" + "x".repeat(32)] }], [{ slimCategories: ["a-1"] }, { slimCategories: ["Store"] }], [{ defaultMode: "slim" }, { defaultMode: "lean" }], + [{ modes: ["slim", "full"] }, { modes: [] }], + [{ modes: ["slim", "full"] }, { modes: ["slim", "full", "slim"] }], + [{ modes: ["slim"] }, { modes: ["lean"] }], [ { images: [{ ...image, runtime: "x".repeat(128) }] }, { images: [{ ...image, runtime: "x".repeat(129) }] }, @@ -486,7 +489,14 @@ describe("operation input/output round trips", () => { expect([ output.safeParse({ ...config, ios: { ...config.ios, defaultMode: "fast" } }).success, output.safeParse({ ...config, android: { emulator: config.android.emulator } }).success, - ]).toEqual([false, false]); + output.safeParse({ ...config, ios: { ...config.ios, modes: [] } }).success, + output.safeParse({ ...config, ios: { ...config.ios, modes: ["slim", "full", "slim"] } }) + .success, + output.safeParse({ ...config, ios: { ...config.ios, modes: ["lean"] } }).success, + ]).toEqual([false, false, false, false, false]); + expect( + output.parse({ ...config, ios: { ...config.ios, modes: ["slim", "full"] } }).ios.modes, + ).toEqual(["slim", "full"]); for (const maxPerRequester of [2, { ios: 2 }, { ios: 1, android: 1 }]) { const parsed = OPERATIONS["config.get"].output.parse({ ...config, diff --git a/src/core/warm-pool/AGENTS.md b/src/core/warm-pool/AGENTS.md index bdea31066..5a109df47 100644 --- a/src/core/warm-pool/AGENTS.md +++ b/src/core/warm-pool/AGENTS.md @@ -41,7 +41,7 @@ Learned kinds: - A kind is learned on `lease.granted`, never for a physical device and never with the pool off. A plain kind is learned on its first lease. - A baseline kind is one row per baseline name, learned once its grants in the window reach `warmPool.baselineLearnAfter`. The mark is stored and never worked out again. Until then the row counts but is not planned, not in `figures()` or `targeted()`, and not matched by `forgetKinds`. Each pass warms it as the baseline's newest version. - `start()` closes the lease rows whose lease the registry no longer holds. -- The catalog check forgets a kind whose model, OS, image tag or driver is gone, or whose baseline is removed or stale. `LEARNED_FAILURES_LIMIT` (`converger.ts`) failed boots in a row forget it too. +- The catalog check forgets a kind whose model, OS, image tag, iOS mode (`ios.modes`) or driver is gone, or whose baseline is removed or stale. `LEARNED_FAILURES_LIMIT` (`converger.ts`) failed boots in a row forget it too. - A kind whose platform has no catalog answer yet (read pending, failed or timed out) is kept and planned for nothing that pass. - `forgetKinds` (ADR 0050) drops a kind's failed-boot count unless a configured target shares its spec. The devices the kind kept are left to the reaper's idle rules. - The learned kinds are the pool's own `state.db` tables (`warmPoolOwner`), kept across restarts and cleared by nuke. Targets are config. diff --git a/website/src/content/docs/docs/reference/events.mdx b/website/src/content/docs/docs/reference/events.mdx index 06aa06832..a21b0b095 100644 --- a/website/src/content/docs/docs/reference/events.mdx +++ b/website/src/content/docs/docs/reference/events.mdx @@ -125,7 +125,7 @@ release and records nothing. | --- | --- | --- | --- | | `capacity.changed` | The worker's running figures changed, and once at start. | `ios`, `android`, `global`, each with `running`, `maxRunning`, `reserved`, `warm`; `ramBudget` (`usedBytes`, `limitBytes`) under the `resource` strategy | Relayed | | `queue.changed` | A request joined or left the queue, and once at start. | `depth` (requests waiting in that line), `physical: true` when the physical line changed | Own and relayed | -| `warm-pool.target-missed` | A `warmPool.targets` entry went short and the pool could do nothing about it. Once per time it goes short. | `platform`, `model`, `osVersion`, `mode`, `origin` (always `configured`), `count`, `ready`, `reason` (`no-driver`, `runtime-missing`, `unknown-model`, `unresolvable`, `boot-failed`, `device-limit`, `running-limit`, `reserve`, `ram-budget`, `memory-pressure`) | Relayed | +| `warm-pool.target-missed` | A `warmPool.targets` entry went short and the pool could do nothing about it. Once per time it goes short. | `platform`, `model`, `osVersion`, `mode`, `origin` (always `configured`), `count`, `ready`, `reason` (`no-driver`, `runtime-missing`, `unknown-model`, `mode-unavailable`, `unresolvable`, `boot-failed`, `device-limit`, `running-limit`, `reserve`, `ram-budget`, `memory-pressure`) | Relayed | ## Devices diff --git a/website/src/content/docs/docs/worker/capacity.mdx b/website/src/content/docs/docs/worker/capacity.mdx index 67994e74e..02233033a 100644 --- a/website/src/content/docs/docs/worker/capacity.mdx +++ b/website/src/content/docs/docs/worker/capacity.mdx @@ -220,6 +220,7 @@ warm pool: enabled, reserve ios 1 android 0 | `disabled` | The warm pool is off (`warmPool.enabled` is `false`). | | `runtime-missing` | Install the runtime or system image. See [Runtimes and images](/simlock/docs/worker/runtimes-and-images). | | `unknown-model` | The model does not exist on this machine, or the platform's `.virtualDevices` is `false`. Check `simlock catalog`. | +| `mode-unavailable` | The target is an iOS mode that `ios.modes` leaves out. Remove the target or add the mode to `ios.modes`. | | `unresolvable` | No device can be created for it. Check its OS version and mode. | | `no-driver` | The platform's tools are missing. Run `simlock doctor`. | | `boot-failed` | The last boot failed, or did not finish within `ios.full.bootTimeoutMs`, `ios.slim.bootTimeoutMs` or `android.bootTimeoutMs`. Simlock tries again later. Check `simlock daemon logs`. | From fd20509f3e42e9d1ad332a2083130bd4d0f0aaaa Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:38:52 +0100 Subject: [PATCH 14/16] test: ios.modes reaches a started worker's leasing, and an Android learned kind survives a slim-only worker (#1651) --- src/daemon/main-start-daemon.test.ts | 23 ++++++++++++++++ ...ate-leasing-warm-pool-served-modes.test.ts | 26 ++++++++++++++----- 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/src/daemon/main-start-daemon.test.ts b/src/daemon/main-start-daemon.test.ts index bb804bf81..e4afb5e99 100644 --- a/src/daemon/main-start-daemon.test.ts +++ b/src/daemon/main-start-daemon.test.ts @@ -478,6 +478,29 @@ describe("startDaemon", () => { .toEqual([{ failure_code: "RUNTIME_MISSING", requester_id: "second" }]); }); + it("a started worker refuses an iOS lease in a mode its ios.modes leaves out", async () => { + const clock = new FakeClock(1_000); + const { daemon } = await start({ + clock, + configOverrides: { ios: { modes: ["slim"] } }, + drivers: [new FakeDriver({ availableOsVersions: ["26.5"], clock, platform: "ios" })], + }); + const session = { + manageEventSubscription: () => undefined, + via: "socket", + principal: "agent", + role: "agent", + } as const; + + await expect( + daemon.dispatch( + "lease.request", + { mode: "full", model: "iPhone 16", osVersion: "26.5", platform: "ios" }, + session, + ), + ).rejects.toMatchObject({ code: "MODE_UNAVAILABLE" }); + }); + it("establishes the instance identity once, and reuses it on the next start", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock-main-identity-")); temporaryDirectories.push(directory); diff --git a/src/leasing/create-leasing-warm-pool-served-modes.test.ts b/src/leasing/create-leasing-warm-pool-served-modes.test.ts index ddc261837..cf2775ab4 100644 --- a/src/leasing/create-leasing-warm-pool-served-modes.test.ts +++ b/src/leasing/create-leasing-warm-pool-served-modes.test.ts @@ -24,6 +24,15 @@ function iosDriver(): FakeDriver { }); } +function androidDriver(): FakeDriver { + return new FakeDriver({ + availableOsVersions: ["36"], + clock: new FakeClock(1_000), + knownModels: ["Pixel 9"], + platform: "android", + }); +} + // why: the engine reads a baseline from `baselines` and copies the source the driver holds, so a row and a saved source stand in for an operator's save. async function saveFullBaseline(harness: Harness, name: string): Promise { const spec = { ...phone, osVersion: "26.1", physical: false } as const; @@ -43,9 +52,10 @@ const learnedKinds = (harness: Harness) => const learnCases: readonly { readonly kept: boolean; - readonly learn: "full" | "full baseline" | "slim"; + readonly learn: "android" | "full" | "full baseline" | "slim"; readonly modes: Modes; }[] = [ + { kept: true, learn: "android", modes: ["slim"] }, { kept: false, learn: "full", modes: ["slim"] }, { kept: false, learn: "full baseline", modes: ["slim"] }, { kept: false, learn: "slim", modes: ["full"] }, @@ -55,12 +65,14 @@ const learnCases: readonly { // why: a worker that learned a kind while it served both modes, then restarts serving fewer, on the same state. async function learnedAfterSwitch( - learn: "full" | "full baseline" | "slim", + learn: "android" | "full" | "full baseline" | "slim", modes: Modes, ): Promise { const state = await openTestState(); + const ios = iosDriver(); const options = { - driver: iosDriver(), + driver: ios, + drivers: [ios, androidDriver()], limits: LIMITS, startPool: true, state, @@ -69,9 +81,11 @@ async function learnedAfterSwitch( const before = await createHarness(options); if (learn === "full baseline") await saveFullBaseline(before, "checkout"); const asked = - learn === "full baseline" - ? { baseline: "checkout", platform: "ios" as const } - : { ...phone, mode: learn, osVersion: "26.1" }; + learn === "android" + ? { model: "Pixel 9", osVersion: "36", platform: "android" as const } + : learn === "full baseline" + ? { baseline: "checkout", platform: "ios" as const } + : { ...phone, mode: learn, osVersion: "26.1" }; const grant = await before.engine.request(asked, { ownerId: "learner", requesterId: "learner" }); await before.engine.release(grant.lease.id, "explicit"); await flush(); From 55fde2a561f6f30f9e081fde613c330846dc5d01 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:47:53 +0100 Subject: [PATCH 15/16] fix(core): doctor names the mode a warm target was refused for, not the mode it asked (#1651) --- src/core/doctor-findings.ts | 4 ++- ...ate-leasing-warm-pool-served-modes.test.ts | 36 ++++++++++++------- .../src/content/docs/docs/worker/capacity.mdx | 2 +- 3 files changed, 28 insertions(+), 14 deletions(-) diff --git a/src/core/doctor-findings.ts b/src/core/doctor-findings.ts index 6dc63a4bc..ca722df14 100644 --- a/src/core/doctor-findings.ts +++ b/src/core/doctor-findings.ts @@ -222,7 +222,9 @@ export function unreachableTarget( ]; } if (short === "mode-unavailable") { - const mode = target.mode; + // why: the resolver refuses the asked mode if unserved, else the full spec a slim ask falls back to (iOS below 18.5); name the one it refused. + const mode = + target.mode !== undefined && !servedModes.includes(target.mode) ? target.mode : "full"; return [ { kind: "warm-pool-target-unreachable", diff --git a/src/leasing/create-leasing-warm-pool-served-modes.test.ts b/src/leasing/create-leasing-warm-pool-served-modes.test.ts index cf2775ab4..f8eb7fb20 100644 --- a/src/leasing/create-leasing-warm-pool-served-modes.test.ts +++ b/src/leasing/create-leasing-warm-pool-served-modes.test.ts @@ -159,36 +159,48 @@ describe("the warm pool on a worker that does not serve every iOS mode", () => { ]).toEqual([true, false]); }); - it("doctor reports a warm target the worker cannot meet because it does not serve its mode, naming the mode, the list and the way out, and nothing when the mode is served", async () => { - const findings = async (modes: Modes | undefined, mode: "slim" | "full") => { + it("doctor reports a warm target the worker cannot meet because it does not serve its mode, naming the refused mode, the list and the way out, and nothing when the mode is served", async () => { + const findings = async ( + modes: Modes | undefined, + target: { readonly mode?: "slim" | "full"; readonly osVersion: string }, + ) => { const harness = await createHarness({ driver: iosDriver(), ...(modes === undefined ? {} : { iosModes: modes }), limits: LIMITS, startPool: true, - warmPool: { - targets: [{ count: 1, mode, model: "iPhone 16", osVersion: "26.1", platform: "ios" }], - }, + warmPool: { targets: [{ count: 1, model: "iPhone 16", platform: "ios", ...target }] }, }); await harness.engine.core.passWarmPool(); await harness.engine.settle(); const report = await harness.engine.core.doctor.reconcile(); return report.findings.filter((finding) => finding.kind === "warm-pool-target-unreachable"); }; - const unreachable = (mode: string, list: string) => [ + const unreachable = (named: string, mode: string, list: string) => [ { kind: "warm-pool-target-unreachable", - message: `iPhone 16 / 26.1 / ${mode} cannot be met: this worker does not serve ${mode} iOS simulators (ios.modes is ${list})`, + message: `${named} cannot be met: this worker does not serve ${mode} iOS simulators (ios.modes is ${list})`, platform: "ios", reason: "mode-unavailable", remedy: `remove the target from warmPool.targets, or add ${mode} to ios.modes`, - target: `iPhone 16 / 26.1 / ${mode}`, + target: named, }, ]; - expect(await findings(["slim"], "full")).toEqual(unreachable("full", '["slim"]')); - expect(await findings(["full"], "slim")).toEqual(unreachable("slim", '["full"]')); - expect(await findings(undefined, "full")).toEqual([]); - expect(await findings(undefined, "slim")).toEqual([]); + expect(await findings(["slim"], { mode: "full", osVersion: "26.1" })).toEqual( + unreachable("iPhone 16 / 26.1 / full", "full", '["slim"]'), + ); + expect(await findings(["full"], { mode: "slim", osVersion: "26.1" })).toEqual( + unreachable("iPhone 16 / 26.1 / slim", "slim", '["full"]'), + ); + // why: iOS below 18.5 cannot be slimmed, so a slim ask (asked or default) is refused as the full it falls back to. + expect(await findings(["slim"], { osVersion: "17.5" })).toEqual( + unreachable("iPhone 16 / 17.5 / slim", "full", '["slim"]'), + ); + expect(await findings(["slim"], { mode: "slim", osVersion: "17.5" })).toEqual( + unreachable("iPhone 16 / 17.5 / slim", "full", '["slim"]'), + ); + expect(await findings(undefined, { mode: "full", osVersion: "26.1" })).toEqual([]); + expect(await findings(undefined, { mode: "slim", osVersion: "26.1" })).toEqual([]); }); }); diff --git a/website/src/content/docs/docs/worker/capacity.mdx b/website/src/content/docs/docs/worker/capacity.mdx index 02233033a..afedb0ca1 100644 --- a/website/src/content/docs/docs/worker/capacity.mdx +++ b/website/src/content/docs/docs/worker/capacity.mdx @@ -220,7 +220,7 @@ warm pool: enabled, reserve ios 1 android 0 | `disabled` | The warm pool is off (`warmPool.enabled` is `false`). | | `runtime-missing` | Install the runtime or system image. See [Runtimes and images](/simlock/docs/worker/runtimes-and-images). | | `unknown-model` | The model does not exist on this machine, or the platform's `.virtualDevices` is `false`. Check `simlock catalog`. | -| `mode-unavailable` | The target is an iOS mode that `ios.modes` leaves out. Remove the target or add the mode to `ios.modes`. | +| `mode-unavailable` | The target is an iOS mode that `ios.modes` leaves out, or a slim target on iOS below 18.5 (which can only be full) when `ios.modes` has no `full`. Remove the target or add the mode to `ios.modes`. | | `unresolvable` | No device can be created for it. Check its OS version and mode. | | `no-driver` | The platform's tools are missing. Run `simlock doctor`. | | `boot-failed` | The last boot failed, or did not finish within `ios.full.bootTimeoutMs`, `ios.slim.bootTimeoutMs` or `android.bootTimeoutMs`. Simlock tries again later. Check `simlock daemon logs`. | From 9c9aacafdd1194ffa573a4e45f256ed82fbf944f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Wed, 18 Nov 2026 09:47:56 +0100 Subject: [PATCH 16/16] test: an explicit slim lease on a slim-only worker is granted; drop the resolver check order from the leasing manual (#1651) --- src/daemon/dispatcher-leases-served-modes.test.ts | 1 + src/leasing/AGENTS.md | 4 ---- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/daemon/dispatcher-leases-served-modes.test.ts b/src/daemon/dispatcher-leases-served-modes.test.ts index b424d4521..1ee36514b 100644 --- a/src/daemon/dispatcher-leases-served-modes.test.ts +++ b/src/daemon/dispatcher-leases-served-modes.test.ts @@ -69,6 +69,7 @@ const baselineRefusal = (mode: string) => const cases: readonly Case[] = [ { name: "no mode", modes: ["slim"], request: phone, granted: "slim" }, + { name: "--mode slim", modes: ["slim"], request: { ...phone, mode: "slim" }, granted: "slim" }, { name: "--mode full", modes: ["slim"], diff --git a/src/leasing/AGENTS.md b/src/leasing/AGENTS.md index cb079b7e9..89589297e 100644 --- a/src/leasing/AGENTS.md +++ b/src/leasing/AGENTS.md @@ -15,10 +15,6 @@ The lock: - Events go out after the commit that made them true. - A physical device's presence is read outside the lock and checked again inside it before the grant. -Served modes: - -- `servedModes` (from `ios.modes`) is checked in the spec resolver, before any catalog read or download: the asked or default mode, a baseline's mode, and again after the cannot-slim fallback. A miss is `ModeUnavailableError`, and `lease.rejected` keeps reason `unresolvable-spec`. - The queue: - `LeaseRequestBook.admit` stores the request before it queues it.