diff --git a/docs/internal/EVENTS.md b/docs/internal/EVENTS.md index 9cefb77da..37842c403 100644 --- a/docs/internal/EVENTS.md +++ b/docs/internal/EVENTS.md @@ -160,7 +160,7 @@ left behind (#79), each when there is one. | `memory.pressure-changed` | from, to (`none`, `warming-paused`, `new-devices-paused`), cause (the new step's reading: trigger `level` or `floor`, availablePercent, level on macOS, floorPercent for a floor trigger; absent to `none`) | a worker's memory pressure step changed: once per change, never per reading; no usable reading drops the step at once (ADR 0068 §5) | MemoryPressureTracker | implemented | | `cleanup.executed` | rule name, action, target, reason | cleanup executor committed a proposed action | CleanupExecutor | implemented | | `doctor.reconciled` | drift findings | daemon reconciliation completed | Doctor | implemented | -| `driver.root-rejected` | platform, root path, reason (not-absolute/missing-marker/invalid-marker/wrong-instance/symlink/wrong-owner/wrong-permissions/non-empty-unowned-root/unreadable/invalid-device-set/device-set-changed) | a driver's device root failed ownership validation at startup, or (iOS) `drivers.ios.deviceSet` was not `simlock` or `default`, conflicted with `drivers.ios.deviceRoot` or with `ios.simulator.headless: false`, or was switched with simulators left in the set being given up (ADR 0048; `root` is then the configured value or the set holding them), so that platform's driver did not start | DaemonServer | implemented | +| `driver.root-rejected` | platform, root path, reason (not-absolute/missing-marker/invalid-marker/wrong-instance/symlink/wrong-owner/wrong-permissions/non-empty-unowned-root/unreadable/invalid-device-set/device-set-changed/sources-path-unfit) | a driver's device root failed ownership validation at startup, or (iOS) `drivers.ios.deviceSet` was not `simlock` or `default`, conflicted with `drivers.ios.deviceRoot` or with `ios.simulator.headless: false`, or was switched with simulators left in the set being given up (ADR 0048; `root` is then the configured value or the set holding them), or no iOS sources folder can have the device set's path length (`sources-path-unfit`, ADR 0076; `root` is the device set), so that platform's driver did not start | DaemonServer | implemented | | `driver.adb-server-rejected` | port, reason (occupied/start-failed/invalid-port) | Simlock's own adb server could not be established — the port was occupied by a server it does not own, the server it started never began listening, or the configured port is not usable — so the Android driver did not start | DaemonServer | implemented | ## Fleet (gateway mode) diff --git a/docs/internal/agent-rules/safety.md b/docs/internal/agent-rules/safety.md index 1ac963978..da9eb96eb 100644 --- a/docs/internal/agent-rules/safety.md +++ b/docs/internal/agent-rules/safety.md @@ -12,7 +12,10 @@ never enforce them only inside an individual rule or driver. A driver may also destroy its own sources (ADR 0061 §1): the seeds and baselines it keeps in its sources set, by an id its source table holds. `doctor --purge-orphans` may also delete a simulator in the sources set - that no table row names. Nothing outside the sources set is reached this way. + that no table row names. Nothing outside the sources set is reached this way, + except a seed or `making` row naming an earlier sources folder of this worker + (`/sources` or the `ios-sources` root, ADR 0076 §4); any other path a row + names is left on disk and logged. A physical device is the one kind of registry device Simlock did not create. It is Simlock's to act on only through its enrollment record, diff --git a/e2e/helpers/agent-device.ts b/e2e/helpers/agent-device.ts index 0c7948355..e46961932 100644 --- a/e2e/helpers/agent-device.ts +++ b/e2e/helpers/agent-device.ts @@ -145,7 +145,10 @@ export async function makeAgent( AGENT_DEVICE_STATE_DIR: home, AGENT_DEVICE_DAEMON_AUTH_TOKEN: token.secret, AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1", - ...(options.direct ? { AGENT_DEVICE_DAEMON_BASE_URL: proxyUrl(env) } : {}), + // why: agent-device 0.21.36 refuses a command on a leased connection (`connect proxy`) with no session named (REMOTE_SESSION_REQUIRED); a direct agent names its session on each command. + ...(options.direct + ? { AGENT_DEVICE_DAEMON_BASE_URL: proxyUrl(env) } + : { AGENT_DEVICE_SESSION: name }), }; const background = new Set(); const agent: Agent = { diff --git a/e2e/helpers/ios-device-set.ts b/e2e/helpers/ios-device-set.ts index 3f5b8689b..3e974f095 100644 --- a/e2e/helpers/ios-device-set.ts +++ b/e2e/helpers/ios-device-set.ts @@ -17,6 +17,12 @@ export function iosDeviceSet(home: string): string { return join(home, "devices", "ios"); } +/** why: ADR 0076: the sources folder is `src` and `_` until its path is as long as the device set's. */ +export function iosSourcesFolder(home: string): string { + const base = join(home, "devices", "src"); + return base + "_".repeat(Math.max(0, iosDeviceSet(home).length - base.length)); +} + /** why: a simctl call that never answers would otherwise hold its test until the test's own timeout, which names nothing; the driver gives its own slowest call, the slim readback, the same 120 s. */ const SIMCTL_CALL_TIMEOUT_MS = 120_000; diff --git a/e2e/helpers/lane-home.test.ts b/e2e/helpers/lane-home.test.ts new file mode 100644 index 000000000..26914aa2e --- /dev/null +++ b/e2e/helpers/lane-home.test.ts @@ -0,0 +1,30 @@ +import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; + +import { clearAllButState } from "./lane-home.js"; + +// why: lane-home is a helper file of the e2e lane, outside any module surface; the daemon start and stop that puts a kept seed's rows back runs only on the slow lane, where a server left behind fails a flow far from its cause. +describe("clearAllButState", () => { + it("keeps the adb server's record, which the flow's own daemon needs to adopt a server left running under an attached emulator", async () => { + const home = await mkdtemp(join(tmpdir(), "simlock-lane-home-test-")); + try { + for (const name of [ + "state.db", + "adb-server.json", + "daemon.log", + "history.db", + "admin.token", + ]) { + await writeFile(join(home, name), "x"); + } + + await clearAllButState(home); + + expect((await readdir(home)).sort()).toEqual(["adb-server.json", "state.db"]); + } finally { + await rm(home, { force: true, recursive: true }); + } + }); +}); diff --git a/e2e/helpers/lane-home.ts b/e2e/helpers/lane-home.ts index c0001ac7b..fd98ae1c0 100644 --- a/e2e/helpers/lane-home.ts +++ b/e2e/helpers/lane-home.ts @@ -5,7 +5,13 @@ import { basename, join } from "node:path"; import { DatabaseSync } from "node:sqlite"; import { OWNED_ROOT_MARKER_FILE } from "../../src/core/index.js"; -import { emptyDeviceSet, iosDeviceSet, setDevices, simctlInSet } from "./ios-device-set.js"; +import { + emptyDeviceSet, + iosDeviceSet, + iosSourcesFolder, + setDevices, + simctlInSet, +} from "./ios-device-set.js"; import { removeHome } from "./remove-home.js"; type Row = Record; @@ -90,10 +96,15 @@ export async function restoreKeptSeeds(home: string): Promise { } } +/** why: the driver's record of its adb server is the only handle on a server that outlives its daemon (it stays while an emulator is attached); removed with the rest, the flow's own daemon finds the port listening with no record and refuses Android as `occupied`. */ +const ADB_SERVER_RECORD = "adb-server.json"; + /** why: what the daemon made between a restore's start and stop (its event history, log and admin secret) is not the flow's, and `state.db` holds the tables the seeds go back into. */ export async function clearAllButState(home: string): Promise { for (const entry of await readdir(home)) { - if (KEPT_ENTRIES.has(entry) || entry.startsWith("state.db")) continue; + if (KEPT_ENTRIES.has(entry) || entry === ADB_SERVER_RECORD || entry.startsWith("state.db")) { + continue; + } await removeHome(join(home, entry)); } } @@ -185,7 +196,7 @@ function folderOf(seed: KeptSeed): string { */ async function pruneSources(home: string, seeds: readonly KeptSeed[]): Promise { const kept = new Set(seeds.map((seed) => basename(folderOf(seed)))); - const iosSources = join(iosDeviceSet(home), "sources"); + const iosSources = iosSourcesFolder(home); if (existsSync(iosSources)) { for (const device of await setDevices(iosSources)) { if (kept.has(device.udid)) continue; diff --git a/e2e/slow-baseline.test.ts b/e2e/slow-baseline.test.ts index cc75918a8..355c59436 100644 --- a/e2e/slow-baseline.test.ts +++ b/e2e/slow-baseline.test.ts @@ -7,7 +7,12 @@ import { describe, expect, it } from "vitest"; import { IOS } from "./helpers/agent-device-targets.js"; import { withDaemon } from "./helpers/index.js"; import type { TestEnv } from "./helpers/env.js"; -import { iosDeviceSet, setDevices, sweepStaleDeviceSets } from "./helpers/ios-device-set.js"; +import { + iosDeviceSet, + iosSourcesFolder, + setDevices, + sweepStaleDeviceSets, +} from "./helpers/ios-device-set.js"; import { DEVICE_READY_MS } from "./helpers/wait.js"; const ANDROID_HOME = @@ -79,12 +84,10 @@ describe.skipIf(process.platform !== "darwin")( expect(listed).toMatchObject({ name: "slow-ios", version: 1 }); expect(listed?.sizeBytes ?? 0).toBeGreaterThan(0); - // why: the sources set sits beside the device set under a custom root, or under `ios-sources` for the default set. - const sourcesSets = [join(deviceSet, "sources"), join(env.home, "devices", "ios-sources")]; - const sourcesSet = sourcesSets.find((candidate) => existsSync(candidate)); - expect(sourcesSet, "no sources set exists after a save").toBeDefined(); + const sourcesSet = iosSourcesFolder(env.home); + expect(existsSync(sourcesSet), "no sources set exists after a save").toBe(true); // why: the sources set also holds the seed the next device is copied from; the baseline's clone is the one named `simlock-baseline-`. - const inSources = (await setDevices(sourcesSet as string)).filter((device) => + const inSources = (await setDevices(sourcesSet)).filter((device) => device.name.startsWith("simlock-baseline-"), ); expect(inSources).toHaveLength(1); diff --git a/e2e/slow-ios-smoke.test.ts b/e2e/slow-ios-smoke.test.ts index b6d2837ac..cb1e5cb38 100644 --- a/e2e/slow-ios-smoke.test.ts +++ b/e2e/slow-ios-smoke.test.ts @@ -1,11 +1,11 @@ import { execFile } from "node:child_process"; -import { join } from "node:path"; import { promisify } from "node:util"; import { describe, expect, it } from "vitest"; import { IOS, withDaemon } from "./helpers/index.js"; import { iosDeviceSet, + iosSourcesFolder, setDevices, sweepStaleDeviceSets, type SimctlDevice, @@ -295,7 +295,7 @@ describe.skipIf(process.platform !== "darwin")( copies.map((device) => device.udid), "the device set holds the copy only", ).toEqual([secondGrant.device.driverDeviceId]); - const seeds = await setDevices(join(deviceSet, "sources")); + const seeds = await setDevices(iosSourcesFolder(env.home)); expect( seeds.map((seed) => seed.state), "the sources set holds the seed shut down", diff --git a/scripts/slow-e2e.sh b/scripts/slow-e2e.sh index 039146c1c..3db955171 100755 --- a/scripts/slow-e2e.sh +++ b/scripts/slow-e2e.sh @@ -21,10 +21,11 @@ # # Before a run it sources `.slow-lane.env` from the main checkout's root, if there is one: this # machine's settings, such as SIMLOCK_E2E_AGENT_DEVICE. A run's temporary homes live under -# /tmp/simlock-slow, so `clean` and `stop` find a run's daemons, emulators and simulators by +# $HOME/.sls (SIMLOCK_SLOW_TMP), so `clean` and `stop` find a run's daemons, emulators and simulators by # that path and touch nothing else, except the simulators in Xcode's own device set whose durable # mark names the instance of a home under that path (a daemon run with drivers.ios.deviceSet -# "default" keeps them there): `clean` and `stop` delete those too. A run starts by cleaning up +# "default" keeps them there): `clean` and `stop` delete those too. The folder holds a marker file the +# run writes; a folder without it is not the lane's, and `clean`, `stop` and a run refuse it (exit 69). A run starts by cleaning up # after earlier ones. # # The run is detached from the calling shell, so no tool time limit kills it halfway and @@ -33,7 +34,8 @@ set -eu # why: the three overrides let the script's own tests use a scratch lock and home directory. lock=${SIMLOCK_SLOW_LOCK:-/tmp/simlock-slow-e2e.lock} -lane_tmp=${SIMLOCK_SLOW_TMP:-/tmp/simlock-slow} +# why: ADR 0076: the lane's `deviceSet: default` flows need a home short enough for the sources folder to match Xcode's set in length, which a path under /tmp (really /private/tmp) cannot. +lane_tmp=${SIMLOCK_SLOW_TMP:-$HOME/.sls} min_free=${SIMLOCK_SLOW_MIN_FREE_GIB:-15} # why: the worker lock the daemon takes (ADR 0059); src/slow-e2e.test.ts keeps this default equal to defaultWorkerLockPath. worker_lock=${SIMLOCK_SLOW_WORKER_LOCK:-/tmp/simlock-$(id -u)/worker.lock} @@ -79,7 +81,16 @@ def leftovers(): found.append((int(pid), text.split(" ")[0])) return found +MARKER = ".simlock-slow-lane" + +def refuse_foreign_lane_tmp(): + # why: lane_tmp defaults to a folder in $HOME; only one this script made (it holds the marker) is the lane's to remove or to kill processes by. + if os.path.exists(lane_tmp) and not os.path.exists(os.path.join(lane_tmp, MARKER)): + print(f"refused: {lane_tmp} was not made by the slow lane (it holds no {MARKER}); move it, or set SIMLOCK_SLOW_TMP to another folder", file=sys.stderr) + sys.exit(69) + def clean(): + refuse_foreign_lane_tmp() procs = leftovers() for pid, _ in procs: try: @@ -249,6 +260,7 @@ echo "$root" > "$lock/root" echo "$log" > "$lock/log" echo "$log" > "$lock.last" mkdir -p "$lane_tmp" +: > "$lane_tmp/.simlock-slow-lane" SIMLOCK_E2E_LOG_DIR="${log%.log}-daemons" TMPDIR="$lane_tmp/" python3 - "$lock" "$log" "$root" "$script" "$@" <<'EOF' import os, subprocess, sys diff --git a/src/core/AGENTS.md b/src/core/AGENTS.md index 4f77c216a..c2db1d6d5 100644 --- a/src/core/AGENTS.md +++ b/src/core/AGENTS.md @@ -58,7 +58,7 @@ Baselines (ADR 0061 §4): - One save or remove at a time. A save: leasing's `releaseToSave` ends the lease, then `ReclaimCoordinator.retireSaved` calls `driver.saveSource` under the `reclaim` claim. A driver failure quarantines the device and answers `BASELINE_SAVE_FAILED`. - A replace keeps the leased devices of older versions. An older version is dropped only when no device record and no provision (`hold`) has it; that is checked after a save, on every `device.deleted` and at startup. - `remove` refuses a baseline a lease uses, and destroys each source before its row. `removeAll` (nuke) deletes rows first. -- `checkStale` runs before `list` and `doctor` and after `component.removed`. +- `checkStale` runs once at startup (after the sources are listed, before the warm pool starts), before `list` and `doctor`, and after `component.removed`. ## Known gaps diff --git a/src/core/create-core.test.ts b/src/core/create-core.test.ts index 4263dde33..3cfaefc0e 100644 --- a/src/core/create-core.test.ts +++ b/src/core/create-core.test.ts @@ -425,6 +425,108 @@ describe("createCore", () => { expect(JSON.stringify(sink.records)).toContain("catalog unreadable"); }); + it("converge stores a baseline's stale reason before the warm pool first resolves a target, and logs a check that failed without failing the start", async () => { + const reason = + "saved in /home/.simlock/devices/ios/sources, which copies cannot be fixed from; save it again"; + const cases = [ + { name: "a stale source", failure: undefined, stored: reason, logged: false, warmed: false }, + { + name: "the check's read fails", + failure: new Error("catalog unreadable"), + stored: null, + logged: true, + warmed: undefined, + }, + ]; + + for (const entry of cases) { + const sink = new MemoryLogSink(); + const { clock, core, driver, registry } = await build({ + sink, + warmTargets: [{ count: 1, model: "iPhone 16", osVersion: "26.5", platform: "ios" }], + }); + const storedWhenWarmPoolFirstResolves: unknown[] = []; + testStateOf(registry) + .database.prepare( + `INSERT INTO baselines (name, version, platform, model, os_version, mode, saved_at, source_id) + VALUES ('login', 1, 'ios', 'iPhone 16', '26.5', 'full', '2026-11-03T00:00:00.000Z', 'src-login')`, + ) + .run(); + // why: a warm target naming the baseline is a learned baseline kind: the pool plans it from the baseline's newest version unless the baseline is stale. + testStateOf(registry) + .database.prepare( + `INSERT INTO warm_kinds (platform, model, os_version, mode, image_tag, baseline, last_leased_at, learned) + VALUES ('ios', 'iPhone 16', '26.5', 'full', '', 'login', 1000, 1)`, + ) + .run(); + driver.setSources([ + { + id: "src-login", + kind: "baseline", + model: "iPhone 16", + osVersion: "26.5", + staleReason: reason, + }, + ]); + // why: the startup listing is call 1; the staleness check's read is call 2. + if (entry.failure !== undefined) driver.failOn("listSources", 2, entry.failure); + // why: the check's read takes a turn of the event loop and a warm pool tick falls in it: a pool already started would resolve its target before the reason is stored. + const listSources = driver.listSources.bind(driver); + let listed = 0; + vi.spyOn(driver, "listSources").mockImplementation(async () => { + listed += 1; + if (listed === 2) { + clock.advance(31_000); + await new Promise((resolve) => setImmediate(resolve)); + } + return await listSources(); + }); + const connected = ports(); + core.connect({ + ...connected, + warmPoolDemand: { + ...connected.warmPoolDemand, + resolve: async () => { + storedWhenWarmPoolFirstResolves.push( + testStateOf(registry).database.prepare("SELECT stale_reason FROM baselines").get(), + ); + return { message: "no driver", refusal: "no-driver" }; + }, + }, + }); + + await expect(core.converge(await core.readStartup()), entry.name).resolves.toBeUndefined(); + await vi.waitFor(() => expect(storedWhenWarmPoolFirstResolves.length).toBeGreaterThan(0)); + + expect( + testStateOf(registry).database.prepare("SELECT stale_reason FROM baselines").get(), + entry.name, + ).toEqual({ stale_reason: entry.stored }); + expect( + storedWhenWarmPoolFirstResolves[0], + `${entry.name}: before the warm pool starts`, + ).toEqual({ + stale_reason: entry.stored, + }); + if (entry.warmed !== undefined) { + await vi.waitFor(() => + expect( + testStateOf(registry).database.prepare("SELECT COUNT(*) AS n FROM warm_kinds").get(), + `${entry.name}: the pool drops the kind of a stale baseline`, + ).toEqual({ n: 0 }), + ); + expect( + driver.calls.filter((call) => call.operation === "provision"), + `${entry.name}: no provision for the stale baseline`, + ).toEqual([]); + } + expect( + JSON.stringify(sink.records).includes("could not check baselines at startup"), + entry.name, + ).toBe(entry.logged); + } + }); + it("converge shuts down and deletes a released device whose wipe was deferred, instead of wiping it", async () => { const harness = await build(); const { released } = await releasedLease(harness, { deferReclaim: true }); diff --git a/src/core/create-core.ts b/src/core/create-core.ts index 78b3ed19e..831fc67f3 100644 --- a/src/core/create-core.ts +++ b/src/core/create-core.ts @@ -444,6 +444,7 @@ export function createCore(options: CoreOptions): Core { await startup.converge(read); await dropReplacedBaselines(); await listStartupSources(options.drivers, options.logger); + await checkBaselinesAtStartup(baselines, options.logger); warmPool.start(); capacityObserver.start(); }, @@ -486,6 +487,23 @@ export function createCore(options: CoreOptions): Core { }; } +/** + * why: a stored stale reason is what a request names a baseline against, so it is stored before the + * first request and the warm pool; a failed check is logged and the start goes on. + */ +async function checkBaselinesAtStartup( + baselines: BaselineService, + logger: Logger | undefined, +): Promise { + try { + await baselines.checkStale(); + } catch (error: unknown) { + logger?.warn( + `could not check baselines at startup: ${error instanceof Error ? error.message : String(error)}`, + ); + } +} + /** * why: the first `listSources` of a process is where a driver sweeps what an earlier process left * in its sources (ADR 0061 §1); a failed read is logged, never fatal, and the sweep runs again on diff --git a/src/core/device-root.ts b/src/core/device-root.ts index 71dd585aa..b5156d66d 100644 --- a/src/core/device-root.ts +++ b/src/core/device-root.ts @@ -18,7 +18,8 @@ export type RootRejectionReason = | "non-empty-unowned-root" | "unreadable" | "invalid-device-set" - | "device-set-changed"; + | "device-set-changed" + | "sources-path-unfit"; export interface OwnedRootMarker { readonly schemaVersion: 1; diff --git a/src/drivers/ios/AGENTS.md b/src/drivers/ios/AGENTS.md index 918b27a4a..8f6a7c6a2 100644 --- a/src/drivers/ios/AGENTS.md +++ b/src/drivers/ios/AGENTS.md @@ -9,7 +9,7 @@ The device set: - Under `drivers.ios.deviceSet: simlock`, never `simctl` without `--set`, except three unscoped calls: `findLegacy`, `destroyLegacy`, and the read-only `simctl list -j devices` of `listComponents`. - Under `default` (ADR 0048) the set is Xcode's own: never `--set`, no owned root, and never act on a device whose durable mark does not name this instance. `listManaged` lists only those, and `findLegacy` answers `undefined`. -- `ios.simulator.headless: false` needs `default`: the `simlock` set has no DeviceHub, so iOS is refused (`invalid-device-set`). Simulators left in the set being given up refuse iOS too (`device-set-changed`); that check reads files only, never `simctl`. +- `ios.simulator.headless: false` needs `default`: the `simlock` set has no DeviceHub, so iOS is refused (`invalid-device-set`). Simulators left in the set being given up, or in either setting's sources folder, refuse iOS too (`device-set-changed`); that check reads files only, never `simctl`. - The erasable mark is written before the durable one, never both at once. Under `default` a failed mark write deletes the new simulator before the error is rethrown. Resolve and boot: @@ -20,19 +20,17 @@ Resolve and boot: - Slim (ADR 0060), on `prepare` of a slim spec only: the managed labels are merged into the simulator's `disabled.plist` before the boot (other entries kept; a failed write is logged and the boot goes on), and `launchctl print-disabled system` is read back after it. A label not as written returns `full`; a readback that fails returns `slim`; both call `onSlimSkipped`, logged only. Every label as written and the write ok: `slim`, and `onSlimmed` becomes `device.slimmed`. - Slim `except` (ADR 0066, `slim-except.ts`): an excepted category's labels are written `false`; an unknown name is `BAD_REQUEST`; a kept label not read back throws `KeptCategoriesError`. - A recovery boot writes no slim overrides and reads nothing back. DeviceHub clipboard isolation is configured before preparation and recovery boots; ready default-set simulators reboot under the lease claim before a grant. Active leases at upgrade are not interrupted and may retain clipboard sync until a later boot or lease end. -- The overrides folder lives outside the device set (`launchdOverridesRoot`), so `destroy` removes it itself after `simctl delete`. - After every boot and before the readback, `runAfterBoot` (`boot-courtesies.ts`) runs the volume step, then the window step. Each only reports its failure (`onSilenceFailed`, `onWindowFailed`), and the device stays in use. - Volume (`ios.simulator.audio: false`): Apps keep playing at volume 0. A baseline source is not silenced. - Window (`ios.simulator.headless: false`): DeviceHub is opened in the background, so the front app stays in front, and is told not to shut down started devices when it quits. Only a non-zero exit of that open means DeviceHub is missing: Simulator.app is then opened instead, detached, so quitting it leaves the simulator running. Any other failure opens nothing. 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 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 folder (ADR 0076): `$SIMLOCK_HOME/devices/src` followed by `_` until its real path is as long as the device set's, an owned root under both settings. When none can fit, iOS is refused `sources-path-unfit`. A row naming another set is a seed made again, or a baseline stale (`BASELINE_STALE`); its simulator is deleted there only when the set is an earlier sources folder (`/sources`, `ios-sources`), else left and logged. It is in no `listManaged` or `simlock simctl list`. - 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. - A `making` row of another process is swept at the first `listSources`; one of this process, once older than any make takes, at the next make of its kind. -- A seed that `simctl delete` reports as `Invalid device` is already gone, so its row is dropped. - `removeComponent` deletes the runtime's seeds first. Physical, passthrough, screen: @@ -45,7 +43,6 @@ Tunnels (`device-tcp.ts`): - A simulator has no network of its own: its sockets are the worker's loopback sockets. A listener is the lease's only when a word of its process's environment is exactly `SIMULATOR_UDID=`, checked on every connection. - `reverse` listens on the device port itself on both loopbacks, and is refused `TUNNEL_PORT_IN_USE` when anything already answers on either, a wildcard listener included. -- No rule sits on a simulator: `sweep` does nothing, and a `reverse`'s `close` sets `holdsDeviceRule: false`, so a lease end with an aborted signal still runs it. ## Known gaps diff --git a/src/drivers/ios/boot-courtesies.test.ts b/src/drivers/ios/boot-courtesies.test.ts index 15ba96edc..e326fff4e 100644 --- a/src/drivers/ios/boot-courtesies.test.ts +++ b/src/drivers/ios/boot-courtesies.test.ts @@ -30,7 +30,7 @@ async function waitForCalls(runner: ScriptedProcessRunner, count: number): Promi } describe("IosSimctlDriver ios.simulator.headless refusal", () => { - const coreSimulatorRoot = "/CoreSim"; + const coreSimulatorRoot = "/Users/me/CoreSimulator"; it.each([ ["false with default", { deviceSet: "default" }, false, undefined], @@ -76,6 +76,7 @@ describe("IosSimctlDriver ios.simulator.headless refusal", () => { }); describe("IosSimctlDriver simulator window", () => { + const coreSimulatorRoot = "/Users/me/CoreSimulator"; const udid = driverData.udid; const slimData = { ...driverData, runtimeId: "com.apple.CoreSimulator.SimRuntime.iOS-18-5" }; const xcrun = (...args: string[]) => ({ command: "xcrun", args: ["simctl", ...args] }); @@ -140,6 +141,7 @@ describe("IosSimctlDriver simulator window", () => { })), ); const driver = await IosSimctlDriver.create({ + coreSimulatorRoot, clock: new FakeClock(), database: await memorySourceDatabase(), driverConfig: { deviceSet: "default" }, @@ -216,6 +218,7 @@ describe("IosSimctlDriver simulator window", () => { const failures: WindowFailedFact[] = []; const driver = await IosSimctlDriver.create({ clock, + coreSimulatorRoot, database: await memorySourceDatabase(), driverConfig: { deviceSet: "default" }, filesystem: new MemoryFilesystem(), diff --git a/src/drivers/ios/device-set-leftovers.test.ts b/src/drivers/ios/device-set-leftovers.test.ts new file mode 100644 index 000000000..74d866ed5 --- /dev/null +++ b/src/drivers/ios/device-set-leftovers.test.ts @@ -0,0 +1,194 @@ +import { describe, expect, it } from "vitest"; + +import { OwnedRootError, OWNED_ROOT_MARKER_FILE } from "../../core/index.js"; +import { FakeClock, MemoryFilesystem, ScriptedProcessRunner } from "../../ports/index.js"; +import { IosSimctlDriver } from "./index.js"; +import { memorySourceDatabase } from "./testing.js"; +import { instanceId } from "./test-slim.js"; + +describe("IosSimctlDriver device set switch", () => { + const coreSimulatorRoot = "/Users/me/CoreSimulator"; + + it("an operator who switches with leftovers gets device-set-changed, and an unreadable folder gets unreadable", async () => { + const ownRoot = "/home/.simlock/devices/ios"; + const xcodeDevices = `${coreSimulatorRoot}/Devices`; + const [first, second, third] = [1, 2, 3].map( + (n) => `00000000-0000-0000-0000-00000000000${String(n)}`, + ); + const mark = (owner: string) => JSON.stringify({ instanceId: owner, token: "t", udid: "u" }); + const steps: readonly [ + string, + Record, + (fs: MemoryFilesystem) => Promise, + { readonly message?: string; readonly path?: string; readonly reason: string } | undefined, + ][] = [ + [ + "default with two devices in Simlock's set", + { deviceSet: "default" }, + async (fs) => { + await fs.mkdirp(`${ownRoot}/${second}`); + await fs.mkdirp(`${ownRoot}/${first}`); + await fs.writeFileAtomic(`${ownRoot}/${OWNED_ROOT_MARKER_FILE}`, "{}"); + }, + { + message: `Refusing the ios device set: Simlock's own set at ${ownRoot} still holds 2 simulator(s) (${first}, ${second}). Set drivers.ios.deviceSet back to simlock, run \`simlock nuke --delete-devices\` and \`simlock doctor --purge-orphans\`, then switch again. Delete any that remain with \`xcrun simctl --set ${ownRoot} delete \`.`, + path: ownRoot, + reason: "device-set-changed", + }, + ], + [ + "default with a seed in the sources set Simlock's own set held", + { deviceSet: "default" }, + async (fs) => { + await fs.mkdirp(`${ownRoot}/sources/${third}`); + await fs.mkdirp(`${ownRoot}/${first}`); + await fs.writeFileAtomic(`${ownRoot}/${OWNED_ROOT_MARKER_FILE}`, "{}"); + }, + { + message: `Refusing the ios device set: Simlock's own set at ${ownRoot} still holds 2 simulator(s) (${first}, ${third}). Set drivers.ios.deviceSet back to simlock, run \`simlock nuke --delete-devices\` and \`simlock doctor --purge-orphans\`, then switch again. Delete any that remain with \`xcrun simctl --set ${ownRoot} delete \`, or, for a seed in a sources folder, \`xcrun simctl --set ${ownRoot}/sources delete \`.`, + path: ownRoot, + reason: "device-set-changed", + }, + ], + [ + "simlock with a seed in the sources set deviceSet default used", + { deviceSet: "simlock" }, + async (fs) => { + await fs.mkdirp(`${ownRoot}-sources/${second}`); + }, + { + message: `Refusing the ios device set: Simlock's sources set at ${ownRoot}-sources still holds 1 simulator(s) (${second}). Set drivers.ios.deviceSet back to default, run \`simlock nuke --delete-devices\` and \`simlock doctor --purge-orphans\`, then switch again. Delete any that remain with \`xcrun simctl --set ${ownRoot}-sources delete \`. Run \`simlock nuke --delete-devices\` again afterwards, so Simlock drops its record of them.`, + path: `${ownRoot}-sources`, + reason: "device-set-changed", + }, + ], + [ + "default with a seed in the simlock sources folder", + { deviceSet: "default" }, + async (fs) => { + await fs.mkdirp(`/home/.simlock/devices/src/${third}`); + }, + { + message: `Refusing the ios device set: Simlock's own set at ${ownRoot} still holds 1 simulator(s) (${third}). Set drivers.ios.deviceSet back to simlock, run \`simlock nuke --delete-devices\` and \`simlock doctor --purge-orphans\`, then switch again. Delete any that remain with \`xcrun simctl --set ${ownRoot} delete \`, or, for a seed in a sources folder, \`xcrun simctl --set /home/.simlock/devices/src delete \`.`, + path: ownRoot, + reason: "device-set-changed", + }, + ], + [ + "simlock with a seed in the default sources folder", + { deviceSet: "simlock" }, + async (fs) => { + await fs.mkdirp(`/home/.simlock/devices/src_____/${second}`); + }, + { + message: `Refusing the ios device set: Simlock's sources set at /home/.simlock/devices/src_____ still holds 1 simulator(s) (${second}). Set drivers.ios.deviceSet back to default, run \`simlock nuke --delete-devices\` and \`simlock doctor --purge-orphans\`, then switch again. Delete any that remain with \`xcrun simctl --set /home/.simlock/devices/src_____ delete \`. Run \`simlock nuke --delete-devices\` again afterwards, so Simlock drops its record of them.`, + path: "/home/.simlock/devices/src_____", + reason: "device-set-changed", + }, + ], + [ + "default with Simlock's set empty", + { deviceSet: "default" }, + async (fs) => { + await fs.mkdirp(ownRoot); + await fs.writeFileAtomic(`${ownRoot}/${OWNED_ROOT_MARKER_FILE}`, "{}"); + }, + undefined, + ], + ["default with no root folder", { deviceSet: "default" }, async () => undefined, undefined], + [ + "simlock with a device of this instance in Xcode's set", + { deviceSet: "simlock" }, + async (fs) => { + await fs.mkdirp(`${xcodeDevices}/${third}`); + await fs.writeFileAtomic(`${xcodeDevices}/${third}/simlock-mark.json`, mark(instanceId)); + }, + { + message: `Refusing the ios device set: Xcode's device set still holds 1 of this Simlock's simulator(s) (${third}). Set drivers.ios.deviceSet back to default, run \`simlock nuke --delete-devices\` and \`simlock doctor --purge-orphans\`, then switch again. Delete any that remain with \`xcrun simctl delete \`.`, + path: xcodeDevices, + reason: "device-set-changed", + }, + ], + [ + "simlock with only unmarked, other-instance and corrupt devices in Xcode's set", + { deviceSet: "simlock" }, + async (fs) => { + await fs.mkdirp(`${xcodeDevices}/${first}`); + await fs.mkdirp(`${xcodeDevices}/${second}`); + await fs.writeFileAtomic(`${xcodeDevices}/${second}/simlock-mark.json`, mark("other")); + await fs.mkdirp(`${xcodeDevices}/${third}`); + await fs.writeFileAtomic(`${xcodeDevices}/${third}/simlock-mark.json`, "{broken"); + }, + undefined, + ], + [ + "default with Simlock's folder unreadable", + { deviceSet: "default" }, + async (fs) => { + await fs.mkdirp(ownRoot); + fs.defineFailure(ownRoot, "EACCES"); + }, + { path: ownRoot, reason: "unreadable" }, + ], + [ + "simlock with Xcode's folder unreadable", + { deviceSet: "simlock" }, + async (fs) => { + await fs.mkdirp(xcodeDevices); + fs.defineFailure(xcodeDevices, "EACCES"); + }, + { path: xcodeDevices, reason: "unreadable" }, + ], + ]; + + for (const [name, config, plant, expected] of steps) { + const filesystem = new MemoryFilesystem(); + await plant(filesystem); + const runner = new ScriptedProcessRunner([]); + const failure = await IosSimctlDriver.create({ + database: await memorySourceDatabase(), + clock: new FakeClock(), + coreSimulatorRoot, + driverConfig: config, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + processRunner: runner, + simlockHome: "/home/.simlock", + }) + .then(() => undefined) + .catch((error: unknown) => error); + + expect(runner.calls, name).toEqual([]); + if (expected === undefined) { + expect(failure, name).toBeUndefined(); + } else { + expect(failure, name).toBeInstanceOf(OwnedRootError); + expect(failure, name).toMatchObject({ ...expected, platform: "ios" }); + } + } + }); + + it.each(["default", "simlock"] as const)( + "a worker whose %s device set is as long as its home plus 12 characters keeps its own seeds in the sources folder the other setting would share", + async (deviceSet) => { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp("/home/.simlock/devices/src/00000000-0000-0000-0000-000000000001"); + + const created = IosSimctlDriver.create({ + database: await memorySourceDatabase(), + clock: new FakeClock(), + // why: `/Users/me/CoreSim1/Devices` is 26 characters, as long as `/home/.simlock/devices/ios`, so both settings name `/home/.simlock/devices/src`. + coreSimulatorRoot: "/Users/me/CoreSim1", + driverConfig: { deviceSet }, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + processRunner: new ScriptedProcessRunner([]), + simlockHome: "/home/.simlock", + }); + + await expect(created).resolves.toBeInstanceOf(IosSimctlDriver); + }, + ); +}); diff --git a/src/drivers/ios/device-set-leftovers.ts b/src/drivers/ios/device-set-leftovers.ts index 6ec8c4621..81c349987 100644 --- a/src/drivers/ios/device-set-leftovers.ts +++ b/src/drivers/ios/device-set-leftovers.ts @@ -14,39 +14,54 @@ const SWITCH_STEPS = * leave them invisible to the new setting, so the driver refuses to start. The * check reads files only: a start-up `simctl` call would be a new way for start-up to hang. */ -export async function refuseOwnSetLeftovers(filesystem: Filesystem, root: string): Promise { - // why: the sources set of `deviceSet: simlock` is the `sources` folder of the set; its seeds are as invisible to `default` as the set's devices. - const entries = [ - ...(await readFolder(filesystem, root)), - ...(await readFolder(filesystem, join(root, "sources"))), - ]; - const udids = entries.filter((entry) => UDID_PATTERN.test(entry)).sort(); +export async function refuseOwnSetLeftovers( + filesystem: Filesystem, + root: string, + sourcesFolders: readonly string[], +): Promise { + // why: the sources folders `simlock` has used are as invisible to `default` as the set's devices, so seeds in any of them are leftovers. + const inSources = new Map(); + for (const folder of sourcesFolders) { + inSources.set(folder, await udidsIn(filesystem, folder)); + } + const udids = [...(await udidsIn(filesystem, root)), ...[...inSources.values()].flat()].sort(); if (udids.length === 0) return; + const holding = sourcesFolders.filter((folder) => (inSources.get(folder) ?? []).length > 0); + const sourcesNote = + holding.length === 0 + ? "" + : `, or, for a seed in a sources folder, ${holding + .map((folder) => `\`xcrun simctl --set ${folder} delete \``) + .join(" or ")}`; throw new OwnedRootError( - `Refusing the ios device set: Simlock's own set at ${root} still holds ${String(udids.length)} simulator(s) (${udids.join(", ")}). Set drivers.ios.deviceSet back to simlock, ${SWITCH_STEPS} Delete any that remain with \`xcrun simctl --set ${root} delete \`, or, for a seed in the sources set, \`xcrun simctl --set ${join(root, "sources")} delete \`.`, + `Refusing the ios device set: Simlock's own set at ${root} still holds ${String(udids.length)} simulator(s) (${udids.join(", ")}). Set drivers.ios.deviceSet back to simlock, ${SWITCH_STEPS} Delete any that remain with \`xcrun simctl --set ${root} delete \`${sourcesNote}.`, "device-set-changed", root, "ios", ); } -/** why: the sources set of `deviceSet: default` is its own folder, which `simlock` never reads, so seeds left there are refused like devices. */ +/** why: the sources folders of `deviceSet: default` are folders `simlock` never reads, so seeds left in them are refused like devices. */ export async function refuseDefaultSourcesLeftovers( filesystem: Filesystem, - sourcesSet: string, + sourcesFolders: readonly string[], ): Promise { - const udids = (await readFolder(filesystem, sourcesSet)) - .filter((entry) => UDID_PATTERN.test(entry)) - .sort(); - if (udids.length === 0) return; + for (const sourcesSet of sourcesFolders) { + const udids = await udidsIn(filesystem, sourcesSet); + if (udids.length === 0) continue; - throw new OwnedRootError( - `Refusing the ios device set: Simlock's sources set at ${sourcesSet} still holds ${String(udids.length)} simulator(s) (${udids.join(", ")}). Set drivers.ios.deviceSet back to default, ${SWITCH_STEPS} Delete any that remain with \`xcrun simctl --set ${sourcesSet} delete \`. Run \`simlock nuke --delete-devices\` again afterwards, so Simlock drops its record of them.`, - "device-set-changed", - sourcesSet, - "ios", - ); + throw new OwnedRootError( + `Refusing the ios device set: Simlock's sources set at ${sourcesSet} still holds ${String(udids.length)} simulator(s) (${udids.join(", ")}). Set drivers.ios.deviceSet back to default, ${SWITCH_STEPS} Delete any that remain with \`xcrun simctl --set ${sourcesSet} delete \`. Run \`simlock nuke --delete-devices\` again afterwards, so Simlock drops its record of them.`, + "device-set-changed", + sourcesSet, + "ios", + ); + } +} + +async function udidsIn(filesystem: Filesystem, folder: string): Promise { + return (await readFolder(filesystem, folder)).filter((entry) => UDID_PATTERN.test(entry)).sort(); } export async function refuseXcodeSetLeftovers( diff --git a/src/drivers/ios/devicectl-passthrough.test.ts b/src/drivers/ios/devicectl-passthrough.test.ts index 879cacb95..697c1d02b 100644 --- a/src/drivers/ios/devicectl-passthrough.test.ts +++ b/src/drivers/ios/devicectl-passthrough.test.ts @@ -5,7 +5,7 @@ import { FakeClock, MemoryFilesystem, ScriptedProcessRunner } from "../../ports/ import { IosSimctlDriver } from "./index.js"; import { memorySourceDatabase } from "./testing.js"; -const deviceRoot = "/Devices"; +const deviceRoot = "/home/.simlock/devices/dev-ios"; const UDID = "00008110-001A2B3C4D5E"; const APP = "com.example.app"; const BUILD = "/builds/App.app"; diff --git a/src/drivers/ios/index.test.ts b/src/drivers/ios/index.test.ts index b8a6e6ae3..39e3c0309 100644 --- a/src/drivers/ios/index.test.ts +++ b/src/drivers/ios/index.test.ts @@ -63,6 +63,7 @@ import { simctl, simctlArgs, slimBootCalls, + sourcesRoot, waitForCalls, } from "./test-slim.js"; @@ -183,28 +184,53 @@ afterEach(() => { if (call.command !== "xcrun" || call.args[0] !== "simctl") continue; if (UNSCOPED_LEGACY_CALLS.has(call.args.join(" "))) continue; expect(call.args.slice(0, 2)).toEqual(["simctl", "--set"]); - expect([deviceRoot, `${deviceRoot}/sources`]).toContain(call.args[2]); + expect([ + deviceRoot, + sourcesRoot, + `${deviceRoot}/sources`, + "/home/.simlock/devices/ios-sources", + ]).toContain(call.args[2]); } }); +/** why: Xcode's set under the tests' core-simulator root is 31 characters, so under this home the sources folder is `src` and 5 underscores. */ +const xcodeSourcesRoot = "/home/.simlock/devices/src_____"; + const seedUdid = "00000000-0000-0000-0000-0000000000aa"; +/** why: a sources folder an earlier run of this instance made, so a test can plant simulators in it. */ +async function plantOwnedRoot(filesystem: Filesystem, path: string): Promise { + await filesystem.mkdirp(path, { mode: 0o700 }); + await filesystem.writeFileAtomic( + `${path}/${OWNED_ROOT_MARKER_FILE}`, + JSON.stringify({ schemaVersion: 1, owner: "simlock", instanceId, platform: "ios" }), + ); +} + interface Catalog { devicetypes: { identifier: string }[]; runtimes: { buildversion?: string; identifier: string }[]; } +/** why: a seed of an earlier release is deleted in the set its row names, which is not always today's sources folder. */ +function simctlIn( + set: string, + ...args: readonly string[] +): { readonly command: string; readonly args: string[] } { + return { args: ["simctl", "--set", set, ...args], command: "xcrun" }; +} + /** why: A seed lives in the sources set, a sibling of the lease device set, and its calls are scoped to that. */ function sourcesSimctl(...args: readonly string[]): { readonly command: string; readonly args: string[]; } { - return { args: ["simctl", "--set", `${deviceRoot}/sources`, ...args], command: "xcrun" }; + return { args: ["simctl", "--set", sourcesRoot, ...args], command: "xcrun" }; } /** why: A database that already holds the seed of the kind `spec` names, so a test of the copy step starts at the clone. */ async function seededDatabase( - seed: { readonly runtimeBuild?: string; readonly udid?: string } = {}, + seed: { readonly runtimeBuild?: string; readonly setPath?: string; readonly udid?: string } = {}, ): Promise { return plantReadySeed(await memorySourceDatabase(), { deviceTypeId: driverData.deviceTypeId, @@ -915,10 +941,6 @@ describe("IosSimctlDriver", () => { rowsWhenCreated, "the seed's row is making, with no simulator yet, when create runs", ).toEqual([{ state: "making", udid: null }]); - expect( - filesystem.mkdirpModes.get(`${deviceRoot}/sources`), - "under deviceSet simlock the sources set is asked for private to the user", - ).toBe(0o700); expect(runner.calls).toEqual([ { ...listInvocation, options: { timeoutMs: 30_000 } }, { ...seedCreate, options: { timeoutMs: 330_000 } }, @@ -1043,12 +1065,7 @@ describe("IosSimctlDriver", () => { { match: simctl("shutdown", driverData.udid) }, { hangs: true, - match: simctl( - "clone", - driverData.udid, - "simlock-baseline-device-1", - `${deviceRoot}/sources`, - ), + match: simctl("clone", driverData.udid, "simlock-baseline-device-1", sourcesRoot), }, ], }, @@ -1091,7 +1108,7 @@ describe("IosSimctlDriver", () => { }); }); - const coreSimulatorRoot = "/CoreSim"; + const coreSimulatorRoot = "/Users/me/CoreSimulator"; it.each([ { @@ -1101,7 +1118,7 @@ describe("IosSimctlDriver", () => { hung: [ "simctl", "--set", - "/home/.simlock/devices/ios-sources", + xcodeSourcesRoot, "clone", seedUdid, driverData.name, @@ -1135,8 +1152,7 @@ describe("IosSimctlDriver", () => { physical: false, }), deleteArgs: (udid: string) => sourcesSimctl("delete", udid).args, - hung: simctl("clone", driverData.udid, "simlock-baseline-device-1", `${deviceRoot}/sources`) - .args, + hung: simctl("clone", driverData.udid, "simlock-baseline-device-1", sourcesRoot).args, isDefault: false, seeded: false, steps: [ @@ -1193,7 +1209,9 @@ describe("IosSimctlDriver", () => { await plantManagedDevice(filesystem); const clock = new FakeClock(); const driver = await IosSimctlDriver.create({ - database: seeded ? await seededDatabase() : await memorySourceDatabase(), + database: seeded + ? await seededDatabase({ setPath: isDefault ? xcodeSourcesRoot : sourcesRoot }) + : await memorySourceDatabase(), clock, ...(isDefault ? { coreSimulatorRoot } : {}), driverConfig: isDefault ? { deviceSet: "default" } : { deviceRoot }, @@ -1483,7 +1501,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(() => sourcesRoot), ); expect(database.prepare("SELECT COUNT(*) AS n FROM ios_source_data").get()).toEqual({ n: 0 }); }, @@ -1551,9 +1569,23 @@ describe("IosSimctlDriver", () => { runtimeBuild: undefined, remade: false, }, + { + name: "its row names the old sources folder of the simlock set", + seedBuild: "23F79", + runtimeBuild: "23F79", + remade: true, + setPath: `${deviceRoot}/sources`, + }, + { + name: "its row names the old sources folder of the default set", + seedBuild: "23F79", + runtimeBuild: "23F79", + remade: true, + setPath: "/home/.simlock/devices/ios-sources", + }, ])( "makes the seed again before copying it only when it is stale: $name -> remade $remade", - async ({ seedBuild, runtimeBuild, remade }) => { + async ({ seedBuild, runtimeBuild, remade, setPath = sourcesRoot }) => { const staleUdid = "00000000-0000-0000-0000-0000000000bb"; const catalog = JSON.parse(listFixture) as { runtimes: { buildversion?: string; identifier: string }[]; @@ -1569,8 +1601,8 @@ describe("IosSimctlDriver", () => { { match: listInvocation, result: { code: 0, stderr: "", stdout: JSON.stringify(catalog) } }, ...(remade ? [ - { match: sourcesSimctl("shutdown", staleUdid) }, - { match: sourcesSimctl("delete", staleUdid) }, + { match: simctlIn(setPath, "shutdown", staleUdid) }, + { match: simctlIn(setPath, "delete", staleUdid) }, { match: sourcesSimctl( "create", @@ -1598,6 +1630,7 @@ describe("IosSimctlDriver", () => { new FakeClock(), filesystem, await seededDatabase({ + setPath, udid: planted, ...(seedBuild === undefined ? {} : { runtimeBuild: seedBuild }), }), @@ -1685,18 +1718,33 @@ describe("IosSimctlDriver", () => { ); it("the first listSources of a process deletes another process's making rows and their simulators, keeps a row whose delete failed, and does not sweep again", async () => { - const [gone, stuck, ready] = [1, 2, 3].map( + const [gone, stuck, ready, foreign] = [1, 2, 3, 4].map( (n) => `00000000-0000-0000-0000-0000000001${String(n)}0`, - ) as [string, string, string]; + ) as [string, string, string, string]; const database = await memorySourceDatabase(); const kind = { deviceTypeId: driverData.deviceTypeId, runtimeId: driverData.runtimeId }; - plantSource(database, { ...kind, maker: "earlier-process", state: "making", udid: gone }); + const oldSet = `${deviceRoot}/sources`; + plantSource(database, { + ...kind, + maker: "earlier-process", + setPath: oldSet, + state: "making", + udid: gone, + }); + const foreignSet = "/Volumes/other/sources"; + plantSource(database, { + ...kind, + maker: "earlier-process", + setPath: foreignSet, + state: "making", + udid: foreign, + }); plantSource(database, { ...kind, maker: "earlier-process", state: "making" }); plantSource(database, { ...kind, maker: "earlier-process", state: "making", udid: stuck }); plantSource(database, { ...kind, udid: ready }); const runner = new ScriptedProcessRunner([ - { match: sourcesSimctl("shutdown", gone) }, - { match: sourcesSimctl("delete", gone) }, + { match: simctlIn(oldSet, "shutdown", gone) }, + { match: simctlIn(oldSet, "delete", gone) }, { match: sourcesSimctl("shutdown", stuck) }, { match: sourcesSimctl("delete", stuck), result: { code: 1, stderr: "busy", stdout: "" } }, { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, @@ -1716,7 +1764,9 @@ describe("IosSimctlDriver", () => { ["list", "-j"], ["list", "-j"], ]); + // why: safety rule 1: a row naming a path that is no sources folder of Simlock loses its row, and its simulator is left where it is. expect(logger.warnings).toEqual([ + expect.stringContaining(`left source ${foreign} in ${foreignSet}`), expect.stringContaining(`could not remove leftover source ${stuck}:`), ]); expect(database.prepare("SELECT udid, state FROM ios_source_data ORDER BY udid").all()).toEqual( @@ -1731,8 +1781,8 @@ describe("IosSimctlDriver", () => { const orphanUdid = "00000000-0000-0000-0000-0000000000ee"; const filesystem = new MemoryFilesystem(); await plantManagedDevice(filesystem); - await filesystem.mkdirp(`${deviceRoot}/sources/${seedUdid}`); - await filesystem.mkdirp(`${deviceRoot}/sources/${orphanUdid}`); + await filesystem.mkdirp(`${sourcesRoot}/${seedUdid}`); + await filesystem.mkdirp(`${sourcesRoot}/${orphanUdid}`); const database = await seededDatabase(); const runner = new ScriptedProcessRunner([ { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, @@ -1814,7 +1864,7 @@ describe("IosSimctlDriver", () => { describe("saveSource", () => { const cloneUdid = "00000000-0000-0000-0000-0000000000bb"; const baselineName = "simlock-baseline-device-1"; - const sourcesSet = `${deviceRoot}/sources`; + const sourcesSet = sourcesRoot; const device = { address: driverData.udid, deviceId: driverData.udid, @@ -1833,6 +1883,7 @@ describe("IosSimctlDriver", () => { overridesPath(driverData.udid), overridesPlist({ "a.b": true }), ); + await plantOwnedRoot(filesystem, sourcesSet); await filesystem.mkdirp(`${sourcesSet}/${cloneUdid}/data`); await filesystem.writeFileAtomic(`${sourcesSet}/${cloneUdid}/data/state`, "12345"); await plantLaunchServices(filesystem, `${sourcesSet}/${cloneUdid}`); @@ -4365,7 +4416,9 @@ describe("IosSimctlDriver listComponents()", () => { deviceTypeId: driverData.deviceTypeId, runtimeId: target.runtime, }; - plantSource(database, { ...removed, udid: goneSeed }); + // why: a seed made by an earlier release sits in the set its row names, and is deleted there. + const oldSet = `${deviceRoot}/sources`; + plantSource(database, { ...removed, setPath: oldSet, udid: goneSeed }); plantSource(database, { ...removed, deviceTypeId: "com.apple.CoreSimulator.SimDeviceType.iPad", @@ -4379,8 +4432,8 @@ describe("IosSimctlDriver listComponents()", () => { const runner = new ScriptedProcessRunner([ imagesListed([target, other]), defaultSetListed({}), - { match: sourcesSimctl("shutdown", goneSeed) }, - { match: sourcesSimctl("delete", goneSeed) }, + { match: simctlIn(oldSet, "shutdown", goneSeed) }, + { match: simctlIn(oldSet, "delete", goneSeed) }, { match: sourcesSimctl("shutdown", stuckSeed) }, { match: sourcesSimctl("delete", stuckSeed), @@ -5455,7 +5508,7 @@ const recoverFull = { mode: "full", purpose: "recover" } as const; const recoverSlim = { mode: "slim", purpose: "recover" } as const; describe("IosSimctlDriver device set", () => { - const coreSimulatorRoot = "/CoreSim"; + const coreSimulatorRoot = "/Users/me/CoreSimulator"; const runtimeImage = { build: "23E244", identifier: "IMG-26.4-23E244", @@ -5480,14 +5533,14 @@ describe("IosSimctlDriver device set", () => { } it.each([ - ["unset", {}, deviceRoot, true, `${deviceRoot}/sources`, false], - ["simlock", { deviceSet: "simlock" }, deviceRoot, true, `${deviceRoot}/sources`, false], + ["unset", {}, deviceRoot, true, sourcesRoot, false], + ["simlock", { deviceSet: "simlock" }, deviceRoot, true, sourcesRoot, false], [ "default", { deviceSet: "default" }, `${coreSimulatorRoot}/Devices`, false, - "/home/.simlock/devices/ios-sources", + xcodeSourcesRoot, true, ], ] as const)( @@ -5572,7 +5625,7 @@ describe("IosSimctlDriver device set", () => { ).resolves.toBeDefined(); await driver.provision(spec); await expect(filesystem.exists(`${sourcesSet}/${OWNED_ROOT_MARKER_FILE}`)).resolves.toBe( - !scoped, + true, ); await driver.makeReady(device, prepareFull); await driver.destroy(device); @@ -5630,142 +5683,6 @@ describe("IosSimctlDriver device set", () => { }, ); - it("an operator who switches with leftovers gets device-set-changed, and an unreadable folder gets unreadable", async () => { - const ownRoot = "/home/.simlock/devices/ios"; - const xcodeDevices = `${coreSimulatorRoot}/Devices`; - const [first, second, third] = [1, 2, 3].map( - (n) => `00000000-0000-0000-0000-00000000000${String(n)}`, - ); - const mark = (owner: string) => JSON.stringify({ instanceId: owner, token: "t", udid: "u" }); - const steps: readonly [ - string, - Record, - (fs: MemoryFilesystem) => Promise, - { readonly message?: string; readonly path?: string; readonly reason: string } | undefined, - ][] = [ - [ - "default with two devices in Simlock's set", - { deviceSet: "default" }, - async (fs) => { - await fs.mkdirp(`${ownRoot}/${second}`); - await fs.mkdirp(`${ownRoot}/${first}`); - await fs.writeFileAtomic(`${ownRoot}/${OWNED_ROOT_MARKER_FILE}`, "{}"); - }, - { - message: `Refusing the ios device set: Simlock's own set at ${ownRoot} still holds 2 simulator(s) (${first}, ${second}). Set drivers.ios.deviceSet back to simlock, run \`simlock nuke --delete-devices\` and \`simlock doctor --purge-orphans\`, then switch again. Delete any that remain with \`xcrun simctl --set ${ownRoot} delete \`, or, for a seed in the sources set, \`xcrun simctl --set ${ownRoot}/sources delete \`.`, - path: ownRoot, - reason: "device-set-changed", - }, - ], - [ - "default with a seed in the sources set Simlock's own set held", - { deviceSet: "default" }, - async (fs) => { - await fs.mkdirp(`${ownRoot}/sources/${third}`); - await fs.mkdirp(`${ownRoot}/${first}`); - await fs.writeFileAtomic(`${ownRoot}/${OWNED_ROOT_MARKER_FILE}`, "{}"); - }, - { - message: `Refusing the ios device set: Simlock's own set at ${ownRoot} still holds 2 simulator(s) (${first}, ${third}). Set drivers.ios.deviceSet back to simlock, run \`simlock nuke --delete-devices\` and \`simlock doctor --purge-orphans\`, then switch again. Delete any that remain with \`xcrun simctl --set ${ownRoot} delete \`, or, for a seed in the sources set, \`xcrun simctl --set ${ownRoot}/sources delete \`.`, - path: ownRoot, - reason: "device-set-changed", - }, - ], - [ - "simlock with a seed in the sources set deviceSet default used", - { deviceSet: "simlock" }, - async (fs) => { - await fs.mkdirp(`${ownRoot}-sources/${second}`); - }, - { - message: `Refusing the ios device set: Simlock's sources set at ${ownRoot}-sources still holds 1 simulator(s) (${second}). Set drivers.ios.deviceSet back to default, run \`simlock nuke --delete-devices\` and \`simlock doctor --purge-orphans\`, then switch again. Delete any that remain with \`xcrun simctl --set ${ownRoot}-sources delete \`. Run \`simlock nuke --delete-devices\` again afterwards, so Simlock drops its record of them.`, - path: `${ownRoot}-sources`, - reason: "device-set-changed", - }, - ], - [ - "default with Simlock's set empty", - { deviceSet: "default" }, - async (fs) => { - await fs.mkdirp(ownRoot); - await fs.writeFileAtomic(`${ownRoot}/${OWNED_ROOT_MARKER_FILE}`, "{}"); - }, - undefined, - ], - ["default with no root folder", { deviceSet: "default" }, async () => undefined, undefined], - [ - "simlock with a device of this instance in Xcode's set", - { deviceSet: "simlock" }, - async (fs) => { - await fs.mkdirp(`${xcodeDevices}/${third}`); - await fs.writeFileAtomic(`${xcodeDevices}/${third}/simlock-mark.json`, mark(instanceId)); - }, - { - message: `Refusing the ios device set: Xcode's device set still holds 1 of this Simlock's simulator(s) (${third}). Set drivers.ios.deviceSet back to default, run \`simlock nuke --delete-devices\` and \`simlock doctor --purge-orphans\`, then switch again. Delete any that remain with \`xcrun simctl delete \`.`, - path: xcodeDevices, - reason: "device-set-changed", - }, - ], - [ - "simlock with only unmarked, other-instance and corrupt devices in Xcode's set", - { deviceSet: "simlock" }, - async (fs) => { - await fs.mkdirp(`${xcodeDevices}/${first}`); - await fs.mkdirp(`${xcodeDevices}/${second}`); - await fs.writeFileAtomic(`${xcodeDevices}/${second}/simlock-mark.json`, mark("other")); - await fs.mkdirp(`${xcodeDevices}/${third}`); - await fs.writeFileAtomic(`${xcodeDevices}/${third}/simlock-mark.json`, "{broken"); - }, - undefined, - ], - [ - "default with Simlock's folder unreadable", - { deviceSet: "default" }, - async (fs) => { - await fs.mkdirp(ownRoot); - fs.defineFailure(ownRoot, "EACCES"); - }, - { path: ownRoot, reason: "unreadable" }, - ], - [ - "simlock with Xcode's folder unreadable", - { deviceSet: "simlock" }, - async (fs) => { - await fs.mkdirp(xcodeDevices); - fs.defineFailure(xcodeDevices, "EACCES"); - }, - { path: xcodeDevices, reason: "unreadable" }, - ], - ]; - - for (const [name, config, plant, expected] of steps) { - const filesystem = new MemoryFilesystem(); - await plant(filesystem); - const runner = new ScriptedProcessRunner([]); - const failure = await IosSimctlDriver.create({ - database: await memorySourceDatabase(), - clock: new FakeClock(), - coreSimulatorRoot, - driverConfig: config, - filesystem, - idGenerator: { generate: () => "device-1" }, - instanceId, - processRunner: runner, - simlockHome: "/home/.simlock", - }) - .then(() => undefined) - .catch((error: unknown) => error); - - expect(runner.calls, name).toEqual([]); - if (expected === undefined) { - expect(failure, name).toBeUndefined(); - } else { - expect(failure, name).toBeInstanceOf(OwnedRootError); - expect(failure, name).toMatchObject({ ...expected, platform: "ios" }); - } - } - }); - it.each([ ["simlock", { deviceRoot, deviceSet: "simlock" }, deviceRoot], ["default", { deviceSet: "default" }, `${coreSimulatorRoot}/Devices`], @@ -5789,7 +5706,7 @@ describe("IosSimctlDriver device set", () => { if (scoped) await plantManagedDevice(filesystem); else await filesystem.mkdirp(`${devicesDir}/${driverData.udid}/data`); const driver = await IosSimctlDriver.create({ - database: await seededDatabase(), + database: await seededDatabase({ setPath: scoped ? sourcesRoot : xcodeSourcesRoot }), clock: new FakeClock(), coreSimulatorRoot, driverConfig: config, @@ -5806,7 +5723,7 @@ describe("IosSimctlDriver device set", () => { [ "simctl", "--set", - scoped ? `${deviceRoot}/sources` : "/home/.simlock/devices/ios-sources", + scoped ? sourcesRoot : xcodeSourcesRoot, "clone", seedUdid, driverData.name, diff --git a/src/drivers/ios/index.ts b/src/drivers/ios/index.ts index 1a0014653..78148a415 100644 --- a/src/drivers/ios/index.ts +++ b/src/drivers/ios/index.ts @@ -84,7 +84,9 @@ import { fillSimctlDevice } from "./simctl-device.js"; import { IosPhysicalHandler } from "./physical.js"; import { createIosDeviceInput } from "./input/index.js"; import { iosRuntimeVersionFromId } from "./runtime-version.js"; -import { IosSourceTable, sourcesSetFor, type ReadySeed, type SourceRow } from "./source-data.js"; +import { IosSourceTable, type ReadySeed, type SourceRow } from "./source-data.js"; +import { seedIsStale, sourceStaleReason } from "./source-staleness.js"; +import { fitSourcesFolders, sourcesFolderOf, sourcesSetCheck } from "./sources-folder.js"; import { createIosScreenCapture } from "./screen-capture.js"; import { defaultIosDeviceRoot, type IosDriverConfig } from "./definition.js"; import { @@ -331,6 +333,7 @@ export class IosSimctlDriver implements Driver { readonly #slimByDefault: boolean; readonly #sources: IosSourceTable; readonly #sourcesSet: string; + readonly #ownsSourcesSet: (path: string) => boolean; #sourceMaker: string | undefined; #swept = false; readonly #seedMakes = new Map>(); @@ -340,6 +343,7 @@ export class IosSimctlDriver implements Driver { options: IosSimctlDriverOptions, deviceRoot: string, rootOptions: EnsureOwnedRootOptions | undefined, + sourcesSet: string, ) { this.rebootReadyBeforeGrant = rootOptions === undefined; this.#clock = options.clock; @@ -369,7 +373,12 @@ export class IosSimctlDriver implements Driver { this.#afterBoot = this.#afterBootFor(options); this.#slimByDefault = options.slimByDefault === true; this.#sources = new IosSourceTable(options.database); - this.#sourcesSet = sourcesSetFor(options.simlockHome, deviceRoot, rootOptions !== undefined); + this.#sourcesSet = sourcesSet; + this.#ownsSourcesSet = sourcesSetCheck( + sourcesSet, + options.simlockHome, + rootOptions === undefined ? undefined : deviceRoot, + ); this.screenCapture = createScreenCaptureFor( options, deviceRoot, @@ -409,13 +418,23 @@ export class IosSimctlDriver implements Driver { static async create(options: IosSimctlDriverOptions): Promise { const deviceSet = configuredDeviceSet(options); if (deviceSet === "default") { - await refuseOwnSetLeftovers(options.filesystem, join(options.simlockHome, "devices", "ios")); - return new IosSimctlDriver(options, xcodeDeviceSetPath(options), undefined); - } - await refuseDefaultSourcesLeftovers( - options.filesystem, + const ownRoot = join(options.simlockHome, "devices", "ios"); + await refuseOwnSetLeftovers(options.filesystem, ownRoot, [ + join(ownRoot, "sources"), + ...(await fitSourcesFolders(options, ownRoot, () => xcodeDeviceSetPath(options))), + ]); + const devices = xcodeDeviceSetPath(options); + const folder = await sourcesFolderOf(options, devices); + return new IosSimctlDriver(options, devices, undefined, folder); + } + await refuseDefaultSourcesLeftovers(options.filesystem, [ join(options.simlockHome, "devices", "ios-sources"), - ); + ...(options.coreSimulatorRoot === undefined + ? [] + : await fitSourcesFolders(options, xcodeDeviceSetPath(options), () => + configuredDeviceRoot(options), + )), + ]); if (options.coreSimulatorRoot !== undefined) { await refuseXcodeSetLeftovers( options.filesystem, @@ -434,7 +453,8 @@ export class IosSimctlDriver implements Driver { }; const deviceRoot = await ensureOwnedRoot(rootOptions); - return new IosSimctlDriver(options, deviceRoot, rootOptions); + const folder = await sourcesFolderOf(options, deviceRoot, true); + return new IosSimctlDriver(options, deviceRoot, rootOptions, folder); } get deviceRoot(): string { @@ -620,7 +640,7 @@ export class IosSimctlDriver implements Driver { if (row.kind !== "seed" || row.runtimeId !== runtimeId || row.udid === undefined) continue; const udid = row.udid; try { - await this.#deleteSeedInTurn(udid); + await this.#deleteSeedInTurn(udid, row.setPath); this.#sources.deleteRow(row.sourceId); } catch (error: unknown) { this.#logger?.warn( @@ -816,7 +836,7 @@ export class IosSimctlDriver implements Driver { const catalog = await this.#loadCatalog(); return [ ...rows.map((row) => { - const staleReason = sourceStaleReason(row, catalog); + const staleReason = sourceStaleReason(row, catalog, this.#sourcesSet); return { id: row.sourceId, kind: row.kind, @@ -886,12 +906,12 @@ export class IosSimctlDriver implements Driver { if (!(await this.#isOrphanSource(sourceId))) { throw new DriverCrashError(`iOS keeps no source ${sourceId}`); } - await this.#deleteSeedInTurn(sourceId); + await this.#deleteSeedInTurn(sourceId, this.#sourcesSet); return; } if (row.udid !== undefined) { const udid = row.udid; - await this.#deleteSeedInTurn(udid); + await this.#deleteSeedInTurn(udid, row.setPath); } this.#sources.deleteRow(sourceId); } @@ -980,7 +1000,7 @@ export class IosSimctlDriver implements Driver { if (row?.state !== "ready" || row.udid === undefined) { throw new DriverCrashError(`iOS keeps no ready source ${sourceId}`); } - const reason = sourceStaleReason(row, await this.#loadCatalog()); + const reason = sourceStaleReason(row, await this.#loadCatalog(), this.#sourcesSet); if (reason !== undefined) throw new DriverCrashError(`source ${sourceId} is stale: ${reason}`); return { udid: row.udid }; } @@ -997,13 +1017,14 @@ export class IosSimctlDriver implements Driver { return made; } - async #deleteSeedInTurn(udid: string): Promise { - await this.#seedTurns.takeToDelete(udid, () => this.#deleteSeedSimulator(udid)); + async #deleteSeedInTurn(udid: string, setPath: string): Promise { + await this.#seedTurns.takeToDelete(udid, () => this.#deleteSeedSimulator(udid, setPath)); } async #findOrMakeSeed(resolved: ResolvedIosSpec, specKey: string): Promise { const seed = this.#sources.findReadySeed(specKey); - if (seed !== undefined && !seedIsStale(seed, resolved)) return seed; + if (seed !== undefined && !seedIsStale(seed, resolved.runtime.build, this.#sourcesSet)) + return seed; if (seed !== undefined) await this.#destroySeed(seed); return this.#makeSeed(resolved, specKey); } @@ -1059,7 +1080,7 @@ export class IosSimctlDriver implements Driver { throw error; } this.#sources.markReady(sourceId, await this.#sizeOf(udid)); - return { sourceId, udid, runtimeBuild: resolved.runtime.build }; + return { sourceId, setPath: this.#sourcesSet, udid, runtimeBuild: resolved.runtime.build }; } catch (error: unknown) { this.#sources.deleteRow(sourceId); throw error; @@ -1081,7 +1102,7 @@ export class IosSimctlDriver implements Driver { async #removeLeftover(row: SourceRow): Promise { try { - if (row.udid !== undefined) await this.#deleteSeedSimulator(row.udid); + if (row.udid !== undefined) await this.#deleteSeedSimulator(row.udid, row.setPath); this.#sources.deleteRow(row.sourceId); } catch (error: unknown) { this.#logger?.warn( @@ -1127,24 +1148,28 @@ export class IosSimctlDriver implements Driver { } async #destroySeed(seed: ReadySeed): Promise { - await this.#deleteSeedInTurn(seed.udid); + await this.#deleteSeedInTurn(seed.udid, seed.setPath); this.#sources.deleteRow(seed.sourceId); } - async #deleteSeedSimulator(udid: string): Promise { - await this.#bestEffortShutdown(udid, this.#sourcesSet); + /** why: a row made by an earlier release names the set its simulator is in; `simctl --set` of any other set answers "Invalid device" for it. */ + async #deleteSeedSimulator(udid: string, setPath: string = this.#sourcesSet): Promise { + if (!this.#ownsSourcesSet(setPath)) { + // why: safety rule 1: a row names a path Simlock never made a sources folder of, so nothing there is its to delete. + this.#logger?.warn( + `left source ${udid} in ${setPath}, which is no sources folder of Simlock`, + ); + return; + } + await this.#bestEffortShutdown(udid, setPath); const args = ["delete", udid]; - const outcome = await this.#invokeSimctl(args, COMMAND_TIMEOUT_MS, this.#sourcesSet); + const outcome = await this.#invokeSimctl(args, COMMAND_TIMEOUT_MS, setPath); // 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.#checked(args, COMMAND_TIMEOUT_MS, outcome); } async #ensureSourcesSet(): Promise { - if (this.#rootOptions !== undefined) { - await this.#filesystem.mkdirp(this.#sourcesSet, { mode: 0o700 }); - return; - } await ensureOwnedRoot({ filesystem: this.#filesystem, idGenerator: this.#idGenerator, @@ -2658,29 +2683,6 @@ function alreadyBooted(stderr: string): boolean { return /current state:\s*Booted|already booted/i.test(stderr); } -/** why: a seed built on a runtime whose build changed no longer matches it; with no build on either side only the runtime's presence is checked, and a provision always has the runtime. */ -function seedIsStale(seed: ReadySeed, resolved: ResolvedIosSpec): boolean { - const current = resolved.runtime.build; - return seed.runtimeBuild !== undefined && current !== undefined && seed.runtimeBuild !== current; -} - -/** why: the phrase reads after "is stale:" in `doctor`, and is what a person acts on, so it names the runtime or device type by id. */ -function sourceStaleReason(row: SourceRow, catalog: SimctlCatalog): string | undefined { - const runtime = catalog.runtimes.find((entry) => entry.identifier === row.runtimeId); - if (runtime === undefined) return `runtime ${row.runtimeId} is not installed`; - if ( - row.runtimeBuild !== undefined && - runtime.build !== undefined && - row.runtimeBuild !== runtime.build - ) { - return `runtime ${row.runtimeId} changed from build ${row.runtimeBuild} to ${runtime.build}`; - } - if (!catalog.deviceTypes.some((entry) => entry.identifier === row.deviceTypeId)) { - return `device type ${row.deviceTypeId} is not available`; - } - return undefined; -} - function seedSpecKey(resolved: ResolvedIosSpec): string { return `${resolved.deviceType.identifier}\u0000${resolved.runtime.identifier}`; } diff --git a/src/drivers/ios/physical.test.ts b/src/drivers/ios/physical.test.ts index fbfaaf9b1..471e31898 100644 --- a/src/drivers/ios/physical.test.ts +++ b/src/drivers/ios/physical.test.ts @@ -40,7 +40,7 @@ const simctlListFixture = readFileSync( const SIMLOCK_HOME = "/home/.simlock"; const JSON_DIR = `${SIMLOCK_HOME}/devicectl`; -const DEVICE_ROOT = "/Devices"; +const DEVICE_ROOT = "/home/.simlock/devices/dev-ios"; const READ_LIMIT_MS = 30_000; const UNINSTALL_LIMIT_MS = 60_000; diff --git a/src/drivers/ios/source-data.ts b/src/drivers/ios/source-data.ts index 2c47f4a49..2fafffdd5 100644 --- a/src/drivers/ios/source-data.ts +++ b/src/drivers/ios/source-data.ts @@ -1,4 +1,3 @@ -import { join } from "node:path"; import type { SqliteDatabase, SqliteSchemaOwner } from "../../ports/index.js"; export const iosSourceDataOwner: SqliteSchemaOwner = { @@ -50,6 +49,7 @@ export interface NewSourceRow { export interface SourceRow { readonly sourceId: string; + readonly setPath: string; readonly kind: "seed" | "baseline"; readonly udid: string | undefined; readonly deviceTypeId: string; @@ -64,6 +64,7 @@ export interface SourceRow { export interface ReadySeed { readonly sourceId: string; + readonly setPath: string; readonly udid: string; readonly runtimeBuild: string | undefined; } @@ -117,12 +118,13 @@ export class IosSourceTable { findReadySeed(specKey: string): ReadySeed | undefined { const row = this.#database .prepare( - "SELECT source_id, udid, runtime_build FROM ios_source_data WHERE kind = 'seed' AND state = 'ready' AND spec_key = ?", + "SELECT source_id, set_path, udid, runtime_build FROM ios_source_data WHERE kind = 'seed' AND state = 'ready' AND spec_key = ?", ) .get(specKey); if (row === undefined) return undefined; return { sourceId: row["source_id"] as string, + setPath: row["set_path"] as string, udid: row["udid"] as string, runtimeBuild: (row["runtime_build"] as string | null) ?? undefined, }; @@ -162,12 +164,13 @@ 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, set_path, kind, udid, device_type_id, runtime_id, runtime_build, model, os_version, state, maker, size_bytes FROM ios_source_data ${where}`, ) .all(...parameters) .map((row) => ({ sourceId: row["source_id"] as string, + setPath: row["set_path"] as string, kind: row["kind"] as "seed" | "baseline", udid: (row["udid"] as string | null) ?? undefined, deviceTypeId: row["device_type_id"] as string, @@ -181,7 +184,3 @@ export class IosSourceTable { })); } } - -export function sourcesSetFor(simlockHome: string, deviceRoot: string, owned: boolean): string { - return owned ? join(deviceRoot, "sources") : join(simlockHome, "devices", "ios-sources"); -} diff --git a/src/drivers/ios/source-staleness.ts b/src/drivers/ios/source-staleness.ts new file mode 100644 index 000000000..1a8a3151d --- /dev/null +++ b/src/drivers/ios/source-staleness.ts @@ -0,0 +1,40 @@ +import type { SimctlCatalog } from "./simctl-parse.js"; +import type { ReadySeed, SourceRow } from "./source-data.js"; + +/** why: a seed in another set than today's sources folder was made before ADR 0076, and a copy of it cannot be fixed from; a seed built on a runtime whose build changed no longer matches it; with no build on either side only the runtime's presence is checked, and a provision always has the runtime. */ +export function seedIsStale( + seed: ReadySeed, + currentBuild: string | undefined, + sourcesSet: string, +): boolean { + if (seed.setPath !== sourcesSet) return true; + return ( + seed.runtimeBuild !== undefined && + currentBuild !== undefined && + seed.runtimeBuild !== currentBuild + ); +} + +/** why: the phrase reads after "is stale:" in `doctor`, and is what a person acts on, so it names the runtime or device type by id. */ +export function sourceStaleReason( + row: SourceRow, + catalog: SimctlCatalog, + sourcesSet: string, +): string | undefined { + if (row.setPath !== sourcesSet) { + return `saved in ${row.setPath}, which copies cannot be fixed from; save it again`; + } + const runtime = catalog.runtimes.find((entry) => entry.identifier === row.runtimeId); + if (runtime === undefined) return `runtime ${row.runtimeId} is not installed`; + if ( + row.runtimeBuild !== undefined && + runtime.build !== undefined && + row.runtimeBuild !== runtime.build + ) { + return `runtime ${row.runtimeId} changed from build ${row.runtimeBuild} to ${runtime.build}`; + } + if (!catalog.deviceTypes.some((entry) => entry.identifier === row.deviceTypeId)) { + return `device type ${row.deviceTypeId} is not available`; + } + return undefined; +} diff --git a/src/drivers/ios/sources-folder.test.ts b/src/drivers/ios/sources-folder.test.ts new file mode 100644 index 000000000..af96b393f --- /dev/null +++ b/src/drivers/ios/sources-folder.test.ts @@ -0,0 +1,242 @@ +import { readFileSync } from "node:fs"; + +import { describe, expect, it } from "vitest"; + +import { OwnedRootError, OWNED_ROOT_MARKER_FILE } from "../../core/index.js"; +import { FakeClock, MemoryFilesystem, ScriptedProcessRunner } from "../../ports/index.js"; +import { IosSimctlDriver } from "./index.js"; +import { memorySourceDatabase, plantSource } from "./testing.js"; +import { deviceRoot, driverData, instanceId, sourcesRoot } from "./test-slim.js"; + +const listFixture = readFileSync(new URL("./fixtures/simctl-list.json", import.meta.url), "utf8"); +const spec = { physical: false, model: "iPhone 16", osVersion: "26.5", platform: "ios" } as const; + +describe("IosSimctlDriver sources folder", () => { + const listInvocation = { + args: ["simctl", "--set", deviceRoot, "list", "-j", "devicetypes", "runtimes"], + command: "xcrun", + }; + const simctlIn = (set: string, ...args: readonly string[]) => ({ + args: ["simctl", "--set", set, ...args], + command: "xcrun", + }); + + it("makes the sources folder an owned root with a path as long as the device set's, under both settings", async () => { + const xcodeSim = "/Users/al/Library/Developer/CoreSimulator"; + const cases = [ + { + name: "simlock, default root", + home: "/home/.simlock", + config: {}, + devices: "/home/.simlock/devices/ios", + sources: "/home/.simlock/devices/src", + }, + { + name: "simlock, configured deviceRoot that fits", + home: "/home/.simlock", + config: { deviceRoot: "/Volumes/simulators/devices" }, + devices: "/Volumes/simulators/devices", + sources: "/home/.simlock/devices/src_", + }, + { + name: "default under the user's home", + home: "/Users/al/.simlock", + config: { deviceSet: "default" }, + devices: `${xcodeSim}/Devices`, + sources: `/Users/al/.simlock/devices/src${"_".repeat(19)}`, + madeBeforeCreate: true, + }, + { + name: "default with SIMLOCK_HOME on another volume", + home: "/Volumes/Fast/simlock", + config: { deviceSet: "default" }, + devices: `${xcodeSim}/Devices`, + sources: `/Volumes/Fast/simlock/devices/src${"_".repeat(16)}`, + madeBeforeCreate: true, + }, + { + name: "simlock with both under /private", + home: "/private/tmp/h", + config: {}, + devices: "/private/tmp/h/devices/ios", + sources: "/private/tmp/h/devices/src", + }, + { + name: "simlock with SIMLOCK_HOME reached through a link to /private", + home: "/tmp/h", + link: "/private/tmp/h", + config: { deviceRoot: "/private/tmp/h/devices/ios" }, + devices: "/private/tmp/h/devices/ios", + sources: "/private/tmp/h/devices/src", + }, + { + name: "default with Xcode's Devices not made yet", + home: "/Users/al/.simlock", + config: { deviceSet: "default" }, + devices: `${xcodeSim}/Devices`, + sources: `/Users/al/.simlock/devices/src${"_".repeat(19)}`, + }, + ] as const; + const seed = "00000000-0000-0000-0000-0000000000aa"; + const copy = "00000000-0000-0000-0000-0000000000bb"; + + for (const entry of cases) { + const scoped = !("deviceSet" in entry.config); + const step = (args: readonly (string | RegExp)[], stdout = "", anySet = true) => ({ + match: { args: ["simctl", ...(anySet ? ["--set", /.*/] : []), ...args], command: "xcrun" }, + result: { code: 0, stderr: "", stdout }, + }); + const runner = new ScriptedProcessRunner([ + step(["list", "-j", "devicetypes", "runtimes"], listFixture, scoped), + step( + ["create", "simlock-seed-device-1", driverData.deviceTypeId, driverData.runtimeId], + `${seed}\n`, + ), + step(["boot", seed]), + step(["bootstatus", seed, "-b"]), + step(["listapps", seed]), + step(["shutdown", seed]), + step(["clone", seed, /^simlock-/, entry.devices], `${copy}\n`), + ]); + const filesystem = new MemoryFilesystem(); + if ("link" in entry) { + await filesystem.mkdirp(entry.link); + filesystem.defineSymlink(entry.home, entry.link); + } else { + await filesystem.mkdirp(entry.home); + } + if ("madeBeforeCreate" in entry) await filesystem.mkdirp(entry.devices); + const driver = await IosSimctlDriver.create({ + database: await memorySourceDatabase(), + clock: new FakeClock(), + coreSimulatorRoot: xcodeSim, + driverConfig: entry.config, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + processRunner: runner, + simlockHome: entry.home, + }); + await filesystem.mkdirp(`${entry.devices}/${copy}/data`); + + await driver.resolveSpec({ model: "iPhone 16", osVersion: "26.5", platform: "ios" }); + await driver.provision(spec); + + const sourceSets = runner.calls.slice(1).map((call) => call.args[2]); + expect(sourceSets, entry.name).toEqual(Array.from({ length: 6 }, () => entry.sources)); + expect(entry.sources.length, entry.name).toBe(entry.devices.length); + await expect( + filesystem.exists(`${entry.sources}/${OWNED_ROOT_MARKER_FILE}`), + entry.name, + ).resolves.toBe(true); + } + }); + + it("refuses iOS with sources-path-unfit and one message per cause where no sources folder can have the device set's path length, and starts where one can", async () => { + const xcodeSim = "/Users/al/Library/Developer/CoreSimulator"; + const xcodeDevices = `${xcodeSim}/Devices`; + const longHome = "/Users/al/very-long-folder-name/ssssss"; + const cases = [ + { + name: "default, home under /private (a)", + home: "/private/tmp/h", + config: { deviceSet: "default" }, + message: `Refusing the ios device set: /private/tmp/h is under /private, where iOS stores each path in two spellings, but Xcode's set ${xcodeDevices} is not. Set SIMLOCK_HOME to a folder outside /tmp and /var.`, + }, + { + name: "default, home too long (b)", + home: longHome, + config: { deviceSet: "default" }, + message: `Refusing the ios device set: the sources folder must have a path as long as ${xcodeDevices} (49 characters), but ${longHome}/devices/ leaves 2 characters for its name, fewer than 3. Set SIMLOCK_HOME to a folder whose real path is at most 37 characters.`, + }, + { + name: "simlock, deviceRoot too short (c)", + home: "/home/.simlock", + config: { deviceRoot: "/d" }, + message: + "Refusing the ios device set: the sources folder must have a path as long as drivers.ios.deviceRoot /d (2 characters), but /home/.simlock/devices/ leaves 0 characters for its name, fewer than 3. Remove drivers.ios.deviceRoot, or set it to a path of at least 26 characters that is under /private only when SIMLOCK_HOME is.", + }, + { + name: "simlock, only the root under /private (c)", + home: "/home/.simlock", + config: { deviceRoot: "/private/tmp/simlock-devices" }, + message: + "Refusing the ios device set: the sources folder must have a path as long as drivers.ios.deviceRoot /private/tmp/simlock-devices (28 characters), but only one of /private/tmp/simlock-devices and /home/.simlock is under /private. Remove drivers.ios.deviceRoot, or set it to a path of at least 26 characters that is under /private only when SIMLOCK_HOME is.", + }, + { + name: "default, home that fits", + home: "/Users/al/.simlock", + config: { deviceSet: "default" }, + }, + ] as const; + + for (const entry of cases) { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp(entry.home); + const failure = await IosSimctlDriver.create({ + database: await memorySourceDatabase(), + clock: new FakeClock(), + coreSimulatorRoot: xcodeSim, + driverConfig: entry.config, + filesystem, + idGenerator: { generate: () => "device-1" }, + instanceId, + processRunner: new ScriptedProcessRunner([]), + simlockHome: entry.home, + }) + .then(() => undefined) + .catch((error: unknown) => error); + + if ("message" in entry) { + expect(failure, entry.name).toBeInstanceOf(OwnedRootError); + expect(failure, entry.name).toMatchObject({ + message: entry.message, + platform: "ios", + reason: "sources-path-unfit", + }); + } else { + expect(failure, entry.name).toBeUndefined(); + } + } + }); + + it("lists a baseline saved in another set as stale with the reason to save it again, one in the sources folder as fresh, and destroys the old one in its own set", async () => { + const [old, fresh] = [ + "00000000-0000-0000-0000-0000000002a0", + "00000000-0000-0000-0000-0000000002b0", + ] as [string, string]; + const oldSet = "/home/.simlock/devices/ios-sources"; + const kind = { deviceTypeId: driverData.deviceTypeId, runtimeId: driverData.runtimeId }; + const database = await memorySourceDatabase(); + plantSource(database, { ...kind, kind: "baseline", setPath: oldSet, udid: old }); + plantSource(database, { ...kind, kind: "baseline", setPath: sourcesRoot, udid: fresh }); + const runner = new ScriptedProcessRunner([ + { match: listInvocation, result: { code: 0, stderr: "", stdout: listFixture } }, + { match: simctlIn(oldSet, "shutdown", old) }, + { match: simctlIn(oldSet, "delete", old) }, + ]); + const driver = await IosSimctlDriver.create({ + database, + clock: new FakeClock(), + driverConfig: { deviceRoot }, + filesystem: new MemoryFilesystem(), + idGenerator: { generate: () => "device-1" }, + instanceId, + processRunner: runner, + simlockHome: "/home/.simlock", + }); + + const listed = await driver.listSources(); + + expect(listed.map((source) => source.staleReason)).toEqual([ + `saved in ${oldSet}, which copies cannot be fixed from; save it again`, + undefined, + ]); + const oldId = listed[0]?.id ?? ""; + await driver.destroySource(oldId); + expect(runner.calls.slice(1).map((call) => [call.args[2], call.args[3]])).toEqual([ + [oldSet, "shutdown"], + [oldSet, "delete"], + ]); + }); +}); diff --git a/src/drivers/ios/sources-folder.ts b/src/drivers/ios/sources-folder.ts new file mode 100644 index 000000000..9951852b3 --- /dev/null +++ b/src/drivers/ios/sources-folder.ts @@ -0,0 +1,159 @@ +import { basename, dirname, join } from "node:path"; + +import { OwnedRootError } from "../../core/index.js"; +import type { Filesystem } from "../../ports/index.js"; + +const SOURCES_FOLDER_NAME = "src"; + +interface SourcesFolderOptions { + /** why: set only for `simlock` with a configured `deviceRoot`: the refusal names that key, where under `default` it names Xcode's set. */ + readonly configuredRoot?: string; + readonly deviceSet: string; + readonly filesystem: Filesystem; + readonly simlockHome: string; +} + +/** + * why: ADR 0076 §1: a copy's stored paths are patched byte for byte, so the folder the sources live in + * has a real path exactly as long as the device set's: `src` followed by `_` to the needed length. + */ +async function sourcesFolderFor(options: SourcesFolderOptions): Promise { + const home = await realPathOf(options.filesystem, options.simlockHome); + const deviceSet = await realPathOf(options.filesystem, options.deviceSet); + const base = join(home, "devices", SOURCES_FOLDER_NAME); + refuseUnfit(options, home, deviceSet); + return base + "_".repeat(Math.max(0, deviceSet.length - base.length)); +} + +function refuseUnfit(options: SourcesFolderOptions, home: string, deviceSet: string): void { + const room = Math.max(0, deviceSet.length - join(home, "devices").length - 1); + const tooShort = `${home}/devices/ leaves ${String(room)} characters for its name, fewer than 3`; + const length = String(deviceSet.length); + const fitsLength = room >= SOURCES_FOLDER_NAME.length; + + if (options.configuredRoot === undefined) { + if (isUnderPrivate(home) && !isUnderPrivate(deviceSet)) { + throw unfit( + deviceSet, + `${home} is under /private, where iOS stores each path in two spellings, but Xcode's set ${deviceSet} is not. Set SIMLOCK_HOME to a folder outside /tmp and /var.`, + ); + } + if (!fitsLength) { + throw unfit( + deviceSet, + `the sources folder must have a path as long as ${deviceSet} (${length} characters), but ${tooShort}. Set SIMLOCK_HOME to a folder whose real path is at most ${String(deviceSet.length - 12)} characters.`, + ); + } + return; + } + + const split = isUnderPrivate(home) !== isUnderPrivate(deviceSet); + if (split || !fitsLength) { + const cause = split + ? `only one of ${options.configuredRoot} and ${home} is under /private` + : tooShort; + throw unfit( + deviceSet, + `the sources folder must have a path as long as drivers.ios.deviceRoot ${options.configuredRoot} (${length} characters), but ${cause}. Remove drivers.ios.deviceRoot, or set it to a path of at least ${String(home.length + 12)} characters that is under /private only when SIMLOCK_HOME is.`, + ); + } +} + +function unfit(deviceSet: string, explanation: string): OwnedRootError { + return new OwnedRootError( + `Refusing the ios device set: ${explanation}`, + "sources-path-unfit", + deviceSet, + "ios", + ); +} + +function isUnderPrivate(path: string): boolean { + return path === "/private" || path.startsWith("/private/"); +} + +/** why: Xcode's `Devices` folder or the other setting's root may not exist yet; its real path is its nearest existing parent's, joined with the rest. */ +async function realPathOf(filesystem: Filesystem, path: string): Promise { + try { + return await filesystem.realpath(path); + } catch (error: unknown) { + if (!isMissing(error)) throw error; + if (dirname(path) === path) return path; + return join(await realPathOf(filesystem, dirname(path)), basename(path)); + } +} + +function isMissing(error: unknown): boolean { + return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT"; +} + +export interface SourcesFolderContext { + readonly driverConfig: Readonly>; + readonly filesystem: Filesystem; + readonly simlockHome: string; +} + +/** why: `configured` is true only for `simlock`, where a `deviceRoot` the operator set is what the refusal names. */ +export function sourcesFolderOf( + options: SourcesFolderContext, + deviceSet: string, + configured = false, +): Promise { + const root = options.driverConfig["deviceRoot"]; + return sourcesFolderFor({ + ...(configured && typeof root === "string" ? { configuredRoot: root } : {}), + deviceSet, + filesystem: options.filesystem, + simlockHome: options.simlockHome, + }); +} + +/** + * why: the other setting's sources folder only matters when it can exist: where its length is unfit, nothing was ever made there, and it is read to nothing. + * A set of `todaySet` whose folder is the same one (a device set of exactly the home's length plus 12) is today's own, never a leftover. + */ +export async function fitSourcesFolders( + options: SourcesFolderContext, + deviceSet: string, + todaySet?: () => string, +): Promise { + const folder = await measured(options, deviceSet); + if (folder === undefined) return []; + let today: string | undefined; + try { + today = todaySet === undefined ? undefined : await measured(options, todaySet()); + } catch { + // why: a setting that cannot be measured has no folder to share; its own refusal comes later. + today = undefined; + } + return folder === today ? [] : [folder]; +} + +async function measured( + options: SourcesFolderContext, + deviceSet: string, +): Promise { + try { + return await sourcesFolderOf(options, deviceSet); + } catch { + // why: a set that cannot be measured is one the check reads anyway, and reports as unreadable. + return undefined; + } +} + +/** + * why: ADR 0076 §4: the only sets a row may name are today's sources folder and the ones earlier releases used: + * `devices/ios-sources`, and `sources` in the owned root (`ownedRoot` is undefined under `default`, which has none besides the home's `devices/ios`). + */ +export function sourcesSetCheck( + today: string, + simlockHome: string, + ownedRoot: string | undefined, +): (path: string) => boolean { + const known = new Set([ + today, + join(simlockHome, "devices", "ios-sources"), + join(ownedRoot ?? join(simlockHome, "devices", "ios"), "sources"), + ]); + return (path) => known.has(path); +} diff --git a/src/drivers/ios/test-slim.ts b/src/drivers/ios/test-slim.ts index 03d03dbfc..23c788832 100644 --- a/src/drivers/ios/test-slim.ts +++ b/src/drivers/ios/test-slim.ts @@ -16,7 +16,10 @@ import { memorySourceDatabase } from "./testing.js"; // why: the slim boot's fixtures, shared by the driver's two test files (index.test.ts is at its size limit). -export const deviceRoot = "/Devices"; +export const deviceRoot = "/home/.simlock/devices/dev-ios"; + +/** why: ADR 0076: the sources folder is as long as the device set (30 characters), `src` and four underscores under this home. */ +export const sourcesRoot = "/home/.simlock/devices/src____"; export const instanceId = "instance-1"; diff --git a/src/drivers/ios/testing.ts b/src/drivers/ios/testing.ts index 2d10c733e..025ce7256 100644 --- a/src/drivers/ios/testing.ts +++ b/src/drivers/ios/testing.ts @@ -15,6 +15,7 @@ export interface PlantedSource { readonly osVersion?: string; readonly runtimeBuild?: string; readonly runtimeId: string; + readonly setPath?: string; readonly sizeBytes?: number; readonly state?: "making" | "ready"; readonly udid?: string; @@ -33,7 +34,7 @@ export function plantSource(database: SqliteDatabase, source: PlantedSource): Sq osVersion: source.osVersion ?? "26.5", runtimeBuild: source.runtimeBuild, runtimeId: source.runtimeId, - setPath: "/Devices/sources", + setPath: source.setPath ?? "/home/.simlock/devices/src____", sourceId, specKey: `${source.deviceTypeId}\u0000${source.runtimeId}`, }); diff --git a/src/slow-e2e.test.ts b/src/slow-e2e.test.ts index ad5030064..434a5228a 100644 --- a/src/slow-e2e.test.ts +++ b/src/slow-e2e.test.ts @@ -51,6 +51,12 @@ function machine() { return { dir, repo, env, run, lock: env.SIMLOCK_SLOW_LOCK, lane: env.SIMLOCK_SLOW_TMP }; } +// why: the script removes and kills by a lane folder only when it holds the marker a run writes. +function markLane(lane: string): void { + mkdirSync(lane, { recursive: true }); + writeFileSync(join(lane, ".simlock-slow-lane"), ""); +} + // why: a process that is not this test's child, as a lane's are not the script's, so it is // reaped as soon as it stops instead of staying a zombie while spawnSync blocks; `group` makes // it lead its own process group, as the lane's runner does. @@ -116,7 +122,7 @@ describe("scripts/slow-e2e.sh", () => { it("clean stops a process whose environment names the lane's home, removes the home, and leaves other processes alone", async () => { const { lane, run } = machine(); - mkdirSync(lane, { recursive: true }); + markLane(lane); const leftover = idleNode({ ...process.env, SIMLOCK_HOME: join(lane, "simlock-e2e-abc") }); const other = idleNode({ ...process.env, SIMLOCK_HOME: join(tmpdir(), "simlock-e2e-other") }); await new Promise((resolve) => setTimeout(resolve, 300)); @@ -129,6 +135,23 @@ describe("scripts/slow-e2e.sh", () => { expect(existsSync(lane)).toBe(false); }); + it("clean, stop and a run refuse a lane folder without the marker, name SIMLOCK_SLOW_TMP, and leave it and its files", () => { + const { lane, lock, run } = machine(); + mkdirSync(lane, { recursive: true }); + writeFileSync(join(lane, "mine.txt"), "an operator's file"); + + const results = [run("clean"), run("stop"), run("check"), run()]; + + for (const result of results) { + expect([result.status, result.stderr]).toEqual([ + 69, + expect.stringContaining("SIMLOCK_SLOW_TMP"), + ]); + } + expect(readFileSync(join(lane, "mine.txt"), "utf8")).toBe("an operator's file"); + expect(existsSync(lock)).toBe(false); + }); + it("clean and stop delete, before removing the lane, the simulators whose durable mark names a lane instance, and no other", () => { const { dir, env, lane } = machine(); const devices = join(dir, "Devices"); @@ -148,6 +171,7 @@ describe("scripts/slow-e2e.sh", () => { mark("UNMARKED", undefined); mark("CORRUPT", "{not json"); const seedLane = () => { + markLane(lane); mkdirSync(join(lane, "simlock-e2e-abc"), { recursive: true }); mkdirSync(join(lane, "simlock-e2e-def", "gateway"), { recursive: true }); writeFileSync( diff --git a/src/source-hygiene.test.ts b/src/source-hygiene.test.ts index 53cb2b89d..371d3971c 100644 --- a/src/source-hygiene.test.ts +++ b/src/source-hygiene.test.ts @@ -29,7 +29,7 @@ type SizedFile = { path: string; lines: number }; const SHRINK_ONLY: Record = { "src/cli/index.test.ts": 11674, "src/drivers/ios/index.test.ts": 6208, - "src/drivers/ios/index.ts": 2700, + "src/drivers/ios/index.ts": 2702, "src/leasing/create-leasing.test.ts": 5389, "src/leasing/lease-acquisition-coordinator.ts": 1663, }; diff --git a/website/src/content/docs/docs/reference/events.mdx b/website/src/content/docs/docs/reference/events.mdx index f262e5246..0c375516e 100644 --- a/website/src/content/docs/docs/reference/events.mdx +++ b/website/src/content/docs/docs/reference/events.mdx @@ -196,7 +196,7 @@ as `incompatible` in `simlock --gateway worker list`. | `cleanup.executed` | Cleanup shut down or deleted an idle device. | `ruleName` (`idle-shutdown` or `idle-destroy`), `action` (`shutdown` or `destroy`), `target`, `reason` | Relayed | | `disk.pressure-detected` | Free disk space fell below `diskPressure.freeBytesThreshold`. Once per crossing. | `freeBytes`, `threshold` | Relayed | | `memory.pressure-changed` | A worker's memory pressure step changed, from `none`, `warming-paused` or `new-devices-paused` to another. Once per change, never per reading. See `memoryPressure.*`. | `from`, `to`, `cause` (`trigger` `level` or `floor`, `availablePercent`, `level` on macOS, `floorPercent` for a floor trigger; absent when `to` is `none`) | Relayed | -| `driver.root-rejected` | A platform did not start because of its device folder: the folder failed its ownership check, or (iOS) `drivers.ios.deviceSet` was invalid, conflicted with `ios.simulator.headless: false`, or was switched while simulators were left in the old set. `simlock doctor` says what to fix. Reasons include `invalid-device-set` and `device-set-changed`; `root` is then the configured value or the set that holds the leftovers. | `platform`, `root`, `reason` | Relayed | +| `driver.root-rejected` | A platform did not start because of its device folder: the folder failed its ownership check, or (iOS) `drivers.ios.deviceSet` was invalid, conflicted with `ios.simulator.headless: false`, or was switched while simulators were left in the old set. `simlock doctor` says what to fix. Reasons include `invalid-device-set`, `device-set-changed` and `sources-path-unfit` (the iOS sources folder cannot be given the device set's path length); `root` is then the configured value or the set that holds the leftovers. | `platform`, `root`, `reason` | Relayed | | `driver.adb-server-rejected` | The adb server Simlock runs for its emulators could not start (see `drivers.android.adbServerPort`), so Android did not start. | `port`, `reason` (`occupied`, `start-failed`, `invalid-port`) | Relayed |