Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,33 @@ beforeEach(async () => {
);
mockWaitForRunner.mockResolvedValue(runnerResponse({ uptimeMs: 1 }));
});
// #4687: a session keeps `booted` from its open. When an external pool deletes that simulator, the
// runner start must name the missing device before xcodebuild waits out its destination timeout.
test('runner session start refuses a booted session simulator the listing no longer has', async () => {
const device = { ...IOS_SIMULATOR, id: 'runner-session-deleted-sim' };
const listing = JSON.stringify({
devices: {
'com.apple.CoreSimulator.SimRuntime.iOS-27-2': [{ udid: 'other-sim', state: 'Booted' }],
},
});
mockRunXcrun.mockImplementation(async (args: string[]) =>
args.includes('list')
? { exitCode: 0, stdout: listing, stderr: '' }
: { exitCode: 0, stdout: '', stderr: '' },
);

await assert.rejects(ensureRunnerSession(device, {}), (error: unknown) => {
assert.ok(error instanceof AppError);
assert.equal(error.code, 'DEVICE_NOT_FOUND');
assert.equal(error.details?.deviceId, device.id);
assert.equal(error.details?.dispatched, 'no');
// The runner cache is shared by every agent on the host; a missing device is no reason to wipe it.
assert.doesNotMatch(String(error.details?.hint), /apple-runner\/derived|clean:xcuitest/);
return true;
});
assert.equal(mockRunCmdBackground.mock.calls.length, 0);
});

test('runner session executes read-only commands without uptime preflight', async () => {
const session = makeRunnerSession({ state: 'starting' });
mockWaitForRunner.mockResolvedValueOnce(runnerResponse({ nodes: [], truncated: false }));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict';
import { beforeEach, test, vi } from 'vitest';
import { appleRunnerTestHost } from '../test-host.ts';
import { assertBootedSimulatorStillListed } from '../runner-simulator-presence.ts';
import { IOS_SIMULATOR } from './device-fixtures.ts';

// The refusal itself is covered on the runner start route in runner-session.test.ts; these cases
// pin the listings that must NOT refuse a start.
const DEVICE = { ...IOS_SIMULATOR, id: '54A531E3-0610-48D3-9904-07E9F028397F' };

const runXcrun = vi.fn();

beforeEach(() => {
runXcrun.mockReset();
appleRunnerTestHost.update({ runXcrun });
});

test('a listing that cannot be read does not refuse the start', async () => {
runXcrun.mockResolvedValueOnce({ exitCode: 1, stdout: '', stderr: 'CoreSimulator unavailable' });
await assertBootedSimulatorStillListed(DEVICE);

runXcrun.mockResolvedValueOnce({ exitCode: 0, stdout: 'not json', stderr: '' });
await assertBootedSimulatorStillListed(DEVICE);

runXcrun.mockRejectedValueOnce(new Error('simctl timed out'));
await assertBootedSimulatorStillListed(DEVICE);
});

test('a simulator this process just observed booted is not listed again', async () => {
appleRunnerTestHost.update({ wasSimulatorRecentlyObservedBooted: async () => true });

await assertBootedSimulatorStillListed(DEVICE);

assert.equal(runXcrun.mock.calls.length, 0);
});

test('a cancelled listing reports the cancellation, not a missing simulator', async () => {
const controller = new AbortController();
runXcrun.mockImplementation(async () => {
controller.abort(new Error('request canceled'));
throw new Error('aborted');
});

await assert.rejects(assertBootedSimulatorStillListed(DEVICE, controller.signal), /canceled/);
});
2 changes: 2 additions & 0 deletions packages/apple-runner/src/__tests__/test-host-defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ function appleToolingTestAdapters(): Pick<
| 'hasScopedAppleToolProvider'
| 'buildSimctlArgsForDevice'
| 'simulatorAddressFor'
| 'wasSimulatorRecentlyObservedBooted'
| 'resolveIosPhysicalDeviceControl'
> {
const simulatorSetPathFor = (device: DeviceInfo): string | undefined =>
Expand Down Expand Up @@ -74,6 +75,7 @@ function appleToolingTestAdapters(): Pick<
udid: device.id,
simulatorSetPath: simulatorSetPathFor(device),
}),
wasSimulatorRecentlyObservedBooted: async () => false,
resolveIosPhysicalDeviceControl: (device): IosPhysicalDeviceRunnerControl => ({
backend: device.iosPhysicalDeviceBackend === 'xctest' ? 'xctest' : 'coredevice',
resolveTunnel: async () => ({ tunnelIp: null }),
Expand Down
3 changes: 3 additions & 0 deletions packages/apple-runner/src/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ type AppleRunnerToolPort = {
) => Promise<Record<string, unknown> | null>;
hasScopedAppleToolProvider: () => boolean;
buildSimctlArgsForDevice: (device: DeviceInfo, args: readonly string[]) => ScopedSimctlCommand;
/** True while this process saw the simulator Booted moments ago, which proves it still exists. */
wasSimulatorRecentlyObservedBooted: (device: DeviceInfo) => Promise<boolean>;
/** A simulator udid with the simulator set that holds it; two devices match only when both do. */
simulatorAddressFor: (
device: DeviceInfo,
Expand Down Expand Up @@ -228,6 +230,7 @@ export const readApplePlistJson = delegate('readApplePlistJson');
export const hasScopedAppleToolProvider = delegate('hasScopedAppleToolProvider');
export const buildSimctlArgsForDevice = delegate('buildSimctlArgsForDevice');
export const simulatorAddressFor = delegate('simulatorAddressFor');
export const wasSimulatorRecentlyObservedBooted = delegate('wasSimulatorRecentlyObservedBooted');
export const resolveIosPhysicalDeviceControl = delegate('resolveIosPhysicalDeviceControl');
export const leaseOwnerStateDir = delegate('leaseOwnerStateDir');
export const hasDeviceClaimAuthority = delegate('hasDeviceClaimAuthority');
Expand Down
13 changes: 7 additions & 6 deletions packages/apple-runner/src/runner-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -867,19 +867,20 @@ export async function stopAllIosRunnerSessions(): Promise<string[]> {
}
}

function ensureBootedIfNeeded(device: DeviceInfo, signal?: AbortSignal): Promise<void> {
if (device.kind !== 'simulator') {
return Promise.resolve();
}
async function ensureBootedIfNeeded(device: DeviceInfo, signal?: AbortSignal): Promise<void> {
if (device.kind !== 'simulator') return;
if (device.booted) {
emitDiagnostic({
level: 'debug',
phase: 'ios_runner_startup_ensure_booted_skipped',
data: { deviceId: device.id },
});
return Promise.resolve();
// Loaded at a start only, outside the Apple facades' eager import closure.
const { assertBootedSimulatorStillListed } = await import('./runner-simulator-presence.ts');
await assertBootedSimulatorStillListed(device, signal);
return;
}
return ensureBooted(device, signal);
await ensureBooted(device, signal);
}

async function ensureBooted(device: DeviceInfo, signal?: AbortSignal): Promise<void> {
Expand Down
67 changes: 67 additions & 0 deletions packages/apple-runner/src/runner-simulator-presence.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { AppError } from '@agent-device/kernel/errors';
import type { DeviceInfo } from '@agent-device/kernel/device';
import {
buildSimctlArgsForDevice,
emitDiagnostic,
isRecord,
runXcrun,
wasSimulatorRecentlyObservedBooted,
} from './host.ts';

/** Budget for the listing that confirms a session's booted simulator still exists. */
const SIMULATOR_LISTING_TIMEOUT_MS = 5_000;

/**
* A session's `booted` fact dates from its open, and an external pool can delete the simulator since.
* xcodebuild then waits out its whole destination timeout and exits with a failure that reads like a
* broken runner cache (#4687). One listing before the launch names the missing simulator instead.
* A Booted observation this process made moments ago already proves the simulator exists, so an
* `open` that just checked readiness pays nothing.
*/
export async function assertBootedSimulatorStillListed(
device: DeviceInfo,
signal?: AbortSignal,
): Promise<void> {
if (await wasSimulatorRecentlyObservedBooted(device)) return;
let listed: boolean | undefined;
try {
const listing = await runXcrun(buildSimctlArgsForDevice(device, ['list', 'devices', '-j']), {
allowFailure: true,
timeoutMs: SIMULATOR_LISTING_TIMEOUT_MS,
signal,
});
listed = listing.exitCode === 0 ? simctlListingHasDevice(listing.stdout, device.id) : undefined;
} catch (error) {
signal?.throwIfAborted();
// CONSERVATIVE: a listing that failed proves nothing about the simulator, so the launch goes on.
emitDiagnostic({
level: 'warn',
phase: 'ios_runner_startup_simulator_listing_failed',
data: { deviceId: device.id, error: String(error) },
});
return;
}
// CONSERVATIVE: only a readable listing that omits the simulator refuses the start.
if (listed !== false) return;
throw new AppError('DEVICE_NOT_FOUND', `iOS simulator ${device.id} no longer exists`, {
deviceId: device.id,
...(device.simulatorSetPath ? { simulatorSetPath: device.simulatorSetPath } : {}),
dispatched: 'no',
hint: 'The simulator this session targets was deleted. Close this session, then open the app on an existing simulator (run devices to list them).',
});
}

/** Whether `simctl list devices -j` lists this udid; undefined when the output is not a listing. */
function simctlListingHasDevice(stdout: string, udid: string): boolean | undefined {
let payload: unknown;
try {
payload = JSON.parse(stdout);
} catch {
return undefined;
}
if (!isRecord(payload) || !isRecord(payload.devices)) return undefined;
return Object.values(payload.devices).some(
(devices) =>
Array.isArray(devices) && devices.some((entry) => isRecord(entry) && entry.udid === udid),
);
}
2 changes: 2 additions & 0 deletions packages/platform-apple/src/core/runner-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ export const appleRunnerHost: AppleRunnerHost = {
hasScopedAppleToolProvider,
buildSimctlArgsForDevice,
simulatorAddressFor,
wasSimulatorRecentlyObservedBooted: async (device) =>
(await import('./simulator.ts')).wasSimulatorRecentlyObservedBooted(device),
resolveIosPhysicalDeviceControl,
leaseOwnerStateDir: getRunnerLeaseOwnerStateDir,
runnerRuntimeSlot: runtimeSlot,
Expand Down
Loading