@@ -499,7 +499,9 @@ export async function updateUserUsageLimit(
499499 * Org-scoped members carry a null `currentUsageLimit` by design (see
500500 * `syncUsageLimitsFromSubscription`). A user whose subscription stops being
501501 * org-scoped without a resync would otherwise stay null and fail closed on
502- * every execution, so a null limit self-heals to the plan default here.
502+ * every execution, so a null limit self-heals to the plan default here. The
503+ * write-back is best-effort: a limit written concurrently wins, and a failed
504+ * write still resolves to the fallback instead of blocking execution.
503505 */
504506export async function getUserUsageLimit (
505507 userId : string ,
@@ -547,19 +549,36 @@ export async function getUserUsageLimit(
547549 ? getPerUserMinimumLimit ( subscription )
548550 : getFreeTierLimit ( )
549551
550- await db
551- . update ( userStats )
552- . set ( {
553- currentUsageLimit : fallbackLimit . toString ( ) ,
554- usageLimitUpdatedAt : new Date ( ) ,
555- } )
556- . where ( and ( eq ( userStats . userId , userId ) , isNull ( userStats . currentUsageLimit ) ) )
552+ try {
553+ const healed = await db
554+ . update ( userStats )
555+ . set ( {
556+ currentUsageLimit : fallbackLimit . toString ( ) ,
557+ usageLimitUpdatedAt : new Date ( ) ,
558+ } )
559+ . where ( and ( eq ( userStats . userId , userId ) , isNull ( userStats . currentUsageLimit ) ) )
560+ . returning ( { currentUsageLimit : userStats . currentUsageLimit } )
561+
562+ if ( healed . length === 0 ) {
563+ const concurrent = await db
564+ . select ( { currentUsageLimit : userStats . currentUsageLimit } )
565+ . from ( userStats )
566+ . where ( eq ( userStats . userId , userId ) )
567+ . limit ( 1 )
557568
558- logger . warn ( 'Healed null usage limit to plan default' , {
559- userId,
560- plan : subscription ?. plan || 'free' ,
561- fallbackLimit,
562- } )
569+ if ( concurrent [ 0 ] ?. currentUsageLimit ) {
570+ return toNumber ( toDecimal ( concurrent [ 0 ] . currentUsageLimit ) )
571+ }
572+ }
573+
574+ logger . warn ( 'Healed null usage limit to plan default' , {
575+ userId,
576+ plan : subscription ?. plan || 'free' ,
577+ fallbackLimit,
578+ } )
579+ } catch ( error ) {
580+ logger . error ( 'Failed to heal null usage limit' , { userId, fallbackLimit, error } )
581+ }
563582
564583 return fallbackLimit
565584 }
0 commit comments