@@ -400,10 +400,10 @@ def decorate(func: Callable[P, R]) -> Callable[P, R]:
400400
401401 @functools .wraps (func )
402402 async def async_wrapper (* args : Any , ** kwargs : Any ) -> Any :
403- state = _RETRY_SCOPE . get ()
403+ state = _active_retry_scope ()
404404 if single (state ):
405405 return await afunc (* args , ** kwargs )
406- token = _RETRY_SCOPE .set (state if state == "owner" else mark )
406+ token = _RETRY_SCOPE .set (( state if state == "owner" else mark , _retry_identity ()) )
407407 try :
408408 return await looped (* args , ** kwargs )
409409 finally :
@@ -414,10 +414,10 @@ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
414414
415415 @functools .wraps (func )
416416 def sync_wrapper (* args : Any , ** kwargs : Any ) -> Any :
417- state = _RETRY_SCOPE . get ()
417+ state = _active_retry_scope ()
418418 if single (state ):
419419 return func (* args , ** kwargs )
420- token = _RETRY_SCOPE .set (state if state == "owner" else mark )
420+ token = _RETRY_SCOPE .set (( state if state == "owner" else mark , _retry_identity ()) )
421421 try :
422422 return looped (* args , ** kwargs )
423423 finally :
@@ -434,13 +434,36 @@ def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
434434 return decorate
435435
436436
437- #: None outside any `llm_retry`, ``"loop"`` inside one, ``"owner"`` inside an
438- #: ``owns_retries=True`` one (where nested retries make a single attempt) .
439- _RETRY_SCOPE : contextvars .ContextVar [str | None ] = contextvars .ContextVar (
437+ #: Current retry scope and its task/thread identity. The scope is ignored when a copied
438+ #: context runs under a different identity .
439+ _RETRY_SCOPE : contextvars .ContextVar [tuple [ str , object ] | None ] = contextvars .ContextVar (
440440 "python_wrap_llm_retry_scope" , default = None
441441)
442442
443443
444+ def _retry_identity () -> object :
445+ """Identify the task or thread that owns an LLM retry scope.
446+
447+ Context variables can be explicitly copied into a new thread, and free-threaded
448+ Python may inherit them by default. A copied scope must not suppress retries in an
449+ independent execution owner.
450+ """
451+ try :
452+ task = asyncio .current_task ()
453+ except RuntimeError :
454+ task = None
455+ if task is not None :
456+ return task
457+ return threading .current_thread ()
458+
459+
460+ def _active_retry_scope () -> str | None :
461+ scope = _RETRY_SCOPE .get ()
462+ if scope is None or scope [1 ] is not _retry_identity ():
463+ return None
464+ return scope [0 ]
465+
466+
444467def _sdk_retries (client : Any ) -> int | None :
445468 """The ``max_retries`` an SDK client (or a guard around one) is set to, or None."""
446469 for source in (client , getattr (client , "_client" , None )):
0 commit comments