@@ -559,6 +559,81 @@ export async function sumUserTotalCost(
559559 return Number ( result [ 0 ] ?. total || 0 ) ;
560560}
561561
562+ function isValidResetAt ( resetAt : Date | null | undefined ) : resetAt is Date {
563+ return resetAt instanceof Date && ! Number . isNaN ( resetAt . getTime ( ) ) ;
564+ }
565+
566+ /**
567+ * Resolve the effective lower bound for a total-cost query: the later of the
568+ * max-age cutoff and a valid reset timestamp. Returns null for all-time.
569+ */
570+ function resolveTotalCostCutoff ( maxAgeDays : number , resetAt ?: Date | null ) : Date | null {
571+ const maxAgeCutoff =
572+ Number . isFinite ( maxAgeDays ) && maxAgeDays > 0
573+ ? new Date ( Date . now ( ) - Math . floor ( maxAgeDays ) * 24 * 60 * 60 * 1000 )
574+ : null ;
575+ if ( isValidResetAt ( resetAt ) ) {
576+ return maxAgeCutoff && maxAgeCutoff > resetAt ? maxAgeCutoff : resetAt ;
577+ }
578+ return maxAgeCutoff ;
579+ }
580+
581+ // Keep each VALUES-join statement well below the driver parameter limit.
582+ const TOTAL_COST_CUTOFF_CHUNK_SIZE = 1000 ;
583+
584+ interface TotalCostCutoffEntry {
585+ entityKey : number | string ;
586+ cutoff : Date ;
587+ }
588+
589+ /**
590+ * Total cost for entities that each carry their own cutoff, aggregated in a
591+ * single SQL statement (per chunk) instead of one query per entity.
592+ *
593+ * A per-entity Promise.all fan-out here can exceed the database pool
594+ * admission limit on fan-out pages such as the user quota list (issue #1511).
595+ * Returns Map of String(entityKey) -> totalCost. Duplicate entity keys keep
596+ * the last cutoff, matching the previous per-entity overwrite order.
597+ */
598+ async function sumTotalCostWithCutoffs (
599+ entityType : "user" | "key" ,
600+ entries : readonly TotalCostCutoffEntry [ ]
601+ ) : Promise < Map < string , number > > {
602+ const totals = new Map < string , number > ( ) ;
603+ const entityColumn = entityType === "user" ? usageLedger . userId : usageLedger . key ;
604+
605+ const deduped = new Map < string , TotalCostCutoffEntry > ( ) ;
606+ for ( const entry of entries ) {
607+ deduped . set ( String ( entry . entityKey ) , entry ) ;
608+ }
609+ const uniqueEntries = [ ...deduped . values ( ) ] ;
610+
611+ for ( let start = 0 ; start < uniqueEntries . length ; start += TOTAL_COST_CUTOFF_CHUNK_SIZE ) {
612+ const chunk = uniqueEntries . slice ( start , start + TOTAL_COST_CUTOFF_CHUNK_SIZE ) ;
613+ const valueRows = chunk . map ( ( entry ) =>
614+ entityType === "user"
615+ ? sql `(${ entry . entityKey as number } ::int, ${ entry . cutoff . toISOString ( ) } ::timestamptz)`
616+ : sql `(${ entry . entityKey as string } ::text, ${ entry . cutoff . toISOString ( ) } ::timestamptz)`
617+ ) ;
618+
619+ const rows = await db . execute ( sql `
620+ SELECT c.entity_id AS entity_id, COALESCE(SUM(${ usageLedger . costUsd } ), 0) AS total
621+ FROM (VALUES ${ sql . join ( valueRows , sql `, ` ) } ) AS c(entity_id, cutoff)
622+ LEFT JOIN ${ usageLedger }
623+ ON ${ entityColumn } = c.entity_id
624+ AND ${ usageLedger . createdAt } >= c.cutoff
625+ AND ${ LEDGER_BILLING_CONDITION }
626+ GROUP BY c.entity_id
627+ ` ) ;
628+
629+ for ( const row of Array . from ( rows ) as Array < { entity_id : unknown ; total : unknown } > ) {
630+ totals . set ( String ( row . entity_id ) , Number ( row . total || 0 ) ) ;
631+ }
632+ }
633+
634+ return totals ;
635+ }
636+
562637/**
563638 * Batch query: total cost grouped by user_id (single SQL query)
564639 * @param userIds - Array of user IDs
@@ -574,26 +649,29 @@ export async function sumUserTotalCostBatch(
574649 if ( userIds . length === 0 ) return result ;
575650 for ( const id of userIds ) result . set ( id , 0 ) ;
576651
577- // Split users: those with costResetAt need individual queries
578- const resetUserIds : number [ ] = [ ] ;
652+ // Split users: those with a valid costResetAt carry their own cutoff and
653+ // are aggregated in a single statement. An invalid reset date behaves
654+ // like no reset, matching sumUserTotalCost.
655+ const resetEntries : Array < { id : number ; cutoff : Date } > = [ ] ;
579656 const batchUserIds : number [ ] = [ ] ;
580657 for ( const id of userIds ) {
581- if ( resetAtMap ?. has ( id ) ) {
582- resetUserIds . push ( id ) ;
658+ const resetAt = resetAtMap ?. get ( id ) ;
659+ if ( isValidResetAt ( resetAt ) ) {
660+ // A valid reset always yields a cutoff (at least the reset itself).
661+ resetEntries . push ( { id, cutoff : resolveTotalCostCutoff ( maxAgeDays , resetAt ) as Date } ) ;
583662 } else {
584663 batchUserIds . push ( id ) ;
585664 }
586665 }
587666
588- // Individual queries for users with costResetAt
589- if ( resetUserIds . length > 0 ) {
590- const resetResults = await Promise . all (
591- resetUserIds . map ( async ( id ) => ( {
592- id,
593- total : await sumUserTotalCost ( id , maxAgeDays , resetAtMap ! . get ( id ) ) ,
594- } ) )
667+ if ( resetEntries . length > 0 ) {
668+ const resetTotals = await sumTotalCostWithCutoffs (
669+ "user" ,
670+ resetEntries . map ( ( { id, cutoff } ) => ( { entityKey : id , cutoff } ) )
595671 ) ;
596- for ( const { id, total } of resetResults ) result . set ( id , total ) ;
672+ for ( const { id } of resetEntries ) {
673+ result . set ( id , resetTotals . get ( String ( id ) ) ?? 0 ) ;
674+ }
597675 }
598676
599677 // Batch query for users without costResetAt
@@ -643,34 +721,35 @@ export async function sumKeyTotalCostBatchByIds(
643721 . where ( inArray ( keys . id , keyIds ) ) ;
644722
645723 const keyStringToId = new Map ( keyMappings . map ( ( k ) => [ k . key , k . id ] ) ) ;
646- const idToKeyString = new Map ( keyMappings . map ( ( k ) => [ k . id , k . key ] ) ) ;
647724 const keyStrings = keyMappings . map ( ( k ) => k . key ) ;
648725 if ( keyStrings . length === 0 ) return result ;
649726
650- // Split keys: those with costResetAt need individual queries
651- const resetKeyIds : number [ ] = [ ] ;
727+ // Split keys: those with a valid costResetAt carry their own cutoff and
728+ // are aggregated in a single statement. An invalid reset date behaves
729+ // like no reset, matching sumKeyTotalCost.
730+ const resetEntries : Array < { id : number ; keyString : string ; cutoff : Date } > = [ ] ;
652731 const batchKeyStrings : string [ ] = [ ] ;
653732 for ( const mapping of keyMappings ) {
654- if ( resetAtMap ?. has ( mapping . id ) ) {
655- resetKeyIds . push ( mapping . id ) ;
733+ const resetAt = resetAtMap ?. get ( mapping . id ) ;
734+ if ( isValidResetAt ( resetAt ) ) {
735+ resetEntries . push ( {
736+ id : mapping . id ,
737+ keyString : mapping . key ,
738+ cutoff : resolveTotalCostCutoff ( maxAgeDays , resetAt ) as Date ,
739+ } ) ;
656740 } else {
657741 batchKeyStrings . push ( mapping . key ) ;
658742 }
659743 }
660744
661- // Individual queries for keys with costResetAt
662- if ( resetKeyIds . length > 0 ) {
663- const resetResults = await Promise . all (
664- resetKeyIds . map ( async ( id ) => {
665- const keyString = idToKeyString . get ( id ) ;
666- if ( ! keyString ) return { id, total : 0 } ;
667- return {
668- id,
669- total : await sumKeyTotalCost ( keyString , maxAgeDays , resetAtMap ! . get ( id ) ) ,
670- } ;
671- } )
745+ if ( resetEntries . length > 0 ) {
746+ const resetTotals = await sumTotalCostWithCutoffs (
747+ "key" ,
748+ resetEntries . map ( ( { keyString, cutoff } ) => ( { entityKey : keyString , cutoff } ) )
672749 ) ;
673- for ( const { id, total } of resetResults ) result . set ( id , total ) ;
750+ for ( const { id, keyString } of resetEntries ) {
751+ result . set ( id , resetTotals . get ( keyString ) ?? 0 ) ;
752+ }
674753 }
675754
676755 // Step 2: Batch aggregate for keys without costResetAt
0 commit comments