Skip to content

Commit 7b3291e

Browse files
committed
fix: classify daemon stop claim results from the clear outcome
`clearDeviceClaim` deliberately resolves without deleting when the on-disk claim is no longer the one it acquired, so the shutdown ledger's "the call resolved" test reported a successor's claim as released — a device the daemon never freed, counted as freed. `clearDeviceClaim` now returns a typed outcome (`deleted` | `absent` | `ownership-changed`) instead of nothing, and the ledger classifies from it: released only when absence is confirmed, and a new `superseded` bucket for a claim another owner had already taken over. Superseded is neither released (this daemon freed nothing) nor orphaned (no claim of ours remains to reconcile), so folding it into either would break that list's meaning; it also raises a warning so a device now owned elsewhere cannot pass silently.
1 parent 0ea71a5 commit 7b3291e

9 files changed

Lines changed: 162 additions & 49 deletions

File tree

‎src/cli/commands/__tests__/daemon.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ const GRACEFUL_RESULT: DaemonStopResult = {
3535
cleanupConfidence: 'known',
3636
claimsReleased: [],
3737
claimsOrphaned: [],
38+
claimsSuperseded: [],
3839
providerReleases: { status: 'completed', released: [], pending: [] },
3940
warnings: [],
4041
};
@@ -79,7 +80,7 @@ test('merges a graceful shutdown report and cleans runner leases with the start-
7980
released: [{ leaseId: 'lease-1', provider: 'limrun' }],
8081
pending: [],
8182
},
82-
claims: { released: [claim], orphaned: [] },
83+
claims: { released: [claim], orphaned: [], superseded: [] },
8384
});
8485

8586
try {
@@ -105,6 +106,7 @@ test('merges a graceful shutdown report and cleans runner leases with the start-
105106
// #1799: a graceful stop reports the claims it actually released.
106107
claimsReleased: [claim],
107108
claimsOrphaned: [],
109+
claimsSuperseded: [],
108110
}),
109111
expect.any(Function),
110112
);

‎src/cli/commands/daemon.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ function mergeShutdownReport(
4646
providerReleases: { status: 'completed', ...report.providerReleases },
4747
claimsReleased: report.claims.released,
4848
claimsOrphaned: report.claims.orphaned,
49+
claimsSuperseded: report.claims.superseded,
50+
warnings: [...stopped.warnings, ...supersededClaimWarnings(report.claims.superseded)],
4951
}
5052
: stopped;
5153
}
@@ -60,6 +62,16 @@ function mergeShutdownReport(
6062
};
6163
}
6264

65+
/** A superseded claim is not a failure to report as one, but the operator's
66+
* device is now owned elsewhere, so it must not pass silently. */
67+
function supersededClaimWarnings(superseded: DaemonStopResult['claimsSuperseded']): string[] {
68+
if (superseded.length === 0) return [];
69+
const devices = superseded.map((claim) => claim.deviceId).join(', ');
70+
return [
71+
`Another owner had already claimed ${devices} before this daemon released it, so those devices are now owned elsewhere.`,
72+
];
73+
}
74+
6375
function renderDaemonStop(
6476
result: Pick<DaemonStopResult, 'stopped' | 'mode' | 'warnings'> & {
6577
clean: boolean;

‎src/daemon/__tests__/daemon-shutdown-report.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,15 @@ test('round-trips provider release and device claim records without lease creden
2727
try {
2828
writeDaemonShutdownReport(stateDir, {
2929
providerReleases: { released: [lease], pending: [lease] },
30-
claims: { released: [claim], orphaned: [] },
30+
claims: { released: [claim], orphaned: [], superseded: [claim] },
3131
});
3232

3333
expect(readDaemonShutdownReport(stateDir)).toEqual({
3434
providerReleases: {
3535
released: [{ leaseId: lease.leaseId, provider: 'limrun' }],
3636
pending: [{ leaseId: lease.leaseId, provider: 'limrun' }],
3737
},
38-
claims: { released: [claim], orphaned: [] },
38+
claims: { released: [claim], orphaned: [], superseded: [claim] },
3939
});
4040
} finally {
4141
fs.rmSync(stateDir, { recursive: true, force: true });
@@ -54,7 +54,7 @@ test('a report written before claim reporting still reads its provider releases'
5454

5555
expect(readDaemonShutdownReport(stateDir)).toEqual({
5656
providerReleases: { released: [], pending: [] },
57-
claims: { released: [], orphaned: [] },
57+
claims: { released: [], orphaned: [], superseded: [] },
5858
});
5959
} finally {
6060
fs.rmSync(stateDir, { recursive: true, force: true });

‎src/daemon/__tests__/device-claims.test.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -254,10 +254,28 @@ test('clears only the exact owner token and identity, never a successor claim',
254254
claimPath(root),
255255
JSON.stringify({ ...stored, ownerToken: 'successor-token', session: 'second' }),
256256
);
257-
await clearDeviceClaim(acquired.ownership);
257+
// Resolving is not releasing: the outcome is what a caller reporting
258+
// ownership must read, since the successor's claim is deliberately kept.
259+
assert.equal(await clearDeviceClaim(acquired.ownership), 'ownership-changed');
258260
assert.equal(inspectDeviceClaims({ serial: device.id })[0]?.claim?.session, 'second');
259261
});
260262

263+
test('reports the exact outcome of clearing an owned, missing, and unowned claim', async () => {
264+
const root = useClaimsRoot();
265+
const acquired = await acquireDeviceClaim({
266+
device,
267+
session: 'owner',
268+
workspace: '/worktrees/owner',
269+
stateDir: root,
270+
});
271+
assert.equal(acquired.status, 'acquired');
272+
if (acquired.status !== 'acquired') return;
273+
274+
assert.equal(await clearDeviceClaim(acquired.ownership), 'deleted');
275+
assert.equal(await clearDeviceClaim(acquired.ownership), 'absent');
276+
assert.equal(await clearDeviceClaim(undefined), 'absent');
277+
});
278+
261279
test('keeps corrupt records visible and classifies dead owners without reclaiming either', () => {
262280
const root = useClaimsRoot();
263281
fs.writeFileSync(path.join(root, 'corrupt.json'), '{bad json');

‎src/daemon/daemon-shutdown-report.ts‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,11 @@ export type ProviderReleaseRecord = {
1111

1212
/**
1313
* #1320: what happened to one session's device claim during graceful teardown.
14-
* `released` means the claim was cleared after the session reached a safe
14+
* `released` means the claim was confirmed gone after the session reached a safe
1515
* terminal state; `orphaned` means teardown left it in place, so the exiting
16-
* daemon's dead owner identity is what later proves it reclaimable.
16+
* daemon's dead owner identity is what later proves it reclaimable; `superseded`
17+
* means another owner had already replaced it, so this daemon released nothing
18+
* and left nothing to reconcile.
1719
*/
1820
export type DeviceClaimRecord = {
1921
deviceKey: string;
@@ -30,14 +32,19 @@ export type DaemonShutdownReport = {
3032
claims: {
3133
released: DeviceClaimRecord[];
3234
orphaned: DeviceClaimRecord[];
35+
superseded: DeviceClaimRecord[];
3336
};
3437
};
3538

3639
export function writeDaemonShutdownReport(
3740
stateDir: string,
3841
outcome: {
3942
providerReleases: { released: readonly DeviceLease[]; pending: readonly DeviceLease[] };
40-
claims: { released: readonly DeviceClaimRecord[]; orphaned: readonly DeviceClaimRecord[] };
43+
claims: {
44+
released: readonly DeviceClaimRecord[];
45+
orphaned: readonly DeviceClaimRecord[];
46+
superseded: readonly DeviceClaimRecord[];
47+
};
4148
},
4249
): void {
4350
const report: DaemonShutdownReport = {
@@ -48,6 +55,7 @@ export function writeDaemonShutdownReport(
4855
claims: {
4956
released: [...outcome.claims.released],
5057
orphaned: [...outcome.claims.orphaned],
58+
superseded: [...outcome.claims.superseded],
5159
},
5260
};
5361
const filePath = shutdownReportPath(stateDir);
@@ -109,11 +117,12 @@ function isProviderReleaseReport(
109117

110118
function readClaimSection(value: { claims?: unknown }): DaemonShutdownReport['claims'] {
111119
const claims = value.claims;
112-
if (!claims || typeof claims !== 'object') return { released: [], orphaned: [] };
113-
const records = claims as { released?: unknown; orphaned?: unknown };
120+
if (!claims || typeof claims !== 'object') return { released: [], orphaned: [], superseded: [] };
121+
const records = claims as { released?: unknown; orphaned?: unknown; superseded?: unknown };
114122
return {
115123
released: readClaimRecords(records.released),
116124
orphaned: readClaimRecords(records.orphaned),
125+
superseded: readClaimRecords(records.superseded),
117126
};
118127
}
119128

‎src/daemon/daemon-stop.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ export type DaemonStopResult = {
2626
*/
2727
claimsReleased: DeviceClaimRecord[];
2828
claimsOrphaned: DeviceClaimRecord[];
29+
/** Claims another owner had already taken over; this daemon released nothing. */
30+
claimsSuperseded: DeviceClaimRecord[];
2931
providerReleases: {
3032
status: 'completed' | 'unknown';
3133
released: ProviderReleaseRecord[];
@@ -71,6 +73,7 @@ export async function stopDaemon(params: {
7173
cleanupConfidence: 'known',
7274
claimsReleased: [],
7375
claimsOrphaned: [],
76+
claimsSuperseded: [],
7477
providerReleases: { status: 'completed', released: [], pending: [] },
7578
warnings: [],
7679
};
@@ -94,6 +97,7 @@ export async function stopDaemon(params: {
9497
cleanupConfidence: 'unknown',
9598
claimsReleased: [],
9699
claimsOrphaned: [],
100+
claimsSuperseded: [],
97101
providerReleases: { status: 'unknown', released: [], pending: null },
98102
warnings: [
99103
'The daemon was force-killed before provider lease state could be finalized. Provider allocations may remain active.',
@@ -153,6 +157,7 @@ function notRunningResult(): DaemonStopResult {
153157
cleanupConfidence: 'known',
154158
claimsReleased: [],
155159
claimsOrphaned: [],
160+
claimsSuperseded: [],
156161
providerReleases: { status: 'completed', released: [], pending: [] },
157162
warnings: [],
158163
};

‎src/daemon/device-claims.ts‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -231,28 +231,44 @@ function isCurrentClaimOwner(
231231
);
232232
}
233233

234+
/**
235+
* What releasing a claim actually did. Resolving is not the same as releasing:
236+
* clearing deliberately leaves a claim it does not own in place, so a caller
237+
* that reports ownership must read this rather than the absence of a throw.
238+
*
239+
* - `deleted` — the claim this ownership acquired was removed.
240+
* - `absent` — no claim remains for the device; nothing to remove.
241+
* - `ownership-changed`— a claim remains, but it is not the one we acquired
242+
* (a successor owner, or a record we cannot attribute).
243+
*/
244+
export type DeviceClaimClearOutcome = 'deleted' | 'absent' | 'ownership-changed';
245+
234246
export async function clearDeviceClaim(
235247
ownership: DeviceClaimSessionOwnership | undefined,
236-
): Promise<void> {
237-
if (!ownership) return;
238-
await withDeviceClaimLock(ownership.deviceKey, async () => {
239-
const inspected = inspectDeviceClaimFile(resolveDeviceClaimPath(ownership.deviceKey));
240-
if (!inspected?.claim) return;
248+
): Promise<DeviceClaimClearOutcome> {
249+
if (!ownership) return 'absent';
250+
return await withDeviceClaimLock(ownership.deviceKey, async () => {
251+
const claimPath = resolveDeviceClaimPath(ownership.deviceKey);
252+
const inspected = inspectDeviceClaimFile(claimPath);
253+
if (!inspected) return 'absent';
241254
const claim = inspected.claim;
242255
if (
256+
!claim ||
243257
claim.ownerToken !== ownership.ownerToken ||
244258
!ownerIdentityMatches(
245259
{ pid: claim.ownerPid, startTime: claim.ownerStartTime },
246260
{ pid: ownership.ownerPid, startTime: ownership.ownerStartTime },
247261
)
248262
) {
249-
return;
263+
return 'ownership-changed';
250264
}
251265
try {
252-
fs.unlinkSync(resolveDeviceClaimPath(ownership.deviceKey));
266+
fs.unlinkSync(claimPath);
253267
} catch (error) {
254268
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
269+
return 'absent';
255270
}
271+
return 'deleted';
256272
});
257273
}
258274

‎src/daemon/server/daemon-shutdown-claims.test.ts‎

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,25 @@ import {
44
isolatedDeviceClaimStores,
55
retainOrphanedDeviceClaims,
66
} from '../../__tests__/test-utils/device-claim-store.ts';
7+
import fs from 'node:fs';
78
import { acquireDeviceClaim } from '../device-claims.ts';
9+
import { resolveDeviceClaimPath } from '../device-claim-paths.ts';
810
import { inspectDeviceClaims } from '../device-claim-inspection.ts';
911
import { createDaemonShutdownClaimLedger } from './daemon-shutdown-claims.ts';
1012
import type { SessionState } from '../types.ts';
1113

1214
const setup = isolatedDeviceClaimStores('agent-device-shutdown-claim-ledger-');
1315

14-
async function claimedSession(name: string): Promise<SessionState> {
16+
function claimRecord(session: SessionState, name: string) {
17+
return {
18+
deviceKey: session.deviceClaim?.deviceKey,
19+
session: name,
20+
platform: 'android',
21+
deviceId: 'emulator-5554',
22+
};
23+
}
24+
25+
async function claimedSession(name: string): Promise<SessionState & { stateDir: string }> {
1526
const { stateDir } = setup();
1627
const acquired = await acquireDeviceClaim({
1728
device: ANDROID_EMULATOR,
@@ -22,6 +33,7 @@ async function claimedSession(name: string): Promise<SessionState> {
2233
});
2334
if (acquired.status !== 'acquired') throw new Error('expected an acquired claim');
2435
return {
36+
stateDir,
2537
name,
2638
device: ANDROID_EMULATOR,
2739
deviceClaim: acquired.ownership,
@@ -38,15 +50,9 @@ test('a claim cleared after clean teardown is reported released', async () => {
3850
ledger.finalize(session);
3951

4052
expect(ledger.claims).toEqual({
41-
released: [
42-
{
43-
deviceKey: session.deviceClaim?.deviceKey,
44-
session: 'default',
45-
platform: 'android',
46-
deviceId: 'emulator-5554',
47-
},
48-
],
53+
released: [claimRecord(session, 'default')],
4954
orphaned: [],
55+
superseded: [],
5056
});
5157
expect(inspectDeviceClaims({})).toEqual([]);
5258
});
@@ -59,17 +65,38 @@ test('a claim left behind by a failed teardown is reported orphaned', async () =
5965
ledger.finalize(session);
6066

6167
expect(ledger.claims.released).toEqual([]);
62-
expect(ledger.claims.orphaned).toEqual([
63-
{
64-
deviceKey: session.deviceClaim?.deviceKey,
65-
session: 'stuck',
66-
platform: 'android',
67-
deviceId: 'emulator-5554',
68-
},
69-
]);
68+
expect(ledger.claims.orphaned).toEqual([claimRecord(session, 'stuck')]);
7069
expect(inspectDeviceClaims({}).map((entry) => entry.claim?.session)).toEqual(['stuck']);
7170
});
7271

72+
test('a claim replaced by a successor owner is reported superseded, never released', async () => {
73+
const session = await claimedSession('replaced');
74+
const deviceKey = session.deviceClaim?.deviceKey ?? '';
75+
// The shape recovery leaves behind: this daemon's claim file is removed out
76+
// from under it, and another owner claims the same device before this daemon
77+
// reaches teardown. `clearDeviceClaim` finds a claim it does not own and
78+
// deliberately leaves it alone, so "the call resolved" cannot mean "released".
79+
fs.rmSync(resolveDeviceClaimPath(deviceKey));
80+
const successor = await acquireDeviceClaim({
81+
device: ANDROID_EMULATOR,
82+
session: 'successor',
83+
workspace: '/worktrees/successor',
84+
stateDir: `${session.stateDir}-successor`,
85+
reconcileOrphanedDeviceClaim: retainOrphanedDeviceClaims,
86+
});
87+
expect(successor.status).toBe('acquired');
88+
89+
const ledger = createDaemonShutdownClaimLedger();
90+
await ledger.releaseClaim(session);
91+
ledger.finalize(session);
92+
93+
expect(ledger.claims.released).toEqual([]);
94+
expect(ledger.claims.orphaned).toEqual([]);
95+
expect(ledger.claims.superseded).toEqual([claimRecord(session, 'replaced')]);
96+
// The successor keeps its device: teardown must never delete a foreign claim.
97+
expect(inspectDeviceClaims({}).map((entry) => entry.claim?.session)).toEqual(['successor']);
98+
});
99+
73100
test('a session that never held a claim contributes nothing', async () => {
74101
const ledger = createDaemonShutdownClaimLedger();
75102
const session: SessionState = {
@@ -82,5 +109,5 @@ test('a session that never held a claim contributes nothing', async () => {
82109
await ledger.releaseClaim(session);
83110
ledger.finalize(session);
84111

85-
expect(ledger.claims).toEqual({ released: [], orphaned: [] });
112+
expect(ledger.claims).toEqual({ released: [], orphaned: [], superseded: [] });
86113
});

0 commit comments

Comments
 (0)