Skip to content

Commit a72c9cd

Browse files
committed
fix(daemon): revalidate claim resources during recovery
1 parent f1febce commit a72c9cd

3 files changed

Lines changed: 123 additions & 1 deletion

File tree

‎packages/daemon-contracts/src/device-claim-reconciliation.test.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ import {
2020
unavailableDeploymentSnapshotAndShutdownOperationFacts,
2121
} from '@agent-device/test-kit';
2222
import type { DeviceClaim } from './device-claims.ts';
23+
import { resolveDeviceClaimPath } from './device-claim-paths.ts';
24+
import { settleVerifiedOrphanedClaim } from './device-claim-settlement.ts';
25+
import { writeDeviceClaim } from './device-claim-store.ts';
26+
import { createOwnerScopedDeviceClaimReconciler } from './device-claim-owner-recovery.ts';
2327

2428
const scope = {
2529
signal: new AbortController().signal,
@@ -233,6 +237,108 @@ const unavailable = Object.freeze({
233237
reason: 'owner-capability-missing' as const,
234238
});
235239

240+
test.each([
241+
{ caseName: 'appearing', initiallyOwned: false, mode: 'direct' },
242+
{ caseName: 'changing owner', initiallyOwned: true, mode: 'direct' },
243+
{ caseName: 'appearing', initiallyOwned: false, mode: 'owner-scoped' },
244+
{ caseName: 'changing owner', initiallyOwned: true, mode: 'owner-scoped' },
245+
] as const)(
246+
'a later foreign manifest $caseName during $mode recovery retains the claim',
247+
async ({ initiallyOwned, mode }) => {
248+
const stateDir = mkdtempForTestSync('device-claim-late-resource-');
249+
const claim = makeClaim(stateDir);
250+
const env = { AGENT_DEVICE_CLAIMS_DIR: path.join(stateDir, 'claims') };
251+
writeDeviceClaim(claim, env);
252+
const sessionDir = path.join(stateDir, 'sessions', claim.session);
253+
appLogResourceStore.write(
254+
appLogResourceStore.resolvePath(sessionDir),
255+
createDurableResourceEnvelope({
256+
resourceKind: 'app-log',
257+
sessionId: claim.session,
258+
device: claim.device,
259+
owner: localRuntimeOwner('android'),
260+
fence: { token: 'app-log-fence', generation: 1 },
261+
lifecycle: 'open',
262+
descriptor: { version: 1, body: { pid: 123 } },
263+
}),
264+
);
265+
const screenPath = screenRecordingDurableResource.store.resolvePath(sessionDir);
266+
const writeScreen = (sessionId: string) =>
267+
screenRecordingDurableResource.store.write(
268+
screenPath,
269+
createDurableResourceEnvelope({
270+
resourceKind: 'screen-recording',
271+
sessionId,
272+
device: claim.device,
273+
owner: localRuntimeOwner('android'),
274+
fence: { token: 'screen-fence', generation: 1 },
275+
lifecycle: 'open',
276+
descriptor: { version: 1, body: {} },
277+
}),
278+
);
279+
if (initiallyOwned) writeScreen(claim.session);
280+
let enterBind!: () => void;
281+
const enteredBind = new Promise<void>((resolve) => {
282+
enterBind = resolve;
283+
});
284+
let resumeBind!: () => void;
285+
const heldBind = new Promise<void>((resolve) => {
286+
resumeBind = resolve;
287+
});
288+
const dispose = vi.fn(async () => {});
289+
const bind = vi.fn(async ({ device }) => {
290+
enterBind();
291+
await heldBind;
292+
return {
293+
device,
294+
owner: localRuntimeOwner('android'),
295+
facts: {
296+
device: { family: 'android' as const, kind: device.kind, providerMode: 'local' as const },
297+
operations: {
298+
appLogReattach: { available: true as const },
299+
appLogCleanup: { available: true as const },
300+
},
301+
},
302+
operations: {
303+
appLogReattach: async () => ({ status: 'missing' as const }),
304+
appLogCleanup: async () => ({ status: 'cleaned' as const }),
305+
},
306+
[Symbol.asyncDispose]: dispose,
307+
};
308+
});
309+
const shutdown = vi.fn(async () => {});
310+
const gateway = {
311+
bind,
312+
shutdown,
313+
} as unknown as DeviceRuntimeGateway<PlatformRuntimeOperations>;
314+
const reconciler =
315+
mode === 'owner-scoped'
316+
? createOwnerScopedDeviceClaimReconciler({
317+
scope,
318+
beforeGateway: inspectDeviceClaimRecovery,
319+
composeGateway: () => gateway,
320+
})
321+
: createDeviceClaimReconciler({ gateway, scope });
322+
const settlement = settleVerifiedOrphanedClaim(claim, reconciler, env);
323+
await enteredBind;
324+
writeScreen('foreign-session');
325+
resumeBind();
326+
327+
await expect(settlement).resolves.toEqual({
328+
status: 'retained',
329+
reason: 'screen-recording-owner-mismatch',
330+
});
331+
expect(fs.existsSync(resolveDeviceClaimPath(claim.deviceKey, env))).toBe(true);
332+
expect(bind).toHaveBeenCalledOnce();
333+
expect(dispose).toHaveBeenCalledOnce();
334+
expect(shutdown).toHaveBeenCalledTimes(mode === 'owner-scoped' ? 1 : 0);
335+
expect(screenRecordingDurableResource.store.read(screenPath)).toMatchObject({
336+
status: 'decoded',
337+
envelope: { sessionId: 'foreign-session', lifecycle: 'open' },
338+
});
339+
},
340+
);
341+
236342
function makeClaim(stateDir: string): DeviceClaim {
237343
return {
238344
schemaVersion: 3,

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,12 @@ export function createDeviceClaimReconciler(params: {
3030
if (inspection.status === 'retained') return inspection;
3131
try {
3232
const sessionsDir = resolveDaemonPaths(claim.stateDir).sessionsDir;
33+
const sessionDir = path.join(sessionsDir, safeSessionName(claim.session));
3334
for (const { resourceKind, resourcePath } of inspection.ownedResources) {
3435
const resource = DEVICE_CLAIM_DURABLE_RESOURCES[resourceKind];
36+
const currentOwnership = inspectResourceOwnership(resource, claim, sessionDir);
37+
if (currentOwnership.status === 'retained') return currentOwnership;
38+
if (currentOwnership.status === 'missing') continue;
3539
// Recovery is intentionally sequential: resources can bind the same exact
3640
// device/runtime owner, so one must release its binding before the next starts.
3741
const outcome = await resource.recover(params, sessionsDir, resourcePath);
@@ -42,6 +46,18 @@ export function createDeviceClaimReconciler(params: {
4246
};
4347
}
4448
}
49+
const afterRecovery = inspectDeviceClaimRecovery(claim);
50+
if (afterRecovery.status === 'retained') return afterRecovery;
51+
const initialPaths = new Set(
52+
inspection.ownedResources.map(({ resourcePath }) => resourcePath),
53+
);
54+
const pending = afterRecovery.ownedResources.find(
55+
({ resourceKind, resourcePath }) =>
56+
!initialPaths.has(resourcePath) || afterRecovery.recoveryKinds.includes(resourceKind),
57+
);
58+
if (pending) {
59+
return { status: 'retained', reason: `${pending.resourceKind}-cleanup-pending` };
60+
}
4561
return { status: 'reconciled' };
4662
} catch (error) {
4763
emitDiagnostic({

‎packages/daemon/src/server/device/__tests__/device-claim-owner-recovery.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ test('owner-scoped recovery uses its pre-gateway ownership decision for terminal
164164
composeGateway: () => ({ bind, shutdown }) as never,
165165
});
166166
expect(await reconcile(claim)).toEqual({ status: 'reconciled' });
167-
expect(openedPaths).toEqual([resourcePath, screenPath, resourcePath, screenPath]);
167+
expect(openedPaths.slice(0, 2)).toEqual([resourcePath, screenPath]);
168168
expect(bind).not.toHaveBeenCalled();
169169
expect(shutdown).toHaveBeenCalledOnce();
170170
expect(appLogResourceStore.read(resourcePath)).toMatchObject({

0 commit comments

Comments
 (0)