Skip to content

Commit e5813a1

Browse files
thymikeeclaude
andcommitted
refactor(kernel): track held execution locks in keyed-lock
The kernel keyed lock now answers which locks an async context holds, including locks a request retains partway through, instead of a second registry in request-execution-locks. - Lock scopes form a chain with live parents, so a lock a holder scope takes later is visible to every scope nested in it. - `withKeyedLockHolder` runs a task that can `hold` locks until it ends; `heldKeyedLockKeys` lists the keys the current context holds. - Request execution locks use them: a held key re-enters, and the same-Mac rule (ADR 0035) is one check. The enclosing-request store, the held set, and the two re-entry special cases are gone. - A nested request whose initial key its parent retained now re-enters it; before, it waited on its own parent. - The close-refusal test builds its error from the production platform refusal over a stubbed app list. Closes #3876. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent c8b944c commit e5813a1

5 files changed

Lines changed: 469 additions & 122 deletions

File tree

‎packages/daemon/src/server/__tests__/request-execution-locks.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -279,3 +279,22 @@ test('a nested request retaining a lock its enclosing request holds re-enters it
279279
}),
280280
).resolves.toBe('reentered');
281281
});
282+
283+
test('a nested request whose initial key its parent retained re-enters it instead of waiting on its parent', async () => {
284+
const locks = new Map<string, Promise<unknown>>();
285+
const parent = createRequestExecutionLocks({ locks, initialKeys: ['session:replay'] });
286+
287+
await expect(
288+
parent.run(async () => {
289+
// A fresh replay retains its device once its first open selects it.
290+
await parent.retainDevice('SIM-001');
291+
// A later step runs as a full request whose plan names the same device.
292+
const step = createRequestExecutionLocks({
293+
locks,
294+
initialKeys: ['session:replay', 'device:SIM-001'],
295+
});
296+
return await step.run(async () => 'reentered');
297+
}),
298+
).resolves.toBe('reentered');
299+
expect(locks.size).toBe(0);
300+
});
Lines changed: 27 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,18 @@
1-
import { AsyncLocalStorage } from 'node:async_hooks';
2-
import { withKeyedLock } from '@agent-device/kernel/keyed-lock';
1+
import {
2+
heldKeyedLockKeys,
3+
withKeyedLock,
4+
withKeyedLockHolder,
5+
type KeyedLockHolder,
6+
} from '@agent-device/kernel/keyed-lock';
37
import { hostDeviceIdOf } from '@agent-device/kernel/device';
48
import { AppError } from '@agent-device/kernel/errors';
59
import type { RequestExecutionLockKey } from './request-binding.ts';
610

7-
type RetainedExecutionLock = {
8-
acquired: Promise<void>;
9-
completion: Promise<void>;
10-
release(): void;
11-
};
12-
1311
export type RequestExecutionLocks = {
1412
run<T>(task: () => Promise<T>): Promise<T>;
1513
retainDevice(deviceId: string): Promise<void>;
1614
};
1715

18-
/**
19-
* The locks each enclosing request holds, innermost last. A request nested in another (a batch
20-
* step) takes its own locks while the enclosing request still holds its own, so the same-host rule
21-
* below applies to the locks it takes up front as much as to the ones it retains later.
22-
*/
23-
const enclosingRequestLocks = new AsyncLocalStorage<
24-
readonly ReadonlySet<RequestExecutionLockKey>[]
25-
>();
26-
2716
/**
2817
* Owns the stable execution locks for one request and any device lock discovered
2918
* after admission. Dynamic device retention is used by a fresh replay whose
@@ -35,72 +24,50 @@ export function createRequestExecutionLocks(params: {
3524
scope?: Readonly<{ signal: AbortSignal }>;
3625
}): RequestExecutionLocks {
3726
const { locks, initialKeys, scope } = params;
38-
const initialKeySet = new Set(initialKeys);
39-
const retainedLocks = new Map<RequestExecutionLockKey, RetainedExecutionLock>();
40-
// Every lock this request holds, for the requests nested in it to see.
41-
const heldLocks = new Set<RequestExecutionLockKey>();
42-
const enclosing = (): readonly ReadonlySet<RequestExecutionLockKey>[] =>
43-
enclosingRequestLocks.getStore() ?? [];
27+
let holder: KeyedLockHolder | undefined;
4428
let running = false;
4529

46-
const releaseRetainedLocks = async (): Promise<void> => {
47-
const held = [...retainedLocks.values()];
48-
for (const lock of held) lock.release();
49-
await Promise.all(held.map(async (lock) => await lock.completion));
50-
retainedLocks.clear();
51-
};
52-
5330
return {
5431
run: async (task) => {
5532
if (running) {
5633
throw new Error('Request execution locks cannot run the same scope concurrently.');
5734
}
5835
running = true;
59-
const outer = enclosing();
60-
const heldOutside = outer.flatMap((held) => [...held]);
36+
// What the requests this one is nested in hold (a batch step runs inside its batch). Its own
37+
// initial keys are taken in sorted order, waiting for each in turn.
38+
const heldOutside = heldRequestLockKeys(locks);
6139
try {
6240
return await withRequestExecutionLockKeys(
6341
locks,
6442
initialKeys,
65-
async () => await enclosingRequestLocks.run([...outer, heldLocks], task),
43+
async () =>
44+
await withKeyedLockHolder(async (taken) => {
45+
holder = taken;
46+
return await task();
47+
}),
6648
scope?.signal,
67-
(key) => {
68-
// An enclosing request already holding this lock re-enters it without waiting.
69-
if (!heldOutside.includes(key)) assertSameHostLockFree(locks, key, heldOutside);
70-
heldLocks.add(key);
71-
},
49+
(key) => assertSameHostLockFree(locks, key, heldOutside),
7250
);
7351
} finally {
74-
heldLocks.clear();
75-
try {
76-
await releaseRetainedLocks();
77-
} finally {
78-
running = false;
79-
}
52+
holder = undefined;
53+
running = false;
8054
}
8155
},
8256
retainDevice: async (deviceId) => {
83-
if (!running) {
57+
if (!holder) {
8458
throw new Error('A device execution lock can only be retained by a running request.');
8559
}
8660
const key = `device:${deviceId}` as const;
87-
if (initialKeySet.has(key)) return;
88-
// An enclosing request already holds it, and this request runs inside that hold.
89-
if (enclosing().some((held) => held.has(key))) return;
90-
91-
let retained = retainedLocks.get(key);
92-
if (!retained) {
93-
const heldKeys = [...heldLocks, ...enclosing().flatMap((held) => [...held])];
94-
assertSameHostLockFree(locks, key, heldKeys);
95-
retained = retainExecutionLock(locks, key, scope?.signal);
96-
retainedLocks.set(key, retained);
97-
heldLocks.add(key);
98-
}
99-
await retained.acquired;
61+
assertSameHostLockFree(locks, key, heldRequestLockKeys(locks));
62+
await holder.hold(locks, key, scope?.signal);
10063
},
10164
};
10265
}
10366

67+
function heldRequestLockKeys(locks: Map<string, Promise<unknown>>): RequestExecutionLockKey[] {
68+
return heldKeyedLockKeys(locks) as RequestExecutionLockKey[];
69+
}
70+
10471
/**
10572
* Whether the request already holds a lock on `deviceId`'s host or one of its app devices
10673
* (ADR 0035). Waiting for a second lock on the same host while holding one could cross another
@@ -113,7 +80,8 @@ function assertSameHostLockFree(
11380
key: RequestExecutionLockKey,
11481
heldKeys: readonly RequestExecutionLockKey[],
11582
): void {
116-
if (!key.startsWith('device:')) return;
83+
// A held key re-enters, and only device keys belong to a host.
84+
if (heldKeys.includes(key) || !key.startsWith('device:')) return;
11785
const deviceId = key.slice('device:'.length);
11886
if (holdsDeviceOfSameHost(deviceId, heldKeys) && locks.has(key)) {
11987
throw deviceExecutionLockBusy(deviceId);
@@ -164,31 +132,3 @@ export async function withRequestExecutionLockKeys<T>(
164132
signal,
165133
);
166134
}
167-
168-
function retainExecutionLock(
169-
locks: Map<string, Promise<unknown>>,
170-
key: RequestExecutionLockKey,
171-
signal?: AbortSignal,
172-
): RetainedExecutionLock {
173-
let markAcquired: () => void = () => {};
174-
let rejectAcquired: (error: unknown) => void = () => {};
175-
let release: () => void = () => {};
176-
const acquired = new Promise<void>((resolve, reject) => {
177-
markAcquired = resolve;
178-
rejectAcquired = reject;
179-
});
180-
const released = new Promise<void>((resolve) => {
181-
release = resolve;
182-
});
183-
const completion = withKeyedLock(
184-
locks,
185-
key,
186-
async () => {
187-
markAcquired();
188-
await released;
189-
},
190-
signal,
191-
);
192-
void completion.catch((error) => rejectAcquired(error));
193-
return { acquired, completion, release };
194-
}

‎packages/daemon/src/sessions/handlers/__tests__/session-device-claims.test.ts‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,11 @@ import { handleSessionOpenCommands as handleProductionOpenCommand } from '../../
6464
import { hostAppDevice, type DeviceInfo } from '@agent-device/kernel/device';
6565
import { makeAuthoringSession } from '../../../__tests__/support/session-factories.ts';
6666
import { AppError } from '@agent-device/kernel/errors';
67+
import { resolveMacOsAppDeviceOpenTarget } from '@agent-device/platform-apple/app-resolution';
68+
import {
69+
createLocalAppleToolProvider,
70+
withAppleToolProvider,
71+
} from '@agent-device/platform-apple/tool-provider';
6772
import {
6873
bindProviderLifecycleRuntime,
6974
bindLifecycleRuntime,
@@ -671,11 +676,24 @@ test('closing another app from an app device session is refused before teardown,
671676
});
672677
mockDispatch.mockResolvedValue(undefined);
673678
// The platform resolves the target as open does and refuses another app of the Mac.
674-
resolveOpenTargetFixture.mockImplementationOnce(async () => {
675-
throw new AppError('INVALID_ARGS', 'This session drives com.apple.TextEdit.', {
676-
reason: 'app-device-scope',
677-
});
679+
// The production platform refusal, over a stubbed list of installed apps.
680+
const provider = createLocalAppleToolProvider({
681+
runCommand: async () => ({ exitCode: 0, stdout: '', stderr: '' }),
678682
});
683+
const macosHost = {
684+
...provider.macosHost!,
685+
listApps: async () => [
686+
{ bundleId: 'com.apple.TextEdit', name: 'TextEdit' },
687+
{ bundleId: 'com.apple.calculator', name: 'Calculator' },
688+
],
689+
};
690+
resolveOpenTargetFixture.mockImplementationOnce(
691+
async (device, _directResolve, input) =>
692+
await withAppleToolProvider(
693+
{ ...provider, macosHost },
694+
async () => await resolveMacOsAppDeviceOpenTarget(device, input.target),
695+
),
696+
);
679697

680698
const outcome = await handleCloseCommand({
681699
host: createTestHostEnvironment(),

0 commit comments

Comments
 (0)