diff --git a/docs/CLI.md b/docs/CLI.md index 9bb24715b..be6bb3917 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -250,6 +250,18 @@ granted. leases for the same missing runtime share one download. The whole wait, queued download included, counts against `downloads.timeoutMs`; running out is `DOWNLOAD_TIMEOUT` (exit 10). Through a gateway the flag has no effect. + On Android it downloads only a level with no image installed at all, and + only when the `google_apis` image for the host would fit the model: a lease + for a TV at an uninstalled level, or for any model at an installed level + whose images do not fit it, fails with `RUNTIME_MISSING` (exit 12, + `downloadable` `false`) and downloads nothing. The message is `No installed + system image fits at Android : ` (without ` at Android + ` when `--os` is not given). The reason is the first of these that rules + out every image: `it needs Android or newer` (or `older`), `it needs a TV + image` (or Wear OS, automotive, desktop, XR, AI glasses, `phone or tablet`, or + `an image tagged `), ` does not take Play Store images`, ` + does not take tablet images`, else `none of the installed images fit it`; or + `Android is not installed`, or `no system image is installed`. - `--ttl ` — the lease's initial TTL, replacing `lease.defaultTtlMs` (15m) for this lease. Asking for more than `lease.maxTtlMs` (4h) is a `BAD_REQUEST` (exit 2), not a silent clamp. See @@ -298,8 +310,10 @@ granted. the host's ABI first; without `--os` the lease gets the newest API level that has one. A lease with `--image-tag` never downloads: if no image of that tag is installed for the API level it fails with `RUNTIME_MISSING` (exit 12), - `--allow-download` or not. Install other image types with `sdkmanager`. A - lease only reuses an idle device created for the same tag, or for no tag + `--allow-download` or not. The image must also fit the model: if the image + of that tag does not, the lease fails with `RUNTIME_MISSING`, `downloadable` + `false`, saying `the image does not fit it` and why. Install other image + types with `sdkmanager`. A lease only reuses an idle device created for the same tag, or for no tag when it names none. On iOS the flag is a `BAD_REQUEST` (exit 2). A tag is 1 to 64 letters, digits, `_`, `.` or `-`. Through a gateway, a lease whose tag no worker lists for that API level, an iOS one included, fails at once with @@ -495,7 +509,10 @@ forward) is gone whether or not recovery succeeds. A lease names its device in one of three ways: - `--device ` asks for exactly that model. It is granted an idle device - of that model, OS, mode and image tag, as always. + of that model, OS, mode and image tag, as always. On Android an idle device on + a level that no longer fits the model (a TV made on a phone image) is not + reused by a lease that names the model; a class or `--os` range lease can + still pick it until idle cleanup removes it. - `--class ` asks for any model of that class. - With neither, the lease asks for a `phone`. @@ -892,9 +909,7 @@ matches when its model and runtime fit and its mode fits the request: with `--mode full` it must be a `full` device, with `--mode slim` a `slim` one, and with no `--mode` it must be one that `status` shows as serving the default mode (see [`simlock status`](#simlock-status)). With no `--os`, the runtime must be the one -the worker would pick: its default runtime when the model pairs with it, -otherwise the model's only paired runtime. A worker whose model pairs with -several runtimes and no default has no warm match for such a request. A request +the worker would pick: the newest runtime the model pairs with. A request with no warm match goes to a machine with free capacity, which boots a device. Otherwise a worker with no free running slot is passed over (a running device nobody has leased counts as free), a worker under its RAM budget @@ -1564,8 +1579,17 @@ installed, which installed runtime is the default (the newest), and for each model the installed runtimes it pairs with (`modelRuntimes`). A model and a runtime that are both listed can still fail to pair — on iOS, a runtime can drop an older model — so pick a pair from `modelRuntimes`. A model with an -empty list pairs with nothing installed. On Android every model pairs with -every installed API level. +empty list pairs with nothing installed. On Android a model pairs with an +installed API level only when an image there fits the model, as Android Studio +would offer it: the image is for the same kind of device (a TV takes `android-tv` +or `google-tv`, a phone takes none of the TV, Wear OS, automotive, desktop, XR +(except `android-xr-ost`), glasses or ChromeOS images), its API level is in the model's range (Pixel 9 +needs Android 35 or newer), a Play Store image only goes with a model that +allows Play Store (Pixel 6 does not), and a `tablet` image only with a tablet +model. `runtimes`, `defaultRuntime` and `images` still list every installed +image, so a level can be listed there and absent from every `modelRuntimes` +list. A custom model made in Android Studio but not listed by `avdmanager` pairs +with every installed level for now. `modelAliases` lists, for a model, the other names `--device` accepts for it on that machine; a model with no other name has no entry. On Android a diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index af72f8bdd..916ea9c17 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -39,7 +39,7 @@ edit yourself keeps the mode you give it until the next `config set`; run | `agentDevice.leaseTtlCapMs` | **Worker side.** Caps the TTL of the leases the agent-device CLI makes and renews through Simlock: a longer `ttlMs` is lowered to it, and a lease that sends none gets it. A whole number of milliseconds from `5000` to `lease.maxTtlMs`; a value outside that range stops the daemon at start. Used only when `agentDevice.enabled` is `true`. | unset (no cap) | | `agentDevice.command` | **Worker side.** The agent-device executable: a name looked up on `PATH`, or a path. Used only when `agentDevice.enabled` is `true`. | `agent-device` | | `exec.timeoutMs` | **Worker side.** How long one `device.exec` command (`simlock simctl` / `simlock adb` against a gateway or over HTTP) may run before the worker kills it and the operation fails with `EXEC_TIMEOUT`. Authoritative: it bounds the process that actually runs. | `10 minutes` | -| `gateway.routing` | **Gateway side.** Which routing policy places a queued request on a worker. `warm-then-free` is the only policy in v1. Among the workers that can serve the request, in order: a worker whose health is not `running`, or that has requests of its own waiting, is left out; a worker holding a ready device that fits goes first (the device's mode must fit the request, a request with no mode fits a device that serves the worker's default mode, and its runtime must be the one requested or, with none requested, the one the worker would pick: its default runtime if the model pairs with it, otherwise the only runtime the model pairs with); otherwise a worker with no free running slot for the platform or overall is left out (a running device that is not leased counts as free: the worker shuts it down to make room), a worker under its RAM budget for the platform is preferred over one at it (a worker at its budget is still asked when it is the only one left), and the one with the most free running capacity for the platform wins. A worker that is left out is busy, not unable: the request waits for it. Ties go to the lowest worker id. | `warm-then-free` | +| `gateway.routing` | **Gateway side.** Which routing policy places a queued request on a worker. `warm-then-free` is the only policy in v1. Among the workers that can serve the request, in order: a worker whose health is not `running`, or that has requests of its own waiting, is left out; a worker holding a ready device that fits goes first (the device's mode must fit the request, a request with no mode fits a device that serves the worker's default mode, and its runtime must be the one requested or, with none requested, the one the worker would pick: the newest runtime the model pairs with); otherwise a worker with no free running slot for the platform or overall is left out (a running device that is not leased counts as free: the worker shuts it down to make room), a worker under its RAM budget for the platform is preferred over one at it (a worker at its budget is still asked when it is the only one left), and the one with the most free running capacity for the platform wins. A worker that is left out is busy, not unable: the request waits for it. Ties go to the lowest worker id. | `warm-then-free` | | `gateway.disconnectedRetentionMs` | **Gateway side.** How long a disconnected worker is kept (greyed, never dispatched to) before the gateway forgets it. The clock is held while the gateway still knows of gateway-issued leases on that worker, and that hold ends when the last of those leases passes its deadline. | `24 hours` | | `gateway.execTimeoutMs` | **Gateway side.** How long the gateway waits on a proxied `device.exec` before giving up. A backstop for a worker that never answers at all — deliberately longer than the worker's own `exec.timeoutMs`, which is authoritative because that side owns the process and can kill it, so an ordinary timeout surfaces as the worker's `EXEC_TIMEOUT` rather than racing this one. | `11 minutes` | | `gateway.leaseRequestTimeoutMs` | **Gateway side.** How long the gateway waits on a forwarded `lease.request` before giving up on that worker for this request, answering `WORKER_UNREACHABLE`. Bounds the one uplink call that otherwise had no timeout of its own, so a wedged worker cannot park a request where neither a deadline nor `lease.cancel` could ever reach it again. Generous against a cold device provision-plus-boot; well below `gateway.execTimeoutMs`, since granting a lease should never take as long as a command run against the device afterward. | `5 minutes` | diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 0805b55fe..5f380e83c 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -702,9 +702,7 @@ The v1 policy (`warm-then-free`) is eight stages: worker's own catalog: its own name for an exact model, or the class with the worker's `modelClasses` as `classOf`. The OS is the one requested or the range requested; with none requested, an exact model needs the runtime - the worker would pick (the catalog's `defaultRuntime` when the model pairs - with it, otherwise its only paired runtime; none when several pair and no - default does) and a class accepts any installed runtime. The mode must + the worker would pick (the newest runtime the model pairs with) and a class accepts any installed runtime. The mode must fit (ADR 0009 §6): `full` needs a device reporting `mode: "full"`, `slim` one reporting `slim`, and a request naming none a device reporting `servesDefaultMode`, which the worker computes in diff --git a/src/core/doctor.test.ts b/src/core/doctor.test.ts index 2a5494bf5..fcd82abe1 100644 --- a/src/core/doctor.test.ts +++ b/src/core/doctor.test.ts @@ -3335,6 +3335,7 @@ describe("Doctor: warm pool targets", () => { readonly enabled?: boolean; readonly limit?: { ios?: number; android?: number; global?: number }; readonly figures?: ReturnType; + readonly driver?: Omit[0], "clock">; }): Promise { const clock = new FakeClock(10_000); const eventBus = new EventBus(clock); @@ -3352,7 +3353,7 @@ describe("Doctor: warm pool targets", () => { targets: options.targets ?? [], }, }, - drivers: [new FakeDriver({ clock, platform: "ios" })], + drivers: [new FakeDriver({ clock, platform: "ios", ...options.driver })], eventBus, registry, warmPool: { @@ -3384,6 +3385,53 @@ describe("Doctor: warm pool targets", () => { ]); }); + it.each([ + ["ios", "iOS", "iPhone 17", ["18.0", "26.0"], "26.0"], + ["android", "Android", "Television (1080p)", ["34", "35"], "35"], + ] as const)( + "names simlock catalog, not component install, for an installed %s version the target's model does not pair with", + async (platform, name, model, runtimes, unpaired) => { + const found = await findings({ + driver: { + availableOsVersions: [...runtimes], + knownModels: [model], + modelRuntimes: { [model]: runtimes.filter((runtime) => runtime !== unpaired) }, + platform, + }, + figures: figuresOf([{ model, osVersion: unpaired, platform, short: "runtime-missing" }]), + }); + + expect(found).toStrictEqual([ + { + kind: "warm-pool-target-unreachable", + message: `${model} does not pair with ${name} ${unpaired}`, + platform, + reason: "runtime-missing", + remedy: `run simlock catalog --platform ${platform}`, + target: `${model} / ${unpaired} / full`, + }, + ]); + }, + ); + + it("keeps the install text for a version the platform's catalog does not list", async () => { + const found = await findings({ + driver: { + availableOsVersions: ["26.0"], + knownModels: ["iPhone 17"], + platform: "ios", + }, + figures: figuresOf([{ model: "iPhone 17", osVersion: "27.0", short: "runtime-missing" }]), + }); + + expect(found).toStrictEqual([ + expect.objectContaining({ + message: "iOS 27.0 is not installed", + remedy: "run simlock component install ios 27.0", + }), + ]); + }); + it("reports a target short with unknown-model as unreachable", async () => { const found = await findings({ figures: figuresOf([{ model: "iPhone 99", osVersion: "26.0", short: "unknown-model" }]), diff --git a/src/core/doctor.ts b/src/core/doctor.ts index ef00d4602..dc55dc08e 100644 --- a/src/core/doctor.ts +++ b/src/core/doctor.ts @@ -15,6 +15,7 @@ import type { DeviceOperationClaims } from "./device-operation-claims.js"; import type { StartupRead } from "./startup-read.js"; import { type Driver, + type DriverCatalogEntry, type DriverDevice, type DriverRejection, type DriverReality, @@ -253,7 +254,7 @@ export class Doctor { const remaining = [ ...(purgeOrphans ? await this.#purgeOrphans(findings, driversByPlatform) : findings), ...(await this.#collectPrerequisites(prerequisites)), - ...this.#warmPoolFindings(), + ...(await this.#warmPoolFindings()), ...this.#optionalModuleFindings(), ]; @@ -578,6 +579,27 @@ export class Doctor { } } + async #catalogsOfMissingRuntimes( + targets: readonly WarmTargetFigures[], + ): Promise> { + const catalogs = new Map(); + const platforms = new Set( + targets.filter((target) => target.short === "runtime-missing").map((t) => t.platform), + ); + for (const driver of this.options.drivers) { + if (!platforms.has(driver.platform)) continue; + try { + catalogs.set(driver.platform, await driver.listCatalog()); + } catch (error) { + this.#logger.warn("Could not read a catalog for a warm pool finding", { + error: errorMessage(error), + platform: driver.platform, + }); + } + } + return catalogs; + } + /** * The warm pool's targets that cannot be met as configured: those the last pass found a runtime * or a model missing for, and the platforms (or the machine) whose targets add up to more than @@ -585,12 +607,16 @@ export class Doctor { * `prerequisite-missing`. A target short for RAM, the device limit or a failed boot is no * finding: those pass with time or with an operator's choice of machine. None with the pool off. */ - #warmPoolFindings(): DoctorFinding[] { + async #warmPoolFindings(): Promise { const { warmPool } = this.options; const { enabled, targets } = this.options.config.warmPool; if (warmPool === undefined || !enabled) return []; const limits = warmPool.runningCapacity(); - const findings = warmPool.figures().targets.flatMap(unreachableTarget); + const figures = warmPool.figures().targets; + const catalogs = await this.#catalogsOfMissingRuntimes(figures); + const findings = figures.flatMap((target) => + unreachableTarget(target, catalogs.get(target.platform)), + ); const reserves = reservedRunning(this.options.config.warmPool, limits); let wanted = 0; for (const platform of ["ios", "android"] as const) { @@ -1075,8 +1101,11 @@ function isRange(osVersion: string): boolean { return parsed.ok && parsed.constraint.kind === "range"; } -/** A warm target the last pass could find no runtime or no model for, as a finding. */ -function unreachableTarget(target: WarmTargetFigures): DoctorFinding[] { +// fallow-ignore-next-line complexity -- one finding per short reason, each a fixed message. +function unreachableTarget( + target: WarmTargetFigures, + catalog: DriverCatalogEntry | undefined, +): DoctorFinding[] { const { model, osVersion, platform, short } = target; const named = [model, osVersion, target.mode].filter((part) => part !== undefined).join(" / "); const name = PLATFORM_NAMES[platform]; @@ -1094,6 +1123,24 @@ function unreachableTarget(target: WarmTargetFigures): DoctorFinding[] { }, ]; } + if ( + model !== undefined && + osVersion !== undefined && + catalog?.runtimes.includes(osVersion) === true && + catalog.modelRuntimes[model] !== undefined && + !catalog.modelRuntimes[model].includes(osVersion) + ) { + return [ + { + kind: "warm-pool-target-unreachable", + message: `${model} does not pair with ${name} ${osVersion}`, + platform, + reason: short, + remedy: `run simlock catalog --platform ${platform}`, + target: named, + }, + ]; + } return [ { kind: "warm-pool-target-unreachable", diff --git a/src/drivers/android/device-profile-source.test.ts b/src/drivers/android/device-profile-source.test.ts index dd5573ee2..e23c8e85a 100644 --- a/src/drivers/android/device-profile-source.test.ts +++ b/src/drivers/android/device-profile-source.test.ts @@ -31,6 +31,23 @@ describe("BuiltinDeviceProfileSource", () => { ]); }); + it("keeps a profile's raw Tag value as tag, besides the class it maps to", async () => { + const runner = new ScriptedProcessRunner([ + processResult( + `Available devices:\nid: 0 or "tv_sdk"\n Name: Sdk TV\n OEM : Google\n Tag : google-tv\n---------\n` + + `id: 1 or "glasses"\n Name: Glasses\n OEM : Google\n Tag : ai-glasses\n`, + ), + ]); + const source = new BuiltinDeviceProfileSource(avdmanager, runner); + + const profiles = await source.profiles(); + + expect(profiles.map((profile) => [profile.name, "tag" in profile && profile.tag])).toEqual([ + ["Sdk TV", "google-tv"], + ["Glasses", "ai-glasses"], + ]); + }); + it("marks a profile custom only when avdmanager lists it with OEM : User", async () => { const runner = new ScriptedProcessRunner([ processResult( diff --git a/src/drivers/android/device-profile-source.ts b/src/drivers/android/device-profile-source.ts index 62eca3610..a8306a91f 100644 --- a/src/drivers/android/device-profile-source.ts +++ b/src/drivers/android/device-profile-source.ts @@ -10,6 +10,7 @@ export type DeviceProfile = readonly custom: boolean; /** From the entry's `Tag :` line (ADR 0015 §3); `undefined` for a tag the table does not know. */ readonly deviceClass: DeviceClass | undefined; + readonly tag?: string | undefined; } | { readonly kind: "library"; @@ -89,6 +90,14 @@ export class DeviceProfileRegistry { * always has. A profile's other names are listed only where they resolve to that profile. */ async catalog(): Promise { + return (await this.catalogWithProfiles()).catalog; + } + + // fallow-ignore-next-line complexity -- the catalog is one pass over the listed profiles. + async catalogWithProfiles(): Promise<{ + readonly catalog: DeviceProfileCatalog; + readonly modelProfiles: ReadonlyMap; + }> { const profiles = await this.#profiles(); const listed = new Map(); for (const profile of profiles) { @@ -118,7 +127,15 @@ export class DeviceProfileRegistry { const deviceClass = profile.kind === "properties" ? "phone" : profile.deviceClass; if (deviceClass !== undefined) modelClasses[profile.name] = deviceClass; } - return { customModels, modelAliases, modelClasses, models }; + const modelProfiles = new Map(); + for (const model of models) { + const profile = matchProfile(profiles, model); + if (profile !== undefined) modelProfiles.set(model, profile); + } + return { + catalog: { customModels, modelAliases, modelClasses, models }, + modelProfiles, + }; } /** @@ -200,6 +217,7 @@ export class BuiltinDeviceProfileSource implements DeviceProfileSource { profile.id.toLocaleLowerCase() === profile.name.toLocaleLowerCase() ? [profile.name] : [profile.name, profile.id], + tag: profile.tag, }), ); return [ diff --git a/src/drivers/android/image-fit.test.ts b/src/drivers/android/image-fit.test.ts new file mode 100644 index 000000000..62b3ac77f --- /dev/null +++ b/src/drivers/android/image-fit.test.ts @@ -0,0 +1,184 @@ +import { describe, expect, it } from "vitest"; + +import type { DeviceProfile } from "./device-profile-source.js"; +import { fits, type ImageFitInput } from "./image-fit.js"; +import { LIBRARY_PROFILES } from "./profiles/index.js"; + +function library(id: string) { + const profile = LIBRARY_PROFILES.find((candidate) => candidate.id === id); + if (profile === undefined) throw new Error(`the library has no profile with id ${id}`); + return profile; +} + +function image(apiLevel: string, tag: string, extra: Partial = {}): ImageFitInput { + return { apiLevel, tag, tags: [tag], ...extra }; +} + +function builtin(id: string, tag: string | undefined, custom = false): DeviceProfile { + return { + avdmanagerId: id, + custom, + deviceClass: undefined, + kind: "builtin", + name: id, + names: [id], + ...(tag === undefined ? {} : { tag }), + }; +} + +const NON_PHONE_TAGS = [ + "android-wear", + "android-desktop", + "android-tv", + "google-tv", + "android-automotive", + "android-automotive-playstore", + "android-automotive-distantdisplay", + "android-xr", + "android-xr-glasses", + "ai-glasses", + "chromeos", +]; + +describe("fits", () => { + it("a TV profile fits android-tv and google-tv images and no phone image", () => { + const tv = library("tv_1080p"); + + expect(fits(tv, image("34", "android-tv"))).toBe(true); + expect(fits(tv, image("34", "google-tv"))).toBe(true); + expect(fits(tv, image("34", "google_apis"))).toBe(false); + expect(fits(tv, image("34", "default"))).toBe(false); + }); + + it.each([ + ["wearos_large_round", "android-wear"], + ["automotive_1080p_landscape", "android-automotive"], + ["desktop_medium", "android-desktop"], + ])("the %s profile fits only images with its exact tag", (id, tag) => { + const profile = library(id); + + expect(fits(profile, image("34", tag))).toBe(true); + expect(fits(profile, image("34", "google_apis"))).toBe(false); + expect(fits(profile, image("34", "android-tv"))).toBe(false); + }); + + it.each(["android-automotive-playstore", "android-automotive-distantdisplay"])( + "the android-automotive tag does not fit an image tagged %s that shares its prefix", + (tag) => { + expect(fits(builtin("auto", "android-automotive"), image("34", tag))).toBe(false); + }, + ); + + it.each(NON_PHONE_TAGS)("a profile with no kind does not fit a %s image", (tag) => { + expect(fits(library("medium_phone"), image("34", "google_apis"))).toBe(true); + expect(fits(library("medium_phone"), image("34", tag))).toBe(false); + }); + + it("an image below a profile's API range does not fit", () => { + const pixel9 = library("pixel_9"); + + expect(fits(pixel9, image("35", "google_apis"))).toBe(true); + expect(fits(pixel9, image("34", "google_apis"))).toBe(false); + }); + + it("an image above a profile's API range max does not fit", () => { + const bounded = { ...library("medium_phone"), apiRange: { max: 33, min: 24 } }; + + expect(fits(bounded, image("33", "google_apis"))).toBe(true); + expect(fits(bounded, image("34", "google_apis"))).toBe(false); + }); + + it("a 36.1 folder level counts as 36", () => { + const capped = { ...library("medium_phone"), apiRange: { max: 36, min: 36 } }; + + expect(fits(capped, image("36.1", "google_apis"))).toBe(true); + expect(fits(capped, image("37.1", "google_apis"))).toBe(false); + }); + + it("android-Baklava with AndroidVersion.ApiLevel=35 fits Pixel 9", () => { + const pixel9 = library("pixel_9"); + + expect(fits(pixel9, image("Baklava", "google_apis", { sourceApiLevel: "35" }))).toBe(true); + expect(fits(pixel9, image("Baklava", "google_apis", { sourceApiLevel: "34" }))).toBe(false); + }); + + it("an image with no number fits only a profile with no range", () => { + const unnumbered = image("Baklava", "google_apis"); + + expect(fits(library("pixel_9"), unnumbered)).toBe(false); + expect(fits(builtin("pixel_9_pro", undefined), unnumbered)).toBe(true); + }); + + it.each(["ai-glasses", "android-xr-glasses"])( + "a profile tagged %s fits both glasses image tags and no phone image", + (profileTag) => { + const glasses = builtin("glasses", profileTag); + + expect(fits(glasses, image("36", "ai-glasses"))).toBe(true); + expect(fits(glasses, image("36", "android-xr-glasses"))).toBe(true); + expect(fits(glasses, image("36", "google_apis"))).toBe(false); + }, + ); + + it("xr_glasses_device fits only android-xr-ost", () => { + const xr = builtin("xr_glasses_device", "android-xr-glasses"); + + expect(fits(xr, image("36", "android-xr-ost"))).toBe(true); + expect(fits(xr, image("36", "ai-glasses"))).toBe(false); + expect(fits(xr, image("36", "android-xr-glasses"))).toBe(false); + }); + + it("a phone profile fits an android-xr-ost image", () => { + expect(fits(library("medium_phone"), image("36", "android-xr-ost"))).toBe(true); + }); + + it("a Play Store image does not fit a profile that disallows Play Store", () => { + const playStore = image("35", "google_apis_playstore"); + + expect(fits(library("pixel_6"), playStore)).toBe(false); + expect(fits(library("pixel_6"), image("35", "google_apis"))).toBe(true); + }); + + it("a Play Store image fits a profile that allows Play Store", () => { + expect(fits(library("medium_phone"), image("35", "google_apis_playstore"))).toBe(true); + }); + + it("an Automotive (1024p landscape) profile fits a single-tag android-automotive-playstore image as a Play Store image", () => { + const profile = library("automotive_1024p_landscape"); + const playStore = image("34", "android-automotive-playstore"); + + expect(fits(profile, playStore)).toBe(true); + expect(fits({ ...profile, playStore: false }, playStore)).toBe(false); + }); + + it("a tablet image fits only a tablet profile", () => { + for (const tag of ["tablet", "aosp_tablet"]) { + expect(fits(library("medium_tablet"), image("35", tag))).toBe(true); + expect(fits(library("medium_phone"), image("35", tag))).toBe(false); + } + }); + + it("an SDK or custom profile fits by its Tag value with no API range and Play Store allowed", () => { + const tv = builtin("tv_sdk", "android-tv"); + const phone = builtin("My Phone", undefined, true); + + expect(fits(tv, image("19", "android-tv"))).toBe(true); + expect(fits(tv, image("19", "google_apis"))).toBe(false); + expect(fits(phone, image("19", "google_apis_playstore"))).toBe(true); + expect(fits(phone, image("19", "android-tv"))).toBe(false); + expect(fits(phone, image("19", "tablet"))).toBe(false); + }); + + it("a devices.xml profile avdmanager did not list fits every image", () => { + const properties: DeviceProfile = { + hardwareProperties: {}, + kind: "properties", + name: "Legacy", + names: ["Legacy"], + }; + + for (const tag of ["android-tv", "google_apis_playstore", "tablet", "android-wear"]) { + expect(fits(properties, image("Baklava", tag))).toBe(true); + } + }); +}); diff --git a/src/drivers/android/image-fit.ts b/src/drivers/android/image-fit.ts index c16c78647..b15ddbdeb 100644 --- a/src/drivers/android/image-fit.ts +++ b/src/drivers/android/image-fit.ts @@ -1,5 +1,8 @@ +import type { DeviceProfile } from "./device-profile-source.js"; + export interface ImageFitInput { readonly apiLevel: string; + readonly sourceApiLevel?: string | undefined; readonly tag: string; readonly tags: readonly string[]; } @@ -17,3 +20,141 @@ export function isPlayStoreImage(image: ImageFitInput): boolean { Number(image.apiLevel) >= MIN_WEAR_PLAY_STORE_API ); } + +type FitCheck = "apiRange" | "kind" | "playStore" | "tablet"; + +const FIT_CHECK_ORDER: readonly FitCheck[] = ["apiRange", "kind", "playStore", "tablet"]; + +const TV_TAGS = ["android-tv", "google-tv"]; +const GLASSES_TAGS = ["ai-glasses", "android-xr-glasses"]; +const XR_GLASSES_PROFILE_ID = "xr_glasses_device"; +const TABLET_TAGS = ["tablet", "aosp_tablet"]; + +const NON_PHONE_TAGS = [ + "android-wear", + "android-desktop", + "android-tv", + "google-tv", + "android-automotive", + "android-automotive-playstore", + "android-automotive-distantdisplay", + "android-xr", + "android-xr-glasses", + "ai-glasses", + "chromeos", +]; + +interface ProfileFacts { + readonly apiRange: { readonly min: number; readonly max?: number } | undefined; + readonly kind: string | undefined; + readonly playStore: boolean; + readonly tablet: boolean; + readonly profileId: string | undefined; +} + +function factsOf(profile: DeviceProfile): ProfileFacts | undefined { + switch (profile.kind) { + case "library": + return { + apiRange: profile.apiRange, + kind: profile.imageKind, + playStore: profile.playStore, + profileId: profile.id, + tablet: profile.tablet, + }; + case "builtin": + return { + apiRange: undefined, + kind: profile.tag, + playStore: true, + profileId: profile.avdmanagerId, + tablet: false, + }; + case "properties": + return undefined; + } +} + +function imageApiLevel(image: ImageFitInput): number | undefined { + for (const candidate of [image.sourceApiLevel, image.apiLevel]) { + const match = /^(\d+)/.exec(candidate ?? ""); + if (match?.[1] !== undefined) return Number(match[1]); + } + return undefined; +} + +function kindFits(facts: ProfileFacts, image: ImageFitInput): boolean { + const has = (tags: readonly string[]): boolean => tags.some((tag) => image.tags.includes(tag)); + const { kind } = facts; + if (facts.profileId === XR_GLASSES_PROFILE_ID) return has(["android-xr-ost"]); + if (kind === undefined) return !has(NON_PHONE_TAGS); + if (TV_TAGS.includes(kind)) return has(TV_TAGS); + if (GLASSES_TAGS.includes(kind)) return has(GLASSES_TAGS); + return has([kind]); +} + +// fallow-ignore-next-line complexity -- the four fit checks are one pass over one profile and image. +function failedChecks(profile: DeviceProfile, image: ImageFitInput): FitCheck[] { + const facts = factsOf(profile); + if (facts === undefined) return []; + const failed = new Set(); + if (facts.apiRange !== undefined) { + const level = imageApiLevel(image); + if ( + level === undefined || + level < facts.apiRange.min || + (facts.apiRange.max !== undefined && level > facts.apiRange.max) + ) { + failed.add("apiRange"); + } + } + if (!kindFits(facts, image)) failed.add("kind"); + if (!facts.playStore && isPlayStoreImage(image)) failed.add("playStore"); + if (!facts.tablet && image.tags.some((tag) => TABLET_TAGS.includes(tag))) failed.add("tablet"); + return FIT_CHECK_ORDER.filter((check) => failed.has(check)); +} + +export function fits(profile: DeviceProfile, image: ImageFitInput): boolean { + return failedChecks(profile, image).length === 0; +} + +function kindName(kind: string | undefined): string { + if (kind === undefined) return "a phone or tablet image"; + if (TV_TAGS.includes(kind)) return "a TV image"; + if (kind === "android-wear") return "a Wear OS image"; + if (kind.startsWith("android-automotive")) return "an automotive image"; + if (kind === "android-desktop") return "a desktop image"; + if (kind.startsWith("android-xr") && !GLASSES_TAGS.includes(kind)) return "an XR image"; + if (GLASSES_TAGS.includes(kind)) return "an AI glasses image"; + return `an image tagged ${kind}`; +} + +export function misfitReason( + profile: DeviceProfile, + images: readonly ImageFitInput[], +): string | undefined { + const facts = factsOf(profile); + if (facts === undefined || images.length === 0) return undefined; + const failures = images.map((image) => failedChecks(profile, image)); + const check = FIT_CHECK_ORDER.find((candidate) => + failures.every((failed) => failed.includes(candidate)), + ); + switch (check) { + case "apiRange": { + const range = facts.apiRange; + const level = imageApiLevel(images[0] as ImageFitInput); + if (range?.max !== undefined && level !== undefined && level > range.max) { + return `it needs Android ${range.max} or older`; + } + return `it needs Android ${range?.min} or newer`; + } + case "kind": + return `it needs ${kindName(facts.profileId === XR_GLASSES_PROFILE_ID ? "android-xr-ost" : facts.kind)}`; + case "playStore": + return `${profile.name} does not take Play Store images`; + case "tablet": + return `${profile.name} does not take tablet images`; + case undefined: + return undefined; + } +} diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 1e4760819..750fa0f90 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -73,6 +73,17 @@ function libraryClasses(extra: Record): Record { return { ...Object.fromEntries(LIBRARY_PROFILES.map((p) => [p.name, p.deviceClass])), ...extra }; } +const withoutNonPhoneImages: Record = { + "Automotive (1024p landscape)": [], + "Automotive (1080p landscape)": [], + "Medium Desktop": [], + "Large Desktop": [], + "Television (1080p)": [], + "Television (4K)": [], + "Wear OS Large Round": [], + "Wear OS Small Round": [], +}; + function libraryRuntimes( runtimes: string[], extra: Record, @@ -1266,13 +1277,18 @@ describe("AndroidDriver", () => { ], modelAliases: libraryAliases({ "Pixel 5": ["pixel_5"] }), modelClasses: libraryClasses({ "Pixel 5": "phone" }), - modelRuntimes: libraryRuntimes(["34", "35"], { "Pixel 5": ["34", "35"] }), + modelRuntimes: libraryRuntimes(["34", "35"], { + ...withoutNonPhoneImages, + "Pixel 5": ["34", "35"], + "Pixel 9": ["35"], + "Pixel 9 Pro XL": ["35"], + }), models: [...libraryModels, "Pixel 5"], runtimes: ["34", "35"], }); }); - it("pairs every model with every installed API level, including one whose only image has a foreign ABI", async () => { + it("pairs a model with an installed API level whose only image has a foreign ABI, when the image fits", async () => { // The host is arm64-v8a; API 33 is installed only as x86_64. const filesystem = await androidFilesystem({ images: [ @@ -1289,7 +1305,13 @@ describe("AndroidDriver", () => { expect(catalog.models).toEqual([...libraryModels, "Pixel 5"]); expect(catalog.modelRuntimes).toEqual( - libraryRuntimes(["33", "35"], { "Pixel 5": ["33", "35"] }), + libraryRuntimes(["33", "35"], { + ...withoutNonPhoneImages, + "Pixel 5": ["33", "35"], + "Pixel 8": ["35"], + "Pixel 9": ["35"], + "Pixel 9 Pro XL": ["35"], + }), ); }); @@ -1310,7 +1332,7 @@ describe("AndroidDriver", () => { const pairs = Object.entries(catalog.modelRuntimes).flatMap(([model, runtimes]) => runtimes.map((osVersion) => ({ model, osVersion })), ); - expect(pairs).toHaveLength((libraryModels.length + 1) * 2); + expect(pairs.length).toBeGreaterThan(0); for (const { model, osVersion } of pairs) { await expect(driver.resolveSpec({ model, osVersion, platform: "android" })).resolves.toEqual({ @@ -1381,7 +1403,16 @@ describe("AndroidDriver", () => { }); it("resolves every listed name of every listed model, in upper and lower case, to that model", async () => { - const filesystem = await androidFilesystem(); + const filesystem = await androidFilesystem({ + images: [ + ["36", "google_apis", "arm64-v8a"], + ["36", "android-tv", "arm64-v8a"], + ["36", "android-wear", "arm64-v8a"], + ["36", "android-automotive", "arm64-v8a"], + ["36", "android-automotive-playstore", "arm64-v8a"], + ["36", "android-desktop", "arm64-v8a"], + ], + }); await writeDevicesXml(filesystem, customDeviceXml("My Tablet", 4096)); const runner = new ScriptedProcessRunner( Array.from({ length: 11 }, () => @@ -1399,7 +1430,7 @@ describe("AndroidDriver", () => { for (const { model, name } of names) { for (const spelling of [name.toUpperCase(), name.toLowerCase()]) { await expect(driver.resolveSpec({ model: spelling, platform: "android" })).resolves.toEqual( - { physical: false, model, osVersion: "34", platform: "android" }, + { physical: false, model, osVersion: "36", platform: "android" }, ); } } @@ -2342,7 +2373,7 @@ describe("AndroidDriver", () => { ]); }); - it("sets `PlayStore.enabled=yes` on a Play Store image when the profile allows Play Store, and `no` on a `google_apis` image or for a profile that does not", async () => { + it("sets `PlayStore.enabled=yes` on a Play Store image when the profile allows Play Store, and `no` on a `google_apis` image", async () => { const playStore = { imageTag: "google_apis_playstore" }; const allowed = await libraryHarness({ ...playStore, listing: pixelDevices }); await allowed.provision("Pixel 9"); @@ -2354,14 +2385,6 @@ describe("AndroidDriver", () => { }); await googleApis.provision("Pixel 9"); expect((await googleApis.config()).get("PlayStore.enabled")).toBe("no"); - - const refused = await libraryHarness({ - ...playStore, - profiles: [testLibraryProfile({ playStore: false })], - seed: seedConfig(["PlayStore.enabled=yes"]), - }); - await refused.provision("Test Phone"); - expect((await refused.config()).get("PlayStore.enabled")).toBe("no"); }); it("reads an image's tags from `SystemImage.TagId`, and from the folder name when it has none", async () => { @@ -4271,7 +4294,19 @@ describe("AndroidDriver library catalog", () => { const runner = new ScriptedProcessRunner([ processResult(binaries.avdmanager, ["list", "device"], "Available devices:\n"), ]); - const driver = await createDriver(await androidFilesystem(), runner); + const driver = await createDriver( + await androidFilesystem({ + images: [ + ["36", "google_apis", "arm64-v8a"], + ["36", "android-tv", "arm64-v8a"], + ["36", "android-wear", "arm64-v8a"], + ["36", "android-automotive", "arm64-v8a"], + ["36", "android-automotive-playstore", "arm64-v8a"], + ["36", "android-desktop", "arm64-v8a"], + ], + }), + runner, + ); const catalog = await driver.listCatalog(); const resolved: string[] = []; @@ -4353,6 +4388,625 @@ describe("AndroidDriver toolVersions()", () => { }); }); +type FitImage = readonly [api: string, tag: string, abi: string, properties?: string]; + +const fitDevices = + `Available devices:\n` + + `id: 0 or "pixel_5"\n Name: Pixel 5\n OEM : Google\n---------\n` + + `id: 1 or "pixel_9_pro"\n Name: Pixel 9 Pro\n OEM : Google\n---------\n` + + `id: 2 or "tv_720p"\n Name: Television (720p)\n OEM : Google\n Tag : android-tv\n---------\n` + + `id: 3 or "My Tablet"\n Name: My Tablet\n OEM : User\n---------\n` + + `id: 4 or "odd"\n Name: Odd Device\n OEM : Google\n Tag : foo-device\n---------\n` + + `id: 5 or "xr_headset"\n Name: XR Headset\n OEM : Google\n Tag : android-xr\n---------\n` + + `id: 6 or "glasses"\n Name: AI Glasses\n OEM : Google\n Tag : ai-glasses\n`; + +class ListingRunner extends ScriptedProcessRunner { + constructor( + private readonly listing: string, + expectations: readonly ScriptedProcessExpectation[], + ) { + super(expectations); + } + + override spawn( + command: string, + args: readonly string[], + options: ProcessRunOptions = {}, + ): ProcessHandle { + if (command === binaries.avdmanager && args[0] === "list") { + return new ScriptedProcessRunner([processResult(command, args, this.listing)]).spawn( + command, + args, + options, + ); + } + return super.spawn(command, args, options); + } +} + +type Refusal = Error & { readonly component?: string; readonly downloadable?: boolean }; + +async function fitHarness( + images: readonly FitImage[], + options: { + readonly devicesXml?: string; + readonly hostAbi?: string; + readonly profiles?: readonly LibraryDeviceProfile[]; + } = {}, +) { + const filesystem = await androidFilesystem({ + images: images.map(([api, tag, abi]) => [api, tag, abi]), + }); + for (const [api, tag, abi, properties] of images) { + if (properties !== undefined) { + await filesystem.writeFileAtomic( + `${sdk}/system-images/android-${api}/${tag}/${abi}/source.properties`, + properties, + ); + } + } + if (options.devicesXml !== undefined) await writeDevicesXml(filesystem, options.devicesXml); + const runner = new ListingRunner(fitDevices, [ + processResult(binaries.avdmanager, [ + "create", + "avd", + "-n", + "simlock_one", + "-k", + /.+/, + "-d", + /.+/, + ]), + processResult(binaries.emulator, ["-version"], "Android emulator version 36.1.9"), + processResult(binaries.adb, ["devices"], "List of devices attached\n"), + ]); + const driver = await createDriver(filesystem, runner, { + hostAbi: options.hostAbi ?? "arm64-v8a", + ids: ["one"], + ...(options.profiles === undefined + ? {} + : { deviceProfileSources: [{ profiles: async () => options.profiles ?? [] }] }), + }); + const resolve = (model: string, osVersion?: string, imageTag?: string) => + driver.resolveSpec({ + model, + platform: "android", + ...(osVersion === undefined ? {} : { osVersion }), + ...(imageTag === undefined ? {} : { imageTag }), + }); + const refusal = (model: string, osVersion?: string, imageTag?: string) => + resolve(model, osVersion, imageTag).then( + () => { + throw new Error(`${model} ${osVersion ?? ""} ${imageTag ?? ""} resolved`); + }, + (error: unknown) => error as Refusal, + ); + const createdPackage = () => { + const create = runner.calls.find((call) => call.args[0] === "create"); + return create?.args[create.args.indexOf("-k") + 1]; + }; + return { createdPackage, driver, filesystem, refusal, resolve, runner }; +} + +const HOST_IMAGES: readonly FitImage[] = [ + ["35", "google_apis", "arm64-v8a"], + ["36", "google_apis_playstore", "arm64-v8a"], + ["34", "android-tv", "arm64-v8a"], +]; + +describe("AndroidDriver image fit", () => { + describe("each row of the In short table", () => { + interface Row { + readonly name: string; + readonly images?: readonly FitImage[]; + readonly model: string; + readonly os?: string; + readonly tag?: string; + readonly resolves?: string; + readonly resolvedTag?: string; + readonly refusedDownloadable?: boolean; + readonly pkg?: string; + } + const withGoogleTv: readonly FitImage[] = [...HOST_IMAGES, ["36", "google-tv", "arm64-v8a"]]; + const withWear: readonly FitImage[] = [...HOST_IMAGES, ["34", "android-wear", "arm64-v8a"]]; + const rows: readonly Row[] = [ + { model: "Television (1080p)", name: "TV 1080p", resolves: "34" }, + { model: "Television (1080p)", name: "TV 1080p at 36", os: "36", refusedDownloadable: false }, + { + model: "Television (1080p)", + name: "TV 1080p with image tag google_apis", + refusedDownloadable: false, + tag: "google_apis", + }, + { model: "Television (720p)", name: "TV 720p, SDK only", resolves: "34" }, + { + images: withGoogleTv, + model: "Television (1080p)", + name: "TV 1080p with a google-tv image at 36", + resolves: "36", + }, + { images: withWear, model: "Wear OS Large Round", name: "Wear OS", resolves: "34" }, + { model: "Pixel 9", name: "Pixel 9", resolves: "36" }, + { model: "Pixel 9", name: "Pixel 9 at 34", os: "34", refusedDownloadable: false }, + { model: "Pixel 9", name: "Pixel 9 at 37", os: "37", refusedDownloadable: true }, + { model: "Television (1080p)", name: "TV 1080p at 37", os: "37", refusedDownloadable: false }, + { model: "Pixel 6", name: "Pixel 6", resolves: "35" }, + { model: "Pixel 6", name: "Pixel 6 at 36", os: "36", refusedDownloadable: false }, + { + model: "Pixel 6", + name: "Pixel 6 with image tag google_apis_playstore", + refusedDownloadable: false, + tag: "google_apis_playstore", + }, + { + model: "Medium Phone", + name: "Medium Phone with image tag google_apis_playstore", + resolvedTag: "google_apis_playstore", + resolves: "36", + tag: "google_apis_playstore", + }, + { model: "Medium Phone", name: "Medium Phone at 35", os: "35", resolves: "35" }, + { model: "Pixel 9 Pro", name: "Pixel 9 Pro, SDK only", resolves: "36" }, + { model: "My Tablet", name: "My Tablet, custom", resolves: "36" }, + ]; + + it.each(rows)("$name gives its After result", async (row) => { + const { driver, refusal, resolve } = await fitHarness(row.images ?? HOST_IMAGES); + + if (row.refusedDownloadable !== undefined) { + expect(await refusal(row.model, row.os, row.tag)).toMatchObject({ + downloadable: row.refusedDownloadable, + name: "RuntimeMissingError", + }); + if (row.os !== undefined) { + expect((await driver.listCatalog()).modelRuntimes[row.model]).not.toContain(row.os); + } + return; + } + const spec = await resolve(row.model, row.os, row.tag); + expect(spec).toEqual({ + ...(row.resolvedTag === undefined ? {} : { imageTag: row.resolvedTag }), + model: row.model, + osVersion: row.resolves, + physical: false, + platform: "android", + }); + expect((await driver.listCatalog()).modelRuntimes[row.model]).toContain(spec.osVersion); + }); + + it("pairs My Tablet with 35 and 36 and not the TV image at 34, and the TV with 34 only", async () => { + const { driver } = await fitHarness(HOST_IMAGES); + + const { modelRuntimes } = await driver.listCatalog(); + + expect(modelRuntimes["My Tablet"]).toEqual(["35", "36"]); + expect(modelRuntimes["Television (1080p)"]).toEqual(["34"]); + expect(modelRuntimes["Pixel 9"]).toEqual(["35", "36"]); + expect(modelRuntimes["Pixel 6"]).toEqual(["35"]); + }); + + it("creates a phone from the Play Store image at the newest level, and the TV from the android-tv image", async () => { + const phone = await fitHarness(HOST_IMAGES); + await phone.driver.provision(await phone.resolve("Pixel 5")); + const tv = await fitHarness(HOST_IMAGES); + await tv.driver.provision(await tv.resolve("Television (720p)")); + + expect(phone.createdPackage()).toBe( + "system-images;android-36;google_apis_playstore;arm64-v8a", + ); + expect(tv.createdPackage()).toBe("system-images;android-34;android-tv;arm64-v8a"); + }); + }); + + describe("downloads", () => { + it.each([ + ["Pixel 9", "37", true, "37"], + ["Pixel 6", "37", true, "37"], + ["Television (1080p)", "37", false, undefined], + ])( + "%s at the uninstalled level %s is downloadable %s, naming component %s", + async (model, os, downloadable, component) => { + const { refusal } = await fitHarness(HOST_IMAGES); + + const failure = await refusal(model, os); + + expect(failure.downloadable).toBe(downloadable); + expect(failure.component).toBe(component); + }, + ); + + it("is not downloadable for an uninstalled level whose google_apis image would not fit", async () => { + const { refusal } = await fitHarness(HOST_IMAGES); + + expect(await refusal("Pixel 9", "34").then((e) => e.downloadable)).toBe(false); + const old = await fitHarness([["35", "google_apis", "arm64-v8a"]], { + profiles: [ + testLibraryProfile({ + apiRange: { max: 33, min: 24 }, + name: "Old Phone", + names: ["Old Phone"], + }), + ], + }); + expect((await old.refusal("Old Phone", "34")).downloadable).toBe(false); + }); + + it("is not downloadable for an installed level with only misfit images", async () => { + const { refusal } = await fitHarness(HOST_IMAGES); + + expect(await refusal("Pixel 6", "36")).toMatchObject({ + component: undefined, + downloadable: false, + }); + }); + }); + + describe("the catalog", () => { + it("lists in modelRuntimes only levels with a fitting image, and every installed image elsewhere", async () => { + const { driver } = await fitHarness([ + ["35", "google_apis", "arm64-v8a"], + ["37", "android-xr", "arm64-v8a"], + ]); + + const catalog = await driver.listCatalog(); + + expect(catalog.modelRuntimes["Pixel 5"]).toEqual(["35"]); + expect(catalog.modelRuntimes["Television (1080p)"]).toEqual([]); + expect(catalog.runtimes).toEqual(["35", "37"]); + expect(catalog.defaultRuntime).toBe("37"); + expect(catalog.images).toEqual([ + { abi: "arm64-v8a", runtime: "35", tag: "google_apis" }, + { abi: "arm64-v8a", runtime: "37", tag: "android-xr" }, + ]); + }); + + it("resolves every pair it lists, and refuses a level it leaves out", async () => { + const { driver, refusal, resolve } = await fitHarness([ + ...HOST_IMAGES, + ["36", "android-wear", "arm64-v8a"], + ["Baklava", "google_apis", "arm64-v8a", "AndroidVersion.ApiLevel=35\n"], + ]); + const catalog = await driver.listCatalog(); + const pairs = Object.entries(catalog.modelRuntimes).flatMap(([model, levels]) => + levels.map((level) => ({ level, model })), + ); + const left = Object.entries(catalog.modelRuntimes).flatMap(([model, levels]) => + catalog.runtimes + .filter((level) => !levels.includes(level)) + .map((level) => ({ level, model })), + ); + expect(pairs.length).toBeGreaterThan(0); + expect(left.length).toBeGreaterThan(0); + + for (const { level, model } of pairs) { + expect(await resolve(model, level)).toMatchObject({ model, osVersion: level }); + } + for (const { level, model } of left) { + expect(await refusal(model, level)).toMatchObject({ + downloadable: false, + name: "RuntimeMissingError", + }); + } + }); + + it("pairs a devices.xml profile avdmanager did not list with every installed level", async () => { + const { driver, resolve } = await fitHarness(HOST_IMAGES, { + devicesXml: customDeviceXml("Legacy Phone", 2048), + }); + + const catalog = await driver.listCatalog(); + + expect(catalog.modelRuntimes["Legacy Phone"]).toEqual(["34", "35", "36"]); + expect(await resolve("Legacy Phone", "34")).toMatchObject({ osVersion: "34" }); + }); + + it("counts android-Baklava with AndroidVersion.ApiLevel=35 as a level Pixel 9 pairs with", async () => { + const { driver, resolve } = await fitHarness([ + ["Baklava", "google_apis", "arm64-v8a", "AndroidVersion.ApiLevel=35\n"], + ["34", "google_apis", "arm64-v8a"], + ]); + + const catalog = await driver.listCatalog(); + + expect(catalog.modelRuntimes["Pixel 9"]).toEqual(["Baklava"]); + expect(await resolve("Pixel 9")).toMatchObject({ osVersion: "Baklava" }); + }); + + it("uses the folder name for --image-tag and the catalog's images[].tag when SystemImage.TagId differs", async () => { + const { driver, refusal, resolve } = await fitHarness([ + ["35", "custom-folder", "arm64-v8a", "SystemImage.TagId=google_apis_playstore\n"], + ]); + + const catalog = await driver.listCatalog(); + + expect(catalog.images).toEqual([{ abi: "arm64-v8a", runtime: "35", tag: "custom-folder" }]); + expect(await resolve("Pixel 5", undefined, "custom-folder")).toMatchObject({ + imageTag: "custom-folder", + }); + expect(await refusal("Pixel 5", undefined, "google_apis_playstore")).toMatchObject({ + downloadable: false, + name: "RuntimeMissingError", + }); + }); + }); + + describe("resolveSpec", () => { + it("gives a request with no version the newest level with a fitting image", async () => { + const { resolve } = await fitHarness([ + ["34", "android-tv", "arm64-v8a"], + ["35", "android-tv", "arm64-v8a"], + ["36", "google_apis", "arm64-v8a"], + ]); + + expect(await resolve("Television (1080p)")).toMatchObject({ osVersion: "35" }); + }); + + it("fails a request with no version RUNTIME_MISSING, not downloadable, when no level has a fitting image", async () => { + const { refusal } = await fitHarness([["36", "google_apis", "arm64-v8a"]]); + + expect(await refusal("Television (1080p)")).toMatchObject({ + component: undefined, + downloadable: false, + name: "RuntimeMissingError", + }); + }); + + it("gives a tagged request an image of that tag that fits, at the newest level having one", async () => { + const { resolve } = await fitHarness([ + ["34", "google_apis_playstore", "arm64-v8a"], + ["35", "google_apis_playstore", "arm64-v8a"], + ["36", "google_apis", "arm64-v8a"], + ]); + + expect(await resolve("Pixel 9 Pro", undefined, "google_apis_playstore")).toMatchObject({ + imageTag: "google_apis_playstore", + osVersion: "35", + }); + }); + + it("skips a newest level whose image of the tag misfits and takes the newest level where it fits", async () => { + const { resolve } = await fitHarness( + [ + ["34", "google_apis_playstore", "arm64-v8a"], + ["36", "google_apis_playstore", "arm64-v8a"], + ], + { + profiles: [ + testLibraryProfile({ + apiRange: { max: 35, min: 24 }, + name: "Capped", + names: ["Capped"], + }), + ], + }, + ); + + expect(await resolve("Capped", undefined, "google_apis_playstore")).toMatchObject({ + osVersion: "34", + }); + }); + }); + + describe("refusal messages", () => { + const phones: readonly FitImage[] = [ + ["35", "google_apis", "arm64-v8a"], + ["36", "google_apis_playstore", "arm64-v8a"], + ]; + + it("names the API range for an API level below the profile's minimum", async () => { + const { refusal } = await fitHarness([["34", "google_apis", "arm64-v8a"]]); + + expect((await refusal("Pixel 9", "34")).message).toBe( + "No installed system image fits Pixel 9 at Android 34: it needs Android 35 or newer", + ); + }); + + it("names the API range for a level above the profile's maximum", async () => { + const { refusal } = await fitHarness([["35", "google_apis", "arm64-v8a"]], { + profiles: [ + testLibraryProfile({ + apiRange: { max: 33, min: 24 }, + name: "Old Phone", + names: ["Old Phone"], + }), + ], + }); + + expect((await refusal("Old Phone", "35")).message).toBe( + "No installed system image fits Old Phone at Android 35: it needs Android 33 or older", + ); + }); + + it.each([ + ["Television (1080p)", "it needs a TV image"], + ["Wear OS Large Round", "it needs a Wear OS image"], + ["Automotive (1080p landscape)", "it needs an automotive image"], + ["Medium Desktop", "it needs a desktop image"], + ["XR Headset", "it needs an XR image"], + ["AI Glasses", "it needs an AI glasses image"], + ])("names the kind for %s with only phone images", async (model, reason) => { + const { refusal } = await fitHarness(phones); + + expect((await refusal(model, "35")).message).toBe( + `No installed system image fits ${model} at Android 35: ${reason}`, + ); + }); + + it("names phone or tablet for a profile with no kind whose only image is a TV image", async () => { + const { refusal } = await fitHarness([["34", "android-tv", "arm64-v8a"]]); + + expect((await refusal("Pixel 5", "34")).message).toBe( + "No installed system image fits Pixel 5 at Android 34: it needs a phone or tablet image", + ); + }); + + it("names the tag for any other kind", async () => { + const { refusal } = await fitHarness(phones); + + expect((await refusal("Odd Device", "35")).message).toBe( + "No installed system image fits Odd Device at Android 35: it needs an image tagged foo-device", + ); + }); + + it("says the model does not take Play Store images", async () => { + const { refusal } = await fitHarness([["36", "google_apis_playstore", "arm64-v8a"]]); + + expect((await refusal("Pixel 6", "36")).message).toBe( + "No installed system image fits Pixel 6 at Android 36: Pixel 6 does not take Play Store images", + ); + }); + + it("says the model does not take tablet images", async () => { + const { refusal } = await fitHarness([["35", "tablet", "arm64-v8a"]]); + + expect((await refusal("Pixel 5", "35")).message).toBe( + "No installed system image fits Pixel 5 at Android 35: Pixel 5 does not take tablet images", + ); + }); + + it("says none of the installed images fit it when no single check rules out every image", async () => { + const { refusal } = await fitHarness([ + ["35", "google_apis_playstore", "arm64-v8a"], + ["35", "android-tv", "arm64-v8a"], + ]); + + expect((await refusal("Pixel 6", "35")).message).toBe( + "No installed system image fits Pixel 6 at Android 35: none of the installed images fit it", + ); + }); + + it("gives the API range reason for an image that fails both API range and kind", async () => { + const { refusal } = await fitHarness([["34", "android-tv", "arm64-v8a"]]); + + expect((await refusal("Pixel 9", "34")).message).toBe( + "No installed system image fits Pixel 9 at Android 34: it needs Android 35 or newer", + ); + }); + + it("drops the level from the message when no version was asked, reading every installed image", async () => { + const { refusal } = await fitHarness([["36", "google_apis", "arm64-v8a"]]); + + expect((await refusal("Television (1080p)")).message).toBe( + "No installed system image fits Television (1080p): it needs a TV image", + ); + }); + + it("says an image tag's image does not fit it, and why", async () => { + const { refusal } = await fitHarness(HOST_IMAGES); + + expect((await refusal("Television (1080p)", undefined, "google_apis")).message).toBe( + "No installed system image fits Television (1080p): the google_apis image does not fit it: it needs a TV image", + ); + expect((await refusal("Television (1080p)", "35", "google_apis")).message).toBe( + "No installed system image fits Television (1080p) at Android 35: the google_apis image does not fit it: it needs a TV image", + ); + }); + + it("says the level is not installed for a level with nothing installed", async () => { + const { refusal } = await fitHarness(HOST_IMAGES); + + expect((await refusal("Pixel 9", "37")).message).toBe( + "No installed system image fits Pixel 9 at Android 37: Android 37 is not installed", + ); + }); + + it("says no system image is installed on a host with no image at all", async () => { + const { refusal } = await fitHarness([]); + + expect((await refusal("Pixel 9")).message).toBe( + "No installed system image fits Pixel 9: no system image is installed", + ); + }); + + it("keeps today's message for an image tag with no image of that tag installed", async () => { + const { refusal } = await fitHarness(HOST_IMAGES); + + expect((await refusal("Pixel 5", "35", "default")).message).toBe( + "No default system image is installed for Android API 35", + ); + }); + }); + + describe("provision", () => { + it("creates the device from a fitting image, never a misfit one that sorts first", async () => { + const { createdPackage, driver, resolve } = await fitHarness( + [ + ["34", "google_apis", "arm64-v8a"], + ["34", "google-tv", "arm64-v8a"], + ["34", "android-tv", "x86_64"], + ], + { hostAbi: "arm64-v8a" }, + ); + + await driver.provision(await resolve("Television (720p)")); + + expect(createdPackage()).toBe("system-images;android-34;google-tv;arm64-v8a"); + }); + + it.each([ + [ + "host-native google_apis", + [ + ["35", "default", "arm64-v8a"], + ["35", "google_apis", "x86_64"], + ["35", "google_apis", "arm64-v8a"], + ] as const, + "system-images;android-35;google_apis;arm64-v8a", + ], + [ + "host-native", + [ + ["35", "google_apis", "x86_64"], + ["35", "default", "arm64-v8a"], + ] as const, + "system-images;android-35;default;arm64-v8a", + ], + [ + "google_apis", + [ + ["35", "default", "x86_64"], + ["35", "google_apis", "x86_64"], + ] as const, + "system-images;android-35;google_apis;x86_64", + ], + ["any", [["35", "default", "x86_64"]] as const, "system-images;android-35;default;x86_64"], + ])("follows today's order among fitting images: %s first", async (_name, images, expected) => { + const { createdPackage, driver, resolve } = await fitHarness(images); + + await driver.provision(await resolve("Pixel 5", "35")); + + expect(createdPackage()).toBe(expected); + }); + + it("throws RUNTIME_MISSING when no fitting image is left, and creates nothing from a misfit one", async () => { + const { driver, filesystem, resolve, runner } = await fitHarness([ + ["34", "google_apis", "arm64-v8a"], + ["34", "android-tv", "arm64-v8a"], + ]); + const spec = await resolve("Television (720p)"); + await filesystem.rm(`${sdk}/system-images/android-34/android-tv`); + + await expect(driver.provision(spec)).rejects.toMatchObject({ + downloadable: false, + name: "RuntimeMissingError", + }); + expect(runner.calls.some((call) => call.args[0] === "create")).toBe(false); + }); + }); + + describe("an image tag whose image misfits", () => { + it("fails RUNTIME_MISSING, not downloadable, and starts no sdkmanager", async () => { + const { refusal, runner } = await fitHarness(HOST_IMAGES); + + const failure = await refusal("Pixel 6", undefined, "google_apis_playstore"); + + expect(failure).toMatchObject({ downloadable: false, name: "RuntimeMissingError" }); + expect(failure.message).toContain("the google_apis_playstore image does not fit it"); + expect(runner.calls.map((call) => call.command)).not.toContain(binaries.sdkmanager); + }); + }); +}); + /** why: every case below asks for the `adb` tool, so this one place names it and leaves the device and context optional. */ async function passthroughOf( driver: object, diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index d3c97fb56..bfa61d57c 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -69,7 +69,7 @@ import { type DeviceProfileSourceDiagnostic, type DeviceProfile, } from "./device-profile-source.js"; -import { isPlayStoreImage } from "./image-fit.js"; +import { fits, isPlayStoreImage, misfitReason } from "./image-fit.js"; import { LibraryDeviceProfileSource } from "./profiles/index.js"; import { type AndroidSdkPaths, locateSdk } from "./sdk-paths.js"; @@ -253,6 +253,7 @@ interface SystemImage { readonly abi: string; readonly apiLevel: string; readonly path: string; + readonly sourceApiLevel?: string | undefined; readonly tag: string; readonly tags: readonly string[]; readonly version: string; @@ -782,11 +783,6 @@ export class AndroidDriver implements Driver { } } - /** - * Never installs: a missing API level throws, naming it as the component to install. A request - * naming an image tag resolves only to an installed image of that tag, and never names a - * component, so it can never lead to a download. - */ async resolveSpec(request: ExactDeviceRequest): Promise { if (request.platform !== this.platform) { throw new Error(`Android driver cannot resolve ${request.platform} requests`); @@ -795,7 +791,7 @@ export class AndroidDriver implements Driver { const profile = await this.#deviceProfiles.resolve(request.model); const images = await this.#installedImages(); if (request.imageTag !== undefined) { - const apiLevel = this.#taggedApiLevel(images, request.imageTag, request.osVersion); + const apiLevel = this.#taggedApiLevel(profile, images, request.imageTag, request.osVersion); this.#resolvedProfiles.set(profile.name.toLocaleLowerCase(), profile); return { imageTag: request.imageTag, @@ -806,26 +802,53 @@ export class AndroidDriver implements Driver { }; } - const installed = installedApiLevels(images); - const apiLevel = request.osVersion ?? installed.at(-1); - if (apiLevel === undefined) { - throw new RuntimeMissingError(this.platform, request.osVersion ?? "default"); - } - - // Every model pairs with every installed API level, whatever the image's ABI -- the same - // list `listCatalog` reports for each model (ADR 0008 §3). - if (!installed.includes(apiLevel)) { - throw new RuntimeMissingError(this.platform, apiLevel, { component: apiLevel }); + const levels = fittingApiLevels(profile, images); + const apiLevel = request.osVersion ?? levels.at(-1); + if (apiLevel === undefined || !levels.includes(apiLevel)) { + throw this.#noFittingImage(profile, images, request.osVersion); } this.#resolvedProfiles.set(profile.name.toLocaleLowerCase(), profile); return { model: profile.name, osVersion: apiLevel, physical: false, platform: this.platform }; } + // fallow-ignore-next-line complexity -- one refusal builder: each branch is one message the spec lists. + #noFittingImage( + profile: DeviceProfile, + images: readonly SystemImage[], + level: string | undefined, + imageTag?: string, + ): RuntimeMissingError { + const considered = level === undefined ? images : images.filter((i) => i.apiLevel === level); + const where = level === undefined ? "" : ` at Android ${level}`; + const tagged = imageTag === undefined ? [] : considered.filter((i) => i.tag === imageTag); + const downloadable = + level !== undefined && + imageTag === undefined && + considered.length === 0 && + fits(profile, { apiLevel: level, tag: "google_apis", tags: ["google_apis"] }); + const error = downloadable + ? new RuntimeMissingError(this.platform, level, { component: level }) + : new RuntimeMissingError(this.platform, level ?? "default", { downloadable: false }); + let reason: string; + if (imageTag !== undefined) { + const why = misfitReason(profile, tagged); + reason = `the ${imageTag} image does not fit it${why === undefined ? "" : `: ${why}`}`; + } else if (images.length === 0) { + reason = "no system image is installed"; + } else if (considered.length === 0) { + reason = `Android ${level} is not installed`; + } else { + reason = misfitReason(profile, considered) ?? "none of the installed images fit it"; + } + error.message = `No installed system image fits ${profile.name}${where}: ${reason}`; + return error; + } + async provision(spec: VirtualSpec): Promise { this.#assertAndroidSpec(spec); const profile = await this.#profileFor(spec.model); - const image = await this.#requireImage(spec.osVersion, spec.imageTag); + const image = await this.#requireImage(profile, spec.osVersion, spec.imageTag); // Cosmetic only, and worth saying so: the prefix is a label that makes an emulator // recognisable in `adb devices` and in its window title. Nothing reads it back as // evidence of anything -- ownership comes from the root this AVD is created in. @@ -1219,21 +1242,26 @@ export class AndroidDriver implements Driver { } async listCatalog(): Promise { - const [{ customModels, modelAliases, modelClasses, models }, images] = await Promise.all([ - this.#deviceProfiles.catalog(), + const [{ catalog, modelProfiles }, images] = await Promise.all([ + this.#deviceProfiles.catalogWithProfiles(), this.#installedImages(), ]); + const { customModels, modelAliases, modelClasses, models } = catalog; const runtimes = installedApiLevels(images); return { ...(customModels.length === 0 ? {} : { customModels: [...customModels] }), defaultRuntime: runtimes.at(-1), - // Installed only, a foreign ABI included: the same images `installedApiLevels` reads. images: images .map((image) => ({ abi: image.abi, runtime: image.apiLevel, tag: image.tag })) .sort(compareCatalogImages), modelAliases, modelClasses, - modelRuntimes: Object.fromEntries(models.map((model) => [model, [...runtimes]])), + modelRuntimes: Object.fromEntries( + models.map((model) => { + const profile = modelProfiles.get(model); + return [model, profile === undefined ? [] : fittingApiLevels(profile, images)]; + }), + ), models: [...models], runtimes, }; @@ -1305,10 +1333,6 @@ export class AndroidDriver implements Driver { await this.#mergeConfigIniLines(avdName, properties); } - /** - * The installed image an API level means -- the one `provision` would use -- with its - * receipt, or `undefined` when no image of that level is installed. Never installs. - */ async findComponent(component: string): Promise { const image = this.#matchingImage(await this.#installedImages(), component, undefined); return image === undefined ? undefined : this.#installedComponent(image); @@ -1598,12 +1622,15 @@ export class AndroidDriver implements Driver { const tagPath = `${apiPath}/${tag}`; for (const abi of (await this.#filesystem.readdir(tagPath)).filter(isVisibleEntry)) { const path = `${tagPath}/${abi}`; + const properties = await readSourceProperties(this.#filesystem, path); + const sourceApiLevel = sourcePropertyValue(properties, "AndroidVersion.ApiLevel"); images.push({ abi, apiLevel: apiMatch[1], path, + ...(sourceApiLevel === undefined ? {} : { sourceApiLevel }), tag, - tags: await systemImageTags(this.#filesystem, path, tag), + tags: systemImageTags(properties, tag), version: await systemImageVersion(this.#filesystem, path), }); } @@ -1612,12 +1639,6 @@ export class AndroidDriver implements Driver { return images; } - /** - * The one function that picks the image of an API level, for resolving and for creating. With a - * tag it picks among the images of that tag only, the host's ABI first. Without one, - * `google_apis` for the host's ABI, then any image for the host's ABI, then any `google_apis`, - * then any. - */ #matchingImage( images: readonly SystemImage[], apiLevel: string, @@ -1636,32 +1657,46 @@ export class AndroidDriver implements Driver { ); } - async #requireImage(apiLevel: string, imageTag: string | undefined): Promise { - const image = this.#matchingImage(await this.#installedImages(), apiLevel, imageTag); + async #requireImage( + profile: DeviceProfile, + apiLevel: string, + imageTag: string | undefined, + ): Promise { + const images = await this.#installedImages(); + const image = this.#matchingImage( + images.filter((candidate) => fits(profile, candidate)), + apiLevel, + imageTag, + ); if (image === undefined) { - throw imageTag === undefined - ? new RuntimeMissingError(this.platform, apiLevel) - : new AndroidImageTagMissingError(apiLevel, imageTag); + if ( + imageTag !== undefined && + !images.some((i) => i.apiLevel === apiLevel && i.tag === imageTag) + ) { + throw new AndroidImageTagMissingError(apiLevel, imageTag); + } + throw this.#noFittingImage(profile, images, apiLevel, imageTag); } return image; } - /** - * The API level a request naming `imageTag` gets: the one it names, which must have an image of - * that tag, or else the newest that has one. Throws a `RuntimeMissingError` naming no - * component when there is none, so no download is ever tried for a tag. - */ #taggedApiLevel( + profile: DeviceProfile, images: readonly SystemImage[], imageTag: string, requested: string | undefined, ): string { - const levels = installedApiLevels(images).filter( - (level) => this.#matchingImage(images, level, imageTag) !== undefined, + const tagged = images.filter( + (image) => + image.tag === imageTag && (requested === undefined || image.apiLevel === requested), ); + if (tagged.length === 0) { + throw new AndroidImageTagMissingError(requested ?? "default", imageTag); + } + const levels = fittingApiLevels(profile, tagged); const apiLevel = requested ?? levels.at(-1); if (apiLevel === undefined || !levels.includes(apiLevel)) { - throw new AndroidImageTagMissingError(apiLevel ?? "default", imageTag); + throw this.#noFittingImage(profile, images, requested, imageTag); } return apiLevel; } @@ -2255,14 +2290,14 @@ class AndroidImageTagMissingError extends RuntimeMissingError { } } -/** - * The installed API levels, oldest first, once each -- foreign-ABI images included. Every model - * pairs with every one of them; `resolveSpec` and `listCatalog` both read this list. - */ function installedApiLevels(images: readonly SystemImage[]): string[] { return [...new Set(images.map((image) => image.apiLevel))].sort(compareApiLevels); } +function fittingApiLevels(profile: DeviceProfile, images: readonly SystemImage[]): string[] { + return installedApiLevels(images.filter((image) => fits(profile, image))); +} + function isVisibleEntry(name: string): boolean { return !name.startsWith("."); } @@ -2423,28 +2458,34 @@ function assertLibraryProfileWritable( } } -async function systemImageTags( +async function readSourceProperties( filesystem: Filesystem, imagePath: string, - folder: string, -): Promise { +): Promise { try { - const properties = await filesystem.readFile(`${imagePath}/source.properties`); - const tagId = properties - .split(/\r?\n/) - .find((line) => line.startsWith("SystemImage.TagId=")) - ?.slice("SystemImage.TagId=".length) - .trim(); - const tags = (tagId ?? "") - .split(",") - .map((tag) => tag.trim()) - .filter((tag) => tag !== ""); - return tags.length > 0 ? tags : [folder]; + return await filesystem.readFile(`${imagePath}/source.properties`); } catch { - return [folder]; + return undefined; } } +function sourcePropertyValue(properties: string | undefined, key: string): string | undefined { + const value = properties + ?.split(/\r?\n/) + .find((line) => line.startsWith(`${key}=`)) + ?.slice(key.length + 1) + .trim(); + return value === undefined || value === "" ? undefined : value; +} + +function systemImageTags(properties: string | undefined, folder: string): readonly string[] { + const tags = (sourcePropertyValue(properties, "SystemImage.TagId") ?? "") + .split(",") + .map((tag) => tag.trim()) + .filter((tag) => tag !== ""); + return tags.length > 0 ? tags : [folder]; +} + /** * The one place an `android.emulator` setting becomes an emulator flag. Every value maps to a * fixed flag; `gpu` is the only one carrying a value, and it is always the argument of `-gpu`. diff --git a/src/gateway/routing/request-match.test.ts b/src/gateway/routing/request-match.test.ts index 896b5358d..27ca6468a 100644 --- a/src/gateway/routing/request-match.test.ts +++ b/src/gateway/routing/request-match.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import { catalogFixture, statusFixture } from "../test-support.js"; import type { WorkerView } from "../worker-registry.js"; -import { listsModel, matchRequest } from "./request-match.js"; +import { deviceFit, listsModel, matchRequest } from "./request-match.js"; function worker(entry: Parameters[0][number]): WorkerView { return { @@ -230,3 +230,70 @@ describe("matchRequest", () => { expect(matchRequest(view, { ...request, osVersion: ">26" })).toBeUndefined(); }); }); + +describe("deviceFit: the runtime a model with no OS is expected to get", () => { + const specOf = (platform: "android" | "ios", model: string, osVersion: string) => + ({ model, osVersion, physical: false, platform }) as const; + + it.each([ + ["android", "Pixel 9", ["35", "36"]], + ["ios", "iPhone 17", ["18.0", "26.0"]], + ] as const)( + "expects the newest paired runtime on %s even when the default runtime is an older paired one", + (platform, model, runtimes) => { + const [older, newest] = runtimes; + const view = worker({ + defaultRuntime: older, + models: [model], + platform, + runtimes: [...runtimes], + }); + + const fit = deviceFit(view, { model, platform }); + + expect(fit?.(specOf(platform, model, newest))).toBe(true); + expect(fit?.(specOf(platform, model, older))).toBe(false); + }, + ); + + it.each([ + ["android", "Pixel 9", ["35", "36"], "37"], + ["ios", "iPhone 17", ["18.0", "26.0"], "27.0"], + ] as const)( + "expects the newest paired runtime on %s when several are paired and the default is not one of them", + (platform, model, runtimes, unpaired) => { + const [older, newest] = runtimes; + const view = worker({ + defaultRuntime: unpaired, + modelRuntimes: { [model]: [...runtimes] }, + models: [model], + platform, + runtimes: [...runtimes, unpaired], + }); + + const fit = deviceFit(view, { model, platform }); + + expect(fit?.(specOf(platform, model, newest))).toBe(true); + expect(fit?.(specOf(platform, model, older))).toBe(false); + }, + ); + + it("expects the newest paired runtime that has an image of the tag, for a request naming a tag", () => { + const view = worker({ + images: [ + { abi: "arm64-v8a", runtime: "34", tag: "google_apis" }, + { abi: "arm64-v8a", runtime: "35", tag: "google_apis" }, + { abi: "arm64-v8a", runtime: "36", tag: "google_apis_playstore" }, + ], + models: ["Pixel 9"], + platform: "android", + runtimes: ["34", "35", "36"], + }); + + const fit = deviceFit(view, { imageTag: "google_apis", model: "Pixel 9", platform: "android" }); + + expect(fit?.({ ...specOf("android", "Pixel 9", "35"), imageTag: "google_apis" })).toBe(true); + expect(fit?.({ ...specOf("android", "Pixel 9", "34"), imageTag: "google_apis" })).toBe(false); + expect(fit?.({ ...specOf("android", "Pixel 9", "36"), imageTag: "google_apis" })).toBe(false); + }); +}); diff --git a/src/gateway/routing/request-match.ts b/src/gateway/routing/request-match.ts index df8465c90..fbec37798 100644 --- a/src/gateway/routing/request-match.ts +++ b/src/gateway/routing/request-match.ts @@ -1,5 +1,10 @@ import { requestedClass } from "../../contract/index.js"; -import { type OsConstraint, parseOsConstraint, satisfies } from "../../contract/os-range.js"; +import { + compareVersions, + type OsConstraint, + parseOsConstraint, + satisfies, +} from "../../contract/os-range.js"; import { findCatalogModel, modelClass, @@ -52,13 +57,6 @@ export function deviceFit( return (spec) => fits(requirement, spec, (listed) => modelClass(catalog, listed)); } -/** - * The OS a device must have. What the request names, exact or a range. With none named: a class - * accepts any installed runtime, and an exact model needs the runtime the worker would pick -- the - * catalog's `defaultRuntime` when the model pairs with it, otherwise its only paired runtime. A - * model with several paired runtimes and no paired default has no answer: the worker's choice then - * depends on what it would boot, and the gateway compares no versions, so no device fits. - */ function osRequirement( catalog: PlatformEntry, model: string, @@ -68,9 +66,8 @@ function osRequirement( if (constraint !== undefined) return constraint; if (request.model === undefined) return { kind: "installed", versions: catalog.runtimes }; const runtimes = pairedRuntimesOf(catalog, model, request); - const picked = runtimes.find((runtime) => runtime === catalog.defaultRuntime); - const versions = picked === undefined ? (runtimes.length === 1 ? runtimes : []) : [picked]; - return { kind: "installed", versions }; + const newest = [...runtimes].sort(compareVersions).at(-1); + return { kind: "installed", versions: newest === undefined ? [] : [newest] }; } /** diff --git a/src/gateway/routing/stages/warm-hit.test.ts b/src/gateway/routing/stages/warm-hit.test.ts index aa2b76931..bcd5b8ef6 100644 --- a/src/gateway/routing/stages/warm-hit.test.ts +++ b/src/gateway/routing/stages/warm-hit.test.ts @@ -266,14 +266,14 @@ describe("warm-hit", () => { expect(warmHit.score(view(catalog, "26.0"), request)).toBe(0); }); - it("gives a request naming no runtime no warm hit when no default runtime pairs and several runtimes do", () => { + it("picks the newest paired runtime for a request naming no runtime when no default runtime pairs and several runtimes do", () => { const catalog = { models: ["iPhone 17"], platform: "ios" as const, runtimes: ["26.0", "18.0"], }; - expect(warmHit.score(view(catalog, "26.0"), request)).toBe(0); + expect(warmHit.score(view(catalog, "26.0"), request)).toBe(1); expect(warmHit.score(view(catalog, "18.0"), request)).toBe(0); }); }); diff --git a/src/leasing/lease-acquisition-coordinator.test.ts b/src/leasing/lease-acquisition-coordinator.test.ts index 4bf73ec90..da4522ebf 100644 --- a/src/leasing/lease-acquisition-coordinator.test.ts +++ b/src/leasing/lease-acquisition-coordinator.test.ts @@ -3285,3 +3285,70 @@ describe("LeaseAcquisitionCoordinator: resolve", () => { }); }); }); + +describe("LeaseAcquisitionCoordinator: levels a model no longer pairs with", () => { + const pixel = { model: "Pixel 8", physical: false, platform: "android" } as const; + const owner = (id: string) => ({ ownerId: id, requesterId: id }); + + class PairingDriver extends FakeDriver { + override async resolveSpec( + ...args: Parameters + ): Promise { + const catalog = await this.listCatalog(); + const { model, osVersion } = args[0]; + if (osVersion !== undefined && !(catalog.modelRuntimes[model] ?? []).includes(osVersion)) { + throw new RuntimeMissingError("android", osVersion); + } + return super.resolveSpec(...args); + } + } + + function pairing(): PairingDriver { + return new PairingDriver({ + availableOsVersions: ["34", "35"], + clock: new FakeClock(1_000), + knownModels: ["Pixel 8"], + modelRuntimes: { "Pixel 8": ["35"] }, + platform: "android", + }); + } + + it("reuses an idle device on a level the catalog pairs for an exact request", async () => { + const harness = await createHarness({ drivers: [pairing()], maxDevices: 2 }); + const idle = await seedReady(harness, { ...pixel, osVersion: "35" }); + + const granted = await harness.coordinator.request( + { ...pixel, osVersion: "35" }, + owner("agent"), + ); + + expect(granted.device.id).toBe(idle.id); + }); + + it("does not pick an idle device on a level the catalog no longer pairs for an exact request", async () => { + const harness = await createHarness({ drivers: [pairing()], maxDevices: 2 }); + const idle = await seedReady(harness, { ...pixel, osVersion: "34" }); + + const outcome = await harness.coordinator + .request({ ...pixel, osVersion: "34" }, owner("agent")) + .then( + (granted) => ({ granted: granted.device.id }), + (error: unknown) => ({ failed: (error as Error).name }), + ); + + expect(outcome).toEqual({ failed: "RuntimeMissingError" }); + expect(idle.state).toBe("ready"); + }); + + it("still picks an idle device on a level the catalog no longer pairs for a range request", async () => { + const harness = await createHarness({ drivers: [pairing()], maxDevices: 2 }); + const idle = await seedReady(harness, { ...pixel, osVersion: "34" }); + + const granted = await harness.coordinator.request( + { model: "Pixel 8", osVersion: ">=34", platform: "android" }, + owner("agent"), + ); + + expect(granted.device.id).toBe(idle.id); + }); +});