diff --git a/src/core/driver.ts b/src/core/driver.ts index b317fdc29..8f668ec91 100644 --- a/src/core/driver.ts +++ b/src/core/driver.ts @@ -149,7 +149,12 @@ export type ReclaimStrategy = ReclaimResult["strategy"]; */ export type DriverEstimate = | { readonly operation: "provision" } - | { readonly operation: "boot" } + | { + readonly operation: "boot"; + /** why: With a `device` a driver may quote that device's own boot path, which it reads asynchronously. */ + readonly device?: DriverDevice; + readonly purpose?: "prepare" | "recover"; + } | { readonly operation: "reclaim"; readonly clean: "standard" | "full" }; export interface DriverCatalogEntry { @@ -351,6 +356,10 @@ export interface Driver { listPresentPhysical(enrolledIds: readonly string[]): Promise; /** Read-only: must never trigger a runtime / system-image download. */ listCatalog(): Promise; + estimate( + estimate: DriverEstimate & { readonly operation: "boot"; readonly device: DriverDevice }, + spec: DeviceSpec, + ): number | Promise; estimate(estimate: DriverEstimate, spec: DeviceSpec): number; leaseEnvironment( device: VirtualDriverDevice | PhysicalDriverDevice, diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 26db23124..acb7c516c 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -799,11 +799,12 @@ describe("AndroidDriver", () => { }); }); - it("boots a shutdown device from its persisted clean baseline after a driver restart", async () => { + it("quotes a 4 s prepare boot for a persisted clean baseline and keeps unknown, recovery, mismatched, wipe-pending and physical boots at 70 s", async () => { const harness = await provisionedHarness(); const booted = await harness.driver.makeReady(harness.device); const restartedRunner = new ScriptedProcessRunner([ + processResult(binaries.emulator, ["-version"], "Android emulator version 36.1.9"), processResult(binaries.emulator, ["-version"], "Android emulator version 36.1.9"), processResult(binaries.adb, ["devices"], "List of devices attached\n"), { @@ -835,11 +836,24 @@ describe("AndroidDriver", () => { markWriteExpectation("emulator-5586", "device-0"), ]); const restartedDriver = await createDriver(harness.filesystem, restartedRunner); + const spec = { + physical: false, + model: "Pixel 5", + osVersion: "34", + platform: "android", + } as const; + // why: Proposed per-device estimate input for #778: the current operation-only input + // cannot distinguish this persisted baseline from a cold boot of the same spec. + const prepareEstimate = { device: booted, operation: "boot", purpose: "prepare" } as const; + const recoveryEstimate = { ...prepareEstimate, purpose: "recover" } as const; + expect(await restartedDriver.estimate({ operation: "boot" }, spec)).toBe(70_000); + expect(await restartedDriver.estimate(recoveryEstimate, spec)).toBe(70_000); + const estimatedBootMs = await restartedDriver.estimate(prepareEstimate, spec); await expect(restartedDriver.makeReady(booted)).resolves.toMatchObject({ address: "emulator-5586", }); - expect(restartedRunner.calls[2]).toMatchObject({ + expect(restartedRunner.calls[3]).toMatchObject({ args: [ "-avd", "simlock_one", @@ -851,6 +865,32 @@ describe("AndroidDriver", () => { ], command: binaries.emulator, }); + expect(estimatedBootMs).toBe(4_000); + + // why: Each row is a prepare boot that `makeReady` would not load the baseline for, so it keeps the cold figure. + const mismatchedRunner = new ScriptedProcessRunner([ + processResult(binaries.emulator, ["-version"], "Android emulator version 37.0.0"), + ]); + const mismatchedDriver = await createDriver(harness.filesystem, mismatchedRunner); + // why: A full reclaim leaves the baseline hash matching but flags the next boot to wipe data. + const wipePendingRunner = new ScriptedProcessRunner([ + avdPathExpectation("emulator-5586"), + processResult(binaries.adb, ["-s", "emulator-5586", "emu", "kill"]), + processResult(binaries.emulator, ["-version"], "Android emulator version 36.1.9"), + ]); + const wipePendingDriver = await createDriver(harness.filesystem, wipePendingRunner); + await wipePendingDriver.reclaim(booted, { clean: "full" }); + expect({ + mismatchedBaselineHash: await mismatchedDriver.estimate(prepareEstimate, spec), + physicalSpec: await restartedDriver.estimate(prepareEstimate, { + class: "phone", + model: "Pixel 5", + osVersion: "34", + physical: true, + platform: "android", + }), + wipePending: await wipePendingDriver.estimate(prepareEstimate, spec), + }).toEqual({ mismatchedBaselineHash: 70_000, physicalSpec: 70_000, wipePending: 70_000 }); }); describe("android.emulator launch options", () => { diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 9cd2f0220..2de7c1687 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -1407,12 +1407,18 @@ export class AndroidDriver implements Driver { }; } - estimate(estimate: DriverEstimate, spec: DeviceSpec): number { + estimate( + estimate: DriverEstimate & { readonly operation: "boot"; readonly device: DriverDevice }, + spec: DeviceSpec, + ): Promise; + estimate(estimate: DriverEstimate, spec: DeviceSpec): number; + estimate(estimate: DriverEstimate, spec: DeviceSpec): number | Promise { switch (estimate.operation) { case "provision": return PROVISION_ESTIMATE_MS; case "boot": - return COLD_BOOT_ESTIMATE_MS; + if (estimate.device === undefined) return COLD_BOOT_ESTIMATE_MS; + return this.#bootEstimate(estimate.device, estimate.purpose, spec); case "reclaim": if (spec.physical) return PHYSICAL_RECLAIM_ESTIMATE_MS; // why: `standard` can still fall back to the wipe branch (about five times longer); `Doctor` @@ -2103,13 +2109,43 @@ export class AndroidDriver implements Driver { } } - async #reconcileBaseline(data: AndroidDriverData, state: DeviceState): Promise { + /** + * why: The one decision both `makeReady` (through `#reconcileBaseline`) and the boot estimate read, + * so the figure quoted is the boot `makeReady` then takes: `load` where the baseline is recorded + * and matches the current emulator and image, `stale` where it is recorded but no longer matches, + * and `none` where a wipe is pending or no baseline is recorded. It changes nothing. + */ + async #baselineVerdict( + data: AndroidDriverData, + needsWipe: boolean, + imageIdentity: string, + ): Promise<"load" | "stale" | "none"> { const baselineHash = await this.#baselineHash(data.avdName); - if (state.needsWipe || baselineHash === undefined) { - return; - } - const currentHash = await this.#currentConfigHash(data.avdName, state.imageIdentity); - if (baselineHash === currentHash) { + if (needsWipe || baselineHash === undefined) return "none"; + const currentHash = await this.#currentConfigHash(data.avdName, imageIdentity); + return baselineHash === currentHash ? "load" : "stale"; + } + + async #bootEstimate( + device: DriverDevice, + purpose: "prepare" | "recover" | undefined, + spec: DeviceSpec, + ): Promise { + if (spec.physical || purpose === "recover") return COLD_BOOT_ESTIMATE_MS; + const data = this.#dataFor(device); + const state = this.#devices.get(data.avdName); + const verdict = await this.#baselineVerdict( + data, + state?.needsWipe === true, + state?.imageIdentity ?? data.imageIdentity ?? "", + ); + return verdict === "load" ? SNAPSHOT_BOOT_ESTIMATE_MS : COLD_BOOT_ESTIMATE_MS; + } + + async #reconcileBaseline(data: AndroidDriverData, state: DeviceState): Promise { + const verdict = await this.#baselineVerdict(data, state.needsWipe, state.imageIdentity); + if (verdict === "none") return; + if (verdict === "load") { state.baselineCaptured = true; state.snapshotExpected = true; return; diff --git a/src/leasing/create-leasing.test.ts b/src/leasing/create-leasing.test.ts index 69fc483c5..47cf3ebdb 100644 --- a/src/leasing/create-leasing.test.ts +++ b/src/leasing/create-leasing.test.ts @@ -6,6 +6,8 @@ import { BootTimeoutError, type ComponentInstaller, type Config, + type DeviceSpec, + type DriverEstimate, DriverCrashError, type VirtualSpec, type LeaseProgress, @@ -983,9 +985,19 @@ describe("createLeasing", () => { }); }); - it("reports only the selected work as it begins", async () => { + it("reports only the selected work as it begins, quoting a shut-down device's own prepare-boot figure", async () => { const clock = new FakeClock(1_000); - const driver = new FakeDriver({ + // why: A real driver quotes a persisted-baseline boot below its cold figure; the fake does so only + // for an estimate that names the device and the prepare purpose. + class DeviceQuotingDriver extends FakeDriver { + override estimate(estimate: DriverEstimate, spec: DeviceSpec): number { + if (estimate.operation === "boot" && estimate.purpose === "prepare") { + return estimate.device === undefined ? 99 : 4; + } + return super.estimate(estimate, spec); + } + } + const driver = new DeviceQuotingDriver({ availableOsVersions: ["26.5"], clock, estimateMs: { boot: 20, provision: 10, reclaim: 15 }, @@ -1010,12 +1022,57 @@ describe("createLeasing", () => { payload: { deviceId: shutdown.id, initiator: "test" }, }); const booted: string[] = []; - await harness.engine.request(request, { - onProgress: (progress) => booted.push(progress.stage), + const bootEtas: (number | undefined)[] = []; + const bootedGrant = await harness.engine.request(request, { + onProgress: (progress) => { + booted.push(progress.stage); + bootEtas.push(progress.stage === "booting" ? progress.etaMs : undefined); + }, requesterId: "shutdown", ownerId: "shutdown", }); expect(booted).toEqual(["booting"]); + expect(bootEtas).toEqual([4]); + expect(bootedGrant.timing.estimatedBootMs).toBe(4); + }); + + it("grants a shut-down device with the cold boot figure when its own boot estimate rejects", async () => { + const clock = new FakeClock(1_000); + class RejectingDeviceEstimateDriver extends FakeDriver { + override estimate(estimate: DriverEstimate, spec: DeviceSpec): number { + if (estimate.operation === "boot" && estimate.device !== undefined) { + return Promise.reject(new Error("emulator -version failed")) as unknown as number; + } + return super.estimate(estimate, spec); + } + } + const driver = new RejectingDeviceEstimateDriver({ + availableOsVersions: ["26.5"], + clock, + estimateMs: { boot: 20, provision: 10, reclaim: 15 }, + platform: "ios", + }); + const harness = await createHarness({ driver, idleShutdownAfterMs: 0 }); + const first = await harness.engine.request(request, { requesterId: "a", ownerId: "a" }); + await harness.engine.release(first.lease.id, "explicit"); + await harness.engine.settle(); + const shutdown = harness.registry.snapshot.devices[0]; + if (shutdown === undefined) throw new Error("Expected provisioned device"); + await harness.registry.transitionDevice(shutdown.id, "shutdown", { + event: "device.shutdown", + payload: { deviceId: shutdown.id, initiator: "test" }, + }); + + const granted = harness.engine + .request(request, { requesterId: "b", ownerId: "b" }) + .then((grant) => grant.timing.estimatedBootMs); + // why: Without the fallback the waiter hangs, so the race turns that hang into a named failure. + const outcome = await Promise.race([ + granted, + new Promise((resolve) => setTimeout(() => resolve("still pending"), 1_000)), + ]); + + expect(outcome).toBe(20); }); it("reports queue insertion without speculative work and isolates callback failures", async () => { diff --git a/src/leasing/lease-acquisition-coordinator.ts b/src/leasing/lease-acquisition-coordinator.ts index 8dc966958..90777aee2 100644 --- a/src/leasing/lease-acquisition-coordinator.ts +++ b/src/leasing/lease-acquisition-coordinator.ts @@ -884,9 +884,9 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { return; } if (action.kind === "boot-shutdown") { - waiter.timing = estimatedBootTiming( + waiter.timing = await estimatedBootTiming( this.options.drivers.get(action.device.spec.platform), - action.device.spec, + action.device, ); await this.#bootShutdown(waiter, action.device, action.capacityReservation, action.claim); return; @@ -1135,12 +1135,11 @@ export class LeaseAcquisitionCoordinator implements AcquisitionMaintenance { capacityReservation: CapacityReservation, claim: DeviceOperationClaim, ): Promise { - const driver = this.options.drivers.get(device.spec.platform); let handoff: ReadyDeviceHandoff; try { this.options.queue.notifyProgress(waiter, { stage: "booting", - etaMs: driver.estimate({ operation: "boot" }, device.spec), + etaMs: waiter.timing.estimatedBootMs, }); const ready = await this.options.lifecycle.bootForLease(device, claim); if (ready === undefined) throw new Error(`Boot target is no longer safe: ${device.id}`); @@ -1362,8 +1361,17 @@ function estimatedTiming(driver: Driver, spec: DeviceSpec): LeaseTiming { }; } -function estimatedBootTiming(driver: Driver, spec: DeviceSpec): LeaseTiming { - const estimatedBootMs = driver.estimate({ operation: "boot" }, spec); +async function estimatedBootTiming(driver: Driver, device: DeviceRecord): Promise { + const spec = device.spec; + // why: The quote is advisory. A driver that cannot read the device's own boot path (a failed + // `emulator -version`, say) must not strand the claim and capacity reservation that the boot + // below releases, so the device-less figure stands in. + const estimatedBootMs = await Promise.resolve( + driver.estimate( + { device: toDriverDevice(device), operation: "boot", purpose: "prepare" }, + spec, + ), + ).catch(() => driver.estimate({ operation: "boot" }, spec)); return { estimatedBootMs, estimatedProvisionMs: 0,