Skip to content

Commit da4026f

Browse files
thymikeeclaude
andcommitted
fix(daemon): never wait for a second lock on the same Mac
App devices made two requests on one Mac concurrent where they used to share the Mac's execution lock. Two replays on two apps that each close their app and open the other's, or a replay that leaves its app for the whole Mac while a fresh open holds the Mac, could then each wait for the lock the other held. A request that holds a lock on a Mac or one of its apps now takes another lock on that Mac mid-request only while it is free, and is otherwise refused with DEVICE_IN_USE (reason DEVICE_EXECUTION_LOCK_BUSY). Locks on other devices are still waited for. This replaces the narrower host-after-app-device-lock rule. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent e43f204 commit da4026f

5 files changed

Lines changed: 127 additions & 31 deletions

File tree

‎docs/adr/0035-macos-app-devices.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,12 @@ Accepted (2026-10-21). Applies to the native macOS app backend (ADR 0031) only.
1818
A request that opens an app device takes its host's execution lock first, in its lock plan, so an
1919
`open --wait` looks at the Mac's sessions under a lock a whole-Mac open also takes. The first
2020
opens on one Mac run their session check and publication one at a time in a daemon. Commands of
21-
an open app session take only the app device's lock. A request that already holds an app device's
22-
lock is refused its host's lock mid-request (`host-after-app-device-lock`) rather than wait out
23-
of order; for example, a replay that closes its app session and then opens `--surface desktop`.
21+
an open app session take only the app device's lock. A request that already holds a lock on a Mac
22+
or one of its apps takes another lock on that Mac mid-request only while it is free, and is
23+
otherwise refused with `DEVICE_IN_USE` (`DEVICE_EXECUTION_LOCK_BUSY`) instead of waiting.
24+
Waiting could cross a request that does the same in the other order: replays on two apps that
25+
each close their app and open the other, or a replay that leaves its app for the whole Mac while
26+
a fresh open holds the Mac. With the whole Mac as one device, such requests shared one lock.
2427
4. One rule relates an app device to its host: the Mac and each of its app devices overlap, and two
2528
app devices do not (`devicesOverlap`). The session store finds a session on an overlapping device,
2629
and a claim selector (`device status --udid`) matches overlapping claims.

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

Lines changed: 84 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { expect, test } from 'vitest';
22
import { createRequestExecutionLocks } from '../request-execution-locks.ts';
3+
import type { RequestExecutionLockKey } from '../request-binding.ts';
34

45
test('a dynamically retained device lock lasts until the owning request completes', async () => {
56
const locks = new Map<string, Promise<unknown>>();
@@ -54,14 +55,57 @@ test('retaining an initial device lock is reentrant within the request', async (
5455
).resolves.toBe('done');
5556
});
5657

57-
test('a request holding an app device lock is refused its host lock instead of deadlocking', async () => {
58+
/**
59+
* Runs two requests that each hold their initial locks, lets both start, then has each retain one
60+
* more device lock. Returns what each retention settled to: `retained` or the refusal.
61+
*/
62+
async function crossRetentions(
63+
first: { keys: RequestExecutionLockKey[]; retain: string },
64+
second: { keys: RequestExecutionLockKey[]; retain: string },
65+
): Promise<unknown[]> {
66+
const locks = new Map<string, Promise<unknown>>();
67+
let started = 0;
68+
let markBothStarted: () => void = () => {};
69+
const bothStarted = new Promise<void>((resolve) => {
70+
markBothStarted = resolve;
71+
});
72+
const run = async (request: { keys: RequestExecutionLockKey[]; retain: string }) => {
73+
const requestLocks = createRequestExecutionLocks({ locks, initialKeys: request.keys });
74+
return await requestLocks.run(async () => {
75+
started += 1;
76+
if (started === 2) markBothStarted();
77+
await bothStarted;
78+
return await requestLocks.retainDevice(request.retain).then(
79+
() => 'retained',
80+
(error: unknown) => error,
81+
);
82+
});
83+
};
84+
return await Promise.all([run(first), run(second)]);
85+
}
86+
87+
const BUSY = {
88+
code: 'DEVICE_IN_USE',
89+
details: { reason: 'DEVICE_EXECUTION_LOCK_BUSY' },
90+
};
91+
92+
test('replays on two apps of one Mac that each open the other app are refused, not deadlocked', async () => {
93+
// Each replay runs in its existing app session, closes its app, and opens the other one.
94+
const outcomes = await crossRetentions(
95+
{ keys: ['session:one', 'device:mac:app:com.example.one'], retain: 'mac:app:com.example.two' },
96+
{ keys: ['session:two', 'device:mac:app:com.example.two'], retain: 'mac:app:com.example.one' },
97+
);
98+
expect(outcomes).toHaveLength(2);
99+
for (const outcome of outcomes) expect(outcome).toMatchObject(BUSY);
100+
});
101+
102+
test('a replay that leaves its app for the whole Mac is refused while another request holds the Mac', async () => {
58103
const locks = new Map<string, Promise<unknown>>();
59-
// A replay in an existing app session holds that app device until it finishes.
60104
const replayLocks = createRequestExecutionLocks({
61105
locks,
62106
initialKeys: ['session:replay', 'device:mac:app:com.example.one'],
63107
});
64-
// A fresh open of the same app in another session takes the host first, then waits for the app.
108+
// A fresh open of the same app in another session holds the Mac and waits for the app.
65109
const freshOpenLocks = createRequestExecutionLocks({
66110
locks,
67111
initialKeys: ['session:fresh', 'device:mac', 'device:mac:app:com.example.one'],
@@ -79,14 +123,10 @@ test('a request holding an app device lock is refused its host lock instead of d
79123
const replayRun = replayLocks.run(async () => {
80124
replayHolding();
81125
await freshWaiting;
82-
// The replay closes its app session and opens the whole Mac.
83-
const refused = await replayLocks.retainDevice('mac').then(
84-
() => undefined,
126+
return await replayLocks.retainDevice('mac').then(
127+
() => 'retained',
85128
(error: unknown) => error,
86129
);
87-
// Another app device of the Mac keeps the host-then-app order and is retained as before.
88-
await replayLocks.retainDevice('mac:app:com.example.two');
89-
return refused;
90130
});
91131
await holding;
92132
const freshRun = freshOpenLocks.run(async () => {
@@ -96,10 +136,41 @@ test('a request holding an app device lock is refused its host lock instead of d
96136
expect(freshEntered).toBe(false);
97137
continueReplay();
98138

99-
expect(await replayRun).toMatchObject({
100-
code: 'UNSUPPORTED_OPERATION',
101-
details: { reason: 'host-after-app-device-lock', deviceId: 'mac' },
102-
});
139+
expect(await replayRun).toMatchObject({ ...BUSY, details: { ...BUSY.details, deviceId: 'mac' } });
103140
await freshRun;
104141
expect(freshEntered).toBe(true);
105142
});
143+
144+
test('a second lock on the same Mac is taken while it is free, and other devices still wait', async () => {
145+
const locks = new Map<string, Promise<unknown>>();
146+
const replayLocks = createRequestExecutionLocks({
147+
locks,
148+
initialKeys: ['session:replay', 'device:mac:app:com.example.one'],
149+
});
150+
await expect(
151+
replayLocks.run(async () => {
152+
await replayLocks.retainDevice('mac:app:com.example.two');
153+
await replayLocks.retainDevice('mac');
154+
return 'done';
155+
}),
156+
).resolves.toBe('done');
157+
158+
// A lock on another device is still waited for, as before.
159+
const holder = createRequestExecutionLocks({ locks, initialKeys: ['device:SIM-002'] });
160+
let releaseHolder: () => void = () => {};
161+
const holderRun = holder.run(
162+
async () =>
163+
await new Promise<void>((resolve) => {
164+
releaseHolder = resolve;
165+
}),
166+
);
167+
const simLocks = createRequestExecutionLocks({ locks, initialKeys: ['device:SIM-001'] });
168+
const simRun = simLocks.run(async () => {
169+
await simLocks.retainDevice('SIM-002');
170+
return 'waited';
171+
});
172+
await new Promise((resolve) => setTimeout(resolve, 10));
173+
releaseHolder();
174+
await holderRun;
175+
await expect(simRun).resolves.toBe('waited');
176+
});

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

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { withKeyedLock } from '@agent-device/kernel/keyed-lock';
2-
import { hostDeviceIdPrefix } from '@agent-device/kernel/device';
2+
import { hostDeviceIdOf } from '@agent-device/kernel/device';
33
import { AppError } from '@agent-device/kernel/errors';
44
import type { RequestExecutionLockKey } from './request-binding.ts';
55

@@ -57,10 +57,13 @@ export function createRequestExecutionLocks(params: {
5757
}
5858
const key = `device:${deviceId}` as const;
5959
if (initialKeySet.has(key)) return;
60-
assertNoHeldAppDeviceOf(deviceId, [...initialKeySet, ...retainedLocks.keys()]);
6160

6261
let retained = retainedLocks.get(key);
6362
if (!retained) {
63+
const heldKeys = [...initialKeySet, ...retainedLocks.keys()];
64+
if (holdsDeviceOfSameHost(deviceId, heldKeys) && locks.has(key)) {
65+
throw deviceExecutionLockBusy(deviceId);
66+
}
6467
retained = retainExecutionLock(locks, key);
6568
retainedLocks.set(key, retained);
6669
}
@@ -70,23 +73,30 @@ export function createRequestExecutionLocks(params: {
7073
}
7174

7275
/**
73-
* Every request takes a host's lock before the locks of its app devices (ADR 0035). A request that
74-
* already holds an app device's lock would take its host's out of that order and could wait on a
75-
* request that holds the host and waits for that app, so it is refused instead of waiting.
76+
* Whether the request already holds a lock on `deviceId`'s host or one of its app devices
77+
* (ADR 0035). Waiting for a second lock on the same host while holding one could cross another
78+
* request that does the same in the other order: replays on two apps of one Mac that each close
79+
* their app and open the other's, or a replay that leaves its app for the whole Mac while a fresh
80+
* open holds the Mac and waits for that app. Such a lock is taken only while it is free.
7681
*/
77-
function assertNoHeldAppDeviceOf(
82+
function holdsDeviceOfSameHost(
7883
deviceId: string,
7984
heldKeys: readonly RequestExecutionLockKey[],
80-
): void {
81-
const appDeviceKeyPrefix = `device:${hostDeviceIdPrefix(deviceId)}`;
82-
if (!heldKeys.some((key) => key.startsWith(appDeviceKeyPrefix))) return;
83-
throw new AppError(
84-
'UNSUPPORTED_OPERATION',
85-
'This request already holds an app of this device, so it cannot also take the whole device.',
85+
): boolean {
86+
const host = hostDeviceIdOf(deviceId);
87+
return heldKeys.some(
88+
(key) => key.startsWith('device:') && hostDeviceIdOf(key.slice('device:'.length)) === host,
89+
);
90+
}
91+
92+
function deviceExecutionLockBusy(deviceId: string): AppError {
93+
return new AppError(
94+
'DEVICE_IN_USE',
95+
`Another request is using ${deviceId}, and this request already holds another device of the same host.`,
8696
{
87-
reason: 'host-after-app-device-lock',
97+
reason: 'DEVICE_EXECUTION_LOCK_BUSY',
8898
deviceId,
89-
hint: 'Run the whole-device step (for example open --surface desktop) as a separate request.',
99+
hint: 'Run this step as a separate request, or retry once the other request finishes.',
90100
},
91101
);
92102
}

‎packages/kernel/src/device.test.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import assert from 'node:assert/strict';
22
import { test } from 'vitest';
3-
import { devicesOverlap, hostAppDevice, type DeviceInfo } from './device.ts';
3+
import { devicesOverlap, hostAppDevice, hostDeviceIdOf, type DeviceInfo } from './device.ts';
44

55
const mac: DeviceInfo = {
66
platform: 'apple',
@@ -21,3 +21,9 @@ test('a host overlaps each of its app devices, and two of its app devices do not
2121
assert.equal(devicesOverlap(one, two), false);
2222
assert.equal(devicesOverlap('host-mac-2', one), false);
2323
});
24+
25+
test('hostDeviceIdOf names the host of an app device and any other device itself', () => {
26+
assert.equal(hostDeviceIdOf(hostAppDevice(mac, 'com.example.one').id), mac.id);
27+
assert.equal(hostDeviceIdOf(mac.id), mac.id);
28+
assert.equal(hostDeviceIdOf('emulator-5554'), 'emulator-5554');
29+
});

‎packages/kernel/src/device.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,12 @@ export function hostAppDeviceId(hostDeviceId: string, bundleId: string): string
7979
return `${hostDeviceIdPrefix(hostDeviceId)}${bundleId.toLowerCase()}`;
8080
}
8181

82+
/** The host of an app device id, or the id itself for any other device. */
83+
export function hostDeviceIdOf(deviceId: string): string {
84+
const infix = deviceId.indexOf(HOST_APP_DEVICE_ID_INFIX);
85+
return infix < 0 ? deviceId : deviceId.slice(0, infix);
86+
}
87+
8288
/** The id prefix every app device of `hostDeviceId` shares. */
8389
export function hostDeviceIdPrefix(hostDeviceId: string): string {
8490
return `${hostDeviceId}${HOST_APP_DEVICE_ID_INFIX}`;

0 commit comments

Comments
 (0)