diff --git a/docs/CLI.md b/docs/CLI.md index 3d5c427bf..298be865a 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -133,9 +133,9 @@ a timer and releasing it when it exits. ``` simlock lease --platform --device [--os ] - [--agent-id ] [--timeout ] [--no-wait] [--detach] - [--ttl ] [--allow-download] [--full] [--export-env] - [--bind-pid ] + [--mode ] [--agent-id ] [--timeout ] + [--no-wait] [--detach] [--ttl ] [--allow-download] + [--export-env] [--bind-pid ] ``` There is only one kind of lease: every lease has a @@ -181,13 +181,16 @@ granted. `component.install-failed` on the event bus (`simlock events --follow`); see [EVENTS.md](EVENTS.md#components). The requester's own progress stream (below) does not yet reflect an in-flight download. -- `--full` — opt this lease out of iOS slim mode (see - [CONFIGURATION.md](CONFIGURATION.md) for what slim mode disables). Only - meaningful when `ios.slim.enabled` is on; ignored otherwise, and ignored - for Android. A `--full` request never matches, and never shares a pool key - with, a slim device, so it can wait for a fresh device to provision or - force a re-provision of one already running, even while slim devices sit - idle in the warm pool. +- `--mode ` — the device mode this lease asks for. Without it, the + lease gets the default mode of the worker that serves it (`ios.defaultMode`, + `full` unless configured). `full` is a guarantee: a `full` lease never gets a + slim device. `slim` is best effort: on a runtime that cannot be slimmed (an + iOS runtime older than 18.5, or any Android device) the lease is granted a + full device. A lease only reuses an idle device of the mode it resolved to, + so it can wait for a fresh device even while devices of the other mode sit + idle. Any other value is a `BAD_REQUEST` (exit 2). See + [CONFIGURATION.md](CONFIGURATION.md#device-mode-slim-and-full) for what a + slim device leaves out. - `--detach` — print the lease result (the same JSON shape as the grant line below, including `device.mode`) and exit instead of staying alive. Nothing then renews the lease on your behalf: keep it with @@ -281,9 +284,9 @@ bookkeeping fields (`driverData`, `quarantine*`, `foreign*`, `recovering*`, the derived `transitionAgeMs`) never appear on a grant; a caller that wants those needs the admin-role `list.get`/`status.get`, not `lease.request`'s output. `device.mode` is the device mode the granted device actually has: -`"slim"` when its feature set was reduced (iOS slim mode applied and this -request did not pass `--full`), and `"full"` otherwise — always `"full"` for -Android. It lets an agent explain a feature-loss failure (missing push notification, +`"slim"` when its feature set was reduced, and `"full"` otherwise — always +`"full"` for Android. A `--mode slim` lease can report `"full"` (slim is best +effort); a `--mode full` lease never reports `"slim"`. It lets an agent explain a feature-loss failure (missing push notification, Spotlight result, StoreKit sheet, universal link, or system picker) instead of misreading it as a bug. See `src/contract/schemas.ts` (`deviceRecordSchema`, `leaseRecordSchema`, `leaseGrantSchema`) for the full @@ -1131,14 +1134,13 @@ enters `quarantined` (see [#21](https://github.com/callstackincubator/simlock/is rather than being re-driven, since it may be mid-erase. As with every other `--fix` correction, a leased device is never touched. -When `ios.slim.enabled` is on, `doctor` also reports a `driver-advisory` +When `ios.defaultMode` is `slim`, `doctor` also reports a `driver-advisory` finding (code `slim-runtime-unsupported`) for each installed iOS runtime older than 18.5 — the version floor `launchctl disable` overrides need to -survive a reboot (see [CONFIGURATION.md](CONFIGURATION.md)). Slim mode -silently does nothing on those runtimes otherwise; this finding is what -makes that visible. It is advisory only — there is no `--fix` for it, since -the fix is either upgrading the runtime or narrowing `ios.slim` to the -runtimes that support it. +survive a reboot (see [CONFIGURATION.md](CONFIGURATION.md#device-mode-slim-and-full)). +A lease on those runtimes that asks for slim, or names no mode, gets a full +device; this finding is what makes that visible. It is advisory only — there +is no `--fix` for it, since the fix is upgrading the runtime. On macOS, `doctor` also reports a `driver-advisory` finding (code `runtime-cache-unreclaimable`) for each iOS runtime that was downloaded to diff --git a/docs/CLIENT.md b/docs/CLIENT.md index b6b6c1b87..780868af2 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -31,16 +31,24 @@ const client = await connectSimlock({ principal: "agent-1", }); -const grant = await client.requestLease({ platform: "ios", model: "iPhone 17 Pro" }); +const grant = await client.requestLease({ platform: "ios", model: "iPhone 17 Pro", mode: "slim" }); // grant: { device, lease, timing } — the contract's LeaseGrant, verbatim await client.releaseLease({ leaseId: grant.lease.id }); await client.close(); ``` +`requestLease` takes an optional `mode`, `"slim"` or `"full"`: the device +mode the lease asks for. Without it the lease gets the default mode of the +worker that serves it (`ios.defaultMode`, `full` unless configured). Any +other value, or a field `requestLease` does not know, is a `BAD_REQUEST`. + `grant.device.mode` is the device mode the granted device actually has: -`"slim"` when its driver reduced its feature set (iOS slim mode), `"full"` -otherwise. A slim device lacks some system features — push notifications, +`"slim"` when its driver reduced its feature set, `"full"` otherwise. `full` +is a guarantee and `slim` is best effort: a `"slim"` request on a runtime +that cannot be slimmed (an iOS runtime older than 18.5, or any Android +device) is granted `"full"`, and a `"full"` request is never granted +`"slim"`. A slim device lacks some system features — push notifications, Spotlight, StoreKit sheets, universal links, system pickers — so check it before treating such a failure as a bug. Every device in `getStatus()` and in an admin's `list({ kind: "devices" })` carries the same `mode`. diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 62a31e3b6..fb4f8d1b8 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -55,9 +55,9 @@ a warning. Inspect the effective, merged configuration at any time with | `drivers.ios.deviceRoot` | The CoreSimulator device set Simlock owns and scopes every `simctl` call to. See [Device roots](#device-roots). | `${SIMLOCK_HOME}/devices/ios` | | `drivers.android.deviceRoot` | The AVD home Simlock owns; exported as `ANDROID_AVD_HOME` to every `avdmanager`/`emulator` call. See [Device roots](#device-roots). | `${SIMLOCK_HOME}/devices/android` | | `drivers.android.adbServerPort` | TCP port for Simlock's own adb server. Must not be the shared server's `5037`. Startup fails closed if it is occupied. | `5038` | -| `ios.slim.enabled` | Master switch for slim mode: disables iOS simulator daemon categories to cut RAM and CPU overhead per device. | `false` | -| `ios.slim.categories` | Which daemon categories to disable when slim mode is on. Omitted means every category the driver knows. | every known category | -| `ios.slim.bootTimeoutMs` | Boot deadline used while slim mode is on, in place of the normal boot timeout. | `10 minutes` | +| `ios.defaultMode` | The device mode an iOS lease request gets when it names none: `slim` or `full`. Every worker makes both kinds whatever this says. See [Device mode: slim and full](#device-mode-slim-and-full). | `full` | +| `ios.slim.categories` | Which daemon categories a slim iOS device has disabled. Omitted means every category the driver knows. | every known category | +| `ios.slim.bootTimeoutMs` | Boot deadline for a slim iOS device, in place of the normal boot timeout. | `10 minutes` | | `android.emulator.headless` | Launch emulators without a window (`-no-window`). Needed on a host with no display, such as a Linux CI runner. See [Android emulator launch options](#android-emulator-launch-options). | `false` | | `android.emulator.gpu` | The emulator's GPU mode, passed as `-gpu ` (for example `host`, `swiftshader_indirect`, `guest`). `auto` passes nothing and leaves the emulator's own choice. | `auto` | | `android.emulator.audio` | `false` launches emulators without audio (`-no-audio`). | `true` | @@ -77,7 +77,7 @@ integer in `1`-`65535`. `gateway.label` are strings, and `gateway.disconnectedRetentionMs`, `gateway.execTimeoutMs`, and `gateway.leaseRequestTimeoutMs` positive numbers. -`ios.slim.enabled` is a boolean, `ios.slim.categories` an array of +`ios.defaultMode` is `slim` or `full`, `ios.slim.categories` an array of non-empty strings, and `ios.slim.bootTimeoutMs` a positive number. `android.emulator.headless`, `android.emulator.audio`, and `android.emulator.bootAnimation` are booleans, and `android.emulator.gpu` a @@ -230,7 +230,7 @@ the mismatch changes on a later refresh) — loud enough to catch the misconfiguration without silently overriding it. Everything else — `capacity.*`, `idle.*`, `warmPool.*`, `health.*`, -`stalledTransition.*`, `drivers.*`, `ios.slim.*`, `android.emulator.*`, `diskPressure.*`, +`stalledTransition.*`, `drivers.*`, `ios.*`, `android.emulator.*`, `diskPressure.*`, `downloads.*`, and the worker-side `gateway.url`/`gateway.token`/ `gateway.label`/`exec.timeoutMs` — is **ignored with a warning**, exactly as an unknown key is. That is deliberately the softer treatment: a gateway's @@ -360,22 +360,58 @@ Running two Simlock instances on one machine now needs distinct `drivers.android.adbServerPort` values as well as distinct `SIMLOCK_HOME` values. -Slim mode is opt-in and iOS-only: it disables simulator daemon categories -that most agent workloads never touch, trading some simulator functionality -for a leaner runtime footprint. The categories are widgets, Siri/Apple -Intelligence, Spotlight/search, iCloud, App Store, mail/calendar (PIM), -Safari/web, Family Sharing, Health, Photos, bundled apps (News/Weather/Maps/ -Tips/games), messaging, connectivity, telemetry, and a miscellaneous group -(`widgets`, `siri`, `search`, `icloud`, `store`, `pim`, `web`, `family`, -`health`, `photos`, `apps`, `messaging`, `connectivity`, `telemetry`, -`other` -- the valid `ios.slim.categories` strings, defined in -`src/drivers/ios/slim-labels.ts`). Measured on one simulator: ~258 -> ~70 -processes, ~4.0 GB -> ~0.9 GB. It requires iOS 18.5 or newer, since the -underlying daemon controls are not available on older runtimes. Turning it -on costs an extra boot per device -- the daemons are disabled between a -first boot and a second, slower one -- which is why -`ios.slim.bootTimeoutMs` defaults higher than the normal boot timeout, -especially on slower CI runners. +## Device mode: slim and full + +A lease request can ask for a `slim` or a `full` device (`simlock lease +--mode`, `mode` on MCP, HTTP, and the client). A request that names no mode +gets the default of the worker that serves it, set by `ios.defaultMode` +(default `full`). Every worker makes both kinds of device whatever its +default is, and keeps them apart: a request only ever reuses an idle device +of the mode it resolved to. + +```json +{ + "ios": { + "defaultMode": "slim", + "slim": { "categories": ["widgets", "siri", "telemetry"] } + } +} +``` + +A slim iOS device has simulator daemon categories disabled that most agent +workloads never touch, trading some simulator functionality for a leaner +runtime footprint. The categories are widgets, Siri/Apple Intelligence, +Spotlight/search, iCloud, App Store, mail/calendar (PIM), Safari/web, Family +Sharing, Health, Photos, bundled apps (News/Weather/Maps/Tips/games), +messaging, connectivity, telemetry, and a miscellaneous group (`widgets`, +`siri`, `search`, `icloud`, `store`, `pim`, `web`, `family`, `health`, +`photos`, `apps`, `messaging`, `connectivity`, `telemetry`, `other` -- the +valid `ios.slim.categories` strings). Measured on one simulator: ~258 -> ~70 +processes, ~4.0 GB -> ~0.9 GB. A slim device costs an extra boot -- the +daemons are disabled between a first boot and a second, slower one -- which +is why `ios.slim.bootTimeoutMs` defaults higher than the normal boot timeout, +especially on slower CI runners. The `ios.slim.*` keys apply to every slim +device the worker makes, whatever its default mode. + +**`full` is a guarantee; `slim` is best effort.** A `full` request never +receives a slim device. A `slim` request on a runtime that cannot be slimmed +-- an iOS runtime older than 18.5, or any Android device -- is granted a full +device rather than failing. The lease reports the mode the device actually +has as `mode`, so check it when it matters. + +On a worker whose default mode is `slim`, `simlock doctor` reports the +installed iOS runtimes that cannot be slimmed. + +**Upgrading a worker that had slim switched on.** The old on/off switch under +`ios.slim` is gone; a config that still sets it gets the usual unknown-key +warning and the default mode `full`. Set `ios.defaultMode: "slim"` to keep slim as the +default. Devices made before the upgrade load as full, including ones that +were slimmed, so such a worker could hand a slimmed device to a `full` +request. Empty it before upgrading: + +```bash +simlock nuke --delete-devices +``` ## Android emulator launch options diff --git a/docs/EVENTS.md b/docs/EVENTS.md index 44fa4ab57..72a5ef7ae 100644 --- a/docs/EVENTS.md +++ b/docs/EVENTS.md @@ -9,13 +9,13 @@ through `simlock events` and `simlock events --follow`. | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| -| `lease.requested` | request id, request spec, requester, wait policy | a lease request is accepted by the daemon and stored; the request id is the stored request's, so an observer can match this event to it | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway — its own fleet queue's admission, before any worker is chosen) | implemented | +| `lease.requested` | request id, request spec (platform, model, os version, device mode when the request named one), requester, wait policy | a lease request is accepted by the daemon and stored; the request id is the stored request's, so an observer can match this event to it | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway — its own fleet queue's admission, before any worker is chosen) | implemented | | `lease.queued` | request id, queue position | no capacity; request entered the wait queue | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway) | implemented | | `lease.granted` | lease id, device id, requester | a device was assigned and handed out | LeaseLifecycle | implemented | | `lease.renewed` | lease id, new deadline | a `lease.renew` succeeded — whether it came from `simlock lease renew`, `POST /v1/leases/{id}/renew`, or the renew timer a running `simlock lease` / MCP session keeps over its own lease. There is one renew path and this is it | LeaseLifecycle | implemented | | `lease.released` | lease id, device id, reason (explicit/killed/device-lost), owner id | an explicit `lease.release` (which is what a `simlock lease` holder does on its way out), (killed) an operator `release --all` or `nuke`, or (device-lost) a leased device could not be recovered after it stopped running outside simlock. Closing a connection is not a release and never emits this | LeaseLifecycle | implemented | | `lease.expired` | lease id, device id, owner id | the lease's deadline passed with no `lease.renew` behind it — the grant-time TTL, or the TTL of the last renew, simply ran out. This is the one way a lease ends without somebody asking, and the only bound on a holder that was killed outright | LeaseLifecycle | implemented | -| `lease.rejected` | request spec, reason (timeout/no-wait/unresolvable-spec/already-leased/boot-timeout/killed/cancelled/daemon-restarted) | a request ended without a grant; `daemon-restarted` is a request still waiting when the daemon stopped, settled as failed when it starts again. The reason list can grow: a consumer must tolerate a reason it does not know; `cancelled` is an explicit single-request cancel (backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter — one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses | LeaseAcquisitionCoordinator / WaitQueue / StartupConverger (worker) / FleetLeaseCoordinator (gateway) | implemented | +| `lease.rejected` | request spec (as on `lease.requested`), reason (timeout/no-wait/unresolvable-spec/already-leased/boot-timeout/killed/cancelled/daemon-restarted) | a request ended without a grant; `daemon-restarted` is a request still waiting when the daemon stopped, settled as failed when it starts again. The reason list can grow: a consumer must tolerate a reason it does not know; `cancelled` is an explicit single-request cancel (backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter — one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses | LeaseAcquisitionCoordinator / WaitQueue / StartupConverger (worker) / FleetLeaseCoordinator (gateway) | implemented | On a **gateway**, the first three of these are its own fleet queue's facts, emitted by `FleetLeaseCoordinator` and never by the worker whose device is @@ -29,7 +29,7 @@ the gateway's own lease index before any worker is ever contacted. | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| -| `device.provisioned` | device id, spec, driver, duration | driver `provision` committed to registry | Registry | implemented | +| `device.provisioned` | device id, spec (platform, model, os version, and `mode: "slim"` for a device planned slim), driver, duration | driver `provision` committed to registry | Registry | implemented | | `device.ready` | device id, boot duration | readiness probe passed | Registry | implemented | | `device.reclaimed` | device id, strategy (erase/snapshot/wipe), duration | fresh-state reclaim finished. Never emitted for a device created under `lease.identity` `fresh`: nothing is reclaimed, the device is deleted instead | Registry | implemented | | `device.purge-failed` | device id, lease id, attempted strategy (erase/snapshot/wipe/delete), duration, stable error summary | release-time purge failed, or (strategy `delete`) the shutdown or delete that ends a `fresh` device's lease failed; the device enters `quarantined` (see below) rather than rejoining the pool. The strategy list can grow: a consumer must tolerate a strategy it does not know | WarmPoolCoordinator | implemented | @@ -48,9 +48,11 @@ the gateway's own lease index before any worker is ever contacted. | `device.orphan-purged` | driver device id, platform, device root | `simlock doctor --purge-orphans` destroyed a device that sat inside a validly-marked Simlock device root with no registry record | Doctor | implemented | | `device.slimmed` | device id, address, platform (ios), categories, label count, duration, signature, unknown labels | after the post-slim reboot succeeded, i.e. once the overrides that disable a set of iOS launchd services are confirmed in force on the simulator | driver-diagnostics | implemented | -A *skipped* slim (an older runtime, a runtime id that didn't parse, or a -failed disable pass) is deliberately not an event — it's operator -diagnostics, not a fact worth putting in front of every event-bus consumer. +A slim request on a runtime that cannot be slimmed is planned as a full +device from the start, so it never reaches a slim pass and produces no +`device.slimmed`. A slim pass that did not take (a failed disable pass) is +deliberately not an event — it's operator diagnostics, not a fact worth +putting in front of every event-bus consumer. ## Components diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 92286ecd9..5940790af 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -235,20 +235,26 @@ Role: `agent`. Enqueues a device request. "timeoutMs": 300000, "noWait": false, "allowDownload": false, - "full": false + "mode": "slim" } ``` `platform` and `device` are required; `os` defaults to the newest installed runtime; `ttlMs` defaults to `lease.defaultTtlMs` and is `400 BAD_REQUEST` above `lease.maxTtlMs`; `timeoutMs` (optional) is enforced daemon-side so a -vanished client can't hold a queue slot forever. `full` (optional, default -`false`) opts this request out of iOS slim mode — platform-neutral in shape, -but only the iOS driver acts on it (as "do not slim"); Android ignores it. A -`full: true` request never matches, and never shares a pool key with, a slim -device, so it can wait for a fresh device to provision or force a re-provision -of one already running, even while slim devices sit idle in the warm pool. See -[CONFIGURATION.md](CONFIGURATION.md) for what slim mode disables. +vanished client can't hold a queue slot forever. `mode` (optional, `"slim"` +or `"full"`) is the device mode the request asks for; without it the request +gets the default mode of the worker that serves it (`ios.defaultMode`, `full` +unless configured). `full` is a guarantee: a `full` request never gets a slim +device. `slim` is best effort: on a runtime that cannot be slimmed (an iOS +runtime older than 18.5, or any Android device) the request is granted a full +device. A request only reuses an idle device of the mode it resolved to, so it +can wait for a fresh device even while devices of the other mode sit idle. See +[CONFIGURATION.md](CONFIGURATION.md#device-mode-slim-and-full) for what a slim +device leaves out. + +The body is strict: a key this route does not know, or a `mode` other than +`"slim"` or `"full"`, is `400 BAD_REQUEST`. `allowDownload` is now clamped through `config.downloads.policy` the same way the socket protocol always was (**bug fix, 0.3.0**): before this @@ -267,7 +273,7 @@ changed since — a request that failed with `NO_CAPACITY` stays failed. To try again, use a new key. Repeating works across a daemon restart, for `lease.requestRetentionMs` after the request finished (see [CONFIGURATION.md](CONFIGURATION.md)). The same key with a different -`platform`, `device`, `os`, or `full` is `409 IDEMPOTENCY_CONFLICT`. Keys +`platform`, `device`, `os`, or `mode` is `409 IDEMPOTENCY_CONFLICT`. Keys belong to your token: another token sending the same key starts a request of its own. @@ -369,9 +375,9 @@ is additive rather than a breaking shape change. Running a *command* on the device is not part of it and does not wait for it: that is `exec`, below. `mode` is the device mode the granted device actually has: `"slim"` when its -feature set was reduced (iOS slim mode applied and the request did not carry -`full: true`), `"full"` otherwise — always `"full"` for Android. It lets a -client explain a +feature set was reduced, `"full"` otherwise — always `"full"` for Android. A +`"slim"` request can be granted `"full"` (slim is best effort); a `"full"` +request is never granted `"slim"`. It lets a client explain a feature-loss failure (missing push notification, Spotlight result, StoreKit sheet, universal link, or system picker) instead of misreading it as a bug. diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index f2ea7fc91..24517bebb 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -232,11 +232,12 @@ protocol 4; ADR 0005 adds `device.exec`, its `output` push family, and a `mode` field `status.get` now always carries, again with no compatibility path kept, taking it to 5; ADR 0008 makes the catalog's `modelRuntimes` and `modelAliases` required, taking it to 6; ADR 0007 makes every device report its device mode -as a required `mode`, taking it to 7. So the range both sides advertise is -`{min: 7, max: 7}`, an older client and a current daemon simply +as a required `mode`, taking it to 7, then lets a lease request choose that +mode with `mode` in place of `full`, taking it to 8. So the range both sides +advertise is `{min: 8, max: 8}`, an older client and a current daemon simply do not overlap, and `hello` fails with `PROTOCOL_VERSION_UNSUPPORTED` naming both ranges. The same negotiation runs over a worker's uplink, which is why a -worker older than ADR 0007 shows up in a gateway's views as `incompatible` +worker older than this shows up in a gateway's views as `incompatible` rather than as a mystery (see [Gateway and worker modes](#gateway-and-worker-modes-adr-0005)). `daemon.stop` stays the frozen exception, accepted at any version the daemon has ever spoken, so the upgrade @@ -767,7 +768,8 @@ emits its own facts — `worker.connected`, `worker.disconnected`, older than ADR 0005 is `incompatible` by range**, by construction rather than by accident. ADR 0008 moves it again, to `{min: 6, max: 6}`, because the catalog's `modelRuntimes` and `modelAliases` are required, and ADR 0007 to - `{min: 7, max: 7}`, because a device's `mode` is required; a worker on an + `{min: 7, max: 7}`, because a device's `mode` is required, then to + `{min: 8, max: 8}`, because a lease request chooses it; a worker on an older version is `incompatible` the same way. That is the ordinary upgrade path, not a failure mode: upgrade the worker. An incompatible worker is marked `incompatible` in its view with both ranges shown and is never dispatched to, and it is not diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index b274fd4e0..1dc0ca7ba 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -16,18 +16,23 @@ in short: `subject.past-tense-fact`, emitted post-commit, facts not commands. > connection close to release on, and no startup sweep to orphan anything. > The ADR takes that exception once, while the package is 0.x; this note > records it here so the catalogue does not read as a silent rule violation. +> +> [ADR 0007](adr/0007-a-lease-request-chooses-the-device-mode.md) §13 takes +> the same exception once more: `lease.requested` and `lease.rejected` carry +> the request, and `device.provisioned` the spec, so `full` leaves those +> payloads and `mode` enters (`requestSpec.mode`, `spec.mode`). ## Lease lifecycle | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| -| `lease.requested` | request id, request spec, requester, wait policy | a lease request is accepted by the daemon and stored; the request id is the stored request's, so an observer can match this event to it (#72 added the id; additive, events rule 6) | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway, ADR 0005 §11 — its own fleet queue's admission, before any worker is chosen) | implemented | +| `lease.requested` | request id, request spec (platform, model, os version, device `mode` as the request named it -- absent when it named none, since the worker's default is applied after this event, ADR 0007 §2), requester, wait policy | a lease request is accepted by the daemon and stored; the request id is the stored request's, so an observer can match this event to it (#72 added the id; additive, events rule 6) | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway, ADR 0005 §11 — its own fleet queue's admission, before any worker is chosen) | implemented | | `lease.queued` | request id, queue position | no capacity; request entered the wait queue | LeaseAcquisitionCoordinator (worker) / FleetLeaseCoordinator (gateway) | implemented | | `lease.granted` | lease id, device id, requester | a device was assigned and handed out | LeaseLifecycle | implemented (payload per ADR 0004 pending) | | `lease.renewed` | lease id, new deadline | a `lease.renew` succeeded — whether it came from `simlock lease renew`, `POST /v1/leases/{id}/renew`, or the renew timer a running `simlock lease` / MCP session keeps over its own lease. There is one renew path and this is it | LeaseLifecycle | implemented (payload per ADR 0004 pending) | | `lease.released` | lease id, device id, reason (explicit/killed/device-lost), owner id | an explicit `lease.release` (which is what a `simlock lease` holder does on its way out), (killed) an operator `release --all` or `nuke`, or (device-lost) a leased device could not be recovered after it stopped running outside simlock. Closing a connection is not a release and never emits this | LeaseLifecycle | implemented (payload per ADR 0004 pending) | | `lease.expired` | lease id, device id, owner id | the lease's deadline passed with no `lease.renew` behind it — the grant-time TTL, or the TTL of the last renew, simply ran out. This is the one way a lease ends without somebody asking, and the only bound on a holder that was killed outright | LeaseLifecycle | implemented (payload per ADR 0004 pending) | -| `lease.rejected` | request spec, reason (timeout/no-wait/unresolvable-spec/already-leased/boot-timeout/killed/cancelled/daemon-restarted) | a request ended without a grant; `daemon-restarted` is a request still waiting when the daemon stopped, settled as failed when it starts again (#72; widens a published vocabulary, which events rule 6 allows as additive). The reason list can grow: a consumer must tolerate a reason it does not know; `cancelled` is an explicit single-request cancel (`LeaseEngine#cancelPending`, backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter -- one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses | LeaseAcquisitionCoordinator / WaitQueue / StartupConverger (worker) / FleetLeaseCoordinator (gateway) | implemented | +| `lease.rejected` | request spec (as on `lease.requested`; `full` replaced by `mode`, ADR 0007 §13), reason (timeout/no-wait/unresolvable-spec/already-leased/boot-timeout/killed/cancelled/daemon-restarted) | a request ended without a grant; `daemon-restarted` is a request still waiting when the daemon stopped, settled as failed when it starts again (#72; widens a published vocabulary, which events rule 6 allows as additive). The reason list can grow: a consumer must tolerate a reason it does not know; `cancelled` is an explicit single-request cancel (`LeaseEngine#cancelPending`, backing `DELETE /v1/lease-requests/{id}`) of a still-queued waiter -- one with device work already in flight is reported `not-cancellable` instead, the same envelope the queue timeout already uses | LeaseAcquisitionCoordinator / WaitQueue / StartupConverger (worker) / FleetLeaseCoordinator (gateway) | implemented | On a **gateway**, these three are its own fleet queue's facts (ADR 0005 §11/§14), emitted by `FleetLeaseCoordinator` and never by the worker whose device is @@ -42,7 +47,7 @@ worker is ever contacted. | Event | Payload (key fields) | Emitted when | Emitter | Status | |---|---|---|---|---| -| `device.provisioned` | device id, spec, driver, duration | driver `provision` committed to registry | Registry | implemented | +| `device.provisioned` | device id, spec (`mode: "slim"` for a device planned slim, absent for a full one -- the one place the planned mode is visible, ADR 0007 §9), driver, duration | driver `provision` committed to registry | Registry | implemented | | `device.ready` | device id, boot duration | readiness probe passed | Registry | implemented | | `device.reclaimed` | device id, strategy (erase/snapshot/wipe), duration | fresh-state reclaim finished. Never emitted for a device created under `lease.identity` `fresh` (#75): nothing is reclaimed, the device is deleted instead | Registry | implemented | | `device.purge-failed` | device id, lease id, attempted strategy (erase/snapshot/wipe/delete), duration, stable error summary | release-time purge failed, or (strategy `delete`, #75) the shutdown or delete that ends a `fresh` device's lease failed; the device enters `quarantined` (see below) rather than rejoining the pool. `delete` widens a published vocabulary (events rule 6 allows additive changes): a consumer must tolerate a strategy it does not know | WarmPoolCoordinator (strategy `delete`: WarmPoolCoordinator's spent-device path) | implemented | @@ -67,9 +72,10 @@ only") is satisfied by waiting for that commit to become observable, not by wait write: the driver applies the `launchctl disable` overrides, reboots the device, and only fires `onSlimmed` once the second `bootstatus` has passed, proving the overrides survived the reboot and are actually in force. The registry's own `device.ready` for that same boot is a separate, -later event, emitted through the normal readiness path once the driver call returns. A *skipped* -slim -- the runtime is older than iOS 18.5, its runtime id didn't parse, or the disable pass itself -failed -- is deliberately not an event: it isn't a fact worth putting in front of every event-bus +later event, emitted through the normal readiness path once the driver call returns. A slim +request on a runtime older than iOS 18.5 is resolved to a full spec before planning (ADR 0007 +§4), so it never reaches a slim pass. A *skipped* slim on a slim-spec device -- its runtime id +didn't parse, or the disable pass itself failed -- is deliberately not an event: it isn't a fact worth putting in front of every event-bus consumer, just operator diagnostics, so it's a `warn` log line (`daemon.driver-discovery`) instead. ## Components diff --git a/docs/internal/KNOWN-PITFALLS.md b/docs/internal/KNOWN-PITFALLS.md index 5fbe72391..a3672471b 100644 --- a/docs/internal/KNOWN-PITFALLS.md +++ b/docs/internal/KNOWN-PITFALLS.md @@ -697,12 +697,14 @@ before. `dataPlane` (see [IDEAS.md](IDEAS.md#a-byte-heavy-data-plane)), not a follow-up to `device.exec`. -## iOS slim mode: accepted costs and feature loss (#87) +## iOS slim devices: accepted costs and feature loss (#87, #172) -`ios.slim` (opt-in, default off) has the iOS driver disable ~170 launchd -daemons across simulator daemon categories to cut RAM/CPU footprint (see -[CONFIGURATION.md](../CONFIGURATION.md)). It carries four trade-offs worth -knowing before turning it on. +A slim iOS device -- one a lease asked for with `mode: "slim"`, or got by +default on a worker whose `ios.defaultMode` is `slim` -- has the iOS driver +disable ~170 launchd daemons across simulator daemon categories to cut +RAM/CPU footprint (see [CONFIGURATION.md](../CONFIGURATION.md)). Every worker +makes both slim and full devices (ADR 0007 §3), so these trade-offs apply to +any worker that is ever asked for a slim one. **Every reclaim pays two boots, indefinitely.** `IosSimctlDriver.reclaim` always runs `simctl erase`, which wipes the simulator's data partition — @@ -716,39 +718,49 @@ for this when nothing pre-provisioned was available. A non-erasing `standard` clean level, if one is added later, would let a reclaimed device stay slim and remove this cost; no such level exists today. -**Runtimes older than iOS 18.5 silently get nothing.** `launchctl disable` +**Runtimes older than iOS 18.5 get full devices.** `launchctl disable` overrides only persist across a reboot on iOS 18.5+; older runtimes accept the commands and drop them on the post-slim reboot, so slimming would cost a -second boot for no effect. `planSlimBoot` (`src/drivers/ios/index.ts`) gates -on this and skips the apply pass entirely rather than paying that cost — -silently, from the requester's point of view: the lease still grants, just -with `mode: "full"`. `simlock doctor`'s `driver-advisory` / -`slim-runtime-unsupported` finding is what makes an unsupported runtime -visible to an operator instead of it only ever showing up as an unexpectedly -non-slim lease. +second boot for no effect. The iOS driver's `resolveSpec` therefore resolves +a slim request on such a runtime to the full spec (ADR 0007 §4): the request +pools with full devices and is granted `mode: "full"`, never an error. Slim +is best effort, so the requester only learns this from the grant's `mode`. +`simlock doctor`'s `driver-advisory` / `slim-runtime-unsupported` finding +names the unsupported runtimes, but only on a worker whose default mode is +`slim` (ADR 0007 §14); a default-full worker stays quiet even when a request +asked for slim explicitly. **Slim devices lose features that depend on the disabled daemons.** Expect push notifications, Spotlight/on-device search, StoreKit/App Store sheets, universal links, Siri/Apple Intelligence, iCloud sync, and some system pickers to not work on a slim device — the categories that back them are -exactly the ones slimming disables. Mitigations: `simlock lease --full` (MCP -`full: true`, HTTP `full: true`) opts a single lease out of slimming, and -every lease response carries the device mode so a caller can tell a +exactly the ones slimming disables. Mitigations: `simlock lease --mode full` +(`mode: "full"` on MCP, HTTP, and the client) guarantees a full device for a +single lease, and every lease response carries the device mode so a caller can tell a feature-loss failure apart from an actual bug instead of guessing — `device.mode === "slim"` on the CLI/MCP/client contract shape, and `lease.mode === "slim"` on HTTP (ADR 0007 §9: one word on every surface). -**Mixing slim and full devices under one spec can make `--full` wait or -re-provision.** `full` is part of spec identity (`DeviceSpec.full`, compared by `sameSpec`, -see [ADR 0002](adr/0002-opt-in-slim-ios-simulators.md)), so a `--full` -request never matches a slim device sitting warm in the pool — even when one is idle and a -match on model/os alone would otherwise be instant. Depending on capacity, -that means either queueing for a fresh device to provision or forcing a -re-provision of a device already running. This is inherent to keeping pool -matching from fragmenting on driver-level settings, not a bug to fix. +**Mixing slim and full devices under one spec can make a request wait or +re-provision.** The planned mode is part of spec identity (`DeviceSpec.mode`, +compared by `sameSpec`, ADR 0007 §6), so a `full` request never matches a +slim device sitting warm in the pool, and a `slim` request never matches a +full one — even when one is idle and a match on model/os alone would +otherwise be instant. Depending on capacity, that means either queueing for +a fresh device to provision or forcing a re-provision of a device already +running. This is what keeps `full` a guarantee, not a bug to fix. + +**A budget sized for slim devices overcommits when full devices are leased.** +The capacity budget counts every device as one size, whatever its mode. An +operator who sized `capacity` for slim devices (~0.9 GB each) on a worker +that also serves `full` requests (~4 GB each) can end up with more full +devices running than the machine has memory for. Until capacity counts by +mode ([#174](https://github.com/callstackincubator/simlock/issues/174)), +size the budget for the mode that is actually leased, or for full devices +when both are. **A cold slim lease outlives a default MCP request timeout.** Measured on -one machine: a `--full` cold lease took ~28s, a cold slim lease ~160s (two +one machine: a full cold lease took ~28s, a cold slim lease ~160s (two real boots plus the disable pass). The MCP SDK's default per-request timeout is 60s, so an MCP client that does not reset its timeout on progress notifications gets `MCP error -32001: Request timed out` on the slim lease @@ -787,25 +799,17 @@ would ever produce. Workaround: after narrowing the category list, reclaim (or destroy) every device already running under the old, wider set before relying on the change — a plain reboot is not enough. -**Turning `ios.slim.enabled` off leaves orphaned `--full` devices sitting in -the pool.** `full` only earns its own pool key while the driver might -otherwise hand back a reduced device (`Driver.reducesFeatures`); once slim -mode is off, no newly resolved spec ever carries `full: true` again. A device -that was provisioned for a `--full` request while slim mode was on keeps -`full: true` on its spec in the registry, so it can no longer match anything -a resolver produces — it becomes unmatchable by any new request. This is not -a permanent orphan: the idle-shutdown and idle-destroy cleanup rules reap it -on the same timers as any other idle device, since neither rule cares what a -device's spec matches. Until those timers fire, though, it occupies a pool -slot doing nothing. - -**A device slimmed before the upgrade to `mode` reports `full`.** A device -record written before devices carried a `mode` loads as `full`, and nothing -is derived from its old feature-profile field (ADR 0007 §11). A worker that -ran with `ios.slim.enabled` on therefore holds slimmed devices that report -`mode: "full"` on grants, `status`, and `list` until their next boot rewrites -the mode. Empty such a worker with `simlock nuke --delete-devices` before -upgrading it. +**A worker upgraded without being emptied can grant a slimmed device as +full.** A device record written before devices carried a `mode` loads as +`full`, and nothing is derived from its old feature-profile field or from +the `full` flag an older daemon stored on its spec (ADR 0007 §11). A worker +that had the old slim switch on therefore holds slimmed devices that load +with a full spec: they report `mode: "full"` on grants, `status`, and `list` +until their next boot rewrites the mode, and they sit in the full pool, so a +`full` request can be granted one. This is the one case where the `full` +guarantee does not hold, and it only covers devices made before the upgrade. +Empty such a worker with `simlock nuke --delete-devices` before upgrading it; +[CONFIGURATION.md](../CONFIGURATION.md) carries the same step. ## A dispatched request whose uplink drops may have granted a lease anyway diff --git a/e2e/daemon-lifecycle.test.ts b/e2e/daemon-lifecycle.test.ts index 9c28cfcb5..462c36f69 100644 --- a/e2e/daemon-lifecycle.test.ts +++ b/e2e/daemon-lifecycle.test.ts @@ -41,6 +41,18 @@ describe("daemon lifecycle & recovery", () => { }); }); + it("simlock config renders ios.defaultMode, full by default, and no on/off switch under ios.slim", async () => { + const env = await withDaemon({ mode: "running" }); + + const config = await env.cli(["config"]); + + expect(config.code).toBe(0); + const ios = (config.json as { ios: { defaultMode: string; slim: Record } }) + .ios; + expect(ios.defaultMode).toBe("full"); + expect(ios.slim).not.toHaveProperty("enabled"); + }); + it("recovers from a kill -9 that leaves a stale socket behind", async () => { const env = await withDaemon({ mode: "running" }); expect(existsSync(env.socketPath)).toBe(true); diff --git a/e2e/fake-driver/fake-driver.ts b/e2e/fake-driver/fake-driver.ts index 38b3b3796..dd978ef38 100644 --- a/e2e/fake-driver/fake-driver.ts +++ b/e2e/fake-driver/fake-driver.ts @@ -219,7 +219,13 @@ export class OutOfProcessFakeDriver implements Driver { const script = await this.#beforeCall("resolveSpec", [request, options]); this.#assertKnownModel(request.model, script); const osVersion = this.#resolveOsVersion(request.osVersion, script, options.allowDownload); - return { model: request.model, osVersion, platform: this.platform }; + const slim = request.mode === "slim" && script.slimmableOsVersions?.includes(osVersion); + return { + model: request.model, + osVersion, + platform: this.platform, + ...(slim === true ? { mode: "slim" as const } : {}), + }; } #assertKnownModel(model: string, script: FakeDriverPlatformScript): void { @@ -263,20 +269,25 @@ export class OutOfProcessFakeDriver implements Driver { /** * Re-reads the script's `address` on every boot -- see `FakeDriverPlatformScript.address`. - * `options.purpose` is logged alongside the call but otherwise ignored -- this fake never - * applies any configuration a `"recover"` boot would need to skip. + * `options` is logged alongside the call. A script with `slimmableOsVersions` reports + * `"slim"` for a prepare boot of a slim-spec device and `"full"` otherwise, as the iOS driver + * does; without it no mode is reported. */ async makeReady( device: DriverDevice, - options?: { readonly purpose: "prepare" | "recover" }, + options: { readonly purpose: "prepare" | "recover"; readonly mode: "slim" | "full" }, ): Promise { const script = await this.#beforeCall("makeReady", [device, options]); this.#devices.set(device.deviceId, "ready"); + const slims = script.slimmableOsVersions !== undefined; return { address: script.address ?? defaultAddress(device.deviceId), deviceId: device.deviceId, driverData: device.driverData, - }; + ...(slims + ? { mode: options.mode === "slim" && options.purpose === "prepare" ? "slim" : "full" } + : {}), + } satisfies DriverDevice; } async reclaim( diff --git a/e2e/fake-driver/types.ts b/e2e/fake-driver/types.ts index dfafa449b..1abd09ce6 100644 --- a/e2e/fake-driver/types.ts +++ b/e2e/fake-driver/types.ts @@ -56,6 +56,12 @@ export interface ScriptedManagedReality { export interface FakeDriverPlatformScript { readonly knownModels?: readonly string[]; readonly availableOsVersions?: readonly string[]; + /** + * The OS versions this fake can slim. A slim request on one of them resolves to a slim spec, + * and a prepare boot of a slim-spec device reports `mode: "slim"`. Absent: every request + * resolves to a full spec and no boot reports a mode, as a driver that does not slim. + */ + readonly slimmableOsVersions?: readonly string[]; /** * What `listCatalog` reports a model pairs with. A model left out pairs with every available * version, which is also the default for every model. diff --git a/e2e/gateway-fleet.test.ts b/e2e/gateway-fleet.test.ts index 934bcaeaa..6f559fd2e 100644 --- a/e2e/gateway-fleet.test.ts +++ b/e2e/gateway-fleet.test.ts @@ -374,6 +374,83 @@ describe("gateway fleet", () => { ]); }); + it("gives a request with a mode that mode on either worker, and a request with none the default of the worker it landed on", async () => { + const port = await freeLoopbackPort(); + const gateway = await withDaemon({ + configOverrides: { http: { host: "127.0.0.1", port }, mode: "gateway" }, + driver: "none", + }); + const minted = await gateway.cli(["token", "create", "--role", "worker"]); + const { secret } = minted.json as { secret: string }; + const uplink = { token: secret, url: `ws://127.0.0.1:${port}` }; + // One model per worker, so the model alone decides where a request lands. Both workers can + // slim the one runtime they have. + await withDaemon({ + configOverrides: { + gateway: { ...uplink, label: "default-full" }, + ios: { defaultMode: "full" }, + }, + driverScript: { + ios: { + availableOsVersions: ["26.0"], + knownModels: ["iPhone 16"], + slimmableOsVersions: ["26.0"], + }, + }, + }); + await withDaemon({ + configOverrides: { + gateway: { ...uplink, label: "default-slim" }, + ios: { defaultMode: "slim" }, + }, + driverScript: { + ios: { + availableOsVersions: ["26.0"], + knownModels: ["iPhone 17"], + slimmableOsVersions: ["26.0"], + }, + }, + }); + await waitForWorkers( + gateway, + (views) => + views.length === 2 && + views.every((view) => view.connection === "connected" && view.catalog.length > 0), + "both workers connected with their catalogs", + ); + + const leaseMode = async (device: string, mode: readonly string[]) => { + const leased = await gateway.cli( + ["lease", "--platform", "ios", "--device", device, "--detach", ...mode], + { timeout: 30_000 }, + ); + expect(leased.code, leased.stderr).toBe(0); + const grant = leased.json as { + readonly device: { readonly mode: string }; + readonly lease: { readonly id: string; readonly worker?: { readonly label?: string } }; + }; + expect((await gateway.cli(["release", grant.lease.id], { timeout: 30_000 })).code).toBe(0); + return { mode: grant.device.mode, worker: grant.lease.worker?.label }; + }; + + await expect(leaseMode("iPhone 16", [])).resolves.toEqual({ + mode: "full", + worker: "default-full", + }); + await expect(leaseMode("iPhone 16", ["--mode", "slim"])).resolves.toEqual({ + mode: "slim", + worker: "default-full", + }); + await expect(leaseMode("iPhone 17", [])).resolves.toEqual({ + mode: "slim", + worker: "default-slim", + }); + await expect(leaseMode("iPhone 17", ["--mode", "full"])).resolves.toEqual({ + mode: "full", + worker: "default-slim", + }); + }); + it("refuses an uplink whose token is not a worker join token", async () => { const port = await freeLoopbackPort(); const gateway = await withDaemon({ diff --git a/e2e/slow-ios-slim.test.ts b/e2e/slow-ios-slim.test.ts index b1cff8ccd..d0ee8526a 100644 --- a/e2e/slow-ios-slim.test.ts +++ b/e2e/slow-ios-slim.test.ts @@ -143,32 +143,50 @@ describe.skipIf(process.platform !== "darwin")( { tags: ["slow", "ios"] }, () => { it( - "scenario 1: slim off (default) is byte-for-byte today's behaviour", - { timeout: 300_000 }, + "scenario 1: on a default-full worker a request with no mode is full, and --mode slim is slim", + { timeout: 600_000 }, async () => { const env = await withDaemon({ driver: "real" }); try { const { model, os } = await catalogModelAndOs(env); - const grant = await leaseDetached(env, model, os, "slim-off-default"); + const grant = await leaseDetached(env, model, os, "default-full"); - expect(grant.mode, "a lease must be full when ios.slim is not configured").toBe("full"); + expect(grant.mode, "a request with no mode must be full on a default-full worker").toBe( + "full", + ); const disabled = await printDisabled(grant.udid); const overlap = [...ALL_LABELS].filter((label) => disabled.has(label)); expect( overlap, - `expected none of the slim label set disabled on a non-slim device, found: ${overlap.join(", ")}`, + `expected none of the slim label set disabled on a full device, found: ${overlap.join(", ")}`, ).toEqual([]); const recorded = await env.events("1h"); const slimmedEvents = recorded.filter((event) => event.event === "device.slimmed"); - expect(slimmedEvents, "no device.slimmed event expected with slim off").toEqual([]); + expect(slimmedEvents, "no device.slimmed event expected for a full device").toEqual([]); const doctorReport = (await env.cli(["doctor"])).json as DoctorReport; const advisories = doctorReport.findings.filter( (finding) => finding.kind === "driver-advisory", ); - expect(advisories, "no driver-advisory finding expected with slim off").toEqual([]); + expect( + advisories, + "no driver-advisory finding expected on a default-full worker", + ).toEqual([]); + + expect((await env.cli(["release", grant.lease])).code).toBe(0); + + const slimGrant = await leaseDetached(env, model, os, "default-full-asks-slim", [ + "--mode", + "slim", + ]); + expect(slimGrant.mode, "--mode slim must be slim on a default-full worker").toBe("slim"); + expect(slimGrant.udid, "a slim request must not reuse the idle full device").not.toBe( + grant.udid, + ); + const slimDisabled = await printDisabled(slimGrant.udid); + expect([...ALL_LABELS].filter((label) => !slimDisabled.has(label))).toEqual([]); await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); } finally { @@ -178,50 +196,22 @@ describe.skipIf(process.platform !== "darwin")( ); it( - "scenario 2/3/4/7: cold slim lease, idempotence across a reclaim, --full opt-out, and doctor advisory absence", + "scenario 2/3/4/7: on a default-slim worker, a cold slim lease, --mode full while a slim device sits idle, idempotence across a reclaim, and doctor advisory absence", { timeout: 900_000 }, async () => { const env = await withDaemon({ driver: "real", - configOverrides: { ios: { slim: { enabled: true } } }, + configOverrides: { ios: { defaultMode: "slim" } }, }); try { const { model, os } = await catalogModelAndOs(env); - // --- scenario 4 half A + baseline process count: a --full lease is untouched. --- - const fullStart = Date.now(); - const fullGrant = await leaseDetached(env, model, os, "slim-full-opt-out", ["--full"]); - const fullDurationMs = Date.now() - fullStart; - expect(fullGrant.mode, "a --full lease's grant must carry mode: full").toBe("full"); - const fullDisabled = await printDisabled(fullGrant.udid); - const fullOverlap = [...ALL_LABELS].filter((label) => fullDisabled.has(label)); - expect( - fullOverlap, - `--full device must have none of the slim labels disabled, found: ${fullOverlap.join(", ")}`, - ).toEqual([]); - const fullProcessCount = await processCount(fullGrant.udid); - - const doctorAfterFull = (await env.cli(["doctor"])).json as DoctorReport; - const driftForFull = doctorAfterFull.findings.filter( - (finding) => finding.kind !== "driver-advisory" && finding.deviceId !== undefined, - ); - expect( - driftForFull.filter((finding) => finding.deviceId === fullGrant.udid), - "doctor must report no drift for the --full device", - ).toEqual([]); - - // --- scenario 2: a cold, non-full lease produces a slim device. --- - const eventsBeforeSlim = await env.events("1h"); - const slimmedBefore = eventsBeforeSlim.filter( - (event) => event.event === "device.slimmed", - ).length; - + // --- scenario 2: a cold lease naming no mode produces a slim device. --- const slimStart = Date.now(); const slimGrant = await leaseDetached(env, model, os, "slim-cold"); const slimDurationMs = Date.now() - slimStart; expect(slimGrant.mode, "a slim lease's grant must carry mode: slim").toBe("slim"); - expect(slimGrant.udid).not.toBe(fullGrant.udid); const slimDisabled = await printDisabled(slimGrant.udid); const missing = [...ALL_LABELS].filter((label) => !slimDisabled.has(label)); @@ -232,8 +222,38 @@ describe.skipIf(process.platform !== "darwin")( const boot = await simctlDevices(); expect(boot.find((device) => device.udid === slimGrant.udid)?.state).toBe("Booted"); - const slimProcessCount = await processCount(slimGrant.udid); + + const eventsAfterSlim = await env.expectEvents(["device.slimmed"], { since: "1h" }); + const slimmedEvents = eventsAfterSlim.filter((event) => event.event === "device.slimmed"); + expect(slimmedEvents.length).toBe(1); + + // --- scenario 4: with the slim device released and idle in the pool, --mode full gets + // a different, full device. --- + expect((await env.cli(["release", slimGrant.lease])).code).toBe(0); + await waitForDeviceState(env, slimGrant.udid, "ready", { timeout: 120_000 }); + + const fullStart = Date.now(); + const fullGrant = await leaseDetached(env, model, os, "slim-full", ["--mode", "full"]); + const fullDurationMs = Date.now() - fullStart; + expect(fullGrant.mode, "a --mode full lease's grant must carry mode: full").toBe("full"); + expect(fullGrant.udid, "--mode full must not receive the idle slim device").not.toBe( + slimGrant.udid, + ); + const fullDisabled = await printDisabled(fullGrant.udid); + const fullOverlap = [...ALL_LABELS].filter((label) => fullDisabled.has(label)); + expect( + fullOverlap, + `--mode full device must have none of the slim labels disabled, found: ${fullOverlap.join(", ")}`, + ).toEqual([]); + const fullProcessCount = await processCount(fullGrant.udid); + + const doctorAfterFull = (await env.cli(["doctor"])).json as DoctorReport; + expect( + doctorAfterFull.findings.filter((finding) => finding.deviceId === fullGrant.udid), + "doctor must report no drift for the full device", + ).toEqual([]); + const reduction = 1 - slimProcessCount / fullProcessCount; expect( reduction, @@ -242,9 +262,6 @@ describe.skipIf(process.platform !== "darwin")( `${(reduction * 100).toFixed(1)}% reduction`, ).toBeGreaterThanOrEqual(0.3); - const eventsAfterSlim = await env.expectEvents(["device.slimmed"], { since: "1h" }); - const slimmedEvents = eventsAfterSlim.filter((event) => event.event === "device.slimmed"); - expect(slimmedEvents.length).toBe(slimmedBefore + 1); const slimmedFact = slimmedEvents.at(-1)?.payload as { deviceId: string; platform?: string; @@ -283,15 +300,11 @@ describe.skipIf(process.platform !== "darwin")( "machine (26.4.1, 27.0) are >= 18.5", ).toEqual([]); - // --- scenario 3: release, then re-lease the same spec. Per docs/internal/KNOWN-PITFALLS.md + // --- scenario 3: re-lease the released slim spec. Per docs/internal/KNOWN-PITFALLS.md // ("Every reclaim pays two boots, indefinitely"), IosSimctlDriver.reclaim always runs // `simctl erase`, wiping the launchctl overrides -- so the documented behaviour is // that the warm-pooled device comes back stock and pays a SECOND device.slimmed, not // that it's skipped. We assert that documented behaviour here. - const releaseResult = await env.cli(["release", slimGrant.lease]); - expect(releaseResult.code).toBe(0); - await waitForDeviceState(env, slimGrant.udid, "ready", { timeout: 120_000 }); - const relet = await leaseDetached(env, model, os, "slim-cold"); expect(relet.udid, "expected the warm-pooled device to be reused").toBe(slimGrant.udid); expect(relet.mode, "re-leased device must still report mode: slim").toBe("slim"); @@ -306,7 +319,7 @@ describe.skipIf(process.platform !== "darwin")( slimmedAfterRelease.length, "expected a SECOND device.slimmed for this udid after release+re-lease, per the " + "documented erase-on-reclaim cost (docs/internal/KNOWN-PITFALLS.md)", - ).toBe(slimmedBefore + 2); + ).toBe(2); await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); } finally { @@ -332,7 +345,7 @@ describe.skipIf(process.platform !== "darwin")( const env = await withDaemon({ driver: "real", configOverrides: { - ios: { slim: { enabled: true, categories: ["siri", "telemetry"] } }, + ios: { defaultMode: "slim", slim: { categories: ["siri", "telemetry"] } }, }, }); try { @@ -364,7 +377,7 @@ describe.skipIf(process.platform !== "darwin")( // --- scenario 6: an unknown category alongside a known one is not fatal. --- await env.withConfig( - { ios: { slim: { enabled: true, categories: ["siri", "no-such-category"] } } }, + { ios: { defaultMode: "slim", slim: { categories: ["siri", "no-such-category"] } } }, async () => { const grant2 = await leaseDetached(env, model, os, "slim-unknown-category"); expect(grant2.mode, "lease must still succeed and be slim").toBe("slim"); @@ -388,7 +401,7 @@ describe.skipIf(process.platform !== "darwin")( const env = await withDaemon({ driver: "real", configOverrides: { - ios: { slim: { enabled: true } }, + ios: { defaultMode: "slim" }, health: { probeIntervalMs: 2_000, recoveryBackoffMs: 1_000, stableObservations: 1 }, }, }); @@ -442,7 +455,7 @@ describe.skipIf(process.platform !== "darwin")( it("scenario 9: MCP carries the device mode both ways", { timeout: 600_000 }, async () => { const env = await withDaemon({ driver: "real", - configOverrides: { ios: { slim: { enabled: true } } }, + configOverrides: { ios: { defaultMode: "slim" } }, }); try { const { model, os } = await catalogModelAndOs(env); @@ -456,7 +469,7 @@ describe.skipIf(process.platform !== "darwin")( const fullResult = await mcp.client.callTool( { name: "lease_simulator", - arguments: { full: true, model, osVersion: os, platform: "ios" }, + arguments: { mode: "full", model, osVersion: os, platform: "ios" }, }, undefined, leaseCallOptions, @@ -465,7 +478,9 @@ describe.skipIf(process.platform !== "darwin")( device: { mode: "slim" | "full" }; lease: { id: string }; }; - expect(fullLeased.device.mode, "MCP full:true lease must report mode: full").toBe("full"); + expect(fullLeased.device.mode, "MCP mode: full lease must report mode: full").toBe( + "full", + ); await mcp.client.callTool({ name: "release_simulator", @@ -486,7 +501,7 @@ describe.skipIf(process.platform !== "darwin")( }; expect( slimLeased.device.mode, - "MCP plain lease under ios.slim.enabled must report mode: slim", + "MCP lease naming no mode on a default-slim worker must report mode: slim", ).toBe("slim"); await mcp.client.callTool({ diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 5721ee269..193271c88 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -137,7 +137,7 @@ describe("readLogFile", () => { * 5), and (see "CLI: lease pushes and exit codes" / "CLI: mcp command" / "CLI: daemon logs" * below) the CLI's own process-lifecycle and stderr-rendering behaviour that no other suite * exercises: the lost-lease exit code and its non-re-release, the `{push:...}` stderr lines - * including the own-lease-id filter, the `--full`/`--no-wait` flag mapping, the `mcp` command's + * including the own-lease-id filter, the `--mode`/`--no-wait` flag mapping, the `mcp` command's * lazy module load and startup-failure reporting, and `daemon logs` working without a * connection. Deleted from the pre-ADR suite: every test that only re-walked a daemon * operation's request/response shape through the CLI (lease grant field-by-field, doctor @@ -2265,7 +2265,7 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( }); }); - it("maps --full and --no-wait onto the contract's full/noWait input fields", async () => { + it("maps --mode and --no-wait onto the contract's mode/noWait input fields", async () => { const output = outputCapture(); let capturedInput: Record | undefined; const client = fakeClient({ @@ -2306,16 +2306,34 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( "--device", "iPhone 17 Pro", "--detach", - "--full", + "--mode", + "slim", "--no-wait", ], output.environmentWith({ connectAdmin: async () => client }), ); - expect(capturedInput?.full).toBe(true); + expect(capturedInput?.mode).toBe("slim"); expect(capturedInput?.noWait).toBe(true); }); - it("omits full and reports noWait: false when neither flag is given", async () => { + it("fails the removed full flag as an unknown option, before connecting", async () => { + const output = outputCapture(); + let connected = false; + const exitCode = await runCli( + ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--full"], + output.environmentWith({ + connectAdmin: async () => { + connected = true; + return fakeClient({}); + }, + }), + ); + expect(exitCode).toBe(2); + expect(connected).toBe(false); + expect(output.stderr).toContain("--full"); + }); + + it("omits mode and reports noWait: false when neither flag is given", async () => { const output = outputCapture(); let capturedInput: Record | undefined; const client = fakeClient({ @@ -2352,7 +2370,7 @@ describe("CLI: lease pushes and exit codes (own logic, not the dispatcher's)", ( ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--detach"], output.environmentWith({ connectAdmin: async () => client }), ); - expect(capturedInput?.full).toBeUndefined(); + expect(capturedInput).not.toHaveProperty("mode"); expect(capturedInput?.noWait).toBe(false); }); }); @@ -3966,7 +3984,7 @@ function testConfig(): Config { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, lease: { diff --git a/src/cli/index.ts b/src/cli/index.ts index a919dafcb..6b56c5248 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -913,8 +913,8 @@ async function runLease( detach: { type: "boolean" }, device: { type: "string" }, "export-env": { type: "boolean" }, - full: { type: "boolean" }, help: { type: "boolean", short: "h" }, + mode: { type: "string" }, "no-wait": { type: "boolean" }, os: { type: "string" }, platform: { type: "string" }, @@ -924,9 +924,9 @@ async function runLease( if (values.help) { environment.stdout.write( "Usage: simlock lease --platform --device [--os ]\n" + - " [--agent-id ] [--timeout ] [--no-wait] [--detach]\n" + - " [--ttl ] [--allow-download] [--full] [--export-env]\n" + - " [--bind-pid ]\n", + " [--mode ] [--agent-id ] [--timeout ]\n" + + " [--no-wait] [--detach] [--ttl ] [--allow-download]\n" + + " [--export-env] [--bind-pid ]\n", ); return 0; } @@ -1074,7 +1074,9 @@ async function runLease( model: values.device, ...(typeof values.os === "string" ? { osVersion: values.os } : {}), platform, - ...(values.full === true ? { full: true } : {}), + // Sent as typed: the contract, not the CLI, decides which modes exist, and answers + // anything else with `BAD_REQUEST`. + ...(typeof values.mode === "string" ? { mode: values.mode as "slim" | "full" } : {}), ...(timeoutMs === undefined ? {} : { timeoutMs }), ...(ttlMs === undefined ? {} : { ttlMs }), }, diff --git a/src/contract/operations.test.ts b/src/contract/operations.test.ts index 75043fd06..1d2ca6d73 100644 --- a/src/contract/operations.test.ts +++ b/src/contract/operations.test.ts @@ -186,14 +186,24 @@ describe("operation input/output round trips", () => { ).toMatchObject({ ttlMs: 60_000 }); }); - it("lease.request: rejects mode, which ADR 0004 removed from the contract", () => { - expect(() => - OPERATIONS["lease.request"].input.parse({ + it.each(["slim", "full"] as const)("lease.request: accepts mode %s", (mode) => { + expect( + OPERATIONS["lease.request"].input.parse({ model: "iPhone 17 Pro", mode, platform: "ios" }), + ).toMatchObject({ mode }); + }); + + it.each([ + ["full", { full: true }], + ["a mode other than slim or full", { mode: "fast" }], + ["the lease mode ADR 0004 retired", { mode: "held" }], + ])("lease.request: rejects %s", (_label, extra) => { + expect( + OPERATIONS["lease.request"].input.safeParse({ model: "iPhone 17 Pro", - mode: "held", platform: "ios", - }), - ).toThrow(); + ...extra, + }).success, + ).toBe(false); }); it("lease.request/lease.renew: a non-positive ttlMs is a schema-level BAD_REQUEST", () => { @@ -598,7 +608,7 @@ describe("operation input/output round trips", () => { recoveryBackoffMs: 1, maxConcurrentRecoveries: 1, }, - ios: { slim: { enabled: false, bootTimeoutMs: 1 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 1 } }, android: { emulator: { headless: true, gpu: "host", audio: false, bootAnimation: false } }, stalledTransition: { thresholdMultiplier: 1, minimumThresholdMs: 1 }, }; diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 0b553fa9c..012d3fe37 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -123,15 +123,17 @@ export const statusGet = defineOperation({ * No `device`/`os` legacy aliases and no nested `request` wrapper -- both accepted by the * pre-ADR-0003 daemon, neither carried forward. `.strict()` on top of dropping the fields: an * old client sending `device`/`os`/`request` gets a clear `BAD_REQUEST` instead of those keys - * silently vanishing. `mode` leaves the same way under ADR 0004 -- there is one kind of lease, - * so a request that still names a mode is a `BAD_REQUEST` rather than a value silently ignored. + * silently vanishing. `mode` is the device mode the request asks for (ADR 0007 §1), absent + * when it names none so the worker's default applies; any value but `slim` or `full` -- the + * lease mode ADR 0004 retired included -- is a `BAD_REQUEST`. `full` was replaced by `mode` + * with no alias, so `.strict()` turns a request that still sends it into a `BAD_REQUEST` too. */ const leaseRequestInputSchema = z .object({ model: z.string().min(1), platform: platformSchema, osVersion: z.string().optional(), - full: z.boolean().optional(), + mode: z.enum(["slim", "full"]).optional(), requesterId: z.string().optional(), allowDownload: z.boolean().optional(), noWait: z.boolean().optional(), diff --git a/src/contract/protocol.ts b/src/contract/protocol.ts index 9f209943a..b8f18f8de 100644 --- a/src/contract/protocol.ts +++ b/src/contract/protocol.ts @@ -14,15 +14,17 @@ export interface ProtocolRange { const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().int() }); /** - * The range this contract's daemon speaks. Both ends are 7, and every move that got it there + * The range this contract's daemon speaks. Both ends are 8, and every move that got it there * was breaking with no shim kept behind them, which is exactly when ADR 0003 §6's honesty * rule says a range must *not* widen: ADR 0004 removed `lease.heartbeat` and `mode` from the * wire (taking it to 4), and ADR 0005 adds `device.exec` and its `output` push family, a * `mode` field `status.get` now always carries, and the gateway surface -- `worker.*`, * `workerId`, the `worker` token role -- on top (taking it to 5). ADR 0008 makes the catalog * carry a required `modelRuntimes` and `modelAliases` per platform (taking it to 6), which a - * gateway reading a worker's catalog depends on. ADR 0007 makes a device's mode a required `mode` on the grant, - * `status.get`, and `list.get` (taking it to 7). It only ever widens once a + * gateway reading a worker's catalog depends on. ADR 0007 makes a device's mode a required `mode` + * on the grant, `status.get`, and `list.get` (taking it to 7), then lets a lease request choose + * that mode with `mode`, replacing `full`, and reshapes `config.get`'s `ios` block (taking it to + * 8). It only ever widens once a * second version is actually kept alive side by side with the first, which nothing here does. * * A client from before any of those changes simply does not overlap this daemon, and `hello` @@ -34,9 +36,10 @@ const protocolRangeSchema = z.object({ min: z.number().int(), max: z.number().in * * The consequence ADR 0005 §31 names: a pre-0005 worker's uplink negotiates nothing, so its * gateway marks it `incompatible` -- with both ranges on the view -- and never dispatches to it. - * A worker on 5 is marked `incompatible` the same way (ADR 0008 §10). + * A worker on 5 is marked `incompatible` the same way (ADR 0008 §10), and so is one on 7 + * (ADR 0007 §12). */ -export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 7, max: 7 }; +export const PROTOCOL_VERSION_RANGE: ProtocolRange = { min: 8, max: 8 }; /** * The one protocol version that ever existed before ranges did. Used only to build the diff --git a/src/contract/schemas.test.ts b/src/contract/schemas.test.ts index 1c8454eaf..d7131999d 100644 --- a/src/contract/schemas.test.ts +++ b/src/contract/schemas.test.ts @@ -206,6 +206,18 @@ describe("statusDeviceSchema's device projection", () => { expect(() => statusDeviceSchema.parse({ ...device, mode: "reduced" })).toThrow(); }); + it("shows no planned mode on a device's spec in a grant, a status device, or a list.get record", () => { + const device = { + ...fullCoreShapedDevice(), + mode: "full", + spec: { platform: "ios", model: "iPhone 17 Pro", osVersion: "26.5", mode: "slim" }, + }; + + expect(grantedDeviceSchema.parse(device).spec).not.toHaveProperty("mode"); + expect(statusDeviceSchema.parse(device).spec).not.toHaveProperty("mode"); + expect(deviceRecordSchema.parse(device).spec).not.toHaveProperty("mode"); + }); + it("rejects a list.get device record without a mode, or with a mode other than slim or full", () => { const record = { id: "device-1", diff --git a/src/contract/schemas.ts b/src/contract/schemas.ts index 524fa6d8d..ee9ff07ee 100644 --- a/src/contract/schemas.ts +++ b/src/contract/schemas.ts @@ -37,11 +37,12 @@ const deviceModeSchema = z.enum(["slim", "full"]); const leaseIdentitySchema = z.enum(["reusable", "fresh"]); +/** A device's spec as responses show it. The spec's planned mode is not shown (ADR 0007 §9): the + * device's `mode` is the one mode a response reports. */ const deviceSpecSchema = z.object({ platform: platformSchema, model: z.string(), osVersion: z.string(), - full: z.boolean().optional(), }); /** Mirrors `DeviceRecord` (src/core/domain.ts) field for field, plus the `status`/`list` @@ -233,7 +234,7 @@ export const leaseRequestRecordSchema = z.object({ platform: platformSchema, model: z.string(), osVersion: z.string().optional(), - full: z.boolean().optional(), + mode: deviceModeSchema.optional(), }), createdAt: z.number(), state: z.enum(["open", "granted", "failed", "cancelled"]), @@ -596,8 +597,8 @@ export const configSchema = z.object({ maxConcurrentRecoveries: z.number(), }), ios: z.object({ + defaultMode: deviceModeSchema, slim: z.object({ - enabled: z.boolean(), categories: z.array(z.string()).optional(), bootTimeoutMs: z.number(), }), diff --git a/src/core/acquisition-planner.test.ts b/src/core/acquisition-planner.test.ts index d0db36faf..1cc716f8c 100644 --- a/src/core/acquisition-planner.test.ts +++ b/src/core/acquisition-planner.test.ts @@ -32,7 +32,7 @@ const config: Config = { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, warmPool: { diff --git a/src/core/cleanup/idle-destroy.test.ts b/src/core/cleanup/idle-destroy.test.ts index 75abec603..cf8ccfd5e 100644 --- a/src/core/cleanup/idle-destroy.test.ts +++ b/src/core/cleanup/idle-destroy.test.ts @@ -28,7 +28,7 @@ const config: Config = { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, idle: { deleteAfterMs: 30_000, shutdownAfterMs: 10_000 }, warmPool: { diff --git a/src/core/cleanup/idle-shutdown.test.ts b/src/core/cleanup/idle-shutdown.test.ts index 06e2e5674..77ce7ef13 100644 --- a/src/core/cleanup/idle-shutdown.test.ts +++ b/src/core/cleanup/idle-shutdown.test.ts @@ -26,7 +26,7 @@ const config: Config = { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, idle: { deleteAfterMs: 30_000, shutdownAfterMs: 10_000 }, warmPool: { diff --git a/src/core/config.test.ts b/src/core/config.test.ts index b777a0c51..d9230a995 100644 --- a/src/core/config.test.ts +++ b/src/core/config.test.ts @@ -114,7 +114,7 @@ describe("loadConfig", () => { }, }, stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, }); expect(Object.isFrozen(config)).toBe(true); expect(Object.isFrozen(resourceOptions(config).limits)).toBe(true); @@ -722,49 +722,67 @@ describe("loadConfig", () => { ).rejects.toThrow(path); }); - it("defaults ios.slim to disabled with no categories and a slim boot timeout", async () => { + it("defaults ios.defaultMode to full, and ios.slim to no categories and a slim boot timeout", async () => { const config = await loadConfig({ configPath, filesystem: new MemoryFilesystem(), systemStats: createStats(), }); - expect(config.ios.slim).toEqual({ enabled: false, bootTimeoutMs: 600_000 }); + expect(config.ios.defaultMode).toBe("full"); + expect(config.ios.slim).toEqual({ bootTimeoutMs: 600_000 }); expect(config.ios.slim.categories).toBeUndefined(); expect("categories" in config.ios.slim).toBe(false); }); - it("applies a file-level ios.slim override, including an explicit category list", async () => { + it("applies a file-level ios.defaultMode and ios.slim override, including an explicit category list", async () => { const filesystem = new MemoryFilesystem(); await filesystem.mkdirp("/home/agent/.simlock"); await filesystem.writeFileAtomic( configPath, JSON.stringify({ ios: { - slim: { enabled: true, categories: ["logging", "diagnostics"], bootTimeoutMs: 900_000 }, + defaultMode: "slim", + slim: { categories: ["logging", "diagnostics"], bootTimeoutMs: 900_000 }, }, }), ); const config = await loadConfig({ configPath, filesystem, systemStats: createStats() }); + expect(config.ios.defaultMode).toBe("slim"); expect(config.ios.slim).toEqual({ - enabled: true, categories: ["logging", "diagnostics"], bootTimeoutMs: 900_000, }); }); - it("rejects a non-boolean ios.slim.enabled", async () => { + it.each(["fast", "worker", true])( + "rejects an ios.defaultMode of %j, naming the key", + async (value) => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic(configPath, JSON.stringify({ ios: { defaultMode: value } })); + + await expect( + loadConfig({ configPath, filesystem, systemStats: createStats() }), + ).rejects.toThrow("ios.defaultMode"); + }, + ); + + it("loads a config that still sets the removed ios.slim switch with the unknown-key warning and the full default", async () => { const filesystem = new MemoryFilesystem(); + const warn = vi.fn(); await filesystem.mkdirp("/home/agent/.simlock"); await filesystem.writeFileAtomic( configPath, - JSON.stringify({ ios: { slim: { enabled: "yes" } } }), + JSON.stringify({ ios: { slim: { enabled: true } } }), ); - await expect( - loadConfig({ configPath, filesystem, systemStats: createStats() }), - ).rejects.toThrow("ios.slim.enabled"); + const config = await loadConfig({ configPath, filesystem, systemStats: createStats(), warn }); + + expect(warn).toHaveBeenCalledWith('Unknown config key: "ios.slim.enabled"'); + expect(config.ios.defaultMode).toBe("full"); + expect(config.ios.slim).not.toHaveProperty("enabled"); }); it.each([ @@ -1219,7 +1237,7 @@ describe("loadConfig modes (ADR 0005)", () => { { mode: "gateway", capacity: { strategy: "fixed", config: { maxRunning: 3 } }, - ios: { slim: { enabled: true } }, + ios: { defaultMode: "slim" }, lease: { defaultTtlMs: 60_000 }, }, { warn }, diff --git a/src/core/config.ts b/src/core/config.ts index c93fa7a0c..366c5d784 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -11,7 +11,7 @@ import { type ResourceStrategyOptions, } from "./capacity/index.js"; import { resourceOptionValidators } from "./capacity/strategies/resource/index.js"; -import type { LeaseIdentity } from "./domain.js"; +import type { DeviceMode, LeaseIdentity } from "./domain.js"; import { booleanValue, ConfigError, @@ -196,12 +196,16 @@ export interface Config { readonly maxConcurrentRecoveries: number; }; readonly ios: { + /** + * The device mode a lease request that names none gets on this worker (ADR 0007 §1). + * Default `"full"`. Every worker makes both kinds of device whatever this says. + */ + readonly defaultMode: DeviceMode; + /** How a slim device is made, whatever the default mode is. */ readonly slim: { - /** Opt-in; default false. */ - readonly enabled: boolean; /** Which daemon categories to disable. Undefined means "every category the driver knows". */ readonly categories?: readonly string[]; - /** Boot deadline used while slim mode is on (slim adds a second boot; CI runners are slow). */ + /** Boot deadline for a slim device (slim adds a second boot; CI runners are slow). */ readonly bootTimeoutMs: number; }; }; @@ -636,8 +640,8 @@ function defaultConfig( maxConcurrentRecoveries: 1, }, ios: { + defaultMode: "full", slim: { - enabled: false, bootTimeoutMs: 600_000, }, }, @@ -778,8 +782,8 @@ function configValidators(strategy: CapacityStrategyName): Record }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, }; } diff --git a/src/core/domain.test.ts b/src/core/domain.test.ts index d86b7c2da..09e686c53 100644 --- a/src/core/domain.test.ts +++ b/src/core/domain.test.ts @@ -146,19 +146,13 @@ describe("sameSpec", () => { expect(sameSpec(spec, { ...spec })).toBe(true); }); - it("treats undefined and false full as the same value", () => { - expect(sameSpec(spec, { ...spec, full: false })).toBe(true); - expect(sameSpec({ ...spec, full: false }, spec)).toBe(true); + it("keeps a slim spec apart from the full spec of the same model and runtime", () => { + expect(sameSpec({ ...spec, mode: "slim" }, spec)).toBe(false); + expect(sameSpec(spec, { ...spec, mode: "slim" })).toBe(false); }); - it("fragments a --full spec from a slim (non-full) spec", () => { - expect(sameSpec({ ...spec, full: true }, spec)).toBe(false); - expect(sameSpec(spec, { ...spec, full: true })).toBe(false); - expect(sameSpec({ ...spec, full: true }, { ...spec, full: false })).toBe(false); - }); - - it("matches two full specs", () => { - expect(sameSpec({ ...spec, full: true }, { ...spec, full: true })).toBe(true); + it("matches two slim specs", () => { + expect(sameSpec({ ...spec, mode: "slim" }, { ...spec, mode: "slim" })).toBe(true); }); it("still compares platform, model, and osVersion", () => { diff --git a/src/core/domain.ts b/src/core/domain.ts index 4969840d4..4bf03dd24 100644 --- a/src/core/domain.ts +++ b/src/core/domain.ts @@ -10,26 +10,27 @@ export interface DeviceSpec { readonly model: string; readonly osVersion: string; /** - * Set when this spec was resolved from a `--full` request (see `DeviceRequest.full`): a - * device with no driver-side resource reduction. Part of spec identity (`sameSpec`) so a - * `--full` request never matches, and never shares a pool key with, a slim device -- the - * ADR's "serve from a separate pool key". Never `false`; omitted for every request that did - * not ask for it, so specs stay byte-identical to before this field existed. + * The mode this device is planned to have: `"slim"` for a device its driver will slim, absent + * for a full one (ADR 0007 §6). Only a driver's `resolveSpec` sets it, and only for a slim + * request it will actually slim; `LeaseAcquisitionCoordinator` refuses it on any other request. + * Part of spec identity (`sameSpec`), so slim and full devices never share a pool, and fixed + * for as long as the device exists. The mode the device actually has is `DeviceRecord.mode`. */ - readonly full?: boolean; + readonly mode?: "slim"; } -/** - * Spec identity as every selection path means it: same platform, model, OS version, and - * `full`-ness. `undefined` and `false` compare equal for `full` so registries written before - * this field existed keep matching. - */ +/** The mode a spec plans: `"slim"` when it says so, `"full"` otherwise. */ +export function specMode(spec: DeviceSpec): DeviceMode { + return spec.mode ?? "full"; +} + +/** Spec identity as every selection path means it: same platform, model, OS version, and mode. */ export function sameSpec(left: DeviceSpec, right: DeviceSpec): boolean { return ( left.platform === right.platform && left.model === right.model && left.osVersion === right.osVersion && - (left.full ?? false) === (right.full ?? false) + specMode(left) === specMode(right) ); } diff --git a/src/core/driver.ts b/src/core/driver.ts index 2ec1fddc8..6ea95c8e1 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -8,12 +8,11 @@ export interface DeviceRequest { readonly model: string; readonly osVersion?: string; /** - * Platform-neutral request for a device with no driver-side resource reduction -- the - * iOS driver happens to implement this as "do not slim"; other drivers ignore it. Never - * read by the core beyond stamping it onto the resolved spec (see `DeviceSpec.full` and - * the comment where `LeaseAcquisitionCoordinator` does that stamping). + * The device mode the request asked for; absent when it named none (ADR 0007 §1). Transports + * carry it as it arrived. `LeaseAcquisitionCoordinator` is the one place an absent mode gets + * the worker's default, and a driver's `resolveSpec` always receives it resolved. */ - readonly full?: boolean; + readonly mode?: DeviceMode; } export interface DriverDevice { @@ -195,14 +194,11 @@ export interface Driver { */ revalidateRoot(): Promise; /** - * True when this driver may hand back devices with a reduced feature set (the iOS driver's - * slim mode, when actually enabled), so a caller's `full` request is meaningful and must not - * share a pool key with a normal one. Optional; a driver that never reduces anything -- the - * default, and every non-iOS driver -- omits it, equivalent to `false`. Read once per spec - * resolution by `LeaseAcquisitionCoordinator`, which is the only place `DeviceSpec.full` gets - * stamped onto a resolved spec. + * Resolves a request into the spec a device is planned on. `request.mode` is always set here, + * resolved by the core. A driver returns a spec with `mode: "slim"` only for a slim request it + * will actually slim; for any other request, and for a slim one it cannot slim, it returns a + * full spec (ADR 0007 §4). A driver that does not slim at all never sets the spec's mode. */ - readonly reducesFeatures?: boolean; resolveSpec( request: DeviceRequest, options: { @@ -225,7 +221,7 @@ export interface Driver { */ makeReady( device: DriverDevice, - options?: { + options: { /** * What this readiness call is for. `"prepare"` (the default) may do work that changes * the device's configuration -- a fresh boot, a driver's own opt-in configuration pass @@ -236,6 +232,12 @@ export interface Driver { * do not apply anything new". */ readonly purpose: "prepare" | "recover"; + /** + * The mode the device's spec plans (`specMode`). The registry is the only record of it + * (ADR 0007 §7): a driver keeps no copy and reads it from here on every boot. A + * `"recover"` boot still applies nothing new, whatever this says. + */ + readonly mode: DeviceMode; }, ): Promise; reclaim( diff --git a/src/core/fake-driver.test.ts b/src/core/fake-driver.test.ts index 1db4a53c6..ef61d7a1f 100644 --- a/src/core/fake-driver.test.ts +++ b/src/core/fake-driver.test.ts @@ -97,6 +97,29 @@ describe("FakeDriver", () => { }); }); + it.each([ + ["a prepare boot of a slim-spec device", { mode: "slim", purpose: "prepare" }, "slim"], + ["a recover boot of a slim-spec device", { mode: "slim", purpose: "recover" }, "full"], + ["a prepare boot of a full-spec device", { mode: "full", purpose: "prepare" }, "full"], + ] as const)( + "a slimming fake reports the mode the iOS driver would for %s", + async (_label, options, reported) => { + const driver = new FakeDriver({ + availableOsVersions: ["26.5"], + clock: new FakeClock(), + platform: "ios", + slimmableOsVersions: ["26.5"], + }); + const device = await driver.provision({ + model: "iPhone 16", + osVersion: "26.5", + platform: "ios", + }); + + await expect(driver.makeReady(device, options)).resolves.toMatchObject({ mode: reported }); + }, + ); + it("keeps makeReady pending until released when instructed to hang", async () => { const driver = new FakeDriver({ clock: new FakeClock(), platform: "ios" }); const device = await driver.provision({ @@ -107,7 +130,7 @@ describe("FakeDriver", () => { driver.hangMakeReady(); let ready = false; - const makeReady = driver.makeReady(device).then(() => { + const makeReady = driver.makeReady(device, prepare).then(() => { ready = true; }); @@ -133,7 +156,7 @@ describe("FakeDriver", () => { }); let ready = false; - const makeReady = driver.makeReady(device).then(() => { + const makeReady = driver.makeReady(device, prepare).then(() => { ready = true; }); clock.advance(49); @@ -242,3 +265,5 @@ describe("FakeDriver", () => { expect(await new FakeDriver(options).listCatalog()).not.toHaveProperty("images"); }); }); + +const prepare = { mode: "full", purpose: "prepare" } as const; diff --git a/src/core/fake-driver.ts b/src/core/fake-driver.ts index 804c3d7fd..704cf5e63 100644 --- a/src/core/fake-driver.ts +++ b/src/core/fake-driver.ts @@ -51,11 +51,17 @@ export interface FakeDriverOptions { */ readonly fullCleanReclaimEstimateMs?: number; /** - * The `DriverDevice.mode` `makeReady` reports for every boot -- undefined by default (this - * fake, like every real driver except iOS, does not slim anything), settable by a test that - * needs to exercise the core's `mode` persistence without a real iOS driver. + * The `DriverDevice.mode` `makeReady` reports for every boot, overriding what it would + * otherwise report -- settable by a test that needs a slim pass that did not happen, or the + * core's `mode` persistence without a real iOS driver. */ readonly mode?: DeviceMode | undefined; + /** + * The OS versions this fake can slim. A slim request on one of them resolves to a slim spec, + * and a prepare boot of a slim-spec device reports `"slim"`. Absent or empty: this fake knows + * nothing of modes, like every real driver but iOS, and every request resolves to a full spec. + */ + readonly slimmableOsVersions?: readonly string[]; readonly knownModels?: readonly string[]; /** * What `listCatalog` reports a model pairs with. A model left out pairs with every available @@ -92,13 +98,6 @@ export interface FakeDriverOptions { readonly legacyDevices?: Readonly>; readonly reclaimResult?: "ready" | "shutdown"; readonly reclaimStrategy?: "erase" | "snapshot" | "wipe"; - /** - * `Driver.reducesFeatures` passthrough -- undefined by default (this fake, like every real - * driver except iOS with slim mode on, does not reduce anything), settable by a test that - * needs to exercise `LeaseAcquisitionCoordinator`'s `full`-stamping decision without a real - * iOS driver. - */ - readonly reducesFeatures?: boolean; } export class FakeDriverUnknownDeviceError extends Error { @@ -111,13 +110,13 @@ export class FakeDriverUnknownDeviceError extends Error { export class FakeDriver implements Driver { readonly platform: Platform; readonly deviceRoot: string; - readonly reducesFeatures?: boolean; readonly #availableOsVersions: Set; readonly #callCounts = new Map(); readonly #calls: FakeDriverCall[] = []; readonly #clock: Clock; readonly #estimateMs: FakeDriverOptions["estimateMs"]; readonly #mode: DeviceMode | undefined; + readonly #slimmableOsVersions: ReadonlySet; readonly #fullCleanReclaimEstimateMs: number | undefined; readonly #failures = new Map(); #hangMakeReady = false; @@ -146,6 +145,7 @@ export class FakeDriver implements Driver { this.#clock = options.clock; this.#estimateMs = options.estimateMs; this.#mode = options.mode; + this.#slimmableOsVersions = new Set(options.slimmableOsVersions ?? []); this.#fullCleanReclaimEstimateMs = options.fullCleanReclaimEstimateMs; this.#knownModels = options.knownModels === undefined ? undefined : new Set(options.knownModels); @@ -159,10 +159,6 @@ export class FakeDriver implements Driver { this.#passthrough = options.passthrough; this.platform = options.platform; this.deviceRoot = options.deviceRoot ?? `/fake/${options.platform}`; - - if (options.reducesFeatures !== undefined) { - this.reducesFeatures = options.reducesFeatures; - } this.#reclaimResult = options.reclaimResult ?? "ready"; this.#reclaimStrategy = options.reclaimStrategy ?? "wipe"; } @@ -212,7 +208,14 @@ export class FakeDriver implements Driver { this.#availableOsVersions.add(osVersion); } - return { model: request.model, osVersion, platform: this.platform }; + return { + model: request.model, + osVersion, + platform: this.platform, + ...(request.mode === "slim" && this.#slimmableOsVersions.has(osVersion) + ? { mode: "slim" as const } + : {}), + }; } async provision(spec: DeviceSpec): Promise { @@ -228,13 +231,13 @@ export class FakeDriver implements Driver { /** * Each boot re-reads a fresh address, same as the real drivers -- never the caller's. - * `options.purpose` is recorded on the call log (`calls`) so a test can assert a caller (e.g. - * `ManagedDeviceLifecycle.recoverLeased`) requested `"recover"`, but this fake never reduces - * anything regardless of purpose -- there is no configuration-changing behaviour to gate. + * `options` is recorded on the call log (`calls`) so a test can assert what a caller passed. + * A slimming fake (`slimmableOsVersions`) reports `"slim"` for a prepare boot of a slim-spec + * device and nothing on a recover boot, as the iOS driver does; the `mode` option overrides it. */ async makeReady( device: DriverDevice, - options?: { readonly purpose: "prepare" | "recover" }, + options: { readonly purpose: "prepare" | "recover"; readonly mode: DeviceMode }, ): Promise { await this.#beforeCall("makeReady", device, options); this.#requireDevice(device); @@ -252,10 +255,18 @@ export class FakeDriver implements Driver { address: addressFor(device.deviceId, bootCount), deviceId: device.deviceId, driverData: device.driverData, - ...(this.#mode === undefined ? {} : { mode: this.#mode }), + ...this.#reportedMode(options), }; } + #reportedMode(options: { readonly purpose: "prepare" | "recover"; readonly mode: DeviceMode }): { + readonly mode?: DeviceMode; + } { + if (this.#mode !== undefined) return { mode: this.#mode }; + if (this.#slimmableOsVersions.size === 0) return {}; + return { mode: options.mode === "slim" && options.purpose === "prepare" ? "slim" : "full" }; + } + async reclaim( device: DriverDevice, options: { readonly clean: "standard" | "full" }, diff --git a/src/core/lease-acquisition-coordinator.test.ts b/src/core/lease-acquisition-coordinator.test.ts index dbf20da21..05da0449c 100644 --- a/src/core/lease-acquisition-coordinator.test.ts +++ b/src/core/lease-acquisition-coordinator.test.ts @@ -15,8 +15,8 @@ import type { Config } from "./config.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; import { DeviceProvisioner } from "./device-provisioner.js"; import { DriverCatalog } from "./driver-catalog.js"; -import { DriverCrashError } from "./driver.js"; -import type { DeviceSpec } from "./domain.js"; +import { type Driver, DriverCrashError, readyTransitionUpdate } from "./driver.js"; +import { type DeviceMode, type DeviceSpec, type Platform, specMode } from "./domain.js"; import { FakeDriver } from "./fake-driver.js"; import { LeaseAcquisitionCoordinator, NoCapacityError } from "./lease-acquisition-coordinator.js"; import { LeaseExpiryScheduler } from "./lease-expiry-scheduler.js"; @@ -50,7 +50,7 @@ function config(maxDevices = 1): Config { downloads: { acceptAndroidLicenses: false, policy: "on-request", timeoutMs: 1_200_000 }, eventBuffer: { capacity: 100 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, health: { enabled: true, @@ -95,7 +95,8 @@ function config(maxDevices = 1): Config { async function createHarness( options: { - readonly drivers?: readonly FakeDriver[]; + readonly defaultModes?: Readonly>>; + readonly drivers?: readonly Driver[]; readonly logger?: Logger; readonly maxDevices?: number; } = {}, @@ -103,7 +104,7 @@ async function createHarness( const clock = new FakeClock(1_000); const bus = new EventBus(clock); const driver = - options.drivers?.[0] ?? + (options.drivers?.[0] as FakeDriver | undefined) ?? new FakeDriver({ clock, platform: "ios", availableOsVersions: ["26.5"] }); const drivers = options.drivers ?? [driver]; let nextId = 0; @@ -150,6 +151,7 @@ async function createHarness( coordinator = new LeaseAcquisitionCoordinator({ claims, decisions, + defaultModes: options.defaultModes ?? {}, drivers: catalog, eventBus: bus, leases, @@ -183,11 +185,16 @@ async function seedReady( provisionDuration: 0, spec, }); - await harness.driver.makeReady(driverDevice); - return harness.registry.transitionDevice(provisioned.id, "ready", { - event: "device.ready", - payload: { bootDuration: 0, deviceId: provisioned.id }, + const ready = await harness.driver.makeReady(driverDevice, { + mode: specMode(spec), + purpose: "prepare", }); + return harness.registry.transitionDevice( + provisioned.id, + "ready", + { event: "device.ready", payload: { bootDuration: 0, deviceId: provisioned.id } }, + readyTransitionUpdate(ready), + ); } async function flush(): Promise { @@ -593,69 +600,142 @@ describe("LeaseAcquisitionCoordinator", () => { ).resolves.toMatchObject({ lease: { ownerId: "reopened", requesterId: "reopened" } }); }); - it("stamps full: true onto the resolved spec centrally for a --full request against a driver that reduces features", async () => { - const harness = await createHarness({ - drivers: [ - new FakeDriver({ - availableOsVersions: ["26.5"], - clock: new FakeClock(1_000), - platform: "ios", - reducesFeatures: true, - }), - ], - }); - const granted = await harness.coordinator.request( - { ...request, full: true }, - { ownerId: "agent", requesterId: "agent" }, + describe("device mode", () => { + /** A driver that slims 26.5 and cannot slim 17.5, like iOS on either side of 18.5. */ + function slimmingDriver(options: { readonly mode?: DeviceMode } = {}): FakeDriver { + return new FakeDriver({ + availableOsVersions: ["17.5", "26.5"], + clock: new FakeClock(1_000), + platform: "ios", + slimmableOsVersions: ["26.5"], + ...options, + }); + } + + const owner = (id: string) => ({ ownerId: id, requesterId: id }); + + it.each([ + ["full", "no mode", undefined, "full"], + ["slim", "no mode", undefined, "slim"], + ["full", "mode slim", "slim", "slim"], + ["slim", "mode full", "full", "full"], + ] as const)( + "on a worker whose default is %s, a request with %s gets that device mode", + async (defaultMode, _label, mode, planned) => { + const harness = await createHarness({ + defaultModes: { ios: defaultMode }, + drivers: [slimmingDriver()], + }); + + const granted = await harness.coordinator.request( + { ...request, ...(mode === undefined ? {} : { mode }) }, + owner("agent"), + ); + + expect(specMode(granted.device.spec)).toBe(planned); + expect(granted.device.mode).toBe(planned); + }, ); - expect(granted.device.spec).toMatchObject({ full: true }); - }); + it("passes the resolved mode to resolveSpec, the default filled in for a request that named none", async () => { + const driver = slimmingDriver(); + const harness = await createHarness({ defaultModes: { ios: "slim" }, drivers: [driver] }); - it("never stamps full: false onto a spec for a plain request", async () => { - const harness = await createHarness(); - const granted = await harness.coordinator.request(request, { - requesterId: "agent", - ownerId: "agent", + await harness.coordinator.request(request, owner("agent")); + + const resolved = driver.calls.find((call) => call.operation === "resolveSpec"); + expect(resolved?.arguments[0]).toMatchObject({ mode: "slim" }); }); - expect(granted.device.spec).not.toHaveProperty("full"); - }); + it("never plans a full request onto a slim spec, even when the driver's resolveSpec returns one", async () => { + class AlwaysSlimDriver extends FakeDriver { + override async resolveSpec( + ...args: Parameters + ): Promise { + return { ...(await super.resolveSpec(...args)), mode: "slim" }; + } + } + const driver = new AlwaysSlimDriver({ + availableOsVersions: ["26.5"], + clock: new FakeClock(1_000), + platform: "ios", + }); + const harness = await createHarness({ drivers: [driver] }); + + const granted = await harness.coordinator.request( + { ...request, mode: "full" }, + owner("agent"), + ); - it("keeps a --full request from matching a warm slim device of the same spec, against a driver that reduces features", async () => { - const harness = await createHarness({ - drivers: [ - new FakeDriver({ - availableOsVersions: ["26.5"], - clock: new FakeClock(1_000), - platform: "ios", - reducesFeatures: true, - }), - ], - maxDevices: 2, + expect(granted.device.spec).not.toHaveProperty("mode"); + const provisioned = driver.calls.find((call) => call.operation === "provision"); + expect(provisioned?.arguments[0]).not.toHaveProperty("mode"); }); - await seedReady(harness, request); - const granted = await harness.coordinator.request( - { ...request, full: true }, - { ownerId: "agent", requesterId: "agent" }, - ); + it("does not give a full request an idle slim device of the same model and runtime", async () => { + const harness = await createHarness({ drivers: [slimmingDriver()], maxDevices: 2 }); + const slim = await seedReady(harness, { ...request, mode: "slim" }); - // A fresh device was provisioned rather than the warm slim one being handed out. - expect(granted.device.spec).toMatchObject({ full: true }); - expect(harness.driver.calls.filter((call) => call.operation === "provision")).toHaveLength(2); - }); + const granted = await harness.coordinator.request( + { ...request, mode: "full" }, + owner("agent"), + ); - it("never stamps full: true onto a spec when the resolving driver does not reduce features, so a --full request produces a spec identical to a normal one", async () => { - const harness = await createHarness(); + expect(granted.device.id).not.toBe(slim.id); + expect(granted.device.mode).toBe("full"); + }); - const fullRequest = await harness.coordinator.request( - { ...request, full: true }, - { ownerId: "agent-full", requesterId: "agent-full" }, - ); + it("does not give a slim request an idle full device of the same model and runtime", async () => { + const harness = await createHarness({ drivers: [slimmingDriver()], maxDevices: 2 }); + const full = await seedReady(harness, request); + + const granted = await harness.coordinator.request( + { ...request, mode: "slim" }, + owner("agent"), + ); + + expect(granted.device.id).not.toBe(full.id); + expect(granted.device.mode).toBe("slim"); + }); + + it("resolves a slim request on a runtime the driver cannot slim to the full spec, reusing an idle full device", async () => { + const oldRuntime = { ...request, osVersion: "17.5" }; + const harness = await createHarness({ drivers: [slimmingDriver()] }); + const full = await seedReady(harness, oldRuntime); + + const granted = await harness.coordinator.request( + { ...oldRuntime, mode: "slim" }, + owner("agent"), + ); - expect(fullRequest.device.spec).not.toHaveProperty("full"); - expect(fullRequest.device.spec).toEqual(request); + expect(granted.device.id).toBe(full.id); + expect(granted.device.spec).toEqual(oldRuntime); + expect(granted.device.mode).toBe("full"); + }); + + it("grants a slim request against a driver that knows nothing of modes a full device", async () => { + const harness = await createHarness(); + + const granted = await harness.coordinator.request( + { ...request, mode: "slim" }, + owner("agent"), + ); + + expect(granted.device.spec).toEqual(request); + expect(granted.device.mode).toBe("full"); + }); + + it("grants a slim-spec device whose slim pass failed as full, and keeps it in the slim pool", async () => { + const harness = await createHarness({ drivers: [slimmingDriver({ mode: "full" })] }); + + const granted = await harness.coordinator.request( + { ...request, mode: "slim" }, + owner("agent"), + ); + + expect(granted.device.mode).toBe("full"); + expect(granted.device.spec).toEqual({ ...request, mode: "slim" }); + }); }); it("A failed eviction shutdown logs the device id and the error, and the waiter is deferred as before.", async () => { diff --git a/src/core/lease-acquisition-coordinator.ts b/src/core/lease-acquisition-coordinator.ts index f8c8853ad..eb198d95e 100644 --- a/src/core/lease-acquisition-coordinator.ts +++ b/src/core/lease-acquisition-coordinator.ts @@ -8,7 +8,14 @@ import { } from "./device-operation-claims.js"; import { type DeviceProvisioner } from "./device-provisioner.js"; import { type LeaseRequestBook } from "./lease-request-book.js"; -import { type DeviceRecord, type DeviceSpec, type LeaseRecord, sameSpec } from "./domain.js"; +import { + type DeviceMode, + type DeviceRecord, + type DeviceSpec, + type LeaseRecord, + type Platform, + sameSpec, +} from "./domain.js"; import { BootTimeoutError, type DeviceRequest, type Driver } from "./driver.js"; import { type DriverCatalog } from "./driver-catalog.js"; import { type LeaseLifecycle } from "./lease-lifecycle.js"; @@ -82,6 +89,11 @@ export type AcquisitionQueue = Pick< export interface LeaseAcquisitionCoordinatorOptions { readonly claims: AcquisitionClaims; readonly decisions: AcquisitionDecision; + /** + * The worker's default device mode per platform, built from config at the composition root + * (ADR 0007 §2). A platform it does not name defaults to `"full"`. + */ + readonly defaultModes: Readonly>>; readonly drivers: AcquisitionDrivers; readonly eventBus: Pick; readonly leases: Pick; @@ -253,29 +265,22 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { return; } try { - const resolved = await driver.resolveSpec(request, { - allowDownload: options.allowDownload ?? false, - // The waiter is the one place that knows which requester triggered this resolution; - // threaded through so a component install a driver ends up doing on this request's - // behalf can attribute its diagnostics (and the resulting `component.install-*` events) - // to it. - requesterId: options.requesterId, - }); - // This is the single place a driver's `resolveSpec` result becomes the spec the core - // matches and provisions on -- so `full` is stamped on centrally here, rather than any - // driver having to know about the flag (architecture rule 3: drivers stay unaware of - // core-only request flags). Never stamped `false`; omitted when the request did not ask - // for it, so specs stay byte-identical to every request that predates this flag. Also - // omitted when the resolving driver doesn't declare `reducesFeatures` (finding #6, issue - // #87 review): a `full` request only means something -- and only earns its own pool key, - // never shared with a normal request's (`sameSpec`) -- against a driver that might - // otherwise hand back a reduced device. Stamping it regardless would fragment a platform - // like Android, which never reduces anything, into two identical pools for no behavioural - // difference. - waiter.spec = - request.full === true && driver.reducesFeatures === true - ? { ...resolved, full: true } - : resolved; + // The one place a request with no mode gets the worker's default (ADR 0007 §2). + const mode = request.mode ?? this.options.defaultModes[request.platform] ?? "full"; + const resolved = await driver.resolveSpec( + { ...request, mode }, + { + allowDownload: options.allowDownload ?? false, + // The waiter is the one place that knows which requester triggered this resolution; + // threaded through so a component install a driver ends up doing on this request's + // behalf can attribute its diagnostics (and the resulting `component.install-*` events) + // to it. + requesterId: options.requesterId, + }, + ); + // Full is a guarantee (ADR 0007 §5): a slim spec is accepted only for a slim request, so a + // driver that returns the wrong thing still cannot put a full request on a slim device. + waiter.spec = mode === "slim" ? resolved : fullSpec(resolved); } catch (error: unknown) { await this.options.decisions.run(async () => { this.#reject(waiter, asError(error), "unresolvable-spec"); @@ -737,3 +742,10 @@ function operationPlan(plan: AcquisitionPlan): OperationPlan | undefined { ? undefined : plan; } + +/** The spec without a planned mode: the full spec of the same model and runtime. */ +function fullSpec(spec: DeviceSpec): DeviceSpec { + if (spec.mode === undefined) return spec; + const { mode: _mode, ...full } = spec; + return full; +} diff --git a/src/core/lease-engine.test.ts b/src/core/lease-engine.test.ts index fd01bd64c..e125ecb05 100644 --- a/src/core/lease-engine.test.ts +++ b/src/core/lease-engine.test.ts @@ -42,7 +42,7 @@ function config(overrides: Partial = {}): Config { downloads: { acceptAndroidLicenses: false, policy: "on-request", timeoutMs: 1_200_000 }, eventBuffer: { capacity: 100 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, health: { enabled: true, @@ -1718,7 +1718,10 @@ describe("LeaseEngine fresh lease identity (#75)", () => { leaseIdentity: freshIos, statePath, }); - const driverDevice = await driver.makeReady(await driver.provision(request)); + const driverDevice = await driver.makeReady(await driver.provision(request), { + mode: "full", + purpose: "prepare", + }); const device = await crashed.registerDevice({ driverData: driverDevice.driverData, driverDeviceId: driverDevice.deviceId, diff --git a/src/core/lease-engine.ts b/src/core/lease-engine.ts index 88f279114..9fad23782 100644 --- a/src/core/lease-engine.ts +++ b/src/core/lease-engine.ts @@ -9,6 +9,7 @@ import type { Proposal } from "./cleanup/types.js"; import { DeviceOperationClaims } from "./device-operation-claims.js"; import { DeviceProvisioner } from "./device-provisioner.js"; import type { + DeviceMode, LeaseGrant as StoredLeaseGrant, LeaseRecord, LeaseRequestFailure, @@ -57,6 +58,11 @@ export interface LeaseEngineOptions { * failure is stored as `INTERNAL` with its own message. */ readonly describeFailure?: (error: unknown) => LeaseRequestFailure; + /** + * The worker's default device mode per platform, built from config by the composition root + * (ADR 0007 §2). Omitted, or silent on a platform, means `"full"`. + */ + readonly defaultModes?: Readonly>>; } export { @@ -158,6 +164,7 @@ export class LeaseEngine { this.#acquisition = new LeaseAcquisitionCoordinator({ claims: this.#claims, decisions: this.#decisions, + defaultModes: options.defaultModes ?? {}, drivers: this.#drivers, eventBus: options.eventBus, leases: this.#leases, diff --git a/src/core/lease-health-monitor.test.ts b/src/core/lease-health-monitor.test.ts index 33e86a70d..a30c2dba3 100644 --- a/src/core/lease-health-monitor.test.ts +++ b/src/core/lease-health-monitor.test.ts @@ -69,7 +69,7 @@ function config(overrides: Partial = {}): Config { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, }; } diff --git a/src/core/lease-request-book.test.ts b/src/core/lease-request-book.test.ts index 0e3804506..cca482466 100644 --- a/src/core/lease-request-book.test.ts +++ b/src/core/lease-request-book.test.ts @@ -203,6 +203,58 @@ describe("Registry lease requests", () => { expect(devices[1]?.[1]).toMatchObject({ mode: "slim" }); }); + it("drops a full key stored before ADR 0007 from a request and from its grant's device spec, and does not write it back", async () => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + const spec = { model: "iPhone 16", osVersion: "26.5", platform: "ios" }; + await filesystem.writeFileAtomic( + statePath, + JSON.stringify({ + devices: [], + leaseRequests: [ + { + createdAt: 1_000, + grant: { + device: { + driverDeviceId: "udid", + id: "dev_1", + mode: "full", + spec: { ...spec, full: true }, + }, + environment: {}, + lease: { id: "lse_1" }, + timing: {}, + }, + id: "req_legacy", + ownerId: "agent", + request: { ...request, full: true }, + requesterId: "agent", + settledAt: 1_000, + state: "granted", + }, + ], + leases: [], + }), + ); + + const { registry } = await loadRegistry({ filesystem }); + const [loaded] = registry.leaseRequests(); + expect(loaded?.request).toEqual(request); + expect(loaded?.grant?.device.spec).toEqual(spec); + + await registry.createLeaseRequest(newRequest("other")); + const written = JSON.parse(await filesystem.readFile(statePath)) as { + readonly leaseRequests: readonly { + readonly id: string; + readonly request: unknown; + readonly grant?: { readonly device: { readonly spec: unknown } }; + }[]; + }; + const stored = written.leaseRequests.find((record) => record.id === "req_legacy"); + expect(stored?.request).toEqual(request); + expect(stored?.grant?.device.spec).toEqual(spec); + }); + it("settles every open record as failed, leaving settled ones alone", async () => { const { registry } = await loadRegistry(); const open = await registry.createLeaseRequest(newRequest("open")); @@ -243,7 +295,7 @@ describe("Registry lease-request load", () => { it.each([ ["a failed record whose failure has no code", { failure: { message: "x" }, state: "failed" }], ["a settled record without its settlement time", { settledAt: undefined, state: "cancelled" }], - ["a request whose full is not a boolean", { request: { ...request, full: "yes" } }], + ["a request whose mode is neither slim nor full", { request: { ...request, mode: "fast" } }], ])("drops %s and loads the rest", async (_label, broken) => { const { registry } = await loadWith([ { ...valid, id: "req_broken", settledAt: 1_000, ...broken }, @@ -305,7 +357,7 @@ describe("LeaseRequestBook", () => { it.each([ ["a different osVersion", { ...request, osVersion: "18.0" }], ["no osVersion where one was named", { model: request.model, platform: request.platform }], - ["full where none was asked", { ...request, full: true }], + ["a mode where none was named", { ...request, mode: "full" as const }], ])("refuses a repeat naming %s as an idempotency conflict", async (_label, different) => { const book = bookOver(memoryStore()); await book.admit(request, keyed, () => granted("lse_1")); @@ -314,12 +366,12 @@ describe("LeaseRequestBook", () => { expect(() => book.replay(different, keyed)).toThrow(IdempotencyConflictError); }); - it("treats full: false and an omitted full as the same request", async () => { + it("replays a repeat naming the same mode", async () => { const book = bookOver(memoryStore()); - await book.admit(request, keyed, () => granted("lse_1")); + await book.admit({ ...request, mode: "slim" }, keyed, () => granted("lse_1")); await settled(); - await expect(book.replay({ ...request, full: false }, keyed)).resolves.toEqual({ + await expect(book.replay({ ...request, mode: "slim" }, keyed)).resolves.toEqual({ lease: { id: "lse_1" }, }); }); diff --git a/src/core/lease-request-book.ts b/src/core/lease-request-book.ts index b9da1ef5b..59663fbae 100644 --- a/src/core/lease-request-book.ts +++ b/src/core/lease-request-book.ts @@ -434,14 +434,14 @@ function storedResult(record: LeaseRequestRecord): Promise /** * Whether two requests name the same device: what an idempotency key promises not to change. An - * omitted `osVersion` and an omitted `full` compare equal to themselves only -- `full: false` and - * omitted are the same request. + * omitted `osVersion` and an omitted `mode` compare equal to themselves only: a request that + * named no mode is not the same request as one that named the worker's default. */ function sameDeviceRequest(left: DeviceRequest, right: DeviceRequest): boolean { return ( left.platform === right.platform && left.model === right.model && left.osVersion === right.osVersion && - (left.full ?? false) === (right.full ?? false) + left.mode === right.mode ); } diff --git a/src/core/managed-device-lifecycle.test.ts b/src/core/managed-device-lifecycle.test.ts index 4b15ffe2b..a186d0dec 100644 --- a/src/core/managed-device-lifecycle.test.ts +++ b/src/core/managed-device-lifecycle.test.ts @@ -47,11 +47,14 @@ async function createHarness() { } async function readyDevice(harness: Awaited>) { - await harness.driver.makeReady({ - address: harness.device.address ?? "", - deviceId: harness.device.driverDeviceId, - driverData: harness.device.driverData, - }); + await harness.driver.makeReady( + { + address: harness.device.address ?? "", + deviceId: harness.device.driverDeviceId, + driverData: harness.device.driverData, + }, + { mode: "full", purpose: "prepare" }, + ); return harness.registry.transitionDevice(harness.device.id, "ready", { event: "device.ready", payload: { bootDuration: 0, deviceId: harness.device.id }, @@ -363,7 +366,7 @@ describe("ManagedDeviceLifecycle", () => { const recoveryCall = harness.driver.calls.filter((call) => call.operation === "makeReady")[ harness.driver.calls.filter((call) => call.operation === "makeReady").length - 1 ]; - expect(recoveryCall?.arguments[1]).toEqual({ purpose: "recover" }); + expect(recoveryCall?.arguments[1]).toEqual({ mode: "full", purpose: "recover" }); }); }); @@ -605,4 +608,86 @@ describe("ManagedDeviceLifecycle", () => { expect(handoff?.device.mode).toBe("full"); }); + + describe("device mode on makeReady", () => { + const slimSpec = { + mode: "slim", + model: "iPhone 16", + osVersion: "26.5", + platform: "ios", + } as const; + + async function slimHarness() { + const clock = new FakeClock(1_000); + const eventBus = new EventBus(clock); + const driver = new FakeDriver({ clock, platform: "ios", slimmableOsVersions: ["26.5"] }); + let nextId = 0; + const registry = await Registry.load({ + clock, + eventBus, + filesystem: new MemoryFilesystem(), + idGenerator: { generate: () => `${nextId++}` }, + statePath, + }); + const claims = new DeviceOperationClaims(); + const lifecycle = new ManagedDeviceLifecycle( + new DriverCatalog([driver]), + registry, + new SerializedDecision(), + claims, + clock, + ); + const driverDevice = await driver.provision(slimSpec); + const device = await registry.registerDevice({ + driverData: driverDevice.driverData, + driverDeviceId: driverDevice.deviceId, + provisionDuration: 0, + spec: slimSpec, + }); + return { claims, device, driver, lifecycle, registry }; + } + + function makeReadyOptions(driver: FakeDriver): readonly unknown[] { + return driver.calls + .filter((call) => call.operation === "makeReady") + .map((call) => call.arguments[1]); + } + + it("passes a slim spec's mode to makeReady on a prepare boot, from provisioning and from shutdown", async () => { + const harness = await slimHarness(); + + const ready = await harness.lifecycle.readyProvisioned(harness.device); + if (ready === undefined) throw new Error("expected a ready device"); + await harness.lifecycle.shutdown(ready, "test", "cleanup"); + const shutdown = harness.registry.snapshot.devices[0]; + if (shutdown === undefined) throw new Error("expected the device"); + const claim = harness.claims.tryClaim(shutdown.id, "boot"); + if (claim === undefined) throw new Error("expected boot claim"); + const handoff = await harness.lifecycle.bootForLease(shutdown, claim); + + expect(makeReadyOptions(harness.driver)).toEqual([ + { mode: "slim", purpose: "prepare" }, + { mode: "slim", purpose: "prepare" }, + ]); + expect(ready.mode).toBe("slim"); + expect(handoff?.device.mode).toBe("slim"); + }); + + it("passes a slim spec's mode on a recovery boot too, under purpose recover", async () => { + const harness = await slimHarness(); + const ready = await harness.lifecycle.readyProvisioned(harness.device); + if (ready === undefined) throw new Error("expected a ready device"); + const lease = await harness.registry.createLease({ + deviceId: ready.id, + ownerId: "agent", + requesterId: "agent", + ttlDeadline: 10_000, + ttlMs: 60_000, + }); + + await harness.lifecycle.recoverLeased(ready, lease.id); + + expect(makeReadyOptions(harness.driver).at(-1)).toEqual({ mode: "slim", purpose: "recover" }); + }); + }); }); diff --git a/src/core/managed-device-lifecycle.ts b/src/core/managed-device-lifecycle.ts index 613ad84b0..e8b542587 100644 --- a/src/core/managed-device-lifecycle.ts +++ b/src/core/managed-device-lifecycle.ts @@ -4,7 +4,13 @@ import { type DeviceOperation, type DeviceOperationClaim, } from "./device-operation-claims.js"; -import type { DeviceRecord, DeviceState, DeviceTransitionUpdate, LeaseRecord } from "./domain.js"; +import { + type DeviceRecord, + type DeviceState, + type DeviceTransitionUpdate, + type LeaseRecord, + specMode, +} from "./domain.js"; import { readyTransitionUpdate, type DriverDevice } from "./driver.js"; import { DriverCatalog } from "./driver-catalog.js"; import { SerializedDecision } from "./serialized-decision.js"; @@ -138,8 +144,7 @@ export class ManagedDeviceLifecycle { * and emits no event, deliberately -- the caller (a `LeaseHealthMonitor`) * owns deciding what happened and telling the holder. * - * Calls `makeReady` with `{ purpose: "recover" }` (see `Driver.makeReady`), never the - * default: safety rule 2 permits this exception to reboot an already-provisioned device and + * Calls `makeReady` with `purpose: "recover"` (see `Driver.makeReady`), never `"prepare"`: safety rule 2 permits this exception to reboot an already-provisioned device and * nothing more, so a driver must not use this reboot to apply any configuration change (the * iOS driver's slim pass) it would otherwise make on a normal `"prepare"` boot -- that would * be a second, unannounced reboot and a configuration change under an active lease, which is @@ -160,7 +165,10 @@ export class ManagedDeviceLifecycle { // still using the address from its original grant. await this.catalog .get(claimed.device.spec.platform) - .makeReady(toDriverDevice(claimed.device), { purpose: "recover" }); + .makeReady(toDriverDevice(claimed.device), { + mode: specMode(claimed.device.spec), + purpose: "recover", + }); } catch (error: unknown) { await this.#release(claimed); throw error; @@ -228,7 +236,10 @@ export class ManagedDeviceLifecycle { try { ready = await this.catalog .get(claimed.device.spec.platform) - .makeReady(toDriverDevice(claimed.device)); + .makeReady(toDriverDevice(claimed.device), { + mode: specMode(claimed.device.spec), + purpose: "prepare", + }); } catch (error: unknown) { await this.#release(claimed); throw error; @@ -258,7 +269,10 @@ export class ManagedDeviceLifecycle { try { ready = await this.catalog .get(claimed.device.spec.platform) - .makeReady(toDriverDevice(claimed.device)); + .makeReady(toDriverDevice(claimed.device), { + mode: specMode(claimed.device.spec), + purpose: "prepare", + }); } catch (error: unknown) { await this.#release(claimed); throw error; diff --git a/src/core/nuke.test.ts b/src/core/nuke.test.ts index bb9eaae45..c60cb8fb3 100644 --- a/src/core/nuke.test.ts +++ b/src/core/nuke.test.ts @@ -167,7 +167,7 @@ function config(): Config { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, idle: { deleteAfterMs: 10, shutdownAfterMs: 5 }, lease: { diff --git a/src/core/reaper.test.ts b/src/core/reaper.test.ts index 1057132ae..3e6326584 100644 --- a/src/core/reaper.test.ts +++ b/src/core/reaper.test.ts @@ -73,7 +73,7 @@ function config(): Config { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, idle: { deleteAfterMs: 30_000, shutdownAfterMs: 10_000 }, lease: { diff --git a/src/core/registry.test.ts b/src/core/registry.test.ts index d8f1a69f3..073d099d9 100644 --- a/src/core/registry.test.ts +++ b/src/core/registry.test.ts @@ -928,6 +928,94 @@ describe("Registry", () => { ).rejects.toThrow("Invalid device record in registry state"); }); + describe("a stored spec's mode", () => { + async function loadDevice(storedSpec: Record) { + const clock = new FakeClock(1_000); + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/agent/.simlock"); + await filesystem.writeFileAtomic( + statePath, + JSON.stringify({ + devices: [ + { + createdAt: 500, + driverData: {}, + driverDeviceId: "driver_stored", + id: "dev_stored", + mode: "full", + spec: storedSpec, + state: "ready", + }, + ], + leases: [], + }), + ); + const load = () => + Registry.load({ + clock, + eventBus: new EventBus(clock), + filesystem, + idGenerator: { generate: () => "new" }, + statePath, + }); + return { filesystem, load }; + } + + it.each([true, false])( + "ignores a stored spec.full of %s and does not write it back", + async (full) => { + const { filesystem, load } = await loadDevice({ ...spec, full }); + const registry = await load(); + + expect(registry.snapshot.devices[0]?.spec).toEqual(spec); + + await registry.registerDevice({ + driverData: {}, + driverDeviceId: "driver_new", + provisionDuration: 0, + spec, + }); + const written = JSON.parse(await filesystem.readFile(statePath)) as { + devices: { id: string; spec: Record }[]; + }; + expect(written.devices.find((device) => device.id === "dev_stored")?.spec).toEqual(spec); + }, + ); + + it("loads a stored slim spec as slim", async () => { + const { load } = await loadDevice({ ...spec, mode: "slim" }); + + expect((await load()).snapshot.devices[0]?.spec).toEqual({ ...spec, mode: "slim" }); + }); + + it.each(["full", "reduced"])("fails the load on a stored spec.mode of %s", async (mode) => { + const { load } = await loadDevice({ ...spec, mode }); + + await expect(load()).rejects.toThrow("Invalid device record in registry state"); + }); + }); + + it("records the planned mode of a slim spec on the device it registers", async () => { + const clock = new FakeClock(1_000); + const registry = await Registry.load({ + clock, + eventBus: new EventBus(clock), + filesystem: new MemoryFilesystem(), + idGenerator: { generate: () => "test" }, + statePath, + }); + + const device = await registry.registerDevice({ + driverData: {}, + driverDeviceId: "driver_test", + provisionDuration: 0, + spec: { ...spec, mode: "slim" }, + }); + + expect(device.spec).toEqual({ ...spec, mode: "slim" }); + expect(device.mode).toBe("full"); + }); + it("clears recovery markers as part of the same commit that ends a lease", async () => { const clock = new FakeClock(1_000); const suffixes = ["device", "lease"]; diff --git a/src/core/registry.ts b/src/core/registry.ts index b1bcd75b3..d2d24f100 100644 --- a/src/core/registry.ts +++ b/src/core/registry.ts @@ -855,7 +855,7 @@ function parseDevice(value: unknown): DeviceRecord { typeof driverDeviceId !== "string" || typeof createdAt !== "number" || !(isDeviceState(state) || state === "warm") || - !isDeviceSpec(spec) || + !isObject(spec) || !("driverData" in value) || // Every other optional field is a number and is swept by // `parseOptionalDeviceNumbers`; `address` is the lone string. Missing is expected of a @@ -874,7 +874,7 @@ function parseDevice(value: unknown): DeviceRecord { id, leaseIdentity: parseLeaseIdentity(value.leaseIdentity), mode: parseDeviceMode(value.mode), - spec, + spec: parseDeviceSpec(spec), state: state === "warm" ? "reclaiming" : state, }; } @@ -901,6 +901,20 @@ function parseDeviceMode(value: unknown): DeviceMode { throw new RegistryLoadError("Invalid device record in registry state"); } +/** + * A spec's planned mode (ADR 0007 §6, §11). A spec written before it existed has none and loads + * as full; its retired `full` key is dropped, so it is not written back. A `mode` other than + * `"slim"` fails the load: no other value can be planned, and guessing could pool a slim device + * with full ones. + */ +function parseDeviceSpec(value: Record): DeviceSpec { + const { full: _retired, ...spec } = value; + if (!isDeviceSpec(spec) || (spec.mode !== undefined && spec.mode !== "slim")) { + throw new RegistryLoadError("Invalid device record in registry state"); + } + return spec; +} + /** * ADR 0003 §4: a lease record written before `ownerId` existed loads with `ownerId` equal to * `requesterId`; present-but-wrong-typed is still corrupt, same treatment as every other @@ -989,7 +1003,7 @@ function parseLeaseRequest(value: unknown): LeaseRequestRecord | undefined { id, ...(idempotencyKey === undefined ? {} : { idempotencyKey }), ownerId, - request, + request: withoutRetiredRequestKeys(request), requesterId, state, ...result, @@ -1039,13 +1053,17 @@ function parseLeaseRequestResult( /** * A stored grant's device follows the device record's own load rule (ADR 0007 §11): no `mode` - * loads as `full`, the retired keys are dropped, and an unknown `mode` makes the record + * loads as `full`, the retired keys (and the spec's `full`) are dropped, and an unknown `mode` makes the record * unusable, so it is skipped like any other inconsistent lease request. */ function parseStoredGrant(grant: unknown): LeaseGrant | undefined { if (!isObject(grant) || !isObject(grant.device)) return undefined; const device: Record = { ...grant.device }; for (const key of retiredDeviceRecordKeys) delete device[key]; + if (isObject(device.spec)) { + const { full: _retired, ...spec } = device.spec; + device.spec = spec; + } if (device.mode === undefined) device.mode = "full"; if (device.mode !== "slim" && device.mode !== "full") return undefined; return { ...grant, device } as unknown as LeaseGrant; @@ -1057,10 +1075,16 @@ function isDeviceRequest(value: unknown): value is DeviceRequest { isPlatform(value.platform) && typeof value.model === "string" && (value.osVersion === undefined || typeof value.osVersion === "string") && - (value.full === undefined || typeof value.full === "boolean") + (value.mode === undefined || value.mode === "slim" || value.mode === "full") ); } +/** A stored request written before ADR 0007 may carry `full`; it is dropped, not written back. */ +function withoutRetiredRequestKeys(request: DeviceRequest): DeviceRequest { + const { full: _retired, ...current } = request as DeviceRequest & { readonly full?: unknown }; + return current; +} + function isLeaseRequestState(value: unknown): value is LeaseRequestState { return value === "open" || value === "granted" || value === "failed" || value === "cancelled"; } diff --git a/src/core/warm-pool-coordinator.test.ts b/src/core/warm-pool-coordinator.test.ts index 43c27f148..8ba71253b 100644 --- a/src/core/warm-pool-coordinator.test.ts +++ b/src/core/warm-pool-coordinator.test.ts @@ -47,7 +47,7 @@ const config: Config = { stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: "on-request", acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, warmPool: { @@ -296,6 +296,29 @@ describe("WarmPoolCoordinator", () => { expect(harness.registry.snapshot.devices[0]).toMatchObject({ mode: "slim" }); }); + it.each([ + ["a slim spec", { ...spec, mode: "slim" as const }, "slim"], + ["a full spec", spec, "full"], + ] as const)( + "passes %s's mode to makeReady on a warm re-boot", + async (_label, deviceSpec, mode) => { + const clock = new FakeClock(1_000); + const driver = new FakeDriver({ clock, platform: "ios", reclaimResult: "shutdown" }); + const reclaiming = device( + "reclaiming", + "reclaiming", + (await driver.provision(deviceSpec)).deviceId, + deviceSpec, + ); + const harness = await createHarness({ devices: [reclaiming], driver }); + + await harness.coordinator.reclaim(released(reclaiming)); + + const boot = driver.calls.filter((call) => call.operation === "makeReady").at(-1); + expect(boot?.arguments[1]).toEqual({ mode, purpose: "prepare" }); + }, + ); + it("stores full, replacing a stored slim, when a warm re-boot's makeReady reports no mode", async () => { const clock = new FakeClock(1_000); const driver = new FakeDriver({ clock, platform: "ios", reclaimResult: "shutdown" }); diff --git a/src/core/warm-pool-coordinator.ts b/src/core/warm-pool-coordinator.ts index 71a0ff8a7..12bdc2f80 100644 --- a/src/core/warm-pool-coordinator.ts +++ b/src/core/warm-pool-coordinator.ts @@ -9,6 +9,7 @@ import { mayBeGranted, type Platform, sameSpec, + specMode, } from "./domain.js"; import { readyTransitionUpdate, type Driver, type DriverDevice } from "./driver.js"; import type { QuarantinePurgeFailure } from "./quarantine-coordinator.js"; @@ -267,7 +268,10 @@ export class WarmPoolCoordinator { /** Undefined on failure; otherwise the driver's freshly re-read device, address included. */ async #tryMakeReady(driver: Driver, released: ReleasedLease): Promise { try { - return await driver.makeReady(toDriverDevice(released.device)); + return await driver.makeReady(toDriverDevice(released.device), { + mode: specMode(released.device.spec), + purpose: "prepare", + }); } catch (error: unknown) { this.#logFailure("making a reclaimed device ready failed", released, "make-ready", error); return undefined; diff --git a/src/daemon-protocol/index.test.ts b/src/daemon-protocol/index.test.ts index cf47efb57..5bc1d3a3e 100644 --- a/src/daemon-protocol/index.test.ts +++ b/src/daemon-protocol/index.test.ts @@ -14,9 +14,9 @@ describe("daemon protocol", () => { // the `worker` token role) all land on the wire with nothing kept behind them, exactly as // ADR 0004's removals took it to 4, so under ADR 0003 §6's honesty rule the range does not // widen to keep speaking 4. ADR 0008 then makes the catalog's `modelRuntimes` required, - // taking it to 6, and ADR 0007 makes a device's mode a required `mode`, taking it to 7, each - // the same way. - expect(DAEMON_PROTOCOL_VERSION).toBe(7); + // taking it to 6, and ADR 0007 makes a device's mode a required `mode`, taking it to 7, then + // lets a lease request choose it, taking it to 8, each the same way. + expect(DAEMON_PROTOCOL_VERSION).toBe(8); expect(serializeFrame({ id: 1, type: "hello" })).toBe('{"id":1,"type":"hello"}\n'); }); diff --git a/src/daemon/dispatcher.test.ts b/src/daemon/dispatcher.test.ts index 339c0b9c1..e70d849d9 100644 --- a/src/daemon/dispatcher.test.ts +++ b/src/daemon/dispatcher.test.ts @@ -1573,7 +1573,7 @@ function testConfig( stalledTransition: { thresholdMultiplier: 3, minimumThresholdMs: 60_000 }, downloads: { policy: downloadsPolicy, acceptAndroidLicenses: false, timeoutMs: 1_200_000 }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, lease: { diff --git a/src/daemon/dispatcher.ts b/src/daemon/dispatcher.ts index 128974b97..695e91ddd 100644 --- a/src/daemon/dispatcher.ts +++ b/src/daemon/dispatcher.ts @@ -295,7 +295,7 @@ export class Dispatcher { model: input.model, platform: input.platform, ...(input.osVersion === undefined ? {} : { osVersion: input.osVersion }), - ...(input.full ? { full: true } : {}), + ...(input.mode === undefined ? {} : { mode: input.mode }), }; this.#requireTtlWithinCap(input.ttlMs); const requesterId = input.requesterId ?? session.principal; diff --git a/src/daemon/main.test.ts b/src/daemon/main.test.ts index acbfcf0f3..6dd80baf5 100644 --- a/src/daemon/main.test.ts +++ b/src/daemon/main.test.ts @@ -28,6 +28,7 @@ import { } from "../ports/index.js"; import { bridgeAndroidDriverDiagnostic, + deviceModeWiring, discoverDrivers, emitComponentInstallDiagnostic, emitSlimDiagnostic, @@ -821,11 +822,19 @@ describe("discoverDrivers on a host with an Android SDK", () => { }); const android = drivers.find((driver) => driver.platform === "android"); await expect( - android?.makeReady({ - address: "emulator-5586", - deviceId: "simlock_one", - driverData: { avdName: "simlock_one", configHash: "", port: 5586, serial: "emulator-5586" }, - }), + android?.makeReady( + { + address: "emulator-5586", + deviceId: "simlock_one", + driverData: { + avdName: "simlock_one", + configHash: "", + port: 5586, + serial: "emulator-5586", + }, + }, + { mode: "full", purpose: "prepare" }, + ), ).rejects.toThrow(/Unexpected process invocation/); expect(processRunner.calls.map((call) => call.args)).toEqual([ @@ -994,6 +1003,18 @@ 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", + (defaultMode) => { + expect(deviceModeWiring({ ios: { defaultMode, slim: { bootTimeoutMs: 1 } } })).toEqual({ + defaultModes: { ios: defaultMode }, + slimByDefault: defaultMode === "slim", + }); + }, + ); +}); + describe("component install diagnostic bridging", () => { it("emits component.install-started/-installed/-failed for the bridged platform", () => { const clock = new FakeClock(1_000); diff --git a/src/daemon/main.ts b/src/daemon/main.ts index 011a57d15..1bacc655f 100644 --- a/src/daemon/main.ts +++ b/src/daemon/main.ts @@ -7,6 +7,7 @@ import { fitHostFacts } from "../contract/index.js"; import { type Config, type ConfigOverrides, + type DeviceMode, type Driver, type DriverRejection, CleanupReaper, @@ -212,6 +213,7 @@ export async function startDaemon(options: StartDaemonOptions = {}): Promise): { + readonly defaultModes: Readonly>>; + readonly slimByDefault: boolean; +} { + return { + defaultModes: { ios: config.ios.defaultMode }, + slimByDefault: config.ios.defaultMode === "slim", + }; +} + /** * Turns the iOS driver's `SlimmedFact` into the matching `device.slimmed` bus event. Mirrors * `emitComponentInstallDiagnostic`: the driver never depends on the event bus directly diff --git a/src/daemon/server.test.ts b/src/daemon/server.test.ts index bfafdc54a..5db61cb76 100644 --- a/src/daemon/server.test.ts +++ b/src/daemon/server.test.ts @@ -2148,46 +2148,44 @@ describe("DaemonServer download policy", () => { }); }); -describe("DaemonServer full request flag", () => { - it("parses request.full: true into a spec stamped full: true", async () => { - // Stamping `full` is gated on the resolving driver declaring `reducesFeatures` -- without it - // there is nothing to opt out of, so the flag would (correctly) leave the spec untouched and - // this test would be asserting the wrong half of that contract. - const harness = await createHarness({ reducesFeatures: true }); +describe("DaemonServer lease request mode", () => { + it("grants a slim request on a runtime the driver can slim with mode slim", async () => { + const harness = await createHarness({ slimmableOsVersions: ["26.5"] }); const client = await createClient(harness.socketPath); await hello(client); const grant = await client.request("lease.request", { requesterId: "agent-1", - full: true, + mode: "slim", model: "iPhone 16", osVersion: "26.5", platform: "ios", }); expect(grant.ok).toBe(true); - expect( - (grant.payload as { device: { spec: Record } }).device.spec, - ).toMatchObject({ full: true }); + expect((grant.payload as { device: { mode: string } }).device.mode).toBe("slim"); await client.close(); }); - it("omits full from the spec when the request does not ask for it", async () => { + it.each([ + ["full", { full: true }], + ["a mode other than slim or full", { mode: "fast" }], + ["the lease mode ADR 0004 retired", { mode: "held" }], + ])("answers a lease.request carrying %s with BAD_REQUEST", async (_label, extra) => { const harness = await createHarness(); const client = await createClient(harness.socketPath); await hello(client); - const grant = await client.request("lease.request", { + const response = await client.request("lease.request", { requesterId: "agent-1", model: "iPhone 16", osVersion: "26.5", platform: "ios", + ...extra, }); - expect(grant.ok).toBe(true); - expect( - (grant.payload as { device: { spec: Record } }).device.spec, - ).not.toHaveProperty("full"); + expect(response.ok).toBe(false); + expect(response.error).toMatchObject({ code: "BAD_REQUEST" }); await client.close(); }); }); @@ -2767,8 +2765,8 @@ async function createHarness( readonly driver?: FakeDriver; readonly driverRejections?: readonly DriverRejection[]; readonly logger?: Logger; - /** Passed to the default `FakeDriver`; makes a `--full` request meaningful (see `Driver.reducesFeatures`). */ - readonly reducesFeatures?: boolean; + /** Passed to the default `FakeDriver`: the OS versions it can slim. */ + readonly slimmableOsVersions?: readonly string[]; /** Overrides the default single-iOS-device capacity limit; a test that needs two * concurrent iOS leases granted (rather than one queued behind the other) sets this. */ readonly iosMaxDevices?: number; @@ -2819,9 +2817,9 @@ async function createHarness( ...(options.estimateMs === undefined ? {} : { estimateMs: options.estimateMs }), ...(options.latencyMs === undefined ? {} : { latencyMs: options.latencyMs }), platform: "ios", - ...(options.reducesFeatures === undefined + ...(options.slimmableOsVersions === undefined ? {} - : { reducesFeatures: options.reducesFeatures }), + : { slimmableOsVersions: options.slimmableOsVersions }), }); const config = testConfig(options.lease, options.downloads, options.iosMaxDevices); const engine = new LeaseEngine({ @@ -3170,7 +3168,7 @@ function testConfig( ...downloadsOverrides, }, http: { enabled: false, host: "127.0.0.1", port: 4700 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, lease: { diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 6031ef903..b91fd79d1 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -871,7 +871,7 @@ describe("IosSimctlDriver", () => { ]); }); - it("stamps full: true into driver data for a --full request, omitted otherwise", async () => { + it("keeps no copy of a slim spec's mode in driver data", async () => { const runner = new ScriptedProcessRunner([ { match: listInvocation, @@ -902,10 +902,10 @@ describe("IosSimctlDriver", () => { { allowDownload: false }, ); - await expect(driver.provision({ ...spec, full: true })).resolves.toEqual({ + await expect(driver.provision({ ...spec, mode: "slim" })).resolves.toEqual({ address: driverData.udid, deviceId: driverData.udid, - driverData: { ...driverData, full: true }, + driverData, }); }); @@ -942,11 +942,14 @@ describe("IosSimctlDriver", () => { const driver = await createDriver(runner); await expect( - driver.makeReady({ - address: driverData.udid, - deviceId: driverData.udid, - driverData, - }), + driver.makeReady( + { + address: driverData.udid, + deviceId: driverData.udid, + driverData, + }, + prepareFull, + ), ).resolves.toEqual({ address: driverData.udid, deviceId: driverData.udid, @@ -968,11 +971,14 @@ describe("IosSimctlDriver", () => { { match: simctl("shutdown", driverData.udid) }, ]); const driver = await createDriver(runner, clock); - const ready = driver.makeReady({ - address: driverData.udid, - deviceId: driverData.udid, - driverData, - }); + const ready = driver.makeReady( + { + address: driverData.udid, + deviceId: driverData.udid, + driverData, + }, + prepareFull, + ); // Handled up front so a failure below reports itself rather than surfacing as an // unhandled rejection in whichever test happens to run next. void ready.catch(() => undefined); @@ -1671,7 +1677,7 @@ describe("IosSimctlDriver", () => { { allowDownload: false }, ); device = await driver.provision(liveSpec); - await driver.makeReady(device); + await driver.makeReady(device, prepareFull); await driver.reclaim(device, { clean: "standard" }); } finally { if (device !== undefined) { @@ -1697,7 +1703,7 @@ describe("IosSimctlDriver", () => { const slimGarbageRuntime = { ...driverData, runtimeId: "not-a-runtime-id" }; function slimOptions(bootTimeoutMs = 300_000) { - return { bootTimeoutMs, categories: ["widgets"], enabled: true } as const; + return { bootTimeoutMs, categories: ["widgets"] } as const; } it("parses simctl runtime ids into [major, minor], including edge cases", () => { @@ -1742,11 +1748,14 @@ describe("IosSimctlDriver", () => { const onSlimmed = vi.fn(); await expect( - (await createDriver(runner)).makeReady({ - address: driverData.udid, - deviceId: driverData.udid, - driverData, - }), + (await createDriver(runner)).makeReady( + { + address: driverData.udid, + deviceId: driverData.udid, + driverData, + }, + prepareFull, + ), ).resolves.toEqual({ address: driverData.udid, deviceId: driverData.udid, @@ -1761,71 +1770,78 @@ describe("IosSimctlDriver", () => { expect(onSlimmed).not.toHaveBeenCalled(); }); - it("boots, applies the disable list, and reboots on a qualifying, not-yet-slimmed device", async () => { - const filesystem = new MemoryFilesystem(); - await plantManagedDevice(filesystem); - const runner = new ScriptedProcessRunner([ - { match: { command: "xcrun", args: simctlArgs("boot", slim18_5.udid) } }, - { - match: { command: "xcrun", args: simctlArgs("bootstatus", slim18_5.udid, "-b") }, - }, - { - match: { - args: simctlArgs("spawn", slim18_5.udid, "/bin/sh", "-c", slimScript(widgetsLabels)), - command: "xcrun", + it.each([false, true])( + "boots a slim-spec device on 18.5, applies the disable list, and reboots (slim by default: %s)", + async (slimByDefault) => { + const filesystem = new MemoryFilesystem(); + await plantManagedDevice(filesystem); + const runner = new ScriptedProcessRunner([ + { match: { command: "xcrun", args: simctlArgs("boot", slim18_5.udid) } }, + { + match: { command: "xcrun", args: simctlArgs("bootstatus", slim18_5.udid, "-b") }, }, - }, - { match: { command: "xcrun", args: simctlArgs("shutdown", slim18_5.udid) } }, - { match: { command: "xcrun", args: simctlArgs("boot", slim18_5.udid) } }, - { - match: { command: "xcrun", args: simctlArgs("bootstatus", slim18_5.udid, "-b") }, - }, - ]); - const onSlimmed = vi.fn(); - const onSlimSkipped = vi.fn(); - const driver = await createSlimDriver( - runner, - filesystem, - slimOptions(), - onSlimmed, - onSlimSkipped, - ); + { + match: { + args: simctlArgs("spawn", slim18_5.udid, "/bin/sh", "-c", slimScript(widgetsLabels)), + command: "xcrun", + }, + }, + { match: { command: "xcrun", args: simctlArgs("shutdown", slim18_5.udid) } }, + { match: { command: "xcrun", args: simctlArgs("boot", slim18_5.udid) } }, + { + match: { command: "xcrun", args: simctlArgs("bootstatus", slim18_5.udid, "-b") }, + }, + ]); + const onSlimmed = vi.fn(); + const onSlimSkipped = vi.fn(); + const driver = await createSlimDriver( + runner, + filesystem, + slimOptions(), + onSlimmed, + onSlimSkipped, + slimByDefault, + ); - const result = await driver.makeReady({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: slim18_5, - }); + const result = await driver.makeReady( + { + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: slim18_5, + }, + prepareSlim, + ); - expect(result).toEqual({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: { ...slim18_5, slimSignature: widgetsSignature }, - mode: "slim", - }); - expect(runner.calls.map((call) => call.args)).toEqual([ - simctlArgs("boot", slim18_5.udid), - simctlArgs("bootstatus", slim18_5.udid, "-b"), - simctlArgs("spawn", slim18_5.udid, "/bin/sh", "-c", slimScript(widgetsLabels)), - simctlArgs("shutdown", slim18_5.udid), - simctlArgs("boot", slim18_5.udid), - simctlArgs("bootstatus", slim18_5.udid, "-b"), - ]); - // Both boots use the widened slim deadline, not the default 120s. - expect(runner.calls[1]?.options).toEqual({ timeoutMs: 300_000 }); - expect(runner.calls[5]?.options).toEqual({ timeoutMs: 300_000 }); - expect(onSlimmed).toHaveBeenCalledTimes(1); - expect(onSlimmed).toHaveBeenCalledWith({ - address: slim18_5.udid, - categories: ["widgets"], - deviceId: slim18_5.udid, - durationMs: expect.any(Number), - labelCount: 3, - signature: widgetsSignature, - unknownLabels: [], - }); - expect(onSlimSkipped).not.toHaveBeenCalled(); - }); + expect(result).toEqual({ + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: { ...slim18_5, slimSignature: widgetsSignature }, + mode: "slim", + }); + expect(runner.calls.map((call) => call.args)).toEqual([ + simctlArgs("boot", slim18_5.udid), + simctlArgs("bootstatus", slim18_5.udid, "-b"), + simctlArgs("spawn", slim18_5.udid, "/bin/sh", "-c", slimScript(widgetsLabels)), + simctlArgs("shutdown", slim18_5.udid), + simctlArgs("boot", slim18_5.udid), + simctlArgs("bootstatus", slim18_5.udid, "-b"), + ]); + // Both boots use the widened slim deadline, not the default 120s. + expect(runner.calls[1]?.options).toEqual({ timeoutMs: 300_000 }); + expect(runner.calls[5]?.options).toEqual({ timeoutMs: 300_000 }); + expect(onSlimmed).toHaveBeenCalledTimes(1); + expect(onSlimmed).toHaveBeenCalledWith({ + address: slim18_5.udid, + categories: ["widgets"], + deviceId: slim18_5.udid, + durationMs: expect.any(Number), + labelCount: 3, + signature: widgetsSignature, + unknownLabels: [], + }); + expect(onSlimSkipped).not.toHaveBeenCalled(); + }, + ); it("downgrades a failed post-apply shutdown to a skip instead of failing the lease, but always reboots first (finding #3 / second-review finding #2, issue #87)", async () => { // CHANGED EXPECTATIONS (second adversarial review, finding #2): the previous version of @@ -1869,11 +1885,14 @@ describe("IosSimctlDriver", () => { onSlimSkipped, ); - const result = await driver.makeReady({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: slim18_5, - }); + const result = await driver.makeReady( + { + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: slim18_5, + }, + prepareSlim, + ); expect(result).toEqual({ address: slim18_5.udid, @@ -1935,11 +1954,14 @@ describe("IosSimctlDriver", () => { slim: slimOptions(), }); - const ready = driver.makeReady({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: slim18_5, - }); + const ready = driver.makeReady( + { + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: slim18_5, + }, + prepareSlim, + ); await waitForCalls(runner, 4); clock.advance(30_000); // COMMAND_TIMEOUT_MS, the `#shutdown` call's own timeout @@ -2006,11 +2028,14 @@ describe("IosSimctlDriver", () => { slim: slimOptions(), }); - const ready = driver.makeReady({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: slim18_5, - }); + const ready = driver.makeReady( + { + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: slim18_5, + }, + prepareSlim, + ); await waitForCalls(runner, 6); clock.advance(300_000); // slim.bootTimeoutMs -- the widened deadline applies to this reboot too @@ -2052,11 +2077,14 @@ describe("IosSimctlDriver", () => { ); await expect( - driver.makeReady({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: slim18_5, - }), + driver.makeReady( + { + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: slim18_5, + }, + prepareSlim, + ), ).rejects.toEqual( expect.objectContaining({ message: expect.stringContaining("Shutting Down") }), ); @@ -2080,11 +2108,14 @@ describe("IosSimctlDriver", () => { const onSlimmed = vi.fn(); const driver = await createSlimDriver(runner, filesystem, slimOptions(), onSlimmed); - const result = await driver.makeReady({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: slimmedData, - }); + const result = await driver.makeReady( + { + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: slimmedData, + }, + prepareSlim, + ); expect(result).toEqual({ address: slim18_5.udid, @@ -2124,11 +2155,14 @@ describe("IosSimctlDriver", () => { const onSlimmed = vi.fn(); const driver = await createSlimDriver(runner, filesystem, slimOptions(), onSlimmed); - const result = await driver.makeReady({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: staleData, - }); + const result = await driver.makeReady( + { + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: staleData, + }, + prepareSlim, + ); expect(result.driverData).toEqual({ ...slim18_5, @@ -2163,11 +2197,14 @@ describe("IosSimctlDriver", () => { const onSlimmed = vi.fn(); const driver = await createSlimDriver(runner, filesystem, slimOptions(), onSlimmed); - await driver.makeReady({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: driftedData, - }); + await driver.makeReady( + { + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: driftedData, + }, + prepareSlim, + ); expect(onSlimmed).toHaveBeenCalledTimes(1); expect(onSlimmed).toHaveBeenCalledWith( @@ -2189,11 +2226,14 @@ describe("IosSimctlDriver", () => { onSlimSkipped, ); - const result = await driver.makeReady({ - address: slim18_4.udid, - deviceId: slim18_4.udid, - driverData: slim18_4, - }); + const result = await driver.makeReady( + { + address: slim18_4.udid, + deviceId: slim18_4.udid, + driverData: slim18_4, + }, + prepareSlim, + ); expect(result).toEqual({ address: slim18_4.udid, @@ -2223,11 +2263,14 @@ describe("IosSimctlDriver", () => { onSlimSkipped, ); - await driver.makeReady({ - address: slim17_5.udid, - deviceId: slim17_5.udid, - driverData: slim17_5, - }); + await driver.makeReady( + { + address: slim17_5.udid, + deviceId: slim17_5.udid, + driverData: slim17_5, + }, + prepareSlim, + ); expect(onSlimSkipped).toHaveBeenCalledWith( expect.objectContaining({ reason: "runtime-too-old" }), @@ -2253,11 +2296,14 @@ describe("IosSimctlDriver", () => { onSlimSkipped, ); - await driver.makeReady({ - address: slimGarbageRuntime.udid, - deviceId: slimGarbageRuntime.udid, - driverData: slimGarbageRuntime, - }); + await driver.makeReady( + { + address: slimGarbageRuntime.udid, + deviceId: slimGarbageRuntime.udid, + driverData: slimGarbageRuntime, + }, + prepareSlim, + ); expect(onSlimSkipped).toHaveBeenCalledWith( expect.objectContaining({ reason: "unknown-runtime" }), @@ -2283,11 +2329,14 @@ describe("IosSimctlDriver", () => { const onSlimmed = vi.fn(); const driver = await createSlimDriver(runner, filesystem, slimOptions(), onSlimmed); - await driver.makeReady({ - address: slim26_0.udid, - deviceId: slim26_0.udid, - driverData: slim26_0, - }); + await driver.makeReady( + { + address: slim26_0.udid, + deviceId: slim26_0.udid, + driverData: slim26_0, + }, + prepareSlim, + ); expect(onSlimmed).toHaveBeenCalledTimes(1); }); @@ -2337,11 +2386,14 @@ describe("IosSimctlDriver", () => { onSlimSkipped, ); - const result = await driver.makeReady({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: slim18_5, - }); + const result = await driver.makeReady( + { + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: slim18_5, + }, + prepareSlim, + ); expect(result).toEqual({ address: slim18_5.udid, @@ -2391,11 +2443,14 @@ describe("IosSimctlDriver", () => { const onSlimmed = vi.fn(); const driver = await createSlimDriver(runner, filesystem, slimOptions(), onSlimmed); - const result = await driver.makeReady({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: alreadySlimmedData, - }); + const result = await driver.makeReady( + { + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: alreadySlimmedData, + }, + prepareSlim, + ); expect(result).toEqual({ address: slim18_5.udid, @@ -2474,14 +2529,17 @@ describe("IosSimctlDriver", () => { processRunner: runner, // No `categories` filter -- every category's labels, chunked the same way a real, // unfiltered slim run would be. - slim: { bootTimeoutMs: 300_000, enabled: true }, + slim: { bootTimeoutMs: 300_000 }, }); - const ready = driver.makeReady({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: slim18_5, - }); + const ready = driver.makeReady( + { + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: slim18_5, + }, + prepareSlim, + ); await waitForCalls(runner, 6); clock.advance(60_000); // SLIM_CHUNK_TIMEOUT_MS @@ -2537,11 +2595,14 @@ describe("IosSimctlDriver", () => { onSlimSkipped, ); - const result = await driver.makeReady({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: slim18_5, - }); + const result = await driver.makeReady( + { + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: slim18_5, + }, + prepareSlim, + ); expect(result).toEqual({ address: slim18_5.udid, @@ -2560,42 +2621,71 @@ describe("IosSimctlDriver", () => { ); }); - it("never slims a device marked full:true, even when it otherwise qualifies", async () => { - const fullData = { ...slim18_5, full: true }; + it.each([false, true])( + "boots a full-spec device on 18.5 once, with the normal deadline (slim by default: %s)", + async (slimByDefault) => { + const runner = new ScriptedProcessRunner([ + { match: { command: "xcrun", args: simctlArgs("boot", slim18_5.udid) } }, + { match: { command: "xcrun", args: simctlArgs("bootstatus", slim18_5.udid, "-b") } }, + ]); + const onSlimmed = vi.fn(); + const onSlimSkipped = vi.fn(); + const driver = await createSlimDriver( + runner, + new MemoryFilesystem(), + slimOptions(), + onSlimmed, + onSlimSkipped, + slimByDefault, + ); + + const result = await driver.makeReady( + { address: slim18_5.udid, deviceId: slim18_5.udid, driverData: slim18_5 }, + prepareFull, + ); + + expect(result).toEqual({ + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: slim18_5, + mode: "full", + }); + expect(runner.calls).toHaveLength(2); + expect(runner.calls[1]?.options).toEqual({ timeoutMs: 120_000 }); + expect(onSlimmed).not.toHaveBeenCalled(); + expect(onSlimSkipped).not.toHaveBeenCalled(); + }, + ); + + it("ignores a full flag an older daemon stamped into driver data: the spec mode decides", async () => { + const filesystem = new MemoryFilesystem(); + await plantManagedDevice(filesystem); + const stamped = { ...slim18_5, full: true }; const runner = new ScriptedProcessRunner([ - { match: { command: "xcrun", args: simctlArgs("boot", fullData.udid) } }, - { match: { command: "xcrun", args: simctlArgs("bootstatus", fullData.udid, "-b") } }, + { match: { command: "xcrun", args: simctlArgs("boot", stamped.udid) } }, + { match: { command: "xcrun", args: simctlArgs("bootstatus", stamped.udid, "-b") } }, + { + match: { + args: simctlArgs("spawn", stamped.udid, "/bin/sh", "-c", slimScript(widgetsLabels)), + command: "xcrun", + }, + }, + { match: { command: "xcrun", args: simctlArgs("shutdown", stamped.udid) } }, + { match: { command: "xcrun", args: simctlArgs("boot", stamped.udid) } }, + { match: { command: "xcrun", args: simctlArgs("bootstatus", stamped.udid, "-b") } }, ]); - const onSlimmed = vi.fn(); - const onSlimSkipped = vi.fn(); - const driver = await createSlimDriver( - runner, - new MemoryFilesystem(), - slimOptions(), - onSlimmed, - onSlimSkipped, - ); + const driver = await createSlimDriver(runner, filesystem, slimOptions()); - const result = await driver.makeReady({ - address: fullData.udid, - deviceId: fullData.udid, - driverData: fullData, - }); + const result = await driver.makeReady( + { address: stamped.udid, deviceId: stamped.udid, driverData: stamped }, + prepareSlim, + ); - expect(result).toEqual({ - address: fullData.udid, - deviceId: fullData.udid, - driverData: fullData, - mode: "full", - }); - expect(runner.calls).toHaveLength(2); - expect(runner.calls[1]?.options).toEqual({ timeoutMs: 120_000 }); - expect(onSlimmed).not.toHaveBeenCalled(); - expect(onSlimSkipped).not.toHaveBeenCalled(); + expect(result.mode).toBe("slim"); }); it("a purpose: 'recover' boot never applies slim, even on a device that would otherwise qualify (finding #1, issue #87 review)", async () => { - // `slim18_5` (not `full`, an 18.5+ runtime) is exactly the shape of device + // `slim18_5` (a slim spec, an 18.5+ runtime) is exactly the shape of device // "boots, applies the disable list, and reboots on a qualifying, not-yet-slimmed device" // (above) slims -- the only difference here is `{ purpose: "recover" }`, standing in for // `ManagedDeviceLifecycle.recoverLeased`'s call on a crashed, still-*leased* device. Safety @@ -2625,7 +2715,7 @@ describe("IosSimctlDriver", () => { deviceId: slim18_5.udid, driverData: slim18_5, }, - { purpose: "recover" }, + { mode: "slim", purpose: "recover" }, ); expect(result).toEqual({ @@ -2657,11 +2747,14 @@ describe("IosSimctlDriver", () => { // covered by "boots, applies the disable list..." above, which starts from data with no // prior slim markers either). await expect( - (await createDriver(runner)).makeReady({ - address: driverData.udid, - deviceId: driverData.udid, - driverData, - }), + (await createDriver(runner)).makeReady( + { + address: driverData.udid, + deviceId: driverData.udid, + driverData, + }, + prepareFull, + ), ).resolves.toEqual({ address: driverData.udid, deviceId: driverData.udid, @@ -2703,11 +2796,14 @@ describe("IosSimctlDriver", () => { slim: slimOptions(), }); - const ready = driver.makeReady({ - address: slim18_5.udid, - deviceId: slim18_5.udid, - driverData: slim18_5, - }); + const ready = driver.makeReady( + { + address: slim18_5.udid, + deviceId: slim18_5.udid, + driverData: slim18_5, + }, + prepareSlim, + ); await waitForCalls(runner, 6); clock.advance(300_000); @@ -2716,7 +2812,7 @@ describe("IosSimctlDriver", () => { expect(runner.calls[5]?.options).toEqual({ timeoutMs: 300_000 }); }); - it("estimates the boot cost with the slim reboot+apply budget when slim is on", async () => { + it("estimates the boot cost with the slim reboot+apply budget for a slim spec", async () => { const driver = await IosSimctlDriver.create({ driverConfig: { deviceRoot }, instanceId, @@ -2728,10 +2824,10 @@ describe("IosSimctlDriver", () => { slim: slimOptions(), }); - expect(driver.estimate({ operation: "boot" }, spec)).toBe(150_000); + expect(driver.estimate({ operation: "boot" }, { ...spec, mode: "slim" })).toBe(150_000); }); - it("quotes the plain cold-boot cost for a full spec even when slim is on, since a full spec never slims (finding #4, issue #87 review)", async () => { + it("quotes the plain cold-boot cost for a full spec, since a full spec never slims", async () => { const driver = await IosSimctlDriver.create({ driverConfig: { deviceRoot }, instanceId, @@ -2743,15 +2839,72 @@ describe("IosSimctlDriver", () => { slim: slimOptions(), }); - expect(driver.estimate({ operation: "boot" }, { ...spec, full: true })).toBe(60_000); + expect(driver.estimate({ operation: "boot" }, spec)).toBe(60_000); + }); + + describe("resolveSpec and the device mode", () => { + const iphone16 = { model: "iPhone 16", platform: "ios" } as const; + + it("returns a full spec for a slim request on a runtime below 18.5", async () => { + const driver = await createSlimDriver( + scriptedListRunner(), + new MemoryFilesystem(), + slimOptions(), + ); + + await expect( + driver.resolveSpec( + { ...iphone16, mode: "slim", osVersion: "18.4" }, + { allowDownload: false }, + ), + ).resolves.toEqual({ ...iphone16, osVersion: "18.4" }); + }); + + it("gives two requests with different modes for one model and runtime different specs", async () => { + const list = { + match: listInvocation, + result: { code: 0, stderr: "", stdout: listFixture }, + }; + const driver = await createSlimDriver( + new ScriptedProcessRunner([list, list]), + new MemoryFilesystem(), + slimOptions(), + ); + + const slim = await driver.resolveSpec( + { ...iphone16, mode: "slim", osVersion: "26.5" }, + { allowDownload: false }, + ); + const full = await driver.resolveSpec( + { ...iphone16, mode: "full", osVersion: "26.5" }, + { allowDownload: false }, + ); + + expect(slim).toEqual({ ...iphone16, mode: "slim", osVersion: "26.5" }); + expect(full).toEqual({ ...iphone16, osVersion: "26.5" }); + }); + + it("returns a full spec for a slim request when slim is not configured", async () => { + const driver = await createDriver(scriptedListRunner()); + + await expect( + driver.resolveSpec( + { ...iphone16, mode: "slim", osVersion: "26.5" }, + { allowDownload: false }, + ), + ).resolves.toEqual({ ...iphone16, osVersion: "26.5" }); + }); }); describe("advisories()", () => { - it("reports slim-runtime-unsupported when an installed runtime predates 18.5", async () => { + it("reports slim-runtime-unsupported when the default mode is slim and an installed runtime predates 18.5", async () => { const driver = await createSlimDriver( scriptedListRunner(), new MemoryFilesystem(), slimOptions(), + undefined, + undefined, + true, ); // listFixture installs iOS 18.4 (below the floor) alongside iOS 26.5 (above it). @@ -2773,12 +2926,19 @@ describe("IosSimctlDriver", () => { const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: onlyNewFixture } }, ]); - const driver = await createSlimDriver(runner, new MemoryFilesystem(), slimOptions()); + const driver = await createSlimDriver( + runner, + new MemoryFilesystem(), + slimOptions(), + undefined, + undefined, + true, + ); await expect(driver.advisories()).resolves.toEqual([]); }); - it("reports nothing when slim mode is off", async () => { + it("reports nothing when slim is not configured", async () => { const driver = await createDriver(scriptedListRunner()); await expect(driver.advisories()).resolves.toEqual([]); @@ -2809,7 +2969,14 @@ describe("IosSimctlDriver", () => { result: { code: 0, stderr: "", stdout: weirdIdentifierFixture }, }, ]); - const driver = await createSlimDriver(runner, new MemoryFilesystem(), slimOptions()); + const driver = await createSlimDriver( + runner, + new MemoryFilesystem(), + slimOptions(), + undefined, + undefined, + true, + ); await expect(driver.advisories()).resolves.toEqual([ { @@ -2819,12 +2986,15 @@ describe("IosSimctlDriver", () => { ]); }); - it("reports nothing when slim is configured but disabled", async () => { - const driver = await createSlimDriver(scriptedListRunner(), new MemoryFilesystem(), { - bootTimeoutMs: 300_000, - categories: ["widgets"], - enabled: false, - }); + it("reports nothing when the default mode is full, even with a runtime below 18.5 installed", async () => { + const driver = await createSlimDriver( + scriptedListRunner(), + new MemoryFilesystem(), + slimOptions(), + undefined, + undefined, + false, + ); await expect(driver.advisories()).resolves.toEqual([]); }); @@ -3152,12 +3322,12 @@ async function createSlimDriver( runner: ScriptedProcessRunner, filesystem: Filesystem, slim: { - readonly enabled: boolean; readonly categories?: readonly string[]; readonly bootTimeoutMs: number; }, onSlimmed?: (fact: SlimmedFact) => void, onSlimSkipped?: (fact: SlimSkippedFact) => void, + slimByDefault = false, ): Promise { return await IosSimctlDriver.create({ driverConfig: { deviceRoot }, @@ -3170,6 +3340,7 @@ async function createSlimDriver( ...(onSlimSkipped === undefined ? {} : { onSlimSkipped }), processRunner: runner, slim, + slimByDefault, }); } @@ -3219,3 +3390,6 @@ function assetInfoPlist(simulatorVersion: string, build: string): string { "", ].join("\n"); } + +const prepareFull = { mode: "full", purpose: "prepare" } as const; +const prepareSlim = { mode: "slim", purpose: "prepare" } as const; diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 923d091ae..ba6096887 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -151,8 +151,6 @@ interface IosDriverData { readonly name: string; readonly runtimeId: string; readonly udid: string; - /** Per-lease override (set by `provision` from the device spec): never slim this device. */ - readonly full?: boolean; /** `slimSignature(...)` of the label set actually applied -- the idempotence marker. */ readonly slimSignature?: string; /** The device's *erasable* provenance-mark token as read at the moment slimming was applied. */ @@ -226,14 +224,21 @@ export interface IosSimctlDriverOptions { * driver never depends on the bus directly (architecture rule 5). Mirrors `onDiagnostic`. */ readonly onSlimmed?: (fact: SlimmedFact) => void; - /** Reports why a device slim didn't happen when slim mode is on. Mirrors `onDiagnostic`. */ + /** Reports why a slim-spec device was not slimmed. Mirrors `onDiagnostic`. */ readonly onSlimSkipped?: (fact: SlimSkippedFact) => void; - /** Slim mode; omitted or `enabled: false` means today's behaviour exactly. */ + /** + * How a slim device is made (`ios.slim`). Omitted means this driver slims nothing: every slim + * request resolves to a full spec. + */ readonly slim?: { - readonly enabled: boolean; readonly categories?: readonly string[]; readonly bootTimeoutMs: number; }; + /** + * True when the worker's default mode for iOS is `slim`, so `advisories()` reports runtimes + * that cannot be slimmed (ADR 0007 §14). The driver is told this, never the default itself. + */ + readonly slimByDefault?: boolean; } type SlimOptions = NonNullable; @@ -312,13 +317,6 @@ type ProcessOutcome = /** iOS simulator implementation. Its simctl details remain opaque to the core. */ export class IosSimctlDriver implements Driver { readonly platform = "ios" as const; - /** - * `true` only when slim mode is actually enabled -- a `--full` request against this driver - * is only meaningful (and only earns its own, separate pool key -- see `Driver.reducesFeatures`) - * while this driver might otherwise hand back a reduced device. Static per driver instance: - * slim mode is process-wide configuration, not something that varies per request. - */ - readonly reducesFeatures: boolean; readonly #clock: Clock; readonly #coreSimulatorRoot: string; readonly #diskSpaceGuard: DiskSpaceGuard; @@ -334,6 +332,7 @@ export class IosSimctlDriver implements Driver { readonly #deviceRoot: string; readonly #rootOptions: EnsureOwnedRootOptions; readonly #slim: SlimOptions | undefined; + readonly #slimByDefault: boolean; private constructor( options: IosSimctlDriverOptions, @@ -353,7 +352,7 @@ export class IosSimctlDriver implements Driver { this.#deviceRoot = deviceRoot; this.#rootOptions = rootOptions; this.#slim = options.slim; - this.reducesFeatures = options.slim?.enabled === true; + this.#slimByDefault = options.slimByDefault === true; } /** @@ -405,9 +404,25 @@ export class IosSimctlDriver implements Driver { throw new IosUnknownModelError(request.model); } - return request.osVersion === undefined + const spec = await (request.osVersion === undefined ? this.#resolveDefaultRuntime(deviceType, catalog, options) - : this.#resolveExactRuntime(deviceType, request.osVersion, catalog, options); + : this.#resolveExactRuntime(deviceType, request.osVersion, catalog, options)); + // The resolution cache (`specKey`) ignores the mode, so the mode is applied here, outside it. + return request.mode === "slim" && this.#canSlim(spec) ? { ...spec, mode: "slim" } : spec; + } + + /** + * Whether this driver will slim a device of this spec: slim is configured and the runtime is + * 18.5 or newer (ADR 0007 §4). Read from the runtime `resolveSpec` just committed, by the same + * `supportsPersistentSlim(iosRuntimeVersionFromId(...))` call `planSlimBoot` makes. + */ + #canSlim(spec: DeviceSpec): boolean { + const runtime = this.#resolvedSpecs.get(specKey(spec))?.runtime; + return ( + this.#slim !== undefined && + runtime !== undefined && + supportsPersistentSlim(iosRuntimeVersionFromId(runtime.identifier)) + ); } /** @@ -734,18 +749,14 @@ export class IosSimctlDriver implements Driver { name, runtimeId: resolved.runtime.identifier, udid, - // Per-lease opt-out (`DeviceSpec.full`, ADR "serve from a separate pool key"): stamped - // onto driver data only when set, so a normal (non-`--full`) request's driver data stays - // byte-identical to a spec resolved before this field existed. - ...(spec.full === true ? { full: true } : {}), } satisfies IosDriverData, }; } /** * The UDID never changes across a boot -- unlike Android's port, there is nothing to - * re-derive. When slim mode is on and this device qualifies (not `full`, runtime new enough -- - * `#slimApplicable`), the boot deadline is widened *before* the first boot (that decision must + * re-derive. When the device's spec is slim (`options.mode`, ADR 0007 §7) and its runtime new + * enough, the boot deadline is widened *before* the first boot (that decision must * be made from `driverData` alone, ADR point 9) and, once booted, a slim pass may run: apply the * disable list, then reboot once more. A failed or skipped slim never fails the lease -- the * device is still returned, just not marked as slimmed. @@ -753,17 +764,17 @@ export class IosSimctlDriver implements Driver { * `options.purpose === "recover"` (the one caller: `ManagedDeviceLifecycle.recoverLeased`, * safety rule 2's crash-recovery exception on an already-*leased* device) always takes the * `"off"` path below -- a single ordinary boot, no slim apply, no second reboot -- regardless - * of slim configuration or this device's own eligibility. Recovery may only get a leased + * of the device's spec mode. Recovery may only get a leased * device running again, never change what it's running; a "prepare"-shaped slim pass under an * active lease would silently strip push/Spotlight/StoreKit/universal-links mid-lease, which * is exactly the broader privilege safety rule 2 says this exception does not grant. */ async makeReady( device: DriverDevice, - options?: { readonly purpose: "prepare" | "recover" }, + options: { readonly purpose: "prepare" | "recover"; readonly mode: DeviceMode }, ): Promise { const data = iosDriverData(device); - const { plan, bootstatusTimeoutMs } = planSlimBoot(data, this.#slim, options?.purpose); + const { plan, bootstatusTimeoutMs } = planSlimBoot(data, this.#slim, options); await this.#bootAndWait(data.udid, device.deviceId, bootstatusTimeoutMs); @@ -776,8 +787,8 @@ export class IosSimctlDriver implements Driver { } if (plan.kind !== "apply") { - // This boot slimmed nothing: slim mode is off, a per-device `full: true` opt-out, a - // `"recover"` boot, or a runtime-gate skip. The device is full. + // This boot slimmed nothing: a full spec, a `"recover"` boot, or a runtime-gate skip. + // The device is full. return this.#asIs(device, data, "full"); } @@ -1198,12 +1209,11 @@ export class IosSimctlDriver implements Driver { case "provision": return PROVISION_ESTIMATE_MS; case "boot": - // Slim mode pays for a second boot plus a launchctl-disable pass on top of the usual + // A slim device pays for a second boot plus a launchctl-disable pass on top of the usual // one -- quoting the plain cold-boot number here would make `doctor` flag every slim - // device as stalled. But a `full` spec never slims (`planSlimBoot`'s `data.full === true` - // branch), so quoting the slim number to a request that will never pay it would make - // `doctor` flag a perfectly on-time `full` boot as stalled instead. - return this.#slim?.enabled === true && spec.full !== true + // device as stalled. A full spec never slims, so quoting the slim number to it would + // make `doctor` flag a perfectly on-time full boot as stalled instead. + return this.#slim !== undefined && spec.mode === "slim" ? SLIM_BOOT_ESTIMATE_MS : COLD_BOOT_ESTIMATE_MS; case "reclaim": @@ -1344,12 +1354,12 @@ export class IosSimctlDriver implements Driver { * drift from what `makeReady` will actually do: an identifier `iosRuntimeVersionFromId` can't * parse is `undefined`, and `supportsPersistentSlim(undefined)` is `false`, so an unparseable * runtime is reported unsupported here exactly as `makeReady` treats it as `"unknown-runtime"`. - * Nothing when slim mode is off (there is no gate to warn about) or when every installed + * Nothing unless the worker's default mode is slim (ADR 0007 §14), or when every installed * runtime qualifies. Read-only: only `#loadCatalog` (a `simctl list`) runs, no boot, no * download, no mutation -- matching `listCatalog`'s own contract. */ async #slimAdvisories(): Promise { - if (this.#slim === undefined || !this.#slim.enabled) { + if (this.#slim === undefined || !this.#slimByDefault) { return []; } @@ -1372,9 +1382,9 @@ export class IosSimctlDriver implements Driver { { code: "slim-runtime-unsupported", message: - `Slim mode is enabled, but iOS ${unsupportedVersions.join(", ")} ${plural ? "are" : "is"} ` + + `The default device mode is slim, but iOS ${unsupportedVersions.join(", ")} ${plural ? "are" : "is"} ` + `below the 18.5 persistent-override floor; devices on ${plural ? "those runtimes" : "that runtime"} ` + - `are never slimmed -- \`launchctl disable\` overrides do not survive a reboot below iOS 18.5`, + `get full devices -- \`launchctl disable\` overrides do not survive a reboot below iOS 18.5`, }, ]; } @@ -2083,10 +2093,10 @@ function iosDriverData(device: DriverDevice): IosDriverData { name: value.name, runtimeId: value.runtimeId, udid: value.udid, - // All three are optional and post-date `state.json` registries written before slim mode + // Both are optional and post-date `state.json` registries written before slim mode // shipped -- absent or wrong-typed is tolerated (ignored) rather than rejected, so an old - // registry keeps loading (compatibility requirement). - ...(typeof value.full === "boolean" ? { full: value.full } : {}), + // registry keeps loading (compatibility requirement). A `full` key an older daemon stamped + // here is not read: the spec's mode is the only record of it (ADR 0007 §7). ...(typeof value.slimSignature === "string" ? { slimSignature: value.slimSignature } : {}), ...(typeof value.slimMarkToken === "string" ? { slimMarkToken: value.slimMarkToken } : {}), }; @@ -2126,9 +2136,9 @@ export function supportsPersistentSlim(version: readonly [number, number] | unde } /** - * What `makeReady` should do about slimming this boot -- decided from `driverData` and the slim - * options alone, before any `simctl` call runs. `"off"` covers both slim mode being disabled - * entirely and this device's per-lease `full: true` opt-out; `"skip"` is the runtime-gate + * What `makeReady` should do about slimming this boot -- decided from `driverData`, the slim + * options and the spec mode alone, before any `simctl` call runs. `"off"` covers a full spec, + * a driver with no slim options, and a recovery boot; `"skip"` is the runtime-gate * failure (too old / unparseable), carrying the `SlimSkippedFact` fields `makeReady` reports * as-is; `"apply"` carries the resolved `slim` options `#applySlimAndReboot` needs. */ @@ -2138,18 +2148,18 @@ type SlimPlan = | { readonly kind: "apply"; readonly slim: SlimOptions }; /** - * Pure decision step extracted from `makeReady`: given only this device's driver data and the - * driver's slim options, decides what this boot should do and how long the initial `bootstatus` - * wait may take. Slim mode off, this device's `full: true` opt-out, and a `"recover"`-purpose - * call all read as `"off"` -- equivalent from here on (same as-is return, same ordinary boot - * deadline). `purpose` defaults to `"prepare"`, matching `Driver.makeReady`'s own default. + * Pure decision step extracted from `makeReady`: given only this device's driver data, the + * driver's slim options, and the `makeReady` options, decides what this boot should do and how + * long the initial `bootstatus` wait may take. A full spec, no slim options, and a + * `"recover"`-purpose call all read as `"off"` -- equivalent from here on (same as-is return, + * same ordinary boot deadline). */ function planSlimBoot( data: IosDriverData, slim: SlimOptions | undefined, - purpose: "prepare" | "recover" = "prepare", + options: { readonly purpose: "prepare" | "recover"; readonly mode: DeviceMode }, ): { readonly plan: SlimPlan; readonly bootstatusTimeoutMs: number } { - if (purpose === "recover" || slim === undefined || !slim.enabled || data.full === true) { + if (options.purpose === "recover" || slim === undefined || options.mode !== "slim") { return { bootstatusTimeoutMs: BOOTSTATUS_TIMEOUT_MS, plan: { kind: "off" } }; } diff --git a/src/gateway/dispatcher.test.ts b/src/gateway/dispatcher.test.ts index ba4b0e9db..acae03b66 100644 --- a/src/gateway/dispatcher.test.ts +++ b/src/gateway/dispatcher.test.ts @@ -49,7 +49,7 @@ const gatewayConfig = { }, http: { enabled: true, host: "127.0.0.1", port: 4700 }, idle: { deleteAfterMs: 1, shutdownAfterMs: 1 }, - ios: { slim: { bootTimeoutMs: 1, enabled: false } }, + ios: { defaultMode: "full" as const, slim: { bootTimeoutMs: 1 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, lease: { defaultTtlMs: 900_000, @@ -647,6 +647,32 @@ describe("GatewayDispatcher", () => { ).rejects.toMatchObject({ code: "FORBIDDEN" }); }); + it.each([ + ["mode slim", { mode: "slim" as const }], + ["no mode", {}], + ])("forwards a lease.request with %s to the worker as it arrived", async (_label, mode) => { + const { directory, dispatcher, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_1", client); + workers.connected("wrk_1", undefined, "0.3.0"); + workers.refresh("wrk_1", { + capacity: statusFixture().capacity, + catalog: catalogFixture([{ models: ["iPhone 17"], platform: "ios", runtimes: ["26.0"] }]) + .platforms, + downloads: { policy: "on-request" }, + }); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + + await dispatcher.dispatch( + "lease.request", + { model: "iPhone 17", noWait: true, platform: "ios", ...mode }, + session({ role: "agent" }), + ); + + if ("mode" in mode) expect(client.lastRequestLeaseInput).toMatchObject(mode); + else expect(client.lastRequestLeaseInput).not.toHaveProperty("mode"); + }); + it("forwards device.exec to the worker that holds the lease, gated on the caller owning it", async () => { const { coordinator, directory, dispatcher, workers } = harness(); const client = new ScriptedWorkerClient(); diff --git a/src/gateway/dispatcher.ts b/src/gateway/dispatcher.ts index 00ebbace5..e58363663 100644 --- a/src/gateway/dispatcher.ts +++ b/src/gateway/dispatcher.ts @@ -366,7 +366,8 @@ export class GatewayDispatcher { model: input.model, platform: input.platform, ...(input.osVersion === undefined ? {} : { osVersion: input.osVersion }), - ...(input.full ? { full: true } : {}), + // Forwarded as it arrived (ADR 0007 §2): the gateway has no default mode of its own. + ...(input.mode === undefined ? {} : { mode: input.mode }), }, { allowDownload: input.allowDownload ?? false, diff --git a/src/gateway/fleet-coordinator.test.ts b/src/gateway/fleet-coordinator.test.ts index 40f00b58f..103427781 100644 --- a/src/gateway/fleet-coordinator.test.ts +++ b/src/gateway/fleet-coordinator.test.ts @@ -181,6 +181,35 @@ function requestOptions(overrides: Partial { + it.each([ + ["slim", { mode: "slim" as const }], + ["full", { mode: "full" as const }], + ])("forwards a request's mode %s to the worker unchanged", async (_label, mode) => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + connectWorker(workers, "wrk_a"); + + await coordinator.request({ ...REQUEST, ...mode }, requestOptions()); + + expect(client.lastRequestLeaseInput).toMatchObject(mode); + }); + + it("forwards no mode when the request named none, so the worker's default applies", async () => { + const { coordinator, directory, workers } = harness(); + const client = new ScriptedWorkerClient(); + directory.add("wrk_a", client); + client.requestLeaseQueue.push({ grant: grantFixture(), kind: "grant" }); + connectWorker(workers, "wrk_a"); + + await coordinator.request(REQUEST, requestOptions()); + + expect(client.lastRequestLeaseInput).not.toHaveProperty("mode"); + }); +}); + describe("FleetLeaseCoordinator stored requests", () => { it("answers a repeat under the same key with the first grant, forwarding nothing a second time", async () => { const { coordinator, directory, workers } = harness(); diff --git a/src/gateway/fleet-coordinator.ts b/src/gateway/fleet-coordinator.ts index f77155f33..75fe1393b 100644 --- a/src/gateway/fleet-coordinator.ts +++ b/src/gateway/fleet-coordinator.ts @@ -804,7 +804,7 @@ export class FleetLeaseCoordinator { ...(waiter.request.osVersion === undefined ? {} : { osVersion: waiter.request.osVersion }), - ...(waiter.request.full === true ? { full: true } : {}), + ...(waiter.request.mode === undefined ? {} : { mode: waiter.request.mode }), requesterId: namespacedRequesterId, // ADR §27a (narrowed, round 3 review, H3): only the worker's own gateway-uplink // session may set `owner` -- and this RPC always travels over exactly that diff --git a/src/gateway/test-support.ts b/src/gateway/test-support.ts index c4e7dbda3..65175e12a 100644 --- a/src/gateway/test-support.ts +++ b/src/gateway/test-support.ts @@ -263,6 +263,8 @@ export class ScriptedWorkerClient { * gave up on it. */ lastRequestLeaseOptions: RequestLeaseOptions | undefined; + /** The input of the last `lease.request` forwarded to this worker. */ + lastRequestLeaseInput: LeaseRequestInput | undefined; constructor( readonly role: "admin" | "agent" = "admin", @@ -318,6 +320,7 @@ export class ScriptedWorkerClient { this.calls.push(`lease.request:${input.requesterId ?? ""}`); this.#throwIfFailing(); this.lastRequestLeaseOptions = options; + this.lastRequestLeaseInput = input; const outcome = this.requestLeaseQueue.shift() ?? this.requestLeaseDefault; for (const progress of outcome.progress ?? []) options.onProgress?.(progress); if (outcome.kind === "hang") return new Promise(() => {}); diff --git a/src/http/app.test.ts b/src/http/app.test.ts index 65d558690..3d5eea05e 100644 --- a/src/http/app.test.ts +++ b/src/http/app.test.ts @@ -287,6 +287,31 @@ describe("POST /v1/lease-requests", () => { expect(dispatcher.calls).toHaveLength(0); }); + it.each([ + ["full", { full: true }], + ["a mode other than slim or full", { mode: "fast" }], + ["a key the route does not know", { colour: "blue" }], + ])("400s a body carrying %s as BAD_REQUEST before ever dispatching", async (_label, extra) => { + const { app, dispatcher } = buildHarness(); + // Raced against a dispatch, so a body that is wrongly accepted fails here on the assertion + // below rather than by waiting for a 201 that only comes once the request is queued. + const response = await Promise.race([ + postLeaseRequest(app, { ...defaultBody, ...extra }), + waitForDispatch(dispatcher, "lease.request").then(() => "dispatched" as const), + ]); + if (response === "dispatched") throw new Error("the body was dispatched instead of refused"); + expect(response.status).toBe(400); + expect(((await response.json()) as { error: { code: string } }).error.code).toBe("BAD_REQUEST"); + expect(dispatcher.calls).toHaveLength(0); + }); + + it("forwards a body's mode to the dispatched lease.request", async () => { + const { app, dispatcher } = buildHarness(); + void postLeaseRequest(app, { ...defaultBody, mode: "slim" }); + const call = await waitForDispatch(dispatcher, "lease.request"); + expect(call.input).toMatchObject({ mode: "slim" }); + }); + it("forwards a body's owner field to the dispatched lease.request rather than silently dropping it (ADR §27a, H7)", async () => { // Before this, `leaseRequestBodySchema` had no `owner` field at all, so a caller naming one // was answered as though it had named none -- the same anti-pattern this codebase's own diff --git a/src/http/app.ts b/src/http/app.ts index a7074855a..c1fa0541b 100644 --- a/src/http/app.ts +++ b/src/http/app.ts @@ -62,20 +62,26 @@ type Env = AuthEnv; /** Upper bound on `?wait=` long-polls; bounds how long an abandoned poll can pin resources. */ const MAX_LONG_POLL_SECONDS = 60; -const leaseRequestBodySchema = z.object({ - allowDownload: z.boolean().optional(), - device: z.string().min(1), - full: z.boolean().optional(), - noWait: z.boolean().optional(), - // ADR §27a (H7, round 2 review): declared and forwarded, not silently dropped -- the shared - // dispatcher's own `lease.request` handler is the one place that decides whether this token - // may set it (`FORBIDDEN` for non-admin), the same gate every other transport is held to. - owner: z.string().min(1).optional(), - os: z.string().min(1).optional(), - platform: z.enum(["ios", "android"]), - timeoutMs: z.number().int().positive().optional(), - ttlMs: z.number().int().positive().optional(), -}); +/** + * Strict (ADR 0007 §10): a body carrying a key this route does not know, the retired `full` + * included, is `400 BAD_REQUEST` rather than having it silently dropped. + */ +const leaseRequestBodySchema = z + .object({ + allowDownload: z.boolean().optional(), + device: z.string().min(1), + mode: z.enum(["slim", "full"]).optional(), + noWait: z.boolean().optional(), + // ADR §27a (H7, round 2 review): declared and forwarded, not silently dropped -- the shared + // dispatcher's own `lease.request` handler is the one place that decides whether this token + // may set it (`FORBIDDEN` for non-admin), the same gate every other transport is held to. + owner: z.string().min(1).optional(), + os: z.string().min(1).optional(), + platform: z.enum(["ios", "android"]), + timeoutMs: z.number().int().positive().optional(), + ttlMs: z.number().int().positive().optional(), + }) + .strict(); /** * `POST /v1/leases/{id}/exec`'s body: `device.exec`'s input minus `leaseId`, which the path @@ -115,7 +121,7 @@ function toLeaseRequestInput(body: z.infer): Leas ...(body.timeoutMs === undefined ? {} : { timeoutMs: body.timeoutMs }), ...(body.noWait === undefined ? {} : { noWait: body.noWait }), ...(body.allowDownload === undefined ? {} : { allowDownload: body.allowDownload }), - ...(body.full === undefined ? {} : { full: body.full }), + ...(body.mode === undefined ? {} : { mode: body.mode }), ...(body.owner === undefined ? {} : { owner: body.owner }), }; } diff --git a/src/http/test-fakes.ts b/src/http/test-fakes.ts index 1d141f720..9f9f0f570 100644 --- a/src/http/test-fakes.ts +++ b/src/http/test-fakes.ts @@ -50,7 +50,7 @@ export function testConfig( }, http: { enabled: true, host: "127.0.0.1", port: 4700 }, idle: { deleteAfterMs: 60_000, shutdownAfterMs: 10_000 }, - ios: { slim: { enabled: false, bootTimeoutMs: 600_000 } }, + ios: { defaultMode: "full", slim: { bootTimeoutMs: 600_000 } }, android: { emulator: { headless: false, gpu: "auto", audio: true, bootAnimation: true } }, lease: { defaultTtlMs: 900_000, @@ -215,7 +215,7 @@ export class FakeDispatcher { model: input.model, platform: input.platform, ...(input.osVersion === undefined ? {} : { osVersion: input.osVersion }), - ...(input.full === true ? { full: true } : {}), + ...(input.mode === undefined ? {} : { mode: input.mode }), }; const options = fakeRequestOptions(input, session); const replay = this.requests.replay(request, options); diff --git a/src/http/tracker.test.ts b/src/http/tracker.test.ts index 5e7d53e7f..e3ecf0a40 100644 --- a/src/http/tracker.test.ts +++ b/src/http/tracker.test.ts @@ -29,7 +29,7 @@ const body = { device: "iPhone 17 Pro", platform: "ios" as const }; async function createTracked( tracker: LeaseRequestTracker, dispatcher: FakeDispatcher, - requestBody: typeof body & { readonly ttlMs?: number } = body, + requestBody: typeof body & { readonly ttlMs?: number; readonly mode?: "slim" | "full" } = body, ): Promise<{ readonly view: TrackedRequestView; readonly callIndex: number }> { const outcomePromise = tracker.submit(identity, requestBody); const call = await waitForDispatch(dispatcher, "lease.request"); @@ -276,15 +276,15 @@ describe("LeaseRequestTracker.submit with allowDownload", () => { }); }); -describe("LeaseRequestTracker.submit with full", () => { - it("passes full through onto the dispatch input, and omits it otherwise", async () => { +describe("LeaseRequestTracker.submit with a mode", () => { + it("passes mode through onto the dispatch input, and omits it when the body names none", async () => { const { dispatcher, tracker } = buildTracker(); - await createTracked(tracker, dispatcher, { ...body, full: true } as typeof body); - expect(dispatcher.calls[0]?.input).toMatchObject({ full: true }); + await createTracked(tracker, dispatcher, { ...body, mode: "slim" }); + expect(dispatcher.calls[0]?.input).toMatchObject({ mode: "slim" }); const { dispatcher: dispatcher2, tracker: tracker2 } = buildTracker(); await createTracked(tracker2, dispatcher2); - expect(dispatcher2.calls[0]?.input).not.toHaveProperty("full"); + expect(dispatcher2.calls[0]?.input).not.toHaveProperty("mode"); }); }); diff --git a/src/http/tracker.ts b/src/http/tracker.ts index 75ef9e620..52a18b97d 100644 --- a/src/http/tracker.ts +++ b/src/http/tracker.ts @@ -14,7 +14,7 @@ export interface LeaseRequestInput { readonly timeoutMs?: number; readonly noWait?: boolean; readonly allowDownload?: boolean; - readonly full?: boolean; + readonly mode?: "slim" | "full"; /** ADR §27a. Threaded straight through to the shared dispatcher's own `lease.request` input -- * the same gate every other transport is held to (`FORBIDDEN` for a non-admin token) decides * this, not this route (H7, round 2 review: before this, `leaseRequestBodySchema` had no @@ -208,7 +208,7 @@ export class LeaseRequestTracker { model: body.device, platform: body.platform, ...(body.os === undefined ? {} : { osVersion: body.os }), - ...(body.full === undefined ? {} : { full: body.full }), + ...(body.mode === undefined ? {} : { mode: body.mode }), ...(body.noWait === undefined ? {} : { noWait: body.noWait }), ...(body.allowDownload === undefined ? {} : { allowDownload: body.allowDownload }), ...(body.timeoutMs === undefined ? {} : { timeoutMs: body.timeoutMs }), @@ -337,9 +337,8 @@ type HttpLeaseProgress = /** * Structural subsets of the *contract's* `lease.request` output shape (`z.infer` * -- see `schemas.ts`), not core's `DeviceRecord`/`LeaseRecord`: `dispatch()` always returns - * contract-shaped data (e.g. `spec.full` is optional there, since the schema declares it - * `.optional()`, where core's own `DeviceSpec.full` is not), and this module never imports core - * domain types at all -- everything it needs from a grant is these few fields. + * contract-shaped data, which need not match core's own types field for field, and this module + * never imports core domain types at all -- everything it needs from a grant is these few fields. */ interface HttpLeaseDevice { readonly id: string; diff --git a/src/mcp/contracts.test.ts b/src/mcp/contracts.test.ts index bd4ccbea3..1cf311f76 100644 --- a/src/mcp/contracts.test.ts +++ b/src/mcp/contracts.test.ts @@ -27,14 +27,20 @@ describe("MCP contracts", () => { ).toThrow(); }); - it("rejects mode, which ADR 0004 removed from the contract entirely", () => { - expect(() => - leaseSimulatorInputSchema.parse({ - model: "iPhone 17 Pro", - platform: "ios", - mode: "detached", - }), - ).toThrow(); + it("accepts a device mode", () => { + expect( + leaseSimulatorInputSchema.parse({ model: "iPhone 17 Pro", mode: "slim", platform: "ios" }), + ).toEqual({ model: "iPhone 17 Pro", mode: "slim", platform: "ios" }); + }); + + it.each([ + ["full", { full: true }], + ["a mode other than slim or full", { mode: "detached" }], + ])("rejects %s", (_label, extra) => { + expect( + leaseSimulatorInputSchema.safeParse({ model: "iPhone 17 Pro", platform: "ios", ...extra }) + .success, + ).toBe(false); }); it("accepts ttlMs, which ADR 0004 allows on every lease request", () => { diff --git a/src/mcp/contracts.ts b/src/mcp/contracts.ts index 3c98149aa..b164c070c 100644 --- a/src/mcp/contracts.ts +++ b/src/mcp/contracts.ts @@ -23,8 +23,8 @@ import { leaseRecordSchema, OPERATIONS } from "../contract/index.js"; * caller-supplied, for the same reason the daemon never lets a request rename its own * principal). `ttlMs` is no longer omitted: ADR 0004 accepts it on every request, so this tool * inherits it from the contract like every other field -- `lease.defaultTtlMs` when the caller - * names none, `BAD_REQUEST` above `lease.maxTtlMs`. `mode` is gone from the contract itself, - * and with it the `superRefine` wrapper that used to need unwrapping before `.omit()`. + * names none, `BAD_REQUEST` above `lease.maxTtlMs`. `mode` is the device mode, inherited the + * same way: `slim` or `full`, absent for the worker's default, anything else `BAD_REQUEST`. */ export const leaseSimulatorInputSchema = OPERATIONS["lease.request"].input.omit({ requesterId: true,