Skip to content

Commit 353832b

Browse files
fix: isolate retry ownership across copied execution contexts
1 parent 6840c42 commit 353832b

6 files changed

Lines changed: 58 additions & 15 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,11 @@ Breaking changes are listed under **Breaking changes**, each with its migration.
1919
stay alive and disrupt later invalidations. A synchronous shutdown callback that times out
2020
exhausts the remaining finite drain budget before another callback can start.
2121

22+
### Fixed
23+
24+
- LLM retry ownership is now limited to the task or thread that established it. A copied
25+
context in a new execution owner no longer suppresses that owner's retries.
26+
2227
## [0.4.0b2] - 2026-11-26
2328

2429
### Breaking changes

‎src/python_wrap/llm.py‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
444467
def _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)):

‎tests/test_adapters_sdk.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
import asyncio
1414
import contextlib
15+
import contextvars
1516
import copy
1617
import json
1718
import threading
@@ -561,7 +562,10 @@ def in_thread() -> None:
561562

562563
@llm_retry(max_attempts=2, delay=1, jitter=0, owns_retries=True)
563564
def owner() -> None:
564-
thread = threading.Thread(target=in_thread)
565+
# Model Python versions/configurations where a new thread inherits the
566+
# parent's ContextVars. The copied scope belongs to the parent thread only.
567+
context = contextvars.copy_context()
568+
thread = threading.Thread(target=lambda: context.run(in_thread))
565569
thread.start()
566570
thread.join()
567571
raise Overloaded

‎tests/test_batching.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -429,12 +429,18 @@ def load(ids: list[int]) -> list[int]:
429429
def test_sync_duplicates_share_a_result():
430430
calls = []
431431

432-
@batch_calls(max_size=2, max_wait=10, key=str.lower)
432+
@batch_calls(max_size=3, max_wait=1, key=str.lower)
433433
def load(names: list[str]) -> dict[str, int]:
434434
calls.append(list(names))
435435
return {n.lower(): len(calls) for n in names}
436436

437-
results, _ = run_threads(3, lambda i: load(["A", "a", "b"][i]))
437+
callers = threading.Barrier(3)
438+
439+
def call(i: int) -> int:
440+
callers.wait()
441+
return load(["A", "a", "b"][i])
442+
443+
results, _ = run_threads(3, call)
438444
assert results == [1, 1, 1]
439445
assert len(calls) == 1
440446
assert sorted(n.lower() for n in calls[0]) == ["a", "b"]

‎tests/test_caching_copy.py‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import pytest
1010

1111
from conftest import FakeClock
12-
from python_wrap import memoize, singleflight
12+
from python_wrap import memoize
1313
from python_wrap.testing import disable_caching
1414
from test_caching_extras import DictStore
1515

@@ -102,8 +102,7 @@ def test_sync_singleflight_waiters_are_isolated() -> None:
102102
release = threading.Event()
103103
calls = 0
104104

105-
@memoize(copy_result=True)
106-
@singleflight
105+
@memoize(copy_result=True, singleflight=True)
107106
def load() -> list[int]:
108107
nonlocal calls
109108
calls += 1
@@ -114,7 +113,13 @@ def load() -> list[int]:
114113
# Holding the leader lets all subsequent calls overlap; joining a completed
115114
# cache hit is also valid, since both paths must deliver independent copies.
116115
results: list[list[int]] = []
117-
threads = [threading.Thread(target=lambda: results.append(load())) for _ in range(4)]
116+
callers = threading.Barrier(4)
117+
118+
def call() -> None:
119+
callers.wait()
120+
results.append(load())
121+
122+
threads = [threading.Thread(target=call) for _ in range(4)]
118123
for thread in threads:
119124
thread.start()
120125
assert entered.wait(2)

‎tests/test_observability.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ def flaky():
155155
spans = exporter.get_finished_spans()
156156
attempts = [s for s in spans if s.name == "python_wrap.retry.attempt"]
157157
assert [s.attributes["python_wrap.retry.attempt"] for s in attempts] == [1, 2, 3]
158-
assert all(s.end_time > s.start_time for s in spans) # no zero-length span
158+
assert all(s.end_time > s.start_time for s in attempts) # no zero-length attempt span
159159
request = next(s for s in spans if s.name == "request")
160160
assert any(e.name == "pw.retry.gave_up" for e in request.events)
161161
assert sum(p.value for p in _points(reader, "python_wrap.retry.gave_up")) == 1

0 commit comments

Comments
 (0)