From 7f69b7fb1988d988103047f218353e4bf048b3b6 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 20:40:46 +0100 Subject: [PATCH 01/11] test: the first provision of a kind makes its seed from a throwaway (#1569) --- src/drivers/ios/driver-options.ts | 2 + src/drivers/ios/index-seed-throwaway.test.ts | 86 ++++++++++++++++++++ src/drivers/ios/test-index.ts | 4 + 3 files changed, 92 insertions(+) create mode 100644 src/drivers/ios/index-seed-throwaway.test.ts diff --git a/src/drivers/ios/driver-options.ts b/src/drivers/ios/driver-options.ts index 0850a8fc0..10da15860 100644 --- a/src/drivers/ios/driver-options.ts +++ b/src/drivers/ios/driver-options.ts @@ -33,6 +33,8 @@ export interface IosSimctlDriverOptions { /** why: the daemon's pid is named in the staging directory of a new root. */ readonly pid?: number; readonly coreSimulatorRoot?: string; + // why: where CoreSimulator keeps each simulator's log folder, which `simctl delete` leaves behind; with none given the driver deletes no log folder. + readonly logsRoot?: string; // why: where launchd_sim keeps each simulator's overrides folder; a test points it elsewhere. readonly launchdOverridesRoot?: string; readonly onSlimmed?: (fact: SlimmedFact) => void; diff --git a/src/drivers/ios/index-seed-throwaway.test.ts b/src/drivers/ios/index-seed-throwaway.test.ts new file mode 100644 index 000000000..e714d990b --- /dev/null +++ b/src/drivers/ios/index-seed-throwaway.test.ts @@ -0,0 +1,86 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { FakeClock, MemoryFilesystem, ScriptedProcessRunner } from "../../ports/index.js"; +import { IosSimctlDriver } from "./index.js"; +import { memorySourceDatabase } from "./testing.js"; +import { deviceRoot, driverData, instanceId, plantManagedDevice, simctl } from "./test-slim.js"; +import { + listFixture, + listInvocation, + logsRoot, + scopedRunners, + seedUdid, + sourcesSimctl, + spec, + throwawayUdid, +} from "./test-index.js"; + +afterEach(() => { + scopedRunners.length = 0; +}); + +describe("IosSimctlDriver seed throwaway", () => { + it("the first provision of a kind makes its seed from a throwaway", async () => { + const copyUdid = "00000000-0000-0000-0000-000000000002"; + const name = "simlock-seed-device-1"; + const cases = [ + { + label: "simlock set", + steps: [ + { + match: simctl("create", name, driverData.deviceTypeId, driverData.runtimeId), + result: { code: 0, stderr: "", stdout: `${throwawayUdid}\n` }, + }, + { match: simctl("boot", throwawayUdid) }, + { match: simctl("bootstatus", throwawayUdid, "-b") }, + { match: simctl("listapps", throwawayUdid) }, + { match: simctl("shutdown", throwawayUdid) }, + { + match: simctl("clone", throwawayUdid, name, `${deviceRoot}/sources`), + result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, + }, + { match: simctl("delete", throwawayUdid) }, + ], + }, + ]; + for (const scenario of cases) { + const database = await memorySourceDatabase(); + const runner = new ScriptedProcessRunner([ + { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, + ...scenario.steps, + { + match: sourcesSimctl("clone", seedUdid, driverData.name, deviceRoot), + result: { code: 0, stderr: "", stdout: `${copyUdid}\n` }, + }, + ]); + scopedRunners.push(runner); + const filesystem = new MemoryFilesystem(); + await plantManagedDevice(filesystem); + await filesystem.mkdirp(`${deviceRoot}/${copyUdid}/data`); + await filesystem.mkdirp(`${logsRoot}/${throwawayUdid}`); + const driver = await IosSimctlDriver.create({ + clock: new FakeClock(), + database, + driverConfig: { deviceRoot }, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + logsRoot, + processRunner: runner, + simlockHome: "/home/.simlock", + }); + + await expect(driver.provision(spec), scenario.label).resolves.toMatchObject({ + deviceId: copyUdid, + }); + + expect(runner.calls.length, scenario.label).toBe(scenario.steps.length + 2); + expect( + database.prepare("SELECT state, udid, throwaway_udid FROM ios_source_data").all(), + scenario.label, + ).toEqual([{ state: "ready", throwaway_udid: throwawayUdid, udid: seedUdid }]); + await expect(filesystem.exists(`${logsRoot}/${throwawayUdid}`), scenario.label).resolves.toBe( + false, + ); + } + }); +}); diff --git a/src/drivers/ios/test-index.ts b/src/drivers/ios/test-index.ts index 4c50a1da3..6600d8e57 100644 --- a/src/drivers/ios/test-index.ts +++ b/src/drivers/ios/test-index.ts @@ -358,3 +358,7 @@ export function assetInfoPlist(simulatorVersion: string, build: string): string } export const prepareFull = { mode: "full", purpose: "prepare" } as const; + +export const throwawayUdid = "00000000-0000-0000-0000-0000000000bb"; + +export const logsRoot = "/Logs/CoreSimulator"; From 559c6ded2d3d0d37fa30ce54bf409187da982199 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 20:42:39 +0100 Subject: [PATCH 02/11] feat(ios): a seed is copied unbooted from a throwaway that booted once and is deleted with its log folder (#1569) --- src/daemon/driver-discovery.ts | 1 + src/drivers/ios/index-device-set.test.ts | 20 ++++-- src/drivers/ios/index-seed-provision.test.ts | 72 +++++++------------ src/drivers/ios/index-seed-sources.test.ts | 68 ++++++++---------- src/drivers/ios/index-seed-throwaway.test.ts | 20 +----- src/drivers/ios/index.ts | 1 + src/drivers/ios/seeds.ts | 73 +++++++++++++++----- src/drivers/ios/source-data.ts | 14 +++- src/drivers/ios/test-index.ts | 20 ++++++ 9 files changed, 161 insertions(+), 128 deletions(-) diff --git a/src/daemon/driver-discovery.ts b/src/daemon/driver-discovery.ts index f00356b3b..3687c43dd 100644 --- a/src/daemon/driver-discovery.ts +++ b/src/daemon/driver-discovery.ts @@ -199,6 +199,7 @@ async function discoverIosDriver( idGenerator: options.idGenerator, instanceId: options.instanceId, logger: logger.child("ios"), + logsRoot: `${homedir()}/Library/Logs/CoreSimulator`, onSilenceFailed: logSilenceFailure(logger), onWindowFailed: logWindowFailure(logger), onSlimmed: emitSlimDiagnostic(options.eventBus), diff --git a/src/drivers/ios/index-device-set.test.ts b/src/drivers/ios/index-device-set.test.ts index 1a526fb5d..f5868b51f 100644 --- a/src/drivers/ios/index-device-set.test.ts +++ b/src/drivers/ios/index-device-set.test.ts @@ -29,6 +29,7 @@ import { seededDatabase, simctlPassthrough, spec, + throwawayUdid, } from "./test-index.js"; describe("IosSimctlDriver device set", () => { @@ -75,13 +76,18 @@ describe("IosSimctlDriver device set", () => { { args: ["create", "simlock-seed-device-1", driverData.deviceTypeId, driverData.runtimeId], scoped: true, - sources: true, + stdout: `${throwawayUdid}\n`, + }, + { args: ["boot", throwawayUdid], scoped: true }, + { args: ["bootstatus", throwawayUdid, "-b"], scoped: true }, + { args: ["listapps", throwawayUdid], scoped: true }, + { args: ["shutdown", throwawayUdid], scoped: true }, + { + args: ["clone", throwawayUdid, "simlock-seed-device-1", sourcesSet], + scoped: true, stdout: `${seedUdid}\n`, }, - { args: ["boot", seedUdid], scoped: true, sources: true }, - { args: ["bootstatus", seedUdid, "-b"], scoped: true, sources: true }, - { args: ["listapps", seedUdid], scoped: true, sources: true }, - { args: ["shutdown", seedUdid], scoped: true, sources: true }, + { args: ["delete", throwawayUdid], scoped: true }, { args: ["clone", seedUdid, driverData.name, devicesDir], scoped: true, @@ -109,7 +115,7 @@ describe("IosSimctlDriver device set", () => { : ["simctl", ...step.args]; const runner = new ScriptedProcessRunner( steps.flatMap((step) => [ - ...(!scoped && step.args[0] === "boot" && step.sources !== true + ...(!scoped && step.args[0] === "boot" && step.args[1] === driverData.udid ? deviceHubEdit( `Set :DevicePreferences:${driverData.udid}:pasteboardSyncEnabled false`, ).map((match) => ({ match })) @@ -120,7 +126,7 @@ describe("IosSimctlDriver device set", () => { ? {} : { result: { code: 0, stderr: "", stdout: step.stdout } }), }, - ...(!scoped && step.args[0] === "delete" + ...(!scoped && step.args[0] === "delete" && step.args[1] === driverData.udid ? deviceHubEdit(`Delete :DevicePreferences:${driverData.udid}`).map((match) => ({ match, })) diff --git a/src/drivers/ios/index-seed-provision.test.ts b/src/drivers/ios/index-seed-provision.test.ts index b1443b98e..dd74be977 100644 --- a/src/drivers/ios/index-seed-provision.test.ts +++ b/src/drivers/ios/index-seed-provision.test.ts @@ -30,6 +30,8 @@ import { seededDatabase, sourcesSimctl, spec, + throwawaySeedSteps, + throwawayUdid, } from "./test-index.js"; /** @@ -61,19 +63,7 @@ describe("IosSimctlDriver", () => { const cloneInvocation = sourcesSimctl("clone", seedUdid, driverData.name, deviceRoot); const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, - { - match: sourcesSimctl( - "create", - "simlock-seed-device-1", - driverData.deviceTypeId, - driverData.runtimeId, - ), - result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, - }, - { match: sourcesSimctl("boot", seedUdid) }, - { match: sourcesSimctl("bootstatus", seedUdid, "-b") }, - { match: sourcesSimctl("listapps", seedUdid) }, - { match: sourcesSimctl("shutdown", seedUdid) }, + ...throwawaySeedSteps(), { match: cloneInvocation, result: { code: 0, stderr: "", stdout: `${driverData.udid}\n` } }, ]); const filesystem = new MemoryFilesystem(); @@ -100,28 +90,26 @@ describe("IosSimctlDriver", () => { const copyUdid = "00000000-0000-0000-0000-000000000002"; const database = await memorySourceDatabase(); const rowsWhenCreated: unknown[] = []; - const seedCreate = sourcesSimctl( + const seedCreate = simctl( "create", "simlock-seed-device-1", driverData.deviceTypeId, driverData.runtimeId, ); const cloneInvocation = sourcesSimctl("clone", seedUdid, driverData.name, deviceRoot); + const [create, ...afterCreate] = throwawaySeedSteps(); const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, { + ...create, match: seedCreate, onSpawn: () => { rowsWhenCreated.push( ...database.prepare("SELECT state, udid FROM ios_source_data").all(), ); }, - result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, }, - { match: sourcesSimctl("boot", seedUdid) }, - { match: sourcesSimctl("bootstatus", seedUdid, "-b") }, - { match: sourcesSimctl("listapps", seedUdid) }, - { match: sourcesSimctl("shutdown", seedUdid) }, + ...afterCreate, { match: cloneInvocation, result: { code: 0, stderr: "", stdout: `${driverData.udid}\n` } }, { match: cloneInvocation, result: { code: 0, stderr: "", stdout: `${copyUdid}\n` } }, ]); @@ -146,15 +134,20 @@ describe("IosSimctlDriver", () => { expect(runner.calls).toEqual([ { ...listInvocation, options: { timeoutMs: 30_000 } }, { ...seedCreate, options: { timeoutMs: 330_000 } }, - { ...sourcesSimctl("boot", seedUdid), options: { timeoutMs: 300_000 } }, - { ...sourcesSimctl("bootstatus", seedUdid, "-b"), options: { timeoutMs: 300_000 } }, - { ...sourcesSimctl("listapps", seedUdid), options: { timeoutMs: 30_000 } }, - { ...sourcesSimctl("shutdown", seedUdid), options: { timeoutMs: 30_000 } }, + { ...simctl("boot", throwawayUdid), options: { timeoutMs: 300_000 } }, + { ...simctl("bootstatus", throwawayUdid, "-b"), options: { timeoutMs: 300_000 } }, + { ...simctl("listapps", throwawayUdid), options: { timeoutMs: 30_000 } }, + { ...simctl("shutdown", throwawayUdid), options: { timeoutMs: 30_000 } }, + { + ...simctl("clone", throwawayUdid, "simlock-seed-device-1", `${deviceRoot}/sources`), + options: { timeoutMs: 330_000 }, + }, + { ...simctl("delete", throwawayUdid), options: { timeoutMs: 30_000 } }, { ...cloneInvocation, options: { timeoutMs: 330_000 } }, ]); await expect(driver.provision(spec)).resolves.toMatchObject({ deviceId: copyUdid }); - expect(runner.calls.slice(7)).toEqual([ + expect(runner.calls.slice(9)).toEqual([ { ...cloneInvocation, options: { timeoutMs: 330_000 } }, ]); }); @@ -188,19 +181,7 @@ describe("IosSimctlDriver", () => { const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, - { - match: sourcesSimctl( - "create", - "simlock-seed-device-1", - driverData.deviceTypeId, - driverData.runtimeId, - ), - result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, - }, - { match: sourcesSimctl("boot", seedUdid) }, - { match: sourcesSimctl("bootstatus", seedUdid, "-b") }, - { match: sourcesSimctl("listapps", seedUdid) }, - { match: sourcesSimctl("shutdown", seedUdid) }, + ...throwawaySeedSteps(), { hangs: true, match: cloneInvocation }, { match: cloneInvocation, result: { code: 0, stderr: "", stdout: `${copyUdid}\n` } }, ]); @@ -209,12 +190,13 @@ describe("IosSimctlDriver", () => { const driver = await createDriver(runner, clock, filesystem); await plantManagedDevice(filesystem); await filesystem.mkdirp(`${deviceRoot}/${copyUdid}/data`); - const clones = (): number => runner.calls.filter((call) => call.args[3] === "clone").length; + const clones = (): number => + runner.calls.filter((call) => call.args[3] === "clone" && call.args[4] === seedUdid).length; const first = driver.provision(spec); const second = driver.provision(spec); const firstSettled = first.catch((caught: unknown) => caught); - await waitForCalls(runner, 8); + await waitForCalls(runner, 10); expect(runner.calls.filter((call) => call.args[3] === "create")).toHaveLength(1); for (let tick = 0; tick < 100; tick += 1) await Promise.resolve(); @@ -243,7 +225,7 @@ describe("IosSimctlDriver", () => { steps: [ { hangs: true, - match: sourcesSimctl( + match: simctl( "create", "simlock-seed-device-1", driverData.deviceTypeId, @@ -338,13 +320,9 @@ describe("IosSimctlDriver", () => { { call: "a seed's create", act: (driver: IosSimctlDriver) => driver.provision(spec), - deleteArgs: (udid: string) => sourcesSimctl("delete", udid).args, - hung: sourcesSimctl( - "create", - "simlock-seed-device-1", - driverData.deviceTypeId, - driverData.runtimeId, - ).args, + deleteArgs: (udid: string) => simctl("delete", udid).args, + hung: simctl("create", "simlock-seed-device-1", driverData.deviceTypeId, driverData.runtimeId) + .args, isDefault: false, seeded: false, steps: [], diff --git a/src/drivers/ios/index-seed-sources.test.ts b/src/drivers/ios/index-seed-sources.test.ts index f640a09b0..4a95236e0 100644 --- a/src/drivers/ios/index-seed-sources.test.ts +++ b/src/drivers/ios/index-seed-sources.test.ts @@ -24,6 +24,8 @@ import { seededDatabase, sourcesSimctl, spec, + throwawaySeedSteps, + throwawayUdid, } from "./test-index.js"; /** @@ -214,19 +216,7 @@ describe("IosSimctlDriver", () => { { match: sourcesSimctl("delete", stuckUdid) }, ] : []), - { - match: sourcesSimctl( - "create", - "simlock-seed-device-1", - driverData.deviceTypeId, - driverData.runtimeId, - ), - result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, - }, - { match: sourcesSimctl("boot", seedUdid) }, - { match: sourcesSimctl("bootstatus", seedUdid, "-b") }, - { match: sourcesSimctl("listapps", seedUdid) }, - { match: sourcesSimctl("shutdown", seedUdid) }, + ...throwawaySeedSteps(), { match: cloneInvocation, result: { code: 0, stderr: "", stdout: `${copyUdid}\n` } }, ]); const filesystem = new MemoryFilesystem(); @@ -254,7 +244,7 @@ describe("IosSimctlDriver", () => { }, { name: "the seed's boot fails", - message: `seed ${seedUdid} did not boot: `, + message: `seed ${throwawayUdid} did not boot: `, script: [{ code: 1, op: "bootstatus" }], tail: ["shutdown", "delete"], }, @@ -271,16 +261,16 @@ describe("IosSimctlDriver", () => { const steps = ["create", "boot", "bootstatus", "listapps", "shutdown"]; const upTo = steps.indexOf(failing.op); const results = new Map([ - ["create", { code: 0, stderr: "", stdout: `${seedUdid}\n` }], + ["create", { code: 0, stderr: "", stdout: `${throwawayUdid}\n` }], ]); const database = await memorySourceDatabase(); const entries = steps.slice(0, upTo + 1).map((op) => { - const match = sourcesSimctl( + const match = simctl( ...(op === "create" ? ["create", "simlock-seed-device-1", driverData.deviceTypeId, driverData.runtimeId] : op === "bootstatus" - ? [op, seedUdid, "-b"] - : [op, seedUdid]), + ? [op, throwawayUdid, "-b"] + : [op, throwawayUdid]), ); if (op !== failing.op) return { match, ...(results.has(op) ? { result: results.get(op)! } : {}) }; @@ -291,7 +281,7 @@ describe("IosSimctlDriver", () => { const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, ...entries, - ...tail.map((op) => ({ match: sourcesSimctl(op, seedUdid) })), + ...tail.map((op) => ({ match: simctl(op, throwawayUdid) })), ]); const clock = new FakeClock(); const driver = await createDriver(runner, clock, undefined, database); @@ -314,7 +304,7 @@ describe("IosSimctlDriver", () => { ...tail, ]); expect(runner.calls.slice(1).map((call) => call.args[2])).toEqual( - runner.calls.slice(1).map(() => `${deviceRoot}/sources`), + runner.calls.slice(1).map(() => deviceRoot), ); expect(database.prepare("SELECT COUNT(*) AS n FROM ios_source_data").get()).toEqual({ n: 0 }); }, @@ -332,21 +322,21 @@ describe("IosSimctlDriver", () => { const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, { - match: sourcesSimctl( + match: simctl( "create", "simlock-seed-device-1", driverData.deviceTypeId, driverData.runtimeId, ), - result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, + result: { code: 0, stderr: "", stdout: `${throwawayUdid}\n` }, }, ...ran.map((op) => { - const match = sourcesSimctl( - ...(op === "bootstatus" ? [op, seedUdid, "-b"] : [op, seedUdid]), + const match = simctl( + ...(op === "bootstatus" ? [op, throwawayUdid, "-b"] : [op, throwawayUdid]), ); return op === hangs ? { hangs: true, match } : { match }; }), - ...["shutdown", "shutdown", "delete"].map((op) => ({ match: sourcesSimctl(op, seedUdid) })), + ...["shutdown", "shutdown", "delete"].map((op) => ({ match: simctl(op, throwawayUdid) })), ]); const clock = new FakeClock(); const driver = await createDriver(runner, clock, undefined, database, undefined, 2_000); @@ -395,6 +385,7 @@ describe("IosSimctlDriver", () => { } } const planted = staleUdid; + const throwaway = throwawaySeedSteps(); const cloneOf = (udid: string) => sourcesSimctl("clone", udid, driverData.name, deviceRoot); const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: JSON.stringify(catalog) } }, @@ -402,19 +393,7 @@ describe("IosSimctlDriver", () => { ? [ { match: sourcesSimctl("shutdown", staleUdid) }, { match: sourcesSimctl("delete", staleUdid) }, - { - match: sourcesSimctl( - "create", - "simlock-seed-device-1", - driverData.deviceTypeId, - driverData.runtimeId, - ), - result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, - }, - { match: sourcesSimctl("boot", seedUdid) }, - { match: sourcesSimctl("bootstatus", seedUdid, "-b") }, - { match: sourcesSimctl("listapps", seedUdid) }, - { match: sourcesSimctl("shutdown", seedUdid) }, + ...throwaway, ] : []), { @@ -439,7 +418,18 @@ describe("IosSimctlDriver", () => { expect(runner.calls.map((call) => call.args[3]).filter((verb) => verb !== "list")).toEqual( remade - ? ["shutdown", "delete", "create", "boot", "bootstatus", "listapps", "shutdown", "clone"] + ? [ + "shutdown", + "delete", + "create", + "boot", + "bootstatus", + "listapps", + "shutdown", + "clone", + "delete", + "clone", + ] : ["clone"], ); }, diff --git a/src/drivers/ios/index-seed-throwaway.test.ts b/src/drivers/ios/index-seed-throwaway.test.ts index e714d990b..3235774c8 100644 --- a/src/drivers/ios/index-seed-throwaway.test.ts +++ b/src/drivers/ios/index-seed-throwaway.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { FakeClock, MemoryFilesystem, ScriptedProcessRunner } from "../../ports/index.js"; import { IosSimctlDriver } from "./index.js"; import { memorySourceDatabase } from "./testing.js"; -import { deviceRoot, driverData, instanceId, plantManagedDevice, simctl } from "./test-slim.js"; +import { deviceRoot, driverData, instanceId, plantManagedDevice } from "./test-slim.js"; import { listFixture, listInvocation, @@ -11,6 +11,7 @@ import { seedUdid, sourcesSimctl, spec, + throwawaySeedSteps, throwawayUdid, } from "./test-index.js"; @@ -21,25 +22,10 @@ afterEach(() => { describe("IosSimctlDriver seed throwaway", () => { it("the first provision of a kind makes its seed from a throwaway", async () => { const copyUdid = "00000000-0000-0000-0000-000000000002"; - const name = "simlock-seed-device-1"; const cases = [ { label: "simlock set", - steps: [ - { - match: simctl("create", name, driverData.deviceTypeId, driverData.runtimeId), - result: { code: 0, stderr: "", stdout: `${throwawayUdid}\n` }, - }, - { match: simctl("boot", throwawayUdid) }, - { match: simctl("bootstatus", throwawayUdid, "-b") }, - { match: simctl("listapps", throwawayUdid) }, - { match: simctl("shutdown", throwawayUdid) }, - { - match: simctl("clone", throwawayUdid, name, `${deviceRoot}/sources`), - result: { code: 0, stderr: "", stdout: `${seedUdid}\n` }, - }, - { match: simctl("delete", throwawayUdid) }, - ], + steps: throwawaySeedSteps(), }, ]; for (const scenario of cases) { diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 906230f9d..2effbd746 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -218,6 +218,7 @@ export class IosSimctlDriver implements Driver { idGenerator: options.idGenerator, instanceId: options.instanceId, logger: options.logger, + logsRoot: options.logsRoot, marks: this.#marks, ownsDeviceSet: rootOptions !== undefined, seedTurns: this.#seedTurns, diff --git a/src/drivers/ios/seeds.ts b/src/drivers/ios/seeds.ts index 3d312130e..8fc4a9083 100644 --- a/src/drivers/ios/seeds.ts +++ b/src/drivers/ios/seeds.ts @@ -43,6 +43,7 @@ interface SeedsOptions { readonly idGenerator: IdGenerator; readonly instanceId: string; readonly logger: Logger | undefined; + readonly logsRoot: string | undefined; readonly marks: DeviceMarks; readonly ownsDeviceSet: boolean; readonly seedTurns: SeedTurns; @@ -61,6 +62,7 @@ export class Seeds { readonly #idGenerator: IdGenerator; readonly #instanceId: string; readonly #logger: Logger | undefined; + readonly #logsRoot: string | undefined; readonly #marks: DeviceMarks; readonly #ownsDeviceSet: boolean; readonly #seedMakes = new Map>(); @@ -81,6 +83,7 @@ export class Seeds { this.#idGenerator = options.idGenerator; this.#instanceId = options.instanceId; this.#logger = options.logger; + this.#logsRoot = options.logsRoot; this.#marks = options.marks; this.#ownsDeviceSet = options.ownsDeviceSet; this.#seedTurns = options.seedTurns; @@ -310,6 +313,9 @@ export class Seeds { sourceId, specKey, }); + let throwaway: string | undefined; + let keepRow = false; + let seedClone: string | undefined; try { await this.#ensureSourcesSet(); const created = await this.#simctl.createSimulator( @@ -319,28 +325,41 @@ export class Seeds { resolved.deviceType.identifier, resolved.runtime.identifier, ], - { destination: this.#sourcesSet, source: this.#sourcesSet }, + {}, ); - const udid = created.stdout.trim(); - this.#sources.setUdid(sourceId, udid); + throwaway = created.stdout.trim(); + this.#sources.setThrowaway(sourceId, throwaway); try { - await this.#boot.bootAndWait(udid, sourceId, this.#fullBootTimeoutMs, this.#sourcesSet); + await this.#boot.bootAndWait(throwaway, sourceId, this.#fullBootTimeoutMs); } catch (error: unknown) { - await this.#deleteSeedSimulator(udid); // why: a seed that ran out of boot time is a boot timeout, as an Android seed's is. if (error instanceof BootTimeoutError) throw error; - throw new DriverCrashError(`seed ${udid} did not boot: ${errorMessage(error)}`); + throw new DriverCrashError(`seed ${throwaway} did not boot: ${errorMessage(error)}`); } - try { - await this.#simctl.shutdown(udid, this.#sourcesSet); - } catch (error: unknown) { - await this.#deleteSeedSimulator(udid); - throw error; - } - this.#sources.markReady(sourceId, await this.#sizeOf(udid)); - return { sourceId, udid, runtimeBuild: resolved.runtime.build }; + await this.#simctl.shutdown(throwaway); + const cloned = await this.#simctl.createSimulator( + ["clone", throwaway, `simlock-seed-${sourceId}`, this.#sourcesSet], + { destination: this.#sourcesSet }, + ); + seedClone = cloned.stdout.trim(); + this.#sources.setUdid(sourceId, seedClone); + const done = throwaway; + throwaway = undefined; + keepRow = true; + await this.#deleteThrowaway(done, false); + keepRow = false; + this.#sources.markReady(sourceId, await this.#sizeOf(seedClone)); + return { sourceId, udid: seedClone, runtimeBuild: resolved.runtime.build }; } catch (error: unknown) { - this.#sources.deleteRow(sourceId); + if (seedClone !== undefined) + await this.#deleteSeedSimulator(seedClone).catch(() => undefined); + if (throwaway !== undefined) { + keepRow = !(await this.#deleteThrowaway(throwaway, true).then( + () => true, + () => false, + )); + } + if (!keepRow) this.#sources.deleteRow(sourceId); throw error; } } @@ -361,6 +380,7 @@ export class Seeds { async #removeLeftover(row: SourceRow): Promise { try { if (row.udid !== undefined) await this.#deleteSeedSimulator(row.udid); + if (row.throwawayUdid !== undefined) await this.#deleteThrowaway(row.throwawayUdid, true); this.#sources.deleteRow(row.sourceId); } catch (error: unknown) { this.#logger?.warn( @@ -381,8 +401,29 @@ export class Seeds { async #deleteSeedSimulator(udid: string): Promise { await this.#simctl.bestEffortShutdown(udid, this.#sourcesSet); + await this.#deleteIn(udid, this.#sourcesSet); + } + + /** why: ADR 0076 §1: the throwaway lives in the device set and is deleted only through the `making` row that names it (ADR 0001 §6), with its log folder, which `simctl delete` leaves behind. */ + async #deleteThrowaway(udid: string, shutdownFirst: boolean): Promise { + if (shutdownFirst) await this.#simctl.bestEffortShutdown(udid); + await this.#deleteIn(udid, undefined); + await this.#deleteLogFolder(udid); + } + + async #deleteLogFolder(udid: string): Promise { + if (this.#logsRoot === undefined) return; + const path = join(this.#logsRoot, udid); + try { + await this.#filesystem.rm(path); + } catch (error: unknown) { + this.#logger?.warn(`could not delete log folder ${path}: ${errorMessage(error)}`); + } + } + + async #deleteIn(udid: string, set: string | undefined): Promise { const args = ["delete", udid]; - const outcome = await this.#simctl.invoke(args, COMMAND_TIMEOUT_MS, this.#sourcesSet); + const outcome = await this.#simctl.invoke(args, COMMAND_TIMEOUT_MS, set); // why: a seed deleted by hand is already gone, and its row must still be dropped. if (outcome.kind === "finished" && unknownDevice(outcome.result)) return; this.#simctl.checked(args, COMMAND_TIMEOUT_MS, outcome); diff --git a/src/drivers/ios/source-data.ts b/src/drivers/ios/source-data.ts index 2c47f4a49..684ba18f7 100644 --- a/src/drivers/ios/source-data.ts +++ b/src/drivers/ios/source-data.ts @@ -29,9 +29,11 @@ export const iosSourceDataOwner: SqliteSchemaOwner = { OR (newer.created_at = ios_source_data.created_at AND newer.source_id > ios_source_data.source_id))); CREATE UNIQUE INDEX ios_source_data_ready_seed ON ios_source_data (spec_key) WHERE kind = 'seed' AND state = 'ready';`, + // why: ADR 0076: the throwaway a seed was copied from, kept so a restart mid-make can delete it through the row. + "ALTER TABLE ios_source_data ADD COLUMN throwaway_udid TEXT", ], name: "ios-source-data", - version: 2, + version: 3, }; export interface NewSourceRow { @@ -52,6 +54,7 @@ export interface SourceRow { readonly sourceId: string; readonly kind: "seed" | "baseline"; readonly udid: string | undefined; + readonly throwawayUdid: string | undefined; readonly deviceTypeId: string; readonly runtimeId: string; readonly runtimeBuild: string | undefined; @@ -104,6 +107,12 @@ export class IosSourceTable { .run(udid, sourceId); } + setThrowaway(sourceId: string, udid: string): void { + this.#database + .prepare("UPDATE ios_source_data SET throwaway_udid = ? WHERE source_id = ?") + .run(udid, sourceId); + } + markReady(sourceId: string, sizeBytes: number | undefined): void { this.#database .prepare("UPDATE ios_source_data SET state = 'ready', size_bytes = ? WHERE source_id = ?") @@ -162,7 +171,7 @@ export class IosSourceTable { #rows(where: string, parameters: readonly (string | number)[]): readonly SourceRow[] { return this.#database .prepare( - `SELECT source_id, kind, udid, device_type_id, runtime_id, runtime_build, model, os_version, + `SELECT source_id, kind, udid, throwaway_udid, device_type_id, runtime_id, runtime_build, model, os_version, state, maker, size_bytes FROM ios_source_data ${where}`, ) .all(...parameters) @@ -170,6 +179,7 @@ export class IosSourceTable { sourceId: row["source_id"] as string, kind: row["kind"] as "seed" | "baseline", udid: (row["udid"] as string | null) ?? undefined, + throwawayUdid: (row["throwaway_udid"] as string | null) ?? undefined, deviceTypeId: row["device_type_id"] as string, runtimeId: row["runtime_id"] as string, runtimeBuild: (row["runtime_build"] as string | null) ?? undefined, diff --git a/src/drivers/ios/test-index.ts b/src/drivers/ios/test-index.ts index 6600d8e57..e4339e737 100644 --- a/src/drivers/ios/test-index.ts +++ b/src/drivers/ios/test-index.ts @@ -362,3 +362,23 @@ export const prepareFull = { mode: "full", purpose: "prepare" } as const; export const throwawayUdid = "00000000-0000-0000-0000-0000000000bb"; export const logsRoot = "/Logs/CoreSimulator"; + +/** why: the calls that make a seed from a throwaway under the `simlock` set, in order; a test starts its script with these, after the catalog read. */ +export function throwawaySeedSteps(seed: string = seedUdid) { + const name = "simlock-seed-device-1"; + return [ + { + match: simctl("create", name, driverData.deviceTypeId, driverData.runtimeId), + result: { code: 0, stderr: "", stdout: `${throwawayUdid}\n` }, + }, + { match: simctl("boot", throwawayUdid) }, + { match: simctl("bootstatus", throwawayUdid, "-b") }, + { match: simctl("listapps", throwawayUdid) }, + { match: simctl("shutdown", throwawayUdid) }, + { + match: simctl("clone", throwawayUdid, name, `${deviceRoot}/sources`), + result: { code: 0, stderr: "", stdout: `${seed}\n` }, + }, + { match: simctl("delete", throwawayUdid) }, + ]; +} From 98fd35a82b43523b0ccbe16c949bf2b140e2bc22 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 20:44:10 +0100 Subject: [PATCH 03/11] test: a seed's throwaway under the default set carries marks and DeviceHub settings (#1569) --- src/drivers/ios/index-seed-throwaway.test.ts | 114 +++++++++++++++---- 1 file changed, 90 insertions(+), 24 deletions(-) diff --git a/src/drivers/ios/index-seed-throwaway.test.ts b/src/drivers/ios/index-seed-throwaway.test.ts index 3235774c8..88afca5ae 100644 --- a/src/drivers/ios/index-seed-throwaway.test.ts +++ b/src/drivers/ios/index-seed-throwaway.test.ts @@ -2,16 +2,19 @@ import { afterEach, describe, expect, it } from "vitest"; import { FakeClock, MemoryFilesystem, ScriptedProcessRunner } from "../../ports/index.js"; import { IosSimctlDriver } from "./index.js"; import { memorySourceDatabase } from "./testing.js"; -import { deviceRoot, driverData, instanceId, plantManagedDevice } from "./test-slim.js"; +import { + deviceHubEdit, + deviceRoot, + driverData, + instanceId, + plantManagedDevice, +} from "./test-slim.js"; import { listFixture, - listInvocation, logsRoot, scopedRunners, seedUdid, - sourcesSimctl, spec, - throwawaySeedSteps, throwawayUdid, } from "./test-index.js"; @@ -19,34 +22,97 @@ afterEach(() => { scopedRunners.length = 0; }); +const copyUdid = "00000000-0000-0000-0000-000000000002"; +const name = "simlock-seed-device-1"; +const coreSimulatorRoot = "/CoreSim"; + +interface World { + readonly label: string; + readonly config: Record; + readonly devicesDir: string; + readonly sourcesSet: string; + readonly isDefault: boolean; +} + +const worlds: readonly World[] = [ + { + config: { deviceRoot }, + devicesDir: deviceRoot, + isDefault: false, + label: "simlock set", + sourcesSet: `${deviceRoot}/sources`, + }, + { + config: { deviceSet: "default" }, + devicesDir: `${coreSimulatorRoot}/Devices`, + isDefault: true, + label: "default set", + sourcesSet: "/home/.simlock/devices/ios-sources", + }, +]; + +function simctlIn(world: World, set: string | undefined, ...args: readonly string[]) { + const scoped = set ?? (world.isDefault ? undefined : world.devicesDir); + return { + args: scoped === undefined ? ["simctl", ...args] : ["simctl", "--set", scoped, ...args], + command: "xcrun", + }; +} + describe("IosSimctlDriver seed throwaway", () => { it("the first provision of a kind makes its seed from a throwaway", async () => { - const copyUdid = "00000000-0000-0000-0000-000000000002"; - const cases = [ - { - label: "simlock set", - steps: throwawaySeedSteps(), - }, - ]; - for (const scenario of cases) { + for (const world of worlds) { + const step = (match: { command: string; args: readonly string[] }, stdout?: string) => ({ + match, + ...(stdout === undefined ? {} : { result: { code: 0, stderr: "", stdout } }), + }); + const inSet = (...args: string[]) => simctlIn(world, undefined, ...args); + const hub = (command: string) => + world.isDefault ? deviceHubEdit(command).map((match) => ({ match })) : []; const database = await memorySourceDatabase(); + const markedAtBoot: Promise[] = []; + const filesystem = new MemoryFilesystem(); const runner = new ScriptedProcessRunner([ - { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, - ...scenario.steps, + step( + world.isDefault + ? { args: ["simctl", "list", "-j", "devicetypes", "runtimes"], command: "xcrun" } + : inSet("list", "-j", "devicetypes", "runtimes"), + listFixture, + ), + step( + inSet("create", name, driverData.deviceTypeId, driverData.runtimeId), + `${throwawayUdid}\n`, + ), + ...hub(`Set :DevicePreferences:${throwawayUdid}:pasteboardSyncEnabled false`), { - match: sourcesSimctl("clone", seedUdid, driverData.name, deviceRoot), - result: { code: 0, stderr: "", stdout: `${copyUdid}\n` }, + match: inSet("boot", throwawayUdid), + onSpawn: () => { + markedAtBoot.push( + filesystem.exists(`${world.devicesDir}/${throwawayUdid}/simlock-mark.json`), + ); + }, }, + step(inSet("bootstatus", throwawayUdid, "-b")), + step(inSet("listapps", throwawayUdid)), + step(inSet("shutdown", throwawayUdid)), + step(inSet("clone", throwawayUdid, name, world.sourcesSet), `${seedUdid}\n`), + step(inSet("delete", throwawayUdid)), + ...hub(`Delete :DevicePreferences:${throwawayUdid}`), + step( + simctlIn(world, world.sourcesSet, "clone", seedUdid, driverData.name, world.devicesDir), + `${copyUdid}\n`, + ), ]); scopedRunners.push(runner); - const filesystem = new MemoryFilesystem(); - await plantManagedDevice(filesystem); - await filesystem.mkdirp(`${deviceRoot}/${copyUdid}/data`); + if (!world.isDefault) await plantManagedDevice(filesystem); + await filesystem.mkdirp(`${world.devicesDir}/${throwawayUdid}/data`); + await filesystem.mkdirp(`${world.devicesDir}/${copyUdid}/data`); await filesystem.mkdirp(`${logsRoot}/${throwawayUdid}`); const driver = await IosSimctlDriver.create({ clock: new FakeClock(), + coreSimulatorRoot, database, - driverConfig: { deviceRoot }, + driverConfig: world.config, filesystem, idGenerator: { generate: () => "device-1" }, instanceId, @@ -55,16 +121,16 @@ describe("IosSimctlDriver seed throwaway", () => { simlockHome: "/home/.simlock", }); - await expect(driver.provision(spec), scenario.label).resolves.toMatchObject({ + await expect(driver.provision(spec), world.label).resolves.toMatchObject({ deviceId: copyUdid, }); - expect(runner.calls.length, scenario.label).toBe(scenario.steps.length + 2); + expect(await Promise.all(markedAtBoot), world.label).toEqual([world.isDefault]); expect( database.prepare("SELECT state, udid, throwaway_udid FROM ios_source_data").all(), - scenario.label, + world.label, ).toEqual([{ state: "ready", throwaway_udid: throwawayUdid, udid: seedUdid }]); - await expect(filesystem.exists(`${logsRoot}/${throwawayUdid}`), scenario.label).resolves.toBe( + await expect(filesystem.exists(`${logsRoot}/${throwawayUdid}`), world.label).resolves.toBe( false, ); } From 2eb80b93f26e5e7b00e6d729600f27528de9c7a7 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 20:44:32 +0100 Subject: [PATCH 04/11] feat(ios): under the default set a seed's throwaway carries marks and DeviceHub settings (#1569) --- src/drivers/ios/index-device-set.test.ts | 9 +++++---- src/drivers/ios/index.ts | 1 + src/drivers/ios/seeds.ts | 10 ++++++++++ 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/drivers/ios/index-device-set.test.ts b/src/drivers/ios/index-device-set.test.ts index f5868b51f..c0eea0a21 100644 --- a/src/drivers/ios/index-device-set.test.ts +++ b/src/drivers/ios/index-device-set.test.ts @@ -115,9 +115,9 @@ describe("IosSimctlDriver device set", () => { : ["simctl", ...step.args]; const runner = new ScriptedProcessRunner( steps.flatMap((step) => [ - ...(!scoped && step.args[0] === "boot" && step.args[1] === driverData.udid + ...(!scoped && step.args[0] === "boot" && step.args[1] !== seedUdid ? deviceHubEdit( - `Set :DevicePreferences:${driverData.udid}:pasteboardSyncEnabled false`, + `Set :DevicePreferences:${String(step.args[1])}:pasteboardSyncEnabled false`, ).map((match) => ({ match })) : []), { @@ -126,8 +126,8 @@ describe("IosSimctlDriver device set", () => { ? {} : { result: { code: 0, stderr: "", stdout: step.stdout } }), }, - ...(!scoped && step.args[0] === "delete" && step.args[1] === driverData.udid - ? deviceHubEdit(`Delete :DevicePreferences:${driverData.udid}`).map((match) => ({ + ...(!scoped && step.args[0] === "delete" + ? deviceHubEdit(`Delete :DevicePreferences:${String(step.args[1])}`).map((match) => ({ match, })) : []), @@ -135,6 +135,7 @@ describe("IosSimctlDriver device set", () => { ); const filesystem = new MemoryFilesystem(); await plantDevice(filesystem, devicesDir); + await filesystem.mkdirp(`${devicesDir}/${throwawayUdid}/data`); if (scoped) await plantManagedDevice(filesystem); const driver = await IosSimctlDriver.create({ database: await memorySourceDatabase(), diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 2effbd746..2f6443a86 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -212,6 +212,7 @@ export class IosSimctlDriver implements Driver { clock: options.clock, slimBoot: this.#slimBoot, database: options.database, + deviceHub: this.#deviceHub, deviceRoot, filesystem: options.filesystem, fullBootTimeoutMs: this.#fullBootTimeoutMs, diff --git a/src/drivers/ios/seeds.ts b/src/drivers/ios/seeds.ts index 8fc4a9083..97f7b0dd8 100644 --- a/src/drivers/ios/seeds.ts +++ b/src/drivers/ios/seeds.ts @@ -12,6 +12,7 @@ import type { Clock, Filesystem, IdGenerator, Logger } from "../../ports/index.j import { errorMessage } from "./command-run.js"; import { SeedTurns } from "./seed-turns.js"; import { COMMAND_TIMEOUT_MS, Simctl, unknownDevice } from "./simctl.js"; +import type { DeviceHubPreferences } from "./devicehub.js"; import { DeviceMarks } from "./marks.js"; import type { SlimBoot } from "./slim-boot.js"; import type { SimulatorBoot } from "./simulator-boot.js"; @@ -37,6 +38,7 @@ interface SeedsOptions { readonly clock: Clock; readonly slimBoot: SlimBoot; readonly database: SqliteDatabase; + readonly deviceHub: DeviceHubPreferences; readonly deviceRoot: string; readonly filesystem: Filesystem; readonly fullBootTimeoutMs: number; @@ -56,6 +58,7 @@ export class Seeds { readonly #boot: SimulatorBoot; readonly #clock: Clock; readonly #slimBoot: SlimBoot; + readonly #deviceHub: DeviceHubPreferences; readonly #deviceRoot: string; readonly #filesystem: Filesystem; readonly #fullBootTimeoutMs: number; @@ -77,6 +80,7 @@ export class Seeds { this.#boot = options.boot; this.#clock = options.clock; this.#slimBoot = options.slimBoot; + this.#deviceHub = options.deviceHub; this.#deviceRoot = options.deviceRoot; this.#filesystem = options.filesystem; this.#fullBootTimeoutMs = options.fullBootTimeoutMs; @@ -329,6 +333,11 @@ export class Seeds { ); throwaway = created.stdout.trim(); this.#sources.setThrowaway(sourceId, throwaway); + if (!this.#ownsDeviceSet) { + // why: ADR 0048: in Xcode's set a simulator is Simlock's only by its mark, and a booted one keeps the clipboard sync it booted with. + await this.#marks.writeMark(throwaway); + await this.#deviceHub.disablePasteboardSync(throwaway); + } try { await this.#boot.bootAndWait(throwaway, sourceId, this.#fullBootTimeoutMs); } catch (error: unknown) { @@ -408,6 +417,7 @@ export class Seeds { async #deleteThrowaway(udid: string, shutdownFirst: boolean): Promise { if (shutdownFirst) await this.#simctl.bestEffortShutdown(udid); await this.#deleteIn(udid, undefined); + if (!this.#ownsDeviceSet) await this.#deviceHub.removePasteboardPreference(udid); await this.#deleteLogFolder(udid); } From 07abda9441c3219cfd5a1b0a736c0e0fd3905775 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 20:45:14 +0100 Subject: [PATCH 05/11] test: a failed seed make deletes its throwaway and a stray log folder never fails it (#1569) --- src/drivers/ios/index-seed-throwaway.test.ts | 120 +++++++++++++++++++ src/drivers/ios/test-index.ts | 15 ++- 2 files changed, 134 insertions(+), 1 deletion(-) diff --git a/src/drivers/ios/index-seed-throwaway.test.ts b/src/drivers/ios/index-seed-throwaway.test.ts index 88afca5ae..696bac931 100644 --- a/src/drivers/ios/index-seed-throwaway.test.ts +++ b/src/drivers/ios/index-seed-throwaway.test.ts @@ -10,11 +10,15 @@ import { plantManagedDevice, } from "./test-slim.js"; import { + RecordingLogger, listFixture, logsRoot, scopedRunners, + listInvocation, seedUdid, + sourcesSimctl, spec, + throwawaySeedSteps, throwawayUdid, } from "./test-index.js"; @@ -134,5 +138,121 @@ describe("IosSimctlDriver seed throwaway", () => { false, ); } + + const whole = throwawaySeedSteps(); + const [create, boot, bootstatus, listapps, shutdown, clone, remove] = whole; + const failed = { code: 1, stderr: "boom", stdout: "" }; + const copy = { + match: sourcesSimctl("clone", seedUdid, driverData.name, deviceRoot), + result: { code: 0, stderr: "", stdout: `${copyUdid}\n` }, + }; + class BrokenLogRemoval extends MemoryFilesystem { + override async rm(path: string): Promise { + if (path.startsWith(logsRoot)) throw new Error("denied"); + await super.rm(path); + } + } + const failures = [ + { + label: "boot fails", + steps: [create, boot, { ...bootstatus, result: failed }, shutdown, remove], + error: /did not boot/, + rows: [], + logFolder: false, + warnings: [], + }, + { + label: "clone fails", + steps: [ + create, + boot, + bootstatus, + listapps, + shutdown, + { ...clone, result: failed }, + shutdown, + remove, + ], + error: /boom/, + rows: [], + logFolder: false, + warnings: [], + }, + { + label: "throwaway delete fails", + steps: [ + create, + boot, + bootstatus, + listapps, + shutdown, + clone, + { ...remove, result: failed }, + { match: sourcesSimctl("shutdown", seedUdid) }, + { match: sourcesSimctl("delete", seedUdid) }, + ], + error: /boom/, + rows: [{ state: "making", throwaway_udid: throwawayUdid, udid: seedUdid }], + logFolder: true, + warnings: [], + }, + { + label: "log folder delete fails", + steps: [...whole, copy], + filesystem: new BrokenLogRemoval(), + rows: [{ state: "ready", throwaway_udid: throwawayUdid, udid: seedUdid }], + logFolder: true, + warnings: [`could not delete log folder ${logsRoot}/${throwawayUdid}: denied`], + }, + { + label: "log folder absent", + steps: [...whole, copy], + absent: true, + rows: [{ state: "ready", throwaway_udid: throwawayUdid, udid: seedUdid }], + logFolder: false, + warnings: [], + }, + ]; + for (const failure of failures) { + const database = await memorySourceDatabase(); + const logger = new RecordingLogger(); + const filesystem = failure.filesystem ?? new MemoryFilesystem(); + const runner = new ScriptedProcessRunner([ + { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, + ...failure.steps, + ]); + scopedRunners.push(runner); + await plantManagedDevice(filesystem); + await filesystem.mkdirp(`${deviceRoot}/${copyUdid}/data`); + if (failure.absent !== true) await filesystem.mkdirp(`${logsRoot}/${throwawayUdid}`); + const driver = await IosSimctlDriver.create({ + clock: new FakeClock(), + database, + driverConfig: { deviceRoot }, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + logger, + logsRoot, + processRunner: runner, + simlockHome: "/home/.simlock", + }); + + const outcome = await driver.provision(spec).then( + () => undefined, + (error: unknown) => error as Error, + ); + + if (failure.error === undefined) expect(outcome, failure.label).toBeUndefined(); + else expect(outcome?.message, failure.label).toMatch(failure.error); + expect( + database.prepare("SELECT state, udid, throwaway_udid FROM ios_source_data").all(), + failure.label, + ).toEqual(failure.rows); + await expect(filesystem.exists(`${logsRoot}/${throwawayUdid}`), failure.label).resolves.toBe( + failure.logFolder, + ); + expect(logger.warnings, failure.label).toEqual(failure.warnings); + } }); }); diff --git a/src/drivers/ios/test-index.ts b/src/drivers/ios/test-index.ts index e4339e737..0eacab7df 100644 --- a/src/drivers/ios/test-index.ts +++ b/src/drivers/ios/test-index.ts @@ -1,5 +1,6 @@ import { readFileSync } from "node:fs"; import { + type ScriptedProcessExpectation, ScriptedProcessRunner, type SqliteDatabase, FakeClock, @@ -364,7 +365,19 @@ export const throwawayUdid = "00000000-0000-0000-0000-0000000000bb"; export const logsRoot = "/Logs/CoreSimulator"; /** why: the calls that make a seed from a throwaway under the `simlock` set, in order; a test starts its script with these, after the catalog read. */ -export function throwawaySeedSteps(seed: string = seedUdid) { +type ScriptedStep = Pick; + +export function throwawaySeedSteps( + seed: string = seedUdid, +): [ + ScriptedStep, + ScriptedStep, + ScriptedStep, + ScriptedStep, + ScriptedStep, + ScriptedStep, + ScriptedStep, +] { const name = "simlock-seed-device-1"; return [ { From c0e9c785458d8742b7cd02f63ef47fa1a94e33c2 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 20:45:37 +0100 Subject: [PATCH 06/11] test: listManaged leaves out a throwaway a making row names (#1569) --- src/drivers/ios/index-seed-throwaway.test.ts | 73 +++++++++++++++++++- src/drivers/ios/testing.ts | 2 + 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/src/drivers/ios/index-seed-throwaway.test.ts b/src/drivers/ios/index-seed-throwaway.test.ts index 696bac931..b4b299f1d 100644 --- a/src/drivers/ios/index-seed-throwaway.test.ts +++ b/src/drivers/ios/index-seed-throwaway.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it } from "vitest"; import { FakeClock, MemoryFilesystem, ScriptedProcessRunner } from "../../ports/index.js"; import { IosSimctlDriver } from "./index.js"; -import { memorySourceDatabase } from "./testing.js"; +import { memorySourceDatabase, plantSource } from "./testing.js"; import { deviceHubEdit, deviceRoot, @@ -255,4 +255,75 @@ describe("IosSimctlDriver seed throwaway", () => { expect(logger.warnings, failure.label).toEqual(failure.warnings); } }); + + it("listManaged leaves out a throwaway a making row names", async () => { + const runtime = "com.apple.CoreSimulator.SimRuntime.iOS-26-5"; + const own = "00000000-0000-0000-0000-0000000000e1"; + const listed = JSON.stringify({ + devices: { + [runtime]: [throwawayUdid, own].map((udid) => ({ + dataPath: `/x/${udid}/data`, + name: udid, + state: "Shutdown", + udid, + })), + }, + }); + const cases = [ + { label: "simlock set, a making row", world: worlds[0]!, state: "making", left: [own] }, + { label: "default set, a making row", world: worlds[1]!, state: "making", left: [own] }, + { + label: "simlock set, a ready row", + world: worlds[0]!, + state: "ready", + left: [throwawayUdid, own], + }, + ] as const; + for (const { label, left, state, world } of cases) { + const database = plantSource(await memorySourceDatabase(), { + deviceTypeId: driverData.deviceTypeId, + runtimeId: driverData.runtimeId, + state, + throwawayUdid, + udid: seedUdid, + }); + const filesystem = new MemoryFilesystem(); + if (!world.isDefault) await plantManagedDevice(filesystem); + for (const udid of [throwawayUdid, own]) { + await filesystem.mkdirp(`${world.devicesDir}/${udid}/data`); + if (world.isDefault) { + const mark = JSON.stringify({ instanceId, token: "t", udid }); + await filesystem.writeFileAtomic(`${world.devicesDir}/${udid}/simlock-mark.json`, mark); + await filesystem.writeFileAtomic( + `${world.devicesDir}/${udid}/data/simlock-mark.json`, + mark, + ); + } + } + const runner = new ScriptedProcessRunner([ + { + match: simctlIn(world, undefined, "list", "-j", "devices"), + result: { code: 0, stderr: "", stdout: listed }, + }, + ]); + scopedRunners.push(runner); + const driver = await IosSimctlDriver.create({ + clock: new FakeClock(), + coreSimulatorRoot, + database, + driverConfig: world.config, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + processRunner: runner, + simlockHome: "/home/.simlock", + }); + + const reality = await driver.listManaged(); + + expect(reality.devices.map((device) => device.deviceId).sort(), label).toEqual( + [...left].sort(), + ); + } + }); }); diff --git a/src/drivers/ios/testing.ts b/src/drivers/ios/testing.ts index 2d10c733e..6e074517e 100644 --- a/src/drivers/ios/testing.ts +++ b/src/drivers/ios/testing.ts @@ -17,6 +17,7 @@ export interface PlantedSource { readonly runtimeId: string; readonly sizeBytes?: number; readonly state?: "making" | "ready"; + readonly throwawayUdid?: string; readonly udid?: string; } @@ -38,6 +39,7 @@ export function plantSource(database: SqliteDatabase, source: PlantedSource): Sq specKey: `${source.deviceTypeId}\u0000${source.runtimeId}`, }); if (source.udid !== undefined) table.setUdid(sourceId, source.udid); + if (source.throwawayUdid !== undefined) table.setThrowaway(sourceId, source.throwawayUdid); if (source.state !== "making") table.markReady(sourceId, source.sizeBytes); return database; } From 680e6ff35ebef9038c4c98a8b23a280eb31a5fd9 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 20:45:47 +0100 Subject: [PATCH 07/11] feat(ios): listManaged leaves out a throwaway a making row names (#1569) --- src/drivers/ios/index.ts | 5 ++++- src/drivers/ios/seeds.ts | 5 +++++ src/drivers/ios/source-data.ts | 9 +++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 2f6443a86..5a5360730 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -472,7 +472,10 @@ export class IosSimctlDriver implements Driver { async listManaged(): Promise { const result = await this.#simctl.run(["list", "-j", "devices"], COMMAND_TIMEOUT_MS); - const listed = parseManagedDevices(JSON.parse(result.stdout) as unknown); + const throwaways = this.#seeds.makingThrowaways(); + const listed = parseManagedDevices(JSON.parse(result.stdout) as unknown).filter( + (device) => !throwaways.has(device.udid), + ); // why: Xcode's set also holds the user's own simulators and other Simlocks'; only a // durable mark naming this instance proves a simulator here is ours. const parsed = diff --git a/src/drivers/ios/seeds.ts b/src/drivers/ios/seeds.ts index 97f7b0dd8..13c2d5cd8 100644 --- a/src/drivers/ios/seeds.ts +++ b/src/drivers/ios/seeds.ts @@ -118,6 +118,11 @@ export class Seeds { ]; } + /** why: a throwaway a `making` row names is the driver's own leftover, deleted through that row (ADR 0001 §6), so it is no leased device and no orphan. */ + makingThrowaways(): ReadonlySet { + return new Set(this.#sources.makingThrowaways()); + } + async saveSource(device: VirtualDriverDevice): Promise<{ sourceId: string; sizeBytes?: number }> { const data = iosDriverData(device); const catalog = await this.#simctl.loadCatalog(); diff --git a/src/drivers/ios/source-data.ts b/src/drivers/ios/source-data.ts index 684ba18f7..674ed8170 100644 --- a/src/drivers/ios/source-data.ts +++ b/src/drivers/ios/source-data.ts @@ -153,6 +153,15 @@ export class IosSourceTable { ]); } + makingThrowaways(): readonly string[] { + return this.#database + .prepare( + "SELECT throwaway_udid FROM ios_source_data WHERE state = 'making' AND throwaway_udid IS NOT NULL", + ) + .all() + .map((row) => row["throwaway_udid"] as string); + } + allUdids(): readonly string[] { return this.#database .prepare("SELECT udid FROM ios_source_data WHERE udid IS NOT NULL") From 64fc83b48aa5eb5b7094232b36304ea86372ecb8 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 20:46:14 +0100 Subject: [PATCH 08/11] test: a restart mid-make deletes the throwaway, its log folder, the seed clone and the row (#1569) --- src/drivers/ios/index-seed-sources.test.ts | 19 +++++- src/drivers/ios/index-seed-throwaway.test.ts | 66 ++++++++++++++++++++ 2 files changed, 83 insertions(+), 2 deletions(-) diff --git a/src/drivers/ios/index-seed-sources.test.ts b/src/drivers/ios/index-seed-sources.test.ts index 4a95236e0..145896e29 100644 --- a/src/drivers/ios/index-seed-sources.test.ts +++ b/src/drivers/ios/index-seed-sources.test.ts @@ -199,11 +199,13 @@ describe("IosSimctlDriver", () => { "the next seed make of a kind destroys this process's own making row of that kind older than 300 s: a row $name", async ({ now, destroyed }) => { const stuckUdid = "00000000-0000-0000-0000-0000000000dd"; + const stuckThrowaway = "00000000-0000-0000-0000-0000000000ee"; const database = plantSource(await memorySourceDatabase(), { deviceTypeId: driverData.deviceTypeId, maker: "device-1", runtimeId: driverData.runtimeId, state: "making", + throwawayUdid: stuckThrowaway, udid: stuckUdid, }); const copyUdid = "00000000-0000-0000-0000-000000000002"; @@ -214,6 +216,8 @@ describe("IosSimctlDriver", () => { ? [ { match: sourcesSimctl("shutdown", stuckUdid) }, { match: sourcesSimctl("delete", stuckUdid) }, + { match: simctl("shutdown", stuckThrowaway) }, + { match: simctl("delete", stuckThrowaway) }, ] : []), ...throwawaySeedSteps(), @@ -227,8 +231,19 @@ describe("IosSimctlDriver", () => { await driver.provision(spec); expect( - runner.calls.filter((call) => call.args[4] === stuckUdid).map((call) => call.args[3]), - ).toEqual(destroyed ? ["shutdown", "delete"] : []); + runner.calls + .filter((call) => [stuckUdid, stuckThrowaway].includes(call.args[4] ?? "")) + .map((call) => `${call.args[3] ?? ""} ${call.args[4] ?? ""}`), + ).toEqual( + destroyed + ? [ + `shutdown ${stuckUdid}`, + `delete ${stuckUdid}`, + `shutdown ${stuckThrowaway}`, + `delete ${stuckThrowaway}`, + ] + : [], + ); expect( database.prepare("SELECT udid FROM ios_source_data WHERE state = 'making'").all(), ).toEqual(destroyed ? [] : [{ udid: stuckUdid }]); diff --git a/src/drivers/ios/index-seed-throwaway.test.ts b/src/drivers/ios/index-seed-throwaway.test.ts index b4b299f1d..d706d7230 100644 --- a/src/drivers/ios/index-seed-throwaway.test.ts +++ b/src/drivers/ios/index-seed-throwaway.test.ts @@ -8,6 +8,7 @@ import { driverData, instanceId, plantManagedDevice, + simctl, } from "./test-slim.js"; import { RecordingLogger, @@ -326,4 +327,69 @@ describe("IosSimctlDriver seed throwaway", () => { ); } }); + + it("a restart mid-make: the first source read deletes the throwaway, its log folder, the seed clone and the row", async () => { + const invalid = { code: 1, stderr: `Invalid device: ${throwawayUdid}`, stdout: "" }; + const cases = [ + { + label: "throwaway only", + udid: undefined, + steps: [ + { match: simctl("shutdown", throwawayUdid) }, + { match: simctl("delete", throwawayUdid) }, + ], + }, + { + label: "throwaway and seed", + udid: seedUdid, + steps: [ + { match: sourcesSimctl("shutdown", seedUdid) }, + { match: sourcesSimctl("delete", seedUdid) }, + { match: simctl("shutdown", throwawayUdid) }, + { match: simctl("delete", throwawayUdid) }, + ], + }, + { + label: "throwaway already gone", + udid: undefined, + steps: [ + { match: simctl("shutdown", throwawayUdid) }, + { match: simctl("delete", throwawayUdid), result: invalid }, + ], + }, + ]; + for (const { label, steps, udid } of cases) { + const database = plantSource(await memorySourceDatabase(), { + deviceTypeId: driverData.deviceTypeId, + runtimeId: driverData.runtimeId, + state: "making", + throwawayUdid, + ...(udid === undefined ? {} : { udid }), + }); + const runner = new ScriptedProcessRunner(steps); + scopedRunners.push(runner); + const filesystem = new MemoryFilesystem(); + await plantManagedDevice(filesystem); + await filesystem.mkdirp(`${logsRoot}/${throwawayUdid}`); + const driver = await IosSimctlDriver.create({ + clock: new FakeClock(), + database, + driverConfig: { deviceRoot }, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + logsRoot, + processRunner: runner, + simlockHome: "/home/.simlock", + }); + + await expect(driver.listSources(), label).resolves.toEqual([]); + + expect(runner.calls.length, label).toBe(steps.length); + expect(database.prepare("SELECT COUNT(*) AS n FROM ios_source_data").get(), label).toEqual({ + n: 0, + }); + await expect(filesystem.exists(`${logsRoot}/${throwawayUdid}`), label).resolves.toBe(false); + } + }); }); From c2a18114626e1a46fccd55974d3f25e7ff3e0f54 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 20:46:35 +0100 Subject: [PATCH 09/11] test: baseline.save deletes the saved-from lease's log folder (#1569) --- src/drivers/ios/index-seed-throwaway.test.ts | 77 ++++++++++++++++++-- 1 file changed, 71 insertions(+), 6 deletions(-) diff --git a/src/drivers/ios/index-seed-throwaway.test.ts b/src/drivers/ios/index-seed-throwaway.test.ts index d706d7230..7248f39d6 100644 --- a/src/drivers/ios/index-seed-throwaway.test.ts +++ b/src/drivers/ios/index-seed-throwaway.test.ts @@ -27,6 +27,13 @@ afterEach(() => { scopedRunners.length = 0; }); +class BrokenLogRemoval extends MemoryFilesystem { + override async rm(path: string): Promise { + if (path.startsWith(logsRoot)) throw new Error("denied"); + await super.rm(path); + } +} + const copyUdid = "00000000-0000-0000-0000-000000000002"; const name = "simlock-seed-device-1"; const coreSimulatorRoot = "/CoreSim"; @@ -147,12 +154,6 @@ describe("IosSimctlDriver seed throwaway", () => { match: sourcesSimctl("clone", seedUdid, driverData.name, deviceRoot), result: { code: 0, stderr: "", stdout: `${copyUdid}\n` }, }; - class BrokenLogRemoval extends MemoryFilesystem { - override async rm(path: string): Promise { - if (path.startsWith(logsRoot)) throw new Error("denied"); - await super.rm(path); - } - } const failures = [ { label: "boot fails", @@ -392,4 +393,68 @@ describe("IosSimctlDriver seed throwaway", () => { await expect(filesystem.exists(`${logsRoot}/${throwawayUdid}`), label).resolves.toBe(false); } }); + + it("baseline.save deletes the saved-from lease's log folder", async () => { + const baselineName = "simlock-baseline-device-1"; + const leaseLogs = `${logsRoot}/${driverData.udid}`; + const clone = simctl("clone", driverData.udid, baselineName, `${deviceRoot}/sources`); + const cloneUdid = "00000000-0000-0000-0000-0000000000cc"; + const cases = [ + { label: "present", plant: true, clone: "ok", logs: false, warnings: [] }, + { label: "absent", plant: false, clone: "ok", logs: false, warnings: [] }, + { + label: "delete fails", + plant: true, + clone: "ok", + fs: new BrokenLogRemoval(), + logs: true, + warnings: [`could not delete log folder ${leaseLogs}: denied`], + }, + { label: "clone fails", plant: true, clone: "fails", logs: true, warnings: [] }, + ] as const; + for (const scenario of cases) { + const database = await memorySourceDatabase(); + const logger = new RecordingLogger(); + const filesystem = "fs" in scenario ? scenario.fs : new MemoryFilesystem(); + await plantManagedDevice(filesystem); + await filesystem.mkdirp(`${deviceRoot}/sources/${cloneUdid}`); + if (scenario.plant) await filesystem.mkdirp(leaseLogs); + const runner = new ScriptedProcessRunner([ + { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, + { match: simctl("shutdown", driverData.udid) }, + scenario.clone === "ok" + ? { match: clone, result: { code: 0, stderr: "", stdout: `${cloneUdid}\n` } } + : { match: clone, result: { code: 1, stderr: "no space", stdout: "" } }, + ]); + scopedRunners.push(runner); + const driver = await IosSimctlDriver.create({ + clock: new FakeClock(), + database, + driverConfig: { deviceRoot }, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + logger, + logsRoot, + processRunner: runner, + simlockHome: "/home/.simlock", + }); + + const saved = await driver + .saveSource({ + address: driverData.udid, + deviceId: driverData.udid, + driverData, + physical: false, + }) + .then( + () => "saved", + () => "failed", + ); + + expect(saved, scenario.label).toBe(scenario.clone === "ok" ? "saved" : "failed"); + await expect(filesystem.exists(leaseLogs), scenario.label).resolves.toBe(scenario.logs); + expect(logger.warnings, scenario.label).toEqual(scenario.warnings); + } + }); }); From c510c5b4c1ff35ea4352be54b101ff6e673ef1e2 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 20:46:51 +0100 Subject: [PATCH 10/11] feat(ios): baseline.save deletes the saved-from lease's log folder (#1569) --- src/drivers/ios/AGENTS.md | 2 ++ src/drivers/ios/seeds.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/drivers/ios/AGENTS.md b/src/drivers/ios/AGENTS.md index 51b81be92..fa28a8707 100644 --- a/src/drivers/ios/AGENTS.md +++ b/src/drivers/ios/AGENTS.md @@ -28,6 +28,8 @@ Resolve and boot: Seeds (ADR 0061): - A simulator is a clone of its kind's seed. A seed is known by its `ios_source_data` row, never by name, and lives in the sources set: `sources` in the owned set, an owned root of its own under `default`. It is in no `listManaged` or `simlock simctl list`. +- A seed is made from a throwaway (ADR 0076): `simlock-seed-` is created in the device set, booted once and shut down, cloned unbooted into the sources set, then deleted with its log folder (`logsRoot`), so a seed never names its own folder. Under `default` the throwaway carries this instance's marks and DeviceHub clipboard sync is off before its boot. `saveSource` deletes the saved-from lease's log folder the same way. A log folder that cannot be deleted is logged and the make or save goes on; a throwaway that cannot be deleted fails the make. +- A throwaway is deleted only through the `making` row that names it (`throwaway_udid`): `listManaged` leaves it out, and the first `listSources` of a later process (or the next make of its kind) deletes it with its log folder and the row. - Every clone (a seed's copy, `saveSource`'s own clone, a `provision` with `source`) has its `data/var/db/lsd/com.apple.LaunchServices-*.csstore` deleted before its first boot: it records each app, system apps included, under the original device's folder. A clone whose drop fails is deleted. - Two provisions of a kind make one seed; clones of a seed and its deletion take turns. - A `clone` or `create` waits `ios.simulator.createTimeoutMs`. At the limit it fails but `simctl` runs on: the UDID it later prints is deleted, the seed's deletion waits for it, and one silent 5 minutes more is killed and logged. diff --git a/src/drivers/ios/seeds.ts b/src/drivers/ios/seeds.ts index 13c2d5cd8..7398e0736 100644 --- a/src/drivers/ios/seeds.ts +++ b/src/drivers/ios/seeds.ts @@ -162,6 +162,8 @@ export class Seeds { await this.#dropLaunchServicesDatabase(this.#sourcesSet, cloneUdid); const sizeBytes = await this.#sizeOf(cloneUdid); this.#sources.markReady(sourceId, sizeBytes); + // why: ADR 0076: the lease is destroyed next, and `simctl delete` leaves its log folder behind for the baseline's copies to inherit. + await this.#deleteLogFolder(data.udid); return { sourceId, ...(sizeBytes === undefined ? {} : { sizeBytes }) }; } catch (error: unknown) { if (cloneUdid !== undefined && cloneUdid !== "") { From ce017e124c1a1b189671fc284c8df28f9c9297cc Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 16 Nov 2026 20:47:29 +0100 Subject: [PATCH 11/11] test: a seed table's upgrade test follows its owner's version (#1569) --- src/daemon/state-owners.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/daemon/state-owners.test.ts b/src/daemon/state-owners.test.ts index c6c385faa..fe3963226 100644 --- a/src/daemon/state-owners.test.ts +++ b/src/daemon/state-owners.test.ts @@ -163,7 +163,7 @@ describe("the seed tables' one-ready-seed-per-kind index (#1367)", () => { state.database .prepare("SELECT version FROM schema_versions WHERE owner = ?") .get(owner.name), - ).toEqual({ version: 2 }); + ).toEqual({ version: owner.version }); expect( state.database .prepare(`SELECT source_id, kind, state FROM ${table} ORDER BY source_id`)