diff --git a/docs/adr/0007-remote-device-leases.md b/docs/adr/0007-remote-device-leases.md index 9038a0b5b8..b8704f816e 100644 --- a/docs/adr/0007-remote-device-leases.md +++ b/docs/adr/0007-remote-device-leases.md @@ -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. @@ -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. @@ -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. diff --git a/docs/adr/0036-bounded-composite-resource-admission.md b/docs/adr/0036-bounded-composite-resource-admission.md index 083146d436..58dc67e3f6 100644 --- a/docs/adr/0036-bounded-composite-resource-admission.md +++ b/docs/adr/0036-bounded-composite-resource-admission.md @@ -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. diff --git a/packages/capture-kit/src/capture-admission/durable-capture-resource.ts b/packages/capture-kit/src/capture-admission/durable-capture-resource.ts index 1e84672773..e7de55aefe 100644 --- a/packages/capture-kit/src/capture-admission/durable-capture-resource.ts +++ b/packages/capture-kit/src/capture-admission/durable-capture-resource.ts @@ -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'; @@ -82,6 +84,7 @@ export function createDurableCaptureResource< finishLive(params: { binding: DurableCaptureSessionBinding; intent: DurableCaptureFinishIntent; + confirmedMissing?: () => boolean; }): Promise { return finishLiveDurableCapture( definition, @@ -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; + resource: DurableCaptureSessionResource; + }): Promise { + 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) { return recoverDurableCaptureResourcesAfterDaemonLock(recoveryParams(params)); }, diff --git a/packages/capture-kit/src/capture-admission/screen-recording-session-resource.ts b/packages/capture-kit/src/capture-admission/screen-recording-session-resource.ts index a5ff0a579b..b94f1b9a6a 100644 --- a/packages/capture-kit/src/capture-admission/screen-recording-session-resource.ts +++ b/packages/capture-kit/src/capture-admission/screen-recording-session-resource.ts @@ -67,6 +67,7 @@ export function adoptStartedScreenRecording(params: { export function finishLiveScreenRecording(params: { binding: DurableCaptureSessionBinding<'screen-recording', ScreenRecordingLiveHandle>; intent: DurableCaptureFinishIntent; + confirmedMissing?: () => boolean; }): Promise { return screenRecordingDurableResource.finishLive(params); } diff --git a/packages/capture-kit/src/durable-capture/transitions.test.ts b/packages/capture-kit/src/durable-capture/transitions.test.ts index d50c0e3c02..719181ccae 100644 --- a/packages/capture-kit/src/durable-capture/transitions.test.ts +++ b/packages/capture-kit/src/durable-capture/transitions.test.ts @@ -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((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(); diff --git a/packages/capture-kit/src/durable-capture/transitions.ts b/packages/capture-kit/src/durable-capture/transitions.ts index def26a9741..ee296f5fa6 100644 --- a/packages/capture-kit/src/durable-capture/transitions.ts +++ b/packages/capture-kit/src/durable-capture/transitions.ts @@ -31,6 +31,7 @@ export async function finishLiveDurableCapture< params: { binding: DurableCaptureSessionBinding; intent: DurableCaptureFinishIntent; + confirmedMissing?: () => boolean; }, resourcePath: string, ): Promise { @@ -43,6 +44,7 @@ export async function finishLiveDurableCapture< fence: active.envelope.fence, resourcePath, intent: params.intent, + confirmedMissing: params.confirmedMissing, onCleanupPending: () => { cleanupPending = true; }, @@ -73,9 +75,15 @@ export async function finishDurableCaptureHandle< fence: ResourceOwnershipFence; resourcePath: string; intent: DurableCaptureFinishIntent; + confirmedMissing?: () => boolean; onCleanupPending?(outcome: Extract): void; }, ): Promise { + const settleIfMissing = (lease: DurableCaptureOpenResourceFenceLease): void => { + if (!params.confirmedMissing?.()) return; + transitionCleanupOutcome(lease, { status: 'already-missing' }); + throw completedDurableCaptureError(definition.store); + }; return await withDurableCaptureResourceFence({ store: definition.store, resourcePath: params.resourcePath, @@ -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', @@ -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; try { finishOutcome = await params.handle.finish(progress); } catch (finishError) { + settleIfMissing(lease); await respondToFailedFinish(definition, lease, params, finishError, params.intent); throw finishError; } @@ -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; }, diff --git a/packages/command-registry/src/flag-definitions-workflow.ts b/packages/command-registry/src/flag-definitions-workflow.ts index 8541ee5d91..79006d74ae 100644 --- a/packages/command-registry/src/flag-definitions-workflow.ts +++ b/packages/command-registry/src/flag-definitions-workflow.ts @@ -96,10 +96,9 @@ export const WORKFLOW_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ min: 100, max: 120000, usageLabel: '--wait ', - 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, }, diff --git a/packages/contracts/src/client-app.ts b/packages/contracts/src/client-app.ts index 4364a60c41..18f224dd86 100644 --- a/packages/contracts/src/client-app.ts +++ b/packages/contracts/src/client-app.ts @@ -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 diff --git a/packages/daemon-contracts/src/daemon-shutdown-report.ts b/packages/daemon-contracts/src/daemon-shutdown-report.ts index 10cc14c87d..216196c1e0 100644 --- a/packages/daemon-contracts/src/daemon-shutdown-report.ts +++ b/packages/daemon-contracts/src/daemon-shutdown-report.ts @@ -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 @@ -27,6 +29,7 @@ export type DeviceClaimRecord = { }; export type DaemonShutdownReport = { + leaseCleanupFailures?: LeaseCleanupFailure[]; providerReleases: { released: ProviderReleaseRecord[]; pending: ProviderReleaseRecord[]; @@ -40,6 +43,7 @@ export type DaemonShutdownReport = { }; export type DaemonShutdownOutcome = { + leaseCleanupFailures?: LeaseCleanupFailure[]; providerReleases: { released: readonly DeviceLease[]; pending: readonly DeviceLease[] }; claims: { released: readonly DeviceClaimRecord[]; @@ -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), @@ -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; @@ -88,9 +97,13 @@ function toProviderReleaseRecord(lease: DeviceLease): ProviderReleaseRecord { }; } -function isProviderReleaseReport( - value: unknown, -): value is Omit & { 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; @@ -103,6 +116,20 @@ function isProviderReleaseReport( ); } +function leaseCleanupFailureSection( + value: unknown, +): Pick { + 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') { diff --git a/packages/daemon-contracts/src/daemon-stop.ts b/packages/daemon-contracts/src/daemon-stop.ts index 4817521a7b..bd0bf885f3 100644 --- a/packages/daemon-contracts/src/daemon-stop.ts +++ b/packages/daemon-contracts/src/daemon-stop.ts @@ -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; diff --git a/packages/daemon/docs/remote-device-lease-contracts.md b/packages/daemon/docs/remote-device-lease-contracts.md index 33a462aeb3..fa96f53ea1 100644 --- a/packages/daemon/docs/remote-device-lease-contracts.md +++ b/packages/daemon/docs/remote-device-lease-contracts.md @@ -16,12 +16,24 @@ If the caller stops heartbeats for a retained lease, that lease expires after it Idle reap then shuts the daemon down within one more idle window. A session cannot outlive the lease it binds at creation. -When the lease is released, expires, or its provider reports the instance ended, the daemon tears the session down under its execution locks and clears its device claim. +When the lease is released, expires, or its provider reports that the instance ended, the daemon tears the session down. +The daemon keeps the device claim until teardown confirms that the runtime is safe to reuse. Any teardown of a leased session, including `close`, finishes an active recording. A daemon-owned export stays downloadable under its producing owner, as with `record stop` (ADR 0024 2.5). This applies even when the device no longer answers. A release is a tenant `lease_release` or a host `DELETE /admin/leases/`. The daemon sweeps for expired leases every second. -Thus, expiry does not wait for a later request. +A request can also trigger expiry. +Both paths share one teardown for each expired session. +The daemon keeps the lease reservation until session cleanup and any provider release are confirmed. +If the provider refuses release and no recovery record exists, an overlapping allocation returns +`DEVICE_LEASE_BUSY` with `releaseStatus: "unknown"`. +If expiry wins, the old owner's request returns `LEASE_NOT_FOUND`. +An owner `close` can report the confirmed lease end in `endedLeases` on that error. +Only `open` with a separate valid lease can replace an expired session. +It waits within the request deadline and the `--wait` budget, if set. +The successor lease must still be valid when the wait ends. +If cleanup remains pending, `open` can return `DEVICE_IN_USE` with reason `DEVICE_LEASE_BUSY`. +Canceling a waiting request leaves teardown running. In-flight work and human-control holds still keep a lease from expiring. After daemon shutdown begins, no new lease-end teardown starts. Shutdown waits for any lease-end teardown that already started before it tears sessions down itself. @@ -52,7 +64,7 @@ This applies to every request that can close a session: - The session cleanup that `test` runs after each script. Nested requests record on the ledger of the outermost request, so a step reply never repeats the report. -If a close finds its lease already inactive, it reports that lease as ended. +If expiry wins, an owner close can report the confirmed lease end once in its refusal. A client never sends a release after such a request. If a client stores the lease id, it forgets that id when the reply names it. The CLI keeps the id of an ended proxy lease apart, and sends it only on `artifacts` while the connection holds no lease. @@ -87,12 +99,12 @@ An expired `batch` refused with `LEASE_NOT_FOUND` also gets a separate request r To read a refused request's record remotely, use the locator in the error and send the lease ID that the request presented, if it presented one. If a lock-exempt command can take the session lock immediately, it can refresh the recording for the session lifetime it was admitted to use. A `test` suite reads, records, and closes an attempt session only with the lease id that the suite sent. -After the lease deadline, a request that holds the session lock and sends the lease id of the session ends that session. -A request that sends a different active lease, and that lease admission accepts for a new session, also ends that expired session under its locks. It then runs as the new owner. Its reply and its diagnostics do not name the expired lease. -The successor starts admitted work before it ends the expired session. -A `batch`, a `replay`, and a bounded step do not end the session, and the lease sweep ends it. With the expired lease id, they are refused with `LEASE_NOT_FOUND`. With a different active lease, they are refused with `LEASE_SESSION_MISMATCH`. -A request without an active lease is refused and ends nothing. The lease sweep ends the session. -A command that holds no session lock ends no session. It leaves the expired session to the lease-end teardown. +The sweep and an authorized request share the daemon's expiry job. +A request that needs settlement waits outside execution locks. +A bounded step that needs settlement returns a step failure and unwinds. +An expired owner request receives `LEASE_NOT_FOUND`. +Only `open` with a separate valid lease can replace the expired session after settlement. +The daemon checks that lease again before it starts work. Tenant, run id, lease backend, client id, device key, and lease provider are labels. The daemon refuses a label that differs from the session lease. A missing label is not a refusal and grants nothing. The daemon compares each value that a request sends for a label: the value in `meta`, the value in `flags`, and each alias of a param. diff --git a/packages/daemon/src/__tests__/support/human-control-router-fixture.ts b/packages/daemon/src/__tests__/support/human-control-router-fixture.ts index c22b131caf..499a22d42f 100644 --- a/packages/daemon/src/__tests__/support/human-control-router-fixture.ts +++ b/packages/daemon/src/__tests__/support/human-control-router-fixture.ts @@ -43,7 +43,6 @@ export function createHumanControlHarness() { deviceRuntimeGateway: lifecycleDeviceRuntimeGateway, androidObservation: clearAndroidObservationFixture, platformResourceCleanup: platformResourceCleanupFixture(), - settleExpiredSession: async () => {}, trackDownloadableArtifact: () => 'artifact-1', }); return { registry, lease, sessionStore, sessionName, handleRequest }; diff --git a/packages/daemon/src/__tests__/support/session-teardown.fixtures.ts b/packages/daemon/src/__tests__/support/session-teardown.fixtures.ts index bfc95e137f..4bdad61ed6 100644 --- a/packages/daemon/src/__tests__/support/session-teardown.fixtures.ts +++ b/packages/daemon/src/__tests__/support/session-teardown.fixtures.ts @@ -1,5 +1,5 @@ import path from 'node:path'; -import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime'; +import { localRuntimeOwner, type RuntimeOwnerRef } from '@agent-device/contracts/platform-runtime'; import type { ScreenRecordingLiveHandle } from '@agent-device/contracts/screen-recording-runtime'; import { createDurableResourceEnvelope } from '@agent-device/capture-kit'; import { webSessionDevice } from '@agent-device/kernel/device'; @@ -12,6 +12,8 @@ export function makeRecordingSession(params: { name: string; sessionStore: SessionStore; finish: ScreenRecordingLiveHandle['finish']; + forceCleanup?: ScreenRecordingLiveHandle['forceCleanup']; + owner?: RuntimeOwnerRef; }): SessionState { const { name, sessionStore, finish } = params; const device = { @@ -37,14 +39,14 @@ export function makeRecordingSession(params: { setRunnerSessionId: () => {}, invalidate: () => {}, finish, - forceCleanup: async () => ({ status: 'cleaned' }), + forceCleanup: params.forceCleanup ?? (async () => ({ status: 'cleaned' })), [Symbol.asyncDispose]: async () => {}, }; const envelope = createDurableResourceEnvelope({ resourceKind: 'screen-recording', sessionId: name, device: { id: device.id, family: 'apple', appleOs: 'ios', kind: 'simulator' }, - owner: localRuntimeOwner('apple'), + owner: params.owner ?? localRuntimeOwner('apple'), fence: { token: `${name}-fence`, generation: 1 }, lifecycle: 'open', descriptor: { version: 1, body: { recordingId: name } }, diff --git a/packages/daemon/src/__tests__/support/test-device-runtime-gateway.ts b/packages/daemon/src/__tests__/support/test-device-runtime-gateway.ts index 51613653e2..0e42541076 100644 --- a/packages/daemon/src/__tests__/support/test-device-runtime-gateway.ts +++ b/packages/daemon/src/__tests__/support/test-device-runtime-gateway.ts @@ -20,7 +20,6 @@ import { } from '../../server/request-router.ts'; import type { BindDeviceRuntime } from '../../core/request-runtime-binding.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; -import type { SessionRef } from '../../core/session-state.ts'; import { applicationLifecycleRuntimeFixture, type LifecycleOperationsLoader, @@ -34,7 +33,6 @@ import { daemonPlatformServicesFixture, } from './platform-services-fixture.ts'; import { platformResourceCleanupFixture } from './platform-resource-cleanup-fixture.ts'; -import { teardownSessionResources } from '../../sessions/session-teardown.ts'; import { providerCredentialsFixture } from './provider-credentials-fixture.ts'; import { unavailableBinding, @@ -208,7 +206,6 @@ export function createRequestHandler( | 'trackClaimRecoveryDisposal' | 'androidObservation' | 'platformResourceCleanup' - | 'settleExpiredSession' > & Partial< Pick< @@ -220,7 +217,6 @@ export function createRequestHandler( | 'trackClaimRecoveryDisposal' | 'androidObservation' | 'platformResourceCleanup' - | 'settleExpiredSession' > >, ) { @@ -232,19 +228,10 @@ export function createRequestHandler( trackClaimRecoveryDisposal = () => {}, androidObservation = clearAndroidObservationFixture, platformResourceCleanup = platformResourceCleanupFixture(), - // The resource half of the daemon-owned settle, over this handler's cleanup fixture. - settleExpiredSession = async (ref: SessionRef) => - await teardownSessionResources({ - appLog: 'run', - ref, - sessionStore: deps.sessionStore, - platformCleanup: platformResourceCleanup, - }), ...rest } = deps; const handle = createProductionRequestHandler({ ...rest, - settleExpiredSession, androidObservation, platformResourceCleanup, platformServices, diff --git a/packages/daemon/src/core/composite-resource-admission-lease.test.ts b/packages/daemon/src/core/composite-resource-admission-lease.test.ts index 8b75f5611d..221851f49a 100644 --- a/packages/daemon/src/core/composite-resource-admission-lease.test.ts +++ b/packages/daemon/src/core/composite-resource-admission-lease.test.ts @@ -55,7 +55,7 @@ test.each(['batch', 'replay'] as const)( expect(world.bind).not.toHaveBeenCalled(); expect(owned.finish).not.toHaveBeenCalled(); expect(world.sessionStore.requireCurrent(world.ref)).toMatchObject(owned.patch); - expect(world.leaseRegistry.consumeExpiredLease(lease.leaseId)?.leaseId).toBe(lease.leaseId); + expect(world.leaseRegistry.consumeExpiredLease(lease.leaseId)).toBeUndefined(); } finally { await world.daemon.close(); } diff --git a/packages/daemon/src/core/composite-resource-admission.test.ts b/packages/daemon/src/core/composite-resource-admission.test.ts index f17dc30964..a4f6c99db9 100644 --- a/packages/daemon/src/core/composite-resource-admission.test.ts +++ b/packages/daemon/src/core/composite-resource-admission.test.ts @@ -821,7 +821,6 @@ test.each(['batch', 'replay'] as const)( const refusedLease = attachLease(refused); const allowedHeartbeat = vi.spyOn(allowed.leaseRegistry, 'heartbeatLease'); const refusedHeartbeat = vi.spyOn(refused.leaseRegistry, 'heartbeatLease'); - const refusedConsume = vi.spyOn(refused.leaseRegistry, 'consumeExpiredLease'); assertRpcOk( await allowed.call('batch', [], { batchSteps: [{ command: 'home' }], @@ -857,7 +856,6 @@ test.each(['batch', 'replay'] as const)( expect(refusedHeartbeat).toHaveBeenCalledWith( expect.objectContaining({ leaseId: refusedLease.leaseId }), ); - expect(refusedConsume).toHaveBeenCalledOnce(); expect(refused.leaseRegistry.getLease(refusedLease)).toMatchObject({ leaseId: refusedLease.leaseId, }); diff --git a/packages/daemon/src/core/session-store.ts b/packages/daemon/src/core/session-store.ts index bc32804ebc..de358b9b86 100644 --- a/packages/daemon/src/core/session-store.ts +++ b/packages/daemon/src/core/session-store.ts @@ -274,11 +274,6 @@ export class SessionStore { return this.listRefs().filter((ref) => ref.session.lease?.leaseId === leaseId); } - currentRefForLease(ref: SessionRef, leaseId: string): SessionRef | undefined { - if (this.resolveCurrent(ref)?.lease?.leaseId !== leaseId) return undefined; - return this.refresh(ref); - } - getRuntimeHints(name: string): SessionRuntimeHints | undefined { return this.runtimeHints.get(name)?.hints; } diff --git a/packages/daemon/src/resources/__tests__/lease-registry-inspection.test.ts b/packages/daemon/src/resources/__tests__/lease-registry-inspection.test.ts index c78dc6f8c1..515bd3859d 100644 --- a/packages/daemon/src/resources/__tests__/lease-registry-inspection.test.ts +++ b/packages/daemon/src/resources/__tests__/lease-registry-inspection.test.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest'; +import { expect, test } from 'vitest'; import assert from 'node:assert/strict'; import { LeaseRegistry } from '../lease-registry.ts'; import { HUMAN_CONTROL_LEASE_REQUEST } from '../../__tests__/support/human-control-fixtures.ts'; @@ -45,23 +45,6 @@ test('read-only backend inspection respects a host-pinned TTL after hold expiry' assert.equal(registry.consumeExpiredLease(leaseId)?.leaseId, leaseId); }); -test('expiry consumption rereads a lease protected by its before-consume owner', () => { - let now = 0; - const registry = new LeaseRegistry({ now: () => now, defaultLeaseTtlMs: 5_000 }); - const lease = registry.allocateLease(HUMAN_CONTROL_LEASE_REQUEST); - now = 5_000; - let inspected = 0; - let pass: ReturnType | undefined; - const consumed = registry.consumeExpiredLease(lease.leaseId, () => { - inspected++; - pass = registry.retainLeaseWork(lease, () => true); - }); - assert.equal(inspected, 1); - assert.equal(consumed, undefined); - assert.equal(registry.inspectLeaseBackend(lease.leaseId), lease.backend); - pass?.release(); -}); - test('expiry consumption sweeps expired holds even when the named lease is absent', async () => { let now = 0; const registry = new LeaseRegistry({ now: () => now, defaultLeaseTtlMs: 5_000 }); @@ -75,3 +58,77 @@ test('expiry consumption sweeps expired holds even when the named lease is absen .holdsByDevice; assert.equal(heldDevices.size, 0); }); + +test.each(['sessionsSettled', 'providerReleased'] as const)( + 'expiry keeps the device reserved after %s until both parts are confirmed', + (first) => { + let now = 1_000; + const registry = new LeaseRegistry({ + now: () => now, + onLeaseExpired: (lease) => registry.reserveExpiredLease(lease), + }); + const request = { ...HUMAN_CONTROL_LEASE_REQUEST, leaseProvider: 'fixture' }; + const lease = registry.allocateLease(request); + now = lease.expiresAt; + expect(registry.consumeExpiredLeases()).toEqual([lease]); + const next = { ...request, runId: 'successor' }; + const expectBusy = () => + expect(() => registry.allocateLease(next)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'DEVICE_LEASE_BUSY' }), + }), + ); + + expectBusy(); + expect(registry.confirmExpiredLeaseEnd(lease.leaseId, first)).toBe(false); + expectBusy(); + const second = first === 'sessionsSettled' ? 'providerReleased' : 'sessionsSettled'; + expect(registry.confirmExpiredLeaseEnd(lease.leaseId, second)).toBe(true); + expect(registry.allocateLease(next).leaseId).not.toBe(lease.leaseId); + }, +); + +test('an ending lease without a device key keeps its run binding until confirmation', () => { + let now = 1_000; + const registry = new LeaseRegistry({ + now: () => now, + onLeaseExpired: (lease) => registry.reserveExpiredLease(lease), + }); + const request = { tenantId: 'tenant', runId: 'run', leaseProvider: 'fixture' }; + const lease = registry.allocateLease(request); + now = lease.expiresAt; + registry.consumeExpiredLeases(); + registry.confirmExpiredLeaseEnd(lease.leaseId, 'sessionsSettled'); + expect(() => registry.allocateLease(request)).toThrow( + expect.objectContaining({ details: expect.objectContaining({ reason: 'DEVICE_LEASE_BUSY' }) }), + ); + expect(registry.confirmExpiredLeaseEnd(lease.leaseId, 'providerReleased')).toBe(true); + expect(registry.allocateLease(request).leaseId).not.toBe(lease.leaseId); +}); + +test('a delayed expiry reservation cannot fence a renewed host lease with the same ID', async () => { + let now = 1_000; + let resume!: () => void; + const beforeReservation = new Promise((resolve) => { + resume = resolve; + }); + const registry = new LeaseRegistry({ now: () => now }); + const leaseId = 'a1b2c3d4e5f60718293a4b5c6d7e8f90'; + const lease = registry.putHostLease(leaseId, HUMAN_CONTROL_LEASE_REQUEST); + now = lease.expiresAt; + const expired = registry.consumeExpiredLease(leaseId); + assert.ok(expired); + const reservation = beforeReservation.then(() => registry.reserveExpiredLease(expired)); + + const reissued = registry.putHostLease(leaseId, HUMAN_CONTROL_LEASE_REQUEST); + const work = registry.retainLeaseWork(reissued, () => true); + now += 1; + work.release(); + expect(registry.inspectActiveLease(leaseId)?.heartbeatAt).toBe(now); + resume(); + + const reserved = await reservation; + expect(registry.releaseLease({ ...HUMAN_CONTROL_LEASE_REQUEST, leaseId }).released).toBe(true); + expect(registry.allocateLease(HUMAN_CONTROL_LEASE_REQUEST).leaseId).not.toBe(leaseId); + expect(reserved).toBe(false); +}); diff --git a/packages/daemon/src/resources/lease-in-flight-work.ts b/packages/daemon/src/resources/lease-in-flight-work.ts index 49e9a6afd0..241fda972c 100644 --- a/packages/daemon/src/resources/lease-in-flight-work.ts +++ b/packages/daemon/src/resources/lease-in-flight-work.ts @@ -14,8 +14,6 @@ export type LeaseWorkWanted = () => boolean; /** A claim on one leased device for the duration of one admitted request's work. */ export type LeaseWorkPass = Readonly<{ leaseId: string; - /** Whether this pass is still registered for its original lease. */ - isRetained(): boolean; /** * Ends the pass. Reports whether the work was still wanted when it ended, which * is what entitles it to renew the lease it just worked on. @@ -43,7 +41,6 @@ export class LeaseInFlightWorkRegistry { this.entriesByLeaseId.set(leaseId, entries); return { leaseId, - isRetained: () => !entry.released && entries.has(entry), release: () => this.releasePass(leaseId, entries, entry), }; } diff --git a/packages/daemon/src/resources/lease-registry-scope.ts b/packages/daemon/src/resources/lease-registry-scope.ts index 1a57ea2ea1..39758650b2 100644 --- a/packages/daemon/src/resources/lease-registry-scope.ts +++ b/packages/daemon/src/resources/lease-registry-scope.ts @@ -393,15 +393,33 @@ export function leaseOwnTtlMs(lease: Pick & { - /** Refuses a released pass, even if the host reused its lease id. */ - assertRetained(): void; -}; - function requireActiveLease(lease: DeviceLease | undefined): DeviceLease { if (lease) return lease; throw new AppError('UNAUTHORIZED', 'Lease is not active', { @@ -70,6 +65,15 @@ export class LeaseRegistry { private readonly mutations = new DeviceMutationDrain(); private readonly inFlightWork = new LeaseInFlightWorkRegistry(); private readonly leases = new Map(); + private readonly ending = new Map< + string, + { + lease: DeviceLease; + sessionsSettled: boolean; + providerRelease: 'pending' | 'confirmed' | 'unknown'; + providerEnded?: true; + } + >(); /** * Every id this daemon has given a lease. Provider release retries and provider-session ownership * stay keyed by a lease id after the lease ends, so a caller-chosen id must never name one again. @@ -142,10 +146,13 @@ export class LeaseRegistry { this.hostTtlMsByLeaseId.set(id, leaseTtlMs); return this.refreshLease(existing, leaseTtlMs); } + this.assertNoEndingLease(id); this.assertHumanControlAdmission(normalized); this.assertDeviceAvailable(normalized); if (normalized.backend === 'macos-app') this.macOsAppTenantIds.add(normalized.tenantId); - if (this.runBindings.has(leaseRunBindingKey(normalized))) { + const runBinding = this.runBindings.get(leaseRunBindingKey(normalized)); + this.assertNoEndingLease(runBinding); + if (runBinding) { throw new AppError('DEVICE_IN_USE', 'This tenant run already holds a lease for the device.', { reason: DEVICE_LEASE_REASONS.busy.reason, }); @@ -190,8 +197,9 @@ export class LeaseRegistry { const scope = { ...request, deviceKey: request.deviceKey ?? lease.deviceKey }; if (!hasAllocatedScope(lease, scope)) return undefined; this.assertHumanControlAdmission(lease); + if (request.retainOnClose) lease.retainOnClose = true; return this.refreshLease( - request.retainOnClose ? { ...lease, retainOnClose: true } : lease, + lease, request.ttlMs === undefined ? leaseOwnTtlMs(lease) : leaseTtlMs, ); } @@ -223,6 +231,7 @@ export class LeaseRegistry { const bindingKey = leaseRunBindingKey(request); const existingId = this.runBindings.get(bindingKey); if (!existingId) return; + this.assertNoEndingLease(existingId); const existingLease = this.leases.get(existingId); if (!existingLease) { this.runBindings.delete(bindingKey); @@ -263,13 +272,10 @@ export class LeaseRegistry { * human-control hold does; a pass whose request was cancelled protects nothing. * `wanted` is how the caller reports that its client is still waiting. */ - retainLeaseWork(lease: Pick, wanted: LeaseWorkWanted): RetainedLeaseWork { + retainLeaseWork(lease: Pick, wanted: LeaseWorkWanted): LeaseWorkPass { const pass = this.inFlightWork.retain(lease.leaseId, wanted); return { leaseId: pass.leaseId, - assertRetained: () => { - requireActiveLease(pass.isRetained() ? this.leases.get(pass.leaseId) : undefined); - }, release: () => { const renewed = pass.release(); if (renewed) this.refreshProtectedLease(lease.leaseId, this.now()); @@ -290,14 +296,27 @@ export class LeaseRegistry { return { released: true, lease }; } - endProviderLease(request: ReleaseLeaseRequest): void { - const lease = this.getLease(request); - if (!lease) return; - this.leases.delete(lease.leaseId); - this.unbindLease(lease); - this.inFlightWork.forget(lease.leaseId); - this.onLeaseExpired?.(lease, 'PROVIDER_INSTANCE_ENDED'); - this.reportProviderLeases(lease); + /** Captures a heartbeat's issuance so its end result can also confirm a lease the sweep took. */ + pinProviderLeaseEnd(leaseId: string): () => boolean { + const lease = this.leases.get(leaseId); + return () => { + if (!lease) return false; + const active = this.leases.get(leaseId) === lease; + if (active) { + this.leases.delete(leaseId); + this.unbindLease(lease); + this.inFlightWork.forget(leaseId); + this.onLeaseExpired?.(lease, 'PROVIDER_INSTANCE_ENDED'); + this.reportProviderLeases(lease); + } + const end = this.ending.get(leaseId); + if (end?.lease === lease) end.providerEnded = true; + return active; + }; + } + + providerInstanceEnded(leaseId: string): boolean { + return this.ending.get(leaseId)?.providerEnded === true; } /** @@ -336,12 +355,6 @@ export class LeaseRegistry { return this.checkLeaseAdmission(request).lease; } - /** Renews a successor before its request tears down the incumbent session. */ - renewInspectedLeaseAdmission(request: HeartbeatLeaseRequest): DeviceLease { - const { lease, ttlMs } = this.checkLeaseAdmission(request); - return this.refreshLease(lease, ttlMs); - } - private checkLeaseAdmission(request: HeartbeatLeaseRequest): { lease: DeviceLease; ttlMs: number; @@ -362,6 +375,13 @@ export class LeaseRegistry { return this.inspectActiveLease(leaseId)?.backend; } + /** Checks the same issuance after a wait without renewing it. */ + pinActiveLease(leaseId: string): () => boolean { + const lease = this.leases.get(leaseId); + return () => + this.leases.get(leaseId) === lease && this.inspectActiveLease(leaseId) !== undefined; + } + /** Read an active lease without sweeping another lease or mutating owner state. */ inspectActiveLease(leaseId: string): DeviceLease | undefined { const id = normalizeLeaseId(leaseId); @@ -659,19 +679,16 @@ export class LeaseRegistry { if (this.isLeaseProtected(lease, now)) continue; this.leases.delete(lease.leaseId); this.unbindLease(lease, lease.expiresAt); - const expiredLease = { ...lease }; - expired.push(expiredLease); - this.onLeaseExpired?.(expiredLease); - this.reportProviderLeases(expiredLease); + expired.push({ ...lease }); + this.onLeaseExpired?.(lease); + this.reportProviderLeases(lease); } return expired; } - consumeExpiredLease(leaseId: string, beforeConsume?: () => void): DeviceLease | undefined { + consumeExpiredLease(leaseId: string): DeviceLease | undefined { const normalizedLeaseId = normalizeLeaseId(leaseId); - const lease = normalizedLeaseId ? this.leases.get(normalizedLeaseId) : undefined; const now = this.now(); - if (lease && beforeConsume && this.wouldConsumeExpiredLease(lease, now)) beforeConsume(); this.expireHumanControlHolds(now); if (!normalizedLeaseId) return undefined; const currentLease = this.leases.get(normalizedLeaseId); @@ -680,10 +697,9 @@ export class LeaseRegistry { } this.leases.delete(currentLease.leaseId); this.unbindLease(currentLease, currentLease.expiresAt); - const expiredLease = { ...currentLease }; - this.onLeaseExpired?.(expiredLease); - this.reportProviderLeases(expiredLease); - return expiredLease; + this.onLeaseExpired?.(currentLease); + this.reportProviderLeases(currentLease); + return { ...currentLease }; } private cleanupExpiredLeases(): void { @@ -713,14 +729,10 @@ export class LeaseRegistry { /** Every renewal route ends here, so a host-pinned lease never outlives the host's window. */ private refreshLease(lease: DeviceLease, ttlMs: number, now = this.now()): DeviceLease { const hostTtlMs = this.hostTtlMsByLeaseId.get(lease.leaseId); - const updated: DeviceLease = { - ...lease, - heartbeatAt: now, - expiresAt: now + (hostTtlMs === undefined ? ttlMs : Math.min(ttlMs, hostTtlMs)), - }; - this.leases.set(updated.leaseId, updated); - this.bindLease(updated); - return { ...updated }; + lease.heartbeatAt = now; + lease.expiresAt = now + (hostTtlMs === undefined ? ttlMs : Math.min(ttlMs, hostTtlMs)); + this.bindLease(lease); + return { ...lease }; } private bindLease(lease: DeviceLease): void { @@ -741,6 +753,40 @@ export class LeaseRegistry { this.providerSessionOwnership.markLeaseReleased(lease, releasedAt); } + reserveExpiredLease(lease: DeviceLease, sessionsSettled = false): boolean { + if (this.leases.has(lease.leaseId)) return false; + this.issuedLeaseIds.add(lease.leaseId); + this.runBindings.set(leaseRunBindingKey(lease), lease.leaseId); + this.ending.set(lease.leaseId, { + lease, + sessionsSettled, + providerRelease: lease.leaseProvider ? 'pending' : 'confirmed', + }); + return true; + } + + markExpiredProviderReleaseUnknown(leaseId: string): void { + const end = this.ending.get(leaseId); + if (end?.providerRelease === 'pending') end.providerRelease = 'unknown'; + } + + confirmExpiredLeaseEnd(leaseId: string, part: 'sessionsSettled' | 'providerReleased'): boolean { + const end = this.ending.get(leaseId); + if (!end) return true; + if (part === 'providerReleased') end.providerRelease = 'confirmed'; + else end.sessionsSettled = true; + if (!end.sessionsSettled || end.providerRelease !== 'confirmed') return false; + const binding = leaseRunBindingKey(end.lease); + if (this.runBindings.get(binding) === leaseId) this.runBindings.delete(binding); + this.ending.delete(leaseId); + return true; + } + + private assertNoEndingLease(leaseId: string | undefined): void { + const end = leaseId && this.ending.get(leaseId); + if (end) throw deviceLeaseBusyError(end.lease, end.providerRelease === 'unknown'); + } + private assertDeviceAvailable(params: { backend: LeaseBackend; leaseProvider?: string; @@ -752,6 +798,10 @@ export class LeaseRegistry { deviceKey: params.deviceKey, }); if (!deviceBindingKey) return; + for (const { lease, providerRelease } of this.ending.values()) { + if (leaseDeviceBindingKey(lease) === deviceBindingKey) + throw deviceLeaseBusyError(lease, providerRelease === 'unknown'); + } const activeLeaseId = this.deviceBindings.get(deviceBindingKey); if (!activeLeaseId) return; const activeLease = this.leases.get(activeLeaseId); diff --git a/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts b/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts index 9a91a8d574..113df94a44 100644 --- a/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts +++ b/packages/daemon/src/server/__tests__/request-execution-scope-lease-expiry.test.ts @@ -1,3 +1,4 @@ +import { createLeaseSessionEnd } from '../lease-session-end.ts'; import { expect, test, vi } from 'vitest'; import { daemonPlatformServicesFixture, @@ -11,7 +12,10 @@ import { } from '@agent-device/test-kit'; import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; -import { createRequestExecutionScope } from '../request-execution-scope.ts'; +import { + getLeaseRegistryExecutionLocks, + createRequestExecutionScope, +} from '../request-execution-scope.ts'; import { teardownSessionResources } from '../../sessions/session-teardown.ts'; import type { DaemonRequest } from '../../core/daemon-request.ts'; import { @@ -32,56 +36,19 @@ function makeRequest(overrides: Partial): DaemonRequest { }; } -test('expired leases remove owned sessions before the next command and free capacity', async () => { - let now = 1_000; - const sessionStore = makeSessionStore('agent-device-request-scope-'); - const leaseRegistry = new LeaseRegistry({ - maxActiveSimulatorLeases: 1, - defaultLeaseTtlMs: 10, - minLeaseTtlMs: 1, - now: () => now, - }); - const lease = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' }); - sessionStore.publish( - 'default', - makeSession('default', { - device: LINUX_DEVICE, - lease: { - leaseId: lease.leaseId, - tenantId: lease.tenantId, - runId: lease.runId, - backend: lease.backend, - leaseProvider: 'proxy', - deviceKey: 'ios:SIM-001', - }, - }), - ); - now = 1_011; - - const scope = await createRequestExecutionScope({ - host: createTestHostEnvironment(), - platformServices: daemonPlatformServicesFixture(), - claimRecoveryGateway: daemonClaimRecoveryGatewayFixture(), - trackClaimRecoveryDisposal: () => {}, - deviceRuntimeGateway: unavailableDeviceRuntimeGateway, - platformRequestScope: platformRequestScopeFixture(), - req: makeRequest({ command: 'snapshot', meta: { leaseId: lease.leaseId } }), - sessionStore, - leaseRegistry, - }); - await scope.runLocked(async () => 'ran'); - - expect(sessionStore.get('default')).toBeUndefined(); - const nextLease = leaseRegistry.allocateLease({ tenantId: 'tenant-b', runId: 'run-2' }); - expect(nextLease.tenantId).toBe('tenant-b'); -}); - test.each(['rebuild', 'retire'] as const)( 'scoped lease expiry preserves a public-name session and a %s during held teardown', async (change) => { let now = 1_000; const store = makeSessionStore('request-scope-lease-lifetime-'); - const leases = new LeaseRegistry({ defaultLeaseTtlMs: 10, minLeaseTtlMs: 1, now: () => now }); + const leases = new LeaseRegistry({ + defaultLeaseTtlMs: 10, + minLeaseTtlMs: 1, + now: () => now, + onLeaseExpired: (ended) => { + void leaseSessionEnd.end(ended.leaseId, 'LEASE_EXPIRED'); + }, + }); const lease = leases.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' }); const address = 'cwd:ownership:default'; const original = store.publish( @@ -117,6 +84,24 @@ test.each(['rebuild', 'retire'] as const)( await release; }); now = 1_011; + const leaseSessionEnd = createLeaseSessionEnd({ + env: {}, + sessionStore: store, + executionLocks: getLeaseRegistryExecutionLocks(leases), + cleanupSessionlessExecutionHost: async () => {}, + teardownSession: async (ref) => + await teardownSessionResources({ + appLog: 'run', + ref, + sessionStore: store, + platformCleanup: { + stopSnapshotHelper, + closeManagedBrowser: async () => {}, + cleanupSessionlessExecutionHost: async () => {}, + retainExecutionHostAfterClose: () => false, + }, + }), + }); const scope = await createRequestExecutionScope({ host: createTestHostEnvironment(), platformServices: daemonPlatformServicesFixture(), @@ -131,21 +116,12 @@ test.each(['rebuild', 'retire'] as const)( }), sessionStore: store, leaseRegistry: leases, - settleExpiredSession: async (ref) => - await teardownSessionResources({ - appLog: 'run', - ref, - sessionStore: store, - platformCleanup: { - stopSnapshotHelper, - closeManagedBrowser: async () => {}, - cleanupSessionlessExecutionHost: async () => {}, - retainExecutionHostAfterClose: () => false, - }, - }), + leaseSessionEnd, }); expect(scope.sessionName).toBe(address); - const running = scope.runLocked(async () => 'ran'); + const running = expect(scope.runLocked(async () => 'ran')).rejects.toMatchObject({ + details: { reason: 'LEASE_NOT_FOUND' }, + }); await entered; let successor: ReturnType | undefined; if (change === 'retire') { @@ -159,7 +135,7 @@ test.each(['rebuild', 'retire'] as const)( ); } else store.update(original, { appName: 'latest' }); resume(); - await expect(running).resolves.toBe('ran'); + await running; expect(stopSnapshotHelper).toHaveBeenCalledExactlyOnceWith(original.session.device); expect(store.requireCurrent(decoy)).toBe(decoy.session); if (successor) expect(store.requireCurrent(successor)).toBe(successor.session); diff --git a/packages/daemon/src/server/__tests__/request-execution-scope-lease-session-end.test.ts b/packages/daemon/src/server/__tests__/request-execution-scope-lease-session-end.test.ts index 992594c611..0f0edafb88 100644 --- a/packages/daemon/src/server/__tests__/request-execution-scope-lease-session-end.test.ts +++ b/packages/daemon/src/server/__tests__/request-execution-scope-lease-session-end.test.ts @@ -17,8 +17,11 @@ import { existingSessionExecutionLockKeys } from '../request-binding.ts'; import { withRequestExecutionLockKeys } from '../request-execution-locks.ts'; import type { SessionStore } from '../../core/session-store.ts'; import type { PlatformResourceCleanup } from '../../core/platform-resource-cleanup.ts'; +import { platformResourceCleanupFixture } from '../../__tests__/support/platform-resource-cleanup-fixture.ts'; import type { SessionTeardown } from '../../sessions/lease-lifecycle.ts'; -import { createLeaseSessionEnd } from '../request-execution-scope.ts'; +import { settleExpiredSession } from '../../sessions/session-teardown.ts'; +import { createLeaseSessionEnd, EXPIRY_TRANSITIONS } from '../lease-session-end.ts'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; bindTestCommandHost(); @@ -36,7 +39,13 @@ async function publishLeasedSession( ): Promise { const { stateDir } = claimStores(); const session = makeIosSession(name, { - lease: { backend: 'ios-simulator', leaseId, tenantId: 'tenant-a', runId: 'run-1' }, + lease: { + backend: 'ios-simulator', + leaseId, + tenantId: 'tenant-a', + runId: 'run-1', + deviceKey: 'ios:simulator:fixture', + }, }); const acquired = await acquireDeviceClaim({ env: process.env, @@ -84,6 +93,7 @@ function leaseSessionEnd( executionLocks, teardownSession, cleanupSessionlessExecutionHost, + withinDiagnosticsScope: (run) => run(), }), }; } @@ -356,28 +366,41 @@ test('end publishes the recorded script of the session it ends', async () => { expect(fs.readFileSync(scriptPath, 'utf8')).toMatch(/recorded-step/); }); -test('end tears down the session opened under the lease and clears its device claim', async () => { - const sessionStore = makeSessionStore('agent-device-lease-end-'); - const claimPath = await publishLeasedSession(sessionStore, 'leased', 'lease-1'); - sessionStore.publish( - 'other', - makeIosSession('other', { - lease: { backend: 'ios-simulator', leaseId: 'lease-2', tenantId: 'tenant-b', runId: 'run-2' }, - }), - ); - expect(fs.existsSync(claimPath)).toBe(true); - const teardownSession = vi.fn(async () => {}); - - await leaseSessionEnd(sessionStore, teardownSession).ender.end('lease-1', 'LEASE_RELEASED'); - - expect(teardownSession).toHaveBeenCalledTimes(1); - expect(teardownSession).toHaveBeenCalledWith(expect.objectContaining({ address: 'leased' })); - expect(sessionStore.get('leased')).toBeUndefined(); - expect(fs.existsSync(claimPath)).toBe(false); - expect(sessionStore.get('other')).toBeDefined(); -}); +test.each(['LEASE_RELEASED', 'PROVIDER_INSTANCE_ENDED', 'LEASE_EXPIRED'] as const)( + '%s logs and tears down its session and clears its device claim', + async (reason) => { + vi.mocked(emitDiagnostic).mockClear(); + const sessionStore = makeSessionStore('agent-device-lease-end-'); + const claimPath = await publishLeasedSession(sessionStore, 'leased', 'lease-1'); + sessionStore.publish( + 'other', + makeIosSession('other', { + lease: { + backend: 'ios-simulator', + leaseId: 'lease-2', + tenantId: 'tenant-b', + runId: 'run-2', + }, + }), + ); + expect(fs.existsSync(claimPath)).toBe(true); + const teardownSession = vi.fn(async () => {}); + + await leaseSessionEnd(sessionStore, teardownSession).ender.end('lease-1', reason); + + expect(teardownSession).toHaveBeenCalledTimes(1); + expect(teardownSession.mock.lastCall?.[0].address).toBe('leased'); + expect(sessionStore.get('leased')).toBeUndefined(); + expect(fs.existsSync(claimPath)).toBe(false); + expect(sessionStore.get('other')).toBeDefined(); + expect(emitDiagnostic).toHaveBeenCalledWith({ + phase: 'leased_session_ended', + data: { reason, session: 'leased', deviceKey: 'ios:simulator:fixture', leaseId: 'lease-1' }, + }); + }, +); -test('end clears the claim of a session whose device no longer answers', async () => { +test('end keeps the claim of a session whose teardown failed', async () => { const sessionStore = makeSessionStore('agent-device-lease-end-unreachable-'); const claimPath = await publishLeasedSession(sessionStore, 'leased', 'lease-1'); @@ -385,8 +408,144 @@ test('end clears the claim of a session whose device no longer answers', async ( throw new Error('device unreachable'); }).ender.end('lease-1', 'LEASE_EXPIRED'); - expect(sessionStore.get('leased')).toBeUndefined(); - expect(fs.existsSync(claimPath)).toBe(false); + expect(sessionStore.get('leased')).toBeDefined(); + expect(fs.existsSync(claimPath)).toBe(true); +}); + +test('a confirmed provider end keeps the claim when independent cleanup fails', async () => { + vi.mocked(emitDiagnostic).mockClear(); + const clock = vi.spyOn(Date, 'now').mockReturnValue(1_000); + try { + const sessionStore = makeSessionStore(); + const claimPath = await publishLeasedSession(sessionStore, 'leased', 'lease-1'); + const stopSnapshotHelper = vi + .fn(async () => {}) + .mockRejectedValueOnce(new Error('snapshot helper stop failed')); + const teardown: SessionTeardown = (ref) => + settleExpiredSession({ + ref, + sessionStore, + appLog: 'run', + platformCleanup: platformResourceCleanupFixture({ stopSnapshotHelper }), + finalizeApplication: async () => {}, + }); + const { ender } = leaseSessionEnd(sessionStore, teardown); + + await ender.end('lease-1', 'PROVIDER_INSTANCE_ENDED'); + expect(Boolean(sessionStore.get('leased'))).toBe(true); + expect(fs.existsSync(claimPath)).toBe(true); + expect(emitDiagnostic).toHaveBeenCalledWith({ + level: 'warn', + phase: 'leased_session_ended', + data: { + reason: 'PROVIDER_INSTANCE_ENDED', + session: 'leased', + deviceKey: 'ios:simulator:fixture', + leaseId: 'lease-1', + failedSteps: ['platform_snapshot_helper'], + error: expect.stringContaining('snapshot helper stop failed'), + }, + }); + clock.mockReturnValue(11_000); + await ender.retryPending(); + expect(stopSnapshotHelper).toHaveBeenCalledTimes(2); + expect(Boolean(sessionStore.get('leased'))).toBe(false); + expect(fs.existsSync(claimPath)).toBe(false); + } finally { + clock.mockRestore(); + } +}); + +test.each([ + { firstAttemptFails: false, events: ['expired', 'settled'] }, + { firstAttemptFails: true, events: ['expired', 'incomplete', 'retry', 'settled'] }, +] as const)( + 'expiry logs each transition with cause when the first attempt fails=$firstAttemptFails', + async ({ firstAttemptFails, events }) => { + vi.mocked(emitDiagnostic).mockClear(); + const clock = vi.spyOn(Date, 'now').mockReturnValue(1_000); + try { + const store = makeSessionStore(); + await publishLeasedSession(store, 'leased', 'lease-1'); + const teardown = vi.fn(async () => {}); + if (firstAttemptFails) teardown.mockRejectedValueOnce(new Error('teardown unavailable')); + const { ender } = leaseSessionEnd(store, teardown); + await ender.end('lease-1', 'LEASE_EXPIRED'); + clock.mockReturnValue(11_000); + await ender.retryPending(); + + expect(store.get('leased')).toBeUndefined(); + expect(teardown).toHaveBeenCalledTimes(firstAttemptFails ? 2 : 1); + const transitions = vi + .mocked(emitDiagnostic) + .mock.calls.map(([event]) => event) + .filter(({ phase }) => phase === 'lease_expiry_transition'); + expect(transitions.map(({ data }) => data)).toEqual( + events.map((event) => { + const [oldState, newState] = EXPIRY_TRANSITIONS[event]; + return { + actor: 'daemon', + event, + oldState, + newState, + cause: 'LEASE_EXPIRED', + session: 'leased', + deviceKey: 'ios:simulator:fixture', + leaseId: 'lease-1', + }; + }), + ); + } finally { + clock.mockRestore(); + } + }, +); + +test('provider release waits for a successful cleanup retry and the address stays reserved', async () => { + vi.mocked(emitDiagnostic).mockClear(); + const clock = vi.spyOn(Date, 'now').mockReturnValue(1_000); + try { + const store = makeSessionStore(); + await publishLeasedSession(store, 'leased', 'lease-1'); + const ref = store.lookup('leased')!; + const teardown = vi.fn(async () => {}).mockRejectedValueOnce(new Error('stop unconfirmed')); + let confirmed = false; + let finish!: () => void; + const done = new Promise((resolve) => { + finish = resolve; + }); + const allowRelease = vi.fn(); + const ender = createLeaseSessionEnd({ + env: store.host.env, + sessionStore: store, + executionLocks: new Map(), + teardownSession: teardown, + cleanupSessionlessExecutionHost: async () => {}, + confirmExpiredSessions: () => confirmed, + }); + + await ender.end('lease-1', 'LEASE_EXPIRED', { done, allowRelease }); + expect(await ender.settlementFor(ref.lifetime)?.done).toBe(false); + expect(allowRelease).not.toHaveBeenCalled(); + expect(ender.closingAt(ref.address)?.lifetime).toBe(ref.lifetime); + + clock.mockReturnValue(11_000); + await ender.retryPending(); + expect(allowRelease).toHaveBeenCalledOnce(); + expect(teardown).toHaveBeenCalledTimes(2); + expect(store.lookup(ref.address)).toBeUndefined(); + expect(ender.closingAt(ref.address)?.lifetime).toBe(ref.lifetime); + + confirmed = true; + finish(); + expect(await ender.settlementFor(ref.lifetime)?.done).toBe(true); + expect(ender.closingAt(ref.address)).toBeUndefined(); + expect(emitDiagnostic).not.toHaveBeenCalledWith( + expect.objectContaining({ data: expect.objectContaining({ leaseId: 'lease-1' }) }), + ); + } finally { + clock.mockRestore(); + } }); test('end waits for the command still holding the session execution locks', async () => { diff --git a/packages/daemon/src/server/__tests__/request-execution-scope.test.ts b/packages/daemon/src/server/__tests__/request-execution-scope.test.ts index b1415051be..3a5a8f57f8 100644 --- a/packages/daemon/src/server/__tests__/request-execution-scope.test.ts +++ b/packages/daemon/src/server/__tests__/request-execution-scope.test.ts @@ -1,3 +1,4 @@ +import { createLeaseSessionEnd } from '../lease-session-end.ts'; import { resolveSessionRequestLogPath } from '@agent-device/daemon-contracts/session-artifact-paths'; import { daemonPlatformServicesFixture, @@ -17,6 +18,7 @@ import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { clearRequestCanceled, markRequestCanceled } from '@agent-device/host-kit/request'; import { createRequestExecutionScope, + getLeaseRegistryExecutionLocks, prepareLockedRequestScope, } from '../request-execution-scope.ts'; import { resolveSessionScope } from '../../sessions/session-routing.ts'; @@ -555,6 +557,18 @@ test('expired leased session cleanup waits for the request execution lock', asyn defaultLeaseTtlMs: 10, minLeaseTtlMs: 1, now: () => now, + onLeaseExpired: (lease) => { + void leaseSessionEnd.end(lease.leaseId, 'LEASE_EXPIRED'); + }, + }); + let firstFinished = false; + const teardown = vi.fn(async () => expect(firstFinished).toBe(true)); + const leaseSessionEnd = createLeaseSessionEnd({ + env: sessionStore.host.env, + executionLocks: getLeaseRegistryExecutionLocks(leaseRegistry), + sessionStore, + teardownSession: teardown, + cleanupSessionlessExecutionHost: async () => {}, }); const lease = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' }); sessionStore.publish( @@ -577,6 +591,7 @@ test('expired leased session cleanup waits for the request execution lock', asyn req: makeRequest({ command: 'click', meta: { leaseId: lease.leaseId } }), sessionStore, leaseRegistry, + leaseSessionEnd, }); let releaseFirst: () => void = () => {}; @@ -598,16 +613,24 @@ test('expired leased session cleanup waits for the request execution lock', asyn markRequestCanceled(requestId); now = 1_011; - const secondRun = second.runLocked(async () => 'second'); - await new Promise((resolve) => setTimeout(resolve, 20)); - expect(sessionStore.get('default')).toBeDefined(); + expect(leaseRegistry.consumeExpiredLeases()).toMatchObject([{ leaseId: lease.leaseId }]); + const dispatch = vi.fn(async () => 'second'); + const refused = expect(second.runLocked(dispatch)).rejects.toMatchObject({ + details: { reason: 'LEASE_NOT_FOUND' }, + }); try { + await Promise.resolve(); + expect(teardown).not.toHaveBeenCalled(); + firstFinished = true; releaseFirst(); await firstRun; - await expect(secondRun).resolves.toBe('second'); + await refused; + expect(dispatch).not.toHaveBeenCalled(); + expect(teardown).toHaveBeenCalledOnce(); expect(sessionStore.get('default')).toBeUndefined(); } finally { + releaseFirst(); clearRequestCanceled(requestId); } }); diff --git a/packages/daemon/src/server/__tests__/request-router-open.test.ts b/packages/daemon/src/server/__tests__/request-router-open.test.ts index 4a26a39f1d..1af33d21ad 100644 --- a/packages/daemon/src/server/__tests__/request-router-open.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-open.test.ts @@ -229,7 +229,7 @@ test('fresh macOS replay locks only the app device it opens first, so other apps meta: { cwd: root }, }, sessionName: 'fresh-macos-replay', - sessionStore: makeSessionStore('agent-device-router-replay-macos-lock-'), + env: makeSessionStore('agent-device-router-replay-macos-lock-').host.env, }); // A replay holds these for its whole run; holding the host too would hold every other app's @@ -266,7 +266,7 @@ test('fresh replay reserves its authored app simulator before any replay step', meta: { cwd: root }, }), sessionName: 'fresh-replay', - sessionStore, + env: sessionStore.host.env, }); expect(keys).toEqual(['session:fresh-replay', 'device:SIM-WITH-APP']); @@ -297,7 +297,7 @@ test('a fresh open of an app device locks its host too, so opens on one Mac run flags: { platform: 'macos', ...(surface ? { surface } : {}) }, }, sessionName: 'fresh-app', - sessionStore, + env: sessionStore.host.env, }); expect((await plan(['com.example.one'])).keys).toEqual([ @@ -330,7 +330,7 @@ test('fresh replay leaves a first deep-link open unbound when a later app target meta: { cwd: root }, }, sessionName: 'fresh-replay-deep-link', - sessionStore, + env: sessionStore.host.env, }); expect(keys).toEqual(['session:fresh-replay-deep-link']); @@ -358,7 +358,7 @@ test('fresh replay preserves an authored Android platform before advisory lockin meta: { cwd: root }, }, sessionName: 'fresh-replay-android', - sessionStore, + env: sessionStore.host.env, }); expect(keys).toEqual(['session:fresh-replay-android', 'device:ANDROID-EMULATOR']); @@ -899,7 +899,7 @@ test('web sessions open side by side on one host, each holding a device of its o openRequest('web-a', { platform: 'web' }, 'req-plan-web-a', {}, ['about:blank']), ), sessionName: 'web-a', - sessionStore, + env: sessionStore.host.env, }); expect(keys).toEqual(['session:web-a', `device:${WEB_DESKTOP_DEVICE.id}:session:p_web-a`]); diff --git a/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts b/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts index a5833ede2b..4d79e2c4ad 100644 --- a/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-web-sessions.test.ts @@ -88,7 +88,7 @@ test.each(['batch', 'replay'] as const)( // directly, so it states the fact the scope would have added. req: seedWebSessionIdentity(freshWebRequest(command, name, replayPath)), sessionName: name, - sessionStore, + env: sessionStore.host.env, }); expect(keys).toEqual([ `session:${name}`, @@ -496,7 +496,7 @@ test('a sessionless web command locks the implicit default session device it bin const plan = await resolveRequestExecutionLockPlan({ req, sessionName: req.session, - sessionStore, + env: sessionStore.host.env, }); const bound = await resolveCommandDevice({ session: undefined, diff --git a/packages/daemon/src/server/application-lifecycle-recovery.ts b/packages/daemon/src/server/application-lifecycle-recovery.ts index 88f72cb141..8a3b7a9807 100644 --- a/packages/daemon/src/server/application-lifecycle-recovery.ts +++ b/packages/daemon/src/server/application-lifecycle-recovery.ts @@ -26,6 +26,7 @@ type SessionFinalization = Readonly<{ session: SessionState; stateDir: string; runtimeHints: RuntimeHintsApplicationInput; + onRuntimeHintsCleared?: () => void; daemonShutdown?: boolean; }>; @@ -46,6 +47,7 @@ async function finalizeSessionApplicationLifecycle(params: SessionFinalization): const runtime = await bind(session.device, use); await runtime.operations.finalizeApplicationClose(input); await runtime.operations.clearRuntimeHints(runtimeHints); + params.onRuntimeHintsCleared?.(); } /** @@ -66,6 +68,7 @@ export async function finalizeDaemonSessionApplicationLifecycle(params: { stateDir: string; /** The stored hints to clear and the app they are bound to, else the session's app. */ runtimeHints: RuntimeHintsApplicationInput; + onRuntimeHintsCleared?: () => void; daemonLeaving?: boolean; }): Promise { const { gateway, scope, session, stateDir, runtimeHints } = params; @@ -81,6 +84,7 @@ export async function finalizeDaemonSessionApplicationLifecycle(params: { session, stateDir, runtimeHints, + onRuntimeHintsCleared: params.onRuntimeHintsCleared, ...(params.daemonLeaving === false ? {} : { daemonShutdown: true }), }); } catch (operationError) { diff --git a/packages/daemon/src/server/http/daemon-runtime-lease-expiry.test.ts b/packages/daemon/src/server/http/daemon-runtime-lease-expiry.test.ts index 2267894580..f461057f4d 100644 --- a/packages/daemon/src/server/http/daemon-runtime-lease-expiry.test.ts +++ b/packages/daemon/src/server/http/daemon-runtime-lease-expiry.test.ts @@ -1,14 +1,31 @@ +import { AppError } from '@agent-device/kernel/errors'; import assert from 'node:assert/strict'; import fs from 'node:fs'; -import { afterEach, test, vi } from 'vitest'; +import { afterEach, expect, test, vi } from 'vitest'; import type { DeviceLease } from '@agent-device/contracts/device'; +import { readDaemonShutdownReport } from '@agent-device/daemon-contracts/daemon-shutdown-report'; +import { LEASE_REASONS } from '@agent-device/contracts/lease-scope'; +import { providerRuntimeOwner } from '@agent-device/contracts/platform-runtime'; const leaseProbe = vi.hoisted(() => ({ registries: [] as import('../../resources/lease-registry.ts').LeaseRegistry[], ended: [] as Array<[string, string]>, retryCalls: 0, shutdownSteps: [] as string[], + store: undefined as import('../../core/session-store.ts').SessionStore | undefined, })); +vi.mock('../../core/session-store.ts', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + SessionStore: class extends actual.SessionStore { + constructor(...args: ConstructorParameters) { + super(...args); + leaseProbe.store = this; + } + }, + }; +}); vi.mock('../../resources/lease-registry.ts', async (importOriginal) => { const actual = await importOriginal(); class RecordedLeaseRegistry extends actual.LeaseRegistry { @@ -19,29 +36,47 @@ vi.mock('../../resources/lease-registry.ts', async (importOriginal) => { } return { ...actual, LeaseRegistry: RecordedLeaseRegistry }; }); -vi.mock('../request-execution-scope.ts', async (importOriginal) => { - const actual = await importOriginal(); +vi.mock('../lease-session-end.ts', async (importOriginal) => { + const actual = await importOriginal(); return { ...actual, - createLeaseSessionEnd: () => ({ - end: async (leaseId: string, reason: string) => { - leaseProbe.ended.push([leaseId, reason]); - }, - retryPending: async () => { - leaseProbe.retryCalls += 1; - }, - cancel: () => { - leaseProbe.shutdownSteps.push('cancel'); - }, - drain: async () => { - leaseProbe.shutdownSteps.push('drain'); - }, - }), + createLeaseSessionEnd: (options: Parameters[0]) => { + const ender = actual.createLeaseSessionEnd(options); + return { + ...ender, + end: async (...args) => { + leaseProbe.ended.push([args[0], args[1]]); + await ender.end(...args); + }, + retryPending: async () => { + leaseProbe.retryCalls += 1; + await ender.retryPending(); + }, + cancel: () => { + leaseProbe.shutdownSteps.push('cancel'); + ender.cancel(); + }, + drain: async () => { + leaseProbe.shutdownSteps.push('drain'); + await ender.drain(); + }, + } satisfies import('../lease-session-end.ts').LeaseSessionEnd; + }, }; }); import { SessionStore } from '../../core/session-store.ts'; -import { daemonRuntimeDepsFixture } from '../../__tests__/support/daemon-runtime-deps-fixture.ts'; +import { + applicationLifecycleResourceFixture, + daemonRuntimeDepsFixture, +} from '../../__tests__/support/daemon-runtime-deps-fixture.ts'; +import { applicationLifecycleRuntimeFixture } from '../../__tests__/support/application-lifecycle-runtime-fixture.ts'; +import { createLifecycleDeviceRuntimeGatewaySpies } from '../../__tests__/support/test-device-runtime-gateway.ts'; +import { platformResourceCleanupFixture } from '../../__tests__/support/platform-resource-cleanup-fixture.ts'; +import { makeRecordingSession } from '../../__tests__/support/session-teardown.fixtures.ts'; +import { makeIosSession } from '../../__tests__/support/session-factories.ts'; +import type { DaemonRuntimeDeps } from './daemon-runtime-deps.ts'; +import type { RpcBody } from './http-server-session-lease-touch.fixtures.ts'; import { startDaemonRuntime } from './daemon-runtime.ts'; import { mkdtempForTestSync, createTestHostEnvironment } from '@agent-device/test-kit'; @@ -52,6 +87,321 @@ afterEach(() => { leaseProbe.ended.length = 0; leaseProbe.retryCalls = 0; leaseProbe.shutdownSteps.length = 0; + leaseProbe.store = undefined; +}); + +function barrier() { + let open!: () => void; + const reached = new Promise((resolve) => { + open = resolve; + }); + return { reached, open }; +} + +const providerLease = { + leaseProvider: 'limrun', + leaseBackend: 'ios-instance', + tenantId: 'tenant-a', + runId: 'run-1', + deviceKey: 'ios:mobile:fixture', + ttlMs: 100, +} as const; + +async function startProviderDaemon(deps: Partial) { + vi.useFakeTimers({ + toFake: ['Date', 'setInterval', 'clearInterval', 'setTimeout', 'clearTimeout'], + }); + const stateDir = mkdtempForTestSync('agent-device-provider-lease-end-'); + const runtime = await startDaemonRuntime({ + composeDeps: daemonRuntimeDepsFixture({ providerRuntimeIds: ['limrun'], ...deps }), + host: createTestHostEnvironment({ + env: { + ...process.env, + AGENT_DEVICE_STATE_DIR: stateDir, + AGENT_DEVICE_DAEMON_SERVER_MODE: 'http', + AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0', + AGENT_DEVICE_LEASE_MIN_TTL_MS: '1', + }, + }), + stderr: { write: () => {} }, + stdout: { write: () => {} }, + }); + assert.ok(runtime && leaseProbe.store && leaseProbe.registries[0]); + return { runtime, registry: leaseProbe.registries[0], store: leaseProbe.store, stateDir }; +} + +async function heartbeatEnded( + runtime: Awaited>['runtime'], + leaseId: string, +) { + const response = await fetch(`http://127.0.0.1:${runtime.httpPort}/rpc`, { + method: 'POST', + headers: { authorization: `Bearer ${runtime.token}`, 'content-type': 'application/json' }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 'heartbeat', + method: 'agent_device.lease.heartbeat', + params: { + session: 'leased', + leaseId, + leaseProvider: providerLease.leaseProvider, + deviceKey: providerLease.deviceKey, + backend: providerLease.leaseBackend, + tenantId: providerLease.tenantId, + runId: providerLease.runId, + }, + }), + }); + const result = (await response.json()) as RpcBody; + expect(result.error?.data?.details?.reason).toBe(LEASE_REASONS.instanceEnded.reason); +} + +function endedInstance(): AppError { + return new AppError('COMMAND_FAILED', 'Provider instance ended', { + reason: LEASE_REASONS.instanceEnded.reason, + }); +} + +async function closeProviderDaemon( + runtime: Awaited>['runtime'], +) { + const shutdown = runtime.close(); + await vi.advanceTimersByTimeAsync(30_000); + return await shutdown; +} + +test('a provider-ended heartbeat disposes its exact lease once and keeps the reservation until disposal', async () => { + const dispose = barrier(); + const release = vi.fn(async (_lease: DeviceLease) => { + await dispose.reached; + return undefined; + }); + const { runtime, registry } = await startProviderDaemon({ + leaseLifecycleProvider: { + heartbeat: async () => { + throw endedInstance(); + }, + release, + }, + }); + const lease = registry.allocateLease(providerLease); + const successor = { ...providerLease, runId: 'run-2' }; + try { + await heartbeatEnded(runtime, lease.leaseId); + await vi.advanceTimersByTimeAsync(0); + expect(release.mock.calls.map(([entry]) => entry.leaseId)).toEqual([lease.leaseId]); + expect(() => registry.allocateLease(successor)).toThrow( + expect.objectContaining({ code: 'DEVICE_IN_USE' }), + ); + dispose.open(); + await vi.advanceTimersByTimeAsync(0); + expect(registry.allocateLease(successor).leaseId).not.toBe(lease.leaseId); + } finally { + dispose.open(); + await closeProviderDaemon(runtime); + } +}); + +test.each([false, true])( + 'a late provider end prevents further recording calls with an in-flight finish=%s', + async (inFlight) => { + const entered = barrier(); + const reply = barrier(); + const stop = barrier(); + const release = vi.fn(async (_lease: DeviceLease) => undefined); + let localStopReady = false; + const { runtime, registry, store } = await startProviderDaemon({ + leaseLifecycleProvider: { + heartbeat: async () => { + entered.open(); + await reply.reached; + throw endedInstance(); + }, + release, + }, + platformResourceCleanup: platformResourceCleanupFixture({ + stopSnapshotHelper: async () => { + if (!localStopReady) throw new Error('local helper still active'); + }, + }), + }); + const lease = registry.allocateLease(providerLease); + const finish = vi.fn(async () => { + if (inFlight) await stop.reached; + throw new Error('provider recorder disconnected'); + }); + const forceCleanup = vi.fn(async () => { + throw new Error('provider recorder disconnected'); + }); + store.publish('leased', { + ...makeRecordingSession({ + name: 'leased', + sessionStore: store, + owner: providerRuntimeOwner('limrun', 'fixture'), + finish, + forceCleanup, + }), + lease, + }); + const heartbeat = heartbeatEnded(runtime, lease.leaseId); + try { + await Promise.race([entered.reached, heartbeat]); + await vi.advanceTimersByTimeAsync(1_000); + expect(finish).toHaveBeenCalledOnce(); + expect(registry.inspectActiveLease(lease.leaseId)).toBeUndefined(); + reply.open(); + await heartbeat; + stop.open(); + await vi.advanceTimersByTimeAsync(10_000); + expect(release).not.toHaveBeenCalled(); + expect(finish).toHaveBeenCalledOnce(); + expect(forceCleanup).toHaveBeenCalledTimes(inFlight ? 0 : 1); + localStopReady = true; + await vi.advanceTimersByTimeAsync(10_000); + expect(release.mock.calls.map(([entry]) => entry.leaseId)).toEqual([lease.leaseId]); + expect(Boolean(store.get('leased'))).toBe(false); + } finally { + reply.open(); + stop.open(); + await heartbeat.catch(() => {}); + await closeProviderDaemon(runtime); + } + }, +); + +test('shutdown releases expired leases after in-flight teardown and retained-host cleanup', async () => { + const entered = barrier(); + const finish = barrier(); + const release = vi.fn(async (_lease: DeviceLease) => undefined); + const cleanupSessionlessExecutionHost = vi.fn(async () => {}); + const { runtime, registry, store } = await startProviderDaemon({ + leaseLifecycleProvider: { release }, + platformResourceCleanup: platformResourceCleanupFixture({ + cleanupSessionlessExecutionHost, + stopSnapshotHelper: async () => { + entered.open(); + await finish.reached; + }, + }), + }); + const lease = registry.allocateLease(providerLease); + store.publish('leased', { ...makeIosSession('leased'), lease }); + try { + await vi.advanceTimersByTimeAsync(1_000); + await entered.reached; + const retainedLease = registry.allocateLease({ + ...providerLease, + runId: 'retained', + deviceKey: 'ios:mobile:retained', + }); + const retained = store.publish('retained', { + ...makeIosSession('retained'), + lease: retainedLease, + }); + store.retire(retained, { retainExecutionHost: true }); + vi.setSystemTime(retainedLease.expiresAt); + const shutdown = closeProviderDaemon(runtime); + finish.open(); + await shutdown; + expect(release.mock.calls.map(([entry]) => entry.leaseId)).toEqual([ + lease.leaseId, + retainedLease.leaseId, + ]); + expect(cleanupSessionlessExecutionHost).toHaveBeenCalledExactlyOnceWith( + retained.session.device, + ); + const [hostStopped] = cleanupSessionlessExecutionHost.mock.invocationCallOrder; + const [, providerReleased] = release.mock.invocationCallOrder; + assert.ok(hostStopped !== undefined && providerReleased !== undefined); + expect(hostStopped).toBeLessThan(providerReleased); + } finally { + finish.open(); + await closeProviderDaemon(runtime); + } +}); + +test('expiry clears the hints for the app they were set for once across cleanup retries', async () => { + const release = vi.fn(async (_lease: DeviceLease) => undefined); + const clearRuntimeHints = vi.fn(async () => {}); + const { gateway, bind } = createLifecycleDeviceRuntimeGatewaySpies(async (device, signal) => ({ + ...(await applicationLifecycleRuntimeFixture(device, signal)), + clearRuntimeHints, + })); + const bindRuntime = bind.getMockImplementation()!; + bind.mockImplementationOnce(async (input) => ({ + ...(await bindRuntime(input)), + [Symbol.asyncDispose]: async () => { + throw new Error('binding disposal failed'); + }, + })); + const { runtime, registry, store } = await startProviderDaemon({ + deviceRuntimeGateway: { + ...gateway, + applicationLifecycle: applicationLifecycleResourceFixture(), + }, + leaseLifecycleProvider: { release }, + }); + const lease = registry.allocateLease(providerLease); + store.publish('leased', { + ...makeIosSession('leased'), + appBundleId: 'com.example.active', + lease, + }); + store.setRuntimeHints( + 'leased', + { metroHost: 'scoped.example', metroPort: 8082 }, + 'com.example.bound', + ); + try { + await vi.advanceTimersByTimeAsync(1_000); + expect(release).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(10_000); + expect(release.mock.calls.map(([entry]) => entry.leaseId)).toEqual([lease.leaseId]); + expect(clearRuntimeHints).toHaveBeenCalledExactlyOnceWith({ + appId: 'com.example.bound', + values: { metroHost: 'scoped.example', metroPort: '8082' }, + }); + } finally { + await closeProviderDaemon(runtime); + } +}); + +test('shutdown releases an expired rental whose local teardown failed', async () => { + const release = vi.fn(async (_lease: DeviceLease) => undefined); + const stopSnapshotHelper = vi.fn(async () => { + throw new Error('snapshot helper still active'); + }); + const { runtime, registry, store, stateDir } = await startProviderDaemon({ + leaseLifecycleProvider: { release }, + platformResourceCleanup: platformResourceCleanupFixture({ stopSnapshotHelper }), + }); + const lease = registry.allocateLease(providerLease); + store.publish('leased', { ...makeIosSession('leased'), lease }); + try { + await vi.advanceTimersByTimeAsync(1_000); + expect(stopSnapshotHelper).toHaveBeenCalledOnce(); + expect(release).not.toHaveBeenCalled(); + + const report = await closeProviderDaemon(runtime); + expect(release.mock.calls.map(([entry]) => entry.leaseId)).toEqual([lease.leaseId]); + const failure = { leaseId: lease.leaseId, failedSteps: ['platform_snapshot_helper'] }; + const reportFields = { leaseCleanupFailures: [failure] }; + expect(report).toMatchObject(reportFields); + expect(readDaemonShutdownReport(stateDir)).toMatchObject(reportFields); + const diagnostics = fs + .readFileSync(`${stateDir}/daemon.log`, 'utf8') + .trim() + .split('\n') + .map((line) => JSON.parse(line)); + expect(diagnostics).toContainEqual( + expect.objectContaining({ + phase: 'leased_session_ended', + data: expect.objectContaining({ ...failure, reason: 'DAEMON_SHUTDOWN', session: 'leased' }), + }), + ); + } finally { + await closeProviderDaemon(runtime); + } }); test('an expired lease ends its session without any further request', async () => { @@ -91,71 +441,150 @@ test('an expired lease ends its session without any further request', async () = } }); -test('a lease that expires after shutdown is refused and reported, not sent to its provider', async () => { - vi.useFakeTimers(); - const stateDir = mkdtempForTestSync('agent-device-daemon-lease-closed-'); - const release = vi.fn(async (_lease: DeviceLease) => ({})); - try { - const runtime = await startDaemonRuntime({ - composeDeps: daemonRuntimeDepsFixture({ - leaseLifecycleProvider: { release }, - providerRuntimeIds: ['browserstack'], - }), - host: createTestHostEnvironment({ - env: { - ...process.env, - AGENT_DEVICE_STATE_DIR: stateDir, - AGENT_DEVICE_DAEMON_SERVER_MODE: 'http', - AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0', - AGENT_DEVICE_LEASE_MIN_TTL_MS: '1', +test.each(['closed', 'provider-runtime-unavailable'] as const)( + 'a non-durable provider refusal (%s) reports unknown release and keeps the reservation', + async (reason) => { + vi.useFakeTimers(); + const stateDir = mkdtempForTestSync('agent-device-daemon-lease-closed-'); + const release = vi.fn(async (_lease: DeviceLease) => ({})); + let runtime: Awaited> | undefined; + try { + runtime = await startDaemonRuntime({ + composeDeps: daemonRuntimeDepsFixture({ + leaseLifecycleProvider: { release }, + providerRuntimeIds: reason === 'closed' ? ['browserstack'] : [], + }), + host: createTestHostEnvironment({ + env: { + ...process.env, + AGENT_DEVICE_STATE_DIR: stateDir, + AGENT_DEVICE_DAEMON_SERVER_MODE: 'http', + AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0', + AGENT_DEVICE_LEASE_MIN_TTL_MS: '1', + }, + }), + stderr: { write: () => {} }, + stdout: { write: () => {} }, + }); + assert.notEqual(runtime, null); + const [registry] = leaseProbe.registries; + assert.ok(registry); + if (reason === 'closed') { + const closing = runtime!.close(); + await vi.runOnlyPendingTimersAsync(); + await closing; + } + + const request = { + tenantId: 'tenant-a', + runId: 'run-1', + leaseProvider: 'browserstack', + deviceKey: 'fixture-device', + ttlMs: 10, + }; + const lease = registry.allocateLease(request); + await vi.advanceTimersByTimeAsync(1_000); + registry.consumeExpiredLease(lease.leaseId); + await vi.advanceTimersByTimeAsync(0); + + // The provider was never asked, and the daemon log names the lease it could not end. + assert.deepEqual(release.mock.calls, []); + const next = { ...request, runId: 'run-2' }; + assert.throws( + () => registry.allocateLease(next), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.code, 'DEVICE_IN_USE'); + assert.equal(error.details?.reason, 'DEVICE_LEASE_BUSY'); + assert.equal(error.details?.releaseStatus, 'unknown'); + return true; }, - }), - stderr: { write: () => {} }, - stdout: { write: () => {} }, - }); - assert.notEqual(runtime, null); - const [registry] = leaseProbe.registries; - assert.ok(registry); - const closing = runtime!.close(); - await vi.runOnlyPendingTimersAsync(); - await closing; - - // An abandoned request let this lease go past its TTL once this daemon had stopped releasing. - const lease = registry.allocateLease({ - tenantId: 'tenant-a', - runId: 'run-1', - leaseProvider: 'browserstack', - ttlMs: 10, + ); + assert.ok(registry.allocateLease({ ...next, deviceKey: 'other-device' }).leaseId); + const rows = fs + .readFileSync(`${stateDir}/daemon.log`, 'utf8') + .split('\n') + .filter((line) => line.length > 0) + .map((line) => JSON.parse(line) as { phase: string; level: string; data?: unknown }); + assert.ok( + rows.some( + (row) => + row.phase === 'provider_lease_release_refused' && + row.level === 'error' && + JSON.stringify(row.data) === + JSON.stringify({ + leaseId: lease.leaseId, + reason, + durable: false, + leaseProvider: 'browserstack', + }), + ), + `expected a refusal row in the daemon log, got ${JSON.stringify(rows.map((r) => r.phase))}`, + ); + } finally { + vi.useRealTimers(); + await runtime?.close(); + fs.rmSync(stateDir, { recursive: true, force: true }); + } + }, +); + +test('expiry reserves the provider device through a slow failed release and a successful retry', async () => { + vi.useFakeTimers(); + const stateDir = mkdtempForTestSync('agent-device-provider-expiry-reservation-'); + let failFirstRelease!: (error: Error) => void; + const firstRelease = new Promise((_resolve, reject) => { + failFirstRelease = reject; + }); + const release = vi + .fn(async (_lease: DeviceLease) => ({})) + .mockImplementationOnce(async () => await firstRelease); + const runtime = await startDaemonRuntime({ + composeDeps: daemonRuntimeDepsFixture({ + leaseLifecycleProvider: { release }, + providerRuntimeIds: ['browserstack'], + }), + host: createTestHostEnvironment({ + env: { + ...process.env, + AGENT_DEVICE_STATE_DIR: stateDir, + AGENT_DEVICE_DAEMON_SERVER_MODE: 'http', + AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0', + AGENT_DEVICE_LEASE_MIN_TTL_MS: '1', + }, + }), + stderr: { write: () => {} }, + stdout: { write: () => {} }, + }); + assert.ok(runtime); + const [registry] = leaseProbe.registries; + assert.ok(registry); + const request = { + tenantId: 'tenant-a', + runId: 'run-1', + leaseProvider: 'browserstack', + deviceKey: 'fixture-device', + ttlMs: 10, + }; + const lease = registry.allocateLease(request); + const next = { ...request, runId: 'run-2' }; + const assertBusy = () => + assert.throws(() => registry.allocateLease(next), { + code: 'DEVICE_IN_USE', }); + try { await vi.advanceTimersByTimeAsync(1_000); - registry.consumeExpiredLease(lease.leaseId); + assert.equal(release.mock.calls.length, 1); + assertBusy(); + failFirstRelease(new Error('provider temporarily unavailable')); await vi.advanceTimersByTimeAsync(0); - - // The provider was never asked, and the daemon log names the lease it could not end. - assert.deepEqual(release.mock.calls, []); - const rows = fs - .readFileSync(`${stateDir}/daemon.log`, 'utf8') - .split('\n') - .filter((line) => line.length > 0) - .map((line) => JSON.parse(line) as { phase: string; level: string; data?: unknown }); - assert.ok( - rows.some( - (row) => - row.phase === 'provider_lease_release_refused' && - row.level === 'error' && - JSON.stringify(row.data) === - JSON.stringify({ - leaseId: lease.leaseId, - reason: 'closed', - durable: false, - leaseProvider: 'browserstack', - }), - ), - `expected a refusal row in the daemon log, got ${JSON.stringify(rows.map((r) => r.phase))}`, - ); + assertBusy(); + await vi.advanceTimersByTimeAsync(1_000); + assert.equal(release.mock.calls.length, 2); + assert.notEqual(registry.allocateLease(next).leaseId, lease.leaseId); } finally { vi.useRealTimers(); - fs.rmSync(stateDir, { recursive: true, force: true }); + await runtime.close(); } }); diff --git a/packages/daemon/src/server/http/daemon-runtime.ts b/packages/daemon/src/server/http/daemon-runtime.ts index c7164eead3..4ba053a953 100644 --- a/packages/daemon/src/server/http/daemon-runtime.ts +++ b/packages/daemon/src/server/http/daemon-runtime.ts @@ -1,3 +1,4 @@ +import type { ExpiryProviderSettlement } from '../lease-session-end.ts'; import type { ComposeDaemonRuntimeDeps } from './daemon-runtime-deps.ts'; import { recoverAppLogResourcesAfterDaemonLock } from '@agent-device/capture-kit/app-log-resource-recovery'; import { resolveSessionRequestLogPath } from '@agent-device/daemon-contracts/session-artifact-paths'; @@ -36,10 +37,7 @@ import { leaseReleaseDiagnosticEvent, } from '../provider-lease-expiry.ts'; import { createRequestHandler } from '../request-router.ts'; -import { - createLeaseSessionEnd, - getLeaseRegistryExecutionLocks, -} from '../request-execution-scope.ts'; +import { getLeaseRegistryExecutionLocks } from '../request-execution-scope.ts'; import type { LeaseEndReason } from '../../sessions/lease-lifecycle.ts'; import { settleExpiredSession } from '../../sessions/session-teardown.ts'; import { resolveDaemonSessionTeardownTimeoutMs } from '../../sessions/session-teardown-budget.ts'; @@ -48,6 +46,7 @@ import { runtimeHintsClearInput } from '../../sessions/session-runtime.ts'; import { closeDaemonServers, teardownDaemonSessionForShutdown, + teardownDaemonSessions, type WritableOutput, createPluginClose, createStartupRollback, @@ -277,12 +276,18 @@ async function startDaemonRuntimeOnHost( } installProviderDeviceAdmission(deps.providerDeviceAdmission); installInteractorResolution(deps.interactorResolution); + const { createLeaseSessionEnd } = await import('../lease-session-end.ts'); const expiredProviderLeaseReleaser = createExpiredProviderLeaseReleaser({ leaseLifecycleProvider: deps.leaseLifecycleProvider, providerRuntimeIds: deps.providerRuntimeIds, recoverExpiredLease: deps.recoverExpiredLease, stateDir: baseDir, recoverableProviderIds: deps.recoverableProviderIds, + onRecovered: (lease) => leaseRegistry.reserveExpiredLease(lease, true), + onReleased: (lease) => { + if (leaseRegistry.confirmExpiredLeaseEnd(lease.leaseId, 'providerReleased')) + leaseSessionEnd.forgetClosing(lease.leaseId); + }, withinDiagnosticsScope: async (run) => await withDaemonDiagnosticsScope({ logPath }, run), }); rollback.onRollback(() => expiredProviderLeaseReleaser.shutdown()); @@ -292,25 +297,42 @@ async function startDaemonRuntimeOnHost( minLeaseTtlMs: parseIntegerEnv(env.AGENT_DEVICE_LEASE_MIN_TTL_MS), maxLeaseTtlMs: parseIntegerEnv(env.AGENT_DEVICE_LEASE_MAX_TTL_MS), onLeaseExpired: (lease, reason) => { - void expiredProviderLeaseReleaser.release(lease).then( - (outcome) => { - // A lease can expire after shutdown closed the releaser, and the sweep runs outside any - // request, so this report goes to the daemon log rather than a request scope. - const event = leaseReleaseDiagnosticEvent(lease, outcome); - if (event) { - void emitDaemonDiagnostic(logPath, event.phase, event.data, event.level).catch( - () => undefined, - ); - } - }, - (error: unknown) => { - void emitDaemonDiagnostic(logPath, 'provider_lease_release_outcome_failed', { - leaseId: lease.leaseId, - error: error instanceof Error ? error.message : String(error), - }).catch(() => undefined); - }, - ); - if (!reason) void endSessionsForLease(lease.leaseId, 'LEASE_EXPIRED'); + if (!leaseRegistry.reserveExpiredLease(lease)) return; + let finishProvider!: () => void; + const providerEnd = new Promise((resolve) => { + finishProvider = resolve; + }); + let allowRelease!: () => void; + const sessionsEnd = new Promise((resolve) => { + allowRelease = resolve; + }); + void endSessionsForLease(lease.leaseId, reason ?? 'LEASE_EXPIRED', { + done: providerEnd, + allowRelease, + }); + void expiredProviderLeaseReleaser + .release(lease, sessionsEnd) + .then( + (outcome) => { + if (outcome.status === 'refused' && !outcome.durable) + leaseRegistry.markExpiredProviderReleaseUnknown(lease.leaseId); + // A lease can expire after shutdown closed the releaser, and the sweep runs outside any + // request, so this report goes to the daemon log rather than a request scope. + const event = leaseReleaseDiagnosticEvent(lease, outcome); + if (event) { + void emitDaemonDiagnostic(logPath, event.phase, event.data, event.level).catch( + () => undefined, + ); + } + }, + (error: unknown) => { + void emitDaemonDiagnostic(logPath, 'provider_lease_release_outcome_failed', { + leaseId: lease.leaseId, + error: error instanceof Error ? error.message : String(error), + }).catch(() => undefined); + }, + ) + .finally(finishProvider); }, onProviderLeasesChanged: (leases) => expiredProviderLeaseReleaser.recordLiveLeases(leases), }); @@ -342,9 +364,10 @@ async function startDaemonRuntimeOnHost( leaseRegistry, endSessionsForLease: async (leaseId, reason) => await endSessionsForLease(leaseId, reason ?? 'LEASE_RELEASED'), - // A request that ends an expired session retires it, so the application is always finalized. - settleExpiredSession: async (ref: SessionRef) => - await settleIdleExpiredSession(ref, 'finalize'), + leaseSessionEnd: { + closingAt: (address) => leaseSessionEnd.closingAt(address), + settlementFor: (lifetime) => leaseSessionEnd.settlementFor(lifetime), + }, appLogAdmissionLedger, audioProbeAdmissionLedger, perfCaptureAdmissionLedger, @@ -379,14 +402,17 @@ async function startDaemonRuntimeOnHost( const shutdownClaimLedger = createDaemonShutdownClaimLedger(env); - const teardownDaemonSession = async (ref: SessionRef): Promise => { + const teardownDaemonSession = async (ref: SessionRef) => { const session = sessionStore.resolveCurrent(ref) ?? ref.session; + const failedSteps: string[] = []; try { - return await teardownDaemonSessionForShutdown({ + const closed = await teardownDaemonSessionForShutdown({ ref, sessionStore, stderr, platformCleanup: deps.platformResourceCleanup, + providerInstanceEnded: () => + leaseRegistry.providerInstanceEnded(session.lease?.leaseId ?? ''), finalizeApplicationLifecycle: async (sessionToFinalize, runtimeHints) => await finalizeDaemonSessionApplicationLifecycle({ gateway: deviceRuntimeGateway, @@ -395,24 +421,19 @@ async function startDaemonRuntimeOnHost( stateDir: baseDir, runtimeHints, }), - afterSuccessfulTeardown: shutdownClaimLedger.releaseClaim, + onFailedSteps: (steps) => { + failedSteps.push(...steps); + }, + afterSuccessfulTeardown: async (current) => { + if (!(await shutdownClaimLedger.releaseClaim(current))) failedSteps.push('device_claim'); + }, }); + return { closed, failedSteps }; } finally { shutdownClaimLedger.finalize(session); } }; - const teardownDaemonSessions = async (): Promise => { - sessionStore.closeAdmission(); - const sessionsToStop = sessionStore.listRefs(); - const outcomes = await Promise.all( - sessionsToStop.map(async (ref) => await teardownDaemonSession(ref).catch(() => false)), - ); - await sessionStore.flushJournalRemovals(); - const closedCount = outcomes.filter(Boolean).length; - return { closed: closedCount, failed: outcomes.length - closedCount }; - }; - // #2833: settles the resources of a session this daemon expires for idleness. Deliberately NOT // `teardownDaemonSession`: that one exists for a daemon that is leaving, so it hands a healthy // execution host to its successor and deletes the session whether the @@ -421,10 +442,7 @@ async function startDaemonRuntimeOnHost( // survive so the next pass can retry rather than leave a claim owned by a process that no longer // knows what it holds. So: resources, then the platform finalization that stops the execution host // and releases its lease, then the claim, cleared last, by the reaper. - const settleIdleExpiredSession = async ( - ref: SessionRef, - afterResourceFailure: 'stop' | 'finalize' = 'stop', - ): Promise => { + const settleIdleExpiredSession = async (ref: SessionRef): Promise => { const session = sessionStore.resolveCurrent(ref) ?? ref.session; const sessionName = ref.address; const runtimeHints = runtimeHintsClearInput( @@ -436,7 +454,8 @@ async function startDaemonRuntimeOnHost( ref, sessionStore, platformCleanup: deps.platformResourceCleanup, - afterResourceFailure, + providerInstanceEnded: () => + leaseRegistry.providerInstanceEnded(session.lease?.leaseId ?? ''), finalizeApplication: async () => await finalizeDaemonSessionApplicationLifecycle({ gateway: deviceRuntimeGateway, @@ -444,6 +463,9 @@ async function startDaemonRuntimeOnHost( session, stateDir: baseDir, runtimeHints, + onRuntimeHintsCleared: () => { + if (sessionStore.resolveCurrent(ref)) sessionStore.clearRuntimeHints(ref); + }, // The one caller that must say so: this daemon is staying alive, so there is no shutdown // phase a healthy runner could be deferred to. Taking the ordinary-close path stops the // runner and releases its lease instead of parking it until process exit. @@ -464,10 +486,16 @@ async function startDaemonRuntimeOnHost( teardownSession: settleIdleExpiredSession, cleanupSessionlessExecutionHost: deps.platformResourceCleanup.cleanupSessionlessExecutionHost, withinDiagnosticsScope: async (run) => await withDaemonDiagnosticsScope({ logPath }, run), + confirmExpiredSessions: (leaseId) => + leaseRegistry.confirmExpiredLeaseEnd(leaseId, 'sessionsSettled'), }); - const endSessionsForLease = async (leaseId: string, reason: LeaseEndReason): Promise => { - await leaseSessionEnd.end(leaseId, reason); + const endSessionsForLease = async ( + leaseId: string, + reason: LeaseEndReason, + providerEnd?: ExpiryProviderSettlement, + ): Promise => { + await leaseSessionEnd.end(leaseId, reason, providerEnd); idleReap.noteActivity(); }; @@ -778,15 +806,18 @@ async function startDaemonRuntimeOnHost( expiredProviderLeaseReleaser.beginShutdown(); // Session teardown, lease finalization and the release drain run outside any request, so they // share one daemon scope; without it every claim, lease and drain diagnostic here is dropped. - const { sessions, providerReleaseDrain } = await withDaemonDiagnosticsScope( - { logPath }, - async () => { - const tornDown = await teardownDaemonSessions(); + const { sessions, providerReleaseDrain, leaseCleanupFailures } = + await withDaemonDiagnosticsScope({ logPath }, async () => { + const tornDown = await teardownDaemonSessions(sessionStore, teardownDaemonSession); const leaseFinalization = await finalizeDaemonLeases({ leaseRegistry, expiredProviderLeaseReleaser, timeoutMs: DAEMON_LEASE_RELEASE_TIMEOUT_MS, }); + await leaseSessionEnd.finishShutdown( + tornDown.failedLeases, + DAEMON_LEASE_RELEASE_TIMEOUT_MS, + ); try { await deps.ownerLifecycle.resetAndroidSnapshotHelper(); } catch (error) { @@ -813,9 +844,16 @@ async function startDaemonRuntimeOnHost( orphanedDeviceKeys: shutdownClaimLedger.claims.orphaned.map((claim) => claim.deviceKey), }, }); - return { sessions: tornDown, providerReleaseDrain: drain }; - }, - ); + const failures = Array.from(tornDown.failedLeases, ([leaseId, failedSteps]) => ({ + leaseId, + failedSteps, + })); + return { + sessions: tornDown.sessions, + providerReleaseDrain: drain, + leaseCleanupFailures: failures, + }; + }); expiredProviderLeaseReleaser.shutdown(); let gatewayShutdownFailed = false; const ownerClose = await settleWithin( @@ -846,7 +884,9 @@ async function startDaemonRuntimeOnHost( } const stoppedRunners = await applicationLifecycle.finalizeDaemonShutdown(); const unknownLeaseIds = new Set(providerReleaseDrain.unknown.map((lease) => lease.leaseId)); + const cleanupFailures = leaseCleanupFailures.length ? { leaseCleanupFailures } : {}; const report: ShutdownReport = { + ...cleanupFailures, providerReleases: { completed: providerReleaseDrain.released.map((lease) => lease.leaseId), pending: providerReleaseDrain.pending @@ -861,6 +901,7 @@ async function startDaemonRuntimeOnHost( plugins, }; shutdownOutcome = { + ...cleanupFailures, providerReleases: providerReleaseDrain, claims: shutdownClaimLedger.claims, }; diff --git a/packages/daemon/src/server/http/daemon-shutdown-claims.ts b/packages/daemon/src/server/http/daemon-shutdown-claims.ts index f279962d66..b9ed59e685 100644 --- a/packages/daemon/src/server/http/daemon-shutdown-claims.ts +++ b/packages/daemon/src/server/http/daemon-shutdown-claims.ts @@ -25,7 +25,7 @@ export type DaemonShutdownClaims = { export type DaemonShutdownClaimLedger = Readonly<{ claims: DaemonShutdownClaims; /** Runs only once a session's teardown reached a safe terminal state. */ - releaseClaim(session: SessionState): Promise; + releaseClaim(session: SessionState): Promise; /** Classifies the session's claim once its teardown has finished either way. */ finalize(session: SessionState): void; }>; @@ -76,9 +76,11 @@ export function createDaemonShutdownClaimLedger( claims, releaseClaim: async (session) => { const claim = session.deviceClaim; - if (!claim) return; + if (!claim) return true; try { - outcomes.set(claim.ownerToken, await clearDeviceClaim(claim, env)); + const outcome = await clearDeviceClaim(claim, env); + outcomes.set(claim.ownerToken, outcome); + return outcome !== 'unattributable'; } catch (error) { outcomes.set(claim.ownerToken, CLEAR_UNRECORDED); emitDiagnostic({ @@ -90,6 +92,7 @@ export function createDaemonShutdownClaimLedger( error: error instanceof Error ? error.message : String(error), }, }); + return false; } }, finalize: (session) => { diff --git a/packages/daemon/src/server/http/http-server-session-lease-settlement.test.ts b/packages/daemon/src/server/http/http-server-session-lease-settlement.test.ts new file mode 100644 index 0000000000..b4dab37244 --- /dev/null +++ b/packages/daemon/src/server/http/http-server-session-lease-settlement.test.ts @@ -0,0 +1,276 @@ +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { afterEach, beforeEach, expect, test, vi } from 'vitest'; +import { skipWhenLoopbackUnavailable } from '@agent-device/test-kit'; +import { startDaemon, type RpcBody } from './http-server-session-lease-touch.fixtures.ts'; + +let world: Awaited> | undefined; + +beforeEach(async (context) => { + if (await skipWhenLoopbackUnavailable(context)) return; + world = await startDaemon(); +}); + +afterEach(async () => { + vi.restoreAllMocks(); + vi.useRealTimers(); + await world?.close(); + world = undefined; +}); + +function expectLeaseIdRefusal(body: RpcBody): void { + expect(body.error?.data).toMatchObject({ + code: 'UNAUTHORIZED', + details: { reason: 'LEASE_SESSION_MISMATCH', field: 'leaseId' }, + }); +} + +function deferred() { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +test.each(['sweep', 'close'] as const)( + '%s wins expiry admission and two owners close with one teardown and one receipt', + async (first) => { + const daemon = world; + if (!daemon) return; + const ref = daemon.publishLeasedSession(daemon.sessionName); + const teardown = holdExpiry(daemon); + daemon.passLeaseDeadline(); + + if (first === 'sweep') daemon.leaseRegistry.consumeExpiredLeases(); + const firstClose = daemon.send('close', [], daemon.owner); + try { + await teardown.entered.promise; + const secondJoined = observeNextExpiryWait(daemon); + const secondClose = daemon.send('close', [], daemon.owner); + await secondJoined; + daemon.leaseRegistry.consumeExpiredLeases(); + teardown.release.resolve(); + + const responses = await Promise.all([firstClose, secondClose]); + for (const response of responses) + expect(response.error?.data?.details?.reason).toBe('LEASE_NOT_FOUND'); + expect( + responses.flatMap((response) => response.error?.data?.details?.endedLeases ?? []), + ).toEqual([{ leaseId: daemon.leaseId, outcome: 'released' }]); + expect(daemon.expiryTeardown).toHaveBeenCalledExactlyOnceWith(ref); + expect(daemon.sessionStore.get(daemon.sessionName)).toBeUndefined(); + } finally { + teardown.release.resolve(); + await firstClose; + } + }, +); + +test.each([undefined, 30_000])( + 'two successors share one teardown with waitMs=%s and only one publishes', + async (waitMs) => { + const daemon = world; + if (!daemon) return; + const ref = daemon.publishLeasedSession(daemon.sessionName); + const a = daemon.allocateOtherClient('ios:mobile:SIM-002'); + const b = daemon.allocateOtherClient('ios:mobile:SIM-003'); + const teardown = holdExpiry(daemon); + daemon.passLeaseDeadline(); + const first = daemon.send('open', ['com.example.app'], a); + try { + await Promise.race([ + teardown.entered.promise, + first.then((response) => { + throw new Error(`First open finished before teardown ${JSON.stringify(response)}`); + }), + ]); + const joined = observeNextExpiryWait(daemon); + const second = daemon.send('open', ['com.example.app'], b, { flags: { waitMs } }); + await Promise.race([ + joined, + second.then((response) => { + throw new Error(`Second open finished before joining ${JSON.stringify(response)}`); + }), + ]); + const closeJoined = observeNextExpiryWait(daemon); + const close = daemon.send('close', [], daemon.owner); + await closeJoined; + teardown.release.resolve(); + const [responses, closed] = await Promise.all([Promise.all([first, second]), close]); + expect(closed.error?.data?.details).toMatchObject({ + reason: 'LEASE_NOT_FOUND', + endedLeases: [{ leaseId: daemon.leaseId, outcome: 'released' }], + }); + + expect( + responses.filter((response) => response.result?.ok), + JSON.stringify(responses), + ).toHaveLength(1); + expectLeaseIdRefusal(responses.find((response) => response.error)!); + expect( + responses.every((response) => !JSON.stringify(response).includes(daemon.leaseId)), + ).toBe(true); + expect(daemon.expiryTeardown).toHaveBeenCalledExactlyOnceWith(ref); + expect(daemon.sessionStore.lookup(daemon.sessionName)?.lifetime).not.toBe(ref.lifetime); + } finally { + teardown.release.resolve(); + await first; + } + }, +); + +test('open --wait can run out while the daemon is still tearing down the expired session', async () => { + const daemon = world; + if (!daemon) return; + const ref = daemon.publishLeasedSession(daemon.sessionName); + const successor = daemon.allocateOtherClient('ios:mobile:SIM-002'); + const teardown = holdExpiry(daemon); + daemon.passLeaseDeadline(); + vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }); + const open = daemon.send('open', ['com.example.app'], successor, { flags: { waitMs: 500 } }); + try { + await teardown.entered.promise; + await vi.advanceTimersByTimeAsync(500); + const response = await open; + expect(response.error?.data).toMatchObject({ + code: 'DEVICE_IN_USE', + details: { reason: 'DEVICE_LEASE_BUSY' }, + }); + expect(daemon.sessionStore.lookup(daemon.sessionName)?.lifetime).toBe(ref.lifetime); + } finally { + teardown.release.resolve(); + vi.useRealTimers(); + await daemon.expiryOwnerSettled(); + await open; + } + expect(daemon.expiryTeardown).toHaveBeenCalledTimes(1); + expect(daemon.sessionStore.lookup(daemon.sessionName)).toBeUndefined(); +}); + +test.each(['close', 'open'] as const)( + 'disconnecting an expired-session %s cancels the caller and leaves teardown running', + async (command) => { + const daemon = world; + if (!daemon) return; + const ref = daemon.publishLeasedSession(daemon.sessionName); + const successor = daemon.allocateOtherClient('ios:mobile:SIM-002'); + const teardown = holdExpiry(daemon); + const controller = new AbortController(); + const completed = new Promise((resolve) => { + daemon.hooks.afterRequest = resolve; + }); + daemon.passLeaseDeadline(); + const pending = expect( + daemon.send( + command, + command === 'open' ? ['com.example.app'] : [], + command === 'open' ? successor : daemon.owner, + { signal: controller.signal }, + ), + ).rejects.toMatchObject({ name: 'AbortError' }); + + try { + await teardown.entered.promise; + controller.abort(); + await pending; + expect(await completed).toMatchObject({ + ok: false, + error: { details: { reason: 'request_canceled' } }, + }); + expect(daemon.sessionStore.lookup(daemon.sessionName)?.lifetime).toBe(ref.lifetime); + } finally { + teardown.release.resolve(); + } + await daemon.expiryOwnerSettled(); + expect(daemon.expiryTeardown).toHaveBeenCalledTimes(1); + expect(daemon.sessionStore.lookup(daemon.sessionName)).toBeUndefined(); + expect(daemon.runtime.bind).not.toHaveBeenCalled(); + }, +); + +function holdExpiry(daemon: Awaited>) { + const entered = deferred(); + const release = deferred(); + daemon.expiryTeardown.mockImplementationOnce(async () => { + entered.resolve(); + await release.promise; + }); + return { entered, release }; +} + +function observeNextExpiryWait(daemon: Awaited>): Promise { + const joined = deferred(); + const lookup = daemon.settlementFor.getMockImplementation()!; + daemon.settlementFor.mockImplementationOnce((lifetime) => { + const settlement = lookup(lifetime); + if (settlement) joined.resolve(); + return settlement; + }); + return joined.promise; +} + +test('a pending hold protects expiry while a mutation drains and restarts the TTL on release', async () => { + const daemon = world; + if (!daemon) return; + const ref = daemon.publishLeasedSession(daemon.sessionName); + const registry = daemon.leaseRegistry; + const lease = registry.inspectActiveLease(daemon.leaseId)!; + const authority = { kind: 'lease', leaseId: daemon.leaseId } as const; + const drain = deferred(); + const mutation = registry.runDeviceMutation(lease, () => drain.promise); + const hold = registry.putHumanControlHold(authority, 'console', {}); + try { + daemon.passLeaseDeadline(); + expect(registry.listHumanControlHolds(authority)[0]?.state).toBe('activating'); + expect(registry.consumeExpiredLeases()).toEqual([]); + expect(daemon.expiryTeardown).not.toHaveBeenCalled(); + } finally { + drain.resolve(); + } + await mutation; + expect((await hold).state).toBe('active'); + daemon.passLeaseDeadline(); + registry.removeHumanControlHold(authority, 'console'); + expect(registry.consumeExpiredLeases()).toEqual([]); + expect((await daemon.send('snapshot', [], daemon.owner)).result?.ok).toBe(true); + + daemon.passLeaseDeadline(); + registry.consumeExpiredLeases(); + await daemon.expiryOwnerSettled(); + expect(daemon.expiryTeardown).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ lifetime: ref.lifetime }), + ); +}); + +test('expiry at a batch step unwinds outer locks and preserves completed progress', async () => { + const daemon = world; + if (!daemon) return; + const ref = daemon.publishLeasedSession(daemon.sessionName); + const retain = daemon.leaseRegistry.retainLeaseWork.bind(daemon.leaseRegistry); + vi.spyOn(daemon.leaseRegistry, 'retainLeaseWork').mockImplementationOnce((lease) => + retain(lease, () => false), + ); + let dispatches = 0; + daemon.hooks.beforeDispatch = () => { + if (++dispatches === 2) daemon.passLeaseDeadline(); + }; + + const response = await daemon.send('batch', [], daemon.owner, { + flags: { batchSteps: [{ command: 'devices' }, { command: 'snapshot' }] }, + }); + + expect(response.error?.data).toMatchObject({ + code: 'UNAUTHORIZED', + details: { + reason: 'LEASE_NOT_FOUND', + step: 2, + executed: 1, + partialResults: [{ command: 'devices', ok: true }], + }, + }); + await daemon.expiryOwnerSettled(); + expect(daemon.expiryTeardown).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ lifetime: ref.lifetime }), + ); + expect(daemon.sessionStore.get(daemon.sessionName)).toBeUndefined(); +}); diff --git a/packages/daemon/src/server/http/http-server-session-lease-touch.fixtures.ts b/packages/daemon/src/server/http/http-server-session-lease-touch.fixtures.ts index 066c5e43af..f15d39e941 100644 --- a/packages/daemon/src/server/http/http-server-session-lease-touch.fixtures.ts +++ b/packages/daemon/src/server/http/http-server-session-lease-touch.fixtures.ts @@ -1,3 +1,5 @@ +import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { createLeaseSessionEnd, type LeaseSessionEnd } from '../lease-session-end.ts'; import path from 'node:path'; import { vi } from 'vitest'; import { @@ -23,11 +25,7 @@ import { platformResourceCleanupFixture } from '../../__tests__/support/platform import { tenantScopedSessionName } from '../../core/session-tenant-scope.ts'; import type { SessionRef } from '../../core/session-state.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; -import { - createLeaseSessionEnd, - getLeaseRegistryExecutionLocks, - type LeaseSessionEnd, -} from '../request-execution-scope.ts'; +import { getLeaseRegistryExecutionLocks } from '../request-execution-scope.ts'; export const TENANT = 'e2b'; export const SESSION = 'agentA'; @@ -44,7 +42,10 @@ export type RpcBody = { result?: { ok?: boolean; data?: Record }; error?: { message?: string; - data?: { code?: string; details?: { reason?: string; field?: string } }; + data?: { + code?: string; + details?: { reason?: string; field?: string; endedLeases?: unknown[] }; + }; }; }; @@ -98,13 +99,14 @@ export async function startDaemon(daemonPolicy?: DaemonPolicy) { }; const observeRunnerSession = vi.fn(async () => ({ alive: true, sessionId: 'runner-1' })); const hostDiagnostics = hostDiagnosticsFixture(); - // A request that ends an expired session itself stops the snapshot helper of that session. const requestTeardown = platformResourceCleanupFixture(); const runtime = createLifecycleDeviceRuntimeGatewaySpies(); const hooks: { beforeDispatch?: () => void | Promise; duringDeviceSelection?: () => void; + afterRequest?: (response: DaemonResponse) => void; } = {}; + const settlementFor = vi.fn(leaseSessionEnd.settlementFor); const handleRequest = createRequestHandler({ host: createTestHostEnvironment({ env: { ...process.env, AGENT_DEVICE_MACOS_APP_BACKEND: 'native' }, @@ -114,6 +116,7 @@ export async function startDaemon(daemonPolicy?: DaemonPolicy) { token: 'daemon-token', sessionStore, leaseRegistry, + leaseSessionEnd: { settlementFor, closingAt: leaseSessionEnd.closingAt }, deviceInventoryGateways: createTestDeviceInventoryGateways({ local: async () => { hooks.duringDeviceSelection?.(); @@ -140,30 +143,43 @@ export async function startDaemon(daemonPolicy?: DaemonPolicy) { }); const daemon = await createDaemonHttpServer({ token: 'daemon-token', - handleRequest, + handleRequest: async (req) => { + const response = await handleRequest(req); + hooks.afterRequest?.(response); + return response; + }, env: {}, cwd: process.cwd(), }); const daemonPort = await listenOnLoopback(daemon); + let requestNumber = 0; const send = async ( command: string, positionals: string[], meta: Record, - request: { session?: string; flags?: Record } = {}, + request: { session?: string; flags?: Record; signal?: AbortSignal } = {}, ) => { + const requestId = `lease-touch-${++requestNumber}`; const response = await fetch(`http://127.0.0.1:${daemonPort}/rpc`, { method: 'POST', + signal: request.signal, headers: { authorization: 'Bearer daemon-token', 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', - id: command, + id: requestId, method: 'agent_device.command', params: { session: request.session ?? SESSION, command, positionals, flags: request.flags ?? {}, - meta: { tenantId: TENANT, sessionIsolation: 'tenant', sessionExplicit: true, ...meta }, + meta: { + requestId, + tenantId: TENANT, + sessionIsolation: 'tenant', + sessionExplicit: true, + ...meta, + }, }, }), }); @@ -189,6 +205,7 @@ export async function startDaemon(daemonPolicy?: DaemonPolicy) { leaseRegistry, publishLeasedSession, expiryTeardown, + settlementFor, observeRunnerSession, hostDiagnostics, requestTeardown, diff --git a/packages/daemon/src/server/http/http-server-session-lease-touch.test.ts b/packages/daemon/src/server/http/http-server-session-lease-touch.test.ts index 768bddc4eb..5226646daa 100644 --- a/packages/daemon/src/server/http/http-server-session-lease-touch.test.ts +++ b/packages/daemon/src/server/http/http-server-session-lease-touch.test.ts @@ -102,13 +102,11 @@ test('a new owner opens the session right after the lease deadline, before the s 'request.started', 'request.finished', ]); - // The open ended the expired session under its own locks, so the lease-end owner found none. - expect(world.requestTeardown.stopSnapshotHelper).toHaveBeenCalledTimes(1); await world.expiryOwnerSettled(); - expect(world.expiryTeardown).not.toHaveBeenCalled(); + expect(world.expiryTeardown).toHaveBeenCalledTimes(1); }); -test('a successor open keeps its lease while the expired session teardown is pending', async () => { +test('a successor lease can expire while it waits for teardown', async () => { const daemon = world; if (!daemon) return; daemon.publishLeasedSession(daemon.sessionName); @@ -117,13 +115,12 @@ test('a successor open keeps its lease while the expired session teardown is pen const originalExpiry = daemon.leaseRegistry.inspectActiveLease(successor.leaseId)?.expiresAt; const teardownEntered = deferred(); const releaseTeardown = deferred(); - daemon.requestTeardown.stopSnapshotHelper.mockImplementationOnce(async () => { + daemon.expiryTeardown.mockImplementationOnce(async () => { teardownEntered.resolve(); await releaseTeardown.promise; }); const open = daemon.send('open', ['com.example.app'], successor); - let protectedExpiry: number | undefined; try { await Promise.race([ teardownEntered.promise, @@ -131,20 +128,22 @@ test('a successor open keeps its lease while the expired session teardown is pen throw new Error(`Open finished before teardown: ${JSON.stringify(response)}`); }), ]); + expect(daemon.leaseRegistry.inspectActiveLease(successor.leaseId)?.expiresAt).toBe( + originalExpiry, + ); daemon.passLeaseDeadline(); - daemon.passLeaseDeadline(); - protectedExpiry = daemon.leaseRegistry.inspectActiveLease(successor.leaseId)?.expiresAt; } finally { releaseTeardown.resolve(); await open; } const opened = await open; - expect(opened.result?.ok, JSON.stringify(opened)).toBe(true); - expect(protectedExpiry).toBeGreaterThan(originalExpiry ?? Infinity); - expect(daemon.sessionStore.get(daemon.sessionName)?.lease?.leaseId).toBe(successor.leaseId); - await daemon.expiryOwnerSettled(); - expect(daemon.expiryTeardown).not.toHaveBeenCalled(); + expect(opened.error?.data).toMatchObject({ + code: 'UNAUTHORIZED', + details: { reason: 'LEASE_NOT_FOUND' }, + }); + expect(daemon.sessionStore.get(daemon.sessionName)).toBeUndefined(); + expect(daemon.expiryTeardown).toHaveBeenCalledTimes(1); }); test('a successor open cannot use a lease id reissued during the expired session teardown', async () => { @@ -155,7 +154,7 @@ test('a successor open cannot use a lease id reissued during the expired session const replacement = { ...successor, runId: 'run-c', clientId: 'client-c' }; daemon.passLeaseDeadline(); let released = false; - daemon.requestTeardown.stopSnapshotHelper.mockImplementationOnce(async () => { + daemon.expiryTeardown.mockImplementationOnce(async () => { await Promise.resolve(); released = daemon.leaseRegistry.releaseLease(successor).released; daemon.leaseRegistry.putHostLease(successor.leaseId, replacement); @@ -209,7 +208,10 @@ test.each([ command: 'snapshot', positionals: [], meta: { clientId: undefined }, - error: { code: 'UNAUTHORIZED', details: { reason: 'LEASE_SCOPE_REQUIRED' } }, + error: { + code: 'UNAUTHORIZED', + details: { reason: 'LEASE_SESSION_MISMATCH', field: 'leaseId' }, + }, }, { command: 'open', @@ -242,7 +244,7 @@ test.each([ { failure: 'lease expires during PID lookup', processAlive: true, - details: { reason: 'LEASE_SESSION_MISMATCH', field: 'leaseId' }, + details: { reason: 'LEASE_NOT_FOUND' }, }, ])( 'a macOS app successor leaves the expired session intact when the $failure', @@ -294,7 +296,8 @@ test('doctor with the lease id after the deadline leaves the session to the leas const ref = world.publishLeasedSession(world.sessionName); world.passLeaseDeadline(); - await world.send('doctor', [], world.owner); + const response = await world.send('doctor', [], world.owner); + expect(response.error?.data?.details?.reason).toBe('LEASE_NOT_FOUND'); expect(world.requestTeardown.stopSnapshotHelper).not.toHaveBeenCalled(); await world.expiryOwnerSettled(); @@ -310,7 +313,7 @@ test('the owner request after the deadline ends its own expired session', async const snapshot = await world.send('snapshot', [], world.owner); expect(snapshot.error?.data?.code, JSON.stringify(snapshot)).toBe('UNAUTHORIZED'); - expect(snapshot.error?.data?.details?.reason).not.toBe('LEASE_SESSION_MISMATCH'); + expect(snapshot.error?.data?.details?.reason).toBe('LEASE_NOT_FOUND'); expect(world.sessionStore.get(world.sessionName)).toBeUndefined(); }); diff --git a/packages/daemon/src/server/http/server-shutdown.ts b/packages/daemon/src/server/http/server-shutdown.ts index 0530ea6571..990e89800f 100644 --- a/packages/daemon/src/server/http/server-shutdown.ts +++ b/packages/daemon/src/server/http/server-shutdown.ts @@ -2,9 +2,11 @@ import type { PluginCleanupOutcome, PluginInventoryEntry, } from '@agent-device/contracts/plugin-inventory'; -import { normalizeError, type NormalizedError } from '@agent-device/kernel/errors'; +import { AppError, normalizeError, type NormalizedError } from '@agent-device/kernel/errors'; +import type { LeaseCleanupFailure } from '@agent-device/daemon-contracts/daemon-shutdown-report'; import { settleWithin, type SettleWithinOutcome } from '@agent-device/host-kit/settle-within'; import type { DaemonServer } from './transport.ts'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import type { RuntimeHintsApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime'; import { SessionStore } from '../../core/session-store.ts'; import type { SessionRef, SessionState } from '../../core/session-state.ts'; @@ -53,6 +55,7 @@ export async function closeDaemonServers( /** What a closed daemon runtime leaves behind, by kind of resource. */ export type ShutdownReport = { + leaseCleanupFailures?: LeaseCleanupFailure[]; /** Provider lease releases, by lease id. `unknown` was still in flight when the budget ran out. */ providerReleases: { completed: string[]; pending: string[]; unknown: string[] }; /** Device runners, by device id: `handedOff` was left running for the next daemon. */ @@ -266,18 +269,22 @@ async function settleDaemonTeardownStep(params: { stderr: WritableOutput; resource: 'app-log' | 'session' | 'lifecycle'; teardown: () => Promise; -}): Promise { +}): Promise { const { session, stderr, resource, teardown } = params; try { await teardown(); - return true; + return []; } catch (error) { stderr.write( `Daemon ${resource} teardown error (${session.name}): ${ error instanceof Error ? error.message : String(error) }\n`, ); - return false; + const steps = error instanceof AppError ? error.details?.failedSteps : undefined; + const failedSteps = Array.isArray(steps) + ? steps.filter((step) => typeof step === 'string') + : []; + return failedSteps.length ? failedSteps : [resource]; } } @@ -299,6 +306,8 @@ export async function teardownDaemonSessionForShutdown(params: { runtimeHints: RuntimeHintsApplicationInput, ) => Promise; afterSuccessfulTeardown?: (session: SessionState) => Promise; + onFailedSteps?: (steps: string[]) => void; + providerInstanceEnded?: () => boolean; }): Promise { const { ref, @@ -319,7 +328,7 @@ export async function teardownDaemonSessionForShutdown(params: { // still owns the daemon lock. It is intentionally outside the generic // teardown race so lock release and runtime shutdown cannot overtake it. - const appLogTeardownSucceeded = await settleDaemonTeardownStep({ + const appLogFailures = await settleDaemonTeardownStep({ session, stderr, resource: 'app-log', @@ -327,7 +336,7 @@ export async function teardownDaemonSessionForShutdown(params: { }); const sessionAfterAppLog = sessionStore.resolveCurrent(ref) ?? session; const teardown = (async () => { - const genericTeardownSucceeded = await settleDaemonTeardownStep({ + const resourceFailures = await settleDaemonTeardownStep({ session, stderr, resource: 'session', @@ -337,9 +346,10 @@ export async function teardownDaemonSessionForShutdown(params: { ref, sessionStore, platformCleanup, + providerInstanceEnded: params.providerInstanceEnded, }), }); - const lifecycleTeardownSucceeded = finalizeApplicationLifecycle + const lifecycleFailures = finalizeApplicationLifecycle ? await settleDaemonTeardownStep({ session, stderr, @@ -347,22 +357,25 @@ export async function teardownDaemonSessionForShutdown(params: { teardown: async () => await finalizeApplicationLifecycle(sessionAfterAppLog, runtimeHints), }) - : true; - return genericTeardownSucceeded && lifecycleTeardownSucceeded; + : []; + return [...resourceFailures, ...lifecycleFailures]; })(); let timedOut = false; - let genericTeardownSucceeded = false; + let genericFailures = ['session_teardown']; try { const teardownOutcome = await settleWithin(async () => await teardown, timeoutMs); if (teardownOutcome.kind === 'deadline') timedOut = true; - else genericTeardownSucceeded = teardownOutcome.value; + else genericFailures = teardownOutcome.value; } catch { // A teardown that rejects is a failed teardown; its own step already wrote why to stderr. } if (timedOut) { stderr.write(`Daemon session teardown timed out (${session.name}).\n`); + genericFailures = ['session_teardown_timeout']; } - const teardownSucceeded = appLogTeardownSucceeded && genericTeardownSucceeded; + const failedSteps = [...appLogFailures, ...genericFailures]; + const teardownSucceeded = failedSteps.length === 0; + params.onFailedSteps?.(failedSteps); // ADR 0012 decision 6, R7 + commit semantics (C2/C5a): commit the healed // `.ad` iff the repair transaction completed, else leave a bounded // `REPAIR_SESSION_EXPIRED` tombstone for the reaped-before-finalize case. @@ -371,3 +384,37 @@ export async function teardownDaemonSessionForShutdown(params: { sessionStore.retire(ref); return teardownSucceeded; } + +export async function teardownDaemonSessions( + sessionStore: SessionStore, + teardown: (ref: SessionRef) => Promise<{ closed: boolean; failedSteps: string[] }>, +) { + sessionStore.closeAdmission(); + const sessionsToStop = sessionStore.listRefs(); + const failedLeases = new Map(); + const outcomes = await Promise.all( + sessionsToStop.map(async (ref) => { + const result = await teardown(ref).catch(() => undefined); + const failedSteps = result?.failedSteps ?? ['session_teardown']; + const { name, lease } = ref.session; + if (lease && failedSteps.length > 0) { + const { leaseId, deviceKey } = lease; + failedLeases.set(leaseId, [ + ...new Set([...(failedLeases.get(leaseId) ?? []), ...failedSteps]), + ]); + emitDiagnostic({ + phase: 'leased_session_ended', + level: 'warn', + data: { reason: 'DAEMON_SHUTDOWN', leaseId, session: name, deviceKey, failedSteps }, + }); + } + return result?.closed ?? false; + }), + ); + await sessionStore.flushJournalRemovals(); + const closedCount = outcomes.filter(Boolean).length; + return { + sessions: { closed: closedCount, failed: outcomes.length - closedCount }, + failedLeases, + }; +} diff --git a/packages/daemon/src/server/lease-session-end.ts b/packages/daemon/src/server/lease-session-end.ts new file mode 100644 index 0000000000..b1ffcc80a3 --- /dev/null +++ b/packages/daemon/src/server/lease-session-end.ts @@ -0,0 +1,421 @@ +import { awaitWithSignal } from '@agent-device/kernel/await-with-signal'; +import { AsyncResource } from 'node:async_hooks'; +import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import { AppError, errorMessage } from '@agent-device/kernel/errors'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { settleWithin } from '@agent-device/host-kit/settle-within'; +import type { SessionStore } from '../core/session-store.ts'; +import type { SessionRef } from '../core/session-state.ts'; +import type { PlatformResourceCleanup } from '../core/platform-resource-cleanup.ts'; +import { + endLeasedSession, + type LeaseEndReason, + type SessionTeardown, +} from '../sessions/lease-lifecycle.ts'; +import { existingSessionExecutionLockKeys } from './request-binding.ts'; +import { withRequestExecutionLockKeys } from './request-execution-locks.ts'; + +export type ExpirySettlement = { + done: Promise; + takeReceipt(): boolean; +}; + +export type Admission = + | { kind: 'admitted' } + | { kind: 'replan' } + | { + kind: 'need-settlement'; + settlement: ExpirySettlement; + ownerLeaseId?: string; + successorIsCurrent?: () => boolean; + } + | { kind: 'refused'; error: AppError }; + +export type LockedAttempt = + | Exclude + | { kind: 'admitted'; value: T }; +export type NeedSettlement = Extract; + +export type ExpiryProviderSettlement = { + done: Promise; + allowRelease(): void; +}; + +export type LeaseSessionEnd = Readonly<{ + /** + * Ends sessions and retained execution hosts owned by `leaseId` under their execution locks. + * Clears live sessions' device claims after teardown. Never rejects. + */ + end: ( + leaseId: string, + reason: LeaseEndReason, + providerEnd?: ExpiryProviderSettlement, + ) => Promise; + closingAt(address: string): SessionRef | undefined; + forgetClosing(leaseId: string): void; + settlementFor: (lifetime: SessionRef['lifetime']) => ExpirySettlement | undefined; + /** Retries retained-host cleanup that failed after the registry removed its lease. */ + retryPending: () => Promise; + finishShutdown: (failedLeases: Map, timeoutMs: number) => Promise; + /** + * Called when the daemon begins to leave. Shutdown tears every session down without taking an + * execution lock, so no lease end may start a teardown after this, including one already queued + * on the locks. + */ + cancel: () => void; + /** Resolves once every lease end already started has finished. */ + drain: () => Promise; +}>; + +const LEASE_END_RETRY_INTERVAL_MS = 10_000; + +export const EXPIRY_TRANSITIONS = { + expired: ['open', 'closing'], + retry: ['cleanup-pending', 'closing'], + settled: ['closing', 'retired'], + incomplete: ['closing', 'cleanup-pending'], +} as const; + +export function createLeaseSessionEnd(params: { + env: HostEnvironment['env']; + sessionStore: SessionStore; + executionLocks: Map>; + teardownSession: SessionTeardown; + cleanupSessionlessExecutionHost: PlatformResourceCleanup['cleanupSessionlessExecutionHost']; + withinDiagnosticsScope?: (run: () => Promise) => Promise; + confirmExpiredSessions?: (leaseId: string) => boolean; +}): LeaseSessionEnd { + const { sessionStore, executionLocks, teardownSession } = params; + let closing = false; + const inFlight = new Map>>(); + const pending = new Map< + string, + { + reason: LeaseEndReason; + nextRetryAt: number; + provider?: ExpiryProviderSettlement; + } + >(); + const closingRefs = new Map(); + const collectClosingRefs = (leaseId: string) => { + for (const ref of sessionStore.leasedSessionRefs(leaseId)) closingRefs.set(ref.address, ref); + return [...closingRefs.values()].filter((ref) => ref.session.lease?.leaseId === leaseId); + }; + const forgetClosing = (leaseId: string) => { + for (const [address, ref] of closingRefs) { + if (ref.session.lease?.leaseId === leaseId) closingRefs.delete(address); + } + }; + const settlements = new WeakMap(); + const daemonContext = new AsyncResource('LeaseExpiry'); + const diagnosticIdentity = ({ session }: SessionRef) => ({ + session: session.name, + deviceKey: session.lease?.deviceKey, + leaseId: params.withinDiagnosticsScope ? session.lease?.leaseId : undefined, + }); + const teardownForLeaseEnd = async (ref: SessionRef, reason: LeaseEndReason) => { + const ended = { phase: 'leased_session_ended', data: { reason, ...diagnosticIdentity(ref) } }; + if (reason !== 'PROVIDER_INSTANCE_ENDED') { + emitDiagnostic(ended); + await teardownSession(ref); + return; + } + try { + await teardownSession(ref); + } catch (error) { + const failedSteps = error instanceof AppError ? error.details?.failedSteps : undefined; + emitDiagnostic({ + ...ended, + level: 'warn', + data: { + ...ended.data, + failedSteps: failedSteps ?? ['application_lifecycle'], + error: errorMessage(error), + }, + }); + throw error; + } + emitDiagnostic(ended); + }; + const transitionExpiry = ( + event: keyof typeof EXPIRY_TRANSITIONS, + refs: readonly SessionRef[], + ) => { + const [oldState, newState] = EXPIRY_TRANSITIONS[event]; + const transition = { actor: 'daemon', event, oldState, newState, cause: 'LEASE_EXPIRED' }; + for (const ref of refs) { + emitDiagnostic({ + phase: 'lease_expiry_transition', + data: { ...transition, ...diagnosticIdentity(ref) }, + }); + } + return newState; + }; + const endLiveSessions = async ( + leaseId: string, + reason: LeaseEndReason, + attempted: Set, + ): Promise => { + const refs = sessionStore + .leasedSessionRefs(leaseId) + .filter(({ lifetime }) => !attempted.has(lifetime)); + await Promise.allSettled( + refs.map( + async (ref) => + await withRequestExecutionLockKeys( + executionLocks, + existingSessionExecutionLockKeys(ref.address, ref.session.device.id), + async () => { + if (closing) return; + const current = sessionStore.resolveCurrent(ref); + if ( + current?.lease?.leaseId !== leaseId || + current.device.id !== ref.session.device.id || + current.deviceClaim !== ref.session.deviceClaim + ) + return; + attempted.add(ref.lifetime); + await endLeasedSession( + sessionStore.refresh(ref), + sessionStore, + (currentRef) => teardownForLeaseEnd(currentRef, reason), + params.env, + ).catch((error) => + emitDiagnostic({ + level: 'warn', + phase: 'leased_session_end_cleanup_failed', + data: { session: ref.address, error: errorMessage(error) }, + }), + ); + }, + ), + ), + ); + }; + + const endRetainedHosts = async (leaseId: string, reason: LeaseEndReason, shutdown = false) => { + // A close queued before this lease end can retire its session while we wait for its locks. + const retainedHosts = sessionStore.listRetainedExecutionHosts(leaseId); + await Promise.all( + retainedHosts.map(async (host) => { + try { + const stop = async () => { + if (!sessionStore.ownsRetainedExecutionHost(host)) return; + if (!sessionStore.findByDevice(host.device.id)) { + await params.cleanupSessionlessExecutionHost(host.device); + } + sessionStore.releaseRetainedExecutionHost(host); + }; + if (shutdown) return await stop(); + await withRequestExecutionLockKeys( + executionLocks, + existingSessionExecutionLockKeys(host.address, host.device.id), + async () => { + if (!closing) await stop(); + }, + ); + } catch (error) { + emitDiagnostic({ + level: 'warn', + phase: 'retained_execution_host_cleanup_failed', + data: { leaseId, reason, deviceId: host.device.id, error: errorMessage(error) }, + }); + } + }), + ); + }; + + const endUnderLocks = async (leaseId: string, reason: LeaseEndReason): Promise => { + const attempted = new Set(); + await endLiveSessions(leaseId, reason, attempted); + await endRetainedHosts(leaseId, reason); + // A reopen can publish its same-lease session while retained-host cleanup waits for the device. + await endLiveSessions(leaseId, reason, attempted); + }; + + const run = async ( + leaseId: string, + reason: LeaseEndReason, + provider?: ExpiryProviderSettlement, + ): Promise => { + try { + await endUnderLocks(leaseId, reason); + } catch (error) { + emitDiagnostic({ + level: 'warn', + phase: 'leased_session_end_failed', + data: { leaseId, reason, error: errorMessage(error) }, + }); + } finally { + if (cleanupConfirmed(leaseId)) { + pending.delete(leaseId); + } else if (!closing) { + pending.set(leaseId, { + reason, + provider, + nextRetryAt: Date.now() + LEASE_END_RETRY_INTERVAL_MS, + }); + } + } + }; + + const cleanupConfirmed = (leaseId: string) => + sessionStore.listRetainedExecutionHosts(leaseId).length === 0 && + sessionStore.leasedSessionRefs(leaseId).length === 0; + + const confirmSessionCleanup = (leaseId: string, provider?: ExpiryProviderSettlement) => { + const confirmed = params.confirmExpiredSessions?.(leaseId) ?? true; + if (confirmed) forgetClosing(leaseId); + provider?.allowRelease(); + return confirmed; + }; + + const registerExpiry = ( + leaseId: string, + refs: readonly SessionRef[], + cleanup: Promise, + provider?: ExpiryProviderSettlement, + ) => { + let reported = false; + const done = cleanup.then(async (retired) => { + if (!retired) return false; + const settled = confirmSessionCleanup(leaseId, provider); + await provider?.done; + if (settled) return true; + const confirmed = params.confirmExpiredSessions?.(leaseId) ?? true; + if (confirmed) forgetClosing(leaseId); + return confirmed; + }); + const settlement: ExpirySettlement = { + done, + takeReceipt: () => { + if (reported) return false; + reported = true; + return true; + }, + }; + for (const { lifetime } of refs) settlements.set(lifetime, settlement); + }; + + const end = async ( + leaseId: string, + reason: LeaseEndReason, + providerEnd?: ExpiryProviderSettlement, + ): Promise => { + if (closing && !providerEnd) return; + const expiry = reason === 'LEASE_EXPIRED'; + const previous = pending.get(leaseId); + const provider = providerEnd ?? previous?.provider; + const settlement = expiry || provider !== undefined; + const existing = inFlight.get(leaseId); + if (settlement && existing) { + if (!expiry) await Promise.all(existing); + return; + } + pending.set(leaseId, { reason, provider, nextRetryAt: 0 }); + if (closing) return; + const refs = settlement ? collectClosingRefs(leaseId) : []; + const runScoped = async (): Promise => { + let retired = false; + const cleanup = async () => { + if (expiry) transitionExpiry(previous ? 'retry' : 'expired', refs); + await run(leaseId, reason, provider); + retired = !pending.has(leaseId); + if (expiry) + retired = transitionExpiry(retired ? 'settled' : 'incomplete', refs) === 'retired'; + }; + await (params.withinDiagnosticsScope?.(cleanup) ?? cleanup()).catch((error) => { + emitDiagnostic({ + level: 'warn', + phase: 'leased_session_end_failed', + data: { reason, error: errorMessage(error) }, + }); + }); + return retired; + }; + // This promise enters a daemon context on its next turn, with no inherited request locks. + const cleanup = settlement + ? daemonContext.runInAsyncScope(() => Promise.resolve().then(runScoped)) + : runScoped(); + const ending = cleanup.then(() => {}); + if (settlement) registerExpiry(leaseId, refs, cleanup, provider); + const running = inFlight.get(leaseId) ?? new Set>(); + running.add(ending); + inFlight.set(leaseId, running); + try { + await ending; + } finally { + running.delete(ending); + if (running.size === 0) inFlight.delete(leaseId); + } + }; + + return { + end, + closingAt: (address) => closingRefs.get(address), + forgetClosing, + settlementFor: (lifetime) => settlements.get(lifetime), + finishShutdown: async (failedLeases, timeoutMs) => { + await settleWithin( + async () => + await Promise.all( + [...pending].map(async ([leaseId, { reason }]) => { + if (!failedLeases.has(leaseId)) await endRetainedHosts(leaseId, reason, true); + }), + ), + timeoutMs, + ); + for (const [leaseId, { provider }] of pending) { + if (!failedLeases.has(leaseId) && cleanupConfirmed(leaseId)) { + pending.delete(leaseId); + confirmSessionCleanup(leaseId, provider); + continue; + } + // Shutdown has retired the sessions. Provider disposal can proceed even if local effects remain. + provider?.allowRelease(); + if (failedLeases.has(leaseId)) continue; + const failedSteps = ['retained_execution_host']; + failedLeases.set(leaseId, failedSteps); + emitDiagnostic({ + phase: 'leased_session_ended', + level: 'warn', + data: { reason: 'DAEMON_SHUTDOWN', leaseId, failedSteps }, + }); + } + }, + retryPending: async () => { + await Promise.all( + Array.from(pending, async ([leaseId, { reason, nextRetryAt }]) => { + if (!inFlight.has(leaseId) && Date.now() >= nextRetryAt) await end(leaseId, reason); + }), + ); + }, + cancel: () => { + closing = true; + }, + drain: async () => { + await Promise.allSettled(Array.from(inFlight.values()).flatMap((running) => [...running])); + }, + }; +} + +export async function awaitExpiry( + done: Promise, + signal: AbortSignal, + deadline: number, +): Promise { + signal.throwIfAborted(); + const remaining = deadline - Date.now(); + if (remaining <= 0) return false; + if (!Number.isFinite(remaining)) return await awaitWithSignal(done, signal); + const budget = new AbortController(); + const timer = setTimeout(() => budget.abort(), remaining); + try { + return await awaitWithSignal(done, AbortSignal.any([signal, budget.signal])); + } catch (error) { + if (signal.aborted || !budget.signal.aborted) throw error; + return false; + } finally { + clearTimeout(timer); + } +} diff --git a/packages/daemon/src/server/provider-lease-expiry.ts b/packages/daemon/src/server/provider-lease-expiry.ts index 5b522b6077..cda34b1b94 100644 --- a/packages/daemon/src/server/provider-lease-expiry.ts +++ b/packages/daemon/src/server/provider-lease-expiry.ts @@ -1,3 +1,4 @@ +import { AsyncResource } from 'node:async_hooks'; import fs from 'node:fs'; import path from 'node:path'; import type { @@ -73,7 +74,10 @@ export type ExpiredProviderLeaseReleaser = { * providers may already be disposed. A recoverable lease is still made durable for the next daemon, * which is what the outcome's `durable` answers. */ - release: (lease: DeviceLease) => Promise; + release: ( + lease: DeviceLease, + afterSessionCleanup?: Promise, + ) => Promise; /** Journals the registry's live provider leases, so a daemon killed while holding them recovers them. */ recordLiveLeases: (leases: readonly DeviceLease[]) => void; /** @@ -104,6 +108,8 @@ export function createExpiredProviderLeaseReleaser(options: { stateDir?: string; recoverableProviderIds?: readonly string[]; retryDelayMs?: number; + onRecovered?: (lease: DeviceLease) => void; + onReleased?: (lease: DeviceLease) => void; /** Gives a timer-driven retry, which runs outside any request, a diagnostics scope. */ withinDiagnosticsScope?: (run: () => Promise) => Promise; }): ExpiredProviderLeaseReleaser { @@ -114,6 +120,8 @@ export function createExpiredProviderLeaseReleaser(options: { const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS; let retryTimer: Timer | undefined; const activeReleaseAttempts = new Map>(); + const releaseContext = new AsyncResource('ProviderLeaseExpiry'); + const sessionCleanup = new Map>(); let phase: ReleaserPhase = 'running'; /** The releases this drain window observed; replaced at each window so one window's set is never another's. */ let drainReleasedLeases = new Map(); @@ -144,6 +152,7 @@ export function createExpiredProviderLeaseReleaser(options: { const recordReleasedLease = (lease: DeviceLease): void => { // The drain window is the only period that reports releases, so the phase is the tracker and the // set cannot grow outside it. + options.onReleased?.(lease); if (phase === 'draining') drainReleasedLeases.set(lease.leaseId, lease); }; @@ -245,6 +254,7 @@ export function createExpiredProviderLeaseReleaser(options: { } for (const leaseId of pendingRecoveryLeases.keys()) persistedRecoveryLeaseIds.add(leaseId); adoptOrphanedLeases(onDiagnostic); + for (const lease of pendingRecoveryLeases.values()) options.onRecovered?.(lease); await retryPending(); }; const recordLiveLeases = (leases: readonly DeviceLease[]): void => { @@ -296,19 +306,29 @@ export function createExpiredProviderLeaseReleaser(options: { return attempt; }; + const startReleaseAttempt = (leaseId: string, key: string, run: () => Promise) => { + const after = sessionCleanup.get(leaseId); + const attempt = after + ? releaseContext.runInAsyncScope(async () => { + await after; + if (phase !== 'closed') await (options.withinDiagnosticsScope?.(run) ?? run()); + }) + : run(); + return trackReleaseAttempt(key, attempt); + }; + const ensureLiveReleaseAttempt = (lease: DeviceLease): Promise | undefined => { if (phase === 'closed') return undefined; if (!isProviderRuntimeAvailable(lease, options.providerRuntimeIds)) return undefined; const key = `live:${lease.leaseId}`; const activeAttempt = activeReleaseAttempts.get(key); if (activeAttempt) return activeAttempt; - const attempt = (async (): Promise => { + return startReleaseAttempt(lease.leaseId, key, async () => { if (await releaseLiveProviderLease(options.leaseLifecycleProvider, lease)) { pendingLiveLeases.delete(lease.leaseId); recordReleasedLease(lease); } - })(); - return trackReleaseAttempt(key, attempt); + }); }; const ensureRecoveryReleaseAttempt = (lease: DeviceLease): Promise | undefined => { @@ -318,14 +338,13 @@ export function createExpiredProviderLeaseReleaser(options: { const key = `recovery:${lease.leaseId}`; const activeAttempt = activeReleaseAttempts.get(key); if (activeAttempt) return activeAttempt; - const attempt = (async (): Promise => { + return startReleaseAttempt(lease.leaseId, key, async () => { if (await releaseExpiredProviderLease(options.recoverExpiredLease, lease)) { pendingRecoveryLeases.delete(lease.leaseId); recordReleasedLease(lease); persistPendingLeases(); } - })(); - return trackReleaseAttempt(key, attempt); + }); }; const retryPending = async (): Promise => { @@ -376,9 +395,16 @@ export function createExpiredProviderLeaseReleaser(options: { advancePhase('draining'); drainReleasedLeases = new Map(); }, - release: async (lease) => { + release: async (lease, afterSessionCleanup) => { if (!lease.leaseProvider) return { status: 'not-required' }; if (phase === 'closed') return refuseClosedRelease(lease); + if (afterSessionCleanup) { + sessionCleanup.set(lease.leaseId, afterSessionCleanup); + const forget = () => { + sessionCleanup.delete(lease.leaseId); + }; + void afterSessionCleanup.then(forget, forget); + } if (isRecoverableProviderAvailable(lease, options.recoverableProviderIds)) { // Set before the first await: the registry journals right after `onLeaseExpired` returns, and the // journal keeps this lease only while it is pending here and not yet durable. diff --git a/packages/daemon/src/server/request-binding.ts b/packages/daemon/src/server/request-binding.ts index 33a36e5386..3bcd486308 100644 --- a/packages/daemon/src/server/request-binding.ts +++ b/packages/daemon/src/server/request-binding.ts @@ -54,29 +54,27 @@ export type LockedRequestBinding = { existingRef: SessionRef | undefined; }; -export async function resolveRequestExecutionLockPlan(params: { +export function resolveRequestExecutionLockPlan(params: { req: DaemonRequest; sessionName: string; - sessionStore: SessionStore; -}): Promise { - const { req, sessionName, sessionStore } = params; - const existingSession = sessionStore.get(sessionName); - if (existingSession) { + existingDeviceId?: string; + env: EnvMap; +}): RequestExecutionLockPlan | Promise { + const { req, sessionName, existingDeviceId, env } = params; + if (existingDeviceId !== undefined) { return { - keys: existingSessionExecutionLockKeys(sessionName, existingSession.device.id), - deviceId: existingSession.device.id, + keys: existingSessionExecutionLockKeys(sessionName, existingDeviceId), + deviceId: existingDeviceId, }; } - const keys = new Set([sessionExecutionLockKey(sessionName)]); - const device = await resolveFreshSessionDevice(req, sessionStore.host.env); - // A fresh app device `open` also locks its host (ADR 0035), before its own lock, so an - // `open --wait` looks at the host's sessions under a lock a whole-host open also takes. A replay - // or batch holds its locks for its whole run, so it locks only its device: the first-open lock - // keyed by host still serializes its opens. An open app session's commands lock only the app. - const ids = !device ? [] : req.command === 'open' ? hostAndDeviceIds(device) : [device.id]; - for (const id of ids) keys.add(deviceExecutionLockKey(id)); - return { keys: orderRequestExecutionLockKeys(keys), deviceId: device?.id }; + return resolveFreshSessionDevice(req, env).then((device) => { + const keys = new Set([sessionExecutionLockKey(sessionName)]); + // A fresh app open also locks its host (ADR 0035). A composite locks only its device. + const ids = !device ? [] : req.command === 'open' ? hostAndDeviceIds(device) : [device.id]; + for (const id of ids) keys.add(deviceExecutionLockKey(id)); + return { keys: orderRequestExecutionLockKeys(keys), deviceId: device?.id }; + }); } async function resolveFreshBoundedOpenDevice(req: DaemonRequest, env: EnvMap): Promise { diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index d8aeb3abe1..34d0d79bb9 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -1,3 +1,5 @@ +import { heldKeyedLockKeys } from '@agent-device/kernel/keyed-lock'; +import { LEASE_REASONS } from '@agent-device/contracts/lease-scope'; import { restrictRemoteHostInputs } from './remote-host-input-policy.ts'; import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -19,7 +21,7 @@ import { getDiagnosticsMeta, updateDiagnosticsScope, } from '@agent-device/host-kit/diagnostics'; -import { AppError, errorMessage } from '@agent-device/kernel/errors'; +import { AppError } from '@agent-device/kernel/errors'; import { type DaemonCommandContext, contextFromFlags as contextFromFlagsWithLog, @@ -30,6 +32,7 @@ import { resolveCallerScopeRoot, resolveSessionScope } from '../sessions/session import { deriveWebSessionIdentity } from '../core/session-tenant-scope.ts'; import { assertProviderLeaseRequestNamesSession, + assertRequestLeaseAdmission, assertRequestLeaseAdmissionPreflight, assertRequestTenantAdmission, resolveRequestSessionName, @@ -38,19 +41,12 @@ import { scopeRequestSession, withTenantAdmissionOnRoutingError, } from '../sessions/request-admission.ts'; -import { isBoundedCompositeRequest } from '../core/lease-context.ts'; +import { isBoundedCompositeRequest, resolveLeaseScope } from '../core/lease-context.ts'; import { admitRequestLeaseForLockedScope, - cleanupExpiredLeasedSession, - endLeasedSession, - type ExpiredSessionTeardown, - resolveLockedRequestSessionRef, inspectSessionProviderReleaseOnClose, - type LeaseEndReason, - type SessionTeardown, } from '../sessions/lease-lifecycle.ts'; import { - existingSessionExecutionLockKeys, prepareLockedRequestBinding, resolveBoundedClaimDevice, resolveRequestExecutionLockPlan, @@ -67,7 +63,11 @@ import { createSessionExecutionLock, withRequestExecutionLockKeys, } from './request-execution-locks.ts'; -import { isRequestCanceled, throwIfRequestCanceled } from '@agent-device/host-kit/request'; +import { + getRequestDeadlineMs, + isRequestCanceled, + throwIfRequestCanceled, +} from '@agent-device/host-kit/request'; import { assertSameOpenOwner, SessionCoordinator, @@ -75,9 +75,10 @@ import { } from '../core/session-store.ts'; import { finalizeDaemonResponse } from './request-finalization.ts'; import { refreshRecordingHealth } from '../sessions/request-recording-health.ts'; -import { retainSuccessorLeaseWork, runAdmittedLeaseWork } from './request-lease-work.ts'; +import { inactiveLease, runAdmittedLeaseWork } from './request-lease-work.ts'; import { assertMacOsAppLeaseProcess } from '../resources/macos-app-lease.ts'; import { + ignoresSessionLease, shouldBlockForInvalidRecording, shouldLockSessionExecution, shouldValidateSessionSelector, @@ -86,7 +87,15 @@ import { shouldRecordEventForRequest, type BoundJournal, } from '@agent-device/session-journal/session-event-log'; -import type { LeaseRegistry, RetainedLeaseWork } from '../resources/lease-registry.ts'; +import type { + Admission, + LeaseSessionEnd, + LockedAttempt, + NeedSettlement, +} from './lease-session-end.ts'; +import { deviceLeaseBusyError } from '../resources/lease-registry-scope.ts'; +import type { LeaseRegistry } from '../resources/lease-registry.ts'; +import { recordEndedLease } from '../core/request-ended-leases.ts'; import type { DaemonRequest } from '../core/daemon-request.ts'; import type { SessionRef, SessionState } from '../core/session-state.ts'; import type { DeviceRuntimeGateway } from '@agent-device/contracts/platform-runtime'; @@ -107,7 +116,6 @@ import { applyCommandDefaults, resolveCommandDeviceClaimPolicy, } from '@agent-device/command-registry/registry'; -import type { PlatformResourceCleanup } from '../core/platform-resource-cleanup.ts'; import type { DaemonPlatformServices } from '../core/platform-services.ts'; import { assertDaemonPolicyAdmitsDevice, @@ -120,22 +128,6 @@ import { type RequestDispatchLedger, } from '../core/request-dispatch-ledger.ts'; -const expiredSessionSettleNotComposed: SessionTeardown = async () => { - throw new AppError( - 'INTERNAL_ERROR', - 'Expired-session teardown was not supplied by root runtime composition', - ); -}; - -function expiredSessionTeardown( - command: string, - holdsSessionLock: boolean, - boundedStep: boolean, -): ExpiredSessionTeardown { - if (!holdsSessionLock) return 'lease-end-owner'; - return command === 'batch' || command === 'replay' || boundedStep ? 'refuse' : 'inline'; -} - // Production daemon wiring owns one LeaseRegistry per process; scoping locks by registry keeps // test and embedded routers isolated without changing process-level serialization there. const leaseRegistryExecutionLocks = new WeakMap>>(); @@ -153,7 +145,10 @@ export type RequestExecutionScope = AsyncDisposable & { admittedRef?: SessionRef; requestLogPath: string; runnerLogPath: string; - runAdmitted(task: () => Promise): Promise; + runAdmitted( + task: () => Promise, + admitted?: { ref: SessionRef | undefined; assertSuccessorCurrent?: () => void }, + ): Promise; runLocked(task: () => Promise): Promise; /** Takes an available session lock and runs `task` if the admitted lifetime is still live. */ tryRunUnderSessionLock(ref: SessionRef, task: () => Promise): Promise; @@ -211,8 +206,7 @@ export async function createRequestExecutionScope(params: { claimRecoveryGateway: ClaimRecoveryGatewayFactory; trackClaimRecoveryDisposal: (disposal: Promise) => void; platformRequestScope: PlatformRequestScope; - /** The daemon-owned teardown of a session whose lease expired (root runtime composition). */ - settleExpiredSession?: SessionTeardown; + leaseSessionEnd?: Pick; providerAppCatalog?: ProviderAppCatalog; pluginInventory?: readonly PluginInventoryEntry[]; daemonPolicy?: DaemonPolicy; @@ -236,10 +230,8 @@ export async function createRequestExecutionScope(params: { const command = scopedReq.command; const startedAtMs = Date.now(); - // The one trait that says a request acts *through* a session rather than merely resolving one: - // it is what puts the session's execution lock in this request's plan, and therefore the only - // trait under which an activity stamp can be written while holding that lock. const attachesToSession = shouldLockSessionExecution(command); + const readsSessionLease = !ignoresSessionLease(command); const sessionName = resolveRequestSessionName({ scopedReq, unscopedReq, sessionStore }); const sessionDir = sessionStore.resolveSessionDir(sessionName); const requestLog = resolveSessionRequestLog({ @@ -289,33 +281,108 @@ export async function createRequestExecutionScope(params: { : undefined; if (devicePin && pinPolicy) pinPolicy.assertRequestHonorsDevicePin(devicePin, scopedReq); if (params.daemonPolicy) assertDaemonPolicyAdmitsRequest(params.daemonPolicy, scopedReq); - const preflightSession = sessionStore.get(sessionName); + const readAddressed = () => + sessionStore.lookup(sessionName) ?? params.leaseSessionEnd?.closingAt(sessionName); + const preflightRef = readAddressed(); + const preflightSession = preflightRef?.session; assertProviderLeaseRequestNamesSession(scopedReq, preflightSession); assertRequestLeaseAdmissionPreflight(scopedReq, preflightSession); // Parse the budget once, before resolving the target device or taking any lock. The lock plan // still supplies the device to wait for, but an out-of-range budget is refused before either. const openWaitBudgetMs = scopedReq.command === 'open' ? readOpenWaitBudgetMs(scopedReq) : undefined; - const lockPlan: RequestExecutionLockPlan = shouldLockSessionExecution(command) - ? await resolveRequestExecutionLockPlan({ req: scopedReq, sessionName, sessionStore }) - : { keys: [], deviceId: undefined }; - // An `--wait ` open spends the first of its budget here, while the request holds no locks - // yet: the device execution lock is what every operation that could free the device also - // needs, so waiting after taking it would have an open block its own recovery. - const openWait = beginOpenDeviceWait({ - req: scopedReq, - budgetMs: openWaitBudgetMs, - sessionName, - sessionStore, - deviceId: lockPlan.deviceId, - }); - await openWait?.waitForDeviceOutsideLocks(); const executionLocks = getLeaseRegistryExecutionLocks(leaseRegistry); - const requestExecutionLocks = createRequestExecutionLocks({ - locks: executionLocks, - initialKeys: lockPlan.keys, - scope: params.platformRequestScope, - }); + const outerKeys = heldKeyedLockKeys(executionLocks); + const hasOuterLocks = outerKeys.length > 0; + const sessionKey = sessionExecutionLockKey(sessionName); + const signal = params.platformRequestScope.signal; + const waitDeadline = openWaitBudgetMs === undefined ? Infinity : startedAtMs + openWaitBudgetMs; + const leaseAdmission = { ...params, env: params.host.env, inspectOnly: true }; + const settlementFor = (ref: SessionRef | undefined) => + ref && params.leaseSessionEnd?.settlementFor(ref.lifetime); + const isInactive = (ref: SessionRef | undefined) => { + const lease = readsSessionLease && ref?.session.lease; + return Boolean(lease && !leaseRegistry.inspectActiveLease(lease.leaseId)); + }; + const authenticateExpiry = async (ref: SessionRef, leaseId: string) => { + assertRequestTenantAdmission(unscopedReq, ref.session); + const presented = resolveLeaseScope(scopedReq).leaseId; + const successor = + command === 'open' && presented && presented !== leaseId + ? assertRequestLeaseAdmission(scopedReq, leaseRegistry, undefined, leaseAdmission) + : undefined; + if (!successor) { + resolveRequestSessionRef(scopedReq, ref); + return undefined; + } + const isCurrent = leaseRegistry.pinActiveLease(successor.leaseId); + if (successor.backend === 'macos-app') { + await assertMacOsAppLeaseProcess(successor); + throwIfRequestCanceled(scopedReq.meta?.requestId); + if (!isCurrent()) throw inactiveLease(); + assertRequestLeaseAdmission(scopedReq, leaseRegistry, undefined, leaseAdmission); + } + return isCurrent; + }; + const resolveExpiryAdmission = async ( + ref: SessionRef | undefined, + settlement = settlementFor(ref), + ): Promise => { + if (!ref || !readsSessionLease) return { kind: 'admitted' }; + const lease = ref.session.lease; + if (!lease || (!settlement && !isInactive(ref))) return { kind: 'admitted' }; + const successorIsCurrent = await authenticateExpiry(ref, lease.leaseId); + if (!settlement) { + leaseRegistry.consumeExpiredLease(lease.leaseId); + settlement = settlementFor(ref); + if (!settlement && !isInactive(ref)) return { kind: 'admitted' }; + } + if (!settlement || hasOuterLocks) return { kind: 'refused', error: inactiveLease() }; + return { + kind: 'need-settlement', + settlement, + successorIsCurrent, + ownerLeaseId: successorIsCurrent ? undefined : lease.leaseId, + }; + }; + const readNestedAddress = async () => { + const addressed = readAddressed(); + const expiry = await resolveExpiryAdmission(addressed); + if (expiry.kind !== 'admitted') + throw expiry.kind === 'refused' ? expiry.error : inactiveLease(); + return addressed; + }; + const admitLease = (ref: SessionRef | undefined, assertCurrent?: () => void) => { + assertCurrent?.(); + return admitRequestLeaseForLockedScope({ + env: params.host.env, + req: scopedReq, + session: ref?.session, + leaseRegistry, + providerAppCatalog: params.providerAppCatalog, + pluginInventory: params.pluginInventory, + daemonPolicy: params.daemonPolicy, + }); + }; + const waitForSettlement = async (attempt: NeedSettlement) => { + const { awaitExpiry } = await import('./lease-session-end.ts'); + const deadline = getRequestDeadlineMs(scopedReq.meta?.requestId) ?? Infinity; + const settled = await awaitExpiry( + attempt.settlement.done, + signal, + Math.min(waitDeadline, deadline), + ); + throwIfRequestCanceled(scopedReq.meta?.requestId); + if (attempt.ownerLeaseId) { + if (settled && command === 'close' && attempt.settlement.takeReceipt()) + recordEndedLease(scopedReq, attempt.ownerLeaseId); + throw inactiveLease(); + } + if (!attempt.successorIsCurrent?.()) throw inactiveLease(); + if (!settled) throw deviceLeaseBusyError(); + return attempt.successorIsCurrent; + }; + let requestExecutionLocks: ReturnType | undefined; const dispatchLedger = requestDispatchLedger(scopedReq); const { claimAdmission, runtimeBindings } = createRequestDeviceAccess({ env: params.host.env, @@ -349,16 +416,111 @@ export async function createRequestExecutionScope(params: { })(); return bindingCleanup; }; - const runAdmittedAndDispose = async (task: () => Promise): Promise => { + const runAdmittedAttempt = async ( + ref: SessionRef | undefined, + task: () => Promise, + successorIsCurrent: (() => boolean) | undefined, + ): Promise> => { + let acting = false; try { - return await scope.runAdmitted(task); + const value = await scope.runAdmitted( + async () => { + acting = true; + return await task(); + }, + { + ref, + assertSuccessorCurrent: () => { + if (successorIsCurrent && !successorIsCurrent()) throw inactiveLease(); + }, + }, + ); + return { kind: 'admitted', value }; + } catch (error) { + if ( + acting || + !isInactive(ref) || + !(error instanceof AppError) || + error.details?.reason !== LEASE_REASONS.notFound.reason + ) + throw error; + const expiry = await resolveExpiryAdmission(ref); + return expiry.kind === 'admitted' ? { kind: 'replan' } : expiry; } finally { - // The router consumes the same cleanup outcome when it finalizes the response, - // preserving a primary command failure over a secondary disposal failure. - await Promise.allSettled([disposeBindings()]); + if (acting) await Promise.allSettled([disposeBindings()]); } }; + const runLockPlan = async ( + lockPlan: RequestExecutionLockPlan, + task: () => Promise, + successorIsCurrent: (() => boolean) | undefined, + expiryProbe: boolean, + ): Promise> => { + if (successorIsCurrent && !successorIsCurrent()) + return { kind: 'refused', error: inactiveLease() }; + const current = readAddressed(); + if (!lockPlan.keys.length && isInactive(current)) return { kind: 'replan' }; + const admission = await resolveExpiryAdmission(current); + if (admission.kind !== 'admitted') return admission; + if (expiryProbe) return { kind: 'replan' }; + if ( + attachesToSession && + current && + current.session.device.id !== lockPlan.deviceId && + !hasOuterLocks + ) + return { kind: 'replan' }; + + return await runAdmittedAttempt(current, task, successorIsCurrent); + }; + + const lockAndAdmit = async ( + task: () => Promise, + observed: SessionRef | undefined, + pinned: SessionRef | undefined, + successorIsCurrent: (() => boolean) | undefined, + ): Promise> => { + const expired = isInactive(pinned); + const pending = settlementFor(pinned); + if (pending || (expired && outerKeys.includes(sessionKey))) { + const admission = await resolveExpiryAdmission(pinned, pending); + return admission.kind === 'admitted' ? { kind: 'replan' } : admission; + } + const plan = + expired || !attachesToSession + ? { keys: expired ? [sessionKey] : [], deviceId: undefined } + : resolveRequestExecutionLockPlan({ + req: scopedReq, + sessionName, + existingDeviceId: observed?.session.device.id, + env: sessionStore.host.env, + }); + const lockPlan = plan instanceof Promise ? await plan : plan; + const openWait = beginOpenDeviceWait({ + req: scopedReq, + budgetMs: + openWaitBudgetMs === undefined ? undefined : Math.max(0, waitDeadline - Date.now()), + sessionName, + sessionStore, + deviceId: lockPlan.deviceId, + }); + if (openWait) await openWait.waitForDeviceOutsideLocks(); + if (settlementFor(pinned)) return { kind: 'replan' }; + requestExecutionLocks = createRequestExecutionLocks({ + locks: executionLocks, + initialKeys: lockPlan.keys, + scope: params.platformRequestScope, + }); + const run = () => runLockPlan(lockPlan, task, successorIsCurrent, expired); + return openWait + ? await openWait.runWhenDeviceIsUnheld({ + acquireLocks: requestExecutionLocks.run, + task: run, + }) + : await requestExecutionLocks.run(run); + }; + const scope: RequestExecutionScope = { host: params.host, req: scopedReq, @@ -367,7 +529,8 @@ export async function createRequestExecutionScope(params: { requestLogPath, runnerLogPath, retainDeviceExecutionLock: async (deviceId) => - await requestExecutionLocks.retainDevice(deviceId), + await (requestExecutionLocks?.retainDevice(deviceId) ?? + scopedReq.internal?.retainDeviceExecutionLock?.(deviceId)), tryRunUnderSessionLock: async (ref, task) => { const key = sessionExecutionLockKey(sessionName); if (executionLocks.has(key)) return; @@ -391,37 +554,16 @@ export async function createRequestExecutionScope(params: { return req; }, recordFinished, - runAdmitted: async (task) => { + runAdmitted: async (task, admitted) => { throwIfRequestCanceled(scopedReq.meta?.requestId); const boundedStep = command !== 'batch' && command !== 'replay' && isBoundedCompositeRequest(scopedReq); - // The session under the lock governs. A refusal here comes before the request inspects a - // resource, ends an expired session or stamps session activity. - const addressed = sessionStore.get(sessionName); - assertRequestTenantAdmission(unscopedReq, addressed); - assertProviderLeaseRequestNamesSession(scopedReq, addressed); - const expiry = { - env: params.host.env, - sessionStore, - leaseRegistry, - teardown: expiredSessionTeardown(command, attachesToSession, boundedStep), - teardownSession: params.settleExpiredSession ?? expiredSessionSettleNotComposed, - }; - let successorWork: RetainedLeaseWork | undefined; + const addressed = admitted ? admitted.ref : await readNestedAddress(); + assertRequestTenantAdmission(unscopedReq, addressed?.session); + assertProviderLeaseRequestNamesSession(scopedReq, addressed?.session); let admissionCompleted = false; try { - const existingRef = await resolveLockedRequestSessionRef({ - ...expiry, - req: scopedReq, - sessionName, - holdDeviceLock: scope.retainDeviceExecutionLock, - admission: params, - onSuccessorAdmitted: (lease) => { - const retained = retainSuccessorLeaseWork(leaseRegistry, scopedReq, lease); - scopedReq = retained.req; - successorWork = retained.work; - }, - }); + const existingRef = resolveRequestSessionRef(scopedReq, addressed); const session = existingRef?.session; const boundedResources = boundedStep ? await import('../core/composite-resource-admission.ts') @@ -486,48 +628,22 @@ export async function createRequestExecutionScope(params: { }); } throwIfRequestCanceled(scopedReq.meta?.requestId); - await cleanupExpiredLeasedSession({ ...expiry, ref: existingRef }); scope.admittedRef = existingRef; - if (!successorWork) { - scopedReq = admitRequestLeaseForLockedScope({ - env: params.host.env, - req: scopedReq, - sessionName, - sessionStore, - leaseRegistry, - providerAppCatalog: params.providerAppCatalog, - pluginInventory: params.pluginInventory, - daemonPolicy: params.daemonPolicy, - resolveSessionRef: (req, ref) => - (scope.admittedRef = resolveRequestSessionRef(req, ref)), - }); - } + scopedReq = admitLease(addressed, admitted?.assertSuccessorCurrent); scope.req = scopedReq; const admittedLease = scopedReq.internal?.admittedLease; if (admittedLease) await assertMacOsAppLeaseProcess(admittedLease); return await runAdmittedLeaseWork({ + assertCurrent: admitted?.assertSuccessorCurrent, leaseRegistry, req: scopedReq, - retainedWork: successorWork, task: async () => { admissionCompleted = true; return await task(); }, }); } finally { - successorWork?.release(); - // The #2833 inactivity deadline is measured from the end of the last admitted command - // that attached to this session, stamped here under the session's execution lock. The lock - // makes this one stamp enough: an expiry has to acquire it too, so it can never catch a - // session mid-command, and one command slower than the window keeps the session it is - // working on — the same guarantee admitted work gives a remote lease (ADR 0007). - // - // Two exclusions carry that parity. Inventory commands (`devices`, `doctor`, `session list`) - // resolve a session address only to locate their own artifacts, so on a shared host they run - // against a session they never act through — stamping there would let a bystander agent's - // polling keep another agent's abandoned claim alive forever. And a request whose client - // hung up preserves nothing, exactly as a canceled request renews no lease: an agent that - // timed out is the behavior this feature exists to catch. + // Stamp completion under the session lock so the idle reaper cannot overtake live work. if ( admissionCompleted && attachesToSession && @@ -537,15 +653,27 @@ export async function createRequestExecutionScope(params: { } } }, - runLocked: async (task) => { - throwIfRequestCanceled(scopedReq.meta?.requestId); - if (!openWait) { - return await requestExecutionLocks.run(async () => await runAdmittedAndDispose(task)); + runLocked: async (task: () => Promise): Promise => { + let pinned = readsSessionLease ? preflightRef : undefined; + let successorIsCurrent: (() => boolean) | undefined; + for (;;) { + throwIfRequestCanceled(scopedReq.meta?.requestId); + const observed = readAddressed(); + if (readsSessionLease) pinned ??= observed; + const attempt = await lockAndAdmit(task, observed, pinned, successorIsCurrent); + switch (attempt.kind) { + case 'admitted': + return attempt.value; + case 'refused': + throw attempt.error; + case 'replan': + if (!settlementFor(pinned)) pinned = undefined; + continue; + case 'need-settlement': + successorIsCurrent = await waitForSettlement(attempt); + pinned = undefined; + } } - return await openWait.runWhenDeviceIsUnheld({ - acquireLocks: requestExecutionLocks.run, - task: async () => await runAdmittedAndDispose(task), - }); }, // Claims outlive the bindings they guard: release only once no device // operation from this request can still run. @@ -794,150 +922,3 @@ export function getLeaseRegistryExecutionLocks( } return locks; } - -export type LeaseSessionEnd = Readonly<{ - /** - * Ends sessions and retained execution hosts owned by `leaseId` under their execution locks. - * Clears live sessions' device claims after teardown. Never rejects. - */ - end: (leaseId: string, reason: LeaseEndReason) => Promise; - /** Retries retained-host cleanup that failed after the registry removed its lease. */ - retryPending: () => Promise; - /** - * Called when the daemon begins to leave. Shutdown tears every session down without taking an - * execution lock, so no lease end may start a teardown after this, including one already queued - * on the locks. - */ - cancel: () => void; - /** Resolves once every lease end already started has finished. */ - drain: () => Promise; -}>; - -const LEASE_END_RETRY_INTERVAL_MS = 10_000; - -export function createLeaseSessionEnd(params: { - env: HostEnvironment['env']; - sessionStore: SessionStore; - executionLocks: Map>; - teardownSession: SessionTeardown; - cleanupSessionlessExecutionHost: PlatformResourceCleanup['cleanupSessionlessExecutionHost']; - withinDiagnosticsScope?: (run: () => Promise) => Promise; -}): LeaseSessionEnd { - const { sessionStore, executionLocks, teardownSession } = params; - let closing = false; - const inFlight = new Map>>(); - const pending = new Map(); - - const endLiveSessions = async (leaseId: string, reason: LeaseEndReason): Promise => { - const refs = sessionStore.leasedSessionRefs(leaseId); - await Promise.all( - refs.map( - async (ref) => - await withRequestExecutionLockKeys( - executionLocks, - existingSessionExecutionLockKeys(ref.address, ref.session.device.id), - async () => { - if (closing) return; - const current = sessionStore.currentRefForLease(ref, leaseId); - if (!current) return; - await endLeasedSession( - current, - sessionStore, - teardownSession, - reason, - params.env, - true, - ); - }, - ), - ), - ); - }; - - const endUnderLocks = async (leaseId: string, reason: LeaseEndReason): Promise => { - await endLiveSessions(leaseId, reason); - // A close queued before this lease end can retire its session while we wait for its locks. - const retainedHosts = sessionStore.listRetainedExecutionHosts(leaseId); - await Promise.all( - retainedHosts.map(async (host) => { - try { - await withRequestExecutionLockKeys( - executionLocks, - existingSessionExecutionLockKeys(host.address, host.device.id), - async () => { - if (closing || !sessionStore.ownsRetainedExecutionHost(host)) return; - if (!sessionStore.findByDevice(host.device.id)) { - await params.cleanupSessionlessExecutionHost(host.device); - } - sessionStore.releaseRetainedExecutionHost(host); - }, - ); - } catch (error) { - emitDiagnostic({ - level: 'warn', - phase: 'retained_execution_host_cleanup_failed', - data: { leaseId, reason, deviceId: host.device.id, error: errorMessage(error) }, - }); - } - }), - ); - // A reopen can publish its same-lease session while retained-host cleanup waits for the device. - await endLiveSessions(leaseId, reason); - }; - - const run = async (leaseId: string, reason: LeaseEndReason): Promise => { - try { - await endUnderLocks(leaseId, reason); - } catch (error) { - emitDiagnostic({ - level: 'warn', - phase: 'leased_session_end_failed', - data: { leaseId, reason, error: errorMessage(error) }, - }); - } finally { - if ( - !closing && - sessionStore.listRetainedExecutionHosts(leaseId).length === 0 && - sessionStore.leasedSessionRefs(leaseId).length === 0 - ) { - pending.delete(leaseId); - } else if (!closing) { - pending.set(leaseId, { reason, nextRetryAt: Date.now() + LEASE_END_RETRY_INTERVAL_MS }); - } - } - }; - - const end = async (leaseId: string, reason: LeaseEndReason): Promise => { - if (closing) return; - pending.set(leaseId, { reason, nextRetryAt: 0 }); - const ending = params.withinDiagnosticsScope - ? params.withinDiagnosticsScope(async () => await run(leaseId, reason)) - : run(leaseId, reason); - const running = inFlight.get(leaseId) ?? new Set>(); - running.add(ending); - inFlight.set(leaseId, running); - try { - await ending; - } finally { - running.delete(ending); - if (running.size === 0) inFlight.delete(leaseId); - } - }; - - return { - end, - retryPending: async () => { - await Promise.all( - Array.from(pending, async ([leaseId, { reason, nextRetryAt }]) => { - if (!inFlight.has(leaseId) && Date.now() >= nextRetryAt) await end(leaseId, reason); - }), - ); - }, - cancel: () => { - closing = true; - }, - drain: async () => { - await Promise.allSettled(Array.from(inFlight.values()).flatMap((running) => [...running])); - }, - }; -} diff --git a/packages/daemon/src/server/request-lease-work.ts b/packages/daemon/src/server/request-lease-work.ts index 4a3445a0e3..c2f5cd1c34 100644 --- a/packages/daemon/src/server/request-lease-work.ts +++ b/packages/daemon/src/server/request-lease-work.ts @@ -1,26 +1,15 @@ -import { isRequestCanceled, throwIfRequestCanceled } from '@agent-device/host-kit/request'; +import { AppError } from '@agent-device/kernel/errors'; +import { LEASE_REASONS } from '@agent-device/contracts/lease-scope'; +import { isRequestCanceled } from '@agent-device/host-kit/request'; import { isHumanControlMutation } from '../core/daemon-command-registry.ts'; -import type { LeaseRegistry, RetainedLeaseWork } from '../resources/lease-registry.ts'; +import type { LeaseRegistry } from '../resources/lease-registry.ts'; import type { DaemonRequest } from '../core/daemon-request.ts'; -import type { DeviceLease } from '@agent-device/contracts/device'; -function retainRequestLeaseWork( - leaseRegistry: LeaseRegistry, - lease: Pick, - requestId: string | undefined, -): RetainedLeaseWork { - return leaseRegistry.retainLeaseWork(lease, () => !isRequestCanceled(requestId)); -} - -export function retainSuccessorLeaseWork( - leaseRegistry: LeaseRegistry, - req: DaemonRequest, - lease: DeviceLease, -): { req: DaemonRequest; work: RetainedLeaseWork } { - return { - req: { ...req, internal: { ...req.internal, admittedLease: lease } }, - work: retainRequestLeaseWork(leaseRegistry, lease, req.meta?.requestId), - }; +export function inactiveLease(): AppError { + return new AppError('UNAUTHORIZED', 'Lease is not active', { + reason: LEASE_REASONS.notFound.reason, + dispatched: 'no', + }); } /** @@ -38,24 +27,20 @@ export async function runAdmittedLeaseWork( params: Readonly<{ leaseRegistry: LeaseRegistry; req: DaemonRequest; - /** A work pass already held and released by the caller. */ - retainedWork?: RetainedLeaseWork; task: () => Promise; + assertCurrent?: () => void; }>, ): Promise { - const { leaseRegistry, req, retainedWork, task } = params; + const { leaseRegistry, req, task } = params; const lease = req.internal?.admittedLease; if (!lease) return await task(); - if (retainedWork) { - throwIfRequestCanceled(req.meta?.requestId); - retainedWork.assertRetained(); - } - const work = retainedWork ?? retainRequestLeaseWork(leaseRegistry, lease, req.meta?.requestId); + params.assertCurrent?.(); + const work = leaseRegistry.retainLeaseWork(lease, () => !isRequestCanceled(req.meta?.requestId)); try { return await (isHumanControlMutation(req) ? leaseRegistry.runDeviceMutation(lease, task) : task()); } finally { - if (!retainedWork) work.release(); + work.release(); } } diff --git a/packages/daemon/src/server/request-router.ts b/packages/daemon/src/server/request-router.ts index 604fde2023..d14a86d1a7 100644 --- a/packages/daemon/src/server/request-router.ts +++ b/packages/daemon/src/server/request-router.ts @@ -1,4 +1,5 @@ -import type { LeaseEndReason, SessionTeardown } from '../sessions/lease-lifecycle.ts'; +import type { LeaseSessionEnd } from './lease-session-end.ts'; +import type { LeaseEndReason } from '../sessions/lease-lifecycle.ts'; import type { PluginInventoryEntry } from '@agent-device/contracts/plugin-inventory'; import { createOwnerScopedDeviceClaimReconciler, @@ -163,7 +164,7 @@ export type RequestRouterDeps = { createCommandSurface: CreateDaemonCommandSurface; platformResourceCleanup: PlatformResourceCleanup; /** Ends the resources of a session whose lease expired, for a request that holds its locks. */ - settleExpiredSession: SessionTeardown; + leaseSessionEnd?: Pick; providerDeviceRuntimeScope?: (task: () => Promise) => Promise; /** ADR 0029: the daemon policy every admitted request, including nested steps, obeys. */ daemonPolicy?: DaemonPolicy; @@ -195,7 +196,7 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { androidObservation, createCommandSurface, platformResourceCleanup, - settleExpiredSession, + leaseSessionEnd, providerDeviceRuntimeScope, trackDownloadableArtifact, daemonPolicy, @@ -326,7 +327,7 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { claimRecoveryGateway, trackClaimRecoveryDisposal, platformRequestScope, - settleExpiredSession, + leaseSessionEnd, providerAppCatalog, pluginInventory, daemonPolicy, @@ -517,7 +518,7 @@ export function createRequestHandler(deps: RequestRouterDeps): DaemonInvokeFn { claimRecoveryGateway, trackClaimRecoveryDisposal, platformRequestScope: createPlatformRequestScope(scopedReq), - settleExpiredSession, + leaseSessionEnd, providerAppCatalog, pluginInventory, daemonPolicy, diff --git a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts index 845bce3760..464a72e1ab 100644 --- a/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts +++ b/packages/daemon/src/sessions/__tests__/lease-lifecycle.test.ts @@ -6,10 +6,8 @@ import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { admitRequestLeaseForLockedScope, - cleanupExpiredLeasedSession, releaseExpiredProviderLease, releaseSessionLease, - resolveLockedRequestSessionRef, } from '../lease-lifecycle.ts'; import type { DaemonRequest } from '../../core/daemon-request.ts'; @@ -50,8 +48,7 @@ test('admitRequestLeaseForLockedScope heartbeats and stores admitted lease on th const req = admitRequestLeaseForLockedScope({ env: process.env, req: makeRequest({ command: 'snapshot', meta: { leaseId: lease.leaseId } }), - sessionName: 'default', - sessionStore, + session: sessionStore.get('default'), leaseRegistry, }); @@ -80,8 +77,7 @@ test('admitRequestLeaseForLockedScope renews no session for a command that ignor command: 'devices', meta: { leaseId: own.leaseId, tenantId: 'tenant-a', runId: 'run-b' }, }), - sessionName: 'default', - sessionStore, + session: sessionStore.get('default'), leaseRegistry, }); @@ -90,91 +86,6 @@ test('admitRequestLeaseForLockedScope renews no session for a command that ignor expect(sessionStore.get('default')?.lease).toEqual(sessionLease); }); -test('resolveLockedRequestSessionRef ends nothing when the successor lease expires while it waits for the device lock', async () => { - let now = 1_000; - const sessionStore = makeSessionStore('agent-device-lease-lifecycle-'); - const leaseRegistry = new LeaseRegistry({ minLeaseTtlMs: 1, now: () => now }); - const expired = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-a', ttlMs: 10 }); - const successor = leaseRegistry.allocateLease({ - tenantId: 'tenant-a', - runId: 'run-b', - ttlMs: 50, - }); - const ref = sessionStore.publish( - 'default', - makeIosSession('default', { - lease: { - leaseId: expired.leaseId, - tenantId: expired.tenantId, - runId: expired.runId, - backend: expired.backend, - }, - }), - ); - now = 1_020; - const teardownSession = vi.fn(async () => {}); - const onSuccessorAdmitted = vi.fn(); - - await expect( - resolveLockedRequestSessionRef({ - env: process.env, - req: makeRequest({ command: 'open', meta: { leaseId: successor.leaseId } }), - sessionName: 'default', - sessionStore, - leaseRegistry, - teardown: 'inline', - holdDeviceLock: async () => { - now = 1_060; - }, - teardownSession, - admission: {}, - onSuccessorAdmitted, - }), - ).rejects.toMatchObject({ details: { reason: 'LEASE_SESSION_MISMATCH' } }); - - expect(teardownSession).not.toHaveBeenCalled(); - expect(onSuccessorAdmitted).not.toHaveBeenCalled(); - expect(sessionStore.lookup('default')?.lifetime).toBe(ref.lifetime); -}); - -test('cleanupExpiredLeasedSession consumes expired lease and deletes the session after teardown', async () => { - let now = 1_000; - const sessionStore = makeSessionStore('agent-device-lease-lifecycle-'); - const leaseRegistry = new LeaseRegistry({ - defaultLeaseTtlMs: 10, - minLeaseTtlMs: 1, - now: () => now, - }); - const lease = leaseRegistry.allocateLease({ tenantId: 'tenant-a', runId: 'run-1' }); - const session = makeIosSession('default', { - lease: { - leaseId: lease.leaseId, - tenantId: lease.tenantId, - runId: lease.runId, - backend: lease.backend, - }, - }); - sessionStore.publish('default', session); - now = 1_011; - const teardownSession = vi.fn(async () => {}); - - const cleaned = await cleanupExpiredLeasedSession({ - env: process.env, - ref: sessionStore.lookup('default'), - sessionStore, - leaseRegistry, - teardownSession, - teardown: 'inline', - }); - - expect(cleaned).toBe(true); - expect(teardownSession).toHaveBeenCalledWith( - expect.objectContaining({ address: 'default', session }), - ); - expect(sessionStore.get('default')).toBeUndefined(); - expect(leaseRegistry.listActiveLeases()).toHaveLength(0); -}); - test('releaseSessionLease releases with the stored session owner scope', async () => { const leaseRegistry = new LeaseRegistry(); const lease = leaseRegistry.allocateLease({ diff --git a/packages/daemon/src/sessions/__tests__/session-idle-activity.test.ts b/packages/daemon/src/sessions/__tests__/session-idle-activity.test.ts index ca25fe09df..169523c3be 100644 --- a/packages/daemon/src/sessions/__tests__/session-idle-activity.test.ts +++ b/packages/daemon/src/sessions/__tests__/session-idle-activity.test.ts @@ -217,7 +217,8 @@ test('the request plan for an existing session keeps the canonical session-first const requestPlan = await resolveRequestExecutionLockPlan({ req: makeRequest({ command: 'snapshot' }), sessionName: 'default', - sessionStore, + existingDeviceId: session.device.id, + env: sessionStore.host.env, }); // What this pins is the PLANNER: an existing session's request takes `existingSessionExecutionLockKeys` diff --git a/packages/daemon/src/sessions/__tests__/session-teardown-expired-settle.test.ts b/packages/daemon/src/sessions/__tests__/session-teardown-expired-settle.test.ts index 33fa671f18..c524c12779 100644 --- a/packages/daemon/src/sessions/__tests__/session-teardown-expired-settle.test.ts +++ b/packages/daemon/src/sessions/__tests__/session-teardown-expired-settle.test.ts @@ -7,7 +7,7 @@ import { settleExpiredSession } from '../session-teardown.ts'; bindTestCommandHost(); -function settleWithFailingResources(afterResourceFailure: 'stop' | 'finalize') { +test('expiry stops at a resource failure so the next pass can retry', async () => { const sessionStore = makeSessionStore('agent-device-expired-settle-'); const ref = sessionStore.publish('default', makeIosSession('default')); const finalizeApplication = vi.fn(async () => {}); @@ -20,21 +20,8 @@ function settleWithFailingResources(afterResourceFailure: 'stop' | 'finalize') { throw new Error('snapshot helper stop failed'); }, }), - afterResourceFailure, finalizeApplication, }); - return { settled, finalizeApplication }; -} - -test('a lease expiry still finalizes the application after a resource failure, which stays the error', async () => { - const { settled, finalizeApplication } = settleWithFailingResources('finalize'); - - await expect(settled).rejects.toThrow(/snapshot helper stop failed/); - expect(finalizeApplication).toHaveBeenCalledTimes(1); -}); - -test('an idle expiry stops at a resource failure, so the next pass can retry', async () => { - const { settled, finalizeApplication } = settleWithFailingResources('stop'); await expect(settled).rejects.toThrow(/snapshot helper stop failed/); expect(finalizeApplication).not.toHaveBeenCalled(); diff --git a/packages/daemon/src/sessions/handlers/lease.ts b/packages/daemon/src/sessions/handlers/lease.ts index 1abbb276de..20a1a24ff7 100644 --- a/packages/daemon/src/sessions/handlers/lease.ts +++ b/packages/daemon/src/sessions/handlers/lease.ts @@ -384,7 +384,9 @@ async function heartbeatLease( const { leaseRegistry, leaseLifecycleProvider, req, endSessionsForLease } = args; const lease = leaseRegistry.heartbeatLease(leaseScopeToHeartbeatRequest(leaseScope)); let providerData: Record | undefined; + const confirmProviderEnd = leaseRegistry.pinProviderLeaseEnd(lease.leaseId); let ended: AppError | undefined; + let endWon = false; try { providerData = await leaseLifecycleProvider?.heartbeat?.(lease, { ...leaseLifecycleContext(req, args.host), @@ -392,13 +394,13 @@ async function heartbeatLease( }); } catch (error) { if (!(error instanceof AppError) || !isProviderInstanceEndedError(error)) throw error; - leaseRegistry.endProviderLease(leaseReleaseRequestFor(lease)); + endWon = confirmProviderEnd(); ended = error; } if (ended) { // The client stops beating only on the typed reason, so a failed teardown must not replace it. try { - await endSessionsForLease?.(lease.leaseId, 'PROVIDER_INSTANCE_ENDED'); + if (endWon) await endSessionsForLease?.(lease.leaseId, 'PROVIDER_INSTANCE_ENDED'); } catch (error) { emitDiagnostic({ level: 'warn', diff --git a/packages/daemon/src/sessions/lease-lifecycle.ts b/packages/daemon/src/sessions/lease-lifecycle.ts index 9fe5b6dd26..5d905e5f1f 100644 --- a/packages/daemon/src/sessions/lease-lifecycle.ts +++ b/packages/daemon/src/sessions/lease-lifecycle.ts @@ -1,24 +1,15 @@ import type { PluginInventoryEntry } from '@agent-device/contracts/plugin-inventory'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { throwIfRequestCanceled } from '@agent-device/host-kit/request'; -import { LEASE_REASONS, leaseScopeToHeartbeatRequest } from '@agent-device/contracts/lease-scope'; import { clearDeviceClaim } from '@agent-device/daemon-contracts/device-claims'; import type { LeaseRegistry } from '../resources/lease-registry.ts'; import { leaseReleaseRequestFor } from '../resources/lease-registry-scope.ts'; -import { assertMacOsAppLeaseProcess } from '../resources/macos-app-lease.ts'; import type { DeviceLease, LeaseLifecycleProvider, ProviderAppCatalog, } from '@agent-device/contracts/device'; -import { resolveLeaseScope } from '../core/lease-context.ts'; -import { - assertRequestLeaseAdmission, - resolveRequestSessionRef, - type ResolveRequestSessionRef, -} from './request-admission.ts'; -import { AppError, errorMessage } from '@agent-device/kernel/errors'; +import { assertRequestLeaseAdmission } from './request-admission.ts'; import type { SessionStore } from '../core/session-store.ts'; import type { DaemonRequest } from '../core/daemon-request.ts'; import type { SessionRef, SessionState } from '../core/session-state.ts'; @@ -61,195 +52,41 @@ export async function releaseExpiredProviderLease( } } -/** - * How a request treats a session whose lease expired. A request that holds the session lock ends - * it (`inline`). A composite refuses the expired lease rather than tear its session down mid-run. - * A request without the session lock leaves the session to the lease-end owner and its locks. - */ -export type ExpiredSessionTeardown = 'inline' | 'refuse' | 'lease-end-owner'; - -export async function cleanupExpiredLeasedSession(params: { - env: HostEnvironment['env']; - /** The session the request holds the lease of; a request that holds none ends no session. */ - ref: SessionRef | undefined; - sessionStore: SessionStore; - leaseRegistry: LeaseRegistry; - teardownSession: SessionTeardown; - teardown: ExpiredSessionTeardown; -}): Promise { - const { ref } = params; - const lease = ref?.session.lease; - if (!ref || !lease) return false; - if ( - !params.leaseRegistry.consumeExpiredLease(lease.leaseId, () => { - if (params.teardown !== 'refuse') return; - throw new AppError('UNAUTHORIZED', 'Lease is not active', { - reason: LEASE_REASONS.notFound.reason, - dispatched: 'no', - }); - }) || - params.teardown !== 'inline' - ) - return false; - await endLeasedSession( - ref, - params.sessionStore, - params.teardownSession, - 'LEASE_EXPIRED', - params.env, - ); - return true; -} - -/** - * Ends one session whose lease is gone (released or expired). The device claim is cleared even when - * teardown fails: the lease that paid for the device has ended, so nobody may keep it. - */ export async function endLeasedSession( ref: SessionRef, sessionStore: SessionStore, teardownSession: SessionTeardown, - reason: LeaseEndReason, env: HostEnvironment['env'], - /** Only the daemon log names the lease id. A request record can reach another client. */ - daemonScope = false, ): Promise { - const session = ref.session; - const leaseId = daemonScope ? session.lease?.leaseId : undefined; - emitDiagnostic({ - level: 'info', - phase: 'leased_session_ended', - data: { reason, leaseId, session: session.name, deviceKey: session.lease?.deviceKey }, - }); - await teardownSession(ref).catch((error) => { - emitDiagnostic({ - level: 'debug', - phase: 'leased_session_end_cleanup_failed', - data: { reason, leaseId, session: session.name, error: errorMessage(error) }, - }); - }); - await clearDeviceClaim(session.deviceClaim, env).catch((error) => { - emitDiagnostic({ - level: 'warn', - phase: 'leased_session_end_device_claim_clear_failed', - data: { - session: session.name, - deviceKey: session.deviceClaim?.deviceKey, - error: errorMessage(error), - }, - }); - }); + const claim = ref.session.deviceClaim; + await teardownSession(ref); + const current = sessionStore.resolveCurrent(ref); + if (!current || current.deviceClaim !== claim) return; + if ((await clearDeviceClaim(claim, env)) === 'unattributable') return; sessionStore.finalizeRepairTeardown(ref); sessionStore.retire(ref); } -type LockedSessionParams = { - env: HostEnvironment['env']; - req: DaemonRequest; - sessionName: string; - sessionStore: SessionStore; - leaseRegistry: LeaseRegistry; - teardown: ExpiredSessionTeardown; - holdDeviceLock: (deviceId: string) => Promise; - teardownSession: SessionTeardown; - admission: Readonly<{ providerAppCatalog?: ProviderAppCatalog; daemonPolicy?: DaemonPolicy }>; - onSuccessorAdmitted(lease: DeviceLease): void; - resolveSessionRef?: ResolveRequestSessionRef; -}; - -/** - * The session that a request acts through, resolved under the session lock. A request that - * presents another active lease first ends a session whose lease is over, and then finds none. - */ -export async function resolveLockedRequestSessionRef( - params: LockedSessionParams, -): Promise { - const { req, sessionName, sessionStore, resolveSessionRef = resolveRequestSessionRef } = params; - const ref = sessionStore.lookup(sessionName); - const ended = - ref !== undefined && - params.teardown === 'inline' && - (await endExpiredSessionForSuccessor(params, ref)); - return resolveSessionRef(req, ended ? sessionStore.lookup(sessionName) : ref); -} - -/** - * Ends the session of a lease that is over, for a request that presents another active lease. A - * new owner can then open the address before the lease sweep runs. Any other request ends nothing. - */ -async function endExpiredSessionForSuccessor( - params: LockedSessionParams, - ref: SessionRef, -): Promise { - const { leaseRegistry } = params; - const expiredLeaseId = ref.session.lease?.leaseId; - const successorScope = resolveLeaseScope(params.req); - const successorLeaseId = successorScope.leaseId; - if (!expiredLeaseId || !successorLeaseId || successorLeaseId === expiredLeaseId) return false; - const canEndSession = () => - params.sessionStore.currentRefForLease(ref, expiredLeaseId) !== undefined && - !leaseRegistry.inspectActiveLease(expiredLeaseId) && - leaseRegistry.inspectActiveLease(successorLeaseId) !== undefined; - if (!canEndSession()) return false; - await params.holdDeviceLock(ref.session.device.id); - throwIfRequestCanceled(params.req.meta?.requestId); - const admitSuccessor = () => - assertRequestLeaseAdmission(params.req, leaseRegistry, undefined, { - ...params.admission, - env: params.env, - inspectOnly: true, - }); - if (!canEndSession()) return false; - const successor = admitSuccessor(); - if (!successor) return false; - if (successor.backend === 'macos-app') { - await assertMacOsAppLeaseProcess(successor); - throwIfRequestCanceled(params.req.meta?.requestId); - if (!canEndSession() || !admitSuccessor()) return false; - } - const admittedSuccessor = leaseRegistry.renewInspectedLeaseAdmission( - leaseScopeToHeartbeatRequest(successorScope), - ); - params.onSuccessorAdmitted(admittedSuccessor); - await endLeasedSession( - ref, - params.sessionStore, - params.teardownSession, - 'LEASE_EXPIRED', - params.env, - ); - // An inactive lease never becomes active again. The registry notes the expiry only now, so the - // lease-end owner that it starts finds no session to end a second time. - leaseRegistry.consumeExpiredLease(expiredLeaseId); - return true; -} - export function admitRequestLeaseForLockedScope(params: { env: HostEnvironment['env']; req: DaemonRequest; - sessionName: string; - sessionStore: SessionStore; + session: SessionState | undefined; leaseRegistry: LeaseRegistry; providerAppCatalog?: ProviderAppCatalog; pluginInventory?: readonly PluginInventoryEntry[]; daemonPolicy?: DaemonPolicy; - resolveSessionRef?: ResolveRequestSessionRef; }): DaemonRequest { - const { - sessionName, - sessionStore, - leaseRegistry, - resolveSessionRef = resolveRequestSessionRef, - } = params; - // The addressed session still decides the app-lease veto. - const addressed = sessionStore.lookup(sessionName); - resolveSessionRef(params.req, addressed); - const activeLease = assertRequestLeaseAdmission(params.req, leaseRegistry, addressed?.session, { - env: params.env, - providerAppCatalog: params.providerAppCatalog, - pluginInventory: params.pluginInventory, - daemonPolicy: params.daemonPolicy, - }); + const activeLease = assertRequestLeaseAdmission( + params.req, + params.leaseRegistry, + params.session, + { + env: params.env, + providerAppCatalog: params.providerAppCatalog, + pluginInventory: params.pluginInventory, + daemonPolicy: params.daemonPolicy, + }, + ); if (!activeLease) return params.req; return { ...params.req, internal: { ...params.req.internal, admittedLease: activeLease } }; } diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.test.ts index c723b6736a..b5868c2636 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.test.ts @@ -12,7 +12,7 @@ import { import { SessionStore } from '../../../core/session-store.ts'; import { LeaseRegistry } from '../../../resources/lease-registry.ts'; import { sessionLeaseOf } from '../../../core/lease-context.ts'; -import { createLeaseSessionEnd } from '../../../server/request-execution-scope.ts'; +import { createLeaseSessionEnd } from '../../../server/lease-session-end.ts'; import { handleLeaseCommands } from '../../handlers/lease.ts'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; import type { SessionState } from '../../../core/session-state.ts'; diff --git a/packages/daemon/src/sessions/session-teardown.ts b/packages/daemon/src/sessions/session-teardown.ts index 42bb4960cd..07c0fca721 100644 --- a/packages/daemon/src/sessions/session-teardown.ts +++ b/packages/daemon/src/sessions/session-teardown.ts @@ -11,7 +11,10 @@ import { import type { SessionStore } from '../core/session-store.ts'; import { finishLiveAudioProbe } from '@agent-device/capture-kit/audio-probe-session-resource'; import { finishLivePerfCapture } from '@agent-device/capture-kit/perf-capture-session-resource'; -import { finishLiveScreenRecording } from '@agent-device/capture-kit/screen-recording-session-resource'; +import { + finishLiveScreenRecording, + screenRecordingDurableResource, +} from '@agent-device/capture-kit/screen-recording-session-resource'; import { openWebSessionNames } from './web-session-names.ts'; import type { PlatformResourceCleanup } from '../core/platform-resource-cleanup.ts'; @@ -127,6 +130,7 @@ export function sessionResourceStopSteps(params: { sessionStore: SessionStore; platformCleanup: PlatformResourceCleanup; appLog: 'run' | 'already-settled'; + providerInstanceEnded?: () => boolean; }): SessionCleanupStep[] { const { ref, sessionStore, platformCleanup } = params; const session = sessionStore.resolveCurrent(ref) ?? ref.session; @@ -137,7 +141,7 @@ export function sessionResourceStopSteps(params: { // gesture-telemetry for overlay finalization, and signalling the recorder first prevents a // leaked `simctl recordVideo` child (and its 0-byte, slot-holding mp4) when a session is torn // down — including on daemon shutdown — without an explicit `record stop`. - { step: 'recording', run: () => finishSessionScreenRecording({ ref, sessionStore }) }, + { step: 'recording', run: () => finishSessionScreenRecording(params) }, ...(params.appLog === 'run' ? [{ step: 'app_log', run: () => stopSessionAppLog({ ref, sessionStore }) }] : []), @@ -177,6 +181,7 @@ type SessionResourceTeardownRequest = { sessionStore: SessionStore; appLog: 'run' | 'already-settled'; platformCleanup?: PlatformResourceCleanup; + providerInstanceEnded?: () => boolean; }; export async function teardownSessionResources( @@ -216,42 +221,39 @@ export async function teardownSessionResources( if (aggregate) throw aggregate; } -/** - * Releases the resources of an expired session, then finalizes its application. An idle expiry - * stops at a resource failure and retries later. A lease expiry retires the session whatever - * happens, so it still finalizes the application, and the resource failure stays the error. - */ +/** Settles session resources before finalizing the application. A failure preserves the session for retry. */ export async function settleExpiredSession( request: SessionResourceTeardownRequest & { finalizeApplication: () => Promise; - afterResourceFailure: 'stop' | 'finalize'; }, ): Promise { - try { - await teardownSessionResources(request); - } catch (error) { - if (request.afterResourceFailure === 'finalize') { - await request.finalizeApplication().catch((finalizeError) => { - emitDiagnostic({ - level: 'error', - phase: 'expired_session_lifecycle_cleanup_failed', - data: { session: request.ref.address, error: String(finalizeError) }, - }); - }); - } - throw error; - } + await teardownSessionResources(request); await request.finalizeApplication(); } async function finishSessionScreenRecording(params: { ref: SessionRef; sessionStore: SessionStore; + providerInstanceEnded?: () => boolean; }): Promise { const binding = bindSessionScreenRecording(params.sessionStore, params.ref); const recording = binding.read(); if (!recording) return; - const completion = await finishLiveScreenRecording({ binding, intent: 'disposal' }); + const { owner } = recording.envelope; + const confirmedMissing = () => + owner.kind === 'provider-runtime' && + owner.provider === params.ref.session.lease?.leaseProvider && + binding.read() === recording && + params.providerInstanceEnded?.() === true; + if (confirmedMissing()) { + await screenRecordingDurableResource.confirmLiveMissing({ binding, resource: recording }); + return; + } + const completion = await finishLiveScreenRecording({ + binding, + intent: 'disposal', + confirmedMissing, + }); if (!params.ref.session.lease) return; const { retainLeasedSessionRecording } = await import('./leased-recording-retention.ts'); retainLeasedSessionRecording(params.ref, completion, recording.envelope.metadata); diff --git a/packages/daemon/test/nightly/concurrency-torture/bindings.ts b/packages/daemon/test/nightly/concurrency-torture/bindings.ts index 4da08c59dd..1027da299c 100644 --- a/packages/daemon/test/nightly/concurrency-torture/bindings.ts +++ b/packages/daemon/test/nightly/concurrency-torture/bindings.ts @@ -132,8 +132,14 @@ async function resolveExecutionLockPlan( sessionStore: SessionStore, ): Promise { if (!shouldLockSessionExecution(req.command)) return []; - const plan = await withPool(() => - resolveRequestExecutionLockPlan({ req, sessionName, sessionStore }), + const plan = await withPool( + async () => + await resolveRequestExecutionLockPlan({ + req, + sessionName, + existingDeviceId: sessionStore.get(sessionName)?.device.id, + env: sessionStore.host.env, + }), ); return plan.keys as LockKey[]; } diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 377a2d453e..2a76293c55 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -199,7 +199,7 @@ Aliases: `launch`, `relaunch`. | `--relaunch` | open: terminate app process before launching it | | `--foreground` | open: keep normal app/device selection and return an initial snapshot of the first screen (a local iOS simulator waits up to 10s for it); without an app, resolve the sole running app on the sole booted iOS simulator; on HarmonyOS with an app target, fail when the launched app does not hold the foreground within 5s | | `--no-record` | Do not record this action | -| `--wait ` | Open: wait up to n ms for a device another session is holding before failing with DEVICE_IN_USE | +| `--wait ` | Open: limit the wait for a busy device or expired session cleanup to n ms | Also accepts: [common options](#common-options): `--timeout `. diff --git a/website/docs/docs/sessions.md b/website/docs/docs/sessions.md index 1065fb0be6..9ee924a660 100644 --- a/website/docs/docs/sessions.md +++ b/website/docs/docs/sessions.md @@ -189,8 +189,12 @@ agent-device open Demo --platform android --wait 60000 If the wait runs out while the device is still busy, `open` fails with `DEVICE_IN_USE`. If the reply names the holder, its owner can run `close --session
` to release the device. -Each waiting `open` gets its full wait. If another waiter gets the device first, the rest keep -waiting for the time left in their own budgets. +Each waiting `open` has its own budget. If another waiter gets the device first, the rest keep +waiting for the time left in their budgets. + +If the session at the address has an expired lease, `open` with your own valid lease waits for +cleanup within the request deadline. Use `--wait` to cap that wait. Your lease must still be valid +when cleanup ends. Behind a shared proxy token, all clients share a tenant. A proxy client can see the holder's address in a refusal or in wait progress if it can list the holder and the holder has a lease or a tenant @@ -198,8 +202,7 @@ scope. To see the address of a leased holder, the caller must send that holder's Open contention and claim conflicts can show the address of an unleased session in another workspace to a local caller. The owner can use that address to close the session from its workspace. -`--wait` waits only for another session. If another workspace's daemon holds the claim, -`open` fails at once. +If another workspace's daemon holds the claim, `open` fails at once. Device-mutating commands like `install` and `reinstall` don't wait either: while a session other than yours holds the device, they fail at once with `DEVICE_IN_USE`. Copying the owner's `--session` address doesn't change that — the claim must also