Skip to content

Commit 3dd240c

Browse files
committed
fix(ios-runner): scope runner reuse to one simulator set and name the set in destination errors
- Reuse and lease adoption now require the same simulator: one udid in one resolved simulator set. The lease records the scoped set; a runner leased or registered for another set is stopped and restarted, never reused. - The runner derives a simulator's set through simulatorAddressFor, which now resolves the set path, instead of restating the simulator predicate. - simulator_set_destination_not_found names the set and the selected Xcode in its message. The Xcode version comes from the toolchain fingerprint owner, so external and adopted sessions report it too; the artifact no longer carries its own copy. The hint points at the error instead of printing field names. - The legacy XCTestDevices restore runs before adoption, so both startup routes pass through it, and a step another daemon already took counts as done instead of failing the startup.
1 parent 18078a3 commit 3dd240c

22 files changed

Lines changed: 372 additions & 105 deletions

‎packages/platform-apple/src/core/__tests__/simctl.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,13 @@ test('simulatorAddressFor carries the set of iOS-family simulators only', () =>
106106
});
107107
});
108108

109+
test('simulatorAddressFor names a blank set path as the default set', () => {
110+
assert.deepEqual(simulatorAddressFor({ ...IOS_SIMULATOR, simulatorSetPath: ' ' }), {
111+
udid: 'sim-1',
112+
simulatorSetPath: undefined,
113+
});
114+
});
115+
109116
function compileTimeSimulatorScopeProof(): void {
110117
// @ts-expect-error A simulator address is minted from its DeviceInfo, never written by hand.
111118
const forged: SimulatorAddress = { udid: 'sim-1', simulatorSetPath: undefined };

‎packages/platform-apple/src/core/runner-host.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import type { AppleRunnerHost } from '../runner/index.ts';
22
import { publishFileSync, acquireProcessLock, withProcessLock } from '@agent-device/host-kit/file';
3-
import { resolveIosSimulatorDeviceSetPath } from '@agent-device/kernel/device-isolation';
43

54
import {
65
isCommandTimeoutError,
@@ -42,7 +41,7 @@ import {
4241
getRunnerDeviceClaimAuthorityProbe,
4342
getRunnerLeaseOwnerStateDir,
4443
} from './runner-owner-state.ts';
45-
import { buildSimctlArgsForDevice } from './simctl.ts';
44+
import { buildSimctlArgsForDevice, simulatorAddressFor } from './simctl.ts';
4645
import { readApplePlistJson, runAppleToolCommand, runXcrun } from './tool-provider.ts';
4746

4847
/**
@@ -86,7 +85,6 @@ export const appleRunnerHost: AppleRunnerHost = {
8685
createTtlMemo,
8786
parseBooleanLiteral,
8887
isRecord,
89-
resolveIosSimulatorDeviceSetPath,
9088
emitRequestProgress,
9189
getRequestSignal,
9290
isRequestCanceled,
@@ -96,6 +94,7 @@ export const appleRunnerHost: AppleRunnerHost = {
9694
runXcrun,
9795
readApplePlistJson,
9896
buildSimctlArgsForDevice,
97+
simulatorAddressFor,
9998
resolveIosPhysicalDeviceControl,
10099
visitXmlPlistEntries,
101100
leaseOwnerStateDir: getRunnerLeaseOwnerStateDir,

‎packages/platform-apple/src/core/simctl.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,19 @@ import type { ScopedSimctlArgs } from '@agent-device/contracts/platform-runtime-
55
import { runXcrun, simctlCommand, type ScopedSimctlCommand } from './tool-provider.ts';
66

77
declare const simulatorAddress: unique symbol;
8-
/** A simulator udid with the set that holds it; minted only from a DeviceInfo. */
8+
/**
9+
* A simulator udid with the resolved set that holds it (undefined for the default set); minted only
10+
* from a DeviceInfo. Two devices name the same simulator only when both fields match.
11+
*/
912
export type SimulatorAddress = Readonly<{ udid: string; simulatorSetPath: string | undefined }> & {
1013
readonly [simulatorAddress]: true;
1114
};
1215

1316
export function simulatorAddressFor(device: DeviceInfo): SimulatorAddress {
1417
const simulatorSetPath =
15-
isIosFamily(device) && device.kind === 'simulator' ? device.simulatorSetPath : undefined;
18+
isIosFamily(device) && device.kind === 'simulator'
19+
? resolveIosSimulatorDeviceSetPath(device.simulatorSetPath)
20+
: undefined;
1621
return Object.freeze({ udid: device.id, simulatorSetPath }) as SimulatorAddress;
1722
}
1823

‎packages/platform-apple/src/runner/__tests__/runner-adoption-route.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ afterEach(() => {
126126
function writeDetachedLease(device: DeviceInfo): void {
127127
const lease: RunnerLease = {
128128
...buildRunnerLease({
129-
deviceId: device.id,
129+
device,
130130
sessionId: `${device.id}:${RUNNER_PORT}:1`,
131131
runnerPid: RUNNER_PID,
132132
port: RUNNER_PORT,

‎packages/platform-apple/src/runner/__tests__/runner-adoption.test.ts‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ let expectedDerived: string;
109109
function writeStaleLeaseFor(device: DeviceInfo, overrides: Partial<RunnerLease> = {}): RunnerLease {
110110
const lease: RunnerLease = {
111111
...buildRunnerLease({
112-
deviceId: device.id,
112+
device,
113113
sessionId: `${device.id}:50700:1`,
114114
runnerPid: 424242,
115115
port: 50700,
@@ -165,7 +165,7 @@ test('readStaleRunnerLease returns dead-owner leases and skips owned ones', () =
165165
// A lease written by this process is owned, not stale.
166166
writeRunnerLease(
167167
buildRunnerLease({
168-
deviceId: simulator.id,
168+
device: simulator,
169169
sessionId: `${simulator.id}:50700:2`,
170170
runnerPid: 424242,
171171
port: 50700,
@@ -324,15 +324,38 @@ test('adoption accepts a legacy lease whose live pid is runner-shaped', async ()
324324
});
325325

326326
test('a runner for a simulator in a custom simulator set is adopted', async () => {
327-
writeStaleLease();
327+
const scopedDevice = { ...simulator, simulatorSetPath: '/custom/device-set' };
328+
writeStaleLeaseFor(scopedDevice);
328329
mockIsProcessAlive.mockReturnValue(true);
329330
mockSendRunnerCommandOnce.mockResolvedValue(new Response(JSON.stringify({ ok: true })));
330331

331-
const scopedDevice = { ...simulator, simulatorSetPath: '/custom/device-set' };
332332
const session = await tryAdoptRunnerSessionFromLease(scopedDevice, {});
333333

334334
expect(session?.state).toBe('ready');
335335
expect(session?.device.simulatorSetPath).toBe('/custom/device-set');
336+
const restamped = JSON.parse(
337+
fs.readFileSync(path.join(leaseDir, `${scopedDevice.id}.json`), 'utf8'),
338+
) as RunnerLease;
339+
expect(restamped.simulatorSetPath).toBe('/custom/device-set');
340+
});
341+
342+
test('a runner leased for the same udid in another simulator set is never adopted', async () => {
343+
mockIsProcessAlive.mockReturnValue(true);
344+
mockSendRunnerCommandOnce.mockResolvedValue(new Response(JSON.stringify({ ok: true })));
345+
const tenantA = { ...simulator, simulatorSetPath: '/custom/tenant-a' };
346+
const tenantB = { ...simulator, simulatorSetPath: '/custom/tenant-b' };
347+
348+
for (const [leasedFor, requested] of [
349+
[tenantA, tenantB],
350+
[tenantA, simulator],
351+
[simulator, tenantA],
352+
] as const) {
353+
writeStaleLeaseFor(leasedFor);
354+
355+
expect(await tryAdoptRunnerSessionFromLease(requested, {})).toBeNull();
356+
expect(adoptionRefusalReason()).toBe('simulator_set_mismatch');
357+
}
358+
expect(mockSendRunnerCommandOnce).not.toHaveBeenCalled();
336359
});
337360

338361
test('adoption is skipped when the runner process is dead', async () => {

‎packages/platform-apple/src/runner/__tests__/runner-device-set.test.ts‎

Lines changed: 93 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,24 @@
11
import assert from 'node:assert/strict';
22
import fs from 'node:fs';
33
import path from 'node:path';
4-
import { test } from 'vitest';
4+
import { afterEach, beforeEach, test, vi } from 'vitest';
5+
import { resetAllProcessMemosForTests } from '@agent-device/kernel/ttl-memo';
56
import { IOS_DEVICE, IOS_SIMULATOR, TVOS_SIMULATOR } from './device-fixtures.ts';
67
import { mkdtempForTestSync } from './tmp-dir.ts';
8+
import { STUBBED_APPLE_TOOLCHAIN, stubAppleToolchainProbes } from './apple-toolchain-fixtures.ts';
79
import {
10+
isSameRunnerSimulator,
811
restoreLegacyXctestDeviceSetRedirect,
912
runnerSimulatorSetFailureDetails,
1013
xcodebuildDestinationArgs,
1114
} from '../runner-device-set.ts';
1215

16+
const toolchainProbe = stubAppleToolchainProbes();
17+
beforeEach(resetAllProcessMemosForTests);
18+
afterEach(() => {
19+
vi.restoreAllMocks();
20+
});
21+
1322
const DESTINATION = 'platform=iOS Simulator,id=sim-1';
1423

1524
test('a scoped-set simulator names its set to xcodebuild beside the destination', () => {
@@ -42,14 +51,38 @@ test('the default set, a blank set path and a physical device leave the destinat
4251
}
4352
});
4453

45-
test('a failure reports the scoped set and the Xcode only for a scoped-set simulator', () => {
54+
test('a failure reports the scoped set and the selected Xcode only for a scoped-set simulator', () => {
4655
const scoped = { ...IOS_SIMULATOR, simulatorSetPath: '/tmp/tenant-a/simulators' };
4756

48-
assert.deepEqual(runnerSimulatorSetFailureDetails(scoped, '26.2'), {
57+
assert.deepEqual(runnerSimulatorSetFailureDetails(scoped), {
4958
simulatorSetPath: '/tmp/tenant-a/simulators',
50-
xcodeVersion: '26.2',
59+
xcodeVersion: STUBBED_APPLE_TOOLCHAIN.xcodeVersion,
5160
});
52-
assert.deepEqual(runnerSimulatorSetFailureDetails(IOS_SIMULATOR, '26.2'), {});
61+
assert.deepEqual(runnerSimulatorSetFailureDetails(IOS_SIMULATOR), {});
62+
});
63+
64+
test('a failure whose Xcode cannot be read still names the scoped set, and no Xcode key', () => {
65+
toolchainProbe.mockReturnValue({ exitCode: 1, stdout: '', stderr: 'xcode-select: error' });
66+
67+
assert.deepEqual(
68+
runnerSimulatorSetFailureDetails({ ...IOS_SIMULATOR, simulatorSetPath: '/tmp/tenant-a/sims' }),
69+
{ simulatorSetPath: '/tmp/tenant-a/sims' },
70+
);
71+
});
72+
73+
test('one udid in two simulator sets names two simulators', () => {
74+
const tenantA = { ...IOS_SIMULATOR, simulatorSetPath: '/tmp/tenant-a/simulators' };
75+
76+
assert.equal(isSameRunnerSimulator(tenantA, { ...tenantA }), true);
77+
assert.equal(
78+
isSameRunnerSimulator(IOS_SIMULATOR, { ...IOS_SIMULATOR, simulatorSetPath: ' ' }),
79+
true,
80+
);
81+
assert.equal(isSameRunnerSimulator(tenantA, IOS_SIMULATOR), false);
82+
assert.equal(
83+
isSameRunnerSimulator(tenantA, { ...tenantA, simulatorSetPath: '/tmp/tenant-b/simulators' }),
84+
false,
85+
);
5386
});
5487

5588
type LegacyRedirect = {
@@ -140,3 +173,58 @@ test('a host with no leftovers is left untouched', () => {
140173
assert.equal(fs.existsSync(paths.xctestDeviceSetPath), false);
141174
assert.equal(fs.existsSync(paths.backupPath), false);
142175
});
176+
177+
/** Runs `step` with the other daemon's whole restore landing just before this daemon's `call`. */
178+
function withOtherDaemonFinishingBefore(
179+
call: 'readlinkSync' | 'unlinkSync' | 'renameSync',
180+
paths: LegacyRedirect,
181+
device: Parameters<typeof restoreLegacyXctestDeviceSetRedirect>[0],
182+
): void {
183+
const original = fs[call] as (...args: unknown[]) => unknown;
184+
vi.spyOn(fs, call).mockImplementationOnce(((...args: unknown[]) => {
185+
restoreLegacyXctestDeviceSetRedirect(device, paths.xctestDeviceSetPath);
186+
return original.apply(fs, args);
187+
}) as never);
188+
restoreLegacyXctestDeviceSetRedirect(device, paths.xctestDeviceSetPath);
189+
}
190+
191+
test('a daemon whose unlink or rename the other daemon already made finishes the restore', () => {
192+
for (const call of ['unlinkSync', 'renameSync'] as const) {
193+
const paths = makeLegacyPaths();
194+
fs.mkdirSync(path.join(paths.backupPath, 'HOST-UDID'), { recursive: true });
195+
fs.symlinkSync(paths.scopedSetPath, paths.xctestDeviceSetPath, 'dir');
196+
197+
withOtherDaemonFinishingBefore(call, paths, IOS_SIMULATOR);
198+
199+
assert.equal(fs.lstatSync(paths.xctestDeviceSetPath).isSymbolicLink(), false, call);
200+
assert.ok(fs.existsSync(path.join(paths.xctestDeviceSetPath, 'HOST-UDID')), call);
201+
assert.equal(fs.existsSync(paths.backupPath), false, call);
202+
assert.ok(fs.existsSync(path.join(paths.scopedSetPath, 'SCOPED-UDID')), call);
203+
vi.restoreAllMocks();
204+
}
205+
});
206+
207+
test('a daemon whose link the other daemon removed before it was read leaves the host alone', () => {
208+
const paths = makeLegacyPaths();
209+
const scoped = { ...IOS_SIMULATOR, simulatorSetPath: paths.scopedSetPath };
210+
fs.symlinkSync(paths.scopedSetPath, paths.xctestDeviceSetPath, 'dir');
211+
212+
withOtherDaemonFinishingBefore('readlinkSync', paths, scoped);
213+
214+
assert.equal(fs.lstatSync(paths.xctestDeviceSetPath, { throwIfNoEntry: false }), undefined);
215+
assert.ok(fs.existsSync(path.join(paths.scopedSetPath, 'SCOPED-UDID')));
216+
});
217+
218+
test('an unlink that fails while the link is still there is reported', () => {
219+
const paths = makeLegacyPaths();
220+
fs.mkdirSync(paths.backupPath);
221+
fs.symlinkSync(paths.scopedSetPath, paths.xctestDeviceSetPath, 'dir');
222+
vi.spyOn(fs, 'unlinkSync').mockImplementationOnce(() => {
223+
throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' });
224+
});
225+
226+
assert.throws(
227+
() => restoreLegacyXctestDeviceSetRedirect(IOS_SIMULATOR, paths.xctestDeviceSetPath),
228+
/EACCES/,
229+
);
230+
});

‎packages/platform-apple/src/runner/__tests__/runner-early-exit-diagnosis.test.ts‎

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
import assert from 'node:assert/strict';
22
import fs from 'node:fs';
33
import path from 'node:path';
4-
import { test } from 'vitest';
4+
import { beforeEach, test } from 'vitest';
55
import type { AppError } from '@agent-device/kernel/errors';
6+
import { resetAllProcessMemosForTests } from '@agent-device/kernel/ttl-memo';
67
import type { ExecBackgroundResult } from '@agent-device/host-kit/command';
78
import { buildRunnerEarlyExitError } from '../runner-startup-transport.ts';
89
import { readRunnerLogTail } from '../runner-io.ts';
910
import type { RunnerSession } from '../runner-session-types.ts';
1011
import { mkdtempForTestSync } from './tmp-dir.ts';
12+
import { STUBBED_APPLE_TOOLCHAIN, stubAppleToolchainProbes } from './apple-toolchain-fixtures.ts';
13+
14+
const toolchainProbe = stubAppleToolchainProbes();
15+
beforeEach(resetAllProcessMemosForTests);
1116

1217
// Verbatim xcodebuild output from an iPhone that was not in the signing account.
1318
// macOS localizes the installer prose, so the machine-readable anchors are the
@@ -171,6 +176,8 @@ const SCOPED_DESTINATION_NOT_FOUND_LOG = [
171176
'\t\t{ platform:iOS Simulator, id:sim-1 }',
172177
].join('\n');
173178

179+
// An external xctestrun: the session carries no build of its own, so the Xcode it names comes from
180+
// the toolchain the host selects.
174181
function simulatorSessionFailingWith(log: string, simulatorSetPath?: string): RunnerSession {
175182
return {
176183
...sessionFailingWith(log),
@@ -183,19 +190,19 @@ function simulatorSessionFailingWith(log: string, simulatorSetPath?: string): Ru
183190
booted: true,
184191
simulatorSetPath,
185192
},
193+
deviceId: 'sim-1',
186194
xctestrunArtifact: {
187195
xctestrunPath: '/tmp/runner.xctestrun',
188196
derived: '/tmp/derived',
189-
cache: 'exact',
197+
cache: 'external',
190198
artifact: 'valid',
191199
buildMs: 0,
192-
xctestrunPathSource: 'manifest',
193-
xcodeVersion: '27.1',
200+
xctestrunPathSource: 'external',
194201
},
195202
};
196203
}
197204

198-
test('a scoped-set simulator test-without-building cannot find names its set and the Xcode', async () => {
205+
test('a scoped-set simulator whose destination is missing names its set and the Xcode', async () => {
199206
const error = (await buildRunnerEarlyExitError({
200207
session: simulatorSessionFailingWith(SCOPED_DESTINATION_NOT_FOUND_LOG, '/tmp/tenant-a/sims'),
201208
port: 8100,
@@ -204,7 +211,30 @@ test('a scoped-set simulator test-without-building cannot find names its set and
204211
assert.equal(error.details?.reason, 'simulator_set_destination_not_found');
205212
assert.match(String(error.details?.hint), /-DVTSimulatorSetLocation/);
206213
assert.equal(error.details?.simulatorSetPath, '/tmp/tenant-a/sims');
207-
assert.equal(error.details?.xcodeVersion, '27.1');
214+
assert.equal(error.details?.xcodeVersion, STUBBED_APPLE_TOOLCHAIN.xcodeVersion);
215+
assert.match(
216+
error.message,
217+
new RegExp(
218+
`simulator set /tmp/tenant-a/sims with Xcode ${STUBBED_APPLE_TOOLCHAIN.xcodeVersion}$`,
219+
),
220+
);
221+
});
222+
223+
test('a scoped-set destination error whose Xcode cannot be read still names the set', async () => {
224+
toolchainProbe.mockReturnValue({ exitCode: 1, stdout: '', stderr: 'xcode-select: error' });
225+
226+
const error = (await buildRunnerEarlyExitError({
227+
session: simulatorSessionFailingWith(SCOPED_DESTINATION_NOT_FOUND_LOG, '/tmp/tenant-a/sims'),
228+
port: 8100,
229+
})) as AppError;
230+
231+
assert.equal(error.details?.reason, 'simulator_set_destination_not_found');
232+
assert.equal(error.details?.simulatorSetPath, '/tmp/tenant-a/sims');
233+
assert.equal('xcodeVersion' in (error.details ?? {}), false);
234+
assert.match(
235+
error.message,
236+
/simulator set \/tmp\/tenant-a\/sims with Xcode \(version unreadable\)$/,
237+
);
208238
});
209239

210240
test('a default-set simulator early exit keeps its boot-failure reason', async () => {

‎packages/platform-apple/src/runner/__tests__/runner-requests.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ test('runner-internal request sites build exactly their runner-requests.json ent
101101
});
102102
writeRunnerLease({
103103
...buildRunnerLease({
104-
deviceId: IOS_SIMULATOR.id,
104+
device: IOS_SIMULATOR,
105105
sessionId: `${IOS_SIMULATOR.id}:${server.port}:1`,
106106
runnerPid: 424242,
107107
port: server.port,

0 commit comments

Comments
 (0)