1- import { AsyncLocalStorage } from 'node:async_hooks' ;
2- import { withKeyedLock } from '@agent-device/kernel/keyed-lock' ;
1+ import {
2+ heldKeyedLockKeys ,
3+ withKeyedLock ,
4+ withKeyedLockHolder ,
5+ type KeyedLockHolder ,
6+ } from '@agent-device/kernel/keyed-lock' ;
37import { hostDeviceIdOf } from '@agent-device/kernel/device' ;
48import { AppError } from '@agent-device/kernel/errors' ;
59import type { RequestExecutionLockKey } from './request-binding.ts' ;
610
7- type RetainedExecutionLock = {
8- acquired : Promise < void > ;
9- completion : Promise < void > ;
10- release ( ) : void ;
11- } ;
12-
1311export type RequestExecutionLocks = {
1412 run < T > ( task : ( ) => Promise < T > ) : Promise < T > ;
1513 retainDevice ( deviceId : string ) : Promise < void > ;
1614} ;
1715
18- /**
19- * The locks each enclosing request holds, innermost last. A request nested in another (a batch
20- * step) takes its own locks while the enclosing request still holds its own, so the same-host rule
21- * below applies to the locks it takes up front as much as to the ones it retains later.
22- */
23- const enclosingRequestLocks = new AsyncLocalStorage <
24- readonly ReadonlySet < RequestExecutionLockKey > [ ]
25- > ( ) ;
26-
2716/**
2817 * Owns the stable execution locks for one request and any device lock discovered
2918 * after admission. Dynamic device retention is used by a fresh replay whose
@@ -35,72 +24,50 @@ export function createRequestExecutionLocks(params: {
3524 scope ?: Readonly < { signal : AbortSignal } > ;
3625} ) : RequestExecutionLocks {
3726 const { locks, initialKeys, scope } = params ;
38- const initialKeySet = new Set ( initialKeys ) ;
39- const retainedLocks = new Map < RequestExecutionLockKey , RetainedExecutionLock > ( ) ;
40- // Every lock this request holds, for the requests nested in it to see.
41- const heldLocks = new Set < RequestExecutionLockKey > ( ) ;
42- const enclosing = ( ) : readonly ReadonlySet < RequestExecutionLockKey > [ ] =>
43- enclosingRequestLocks . getStore ( ) ?? [ ] ;
27+ let holder : KeyedLockHolder | undefined ;
4428 let running = false ;
4529
46- const releaseRetainedLocks = async ( ) : Promise < void > => {
47- const held = [ ...retainedLocks . values ( ) ] ;
48- for ( const lock of held ) lock . release ( ) ;
49- await Promise . all ( held . map ( async ( lock ) => await lock . completion ) ) ;
50- retainedLocks . clear ( ) ;
51- } ;
52-
5330 return {
5431 run : async ( task ) => {
5532 if ( running ) {
5633 throw new Error ( 'Request execution locks cannot run the same scope concurrently.' ) ;
5734 }
5835 running = true ;
59- const outer = enclosing ( ) ;
60- const heldOutside = outer . flatMap ( ( held ) => [ ...held ] ) ;
36+ // What the requests this one is nested in hold (a batch step runs inside its batch). Its own
37+ // initial keys are taken in sorted order, waiting for each in turn.
38+ const heldOutside = heldRequestLockKeys ( locks ) ;
6139 try {
6240 return await withRequestExecutionLockKeys (
6341 locks ,
6442 initialKeys ,
65- async ( ) => await enclosingRequestLocks . run ( [ ...outer , heldLocks ] , task ) ,
43+ async ( ) =>
44+ await withKeyedLockHolder ( async ( taken ) => {
45+ holder = taken ;
46+ return await task ( ) ;
47+ } ) ,
6648 scope ?. signal ,
67- ( key ) => {
68- // An enclosing request already holding this lock re-enters it without waiting.
69- if ( ! heldOutside . includes ( key ) ) assertSameHostLockFree ( locks , key , heldOutside ) ;
70- heldLocks . add ( key ) ;
71- } ,
49+ ( key ) => assertSameHostLockFree ( locks , key , heldOutside ) ,
7250 ) ;
7351 } finally {
74- heldLocks . clear ( ) ;
75- try {
76- await releaseRetainedLocks ( ) ;
77- } finally {
78- running = false ;
79- }
52+ holder = undefined ;
53+ running = false ;
8054 }
8155 } ,
8256 retainDevice : async ( deviceId ) => {
83- if ( ! running ) {
57+ if ( ! holder ) {
8458 throw new Error ( 'A device execution lock can only be retained by a running request.' ) ;
8559 }
8660 const key = `device:${ deviceId } ` as const ;
87- if ( initialKeySet . has ( key ) ) return ;
88- // An enclosing request already holds it, and this request runs inside that hold.
89- if ( enclosing ( ) . some ( ( held ) => held . has ( key ) ) ) return ;
90-
91- let retained = retainedLocks . get ( key ) ;
92- if ( ! retained ) {
93- const heldKeys = [ ...heldLocks , ...enclosing ( ) . flatMap ( ( held ) => [ ...held ] ) ] ;
94- assertSameHostLockFree ( locks , key , heldKeys ) ;
95- retained = retainExecutionLock ( locks , key , scope ?. signal ) ;
96- retainedLocks . set ( key , retained ) ;
97- heldLocks . add ( key ) ;
98- }
99- await retained . acquired ;
61+ assertSameHostLockFree ( locks , key , heldRequestLockKeys ( locks ) ) ;
62+ await holder . hold ( locks , key , scope ?. signal ) ;
10063 } ,
10164 } ;
10265}
10366
67+ function heldRequestLockKeys ( locks : Map < string , Promise < unknown > > ) : RequestExecutionLockKey [ ] {
68+ return heldKeyedLockKeys ( locks ) as RequestExecutionLockKey [ ] ;
69+ }
70+
10471/**
10572 * Whether the request already holds a lock on `deviceId`'s host or one of its app devices
10673 * (ADR 0035). Waiting for a second lock on the same host while holding one could cross another
@@ -113,7 +80,8 @@ function assertSameHostLockFree(
11380 key : RequestExecutionLockKey ,
11481 heldKeys : readonly RequestExecutionLockKey [ ] ,
11582) : void {
116- if ( ! key . startsWith ( 'device:' ) ) return ;
83+ // A held key re-enters, and only device keys belong to a host.
84+ if ( heldKeys . includes ( key ) || ! key . startsWith ( 'device:' ) ) return ;
11785 const deviceId = key . slice ( 'device:' . length ) ;
11886 if ( holdsDeviceOfSameHost ( deviceId , heldKeys ) && locks . has ( key ) ) {
11987 throw deviceExecutionLockBusy ( deviceId ) ;
@@ -164,31 +132,3 @@ export async function withRequestExecutionLockKeys<T>(
164132 signal ,
165133 ) ;
166134}
167-
168- function retainExecutionLock (
169- locks : Map < string , Promise < unknown > > ,
170- key : RequestExecutionLockKey ,
171- signal ?: AbortSignal ,
172- ) : RetainedExecutionLock {
173- let markAcquired : ( ) => void = ( ) => { } ;
174- let rejectAcquired : ( error : unknown ) => void = ( ) => { } ;
175- let release : ( ) => void = ( ) => { } ;
176- const acquired = new Promise < void > ( ( resolve , reject ) => {
177- markAcquired = resolve ;
178- rejectAcquired = reject ;
179- } ) ;
180- const released = new Promise < void > ( ( resolve ) => {
181- release = resolve ;
182- } ) ;
183- const completion = withKeyedLock (
184- locks ,
185- key ,
186- async ( ) => {
187- markAcquired ( ) ;
188- await released ;
189- } ,
190- signal ,
191- ) ;
192- void completion . catch ( ( error ) => rejectAcquired ( error ) ) ;
193- return { acquired, completion, release } ;
194- }
0 commit comments