@@ -520,22 +520,35 @@ describe("gateway usage helpers", () => {
520520 } ) ;
521521 } ) ;
522522
523- it ( "usage.cost all-agent scope bounds concurrency to COST_USAGE_AGENT_LOAD_CONCURRENCY " , async ( ) => {
524- const agentCount = 25 ;
523+ it ( "bounds usage.cost all-agent cache loads " , async ( ) => {
524+ const agentCount = 13 ;
525525 const concurrencyLimit = 12 ;
526+ let releaseLoads ! : ( ) => void ;
527+ const loadsReleased = new Promise < void > ( ( resolve ) => {
528+ releaseLoads = resolve ;
529+ } ) ;
530+ let resolveFirstBatchStarted ! : ( ) => void ;
531+ const firstBatchStarted = new Promise < void > ( ( resolve ) => {
532+ resolveFirstBatchStarted = resolve ;
533+ } ) ;
534+ let started = 0 ;
526535 let inFlight = 0 ;
527536 let peakInFlight = 0 ;
528537
529538 vi . mocked ( loadCostUsageSummaryFromCache ) . mockImplementation ( async ( ) => {
530- inFlight ++ ;
539+ started += 1 ;
540+ inFlight += 1 ;
531541 peakInFlight = Math . max ( peakInFlight , inFlight ) ;
532- await new Promise < void > ( ( r ) => { setTimeout ( r , 0 ) ; } ) ;
533- inFlight -- ;
542+ if ( started === concurrencyLimit ) {
543+ resolveFirstBatchStarted ( ) ;
544+ }
545+ await loadsReleased ;
546+ inFlight -= 1 ;
534547 return costSummary ( { totalTokens : 1 , totalCost : 0 } ) ;
535548 } ) ;
536549
537550 const respond = vi . fn ( ) ;
538- await usageHandlers [ "usage.cost" ] ( {
551+ const request = usageHandlers [ "usage.cost" ] ( {
539552 respond,
540553 params : { startDate : "2026-02-01" , endDate : "2026-02-02" , agentScope : "all" } ,
541554 context : {
@@ -547,8 +560,14 @@ describe("gateway usage helpers", () => {
547560 } ,
548561 } as unknown as Parameters < ( typeof usageHandlers ) [ "usage.cost" ] > [ 0 ] ) ;
549562
550- expect ( peakInFlight ) . toBeLessThanOrEqual ( concurrencyLimit ) ;
551- expect ( peakInFlight ) . toBe ( concurrencyLimit ) ;
563+ await firstBatchStarted ;
564+ const startedBeforeRelease = started ;
565+ const peakBeforeRelease = peakInFlight ;
566+ releaseLoads ( ) ;
567+ await request ;
568+
569+ expect ( startedBeforeRelease ) . toBe ( concurrencyLimit ) ;
570+ expect ( peakBeforeRelease ) . toBe ( concurrencyLimit ) ;
552571 expect ( respond ) . toHaveBeenCalledWith (
553572 true ,
554573 expect . objectContaining ( {
0 commit comments