Skip to content

Commit 0e12a46

Browse files
committed
fix(ios-runner): keep the RUNNER_BUSY refusal through a mid-window wait deadline
A wait bounds each poll with its own abort signal and keeps the last typed refusal as the wait's cause. Inside the resend window that deadline surfaced as a bare cancellation, so a wait timing out mid-window reported a stalled capture and dropped the runner's own code, message and hint. The resend loop now remembers the last busy refusal and rethrows it when the abort is a caller deadline; only a cancelled request reports as a cancellation. Also: jitter 0 on the resend policy so the documented 5.4s window is the actual one, and a test pinning that a mutating command meets RUNNER_BUSY once with no status probe and no resend.
1 parent 890069c commit 0e12a46

2 files changed

Lines changed: 98 additions & 20 deletions

File tree

‎packages/platform-apple/src/runner/__tests__/runner-command-busy-resend.test.ts‎

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -135,28 +135,79 @@ test('read-only transport failures keep the three-attempt resend budget', async
135135
assert.equal(sentCommands().filter((command) => command === 'snapshot').length, 3);
136136
});
137137

138-
test('a cancelled request wakes the RUNNER_BUSY delay instead of sleeping it out', async () => {
138+
test('a wait deadline landing mid-window rethrows the last RUNNER_BUSY refusal, not a cancel', async () => {
139+
// `wait` bounds each poll with its own abort signal (runWithinWaitDeadline) and keeps the last
140+
// typed refusal as the wait's cause. The refusal must therefore survive the deadline: a bare
141+
// cancellation would make the wait report a stalled capture and drop the runner's own code.
139142
vi.useFakeTimers();
140-
const controller = new AbortController();
143+
const deadline = new AbortController();
141144
mockExecuteRunnerCommandWithSession
142145
.mockRejectedValueOnce(busyRefusal())
143146
.mockResolvedValue({ nodes: [], truncated: false });
144147

145148
const pending = runAppleRunnerCommand(
146149
IOS_SIMULATOR,
147150
{ command: 'snapshot' },
148-
{ signal: controller.signal },
151+
{ requestId: 'req-wait', signal: deadline.signal },
152+
);
153+
const settled = pending.then(
154+
() => undefined,
155+
(error: unknown) => error,
156+
);
157+
await vi.advanceTimersByTimeAsync(50);
158+
deadline.abort(new DOMException('Wait deadline exceeded', 'TimeoutError'));
159+
await vi.advanceTimersByTimeAsync(0);
160+
const error = await settled;
161+
162+
assert.ok(error instanceof AppError, `expected the refusal, got ${String(error)}`);
163+
assert.equal(error.details?.runnerErrorCode, 'RUNNER_BUSY');
164+
assert.equal(error.details?.retriable, true);
165+
assert.deepEqual(sentCommands(), ['snapshot']);
166+
});
167+
168+
test('a cancelled request wakes the RUNNER_BUSY delay and reports the cancellation', async () => {
169+
vi.useFakeTimers();
170+
const request = new AbortController();
171+
appleRunnerTestHost.update({ getRequestSignal: () => request.signal });
172+
mockExecuteRunnerCommandWithSession
173+
.mockRejectedValueOnce(busyRefusal())
174+
.mockResolvedValue({ nodes: [], truncated: false });
175+
176+
const pending = runAppleRunnerCommand(
177+
IOS_SIMULATOR,
178+
{ command: 'snapshot' },
179+
{ requestId: 'req-cancelled' },
149180
);
150181
const settled = pending.then(
151182
() => undefined,
152183
(error: unknown) => error,
153184
);
154185
// Inside the first 200ms delay; the next attempt would otherwise succeed at the timer.
155186
await vi.advanceTimersByTimeAsync(50);
156-
controller.abort();
187+
requestCancellation.markRequestCanceled('req-cancelled');
188+
request.abort();
157189
await vi.advanceTimersByTimeAsync(0);
158190
const error = await settled;
159191

160192
assert.ok(isRequestCanceledError(error), `expected a canceled request, got ${String(error)}`);
161193
assert.deepEqual(sentCommands(), ['snapshot']);
162194
});
195+
196+
test('a mutating command meets RUNNER_BUSY once, with no status probe and no resend', async () => {
197+
// The status-recovery bypass for structured replies reaches mutating commands too: the refusal
198+
// says the tap did not run, so there is nothing to recover and nothing is replayed.
199+
mockExecuteRunnerCommandWithSession.mockRejectedValueOnce(busyRefusal());
200+
201+
await assert.rejects(
202+
() => runAppleRunnerCommand(IOS_SIMULATOR, { command: 'tap', x: 120, y: 240 }),
203+
(error: unknown) => {
204+
assert.ok(error instanceof AppError);
205+
assert.equal(error.details?.runnerErrorCode, 'RUNNER_BUSY');
206+
assert.equal(error.details?.recovery, undefined);
207+
return true;
208+
},
209+
);
210+
211+
assert.deepEqual(sentCommands(), ['tap']);
212+
assert.equal(mockInvalidateRunnerSession.mock.calls.length, 0);
213+
});

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

Lines changed: 43 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import { retryWithPolicy, emitDiagnostic } from './host.ts';
1+
import { retryWithPolicy, emitDiagnostic, getRequestSignal, isRequestCanceled } from './host.ts';
22
import { isIosFamily, type DeviceInfo } from '@agent-device/kernel/device';
3+
import { isRequestCanceledError } from '@agent-device/kernel/errors';
34
import {
45
ensureRunnerSession,
56
readRunnerSessionLiveness,
@@ -36,22 +37,38 @@ import { RUNNER_COMMAND_TIMEOUT_MS } from './runner-transport.ts';
3637
/**
3738
* Attempts a read-only command may spend on one error class; 1 means no resend. A `RUNNER_BUSY`
3839
* refusal is the runner refusing fast on purpose while it drains abandoned XCTest work (#1105), so
39-
* that budget has to outlast the drain. The window is a heuristic, not a measurement: with 200ms
40-
* doubling to a 1s cap it spans roughly 4 to 6.5s of delay across eight attempts before jitter and
41-
* round trips, and a drain that outlives it still surfaces as `RUNNER_BUSY` (the runner's own
42-
* `abandonedForSeconds=` marker in runner.log is the evidence for tuning it). Transport failures
43-
* keep the pre-existing three attempts. The budget is positional: the error on each attempt sets
44-
* how many attempts the loop may reach in total, so three busy refusals followed by a transport
45-
* failure resend no further.
40+
* that budget has to outlast the drain. The window is a heuristic, not a measurement: 200ms doubling
41+
* to a 1s cap, no jitter, is 5.4s of delay across eight attempts before round trips, and a drain
42+
* that outlives it still surfaces as `RUNNER_BUSY` (the runner's own `abandonedForSeconds=` marker
43+
* in runner.log is the evidence for tuning it). Transport failures keep the pre-existing three
44+
* attempts. The budget is positional: the error on each attempt sets how many attempts the loop may
45+
* reach in total, so three busy refusals followed by a transport failure resend no further.
4646
*/
4747
const RUNNER_BUSY_RESEND_ATTEMPTS = 8;
4848
const TRANSPORT_RESEND_ATTEMPTS = 3;
49+
const READ_ONLY_RESEND_POLICY = {
50+
maxAttempts: RUNNER_BUSY_RESEND_ATTEMPTS,
51+
baseDelayMs: 200,
52+
maxDelayMs: 1_000,
53+
jitter: 0,
54+
};
4955

5056
function readOnlyResendBudget(error: unknown): number {
5157
if (isRunnerBusyError(error)) return RUNNER_BUSY_RESEND_ATTEMPTS;
5258
return isRetryableRunnerError(error) ? TRANSPORT_RESEND_ATTEMPTS : 1;
5359
}
5460

61+
/**
62+
* Whether the request itself was cancelled, as opposed to one caller's deadline on this command.
63+
* A `wait` bounds each poll with its own abort signal; that deadline landing inside the resend
64+
* window must not erase the refusal the runner already gave.
65+
*/
66+
function isRunnerRequestCancelled(options: AppleRunnerCommandOptions): boolean {
67+
return (
68+
isRequestCanceled(options.requestId) || getRequestSignal(options.requestId)?.aborted === true
69+
);
70+
}
71+
5572
export async function runAppleRunnerCommand(
5673
device: DeviceInfo,
5774
command: RunnerCommand,
@@ -61,27 +78,37 @@ export async function runAppleRunnerCommand(
6178
assertRunnerRequestActive(options.requestId);
6279
const runnerCommand = withRunnerCommandId(command);
6380
const provider = resolveAppleRunnerRuntime(device, options);
64-
if (isReadOnlyRunnerCommand(runnerCommand)) {
65-
return retryWithPolicy(
81+
if (!isReadOnlyRunnerCommand(runnerCommand)) {
82+
return provider.runCommand(device, runnerCommand, options);
83+
}
84+
let lastBusyRefusal: unknown;
85+
try {
86+
return await retryWithPolicy(
6687
() => {
6788
assertRunnerRequestActive(options.requestId);
6889
return provider.runCommand(device, runnerCommand, options);
6990
},
7091
{
71-
maxAttempts: RUNNER_BUSY_RESEND_ATTEMPTS,
72-
baseDelayMs: 200,
73-
maxDelayMs: 1_000,
92+
...READ_ONLY_RESEND_POLICY,
7493
shouldRetry: (error, attempt) => {
7594
assertRunnerRequestActive(options.requestId);
95+
if (isRunnerBusyError(error)) lastBusyRefusal = error;
7696
return attempt < readOnlyResendBudget(error);
7797
},
7898
},
79-
// The busy window is seconds long, so a cancelled request must wake the delay instead of
80-
// sleeping it out and sending one more attempt.
99+
// The busy window is seconds long, so an abort must wake the delay instead of sleeping it
100+
// out and sending one more attempt.
81101
{ signal: resolveRunnerRequestSignal(options) },
82102
);
103+
} catch (error) {
104+
// A caller's deadline (a `wait` poll bounding this capture) that lands mid-window still has an
105+
// answer: the runner refused, and that typed refusal is what the caller can act on. Only a
106+
// cancelled request reports as a bare cancellation.
107+
if (isRequestCanceledError(error) && lastBusyRefusal && !isRunnerRequestCancelled(options)) {
108+
throw lastBusyRefusal;
109+
}
110+
throw error;
83111
}
84-
return provider.runCommand(device, runnerCommand, options);
85112
}
86113

87114
export async function notifyIosRunnerAppRelaunched(

0 commit comments

Comments
 (0)