Skip to content

Commit caae0b0

Browse files
committed
fix(ios-snapshot): prepare the AX bridge off the capture deadline
A first Simulator capture prepared the bridge inside its own request deadline: the toolchain identity probes, the source fingerprint and, on a cache miss, a clang build. On a fresh host that cost outruns any capture budget, the request signal ends it, and the route throws instead of falling back — `wait_capture_stalled` with `readableCaptures: 0` (#2491). Preparation is now a daemon-scoped single-flight attempt with its own ceiling. A capture waits a measured slice for it and otherwise serves from the XCTest runner while the attempt continues; `preparing` is a typed outcome that leaves the app generation's bridge eligible instead of opening the circuit.
1 parent ad9b906 commit caae0b0

8 files changed

Lines changed: 435 additions & 45 deletions

File tree

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,32 @@ test('typed bridge failure falls back once and disables retries for that app gen
302302
});
303303
});
304304

305+
test('a bridge still being prepared sends only that capture to the runner', async () => {
306+
const source = sourceReturning({
307+
stage: 'failed',
308+
failure: { kind: 'preparing', code: 'bridge-preparation-pending' },
309+
});
310+
const fallback = vi.fn(async () => runnerResult());
311+
const route = createAppleSnapshotRoute(platformRuntimeHostFixture(), {
312+
source,
313+
resolveTarget: vi.fn(async () => target),
314+
});
315+
316+
const first = await route.capture(ios, input, signal(), fallback);
317+
const second = await route.capture(ios, input, signal(), fallback);
318+
319+
// An attempt in flight says nothing about this app generation, so unlike a failed bridge it must
320+
// not close the circuit: a stable screen would never use the finished preparation.
321+
expect(source.acquire).toHaveBeenCalledTimes(2);
322+
expect(fallback).toHaveBeenCalledTimes(2);
323+
const pending = [
324+
'Simulator AX snapshot unavailable (bridge-preparation-pending); used XCTest for this app generation.',
325+
];
326+
expect(first.warnings).toEqual(pending);
327+
// The circuit-disabled sentence would mean the route gave up on the bridge for this generation.
328+
expect(second.warnings).toEqual(pending);
329+
});
330+
305331
test('a new app generation re-enables the bridge', async () => {
306332
const source = sourceReturning({
307333
stage: 'failed',

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

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ async function fallbackAfterFailure(
258258
disabledGenerations: Set<string>,
259259
cause?: unknown,
260260
): Promise<SnapshotResult> {
261-
disabledGenerations.add(generationKey(failedTarget));
261+
disableGenerationFor(failure, failedTarget, disabledGenerations);
262262
emitRouteDiagnostic(
263263
failure.code,
264264
{ id: failedTarget.udid },
@@ -277,6 +277,21 @@ async function fallbackAfterFailure(
277277
);
278278
}
279279

280+
/**
281+
* A failed bridge is evidence about this app generation, so its captures take the runner until the
282+
* generation is rebaselined. A bridge that is merely still being prepared is evidence about the
283+
* daemon's build queue instead: the same generation must be able to use it as soon as it exists,
284+
* which is what let one cold host cost every later capture of a stable screen (#2491).
285+
*/
286+
function disableGenerationFor(
287+
failure: SnapshotSourceFailure,
288+
failedTarget: SimulatorSnapshotTarget,
289+
disabledGenerations: Set<string>,
290+
): void {
291+
if (failure.kind === 'preparing') return;
292+
disabledGenerations.add(generationKey(failedTarget));
293+
}
294+
280295
async function runFallback(
281296
deviceId: string,
282297
input: CaptureSnapshotInput,

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

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,12 @@ import {
1717
SNAPSHOT_SOURCE_PROTOCOL_VERSION,
1818
SNAPSHOT_SOURCE_VERSION,
1919
} from './protocol.ts';
20-
import type { SnapshotSourceHost, SnapshotSourceProcess, SnapshotSourceSocket } from './types.ts';
20+
import type {
21+
SnapshotSourceHost,
22+
SnapshotSourceOutcome,
23+
SnapshotSourceProcess,
24+
SnapshotSourceSocket,
25+
} from './types.ts';
2126

2227
test('the Simulator AX source returns raw acquisition facts and discloses unsupported facets', async () => {
2328
const root = await mkdtemp(path.join(os.tmpdir(), 'agent-device-snapshot-adapter-'));
@@ -144,8 +149,8 @@ test('the Simulator AX source refuses a tree that ends at content another proces
144149
}
145150
});
146151

147-
test('preparation consumes the same acquisition deadline as bridge I/O', async () => {
148-
const root = await mkdtemp(path.join(os.tmpdir(), 'agent-device-snapshot-adapter-deadline-'));
152+
test('a capture reports a cold preparation instead of spending its deadline on it', async () => {
153+
const root = await mkdtemp(path.join(os.tmpdir(), 'agent-device-snapshot-adapter-preparing-'));
149154
const sourceRoot = path.join(root, 'source');
150155
const cacheRoot = path.join(root, 'cache');
151156
await (await import('@agent-device/host-kit/host-file')).ensureHostDirectory(sourceRoot);
@@ -154,19 +159,33 @@ test('preparation consumes the same acquisition deadline as bridge I/O', async (
154159
await writeFile(path.join(sourceRoot, 'SnapshotBridgeRuntime.h'), 'native header');
155160
await writeFile(path.join(sourceRoot, 'SnapshotBridgeCapture.h'), 'native header');
156161
await writeFile(path.join(sourceRoot, 'SnapshotBridgeCapture.m'), 'native header');
157-
const fixture = createAdapterHost(150);
162+
const fixture = createAdapterHost(300);
158163
const source = createSimulatorSnapshotSource({ host: fixture.host, sourceRoot, cacheRoot });
159-
const request = createIosSnapshotRequest();
160-
const hint = deriveIosCaptureHint(request);
164+
const hint = deriveIosCaptureHint(createIosSnapshotRequest());
165+
const target = { ...targetForTest(), generation: 'generation-1' };
161166

162167
try {
163-
const outcome = await source.acquire({
164-
target: { ...targetForTest(), generation: 'generation-1' },
168+
const startedAt = performance.now();
169+
let outcome: SnapshotSourceOutcome = await source.acquire({
170+
target,
165171
hint,
166172
limits: { maxDurationMs: 100 },
167173
});
174+
const waitedMs = performance.now() - startedAt;
168175
assert.equal(outcome.stage, 'failed');
169-
if (outcome.stage === 'failed') assert.equal(outcome.failure.kind, 'timeout');
176+
if (outcome.stage === 'failed') {
177+
assert.equal(outcome.failure.kind, 'preparing');
178+
assert.equal(outcome.failure.code, 'bridge-preparation-pending');
179+
}
180+
// The capture ends on its own budget while the attempt it started keeps compiling detached;
181+
// waiting for that build is what let a cold host cancel captures that had a working runner.
182+
assert.ok(waitedMs < 300, `capture waited ${waitedMs}ms for a 300ms build`);
183+
184+
for (let attempt = 0; attempt < 20 && outcome.stage !== 'acquired'; attempt += 1) {
185+
await new Promise((resolve) => setTimeout(resolve, 50));
186+
outcome = await source.acquire({ target, hint });
187+
}
188+
assert.equal(outcome.stage, 'acquired');
170189
assert.equal(fixture.builds, 1);
171190
} finally {
172191
await source.close();

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

Lines changed: 14 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,17 @@ import type {
44
IosSnapshotAcquisition,
55
IosViewportEvidence,
66
} from '@agent-device/contracts/ios-snapshot';
7-
import { ensureSnapshotBridgeBinary } from './cache.ts';
87
import { createSnapshotSourceDeadline, remainingSnapshotSourceMs } from './deadline.ts';
98
import { AcceptedDepthHints, type DepthHintDecision } from './depth-hints.ts';
109
import { asSnapshotSourceError, snapshotSourceError } from './errors.ts';
1110
import { SnapshotBridgeManager } from './lifecycle.ts';
1211
import { resolveSnapshotSourceLimits } from './limits.ts';
1312
import { readSnapshotBridgeRecovery, type SnapshotBridgeEnvelope } from './protocol.ts';
13+
import { createSnapshotBridgePreparation } from './preparation.ts';
1414
import { decodeSnapshotBridgeTree } from './tree.ts';
1515
import { createSnapshotSourceHost } from './host.ts';
1616
import type {
1717
SnapshotSourceHost,
18-
SnapshotSourceBridgeBinary,
1918
SnapshotSourceLimits,
2019
SnapshotSourceOutcome,
2120
SnapshotSourceRequest,
@@ -41,36 +40,17 @@ export function createSimulatorSnapshotSource(
4140
const host = options.host ?? createSnapshotSourceHost();
4241
const manager = new SnapshotBridgeManager(host);
4342
const depthHints = new AcceptedDepthHints();
44-
const preparedBinaries = new Map<string, SnapshotSourceBridgeBinary>();
43+
// Preparation is daemon-scoped work: it reads the toolchain identity, fingerprints the bridge
44+
// source and may compile it. It runs detached so no capture's deadline pays for it (#2491).
45+
const preparation = createSnapshotBridgePreparation({
46+
host,
47+
limits: resolveSnapshotSourceLimits(options.limits),
48+
producer: SNAPSHOT_SOURCE_PRODUCER,
49+
sourceRoot: options.sourceRoot,
50+
cacheRoot: options.cacheRoot,
51+
});
4552
let closed = false;
4653

47-
const prepare = async (
48-
input: Readonly<{
49-
runtime: string;
50-
limits: SnapshotSourceLimits;
51-
deadline: import('./deadline.ts').SnapshotSourceDeadline;
52-
}>,
53-
) => {
54-
if (closed) throw snapshotSourceError('unsupported', 'source-closed');
55-
const prepared = preparedBinaries.get(input.runtime);
56-
if (prepared) return prepared;
57-
const completed = await host.withDiagnosticTimer(
58-
'ios.snapshot-source.prepare',
59-
async () =>
60-
await ensureSnapshotBridgeBinary({
61-
host,
62-
runtime: input.runtime,
63-
limits: input.limits,
64-
deadline: input.deadline,
65-
sourceRoot: options.sourceRoot,
66-
cacheRoot: options.cacheRoot,
67-
}),
68-
{ producer: SNAPSHOT_SOURCE_PRODUCER },
69-
);
70-
preparedBinaries.set(input.runtime, completed);
71-
return completed;
72-
};
73-
7454
const acquire = async (request: SnapshotSourceRequest): Promise<SnapshotSourceOutcome> => {
7555
try {
7656
if (closed) throw snapshotSourceError('unsupported', 'source-closed');
@@ -83,11 +63,11 @@ export function createSimulatorSnapshotSource(
8363
return await host.withDiagnosticTimer(
8464
'ios.snapshot-source.acquire',
8565
async () => {
86-
const bridge = await prepare({
87-
runtime: request.target.runtime,
88-
limits,
66+
const bridge = await preparation.readyBinary(
67+
request.target.runtime,
8968
deadline,
90-
});
69+
'bridge-preparation-deadline',
70+
);
9171
const decision = depthHints.consume(request.target, requestedLevels, explicitDepth);
9272
const envelope = await manager.request({
9373
target: request.target,

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ const APP_ERROR_CODE_BY_KIND: Readonly<Record<SnapshotSourceFailureKind, string>
99
cancelled: 'COMMAND_FAILED',
1010
'process-crash': 'COMMAND_FAILED',
1111
'transport-failure': 'COMMAND_FAILED',
12+
preparing: 'COMMAND_FAILED',
1213
};
1314

1415
export class SnapshotSourceError extends AppError {
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
import assert from 'node:assert/strict';
2+
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
3+
import os from 'node:os';
4+
import path from 'node:path';
5+
import { test } from 'vitest';
6+
import { createSnapshotSourceDeadline } from './deadline.ts';
7+
import { createSnapshotSourceHost } from './host.ts';
8+
import { resolveSnapshotSourceLimits } from './limits.ts';
9+
import {
10+
createSnapshotBridgePreparation,
11+
SNAPSHOT_BRIDGE_PREPARATION_RETRY_AFTER_MS,
12+
} from './preparation.ts';
13+
import type { SnapshotSourceHost } from './types.ts';
14+
15+
const BRIDGE_SOURCES = [
16+
'SnapshotBridge.m',
17+
'SnapshotBridgeRuntime.m',
18+
'SnapshotBridgeRuntime.h',
19+
'SnapshotBridgeCapture.h',
20+
'SnapshotBridgeCapture.m',
21+
];
22+
23+
test('one detached preparation answers every capture that arrives while it runs', async () => {
24+
const root = await writeBridgeSource('preparation-shared-');
25+
let releaseBuild = () => {};
26+
const gate = new Promise<void>((resolve) => {
27+
releaseBuild = resolve;
28+
});
29+
const fixture = createPreparationHost({ build: 'pending', gate });
30+
const preparation = createSnapshotBridgePreparation({
31+
host: fixture.host,
32+
limits: resolveSnapshotSourceLimits({}),
33+
producer: 'test',
34+
sourceRoot: path.join(root, 'source'),
35+
cacheRoot: path.join(root, 'cache'),
36+
});
37+
38+
try {
39+
const pending = await Promise.all([
40+
preparation.readyBinary('ios-simulator', deadline(300), 'test-deadline').then(
41+
() => undefined,
42+
(error: unknown) => failureOf(error),
43+
),
44+
preparation.readyBinary('ios-simulator', deadline(300), 'test-deadline').then(
45+
() => undefined,
46+
(error: unknown) => failureOf(error),
47+
),
48+
]);
49+
for (const failure of pending) {
50+
assert.equal(failure?.kind, 'preparing');
51+
assert.equal(failure?.code, 'bridge-preparation-pending');
52+
}
53+
assert.equal(fixture.builds, 1);
54+
55+
releaseBuild();
56+
const binary = await preparation.readyBinary('ios-simulator', deadline(5_000), 'test-deadline');
57+
assert.ok(binary.path.startsWith(path.join(root, 'cache')));
58+
assert.ok(binary.cacheKey.length > 0);
59+
assert.equal(fixture.builds, 1);
60+
} finally {
61+
await rm(root, { recursive: true, force: true });
62+
}
63+
});
64+
65+
test('a failed preparation is reported to each capture without rebuilding per capture', async () => {
66+
const root = await writeBridgeSource('preparation-failed-');
67+
const fixture = createPreparationHost({ build: 'fails', gate: undefined });
68+
let clockMs = 0;
69+
const preparation = createSnapshotBridgePreparation({
70+
host: fixture.host,
71+
limits: resolveSnapshotSourceLimits({}),
72+
producer: 'test',
73+
sourceRoot: path.join(root, 'source'),
74+
cacheRoot: path.join(root, 'cache'),
75+
now: () => clockMs,
76+
});
77+
78+
try {
79+
const first = await preparation
80+
.readyBinary(
81+
'ios-simulator',
82+
deadline(5_000, () => clockMs),
83+
'test-deadline',
84+
)
85+
.then(
86+
() => undefined,
87+
(error: unknown) => failureOf(error),
88+
);
89+
assert.equal(first?.kind, 'unsupported');
90+
assert.equal(first?.code, 'native-build-failed');
91+
assert.equal(fixture.builds, 1);
92+
93+
const again = await preparation
94+
.readyBinary(
95+
'ios-simulator',
96+
deadline(5_000, () => clockMs),
97+
'test-deadline',
98+
)
99+
.then(
100+
() => undefined,
101+
(error: unknown) => failureOf(error),
102+
);
103+
assert.deepEqual(again, first);
104+
assert.equal(fixture.builds, 1);
105+
106+
clockMs += SNAPSHOT_BRIDGE_PREPARATION_RETRY_AFTER_MS + 1;
107+
const retried = await preparation
108+
.readyBinary(
109+
'ios-simulator',
110+
deadline(5_000, () => clockMs),
111+
'test-deadline',
112+
)
113+
.then(
114+
() => undefined,
115+
(error: unknown) => failureOf(error),
116+
);
117+
assert.equal(retried?.code, 'native-build-failed');
118+
assert.equal(fixture.builds, 2);
119+
} finally {
120+
await rm(root, { recursive: true, force: true });
121+
}
122+
});
123+
124+
async function writeBridgeSource(prefix: string): Promise<string> {
125+
const root = await mkdtemp(path.join(os.tmpdir(), `agent-device-bridge-${prefix}`));
126+
const sourceRoot = path.join(root, 'source');
127+
await (await import('@agent-device/host-kit/host-file')).ensureHostDirectory(sourceRoot);
128+
for (const name of BRIDGE_SOURCES) {
129+
await writeFile(path.join(sourceRoot, name), 'native source');
130+
}
131+
return root;
132+
}
133+
134+
function deadline(timeoutMs: number, now: () => number = Date.now) {
135+
return createSnapshotSourceDeadline(timeoutMs, undefined, now);
136+
}
137+
138+
function failureOf(error: unknown): Readonly<{ kind: string; code: string }> | undefined {
139+
const failure = (error as Readonly<{ failureKind?: unknown; failureCode?: unknown }>) ?? {};
140+
return typeof failure.failureKind === 'string' && typeof failure.failureCode === 'string'
141+
? { kind: failure.failureKind, code: failure.failureCode }
142+
: undefined;
143+
}
144+
145+
function createPreparationHost(
146+
build: Readonly<{ build: 'pending' | 'fails'; gate: Promise<void> | undefined }>,
147+
): Readonly<{ host: SnapshotSourceHost; builds: number }> {
148+
const fixture: { host: SnapshotSourceHost; builds: number } = {
149+
host: undefined as never,
150+
builds: 0,
151+
};
152+
const host: SnapshotSourceHost = {
153+
...createSnapshotSourceHost(),
154+
run: async (command, args) => {
155+
if (command === 'xcrun' && args.includes('clang')) {
156+
fixture.builds += 1;
157+
if (build.build === 'pending') await build.gate;
158+
if (build.build === 'fails') return { stdout: '', stderr: 'boom', exitCode: 1 };
159+
await writeFile(args.at(-1)!, 'bridge-binary');
160+
return { stdout: '', stderr: '', exitCode: 0 };
161+
}
162+
return {
163+
stdout:
164+
command === 'xcodebuild'
165+
? 'Xcode 16.4\nBuild version 16F6'
166+
: command === 'sw_vers'
167+
? '15.6'
168+
: command === 'uname'
169+
? 'arm64'
170+
: '26.2',
171+
stderr: '',
172+
exitCode: 0,
173+
};
174+
},
175+
};
176+
fixture.host = host;
177+
return fixture;
178+
}

0 commit comments

Comments
 (0)