From 95603c3a575fa8d326110c3bdb22ae7125b6f304 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 1 Oct 2026 19:05:43 +0200 Subject: [PATCH 1/9] test(e2e): the slim lane reaches its devices through Simlock's own device set Every simctl call in slow-ios-slim now carries --set, taken from the grant's SIMLOCK_IOS_DEVICE_SET, as the smoke lane's already do. Each test empties its own set (shutdown, then delete) before withDaemon removes the home, so no launchd_sim is left writing into a directory being removed (ENOTEMPTY) and no simulator outlives its test. The last test now checks for running processes in this file's sets instead of simlock- names in the default set, where Simlock devices never live. A grant that comes back full where slim was expected now carries the daemon's skipped-slim log lines in the failure message. The set helpers move from slow-ios-smoke into e2e/helpers/ios-device-set.ts so both lanes share one copy. --- e2e/helpers/ios-device-set.ts | 93 +++++++++++++++++ e2e/slow-ios-slim.test.ts | 183 +++++++++++++++++++--------------- e2e/slow-ios-smoke.test.ts | 81 ++------------- 3 files changed, 205 insertions(+), 152 deletions(-) create mode 100644 e2e/helpers/ios-device-set.ts diff --git a/e2e/helpers/ios-device-set.ts b/e2e/helpers/ios-device-set.ts new file mode 100644 index 000000000..f2af6c13a --- /dev/null +++ b/e2e/helpers/ios-device-set.ts @@ -0,0 +1,93 @@ +import { execFile } from "node:child_process"; +import { readdir, rm, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; + +const execFileAsync = promisify(execFile); + +export interface SimctlDevice { + readonly udid: string; + readonly name: string; + readonly state: string; +} + +/** Where a `withDaemon` env's Simlock keeps its iOS devices: its own device set (ADR 0001). */ +export function iosDeviceSet(home: string): string { + return join(home, "devices", "ios"); +} + +/** + * `xcrun simctl --set ...args`. Every simctl call against a Simlock device carries + * `--set`, exactly as the driver's do: a device in a custom set is not addressable, or even + * listable, without it. + */ +export async function simctlInSet( + deviceSet: string, + args: readonly string[], +): Promise<{ readonly stdout: string }> { + return execFileAsync("xcrun", ["simctl", "--set", deviceSet, ...args]); +} + +/** Devices in one device set. */ +export async function setDevices(deviceSet: string): Promise { + const { stdout } = await simctlInSet(deviceSet, ["list", "devices", "-j"]); + const parsed = JSON.parse(stdout) as { devices: Record }; + return Object.values(parsed.devices).flat(); +} + +/** + * Everything in the set, by membership rather than by name: the set is Simlock's own, so + * nothing else can be in it, and CoreSimulator has to be told to forget these devices + * before the temporary home holding them is removed. + * + * Shut down first, always. `simctl delete` refuses a booted device, and this runs on the + * failure path too -- a `waitFor` that gave up leaves devices booted -- so deleting + * without shutting down would leave a running `launchd_sim` attached to a set directory + * that `withDaemon`'s teardown is about to remove recursively, and still writing into it + * while it does (`ENOTEMPTY`). + */ +export async function emptyDeviceSet(deviceSet: string): Promise { + for (const device of await setDevices(deviceSet).catch(() => [])) { + await simctlInSet(deviceSet, ["shutdown", device.udid]).catch(() => undefined); + await simctlInSet(deviceSet, ["delete", device.udid]).catch(() => undefined); + } +} + +/** Older than any run of a real-simctl lane can be. */ +const STALE_SET_AGE_MS = 60 * 60 * 1000; + +/** + * Device sets left behind by a run that died before its own cleanup -- a killed vitest, a + * crashed machine. Nothing else reclaims them now that the set lives inside a per-test + * temporary home instead of the shared default set the old prefix sweep covered, so the + * tens of gigabytes each holds would sit in `$TMPDIR` forever. Age-gated rather than + * scoped to this run so it can never sweep a set out from under a live one, including a + * sibling running in parallel. + */ +export async function sweepStaleDeviceSets(): Promise { + const entries = await readdir(tmpdir(), { withFileTypes: true }).catch(() => []); + for (const entry of entries) { + if (!entry.isDirectory() || !entry.name.startsWith("simlock-e2e-")) continue; + const deviceSet = iosDeviceSet(join(tmpdir(), entry.name)); + const details = await stat(deviceSet).catch(() => undefined); + if (details === undefined || Date.now() - details.mtimeMs < STALE_SET_AGE_MS) continue; + await emptyDeviceSet(deviceSet); + await rm(deviceSet, { force: true, recursive: true }); + } +} + +/** + * Host processes whose command line names a path inside `deviceSet`. A booted simulator runs a + * `launchd_sim` (and its children) out of its device directory, so a non-empty result means a + * simulator of that set is still running -- even after the set's directory is gone, which + * `simctl --set` alone can no longer see. `$TMPDIR` lives under `/var`, a symlink to + * `/private/var`, so the match drops that prefix: it then holds for either spelling. + */ +export async function processesInDeviceSet(deviceSet: string): Promise { + const needle = `${deviceSet.replace(/^\/private(?=\/)/, "")}/`; + const { stdout } = await execFileAsync("ps", ["-axo", "command="], { + maxBuffer: 16 * 1024 * 1024, + }); + return stdout.split("\n").filter((line) => line.includes(needle)); +} diff --git a/e2e/slow-ios-slim.test.ts b/e2e/slow-ios-slim.test.ts index b1cff8ccd..4b9326e36 100644 --- a/e2e/slow-ios-slim.test.ts +++ b/e2e/slow-ios-slim.test.ts @@ -1,24 +1,25 @@ -import { execFile } from "node:child_process"; -import { promisify } from "node:util"; +import { readFile } from "node:fs/promises"; import { describe, expect, it } from "vitest"; import { SLIM_CATEGORIES, labelsFor } from "../src/drivers/ios/slim-labels.js"; -import { waitFor, waitForDeviceState, withDaemon } from "./helpers/index.js"; +import { waitForDeviceState, withDaemon } from "./helpers/index.js"; import type { TestEnv } from "./helpers/env.js"; - -const execFileAsync = promisify(execFile); - -interface SimctlDevice { - readonly udid: string; - readonly name: string; - readonly state: string; -} +import { + emptyDeviceSet, + iosDeviceSet, + processesInDeviceSet, + setDevices, + simctlInSet, + sweepStaleDeviceSets, +} from "./helpers/ios-device-set.js"; /** The fields of a `simlock lease --detach` grant this lane reads, flattened. */ interface LeaseGrant { readonly lease: string; readonly udid: string; readonly mode: "slim" | "full"; + /** The device set the grant says the device lives in; no simctl call reaches it without. */ + readonly deviceSet: string; } interface DoctorReport { @@ -37,31 +38,35 @@ interface CatalogPlatform { readonly modelRuntimes: Readonly>; } -async function simctlDevices(): Promise { - const { stdout } = await execFileAsync("xcrun", ["simctl", "list", "devices", "-j"]); - const parsed = JSON.parse(stdout) as { devices: Record }; - return Object.values(parsed.devices).flat(); -} +/** + * Every device set a test in this file handed to `withDaemon`, so the last test can check that + * none of them still runs a simulator once each test's own cleanup is done. + */ +const usedDeviceSets: string[] = []; -async function deleteStraySimlockSimulators(): Promise { - const devices = await simctlDevices(); - for (const device of devices) { - if (device.name.startsWith("simlock-")) { - await execFileAsync("xcrun", ["simctl", "delete", device.udid]).catch(() => undefined); - } - } +/** + * Starts the daemon for one test and records its device set. The test's own `finally` must + * `emptyDeviceSet` it: `withDaemon`'s teardown only stops the daemon and removes the home, + * and neither shuts a booted simulator down. + */ +async function withSlimDaemon( + configOverrides: Record = {}, +): Promise<{ readonly env: TestEnv; readonly deviceSet: string }> { + const env = await withDaemon({ driver: "real", configOverrides }); + const deviceSet = iosDeviceSet(env.home); + usedDeviceSets.push(deviceSet); + return { deviceSet, env }; } /** - * Parses `xcrun simctl spawn launchctl print-disabled system`, which prints lines like + * Parses `xcrun simctl --set spawn launchctl print-disabled system`, which prints lines like * ` "com.apple.foo" => disabled` / `=> enabled` (verified live on this machine, iOS 26.4.1). * Returns only the labels currently disabled. */ -async function printDisabled(udid: string): Promise> { - const { stdout } = await execFileAsync("xcrun", [ - "simctl", +async function printDisabled(grant: LeaseGrant): Promise> { + const { stdout } = await simctlInSet(grant.deviceSet, [ "spawn", - udid, + grant.udid, "launchctl", "print-disabled", "system", @@ -82,8 +87,8 @@ async function printDisabled(udid: string): Promise> { * line; good enough as a relative, before/after comparison -- this test never asserts an * absolute count, only that a slim device's count is materially lower than a full device's. */ -async function processCount(udid: string): Promise { - const { stdout } = await execFileAsync("xcrun", ["simctl", "spawn", udid, "launchctl", "list"]); +async function processCount(grant: LeaseGrant): Promise { + const { stdout } = await simctlInSet(grant.deviceSet, ["spawn", grant.udid, "launchctl", "list"]); return stdout.split("\n").filter((line) => line.trim() !== "").length; } @@ -128,9 +133,33 @@ async function leaseDetached( expect(lease.code, `lease failed: ${lease.stderr}`).toBe(0); const grant = lease.json as { device: { driverDeviceId: string; mode: "slim" | "full" }; + environment: Record; lease: { id: string }; }; - return { lease: grant.lease.id, mode: grant.device.mode, udid: grant.device.driverDeviceId }; + const deviceSet = grant.environment.SIMLOCK_IOS_DEVICE_SET; + expect(deviceSet, "an iOS grant must name the device set its device lives in").toBeDefined(); + return { + deviceSet: deviceSet as string, + lease: grant.lease.id, + mode: grant.device.mode, + udid: grant.device.driverDeviceId, + }; +} + +/** + * The daemon's own account of every slim it skipped. A grant that comes back `full` where + * `slim` was expected says nothing about why; these lines do, so they go in the message. + */ +async function slimSkips(env: TestEnv): Promise { + const log = await readFile(env.logPath, "utf8").catch(() => ""); + const skips = log.split("\n").filter((line) => line.includes("Skipped iOS device slim")); + return skips.length === 0 ? "the daemon logged no skipped slim" : skips.join("\n"); +} + +async function expectSlim(env: TestEnv, grant: LeaseGrant, message: string): Promise { + expect(grant.mode, `${message}\n${grant.mode === "slim" ? "" : await slimSkips(env)}`).toBe( + "slim", + ); } const ALL_LABELS = new Set(labelsFor(SLIM_CATEGORIES)); @@ -146,14 +175,15 @@ describe.skipIf(process.platform !== "darwin")( "scenario 1: slim off (default) is byte-for-byte today's behaviour", { timeout: 300_000 }, async () => { - const env = await withDaemon({ driver: "real" }); + await sweepStaleDeviceSets(); + const { env, deviceSet } = await withSlimDaemon(); try { const { model, os } = await catalogModelAndOs(env); const grant = await leaseDetached(env, model, os, "slim-off-default"); expect(grant.mode, "a lease must be full when ios.slim is not configured").toBe("full"); - const disabled = await printDisabled(grant.udid); + const disabled = await printDisabled(grant); const overlap = [...ALL_LABELS].filter((label) => disabled.has(label)); expect( overlap, @@ -172,7 +202,7 @@ describe.skipIf(process.platform !== "darwin")( await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); } finally { - await deleteStraySimlockSimulators(); + await emptyDeviceSet(deviceSet); } }, ); @@ -181,10 +211,7 @@ describe.skipIf(process.platform !== "darwin")( "scenario 2/3/4/7: cold slim lease, idempotence across a reclaim, --full opt-out, and doctor advisory absence", { timeout: 900_000 }, async () => { - const env = await withDaemon({ - driver: "real", - configOverrides: { ios: { slim: { enabled: true } } }, - }); + const { env, deviceSet } = await withSlimDaemon({ ios: { slim: { enabled: true } } }); try { const { model, os } = await catalogModelAndOs(env); @@ -193,13 +220,13 @@ describe.skipIf(process.platform !== "darwin")( const fullGrant = await leaseDetached(env, model, os, "slim-full-opt-out", ["--full"]); const fullDurationMs = Date.now() - fullStart; expect(fullGrant.mode, "a --full lease's grant must carry mode: full").toBe("full"); - const fullDisabled = await printDisabled(fullGrant.udid); + const fullDisabled = await printDisabled(fullGrant); const fullOverlap = [...ALL_LABELS].filter((label) => fullDisabled.has(label)); expect( fullOverlap, `--full device must have none of the slim labels disabled, found: ${fullOverlap.join(", ")}`, ).toEqual([]); - const fullProcessCount = await processCount(fullGrant.udid); + const fullProcessCount = await processCount(fullGrant); const doctorAfterFull = (await env.cli(["doctor"])).json as DoctorReport; const driftForFull = doctorAfterFull.findings.filter( @@ -220,20 +247,20 @@ describe.skipIf(process.platform !== "darwin")( const slimGrant = await leaseDetached(env, model, os, "slim-cold"); const slimDurationMs = Date.now() - slimStart; - expect(slimGrant.mode, "a slim lease's grant must carry mode: slim").toBe("slim"); + await expectSlim(env, slimGrant, "a slim lease's grant must carry mode: slim"); expect(slimGrant.udid).not.toBe(fullGrant.udid); - const slimDisabled = await printDisabled(slimGrant.udid); + const slimDisabled = await printDisabled(slimGrant); const missing = [...ALL_LABELS].filter((label) => !slimDisabled.has(label)); expect( missing.length, `expected every slim label disabled on a slim device, missing ${missing.length} of ${ALL_LABELS.size}: ${missing.slice(0, 10).join(", ")}${missing.length > 10 ? "..." : ""}`, ).toBe(0); - const boot = await simctlDevices(); + const boot = await setDevices(slimGrant.deviceSet); expect(boot.find((device) => device.udid === slimGrant.udid)?.state).toBe("Booted"); - const slimProcessCount = await processCount(slimGrant.udid); + const slimProcessCount = await processCount(slimGrant); const reduction = 1 - slimProcessCount / fullProcessCount; expect( reduction, @@ -294,7 +321,7 @@ describe.skipIf(process.platform !== "darwin")( const relet = await leaseDetached(env, model, os, "slim-cold"); expect(relet.udid, "expected the warm-pooled device to be reused").toBe(slimGrant.udid); - expect(relet.mode, "re-leased device must still report mode: slim").toBe("slim"); + await expectSlim(env, relet, "re-leased device must still report mode: slim"); const eventsAfterRelease = await env.expectEvents(["device.slimmed", "device.slimmed"], { since: "1h", @@ -310,7 +337,7 @@ describe.skipIf(process.platform !== "darwin")( await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); } finally { - await deleteStraySimlockSimulators(); + await emptyDeviceSet(deviceSet); } }, ); @@ -329,19 +356,16 @@ describe.skipIf(process.platform !== "darwin")( labelsFor(SLIM_CATEGORIES.filter((category) => category.name === "photos")), ); - const env = await withDaemon({ - driver: "real", - configOverrides: { - ios: { slim: { enabled: true, categories: ["siri", "telemetry"] } }, - }, + const { env, deviceSet } = await withSlimDaemon({ + ios: { slim: { enabled: true, categories: ["siri", "telemetry"] } }, }); try { const { model, os } = await catalogModelAndOs(env); // --- scenario 5 --- const grant = await leaseDetached(env, model, os, "slim-subset"); - expect(grant.mode).toBe("slim"); - const disabled = await printDisabled(grant.udid); + await expectSlim(env, grant, "a categories-subset lease must be slim"); + const disabled = await printDisabled(grant); const missingSiri = [...siriLabels].filter((label) => !disabled.has(label)); const missingTelemetry = [...telemetryLabels].filter((label) => !disabled.has(label)); @@ -367,8 +391,8 @@ describe.skipIf(process.platform !== "darwin")( { ios: { slim: { enabled: true, categories: ["siri", "no-such-category"] } } }, async () => { const grant2 = await leaseDetached(env, model, os, "slim-unknown-category"); - expect(grant2.mode, "lease must still succeed and be slim").toBe("slim"); - const disabled2 = await printDisabled(grant2.udid); + await expectSlim(env, grant2, "lease must still succeed and be slim"); + const disabled2 = await printDisabled(grant2); const missingSiri2 = [...siriLabels].filter((label) => !disabled2.has(label)); expect(missingSiri2, "expected every siri label disabled").toEqual([]); @@ -376,7 +400,7 @@ describe.skipIf(process.platform !== "darwin")( }, ); } finally { - await deleteStraySimlockSimulators(); + await emptyDeviceSet(deviceSet); } }, ); @@ -385,18 +409,15 @@ describe.skipIf(process.platform !== "darwin")( "scenario 8: a health-monitor recovery boot does not re-slim", { timeout: 600_000 }, async () => { - const env = await withDaemon({ - driver: "real", - configOverrides: { - ios: { slim: { enabled: true } }, - health: { probeIntervalMs: 2_000, recoveryBackoffMs: 1_000, stableObservations: 1 }, - }, + const { env, deviceSet } = await withSlimDaemon({ + ios: { slim: { enabled: true } }, + health: { probeIntervalMs: 2_000, recoveryBackoffMs: 1_000, stableObservations: 1 }, }); try { const { model, os } = await catalogModelAndOs(env); const grant = await leaseDetached(env, model, os, "slim-recovery", []); - expect(grant.mode).toBe("slim"); - const disabledBefore = await printDisabled(grant.udid); + await expectSlim(env, grant, "a slim-mode lease must be slim"); + const disabledBefore = await printDisabled(grant); expect([...ALL_LABELS].filter((label) => !disabledBefore.has(label)).length).toBe(0); const eventsBefore = await env.events("1h"); @@ -406,17 +427,17 @@ describe.skipIf(process.platform !== "darwin")( // Pull the device out from under simlock, exactly as leased-device-crash-recovery.test.ts // does with the fake driver -- here with the real simctl toolchain. - await execFileAsync("xcrun", ["simctl", "shutdown", grant.udid]); + await simctlInSet(grant.deviceSet, ["shutdown", grant.udid]); await env.expectEvents(["device.crash-detected", "device.recovered"], { since: "1h", timeout: 180_000, }); - const booted = await simctlDevices(); + const booted = await setDevices(grant.deviceSet); expect(booted.find((device) => device.udid === grant.udid)?.state).toBe("Booted"); - const disabledAfter = await printDisabled(grant.udid); + const disabledAfter = await printDisabled(grant); const missingAfter = [...ALL_LABELS].filter((label) => !disabledAfter.has(label)); expect(missingAfter, "expected the device to still be fully slim after recovery").toEqual( [], @@ -434,16 +455,13 @@ describe.skipIf(process.platform !== "darwin")( await env.cli(["release", grant.lease]).catch(() => undefined); await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); } finally { - await deleteStraySimlockSimulators(); + await emptyDeviceSet(deviceSet); } }, ); it("scenario 9: MCP carries the device mode both ways", { timeout: 600_000 }, async () => { - const env = await withDaemon({ - driver: "real", - configOverrides: { ios: { slim: { enabled: true } } }, - }); + const { env, deviceSet } = await withSlimDaemon({ ios: { slim: { enabled: true } } }); try { const { model, os } = await catalogModelAndOs(env); const mcp = await env.mcpClient({ env: { SIMLOCK_AGENT_ID: "slim-mcp" } }); @@ -499,7 +517,7 @@ describe.skipIf(process.platform !== "darwin")( await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); } finally { - await deleteStraySimlockSimulators(); + await emptyDeviceSet(deviceSet); } // HTTP is skipped here: it needs a real reserved port plus its own auth-token setup @@ -508,11 +526,18 @@ describe.skipIf(process.platform !== "darwin")( // judged not worth a third real boot cycle in this already-expensive slow lane. }); - it("no simlock- simulator remains after this file's flows", { timeout: 60_000 }, async () => { - await waitFor( - async () => !(await simctlDevices()).some((device) => device.name.startsWith("simlock-")), - { timeout: 30_000, label: "no simlock- simulator left behind" }, - ); - }); + it( + "no simulator from this file's device sets is still running after its flows", + { timeout: 60_000 }, + async () => { + expect(usedDeviceSets.length, "expected the flows above to have run").toBeGreaterThan(0); + for (const deviceSet of usedDeviceSets) { + expect( + await processesInDeviceSet(deviceSet), + `a simulator of ${deviceSet} outlived its test`, + ).toEqual([]); + } + }, + ); }, ); diff --git a/e2e/slow-ios-smoke.test.ts b/e2e/slow-ios-smoke.test.ts index f4364010a..6bcf23f94 100644 --- a/e2e/slow-ios-smoke.test.ts +++ b/e2e/slow-ios-smoke.test.ts @@ -1,41 +1,20 @@ import { execFile } from "node:child_process"; -import { readdir, rm, stat } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; import { promisify } from "node:util"; import { describe, expect, it } from "vitest"; import { withDaemon } from "./helpers/index.js"; +import { + emptyDeviceSet, + iosDeviceSet, + setDevices, + sweepStaleDeviceSets, + type SimctlDevice, +} from "./helpers/ios-device-set.js"; import type { TestEnv } from "./helpers/env.js"; import { waitFor } from "./helpers/wait.js"; const execFileAsync = promisify(execFile); -interface SimctlDevice { - readonly udid: string; - readonly name: string; - readonly state: string; -} - -/** - * Devices in one device set. Every simctl call here carries `--set`, exactly as the - * driver's do: a device in a custom set is not addressable, or even listable, without it. - * Omitting the flag is how this lane checks the *other* half of containment -- see - * `defaultSetDevices`. - */ -async function setDevices(deviceSet: string): Promise { - const { stdout } = await execFileAsync("xcrun", [ - "simctl", - "--set", - deviceSet, - "list", - "devices", - "-j", - ]); - const parsed = JSON.parse(stdout) as { devices: Record }; - return Object.values(parsed.devices).flat(); -} - /** The machine's own device set -- the one Xcode shows. Simlock's devices must never be in it. */ async function defaultSetDevices(): Promise { const { stdout } = await execFileAsync("xcrun", ["simctl", "list", "devices", "-j"]); @@ -52,50 +31,6 @@ async function simctlRuntimes(): Promise { return parsed.runtimes.filter((runtime) => runtime.isAvailable).map((runtime) => runtime.version); } -/** - * Everything in the set, by membership rather than by name: the set is Simlock's own, so - * nothing else can be in it, and CoreSimulator has to be told to forget these devices - * before the temporary home holding them is removed. - * - * Shut down first, always. `simctl delete` refuses a booted device, and this runs on the - * failure path too -- a `waitFor` that gave up leaves devices booted -- so deleting - * without shutting down would leave a running `launchd_sim` attached to a set directory - * that `withDaemon`'s teardown is about to remove recursively. - */ -async function emptyDeviceSet(deviceSet: string): Promise { - for (const device of await setDevices(deviceSet).catch(() => [])) { - await execFileAsync("xcrun", ["simctl", "--set", deviceSet, "shutdown", device.udid]).catch( - () => undefined, - ); - await execFileAsync("xcrun", ["simctl", "--set", deviceSet, "delete", device.udid]).catch( - () => undefined, - ); - } -} - -/** Older than any run of this lane can be: its own timeout is five minutes. */ -const STALE_SET_AGE_MS = 60 * 60 * 1000; - -/** - * Device sets left behind by a run that died before its own cleanup -- a killed vitest, a - * crashed machine. Nothing else reclaims them now that the set lives inside a per-test - * temporary home instead of the shared default set the old prefix sweep covered, so the - * tens of gigabytes each holds would sit in `$TMPDIR` forever. Age-gated rather than - * scoped to this run so it can never sweep a set out from under a live one, including a - * sibling running in parallel. - */ -async function sweepStaleDeviceSets(): Promise { - const entries = await readdir(tmpdir(), { withFileTypes: true }).catch(() => []); - for (const entry of entries) { - if (!entry.isDirectory() || !entry.name.startsWith("simlock-e2e-")) continue; - const deviceSet = join(tmpdir(), entry.name, "devices", "ios"); - const details = await stat(deviceSet).catch(() => undefined); - if (details === undefined || Date.now() - details.mtimeMs < STALE_SET_AGE_MS) continue; - await emptyDeviceSet(deviceSet); - await rm(deviceSet, { force: true, recursive: true }); - } -} - // This lane needs the real simctl toolchain, hence darwin-only and gated on an // installed runtime -- it never installs one itself (no --allow-download). /** @@ -128,7 +63,7 @@ describe.skipIf(process.platform !== "darwin")( } const env = await withDaemon({ driver: "real" }); - const deviceSet = join(env.home, "devices", "ios"); + const deviceSet = iosDeviceSet(env.home); try { const catalog = await env.cli(["catalog", "--json", "--platform", "ios"]); expect(catalog.code).toBe(0); From 4b1ce9bf2dea33bd43336766cb9b0dbe75c0ebce Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 1 Oct 2026 19:20:42 +0200 Subject: [PATCH 2/9] fix(ios): a slim skipped for failed chunks says what simctl reported "all N chunk(s) failed to run" named no cause, so an intermittent failure on real simulators could not be diagnosed from the daemon log. The detail now ends with the last failed chunk's exit code and stderr, or its timeout. --- src/drivers/ios/index.test.ts | 8 ++++++-- src/drivers/ios/index.ts | 18 +++++++++++++++++- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 6031ef903..04b6c8bfd 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -2513,7 +2513,7 @@ describe("IosSimctlDriver", () => { ); }); - it("treats a total apply failure as a skip: single boot, no reboot, no marker, no event", async () => { + it("treats a total apply failure as a skip whose detail carries simctl's exit and stderr: single boot, no reboot, no marker, no event", async () => { const filesystem = new MemoryFilesystem(); await plantManagedDevice(filesystem); const runner = new ScriptedProcessRunner([ @@ -2556,7 +2556,11 @@ describe("IosSimctlDriver", () => { ]); expect(onSlimmed).not.toHaveBeenCalled(); expect(onSlimSkipped).toHaveBeenCalledWith( - expect.objectContaining({ deviceId: slim18_5.udid, reason: "apply-failed" }), + expect.objectContaining({ + deviceId: slim18_5.udid, + detail: "all 1 chunk(s) failed to run; last: exit 1: boom", + reason: "apply-failed", + }), ); }); diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 923d091ae..1d0b9ee15 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -1042,6 +1042,9 @@ export class IosSimctlDriver implements Driver { const rejectedLabels: string[] = [...rejected]; const unattemptedLabels: string[] = []; let anyChunkSucceeded = false; + // Why the most recent failed chunk failed, so a skip that drops the whole slim pass says + // what simctl actually reported rather than only that something went wrong. + let lastChunkFailure = ""; for (const chunkLabels of chunks) { // `DYLD_ROOT_PATH` is what makes a bare `launchctl` inside the simulator load the @@ -1060,6 +1063,7 @@ export class IosSimctlDriver implements Driver { if (outcome.kind === "timed-out" || outcome.result.code !== 0) { unattemptedLabels.push(...chunkLabels); + lastChunkFailure = describeFailedChunk(outcome); continue; } @@ -1073,7 +1077,10 @@ export class IosSimctlDriver implements Driver { } if (!anyChunkSucceeded) { - return { detail: `all ${String(chunks.length)} chunk(s) failed to run`, kind: "failed" }; + return { + detail: `all ${String(chunks.length)} chunk(s) failed to run; last: ${lastChunkFailure}`, + kind: "failed", + }; } return { kind: "applied", rejectedLabels, unattemptedLabels }; @@ -2188,6 +2195,15 @@ export function sanitizeSlimLabels(labels: readonly string[]): { return { rejected, safe }; } +/** What simctl reported for a slim chunk that did not run: its timeout, or exit and stderr. */ +function describeFailedChunk(outcome: ProcessOutcome): string { + if (outcome.kind === "timed-out") { + return `timed out after ${String(SLIM_CHUNK_TIMEOUT_MS)}ms`; + } + const stderr = outcome.result.stderr.trim(); + return `exit ${String(outcome.result.code)}: ${stderr === "" ? "(no stderr)" : stderr}`; +} + function chunk(items: readonly T[], size: number): readonly (readonly T[])[] { const chunks: T[][] = []; for (let index = 0; index < items.length; index += size) { From 486ca57f47b97f13fd801c59ccc227fe10456571 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 1 Oct 2026 20:01:53 +0200 Subject: [PATCH 3/9] test(e2e): withDaemon empties a real iOS device set before removing the home A test that hits its timeout is abandoned with its body still running, so cleanup in its own finally may not have run when teardown removes the home: a booted simulator kept writing into its directory (ENOTEMPTY) and outlived the run. Teardown now empties the set itself once the daemon is stopped, and the two iOS lanes drop their own copies of that cleanup. --- e2e/helpers/env.ts | 19 +- e2e/slow-ios-slim.test.ts | 568 ++++++++++++++++++------------------- e2e/slow-ios-smoke.test.ts | 225 +++++++-------- 3 files changed, 391 insertions(+), 421 deletions(-) diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index 51edc902b..45723627f 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -22,6 +22,7 @@ import { type DriverScriptControl, } from "./driver-script.js"; import { events, expectEvents, type RecordedEvent } from "./events.js"; +import { emptyDeviceSet, iosDeviceSet } from "./ios-device-set.js"; import { mcpClient, type McpClientHandle, type McpClientOptions } from "./mcp.js"; import { REPO_ROOT } from "./repo-root.js"; import { waitFor } from "./wait.js"; @@ -299,7 +300,14 @@ export async function withDaemon(options: WithDaemonOptions = {}): Promise; + /** The real-SDK lane: the home holds a real iOS device set that must be emptied first. */ + readonly realDrivers: boolean; readonly socketPath: string; } async function teardown(state: TeardownState): Promise { - const { backgroundProcesses, env, home, mcpClients, socketPath } = state; + const { backgroundProcesses, env, home, mcpClients, realDrivers, socketPath } = state; for (const client of mcpClients) { await client.close().catch(() => undefined); } @@ -358,6 +368,11 @@ async function teardown(state: TeardownState): Promise { } } + // Here rather than in each test's own `finally`: a test that hits its timeout is abandoned + // with its body still running, so its `finally` may not have run yet -- and a booted + // simulator keeps writing into its device directory while `rm` below walks it (`ENOTEMPTY`), + // then outlives the home. The daemon is stopped by now, so nothing boots another one. + if (realDrivers) await emptyDeviceSet(iosDeviceSet(home)); await rm(home, { force: true, recursive: true }); if (strayPids.length > 0) { diff --git a/e2e/slow-ios-slim.test.ts b/e2e/slow-ios-slim.test.ts index 4b9326e36..e641817fc 100644 --- a/e2e/slow-ios-slim.test.ts +++ b/e2e/slow-ios-slim.test.ts @@ -5,7 +5,6 @@ import { SLIM_CATEGORIES, labelsFor } from "../src/drivers/ios/slim-labels.js"; import { waitForDeviceState, withDaemon } from "./helpers/index.js"; import type { TestEnv } from "./helpers/env.js"; import { - emptyDeviceSet, iosDeviceSet, processesInDeviceSet, setDevices, @@ -40,22 +39,15 @@ interface CatalogPlatform { /** * Every device set a test in this file handed to `withDaemon`, so the last test can check that - * none of them still runs a simulator once each test's own cleanup is done. + * none of them still runs a simulator once teardown has emptied it. */ const usedDeviceSets: string[] = []; -/** - * Starts the daemon for one test and records its device set. The test's own `finally` must - * `emptyDeviceSet` it: `withDaemon`'s teardown only stops the daemon and removes the home, - * and neither shuts a booted simulator down. - */ -async function withSlimDaemon( - configOverrides: Record = {}, -): Promise<{ readonly env: TestEnv; readonly deviceSet: string }> { +/** Starts the real-driver daemon for one test and records its device set. */ +async function withSlimDaemon(configOverrides: Record = {}): Promise { const env = await withDaemon({ driver: "real", configOverrides }); - const deviceSet = iosDeviceSet(env.home); - usedDeviceSets.push(deviceSet); - return { deviceSet, env }; + usedDeviceSets.push(iosDeviceSet(env.home)); + return env; } /** @@ -176,34 +168,30 @@ describe.skipIf(process.platform !== "darwin")( { timeout: 300_000 }, async () => { await sweepStaleDeviceSets(); - const { env, deviceSet } = await withSlimDaemon(); - try { - const { model, os } = await catalogModelAndOs(env); - const grant = await leaseDetached(env, model, os, "slim-off-default"); + const env = await withSlimDaemon(); + const { model, os } = await catalogModelAndOs(env); + const grant = await leaseDetached(env, model, os, "slim-off-default"); - expect(grant.mode, "a lease must be full when ios.slim is not configured").toBe("full"); + expect(grant.mode, "a lease must be full when ios.slim is not configured").toBe("full"); - const disabled = await printDisabled(grant); - const overlap = [...ALL_LABELS].filter((label) => disabled.has(label)); - expect( - overlap, - `expected none of the slim label set disabled on a non-slim device, found: ${overlap.join(", ")}`, - ).toEqual([]); + const disabled = await printDisabled(grant); + const overlap = [...ALL_LABELS].filter((label) => disabled.has(label)); + expect( + overlap, + `expected none of the slim label set disabled on a non-slim device, found: ${overlap.join(", ")}`, + ).toEqual([]); - const recorded = await env.events("1h"); - const slimmedEvents = recorded.filter((event) => event.event === "device.slimmed"); - expect(slimmedEvents, "no device.slimmed event expected with slim off").toEqual([]); + const recorded = await env.events("1h"); + const slimmedEvents = recorded.filter((event) => event.event === "device.slimmed"); + expect(slimmedEvents, "no device.slimmed event expected with slim off").toEqual([]); - const doctorReport = (await env.cli(["doctor"])).json as DoctorReport; - const advisories = doctorReport.findings.filter( - (finding) => finding.kind === "driver-advisory", - ); - expect(advisories, "no driver-advisory finding expected with slim off").toEqual([]); + const doctorReport = (await env.cli(["doctor"])).json as DoctorReport; + const advisories = doctorReport.findings.filter( + (finding) => finding.kind === "driver-advisory", + ); + expect(advisories, "no driver-advisory finding expected with slim off").toEqual([]); - await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); - } finally { - await emptyDeviceSet(deviceSet); - } + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); }, ); @@ -211,134 +199,130 @@ describe.skipIf(process.platform !== "darwin")( "scenario 2/3/4/7: cold slim lease, idempotence across a reclaim, --full opt-out, and doctor advisory absence", { timeout: 900_000 }, async () => { - const { env, deviceSet } = await withSlimDaemon({ ios: { slim: { enabled: true } } }); - try { - const { model, os } = await catalogModelAndOs(env); - - // --- scenario 4 half A + baseline process count: a --full lease is untouched. --- - const fullStart = Date.now(); - const fullGrant = await leaseDetached(env, model, os, "slim-full-opt-out", ["--full"]); - const fullDurationMs = Date.now() - fullStart; - expect(fullGrant.mode, "a --full lease's grant must carry mode: full").toBe("full"); - const fullDisabled = await printDisabled(fullGrant); - const fullOverlap = [...ALL_LABELS].filter((label) => fullDisabled.has(label)); - expect( - fullOverlap, - `--full device must have none of the slim labels disabled, found: ${fullOverlap.join(", ")}`, - ).toEqual([]); - const fullProcessCount = await processCount(fullGrant); - - const doctorAfterFull = (await env.cli(["doctor"])).json as DoctorReport; - const driftForFull = doctorAfterFull.findings.filter( - (finding) => finding.kind !== "driver-advisory" && finding.deviceId !== undefined, - ); - expect( - driftForFull.filter((finding) => finding.deviceId === fullGrant.udid), - "doctor must report no drift for the --full device", - ).toEqual([]); - - // --- scenario 2: a cold, non-full lease produces a slim device. --- - const eventsBeforeSlim = await env.events("1h"); - const slimmedBefore = eventsBeforeSlim.filter( - (event) => event.event === "device.slimmed", - ).length; - - const slimStart = Date.now(); - const slimGrant = await leaseDetached(env, model, os, "slim-cold"); - const slimDurationMs = Date.now() - slimStart; - - await expectSlim(env, slimGrant, "a slim lease's grant must carry mode: slim"); - expect(slimGrant.udid).not.toBe(fullGrant.udid); + const env = await withSlimDaemon({ ios: { slim: { enabled: true } } }); + const { model, os } = await catalogModelAndOs(env); - const slimDisabled = await printDisabled(slimGrant); - const missing = [...ALL_LABELS].filter((label) => !slimDisabled.has(label)); - expect( - missing.length, - `expected every slim label disabled on a slim device, missing ${missing.length} of ${ALL_LABELS.size}: ${missing.slice(0, 10).join(", ")}${missing.length > 10 ? "..." : ""}`, - ).toBe(0); + // --- scenario 4 half A + baseline process count: a --full lease is untouched. --- + const fullStart = Date.now(); + const fullGrant = await leaseDetached(env, model, os, "slim-full-opt-out", ["--full"]); + const fullDurationMs = Date.now() - fullStart; + expect(fullGrant.mode, "a --full lease's grant must carry mode: full").toBe("full"); + const fullDisabled = await printDisabled(fullGrant); + const fullOverlap = [...ALL_LABELS].filter((label) => fullDisabled.has(label)); + expect( + fullOverlap, + `--full device must have none of the slim labels disabled, found: ${fullOverlap.join(", ")}`, + ).toEqual([]); + const fullProcessCount = await processCount(fullGrant); + + const doctorAfterFull = (await env.cli(["doctor"])).json as DoctorReport; + const driftForFull = doctorAfterFull.findings.filter( + (finding) => finding.kind !== "driver-advisory" && finding.deviceId !== undefined, + ); + expect( + driftForFull.filter((finding) => finding.deviceId === fullGrant.udid), + "doctor must report no drift for the --full device", + ).toEqual([]); + + // --- scenario 2: a cold, non-full lease produces a slim device. --- + const eventsBeforeSlim = await env.events("1h"); + const slimmedBefore = eventsBeforeSlim.filter( + (event) => event.event === "device.slimmed", + ).length; + + const slimStart = Date.now(); + const slimGrant = await leaseDetached(env, model, os, "slim-cold"); + const slimDurationMs = Date.now() - slimStart; + + await expectSlim(env, slimGrant, "a slim lease's grant must carry mode: slim"); + expect(slimGrant.udid).not.toBe(fullGrant.udid); + + const slimDisabled = await printDisabled(slimGrant); + const missing = [...ALL_LABELS].filter((label) => !slimDisabled.has(label)); + expect( + missing.length, + `expected every slim label disabled on a slim device, missing ${missing.length} of ${ALL_LABELS.size}: ${missing.slice(0, 10).join(", ")}${missing.length > 10 ? "..." : ""}`, + ).toBe(0); + + const boot = await setDevices(slimGrant.deviceSet); + expect(boot.find((device) => device.udid === slimGrant.udid)?.state).toBe("Booted"); + + const slimProcessCount = await processCount(slimGrant); + const reduction = 1 - slimProcessCount / fullProcessCount; + expect( + reduction, + `expected the slim device's launchctl job count (${String(slimProcessCount)}) to be ` + + `at least 30% lower than the full device's (${String(fullProcessCount)}), got a ` + + `${(reduction * 100).toFixed(1)}% reduction`, + ).toBeGreaterThanOrEqual(0.3); + + const eventsAfterSlim = await env.expectEvents(["device.slimmed"], { since: "1h" }); + const slimmedEvents = eventsAfterSlim.filter((event) => event.event === "device.slimmed"); + expect(slimmedEvents.length).toBe(slimmedBefore + 1); + const slimmedFact = slimmedEvents.at(-1)?.payload as { + deviceId: string; + platform?: string; + categories: readonly string[]; + labelCount: number; + unknownLabels: readonly string[]; + }; + expect(slimmedFact.categories.length, "expected every category resolved").toBe( + SLIM_CATEGORIES.length, + ); + expect(new Set(slimmedFact.categories)).toEqual(ALL_CATEGORY_NAMES); + expect(slimmedFact.labelCount).toBe(ALL_LABELS.size); + // Reported, not asserted empty -- known-pitfalls.md documents that Apple drift can + // legitimately produce rejected labels here; this is evidence for the report, not a + // pass/fail condition. + // eslint-disable-next-line no-console + console.log( + `[slim e2e] scenario 2 unknownLabels (${slimmedFact.unknownLabels.length}): ` + + JSON.stringify(slimmedFact.unknownLabels), + ); - const boot = await setDevices(slimGrant.deviceSet); - expect(boot.find((device) => device.udid === slimGrant.udid)?.state).toBe("Booted"); + console.log( + `[slim e2e] lease duration: full=${String(fullDurationMs)}ms slim(cold)=${String(slimDurationMs)}ms; ` + + `process count: full=${String(fullProcessCount)} slim=${String(slimProcessCount)} ` + + `(${(reduction * 100).toFixed(1)}% reduction)`, + ); - const slimProcessCount = await processCount(slimGrant); - const reduction = 1 - slimProcessCount / fullProcessCount; - expect( - reduction, - `expected the slim device's launchctl job count (${String(slimProcessCount)}) to be ` + - `at least 30% lower than the full device's (${String(fullProcessCount)}), got a ` + - `${(reduction * 100).toFixed(1)}% reduction`, - ).toBeGreaterThanOrEqual(0.3); - - const eventsAfterSlim = await env.expectEvents(["device.slimmed"], { since: "1h" }); - const slimmedEvents = eventsAfterSlim.filter((event) => event.event === "device.slimmed"); - expect(slimmedEvents.length).toBe(slimmedBefore + 1); - const slimmedFact = slimmedEvents.at(-1)?.payload as { - deviceId: string; - platform?: string; - categories: readonly string[]; - labelCount: number; - unknownLabels: readonly string[]; - }; - expect(slimmedFact.categories.length, "expected every category resolved").toBe( - SLIM_CATEGORIES.length, - ); - expect(new Set(slimmedFact.categories)).toEqual(ALL_CATEGORY_NAMES); - expect(slimmedFact.labelCount).toBe(ALL_LABELS.size); - // Reported, not asserted empty -- known-pitfalls.md documents that Apple drift can - // legitimately produce rejected labels here; this is evidence for the report, not a - // pass/fail condition. - // eslint-disable-next-line no-console - console.log( - `[slim e2e] scenario 2 unknownLabels (${slimmedFact.unknownLabels.length}): ` + - JSON.stringify(slimmedFact.unknownLabels), - ); - - console.log( - `[slim e2e] lease duration: full=${String(fullDurationMs)}ms slim(cold)=${String(slimDurationMs)}ms; ` + - `process count: full=${String(fullProcessCount)} slim=${String(slimProcessCount)} ` + - `(${(reduction * 100).toFixed(1)}% reduction)`, - ); - - // --- scenario 7: doctor advisory is absent (both installed runtimes are >= 18.5). --- - const doctorAfterSlim = (await env.cli(["doctor"])).json as DoctorReport; - const advisories = doctorAfterSlim.findings.filter( - (finding) => finding.kind === "driver-advisory", - ); - expect( - advisories, - "expected no slim-runtime-unsupported advisory: both installed runtimes on this " + - "machine (26.4.1, 27.0) are >= 18.5", - ).toEqual([]); + // --- scenario 7: doctor advisory is absent (both installed runtimes are >= 18.5). --- + const doctorAfterSlim = (await env.cli(["doctor"])).json as DoctorReport; + const advisories = doctorAfterSlim.findings.filter( + (finding) => finding.kind === "driver-advisory", + ); + expect( + advisories, + "expected no slim-runtime-unsupported advisory: both installed runtimes on this " + + "machine (26.4.1, 27.0) are >= 18.5", + ).toEqual([]); + + // --- scenario 3: release, then re-lease the same spec. Per docs/internal/KNOWN-PITFALLS.md + // ("Every reclaim pays two boots, indefinitely"), IosSimctlDriver.reclaim always runs + // `simctl erase`, wiping the launchctl overrides -- so the documented behaviour is + // that the warm-pooled device comes back stock and pays a SECOND device.slimmed, not + // that it's skipped. We assert that documented behaviour here. + const releaseResult = await env.cli(["release", slimGrant.lease]); + expect(releaseResult.code).toBe(0); + await waitForDeviceState(env, slimGrant.udid, "ready", { timeout: 120_000 }); + + const relet = await leaseDetached(env, model, os, "slim-cold"); + expect(relet.udid, "expected the warm-pooled device to be reused").toBe(slimGrant.udid); + await expectSlim(env, relet, "re-leased device must still report mode: slim"); + + const eventsAfterRelease = await env.expectEvents(["device.slimmed", "device.slimmed"], { + since: "1h", + }); + const slimmedAfterRelease = eventsAfterRelease.filter( + (event) => event.event === "device.slimmed", + ); + expect( + slimmedAfterRelease.length, + "expected a SECOND device.slimmed for this udid after release+re-lease, per the " + + "documented erase-on-reclaim cost (docs/internal/KNOWN-PITFALLS.md)", + ).toBe(slimmedBefore + 2); - // --- scenario 3: release, then re-lease the same spec. Per docs/internal/KNOWN-PITFALLS.md - // ("Every reclaim pays two boots, indefinitely"), IosSimctlDriver.reclaim always runs - // `simctl erase`, wiping the launchctl overrides -- so the documented behaviour is - // that the warm-pooled device comes back stock and pays a SECOND device.slimmed, not - // that it's skipped. We assert that documented behaviour here. - const releaseResult = await env.cli(["release", slimGrant.lease]); - expect(releaseResult.code).toBe(0); - await waitForDeviceState(env, slimGrant.udid, "ready", { timeout: 120_000 }); - - const relet = await leaseDetached(env, model, os, "slim-cold"); - expect(relet.udid, "expected the warm-pooled device to be reused").toBe(slimGrant.udid); - await expectSlim(env, relet, "re-leased device must still report mode: slim"); - - const eventsAfterRelease = await env.expectEvents(["device.slimmed", "device.slimmed"], { - since: "1h", - }); - const slimmedAfterRelease = eventsAfterRelease.filter( - (event) => event.event === "device.slimmed", - ); - expect( - slimmedAfterRelease.length, - "expected a SECOND device.slimmed for this udid after release+re-lease, per the " + - "documented erase-on-reclaim cost (docs/internal/KNOWN-PITFALLS.md)", - ).toBe(slimmedBefore + 2); - - await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); - } finally { - await emptyDeviceSet(deviceSet); - } + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); }, ); @@ -356,52 +340,48 @@ describe.skipIf(process.platform !== "darwin")( labelsFor(SLIM_CATEGORIES.filter((category) => category.name === "photos")), ); - const { env, deviceSet } = await withSlimDaemon({ + const env = await withSlimDaemon({ ios: { slim: { enabled: true, categories: ["siri", "telemetry"] } }, }); - try { - const { model, os } = await catalogModelAndOs(env); + const { model, os } = await catalogModelAndOs(env); - // --- scenario 5 --- - const grant = await leaseDetached(env, model, os, "slim-subset"); - await expectSlim(env, grant, "a categories-subset lease must be slim"); - const disabled = await printDisabled(grant); + // --- scenario 5 --- + const grant = await leaseDetached(env, model, os, "slim-subset"); + await expectSlim(env, grant, "a categories-subset lease must be slim"); + const disabled = await printDisabled(grant); - const missingSiri = [...siriLabels].filter((label) => !disabled.has(label)); - const missingTelemetry = [...telemetryLabels].filter((label) => !disabled.has(label)); - expect(missingSiri, "expected every siri label disabled").toEqual([]); - expect(missingTelemetry, "expected every telemetry label disabled").toEqual([]); + const missingSiri = [...siriLabels].filter((label) => !disabled.has(label)); + const missingTelemetry = [...telemetryLabels].filter((label) => !disabled.has(label)); + expect(missingSiri, "expected every siri label disabled").toEqual([]); + expect(missingTelemetry, "expected every telemetry label disabled").toEqual([]); - const leakedPhotos = [...photosLabels].filter((label) => disabled.has(label)); - expect( - leakedPhotos, - `expected no photos-category label disabled, found: ${leakedPhotos.join(", ")}`, - ).toEqual([]); + const leakedPhotos = [...photosLabels].filter((label) => disabled.has(label)); + expect( + leakedPhotos, + `expected no photos-category label disabled, found: ${leakedPhotos.join(", ")}`, + ).toEqual([]); - const recorded = await env.expectEvents(["device.slimmed"], { since: "1h" }); - const fact = recorded.find((event) => event.event === "device.slimmed")?.payload as { - categories: readonly string[]; - }; - expect(fact.categories).toEqual(["siri", "telemetry"]); - - await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); - - // --- scenario 6: an unknown category alongside a known one is not fatal. --- - await env.withConfig( - { ios: { slim: { enabled: true, categories: ["siri", "no-such-category"] } } }, - async () => { - const grant2 = await leaseDetached(env, model, os, "slim-unknown-category"); - await expectSlim(env, grant2, "lease must still succeed and be slim"); - const disabled2 = await printDisabled(grant2); - const missingSiri2 = [...siriLabels].filter((label) => !disabled2.has(label)); - expect(missingSiri2, "expected every siri label disabled").toEqual([]); - - await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); - }, - ); - } finally { - await emptyDeviceSet(deviceSet); - } + const recorded = await env.expectEvents(["device.slimmed"], { since: "1h" }); + const fact = recorded.find((event) => event.event === "device.slimmed")?.payload as { + categories: readonly string[]; + }; + expect(fact.categories).toEqual(["siri", "telemetry"]); + + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); + + // --- scenario 6: an unknown category alongside a known one is not fatal. --- + await env.withConfig( + { ios: { slim: { enabled: true, categories: ["siri", "no-such-category"] } } }, + async () => { + const grant2 = await leaseDetached(env, model, os, "slim-unknown-category"); + await expectSlim(env, grant2, "lease must still succeed and be slim"); + const disabled2 = await printDisabled(grant2); + const missingSiri2 = [...siriLabels].filter((label) => !disabled2.has(label)); + expect(missingSiri2, "expected every siri label disabled").toEqual([]); + + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); + }, + ); }, ); @@ -409,117 +389,107 @@ describe.skipIf(process.platform !== "darwin")( "scenario 8: a health-monitor recovery boot does not re-slim", { timeout: 600_000 }, async () => { - const { env, deviceSet } = await withSlimDaemon({ + const env = await withSlimDaemon({ ios: { slim: { enabled: true } }, health: { probeIntervalMs: 2_000, recoveryBackoffMs: 1_000, stableObservations: 1 }, }); - try { - const { model, os } = await catalogModelAndOs(env); - const grant = await leaseDetached(env, model, os, "slim-recovery", []); - await expectSlim(env, grant, "a slim-mode lease must be slim"); - const disabledBefore = await printDisabled(grant); - expect([...ALL_LABELS].filter((label) => !disabledBefore.has(label)).length).toBe(0); - - const eventsBefore = await env.events("1h"); - const slimmedBefore = eventsBefore.filter( - (event) => event.event === "device.slimmed", - ).length; - - // Pull the device out from under simlock, exactly as leased-device-crash-recovery.test.ts - // does with the fake driver -- here with the real simctl toolchain. - await simctlInSet(grant.deviceSet, ["shutdown", grant.udid]); - - await env.expectEvents(["device.crash-detected", "device.recovered"], { - since: "1h", - timeout: 180_000, - }); - - const booted = await setDevices(grant.deviceSet); - expect(booted.find((device) => device.udid === grant.udid)?.state).toBe("Booted"); - - const disabledAfter = await printDisabled(grant); - const missingAfter = [...ALL_LABELS].filter((label) => !disabledAfter.has(label)); - expect(missingAfter, "expected the device to still be fully slim after recovery").toEqual( - [], - ); - - const eventsAfter = await env.events("1h"); - const slimmedAfter = eventsAfter.filter( - (event) => event.event === "device.slimmed", - ).length; - expect( - slimmedAfter, - "recovery must not fire a new device.slimmed (recover purpose never slims)", - ).toBe(slimmedBefore); - - await env.cli(["release", grant.lease]).catch(() => undefined); - await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); - } finally { - await emptyDeviceSet(deviceSet); - } + const { model, os } = await catalogModelAndOs(env); + const grant = await leaseDetached(env, model, os, "slim-recovery", []); + await expectSlim(env, grant, "a slim-mode lease must be slim"); + const disabledBefore = await printDisabled(grant); + expect([...ALL_LABELS].filter((label) => !disabledBefore.has(label)).length).toBe(0); + + const eventsBefore = await env.events("1h"); + const slimmedBefore = eventsBefore.filter( + (event) => event.event === "device.slimmed", + ).length; + + // Pull the device out from under simlock, exactly as leased-device-crash-recovery.test.ts + // does with the fake driver -- here with the real simctl toolchain. + await simctlInSet(grant.deviceSet, ["shutdown", grant.udid]); + + await env.expectEvents(["device.crash-detected", "device.recovered"], { + since: "1h", + timeout: 180_000, + }); + + const booted = await setDevices(grant.deviceSet); + expect(booted.find((device) => device.udid === grant.udid)?.state).toBe("Booted"); + + const disabledAfter = await printDisabled(grant); + const missingAfter = [...ALL_LABELS].filter((label) => !disabledAfter.has(label)); + expect(missingAfter, "expected the device to still be fully slim after recovery").toEqual( + [], + ); + + const eventsAfter = await env.events("1h"); + const slimmedAfter = eventsAfter.filter((event) => event.event === "device.slimmed").length; + expect( + slimmedAfter, + "recovery must not fire a new device.slimmed (recover purpose never slims)", + ).toBe(slimmedBefore); + + await env.cli(["release", grant.lease]).catch(() => undefined); + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); }, ); it("scenario 9: MCP carries the device mode both ways", { timeout: 600_000 }, async () => { - const { env, deviceSet } = await withSlimDaemon({ ios: { slim: { enabled: true } } }); + const env = await withSlimDaemon({ ios: { slim: { enabled: true } } }); + const { model, os } = await catalogModelAndOs(env); + const mcp = await env.mcpClient({ env: { SIMLOCK_AGENT_ID: "slim-mcp" } }); try { - const { model, os } = await catalogModelAndOs(env); - const mcp = await env.mcpClient({ env: { SIMLOCK_AGENT_ID: "slim-mcp" } }); - try { - // The SDK's default request timeout is 60s; a cold slim lease takes ~160s on this - // machine (two real boots). Simlock relays boot progress as MCP progress - // notifications, so a client that resets its timeout on progress survives it -- - // which is what a real agent's client must do too (see docs/internal/KNOWN-PITFALLS.md). - const leaseCallOptions = { resetTimeoutOnProgress: true, timeout: 600_000 }; - const fullResult = await mcp.client.callTool( - { - name: "lease_simulator", - arguments: { full: true, model, osVersion: os, platform: "ios" }, - }, - undefined, - leaseCallOptions, - ); - const fullLeased = fullResult.structuredContent as { - device: { mode: "slim" | "full" }; - lease: { id: string }; - }; - expect(fullLeased.device.mode, "MCP full:true lease must report mode: full").toBe("full"); - - await mcp.client.callTool({ - name: "release_simulator", - arguments: { leaseId: fullLeased.lease.id }, - }); - - const slimResult = await mcp.client.callTool( - { - name: "lease_simulator", - arguments: { model, osVersion: os, platform: "ios" }, - }, - undefined, - leaseCallOptions, - ); - const slimLeased = slimResult.structuredContent as { - device: { mode: "slim" | "full" }; - lease: { id: string }; - }; - expect( - slimLeased.device.mode, - "MCP plain lease under ios.slim.enabled must report mode: slim", - ).toBe("slim"); - - await mcp.client.callTool({ - name: "release_simulator", - arguments: { leaseId: slimLeased.lease.id }, - }); - } finally { - await mcp.close(); - } + // The SDK's default request timeout is 60s; a cold slim lease takes ~160s on this + // machine (two real boots). Simlock relays boot progress as MCP progress + // notifications, so a client that resets its timeout on progress survives it -- + // which is what a real agent's client must do too (see docs/internal/KNOWN-PITFALLS.md). + const leaseCallOptions = { resetTimeoutOnProgress: true, timeout: 600_000 }; + const fullResult = await mcp.client.callTool( + { + name: "lease_simulator", + arguments: { full: true, model, osVersion: os, platform: "ios" }, + }, + undefined, + leaseCallOptions, + ); + const fullLeased = fullResult.structuredContent as { + device: { mode: "slim" | "full" }; + lease: { id: string }; + }; + expect(fullLeased.device.mode, "MCP full:true lease must report mode: full").toBe("full"); + + await mcp.client.callTool({ + name: "release_simulator", + arguments: { leaseId: fullLeased.lease.id }, + }); - await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); + const slimResult = await mcp.client.callTool( + { + name: "lease_simulator", + arguments: { model, osVersion: os, platform: "ios" }, + }, + undefined, + leaseCallOptions, + ); + const slimLeased = slimResult.structuredContent as { + device: { mode: "slim" | "full" }; + lease: { id: string }; + }; + expect( + slimLeased.device.mode, + "MCP plain lease under ios.slim.enabled must report mode: slim", + ).toBe("slim"); + + await mcp.client.callTool({ + name: "release_simulator", + arguments: { leaseId: slimLeased.lease.id }, + }); } finally { - await emptyDeviceSet(deviceSet); + await mcp.close(); } + await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); + // HTTP is skipped here: it needs a real reserved port plus its own auth-token setup // (see http-api.test.ts) on top of another real cold iOS lease, which -- given MCP // already exercises the same `grant.device.mode` plumbing through a second transport -- was diff --git a/e2e/slow-ios-smoke.test.ts b/e2e/slow-ios-smoke.test.ts index 6bcf23f94..90f7ea24c 100644 --- a/e2e/slow-ios-smoke.test.ts +++ b/e2e/slow-ios-smoke.test.ts @@ -4,7 +4,6 @@ import { describe, expect, it } from "vitest"; import { withDaemon } from "./helpers/index.js"; import { - emptyDeviceSet, iosDeviceSet, setDevices, sweepStaleDeviceSets, @@ -64,128 +63,114 @@ describe.skipIf(process.platform !== "darwin")( const env = await withDaemon({ driver: "real" }); const deviceSet = iosDeviceSet(env.home); - try { - const catalog = await env.cli(["catalog", "--json", "--platform", "ios"]); - expect(catalog.code).toBe(0); - const platforms = ( - catalog.json as { - platforms: { platform: string; models: string[]; runtimes: string[] }[]; - } - ).platforms; - const iosCatalog = platforms.find((platform) => platform.platform === "ios"); - expect(iosCatalog, "simlock catalog reported no iOS platform").toBeDefined(); - expect( - iosCatalog?.models.length ?? 0, - "simlock catalog reported no iOS models", - ).toBeGreaterThan(0); - for (const runtime of iosCatalog?.runtimes ?? []) { - expect( - availableRuntimes, - "simlock catalog's runtimes must agree with real simctl", - ).toContain(runtime); + const catalog = await env.cli(["catalog", "--json", "--platform", "ios"]); + expect(catalog.code).toBe(0); + const platforms = ( + catalog.json as { + platforms: { platform: string; models: string[]; runtimes: string[] }[]; } - const model = iosCatalog?.models[0] as string; - - const lease = await env.cli( - [ - "lease", - "--platform", - "ios", - "--device", - model, - "--agent-id", - "ios-smoke", - "--detach", - ], - { timeout: 120_000 }, - ); - expect(lease.code, `lease failed: ${lease.stderr}`).toBe(0); - const grant = lease.json as { - device: { driverDeviceId: string }; - environment: Record; - lease: { id: string }; - }; - // On iOS the driver's device id is the simulator's UDID. - const udid = grant.device.driverDeviceId; - - // The grant has to say how to reach the device, because nothing else does: the - // UDID below resolves to nothing without this path (ADR 0001, decision 7). - expect(grant.environment).toEqual({ SIMLOCK_IOS_DEVICE_SET: deviceSet }); - - await expectSimctlPassthrough(env, udid); - - const booted = await setDevices(deviceSet); - const bootedDevice = booted.find((device) => device.udid === udid); - expect( - bootedDevice, - `simctl --set ${deviceSet} does not know about udid ${udid}`, - ).toBeDefined(); - expect(bootedDevice?.state).toBe("Booted"); - // The naming is a label with no authority behind it (safety rule 8) -- what - // proves ownership is the set the device was just found in -- but it is still - // what a human reads in the simulator window title, so it stays checked. - expect( - bootedDevice?.name.startsWith("simlock-"), - "device name must carry the simlock- prefix", - ).toBe(true); - expect( - (await defaultSetDevices()).some((device) => device.udid === udid), - "a Simlock simulator must be invisible in the machine's default device set", - ).toBe(false); - - // Provenance: both marks exist with the same token. `doctor` is the - // documented way to observe this -- a foreign-provenance-change finding - // for this device would mean the marks disagree or are missing. - const doctorReport = await env.cli(["doctor"]); - expect(doctorReport.code).toBe(0); - const findings = ( - doctorReport.json as { findings: { kind: string; deviceId?: string }[] } - ).findings; - const devices = (await env.cli(["list", "--devices"])).json as { - id: string; - driverDeviceId: string; - }[]; - const registryId = devices.find((device) => device.driverDeviceId === udid)?.id; - expect( - findings.some( - (finding) => - finding.kind === "foreign-provenance-change" && finding.deviceId === registryId, - ), - "expected no provenance drift for a device simlock just created", - ).toBe(false); + ).platforms; + const iosCatalog = platforms.find((platform) => platform.platform === "ios"); + expect(iosCatalog, "simlock catalog reported no iOS platform").toBeDefined(); + expect( + iosCatalog?.models.length ?? 0, + "simlock catalog reported no iOS models", + ).toBeGreaterThan(0); + for (const runtime of iosCatalog?.runtimes ?? []) { expect( - findings.some((finding) => finding.kind === "driver-unavailable"), - "the iOS driver must have started, with a root it owns", - ).toBe(false); - - const release = await env.cli(["release", grant.lease.id]); - expect(release.code, `release failed: ${release.stderr}`).toBe(0); - - // Still Booted: the warm pool only demotes after idle.shutdownAfterMs, - // which defaults far longer than this test. - await waitFor( - async () => { - const rows = (await env.cli(["list", "--devices"])).json as { - driverDeviceId: string; - state: string; - }[]; - return rows.some((row) => row.driverDeviceId === udid && row.state === "ready"); - }, - { timeout: 60_000, label: "device returns to ready after release" }, - ); - const stillBooted = await setDevices(deviceSet); - expect(stillBooted.find((device) => device.udid === udid)?.state).toBe("Booted"); - - const nuke = await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 60_000 }); - expect(nuke.code).toBe(0); - - await waitFor(async () => (await setDevices(deviceSet)).length === 0, { - timeout: 60_000, - label: "no simulator remains in Simlock's device set after nuke --delete-devices", - }); - } finally { - await emptyDeviceSet(deviceSet); + availableRuntimes, + "simlock catalog's runtimes must agree with real simctl", + ).toContain(runtime); } + const model = iosCatalog?.models[0] as string; + + const lease = await env.cli( + ["lease", "--platform", "ios", "--device", model, "--agent-id", "ios-smoke", "--detach"], + { timeout: 120_000 }, + ); + expect(lease.code, `lease failed: ${lease.stderr}`).toBe(0); + const grant = lease.json as { + device: { driverDeviceId: string }; + environment: Record; + lease: { id: string }; + }; + // On iOS the driver's device id is the simulator's UDID. + const udid = grant.device.driverDeviceId; + + // The grant has to say how to reach the device, because nothing else does: the + // UDID below resolves to nothing without this path (ADR 0001, decision 7). + expect(grant.environment).toEqual({ SIMLOCK_IOS_DEVICE_SET: deviceSet }); + + await expectSimctlPassthrough(env, udid); + + const booted = await setDevices(deviceSet); + const bootedDevice = booted.find((device) => device.udid === udid); + expect( + bootedDevice, + `simctl --set ${deviceSet} does not know about udid ${udid}`, + ).toBeDefined(); + expect(bootedDevice?.state).toBe("Booted"); + // The naming is a label with no authority behind it (safety rule 8) -- what + // proves ownership is the set the device was just found in -- but it is still + // what a human reads in the simulator window title, so it stays checked. + expect( + bootedDevice?.name.startsWith("simlock-"), + "device name must carry the simlock- prefix", + ).toBe(true); + expect( + (await defaultSetDevices()).some((device) => device.udid === udid), + "a Simlock simulator must be invisible in the machine's default device set", + ).toBe(false); + + // Provenance: both marks exist with the same token. `doctor` is the + // documented way to observe this -- a foreign-provenance-change finding + // for this device would mean the marks disagree or are missing. + const doctorReport = await env.cli(["doctor"]); + expect(doctorReport.code).toBe(0); + const findings = (doctorReport.json as { findings: { kind: string; deviceId?: string }[] }) + .findings; + const devices = (await env.cli(["list", "--devices"])).json as { + id: string; + driverDeviceId: string; + }[]; + const registryId = devices.find((device) => device.driverDeviceId === udid)?.id; + expect( + findings.some( + (finding) => + finding.kind === "foreign-provenance-change" && finding.deviceId === registryId, + ), + "expected no provenance drift for a device simlock just created", + ).toBe(false); + expect( + findings.some((finding) => finding.kind === "driver-unavailable"), + "the iOS driver must have started, with a root it owns", + ).toBe(false); + + const release = await env.cli(["release", grant.lease.id]); + expect(release.code, `release failed: ${release.stderr}`).toBe(0); + + // Still Booted: the warm pool only demotes after idle.shutdownAfterMs, + // which defaults far longer than this test. + await waitFor( + async () => { + const rows = (await env.cli(["list", "--devices"])).json as { + driverDeviceId: string; + state: string; + }[]; + return rows.some((row) => row.driverDeviceId === udid && row.state === "ready"); + }, + { timeout: 60_000, label: "device returns to ready after release" }, + ); + const stillBooted = await setDevices(deviceSet); + expect(stillBooted.find((device) => device.udid === udid)?.state).toBe("Booted"); + + const nuke = await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 60_000 }); + expect(nuke.code).toBe(0); + + await waitFor(async () => (await setDevices(deviceSet)).length === 0, { + timeout: 60_000, + label: "no simulator remains in Simlock's device set after nuke --delete-devices", + }); }, ); }, From 7c7dd8d527ba12fcde933d7337a7110ee715581b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 08:14:23 +0200 Subject: [PATCH 4/9] test: prove the slim skip names the last chunk's cause, timeout included Scenario 9's MCP slim lease now fails with the daemon's skip lines like the others. A driver test runs four failing chunks, the last one timing out, so the detail is shown to name the last cause and the timeout. The untested "(no stderr)" fallback goes. --- e2e/slow-ios-slim.test.ts | 23 ++++++++-------- src/drivers/ios/index.test.ts | 50 +++++++++++++++++++++++++++++++++++ src/drivers/ios/index.ts | 3 +-- 3 files changed, 62 insertions(+), 14 deletions(-) diff --git a/e2e/slow-ios-slim.test.ts b/e2e/slow-ios-slim.test.ts index 0a1ec80ec..d109e374e 100644 --- a/e2e/slow-ios-slim.test.ts +++ b/e2e/slow-ios-slim.test.ts @@ -148,10 +148,8 @@ async function slimSkips(env: TestEnv): Promise { return skips.length === 0 ? "the daemon logged no skipped slim" : skips.join("\n"); } -async function expectSlim(env: TestEnv, grant: LeaseGrant, message: string): Promise { - expect(grant.mode, `${message}\n${grant.mode === "slim" ? "" : await slimSkips(env)}`).toBe( - "slim", - ); +async function expectSlim(env: TestEnv, mode: LeaseGrant["mode"], message: string): Promise { + expect(mode, `${message}\n${mode === "slim" ? "" : await slimSkips(env)}`).toBe("slim"); } const ALL_LABELS = new Set(labelsFor(SLIM_CATEGORIES)); @@ -201,7 +199,7 @@ describe.skipIf(process.platform !== "darwin")( "--mode", "slim", ]); - await expectSlim(env, slimGrant, "--mode slim must be slim on a default-full worker"); + await expectSlim(env, slimGrant.mode, "--mode slim must be slim on a default-full worker"); expect(slimGrant.udid, "a slim request must not reuse the idle full device").not.toBe( grant.udid, ); @@ -224,7 +222,7 @@ describe.skipIf(process.platform !== "darwin")( const slimGrant = await leaseDetached(env, model, os, "slim-cold"); const slimDurationMs = Date.now() - slimStart; - await expectSlim(env, slimGrant, "a slim lease's grant must carry mode: slim"); + await expectSlim(env, slimGrant.mode, "a slim lease's grant must carry mode: slim"); const slimDisabled = await printDisabled(slimGrant); const missing = [...ALL_LABELS].filter((label) => !slimDisabled.has(label)); @@ -320,7 +318,7 @@ describe.skipIf(process.platform !== "darwin")( // that it's skipped. We assert that documented behaviour here. const relet = await leaseDetached(env, model, os, "slim-cold"); expect(relet.udid, "expected the warm-pooled device to be reused").toBe(slimGrant.udid); - await expectSlim(env, relet, "re-leased device must still report mode: slim"); + await expectSlim(env, relet.mode, "re-leased device must still report mode: slim"); const eventsAfterRelease = await env.expectEvents(["device.slimmed", "device.slimmed"], { since: "1h", @@ -359,7 +357,7 @@ describe.skipIf(process.platform !== "darwin")( // --- scenario 5 --- const grant = await leaseDetached(env, model, os, "slim-subset"); - await expectSlim(env, grant, "a default-slim lease must be slim"); + await expectSlim(env, grant.mode, "a default-slim lease must be slim"); const disabled = await printDisabled(grant); const missingSiri = [...siriLabels].filter((label) => !disabled.has(label)); @@ -386,7 +384,7 @@ describe.skipIf(process.platform !== "darwin")( { ios: { defaultMode: "slim", slim: { categories: ["siri", "no-such-category"] } } }, async () => { const grant2 = await leaseDetached(env, model, os, "slim-unknown-category"); - await expectSlim(env, grant2, "lease must still succeed and be slim"); + await expectSlim(env, grant2.mode, "lease must still succeed and be slim"); const disabled2 = await printDisabled(grant2); const missingSiri2 = [...siriLabels].filter((label) => !disabled2.has(label)); expect(missingSiri2, "expected every siri label disabled").toEqual([]); @@ -407,7 +405,7 @@ describe.skipIf(process.platform !== "darwin")( }); const { model, os } = await catalogModelAndOs(env); const grant = await leaseDetached(env, model, os, "slim-recovery", []); - await expectSlim(env, grant, "a default-slim lease must be slim"); + await expectSlim(env, grant.mode, "a default-slim lease must be slim"); const disabledBefore = await printDisabled(grant); expect([...ALL_LABELS].filter((label) => !disabledBefore.has(label)).length).toBe(0); @@ -487,10 +485,11 @@ describe.skipIf(process.platform !== "darwin")( device: { mode: "slim" | "full" }; lease: { id: string }; }; - expect( + await expectSlim( + env, slimLeased.device.mode, "MCP lease naming no mode on a default-slim worker must report mode: slim", - ).toBe("slim"); + ); await mcp.client.callTool({ name: "release_simulator", diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 625b9aae1..12897d2fb 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -2625,6 +2625,56 @@ describe("IosSimctlDriver", () => { ); }); + it("names the last failed chunk's cause when every chunk fails, a timeout included", async () => { + const allLabels = labelsFor(resolveSlimCategories(undefined).categories); + const chunks = [0, 1, 2, 3].map((index) => allLabels.slice(index * 50, (index + 1) * 50)); + expect(allLabels.length).toBeGreaterThan(150); + const spawnArgs = (labelChunk: readonly string[]) => + simctlArgs("spawn", slim18_5.udid, "/bin/sh", "-c", slimScript(labelChunk)); + + const filesystem = new MemoryFilesystem(); + await plantManagedDevice(filesystem); + const clock = new FakeClock(); + const runner = new ScriptedProcessRunner([ + { match: { command: "xcrun", args: simctlArgs("boot", slim18_5.udid) } }, + { match: { command: "xcrun", args: simctlArgs("bootstatus", slim18_5.udid, "-b") } }, + // Three different exits before the timeout, so a detail that kept any but the last + // failure would name one of them instead. + ...["first", "second", "third"].map((stderr, index) => ({ + match: { args: spawnArgs(chunks[index] ?? []), command: "xcrun" }, + result: { code: 1, stderr, stdout: "" }, + })), + { hangs: true, match: { args: spawnArgs(chunks[3] ?? []), command: "xcrun" } }, + ]); + const onSlimSkipped = vi.fn(); + const driver = await IosSimctlDriver.create({ + driverConfig: { deviceRoot }, + instanceId, + simlockHome: "/home/.simlock", + clock, + filesystem, + idGenerator: { generate: () => "device-1" }, + onSlimSkipped, + processRunner: runner, + slim: { bootTimeoutMs: 300_000 }, + }); + + const ready = driver.makeReady( + { address: slim18_5.udid, deviceId: slim18_5.udid, driverData: slim18_5 }, + prepareSlim, + ); + await waitForCalls(runner, 6); + clock.advance(60_000); // SLIM_CHUNK_TIMEOUT_MS + + expect((await ready).mode).toBe("full"); + expect(onSlimSkipped).toHaveBeenCalledWith( + expect.objectContaining({ + detail: "all 4 chunk(s) failed to run; last: timed out after 60000ms", + reason: "apply-failed", + }), + ); + }); + it.each([false, true])( "boots a full-spec device on 18.5 once, with the normal deadline (slim by default: %s)", async (slimByDefault) => { diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 13f3cea03..32e7cb5f9 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -2210,8 +2210,7 @@ function describeFailedChunk(outcome: ProcessOutcome): string { if (outcome.kind === "timed-out") { return `timed out after ${String(SLIM_CHUNK_TIMEOUT_MS)}ms`; } - const stderr = outcome.result.stderr.trim(); - return `exit ${String(outcome.result.code)}: ${stderr === "" ? "(no stderr)" : stderr}`; + return `exit ${String(outcome.result.code)}: ${outcome.result.stderr.trim()}`; } function chunk(items: readonly T[], size: number): readonly (readonly T[])[] { From 7283294ece9f98e97cb63ea61cef6c5d310719c4 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 08:19:53 +0200 Subject: [PATCH 5/9] test(e2e): emptying a device set in teardown is bounded Each simctl call while emptying a set now has a 15s deadline and devices are handled in parallel, so a hung simctl cannot eat the teardown hook's budget and leave the home behind. The skip-detail test feeds stderr with its trailing newline, as real simctl prints it. --- e2e/helpers/env.ts | 5 ++++- e2e/helpers/ios-device-set.ts | 34 +++++++++++++++++++++++++++------- src/drivers/ios/index.test.ts | 3 ++- 3 files changed, 33 insertions(+), 9 deletions(-) diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index 45723627f..cc9751cd0 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -316,7 +316,10 @@ interface TeardownState { readonly env: NodeJS.ProcessEnv; readonly home: string; readonly mcpClients: ReadonlySet; - /** The real-SDK lane: the home holds a real iOS device set that must be emptied first. */ + /** + * The real-SDK lane: the home may hold a real iOS device set, which must be emptied before + * the home is removed. An Android-only or non-macOS run has none; emptying it is a no-op. + */ readonly realDrivers: boolean; readonly socketPath: string; } diff --git a/e2e/helpers/ios-device-set.ts b/e2e/helpers/ios-device-set.ts index f2af6c13a..c33061959 100644 --- a/e2e/helpers/ios-device-set.ts +++ b/e2e/helpers/ios-device-set.ts @@ -25,13 +25,26 @@ export function iosDeviceSet(home: string): string { export async function simctlInSet( deviceSet: string, args: readonly string[], + options: { readonly timeoutMs?: number } = {}, ): Promise<{ readonly stdout: string }> { - return execFileAsync("xcrun", ["simctl", "--set", deviceSet, ...args]); + return execFileAsync("xcrun", ["simctl", "--set", deviceSet, ...args], { + timeout: options.timeoutMs ?? 0, + }); } +/** + * Per call while emptying a set. Teardown runs inside a 60s hook that already spends up to + * ~25s stopping the daemon, so a hung simctl must give up rather than eat the rest of it -- + * the home's removal comes after. + */ +const EMPTY_SET_CALL_TIMEOUT_MS = 15_000; + /** Devices in one device set. */ -export async function setDevices(deviceSet: string): Promise { - const { stdout } = await simctlInSet(deviceSet, ["list", "devices", "-j"]); +export async function setDevices( + deviceSet: string, + options: { readonly timeoutMs?: number } = {}, +): Promise { + const { stdout } = await simctlInSet(deviceSet, ["list", "devices", "-j"], options); const parsed = JSON.parse(stdout) as { devices: Record }; return Object.values(parsed.devices).flat(); } @@ -46,12 +59,19 @@ export async function setDevices(deviceSet: string): Promise { * without shutting down would leave a running `launchd_sim` attached to a set directory * that `withDaemon`'s teardown is about to remove recursively, and still writing into it * while it does (`ENOTEMPTY`). + * + * Devices are handled in parallel and every call is bounded, so emptying a set of any size + * takes at most two `EMPTY_SET_CALL_TIMEOUT_MS`. */ export async function emptyDeviceSet(deviceSet: string): Promise { - for (const device of await setDevices(deviceSet).catch(() => [])) { - await simctlInSet(deviceSet, ["shutdown", device.udid]).catch(() => undefined); - await simctlInSet(deviceSet, ["delete", device.udid]).catch(() => undefined); - } + const bounded = { timeoutMs: EMPTY_SET_CALL_TIMEOUT_MS }; + const devices = await setDevices(deviceSet, bounded).catch(() => []); + await Promise.all( + devices.map(async (device) => { + await simctlInSet(deviceSet, ["shutdown", device.udid], bounded).catch(() => undefined); + await simctlInSet(deviceSet, ["delete", device.udid], bounded).catch(() => undefined); + }), + ); } /** Older than any run of a real-simctl lane can be. */ diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index 12897d2fb..f5e7d9471 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -2582,7 +2582,8 @@ describe("IosSimctlDriver", () => { args: simctlArgs("spawn", slim18_5.udid, "/bin/sh", "-c", slimScript(widgetsLabels)), command: "xcrun", }, - result: { code: 1, stderr: "boom", stdout: "" }, + // Real simctl stderr ends in a newline; the detail must not carry it. + result: { code: 1, stderr: "boom\n", stdout: "" }, }, ]); const onSlimmed = vi.fn(); From b28d9b434e816cfa4b3c265d5ac631708e30a854 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 10:10:29 +0200 Subject: [PATCH 6/9] test(e2e): scenario 2 waits as long as a slim reclaim takes Back to ready after release is an erase plus a fresh slim prepare (two boots and the disable pass), which the driver budgets at ~34s + ~150s. The 120s wait failed a device that was on schedule, even on an idle host. --- e2e/slow-ios-slim.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/e2e/slow-ios-slim.test.ts b/e2e/slow-ios-slim.test.ts index d109e374e..377a8dc6d 100644 --- a/e2e/slow-ios-slim.test.ts +++ b/e2e/slow-ios-slim.test.ts @@ -212,7 +212,7 @@ describe.skipIf(process.platform !== "darwin")( it( "scenario 2/3/4/7: on a default-slim worker, a cold slim lease, --mode full while a slim device sits idle, idempotence across a reclaim, and doctor advisory absence", - { timeout: 900_000 }, + { timeout: 1_200_000 }, async () => { const env = await withRealDaemon({ ios: { defaultMode: "slim" } }); const { model, os } = await catalogModelAndOs(env); @@ -242,7 +242,10 @@ describe.skipIf(process.platform !== "darwin")( // --- scenario 4: with the slim device released and idle in the pool, --mode full gets // a different, full device. --- expect((await env.cli(["release", slimGrant.lease])).code).toBe(0); - await waitForDeviceState(env, slimGrant.udid, "ready", { timeout: 120_000 }); + // Back to `ready` means reclaim (an erase) and then a fresh slim prepare: a boot, the + // disable pass, and a second boot. The driver itself budgets ~34s plus ~150s for that, + // so a wait sized for one ordinary boot fails a device that is on schedule. + await waitForDeviceState(env, slimGrant.udid, "ready", { timeout: 300_000 }); const fullStart = Date.now(); const fullGrant = await leaseDetached(env, model, os, "slim-full", ["--mode", "full"]); From b9e17ef81245a9b0502354f4ef31503bc167f8cd Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 10:22:41 +0200 Subject: [PATCH 7/9] test(e2e): the slow lanes keep only what needs real hardware The slim lane drops the scenarios that re-prove unit-tested logic: mode choice on a default-full worker, category subsets, unknown categories, the doctor advisory, MCP mode plumbing, and the re-slim after reclaim. What stays is what only a real simulator shows: launchd takes every label and keeps it across the reboot, a slim device runs at least 30% fewer jobs than a full one leased beside it (no reclaim wait), and crash recovery does not re-slim. slow-no-implicit-download goes: it never asks for a missing runtime, so it could not fail for the right reason. error-exit-codes proves RUNTIME_MISSING never reaches provision. --- docs/internal/KNOWN-PITFALLS.md | 7 +- e2e/README.md | 14 +- e2e/slow-ios-slim.test.ts | 306 +++----------------------- e2e/slow-no-implicit-download.test.ts | 101 --------- 4 files changed, 46 insertions(+), 382 deletions(-) delete mode 100644 e2e/slow-no-implicit-download.test.ts diff --git a/docs/internal/KNOWN-PITFALLS.md b/docs/internal/KNOWN-PITFALLS.md index a3672471b..295f21ca5 100644 --- a/docs/internal/KNOWN-PITFALLS.md +++ b/docs/internal/KNOWN-PITFALLS.md @@ -766,9 +766,10 @@ is 60s, so an MCP client that does not reset its timeout on progress notifications gets `MCP error -32001: Request timed out` on the slim lease even though the daemon completes it. Simlock relays boot progress as MCP progress notifications precisely so clients can pass -`resetTimeoutOnProgress: true` (or a longer timeout) on `lease_simulator`; -`e2e/slow-ios-slim.test.ts` shows the call shape. The warm pool hides this -for every lease after the first. +`resetTimeoutOnProgress: true` (or a longer timeout) on `lease_simulator`, +as in `client.callTool(request, undefined, { resetTimeoutOnProgress: true, +timeout: 600_000 })`. The warm pool hides this for every lease after the +first. **`launchctl disable` accepts labels that do not exist.** Verified on iOS 26.4 and 27.0 simulators: disabling `system/com.apple.does.not.exist` exits diff --git a/e2e/README.md b/e2e/README.md index 0a183484a..e21ada656 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -53,13 +53,13 @@ running test body silently never fires — see the comment in `helpers/env.ts`. ## Known gaps -- **The slow lane does not pass reliably as a whole run.** Each of the three - flows passes on its own, but a combined `pnpm run test:e2e:slow` has failed on - every attempt so far: a daemon occasionally outlives `daemon stop` and trips - teardown's stray-process assertion, and the no-implicit-download flow has hit - its 300s timeout. Not yet root-caused, and not yet distinguished from the - reclaim stall recorded in [../docs/internal/KNOWN-PITFALLS.md](../docs/internal/KNOWN-PITFALLS.md). - Treat the slow lane as a manual, one-flow-at-a-time tool until that is fixed. +- **The slow lane does not pass reliably as a whole run.** A daemon + occasionally outlives `daemon stop` and trips teardown's stray-process + assertion; not yet root-caused, and not yet distinguished from the reclaim + stall recorded in [../docs/internal/KNOWN-PITFALLS.md](../docs/internal/KNOWN-PITFALLS.md). + The slim lane also fails while a 50-label disable batch can outrun its fixed + 60s limit on a cold boot ([#206](https://github.com/callstackincubator/simlock/issues/206)). Treat the slow lane as a manual, + one-flow-at-a-time tool until both are fixed. - `daemon status` ignores `--json` and always prints raw JSON; documented by an `it.fails` in `daemon-lifecycle.test.ts`. - Android is exercised through the fake driver in the fast lane; only diff --git a/e2e/slow-ios-slim.test.ts b/e2e/slow-ios-slim.test.ts index 377a8dc6d..1065dffe4 100644 --- a/e2e/slow-ios-slim.test.ts +++ b/e2e/slow-ios-slim.test.ts @@ -2,7 +2,7 @@ import { readFile } from "node:fs/promises"; import { describe, expect, it } from "vitest"; import { SLIM_CATEGORIES, labelsFor } from "../src/drivers/ios/slim-labels.js"; -import { waitForDeviceState, withDaemon } from "./helpers/index.js"; +import { withDaemon } from "./helpers/index.js"; import type { TestEnv } from "./helpers/env.js"; import { iosDeviceSet, @@ -21,15 +21,6 @@ interface LeaseGrant { readonly deviceSet: string; } -interface DoctorReport { - readonly findings: readonly { - readonly kind: string; - readonly code?: string; - readonly platform?: string; - readonly deviceId?: string; - }[]; -} - interface CatalogPlatform { readonly platform: string; readonly models: readonly string[]; @@ -162,244 +153,80 @@ describe.skipIf(process.platform !== "darwin")( { tags: ["slow", "ios"] }, () => { it( - "scenario 1: on a default-full worker a request with no mode is full, and --mode slim is slim", - { timeout: 600_000 }, + "on a default-slim worker, a cold lease naming no mode boots slim with every label disabled, and runs at least 30% fewer launchd jobs than a --mode full device beside it", + { timeout: 900_000 }, async () => { await sweepStaleDeviceSets(); - const env = await withRealDaemon(); - const { model, os } = await catalogModelAndOs(env); - const grant = await leaseDetached(env, model, os, "default-full"); - - expect(grant.mode, "a request with no mode must be full on a default-full worker").toBe( - "full", - ); - - const disabled = await printDisabled(grant); - const overlap = [...ALL_LABELS].filter((label) => disabled.has(label)); - expect( - overlap, - `expected none of the slim label set disabled on a full device, found: ${overlap.join(", ")}`, - ).toEqual([]); - - const recorded = await env.events("1h"); - const slimmedEvents = recorded.filter((event) => event.event === "device.slimmed"); - expect(slimmedEvents, "no device.slimmed event expected for a full device").toEqual([]); - - const doctorReport = (await env.cli(["doctor"])).json as DoctorReport; - const advisories = doctorReport.findings.filter( - (finding) => finding.kind === "driver-advisory", - ); - expect(advisories, "no driver-advisory finding expected on a default-full worker").toEqual( - [], - ); - - expect((await env.cli(["release", grant.lease])).code).toBe(0); - - const slimGrant = await leaseDetached(env, model, os, "default-full-asks-slim", [ - "--mode", - "slim", - ]); - await expectSlim(env, slimGrant.mode, "--mode slim must be slim on a default-full worker"); - expect(slimGrant.udid, "a slim request must not reuse the idle full device").not.toBe( - grant.udid, - ); - const slimDisabled = await printDisabled(slimGrant); - expect([...ALL_LABELS].filter((label) => !slimDisabled.has(label))).toEqual([]); - - await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); - }, - ); - - it( - "scenario 2/3/4/7: on a default-slim worker, a cold slim lease, --mode full while a slim device sits idle, idempotence across a reclaim, and doctor advisory absence", - { timeout: 1_200_000 }, - async () => { const env = await withRealDaemon({ ios: { defaultMode: "slim" } }); const { model, os } = await catalogModelAndOs(env); - // --- scenario 2: a cold lease naming no mode produces a slim device. --- const slimStart = Date.now(); const slimGrant = await leaseDetached(env, model, os, "slim-cold"); const slimDurationMs = Date.now() - slimStart; + await expectSlim(env, slimGrant.mode, "a lease naming no mode must be slim"); - await expectSlim(env, slimGrant.mode, "a slim lease's grant must carry mode: slim"); - + // What only a real simulator can show: launchd took every label, and the overrides + // survived the reboot that makes them take effect. const slimDisabled = await printDisabled(slimGrant); const missing = [...ALL_LABELS].filter((label) => !slimDisabled.has(label)); expect( missing.length, `expected every slim label disabled on a slim device, missing ${missing.length} of ${ALL_LABELS.size}: ${missing.slice(0, 10).join(", ")}${missing.length > 10 ? "..." : ""}`, ).toBe(0); + const booted = await setDevices(slimGrant.deviceSet); + expect(booted.find((device) => device.udid === slimGrant.udid)?.state).toBe("Booted"); - const boot = await setDevices(slimGrant.deviceSet); - expect(boot.find((device) => device.udid === slimGrant.udid)?.state).toBe("Booted"); - const slimProcessCount = await processCount(slimGrant); - - const eventsAfterSlim = await env.expectEvents(["device.slimmed"], { since: "1h" }); - const slimmedEvents = eventsAfterSlim.filter((event) => event.event === "device.slimmed"); + const recorded = await env.expectEvents(["device.slimmed"], { since: "1h" }); + const slimmedEvents = recorded.filter((event) => event.event === "device.slimmed"); expect(slimmedEvents.length).toBe(1); + const slimmedFact = slimmedEvents[0]?.payload as { + categories: readonly string[]; + labelCount: number; + unknownLabels: readonly string[]; + }; + expect(new Set(slimmedFact.categories)).toEqual(ALL_CATEGORY_NAMES); + expect(slimmedFact.labelCount).toBe(ALL_LABELS.size); + // Reported, not asserted empty: Apple can rename or drop a daemon between runtimes + // (docs/internal/KNOWN-PITFALLS.md), and that is evidence for the report, not a failure. + console.log( + `[slim e2e] unknownLabels (${slimmedFact.unknownLabels.length}): ` + + JSON.stringify(slimmedFact.unknownLabels), + ); - // --- scenario 4: with the slim device released and idle in the pool, --mode full gets - // a different, full device. --- - expect((await env.cli(["release", slimGrant.lease])).code).toBe(0); - // Back to `ready` means reclaim (an erase) and then a fresh slim prepare: a boot, the - // disable pass, and a second boot. The driver itself budgets ~34s plus ~150s for that, - // so a wait sized for one ordinary boot fails a device that is on schedule. - await waitForDeviceState(env, slimGrant.udid, "ready", { timeout: 300_000 }); - + // The slim device stays leased, so the full one is a second device by construction. const fullStart = Date.now(); - const fullGrant = await leaseDetached(env, model, os, "slim-full", ["--mode", "full"]); + const fullGrant = await leaseDetached(env, model, os, "full-beside", ["--mode", "full"]); const fullDurationMs = Date.now() - fullStart; expect(fullGrant.mode, "a --mode full lease's grant must carry mode: full").toBe("full"); - expect(fullGrant.udid, "--mode full must not receive the idle slim device").not.toBe( - slimGrant.udid, - ); const fullDisabled = await printDisabled(fullGrant); const fullOverlap = [...ALL_LABELS].filter((label) => fullDisabled.has(label)); expect( fullOverlap, - `--mode full device must have none of the slim labels disabled, found: ${fullOverlap.join(", ")}`, - ).toEqual([]); - const fullProcessCount = await processCount(fullGrant); - - const doctorAfterFull = (await env.cli(["doctor"])).json as DoctorReport; - expect( - doctorAfterFull.findings.filter((finding) => finding.deviceId === fullGrant.udid), - "doctor must report no drift for the full device", + `a full device must have none of the slim labels disabled, found: ${fullOverlap.join(", ")}`, ).toEqual([]); + // The reason slim mode exists: fewer jobs running inside the simulator. + const slimProcessCount = await processCount(slimGrant); + const fullProcessCount = await processCount(fullGrant); const reduction = 1 - slimProcessCount / fullProcessCount; - expect( - reduction, - `expected the slim device's launchctl job count (${String(slimProcessCount)}) to be ` + - `at least 30% lower than the full device's (${String(fullProcessCount)}), got a ` + - `${(reduction * 100).toFixed(1)}% reduction`, - ).toBeGreaterThanOrEqual(0.3); - - const slimmedFact = slimmedEvents.at(-1)?.payload as { - deviceId: string; - platform?: string; - categories: readonly string[]; - labelCount: number; - unknownLabels: readonly string[]; - }; - expect(slimmedFact.categories.length, "expected every category resolved").toBe( - SLIM_CATEGORIES.length, - ); - expect(new Set(slimmedFact.categories)).toEqual(ALL_CATEGORY_NAMES); - expect(slimmedFact.labelCount).toBe(ALL_LABELS.size); - // Reported, not asserted empty -- known-pitfalls.md documents that Apple drift can - // legitimately produce rejected labels here; this is evidence for the report, not a - // pass/fail condition. - // eslint-disable-next-line no-console - console.log( - `[slim e2e] scenario 2 unknownLabels (${slimmedFact.unknownLabels.length}): ` + - JSON.stringify(slimmedFact.unknownLabels), - ); - console.log( `[slim e2e] lease duration: full=${String(fullDurationMs)}ms slim(cold)=${String(slimDurationMs)}ms; ` + `process count: full=${String(fullProcessCount)} slim=${String(slimProcessCount)} ` + `(${(reduction * 100).toFixed(1)}% reduction)`, ); - - // --- scenario 7: doctor advisory is absent (both installed runtimes are >= 18.5). --- - const doctorAfterSlim = (await env.cli(["doctor"])).json as DoctorReport; - const advisories = doctorAfterSlim.findings.filter( - (finding) => finding.kind === "driver-advisory", - ); - expect( - advisories, - "expected no slim-runtime-unsupported advisory: both installed runtimes on this " + - "machine (26.4.1, 27.0) are >= 18.5", - ).toEqual([]); - - // --- scenario 3: re-lease the released slim spec. Per docs/internal/KNOWN-PITFALLS.md - // ("Every reclaim pays two boots, indefinitely"), IosSimctlDriver.reclaim always runs - // `simctl erase`, wiping the launchctl overrides -- so the documented behaviour is - // that the warm-pooled device comes back stock and pays a SECOND device.slimmed, not - // that it's skipped. We assert that documented behaviour here. - const relet = await leaseDetached(env, model, os, "slim-cold"); - expect(relet.udid, "expected the warm-pooled device to be reused").toBe(slimGrant.udid); - await expectSlim(env, relet.mode, "re-leased device must still report mode: slim"); - - const eventsAfterRelease = await env.expectEvents(["device.slimmed", "device.slimmed"], { - since: "1h", - }); - const slimmedAfterRelease = eventsAfterRelease.filter( - (event) => event.event === "device.slimmed", - ); expect( - slimmedAfterRelease.length, - "expected a SECOND device.slimmed for this udid after release+re-lease, per the " + - "documented erase-on-reclaim cost (docs/internal/KNOWN-PITFALLS.md)", - ).toBe(2); - - await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); - }, - ); - - it( - "scenario 5/6: a categories subset disables only its own labels, and an unknown category is not fatal", - { timeout: 900_000 }, - async () => { - const siriLabels = new Set( - labelsFor(SLIM_CATEGORIES.filter((category) => category.name === "siri")), - ); - const telemetryLabels = new Set( - labelsFor(SLIM_CATEGORIES.filter((category) => category.name === "telemetry")), - ); - const photosLabels = new Set( - labelsFor(SLIM_CATEGORIES.filter((category) => category.name === "photos")), - ); - - const env = await withRealDaemon({ - ios: { defaultMode: "slim", slim: { categories: ["siri", "telemetry"] } }, - }); - const { model, os } = await catalogModelAndOs(env); - - // --- scenario 5 --- - const grant = await leaseDetached(env, model, os, "slim-subset"); - await expectSlim(env, grant.mode, "a default-slim lease must be slim"); - const disabled = await printDisabled(grant); - - const missingSiri = [...siriLabels].filter((label) => !disabled.has(label)); - const missingTelemetry = [...telemetryLabels].filter((label) => !disabled.has(label)); - expect(missingSiri, "expected every siri label disabled").toEqual([]); - expect(missingTelemetry, "expected every telemetry label disabled").toEqual([]); - - const leakedPhotos = [...photosLabels].filter((label) => disabled.has(label)); - expect( - leakedPhotos, - `expected no photos-category label disabled, found: ${leakedPhotos.join(", ")}`, - ).toEqual([]); - - const recorded = await env.expectEvents(["device.slimmed"], { since: "1h" }); - const fact = recorded.find((event) => event.event === "device.slimmed")?.payload as { - categories: readonly string[]; - }; - expect(fact.categories).toEqual(["siri", "telemetry"]); + reduction, + `expected the slim device's launchctl job count (${String(slimProcessCount)}) to be ` + + `at least 30% lower than the full device's (${String(fullProcessCount)}), got a ` + + `${(reduction * 100).toFixed(1)}% reduction`, + ).toBeGreaterThanOrEqual(0.3); await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); - - // --- scenario 6: an unknown category alongside a known one is not fatal. --- - await env.withConfig( - { ios: { defaultMode: "slim", slim: { categories: ["siri", "no-such-category"] } } }, - async () => { - const grant2 = await leaseDetached(env, model, os, "slim-unknown-category"); - await expectSlim(env, grant2.mode, "lease must still succeed and be slim"); - const disabled2 = await printDisabled(grant2); - const missingSiri2 = [...siriLabels].filter((label) => !disabled2.has(label)); - expect(missingSiri2, "expected every siri label disabled").toEqual([]); - - await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); - }, - ); }, ); it( - "scenario 8: a health-monitor recovery boot does not re-slim", + "a health-monitor recovery boot of a slim device does not re-slim it", { timeout: 600_000 }, async () => { const env = await withRealDaemon({ @@ -447,69 +274,6 @@ describe.skipIf(process.platform !== "darwin")( }, ); - it("scenario 9: MCP carries the device mode both ways", { timeout: 600_000 }, async () => { - const env = await withRealDaemon({ ios: { defaultMode: "slim" } }); - const { model, os } = await catalogModelAndOs(env); - const mcp = await env.mcpClient({ env: { SIMLOCK_AGENT_ID: "slim-mcp" } }); - try { - // The SDK's default request timeout is 60s; a cold slim lease takes ~160s on this - // machine (two real boots). Simlock relays boot progress as MCP progress - // notifications, so a client that resets its timeout on progress survives it -- - // which is what a real agent's client must do too (see docs/internal/KNOWN-PITFALLS.md). - const leaseCallOptions = { resetTimeoutOnProgress: true, timeout: 600_000 }; - const fullResult = await mcp.client.callTool( - { - name: "lease_simulator", - arguments: { mode: "full", model, osVersion: os, platform: "ios" }, - }, - undefined, - leaseCallOptions, - ); - const fullLeased = fullResult.structuredContent as { - device: { mode: "slim" | "full" }; - lease: { id: string }; - }; - expect(fullLeased.device.mode, "MCP mode: full lease must report mode: full").toBe("full"); - - await mcp.client.callTool({ - name: "release_simulator", - arguments: { leaseId: fullLeased.lease.id }, - }); - - const slimResult = await mcp.client.callTool( - { - name: "lease_simulator", - arguments: { model, osVersion: os, platform: "ios" }, - }, - undefined, - leaseCallOptions, - ); - const slimLeased = slimResult.structuredContent as { - device: { mode: "slim" | "full" }; - lease: { id: string }; - }; - await expectSlim( - env, - slimLeased.device.mode, - "MCP lease naming no mode on a default-slim worker must report mode: slim", - ); - - await mcp.client.callTool({ - name: "release_simulator", - arguments: { leaseId: slimLeased.lease.id }, - }); - } finally { - await mcp.close(); - } - - await env.cli(["nuke", "--delete-devices", "--yes"], { timeout: 180_000 }); - - // HTTP is skipped here: it needs a real reserved port plus its own auth-token setup - // (see http-api.test.ts) on top of another real cold iOS lease, which -- given MCP - // already exercises the same `grant.device.mode` plumbing through a second transport -- was - // judged not worth a third real boot cycle in this already-expensive slow lane. - }); - it( "no simulator from this file's device sets is still running after its flows", { timeout: 60_000 }, diff --git a/e2e/slow-no-implicit-download.test.ts b/e2e/slow-no-implicit-download.test.ts deleted file mode 100644 index 48a8d1cb5..000000000 --- a/e2e/slow-no-implicit-download.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { execFile } from "node:child_process"; -import { existsSync, readdirSync } from "node:fs"; -import { homedir } from "node:os"; -import { join } from "node:path"; -import { promisify } from "node:util"; -import { describe, expect, it } from "vitest"; - -import { withDaemon } from "./helpers/index.js"; - -const execFileAsync = promisify(execFile); -const ANDROID_HOME = - process.env.ANDROID_HOME ?? - process.env.ANDROID_SDK_ROOT ?? - join(homedir(), "Library/Android/sdk"); -const hasAndroidSdk = existsSync(ANDROID_HOME); - -async function simctlRuntimeNames(): Promise { - const { stdout } = await execFileAsync("xcrun", ["simctl", "list", "runtimes", "-j"]); - const parsed = JSON.parse(stdout) as { runtimes: { name: string }[] }; - return parsed.runtimes.map((runtime) => runtime.name).sort(); -} - -function androidSystemImages(): string[] { - const root = join(ANDROID_HOME, "system-images"); - if (!existsSync(root)) return []; - return readdirSync(root).sort(); -} - -/** - * safety.md #4: missing runtimes / system images fail the request unless - * `--allow-download` was explicitly passed. This flow never passes it, and asserts - * the installed-runtime inventory is byte-for-byte the same before and after -- - * the strongest evidence available short of an actual network-activity monitor that - * nothing multi-GB was pulled down as a side effect of any command this suite ran. - */ -describe.skipIf(process.platform !== "darwin")( - "no-implicit-download invariant", - { tags: ["slow", "ios", "android"] }, - () => { - it( - "leaves installed iOS runtimes and Android system images unchanged across a normal lease/release/doctor/cleanup/nuke cycle", - { timeout: 300_000 }, - async () => { - const iosRuntimesBefore = await simctlRuntimeNames(); - const androidImagesBefore = androidSystemImages(); - - const env = await withDaemon({ driver: "real" }); - let nukeCode: number | null | undefined; - try { - const catalog = await env.cli(["catalog", "--json"]); - expect(catalog.code).toBe(0); - const platforms = ( - catalog.json as { platforms: { platform: string; models: string[] }[] } - ).platforms; - const ios = platforms.find((platform) => platform.platform === "ios"); - - if (ios !== undefined && ios.models.length > 0) { - const lease = await env.cli( - [ - "lease", - "--platform", - "ios", - "--device", - ios.models[0] as string, - "--agent-id", - "no-download", - "--detach", - ], - { timeout: 120_000 }, - ); - expect(lease.code, `lease failed: ${lease.stderr}`).toBe(0); - const grant = lease.json as { lease: { id: string } }; - const release = await env.cli(["release", grant.lease.id]); - expect(release.code, `release failed: ${release.stderr}`).toBe(0); - } - - await env.cli(["doctor"]); - await env.cli(["cleanup", "--dry-run"]); - } finally { - // nuke is the last step of the cycle and the only cleanup: this flow must never - // touch anything besides what simlock itself created. It runs here so a failed - // lease or release above still destroys the device it left behind. A nuke that - // fails too must not hide that earlier failure, so its result is checked below. - const nuke = await env - .cli(["nuke", "--delete-devices", "--yes"], { timeout: 60_000 }) - .catch(() => undefined); - nukeCode = nuke?.code; - } - expect(nukeCode, "nuke --delete-devices must succeed").toBe(0); - - const iosRuntimesAfter = await simctlRuntimeNames(); - expect(iosRuntimesAfter).toEqual(iosRuntimesBefore); - - if (hasAndroidSdk) { - const androidImagesAfter = androidSystemImages(); - expect(androidImagesAfter).toEqual(androidImagesBefore); - } - }, - ); - }, -); From 4fe784aea655bada57cd3210bfa254d8125c2d54 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 10:29:05 +0200 Subject: [PATCH 8/9] test(e2e): the fast lane drops tests that re-prove the same behaviour Cut where another e2e test or a unit test already proves the same claim: the SIGKILL and SIGTERM liveness cases (folded into renew-ttl, and covered by the CLI's signal tests), a fourth renew-keeps-width check, the reclaim ETA push, the MCP lifecycle twin (its CLI agreement check moves to mcp-session), config-default and log-format checks, a second events-after-restart read over HTTP, overLimit, and three daemon-log operation-line cases. Merged onto one daemon: the doctor orphan flows (--fix, declined purge, unprovable root, confirmed purge) and the two unrecoverable-device flows. Kept despite overlap: gateway-fleet's forbidden-token test is the only test of the token role check, and its worker-list test the only one of host facts over a real uplink. --- e2e/capacity-cleanup-nuke.test.ts | 54 --------- e2e/contention.test.ts | 47 -------- e2e/daemon-lifecycle.test.ts | 67 ----------- e2e/daemon-log.test.ts | 79 ------------- e2e/doctor-drift.test.ts | 134 +++++++--------------- e2e/error-exit-codes.test.ts | 46 +------- e2e/event-history.test.ts | 34 +----- e2e/held-lease-liveness.test.ts | 81 ------------- e2e/http-api.test.ts | 49 -------- e2e/lease-environment-passthrough.test.ts | 63 ---------- e2e/lease-lifecycle.test.ts | 66 ----------- e2e/leased-device-crash-recovery.test.ts | 68 +++-------- e2e/mcp-session.test.ts | 10 +- e2e/renew-ttl.test.ts | 56 +++------ src/cli/index.test.ts | 4 +- 15 files changed, 90 insertions(+), 768 deletions(-) diff --git a/e2e/capacity-cleanup-nuke.test.ts b/e2e/capacity-cleanup-nuke.test.ts index da31fa724..d55c1d75c 100644 --- a/e2e/capacity-cleanup-nuke.test.ts +++ b/e2e/capacity-cleanup-nuke.test.ts @@ -157,60 +157,6 @@ describe("capacity, warm pool, cleanup, and nuke", () => { await waitForLeaseCount(env, 0); }); - it("reports overLimit when a lowered running limit can't yet be met, without evicting existing leases", async () => { - const env = await withDaemon({ - configOverrides: { limits: { maxRunning: 3, ios: { maxDevices: 3, maxRunning: 3 } } }, - }); - await env.driverScript.set({ - ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, - }); - - // `--detach`, so no holder process has to stay alive across the `daemon stop` that - // `withConfig` triggers to pick up the new limit. The leases themselves survive that - // stop either way now (ADR 0004 §3), which is what lets this exercise "a lowered limit - // doesn't evict an existing lease" against a genuinely still-leased device. - const leaseOne = await env.cli([ - "lease", - "--platform", - "ios", - "--device", - "iPhone 16", - "--os", - "18.4", - "--agent-id", - "overlimit-one", - "--detach", - ]); - const grantOne = leaseOne.json as { lease: { id: string } }; - const leaseTwo = await env.cli([ - "lease", - "--platform", - "ios", - "--device", - "iPhone 16", - "--os", - "18.4", - "--agent-id", - "overlimit-two", - "--detach", - ]); - const grantTwo = leaseTwo.json as { lease: { id: string } }; - - await env.withConfig({ limits: { ios: { maxRunning: 1 } } }, async () => { - const afterLower = await status(env); - expect(afterLower.capacity.ios.overLimit).toBe(true); - - // Pre-existing leases must never be evicted just because the limit dropped - // below what is currently held. - const leases = (await env.cli(["list", "--leases"])).json as { id: string }[]; - expect(leases.map((lease) => lease.id)).toEqual( - expect.arrayContaining([grantOne.lease.id, grantTwo.lease.id]), - ); - }); - - await env.cli(["release", "--all", "--yes"]); - }); - it("demotes an idle device, previews cleanup without executing on --dry-run, and nuke touches only registry devices", async () => { const env = await withDaemon({ configOverrides: { diff --git a/e2e/contention.test.ts b/e2e/contention.test.ts index 16154c946..a96c8ff09 100644 --- a/e2e/contention.test.ts +++ b/e2e/contention.test.ts @@ -69,55 +69,8 @@ describe("contention & queueing", () => { waiterE.kill("SIGTERM"); await waiterE.waitForExit(15_000); }); - - it("tells a waiter queued behind a reclaim how long that reclaim runs", async () => { - const env = await withDaemon({ - configOverrides: { limits: { maxRunning: 1, ios: { maxDevices: 1, maxRunning: 1 } } }, - }); - await env.driverScript.set({ - ios: { - knownModels: ["iPhone 16"], - availableOsVersions: ["18.4"], - estimateMs: { reclaim: 34_000 }, - latencyMs: { reclaim: 4_000 }, - }, - }); - - const holder = await env.cli([...LEASE_ARGS, "--agent-id", "agent-holder", "--detach"]); - expect(holder.code).toBe(0); - const holderGrant = holder.json as { lease: { id: string } }; - - // Release hands the caller back before the purge (#58), so the device is `reclaiming` with - // its full latency still ahead when the next requester arrives -- the case the stage exists - // for, and the one nothing exercised before this covered the whole path out to the CLI. - const release = await env.cli(["release", holderGrant.lease.id]); - expect(release.code).toBe(0); - - const waiter = env.cliBackground([...LEASE_ARGS, "--agent-id", "agent-waiter"]); - await waitFor(() => waiter.progressEvents().some(isReclaimingWithEta(34_000)), { - label: "agent-waiter told the reclaim's ETA", - }); - expect(waiter.progressEvents().some((event) => isQueuedAt(event, 1))).toBe(true); - - const granted = JSON.parse(await waiter.firstStdoutLine(15_000)) as { - device: { spec: { model: string } }; - }; - expect(granted.device.spec.model).toBe("iPhone 16"); - - waiter.kill("SIGTERM"); - await waiter.waitForExit(15_000); - }); }); -function isReclaimingWithEta(etaMs: number): (event: unknown) => boolean { - return (event) => - typeof event === "object" && - event !== null && - (event as Record).push === "progress" && - (event as Record).stage === "reclaiming" && - (event as Record).etaMs === etaMs; -} - function isQueuedAt(event: unknown, position: number): boolean { return ( typeof event === "object" && diff --git a/e2e/daemon-lifecycle.test.ts b/e2e/daemon-lifecycle.test.ts index 462c36f69..95baae3b9 100644 --- a/e2e/daemon-lifecycle.test.ts +++ b/e2e/daemon-lifecycle.test.ts @@ -30,29 +30,6 @@ describe("daemon lifecycle & recovery", () => { expect(countOccurrences(after, "Daemon started")).toBe(startedCountBefore); }); - it("simlock config renders the android.emulator block with its defaults", async () => { - const env = await withDaemon({ mode: "running" }); - - const config = await env.cli(["config"]); - - expect(config.code).toBe(0); - expect((config.json as { android?: unknown }).android).toEqual({ - emulator: { audio: true, bootAnimation: true, gpu: "auto", headless: false }, - }); - }); - - it("simlock config renders ios.defaultMode, full by default, and no on/off switch under ios.slim", async () => { - const env = await withDaemon({ mode: "running" }); - - const config = await env.cli(["config"]); - - expect(config.code).toBe(0); - const ios = (config.json as { ios: { defaultMode: string; slim: Record } }) - .ios; - expect(ios.defaultMode).toBe("full"); - expect(ios.slim).not.toHaveProperty("enabled"); - }); - it("recovers from a kill -9 that leaves a stale socket behind", async () => { const env = await withDaemon({ mode: "running" }); expect(existsSync(env.socketPath)).toBe(true); @@ -86,50 +63,6 @@ describe("daemon lifecycle & recovery", () => { expect(statusHuman.stdout).toContain("Daemon running"); }); - it("writes the documented structured startup lines to daemon.log", async () => { - const env = await withDaemon({ mode: "running" }); - - const contents = await readFile(env.logPath, "utf8"); - const lines = contents - .trim() - .split("\n") - .filter((line) => line !== "") - .map((line) => JSON.parse(line) as Record); - - expect(lines.length, "daemon.log is empty after startup -- see report").toBeGreaterThan(0); - - const startRecord = lines.find((line) => line.message === "Daemon started"); - expect(startRecord, "no 'Daemon started' record in daemon.log").toBeDefined(); - expect(startRecord).toMatchObject({ - fields: expect.objectContaining({ - version: expect.any(String), - protocolVersion: expect.any(Number), - socketPath: env.socketPath, - }), - }); - - const modules = new Set(lines.map((line) => line.module)); - expect(modules.has("daemon.driver-discovery"), "no driver-discovery log lines").toBe(true); - expect(modules.has("daemon.connection-host"), "no connection-host log lines").toBe(true); - }); - - it("rotates daemon.log to daemon.log.1 once past config.log.rotateBytes", async () => { - const env = await withDaemon({ mode: "auto" }); - - await env.withConfig({ log: { rotateBytes: 200 } }, async () => { - await waitFor(() => existsSync(`${env.logPath}.1`), { - timeout: 15_000, - label: "daemon.log.1 created after low rotateBytes", - }); - // Rotation renames daemon.log away and then opens a fresh one; with a 200-byte cap - // nearly every startup line rotates, so a one-shot check can land in that gap. - await waitFor(() => existsSync(env.logPath), { - timeout: 15_000, - label: "a fresh daemon.log opened after rotation", - }); - }); - }); - it("stops while a detached lease is still outstanding", async () => { const env = await withDaemon(); await env.driverScript.set({ diff --git a/e2e/daemon-log.test.ts b/e2e/daemon-log.test.ts index b676cb4b8..a5a8dbe67 100644 --- a/e2e/daemon-log.test.ts +++ b/e2e/daemon-log.test.ts @@ -26,12 +26,6 @@ async function logLines(env: TestEnv): Promise { .map((line) => JSON.parse(line) as LogLine); } -async function operationLines(env: TestEnv, operation: string): Promise { - return (await logLines(env)).filter( - (line) => line.message === "operation" && line.fields?.operation === operation, - ); -} - const IOS = { ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] } }; async function leaseDetached(env: TestEnv): Promise { @@ -65,79 +59,6 @@ async function reservePort(): Promise { } describe("daemon.log", () => { - it("a lease and its release over the socket each leave one operation line naming the requester", async () => { - const env = await withDaemon({ agentId: "log-agent" }); - await env.driverScript.set(IOS); - - const leaseId = await leaseDetached(env); - const released = await env.cli(["release", leaseId]); - expect(released.code, released.stderr).toBe(0); - - await waitFor(async () => (await operationLines(env, "lease.release")).length > 0, { - label: "the lease.release line", - }); - const requests = await operationLines(env, "lease.request"); - const releases = await operationLines(env, "lease.release"); - expect(requests).toEqual([ - expect.objectContaining({ - level: "info", - fields: expect.objectContaining({ - principal: "log-agent", - requesterId: "log-agent", - durationMs: expect.any(Number), - }), - }), - ]); - expect(releases).toEqual([ - expect.objectContaining({ - level: "info", - fields: expect.objectContaining({ - principal: "log-agent", - leaseId, - durationMs: expect.any(Number), - }), - }), - ]); - }); - - it("a lease request for an unknown model leaves an operation line with its error code", async () => { - const env = await withDaemon(); - await env.driverScript.set({ - ios: { failures: { resolveSpec: { type: "UnknownModelError", model: "Bogus Phone" } } }, - }); - - const lease = await env.cli([ - "lease", - "--platform", - "ios", - "--device", - "Bogus Phone", - "--detach", - ]); - expect(lease.code).not.toBe(0); - - expect(await operationLines(env, "lease.request")).toEqual([ - expect.objectContaining({ - level: "info", - fields: expect.objectContaining({ code: "UNKNOWN_MODEL" }), - }), - ]); - }); - - it("at the default level simlock status leaves no operation line; at debug it leaves one", async () => { - const quiet = await withDaemon(); - expect((await quiet.cli(["status"])).code).toBe(0); - expect(await operationLines(quiet, "status.get")).toEqual([]); - - // `daemon start` asks for status itself, so the count is taken around this one call. - const verbose = await withDaemon({ configOverrides: { log: { level: "debug" } } }); - const before = (await operationLines(verbose, "status.get")).length; - expect((await verbose.cli(["status"])).code).toBe(0); - const after = await operationLines(verbose, "status.get"); - expect(after).toHaveLength(before + 1); - expect(after.at(-1)).toMatchObject({ level: "debug" }); - }); - it("a scripted boot failure leaves a line naming the device and the driver's error text", async () => { const env = await withDaemon(); await env.driverScript.set({ diff --git a/e2e/doctor-drift.test.ts b/e2e/doctor-drift.test.ts index f13d16595..87fbb4e1b 100644 --- a/e2e/doctor-drift.test.ts +++ b/e2e/doctor-drift.test.ts @@ -206,25 +206,37 @@ describe("doctor and drift", () => { await heldB.waitForExit(15_000).catch(() => undefined); }); - it("purges orphans only when asked and confirmed, and re-proves the root first", async () => { + it("purges orphans only when asked and confirmed and the root re-proves first, while --fix only reports them", async () => { const env = await withDaemon(); - await env.driverScript.set({ - ios: { - knownModels: ["iPhone 16"], - availableOsVersions: ["18.4"], - managedReality: { - devices: [{ deviceId: "fake-ios-orphan", runState: "running" }], - processes: [{ deviceId: "fake-ios-orphan" }], - }, + const orphanScript = { + knownModels: ["iPhone 16"], + availableOsVersions: ["18.4"], + managedReality: { + devices: [{ deviceId: "fake-ios-orphan", runState: "running" as const }], + processes: [{ deviceId: "fake-ios-orphan" }], }, - }); + }; + await env.driverScript.set({ ios: orphanScript }); + const operations = async () => (await env.driverLog.calls()).map((call) => call.operation); + const kinds = (result: { json?: unknown }) => + (result.json as { findings: Finding[] }).findings.map((f) => f.kind); const reported = await env.cli(["doctor"]); expect(reported.code).toBe(0); - expect((reported.json as { findings: Finding[] }).findings.map((f) => f.kind)).toEqual([ - "orphan-device", - "orphan-process", - ]); + expect(kinds(reported)).toEqual(["orphan-device", "orphan-process"]); + + // ADR 0001 decision 6: `purgeOrphans` is not part of `fix`, so an operator already running + // `doctor --fix` unattended does not gain a device-destroying behaviour by upgrading. Its + // own step, asserted on its own: folding the purge into `fix` would still pass the purge + // steps below. `--yes` too, since the confirmation is not what keeps `--fix` safe. + await env.driverLog.clear(); + const fixed = await env.cli(["doctor", "--fix", "--yes"]); + expect(fixed.code).toBe(0); + expect(kinds(fixed)).toEqual(["orphan-device", "orphan-process"]); + expect(await operations(), "--fix must never destroy a device").not.toContain("destroy"); + // The purge is the only path that re-proves the root, because it is the only one that + // was ever going to destroy anything. + expect(await operations()).not.toContain("revalidateRoot"); // No TTY behind the e2e CLI, so `confirm` answers no: the refusal is the documented // `USAGE`/exit 2 contract `release --all` already has (safety rule 5). @@ -232,90 +244,32 @@ describe("doctor and drift", () => { const declined = await env.cli(["doctor", "--purge-orphans"]); expect(declined.code).toBe(2); expect(declined.error?.code).toBe("USAGE"); - expect((await env.driverLog.calls()).map((call) => call.operation)).not.toContain("destroy"); - - await env.driverLog.clear(); - const purged = await env.cli(["doctor", "--purge-orphans", "--yes"]); - expect(purged.code).toBe(0); - - // Both findings go: destroying the device covers the process it was running. - expect((purged.json as { findings: Finding[] }).findings).toEqual([]); - const operations = (await env.driverLog.calls()) - .map((call) => call.operation) - .filter((operation) => operation !== "listManaged"); - expect(operations, "the root is re-proven before anything is destroyed").toEqual([ - "revalidateRoot", - "destroy", - ]); - await env.expectEvents(["device.orphan-purged"]); - }); - - /** - * The separation ADR 0001 decision 6 turns on, asserted from the outside. `purgeOrphans` - * is not part of `fix` precisely so that an operator already running `doctor --fix` - * unattended in CI does not acquire a device-destroying behaviour by upgrading -- which - * only holds if `--fix` genuinely leaves orphans alone. - * - * Worth its own flow rather than an assertion inside the purge test above: the failure it - * guards against is the plausible mis-fix of the bug that flag actually shipped with. The - * daemon dropped `purgeOrphans` on the floor and destroyed nothing; folding it into `fix` - * would have made the purge test pass while quietly making `--fix` destructive for - * everyone. - */ - it("reports orphans under --fix and destroys none of them", async () => { - const env = await withDaemon(); - await env.driverScript.set({ - ios: { - knownModels: ["iPhone 16"], - availableOsVersions: ["18.4"], - managedReality: { - devices: [{ deviceId: "fake-ios-orphan", runState: "running" }], - processes: [{ deviceId: "fake-ios-orphan" }], - }, - }, - }); - - await env.driverLog.clear(); - // `--yes` too: the confirmation is not what keeps `--fix` non-destructive, so answering - // it in advance must not change the outcome either. - const fixed = await env.cli(["doctor", "--fix", "--yes"]); + expect(await operations()).not.toContain("destroy"); - expect(fixed.code).toBe(0); - expect((fixed.json as { findings: Finding[] }).findings.map((f) => f.kind)).toEqual([ - "orphan-device", - "orphan-process", - ]); - expect( - (await env.driverLog.calls()).map((call) => call.operation), - "--fix must never destroy a device, however the run was confirmed", - ).not.toContain("destroy"); - // The purge is the only path that re-proves the root, because it is the only one that - // was ever going to destroy anything. - expect((await env.driverLog.calls()).map((call) => call.operation)).not.toContain( - "revalidateRoot", - ); - }); - - it("destroys nothing when the root can no longer be proven", async () => { - const env = await withDaemon(); + // A root that stopped proving ownership is exactly the case where `listManaged` may be + // describing the user's own devices: the orphans stay reported, and stay on disk. await env.driverScript.set({ ios: { - knownModels: ["iPhone 16"], - availableOsVersions: ["18.4"], + ...orphanScript, failures: { revalidateRoot: { type: "generic", message: "root is a symlink now" } }, - managedReality: { devices: [{ deviceId: "fake-ios-orphan", runState: "stopped" }] }, }, }); - await env.driverLog.clear(); const refused = await env.cli(["doctor", "--purge-orphans", "--yes"]); - - // The orphan stays reported, and stays on disk: a root that stopped proving ownership - // is exactly the case where `listManaged` may be describing the user's own devices. expect(refused.code).toBe(0); - expect((refused.json as { findings: Finding[] }).findings.map((f) => f.kind)).toEqual([ - "orphan-device", - ]); - expect((await env.driverLog.calls()).map((call) => call.operation)).not.toContain("destroy"); + expect(kinds(refused)).toEqual(["orphan-device", "orphan-process"]); + expect(await operations()).not.toContain("destroy"); + + await env.driverScript.set({ ios: orphanScript }); + await env.driverLog.clear(); + const purged = await env.cli(["doctor", "--purge-orphans", "--yes"]); + expect(purged.code).toBe(0); + // Both findings go: destroying the device covers the process it was running. + expect((purged.json as { findings: Finding[] }).findings).toEqual([]); + expect( + (await operations()).filter((operation) => operation !== "listManaged"), + "the root is re-proven before anything is destroyed", + ).toEqual(["revalidateRoot", "destroy"]); + await env.expectEvents(["device.orphan-purged"]); }); }); diff --git a/e2e/error-exit-codes.test.ts b/e2e/error-exit-codes.test.ts index 5b8631c72..b33aa3ee3 100644 --- a/e2e/error-exit-codes.test.ts +++ b/e2e/error-exit-codes.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; -import { waitForLeaseCount, withDaemon, type CliResult } from "./helpers/index.js"; +import { withDaemon, type CliResult } from "./helpers/index.js"; /** * Asserts the documented failure contract from docs/CLI.md#global-exit-codes: exit @@ -83,48 +83,4 @@ describe("error and exit-code table", () => { const result = await env.cli(["lease", "renew", "lse_does-not-exist"]); expectStructuredFailure(result, 1, "UNKNOWN_LEASE"); }); - - it("lease renew on a running holder's lease -> exit 0 with a later deadline", async () => { - const env = await withDaemon(); - await env.driverScript.set({ - ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, - }); - - const holder = env.cliBackground([ - "lease", - "--platform", - "ios", - "--device", - "iPhone 16", - "--os", - "18.4", - "--agent-id", - "flow4-holder", - ]); - const grant = JSON.parse(await holder.firstStdoutLine()) as { - lease: { id: string; ttlMs: number }; - }; - - try { - const rows = await waitForLeaseCount(env, 1); - const before = rows.find((row) => row.id === grant.lease.id); - if (before === undefined) { - throw new Error(`lease ${grant.lease.id} not found before renew`); - } - const beforeDeadline = before.ttlDeadline as number; - - const result = await env.cli(["lease", "renew", grant.lease.id]); - expect(result.code).toBe(0); - expect(result.stderr).toBe(""); - const renewed = result.json as { id: string; ttlMs: number; ttlDeadline: number }; - expect(renewed.id).toBe(grant.lease.id); - // ADR 0004: one kind of lease, and a body-less renew re-applies its own stored width - // rather than any mode-shaped default. - expect(renewed.ttlMs).toBe(grant.lease.ttlMs); - expect(renewed.ttlDeadline).toBeGreaterThan(beforeDeadline); - } finally { - holder.kill("SIGTERM"); - await holder.waitForExit(15_000); - } - }); }); diff --git a/e2e/event-history.test.ts b/e2e/event-history.test.ts index d58caec3f..ff7c3d9d7 100644 --- a/e2e/event-history.test.ts +++ b/e2e/event-history.test.ts @@ -1,5 +1,5 @@ import { existsSync } from "node:fs"; -import { mkdir, readFile, stat } from "node:fs/promises"; +import { readFile, stat } from "node:fs/promises"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; @@ -68,26 +68,6 @@ describe("event history", () => { expect(grantOf(parseLines(history.stdout), leaseId)).toEqual(before); }); - it("writes every event file line as JSON carrying seq, timestamp, event, payload and module", async () => { - const env = await withDaemon(); - await prepare(env); - const leaseId = await leaseDevice(env); - expect((await env.cli(["release", leaseId])).code).toBe(0); - - const lines = (await readFile(join(env.home, "events.jsonl"), "utf8")).trimEnd().split("\n"); - - expect(lines.length).toBeGreaterThan(1); - for (const line of lines) { - expect(Object.keys(JSON.parse(line) as object).sort()).toEqual([ - "event", - "module", - "payload", - "seq", - "timestamp", - ]); - } - }); - it("prints the history with the daemon stopped, and the daemon stays stopped", async () => { const env = await withDaemon(); await prepare(env); @@ -147,16 +127,4 @@ describe("event history", () => { expect(emitted.length).toBeGreaterThan(0); expect(emitted.filter((entry) => !onDisk.has(`${entry.seq}:${entry.timestamp}`))).toEqual([]); }); - - it("grants and releases a lease with a directory at the event file's path", async () => { - const env = await withDaemon({ mode: "auto" }); - await mkdir(join(env.home, "events.jsonl")); - expect((await env.startDaemon()).code).toBe(0); - await prepare(env); - - const leaseId = await leaseDevice(env); - const release = await env.cli(["release", leaseId]); - - expect(release.code).toBe(0); - }); }); diff --git a/e2e/held-lease-liveness.test.ts b/e2e/held-lease-liveness.test.ts index 9e4acea76..7d982069c 100644 --- a/e2e/held-lease-liveness.test.ts +++ b/e2e/held-lease-liveness.test.ts @@ -8,87 +8,6 @@ import { waitForDeviceState, waitForLeaseCount, withDaemon } from "./helpers/ind * its close, its daemon's death, or a restart -- ends one. */ describe("lease liveness & restart", () => { - it("keeps a SIGKILLed holder's lease until it expires, then frees the device", async () => { - // The one behaviour change a local user notices (ADR 0004's Consequences): a holder that - // cannot run its own release path holds its device until `ttlDeadline`. A short TTL is - // the bound, which is why this env sets one. - const env = await withDaemon({ configOverrides: { lease: { defaultTtlMs: 5_000 } } }); - await env.driverScript.set({ - ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, - }); - - const holder = env.cliBackground([ - "lease", - "--platform", - "ios", - "--device", - "iPhone 16", - "--os", - "18.4", - "--agent-id", - "flow5-killed", - ]); - const grant = JSON.parse(await holder.firstStdoutLine()) as { - lease: { id: string }; - device: { driverDeviceId: string }; - }; - await waitForLeaseCount(env, 1); - - holder.kill("SIGKILL"); - await holder.waitForExit(15_000); - - // Killed outright, so nothing released: the lease is still there right after the holder - // is gone, with its device still leased. - const leases = (await env.cli(["list", "--leases"])).json as { id: string }[]; - expect(leases.map((lease) => lease.id)).toContain(grant.lease.id); - - // Its own deadline is what ends it -- nothing renews it any more. - await waitForLeaseCount(env, 0, { timeout: 30_000 }); - await waitForDeviceState(env, grant.device.driverDeviceId, "ready"); - await env.expectEvents(["lease.granted", "lease.expired"]); - }); - - it("releases at once when a holder exits gracefully, without waiting for the TTL", async () => { - const env = await withDaemon({ configOverrides: { lease: { defaultTtlMs: 600_000 } } }); - await env.driverScript.set({ - ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, - }); - - const holder = env.cliBackground([ - "lease", - "--platform", - "ios", - "--device", - "iPhone 16", - "--os", - "18.4", - "--agent-id", - "flow5-sigterm", - ]); - const grant = JSON.parse(await holder.firstStdoutLine()) as { - lease: { id: string }; - device: { driverDeviceId: string }; - }; - await waitForLeaseCount(env, 1); - - // Release-on-exit is the holder's own policy (ADR 0004 §2), and it is what makes a - // normal exit still free the device immediately -- the ten-minute TTL above never - // comes into it. - holder.kill("SIGTERM"); - const exit = await holder.waitForExit(15_000); - expect(exit.code).toBe(0); - - await waitForLeaseCount(env, 0); - await waitForDeviceState(env, grant.device.driverDeviceId, "ready"); - const recorded = await env.expectEvents(["lease.granted", "lease.released"]); - expect(recorded).toContainEqual( - expect.objectContaining({ - event: "lease.released", - payload: expect.objectContaining({ leaseId: grant.lease.id, reason: "explicit" }), - }), - ); - }); - it("keeps a lease across an ungraceful daemon restart, with its TTL timer restored", async () => { // The TTL is the floor on this test's wall clock -- the last step waits it out -- so it is // sized against what has to fit inside it, not padded further: a kill-and-restart (and a diff --git a/e2e/http-api.test.ts b/e2e/http-api.test.ts index 352862c3e..df3d83201 100644 --- a/e2e/http-api.test.ts +++ b/e2e/http-api.test.ts @@ -308,53 +308,4 @@ describe("HTTP API", () => { await env.cli(["release", lease?.id ?? ""]); }); - - it("GET /v1/events?since=1h returns an event from before a daemon restart", async () => { - const port = await reservePort(); - const env = await withDaemon({ - configOverrides: { http: { enabled: true, host: "127.0.0.1", port } }, - }); - await env.driverScript.set({ - ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, - }); - const lease = await env.cli([ - "lease", - "--platform", - "ios", - "--device", - "iPhone 16", - "--os", - "18.4", - "--detach", - ]); - expect(lease.code).toBe(0); - const leaseId = (lease.json as { lease: { id: string } }).lease.id; - const token = await env.cli(["token", "create", "--role", "operator"]); - const operatorAuth = { authorization: `Bearer ${(token.json as { secret: string }).secret}` }; - - await env.restartDaemon(); - const baseUrl = `http://127.0.0.1:${port}`; - await waitFor( - async () => { - try { - return (await fetch(`${baseUrl}/v1/healthz`)).ok; - } catch { - return false; - } - }, - { label: "HTTP gateway accepting connections after the restart" }, - ); - const response = await fetch(`${baseUrl}/v1/events?since=1h`, { headers: operatorAuth }); - - expect(response.status).toBe(200); - const body = (await response.json()) as { - events: { event: string; payload: { leaseId?: string } }[]; - }; - expect(body.events).toContainEqual( - expect.objectContaining({ - event: "lease.granted", - payload: expect.objectContaining({ leaseId }), - }), - ); - }); }); diff --git a/e2e/lease-environment-passthrough.test.ts b/e2e/lease-environment-passthrough.test.ts index 57b8530ee..1d8fdc3cd 100644 --- a/e2e/lease-environment-passthrough.test.ts +++ b/e2e/lease-environment-passthrough.test.ts @@ -68,69 +68,6 @@ describe("reaching a leased device", () => { expect((await env.cli(["release", grant.lease.id])).code).toBe(0); }); - it("carries the driver's environment on the grant, as JSON and as shell exports", async () => { - const env = await withDaemon(); - await env.driverScript.set({ - ios: { - knownModels: ["iPhone 16"], - availableOsVersions: ["18.4"], - // A device root is a configurable path: the quote and the space are the two - // characters a naive `--export-env` corrupts. - leaseEnvironment: { SIMLOCK_IOS_DEVICE_SET: "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/Users/o'brien/My Sims/devices/ios" }, - }, - }); - - const lease = await env.cli([ - "lease", - "--platform", - "ios", - "--device", - "iPhone 16", - "--agent-id", - "env-json-agent", - "--detach", - ]); - expect(lease.code).toBe(0); - const grant = lease.json as { lease: { id: string }; environment: Record }; - expect(grant.environment).toEqual({ - SIMLOCK_IOS_DEVICE_SET: "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/Users/o'brien/My Sims/devices/ios", - }); - expect((await env.cli(["release", grant.lease.id])).code).toBe(0); - - const exported = await env.cli([ - "lease", - "--platform", - "ios", - "--device", - "iPhone 16", - "--agent-id", - "env-export-agent", - "--detach", - "--export-env", - ]); - expect(exported.code).toBe(0); - expect(exported.stdout).toBe( - "export SIMLOCK_IOS_DEVICE_SET='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/Users/o'\\''brien/My Sims/devices/ios'\n", - ); - // The assertion that matters is a real shell's, not a string comparison: what - // `eval "$(simlock lease ... --export-env)"` puts in the environment has to be the - // path byte for byte, quote and space included. - const evaluated = await execFileAsync("/bin/sh", [ - "-c", - `${exported.stdout}printf %s "$SIMLOCK_IOS_DEVICE_SET"`, - ]); - expect(evaluated.stdout).toBe("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/Users/o'brien/My Sims/devices/ios"); - // Released rather than left to the TTL: this flow is about the grant, and leaving a - // lease outstanding would make it share a failure mode with the shutdown flow that - // covers that case deliberately (`daemon lifecycle & recovery`). - const exportedGrant = JSON.parse((await env.cli(["status", "--json"])).stdout) as { - readonly leases: readonly { readonly id: string }[]; - }; - for (const lease of exportedGrant.leases) { - await env.cli(["release", lease.id]); - } - }); - /** * Both wrappers, because they are two different drivers answering the same operation and * the CLI knows the names but nothing else: which flag scopes the tool, and what its diff --git a/e2e/lease-lifecycle.test.ts b/e2e/lease-lifecycle.test.ts index fa1b53217..a61665b10 100644 --- a/e2e/lease-lifecycle.test.ts +++ b/e2e/lease-lifecycle.test.ts @@ -64,70 +64,4 @@ describe("lease lifecycle across both frontends", () => { await env.expectEvents(["lease.requested", "lease.granted", "lease.released"]); }); - - it("agrees with the CLI when the lease/release cycle runs through MCP", async () => { - const env = await withDaemon(); - await env.driverScript.set({ - ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, - }); - const agentId = "flow2-mcp-agent"; - - const mcp = await env.mcpClient({ env: { SIMLOCK_AGENT_ID: agentId } }); - try { - const leaseResult = await mcp.client.callTool({ - name: "lease_simulator", - arguments: { model: "iPhone 16", osVersion: "18.4", platform: "ios" }, - }); - const leased = leaseResult.structuredContent as { - device: { driverDeviceId: string; spec: { model: string } }; - lease: { id: string }; - }; - expect(leased.device.spec.model).toBe("iPhone 16"); - - const statusResult = await mcp.client.callTool({ name: "lease_status", arguments: {} }); - expect(statusResult.structuredContent).toMatchObject({ - held: true, - id: leased.lease.id, - }); - - // The CLI frontend must see the exact same lease, keyed by the same requester id. - const cliLeases = await env.cli(["list", "--leases"]); - expect(cliLeases.code).toBe(0); - expect(cliLeases.json).toEqual( - expect.arrayContaining([ - expect.objectContaining({ id: leased.lease.id, requesterId: agentId }), - ]), - ); - - // A slow purge is the realistic case (an iOS erase runs tens of seconds), and - // the agent must not be made to sit through it: release_simulator returns on - // the registry commit and the wipe finishes behind it. - await env.driverScript.merge({ ios: { latencyMs: { reclaim: 5_000 } } }); - - const releaseResult = await mcp.client.callTool({ - name: "release_simulator", - arguments: { leaseId: leased.lease.id }, - }); - expect(releaseResult.structuredContent).toMatchObject({ - leaseId: leased.lease.id, - released: true, - }); - - // Already answered, while the erase it handed off is still running: the lease is - // gone from the CLI's view and the device is `reclaiming`, not yet `ready`. - const cliLeasesAfter = await env.cli(["list", "--leases"]); - expect(cliLeasesAfter.json).toEqual([]); - const midPurge = await env.cli(["list", "--devices"]); - expect(midPurge.json).toEqual([ - expect.objectContaining({ - driverDeviceId: leased.device.driverDeviceId, - state: "reclaiming", - }), - ]); - - await waitForDeviceState(env, leased.device.driverDeviceId, "ready"); - } finally { - await mcp.close(); - } - }); }); diff --git a/e2e/leased-device-crash-recovery.test.ts b/e2e/leased-device-crash-recovery.test.ts index 697656ec6..76381dd73 100644 --- a/e2e/leased-device-crash-recovery.test.ts +++ b/e2e/leased-device-crash-recovery.test.ts @@ -148,58 +148,6 @@ describe("leased device crash recovery", () => { await held.waitForExit(15_000).catch(() => undefined); }); - it("gives the lease up when a leased device cannot be recovered", async () => { - const env = await withDaemon({ - configOverrides: { - health: { ...HEALTH_CONFIG_BASE, maxRecoveryAttempts: 1 }, - limits: { ios: { maxDevices: 2, maxRunning: 2 }, maxRunning: 2 }, - }, - }); - await env.driverScript.set({ - ios: { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }, - }); - - const held = leaseHeld(env, "crash-recovery-b"); - const grant = await grantOf(held); - await waitForLeaseCount(env, 1); - - // Same crash as the first flow, but every reboot attempt fails and there is - // only one attempt to give -- recovery cannot work. - await env.driverScript.merge({ - ios: { - failures: { - makeReady: { message: "simulated unrecoverable boot failure", type: "generic" }, - }, - managedReality: { - devices: [{ deviceId: grant.device.driverDeviceId, runState: "stopped" }], - }, - }, - }); - - const recorded = await env.expectEvents(["device.recovery-failed", "lease.released"]); - const recoveryFailed = recorded.find((event) => event.event === "device.recovery-failed"); - expect(recoveryFailed?.payload).toMatchObject({ - leaseId: grant.lease.id, - reason: "attempts-exhausted", - }); - const released = recorded.find( - (event) => - event.event === "lease.released" && - (event.payload as { leaseId?: string }).leaseId === grant.lease.id, - ); - expect(released?.payload).toMatchObject({ leaseId: grant.lease.id, reason: "device-lost" }); - - // The device is back in the pool, not stuck leased to a dead device. - await waitForLeaseCount(env, 0); - const leases = (await env.cli(["list", "--leases"])).json; - expect(leases).not.toEqual( - expect.arrayContaining([expect.objectContaining({ id: grant.lease.id })]), - ); - - held.kill("SIGKILL"); - await held.waitForExit(15_000).catch(() => undefined); - }); - // Regression guard: writing this suite found that the held CLI never learned its // lease had died. The daemon has always pushed `lease-lost` for a `device-lost` // release -- the same push MCP's `#handleLeaseLost` reacts to -- but `runLease`'s @@ -207,7 +155,7 @@ describe("leased device crash recovery", () => { // nor exited; it sat forever awaiting an OS signal while holding nothing. Recovery // giving up is the first thing that ends a lease with no human involved, which is // what made the gap matter enough to fix. - it("the held CLI observes its lease ending when the device is unrecoverable", async () => { + it("gives the lease up as device-lost when a leased device cannot be recovered, and the held CLI reports it and exits 14", async () => { const env = await withDaemon({ configOverrides: { health: { ...HEALTH_CONFIG_BASE, maxRecoveryAttempts: 1 }, @@ -233,7 +181,19 @@ describe("leased device crash recovery", () => { }, }); - // The daemon-side lease is released well before this returns. + // Every reboot attempt fails and there is only one attempt to give, so recovery gives + // up and the lease ends with the device, not stuck leased to a dead device. + const recorded = await env.expectEvents(["device.recovery-failed", "lease.released"]); + expect( + recorded.find((event) => event.event === "device.recovery-failed")?.payload, + ).toMatchObject({ leaseId: grant.lease.id, reason: "attempts-exhausted" }); + expect( + recorded.find( + (event) => + event.event === "lease.released" && + (event.payload as { leaseId?: string }).leaseId === grant.lease.id, + )?.payload, + ).toMatchObject({ leaseId: grant.lease.id, reason: "device-lost" }); await waitForLeaseCount(env, 0); // Expected: the held process reports the lost lease on stderr (mirroring diff --git a/e2e/mcp-session.test.ts b/e2e/mcp-session.test.ts index d4b21bfff..6d0c6ffdc 100644 --- a/e2e/mcp-session.test.ts +++ b/e2e/mcp-session.test.ts @@ -8,7 +8,7 @@ interface McpErrorPayload { } describe("MCP session semantics", () => { - it("exercises all four tools, and streams strictly increasing progress with human messages", async () => { + it("exercises all four tools, streams strictly increasing progress with human messages, and its lease is the one the CLI lists", async () => { const env = await withDaemon(); await env.driverScript.set({ ios: { knownModels: ["iPhone 16"], availableOsVersions: ["18.4"] }, @@ -53,6 +53,14 @@ describe("MCP session semantics", () => { id: leased.lease.id, }); + // The CLI frontend must see the exact same lease, keyed by the same requester id. + const cliLeases = await env.cli(["list", "--leases"]); + expect(cliLeases.json).toEqual( + expect.arrayContaining([ + expect.objectContaining({ id: leased.lease.id, requesterId: "flow7-tools" }), + ]), + ); + const released = await mcp.client.callTool({ name: "release_simulator", arguments: { leaseId: leased.lease.id }, diff --git a/e2e/renew-ttl.test.ts b/e2e/renew-ttl.test.ts index 0d72a61b3..96ac1b334 100644 --- a/e2e/renew-ttl.test.ts +++ b/e2e/renew-ttl.test.ts @@ -45,7 +45,7 @@ describe("TTL leases and client-side renewal (ADR 0004)", () => { ); }); - it("keeps a renewing holder's lease alive (MCP and CLI) while an unrenewed lease expires", async () => { + it("keeps a renewing holder's lease alive (MCP and CLI) while a SIGKILLed holder's lease stays until its TTL, then expires", async () => { const env = await withDaemon({ // Short enough that the unrenewed lease's expiry lands inside the test's own timeline; // both holders renew at a third of it, so they slide well past it (ADR 0004 §2). @@ -81,7 +81,7 @@ describe("TTL leases and client-side renewal (ADR 0004)", () => { lease: { id: string; ttlDeadline: number }; }; - const detachedResult = await env.cli([ + const killedHolder = env.cliBackground([ "lease", "--platform", "ios", @@ -90,21 +90,26 @@ describe("TTL leases and client-side renewal (ADR 0004)", () => { "--os", "18.4", "--agent-id", - "flow6-detached", - "--detach", + "flow6-killed", ]); - const detachedGrant = detachedResult.json as { lease: { id: string } }; - - // Both holders -- MCP and CLI -- renew on their own timer at a third of the TTL (ADR - // 0004 §2), pushing their deadline well past the grant-time one. The `--detach` lease - // has no holder process at all, so nothing renews it and it expires exactly at its own - // deadline. + const killedGrant = JSON.parse(await killedHolder.firstStdoutLine()) as { + lease: { id: string }; + }; + killedHolder.kill("SIGKILL"); + await killedHolder.waitForExit(15_000); + // Killed outright, it never ran its release path, and its connection closing ends + // nothing (ADR 0004): the lease is still there right after the holder is gone. + expect((await leaseRows(env)).map((row) => row.id)).toContain(killedGrant.lease.id); + + // Both live holders -- MCP and CLI -- renew on their own timer at a third of the TTL + // (ADR 0004 §2), pushing their deadline well past the grant-time one. Nothing renews + // the killed holder's lease any more, so its own deadline ends it. await waitFor( async () => { const rows = await leaseRows(env); - return rows.every((row) => row.id !== detachedGrant.lease.id); + return rows.every((row) => row.id !== killedGrant.lease.id); }, - { timeout: 15_000, label: "the unrenewed --detach lease expires at its TTL" }, + { timeout: 15_000, label: "the SIGKILLed holder's lease expires at its TTL" }, ); const rowsAfterExpiry = await leaseRows(env); @@ -144,7 +149,7 @@ describe("TTL leases and client-side renewal (ADR 0004)", () => { expect(recorded).toContainEqual( expect.objectContaining({ event: "lease.expired", - payload: expect.objectContaining({ leaseId: detachedGrant.lease.id }), + payload: expect.objectContaining({ leaseId: killedGrant.lease.id }), }), ); @@ -159,7 +164,7 @@ describe("TTL leases and client-side renewal (ADR 0004)", () => { } }); - it("renews a --detach lease by hand, keeping its own width, and caps what may be asked for", async () => { + it("renews a --detach lease by hand, keeping its own width", async () => { const env = await withDaemon({ configOverrides: { lease: { defaultTtlMs: 60_000, maxTtlMs: 120_000 } }, }); @@ -193,29 +198,6 @@ describe("TTL leases and client-side renewal (ADR 0004)", () => { expect(renewedLease.ttlMs).toBe(90_000); expect(renewedLease.ttlDeadline).toBeGreaterThanOrEqual(grant.lease.ttlDeadline); - // Above `lease.maxTtlMs` is a BAD_REQUEST, not a silent clamp -- on a renew... - const tooLong = await env.cli(["lease", "renew", grant.lease.id, "--ttl", "5m"]); - expect(tooLong.code).toBe(2); - expect(tooLong.error?.code).toBe("BAD_REQUEST"); - - // ...and on a request. - const tooLongRequest = await env.cli([ - "lease", - "--platform", - "ios", - "--device", - "iPhone 16", - "--os", - "18.4", - "--agent-id", - "asks-too-much", - "--detach", - "--ttl", - "5m", - ]); - expect(tooLongRequest.code).toBe(2); - expect(tooLongRequest.error?.code).toBe("BAD_REQUEST"); - await env.cli(["release", grant.lease.id]); }); }); diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 193271c88..f72aa525c 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -146,8 +146,8 @@ describe("readLogFile", () => { * `daemon/dispatcher.test.ts`, and `SimlockClientImpl`'s own suite in * `simlock-client/client.test.ts`; re-asserting it a third time through the CLI tested only that * this module still calls `client.foo()`, which the TypeScript compiler already guarantees - * against `SimlockAdminClient`'s interface. `--bind-pid`/parent-watch termination races are not - * covered by any suite in `pnpm run test` -- they survive only in the real-hardware e2e lanes. + * against `SimlockAdminClient`'s interface. `--bind-pid`/parent-watch termination is covered + * across real processes by the fast e2e lane (`e2e/parent-watch.test.ts`), not here. */ describe("CLI: exit codes", () => { it.each([ From 4714427f15ffef0c665dff410def84fc5d9cdd2b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 10:43:01 +0200 Subject: [PATCH 9/9] test(e2e): teardown's hook has room for stopping the daemon and emptying a set Emptying a device set is three bounded calls in a row (list, shutdown, delete), up to 45s, on top of ~35s stopping the daemon -- more than the old 60s hookTimeout, which would cut teardown short before the home is removed. --- e2e/helpers/ios-device-set.ts | 9 +++++---- vitest.config.ts | 4 +++- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/e2e/helpers/ios-device-set.ts b/e2e/helpers/ios-device-set.ts index c33061959..c18f19454 100644 --- a/e2e/helpers/ios-device-set.ts +++ b/e2e/helpers/ios-device-set.ts @@ -33,9 +33,9 @@ export async function simctlInSet( } /** - * Per call while emptying a set. Teardown runs inside a 60s hook that already spends up to - * ~25s stopping the daemon, so a hung simctl must give up rather than eat the rest of it -- - * the home's removal comes after. + * Per call while emptying a set. Teardown runs inside the e2e `hookTimeout` and stops the + * daemon first, so a hung simctl must give up rather than eat the rest of the hook -- the + * home's removal comes after. */ const EMPTY_SET_CALL_TIMEOUT_MS = 15_000; @@ -61,7 +61,8 @@ export async function setDevices( * while it does (`ENOTEMPTY`). * * Devices are handled in parallel and every call is bounded, so emptying a set of any size - * takes at most two `EMPTY_SET_CALL_TIMEOUT_MS`. + * takes at most three `EMPTY_SET_CALL_TIMEOUT_MS`: the list, then each device's shutdown and + * delete. */ export async function emptyDeviceSet(deviceSet: string): Promise { const bounded = { timeoutMs: EMPTY_SET_CALL_TIMEOUT_MS }; diff --git a/vitest.config.ts b/vitest.config.ts index 0764e8162..9cee5bb05 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -25,7 +25,9 @@ export default defineConfig({ // per-test timeout -- a hang in the fast fake-driver lane should fail in // ~2 minutes, not stall CI for ten. testTimeout: 120_000, - hookTimeout: 60_000, + // Teardown is a hook: stopping the daemon and waiting its process out can take ~35s, + // and a real-SDK flow's teardown then empties its iOS device set (up to 45s more). + hookTimeout: 120_000, }, }, ],