Skip to content

Commit 38c1279

Browse files
committed
refactor: quality pass over the iOS startup perf stack
Applied from a 4-angle review (reuse / simplification / efficiency / altitude) of the #1011 diff: - RunnerSession.child is now a RunnerProcessHandle (pid/exitCode) instead of ChildProcess: every consumer only reads pid/exitCode and kills by pid, the adoption surrogate no longer needs double casts, and the compiler enforces what a comment used to promise. Real children satisfy the handle structurally. - session-open prewarm scheduling collapsed into schedulePrewarm/ awaitPrewarm closures; the fallback guard is a dedicated local instead of reading the OpenTiming telemetry object (kept separate from the promise itself, which is legitimately undefined when prewarm is unavailable). - adoption: expected derived path computed once and threaded through (resolveExpectedRunnerCacheMetadata does a recursive source-stat walk per call, and it runs under the lease lock); guard chain flattened into skip(reason) early returns; probe timeout 2s -> 500ms (localhost refusal is instant, the timeout only bounds the wedged-runner case); dead path.dirname fallback removed. - shared normalizeRunnerStartupTimeoutMs and buildRunnerSessionId in runner-session-types; deleted the verbatim copies. - detach kill switch parses through utils/source-value parseBooleanLiteral (now exported) instead of a bespoke dialect that treated 'no' as enabled. - dropped buildDetachedRunnerLease's untriggerable idempotence guard, direct Map iteration in the detach loop, and a freshness warning on markSimulatorBooted for future callers.
1 parent efe4400 commit 38c1279

9 files changed

Lines changed: 114 additions & 99 deletions

File tree

‎src/daemon/handlers/session-open.ts‎

Lines changed: 34 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,10 @@ async function completeOpenCommand(params: {
168168
const timing: OpenTiming = {};
169169

170170
const shouldPrewarmIosRunner =
171-
isIosFamily(device) && surface === 'app' && openPositionals.length > 0;
171+
isIosFamily(device) &&
172+
surface === 'app' &&
173+
openPositionals.length > 0 &&
174+
Boolean(sessionAppBundleId);
172175
const runnerPrewarmOptions = buildAppleRunnerSessionOptions({
173176
req,
174177
logPath,
@@ -177,19 +180,32 @@ async function completeOpenCommand(params: {
177180
});
178181
const shouldPrewarmRunnerBeforeOpen = req.flags?.maestro?.prewarmRunnerBeforeOpen === true;
179182
let runnerPrewarm: Promise<void> | undefined;
183+
// Tracked separately from `runnerPrewarm`: prewarmIosRunnerSession may
184+
// return undefined (prewarm unavailable), and one attempt is one attempt.
185+
let runnerPrewarmScheduled = false;
186+
let runnerPrewarmAwaited = false;
187+
const schedulePrewarm = (
188+
options: Parameters<typeof prewarmIosRunnerSession>[1] = runnerPrewarmOptions,
189+
): void => {
190+
runnerPrewarmScheduled = true;
191+
timing.runnerPrewarmKind = 'session';
192+
timing.runnerPrewarmScheduled = true;
193+
runnerPrewarm = prewarmIosRunnerSession(device, options);
194+
};
195+
const awaitPrewarm = async (): Promise<void> => {
196+
if (!runnerPrewarm || runnerPrewarmAwaited) return;
197+
runnerPrewarmAwaited = true;
198+
const startedAtMs = Date.now();
199+
await runnerPrewarm;
200+
timing.runnerPrewarmWaited = true;
201+
timing.runnerPrewarmDurationMs = Math.max(0, Date.now() - startedAtMs);
202+
};
180203
// Start the runner spin-up before close/open dispatch on simulators: neither
181204
// touches the runner there (both ride simctl), so the xcodebuild ramp
182205
// overlaps the app relaunch instead of following it. Real devices tear the
183206
// runner down in relaunchCloseApp, so their prewarm stays post-open.
184-
if (
185-
shouldPrewarmIosRunner &&
186-
sessionAppBundleId &&
187-
isIosSimulator(device) &&
188-
!shouldPrewarmRunnerBeforeOpen
189-
) {
190-
timing.runnerPrewarmKind = 'session';
191-
timing.runnerPrewarmScheduled = true;
192-
runnerPrewarm = prewarmIosRunnerSession(device, runnerPrewarmOptions);
207+
if (shouldPrewarmIosRunner && isIosSimulator(device) && !shouldPrewarmRunnerBeforeOpen) {
208+
schedulePrewarm();
193209
}
194210

195211
if (shouldRelaunch && openTarget) {
@@ -218,17 +234,9 @@ async function completeOpenCommand(params: {
218234
runtime,
219235
});
220236
timing.runtimeHintsDurationMs = Math.max(0, Date.now() - runtimeHintsStartedAtMs);
221-
if (shouldPrewarmIosRunner && sessionAppBundleId && shouldPrewarmRunnerBeforeOpen) {
222-
timing.runnerPrewarmKind = 'session';
223-
timing.runnerPrewarmScheduled = true;
224-
runnerPrewarm = prewarmIosRunnerSession(device, {
225-
...runnerPrewarmOptions,
226-
propagateError: true,
227-
});
228-
const runnerPrewarmStartedAtMs = Date.now();
229-
await runnerPrewarm;
230-
timing.runnerPrewarmWaited = true;
231-
timing.runnerPrewarmDurationMs = Math.max(0, Date.now() - runnerPrewarmStartedAtMs);
237+
if (shouldPrewarmIosRunner && shouldPrewarmRunnerBeforeOpen) {
238+
schedulePrewarm({ ...runnerPrewarmOptions, propagateError: true });
239+
await awaitPrewarm();
232240
}
233241
const openStartedAtMs = Date.now();
234242
const provisionalSession = await prepareOpenDispatchSession({
@@ -260,17 +268,12 @@ async function completeOpenCommand(params: {
260268
openPositionals,
261269
});
262270
timing.launchUrlDurationMs = Math.max(0, Date.now() - launchUrlStartedAtMs);
263-
if (shouldPrewarmIosRunner && sessionAppBundleId && timing.runnerPrewarmScheduled !== true) {
264-
timing.runnerPrewarmKind = 'session';
265-
timing.runnerPrewarmScheduled = true;
266-
runnerPrewarm = prewarmIosRunnerSession(device, runnerPrewarmOptions);
271+
if (shouldPrewarmIosRunner && !runnerPrewarmScheduled) {
272+
schedulePrewarm();
267273
}
268-
if (shouldRelaunch && runnerPrewarm && timing.runnerPrewarmWaited !== true) {
269-
const runnerPrewarmStartedAtMs = Date.now();
270-
await runnerPrewarm;
271-
timing.runnerPrewarmWaited = true;
272-
timing.runnerPrewarmDurationMs = Math.max(0, Date.now() - runnerPrewarmStartedAtMs);
273-
} else if (runnerPrewarm && timing.runnerPrewarmWaited !== true) {
274+
if (shouldRelaunch) {
275+
await awaitPrewarm();
276+
} else if (runnerPrewarm && !runnerPrewarmAwaited) {
274277
timing.runnerPrewarmWaited = false;
275278
}
276279
sessionAppBundleId = await inferAndroidPackageAfterOpen(device, openTarget, sessionAppBundleId);

‎src/platforms/apple/core/__tests__/runner-adoption.test.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -110,11 +110,9 @@ test('readStaleRunnerLease returns dead-owner leases and skips owned ones', () =
110110
expect(readStaleRunnerLease(simulator.id)).toBeNull();
111111
});
112112

113-
test('buildDetachedRunnerLease rewrites the token once', () => {
113+
test('buildDetachedRunnerLease rewrites the token', () => {
114114
const lease = writeStaleLease();
115-
const detached = buildDetachedRunnerLease(lease);
116-
expect(detached.ownerToken).toBe(`detached-${lease.ownerToken}`);
117-
expect(buildDetachedRunnerLease(detached).ownerToken).toBe(detached.ownerToken);
115+
expect(buildDetachedRunnerLease(lease).ownerToken).toBe(`detached-${lease.ownerToken}`);
118116
});
119117

120118
test('adoption succeeds for a live, matching, probe-healthy runner', async () => {

‎src/platforms/apple/core/runner/runner-adoption.ts‎

Lines changed: 45 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@ import path from 'node:path';
22
import { resolveIosSimulatorDeviceSetPath } from '../../../../utils/device-isolation.ts';
33
import { emitDiagnostic } from '../../../../utils/diagnostics.ts';
44
import { isProcessAlive } from '../../../../utils/process-identity.ts';
5+
import { parseBooleanLiteral } from '../../../../utils/source-value.ts';
56
import type { DeviceInfo } from '../../../../kernel/device.ts';
6-
import type { ExecResult, ExecBackgroundResult } from '../../../../utils/exec.ts';
7+
import type { ExecResult } from '../../../../utils/exec.ts';
78
import { sendRunnerCommandOnce } from './runner-transport.ts';
89
import { withRunnerCommandId } from './runner-contract.ts';
910
import {
@@ -17,17 +18,25 @@ import {
1718
resolveRunnerDerivedPath,
1819
type RunnerXctestrunArtifact,
1920
} from './runner-xctestrun.ts';
20-
import type { RunnerSession } from './runner-session-types.ts';
21+
import {
22+
buildRunnerSessionId,
23+
normalizeRunnerStartupTimeoutMs,
24+
type RunnerProcessHandle,
25+
type RunnerSession,
26+
} from './runner-session-types.ts';
2127

22-
const RUNNER_ADOPTION_PROBE_TIMEOUT_MS = 2_000;
28+
// A healthy localhost runner answers uptime in tens of milliseconds and a dead
29+
// port refuses immediately; the timeout only bounds the wedged-runner case,
30+
// where giving up fast matters — the probe runs under the lease lock, in
31+
// series before the restart it would otherwise avoid.
32+
const RUNNER_ADOPTION_PROBE_TIMEOUT_MS = 500;
2333
const RUNNER_ADOPTION_EXIT_POLL_INTERVAL_MS = 1_000;
2434

2535
// Kill switch for the runner handoff across daemon restarts: disables both
2636
// detaching healthy simulator runners on graceful shutdown and adopting them
2737
// on the next startup.
2838
export function isIosRunnerDetachEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
29-
const value = env.AGENT_DEVICE_IOS_RUNNER_DETACH?.trim().toLowerCase();
30-
return value !== '0' && value !== 'false' && value !== 'off';
39+
return parseBooleanLiteral(env.AGENT_DEVICE_IOS_RUNNER_DETACH ?? '') !== false;
3140
}
3241

3342
// Adopts a still-running runner left behind by a dead daemon (crash or
@@ -47,24 +56,27 @@ export async function tryAdoptRunnerSessionFromLease(
4756
if (resolveIosSimulatorDeviceSetPath(device.simulatorSetPath)) return null;
4857
const lease = readStaleRunnerLease(device.id);
4958
if (!lease) return null;
50-
const runnerPid = lease.runnerPid;
51-
const rejection = runnerPid
52-
? await probeAdoptableRunnerLease(device, lease, runnerPid)
53-
: 'runner_pid_missing';
54-
if (rejection || !runnerPid) {
59+
60+
const skip = (reason: string): null => {
5561
emitDiagnostic({
5662
level: 'debug',
5763
phase: 'ios_runner_lease_adoption_skipped',
58-
data: {
59-
deviceId: device.id,
60-
runnerPid: lease.runnerPid,
61-
port: lease.port,
62-
reason: rejection,
63-
},
64+
data: { deviceId: device.id, runnerPid: lease.runnerPid, port: lease.port, reason },
6465
});
6566
return null;
67+
};
68+
69+
const runnerPid = lease.runnerPid;
70+
if (!runnerPid) return skip('runner_pid_missing');
71+
if (!isProcessAlive(runnerPid)) return skip('runner_process_dead');
72+
const expectedDerived = resolveExpectedDerivedPath(device);
73+
if (!expectedDerived) return skip('expected_derived_unresolved');
74+
if (!lease.xctestrunPath.startsWith(`${expectedDerived}${path.sep}`)) {
75+
return skip('artifact_fingerprint_mismatch');
6676
}
67-
const session = buildAdoptedRunnerSession(device, lease, runnerPid, options);
77+
if (!(await probeRunnerAnswersUptime(device, lease.port))) return skip('probe_failed');
78+
79+
const session = buildAdoptedRunnerSession(device, lease, runnerPid, expectedDerived, options);
6880
try {
6981
writeRunnerLease(session.lease);
7082
} catch {
@@ -76,38 +88,27 @@ export async function tryAdoptRunnerSessionFromLease(
7688
data: {
7789
deviceId: device.id,
7890
sessionId: session.sessionId,
79-
runnerPid: lease.runnerPid,
91+
runnerPid,
8092
port: lease.port,
8193
previousOwnerPid: lease.ownerPid,
8294
},
8395
});
8496
return session;
8597
}
8698

87-
async function probeAdoptableRunnerLease(
88-
device: DeviceInfo,
89-
lease: RunnerLease,
90-
runnerPid: number,
91-
): Promise<string | null> {
92-
if (!isProcessAlive(runnerPid)) return 'runner_process_dead';
93-
const expectedDerived = resolveExpectedDerivedPath(device);
94-
if (!expectedDerived) return 'expected_derived_unresolved';
95-
if (!lease.xctestrunPath.startsWith(`${expectedDerived}${path.sep}`)) {
96-
return 'artifact_fingerprint_mismatch';
97-
}
99+
async function probeRunnerAnswersUptime(device: DeviceInfo, port: number): Promise<boolean> {
98100
try {
99101
const response = await sendRunnerCommandOnce(
100102
device,
101-
lease.port,
103+
port,
102104
withRunnerCommandId({ command: 'uptime' }),
103105
RUNNER_ADOPTION_PROBE_TIMEOUT_MS,
104106
);
105107
const payload = JSON.parse(await response.text()) as { ok?: unknown };
106-
if (payload?.ok !== true) return 'probe_rejected';
108+
return payload?.ok === true;
107109
} catch {
108-
return 'probe_failed';
110+
return false;
109111
}
110-
return null;
111112
}
112113

113114
function resolveExpectedDerivedPath(device: DeviceInfo): string | null {
@@ -122,12 +123,13 @@ function buildAdoptedRunnerSession(
122123
device: DeviceInfo,
123124
lease: RunnerLease,
124125
runnerPid: number,
126+
expectedDerived: string,
125127
options: { startupTimeoutMs?: number },
126128
): RunnerSession & { lease: RunnerLease } {
127-
const sessionId = `${device.id}:${lease.port}:${Date.now()}`;
129+
const sessionId = buildRunnerSessionId(device.id, lease.port);
128130
const artifact: RunnerXctestrunArtifact = {
129131
xctestrunPath: lease.xctestrunPath,
130-
derived: resolveExpectedDerivedPath(device) ?? path.dirname(lease.xctestrunPath),
132+
derived: expectedDerived,
131133
cache: 'exact',
132134
artifact: 'valid',
133135
buildMs: 0,
@@ -147,7 +149,7 @@ function buildAdoptedRunnerSession(
147149
child,
148150
// The probe already proved the runner answers commands.
149151
ready: true,
150-
startupTimeoutMs: normalizeStartupTimeoutMs(options.startupTimeoutMs),
152+
startupTimeoutMs: normalizeRunnerStartupTimeoutMs(options.startupTimeoutMs),
151153
lease: buildRunnerLease({
152154
deviceId: device.id,
153155
sessionId,
@@ -160,29 +162,23 @@ function buildAdoptedRunnerSession(
160162
}
161163

162164
// The adopted xcodebuild was spawned by a dead process, so there is no
163-
// ChildProcess handle. Downstream code only reads pid/exitCode and kills by
164-
// pid, so a pid-backed surrogate suffices; a low-frequency poll flips
165-
// exitCode and settles testPromise when the process actually exits, which is
166-
// what the transport's early-exit detection and disposal wait on.
165+
// ChildProcess to hold — just a pid-backed RunnerProcessHandle. A
166+
// low-frequency poll flips exitCode and settles testPromise when the process
167+
// actually exits, which is what the transport's early-exit detection and
168+
// disposal wait on.
167169
function watchDetachedRunnerProcess(pid: number): {
168-
child: ExecBackgroundResult['child'];
170+
child: RunnerProcessHandle;
169171
wait: Promise<ExecResult>;
170172
} {
171-
const child = { pid, exitCode: null } as unknown as ExecBackgroundResult['child'];
173+
const child: RunnerProcessHandle = { pid, exitCode: null };
172174
const wait = new Promise<ExecResult>((resolve) => {
173175
const timer = setInterval(() => {
174176
if (isProcessAlive(pid)) return;
175177
clearInterval(timer);
176-
(child as { exitCode: number | null }).exitCode = -1;
178+
child.exitCode = -1;
177179
resolve({ stdout: '', stderr: '', exitCode: -1 });
178180
}, RUNNER_ADOPTION_EXIT_POLL_INTERVAL_MS);
179181
timer.unref?.();
180182
});
181183
return { child, wait };
182184
}
183-
184-
function normalizeStartupTimeoutMs(value: number | undefined): number | undefined {
185-
return typeof value === 'number' && Number.isFinite(value) && value > 0
186-
? Math.floor(value)
187-
: undefined;
188-
}

‎src/platforms/apple/core/runner/runner-disposal.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { emitDiagnostic } from '../../../../utils/diagnostics.ts';
22
import type { DeviceInfo } from '../../../../kernel/device.ts';
33
import { isProcessAlive, isProcessGroupAlive } from '../../../../utils/process-identity.ts';
4+
import type { ExecBackgroundResult } from '../../../../utils/exec.ts';
45
import { cleanupTempFile, waitForRunner } from './runner-transport.ts';
56
import { withRunnerCommandId, type RunnerCommand } from './runner-contract.ts';
67
import {
@@ -165,7 +166,7 @@ async function signalRunnerSessions(
165166
}
166167

167168
async function signalRunnerPrepProcesses(
168-
prepProcesses: readonly RunnerSession['child'][],
169+
prepProcesses: readonly ExecBackgroundResult['child'][],
169170
signal: 'SIGINT' | 'SIGTERM' | 'SIGKILL',
170171
): Promise<void> {
171172
await Promise.allSettled(

‎src/platforms/apple/core/runner/runner-lease.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,6 @@ export function readStaleRunnerLease(deviceId: string): RunnerLease | null {
239239
// matches this daemon, so the shutdown's own lease-cleanup paths skip it, and
240240
// once this process exits the lease classifies as stale for the next adopter.
241241
export function buildDetachedRunnerLease(lease: RunnerLease): RunnerLease {
242-
if (lease.ownerToken.startsWith('detached-')) return lease;
243242
return { ...lease, ownerToken: `detached-${lease.ownerToken}` };
244243
}
245244

‎src/platforms/apple/core/runner/runner-session-types.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
11
import type { RunnerLogicalLeaseContext } from '../../../../core/runner-lease-context.ts';
2-
import type { ExecResult, ExecBackgroundResult } from '../../../../utils/exec.ts';
2+
import type { ExecResult } from '../../../../utils/exec.ts';
33
import type { DeviceInfo } from '../../../../kernel/device.ts';
44
import type { RunnerXctestrunArtifact } from './runner-xctestrun.ts';
55
import type { RunnerLease } from './runner-lease.ts';
66

7+
// The runner process seen through the session: pid for liveness/kill-tree and
8+
// exitCode for early-exit detection. A spawned ChildProcess satisfies this
9+
// structurally; adopted runners (whose spawner died) provide a pid-backed
10+
// surrogate — which is why the session must not assume streams or kill() here.
11+
export type RunnerProcessHandle = {
12+
pid?: number | undefined;
13+
exitCode: number | null;
14+
};
15+
716
export type RunnerSession = {
817
sessionId: string;
918
device: DeviceInfo;
@@ -13,7 +22,7 @@ export type RunnerSession = {
1322
xctestrunArtifact?: RunnerXctestrunArtifact;
1423
jsonPath: string;
1524
testPromise: Promise<ExecResult>;
16-
child: ExecBackgroundResult['child'];
25+
child: RunnerProcessHandle;
1726
ready: boolean;
1827
startupTimeoutMs?: number;
1928
// Records the last allowlisted mutating interaction that the runner confirmed
@@ -26,3 +35,13 @@ export type RunnerSession = {
2635
simulatorSetRedirect?: { release: () => Promise<void> };
2736
lease?: RunnerLease;
2837
};
38+
39+
export function buildRunnerSessionId(deviceId: string, port: number): string {
40+
return `${deviceId}:${port}:${Date.now()}`;
41+
}
42+
43+
export function normalizeRunnerStartupTimeoutMs(value: number | undefined): number | undefined {
44+
return typeof value === 'number' && Number.isFinite(value) && value > 0
45+
? Math.floor(value)
46+
: undefined;
47+
}

0 commit comments

Comments
 (0)