Skip to content

Commit 2f8824a

Browse files
committed
fix(ios): one deadline per discovery, exact claims, route-level regression
Review follow-up. The 15s budget was per subprocess (two simctl probes, then a 3s ps read); discovery now shares one deadline across all three. The comments and changelog no longer claim "once per app generation": single-flight removes duplicate discoveries, each capture still waits up to its 1.5s slice for the in-flight one, and a failed discovery is forgotten so the next capture starts another. A route-level test runs the production resolver over a simctl that answers only when released: the first capture falls back within the slice, the released discovery then serves the bridge without a second spawn.
1 parent 4b59db8 commit 2f8824a

4 files changed

Lines changed: 122 additions & 25 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@
22

33
## Unreleased
44

5-
- Fixed: the iOS Simulator AX snapshot route no longer charges every capture for a slow app
6-
discovery. Discovery (`simctl launchctl list` through xcrun) takes seconds on a loaded host; a
7-
capture now waits a bounded slice for it, takes the XCTest fallback, and the discovery keeps
8-
running so the next capture joins or reuses it instead of paying the probe again. A `wait`
9-
issued right after `open` could previously lose its whole budget to repeated 3s probe timeouts
10-
and report `wait_capture_stalled` with the app already on screen.
5+
- Fixed: the iOS Simulator AX snapshot route bounds how long a capture waits for app discovery
6+
and stops starting a discovery per capture. Discovery (`simctl launchctl list` through xcrun)
7+
takes seconds on a loaded host; a capture now waits at most 1.5s for the one in-flight
8+
discovery, takes the XCTest fallback, and the discovery keeps running under its own 15s
9+
deadline for the captures that follow. Previously each capture ran its own probe with a 3s
10+
timeout on its critical path, so a `wait` issued right after `open` could spend its budget on
11+
probe timeouts and report `wait_capture_stalled` with the app already on screen.
1112
- Fixed: iOS snapshots no longer report `truncated: true` merely because a later backend produced
1213
them. The runner stamped every recovered capture as truncated — including a complete private-AX
1314
tree taken while the XCTest channel was penalized as slow — so a strict `is absent` / `wait absent`

‎packages/platform-apple/src/snapshot-route.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import { expect, test, vi } from 'vitest';
22
import type { DeviceInfo } from '@agent-device/kernel/device';
33
import { areIosSnapshotComparisonIdentitiesEqual } from '@agent-device/capture-kit/ios-snapshot-planning';
4+
import { createLocalAppleToolProvider, withAppleToolProvider } from './core/tool-provider.ts';
45
import { platformRuntimeHostFixture } from './runtime.fixtures.ts';
56
import { createAppleSnapshotRoute } from './snapshot-route.ts';
7+
import { createSimulatorSnapshotTargetResolver } from './snapshot-target.ts';
68
import type { SimulatorSnapshotSource, SnapshotSourceOutcome } from './snapshot-source-facade.ts';
79

810
const ios = {
@@ -202,6 +204,68 @@ test('cancelled acquisition does not start a fallback after the request aborts',
202204
expect(fallback).not.toHaveBeenCalled();
203205
});
204206

207+
test('a slow app discovery yields to the XCTest fallback within its wait slice, then serves the bridge', async () => {
208+
// The production resolver over a simctl whose `launchctl list` answers only when released,
209+
// the shape of a loaded CI host: the first capture must not sit on that probe.
210+
let release!: () => void;
211+
const released = new Promise<void>((resolve) => {
212+
release = resolve;
213+
});
214+
const run = vi.fn(async (args: string[]) => {
215+
if (args[0] === 'spawn') await released;
216+
return {
217+
stdout:
218+
args[0] === 'spawn'
219+
? `42\t0\tUIKitApplication:${input.options.appBundleId}[launch-a][rb-legacy]`
220+
: JSON.stringify({
221+
devices: { 'com.apple.CoreSimulator.SimRuntime.iOS-26-0': [{ udid: ios.id }] },
222+
}),
223+
stderr: '',
224+
exitCode: 0,
225+
};
226+
});
227+
const runCommand = vi.fn(async () => ({ stdout: 'start-a', stderr: '', exitCode: 0 }));
228+
const fallback = vi.fn(async () => runnerResult());
229+
const source = sourceReturning(bridgeAcquisition());
230+
const presentIosAcquisition = vi.fn(async () => ({
231+
backend: 'xctest' as const,
232+
producer: 'simulator-ax-bridge' as const,
233+
nodes: [{ index: 0, type: 'Application' }],
234+
}));
235+
const route = createAppleSnapshotRoute(
236+
{
237+
...platformRuntimeHostFixture(),
238+
snapshot: { captureSurface: vi.fn(), presentIosAcquisition },
239+
},
240+
{ source, resolveTarget: createSimulatorSnapshotTargetResolver() },
241+
);
242+
vi.useFakeTimers();
243+
try {
244+
await withAppleToolProvider(
245+
createLocalAppleToolProvider({ simctl: { run }, runCommand }),
246+
async () => {
247+
const first = route.capture(ios, input, signal(), fallback);
248+
await vi.advanceTimersByTimeAsync(1_500);
249+
const result = await first;
250+
expect(fallback).toHaveBeenCalledOnce();
251+
expect(result.warnings).toEqual([
252+
'Simulator AX snapshot unavailable (target-resolution-failed); used XCTest for an unverified app generation.',
253+
]);
254+
expect(source.acquire).not.toHaveBeenCalled();
255+
256+
release();
257+
await vi.advanceTimersByTimeAsync(0);
258+
const second = await route.capture(ios, input, signal(), fallback);
259+
expect(second.producer).toBe('simulator-ax-bridge');
260+
expect(fallback).toHaveBeenCalledOnce();
261+
expect(run.mock.calls.filter(([args]) => args[0] === 'spawn')).toHaveLength(1);
262+
},
263+
);
264+
} finally {
265+
vi.useRealTimers();
266+
}
267+
});
268+
205269
function bridgeAcquisition(): Extract<SnapshotSourceOutcome, { stage: 'acquired' }> {
206270
return {
207271
stage: 'acquired',

‎packages/platform-apple/src/snapshot-target.test.ts‎

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ const signal = () => new AbortController().signal;
1717

1818
function targetFixture() {
1919
const state = { pid: 42, launch: 'launch-a', start: 'start-a' as string | null };
20-
const run = vi.fn(async (args: string[]) => ({
20+
const run = vi.fn(async (args: string[], _options?: { timeoutMs?: number }) => ({
2121
stdout:
2222
args[0] === 'spawn'
2323
? `90\t0\tUIKitApplication:com.example.app.beta[wrong][rb-legacy]\n${state.pid}\t0\tUIKitApplication:${app}[${state.launch}][rb-legacy]`
@@ -27,11 +27,13 @@ function targetFixture() {
2727
stderr: '',
2828
exitCode: 0,
2929
}));
30-
const runCommand = vi.fn(async () => ({
31-
stdout: state.start ?? '',
32-
stderr: '',
33-
exitCode: state.start ? 0 : 1,
34-
}));
30+
const runCommand = vi.fn(
31+
async (_tool: string, _args: string[], _options?: { timeoutMs?: number }) => ({
32+
stdout: state.start ?? '',
33+
stderr: '',
34+
exitCode: state.start ? 0 : 1,
35+
}),
36+
);
3537
const provider = createLocalAppleToolProvider({ simctl: { run }, runCommand });
3638
const resolve = createSimulatorSnapshotTargetResolver();
3739
return {
@@ -202,3 +204,28 @@ test('a cancelled caller leaves discovery running for the next capture', async (
202204
expect(fixture.discoveryCount()).toBe(1);
203205
});
204206
});
207+
208+
test('one discovery shares a single deadline across its simctl probes and the identity read', async () => {
209+
const fixture = targetFixture();
210+
const release = deferredSpawn(fixture);
211+
vi.useFakeTimers();
212+
try {
213+
await withAppleToolProvider(fixture.provider, async () => {
214+
const pending = fixture.resolve(ios, app, signal());
215+
pending.catch(() => undefined);
216+
// The spawn ran 13s of the 15s discovery deadline before answering.
217+
await vi.advanceTimersByTimeAsync(13_000);
218+
release();
219+
await vi.advanceTimersByTimeAsync(0);
220+
await expect(fixture.resolve(ios, app, signal())).resolves.toMatchObject({ pid: 42 });
221+
222+
const spawnOptions = fixture.run.mock.calls.find(([args]) => args[0] === 'spawn')?.[1];
223+
expect(spawnOptions?.timeoutMs).toBe(15_000);
224+
const identityOptions = fixture.runCommand.mock.calls[0]?.[2];
225+
expect(identityOptions?.timeoutMs).toBeGreaterThan(0);
226+
expect(identityOptions?.timeoutMs).toBeLessThanOrEqual(2_000);
227+
});
228+
} finally {
229+
vi.useRealTimers();
230+
}
231+
});

‎packages/platform-apple/src/snapshot-target.ts‎

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,13 @@ import { readSnapshotTargetProcessStartTime } from './snapshot-process.ts';
66
/** Identity re-check of a cached target: one local `ps`, never CoreSimulator IPC. */
77
const TARGET_IDENTITY_TIMEOUT_MS = 3_000;
88
/**
9-
* Discovery spawns `simctl launchctl list` through xcrun, which takes ~1s on an idle Mac and
10-
* several seconds on a loaded CI host. One capture waits this long for it and then takes the
11-
* XCTest fallback while discovery keeps running; the next capture joins the same discovery
12-
* instead of starting another, so a slow host pays the probe once per app generation, never
13-
* once per capture. Sized for the healthy case so the first capture after `open` still reaches
14-
* the bridge on a responsive host.
9+
* How long one capture waits for an in-flight discovery before taking the XCTest fallback.
10+
* Discovery spawns `simctl launchctl list` through xcrun: ~1s on an idle Mac, several seconds
11+
* on a loaded CI host. The wait is per capture, so captures that keep arriving while the probe
12+
* runs each spend up to this long; the probe itself is shared and outlives them.
1513
*/
1614
const TARGET_DISCOVERY_WAIT_MS = 1_500;
17-
/** The budget of the discovery itself, detached from the capture that started it. */
15+
/** Overall deadline of one discovery (both simctl probes and the `ps` identity read). */
1816
const TARGET_DISCOVERY_TIMEOUT_MS = 15_000;
1917

2018
export type SimulatorSnapshotTarget = Readonly<{
@@ -51,8 +49,9 @@ export function createSimulatorSnapshotTargetResolver(): SimulatorSnapshotTarget
5149
targets.delete(key);
5250
let discovery = discoveries.get(key);
5351
if (!discovery) {
54-
// Detached from the caller's signal: a capture that gives up on the probe, or is
55-
// cancelled, must not take the probe down with it.
52+
// One discovery per target at a time, detached from the caller's signal: a capture that
53+
// gives up on it, or is cancelled, must not take it down. A discovery that fails is
54+
// forgotten, so the next capture starts a new one.
5655
discovery = resolveSimulatorSnapshotTarget(device, appBundleId, runtimeByDevice)
5756
.then((target) => {
5857
targets.set(key, target);
@@ -95,12 +94,13 @@ async function resolveSimulatorSnapshotTarget(
9594
appBundleId: string,
9695
runtimeByDevice: Map<string, Promise<string>>,
9796
): Promise<SimulatorSnapshotTarget> {
97+
const deadline = Date.now() + TARGET_DISCOVERY_TIMEOUT_MS;
9898
const [jobs, runtime] = await Promise.all([
9999
runSimctl(device, ['spawn', device.id, 'launchctl', 'list'], {
100100
allowFailure: true,
101-
timeoutMs: TARGET_DISCOVERY_TIMEOUT_MS,
101+
timeoutMs: remainingMs(deadline),
102102
}),
103-
readSimulatorRuntime(device, runtimeByDevice),
103+
readSimulatorRuntime(device, runtimeByDevice, deadline),
104104
]);
105105
if (jobs.exitCode !== 0) {
106106
throw targetError('simulator-target-probe-failed', device, appBundleId);
@@ -110,7 +110,7 @@ async function resolveSimulatorSnapshotTarget(
110110
throw targetError('simulator-target-unavailable', device, appBundleId);
111111
}
112112
const processStartTime = await readSnapshotTargetProcessStartTime(job.pid, {
113-
timeoutMs: TARGET_IDENTITY_TIMEOUT_MS,
113+
timeoutMs: Math.min(TARGET_IDENTITY_TIMEOUT_MS, remainingMs(deadline)),
114114
});
115115
if (!processStartTime) {
116116
throw targetError('simulator-target-identity-unavailable', device, appBundleId);
@@ -128,12 +128,13 @@ async function resolveSimulatorSnapshotTarget(
128128
async function readSimulatorRuntime(
129129
device: DeviceInfo,
130130
runtimeByDevice: Map<string, Promise<string>>,
131+
deadline: number,
131132
): Promise<string> {
132133
const existing = runtimeByDevice.get(device.id);
133134
if (existing) return await existing;
134135
const pending = runSimctl(device, ['list', 'devices', '-j'], {
135136
allowFailure: true,
136-
timeoutMs: TARGET_DISCOVERY_TIMEOUT_MS,
137+
timeoutMs: remainingMs(deadline),
137138
}).then((result) => {
138139
if (result.exitCode !== 0) throw targetError('simulator-runtime-probe-failed', device, '');
139140
const payload = JSON.parse(result.stdout) as {
@@ -167,6 +168,10 @@ function readApplicationJob(
167168
return undefined;
168169
}
169170

171+
function remainingMs(deadline: number): number {
172+
return Math.max(1, deadline - Date.now());
173+
}
174+
170175
function targetError(reason: string, device: DeviceInfo, appBundleId: string): AppError {
171176
return new AppError(
172177
'COMMAND_FAILED',

0 commit comments

Comments
 (0)