@@ -151,6 +151,8 @@ def __init__(
151151 self .audience = audience
152152 self .token_cache : Dict [str , _TokenCacheEntry ] = {}
153153 self .actor_token_cache : Optional [_TokenCacheEntry ] = None
154+ # Earliest expiry across token_cache; None when no cached token expires.
155+ self ._earliest_expiry : Optional [int ] = None
154156
155157 def add_to_agent (self , agent : BaseAgent ):
156158 """
@@ -240,17 +242,26 @@ async def before_run_callback(
240242 token = subject_token ,
241243 expiry = expiry ,
242244 )
245+ self ._earliest_expiry = _earlier_expiry (self ._earliest_expiry , expiry )
243246 logger .debug ("Cached new subject token" )
244247 return None
245248
246249 def _read_subject_token (self , state : dict ) -> Optional [str ]:
247- """Resolve the acting caller's subject token from session state."""
250+ """Resolve the acting caller's subject token from session state.
251+
252+ get_subject_token is caller-supplied, so a raising implementation fails
253+ closed (no token propagated) instead of aborting the agent run.
254+ """
248255 get_subject_token = (
249256 self .sts_integration .get_subject_token
250257 if self .sts_integration and self .sts_integration .get_subject_token
251258 else _default_get_subject_token
252259 )
253- return get_subject_token (state )
260+ try :
261+ return get_subject_token (state )
262+ except Exception as e :
263+ logger .warning (f"Failed to read subject token from session state: { e } " )
264+ return None
254265
255266 def _cache_key_for (self , session_id : str , subject_token : Optional [str ]) -> str :
256267 return f"{ session_id } \0 { _subject_key (subject_token )} "
@@ -314,12 +325,7 @@ async def after_run_callback(
314325 invocation_context : InvocationContext ,
315326 ) -> Optional [dict ]:
316327 """Clean up expired tokens after run, preserving valid tokens."""
317- # A session now holds one entry per subject, and only the acting
318- # subject's key is derivable here, so sweep every expired entry rather
319- # than leaving the other subjects' behind.
320- for key in [key for key , entry in self .token_cache .items () if _has_token_expired (entry .expiry )]:
321- logger .debug ("Removing expired subject token from cache" )
322- self .token_cache .pop (key , None )
328+ self ._sweep_expired_subject_tokens ()
323329
324330 # Clean up expired actor token cache
325331 if self .actor_token_cache and _has_token_expired (self .actor_token_cache .expiry ):
@@ -328,6 +334,37 @@ async def after_run_callback(
328334
329335 return None
330336
337+ def _sweep_expired_subject_tokens (self ) -> None :
338+ """Drop every expired subject token from the cache.
339+
340+ A session holds one entry per subject and only the acting subject's key
341+ is derivable here, so entries belonging to other subjects and other
342+ sessions are swept too; scoping the sweep to the current session would
343+ keep the entries of sessions that never run again forever. The earliest
344+ expiry gates the scan, so a growing cache is only walked when there is
345+ something to evict.
346+ """
347+ if self ._earliest_expiry is None or not _has_token_expired (self ._earliest_expiry ):
348+ return
349+
350+ earliest_expiry : Optional [int ] = None
351+ for key , entry in list (self .token_cache .items ()):
352+ if _has_token_expired (entry .expiry ):
353+ logger .debug ("Removing expired subject token from cache" )
354+ self .token_cache .pop (key , None )
355+ continue
356+ earliest_expiry = _earlier_expiry (earliest_expiry , entry .expiry )
357+ self ._earliest_expiry = earliest_expiry
358+
359+
360+ def _earlier_expiry (current : Optional [int ], candidate : Optional [int ]) -> Optional [int ]:
361+ """Return the earlier of two expiries; None means "does not expire"."""
362+ if candidate is None :
363+ return current
364+ if current is None :
365+ return candidate
366+ return min (current , candidate )
367+
331368
332369def _has_token_expired (expiry : Optional [int ], buffer_seconds : int = 5 ) -> bool :
333370 """Check if a token has expired or will expire soon.
0 commit comments