Skip to content

Commit 00e4952

Browse files
committed
fix(daemon): hold an existing claim only for its own claim kind
An acquirer now holds an existing claim only when the record states the very kind of claim the acquirer would write itself — the same transientCommand for transient admission — under the same session, workspace, and daemon identity. An unstated record matches no acquirer, so acquisition never adopts a migrated v1/v2 record, and an open session named after a command label never inherits an in-flight command's owner token. claimHeldDevice passes the acquirer's typed kind and command to resolveExistingClaim, the boundary every acquire route goes through, which retires the label guard in acquireTransientDeviceClaim. Ref: #3714 (comment)
1 parent e2fe4ba commit 00e4952

3 files changed

Lines changed: 176 additions & 17 deletions

File tree

‎packages/daemon-contracts/src/device-claim-settlement.ts‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { resolveDeviceClaimPath } from './device-claim-paths.ts';
2121
import {
2222
ownershipFromClaim,
2323
type DeviceClaim,
24+
type DeviceClaimOwnerKind,
2425
type DeviceClaimSessionOwnership,
2526
} from './device-claim-record.ts';
2627
import { writeDeviceClaim } from './device-claim-store.ts';
@@ -43,6 +44,13 @@ export type DeviceClaimReconciler = (
4344
claim: DeviceClaim,
4445
) => Promise<DeviceClaimReconciliationResult>;
4546

47+
/**
48+
* The acquirer whose ownership `resolveExistingClaim` judges: the kind of claim it could have
49+
* written itself — never `unstated`, which no acquirer can be — plus the command a transient
50+
* acquirer scopes to.
51+
*/
52+
export type DeviceClaimAcquirerKind = Exclude<DeviceClaimOwnerKind, 'unstated'>;
53+
4654
/**
4755
* Settles the claim file an acquisition found, and decides whether this caller may write its own.
4856
* The recorded owner's own state answers first — a dead, unreachable, or superseded owner is
@@ -57,6 +65,10 @@ export async function resolveExistingClaim(params: {
5765
session: string;
5866
workspace: string;
5967
stateDir: string;
68+
/** The kind of claim this acquirer would write, so `isCurrentClaimOwner` can compare kinds. */
69+
claimOwnerKind: DeviceClaimAcquirerKind;
70+
/** The command a `transient-command` acquirer scopes to; absent exactly when the kind is. */
71+
transientCommand?: string;
6072
reconcileOrphanedDeviceClaim: DeviceClaimReconciler;
6173
observeDeviceBoot?: DeviceBootObservationService;
6274
}): Promise<ExistingClaimResolution> {
@@ -187,11 +199,31 @@ function isAbandonedClaimOfThisDaemon(
187199
return isAbandonedDeviceClaim(claim) && isClaimOwnedByThisDaemon(claim, stateDir, owner);
188200
}
189201

202+
/**
203+
* An acquirer holds an existing claim only when the record states the very kind of claim this
204+
* acquirer would write itself — the same `transientCommand` for transient admission — under the
205+
* same session, workspace, and daemon. `unstated` matches no acquirer, so a migrated record can
206+
* hold and fence the device but can never be adopted at acquisition, however exactly its session
207+
* label or copyable `--session` address lines up (#3345).
208+
*/
190209
function isCurrentClaimOwner(
191210
claim: DeviceClaim,
192-
params: { session: string; workspace: string; stateDir: string },
211+
params: {
212+
session: string;
213+
workspace: string;
214+
stateDir: string;
215+
claimOwnerKind: DeviceClaimAcquirerKind;
216+
transientCommand?: string;
217+
},
193218
owner: ReturnType<typeof readCurrentOwnerIdentity>,
194219
): boolean {
220+
if (claim.claimOwnerKind !== params.claimOwnerKind) return false;
221+
if (
222+
params.claimOwnerKind === 'transient-command' &&
223+
claim.transientCommand !== params.transientCommand
224+
) {
225+
return false;
226+
}
195227
return (
196228
claim.session === params.session &&
197229
claim.workspace === params.workspace &&

‎packages/daemon-contracts/src/device-claims.ts‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import {
3838
isClaimOwnedByThisDaemon,
3939
resolveExistingClaim,
4040
settleVerifiedOrphanedClaim,
41+
type DeviceClaimAcquirerKind,
4142
type DeviceClaimReconciler,
4243
} from './device-claim-settlement.ts';
4344
import { withDeviceClaimLock, writeDeviceClaim } from './device-claim-store.ts';
@@ -157,16 +158,13 @@ export async function acquireTransientDeviceClaim(params: {
157158
// Only a record that states its kind can take part in a kind decision. A migrated record
158159
// states none, and `isClaimOwnedByThisDaemon` matches pid plus start time — which two
159160
// processes can share once a start time is unreadable — so coverage has to refuse rather
160-
// than assume an old record was not some other owner's command claim (#3345).
161+
// than assume an old record was not some other owner's command claim (#3345). A live claim
162+
// of any other kind — another session's or a command's, including one labeled exactly like
163+
// this command — refuses here, because renewing it would hand this request a token it
164+
// never took.
161165
if (claimKind !== 'open-session') {
162166
return { status: 'conflict', conflict: existing };
163167
}
164-
// A session literally named this command's label is not this command's claim either:
165-
// below, `claimHeldDevice` matches holders by the session string it is handed, and
166-
// renewing that claim would hand this request the open session's release token.
167-
if (existing.claim.session === transientDeviceClaimSession(params.command)) {
168-
return { status: 'conflict', conflict: existing };
169-
}
170168
}
171169
return await claimHeldDevice({
172170
device: params.device,
@@ -196,9 +194,12 @@ async function claimHeldDevice(params: {
196194
}): Promise<DeviceClaimAcquireResult> {
197195
const { deviceKey, identity } = params;
198196
const owner = readCurrentOwnerIdentity();
197+
const claimOwnerKind: DeviceClaimAcquirerKind =
198+
params.transientCommand === undefined ? 'open-session' : 'transient-command';
199199
const existing = await resolveExistingClaim({
200200
...params,
201201
owner,
202+
claimOwnerKind,
202203
});
203204
if (existing.status === 'conflict') return existing;
204205
if (existing.status === 'held') return { status: 'acquired', ownership: existing.ownership };
@@ -218,7 +219,7 @@ async function claimHeldDevice(params: {
218219
ownerToken: crypto.randomUUID(),
219220
createdAtMs: now,
220221
updatedAtMs: now,
221-
claimOwnerKind: params.transientCommand === undefined ? 'open-session' : 'transient-command',
222+
claimOwnerKind,
222223
...(params.transientCommand === undefined ? {} : { transientCommand: params.transientCommand }),
223224
};
224225
writeDeviceClaim(claim);

‎packages/daemon/src/resources/device/__tests__/device-claim-settlement.test.ts‎

Lines changed: 134 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@ import { afterEach, test, vi } from 'vitest';
66
import * as hostProcess from '@agent-device/host-kit/process';
77
import {
88
acquireDeviceClaim as acquireProductionDeviceClaim,
9+
acquireTransientDeviceClaim,
910
canonicalLocalDeviceKey,
1011
inspectDeviceClaims,
12+
renewDeviceClaim,
1113
} from '@agent-device/daemon-contracts/device-claims';
1214
import type { DeviceBootObservationService } from '@agent-device/contracts/device-boot';
1315
import type { DeviceInfo } from '@agent-device/kernel/device';
@@ -94,10 +96,134 @@ test('preserves and reports a live foreign claim without overwriting it', async
9496
assert.equal(inspectDeviceClaims({ serial: device.id })[0]?.claim?.session, 'first');
9597
});
9698

99+
// The maintainer's trace on #3714: `install` holds a transient claim under the label
100+
// `transient:install`; an `open` from the same workspace addressed at that label must not be
101+
// handed the command's ownership token. Any session string can be typed into `--session`; only
102+
// the stored kind says who holds the claim, so an open-session acquirer never holds a
103+
// transient-command record and vice versa.
104+
test('an open session addressed at a command label never adopts the in-flight command claim', async () => {
105+
const root = useClaimsRoot();
106+
const holder = await acquireTransientDeviceClaim({
107+
device,
108+
command: 'install',
109+
coveredBySession: 'open-a',
110+
coveredClaimIsOwnedByRequest: () => false,
111+
workspace: '/worktrees/first',
112+
stateDir: root,
113+
reconcileOrphanedDeviceClaim: async () => ({ status: 'retained', reason: 'test-no-recovery' }),
114+
});
115+
assert.equal(holder.status, 'acquired');
116+
if (holder.status !== 'acquired') return;
117+
118+
const open = await acquireDeviceClaim({
119+
device,
120+
session: 'transient:install',
121+
workspace: '/worktrees/first',
122+
stateDir: root,
123+
});
124+
125+
assert.equal(open.status, 'conflict');
126+
if (open.status !== 'conflict') return;
127+
assert.equal(open.conflict.classification, 'live');
128+
// The refusal wrote nothing: the command still holds the device with its own token.
129+
assert.equal(storedClaim().ownerToken, holder.ownership.ownerToken);
130+
});
131+
132+
// The mirror direction, pinned at the settlement boundary every acquire route goes through. Two
133+
// live requests can never share one claim: a second `reinstall` or `install` reaching the running
134+
// `install`'s claim — same workspace, label as session — is refused, and only the request that
135+
// took the claim re-enters it, through the token the admission layer already pins.
136+
test('a second request never holds an in-flight command claim, under its own label or another’s', async () => {
137+
const root = useClaimsRoot();
138+
const holder = await acquireTransientDeviceClaim({
139+
device,
140+
command: 'install',
141+
coveredBySession: 'open-a',
142+
coveredClaimIsOwnedByRequest: () => false,
143+
workspace: '/worktrees/first',
144+
stateDir: root,
145+
reconcileOrphanedDeviceClaim: async () => ({ status: 'retained', reason: 'test-no-recovery' }),
146+
});
147+
assert.equal(holder.status, 'acquired');
148+
if (holder.status !== 'acquired') return;
149+
150+
const intruder = await acquireTransientDeviceClaim({
151+
device,
152+
command: 'reinstall',
153+
coveredBySession: 'transient:install',
154+
coveredClaimIsOwnedByRequest: () => true,
155+
workspace: '/worktrees/first',
156+
stateDir: root,
157+
reconcileOrphanedDeviceClaim: async () => ({ status: 'retained', reason: 'test-no-recovery' }),
158+
});
159+
assert.equal(intruder.status, 'conflict');
160+
assert.equal(storedClaim().ownerToken, holder.ownership.ownerToken);
161+
162+
const sameCommand = await acquireTransientDeviceClaim({
163+
device,
164+
command: 'install',
165+
coveredBySession: 'some-other-session',
166+
coveredClaimIsOwnedByRequest: () => false,
167+
workspace: '/worktrees/first',
168+
stateDir: root,
169+
reconcileOrphanedDeviceClaim: async () => ({ status: 'retained', reason: 'test-no-recovery' }),
170+
});
171+
// A different request of the SAME command still refuses: only the request holding the claim's
172+
// release token re-enters it (the admission layer pins that), so a live command claim is never
173+
// disposed from under its holder by a second same-named request.
174+
assert.equal(sameCommand.status, 'conflict');
175+
assert.equal(storedClaim().ownerToken, holder.ownership.ownerToken);
176+
});
177+
178+
// A migrated record states no kind, so no acquirer's kind can equal it: even the same principal
179+
// in the same workspace cannot hold it at acquisition, and a record whose start time is unreadable
180+
// (`null === null` against this process) is the case that most needs the refusal. Acquisition
181+
// never renews it either — the token the record itself names is the only renewal route left.
182+
test('a migrated record states no kind, so acquisition never holds it', async () => {
183+
for (const startTimeUnavailable of [false, true]) {
184+
const root = useClaimsRoot();
185+
const identity = startTimeUnavailable
186+
? { pid: process.pid, startTime: null }
187+
: hostProcess.readCurrentOwnerIdentity();
188+
const owner = vi.spyOn(hostProcess, 'readCurrentOwnerIdentity').mockReturnValue(identity);
189+
try {
190+
fs.writeFileSync(
191+
claimPath(root),
192+
JSON.stringify({
193+
schemaVersion: 2,
194+
deviceKey: canonicalLocalDeviceKey(device),
195+
device: { family: 'android', id: device.id, name: device.name, kind: device.kind },
196+
session: 'legacy-owner',
197+
workspace: '/worktrees/legacy',
198+
stateDir: root,
199+
ownerPid: identity.pid,
200+
ownerStartTime: identity.startTime,
201+
ownerToken: 'legacy-token',
202+
createdAtMs: 1,
203+
updatedAtMs: 1,
204+
}),
205+
);
206+
207+
const held = await acquireDeviceClaim({
208+
device,
209+
session: 'legacy-owner',
210+
workspace: '/worktrees/legacy',
211+
stateDir: root,
212+
});
213+
214+
assert.equal(held.status, 'conflict');
215+
assert.equal(storedClaim().ownerToken, 'legacy-token');
216+
assert.equal(storedClaim().updatedAtMs, 1);
217+
} finally {
218+
owner.mockRestore();
219+
}
220+
}
221+
});
222+
97223
// Renewal, abandon, and clear write a decoded claim back. A migrated record must therefore carry
98224
// the current schema version: a legacy version on the migrated device shape reads back as
99-
// inconsistent and locks the owner out of its own next command.
100-
test('a renewal of a migrated record writes back the shape the reader expects', async () => {
225+
// inconsistent and locks the device out of any settlement path that reads it.
226+
test('a renewal through a migrated record’s own token writes back the shape the reader expects', async () => {
101227
const root = useClaimsRoot();
102228
fs.writeFileSync(
103229
claimPath(root),
@@ -116,13 +242,13 @@ test('a renewal of a migrated record writes back the shape the reader expects',
116242
}),
117243
);
118244

119-
const held = await acquireDeviceClaim({
120-
device,
121-
session: 'legacy-owner',
122-
workspace: '/worktrees/legacy',
123-
stateDir: root,
245+
const renewal = await renewDeviceClaim({
246+
deviceKey: canonicalLocalDeviceKey(device),
247+
ownerToken: 'legacy-token',
248+
ownerPid: process.pid,
249+
ownerStartTime: 'test-process-start-time',
124250
});
125-
assert.equal(held.status, 'acquired');
251+
assert.equal(renewal.status, 'renewed');
126252

127253
const persisted = JSON.parse(fs.readFileSync(claimPath(root), 'utf8')) as Record<string, unknown>;
128254
assert.equal(persisted.schemaVersion, 3);

0 commit comments

Comments
 (0)