Skip to content

Commit b21efb0

Browse files
committed
refactor(apple): own the toolchain probe budget in platform-apple and trim narration
COLD_TOOLCHAIN_PROBE_TIMEOUT_MS moves from @agent-device/host-kit/command to runner/apple-runner-platform.ts, beside the SDK names the probes are run against. Both Apple toolchain probers import it directly, so the runner host port no longer carries a coldToolchainProbeTimeoutMs() accessor for a plain number. isCommandTimeoutError stays in host-kit, where the exec layer stamps the detail it reads. The comments that narrated control flow the code already shows are gone; the cold-start stall rationale (on the constant), the spawnSync cancellation limitation (on the probe clock) and one line per phase-deadline creation site remain.
1 parent c24d42c commit b21efb0

12 files changed

Lines changed: 54 additions & 165 deletions

File tree

‎packages/host-kit/src/command.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
export {
22
coerceExecResult,
3-
COLD_TOOLCHAIN_PROBE_TIMEOUT_MS,
43
type CommandExecutorOverride,
54
type ExecBackgroundOptions,
65
type ExecBackgroundResult,

‎packages/host-kit/src/internal/exec.ts‎

Lines changed: 3 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -593,12 +593,9 @@ function createTimeoutError(
593593
}
594594

595595
/**
596-
* True only for the COMMAND_FAILED error this module raises when it kills a
597-
* command at its own `timeoutMs` — the structured signal both timeout sites
598-
* above stamp on `details.timeoutMs`. Callers that retry a timed-out command
599-
* classify with this instead of matching the message text, so a command whose
600-
* own output happens to say "timed out after 10ms" is not mistaken for a
601-
* timeout the exec layer imposed.
596+
* True only for the COMMAND_FAILED error this module raises when it kills a command at
597+
* its own `timeoutMs`. Callers classify with this rather than matching the message text,
598+
* so a command whose own output says "timed out" is not mistaken for one exec killed.
602599
*/
603600
export function isCommandTimeoutError(error: unknown): boolean {
604601
return (
@@ -608,21 +605,6 @@ export function isCommandTimeoutError(error: unknown): boolean {
608605
);
609606
}
610607

611-
/**
612-
* Ceiling on one Apple toolchain identity probe attempt (`xcodebuild -version`,
613-
* `xcrun --show-sdk-version`, `sw_vers`, `uname`, …). On a fresh macOS host,
614-
* Apple's syspolicyd signature scan blocks the very first `xcodebuild`/`xcrun`/
615-
* large-binary exec after boot for roughly 18 to 19 seconds at 0% CPU; the
616-
* second exec of the same tool is instant. A budget sized for a warm toolchain
617-
* (the old 10 s / 5 s split) trips on that cold-start stall and reports a bogus
618-
* toolchain-probe timeout unrelated to the change under test (#2422).
619-
*
620-
* It sits beside {@link isCommandTimeoutError} because it is a property of
621-
* exec'ing an Apple tool rather than of either prober: both Apple toolchain
622-
* probers read this one value.
623-
*/
624-
export const COLD_TOOLCHAIN_PROBE_TIMEOUT_MS = 30_000;
625-
626608
function createExitError(
627609
executable: string,
628610
cmd: string,

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

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import { publishFileSync, acquireProcessLock } from '@agent-device/host-kit/file
33
import { resolveIosSimulatorDeviceSetPath } from '@agent-device/kernel/device-isolation';
44

55
import {
6-
COLD_TOOLCHAIN_PROBE_TIMEOUT_MS,
76
isCommandTimeoutError,
87
requireExecSuccess,
98
runCmdBackground,
@@ -58,7 +57,6 @@ export const appleRunnerHost: AppleRunnerHost = {
5857
runCmdBackground,
5958
requireExecSuccess,
6059
isCommandTimeoutError,
61-
coldToolchainProbeTimeoutMs: () => COLD_TOOLCHAIN_PROBE_TIMEOUT_MS,
6260
emitDiagnostic,
6361
withDiagnosticTimer,
6462
retryWithPolicy,

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

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,7 @@ import {
1515
resolveRunnerSandboxBuildArgs,
1616
resolveExpectedRunnerCacheMetadata,
1717
} from '../runner-cache-metadata.ts';
18-
// The one owning module for the probe budget: host-kit's exec layer. The
19-
// snapshot-source prober imports it from there directly; this file's probes read
20-
// the same value through the runner host port (#2422).
21-
import { COLD_TOOLCHAIN_PROBE_TIMEOUT_MS } from '@agent-device/host-kit/command';
18+
import { COLD_TOOLCHAIN_PROBE_TIMEOUT_MS } from '../apple-runner-platform.ts';
2219
import { appleToolchainProbeResult, stubAppleToolchainProbes } from './apple-toolchain-fixtures.ts';
2320

2421
const runCmdSync = stubAppleToolchainProbes();

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,19 @@ import {
66
type DeviceInfo,
77
} from '@agent-device/kernel/device';
88

9+
/**
10+
* Ceiling on one Apple toolchain identity probe attempt (`xcodebuild -version`, `xcrun
11+
* --sdk <sdk> --show-sdk-version`). On a fresh macOS host Apple's syspolicyd signature
12+
* scan blocks the first `xcodebuild`/`xcrun` exec after boot for roughly 18 to 19 seconds
13+
* at 0% CPU, and the next exec of the same tool is instant; a budget sized for a warm
14+
* toolchain (the old 10 s / 5 s split) trips on that stall and reports a toolchain
15+
* timeout that says nothing about the toolchain (#2422).
16+
*
17+
* It sits beside the SDK names the probes run against so both Apple toolchain probers
18+
* read one value without either owning it.
19+
*/
20+
export const COLD_TOOLCHAIN_PROBE_TIMEOUT_MS = 30_000;
21+
922
export type RunnerApplePlatformName = 'iOS' | 'tvOS' | 'macOS' | 'visionOS';
1023

1124
type RunnerPlatformDeviceKind = 'simulator' | 'device';

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

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -149,21 +149,8 @@ export type AppleRunnerHost = {
149149
message: string,
150150
extra?: Record<string, unknown> | ((result: ExecResult) => Record<string, unknown>),
151151
): ExecResult;
152-
/**
153-
* True only for the error the exec layer raises when it killed a command at
154-
* the `timeoutMs` the caller asked for, read from the structured detail it
155-
* stamps rather than from the message text.
156-
*/
152+
/** True only for the error the exec layer raises when it killed a command at `timeoutMs`. */
157153
isCommandTimeoutError(error: unknown): boolean;
158-
/**
159-
* Ceiling on one Apple toolchain identity probe attempt, in milliseconds:
160-
* `COLD_TOOLCHAIN_PROBE_TIMEOUT_MS` from `@agent-device/host-kit/command`,
161-
* which owns it for both Apple toolchain probers. Like every other host-kit
162-
* symbol above it arrives through this port rather than by import, because
163-
* `scripts/__tests__/eager-closure-budgets.test.ts` holds the runner entry to
164-
* the modules it evaluates today and a static edge to host-kit adds five.
165-
*/
166-
coldToolchainProbeTimeoutMs(): number;
167154
// Diagnostics (@agent-device/host-kit/diagnostics)
168155
emitDiagnostic(event: DiagnosticEventInput): void;
169156
withDiagnosticTimer<T>(
@@ -294,8 +281,6 @@ export const requireExecSuccess: AppleRunnerHost['requireExecSuccess'] = (result
294281
requireHost().requireExecSuccess(result, message, extra);
295282
export const isCommandTimeoutError: AppleRunnerHost['isCommandTimeoutError'] = (error) =>
296283
requireHost().isCommandTimeoutError(error);
297-
export const coldToolchainProbeTimeoutMs: AppleRunnerHost['coldToolchainProbeTimeoutMs'] = () =>
298-
requireHost().coldToolchainProbeTimeoutMs();
299284
export const emitDiagnostic: AppleRunnerHost['emitDiagnostic'] = (event) =>
300285
requireHost().emitDiagnostic(event);
301286
export const withDiagnosticTimer = <T>(

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

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -55,12 +55,7 @@ export async function tryAdoptRunnerSessionFromLease(
5555
device: DeviceInfo,
5656
options: {
5757
startupTimeoutMs?: number;
58-
/**
59-
* The startup phase's clock, shared with the caller. The fingerprint check
60-
* below runs the same blocking toolchain probes a fresh startup would, so
61-
* the adopted session must be given what those probes left rather than a
62-
* fresh `startupTimeoutMs` (#2422).
63-
*/
58+
/** The startup phase's clock: the fingerprint check below spends from it (#2422). */
6459
phaseDeadline?: Deadline;
6560
/** The owning request's cancellation signal, forwarded to those probes. */
6661
signal?: AbortSignal;
@@ -163,10 +158,7 @@ function resolveExpectedDerivedPath(
163158
resolveExpectedRunnerCacheMetadata(device, undefined, budget),
164159
);
165160
} catch (error) {
166-
// An unresolvable fingerprint is a miss the caller recovers from by starting
167-
// fresh. A canceled request is not: the client that asked for this startup
168-
// is gone, so it leaves through the catch rather than becoming one more
169-
// reason to keep going.
161+
// An unresolvable fingerprint is a miss the caller starts fresh from; a cancel is not.
170162
if (isRequestCanceledError(error)) throw error;
171163
return null;
172164
}

‎packages/platform-apple/src/runner/runner-artifact.ts‎

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -90,11 +90,7 @@ export async function ensureXctestrunArtifact(
9090
if (external) return external;
9191

9292
const projectRoot = findProjectRoot();
93-
// One clock for the whole build phase. The cache decision runs blocking
94-
// toolchain probes before any build starts, so a cold probe's stall is time
95-
// the build no longer has: both read this deadline rather than each starting
96-
// from a fresh copy of `buildTimeoutMs` (#2422). The cache lock, the reuse
97-
// evaluation, and the cleanup between them are on it too.
93+
// One clock for the whole build phase: the toolchain probes and the xcodebuild share it.
9894
const phaseDeadline = createRunnerPhaseDeadline(options.buildTimeoutMs);
9995
const expectedCacheMetadata = resolveExpectedRunnerCacheMetadata(device, projectRoot, {
10096
deadline: phaseDeadline,
@@ -260,10 +256,6 @@ async function buildXctestrunArtifact(params: {
260256
throw new AppError('COMMAND_FAILED', 'iOS runner project not found', { projectPath });
261257
}
262258

263-
// What the phase has left after the toolchain probes, the cache lock, and the
264-
// reuse evaluation -- computed before the build announces itself, so a phase
265-
// already spent fails here instead of starting an xcodebuild it would have to
266-
// kill at once (#2422).
267259
const buildTimeoutMs = requireRunnerPhaseRemainingMs(
268260
phaseDeadline,
269261
options.buildTimeoutMs,

‎packages/platform-apple/src/runner/runner-cache-metadata.ts‎

Lines changed: 25 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import {
88
isRequestCanceledError,
99
} from '@agent-device/kernel/errors';
1010
import {
11-
coldToolchainProbeTimeoutMs,
1211
createTtlMemo,
1312
Deadline,
1413
isCommandTimeoutError,
@@ -19,6 +18,7 @@ import {
1918
type TtlMemo,
2019
} from './host.ts';
2120
import {
21+
COLD_TOOLCHAIN_PROBE_TIMEOUT_MS,
2222
resolveRunnerBuildDestinationFamily,
2323
resolveRunnerDerivedBaseName,
2424
resolveRunnerPlatformName,
@@ -33,13 +33,9 @@ const RUNNER_CACHE_SCHEMA_VERSION = 2;
3333
const RUNNER_CACHE_METADATA_VALUE_MAX_LENGTH = 300;
3434

3535
/**
36-
* Ceiling on the wall clock the whole toolchain fingerprint may spend, across
37-
* all three probes and their retries, when the owning phase carries no shorter
38-
* budget. Sized for the one cold-start stall the retry exists for -- a single
39-
* stalled probe (up to the host's `coldToolchainProbeTimeoutMs()`) plus its
40-
* now-warm retry and the two remaining probes -- not for three independently
41-
* stalling tools, which is why the per-call timeout alone is not the bound
42-
* (#2422).
36+
* Ceiling on the wall clock the whole toolchain fingerprint may spend, across all three
37+
* probes and their retries, when the owning phase carries no shorter budget: one stalled
38+
* probe, its warm retry, and the two probes still to run (#2422).
4339
*/
4440
const TOOLCHAIN_FINGERPRINT_BUDGET_MS = 45_000;
4541
const TOOLCHAIN_PROBE_MAX_BUFFER = 128 * 1024;
@@ -71,25 +67,17 @@ type ToolchainProbeFailure = {
7167
};
7268

7369
/**
74-
* The one clock a runner phase spends, for a step whose budget is `timeoutMs`;
75-
* `undefined` for a caller that carries no budget at all (background and
76-
* preflight surfaces). The cache decision's blocking toolchain probes and the
77-
* step the phase exists for (an `xcodebuild` build, a runner startup) both read
78-
* it, so what the probes spend is time the step no longer has. Create it once
79-
* per phase and read the rest with {@link requireRunnerPhaseRemainingMs}; a
80-
* step that hands the probes a timeout and then hands itself the same number
81-
* again spends the phase's budget twice (#2422).
70+
* The one clock a runner phase spends, created once per phase and read with
71+
* {@link requireRunnerPhaseRemainingMs}; `undefined` for a caller carrying no budget.
8272
*/
8373
export function createRunnerPhaseDeadline(timeoutMs: number | undefined): Deadline | undefined {
8474
if (timeoutMs === undefined || !Number.isFinite(timeoutMs)) return undefined;
8575
return Deadline.fromTimeoutMs(Math.max(0, timeoutMs));
8676
}
8777

8878
/**
89-
* What the phase has left for its next step, or `fallbackTimeoutMs` when it
90-
* carries no deadline. Throws instead of returning zero: a step reached with
91-
* nothing left must fail before it spawns anything, not start a process it
92-
* would have to kill immediately.
79+
* What the phase has left for its next step, or `fallbackTimeoutMs` when it carries no
80+
* deadline. Throws rather than returning zero, so a spent phase fails before it spawns.
9381
*/
9482
export function requireRunnerPhaseRemainingMs(
9583
deadline: Deadline | undefined,
@@ -102,12 +90,7 @@ export function requireRunnerPhaseRemainingMs(
10290
return remainingMs;
10391
}
10492

105-
/**
106-
* The one error a runner phase raises when a step is reached with nothing left
107-
* to spend, whether that step is an `xcodebuild` build, a runner startup, or a
108-
* toolchain probe. It says the budget ran out, not that the thing it would have
109-
* run is broken.
110-
*/
93+
/** Says the phase budget ran out, not that the step it would have run is broken. */
11194
function runnerPhaseBudgetExhaustedError(phase: string): AppError {
11295
return new AppError('COMMAND_FAILED', 'The Apple runner budget ran out before this step began', {
11396
phase,
@@ -117,17 +100,8 @@ function runnerPhaseBudgetExhaustedError(phase: string): AppError {
117100
}
118101

119102
/**
120-
* What the phase that wants a runner cache decision has left to spend on it.
121-
* The decision blocks the calling request on up to three synchronous `spawnSync`
122-
* probes, so the phase's own deadline and cancellation must reach them: an
123-
* exhausted budget fails the decision instead of starting another 30 second
124-
* probe, and a canceled request surfaces the cancellation rather than
125-
* retrying (#2422). A caller with neither still gets
126-
* {@link TOOLCHAIN_FINGERPRINT_BUDGET_MS} as the ceiling.
127-
*
128-
* `spawnSync` cannot be interrupted once it has started, so cancellation is
129-
* observed between attempts; the per-attempt cap is what bounds how long that
130-
* takes.
103+
* What the phase that wants a runner cache decision has left to spend on it. A caller
104+
* with neither field still gets {@link TOOLCHAIN_FINGERPRINT_BUDGET_MS} as the ceiling.
131105
*/
132106
export type RunnerCacheProbeBudget = {
133107
/** The owning phase's clock, shared with whatever the phase does next. */
@@ -137,9 +111,11 @@ export type RunnerCacheProbeBudget = {
137111
};
138112

139113
/**
140-
* The remaining-time and cancellation view the probes consult. One is created
141-
* per fingerprint read, so the three probes and their retries share -- and
142-
* together cannot exceed -- a single budget.
114+
* The remaining-time and cancellation view the probes consult: one per fingerprint read,
115+
* so the three probes and their retries share a single budget.
116+
*
117+
* `spawnSync` cannot be interrupted once it has started, so cancellation is observed
118+
* between attempts; the per-attempt cap is what bounds how long that takes.
143119
*/
144120
type ToolchainProbeClock = {
145121
/** Milliseconds the next attempt may block for; 0 once the budget is spent. */
@@ -152,10 +128,6 @@ function createToolchainProbeClock(
152128
budget: RunnerCacheProbeBudget | undefined,
153129
): ToolchainProbeClock {
154130
const phaseDeadline = budget?.deadline;
155-
// The fingerprint's own deadline, opened at whichever of the two ceilings is
156-
// nearer: the phase's remainder, or the fingerprint budget for a caller with
157-
// no phase clock (or a generous one). Both are wall-clock, so the step after
158-
// the probes still sees the time they spent.
159131
const deadline = Deadline.fromTimeoutMs(
160132
Math.min(
161133
TOOLCHAIN_FINGERPRINT_BUDGET_MS,
@@ -164,7 +136,7 @@ function createToolchainProbeClock(
164136
);
165137
return {
166138
attemptTimeoutMs: () =>
167-
Math.min(coldToolchainProbeTimeoutMs(), Math.floor(deadline.remainingMs())),
139+
Math.min(COLD_TOOLCHAIN_PROBE_TIMEOUT_MS, Math.floor(deadline.remainingMs())),
168140
throwIfCanceled: () => {
169141
if (budget?.signal?.aborted) {
170142
throw createRequestCanceledError({ phase: 'apple_toolchain_probe' });
@@ -279,18 +251,14 @@ function toolchainFingerprintCache(): TtlMemo<string, RunnerToolchainFingerprint
279251
}
280252

281253
/**
282-
* The toolchain half of the cache key, or a failure. A probe that timed out or
283-
* could not be read has no value to compare or persist, and the same
284-
* fingerprint also names the derived-data directory, so an unreadable
285-
* toolchain fails the cache decision instead of standing in for one.
254+
* The toolchain half of the cache key. It also names the derived-data directory, so an
255+
* unreadable toolchain fails the cache decision instead of standing in for one.
286256
*/
287257
function requireRunnerToolchainFingerprint(
288258
sdkName: string,
289259
budget: RunnerCacheProbeBudget | undefined,
290260
): RunnerToolchainFingerprint {
291-
// Checked before the cache, not just before the probes: a canceled request
292-
// must surface as canceled even on a cache hit, or adoption reads a stale
293-
// "success" and goes on to probe uptime and write the lease (#2422).
261+
// Before the cache, not just before the probes: a hit must not hide a cancellation.
294262
const clock = createToolchainProbeClock(budget);
295263
clock.throwIfCanceled();
296264
const cached = toolchainFingerprintCache().get(sdkName);
@@ -359,12 +327,7 @@ function runToolchainProbe(
359327
try {
360328
output = runToolchainProbeCommand(cmd, args, clock);
361329
} catch (error) {
362-
// A canceled request and a spent budget are the caller's own errors to
363-
// see, not an unreadable toolchain: only what's left becomes a probe
364-
// failure. Checked again here (not just in attemptToolchainProbe) because
365-
// the request can abort while this exec is in flight, after its own guard
366-
// already passed -- including on the last probe, where there is no next
367-
// attempt left to catch it.
330+
// A cancellation or a spent budget is the caller's error, not an unreadable toolchain.
368331
clock.throwIfCanceled();
369332
if (isRequestCanceledError(error) || isRunnerPhaseBudgetExhaustedError(error)) throw error;
370333
return probeFailure(probe, 'probe_error', error instanceof Error ? error.message : `${error}`);
@@ -381,17 +344,9 @@ function runToolchainProbe(
381344
}
382345

383346
/**
384-
* Runs one toolchain probe, retrying exactly once if the attempt timed out and
385-
* the shared budget still has room. Apple's syspolicyd signature scan blocks
386-
* the first `xcodebuild`/`xcrun` exec after a fresh host boots (see
387-
* `COLD_TOOLCHAIN_PROBE_TIMEOUT_MS` in `@agent-device/host-kit/command`, which
388-
* reaches this file through the host port); the immediate next exec of the same
389-
* tool is instant, so the retry recovers without widening the per-call budget. Only the
390-
* exec layer's structured timeout is retried -- a tool that failed on its own
391-
* and merely said "timed out" in its output is not this stall. The retry calls
392-
* the same guarded attempt below, so a request canceled or a budget spent
393-
* between attempts is caught there rather than trusted from before the first
394-
* one.
347+
* Retries exactly once, and only the exec layer's structured timeout: the stall
348+
* {@link COLD_TOOLCHAIN_PROBE_TIMEOUT_MS} names clears on the next exec of the same tool,
349+
* while a tool that failed on its own and said "timed out" in its output is not it.
395350
*/
396351
function runToolchainProbeCommand(
397352
cmd: string,
@@ -406,7 +361,7 @@ function runToolchainProbeCommand(
406361
}
407362
}
408363

409-
/** The one guard site for a toolchain probe attempt: cancellation and a spent budget both throw here, before anything execs. */
364+
/** The one guard site: cancellation and a spent budget both throw here, before any exec. */
410365
function attemptToolchainProbe(
411366
cmd: string,
412367
args: string[],

‎packages/platform-apple/src/runner/runner-session.ts‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,7 @@ export async function ensureRunnerSession(
112112
// from a retained-after-close runner no longer applies.
113113
cancelIosRunnerIdleStop(device.id);
114114
return await withRunnerSessionLock(device.id, async () => {
115-
// One clock for the whole startup phase. The reuse check runs the same
116-
// blocking toolchain probes the startup after it would, so a cold probe's
117-
// stall is time the startup no longer has: everything below reads what this
118-
// deadline has left rather than `startupTimeoutMs` again (#2422).
115+
// One clock for the whole startup phase: the toolchain probes and the startup share it.
119116
const phaseDeadline = createRunnerPhaseDeadline(options.startupTimeoutMs);
120117
const existing = runnerSessions.get(device.id);
121118
if (existing) {
@@ -195,10 +192,7 @@ async function startRunnerSessionWithLease(
195192
phase: 'ios_runner_startup_cleanup_stale_bundles_skipped',
196193
});
197194
}
198-
// What the startup phase has left after the reuse probe, the adoption attempt
199-
// and the pre-build cleanup. Read before the build rather than after it: the
200-
// build answers to its own `buildTimeoutMs` deadline, so charging it to the
201-
// startup budget as well would spend that budget twice over (#2422).
195+
// Read before the build, which answers to its own `buildTimeoutMs` deadline (#2422).
202196
const startupTimeoutMs = requireRunnerPhaseRemainingMs(
203197
phaseDeadline,
204198
options.startupTimeoutMs,

0 commit comments

Comments
 (0)