Skip to content

Commit 05e52bb

Browse files
thymikeeclaude
andcommitted
fix(revyl): hold a joining allocation to its own caller
A second allocation that joined the start already running for its lease inherited the first caller's request and threw away its own. It accepted connect flags Revyl refuses on every other path, because the gate sat in the branch that starts a device, and it waited out the patience of the caller that arrived first, reporting that caller's failure as its own. Both are per-caller facts, so both are now read from the joining context: the flags are refused before the join, and the wait is bounded by the joiner's own signal and deadline. Giving up on a join stops nothing at Revyl: the device belongs to every caller that joined the start, so the callers still waiting get theirs and the runtime holds one session. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 6bebd73 commit 05e52bb

3 files changed

Lines changed: 229 additions & 50 deletions

File tree

‎packages/provider-revyl/src/revyl-session.ts‎

Lines changed: 75 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,24 @@ export type RevylStartRequestInput = Readonly<{
5858
deadline?: number;
5959
}>;
6060

61+
/**
62+
* One caller's own patience: the signal it cancels with and the deadline it stops at. Both are optional,
63+
* and a caller with neither waits for whatever its work takes.
64+
*/
65+
export type RevylCallerBudget = Readonly<{ signal?: AbortSignal; deadline?: number }>;
66+
67+
/**
68+
* One caller's wait for work this process is already doing, bounded by that caller's own deadline and
69+
* canceled with its own signal. `settled` says whether this wait is what ended the race, which is what
70+
* lets a caller report its own cancellation rather than the outcome of a shared request it stopped
71+
* watching. `dispose` retires the listener once the work itself is done.
72+
*/
73+
export type RevylCallerWait<T> = Readonly<{
74+
promise: Promise<T>;
75+
settled: () => boolean;
76+
dispose: () => void;
77+
}>;
78+
6179
/**
6280
* What one start has to undo: the session that holds the rented device, and the run that routes to
6381
* it. `sessionId` is always the id the backend was told, or the one it answered with, so the end
@@ -205,23 +223,21 @@ async function submitRevylStart(
205223
}
206224

207225
/**
208-
* The caller's own wait for the start, bounded by its whole-allocation deadline and canceled with it,
209-
* or absent when the caller gave it neither and the request's timeout is all there is to wait for.
210-
* `settled` says whether this wait is what ended the race, which is what decides whether the session
211-
* the request named has to be stopped before the failure returns.
226+
* One caller's wait for work this process is already doing, bounded by that caller's own deadline and
227+
* canceled with its own signal. `settled` says whether this wait is what ended the race, which is what
228+
* lets a caller report its own cancellation rather than the outcome of a shared request it stopped
229+
* watching. `dispose` retires the listener once the work itself is done.
212230
*/
213-
type RevylCallerWait = Readonly<{
214-
promise: Promise<RevylStartDeviceResponse>;
215-
settled: () => boolean;
216-
dispose: () => void;
217-
}>;
218-
219-
function callerWait(deadline: number, input: RevylStartRequestInput): RevylCallerWait | undefined {
220-
if (input.deadline === undefined && input.signal === undefined) return undefined;
231+
export function revylCallerWait<T>(
232+
deadline: number,
233+
budget: RevylCallerBudget,
234+
onGiveUp: () => unknown,
235+
): RevylCallerWait<T> | undefined {
236+
if (budget.deadline === undefined && budget.signal === undefined) return undefined;
221237
const parts: AbortSignal[] = [];
222238
if (Number.isFinite(deadline))
223239
parts.push(AbortSignal.timeout(Math.max(0, deadline - Date.now())));
224-
if (input.signal !== undefined) parts.push(input.signal);
240+
if (budget.signal !== undefined) parts.push(budget.signal);
225241
const signal = parts.length === 1 ? parts[0]! : AbortSignal.any(parts);
226242
let rejected = false;
227243
let onAbort: () => void = () => {};
@@ -232,9 +248,9 @@ function callerWait(deadline: number, input: RevylStartRequestInput): RevylCalle
232248
// A signal that is already aborted never fires its listener, so that wait has to start over the
233249
// edge rather than sit on it.
234250
const promise = signal.aborted
235-
? Promise.reject(reject(startCanceled(input)))
236-
: new Promise<RevylStartDeviceResponse>((_, rejectPromise) => {
237-
onAbort = () => rejectPromise(reject(startCanceled(input)));
251+
? Promise.reject(reject(onGiveUp()))
252+
: new Promise<T>((_, rejectPromise) => {
253+
onAbort = () => rejectPromise(reject(onGiveUp()));
238254
signal.addEventListener('abort', onAbort, { once: true });
239255
});
240256
return Object.freeze({
@@ -244,6 +260,17 @@ function callerWait(deadline: number, input: RevylStartRequestInput): RevylCalle
244260
});
245261
}
246262

263+
/**
264+
* The caller's own wait for the start, or absent when the caller gave it neither a deadline nor a
265+
* signal and the request's timeout is all there is to wait for.
266+
*/
267+
function callerWait(
268+
deadline: number,
269+
input: RevylStartRequestInput,
270+
): RevylCallerWait<RevylStartDeviceResponse> | undefined {
271+
return revylCallerWait<RevylStartDeviceResponse>(deadline, input, () => startCanceled(input));
272+
}
273+
247274
/** The start phase's budget: the caller's whole-allocation deadline when it is shorter than the client's. */
248275
function startDeadline(input: RevylStartRequestInput): number {
249276
const own = Date.now() + REVYL_START_DEVICE_TIMEOUT_MS;
@@ -259,6 +286,37 @@ function startCanceled(input: RevylStartRequestInput): AppError {
259286
);
260287
}
261288

289+
/**
290+
* The failure for a caller that stopped waiting for a device: its own cancellation when it hung up, and
291+
* the budget that ran out when it did not. `budgetMs` is the wait that ended, which is the number the
292+
* report has to name — the readiness phase's own budget there, the caller's whole deadline for a join
293+
* that never had a phase of its own.
294+
*/
295+
export function revylCallerGaveUp(
296+
platform: RevylPlatform,
297+
budget: RevylCallerBudget,
298+
budgetMs: number,
299+
): AppError {
300+
if (budget.signal?.aborted) {
301+
return new AppError(
302+
'COMMAND_FAILED',
303+
'The Revyl device start was canceled before it was ready.',
304+
{ reason: 'request_canceled', platform },
305+
budget.signal.reason,
306+
);
307+
}
308+
return new AppError(
309+
'COMMAND_FAILED',
310+
`Revyl did not report a ready device within ${budgetMs} ms.`,
311+
{
312+
reason: 'provider-not-ready',
313+
timeoutMs: budgetMs,
314+
...(budget.deadline === undefined ? {} : { deadline: budget.deadline }),
315+
hint: 'Retry the command; Revyl may have had no device of that model available.',
316+
},
317+
);
318+
}
319+
262320
/**
263321
* Whether a `start_device` that never reached the caller may still have rented a device. Only a status
264322
* the backend settled with a refusal rules that out, and that is one read of the client's status table.
@@ -427,20 +485,9 @@ async function untilRevylWorkerReady(
427485
/** Fails the moment the readiness budget is spent, whatever a poll that was already sent answers. */
428486
function requireTime(deadline: RevylDeadline, input: RevylStartRequestInput): void {
429487
if (Date.now() < deadline.at) return;
430-
if (input.signal?.aborted) throw startCanceled(input);
431488
// The budget is the caller's deadline when it is shorter, so the number named has to be the one that
432489
// actually ran out.
433-
const budgetMs = deadline.budgetMs;
434-
throw new AppError(
435-
'COMMAND_FAILED',
436-
`Revyl did not report a ready device within ${budgetMs} ms.`,
437-
{
438-
reason: 'provider-not-ready',
439-
timeoutMs: budgetMs,
440-
...(input.deadline === undefined ? {} : { deadline: input.deadline }),
441-
hint: 'Retry the command; Revyl may have had no device of that model available.',
442-
},
443-
);
490+
throw revylCallerGaveUp(input.platform, input, deadline.budgetMs);
444491
}
445492

446493
/** The remaining readiness budget, so a poll that outlives it is canceled rather than awaited. */

‎packages/provider-revyl/src/runtime.test.ts‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,83 @@ test('two allocations of one lease that overlap rent one device, and both report
110110
]);
111111
});
112112

113+
test('a joining allocation refuses the flags Revyl has no field for before it joins', async () => {
114+
// The first caller's start is still unanswered when the second arrives with a flag Revyl reads never.
115+
// An allocation that reuses a device the daemon already holds carries a profile of its own, and a join
116+
// that skipped the gate would accept a flag the same caller is refused for on every other path.
117+
const fixture = await backend({ startDelayMs: 400 });
118+
const runtime = fixture.createRuntime();
119+
const lease = revylLease('ios');
120+
const first = runtime.leaseLifecycle?.allocate?.(lease);
121+
await waitFor(() => fixture.paths().some((path) => path.endsWith('/start_device')));
122+
123+
await assert.rejects(
124+
async () =>
125+
await runtime.leaseLifecycle?.allocate?.(lease, { flags: { providerProject: 'team' } }),
126+
(error: unknown) =>
127+
error instanceof AppError &&
128+
error.code === 'INVALID_ARGS' &&
129+
error.details?.provider === 'revyl' &&
130+
error.message.includes('--provider-project'),
131+
);
132+
133+
// The refused caller is answered at once, while the caller that rented the device is left alone.
134+
assert.equal((await first)?.providerSessionId, revylSessionIdForLease('lease-1'));
135+
assert.equal(
136+
fixture.paths().filter((path) => path.endsWith('/start_device')).length,
137+
1,
138+
'the refused join must not rent a device of its own',
139+
);
140+
});
141+
142+
test('a canceled joiner reports its own cancellation while the shared start runs on', async () => {
143+
// Both callers wait on one start. The second hangs up first, and the rule is that this changes only
144+
// what that caller hears: waiting out the first caller's patience instead would report the wrong
145+
// failure, and stopping the start would take the device from the caller still waiting for it.
146+
const fixture = await backend({ startDelayMs: 400 });
147+
const runtime = fixture.createRuntime();
148+
const lease = revylLease('ios');
149+
const first = runtime.leaseLifecycle?.allocate?.(lease);
150+
await waitFor(() => fixture.paths().some((path) => path.endsWith('/start_device')));
151+
152+
const controller = new AbortController();
153+
const joining = runtime.leaseLifecycle!.allocate!(lease, { signal: controller.signal });
154+
controller.abort();
155+
156+
await assert.rejects(
157+
async () => await joining,
158+
(error: unknown) => error instanceof AppError && error.details?.reason === 'request_canceled',
159+
);
160+
161+
// The caller that started the device still gets it, and the runtime holds exactly one session.
162+
assert.equal((await first)?.providerSessionId, revylSessionIdForLease('lease-1'));
163+
await runtime.shutdown();
164+
assert.deepEqual(stops(fixture), [
165+
`POST /api/v1/execution/device/sessions/${revylSessionIdForLease('lease-1')}/stop`,
166+
]);
167+
});
168+
169+
test("a joiner whose deadline expires names its own budget, not the other caller's", async () => {
170+
// The deadline is the other half of the same rule: a joiner that gave Revyl 60 ms cannot be made to
171+
// wait for the patience of the caller that started first, and the failure names the wait it was given.
172+
const fixture = await backend({ startDelayMs: 800 });
173+
const runtime = fixture.createRuntime();
174+
const lease = revylLease('ios');
175+
const first = runtime.leaseLifecycle?.allocate?.(lease);
176+
await waitFor(() => fixture.paths().some((path) => path.endsWith('/start_device')));
177+
178+
await assert.rejects(
179+
async () => await runtime.leaseLifecycle?.allocate?.(lease, { deadline: Date.now() + 60 }),
180+
(error: unknown) =>
181+
error instanceof AppError &&
182+
error.details?.reason === 'provider-not-ready' &&
183+
typeof error.details?.timeoutMs === 'number' &&
184+
error.details.timeoutMs < 700,
185+
);
186+
187+
assert.equal((await first)?.providerSessionId, revylSessionIdForLease('lease-1'));
188+
});
189+
113190
test('release stops the session once, and shutdown stops the sessions a lease never released', async () => {
114191
const fixture = await backend();
115192
const runtime = fixture.createRuntime();

‎packages/provider-revyl/src/runtime.ts‎

Lines changed: 77 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,14 @@ import {
2222
type RevylPlatform,
2323
} from './device.ts';
2424
import { createRevylClient, isRevylSessionGone, type RevylClient } from './revyl-client.ts';
25-
import { startRevylSession, stopRevylSession, type RevylSession } from './revyl-session.ts';
25+
import {
26+
revylCallerGaveUp,
27+
revylCallerWait,
28+
startRevylSession,
29+
stopRevylSession,
30+
type RevylCallerBudget,
31+
type RevylSession,
32+
} from './revyl-session.ts';
2633
import { createRevylInteractor } from './interactor.ts';
2734
import { providerRuntimeOwner } from '@agent-device/contracts/platform-runtime';
2835
import { resolveRevylRuntimeInstance } from './runtime-instance.ts';
@@ -115,7 +122,7 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime {
115122
* One entry per lease whose device is being rented, kept until the session reaches the table. A second
116123
* allocation of that lease joins it rather than renting a device nobody will stop.
117124
*/
118-
private readonly pendingAllocations = new Map<string, Promise<RevylAllocation | undefined>>();
125+
private readonly pendingAllocations = new Map<string, Promise<RevylAllocation>>();
119126
private shuttingDown = false;
120127
readonly provider = REVYL_PROVIDER;
121128

@@ -260,28 +267,65 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime {
260267
* nothing pointing at it; the second call joins the first instead. The session reaches the table while
261268
* the start is still registered, so a third allocation cannot arrive in the gap between one finishing
262269
* and the other learning about it and rent a device of its own.
270+
*
271+
* A caller joins only after its own flags are refused and its own budget is installed, so joining
272+
* neither accepts a profile Revyl would ignore nor inherits the patience of the caller that started
273+
* first.
263274
*/
264275
private async allocateOncePerLease(
265276
lease: DeviceLease,
266277
context?: LeaseLifecycleContext,
267278
): Promise<RevylAllocation | undefined> {
279+
const platform =
280+
lease.leaseProvider === this.provider
281+
? platformForRevylLeaseBackend(lease.backend)
282+
: undefined;
283+
if (platform === undefined) return undefined;
284+
const { rejectRefusedRevylProfileFields } = await import('./session-allocation.ts');
285+
// Before the join below: an allocation that reuses a live lease still carries flags of its own,
286+
// and Revyl reads none of them — whether it starts a device or joins one that is starting.
287+
rejectRefusedRevylProfileFields(context);
268288
const pending = this.pendingAllocations.get(lease.leaseId);
269-
if (pending) {
270-
// The device was taken by the call already running, so this one is not the one to end it.
271-
const joined = await pending;
272-
return joined === undefined ? undefined : { ...joined, rentedNow: false };
273-
}
274-
const starting = this.allocate(lease, context);
289+
if (pending) return await this.joinAllocation(pending, platform, context);
290+
const starting = this.allocate(lease, platform, context);
275291
this.pendingAllocations.set(lease.leaseId, starting);
276292
try {
277293
const allocated = await starting;
278-
if (allocated && !this.shuttingDown) this.sessions.set(lease.leaseId, allocated.session);
294+
// Recorded while the start is still registered, so no allocation can arrive in the gap after it
295+
// and rent a device of its own.
296+
if (!this.shuttingDown) this.sessions.set(lease.leaseId, allocated.session);
279297
return allocated;
280298
} finally {
281299
this.pendingAllocations.delete(lease.leaseId);
282300
}
283301
}
284302

303+
/**
304+
* Waits for the start another caller already has running for this lease, within this caller's own
305+
* budget. Hanging up here never stops that start: the device belongs to every caller that joined it, so
306+
* this one reports its own cancellation or its own expired deadline and the start runs on for the
307+
* callers still waiting. A joiner never took the device, so it never ends it either way.
308+
*/
309+
private async joinAllocation(
310+
pending: Promise<RevylAllocation>,
311+
platform: RevylPlatform,
312+
context?: LeaseLifecycleContext,
313+
): Promise<RevylAllocation> {
314+
const budget = revylCallerBudget(context);
315+
// The number the report names is the wait this caller was granted, so it is measured from the moment
316+
// the join started rather than from the deadline's own epoch instant.
317+
const joinedAt = Date.now();
318+
const gaveUp = revylCallerWait<never>(budget.deadline ?? Number.POSITIVE_INFINITY, budget, () =>
319+
revylCallerGaveUp(platform, budget, Math.max(0, (budget.deadline ?? joinedAt) - joinedAt)),
320+
);
321+
if (gaveUp === undefined) return await joinOf(pending);
322+
try {
323+
return await joinOf(Promise.race([pending, gaveUp.promise]));
324+
} finally {
325+
gaveUp.dispose();
326+
}
327+
}
328+
285329
/** Resolves once no allocation is in flight, so shutdown stops everything that exists. */
286330
private async awaitInFlightAllocations(): Promise<void> {
287331
const pending = [...this.inFlightAllocations];
@@ -291,21 +335,14 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime {
291335
}
292336

293337
/**
294-
* One allocation's session, with `rentedNow` naming whether this call is the one that took the
295-
* device. A lease of another provider, or of a backend Revyl has no device for, is answered with
296-
* nothing, which is how the core reads "this provider has no allocation to report".
338+
* One allocation's session, with `rentedNow` naming whether this call is the one that took the device.
339+
* The lease is already known to be Revyl's, and its context already refused, by the caller above.
297340
*/
298341
private async allocate(
299342
lease: DeviceLease,
343+
platform: RevylPlatform,
300344
context?: LeaseLifecycleContext,
301-
): Promise<RevylAllocation | undefined> {
302-
if (lease.leaseProvider !== this.provider) return undefined;
303-
const platform = platformForRevylLeaseBackend(lease.backend);
304-
if (!platform) return undefined;
305-
const { rejectRefusedRevylProfileFields } = await import('./session-allocation.ts');
306-
// Before the reuse below: a repeat allocation of a live lease carries flags of its own, and
307-
// Revyl reads none of them a second time.
308-
rejectRefusedRevylProfileFields(context);
345+
): Promise<RevylAllocation> {
309346
if (this.shuttingDown) throw shuttingDownDuring(lease.leaseId, 'allocate');
310347
// A repeat allocation of a live lease is that same device, and Revyl is asked for nothing.
311348
const existing = this.sessions.get(lease.leaseId);
@@ -340,8 +377,7 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime {
340377
appUrl: resolveRevylAppUrl(context),
341378
deviceModel: selection.deviceModel,
342379
osVersion: selection.osVersion,
343-
...(context?.signal === undefined ? {} : { signal: context.signal }),
344-
...(context?.deadline === undefined ? {} : { deadline: context.deadline }),
380+
...revylCallerBudget(context),
345381
});
346382
}
347383

@@ -422,6 +458,25 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime {
422458
}
423459
}
424460

461+
/**
462+
* The caller's own patience, read from the lease context it arrived with. A caller that names neither
463+
* waits for whatever the work takes.
464+
*/
465+
function revylCallerBudget(context?: LeaseLifecycleContext): RevylCallerBudget {
466+
return {
467+
...(context?.signal === undefined ? {} : { signal: context.signal }),
468+
...(context?.deadline === undefined ? {} : { deadline: context.deadline }),
469+
};
470+
}
471+
472+
/**
473+
* What a joined allocation reports: the device the caller that started it rented, which this call did
474+
* not take and therefore does not owe ending.
475+
*/
476+
async function joinOf(pending: Promise<RevylAllocation>): Promise<RevylAllocation> {
477+
return { ...(await pending), rentedNow: false };
478+
}
479+
425480
/** Recovery and lifecycle calls arrive for one provider's lease; anything else is a routing bug. */
426481
function requireRevylLease(lease: DeviceLease, operation: 'recover' | 'release'): void {
427482
if (lease.leaseProvider === REVYL_PROVIDER && platformForRevylLeaseBackend(lease.backend)) return;

0 commit comments

Comments
 (0)