Skip to content

Commit dacec4a

Browse files
committed
fix(daemon): retain execution locks through binding cleanup
ADR 0019 requires request bindings to dispose before device/session lock release. Await the shared cleanup outcome under initial and retained execution locks, then let response finalization preserve primary failures and report cleanup failures. At base 4c1c786, six blocked-cleanup regressions fail: queued same-session or same-device requests enter on success, throw, and cancellation. With the fix all six pass; the scope and open-wait suites pass (42 tests). No request-binding disposal bound exists; no timeout was added. Device dispatch is unchanged.
1 parent 4c1c786 commit dacec4a

2 files changed

Lines changed: 90 additions & 10 deletions

File tree

‎packages/daemon/src/core/__tests__/request-runtime-binding-router.test.ts‎

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import fs from 'node:fs';
22
import { expect, test, vi } from 'vitest';
3+
import {
4+
clearRequestCanceled,
5+
markRequestCanceled,
6+
throwIfRequestCanceled,
7+
} from '@agent-device/host-kit/request';
8+
import { AppError } from '@agent-device/kernel/errors';
39
import { applicationLifecycleOperationFacts } from '@agent-device/contracts/application-lifecycle-runtime';
410
import {
511
type DeviceBinding,
@@ -51,6 +57,65 @@ test('primary request failure survives a rejecting binding disposal', async () =
5157
expect(phases).toContain('request_binding_cleanup_failed');
5258
});
5359

60+
for (const outcome of ['success', 'throw', 'cancellation'] as const) {
61+
for (const key of ['session', 'device'] as const) {
62+
test(`binding cleanup holds the ${key} execution lock after ${outcome}`, async () => {
63+
const runtime = makeGateway();
64+
const { handler, sessionStore } = makeHandler(runtime.gateway);
65+
const current = sessionStore.get('session')!;
66+
sessionStore.publish('other-session', { ...current, name: 'other-session', actions: [] });
67+
const requestId = `cleanup-${key}-${outcome}`;
68+
let markCleanupStarted: () => void = () => {};
69+
let finishCleanup: () => void = () => {};
70+
const cleanupStarted = new Promise<void>((resolve) => {
71+
markCleanupStarted = resolve;
72+
});
73+
const cleanupFinished = new Promise<void>((resolve) => {
74+
finishCleanup = resolve;
75+
});
76+
runtime.bindingDispose.mockImplementationOnce(async () => {
77+
markCleanupStarted();
78+
await cleanupFinished;
79+
});
80+
let doctorCalls = 0;
81+
vi.spyOn(runtime.operations, 'appLogDoctor').mockImplementation(async () => {
82+
if (doctorCalls++ > 0) return { backend: 'android', checks: {}, notes: [] };
83+
if (outcome === 'throw') throw new AppError('COMMAND_FAILED', 'doctor failed');
84+
if (outcome === 'cancellation') {
85+
markRequestCanceled(requestId);
86+
throwIfRequestCanceled(requestId);
87+
}
88+
return { backend: 'android', checks: {}, notes: [] };
89+
});
90+
const first = handler({ ...request(['doctor']), meta: { requestId } });
91+
await cleanupStarted;
92+
const second = handler({
93+
...request(['doctor']),
94+
session: key === 'session' ? 'session' : 'other-session',
95+
meta: { requestId: `${requestId}-queued` },
96+
});
97+
try {
98+
await new Promise<void>((resolve) => setImmediate(resolve));
99+
expect(runtime.bind).toHaveBeenCalledTimes(1);
100+
} finally {
101+
finishCleanup();
102+
clearRequestCanceled(requestId);
103+
}
104+
const [firstResponse, secondResponse] = await Promise.all([first, second]);
105+
expect(firstResponse.ok).toBe(outcome === 'success');
106+
if (outcome === 'cancellation') {
107+
expect(firstResponse).toMatchObject({
108+
ok: false,
109+
error: { code: 'COMMAND_FAILED', details: { reason: 'request_canceled' } },
110+
});
111+
}
112+
expect(secondResponse.ok).toBe(true);
113+
expect(runtime.bind).toHaveBeenCalledTimes(2);
114+
expect(runtime.bindingDispose).toHaveBeenCalledTimes(2);
115+
});
116+
}
117+
}
118+
54119
function makeHandler(gateway: DeviceRuntimeGateway<PlatformRuntimeOperations>) {
55120
const sessionStore = makeSessionStore('request-runtime-binding-router-');
56121
sessionStore.publish('session', {
@@ -181,7 +246,7 @@ function makeGateway(disposeError?: Error) {
181246
bind,
182247
shutdown: async () => {},
183248
};
184-
return { gateway, bind, bindingDispose, forceCleanup, handle };
249+
return { gateway, bind, bindingDispose, forceCleanup, handle, operations };
185250
}
186251

187252
const unavailableRecording = Object.freeze({

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

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,27 @@ export async function createRequestExecutionScope(params: {
266266
claimRecoveryGateway: params.claimRecoveryGateway,
267267
});
268268

269+
let bindingCleanup: Promise<void> | undefined;
270+
const disposeBindings = (): Promise<void> => {
271+
bindingCleanup ??= (async () => {
272+
try {
273+
await runtimeBindings?.[Symbol.asyncDispose]();
274+
} finally {
275+
await claimAdmission?.[Symbol.asyncDispose]();
276+
}
277+
})();
278+
return bindingCleanup;
279+
};
280+
const runAdmittedAndDispose = async <T>(task: () => Promise<T>): Promise<T> => {
281+
try {
282+
return await scope.runAdmitted(task);
283+
} finally {
284+
// The router consumes the same cleanup outcome when it finalizes the response,
285+
// preserving a primary command failure over a secondary disposal failure.
286+
await Promise.allSettled([disposeBindings()]);
287+
}
288+
};
289+
269290
const scope: RequestExecutionScope = {
270291
req: scopedReq,
271292
command,
@@ -330,22 +351,16 @@ export async function createRequestExecutionScope(params: {
330351
runLocked: async (task) => {
331352
throwIfRequestCanceled(scopedReq.meta?.requestId);
332353
if (!openWait) {
333-
return await requestExecutionLocks.run(async () => await scope.runAdmitted(task));
354+
return await requestExecutionLocks.run(async () => await runAdmittedAndDispose(task));
334355
}
335356
return await openWait.runWhenDeviceIsUnheld({
336357
acquireLocks: requestExecutionLocks.run,
337-
task: async () => await scope.runAdmitted(task),
358+
task: async () => await runAdmittedAndDispose(task),
338359
});
339360
},
340361
// Claims outlive the bindings they guard: release only once no device
341362
// operation from this request can still run.
342-
[Symbol.asyncDispose]: async () => {
343-
try {
344-
await runtimeBindings?.[Symbol.asyncDispose]();
345-
} finally {
346-
await claimAdmission?.[Symbol.asyncDispose]();
347-
}
348-
},
363+
[Symbol.asyncDispose]: disposeBindings,
349364
};
350365
requestScopeFinalizers.set(scope, (response) => {
351366
if (shouldRecordRequestEvents) {

0 commit comments

Comments
 (0)