Skip to content

Commit fb603fa

Browse files
thymikeeclaude
andcommitted
fix(revyl): share one in-flight stop per lease and refuse mismatched joins
A release, a recovery and a shutdown that overlap now join the lease's one in-flight /stop instead of each sending their own; a failed stop clears it so the next caller retries. An allocation that joins a lease started for a different app URL, device model or OS version is refused rather than handed that device. The fixture tracks Revyl sessions per session id. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 53d684b commit fb603fa

4 files changed

Lines changed: 157 additions & 47 deletions

File tree

‎packages/provider-revyl/src/revyl-backend.fixtures.ts‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import http from 'node:http';
22
import type { AddressInfo } from 'node:net';
33
import type { DeviceLease } from '@agent-device/contracts/device';
4+
import { isRecord } from '@agent-device/kernel/record';
45
import { REVYL_PROVIDER } from './device.ts';
56
import { createRevylRuntime, type RevylRuntime } from './runtime.ts';
67

@@ -98,13 +99,11 @@ export async function startRevylFixtureBackend(
9899
/** The platform and session id of the last `start_device`, which is what later answers report. */
99100
let started: { platform: string; sessionId: string } | undefined;
100101
/**
101-
* Whether Revyl would hold a session right now. A session is made when `start_device` is *answered* —
102-
* with a start delay, later than the request — and a confirmed `/stop` ends it, so a stop sent inside
103-
* that gap names a session that does not exist yet.
102+
* The sessions Revyl would hold right now, by id. A session is made when its `start_device` is
103+
* *answered* — with a start delay, later than the request — and a confirmed `/stop` for that id ends
104+
* it, so a stop sent inside that gap names a session that does not exist yet.
104105
*/
105-
const sessionIsOpen = () =>
106-
answered.some((path) => path.endsWith('/start_device')) &&
107-
!answered.some((path) => path.endsWith('/stop'));
106+
const openSessions = new Set<string>();
108107
const screen = options.screen ?? DEFAULT_IOS_SCREEN;
109108

110109
const overrides = new Map(Object.entries(options.respond ?? {}));
@@ -129,6 +128,13 @@ export async function startRevylFixtureBackend(
129128
// recorded on receipt — cannot say.
130129
response.on('finish', () => {
131130
answered.push(`${method} ${url}`);
131+
if (response.statusCode !== 200) return;
132+
const startedId = isRecord(recorded) ? recorded.session_id : undefined;
133+
if (url.endsWith('/start_device') && typeof startedId === 'string') {
134+
openSessions.add(startedId);
135+
}
136+
const stoppedId = sessionIdIn(url);
137+
if (stoppedId !== undefined) openSessions.delete(stoppedId);
132138
});
133139
const override = overrides.get(`${method} ${url}`);
134140
if (override !== undefined) {
@@ -166,7 +172,8 @@ export async function startRevylFixtureBackend(
166172
stop: () => {
167173
// With `sessionExistsOnceStarted`, a stop that arrives before the start has answered names a
168174
// session Revyl never made. The caller must not read that 404 as a release it never got.
169-
if (options.sessionExistsOnceStarted && !sessionIsOpen()) {
175+
const stopping = sessionIdIn(url);
176+
if (options.sessionExistsOnceStarted && (!stopping || !openSessions.has(stopping))) {
170177
return { status: 404, body: { detail: 'no such session', error: 'Not Found' } };
171178
}
172179
return {

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

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

113+
test('a joining allocation for a different app or device is refused, not handed the first device', async () => {
114+
const fixture = await backend({ startDelayMs: 200 });
115+
const runtime = fixture.createRuntime();
116+
const lease = revylLease('ios');
117+
const first = runtime.leaseLifecycle?.allocate?.(lease, {
118+
initialApp: 'https://apps.test/a.zip',
119+
});
120+
121+
await assert.rejects(
122+
async () =>
123+
await runtime.leaseLifecycle?.allocate?.(lease, {
124+
initialApp: 'https://apps.test/b.zip',
125+
flags: { device: 'iPhone 16' },
126+
}),
127+
(error: unknown) =>
128+
error instanceof AppError &&
129+
error.details?.reason === 'provider-lease-request-mismatch' &&
130+
JSON.stringify(error.details?.fields) === JSON.stringify(['appUrl', 'deviceModel']),
131+
);
132+
// A joiner that names nothing of its own accepts the device the lease already has.
133+
const [started, joined] = await Promise.all([first, runtime.leaseLifecycle?.allocate?.(lease)]);
134+
assert.equal(joined?.providerSessionId, started?.providerSessionId);
135+
assert.equal(fixture.paths().filter((path) => path.endsWith('start_device')).length, 1);
136+
});
137+
113138
test('a joining allocation refuses the flags Revyl has no field for before it joins', async () => {
114139
// The first caller's start is still unanswered when the second arrives with a flag Revyl reads never.
115140
// An allocation that reuses a device the daemon already holds carries a profile of its own, and a join
@@ -242,6 +267,24 @@ test('release stops the session once, and shutdown stops the sessions a lease ne
242267
]);
243268
});
244269

270+
test('a release, a recovery and a shutdown that overlap send one stop between them', async () => {
271+
const stopPath = `POST /api/v1/execution/device/sessions/${revylSessionIdForLease('lease-1')}/stop`;
272+
const fixture = await backend({
273+
respond: { [stopPath]: { delayMs: 150, body: { success: true, request_accepted: true } } },
274+
});
275+
const runtime = fixture.createRuntime();
276+
const lease = revylLease('ios');
277+
await runtime.leaseLifecycle?.allocate?.(lease);
278+
279+
await Promise.all([
280+
runtime.leaseLifecycle?.release?.(lease),
281+
runtime.recoverExpiredLease(lease),
282+
runtime.shutdown(),
283+
]);
284+
285+
assert.deepEqual(stops(fixture), [stopPath]);
286+
});
287+
245288
test('a stop Revyl refuses keeps the lease for a retry and reports the session it could not release', async () => {
246289
const stopPath = `POST /api/v1/execution/device/sessions/${revylSessionIdForLease('lease-1')}/stop`;
247290
const fixture = await backend({

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

Lines changed: 55 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import { createRevylInteractor } from './interactor.ts';
3737
import { providerRuntimeOwner } from '@agent-device/contracts/platform-runtime';
3838
import { resolveRevylRuntimeInstance } from './runtime-instance.ts';
3939
import { revylSessionIdForLease } from './session-identity.ts';
40+
import type { RevylStartRequest } from './session-allocation.ts';
4041

4142
export type RevylRuntimeOptions = Readonly<{
4243
apiKey: string;
@@ -81,6 +82,8 @@ type RevylStopOutcome = Readonly<{
8182
* session that start produced, and the `/stop` that has not been confirmed yet.
8283
*/
8384
class RevylLeaseEntry {
85+
/** What the start was asked for, which a joining allocation has to ask for too. */
86+
readonly request: RevylStartRequest;
8487
/**
8588
* Settles once this lease's `start_device` has answered and the stop that a failed start owed has
8689
* settled with it, so a reader that awaits it cannot miss a rented device.
@@ -92,15 +95,26 @@ class RevylLeaseEntry {
9295
stop: RevylRentedSession | undefined;
9396
/** Whether Revyl confirmed `/stop` for {@link stop}. Only this lets the entry leave the map. */
9497
stopConfirmed: boolean;
98+
/**
99+
* The `/stop` in flight for {@link stop}, shared by every release, recovery and shutdown that arrives
100+
* while it runs, so Revyl sees one stop per attempt. Cleared once it settles, so a failed stop is
101+
* retried by the next caller.
102+
*/
103+
stopping: Promise<string | undefined> | undefined;
95104

96105
/**
97106
* `start` fills this entry in as it goes; it may write the entry's own fields, but it must never wait
98107
* on them, because the assignment below has not happened while its body first runs.
99108
*/
100-
constructor(start: (entry: RevylLeaseEntry) => Promise<RevylStartOutcome>) {
109+
constructor(
110+
request: RevylStartRequest,
111+
start: (entry: RevylLeaseEntry) => Promise<RevylStartOutcome>,
112+
) {
113+
this.request = request;
101114
this.session = undefined;
102115
this.stop = undefined;
103116
this.stopConfirmed = false;
117+
this.stopping = undefined;
104118
this.start = start(this);
105119
}
106120
}
@@ -251,16 +265,25 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime {
251265
? platformForRevylLeaseBackend(lease.backend)
252266
: undefined;
253267
if (platform === undefined) return undefined;
254-
const { rejectRefusedRevylProfileFields } = await import('./session-allocation.ts');
268+
const {
269+
rejectRefusedRevylProfileFields,
270+
requireSameRevylStartRequest,
271+
resolveRevylStartRequest,
272+
} = await import('./session-allocation.ts');
255273
// Before the join below: an allocation that reuses a live lease still carries flags of its own,
256274
// and Revyl reads none of them — whether it starts a device or joins one that is starting.
257275
rejectRefusedRevylProfileFields(context);
276+
const request = resolveRevylStartRequest(context, {
277+
...(this.options.deviceModel === undefined ? {} : { deviceModel: this.options.deviceModel }),
278+
...(this.options.osVersion === undefined ? {} : { osVersion: this.options.osVersion }),
279+
});
258280
// Nothing between here and the entry's registration awaits, so one caller can never miss another's.
259281
if (this.shuttingDown) throw shuttingDownDuring(lease.leaseId, 'allocate');
260282
const existing = this.leases.get(lease.leaseId);
283+
if (existing) requireSameRevylStartRequest(lease.leaseId, existing.request, request);
261284
// The caller that started the device waits on it the same way a joiner does: one entry, one awaitable,
262285
// each caller bounded by its own patience.
263-
const entry = existing ?? this.rent(lease, platform, context);
286+
const entry = existing ?? this.rent(lease, platform, request, context);
264287
const outcome = await this.join(entry, platform, context);
265288
if (this.shuttingDown) {
266289
// The device this start rented is already an entry shutdown is ending, so this caller only reports
@@ -276,8 +299,15 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime {
276299
* map before the first `await`, so an allocation that arrives mid-start joins it instead of renting a
277300
* second device, and a release that arrives then has somewhere to find the session.
278301
*/
279-
private rent(lease: DeviceLease, platform: RevylPlatform, context?: LeaseLifecycleContext) {
280-
const entry = new RevylLeaseEntry((target) => this.runStart(target, lease, platform, context));
302+
private rent(
303+
lease: DeviceLease,
304+
platform: RevylPlatform,
305+
request: RevylStartRequest,
306+
context?: LeaseLifecycleContext,
307+
) {
308+
const entry = new RevylLeaseEntry(request, (target) =>
309+
this.runStart(target, lease, platform, context),
310+
);
281311
this.leases.set(lease.leaseId, entry);
282312
return entry;
283313
}
@@ -297,7 +327,13 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime {
297327
const leaseId = lease.leaseId;
298328
let started: RevylStart;
299329
try {
300-
started = await this.startLeaseDevice(lease, platform, context);
330+
started = await startRevylSession(this.client, lease, {
331+
platform,
332+
appUrl: entry.request.appUrl,
333+
deviceModel: entry.request.deviceModel,
334+
osVersion: entry.request.osVersion,
335+
...revylCallerBudget(context),
336+
});
301337
} catch (error) {
302338
// The start failed somewhere this module does not model, and the request may already have gone out,
303339
// so the id it carried is the handle the entry has to end.
@@ -323,7 +359,7 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime {
323359
entry.stop = rented;
324360
// The entry ends what a failed start rented rather than waiting for a release to ask: the device is
325361
// billed from the moment Revyl made it, and this is the first moment its id is known.
326-
const failure = await this.stopRented(rented);
362+
const failure = await this.stopOwed(entry, rented);
327363
if (failure === undefined) {
328364
entry.stopConfirmed = true;
329365
this.closeLease(leaseId, entry);
@@ -383,7 +419,7 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime {
383419
const session = entry.session;
384420
// A failed start has already ended its own session before this point, and a caller that releases such
385421
// a lease must not make Revyl see a second stop for a session already gone.
386-
const failure = entry.stopConfirmed ? undefined : await this.stopRented(target);
422+
const failure = entry.stopConfirmed ? undefined : await this.stopOwed(entry, target);
387423
if (failure === undefined) {
388424
entry.stopConfirmed = true;
389425
this.closeLease(leaseId, entry);
@@ -418,6 +454,17 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime {
418454
return outcome.data ?? { providerSessionId: outcome.providerSessionId };
419455
}
420456

457+
/** The entry's one in-flight `/stop`, started by the first caller and joined by the rest. */
458+
private stopOwed(
459+
entry: RevylLeaseEntry,
460+
target: RevylRentedSession,
461+
): Promise<string | undefined> {
462+
entry.stopping ??= this.stopRented(target).finally(() => {
463+
entry.stopping = undefined;
464+
});
465+
return entry.stopping;
466+
}
467+
421468
/**
422469
* One `/stop`, with Revyl's own "no such session" read as released: that device is not rented. The
423470
* failure's message is what the caller reports; `undefined` is the confirmation the entry needs.
@@ -431,38 +478,6 @@ class RevylRuntimeImplementation implements ProviderDeviceRuntime {
431478
}
432479
}
433480

434-
/**
435-
* One start. The caller's own budget rides along, so a start that runs past it fails as that caller's
436-
* expired patience rather than as a device nobody asked for; the request itself keeps the client's
437-
* longer budget, because its answer is the only thing that names what was rented.
438-
*/
439-
private async startLeaseDevice(
440-
lease: DeviceLease,
441-
platform: RevylPlatform,
442-
context?: LeaseLifecycleContext,
443-
): Promise<RevylStart> {
444-
const { resolveRevylAppUrl, resolveRevylDeviceSelection } =
445-
await import('./session-allocation.ts');
446-
const selection = resolveRevylDeviceSelection(
447-
context,
448-
this.options.deviceModel === undefined && this.options.osVersion === undefined
449-
? {}
450-
: {
451-
...(this.options.deviceModel === undefined
452-
? {}
453-
: { deviceModel: this.options.deviceModel }),
454-
...(this.options.osVersion === undefined ? {} : { osVersion: this.options.osVersion }),
455-
},
456-
);
457-
return await startRevylSession(this.client, lease, {
458-
platform,
459-
appUrl: resolveRevylAppUrl(context),
460-
deviceModel: selection.deviceModel,
461-
osVersion: selection.osVersion,
462-
...revylCallerBudget(context),
463-
});
464-
}
465-
466481
private sessionForDevice(device: DeviceInfo): RevylSession | undefined {
467482
const parsed = parseRevylDeviceId(device.id);
468483
if (!parsed) return undefined;

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

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { LeaseLifecycleContext } from '@agent-device/contracts/device';
2+
import { AppError } from '@agent-device/kernel/errors';
23
import { rejectRefusedProviderProfileFields } from '@agent-device/contracts/provider-profile-fields';
34
import { REVYL_PROFILE_FIELDS } from './profile-fields.ts';
45

@@ -41,6 +42,50 @@ export function resolveRevylDeviceSelection(
4142
};
4243
}
4344

45+
/** What one allocation asks Revyl to start: the app to install and the device to pick. */
46+
export type RevylStartRequest = Readonly<{
47+
appUrl?: string;
48+
deviceModel?: string;
49+
osVersion?: string;
50+
}>;
51+
52+
export function resolveRevylStartRequest(
53+
context: LeaseLifecycleContext | undefined,
54+
fallback: Readonly<{ deviceModel?: string; osVersion?: string }>,
55+
): RevylStartRequest {
56+
const appUrl = resolveRevylAppUrl(context);
57+
return {
58+
...(appUrl === undefined ? {} : { appUrl }),
59+
...resolveRevylDeviceSelection(context, fallback),
60+
};
61+
}
62+
63+
/**
64+
* Refuses an allocation that joins a lease whose device was started for a different app or device.
65+
* A field the joiner leaves unset accepts whatever the lease has; one it names has to match, because
66+
* the joiner would otherwise be handed a device it did not ask for.
67+
*/
68+
export function requireSameRevylStartRequest(
69+
leaseId: string,
70+
started: RevylStartRequest,
71+
joining: RevylStartRequest,
72+
): void {
73+
const differing = (Object.keys(joining) as (keyof RevylStartRequest)[]).filter(
74+
(field) => joining[field] !== undefined && joining[field] !== started[field],
75+
);
76+
if (differing.length === 0) return;
77+
throw new AppError(
78+
'INVALID_ARGS',
79+
`Revyl lease ${leaseId} already has a device started for a different ${differing.join(', ')}.`,
80+
{
81+
reason: 'provider-lease-request-mismatch',
82+
leaseId,
83+
fields: differing,
84+
hint: 'Disconnect and connect again to rent a device for the new app or device selection.',
85+
},
86+
);
87+
}
88+
4489
/** One text selection a profile or flag carries: trimmed, and absent when it is blank. */
4590
export function revylTextFlag(value: unknown): string | undefined {
4691
const text = typeof value === 'string' ? value.trim() : '';

0 commit comments

Comments
 (0)