From b208b5bcb95ea9cb180e849493c8c81701b2def2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 28 Nov 2026 08:34:24 +0100 Subject: [PATCH 1/3] refactor(daemon): trim expired-lease admission code Co-Authored-By: Claude Sonnet 5.5 --- .../src/server/request-execution-locks.ts | 11 ----- .../src/server/request-execution-scope.ts | 7 ++-- .../daemon/src/sessions/lease-lifecycle.ts | 42 +++++++++---------- 3 files changed, 23 insertions(+), 37 deletions(-) diff --git a/packages/daemon/src/server/request-execution-locks.ts b/packages/daemon/src/server/request-execution-locks.ts index 3798053828..deffb54864 100644 --- a/packages/daemon/src/server/request-execution-locks.ts +++ b/packages/daemon/src/server/request-execution-locks.ts @@ -1,4 +1,3 @@ -import { AsyncResource } from 'node:async_hooks'; import { heldKeyedLockKeys, withKeyedLock, @@ -71,16 +70,6 @@ export function createRequestExecutionLocks(params: { }; } -/** - * `end` bound to the current context. Bound before a request takes a lock, it runs outside that - * request's locks wherever the request calls it, so it never holds one while it waits for another. - */ -export function bindOutsideRequestLocks( - end: ((leaseId: string) => Promise) | undefined, -): ((leaseId: string) => Promise) | undefined { - return end && AsyncResource.bind(end); -} - function heldRequestLockKeys(locks: Map>): RequestExecutionLockKey[] { return heldKeyedLockKeys(locks) as RequestExecutionLockKey[]; } diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index b6807babc0..c5dbfc1bbf 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -1,3 +1,4 @@ +import { AsyncResource } from 'node:async_hooks'; 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'; @@ -58,7 +59,6 @@ import { readOpenWaitBudgetMs, } from '../sessions/open-device-contention-wait.ts'; import { - bindOutsideRequestLocks, createRequestExecutionLocks, withRequestExecutionLockKeys, } from './request-execution-locks.ts'; @@ -239,8 +239,9 @@ export async function createRequestExecutionScope(params: { endSessionsForLease?: (leaseId: string) => Promise; }): Promise { const { sessionStore, leaseRegistry } = params; - // Bound here, before this request takes a lock. - const queueLeaseEnd = bindOutsideRequestLocks(params.endSessionsForLease); + // Bound before this request takes a lock, so the lease end never waits for one while holding another. + const queueLeaseEnd = + params.endSessionsForLease && AsyncResource.bind(params.endSessionsForLease); const tenantScopedReq = scopeRequestSession(restrictRemoteHostInputs(params.req)); // A nested batch or replay step arrives with the identity of the request that spawned it, and its // own name is already the store key. diff --git a/packages/daemon/src/sessions/lease-lifecycle.ts b/packages/daemon/src/sessions/lease-lifecycle.ts index 04ff3474d5..c23c6203f9 100644 --- a/packages/daemon/src/sessions/lease-lifecycle.ts +++ b/packages/daemon/src/sessions/lease-lifecycle.ts @@ -80,13 +80,18 @@ export async function cleanupExpiredLeasedSession(params: { teardownSession: SessionTeardown; /** Starts the daemon's lease end outside this request's execution locks. */ queueLeaseEnd?: (leaseId: string) => Promise; + /** False for a `close` planned before its session existed: locks are planned before they are taken. */ holdsSessionLocks: (ref: SessionRef) => boolean; }): Promise { const ref = params.sessionStore.lookup(params.sessionName); const lease = ref?.session.lease; if (!ref || !lease) return false; + const kind = classifyEndedLeaseRequest(params.req); const expired = params.leaseRegistry.consumeExpiredLease(lease.leaseId, () => { - if (!refusesExpiredLeaseTeardown(params.req, params.leaseRegistry)) return; + const refuses = + kind === 'composite' || + (kind === 'device-work' && namesInactiveLease(params.req, params.leaseRegistry)); + if (!refuses) return; throw new AppError('UNAUTHORIZED', 'Lease is not active', { reason: LEASE_REASONS.notFound.reason, dispatched: 'no', @@ -106,25 +111,28 @@ export async function cleanupExpiredLeasedSession(params: { } if ( !params.queueLeaseEnd || - doesDeviceWork(params.req) || - isBoundedCompositeRequest(params.req) || + kind === 'composite' || + kind === 'device-work' || params.leaseRegistry.inspectLeaseBackend(lease.leaseId) !== undefined ) { return false; } // The lease end locks every session of the lease, so no request waits for it under its own locks. void params.queueLeaseEnd(lease.leaseId); - if (endsSession(params.req) && params.holdsSessionLocks(ref)) await end(); + if (kind === 'ends-session' && params.holdsSessionLocks(ref)) await end(); return true; } -function refusesExpiredLeaseTeardown(req: DaemonRequest, leaseRegistry: LeaseRegistry): boolean { - return ( - req.command === 'batch' || - req.command === 'replay' || - isBoundedCompositeRequest(req) || - (doesDeviceWork(req) && namesInactiveLease(req, leaseRegistry)) - ); +type EndedLeaseRequestKind = 'composite' | 'ends-session' | 'exempt' | 'device-work'; + +function classifyEndedLeaseRequest(req: DaemonRequest): EndedLeaseRequestKind { + if (req.command === 'batch' || req.command === 'replay' || isBoundedCompositeRequest(req)) { + return 'composite'; + } + // A `close` ends its session, unless a replay step asks it to close only the app. + const releases = resolveCommandDeviceClaimPolicy(req.command) === 'release-session'; + if (releases && req.internal?.closeAppOnly !== true) return 'ends-session'; + return isLeaseAdmissionExempt(req.command) ? 'exempt' : 'device-work'; } /** Whether admission would refuse the lease the request names, which must then come first. */ @@ -133,18 +141,6 @@ function namesInactiveLease(req: DaemonRequest, leaseRegistry: LeaseRegistry): b return leaseId !== undefined && leaseRegistry.inspectLeaseBackend(leaseId) === undefined; } -function doesDeviceWork(req: DaemonRequest): boolean { - return !endsSession(req) && !isLeaseAdmissionExempt(req.command); -} - -/** A `close` ends its session, unless a replay step asks it to close only the app. */ -function endsSession(req: DaemonRequest): boolean { - return ( - resolveCommandDeviceClaimPolicy(req.command) === 'release-session' && - req.internal?.closeAppOnly !== 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. From bd7165196f3321c617db51220fef44dea3e70391 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 28 Nov 2026 08:38:32 +0100 Subject: [PATCH 2/3] refactor(daemon): keep the lease-end bind helper Inlining it added a branch that put createRequestExecutionScope over the Fallow cyclomatic threshold. Co-Authored-By: Claude Opus 5.5 --- packages/daemon/src/server/request-execution-locks.ts | 11 +++++++++++ packages/daemon/src/server/request-execution-scope.ts | 7 +++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/packages/daemon/src/server/request-execution-locks.ts b/packages/daemon/src/server/request-execution-locks.ts index deffb54864..3798053828 100644 --- a/packages/daemon/src/server/request-execution-locks.ts +++ b/packages/daemon/src/server/request-execution-locks.ts @@ -1,3 +1,4 @@ +import { AsyncResource } from 'node:async_hooks'; import { heldKeyedLockKeys, withKeyedLock, @@ -70,6 +71,16 @@ export function createRequestExecutionLocks(params: { }; } +/** + * `end` bound to the current context. Bound before a request takes a lock, it runs outside that + * request's locks wherever the request calls it, so it never holds one while it waits for another. + */ +export function bindOutsideRequestLocks( + end: ((leaseId: string) => Promise) | undefined, +): ((leaseId: string) => Promise) | undefined { + return end && AsyncResource.bind(end); +} + function heldRequestLockKeys(locks: Map>): RequestExecutionLockKey[] { return heldKeyedLockKeys(locks) as RequestExecutionLockKey[]; } diff --git a/packages/daemon/src/server/request-execution-scope.ts b/packages/daemon/src/server/request-execution-scope.ts index c5dbfc1bbf..b6807babc0 100644 --- a/packages/daemon/src/server/request-execution-scope.ts +++ b/packages/daemon/src/server/request-execution-scope.ts @@ -1,4 +1,3 @@ -import { AsyncResource } from 'node:async_hooks'; 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'; @@ -59,6 +58,7 @@ import { readOpenWaitBudgetMs, } from '../sessions/open-device-contention-wait.ts'; import { + bindOutsideRequestLocks, createRequestExecutionLocks, withRequestExecutionLockKeys, } from './request-execution-locks.ts'; @@ -239,9 +239,8 @@ export async function createRequestExecutionScope(params: { endSessionsForLease?: (leaseId: string) => Promise; }): Promise { const { sessionStore, leaseRegistry } = params; - // Bound before this request takes a lock, so the lease end never waits for one while holding another. - const queueLeaseEnd = - params.endSessionsForLease && AsyncResource.bind(params.endSessionsForLease); + // Bound here, before this request takes a lock. + const queueLeaseEnd = bindOutsideRequestLocks(params.endSessionsForLease); const tenantScopedReq = scopeRequestSession(restrictRemoteHostInputs(params.req)); // A nested batch or replay step arrives with the identity of the request that spawned it, and its // own name is already the store key. From b1fcf1424365fa9e6e116271b20f0e9449440f3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 28 Nov 2026 09:03:44 +0100 Subject: [PATCH 3/3] docs(daemon): say when holdsSessionLocks can be false Co-Authored-By: Claude Opus 5.5 --- packages/daemon/src/sessions/lease-lifecycle.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/daemon/src/sessions/lease-lifecycle.ts b/packages/daemon/src/sessions/lease-lifecycle.ts index c23c6203f9..02b46a4dc0 100644 --- a/packages/daemon/src/sessions/lease-lifecycle.ts +++ b/packages/daemon/src/sessions/lease-lifecycle.ts @@ -80,7 +80,10 @@ export async function cleanupExpiredLeasedSession(params: { teardownSession: SessionTeardown; /** Starts the daemon's lease end outside this request's execution locks. */ queueLeaseEnd?: (leaseId: string) => Promise; - /** False for a `close` planned before its session existed: locks are planned before they are taken. */ + /** + * Can be false for a `close` planned before its session existed, because locks are planned before + * they are taken. A `close` whose device flags select the session device still plans both keys. + */ holdsSessionLocks: (ref: SessionRef) => boolean; }): Promise { const ref = params.sessionStore.lookup(params.sessionName);