Skip to content

Commit 2a4f666

Browse files
Merge pull request #21 from LitePy/fix/ci-main-green
fix: isolate retry ownership across copied execution contexts
2 parents 0178111 + 543c6e3 commit 2a4f666

6 files changed

Lines changed: 84 additions & 16 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,12 @@ 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, and stored
26+
retry scopes do not retain finished tasks.
27+
2228
## [0.4.0b2] - 2026-11-26
2329

2430
### Breaking changes

‎src/python_wrap/llm.py‎

Lines changed: 37 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
import threading
4242
import time
4343
import uuid
44+
import weakref
4445
from collections import OrderedDict
4546
from 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+
444473
def _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)):

‎tests/test_adapters_sdk.py‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,13 @@
1212

1313
import asyncio
1414
import contextlib
15+
import contextvars
1516
import copy
17+
import gc
1618
import json
1719
import threading
1820
import warnings
21+
import weakref
1922
from collections.abc import AsyncIterator, Iterator
2023
from types import SimpleNamespace
2124
from typing import Any
@@ -561,7 +564,10 @@ def in_thread() -> None:
561564

562565
@llm_retry(max_attempts=2, delay=1, jitter=0, owns_retries=True)
563566
def owner() -> None:
564-
thread = threading.Thread(target=in_thread)
567+
# Model Python versions/configurations where a new thread inherits the
568+
# parent's ContextVars. The copied scope belongs to the parent thread only.
569+
context = contextvars.copy_context()
570+
thread = threading.Thread(target=lambda: context.run(in_thread))
565571
thread.start()
566572
thread.join()
567573
raise Overloaded
@@ -571,6 +577,22 @@ def owner() -> None:
571577
assert len(seen) == 2 * 3 # a new thread does not inherit the owner scope
572578

573579

580+
def test_copied_owner_context_does_not_retain_finished_task() -> None:
581+
captured: dict[str, Any] = {}
582+
583+
@llm_retry(max_attempts=1, owns_retries=True)
584+
async def owner() -> None:
585+
task = asyncio.current_task()
586+
assert task is not None
587+
captured["task"] = weakref.ref(task)
588+
captured["context"] = contextvars.copy_context()
589+
590+
asyncio.run(owner())
591+
gc.collect()
592+
593+
assert captured["task"]() is None
594+
595+
574596
def test_llm_retry_settings_and_stats_survive_the_owner_wrapper() -> None:
575597
@llm_retry(max_attempts=2, owns_retries=True, client=FakeClient(max_retries=3))
576598
def call() -> str:

‎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)