Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions docs/adr/0007-remote-device-leases.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,29 @@ A daemon that enforces this rule reports the `session-lease-id` capability.

A session binds its admitted lease when it is created. Recording and snapshot can also create a session.
A session that starts without a lease stays unleased for its lifetime.
If an `open` would change the session's lease, the daemon refuses it with `LEASE_SESSION_MISMATCH` before launch.
Close the session under its current ownership before you open it under another lease.
If an `open` would change a live session's lease, the daemon refuses it with `LEASE_SESSION_MISMATCH` before launch.
Only an `open` with its own active lease can replace an expired session.
After settlement, the daemon resolves the address and device again and checks the successor lease under the new locks.

Lease admission and request execution share the daemon request lock.
Scope resolution may precede the lock. Ownership mutation must not.
A session cannot outlive its lease: lease end tears down its sessions and clears their device claims, even when the device no longer answers.
Lease expiry revokes admission before teardown.
The sweep and requests use the same daemon job for each expired session lifetime.
A request confirms expiry under the session lock and waits outside execution locks.
A lease end record covers all sessions, any retained execution host, and provider release.
The session job checks the lifetime and claim token under the session and device locks.
It clears the claim after cleanup confirms that the runtime is safe to reuse.
The registry reserves the lease's device scope until session cleanup and provider release are confirmed.
Canceling a request stops its wait while the daemon continues settlement.
An expired owner request returns `LEASE_NOT_FOUND`.
An owner `close` can report a confirmed end once in the outermost response.
When a provider reports an instance ended, the daemon ends the lease and its sessions regardless of provider cleanup outcome.
A cloud provider runtime refuses to allocate a lease that it is ending. It forgets a rented device only after the provider confirmed its stop.
Recoverable provider leases are journaled so a later daemon can end rentals left by a dead daemon. Sessions and claims are not restored.
Recoverable provider leases are journaled so a later daemon can end rentals left by a dead daemon.
Startup restores the reservation for an unresolved recoverable lease before it accepts overlapping allocations.
Live sessions start empty, and persistent device claims are checked under their host-global lock.

The registry checks the lease issuance, effective deadline, wanted work, and pending or active holds in the same expiry decision.
Wanted admitted work and human-control holds defer expiry.
Wanted work renews the existing inactivity window when it finishes. Canceled work neither defers expiry past cancellation nor renews it.
Before admission, a client phase such as an artifact upload sends lease heartbeats for as long as it runs.
Expand Down Expand Up @@ -67,7 +80,8 @@ The detailed contracts are in the [daemon](../../packages/daemon/docs/remote-dev
- Device-aware ownership makes contention recoverable before platform execution and keeps provider and device identity in scope.
- A single request lock keeps ownership and execution consistent.
- Preserving wanted work prevents an active command or provider allocation from losing its device to inactivity expiry.
- Recovery ends paid rentals without reviving claims and sessions that died with the daemon.
- Recovery ends paid rentals while live session admission starts empty.
- One expiry job prevents an owner request and the sweep from performing the same teardown.
- Host-owned app leases keep tenants from choosing their own authority over the desktop.
- A shared proxy token cannot tell one client from another. A session name and tenant can be listed or guessed, so only a random lease id can prove ownership.

Expand All @@ -76,6 +90,7 @@ The detailed contracts are in the [daemon](../../packages/daemon/docs/remote-dev
- Use runner locks as client leases: they protect tooling, not remote ownership.
- Restore live leases after daemon death: their sessions and device claims no longer exist.
- Keep a separate provider lease table per provider: repeated lifecycle bookkeeping drifts.
- Tear down expiry inline with a request: the sweep and successor can race the same effects.
- Put the table in contracts: it owns lifecycle mechanics, not wire vocabulary.
- Put the table in capture-kit: renting a device prepares it for execution, which provision-kit owns.
- Silently accept unsupported device specifications: the client could receive a different device than requested.
Expand Down
5 changes: 5 additions & 0 deletions docs/adr/0036-bounded-composite-resource-admission.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ Accepted for issue #3325 bounded composite resource admission.

For a bounded `batch` or `replay`, classify each step by the command descriptor's resource trait. `packages/daemon/src/core/composite-resource-admission.ts` owns the admission decision under the existing session and device locks. It reads existing resource owners and operation plans. A resource shape that cannot finish within the composite budget is refused before that step's lease admission, binding, cleanup, or native effect. Unknown shapes fail closed. The typed refusal names the shape and public command name while retaining completed progress and replay source.

Check lease expiry before admitting the composite under its outer locks.
If a step needs lease settlement while it holds outer locks, it returns a step failure.
The daemon job takes the execution locks after the composite unwinds.
The composite preserves completed progress and replay source.

The same boundary inspects session disposal for `close`. It uses stored resource handles and the daemon's actual provider release decision. An owned Android test IME alone is ordinary close cleanup: once close starts, restoration settles through the existing teardown path, which may exceed the remaining composite time. A failed restore on a session that holds a device claim keeps the session and its claim, so a retried `close` reruns the cleanup; a session without a claim is retired (#4237). The kept session does not hold a detached daemon open, so when nothing else uses that daemon, its idle-reap shutdown retries the cleanup and leaves a claim it cannot confirm stale. An embedded runtime or a disabled idle timeout never reaps, so there only a retried `close` releases the claim. Existing-session `open` preserves resource handles, even when it relaunches the app; it does not run session resource teardown or provider release. The boundary still validates an existing-session `open` before admission. Maestro app-only stop leaves its session and resources intact. For claim acquisition, a read-only preview uses the actual acquisition decisions and refuses durable recovery before a stable step reaches binding. Root and transient recovery gateways repeat the check when the claim changes after preview. A cross-daemon change after preview can already have reached facts or binding before the gateway backstop stops recovery.

The outer composite still authenticates, renews its lease, protects in-flight work, and reports activity. It does not refresh recording health because that read can invalidate a durable recording; an admitted step owns its own refresh. Direct commands and unbounded tests keep their existing behavior.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ import {
type DurableCaptureRecoveryParams,
type DurableCaptureRecordDefinition,
type DurableCaptureSessionBinding,
type DurableCaptureSessionResource,
type FinishRecoveredDurableCaptureParams,
} from '../durable-capture/index.ts';
import { cleanupDurableCaptureDescriptor } from '../durable-capture/transitions.ts';
import type { LiveResourceHandle } from '@agent-device/contracts/durable-resource';
import type { ResourceOwnershipFence } from '@agent-device/contracts/platform-runtime';
import type { DeviceInfo } from '@agent-device/kernel/device';
Expand Down Expand Up @@ -82,6 +84,7 @@ export function createDurableCaptureResource<
finishLive(params: {
binding: DurableCaptureSessionBinding<K, H>;
intent: DurableCaptureFinishIntent;
confirmedMissing?: () => boolean;
}): Promise<C> {
return finishLiveDurableCapture(
definition,
Expand All @@ -98,6 +101,18 @@ export function createDurableCaptureResource<
resourcePath: definition.store.resolvePath(params.binding.sessionDir),
});
},
/** Records external proof that this exact native resource no longer exists. */
async confirmLiveMissing(params: {
binding: DurableCaptureSessionBinding<K, H>;
resource: DurableCaptureSessionResource<K, H>;
}): Promise<void> {
await cleanupDurableCaptureDescriptor(definition, {
envelope: params.resource.envelope,
resourcePath: definition.store.resolvePath(params.binding.sessionDir),
cleanup: async () => ({ status: 'already-missing' }),
});
params.binding.clear(params.resource);
},
recoverAll(params: SessionCaptureRecoveryParams<K, H, C>) {
return recoverDurableCaptureResourcesAfterDaemonLock(recoveryParams(params));
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export function adoptStartedScreenRecording(params: {
export function finishLiveScreenRecording(params: {
binding: DurableCaptureSessionBinding<'screen-recording', ScreenRecordingLiveHandle>;
intent: DurableCaptureFinishIntent;
confirmedMissing?: () => boolean;
}): Promise<ScreenRecordingCompletion> {
return screenRecordingDurableResource.finishLive(params);
}
Expand Down
40 changes: 40 additions & 0 deletions packages/capture-kit/src/durable-capture/transitions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,46 @@ import {
testCaptureStore,
} from './durable-capture.fixtures.ts';
import { finishLiveDurableCapture } from './transitions.ts';
import { withDurableCaptureResourceFence } from './fence.ts';

test('proof received while waiting for the resource fence prevents native cleanup', async () => {
const context = makeDurableCaptureContext();
const start = makeDurableCaptureStartResult(context);
await adoptStartedDurableCapture(
testCaptureDefinition,
{ ...context, ...start, throwIfCanceled: () => {} },
context.resourcePath,
);
let release!: () => void;
const held = new Promise<void>((resolve) => {
release = resolve;
});
const holder = withDurableCaptureResourceFence({
store: testCaptureStore,
resourcePath: context.resourcePath,
expected: start.envelope.fence,
onCompleted: () => {},
run: () => held,
});
let confirmed = false;
const attempt = finishLiveDurableCapture(
testCaptureDefinition,
{ binding: context.binding, intent: 'disposal', confirmedMissing: () => confirmed },
context.resourcePath,
);
confirmed = true;
release();
await holder;
await expect(attempt).rejects.toMatchObject({
details: { reason: 'resource-already-completed' },
});
expect(start.finish).not.toHaveBeenCalled();
expect(start.forceCleanup).not.toHaveBeenCalled();
expect(context.binding.read()).toBeUndefined();
expect(testCaptureStore.read(context.resourcePath)).toMatchObject({
envelope: { lifecycle: 'completed', metadata: { cleanupStatus: 'already-missing' } },
});
});

test('finish failure remains primary when cleanup and cleanup-pending persistence both fail', async () => {
const context = makeDurableCaptureContext();
Expand Down
15 changes: 14 additions & 1 deletion packages/capture-kit/src/durable-capture/transitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export async function finishLiveDurableCapture<
params: {
binding: DurableCaptureSessionBinding<K, H>;
intent: DurableCaptureFinishIntent;
confirmedMissing?: () => boolean;
},
resourcePath: string,
): Promise<C> {
Expand All @@ -43,6 +44,7 @@ export async function finishLiveDurableCapture<
fence: active.envelope.fence,
resourcePath,
intent: params.intent,
confirmedMissing: params.confirmedMissing,
onCleanupPending: () => {
cleanupPending = true;
},
Expand Down Expand Up @@ -73,9 +75,15 @@ export async function finishDurableCaptureHandle<
fence: ResourceOwnershipFence;
resourcePath: string;
intent: DurableCaptureFinishIntent;
confirmedMissing?: () => boolean;
onCleanupPending?(outcome: Extract<CleanupOutcome, { status: 'cleanup-pending' }>): void;
},
): Promise<C> {
const settleIfMissing = (lease: DurableCaptureOpenResourceFenceLease<K>): void => {
if (!params.confirmedMissing?.()) return;
transitionCleanupOutcome(lease, { status: 'already-missing' });
throw completedDurableCaptureError(definition.store);
};
return await withDurableCaptureResourceFence({
store: definition.store,
resourcePath: params.resourcePath,
Expand All @@ -87,7 +95,9 @@ export async function finishDurableCaptureHandle<
onCompleted: async ({ envelope }) => {
let cleanup: CleanupOutcome;
try {
cleanup = await params.handle.forceCleanup();
cleanup = params.confirmedMissing?.()
? { status: 'already-missing' }
: await params.handle.forceCleanup();
} catch (error) {
cleanup = {
status: 'cleanup-pending',
Expand All @@ -110,12 +120,14 @@ export async function finishDurableCaptureHandle<
throw completedDurableCaptureError(definition.store);
},
run: async (lease) => {
settleIfMissing(lease);
markCompletingDurableCapture(lease);
const progress = createStopProgress(lease);
let finishOutcome: FinishOutcome<C>;
try {
finishOutcome = await params.handle.finish(progress);
} catch (finishError) {
settleIfMissing(lease);
await respondToFailedFinish(definition, lease, params, finishError, params.intent);
throw finishError;
}
Expand All @@ -125,6 +137,7 @@ export async function finishDurableCaptureHandle<
}
transitionFinishOutcome(definition, lease, finishOutcome);
const finishError = cleanupPendingError(definition, finishOutcome);
settleIfMissing(lease);
await respondToFailedFinish(definition, lease, params, finishError, params.intent);
throw finishError;
},
Expand Down
5 changes: 2 additions & 3 deletions packages/command-registry/src/flag-definitions-workflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,9 @@ export const WORKFLOW_FLAG_DEFINITIONS: readonly FlagDefinition[] = [
min: 100,
max: 120000,
usageLabel: '--wait <ms>',
usageDescription:
'Open: wait up to n ms for a device another session is holding before failing with DEVICE_IN_USE',
usageDescription: 'Open: limit the wait for a busy device or expired session cleanup to n ms',
inputDescription:
"Wait up to n milliseconds (100-120000) while another session holds the device, then fail with DEVICE_IN_USE. A claim held by another workspace fails at once. The wait extends this command's timeout.",
'Wait 100-120000 ms for a busy device or expired session cleanup. Return DEVICE_IN_USE if still busy. Claims from other workspaces fail at once. This extends the command timeout.',
projectConfig: false,
recorded: false,
},
Expand Down
5 changes: 2 additions & 3 deletions packages/contracts/src/client-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,8 @@ export type AppOpenOptions = AgentDeviceRequestOverrides &
/** Startup budget in milliseconds: bounds the Simulator boot wait on a cold device. */
timeoutMs?: number;
/**
* Wait up to n milliseconds (100-120000) while another session holds the device, then fail
* with DEVICE_IN_USE. A claim held by another workspace fails at once. The wait extends this
* command's timeout.
* Wait 100-120000 ms for a busy device or expired session cleanup. Return DEVICE_IN_USE if
* still busy. Claims from other workspaces fail at once. This extends the command timeout.
*/
waitMs?: number;
// Editor documentation for a public type: a `.d.ts` is read where no
Expand Down
35 changes: 31 additions & 4 deletions packages/daemon-contracts/src/daemon-shutdown-report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export type ProviderReleaseRecord = {
provider?: string;
};

export type LeaseCleanupFailure = { leaseId: string; failedSteps: string[] };

/**
* #1320: what happened to one session's device claim during graceful teardown.
* `released` means the claim was confirmed gone after the session reached a safe
Expand All @@ -27,6 +29,7 @@ export type DeviceClaimRecord = {
};

export type DaemonShutdownReport = {
leaseCleanupFailures?: LeaseCleanupFailure[];
providerReleases: {
released: ProviderReleaseRecord[];
pending: ProviderReleaseRecord[];
Expand All @@ -40,6 +43,7 @@ export type DaemonShutdownReport = {
};

export type DaemonShutdownOutcome = {
leaseCleanupFailures?: LeaseCleanupFailure[];
providerReleases: { released: readonly DeviceLease[]; pending: readonly DeviceLease[] };
claims: {
released: readonly DeviceClaimRecord[];
Expand All @@ -51,6 +55,7 @@ export type DaemonShutdownOutcome = {

export function buildDaemonShutdownReport(outcome: DaemonShutdownOutcome): DaemonShutdownReport {
return {
...leaseCleanupFailureSection(outcome.leaseCleanupFailures),
providerReleases: {
released: outcome.providerReleases.released.map(toProviderReleaseRecord),
pending: outcome.providerReleases.pending.map(toProviderReleaseRecord),
Expand All @@ -70,7 +75,11 @@ export function readDaemonShutdownReport(stateDir: string): DaemonShutdownReport
fs.readFileSync(resolveDaemonShutdownReportPath(stateDir), 'utf8'),
);
return isProviderReleaseReport(parsed)
? { providerReleases: parsed.providerReleases, claims: readClaimSection(parsed) }
? {
providerReleases: parsed.providerReleases,
claims: readClaimSection(parsed),
...leaseCleanupFailureSection(parsed.leaseCleanupFailures),
}
: null;
} catch {
return null;
Expand All @@ -88,9 +97,13 @@ function toProviderReleaseRecord(lease: DeviceLease): ProviderReleaseRecord {
};
}

function isProviderReleaseReport(
value: unknown,
): value is Omit<DaemonShutdownReport, 'claims'> & { claims?: unknown } {
function isProviderReleaseReport(value: unknown): value is Pick<
DaemonShutdownReport,
'providerReleases'
> & {
claims?: unknown;
leaseCleanupFailures?: unknown;
} {
if (!value || typeof value !== 'object') return false;
const releases = (value as { providerReleases?: unknown }).providerReleases;
if (!releases || typeof releases !== 'object') return false;
Expand All @@ -103,6 +116,20 @@ function isProviderReleaseReport(
);
}

function leaseCleanupFailureSection(
value: unknown,
): Pick<DaemonShutdownReport, 'leaseCleanupFailures'> {
if (!Array.isArray(value)) return {};
const leaseCleanupFailures = value.filter(
(item): item is LeaseCleanupFailure =>
isProviderReleaseRecord(item) &&
'failedSteps' in item &&
Array.isArray(item.failedSteps) &&
item.failedSteps.every((step) => typeof step === 'string'),
);
return leaseCleanupFailures.length ? { leaseCleanupFailures } : {};
}

function readClaimSection(value: { claims?: unknown }): DaemonShutdownReport['claims'] {
const claims = value.claims;
if (!claims || typeof claims !== 'object') {
Expand Down
4 changes: 4 additions & 0 deletions packages/daemon-contracts/src/daemon-stop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,10 @@ export function mergeDaemonShutdownReport(
...supersededClaimWarnings(report.claims.superseded),
...orphanedClaimWarnings(report.claims.orphaned),
...unattributableClaimWarnings(report.claims.unattributable),
...(report.leaseCleanupFailures ?? []).map(
({ leaseId, failedSteps }) =>
`Lease ${leaseId} had unfinished local cleanup at shutdown (${failedSteps.join(', ')}).`,
),
],
}
: stopped;
Expand Down
Loading
Loading