4141import threading
4242import time
4343import uuid
44+ import weakref
4445from collections import OrderedDict
4546from collections .abc import (
4647 AsyncIterable ,
@@ -400,10 +401,10 @@ def decorate(func: Callable[P, R]) -> Callable[P, R]:
400401
401402 @functools .wraps (func )
402403 async def async_wrapper (* args : Any , ** kwargs : Any ) -> Any :
403- state = _RETRY_SCOPE . get ()
404+ state = _active_retry_scope ()
404405 if single (state ):
405406 return await afunc (* args , ** kwargs )
406- token = _RETRY_SCOPE .set (state if state == "owner" else mark )
407+ token = _RETRY_SCOPE .set (( state if state == "owner" else mark , _retry_identity ()) )
407408 try :
408409 return await looped (* args , ** kwargs )
409410 finally :
@@ -414,10 +415,10 @@ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
414415
415416 @functools .wraps (func )
416417 def sync_wrapper (* args : Any , ** kwargs : Any ) -> Any :
417- state = _RETRY_SCOPE . get ()
418+ state = _active_retry_scope ()
418419 if single (state ):
419420 return func (* args , ** kwargs )
420- token = _RETRY_SCOPE .set (state if state == "owner" else mark )
421+ token = _RETRY_SCOPE .set (( state if state == "owner" else mark , _retry_identity ()) )
421422 try :
422423 return looped (* args , ** kwargs )
423424 finally :
@@ -434,13 +435,41 @@ def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
434435 return decorate
435436
436437
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 (
440- "python_wrap_llm_retry_scope" , default = None
438+ #: Current retry scope and its task/thread identity. The scope is ignored when a copied
439+ #: context runs under a different identity .
440+ _RETRY_SCOPE : contextvars .ContextVar [tuple [ str , weakref . ReferenceType [ object ]] | None ] = (
441+ contextvars . ContextVar ( "python_wrap_llm_retry_scope" , default = None )
441442)
442443
443444
445+ def _retry_owner () -> object :
446+ """Identify the task or thread that owns an LLM retry scope.
447+
448+ Context variables can be explicitly copied into a new thread, and free-threaded
449+ Python may inherit them by default. A copied scope must not suppress retries in an
450+ independent execution owner. Return the object itself only transiently; the stored
451+ scope keeps a weak reference so a long-lived copied context cannot retain a task.
452+ """
453+ try :
454+ task = asyncio .current_task ()
455+ except RuntimeError :
456+ task = None
457+ if task is not None :
458+ return task
459+ return threading .current_thread ()
460+
461+
462+ def _retry_identity () -> weakref .ReferenceType [object ]:
463+ return weakref .ref (_retry_owner ())
464+
465+
466+ def _active_retry_scope () -> str | None :
467+ scope = _RETRY_SCOPE .get ()
468+ if scope is None or scope [1 ]() is not _retry_owner ():
469+ return None
470+ return scope [0 ]
471+
472+
444473def _sdk_retries (client : Any ) -> int | None :
445474 """The ``max_retries`` an SDK client (or a guard around one) is set to, or None."""
446475 for source in (client , getattr (client , "_client" , None )):
0 commit comments