Skip to content

Commit e84bdc1

Browse files
committed
perf(ios): reuse process-verified snapshot targets
1 parent 37e3ef5 commit e84bdc1

9 files changed

Lines changed: 235 additions & 59 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { runAppleToolCommand } from './core/tool-provider.ts';
2+
3+
export async function readSnapshotTargetProcessStartTime(
4+
pid: number,
5+
options: { signal?: AbortSignal; timeoutMs: number },
6+
): Promise<string | null> {
7+
const result = await runAppleToolCommand('ps', ['-p', String(pid), '-o', 'lstart='], {
8+
allowFailure: true,
9+
signal: options.signal,
10+
timeoutMs: options.timeoutMs,
11+
});
12+
if (result.exitCode !== 0) return null;
13+
return result.stdout.trim() || null;
14+
}

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ const target = {
2121
pid: 42,
2222
generation: '42:launch-a',
2323
targetId: `${ios.id}:com.example.app`,
24+
processStartTime: 'target-start',
2425
} as const;
2526

2627
const input = { options: { appBundleId: 'com.example.app' } } as const;
@@ -117,6 +118,12 @@ test('stale bridge acquisition resolves the current generation before XCTest fal
117118
const result = await route.capture(ios, input, signal(), async () => runnerResult());
118119

119120
expect(resolveTarget).toHaveBeenCalledTimes(2);
121+
expect(resolveTarget).toHaveBeenLastCalledWith(
122+
ios,
123+
input.options.appBundleId,
124+
expect.any(AbortSignal),
125+
'refresh',
126+
);
120127
expect(result.comparisonIdentity?.lineage).toEqual({
121128
targetId: currentTarget.targetId,
122129
generation: currentTarget.generation,

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

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,11 @@ import {
2323
type SimulatorSnapshotSource,
2424
type SnapshotSourceFailure,
2525
} from './snapshot-source-facade.ts';
26-
import { resolveSimulatorSnapshotTarget, type SimulatorSnapshotTarget } from './snapshot-target.ts';
26+
import {
27+
createSimulatorSnapshotTargetResolver,
28+
type SimulatorSnapshotTarget,
29+
type SimulatorSnapshotTargetResolver,
30+
} from './snapshot-target.ts';
2731

2832
type SnapshotFallback = (input: CaptureSnapshotInput) => Promise<SnapshotResult>;
2933

@@ -41,11 +45,11 @@ export function createAppleSnapshotRoute(
4145
host: PlatformRuntimeHost,
4246
options: Readonly<{
4347
source?: SimulatorSnapshotSource;
44-
resolveTarget?: typeof resolveSimulatorSnapshotTarget;
48+
resolveTarget?: SimulatorSnapshotTargetResolver;
4549
}> = {},
4650
): AppleSnapshotRoute {
4751
const source = options.source ?? createSimulatorSnapshotSource();
48-
const resolveTarget = options.resolveTarget ?? resolveSimulatorSnapshotTarget;
52+
const resolveTarget = options.resolveTarget ?? createSimulatorSnapshotTargetResolver();
4953
const disabledGenerations = new Set<string>();
5054
const latestGeneration = new Map<string, string>();
5155

@@ -213,12 +217,12 @@ async function resolveFailureFallbackIdentity(
213217
device: DeviceInfo,
214218
appBundleId: string,
215219
signal: AbortSignal,
216-
resolveTarget: typeof resolveSimulatorSnapshotTarget,
220+
resolveTarget: SimulatorSnapshotTargetResolver,
217221
): Promise<FallbackIdentity> {
218222
if (failure.kind !== 'stale-target') return { lineage: target, residue: [] };
219223
try {
220224
return {
221-
lineage: await resolveTarget(device, appBundleId, signal),
225+
lineage: await resolveTarget(device, appBundleId, signal, 'refresh'),
222226
residue: [],
223227
};
224228
} catch (error) {

‎packages/platform-apple/src/snapshot-source/host.ts‎

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { findProjectRoot } from '@agent-device/host-kit/version';
2424
import { SnapshotSourceError, snapshotSourceError } from './errors.ts';
2525
import { remainingSnapshotSourceMs } from './deadline.ts';
2626
import type { SnapshotSourceHost, SnapshotSourceProcess, SnapshotSourceSocket } from './types.ts';
27+
import { readSnapshotTargetProcessStartTime } from '../snapshot-process.ts';
2728

2829
const BRIDGE_IDLE_TIMEOUT_SECONDS = 60;
2930
const MAX_PROCESS_LOG_BYTES = 64 * 1024;
@@ -48,23 +49,10 @@ export function createSnapshotSourceHost(): SnapshotSourceHost {
4849
emitDiagnostic,
4950
withDiagnosticTimer,
5051
processId: hostProcessId,
51-
readTargetProcessStartTime,
52+
readTargetProcessStartTime: readSnapshotTargetProcessStartTime,
5253
};
5354
}
5455

55-
async function readTargetProcessStartTime(
56-
pid: number,
57-
options: { signal?: AbortSignal; timeoutMs: number },
58-
): Promise<string | null> {
59-
const result = await runCmd('ps', ['-p', String(pid), '-o', 'lstart='], {
60-
allowFailure: true,
61-
signal: options.signal,
62-
timeoutMs: options.timeoutMs,
63-
});
64-
if (result.exitCode !== 0) return null;
65-
return result.stdout.trim() || null;
66-
}
67-
6856
function startSnapshotBridge(
6957
udid: string,
7058
bridgePath: string,

‎packages/platform-apple/src/snapshot-source/lifecycle.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,27 @@ test('the manager rejects a response carrying a previous target generation as st
314314
await manager.close();
315315
});
316316

317+
test('the manager rejects a cached target replaced before acquisition begins', async () => {
318+
const fixture = createLifecycleFixture({
319+
targetStartTimes: ['replacement-start', 'replacement-start'],
320+
});
321+
const manager = new SnapshotBridgeManager(fixture.host);
322+
await assert.rejects(
323+
manager.request({
324+
target: { ...target, processStartTime: 'original-start' },
325+
bridge,
326+
limits,
327+
maxDepth: 10,
328+
deadline: deadline(),
329+
}),
330+
(error: unknown) =>
331+
error instanceof SnapshotSourceError &&
332+
error.failureKind === 'stale-target' &&
333+
error.failureCode === 'target-process-changed',
334+
);
335+
await manager.close();
336+
});
337+
317338
test('the manager rejects a tree when the target process changes during acquisition', async () => {
318339
const fixture = createLifecycleFixture({ targetStartTimes: ['start-1', 'start-2'] });
319340
const manager = new SnapshotBridgeManager(fixture.host);

‎packages/platform-apple/src/snapshot-source/lifecycle.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,14 @@ export class SnapshotBridgeManager {
240240
generation: target.generation,
241241
});
242242
}
243+
if (target.processStartTime !== undefined && target.processStartTime !== startTime) {
244+
throw snapshotSourceError('stale-target', 'target-process-changed', {
245+
pid: target.pid,
246+
generation: target.generation,
247+
expectedStartTime: target.processStartTime,
248+
observedStartTime: startTime,
249+
});
250+
}
243251
return startTime;
244252
}
245253

‎packages/platform-apple/src/snapshot-source/types.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ export type SnapshotSourceTarget = Readonly<{
2121
pid: number;
2222
generation: string;
2323
targetId?: string;
24+
processStartTime?: string;
2425
}>;
2526

2627
export type SnapshotSourceRequest = Readonly<{
Lines changed: 121 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { expect, test, vi } from 'vitest';
22
import type { DeviceInfo } from '@agent-device/kernel/device';
33
import { createLocalAppleToolProvider, withAppleToolProvider } from './core/tool-provider.ts';
4-
import { resolveSimulatorSnapshotTarget } from './snapshot-target.ts';
4+
import { createSimulatorSnapshotTargetResolver } from './snapshot-target.ts';
55

66
const ios = {
77
platform: 'apple',
@@ -12,42 +12,128 @@ const ios = {
1212
target: 'mobile',
1313
booted: true,
1414
} as const satisfies DeviceInfo;
15+
const app = 'com.example.app';
16+
const signal = () => new AbortController().signal;
1517

16-
test('resolves exact app pid, runtime, and launch generation from simctl', async () => {
17-
const run = vi.fn(async (args: string[]) => {
18-
if (args[0] === 'spawn') {
19-
return {
20-
stdout: [
21-
'90\t0\tUIKitApplication:com.example.app.beta[wrong][rb-legacy]',
22-
'42\t0\tUIKitApplication:com.example.app[launch-a][rb-legacy]',
23-
].join('\n'),
24-
stderr: '',
25-
exitCode: 0,
26-
};
27-
}
28-
return {
29-
stdout: JSON.stringify({
30-
devices: {
31-
'com.apple.CoreSimulator.SimRuntime.iOS-26-0': [{ udid: ios.id }],
32-
},
33-
}),
34-
stderr: '',
35-
exitCode: 0,
36-
};
18+
function targetFixture() {
19+
const state = { pid: 42, launch: 'launch-a', start: 'start-a' as string | null };
20+
const run = vi.fn(async (args: string[]) => ({
21+
stdout:
22+
args[0] === 'spawn'
23+
? `90\t0\tUIKitApplication:com.example.app.beta[wrong][rb-legacy]\n${state.pid}\t0\tUIKitApplication:${app}[${state.launch}][rb-legacy]`
24+
: JSON.stringify({
25+
devices: { 'com.apple.CoreSimulator.SimRuntime.iOS-26-0': [{ udid: ios.id }] },
26+
}),
27+
stderr: '',
28+
exitCode: 0,
29+
}));
30+
const runCommand = vi.fn(async () => ({
31+
stdout: state.start ?? '',
32+
stderr: '',
33+
exitCode: state.start ? 0 : 1,
34+
}));
35+
const provider = createLocalAppleToolProvider({ simctl: { run }, runCommand });
36+
const resolve = createSimulatorSnapshotTargetResolver();
37+
return {
38+
state,
39+
run,
40+
runCommand,
41+
provider,
42+
resolve,
43+
discoveryCount: () => run.mock.calls.filter(([args]) => args[0] === 'spawn').length,
44+
};
45+
}
46+
47+
test('an unchanged OS process reuses its exact app target without another simctl spawn', async () => {
48+
const fixture = targetFixture();
49+
await withAppleToolProvider(fixture.provider, async () => {
50+
const first = await fixture.resolve(ios, app, signal());
51+
const second = await fixture.resolve(ios, app, signal());
52+
expect(second).toBe(first);
53+
expect(first).toEqual({
54+
udid: ios.id,
55+
runtime: 'com.apple.CoreSimulator.SimRuntime.iOS-26-0',
56+
pid: 42,
57+
generation: `42:UIKitApplication:${app}[launch-a][rb-legacy]:start-a`,
58+
targetId: `${ios.id}:${app}`,
59+
processStartTime: 'start-a',
60+
});
61+
expect(fixture.discoveryCount()).toBe(1);
62+
expect(fixture.runCommand).toHaveBeenCalledTimes(2);
3763
});
38-
const provider = createLocalAppleToolProvider({ simctl: { run } });
64+
});
3965

40-
const result = await withAppleToolProvider(
41-
provider,
42-
async () =>
43-
await resolveSimulatorSnapshotTarget(ios, 'com.example.app', new AbortController().signal),
44-
);
45-
46-
expect(result).toEqual({
47-
udid: 'ios-1',
48-
runtime: 'com.apple.CoreSimulator.SimRuntime.iOS-26-0',
49-
pid: 42,
50-
generation: '42:UIKitApplication:com.example.app[launch-a][rb-legacy]',
51-
targetId: 'ios-1:com.example.app',
66+
test('PID reuse cannot reuse a target from a different OS process start', async () => {
67+
const fixture = targetFixture();
68+
await withAppleToolProvider(fixture.provider, async () => {
69+
const first = await fixture.resolve(ios, app, signal());
70+
fixture.state.start = 'start-b';
71+
const second = await fixture.resolve(ios, app, signal());
72+
expect(second.pid).toBe(first.pid);
73+
expect(second.generation).not.toBe(first.generation);
74+
expect(second.processStartTime).toBe('start-b');
75+
expect(fixture.discoveryCount()).toBe(2);
76+
});
77+
});
78+
79+
test('a relaunched app resolves the replacement PID after the prior process disappears', async () => {
80+
const fixture = targetFixture();
81+
await withAppleToolProvider(fixture.provider, async () => {
82+
await fixture.resolve(ios, app, signal());
83+
fixture.runCommand.mockResolvedValueOnce({ stdout: '', stderr: '', exitCode: 1 });
84+
fixture.state.pid = 84;
85+
fixture.state.launch = 'launch-b';
86+
fixture.state.start = 'start-b';
87+
expect(await fixture.resolve(ios, app, signal())).toMatchObject({
88+
pid: 84,
89+
processStartTime: 'start-b',
90+
});
91+
expect(fixture.discoveryCount()).toBe(2);
92+
});
93+
});
94+
95+
test('unavailable OS identity never publishes or retains an unverified target', async () => {
96+
const fixture = targetFixture();
97+
await withAppleToolProvider(fixture.provider, async () => {
98+
await fixture.resolve(ios, app, signal());
99+
fixture.state.start = null;
100+
await expect(fixture.resolve(ios, app, signal())).rejects.toMatchObject({
101+
details: { reason: 'simulator-target-identity-unavailable' },
102+
});
103+
fixture.state.start = 'start-a';
104+
await fixture.resolve(ios, app, signal());
105+
expect(fixture.discoveryCount()).toBe(3);
106+
});
107+
});
108+
109+
test('stale acquisition refresh explicitly bypasses an otherwise live cached target', async () => {
110+
const fixture = targetFixture();
111+
await withAppleToolProvider(fixture.provider, async () => {
112+
await fixture.resolve(ios, app, signal());
113+
fixture.state.pid = 84;
114+
fixture.state.launch = 'launch-b';
115+
const next = await fixture.resolve(ios, app, signal(), 'refresh');
116+
expect(next.pid).toBe(84);
117+
expect(fixture.discoveryCount()).toBe(2);
118+
});
119+
});
120+
121+
test('target facts stay within their runtime owner', async () => {
122+
const fixture = targetFixture();
123+
await withAppleToolProvider(fixture.provider, async () => {
124+
await fixture.resolve(ios, app, signal());
125+
await createSimulatorSnapshotTargetResolver()(ios, app, signal());
126+
expect(fixture.discoveryCount()).toBe(2);
127+
});
128+
});
129+
130+
test('an aborted request cannot reuse a cached target', async () => {
131+
const fixture = targetFixture();
132+
await withAppleToolProvider(fixture.provider, async () => {
133+
await fixture.resolve(ios, app, signal());
134+
const controller = new AbortController();
135+
controller.abort(new Error('request-ended'));
136+
await expect(fixture.resolve(ios, app, controller.signal)).rejects.toThrow('request-ended');
137+
expect(fixture.runCommand).toHaveBeenCalledTimes(1);
52138
});
53139
});

0 commit comments

Comments
 (0)