Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ beforeEach(() => {
// `readPreparePhaseTimeoutMs` raises when the boot ate the budget: "prepare ios-runner timed out"
// with reason `prepare_deadline_expired`. That indicts the boot, not the derived data it was
// launched from, so the artifact stays and prepare retries with a fresh session. The artifact is
// only wiped by the rules that indict it, such as a runner that refused the connection.
// only wiped after a rule indicts it, such as a refused connection, and the retry fails too.

test('a prepare deadline spent during boot keeps the restored artifact and retries', async () => {
vi.useFakeTimers();
Expand Down Expand Up @@ -112,18 +112,84 @@ test('a prepare deadline spent during boot keeps the restored artifact and retri
}
});

// The bad-cache recovery decision: a restored artifact whose runner refuses the connection is
// indicted, wiped for the run, and replaced by one forced rebuild — under one admission token
// owned by the prepare loop, so the rebuild is the retry a fence governs rather than a fresh
// start that slips past it (#3220).
// A startup deadline that expires while xcodebuild is alive looks the same for a slow boot on a
// loaded host and for a corrupt artifact. The restored artifact lives in the shared cache that
// concurrent first opens read, so the first miss retries on that cache and never cleans it (#4689).

test('prepareIosRunner marks a bad restored artifact and rebuilds once after health failure', async () => {
test('a startup deadline on a restored artifact retries without rebuilding the shared cache', async () => {
const fixtures = makeBadCacheRecoveryFixtures();

mockEnsureRunnerSession
.mockResolvedValueOnce(fixtures.restoredSession)
.mockResolvedValueOnce(fixtures.retrySession);
mockExecuteRunnerCommandWithSession
.mockRejectedValueOnce(runnerConnectFailure('runner_connect_refused'))
.mockResolvedValueOnce({ uptimeMs: 42 });

const result = await prepareIosRunner(IOS_SIMULATOR, { healthTimeoutMs: 90_000 });

assert.equal(result.xctestrunPath, '/tmp/restored.xctestrun');
assert.equal(result.recoveryReason, 'Runner did not accept connection');
assert.equal(mockMarkRunnerXctestrunArtifactBadForRun.mock.calls.length, 0);
assert.deepEqual(mockInvalidateRunnerSession.mock.calls, [
[fixtures.restoredSession, 'prepare_runner_health_retry'],
]);
const retryOptions = mockEnsureRunnerSession.mock.calls[1]?.[1] as
| Record<string, unknown>
| undefined;
assert.equal(retryOptions?.forceRunnerXctestrunRebuild, undefined);
assert.equal(mockExecuteRunnerCommandWithSession.mock.calls[1]?.[1], fixtures.retrySession);
});

// The connect loop of the first attempt can spend the whole prepare deadline, so the retry fails
// before it starts. The refusal still indicts the restored artifact: it is cleaned for the next
// prepare, because no budget is left to rebuild it in this one.

test('a refused restored artifact whose retry runs out of prepare deadline is cleaned', async () => {
vi.useFakeTimers();
try {
vi.setSystemTime(1_000);
const fixtures = makeBadCacheRecoveryFixtures();
const prepareDeadline = Deadline.fromTimeoutMs(45_000);

mockEnsureRunnerSession.mockResolvedValueOnce(fixtures.restoredSession);
mockExecuteRunnerCommandWithSession.mockImplementationOnce(async () => {
vi.setSystemTime(46_000);
throw runnerConnectFailure('runner_connect_refused');
});

await assert.rejects(
() => prepareIosRunner(IOS_SIMULATOR, { healthTimeoutMs: 90_000, prepareDeadline }),
(error: unknown) => {
assert.ok(error instanceof AppError);
assert.equal(error.details?.reason, 'prepare_deadline_expired');
return true;
},
);

assert.deepEqual(mockMarkRunnerXctestrunArtifactBadForRun.mock.calls, [
[fixtures.restoredArtifact, 'Runner did not accept connection'],
]);
assert.equal(mockEnsureRunnerSession.mock.calls.length, 1);
} finally {
vi.useRealTimers();
}
});

// The bad-cache recovery decision: a restored artifact whose runner refuses the connection, and
// whose retry fails too, is indicted, wiped for the run, and replaced by one forced rebuild — under one
// admission token owned by the prepare loop, so the rebuild is the retry a fence governs rather
// than a fresh start that slips past it (#3220).

test('prepareIosRunner rebuilds a restored artifact whose runner refuses the connection twice', async () => {
const fixtures = makeBadCacheRecoveryFixtures();

mockEnsureRunnerSession
.mockResolvedValueOnce(fixtures.restoredSession)
.mockResolvedValueOnce(fixtures.retrySession)
.mockResolvedValueOnce(fixtures.rebuiltSession);
mockExecuteRunnerCommandWithSession
.mockRejectedValueOnce(runnerConnectFailure('runner_connect_refused'))
.mockRejectedValueOnce(runnerConnectFailure('runner_connect_refused'))
.mockResolvedValueOnce({ uptimeMs: 42 });

Expand Down Expand Up @@ -153,17 +219,25 @@ test('prepareIosRunner invalidates rebuilt sessions when bad-cache recovery heal
xctestrunPath: restoredArtifact.xctestrunPath,
xctestrunArtifact: restoredArtifact,
});
const rebuiltSession = makeRunnerSession({
const retrySession = makeRunnerSession({
port: 8101,
xctestrunPath: restoredArtifact.xctestrunPath,
xctestrunArtifact: restoredArtifact,
});
const rebuiltSession = makeRunnerSession({
port: 8102,
xctestrunPath: rebuiltArtifact.xctestrunPath,
xctestrunArtifact: rebuiltArtifact,
});

mockEnsureRunnerSession
.mockResolvedValueOnce(restoredSession)
.mockResolvedValueOnce(retrySession)
.mockResolvedValueOnce(rebuiltSession);
mockExecuteRunnerCommandWithSession
.mockRejectedValueOnce(runnerConnectFailure('runner_endpoint_probe_exhausted'))
// The retry fails differently; the first failure already indicted the restored artifact.
.mockRejectedValueOnce(new AppError('COMMAND_FAILED', 'Runner health timed out'))
.mockRejectedValueOnce(new AppError('COMMAND_FAILED', 'Runner health timed out'));

await assert.rejects(
Expand All @@ -180,7 +254,8 @@ test('prepareIosRunner invalidates rebuilt sessions when bad-cache recovery heal
);

assert.deepEqual(mockInvalidateRunnerSession.mock.calls, [
[restoredSession, 'prepare_cached_runner_health_failed'],
[restoredSession, 'prepare_runner_health_retry'],
[retrySession, 'prepare_cached_runner_health_failed'],
[rebuiltSession, 'prepare_rebuilt_runner_health_failed'],
]);
assert.deepEqual(mockMarkRunnerXctestrunArtifactBadForRun.mock.calls[0], [
Expand All @@ -206,13 +281,18 @@ function makeBadCacheRecoveryFixtures() {
xctestrunPath: restoredArtifact.xctestrunPath,
xctestrunArtifact: restoredArtifact,
});
const rebuiltSession = makeRunnerSession({
const retrySession = makeRunnerSession({
port: 8101,
xctestrunPath: restoredArtifact.xctestrunPath,
xctestrunArtifact: restoredArtifact,
});
const rebuiltSession = makeRunnerSession({
port: 8102,
xctestrunPath: rebuiltArtifact.xctestrunPath,
xctestrunArtifact: rebuiltArtifact,
});

return { restoredArtifact, restoredSession, rebuiltSession };
return { restoredArtifact, restoredSession, retrySession, rebuiltSession };
}

function assertRecoveredPrepareResult(result: Awaited<ReturnType<typeof prepareIosRunner>>): void {
Expand All @@ -234,34 +314,38 @@ function assertRecoveredPrepareResult(result: Awaited<ReturnType<typeof prepareI
function assertBadCacheRecoverySideEffects(
fixtures: ReturnType<typeof makeBadCacheRecoveryFixtures>,
): void {
assert.deepEqual(mockInvalidateRunnerSession.mock.calls[0], [
fixtures.restoredSession,
'prepare_cached_runner_health_failed',
assert.deepEqual(mockInvalidateRunnerSession.mock.calls, [
[fixtures.restoredSession, 'prepare_runner_health_retry'],
[fixtures.retrySession, 'prepare_cached_runner_health_failed'],
]);
assert.deepEqual(mockMarkRunnerXctestrunArtifactBadForRun.mock.calls[0], [
fixtures.restoredArtifact,
'Runner did not accept connection',
assert.deepEqual(mockMarkRunnerXctestrunArtifactBadForRun.mock.calls, [
[fixtures.restoredArtifact, 'Runner did not accept connection'],
]);
const firstCallOptions = mockEnsureRunnerSession.mock.calls[0]?.[1] as
| { startAdmission?: unknown }
| undefined;
const retryOptions = mockEnsureRunnerSession.mock.calls[1]?.[1] as
const reuseRetryOptions = mockEnsureRunnerSession.mock.calls[1]?.[1] as
| Record<string, unknown>
| undefined;
assert.equal(reuseRetryOptions?.forceRunnerXctestrunRebuild, undefined);
const rebuildOptions = mockEnsureRunnerSession.mock.calls[2]?.[1] as
| Record<string, unknown>
| undefined;
assert.deepEqual(retryOptions, {
assert.deepEqual(rebuildOptions, {
healthTimeoutMs: 90_000,
buildTimeoutMs: 300_000,
cleanStaleBundles: true,
forceRunnerXctestrunRebuild: true,
startAdmission: firstCallOptions?.startAdmission,
});
// Both attempts of the prepare loop share one admission token: the retry
// is the replacement build for the first attempt, not a newcomer.
// Every start of the prepare loop shares one admission token: the rebuild
// is the replacement build for the failed attempts, not a newcomer.
assert.ok(firstCallOptions?.startAdmission);
assert.equal(mockExecuteRunnerCommandWithSession.mock.calls.length, 2);
assert.equal(reuseRetryOptions?.startAdmission, firstCallOptions?.startAdmission);
assert.equal(mockExecuteRunnerCommandWithSession.mock.calls.length, 3);
assert.equal(mockExecuteRunnerCommandWithSession.mock.calls[0]?.[2].command, 'uptime');
assert.equal(mockExecuteRunnerCommandWithSession.mock.calls[0]?.[4], 90_000);
assert.equal(mockExecuteRunnerCommandWithSession.mock.calls[1]?.[1], fixtures.rebuiltSession);
assert.equal(mockExecuteRunnerCommandWithSession.mock.calls[2]?.[1], fixtures.rebuiltSession);
}

function assertRecoveredPrepareDiagnostics(): void {
Expand Down
68 changes: 51 additions & 17 deletions packages/apple-runner/src/runner-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
// runner the loop's killed child was building meets a closed gate instead (#3220).
const startAdmission = openRunnerStartLoopAdmission(device.id);
let recoveryReason: string | undefined;
let suspect: SuspectCachedArtifact | undefined;
try {
for (let attempt = 1; attempt <= PREPARE_RUNNER_HEALTH_MAX_SESSION_ATTEMPTS; attempt += 1) {
const result = await runPrepareAttempt({
Expand All @@ -90,9 +91,11 @@
signal,
attempt,
recoveryReason,
suspect,
});
if (result.kind === 'prepared') return result.result;
recoveryReason = result.recoveryReason;
suspect = result.suspect;
}
} finally {
finishRunnerStartAdmission(startAdmission);
Expand All @@ -102,9 +105,19 @@
throw new AppError('COMMAND_FAILED', 'iOS runner prepare failed');
}

type RestoredRunnerSession = RunnerSession & {
xctestrunArtifact: NonNullable<RunnerSession['xctestrunArtifact']>;
};

/** A restored artifact that a failed attempt indicted, and the failure that indicted it. */
type SuspectCachedArtifact = Readonly<{
artifact: RestoredRunnerSession['xctestrunArtifact'];
reason: string;
}>;

type PrepareAttemptResult =
| { kind: 'prepared'; result: PrepareIosRunnerResult }
| { kind: 'retry'; recoveryReason: string };
| { kind: 'retry'; recoveryReason: string; suspect: SuspectCachedArtifact | undefined };

async function runPrepareAttempt(params: {
device: DeviceInfo;
Expand All @@ -113,14 +126,24 @@
signal: AbortSignal | undefined;
attempt: number;
recoveryReason: string | undefined;
suspect: SuspectCachedArtifact | undefined;
}): Promise<PrepareAttemptResult> {
const { device, command, options, signal, attempt, recoveryReason } = params;
const { device, command, options, signal, attempt, recoveryReason, suspect } = params;
const connectStartedAt = Date.now();
assertRunnerStartAdmitsPreparation(device.id, options.startAdmission);
let sessionPhaseTimeouts: PrepareDeadlinePhaseTimeouts;
try {
sessionPhaseTimeouts = readPrepareDeadlinePhaseTimeouts(options, 'runner_session');
} catch (error) {
// The indicted attempt spent the deadline, so no rebuild fits in this prepare. Cleaning the
// artifact makes the next prepare build a fresh one.
if (suspect) await markRunnerXctestrunArtifactBadForRun(suspect.artifact, suspect.reason);
throw error;
}

Check warning on line 142 in packages/apple-runner/src/runner-lifecycle.ts

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

minor: One ambiguous refusal still cleans the shared cache when the retry has no budget left

On a loaded host, attempt 1's connect loop can consume nearly the whole prepare deadline and fail with `runner_connect_refused`; attempt 2 then throws `prepare_deadline_expired` before any session starts, and the new catch calls `markRunnerXctestrunArtifactBadForRun`, cleaning the shared `cache-<key>` that concurrent first opens are reading. The clean fires on a single indictment with no second failure, contradicting the rule that the first indictment retries without cleaning, and the wipe provides no benefit to the current prepare since it still fails.
Comment thread
thymikee marked this conversation as resolved.
Resolved
const session = await ensureRunnerSession(device, {
...options,
cleanStaleBundles: attempt > 1 ? true : options.cleanStaleBundles,
...readPrepareDeadlinePhaseTimeouts(options, 'runner_session'),
...sessionPhaseTimeouts,
});
assertExpectedRunnerSession(session, options.expectedRunnerSessionId);
const connectMs = Date.now() - connectStartedAt;
Expand All @@ -146,6 +169,7 @@
signal,
attempt,
error,
suspect,
});
}
}
Expand All @@ -158,6 +182,7 @@
signal: AbortSignal | undefined;
attempt: number;
error: unknown;
suspect: SuspectCachedArtifact | undefined;
}): Promise<PrepareAttemptResult> {
const { device, session, command, options, signal, attempt, error } = params;
assertRunnerStartAdmitsPreparation(device.id, options.startAdmission);
Expand All @@ -168,7 +193,10 @@
throw error;
}
if (shouldRetainRunnerSession(appErr)) throw error;
if (attempt === 1 && shouldRecoverBadCachedRunnerArtifact(appErr, session)) {
// A slow boot on a loaded host fails the same way as a corrupt artifact, and the rebuild cleans
// a cache that concurrent sessions read. The first indictment retries on the cache; a retry that
// also fails, in any way, rebuilds it (#4689).
if (params.suspect && hasRestoredRunnerArtifact(session)) {
return {
kind: 'prepared',
result: await recoverBadCachedRunnerArtifact({
Comment thread
thymikee marked this conversation as resolved.
Resolved
Expand All @@ -177,7 +205,7 @@
command,
options,
signal,
error: appErr,
reason: params.suspect.reason,
}),
};
}
Expand All @@ -204,21 +232,24 @@
reason,
},
});
return { kind: 'retry', recoveryReason: reason };
return {
kind: 'retry',
recoveryReason: reason,
suspect: shouldRecoverBadCachedRunnerArtifact(appErr, session)
? { artifact: session.xctestrunArtifact, reason }
: undefined,
};
}

async function recoverBadCachedRunnerArtifact(params: {
device: DeviceInfo;
session: RunnerSession & {
xctestrunArtifact: NonNullable<RunnerSession['xctestrunArtifact']>;
};
session: RestoredRunnerSession;
command: RunnerCommand;
options: PrepareIosRunnerOptions;
signal: AbortSignal | undefined;
error: AppError;
reason: string;
}): Promise<PrepareIosRunnerResult> {
const { device, session, command, options, signal, error } = params;
const reason = error.message || 'runner_health_failed';
const { device, session, command, options, signal, reason } = params;
await invalidateRunnerSession(session, 'prepare_cached_runner_health_failed');
await markRunnerXctestrunArtifactBadForRun(session.xctestrunArtifact, reason);
const connectStartedAt = Date.now();
Expand Down Expand Up @@ -611,12 +642,15 @@
function shouldRecoverBadCachedRunnerArtifact(
error: AppError,
session: RunnerSession,
): session is RunnerSession & {
xctestrunArtifact: NonNullable<RunnerSession['xctestrunArtifact']>;
} {
): session is RestoredRunnerSession {
return hasRestoredRunnerArtifact(session) && shouldRebuildCachedRunnerArtifact(error);
}

/** A freshly built artifact is never rebuilt: the build that just made it would not differ. */
function hasRestoredRunnerArtifact(session: RunnerSession): session is RestoredRunnerSession {
const artifact = session.xctestrunArtifact;
if (!artifact || artifact.cache === 'miss') return false;
return shouldRebuildCachedRunnerArtifact(error);
if (!artifact) return false;
return artifact.cache !== 'miss';
}

function wrapPrepareHealthFailure(
Expand Down
Loading