Skip to content

Commit 4633472

Browse files
committed
refactor(daemon): tighten the open-wait request seams
The request scope now parses the `waitMs` option once and supplies the resulting budget to the wait, instead of validating it before the device lookup and reading it again afterward. The reader fails closed when a caller supplies a budget but its option declaration has gone missing. The refusal helper checks the command directly, so reuse outside the open path cannot offer `--wait` to an interaction.
1 parent 8cbf480 commit 4633472

3 files changed

Lines changed: 48 additions & 38 deletions

File tree

‎src/daemon/__tests__/open-device-contention-wait.test.ts‎

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,15 @@ function openRequest(flags: CommandFlags): DaemonRequest {
3535
};
3636
}
3737

38+
function beginWait(
39+
params: Omit<Parameters<typeof beginOpenDeviceWait>[0], 'budgetMs'>,
40+
): ReturnType<typeof beginOpenDeviceWait> {
41+
return beginOpenDeviceWait({
42+
...params,
43+
budgetMs: readOpenWaitBudgetMs(params.req),
44+
});
45+
}
46+
3847
function session(address: string): SessionState {
3948
return {
4049
name: 'default',
@@ -102,23 +111,17 @@ test('the daemon holds a budget to the bounds its own option declares', () => {
102111
code: 'INVALID_ARGS',
103112
});
104113
}
105-
106-
// A budget that cannot be spent is refused before the device it was meant for is even in play.
107-
expect(
108-
thrownBy(() =>
109-
beginOpenDeviceWait({
110-
req: openRequest({ waitMs: (max ?? 0) + 1 }),
111-
sessionName: OPENER_ADDRESS,
112-
sessionStore: new SessionStore('/tmp/ad-wait-unresolved'),
113-
deviceId: undefined,
114-
}),
115-
),
116-
).toMatchObject({ code: 'INVALID_ARGS' });
117114
});
118115

119116
test('a refusal offers the flag only to a caller that did not arrive carrying it', () => {
120117
expect(describeOpenWaitForRefusal(openRequest({}))).toEqual({ offersDeviceWait: true });
121118

119+
// An interaction has no `--wait` of its own, even though the shared refusal builder may one day
120+
// receive its request.
121+
expect(describeOpenWaitForRefusal({ ...openRequest({}), command: 'tap' })).toEqual({
122+
offersDeviceWait: false,
123+
});
124+
122125
// The open that passed `--wait` and still hit a busy device is not being sent off to run the
123126
// same open with the flag it used.
124127
const carried = openRequest({ waitMs: 1_000 });
@@ -133,23 +136,23 @@ test('only a fresh open with a budget and a resolved device gets a wait', () =>
133136
const budget = openRequest({ waitMs: 5_000 });
134137

135138
expect(
136-
beginOpenDeviceWait({
139+
beginWait({
137140
req: { ...budget, command: 'tap' },
138141
sessionName: OPENER_ADDRESS,
139142
sessionStore,
140143
deviceId: IOS_SIMULATOR.id,
141144
}),
142145
).toBeUndefined();
143146
expect(
144-
beginOpenDeviceWait({
147+
beginWait({
145148
req: budget,
146149
sessionName: OPENER_ADDRESS,
147150
sessionStore,
148151
deviceId: undefined,
149152
}),
150153
).toBeUndefined();
151154
expect(
152-
beginOpenDeviceWait({
155+
beginWait({
153156
req: openRequest({}),
154157
sessionName: OPENER_ADDRESS,
155158
sessionStore,
@@ -160,7 +163,7 @@ test('only a fresh open with a budget and a resolved device gets a wait', () =>
160163
// An open onto a session that already exists is bound to a device nobody else is refused for.
161164
sessionStore.set(OPENER_ADDRESS, session(OPENER_ADDRESS));
162165
expect(
163-
beginOpenDeviceWait({
166+
beginWait({
164167
req: budget,
165168
sessionName: OPENER_ADDRESS,
166169
sessionStore,
@@ -174,7 +177,7 @@ test('a free device is read once in the store and records no wait', async () =>
174177
const store = makeSessionStore('agent-device-open-wait-');
175178
const looks = vi.spyOn(store, 'findByDevice');
176179

177-
const wait = beginOpenDeviceWait({
180+
const wait = beginWait({
178181
req,
179182
sessionName: OPENER_ADDRESS,
180183
sessionStore: store,
@@ -194,7 +197,7 @@ test('a device that frees up ends the wait without claiming a spent budget', asy
194197

195198
await waitUntil(
196199
() =>
197-
beginOpenDeviceWait({
200+
beginWait({
198201
req,
199202
sessionName: OPENER_ADDRESS,
200203
sessionStore: store,
@@ -212,7 +215,7 @@ test('an open yields the device lock to a session that took the device after the
212215
vi.useFakeTimers();
213216
const req = openRequest({ waitMs: 30_000 });
214217
const store = makeSessionStore('agent-device-open-wait-');
215-
const wait = beginOpenDeviceWait({
218+
const wait = beginWait({
216219
req,
217220
sessionName: OPENER_ADDRESS,
218221
sessionStore: store,
@@ -253,7 +256,7 @@ test('a budget that runs out busy costs the whole budget, then lets the open ref
253256
const req = openRequest({ waitMs: 1000 });
254257
const store = storeWithHolder();
255258
const looks = vi.spyOn(store, 'findByDevice');
256-
const wait = beginOpenDeviceWait({
259+
const wait = beginWait({
257260
req,
258261
sessionName: OPENER_ADDRESS,
259262
sessionStore: store,
@@ -289,7 +292,7 @@ test('a request the client gave up on stops waiting at its next poll', async ()
289292
vi.useFakeTimers();
290293
const req = openRequest({ waitMs: 60_000 });
291294
markRequestCanceled('req-open-wait');
292-
const wait = beginOpenDeviceWait({
295+
const wait = beginWait({
293296
req,
294297
sessionName: OPENER_ADDRESS,
295298
sessionStore: storeWithHolder(),

‎src/daemon/open-device-contention-wait.ts‎

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { getFlagDefinitionsForKey } from '@agent-device/command-registry/flag-re
22
import { readOptionalInteger } from '@agent-device/contracts/command';
33
import { emitRequestProgress, throwIfRequestCanceled } from '@agent-device/host-kit/request';
44
import { Deadline, sleep } from '@agent-device/host-kit/retry';
5+
import { AppError } from '@agent-device/kernel/errors';
56
import type { DaemonRequest } from './daemon-request.ts';
67
import type { SessionStore } from './session-store.ts';
78
import type { SessionRecoveryOptions } from './session-recovery-hints.ts';
@@ -22,10 +23,18 @@ const DEVICE_CONTENTION_POLL_MS = 250;
2223
* declaration instead of trusting whichever surface assembled the request.
2324
*/
2425
export function readOpenWaitBudgetMs(req: DaemonRequest): number | undefined {
25-
const declaration = getFlagDefinitionsForKey('waitMs')[0];
26-
return readOptionalInteger((req.flags ?? {}) as Record<string, unknown>, 'waitMs', {
27-
min: declaration?.min,
28-
max: declaration?.max,
26+
const flags = (req.flags ?? {}) as Record<string, unknown>;
27+
if (flags.waitMs === undefined) return undefined;
28+
const [declaration] = getFlagDefinitionsForKey('waitMs');
29+
if (!declaration) {
30+
throw new AppError(
31+
'INTERNAL_ERROR',
32+
'The waitMs option has no flag declaration whose bounds the daemon can enforce.',
33+
);
34+
}
35+
return readOptionalInteger(flags, 'waitMs', {
36+
min: declaration.min,
37+
max: declaration.max,
2938
});
3039
}
3140

@@ -51,7 +60,7 @@ export function readOpenWaitAttempt(req: DaemonRequest): SessionRecoveryOptions
5160
export function describeOpenWaitForRefusal(req: DaemonRequest): SessionRecoveryOptions {
5261
return {
5362
...readOpenWaitAttempt(req),
54-
offersDeviceWait: typeof req.flags?.waitMs !== 'number',
63+
offersDeviceWait: req.command === 'open' && typeof req.flags?.waitMs !== 'number',
5564
};
5665
}
5766

@@ -92,19 +101,18 @@ export type OpenDeviceWait = {
92101
*
93102
* `deviceId` is the device the request's own execution-lock plan reserves, so the wait and the
94103
* lock agree on which device is being waited for without resolving a target a second time.
104+
* `budgetMs` must already have been read through {@link readOpenWaitBudgetMs}, allowing the request
105+
* scope to reject an out-of-range budget before resolving that device.
95106
*/
96107
export function beginOpenDeviceWait(params: {
97108
req: DaemonRequest;
109+
budgetMs: number | undefined;
98110
sessionName: string;
99111
sessionStore: SessionStore;
100112
deviceId: string | undefined;
101113
}): OpenDeviceWait | undefined {
102-
const { req, sessionName, sessionStore, deviceId } = params;
103-
if (req.command !== 'open') return undefined;
104-
// The budget is read before anything else, so a request carrying a budget it may not spend is
105-
// refused whether or not its device turned out to be resolvable.
106-
const budgetMs = readOpenWaitBudgetMs(req);
107-
if (budgetMs === undefined) return undefined;
114+
const { req, budgetMs, sessionName, sessionStore, deviceId } = params;
115+
if (req.command !== 'open' || budgetMs === undefined) return undefined;
108116
if (deviceId === undefined || sessionStore.get(sessionName)) return undefined;
109117
return createOpenDeviceWait({ req, sessionName, sessionStore, deviceId, budgetMs });
110118
}

‎src/daemon/request-execution-scope.ts‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -176,12 +176,10 @@ export async function createRequestExecutionScope(params: {
176176
}
177177
try {
178178
assertLockedLeaseAdmissionPreflight(scopedReq);
179-
// An out-of-range `--wait` is refused before resolving the target device or taking any lock.
180-
// `beginOpenDeviceWait` still needs the device id from the lock plan, but validating the budget
181-
// is independent of that lookup.
182-
if (scopedReq.command === 'open') {
183-
readOpenWaitBudgetMs(scopedReq);
184-
}
179+
// Parse the budget once, before resolving the target device or taking any lock. The lock plan
180+
// still supplies the device to wait for, but an out-of-range budget is refused before either.
181+
const openWaitBudgetMs =
182+
scopedReq.command === 'open' ? readOpenWaitBudgetMs(scopedReq) : undefined;
185183
const lockPlan: RequestExecutionLockPlan = shouldLockSessionExecution(command)
186184
? await resolveRequestExecutionLockPlan({ req: scopedReq, sessionName, sessionStore })
187185
: { keys: [], deviceId: undefined };
@@ -190,6 +188,7 @@ export async function createRequestExecutionScope(params: {
190188
// needs, so waiting after taking it would have an open block its own recovery.
191189
const openWait = beginOpenDeviceWait({
192190
req: scopedReq,
191+
budgetMs: openWaitBudgetMs,
193192
sessionName,
194193
sessionStore,
195194
deviceId: lockPlan.deviceId,

0 commit comments

Comments
 (0)