diff --git a/CHANGELOG.md b/CHANGELOG.md index fe80257..8113664 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,12 @@ Breaking changes are listed under **Breaking changes**, each with its migration. stay alive and disrupt later invalidations. A synchronous shutdown callback that times out exhausts the remaining finite drain budget before another callback can start. +### Fixed + +- LLM retry ownership is now limited to the task or thread that established it. A copied + context in a new execution owner no longer suppresses that owner's retries, and stored + retry scopes do not retain finished tasks. + ## [0.4.0b2] - 2026-11-26 ### Breaking changes diff --git a/src/python_wrap/llm.py b/src/python_wrap/llm.py index 456c14f..c5e09f1 100644 --- a/src/python_wrap/llm.py +++ b/src/python_wrap/llm.py @@ -41,6 +41,7 @@ import threading import time import uuid +import weakref from collections import OrderedDict from collections.abc import ( AsyncIterable, @@ -400,10 +401,10 @@ def decorate(func: Callable[P, R]) -> Callable[P, R]: @functools.wraps(func) async def async_wrapper(*args: Any, **kwargs: Any) -> Any: - state = _RETRY_SCOPE.get() + state = _active_retry_scope() if single(state): return await afunc(*args, **kwargs) - token = _RETRY_SCOPE.set(state if state == "owner" else mark) + token = _RETRY_SCOPE.set((state if state == "owner" else mark, _retry_identity())) try: return await looped(*args, **kwargs) finally: @@ -414,10 +415,10 @@ async def async_wrapper(*args: Any, **kwargs: Any) -> Any: @functools.wraps(func) def sync_wrapper(*args: Any, **kwargs: Any) -> Any: - state = _RETRY_SCOPE.get() + state = _active_retry_scope() if single(state): return func(*args, **kwargs) - token = _RETRY_SCOPE.set(state if state == "owner" else mark) + token = _RETRY_SCOPE.set((state if state == "owner" else mark, _retry_identity())) try: return looped(*args, **kwargs) finally: @@ -434,13 +435,41 @@ def sync_wrapper(*args: Any, **kwargs: Any) -> Any: return decorate -#: None outside any `llm_retry`, ``"loop"`` inside one, ``"owner"`` inside an -#: ``owns_retries=True`` one (where nested retries make a single attempt). -_RETRY_SCOPE: contextvars.ContextVar[str | None] = contextvars.ContextVar( - "python_wrap_llm_retry_scope", default=None +#: Current retry scope and its task/thread identity. The scope is ignored when a copied +#: context runs under a different identity. +_RETRY_SCOPE: contextvars.ContextVar[tuple[str, weakref.ReferenceType[object]] | None] = ( + contextvars.ContextVar("python_wrap_llm_retry_scope", default=None) ) +def _retry_owner() -> object: + """Identify the task or thread that owns an LLM retry scope. + + Context variables can be explicitly copied into a new thread, and free-threaded + Python may inherit them by default. A copied scope must not suppress retries in an + independent execution owner. Return the object itself only transiently; the stored + scope keeps a weak reference so a long-lived copied context cannot retain a task. + """ + try: + task = asyncio.current_task() + except RuntimeError: + task = None + if task is not None: + return task + return threading.current_thread() + + +def _retry_identity() -> weakref.ReferenceType[object]: + return weakref.ref(_retry_owner()) + + +def _active_retry_scope() -> str | None: + scope = _RETRY_SCOPE.get() + if scope is None or scope[1]() is not _retry_owner(): + return None + return scope[0] + + def _sdk_retries(client: Any) -> int | None: """The ``max_retries`` an SDK client (or a guard around one) is set to, or None.""" for source in (client, getattr(client, "_client", None)): diff --git a/tests/test_adapters_sdk.py b/tests/test_adapters_sdk.py index 25d6036..9f4eebf 100644 --- a/tests/test_adapters_sdk.py +++ b/tests/test_adapters_sdk.py @@ -12,10 +12,13 @@ import asyncio import contextlib +import contextvars import copy +import gc import json import threading import warnings +import weakref from collections.abc import AsyncIterator, Iterator from types import SimpleNamespace from typing import Any @@ -561,7 +564,10 @@ def in_thread() -> None: @llm_retry(max_attempts=2, delay=1, jitter=0, owns_retries=True) def owner() -> None: - thread = threading.Thread(target=in_thread) + # Model Python versions/configurations where a new thread inherits the + # parent's ContextVars. The copied scope belongs to the parent thread only. + context = contextvars.copy_context() + thread = threading.Thread(target=lambda: context.run(in_thread)) thread.start() thread.join() raise Overloaded @@ -571,6 +577,22 @@ def owner() -> None: assert len(seen) == 2 * 3 # a new thread does not inherit the owner scope +def test_copied_owner_context_does_not_retain_finished_task() -> None: + captured: dict[str, Any] = {} + + @llm_retry(max_attempts=1, owns_retries=True) + async def owner() -> None: + task = asyncio.current_task() + assert task is not None + captured["task"] = weakref.ref(task) + captured["context"] = contextvars.copy_context() + + asyncio.run(owner()) + gc.collect() + + assert captured["task"]() is None + + def test_llm_retry_settings_and_stats_survive_the_owner_wrapper() -> None: @llm_retry(max_attempts=2, owns_retries=True, client=FakeClient(max_retries=3)) def call() -> str: diff --git a/tests/test_batching.py b/tests/test_batching.py index 6d6910c..df5d4a5 100644 --- a/tests/test_batching.py +++ b/tests/test_batching.py @@ -429,12 +429,18 @@ def load(ids: list[int]) -> list[int]: def test_sync_duplicates_share_a_result(): calls = [] - @batch_calls(max_size=2, max_wait=10, key=str.lower) + @batch_calls(max_size=3, max_wait=1, key=str.lower) def load(names: list[str]) -> dict[str, int]: calls.append(list(names)) return {n.lower(): len(calls) for n in names} - results, _ = run_threads(3, lambda i: load(["A", "a", "b"][i])) + callers = threading.Barrier(3) + + def call(i: int) -> int: + callers.wait() + return load(["A", "a", "b"][i]) + + results, _ = run_threads(3, call) assert results == [1, 1, 1] assert len(calls) == 1 assert sorted(n.lower() for n in calls[0]) == ["a", "b"] diff --git a/tests/test_caching_copy.py b/tests/test_caching_copy.py index 5c17862..f090014 100644 --- a/tests/test_caching_copy.py +++ b/tests/test_caching_copy.py @@ -9,7 +9,7 @@ import pytest from conftest import FakeClock -from python_wrap import memoize, singleflight +from python_wrap import memoize from python_wrap.testing import disable_caching from test_caching_extras import DictStore @@ -102,8 +102,7 @@ def test_sync_singleflight_waiters_are_isolated() -> None: release = threading.Event() calls = 0 - @memoize(copy_result=True) - @singleflight + @memoize(copy_result=True, singleflight=True) def load() -> list[int]: nonlocal calls calls += 1 @@ -114,7 +113,13 @@ def load() -> list[int]: # Holding the leader lets all subsequent calls overlap; joining a completed # cache hit is also valid, since both paths must deliver independent copies. results: list[list[int]] = [] - threads = [threading.Thread(target=lambda: results.append(load())) for _ in range(4)] + callers = threading.Barrier(4) + + def call() -> None: + callers.wait() + results.append(load()) + + threads = [threading.Thread(target=call) for _ in range(4)] for thread in threads: thread.start() assert entered.wait(2) diff --git a/tests/test_observability.py b/tests/test_observability.py index 5024189..0c4b913 100644 --- a/tests/test_observability.py +++ b/tests/test_observability.py @@ -155,7 +155,7 @@ def flaky(): spans = exporter.get_finished_spans() attempts = [s for s in spans if s.name == "python_wrap.retry.attempt"] assert [s.attributes["python_wrap.retry.attempt"] for s in attempts] == [1, 2, 3] - assert all(s.end_time > s.start_time for s in spans) # no zero-length span + assert all(s.end_time > s.start_time for s in attempts) # no zero-length attempt span request = next(s for s in spans if s.name == "request") assert any(e.name == "pw.retry.gave_up" for e in request.events) assert sum(p.value for p in _points(reader, "python_wrap.retry.gave_up")) == 1