11import { spawnSync } from "node:child_process" ;
22import { describe , expect , it } from "vitest" ;
3+ import { testing as workerTesting } from "../../scripts/bench-agent-concurrency-worker.ts" ;
34import {
45 testing ,
56 WORKER_RESULT_SENTINEL ,
67 type WorkerResult ,
78 type WorkerScenario ,
89} from "../../scripts/bench-agent-concurrency.ts" ;
10+ import {
11+ resetGatewayWorkAdmission ,
12+ runWithGatewayIndependentRootWorkAdmission ,
13+ } from "../../src/process/gateway-work-admission.js" ;
14+ import { createDeferred } from "../../src/test-utils/deferred.js" ;
915
1016function workerResult ( scenario : WorkerScenario , size : number , timingsMs = [ 1 , 2 , 3 ] ) : WorkerResult {
1117 const invariant : Record < string , number | boolean > =
@@ -25,6 +31,7 @@ function workerResult(scenario: WorkerScenario, size: number, timingsMs = [1, 2,
2531 postTeardownTaskRows : 0 ,
2632 postTeardownDurableSubagentRows : 0 ,
2733 postTeardownDurableTaskRows : 0 ,
34+ postTeardownActiveRootWork : 0 ,
2835 }
2936 : scenario === "admission"
3037 ? { ok : true , admissionCap : size , overflowRejected : true , released : true }
@@ -108,6 +115,37 @@ describe("agent concurrency benchmark", () => {
108115 expect ( summary ) . toMatchObject ( { count : 20 , p50 : 10 , p95 : 19 , p99 : 20 , max : 20 } ) ;
109116 } ) ;
110117
118+ it ( "drains detached gateway root work before the next spawn sample" , async ( ) => {
119+ resetGatewayWorkAdmission ( ) ;
120+ const deferred = createDeferred ( ) ;
121+ const rootWork = runWithGatewayIndependentRootWorkAdmission ( ( ) => deferred . promise ) ;
122+ try {
123+ const drain = workerTesting . drainSpawnSampleRootWork ( ) ;
124+ await expect (
125+ Promise . race ( [
126+ drain . then ( ( ) => "drained" ) ,
127+ new Promise < string > ( ( resolve ) => setImmediate ( ( ) => resolve ( "pending" ) ) ) ,
128+ ] ) ,
129+ ) . resolves . toBe ( "pending" ) ;
130+
131+ deferred . resolve ( ) ;
132+ await expect ( drain ) . resolves . toBeUndefined ( ) ;
133+ } finally {
134+ deferred . resolve ( ) ;
135+ await rootWork ;
136+ resetGatewayWorkAdmission ( ) ;
137+ }
138+ } ) ;
139+
140+ it ( "rejects a spawn sample when detached gateway root work does not drain" , async ( ) => {
141+ await expect (
142+ workerTesting . drainSpawnSampleRootWork ( async ( timeoutMs ) => {
143+ expect ( timeoutMs ) . toBe ( 30_000 ) ;
144+ return { drained : false , active : 2 } ;
145+ } ) ,
146+ ) . rejects . toThrow ( "spawn sample left 2 active gateway root work items" ) ;
147+ } ) ;
148+
111149 it ( "aggregates synthetic worker results into schema version 2" , ( ) => {
112150 const options = testing . parseOptions ( [
113151 "--runs" ,
0 commit comments