From 496bc66602ca4fdb2664f522abfdc22df62be4e7 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Thu, 26 Nov 2026 20:54:23 +0200 Subject: [PATCH 01/38] fix: keep results after bookkeeping errors, keep key errors out of store outages - Circuit breaker and shared bulkhead release log store errors after a call finished and return its result instead of raising. - Redis cache stores build keys and run the codec outside the backend monitor: unencodable keys raise TypeError, undecodable entries are misses (cache.rejected reason "decode"), dumps errors propagate. - Key encoder accepts subclasses of the plain types, named tuples (class tagged), and a __cache_key__() hook; -0.0 and 0.0 share a key. Adds python_wrap._runtime.cache_key_of. - Half-open rejections carry a positive retry_after (local and shared). - Hinted waits get up to 10% jitter and a 50 ms floor for a zero hint. - Prefork: watches restart in forked children, SQL lock backends rebind after fork, plain locks on shared-state paths become fork-safe. - Live Redis tests for each Lua script and the backend recovery events; a requests adapter test module; a release-metadata check script and tests. --- scripts/check_release.py | 120 ++++++++++ src/python_wrap/__init__.py | 2 +- src/python_wrap/_runtime.py | 36 ++- src/python_wrap/adapters/_frameworks.py | 7 +- src/python_wrap/adapters/_sdk.py | 5 +- src/python_wrap/async_cache.py | 30 ++- src/python_wrap/caching.py | 2 +- src/python_wrap/celery.py | 6 +- src/python_wrap/circuit.py | 20 +- src/python_wrap/coordination.py | 15 +- src/python_wrap/http.py | 13 +- src/python_wrap/llm_shared.py | 7 +- src/python_wrap/mcp_guard.py | 5 +- src/python_wrap/policies.py | 86 ++++++- src/python_wrap/quotas.py | 5 +- src/python_wrap/retry.py | 16 +- src/python_wrap/shared.py | 24 +- src/python_wrap/stores.py | 40 ++-- tests/conftest.py | 130 +++++++++++ tests/test_backend_recovered.py | 70 ++++++ tests/test_concurrency.py | 14 +- tests/test_fork_safety.py | 244 +++++++++++++++++++- tests/test_http.py | 5 +- tests/test_http_requests.py | 139 +++++++++++ tests/test_redis_backends.py | 24 ++ tests/test_redis_scripts_live.py | 291 ++++++++++++++++++++++++ tests/test_release_041.py | 270 ++++++++++++++++++++++ tests/test_release_metadata.py | 46 ++++ tests/test_retry.py | 3 +- tests/test_stability.py | 32 +++ 30 files changed, 1627 insertions(+), 80 deletions(-) create mode 100644 scripts/check_release.py create mode 100644 tests/test_backend_recovered.py create mode 100644 tests/test_http_requests.py create mode 100644 tests/test_redis_scripts_live.py create mode 100644 tests/test_release_041.py create mode 100644 tests/test_release_metadata.py diff --git a/scripts/check_release.py b/scripts/check_release.py new file mode 100644 index 0000000..36ad0e9 --- /dev/null +++ b/scripts/check_release.py @@ -0,0 +1,120 @@ +"""Release metadata checks: changelog shape, version and classifier, stability status. + +Usage: python scripts/check_release.py [--tag] + +--tag also fails when the *Unreleased* changelog section still has entries. +Run it with --tag at tag time. + +Stability rule: while stability.md lists a provisional module with a target +version, the classifier must be ``4 - Beta``. Once no provisional rows remain it +must be ``5 - Production/Stable``. +""" + +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +import tomllib + +ROOT = Path(__file__).resolve().parents[1] +CHANGELOG = ROOT / "CHANGELOG.md" +STABILITY = ROOT / "docs" / "project" / "stability.md" +PYPROJECT = ROOT / "pyproject.toml" +INIT = ROOT / "src" / "python_wrap" / "__init__.py" + +BETA = "Development Status :: 4 - Beta" +STABLE = "Development Status :: 5 - Production/Stable" +PROVISIONAL_ROW = re.compile(r"^\| `[^|]*\|\s*\d+\.\d+\.\d+\s*\|") + + +def changelog_sections(text: str) -> dict[str, list[str]]: + sections: dict[str, list[str]] = {} + current: list[str] | None = None + for line in text.splitlines(): + if line.startswith("## ["): + name = line[4 : line.index("]")] + current = sections.setdefault(name, []) + elif current is not None: + current.append(line) + return sections + + +def duplicate_entries(text: str) -> list[str]: + """Repeated ``###`` headings or bullet entries inside one version section.""" + problems = [] + for version, body in changelog_sections(text).items(): + headings = [line for line in body if line.startswith("### ")] + entries: list[str] = [] + for line in body: + if line.startswith("- "): + entries.append(line[2:].strip()) + elif entries and line.startswith(" ") and line.strip(): + entries[-1] += " " + line.strip() + for kind, items in (("heading", headings), ("entry", entries)): + seen: set[str] = set() + for item in items: + if item in seen: + problems.append(f"[{version}] duplicate {kind}: {item[:70]}") + seen.add(item) + return problems + + +def unreleased_entries(text: str) -> list[str]: + body = changelog_sections(text).get("Unreleased", []) + return ( + ["[Unreleased] still has entries; move them under the release version"] + if any(line.strip() for line in body) + else [] + ) + + +def package_version() -> str: + match = re.search(r'__version__\s*=\s*"([^"]+)"', INIT.read_text(encoding="utf-8")) + if not match: + raise SystemExit("no __version__ in src/python_wrap/__init__.py") + return match.group(1) + + +def version_and_classifier_problems() -> list[str]: + project = tomllib.loads(PYPROJECT.read_text(encoding="utf-8"))["project"] + problems = [] + if "version" not in project.get("dynamic", []) and project.get("version") != package_version(): + problems.append("pyproject version differs from __version__") + classifiers = [c for c in project.get("classifiers", []) if c.startswith("Development Status")] + if len(classifiers) != 1: + problems.append(f"expected one Development Status classifier, found {len(classifiers)}") + provisional = sum( + bool(PROVISIONAL_ROW.match(line)) + for line in STABILITY.read_text(encoding="utf-8").splitlines() + ) + if provisional and classifiers and classifiers[0] != BETA: + problems.append( + f"stability.md lists {provisional} provisional rows, classifier is not Beta" + ) + if not provisional and classifiers and classifiers[0] != STABLE: + problems.append("stability.md lists no provisional rows, classifier is not Stable") + return problems + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument( + "--tag", action="store_true", help="also require an empty Unreleased section" + ) + args = parser.parse_args() + text = CHANGELOG.read_text(encoding="utf-8") + problems = duplicate_entries(text) + version_and_classifier_problems() + if args.tag: + problems += unreleased_entries(text) + for problem in problems: + print(f"FAIL: {problem}") + if not problems: + print("release metadata OK") + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/python_wrap/__init__.py b/src/python_wrap/__init__.py index dcdc979..afbce89 100644 --- a/src/python_wrap/__init__.py +++ b/src/python_wrap/__init__.py @@ -281,7 +281,7 @@ validate_args, ) -__version__ = "0.4.0" +__version__ = "0.4.1" # A library must never configure logging; this only silences "no handler" warnings. logging.getLogger("python_wrap").addHandler(logging.NullHandler()) diff --git a/src/python_wrap/_runtime.py b/src/python_wrap/_runtime.py index 5d70ab5..2b20e67 100644 --- a/src/python_wrap/_runtime.py +++ b/src/python_wrap/_runtime.py @@ -51,7 +51,8 @@ def _enc(value: Any, out: list[bytes]) -> None: elif kind is int: out.append(b"i%d;" % value) elif kind is float: - out.append(b"f" + value.hex().encode() + b";") + # -0.0 == 0.0 as arguments, so they must share one key. + out.append(b"f" + (0.0 if value == 0 else value).hex().encode() + b";") elif kind is str: raw = value.encode("utf-8", "surrogatepass") out.append(b"s%d:" % len(raw) + raw) @@ -86,6 +87,30 @@ def _enc(value: Any, out: list[bytes]) -> None: elif dataclasses.is_dataclass(value) and not isinstance(value, type): out.append(f"C{kind.__module__}.{kind.__qualname__}:".encode()) _enc({f.name: getattr(value, f.name) for f in dataclasses.fields(value)}, out) + # Subclasses of the plain types encode like their base. The class tag on a named + # tuple keeps it from colliding with a plain tuple of the same items. + elif callable(getattr(value, "__cache_key__", None)): + out.append(f"K{kind.__module__}.{kind.__qualname__}:".encode()) + _enc(value.__cache_key__(), out) + elif isinstance(value, tuple) and hasattr(kind, "_fields"): + out.append(f"C{kind.__module__}.{kind.__qualname__}:".encode()) + _enc({name: getattr(value, name) for name in kind._fields}, out) + elif isinstance(value, int): + out.append(b"i%d;" % int(value)) + elif isinstance(value, float): + _enc(float(value), out) + elif isinstance(value, str): + _enc(str(value), out) + elif isinstance(value, (bytes, bytearray)): + _enc(bytes(value), out) + elif isinstance(value, tuple): + _enc(tuple(value), out) + elif isinstance(value, list): + _enc(list(value), out) + elif isinstance(value, dict): + _enc(dict(value), out) + elif isinstance(value, (set, frozenset)): + _enc(frozenset(value), out) else: raise TypeError( f"a value of type {kind.__qualname__!r} has no stable cache key across " @@ -104,6 +129,15 @@ def stable_digest(value: Any) -> str: return hashlib.sha256(b"".join(out)).hexdigest() +def cache_key_of(value: Any) -> str: + """The stable digest a cache or idempotency key uses for ``value``. + + Lets applications check that their argument types have a stable key before they + rely on it. Raises `TypeError` for values with no stable form. + """ + return stable_digest(value) + + def call_key( func: Callable[..., Any], key: str | Callable[..., Any] | None, diff --git a/src/python_wrap/adapters/_frameworks.py b/src/python_wrap/adapters/_frameworks.py index f4ea78d..3c8df5e 100644 --- a/src/python_wrap/adapters/_frameworks.py +++ b/src/python_wrap/adapters/_frameworks.py @@ -2,12 +2,11 @@ from __future__ import annotations -import threading import time from collections.abc import Mapping from typing import Any -from python_wrap import _core +from python_wrap import _core, _fork from python_wrap.agents import ( EffectConflict, EffectUnknown, @@ -98,7 +97,7 @@ def __init__(self, budget: Any, model: str | None = None) -> None: self.budget = budget self.model = model self._last = (0, 0) - self._lock = threading.Lock() + self._lock = _fork.ForkSafeLock() def add(self, tokens_in: int, tokens_out: int, model: str | None = None) -> Any: """Add a known amount (one model response).""" @@ -211,7 +210,7 @@ def __init__(self, max_tool_calls: int | None, max_repeats: int | None) -> None: raise ValueError(f"{label} must be a positive integer or None") self.max_tool_calls = max_tool_calls self.max_repeats = max_repeats - self._lock = threading.Lock() + self._lock = _fork.ForkSafeLock() self.calls = 0 self._seen: dict[tuple[str, str | None], int] = {} diff --git a/src/python_wrap/adapters/_sdk.py b/src/python_wrap/adapters/_sdk.py index 9c2d186..fdbf725 100644 --- a/src/python_wrap/adapters/_sdk.py +++ b/src/python_wrap/adapters/_sdk.py @@ -25,7 +25,6 @@ import json import math import re -import threading import warnings from collections.abc import ( AsyncGenerator, @@ -40,7 +39,7 @@ ) from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast -from python_wrap import _core +from python_wrap import _core, _fork from python_wrap.errors import PythonWrapError from python_wrap.llm import ( Budget, @@ -1265,7 +1264,7 @@ def __init__( raise ValueError(f"min_prompt_tokens must be >= 0, got {min_prompt_tokens!r}") self.min_calls, self.min_hit_rate = min_calls, min_hit_rate self.min_prompt_tokens, self.name, self.warn = min_prompt_tokens, name, warn - self._lock = threading.Lock() + self._lock = _fork.ForkSafeLock() self.reset() def reset(self) -> None: diff --git a/src/python_wrap/async_cache.py b/src/python_wrap/async_cache.py index 673b7fa..520af7d 100644 --- a/src/python_wrap/async_cache.py +++ b/src/python_wrap/async_cache.py @@ -235,35 +235,43 @@ async def _run(self, action: Callable[[], Awaitable[Any]], default: Any = None) async def get(self, key: Hashable, /) -> Any | None: """Return a decoded entry, or None on a miss.""" + # Key building and codec work stay outside the backend monitor (see RedisStore.get). + name = self._key(key) + async def read() -> Any: - value = await self.client.get(self._key(key)) - if value is None: - return None - try: - return self.loads(value) - except InvalidSignature: - _core.emit("cache.rejected", self.prefix, reason="signature") - return None + return await self.client.get(name) - return await self._run(read) + value = await self._run(read) + if value is None: + return None + try: + return self.loads(value) + except InvalidSignature: + _core.emit("cache.rejected", self.prefix, reason="signature") + except Exception: + _core.emit("cache.rejected", self.prefix, reason="decode") + return None async def set(self, key: Hashable, entry: Any, ttl: float | None, /) -> None: """Store an entry with millisecond TTL precision.""" if ttl is not None and ttl <= 0: await self.delete(key) return + name = self._key(key) + payload = self.dumps(entry) options = {} if ttl is None else {"px": max(1, math.ceil(ttl * 1000))} async def write() -> None: - await self.client.set(self._key(key), self.dumps(entry), **options) + await self.client.set(name, payload, **options) await self._run(write) async def delete(self, key: Hashable, /) -> bool: """Delete one entry; report whether it existed.""" + name = self._key(key) async def remove() -> Any: - return await self.client.delete(self._key(key)) + return await self.client.delete(name) return bool(await self._run(remove, False)) diff --git a/src/python_wrap/caching.py b/src/python_wrap/caching.py index 992afda..dd31567 100644 --- a/src/python_wrap/caching.py +++ b/src/python_wrap/caching.py @@ -541,7 +541,7 @@ def put(self, k: Hashable, entry: tuple[Any, float | None, bool, float | None]) _async_tag_clients: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary() _tag_store_owners: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary() _async_tag_store_owners: weakref.WeakValueDictionary[int, Any] = weakref.WeakValueDictionary() -_tag_registry_lock = threading.RLock() +_tag_registry_lock = _fork.ForkSafeRLock() def _register_tag_client( diff --git a/src/python_wrap/celery.py b/src/python_wrap/celery.py index 0b95acb..cf1d278 100644 --- a/src/python_wrap/celery.py +++ b/src/python_wrap/celery.py @@ -1,5 +1,7 @@ """Celery integration: task context, Celery-aware retry countdowns and shared breakers. +Provisional: may change in a minor release; target 0.5.0. + Imported only when used; Celery itself is never imported at module level. Two layers of retry exist in a Celery app: python-wrap's in-process `retry` (fast, a @@ -247,7 +249,7 @@ def retry_countdown( assert retry_countdown(task, CircuitOpenError("open", retry_after=42)) == 42 ``` """ - from python_wrap.retry import _compute_delay, _validate, retry_after_header + from python_wrap.retry import _compute_delay, _hinted, _validate, retry_after_header _validate(1, delay, backoff, max_delay, jitter) if delays is not None and not delays: @@ -255,7 +257,7 @@ def retry_countdown( if respect_retry_after and exc is not None: hinted = retry_after_header(exc) if hinted is not None: - return min(hinted, max_delay) + return _hinted(hinted, max_delay) retries = int(getattr(getattr(task, "request", None), "retries", 0) or 0) if delays is not None: base = float(delays[min(retries, len(delays) - 1)]) diff --git a/src/python_wrap/circuit.py b/src/python_wrap/circuit.py index 4426d5d..1daa364 100644 --- a/src/python_wrap/circuit.py +++ b/src/python_wrap/circuit.py @@ -586,9 +586,10 @@ def _admit(self, data: dict[str, Any] | None) -> tuple[int, bool]: ) elif self._state is CircuitState.HALF_OPEN: if self._trials >= self.half_open_max_calls: + # A zero hint would make rejected callers retry at once. error = CircuitOpenError( f"circuit {self.name} is half-open and its trial calls are in use", - retry_after=0.0, + retry_after=min(max(self.recovery_timeout, 0.05), 1.0), ) else: self._trials += 1 @@ -742,7 +743,11 @@ def _call_sync(self, func: Callable[..., Any], args: Any, kwargs: Any) -> Any: except Exception: self._log.exception("circuit outcome bookkeeping failed; preserving original error") raise - self._success(generation, trial, self._slow(started)) + # The call already happened: a bookkeeping failure must never replace its result. + try: + self._success(generation, trial, self._slow(started)) + except Exception: + self._log.exception("circuit outcome bookkeeping failed; returning the result") return result async def _acall(self, func: Callable[..., Any], args: Any, kwargs: Any) -> Any: @@ -792,9 +797,16 @@ async def _acall(self, func: Callable[..., Any], args: Any, kwargs: Any) -> Any: if cancelled: raise asyncio.CancelledError if error is not None: - raise error + # The call already happened: log, never replace its result. + self._log.error( + "circuit outcome bookkeeping failed; returning the result", + exc_info=(type(error), error, error.__traceback__), + ) else: - self._success(generation, trial, slow) + try: + self._success(generation, trial, slow) + except Exception: + self._log.exception("circuit outcome bookkeeping failed; returning the result") return result def __call__(self, func: F) -> F: diff --git a/src/python_wrap/coordination.py b/src/python_wrap/coordination.py index 76af06c..e0bfbd3 100644 --- a/src/python_wrap/coordination.py +++ b/src/python_wrap/coordination.py @@ -181,8 +181,19 @@ def __init__(self, engine: Any) -> None: self._pid = os.getpid() def _process(self) -> None: - if os.getpid() != self._pid: + if os.getpid() == self._pid: + return + dispose = getattr(self.engine, "dispose", None) + if dispose is None: raise RuntimeError("create SQL lock engines and backends after fork") + with self._lock: + if os.getpid() == self._pid: + return + # Connections opened before the fork belong to the parent: forget them + # without closing, and discard pooled sockets the child must not reuse. + self._connections = {} + dispose(close=False) + self._pid = os.getpid() def _resource(self, key: str) -> Any: if self.dialect == "postgresql": @@ -379,7 +390,7 @@ def __init__( self._stop = threading.Event() self._thread: threading.Thread | None = None self._task: asyncio.Task[None] | None = None - self._lifecycle = threading.Lock() + self._lifecycle = _fork.ForkSafeLock() self._entering = self._active = self._finished = False self._pid = os.getpid() diff --git a/src/python_wrap/http.py b/src/python_wrap/http.py index 482de7d..d634ed9 100644 --- a/src/python_wrap/http.py +++ b/src/python_wrap/http.py @@ -1,5 +1,7 @@ """HTTP client integration: retry policy, httpx transports, requests adapter, generic decorator. +Provisional: may change in a minor release; target 0.5.0. + Everything here is duck-typed or imports its third-party library lazily, so ``python_wrap`` keeps zero runtime dependencies. The decision logic lives in two pure helpers, `should_retry` and `retry_delay`, which every integration shares. @@ -15,12 +17,11 @@ import contextlib import importlib import logging -import threading from collections.abc import Awaitable, Callable, Iterable, Mapping from dataclasses import dataclass, field from typing import Any -from python_wrap import _core +from python_wrap import _core, _fork from python_wrap.deadline import remaining as _deadline_remaining from python_wrap.retry import RetryBudget, _compute_delay, http_status, retry, retry_after_header @@ -241,7 +242,11 @@ def retry_delay( if policy.respect_retry_after: hinted = retry_after_header(response_or_exc) if hinted is not None: - return None if hinted > policy.max_retry_after else hinted + if hinted > policy.max_retry_after: + return None + from python_wrap.retry import _hinted + + return _hinted(hinted, policy.max_retry_after) return _compute_delay( max(attempt, 1), policy.delay, policy.backoff, policy.max_delay, policy.jitter ) @@ -350,7 +355,7 @@ class HttpPolicy: default_factory=dict, init=False, repr=False, compare=False ) _blocked: dict[str, float] = field(default_factory=dict, init=False, repr=False, compare=False) - _lock: Any = field(default_factory=threading.Lock, init=False, repr=False, compare=False) + _lock: Any = field(default_factory=_fork.ForkSafeLock, init=False, repr=False, compare=False) def __post_init__(self) -> None: for name in ("connect_timeout", "read_timeout"): diff --git a/src/python_wrap/llm_shared.py b/src/python_wrap/llm_shared.py index d2b9033..77af7fe 100644 --- a/src/python_wrap/llm_shared.py +++ b/src/python_wrap/llm_shared.py @@ -29,13 +29,12 @@ import os import re import sqlite3 -import threading from collections.abc import Iterable, Iterator from datetime import datetime, timezone from email.utils import parsedate_to_datetime from typing import Any -from python_wrap import _core +from python_wrap import _core, _fork __all__ = [ "AsyncRedisTokenWindow", @@ -321,7 +320,7 @@ def __init__(self, name: str = "tokens", *, fail_open: bool = True) -> None: self.name = name self.fail_open = fail_open self._fallback: _State | None = None - self._flock = threading.Lock() + self._flock = _fork.ForkSafeLock() # -- storage hook ------------------------------------------------------------ def _transact(self, op: str, a: float, b: float, capacity: float, rate: float) -> float: @@ -417,7 +416,7 @@ def __init__(self, path: str | os.PathLike[str], timeout: float, schema: str) -> self.timeout = timeout self._schema = schema self._prepared = False - self._plock = threading.Lock() + self._plock = _fork.ForkSafeLock() @contextlib.contextmanager def connection(self) -> Iterator[sqlite3.Connection]: diff --git a/src/python_wrap/mcp_guard.py b/src/python_wrap/mcp_guard.py index 9aa08c0..ffba265 100644 --- a/src/python_wrap/mcp_guard.py +++ b/src/python_wrap/mcp_guard.py @@ -25,11 +25,10 @@ import asyncio import fnmatch import functools -import threading from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence from typing import Any, cast -from python_wrap import _core +from python_wrap import _core, _fork from python_wrap._runtime import seconds as _parse_seconds from python_wrap.circuit import CircuitBreaker from python_wrap.timeouts import _current_token, checkpoint @@ -38,7 +37,7 @@ _LAYER_ATTR = "__python_wrap_layer__" _BREAKERS: dict[str, CircuitBreaker] = {} -_BREAKERS_LOCK = threading.Lock() +_BREAKERS_LOCK = _fork.ForkSafeLock() _DEFAULT_RETRY_ON: tuple[type[BaseException], ...] = (ConnectionError, TimeoutError, OSError) diff --git a/src/python_wrap/policies.py b/src/python_wrap/policies.py index 52c9492..dfd17ef 100644 --- a/src/python_wrap/policies.py +++ b/src/python_wrap/policies.py @@ -13,6 +13,7 @@ import json import os import threading +import time from collections.abc import Callable, Mapping from pathlib import Path from typing import Any, Protocol, TypeVar, cast @@ -80,21 +81,61 @@ def read(self) -> Any: class Watch: - """A running `PolicyRegistry.watch`; ``stop()`` ends it. Does not survive a fork.""" + """A running `PolicyRegistry.watch`; ``stop()`` ends it. + + The poll thread is not inherited by a forked child. The child starts its own on + first policy resolution (`ensure_running`); `alive` reports False until then. + """ def __init__(self, registry: PolicyRegistry, source: PolicySource, interval: float): self.registry, self.source, self.interval = registry, source, interval self._stop = threading.Event() self._last: str | None = None + self._last_ok: float | None = None + self._pid = os.getpid() + self._thread: threading.Thread | None = None self.poll() # the first read happens now, so a broken source fails loudly - self._thread = threading.Thread(target=self._run, daemon=True, name="python-wrap-policies") + self._start() + + def _start(self) -> None: + self._thread = threading.Thread( + target=self._run, args=(self._stop,), daemon=True, name="python-wrap-policies" + ) self._thread.start() + @property + def alive(self) -> bool: + """True when this process has a running poll thread for this watch.""" + thread = self._thread + return thread is not None and self._pid == os.getpid() and thread.is_alive() + + @property + def pid(self) -> int: + """The process that owns the current poll thread.""" + return self._pid + + @property + def seconds_since_poll(self) -> float | None: + """Seconds since the last successful read of the source, None before one.""" + if self._last_ok is None: + return None + return time.monotonic() - self._last_ok + + def ensure_running(self) -> None: + """Start a fresh poll thread when called from a process that did not create it.""" + if os.getpid() == self._pid or self._stop.is_set(): + return + self._stop = threading.Event() + self._last = None + self._pid = os.getpid() + self._start() + def poll(self) -> bool: """Read the source once; apply it if it changed. True when a change was applied.""" try: mapping = self.source.read() text = json.dumps(mapping, sort_keys=True, default=repr) + self._last_ok = time.monotonic() if text == self._last: return False self.registry.load_from_mapping(mapping) @@ -105,13 +146,15 @@ def poll(self) -> bool: self._last = text return True - def _run(self) -> None: - while not self._stop.wait(self.interval): + def _run(self, stop: threading.Event) -> None: + while not stop.wait(self.interval): self.poll() def stop(self) -> None: self._stop.set() - self._thread.join(timeout=self.interval + 1) + thread = self._thread + if thread is not None and self._pid == os.getpid(): + thread.join(timeout=self.interval + 1) class PolicyRegistry: @@ -128,6 +171,8 @@ def __init__(self) -> None: self._settings: dict[str, dict[str, Any]] = {} self._versions: dict[str, int] = {} self._compiled: dict[str, Policy] = {} + self._watches: list[Watch] = [] + self._watch_pid = os.getpid() self._exceptions: dict[str, type[BaseException]] = { f"builtins.{name}": value for name, value in vars(builtins).items() @@ -186,6 +231,12 @@ def _resolve(self, key: str | None, value: Any) -> Any: return [self._resolve(None, item) for item in value] return value + def _restart_watches(self) -> None: + """Let each watch restart its poll thread in a forked child (once per child).""" + self._watch_pid = os.getpid() + for watch in list(self._watches): + watch.ensure_running() + def watch(self, source: PolicySource, interval: float = 30) -> Watch: """Poll ``source`` every ``interval`` seconds and apply each changed mapping. @@ -197,7 +248,9 @@ def watch(self, source: PolicySource, interval: float = 30) -> Watch: """ if interval <= 0: raise ValueError("interval must be positive") - return Watch(self, source, interval) + watch = Watch(self, source, interval) + self._watches.append(watch) + return watch def register(self, name: str, **settings: Any) -> None: """Atomically replace one named policy after validating its full configuration.""" @@ -337,6 +390,8 @@ def decorate(func: F) -> F: def resolve() -> Any: nonlocal version, compiled + if self._watch_pid != os.getpid(): + self._restart_watches() with self._lock: if name not in self._settings: raise KeyError(f"policy {name!r} is not registered") @@ -385,12 +440,23 @@ def _carry_state(old: Policy, new: Policy) -> None: _health_registered = False +def _health_report() -> dict[str, Any]: + watches = [ + { + "alive": watch.alive, + "pid": watch.pid, + "interval": watch.interval, + "seconds_since_poll": watch.seconds_since_poll, + } + for watch in list(policies._watches) + ] + return {"healthy": True, "generations": dict(policies._versions), "watches": watches} + + def _register_health() -> None: - """Report each named policy's generation in `python_wrap.health.health.report()`.""" + """Report policy generations and watches in `python_wrap.health.health.report()`.""" global _health_registered from python_wrap.health import health _health_registered = True - health.register_check( - "policies", lambda: {"healthy": True, "generations": dict(policies._versions)} - ) + health.register_check("policies", _health_report) diff --git a/src/python_wrap/quotas.py b/src/python_wrap/quotas.py index ee6db56..3389ed2 100644 --- a/src/python_wrap/quotas.py +++ b/src/python_wrap/quotas.py @@ -1,4 +1,7 @@ -"""Atomic Redis rate windows and explicit run budgets.""" +"""Atomic Redis rate windows and explicit run budgets. + +Provisional: may change in a minor release; target 0.5.0. +""" from __future__ import annotations diff --git a/src/python_wrap/retry.py b/src/python_wrap/retry.py index 205f747..1cb11d9 100644 --- a/src/python_wrap/retry.py +++ b/src/python_wrap/retry.py @@ -575,6 +575,20 @@ def matches(result: Any) -> bool: HINT_CEILING = 600.0 +#: Floor for a hint of exactly zero (a half-open breaker or ``Retry-After: 0``), so a +#: rejected caller never retries in a tight loop. +HINT_FLOOR = 0.05 +#: Proportional jitter added on top of a hinted wait. The hint stays a lower bound, so +#: callers rejected together spread out instead of returning in the same instant. +HINT_JITTER = 0.1 + + +def _hinted(hint: float, ceiling: float) -> float: + """Apply the hint floor and jitter to a server or breaker hint, capped at ``ceiling``.""" + base = hint if hint > 0 else HINT_FLOOR + return min(base * (1 + random.uniform(0, HINT_JITTER)), ceiling) + + def _parse_hint(value: Any) -> float | None: if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): return None @@ -730,7 +744,7 @@ def _wait_for(self, attempt: int, exc: BaseException | None, result: Any = None) ) hint = None if hint is not None: - return min(hint, HINT_CEILING if self.max_delay is None else self.max_delay) + return _hinted(hint, HINT_CEILING if self.max_delay is None else self.max_delay) if self.delays is not None: delay = self.delays[min(attempt - 1, len(self.delays) - 1)] return _compute_delay(1, delay, 1.0, self.max_delay, self.jitter) diff --git a/src/python_wrap/shared.py b/src/python_wrap/shared.py index 686dc49..b68685a 100644 --- a/src/python_wrap/shared.py +++ b/src/python_wrap/shared.py @@ -1,4 +1,7 @@ -"""Redis coordination backends for circuit breakers and bulkheads.""" +"""Redis coordination backends for circuit breakers and bulkheads. + +Provisional: may change in a minor release; target 0.5.0. +""" from __future__ import annotations @@ -78,7 +81,10 @@ redis.call('HSET',KEYS[1],'trial_deadline',now+math.max(1000,reset)) end end if state=='open' or (state=='half_open' and trials>=halfmax) then - admitted=0; wait=math.max(0,opened+reset-now) + admitted=0 + if state=='half_open' then + wait=math.max(50,tonumber(redis.call('HGET',KEYS[1],'trial_deadline') or '0')-now) + else wait=math.max(0,opened+reset-now) end redis.call('HINCRBY',KEYS[1],'total_rejected',1) elseif state=='half_open' then trial=1; trials=trials+1 end elseif (op=='success' or op=='failure' or op=='neutral') and tonumber(ARGV[7])==gen then @@ -543,7 +549,12 @@ def release(self, typ: Any = None, exc: Any = None, tb: Any = None) -> None: self._stack.set(stack[:-1]) try: if lease is not None: - lease.__exit__(typ, exc, tb) + try: + lease.__exit__(typ, exc, tb) + except Exception as error: + # The protected call already finished; a failed release must not replace + # its result or error. The slot expires by its TTL. + self._monitor.failed(error, "release") finally: with self._lock: self._active -= 1 @@ -580,7 +591,12 @@ async def release_async(self, typ: Any = None, exc: Any = None, tb: Any = None) self._stack.set(stack[:-1]) try: if lease is not None: - await lease.__aexit__(typ, exc, tb) + try: + await lease.__aexit__(typ, exc, tb) + except Exception as error: + # The protected call already finished; a failed release must not replace + # its result or error. The slot expires by its TTL. + self._monitor.failed(error, "release") finally: with self._lock: self._active -= 1 diff --git a/src/python_wrap/stores.py b/src/python_wrap/stores.py index 72168bd..77f0521 100644 --- a/src/python_wrap/stores.py +++ b/src/python_wrap/stores.py @@ -1,4 +1,7 @@ -"""Optional Redis cache adapter. The caller supplies a client; redis is not imported.""" +"""Optional Redis cache adapter. The caller supplies a client; redis is not imported. + +Provisional: may change in a minor release; target 0.5.0. +""" from __future__ import annotations @@ -116,31 +119,36 @@ def _run(self, action: Callable[[], Any], default: Any = None) -> Any: def get(self, key: Hashable, /) -> Any: """Return a decoded entry, or None on a miss.""" - def read() -> Any: - value = self.client.get(self._key(key)) - if value is None: - return None - try: - return self.loads(value) - except InvalidSignature: - from python_wrap import _core - - _core.emit("cache.rejected", self.prefix, reason="signature") - return None - - return self._run(read) + # Key building and codec work stay outside the backend monitor: a bad key or + # a value that cannot be encoded is a caller error, not a store outage. + name = self._key(key) + value = self._run(lambda: self.client.get(name)) + if value is None: + return None + from python_wrap import _core + + try: + return self.loads(value) + except InvalidSignature: + _core.emit("cache.rejected", self.prefix, reason="signature") + except Exception: + _core.emit("cache.rejected", self.prefix, reason="decode") + return None def set(self, key: Hashable, entry: Any, ttl: float | None, /) -> None: """Store an entry with millisecond TTL precision.""" if ttl is not None and ttl <= 0: self.delete(key) return + name = self._key(key) + payload = self.dumps(entry) options = {} if ttl is None else {"px": max(1, math.ceil(ttl * 1000))} - self._run(lambda: self.client.set(self._key(key), self.dumps(entry), **options)) + self._run(lambda: self.client.set(name, payload, **options)) def delete(self, key: Hashable, /) -> bool: """Delete one entry; report whether it existed.""" - return bool(self._run(lambda: self.client.delete(self._key(key)), False)) + name = self._key(key) + return bool(self._run(lambda: self.client.delete(name), False)) def clear(self) -> None: """Delete this namespace, in batches, using UNLINK where supported.""" diff --git a/tests/conftest.py b/tests/conftest.py index 8a09f5f..1534f62 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -19,3 +19,133 @@ def fake_clock() -> Iterator[FakeClock]: with _fake_clock() as clock: yield clock + + +class _RespClient: + """Minimal RESP client over a Unix socket; enough for the scripts' ``eval``/``get``.""" + + def __init__(self, path: str) -> None: + self.path = path + + def execute(self, *args: object) -> object: + import socket + + values = [v if isinstance(v, bytes) else str(v).encode() for v in args] + payload = b"*" + str(len(values)).encode() + b"\r\n" + for value in values: + payload += b"$" + str(len(value)).encode() + b"\r\n" + value + b"\r\n" + with socket.socket(socket.AF_UNIX) as conn: + conn.settimeout(3) + conn.connect(self.path) + conn.sendall(payload) + stream = conn.makefile("rb") + + def read() -> object: + line = stream.readline() + if not line: + raise RuntimeError("Redis disconnected") + kind, body = line[:1], line[1:-2] + if kind == b"-": + raise RuntimeError(body.decode()) + if kind == b":": + return int(body) + if kind == b"+": + return body + size = int(body) + if size < 0: + return None + if kind == b"*": + return [read() for _ in range(size)] + value = stream.read(size) + stream.read(2) + return value + + return read() + + def get(self, key: str) -> object: + return self.execute("GET", key) + + def delete(self, *keys: str) -> object: + return self.execute("DEL", *keys) + + def eval(self, script: str, count: int, *args: object) -> object: + return self.execute("EVAL", script, count, *args) + + +@pytest.fixture(scope="session") +def redis_server_client() -> Iterator[_RespClient]: + """A real redis-server on a Unix socket; fails (not skips) when PW_REQUIRE_REDIS=1.""" + import os + import shutil + import socket + import subprocess + import tempfile + import time + from pathlib import Path + + executable = shutil.which("redis-server") + if executable is None or not hasattr(socket, "AF_UNIX"): + if os.environ.get("PW_REQUIRE_REDIS") == "1": + pytest.fail("redis-server and Unix sockets required") + pytest.skip("redis-server and Unix sockets required") + with tempfile.TemporaryDirectory(prefix="pw-redis-", dir="/tmp") as root: + path = str(Path(root) / "r.sock") + proc = subprocess.Popen( + [executable, "--port", "0", "--unixsocket", path, "--save", "", "--appendonly", "no"], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + try: + client = _RespClient(path) + for _ in range(100): + if Path(path).exists(): + break + if proc.poll() is not None: + log = proc.stdout.read().decode() + sandboxed = "Operation not permitted" in log + if sandboxed and os.environ.get("PW_REQUIRE_REDIS") != "1": + pytest.skip("sandbox prohibits Redis socket binding") + pytest.fail(log) + time.sleep(0.01) + assert client.execute("PING") == b"PONG" + yield client + finally: + proc.terminate() + proc.wait(timeout=5) + + +class FailingThenRecoveringClient: + """Proxy over a real client. While ``down`` is true every command raises ConnectionError.""" + + def __init__(self, inner: object) -> None: + self._inner = inner + self.down = False + + def __getattr__(self, name: str) -> object: + target = getattr(self._inner, name) + if not callable(target): + return target + + def command(*args: object, **kwargs: object) -> object: + if self.down: + raise ConnectionError("store down") + return target(*args, **kwargs) + + return command + + +@pytest.fixture +def failing_then_recovering_client( + redis_server_client: _RespClient, +) -> Iterator[FailingThenRecoveringClient]: + proxy = FailingThenRecoveringClient(redis_server_client) + yield proxy + proxy.down = False + + +@pytest.fixture(autouse=True) +def _no_hint_jitter(monkeypatch: pytest.MonkeyPatch) -> None: + """Exact hinted waits are asserted here; hint jitter has its own tests.""" + import importlib + + monkeypatch.setattr(importlib.import_module("python_wrap.retry"), "HINT_JITTER", 0.0) diff --git a/tests/test_backend_recovered.py b/tests/test_backend_recovered.py new file mode 100644 index 0000000..b9366c3 --- /dev/null +++ b/tests/test_backend_recovered.py @@ -0,0 +1,70 @@ +"""``backend.recovered`` is emitted once a shared backend answers again after a failure. + +Each kind runs its real script against a real redis-server through the +``failing_then_recovering_client`` proxy (conftest): the store fails, the call raises (or +falls back), the store comes back, and the next call must emit the recovery event. +""" + +from __future__ import annotations + +import uuid + +import pytest + +from python_wrap.circuit import CircuitBreaker +from python_wrap.coordination import RedisLock +from python_wrap.events import listening +from python_wrap.quotas import Quota, RedisWindow +from python_wrap.retry import RetryBudget +from python_wrap.shared import RedisBreakerState, RedisRetryBudget, SharedBulkhead + +KINDS = ["breaker", "window", "quota", "bulkhead", "budget"] + + +def _operation(kind: str, client: object): + tag = uuid.uuid4().hex[:8] + if kind == "breaker": + breaker = CircuitBreaker( + name=f"rec-{tag}", + backend=RedisBreakerState(client, f"rec-{tag}:", state_ttl=0), + failure_threshold=5, + ) + return lambda: breaker.call(lambda: "ok") + if kind == "window": + window = RedisWindow(client, f"rec-{tag}", calls=100, period=60) + return window.acquire + if kind == "quota": + quota = Quota(100, client=client, key=f"rec-{tag}") + return quota.take + if kind == "bulkhead": + bulkhead = SharedBulkhead(2, backend=RedisLock(client, f"rec-{tag}:"), name=f"rec-{tag}") + + def use() -> None: + bulkhead.acquire() + bulkhead.release() + + return use + if kind == "budget": + budget = RetryBudget(backend=RedisRetryBudget(client, f"rec-{tag}")) + return budget.deposit + raise AssertionError(kind) + + +@pytest.mark.parametrize("kind", KINDS) +def test_backend_recovered_event_per_kind(kind, failing_then_recovering_client): + proxy = failing_then_recovering_client + use = _operation(kind, proxy) + events = [] + with listening(events.append): + use() # healthy: no recovery event yet + proxy.down = True + with pytest.raises(ConnectionError): + use() + assert [e.name for e in events if e.name == "backend.error"] == ["backend.error"] + assert not [e for e in events if e.name == "backend.recovered"] + proxy.down = False + use() + use() # the second healthy call does not emit again + recovered = [e for e in events if e.name == "backend.recovered"] + assert len(recovered) == 1 + assert recovered[0].fields["backend"] == kind diff --git a/tests/test_concurrency.py b/tests/test_concurrency.py index 97c9c27..939ecfc 100644 --- a/tests/test_concurrency.py +++ b/tests/test_concurrency.py @@ -1414,32 +1414,38 @@ def t(): assert not limiter.try_acquire() -def test_rate_limit_override_flipped_while_waiting(fake_clock, monkeypatch): +def test_rate_limit_override_flipped_while_waiting(fake_clock): limiter = RateLimiter(1, 100, block=True) limiter.try_acquire() def sleep(seconds): _core.overrides.disable_rate_limits = True - monkeypatch.setattr(_core, "sleep", sleep) + # Restore in this body, not through monkeypatch: fixture teardown order would + # otherwise put the fake clock's sleep back as the "original" for later tests. + real_sleep = _core.sleep + _core.sleep = sleep try: with limiter: pass finally: + _core.sleep = real_sleep _core.overrides.disable_rate_limits = False -async def test_rate_limit_override_flipped_while_waiting_async(fake_clock, monkeypatch): +async def test_rate_limit_override_flipped_while_waiting_async(fake_clock): limiter = RateLimiter(1, 100, block=True) limiter.try_acquire() async def async_sleep(seconds): _core.overrides.disable_rate_limits = True - monkeypatch.setattr(_core, "async_sleep", async_sleep) + real_async_sleep = _core.async_sleep + _core.async_sleep = async_sleep try: assert await limiter.acquire_async() finally: + _core.async_sleep = real_async_sleep _core.overrides.disable_rate_limits = False diff --git a/tests/test_fork_safety.py b/tests/test_fork_safety.py index 7c9e44e..bff85b4 100644 --- a/tests/test_fork_safety.py +++ b/tests/test_fork_safety.py @@ -2,16 +2,22 @@ from __future__ import annotations +import ast +import json import os import subprocess import sys import textwrap +import threading +import time +from pathlib import Path import pytest -pytestmark = pytest.mark.skipif(not hasattr(os, "fork"), reason="POSIX fork only") +posix_only = pytest.mark.skipif(not hasattr(os, "fork"), reason="POSIX fork only") +@posix_only def test_fork_resets_inherited_locks_cache_flights_and_periodic(): script = """ import os, threading, logging @@ -93,3 +99,239 @@ def work(): ref = create() gc.collect() assert ref() is None + + +def _child_exit(ok: bool) -> None: + os._exit(0 if ok else 1) + + +def _wait_exit(pid: int) -> int: + _, status = os.waitpid(pid, 0) + return os.waitstatus_to_exitcode(status) + + +@posix_only +def test_watch_polls_in_forked_child(tmp_path: Path): + from python_wrap.policies import FileSource, PolicyRegistry + + path = tmp_path / "policies.json" + path.write_text(json.dumps({"db": {"retry": {"max_attempts": 1, "delay": 0}}})) + registry = PolicyRegistry() + watch = registry.watch(FileSource(path), interval=0.05) + watch_thread_alive = watch.alive + path.write_text(json.dumps({"db": {"retry": {"max_attempts": 3, "delay": 0}}})) + pid = os.fork() + if pid == 0: + ok = False + try: + # Resolving a policy is what starts the child's own poll thread. + registry.resilient("db")(lambda: None)() + deadline = time.monotonic() + 2 + while time.monotonic() < deadline: + if registry._versions.get("db", 0) >= 2 and watch.alive: + ok = True + break + time.sleep(0.02) + finally: + _child_exit(ok) + try: + assert watch_thread_alive + assert _wait_exit(pid) == 0 + finally: + watch.stop() + + +@posix_only +def test_watch_alive_false_in_child_until_first_use(tmp_path: Path): + from python_wrap.policies import FileSource, PolicyRegistry + + path = tmp_path / "policies.json" + path.write_text(json.dumps({"db": {"retry": {"max_attempts": 1, "delay": 0}}})) + registry = PolicyRegistry() + watch = registry.watch(FileSource(path), interval=0.05) + assert watch.alive + pid = os.fork() + if pid == 0: + ok = False + try: + before = not watch.alive + registry.resilient("db")(lambda: None)() + ok = before and watch.alive and watch.pid == os.getpid() + finally: + _child_exit(ok) + try: + assert _wait_exit(pid) == 0 + assert watch.alive + finally: + watch.stop() + + +class _FakeResult: + def __init__(self, value: object) -> None: + self.value = value + + def scalar(self) -> object: + return self.value + + +class _FakeConnection: + def __init__(self) -> None: + self.closed = False + self.invalidated = False + + def exec_driver_sql(self, sql: str, params: tuple = ()) -> _FakeResult: + if "pg_advisory_unlock" in sql or "pg_try_advisory_lock" in sql: + return _FakeResult(True) + return _FakeResult(1) + + def invalidate(self) -> None: + self.invalidated = True + + def close(self) -> None: + self.closed = True + + +class _FakeEngine: + """Stand-in engine: records dispose calls, hands out fake connections.""" + + def __init__(self) -> None: + self.disposed: list[bool] = [] + + def connect(self) -> _FakeConnection: + return _FakeConnection() + + def dispose(self, close: bool = True) -> None: + self.disposed.append(close) + + +class _NoDisposeEngine(_FakeEngine): + dispose = None # type: ignore[assignment] + + +@posix_only +def test_sql_lock_backend_rebinds_after_fork(): + from python_wrap.coordination import PgAdvisoryLock + + engine = _FakeEngine() + backend = PgAdvisoryLock(engine) + assert backend.acquire("parent-key", "parent-token", 30) + pid = os.fork() + if pid == 0: + ok = False + try: + # The parent's lease is not ours; its connection must not be reused. + stale_release = backend.release("parent-key", "parent-token") is False + acquired = backend.acquire("child-key", "child-token", 30) + released = backend.release("child-key", "child-token") + disposed_without_close = engine.disposed == [False] + no_dispose = PgAdvisoryLock(_NoDisposeEngine()) + no_dispose._pid = -1 # simulate a backend created before a fork + try: + no_dispose.acquire("k", "t", 30) + raises = False + except RuntimeError: + raises = True + ok = stale_release and acquired and released and disposed_without_close and raises + finally: + _child_exit(ok) + try: + assert _wait_exit(pid) == 0 + assert backend.release("parent-key", "parent-token") is True + finally: + backend._connections.clear() + + +@posix_only +def test_http_policy_lock_usable_after_fork_with_lock_held(): + from python_wrap.http import HttpPolicy + + policy = HttpPolicy() + held, finish = threading.Event(), threading.Event() + + def holder() -> None: + with policy._lock: + held.set() + finish.wait(5) + + thread = threading.Thread(target=holder) + thread.start() + try: + assert held.wait(2) + pid = os.fork() + if pid == 0: + ok = False + try: + ok = policy._lock.acquire(False) + if ok: + policy._lock.release() + finally: + _child_exit(ok) + assert _wait_exit(pid) == 0 + finally: + finish.set() + thread.join() + + +# Plain threading locks that remain on purpose. Keyed by (file, assignment target) with +# the maximum number of occurrences allowed and the reason each one is still plain. +PLAIN_LOCK_ALLOW_LIST: dict[tuple[str, str], tuple[int, str]] = { + ("coordination.py", "self._connections[token]"): ( + 1, + "per-lease operation lock, made in acquire and dropped with its slot " + "(_process clears slots after fork)", + ), + ("timeouts.py", "self.done"): (1, "outside the 0.4.1 file scope; convert in a follow-up"), + ("timeouts.py", "self.lock"): (2, "outside the 0.4.1 file scope; convert in a follow-up"), + ("timing.py", "_trace_lock"): (1, "outside the 0.4.1 file scope; convert in a follow-up"), + ("timing.py", "_gate"): (2, "outside the 0.4.1 file scope; convert in a follow-up"), + ("state.py", "self._state_lock"): (1, "outside the 0.4.1 file scope; convert in a follow-up"), + ("agents.py", "self._lock"): (5, "outside the 0.4.1 file scope; convert in a follow-up"), + ("async_cache.py", "stats_lock"): (1, "outside the 0.4.1 file scope; convert in a follow-up"), + ("llm_cassette.py", "self._lock"): (2, "outside the 0.4.1 file scope; convert in a follow-up"), + ("llm_testing.py", "self._lock"): (1, "outside the 0.4.1 file scope; convert in a follow-up"), +} + + +def _plain_lock_sites() -> dict[tuple[str, str], int]: + root = Path(__file__).resolve().parents[1] / "src" / "python_wrap" + found: dict[tuple[str, str], int] = {} + for path in sorted(root.rglob("*.py")): + if path.name == "_fork.py": + continue + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + parents: dict[int, ast.AST] = {} + for node in ast.walk(tree): + for child in ast.iter_child_nodes(node): + parents[id(child)] = node + for node in ast.walk(tree): + if not ( + isinstance(node, ast.Attribute) + and node.attr in {"Lock", "RLock"} + and isinstance(node.value, ast.Name) + and node.value.id == "threading" + ): + continue + target = node + while id(target) in parents and not isinstance( + parents[id(target)], (ast.Assign, ast.AnnAssign, ast.AugAssign, ast.stmt) + ): + target = parents[id(target)] + owner = parents.get(id(target)) + if isinstance(owner, ast.Assign): + name = ast.unparse(owner.targets[0]) + elif isinstance(owner, ast.AnnAssign): + name = ast.unparse(owner.target) + else: + name = ast.unparse(target) + key = (str(path.relative_to(root)), name) + found[key] = found.get(key, 0) + 1 + return found + + +def test_no_plain_threading_locks_in_package(): + unexpected = [] + for key, count in _plain_lock_sites().items(): + allowed, _reason = PLAIN_LOCK_ALLOW_LIST.get(key, (0, "")) + if count > allowed: + unexpected.append(f"{key[0]}: {key[1]} ({count} plain, {allowed} allowed)") + assert not unexpected, "use _fork.ForkSafeLock/ForkSafeRLock: " + "; ".join(unexpected) diff --git a/tests/test_http.py b/tests/test_http.py index 4fb7ce2..d82c9c7 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -550,9 +550,10 @@ def test_retry_after_garbage_and_odd_values_are_ignored() -> None: def test_retry_after_negative_and_past_date_mean_retry_now() -> None: - assert retry_delay(Response(503, {"Retry-After": "-5"}), 1) == 0.0 + # "now" is the 50 ms floor: a zero hint never produces a tight retry loop. + assert retry_delay(Response(503, {"Retry-After": "-5"}), 1) == 0.05 past = "Wed, 21 Oct 2015 07:28:00 GMT" - assert retry_delay(Response(503, {"Retry-After": past}), 1) == 0.0 + assert retry_delay(Response(503, {"Retry-After": past}), 1) == 0.05 def test_retry_after_header_is_case_insensitive_and_json_fallback_survives_garbage() -> None: diff --git a/tests/test_http_requests.py b/tests/test_http_requests.py new file mode 100644 index 0000000..c880dd9 --- /dev/null +++ b/tests/test_http_requests.py @@ -0,0 +1,139 @@ +"""``mount_policy`` on a real ``requests.Session`` against a local ``http.server``. + +The server binds to port 0 and the test reads the port back, so nothing leaves the +machine and nothing collides with other processes. +""" + +from __future__ import annotations + +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import pytest + +requests = pytest.importorskip("requests", reason="the requests package is not installed") + +from python_wrap.circuit import CircuitBreaker # noqa: E402 +from python_wrap.deadline import deadline # noqa: E402 +from python_wrap.errors import CircuitOpenError # noqa: E402 +from python_wrap.http import HttpPolicy, HttpRetryPolicy, mount_policy # noqa: E402 + + +class _Handler(BaseHTTPRequestHandler): + def do_GET(self) -> None: + self._serve() + + def do_POST(self) -> None: + self._serve() + + def _serve(self) -> None: + length = int(self.headers.get("Content-Length") or 0) + if length: + self.rfile.read(length) + server = self.server + with server.lock: # type: ignore[attr-defined] + server.hits.append((self.command, self.path)) # type: ignore[attr-defined] + status = server.statuses.get(self.path, 200) # type: ignore[attr-defined] + delay = server.delay # type: ignore[attr-defined] + if delay: + time.sleep(delay) + self.send_response(status) + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, format: str, *args: object) -> None: + return + + +class _Server(ThreadingHTTPServer): + daemon_threads = True + + def __init__(self) -> None: + super().__init__(("127.0.0.1", 0), _Handler) + self.hits: list[tuple[str, str]] = [] + self.statuses: dict[str, int] = {} + self.delay = 0.0 + self.lock = threading.Lock() + + @property + def url(self) -> str: + host, port = self.server_address[:2] + return f"http://{host}:{port}" + + def count(self, method: str, path: str) -> int: + with self.lock: + return self.hits.count((method, path)) + + +@pytest.fixture +def local_server(): + server = _Server() + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield server + finally: + server.shutdown() + server.server_close() + + +def _session() -> requests.Session: + session = requests.Session() + session.trust_env = False # ignore proxy variables: the server is local + return session + + +def test_mount_policy_5xx_counts_and_4xx_does_not(local_server): + server = local_server + server.statuses.update({"/boom": 500, "/missing": 404}) + breaker = CircuitBreaker(name="http-requests-5xx", failure_threshold=2, recovery_timeout=60) + session = _session() + mount_policy(session, HttpPolicy(breaker=breaker, retry=HttpRetryPolicy(max_attempts=1))) + + for _ in range(5): + assert session.get(server.url + "/missing").status_code == 404 + assert breaker.state == "closed" # client errors are not dependency failures + + assert session.get(server.url + "/boom").status_code == 500 + assert breaker.state == "closed" + assert session.get(server.url + "/boom").status_code == 500 # second 5xx opens it + assert breaker.state == "open" + + before = server.count("GET", "/boom") + server.count("GET", "/missing") + with pytest.raises(CircuitOpenError): + session.get(server.url + "/boom") + after = server.count("GET", "/boom") + server.count("GET", "/missing") + assert after == before # an open breaker sends nothing to the server + + +def test_mount_policy_timeout_shortened_to_deadline(local_server): + server = local_server + server.delay = 3.0 # the server answers only after the deadline has passed + session = _session() + mount_policy(session, HttpPolicy(read_timeout=10, retry=HttpRetryPolicy(max_attempts=1))) + + started = time.monotonic() + with deadline(0.5), pytest.raises(requests.exceptions.Timeout): + session.get(server.url + "/slow") + elapsed = time.monotonic() - started + # The configured read timeout is 10 s; without the shortening this call would have + # waited for the 3 s answer and returned 200. + assert elapsed < 2.5 + + +def test_post_is_not_retried_without_idempotency_key(local_server): + server = local_server + server.statuses.update({"/orders": 503}) + session = _session() + mount_policy(session, HttpPolicy(retry=HttpRetryPolicy(max_attempts=3, delay=0))) + + assert session.post(server.url + "/orders", data=b"x").status_code == 503 + assert server.count("POST", "/orders") == 1 # not repeated: POST is not idempotent + + keyed = {"Idempotency-Key": "order-1"} + assert session.post(server.url + "/orders", data=b"x", headers=keyed).status_code == 503 + assert server.count("POST", "/orders") == 1 + 3 # with the key, all three attempts ran + + assert session.get(server.url + "/orders").status_code == 503 + assert server.count("GET", "/orders") == 3 # GET is retried by default diff --git a/tests/test_redis_backends.py b/tests/test_redis_backends.py index 4fdd60e..439a67a 100644 --- a/tests/test_redis_backends.py +++ b/tests/test_redis_backends.py @@ -440,3 +440,27 @@ def price(sku): assert calls == ["a1"] invalidate_tags("sku:a1", client=redis_client) assert workers[3]("a1") == 2 + + +def test_redis_half_open_rejection_has_positive_wait(redis_client): + """A caller rejected while the single trial slot is in use must not get a zero wait.""" + breaker = CircuitBreaker( + name="g10-half-open", + failure_threshold=1, + recovery_timeout=0.2, + half_open_max_calls=1, + backend=RedisBreakerState(redis_client, state_ttl=0), + ) + + def boom() -> None: + raise ConnectionError("boom") + + with pytest.raises(ConnectionError): + breaker.call(boom) # opens the breaker + time.sleep(0.3) # recovery elapsed: the next admission is the half-open trial + generation, trial = breaker._acquire() + assert trial is True + with pytest.raises(CircuitOpenError) as rejected: + breaker._acquire() # the only trial slot is in use + assert rejected.value.retry_after > 0 + breaker._release(generation, trial) diff --git a/tests/test_redis_scripts_live.py b/tests/test_redis_scripts_live.py new file mode 100644 index 0000000..95a4db9 --- /dev/null +++ b/tests/test_redis_scripts_live.py @@ -0,0 +1,291 @@ +"""Each Lua script runs on a real redis-server and returns the answers its callers rely on. + +The tests here drive the scripts through the public classes and record which script +text reached ``EVAL``, so a script that the server rejects, or that no test reaches, +fails loudly. ``tests/test_stability.py`` checks that every module-level script has a +test in this file or in ``tests/test_redis_backends.py``. +""" + +from __future__ import annotations + +import os +import shutil +import socket +import subprocess +import tempfile +import time +import uuid +from pathlib import Path + +import pytest + +from python_wrap.agents import _REDIS_CLAIM, _REDIS_SETTLE, EffectRecord, RedisEffectStore +from python_wrap.circuit import CircuitBreaker +from python_wrap.coordination import _LEASE, RedisLock +from python_wrap.errors import CircuitOpenError +from python_wrap.llm import _REDIS_ADD, RedisBudgetBackend +from python_wrap.llm_shared import _LUA_STEP, RedisTokenWindow +from python_wrap.quotas import _WINDOW, Quota, QuotaExhausted, RedisWindow +from python_wrap.retry import RetryBudget +from python_wrap.shared import _BREAKER, _BUDGET, RedisBreakerState, RedisRetryBudget + + +class Recording: + """Forwards to a real client and remembers every script sent with ``eval``.""" + + def __init__(self, inner): + self.inner = inner + self.scripts: list[str] = [] + + def eval(self, script, count, *args): + self.scripts.append(script) + return self.inner.eval(script, count, *args) + + def __getattr__(self, name): + return getattr(self.inner, name) + + +class Client: + def __init__(self, path): + self.path = path + + def execute(self, *args): + values = [value if isinstance(value, bytes) else str(value).encode() for value in args] + payload = ( + b"*" + + str(len(values)).encode() + + b"\r\n" + + b"".join( + b"$" + str(len(value)).encode() + b"\r\n" + value + b"\r\n" for value in values + ) + ) + with socket.socket(socket.AF_UNIX) as conn: + conn.settimeout(3) + conn.connect(self.path) + conn.sendall(payload) + stream = conn.makefile("rb") + + def read(): + line = stream.readline() + if not line: + raise RuntimeError("Redis disconnected") + kind, body = line[:1], line[1:-2] + if kind == b"-": + raise RuntimeError(body.decode()) + if kind == b":": + return int(body) + if kind == b"+": + return body + size = int(body) + if size < 0: + return None + if kind == b"*": + return [read() for _ in range(size)] + value = stream.read(size) + assert stream.read(2) == b"\r\n" + return value + + return read() + + def get(self, key): + return self.execute("GET", key) + + def set(self, key, value, **kw): + args = ["SET", key, value] + for k, v in kw.items(): + args.extend([k.upper(), v]) + return self.execute(*args) + + def delete(self, *keys): + return self.execute("DEL", *keys) + + def unlink(self, *keys): + return self.execute("UNLINK", *keys) + + def eval(self, script, count, *args): + return self.execute("EVAL", script, count, *args) + + def hmget(self, key, *fields): + return self.execute("HMGET", key, *fields) + + def hget(self, key, field): + return self.execute("HGET", key, field) + + def pttl(self, key): + return self.execute("PTTL", key) + + def scan_iter(self, **kw): + cursor = 0 + while True: + cursor, keys = self.execute( + "SCAN", cursor, "MATCH", kw["match"], "COUNT", kw.get("count", 200) + ) + yield from keys + if int(cursor) == 0: + break + + +@pytest.fixture(scope="module") +def redis_client(): + executable = shutil.which("redis-server") + if executable is None or not hasattr(socket, "AF_UNIX"): + if os.environ.get("PW_REQUIRE_REDIS") == "1": + pytest.fail("redis-server and Unix sockets required") + pytest.skip("redis-server and Unix sockets required") + # Short path for macOS's AF_UNIX length limit. + with tempfile.TemporaryDirectory(prefix="pw-redis-", dir="/tmp") as root: + path = str(Path(root) / "r.sock") + proc = subprocess.Popen( + [executable, "--port", "0", "--unixsocket", path, "--save", "", "--appendonly", "no"], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) + try: + client = Client(path) + for _ in range(100): + if Path(path).exists(): + break + if proc.poll() is not None: + log = proc.stdout.read().decode() + if ( + "Operation not permitted" in log + and os.environ.get("PW_REQUIRE_REDIS") != "1" + ): + pytest.skip("sandbox prohibits Redis socket binding") + pytest.fail(log) + time.sleep(0.01) + assert client.execute("PING") == b"PONG" + yield client + finally: + proc.terminate() + proc.wait(timeout=5) + + +def _name(prefix: str) -> str: + return f"{prefix}-{uuid.uuid4().hex[:10]}" + + +def test_quota_script_runs_live(redis_client): + rec = Recording(redis_client) + key = _name("live-quota") + quota = Quota(3, client=rec, key=key, ttl=60) + assert [quota.take(), quota.take()] == [2, 1] + assert quota.remaining == 1 + assert 0 < int(redis_client.pttl(key)) <= 60_000 # the TTL was applied on first use + assert quota.take() == 0 + with pytest.raises(QuotaExhausted): + quota.take() + assert redis_client.get(key) == b"3" # the refused take did not increment + assert quota.remaining == 0 + quota.reset() + assert quota.remaining == 3 + assert len(rec.scripts) >= 4 + + +def test_window_script_runs_live(redis_client): + rec = Recording(redis_client) + window = RedisWindow(rec, _name("live-window"), calls=2, period=0.3) + assert window.acquire() == 0 and window.acquire() == 0 + wait = window.acquire() + assert 0 < wait <= 0.3 # third call refused: seconds until the oldest slot expires + time.sleep(wait + 0.05) + assert window.acquire() == 0 # the expired slot is freed on the server clock + assert _WINDOW in rec.scripts + window.clear() + assert window.acquire() == 0 + + +def test_token_window_script_runs_live(redis_client): + rec = Recording(redis_client) + window = RedisTokenWindow(rec, _name("live-tokens"), fail_open=False) + assert window.reserve(4, capacity=10, rate=1.0) == 0.0 + level = window.level(10, 1.0) + assert 5.0 < level < 6.5 # 10 - 4, plus the refill since the reserve + wait = window.reserve(10, capacity=10, rate=1.0) + assert 3.0 < wait <= 4.0 # about 4 tokens short at one token per second + window.force(8, capacity=10, rate=1.0) # about 6 available: the forced take is 2 in debt + assert -2.1 < window.level(10, 1.0) < 0 + assert _LUA_STEP in rec.scripts + + +def test_lease_script_runs_live(redis_client): + rec = Recording(redis_client) + lock = RedisLock(rec, _name("live-lease") + ":") + assert lock.acquire("job", "t1", ttl=30) is True + assert lock.acquire("job", "t2", ttl=30) is False # capacity one + assert lock.renew("job", "t1", ttl=30) is True + assert lock.renew("job", "t2", ttl=30) is False + assert lock.release("job", "t2") is False # a non-owner cannot release + assert lock.release("job", "t1") is True + assert lock.acquire("job", "t2", ttl=30) is True + assert lock.acquire("pool", "a", ttl=30, limit=2) is True + assert lock.acquire("pool", "b", ttl=30, limit=2) is True + assert lock.acquire("pool", "c", ttl=30, limit=2) is False + assert lock.acquire("short", "s", ttl=0.2) is True + time.sleep(0.35) + assert lock.acquire("short", "n", ttl=30) is True # the expired lease was dropped + assert _LEASE in rec.scripts + + +def test_breaker_script_runs_live(redis_client): + rec = Recording(redis_client) + state = RedisBreakerState(rec, _name("live-breaker") + ":", state_ttl=0) + breaker = CircuitBreaker(name=_name("live-breaker-name"), failure_threshold=2, backend=state) + + def boom(): + raise RuntimeError("down") + + for _ in range(2): + with pytest.raises(RuntimeError): + breaker.call(boom) + assert breaker.state.value == "open" + with pytest.raises(CircuitOpenError): + breaker.call(lambda: "never") + assert _BREAKER in rec.scripts + + +def test_retry_budget_script_runs_live(redis_client): + rec = Recording(redis_client) + budget = RetryBudget( + ratio=0.5, min_per_second=0, window=10, backend=RedisRetryBudget(rec, _name("live-budget")) + ) + for _ in range(4): + budget.deposit() + # Allowance is 0.5 * 4 requests = 2 retries, so the third withdrawal is refused. + assert [budget.try_withdraw(), budget.try_withdraw(), budget.try_withdraw()] == [ + True, + True, + False, + ] + assert _BUDGET in rec.scripts + + +def test_spend_counter_script_runs_live(redis_client): + rec = Recording(redis_client) + backend = RedisBudgetBackend(rec, _name("live-spend")) + assert backend.add("team", 5, 0.25, ttl=60) == (5, 0.25) + assert backend.add("team", 7, 0.5, ttl=60) == (12, 0.75) + assert backend.get("team") == (12, 0.75) + assert 0 < int(redis_client.pttl(backend._key("team"))) <= 60_000 + backend.delete("team") + assert backend.get("team") == (0, 0.0) + assert _REDIS_ADD in rec.scripts + + +def test_effect_ledger_scripts_run_live(redis_client): + rec = Recording(redis_client) + store = RedisEffectStore(rec, _name("live-effects") + ":") + first = EffectRecord(key="call-1", tool="pay", state="started", owner="own-1") + assert store.claim(first, 60, None) is None # the first claim wins + rival = EffectRecord(key="call-1", tool="pay", state="started", owner="own-2") + seen = store.claim(rival, 60, "") + assert seen is not None and seen.owner == "own-1" # a second claim sees the holder + done = EffectRecord( + key="call-1", tool="pay", state="succeeded", owner="own-1", has_result=True, result=42 + ) + assert store.settle(done, 60) is True + stale = EffectRecord(key="call-1", tool="pay", state="failed", owner="own-2") + assert store.settle(stale, 60) is False # a stale owner cannot overwrite the outcome + got = store.get("call-1") + assert got is not None and got.state == "succeeded" and got.result == 42 + assert _REDIS_CLAIM in rec.scripts and _REDIS_SETTLE in rec.scripts diff --git a/tests/test_release_041.py b/tests/test_release_041.py new file mode 100644 index 0000000..2c44c52 --- /dev/null +++ b/tests/test_release_041.py @@ -0,0 +1,270 @@ +"""0.4.1 regressions: caller errors are not store outages, and a finished call keeps its result.""" + +from __future__ import annotations + +import os +import subprocess +import sys +from typing import Any, NamedTuple + +import pytest + +from python_wrap import events +from python_wrap._runtime import cache_key_of +from python_wrap.caching import memoize +from python_wrap.circuit import CircuitBreaker +from python_wrap.shared import RedisBreakerState +from python_wrap.stores import RedisStore, json_codec + + +class FakeRedis: + """A dict-backed client that counts calls and can be switched to fail.""" + + def __init__(self) -> None: + self.data: dict[str, bytes] = {} + self.calls = 0 + self.fail = False + + def _tick(self) -> None: + self.calls += 1 + if self.fail: + raise ConnectionError("store down") + + def get(self, key: str) -> bytes | None: + self._tick() + return self.data.get(key) + + def set(self, key: str, value: bytes, px: int | None = None) -> None: + self._tick() + self.data[key] = value + + def delete(self, key: str) -> int: + self._tick() + return int(self.data.pop(key, None) is not None) + + +class Scope(NamedTuple): + tenant: str + region: str + + +def _store(client: FakeRedis, prefix: str = "t:") -> RedisStore: + return RedisStore(client, prefix, dumps=json_codec()[0], loads=json_codec()[1]) + + +# --- Gap 1: key and codec errors are not counted as a store outage ----------------- + + +def test_unstable_key_raises_and_leaves_store_healthy() -> None: + client = FakeRedis() + store = _store(client, "g1-key:") + seen: list[str] = [] + with events.listening(lambda e: seen.append(e.name)): + with pytest.raises(TypeError): + store.get(object()) + with pytest.raises(TypeError): + store.set(object(), "v", None) + assert "backend.error" not in seen + assert client.calls == 0 + assert store._monitor.degraded is False + + +def test_memoize_over_redis_store_raises_for_unstable_argument() -> None: + client = FakeRedis() + + @memoize(store=_store(client, "g1-memo:"), ttl=60) + def load(item: object) -> int: + return 1 + + seen: list[str] = [] + with events.listening(lambda e: seen.append(e.name)), pytest.raises(TypeError): + load(object()) + assert "backend.error" not in seen + + +def test_named_tuple_key_is_stable_across_hash_seeds() -> None: + snippet = ( + "from typing import NamedTuple\n" + "from python_wrap._runtime import cache_key_of\n" + "class Scope(NamedTuple):\n" + " tenant: str\n" + " region: str\n" + "print(cache_key_of(Scope('a', 'b')))\n" + ) + outputs = set() + for seed in ("1", "99"): + env = {**os.environ, "PYTHONHASHSEED": seed} + out = subprocess.run( + [sys.executable, "-c", snippet], + env=env, + capture_output=True, + text=True, + check=True, + ).stdout + outputs.add(out) + assert len(outputs) == 1 + + +def test_named_tuple_and_plain_tuple_do_not_collide() -> None: + assert cache_key_of(Scope("a", "b")) != cache_key_of(("a", "b")) + + +def test_str_and_int_subclasses_encode_like_their_base() -> None: + class Name(str): + pass + + class Count(int): + pass + + assert cache_key_of(Name("x")) == cache_key_of("x") + assert cache_key_of(Count(3)) == cache_key_of(3) + + +def test_negative_zero_and_zero_share_a_key() -> None: + assert cache_key_of(-0.0) == cache_key_of(0.0) + + +def test_cache_key_hook_is_used() -> None: + class Account: + def __init__(self, ident: int) -> None: + self.id = ident + + def __cache_key__(self) -> tuple[str, int]: + return ("account", self.id) + + assert cache_key_of(Account(7)) == cache_key_of(Account(7)) + assert cache_key_of(Account(7)) != cache_key_of(Account(8)) + + +def test_undecodable_entry_is_a_miss_and_store_stays_up() -> None: + client = FakeRedis() + store = _store(client, "g1-decode:") + store.set("a", {"x": 1}, None) + store.set("b", {"y": 2}, None) + for key in list(client.data): + client.data[key] = b"\x00not json" + seen: list[str] = [] + with events.listening(lambda e: seen.append(e.name)): + assert store.get("a") is None + assert store.get("b") is None + assert "backend.error" not in seen + assert store._monitor.degraded is False + assert client.calls == 4 # two gets, each reached the store + + +def test_dumps_error_propagates() -> None: + client = FakeRedis() + store = _store(client, "g1-dumps:") + with pytest.raises(TypeError): + store.set("k", {1, 2}, None) # json cannot encode a set + assert client.calls == 0 + + +def test_async_store_decode_is_a_miss() -> None: + import asyncio + + from python_wrap.async_cache import AsyncRedisStore + + class AsyncFake: + def __init__(self) -> None: + self.data: dict[str, bytes] = {} + self.gets = 0 + + async def get(self, key: str) -> bytes | None: + self.gets += 1 + return self.data.get(key) + + client = AsyncFake() + store = AsyncRedisStore(client, "p:", dumps=json_codec()[0], loads=json_codec()[1]) + client.data[store._key("x")] = b"\x00bad" + seen: list[str] = [] + + async def run() -> Any: + with events.listening(lambda e: seen.append(e.name)): + return await store.get("x") + + assert asyncio.run(run()) is None + assert client.gets == 1 + assert "backend.error" not in seen + assert store._monitor.degraded is False + + +# --- Gap 2: a store error after a successful call keeps the result ---------------- + + +class _StoreStub: + """A breaker backend whose admission and bookkeeping never reach a real store. + + The breaker's admission and settlement are patched per test, so the only code under + test is what runs after the wrapped function returns. + """ + + def eval(self, *args: object) -> object: + raise ConnectionError("not reached: admission is patched") + + evalsha = eval + get = eval + + +def _breaker_with_failing_bookkeeping(name: str, monkeypatch: pytest.MonkeyPatch) -> CircuitBreaker: + breaker = CircuitBreaker(name=name, backend=RedisBreakerState(_StoreStub(), state_ttl=0)) + monkeypatch.setattr(breaker, "_acquire", lambda: (0, False)) + + def bookkeeping_fails(*args: Any, **kwargs: Any) -> None: + raise ConnectionError("bookkeeping store error") + + monkeypatch.setattr(breaker, "_success", bookkeeping_fails) + return breaker + + +def test_store_error_after_success_returns_result_sync(monkeypatch: pytest.MonkeyPatch) -> None: + breaker = _breaker_with_failing_bookkeeping("g2-sync", monkeypatch) + runs: list[int] = [] + + @breaker + def pay() -> str: + runs.append(1) + return "paid" + + seen: list[str] = [] + with events.listening(lambda e: seen.append(e.name)): + assert pay() == "paid" + assert runs == [1] + + +def test_store_error_after_success_returns_result_async(monkeypatch: pytest.MonkeyPatch) -> None: + import asyncio + + breaker = _breaker_with_failing_bookkeeping("g2-async", monkeypatch) + runs: list[int] = [] + + @breaker + async def send() -> str: + runs.append(1) + return "sent" + + assert asyncio.run(send()) == "sent" + assert runs == [1] + + +# --- Gap 10: hinted waits get jitter on top and a floor for zero ------------------ + + +def test_hint_gets_jitter_and_stays_a_lower_bound(monkeypatch: pytest.MonkeyPatch) -> None: + import importlib + + retry_mod = importlib.import_module("python_wrap.retry") + monkeypatch.setattr(retry_mod, "HINT_JITTER", 0.1) + waits = [retry_mod._hinted(10.0, 1000.0) for _ in range(500)] + assert all(10.0 <= wait <= 11.0 for wait in waits) + assert max(waits) - min(waits) > 0.5 # the waits are actually spread out + + +def test_zero_hint_is_floored_and_cap_still_applies(monkeypatch: pytest.MonkeyPatch) -> None: + import importlib + + retry_mod = importlib.import_module("python_wrap.retry") + monkeypatch.setattr(retry_mod, "HINT_JITTER", 0.0) + assert retry_mod._hinted(0.0, 1000.0) == retry_mod.HINT_FLOOR + monkeypatch.setattr(retry_mod, "HINT_JITTER", 0.1) + assert retry_mod._hinted(500.0, 30.0) == 30.0 diff --git a/tests/test_release_metadata.py b/tests/test_release_metadata.py new file mode 100644 index 0000000..21d3c5a --- /dev/null +++ b/tests/test_release_metadata.py @@ -0,0 +1,46 @@ +"""Release metadata: changelog shape, version and classifier, provisional docstrings.""" + +from __future__ import annotations + +import ast +import importlib.util +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +PROVISIONAL_MODULES = ["shared", "quotas", "stores", "http", "celery"] + + +def _load_check_release(): + spec = importlib.util.spec_from_file_location( + "check_release", ROOT / "scripts" / "check_release.py" + ) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +check_release = _load_check_release() + + +def test_changelog_has_no_duplicate_entries() -> None: + text = (ROOT / "CHANGELOG.md").read_text(encoding="utf-8") + assert check_release.duplicate_entries(text) == [] + + +def test_duplicate_check_detects_repeated_entry() -> None: + text = "## [1.0.0]\n\n### Added\n\n- same entry\n\n### Added\n\n- same entry\n" + problems = check_release.duplicate_entries(text) + assert any("duplicate heading" in p for p in problems) + assert any("duplicate entry" in p for p in problems) + + +def test_version_and_classifier_are_consistent() -> None: + assert check_release.version_and_classifier_problems() == [] + + +def test_provisional_modules_say_so_in_docstring() -> None: + for name in PROVISIONAL_MODULES: + source = (ROOT / "src" / "python_wrap" / f"{name}.py").read_text(encoding="utf-8") + doc = ast.get_docstring(ast.parse(source)) or "" + assert "Provisional:" in doc, f"{name}.py docstring lacks a Provisional line" diff --git a/tests/test_retry.py b/tests/test_retry.py index 6a22568..d351a2f 100644 --- a/tests/test_retry.py +++ b/tests/test_retry.py @@ -401,7 +401,8 @@ def boom(exc: BaseException) -> float | None: retry(Flaky(1), delay=3, delay_from=lambda e: float("nan"))() retry(Flaky(1), delay=4, delay_from=lambda e: "x")() # type: ignore[arg-type,return-value] retry(Flaky(1), delay_from=lambda e: -5)() - assert fake_clock.sleeps == [2, 3, 4, 0.0] + # A hint of zero (here clamped from -5) waits the 50 ms floor, never a tight loop. + assert fake_clock.sleeps == [2, 3, 4, 0.05] def test_retry_after_recipe(fake_clock: FakeClock) -> None: diff --git a/tests/test_stability.py b/tests/test_stability.py index 8c6fc8c..bfc4f37 100644 --- a/tests/test_stability.py +++ b/tests/test_stability.py @@ -8,6 +8,7 @@ from __future__ import annotations import inspect +import re import pytest @@ -129,3 +130,34 @@ def test_shared_backend_key_formats_are_frozen(): table = SqlResultStore.ddl("postgresql")[0] for column in ("idem_key", "status", "owner", "result", "expires_at"): assert column in table + + +_LIVE_TEST_FILES = ("tests/test_redis_backends.py", "tests/test_redis_scripts_live.py") + + +def _module_lua_scripts() -> list[str]: + """Names of module-level triple-quoted Lua scripts (``redis.call`` in the body).""" + import re + from pathlib import Path + + src = Path(python_wrap.__file__).parent + pattern = re.compile(r'^([A-Za-z_]\w*) = """(.*?)"""', re.MULTILINE | re.DOTALL) + names: list[str] = [] + for path in sorted(src.glob("*.py")): + for match in pattern.finditer(path.read_text(encoding="utf-8")): + if "redis.call(" in match.group(2): + names.append(match.group(1)) + return names + + +def test_every_lua_script_has_a_live_test(): + from pathlib import Path + + root = Path(__file__).resolve().parent.parent + live = "\n".join((root / name).read_text(encoding="utf-8") for name in _LIVE_TEST_FILES) + scripts = _module_lua_scripts() + # The known scripts must all be found; a silent miss would hide a new one. + for known in ("_BREAKER", "_BUDGET", "_WINDOW", "_LEASE", "_LUA_STEP", "_REDIS_ADD"): + assert known in scripts, known + missing = [name for name in scripts if not re.search(rf"\b{name}\b", live)] + assert not missing, f"Lua scripts without a live test: {missing}" From 01e3f60daf216b80bbe6e5d27adc8966bca6fb63 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Thu, 26 Nov 2026 20:54:24 +0200 Subject: [PATCH 02/38] docs: document 0.4.1 behaviour changes and update the changelog Feature pages for caching, circuit breakers, retry, HTTP clients and shared limits describe the new key rules, failure modes and hint jitter. Examples and cookbook assertions that depended on exact retry waits now use ranges. Changelog and README gain the 0.4.1 entries and the stable-surface section. --- CHANGELOG.md | 19 +++++--- README.md | 12 +++++ RELEASING.md | 5 ++- docs/cookbook/resilient-llm-client.md | 2 +- docs/cookbook/sdk-adapters.md | 2 +- docs/features/ai/llm-calls.md | 4 +- docs/features/caching/async-stores.md | 6 ++- docs/features/caching/memoize.md | 8 +++- .../caching/stores-and-credentials.md | 44 +++++++++++++++++-- docs/features/concurrency/bulkheads.md | 3 ++ docs/features/concurrency/shared-limits.md | 4 +- docs/features/resilience/circuit-breaker.md | 4 ++ docs/features/resilience/http-clients.md | 6 +-- .../resilience/multi-process-breakers.md | 3 ++ docs/features/resilience/retry.md | 6 +-- docs/llms-full.txt | 10 ++--- docs/project/stability.md | 5 ++- examples/llm_client.py | 2 +- .../support_agent/tests/test_agent.py | 2 +- examples/resilient_llm_client.py | 2 +- 20 files changed, 113 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61d5ff5..e72f18d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration. ## [Unreleased] +## [0.4.1] - unreleased + ### Security - Shared SQLite token windows now sample time after taking the writer lock and keep stored @@ -24,6 +26,16 @@ Breaking changes are listed under **Breaking changes**, each with its migration. - 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. +- A store error after a successful call no longer replaces the result: circuit breaker bookkeeping (sync and async) and shared bulkhead release are logged and the result is returned. `backend.error` is emitted with operation "success" or "release". +- Redis and async Redis cache stores: key building and codec work now run outside the backend monitor. A key that cannot be encoded raises `TypeError` and does not count as a store outage. An entry that cannot be decoded is a miss with `cache.rejected(reason="decode")`. +- `-0.0` and `0.0` now produce the same cache key. This changes the key of `-0.0` arguments only. +- Half-open circuit rejections carry a positive `retry_after` (local: `min(max(recovery_timeout, 0.05), 1.0)`; shared: time to the trial deadline, at least 50 ms). +- Every hinted wait (`Retry-After`, breaker hints, retry countdowns) gets up to 10% jitter on top and a 50 ms floor when the hint is 0. Exact hinted waits in tests change accordingly. + +### Added + +- `python_wrap._runtime.cache_key_of(value)` public helper. +- The key encoder accepts subclasses of `str`, `int`, `float`, `bytes`, `tuple`, `list`, `dict` and `set`; named tuples (class-tagged); and an application hook `__cache_key__()`. ## [0.4.0] - 2026-11-26 @@ -174,13 +186,6 @@ shared stores written by other processes). Fixed: lease and retry budget move to Redis, keyed by the preset name. `SharedBackends` overrides one layer. `RetryBudget(backend=...)` and `RedisRetryBudget` cap retries across a fleet. -### Added - -- `on_backend_error="raise" | "local" | "allow"` on shared breakers, windows, quotas, - bulkheads and `RedisSource`, plus `configure(backend_errors=...)`, `retry_backend_after`, - the events `backend.error` / `backend.recovered`, and a `degraded` health status while a - fallback is active. `RedisStore`/`AsyncRedisStore` report through the same events. - ## [0.4.0b1] - 2026-11-11 First beta. The public API is feature-complete for 0.4: the remaining work before the diff --git a/README.md b/README.md index 1480751..77f9232 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,18 @@ Unreleased on `main`; see the [CHANGELOG](https://github.com/LitePy/PythonWrap/b The [stable core](https://pythonwrap.readthedocs.io/en/latest/project/stability/) (retry, circuit breaker, timeout, policies, presets) is now frozen ahead of 1.0. +## What is stable in 0.4 + +The stable core is frozen: retry, circuit breaker, timeout and deadline, policies, presets, +errors and events. It does not change incompatibly before 1.0. + +Provisional modules may change in a minor release. They are `shared`, `coordination`, +`quotas`, `stores`, `http` and `celery` (target 0.5.0), and `async_cache`, `web`, +`exporters` and `observability` (target 0.6.0). The newer integrations (dashboard, chaos, +migrate and distributed backends) are provisional too. The full policy, graduation +criteria and status table are in +[`docs/project/stability.md`](https://github.com/LitePy/PythonWrap/blob/main/docs/project/stability.md). + ## New in 0.4 (beta) | Need | API | diff --git a/RELEASING.md b/RELEASING.md index bf562cf..f88094f 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -32,7 +32,9 @@ was removed; revoke the token it used at ] - `. The - GitHub release notes are taken from this section. + GitHub release notes are taken from this section. Two checks before tagging: + - No `Unreleased` entry may describe code that is in the tag. Cut the section first. + - A final release differs from its last beta only by fixes. New features need a new beta. 3. **Check locally.** ```bash @@ -43,6 +45,7 @@ was removed; revoke the token it used at 0 # A backup model for outages. diff --git a/docs/cookbook/sdk-adapters.md b/docs/cookbook/sdk-adapters.md index d623ea6..baa83b6 100644 --- a/docs/cookbook/sdk-adapters.md +++ b/docs/cookbook/sdk-adapters.md @@ -62,7 +62,7 @@ chat = llm_client("docs-chat", spend=spend)(create) with fake_clock() as clock: reply = chat(model="any", messages=[{"role": "user", "content": "hello"}]) assert reply.choices[0].message.content == "hi" -assert clock.sleeps == [2.0] # waited what the provider asked +assert 2.0 <= clock.sleeps[0] <= 2.2 # waited what the provider asked, plus up to 10% jitter assert spend.spent().tokens == 40 ``` diff --git a/docs/features/ai/llm-calls.md b/docs/features/ai/llm-calls.md index 239c63c..6828df5 100644 --- a/docs/features/ai/llm-calls.md +++ b/docs/features/ai/llm-calls.md @@ -59,7 +59,7 @@ assert not llm_transient(APIStatusError(400, "content_policy_violation")) `llm_retry()` is a `retry` that retries only `llm_transient` errors. Waits double from 1 s (plus up to 0.5 s jitter) unless the provider sent `Retry-After` or `retry-after-ms`; -that wait is used exactly, capped at `max_delay` (60 s by default). A `RetryBudget` +that wait is a lower bound, with up to 10% jitter added, capped at `max_delay` (60 s by default). A `RetryBudget` (20 % of calls plus 5 retries per second) keeps an outage from multiplying your traffic. `presets.llm_client(name)` bundles it into a `Policy`: @@ -96,7 +96,7 @@ def complete(prompt: str) -> dict[str, object]: with fake_clock() as clock: complete("Summarise this") -assert clock.sleeps == [2.0] # the provider's Retry-After +assert len(clock.sleeps) == 1 and 2.0 <= clock.sleeps[0] <= 2.2 # the provider's Retry-After, plus up to 10% jitter assert chat.explain().findings == () ``` diff --git a/docs/features/caching/async-stores.md b/docs/features/caching/async-stores.md index e88f77c..b15fcaf 100644 --- a/docs/features/caching/async-stores.md +++ b/docs/features/caching/async-stores.md @@ -90,8 +90,10 @@ async def get_price(sku: str) -> dict: return await price(sku) ``` -By default errors from Redis are logged and treated as misses (`fail_open=True`); pass -`fail_open=False` to raise. `clear()` scans only this store's prefix and deletes in +By default Redis connection or server errors are logged and treated as misses +(`fail_open=True`); pass `fail_open=False` to raise. An unencodable key raises `TypeError` +and is not treated as a store outage. A stored value that cannot be decoded is a miss +(`cache.rejected`, `reason="decode"`). See [stores and credentials](stores-and-credentials.md#failure-modes). `clear()` scans only this store's prefix and deletes in batches with `UNLINK`. With several processes sharing the store, add `lock=AsyncRedisLock(client)` so only one diff --git a/docs/features/caching/memoize.md b/docs/features/caching/memoize.md index 9e84e71..bc69bc4 100644 --- a/docs/features/caching/memoize.md +++ b/docs/features/caching/memoize.md @@ -107,8 +107,12 @@ A shared store (`RedisStore`, `AsyncRedisStore`) and the `idempotent`/`single_in keys use a canonical encoding: dict items and set members are sorted, so the same arguments give the same key in every process whatever its `PYTHONHASHSEED` or insertion order. Plain data (None, bool, int, float, str, bytes, tuple, list, dict, set, frozenset), -enums, dataclasses, `datetime` and `decimal` values, `UUID` and paths are supported. Any -other object raises `TypeError` naming the argument; pass `key=` for it. Redis keys carry +enums, dataclasses, `datetime` and `decimal` values, `UUID` and paths are supported. Subclasses +of these base types encode like their base. Named tuples carry their class, so a named tuple and +a plain tuple with the same items get different keys. An object with a `__cache_key__()` method +is encoded through the value that method returns. `0.0` and `-0.0` share one key. Any +other object raises `TypeError` naming the argument; pass `key=` for it. See +[stores and credentials](stores-and-credentials.md#cache-keys) for the `cache_key_of` helper. Redis keys carry a `k2:` format marker, so entries written by 0.4.0b1 are never misread and simply expire (`clear()` still removes them). `doctor` reports PW022 for a cached function with a shared store and no `key=` whose parameters are dicts, sets or unannotated. diff --git a/docs/features/caching/stores-and-credentials.md b/docs/features/caching/stores-and-credentials.md index 0fdfd48..1d49622 100644 --- a/docs/features/caching/stores-and-credentials.md +++ b/docs/features/caching/stores-and-credentials.md @@ -30,11 +30,47 @@ entries. Implicit pickle is deprecated; pass `signed_pickle_codec(secret)` or `json_codec()` from `python_wrap.stores`. `configure(cache_codec=(dumps, loads))` sets the default for both sync and async Redis stores. Entries are opaque tuples, so custom serializers must round-trip them. Invalid signatures are misses and emit -`cache.rejected` before anything is unpickled. +`cache.rejected` with `reason="signature"` before anything is unpickled. -`fail_open=True` (the default) logs a backend error and treats a read as a miss or a -write as a no-op. Set it to `False` when persistence is part of correctness, especially -for [idempotency](../concurrency/leases-and-idempotency.md#idempotency). +### Failure modes + +Redis and codec failures fall into three groups: + +| Situation | Result | +| --- | --- | +| Redis client error (connection, timeout, server error) | Store outage: `fail_open=True` logs `backend.error` and treats a read as a miss or a write as a no-op. `fail_open=False` raises. | +| Key cannot be encoded (for example an unsupported argument type) | `TypeError` to the caller. Not a store outage: no `backend.error`, and `fail_open` does not apply. | +| Stored value cannot be decoded | A miss, with `cache.rejected` and `reason="decode"`; `reason="signature"` for a bad signature. | +| Value cannot be encoded by `dumps` | The error propagates to the caller. | + +Set `fail_open=False` when persistence is part of correctness, especially +for [idempotency](../concurrency/leases-and-idempotency.md#idempotency). The +async store (`AsyncRedisStore`) follows the same rules. + +### Cache keys + +Shared stores derive keys with the canonical encoder used by `memoize`. Plain +values, their subclasses (for example a `str` subclass), named tuples +(encoded with their class, so they never collide with a plain tuple) and `-0.0`/`0.0` +(one key) are handled. For your own types, define `__cache_key__()` returning a value +the encoder already accepts: + +```python +from python_wrap._runtime import cache_key_of + +class Region: + def __init__(self, code: str, zone: int) -> None: + self.code, self.zone = code, zone + + def __cache_key__(self) -> tuple[str, int]: + return (self.code, self.zone) + +assert cache_key_of(Region("eu", 2)) == cache_key_of(Region("eu", 2)) +``` + +`cache_key_of` is available as `python_wrap._runtime.cache_key_of`. It is not part of the +top-level public API. It raises `TypeError` for a value with no stable form, so you can +check an argument type before relying on it in a shared store. `cache_info().currsize` is **None** for this adapter: statistics never scan Redis. `clear()` scans only the escaped namespace and deletes in bounded batches; clearing a diff --git a/docs/features/concurrency/bulkheads.md b/docs/features/concurrency/bulkheads.md index b5b3609..7c1c498 100644 --- a/docs/features/concurrency/bulkheads.md +++ b/docs/features/concurrency/bulkheads.md @@ -97,6 +97,9 @@ Waiting for a slot (the bulkhead `timeout`) runs on **real time**. `fast_mode()` !!! warning "Threads and event loops have separate limits" Sync callers share a `threading.BoundedSemaphore`; async callers use one `asyncio.Semaphore` per event loop (asyncio primitives cannot be shared across loops). So the cap applies separately to threads and to each loop. If one program uses both sides, give each side its own bulkhead. Never use `with bulkhead:` inside a coroutine: waiting for a slot there would block the event loop. +!!! note "Release errors on shared bulkheads" + A `Bulkhead` with a shared `backend=` that fails to release its slot logs the error (`backend.error`, `operation="release"`) and returns the call's own result or exception. The slot expires at its TTL. See [shared limits](shared-limits.md#shared-bulkheads). + !!! warning "A bulkhead inside a global limit can starve" Suppose `map_async(fetch, urls, limit=10)` calls a function that waits for a per-host `Bulkhead(2)`. A task holds one of the 10 global slots *while it queues for the bulkhead*. If most URLs hit the same host, ten tasks sit on global slots, two work and eight wait, so requests to every other host are blocked behind them (and with a `timeout` or `max_waiting` the waiters may be rejected instead). Two ways out: diff --git a/docs/features/concurrency/shared-limits.md b/docs/features/concurrency/shared-limits.md index bea81bc..2c02635 100644 --- a/docs/features/concurrency/shared-limits.md +++ b/docs/features/concurrency/shared-limits.md @@ -116,7 +116,9 @@ async def call_model(): The lease-backed capacity is shared; `max_waiting` bounds the queue in **each process**. `active` and `waiting` report local calls, not a global monitor. Sync and async context managers work too. For shared async use `async with capacity` so release can await -backend I/O. Lease expiry has the same [limits](leases-and-idempotency.md#redis-and-sql-backends) +backend I/O. A release error is logged through `backend.error` with `operation="release"` +and does not fail the call: the call's result or exception is kept, and the slot expires +at its `ttl`. Lease expiry has the same [limits](leases-and-idempotency.md#redis-and-sql-backends) as a distributed lock; long external work must tolerate a lost lease. ## Async services diff --git a/docs/features/resilience/circuit-breaker.md b/docs/features/resilience/circuit-breaker.md index 4f3ec45..03a9bf0 100644 --- a/docs/features/resilience/circuit-breaker.md +++ b/docs/features/resilience/circuit-breaker.md @@ -44,6 +44,10 @@ assert call_api.breaker.state is CircuitState.CLOSED Only exceptions matching `on=` count as failures; others pass through uncounted. `half_open_max_calls` limits how many trial calls may run at once while half-open. +A call rejected while half-open raises `CircuitOpenError` with a positive `retry_after`: between 0.05 and 1.0 seconds for a local breaker, so a rejected caller never retries at once. Admission errors still raise in `raise` mode. + +If the breaker's own bookkeeping fails after the wrapped function has returned, the error is logged and the function's result is returned. Bookkeeping errors never replace a result. + ## Sharing one breaker `@circuit_breaker(...)` gives the function its own breaker, exposed as `wrapper.breaker`. To **share one breaker across several functions** (they all hit the same service), create a `CircuitBreaker` and use the instance as the decorator: diff --git a/docs/features/resilience/http-clients.md b/docs/features/resilience/http-clients.md index f678c79..497a684 100644 --- a/docs/features/resilience/http-clients.md +++ b/docs/features/resilience/http-clients.md @@ -61,7 +61,7 @@ assert not should_retry("GET", {}, status=404) | `methods` | `IDEMPOTENT_METHODS` | Methods safe to repeat | | `retry_on` | `ConnectionError`, `TimeoutError`, `OSError` | Transport error types | | `retry_on_names` | httpx / requests / aiohttp class names | Matched along the exception's MRO, so the libraries are never imported | -| `respect_retry_after` | `True` | Use `Retry-After` as the exact wait | +| `respect_retry_after` | `True` | Use `Retry-After` as the wait (a lower bound, plus up to 10% jitter) | | `max_retry_after` | `60` | A longer `Retry-After` means: stop and hand back the response | | `budget` | `None` | A shared [`RetryBudget`](retry.md) | | `idempotency_header` | `"Idempotency-Key"` | Header that makes any method retryable (`None` disables) | @@ -183,7 +183,7 @@ async def put_item(session: aiohttp.ClientSession, item_id: int, data: dict): ## Retry-After -When a response carries `Retry-After` (seconds or an HTTP date) that value is the wait, exactly, with no backoff or jitter added. If it exceeds `max_retry_after` the server is asking for longer than you are willing to wait, so retrying stops and the response is returned for the caller to handle. +When a response carries `Retry-After` (seconds or an HTTP date) that value is a lower bound for the wait, with up to 10% jitter added so clients do not retry in lockstep. A value of zero waits 50 ms. The wait never exceeds `max_retry_after`. If it exceeds `max_retry_after` the server is asking for longer than you are willing to wait, so retrying stops and the response is returned for the caller to handle. ```python from python_wrap.http import HttpRetryPolicy, retry_delay @@ -193,7 +193,7 @@ class Resp: self.headers = {"Retry-After": value} policy = HttpRetryPolicy(max_retry_after=30) -assert retry_delay(Resp("5"), 1, policy) == 5.0 +assert 5.0 <= retry_delay(Resp("5"), 1, policy) <= 5.5 assert retry_delay(Resp("3600"), 1, policy) is None ``` diff --git a/docs/features/resilience/multi-process-breakers.md b/docs/features/resilience/multi-process-breakers.md index faf9084..420ab02 100644 --- a/docs/features/resilience/multi-process-breakers.md +++ b/docs/features/resilience/multi-process-breakers.md @@ -49,6 +49,9 @@ Behaviour matches `RedisBreakerState`: generation fencing so late results from b a cap on concurrent half-open trial calls, a trial deadline of `max(1s, recovery_timeout)` so a crashed probe cannot hold the slot, an optional failure `window`, and the totals in `.stats`. +A call rejected while half-open carries a `retry_after` equal to the time until the trial deadline, and at least 50 ms. +As with local breakers, a bookkeeping error after the wrapped call has returned is logged and the call's result is returned. + Notes: - Create the object in each process (or let it reconnect after fork: connections are reopened automatically when the diff --git a/docs/features/resilience/retry.md b/docs/features/resilience/retry.md index 272599d..90c1b3f 100644 --- a/docs/features/resilience/retry.md +++ b/docs/features/resilience/retry.md @@ -73,7 +73,7 @@ The wait before attempt `n + 1` is `min(delay * backoff ** (n - 1), max_delay) + | `retry_if` | `None` | Extra predicate on the exception; retry only if it returns `True`. May be `async def` for async functions. | | `retry_if_result` | `None` | Predicate on the return value; `True` means "retry". The last value is returned when retries run out. May be `async def` for async functions. | | `on_retry` | `None` | Called with a `RetryState` before each wait. May be async for async functions. Ordinary hook errors are logged and swallowed. | -| `delay_from` | `None` | Exception or rejected result → seconds or None: exact wait for this attempt (e.g. `Retry-After`). | +| `delay_from` | `None` | Exception or rejected result → seconds or None: wait for this attempt, with jitter and a floor (e.g. `Retry-After`). | | `budget` | `None` | A `RetryBudget` shared with other retried code, so retries stay a fraction of traffic. | | `logger` | package logger | Logger or logger name for the per-retry message. | | `log_level` | `WARNING` | Level of the per-retry message; `None` disables it. | @@ -270,7 +270,7 @@ assert stats is not None and stats.budget_exhausted > 0 ## Honouring Retry-After -Servers that answer 429 or 503 often say how long to wait. Pass `delay_from` a synchronous function that maps the exception or rejected result to a number of seconds, or to `None` to fall back to the normal backoff. A number is the exact wait for that attempt (no backoff, no jitter), still capped by `max_delay` and `max_time`. +Servers that answer 429 or 503 often say how long to wait. Pass `delay_from` a synchronous function that maps the exception or rejected result to a number of seconds, or to `None` to fall back to the normal backoff. A number is the wait for that attempt, not backoff: the hint is a lower bound, and up to 10% jitter is added so callers rejected together do not return at the same instant. A hint of zero waits 50 ms. The wait is still capped by `max_delay` and `max_time`. `retry_after_header` reads `.retry_after` or a `Retry-After` header on the object itself or its `.response` (seconds or an HTTP-date). It never raises, so it works with returned responses and `httpx.HTTPStatusError`/`requests.HTTPError` without importing those clients. The example uses a stand-in exception with the same shape: @@ -325,7 +325,7 @@ def request(): with fake_clock() as clock: assert request().status_code == 200 -assert clock.sleeps == [7.0] +assert len(clock.sleeps) == 1 and 7.0 <= clock.sleeps[0] <= 7.7 # hint + up to 10% jitter ``` For APIs with a body field, use diff --git a/docs/llms-full.txt b/docs/llms-full.txt index e893c0b..e5e2d5c 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -1239,7 +1239,7 @@ assert not llm_transient(APIStatusError(400, "content_policy_violation")) `llm_retry()` is a `retry` that retries only `llm_transient` errors. Waits double from 1 s (plus up to 0.5 s jitter) unless the provider sent `Retry-After` or `retry-after-ms`; -that wait is used exactly, capped at `max_delay` (60 s by default). A `RetryBudget` +that wait is a lower bound, with up to 10% jitter added, capped at `max_delay` (60 s by default). A `RetryBudget` (20 % of calls plus 5 retries per second) keeps an outage from multiplying your traffic. `presets.llm_client(name)` bundles it into a `Policy`: @@ -1276,7 +1276,7 @@ def complete(prompt: str) -> dict[str, object]: with fake_clock() as clock: complete("Summarise this") -assert clock.sleeps == [2.0] # the provider's Retry-After +assert len(clock.sleeps) == 1 and 2.0 <= clock.sleeps[0] <= 2.2 # the provider's Retry-After, plus up to 10% jitter assert chat.explain().findings == () ``` @@ -4420,7 +4420,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm - `python_wrap.WebhookAlerter`: `WebhookAlerter(url: str, *, format: str = 'json', on: Iterable[str | CircuitState] = ('open',), cooldown: float = 300.0, timeout: float = 5.0, sender: Sender | None = None, include_recovery: bool = True, context: Mapping[str, Any] | None = None)` Post a chat message when a circuit breaker reaches a chosen state. - `python_wrap.__version__` - Constant: '0.4.0' + Constant: '0.4.1' - `python_wrap.ainvalidate_tags`: `ainvalidate_tags(*names: str, client: Any = None) -> None` `invalidate_tags` for ``redis.asyncio`` clients (amemoize with AsyncRedisStore). - `python_wrap.amap_iter`: `amap_iter(fn: Callable[[T], Awaitable[R]], items: Iterable[T] | AsyncIterable[T], *, limit: int, ordered: bool = True, return_exceptions: bool = False) -> AsyncGenerator[Any, None]` @@ -4820,7 +4820,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm - `python_wrap.decorators` Compatibility module: v0.1 imported everything from ``python_wrap.decorators``. - `python_wrap.decorators.__version__` - Constant: '0.4.0' + Constant: '0.4.1' - `python_wrap.devtools` Developer tools: deprecation warnings, mock data and decorator composition. - `python_wrap.django` @@ -5134,7 +5134,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm - `python_wrap.policies.RedisSource`: `RedisSource(client: Any, key: str = 'python-wrap:policies')` One Redis string key holding the JSON mapping, shared by every replica. - `python_wrap.policies.Watch`: `Watch(registry: PolicyRegistry, source: PolicySource, interval: float)` - A running `PolicyRegistry.watch`; ``stop()`` ends it. Does not survive a fork. + A running `PolicyRegistry.watch`; ``stop()`` ends it. - `python_wrap.policy.ROLES` Constant: ('observe', 'validate', 'fallback', 'cache', 'limiter', 'bulkhead', 'breaker', 'retry', 'timeout', 'guard') - `python_wrap.predicates` diff --git a/docs/project/stability.md b/docs/project/stability.md index ce62e67..9d72ba7 100644 --- a/docs/project/stability.md +++ b/docs/project/stability.md @@ -45,7 +45,7 @@ graduates to stable core by being added to the table above (and to the stability ### Graduation -A provisional module graduates when all three hold: +A provisional module graduates when all four hold: 1. **Soak.** A multi-process soak (`benchmarks/soak.py --processes N --redis-url ...`) ran for at least an hour against the real backend with no leak, no stuck lease and @@ -53,6 +53,9 @@ A provisional module graduates when all three hold: 2. **Live CI.** Its backends run in CI against the real service (Redis, PostgreSQL, SQL Server through pymssql and pyodbc), not only against fakes. 3. **One quiet minor release.** It went through one minor release with no breaking change. +4. **No fake-only coverage.** No shared feature is covered by fakes only: each of its + scripts and shared code paths has at least one test against the real service. Every + Lua script must have a live test; `tests/test_stability.py` enforces this by name. | Module | Target | Status | | --- | --- | --- | diff --git a/examples/llm_client.py b/examples/llm_client.py index 5f6be56..4c6a185 100644 --- a/examples/llm_client.py +++ b/examples/llm_client.py @@ -80,7 +80,7 @@ def ask(question: str) -> dict[str, Any]: with fake_clock() as clock: answer = ask("What is a circuit breaker?") - assert clock.sleeps == [3.0], clock.sleeps # honoured Retry-After + assert len(clock.sleeps) == 1 and 3.0 <= clock.sleeps[0] <= 3.3, clock.sleeps # Retry-After, plus up to 10% jitter provider.failures.append(ProviderError(400, "content_policy_violation")) try: ask("something the provider refuses") diff --git a/examples/projects/support_agent/tests/test_agent.py b/examples/projects/support_agent/tests/test_agent.py index 7d17cf9..e3d78c5 100644 --- a/examples/projects/support_agent/tests/test_agent.py +++ b/examples/projects/support_agent/tests/test_agent.py @@ -121,7 +121,7 @@ def test_both_models_rate_limited_retries_after_retry_after(make_app: MakeApp, c result = app.handle(TICKET, run_id="t-1") assert result.llm_calls == 4 - assert clock.sleeps[0] == 7.0 # the provider's Retry-After, honoured, instantly + assert 7.0 <= clock.sleeps[0] <= 7.7 # the provider's Retry-After, honoured, plus up to 10% jitter assert len(app.payments.refunds) == 1 diff --git a/examples/resilient_llm_client.py b/examples/resilient_llm_client.py index d80fd34..630b6ad 100644 --- a/examples/resilient_llm_client.py +++ b/examples/resilient_llm_client.py @@ -35,7 +35,7 @@ def ask(question: str) -> Any: with fake_clock() as clock: answer = ask("Say hi") - assert clock.sleeps == [2.0], clock.sleeps # the provider's Retry-After + assert len(clock.sleeps) == 1 and 2.0 <= clock.sleeps[0] <= 2.2, clock.sleeps # the provider's Retry-After, plus up to 10% jitter assert answer.text == "hi" and provider.call_count == 2 assert spend.spent().tokens > 0 print("1. retried a 429 after Retry-After 2 s:", answer.text) From aac8f473ac5796e1da2cb6c3341e42e3ba755cf1 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Thu, 26 Nov 2026 21:20:42 +0200 Subject: [PATCH 03/38] feat: warn about the 0.5.0 retry default change; doctor PW024 and PW025 - A bare retry or retrying() with no delay, backoff or jitter emits one FutureWarning per process that names the 0.5.0 defaults. - Doctor PW024 (no backoff or jitter on a retry) runs without --multiprocess. - Doctor PW025 (warning): a retry on every Exception with no retry_if or retry_if_result. --- .../features/resilience/presets-and-doctor.md | 5 +- docs/features/resilience/retry.md | 13 ++- docs/llms-full.txt | 5 +- src/python_wrap/doctor.py | 19 ++++- src/python_wrap/retry.py | 34 +++++++- tests/e2e/test_e2e_cli_mcp.py | 2 +- tests/test_doctor.py | 52 +++++++++--- tests/test_mcp.py | 4 +- tests/test_retry_schedules.py | 83 +++++++++++++++++++ 9 files changed, 193 insertions(+), 24 deletions(-) diff --git a/docs/features/resilience/presets-and-doctor.md b/docs/features/resilience/presets-and-doctor.md index b717664..0c7de7d 100644 --- a/docs/features/resilience/presets-and-doctor.md +++ b/docs/features/resilience/presets-and-doctor.md @@ -120,7 +120,7 @@ assert "PW006" in [finding.code for finding in report.findings] # timeout outsi ### Findings -The doctor reports codes PW001 to PW019 (the table lists them by group, not strictly in numeric order). +The doctor reports codes PW001 to PW025 (the table lists them by group, not strictly in numeric order). | Code | Severity | Meaning | | --- | --- | --- | @@ -145,7 +145,8 @@ The doctor reports codes PW001 to PW019 (the table lists them by group, not stri | PW021 | warning | An `mcp_guard` retries every tool (`retry=` without `retry_tools=`): a retried MCP write may run twice. | | PW022 | warning | `memoize` with a shared store and no `key=` on a function with dict, set or unannotated parameters: equal arguments are keyed alike in every process, but an unsupported object raises `TypeError`. | | PW023 | warning | `python_wrap.celery.check_visibility`: a blocking limiter, unbounded bulkhead queue or retry `max_time` can outlive the broker's visibility timeout, so the broker delivers the task again while it still runs. | -| PW024 | warning | With `--multiprocess`, a retry layer has no backoff or jitter; workers may retry together. Use `backoff=2, jitter="full"`. | +| PW024 | warning | A retry layer has no backoff or jitter (`backoff=1` or no `jitter`): callers that fail together retry together, and with `--multiprocess` every worker does. Use `backoff=2, jitter="full"`. | +| PW025 | warning | A retry on every `Exception` with neither `retry_if=` nor `retry_if_result=`: programming errors and non-transient failures are retried. Narrow `on=` or add a predicate. Fires together with PW003, which also covers a broad `on=` with only `retry_if_result=`. | | PW018 | warning | A python-wrap LLM retry wraps an SDK client (`llm_retry(client=...)`) whose own retries are still on: attempts multiply (4 x 3 = 12). See [OpenAI and Anthropic SDK clients](../ai/openai-anthropic.md#doctor-checks). | | PW019 | warning | A retry wraps a streamed LLM call (`stream_timeout`) without `resume_safe`: a replay after output started repeats text and half-done tool calls. | diff --git a/docs/features/resilience/retry.md b/docs/features/resilience/retry.md index 90c1b3f..9832039 100644 --- a/docs/features/resilience/retry.md +++ b/docs/features/resilience/retry.md @@ -44,7 +44,10 @@ For several workers, set a project default before decorating functions: `configure(retry={"backoff": 2, "jitter": "full", "max_delay": 30})`. `jitter="full"` chooses any wait between zero and the capped backoff; `"equal"` chooses between half and all of it. A numeric jitter still adds up to that many -seconds. Bare retry defaults stay unchanged for this release. +seconds. + +!!! warning "Bare `@retry` defaults change in 0.5.0" + A bare `@retry` (or `retrying()`) with no `delay`, `backoff` or `jitter` waits 1 s, three times, with no jitter. This release emits one `FutureWarning` per process saying so. In 0.5.0 the fallback becomes `backoff=2`, `jitter="equal"` and `max_delay=30`. To keep today's behaviour, pass `delay=`, `backoff=` or `jitter=` explicitly, or set the values with `configure(retry={...})`. An explicit `delays=` schedule does not warn. The `doctor` reports PW024 (no backoff or jitter) and PW025 (retries every `Exception` with no `retry_if=` or `retry_if_result=`) for such retries. ## When to use it @@ -496,6 +499,14 @@ Sentry breadcrumbs so an error report shows what happened before the failure. Set `max_attempts`, `delay`, `backoff`, `max_delay`, `jitter`, `max_time`, `log_level` and `budget` once for the whole project with `python_wrap.config.configure(retry={...})`. See [Configuration](../configuration.md). +To use the 0.5.0 timing defaults today: + +```python +configure(retry={"backoff": 2, "jitter": "equal", "max_delay": 30}) +``` + +Setting any of `delay`, `backoff` or `jitter` here also silences the default-change warning. + ## Logging Each retry logs one message at `log_level` (default `WARNING`) on `logger`. Use `log_level=logging.INFO` to quiet it, `log_level=None` to turn it off, and `log_exc_info=True` to attach the traceback. diff --git a/docs/llms-full.txt b/docs/llms-full.txt index e5e2d5c..12826a8 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -3702,7 +3702,7 @@ assert "PW006" in [finding.code for finding in report.findings] # timeout outsi #### Findings -The doctor reports codes PW001 to PW019 (the table lists them by group, not strictly in numeric order). +The doctor reports codes PW001 to PW025 (the table lists them by group, not strictly in numeric order). | Code | Severity | Meaning | | --- | --- | --- | @@ -3727,7 +3727,8 @@ The doctor reports codes PW001 to PW019 (the table lists them by group, not stri | PW021 | warning | An `mcp_guard` retries every tool (`retry=` without `retry_tools=`): a retried MCP write may run twice. | | PW022 | warning | `memoize` with a shared store and no `key=` on a function with dict, set or unannotated parameters: equal arguments are keyed alike in every process, but an unsupported object raises `TypeError`. | | PW023 | warning | `python_wrap.celery.check_visibility`: a blocking limiter, unbounded bulkhead queue or retry `max_time` can outlive the broker's visibility timeout, so the broker delivers the task again while it still runs. | -| PW024 | warning | With `--multiprocess`, a retry layer has no backoff or jitter; workers may retry together. Use `backoff=2, jitter="full"`. | +| PW024 | warning | A retry layer has no backoff or jitter (`backoff=1` or no `jitter`): callers that fail together retry together, and with `--multiprocess` every worker does. Use `backoff=2, jitter="full"`. | +| PW025 | warning | A retry on every `Exception` with neither `retry_if=` nor `retry_if_result=`: programming errors and non-transient failures are retried. Narrow `on=` or add a predicate. Fires together with PW003, which also covers a broad `on=` with only `retry_if_result=`. | | PW018 | warning | A python-wrap LLM retry wraps an SDK client (`llm_retry(client=...)`) whose own retries are still on: attempts multiply (4 x 3 = 12). See [OpenAI and Anthropic SDK clients](../ai/openai-anthropic.md#doctor-checks). | | PW019 | warning | A retry wraps a streamed LLM call (`stream_timeout`) without `resume_safe`: a replay after output started repeats text and half-done tool calls. | diff --git a/src/python_wrap/doctor.py b/src/python_wrap/doctor.py index 792895b..c5e7d8b 100644 --- a/src/python_wrap/doctor.py +++ b/src/python_wrap/doctor.py @@ -259,13 +259,14 @@ def _check( for layer in retries: settings = layer.settings attempts, max_time = settings.get("max_attempts"), settings.get("max_time") - if multiprocess and (settings.get("backoff") == 1 or not settings.get("jitter")): + if settings.get("backoff") == 1 or not settings.get("jitter"): found.append( Finding( "PW024", "warning", - "retry across workers has no backoff or jitter: synchronized retries can " - "overload a recovering dependency. Use backoff=2, jitter='full'.", + "retry has no backoff or jitter: callers that fail together retry " + "together, and under --multiprocess every worker does, which can overload " + "a recovering dependency. Use backoff=2, jitter='full'.", ) ) if attempts is None and max_time is None: @@ -300,6 +301,18 @@ def _check( "are retried too. Narrow on= or add retry_if=, for example db_transient.", ) ) + if broad and not ( + settings.get("retry_if") or settings.get("retry_if_result") + ): + found.append( + Finding( + "PW025", + "warning", + "retry on every Exception with no retry_if= or retry_if_result=: programming " + "errors and non-transient failures are retried. Narrow on= or add a " + "predicate, for example retry_if=db_transient.", + ) + ) if not settings.get("budget"): found.append( Finding( diff --git a/src/python_wrap/retry.py b/src/python_wrap/retry.py index 1cb11d9..b803d14 100644 --- a/src/python_wrap/retry.py +++ b/src/python_wrap/retry.py @@ -595,8 +595,38 @@ def _parse_hint(value: Any) -> float | None: return max(float(value), 0.0) -def _resolve_defaults(**given: Any) -> dict[str, Any]: +#: Set once the default-change FutureWarning has been emitted in this process. +_DEFAULT_CHANGE_WARNED = False +_TIMING_ARGUMENTS = ("delay", "backoff", "jitter") + + +def _warn_default_change(given: dict[str, Any], schedule: bool) -> None: + """Warn once per process when a call relies on the timing defaults that change in 0.5.0. + + An explicit ``delays=`` schedule replaces those defaults, so it never warns. + """ + global _DEFAULT_CHANGE_WARNED + if _DEFAULT_CHANGE_WARNED or schedule: + return + if any(given.get(name, _UNSET) is not _UNSET for name in _TIMING_ARGUMENTS): + return + if any( + config.retry_default(name, _UNSET, _MISSING) is not _MISSING for name in _TIMING_ARGUMENTS + ): + return + _DEFAULT_CHANGE_WARNED = True + warnings.warn( + "bare @retry waits 1 s, three times, with no jitter; the defaults change to " + "backoff=2, jitter='equal', max_delay=30 in 0.5.0; pass them explicitly or use " + "configure(retry=...) to keep the current behaviour", + FutureWarning, + stacklevel=4, + ) + + +def _resolve_defaults(*, schedule: bool = False, **given: Any) -> dict[str, Any]: """Fill arguments left unset from `python_wrap.config` (read at decoration time).""" + _warn_default_change(given, schedule) return {k: config.retry_default(k, v, _RETRY_FALLBACK[k]) for k, v in given.items()} @@ -1148,6 +1178,7 @@ def retry( ... def fetch() -> str: ... """ ds = _resolve_defaults( + schedule=delays is not None, max_attempts=max_attempts, delay=delay, backoff=backoff, @@ -1484,6 +1515,7 @@ def retrying( ... do_work() # doctest: +SKIP """ ds = _resolve_defaults( + schedule=delays is not None, max_attempts=max_attempts, delay=delay, backoff=backoff, diff --git a/tests/e2e/test_e2e_cli_mcp.py b/tests/e2e/test_e2e_cli_mcp.py index 642fcec..2ea2bed 100644 --- a/tests/e2e/test_e2e_cli_mcp.py +++ b/tests/e2e/test_e2e_cli_mcp.py @@ -20,7 +20,7 @@ catalog = policy( name="catalog", - retry=retry(max_attempts=3, on=ConnectionError, budget=RetryBudget()), + retry=retry(max_attempts=3, on=ConnectionError, budget=RetryBudget(), backoff=2, jitter="full"), timeout=timeout(2), ) charge = policy(name="charge", retry=retry(max_attempts=3, on=ConnectionError), timeout=timeout(5)) diff --git a/tests/test_doctor.py b/tests/test_doctor.py index 8a67f31..a112bfe 100644 --- a/tests/test_doctor.py +++ b/tests/test_doctor.py @@ -41,7 +41,9 @@ def test_explain_lists_layers_in_canonical_order_with_settings(): stack = policy( name="io", timeout=timeout(2), - retry=retry(max_attempts=3, on=ConnectionError, budget=budget, max_time=30), + retry=retry( + max_attempts=3, on=ConnectionError, budget=budget, max_time=30, backoff=2, jitter="full" + ), breaker=CircuitBreaker(failure_threshold=4, name="io"), bulkhead=Bulkhead(5), limiter=RateLimiter(10, 1, name="io"), @@ -68,17 +70,34 @@ def test_unbounded_retry_is_an_error(): assert "PW001" in codes(report) -def test_multiprocess_retry_warns_without_backoff_or_jitter(): +def test_pw024_without_multiprocess_flag(): stack = policy(retry=retry(on=OSError)) - assert "PW024" not in codes(stack.explain()) + assert "PW024" in codes(stack.explain()) assert "PW024" in codes(explain(stack, multiprocess=True)) safe = policy(retry=retry(on=OSError, backoff=2, jitter="full")) assert "PW024" not in codes(explain(safe, multiprocess=True)) + assert "PW024" not in codes(safe.explain()) + + +def test_pw025_broad_exception(): + report = explain(policy(retry=retry(on=Exception, max_attempts=3))) + assert "PW025" in codes(report) + assert "PW003" in codes(report) + narrow = explain(policy(retry=retry(on=OSError, max_attempts=3))) + assert "PW025" not in codes(narrow) + + +def test_pw025_silent_with_retry_if(): + stack = policy(retry=retry(on=Exception, retry_if=lambda exc: isinstance(exc, OSError))) + assert "PW025" not in codes(stack.explain()) + by_result = policy(retry=retry(on=Exception, retry_if_result=lambda value: value is None)) + assert "PW025" not in codes(by_result.explain()) def test_non_idempotent_retry_is_an_error_only_when_declared(): stack = policy( - retry=retry(max_attempts=3, on=OSError, budget=RetryBudget()), timeout=timeout(1) + retry=retry(max_attempts=3, on=OSError, budget=RetryBudget(), backoff=2, jitter="full"), + timeout=timeout(1), ) assert stack.explain().ok report = stack.explain(idempotent=False) @@ -97,7 +116,14 @@ def test_warnings_for_missing_timeout_broad_exceptions_and_budget(): def test_timeout_not_shorter_than_retry_budget(): report = explain( policy( - retry=retry(max_attempts=3, max_time=5, on=OSError, budget=RetryBudget()), + retry=retry( + max_attempts=3, + max_time=5, + on=OSError, + budget=RetryBudget(), + backoff=2, + jitter="full", + ), timeout=timeout(5), ) ) @@ -108,7 +134,7 @@ def test_misplaced_layers_in_outer_inner_are_detected(): # A breaker put *inside* the retry via inner= counts every attempt. report = explain( policy( - retry=retry(max_attempts=2, on=OSError, budget=RetryBudget()), + retry=retry(max_attempts=2, on=OSError, budget=RetryBudget(), backoff=2, jitter="full"), timeout=timeout(1), inner=CircuitBreaker(), ) @@ -121,8 +147,8 @@ def test_duplicate_retry_layers_multiply_attempts(): report = explain( policy( retry=[ - retry(max_attempts=3, on=OSError, budget=RetryBudget()), - retry(max_attempts=3, on=OSError, budget=RetryBudget()), + retry(max_attempts=3, on=OSError, budget=RetryBudget(), backoff=2, jitter="full"), + retry(max_attempts=3, on=OSError, budget=RetryBudget(), backoff=2, jitter="full"), ], timeout=timeout(1), ) @@ -131,7 +157,7 @@ def test_duplicate_retry_layers_multiply_attempts(): def test_doctor_walks_hand_stacked_decorators(signals_usable_for_layout): - @retry(max_attempts=3, on=ConnectionError, budget=RetryBudget()) + @retry(max_attempts=3, on=ConnectionError, budget=RetryBudget(), backoff=2, jitter="full") @timeout(2) @memoize def fetch(x: int) -> int: @@ -148,11 +174,11 @@ def test_doctor_flags_retry_outside_breaker_order(signals_usable_for_layout): breaker = CircuitBreaker(name="b") @breaker - @retry(max_attempts=2, on=OSError, budget=RetryBudget()) + @retry(max_attempts=2, on=OSError, budget=RetryBudget(), backoff=2, jitter="full") @timeout(1) def ok() -> None: ... - @retry(max_attempts=2, on=OSError, budget=RetryBudget()) + @retry(max_attempts=2, on=OSError, budget=RetryBudget(), backoff=2, jitter="full") @breaker @timeout(1) def misordered() -> None: ... @@ -162,7 +188,7 @@ def misordered() -> None: ... def test_doctor_on_async_and_plain_functions(): - @retry(max_attempts=2, on=OSError, budget=RetryBudget()) + @retry(max_attempts=2, on=OSError, budget=RetryBudget(), backoff=2, jitter="full") @timeout(1) async def fetch() -> int: return 1 @@ -371,7 +397,7 @@ def not_a_method(x: int) -> int: # type: ignore[misc] def test_pw011_found_under_other_layers(): class Repo: - @retry(max_attempts=2, on=ConnectionError, budget=RetryBudget()) + @retry(max_attempts=2, on=ConnectionError, budget=RetryBudget(), backoff=2, jitter="full") @timeout(1) @memoize def load(self, x: int) -> int: diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 5a1d2d8..f1905b0 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -34,7 +34,9 @@ safe = policy( name="safe", - retry=retry(max_attempts=3, on=ConnectionError, budget=RetryBudget()), + retry=retry( + max_attempts=3, on=ConnectionError, budget=RetryBudget(), backoff=2, jitter="full" + ), timeout=timeout(2), ) charge = policy(name="charge", retry=retry(max_attempts=3, on=ConnectionError)) diff --git a/tests/test_retry_schedules.py b/tests/test_retry_schedules.py index 1a79de2..20d58a0 100644 --- a/tests/test_retry_schedules.py +++ b/tests/test_retry_schedules.py @@ -3,13 +3,16 @@ from __future__ import annotations import asyncio +import importlib import random +import warnings from typing import Any import pytest from conftest import FakeClock from python_wrap import deadline, retry, retrying +from python_wrap.config import configured @pytest.mark.parametrize("inline", [False, True]) @@ -118,3 +121,83 @@ async def job() -> None: task.cancel() with pytest.raises(asyncio.CancelledError): await task + + +@pytest.fixture +def fresh_default_warning(monkeypatch: pytest.MonkeyPatch) -> None: + """Reset the once-per-process default-change flag so each test sees the first warning.""" + module = importlib.import_module("python_wrap.retry") + monkeypatch.setattr(module, "_DEFAULT_CHANGE_WARNED", False) + + +def _default_change_warnings( + caught: list[warnings.WarningMessage], +) -> list[warnings.WarningMessage]: + return [w for w in caught if issubclass(w.category, FutureWarning)] + + +@pytest.mark.usefixtures("fresh_default_warning") +def test_bare_retry_warns_about_default_change() -> None: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("default") + + @retry + def first() -> None: ... + + @retry(max_attempts=5) + def second() -> None: ... + + found = _default_change_warnings(caught) + assert len(found) == 1 + message = str(found[0].message) + assert "0.5.0" in message and "backoff=2" in message and "jitter='equal'" in message + assert found[0].filename == __file__ + + +@pytest.mark.usefixtures("fresh_default_warning") +def test_bare_retry_warns_once_per_process() -> None: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + for _ in range(3): + + @retry + def bare() -> None: ... + + assert len(_default_change_warnings(caught)) == 1 + + +@pytest.mark.usefixtures("fresh_default_warning") +def test_explicit_arguments_do_not_warn() -> None: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + + @retry(delay=0.5) + def with_delay() -> None: ... + + @retry(backoff=1) + def with_backoff() -> None: ... + + @retry(jitter="full") + def with_jitter() -> None: ... + + @retry(delays=[1, 2]) + def with_schedule() -> None: ... + + with configured(retry={"delay": 2.0}): + + @retry + def configured_delay() -> None: ... + + assert _default_change_warnings(caught) == [] + + +@pytest.mark.usefixtures("fresh_default_warning") +def test_configured_retry_defaults_do_not_warn() -> None: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + with configured(retry={"backoff": 2, "jitter": "equal", "max_delay": 30}): + + @retry + def bare_with_new_defaults() -> None: ... + + assert _default_change_warnings(caught) == [] From 6863adddb1b8f7ad50d8c6b9df63899980664d34 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Thu, 26 Nov 2026 21:27:08 +0200 Subject: [PATCH 04/38] feat: cache codec shortcuts, visible implicit-pickle warning, doctor PW026 - configure(cache_codec="json") and configure(cache_codec=("signed-pickle", ENV_NAME)) select the shared-cache codec; the secret is read from the named environment variable when each store is built. Adds stores.resolve_codec. - The implicit plain-pickle warning on RedisStore and AsyncRedisStore is a FutureWarning that names the 0.5.0 default change. - Doctor PW026 (warning) for a memoized function on a shared store that uses plain pickle. --- .../caching/stores-and-credentials.md | 36 ++++- docs/features/configuration.md | 2 +- .../features/resilience/presets-and-doctor.md | 1 + docs/llms-full.txt | 3 + docs/project/threat-model.md | 6 +- src/python_wrap/async_cache.py | 18 ++- src/python_wrap/config.py | 30 ++++- src/python_wrap/doctor.py | 32 ++++- src/python_wrap/stores.py | 59 ++++++++- tests/test_cache_codec.py | 123 ++++++++++++++++++ tests/test_doctor.py | 75 +++++++++++ 11 files changed, 349 insertions(+), 36 deletions(-) create mode 100644 tests/test_cache_codec.py diff --git a/docs/features/caching/stores-and-credentials.md b/docs/features/caching/stores-and-credentials.md index 1d49622..873ba26 100644 --- a/docs/features/caching/stores-and-credentials.md +++ b/docs/features/caching/stores-and-credentials.md @@ -26,11 +26,37 @@ def price(sku: str) -> float: Keys are hashed by default. `key_format=` can provide an external string key when other code needs to seed or inspect entries. `version=` isolates a new deployment's -entries. Implicit pickle is deprecated; pass `signed_pickle_codec(secret)` or -`json_codec()` from `python_wrap.stores`. `configure(cache_codec=(dumps, loads))` -sets the default for both sync and async Redis stores. Entries are opaque tuples, -so custom serializers must round-trip them. Invalid signatures are misses and emit -`cache.rejected` with `reason="signature"` before anything is unpickled. +entries. Entries are opaque tuples, so custom serializers must round-trip them. +Invalid signatures are misses and emit `cache.rejected` with `reason="signature"` +before anything is unpickled. + +### Codecs + +Choose the codec explicitly. The options: + +| Choice | Use when | +| --- | --- | +| `dumps=json_codec()[0], loads=json_codec()[1]` | Results are JSON-shaped (dicts, lists, strings, numbers). Safe on shared Redis. | +| `dumps, loads = signed_pickle_codec(secret)` | Python objects must round-trip. The secret is passed in code. | +| `configure(cache_codec="json")` | One line sets JSON for every `RedisStore` and `AsyncRedisStore` built without `dumps=`/`loads=`. | +| `configure(cache_codec=("signed-pickle", "APP_CACHE_SECRET"))` | Same, with the signing secret read from the named environment variable when each store is built. The variable must be set and at least 16 bytes, or `ValueError` names it. | +| `configure(cache_codec=(dumps, loads))` | A project-wide custom pair. | + + +```python +from python_wrap import configure + +# APP_CACHE_SECRET is set in the deployment environment, never in code. +configure(cache_codec=("signed-pickle", "APP_CACHE_SECRET")) +``` + +A store built with no codec and no `cache_codec` default still uses plain pickle, which +is the implicit default. It emits a `FutureWarning` (visible under the default warning +filters) that names the fix. **In 0.5.0 the implicit default becomes JSON**, so a +store that relies on pickle must name a codec before then. `doctor` reports a `memoize` +on a store with plain pickle as PW026. Until 0.5.0, entries written with plain pickle +still load; after it, pickle entries fail to decode and are treated as misses. Use +`version=` to retire old entries at once. ### Failure modes diff --git a/docs/features/configuration.md b/docs/features/configuration.md index 6828579..27e9b16 100644 --- a/docs/features/configuration.md +++ b/docs/features/configuration.md @@ -57,7 +57,7 @@ dependency during an incident. See [named policies](resilience/named-policies.md | `redact_extra` | Names **added** to the redaction list (the built-ins stay), for `log_args` and `audit`. | | `backend_errors` | Default `on_backend_error` for shared backends: `"raise"`, `"local"` or `"allow"`. | | `shared` | Redis client or `SharedBackends` used by presets and `PolicyRegistry` when a policy names no backend. | -| `cache_codec` | `(dumps, loads)` pair, the default codec for sync and async Redis stores. | +| `cache_codec` | Default codec for sync and async Redis stores built without `dumps=`/`loads=`: `"json"`, `("signed-pickle", ENV_NAME)` (secret read from that environment variable) or a `(dumps, loads)` pair. | Each key you pass replaces that key as a whole (`retry={...}` replaces the previous retry defaults); keys you don't mention are untouched. Unknown keys raise `TypeError` with a hint: diff --git a/docs/features/resilience/presets-and-doctor.md b/docs/features/resilience/presets-and-doctor.md index 0c7de7d..f8f5db2 100644 --- a/docs/features/resilience/presets-and-doctor.md +++ b/docs/features/resilience/presets-and-doctor.md @@ -147,6 +147,7 @@ The doctor reports codes PW001 to PW025 (the table lists them by group, not stri | PW023 | warning | `python_wrap.celery.check_visibility`: a blocking limiter, unbounded bulkhead queue or retry `max_time` can outlive the broker's visibility timeout, so the broker delivers the task again while it still runs. | | PW024 | warning | A retry layer has no backoff or jitter (`backoff=1` or no `jitter`): callers that fail together retry together, and with `--multiprocess` every worker does. Use `backoff=2, jitter="full"`. | | PW025 | warning | A retry on every `Exception` with neither `retry_if=` nor `retry_if_result=`: programming errors and non-transient failures are retried. Narrow `on=` or add a predicate. Fires together with PW003, which also covers a broad `on=` with only `retry_if_result=`. | +| PW026 | warning | `memoize` with a shared store that uses plain pickle (the implicit default, or `pickle.dumps`): anyone who can write the namespace can run code in every reader. Pass `dumps=`/`loads=` (for example `json_codec()`) or `configure(cache_codec="json")`. See [Shared caches](../caching/stores-and-credentials.md#codecs). | | PW018 | warning | A python-wrap LLM retry wraps an SDK client (`llm_retry(client=...)`) whose own retries are still on: attempts multiply (4 x 3 = 12). See [OpenAI and Anthropic SDK clients](../ai/openai-anthropic.md#doctor-checks). | | PW019 | warning | A retry wraps a streamed LLM call (`stream_timeout`) without `resume_safe`: a replay after output started repeats text and half-done tool calls. | diff --git a/docs/llms-full.txt b/docs/llms-full.txt index 12826a8..5d2e974 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -3729,6 +3729,7 @@ The doctor reports codes PW001 to PW025 (the table lists them by group, not stri | PW023 | warning | `python_wrap.celery.check_visibility`: a blocking limiter, unbounded bulkhead queue or retry `max_time` can outlive the broker's visibility timeout, so the broker delivers the task again while it still runs. | | PW024 | warning | A retry layer has no backoff or jitter (`backoff=1` or no `jitter`): callers that fail together retry together, and with `--multiprocess` every worker does. Use `backoff=2, jitter="full"`. | | PW025 | warning | A retry on every `Exception` with neither `retry_if=` nor `retry_if_result=`: programming errors and non-transient failures are retried. Narrow `on=` or add a predicate. Fires together with PW003, which also covers a broad `on=` with only `retry_if_result=`. | +| PW026 | warning | `memoize` with a shared store that uses plain pickle (the implicit default, or `pickle.dumps`): anyone who can write the namespace can run code in every reader. Pass `dumps=`/`loads=` (for example `json_codec()`) or `configure(cache_codec="json")`. See [Shared caches](../caching/stores-and-credentials.md#codecs). | | PW018 | warning | A python-wrap LLM retry wraps an SDK client (`llm_retry(client=...)`) whose own retries are still on: attempts multiply (4 x 3 = 12). See [OpenAI and Anthropic SDK clients](../ai/openai-anthropic.md#doctor-checks). | | PW019 | warning | A retry wraps a streamed LLM call (`stream_timeout`) without `resume_safe`: a replay after output started repeats text and half-done tool calls. | @@ -5200,6 +5201,8 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm State safety: `revert_on_failure` and transactions. - `python_wrap.stores` Optional Redis cache adapter. The caller supplies a client; redis is not imported. +- `python_wrap.stores.resolve_codec`: `resolve_codec(value: Any) -> tuple[Callable[[Any], bytes], Callable[[bytes], Any]]` + Turn a configured codec into a ``(dumps, loads)`` pair. - `python_wrap.stores.signed_pickle_codec`: `signed_pickle_codec(secret: bytes) -> tuple[Callable[[Any], bytes], Callable[[bytes], Any]]` Authenticate pickle bytes before loading them; keep the signing key private. - `python_wrap.switches` diff --git a/docs/project/threat-model.md b/docs/project/threat-model.md index bb1b218..bce5b08 100644 --- a/docs/project/threat-model.md +++ b/docs/project/threat-model.md @@ -27,7 +27,9 @@ round-trip. Unpickling attacker-controlled bytes executes code, so: - For shared or less-trusted Redis instances pass `json_codec()` from `python_wrap.stores` (JSON-shaped results only), or `signed_pickle_codec(secret)` if Python objects must round-trip. A bad signature is a cache miss and emits `cache.rejected` before unpickling. - `configure(cache_codec=...)` sets the project default; `version=` isolates deployments. + `configure(cache_codec="json")` or `configure(cache_codec=("signed-pickle", ENV_NAME))` + sets the project default; `version=` isolates deployments. The implicit default is plain + pickle until 0.5.0 (a `FutureWarning`, doctor PW026). - Keys are hashed (`sha256` of a pickle of the arguments, **dump only**), so a cache key never reveals arguments and never loads data. @@ -156,7 +158,7 @@ Regression tests: `tests/test_genai.py`, `tests/test_redaction.py`. ## Accepted risks - `RedisStore`/`AsyncRedisStore` still default to pickle for compatibility, with a - `DeprecationWarning` when the default is implicit. Use signed pickle or JSON for + `FutureWarning` when the default is implicit; the default becomes JSON in 0.5.0. Use signed pickle or JSON for a shared Redis namespace. - `PW_CHAOS` and policy files may name an exception as `module:Class`; resolving it imports that module. These are deployment configuration, never request input, and anything that diff --git a/src/python_wrap/async_cache.py b/src/python_wrap/async_cache.py index 520af7d..8c0cb29 100644 --- a/src/python_wrap/async_cache.py +++ b/src/python_wrap/async_cache.py @@ -46,7 +46,13 @@ _tag_versions, _ttl_seconds, ) -from python_wrap.stores import KEY_FORMAT, InvalidSignature, json_codec +from python_wrap.stores import ( + IMPLICIT_PICKLE_WARNING, + KEY_FORMAT, + InvalidSignature, + json_codec, + resolve_codec, +) __all__ = [ "AsyncCacheStore", @@ -210,15 +216,13 @@ def __init__( if codec is None: import warnings - warnings.warn( - "implicit pickle cache codec is deprecated; pass a codec", - DeprecationWarning, - stacklevel=2, - ) + warnings.warn(IMPLICIT_PICKLE_WARNING, FutureWarning, stacklevel=2) codec = (pickle.dumps, pickle.loads) - dumps, loads = codec + dumps, loads = resolve_codec(codec) self.client, self.prefix = client, prefix + (f"v{version}:" if version else "") self.dumps, self.loads = dumps or pickle.dumps, loads or pickle.loads + # Plain pickle on a shared store: doctor reports it (PW026). + self.implicit_pickle = self.dumps is pickle.dumps self.key_format, self.fail_open = key_format, fail_open self._monitor = BackendMonitor( "cache", prefix, "allow" if fail_open else "raise", retry_backend_after diff --git a/src/python_wrap/config.py b/src/python_wrap/config.py index ab9d41b..7c6d5da 100644 --- a/src/python_wrap/config.py +++ b/src/python_wrap/config.py @@ -52,6 +52,24 @@ def _names(value: Any, key: str) -> tuple[str, ...]: return names +def _validate_codec(value: Any) -> Any: + """Normalise ``cache_codec``: ``None``, ``"json"``, ``("signed-pickle", ENV_NAME)`` + or a ``(dumps, loads)`` callable pair. The secret itself is read when a store is built.""" + if value is None or value == "json": + return value + if isinstance(value, tuple) and len(value) == 2: + if value[0] == "signed-pickle": + if not isinstance(value[1], str) or not value[1]: + raise TypeError("cache_codec ('signed-pickle', ...) needs an environment name") + return ("signed-pickle", value[1]) + if all(callable(part) for part in value): + return value + raise TypeError( + "cache_codec must be 'json', ('signed-pickle', ENV_NAME), a (dumps, loads) " + f"callable pair or None, got {value!r}" + ) + + def _validate(key: str, value: Any) -> Any: if key == "logger": if value is not None and not isinstance(value, (str, logging.Logger)): @@ -80,13 +98,7 @@ def _validate(key: str, value: Any) -> Any: if key == "shared": return value if key == "cache_codec": - if value is not None and ( - not isinstance(value, tuple) - or len(value) != 2 - or not all(callable(part) for part in value) - ): - raise TypeError("cache_codec must be a (dumps, loads) callable pair or None") - return value + return _validate_codec(value) if key == "backend_errors": if value is not None and value not in ("raise", "local", "allow"): raise ValueError("backend_errors must be 'raise', 'local', 'allow' or None") @@ -121,6 +133,10 @@ def configure(**defaults: Any) -> None: retry budgets that do not name their own backend. `None` clears it. - `redact_extra`: fragments added to the redaction list (the built-ins stay), for `log_args` and `audit`. + - `cache_codec`: default codec for `RedisStore` and `AsyncRedisStore` built + without `dumps=`/`loads=`: `"json"`, `("signed-pickle", ENV_NAME)` (the + secret is read from that environment variable when the store is built) or a + `(dumps, loads)` pair. Raises: TypeError: For an unknown key (with a "did you mean" hint) or a wrongly typed value diff --git a/src/python_wrap/doctor.py b/src/python_wrap/doctor.py index c5e7d8b..7318b17 100644 --- a/src/python_wrap/doctor.py +++ b/src/python_wrap/doctor.py @@ -5,10 +5,11 @@ `findings` flag the combinations that usually cause production incidents: retries without a per-attempt timeout, retries of non-idempotent operations, unbounded retries, timeouts longer than the whole retry budget, memoized methods keyed on ``self`` with no -bound (PW011), LLM calls without a spend budget or timeout (PW013-PW015), SDK retries -under a python-wrap retry and retried streams without ``resume_safe`` (PW018-PW019), layers stacked -out of the canonical order (`python_wrap.policy.ROLES`) and, with ``multiprocess=True``, -limits that are enforced separately in every worker process. +bound (PW011), shared caches on plain pickle (PW026), LLM calls without a spend budget or +timeout (PW013-PW015), SDK retries under a python-wrap retry and retried streams without +``resume_safe`` (PW018-PW019), layers stacked out of the canonical order +(`python_wrap.policy.ROLES`) and, with ``multiprocess=True``, limits that are enforced +separately in every worker process. Nothing is called: only configuration attributes are read. @@ -207,9 +208,16 @@ def _cache_settings(obj: Any) -> dict[str, Any]: or params.get("store") is not None ) self_in_key = bool(names) and names[0] == "self" and not params.get("per_instance") + store = params.get("store") + # A store may wrap the Redis adapter (ThreadedStore keeps it in `.store`). + plain = bool( + getattr(store, "implicit_pickle", False) + or getattr(getattr(store, "store", None), "implicit_pickle", False) + ) return { "self_in_key": self_in_key and params.get("key") is None, "bounded": bounded, + "implicit_pickle": plain, "unstable_key": params.get("store") is not None and params.get("key") is None and _loose_parameters(getattr(obj, "__wrapped__", obj)), @@ -301,9 +309,7 @@ def _check( "are retried too. Narrow on= or add retry_if=, for example db_transient.", ) ) - if broad and not ( - settings.get("retry_if") or settings.get("retry_if_result") - ): + if broad and not (settings.get("retry_if") or settings.get("retry_if_result")): found.append( Finding( "PW025", @@ -425,6 +431,18 @@ def _check( "TypeError at call time: pass key= if an argument is not plain data.", ) ) + for layer in layers: + if layer.role == "cache" and layer.settings.get("implicit_pickle"): + found.append( + Finding( + "PW026", + "warning", + "memoize uses a shared store with plain pickle: anyone who can write the " + "cache namespace can run code in every process that reads it. Pass " + "dumps=/loads= (for example json_codec()), or configure(cache_codec='json') " + "for every store. Plain pickle becomes the JSON default in 0.5.0.", + ) + ) found += _check_agents(layers, retries) from python_wrap.llm import doctor_findings as _llm_findings diff --git a/src/python_wrap/stores.py b/src/python_wrap/stores.py index 77f0521..e8263a1 100644 --- a/src/python_wrap/stores.py +++ b/src/python_wrap/stores.py @@ -8,6 +8,7 @@ import hashlib import hmac import math +import os import pickle import re import warnings @@ -19,7 +20,15 @@ KEY_FORMAT = "k2:" # key encoding version: entries written by 0.4.0b1 expire unread -__all__ = ["RedisStore", "json_codec", "signed_pickle_codec"] +__all__ = ["RedisStore", "json_codec", "resolve_codec", "signed_pickle_codec"] + +SIGNED_PICKLE = "signed-pickle" +"""Codec name used in ``cache_codec=("signed-pickle", ENV_NAME)``.""" + +IMPLICIT_PICKLE_WARNING = ( + "implicit pickle cache codec is deprecated and becomes JSON in 0.5.0; pass dumps=/loads= " + "(for example json_codec()) or configure(cache_codec='json')" +) class InvalidSignature(ValueError): @@ -51,6 +60,43 @@ def json_codec() -> tuple[Callable[[Any], bytes], Callable[[bytes], Any]]: return lambda value: json.dumps(value, separators=(",", ":")).encode(), json.loads +def resolve_codec(value: Any) -> tuple[Callable[[Any], bytes], Callable[[bytes], Any]]: + """Turn a configured codec into a ``(dumps, loads)`` pair. + + Accepts ``"json"`` (`json_codec`), ``("signed-pickle", ENV_NAME)`` (`signed_pickle_codec` + with the secret read from that environment variable, at call time) or a ``(dumps, loads)`` + pair, returned unchanged. + + Raises: + ValueError: If the environment variable is unset or its value is shorter than 16 bytes, + or if ``value`` is an unknown codec name. + TypeError: If ``value`` has no supported shape. + """ + if value == "json": + return json_codec() + if isinstance(value, tuple) and len(value) == 2 and value[0] == SIGNED_PICKLE: + env_name = value[1] + if not isinstance(env_name, str) or not env_name: + raise ValueError("signed-pickle codec needs the name of an environment variable") + secret = os.environb.get(os.fsencode(env_name)) + if secret is None: + raise ValueError( + f"signed-pickle cache codec: environment variable {env_name} is not set" + ) + if len(secret) < 16: + raise ValueError( + f"signed-pickle cache codec: secret in {env_name} must be at least 16 bytes" + ) + return signed_pickle_codec(secret) + if isinstance(value, str): + raise ValueError(f"unknown cache codec {value!r}; use 'json' or a codec pair") + if isinstance(value, tuple) and len(value) == 2 and all(callable(p) for p in value): + return value + raise TypeError( + "cache codec must be 'json', ('signed-pickle', ENV_NAME) or a (dumps, loads) pair" + ) + + class RedisStore: """A namespaced `CacheStore` with opaque hashed keys and configurable serialization. @@ -93,15 +139,14 @@ def __init__( codec = get_config().get("cache_codec") if codec is None: - warnings.warn( - "implicit pickle cache codec is deprecated; pass a codec", - DeprecationWarning, - stacklevel=2, - ) + warnings.warn(IMPLICIT_PICKLE_WARNING, FutureWarning, stacklevel=2) codec = (pickle.dumps, pickle.loads) - dumps, loads = codec + dumps, loads = resolve_codec(codec) self.client, self.prefix = client, prefix + (f"v{version}:" if version else "") self.dumps, self.loads = dumps or pickle.dumps, loads or pickle.loads + # Plain pickle on a shared store lets anyone who can write the namespace run code + # in every reader; doctor reports it (PW026). + self.implicit_pickle = self.dumps is pickle.dumps self.key_format, self.fail_open = key_format, fail_open # fail_open=True is "allow" (a miss); False is "raise". self._monitor = BackendMonitor( diff --git a/tests/test_cache_codec.py b/tests/test_cache_codec.py new file mode 100644 index 0000000..2bed8c5 --- /dev/null +++ b/tests/test_cache_codec.py @@ -0,0 +1,123 @@ +"""Cache codec selection: the configured shortcuts, the visible implicit-pickle warning.""" + +from __future__ import annotations + +import pickle +import warnings + +import pytest + +from python_wrap import configure +from python_wrap.async_cache import AsyncRedisStore +from python_wrap.config import reset_config +from python_wrap.stores import RedisStore, json_codec, resolve_codec + +SECRET_ENV = "PW_TEST_CACHE_SECRET_041" + + +class FakeRedis: + def __init__(self) -> None: + self.data: dict[str, bytes] = {} + + def get(self, name): + return self.data.get(name) + + def set(self, name, payload, **options): + self.data[name] = payload + return True + + def delete(self, *names): + return sum(self.data.pop(name, None) is not None for name in names) + + def scan_iter(self, match=None, count=None): + return iter(list(self.data)) + + +@pytest.fixture(autouse=True) +def clean_config(): + reset_config() + yield + reset_config() + + +def test_cache_codec_json_shortcut(): + configure(cache_codec="json") + store = RedisStore(FakeRedis(), "j:") + store.set("k", {"a": [1, 2]}, None) + assert store.get("k") == {"a": [1, 2]} + assert store.implicit_pickle is False + assert store.dumps is not pickle.dumps + + +def test_cache_codec_signed_pickle_reads_env(monkeypatch): + monkeypatch.setenv(SECRET_ENV, "x" * 16) + configure(cache_codec=("signed-pickle", SECRET_ENV)) + client = FakeRedis() + store = RedisStore(client, "s:") + store.set("k", ("value", 3), None) + assert store.get("k") == ("value", 3) + assert store.implicit_pickle is False + # the entry is authenticated: a forged payload is rejected, not unpickled + name = next(iter(client.data)) + client.data[name] = b"\x00" * 32 + pickle.dumps(("evil",)) + assert store.get("k") is None + + +def test_signed_pickle_missing_secret_raises(monkeypatch): + monkeypatch.delenv(SECRET_ENV, raising=False) + with pytest.raises(ValueError, match=SECRET_ENV): + resolve_codec(("signed-pickle", SECRET_ENV)) + configure(cache_codec=("signed-pickle", SECRET_ENV)) + with pytest.raises(ValueError, match=SECRET_ENV): + RedisStore(FakeRedis(), "m:") + + +def test_short_secret_rejected(monkeypatch): + monkeypatch.setenv(SECRET_ENV, "short") + with pytest.raises(ValueError, match="16 bytes"): + resolve_codec(("signed-pickle", SECRET_ENV)) + + +def test_resolve_codec_passes_pairs_and_json_through(): + pair = json_codec() + assert resolve_codec(pair) == pair + assert resolve_codec("json")[0](["x"]) == b'["x"]' + with pytest.raises(ValueError, match="unknown cache codec"): + resolve_codec("yaml") + + +def test_configure_rejects_unknown_codec_values(): + with pytest.raises(TypeError, match="cache_codec"): + configure(cache_codec="yaml") + with pytest.raises(TypeError, match="cache_codec"): + configure(cache_codec=("signed-pickle", "")) + with pytest.raises(TypeError, match="cache_codec"): + configure(cache_codec=("signed-pickle", 5)) + + +def test_implicit_pickle_warns_visibly(): + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + store = RedisStore(FakeRedis(), "w:") + futures = [w for w in record if issubclass(w.category, FutureWarning)] + assert len(futures) == 1 + assert "0.5.0" in str(futures[0].message) + assert "json_codec" in str(futures[0].message) + assert store.implicit_pickle is True + + +def test_implicit_pickle_warns_on_async_store(): + class AsyncClient: + pass + + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + AsyncRedisStore(AsyncClient(), "w:") + assert any(issubclass(w.category, FutureWarning) for w in record) + + +def test_explicit_codec_does_not_warn(): + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + RedisStore(FakeRedis(), "e:", dumps=json_codec()[0], loads=json_codec()[1]) + assert not [w for w in record if issubclass(w.category, FutureWarning)] diff --git a/tests/test_doctor.py b/tests/test_doctor.py index a112bfe..2e7da6a 100644 --- a/tests/test_doctor.py +++ b/tests/test_doctor.py @@ -5,6 +5,7 @@ import asyncio import sys import types +import warnings import pytest @@ -22,6 +23,7 @@ from python_wrap.__main__ import main as cli from python_wrap.doctor import Report, doctor, explain from python_wrap.presets import db_call, http_client, third_party_api +from python_wrap.stores import RedisStore, json_codec def codes(report: Report) -> list[str]: @@ -477,3 +479,76 @@ def test_cli_doctor_multiprocess(capsys, monkeypatch): assert cli(["doctor", "--multiprocess", "pw_doctor_mp:stack"]) == 0 assert "WARNING PW012" in capsys.readouterr().out assert cli(["doctor", "--multiprocess", "--strict", "pw_doctor_mp:stack"]) == 1 + + +class _FakeRedis: + """Just enough of a Redis client for RedisStore construction and memoize.""" + + def __init__(self) -> None: + self.data: dict[str, bytes] = {} + + def get(self, name): + return self.data.get(name) + + def set(self, name, payload, **options): + self.data[name] = payload + + def delete(self, *names): + return sum(self.data.pop(name, None) is not None for name in names) + + def scan_iter(self, match=None, count=None): + return iter(list(self.data)) + + +def test_pw026_implicit_pickle(): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + store = RedisStore(_FakeRedis(), "d:") + + @memoize(store=store, ttl=60) + def price(sku: str) -> float: + return 1.0 + + report = doctor(price) + assert [f.code for f in report.findings] == ["PW026"] + assert report.findings[0].severity == "warning" + assert report.ok + + +def test_pw026_sees_a_store_wrapped_in_a_delegating_store(): + class Wrapped: + def __init__(self, inner): + self.store = inner + + def get(self, key): + return self.store.get(key) + + def set(self, key, entry, ttl): + self.store.set(key, entry, ttl) + + def delete(self, key): + return self.store.delete(key) + + def clear(self): + self.store.clear() + + def __len__(self): + return 0 + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + inner = RedisStore(_FakeRedis(), "d:") + + @memoize(store=Wrapped(inner), ttl=60) + def price(sku: str) -> float: + return 1.0 + + assert "PW026" in [f.code for f in doctor(price).findings] + + +def test_pw026_silent_with_json_codec(): + @memoize(store=RedisStore(_FakeRedis(), "d:", dumps=json_codec()[0], loads=json_codec()[1])) + def price(sku: str) -> float: + return 1.0 + + assert "PW026" not in [f.code for f in doctor(price).findings] From 322a3176510a61b6c1caacb4f1595126c14e0ea4 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Thu, 26 Nov 2026 21:33:01 +0200 Subject: [PATCH 05/38] feat: hint_jitter and min_delay options for hinted waits retry, retrying, retry_countdown, retry_task and HttpRetryPolicy accept hint_jitter (default 0.1) and min_delay (default 0.0). Hinted waits from delay_from, Retry-After and breaker retry_after are jittered by default, so exact hinted waits need hint_jitter=0. --- docs/features/resilience/http-clients.md | 4 +- docs/features/resilience/retry.md | 9 ++- docs/llms-full.txt | 10 +-- src/python_wrap/celery.py | 15 ++++- src/python_wrap/http.py | 13 +++- src/python_wrap/retry.py | 67 +++++++++++++++++-- tests/test_celery_helpers.py | 20 ++++++ tests/test_http.py | 22 ++++++ tests/test_release_041.py | 23 ------- tests/test_retry.py | 85 ++++++++++++++++++++++++ 10 files changed, 228 insertions(+), 40 deletions(-) diff --git a/docs/features/resilience/http-clients.md b/docs/features/resilience/http-clients.md index 497a684..e77c083 100644 --- a/docs/features/resilience/http-clients.md +++ b/docs/features/resilience/http-clients.md @@ -62,6 +62,8 @@ assert not should_retry("GET", {}, status=404) | `retry_on` | `ConnectionError`, `TimeoutError`, `OSError` | Transport error types | | `retry_on_names` | httpx / requests / aiohttp class names | Matched along the exception's MRO, so the libraries are never imported | | `respect_retry_after` | `True` | Use `Retry-After` as the wait (a lower bound, plus up to 10% jitter) | +| `hint_jitter` | `None` (0.1) | Proportional jitter on a `Retry-After` wait; `0` makes it exact. Finite, `>= 0` | +| `min_delay` | `0.0` | Minimum for a `Retry-After` wait, in seconds. Finite, `>= 0` | | `max_retry_after` | `60` | A longer `Retry-After` means: stop and hand back the response | | `budget` | `None` | A shared [`RetryBudget`](retry.md) | | `idempotency_header` | `"Idempotency-Key"` | Header that makes any method retryable (`None` disables) | @@ -183,7 +185,7 @@ async def put_item(session: aiohttp.ClientSession, item_id: int, data: dict): ## Retry-After -When a response carries `Retry-After` (seconds or an HTTP date) that value is a lower bound for the wait, with up to 10% jitter added so clients do not retry in lockstep. A value of zero waits 50 ms. The wait never exceeds `max_retry_after`. If it exceeds `max_retry_after` the server is asking for longer than you are willing to wait, so retrying stops and the response is returned for the caller to handle. +When a response carries `Retry-After` (seconds or an HTTP date) that value is a lower bound for the wait, with up to 10% jitter added so clients do not retry in lockstep. A value of zero waits 50 ms. Set `hint_jitter=0` for the exact header value, or `min_delay` for a larger floor. The wait never exceeds `max_retry_after`. If it exceeds `max_retry_after` the server is asking for longer than you are willing to wait, so retrying stops and the response is returned for the caller to handle. ```python from python_wrap.http import HttpRetryPolicy, retry_delay diff --git a/docs/features/resilience/retry.md b/docs/features/resilience/retry.md index 9832039..58bf96f 100644 --- a/docs/features/resilience/retry.md +++ b/docs/features/resilience/retry.md @@ -77,6 +77,8 @@ The wait before attempt `n + 1` is `min(delay * backoff ** (n - 1), max_delay) + | `retry_if_result` | `None` | Predicate on the return value; `True` means "retry". The last value is returned when retries run out. May be `async def` for async functions. | | `on_retry` | `None` | Called with a `RetryState` before each wait. May be async for async functions. Ordinary hook errors are logged and swallowed. | | `delay_from` | `None` | Exception or rejected result → seconds or None: wait for this attempt, with jitter and a floor (e.g. `Retry-After`). | +| `hint_jitter` | `None` (0.1) | Proportional jitter on hinted waits: `base * (1 + uniform(0, hint_jitter))`. The hint stays a lower bound. `0` makes hints exact. Finite, `>= 0`. | +| `min_delay` | `0.0` | Minimum for hinted waits, in seconds; a smaller hint is raised to it. Finite, `>= 0`. | | `budget` | `None` | A `RetryBudget` shared with other retried code, so retries stay a fraction of traffic. | | `logger` | package logger | Logger or logger name for the per-retry message. | | `log_level` | `WARNING` | Level of the per-retry message; `None` disables it. | @@ -273,7 +275,12 @@ assert stats is not None and stats.budget_exhausted > 0 ## Honouring Retry-After -Servers that answer 429 or 503 often say how long to wait. Pass `delay_from` a synchronous function that maps the exception or rejected result to a number of seconds, or to `None` to fall back to the normal backoff. A number is the wait for that attempt, not backoff: the hint is a lower bound, and up to 10% jitter is added so callers rejected together do not return at the same instant. A hint of zero waits 50 ms. The wait is still capped by `max_delay` and `max_time`. +Servers that answer 429 or 503 often say how long to wait. Pass `delay_from` a synchronous function that maps the exception or rejected result to a number of seconds, or to `None` to fall back to the normal backoff. A number is the wait for that attempt, not backoff: the hint is a lower bound, and up to 10% jitter is added so callers rejected together do not return at the same instant. A hint of zero waits 50 ms. Use `min_delay` to raise every hinted wait to a floor, and `hint_jitter=0` to get the exact hint. The wait is still capped by `max_delay` and `max_time`, after the jitter is applied. + +```python +@retry(delay_from=retry_after_header, hint_jitter=0.1, min_delay=0.05) +def fetch(): ... +``` `retry_after_header` reads `.retry_after` or a `Retry-After` header on the object itself or its `.response` (seconds or an HTTP-date). It never raises, so it works with returned responses and `httpx.HTTPStatusError`/`requests.HTTPError` without importing those clients. The example uses a stand-in exception with the same shape: diff --git a/docs/llms-full.txt b/docs/llms-full.txt index 5d2e974..339ec6b 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -4319,7 +4319,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm A disabled integration was called. - `python_wrap.HealthRegistry`: `HealthRegistry()` Register named components; report structural state without calling user functions. -- `python_wrap.HttpRetryPolicy`: `HttpRetryPolicy(max_attempts: int = 3, delay: float = 0.5, backoff: float = 2.0, max_delay: float = 30.0, jitter: float | str = 0.0, statuses: frozenset[int] = frozenset({408, 425, 429, 500, 502, 503, 504}), methods: frozenset[str] = frozenset({'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PUT', 'TRACE'}), retry_on: tuple[type[BaseException], ...] = (ConnectionError, TimeoutError, OSError), retry_on_names: frozenset[str] = frozenset({'ClientConnectionError', 'ClientOSError', 'ConnectError', 'ConnectTimeout', 'ConnectionError', 'ReadTimeout', 'ServerDisconnectedError', 'Timeout', 'TransportError'}), respect_retry_after: bool = True, max_retry_after: float = 60.0, budget: RetryBudget | None = None, idempotency_header: str | None = 'Idempotency-Key')` +- `python_wrap.HttpRetryPolicy`: `HttpRetryPolicy(max_attempts: int = 3, delay: float = 0.5, backoff: float = 2.0, max_delay: float = 30.0, jitter: float | str = 0.0, statuses: frozenset[int] = frozenset({408, 425, 429, 500, 502, 503, 504}), methods: frozenset[str] = frozenset({'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PUT', 'TRACE'}), retry_on: tuple[type[BaseException], ...] = (ConnectionError, TimeoutError, OSError), retry_on_names: frozenset[str] = frozenset({'ClientConnectionError', 'ClientOSError', 'ConnectError', 'ConnectTimeout', 'ConnectionError', 'ReadTimeout', 'ServerDisconnectedError', 'Timeout', 'TransportError'}), respect_retry_after: bool = True, max_retry_after: float = 60.0, budget: RetryBudget | None = None, idempotency_header: str | None = 'Idempotency-Key', hint_jitter: float | None = None, min_delay: float = 0.0)` What to retry, how long to wait, and when to stop, for HTTP calls. - `python_wrap.INJECTED` Constant: INJECTED @@ -4565,7 +4565,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Forget every configured default, restoring the built-in behaviour. - `python_wrap.resilient`: `resilient(name: str) -> Callable[[F], F]` Decorate with a named policy, resolving configuration at call time. -- `python_wrap.retry`: `retry(func: Callable[..., Any] | None = None, /, *, max_attempts: int | None = , delay: float = , backoff: float = , max_delay: float | None = , jitter: float | str = , max_time: float | None = , on: ExceptionTypes = Exception, retry_if: ExceptionPredicate | None = None, retry_if_result: ResultPredicate | None = None, on_retry: RetryCallback | None = None, delay_from: Callable[[Any], float | None] | None = None, delays: Sequence[float] | None = None, budget: RetryBudget | None = , logger: LoggerLike = None, log_level: int | None = , log_exc_info: bool = False, log_values: bool = True) -> Any` +- `python_wrap.retry`: `retry(func: Callable[..., Any] | None = None, /, *, max_attempts: int | None = , delay: float = , backoff: float = , max_delay: float | None = , jitter: float | str = , max_time: float | None = , on: ExceptionTypes = Exception, retry_if: ExceptionPredicate | None = None, retry_if_result: ResultPredicate | None = None, on_retry: RetryCallback | None = None, delay_from: Callable[[Any], float | None] | None = None, delays: Sequence[float] | None = None, budget: RetryBudget | None = , logger: LoggerLike = None, log_level: int | None = , log_exc_info: bool = False, log_values: bool = True, hint_jitter: float | None = None, min_delay: float = 0.0) -> Any` Retry a function when it raises (or returns a bad value), with optional backoff. - `python_wrap.retry_after_header`: `retry_after_header(value: Any, *, json_key: str | None = None) -> float | None` Extract a server-requested wait for `delay_from=`, from an error **or a result**. @@ -4573,7 +4573,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Deprecated alias for ``retry(on=exceptions or Exception, ...)``. - `python_wrap.retry_stats`: `retry_stats(func: Callable[..., Any]) -> RetryStats | None` Return the `RetryStats` of a function decorated with `retry`. -- `python_wrap.retrying`: `retrying(*, max_attempts: int | None = , delay: float = , backoff: float = , max_delay: float | None = , jitter: float | str = , max_time: float | None = , on: ExceptionTypes = Exception, retry_if: ExceptionPredicate | None = None, retry_if_result: ResultPredicate | None = None, on_retry: RetryCallback | None = None, delay_from: Callable[[Any], float | None] | None = None, delays: Sequence[float] | None = None, budget: RetryBudget | None = , logger: LoggerLike = None, log_level: int | None = , log_exc_info: bool = False, log_values: bool = True, name: str = 'retrying') -> Retrying` +- `python_wrap.retrying`: `retrying(*, max_attempts: int | None = , delay: float = , backoff: float = , max_delay: float | None = , jitter: float | str = , max_time: float | None = , on: ExceptionTypes = Exception, retry_if: ExceptionPredicate | None = None, retry_if_result: ResultPredicate | None = None, on_retry: RetryCallback | None = None, delay_from: Callable[[Any], float | None] | None = None, delays: Sequence[float] | None = None, budget: RetryBudget | None = , logger: LoggerLike = None, log_level: int | None = , log_exc_info: bool = False, log_values: bool = True, hint_jitter: float | None = None, min_delay: float = 0.0, name: str = 'retrying') -> Retrying` Retry an inline block of code instead of a whole function. - `python_wrap.revert_on_failure`: `revert_on_failure(func: Callable[..., Any] | None = None, /, *, target: str | int = 0, attrs: Iterable[str] | None = None, deep: bool = False) -> Any` Restore an object's attributes if the function raises. @@ -4769,9 +4769,9 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Bind task_id/name and a deadline from the task's time limit around task execution. - `python_wrap.celery.resilient_task`: `resilient_task(policy: Any = None, *, requeue_on: tuple[type[BaseException], ...] | None = None, delays: Sequence[float] | None = None, max_retries: int | None = None, requeue_when_limited: bool = True, **schedule: Any) -> Any` Run a bound task body through ``policy`` and re-queue it when the dependency is busy. -- `python_wrap.celery.retry_countdown`: `retry_countdown(task: Any, exc: BaseException | None = None, *, delays: Sequence[float] | None = None, delay: float = 5.0, backoff: float = 2.0, max_delay: float = 600.0, jitter: float | str = 0.0, respect_retry_after: bool = True) -> float` +- `python_wrap.celery.retry_countdown`: `retry_countdown(task: Any, exc: BaseException | None = None, *, delays: Sequence[float] | None = None, delay: float = 5.0, backoff: float = 2.0, max_delay: float = 600.0, jitter: float | str = 0.0, respect_retry_after: bool = True, hint_jitter: float | None = None, min_delay: float = 0.0) -> float` Seconds to wait before Celery runs ``task`` again, following python-wrap rules. -- `python_wrap.celery.retry_task`: `retry_task(task: Any, exc: BaseException, *, max_retries: int | None = None, delays: Sequence[float] | None = None, delay: float = 5.0, backoff: float = 2.0, max_delay: float = 600.0, jitter: float | str = 0.0, respect_retry_after: bool = True) -> NoReturn` +- `python_wrap.celery.retry_task`: `retry_task(task: Any, exc: BaseException, *, max_retries: int | None = None, delays: Sequence[float] | None = None, delay: float = 5.0, backoff: float = 2.0, max_delay: float = 600.0, jitter: float | str = 0.0, respect_retry_after: bool = True, hint_jitter: float | None = None, min_delay: float = 0.0) -> NoReturn` Ask Celery to retry ``task`` later with a `retry_countdown` schedule. - `python_wrap.celery.shared_breaker`: `shared_breaker(name: str, backend: Any, **options: Any) -> Any` A `CircuitBreaker` whose state lives in ``backend``, shared by every worker process. diff --git a/src/python_wrap/celery.py b/src/python_wrap/celery.py index cf1d278..90be116 100644 --- a/src/python_wrap/celery.py +++ b/src/python_wrap/celery.py @@ -210,6 +210,8 @@ def retry_countdown( max_delay: float = 600.0, jitter: float | str = 0.0, respect_retry_after: bool = True, + hint_jitter: float | None = None, + min_delay: float = 0.0, ) -> float: """Seconds to wait before Celery runs ``task`` again, following python-wrap rules. @@ -229,6 +231,9 @@ def retry_countdown( max_delay: Upper bound for every wait. jitter: Random extra seconds added to scheduled (not server-requested) waits. respect_retry_after: Honour a wait carried by the exception. + hint_jitter: Proportional jitter added to a hinted wait (``exc.retry_after`` or + ``Retry-After``); the hint stays a lower bound. ``0`` keeps it exact. + min_delay: Minimum for a hinted wait, in seconds. Returns: Non-negative seconds, suitable for ``task.retry(countdown=...)``. @@ -251,13 +256,13 @@ def retry_countdown( """ from python_wrap.retry import _compute_delay, _hinted, _validate, retry_after_header - _validate(1, delay, backoff, max_delay, jitter) + _validate(1, delay, backoff, max_delay, jitter, None, hint_jitter, min_delay) if delays is not None and not delays: raise ValueError("delays must not be empty") if respect_retry_after and exc is not None: hinted = retry_after_header(exc) if hinted is not None: - return _hinted(hinted, max_delay) + return _hinted(hinted, max_delay, hint_jitter, min_delay) retries = int(getattr(getattr(task, "request", None), "retries", 0) or 0) if delays is not None: base = float(delays[min(retries, len(delays) - 1)]) @@ -277,6 +282,8 @@ def retry_task( max_delay: float = 600.0, jitter: float | str = 0.0, respect_retry_after: bool = True, + hint_jitter: float | None = None, + min_delay: float = 0.0, ) -> NoReturn: """Ask Celery to retry ``task`` later with a `retry_countdown` schedule. @@ -301,6 +308,8 @@ def sync_orders(self, account_id): max_delay: See `retry_countdown`. jitter: See `retry_countdown`. respect_retry_after: See `retry_countdown`. + hint_jitter: See `retry_countdown`. + min_delay: See `retry_countdown`. Raises: Exception: Always; this function never returns. @@ -314,6 +323,8 @@ def sync_orders(self, account_id): max_delay=max_delay, jitter=jitter, respect_retry_after=respect_retry_after, + hint_jitter=hint_jitter, + min_delay=min_delay, ) options: dict[str, Any] = {"exc": exc, "countdown": countdown} if max_retries is not None: diff --git a/src/python_wrap/http.py b/src/python_wrap/http.py index d634ed9..692c273 100644 --- a/src/python_wrap/http.py +++ b/src/python_wrap/http.py @@ -79,9 +79,13 @@ class HttpRetryPolicy: retry_on: Exception types treated as transport failures. retry_on_names: Class names matched along an exception's MRO, so httpx, requests and aiohttp errors are recognised without importing those libraries. - respect_retry_after: Use a ``Retry-After`` header as the exact wait. + respect_retry_after: Use a ``Retry-After`` header as the wait. max_retry_after: A ``Retry-After`` larger than this means "do not retry": the response is returned (or the error raised) instead. + hint_jitter: Proportional jitter added to a ``Retry-After`` wait + (``base * (1 + uniform(0, hint_jitter))``); the header stays a lower bound. + ``0`` makes it exact. Finite and >= 0. + min_delay: Minimum for a ``Retry-After`` wait, in seconds. Finite and >= 0. budget: Optional shared `RetryBudget`; when it refuses, retrying stops. idempotency_header: A request carrying this header may be retried whatever its method. @@ -112,6 +116,8 @@ class HttpRetryPolicy: max_retry_after: float = 60.0 budget: RetryBudget | None = field(default=None, compare=False) idempotency_header: str | None = "Idempotency-Key" + hint_jitter: float | None = None + min_delay: float = 0.0 def __post_init__(self) -> None: if self.max_attempts < 1: @@ -130,6 +136,9 @@ def __post_init__(self) -> None: raise ValueError(f"jitter must be >= 0, 'full' or 'equal', got {self.jitter!r}") if not self.max_retry_after >= 0: raise ValueError(f"max_retry_after must be >= 0, got {self.max_retry_after!r}") + from python_wrap.retry import _validate_hint_options + + _validate_hint_options(self.hint_jitter, self.min_delay) if self.budget is not None and not isinstance(self.budget, RetryBudget): raise TypeError("budget must be a RetryBudget or None") object.__setattr__(self, "statuses", frozenset(self.statuses)) @@ -246,7 +255,7 @@ def retry_delay( return None from python_wrap.retry import _hinted - return _hinted(hinted, policy.max_retry_after) + return _hinted(hinted, policy.max_retry_after, policy.hint_jitter, policy.min_delay) return _compute_delay( max(attempt, 1), policy.delay, policy.backoff, policy.max_delay, policy.jitter ) diff --git a/src/python_wrap/retry.py b/src/python_wrap/retry.py index b803d14..496bd20 100644 --- a/src/python_wrap/retry.py +++ b/src/python_wrap/retry.py @@ -89,6 +89,8 @@ def _validate( max_delay: float | None, jitter: float | str, max_time: float | None = None, + hint_jitter: float | None = None, + min_delay: float = 0.0, ) -> None: if max_attempts is not None and max_attempts < 1: raise ValueError(f"max_attempts must be >= 1 or None, got {max_attempts!r}") @@ -104,6 +106,18 @@ def _validate( raise ValueError(f"max_delay must be >= 0, got {max_delay!r}") if max_time is not None and max_time < 0: raise ValueError(f"max_time must be >= 0 or None, got {max_time!r}") + _validate_hint_options(hint_jitter, min_delay) + + +def _validate_hint_options(hint_jitter: float | None, min_delay: float) -> None: + """Check the hint options; ``hint_jitter=None`` means the default `HINT_JITTER`.""" + for name, value in (("hint_jitter", hint_jitter), ("min_delay", min_delay)): + if value is None and name == "hint_jitter": + continue + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{name} must be a finite number >= 0, got {value!r}") + if not math.isfinite(value) or value < 0: + raise ValueError(f"{name} must be a finite number >= 0, got {value!r}") def _validate_delays(delays: Sequence[float] | None) -> tuple[float, ...] | None: @@ -583,10 +597,22 @@ def matches(result: Any) -> bool: HINT_JITTER = 0.1 -def _hinted(hint: float, ceiling: float) -> float: - """Apply the hint floor and jitter to a server or breaker hint, capped at ``ceiling``.""" +def _hinted( + hint: float, + ceiling: float, + hint_jitter: float | None = None, + min_delay: float = 0.0, +) -> float: + """Apply the minimum, the hint floor and jitter to a hint, capped at ``ceiling``. + + The base is ``max(hint, min_delay)``; a hint of exactly zero uses `HINT_FLOOR` + instead (still raised to ``min_delay``). The jitter is proportional and only adds + time, so the hint stays a lower bound. ``hint_jitter=None`` means `HINT_JITTER`. + """ + jitter = HINT_JITTER if hint_jitter is None else hint_jitter base = hint if hint > 0 else HINT_FLOOR - return min(base * (1 + random.uniform(0, HINT_JITTER)), ceiling) + base = max(base, min_delay) + return min(base * (1 + random.uniform(0, jitter)), ceiling) def _parse_hint(value: Any) -> float | None: @@ -672,10 +698,14 @@ def __init__( stats: RetryStats, delays: Sequence[float] | None = None, log_values: bool = True, + hint_jitter: float | None = None, + min_delay: float = 0.0, ) -> None: - _validate(max_attempts, delay, backoff, max_delay, jitter, max_time) + _validate(max_attempts, delay, backoff, max_delay, jitter, max_time, hint_jitter, min_delay) _check_budget(budget) self.name = name + self.hint_jitter = None if hint_jitter is None else float(hint_jitter) + self.min_delay = float(min_delay) self.max_attempts = max_attempts self.delay = delay self.delays = _validate_delays(delays) @@ -774,7 +804,12 @@ def _wait_for(self, attempt: int, exc: BaseException | None, result: Any = None) ) hint = None if hint is not None: - return _hinted(hint, HINT_CEILING if self.max_delay is None else self.max_delay) + return _hinted( + hint, + HINT_CEILING if self.max_delay is None else self.max_delay, + self.hint_jitter, + self.min_delay, + ) if self.delays is not None: delay = self.delays[min(attempt - 1, len(self.delays) - 1)] return _compute_delay(1, delay, 1.0, self.max_delay, self.jitter) @@ -1050,6 +1085,8 @@ def retry( log_level: int | None = ..., log_exc_info: bool = ..., log_values: bool = ..., + hint_jitter: float | None = ..., + min_delay: float = ..., ) -> F: ... @overload def retry( @@ -1073,6 +1110,8 @@ def retry( log_level: int | None = ..., log_exc_info: bool = ..., log_values: bool = ..., + hint_jitter: float | None = ..., + min_delay: float = ..., ) -> Callable[[F], F]: ... def retry( func: Callable[..., Any] | None = None, @@ -1095,6 +1134,8 @@ def retry( log_level: int | None = _UNSET, log_exc_info: bool = False, log_values: bool = True, + hint_jitter: float | None = None, + min_delay: float = 0.0, ) -> Any: """Retry a function when it raises (or returns a bad value), with optional backoff. @@ -1164,6 +1205,12 @@ def retry( failures, and suppresses log_exc_info. Events, stats and callbacks still receive original objects; function names and custom loggers are caller-owned. log_exc_info: Attach the traceback to the per-retry log record. + hint_jitter: Proportional jitter for hinted waits (`delay_from`): the wait is + ``base * (1 + uniform(0, hint_jitter))``, so the hint stays a lower bound + and callers rejected together spread out. ``0`` makes hints exact. Must be + finite and >= 0. + min_delay: Minimum for hinted waits, in seconds; a hint below it is raised to + it. Finite and >= 0. A hint of exactly 0 is floored at 0.05 s either way. Returns: The wrapped function, or a decorator when `func` is omitted. @@ -1197,7 +1244,7 @@ def retry( ) budget = ds["budget"] # Validate eagerly so a bad option fails at decoration time, even with no function yet. - _validate(max_attempts, delay, backoff, max_delay, jitter, max_time) + _validate(max_attempts, delay, backoff, max_delay, jitter, max_time, hint_jitter, min_delay) _check_budget(budget) delays = _validate_delays(delays) @@ -1237,6 +1284,8 @@ def decorate(f: Callable[P, R]) -> Callable[P, R]: log_exc_info=log_exc_info, log_values=log_values, stats=stats, + hint_jitter=hint_jitter, + min_delay=min_delay, ) check_result = retry_if_result is not None @@ -1457,6 +1506,8 @@ def retrying( log_level: int | None = _UNSET, log_exc_info: bool = False, log_values: bool = True, + hint_jitter: float | None = None, + min_delay: float = 0.0, name: str = "retrying", ) -> Retrying: """Retry an inline block of code instead of a whole function. @@ -1500,6 +1551,8 @@ def retrying( failures, and suppresses log_exc_info. Events, stats and callbacks still receive original objects; function names and custom loggers are caller-owned. log_exc_info: Attach the traceback to the per-retry log record. + hint_jitter: Proportional jitter for hinted waits (`delay_from`); see `retry`. + min_delay: Minimum for hinted waits in seconds; see `retry`. name: Name used in log messages and events. Returns: @@ -1553,6 +1606,8 @@ def retrying( log_exc_info=log_exc_info, log_values=log_values, stats=RetryStats(), + hint_jitter=hint_jitter, + min_delay=min_delay, ) ) diff --git a/tests/test_celery_helpers.py b/tests/test_celery_helpers.py index 5c59aa3..79264e9 100644 --- a/tests/test_celery_helpers.py +++ b/tests/test_celery_helpers.py @@ -51,6 +51,26 @@ def test_waits_requested_by_the_failure_win_and_are_capped(): assert retry_countdown(task, http_error, respect_retry_after=False) == 5 +def test_hinted_waits_take_hint_jitter_and_min_delay(): + task = FakeTask(0) + assert retry_countdown(task, CircuitOpenError("open", retry_after=42), hint_jitter=0) == 42 + for _ in range(100): + wait = retry_countdown(task, CircuitOpenError("open", retry_after=42)) + assert 42 <= wait <= 42 * 1.1 + tiny = CircuitOpenError("open", retry_after=0.0) + assert retry_countdown(task, tiny, hint_jitter=0, min_delay=3) == 3 + assert retry_countdown(task, tiny, hint_jitter=0) == 0.05 + with pytest.raises(ValueError, match="min_delay"): + retry_countdown(task, tiny, min_delay=-1) + + +def test_retry_task_passes_hint_options_through(): + task = FakeTask(0) + with pytest.raises(Retry): + retry_task(task, CircuitOpenError("open", retry_after=10), hint_jitter=0, min_delay=12) + assert task.calls[-1]["countdown"] == 12 + + def test_jitter_is_bounded(): for _ in range(50): wait = retry_countdown(FakeTask(0), delay=1, jitter=0.5) diff --git a/tests/test_http.py b/tests/test_http.py index d82c9c7..01eef5b 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -549,6 +549,28 @@ def test_retry_after_garbage_and_odd_values_are_ignored() -> None: assert retry_delay(Response(503, {"Retry-After": bad}), 1, HttpRetryPolicy(delay=2)) == 2.0 +def test_retry_after_hint_jitter_and_min_delay_options() -> None: + exact = HttpRetryPolicy(hint_jitter=0) + assert retry_delay(Response(429, {"Retry-After": "2"}), 1, exact) == 2.0 + floored = HttpRetryPolicy(hint_jitter=0, min_delay=5) + assert retry_delay(Response(429, {"Retry-After": "2"}), 1, floored) == 5.0 + assert ( + retry_delay(Response(429, {"Retry-After": "0"}), 1, HttpRetryPolicy(hint_jitter=0)) == 0.05 + ) + jittered = HttpRetryPolicy() + assert jittered.hint_jitter is None and jittered.min_delay == 0.0 + for _ in range(100): + assert 2.0 <= retry_delay(Response(429, {"Retry-After": "2"}), 1, jittered) <= 2.2 + + +def test_hint_options_are_validated() -> None: + for bad in (-1, float("inf"), float("nan")): + with pytest.raises(ValueError, match="hint_jitter"): + HttpRetryPolicy(hint_jitter=bad) + with pytest.raises(ValueError, match="min_delay"): + HttpRetryPolicy(min_delay=bad) + + def test_retry_after_negative_and_past_date_mean_retry_now() -> None: # "now" is the 50 ms floor: a zero hint never produces a tight retry loop. assert retry_delay(Response(503, {"Retry-After": "-5"}), 1) == 0.05 diff --git a/tests/test_release_041.py b/tests/test_release_041.py index 2c44c52..43d1ce4 100644 --- a/tests/test_release_041.py +++ b/tests/test_release_041.py @@ -245,26 +245,3 @@ async def send() -> str: assert asyncio.run(send()) == "sent" assert runs == [1] - - -# --- Gap 10: hinted waits get jitter on top and a floor for zero ------------------ - - -def test_hint_gets_jitter_and_stays_a_lower_bound(monkeypatch: pytest.MonkeyPatch) -> None: - import importlib - - retry_mod = importlib.import_module("python_wrap.retry") - monkeypatch.setattr(retry_mod, "HINT_JITTER", 0.1) - waits = [retry_mod._hinted(10.0, 1000.0) for _ in range(500)] - assert all(10.0 <= wait <= 11.0 for wait in waits) - assert max(waits) - min(waits) > 0.5 # the waits are actually spread out - - -def test_zero_hint_is_floored_and_cap_still_applies(monkeypatch: pytest.MonkeyPatch) -> None: - import importlib - - retry_mod = importlib.import_module("python_wrap.retry") - monkeypatch.setattr(retry_mod, "HINT_JITTER", 0.0) - assert retry_mod._hinted(0.0, 1000.0) == retry_mod.HINT_FLOOR - monkeypatch.setattr(retry_mod, "HINT_JITTER", 0.1) - assert retry_mod._hinted(500.0, 30.0) == 30.0 diff --git a/tests/test_retry.py b/tests/test_retry.py index d351a2f..2f25fd7 100644 --- a/tests/test_retry.py +++ b/tests/test_retry.py @@ -1460,3 +1460,88 @@ async def call() -> FakeResult: assert asyncio.run(call()).status_code == 200 assert fake_clock.sleeps == [3.0] + + +# --- Hinted waits: per-call jitter, a minimum and validation ------------------------- + + +def test_hint_gets_jitter_and_stays_a_lower_bound() -> None: + from python_wrap.retry import _hinted + + waits = [_hinted(10.0, 1000.0, hint_jitter=0.1) for _ in range(500)] + assert all(10.0 <= wait <= 11.0 for wait in waits) + assert max(waits) - min(waits) > 0.5 # spread out, not one instant + + +def test_zero_hint_is_floored(monkeypatch: pytest.MonkeyPatch) -> None: + import importlib + + from python_wrap.retry import HINT_FLOOR, _hinted + + retry_mod = importlib.import_module("python_wrap.retry") + assert HINT_FLOOR == 0.05 + assert _hinted(0.0, 1000.0, hint_jitter=0.0) == 0.05 + waits = [_hinted(0.0, 1000.0, hint_jitter=0.1) for _ in range(200)] + assert all(0.05 <= wait <= 0.055 for wait in waits) + # The module constant is the default when hint_jitter is not given. + monkeypatch.setattr(retry_mod, "HINT_JITTER", 0.0) + assert _hinted(0.0, 1000.0) == HINT_FLOOR + assert _hinted(500.0, 30.0) == 30.0 + + +def test_min_delay_raises_small_hints(fake_clock: FakeClock) -> None: + from python_wrap.retry import _hinted + + assert _hinted(0.01, 1000.0, hint_jitter=0.0, min_delay=0.2) == 0.2 + assert _hinted(0.0, 1000.0, hint_jitter=0.0, min_delay=0.2) == 0.2 + assert _hinted(3.0, 1000.0, hint_jitter=0.0, min_delay=0.2) == 3.0 + + hints = iter([0.01, 0.0]) + f = Flaky(2) + retry( + f, + max_attempts=3, + delay=1, + on=ValueError, + delay_from=lambda e: next(hints), + hint_jitter=0.0, + min_delay=0.2, + )() + assert fake_clock.sleeps == [0.2, 0.2] + + +def test_hint_jitter_zero_is_exact(fake_clock: FakeClock) -> None: + f = Flaky(2) + retry(f, max_attempts=3, delay=1, on=ValueError, delay_from=lambda e: 3.0, hint_jitter=0)() + assert fake_clock.sleeps == [3.0, 3.0] + + +def test_hint_capped_after_jitter(fake_clock: FakeClock) -> None: + from python_wrap.retry import _hinted + + for _ in range(100): + assert _hinted(500.0, 30.0, hint_jitter=0.5) == 30.0 + f = Flaky(1) + retry( + f, + max_attempts=2, + delay=1, + on=ValueError, + delay_from=lambda e: 25.0, + hint_jitter=0.5, + max_delay=30, + )() + assert 25.0 <= fake_clock.sleeps[0] <= 30.0 + + +def test_invalid_hint_jitter_and_min_delay_rejected() -> None: + bad_values = [-0.1, float("inf"), float("nan"), True, "0.1"] + for bad in bad_values: + with pytest.raises(ValueError, match="hint_jitter"): + retry(max_attempts=2, hint_jitter=bad)(lambda: None) # type: ignore[arg-type] + with pytest.raises(ValueError, match="hint_jitter"): + retrying(max_attempts=2, hint_jitter=bad) # type: ignore[arg-type] + with pytest.raises(ValueError, match="min_delay"): + retry(max_attempts=2, min_delay=bad)(lambda: None) # type: ignore[arg-type] + with pytest.raises(ValueError, match="min_delay"): + retrying(max_attempts=2, min_delay=bad) # type: ignore[arg-type] From 10bd0bc9a9e74e305fae3cde8613fa7f85309b8f Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Thu, 26 Nov 2026 21:42:42 +0200 Subject: [PATCH 06/38] fix: read Celery request id and deadline from attributes or headers - The request id and inherited deadline are read from the request attributes or its headers mapping, so both Celery header layouts are found. - A task published from another app's sender no longer gets this integration's headers. The task log context carries request_id_inherited. - Real-worker tests run an embedded Celery worker on an in-memory broker. - Documents the clock-skew limit of inherit_deadline. --- .github/workflows/ci.yml | 2 +- docs/cookbook/framework-integrations.md | 19 ++++ docs/project/stability.md | 2 +- src/python_wrap/celery.py | 34 ++++++- tests/test_celery_real_worker.py | 119 ++++++++++++++++++++++++ tests/test_celery_tasks.py | 54 ++++++++++- 6 files changed, 223 insertions(+), 7 deletions(-) create mode 100644 tests/test_celery_real_worker.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e4d7262..a6ce4cc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -263,7 +263,7 @@ jobs: run: >- uv run --frozen ${{ matrix.versions.pins }} pytest tests/test_integrations.py tests/test_http.py tests/test_web.py - tests/test_celery_helpers.py + tests/test_celery_helpers.py tests/test_celery_real_worker.py sql-backends: # PgAdvisoryLock, SqlAppLock and the transient-error predicates against real servers. diff --git a/docs/cookbook/framework-integrations.md b/docs/cookbook/framework-integrations.md index b260c3e..89faea7 100644 --- a/docs/cookbook/framework-integrations.md +++ b/docs/cookbook/framework-integrations.md @@ -89,6 +89,25 @@ Published tasks carry the current request id. Pass `inherit_deadline=True` to `i when a task should stop within the caller's remaining budget; it is off by default because most queued tasks must continue after the request ends. +What is propagated: + +- `x_request_id`: the publisher's bound request id. The worker binds it again, so the + task's log lines carry the same `request_id`. A header the caller sets explicitly is kept. + The task's log context has `request_id_inherited`: `True` when the header arrived, + `False` when the task was published outside a request. +- `x_deadline_at` (only with `inherit_deadline=True`): the publisher's deadline as an + absolute wall-clock time. The worker runs the task under the smaller of that remaining + time and its own time limit; a deadline that has already passed gives a zero budget. + +Clock skew: the inherited deadline is compared with the worker's clock, so the hosts' +clocks must be synchronised (NTP or the platform equivalent). A worker clock that runs +ahead of the publisher's shortens the task's budget by the difference; one that runs +behind lengthens it. python-wrap does not correct for skew. A few seconds of drift is a +few seconds of budget, so keep it small relative to the deadlines you send. + +The header and budget behaviour is checked against a real Celery worker in +`tests/test_celery_real_worker.py` (embedded solo-pool worker, in-memory broker). + ### Retrying tasks with Celery and python-wrap together Keep the two retry layers apart: python-wrap's in-process `retry` handles short blips diff --git a/docs/project/stability.md b/docs/project/stability.md index 9d72ba7..531015d 100644 --- a/docs/project/stability.md +++ b/docs/project/stability.md @@ -61,7 +61,7 @@ A provisional module graduates when all four hold: | --- | --- | --- | | `shared`, `coordination`, `quotas`, `stores` | 0.5.0 | Live CI in place; storage formats pinned by `tests/test_stability.py`; 1-minute 4-process soak passed, 1-hour soak pending | | `http` | 0.5.0 | CI against the real requests and httpx packages; soak pending | -| `celery` | 0.5.0 | CI against the real Celery package (no broker yet); soak pending | +| `celery` | 0.5.0 | CI against the real Celery package; real-worker tests run an embedded worker on an in-memory broker; soak pending | | `async_cache`, `web`, `exporters`, `observability` | 0.6.0 | Changed in 0.4.0b2 | The storage formats of the backends above are already frozen: a change to them fails the diff --git a/src/python_wrap/celery.py b/src/python_wrap/celery.py index 90be116..338012b 100644 --- a/src/python_wrap/celery.py +++ b/src/python_wrap/celery.py @@ -71,6 +71,9 @@ def _publish(self, sender: Any = None, headers: Any = None, **kw: Any) -> None: """Copy the request id (and, if enabled, the absolute deadline) into task headers.""" if headers is None: return + sender_app = getattr(sender, "app", None) + if sender_app is not None and sender_app is not self.app: + return import time from python_wrap.deadline import remaining @@ -105,13 +108,17 @@ def _before( if hard: budget = max(hard - self.hard_margin, hard * 0.5) request = getattr(task, "request", None) - fields = {"task_id": task_id, "task_name": getattr(task, "name", None)} - inherited = getattr(request, "x_request_id", None) + fields: dict[str, Any] = { + "task_id": task_id, + "task_name": getattr(task, "name", None), + } + inherited = _header(request, "x_request_id") + fields["request_id_inherited"] = bool(inherited) if inherited: from python_wrap._integration import request_id fields["request_id"] = request_id(inherited) - deadline_at = getattr(request, "x_deadline_at", None) + deadline_at = _header(request, "x_deadline_at") if self.inherit_deadline and isinstance(deadline_at, (int, float)): import time @@ -179,11 +186,18 @@ def install( The deadline is the soft time limit; with only a hard limit it is the hard limit minus ``hard_margin`` seconds (at least half of it), so cooperative code stops before the worker kills the task. Published tasks carry the request id in their headers and the - worker binds it again, so logs from the web request and the task join. With + worker binds it again, so logs from the web request and the task join; the bound + ``request_id_inherited`` field says whether the header arrived. With ``inherit_deadline=True`` the publisher's remaining deadline is sent too and the task runs under the smaller of it and its time limit (opt in: most tasks should outlive the request that queued them). + The inherited deadline is an absolute wall-clock time taken from the publisher's host, + so it is only as accurate as the clocks: a worker clock that runs ahead of the publisher + shortens the budget by the difference, and one that runs behind extends it. Keep the + hosts' clocks synchronised (NTP or the platform equivalent) before enabling it; the + skew is not corrected and a skew of a few seconds is a few seconds of budget. + Fork-safe python-wrap components reset through their POSIX hooks automatically; this adapter never starts background loops or opens backend connections at import. """ @@ -375,6 +389,18 @@ def operate(self, breaker, operation, generation=0, trial=False): return CircuitBreaker(name=name, backend=state, **options) +def _header(request: Any, name: str) -> Any: + """A propagated header from a task request. + + Celery versions differ on where custom message headers appear: as attributes of the + request object, or only in its ``headers`` mapping. Check both. + """ + value = getattr(request, name, None) + if value is None: + value = (getattr(request, "headers", None) or {}).get(name) + return value + + def _bound(args: tuple[Any, ...], what: str) -> Any: if not args or not hasattr(args[0], "request"): raise TypeError(f"{what} needs a bound task: use @app.task(bind=True) above it") diff --git a/tests/test_celery_real_worker.py b/tests/test_celery_real_worker.py new file mode 100644 index 0000000..ae626c8 --- /dev/null +++ b/tests/test_celery_real_worker.py @@ -0,0 +1,119 @@ +"""Context propagation from a publisher to a real Celery worker. + +Runs an embedded worker thread (``celery.contrib.testing.worker.start_worker``, solo pool) +against an in-memory broker and result backend, so headers travel through the real +message path. Skipped when Celery is not installed (CI installs it in the framework job). +""" + +from __future__ import annotations + +import pytest + +celery = pytest.importorskip("celery", reason="needs the celery package") +pytest.importorskip( + "celery.contrib.testing.worker", reason="celery.contrib.testing is not in this version" +) + +from celery.contrib.testing.worker import start_worker # noqa: E402 + +from python_wrap.celery import _header, install # noqa: E402 +from python_wrap.deadline import deadline, remaining # noqa: E402 +from python_wrap.logs import current_log_context, log_context # noqa: E402 + + +@pytest.fixture(autouse=True) +def _restore_logging(): + # Embedded workers reconfigure the root logger; put it back so later tests' log + # capture (caplog) keeps working. + import logging + + root = logging.getLogger() + handlers, level = list(root.handlers), root.level + yield + root.handlers[:] = handlers + root.setLevel(level) + + +@pytest.fixture +def app(): + app = celery.Celery( + "pythonwrap-real-worker", + broker="memory://", + backend="cache+memory://", + ) + app.conf.update( + task_always_eager=False, + worker_hijack_root_logger=False, + task_store_eager_result=True, + ) + + @app.task(name="pw.real.report", bind=True, shared=False) + def report(self): + return { + "log": current_log_context(), + "remaining": remaining(), + "header_request_id": _header(self.request, "x_request_id"), + } + + app.finalize() + yield app + app.close() + + +def _run(app, publish): + """Publish via ``publish()`` and wait for the result from an embedded worker.""" + with start_worker(app, pool="solo", perform_ping_check=False, shutdown_timeout=20): + result = publish() + return result.get(timeout=20) + + +def test_request_id_reaches_the_task(app): + handle = install(app) + try: + with log_context(request_id="req-real-1"): + data = _run(app, lambda: app.tasks["pw.real.report"].delay()) + finally: + handle.close() + assert data["log"]["request_id"] == "req-real-1" + assert data["log"]["request_id_inherited"] is True + assert data["header_request_id"] == "req-real-1" + + +def test_inherited_deadline_shortens_the_task_budget(app): + handle = install(app, inherit_deadline=True) + try: + with log_context(request_id="req-real-2"), deadline(5.0): + published_left = remaining() + data = _run(app, lambda: app.tasks["pw.real.report"].delay()) + finally: + handle.close() + assert data["remaining"] is not None + assert data["remaining"] <= published_left + 1e-6 + assert data["remaining"] > 0 + + +def test_no_deadline_inherited_by_default(app): + handle = install(app) + try: + with log_context(request_id="req-real-3"), deadline(5.0): + data = _run(app, lambda: app.tasks["pw.real.report"].delay()) + finally: + handle.close() + assert data["log"]["request_id"] == "req-real-3" + assert data["remaining"] is None + + +def test_explicit_header_is_not_overwritten(app): + handle = install(app) + try: + with log_context(request_id="req-outer"): + data = _run( + app, + lambda: app.tasks["pw.real.report"].apply_async( + headers={"x_request_id": "explicit-id"} + ), + ) + finally: + handle.close() + assert data["header_request_id"] == "explicit-id" + assert data["log"]["request_id"] == "explicit-id" diff --git a/tests/test_celery_tasks.py b/tests/test_celery_tasks.py index 7d8945b..00e8c26 100644 --- a/tests/test_celery_tasks.py +++ b/tests/test_celery_tasks.py @@ -2,12 +2,21 @@ from __future__ import annotations +import contextlib +import contextvars from types import SimpleNamespace from typing import Any import pytest -from python_wrap.celery import check_visibility, idempotent_task, resilient_task +from python_wrap import _fork +from python_wrap import celery as pw_celery +from python_wrap.celery import ( + _header, + check_visibility, + idempotent_task, + resilient_task, +) from python_wrap.circuit import CircuitBreaker from python_wrap.concurrency import RateLimiter from python_wrap.errors import CircuitOpenError @@ -89,3 +98,46 @@ def test_visibility_check_flags_blocking_limiter() -> None: def test_error_type_is_circuit_open() -> None: assert issubclass(CircuitOpenError, Exception) + + +def test_header_read_from_request_headers_mapping() -> None: + mapped = SimpleNamespace(headers={"x_request_id": "from-mapping"}) + assert _header(mapped, "x_request_id") == "from-mapping" + assert _header(mapped, "x_deadline_at") is None + attribute = SimpleNamespace(x_request_id="from-attribute", headers={"x_request_id": "other"}) + assert _header(attribute, "x_request_id") == "from-attribute" + assert _header(SimpleNamespace(headers=None), "x_request_id") is None + + +def test_inherited_flag_is_bound(monkeypatch: pytest.MonkeyPatch) -> None: + bound: list[dict[str, Any]] = [] + + def record(fields: dict[str, Any], budget: float | None = None) -> contextlib.ExitStack: + bound.append(fields) + return contextlib.ExitStack() + + monkeypatch.setattr(pw_celery, "scope", record) + app = object() + handle = object.__new__(pw_celery.TaskContext) + handle.app, handle.use_soft_deadline = app, True + handle.hard_margin, handle.inherit_deadline = 5.0, False + handle.closed, handle._active = False, 0 + handle._lock = _fork.ForkSafeLock() + handle._scopes = contextvars.ContextVar("g16_scopes", default=()) + + inherited = SimpleNamespace( + app=app, + name="demo.task", + soft_time_limit=None, + request=SimpleNamespace(headers={"x_request_id": "req-16"}), + ) + handle._before(task=inherited, task_id="t-1") + fresh = SimpleNamespace( + app=app, name="demo.task", soft_time_limit=None, request=SimpleNamespace(retries=0) + ) + handle._before(task=fresh, task_id="t-2") + + assert bound[0]["request_id_inherited"] is True + assert bound[0]["request_id"] == "req-16" + assert bound[1]["request_id_inherited"] is False + assert "request_id" not in bound[1] From 6cedccc99739574beed4ca092ba7a42d47123d97 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Thu, 26 Nov 2026 21:49:29 +0200 Subject: [PATCH 07/38] fix: every lock in the package is fork-safe; real prefork check in CI - All plain threading locks and Conditions in src/python_wrap (outside _fork.py) use ForkSafeLock/ForkSafeRLock; a test scans for plain locks with no allow-list. - scripts/prefork_check.py starts a watch in the parent, forks two workers and checks each applies a changed policy file within two poll intervals; CI runs it. - Documents watch and SQL lock behaviour under prefork servers. --- .github/workflows/ci.yml | 3 + .../concurrency/leases-and-idempotency.md | 6 +- docs/features/resilience/named-policies.md | 7 +- docs/project/limitations.md | 2 +- scripts/prefork_check.py | 160 ++++++++++++++++++ scripts/smoke_wheel.py | 6 +- src/python_wrap/_fork.py | 14 ++ src/python_wrap/agents.py | 12 +- src/python_wrap/async_cache.py | 3 +- src/python_wrap/buffering.py | 4 +- src/python_wrap/coordination.py | 2 +- src/python_wrap/llm_cassette.py | 6 +- src/python_wrap/llm_testing.py | 5 +- src/python_wrap/state.py | 5 +- src/python_wrap/timeouts.py | 8 +- src/python_wrap/timing.py | 6 +- tests/test_fork_safety.py | 39 ++--- tests/test_prefork_live.py | 21 +++ 18 files changed, 257 insertions(+), 52 deletions(-) create mode 100644 scripts/prefork_check.py create mode 100644 tests/test_prefork_live.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a6ce4cc..1198a20 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -265,6 +265,9 @@ jobs: pytest tests/test_integrations.py tests/test_http.py tests/test_web.py tests/test_celery_helpers.py tests/test_celery_real_worker.py + - name: Prefork workers keep a policy watch alive after os.fork + run: uv run --frozen python scripts/prefork_check.py + sql-backends: # PgAdvisoryLock, SqlAppLock and the transient-error predicates against real servers. name: PostgreSQL and SQL Server backends diff --git a/docs/features/concurrency/leases-and-idempotency.md b/docs/features/concurrency/leases-and-idempotency.md index 4be6b49..9f84c61 100644 --- a/docs/features/concurrency/leases-and-idempotency.md +++ b/docs/features/concurrency/leases-and-idempotency.md @@ -74,7 +74,11 @@ exposes that behavior for function calls. `PgAdvisoryLock(engine)` and `SqlAppLock(engine)` accept a SQLAlchemy engine and hold a dedicated session connection while the lease is held. SQL session locks last for the session rather than a wall-clock TTL. Capacity must be one. Create engines and SQL -lock backends after fork; inherited SQL backends reject use. Use client/database +lock backends before a fork (for example at import time in a preloading server). In a +forked child, the backend forgets the parent's connections without closing them, disposes +the inherited engine without closing its shared sockets, and then works normally. A lease +the parent holds stays with the parent: the child's `release` for that token returns +`False`. An engine without `dispose` still raises `RuntimeError` in a child. Use client/database timeouts. Unlock failures invalidate the dedicated connection rather than returning a potentially locked session to its pool. These adapters need your application's SQLAlchemy installation and database driver; python-wrap does not install them. diff --git a/docs/features/resilience/named-policies.md b/docs/features/resilience/named-policies.md index 381ec3d..17bbd28 100644 --- a/docs/features/resilience/named-policies.md +++ b/docs/features/resilience/named-policies.md @@ -82,7 +82,12 @@ policies.register_backend("default", RedisWindow(...)) Every builtin exception and the `*_transient` predicates from `python_wrap.predicates` are registered already. An unknown name raises ValueError that names the `register_*` call to use. -A watch does not survive a fork. Start it in each worker after the fork. +Watches and process pools: a `Watch` keeps working in a forked worker. Its poll thread is not +copied into the child, so the child starts its own the first time it resolves a policy in that +process (`watch.alive` is False until then, and `watch.pid` names the owning process). Start the +watch in the parent before forking (a preloading server) or in each worker; both work. The +`policies` entry of `health.report()` lists each watch with `alive`, `pid`, `interval` and +`seconds_since_poll`. `scripts/prefork_check.py` runs this path in CI with two forked workers. `python_wrap.health.health.report()` includes a `policies` entry with each policy's generation once the global `policies` registry has loaded one. diff --git a/docs/project/limitations.md b/docs/project/limitations.md index ef4eb11..b290125 100644 --- a/docs/project/limitations.md +++ b/docs/project/limitations.md @@ -87,7 +87,7 @@ Decorated functions pickle by reference, so the rules are those of plain functio With default backends, each worker has its own cache, rate limiter, circuit breaker, bulkhead and counters. A pool-wide limit requires an explicitly shared backend; `python -m python_wrap doctor --multiprocess` (PW012) lists the layers that lack one. Forked -workers also need the [documented child-reset lifecycle](migration-0.3.md#forked-workers). `CircuitBreaker`, `RateLimiter`, `Bulkhead`, `RetryBudget`, `Transaction`, `Policy` and `testing.FakeClock` raise `TypeError` when pickled or copied. A `cached_property` value is not pickled with its instance and is computed again after unpickling. See [Process pools and pickling](../get-started/async-and-methods.md#process-pools-and-pickling). +workers also need the [documented child-reset lifecycle](migration-0.3.md#forked-workers) for in-process state. Policy watches and SQL lock backends restart on their own in a forked child. `CircuitBreaker`, `RateLimiter`, `Bulkhead`, `RetryBudget`, `Transaction`, `Policy` and `testing.FakeClock` raise `TypeError` when pickled or copied. A `cached_property` value is not pickled with its instance and is computed again after unpickling. See [Process pools and pickling](../get-started/async-and-methods.md#process-pools-and-pickling). ## Optional distributed coordination diff --git a/scripts/prefork_check.py b/scripts/prefork_check.py new file mode 100644 index 0000000..22bae77 --- /dev/null +++ b/scripts/prefork_check.py @@ -0,0 +1,160 @@ +"""Prefork check: a policy watch started before os.fork keeps working in every worker. + +The parent starts a FileSource watch at import time (a preloading server), then forks +two workers. Each worker resolves a policy once, which starts its own poll thread, and +reports "ready". After every worker is ready the parent rewrites the policy file, and +each worker must report "applied" with the new generation within two poll intervals +(plus a small grace period for loaded CI runners). Exit status 0 means every worker +applied the change in time. Standard library only; POSIX only. +""" + +from __future__ import annotations + +import json +import os +import select +import sys +import tempfile +import time +from collections.abc import Iterator +from pathlib import Path +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from python_wrap.policies import PolicyRegistry, Watch + +INTERVAL = 0.2 # seconds between polls +GRACE = 1.0 # extra seconds allowed on a loaded runner +WORKERS = 2 +TIMEOUT = 15.0 # overall bound for each phase + + +def _write_policy(path: Path, max_attempts: int) -> None: + path.write_text(json.dumps({"db": {"retry": {"max_attempts": max_attempts, "delay": 0}}})) + + +def _emit(fd: int, message: dict[str, object]) -> None: + os.write(fd, json.dumps(message).encode() + b"\n") + + +def _worker(registry: PolicyRegistry, watch: Watch, fd: int) -> None: + """Runs in the forked child: start its own poll thread, then wait for a new generation.""" + ok = False + try: + resolve = registry.resilient("db")(lambda: None) + resolve() # the first resolution starts this process's poll thread + start = registry.describe("db")["db"]["generation"] + _emit(fd, {"event": "ready", "pid": os.getpid(), "alive": watch.alive, "generation": start}) + deadline = time.monotonic() + TIMEOUT + while time.monotonic() < deadline: + generation = registry.describe("db")["db"]["generation"] + if generation > start: + _emit(fd, {"event": "applied", "pid": os.getpid(), "generation": generation}) + ok = True + break + time.sleep(0.01) + except Exception as exc: # reported on stderr; the parent exits nonzero + sys.stderr.write(f"worker {os.getpid()} failed: {type(exc).__name__}: {exc}\n") + finally: + os.close(fd) + os._exit(0 if ok else 1) + + +def _messages(fds: list[int], timeout: float) -> Iterator[tuple[float, dict[str, object]]]: + """Yield (monotonic receive time, message) for each JSON line until timeout or EOF.""" + buffers = dict.fromkeys(fds, b"") + deadline = time.monotonic() + timeout + while buffers: + remaining = deadline - time.monotonic() + if remaining <= 0: + return + readable, _, _ = select.select(list(buffers), [], [], remaining) + for fd in readable: + chunk = os.read(fd, 4096) + if not chunk: + del buffers[fd] + continue + *lines, rest = (buffers[fd] + chunk).split(b"\n") + buffers[fd] = rest + for line in lines: + yield time.monotonic(), json.loads(line) + + +def main() -> int: + if not hasattr(os, "fork"): + print("prefork check needs os.fork (POSIX only)", file=sys.stderr) + return 2 + + from python_wrap.policies import FileSource, PolicyRegistry + + with tempfile.TemporaryDirectory(prefix="pw-prefork-") as tmp: + path = Path(tmp) / "policies.json" + _write_policy(path, max_attempts=1) + + # Preload: the watch and its poll thread exist before any worker is forked. + registry = PolicyRegistry() + watch = registry.watch(FileSource(path), interval=INTERVAL) + before = registry.describe("db")["db"]["generation"] + + read_ends: list[int] = [] + pids: list[int] = [] + for _ in range(WORKERS): + read_fd, write_fd = os.pipe() + pid = os.fork() + if pid == 0: + os.close(read_fd) + _worker(registry, watch, write_fd) + os.close(write_fd) + read_ends.append(read_fd) + pids.append(pid) + + failures: list[str] = [] + ready = [] + for _at, message in _messages(read_ends, TIMEOUT): + if message.get("event") == "ready": + ready.append(message) + if len(ready) == WORKERS: + break + if len(ready) != WORKERS: + failures.append(f"only {len(ready)} of {WORKERS} workers became ready") + elif not all(m["alive"] is True for m in ready): + failures.append("a worker reports its watch is not alive after first use") + + _write_policy(path, max_attempts=3) + changed_at = time.monotonic() + applied = [] + for at, message in _messages(read_ends, TIMEOUT): + if message.get("event") == "applied": + applied.append((at - changed_at, message)) + if len(applied) == WORKERS: + break + + limit = 2 * INTERVAL + GRACE + if len(applied) != WORKERS: + failures.append(f"only {len(applied)} of {WORKERS} workers applied the change") + for latency, message in applied: + if latency > limit: + failures.append(f"pid {message['pid']} took {latency:.2f}s (limit {limit:.2f}s)") + if message["generation"] != before + 1: + failures.append(f"pid {message['pid']} applied generation {message['generation']}") + + for fd in read_ends: + os.close(fd) + for pid in pids: + _, status = os.waitpid(pid, 0) + if os.waitstatus_to_exitcode(status) != 0: + failures.append(f"worker {pid} exited with status {status}") + watch.stop() + + summary = { + "workers": WORKERS, + "interval": INTERVAL, + "applied_seconds": sorted(round(latency, 3) for latency, _ in applied), + "failures": failures, + } + print(json.dumps(summary, sort_keys=True)) + return 1 if failures else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/smoke_wheel.py b/scripts/smoke_wheel.py index 01e3435..e6b3238 100644 --- a/scripts/smoke_wheel.py +++ b/scripts/smoke_wheel.py @@ -5,9 +5,9 @@ Steps: build one wheel from the checkout (``uv build`` if available, else ``python -m build``), create an empty virtual environment, install only that wheel, then run a short script with ``python -I`` from a scratch directory so the source tree cannot stand in for anything the -wheel left out. The script checks the version is a PEP 440 release (final or beta), that there are no runtime -dependencies, that ``py.typed`` and the packaged data files ship, that the command line tools -work and that a retry, timeout and LLM happy path runs. Standard library only. +wheel left out. The script checks the version is a PEP 440 release (final or beta), that there are +no runtime dependencies, that ``py.typed`` and the packaged data files ship, that the command line +tools work and that a retry, timeout and LLM happy path runs. Standard library only. """ from __future__ import annotations diff --git a/src/python_wrap/_fork.py b/src/python_wrap/_fork.py index 6024e80..2af82e1 100644 --- a/src/python_wrap/_fork.py +++ b/src/python_wrap/_fork.py @@ -90,6 +90,20 @@ def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: def release(self) -> None: self._lock.release() + def locked(self) -> bool: + probe = getattr(self._lock, "locked", None) # RLock.locked exists on 3.14+ + return probe() if probe is not None else self._lock._is_owned() # type: ignore[attr-defined] + + # threading.Condition uses these private hooks on an RLock to wait and notify. + def _is_owned(self) -> bool: + return self._lock._is_owned() # type: ignore[attr-defined] + + def _release_save(self) -> Any: + return self._lock._release_save() # type: ignore[attr-defined] + + def _acquire_restore(self, state: Any) -> None: + self._lock._acquire_restore(state) # type: ignore[attr-defined] + def __enter__(self) -> bool: return self.acquire() diff --git a/src/python_wrap/agents.py b/src/python_wrap/agents.py index 9629953..80805c5 100644 --- a/src/python_wrap/agents.py +++ b/src/python_wrap/agents.py @@ -45,7 +45,7 @@ from types import MappingProxyType, TracebackType from typing import Any, ParamSpec, Protocol, TypeVar, cast, overload -from python_wrap import _core +from python_wrap import _core, _fork from python_wrap._runtime import seconds as _parse_seconds from python_wrap.errors import PythonWrapError, TimeoutExpired from python_wrap.timeouts import CancelToken, _current_token @@ -404,7 +404,7 @@ def __init__(self, guard: RunGuard, run_id: str, parent: AgentRun | None) -> Non self.token = CancelToken( f"agent run {run_id}", guard.max_seconds or 0.0, _current_token.get() ) - self._lock = threading.Lock() + self._lock = _fork.ForkSafeLock() self._steps = 0 self._history: list[Step] = [] self._counts: dict[tuple[str, str, str], int] = {} @@ -1012,7 +1012,7 @@ def __init__(self, max_entries: int = 10_000) -> None: raise ValueError("max_entries must be a positive integer") self.max_entries = max_entries self._data: dict[str, tuple[EffectRecord, float]] = {} - self._lock = threading.Lock() + self._lock = _fork.ForkSafeLock() def __len__(self) -> int: with self._lock: @@ -1097,7 +1097,7 @@ def __init__( self.path = os.fspath(path) self.dumps, self.loads, self.timeout = dumps, loads, timeout - self._lock = threading.Lock() + self._lock = _fork.ForkSafeLock() self._conn: Any = None self._pid = 0 with self._lock: @@ -1374,7 +1374,7 @@ def __init__( raise ValueError("poll must be positive") self.poll = poll self.name = name - self._lock = threading.Lock() + self._lock = _fork.ForkSafeLock() self._events: dict[str, threading.Event] = {} self._orphans: set[str] = set() self._local_store = isinstance(self.store, MemoryEffectStore) @@ -2370,7 +2370,7 @@ def __init__( self.policy = policy self.guard = guard self._tools: dict[str, Callable[..., Any]] = {} - self._lock = threading.Lock() + self._lock = _fork.ForkSafeLock() for func in tools: self.add(func) diff --git a/src/python_wrap/async_cache.py b/src/python_wrap/async_cache.py index 8c0cb29..07d2abc 100644 --- a/src/python_wrap/async_cache.py +++ b/src/python_wrap/async_cache.py @@ -24,7 +24,6 @@ import pickle import random import re -import threading from collections import OrderedDict from collections.abc import Awaitable, Callable, Hashable from typing import Any, Protocol, TypeVar, runtime_checkable @@ -552,7 +551,7 @@ def decorate(func: F) -> F: build_key = _make_key_builder(func, False, key) name = _core.qualname(func) hits = misses = 0 - stats_lock = threading.Lock() + stats_lock = _fork.ForkSafeLock() inflight: dict[tuple[int, Hashable], asyncio.Future[Any]] = {} background: set[asyncio.Future[Any]] = set() # strong refs to refresh tasks diff --git a/src/python_wrap/buffering.py b/src/python_wrap/buffering.py index 0e8e3bd..d470ba3 100644 --- a/src/python_wrap/buffering.py +++ b/src/python_wrap/buffering.py @@ -331,7 +331,7 @@ def __init__( self.log = _core.get_logger(logger) self.journal = journal self._replayed = journal is None - self._condition = threading.Condition() + self._condition = threading.Condition(_fork.ForkSafeRLock()) self._bindings_lock = _fork.ForkSafeLock() self._queue: deque[Any] = deque() self._pending = self._written = self._dropped = self._failed = self._failed_records = 0 @@ -358,7 +358,7 @@ def _reset_after_fork(self) -> None: # replaying the same records. Call replay() explicitly in the one process # that owns the journal. self._replayed = True - self._condition = threading.Condition() + self._condition = threading.Condition(_fork.ForkSafeRLock()) self._fork_dropped = self._pending self._queue.clear() self._pending = 0 diff --git a/src/python_wrap/coordination.py b/src/python_wrap/coordination.py index e0bfbd3..a23cff6 100644 --- a/src/python_wrap/coordination.py +++ b/src/python_wrap/coordination.py @@ -246,7 +246,7 @@ def acquire(self, key: str, token: str, ttl: float, limit: int = 1) -> bool: with self._lock: if token in self._connections: raise RuntimeError("a SQL lease token was acquired concurrently") - self._connections[token] = (key, conn, threading.Lock()) + self._connections[token] = (key, conn, _fork.ForkSafeLock()) return True except BaseException: try: diff --git a/src/python_wrap/llm_cassette.py b/src/python_wrap/llm_cassette.py index 75df847..f7e1521 100644 --- a/src/python_wrap/llm_cassette.py +++ b/src/python_wrap/llm_cassette.py @@ -40,7 +40,7 @@ from typing import Any, Literal, cast from urllib.parse import parse_qsl, quote, urlsplit -from python_wrap import _core +from python_wrap import _core, _fork from python_wrap.errors import PythonWrapError from python_wrap.redaction import MASK, is_sensitive, redact @@ -250,7 +250,7 @@ def __init__(self, inner: Any, finish: Callable[[list[bytes], bool], None]) -> N self._chunks: list[bytes] = [] self._complete = False self._done = False - self._lock = threading.Lock() + self._lock = _fork.ForkSafeLock() def _settle(self) -> None: with self._lock: @@ -467,7 +467,7 @@ def __init__( self.redact_responses = redact_responses self._secrets = tuple(s for s in secrets if isinstance(s, str) and len(s) >= 4) self.allow_repeat, self.autosave = allow_repeat, autosave - self._lock = threading.RLock() + self._lock = _fork.ForkSafeRLock() self._entries: list[dict[str, Any]] = [] self._used: set[int] = set() self.recorded = 0 diff --git a/src/python_wrap/llm_testing.py b/src/python_wrap/llm_testing.py index adfb1b7..8378bcf 100644 --- a/src/python_wrap/llm_testing.py +++ b/src/python_wrap/llm_testing.py @@ -24,13 +24,12 @@ import json import re -import threading from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence from dataclasses import dataclass from types import SimpleNamespace, TracebackType from typing import TYPE_CHECKING, Any -from python_wrap import _core +from python_wrap import _core, _fork from python_wrap.chaos import FaultInjector, fault_point if TYPE_CHECKING: @@ -525,7 +524,7 @@ def __init__( self._first = first_token_delay self._chunk_delay = chunk_delay self._chunk_size = chunk_size - self._lock = threading.Lock() + self._lock = _fork.ForkSafeLock() self._next = 0 self.calls: list[FakeCall] = [] self._run = fault_point(self.point, injector=injector)(self._serve) diff --git a/src/python_wrap/state.py b/src/python_wrap/state.py index d0b36c3..bfa8d3b 100644 --- a/src/python_wrap/state.py +++ b/src/python_wrap/state.py @@ -7,12 +7,11 @@ import copy import functools import inspect -import threading from collections.abc import Callable, Iterable from types import TracebackType from typing import Any, Final, NoReturn, ParamSpec, TypeVar, cast, overload -from python_wrap import _core +from python_wrap import _core, _fork from python_wrap._core import F, LoggerLike __all__ = [ @@ -282,7 +281,7 @@ def __init__(self, logger: LoggerLike = None) -> None: self._commit: list[tuple[Callable[..., Any], tuple[Any, ...], dict[str, Any]]] = [] self._rollback: list[tuple[Callable[..., Any], tuple[Any, ...], dict[str, Any]]] = [] self._state = "pending" - self._state_lock = threading.Lock() + self._state_lock = _fork.ForkSafeLock() @property def state(self) -> str: diff --git a/src/python_wrap/timeouts.py b/src/python_wrap/timeouts.py index 4b32877..1603dcb 100644 --- a/src/python_wrap/timeouts.py +++ b/src/python_wrap/timeouts.py @@ -21,7 +21,7 @@ cast, ) -from python_wrap import _core +from python_wrap import _core, _fork from python_wrap import deadline as _deadline from python_wrap._core import F, P, R from python_wrap.errors import TimeoutExpired @@ -299,7 +299,7 @@ def __init__(self, func: Callable[..., Any], args: Any, kwargs: Any) -> None: self.args = args self.kwargs = kwargs self.context = contextvars.copy_context() # per call, as with a fresh thread - self.done = threading.Lock() + self.done = _fork.ForkSafeLock() self.done.acquire() self.result: Any = None self.error: BaseException | None = None @@ -325,7 +325,7 @@ class _WorkerPool: """ def __init__(self) -> None: - self.lock = threading.Lock() + self.lock = _fork.ForkSafeLock() self.idle: list[queue.SimpleQueue[_Job]] = [] # inboxes of idle workers (LIFO) self.count = 0 @@ -367,7 +367,7 @@ def abandon(self, job: _Job) -> None: def reset(self) -> None: """After `os.fork`: the parent's workers do not exist in the child.""" - self.lock = threading.Lock() + self.lock = _fork.ForkSafeLock() self.idle = [] diff --git a/src/python_wrap/timing.py b/src/python_wrap/timing.py index 2a1516a..cf95719 100644 --- a/src/python_wrap/timing.py +++ b/src/python_wrap/timing.py @@ -333,7 +333,7 @@ class MemoryRecord: net_bytes: int -_trace_lock = threading.Lock() +_trace_lock = _fork.ForkSafeLock() _trace_users = 0 _trace_started_by_us = False @@ -365,7 +365,7 @@ def _trace_release() -> None: # re-entrant for the call holding it: nested measured calls, and tasks or # ``asyncio.to_thread`` workers started inside it (they inherit the context variable), # enter immediately instead of deadlocking on their parent. -_gate = threading.Condition(threading.Lock()) +_gate = threading.Condition(_fork.ForkSafeLock()) _gate_owner: object | None = None _gate_depth = 0 _measuring: contextvars.ContextVar[object | None] = contextvars.ContextVar( @@ -375,7 +375,7 @@ def _trace_release() -> None: def _reset_gate() -> None: global _gate, _gate_owner, _gate_depth - _gate = threading.Condition(threading.Lock()) + _gate = threading.Condition(_fork.ForkSafeLock()) _gate_owner, _gate_depth = None, 0 diff --git a/tests/test_fork_safety.py b/tests/test_fork_safety.py index bff85b4..b335575 100644 --- a/tests/test_fork_safety.py +++ b/tests/test_fork_safety.py @@ -272,24 +272,9 @@ def holder() -> None: thread.join() -# Plain threading locks that remain on purpose. Keyed by (file, assignment target) with -# the maximum number of occurrences allowed and the reason each one is still plain. -PLAIN_LOCK_ALLOW_LIST: dict[tuple[str, str], tuple[int, str]] = { - ("coordination.py", "self._connections[token]"): ( - 1, - "per-lease operation lock, made in acquire and dropped with its slot " - "(_process clears slots after fork)", - ), - ("timeouts.py", "self.done"): (1, "outside the 0.4.1 file scope; convert in a follow-up"), - ("timeouts.py", "self.lock"): (2, "outside the 0.4.1 file scope; convert in a follow-up"), - ("timing.py", "_trace_lock"): (1, "outside the 0.4.1 file scope; convert in a follow-up"), - ("timing.py", "_gate"): (2, "outside the 0.4.1 file scope; convert in a follow-up"), - ("state.py", "self._state_lock"): (1, "outside the 0.4.1 file scope; convert in a follow-up"), - ("agents.py", "self._lock"): (5, "outside the 0.4.1 file scope; convert in a follow-up"), - ("async_cache.py", "stats_lock"): (1, "outside the 0.4.1 file scope; convert in a follow-up"), - ("llm_cassette.py", "self._lock"): (2, "outside the 0.4.1 file scope; convert in a follow-up"), - ("llm_testing.py", "self._lock"): (1, "outside the 0.4.1 file scope; convert in a follow-up"), -} +# Plain threading locks that remain on purpose, keyed by (file, assignment target) with the +# allowed count and a one-line reason. Empty: every lock in the package is a _fork wrapper. +PLAIN_LOCK_ALLOW_LIST: dict[tuple[str, str], tuple[int, str]] = {} def _plain_lock_sites() -> dict[tuple[str, str], int]: @@ -306,11 +291,16 @@ def _plain_lock_sites() -> dict[tuple[str, str], int]: for node in ast.walk(tree): if not ( isinstance(node, ast.Attribute) - and node.attr in {"Lock", "RLock"} + and node.attr in {"Lock", "RLock", "Condition"} and isinstance(node.value, ast.Name) and node.value.id == "threading" ): continue + if node.attr == "Condition": + # A Condition is only plain when it makes its own RLock (no argument). + call = parents.get(id(node)) + if not (isinstance(call, ast.Call) and call.func is node and not call.args): + continue target = node while id(target) in parents and not isinstance( parents[id(target)], (ast.Assign, ast.AnnAssign, ast.AugAssign, ast.stmt) @@ -328,6 +318,17 @@ def _plain_lock_sites() -> dict[tuple[str, str], int]: return found +def test_condition_over_fork_safe_rlock_waits_and_notifies(): + import threading + + from python_wrap._fork import ForkSafeRLock + + cond = threading.Condition(ForkSafeRLock()) + with cond: + assert cond.wait(0.01) is False + cond.notify_all() + + def test_no_plain_threading_locks_in_package(): unexpected = [] for key, count in _plain_lock_sites().items(): diff --git a/tests/test_prefork_live.py b/tests/test_prefork_live.py new file mode 100644 index 0000000..ded4816 --- /dev/null +++ b/tests/test_prefork_live.py @@ -0,0 +1,21 @@ +"""Run the prefork worker check in a fresh interpreter: a watch started before fork lives on.""" + +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "prefork_check.py" + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="POSIX fork only") +def test_prefork_workers_apply_watch_change_within_two_intervals(): + result = subprocess.run( + [sys.executable, str(SCRIPT)], capture_output=True, text=True, timeout=120 + ) + assert result.returncode == 0, result.stdout + result.stderr + assert '"failures": []' in result.stdout, result.stdout From 9df5897764c704ddf2b79f58969c1667cc8954fa Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 27 Nov 2026 08:10:55 +0200 Subject: [PATCH 08/38] test: cover mount_policy, live quota script and CI live job - mount_policy tests: per-host breakers, default timeouts, 429 Retry-After pauses, request-id and deadline propagation. - Live Redis tests for the quota script, backend-recovered events and the requests adapter run in the backend-integration CI job. - The quota Lua script is a module constant (no behaviour change). --- .github/workflows/ci.yml | 5 +- src/python_wrap/quotas.py | 20 +++--- tests/test_http_requests.py | 113 ++++++++++++++++++++++++++++++- tests/test_redis_scripts_live.py | 3 +- 4 files changed, 127 insertions(+), 14 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1198a20..d264ef4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -230,7 +230,10 @@ jobs: run: sudo apt-get update && sudo apt-get install -y redis-server - run: uv sync --group dev --frozen - name: Validate atomic backend scripts against Redis - run: uv run --no-sync pytest tests/test_redis_backends.py tests/test_fork_safety.py + run: >- + uv run --no-sync --with 'requests>=2.32' pytest tests/test_redis_backends.py + tests/test_fork_safety.py tests/test_redis_scripts_live.py tests/test_backend_recovered.py + tests/test_http_requests.py framework-integration: # Oldest supported and newest releases of each framework, so an adapter that only diff --git a/src/python_wrap/quotas.py b/src/python_wrap/quotas.py index 3389ed2..2796f16 100644 --- a/src/python_wrap/quotas.py +++ b/src/python_wrap/quotas.py @@ -21,6 +21,16 @@ F = TypeVar("F", bound=Callable[..., Any]) +_QUOTA = """ +local used=tonumber(redis.call('GET',KEYS[1]) or '0') +if used+tonumber(ARGV[1])>tonumber(ARGV[2]) then return -1 end +used=redis.call('INCRBY',KEYS[1],ARGV[1]) +if tonumber(ARGV[3])>0 and redis.call('PTTL',KEYS[1])<0 then + redis.call('PEXPIRE',KEYS[1],ARGV[3]) end +return tonumber(ARGV[2])-used +""" + + class QuotaExhausted(RuntimeError): """A named run quota has no remaining allowance.""" @@ -75,21 +85,13 @@ def take(self, amount: int = 1) -> int: raise ValueError("Redis quota amount exceeds exact Lua integer range") if self.client is None: return self._take_local(amount) - script = """ -local used=tonumber(redis.call('GET',KEYS[1]) or '0') -if used+tonumber(ARGV[1])>tonumber(ARGV[2]) then return -1 end -used=redis.call('INCRBY',KEYS[1],ARGV[1]) -if tonumber(ARGV[3])>0 and redis.call('PTTL',KEYS[1])<0 then - redis.call('PEXPIRE',KEYS[1],ARGV[3]) end -return tonumber(ARGV[2])-used -""" assert self._monitor is not None monitor = self._monitor result = monitor.call( "take", lambda: int( self.client.eval( - script, + _QUOTA, 1, self.key, amount, diff --git a/tests/test_http_requests.py b/tests/test_http_requests.py index c880dd9..9a27546 100644 --- a/tests/test_http_requests.py +++ b/tests/test_http_requests.py @@ -9,6 +9,7 @@ import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any import pytest @@ -18,6 +19,8 @@ from python_wrap.deadline import deadline # noqa: E402 from python_wrap.errors import CircuitOpenError # noqa: E402 from python_wrap.http import HttpPolicy, HttpRetryPolicy, mount_policy # noqa: E402 +from python_wrap.logs import log_context # noqa: E402 +from python_wrap.ratelimit import RateLimiter # noqa: E402 class _Handler(BaseHTTPRequestHandler): @@ -34,11 +37,15 @@ def _serve(self) -> None: server = self.server with server.lock: # type: ignore[attr-defined] server.hits.append((self.command, self.path)) # type: ignore[attr-defined] + server.seen.append(self.headers) # type: ignore[attr-defined] status = server.statuses.get(self.path, 200) # type: ignore[attr-defined] delay = server.delay # type: ignore[attr-defined] + retry_after = server.retry_after.get(self.path) # type: ignore[attr-defined] if delay: time.sleep(delay) self.send_response(status) + if retry_after is not None: + self.send_header("Retry-After", retry_after) self.send_header("Content-Length", "0") self.end_headers() @@ -52,7 +59,9 @@ class _Server(ThreadingHTTPServer): def __init__(self) -> None: super().__init__(("127.0.0.1", 0), _Handler) self.hits: list[tuple[str, str]] = [] + self.seen: list[Any] = [] # request header objects, in arrival order self.statuses: dict[str, int] = {} + self.retry_after: dict[str, str] = {} self.delay = 0.0 self.lock = threading.Lock() @@ -61,16 +70,34 @@ def url(self) -> str: host, port = self.server_address[:2] return f"http://{host}:{port}" + def url_on(self, hostname: str) -> str: + """The same server reached through another host name (the port is what matters).""" + return f"http://{hostname}:{self.server_address[1]}" + def count(self, method: str, path: str) -> int: with self.lock: return self.hits.count((method, path)) +def _start() -> _Server: + server = _Server() + threading.Thread(target=server.serve_forever, daemon=True).start() + return server + + @pytest.fixture def local_server(): - server = _Server() - thread = threading.Thread(target=server.serve_forever, daemon=True) - thread.start() + server = _start() + try: + yield server + finally: + server.shutdown() + server.server_close() + + +@pytest.fixture +def second_server(): + server = _start() try: yield server finally: @@ -137,3 +164,83 @@ def test_post_is_not_retried_without_idempotency_key(local_server): assert session.get(server.url + "/orders").status_code == 503 assert server.count("GET", "/orders") == 3 # GET is retried by default + + +def test_mount_policy_per_host_breaker_opens_for_one_host(local_server, second_server): + # Host names are the per-host key, so the two servers are reached as 127.0.0.1 and + # localhost while both listen on loopback with different ports. + failing, healthy = local_server, second_server + failing.statuses["/boom"] = 500 + policy = HttpPolicy( + breaker=lambda name: CircuitBreaker(name=name, failure_threshold=2, recovery_timeout=60), + per_host=True, + retry=HttpRetryPolicy(max_attempts=1), + ) + session = _session() + mount_policy(session, policy) + + assert session.get(failing.url_on("127.0.0.1") + "/boom").status_code == 500 + assert session.get(failing.url_on("127.0.0.1") + "/boom").status_code == 500 + assert policy.guards("127.0.0.1")[0].state == "open" + + with pytest.raises(CircuitOpenError): + session.get(failing.url_on("127.0.0.1") + "/ok") + assert failing.count("GET", "/ok") == 0 # the open host is not contacted + + # The other host keeps working and has its own closed breaker. + assert session.get(healthy.url_on("localhost") + "/ok").status_code == 200 + assert policy.guards("localhost")[0].state == "closed" + assert healthy.count("GET", "/ok") == 1 + + +def test_mount_policy_default_timeouts_apply_when_caller_set_none(local_server): + server = local_server + server.delay = 1.0 # answers after the default read timeout has passed + session = _session() + mount_policy(session, HttpPolicy(read_timeout=0.2, retry=HttpRetryPolicy(max_attempts=1))) + + started = time.monotonic() + with pytest.raises(requests.exceptions.ReadTimeout): + session.get(server.url + "/slow") + assert time.monotonic() - started < 0.9 # the 1 s answer was never awaited + + # A timeout the caller passed is kept as given: the same slow server now answers. + assert session.get(server.url + "/slow", timeout=5).status_code == 200 + + +def test_mount_policy_429_pause(local_server): + server = local_server + server.statuses["/limited"] = 429 + server.retry_after["/limited"] = "1" + policy = HttpPolicy( + limiter=RateLimiter(calls=100, period=1.0), retry=HttpRetryPolicy(max_attempts=1) + ) + session = _session() + mount_policy(session, policy) + + assert session.get(server.url + "/limited").status_code == 429 + server.statuses["/limited"] = 200 # the next call would succeed if it were sent now + + started = time.monotonic() + assert session.get(server.url + "/limited").status_code == 200 + # The host was asked to wait for Retry-After, so the second call paused first. + assert time.monotonic() - started >= 0.8 + assert server.count("GET", "/limited") == 2 + + +def test_mount_policy_propagates_request_id_and_deadline(local_server): + server = local_server + session = _session() + mount_policy(session, HttpPolicy(propagate=True, retry=HttpRetryPolicy(max_attempts=1))) + + with log_context(request_id="req-prop-1"), deadline(5.0): + assert session.get(server.url + "/trace").status_code == 200 + sent = server.seen[-1] + assert sent["X-Request-ID"] == "req-prop-1" + remaining_ms = int(sent["X-Request-Deadline"]) + assert 4000 < remaining_ms <= 5000 # the remaining budget, in milliseconds + + assert session.get(server.url + "/trace").status_code == 200 + bare = server.seen[-1] + assert bare.get("X-Request-ID") is None # nothing bound, nothing sent + assert bare.get("X-Request-Deadline") is None diff --git a/tests/test_redis_scripts_live.py b/tests/test_redis_scripts_live.py index 95a4db9..ea3d1b5 100644 --- a/tests/test_redis_scripts_live.py +++ b/tests/test_redis_scripts_live.py @@ -25,7 +25,7 @@ from python_wrap.errors import CircuitOpenError from python_wrap.llm import _REDIS_ADD, RedisBudgetBackend from python_wrap.llm_shared import _LUA_STEP, RedisTokenWindow -from python_wrap.quotas import _WINDOW, Quota, QuotaExhausted, RedisWindow +from python_wrap.quotas import _QUOTA, _WINDOW, Quota, QuotaExhausted, RedisWindow from python_wrap.retry import RetryBudget from python_wrap.shared import _BREAKER, _BUDGET, RedisBreakerState, RedisRetryBudget @@ -180,6 +180,7 @@ def test_quota_script_runs_live(redis_client): quota.reset() assert quota.remaining == 3 assert len(rec.scripts) >= 4 + assert _QUOTA in rec.scripts # the module constant is the script Quota.take sends def test_window_script_runs_live(redis_client): From 8b2ef0b16f9d2b3115e5bdab2ed845dfdd7e29a7 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 27 Nov 2026 08:16:40 +0200 Subject: [PATCH 09/38] fix: keyed rate windows and LLM scopes use the stable key encoding Keyed rate windows, keyed LLM budget scopes and the keyed LLM response cache hash their key with stable_digest, so a set, frozenset or dict key no longer splits into several windows across processes. Their store keys change once on upgrade; for one period a keyed limit can admit up to twice its rate while old and new processes overlap. Unkeyed limits keep their store keys. Name-only call sites use name_digest, which keeps the previous digest output. --- docs/features/concurrency/rate-limits.md | 2 + src/python_wrap/_runtime.py | 13 +++- src/python_wrap/async_cache.py | 6 +- src/python_wrap/caching.py | 10 +-- src/python_wrap/idempotency.py | 14 ++-- src/python_wrap/llm.py | 8 ++- src/python_wrap/quotas.py | 7 +- src/python_wrap/shared.py | 6 +- tests/test_stability.py | 13 ++++ tests/test_stable_keys.py | 85 ++++++++++++++++++++++++ 10 files changed, 139 insertions(+), 25 deletions(-) diff --git a/docs/features/concurrency/rate-limits.md b/docs/features/concurrency/rate-limits.md index 5e49564..243daa6 100644 --- a/docs/features/concurrency/rate-limits.md +++ b/docs/features/concurrency/rate-limits.md @@ -91,6 +91,8 @@ assert tick() + tick() == 2 # the second call waits about 20 ms `key=` receives the call's arguments (including `self` for methods) and returns a hashable bucket key. Each key gets its own limit. +A bucket key must be made of plain values the encoder accepts: `None`, `bool`, `int`, `float`, `str`, `bytes`, `tuple`, `list`, `dict`, `set`, `frozenset`, enums, dataclasses, named tuples, `datetime`, `decimal`, `uuid`, paths, and objects with a `__cache_key__()` method. Sets, frozensets and dicts are keyed by content, so every process gets the same window for `frozenset({"a", "b"})` whatever its hash seed. Other objects raise `TypeError` when the limit is first used; return a plain key from `key=` instead. Unkeyed limits are unaffected. + ```python from python_wrap import RateLimitExceeded, rate_limit diff --git a/src/python_wrap/_runtime.py b/src/python_wrap/_runtime.py index 2b20e67..fcbb14e 100644 --- a/src/python_wrap/_runtime.py +++ b/src/python_wrap/_runtime.py @@ -37,11 +37,20 @@ def seconds(value: float | str, *, positive: bool = True) -> float: return result -def digest(value: Any) -> str: - """Pickle digest for names and other values that are stable by construction.""" +def name_digest(value: Any) -> str: + """Pickle digest for names only: str or None values fixed in the source code. + + Pickle is not stable for caller values (sets, frozensets, dicts, shared references), + so caller-supplied keys must go through `stable_digest`. Output is kept byte-identical + to the earlier `digest`, so existing store keys do not move. + """ return hashlib.sha256(pickle.dumps(value, protocol=4)).hexdigest() +# Deprecated alias for `name_digest`; kept so existing imports keep working. +digest = name_digest + + def _enc(value: Any, out: list[bytes]) -> None: kind = type(value) if value is None: diff --git a/src/python_wrap/async_cache.py b/src/python_wrap/async_cache.py index 07d2abc..8c66fed 100644 --- a/src/python_wrap/async_cache.py +++ b/src/python_wrap/async_cache.py @@ -30,7 +30,7 @@ from python_wrap import _core, _fork from python_wrap._backend import BackendMonitor -from python_wrap._runtime import digest, stable_digest +from python_wrap._runtime import name_digest, stable_digest from python_wrap.caching import ( _TAG_PREFIX, CacheInfo, @@ -536,7 +536,7 @@ async def versions(names: list[str]) -> dict[str, str] | None: if not tag_async: return _tag_versions(names, tag_client) try: - return {n: _decode(await tag_client.get(_TAG_PREFIX + digest(n))) for n in names} + return {n: _decode(await tag_client.get(_TAG_PREFIX + name_digest(n))) for n in names} except Exception: # unknown versions read as a miss return None @@ -609,7 +609,7 @@ def lease_for(k: Hashable, wait: bool) -> Any: from python_wrap.coordination import Lease return Lease( - f"amemo:{digest(name)}:{stable_digest(k)}", + f"amemo:{name_digest(name)}:{stable_digest(k)}", backend=lock, ttl=lock_ttl, wait=wait, diff --git a/src/python_wrap/caching.py b/src/python_wrap/caching.py index dd31567..92c833c 100644 --- a/src/python_wrap/caching.py +++ b/src/python_wrap/caching.py @@ -28,7 +28,7 @@ ) from python_wrap import _core, _fork -from python_wrap._runtime import digest, stable_digest +from python_wrap._runtime import name_digest, stable_digest __all__ = [ "CacheInfo", @@ -586,7 +586,7 @@ def _tag_versions(names: list[str], client: Any) -> dict[str, str] | None: if client is None: return {n: f"{_tag_epoch[0]}:{_local_tags.get(n, '')}" for n in names} try: - return {n: _decode(client.get(_TAG_PREFIX + digest(n))) for n in names} + return {n: _decode(client.get(_TAG_PREFIX + name_digest(n))) for n in names} except Exception: # an unknown version must read as a miss, never as a hit return None @@ -609,7 +609,7 @@ def invalidate_tags(*names: str, client: Any = None) -> None: token = uuid.uuid4().hex _remember_local(name, token) for target in _tag_client_targets(_tag_clients, _tag_store_owners, client): - target.set(_TAG_PREFIX + digest(name), token) + target.set(_TAG_PREFIX + name_digest(name), token) async def ainvalidate_tags(*names: str, client: Any = None) -> None: @@ -618,7 +618,7 @@ async def ainvalidate_tags(*names: str, client: Any = None) -> None: token = uuid.uuid4().hex _remember_local(name, token) for target in _tag_client_targets(_async_tag_clients, _async_tag_store_owners, client): - await target.set(_TAG_PREFIX + digest(name), token) + await target.set(_TAG_PREFIX + name_digest(name), token) @overload @@ -1005,7 +1005,7 @@ def lease_for(k: Hashable, wait: bool) -> Any: from python_wrap.coordination import Lease return Lease( - f"memo:{digest(name)}:{stable_digest(k)}", + f"memo:{name_digest(name)}:{stable_digest(k)}", backend=lock_backend, ttl=lock_ttl, wait=wait, diff --git a/src/python_wrap/idempotency.py b/src/python_wrap/idempotency.py index 8018cdd..c3b17e6 100644 --- a/src/python_wrap/idempotency.py +++ b/src/python_wrap/idempotency.py @@ -13,7 +13,7 @@ from typing import Any, TypeVar, cast from python_wrap import _core, _fork -from python_wrap._runtime import call_key, digest, seconds +from python_wrap._runtime import call_key, name_digest, seconds from python_wrap.coordination import AlreadyRunning, Lease, LocalLease, _drain __all__ = ["MemoryResultStore", "SqlResultStore", "idempotent"] @@ -164,7 +164,7 @@ def _read(self, conn: Any, key: str) -> tuple[Any] | None: # The table name was validated as an identifier; values are bound parameters. row = conn.execute( self._sql(f"SELECT status, result, expires_at FROM {self.table} WHERE idem_key=:k"), # nosec B608 - {"k": digest(key)}, + {"k": name_digest(key)}, ).first() if row is None or row[0] != "done" or int(row[2]) <= self._now(): return None @@ -172,7 +172,7 @@ def _read(self, conn: Any, key: str) -> tuple[Any] | None: def _claim(self, conn: Any, key: str, owner: str, ttl: float) -> bool: """Insert a ``running`` row, or take over an expired one. False if it is live.""" - params = {"k": digest(key), "o": owner, "e": self._now() + int(ttl * 1000)} + params = {"k": name_digest(key), "o": owner, "e": self._now() + int(ttl * 1000)} try: with conn.begin_nested(): conn.execute( @@ -201,7 +201,7 @@ def _finish(self, conn: Any, key: str, value: Any, ttl: float, owner: str) -> No " WHERE idem_key=:k AND owner=:o" ), { - "k": digest(key), + "k": name_digest(key), "o": owner, "r": self.dumps(value), "e": self._now() + int(ttl * 1000), @@ -215,7 +215,7 @@ def get(self, key: str) -> tuple[Any] | None: def set(self, key: str, entry: tuple[Any], ttl: float) -> None: params = { - "k": digest(key), + "k": name_digest(key), "o": "", "r": self.dumps(entry[0]), "e": self._now() + int(ttl * 1000), @@ -244,7 +244,7 @@ def delete(self, key: str) -> bool: with self.engine.begin() as conn: gone = conn.execute( self._sql(f"DELETE FROM {self.table} WHERE idem_key=:k"), # nosec B608 - {"k": digest(key)}, + {"k": name_digest(key)}, ) return bool(gone.rowcount) @@ -317,7 +317,7 @@ def idempotent( lock = AsyncRedisLock if isinstance(results, AsyncRedisStore) else RedisLock backend = lock( results.client, - prefix="python-wrap:idempotency-locks:" + digest(results.prefix) + ":", + prefix="python-wrap:idempotency-locks:" + name_digest(results.prefix) + ":", ) async def read(k: str) -> Any: diff --git a/src/python_wrap/llm.py b/src/python_wrap/llm.py index c5e09f1..af1c209 100644 --- a/src/python_wrap/llm.py +++ b/src/python_wrap/llm.py @@ -58,7 +58,7 @@ from typing import TYPE_CHECKING, Any, Literal, ParamSpec, Protocol, TypeVar, cast, overload from python_wrap import _core, _fork -from python_wrap._runtime import digest +from python_wrap._runtime import stable_digest from python_wrap.circuit import CircuitBreaker from python_wrap.errors import CircuitOpenError, PythonWrapError, RateLimitExceeded, TimeoutExpired from python_wrap.retry import RetryBudget, retry, retry_after_header @@ -959,7 +959,7 @@ def _scope_key(self, args: tuple[Any, ...], kwargs: dict[str, Any], key: Any) -> if key is _MISSING: assert self.key is not None key = self.key(*args, **kwargs) - return self._qualify(f"key:{digest(key)}") + return self._qualify(f"key:{stable_digest(key)}") run = _RUNS.get().get(self._id) if run is None: raise RuntimeError( @@ -1810,7 +1810,9 @@ def plan(args: tuple[Any, ...], kwargs: dict[str, Any]) -> tuple[str, str, str] if request.get("stream") is True: return None request = {k: v for k, v in request.items() if k not in skip} - exact = prefix + (digest(key(*args, **kwargs)) if key is not None else _hash(request)) + exact = prefix + ( + stable_digest(key(*args, **kwargs)) if key is not None else _hash(request) + ) group = _hash({k: v for k, v in request.items() if k not in _PROMPT_FIELDS}) return exact, group, _prompt_text(request) diff --git a/src/python_wrap/quotas.py b/src/python_wrap/quotas.py index 2796f16..6d87c5e 100644 --- a/src/python_wrap/quotas.py +++ b/src/python_wrap/quotas.py @@ -14,7 +14,7 @@ from python_wrap import _core, _fork from python_wrap._backend import BackendMonitor -from python_wrap._runtime import digest, seconds +from python_wrap._runtime import name_digest, seconds, stable_digest from python_wrap.errors import RateLimitExceeded __all__ = ["AsyncRedisWindow", "Quota", "QuotaExhausted", "RedisWindow", "shared_rate_limit"] @@ -164,10 +164,13 @@ def _fallback(self, key: Any) -> float: return float(self._local.acquire(key)) def _eval_args(self, key: Any) -> tuple[Any, ...]: + # Unkeyed windows keep the store key they have always had (the pickle digest of + # None); caller-supplied keys use the stable encoding. + suffix = name_digest(None) if key is None else stable_digest(key) return ( _WINDOW, 1, - self.key + ":" + digest(key), + self.key + ":" + suffix, self.calls, max(1, math.ceil(self.period * 1000)), uuid.uuid4().hex, diff --git a/src/python_wrap/shared.py b/src/python_wrap/shared.py index b68685a..2d310ac 100644 --- a/src/python_wrap/shared.py +++ b/src/python_wrap/shared.py @@ -16,7 +16,7 @@ from python_wrap import _core, _fork from python_wrap._backend import BackendMonitor -from python_wrap._runtime import digest, seconds +from python_wrap._runtime import name_digest, seconds from python_wrap.coordination import AlreadyRunning, Lease from python_wrap.errors import BulkheadFull @@ -182,7 +182,7 @@ def __init__( if not name: raise ValueError("a shared retry budget needs a name") self.client, self.name = client, name - self.key = prefix + "{" + digest(name) + "}" + self.key = prefix + "{" + name_digest(name) + "}" self._monitor = BackendMonitor("budget", name, on_backend_error, retry_backend_after) def _eval(self, budget: Any, op: str) -> Any: @@ -339,7 +339,7 @@ def _args( count: int = 1, slow: bool = False, ) -> tuple[Any, ...]: - key = self.prefix + "{" + digest(breaker.name) + "}" + key = self.prefix + "{" + name_digest(breaker.name) + "}" return ( 3, key, diff --git a/tests/test_stability.py b/tests/test_stability.py index bfc4f37..c713abb 100644 --- a/tests/test_stability.py +++ b/tests/test_stability.py @@ -161,3 +161,16 @@ def test_every_lua_script_has_a_live_test(): assert known in scripts, known missing = [name for name in scripts if not re.search(rf"\b{name}\b", live)] assert not missing, f"Lua scripts without a live test: {missing}" + + +def test_keyed_window_store_key_is_frozen(): + from python_wrap.quotas import RedisWindow + + class _Client: + def eval(self, *args): + self.key = args[2] + return 0 + + client = _Client() + RedisWindow(client, "pw:win", calls=5, period=1).acquire(frozenset({"a", "b"})) + assert client.key == ("pw:win:75bb2033dc5d38d46d856f13e0fe05fcc2dc000fc4609519abe47786f5ffa438") diff --git a/tests/test_stable_keys.py b/tests/test_stable_keys.py index 000d2b8..19a65eb 100644 --- a/tests/test_stable_keys.py +++ b/tests/test_stable_keys.py @@ -3,11 +3,14 @@ from __future__ import annotations import os +import re import subprocess import sys +from pathlib import Path import pytest +import python_wrap from python_wrap._runtime import call_key, stable_digest _SNIPPET = ( @@ -40,3 +43,85 @@ def f(x: object) -> None: ... with pytest.raises(TypeError, match=r"argument 'x'.*key="): call_key(f, None, (object(),), {}) + + +# Names whose pickle digest is fixed in the source: each entry is the argument text of a +# name_digest(...) call that is allowed, per module. Caller values must use stable_digest. +# Idempotency keys are the strings call_key returns (already stable), not raw caller values. +_NAME_CALLS = { + "_runtime.py": {"value: Any"}, + "shared.py": {"name", "breaker.name"}, + "caching.py": {"n", "name"}, + "async_cache.py": {"n", "name"}, + "idempotency.py": {"key", "results.prefix"}, + "quotas.py": {"None"}, +} +_BARE_DIGEST = re.compile(r"(? None: + src = Path(python_wrap.__file__).parent + bare = [] + seen: dict[str, set[str]] = {} + for path in sorted(src.rglob("*.py")): + text = path.read_text(encoding="utf-8") + for number, line in enumerate(text.splitlines(), 1): + if _BARE_DIGEST.search(line): + bare.append(f"{path.name}:{number}: {line.strip()}") + for match in _NAME_DIGEST.finditer(text): + seen.setdefault(path.name, set()).add(match[1].strip()) + assert bare == [], "pickle digest called without name_digest" + for name, args in seen.items(): + assert args <= _NAME_CALLS[name], f"{name}: unexpected name_digest argument {args}" + + +_WINDOW_SNIPPET = ( + "from python_wrap.quotas import RedisWindow\n" + "class _Client:\n" + " def eval(self, *args):\n" + " print(args[2])\n" + " return 0\n" + "RedisWindow(_Client(), 'pw:win', calls=5, period=1).acquire(frozenset({'a', 'b'}))\n" +) + +_LLM_SNIPPET = ( + "from python_wrap.llm import Budget\n" + "budget = Budget(tokens=10, per='key', key=lambda: 'x')\n" + "print(budget._scope_key((), {}, frozenset({'a', 'b'})))\n" +) + + +def _run_snippet(snippet: str, seed: str) -> str: + env = {**os.environ, "PYTHONHASHSEED": seed} + return subprocess.run( + [sys.executable, "-c", snippet], env=env, capture_output=True, text=True, check=True + ).stdout + + +def test_window_key_is_stable_for_frozenset_across_hash_seeds() -> None: + outputs = {_run_snippet(_WINDOW_SNIPPET, seed) for seed in ("1", "2", "12345")} + assert len(outputs) == 1 + + +def test_llm_scope_key_is_stable_across_hash_seeds() -> None: + outputs = {_run_snippet(_LLM_SNIPPET, seed) for seed in ("1", "2", "12345")} + assert len(outputs) == 1 + + +def test_unkeyed_window_key_is_unchanged() -> None: + from python_wrap.quotas import RedisWindow + + class _Client: + def eval(self, *args: object) -> int: + self.key = args[2] + return 0 + + client = _Client() + RedisWindow(client, "pw:win", calls=5, period=1).acquire() + assert client.key == ("pw:win:9c298d589a2158eb513cb52191144518a2acab2cb0c04f1df14fca0f712fa4a1") + + +def test_equal_tuples_with_shared_and_distinct_members_hash_alike() -> None: + shared = ["a"] + assert stable_digest((shared, shared)) == stable_digest((["a"], ["a"])) From 397c888f449751d55fa658b8f49fc8935739fca0 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 27 Nov 2026 08:24:20 +0200 Subject: [PATCH 10/38] perf: shared breaker answers from the process cache without tasks - A closed or open state of a shared breaker is answered inline from the process cache; the async shared breaker creates no task per call. - The open state is cached until its recovery time, for at most min(wait, state_ttl * 5) seconds. Rejections answered locally are not added to the store's total_rejected. - Half-open is never cached; reset and force_open always reach the store. - Performance page updated from a benchmark run on CPython 3.14.7. --- .../resilience/multi-process-breakers.md | 22 +++ docs/project/performance.md | 17 +- src/python_wrap/circuit.py | 64 ++++--- src/python_wrap/shared.py | 58 +++++- tests/test_breaker_fast_path.py | 168 ++++++++++++++++++ tests/test_redis_backends.py | 34 ++++ 6 files changed, 329 insertions(+), 34 deletions(-) create mode 100644 tests/test_breaker_fast_path.py diff --git a/docs/features/resilience/multi-process-breakers.md b/docs/features/resilience/multi-process-breakers.md index 420ab02..06c9612 100644 --- a/docs/features/resilience/multi-process-breakers.md +++ b/docs/features/resilience/multi-process-breakers.md @@ -67,6 +67,28 @@ Notes: Use `RedisBreakerState(client)` when instances run on different machines (see [shared limits](../concurrency/shared-limits.md)). It has the same contract and uses the Redis server's clock. +### What is cached, and for how long + +With `state_ttl` above zero (the default is 1 second), a process answers some calls from memory instead of the store: + +- **Closed**: calls are admitted locally and successes are batched to the store (see the class docstring). +- **Open**: rejections are answered locally until the recovery time the store reported. The cached open + state is kept for at most `min(wait, state_ttl * 5)` seconds after the store's answer, where `wait` is the remaining + recovery time. With the default `state_ttl`, that is at most 5 seconds. +- **Half-open**: never cached. Every admission to the trial phase goes to the store, which grants or refuses the trial. +- **Reset and force-open**: always sent to the store, which overwrites the cached state. + +The staleness bound is the trade. If another process resets the breaker, this process keeps rejecting for up to +`min(wait, state_ttl * 5)` seconds after it last heard the open state, even though the breaker is closed in the store. +Lower `state_ttl` to shorten that window; `state_ttl=0` sends every call to the store and disables both caches. + +Local rejections do not reach the store, so `total_rejected` in the store (and `stats.rejected` read from a +shared breaker) undercounts the rejections that were answered from the cache. Count rejections in your own +telemetry with the `circuit.rejected` event if you need exact numbers. + +Calls answered from the cache also skip the thread or task that an async wrapper would otherwise start, so a +rejected call on an open shared breaker costs no store round trip and no thread hop. + ## Celery prefork Each prefork child is a separate process, so by default each has its own breaker and one task failing does not warn diff --git a/docs/project/performance.md b/docs/project/performance.md index 9a4aad0..5ff175a 100644 --- a/docs/project/performance.md +++ b/docs/project/performance.md @@ -63,15 +63,20 @@ Measured on an Apple M2 Pro (10 cores, 16 GB), macOS, CPython 3.14.7, full run Shared backends, measured with an in-memory stand-in for the Redis client, so the numbers show what the library adds around a store round trip, not the network -(`python benchmarks/run.py --filter shared`, CPython 3.11 on the same machine): +(`python benchmarks/run.py --filter shared`, CPython 3.14.7 on the same machine): | Decorator | sync ns/call | async ns/call | | --- | ---: | ---: | -| circuit_breaker (shared) | 2,878 | 85,428 | -| circuit_breaker (shared, async via thread) | - | 145,410 | -| Bulkhead(8) (shared) | 36,109 | 117,264 | -| Bulkhead(8) (shared, async via thread) | - | 191,379 | -| rate_limit (shared) | 2,960 | 3,315 | +| circuit_breaker (shared) | 3,042 | 3,031 | +| circuit_breaker (shared, async via thread) | - | 3,086 | +| Bulkhead(8) (shared) | 49,788 | 131,548 | +| Bulkhead(8) (shared, async via thread) | - | 218,877 | +| rate_limit (shared) | 3,604 | 4,295 | + +The breaker rows changed with the open-state cache and the inline cached path: the same run +of the previous release (its code at HEAD, same interpreter) measured the async breaker at +93,471 ns and through a thread at 158,961 ns, with the sync row at 3,528 ns. The other rows +were measured in the same run and are shown as they came out of it. Against a real Redis (local server, CPython 3.11, Apple M2 Pro), from `python benchmarks/run.py --filter redis --redis-url redis://localhost:6379/0` (needs the diff --git a/src/python_wrap/circuit.py b/src/python_wrap/circuit.py index 1daa364..bac11c6 100644 --- a/src/python_wrap/circuit.py +++ b/src/python_wrap/circuit.py @@ -408,16 +408,33 @@ def _try( raise TypeError( f"circuit {self.name} has an async backend; use the async form of this call" ) + local = self._local_answer(operation, generation, trial, slow) + if local is not None: + return local return self._monitor.call( operation, lambda: self._remote(operation, generation, trial, slow), lambda: None ) + def _local_answer( + self, operation: str, generation: int = 0, trial: bool = False, slow: bool = False + ) -> dict[str, Any] | None: + """The backend's cached answer, observed like a store answer; None if the store must.""" + backend, monitor = self.backend, self._monitor + try_local = getattr(backend, "try_local", None) + if try_local is None or monitor is None or monitor._skipping(): + return None + data = try_local(self, operation, generation, trial, slow) + return None if data is None else self._observe(data) + async def _atry( self, operation: str, generation: int = 0, trial: bool = False, slow: bool = False ) -> dict[str, Any] | None: """`_try` for an async backend: the store round trip is awaited.""" if self._monitor is None: return None + local = self._local_answer(operation, generation, trial, slow) + if local is not None: + return local async def run() -> dict[str, Any]: extra = {"slow": True} if slow else {} # backends without slow-call support still work @@ -755,7 +772,10 @@ async def _acall(self, func: Callable[..., Any], args: Any, kwargs: Any) -> Any: # Synchronous network admission cannot be abandoned on cancellation: a late # successful admission would otherwise strand a half-open trial reservation. - if self.backend is not None: + local = self._local_answer("admit") if self.backend is not None else None + if local is not None: # answered from the cache: no task, no thread, no await + generation, trial = self._admit(local) + elif self.backend is not None: admission = self._offload("_acquire") try: generation, trial = await asyncio.shield(admission) @@ -773,15 +793,18 @@ async def _acall(self, func: Callable[..., Any], args: Any, kwargs: Any) -> Any: except BaseException as exc: slow = self._slow(started) if self.backend is not None: - settlement = self._offload("_settle", generation, trial, exc, slow) - _, error, cancelled = await _drain(settlement) - if cancelled: - raise asyncio.CancelledError from None - if error is not None: - self._log.error( - "circuit outcome bookkeeping failed; preserving original error", - exc_info=(type(error), error, error.__traceback__), - ) + # A failure always reaches the store; an uncounted exception may release a + # trial slot that the cache can settle locally. + if self._counted(exc) or self._local_answer("neutral", generation, trial) is None: + settlement = self._offload("_settle", generation, trial, exc, slow) + _, error, cancelled = await _drain(settlement) + if cancelled: + raise asyncio.CancelledError from None + if error is not None: + self._log.error( + "circuit outcome bookkeeping failed; preserving original error", + exc_info=(type(error), error, error.__traceback__), + ) else: try: self._settle(generation, trial, exc, slow) @@ -792,16 +815,17 @@ async def _acall(self, func: Callable[..., Any], args: Any, kwargs: Any) -> Any: raise slow = self._slow(started) if self.backend is not None: - success = self._offload("_success", generation, trial, slow) - _, error, cancelled = await _drain(success) - if cancelled: - raise asyncio.CancelledError - if error is not None: - # The call already happened: log, never replace its result. - self._log.error( - "circuit outcome bookkeeping failed; returning the result", - exc_info=(type(error), error, error.__traceback__), - ) + if self._local_answer("success", generation, trial, slow) is None: + success = self._offload("_success", generation, trial, slow) + _, error, cancelled = await _drain(success) + if cancelled: + raise asyncio.CancelledError + if error is not None: + # The call already happened: log, never replace its result. + self._log.error( + "circuit outcome bookkeeping failed; returning the result", + exc_info=(type(error), error, error.__traceback__), + ) else: try: self._success(generation, trial, slow) diff --git a/src/python_wrap/shared.py b/src/python_wrap/shared.py index 2d310ac..3003d48 100644 --- a/src/python_wrap/shared.py +++ b/src/python_wrap/shared.py @@ -263,9 +263,13 @@ def _reset_after_fork(self) -> None: self._cache.clear() def _local( - self, breaker: Any, operation: str, trial: bool, slow: bool = False + self, breaker: Any, operation: str, trial: bool, slow: bool = False, peek: bool = False ) -> tuple[Any, int, int]: - """``(answer or None, successes to flush, their generation)`` from the cache.""" + """``(answer or None, successes to flush, their generation)`` from the cache. + + ``peek`` answers only: when the store or a flush is due it changes nothing and + returns ``(None, 0, 0)``, so the caller's normal path does the flush itself. + """ if self.state_ttl == 0 or trial or slow: # a slow call can open a rated breaker return None, 0, 0 now = _core.monotonic() @@ -274,14 +278,26 @@ def _local( if entry is None: return None, 0, 0 data, read_at, pending, flushed = entry + if data["state"] == "open": + # Open entries keep the local rejection deadline in the fourth slot. + if operation == "admit" and now < flushed: + wait = math.ceil((flushed - now) * 1000) + return dict(data, admitted=0, trial=0, wait=wait, old="open"), 0, 0 + if not peek: + del self._cache[breaker.name] + return None, 0, 0 generation = data["generation"] if operation in {"failure", "reset", "force_open"} or now - read_at >= self.state_ttl: # The store answers; a failure (or a refresh) carries batched successes first. - entry[2], entry[3] = 0, now - return None, 0 if operation in {"reset", "force_open"} else pending, generation + if not peek: + entry[2], entry[3] = 0, now + return None, 0 if operation in {"reset", "force_open"} else pending, generation + return None, 0, 0 if operation == "success": pending += 1 if pending >= self.flush_every or now - flushed >= self.flush_interval: + if peek: + return None, 0, 0 entry[2], entry[3] = 0, now return dict(data, old=data["state"]), pending, generation entry[2] = pending @@ -289,14 +305,40 @@ def _local( answer["total_successes"] = data["total_successes"] + entry[2] return answer, 0, 0 + def try_local( + self, + breaker: Any, + operation: str, + generation: int = 0, + trial: bool = False, + slow: bool = False, + ) -> dict[str, Any] | None: + """The cached answer for ``operation``, or None when the store must answer. + + Never touches the store and never flushes: when a flush is due it returns None and + leaves the pending successes in place, so ``operate`` performs the flush. + ``AsyncRedisBreakerState`` inherits this method, since it needs no await. + """ + data, _, _ = self._local(breaker, operation, trial, slow, peek=True) + return data # type: ignore[no-any-return] + def _remember(self, breaker: Any, data: dict[str, Any]) -> dict[str, Any]: if self.state_ttl: + now = _core.monotonic() with self._lock: + old = self._cache.get(breaker.name) if data["state"] == "closed": - old = self._cache.get(breaker.name) - pending, flushed = (old[2], old[3]) if old else (0, _core.monotonic()) - self._cache[breaker.name] = [data, _core.monotonic(), pending, flushed] - else: + if old is not None and old[0]["state"] == "closed": + pending, flushed = old[2], old[3] + else: + pending, flushed = 0, now + self._cache[breaker.name] = [data, now, pending, flushed] + elif data["state"] == "open" and data["wait"] > 0: + # Rejections stay local until recovery, but never for longer than + # state_ttl * 5: a reset by another process is seen within that bound. + horizon = min(data["wait"] / 1000, self.state_ttl * 5) + self._cache[breaker.name] = [data, now, 0, now + horizon] + else: # half-open trials and trips without a recovery time go to the store self._cache.pop(breaker.name, None) return data diff --git a/tests/test_breaker_fast_path.py b/tests/test_breaker_fast_path.py new file mode 100644 index 0000000..8200322 --- /dev/null +++ b/tests/test_breaker_fast_path.py @@ -0,0 +1,168 @@ +"""Breaker fast path: cached answers skip tasks, threads and store round trips.""" + +from __future__ import annotations + +import asyncio +import contextlib +from typing import Any + +import pytest + +from python_wrap.circuit import CircuitBreaker +from python_wrap.errors import CircuitOpenError +from python_wrap.shared import AsyncRedisBreakerState, RedisBreakerState +from python_wrap.testing import fake_clock + + +def row(state: str = "closed", admitted: int = 1, wait: int = 0, trial: int = 0) -> list[Any]: + return [admitted, state, 1, trial, wait, 0, 0, 0, 0, 0, state] + + +class Store: + """A sync Redis stand-in that records each breaker operation it is asked to run.""" + + def __init__(self, answer: list[Any] | None = None) -> None: + self.answer = answer or row() + self.ops: list[str] = [] + + def eval(self, script: str, numkeys: int, *args: Any) -> list[Any]: + self.ops.append(args[3]) # keys first, then the operation + return self.answer + + +class AsyncStore: + """A redis.asyncio stand-in: the same bookkeeping, with an awaited ``eval``.""" + + def __init__(self) -> None: + self.answer = row() + self.ops: list[str] = [] + + async def eval(self, script: str, numkeys: int, *args: Any) -> list[Any]: + await asyncio.sleep(0) + self.ops.append(args[3]) + return self.answer + + +def test_async_closed_breaker_creates_no_tasks_when_cached(monkeypatch: pytest.MonkeyPatch) -> None: + created = 0 + + def count(original: Any) -> Any: + def wrapper(*args: Any, **kwargs: Any) -> Any: + nonlocal created + created += 1 + return original(*args, **kwargs) + + return wrapper + + loop = asyncio.new_event_loop() + monkeypatch.setattr(asyncio, "ensure_future", count(asyncio.ensure_future)) + monkeypatch.setattr(asyncio, "create_task", count(asyncio.create_task)) + with contextlib.suppress(AttributeError, TypeError): # a C loop has no instance attribute + monkeypatch.setattr(loop, "create_task", count(loop.create_task)) + + async def work() -> None: + store = AsyncStore() + state = AsyncRedisBreakerState(store, state_ttl=1, flush_every=100_000) + breaker = CircuitBreaker(name="async-hot", backend=state) + + async def ok() -> int: + return 1 + + for _ in range(1000): + assert await breaker.call(ok) == 1 + assert len(store.ops) < 10 + + try: + with fake_clock(): + loop.run_until_complete(work()) + finally: + loop.close() + assert created < 10 + + +def test_sync_client_in_async_code_uses_no_thread_when_cached( + monkeypatch: pytest.MonkeyPatch, +) -> None: + threads = 0 + + def counting_to_thread(*args: Any, **kwargs: Any) -> Any: + nonlocal threads + threads += 1 + raise AssertionError("asyncio.to_thread must not run for a cached breaker") + + store = Store() + state = RedisBreakerState(store, state_ttl=1, flush_every=100_000) + breaker = CircuitBreaker(name="sync-client", backend=state) + with fake_clock(): + breaker.call(lambda: 1) # warm the cache from sync code, before any loop runs + monkeypatch.setattr(asyncio, "to_thread", counting_to_thread) + + async def ok() -> int: + return 1 + + async def work() -> None: + for _ in range(1000): + assert await breaker.call(ok) == 1 + + asyncio.run(work()) + assert threads == 0 + + +def test_open_state_rejects_locally_until_recovery() -> None: + store = Store(row("open", admitted=0, wait=1000)) + breaker = CircuitBreaker(name="open-local", backend=RedisBreakerState(store, state_ttl=10)) + with fake_clock() as clock: + with pytest.raises(CircuitOpenError): + breaker.call(lambda: 1) # the store answers and the open state is cached + commands = len(store.ops) + for _ in range(100): + with pytest.raises(CircuitOpenError) as info: + breaker.call(lambda: 1) + assert len(store.ops) == commands # served locally + assert 0 < info.value.retry_after <= 1.0 + store.answer = row("closed") # recovery: the cached rejection expires + clock.advance(1.5) + assert breaker.call(lambda: 7) == 7 + assert store.ops[-1] == "admit" + + +def test_open_cache_bounded_by_state_ttl_multiple() -> None: + store = Store(row("open", admitted=0, wait=60_000)) # the store says a minute + state = RedisBreakerState(store, state_ttl=0.1) # so the cache keeps at most 0.5 s + breaker = CircuitBreaker(name="bounded", backend=state) + with fake_clock() as clock: + with pytest.raises(CircuitOpenError): + breaker.call(lambda: 1) + clock.advance(0.4) + with pytest.raises(CircuitOpenError): + breaker.call(lambda: 1) + assert store.ops == ["admit"] # still local + store.answer = row("closed") # another process reset the breaker + clock.advance(0.2) + assert breaker.call(lambda: 1) == 1 # the bound expired: the store is asked again + assert store.ops == ["admit", "admit"] + + +def test_half_open_is_not_cached() -> None: + store = Store(row("half_open", trial=1)) + state = RedisBreakerState(store, state_ttl=10) + breaker = CircuitBreaker(name="probe", backend=state) + with fake_clock(): + breaker.call(lambda: 1) + breaker.call(lambda: 1) + assert store.ops.count("admit") == 2 # every admission to half-open reaches the store + + +def test_reset_overwrites_cached_open() -> None: + store = Store(row("open", admitted=0, wait=60_000)) + breaker = CircuitBreaker(name="reset-open", backend=RedisBreakerState(store, state_ttl=10)) + with fake_clock(): + with pytest.raises(CircuitOpenError): + breaker.call(lambda: 1) + store.answer = row("closed") + breaker.reset() + assert store.ops[-1] == "reset" # never answered from the cache + before = len(store.ops) + for _ in range(10): + assert breaker.call(lambda: 1) == 1 + assert len(store.ops) == before # the closed answer replaced the cached open one diff --git a/tests/test_redis_backends.py b/tests/test_redis_backends.py index 439a67a..5ce6e05 100644 --- a/tests/test_redis_backends.py +++ b/tests/test_redis_backends.py @@ -464,3 +464,37 @@ def boom() -> None: breaker._acquire() # the only trial slot is in use assert rejected.value.retry_after > 0 breaker._release(generation, trial) + + +def test_open_breaker_rejects_locally_with_few_store_commands(redis_client): + class Recording: + """Forwards to the live client and counts every command sent to the store.""" + + def __init__(self, inner): + self.inner, self.commands = inner, 0 + + def eval(self, script, count, *args): + self.commands += 1 + return self.inner.eval(script, count, *args) + + def __getattr__(self, name): + return getattr(self.inner, name) + + rec = Recording(redis_client) + state = RedisBreakerState(rec, "cached-open:", state_ttl=1) + breaker = CircuitBreaker( + name="cached-open-name", failure_threshold=1, recovery_timeout=30, backend=state + ) + + def boom(): + raise ConnectionError("down") + + with pytest.raises(ConnectionError): + breaker.call(boom) + with pytest.raises(CircuitOpenError): + breaker.call(lambda: "never") # the store answers once and the open state is cached + before = rec.commands + for _ in range(1000): + with pytest.raises(CircuitOpenError): + breaker.call(lambda: "never") + assert rec.commands - before < 10 From dd8ec09cb54ba9c64c276eb9ff42fda53d4f0e4e Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 27 Nov 2026 08:35:10 +0200 Subject: [PATCH 11/38] perf: Redis scripts run via EVALSHA; retry budget batches deposits - All Redis Lua scripts run through python_wrap._scripts.Script: EVALSHA first, reload on NOSCRIPT. Script text and key formats are unchanged. - RedisRetryBudget batches deposits (flush_every=1000 or flush_interval=1.0 s). Withdrawals and totals flush first. A deposit never raises; a store error adds its count to the local budget. - The budget script accepts an optional deposit count; four-argument callers keep working. --- benchmarks/run.py | 13 ++- .../features/resilience/presets-and-doctor.md | 8 ++ docs/features/resilience/retry.md | 7 ++ docs/llms-full.txt | 10 +- src/python_wrap/_scripts.py | 58 ++++++++++ src/python_wrap/agents.py | 11 +- src/python_wrap/coordination.py | 10 +- src/python_wrap/llm.py | 4 +- src/python_wrap/llm_shared.py | 13 ++- src/python_wrap/quotas.py | 13 ++- src/python_wrap/retry.py | 4 +- src/python_wrap/shared.py | 105 ++++++++++++------ tests/test_async_backends.py | 4 +- tests/test_backend_recovered.py | 3 +- tests/test_redis_backends.py | 90 +++++++++++++++ tests/test_shared_presets.py | 74 +++++++++++- 16 files changed, 369 insertions(+), 58 deletions(-) create mode 100644 src/python_wrap/_scripts.py diff --git a/benchmarks/run.py b/benchmarks/run.py index acb4ddc..43d64b6 100644 --- a/benchmarks/run.py +++ b/benchmarks/run.py @@ -42,9 +42,10 @@ from python_wrap.coordination import AsyncRedisSemaphore, RedisSemaphore from python_wrap.devtools import deprecate, mock_data from python_wrap.logs import audit, log_args +from python_wrap.presets import http_client from python_wrap.quotas import AsyncRedisWindow, RedisWindow, shared_rate_limit -from python_wrap.retry import retry -from python_wrap.shared import AsyncRedisBreakerState, RedisBreakerState +from python_wrap.retry import RetryBudget, retry +from python_wrap.shared import AsyncRedisBreakerState, RedisBreakerState, RedisRetryBudget from python_wrap.timing import timing from python_wrap.validation import check_type, enforce_types, validate_args @@ -168,9 +169,12 @@ def _redis_cases(url: str) -> list[Case]: ("circuit_breaker", _shared_breaker), ("Bulkhead(8)", _shared_bulkhead), ("rate_limit", _shared_window), + ("retry_budget", _shared_budget), ] + preset = http_client("bench", shared=client) return [ *(Case(f"{name} (redis)", lambda fn, b=build: b(client)(fn), None) for name, build in rows), + Case("http_client (shared)", lambda fn: preset(fn), None), Case("memoize (redis hit)", lambda fn: memoize(store=store, ttl=60)(fn), None), ] @@ -190,6 +194,11 @@ def _shared_window(client: Any) -> Callable[[Any], Any]: return shared_rate_limit(kind(client, "bench", calls=10**9, period=1)) +def _shared_budget(client: Any) -> Callable[[Any], Any]: + budget = RetryBudget(ratio=0.2, min_per_second=5, backend=RedisRetryBudget(client, "bench")) + return retry(max_attempts=3, delay=0, budget=budget, logger=LOG) + + def cases() -> list[Case]: out = [ _case("timing (logging off)", lambda: timing(logger=LOG)), diff --git a/docs/features/resilience/presets-and-doctor.md b/docs/features/resilience/presets-and-doctor.md index f8f5db2..ca3ec16 100644 --- a/docs/features/resilience/presets-and-doctor.md +++ b/docs/features/resilience/presets-and-doctor.md @@ -81,6 +81,14 @@ purpose. A bare client wraps `RedisBreakerState`, `RedisWindow`, `RedisSemaphore Layers built this way report `shared=True`, so PW012 stays quiet. Store failures follow [`on_backend_error`](../concurrency/shared-limits.md#when-the-shared-store-is-down). +What `shared=` costs per call: the breaker reads its closed state from Redis at most once +per `state_ttl` (successes are batched), and the retry budget counts each first attempt +in memory and sends the deposits in batches (`flush_every=1000` or `flush_interval=1.0` +seconds), so a deposit costs one round trip per 1000 calls under load, or one per second +when traffic is slow, instead of one per call. Withdrawals, which happen only on a retry, go +to Redis at once. Every script runs with `EVALSHA` and is sent in full only after a +`NOSCRIPT` reply. + ## Explaining a policy `Policy.explain()` (or `python_wrap.doctor.explain`) lists the layers outermost first with diff --git a/docs/features/resilience/retry.md b/docs/features/resilience/retry.md index 58bf96f..26e3c7d 100644 --- a/docs/features/resilience/retry.md +++ b/docs/features/resilience/retry.md @@ -270,6 +270,13 @@ assert stats is not None and stats.budget_exhausted > 0 `budget.stats` returns a `RetryBudgetStats` with `requests` and `retries` (in the current window), `rejected` (refused since creation or the last `reset()`) and `allowed` (retries it would grant right now). One budget is thread-safe and can be shared across threads, event loops, `retry` decorators and `retrying` blocks; it never blocks or sleeps. To give every retry in the project the same budget, set it once with `configure(retry={"budget": RetryBudget()})` before decorating; pass `budget=None` to opt a function out. +A budget that lives in Redis (`RedisRetryBudget`, or a preset built with `shared=`) batches +its deposits: a first attempt is counted in memory and sent with the next batch, at +`flush_every` deposits or `flush_interval` seconds, whichever comes first. Withdrawals and +`stats` flush the batch first, so a retry always sees every call made in this process. A +deposit never raises; if the store is down its count moves to the local budget. An idle +process can hold up to `flush_every - 1` deposits until its next retry or `stats` read. + !!! tip "One budget per dependency" Share a budget between the calls that hit the same service. A budget shared by unrelated services lets a failing one spend the retries the others need. diff --git a/docs/llms-full.txt b/docs/llms-full.txt index 339ec6b..42168fc 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -3663,6 +3663,14 @@ purpose. A bare client wraps `RedisBreakerState`, `RedisWindow`, `RedisSemaphore Layers built this way report `shared=True`, so PW012 stays quiet. Store failures follow [`on_backend_error`](../concurrency/shared-limits.md#when-the-shared-store-is-down). +What `shared=` costs per call: the breaker reads its closed state from Redis at most once +per `state_ttl` (successes are batched), and the retry budget counts each first attempt +in memory and sends the deposits in batches (`flush_every=1000` or `flush_interval=1.0` +seconds), so a deposit costs one round trip per 1000 calls under load, or one per second +when traffic is slow, instead of one per call. Withdrawals, which happen only on a retry, go +to Redis at once. Every script runs with `EVALSHA` and is sent in full only after a +`NOSCRIPT` reply. + ### Explaining a policy `Policy.explain()` (or `python_wrap.doctor.explain`) lists the layers outermost first with @@ -5189,7 +5197,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Split a name into lowercase word segments. - `python_wrap.shared` Redis coordination backends for circuit breakers and bulkheads. -- `python_wrap.shared.RedisRetryBudget`: `RedisRetryBudget(client: Any, name: str, *, prefix: str = 'python-wrap:budget:', on_backend_error: str | None = None, retry_backend_after: float = 1.0)` +- `python_wrap.shared.RedisRetryBudget`: `RedisRetryBudget(client: Any, name: str, *, prefix: str = 'python-wrap:budget:', on_backend_error: str | None = None, retry_backend_after: float = 1.0, flush_interval: float = 1.0, flush_every: int = 1000)` A `RetryBudget` backend that counts requests and retries in Redis. - `python_wrap.shared.SharedBackends`: `SharedBackends(client: Any = None, breaker_state: Any = None, window: Any = None, semaphore: Any = None, budget: Any = None)` The shared stores a preset or policy uses, built from one Redis client. diff --git a/src/python_wrap/_scripts.py b/src/python_wrap/_scripts.py new file mode 100644 index 0000000..2c749d4 --- /dev/null +++ b/src/python_wrap/_scripts.py @@ -0,0 +1,58 @@ +"""Lua scripts sent to Redis by hash: ``EVALSHA`` first, the full source on ``NOSCRIPT``. + +A `Script` keeps the source and its SHA-1. Each call sends only the 40-character hash +when the server already has the script; the server answers ``NOSCRIPT`` after a restart +or ``SCRIPT FLUSH``, and the source is then sent once with ``EVAL``, which also caches +it. A client without ``evalsha`` (a minimal or proxied client) always uses ``EVAL``. +""" + +from __future__ import annotations + +import hashlib +from typing import Any + +__all__ = ["Script"] + + +def _no_script(exc: Exception) -> bool: + """True for Redis's NOSCRIPT reply (redis-py: NoScriptError, "No matching script").""" + text = str(exc) + return type(exc).__name__ == "NoScriptError" or "NOSCRIPT" in text or "No matching" in text + + +class Script: + """A Lua script with its SHA-1, run with ``EVALSHA`` and reloaded on ``NOSCRIPT``. + + Args: + source: The Lua source. Its bytes define the hash, so any edit changes the id. + """ + + __slots__ = ("sha", "source") + + def __init__(self, source: str) -> None: + self.source = source + self.sha = hashlib.sha1(source.encode(), usedforsecurity=False).hexdigest() + + def run(self, client: Any, numkeys: int, *args: Any) -> Any: + """Run the script on a synchronous client; ``args`` are its keys then its arguments.""" + evalsha = getattr(client, "evalsha", None) + if evalsha is None: + return client.eval(self.source, numkeys, *args) + try: + return evalsha(self.sha, numkeys, *args) + except Exception as exc: + if not _no_script(exc): + raise + return client.eval(self.source, numkeys, *args) + + async def arun(self, client: Any, numkeys: int, *args: Any) -> Any: + """`run` for an ``redis.asyncio`` client: the round trip is awaited.""" + evalsha = getattr(client, "evalsha", None) + if evalsha is None: + return await client.eval(self.source, numkeys, *args) + try: + return await evalsha(self.sha, numkeys, *args) + except Exception as exc: + if not _no_script(exc): + raise + return await client.eval(self.source, numkeys, *args) diff --git a/src/python_wrap/agents.py b/src/python_wrap/agents.py index 80805c5..10efd41 100644 --- a/src/python_wrap/agents.py +++ b/src/python_wrap/agents.py @@ -47,6 +47,7 @@ from python_wrap import _core, _fork from python_wrap._runtime import seconds as _parse_seconds +from python_wrap._scripts import Script from python_wrap.errors import PythonWrapError, TimeoutExpired from python_wrap.timeouts import CancelToken, _current_token @@ -1192,6 +1193,7 @@ def close(self) -> None: end return redis.call('HGET',KEYS[1],'data') """ +_REDIS_CLAIM_SCRIPT = Script(_REDIS_CLAIM) _REDIS_SETTLE = """ if redis.call('HGET',KEYS[1],'owner')==ARGV[1] then @@ -1201,6 +1203,7 @@ def close(self) -> None: end return 0 """ +_REDIS_SETTLE_SCRIPT = Script(_REDIS_SETTLE) class RedisEffectStore: @@ -1247,8 +1250,8 @@ def get(self, key: str, /) -> EffectRecord | None: return self._decode(self.client.hget(self._key(key), "data")) def claim(self, record: EffectRecord, ttl: float, expect: str | None, /) -> EffectRecord | None: - found = self.client.eval( - _REDIS_CLAIM, + found = _REDIS_CLAIM_SCRIPT.run( + self.client, 1, self._key(record.key), expect or "", @@ -1259,8 +1262,8 @@ def claim(self, record: EffectRecord, ttl: float, expect: str | None, /) -> Effe return None if found is None or found is False else self._decode(found) def settle(self, record: EffectRecord, ttl: float, /) -> bool: - done = self.client.eval( - _REDIS_SETTLE, + done = _REDIS_SETTLE_SCRIPT.run( + self.client, 1, self._key(record.key), record.owner, diff --git a/src/python_wrap/coordination.py b/src/python_wrap/coordination.py index a23cff6..a795e06 100644 --- a/src/python_wrap/coordination.py +++ b/src/python_wrap/coordination.py @@ -15,6 +15,7 @@ from python_wrap import _core, _fork from python_wrap._runtime import call_key, seconds +from python_wrap._scripts import Script __all__ = [ "AlreadyRunning", @@ -104,6 +105,7 @@ def _validate_request(key: str, token: str, ttl: float, limit: int) -> None: redis.call('PEXPIRE',KEYS[1],math.max(1,tonumber(last[2])-now)) return 1 """ +_LEASE_SCRIPT = Script(_LEASE) class RedisLock: @@ -121,8 +123,8 @@ def __init__(self, client: Any, prefix: str = "python-wrap:lease:") -> None: def _call(self, op: str, key: str, token: str, ttl: float, limit: int = 1) -> bool: _validate_request(key, token, ttl, limit) return bool( - self.client.eval( - _LEASE, 1, self.prefix + key, op, token, max(1, math.ceil(ttl * 1000)), limit + _LEASE_SCRIPT.run( + self.client, 1, self.prefix + key, op, token, max(1, math.ceil(ttl * 1000)), limit ) ) @@ -152,8 +154,8 @@ async def _call( # type: ignore[override] ) -> bool: _validate_request(key, token, ttl, limit) return bool( - await self.client.eval( - _LEASE, 1, self.prefix + key, op, token, max(1, math.ceil(ttl * 1000)), limit + await _LEASE_SCRIPT.arun( + self.client, 1, self.prefix + key, op, token, max(1, math.ceil(ttl * 1000)), limit ) ) diff --git a/src/python_wrap/llm.py b/src/python_wrap/llm.py index af1c209..946722b 100644 --- a/src/python_wrap/llm.py +++ b/src/python_wrap/llm.py @@ -59,6 +59,7 @@ from python_wrap import _core, _fork from python_wrap._runtime import stable_digest +from python_wrap._scripts import Script from python_wrap.circuit import CircuitBreaker from python_wrap.errors import CircuitOpenError, PythonWrapError, RateLimitExceeded, TimeoutExpired from python_wrap.retry import RetryBudget, retry, retry_after_header @@ -747,6 +748,7 @@ def delete(self, key: str) -> None: redis.call('PEXPIRE',KEYS[1],ARGV[3]) end return {t, tostring(u)} """ +_REDIS_ADD_SCRIPT = Script(_REDIS_ADD) class RedisBudgetBackend: @@ -772,7 +774,7 @@ def _key(self, key: str) -> str: def add(self, key: str, tokens: int, usd: float, ttl: float | None) -> tuple[int, float]: millis = 0 if ttl is None else max(1, math.ceil(ttl * 1000)) - result = self.client.eval(_REDIS_ADD, 1, self._key(key), tokens, repr(usd), millis) + result = _REDIS_ADD_SCRIPT.run(self.client, 1, self._key(key), tokens, repr(usd), millis) return int(result[0]), float(result[1]) def get(self, key: str) -> tuple[int, float]: diff --git a/src/python_wrap/llm_shared.py b/src/python_wrap/llm_shared.py index 77af7fe..3b883fe 100644 --- a/src/python_wrap/llm_shared.py +++ b/src/python_wrap/llm_shared.py @@ -35,6 +35,7 @@ from typing import Any from python_wrap import _core, _fork +from python_wrap._scripts import Script __all__ = [ "AsyncRedisTokenWindow", @@ -291,6 +292,7 @@ def _step( redis.call('PEXPIRE',KEYS[1],ttl) return string.format('%.9f',result) """ +_LUA_STEP_SCRIPT = Script(_LUA_STEP) # --------------------------------------------------------------------------- the base @@ -648,7 +650,8 @@ def action() -> None: def _redis_args( name: str, prefix: str, op: str, a: float, b: float, cap: float, rate: float ) -> Any: - return (_LUA_STEP, 1, f"{prefix}:{name}", op, repr(a), repr(b), repr(cap), repr(rate)) + """Script arguments after the script itself: numkeys, key, op, a, b, capacity, rate.""" + return (1, f"{prefix}:{name}", op, repr(a), repr(b), repr(cap), repr(rate)) class RedisTokenWindow(SharedTokenWindow): @@ -682,7 +685,9 @@ def __init__( self.client, self.prefix = client, prefix def _transact(self, op: str, a: float, b: float, capacity: float, rate: float) -> float: - reply = self.client.eval(*_redis_args(self.name, self.prefix, op, a, b, capacity, rate)) + reply = _LUA_STEP_SCRIPT.run( + self.client, *_redis_args(self.name, self.prefix, op, a, b, capacity, rate) + ) return float(reply) @@ -715,8 +720,8 @@ def _transact(self, op: str, a: float, b: float, capacity: float, rate: float) - async def _arun(self, op: str, a: float, b: float, capacity: float, rate: float) -> float: try: - reply = await self.client.eval( - *_redis_args(self.name, self.prefix, op, a, b, capacity, rate) + reply = await _LUA_STEP_SCRIPT.arun( + self.client, *_redis_args(self.name, self.prefix, op, a, b, capacity, rate) ) return float(reply) except Exception as exc: diff --git a/src/python_wrap/quotas.py b/src/python_wrap/quotas.py index 6d87c5e..b24b9e8 100644 --- a/src/python_wrap/quotas.py +++ b/src/python_wrap/quotas.py @@ -15,6 +15,7 @@ from python_wrap import _core, _fork from python_wrap._backend import BackendMonitor from python_wrap._runtime import name_digest, seconds, stable_digest +from python_wrap._scripts import Script from python_wrap.errors import RateLimitExceeded __all__ = ["AsyncRedisWindow", "Quota", "QuotaExhausted", "RedisWindow", "shared_rate_limit"] @@ -29,6 +30,7 @@ redis.call('PEXPIRE',KEYS[1],ARGV[3]) end return tonumber(ARGV[2])-used """ +_QUOTA_SCRIPT = Script(_QUOTA) class QuotaExhausted(RuntimeError): @@ -90,8 +92,8 @@ def take(self, amount: int = 1) -> int: result = monitor.call( "take", lambda: int( - self.client.eval( - _QUOTA, + _QUOTA_SCRIPT.run( + self.client, 1, self.key, amount, @@ -131,6 +133,7 @@ def reset(self) -> None: end redis.call('ZADD',KEYS[1],now,ARGV[3]); redis.call('PEXPIRE',KEYS[1],ARGV[2]); return 0 """ +_WINDOW_SCRIPT = Script(_WINDOW) class _WindowConfig: @@ -164,11 +167,11 @@ def _fallback(self, key: Any) -> float: return float(self._local.acquire(key)) def _eval_args(self, key: Any) -> tuple[Any, ...]: + """Script arguments after the script itself: numkeys, key, calls, period, member.""" # Unkeyed windows keep the store key they have always had (the pickle digest of # None); caller-supplied keys use the stable encoding. suffix = name_digest(None) if key is None else stable_digest(key) return ( - _WINDOW, 1, self.key + ":" + suffix, self.calls, @@ -198,7 +201,7 @@ def acquire(self, key: Any = None) -> float: """Return zero when admitted, otherwise seconds until the oldest slot expires.""" return self._monitor.call( "acquire", - lambda: float(self.client.eval(*self._eval_args(key))) / 1000, + lambda: float(_WINDOW_SCRIPT.run(self.client, *self._eval_args(key))) / 1000, lambda: self._fallback(key), ) @@ -258,7 +261,7 @@ async def acquire(self, key: Any = None) -> float: """Return zero when admitted, otherwise seconds until the oldest slot expires.""" async def run() -> float: - return float(await self.client.eval(*self._eval_args(key))) / 1000 + return float(await _WINDOW_SCRIPT.arun(self.client, *self._eval_args(key))) / 1000 return await self._monitor.acall("acquire", run, lambda: self._fallback(key)) diff --git a/src/python_wrap/retry.py b/src/python_wrap/retry.py index 496bd20..ac8ee42 100644 --- a/src/python_wrap/retry.py +++ b/src/python_wrap/retry.py @@ -365,10 +365,10 @@ def deposit(self) -> None: return self._deposit_local() - def _deposit_local(self) -> None: + def _deposit_local(self, count: int = 1) -> None: with self._lock: index, _ = self._slot() - self._requests[index] += 1 + self._requests[index] += count def try_withdraw(self) -> bool: """Take one retry from the budget. diff --git a/src/python_wrap/shared.py b/src/python_wrap/shared.py index 3003d48..4e01fde 100644 --- a/src/python_wrap/shared.py +++ b/src/python_wrap/shared.py @@ -7,7 +7,6 @@ import asyncio import contextvars -import hashlib import math import threading import uuid @@ -17,6 +16,7 @@ from python_wrap import _core, _fork from python_wrap._backend import BackendMonitor from python_wrap._runtime import name_digest, seconds +from python_wrap._scripts import Script from python_wrap.coordination import AlreadyRunning, Lease from python_wrap.errors import BulkheadFull @@ -129,21 +129,15 @@ """ -_BREAKER_SHA = hashlib.sha1(_BREAKER.encode(), usedforsecurity=False).hexdigest() # Redis script id - - -def _no_script(exc: Exception) -> bool: - """True for Redis's NOSCRIPT reply (redis-py: NoScriptError, "No matching script").""" - text = str(exc) - return type(exc).__name__ == "NoScriptError" or "NOSCRIPT" in text or "No matching" in text - +_BREAKER_SCRIPT = Script(_BREAKER) _BUDGET = """ local t=redis.call('TIME'); local now=t[1]*1000+math.floor(t[2]/1000) local width=tonumber(ARGV[2]); local epoch=math.floor(now/width) local op=ARGV[1] if op=='deposit' then - redis.call('HINCRBY',KEYS[1],'r:'..epoch,1); redis.call('PEXPIRE',KEYS[1],width*12); return 1 + local n=tonumber(ARGV[5] or '1') + redis.call('HINCRBY',KEYS[1],'r:'..epoch,n); redis.call('PEXPIRE',KEYS[1],width*12); return 1 end local req,ret=0,0 local all=redis.call('HGETALL',KEYS[1]) @@ -160,6 +154,8 @@ def _no_script(exc: Exception) -> bool: return 0 """ +_BUDGET_SCRIPT = Script(_BUDGET) + class RedisRetryBudget: """A `RetryBudget` backend that counts requests and retries in Redis. @@ -168,6 +164,14 @@ class RedisRetryBudget: Redis clock, so every process (and host) draws on one allowance. Keys come from ``name``: two services that use the same name share a budget on purpose. Pass it as ``RetryBudget(..., backend=RedisRetryBudget(client, "vendor"))``. + + Deposits are counted in memory and sent in batches: at the next deposit once + ``flush_every`` are pending or ``flush_interval`` seconds passed since the last flush. + Withdrawals and totals flush pending deposits first, so they see every deposit made + in this process. A process that goes idle can hold up to ``flush_every - 1`` deposits + back until its next withdrawal, which only shifts the ratio slightly. A deposit never + raises: if the store is down, its count goes to the local budget instead. The script + runs with ``EVALSHA`` and is loaded again on ``NOSCRIPT``. """ def __init__( @@ -178,21 +182,74 @@ def __init__( prefix: str = "python-wrap:budget:", on_backend_error: str | None = None, retry_backend_after: float = 1.0, + flush_interval: float = 1.0, + flush_every: int = 1000, ) -> None: if not name: raise ValueError("a shared retry budget needs a name") + if not math.isfinite(flush_interval) or flush_interval < 0: + raise ValueError("flush_interval must be >= 0") + if isinstance(flush_every, bool) or not isinstance(flush_every, int) or flush_every < 1: + raise ValueError("flush_every must be a positive integer") self.client, self.name = client, name self.key = prefix + "{" + name_digest(name) + "}" + self.flush_interval, self.flush_every = flush_interval, flush_every self._monitor = BackendMonitor("budget", name, on_backend_error, retry_backend_after) + self._pending = 0 + self._flushed_at = _core.monotonic() + self._lock = _fork.ForkSafeLock() + _fork.register(self) + + def _reset_after_fork(self) -> None: + # Pending deposits belong to the parent process, which still sends them. + self._pending = 0 + self._flushed_at = _core.monotonic() - def _eval(self, budget: Any, op: str) -> Any: + def _eval(self, budget: Any, op: str, count: int = 1) -> Any: width = max(1, math.ceil(budget.window * 1000 / 10)) - return self.client.eval(_BUDGET, 1, self.key, op, width, budget.ratio, budget._reserve) + return _BUDGET_SCRIPT.run( + self.client, 1, self.key, op, width, budget.ratio, budget._reserve, count + ) + + def _take_pending(self) -> int: + """Reset the pending count and the flush clock; the caller holds ``_lock``.""" + count, self._pending = self._pending, 0 + self._flushed_at = _core.monotonic() + return count + + def _flush(self, budget: Any, count: int) -> None: + """Send ``count`` deposits. Never raises: a store error counts them locally.""" + if count <= 0: + return + if self._monitor._skipping(): + budget._deposit_local(count) + return + try: + self._eval(budget, "deposit", count) + except Exception as exc: + self._monitor.failed(exc, "deposit") + budget._deposit_local(count) + else: + self._monitor.succeeded() + + def _flush_pending(self, budget: Any) -> None: + with self._lock: + count = self._take_pending() + self._flush(budget, count) def deposit(self, budget: Any) -> None: - self._monitor.call("deposit", lambda: self._eval(budget, "deposit"), budget._deposit_local) + with self._lock: + self._pending += 1 + due = ( + self._pending >= self.flush_every + or _core.monotonic() - self._flushed_at >= self.flush_interval + ) + count = self._take_pending() if due else 0 + self._flush(budget, count) def try_withdraw(self, budget: Any) -> bool: + self._flush_pending(budget) + def fallback() -> bool: return budget._withdraw_local() if self._monitor.mode == "local" else True @@ -203,6 +260,8 @@ def fallback() -> bool: ) def totals(self, budget: Any) -> tuple[int, int]: + self._flush_pending(budget) + def local() -> tuple[int, int]: with budget._lock: totals: tuple[int, int] = budget._totals(budget._slot()[1]) @@ -343,15 +402,7 @@ def _remember(self, breaker: Any, data: dict[str, Any]) -> dict[str, Any]: return data def _call(self, args: tuple[Any, ...]) -> Any: - evalsha = getattr(self.client, "evalsha", None) - if evalsha is None: - return self.client.eval(_BREAKER, *args) - try: - return evalsha(_BREAKER_SHA, *args) - except Exception as exc: - if not _no_script(exc): - raise - return self.client.eval(_BREAKER, *args) + return _BREAKER_SCRIPT.run(self.client, *args) def operate( self, @@ -439,15 +490,7 @@ class AsyncRedisBreakerState(RedisBreakerState): """ async def _acall(self, args: tuple[Any, ...]) -> Any: - evalsha = getattr(self.client, "evalsha", None) - if evalsha is None: - return await self.client.eval(_BREAKER, *args) - try: - return await evalsha(_BREAKER_SHA, *args) - except Exception as exc: - if not _no_script(exc): - raise - return await self.client.eval(_BREAKER, *args) + return await _BREAKER_SCRIPT.arun(self.client, *args) async def operate( # type: ignore[override] self, diff --git a/tests/test_async_backends.py b/tests/test_async_backends.py index adae271..9291259 100644 --- a/tests/test_async_backends.py +++ b/tests/test_async_backends.py @@ -180,7 +180,9 @@ def test_async_window_matches_sync_window_arguments() -> None: window = AsyncRedisWindow(fake, "w", calls=3, period=1.5) assert asyncio.run(window.acquire("k")) == 0.0 script, nkeys, key, calls, period_ms, member = fake.evals[0] - sync_args = RedisWindow(object(), "w", calls=3, period=1.5)._eval_args("k") + from python_wrap.quotas import _WINDOW + + sync_args = (_WINDOW, *RedisWindow(object(), "w", calls=3, period=1.5)._eval_args("k")) assert (script, nkeys, key, calls, period_ms) == sync_args[:5] assert isinstance(member, str) and len(member) == 32 with pytest.raises(ValueError): diff --git a/tests/test_backend_recovered.py b/tests/test_backend_recovered.py index b9366c3..bedae7d 100644 --- a/tests/test_backend_recovered.py +++ b/tests/test_backend_recovered.py @@ -45,8 +45,9 @@ def use() -> None: return use if kind == "budget": + # Deposits are batched in memory, so a withdrawal is the call that reaches the store. budget = RetryBudget(backend=RedisRetryBudget(client, f"rec-{tag}")) - return budget.deposit + return budget.try_withdraw raise AssertionError(kind) diff --git a/tests/test_redis_backends.py b/tests/test_redis_backends.py index 5ce6e05..67d4029 100644 --- a/tests/test_redis_backends.py +++ b/tests/test_redis_backends.py @@ -9,6 +9,7 @@ import subprocess import tempfile import time +import uuid from concurrent.futures import ThreadPoolExecutor from pathlib import Path @@ -24,9 +25,15 @@ RedisLock, RedisStore, RedisWindow, + RetryBudget, idempotent, memoize, ) +from python_wrap._scripts import Script +from python_wrap.coordination import _LEASE_SCRIPT +from python_wrap.llm_shared import _LUA_STEP_SCRIPT, RedisTokenWindow +from python_wrap.quotas import _WINDOW_SCRIPT +from python_wrap.shared import _BUDGET, _BUDGET_SCRIPT, RedisRetryBudget class Client: @@ -498,3 +505,86 @@ def boom(): with pytest.raises(CircuitOpenError): breaker.call(lambda: "never") assert rec.commands - before < 10 + + +def _name(prefix: str) -> str: + return f"{prefix}-{uuid.uuid4().hex[:10]}" + + +class ShaClient(Client): + """`Client` with ``EVALSHA``, so the library takes the hash path first.""" + + def evalsha(self, sha, count, *args): + return self.execute("EVALSHA", sha, count, *args) + + def loaded(self, script: Script) -> bool: + return self.execute("SCRIPT", "EXISTS", script.sha) == [1] + + +def test_budget_script_deposit_withdraw_totals(redis_client): + backend = RedisRetryBudget(redis_client, _name("budget-live")) + budget = RetryBudget(ratio=0.5, min_per_second=0, window=10, backend=backend) + for _ in range(4): + budget.deposit() + assert backend.totals(budget) == (4, 0) # totals flushes the batched deposits + assert [budget.try_withdraw() for _ in range(3)] == [True, True, False] + assert backend.totals(budget) == (4, 2) + assert budget.stats.requests == 4 and budget.stats.retries == 2 + + +def test_budget_deposit_count_argument_defaults_to_one(redis_client): + backend = RedisRetryBudget(redis_client, _name("budget-count")) + width, ratio, reserve = 1000, 0.2, 0 + # An old caller sends four arguments and counts one; a new one sends a count. + assert redis_client.eval(_BUDGET, 1, backend.key, "deposit", width, ratio, reserve) == 1 + assert redis_client.eval(_BUDGET, 1, backend.key, "deposit", width, ratio, reserve, 3) == 1 + assert redis_client.eval(_BUDGET, 1, backend.key, "totals", width, ratio, reserve) == [4, 0] + + +def test_budget_slots_expire(redis_client): + backend = RedisRetryBudget(redis_client, _name("budget-expire")) + budget = RetryBudget(ratio=0.5, min_per_second=0, window=0.3, backend=backend) + budget.deposit() + assert backend.totals(budget) == (1, 0) + time.sleep(0.6) # the hash expires twelve slots after its last write + assert backend.totals(budget) == (0, 0) + + +def test_budget_shared_between_two_clients(redis_client): + name = _name("budget-share") + first = RedisRetryBudget(Client(redis_client.path), name) + second = RedisRetryBudget(Client(redis_client.path), name) + # ratio 0 and a reserve of 0.2 * 10 = 2 retries: both budgets draw on one reserve. + a = RetryBudget(ratio=0, min_per_second=0.2, window=10, backend=first) + b = RetryBudget(ratio=0, min_per_second=0.2, window=10, backend=second) + assert a.try_withdraw() and b.try_withdraw() + assert not a.try_withdraw() + assert b.stats.retries == 2 and a.stats.rejected == 1 + + +def test_scripts_reload_on_noscript(redis_client): + client = ShaClient(redis_client.path) + client.execute("SCRIPT", "FLUSH") + # Each script runs once, the server forgets it, and the next call must reload it. + window = RedisWindow(client, _name("reload-window"), calls=2, period=1) + assert window.acquire() == 0 + assert client.loaded(_WINDOW_SCRIPT) + client.execute("SCRIPT", "FLUSH") + assert window.acquire() == 0 and client.loaded(_WINDOW_SCRIPT) + + lock = RedisLock(client, _name("reload-lease") + ":") + assert lock.acquire("key", "t1", 5) + client.execute("SCRIPT", "FLUSH") + assert lock.renew("key", "t1", 5) and client.loaded(_LEASE_SCRIPT) + + backend = RedisRetryBudget(client, _name("reload-budget"), flush_every=1) + budget = RetryBudget(ratio=0.5, min_per_second=0, window=10, backend=backend) + budget.deposit() + client.execute("SCRIPT", "FLUSH") + budget.deposit() # the deposit reloads the script and counts both requests + assert backend.totals(budget) == (2, 0) and client.loaded(_BUDGET_SCRIPT) + + tokens = RedisTokenWindow(client, _name("reload-tokens"), prefix="python-wrap:tokens") + assert tokens.reserve(1, 10, 1) == 0 + client.execute("SCRIPT", "FLUSH") + assert tokens.reserve(1, 10, 1) == 0 and client.loaded(_LUA_STEP_SCRIPT) diff --git a/tests/test_shared_presets.py b/tests/test_shared_presets.py index 79078ef..8ec6943 100644 --- a/tests/test_shared_presets.py +++ b/tests/test_shared_presets.py @@ -2,8 +2,11 @@ from __future__ import annotations +import os from typing import Any +import pytest + from python_wrap.config import configured from python_wrap.policies import PolicyRegistry from python_wrap.presets import http_client, third_party_api @@ -12,19 +15,21 @@ class FakeRedis: - """Understands only the budget script; records every other eval.""" + """Understands only the budget script; records every other eval and counts calls.""" def __init__(self) -> None: self.req = self.ret = 0 + self.calls = 0 self.other: list[Any] = [] def eval(self, script: str, numkeys: int, key: str, *args: Any) -> Any: + self.calls += 1 if "'deposit'" not in script: self.other.append(key) return [b"closed"] op, _width, ratio, reserve = args[0], args[1], float(args[2]), float(args[3]) if op == "deposit": - self.req += 1 + self.req += int(args[4]) if len(args) > 4 else 1 # four-argument callers count 1 return 1 if op == "totals": return [self.req, self.ret] @@ -64,3 +69,68 @@ def test_third_party_window_and_configure_default() -> None: def test_unshared_preset_still_per_process() -> None: layers = {layer.role: layer for layer in http_client("g2-local").explain().layers} assert layers["breaker"].settings["shared"] is False + + +def test_thousand_calls_flush_few_deposits() -> None: + client = FakeRedis() + backend = RedisRetryBudget(client, "batched", flush_interval=60, flush_every=1000) + budget = RetryBudget(ratio=0.2, min_per_second=5, backend=backend) + for _ in range(1000): + budget.deposit() + assert client.calls < 10 # the 1000th deposit flushed; nothing else reached the store + assert budget.stats.requests == 1000 # totals flushes the rest first + assert client.req == 1000 + + +def test_withdraw_flushes_pending_deposits_first() -> None: + client = FakeRedis() + backend = RedisRetryBudget(client, "first", flush_interval=60, flush_every=1000) + budget = RetryBudget(ratio=0.5, min_per_second=0, backend=backend) + for _ in range(4): + budget.deposit() + assert client.req == 0 # still pending in this process + # 0.5 * 4 requests allow two retries; the withdrawal must see all four deposits. + assert [budget.try_withdraw(), budget.try_withdraw(), budget.try_withdraw()] == [ + True, + True, + False, + ] + assert client.req == 4 and client.ret == 2 + + +def test_deposit_never_raises_when_store_is_down() -> None: + class Down: + def eval(self, *args: Any) -> Any: + raise ConnectionError("store is down") + + backend = RedisRetryBudget( + Down(), "down", flush_interval=0, flush_every=1, on_backend_error="raise" + ) + budget = RetryBudget(ratio=0.2, min_per_second=5, backend=backend) + for _ in range(3): + budget.deposit() # a failing store must not fail the call + assert sum(budget._requests) == 3 # the counts fell back to the local budget + with pytest.raises(ConnectionError): + budget.try_withdraw() # withdrawals keep their "raise" behaviour + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs POSIX fork") +def test_budget_pending_cleared_after_fork() -> None: + client = FakeRedis() + backend = RedisRetryBudget(client, "forked", flush_interval=60, flush_every=1000) + budget = RetryBudget(ratio=0.2, min_per_second=5, backend=backend) + for _ in range(3): + budget.deposit() + pid = os.fork() + if pid == 0: # child: the parent's pending deposits are not ours to send + code = 0 + try: + if backend._pending != 0 or client.req != 0: + code = 1 + finally: + os._exit(code) + _, status = os.waitpid(pid, 0) + assert os.WEXITSTATUS(status) == 0 + assert backend._pending == 3 # the parent keeps and later sends its own three + budget.try_withdraw() + assert client.req == 3 From 487b1a094f2c362d9c2ef8ab9598eca4cdf96b61 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 27 Nov 2026 08:49:58 +0200 Subject: [PATCH 12/38] feat: one on_backend_error rule for caches, token windows, leases and bulkheads - on_backend_error on RedisStore, AsyncRedisStore, the token windows, Lease and Bulkhead. Caches default to allow, token windows to local, and the others to raise; the defaults are unchanged. - configure(backend_errors=) applies to caches and token windows built without an explicit mode. The project default is cached instead of copied per call. - Caches and token windows emit backend.error on store errors; memoize with lock= computes when the lock store is down. - A store error while a shared bulkhead is queued no longer escapes in every mode. Quota.remaining and Quota.reset respect the backend mode. - Repeated store failures log one warning per interval, not one per call. - fail_open= is deprecated (DeprecationWarning, removed in 0.6.0). --- .../ai/shared-limits-and-cassettes.md | 2 +- docs/features/caching/async-stores.md | 2 +- .../caching/stores-and-credentials.md | 15 +- docs/features/concurrency/shared-limits.md | 21 +- docs/features/configuration.md | 2 +- docs/llms-full.txt | 18 +- docs/project/operations.md | 3 +- src/python_wrap/_backend.py | 71 ++++- src/python_wrap/async_cache.py | 21 +- src/python_wrap/bulkhead.py | 4 + src/python_wrap/caching.py | 1 + src/python_wrap/config.py | 5 +- src/python_wrap/coordination.py | 72 ++++- src/python_wrap/llm_shared.py | 94 ++++-- src/python_wrap/quotas.py | 25 +- src/python_wrap/shared.py | 34 ++- src/python_wrap/stores.py | 21 +- tests/test_backend_rules.py | 276 ++++++++++++++++++ 18 files changed, 583 insertions(+), 104 deletions(-) create mode 100644 tests/test_backend_rules.py diff --git a/docs/features/ai/shared-limits-and-cassettes.md b/docs/features/ai/shared-limits-and-cassettes.md index 67430e2..4c105c8 100644 --- a/docs/features/ai/shared-limits-and-cassettes.md +++ b/docs/features/ai/shared-limits-and-cassettes.md @@ -46,7 +46,7 @@ Every worker must use the same `tokens_per_minute`; the window name picks the bu ### When storage fails -By default a window **fails open**: if the file is locked or Redis is unreachable it emits `rate_limit.store_error` and uses a private in-memory bucket for that call, so an outage degrades to per-process limiting instead of stopping every LLM call. Pass `fail_open=False` to raise instead. +By default a token window uses `on_backend_error="local"`: if the file is locked or Redis is unreachable it emits `backend.error` (and the older `rate_limit.store_error`, removed in 0.6.0) and uses a private in-memory bucket for that call, so an outage degrades to per-process limiting instead of stopping every LLM call. Pass `on_backend_error="allow"` to admit calls without accounting, or `on_backend_error="raise"` to raise. The `fail_open=` argument still works but is deprecated (removed in 0.6.0). `configure(backend_errors=...)` sets the default for windows built without an explicit mode. ### Backing off together diff --git a/docs/features/caching/async-stores.md b/docs/features/caching/async-stores.md index b15fcaf..f0f30a2 100644 --- a/docs/features/caching/async-stores.md +++ b/docs/features/caching/async-stores.md @@ -91,7 +91,7 @@ async def get_price(sku: str) -> dict: ``` By default Redis connection or server errors are logged and treated as misses -(`fail_open=True`); pass `fail_open=False` to raise. An unencodable key raises `TypeError` +(`on_backend_error="allow"`); pass `on_backend_error="raise"` to raise. An unencodable key raises `TypeError` and is not treated as a store outage. A stored value that cannot be decoded is a miss (`cache.rejected`, `reason="decode"`). See [stores and credentials](stores-and-credentials.md#failure-modes). `clear()` scans only this store's prefix and deletes in batches with `UNLINK`. diff --git a/docs/features/caching/stores-and-credentials.md b/docs/features/caching/stores-and-credentials.md index 873ba26..a29eaa0 100644 --- a/docs/features/caching/stores-and-credentials.md +++ b/docs/features/caching/stores-and-credentials.md @@ -17,7 +17,7 @@ from python_wrap.stores import signed_pickle_codec client = redis.Redis(socket_timeout=2, socket_connect_timeout=2) dumps, loads = signed_pickle_codec(b"replace-with-a-secret-at-least-16-bytes") store = RedisStore(client, prefix="myapp:price:", version=1, - dumps=dumps, loads=loads, fail_open=False) + dumps=dumps, loads=loads, on_backend_error="raise") @memoize(store=store, ttl=300) def price(sku: str) -> float: @@ -64,15 +64,20 @@ Redis and codec failures fall into three groups: | Situation | Result | | --- | --- | -| Redis client error (connection, timeout, server error) | Store outage: `fail_open=True` logs `backend.error` and treats a read as a miss or a write as a no-op. `fail_open=False` raises. | -| Key cannot be encoded (for example an unsupported argument type) | `TypeError` to the caller. Not a store outage: no `backend.error`, and `fail_open` does not apply. | +| Redis client error (connection, timeout, server error) | Store outage: `on_backend_error="allow"` (the default) logs `backend.error` and treats a read as a miss or a write as a no-op. `on_backend_error="raise"` raises. `"local"` behaves like `"allow"`. | +| Key cannot be encoded (for example an unsupported argument type) | `TypeError` to the caller. Not a store outage: no `backend.error`, and `on_backend_error` does not apply. | | Stored value cannot be decoded | A miss, with `cache.rejected` and `reason="decode"`; `reason="signature"` for a bad signature. | | Value cannot be encoded by `dumps` | The error propagates to the caller. | -Set `fail_open=False` when persistence is part of correctness, especially +Set `on_backend_error="raise"` when persistence is part of correctness, especially for [idempotency](../concurrency/leases-and-idempotency.md#idempotency). The async store (`AsyncRedisStore`) follows the same rules. +The mode resolves in this order: the `on_backend_error=` argument, then the deprecated +`fail_open=` argument (it emits a `DeprecationWarning` and is removed in 0.6.0), then +`configure(backend_errors=...)`, then `"allow"`. Set `configure(backend_errors="raise")` to make +every cache built without an explicit mode strict. + ### Cache keys Shared stores derive keys with the canonical encoder used by `memoize`. Plain @@ -165,7 +170,7 @@ from python_wrap import RedisLock, RedisStore, invalidate_tags, memoize client = Redis() @memoize( - store=RedisStore(client, "orders:", fail_open=False), + store=RedisStore(client, "orders:", on_backend_error="raise"), ttl=300, ttl_jitter=0.1, lock=RedisLock(client), diff --git a/docs/features/concurrency/shared-limits.md b/docs/features/concurrency/shared-limits.md index 2c02635..9410f03 100644 --- a/docs/features/concurrency/shared-limits.md +++ b/docs/features/concurrency/shared-limits.md @@ -3,6 +3,12 @@ Default limiters, breakers and bulkheads are in-process. Optional Redis backends extend coordination across workers; they take a client created by your application. +When a shared store is down, breakers, rate windows, quotas, bulkheads and retry budgets +raise by default (`on_backend_error="raise"`). Caches allow, and token windows fall back to +a local bucket; see [store-down rules](#when-the-shared-store-is-down). Release 0.5.0 changes +the default for these backends to `"local"`; set `configure(backend_errors="raise")` to keep +today's behaviour after upgrading. + ## A run quota ```python @@ -159,6 +165,12 @@ Every shared backend takes the same option, `on_backend_error`: | `"local"` | Use this process's own breaker, window, quota or bulkhead cap until the store answers. | | `"allow"` | Admit the call and skip accounting. | +Caches take `on_backend_error` too: `"allow"` (a miss, writes dropped) is their default, and +`"local"` behaves like `"allow"`. Token windows default to `"local"`. Leases +(`Lease(..., on_backend_error="allow")`) enter without the lease and set `degraded`; memoize +uses that to compute the value when its lock store is down. `Lease` itself defaults to +`"raise"`, which `idempotent` and `single_instance` keep. + ```python from python_wrap import CircuitBreaker, configure @@ -170,10 +182,11 @@ breaker = CircuitBreaker(name="vendor", backend=RedisBreakerState(client), ``` The first error logs a WARNING and emits `backend.error` (fields `backend`, `operation`, `error`); the next -success emits `backend.recovered`. While a fallback is active `health.summary()` reports -`degraded`. Idempotency result stores always raise. `RedisStore` keeps `fail_open` -(`True` is `"allow"`, `False` is `"raise"`); `RedisSource` takes `on_backend_error` and -answers its `default`. +success emits `backend.recovered`. Repeated failures while the store stays down log one +WARNING per interval, not one per call. While a fallback is active `health.summary()` reports +`degraded`. Idempotency result stores always raise. `RedisStore` and `AsyncRedisStore` keep +`fail_open` as a deprecated alias (removed in 0.6.0; `True` is `"allow"`, `False` is `"raise"`); +`RedisSource` takes `on_backend_error` and answers its `default`. See [quotas API](../../api/quotas.md), [shared backends API](../../api/shared.md), and [bulkhead API](../../api/bulkhead.md). diff --git a/docs/features/configuration.md b/docs/features/configuration.md index 27e9b16..6cfa242 100644 --- a/docs/features/configuration.md +++ b/docs/features/configuration.md @@ -55,7 +55,7 @@ dependency during an incident. See [named policies](resilience/named-policies.md | `retry` | Dict of defaults for `retry` and `retrying`: `max_attempts`, `delay`, `backoff`, `max_delay`, `jitter`, `max_time`, `log_level`, `budget` (one shared `RetryBudget`). | | `redact` | Replaces the built-in `DEFAULT_REDACT` list for `log_args` and `audit`. `None` restores it. | | `redact_extra` | Names **added** to the redaction list (the built-ins stay), for `log_args` and `audit`. | -| `backend_errors` | Default `on_backend_error` for shared backends: `"raise"`, `"local"` or `"allow"`. | +| `backend_errors` | Default `on_backend_error` for shared backends: `"raise"`, `"local"` or `"allow"`. Covers breakers, windows, quotas, bulkheads, budgets, caches and token windows. Caches and token windows keep their own built-in defaults (`"allow"` and `"local"`) when this is unset. | | `shared` | Redis client or `SharedBackends` used by presets and `PolicyRegistry` when a policy names no backend. | | `cache_codec` | Default codec for sync and async Redis stores built without `dumps=`/`loads=`: `"json"`, `("signed-pickle", ENV_NAME)` (secret read from that environment variable) or a `(dumps, loads)` pair. | diff --git a/docs/llms-full.txt b/docs/llms-full.txt index 42168fc..f259367 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -2414,7 +2414,7 @@ Every worker must use the same `tokens_per_minute`; the window name picks the bu #### When storage fails -By default a window **fails open**: if the file is locked or Redis is unreachable it emits `rate_limit.store_error` and uses a private in-memory bucket for that call, so an outage degrades to per-process limiting instead of stopping every LLM call. Pass `fail_open=False` to raise instead. +By default a token window uses `on_backend_error="local"`: if the file is locked or Redis is unreachable it emits `backend.error` (and the older `rate_limit.store_error`, removed in 0.6.0) and uses a private in-memory bucket for that call, so an outage degrades to per-process limiting instead of stopping every LLM call. Pass `on_backend_error="allow"` to admit calls without accounting, or `on_backend_error="raise"` to raise. The `fail_open=` argument still works but is deprecated (removed in 0.6.0). `configure(backend_errors=...)` sets the default for windows built without an explicit mode. #### Backing off together @@ -4263,7 +4263,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm `RedisLock` for ``redis.asyncio`` clients: every round trip is awaited, not threaded. - `python_wrap.AsyncRedisSemaphore`: `AsyncRedisSemaphore(client: Any, prefix: str = 'python-wrap:lease:')` `AsyncRedisLock` with capacity supplied by Lease(limit=...). -- `python_wrap.AsyncRedisStore`: `AsyncRedisStore(client: Any, prefix: str, *, dumps: Callable[[Any], bytes] | None = None, loads: Callable[[bytes], Any] | None = None, key_format: Callable[[Hashable], str] | None = None, fail_open: bool = True, retry_backend_after: float = 1.0, version: int | None = None)` +- `python_wrap.AsyncRedisStore`: `AsyncRedisStore(client: Any, prefix: str, *, dumps: Callable[[Any], bytes] | None = None, loads: Callable[[bytes], Any] | None = None, key_format: Callable[[Hashable], str] | None = None, on_backend_error: str | None = None, fail_open: Any = , retry_backend_after: float = 1.0, version: int | None = None)` A namespaced `AsyncCacheStore` for ``redis.asyncio``-compatible clients. - `python_wrap.AsyncRedisWindow`: `AsyncRedisWindow(client: Any, key: str, *, calls: int, period: float | str, on_backend_error: str | None = None, retry_backend_after: float = 1.0)` `RedisWindow` for ``redis.asyncio`` clients: the round trip is awaited, not threaded. @@ -4285,7 +4285,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Pending includes records currently being written; failures are counted separately. - `python_wrap.Buffered`: `Buffered(func: Callable[[list[Any]], Any], *, max_size: int = 200, flush_interval: float = 1, max_queue: int = 10000, on_full: str = 'drop', drain_on_exit: float = 3, on_error: str = 'continue', logger: Any = None, journal: BufferJournal | None = None)` A synchronous batch callable with submit/flush/close/disable/stats controls. -- `python_wrap.Bulkhead`: `Bulkhead(max_concurrent: int, *, max_waiting: int | None = None, timeout: float | None = None, name: str | None = None, backend: Any = None, ttl: float = 60)` +- `python_wrap.Bulkhead`: `Bulkhead(max_concurrent: int, *, max_waiting: int | None = None, timeout: float | None = None, name: str | None = None, backend: Any = None, ttl: float = 60, on_backend_error: str | None = None, retry_backend_after: float = 1.0)` Allow at most `max_concurrent` calls at once; reject when too many are waiting. - `python_wrap.BulkheadFull`: `BulkheadFull(message: str, *, name: str | None, max_concurrent: int)` A bulkhead is at capacity: its wait queue is full, or waiting for a slot timed out. @@ -4331,7 +4331,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm What to retry, how long to wait, and when to stop, for HTTP calls. - `python_wrap.INJECTED` Constant: INJECTED -- `python_wrap.Lease`: `Lease(key: str, *, backend: Any = None, ttl: float | str = 60, limit: int = 1, wait: bool = False, timeout: float | None = None, renew: bool = True)` +- `python_wrap.Lease`: `Lease(key: str, *, backend: Any = None, ttl: float | str = 60, limit: int = 1, wait: bool = False, timeout: float | None = None, renew: bool = True, on_backend_error: str | None = None)` Single-use sync/async lease context with renewal and bounded acquisition wait. - `python_wrap.LeaseLost` A lease expired or could not be renewed while work was running. @@ -4387,7 +4387,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm The same atomic lease backend, with capacity supplied by Lease(limit=...). - `python_wrap.RedisSource`: `RedisSource(client: Any, prefix: str = 'python-wrap:switch:', *, default: bool = True, on_backend_error: str | None = None, retry_backend_after: float = 1.0)` Read a boolean flag from a supplied Redis client. -- `python_wrap.RedisStore`: `RedisStore(client: Any, prefix: str, *, dumps: Callable[[Any], bytes] | None = None, loads: Callable[[bytes], Any] | None = None, key_format: Callable[[Hashable], str] | None = None, fail_open: bool = True, retry_backend_after: float = 1.0, version: int | None = None)` +- `python_wrap.RedisStore`: `RedisStore(client: Any, prefix: str, *, dumps: Callable[[Any], bytes] | None = None, loads: Callable[[bytes], Any] | None = None, key_format: Callable[[Hashable], str] | None = None, on_backend_error: str | None = None, fail_open: Any = , retry_backend_after: float = 1.0, version: int | None = None)` A namespaced `CacheStore` with opaque hashed keys and configurable serialization. - `python_wrap.RedisWindow`: `RedisWindow(client: Any, key: str, *, calls: int, period: float | str, on_backend_error: str | None = None, retry_backend_after: float = 1.0)` Atomic sliding-window admission using the Redis server's clock. @@ -5029,17 +5029,17 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm LLM fault rules that act on HTTP exchanges; reach it as ``chaos.llm_http``. - `python_wrap.llm_shared` Token limits and budgets shared by several worker processes. -- `python_wrap.llm_shared.AsyncRedisTokenWindow`: `AsyncRedisTokenWindow(client: Any, name: str = 'tokens', *, prefix: str = 'python-wrap:tokens', fail_open: bool = True)` +- `python_wrap.llm_shared.AsyncRedisTokenWindow`: `AsyncRedisTokenWindow(client: Any, name: str = 'tokens', *, prefix: str = 'python-wrap:tokens', on_backend_error: str | None = None, fail_open: Any = )` `RedisTokenWindow` for ``redis.asyncio`` clients: round trips are awaited. - `python_wrap.llm_shared.RateLimitHint`: `RateLimitHint(remaining_tokens: float | None = None, reset_seconds: float | None = None, retry_after: float | None = None)` What a provider's rate-limit headers said, in plain numbers. -- `python_wrap.llm_shared.RedisTokenWindow`: `RedisTokenWindow(client: Any, name: str = 'tokens', *, prefix: str = 'python-wrap:tokens', fail_open: bool = True)` +- `python_wrap.llm_shared.RedisTokenWindow`: `RedisTokenWindow(client: Any, name: str = 'tokens', *, prefix: str = 'python-wrap:tokens', on_backend_error: str | None = None, fail_open: Any = )` A `SharedTokenWindow` on Redis, shared by every worker on every host. - `python_wrap.llm_shared.SQLiteBudgetBackend`: `SQLiteBudgetBackend(path: str | os.PathLike[str], *, timeout: float = 10.0)` A `python_wrap.llm.BudgetBackend` in SQLite: one budget shared by local processes. -- `python_wrap.llm_shared.SQLiteTokenWindow`: `SQLiteTokenWindow(path: str | os.PathLike[str], name: str = 'tokens', *, timeout: float = 10.0, fail_open: bool = True)` +- `python_wrap.llm_shared.SQLiteTokenWindow`: `SQLiteTokenWindow(path: str | os.PathLike[str], name: str = 'tokens', *, timeout: float = 10.0, on_backend_error: str | None = None, fail_open: Any = )` A `SharedTokenWindow` in one SQLite file, shared by processes on one host. -- `python_wrap.llm_shared.SharedTokenWindow`: `SharedTokenWindow(name: str = 'tokens', *, fail_open: bool = True)` +- `python_wrap.llm_shared.SharedTokenWindow`: `SharedTokenWindow(name: str = 'tokens', *, on_backend_error: str | None = None, fail_open: Any = )` A token bucket held in shared storage; the base of the concrete windows. - `python_wrap.llm_shared.parse_rate_limit_headers`: `parse_rate_limit_headers(headers: Any) -> RateLimitHint` Read token-window hints from provider response headers; never raises. diff --git a/docs/project/operations.md b/docs/project/operations.md index 0327523..14f6905 100644 --- a/docs/project/operations.md +++ b/docs/project/operations.md @@ -16,6 +16,7 @@ StatsD, or OpenTelemetry) and alert on: | Load is being shed | `python_wrap_rejections_total{kind="bulkhead"}` | sustained non-zero | | Timeouts | `python_wrap_timeouts_total` | rate above normal baseline | | Component health | `python_wrap_health_up == 0` | any critical component | +| Shared store down | `backend.error` events (`pw_backend_errors_total`); health `degraded` | any sustained non-zero rate; fallbacks are active (`backend.recovered` clears it) | The sample [Grafana dashboard](https://github.com/LitePy/PythonWrap/blob/main/docs/assets/grafana-dashboard.json) plots all of these. For chat notifications on breaker opens use @@ -102,7 +103,7 @@ Upgrade notes: - Changing a breaker's **settings** does not require clearing state; changing its **name** starts a fresh state (the old key stays until deleted). - Changing a cache's codec (pickle to JSON) requires a new store `prefix`: old entries - would not decode. Undecodable entries are treated as misses when `fail_open=True`. + would not decode. Undecodable entries are treated as misses under `on_backend_error="allow"`. - Lease, window and quota keys need no migration; they expire on their own. ## Graceful shutdown diff --git a/src/python_wrap/_backend.py b/src/python_wrap/_backend.py index ea238bc..f7dd583 100644 --- a/src/python_wrap/_backend.py +++ b/src/python_wrap/_backend.py @@ -21,10 +21,48 @@ BACKEND_ERROR_MODES = ("raise", "local", "allow") -def default_mode() -> str: - from python_wrap.config import get_config +_NOT_GIVEN: Any = object() +"""Sentinel for an argument that was not passed (so ``None`` stays a valid value).""" + +_project_default: str | None = None +"""Mirror of ``configure(backend_errors=)``; kept in step by `python_wrap.config`.""" + + +def _set_default(value: str | None) -> None: + """Called by `python_wrap.config` whenever the configuration changes.""" + global _project_default + _project_default = value + - return str(get_config()["backend_errors"] or "raise") +def default_mode() -> str: + """The mode used when a backend was built with no explicit mode.""" + return _project_default or "raise" + + +def resolve_mode(on_backend_error: str | None, fail_open: Any, owner: str, default: str) -> str: + """Resolve a backend's mode: explicit argument, deprecated ``fail_open``, project default. + + ``default`` applies when neither is given and nothing is configured. ``fail_open`` is + deprecated (removed in 0.6.0): ``True`` maps to ``allow``, ``False`` to ``raise``, and + it is ignored when ``on_backend_error`` is given (but still warns). + Call it directly from the constructor so the warning points at the caller. + """ + if fail_open is not _NOT_GIVEN: + import warnings + + warnings.warn( + f"{owner}(fail_open=) is deprecated and is removed in 0.6.0; " + "pass on_backend_error='allow' or on_backend_error='raise' instead", + DeprecationWarning, + stacklevel=3, + ) + if on_backend_error is not None: + if on_backend_error not in BACKEND_ERROR_MODES: + raise ValueError(f"on_backend_error must be one of {BACKEND_ERROR_MODES}") + return on_backend_error + if fail_open is not _NOT_GIVEN: + return "allow" if fail_open else "raise" + return _project_default or default class BackendMonitor: @@ -47,6 +85,7 @@ def __init__( self._mode = on_backend_error self.retry_backend_after = retry_backend_after self._until = 0.0 + self._logged_until = 0.0 self._down = False self._lock = _fork.ForkSafeLock() _fork.register(self) @@ -56,7 +95,7 @@ def __init__( health.register(f"backend:{kind}:{name}", self) def _reset_after_fork(self) -> None: - self._until, self._down = 0.0, False + self._until, self._logged_until, self._down = 0.0, 0.0, False @property def mode(self) -> str: @@ -70,17 +109,23 @@ def _skipping(self) -> bool: return self.mode != "raise" and time.monotonic() < self._until def failed(self, exc: BaseException, operation: str) -> None: + now = time.monotonic() with self._lock: self._down = True - self._until = time.monotonic() + self.retry_backend_after - _core.get_logger(None).warning( - "%s backend %r: %s failed (%s); on_backend_error=%s", - self.kind, - self.name, - operation, - type(exc).__name__, - self.mode, - ) + self._until = now + self.retry_backend_after + # A dead store fails every call; one warning per interval is enough. + log = now >= self._logged_until + if log: + self._logged_until = now + max(self.retry_backend_after, 1.0) + if log: + _core.get_logger(None).warning( + "%s backend %r: %s failed (%s); on_backend_error=%s", + self.kind, + self.name, + operation, + type(exc).__name__, + self.mode, + ) _core.emit( "backend.error", self.name, diff --git a/src/python_wrap/async_cache.py b/src/python_wrap/async_cache.py index 8c66fed..dd9adf5 100644 --- a/src/python_wrap/async_cache.py +++ b/src/python_wrap/async_cache.py @@ -29,7 +29,7 @@ from typing import Any, Protocol, TypeVar, runtime_checkable from python_wrap import _core, _fork -from python_wrap._backend import BackendMonitor +from python_wrap._backend import _NOT_GIVEN, BackendMonitor, resolve_mode from python_wrap._runtime import name_digest, stable_digest from python_wrap.caching import ( _TAG_PREFIX, @@ -184,7 +184,11 @@ class AsyncRedisStore: dumps: Serializer for entries; defaults to pickle. loads: Deserializer matching dumps. key_format: Optional function turning a cache key into a stable external key. - fail_open: Treat backend errors as misses/no-ops and log them, rather than raise. + on_backend_error: ``"allow"`` (a miss; writes are dropped), ``"raise"`` or ``"local"`` + (same as ``"allow"`` for a cache). Defaults to ``configure(backend_errors=)``, then + ``"allow"``. Every error emits ``backend.error``. + fail_open: Deprecated alias (removed in 0.6.0): ``True`` is ``"allow"``, ``False`` + is ``"raise"``. Ignored when ``on_backend_error`` is given. Raises: ValueError: If ``prefix`` is empty. @@ -198,7 +202,8 @@ def __init__( dumps: Callable[[Any], bytes] | None = None, loads: Callable[[bytes], Any] | None = None, key_format: Callable[[Hashable], str] | None = None, - fail_open: bool = True, + on_backend_error: str | None = None, + fail_open: Any = _NOT_GIVEN, retry_backend_after: float = 1.0, version: int | None = None, ) -> None: @@ -222,10 +227,11 @@ def __init__( self.dumps, self.loads = dumps or pickle.dumps, loads or pickle.loads # Plain pickle on a shared store: doctor reports it (PW026). self.implicit_pickle = self.dumps is pickle.dumps - self.key_format, self.fail_open = key_format, fail_open - self._monitor = BackendMonitor( - "cache", prefix, "allow" if fail_open else "raise", retry_backend_after - ) + mode = resolve_mode(on_backend_error, fail_open, type(self).__name__, "allow") + mode = "allow" if mode == "local" else mode # a miss is already the local answer + self.key_format, self.on_backend_error = key_format, mode + self.fail_open = mode != "raise" # derived; idempotency and web read it + self._monitor = BackendMonitor("cache", prefix, mode, retry_backend_after) def _key(self, key: Hashable) -> str: if self.key_format: @@ -614,6 +620,7 @@ def lease_for(k: Hashable, wait: bool) -> Any: ttl=lock_ttl, wait=wait, timeout=lock_wait if wait else None, + on_backend_error="allow", ) async def compute(k: Hashable, args: Any, kwargs: Any, refreshing: bool = False) -> Any: diff --git a/src/python_wrap/bulkhead.py b/src/python_wrap/bulkhead.py index 39ed474..b8a90ba 100644 --- a/src/python_wrap/bulkhead.py +++ b/src/python_wrap/bulkhead.py @@ -142,6 +142,8 @@ def __init__( name: str | None = None, backend: Any = None, ttl: float = 60, + on_backend_error: str | None = None, + retry_backend_after: float = 1.0, ) -> None: if isinstance(max_concurrent, bool) or not isinstance(max_concurrent, int): raise ValueError(f"max_concurrent must be an integer, got {max_concurrent!r}") @@ -164,6 +166,8 @@ def __init__( max_waiting=max_waiting, timeout=timeout, ttl=ttl, + on_backend_error=on_backend_error, + retry_backend_after=retry_backend_after, ) self.max_concurrent = max_concurrent self.max_waiting = max_waiting diff --git a/src/python_wrap/caching.py b/src/python_wrap/caching.py index 92c833c..51591b1 100644 --- a/src/python_wrap/caching.py +++ b/src/python_wrap/caching.py @@ -1010,6 +1010,7 @@ def lease_for(k: Hashable, wait: bool) -> Any: ttl=lock_ttl, wait=wait, timeout=lock_wait if wait else None, + on_backend_error="allow", ) def cached_outcome(b: Any, k: Hashable) -> tuple[bool, Any]: diff --git a/src/python_wrap/config.py b/src/python_wrap/config.py index 7c6d5da..c756eed 100644 --- a/src/python_wrap/config.py +++ b/src/python_wrap/config.py @@ -14,7 +14,7 @@ from collections.abc import Iterable, Iterator, Mapping from typing import Any -from python_wrap import _core, _fork +from python_wrap import _backend, _core, _fork __all__ = ["configure", "configured", "get_config", "reset_config"] @@ -160,6 +160,7 @@ def configure(**defaults: Any) -> None: _state.update(clean) if "logger" in clean: _core._default_logger = clean["logger"] + _backend._set_default(_state.get("backend_errors")) def get_config() -> dict[str, Any]: @@ -203,6 +204,7 @@ def reset_config() -> None: with _lock: _state.clear() _core._default_logger = None + _backend._set_default(None) @contextlib.contextmanager @@ -234,6 +236,7 @@ def configured(**defaults: Any) -> Iterator[None]: _state.clear() _state.update(saved) _core._default_logger = saved.get("logger") + _backend._set_default(saved.get("backend_errors")) def retry_default(name: str, value: Any, fallback: Any) -> Any: diff --git a/src/python_wrap/coordination.py b/src/python_wrap/coordination.py index a795e06..de40577 100644 --- a/src/python_wrap/coordination.py +++ b/src/python_wrap/coordination.py @@ -377,7 +377,17 @@ def __init__( wait: bool = False, timeout: float | None = None, renew: bool = True, + on_backend_error: str | None = None, ) -> None: + """Create a lease. ``on_backend_error`` is ``"raise"`` (the default, also when None: + a store outage fails the call) or ``"allow"`` (enter without the lease, set + ``degraded`` and skip renewal and release). It never reads ``configure(backend_errors=)``, + so ``idempotent`` and ``single_instance`` stay strict unless asked otherwise. + """ + if on_backend_error not in (None, "raise", "allow"): + raise ValueError("Lease on_backend_error must be 'raise' or 'allow'") + self.on_backend_error = on_backend_error or "raise" + self.degraded = False self.key = key self.backend: Any = backend if backend is not None else _LOCAL self.ttl = seconds(ttl) @@ -417,6 +427,22 @@ def _try(self) -> bool: logging.getLogger("python_wrap").exception("lease acquire cleanup failed") raise + def _degrade(self, exc: Exception) -> None: + """Enter without the lease after a store error (``on_backend_error="allow"``).""" + self.degraded = self._active = True + logging.getLogger("python_wrap").warning( + "lease store failed for %r (%s); entering without the lease", + self.key, + type(exc).__name__, + ) + _core.emit( + "backend.error", + self.key, + backend="lease", + operation="acquire", + error=type(exc).__name__, + ) + def _renew(self) -> None: try: self.lost = self.lost or not self.backend.renew(self.key, self.token, self.ttl) @@ -481,11 +507,21 @@ def __enter__(self) -> Lease: self._prepare() try: start = time.monotonic() - while not self._try(): - left = None if self.timeout is None else self.timeout - (time.monotonic() - start) - if not self.wait or (left is not None and left <= 0): - raise AlreadyRunning(self.key) - time.sleep(min(0.05, self.ttl / 3, left if left is not None else self.ttl)) + try: + while not self._try(): + left = ( + None if self.timeout is None else self.timeout - (time.monotonic() - start) + ) + if not self.wait or (left is not None and left <= 0): + raise AlreadyRunning(self.key) + time.sleep(min(0.05, self.ttl / 3, left if left is not None else self.ttl)) + except AlreadyRunning: + raise + except Exception as exc: + if self.on_backend_error != "allow": + raise + self._degrade(exc) + return self self._active = True if self.auto_renew: @@ -516,6 +552,9 @@ def __exit__(self, typ: Any, exc: Any, tb: Any) -> None: return if not self._active: raise RuntimeError("lease exited without an acquisition") + if self.degraded: + self._active, self._finished = False, True + return self._stop.set() if self._thread is not None: self._thread.join() @@ -550,11 +589,21 @@ async def __aenter__(self) -> Lease: try: loop = asyncio.get_running_loop() start = loop.time() - while not await self._atry(): - left = None if self.timeout is None else self.timeout - (loop.time() - start) - if not self.wait or (left is not None and left <= 0): - raise AlreadyRunning(self.key) - await asyncio.sleep(min(0.05, self.ttl / 3, left if left is not None else self.ttl)) + try: + while not await self._atry(): + left = None if self.timeout is None else self.timeout - (loop.time() - start) + if not self.wait or (left is not None and left <= 0): + raise AlreadyRunning(self.key) + await asyncio.sleep( + min(0.05, self.ttl / 3, left if left is not None else self.ttl) + ) + except AlreadyRunning: + raise + except Exception as exc: + if self.on_backend_error != "allow": + raise + self._degrade(exc) + return self self._active = True if self.auto_renew: @@ -582,6 +631,9 @@ async def __aexit__(self, typ: Any, exc: Any, tb: Any) -> None: return if not self._active: raise RuntimeError("lease exited without an acquisition") + if self.degraded: + self._active, self._finished = False, True + return async def finish() -> bool: if self._task is not None: diff --git a/src/python_wrap/llm_shared.py b/src/python_wrap/llm_shared.py index 3b883fe..c823f3e 100644 --- a/src/python_wrap/llm_shared.py +++ b/src/python_wrap/llm_shared.py @@ -35,6 +35,7 @@ from typing import Any from python_wrap import _core, _fork +from python_wrap._backend import _NOT_GIVEN, BackendMonitor, resolve_mode from python_wrap._scripts import Script __all__ = [ @@ -307,20 +308,32 @@ class SharedTokenWindow: monotonic clock. A subclass implements ``_transact``. When the storage fails (locked database, unreachable Redis, an exception from the - client) and ``fail_open`` is true, the window logs a ``rate_limit.store_error`` event - and falls back to a private in-memory bucket for that call, so an outage degrades to - per-process limiting instead of stopping every LLM call. ``fail_open=False`` raises. + client) the window applies ``on_backend_error``. ``"local"`` (the default, also the + project default when nothing is configured) serves the call from a private in-memory + bucket, so an outage degrades to per-process limiting instead of stopping every LLM + call. ``"allow"`` admits the call without accounting. ``"raise"`` raises. Every error + emits ``backend.error`` and ``rate_limit.store_error``. Attributes: name: Identifies the bucket inside the storage; share it to share the quota. - fail_open: Whether storage errors fall back to a local bucket. + on_backend_error: The resolved mode (``"raise"``, ``"local"`` or ``"allow"``). + fail_open: Derived from the mode (true unless it is ``"raise"``); deprecated. """ - def __init__(self, name: str = "tokens", *, fail_open: bool = True) -> None: + def __init__( + self, + name: str = "tokens", + *, + on_backend_error: str | None = None, + fail_open: Any = _NOT_GIVEN, + ) -> None: if not name: raise ValueError("a window needs a nonempty name") self.name = name - self.fail_open = fail_open + mode = resolve_mode(on_backend_error, fail_open, type(self).__name__, "local") + self.on_backend_error = mode + self.fail_open = mode != "raise" + self._monitor = BackendMonitor("tokens", name, mode) self._fallback: _State | None = None self._flock = _fork.ForkSafeLock() @@ -335,14 +348,25 @@ def _local(self, op: str, a: float, b: float, capacity: float, rate: float) -> f ) return result + def _store_error(self, exc: Exception, op: str) -> None: + # Kept until 0.6.0; the generic backend.error event is emitted by the monitor. + _core.emit("rate_limit.store_error", self.name, error=type(exc).__name__, op=op) + + def _degraded(self, op: str, a: float, b: float, capacity: float, rate: float) -> float: + """Answer for a failed store: the local bucket, or admission without accounting.""" + if self._monitor.mode == "local": + return self._local(op, a, b, capacity, rate) + return float(capacity) if op == "level" else 0.0 + def _run(self, op: str, a: float, b: float, capacity: float, rate: float) -> float: - try: - return self._transact(op, a, b, capacity, rate) - except Exception as exc: - _core.emit("rate_limit.store_error", self.name, error=type(exc).__name__, op=op) - if not self.fail_open: + def store() -> float: + try: + return self._transact(op, a, b, capacity, rate) + except Exception as exc: + self._store_error(exc, op) raise - return self._local(op, a, b, capacity, rate) + + return self._monitor.call(op, store, lambda: self._degraded(op, a, b, capacity, rate)) # -- the limiter-facing operations -------------------------------------------- def reserve(self, tokens: int, capacity: float, rate: float) -> float: @@ -493,8 +517,10 @@ class SQLiteTokenWindow(SharedTokenWindow): path: The database file (created if missing). name: Bucket name inside the file. timeout: Seconds to wait for a competing writer before the storage counts as - failed (see ``fail_open``). - fail_open: Fall back to an in-memory bucket when storage fails. + failed (see ``on_backend_error``). + on_backend_error: ``"local"`` (default: an in-memory bucket), ``"allow"`` or + ``"raise"``. Defaults to ``configure(backend_errors=)``. + fail_open: Deprecated alias (removed in 0.6.0) for ``on_backend_error``. Example: ```python @@ -519,9 +545,10 @@ def __init__( name: str = "tokens", *, timeout: float = 10.0, - fail_open: bool = True, + on_backend_error: str | None = None, + fail_open: Any = _NOT_GIVEN, ) -> None: - super().__init__(name, fail_open=fail_open) + super().__init__(name, on_backend_error=on_backend_error, fail_open=fail_open) self._file = _SQLiteFile( path, timeout, @@ -668,7 +695,9 @@ class RedisTokenWindow(SharedTokenWindow): client: The Redis client. name: Bucket name; share it to share the quota. prefix: Namespace for the key. - fail_open: Fall back to an in-memory bucket when Redis fails. + on_backend_error: ``"local"`` (default: an in-memory bucket), ``"allow"`` or + ``"raise"`` when Redis fails. Defaults to ``configure(backend_errors=)``. + fail_open: Deprecated alias (removed in 0.6.0) for ``on_backend_error``. """ def __init__( @@ -677,9 +706,10 @@ def __init__( name: str = "tokens", *, prefix: str = "python-wrap:tokens", - fail_open: bool = True, + on_backend_error: str | None = None, + fail_open: Any = _NOT_GIVEN, ) -> None: - super().__init__(name, fail_open=fail_open) + super().__init__(name, on_backend_error=on_backend_error, fail_open=fail_open) if not prefix: raise ValueError("RedisTokenWindow needs a nonempty prefix") self.client, self.prefix = client, prefix @@ -706,9 +736,10 @@ def __init__( name: str = "tokens", *, prefix: str = "python-wrap:tokens", - fail_open: bool = True, + on_backend_error: str | None = None, + fail_open: Any = _NOT_GIVEN, ) -> None: - super().__init__(name, fail_open=fail_open) + super().__init__(name, on_backend_error=on_backend_error, fail_open=fail_open) if not prefix: raise ValueError("AsyncRedisTokenWindow needs a nonempty prefix") self.client, self.prefix = client, prefix @@ -719,16 +750,19 @@ def _transact(self, op: str, a: float, b: float, capacity: float, rate: float) - ) async def _arun(self, op: str, a: float, b: float, capacity: float, rate: float) -> float: - try: - reply = await _LUA_STEP_SCRIPT.arun( - self.client, *_redis_args(self.name, self.prefix, op, a, b, capacity, rate) - ) - return float(reply) - except Exception as exc: - _core.emit("rate_limit.store_error", self.name, error=type(exc).__name__, op=op) - if not self.fail_open: + async def store() -> float: + try: + reply = await _LUA_STEP_SCRIPT.arun( + self.client, *_redis_args(self.name, self.prefix, op, a, b, capacity, rate) + ) + return float(reply) + except Exception as exc: + self._store_error(exc, op) raise - return self._local(op, a, b, capacity, rate) + + return await self._monitor.acall( + op, store, lambda: self._degraded(op, a, b, capacity, rate) + ) async def areserve(self, tokens: int, capacity: float, rate: float) -> float: """Async `reserve`.""" diff --git a/src/python_wrap/quotas.py b/src/python_wrap/quotas.py index b24b9e8..3cf004a 100644 --- a/src/python_wrap/quotas.py +++ b/src/python_wrap/quotas.py @@ -113,15 +113,34 @@ def remaining(self) -> int: with self._lock: used = self._used else: - used = int(self.client.get(self.key) or 0) + assert self._monitor is not None + used = self._monitor.call( + "remaining", + lambda: int(self.client.get(self.key) or 0), + self._fallback_used, + ) return max(0, self.limit - used) + def _fallback_used(self) -> int: + """Usage when the store is down: the local counter in "local" mode, else none.""" + assert self._monitor is not None + if self._monitor.mode != "local": + return 0 + with self._lock: + return self._used + def reset(self) -> None: if self.client is None: with self._lock: self._used = 0 - else: - self.client.delete(self.key) + return + + def clear_local() -> None: + with self._lock: + self._used = 0 + + assert self._monitor is not None + self._monitor.call("reset", lambda: self.client.delete(self.key), clear_local) _WINDOW = """ diff --git a/src/python_wrap/shared.py b/src/python_wrap/shared.py index 4e01fde..c4b7b8b 100644 --- a/src/python_wrap/shared.py +++ b/src/python_wrap/shared.py @@ -606,6 +606,18 @@ def acquire(self) -> None: if self._monitor._skipping(): return self._local_admit(threading.get_ident()) lease = self._lease() + try: + self._enter(lease) + except BulkheadFull: + raise + except Exception as exc: # a store error, first attempt or while queued + self._store_down(exc) + return self._local_admit(threading.get_ident()) + self._monitor.succeeded() + self._admitted(lease, threading.get_ident()) + + def _enter(self, lease: Lease) -> None: + """Acquire ``lease``, queueing up to ``max_waiting`` while the backend is full.""" try: lease.__enter__() except AlreadyRunning: @@ -618,11 +630,6 @@ def acquire(self) -> None: finally: with self._lock: self._waiting -= 1 - except Exception as exc: - self._store_down(exc) - return self._local_admit(threading.get_ident()) - self._monitor.succeeded() - self._admitted(lease, threading.get_ident()) def release(self, typ: Any = None, exc: Any = None, tb: Any = None) -> None: stack = self._stack.get() @@ -648,6 +655,18 @@ async def acquire_async(self) -> None: if self._monitor._skipping(): return self._local_admit(asyncio.current_task()) lease = self._lease() + try: + await self._aenter(lease) + except BulkheadFull: + raise + except Exception as exc: # a store error, first attempt or while queued + self._store_down(exc) + return self._local_admit(asyncio.current_task()) + self._monitor.succeeded() + self._admitted(lease, asyncio.current_task()) + + async def _aenter(self, lease: Lease) -> None: + """Async `_enter`.""" try: await lease.__aenter__() except AlreadyRunning: @@ -660,11 +679,6 @@ async def acquire_async(self) -> None: finally: with self._lock: self._waiting -= 1 - except Exception as exc: - self._store_down(exc) - return self._local_admit(asyncio.current_task()) - self._monitor.succeeded() - self._admitted(lease, asyncio.current_task()) async def release_async(self, typ: Any = None, exc: Any = None, tb: Any = None) -> None: stack = self._stack.get() diff --git a/src/python_wrap/stores.py b/src/python_wrap/stores.py index e8263a1..98babf2 100644 --- a/src/python_wrap/stores.py +++ b/src/python_wrap/stores.py @@ -15,7 +15,7 @@ from collections.abc import Callable, Hashable from typing import Any -from python_wrap._backend import BackendMonitor +from python_wrap._backend import _NOT_GIVEN, BackendMonitor, resolve_mode from python_wrap._runtime import stable_digest KEY_FORMAT = "k2:" # key encoding version: entries written by 0.4.0b1 expire unread @@ -106,7 +106,11 @@ class RedisStore: dumps: Serializer for entries; defaults to pickle (trusted Redis data only). loads: Deserializer matching dumps. key_format: Optional function turning a cache key into a stable external key. - fail_open: Treat backend errors as misses/no-ops and log them, rather than raise. + on_backend_error: ``"allow"`` (a miss; writes are dropped), ``"raise"`` or ``"local"`` + (same as ``"allow"`` for a cache). Defaults to ``configure(backend_errors=)``, then + ``"allow"``. Every error emits ``backend.error``. + fail_open: Deprecated alias (removed in 0.6.0): ``True`` is ``"allow"``, ``False`` + is ``"raise"``. Ignored when ``on_backend_error`` is given. `size()` is unknown (None); `cache_info()` never scans Redis. `clear()` scans only this namespace, escaping glob metacharacters, and deletes in bounded batches. @@ -124,7 +128,8 @@ def __init__( dumps: Callable[[Any], bytes] | None = None, loads: Callable[[bytes], Any] | None = None, key_format: Callable[[Hashable], str] | None = None, - fail_open: bool = True, + on_backend_error: str | None = None, + fail_open: Any = _NOT_GIVEN, retry_backend_after: float = 1.0, version: int | None = None, ) -> None: @@ -147,11 +152,11 @@ def __init__( # Plain pickle on a shared store lets anyone who can write the namespace run code # in every reader; doctor reports it (PW026). self.implicit_pickle = self.dumps is pickle.dumps - self.key_format, self.fail_open = key_format, fail_open - # fail_open=True is "allow" (a miss); False is "raise". - self._monitor = BackendMonitor( - "cache", prefix, "allow" if fail_open else "raise", retry_backend_after - ) + mode = resolve_mode(on_backend_error, fail_open, type(self).__name__, "allow") + mode = "allow" if mode == "local" else mode # a miss is already the local answer + self.key_format, self.on_backend_error = key_format, mode + self.fail_open = mode != "raise" # derived; idempotency and web read it + self._monitor = BackendMonitor("cache", prefix, mode, retry_backend_after) def _key(self, key: Hashable) -> str: if self.key_format: diff --git a/tests/test_backend_rules.py b/tests/test_backend_rules.py new file mode 100644 index 0000000..9bd4f22 --- /dev/null +++ b/tests/test_backend_rules.py @@ -0,0 +1,276 @@ +"""Store-down rules for caches, token windows, leases, bulkheads and quotas (0.4.1 step). + +Defaults are unchanged in 0.4.x: caches allow, token windows fall back to a local bucket, +breakers, windows, quotas, bulkheads and budgets raise. ``configure(backend_errors=)`` +overrides the default of every backend that is built without an explicit mode. +""" + +from __future__ import annotations + +import logging +import uuid +from collections.abc import Callable +from typing import Any + +import pytest + +from python_wrap.async_cache import AsyncRedisStore, amemoize +from python_wrap.bulkhead import Bulkhead +from python_wrap.caching import memoize +from python_wrap.circuit import CircuitBreaker +from python_wrap.config import configured +from python_wrap.coordination import AsyncRedisLock, Lease, RedisLock +from python_wrap.events import listening +from python_wrap.llm_shared import RedisTokenWindow +from python_wrap.quotas import Quota +from python_wrap.shared import RedisBreakerState, SharedBulkhead +from python_wrap.stores import RedisStore, json_codec + + +class Dead: + """A synchronous client whose every command fails.""" + + def _down(self, *args: object, **kwargs: object) -> object: + raise ConnectionError("store down") + + eval = evalsha = get = set = delete = acquire = release = renew = _down + + +class AsyncDead: + """An asynchronous client whose every command fails.""" + + async def _down(self, *args: object, **kwargs: object) -> object: + raise ConnectionError("store down") + + eval = evalsha = get = set = delete = acquire = release = renew = _down + + +def _names(events: list[Any]) -> list[str]: + return [e.name for e in events] + + +def _store(prefix: str, **kwargs: Any) -> RedisStore: + dumps, loads = json_codec() + return RedisStore(Dead(), prefix, dumps=dumps, loads=loads, **kwargs) + + +def test_cache_store_reads_project_default() -> None: + with configured(backend_errors="raise"), pytest.raises(ConnectionError): + _store("cfg-raise:").get("k") + with configured(backend_errors="local"): # a cache treats local as allow + assert _store("cfg-local:").get("k") is None + assert _store("cfg-none:").get("k") is None # built-in default: allow + with configured(backend_errors="raise"): + explicit = _store("cfg-explicit:", on_backend_error="allow") + assert explicit.get("k") is None # the argument wins over the project default + + +def test_fail_open_alias_warns_and_maps() -> None: + with pytest.warns(DeprecationWarning, match="0.6.0"): + strict = _store("alias-strict:", fail_open=False) + assert strict.fail_open is False + with pytest.raises(ConnectionError): + strict.get("k") + with pytest.warns(DeprecationWarning, match="0.6.0"): + lenient = _store("alias-lenient:", fail_open=True) + assert lenient.fail_open is True and lenient.get("k") is None + with pytest.warns(DeprecationWarning, match="0.6.0"): + ignored = _store("alias-ignored:", on_backend_error="raise", fail_open=True) + assert ignored.on_backend_error == "raise" + with pytest.raises(ValueError): + _store("alias-bad:", on_backend_error="nope") + + +def test_token_window_emits_backend_error_and_falls_back_local() -> None: + window = RedisTokenWindow(Dead(), f"tok-{uuid.uuid4().hex[:6]}") + assert window.on_backend_error == "local" + events: list[Any] = [] + with listening(events.append): + assert window.reserve(100, 100, 1.0) == 0.0 # admitted from the local bucket + assert window.reserve(100, 100, 1.0) > 0.0 # the local bucket is now full + window.force(10, 100, 1.0) + names = _names(events) + assert names.count("backend.error") == 1 # later calls skip the dead store + assert "rate_limit.store_error" in names + + +def test_token_window_allow_admits() -> None: + window = RedisTokenWindow(Dead(), f"tok-{uuid.uuid4().hex[:6]}", on_backend_error="allow") + assert [window.reserve(1000, 100, 1.0) for _ in range(3)] == [0.0, 0.0, 0.0] + assert window.level(100, 1.0) == 100.0 + + +def test_memoize_lock_computes_when_lease_store_is_down() -> None: + calls: list[int] = [] + + @memoize(store=RedisStore(Dead(), "memo-sync:"), lock=RedisLock(Dead()), ttl=60) + def value(n: int) -> int: + calls.append(n) + return n * 2 + + assert value(3) == 6 + assert value(3) == 6 + assert calls == [3, 3] # no cache and no lease: each call computes + + +@pytest.mark.asyncio +async def test_amemoize_lock_computes_when_lease_store_is_down() -> None: + calls: list[int] = [] + + @amemoize( + store=AsyncRedisStore(AsyncDead(), "memo-async:"), + lock=AsyncRedisLock(AsyncDead()), + ttl=60, + ) + async def value(n: int) -> int: + calls.append(n) + return n * 2 + + assert await value(4) == 8 + assert calls == [4] + + +def test_lease_allow_enters_degraded_without_release() -> None: + lease = Lease("deg", backend=Dead(), on_backend_error="allow") + with lease: + assert lease.degraded is True + assert lease.degraded is True + with pytest.raises(ConnectionError), Lease("strict", backend=Dead()): + pass + + +def test_bulkhead_queue_error_uses_fallback() -> None: + class QueueFails: + """First attempt: the slot is busy. The attempt made while queued: store error.""" + + def __init__(self) -> None: + self.attempts = 0 + + def acquire(self, key: str, token: str, ttl: float, limit: int = 1) -> bool: + self.attempts += 1 + if self.attempts == 1: + return False + raise ConnectionError("store down") + + def release(self, key: str, token: str) -> bool: + raise ConnectionError("store down") + + backend = QueueFails() + bulkhead = SharedBulkhead( + 1, + backend=backend, + name=f"bh-{uuid.uuid4().hex[:6]}", + max_waiting=1, + on_backend_error="local", + ) + bulkhead.acquire() # no ConnectionError escapes the queue attempt + assert bulkhead.active == 1 + bulkhead.release() + assert bulkhead.active == 0 + assert backend.attempts == 2 + + strict = SharedBulkhead(1, backend=QueueFails(), name="bh-strict", max_waiting=1) + with pytest.raises(ConnectionError): + strict.acquire() + + +def test_bulkhead_accepts_on_backend_error() -> None: + bulkhead = Bulkhead( + 1, + name="vendor", + backend=Dead(), + on_backend_error="allow", + retry_backend_after=0.5, + ) + assert bulkhead._shared is not None + assert bulkhead._shared._monitor.mode == "allow" + assert bulkhead._shared._monitor.retry_backend_after == 0.5 + with bulkhead: + pass # allowed without accounting + with pytest.raises(ValueError): + Bulkhead(1, name="vendor2", backend=Dead(), on_backend_error="nope") + + +def test_quota_remaining_and_reset_use_monitor() -> None: + quota = Quota(10, name="q-local", client=Dead(), key="q-local", on_backend_error="local") + events: list[Any] = [] + with listening(events.append): + assert quota.take(3) == 7 # the local counter serves the call + assert quota.remaining == 7 # store down: the local counter answers + assert quota.remaining == 7 + quota.reset() + assert quota.remaining == 10 + assert _names(events).count("backend.error") == 1 + + strict = Quota(10, name="q-strict", client=Dead(), key="q-strict") + with pytest.raises(ConnectionError): + _ = strict.remaining + with pytest.raises(ConnectionError): + strict.reset() + + +@pytest.mark.parametrize("kind", ["cache", "tokens"]) +def test_recovered_event_after_first_success( + kind: str, failing_then_recovering_client: Any +) -> None: + proxy = failing_then_recovering_client + tag = uuid.uuid4().hex[:6] + use: Callable[[], Any] + if kind == "cache": + dumps, loads = json_codec() + store = RedisStore(proxy, f"rec-{tag}:", dumps=dumps, loads=loads, retry_backend_after=0) + + def use() -> Any: + return store.get("k") + + else: + window = RedisTokenWindow(proxy, f"rec-{tag}") + window._monitor.retry_backend_after = 0 + + def use() -> Any: + return window.reserve(1, 100, 1.0) + + events: list[Any] = [] + with listening(events.append): + use() # healthy + proxy.down = True + use() # the fallback answers; the failure is reported once + proxy.down = False + use() + use() + names = _names(events) + assert names.count("backend.error") == 1 + assert names.count("backend.recovered") == 1 + + +def test_raise_mode_logs_once_per_interval(caplog: pytest.LogCaptureFixture) -> None: + breaker = CircuitBreaker(name=f"log-{uuid.uuid4().hex[:6]}", backend=RedisBreakerState(Dead())) + caplog.set_level(logging.WARNING) + failures = 0 + for _ in range(1000): + try: + breaker.call(lambda: 1) + except ConnectionError: + failures += 1 + assert failures == 1000 + warnings = [r for r in caplog.records if "failed (ConnectionError)" in r.getMessage()] + assert 1 <= len(warnings) <= 5 + + +def test_mode_lookup_does_not_copy_config(monkeypatch: pytest.MonkeyPatch) -> None: + import python_wrap.config as config + + calls = 0 + real = config.get_config + + def counting() -> dict[str, Any]: + nonlocal calls + calls += 1 + return real() + + monkeypatch.setattr(config, "get_config", counting) + breaker = CircuitBreaker(name=f"mode-{uuid.uuid4().hex[:6]}", backend=RedisBreakerState(Dead())) + for _ in range(100): + with pytest.raises(ConnectionError): + breaker.call(lambda: 1) + assert calls == 0 From 3616bf17906e0cf3edcfbc6b91c2a478c0595e62 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 27 Nov 2026 09:01:03 +0200 Subject: [PATCH 13/38] perf: shared leases renew from one thread per process; poll back-off - One daemon renewal thread per process serves every shared lease, so a call no longer starts a thread. A renewal that starts after the TTL marks the lease lost. Degraded leases are never queued for renewal. - Waiting for a lease backs off its polls (50 ms doubling to 0.5 s, capped at ttl/3 and the time left, up to 20% jitter) instead of polling every 50 ms. - The renewal thread restarts in a forked child. --- docs/features/concurrency/bulkheads.md | 3 + docs/features/concurrency/shared-limits.md | 7 + src/python_wrap/coordination.py | 181 ++++++++++++++++++--- tests/test_fork_safety.py | 36 ++++ tests/test_lease_renewer.py | 137 ++++++++++++++++ tests/test_redis_backends.py | 36 ++++ 6 files changed, 377 insertions(+), 23 deletions(-) create mode 100644 tests/test_lease_renewer.py diff --git a/docs/features/concurrency/bulkheads.md b/docs/features/concurrency/bulkheads.md index 7c1c498..8f23b4d 100644 --- a/docs/features/concurrency/bulkheads.md +++ b/docs/features/concurrency/bulkheads.md @@ -100,6 +100,9 @@ Waiting for a slot (the bulkhead `timeout`) runs on **real time**. `fast_mode()` !!! note "Release errors on shared bulkheads" A `Bulkhead` with a shared `backend=` that fails to release its slot logs the error (`backend.error`, `operation="release"`) and returns the call's own result or exception. The slot expires at its TTL. See [shared limits](shared-limits.md#shared-bulkheads). +!!! note "Cost per call on shared bulkheads" + Each call on a shared `backend=` makes two store round trips (acquire and release). It does not start a thread: every lease in a process is renewed by one shared daemon thread, started on the first shared acquire, and a call that ends before its first renewal is due costs no renewal work. Waiting callers poll the store with back-off (50 ms doubling to 0.5 s, capped at `ttl / 3` and the time left, plus up to 20 % jitter) instead of every 50 ms. A renewal that starts after the lease's TTL marks it lost. + !!! warning "A bulkhead inside a global limit can starve" Suppose `map_async(fetch, urls, limit=10)` calls a function that waits for a per-host `Bulkhead(2)`. A task holds one of the 10 global slots *while it queues for the bulkhead*. If most URLs hit the same host, ten tasks sit on global slots, two work and eight wait, so requests to every other host are blocked behind them (and with a `timeout` or `max_waiting` the waiters may be rejected instead). Two ways out: diff --git a/docs/features/concurrency/shared-limits.md b/docs/features/concurrency/shared-limits.md index 9410f03..ba4a9ba 100644 --- a/docs/features/concurrency/shared-limits.md +++ b/docs/features/concurrency/shared-limits.md @@ -127,6 +127,13 @@ and does not fail the call: the call's result or exception is kept, and the slot at its `ttl`. Lease expiry has the same [limits](leases-and-idempotency.md#redis-and-sql-backends) as a distributed lock; long external work must tolerate a lost lease. +Shared capacity costs two store round trips per call (acquire and release) and no thread +per call. Each process runs one renewal thread for all of its leases, started on the first +shared acquire; a slow store call in that thread delays other renewals in the same process, +so keep the client's socket timeout short. A process that restarts or forks starts with no +renewal thread and renews only leases it acquired itself. Waiting callers back off their +polls from 50 ms up to 0.5 s (capped at `ttl / 3` and the time left), with up to 20 % jitter. + ## Async services `AsyncRedisBreakerState` and `AsyncRedisSemaphore` are the `redis.asyncio` counterparts of diff --git a/src/python_wrap/coordination.py b/src/python_wrap/coordination.py index de40577..80541dd 100644 --- a/src/python_wrap/coordination.py +++ b/src/python_wrap/coordination.py @@ -5,9 +5,11 @@ import asyncio import contextlib import hashlib +import heapq import logging import math import os +import random import threading import uuid from collections.abc import Callable @@ -358,6 +360,122 @@ async def _drain(task: asyncio.Task[Any]) -> tuple[Any, BaseException | None, bo return None, error, cancelled +class _Renewer: + """One daemon thread per process renews every active auto-renewing lease. + + A heap of ``(due, seq, lease)`` orders renewals oldest first. ``discard`` marks a lease + done and leaves its entry in the heap (lazy removal); the heap is rebuilt once most of + its entries are dead. A renewal that starts after the lease's deadline (its TTL since + the last successful acquire or renew) marks the lease lost instead of renewing it. + A fork resets the renewer: the child has no thread and no inherited leases. + """ + + def __init__(self) -> None: + self._lock = _fork.ForkSafeLock() + self._heap: list[tuple[float, int, Lease]] = [] + self._seq = 0 + self._dead = 0 + self._thread: threading.Thread | None = None + self._wake = threading.Event() + + def _reset_after_fork(self) -> None: + self._lock = _fork.ForkSafeLock() + self._heap = [] + self._seq = self._dead = 0 + self._thread = None + self._wake = threading.Event() + + def _push(self, lease: Lease, due: float) -> None: + self._seq += 1 + heapq.heappush(self._heap, (due, self._seq, lease)) + lease._queued = True + + def add(self, lease: Lease) -> None: + """Schedule renewals for an acquired lease; the first is due at ``ttl / 3``.""" + with self._lock: + lease._renew_done = False + self._push(lease, _core.monotonic() + lease.ttl / 3) + if self._thread is None: + thread = threading.Thread( + target=self._run, daemon=True, name="python-wrap-lease-renewer" + ) + try: + thread.start() + except BaseException: + # The caller releases the lease; its heap entry must not renew it. + lease._renew_done = True + self._dead += 1 + raise + self._thread = thread + self._wake.set() + + def discard(self, lease: Lease) -> None: + """Stop renewing ``lease``; its heap entry is dropped when it reaches the top.""" + with self._lock: + if lease._renew_done: + return + lease._renew_done = True + if lease._queued: + self._dead += 1 + if self._dead > 32 and self._dead * 2 > len(self._heap): + live = [entry for entry in self._heap if not entry[2]._renew_done] + for _, _, stale in self._heap: + if stale._renew_done: + stale._queued = False + heapq.heapify(live) + self._heap, self._dead = live, 0 + + def _next(self) -> tuple[Lease | None, float]: + """Pop the next due live lease, or return the seconds to wait for one.""" + with self._lock: + while self._heap: + due, _, lease = self._heap[0] + if lease._renew_done: + heapq.heappop(self._heap) + lease._queued = False + self._dead -= 1 + continue + now = _core.monotonic() + if due > now: + return None, due - now + heapq.heappop(self._heap) + lease._queued = False + return lease, 0.0 + return None, 3600.0 + + def _run(self) -> None: + while True: + lease, wait = self._next() + if lease is None: + self._wake.wait(wait) + self._wake.clear() + continue + # Renewal runs outside the heap lock: a slow store call must not block add/discard. + try: + lease._renew() + except BaseException: + logging.getLogger("python_wrap").exception("lease renewal failed") + lease.lost = True + if lease.lost or lease._renew_done: + continue + with self._lock: + if not lease._renew_done: + self._push(lease, _core.monotonic() + lease.ttl / 3) + + +_RENEWER = _Renewer() +_RENEWER_RESET = _fork.register_reset(_RENEWER._reset_after_fork) + + +def _poll_delay(attempt: int, ttl: float, left: float | None) -> float: + """Wait between acquisition attempts: 50 ms doubling to 0.5 s, plus up to 20 % jitter. + + Capped at ``ttl / 3`` and at the time left before the caller's timeout. + """ + delay: float = min(0.05 * 2 ** min(attempt, 10), 0.5, ttl / 3) * (1 + 0.2 * random.random()) + return delay if left is None else min(delay, left) + + class Lease: """Single-use sync/async lease context with renewal and bounded acquisition wait. @@ -399,8 +517,10 @@ def __init__( self.lost = False self._async = _core.is_async(self.backend.acquire) self._inline = type(self.backend) is LocalLease # built-in, in memory: nothing blocks - self._stop = threading.Event() - self._thread: threading.Thread | None = None + # Renewal bookkeeping for the shared _Renewer; the async beat task ignores it. + self._deadline = math.inf + self._queued = self._renew_done = False + self._renew_lock = _fork.ForkSafeLock() self._task: asyncio.Task[None] | None = None self._lifecycle = _fork.ForkSafeLock() self._entering = self._active = self._finished = False @@ -418,7 +538,11 @@ def _prepare(self) -> None: def _try(self) -> bool: try: - return bool(self.backend.acquire(self.key, self.token, self.ttl, self.limit)) + started = _core.monotonic() + acquired = bool(self.backend.acquire(self.key, self.token, self.ttl, self.limit)) + if acquired: + self._deadline = started + self.ttl + return acquired except BaseException: # An acquire may succeed server-side before its response is lost. try: @@ -444,10 +568,23 @@ def _degrade(self, exc: Exception) -> None: ) def _renew(self) -> None: - try: - self.lost = self.lost or not self.backend.renew(self.key, self.token, self.ttl) - except Exception: - self.lost = True + # One renewal at a time per lease; __exit__ takes the same lock after marking the + # lease done, so no renewal can run after the lease has been released. + with self._renew_lock: + if self._renew_done: + return + started = _core.monotonic() + if started > self._deadline: + self.lost = True # the store has expired it: renewing now cannot restore it + return + try: + renewed = bool(self.backend.renew(self.key, self.token, self.ttl)) + except Exception: + renewed = False + if not renewed: + self.lost = True + elif not self.lost: + self._deadline = started + self.ttl async def _try_async(self) -> bool: try: @@ -507,6 +644,7 @@ def __enter__(self) -> Lease: self._prepare() try: start = time.monotonic() + attempt = 0 try: while not self._try(): left = ( @@ -514,7 +652,8 @@ def __enter__(self) -> Lease: ) if not self.wait or (left is not None and left <= 0): raise AlreadyRunning(self.key) - time.sleep(min(0.05, self.ttl / 3, left if left is not None else self.ttl)) + time.sleep(_poll_delay(attempt, self.ttl, left)) + attempt += 1 except AlreadyRunning: raise except Exception as exc: @@ -524,16 +663,8 @@ def __enter__(self) -> Lease: return self self._active = True if self.auto_renew: - - def beat() -> None: - while not self._stop.wait(self.ttl / 3): - self._renew() - if self.lost: - return - - self._thread = threading.Thread(target=beat, daemon=True, name="python-wrap-lease") try: - self._thread.start() + _RENEWER.add(self) except BaseException: try: self.backend.release(self.key, self.token) @@ -545,6 +676,12 @@ def beat() -> None: finally: self._entering = False + def _stop_renewal(self) -> None: + """Stop scheduling renewals and wait out one that is already running.""" + _RENEWER.discard(self) + with self._renew_lock: + pass + def __exit__(self, typ: Any, exc: Any, tb: Any) -> None: if os.getpid() != self._pid: if exc is None: @@ -555,9 +692,7 @@ def __exit__(self, typ: Any, exc: Any, tb: Any) -> None: if self.degraded: self._active, self._finished = False, True return - self._stop.set() - if self._thread is not None: - self._thread.join() + self._stop_renewal() try: released = self.backend.release(self.key, self.token) except Exception: @@ -589,14 +724,14 @@ async def __aenter__(self) -> Lease: try: loop = asyncio.get_running_loop() start = loop.time() + attempt = 0 try: while not await self._atry(): left = None if self.timeout is None else self.timeout - (loop.time() - start) if not self.wait or (left is not None and left <= 0): raise AlreadyRunning(self.key) - await asyncio.sleep( - min(0.05, self.ttl / 3, left if left is not None else self.ttl) - ) + await asyncio.sleep(_poll_delay(attempt, self.ttl, left)) + attempt += 1 except AlreadyRunning: raise except Exception as exc: diff --git a/tests/test_fork_safety.py b/tests/test_fork_safety.py index b335575..31c8862 100644 --- a/tests/test_fork_safety.py +++ b/tests/test_fork_safety.py @@ -336,3 +336,39 @@ def test_no_plain_threading_locks_in_package(): if count > allowed: unexpected.append(f"{key[0]}: {key[1]} ({count} plain, {allowed} allowed)") assert not unexpected, "use _fork.ForkSafeLock/ForkSafeRLock: " + "; ".join(unexpected) + + +class _AlwaysHeldStore: + def acquire(self, key, token, ttl, limit=1): + return True + + def renew(self, key, token, ttl): + return True + + def release(self, key, token): + return True + + +@posix_only +def test_renewer_restarts_after_fork(): + from python_wrap import Lease, coordination + + parent_lease = Lease("parent-held", backend=_AlwaysHeldStore(), ttl=60) + with parent_lease: + assert coordination._RENEWER._heap # the parent's lease is queued for renewal + pid = os.fork() + if pid == 0: + ok = False + try: + renewer = coordination._RENEWER + # The child starts with no inherited heap entries and no renewal thread. + ok = not renewer._heap and renewer._thread is None + child_lease = Lease("child", backend=_AlwaysHeldStore(), ttl=0.3) + with child_lease: + time.sleep(0.5) # longer than the TTL: the child's own renewer runs + ok = ok and not child_lease.lost and renewer._thread is not None + # Only the child's own (now finished) lease may remain queued. + ok = ok and all(entry[2] is child_lease for entry in renewer._heap) + finally: + _child_exit(ok) + assert _wait_exit(pid) == 0 diff --git a/tests/test_lease_renewer.py b/tests/test_lease_renewer.py new file mode 100644 index 0000000..3560141 --- /dev/null +++ b/tests/test_lease_renewer.py @@ -0,0 +1,137 @@ +"""Shared lease renewal: one renewal thread per process, renewals on time, losses detected.""" + +from __future__ import annotations + +import threading +import time +from typing import Any + +import pytest + +from python_wrap import AlreadyRunning, Bulkhead, Lease, LeaseLost +from python_wrap.coordination import _poll_delay + + +class FakeStore: + """In-memory lease store with real TTL expiry; counts calls for assertions.""" + + def __init__(self, *, renew_ok: bool = True, busy: bool = False) -> None: + self.holders: dict[str, tuple[str, float]] = {} + self.acquire_calls = self.renew_calls = 0 + self.renew_ok, self.busy = renew_ok, busy + self._lock = threading.Lock() + + def acquire(self, key: str, token: str, ttl: float, limit: int = 1) -> bool: + with self._lock: + self.acquire_calls += 1 + now = time.monotonic() + live = {t: exp for t, exp in self.holders.values() if exp > now} + if self.busy or (token not in live and len(live) >= limit): + return False + self.holders[token] = (token, now + ttl) + return True + + def renew(self, key: str, token: str, ttl: float) -> bool: + with self._lock: + self.renew_calls += 1 + held = self.holders.get(token) + if not self.renew_ok or held is None or held[1] <= time.monotonic(): + return False + self.holders[token] = (token, time.monotonic() + ttl) + return True + + def release(self, key: str, token: str) -> bool: + with self._lock: + return self.holders.pop(token, None) is not None + + def holds(self, token: str) -> bool: + return token in self.holders and self.holders[token][1] > time.monotonic() + + +def _renewer_threads() -> list[threading.Thread]: + return [t for t in threading.enumerate() if t.name == "python-wrap-lease-renewer"] + + +def test_shared_bulkhead_starts_one_thread_for_many_calls(monkeypatch: pytest.MonkeyPatch): + started: list[Any] = [] + real_start = threading.Thread.start + + def counting_start(self: threading.Thread) -> None: + started.append(self) + real_start(self) + + monkeypatch.setattr(threading.Thread, "start", counting_start) + bulkhead = Bulkhead(8, name="renewer-threads", backend=FakeStore()) + for _ in range(1000): + with bulkhead: + pass + assert len(started) <= 1 + assert len(_renewer_threads()) <= 1 + + +def test_long_call_is_renewed(): + store = FakeStore() + lease = Lease("long", backend=store, ttl=0.3) + with lease: + time.sleep(1.0) # several TTLs: only renewal keeps the lease alive + assert store.holds(lease.token) + assert not lease.lost + assert not store.holds(lease.token) + renews = store.renew_calls + time.sleep(0.5) + assert store.renew_calls == renews # released leases are no longer renewed + + +def test_lost_lease_detected_by_renewer(): + store = FakeStore(renew_ok=False) + lease = Lease("lost", backend=store, ttl=0.3) + with pytest.raises(LeaseLost), lease: + deadline = time.monotonic() + 2.0 + while not lease.lost and time.monotonic() < deadline: + time.sleep(0.01) + assert lease.lost + renews = store.renew_calls + time.sleep(0.5) + assert store.renew_calls == renews # a lost lease is dropped from the renewer + + +def test_lease_past_its_ttl_before_renewal_is_marked_lost(): + store = FakeStore() + lease = Lease("late", backend=store, ttl=0.2) + with lease: + lease._deadline = time.monotonic() - 1 # renewal would start after expiry + lease._renew() + assert lease.lost + assert store.renew_calls == 0 + lease.lost = False # keep the exit path from raising for this unit check + + +def test_wait_poll_backs_off(): + store = FakeStore(busy=True) + lease = Lease("busy", backend=store, ttl=60, wait=True, timeout=1.0) + with pytest.raises(AlreadyRunning), lease: + pass + # A fixed 50 ms poll made about 20 attempts in one second; back-off makes about 6. + assert 3 <= store.acquire_calls <= 8 + + +@pytest.mark.parametrize(("attempt", "ttl", "left"), [(0, 60, None), (9, 60, None), (3, 0.3, 5)]) +def test_poll_delay_is_capped(attempt: int, ttl: float, left: float | None): + delay = _poll_delay(attempt, ttl, left) + assert 0 < delay <= min(0.6, ttl / 3 * 1.2 + 1e-9) + assert left is None or delay <= left + + +def test_degraded_lease_is_never_queued_for_renewal(): + class Down(FakeStore): + def acquire(self, *args: Any, **kwargs: Any) -> bool: + raise ConnectionError("store down") + + def release(self, *args: Any, **kwargs: Any) -> bool: + raise ConnectionError("store down") + + lease = Lease("down", backend=Down(), ttl=0.3, on_backend_error="allow") + with lease: + assert lease.degraded + assert not lease._queued + assert not lease._queued diff --git a/tests/test_redis_backends.py b/tests/test_redis_backends.py index 67d4029..a22aa63 100644 --- a/tests/test_redis_backends.py +++ b/tests/test_redis_backends.py @@ -588,3 +588,39 @@ def test_scripts_reload_on_noscript(redis_client): assert tokens.reserve(1, 10, 1) == 0 client.execute("SCRIPT", "FLUSH") assert tokens.reserve(1, 10, 1) == 0 and client.loaded(_LUA_STEP_SCRIPT) + + +def _limit_worker(path, active, peak, rounds): + from python_wrap import Lease, RedisSemaphore + + backend = RedisSemaphore(Client(path), "two-proc:") + + def one(_): + with Lease("pool", backend=backend, limit=2, ttl=5, wait=True, timeout=30): + with active.get_lock(): + active.value += 1 + peak.value = max(peak.value, active.value) + time.sleep(0.02) + with active.get_lock(): + active.value -= 1 + + with ThreadPoolExecutor(3) as pool: + list(pool.map(one, range(rounds))) + + +def test_bulkhead_limit_holds_across_two_processes(redis_client): + import multiprocessing + + ctx = multiprocessing.get_context("fork") + active, peak = ctx.Value("i", 0), ctx.Value("i", 0) + workers = [ + ctx.Process(target=_limit_worker, args=(redis_client.path, active, peak, 8)) + for _ in range(2) + ] + for worker in workers: + worker.start() + for worker in workers: + worker.join(90) + assert [worker.exitcode for worker in workers] == [0, 0] + assert active.value == 0 + assert peak.value <= 2 # the shared capacity holds across both processes From 24a4bf984a5b24310a668569d7607ae35ea6b451 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 27 Nov 2026 09:10:14 +0200 Subject: [PATCH 14/38] feat: idempotent task scope; re-queues no longer consume task retries - idempotent_task(scope="delivery" | "arguments") keys on the task id or the arguments; key= still overrides both. Without scope or key the arguments key is kept and a FutureWarning names the 0.5.0 default change. - A delivery that finds its task running is re-queued up to requeue_limit times, counted in the x_pw_requeues header; the task's own max_retries is not used up. - The lease default drops from 600 s to 60 s. - PW023 flags an idempotent lease longer than the visibility timeout. - Example: examples/celery_idempotent_tasks.py. --- docs/api/celery.md | 3 + docs/cookbook/framework-integrations.md | 44 +++++- .../features/resilience/presets-and-doctor.md | 2 +- docs/llms-full.txt | 6 +- examples/README.md | 1 + examples/celery_idempotent_tasks.py | 51 +++++++ src/python_wrap/celery.py | 125 ++++++++++++++-- tests/test_celery_real_worker.py | 20 +++ tests/test_celery_tasks.py | 135 +++++++++++++++++- 9 files changed, 363 insertions(+), 24 deletions(-) create mode 100644 examples/celery_idempotent_tasks.py diff --git a/docs/api/celery.md b/docs/api/celery.md index f1330b3..31f6144 100644 --- a/docs/api/celery.md +++ b/docs/api/celery.md @@ -1 +1,4 @@ ::: python_wrap.celery + +See the idempotent task scopes and the "what runs twice, what does not" table in the +[framework integrations cookbook](../cookbook/framework-integrations.md#idempotent-tasks-what-runs-twice-what-does-not). diff --git a/docs/cookbook/framework-integrations.md b/docs/cookbook/framework-integrations.md index 89faea7..dc21660 100644 --- a/docs/cookbook/framework-integrations.md +++ b/docs/cookbook/framework-integrations.md @@ -162,7 +162,7 @@ install(app) # soft limit, else hard limit minus hard_margin=5 s, becomes the d @app.task(bind=True, acks_late=True, max_retries=8, time_limit=300) -@idempotent_task(store=result_store) # RedisStore(client, "tasks:", fail_open=False) +@idempotent_task(scope="delivery", store=result_store) # RedisStore(client, "tasks:", fail_open=False) @resilient_task(vendor_policy, delays=[30, 120, 600]) def sync_orders(self, account_id: int) -> None: ... ``` @@ -171,11 +171,45 @@ def sync_orders(self, account_id: int) -> None: ... `CircuitOpenError`, `RateLimitExceeded` and `BulkheadFull`, using the error's `retry_after` as the countdown. With `requeue_when_limited=True` (default) a blocking limiter raises instead of sleeping, so the task waits in the queue and never holds a worker slot. -- `idempotent_task(key=..., store=..., ttl=...)` keys on task name plus arguments: a second - delivery returns the stored result, and a delivery that finds the task running is re-queued - after `requeue_delay` seconds instead of run. Use a shared store for a fleet. +- `idempotent_task(scope=..., store=..., ttl=...)` runs the body once per key. `scope="delivery"` + keys on the task's id, so redeliveries and retries of one task run once while two tasks with + the same arguments each run. `scope="arguments"` keys on task name plus arguments (the 0.4.x + default, with a `FutureWarning`; it becomes `"delivery"` in 0.5.0). `key=` overrides both. + A delivery that finds the task running is re-queued after about `requeue_delay` seconds (with + jitter); those re-queues are counted in the message headers and do not use the task's own + `max_retries`. After `requeue_limit` of them (default enough for a crashed owner's lease to + expire) the call raises `AlreadyRunning`. Use a shared store for a fleet. + The lease is `lease_ttl=60` seconds by default and renewed while the body runs, so a crashed + owner frees it quickly. - `check_visibility(policy, visibility_timeout)` reports PW023 for blocking limiters, - unbounded bulkhead queues and retry `max_time` that outlive the visibility timeout. + unbounded bulkhead queues and retry `max_time` and an `idempotent_task` lease longer than the visibility timeout. + +### Idempotent tasks: what runs twice, what does not + +`idempotent_task` with `scope="delivery"` is the default to reach for. The table covers the +cases that matter; a crash between an external effect and its recorded result is the one case +that can still run an effect twice (see the transactional store for that). + +| Situation | `scope="delivery"` | `scope="arguments"` (0.4.x default) | +|---|---|---| +| Broker delivers one task id twice (late ack, visibility timeout) | runs once | runs once | +| Application retries a task after a failure (same id) | runs (a failed run stores no result) | runs (same) | +| Same task id delivered again while the first run is still going | re-queued, then the stored result | re-queued, then the stored result | +| Periodic job, same arguments, new task id each time | runs every time | runs once per `ttl` (skips the repeats) | +| Two independent calls with the same arguments, new ids | both run | the second returns the first result | +| Worker killed mid-run, task redelivered later | runs after the lease expires (the lease is 60 s by default) | same | +| Direct call, no task id (tests, eager calls) | `TypeError`: pass `key=` | runs | +| External effect done, worker killed before the result is stored | runs the effect again | runs the effect again | + + +```python +from python_wrap.celery import idempotent_task + + +@app.task(bind=True, acks_late=True) +@idempotent_task(scope="delivery", ttl="10m") # one run per task id, however often delivered +def sync_orders(self, account_id: int) -> None: ... +``` ## Worker lifecycle diff --git a/docs/features/resilience/presets-and-doctor.md b/docs/features/resilience/presets-and-doctor.md index ca3ec16..733ca13 100644 --- a/docs/features/resilience/presets-and-doctor.md +++ b/docs/features/resilience/presets-and-doctor.md @@ -152,7 +152,7 @@ The doctor reports codes PW001 to PW025 (the table lists them by group, not stri | PW020 | warning | An `mcp_guard` (or a pydantic-ai / OpenAI Agents SDK tool wrapped by the python-wrap adapters) has no timeout: a hung server or tool holds the agent turn forever. See [Agent frameworks and MCP](../ai/agent-frameworks.md#doctor-checks). | | PW021 | warning | An `mcp_guard` retries every tool (`retry=` without `retry_tools=`): a retried MCP write may run twice. | | PW022 | warning | `memoize` with a shared store and no `key=` on a function with dict, set or unannotated parameters: equal arguments are keyed alike in every process, but an unsupported object raises `TypeError`. | -| PW023 | warning | `python_wrap.celery.check_visibility`: a blocking limiter, unbounded bulkhead queue or retry `max_time` can outlive the broker's visibility timeout, so the broker delivers the task again while it still runs. | +| PW023 | warning | `python_wrap.celery.check_visibility`: a blocking limiter, unbounded bulkhead queue, retry `max_time`, or an `idempotent_task` lease (`lease_ttl`) can outlive the broker's visibility timeout, so the broker delivers the task again while it still runs (for a lease: a redelivery finds the lease held and is re-queued until it expires). | | PW024 | warning | A retry layer has no backoff or jitter (`backoff=1` or no `jitter`): callers that fail together retry together, and with `--multiprocess` every worker does. Use `backoff=2, jitter="full"`. | | PW025 | warning | A retry on every `Exception` with neither `retry_if=` nor `retry_if_result=`: programming errors and non-transient failures are retried. Narrow `on=` or add a predicate. Fires together with PW003, which also covers a broad `on=` with only `retry_if_result=`. | | PW026 | warning | `memoize` with a shared store that uses plain pickle (the implicit default, or `pickle.dumps`): anyone who can write the namespace can run code in every reader. Pass `dumps=`/`loads=` (for example `json_codec()`) or `configure(cache_codec="json")`. See [Shared caches](../caching/stores-and-credentials.md#codecs). | diff --git a/docs/llms-full.txt b/docs/llms-full.txt index f259367..f888d0c 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -3734,7 +3734,7 @@ The doctor reports codes PW001 to PW025 (the table lists them by group, not stri | PW020 | warning | An `mcp_guard` (or a pydantic-ai / OpenAI Agents SDK tool wrapped by the python-wrap adapters) has no timeout: a hung server or tool holds the agent turn forever. See [Agent frameworks and MCP](../ai/agent-frameworks.md#doctor-checks). | | PW021 | warning | An `mcp_guard` retries every tool (`retry=` without `retry_tools=`): a retried MCP write may run twice. | | PW022 | warning | `memoize` with a shared store and no `key=` on a function with dict, set or unannotated parameters: equal arguments are keyed alike in every process, but an unsupported object raises `TypeError`. | -| PW023 | warning | `python_wrap.celery.check_visibility`: a blocking limiter, unbounded bulkhead queue or retry `max_time` can outlive the broker's visibility timeout, so the broker delivers the task again while it still runs. | +| PW023 | warning | `python_wrap.celery.check_visibility`: a blocking limiter, unbounded bulkhead queue, retry `max_time`, or an `idempotent_task` lease (`lease_ttl`) can outlive the broker's visibility timeout, so the broker delivers the task again while it still runs (for a lease: a redelivery finds the lease held and is re-queued until it expires). | | PW024 | warning | A retry layer has no backoff or jitter (`backoff=1` or no `jitter`): callers that fail together retry together, and with `--multiprocess` every worker does. Use `backoff=2, jitter="full"`. | | PW025 | warning | A retry on every `Exception` with neither `retry_if=` nor `retry_if_result=`: programming errors and non-transient failures are retried. Narrow `on=` or add a predicate. Fires together with PW003, which also covers a broad `on=` with only `retry_if_result=`. | | PW026 | warning | `memoize` with a shared store that uses plain pickle (the implicit default, or `pickle.dumps`): anyone who can write the namespace can run code in every reader. Pass `dumps=`/`loads=` (for example `json_codec()`) or `configure(cache_codec="json")`. See [Shared caches](../caching/stores-and-credentials.md#codecs). | @@ -4771,8 +4771,8 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Signal subscription handle; close disconnects only this app's handlers. - `python_wrap.celery.check_visibility`: `check_visibility(target: Any, visibility_timeout: float) -> tuple[Any, ...]` PW023: blocking waits that can outlive the broker's ``visibility_timeout``. -- `python_wrap.celery.idempotent_task`: `idempotent_task(*, key: Any = None, store: Any = None, ttl: float | str = '1d', backend: Any = None, lease_ttl: float | str = 600, requeue_delay: float = 30.0, max_retries: int | None = None) -> Any` - Run a bound task once per name and arguments, even when the broker delivers it twice. +- `python_wrap.celery.idempotent_task`: `idempotent_task(*, key: Any = None, scope: str | None = None, store: Any = None, ttl: float | str = '1d', backend: Any = None, lease_ttl: float | str = 60, requeue_delay: float = 30.0, requeue_limit: int | None = None, max_retries: int | None = None) -> Any` + Run a bound task once per delivery (``scope="delivery"``) or per arguments, even when the broker delivers it twice. - `python_wrap.celery.install`: `install(app: Any, *, use_soft_deadline: bool = True, hard_margin: float = 5.0, inherit_deadline: bool = False) -> TaskContext` Bind task_id/name and a deadline from the task's time limit around task execution. - `python_wrap.celery.resilient_task`: `resilient_task(policy: Any = None, *, requeue_on: tuple[type[BaseException], ...] | None = None, delays: Sequence[float] | None = None, max_retries: int | None = None, requeue_when_limited: bool = True, **schedule: Any) -> Any` diff --git a/examples/README.md b/examples/README.md index fdbd67c..0eaf3e6 100644 --- a/examples/README.md +++ b/examples/README.md @@ -11,6 +11,7 @@ $ python examples/resilient_http.py | --- | --- | --- | | [`resilient_http.py`](resilient_http.py) | Retry with backoff and jitter, circuit breaker per host, rate limit, overall timeout, against a fake transport | [Resilient HTTP client](../docs/cookbook/resilient-http-client.md) | | [`request_propagation.py`](request_propagation.py) | Pass a trusted request id and remaining deadline to a downstream HTTP call, offline | [Framework integrations](../docs/cookbook/framework-integrations.md) | +| [`celery_idempotent_tasks.py`](celery_idempotent_tasks.py) | `idempotent_task(scope="delivery")`: a redelivered task runs once, a periodic job with the same arguments runs every time, offline | [Framework integrations](../docs/cookbook/framework-integrations.md#idempotent-tasks-what-runs-twice-what-does-not) | | [`async_crawler.py`](async_crawler.py) | `map_async`, a `Bulkhead` per host, `race` over mirrors, `run_sync` | [Async crawler](../docs/cookbook/async-crawler.md) | | [`web_caching.py`](web_caching.py) | `memoize(ttl=)`, `singleflight` against thundering herds, per-user `rate_limit` (framework-free) | [FastAPI](../docs/cookbook/fastapi.md) | | [`service_layer.py`](service_layer.py) | Cached service functions, `transactional` commit/rollback hooks, `deprecate` | [Django](../docs/cookbook/django.md) | diff --git a/examples/celery_idempotent_tasks.py b/examples/celery_idempotent_tasks.py new file mode 100644 index 0000000..748b6a9 --- /dev/null +++ b/examples/celery_idempotent_tasks.py @@ -0,0 +1,51 @@ +"""Idempotent Celery tasks: one run per delivery, redelivery and periodic work, offline. + +The broker is simulated with a fake task object that carries a request id, the way a +delivered Celery task does. Real code decorates a bound ``@app.task(bind=True)`` the same way. +Run with ``python examples/celery_idempotent_tasks.py``. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +from python_wrap.celery import idempotent_task + + +class FakeTask: + """Stands in for a bound Celery task: a name and a request with the delivery's id.""" + + name = "examples.sync_orders" + + def __init__(self, task_id: str) -> None: + self.request = SimpleNamespace(id=task_id, retries=0) + + +runs: list[str] = [] + + +@idempotent_task(scope="delivery", ttl="10m") +def sync_orders(self: FakeTask, account_id: int) -> str: + runs.append(f"{self.request.id}:{account_id}") + return f"synced account {account_id}" + + +def main() -> None: + # 1. Two messages, one task id (the broker delivers twice): the body runs once. + print("delivery 1:", sync_orders(FakeTask("task-a"), 42)) + print("delivery 2:", sync_orders(FakeTask("task-a"), 42)) + print("runs so far:", runs) + + # 2. A periodic job with the same arguments but a new task id: it runs again. + print("hourly run:", sync_orders(FakeTask("task-b"), 42)) + print("runs so far:", runs) + + # 3. A direct call has no id: pass key= (or scope="arguments") instead. + try: + sync_orders(SimpleNamespace(name="examples.sync_orders", request=SimpleNamespace()), 42) + except TypeError as exc: + print("direct call:", exc) + + +if __name__ == "__main__": + main() diff --git a/src/python_wrap/celery.py b/src/python_wrap/celery.py index 338012b..de41a45 100644 --- a/src/python_wrap/celery.py +++ b/src/python_wrap/celery.py @@ -16,6 +16,7 @@ from __future__ import annotations import contextvars +import warnings from collections.abc import Sequence from typing import Any, NoReturn @@ -470,48 +471,120 @@ def wrapper(*args: Any, **kwargs: Any) -> Any: return decorate +_DEFAULT_SCOPE_WARNED = False +_SCOPES = (None, "delivery", "arguments") + + +def _warn_default_scope() -> None: + global _DEFAULT_SCOPE_WARNED + if _DEFAULT_SCOPE_WARNED: + return + _DEFAULT_SCOPE_WARNED = True + warnings.warn( + "idempotent_task() without scope= or key= keeps the arguments key in python-wrap " + "0.4.x; from 0.5.0 the default is scope='delivery' (one run per task id). Pass " + "scope='arguments' to keep today's behaviour or scope='delivery' to adopt the new " + "default.", + FutureWarning, + stacklevel=3, + ) + + +def _requeues(task: Any) -> int: + """How many times this delivery was already re-queued because its key was running.""" + return int(_header(getattr(task, "request", None), "x_pw_requeues") or 0) + + def idempotent_task( *, key: Any = None, + scope: str | None = None, store: Any = None, ttl: float | str = "1d", backend: Any = None, - lease_ttl: float | str = 600, + lease_ttl: float | str = 60, requeue_delay: float = 30.0, + requeue_limit: int | None = None, max_retries: int | None = None, ) -> Any: - """Run a bound task once per name and arguments, even when the broker delivers it twice. + """Run a bound task once per delivery (``scope="delivery"``) or per arguments, even when + the broker delivers it twice. With late acknowledgement a task is delivered again after a worker dies, and a task that outlives the visibility timeout is delivered while it still runs. The result is stored - under the task name plus its arguments (override with ``key=``): a repeat delivery returns - the stored result without running the body, and a delivery that arrives while the first - still runs is re-queued after ``requeue_delay`` seconds instead of run. + under a key; a repeat delivery returns the stored result without running the body, and a + delivery that arrives while the first still runs is re-queued after about + ``requeue_delay`` seconds instead of run. + + Scopes: + + - ``"delivery"``: the key is the task's id. Redeliveries and retries of one task run once; + two tasks with the same arguments (a periodic job) each run. Needs a task id, so the + task must be delivered by the broker (a direct call raises `TypeError`; pass ``key=``). + - ``"arguments"``: the key is the task name plus its arguments. Two calls with the same + arguments within ``ttl`` are one run: use it only for work that is truly repeated by + content. + - ``None`` (the 0.4.x default): the arguments key, with a `FutureWarning`. From 0.5.0 the + default is ``"delivery"``. + + ``key=`` overrides both scopes. + + Waiting for a running or dead owner does not use the task's own retry allowance: the + re-queue passes ``max_retries=request.retries + 1`` and counts its own re-queues in the + ``x_pw_requeues`` header, up to ``requeue_limit`` (default: enough for a crashed owner's + lease to expire, ``ceil(lease_ttl / requeue_delay) + 2``). Then `AlreadyRunning` is raised. Use a shared ``store`` (``RedisStore(client, prefix, fail_open=False)``) so every worker sees the same results; the default is per process. Same crash gap as `idempotent`: an external effect and its recorded result are not one atomic step. Args: - key: ``str`` or ``callable(task, *args, **kwargs)``; default task name + arguments. + key: ``str`` or ``callable(task, *args, **kwargs)``; overrides ``scope``. + scope: ``"delivery"``, ``"arguments"`` or None (see above). store: Result store (see `python_wrap.idempotency.idempotent`). ttl: How long a result is kept. backend: Shared lease backend (derived from a `RedisStore`). - lease_ttl: Lease held while the body runs (renewed automatically). - requeue_delay: Countdown for a delivery that finds the task running. - max_retries: Overrides the task's ``max_retries`` for that re-queue. + lease_ttl: Lease held while the body runs (renewed every third of it). A crashed + owner's lease frees after this long. + requeue_delay: Base countdown for a delivery that finds the task running (jittered). + requeue_limit: Re-queues allowed for one delivery before `AlreadyRunning`. + max_retries: Celery ``max_retries`` for the re-queue. Default: the task's own count + plus one, so the re-queue never exhausts the task's retries. """ import functools + import math - from python_wrap._runtime import stable_digest + from python_wrap._runtime import seconds, stable_digest from python_wrap.coordination import AlreadyRunning from python_wrap.idempotency import idempotent + if scope not in _SCOPES: + raise ValueError("scope must be 'delivery', 'arguments' or None") + if requeue_delay <= 0: + raise ValueError("requeue_delay must be positive") + if requeue_limit is not None and requeue_limit < 0: + raise ValueError("requeue_limit must not be negative") + lease_seconds = seconds(lease_ttl) + allowed = ( + requeue_limit if requeue_limit is not None else math.ceil(lease_seconds / requeue_delay) + 2 + ) + if scope is None and key is None: + _warn_default_scope() + def derive(task: Any, *args: Any, **kwargs: Any) -> str: if isinstance(key, str): return key if key is not None: return str(key(task, *args, **kwargs)) + if scope == "delivery": + request_id = getattr(getattr(task, "request", None), "id", None) + if not request_id: + raise TypeError( + "idempotent_task(scope='delivery') needs a task id: the task was called " + "directly, not delivered by the broker. Call it with .delay() or " + ".apply_async(), or pass key= (or scope='arguments') for a direct call." + ) + return f"celery:{task.name}:id:{request_id}" return f"celery:{task.name}:{stable_digest((args, sorted(kwargs.items())))}" def decorate(func: Any) -> Any: @@ -525,8 +598,24 @@ def wrapper(*args: Any, **kwargs: Any) -> Any: try: return once(*args, **kwargs) except AlreadyRunning as exc: - retry_task(task, exc, delays=[requeue_delay], max_retries=max_retries) - + count = _requeues(task) + if count >= allowed: + raise + countdown = retry_countdown( + task, exc, delays=[requeue_delay], jitter=requeue_delay / 2 + ) + limit = max_retries if max_retries is not None else task.request.retries + 1 + raise task.retry( + exc=exc, + countdown=countdown, + max_retries=limit, + headers={"x_pw_requeues": count + 1}, + ) from None + + wrapper.__python_wrap_layer__ = ( # type: ignore[attr-defined] + "idempotent", + {"scope": scope or "arguments", "lease_ttl": lease_seconds}, + ) return wrapper return decorate @@ -554,6 +643,18 @@ def check_visibility(target: Any, visibility_timeout: float) -> tuple[Any, ...]: reason = "a bulkhead queue with no timeout can wait without a bound" elif layer.role == "retry" and (s.get("max_time") or 0) > visibility_timeout: reason = f"retry max_time {s['max_time']:g}s exceeds the visibility timeout" + elif layer.role == "idempotent" and (s.get("lease_ttl") or 0) > visibility_timeout: + found.append( + Finding( + "PW023", + "warning", + f"idempotent_task lease of {s['lease_ttl']:g}s exceeds the visibility " + f"timeout of {visibility_timeout:g}s: a redelivery after a worker crash " + "finds the lease still held and is re-queued until it expires. Lower " + "lease_ttl below the visibility timeout.", + ) + ) + continue if reason: found.append( Finding( diff --git a/tests/test_celery_real_worker.py b/tests/test_celery_real_worker.py index ae626c8..dafb9cf 100644 --- a/tests/test_celery_real_worker.py +++ b/tests/test_celery_real_worker.py @@ -117,3 +117,23 @@ def test_explicit_header_is_not_overwritten(app): handle.close() assert data["header_request_id"] == "explicit-id" assert data["log"]["request_id"] == "explicit-id" + + +def test_task_delivered_twice_runs_once_with_delivery_scope(app): + # The killed-worker redelivery is not reproducible in-process, so this checks the part + # that is: two messages carrying one task id run the body once under scope="delivery". + from python_wrap.celery import idempotent_task + + runs: list[int] = [] + + @app.task(name="pw.real.once", bind=True, shared=False) + @idempotent_task(scope="delivery", ttl="10m") + def once(self, n): + runs.append(n) + return n * 10 + + with start_worker(app, pool="solo", perform_ping_check=False, shutdown_timeout=20): + first = app.tasks["pw.real.once"].apply_async((4,), task_id="g15-real-same-id") + again = app.tasks["pw.real.once"].apply_async((4,), task_id="g15-real-same-id") + assert first.get(timeout=20) == again.get(timeout=20) == 40 + assert runs == [4] diff --git a/tests/test_celery_tasks.py b/tests/test_celery_tasks.py index 00e8c26..7d94a62 100644 --- a/tests/test_celery_tasks.py +++ b/tests/test_celery_tasks.py @@ -4,6 +4,7 @@ import contextlib import contextvars +import warnings from types import SimpleNamespace from typing import Any @@ -19,6 +20,7 @@ ) from python_wrap.circuit import CircuitBreaker from python_wrap.concurrency import RateLimiter +from python_wrap.coordination import AlreadyRunning from python_wrap.errors import CircuitOpenError @@ -29,19 +31,21 @@ class Requeued(Exception): class Task: name = "demo.task" - def __init__(self) -> None: - self.request = SimpleNamespace(retries=0) + def __init__(self, task_id: str | None = None) -> None: + self.request = SimpleNamespace(retries=0, id=task_id) self.countdown: float | None = None + self.options: dict[str, Any] = {} def retry(self, **options: Any) -> Requeued: self.countdown = options["countdown"] + self.options = options return Requeued() def test_idempotent_task_runs_body_once_for_a_redelivery() -> None: runs: list[int] = [] - @idempotent_task() + @idempotent_task(scope="arguments") def body(self: Task, n: int) -> int: runs.append(n) return n * 2 @@ -141,3 +145,128 @@ def record(fields: dict[str, Any], budget: float | None = None) -> contextlib.Ex assert bound[0]["request_id"] == "req-16" assert bound[1]["request_id_inherited"] is False assert "request_id" not in bound[1] + + +def test_delivery_scope_runs_each_distinct_task_id() -> None: + runs: list[int] = [] + + @idempotent_task(scope="delivery") + def body(self: Task, n: int) -> int: + runs.append(n) + return n + + body(Task("g15-distinct-1"), 7) + body(Task("g15-distinct-2"), 7) + assert runs == [7, 7] + + +def test_delivery_scope_runs_once_for_a_redelivery() -> None: + runs: list[int] = [] + + @idempotent_task(scope="delivery") + def body(self: Task, n: int) -> int: + runs.append(n) + return n * 2 + + first, again = Task("g15-redeliver"), Task("g15-redeliver") + assert body(first, 3) == body(again, 3) == 6 + assert runs == [3] + + +def test_arguments_scope_keeps_old_behaviour() -> None: + runs: list[int] = [] + + @idempotent_task(scope="arguments") + def body(self: Task, n: int) -> int: + runs.append(n) + return n + + body(Task("g15-args-1"), 9) + body(Task("g15-args-2"), 9) + assert runs == [9] + + +def test_default_scope_warns_in_0_4(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(pw_celery, "_DEFAULT_SCOPE_WARNED", False) + with pytest.warns(FutureWarning, match="0.5.0"): + idempotent_task()(lambda self: 1) + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + idempotent_task()(lambda self: 1) + assert not [w for w in seen if issubclass(w.category, FutureWarning)] + + +def test_key_overrides_scope_without_warning() -> None: + with warnings.catch_warnings(): + warnings.simplefilter("error") + + @idempotent_task(key="g15-fixed", scope="delivery") + def body(self: Task) -> str: + return "ran" + + assert body(Task("g15-key-a")) == "ran" + assert body(Task("g15-key-b")) == "ran" # the stored result under the fixed key + + +def test_requeue_while_running_does_not_consume_retries() -> None: + @idempotent_task(scope="delivery", requeue_delay=30) + def body(self: Task) -> str: + with pytest.raises(Requeued): + outer_call(self) # same id: finds the lease held by this run + return "done" + + outer_call = body + task = Task("g15-requeue") + task.request.retries = 2 + assert body(task) == "done" + # The nested delivery was re-queued (not raised) with the task's own limit kept open. + assert task.options["max_retries"] == 3 + assert task.options["headers"] == {"x_pw_requeues": 1} + assert 30 <= task.countdown <= 45 + + +def test_requeue_limit_then_already_running() -> None: + attempts: list[str] = [] + + @idempotent_task(scope="delivery", requeue_limit=2) + def body(self: Task) -> str: + for count in range(3): + self.request.x_pw_requeues = count + try: + body_inner(self) + attempts.append("ran") + except AlreadyRunning: + attempts.append("already-running") + except Requeued: + attempts.append("requeued") + return "done" + + body_inner = body + task = Task("g15-limit") + assert body(task) == "done" + assert attempts == ["requeued", "requeued", "already-running"] + + +def test_missing_task_id_raises_with_hint() -> None: + @idempotent_task(scope="delivery") + def body(self: Task) -> int: + return 1 + + with pytest.raises(TypeError, match="key="): + body(Task(None)) + + +def test_pw023_lease_longer_than_visibility() -> None: + @idempotent_task(scope="delivery", lease_ttl=600) + def body(self: Task) -> int: + return 1 + + found = check_visibility(body, 300) + assert [f.code for f in found] == ["PW023"] + assert "lease" in found[0].message + + @idempotent_task(scope="delivery", lease_ttl=60) + def short(self: Task) -> int: + return 1 + + assert check_visibility(short, 300) == () From 0f4c396c18cb2798ab2154d07742afe423f23f68 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Mon, 30 Nov 2026 13:46:46 +0200 Subject: [PATCH 15/38] Complete cache coordination and resilience fixes --- CHANGELOG.md | 16 +++ docs/features/caching/memoize.md | 6 + docs/features/configuration.md | 2 + docs/features/resilience/http-clients.md | 5 +- docs/llms-full.txt | 12 +- src/python_wrap/adapters/langchain.py | 2 +- src/python_wrap/async_cache.py | 31 +++-- src/python_wrap/caching.py | 164 ++++++++++++++++++++--- src/python_wrap/coordination.py | 40 ++++++ src/python_wrap/events.py | 3 +- src/python_wrap/http.py | 57 +++++--- src/python_wrap/idempotency.py | 20 ++- src/python_wrap/policies.py | 59 +++++--- tests/test_cache_coordination.py | 27 +++- tests/test_http_policy.py | 10 ++ tests/test_http_requests.py | 5 +- tests/test_policy_watch.py | 12 +- tests/test_redis_backends.py | 13 +- tests/test_sql_result_store.py | 20 +++ 19 files changed, 421 insertions(+), 83 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e72f18d..689d48d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,22 @@ Breaking changes are listed under **Breaking changes**, each with its migration. ## [Unreleased] +### Added + +- Tagged cache invalidation returns the number of shared writes and supports + `require_shared=True`. Both cache decorators support `lock_wait=None` to wait + for the shared lease. +- Policy watches support strict startup validation and optional polling jitter. +- HTTP policies cap cached host state with `max_hosts` (default 1000). + +### Fixed + +- Shared caches batch tag reads and recreate missing version tokens so deleting + a tag key cannot revive an old entry. +- HTTP policies honor a host's 429 pause without requiring a configured limiter. +- Failed transactional idempotent calls remove their own unfinished claim. +- LangChain transport models with `max_retries=None` are rebuilt with retries disabled. + ## [0.4.1] - unreleased ### Security diff --git a/docs/features/caching/memoize.md b/docs/features/caching/memoize.md index bc69bc4..4702079 100644 --- a/docs/features/caching/memoize.md +++ b/docs/features/caching/memoize.md @@ -491,6 +491,12 @@ Unlike v0.1, every decorated function gets its own store, even when one `cache(. `memoize` (and `cache`) emit `cache.hit`, `cache.miss` and `cache.evicted` (field `reason`: `"lru"` or `"ttl"`) to `python_wrap.events` listeners, with the function's qualified name. With `stale_ttl` they also emit `cache.stale` (a stale value was served and a background refresh started; the hit itself is reported as `cache.hit`) and `cache.refresh_failed` (field `exception`). With no listener registered this costs one list check. See [Metrics](../observability/metrics.md) for recipes. +## Shared tags and leases + +Use `tags=` to attach versioned tags to entries. In a worker that has not created a tagged cache, pass the Redis client explicitly to `invalidate_tags("orders", client=client, require_shared=True)`. The return value counts successful shared writes. For async Redis clients, await `ainvalidate_tags`. + +Use `lock_wait=None` to wait until a shared lease can be acquired. With a finite `lock_wait`, the cache rechecks the stored value when the initial wait expires and continues waiting when the backend confirms a holder is still active. + ## Testing Use `python_wrap.testing.disable_caching()` to bypass every cache in tests: nothing is read, written or refreshed. `ttl` and `stale_ttl` run on the package clock, so `python_wrap.testing.fake_clock()` makes entries expire or turn stale without waiting (see the example under [Serving stale values](#serving-stale-values-while-refreshing)). diff --git a/docs/features/configuration.md b/docs/features/configuration.md index 6cfa242..8dd67c9 100644 --- a/docs/features/configuration.md +++ b/docs/features/configuration.md @@ -47,6 +47,8 @@ instead. `configure()` sets defaults read at decoration time; a watched policy c on every replica without a restart, for example to lower a rate limit or stop retries for one dependency during an incident. See [named policies](resilience/named-policies.md). +A policy watch accepts `strict=True` to raise on a failed initial read or invalid mapping. Use `jitter=0.1` to vary the poll interval by up to 10 percent in either direction. + ## Keys | Key | Effect | diff --git a/docs/features/resilience/http-clients.md b/docs/features/resilience/http-clients.md index e77c083..3f2860a 100644 --- a/docs/features/resilience/http-clients.md +++ b/docs/features/resilience/http-clients.md @@ -133,7 +133,7 @@ mount_policy(session, policy) - 5xx responses and transport errors count as breaker failures; 4xx never do. `breaker=True` builds a default breaker (5 failures, 30 s) that uses `configure(shared=...)` when set, so every worker shares it. -- A `429` with `Retry-After` pauses later calls to that host (if a `limiter` is set) instead of +- A `429` with `Retry-After` pauses later calls to that host instead of letting them fail; a wait longer than `max_retry_after` or the deadline raises `RateLimitExceeded`. - `connect_timeout` / `read_timeout` apply only where the caller set none (`requests` has none @@ -141,7 +141,8 @@ mount_policy(session, policy) [deadline](../resilience/timeout.md). - Without `per_host`, pass ready-made objects and every host shares them. With it, pass factories `name -> object` (a ready-made object is rejected so state is never shared by - accident). + accident). `max_hosts` defaults to 1000 and bounds remembered host guards and pauses. + An evicted host gets fresh local guards on its next request. - `RetryTransport`, `AsyncRetryTransport` and `mount_retries` stay as thin retry-only wrappers. ## aiohttp and hand-written clients diff --git a/docs/llms-full.txt b/docs/llms-full.txt index f888d0c..a9e0b35 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -4431,11 +4431,11 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Post a chat message when a circuit breaker reaches a chosen state. - `python_wrap.__version__` Constant: '0.4.1' -- `python_wrap.ainvalidate_tags`: `ainvalidate_tags(*names: str, client: Any = None) -> None` +- `python_wrap.ainvalidate_tags`: `ainvalidate_tags(*names: str, client: Any = None, require_shared: bool = False) -> int` `invalidate_tags` for ``redis.asyncio`` clients (amemoize with AsyncRedisStore). - `python_wrap.amap_iter`: `amap_iter(fn: Callable[[T], Awaitable[R]], items: Iterable[T] | AsyncIterable[T], *, limit: int, ordered: bool = True, return_exceptions: bool = False) -> AsyncGenerator[Any, None]` Apply `fn` to every item, at most `limit` at a time, yielding results as they come. -- `python_wrap.amemoize`: `amemoize(*, ttl: float | None = None, key: Callable[..., Hashable] | None = None, store: AsyncCacheStore | None = None, cache_none: bool = True, copy_result: bool = False, singleflight: bool = True, stale_ttl: float | datetime.timedelta | None = None, cache_exceptions: type[BaseException] | tuple[type[BaseException], ...] = (), exception_ttl: float | datetime.timedelta | None = None, logger: _core.LoggerLike = None, lock: Any = None, lock_ttl: float = 30, lock_wait: float = 5, tags: Callable[..., Any] | None = None, ttl_jitter: float = 0.0) -> Callable[[F], F]` +- `python_wrap.amemoize`: `amemoize(*, ttl: float | None = None, key: Callable[..., Hashable] | None = None, store: AsyncCacheStore | None = None, cache_none: bool = True, copy_result: bool = False, singleflight: bool = True, stale_ttl: float | datetime.timedelta | None = None, cache_exceptions: type[BaseException] | tuple[type[BaseException], ...] = (), exception_ttl: float | datetime.timedelta | None = None, logger: _core.LoggerLike = None, lock: Any = None, lock_ttl: float = 30, lock_wait: float | None = 5, tags: Callable[..., Any] | None = None, ttl_jitter: float = 0.0) -> Callable[[F], F]` Cache the results of an ``async def`` function in an `AsyncCacheStore`. - `python_wrap.aprocess_batches`: `aprocess_batches(items: Iterable[Any], handler: Callable[[Any], Any], *, chunk_size: int = 500, classify: Callable[[Exception], str] = , checkpoint: Any = None, on_progress: Callable[[int, int], Any] | None = None) -> BatchResult[Any, Any]` Await per-item processing with the same checkpoint and outcome semantics. @@ -4513,7 +4513,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Walk cause/context and driver .orig links, including cycles, once per exception. - `python_wrap.invalidate`: `invalidate(instance: object, *names: str) -> int` Forget cached `cached_property` values of ``instance``. -- `python_wrap.invalidate_tags`: `invalidate_tags(*names: str, client: Any = None) -> None` +- `python_wrap.invalidate_tags`: `invalidate_tags(*names: str, client: Any = None, require_shared: bool = False) -> int` Make every cached entry written with one of these tags miss on its next read. - `python_wrap.is_sensitive`: `is_sensitive(name: object, fragments: Iterable[str] | None = None, *, match: str = 'segment') -> bool` Return True when ``name`` looks like it holds a secret. @@ -4535,7 +4535,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Guard an MCP tool-call path with a timeout, retries and a per-server breaker. - `python_wrap.measure_memory`: `measure_memory(func: Callable[..., Any] | None = None, /, *, logger: LoggerLike = None, level: int = 20, callback: Callable[[MemoryRecord], None] | None = None, exclusive: bool = True) -> Any` Measure the Python memory a call allocates, using `tracemalloc`. -- `python_wrap.memoize`: `memoize(func: Callable[..., Any] | None = None, /, *, maxsize: int | None = None, ttl: float | datetime.timedelta | Callable[[Any], float | None] | None = None, stale_ttl: float | datetime.timedelta | None = None, typed: bool = False, key: Callable[..., Hashable] | None = None, cache_exceptions: type[BaseException] | tuple[type[BaseException], ...] = (), exception_ttl: float | datetime.timedelta | None = None, store: CacheStore | None = None, per_instance: bool = False, singleflight: bool = False, copy_result: bool = False, logger: _core.LoggerLike = None, lock: Any = None, lock_ttl: float = 30, lock_wait: float = 5, tags: Callable[..., Any] | None = None, ttl_jitter: float = 0.0) -> Any` +- `python_wrap.memoize`: `memoize(func: Callable[..., Any] | None = None, /, *, maxsize: int | None = None, ttl: float | datetime.timedelta | Callable[[Any], float | None] | None = None, stale_ttl: float | datetime.timedelta | None = None, typed: bool = False, key: Callable[..., Hashable] | None = None, cache_exceptions: type[BaseException] | tuple[type[BaseException], ...] = (), exception_ttl: float | datetime.timedelta | None = None, store: CacheStore | None = None, per_instance: bool = False, singleflight: bool = False, copy_result: bool = False, logger: _core.LoggerLike = None, lock: Any = None, lock_ttl: float = 30, lock_wait: float | None = 5, tags: Callable[..., Any] | None = None, ttl_jitter: float = 0.0) -> Any` Cache a function's results per argument values. - `python_wrap.message_contains`: `message_contains(*fragments: str, case_sensitive: bool = False) -> Predicate` Match any fragment in an exception's message (case-insensitive by default). @@ -4923,7 +4923,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm The asyncio counterpart of `PolicyTransport` for ``httpx.AsyncClient``. - `python_wrap.http.AsyncRetryTransport`: `AsyncRetryTransport(inner: Any, policy: HttpRetryPolicy | None = None)` The asyncio counterpart of `RetryTransport` for ``httpx.AsyncClient``. -- `python_wrap.http.HttpPolicy`: `HttpPolicy(retry: HttpRetryPolicy = , breaker: Any = None, limiter: Any = None, bulkhead: Any = None, connect_timeout: float | None = None, read_timeout: float | None = None, per_host: bool = False, shared: Any = None, propagate: bool = False)` +- `python_wrap.http.HttpPolicy`: `HttpPolicy(retry: HttpRetryPolicy = , breaker: Any = None, limiter: Any = None, bulkhead: Any = None, connect_timeout: float | None = None, read_timeout: float | None = None, per_host: bool = False, shared: Any = None, propagate: bool = False, max_hosts: int = 1000)` Retries plus a circuit breaker, rate limiter, bulkhead and timeouts for HTTP calls. - `python_wrap.http.IDEMPOTENT_METHODS` Constant: frozenset({'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PUT', 'TRACE'}) @@ -5143,7 +5143,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Type alias: python_wrap.policies.PolicySource - `python_wrap.policies.RedisSource`: `RedisSource(client: Any, key: str = 'python-wrap:policies')` One Redis string key holding the JSON mapping, shared by every replica. -- `python_wrap.policies.Watch`: `Watch(registry: PolicyRegistry, source: PolicySource, interval: float)` +- `python_wrap.policies.Watch`: `Watch(registry: PolicyRegistry, source: PolicySource, interval: float, *, strict: bool = False, jitter: float = 0)` A running `PolicyRegistry.watch`; ``stop()`` ends it. - `python_wrap.policy.ROLES` Constant: ('observe', 'validate', 'fallback', 'cache', 'limiter', 'bulkhead', 'breaker', 'retry', 'timeout', 'guard') diff --git a/src/python_wrap/adapters/langchain.py b/src/python_wrap/adapters/langchain.py index b42a9c9..6a35d97 100644 --- a/src/python_wrap/adapters/langchain.py +++ b/src/python_wrap/adapters/langchain.py @@ -45,7 +45,7 @@ def without_retries(model: Any) -> Any: bound = getattr(model, "bound", None) if bound is not None and hasattr(model, "model_copy"): # bind_tools() and friends return model.model_copy(update={"bound": without_retries(bound)}) - if not getattr(model, "max_retries", 0): + if getattr(model, "max_retries", 0) == 0: return model fields = {name: getattr(model, name) for name in getattr(model, "model_fields_set", ())} try: diff --git a/src/python_wrap/async_cache.py b/src/python_wrap/async_cache.py index dd9adf5..904bfc7 100644 --- a/src/python_wrap/async_cache.py +++ b/src/python_wrap/async_cache.py @@ -32,17 +32,16 @@ from python_wrap._backend import _NOT_GIVEN, BackendMonitor, resolve_mode from python_wrap._runtime import name_digest, stable_digest from python_wrap.caching import ( - _TAG_PREFIX, CacheInfo, _async_tag_clients, _async_tag_store_owners, _await_shared, - _decode, _exception_types, _make_key_builder, _register_tag_client, _shared_future, _tag_versions, + _tag_versions_async, _ttl_seconds, ) from python_wrap.stores import ( @@ -438,7 +437,7 @@ def amemoize( logger: _core.LoggerLike = None, lock: Any = None, lock_ttl: float = 30, - lock_wait: float = 5, + lock_wait: float | None = 5, tags: Callable[..., Any] | None = None, ttl_jitter: float = 0.0, ) -> Callable[[F], F]: @@ -478,7 +477,7 @@ def amemoize( process computes a missing key, the others wait up to ``lock_wait`` and read the store again. Stale refreshes take it without waiting. Needs ``store``. lock_ttl: Seconds the stampede lease lives (renewed while computing). - lock_wait: Seconds a process waits for another's computation. + lock_wait: Seconds to wait for another process, or None to wait for its lease. tags: ``tags(*args, **kwargs)`` returning tag names; see `python_wrap.caching.invalidate_tags` and ``ainvalidate_tags``. ttl_jitter: Shorten each ttl by a random share up to this (0 to 1). @@ -530,7 +529,9 @@ async def main() -> None: if not 0 <= ttl_jitter < 1: raise ValueError("ttl_jitter must be in [0, 1)") tag_client: Any = getattr(store, "client", None) if tags is not None else None - tag_async = tag_client is not None and _core.is_async(tag_client.get) + tag_async = tag_client is not None and ( + isinstance(store, AsyncRedisStore) or _core.is_async(tag_client.get) + ) if tag_async: _register_tag_client(_async_tag_clients, _async_tag_store_owners, tag_client, store) elif tag_client is not None: @@ -541,10 +542,7 @@ async def main() -> None: async def versions(names: list[str]) -> dict[str, str] | None: if not tag_async: return _tag_versions(names, tag_client) - try: - return {n: _decode(await tag_client.get(_TAG_PREFIX + name_digest(n))) for n in names} - except Exception: # unknown versions read as a miss - return None + return await _tag_versions_async(names, tag_client) stale_s = _ttl_seconds(stale_ttl) exc_types = _exception_types(cache_exceptions) @@ -586,6 +584,8 @@ def count(hit: bool) -> None: _core.emit("cache.hit" if hit else "cache.miss", name) async def save(k: Hashable, value: Any, is_exc: bool, tv: Any = None) -> None: + if tags is not None and tv is None: + return life = exc_ttl if is_exc else ttl if ttl_jitter and life: life *= 1 - random.random() * ttl_jitter # nosec B311 - not security @@ -627,13 +627,22 @@ async def compute(k: Hashable, args: Any, kwargs: Any, refreshing: bool = False) """Compute and store, once across processes when ``lock`` is set.""" if lock is None: return await run(k, args, kwargs) - from python_wrap.coordination import AlreadyRunning + from python_wrap.coordination import AlreadyRunning, _held_async lease = lease_for(k, not refreshing) try: await lease.__aenter__() except AlreadyRunning: - lease = None + found, value, is_exc, _ = await read(k) + if found: + if is_exc: + raise value from None + return value + if not refreshing and await _held_async(lease.backend, lease.key): + lease.timeout = None + await lease.__aenter__() + else: + lease = None try: if lease is None or not refreshing: found, value, is_exc, stale = await read(k) diff --git a/src/python_wrap/caching.py b/src/python_wrap/caching.py index 51591b1..93cc7ff 100644 --- a/src/python_wrap/caching.py +++ b/src/python_wrap/caching.py @@ -581,16 +581,98 @@ def _decode(value: Any) -> str: return value.decode() if isinstance(value, bytes) else str(value or "") +# Set on a client whose MGET failed once (cluster slots, proxies): later reads use GET. +_NO_MGET = "_python_wrap_no_mget" + + +def _tag_keys(names: list[str]) -> list[str]: + return [_TAG_PREFIX + name_digest(n) for n in names] + + +def _remember_no_mget(client: Any) -> None: + with contextlib.suppress(AttributeError, TypeError): + setattr(client, _NO_MGET, True) + + +def _fetch_values(client: Any, keys: list[str]) -> list[Any]: + """Raw values for ``keys``: one MGET when the client has it, else one GET per key.""" + if getattr(client, "mget", None) is not None and not getattr(client, _NO_MGET, False): + try: + return list(client.mget(keys)) + except Exception: # e.g. MGET across cluster slots: fall back, and remember it + values = [client.get(k) for k in keys] + _remember_no_mget(client) + return values + return [client.get(k) for k in keys] + + +async def _fetch_values_async(client: Any, keys: list[str]) -> list[Any]: + """`_fetch_values` for ``redis.asyncio`` clients.""" + if getattr(client, "mget", None) is not None and not getattr(client, _NO_MGET, False): + try: + return list(await client.mget(keys)) + except Exception: + values = [await client.get(k) for k in keys] + _remember_no_mget(client) + return values + return [await client.get(k) for k in keys] + + +def _token_versions(names: list[str], raw: list[Any]) -> dict[str, str]: + return {n: _decode(v) for n, v in zip(names, raw, strict=True)} + + def _tag_versions(names: list[str], client: Any) -> dict[str, str] | None: - """Current token per tag (from Redis when shared); None if the store cannot answer.""" + """Current token per tag (from Redis when shared); None if the store cannot answer. + + A tag with no version key gets a random token (SET NX, so concurrent creators agree + on one): an empty token would revive entries written before a deleted key. + """ if client is None: - return {n: f"{_tag_epoch[0]}:{_local_tags.get(n, '')}" for n in names} + tokens = {} + for n in names: + token = _local_tags.get(n) + if token is None: + token = uuid.uuid4().hex + _remember_local(n, token) + tokens[n] = token + return {n: f"{_tag_epoch[0]}:{tokens[n]}" for n in names} + if not names: + return {} + keys = _tag_keys(names) try: - return {n: _decode(client.get(_TAG_PREFIX + name_digest(n))) for n in names} + raw = _fetch_values(client, keys) + if any(v is None for v in raw): + for key, value in zip(keys, raw, strict=True): + if value is None: + client.set(key, uuid.uuid4().hex, nx=True) + raw = _fetch_values(client, keys) # read back: the winner's token everywhere + if any(v is None for v in raw): + return None # dropped again at once: unknown, so a miss + return _token_versions(names, raw) except Exception: # an unknown version must read as a miss, never as a hit return None +async def _tag_versions_async(names: list[str], client: Any) -> dict[str, str] | None: + """`_tag_versions` for ``redis.asyncio`` clients.""" + if not names: + return {} + keys = _tag_keys(names) + try: + raw = await _fetch_values_async(client, keys) + if any(v is None for v in raw): + for key, value in zip(keys, raw, strict=True): + if value is None: + await client.set(key, uuid.uuid4().hex, nx=True) + raw = await _fetch_values_async(client, keys) + if any(v is None for v in raw): + return None + return _token_versions(names, raw) + except Exception: + return None + + def _remember_local(name: str, token: str) -> None: if len(_local_tags) >= _MAX_LOCAL_TAGS and name not in _local_tags: _local_tags.clear() # tag names may come from data: bound the memory @@ -598,27 +680,61 @@ def _remember_local(name: str, token: str) -> None: _local_tags[name] = token -def invalidate_tags(*names: str, client: Any = None) -> None: +def _no_shared_store(require_shared: bool, written: int) -> None: + if require_shared and written == 0: + raise RuntimeError( + "invalidate_tags(require_shared=True) wrote no shared store: pass client= " + "or invalidate from a process that built a tagged memoize(store=...)" + ) + + +def invalidate_tags(*names: str, client: Any = None, require_shared: bool = False) -> int: """Make every cached entry written with one of these tags miss on its next read. Each tag gets a new version token: in this process, and in Redis through every sync client used by a ``memoize(tags=..., store=RedisStore(...))`` here (and - ``client`` when given). One write per tag, no scan. Async clients: `ainvalidate_tags`. + ``client`` when given). One write per tag and client, no scan. Every target is + tried; the first error is raised after all of them. Returns the number of shared + writes made. ``require_shared=True`` raises RuntimeError when that number is 0 + (a process with no store would otherwise invalidate only itself). Async clients: + `ainvalidate_tags`. """ + written = 0 + first_error: Exception | None = None for name in names: token = uuid.uuid4().hex _remember_local(name, token) for target in _tag_client_targets(_tag_clients, _tag_store_owners, client): - target.set(_TAG_PREFIX + name_digest(name), token) + try: + target.set(_TAG_PREFIX + name_digest(name), token) + except Exception as exc: + first_error = first_error or exc + else: + written += 1 + if first_error is not None: + raise first_error + _no_shared_store(require_shared, written) + return written -async def ainvalidate_tags(*names: str, client: Any = None) -> None: +async def ainvalidate_tags(*names: str, client: Any = None, require_shared: bool = False) -> int: """`invalidate_tags` for ``redis.asyncio`` clients (amemoize with AsyncRedisStore).""" + written = 0 + first_error: Exception | None = None for name in names: token = uuid.uuid4().hex _remember_local(name, token) for target in _tag_client_targets(_async_tag_clients, _async_tag_store_owners, client): - await target.set(_TAG_PREFIX + name_digest(name), token) + try: + await target.set(_TAG_PREFIX + name_digest(name), token) + except Exception as exc: + first_error = first_error or exc + else: + written += 1 + if first_error is not None: + raise first_error + _no_shared_store(require_shared, written) + return written @overload @@ -642,7 +758,7 @@ def memoize( logger: _core.LoggerLike = None, lock: Any = None, lock_ttl: float = 30, - lock_wait: float = 5, + lock_wait: float | None = 5, tags: Callable[..., Any] | None = None, ttl_jitter: float = 0.0, ) -> Callable[[Callable[P, R]], Memoized[P, R]]: ... @@ -664,7 +780,7 @@ def memoize( logger: _core.LoggerLike = None, lock: Any = None, lock_ttl: float = 30, - lock_wait: float = 5, + lock_wait: float | None = 5, tags: Callable[..., Any] | None = None, ttl_jitter: float = 0.0, ) -> Any: @@ -757,7 +873,7 @@ def memoize( compute only if the entry is still absent. Stale refreshes take the same lease without waiting, so one process refreshes. Needs ``store``. lock_ttl: Seconds the stampede lease lives (renewed while computing). - lock_wait: Seconds a process waits for another's computation. + lock_wait: Seconds to wait for another process, or None to wait for its lease. tags: ``tags(*args, **kwargs)`` returning tag names for the entry; see `invalidate_tags`. Each tag costs one store read per hit. ttl_jitter: Shorten each entry's ttl by a random share up to this (0 to 1), so @@ -977,6 +1093,10 @@ def save( snapshot = isolate(value) if copy_result and not is_exc else value if not is_exc and seconds is not None and seconds <= 0: return snapshot # not stored, but async waiters still need a private outcome + if tags is not None and tv is None: + # Versions unknown (store down): an entry without them would never read as + # outdated, so it is not stored and the next read recomputes. + return snapshot keep = seconds if seconds is not None and stale_s is not None and not is_exc: keep = seconds + stale_s @@ -1024,13 +1144,20 @@ def cached_outcome(b: Any, k: Hashable) -> tuple[bool, Any]: def once_across_processes(b: Any, k: Hashable, run: Callable[[], Any]) -> Any: """Run ``run()`` (returns ``(snapshot, result)``) unless another process did.""" - from python_wrap.coordination import AlreadyRunning + from python_wrap.coordination import AlreadyRunning, _held_sync lease = lease_for(k, True) try: lease.__enter__() except AlreadyRunning: - lease = None # waited lock_wait: use its result if it landed, else compute + found, value = cached_outcome(b, k) + if found: + return value, value + if _held_sync(lease.backend, lease.key): + lease.timeout = None + lease.__enter__() + else: + lease = None try: found, value = cached_outcome(b, k) return (value, value) if found else run() @@ -1043,13 +1170,20 @@ async def aonce_across_processes( b: Any, k: Hashable, run: Callable[[], Awaitable[Any]] ) -> Any: """Async `once_across_processes`; ``run()`` returns the saved result.""" - from python_wrap.coordination import AlreadyRunning + from python_wrap.coordination import AlreadyRunning, _held_async lease = lease_for(k, True) try: await lease.__aenter__() except AlreadyRunning: - lease = None + found, value = cached_outcome(b, k) + if found: + return value + if await _held_async(lease.backend, lease.key): + lease.timeout = None + await lease.__aenter__() + else: + lease = None try: found, value = cached_outcome(b, k) return value if found else await run() diff --git a/src/python_wrap/coordination.py b/src/python_wrap/coordination.py index 80541dd..8f70e78 100644 --- a/src/python_wrap/coordination.py +++ b/src/python_wrap/coordination.py @@ -6,6 +6,7 @@ import contextlib import hashlib import heapq +import inspect import logging import math import os @@ -84,6 +85,37 @@ def release(self, key: str, token: str) -> bool: self._entries.pop(key, None) return expires is not None and expires > _core.monotonic() + def held(self, key: str) -> bool: + """True while any owner's lease on ``key`` has not expired.""" + with self._lock: + now = _core.monotonic() + return any(expires > now for expires in self._entries.get(key, {}).values()) + + +def _held_sync(backend: Any, key: str) -> bool: + """Whether the backend reports the lease held. False if unsupported or unavailable.""" + held = getattr(backend, "held", None) + if held is None: + return False + try: + return bool(held(key)) + except Exception: + return False + + +async def _held_async(backend: Any, key: str) -> bool: + """Awaitable `_held_sync` for async backends (sync ones are accepted too).""" + held = getattr(backend, "held", None) + if held is None: + return False + try: + result = held(key) + if inspect.isawaitable(result): + result = await result + return bool(result) + except Exception: + return False + def _validate_request(key: str, token: str, ttl: float, limit: int) -> None: if not isinstance(key, str) or not key or not isinstance(token, str) or not token: @@ -98,6 +130,7 @@ def _validate_request(key: str, token: str, ttl: float, limit: int) -> None: redis.call('ZREMRANGEBYSCORE',KEYS[1],'-inf',now) local op=ARGV[1]; local token=ARGV[2]; local ttl=tonumber(ARGV[3]); local limit=tonumber(ARGV[4]) if op=='release' then return redis.call('ZREM',KEYS[1],token) end +if op=='held' then return redis.call('ZCARD',KEYS[1]) end if op=='renew' then if not redis.call('ZSCORE',KEYS[1],token) then return 0 end elseif not redis.call('ZSCORE',KEYS[1],token) and redis.call('ZCARD',KEYS[1])>=limit then @@ -139,6 +172,10 @@ def renew(self, key: str, token: str, ttl: float) -> bool: def release(self, key: str, token: str) -> bool: return self._call("release", key, token, 1) + def held(self, key: str) -> bool: + """True while the lease key has an unexpired owner (expired owners are trimmed).""" + return bool(_LEASE_SCRIPT.run(self.client, 1, self.prefix + key, "held", "-", 1, 1)) + class RedisSemaphore(RedisLock): """The same atomic lease backend, with capacity supplied by Lease(limit=...).""" @@ -170,6 +207,9 @@ async def renew(self, key: str, token: str, ttl: float) -> bool: # type: ignore async def release(self, key: str, token: str) -> bool: # type: ignore[override] return await self._call("release", key, token, 1) + async def held(self, key: str) -> bool: # type: ignore[override] + return bool(await _LEASE_SCRIPT.arun(self.client, 1, self.prefix + key, "held", "-", 1, 1)) + class AsyncRedisSemaphore(AsyncRedisLock): """`AsyncRedisLock` with capacity supplied by Lease(limit=...).""" diff --git a/src/python_wrap/events.py b/src/python_wrap/events.py index 2d51504..1efad8b 100644 --- a/src/python_wrap/events.py +++ b/src/python_wrap/events.py @@ -144,8 +144,9 @@ ), "config.rejected": ( "A watched policy source could not be read or validated; the current policies " - "stay. function is 'policies'. Fields: error (str, the exception class)." + "stay. function is 'policies'. Fields: error (str, the exception class), message (str)." ), + "http.host_evicted": "A local host guard was evicted. function is the host policy name.", "backend.recovered": ( "A shared backend answered again after backend.error. Fields: backend (str)." ), diff --git a/src/python_wrap/http.py b/src/python_wrap/http.py index 692c273..67b90fa 100644 --- a/src/python_wrap/http.py +++ b/src/python_wrap/http.py @@ -17,6 +17,7 @@ import contextlib import importlib import logging +from collections import OrderedDict from collections.abc import Awaitable, Callable, Iterable, Mapping from dataclasses import dataclass, field from typing import Any @@ -325,12 +326,12 @@ class HttpPolicy: """Retries plus a circuit breaker, rate limiter, bulkhead and timeouts for HTTP calls. Attributes: - retry: The `HttpRetryPolicy` (method safety, backoff, ``Retry-After``). + retry: The `HttpRetryPolicy` (method safety, backoff, ``Retry-After``). A 429 with + ``Retry-After`` pauses later calls to that host. breaker: ``True`` (5 failures, 30 s), a `CircuitBreaker`, or with ``per_host`` a factory ``name -> CircuitBreaker``. 5xx responses and transport errors count as failures; 4xx responses never do. limiter: A `RateLimiter`, or with ``per_host`` a factory ``name -> RateLimiter``. - A 429 ``Retry-After`` pauses later calls to that host instead of failing them. bulkhead: A `Bulkhead`, or with ``per_host`` a factory ``name -> Bulkhead``. connect_timeout: Used when the caller set no connect timeout. read_timeout: Used when the caller set no read timeout. @@ -360,13 +361,18 @@ class HttpPolicy: per_host: bool = False shared: Any = None propagate: bool = False - _hosts: dict[str, tuple[Any, Any, Any]] = field( - default_factory=dict, init=False, repr=False, compare=False + max_hosts: int = 1000 + _hosts: OrderedDict[str, tuple[Any, Any, Any]] = field( + default_factory=OrderedDict, init=False, repr=False, compare=False + ) + _blocked: OrderedDict[str, float] = field( + default_factory=OrderedDict, init=False, repr=False, compare=False ) - _blocked: dict[str, float] = field(default_factory=dict, init=False, repr=False, compare=False) _lock: Any = field(default_factory=_fork.ForkSafeLock, init=False, repr=False, compare=False) def __post_init__(self) -> None: + if type(self.max_hosts) is not int or self.max_hosts < 1: + raise ValueError("max_hosts must be a positive integer") for name in ("connect_timeout", "read_timeout"): value = getattr(self, name) if value is not None and not value > 0: @@ -422,15 +428,24 @@ def guards(self, host: str) -> tuple[Any, Any, Any]: for kind in ("breaker", "limiter", "bulkhead") ) self._hosts[key] = found - return found + if len(self._hosts) > self.max_hosts: + evicted, _ = self._hosts.popitem(last=False) + else: + evicted = None + else: + self._hosts.move_to_end(key) + evicted = None + if evicted is not None: + _core.emit("http.host_evicted", f"http:{evicted}") + return found # -- helpers shared by the sync and async paths ------------------------------------ def _blocked_wait(self, host: str) -> float: with self._lock: - until = self._blocked.get(host, 0.0) - wait = until - _core.monotonic() - if wait <= 0: - return 0.0 + wait = self._blocked.get(host, 0.0) - _core.monotonic() + if wait <= 0: + self._blocked.pop(host, None) + return 0.0 left = _deadline_remaining() if wait > self.retry.max_retry_after or (left is not None and wait >= left): from python_wrap.errors import RateLimitExceeded @@ -439,12 +454,16 @@ def _blocked_wait(self, host: str) -> float: return wait def _note(self, host: str, response: Any) -> None: - if self.limiter is None or _status_of(response) != 429: + if _status_of(response) != 429: return hinted = retry_after_header(response) if hinted: with self._lock: - self._blocked[host] = _core.monotonic() + hinted + until = _core.monotonic() + hinted + self._blocked[host] = max(until, self._blocked.get(host, 0.0)) + self._blocked.move_to_end(host) + if len(self._blocked) > self.max_hosts: + self._blocked.popitem(last=False) def _request_headers(self, headers: Any) -> None: """Add the request id and the remaining deadline to an outgoing header mapping.""" @@ -490,10 +509,9 @@ def requests_timeout(self, timeout: Any) -> Any: def call(self, host: str, send: Callable[[], Any]) -> Any: """One attempt through the guards: limiter, bulkhead, breaker, then ``send()``.""" breaker, limiter, bulkhead = self.guards(host) - if limiter is not None: - wait = self._blocked_wait(host) - if wait: - _core.sleep(wait) + wait = self._blocked_wait(host) + if wait: + _core.sleep(wait) def counted() -> Any: response = send() @@ -517,10 +535,9 @@ def counted() -> Any: async def acall(self, host: str, send: Callable[[], Awaitable[Any]]) -> Any: """`call` for coroutines.""" breaker, limiter, bulkhead = self.guards(host) - if limiter is not None: - wait = self._blocked_wait(host) - if wait: - await _core.async_sleep(wait) + wait = self._blocked_wait(host) + if wait: + await _core.async_sleep(wait) async def counted() -> Any: response = await send() diff --git a/src/python_wrap/idempotency.py b/src/python_wrap/idempotency.py index c3b17e6..ccb4ad6 100644 --- a/src/python_wrap/idempotency.py +++ b/src/python_wrap/idempotency.py @@ -208,6 +208,15 @@ def _finish(self, conn: Any, key: str, value: Any, ttl: float, owner: str) -> No }, ) + def _abandon(self, conn: Any, key: str, owner: str) -> None: + conn.execute( + self._sql( + f"DELETE FROM {self.table} WHERE idem_key=:k" # nosec B608 + " AND owner=:o AND status='running'" + ), + {"k": name_digest(key), "o": owner}, + ) + # -- the result-store contract used by idempotent ------------------------------------ def get(self, key: str) -> tuple[Any] | None: with self.engine.connect() as conn: @@ -439,8 +448,15 @@ def wrapper(*args: Any, **kw: Any) -> Any: if in_progress == "return_none": return None raise AlreadyRunning("idem:" + k) - value = func(*args, **kw) - store._finish(conn, k, value, retention, owner) + try: + value = func(*args, **kw) + store._finish(conn, k, value, retention, owner) + except BaseException as exc: + try: + store._abandon(conn, k, owner) + except Exception as cleanup_error: + raise exc from cleanup_error + raise return value return wrapper diff --git a/src/python_wrap/policies.py b/src/python_wrap/policies.py index dfd17ef..b3c4df6 100644 --- a/src/python_wrap/policies.py +++ b/src/python_wrap/policies.py @@ -12,6 +12,7 @@ import builtins import json import os +import random import threading import time from collections.abc import Callable, Mapping @@ -87,14 +88,27 @@ class Watch: first policy resolution (`ensure_running`); `alive` reports False until then. """ - def __init__(self, registry: PolicyRegistry, source: PolicySource, interval: float): + def __init__( + self, + registry: PolicyRegistry, + source: PolicySource, + interval: float, + *, + strict: bool = False, + jitter: float = 0, + ): self.registry, self.source, self.interval = registry, source, interval + self.jitter = jitter + self._last_error: tuple[type[Exception], str] | None = None self._stop = threading.Event() self._last: str | None = None self._last_ok: float | None = None self._pid = os.getpid() self._thread: threading.Thread | None = None - self.poll() # the first read happens now, so a broken source fails loudly + if strict: + self._read_and_apply() + else: + self.poll() self._start() def _start(self) -> None: @@ -130,24 +144,35 @@ def ensure_running(self) -> None: self._pid = os.getpid() self._start() + def _read_and_apply(self) -> bool: + mapping = self.source.read() + text = json.dumps(mapping, sort_keys=True, default=repr) + changed = text != self._last + if changed: + self.registry.load_from_mapping(mapping) + self._last = text + self._last_ok = time.monotonic() + self._last_error = None + return changed + def poll(self) -> bool: """Read the source once; apply it if it changed. True when a change was applied.""" try: - mapping = self.source.read() - text = json.dumps(mapping, sort_keys=True, default=repr) - self._last_ok = time.monotonic() - if text == self._last: - return False - self.registry.load_from_mapping(mapping) + return self._read_and_apply() except Exception as exc: - # A bad mapping keeps the current policies; the source is retried next poll. - _core.emit("config.rejected", "policies", error=type(exc).__name__) + kind = type(exc).__name__ + message = "Policy source read or validation failed" + _core.emit("config.rejected", "policies", error=kind, message=message) + error = (type(exc), str(exc)) + if error != self._last_error: + _core.get_logger(None).warning("%s (%s)", message, kind) + self._last_error = error return False - self._last = text - return True def _run(self, stop: threading.Event) -> None: - while not stop.wait(self.interval): + while not stop.wait( + self.interval * (1 + random.uniform(-self.jitter, self.jitter)) # nosec B311 + ): self.poll() def stop(self) -> None: @@ -237,7 +262,9 @@ def _restart_watches(self) -> None: for watch in list(self._watches): watch.ensure_running() - def watch(self, source: PolicySource, interval: float = 30) -> Watch: + def watch( + self, source: PolicySource, interval: float = 30, *, strict: bool = False, jitter: float = 0 + ) -> Watch: """Poll ``source`` every ``interval`` seconds and apply each changed mapping. A whole mapping is validated before it is applied; a bad one keeps the current @@ -248,7 +275,9 @@ def watch(self, source: PolicySource, interval: float = 30) -> Watch: """ if interval <= 0: raise ValueError("interval must be positive") - watch = Watch(self, source, interval) + if not 0 <= jitter < 1: + raise ValueError("jitter must be in [0, 1)") + watch = Watch(self, source, interval, strict=strict, jitter=jitter) self._watches.append(watch) return watch diff --git a/tests/test_cache_coordination.py b/tests/test_cache_coordination.py index 79ae2f4..e489aee 100644 --- a/tests/test_cache_coordination.py +++ b/tests/test_cache_coordination.py @@ -81,8 +81,12 @@ def __init__(self) -> None: self.set_calls = 0 self.closed = False - async def get(self, key: str) -> bytes | None: - return self.data.get(key) + def get(self, key: str) -> Any: + # redis.asyncio command methods return awaitables from regular methods. + async def read() -> bytes | None: + return self.data.get(key) + + return read() async def set(self, key: str, value: bytes, **_: Any) -> bool: if self.closed: @@ -288,3 +292,22 @@ def f(n: int) -> int: assert len(set(ttls)) > 1 with pytest.raises(ValueError): memoize(ttl_jitter=1.0) + + +def test_tag_versions_missing_key_cannot_revive_old_result() -> None: + from python_wrap.caching import _tag_keys + + client = SyncRedis() + store = RedisStore(client, "deleted-tag:", dumps=json.dumps, loads=json.loads) + calls = 0 + + @memoize(store=store, tags=lambda: ["deleted"]) + def cached() -> int: + nonlocal calls + calls += 1 + return calls + + assert cached() == cached() == 1 + assert invalidate_tags("deleted", client=client, require_shared=True) >= 1 + client.delete(*_tag_keys(["deleted"])) + assert cached() == cached() == 2 diff --git a/tests/test_http_policy.py b/tests/test_http_policy.py index 940653b..9e2f06b 100644 --- a/tests/test_http_policy.py +++ b/tests/test_http_policy.py @@ -110,3 +110,13 @@ async def main() -> int: def test_per_host_rejects_a_single_shared_object() -> None: with pytest.raises(ValueError): HttpPolicy(breaker=CircuitBreaker(name="x"), per_host=True) + + +def test_per_host_guards_evict_least_recently_used() -> None: + policy = HttpPolicy(breaker=True, per_host=True, max_hosts=2) + first = policy.guards("a") + second = policy.guards("b") + assert policy.guards("a") is first + policy.guards("c") + assert policy.guards("a") is first + assert policy.guards("b") is not second diff --git a/tests/test_http_requests.py b/tests/test_http_requests.py index 9a27546..c59acde 100644 --- a/tests/test_http_requests.py +++ b/tests/test_http_requests.py @@ -20,7 +20,6 @@ from python_wrap.errors import CircuitOpenError # noqa: E402 from python_wrap.http import HttpPolicy, HttpRetryPolicy, mount_policy # noqa: E402 from python_wrap.logs import log_context # noqa: E402 -from python_wrap.ratelimit import RateLimiter # noqa: E402 class _Handler(BaseHTTPRequestHandler): @@ -212,9 +211,7 @@ def test_mount_policy_429_pause(local_server): server = local_server server.statuses["/limited"] = 429 server.retry_after["/limited"] = "1" - policy = HttpPolicy( - limiter=RateLimiter(calls=100, period=1.0), retry=HttpRetryPolicy(max_attempts=1) - ) + policy = HttpPolicy(retry=HttpRetryPolicy(max_attempts=1)) session = _session() mount_policy(session, policy) diff --git a/tests/test_policy_watch.py b/tests/test_policy_watch.py index c622c60..39adba3 100644 --- a/tests/test_policy_watch.py +++ b/tests/test_policy_watch.py @@ -102,7 +102,10 @@ def boom() -> None: unsubscribe() names = [name for name, _ in seen] assert names.count("config.changed") == 2 - assert ("config.rejected", {"error": "JSONDecodeError"}) in seen + assert ( + "config.rejected", + {"error": "JSONDecodeError", "message": "Policy source read or validation failed"}, + ) in seen def test_unchanged_mapping_keeps_generation(monkeypatch: pytest.MonkeyPatch) -> None: @@ -133,3 +136,10 @@ def test_global_registry_reports_generations_in_health() -> None: policies.register("health-probe", timeout=1) report = health.report() assert report["policies"]["generations"]["health-probe"] >= 1 + + +def test_strict_watch_rejects_invalid_source_at_start(tmp_path: Path) -> None: + path = tmp_path / "policies.json" + path.write_text("{", encoding="utf-8") + with pytest.raises(json.JSONDecodeError): + PolicyRegistry().watch(FileSource(path), strict=True) diff --git a/tests/test_redis_backends.py b/tests/test_redis_backends.py index a22aa63..a57a120 100644 --- a/tests/test_redis_backends.py +++ b/tests/test_redis_backends.py @@ -81,10 +81,13 @@ def read(): def get(self, key): return self.execute("GET", key) + def mget(self, keys): + return self.execute("MGET", *keys) + def set(self, key, value, **kw): args = ["SET", key, value] for k, v in kw.items(): - args.extend([k.upper(), v]) + args.extend([k.upper()] if v is True else [k.upper(), v]) return self.execute(*args) def delete(self, *keys): @@ -428,6 +431,7 @@ def _raise(): def test_redis_tags_and_stampede_lease_across_wrappers(redis_client): from python_wrap import invalidate_tags + from python_wrap.caching import _tag_keys store = RedisStore(redis_client, "tagged:", fail_open=False) calls = [] @@ -439,13 +443,16 @@ def price(sku): lock = RedisLock(redis_client, "memo-locks:") workers = [ - memoize(store=store, ttl=60, lock=lock, tags=lambda sku: [f"sku:{sku}"])(price) + memoize(store=store, ttl=60, lock=lock, lock_wait=0.01, tags=lambda sku: [f"sku:{sku}"])( + price + ) for _ in range(8) ] with ThreadPoolExecutor(8) as pool: assert set(pool.map(lambda fn: fn("a1"), workers)) == {1} assert calls == ["a1"] - invalidate_tags("sku:a1", client=redis_client) + assert invalidate_tags("sku:a1", client=redis_client, require_shared=True) == 1 + redis_client.delete(*_tag_keys(["sku:a1"])) assert workers[3]("a1") == 2 diff --git a/tests/test_sql_result_store.py b/tests/test_sql_result_store.py index c023a85..7022a06 100644 --- a/tests/test_sql_result_store.py +++ b/tests/test_sql_result_store.py @@ -153,3 +153,23 @@ def test_validation() -> None: async def nope() -> None: ... assert "NVARCHAR(MAX)" in SqlResultStore.ddl("mssql")[0] + + +def test_failed_call_removes_its_claim_even_if_caller_commits(engine: Any) -> None: + with engine.begin() as conn: + calls = 0 + + @idempotent(store=SqlResultStore(engine), connection=lambda: conn) + def run() -> int: + nonlocal calls + calls += 1 + if calls == 1: + raise ValueError("failed") + return calls + + with pytest.raises(ValueError, match="failed"): + run() + + with engine.begin() as conn: + assert run() == 2 + assert run() == 2 From dd32e37d8da91843a74af453b3bcb5db5f5243aa Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Mon, 30 Nov 2026 13:48:45 +0200 Subject: [PATCH 16/38] Share HTTP pauses and guard configuration through Redis --- CHANGELOG.md | 3 +- README.md | 5 + docs/features/resilience/http-clients.md | 4 + src/python_wrap/http.py | 130 +++++++++++++++++++++-- src/python_wrap/shared.py | 9 +- tests/test_http_policy.py | 51 +++++++++ tests/test_stability.py | 2 + tests/test_stable_keys.py | 1 + 8 files changed, 192 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 689d48d..46d3d9e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration. `require_shared=True`. Both cache decorators support `lock_wait=None` to wait for the shared lease. - Policy watches support strict startup validation and optional polling jitter. -- HTTP policies cap cached host state with `max_hosts` (default 1000). +- HTTP policies cap cached host state with `max_hosts` (default 1000), accept + limiter and bulkhead mappings, and share 429 pauses through Redis. ### Fixed diff --git a/README.md b/README.md index 77f9232..3fe72bf 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,11 @@ circuit breaker, timeout, policies, presets) is now frozen ahead of 1.0. The stable core is frozen: retry, circuit breaker, timeout and deadline, policies, presets, errors and events. It does not change incompatibly before 1.0. +For shared HTTP policies, `HttpPolicy(shared=redis, per_host=True)` shares +429 pauses across processes. Pass `limiter={"calls": 50, "period": 1}` and +`bulkhead={"max_concurrent": 8}` to share those per-host guards as well. +See [HTTP clients](https://pythonwrap.readthedocs.io/en/latest/features/resilience/http-clients/). + Provisional modules may change in a minor release. They are `shared`, `coordination`, `quotas`, `stores`, `http` and `celery` (target 0.5.0), and `async_cache`, `web`, `exporters` and `observability` (target 0.6.0). The newer integrations (dashboard, chaos, diff --git a/docs/features/resilience/http-clients.md b/docs/features/resilience/http-clients.md index 3f2860a..0228849 100644 --- a/docs/features/resilience/http-clients.md +++ b/docs/features/resilience/http-clients.md @@ -143,6 +143,10 @@ mount_policy(session, policy) factories `name -> object` (a ready-made object is rejected so state is never shared by accident). `max_hosts` defaults to 1000 and bounds remembered host guards and pauses. An evicted host gets fresh local guards on its next request. +- With `shared=` set to a Redis client, policies share 429 pauses and check Redis at + most once per second per remembered host. A store failure leaves the local pause + in effect. Use `limiter={"calls": 50, "period": 1}` and + `bulkhead={"max_concurrent": 8}` to build guards backed by the same Redis client. - `RetryTransport`, `AsyncRetryTransport` and `mount_retries` stay as thin retry-only wrappers. ## aiohttp and hand-written clients diff --git a/src/python_wrap/http.py b/src/python_wrap/http.py index 67b90fa..8733933 100644 --- a/src/python_wrap/http.py +++ b/src/python_wrap/http.py @@ -14,17 +14,22 @@ from __future__ import annotations +import asyncio import contextlib import importlib import logging +import math from collections import OrderedDict from collections.abc import Awaitable, Callable, Iterable, Mapping from dataclasses import dataclass, field from typing import Any from python_wrap import _core, _fork +from python_wrap._backend import BackendMonitor +from python_wrap._runtime import name_digest from python_wrap.deadline import remaining as _deadline_remaining from python_wrap.retry import RetryBudget, _compute_delay, http_status, retry, retry_after_header +from python_wrap.shared import _async_redis_client __all__ = [ "IDEMPOTENT_METHODS", @@ -321,6 +326,10 @@ def __init__(self, response: Any) -> None: self.response = response +def _pause_key(host: str) -> str: + return "python-wrap:http-pause:" + name_digest(host) + + @dataclass(frozen=True) class HttpPolicy: """Retries plus a circuit breaker, rate limiter, bulkhead and timeouts for HTTP calls. @@ -368,6 +377,15 @@ class HttpPolicy: _blocked: OrderedDict[str, float] = field( default_factory=OrderedDict, init=False, repr=False, compare=False ) + _pause_checks: OrderedDict[str, float] = field( + default_factory=OrderedDict, init=False, repr=False, compare=False + ) + _pause_monitor: BackendMonitor = field( + default_factory=lambda: BackendMonitor("http", "pause", "allow", register=False), + init=False, + repr=False, + compare=False, + ) _lock: Any = field(default_factory=_fork.ForkSafeLock, init=False, repr=False, compare=False) def __post_init__(self) -> None: @@ -380,6 +398,17 @@ def __post_init__(self) -> None: for name in ("limiter", "bulkhead"): if getattr(self, name) is True: raise ValueError(f"{name}=True is not allowed: pass the object or a factory") + for kind, required in ( + ("limiter", {"calls", "period"}), + ("bulkhead", {"max_concurrent"}), + ): + options = getattr(self, kind) + if isinstance(options, Mapping): + if options.keys() != required: + raise ValueError( + f"{kind} mapping requires exactly {', '.join(sorted(required))}" + ) + object.__setattr__(self, kind, dict(options)) if self.per_host: from python_wrap.bulkhead import Bulkhead from python_wrap.circuit import CircuitBreaker @@ -395,6 +424,18 @@ def __post_init__(self) -> None: # -- per-host state ---------------------------------------------------------------- def _build(self, kind: str, value: Any, name: str) -> Any: + if isinstance(value, Mapping) and kind in ("limiter", "bulkhead"): + from python_wrap.bulkhead import Bulkhead + from python_wrap.concurrency import RateLimiter + from python_wrap.shared import resolve_shared + + sb = resolve_shared(self.shared) + if kind == "bulkhead": + lease = None if sb is None else sb.lease_backend() + return Bulkhead(value["max_concurrent"], name=name, backend=lease) + calls, period = value["calls"], value["period"] + window = None if sb is None else sb.rate_window(name, calls, period) + return RateLimiter(calls, period, name=name, backend=window) if value is None or (not callable(value) and value is not True): return value if value is True: # only the breaker has a default @@ -453,17 +494,82 @@ def _blocked_wait(self, host: str) -> float: raise RateLimitExceeded(f"{host} asked clients to wait {wait:.1f}s", retry_after=wait) return wait - def _note(self, host: str, response: Any) -> None: - if _status_of(response) != 429: + def _pause_client(self) -> Any: + from python_wrap.shared import resolve_shared + + shared = resolve_shared(self.shared) + return None if shared is None else shared.client + + def _should_read_pause(self, host: str) -> bool: + now = _core.monotonic() + with self._lock: + previous = self._pause_checks.get(host) + if previous is not None and now - previous < 1: + return False + self._pause_checks[host] = now + self._pause_checks.move_to_end(host) + if len(self._pause_checks) > self.max_hosts: + self._pause_checks.popitem(last=False) + return True + + def _remember_pause(self, host: str, seconds: float) -> None: + if seconds <= 0: + return + with self._lock: + until = _core.monotonic() + seconds + self._blocked[host] = max(until, self._blocked.get(host, 0.0)) + self._blocked.move_to_end(host) + if len(self._blocked) > self.max_hosts: + self._blocked.popitem(last=False) + + def _read_pause(self, host: str) -> None: + client = self._pause_client() + if client is not None and self._should_read_pause(host): + millis = self._pause_monitor.call( + "pttl", lambda: client.pttl(_pause_key(host)), lambda: 0 + ) + self._remember_pause(host, millis / 1000) + + async def _aread_pause(self, host: str) -> None: + client = self._pause_client() + if client is None: return - hinted = retry_after_header(response) + if not _async_redis_client(client): + await asyncio.to_thread(self._read_pause, host) + elif self._should_read_pause(host): + millis = await self._pause_monitor.acall( + "pttl", lambda: client.pttl(_pause_key(host)), lambda: 0 + ) + self._remember_pause(host, millis / 1000) + + def _note(self, host: str, response: Any) -> None: + hinted = retry_after_header(response) if _status_of(response) == 429 else None if hinted: - with self._lock: - until = _core.monotonic() + hinted - self._blocked[host] = max(until, self._blocked.get(host, 0.0)) - self._blocked.move_to_end(host) - if len(self._blocked) > self.max_hosts: - self._blocked.popitem(last=False) + self._remember_pause(host, hinted) + client = self._pause_client() + if client is not None: + self._pause_monitor.call( + "set", + lambda: client.set(_pause_key(host), "1", px=math.ceil(hinted * 1000)), + lambda: None, + ) + + async def _anote(self, host: str, response: Any) -> None: + hinted = retry_after_header(response) if _status_of(response) == 429 else None + if not hinted: + return + client = self._pause_client() + if client is None: + self._remember_pause(host, hinted) + elif not _async_redis_client(client): + await asyncio.to_thread(self._note, host, response) + else: + self._remember_pause(host, hinted) + await self._pause_monitor.acall( + "set", + lambda: client.set(_pause_key(host), "1", px=math.ceil(hinted * 1000)), + lambda: None, + ) def _request_headers(self, headers: Any) -> None: """Add the request id and the remaining deadline to an outgoing header mapping.""" @@ -508,7 +614,9 @@ def requests_timeout(self, timeout: Any) -> Any: def call(self, host: str, send: Callable[[], Any]) -> Any: """One attempt through the guards: limiter, bulkhead, breaker, then ``send()``.""" + host = host.lower().rstrip(".") breaker, limiter, bulkhead = self.guards(host) + self._read_pause(host) wait = self._blocked_wait(host) if wait: _core.sleep(wait) @@ -534,7 +642,9 @@ def counted() -> Any: async def acall(self, host: str, send: Callable[[], Awaitable[Any]]) -> Any: """`call` for coroutines.""" + host = host.lower().rstrip(".") breaker, limiter, bulkhead = self.guards(host) + await self._aread_pause(host) wait = self._blocked_wait(host) if wait: await _core.async_sleep(wait) @@ -555,7 +665,7 @@ async def counted() -> Any: response = await breaker.call(counted) if breaker is not None else await counted() except _ServerError as exc: response = exc.response - self._note(host, response) + await self._anote(host, response) return response diff --git a/src/python_wrap/shared.py b/src/python_wrap/shared.py index c4b7b8b..b008fee 100644 --- a/src/python_wrap/shared.py +++ b/src/python_wrap/shared.py @@ -701,6 +701,11 @@ async def release_async(self, typ: Any = None, exc: Any = None, tb: Any = None) self._active -= 1 +def _async_redis_client(client: Any) -> bool: + # redis-py's command mixins return awaitables from regular Python methods. + return _core.is_async(client.eval) or _core.is_async(getattr(client, "execute_command", None)) + + @dataclass class SharedBackends: """The shared stores a preset or policy uses, built from one Redis client. @@ -720,7 +725,7 @@ class SharedBackends: @property def is_async(self) -> bool: """True for a ``redis.asyncio`` client: layers are built from the async classes.""" - return self.client is not None and _core.is_async(self.client.eval) + return self.client is not None and _async_redis_client(self.client) def breaker(self) -> Any: if self.breaker_state is not None: @@ -735,7 +740,7 @@ def rate_window(self, name: str, calls: int, period: float) -> Any: client = self.window if self.window is not None else self.client if client is None: return None - kind = AsyncRedisWindow if _core.is_async(client.eval) else RedisWindow + kind = AsyncRedisWindow if _async_redis_client(client) else RedisWindow return kind(client, f"python-wrap:window:{name}", calls=calls, period=period) def lease_backend(self) -> Any: diff --git a/tests/test_http_policy.py b/tests/test_http_policy.py index 9e2f06b..18bd92d 100644 --- a/tests/test_http_policy.py +++ b/tests/test_http_policy.py @@ -120,3 +120,54 @@ def test_per_host_guards_evict_least_recently_used() -> None: policy.guards("c") assert policy.guards("a") is first assert policy.guards("b") is not second + + +def test_http_guard_mappings_use_shared_backends() -> None: + from python_wrap.coordination import LocalLease + from python_wrap.shared import SharedBackends + + class Client: + def eval(self, *args: Any) -> Any: + pytest.fail("building a policy must not contact Redis") + + lease = LocalLease() + policy = HttpPolicy( + limiter={"calls": 3, "period": 10}, + bulkhead={"max_concurrent": 2}, + per_host=True, + shared=SharedBackends(window=Client(), semaphore=lease), + ) + _, limiter, bulkhead = policy.guards("api.example") + assert limiter._backend is not None + assert bulkhead._shared is not None + assert policy.guards("other.example")[1] is not limiter + + +def test_429_pause_is_visible_to_another_policy() -> None: + from python_wrap.errors import RateLimitExceeded + + class Client: + def __init__(self) -> None: + self.values: dict[str, int] = {} + self.reads = 0 + + def eval(self, *args: Any) -> Any: + pytest.fail("unexpected script") + + def pttl(self, key: str) -> int: + self.reads += 1 + return self.values.get(key, -2) + + def set(self, key: str, value: str, *, px: int) -> None: + self.values[key] = px + + client = Client() + response = Resp(429) + response.headers["Retry-After"] = "30" + assert HttpPolicy(shared=client).call("API.example.", lambda: response) is response + + other = HttpPolicy(shared=client, retry=HttpRetryPolicy(max_retry_after=5)) + for _ in range(2): + with pytest.raises(RateLimitExceeded): + other.call("api.example", lambda: pytest.fail("request should pause")) + assert client.reads == 2 diff --git a/tests/test_stability.py b/tests/test_stability.py index c713abb..72bb144 100644 --- a/tests/test_stability.py +++ b/tests/test_stability.py @@ -110,6 +110,7 @@ def test_shared_backend_key_formats_are_frozen(): from python_wrap._runtime import digest from python_wrap.caching import _TAG_PREFIX from python_wrap.coordination import RedisLock + from python_wrap.http import _pause_key from python_wrap.idempotency import SqlResultStore from python_wrap.shared import RedisBreakerState, RedisRetryBudget from python_wrap.stores import KEY_FORMAT @@ -126,6 +127,7 @@ def test_shared_backend_key_formats_are_frozen(): assert RedisRetryBudget(None, "vendor").key == f"python-wrap:budget:{{{VENDOR_DIGEST}}}" assert RedisLock(None).prefix == "python-wrap:lease:" assert _TAG_PREFIX == "python-wrap:tag:" + assert _pause_key("vendor") == f"python-wrap:http-pause:{VENDOR_DIGEST}" assert KEY_FORMAT == "k2:" table = SqlResultStore.ddl("postgresql")[0] for column in ("idem_key", "status", "owner", "result", "expires_at"): diff --git a/tests/test_stable_keys.py b/tests/test_stable_keys.py index 19a65eb..0868723 100644 --- a/tests/test_stable_keys.py +++ b/tests/test_stable_keys.py @@ -55,6 +55,7 @@ def f(x: object) -> None: ... "async_cache.py": {"n", "name"}, "idempotency.py": {"key", "results.prefix"}, "quotas.py": {"None"}, + "http.py": {"host"}, } _BARE_DIGEST = re.compile(r"(? Date: Mon, 30 Nov 2026 13:49:49 +0200 Subject: [PATCH 17/38] Share keyed LLM token windows across processes --- CHANGELOG.md | 2 ++ docs/features/ai/openai-anthropic.md | 4 +-- docs/llms-full.txt | 6 ++-- src/python_wrap/adapters/_sdk.py | 50 ++++++++++++++++++--------- src/python_wrap/adapters/anthropic.py | 2 ++ src/python_wrap/events.py | 1 + src/python_wrap/llm_shared.py | 28 +++++++++++++++ tests/test_azure_openai.py | 25 +++++++++++--- 8 files changed, 93 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 46d3d9e..6e3a994 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration. ### Added +- OpenAI and Anthropic adapters support per-key token windows backed by shared Redis or SQLite. + - Tagged cache invalidation returns the number of shared writes and supports `require_shared=True`. Both cache decorators support `lock_wait=None` to wait for the shared lease. diff --git a/docs/features/ai/openai-anthropic.md b/docs/features/ai/openai-anthropic.md index 90f3f59..b2e7589 100644 --- a/docs/features/ai/openai-anthropic.md +++ b/docs/features/ai/openai-anthropic.md @@ -389,8 +389,8 @@ Entra ID token refresh, and regional failover. On Azure, `model=` is the deployment name. Quotas are per deployment and region, so pass `limiter_key` to keep one token window per deployment. Each key gets the shared -limiter's settings. `limiter_key` works with in-process limiters only: a -`TokenRateLimiter` with `store=` raises `ValueError`. +limiter's settings. With a shared SQLite or Redis token store, the same key +uses the same window across processes. This also works with `guard_anthropic`. `Budget(prices=...)` matches model names by prefix. A deployment name usually does not start with the model name, so key prices by deployment name. Prices are dollars per diff --git a/docs/llms-full.txt b/docs/llms-full.txt index a9e0b35..e25e853 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -1967,8 +1967,8 @@ Entra ID token refresh, and regional failover. On Azure, `model=` is the deployment name. Quotas are per deployment and region, so pass `limiter_key` to keep one token window per deployment. Each key gets the shared -limiter's settings. `limiter_key` works with in-process limiters only: a -`TokenRateLimiter` with `store=` raises `ValueError`. +limiter's settings. With a shared SQLite or Redis token store, the same key +uses the same window across processes. This also works with `guard_anthropic`. `Budget(prices=...)` matches model names by prefix. A deployment name usually does not start with the model name, so key prices by deployment name. Prices are dollars per @@ -4649,7 +4649,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm A stream failed after it had produced output; it is not replayed. - `python_wrap.adapters.StreamedToolCall`: `StreamedToolCall(id: str | None, name: str | None, arguments: str, index: int)` A tool call assembled from stream events. -- `python_wrap.adapters.guard_anthropic`: `guard_anthropic(client: Any, *, budget: Budget | None = None, limiter: TokenRateLimiter | None = None, policy: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None, attempts: int = 4, retry: Mapping[str, Any] | None = None, owns_retries: bool = True, trace: bool | Mapping[str, Any] = False, cache_guard: CacheGuard | None = None, read_headers: bool = True, first_token: float | None = None, chunk_gap: float | None = None, total: float | None = None, is_async: bool | None = None) -> GuardedAnthropic` +- `python_wrap.adapters.guard_anthropic`: `guard_anthropic(client: Any, *, budget: Budget | None = None, limiter: TokenRateLimiter | None = None, policy: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None, attempts: int = 4, retry: Mapping[str, Any] | None = None, owns_retries: bool = True, trace: bool | Mapping[str, Any] = False, cache_guard: CacheGuard | None = None, read_headers: bool = True, first_token: float | None = None, chunk_gap: float | None = None, total: float | None = None, is_async: bool | None = None, limiter_key: Callable[[Mapping[str, Any]], str] | None = None) -> GuardedAnthropic` Wrap an Anthropic SDK client so every call is retried, budgeted and rate limited once. - `python_wrap.adapters.guard_chat_model`: `guard_chat_model(model: Any, *, budget: Budget | None = None, limiter: TokenRateLimiter | None = None, policy: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None, attempts: int = 4, retry: Mapping[str, Any] | None = None, trace: bool | Mapping[str, Any] = False, first_token: float | None = None, chunk_gap: float | None = None, total: float | None = None) -> GuardedChatModel` Wrap a LangChain chat model so each call is retried, budgeted and limited once. diff --git a/src/python_wrap/adapters/_sdk.py b/src/python_wrap/adapters/_sdk.py index fdbf725..41fba40 100644 --- a/src/python_wrap/adapters/_sdk.py +++ b/src/python_wrap/adapters/_sdk.py @@ -40,6 +40,7 @@ from typing import TYPE_CHECKING, Any, Generic, TypeVar, cast from python_wrap import _core, _fork +from python_wrap._runtime import stable_digest from python_wrap.errors import PythonWrapError from python_wrap.llm import ( Budget, @@ -1395,7 +1396,17 @@ def __repr__(self) -> str: def _is_async_client(client: Any) -> bool: - return type(client).__name__.startswith("Async") + if type(client).__name__.startswith("Async"): + return True + chat = getattr(getattr(client, "chat", None), "completions", None) + return any( + _core.is_async(getattr(endpoint, "create", None)) + for endpoint in ( + chat, + getattr(client, "messages", None), + getattr(client, "responses", None), + ) + ) class _Endpoint: @@ -1690,10 +1701,6 @@ def __init__( is_async: bool | None = None, limiter_key: Callable[[Mapping[str, Any]], str] | None = None, ) -> None: - if limiter_key is not None and getattr(limiter, "_store", None) is not None: - # shortcut: per-key windows are in-process only; upgrade when a shared token - # window can be cloned under a new name. - raise ValueError("limiter_key needs an in-process TokenRateLimiter (no store=)") if isinstance(attempts, bool) or not isinstance(attempts, int) or attempts < 1: raise ValueError(f"attempts must be an integer >= 1, got {attempts!r}") if retry is not None and ("max_attempts" in retry or "owns_retries" in retry): @@ -1711,6 +1718,8 @@ def __init__( self.budget, self.limiter, self.policy = budget, limiter, policy self.limiter_key = limiter_key self._limiters: dict[str, TokenRateLimiter] = {} + self._limiter_lock = _fork.ForkSafeLock() + self._limiter_overflow = False self.attempts = attempts if owns_retries else 1 self.owns_retries = owns_retries self._retry_options = dict(retry or {}) @@ -1787,22 +1796,31 @@ def _limiting(self, request: Mapping[str, Any] | None = None) -> TokenRateLimite if self.limiter_key is None or request is None: return limiter key = str(self.limiter_key(request)) - found = self._limiters.get(key) - if found is None and len(self._limiters) >= _MAX_LIMITER_KEYS: - return limiter # keys may come from requests: never grow without bound - if found is None: - found = self._limiters.setdefault( - key, - TokenRateLimiter( + with self._limiter_lock: + found = self._limiters.get(key) + if found is not None: + return found + if len(self._limiters) < _MAX_LIMITER_KEYS: + suffix = re.sub(r"[^A-Za-z0-9._-]", "_", key)[:64] + if suffix != key: + suffix += ":" + stable_digest(key) + store = limiter._store + found = TokenRateLimiter( limiter.tokens_per_minute, estimate=limiter._estimate, usage=limiter.usage, block=limiter.block, max_wait=limiter.max_wait, - name=f"{limiter.name}:{key}", - ), - ) - return found + name=f"{limiter.name}:{suffix}", + store=None if store is None else store.named(suffix), + ) + self._limiters[key] = found + return found + warn = not self._limiter_overflow + self._limiter_overflow = True + if warn: + _core.emit("rate_limit.key_overflow", limiter.name, limit=_MAX_LIMITER_KEYS) + return limiter def _seed(self, headers: Any, request: Mapping[str, Any] | None = None) -> None: limiter = self._limiting(request) diff --git a/src/python_wrap/adapters/anthropic.py b/src/python_wrap/adapters/anthropic.py index b508c75..65da146 100644 --- a/src/python_wrap/adapters/anthropic.py +++ b/src/python_wrap/adapters/anthropic.py @@ -79,6 +79,7 @@ def guard_anthropic( chunk_gap: float | None = None, total: float | None = None, is_async: bool | None = None, + limiter_key: Callable[[Mapping[str, Any]], str] | None = None, ) -> GuardedAnthropic: """Wrap an Anthropic SDK client so every call is retried, budgeted and rate limited once. @@ -125,6 +126,7 @@ def with_options(self, *, max_retries: int) -> "Client": client, budget=budget, limiter=limiter, + limiter_key=limiter_key, policy=policy, attempts=attempts, retry=retry, diff --git a/src/python_wrap/events.py b/src/python_wrap/events.py index 1efad8b..790cb39 100644 --- a/src/python_wrap/events.py +++ b/src/python_wrap/events.py @@ -146,6 +146,7 @@ "A watched policy source could not be read or validated; the current policies " "stay. function is 'policies'. Fields: error (str, the exception class), message (str)." ), + "rate_limit.key_overflow": "An SDK limiter reached its key limit. Fields: limit (int).", "http.host_evicted": "A local host guard was evicted. function is the host policy name.", "backend.recovered": ( "A shared backend answered again after backend.error. Fields: backend (str)." diff --git a/src/python_wrap/llm_shared.py b/src/python_wrap/llm_shared.py index c823f3e..c31235a 100644 --- a/src/python_wrap/llm_shared.py +++ b/src/python_wrap/llm_shared.py @@ -337,6 +337,10 @@ def __init__( self._fallback: _State | None = None self._flock = _fork.ForkSafeLock() + def named(self, suffix: str) -> SharedTokenWindow: + """Open an independent window under this name and suffix.""" + raise NotImplementedError + # -- storage hook ------------------------------------------------------------ def _transact(self, op: str, a: float, b: float, capacity: float, rate: float) -> float: raise NotImplementedError @@ -561,6 +565,14 @@ def path(self) -> str: """The database file.""" return self._file.path + def named(self, suffix: str) -> SQLiteTokenWindow: + return type(self)( + self.path, + f"{self.name}:{suffix}", + timeout=self._file.timeout, + on_backend_error=self.on_backend_error, + ) + def _once(self, op: str, a: float, b: float, capacity: float, rate: float) -> float: with self._file.connection() as conn: now = _core.wall_time() @@ -714,6 +726,14 @@ def __init__( raise ValueError("RedisTokenWindow needs a nonempty prefix") self.client, self.prefix = client, prefix + def named(self, suffix: str) -> RedisTokenWindow: + return type(self)( + self.client, + f"{self.name}:{suffix}", + prefix=self.prefix, + on_backend_error=self.on_backend_error, + ) + def _transact(self, op: str, a: float, b: float, capacity: float, rate: float) -> float: reply = _LUA_STEP_SCRIPT.run( self.client, *_redis_args(self.name, self.prefix, op, a, b, capacity, rate) @@ -744,6 +764,14 @@ def __init__( raise ValueError("AsyncRedisTokenWindow needs a nonempty prefix") self.client, self.prefix = client, prefix + def named(self, suffix: str) -> AsyncRedisTokenWindow: + return type(self)( + self.client, + f"{self.name}:{suffix}", + prefix=self.prefix, + on_backend_error=self.on_backend_error, + ) + def _transact(self, op: str, a: float, b: float, capacity: float, rate: float) -> float: raise RuntimeError( "AsyncRedisTokenWindow is async-only: use token_rate_limit(...) on async functions" diff --git a/tests/test_azure_openai.py b/tests/test_azure_openai.py index 4af5a0c..c623c61 100644 --- a/tests/test_azure_openai.py +++ b/tests/test_azure_openai.py @@ -91,9 +91,26 @@ def test_limiter_key_keeps_one_window_per_deployment() -> None: guarded.embeddings.create(model="west", input="b") assert set(guarded._limiters) == {"east", "west"} assert guarded._limiters["east"] is not guarded._limiters["west"] - with pytest.raises(ValueError, match="limiter_key"): - guard_openai( - azure(seen), - limiter=TokenRateLimiter(tokens_per_minute=10, store=object()), + + +def test_limiter_key_shares_windows_by_deployment(tmp_path) -> None: + from python_wrap.llm_shared import SQLiteTokenWindow + + store = SQLiteTokenWindow(tmp_path / "tokens.db", "chat") + + def client(): + return guard_openai( + azure([]), + limiter=TokenRateLimiter(tokens_per_minute=100, store=store), limiter_key=lambda kw: kw["model"], ) + + first, second = client(), client() + east = first._limiting({"model": "east"})._store + east_peer = second._limiting({"model": "east"})._store + west = second._limiting({"model": "west"})._store + assert east.name == east_peer.name == "chat:east" + assert west.name == "chat:west" + assert east.reserve(100, 100, 0.001) == 0 + assert east_peer.reserve(100, 100, 0.001) > 0 + assert west.reserve(100, 100, 0.001) == 0 From 98d8eac61caf25e3da3b86469715b2d975f35865 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Mon, 30 Nov 2026 13:51:09 +0200 Subject: [PATCH 18/38] Allow retry defaults to update running applications --- CHANGELOG.md | 2 + docs/features/configuration.md | 5 +- src/python_wrap/config.py | 28 ++++++++++- src/python_wrap/retry.py | 88 ++++++++++++++++++++-------------- tests/test_config.py | 28 +++++++++++ 5 files changed, 113 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e3a994..c14e840 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration. ### Added +- `configure(live=True)` refreshes omitted retry arguments on already-decorated functions. + - OpenAI and Anthropic adapters support per-key token windows backed by shared Redis or SQLite. - Tagged cache invalidation returns the number of shared writes and supports diff --git a/docs/features/configuration.md b/docs/features/configuration.md index 8dd67c9..d5503fb 100644 --- a/docs/features/configuration.md +++ b/docs/features/configuration.md @@ -43,7 +43,10 @@ reset_config() ``` For settings that must change while the process runs, use a `PolicyRegistry` with `watch()` -instead. `configure()` sets defaults read at decoration time; a watched policy changes behaviour +for named policies. By default `configure()` sets retry defaults at decoration time. +Use `configure(live=True, retry={"max_attempts": 2})` to update omitted retry arguments +on already-decorated functions. Explicit arguments retain precedence, and each retry +call retains the settings it started with. A watched policy changes behaviour on every replica without a restart, for example to lower a rate limit or stop retries for one dependency during an incident. See [named policies](resilience/named-policies.md). diff --git a/src/python_wrap/config.py b/src/python_wrap/config.py index c756eed..3d1664b 100644 --- a/src/python_wrap/config.py +++ b/src/python_wrap/config.py @@ -21,7 +21,16 @@ UNSET: Any = object() """Sentinel meaning "argument not passed"; resolved against the configured defaults.""" -_KEYS = ("logger", "retry", "redact", "redact_extra", "backend_errors", "shared", "cache_codec") +_KEYS = ( + "logger", + "retry", + "redact", + "redact_extra", + "backend_errors", + "shared", + "cache_codec", + "live", +) _RETRY_KEYS = ( "max_attempts", "delay", @@ -35,6 +44,7 @@ _lock = _fork.ForkSafeRLock() _state: dict[str, Any] = {} +_live_retry: dict[str, Any] | None = None def _hint(name: str, valid: tuple[str, ...], what: str) -> TypeError: @@ -75,6 +85,10 @@ def _validate(key: str, value: Any) -> Any: if value is not None and not isinstance(value, (str, logging.Logger)): raise TypeError(f"logger must be a logging.Logger, a name or None, got {value!r}") return value + if key == "live": + if not isinstance(value, bool): + raise TypeError("live must be bool") + return value if key == "retry": if not isinstance(value, Mapping): raise TypeError(f"retry must be a mapping of retry defaults, got {value!r}") @@ -113,7 +127,8 @@ def configure(**defaults: Any) -> None: Call it once at start-up, before decorating: values are read when a decorator is applied, so decorators applied earlier keep their settings. Keys not mentioned keep - their current value; each key you pass replaces that key entirely (`retry={...}` + their current value. Set `live=True` to refresh omitted retry arguments at call time. + Each key you pass replaces that key entirely (`retry={...}` replaces the previous retry defaults). Explicit decorator arguments always win. Args: @@ -152,12 +167,15 @@ def configure(**defaults: Any) -> None: reset_config() ``` """ + global _live_retry for key in defaults: if key not in _KEYS: raise _hint(key, _KEYS, "configuration key") clean = {k: _validate(k, v) for k, v in defaults.items()} with _lock: _state.update(clean) + if {"live", "retry"} & clean.keys(): + _live_retry = dict(_state.get("retry", {})) if _state.get("live") else None if "logger" in clean: _core._default_logger = clean["logger"] _backend._set_default(_state.get("backend_errors")) @@ -186,6 +204,7 @@ def get_config() -> dict[str, Any]: "backend_errors": _state.get("backend_errors"), "shared": _state.get("shared"), "cache_codec": _state.get("cache_codec"), + "live": _state.get("live", False), } @@ -201,8 +220,10 @@ def reset_config() -> None: assert get_config()["retry"] == {} ``` """ + global _live_retry with _lock: _state.clear() + _live_retry = None _core._default_logger = None _backend._set_default(None) @@ -226,8 +247,10 @@ def configured(**defaults: Any) -> Iterator[None]: assert get_config()["retry"] == {} ``` """ + global _live_retry with _lock: saved = dict(_state) + saved_live_retry = _live_retry configure(**defaults) try: yield @@ -235,6 +258,7 @@ def configured(**defaults: Any) -> Iterator[None]: with _lock: _state.clear() _state.update(saved) + _live_retry = saved_live_retry _core._default_logger = saved.get("logger") _backend._set_default(saved.get("backend_errors")) diff --git a/src/python_wrap/retry.py b/src/python_wrap/retry.py index ac8ee42..d73cac5 100644 --- a/src/python_wrap/retry.py +++ b/src/python_wrap/retry.py @@ -1224,17 +1224,17 @@ def retry( >>> @retry(max_attempts=5, delay=0.5, backoff=2, on=ConnectionError) ... def fetch() -> str: ... """ - ds = _resolve_defaults( - schedule=delays is not None, - max_attempts=max_attempts, - delay=delay, - backoff=backoff, - max_delay=max_delay, - jitter=jitter, - max_time=max_time, - log_level=log_level, - budget=budget, - ) + given = { + "max_attempts": max_attempts, + "delay": delay, + "backoff": backoff, + "max_delay": max_delay, + "jitter": jitter, + "max_time": max_time, + "log_level": log_level, + "budget": budget, + } + ds = _resolve_defaults(schedule=delays is not None, **given) max_attempts, delay, backoff = ds["max_attempts"], ds["delay"], ds["backoff"] max_delay, jitter, max_time, log_level = ( ds["max_delay"], @@ -1264,29 +1264,45 @@ def retry( def decorate(f: Callable[P, R]) -> Callable[P, R]: stats = RetryStats() - engine = _Engine( - _core.qualname(f), - max_attempts=max_attempts, - delay=delay, - backoff=backoff, - max_delay=max_delay, - jitter=jitter, - max_time=max_time, - on=on, - retry_if=retry_if, - retry_if_result=retry_if_result, - on_retry=on_retry, - delay_from=delay_from, - delays=delays, - budget=budget, - logger=logger, - log_level=log_level, - log_exc_info=log_exc_info, - log_values=log_values, - stats=stats, - hint_jitter=hint_jitter, - min_delay=min_delay, - ) + + def build_engine(resolved: dict[str, Any]) -> _Engine: + return _Engine( + _core.qualname(f), + on=on, + retry_if=retry_if, + retry_if_result=retry_if_result, + on_retry=on_retry, + delay_from=delay_from, + delays=delays, + logger=logger, + log_exc_info=log_exc_info, + log_values=log_values, + stats=stats, + hint_jitter=hint_jitter, + min_delay=min_delay, + **resolved, + ) + + frozen_engine = build_engine(ds) + live_engine: tuple[dict[str, Any], _Engine] | None = None + + def current_engine() -> _Engine: + nonlocal live_engine + snapshot = config._live_retry + if snapshot is None: + return frozen_engine + cached = live_engine + if cached is not None and cached[0] is snapshot: + return cached[1] + engine = build_engine( + { + name: snapshot.get(name, _RETRY_FALLBACK[name]) if value is _UNSET else value + for name, value in given.items() + } + ) + live_engine = snapshot, engine + return engine + check_result = retry_if_result is not None if _core.is_async(f): @@ -1294,6 +1310,7 @@ def decorate(f: Callable[P, R]) -> Callable[P, R]: @functools.wraps(af) async def async_wrapper(*args: Any, **kwargs: Any) -> Any: + engine = current_engine() started = engine.start_call() attempt = 1 history: list[AttemptRecord] = [] @@ -1322,10 +1339,11 @@ async def async_wrapper(*args: Any, **kwargs: Any) -> Any: setattr(async_wrapper, _LAYER_ATTR, ("retry", settings)) return cast("Callable[P, R]", async_wrapper) - engine.check_sync(*engine.async_hooks) + frozen_engine.check_sync(*frozen_engine.async_hooks) @functools.wraps(f) def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: + engine = current_engine() started = engine.start_call() attempt = 1 history: list[AttemptRecord] = [] diff --git a/tests/test_config.py b/tests/test_config.py index 7fbc6c2..394c10a 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -44,6 +44,7 @@ def test_defaults_and_get_config_is_a_copy() -> None: "backend_errors": None, "shared": None, "cache_codec": None, + "live": False, } cfg["retry"]["delay"] = 5 assert get_config()["retry"] == {} @@ -295,3 +296,30 @@ def test_retrying_block_respects_deadline(fake_clock: FakeClock) -> None: with attempt: f() assert f.calls == 1 + + +def test_live_retry_defaults_refresh_existing_decorators() -> None: + calls = [] + explicit_calls = [] + + @retry(delay=0) + def fails() -> None: + calls.append(1) + raise ConnectionError + + @retry(max_attempts=1, delay=0) + def explicit() -> None: + explicit_calls.append(1) + raise ConnectionError + + with configured(live=True, retry={"max_attempts": 2}): + with pytest.raises(ConnectionError): + fails() + with pytest.raises(ConnectionError): + explicit() + configure(retry={"max_attempts": 1}) + with pytest.raises(ConnectionError): + fails() + + assert len(calls) == 3 + assert len(explicit_calls) == 1 From 75ad1e826329033bb69f4e5d12428ea47badf368 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Mon, 30 Nov 2026 13:53:27 +0200 Subject: [PATCH 19/38] Keep fork-aware synchronization and SDK detection typed --- src/python_wrap/_fork.py | 4 ++-- src/python_wrap/adapters/_sdk.py | 13 +++++-------- src/python_wrap/buffering.py | 4 ++-- src/python_wrap/timing.py | 4 ++-- 4 files changed, 11 insertions(+), 14 deletions(-) diff --git a/src/python_wrap/_fork.py b/src/python_wrap/_fork.py index 2af82e1..06a9f33 100644 --- a/src/python_wrap/_fork.py +++ b/src/python_wrap/_fork.py @@ -92,11 +92,11 @@ def release(self) -> None: def locked(self) -> bool: probe = getattr(self._lock, "locked", None) # RLock.locked exists on 3.14+ - return probe() if probe is not None else self._lock._is_owned() # type: ignore[attr-defined] + return bool(probe()) if probe is not None else self._is_owned() # threading.Condition uses these private hooks on an RLock to wait and notify. def _is_owned(self) -> bool: - return self._lock._is_owned() # type: ignore[attr-defined] + return bool(self._lock._is_owned()) # type: ignore[attr-defined] def _release_save(self) -> Any: return self._lock._release_save() # type: ignore[attr-defined] diff --git a/src/python_wrap/adapters/_sdk.py b/src/python_wrap/adapters/_sdk.py index 41fba40..77b5773 100644 --- a/src/python_wrap/adapters/_sdk.py +++ b/src/python_wrap/adapters/_sdk.py @@ -1399,14 +1399,11 @@ def _is_async_client(client: Any) -> bool: if type(client).__name__.startswith("Async"): return True chat = getattr(getattr(client, "chat", None), "completions", None) - return any( - _core.is_async(getattr(endpoint, "create", None)) - for endpoint in ( - chat, - getattr(client, "messages", None), - getattr(client, "responses", None), - ) - ) + for endpoint in (chat, getattr(client, "messages", None), getattr(client, "responses", None)): + create = getattr(endpoint, "create", None) + if create is not None and _core.is_async(create): + return True + return False class _Endpoint: diff --git a/src/python_wrap/buffering.py b/src/python_wrap/buffering.py index d470ba3..6300c34 100644 --- a/src/python_wrap/buffering.py +++ b/src/python_wrap/buffering.py @@ -331,7 +331,7 @@ def __init__( self.log = _core.get_logger(logger) self.journal = journal self._replayed = journal is None - self._condition = threading.Condition(_fork.ForkSafeRLock()) + self._condition = threading.Condition(_fork.ForkSafeRLock()) # type: ignore[arg-type] self._bindings_lock = _fork.ForkSafeLock() self._queue: deque[Any] = deque() self._pending = self._written = self._dropped = self._failed = self._failed_records = 0 @@ -358,7 +358,7 @@ def _reset_after_fork(self) -> None: # replaying the same records. Call replay() explicitly in the one process # that owns the journal. self._replayed = True - self._condition = threading.Condition(_fork.ForkSafeRLock()) + self._condition = threading.Condition(_fork.ForkSafeRLock()) # type: ignore[arg-type] self._fork_dropped = self._pending self._queue.clear() self._pending = 0 diff --git a/src/python_wrap/timing.py b/src/python_wrap/timing.py index cf95719..c089748 100644 --- a/src/python_wrap/timing.py +++ b/src/python_wrap/timing.py @@ -365,7 +365,7 @@ def _trace_release() -> None: # re-entrant for the call holding it: nested measured calls, and tasks or # ``asyncio.to_thread`` workers started inside it (they inherit the context variable), # enter immediately instead of deadlocking on their parent. -_gate = threading.Condition(_fork.ForkSafeLock()) +_gate = threading.Condition(_fork.ForkSafeLock()) # type: ignore[arg-type] _gate_owner: object | None = None _gate_depth = 0 _measuring: contextvars.ContextVar[object | None] = contextvars.ContextVar( @@ -375,7 +375,7 @@ def _trace_release() -> None: def _reset_gate() -> None: global _gate, _gate_owner, _gate_depth - _gate = threading.Condition(_fork.ForkSafeLock()) + _gate = threading.Condition(_fork.ForkSafeLock()) # type: ignore[arg-type] _gate_owner, _gate_depth = None, 0 From b3c7efa7aa21cb1bed2a116c21deccb84816159c Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Mon, 30 Nov 2026 13:53:27 +0200 Subject: [PATCH 20/38] Support async Redis retry budgets --- CHANGELOG.md | 2 + docs/features/concurrency/shared-limits.md | 4 +- docs/features/resilience/retry.md | 3 + docs/llms-full.txt | 2 + src/python_wrap/http.py | 71 +++++++++++----- src/python_wrap/retry.py | 98 +++++++++++++++++++--- src/python_wrap/shared.py | 84 +++++++++++++++++-- tests/test_redis_backends.py | 36 ++++++++ 8 files changed, 258 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c14e840..67fd2bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration. ### Added +- Async retries and HTTP transports can use Redis-backed retry budgets without blocking the loop. + - `configure(live=True)` refreshes omitted retry arguments on already-decorated functions. - OpenAI and Anthropic adapters support per-key token windows backed by shared Redis or SQLite. diff --git a/docs/features/concurrency/shared-limits.md b/docs/features/concurrency/shared-limits.md index ba4a9ba..112b44c 100644 --- a/docs/features/concurrency/shared-limits.md +++ b/docs/features/concurrency/shared-limits.md @@ -145,8 +145,8 @@ Its `.state` and `.stats` report the last state the store returned in this proce `force_open()` raise `TypeError`. `AsyncRedisSemaphore` works with `SharedBulkhead` and `Bulkhead(..., backend=...)`; sync `acquire()` raises `TypeError`. Passing an async client to `SharedBackends(client=...)`, or `shared=` on a preset or policy, selects these async -backends. Retry budgets stay per process in that case; pass -`budget=RedisRetryBudget(sync_client, name)` to share them. +backends, including `AsyncRedisRetryBudget` for shared retry budgets. Use +`await budget.astats()` to inspect an async budget. ```python diff --git a/docs/features/resilience/retry.md b/docs/features/resilience/retry.md index 26e3c7d..adca138 100644 --- a/docs/features/resilience/retry.md +++ b/docs/features/resilience/retry.md @@ -276,6 +276,9 @@ its deposits: a first attempt is counted in memory and sent with the next batch, `stats` flush the batch first, so a retry always sees every call made in this process. A deposit never raises; if the store is down its count moves to the local budget. An idle process can hold up to `flush_every - 1` deposits until its next retry or `stats` read. +For a `redis.asyncio` client, use `AsyncRedisRetryBudget` from `python_wrap.shared`. +Async decorators and HTTP transports await the backend. In an async `retrying` loop, +use `async with attempt` to await the budget, and inspect it with `await budget.astats()`. !!! tip "One budget per dependency" Share a budget between the calls that hit the same service. A budget shared by unrelated services lets a failing one spend the retries the others need. diff --git a/docs/llms-full.txt b/docs/llms-full.txt index e25e853..3868123 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -5197,6 +5197,8 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Split a name into lowercase word segments. - `python_wrap.shared` Redis coordination backends for circuit breakers and bulkheads. +- `python_wrap.shared.AsyncRedisRetryBudget`: `AsyncRedisRetryBudget(client: Any, name: str, *, prefix: str = 'python-wrap:budget:', on_backend_error: str | None = None, retry_backend_after: float = 1.0, flush_interval: float = 1.0, flush_every: int = 1000)` + A shared retry budget for a redis.asyncio client. - `python_wrap.shared.RedisRetryBudget`: `RedisRetryBudget(client: Any, name: str, *, prefix: str = 'python-wrap:budget:', on_backend_error: str | None = None, retry_backend_after: float = 1.0, flush_interval: float = 1.0, flush_every: int = 1000)` A `RetryBudget` backend that counts requests and retries in Redis. - `python_wrap.shared.SharedBackends`: `SharedBackends(client: Any = None, breaker_state: Any = None, window: Any = None, semaphore: Any = None, budget: Any = None)` diff --git a/src/python_wrap/http.py b/src/python_wrap/http.py index 8733933..a304353 100644 --- a/src/python_wrap/http.py +++ b/src/python_wrap/http.py @@ -275,42 +275,70 @@ def __init__(self, policy: HttpRetryPolicy, method: str, headers: Any, host: str self.method = str(method).upper() self.headers = headers self.name = f"http {self.method} {host}".rstrip() - if policy.budget is not None: - policy.budget.deposit() - def next_delay( + def start(self) -> None: + if self.policy.budget is not None: + self.policy.budget.deposit() + + async def astart(self) -> None: + if self.policy.budget is not None: + await self.policy.budget.adeposit() + + def _planned_delay( self, attempt: int, response: Any = None, exc: BaseException | None = None - ) -> float | None: + ) -> tuple[float | None, dict[str, Any]]: """The wait before the next attempt, or `None` to stop (response/exception stands).""" policy = self.policy subject = exc if exc is not None else response status = _status_of(response) if exc is None else None - if not should_retry(self.method, self.headers, status, exc, policy): - return None fields: dict[str, Any] = {"attempts": attempt, "exception": exc, "status": status} + if not should_retry(self.method, self.headers, status, exc, policy): + return None, fields if attempt >= policy.max_attempts: _core.emit("retry.gave_up", self.name, **fields) - return None + return None, fields wait = retry_delay(subject, attempt, policy) if wait is None: _core.emit("retry.gave_up", self.name, **fields) - return None + return None, fields left = _deadline_remaining() if left is not None and wait >= left: _core.emit("retry.gave_up", self.name, **fields) - return None - if policy.budget is not None and not policy.budget.try_withdraw(): + return None, fields + return wait, fields + + def next_delay( + self, attempt: int, response: Any = None, exc: BaseException | None = None + ) -> float | None: + wait, fields = self._planned_delay(attempt, response, exc) + budget = self.policy.budget + denied = wait is not None and budget is not None and not budget.try_withdraw() + return self._record_delay(wait, fields, denied) + + async def anext_delay( + self, attempt: int, response: Any = None, exc: BaseException | None = None + ) -> float | None: + wait, fields = self._planned_delay(attempt, response, exc) + budget = self.policy.budget + denied = wait is not None and budget is not None and not await budget.atry_withdraw() + return self._record_delay(wait, fields, denied) + + def _record_delay( + self, wait: float | None, fields: dict[str, Any], denied: bool + ) -> float | None: + if denied: _core.emit("retry.budget_exhausted", self.name, **fields) _core.emit("retry.gave_up", self.name, **fields) return None - _core.emit( - "retry.attempt_failed", - self.name, - attempt=attempt, - exception=exc, - status=status, - next_delay=wait, - ) + if wait is not None: + _core.emit( + "retry.attempt_failed", + self.name, + attempt=fields["attempts"], + exception=fields["exception"], + status=fields["status"], + next_delay=wait, + ) return wait def succeeded(self, attempt: int) -> None: @@ -740,6 +768,7 @@ def handle_request(self, request: Any) -> Any: full = self._full host = _host(request.url) run = _Run(full.retry, request.method, request.headers, host) + run.start() attempt = 0 while True: attempt += 1 @@ -831,17 +860,18 @@ async def handle_async_request(self, request: Any) -> Any: full = self._full host = _host(request.url) run = _Run(full.retry, request.method, request.headers, host) + await run.astart() attempt = 0 while True: attempt += 1 try: response = await full.acall(host, lambda: self._send(request)) except Exception as exc: - wait = run.next_delay(attempt, exc=exc) + wait = await run.anext_delay(attempt, exc=exc) if wait is None: raise else: - wait = run.next_delay(attempt, response=response) + wait = await run.anext_delay(attempt, response=response) if wait is None: run.succeeded(attempt) return response @@ -938,6 +968,7 @@ def send(self, request: Any, **kwargs: Any) -> Any: full = self.http_policy host = _host(request.url) run = _Run(full.retry, request.method, request.headers, host) + run.start() def once() -> Any: full_timeout = full.requests_timeout(kwargs.get("timeout")) diff --git a/src/python_wrap/retry.py b/src/python_wrap/retry.py index d73cac5..2490479 100644 --- a/src/python_wrap/retry.py +++ b/src/python_wrap/retry.py @@ -365,6 +365,15 @@ def deposit(self) -> None: return self._deposit_local() + async def adeposit(self) -> None: + """Record a request using either a local or shared budget.""" + if self.backend is None: + self._deposit_local() + elif (deposit := getattr(self.backend, "adeposit", None)) is not None: + await deposit(self) + else: + await asyncio.to_thread(self.deposit) + def _deposit_local(self, count: int = 1) -> None: with self._lock: index, _ = self._slot() @@ -388,6 +397,19 @@ def try_withdraw(self) -> bool: return False return self._withdraw_local() + async def atry_withdraw(self) -> bool: + """Take one retry from the budget without blocking the event loop.""" + if self.backend is None: + return self._withdraw_local() + withdraw = getattr(self.backend, "atry_withdraw", None) + if withdraw is None: + return await asyncio.to_thread(self.try_withdraw) + if await withdraw(self): + return True + with self._lock: + self._rejected += 1 + return False + def _withdraw_local(self) -> bool: with self._lock: index, epoch = self._slot() @@ -397,6 +419,22 @@ def _withdraw_local(self) -> bool: self._rejected += 1 return False + async def astats(self) -> RetryBudgetStats: + """Return a snapshot of the budget from an async caller.""" + if self.backend is None: + return self.stats + totals = getattr(self.backend, "atotals", None) + if totals is None: + return await asyncio.to_thread(lambda: self.stats) + requests, retries = await totals(self) + with self._lock: + return RetryBudgetStats( + requests, + retries, + self._rejected, + max(math.floor(self._available(requests, retries)), 0), + ) + @property def stats(self) -> RetryBudgetStats: """A consistent `RetryBudgetStats` snapshot of the current window.""" @@ -744,6 +782,13 @@ def start_call(self) -> float: self.stats.calls += 1 return _core.monotonic() + async def astart_call(self) -> float: + if self.budget is not None: + await self.budget.adeposit() + with self.stats._lock: + self.stats.calls += 1 + return _core.monotonic() + def _start_call_with_budget(self) -> float: with self.stats._lock: self.stats.calls += 1 @@ -815,7 +860,7 @@ def _wait_for(self, attempt: int, exc: BaseException | None, result: Any = None) return _compute_delay(1, delay, 1.0, self.max_delay, self.jitter) return _compute_delay(attempt, self.delay, self.backoff, self.max_delay, self.jitter) - def _plan( + def _planned_delay( self, attempt: int, exc: BaseException | None, @@ -825,7 +870,6 @@ def _plan( ) -> float | None: """The wait before the next attempt, or None to stop (counted and emitted).""" wait: float | None = None - denied = False limit = self.limit() if wanted and (limit is None or attempt < limit): wait = self._wait_for(attempt, exc, result) @@ -834,9 +878,39 @@ def _plan( left = _deadline_remaining() if wait is not None and left is not None and wait > left: wait = None # never sleep past the surrounding `deadline` - if wait is not None and self.budget is not None and not self.budget.try_withdraw(): - wait = None - denied = True + return wait + + def _plan( + self, + attempt: int, + exc: BaseException | None, + wanted: bool, + started: float, + result: Any = None, + ) -> float | None: + wait = self._planned_delay(attempt, exc, wanted, started, result) + denied = wait is not None and self.budget is not None and not self.budget.try_withdraw() + return self._record_plan(attempt, exc, wait, denied) + + async def _aplan( + self, + attempt: int, + exc: BaseException | None, + wanted: bool, + started: float, + result: Any = None, + ) -> float | None: + wait = self._planned_delay(attempt, exc, wanted, started, result) + denied = ( + wait is not None and self.budget is not None and not await self.budget.atry_withdraw() + ) + return self._record_plan(attempt, exc, wait, denied) + + def _record_plan( + self, attempt: int, exc: BaseException | None, wait: float | None, denied: bool + ) -> float | None: + if denied: + wait = None if wait is None: with self.stats._lock: self.stats.gave_up += 1 @@ -961,7 +1035,7 @@ async def afailure(self, attempt: int, exc: BaseException, started: float) -> fl return None self._record(exc) wanted = self.retry_if is None or bool(await _maybe_await(self.retry_if(exc))) - wait = self._plan(attempt, exc, wanted, started) + wait = await self._aplan(attempt, exc, wanted, started) if wait is not None: await self._arun_hook(self._state(attempt, exc, None, wait, started)) self._announce(attempt, exc, None, wait) @@ -975,7 +1049,7 @@ async def arejects(self, result: Any) -> bool: async def aresult_failure(self, attempt: int, result: Any, started: float) -> float | None: """`result_failure` for async callers.""" - wait = self._plan(attempt, None, True, started, result) + wait = await self._aplan(attempt, None, True, started, result) if wait is not None: state = self._state(attempt, None, result, wait, started) await self._arun_hook(state) @@ -1311,7 +1385,7 @@ def current_engine() -> _Engine: @functools.wraps(af) async def async_wrapper(*args: Any, **kwargs: Any) -> Any: engine = current_engine() - started = engine.start_call() + started = await engine.astart_call() attempt = 1 history: list[AttemptRecord] = [] while True: @@ -1377,9 +1451,9 @@ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: class _Run: - def __init__(self, engine: _Engine) -> None: + def __init__(self, engine: _Engine, started: float) -> None: self.engine = engine - self.started = engine.start_call() + self.started = started class Attempt: @@ -1475,7 +1549,7 @@ def stats(self) -> RetryStats: return self._engine.stats def __iter__(self) -> Iterator[Attempt]: - run = _Run(self._engine) + run = _Run(self._engine, self._engine.start_call()) number = 1 while True: attempt = Attempt(number, run) @@ -1490,7 +1564,7 @@ def __iter__(self) -> Iterator[Attempt]: number += 1 async def __aiter__(self) -> AsyncIterator[Attempt]: - run = _Run(self._engine) + run = _Run(self._engine, await self._engine.astart_call()) number = 1 while True: attempt = Attempt(number, run) diff --git a/src/python_wrap/shared.py b/src/python_wrap/shared.py index b008fee..730f66d 100644 --- a/src/python_wrap/shared.py +++ b/src/python_wrap/shared.py @@ -22,6 +22,7 @@ __all__ = [ "AsyncRedisBreakerState", + "AsyncRedisRetryBudget", "RedisBreakerState", "RedisRetryBudget", "SharedBackends", @@ -237,15 +238,17 @@ def _flush_pending(self, budget: Any) -> None: count = self._take_pending() self._flush(budget, count) - def deposit(self, budget: Any) -> None: + def _queue_deposit(self) -> int: with self._lock: self._pending += 1 due = ( self._pending >= self.flush_every or _core.monotonic() - self._flushed_at >= self.flush_interval ) - count = self._take_pending() if due else 0 - self._flush(budget, count) + return self._take_pending() if due else 0 + + def deposit(self, budget: Any) -> None: + self._flush(budget, self._queue_deposit()) def try_withdraw(self, budget: Any) -> bool: self._flush_pending(budget) @@ -271,6 +274,71 @@ def local() -> tuple[int, int]: return int(row[0]), int(row[1]) +class AsyncRedisRetryBudget(RedisRetryBudget): + """A shared retry budget for a redis.asyncio client.""" + + def _eval(self, budget: Any, op: str, count: int = 1) -> Any: + raise TypeError("AsyncRedisRetryBudget requires async retry or budget methods") + + def deposit(self, budget: Any) -> None: + raise TypeError("use await budget.adeposit() with AsyncRedisRetryBudget") + + def try_withdraw(self, budget: Any) -> bool: + raise TypeError("use await budget.atry_withdraw() with AsyncRedisRetryBudget") + + def totals(self, budget: Any) -> tuple[int, int]: + raise TypeError("use await budget.astats() with AsyncRedisRetryBudget") + + async def _aeval(self, budget: Any, op: str, count: int = 1) -> Any: + width = max(1, math.ceil(budget.window * 1000 / 10)) + return await _BUDGET_SCRIPT.arun( + self.client, 1, self.key, op, width, budget.ratio, budget._reserve, count + ) + + async def _aflush(self, budget: Any, count: int) -> None: + if count <= 0: + return + if not self._monitor._skipping(): + try: + await self._aeval(budget, "deposit", count) + except Exception as exc: + self._monitor.failed(exc, "deposit") + else: + self._monitor.succeeded() + return + budget._deposit_local(count) + + async def adeposit(self, budget: Any) -> None: + await self._aflush(budget, self._queue_deposit()) + + async def _aflush_pending(self, budget: Any) -> None: + with self._lock: + count = self._take_pending() + await self._aflush(budget, count) + + async def atry_withdraw(self, budget: Any) -> bool: + await self._aflush_pending(budget) + + async def withdraw() -> bool: + return int(await self._aeval(budget, "withdraw")) == 1 + + def fallback() -> bool: + return budget._withdraw_local() if self._monitor.mode == "local" else True + + return await self._monitor.acall("withdraw", withdraw, fallback) + + async def atotals(self, budget: Any) -> tuple[int, int]: + await self._aflush_pending(budget) + + def local() -> tuple[int, int]: + with budget._lock: + totals: tuple[int, int] = budget._totals(budget._slot()[1]) + return totals + + row = await self._monitor.acall("totals", lambda: self._aeval(budget, "totals"), local) + return int(row[0]), int(row[1]) + + class RedisBreakerState: """Atomic Redis breaker state, window failures and bounded half-open trial leases. @@ -703,7 +771,8 @@ async def release_async(self, typ: Any = None, exc: Any = None, tb: Any = None) def _async_redis_client(client: Any) -> bool: # redis-py's command mixins return awaitables from regular Python methods. - return _core.is_async(client.eval) or _core.is_async(getattr(client, "execute_command", None)) + execute = getattr(client, "execute_command", None) + return _core.is_async(client.eval) or (execute is not None and _core.is_async(execute)) @dataclass @@ -755,11 +824,10 @@ def lease_backend(self) -> Any: def budget_backend(self, name: str) -> Any: if self.budget is not None: return self.budget - # shortcut: retry budgets are sync only, so an async client keeps them per process; - # pass budget=RedisRetryBudget(sync_client, name) to share them. - if self.client is None or self.is_async: + if self.client is None: return None - return RedisRetryBudget(self.client, name) + kind = AsyncRedisRetryBudget if self.is_async else RedisRetryBudget + return kind(self.client, name) def resolve_shared(shared: Any) -> SharedBackends | None: diff --git a/tests/test_redis_backends.py b/tests/test_redis_backends.py index a57a120..69cc822 100644 --- a/tests/test_redis_backends.py +++ b/tests/test_redis_backends.py @@ -631,3 +631,39 @@ def test_bulkhead_limit_holds_across_two_processes(redis_client): assert [worker.exitcode for worker in workers] == [0, 0] assert active.value == 0 assert peak.value <= 2 # the shared capacity holds across both processes + + +def test_async_retry_budget_shares_allowance_on_live_redis(redis_client): + import asyncio + + from python_wrap import retry + from python_wrap.shared import AsyncRedisRetryBudget, SharedBackends + + name = _name("async-budget") + backend = SharedBackends(client=AsyncClient(redis_client)).budget_backend(name) + assert isinstance(backend, AsyncRedisRetryBudget) + budget = RetryBudget(ratio=0, min_per_second=0.1, window=10, backend=backend) + peer = RetryBudget( + ratio=0, min_per_second=0.1, window=10, backend=RedisRetryBudget(redis_client, name) + ) + attempts = [] + + @retry(max_attempts=3, delay=0, budget=budget) + async def fail(): + attempts.append(1) + raise ConnectionError + + async def check(): + with pytest.raises(ConnectionError): + await fail() + snapshot = await budget.astats() + assert (snapshot.requests, snapshot.retries, snapshot.rejected, snapshot.allowed) == ( + 1, + 1, + 1, + 0, + ) + + asyncio.run(check()) + assert len(attempts) == 2 + assert not peer.try_withdraw() From c7ce00e417cef1b771c5481dcfef48a766b0e3a9 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Wed, 2 Dec 2026 12:02:37 +0200 Subject: [PATCH 21/38] Extend SQL idempotency and LangChain integration --- CHANGELOG.md | 4 + docs/features/ai/langchain.md | 15 +- .../concurrency/leases-and-idempotency.md | 11 +- docs/llms-full.txt | 25 +- src/python_wrap/adapters/__init__.py | 6 + src/python_wrap/adapters/langchain.py | 209 +++++++++++++-- src/python_wrap/idempotency.py | 239 ++++++++++++------ tests/test_langchain_adapter.py | 46 ++++ tests/test_sql_backends_live.py | 26 +- tests/test_sql_result_store.py | 70 ++++- 10 files changed, 524 insertions(+), 127 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 67fd2bd..c99c03c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ Breaking changes are listed under **Breaking changes**, each with its migration. ### Added +- LangChain guards compose as runnables, preserve guards on bindings, and cover embeddings. + +- SQL idempotency supports async connections, database-clock expiration, and sequential DDL. + - Async retries and HTTP transports can use Redis-backed retry budgets without blocking the loop. - `configure(live=True)` refreshes omitted retry arguments on already-decorated functions. diff --git a/docs/features/ai/langchain.md b/docs/features/ai/langchain.md index 5f25bdf..62d24a9 100644 --- a/docs/features/ai/langchain.md +++ b/docs/features/ai/langchain.md @@ -95,9 +95,12 @@ under it is rebuilt, and the binding is kept. If you only need the rebuild, call `without_retries(model)`. It returns the same model with `max_retries=0` and no python-wrap layers. -Only `invoke`, `ainvoke`, `stream` and `astream` are guarded. Every other attribute, -such as `batch` or `bind_tools`, belongs to the retry-free model and is not guarded. -Use the guarded model for the calls that must be counted and retried. +The guard is a LangChain Runnable. Use it in a pipe such as `prompt | guarded | parser`. +`batch` and `abatch` run each input through the guard. Tool bindings, structured output, +configuration bindings, and fallbacks retain the guard settings. + +Use `guard_embeddings(model, budget=budget, limiter=limiter)` for sync and async document +and query embeddings. The guard charges estimated input tokens. ## Streams @@ -113,9 +116,9 @@ for the stream rules, which are the same here. ## Observe without wrapping When the model cannot be wrapped, for example inside a chain you do not build, add -`PythonWrapCallback` to the callbacks. It only observes: tokens, latency, model and -errors go into the `genai.llm_call` event. It captures no content and never changes a -call. +`PythonWrapCallback` to the callbacks. Tokens, latency, model and errors go into the +`genai.llm_call` event. Pass `budget=` or `limiter=` to account for observed usage. +Callbacks skip accounting when the call already runs through the guard. ```python diff --git a/docs/features/concurrency/leases-and-idempotency.md b/docs/features/concurrency/leases-and-idempotency.md index 9f84c61..535bfb7 100644 --- a/docs/features/concurrency/leases-and-idempotency.md +++ b/docs/features/concurrency/leases-and-idempotency.md @@ -143,12 +143,16 @@ own database, through a SQLAlchemy `Engine`. It works the same on PostgreSQL, SQ and SQLite. The table is never created for you: `SqlResultStore.ddl("postgresql")` (or `"mssql"` or `"sqlite"`) returns the CREATE TABLE and CREATE INDEX statements, and you run them in a migration. Call `store.purge_expired()` from a scheduled job to delete -expired rows. +expired rows. Use `SqlResultStore(engine, clock="database")` to compare and assign +expiry on the server clock. Both clock modes store Unix milliseconds. For new tables, +`SqlResultStore.ddl(dialect, layout="sequential")` creates a sequential primary key and +a unique index on the digest. The default hash layout remains compatible with existing tables. When the function writes to the same database, pass `connection=` with a callable that returns the SQLAlchemy `Connection` in use. The key is then recorded in your transaction, so the key and the write commit or roll back together. A retry after a crash runs once. -Only sync functions are supported. +Async functions use a SQLAlchemy `AsyncConnection` returned by the provider. +A plain `SqlResultStore` also accepts an async engine for async decorated functions. ```python @@ -172,7 +176,8 @@ with engine.begin() as conn: SQLite needs one extra setup step. Python's sqlite3 driver does not emit BEGIN, which breaks savepoints. Use SQLAlchemy's documented recipe: a `connect` event that sets `dbapi_connection.isolation_level = None`, and a `begin` event that runs -`conn.exec_driver_sql("BEGIN")`. +`conn.exec_driver_sql("BEGIN")`. With aiosqlite, register these events on +`async_engine.sync_engine`. See [coordination API](../../api/coordination.md), [idempotency API](../../api/idempotency.md), and [fork behavior](../../project/migration-0.3.md#forked-workers). diff --git a/docs/llms-full.txt b/docs/llms-full.txt index 3868123..628d20c 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -2116,9 +2116,12 @@ under it is rebuilt, and the binding is kept. If you only need the rebuild, call `without_retries(model)`. It returns the same model with `max_retries=0` and no python-wrap layers. -Only `invoke`, `ainvoke`, `stream` and `astream` are guarded. Every other attribute, -such as `batch` or `bind_tools`, belongs to the retry-free model and is not guarded. -Use the guarded model for the calls that must be counted and retried. +The guard is a LangChain Runnable. Use it in a pipe such as `prompt | guarded | parser`. +`batch` and `abatch` run each input through the guard. Tool bindings, structured output, +configuration bindings, and fallbacks retain the guard settings. + +Use `guard_embeddings(model, budget=budget, limiter=limiter)` for sync and async document +and query embeddings. The guard charges estimated input tokens. ### Streams @@ -2134,9 +2137,9 @@ for the stream rules, which are the same here. ### Observe without wrapping When the model cannot be wrapped, for example inside a chain you do not build, add -`PythonWrapCallback` to the callbacks. It only observes: tokens, latency, model and -errors go into the `genai.llm_call` event. It captures no content and never changes a -call. +`PythonWrapCallback` to the callbacks. Tokens, latency, model and errors go into the +`genai.llm_call` event. Pass `budget=` or `limiter=` to account for observed usage. +Callbacks skip accounting when the call already runs through the guard. ```python @@ -4413,7 +4416,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm `timeout` is about to take over ``SIGALRM`` that something else already uses. - `python_wrap.SqlAppLock`: `SqlAppLock(engine: Any)` SQLAlchemy SQL Server session locks (pyodbc/pymssql); TTL is session lifetime. -- `python_wrap.SqlResultStore`: `SqlResultStore(engine: Any, table: str = 'pw_idempotency', *, dumps: Callable[[Any], str] = dumps, loads: Callable[[str], Any] = loads)` +- `python_wrap.SqlResultStore`: `SqlResultStore(engine: Any, table: str = 'pw_idempotency', *, clock: str = 'application', dumps: Callable[[Any], str] = dumps, loads: Callable[[str], Any] = loads)` Idempotency results in a table of the application's own database (SQLAlchemy). - `python_wrap.ThreadedStore`: `ThreadedStore(store: Any, *, executor: concurrent.futures.Executor | None = None)` Use a synchronous `CacheStore` from async code without blocking the event loop. @@ -4633,15 +4636,17 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm What a `CacheGuard` has seen. - `python_wrap.adapters.GuardedAnthropic`: `GuardedAnthropic(client: Any, **options: Any)` The proxy `guard_anthropic` returns; see `GuardedClient` for the layers. -- `python_wrap.adapters.GuardedChatModel`: `GuardedChatModel(model: Any, **options: Any)` +- `python_wrap.adapters.GuardedChatModel`: `GuardedChatModel(model: Any, *, _shared: GuardedChatModel | None = None, **options: Any)` The wrapper `guard_chat_model` returns. - `python_wrap.adapters.GuardedClient`: `GuardedClient(client: Any, *, system: str, budget: Budget | None = None, limiter: TokenRateLimiter | None = None, policy: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None, attempts: int = 4, retry: Mapping[str, Any] | None = None, owns_retries: bool = True, trace: bool | Mapping[str, Any] = False, cache_guard: CacheGuard | None = None, read_headers: bool = True, first_token: float | None = None, chunk_gap: float | None = None, total: float | None = None, is_async: bool | None = None, limiter_key: Callable[[Mapping[str, Any]], str] | None = None)` The proxy `guard_openai` and `guard_anthropic` return. +- `python_wrap.adapters.GuardedEmbeddings`: `GuardedEmbeddings(model: Any, **options: Any)` + Apply retry, budget and token limits to a LangChain embeddings model. - `python_wrap.adapters.GuardedOpenAI`: `GuardedOpenAI(client: Any, **options: Any)` The proxy `guard_openai` returns; see `GuardedClient` for the layers. - `python_wrap.adapters.PromptCacheWarning` Prompt caching looks ineffective (`CacheGuard`). -- `python_wrap.adapters.PythonWrapCallback`: `PythonWrapCallback(name: str = 'langchain')` +- `python_wrap.adapters.PythonWrapCallback`: `PythonWrapCallback(name: str = 'langchain', *, budget: Budget | None = None, limiter: TokenRateLimiter | None = None)` A LangChain callback handler that observes calls and emits ``genai.llm_call``. - `python_wrap.adapters.ResumableStream`: `ResumableStream(factory: Callable[[], Any], *, max_attempts: int = 3, retry_if: Callable[[BaseException], bool] | None = None, delay: float = 0.5, max_delay: float = 8.0, first_token: float | None = None, chunk_gap: float | None = None, total: float | None = None, on_finish: _Finish | None = None, name: str = 'stream')` A streamed LLM response that reopens itself only while that is safe. @@ -4653,6 +4658,8 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Wrap an Anthropic SDK client so every call is retried, budgeted and rate limited once. - `python_wrap.adapters.guard_chat_model`: `guard_chat_model(model: Any, *, budget: Budget | None = None, limiter: TokenRateLimiter | None = None, policy: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None, attempts: int = 4, retry: Mapping[str, Any] | None = None, trace: bool | Mapping[str, Any] = False, first_token: float | None = None, chunk_gap: float | None = None, total: float | None = None) -> GuardedChatModel` Wrap a LangChain chat model so each call is retried, budgeted and limited once. +- `python_wrap.adapters.guard_embeddings`: `guard_embeddings(model: Any, *, budget: Budget | None = None, limiter: TokenRateLimiter | None = None, policy: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None, attempts: int = 4, retry: Mapping[str, Any] | None = None) -> GuardedEmbeddings` + Guard embedding calls and charge estimated input tokens. - `python_wrap.adapters.guard_openai`: `guard_openai(client: Any, *, budget: Budget | None = None, limiter: TokenRateLimiter | None = None, policy: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None, attempts: int = 4, retry: Mapping[str, Any] | None = None, owns_retries: bool = True, trace: bool | Mapping[str, Any] = False, cache_guard: CacheGuard | None = None, read_headers: bool = True, first_token: float | None = None, chunk_gap: float | None = None, total: float | None = None, is_async: bool | None = None, limiter_key: Callable[[Mapping[str, Any]], str] | None = None) -> GuardedOpenAI` Wrap an OpenAI SDK client so every call is retried, budgeted and rate limited once. - `python_wrap.adapters.no_sdk_retries`: `no_sdk_retries(client: C) -> C` diff --git a/src/python_wrap/adapters/__init__.py b/src/python_wrap/adapters/__init__.py index 4870e2a..ae93b50 100644 --- a/src/python_wrap/adapters/__init__.py +++ b/src/python_wrap/adapters/__init__.py @@ -37,8 +37,10 @@ from python_wrap.adapters.anthropic import GuardedAnthropic, guard_anthropic from python_wrap.adapters.langchain import ( GuardedChatModel, + GuardedEmbeddings, PythonWrapCallback, guard_chat_model, + guard_embeddings, ) from python_wrap.adapters.openai import GuardedOpenAI, guard_openai @@ -61,8 +63,10 @@ "GuardedAnthropic": "anthropic", "guard_anthropic": "anthropic", "GuardedChatModel": "langchain", + "GuardedEmbeddings": "langchain", "PythonWrapCallback": "langchain", "guard_chat_model": "langchain", + "guard_embeddings": "langchain", } __all__ = [ @@ -71,6 +75,7 @@ "GuardedAnthropic", "GuardedChatModel", "GuardedClient", + "GuardedEmbeddings", "GuardedOpenAI", "PromptCacheWarning", "PythonWrapCallback", @@ -79,6 +84,7 @@ "StreamedToolCall", "guard_anthropic", "guard_chat_model", + "guard_embeddings", "guard_openai", "no_sdk_retries", "resume_safe", diff --git a/src/python_wrap/adapters/langchain.py b/src/python_wrap/adapters/langchain.py index 6a35d97..cc6f03c 100644 --- a/src/python_wrap/adapters/langchain.py +++ b/src/python_wrap/adapters/langchain.py @@ -9,24 +9,38 @@ rate-limit headers when ``response_metadata["headers"]`` carries them). ``stream``/``astream`` return a `ResumableStream`: reopened only before any output. -`PythonWrapCallback` only observes (usage, latency, errors) and emits the -``genai.llm_call`` event, for code paths where the model cannot be wrapped. +`PythonWrapCallback` emits the ``genai.llm_call`` event and can optionally account for +usage on code paths where the model cannot be wrapped. -LangChain is never imported here. +LangChain is imported lazily when constructing a guard. """ from __future__ import annotations +import contextvars +import functools +import importlib import time import uuid from collections.abc import Callable, Mapping from typing import Any -from python_wrap import _core +from python_wrap import _core, _fork from python_wrap.adapters._sdk import GuardedClient, ResumableStream -from python_wrap.llm import Budget, TokenRateLimiter, read_usage +from python_wrap.llm import Budget, TokenRateLimiter, estimate_tokens, read_usage -__all__ = ["GuardedChatModel", "PythonWrapCallback", "guard_chat_model", "without_retries"] +__all__ = [ + "GuardedChatModel", + "GuardedEmbeddings", + "PythonWrapCallback", + "guard_chat_model", + "guard_embeddings", + "without_retries", +] + +_guard_active: contextvars.ContextVar[bool] = contextvars.ContextVar( + "python_wrap_langchain_guard_active", default=False +) def without_retries(model: Any) -> Any: @@ -77,6 +91,15 @@ def _text(value: Any) -> str: return str(value) +def _stream_config(config: Any) -> dict[str, Any]: + settings = dict(config or {}) + settings["metadata"] = { + **(settings.get("metadata") or {}), + "python_wrap_langchain_guarded": True, + } + return settings + + def _headers(result: Any) -> Any: meta = getattr(result, "response_metadata", None) return meta.get("headers") if isinstance(meta, Mapping) else None @@ -85,41 +108,70 @@ def _headers(result: Any) -> Any: class GuardedChatModel: """The wrapper `guard_chat_model` returns. - ``invoke``, ``ainvoke``, ``stream`` and ``astream`` are guarded; every other attribute - is the retry-free model's (``batch`` and tools such as ``bind_tools`` are not guarded). + Invocation, streaming, and bindings retain the same guard settings. Attributes: raw: The model you passed. model: The copy calls go through (``max_retries=0``). """ - def __init__(self, model: Any, **options: Any) -> None: + def __init__( + self, model: Any, *, _shared: GuardedChatModel | None = None, **options: Any + ) -> None: self.raw = model - self.model = without_retries(model) - self._sync = GuardedClient(_NoSdk(), system="langchain", is_async=False, **options) - self._async = GuardedClient(_NoSdk(), system="langchain", is_async=True, **options) + self.model = without_retries(model) if _shared is None else model + if _shared is None: + self._sync = GuardedClient(_NoSdk(), system="langchain", is_async=False, **options) + self._async = GuardedClient(_NoSdk(), system="langchain", is_async=True, **options) + else: + self._sync, self._async = _shared._sync, _shared._async self._invoke = self._sync._compose("langchain.invoke", self._attempt) self._ainvoke = self._async._compose("langchain.ainvoke", self._aattempt) + def bind(self, **kwargs: Any) -> GuardedChatModel: + return type(self)(self.model.bind(**kwargs), _shared=self) + + def bind_tools(self, *args: Any, **kwargs: Any) -> GuardedChatModel: + return type(self)(self.model.bind_tools(*args, **kwargs), _shared=self) + + def with_config(self, *args: Any, **kwargs: Any) -> GuardedChatModel: + return type(self)(self.model.with_config(*args, **kwargs), _shared=self) + + def with_structured_output(self, *args: Any, **kwargs: Any) -> GuardedChatModel: + return type(self)(self.model.with_structured_output(*args, **kwargs), _shared=self) + + def with_fallbacks(self, fallbacks: Any, **kwargs: Any) -> GuardedChatModel: + guarded = [without_retries(getattr(model, "model", model)) for model in fallbacks] + return type(self)(self.model.with_fallbacks(guarded, **kwargs), _shared=self) + + def with_retry(self, *args: Any, **kwargs: Any) -> Any: + raise ValueError("python-wrap owns the retries") + def _attempt(self, input: Any, config: Any = None, **kwargs: Any) -> Any: request = {"input": _text(input)} cost = self._sync._reserve((), request, "langchain.invoke") + token = _guard_active.set(True) try: result = self.model.invoke(input, config, **kwargs) except BaseException as exc: self._sync._failed(cost, exc, request) raise + finally: + _guard_active.reset(token) self._sync._settled(cost, result, _headers(result), request) return result async def _aattempt(self, input: Any, config: Any = None, **kwargs: Any) -> Any: request = {"input": _text(input)} cost = await self._async._areserve((), request, "langchain.ainvoke") + token = _guard_active.set(True) try: result = await self.model.ainvoke(input, config, **kwargs) except BaseException as exc: self._async._failed(cost, exc, request) raise + finally: + _guard_active.reset(token) self._async._settled(cost, result, _headers(result), request) return result @@ -135,7 +187,7 @@ def stream(self, input: Any, config: Any = None, **kwargs: Any) -> ResumableStre admission = self._sync._admit((input,), request, "langchain.stream") return self._sync._resumable( "langchain.stream", - lambda: self.model.stream(input, config, **kwargs), + lambda: self.model.stream(input, _stream_config(config), **kwargs), admission, request, ) @@ -146,7 +198,7 @@ async def astream(self, input: Any, config: Any = None, **kwargs: Any) -> Any: admission = await self._async._aadmit((input,), request, "langchain.astream") stream = self._async._resumable( "langchain.astream", - lambda: self.model.astream(input, config, **kwargs), + lambda: self.model.astream(input, _stream_config(config), **kwargs), admission, request, ) @@ -162,6 +214,21 @@ def __repr__(self) -> str: return f"GuardedChatModel({type(self.raw).__name__}, attempts={self._sync.attempts})" +@functools.lru_cache(maxsize=1) +def _runnable_class() -> type[GuardedChatModel]: + try: + runnable = importlib.import_module("langchain_core.runnables").Runnable + except ModuleNotFoundError as exc: + if exc.name != "langchain_core": + raise + return GuardedChatModel + + class _GuardedRunnable(GuardedChatModel, runnable): # type: ignore[misc, valid-type] + pass + + return _GuardedRunnable + + def guard_chat_model( model: Any, *, @@ -208,7 +275,7 @@ def invoke(self, input, config=None): assert guard_chat_model(FakeModel()).invoke("hello")["content"] == "hi" ``` """ - return GuardedChatModel( + return _runnable_class()( model, budget=budget, limiter=limiter, @@ -222,12 +289,88 @@ def invoke(self, input, config=None): ) +class GuardedEmbeddings: + """Apply retry, budget and token limits to a LangChain embeddings model.""" + + def __init__(self, model: Any, **options: Any) -> None: + self.raw = model + self.model = without_retries(model) + self._sync = GuardedClient(_NoSdk(), system="langchain", is_async=False, **options) + self._async = GuardedClient(_NoSdk(), system="langchain", is_async=True, **options) + self._embed = self._sync._compose("langchain.embed", self._attempt) + self._aembed = self._async._compose("langchain.aembed", self._aattempt) + + @staticmethod + def _response(value: Any, tokens: int) -> dict[str, Any]: + return {"value": value, "usage": {"input_tokens": tokens, "output_tokens": 0}} + + def _attempt(self, text: Any, method: str, **kwargs: Any) -> Any: + request = {"input": text} + reserved = self._sync._reserve((), request, "langchain.embed") + try: + value = getattr(self.model, method)(text, **kwargs) + except BaseException as exc: + self._sync._failed(reserved, exc, request) + raise + tokens = ( + reserved if self._sync._limiting(request) is not None else estimate_tokens(**request) + ) + return self._response(value, tokens) + + async def _aattempt(self, text: Any, method: str, **kwargs: Any) -> Any: + request = {"input": text} + reserved = await self._async._areserve((), request, "langchain.aembed") + limiter = self._async._limiting(request) + try: + value = await getattr(self.model, method)(text, **kwargs) + except BaseException: + if limiter is not None: + await limiter._asettle(reserved, 0) + raise + tokens = reserved if limiter is not None else estimate_tokens(**request) + return self._response(value, tokens) + + def embed_documents(self, texts: list[str], **kwargs: Any) -> list[list[float]]: + result: list[list[float]] = self._embed(texts, "embed_documents", **kwargs)["value"] + return result + + def embed_query(self, text: str, **kwargs: Any) -> list[float]: + result: list[float] = self._embed(text, "embed_query", **kwargs)["value"] + return result + + async def aembed_documents(self, texts: list[str], **kwargs: Any) -> list[list[float]]: + result: list[list[float]] = (await self._aembed(texts, "aembed_documents", **kwargs))[ + "value" + ] + return result + + async def aembed_query(self, text: str, **kwargs: Any) -> list[float]: + result: list[float] = (await self._aembed(text, "aembed_query", **kwargs))["value"] + return result + + +def guard_embeddings( + model: Any, + *, + budget: Budget | None = None, + limiter: TokenRateLimiter | None = None, + policy: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None, + attempts: int = 4, + retry: Mapping[str, Any] | None = None, +) -> GuardedEmbeddings: + """Guard embedding calls and charge estimated input tokens.""" + return GuardedEmbeddings( + model, budget=budget, limiter=limiter, policy=policy, attempts=attempts, retry=retry + ) + + class PythonWrapCallback: """A LangChain callback handler that observes calls and emits ``genai.llm_call``. Use it where a model cannot be wrapped (inside a chain built elsewhere): ``model.invoke(prompt, config={"callbacks": [PythonWrapCallback()]})``. It records - tokens, latency, model and errors; it never changes a call and captures no content. + tokens, latency, model and errors. Pass a budget or limiter to account for usage + on unguarded calls. It captures no content. Duck-typed: LangChain need not be importable when it is created. """ @@ -237,20 +380,35 @@ class PythonWrapCallback: raise_error = False run_inline = True - def __init__(self, name: str = "langchain") -> None: - self.name = name - self._started: dict[Any, tuple[float, float]] = {} + def __init__( + self, + name: str = "langchain", + *, + budget: Budget | None = None, + limiter: TokenRateLimiter | None = None, + ) -> None: + self.name, self.budget, self.limiter = name, budget, limiter + self._started: dict[Any, tuple[float, float, bool]] = {} + self._lock = _fork.ForkSafeLock() + + def _start(self, run_id: Any, metadata: Any) -> None: + guarded = _guard_active.get() or bool((metadata or {}).get("python_wrap_langchain_guarded")) + with self._lock: + self._started[run_id] = (time.monotonic(), time.time(), guarded) + if len(self._started) > 10_000: + del self._started[next(iter(self._started))] def on_llm_start(self, serialized: Any, prompts: Any, *, run_id: Any = None, **_: Any) -> None: - self._started[run_id] = (time.monotonic(), time.time()) + self._start(run_id, _.get("metadata")) def on_chat_model_start( self, serialized: Any, messages: Any, *, run_id: Any = None, **_: Any ) -> None: - self._started[run_id] = (time.monotonic(), time.time()) + self._start(run_id, _.get("metadata")) def _emit(self, run_id: Any, status: str, **fields: Any) -> None: - began, wall = self._started.pop(run_id, (time.monotonic(), time.time())) + with self._lock: + began, wall, _ = self._started.pop(run_id, (time.monotonic(), time.time(), False)) _core.emit( "genai.llm_call", self.name, @@ -276,6 +434,13 @@ def on_llm_end(self, response: Any, *, run_id: Any = None, **_: Any) -> None: for generation in batch: usage = read_usage(getattr(generation, "message", None)) or usage model = output.get("model_name") or (usage.model if usage else None) + with self._lock: + started = self._started.get(run_id) + if usage is not None and not (started[2] if started else _guard_active.get()): + if self.budget is not None: + self.budget.record(usage) + if self.limiter is not None: + self.limiter.settle(0, usage.total_tokens) self._emit( run_id, "ok", diff --git a/src/python_wrap/idempotency.py b/src/python_wrap/idempotency.py index ccb4ad6..18190ff 100644 --- a/src/python_wrap/idempotency.py +++ b/src/python_wrap/idempotency.py @@ -5,6 +5,7 @@ import asyncio import functools import importlib +import inspect import json import re import uuid @@ -91,6 +92,17 @@ def delete(self, key: str) -> bool: "sqlite": ("TEXT", "INTEGER"), } +_CLOCK_SQL = { + "postgresql": "CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)", + "mssql": "DATEDIFF_BIG(millisecond, '19700101', SYSUTCDATETIME())", + "sqlite": "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)", +} +_SEQUENTIAL_ID = { + "postgresql": "BIGINT GENERATED BY DEFAULT AS IDENTITY", + "mssql": "BIGINT IDENTITY(1,1)", + "sqlite": "INTEGER", +} + class SqlResultStore: """Idempotency results in a table of the application's own database (SQLAlchemy). @@ -109,7 +121,8 @@ class SqlResultStore: error instead of a second run. Args: - engine: A SQLAlchemy ``Engine``. + engine: A SQLAlchemy engine or async engine. + clock: ``"application"`` or ``"database"`` for expiration calculations. table: Table name (letters, digits and underscores only). dumps: Serializer for results; defaults to ``json.dumps``. loads: Deserializer matching ``dumps``. @@ -125,27 +138,39 @@ def __init__( engine: Any, table: str = "pw_idempotency", *, + clock: str = "application", dumps: Callable[[Any], str] = json.dumps, loads: Callable[[str], Any] = json.loads, ) -> None: if not isinstance(table, str) or not _IDENTIFIER.fullmatch(table): raise ValueError("table must be a plain SQL identifier") + if clock not in {"application", "database"}: + raise ValueError("clock must be application or database") + self.clock = clock self.engine, self.table, self.dumps, self.loads = engine, table, dumps, loads @staticmethod - def ddl(dialect: str, table: str = "pw_idempotency") -> list[str]: + def ddl(dialect: str, table: str = "pw_idempotency", *, layout: str = "hash") -> list[str]: """``CREATE`` statements for ``dialect`` (``postgresql``, ``mssql`` or ``sqlite``).""" if dialect not in _TYPES: raise ValueError(f"dialect must be one of {sorted(_TYPES)}") if not _IDENTIFIER.fullmatch(table): raise ValueError("table must be a plain SQL identifier") + if layout not in {"hash", "sequential"}: + raise ValueError("layout must be hash or sequential") text_type, int_type = _TYPES[dialect] - return [ - f"CREATE TABLE {table} (idem_key VARCHAR(64) NOT NULL PRIMARY KEY," + columns = "idem_key VARCHAR(64) NOT NULL PRIMARY KEY" + if layout == "sequential": + columns = f"id {_SEQUENTIAL_ID[dialect]} PRIMARY KEY, idem_key VARCHAR(64) NOT NULL" + statements = [ + f"CREATE TABLE {table} ({columns}," f" status VARCHAR(8) NOT NULL, owner VARCHAR(64) NOT NULL," f" result {text_type} NULL, expires_at {int_type} NOT NULL)", f"CREATE INDEX {table}_expires ON {table} (expires_at)", ] + if layout == "sequential": + statements.insert(1, f"CREATE UNIQUE INDEX {table}_key ON {table} (idem_key)") + return statements @staticmethod def _sql(statement: str) -> Any: @@ -156,55 +181,55 @@ def _duplicate() -> Any: """SQLAlchemy's IntegrityError (raised for a primary-key clash).""" return importlib.import_module("sqlalchemy.exc").IntegrityError - @staticmethod - def _now() -> int: - return int(_core.wall_time() * 1000) + def _timed(self, conn: Any, statement: str, params: dict[str, Any]) -> Any: + if self.clock == "database": + statement = statement.replace(":now", _CLOCK_SQL[conn.dialect.name]) + else: + params = {**params, "now": int(_core.wall_time() * 1000)} + return conn.execute(self._sql(statement), params) def _read(self, conn: Any, key: str) -> tuple[Any] | None: # The table name was validated as an identifier; values are bound parameters. - row = conn.execute( - self._sql(f"SELECT status, result, expires_at FROM {self.table} WHERE idem_key=:k"), # nosec B608 + row = self._timed( + conn, + f"SELECT result FROM {self.table}" # nosec B608 + " WHERE idem_key=:k AND status='done' AND expires_at>:now", {"k": name_digest(key)}, ).first() - if row is None or row[0] != "done" or int(row[2]) <= self._now(): - return None - return (self.loads(row[1]),) + return None if row is None else (self.loads(row[0]),) def _claim(self, conn: Any, key: str, owner: str, ttl: float) -> bool: """Insert a ``running`` row, or take over an expired one. False if it is live.""" - params = {"k": name_digest(key), "o": owner, "e": self._now() + int(ttl * 1000)} + params = {"k": name_digest(key), "o": owner, "ttl": int(ttl * 1000)} try: with conn.begin_nested(): - conn.execute( - self._sql( - f"INSERT INTO {self.table} (idem_key, status, owner, result, expires_at)" # nosec B608 - " VALUES (:k, 'running', :o, NULL, :e)" - ), + self._timed( + conn, + f"INSERT INTO {self.table} (idem_key, status, owner, result, expires_at)" # nosec B608 + " VALUES (:k, 'running', :o, NULL, :now + :ttl)", params, ) return True except self._duplicate(): pass - taken = conn.execute( - self._sql( - f"UPDATE {self.table} SET status='running', owner=:o, result=NULL," # nosec B608 - " expires_at=:e WHERE idem_key=:k AND expires_at<=:now" - ), - {**params, "now": self._now()}, + taken = self._timed( + conn, + f"UPDATE {self.table} SET status='running', owner=:o, result=NULL," # nosec B608 + " expires_at=:now + :ttl WHERE idem_key=:k AND expires_at<=:now", + params, ) return bool(taken.rowcount == 1) def _finish(self, conn: Any, key: str, value: Any, ttl: float, owner: str) -> None: - conn.execute( - self._sql( - f"UPDATE {self.table} SET status='done', result=:r, expires_at=:e" # nosec B608 - " WHERE idem_key=:k AND owner=:o" - ), + self._timed( + conn, + f"UPDATE {self.table} SET status='done', result=:r, expires_at=:now + :ttl" # nosec B608 + " WHERE idem_key=:k AND owner=:o", { "k": name_digest(key), "o": owner, "r": self.dumps(value), - "e": self._now() + int(ttl * 1000), + "ttl": int(ttl * 1000), }, ) @@ -222,40 +247,62 @@ def get(self, key: str) -> tuple[Any] | None: with self.engine.connect() as conn: return self._read(conn, key) - def set(self, key: str, entry: tuple[Any], ttl: float) -> None: + def _set(self, conn: Any, key: str, entry: tuple[Any], ttl: float) -> None: params = { "k": name_digest(key), "o": "", "r": self.dumps(entry[0]), - "e": self._now() + int(ttl * 1000), + "ttl": int(ttl * 1000), } - update = self._sql( - f"UPDATE {self.table} SET status='done', owner=:o, result=:r, expires_at=:e" # nosec B608 + update = ( + f"UPDATE {self.table} SET status='done', owner=:o, result=:r, expires_at=:now + :ttl" # nosec B608 " WHERE idem_key=:k" ) + if self._timed(conn, update, params).rowcount: + return + try: + with conn.begin_nested(): + self._timed( + conn, + f"INSERT INTO {self.table}" # nosec B608 + " (idem_key, status, owner, result, expires_at)" + " VALUES (:k, 'done', :o, :r, :now + :ttl)", + params, + ) + except self._duplicate(): # inserted concurrently: last writer wins, as in Redis + self._timed(conn, update, params) + + def _delete(self, conn: Any, key: str) -> bool: + gone = conn.execute( + self._sql(f"DELETE FROM {self.table} WHERE idem_key=:k"), # nosec B608 + {"k": name_digest(key)}, + ) + return bool(gone.rowcount) + + def set(self, key: str, entry: tuple[Any], ttl: float) -> None: with self.engine.begin() as conn: - if conn.execute(update, params).rowcount: - return - try: - with conn.begin_nested(): - conn.execute( - self._sql( - f"INSERT INTO {self.table}" # nosec B608 - " (idem_key, status, owner, result, expires_at)" - " VALUES (:k, 'done', :o, :r, :e)" - ), - params, - ) - except self._duplicate(): # inserted concurrently: last writer wins, as in Redis - conn.execute(update, params) + self._set(conn, key, entry, ttl) def delete(self, key: str) -> bool: with self.engine.begin() as conn: - gone = conn.execute( - self._sql(f"DELETE FROM {self.table} WHERE idem_key=:k"), # nosec B608 - {"k": name_digest(key)}, - ) - return bool(gone.rowcount) + return self._delete(conn, key) + + async def aget(self, key: str) -> tuple[Any] | None: + """Read a result on a SQLAlchemy async engine.""" + async with self.engine.connect() as conn: + result: tuple[Any] | None = await conn.run_sync(self._read, key) + return result + + async def aset(self, key: str, entry: tuple[Any], ttl: float) -> None: + """Write a result on a SQLAlchemy async engine.""" + async with self.engine.begin() as conn: + await conn.run_sync(self._set, key, entry, ttl) + + async def adelete(self, key: str) -> bool: + """Delete a result on a SQLAlchemy async engine.""" + async with self.engine.begin() as conn: + deleted: bool = await conn.run_sync(self._delete, key) + return deleted def purge_expired(self, limit: int = 1000) -> int: """Delete up to ``limit`` expired rows; returns how many went. Call it on a schedule.""" @@ -269,7 +316,7 @@ def purge_expired(self, limit: int = 1000) -> int: f" WHERE expires_at<=:now LIMIT {limit})" ) with self.engine.begin() as conn: - return int(conn.execute(self._sql(sql), {"now": self._now()}).rowcount) + return int(self._timed(conn, sql, {}).rowcount) def idempotent( @@ -316,7 +363,10 @@ def idempotent( raise ValueError("idempotency requires a result store with fail_open=False") if backend is not None and not isinstance(backend, LocalLease) and store is None: raise ValueError("a distributed lease requires an explicitly shared result store") - native = _core.is_async(results.get) # an AsyncCacheStore: awaited, never threaded + async_sql = isinstance(results, SqlResultStore) and hasattr(results.engine, "sync_engine") + reader = results.aget if async_sql else results.get + writer = results.aset if async_sql else results.set + native = _core.is_async(reader) # Async stores are awaited directly. if backend is None: from python_wrap.async_cache import AsyncRedisStore from python_wrap.coordination import AsyncRedisLock, RedisLock @@ -330,12 +380,12 @@ def idempotent( ) async def read(k: str) -> Any: - return await (results.get(k) if native else asyncio.to_thread(results.get, k)) + return await (reader(k) if native else asyncio.to_thread(reader, k)) def write(k: str, value: Any) -> Any: if native: - return asyncio.ensure_future(results.set(k, (value,), retention)) - return asyncio.create_task(asyncio.to_thread(results.set, k, (value,), retention)) + return asyncio.ensure_future(writer(k, (value,), retention)) + return asyncio.create_task(asyncio.to_thread(writer, k, (value,), retention)) if connection is not None and not isinstance(results, SqlResultStore): raise TypeError("connection= needs store=SqlResultStore(...)") @@ -344,13 +394,10 @@ def decorate(func: F) -> F: if native and not _core.is_async(func): raise TypeError("an async result store needs an async def function") if connection is not None: - if _core.is_async(func): - raise TypeError("connection= supports sync functions only") + transaction = _atransactional if _core.is_async(func) else _transactional return cast( F, - _transactional( - func, key, results, connection, retention, lease_seconds, in_progress - ), + transaction(func, key, results, connection, retention, lease_seconds, in_progress), ) def scope(k: str) -> Lease: @@ -437,17 +484,10 @@ def _transactional( def wrapper(*args: Any, **kw: Any) -> Any: k = call_key(func, key, args, kw) conn = connection() - found = store._read(conn, k) - if found is not None: - return found[0] owner = uuid.uuid4().hex - if not store._claim(conn, k, owner, lease_seconds): - found = store._read(conn, k) # a duplicate committed while we waited on its lock - if found is not None: - return found[0] - if in_progress == "return_none": - return None - raise AlreadyRunning("idem:" + k) + claimed, cached = _claim_result(conn, store, k, owner, lease_seconds, in_progress) + if not claimed: + return cached try: value = func(*args, **kw) store._finish(conn, k, value, retention, owner) @@ -460,3 +500,56 @@ def wrapper(*args: Any, **kw: Any) -> Any: return value return wrapper + + +def _claim_result( + conn: Any, store: SqlResultStore, key: str, owner: str, lease_seconds: float, in_progress: str +) -> tuple[bool, Any]: + if conn.get_execution_options().get("isolation_level") == "AUTOCOMMIT": + raise RuntimeError("idempotent(connection=...) requires a transactional connection") + found = store._read(conn, key) + if found is not None: + return False, found[0] + if store._claim(conn, key, owner, lease_seconds): + return True, None + found = store._read(conn, key) + if found is not None: + return False, found[0] + if in_progress == "return_none": + return False, None + raise AlreadyRunning("idem:" + key) + + +def _atransactional( + func: Callable[..., Any], + key: str | Callable[..., Any] | None, + store: SqlResultStore, + connection: Callable[[], Any], + retention: float, + lease_seconds: float, + in_progress: str, +) -> Callable[..., Any]: + @functools.wraps(func) + async def wrapper(*args: Any, **kw: Any) -> Any: + k = call_key(func, key, args, kw) + conn = connection() + if not hasattr(conn, "run_sync") and inspect.isawaitable(conn): + conn = await conn + owner = uuid.uuid4().hex + claimed, cached = await conn.run_sync( + _claim_result, store, k, owner, lease_seconds, in_progress + ) + if not claimed: + return cached + try: + value = await func(*args, **kw) + await conn.run_sync(store._finish, k, value, retention, owner) + except BaseException as exc: + try: + await conn.run_sync(store._abandon, k, owner) + except Exception as cleanup_error: + raise exc from cleanup_error + raise + return value + + return wrapper diff --git a/tests/test_langchain_adapter.py b/tests/test_langchain_adapter.py index d1aa24b..a41af23 100644 --- a/tests/test_langchain_adapter.py +++ b/tests/test_langchain_adapter.py @@ -110,3 +110,49 @@ def test_callback_emits_genai_llm_call() -> None: unsubscribe() assert seen and seen[0]["status"] == "ok" assert seen[0]["input_tokens"] == 10 and seen[0]["output_tokens"] == 5 + + +def test_runnable_composes_and_batch_retains_budget() -> None: + from langchain_core.runnables import Runnable, RunnableLambda + + budget = Budget(tokens=1000) + guarded = guard_chat_model(FlakyModel(calls=[]), budget=budget) + assert isinstance(guarded, Runnable) + chain = RunnableLambda(str) | guarded.with_config(tags=["test"]) + assert len(chain.batch(["hi", "again"])) == 2 + assert budget.spent().tokens == 30 + + +def test_callback_charges_only_unguarded_calls() -> None: + budget = Budget(tokens=1000) + callback = PythonWrapCallback(budget=budget) + config = {"callbacks": [callback]} + model = FlakyModel(max_retries=0, calls=[]) + model.invoke("hi", config=config) + assert budget.spent().tokens == 15 + guard_chat_model(model, budget=budget).invoke("hi", config=config) + assert budget.spent().tokens == 30 + + +def test_embeddings_guard_retries_and_charges_input_estimate() -> None: + from python_wrap.adapters import guard_embeddings + + class Embeddings: + calls = 0 + + def embed_query(self, text: str) -> list[float]: + self.calls += 1 + if self.calls == 1: + raise RateLimited() + return [1.0] + + async def aembed_documents(self, texts: list[str]) -> list[list[float]]: + return [[1.0] for _ in texts] + + budget = Budget(tokens=1000) + model = Embeddings() + guarded = guard_embeddings(model, budget=budget, retry={"delay": 0}) + assert guarded.embed_query("abcdefgh") == [1.0] + assert model.calls == 2 + assert asyncio.run(guarded.aembed_documents(["abcd", "efgh"])) == [[1.0], [1.0]] + assert budget.spent().tokens == 4 diff --git a/tests/test_sql_backends_live.py b/tests/test_sql_backends_live.py index b9664d5..5601c10 100644 --- a/tests/test_sql_backends_live.py +++ b/tests/test_sql_backends_live.py @@ -154,24 +154,34 @@ def test_sqlserver_errors_are_classified(mssql_engine): conn.exec_driver_sql(f"DROP TABLE {table}") -@pytest.fixture(params=["postgres", "mssql"]) -def result_table(request: Any) -> Iterator[tuple[Any, str]]: - engine = request.getfixturevalue("pg_engine" if request.param == "postgres" else "mssql_engine") +@pytest.fixture( + params=[ + ("postgres", "hash"), + ("mssql", "hash"), + ("postgres", "sequential"), + ("mssql", "sequential"), + ] +) +def result_table(request: Any) -> Iterator[tuple[Any, str, str]]: + backend, layout = request.param + engine = request.getfixturevalue("pg_engine" if backend == "postgres" else "mssql_engine") table = f"pw_idem_{uuid.uuid4().hex[:8]}" - dialect = "postgresql" if request.param == "postgres" else "mssql" + dialect = "postgresql" if backend == "postgres" else "mssql" with engine.begin() as conn: - for statement in SqlResultStore.ddl(dialect, table): + for statement in SqlResultStore.ddl(dialect, table, layout=layout): conn.exec_driver_sql(statement) conn.exec_driver_sql(f"CREATE TABLE {table}_orders (id int)") - yield engine, table + yield engine, table, layout with engine.begin() as conn: conn.exec_driver_sql(f"DROP TABLE {table}") conn.exec_driver_sql(f"DROP TABLE {table}_orders") def test_sql_result_store_key_commits_with_the_write(result_table): - engine, table = result_table - store = SqlResultStore(engine, table) + engine, table, layout = result_table + store = SqlResultStore( + engine, table, clock="database" if layout == "sequential" else "application" + ) store.set("plain", ({"n": 1},), 60) assert store.get("plain") == ({"n": 1},) current = {} diff --git a/tests/test_sql_result_store.py b/tests/test_sql_result_store.py index 7022a06..134e6ff 100644 --- a/tests/test_sql_result_store.py +++ b/tests/test_sql_result_store.py @@ -146,12 +146,6 @@ def test_validation() -> None: SqlResultStore.ddl("oracle") with pytest.raises(TypeError): idempotent(connection=lambda: None) - store = SqlResultStore(object()) - with pytest.raises(TypeError): - - @idempotent(store=store, connection=lambda: None) - async def nope() -> None: ... - assert "NVARCHAR(MAX)" in SqlResultStore.ddl("mssql")[0] @@ -173,3 +167,67 @@ def run() -> int: with engine.begin() as conn: assert run() == 2 assert run() == 2 + + +@pytest.mark.asyncio +async def test_async_sql_result_store_and_transaction(tmp_path: Path) -> None: + pytest.importorskip("aiosqlite") + pytest.importorskip("greenlet") + from sqlalchemy.ext.asyncio import create_async_engine + + db = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'async.db'}") + store = SqlResultStore(db) + try: + async with db.begin() as conn: + for statement in store.ddl("sqlite"): + await conn.exec_driver_sql(statement) + + calls = 0 + + @idempotent(store=store) + async def plain() -> int: + nonlocal calls + calls += 1 + return calls + + assert await plain() == await plain() == 1 + + async with db.begin() as conn: + + @idempotent(store=store, connection=lambda: conn) + async def transaction() -> int: + nonlocal calls + calls += 1 + if calls == 2: + raise ValueError("retry me") + return calls + + with pytest.raises(ValueError, match="retry me"): + await transaction() + assert await transaction() == await transaction() == 3 + finally: + await db.dispose() + + +def test_database_clock_and_sequential_layout(engine: Any) -> None: + store = SqlResultStore(engine, "sequential_idem", clock="database") + with engine.begin() as conn: + for statement in store.ddl("sqlite", store.table, layout="sequential"): + conn.exec_driver_sql(statement) + with fake_clock() as clock: + store.set("a", ("result",), 60) + clock.advance(120) + assert store.get("a") == ("result",) + assert store.purge_expired() == 0 + assert store.delete("a") + + +def test_transactional_idempotency_rejects_autocommit(engine: Any) -> None: + with engine.connect().execution_options(isolation_level="AUTOCOMMIT") as conn: + + @idempotent(store=SqlResultStore(engine), connection=lambda: conn) + def work() -> None: + pytest.fail("autocommit work ran") + + with pytest.raises(RuntimeError, match="transactional connection"): + work() From 613a59b72a33d483198f169da4dd2d706c28725c Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Thu, 3 Dec 2026 07:35:45 +0200 Subject: [PATCH 22/38] Reuse shared bulkhead slots during an opt-in idle window --- CHANGELOG.md | 2 + benchmarks/run.py | 5 +- docs/features/concurrency/bulkheads.md | 8 +++ docs/llms-full.txt | 4 +- src/python_wrap/bulkhead.py | 4 ++ src/python_wrap/coordination.py | 43 ++++++++++++-- src/python_wrap/shared.py | 82 +++++++++++++++++++++++++- tests/test_bulkhead.py | 43 ++++++++++++++ 8 files changed, 179 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c99c03c..5b9bea3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration. ### Added +- Shared bulkheads can opt into brief lease reuse with `slot_idle=`. + - LangChain guards compose as runnables, preserve guards on bindings, and cover embeddings. - SQL idempotency supports async connections, database-clock expiration, and sequential DDL. diff --git a/benchmarks/run.py b/benchmarks/run.py index 43d64b6..9b11c16 100644 --- a/benchmarks/run.py +++ b/benchmarks/run.py @@ -168,6 +168,7 @@ def _redis_cases(url: str) -> list[Case]: rows = [ ("circuit_breaker", _shared_breaker), ("Bulkhead(8)", _shared_bulkhead), + ("Bulkhead(8, slot_idle=1)", functools.partial(_shared_bulkhead, slot_idle=1)), ("rate_limit", _shared_window), ("retry_budget", _shared_budget), ] @@ -184,9 +185,9 @@ def _shared_breaker(client: Any) -> Callable[[Any], Any]: return CircuitBreaker(name="bench", backend=kind(client), logger=LOG) -def _shared_bulkhead(client: Any) -> Callable[[Any], Any]: +def _shared_bulkhead(client: Any, *, slot_idle: float = 0) -> Callable[[Any], Any]: kind = AsyncRedisSemaphore if _is_async(client) else RedisSemaphore - return Bulkhead(8, name="bench", backend=kind(client)) + return Bulkhead(8, name="bench", backend=kind(client), slot_idle=slot_idle) def _shared_window(client: Any) -> Callable[[Any], Any]: diff --git a/docs/features/concurrency/bulkheads.md b/docs/features/concurrency/bulkheads.md index 8f23b4d..d44b5fc 100644 --- a/docs/features/concurrency/bulkheads.md +++ b/docs/features/concurrency/bulkheads.md @@ -29,6 +29,14 @@ asyncio.run(main()) - For "at most N of these at once" with no queue limit, use [`limit_concurrency`](#limit_concurrency). - To limit calls per time window instead, use [Rate limits](rate-limits.md). To bound a batch of awaitables you are starting yourself, use [`gather_limit` or `map_async`](async-helpers.md). + +### Reuse shared slots + +Use `Bulkhead(8, name="vendor", backend=semaphore, slot_idle=1)` to let the +same process reuse a released slot for up to one second. The backend still counts +that slot during the idle interval, so another process may wait longer. The default +`slot_idle=0` releases each slot immediately. + ## Bulkhead | Argument | Meaning | diff --git a/docs/llms-full.txt b/docs/llms-full.txt index 628d20c..f67bfcb 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -4288,7 +4288,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Pending includes records currently being written; failures are counted separately. - `python_wrap.Buffered`: `Buffered(func: Callable[[list[Any]], Any], *, max_size: int = 200, flush_interval: float = 1, max_queue: int = 10000, on_full: str = 'drop', drain_on_exit: float = 3, on_error: str = 'continue', logger: Any = None, journal: BufferJournal | None = None)` A synchronous batch callable with submit/flush/close/disable/stats controls. -- `python_wrap.Bulkhead`: `Bulkhead(max_concurrent: int, *, max_waiting: int | None = None, timeout: float | None = None, name: str | None = None, backend: Any = None, ttl: float = 60, on_backend_error: str | None = None, retry_backend_after: float = 1.0)` +- `python_wrap.Bulkhead`: `Bulkhead(max_concurrent: int, *, max_waiting: int | None = None, timeout: float | None = None, name: str | None = None, backend: Any = None, ttl: float = 60, slot_idle: float = 0, on_backend_error: str | None = None, retry_backend_after: float = 1.0)` Allow at most `max_concurrent` calls at once; reject when too many are waiting. - `python_wrap.BulkheadFull`: `BulkheadFull(message: str, *, name: str | None, max_concurrent: int)` A bulkhead is at capacity: its wait queue is full, or waiting for a slot timed out. @@ -5210,7 +5210,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm A `RetryBudget` backend that counts requests and retries in Redis. - `python_wrap.shared.SharedBackends`: `SharedBackends(client: Any = None, breaker_state: Any = None, window: Any = None, semaphore: Any = None, budget: Any = None)` The shared stores a preset or policy uses, built from one Redis client. -- `python_wrap.shared.SharedBulkhead`: `SharedBulkhead(max_concurrent: int, *, backend: Any, name: str, max_waiting: int | None = None, timeout: float | None = None, ttl: float = 60, on_backend_error: str | None = None, retry_backend_after: float = 1.0)` +- `python_wrap.shared.SharedBulkhead`: `SharedBulkhead(max_concurrent: int, *, backend: Any, name: str, max_waiting: int | None = None, timeout: float | None = None, ttl: float = 60, slot_idle: float = 0, on_backend_error: str | None = None, retry_backend_after: float = 1.0)` Renewable lease-backed concurrency cap; max_waiting is a per-process queue bound. - `python_wrap.slow` Slow-call detection for synchronous and asynchronous functions. diff --git a/src/python_wrap/bulkhead.py b/src/python_wrap/bulkhead.py index b8a90ba..9122521 100644 --- a/src/python_wrap/bulkhead.py +++ b/src/python_wrap/bulkhead.py @@ -142,6 +142,7 @@ def __init__( name: str | None = None, backend: Any = None, ttl: float = 60, + slot_idle: float = 0, on_backend_error: str | None = None, retry_backend_after: float = 1.0, ) -> None: @@ -153,6 +154,8 @@ def __init__( raise ValueError(f"max_waiting must be >= 0 or None, got {max_waiting}") if timeout is not None and timeout < 0: raise ValueError(f"timeout must be >= 0 or None, got {timeout}") + if backend is None and slot_idle != 0: + raise ValueError("slot_idle requires a shared backend") self._shared: Any = None if backend is not None: if not name: @@ -166,6 +169,7 @@ def __init__( max_waiting=max_waiting, timeout=timeout, ttl=ttl, + slot_idle=slot_idle, on_backend_error=on_backend_error, retry_backend_after=retry_backend_after, ) diff --git a/src/python_wrap/coordination.py b/src/python_wrap/coordination.py index 8f70e78..2767417 100644 --- a/src/python_wrap/coordination.py +++ b/src/python_wrap/coordination.py @@ -413,6 +413,7 @@ class _Renewer: def __init__(self) -> None: self._lock = _fork.ForkSafeLock() self._heap: list[tuple[float, int, Lease]] = [] + self._callbacks: list[tuple[float, int, Callable[[], None]]] = [] self._seq = 0 self._dead = 0 self._thread: threading.Thread | None = None @@ -421,6 +422,7 @@ def __init__(self) -> None: def _reset_after_fork(self) -> None: self._lock = _fork.ForkSafeLock() self._heap = [] + self._callbacks = [] self._seq = self._dead = 0 self._thread = None self._wake = threading.Event() @@ -465,10 +467,26 @@ def discard(self, lease: Lease) -> None: heapq.heapify(live) self._heap, self._dead = live, 0 - def _next(self) -> tuple[Lease | None, float]: + def at(self, deadline: float, callback: Callable[[], None]) -> None: + """Run a lease cleanup on the existing renewal thread.""" + with self._lock: + self._seq += 1 + heapq.heappush(self._callbacks, (deadline, self._seq, callback)) + self._wake.set() + + def _next(self) -> tuple[Lease | Callable[[], None] | None, float]: """Pop the next due live lease, or return the seconds to wait for one.""" with self._lock: - while self._heap: + while self._heap or self._callbacks: + if self._callbacks and ( + not self._heap or self._callbacks[0][:2] < self._heap[0][:2] + ): + due, _, callback = self._callbacks[0] + left = due - _core.monotonic() + if left > 0: + return None, left + heapq.heappop(self._callbacks) + return callback, 0.0 due, _, lease = self._heap[0] if lease._renew_done: heapq.heappop(self._heap) @@ -485,10 +503,16 @@ def _next(self) -> tuple[Lease | None, float]: def _run(self) -> None: while True: + self._wake.clear() lease, wait = self._next() if lease is None: self._wake.wait(wait) - self._wake.clear() + continue + if not isinstance(lease, Lease): + try: + lease() + except BaseException: + logging.getLogger("python_wrap").exception("lease cleanup failed") continue # Renewal runs outside the heap lock: a slow store call must not block add/discard. try: @@ -628,7 +652,11 @@ def _renew(self) -> None: async def _try_async(self) -> bool: try: - return bool(await self.backend.acquire(self.key, self.token, self.ttl, self.limit)) + started = _core.monotonic() + acquired = bool(await self.backend.acquire(self.key, self.token, self.ttl, self.limit)) + if acquired: + self._deadline = started + self.ttl + return acquired except BaseException: try: await self.backend.release(self.key, self.token) @@ -638,7 +666,12 @@ async def _try_async(self) -> bool: async def _renew_async(self) -> None: try: - self.lost = self.lost or not await self.backend.renew(self.key, self.token, self.ttl) + started = _core.monotonic() + self.lost = self.lost or started > self._deadline + if not self.lost: + self.lost = not await self.backend.renew(self.key, self.token, self.ttl) + if not self.lost: + self._deadline = started + self.ttl except Exception: self.lost = True diff --git a/src/python_wrap/shared.py b/src/python_wrap/shared.py index 730f66d..c82199d 100644 --- a/src/python_wrap/shared.py +++ b/src/python_wrap/shared.py @@ -17,7 +17,7 @@ from python_wrap._backend import BackendMonitor from python_wrap._runtime import name_digest, seconds from python_wrap._scripts import Script -from python_wrap.coordination import AlreadyRunning, Lease +from python_wrap.coordination import _RENEWER, AlreadyRunning, Lease from python_wrap.errors import BulkheadFull __all__ = [ @@ -590,6 +590,7 @@ def __init__( max_waiting: int | None = None, timeout: float | None = None, ttl: float = 60, + slot_idle: float = 0, on_backend_error: str | None = None, retry_backend_after: float = 1.0, ) -> None: @@ -609,6 +610,9 @@ def __init__( self.max_waiting = max_waiting self.timeout = None if timeout is None else seconds(timeout, positive=False) self.ttl = seconds(ttl) + self.slot_idle = seconds(slot_idle, positive=False) + self._idle: dict[Lease, tuple[asyncio.AbstractEventLoop | None, float]] = {} + self._idle_scheduled: set[Lease] = set() self._monitor = BackendMonitor("bulkhead", name, on_backend_error, retry_backend_after) acquire = getattr(backend, "acquire", None) self._async = acquire is not None and _core.is_async(acquire) @@ -622,6 +626,8 @@ def __init__( def _reset_after_fork(self) -> None: self._waiting = self._active = 0 self._stack.set(()) + self._idle.clear() + self._idle_scheduled.clear() @property def waiting(self) -> int: @@ -666,11 +672,79 @@ def _admitted(self, lease: Lease, owner: object) -> None: with self._lock: self._active += 1 + def _take_idle(self, loop: asyncio.AbstractEventLoop | None) -> Lease | None: + if not self.slot_idle: + return None + now = _core.monotonic() + with self._lock: + closed = [ + lease + for lease, (owner_loop, _) in self._idle.items() + if owner_loop is not None and owner_loop.is_closed() + ] + for lease in closed: + del self._idle[lease] + self._idle_scheduled.discard(lease) + for lease, (owner_loop, deadline) in self._idle.items(): + if owner_loop is loop and now < min(deadline, lease._deadline) and not lease.lost: + del self._idle[lease] + return lease + return None + + def _return_idle(self, lease: Lease, loop: asyncio.AbstractEventLoop | None) -> bool: + if not self.slot_idle or lease.lost: + return False + deadline = _core.monotonic() + self.slot_idle + with self._lock: + self._idle[lease] = (loop, deadline) + if lease in self._idle_scheduled: + return True + self._idle_scheduled.add(lease) + self._schedule_idle(lease, loop, deadline) + return True + + def _schedule_idle( + self, lease: Lease, loop: asyncio.AbstractEventLoop | None, deadline: float + ) -> None: + def expire() -> None: + with self._lock: + idle = self._idle.get(lease) + if idle is None: + self._idle_scheduled.discard(lease) + return + _, due = idle + if due <= _core.monotonic(): + del self._idle[lease] + self._idle_scheduled.discard(lease) + else: + self._schedule_idle(lease, loop, due) + return + if loop is None: + try: + lease.__exit__(None, None, None) + except Exception as error: + self._monitor.failed(error, "release") + else: + loop.create_task(self._expire_async(lease)) + + if loop is None: + _RENEWER.at(deadline, expire) + else: + loop.call_later(max(deadline - _core.monotonic(), 0.0), expire) + + async def _expire_async(self, lease: Lease) -> None: + try: + await lease.__aexit__(None, None, None) + except Exception as error: + self._monitor.failed(error, "release") + def acquire(self) -> None: if self._async: raise TypeError( "this bulkhead's backend is async; it protects async def functions only" ) + if (idle := self._take_idle(None)) is not None: + return self._admitted(idle, threading.get_ident()) if self._monitor._skipping(): return self._local_admit(threading.get_ident()) lease = self._lease() @@ -708,7 +782,7 @@ def release(self, typ: Any = None, exc: Any = None, tb: Any = None) -> None: raise RuntimeError("shared bulkhead must be released in its acquiring thread") self._stack.set(stack[:-1]) try: - if lease is not None: + if lease is not None and not self._return_idle(lease, None): try: lease.__exit__(typ, exc, tb) except Exception as error: @@ -720,6 +794,8 @@ def release(self, typ: Any = None, exc: Any = None, tb: Any = None) -> None: self._active -= 1 async def acquire_async(self) -> None: + if (idle := self._take_idle(asyncio.get_running_loop())) is not None: + return self._admitted(idle, asyncio.current_task()) if self._monitor._skipping(): return self._local_admit(asyncio.current_task()) lease = self._lease() @@ -757,7 +833,7 @@ async def release_async(self, typ: Any = None, exc: Any = None, tb: Any = None) raise RuntimeError("shared bulkhead must be released in its acquiring task") self._stack.set(stack[:-1]) try: - if lease is not None: + if lease is not None and not self._return_idle(lease, asyncio.get_running_loop()): try: await lease.__aexit__(typ, exc, tb) except Exception as error: diff --git a/tests/test_bulkhead.py b/tests/test_bulkhead.py index aa838eb..0a1d15d 100644 --- a/tests/test_bulkhead.py +++ b/tests/test_bulkhead.py @@ -433,3 +433,46 @@ def make(cls, x: int) -> tuple[type, int]: assert Pool.make(2) == (Pool, 2) assert Pool().make(3) == (Pool, 3) assert Pool.make.bulkhead.max_concurrent == 1 + + +def test_shared_slot_idle_reuses_then_releases() -> None: + from python_wrap.coordination import LocalLease + + class CountedLease(LocalLease): + acquisitions = 0 + released = threading.Event() + + def acquire(self, key: str, token: str, ttl: float, limit: int = 1) -> bool: + self.acquisitions += 1 + return super().acquire(key, token, ttl, limit) + + def release(self, key: str, token: str) -> bool: + released = super().release(key, token) + self.released.set() + return released + + backend = CountedLease() + bulkhead = Bulkhead(1, backend=backend, name="idle-sync", slot_idle=0.1) + for _ in range(10): + with bulkhead: + assert bulkhead.active == 1 + assert backend.acquisitions == 1 + assert backend.released.wait(2) + assert not backend.held("idle-sync") + + +@pytest.mark.asyncio +async def test_async_shared_slot_idle_reuses_then_releases() -> None: + from python_wrap.coordination import LocalLease + + backend = LocalLease() + bulkhead = Bulkhead(1, backend=backend, name="idle-async", slot_idle=0.1) + async with bulkhead: + assert backend.held("idle-async") + async with bulkhead: + assert backend.held("idle-async") + for _ in range(100): + if not backend.held("idle-async"): + break + await asyncio.sleep(0.01) + assert not backend.held("idle-async") From c95d3f938cdbd87d78542c65cd175e96bf5360c0 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Thu, 3 Dec 2026 07:49:42 +0200 Subject: [PATCH 23/38] Preserve Celery retry allowance while waiting for a lease --- CHANGELOG.md | 2 ++ RELEASING.md | 7 +++++ docs/cookbook/framework-integrations.md | 3 ++- src/python_wrap/celery.py | 28 ++++++++++++++++--- tests/test_async_shared.py | 3 ++- tests/test_celery_real_worker.py | 36 +++++++++++++++++++++++++ 6 files changed, 74 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b9bea3..7e91281 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration. ### Fixed +- Celery deliveries waiting on an idempotency lease preserve the task retry counter. + - Shared caches batch tag reads and recreate missing version tokens so deleting a tag key cannot revive an old entry. - HTTP policies honor a host's 429 pause without requiring a configured limiter. diff --git a/RELEASING.md b/RELEASING.md index f88094f..78d771d 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -27,6 +27,13 @@ was removed; revoke the token it used at None: ... default, with a `FutureWarning`; it becomes `"delivery"` in 0.5.0). `key=` overrides both. A delivery that finds the task running is re-queued after about `requeue_delay` seconds (with jitter); those re-queues are counted in the message headers and do not use the task's own - `max_retries`. After `requeue_limit` of them (default enough for a crashed owner's lease to + `max_retries` by default. An explicit `max_retries=` uses Celery's standard retry counting. + After `requeue_limit` of them (default enough for a crashed owner's lease to expire) the call raises `AlreadyRunning`. Use a shared store for a fleet. The lease is `lease_ttl=60` seconds by default and renewed while the body runs, so a crashed owner frees it quickly. diff --git a/src/python_wrap/celery.py b/src/python_wrap/celery.py index de41a45..f8bc980 100644 --- a/src/python_wrap/celery.py +++ b/src/python_wrap/celery.py @@ -495,6 +495,27 @@ def _requeues(task: Any) -> int: return int(_header(getattr(task, "request", None), "x_pw_requeues") or 0) +def _requeue_delivery(task: Any, error: BaseException, countdown: float, count: int) -> Any: + # Celery's Task.retry always increments the delivery's own retry count. + import importlib + + exceptions = importlib.import_module("celery.exceptions") + + request = task.request + if request.called_directly: + raise error + headers = {**(request.headers or {}), "x_pw_requeues": count + 1} + signature = task.signature_from_request( + request, countdown=countdown, retries=request.retries, headers=headers + ) + if not request.is_eager: + try: + signature.apply_async() + except Exception as exc: + raise exceptions.Reject(exc, requeue=False) from exc + return exceptions.Retry(exc=error, when=countdown, is_eager=request.is_eager, sig=signature) + + def idempotent_task( *, key: Any = None, @@ -530,7 +551,7 @@ def idempotent_task( ``key=`` overrides both scopes. Waiting for a running or dead owner does not use the task's own retry allowance: the - re-queue passes ``max_retries=request.retries + 1`` and counts its own re-queues in the + re-queue preserves Celery's retry counter and counts its own re-queues in the ``x_pw_requeues`` header, up to ``requeue_limit`` (default: enough for a crashed owner's lease to expire, ``ceil(lease_ttl / requeue_delay) + 2``). Then `AlreadyRunning` is raised. @@ -548,8 +569,7 @@ def idempotent_task( owner's lease frees after this long. requeue_delay: Base countdown for a delivery that finds the task running (jittered). requeue_limit: Re-queues allowed for one delivery before `AlreadyRunning`. - max_retries: Celery ``max_retries`` for the re-queue. Default: the task's own count - plus one, so the re-queue never exhausts the task's retries. + max_retries: An explicit override uses Celery's standard retry semantics. """ import functools import math @@ -604,6 +624,8 @@ def wrapper(*args: Any, **kwargs: Any) -> Any: countdown = retry_countdown( task, exc, delays=[requeue_delay], jitter=requeue_delay / 2 ) + if max_retries is None and callable(getattr(task, "signature_from_request", None)): + raise _requeue_delivery(task, exc, countdown, count) from None limit = max_retries if max_retries is not None else task.request.retries + 1 raise task.retry( exc=exc, diff --git a/tests/test_async_shared.py b/tests/test_async_shared.py index dc2afc3..64ae656 100644 --- a/tests/test_async_shared.py +++ b/tests/test_async_shared.py @@ -150,12 +150,13 @@ def test_shared_bulkhead_with_async_backend_refuses_sync_acquire() -> None: def test_shared_backends_pick_async_classes_for_an_async_client() -> None: from python_wrap.quotas import AsyncRedisWindow + from python_wrap.shared import AsyncRedisRetryBudget shared = SharedBackends(client=AsyncEval(1)) assert isinstance(shared.breaker(), AsyncRedisBreakerState) assert isinstance(shared.lease_backend(), AsyncRedisSemaphore) assert isinstance(shared.rate_window("x", 1, 1), AsyncRedisWindow) - assert shared.budget_backend("x") is None + assert isinstance(shared.budget_backend("x"), AsyncRedisRetryBudget) def test_idempotent_awaits_an_async_result_store(no_threads: None) -> None: diff --git a/tests/test_celery_real_worker.py b/tests/test_celery_real_worker.py index dafb9cf..c9a835d 100644 --- a/tests/test_celery_real_worker.py +++ b/tests/test_celery_real_worker.py @@ -137,3 +137,39 @@ def once(self, n): again = app.tasks["pw.real.once"].apply_async((4,), task_id="g15-real-same-id") assert first.get(timeout=20) == again.get(timeout=20) == 40 assert runs == [4] + + +def test_waiting_delivery_preserves_task_retry_allowance(app): + import threading + + from celery.signals import task_retry + + from python_wrap.celery import idempotent_task + from python_wrap.coordination import Lease, LocalLease + + backend = LocalLease() + retried = threading.Event() + attempts = [] + + @app.task(name="pw.real.wait", bind=True, shared=False, max_retries=1) + @idempotent_task(scope="delivery", backend=backend, requeue_delay=0.2, requeue_limit=10) + def work(self): + attempts.append(self.request.retries) + if self.request.retries == 0: + raise self.retry(countdown=0, exc=TimeoutError("transient")) + return "done" + + def on_retry(sender, request, **_): + if getattr(sender, "name", None) == "pw.real.wait" and request.retries == 0: + retried.set() + + task_retry.connect(on_retry, weak=False) + try: + with start_worker(app, pool="solo", perform_ping_check=False, shutdown_timeout=20): + with Lease("idem:celery:pw.real.wait:id:waiting", backend=backend, ttl=20): + result = work.apply_async(task_id="waiting") + assert retried.wait(10) + assert result.get(timeout=20) == "done" + finally: + task_retry.disconnect(on_retry) + assert attempts == [0, 1] From a4555354d231d5fdad06008a3085790fef60a455 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Thu, 3 Dec 2026 07:53:40 +0200 Subject: [PATCH 24/38] Keep retry documentation examples executable --- docs/features/resilience/presets-and-doctor.md | 3 ++- docs/features/resilience/retry.md | 10 ++++++++-- docs/llms-full.txt | 3 ++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/features/resilience/presets-and-doctor.md b/docs/features/resilience/presets-and-doctor.md index 733ca13..3cc3c85 100644 --- a/docs/features/resilience/presets-and-doctor.md +++ b/docs/features/resilience/presets-and-doctor.md @@ -99,7 +99,8 @@ from python_wrap import RetryBudget, policy, retry, timeout stack = policy( name="catalog", - retry=retry(max_attempts=3, on=ConnectionError, budget=RetryBudget()), + retry=retry(max_attempts=3, delay=0.1, backoff=2, jitter="equal", + on=ConnectionError, budget=RetryBudget()), timeout=timeout(2), ) report = stack.explain() diff --git a/docs/features/resilience/retry.md b/docs/features/resilience/retry.md index adca138..e2f5a08 100644 --- a/docs/features/resilience/retry.md +++ b/docs/features/resilience/retry.md @@ -288,6 +288,8 @@ use `async with attempt` to await the budget, and inspect it with `await budget. Servers that answer 429 or 503 often say how long to wait. Pass `delay_from` a synchronous function that maps the exception or rejected result to a number of seconds, or to `None` to fall back to the normal backoff. A number is the wait for that attempt, not backoff: the hint is a lower bound, and up to 10% jitter is added so callers rejected together do not return at the same instant. A hint of zero waits 50 ms. Use `min_delay` to raise every hinted wait to a floor, and `hint_jitter=0` to get the exact hint. The wait is still capped by `max_delay` and `max_time`, after the jitter is applied. ```python +from python_wrap import retry, retry_after_header + @retry(delay_from=retry_after_header, hint_jitter=0.1, min_delay=0.05) def fetch(): ... ``` @@ -516,10 +518,14 @@ Sentry breadcrumbs so an error report shows what happened before the failure. Set `max_attempts`, `delay`, `backoff`, `max_delay`, `jitter`, `max_time`, `log_level` and `budget` once for the whole project with `python_wrap.config.configure(retry={...})`. See [Configuration](../configuration.md). -To use the 0.5.0 timing defaults today: +To try the 0.5.0 timing defaults in a scoped block: ```python -configure(retry={"backoff": 2, "jitter": "equal", "max_delay": 30}) +from python_wrap.config import configured + +with configured(retry={"backoff": 2, "jitter": "equal", "max_delay": 30}): + # Decorate functions here to use these defaults. + ... ``` Setting any of `delay`, `backoff` or `jitter` here also silences the default-change warning. diff --git a/docs/llms-full.txt b/docs/llms-full.txt index f67bfcb..1974213 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -3684,7 +3684,8 @@ from python_wrap import RetryBudget, policy, retry, timeout stack = policy( name="catalog", - retry=retry(max_attempts=3, on=ConnectionError, budget=RetryBudget()), + retry=retry(max_attempts=3, delay=0.1, backoff=2, jitter="equal", + on=ConnectionError, budget=RetryBudget()), timeout=timeout(2), ) report = stack.explain() From a4d9bc3af46c243ae035728b832d038d15db2fe7 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Thu, 3 Dec 2026 12:05:42 +0200 Subject: [PATCH 25/38] Verify Celery broker redelivery after worker loss --- .github/workflows/ci.yml | 10 ++- docs/project/stability.md | 2 +- tests/test_celery_real_worker.py | 101 ++++++++++++++++++++++++++++++- 3 files changed, 108 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d264ef4..5428617 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -240,6 +240,14 @@ jobs: # works on one end of the range shows up here. name: Frameworks (${{ matrix.versions.name }}) runs-on: ubuntu-latest + env: + PW_CELERY_REDIS_URL: redis://127.0.0.1:6379/0 + services: + redis: + image: redis:7-alpine + ports: + - 6379:6379 + options: --health-cmd "redis-cli ping" --health-interval 2s --health-timeout 2s --health-retries 15 strategy: fail-fast: false matrix: @@ -264,7 +272,7 @@ jobs: - run: uv sync --group dev --frozen - name: Exercise real framework request/task lifecycles and HTTP clients run: >- - uv run --frozen ${{ matrix.versions.pins }} + uv run --frozen --with redis ${{ matrix.versions.pins }} pytest tests/test_integrations.py tests/test_http.py tests/test_web.py tests/test_celery_helpers.py tests/test_celery_real_worker.py diff --git a/docs/project/stability.md b/docs/project/stability.md index 531015d..d0b1192 100644 --- a/docs/project/stability.md +++ b/docs/project/stability.md @@ -61,7 +61,7 @@ A provisional module graduates when all four hold: | --- | --- | --- | | `shared`, `coordination`, `quotas`, `stores` | 0.5.0 | Live CI in place; storage formats pinned by `tests/test_stability.py`; 1-minute 4-process soak passed, 1-hour soak pending | | `http` | 0.5.0 | CI against the real requests and httpx packages; soak pending | -| `celery` | 0.5.0 | CI against the real Celery package; real-worker tests run an embedded worker on an in-memory broker; soak pending | +| `celery` | 0.5.0 | CI against the real Celery package; real-worker tests check propagation on an in-memory broker and worker loss on Redis; soak pending | | `async_cache`, `web`, `exporters`, `observability` | 0.6.0 | Changed in 0.4.0b2 | The storage formats of the backends above are already frozen: a change to them fails the diff --git a/tests/test_celery_real_worker.py b/tests/test_celery_real_worker.py index c9a835d..ebd4e3b 100644 --- a/tests/test_celery_real_worker.py +++ b/tests/test_celery_real_worker.py @@ -2,7 +2,7 @@ Runs an embedded worker thread (``celery.contrib.testing.worker.start_worker``, solo pool) against an in-memory broker and result backend, so headers travel through the real -message path. Skipped when Celery is not installed (CI installs it in the framework job). +message path. With PW_CELERY_REDIS_URL set, also checks redelivery after a prefork crash. """ from __future__ import annotations @@ -120,8 +120,6 @@ def test_explicit_header_is_not_overwritten(app): def test_task_delivered_twice_runs_once_with_delivery_scope(app): - # The killed-worker redelivery is not reproducible in-process, so this checks the part - # that is: two messages carrying one task id run the body once under scope="delivery". from python_wrap.celery import idempotent_task runs: list[int] = [] @@ -173,3 +171,100 @@ def on_retry(sender, request, **_): finally: task_retry.disconnect(on_retry) assert attempts == [0, 1] + + +def _crash_worker_app(url, namespace): + import json + import os + + import redis + + from python_wrap import RedisStore + from python_wrap.celery import idempotent_task + + client = redis.Redis.from_url(url) + attempts = f"{namespace}:attempts" + worker_app = celery.Celery(namespace, broker=url, backend=url) + worker_app.conf.update( + task_default_queue=namespace, + worker_hijack_root_logger=False, + worker_lost_wait=0.5, + ) + + @worker_app.task( + name=f"{namespace}.work", + bind=True, + shared=False, + acks_late=True, + reject_on_worker_lost=True, + ) + @idempotent_task( + scope="delivery", + store=RedisStore( + client, + f"{namespace}:results:", + dumps=json.dumps, + loads=json.loads, + on_backend_error="raise", + ), + lease_ttl=2, + requeue_delay=0.2, + requeue_limit=20, + ) + def work(self): + if client.incr(attempts) == 1: + os._exit(17) + return {"attempts": int(client.get(attempts)), "retries": self.request.retries} + + return worker_app, client + + +def test_worker_loss_redelivers_after_lease_expiration(tmp_path): + import os + import subprocess + import sys + import uuid + from pathlib import Path + + url = os.environ.get("PW_CELERY_REDIS_URL") + if not url: + pytest.skip("set PW_CELERY_REDIS_URL to exercise Redis broker redelivery") + pytest.importorskip("redis") + namespace = f"pw-test:{uuid.uuid4().hex}" + app, client = _crash_worker_app(url, namespace) + log = tmp_path / "worker.log" + with log.open("w") as output: + worker = subprocess.Popen( + [ + sys.executable, + "-c", + ( + "import os, sys, billiard; billiard.set_start_method('fork', force=True); " + "from test_celery_real_worker import _crash_worker_app; " + "app, _ = _crash_worker_app(os.environ['PW_CELERY_REDIS_URL'], sys.argv[1]); " + "app.worker_main(['worker', '--pool=prefork', '--concurrency=1', " + "'--without-gossip', '--without-mingle', '--without-heartbeat'])" + ), + namespace, + ], + cwd=Path(__file__).parent, + stdout=output, + stderr=subprocess.STDOUT, + ) + try: + result = app.tasks[f"{namespace}.work"].delay() + assert result.get(timeout=40) == {"attempts": 2, "retries": 0} + except Exception as exc: + pytest.fail(f"{exc!r}\n{log.read_text()}") + finally: + worker.terminate() + try: + worker.wait(timeout=10) + except subprocess.TimeoutExpired: + worker.kill() + worker.wait() + keys = list(client.scan_iter(match=f"{namespace}:*")) + if keys: + client.delete(*keys) + app.close() + client.close() From 2d67d4b9e094383b02c92637ca38ff9e85124bc6 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Thu, 3 Dec 2026 12:07:14 +0200 Subject: [PATCH 26/38] Exercise shared retry budgets and bulkheads in Redis soak --- benchmarks/soak.py | 86 ++++++++++++++++++++++++++++++------- docs/project/performance.md | 4 ++ 2 files changed, 75 insertions(+), 15 deletions(-) diff --git a/benchmarks/soak.py b/benchmarks/soak.py index 4b69388..d01a0cf 100644 --- a/benchmarks/soak.py +++ b/benchmarks/soak.py @@ -7,15 +7,15 @@ * check a policy before a production pilot (are retries capped during an outage? does the breaker open and recover?), and -* catch leaks: run it for minutes with ``--duration`` and compare ``rss_growth_kb``. +* catch leaks: run it for minutes with ``--duration`` and compare ``traced_memory_growth_kb``. python benchmarks/soak.py # 20 s, 16 threads python benchmarks/soak.py --duration 600 --threads 64 --json > soak.json python benchmarks/soak.py --processes 4 --redis-url redis://localhost:6379/0 With ``--processes N --redis-url URL`` every process shares one Redis circuit breaker and -one Redis rate limiter (``--limit`` calls per second across all processes) and the report -adds up the processes. That mode needs the ``redis`` package. +one Redis rate limiter and retry budget. Pass ``--bulkhead N`` to share concurrency +slots and check for retained slots after shutdown. That mode needs the ``redis`` package. Standard library only. Real time is used (not ``fake_clock``): this is a soak, not a test. """ @@ -29,6 +29,7 @@ import threading import time import tracemalloc +from concurrent.futures import ThreadPoolExecutor from pathlib import Path from typing import Any @@ -38,7 +39,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src")) from python_wrap import CircuitBreaker, CircuitOpenError, RetryBudget, policy, retry, timeout -from python_wrap.errors import RateLimitExceeded +from python_wrap.errors import BulkheadFull, RateLimitExceeded, TimeoutExpired from python_wrap.retry import attempt_history @@ -85,6 +86,7 @@ def run( redis_url: str | None = None, limit: int = 1000, run_id: str = "local", + bulkhead: int | None = None, ) -> dict[str, Any]: dependency = FlakyDependency(period, seed) budget = RetryBudget(ratio=0.2, min_per_second=5) @@ -93,14 +95,26 @@ def run( if redis_url is not None: import redis + from python_wrap import Bulkhead, RedisSemaphore from python_wrap.concurrency import RateLimiter from python_wrap.quotas import RedisWindow - from python_wrap.shared import RedisBreakerState + from python_wrap.shared import RedisBreakerState, RedisRetryBudget client = redis.Redis.from_url(redis_url) backend = RedisBreakerState(client, prefix=f"python-wrap:soak:{run_id}:") window = RedisWindow(client, f"python-wrap:soak:{run_id}:limit", calls=limit, period=1) layers["limiter"] = RateLimiter(calls=limit, period=1, backend=window) + budget = RetryBudget( + ratio=0.2, min_per_second=5, backend=RedisRetryBudget(client, f"soak:{run_id}") + ) + if bulkhead is not None: + layers["bulkhead"] = Bulkhead( + bulkhead, + name=f"soak:{run_id}", + backend=RedisSemaphore(client), + timeout=0.05, + ttl=10, + ) breaker = CircuitBreaker( failure_threshold=10, recovery_timeout=1.0, name="soak", backend=backend ) @@ -112,7 +126,16 @@ def run( **layers, )(dependency) - stats = {"calls": 0, "ok": 0, "gave_up": 0, "rejected": 0, "limited": 0, "attempts": 0} + stats = { + "calls": 0, + "ok": 0, + "gave_up": 0, + "rejected": 0, + "limited": 0, + "bulkhead_rejected": 0, + "timed_out": 0, + "attempts": 0, + } latencies: list[float] = [] lock = threading.Lock() stop = time.monotonic() + duration @@ -127,6 +150,10 @@ def worker() -> None: outcome, attempts = "rejected", 0 except RateLimitExceeded: outcome, attempts = "limited", 0 + except BulkheadFull: + outcome, attempts = "bulkhead_rejected", 0 + except TimeoutExpired: + outcome, attempts = "timed_out", 0 except ConnectionError as exc: outcome, attempts = "gave_up", len(attempt_history(exc)) or 1 elapsed = time.perf_counter() - began @@ -136,16 +163,15 @@ def worker() -> None: stats["attempts"] += attempts if len(latencies) < 200_000: latencies.append(elapsed) - if outcome in ("rejected", "limited"): + if outcome in ("rejected", "limited", "bulkhead_rejected"): time.sleep(0.005) tracemalloc.start() baseline = tracemalloc.get_traced_memory()[0] - pool = [threading.Thread(target=worker, daemon=True) for _ in range(threads)] - for thread in pool: - thread.start() - for thread in pool: - thread.join() + with ThreadPoolExecutor(max_workers=threads) as pool: + jobs = [pool.submit(worker) for _ in range(threads)] + for job in jobs: + job.result() current, peak = tracemalloc.get_traced_memory() tracemalloc.stop() calls = max(stats["calls"], 1) @@ -192,11 +218,31 @@ def run_processes(processes: int, redis_url: str, limit: int, **options: Any) -> reports = pool.map(_run_one, jobs) total = { key: sum(r[key] for r in reports) - for key in ("calls", "ok", "gave_up", "rejected", "limited", "attempts", "dependency_calls") + for key in ( + "calls", + "ok", + "gave_up", + "rejected", + "limited", + "bulkhead_rejected", + "timed_out", + "attempts", + "dependency_calls", + ) } + slots_held = False + if options.get("bulkhead") is not None: + import redis + + from python_wrap import RedisSemaphore + + with redis.Redis.from_url(redis_url) as client: + slots_held = RedisSemaphore(client).held(f"soak:{run_id}") calls = max(total["calls"], 1) return { "processes": processes, + "duration_s": options["duration"], + "bulkhead_slots_held_after": slots_held, **total, "amplification": round(total["dependency_calls"] / calls, 3), "admitted_per_second": round((calls - total["limited"]) / options["duration"], 1), @@ -215,18 +261,28 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument("--seed", type=int, default=7) parser.add_argument("--json", action="store_true", help="print only the JSON report") parser.add_argument("--processes", type=int, default=1, help="processes (needs --redis-url)") - parser.add_argument("--redis-url", default=None, help="share breaker and limiter in Redis") + parser.add_argument( + "--redis-url", default=None, help="share breaker, limiter, and retry budget in Redis" + ) parser.add_argument("--limit", type=int, default=1000, help="shared calls per second") + parser.add_argument("--bulkhead", type=int, default=None, help="shared concurrency slots") args = parser.parse_args(argv) + if args.bulkhead is not None and ( + args.bulkhead < 1 or not args.redis_url or args.processes < 2 + ): + parser.error("--bulkhead needs a positive slot count, --redis-url, and --processes >= 2") if args.processes > 1: if not args.redis_url: parser.error("--processes needs --redis-url") report = run_processes( args.processes, args.redis_url, args.limit, duration=args.duration, threads=args.threads, period=args.period, seed=args.seed, + bulkhead=args.bulkhead, ) # fmt: skip print(json.dumps(report, indent=2, default=str)) - return 0 if report["amplification"] <= 2.0 else 1 + return ( + 0 if report["amplification"] <= 2.0 and not report["bulkhead_slots_held_after"] else 1 + ) report = run(args.duration, args.threads, args.period, args.seed, args.redis_url, args.limit) if not args.json: print(f"soak: {args.duration:g}s, {args.threads} threads, phase {args.period:g}s") diff --git a/docs/project/performance.md b/docs/project/performance.md index 5ff175a..44b6cbe 100644 --- a/docs/project/performance.md +++ b/docs/project/performance.md @@ -94,6 +94,10 @@ bulkhead pays two lease round trips plus starting its lease-renewal thread on ev call; prefer it for calls that take far longer than that. Measure where your service runs: these numbers are mostly the network round trip. +For a one-hour run with the shared retry budget and bulkhead enabled, use +`python benchmarks/soak.py --processes 2 --threads 8 --duration 3600 --limit 100 --bulkhead 4 --redis-url ...`. +The JSON report includes the call outcomes and a check for slots left held after the run. + A 60-second soak with 4 processes x 8 threads sharing one Redis breaker and a 2,000 calls/s limiter (`python benchmarks/soak.py --processes 4 --threads 8 --duration 60 --limit 2000 --redis-url ...`) admitted 1,996 calls/s across all processes, sent 0.36 From 29aaab71c18c961a1ec95b8a26e4bffa2bb2ec14 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Thu, 3 Dec 2026 20:25:10 +0200 Subject: [PATCH 27/38] Close 0.4.2 release verification gaps --- .github/workflows/ci.yml | 18 +++- .github/workflows/release.yml | 4 + CHANGELOG.md | 38 ++++----- docs/features/ai/langchain.md | 6 +- docs/features/concurrency/shared-limits.md | 5 +- src/python_wrap/__init__.py | 2 +- src/python_wrap/_backend.py | 10 ++- src/python_wrap/adapters/langchain.py | 8 ++ tests/test_backend_errors.py | 3 +- tests/test_langchain_providers.py | 89 ++++++++++++++++++++ tests/test_sql_backends_live.py | 98 +++++++++++++++++++++- 11 files changed, 252 insertions(+), 29 deletions(-) create mode 100644 tests/test_langchain_providers.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5428617..2fbb74f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,7 +13,7 @@ name: CI on: push: - branches: [main, 'fix/**'] + branches: [main, 'fix/**', 'release/**'] pull_request: workflow_dispatch: @@ -279,6 +279,20 @@ jobs: - name: Prefork workers keep a policy watch alive after os.fork run: uv run --frozen python scripts/prefork_check.py + - name: LangChain provider contracts + if: matrix.versions.name == 'latest' + run: >- + uv run --frozen --with langchain-openai --with langchain-anthropic + pytest tests/test_langchain_adapter.py tests/test_langchain_providers.py + + - name: LangChain minimum core contracts + if: matrix.versions.name == 'oldest' + env: + PYTEST_DISABLE_PLUGIN_AUTOLOAD: "1" + run: >- + uv run --frozen --no-default-groups --group core-test --with 'langchain-core==0.3.0' + pytest tests/test_langchain_adapter.py + sql-backends: # PgAdvisoryLock, SqlAppLock and the transient-error predicates against real servers. name: PostgreSQL and SQL Server backends @@ -321,7 +335,7 @@ jobs: exit 1 - name: Live SQL backend tests run: >- - uv run --frozen --with 'sqlalchemy>=2' --with 'psycopg[binary]>=3.1' + uv run --frozen --with 'sqlalchemy[asyncio]>=2' --with aiosqlite --with 'psycopg[binary]>=3.1' --with 'pymssql>=2.3' pytest tests/test_sql_backends_live.py tests/test_transient_predicates.py tests/test_sql_result_store.py - name: Install the Microsoft ODBC driver for SQL Server diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7bc8460..976e806 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -69,6 +69,10 @@ jobs: fi fi + - name: Check changelog and stability metadata + if: github.ref_type == 'tag' + run: uv run --frozen --no-sync python scripts/check_release.py --tag + - name: Install Redis for the release integration gate run: sudo apt-get update && sudo apt-get install -y redis-server diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e91281..16d413b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,19 @@ Breaking changes are listed under **Breaking changes**, each with its migration. ## [Unreleased] +### Security + +- Shared SQLite token windows now sample time after taking the writer lock and keep stored + timestamps from moving backward, preventing delayed transactions or clock rollback from + granting extra refill. Tagged cache invalidation now weakly tracks Redis clients (or their + cache stores when a client cannot be weakly referenced), so abandoned closed clients do not + stay alive and disrupt later invalidations. A synchronous shutdown callback that times out + exhausts the remaining finite drain budget before another callback can start. + ### Added +- `python_wrap._runtime.cache_key_of(value)` exposes stable key encoding for application checks. +- The key encoder accepts subclasses of builtin types, named tuples and `__cache_key__()`. - Shared bulkheads can opt into brief lease reuse with `slot_idle=`. - LangChain guards compose as runnables, preserve guards on bindings, and cover embeddings. @@ -31,6 +42,12 @@ Breaking changes are listed under **Breaking changes**, each with its migration. - HTTP policies cap cached host state with `max_hosts` (default 1000), accept limiter and bulkhead mappings, and share 429 pauses through Redis. +### Deprecated + +- Implicit shared backend error handling warns that the default switches from `"raise"` + to `"local"` in 0.5.0. Set `on_backend_error=` or `configure(backend_errors=...)` + to pin the desired mode. The 0.4.x behavior stays the same. + ### Fixed - Celery deliveries waiting on an idempotency lease preserve the task retry counter. @@ -39,20 +56,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration. a tag key cannot revive an old entry. - HTTP policies honor a host's 429 pause without requiring a configured limiter. - Failed transactional idempotent calls remove their own unfinished claim. -- LangChain transport models with `max_retries=None` are rebuilt with retries disabled. - -## [0.4.1] - unreleased - -### Security - -- Shared SQLite token windows now sample time after taking the writer lock and keep stored - timestamps from moving backward, preventing delayed transactions or clock rollback from - granting extra refill. Tagged cache invalidation now weakly tracks Redis clients (or their - cache stores when a client cannot be weakly referenced), so abandoned closed clients do not - 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 +- Rebuilding LangChain provider models drops the original SDK clients so their retries + are disabled while preserving the API settings and HTTP transports. - 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 @@ -63,11 +68,6 @@ Breaking changes are listed under **Breaking changes**, each with its migration. - Half-open circuit rejections carry a positive `retry_after` (local: `min(max(recovery_timeout, 0.05), 1.0)`; shared: time to the trial deadline, at least 50 ms). - Every hinted wait (`Retry-After`, breaker hints, retry countdowns) gets up to 10% jitter on top and a 50 ms floor when the hint is 0. Exact hinted waits in tests change accordingly. -### Added - -- `python_wrap._runtime.cache_key_of(value)` public helper. -- The key encoder accepts subclasses of `str`, `int`, `float`, `bytes`, `tuple`, `list`, `dict` and `set`; named tuples (class-tagged); and an application hook `__cache_key__()`. - ## [0.4.0] - 2026-11-26 ### Breaking changes diff --git a/docs/features/ai/langchain.md b/docs/features/ai/langchain.md index 62d24a9..0c75324 100644 --- a/docs/features/ai/langchain.md +++ b/docs/features/ai/langchain.md @@ -132,5 +132,7 @@ unless you run several chains and need to tell them apart. ## Testing -The adapter is tested against langchain-core's real `BaseChatModel`. Two 429 responses -followed by a success make three provider calls, and the budget is charged once. +Tests exercise the oldest supported `langchain-core` and the current provider integrations. +The `ChatOpenAI` and `ChatAnthropic` tests stub HTTP at the transport and verify that +rebuilding preserves credentials and the endpoint. Two 429 responses followed by a success +make three requests through a tool-bound model and charge the budget once. diff --git a/docs/features/concurrency/shared-limits.md b/docs/features/concurrency/shared-limits.md index 112b44c..48535f2 100644 --- a/docs/features/concurrency/shared-limits.md +++ b/docs/features/concurrency/shared-limits.md @@ -168,10 +168,13 @@ Every shared backend takes the same option, `on_backend_error`: | Value | Effect | |---|---| -| `"raise"` (default) | The store error propagates. | +| `"raise"` (0.4.x default) | The store error propagates. | | `"local"` | Use this process's own breaker, window, quota or bulkhead cap until the store answers. | | `"allow"` | Admit the call and skip accounting. | +The shared backend default changes from `"raise"` to `"local"` in 0.5.0. Set the mode +explicitly on the backend or in `configure(backend_errors=...)` to pin it across releases. + Caches take `on_backend_error` too: `"allow"` (a miss, writes dropped) is their default, and `"local"` behaves like `"allow"`. Token windows default to `"local"`. Leases (`Lease(..., on_backend_error="allow")`) enter without the lease and set `degraded`; memoize diff --git a/src/python_wrap/__init__.py b/src/python_wrap/__init__.py index afbce89..9404ed4 100644 --- a/src/python_wrap/__init__.py +++ b/src/python_wrap/__init__.py @@ -281,7 +281,7 @@ validate_args, ) -__version__ = "0.4.1" +__version__ = "0.4.2" # A library must never configure logging; this only silences "no handler" warnings. logging.getLogger("python_wrap").addHandler(logging.NullHandler()) diff --git a/src/python_wrap/_backend.py b/src/python_wrap/_backend.py index f7dd583..b9d33ed 100644 --- a/src/python_wrap/_backend.py +++ b/src/python_wrap/_backend.py @@ -10,6 +10,7 @@ from __future__ import annotations import time +import warnings from collections.abc import Awaitable, Callable from typing import Any, TypeVar @@ -48,8 +49,6 @@ def resolve_mode(on_backend_error: str | None, fail_open: Any, owner: str, defau Call it directly from the constructor so the warning points at the caller. """ if fail_open is not _NOT_GIVEN: - import warnings - warnings.warn( f"{owner}(fail_open=) is deprecated and is removed in 0.6.0; " "pass on_backend_error='allow' or on_backend_error='raise' instead", @@ -81,6 +80,13 @@ def __init__( raise ValueError(f"on_backend_error must be one of {BACKEND_ERROR_MODES}") if retry_backend_after < 0: raise ValueError("retry_backend_after must be >= 0") + if on_backend_error is None and _project_default is None: + warnings.warn( + "the shared backend error default changes from 'raise' to 'local' in 0.5.0; " + "pass on_backend_error= or configure(backend_errors=...) to pick a mode", + FutureWarning, + stacklevel=1, + ) self.kind, self.name = kind, name self._mode = on_backend_error self.retry_backend_after = retry_backend_after diff --git a/src/python_wrap/adapters/langchain.py b/src/python_wrap/adapters/langchain.py index cc6f03c..ebf28b4 100644 --- a/src/python_wrap/adapters/langchain.py +++ b/src/python_wrap/adapters/langchain.py @@ -62,6 +62,14 @@ def without_retries(model: Any) -> Any: if getattr(model, "max_retries", 0) == 0: return model fields = {name: getattr(model, name) for name in getattr(model, "model_fields_set", ())} + # Some provider validators add their SDK clients to model_fields_set. Reusing those + # clients would keep the old retry settings. Keep the underlying HTTP transports. + if any( + cls.__module__.split(".")[0] in {"langchain_openai", "langchain_anthropic"} + for cls in type(model).__mro__ + ): + for name in ("client", "async_client", "root_client", "root_async_client"): + fields.pop(name, None) try: return type(model)(**{**fields, "max_retries": 0}) except Exception as exc: diff --git a/tests/test_backend_errors.py b/tests/test_backend_errors.py index 84433eb..6793c99 100644 --- a/tests/test_backend_errors.py +++ b/tests/test_backend_errors.py @@ -36,7 +36,8 @@ def call() -> int: def test_raise_is_the_default_and_configure_changes_it() -> None: - breaker = CircuitBreaker(name="g1-raise", backend=RedisBreakerState(Dead())) + with pytest.warns(FutureWarning, match="from 'raise' to 'local' in 0.5.0"): + breaker = CircuitBreaker(name="g1-raise", backend=RedisBreakerState(Dead())) with pytest.raises(ConnectionError): breaker.call(lambda: 1) with configured(backend_errors="allow"): diff --git a/tests/test_langchain_providers.py b/tests/test_langchain_providers.py new file mode 100644 index 0000000..f2dc337 --- /dev/null +++ b/tests/test_langchain_providers.py @@ -0,0 +1,89 @@ +"""The real provider models keep their configuration when rebuilt without SDK retries.""" + +from __future__ import annotations + +from importlib import import_module + +import pytest + +from python_wrap.adapters.langchain import PythonWrapCallback, guard_chat_model +from python_wrap.events import listening +from python_wrap.llm import Budget +from python_wrap.testing import fake_clock + +pytestmark = pytest.mark.sdk + + +@pytest.mark.parametrize("provider", ["openai", "anthropic"]) +def test_bound_provider_retries_and_charges_once(provider): + integration = pytest.importorskip(f"langchain_{provider}") + model_type = integration.ChatOpenAI if provider == "openai" else integration.ChatAnthropic + sdk = import_module(provider) + http = import_module( + next( + cls.__module__.split(".")[0] + for cls in sdk.DefaultHttpxClient.__mro__ + if cls.__module__.startswith(("httpx.", "httpx2.")) + ) + ) + requests = [] + + def respond(request): + requests.append(request) + if len(requests) <= 2: + return http.Response(429, json={"error": {"message": "slow down"}}) + if provider == "openai": + return http.Response( + 200, + json={ + "id": "chatcmpl-test", + "object": "chat.completion", + "model": "gpt-4o-mini", + "choices": [{"index": 0, "message": {"role": "assistant", "content": "done"}}], + "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}, + }, + ) + return http.Response( + 200, + json={ + "id": "msg_test", + "type": "message", + "role": "assistant", + "model": "claude-sonnet-4-6", + "content": [{"type": "text", "text": "done"}], + "stop_reason": "end_turn", + "usage": {"input_tokens": 10, "output_tokens": 5}, + }, + ) + + def lookup(city: str) -> str: + """Look up a city.""" + return city + + with http.Client(transport=http.MockTransport(respond)) as client: + model = model_type( + model="gpt-4o-mini" if provider == "openai" else "claude-sonnet-4-6", + api_key="test-key", + base_url="https://provider.test", + http_client=client, + max_retries=None if provider == "openai" else 2, + ) + budget = Budget(tokens=1000) + guarded = guard_chat_model(model, budget=budget, attempts=3, retry={"delay": 0}) + events = [] + with fake_clock(), listening(events.append): + result = guarded.bind_tools([lookup]).invoke( + "hello", config={"callbacks": [PythonWrapCallback(budget=budget)]} + ) + + assert result.usage_metadata["total_tokens"] == 15 + assert guarded.model.max_retries == 0 + assert len(requests) == 3 + assert sum(event.name == "retry.attempt_failed" for event in events) == 2 + assert all(request.url.host == "provider.test" for request in requests) + for request in requests: + if provider == "anthropic" and "x-api-key" in request.headers: + assert request.headers["x-api-key"] == "test-key" + else: + assert request.headers["authorization"] == "Bearer test-key" + assert budget.spent().tokens == 15 diff --git a/tests/test_sql_backends_live.py b/tests/test_sql_backends_live.py index 5601c10..d21c84c 100644 --- a/tests/test_sql_backends_live.py +++ b/tests/test_sql_backends_live.py @@ -103,6 +103,32 @@ def job() -> str: assert job() == "done" and runs == [1] +@pytest.mark.skipif(not hasattr(os, "fork"), reason="POSIX fork only") +def test_sql_lock_backend_rebinds_after_fork(lock_backend): + import multiprocessing + + backend, _ = lock_backend + key = f"fork-{uuid.uuid4().hex}" + assert backend.acquire(key, "parent", 30) + + def use_in_child(): + assert not backend.acquire(key, "child", 30) + assert backend.acquire(key + "-child", "child", 30) + assert backend.release(key + "-child", "child") + + child = multiprocessing.get_context("fork").Process(target=use_in_child) + child.start() + try: + child.join(timeout=10) + assert child.exitcode == 0 + finally: + if child.is_alive(): + child.kill() + child.join(timeout=5) + child.close() + assert backend.release(key, "parent") + + def test_postgres_errors_are_classified(pg_engine): sqlalchemy = pytest.importorskip("sqlalchemy") table = f"pw_live_{uuid.uuid4().hex[:8]}" @@ -160,7 +186,8 @@ def test_sqlserver_errors_are_classified(mssql_engine): ("mssql", "hash"), ("postgres", "sequential"), ("mssql", "sequential"), - ] + ], + ids=["postgres-hash", "mssql-hash", "postgres-sequential", "mssql-sequential"], ) def result_table(request: Any) -> Iterator[tuple[Any, str, str]]: backend, layout = request.param @@ -203,3 +230,72 @@ def place() -> str: with engine.connect() as conn: assert conn.exec_driver_sql(f"SELECT COUNT(*) FROM {table}_orders").scalar() == 1 assert store.purge_expired() == 0 + + +def test_concurrent_duplicate_returns_committed_result(result_table): + from concurrent.futures import ThreadPoolExecutor, TimeoutError + from threading import Event + + engine, table, _ = result_table + store = SqlResultStore(engine, table) + entered = Event() + calls = [] + + def invoke(conn): + @idempotent(key="concurrent", store=store, connection=lambda: conn) + def work(): + calls.append(1) + return {"calls": len(calls)} + + return work() + + def follow(): + with engine.begin() as conn: + entered.set() + return invoke(conn) + + with ThreadPoolExecutor(max_workers=1) as pool: + with engine.begin() as first: + assert invoke(first) == {"calls": 1} + duplicate = pool.submit(follow) + assert entered.wait(5) + with pytest.raises(TimeoutError): + duplicate.result(timeout=0.1) + assert duplicate.result(timeout=20) == {"calls": 1} + assert calls == [1] + + +@pytest.mark.asyncio +async def test_async_postgres_result_store_uses_database_clock(pg_engine, monkeypatch): + from sqlalchemy.ext.asyncio import create_async_engine + + from python_wrap import _core + + engine = create_async_engine(pg_engine.url) + table = f"pw_idem_async_{uuid.uuid4().hex[:8]}" + store = SqlResultStore(engine, table, clock="database") + calls = [] + try: + async with engine.begin() as conn: + for statement in store.ddl("postgresql", table, layout="sequential"): + await conn.exec_driver_sql(statement) + + def transaction(connection): + @idempotent(key="async", ttl=60, store=store, connection=lambda: connection) + async def work(): + calls.append(1) + return len(calls) + + return work() + + async with engine.begin() as conn: + assert await transaction(conn) == 1 + monkeypatch.setattr(_core, "wall_time", lambda: 10**12) + async with engine.begin() as conn: + assert await transaction(conn) == 1 + assert (await conn.exec_driver_sql(f"SELECT COUNT(*) FROM {table}")).scalar() == 1 + assert calls == [1] + finally: + async with engine.begin() as conn: + await conn.exec_driver_sql(f"DROP TABLE IF EXISTS {table}") + await engine.dispose() From 03573a9babc3a18e163b59b7ea62d8517bc2f2fc Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 4 Dec 2026 05:50:13 +0200 Subject: [PATCH 28/38] Honor shared HTTP pauses and repair release checks --- CHANGELOG.md | 2 ++ RELEASING.md | 9 ++---- docs/features/resilience/http-clients.md | 6 ++-- docs/llms-full.txt | 10 ++++--- scripts/smoke_wheel.py | 2 +- src/python_wrap/http.py | 38 ++++++++++++------------ tests/test_http_policy.py | 10 +++---- tests/test_redis_backends.py | 32 ++++++++++++++++++++ 8 files changed, 70 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 16d413b..f1b026d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration. - Shared caches batch tag reads and recreate missing version tokens so deleting a tag key cannot revive an old entry. - HTTP policies honor a host's 429 pause without requiring a configured limiter. +- Policies read a shared 429 pause before each attempt. Overlapping responses can extend + the pause but cannot shorten it. - Failed transactional idempotent calls remove their own unfinished claim. - Rebuilding LangChain provider models drops the original SDK clients so their retries are disabled while preserving the API settings and HTTP transports. diff --git a/RELEASING.md b/RELEASING.md index 78d771d..283f3db 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -57,13 +57,10 @@ against the patch-release policy before tagging. The default `pytest` run includes the `tests/e2e/` happy-path scenarios. -4. **Merge to `main`**, after the local checks pass. CI and docs run only on pushes - to `main`, so PR updates do not start Actions runs. Wait for both workflows on the - merged commit to pass before creating a release tag. The Redis integration job is +4. **Merge to `main`**, after local checks and release-branch CI pass. Wait for CI and + the docs workflow on the merged commit before creating a release tag. The Redis integration job is required for 0.3.0; the release workflow repeats its real-server gate before any - upload, so a skipped local Redis run cannot approve a publication. If the repository requires - PR status checks, a maintainer must align that rule with this post-merge policy; - new PR commits will not receive CI/docs checks. + upload, so a skipped local Redis run cannot approve a publication. 5. **Rehearse (recommended for a big release).** Tag a pre-release such as `v0.3.0rc1` (after setting `__version__ = "0.3.0rc1"`). Every tagged version is published to TestPyPI and installed back from that index diff --git a/docs/features/resilience/http-clients.md b/docs/features/resilience/http-clients.md index 0228849..afa68bd 100644 --- a/docs/features/resilience/http-clients.md +++ b/docs/features/resilience/http-clients.md @@ -143,9 +143,9 @@ mount_policy(session, policy) factories `name -> object` (a ready-made object is rejected so state is never shared by accident). `max_hosts` defaults to 1000 and bounds remembered host guards and pauses. An evicted host gets fresh local guards on its next request. -- With `shared=` set to a Redis client, policies share 429 pauses and check Redis at - most once per second per remembered host. A store failure leaves the local pause - in effect. Use `limiter={"calls": 50, "period": 1}` and +- With `shared=` set to a Redis client, policies check the shared 429 pause before + each attempt. A shorter `Retry-After` cannot shorten a pause already in Redis. A + store failure leaves the local pause in effect. Use `limiter={"calls": 50, "period": 1}` and `bulkhead={"max_concurrent": 8}` to build guards backed by the same Redis client. - `RetryTransport`, `AsyncRetryTransport` and `mount_retries` stay as thin retry-only wrappers. diff --git a/docs/llms-full.txt b/docs/llms-full.txt index 1974213..14f35b9 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -2153,8 +2153,10 @@ unless you run several chains and need to tell them apart. ### Testing -The adapter is tested against langchain-core's real `BaseChatModel`. Two 429 responses -followed by a success make three provider calls, and the budget is charged once. +Tests exercise the oldest supported `langchain-core` and the current provider integrations. +The `ChatOpenAI` and `ChatAnthropic` tests stub HTTP at the transport and verify that +rebuilding preserves credentials and the endpoint. Two 429 responses followed by a success +make three requests through a tool-bound model and charge the budget once. --- @@ -4434,7 +4436,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm - `python_wrap.WebhookAlerter`: `WebhookAlerter(url: str, *, format: str = 'json', on: Iterable[str | CircuitState] = ('open',), cooldown: float = 300.0, timeout: float = 5.0, sender: Sender | None = None, include_recovery: bool = True, context: Mapping[str, Any] | None = None)` Post a chat message when a circuit breaker reaches a chosen state. - `python_wrap.__version__` - Constant: '0.4.1' + Constant: '0.4.2' - `python_wrap.ainvalidate_tags`: `ainvalidate_tags(*names: str, client: Any = None, require_shared: bool = False) -> int` `invalidate_tags` for ``redis.asyncio`` clients (amemoize with AsyncRedisStore). - `python_wrap.amap_iter`: `amap_iter(fn: Callable[[T], Awaitable[R]], items: Iterable[T] | AsyncIterable[T], *, limit: int, ordered: bool = True, return_exceptions: bool = False) -> AsyncGenerator[Any, None]` @@ -4838,7 +4840,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm - `python_wrap.decorators` Compatibility module: v0.1 imported everything from ``python_wrap.decorators``. - `python_wrap.decorators.__version__` - Constant: '0.4.1' + Constant: '0.4.2' - `python_wrap.devtools` Developer tools: deprecation warnings, mock data and decorator composition. - `python_wrap.django` diff --git a/scripts/smoke_wheel.py b/scripts/smoke_wheel.py index e6b3238..fa74c38 100644 --- a/scripts/smoke_wheel.py +++ b/scripts/smoke_wheel.py @@ -97,7 +97,7 @@ def ask(question): with fake_clock() as clock: assert fetch() == "ok" and len(calls) == 3 assert ask("hello").text == "hi" and provider.call_count == 2 - assert clock.sleeps[-1] == 2.0 + assert 2.0 <= clock.sleeps[-1] <= 2.2 print(f"smoke ok: python-wrap {version}") """ ) diff --git a/src/python_wrap/http.py b/src/python_wrap/http.py index a304353..ebd9d4f 100644 --- a/src/python_wrap/http.py +++ b/src/python_wrap/http.py @@ -27,6 +27,7 @@ from python_wrap import _core, _fork from python_wrap._backend import BackendMonitor from python_wrap._runtime import name_digest +from python_wrap._scripts import Script from python_wrap.deadline import remaining as _deadline_remaining from python_wrap.retry import RetryBudget, _compute_delay, http_status, retry, retry_after_header from python_wrap.shared import _async_redis_client @@ -358,6 +359,16 @@ def _pause_key(host: str) -> str: return "python-wrap:http-pause:" + name_digest(host) +_EXTEND_PAUSE = """ +local ttl = tonumber(ARGV[1]) +if redis.call('PTTL', KEYS[1]) < ttl then + redis.call('SET', KEYS[1], '1', 'PX', ttl) +end +return 1 +""" +_EXTEND_PAUSE_SCRIPT = Script(_EXTEND_PAUSE) + + @dataclass(frozen=True) class HttpPolicy: """Retries plus a circuit breaker, rate limiter, bulkhead and timeouts for HTTP calls. @@ -405,9 +416,6 @@ class HttpPolicy: _blocked: OrderedDict[str, float] = field( default_factory=OrderedDict, init=False, repr=False, compare=False ) - _pause_checks: OrderedDict[str, float] = field( - default_factory=OrderedDict, init=False, repr=False, compare=False - ) _pause_monitor: BackendMonitor = field( default_factory=lambda: BackendMonitor("http", "pause", "allow", register=False), init=False, @@ -528,18 +536,6 @@ def _pause_client(self) -> Any: shared = resolve_shared(self.shared) return None if shared is None else shared.client - def _should_read_pause(self, host: str) -> bool: - now = _core.monotonic() - with self._lock: - previous = self._pause_checks.get(host) - if previous is not None and now - previous < 1: - return False - self._pause_checks[host] = now - self._pause_checks.move_to_end(host) - if len(self._pause_checks) > self.max_hosts: - self._pause_checks.popitem(last=False) - return True - def _remember_pause(self, host: str, seconds: float) -> None: if seconds <= 0: return @@ -552,7 +548,7 @@ def _remember_pause(self, host: str, seconds: float) -> None: def _read_pause(self, host: str) -> None: client = self._pause_client() - if client is not None and self._should_read_pause(host): + if client is not None: millis = self._pause_monitor.call( "pttl", lambda: client.pttl(_pause_key(host)), lambda: 0 ) @@ -564,7 +560,7 @@ async def _aread_pause(self, host: str) -> None: return if not _async_redis_client(client): await asyncio.to_thread(self._read_pause, host) - elif self._should_read_pause(host): + else: millis = await self._pause_monitor.acall( "pttl", lambda: client.pttl(_pause_key(host)), lambda: 0 ) @@ -578,7 +574,9 @@ def _note(self, host: str, response: Any) -> None: if client is not None: self._pause_monitor.call( "set", - lambda: client.set(_pause_key(host), "1", px=math.ceil(hinted * 1000)), + lambda: _EXTEND_PAUSE_SCRIPT.run( + client, 1, _pause_key(host), math.ceil(hinted * 1000) + ), lambda: None, ) @@ -595,7 +593,9 @@ async def _anote(self, host: str, response: Any) -> None: self._remember_pause(host, hinted) await self._pause_monitor.acall( "set", - lambda: client.set(_pause_key(host), "1", px=math.ceil(hinted * 1000)), + lambda: _EXTEND_PAUSE_SCRIPT.arun( + client, 1, _pause_key(host), math.ceil(hinted * 1000) + ), lambda: None, ) diff --git a/tests/test_http_policy.py b/tests/test_http_policy.py index 18bd92d..2c4bf71 100644 --- a/tests/test_http_policy.py +++ b/tests/test_http_policy.py @@ -151,16 +151,14 @@ def __init__(self) -> None: self.values: dict[str, int] = {} self.reads = 0 - def eval(self, *args: Any) -> Any: - pytest.fail("unexpected script") + def eval(self, script: str, count: int, key: str, ttl: int) -> int: + self.values[key] = max(ttl, self.values.get(key, 0)) + return 1 def pttl(self, key: str) -> int: self.reads += 1 return self.values.get(key, -2) - def set(self, key: str, value: str, *, px: int) -> None: - self.values[key] = px - client = Client() response = Resp(429) response.headers["Retry-After"] = "30" @@ -170,4 +168,4 @@ def set(self, key: str, value: str, *, px: int) -> None: for _ in range(2): with pytest.raises(RateLimitExceeded): other.call("api.example", lambda: pytest.fail("request should pause")) - assert client.reads == 2 + assert client.reads == 3 diff --git a/tests/test_redis_backends.py b/tests/test_redis_backends.py index 69cc822..4ede747 100644 --- a/tests/test_redis_backends.py +++ b/tests/test_redis_backends.py @@ -456,6 +456,38 @@ def price(sku): assert workers[3]("a1") == 2 +def test_redis_http_pause_is_visible_immediately_and_cannot_shorten(redis_client): + from types import SimpleNamespace + + from python_wrap.errors import RateLimitExceeded + from python_wrap.http import _EXTEND_PAUSE, HttpPolicy, HttpRetryPolicy + + class PauseClient(ShaClient): + def pttl(self, key): + return self.execute("PTTL", key) + + host = "pause.example" + retry = HttpRetryPolicy(max_retry_after=5) + first, second, peer = [ + HttpPolicy(shared=PauseClient(redis_client.path), retry=retry) for _ in range(3) + ] + + def request_while_first_sets_pause(): + first.call(host, lambda: SimpleNamespace(status_code=429, headers={"Retry-After": "30"})) + return SimpleNamespace(status_code=429, headers={"Retry-After": "1"}) + + def send(): + return SimpleNamespace(status_code=200, headers={}) + + assert peer.call(host, send).status_code == 200 + assert second.call(host, request_while_first_sets_pause).status_code == 429 + assert peer.shared.loaded(Script(_EXTEND_PAUSE)) + with pytest.raises(RateLimitExceeded) as rejected: + peer.call(host, lambda: pytest.fail("the shared pause should prevent this request")) + assert rejected.value.retry_after > 5 + assert peer.call("other.example", send).status_code == 200 + + def test_redis_half_open_rejection_has_positive_wait(redis_client): """A caller rejected while the single trial slot is in use must not get a zero wait.""" breaker = CircuitBreaker( From 1b250ee62cbfec24ed011279e871f574a9c4bcee Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 4 Dec 2026 05:55:56 +0200 Subject: [PATCH 29/38] Close cache outage and platform verification gaps --- .github/workflows/ci.yml | 2 +- CHANGELOG.md | 3 ++ docs/features/ai/langchain.md | 1 + docs/features/concurrency/shared-limits.md | 4 ++- docs/llms-full.txt | 3 +- docs/project/performance.md | 13 +++++--- pyproject.toml | 1 + scripts/check_release.py | 5 ++- src/python_wrap/async_cache.py | 2 ++ src/python_wrap/caching.py | 3 ++ src/python_wrap/coordination.py | 16 ++++++++++ src/python_wrap/stores.py | 5 +-- tests/conftest.py | 3 ++ tests/test_backend_recovered.py | 37 +++++++++++++++++++++- tests/test_backend_rules.py | 7 ++-- tests/test_langchain_providers.py | 19 ++++++++--- uv.lock | 4 +++ 17 files changed, 110 insertions(+), 18 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2fbb74f..71312e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -282,7 +282,7 @@ jobs: - name: LangChain provider contracts if: matrix.versions.name == 'latest' run: >- - uv run --frozen --with langchain-openai --with langchain-anthropic + uv run --frozen --with langchain --with langchain-openai --with langchain-anthropic pytest tests/test_langchain_adapter.py tests/test_langchain_providers.py - name: LangChain minimum core contracts diff --git a/CHANGELOG.md b/CHANGELOG.md index f1b026d..930bc44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,9 @@ Breaking changes are listed under **Breaking changes**, each with its migration. - HTTP policies honor a host's 429 pause without requiring a configured limiter. - Policies read a shared 429 pause before each attempt. Overlapping responses can extend the pause but cannot shorten it. +- Cache decorators back off lease requests during a store outage and emit a recovery event + when the lease backend responds again. +- Signed-pickle codec configuration reads its signing secret on Windows as well as POSIX. - Failed transactional idempotent calls remove their own unfinished claim. - Rebuilding LangChain provider models drops the original SDK clients so their retries are disabled while preserving the API settings and HTTP transports. diff --git a/docs/features/ai/langchain.md b/docs/features/ai/langchain.md index 0c75324..0a2fb36 100644 --- a/docs/features/ai/langchain.md +++ b/docs/features/ai/langchain.md @@ -136,3 +136,4 @@ Tests exercise the oldest supported `langchain-core` and the current provider in The `ChatOpenAI` and `ChatAnthropic` tests stub HTTP at the transport and verify that rebuilding preserves credentials and the endpoint. Two 429 responses followed by a success make three requests through a tool-bound model and charge the budget once. +The OpenAI case also runs through `langchain.agents.create_agent` with a guarded model. diff --git a/docs/features/concurrency/shared-limits.md b/docs/features/concurrency/shared-limits.md index 48535f2..cf17791 100644 --- a/docs/features/concurrency/shared-limits.md +++ b/docs/features/concurrency/shared-limits.md @@ -178,7 +178,9 @@ explicitly on the backend or in `configure(backend_errors=...)` to pin it across Caches take `on_backend_error` too: `"allow"` (a miss, writes dropped) is their default, and `"local"` behaves like `"allow"`. Token windows default to `"local"`. Leases (`Lease(..., on_backend_error="allow")`) enter without the lease and set `degraded`; memoize -uses that to compute the value when its lock store is down. `Lease` itself defaults to +uses that to compute the value when its lock store is down. Cache decorators back off lease +requests for one second after an acquisition error and report when Redis answers again. +`Lease` itself defaults to `"raise"`, which `idempotent` and `single_instance` keep. diff --git a/docs/llms-full.txt b/docs/llms-full.txt index 14f35b9..be9b01f 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -2157,6 +2157,7 @@ Tests exercise the oldest supported `langchain-core` and the current provider in The `ChatOpenAI` and `ChatAnthropic` tests stub HTTP at the transport and verify that rebuilding preserves credentials and the endpoint. Two 429 responses followed by a success make three requests through a tool-bound model and charge the budget once. +The OpenAI case also runs through `langchain.agents.create_agent` with a guarded model. --- @@ -4337,7 +4338,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm What to retry, how long to wait, and when to stop, for HTTP calls. - `python_wrap.INJECTED` Constant: INJECTED -- `python_wrap.Lease`: `Lease(key: str, *, backend: Any = None, ttl: float | str = 60, limit: int = 1, wait: bool = False, timeout: float | None = None, renew: bool = True, on_backend_error: str | None = None)` +- `python_wrap.Lease`: `Lease(key: str, *, backend: Any = None, ttl: float | str = 60, limit: int = 1, wait: bool = False, timeout: float | None = None, renew: bool = True, on_backend_error: str | None = None, _monitor: BackendMonitor | None = None)` Single-use sync/async lease context with renewal and bounded acquisition wait. - `python_wrap.LeaseLost` A lease expired or could not be renewed while work was running. diff --git a/docs/project/performance.md b/docs/project/performance.md index 44b6cbe..74ecb0b 100644 --- a/docs/project/performance.md +++ b/docs/project/performance.md @@ -89,10 +89,10 @@ Against a real Redis (local server, CPython 3.11, Apple M2 Pro), from | rate_limit (redis) | 97,673 | | memoize (redis hit) | 83,965 | -The breaker row is low because a closed state is served from its `state_ttl` cache. The -bulkhead pays two lease round trips plus starting its lease-renewal thread on every -call; prefer it for calls that take far longer than that. Measure where your service -runs: these numbers are mostly the network round trip. +The breaker row is low because a closed state is served from its `state_ttl` cache. +By default, each bulkhead call makes two lease round trips. A single renewal thread +serves all synchronous leases in each process. Set `slot_idle=` to reuse a slot for +nearby calls in the same process. An idle slot remains reserved during that window. For a one-hour run with the shared retry budget and bulkhead enabled, use `python benchmarks/soak.py --processes 2 --threads 8 --duration 3600 --limit 100 --bulkhead 4 --redis-url ...`. @@ -104,6 +104,11 @@ A 60-second soak with 4 processes x 8 threads sharing one Redis breaker and a dependency calls per logical call through the outage phases, ended with the breaker closed in every process and had no stuck lease or hang. +The 0.4.2 branch also completed a 60-second run with four processes, four threads each, +a shared retry budget, eight shared bulkhead slots and a 1,000 calls/s limit. On an +Apple M2 Pro with CPython 3.11.16 and local Redis 8.0.2, it processed 110,489 calls, +admitted 860 calls/s and ended with all four breakers closed and no slots held. + A closed shared breaker answers from its cached state (`state_ttl`) and sends successes in batches, so most calls make no store round trip. The async rows use an awaited `redis.asyncio` client; the "via thread" rows pass a sync client to async code, which diff --git a/pyproject.toml b/pyproject.toml index 521165e..64b51ab 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,6 +63,7 @@ Changelog = "https://github.com/LitePy/PythonWrap/blob/main/CHANGELOG.md" [dependency-groups] core-test = [ + "tomli>=2; python_version < '3.11'", "pytest>=9.2.0", "pytest-cov>=6.0", "pytest-asyncio>=1.4.1.post1", diff --git a/scripts/check_release.py b/scripts/check_release.py index 36ad0e9..324917b 100644 --- a/scripts/check_release.py +++ b/scripts/check_release.py @@ -17,7 +17,10 @@ import sys from pathlib import Path -import tomllib +try: + import tomllib +except ModuleNotFoundError: # Python 3.10 + import tomli as tomllib ROOT = Path(__file__).resolve().parents[1] CHANGELOG = ROOT / "CHANGELOG.md" diff --git a/src/python_wrap/async_cache.py b/src/python_wrap/async_cache.py index 904bfc7..8f3d42b 100644 --- a/src/python_wrap/async_cache.py +++ b/src/python_wrap/async_cache.py @@ -554,6 +554,7 @@ def decorate(func: F) -> F: backend: AsyncCacheStore = store if store is not None else AsyncMemoryStore() build_key = _make_key_builder(func, False, key) name = _core.qualname(func) + lease_monitor = BackendMonitor("lease", name, "allow") if lock is not None else None hits = misses = 0 stats_lock = _fork.ForkSafeLock() inflight: dict[tuple[int, Hashable], asyncio.Future[Any]] = {} @@ -621,6 +622,7 @@ def lease_for(k: Hashable, wait: bool) -> Any: wait=wait, timeout=lock_wait if wait else None, on_backend_error="allow", + _monitor=lease_monitor, ) async def compute(k: Hashable, args: Any, kwargs: Any, refreshing: bool = False) -> Any: diff --git a/src/python_wrap/caching.py b/src/python_wrap/caching.py index 93cc7ff..48c3700 100644 --- a/src/python_wrap/caching.py +++ b/src/python_wrap/caching.py @@ -28,6 +28,7 @@ ) from python_wrap import _core, _fork +from python_wrap._backend import BackendMonitor from python_wrap._runtime import name_digest, stable_digest __all__ = [ @@ -960,6 +961,7 @@ def decorate(f: Callable[..., Any]) -> Any: if per_instance and fast_n == 0: raise TypeError("per_instance=True needs a method (a function taking self)") name = _core.qualname(f) + lease_monitor = BackendMonitor("lease", name, "allow") if lock_backend is not None else None def isolate(value: Any) -> Any: # Never copy while holding a cache lock: user __deepcopy__ methods may @@ -1131,6 +1133,7 @@ def lease_for(k: Hashable, wait: bool) -> Any: wait=wait, timeout=lock_wait if wait else None, on_backend_error="allow", + _monitor=lease_monitor, ) def cached_outcome(b: Any, k: Hashable) -> tuple[bool, Any]: diff --git a/src/python_wrap/coordination.py b/src/python_wrap/coordination.py index 2767417..e407fce 100644 --- a/src/python_wrap/coordination.py +++ b/src/python_wrap/coordination.py @@ -17,6 +17,7 @@ from typing import Any, TypeVar, cast from python_wrap import _core, _fork +from python_wrap._backend import BackendMonitor from python_wrap._runtime import call_key, seconds from python_wrap._scripts import Script @@ -560,6 +561,7 @@ def __init__( timeout: float | None = None, renew: bool = True, on_backend_error: str | None = None, + _monitor: BackendMonitor | None = None, ) -> None: """Create a lease. ``on_backend_error`` is ``"raise"`` (the default, also when None: a store outage fails the call) or ``"allow"`` (enter without the lease, set @@ -569,6 +571,7 @@ def __init__( if on_backend_error not in (None, "raise", "allow"): raise ValueError("Lease on_backend_error must be 'raise' or 'allow'") self.on_backend_error = on_backend_error or "raise" + self._monitor = _monitor self.degraded = False self.key = key self.backend: Any = backend if backend is not None else _LOCAL @@ -604,6 +607,8 @@ def _try(self) -> bool: try: started = _core.monotonic() acquired = bool(self.backend.acquire(self.key, self.token, self.ttl, self.limit)) + if self._monitor is not None: + self._monitor.succeeded() if acquired: self._deadline = started + self.ttl return acquired @@ -618,6 +623,9 @@ def _try(self) -> bool: def _degrade(self, exc: Exception) -> None: """Enter without the lease after a store error (``on_backend_error="allow"``).""" self.degraded = self._active = True + if self._monitor is not None: + self._monitor.failed(exc, "acquire") + return logging.getLogger("python_wrap").warning( "lease store failed for %r (%s); entering without the lease", self.key, @@ -654,6 +662,8 @@ async def _try_async(self) -> bool: try: started = _core.monotonic() acquired = bool(await self.backend.acquire(self.key, self.token, self.ttl, self.limit)) + if self._monitor is not None: + self._monitor.succeeded() if acquired: self._deadline = started + self.ttl return acquired @@ -716,6 +726,9 @@ def __enter__(self) -> Lease: self._sync_only() self._prepare() try: + if self._monitor is not None and self._monitor._skipping(): + self.degraded = self._active = True + return self start = time.monotonic() attempt = 0 try: @@ -795,6 +808,9 @@ async def _atry(self) -> bool: async def __aenter__(self) -> Lease: self._prepare() try: + if self._monitor is not None and self._monitor._skipping(): + self.degraded = self._active = True + return self loop = asyncio.get_running_loop() start = loop.time() attempt = 0 diff --git a/src/python_wrap/stores.py b/src/python_wrap/stores.py index 98babf2..d6b7310 100644 --- a/src/python_wrap/stores.py +++ b/src/python_wrap/stores.py @@ -78,11 +78,12 @@ def resolve_codec(value: Any) -> tuple[Callable[[Any], bytes], Callable[[bytes], env_name = value[1] if not isinstance(env_name, str) or not env_name: raise ValueError("signed-pickle codec needs the name of an environment variable") - secret = os.environb.get(os.fsencode(env_name)) - if secret is None: + configured_secret = os.getenv(env_name) + if configured_secret is None: raise ValueError( f"signed-pickle cache codec: environment variable {env_name} is not set" ) + secret = os.fsencode(configured_secret) if len(secret) < 16: raise ValueError( f"signed-pickle cache codec: secret in {env_name} must be at least 16 bytes" diff --git a/tests/conftest.py b/tests/conftest.py index 1534f62..c68a08d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -65,6 +65,9 @@ def read() -> object: def get(self, key: str) -> object: return self.execute("GET", key) + def set(self, key: str, value: bytes, *, px: int) -> object: + return self.execute("SET", key, value, "PX", px) + def delete(self, *keys: str) -> object: return self.execute("DEL", *keys) diff --git a/tests/test_backend_recovered.py b/tests/test_backend_recovered.py index bedae7d..b4bfcad 100644 --- a/tests/test_backend_recovered.py +++ b/tests/test_backend_recovered.py @@ -7,18 +7,22 @@ from __future__ import annotations +import time import uuid import pytest +from python_wrap.caching import memoize from python_wrap.circuit import CircuitBreaker from python_wrap.coordination import RedisLock from python_wrap.events import listening +from python_wrap.llm_shared import RedisTokenWindow from python_wrap.quotas import Quota, RedisWindow from python_wrap.retry import RetryBudget from python_wrap.shared import RedisBreakerState, RedisRetryBudget, SharedBulkhead +from python_wrap.stores import RedisStore, json_codec -KINDS = ["breaker", "window", "quota", "bulkhead", "budget"] +KINDS = ["breaker", "window", "quota", "bulkhead", "budget", "cache", "tokens"] def _operation(kind: str, client: object): @@ -48,6 +52,13 @@ def use() -> None: # Deposits are batched in memory, so a withdrawal is the call that reaches the store. budget = RetryBudget(backend=RedisRetryBudget(client, f"rec-{tag}")) return budget.try_withdraw + if kind == "cache": + dumps, loads = json_codec() + store = RedisStore(client, tag, dumps=dumps, loads=loads, on_backend_error="raise") + return lambda: store.get("key") + if kind == "tokens": + window = RedisTokenWindow(client, tag, on_backend_error="raise") + return lambda: window.reserve(1, 100, 1) raise AssertionError(kind) @@ -69,3 +80,27 @@ def test_backend_recovered_event_per_kind(kind, failing_then_recovering_client): recovered = [e for e in events if e.name == "backend.recovered"] assert len(recovered) == 1 assert recovered[0].fields["backend"] == kind + + +def test_cache_lease_backs_off_and_recovers_on_real_redis(failing_then_recovering_client): + client = failing_then_recovering_client + dumps, loads = json_codec() + store = RedisStore(client, f"lease-recovery-{uuid.uuid4().hex}:", dumps=dumps, loads=loads) + + @memoize(store=store, lock=RedisLock(client), ttl=60) + def value(n): + return n + + def lease_events(): + return [event.name for event in events if event.fields.get("backend") == "lease"] + + events = [] + with listening(events.append): + client.down = True + assert [value(n) for n in range(100)] == list(range(100)) + assert lease_events() == ["backend.error"] + client.down = False + time.sleep(1.05) + assert value(0) == value(0) == 0 + assert lease_events() == ["backend.error", "backend.recovered"] + assert value.cache_info().hits == 1 diff --git a/tests/test_backend_rules.py b/tests/test_backend_rules.py index 9bd4f22..592936c 100644 --- a/tests/test_backend_rules.py +++ b/tests/test_backend_rules.py @@ -126,8 +126,11 @@ async def value(n: int) -> int: calls.append(n) return n * 2 - assert await value(4) == 8 - assert calls == [4] + events = [] + with listening(events.append): + assert await value(4) == await value(4) == 8 + assert calls == [4, 4] + assert sum(event.fields.get("backend") == "lease" for event in events) == 1 def test_lease_allow_enters_degraded_without_release() -> None: diff --git a/tests/test_langchain_providers.py b/tests/test_langchain_providers.py index f2dc337..7703b10 100644 --- a/tests/test_langchain_providers.py +++ b/tests/test_langchain_providers.py @@ -14,9 +14,14 @@ pytestmark = pytest.mark.sdk -@pytest.mark.parametrize("provider", ["openai", "anthropic"]) -def test_bound_provider_retries_and_charges_once(provider): +@pytest.mark.parametrize( + ("provider", "agent"), + [("openai", False), ("anthropic", False), ("openai", True)], + ids=["openai", "anthropic", "openai-agent"], +) +def test_bound_provider_retries_and_charges_once(provider, agent): integration = pytest.importorskip(f"langchain_{provider}") + agents = pytest.importorskip("langchain.agents") if agent else None model_type = integration.ChatOpenAI if provider == "openai" else integration.ChatAnthropic sdk = import_module(provider) http = import_module( @@ -71,10 +76,14 @@ def lookup(city: str) -> str: budget = Budget(tokens=1000) guarded = guard_chat_model(model, budget=budget, attempts=3, retry={"delay": 0}) events = [] + config = {"callbacks": [PythonWrapCallback(budget=budget)]} with fake_clock(), listening(events.append): - result = guarded.bind_tools([lookup]).invoke( - "hello", config={"callbacks": [PythonWrapCallback(budget=budget)]} - ) + if agents is None: + result = guarded.bind_tools([lookup]).invoke("hello", config=config) + else: + graph = agents.create_agent(guarded, tools=[lookup]) + outcome = graph.invoke({"messages": [{"role": "user", "content": "hello"}]}, config) + result = outcome["messages"][-1] assert result.usage_metadata["total_tokens"] == 15 assert guarded.model.max_retries == 0 diff --git a/uv.lock b/uv.lock index 240e0f6..8ca5656 100644 --- a/uv.lock +++ b/uv.lock @@ -3304,6 +3304,7 @@ core-test = [ { name = "pytest-asyncio" }, { name = "pytest-cov" }, { name = "ruff" }, + { name = "tomli", marker = "python_full_version < '3.11'" }, ] dev = [ { name = "hypothesis", version = "6.168.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, @@ -3317,6 +3318,7 @@ dev = [ { name = "pytest-asyncio" }, { name = "pytest-cov" }, { name = "ruff" }, + { name = "tomli", marker = "python_full_version < '3.11'" }, ] docs = [ { name = "mkdocs-material", version = "9.7.7", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, @@ -3350,6 +3352,7 @@ core-test = [ { name = "pytest-asyncio", specifier = ">=1.4.1.post1" }, { name = "pytest-cov", specifier = ">=6.0" }, { name = "ruff", specifier = ">=0.17.4" }, + { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2" }, ] dev = [ { name = "hypothesis", specifier = ">=6.100" }, @@ -3361,6 +3364,7 @@ dev = [ { name = "pytest-asyncio", specifier = ">=1.4.1.post1" }, { name = "pytest-cov", specifier = ">=6.0" }, { name = "ruff", specifier = ">=0.17.4" }, + { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2" }, ] docs = [ { name = "mkdocs-material", specifier = ">=9.5" }, From 33d0224404f1a21f93672c25e3839b80c4b5cb6e Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 4 Dec 2026 05:59:41 +0200 Subject: [PATCH 30/38] Enforce shared bulkhead capacity during local fallback --- CHANGELOG.md | 1 + benchmarks/run.py | 7 ++----- docs/project/performance.md | 5 +++++ src/python_wrap/shared.py | 28 ++++++++++++++-------------- tests/test_backend_rules.py | 25 +++++++++++++++++++++++++ tests/test_redis_backends.py | 13 +++++++++++-- 6 files changed, 58 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 930bc44..2f0a9da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,6 +60,7 @@ Breaking changes are listed under **Breaking changes**, each with its migration. - Cache decorators back off lease requests during a store outage and emit a recovery event when the lease backend responds again. - Signed-pickle codec configuration reads its signing secret on Windows as well as POSIX. +- The local fallback for a shared bulkhead enforces capacity under concurrent admission. - Failed transactional idempotent calls remove their own unfinished claim. - Rebuilding LangChain provider models drops the original SDK clients so their retries are disabled while preserving the API settings and HTTP transports. diff --git a/benchmarks/run.py b/benchmarks/run.py index 9b11c16..4854cc1 100644 --- a/benchmarks/run.py +++ b/benchmarks/run.py @@ -231,6 +231,7 @@ def cases() -> list[Case]: Case("retry+timeout+circuit_breaker", _stack, _stack_async), *_shared("circuit_breaker", _shared_breaker, _CLOSED), *_shared("Bulkhead(8)", _shared_bulkhead, 1), + *_shared("Bulkhead(8, slot_idle=1)", functools.partial(_shared_bulkhead, slot_idle=1), 1), ] # An async window refuses sync functions, so it has no "via thread" row. out.append( @@ -261,11 +262,7 @@ async def _arun(f: Callable[..., Awaitable[Any]], n: int) -> float: def _time_async(f: Fn, n: int) -> float: - loop = asyncio.new_event_loop() - try: - return loop.run_until_complete(_arun(f, n)) - finally: - loop.close() + return asyncio.run(_arun(f, n)) def _measure( diff --git a/docs/project/performance.md b/docs/project/performance.md index 74ecb0b..e54f5f3 100644 --- a/docs/project/performance.md +++ b/docs/project/performance.md @@ -78,6 +78,11 @@ of the previous release (its code at HEAD, same interpreter) measured the async 93,471 ns and through a thread at 158,961 ns, with the sync row at 3,528 ns. The other rows were measured in the same run and are shown as they came out of it. +On the 0.4.2 branch, a quick run on the same hardware with CPython 3.11.16 measured +`Bulkhead(8, slot_idle=1)` at 1.95 µs per synchronous call and 2.39 µs per native async +call with the in-memory Redis stand-in. The shared breaker measured 2.19 µs and 2.49 µs +respectively. Without slot reuse, the bulkhead measured 13.47 µs and 215.93 µs. + Against a real Redis (local server, CPython 3.11, Apple M2 Pro), from `python benchmarks/run.py --filter redis --redis-url redis://localhost:6379/0` (needs the `redis` package): diff --git a/src/python_wrap/shared.py b/src/python_wrap/shared.py index c82199d..b2034a6 100644 --- a/src/python_wrap/shared.py +++ b/src/python_wrap/shared.py @@ -616,7 +616,7 @@ def __init__( self._monitor = BackendMonitor("bulkhead", name, on_backend_error, retry_backend_after) acquire = getattr(backend, "acquire", None) self._async = acquire is not None and _core.is_async(acquire) - self._stack: contextvars.ContextVar[tuple[tuple[Lease, object], ...]] = ( + self._stack: contextvars.ContextVar[tuple[tuple[Lease | None, object], ...]] = ( contextvars.ContextVar("bulkhead_leases", default=()) ) self._lock = _fork.ForkSafeLock() @@ -646,12 +646,6 @@ def _store_down(self, exc: Exception) -> None: if self._monitor.mode == "raise": raise exc - def _local_admit(self, owner: object) -> None: - """Store is down: "allow" admits; "local" admits up to this process's capacity.""" - if self._monitor.mode == "local" and self.active >= self.capacity: - raise self._rejected("shared bulkhead full (local fallback)") - self._admitted(None, owner) # type: ignore[arg-type] - def _lease(self) -> Lease: return Lease(self.name, backend=self.backend, ttl=self.ttl, limit=self.capacity, wait=False) @@ -667,10 +661,16 @@ def _queued(self) -> None: if rejected: raise self._rejected("shared bulkhead queue full") - def _admitted(self, lease: Lease, owner: object) -> None: - self._stack.set((*self._stack.get(), (lease, owner))) + def _admitted(self, lease: Lease | None, owner: object) -> None: with self._lock: - self._active += 1 + rejected = ( + lease is None and self._monitor.mode == "local" and self._active >= self.capacity + ) + if not rejected: + self._active += 1 + if rejected: + raise self._rejected("shared bulkhead full (local fallback)") + self._stack.set((*self._stack.get(), (lease, owner))) def _take_idle(self, loop: asyncio.AbstractEventLoop | None) -> Lease | None: if not self.slot_idle: @@ -746,7 +746,7 @@ def acquire(self) -> None: if (idle := self._take_idle(None)) is not None: return self._admitted(idle, threading.get_ident()) if self._monitor._skipping(): - return self._local_admit(threading.get_ident()) + return self._admitted(None, threading.get_ident()) lease = self._lease() try: self._enter(lease) @@ -754,7 +754,7 @@ def acquire(self) -> None: raise except Exception as exc: # a store error, first attempt or while queued self._store_down(exc) - return self._local_admit(threading.get_ident()) + return self._admitted(None, threading.get_ident()) self._monitor.succeeded() self._admitted(lease, threading.get_ident()) @@ -797,7 +797,7 @@ async def acquire_async(self) -> None: if (idle := self._take_idle(asyncio.get_running_loop())) is not None: return self._admitted(idle, asyncio.current_task()) if self._monitor._skipping(): - return self._local_admit(asyncio.current_task()) + return self._admitted(None, asyncio.current_task()) lease = self._lease() try: await self._aenter(lease) @@ -805,7 +805,7 @@ async def acquire_async(self) -> None: raise except Exception as exc: # a store error, first attempt or while queued self._store_down(exc) - return self._local_admit(asyncio.current_task()) + return self._admitted(None, asyncio.current_task()) self._monitor.succeeded() self._admitted(lease, asyncio.current_task()) diff --git a/tests/test_backend_rules.py b/tests/test_backend_rules.py index 592936c..e71a9a7 100644 --- a/tests/test_backend_rules.py +++ b/tests/test_backend_rules.py @@ -142,6 +142,31 @@ def test_lease_allow_enters_degraded_without_release() -> None: pass +def test_shared_bulkhead_local_fallback_caps_concurrent_callers() -> None: + from concurrent.futures import ThreadPoolExecutor + from threading import Barrier + + from python_wrap.errors import BulkheadFull + + bulkhead = Bulkhead(1, name="local-fallback", backend=Dead(), on_backend_error="local") + with bulkhead: # mark the backend unavailable before starting the concurrent callers + pass + batch = Barrier(8, timeout=5) + + def enter(_: int) -> bool: + batch.wait() + try: + with bulkhead: + batch.wait() + return True + except BulkheadFull: + batch.wait() + return False + + with ThreadPoolExecutor(max_workers=8) as pool: + assert sum(pool.map(enter, range(8))) == 1 + + def test_bulkhead_queue_error_uses_fallback() -> None: class QueueFails: """First attempt: the slot is busy. The attempt made while queued: store error.""" diff --git a/tests/test_redis_backends.py b/tests/test_redis_backends.py index 4ede747..d7d0c07 100644 --- a/tests/test_redis_backends.py +++ b/tests/test_redis_backends.py @@ -630,12 +630,21 @@ def test_scripts_reload_on_noscript(redis_client): def _limit_worker(path, active, peak, rounds): - from python_wrap import Lease, RedisSemaphore + from python_wrap import Bulkhead, RedisSemaphore backend = RedisSemaphore(Client(path), "two-proc:") + bulkhead = Bulkhead( + 2, + name="pool", + backend=backend, + timeout=30, + ttl=5, + slot_idle=0.03, + on_backend_error="raise", + ) def one(_): - with Lease("pool", backend=backend, limit=2, ttl=5, wait=True, timeout=30): + with bulkhead: with active.get_lock(): active.value += 1 peak.value = max(peak.value, active.value) From 2cce0e30d5a631cc08fee1685208ccb0df2b9ed1 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 4 Dec 2026 06:04:08 +0200 Subject: [PATCH 31/38] Give streaming timeout tests room for CI scheduling --- tests/test_llm.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_llm.py b/tests/test_llm.py index f74100d..8408db8 100644 --- a/tests/test_llm.py +++ b/tests/test_llm.py @@ -678,8 +678,8 @@ def test_stream_passes_through_when_fast() -> None: ("delays", "limits", "tripped", "received"), [ ([0.5], {"first_token": 0.05}, "first_token", []), - ([0, 0, 0.5], {"first_token": 1, "chunk_gap": 0.05}, "chunk_gap", [0, 1]), - ([0, 0.04, 0.04, 0.04, 0.04], {"chunk_gap": 1, "total": 0.1}, "total", [0, 1]), + ([0, 0, 0.8], {"first_token": 1, "chunk_gap": 0.2}, "chunk_gap", [0, 1]), + ([0, 0, 1.5], {"chunk_gap": 2, "total": 0.5}, "total", [0, 1]), ], ) def test_sync_stream_limits( From bbb6c24f30ac54454f0f3fa042501700374524b0 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 4 Dec 2026 09:18:26 +0200 Subject: [PATCH 32/38] Record the one-hour Redis soak results --- docs/project/performance.md | 17 +++++++++++++++++ docs/project/stability.md | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/docs/project/performance.md b/docs/project/performance.md index e54f5f3..debfae4 100644 --- a/docs/project/performance.md +++ b/docs/project/performance.md @@ -123,6 +123,23 @@ The "x bare" factors look dramatic because the bare function is nearly free. Rea nanosecond columns: 2,000 ns is two microseconds, a thousandth of a typical 2 ms HTTP request. +### One-hour Redis soak + +On December 4, 2026, the run started from 0.4.2 branch commit `29aaab7` and used +the same hardware, Python and Redis versions as the 60-second run. + +```bash +python benchmarks/soak.py --duration 3600 --threads 4 --processes 4 \ + --redis-url redis://127.0.0.1:16382/1 --limit 1000 --bulkhead 8 --json +``` + +The four workers made 6,236,928 logical calls and 1,920,047 dependency calls through +the simulated outage phases, with 30 timeouts. The rate limiter admitted an average of +833.6 calls/s. +All four breakers ended closed and Redis reported no held bulkhead slots. The highest +worker p99 latency was 56.1 ms. Traced memory grew by roughly 8 MiB per worker, including +the benchmark's bounded latency samples. The run reports endpoint memory growth. + ## Interpretation **Cheap (under about 300 ns).** `once`, `throttle`, `log_args` with its level disabled, diff --git a/docs/project/stability.md b/docs/project/stability.md index d0b1192..a70553c 100644 --- a/docs/project/stability.md +++ b/docs/project/stability.md @@ -59,7 +59,7 @@ A provisional module graduates when all four hold: | Module | Target | Status | | --- | --- | --- | -| `shared`, `coordination`, `quotas`, `stores` | 0.5.0 | Live CI in place; storage formats pinned by `tests/test_stability.py`; 1-minute 4-process soak passed, 1-hour soak pending | +| `shared`, `coordination`, `quotas`, `stores` | 0.5.0 | Storage formats pinned by `tests/test_stability.py`; [one-hour Redis soak](performance.md#one-hour-redis-soak) completed for the breaker, limiter, retry budget and bulkhead | | `http` | 0.5.0 | CI against the real requests and httpx packages; soak pending | | `celery` | 0.5.0 | CI against the real Celery package; real-worker tests check propagation on an in-memory broker and worker loss on Redis; soak pending | | `async_cache`, `web`, `exporters`, `observability` | 0.6.0 | Changed in 0.4.0b2 | From 56a09ade290a1821111addfed0464d0723dcd4ec Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 4 Dec 2026 13:28:41 +0200 Subject: [PATCH 33/38] Apply the planned 0.5.0 resilience defaults --- CHANGELOG.md | 16 +++- docs/cookbook/framework-integrations.md | 6 +- docs/features/caching/async-stores.md | 7 +- .../caching/stores-and-credentials.md | 12 +-- docs/features/concurrency/shared-limits.md | 14 ++- docs/features/configuration.md | 4 +- .../features/resilience/presets-and-doctor.md | 2 +- docs/features/resilience/retry.md | 19 ++-- docs/llms-full.txt | 14 +-- docs/project/threat-model.md | 11 +-- examples/llm_chaos.py | 9 +- src/python_wrap/__init__.py | 2 +- src/python_wrap/_backend.py | 9 +- src/python_wrap/async_cache.py | 19 ++-- src/python_wrap/caching.py | 5 + src/python_wrap/celery.py | 31 ++----- src/python_wrap/doctor.py | 2 +- src/python_wrap/http.py | 2 +- src/python_wrap/policies.py | 7 +- src/python_wrap/retry.py | 59 ++++-------- src/python_wrap/stores.py | 23 ++--- tests/e2e/test_e2e_http_client.py | 2 +- tests/test_async_cache.py | 5 +- tests/test_attempt_history.py | 2 +- tests/test_backend_errors.py | 15 ++- tests/test_backend_recovered.py | 5 +- tests/test_backend_rules.py | 15 ++- tests/test_cache_codec.py | 39 ++++---- tests/test_celery_helpers.py | 6 +- tests/test_celery_tasks.py | 19 ++-- tests/test_chaos.py | 5 +- tests/test_config.py | 12 +-- tests/test_doctor.py | 12 +-- tests/test_http.py | 37 ++++---- tests/test_llm_testing.py | 11 ++- tests/test_local_state.py | 2 +- tests/test_policy_watch.py | 6 +- tests/test_retry.py | 6 ++ tests/test_retry_schedules.py | 91 +++---------------- tests/test_security_fixes.py | 10 +- 40 files changed, 250 insertions(+), 323 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f0a9da..bf2e672 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,11 +42,19 @@ Breaking changes are listed under **Breaking changes**, each with its migration. - HTTP policies cap cached host state with `max_hosts` (default 1000), accept limiter and bulkhead mappings, and share 429 pauses through Redis. -### Deprecated +### Changed -- Implicit shared backend error handling warns that the default switches from `"raise"` - to `"local"` in 0.5.0. Set `on_backend_error=` or `configure(backend_errors=...)` - to pin the desired mode. The 0.4.x behavior stays the same. +- Retry defaults use exponential backoff, equal jitter, and a 30-second scheduled delay cap. + Pass `backoff=1, jitter=0, max_delay=None` to restore 0.4.x timing. Explicit delay schedules + keep their values. HTTP and Celery backoff use equal jitter by default. +- Shared Redis caches default to JSON. Existing pickle entries are read as misses. + Choose an explicit codec if you need to cache exceptions or other Python objects. +- Shared backends fall back to local state during an outage. Set + `configure(backend_errors="raise")` for 0.4.x behavior. Strict leases and idempotency + retain their existing error behavior. +- Policy watches reject an invalid initial load by default. Pass `strict=False` to keep polling. +- Celery idempotency defaults to the delivery ID. Pass `scope="arguments"` to retain the + 0.4.x cache key and behavior. ### Fixed diff --git a/docs/cookbook/framework-integrations.md b/docs/cookbook/framework-integrations.md index 7b011bb..0318953 100644 --- a/docs/cookbook/framework-integrations.md +++ b/docs/cookbook/framework-integrations.md @@ -173,8 +173,8 @@ def sync_orders(self, account_id: int) -> None: ... instead of sleeping, so the task waits in the queue and never holds a worker slot. - `idempotent_task(scope=..., store=..., ttl=...)` runs the body once per key. `scope="delivery"` keys on the task's id, so redeliveries and retries of one task run once while two tasks with - the same arguments each run. `scope="arguments"` keys on task name plus arguments (the 0.4.x - default, with a `FutureWarning`; it becomes `"delivery"` in 0.5.0). `key=` overrides both. + the same arguments each run. Delivery scope is the default. Pass `scope="arguments"` to + keep the 0.4.x key based on task name and arguments. `key=` overrides both. A delivery that finds the task running is re-queued after about `requeue_delay` seconds (with jitter); those re-queues are counted in the message headers and do not use the task's own `max_retries` by default. An explicit `max_retries=` uses Celery's standard retry counting. @@ -191,7 +191,7 @@ def sync_orders(self, account_id: int) -> None: ... cases that matter; a crash between an external effect and its recorded result is the one case that can still run an effect twice (see the transactional store for that). -| Situation | `scope="delivery"` | `scope="arguments"` (0.4.x default) | +| Situation | `scope="delivery"` (default) | `scope="arguments"` | |---|---|---| | Broker delivers one task id twice (late ack, visibility timeout) | runs once | runs once | | Application retries a task after a failure (same id) | runs (a failed run stores no result) | runs (same) | diff --git a/docs/features/caching/async-stores.md b/docs/features/caching/async-stores.md index f0f30a2..f7230ae 100644 --- a/docs/features/caching/async-stores.md +++ b/docs/features/caching/async-stores.md @@ -148,7 +148,6 @@ threads. ## Serialization and trust -Entries are stored as `(value, expires_at)` pairs. The default serializer is pickle, -and unpickling bytes an attacker can write to Redis can execute arbitrary code, so use -pickle only with a Redis instance you fully trust. For anything else pass -`json_codec()`; values must then be JSON-serializable and tuples come back as lists. +Entries are stored as `(value, expires_at)` pairs. The default serializer is JSON. +Values must be JSON-serializable, and tuples come back as lists. Use a codec that +supports exceptions if you set `cache_exceptions=`. diff --git a/docs/features/caching/stores-and-credentials.md b/docs/features/caching/stores-and-credentials.md index a29eaa0..e773668 100644 --- a/docs/features/caching/stores-and-credentials.md +++ b/docs/features/caching/stores-and-credentials.md @@ -50,13 +50,11 @@ from python_wrap import configure configure(cache_codec=("signed-pickle", "APP_CACHE_SECRET")) ``` -A store built with no codec and no `cache_codec` default still uses plain pickle, which -is the implicit default. It emits a `FutureWarning` (visible under the default warning -filters) that names the fix. **In 0.5.0 the implicit default becomes JSON**, so a -store that relies on pickle must name a codec before then. `doctor` reports a `memoize` -on a store with plain pickle as PW026. Until 0.5.0, entries written with plain pickle -still load; after it, pickle entries fail to decode and are treated as misses. Use -`version=` to retire old entries at once. +Shared Redis caches default to JSON. After upgrading, old pickle entries fail JSON +decoding and are treated as misses. Set `version=` to retire the old namespace at once. +JSON values must be serializable, and tuples decode as lists. To use `cache_exceptions`, +select a codec that can serialize exceptions, such as a signed pickle codec. +Doctor reports use of plain pickle as PW026. ### Failure modes diff --git a/docs/features/concurrency/shared-limits.md b/docs/features/concurrency/shared-limits.md index cf17791..cad2be8 100644 --- a/docs/features/concurrency/shared-limits.md +++ b/docs/features/concurrency/shared-limits.md @@ -4,10 +4,8 @@ Default limiters, breakers and bulkheads are in-process. Optional Redis backends coordination across workers; they take a client created by your application. When a shared store is down, breakers, rate windows, quotas, bulkheads and retry budgets -raise by default (`on_backend_error="raise"`). Caches allow, and token windows fall back to -a local bucket; see [store-down rules](#when-the-shared-store-is-down). Release 0.5.0 changes -the default for these backends to `"local"`; set `configure(backend_errors="raise")` to keep -today's behaviour after upgrading. +fall back to process-local state by default. Set `configure(backend_errors="raise")` +to restore error propagation. See [store-down rules](#when-the-shared-store-is-down). ## A run quota @@ -168,12 +166,12 @@ Every shared backend takes the same option, `on_backend_error`: | Value | Effect | |---|---| -| `"raise"` (0.4.x default) | The store error propagates. | -| `"local"` | Use this process's own breaker, window, quota or bulkhead cap until the store answers. | +| `"raise"` | The store error propagates. | +| `"local"` (default) | Use this process's own breaker, window, quota or bulkhead cap until the store answers. | | `"allow"` | Admit the call and skip accounting. | -The shared backend default changes from `"raise"` to `"local"` in 0.5.0. Set the mode -explicitly on the backend or in `configure(backend_errors=...)` to pin it across releases. +Set the mode explicitly on the backend or in `configure(backend_errors=...)` to override +the built-in default. Caches take `on_backend_error` too: `"allow"` (a miss, writes dropped) is their default, and `"local"` behaves like `"allow"`. Token windows default to `"local"`. Leases diff --git a/docs/features/configuration.md b/docs/features/configuration.md index d5503fb..6084324 100644 --- a/docs/features/configuration.md +++ b/docs/features/configuration.md @@ -50,7 +50,9 @@ call retains the settings it started with. A watched policy changes behaviour on every replica without a restart, for example to lower a rate limit or stop retries for one dependency during an incident. See [named policies](resilience/named-policies.md). -A policy watch accepts `strict=True` to raise on a failed initial read or invalid mapping. Use `jitter=0.1` to vary the poll interval by up to 10 percent in either direction. +A policy watch raises on a failed first read or invalid mapping by default. Pass `strict=False` +to keep polling after a failed initial load. Use `jitter=0.1` to vary the poll interval by up +to 10 percent in either direction. ## Keys diff --git a/docs/features/resilience/presets-and-doctor.md b/docs/features/resilience/presets-and-doctor.md index 3cc3c85..756b657 100644 --- a/docs/features/resilience/presets-and-doctor.md +++ b/docs/features/resilience/presets-and-doctor.md @@ -156,7 +156,7 @@ The doctor reports codes PW001 to PW025 (the table lists them by group, not stri | PW023 | warning | `python_wrap.celery.check_visibility`: a blocking limiter, unbounded bulkhead queue, retry `max_time`, or an `idempotent_task` lease (`lease_ttl`) can outlive the broker's visibility timeout, so the broker delivers the task again while it still runs (for a lease: a redelivery finds the lease held and is re-queued until it expires). | | PW024 | warning | A retry layer has no backoff or jitter (`backoff=1` or no `jitter`): callers that fail together retry together, and with `--multiprocess` every worker does. Use `backoff=2, jitter="full"`. | | PW025 | warning | A retry on every `Exception` with neither `retry_if=` nor `retry_if_result=`: programming errors and non-transient failures are retried. Narrow `on=` or add a predicate. Fires together with PW003, which also covers a broad `on=` with only `retry_if_result=`. | -| PW026 | warning | `memoize` with a shared store that uses plain pickle (the implicit default, or `pickle.dumps`): anyone who can write the namespace can run code in every reader. Pass `dumps=`/`loads=` (for example `json_codec()`) or `configure(cache_codec="json")`. See [Shared caches](../caching/stores-and-credentials.md#codecs). | +| PW026 | warning | `memoize` with a shared store that uses plain pickle: anyone who can write the namespace can run code in every reader. Use `json_codec()` or `configure(cache_codec="json")`. See [Shared caches](../caching/stores-and-credentials.md#codecs). | | PW018 | warning | A python-wrap LLM retry wraps an SDK client (`llm_retry(client=...)`) whose own retries are still on: attempts multiply (4 x 3 = 12). See [OpenAI and Anthropic SDK clients](../ai/openai-anthropic.md#doctor-checks). | | PW019 | warning | A retry wraps a streamed LLM call (`stream_timeout`) without `resume_safe`: a replay after output started repeats text and half-done tool calls. | diff --git a/docs/features/resilience/retry.md b/docs/features/resilience/retry.md index e2f5a08..64183b3 100644 --- a/docs/features/resilience/retry.md +++ b/docs/features/resilience/retry.md @@ -46,8 +46,11 @@ For several workers, set a project default before decorating functions: chooses between half and all of it. A numeric jitter still adds up to that many seconds. -!!! warning "Bare `@retry` defaults change in 0.5.0" - A bare `@retry` (or `retrying()`) with no `delay`, `backoff` or `jitter` waits 1 s, three times, with no jitter. This release emits one `FutureWarning` per process saying so. In 0.5.0 the fallback becomes `backoff=2`, `jitter="equal"` and `max_delay=30`. To keep today's behaviour, pass `delay=`, `backoff=` or `jitter=` explicitly, or set the values with `configure(retry={...})`. An explicit `delays=` schedule does not warn. The `doctor` reports PW024 (no backoff or jitter) and PW025 (retries every `Exception` with no `retry_if=` or `retry_if_result=`) for such retries. +A bare `@retry` or `retrying()` uses exponential backoff and equal jitter. The first +retry waits 0.5 to 1 second, and the second waits 1 to 2 seconds. Scheduled backoff is +capped at 30 seconds. A server hint keeps its separate ceiling unless you set +`max_delay=` explicitly. Explicit `delays=` schedules keep their exact values unless +you configure a cap or jitter. ## When to use it @@ -68,9 +71,9 @@ The wait before attempt `n + 1` is `min(delay * backoff ** (n - 1), max_delay) + | `max_attempts` | `3` | Total calls allowed. `None` retries forever. | | `delay` | `1.0` | Base wait in seconds. | | `delays` | `None` | Explicit nonempty delay sequence; repeat the last entry. Overrides `delay`/`backoff`, with the same cap and jitter. | -| `backoff` | `1.0` | Multiplier applied after each failure (use `2` for exponential). | -| `max_delay` | `None` | Cap on the backoff wait (before jitter). | -| `jitter` | `0.0` | Up to this many random extra seconds, so many clients do not retry in lockstep. | +| `backoff` | `2.0` | Multiplier applied after each failure (use `2` for exponential). | +| `max_delay` | `30.0` | Cap on the backoff wait (before jitter). | +| `jitter` | `"equal"` | Choose between half and all of the capped wait. A numeric value adds up to that many seconds. | | `max_time` | `None` | Total time budget in seconds from the first attempt. | | `on` | `Exception` | Exception type(s) that trigger a retry. Anything else propagates immediately. | | `retry_if` | `None` | Extra predicate on the exception; retry only if it returns `True`. May be `async def` for async functions. | @@ -518,18 +521,16 @@ Sentry breadcrumbs so an error report shows what happened before the failure. Set `max_attempts`, `delay`, `backoff`, `max_delay`, `jitter`, `max_time`, `log_level` and `budget` once for the whole project with `python_wrap.config.configure(retry={...})`. See [Configuration](../configuration.md). -To try the 0.5.0 timing defaults in a scoped block: +To restore the 0.4.x timing defaults in a scoped block: ```python from python_wrap.config import configured -with configured(retry={"backoff": 2, "jitter": "equal", "max_delay": 30}): +with configured(retry={"backoff": 1, "jitter": 0, "max_delay": None}): # Decorate functions here to use these defaults. ... ``` -Setting any of `delay`, `backoff` or `jitter` here also silences the default-change warning. - ## Logging Each retry logs one message at `log_level` (default `WARNING`) on `logger`. Use `log_level=logging.INFO` to quiet it, `log_level=None` to turn it off, and `log_exc_info=True` to attach the traceback. diff --git a/docs/llms-full.txt b/docs/llms-full.txt index be9b01f..81628d2 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -3744,7 +3744,7 @@ The doctor reports codes PW001 to PW025 (the table lists them by group, not stri | PW023 | warning | `python_wrap.celery.check_visibility`: a blocking limiter, unbounded bulkhead queue, retry `max_time`, or an `idempotent_task` lease (`lease_ttl`) can outlive the broker's visibility timeout, so the broker delivers the task again while it still runs (for a lease: a redelivery finds the lease held and is re-queued until it expires). | | PW024 | warning | A retry layer has no backoff or jitter (`backoff=1` or no `jitter`): callers that fail together retry together, and with `--multiprocess` every worker does. Use `backoff=2, jitter="full"`. | | PW025 | warning | A retry on every `Exception` with neither `retry_if=` nor `retry_if_result=`: programming errors and non-transient failures are retried. Narrow `on=` or add a predicate. Fires together with PW003, which also covers a broad `on=` with only `retry_if_result=`. | -| PW026 | warning | `memoize` with a shared store that uses plain pickle (the implicit default, or `pickle.dumps`): anyone who can write the namespace can run code in every reader. Pass `dumps=`/`loads=` (for example `json_codec()`) or `configure(cache_codec="json")`. See [Shared caches](../caching/stores-and-credentials.md#codecs). | +| PW026 | warning | `memoize` with a shared store that uses plain pickle: anyone who can write the namespace can run code in every reader. Use `json_codec()` or `configure(cache_codec="json")`. See [Shared caches](../caching/stores-and-credentials.md#codecs). | | PW018 | warning | A python-wrap LLM retry wraps an SDK client (`llm_retry(client=...)`) whose own retries are still on: attempts multiply (4 x 3 = 12). See [OpenAI and Anthropic SDK clients](../ai/openai-anthropic.md#doctor-checks). | | PW019 | warning | A retry wraps a streamed LLM call (`stream_timeout`) without `resume_safe`: a replay after output started repeats text and half-done tool calls. | @@ -4334,7 +4334,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm A disabled integration was called. - `python_wrap.HealthRegistry`: `HealthRegistry()` Register named components; report structural state without calling user functions. -- `python_wrap.HttpRetryPolicy`: `HttpRetryPolicy(max_attempts: int = 3, delay: float = 0.5, backoff: float = 2.0, max_delay: float = 30.0, jitter: float | str = 0.0, statuses: frozenset[int] = frozenset({408, 425, 429, 500, 502, 503, 504}), methods: frozenset[str] = frozenset({'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PUT', 'TRACE'}), retry_on: tuple[type[BaseException], ...] = (ConnectionError, TimeoutError, OSError), retry_on_names: frozenset[str] = frozenset({'ClientConnectionError', 'ClientOSError', 'ConnectError', 'ConnectTimeout', 'ConnectionError', 'ReadTimeout', 'ServerDisconnectedError', 'Timeout', 'TransportError'}), respect_retry_after: bool = True, max_retry_after: float = 60.0, budget: RetryBudget | None = None, idempotency_header: str | None = 'Idempotency-Key', hint_jitter: float | None = None, min_delay: float = 0.0)` +- `python_wrap.HttpRetryPolicy`: `HttpRetryPolicy(max_attempts: int = 3, delay: float = 0.5, backoff: float = 2.0, max_delay: float = 30.0, jitter: float | str = 'equal', statuses: frozenset[int] = frozenset({408, 425, 429, 500, 502, 503, 504}), methods: frozenset[str] = frozenset({'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PUT', 'TRACE'}), retry_on: tuple[type[BaseException], ...] = (ConnectionError, TimeoutError, OSError), retry_on_names: frozenset[str] = frozenset({'ClientConnectionError', 'ClientOSError', 'ConnectError', 'ConnectTimeout', 'ConnectionError', 'ReadTimeout', 'ServerDisconnectedError', 'Timeout', 'TransportError'}), respect_retry_after: bool = True, max_retry_after: float = 60.0, budget: RetryBudget | None = None, idempotency_header: str | None = 'Idempotency-Key', hint_jitter: float | None = None, min_delay: float = 0.0)` What to retry, how long to wait, and when to stop, for HTTP calls. - `python_wrap.INJECTED` Constant: INJECTED @@ -4437,7 +4437,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm - `python_wrap.WebhookAlerter`: `WebhookAlerter(url: str, *, format: str = 'json', on: Iterable[str | CircuitState] = ('open',), cooldown: float = 300.0, timeout: float = 5.0, sender: Sender | None = None, include_recovery: bool = True, context: Mapping[str, Any] | None = None)` Post a chat message when a circuit breaker reaches a chosen state. - `python_wrap.__version__` - Constant: '0.4.2' + Constant: '0.5.0b1' - `python_wrap.ainvalidate_tags`: `ainvalidate_tags(*names: str, client: Any = None, require_shared: bool = False) -> int` `invalidate_tags` for ``redis.asyncio`` clients (amemoize with AsyncRedisStore). - `python_wrap.amap_iter`: `amap_iter(fn: Callable[[T], Awaitable[R]], items: Iterable[T] | AsyncIterable[T], *, limit: int, ordered: bool = True, return_exceptions: bool = False) -> AsyncGenerator[Any, None]` @@ -4788,9 +4788,9 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Bind task_id/name and a deadline from the task's time limit around task execution. - `python_wrap.celery.resilient_task`: `resilient_task(policy: Any = None, *, requeue_on: tuple[type[BaseException], ...] | None = None, delays: Sequence[float] | None = None, max_retries: int | None = None, requeue_when_limited: bool = True, **schedule: Any) -> Any` Run a bound task body through ``policy`` and re-queue it when the dependency is busy. -- `python_wrap.celery.retry_countdown`: `retry_countdown(task: Any, exc: BaseException | None = None, *, delays: Sequence[float] | None = None, delay: float = 5.0, backoff: float = 2.0, max_delay: float = 600.0, jitter: float | str = 0.0, respect_retry_after: bool = True, hint_jitter: float | None = None, min_delay: float = 0.0) -> float` +- `python_wrap.celery.retry_countdown`: `retry_countdown(task: Any, exc: BaseException | None = None, *, delays: Sequence[float] | None = None, delay: float = 5.0, backoff: float = 2.0, max_delay: float = 600.0, jitter: float | str | None = None, respect_retry_after: bool = True, hint_jitter: float | None = None, min_delay: float = 0.0) -> float` Seconds to wait before Celery runs ``task`` again, following python-wrap rules. -- `python_wrap.celery.retry_task`: `retry_task(task: Any, exc: BaseException, *, max_retries: int | None = None, delays: Sequence[float] | None = None, delay: float = 5.0, backoff: float = 2.0, max_delay: float = 600.0, jitter: float | str = 0.0, respect_retry_after: bool = True, hint_jitter: float | None = None, min_delay: float = 0.0) -> NoReturn` +- `python_wrap.celery.retry_task`: `retry_task(task: Any, exc: BaseException, *, max_retries: int | None = None, delays: Sequence[float] | None = None, delay: float = 5.0, backoff: float = 2.0, max_delay: float = 600.0, jitter: float | str | None = None, respect_retry_after: bool = True, hint_jitter: float | None = None, min_delay: float = 0.0) -> NoReturn` Ask Celery to retry ``task`` later with a `retry_countdown` schedule. - `python_wrap.celery.shared_breaker`: `shared_breaker(name: str, backend: Any, **options: Any) -> Any` A `CircuitBreaker` whose state lives in ``backend``, shared by every worker process. @@ -4841,7 +4841,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm - `python_wrap.decorators` Compatibility module: v0.1 imported everything from ``python_wrap.decorators``. - `python_wrap.decorators.__version__` - Constant: '0.4.2' + Constant: '0.5.0b1' - `python_wrap.devtools` Developer tools: deprecation warnings, mock data and decorator composition. - `python_wrap.django` @@ -5154,7 +5154,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm Type alias: python_wrap.policies.PolicySource - `python_wrap.policies.RedisSource`: `RedisSource(client: Any, key: str = 'python-wrap:policies')` One Redis string key holding the JSON mapping, shared by every replica. -- `python_wrap.policies.Watch`: `Watch(registry: PolicyRegistry, source: PolicySource, interval: float, *, strict: bool = False, jitter: float = 0)` +- `python_wrap.policies.Watch`: `Watch(registry: PolicyRegistry, source: PolicySource, interval: float, *, strict: bool = True, jitter: float = 0)` A running `PolicyRegistry.watch`; ``stop()`` ends it. - `python_wrap.policy.ROLES` Constant: ('observe', 'validate', 'fallback', 'cache', 'limiter', 'bulkhead', 'breaker', 'retry', 'timeout', 'guard') diff --git a/docs/project/threat-model.md b/docs/project/threat-model.md index bce5b08..c71e5d3 100644 --- a/docs/project/threat-model.md +++ b/docs/project/threat-model.md @@ -19,8 +19,8 @@ serialization and redaction surfaces. It complements [SECURITY.md](https://githu ## Serialization review **Pickle is only ever *loaded* from caches you configured.** `RedisStore` and -`AsyncRedisStore` default to `pickle.dumps`/`pickle.loads` so arbitrary Python results -round-trip. Unpickling attacker-controlled bytes executes code, so: +`AsyncRedisStore` default to JSON. An explicit pickle codec allows arbitrary Python results +to round-trip. Unpickling attacker-controlled bytes executes code, so: - Anyone able to write keys under the store's prefix can execute code in every process that reads the cache. Treat write access to that Redis as equivalent to code execution. @@ -28,8 +28,7 @@ round-trip. Unpickling attacker-controlled bytes executes code, so: (JSON-shaped results only), or `signed_pickle_codec(secret)` if Python objects must round-trip. A bad signature is a cache miss and emits `cache.rejected` before unpickling. `configure(cache_codec="json")` or `configure(cache_codec=("signed-pickle", ENV_NAME))` - sets the project default; `version=` isolates deployments. The implicit default is plain - pickle until 0.5.0 (a `FutureWarning`, doctor PW026). + sets the project default. Use `version=` to isolate deployments. Doctor reports plain pickle as PW026. - Keys are hashed (`sha256` of a pickle of the arguments, **dump only**), so a cache key never reveals arguments and never loads data. @@ -157,9 +156,7 @@ Regression tests: `tests/test_genai.py`, `tests/test_redaction.py`. ## Accepted risks -- `RedisStore`/`AsyncRedisStore` still default to pickle for compatibility, with a - `FutureWarning` when the default is implicit; the default becomes JSON in 0.5.0. Use signed pickle or JSON for - a shared Redis namespace. +- An explicitly configured plain pickle codec trusts all writers in its Redis namespace. - `PW_CHAOS` and policy files may name an exception as `module:Class`; resolving it imports that module. These are deployment configuration, never request input, and anything that is not an exception class is rejected. diff --git a/examples/llm_chaos.py b/examples/llm_chaos.py index 94ec556..9c19fbd 100644 --- a/examples/llm_chaos.py +++ b/examples/llm_chaos.py @@ -25,7 +25,14 @@ class BadModelOutput(ValueError): pass -@retry(max_attempts=5, delay=30.0, backoff=2, on=(RateLimitError, OverloadedError, BadModelOutput)) +@retry( + max_attempts=5, + delay=30.0, + backoff=2, + jitter=0, + max_delay=None, + on=(RateLimitError, OverloadedError, BadModelOutput), +) def ask_weather(question: str) -> dict[str, object]: reply = llm.complete(messages=[{"role": "user", "content": question}]) try: diff --git a/src/python_wrap/__init__.py b/src/python_wrap/__init__.py index 9404ed4..6508214 100644 --- a/src/python_wrap/__init__.py +++ b/src/python_wrap/__init__.py @@ -281,7 +281,7 @@ validate_args, ) -__version__ = "0.4.2" +__version__ = "0.5.0b1" # A library must never configure logging; this only silences "no handler" warnings. logging.getLogger("python_wrap").addHandler(logging.NullHandler()) diff --git a/src/python_wrap/_backend.py b/src/python_wrap/_backend.py index b9d33ed..8d2f58a 100644 --- a/src/python_wrap/_backend.py +++ b/src/python_wrap/_backend.py @@ -37,7 +37,7 @@ def _set_default(value: str | None) -> None: def default_mode() -> str: """The mode used when a backend was built with no explicit mode.""" - return _project_default or "raise" + return _project_default or "local" def resolve_mode(on_backend_error: str | None, fail_open: Any, owner: str, default: str) -> str: @@ -80,13 +80,6 @@ def __init__( raise ValueError(f"on_backend_error must be one of {BACKEND_ERROR_MODES}") if retry_backend_after < 0: raise ValueError("retry_backend_after must be >= 0") - if on_backend_error is None and _project_default is None: - warnings.warn( - "the shared backend error default changes from 'raise' to 'local' in 0.5.0; " - "pass on_backend_error= or configure(backend_errors=...) to pick a mode", - FutureWarning, - stacklevel=1, - ) self.kind, self.name = kind, name self._mode = on_backend_error self.retry_backend_after = retry_backend_after diff --git a/src/python_wrap/async_cache.py b/src/python_wrap/async_cache.py index 8f3d42b..3191e59 100644 --- a/src/python_wrap/async_cache.py +++ b/src/python_wrap/async_cache.py @@ -45,9 +45,9 @@ _ttl_seconds, ) from python_wrap.stores import ( - IMPLICIT_PICKLE_WARNING, KEY_FORMAT, InvalidSignature, + _json_dumps, json_codec, resolve_codec, ) @@ -172,15 +172,11 @@ class AsyncRedisStore: ``clear()`` that scans only this namespace and deletes in bounded batches (UNLINK where available). - Warning: - The default serializer is pickle. Only use it with a Redis instance you fully - trust; pass ``dumps``/``loads`` from `json_codec` otherwise. - Args: client: A ``redis.asyncio`` client (awaitable get/set/delete, optionally unlink, and an async-iterator ``scan_iter``). prefix: A nonempty namespace unique to one cached function. - dumps: Serializer for entries; defaults to pickle. + dumps: Serializer for entries; defaults to JSON when neither hook is given. loads: Deserializer matching dumps. key_format: Optional function turning a cache key into a stable external key. on_backend_error: ``"allow"`` (a miss; writes are dropped), ``"raise"`` or ``"local"`` @@ -215,13 +211,7 @@ def __init__( if dumps is None and loads is None: from python_wrap.config import get_config - codec = get_config().get("cache_codec") - if codec is None: - import warnings - - warnings.warn(IMPLICIT_PICKLE_WARNING, FutureWarning, stacklevel=2) - codec = (pickle.dumps, pickle.loads) - dumps, loads = resolve_codec(codec) + dumps, loads = resolve_codec(get_config().get("cache_codec") or "json") self.client, self.prefix = client, prefix + (f"v{version}:" if version else "") self.dumps, self.loads = dumps or pickle.dumps, loads or pickle.loads # Plain pickle on a shared store: doctor reports it (PW026). @@ -546,6 +536,9 @@ async def versions(names: list[str]) -> dict[str, str] | None: stale_s = _ttl_seconds(stale_ttl) exc_types = _exception_types(cache_exceptions) + codec_store = store.store if isinstance(store, ThreadedStore) else store + if exc_types and getattr(codec_store, "dumps", None) is _json_dumps: + raise TypeError("cache_exceptions requires a codec that can serialize exceptions") exc_ttl = _ttl_seconds(exception_ttl) if exception_ttl is not None else ttl def decorate(func: F) -> F: diff --git a/src/python_wrap/caching.py b/src/python_wrap/caching.py index 48c3700..57849a7 100644 --- a/src/python_wrap/caching.py +++ b/src/python_wrap/caching.py @@ -938,6 +938,11 @@ def memoize( raise ValueError("stale_ttl requires ttl") stale_s = _ttl_seconds(stale_ttl) exc_types = _exception_types(cache_exceptions) + if exc_types: + from python_wrap.stores import _json_dumps + + if getattr(store, "dumps", None) is _json_dumps: + raise TypeError("cache_exceptions requires a codec that can serialize exceptions") exc_ttl_s = _ttl_seconds(exception_ttl) if exception_ttl is not None else ttl_s if exc_types and ttl_fn is not None and exception_ttl is None: raise ValueError("exception_ttl is required when ttl is a callable") diff --git a/src/python_wrap/celery.py b/src/python_wrap/celery.py index f8bc980..1aa207b 100644 --- a/src/python_wrap/celery.py +++ b/src/python_wrap/celery.py @@ -16,7 +16,6 @@ from __future__ import annotations import contextvars -import warnings from collections.abc import Sequence from typing import Any, NoReturn @@ -223,7 +222,7 @@ def retry_countdown( delay: float = 5.0, backoff: float = 2.0, max_delay: float = 600.0, - jitter: float | str = 0.0, + jitter: float | str | None = None, respect_retry_after: bool = True, hint_jitter: float | None = None, min_delay: float = 0.0, @@ -271,6 +270,8 @@ def retry_countdown( """ from python_wrap.retry import _compute_delay, _hinted, _validate, retry_after_header + if jitter is None: + jitter = "equal" if delays is None else 0.0 _validate(1, delay, backoff, max_delay, jitter, None, hint_jitter, min_delay) if delays is not None and not delays: raise ValueError("delays must not be empty") @@ -295,7 +296,7 @@ def retry_task( delay: float = 5.0, backoff: float = 2.0, max_delay: float = 600.0, - jitter: float | str = 0.0, + jitter: float | str | None = None, respect_retry_after: bool = True, hint_jitter: float | None = None, min_delay: float = 0.0, @@ -471,25 +472,9 @@ def wrapper(*args: Any, **kwargs: Any) -> Any: return decorate -_DEFAULT_SCOPE_WARNED = False _SCOPES = (None, "delivery", "arguments") -def _warn_default_scope() -> None: - global _DEFAULT_SCOPE_WARNED - if _DEFAULT_SCOPE_WARNED: - return - _DEFAULT_SCOPE_WARNED = True - warnings.warn( - "idempotent_task() without scope= or key= keeps the arguments key in python-wrap " - "0.4.x; from 0.5.0 the default is scope='delivery' (one run per task id). Pass " - "scope='arguments' to keep today's behaviour or scope='delivery' to adopt the new " - "default.", - FutureWarning, - stacklevel=3, - ) - - def _requeues(task: Any) -> int: """How many times this delivery was already re-queued because its key was running.""" return int(_header(getattr(task, "request", None), "x_pw_requeues") or 0) @@ -545,8 +530,7 @@ def idempotent_task( - ``"arguments"``: the key is the task name plus its arguments. Two calls with the same arguments within ``ttl`` are one run: use it only for work that is truly repeated by content. - - ``None`` (the 0.4.x default): the arguments key, with a `FutureWarning`. From 0.5.0 the - default is ``"delivery"``. + - ``None`` (the default): use the delivery scope. ``key=`` overrides both scopes. @@ -588,8 +572,7 @@ def idempotent_task( allowed = ( requeue_limit if requeue_limit is not None else math.ceil(lease_seconds / requeue_delay) + 2 ) - if scope is None and key is None: - _warn_default_scope() + scope = scope or "delivery" def derive(task: Any, *args: Any, **kwargs: Any) -> str: if isinstance(key, str): @@ -636,7 +619,7 @@ def wrapper(*args: Any, **kwargs: Any) -> Any: wrapper.__python_wrap_layer__ = ( # type: ignore[attr-defined] "idempotent", - {"scope": scope or "arguments", "lease_ttl": lease_seconds}, + {"scope": scope, "lease_ttl": lease_seconds}, ) return wrapper diff --git a/src/python_wrap/doctor.py b/src/python_wrap/doctor.py index 7318b17..00ede6c 100644 --- a/src/python_wrap/doctor.py +++ b/src/python_wrap/doctor.py @@ -440,7 +440,7 @@ def _check( "memoize uses a shared store with plain pickle: anyone who can write the " "cache namespace can run code in every process that reads it. Pass " "dumps=/loads= (for example json_codec()), or configure(cache_codec='json') " - "for every store. Plain pickle becomes the JSON default in 0.5.0.", + "for every store. JSON is the default when no codec is configured.", ) ) found += _check_agents(layers, retries) diff --git a/src/python_wrap/http.py b/src/python_wrap/http.py index ebd9d4f..a0fe53d 100644 --- a/src/python_wrap/http.py +++ b/src/python_wrap/http.py @@ -114,7 +114,7 @@ class HttpRetryPolicy: delay: float = 0.5 backoff: float = 2.0 max_delay: float = 30.0 - jitter: float | str = 0.0 + jitter: float | str = "equal" statuses: frozenset[int] = RETRYABLE_STATUSES methods: frozenset[str] = IDEMPOTENT_METHODS retry_on: tuple[type[BaseException], ...] = (ConnectionError, TimeoutError, OSError) diff --git a/src/python_wrap/policies.py b/src/python_wrap/policies.py index b3c4df6..40bfa29 100644 --- a/src/python_wrap/policies.py +++ b/src/python_wrap/policies.py @@ -94,7 +94,7 @@ def __init__( source: PolicySource, interval: float, *, - strict: bool = False, + strict: bool = True, jitter: float = 0, ): self.registry, self.source, self.interval = registry, source, interval @@ -263,7 +263,7 @@ def _restart_watches(self) -> None: watch.ensure_running() def watch( - self, source: PolicySource, interval: float = 30, *, strict: bool = False, jitter: float = 0 + self, source: PolicySource, interval: float = 30, *, strict: bool = True, jitter: float = 0 ) -> Watch: """Poll ``source`` every ``interval`` seconds and apply each changed mapping. @@ -272,6 +272,9 @@ def watch( ``config.changed``. Runtime state carries over when a policy keeps its name: an open in-process breaker stays open under the new thresholds (shared breakers keep their state in the backend anyway). + + Startup raises if the first poll fails. Pass ``strict=False`` to keep polling + after a failed initial load. """ if interval <= 0: raise ValueError("interval must be positive") diff --git a/src/python_wrap/retry.py b/src/python_wrap/retry.py index 2490479..c9a725a 100644 --- a/src/python_wrap/retry.py +++ b/src/python_wrap/retry.py @@ -659,51 +659,23 @@ def _parse_hint(value: Any) -> float | None: return max(float(value), 0.0) -#: Set once the default-change FutureWarning has been emitted in this process. -_DEFAULT_CHANGE_WARNED = False -_TIMING_ARGUMENTS = ("delay", "backoff", "jitter") - - -def _warn_default_change(given: dict[str, Any], schedule: bool) -> None: - """Warn once per process when a call relies on the timing defaults that change in 0.5.0. - - An explicit ``delays=`` schedule replaces those defaults, so it never warns. - """ - global _DEFAULT_CHANGE_WARNED - if _DEFAULT_CHANGE_WARNED or schedule: - return - if any(given.get(name, _UNSET) is not _UNSET for name in _TIMING_ARGUMENTS): - return - if any( - config.retry_default(name, _UNSET, _MISSING) is not _MISSING for name in _TIMING_ARGUMENTS - ): - return - _DEFAULT_CHANGE_WARNED = True - warnings.warn( - "bare @retry waits 1 s, three times, with no jitter; the defaults change to " - "backoff=2, jitter='equal', max_delay=30 in 0.5.0; pass them explicitly or use " - "configure(retry=...) to keep the current behaviour", - FutureWarning, - stacklevel=4, - ) - - def _resolve_defaults(*, schedule: bool = False, **given: Any) -> dict[str, Any]: """Fill arguments left unset from `python_wrap.config` (read at decoration time).""" - _warn_default_change(given, schedule) - return {k: config.retry_default(k, v, _RETRY_FALLBACK[k]) for k, v in given.items()} + fallback = _SCHEDULE_FALLBACK if schedule else _RETRY_FALLBACK + return {k: config.retry_default(k, v, fallback[k]) for k, v in given.items()} _RETRY_FALLBACK: dict[str, Any] = { "max_attempts": 3, "delay": 1.0, - "backoff": 1.0, - "max_delay": None, - "jitter": 0.0, + "backoff": 2.0, + "max_delay": 30.0, + "jitter": "equal", "max_time": None, "log_level": logging.WARNING, "budget": None, } +_SCHEDULE_FALLBACK = {**_RETRY_FALLBACK, "max_delay": None, "jitter": 0.0} def _async_hooks(**hooks: Callable[..., Any] | None) -> list[str]: @@ -722,6 +694,7 @@ def __init__( delay: float, backoff: float, max_delay: float | None, + hint_max_delay: float | None, jitter: float | str, max_time: float | None, on: ExceptionTypes, @@ -743,6 +716,7 @@ def __init__( _check_budget(budget) self.name = name self.hint_jitter = None if hint_jitter is None else float(hint_jitter) + self.hint_max_delay = HINT_CEILING if hint_max_delay is None else hint_max_delay self.min_delay = float(min_delay) self.max_attempts = max_attempts self.delay = delay @@ -851,7 +825,7 @@ def _wait_for(self, attempt: int, exc: BaseException | None, result: Any = None) if hint is not None: return _hinted( hint, - HINT_CEILING if self.max_delay is None else self.max_delay, + self.hint_max_delay, self.hint_jitter, self.min_delay, ) @@ -1308,6 +1282,8 @@ def retry( "log_level": log_level, "budget": budget, } + hint_max_delay_arg = max_delay + hint_max_delay = config.retry_default("max_delay", hint_max_delay_arg, None) ds = _resolve_defaults(schedule=delays is not None, **given) max_attempts, delay, backoff = ds["max_attempts"], ds["delay"], ds["backoff"] max_delay, jitter, max_time, log_level = ( @@ -1339,7 +1315,7 @@ def retry( def decorate(f: Callable[P, R]) -> Callable[P, R]: stats = RetryStats() - def build_engine(resolved: dict[str, Any]) -> _Engine: + def build_engine(resolved: dict[str, Any], hint_cap: float | None) -> _Engine: return _Engine( _core.qualname(f), on=on, @@ -1353,12 +1329,14 @@ def build_engine(resolved: dict[str, Any]) -> _Engine: log_values=log_values, stats=stats, hint_jitter=hint_jitter, + hint_max_delay=hint_cap, min_delay=min_delay, **resolved, ) - frozen_engine = build_engine(ds) + frozen_engine = build_engine(ds, hint_max_delay) live_engine: tuple[dict[str, Any], _Engine] | None = None + fallback = _SCHEDULE_FALLBACK if delays is not None else _RETRY_FALLBACK def current_engine() -> _Engine: nonlocal live_engine @@ -1370,9 +1348,10 @@ def current_engine() -> _Engine: return cached[1] engine = build_engine( { - name: snapshot.get(name, _RETRY_FALLBACK[name]) if value is _UNSET else value + name: snapshot.get(name, fallback[name]) if value is _UNSET else value for name, value in given.items() - } + }, + snapshot.get("max_delay") if hint_max_delay_arg is _UNSET else hint_max_delay_arg, ) live_engine = snapshot, engine return engine @@ -1659,6 +1638,7 @@ def retrying( ... with attempt: ... do_work() # doctest: +SKIP """ + hint_max_delay = config.retry_default("max_delay", max_delay, None) ds = _resolve_defaults( schedule=delays is not None, max_attempts=max_attempts, @@ -1699,6 +1679,7 @@ def retrying( log_values=log_values, stats=RetryStats(), hint_jitter=hint_jitter, + hint_max_delay=hint_max_delay, min_delay=min_delay, ) ) diff --git a/src/python_wrap/stores.py b/src/python_wrap/stores.py index d6b7310..3ebece0 100644 --- a/src/python_wrap/stores.py +++ b/src/python_wrap/stores.py @@ -7,11 +7,11 @@ import hashlib import hmac +import json import math import os import pickle import re -import warnings from collections.abc import Callable, Hashable from typing import Any @@ -25,11 +25,6 @@ SIGNED_PICKLE = "signed-pickle" """Codec name used in ``cache_codec=("signed-pickle", ENV_NAME)``.""" -IMPLICIT_PICKLE_WARNING = ( - "implicit pickle cache codec is deprecated and becomes JSON in 0.5.0; pass dumps=/loads= " - "(for example json_codec()) or configure(cache_codec='json')" -) - class InvalidSignature(ValueError): """A cache entry failed authentication.""" @@ -53,11 +48,13 @@ def loads(data: bytes) -> Any: return dumps, loads +def _json_dumps(value: Any) -> bytes: + return json.dumps(value, separators=(",", ":")).encode() + + def json_codec() -> tuple[Callable[[Any], bytes], Callable[[bytes], Any]]: """Return a JSON codec for cache entries with JSON-compatible values.""" - import json - - return lambda value: json.dumps(value, separators=(",", ":")).encode(), json.loads + return _json_dumps, json.loads def resolve_codec(value: Any) -> tuple[Callable[[Any], bytes], Callable[[bytes], Any]]: @@ -104,7 +101,7 @@ class RedisStore: Args: client: A synchronous Redis-compatible client. prefix: A nonempty namespace unique to one cached function. - dumps: Serializer for entries; defaults to pickle (trusted Redis data only). + dumps: Serializer for entries; defaults to JSON when neither hook is given. loads: Deserializer matching dumps. key_format: Optional function turning a cache key into a stable external key. on_backend_error: ``"allow"`` (a miss; writes are dropped), ``"raise"`` or ``"local"`` @@ -143,11 +140,7 @@ def __init__( if dumps is None and loads is None: from python_wrap.config import get_config - codec = get_config().get("cache_codec") - if codec is None: - warnings.warn(IMPLICIT_PICKLE_WARNING, FutureWarning, stacklevel=2) - codec = (pickle.dumps, pickle.loads) - dumps, loads = resolve_codec(codec) + dumps, loads = resolve_codec(get_config().get("cache_codec") or "json") self.client, self.prefix = client, prefix + (f"v{version}:" if version else "") self.dumps, self.loads = dumps or pickle.dumps, loads or pickle.loads # Plain pickle on a shared store lets anyone who can write the namespace run code diff --git a/tests/e2e/test_e2e_http_client.py b/tests/e2e/test_e2e_http_client.py index e697ad3..44a303b 100644 --- a/tests/e2e/test_e2e_http_client.py +++ b/tests/e2e/test_e2e_http_client.py @@ -59,7 +59,7 @@ def breaker_for(self, host: str) -> CircuitBreaker: ) @timeout(30) - @retry(max_attempts=4, delay=0.2, backoff=2, max_delay=5, on=TRANSIENT) + @retry(max_attempts=4, delay=0.2, jitter=0, backoff=2, max_delay=5, on=TRANSIENT) @rate_limit(5, 1.0, block=True, key=lambda self, url: host_of(url)) def get(self, url: str) -> int: return self.breaker_for(host_of(url)).call(self._send, url) diff --git a/tests/test_async_cache.py b/tests/test_async_cache.py index 2a2e989..5103377 100644 --- a/tests/test_async_cache.py +++ b/tests/test_async_cache.py @@ -4,6 +4,7 @@ import asyncio import logging +import pickle from collections.abc import AsyncIterator from typing import Any @@ -342,7 +343,7 @@ async def test_redis_store_roundtrip_and_ttl() -> None: assert isinstance(store, AsyncCacheStore) assert await store.get(("k",)) is None await store.set(("k",), ("v", None), 1.5) - assert await store.get(("k",)) == ("v", None) + assert await store.get(("k",)) == ["v", None] (stored_key,) = client.data assert stored_key.startswith("p:k2:") and "k" not in stored_key[5:] assert client.expiries[stored_key] == 1500 @@ -423,7 +424,7 @@ async def test_amemoize_with_pickle_redis_store() -> None: client = FakeAsyncRedis() calls = 0 - @amemoize(ttl=60, store=AsyncRedisStore(client, "pk:")) + @amemoize(ttl=60, store=AsyncRedisStore(client, "pk:", dumps=pickle.dumps, loads=pickle.loads)) async def f(n: int) -> tuple[int, int]: nonlocal calls calls += 1 diff --git a/tests/test_attempt_history.py b/tests/test_attempt_history.py index 55466bb..1f8bd8f 100644 --- a/tests/test_attempt_history.py +++ b/tests/test_attempt_history.py @@ -16,7 +16,7 @@ def test_gave_up_exception_carries_one_record_per_attempt(fake_clock): - @retry(max_attempts=3, delay=1, backoff=2, on=ConnectionError) + @retry(jitter=0, max_attempts=3, delay=1, backoff=2, on=ConnectionError) def fetch() -> None: fake_clock.advance(0.5) raise ConnectionError("secret-host refused") diff --git a/tests/test_backend_errors.py b/tests/test_backend_errors.py index 6793c99..9264be6 100644 --- a/tests/test_backend_errors.py +++ b/tests/test_backend_errors.py @@ -35,14 +35,13 @@ def call() -> int: assert health.summary()["status"] == "degraded" -def test_raise_is_the_default_and_configure_changes_it() -> None: - with pytest.warns(FutureWarning, match="from 'raise' to 'local' in 0.5.0"): - breaker = CircuitBreaker(name="g1-raise", backend=RedisBreakerState(Dead())) - with pytest.raises(ConnectionError): - breaker.call(lambda: 1) - with configured(backend_errors="allow"): - allowed = CircuitBreaker(name="g1-cfg", backend=RedisBreakerState(Dead())) - assert allowed.call(lambda: 2) == 2 +def test_local_is_the_default_and_configure_can_restore_raise() -> None: + breaker = CircuitBreaker(name="g1-default", backend=RedisBreakerState(Dead())) + assert breaker.call(lambda: 1) == 1 + with configured(backend_errors="raise"): + strict = CircuitBreaker(name="g1-strict", backend=RedisBreakerState(Dead())) + with pytest.raises(ConnectionError): + strict.call(lambda: 2) def test_window_local_fallback_enforces_limit_in_process() -> None: diff --git a/tests/test_backend_recovered.py b/tests/test_backend_recovered.py index b4bfcad..250e97f 100644 --- a/tests/test_backend_recovered.py +++ b/tests/test_backend_recovered.py @@ -14,6 +14,7 @@ from python_wrap.caching import memoize from python_wrap.circuit import CircuitBreaker +from python_wrap.config import configured from python_wrap.coordination import RedisLock from python_wrap.events import listening from python_wrap.llm_shared import RedisTokenWindow @@ -65,9 +66,9 @@ def use() -> None: @pytest.mark.parametrize("kind", KINDS) def test_backend_recovered_event_per_kind(kind, failing_then_recovering_client): proxy = failing_then_recovering_client - use = _operation(kind, proxy) events = [] - with listening(events.append): + with configured(backend_errors="raise"), listening(events.append): + use = _operation(kind, proxy) use() # healthy: no recovery event yet proxy.down = True with pytest.raises(ConnectionError): diff --git a/tests/test_backend_rules.py b/tests/test_backend_rules.py index e71a9a7..8f9674d 100644 --- a/tests/test_backend_rules.py +++ b/tests/test_backend_rules.py @@ -197,7 +197,9 @@ def release(self, key: str, token: str) -> bool: assert bulkhead.active == 0 assert backend.attempts == 2 - strict = SharedBulkhead(1, backend=QueueFails(), name="bh-strict", max_waiting=1) + strict = SharedBulkhead( + 1, backend=QueueFails(), name="bh-strict", max_waiting=1, on_backend_error="raise" + ) with pytest.raises(ConnectionError): strict.acquire() @@ -230,7 +232,7 @@ def test_quota_remaining_and_reset_use_monitor() -> None: assert quota.remaining == 10 assert _names(events).count("backend.error") == 1 - strict = Quota(10, name="q-strict", client=Dead(), key="q-strict") + strict = Quota(10, name="q-strict", client=Dead(), key="q-strict", on_backend_error="raise") with pytest.raises(ConnectionError): _ = strict.remaining with pytest.raises(ConnectionError): @@ -272,7 +274,11 @@ def use() -> Any: def test_raise_mode_logs_once_per_interval(caplog: pytest.LogCaptureFixture) -> None: - breaker = CircuitBreaker(name=f"log-{uuid.uuid4().hex[:6]}", backend=RedisBreakerState(Dead())) + breaker = CircuitBreaker( + name=f"log-{uuid.uuid4().hex[:6]}", + backend=RedisBreakerState(Dead()), + on_backend_error="raise", + ) caplog.set_level(logging.WARNING) failures = 0 for _ in range(1000): @@ -299,6 +305,5 @@ def counting() -> dict[str, Any]: monkeypatch.setattr(config, "get_config", counting) breaker = CircuitBreaker(name=f"mode-{uuid.uuid4().hex[:6]}", backend=RedisBreakerState(Dead())) for _ in range(100): - with pytest.raises(ConnectionError): - breaker.call(lambda: 1) + assert breaker.call(lambda: 1) == 1 assert calls == 0 diff --git a/tests/test_cache_codec.py b/tests/test_cache_codec.py index 2bed8c5..5a5fde5 100644 --- a/tests/test_cache_codec.py +++ b/tests/test_cache_codec.py @@ -95,25 +95,26 @@ def test_configure_rejects_unknown_codec_values(): configure(cache_codec=("signed-pickle", 5)) -def test_implicit_pickle_warns_visibly(): - with warnings.catch_warnings(record=True) as record: - warnings.simplefilter("always") - store = RedisStore(FakeRedis(), "w:") - futures = [w for w in record if issubclass(w.category, FutureWarning)] - assert len(futures) == 1 - assert "0.5.0" in str(futures[0].message) - assert "json_codec" in str(futures[0].message) - assert store.implicit_pickle is True - - -def test_implicit_pickle_warns_on_async_store(): - class AsyncClient: - pass - - with warnings.catch_warnings(record=True) as record: - warnings.simplefilter("always") - AsyncRedisStore(AsyncClient(), "w:") - assert any(issubclass(w.category, FutureWarning) for w in record) +@pytest.mark.parametrize("store_type", [RedisStore, AsyncRedisStore]) +def test_shared_cache_defaults_to_json(store_type): + store = store_type(FakeRedis(), "json:") + assert store.dumps([1, 2]) == b"[1,2]" + assert store.loads(b"[1,2]") == [1, 2] + assert not store.implicit_pickle + + +def test_json_stores_refuse_exception_caching(): + from python_wrap import amemoize, memoize + from python_wrap.async_cache import ThreadedStore + + store = RedisStore(FakeRedis(), "json:") + for decorator, backend in ( + (memoize, store), + (amemoize, AsyncRedisStore(FakeRedis(), "json-async:")), + (amemoize, ThreadedStore(store)), + ): + with pytest.raises(TypeError, match="serialize exceptions"): + decorator(store=backend, cache_exceptions=LookupError) def test_explicit_codec_does_not_warn(): diff --git a/tests/test_celery_helpers.py b/tests/test_celery_helpers.py index 79264e9..3ca217d 100644 --- a/tests/test_celery_helpers.py +++ b/tests/test_celery_helpers.py @@ -31,7 +31,7 @@ def retry(self, **options: object) -> BaseException: @pytest.mark.parametrize(("retries", "expected"), [(0, 5), (1, 10), (2, 20), (3, 40), (9, 600)]) def test_exponential_schedule_by_celery_retry_count(retries, expected): - assert retry_countdown(FakeTask(retries)) == expected + assert expected / 2 <= retry_countdown(FakeTask(retries)) <= expected def test_explicit_delays_repeat_the_last_entry(): @@ -48,7 +48,7 @@ def test_waits_requested_by_the_failure_win_and_are_capped(): http_error.response = response # type: ignore[attr-defined] assert retry_countdown(task, http_error) == 120 assert retry_countdown(task, http_error, max_delay=60) == 60 - assert retry_countdown(task, http_error, respect_retry_after=False) == 5 + assert retry_countdown(task, http_error, respect_retry_after=False, jitter=0) == 5 def test_hinted_waits_take_hint_jitter_and_min_delay(): @@ -78,7 +78,7 @@ def test_jitter_is_bounded(): def test_task_without_request_counts_as_first_retry(): - assert retry_countdown(object()) == 5 + assert 2.5 <= retry_countdown(object()) <= 5 @pytest.mark.parametrize( diff --git a/tests/test_celery_tasks.py b/tests/test_celery_tasks.py index 7d94a62..ea2e525 100644 --- a/tests/test_celery_tasks.py +++ b/tests/test_celery_tasks.py @@ -186,14 +186,17 @@ def body(self: Task, n: int) -> int: assert runs == [9] -def test_default_scope_warns_in_0_4(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(pw_celery, "_DEFAULT_SCOPE_WARNED", False) - with pytest.warns(FutureWarning, match="0.5.0"): - idempotent_task()(lambda self: 1) - with warnings.catch_warnings(record=True) as seen: - warnings.simplefilter("always") - idempotent_task()(lambda self: 1) - assert not [w for w in seen if issubclass(w.category, FutureWarning)] +def test_default_scope_uses_the_delivery_id() -> None: + runs = [] + + @idempotent_task() + def body(self: Task, n: int) -> int: + runs.append(n) + return n + + assert body(Task("default-first"), 9) == body(Task("default-first"), 9) == 9 + assert body(Task("default-second"), 9) == 9 + assert runs == [9, 9] def test_key_overrides_scope_without_warning() -> None: diff --git a/tests/test_chaos.py b/tests/test_chaos.py index d93cbbe..fc93706 100644 --- a/tests/test_chaos.py +++ b/tests/test_chaos.py @@ -262,7 +262,10 @@ def test_events() -> None: def test_policy_inner_retry_recovers(fake_clock) -> None: # type: ignore[no-untyped-def] - @policy(retry=retry(max_attempts=3, delay=1, on=ConnectionError), inner=fault_point("pol.x")) + @policy( + retry=retry(jitter=0, backoff=1, max_attempts=3, delay=1, on=ConnectionError), + inner=fault_point("pol.x"), + ) def fetch() -> str: return "data" diff --git a/tests/test_config.py b/tests/test_config.py index 394c10a..385a3f2 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -76,7 +76,7 @@ def test_validation() -> None: def test_retry_defaults_apply_and_explicit_wins(fake_clock: FakeClock) -> None: - configure(retry={"max_attempts": 5, "delay": 0.5, "backoff": 2.0}) + configure(retry={"max_attempts": 5, "delay": 0.5, "backoff": 2.0, "jitter": 0}) f = Flaky(3) assert retry(f)() == "ok" assert fake_clock.sleeps == [0.5, 1.0, 2.0] @@ -123,7 +123,7 @@ def test_retry_default_none_disables_log(caplog: pytest.LogCaptureFixture) -> No def test_retrying_uses_defaults(fake_clock: FakeClock) -> None: - configure(retry={"max_attempts": 2, "delay": 4}) + configure(retry={"max_attempts": 2, "delay": 4, "jitter": 0}) f = Flaky(10) with pytest.raises(ValueError): for attempt in retrying(): @@ -251,7 +251,7 @@ def f(xx: int, yy: int, password: str) -> None: ... def test_retry_respects_deadline(fake_clock: FakeClock) -> None: f = Flaky(100) with deadline(5), pytest.raises(ValueError): - retry(f, max_attempts=None, delay=2)() + retry(f, max_attempts=None, delay=2, backoff=1, jitter=0)() # sleeps 2, 2 (t=4); the next 2s would run past the 5s deadline assert fake_clock.sleeps == [2, 2] assert f.calls == 3 @@ -267,7 +267,7 @@ def test_retry_deadline_already_expired(fake_clock: FakeClock) -> None: def test_retry_without_deadline_unchanged(fake_clock: FakeClock) -> None: f = Flaky(2) - assert retry(f, delay=100)() == "ok" + assert retry(f, delay=100, backoff=1, jitter=0, max_delay=None)() == "ok" assert fake_clock.sleeps == [100, 100] @@ -276,7 +276,7 @@ def test_async_retry_respects_deadline(fake_clock: FakeClock) -> None: f = Flaky(100) - @retry(max_attempts=None, delay=2) + @retry(max_attempts=None, delay=2, backoff=1, jitter=0) async def call() -> str: return f() @@ -292,7 +292,7 @@ async def run() -> None: def test_retrying_block_respects_deadline(fake_clock: FakeClock) -> None: f = Flaky(100) with deadline(1), pytest.raises(ValueError): - for attempt in retrying(max_attempts=None, delay=2): + for attempt in retrying(max_attempts=None, delay=2, backoff=1, jitter=0): with attempt: f() assert f.calls == 1 diff --git a/tests/test_doctor.py b/tests/test_doctor.py index 2e7da6a..2a0cca8 100644 --- a/tests/test_doctor.py +++ b/tests/test_doctor.py @@ -3,9 +3,9 @@ from __future__ import annotations import asyncio +import pickle import sys import types -import warnings import pytest @@ -73,7 +73,7 @@ def test_unbounded_retry_is_an_error(): def test_pw024_without_multiprocess_flag(): - stack = policy(retry=retry(on=OSError)) + stack = policy(retry=retry(on=OSError, backoff=1, jitter=0)) assert "PW024" in codes(stack.explain()) assert "PW024" in codes(explain(stack, multiprocess=True)) safe = policy(retry=retry(on=OSError, backoff=2, jitter="full")) @@ -501,9 +501,7 @@ def scan_iter(self, match=None, count=None): def test_pw026_implicit_pickle(): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", FutureWarning) - store = RedisStore(_FakeRedis(), "d:") + store = RedisStore(_FakeRedis(), "d:", dumps=pickle.dumps, loads=pickle.loads) @memoize(store=store, ttl=60) def price(sku: str) -> float: @@ -535,9 +533,7 @@ def clear(self): def __len__(self): return 0 - with warnings.catch_warnings(): - warnings.simplefilter("ignore", FutureWarning) - inner = RedisStore(_FakeRedis(), "d:") + inner = RedisStore(_FakeRedis(), "d:", dumps=pickle.dumps, loads=pickle.loads) @memoize(store=Wrapped(inner), ttl=60) def price(sku: str) -> float: diff --git a/tests/test_http.py b/tests/test_http.py index 01eef5b..0746bba 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -164,12 +164,12 @@ def test_retry_after_http_date() -> None: def test_retry_after_ignored_when_disabled() -> None: - policy = HttpRetryPolicy(respect_retry_after=False, delay=1) + policy = HttpRetryPolicy(jitter=0, respect_retry_after=False, delay=1) assert retry_delay(Response(429, {"Retry-After": "99"}), 1, policy) == 1.0 def test_backoff_cap_and_jitter() -> None: - policy = HttpRetryPolicy(delay=1, backoff=2, max_delay=5) + policy = HttpRetryPolicy(jitter=0, delay=1, backoff=2, max_delay=5) assert [retry_delay(Response(503), n, policy) for n in (1, 2, 3, 4)] == [1, 2, 4, 5] jittery = HttpRetryPolicy(delay=1, jitter=0.5) assert 1.0 <= (retry_delay(Response(503), 1, jittery) or 0) <= 1.5 @@ -181,7 +181,7 @@ def test_backoff_cap_and_jitter() -> None: def test_sync_retries_status_and_closes_discarded(fake_clock: FakeClock) -> None: bad1, bad2, good = Response(503), Response(502), Response(200) inner = Inner(bad1, bad2, good) - transport = RetryTransport(inner, HttpRetryPolicy(delay=1, backoff=2)) + transport = RetryTransport(inner, HttpRetryPolicy(jitter=0, delay=1, backoff=2)) assert transport.handle_request(Request()) is good assert fake_clock.sleeps == [1, 2] assert bad1.closed and bad2.closed and not good.closed @@ -189,7 +189,7 @@ def test_sync_retries_status_and_closes_discarded(fake_clock: FakeClock) -> None def test_sync_returns_last_response_when_exhausted(fake_clock: FakeClock) -> None: responses = [Response(503) for _ in range(3)] - transport = RetryTransport(Inner(*responses), HttpRetryPolicy(delay=1)) + transport = RetryTransport(Inner(*responses), HttpRetryPolicy(jitter=0, delay=1)) assert transport.handle_request(Request()) is responses[-1] assert fake_clock.sleeps == [1, 2] assert not responses[-1].closed @@ -197,7 +197,7 @@ def test_sync_returns_last_response_when_exhausted(fake_clock: FakeClock) -> Non def test_sync_retries_exception_then_raises(fake_clock: FakeClock) -> None: inner = Inner(ConnectionError("a"), ConnectionError("b"), ConnectionError("c")) - transport = RetryTransport(inner, HttpRetryPolicy(delay=1)) + transport = RetryTransport(inner, HttpRetryPolicy(jitter=0, delay=1)) with pytest.raises(ConnectionError, match="c"): transport.handle_request(Request()) assert inner.calls == 3 @@ -261,7 +261,7 @@ def test_sync_budget_allows_when_available(fake_clock: FakeClock) -> None: def test_sync_deadline_respected(fake_clock: FakeClock) -> None: resp = Response(503) inner = Inner(Response(503), resp) - transport = RetryTransport(inner, HttpRetryPolicy(delay=1, backoff=10)) + transport = RetryTransport(inner, HttpRetryPolicy(jitter=0, delay=1, backoff=10)) with deadline(5): # first wait 1s fits; second wait 10s would outlast the 4s left assert transport.handle_request(Request()) is resp @@ -272,7 +272,7 @@ def test_sync_events(fake_clock: FakeClock) -> None: seen: list[Any] = [] inner = Inner(Response(503), Response(200)) with listening(seen.append): - RetryTransport(inner, HttpRetryPolicy(delay=1)).handle_request(Request()) + RetryTransport(inner, HttpRetryPolicy(jitter=0, delay=1)).handle_request(Request()) names = [e.name for e in seen] assert names == ["retry.attempt_failed", "retry.succeeded"] assert seen[0].function == "http GET api.example.com" @@ -280,9 +280,9 @@ def test_sync_events(fake_clock: FakeClock) -> None: seen.clear() with listening(seen.append): - RetryTransport(Inner(Response(503)), HttpRetryPolicy(max_attempts=1)).handle_request( - Request() - ) + RetryTransport( + Inner(Response(503)), HttpRetryPolicy(jitter=0, max_attempts=1) + ).handle_request(Request()) assert [e.name for e in seen] == ["retry.gave_up"] @@ -298,7 +298,7 @@ def test_sync_close_and_context() -> None: async def test_async_retries_and_closes(fake_clock: FakeClock) -> None: bad, good = Response(503), Response(200) - transport = AsyncRetryTransport(Inner(bad, good), HttpRetryPolicy(delay=2)) + transport = AsyncRetryTransport(Inner(bad, good), HttpRetryPolicy(jitter=0, delay=2)) assert await transport.handle_async_request(Request()) is good assert fake_clock.sleeps == [2] assert bad.closed @@ -381,7 +381,7 @@ def test_mount_retries_retries_and_mounts( bad, good = Response(503), Response(200) base.script = [bad, good] session = FakeSession() - adapter = mount_retries(session, HttpRetryPolicy(delay=3)) + adapter = mount_retries(session, HttpRetryPolicy(jitter=0, delay=3)) assert set(session.mounts) == {"http://", "https://"} assert session.mounts["https://"] is adapter assert isinstance(adapter, base) @@ -422,7 +422,7 @@ def __init__(self, status: int, headers: dict[str, str] | None = None) -> None: async def test_http_retry_async_status_and_retry_after(fake_clock: FakeClock) -> None: script = [AioResponse(429, {"Retry-After": "4"}), AioResponse(503), AioResponse(200)] - @http_retry(HttpRetryPolicy(delay=1)) + @http_retry(HttpRetryPolicy(jitter=0, delay=1)) async def fetch() -> AioResponse: return script.pop(0) @@ -433,7 +433,7 @@ async def fetch() -> AioResponse: async def test_http_retry_exceptions_by_name(fake_clock: FakeClock) -> None: calls = 0 - @http_retry(HttpRetryPolicy(delay=1)) + @http_retry(HttpRetryPolicy(jitter=0, delay=1)) async def fetch() -> AioResponse: nonlocal calls calls += 1 @@ -446,7 +446,7 @@ async def fetch() -> AioResponse: def test_http_retry_exhausted_returns_last(fake_clock: FakeClock) -> None: - @http_retry(HttpRetryPolicy(max_attempts=2, delay=1)) + @http_retry(HttpRetryPolicy(jitter=0, max_attempts=2, delay=1)) def fetch() -> AioResponse: return AioResponse(503) @@ -520,7 +520,7 @@ def handler(request: Any) -> Any: return httpx.Response(503 if attempts < 3 else 200, json={"ok": True}) client = httpx.Client( - transport=RetryTransport(httpx.MockTransport(handler), HttpRetryPolicy(delay=1)) + transport=RetryTransport(httpx.MockTransport(handler), HttpRetryPolicy(jitter=0, delay=1)) ) assert client.get("https://api.example.com/x").status_code == 200 assert attempts == 3 and fake_clock.sleeps == [1, 2] @@ -546,7 +546,10 @@ def handler(request: Any) -> Any: def test_retry_after_garbage_and_odd_values_are_ignored() -> None: for bad in ("soon", "", "1_0", "nan", "inf", "Mon, 99 Foo 2020 99:99:99 GMT"): - assert retry_delay(Response(503, {"Retry-After": bad}), 1, HttpRetryPolicy(delay=2)) == 2.0 + assert ( + retry_delay(Response(503, {"Retry-After": bad}), 1, HttpRetryPolicy(jitter=0, delay=2)) + == 2.0 + ) def test_retry_after_hint_jitter_and_min_delay_options() -> None: diff --git a/tests/test_llm_testing.py b/tests/test_llm_testing.py index f1ef804..a5db3d7 100644 --- a/tests/test_llm_testing.py +++ b/tests/test_llm_testing.py @@ -135,7 +135,7 @@ def test_fake_stream_error_after_chunks_and_validation() -> None: def test_rate_limit_fault_with_retry_and_times() -> None: llm = fake_llm(["done"]) - @retry(max_attempts=4, delay=1.0, on=RateLimitError) + @retry(jitter=0, backoff=1, max_delay=None, max_attempts=4, delay=1.0, on=RateLimitError) def ask() -> str: return llm.complete(messages=MSG).text @@ -297,7 +297,14 @@ def test_millisecond_agent_test() -> None: llm = fake_llm(["final answer"], usage=(12, 4)) - @retry(max_attempts=5, delay=60.0, backoff=2, on=(RateLimitError, OverloadedError)) + @retry( + jitter=0, + max_delay=None, + max_attempts=5, + delay=60.0, + backoff=2, + on=(RateLimitError, OverloadedError), + ) def agent() -> str: return llm.complete(messages=MSG).text diff --git a/tests/test_local_state.py b/tests/test_local_state.py index f9fef6f..f18e27b 100644 --- a/tests/test_local_state.py +++ b/tests/test_local_state.py @@ -173,7 +173,7 @@ def test_validation(tmp_path): def test_error_propagates_not_healthy(tmp_path): backend = SQLiteBreakerState(tmp_path / "missing" / "dir" / "b.db") - breaker = CircuitBreaker(name="x", backend=backend) + breaker = CircuitBreaker(name="x", backend=backend, on_backend_error="raise") with pytest.raises(sqlite3.OperationalError): breaker.call(lambda: 1) diff --git a/tests/test_policy_watch.py b/tests/test_policy_watch.py index 39adba3..313bc7b 100644 --- a/tests/test_policy_watch.py +++ b/tests/test_policy_watch.py @@ -138,8 +138,10 @@ def test_global_registry_reports_generations_in_health() -> None: assert report["policies"]["generations"]["health-probe"] >= 1 -def test_strict_watch_rejects_invalid_source_at_start(tmp_path: Path) -> None: +def test_watch_rejects_invalid_source_at_start_by_default(tmp_path: Path) -> None: path = tmp_path / "policies.json" path.write_text("{", encoding="utf-8") with pytest.raises(json.JSONDecodeError): - PolicyRegistry().watch(FileSource(path), strict=True) + PolicyRegistry().watch(FileSource(path)) + watch = PolicyRegistry().watch(FileSource(path), strict=False) + watch.stop() diff --git a/tests/test_retry.py b/tests/test_retry.py index 2f25fd7..fdc78e9 100644 --- a/tests/test_retry.py +++ b/tests/test_retry.py @@ -35,6 +35,12 @@ from python_wrap.testing import disable_retries, fast_mode +@pytest.fixture(autouse=True) +def deterministic_retry_timing(): + with configured(retry={"backoff": 1, "jitter": 0, "max_delay": None}): + yield + + class Flaky: """Fails ``failures`` times, then returns ``"ok"``.""" diff --git a/tests/test_retry_schedules.py b/tests/test_retry_schedules.py index 20d58a0..b8aba09 100644 --- a/tests/test_retry_schedules.py +++ b/tests/test_retry_schedules.py @@ -3,16 +3,13 @@ from __future__ import annotations import asyncio -import importlib import random -import warnings from typing import Any import pytest from conftest import FakeClock from python_wrap import deadline, retry, retrying -from python_wrap.config import configured @pytest.mark.parametrize("inline", [False, True]) @@ -123,81 +120,15 @@ async def job() -> None: await task -@pytest.fixture -def fresh_default_warning(monkeypatch: pytest.MonkeyPatch) -> None: - """Reset the once-per-process default-change flag so each test sees the first warning.""" - module = importlib.import_module("python_wrap.retry") - monkeypatch.setattr(module, "_DEFAULT_CHANGE_WARNED", False) - - -def _default_change_warnings( - caught: list[warnings.WarningMessage], -) -> list[warnings.WarningMessage]: - return [w for w in caught if issubclass(w.category, FutureWarning)] - - -@pytest.mark.usefixtures("fresh_default_warning") -def test_bare_retry_warns_about_default_change() -> None: - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("default") - - @retry - def first() -> None: ... - - @retry(max_attempts=5) - def second() -> None: ... - - found = _default_change_warnings(caught) - assert len(found) == 1 - message = str(found[0].message) - assert "0.5.0" in message and "backoff=2" in message and "jitter='equal'" in message - assert found[0].filename == __file__ - - -@pytest.mark.usefixtures("fresh_default_warning") -def test_bare_retry_warns_once_per_process() -> None: - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - for _ in range(3): - - @retry - def bare() -> None: ... - - assert len(_default_change_warnings(caught)) == 1 - - -@pytest.mark.usefixtures("fresh_default_warning") -def test_explicit_arguments_do_not_warn() -> None: - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - - @retry(delay=0.5) - def with_delay() -> None: ... - - @retry(backoff=1) - def with_backoff() -> None: ... - - @retry(jitter="full") - def with_jitter() -> None: ... - - @retry(delays=[1, 2]) - def with_schedule() -> None: ... - - with configured(retry={"delay": 2.0}): - - @retry - def configured_delay() -> None: ... - - assert _default_change_warnings(caught) == [] - - -@pytest.mark.usefixtures("fresh_default_warning") -def test_configured_retry_defaults_do_not_warn() -> None: - with warnings.catch_warnings(record=True) as caught: - warnings.simplefilter("always") - with configured(retry={"backoff": 2, "jitter": "equal", "max_delay": 30}): - - @retry - def bare_with_new_defaults() -> None: ... +def test_default_schedule_backs_off_with_equal_jitter(fake_clock: FakeClock) -> None: + @retry(log_level=None) + def fail() -> None: + raise ConnectionError - assert _default_change_warnings(caught) == [] + for _ in range(1000): + with pytest.raises(ConnectionError): + fail() + first, second = fake_clock.sleeps[::2], fake_clock.sleeps[1::2] + assert all(0.5 <= delay <= 1 for delay in first) + assert all(1 <= delay <= 2 for delay in second) + assert max(first) - min(first) > 0.48 diff --git a/tests/test_security_fixes.py b/tests/test_security_fixes.py index a2bc303..8dbe51c 100644 --- a/tests/test_security_fixes.py +++ b/tests/test_security_fixes.py @@ -187,7 +187,15 @@ def call() -> str: def test_explicit_max_delay_still_wins_and_infinite_hints_are_ignored(fake_clock): attempts = [] - @retry(max_attempts=3, delay=2, max_delay=30, on=Throttled, delay_from=lambda e: e.retry_after) + @retry( + max_attempts=3, + delay=2, + backoff=1, + jitter=0, + max_delay=30, + on=Throttled, + delay_from=lambda e: e.retry_after, + ) def call() -> str: attempts.append(1) if len(attempts) == 1: From b5df61cfe5f17cb4633c5dd148d5e34927e83551 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 4 Dec 2026 13:32:29 +0200 Subject: [PATCH 34/38] Account for guarded structured replies and verify beta release notes --- CHANGELOG.md | 7 ++++- docs/features/ai/langchain.md | 5 ++++ docs/llms-full.txt | 5 ++++ scripts/check_release.py | 14 +++++++--- src/python_wrap/adapters/langchain.py | 38 ++++++++++++++++++++++----- src/python_wrap/llm.py | 7 +++++ tests/test_langchain_adapter.py | 20 ++++++++++++++ tests/test_langchain_providers.py | 31 +++++++++++++++------- tests/test_release_metadata.py | 6 +++++ 9 files changed, 113 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bf2e672..eeb17dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration. ## [Unreleased] +## [0.5.0b1] - 2026-12-04 + ### Security - Shared SQLite token windows now sample time after taking the writer lock and keep stored @@ -72,6 +74,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration. - Failed transactional idempotent calls remove their own unfinished claim. - Rebuilding LangChain provider models drops the original SDK clients so their retries are disabled while preserving the API settings and HTTP transports. +- LangChain structured output with `include_raw=True` counts token usage from the + provider message. Guarded models block direct generation methods that bypass the guard. - 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 @@ -976,7 +980,8 @@ Core: Initial release. -[Unreleased]: https://github.com/LitePy/PythonWrap/compare/v0.4.0...HEAD +[Unreleased]: https://github.com/LitePy/PythonWrap/compare/v0.5.0b1...HEAD +[0.5.0b1]: https://github.com/LitePy/PythonWrap/compare/v0.4.0...v0.5.0b1 [0.4.0]: https://github.com/LitePy/PythonWrap/compare/v0.4.0b2...v0.4.0 [0.4.0b1]: https://github.com/LitePy/PythonWrap/compare/v0.3.0...v0.4.0b1 [0.3.0]: https://github.com/LitePy/PythonWrap/compare/v0.2.1...v0.3.0 diff --git a/docs/features/ai/langchain.md b/docs/features/ai/langchain.md index 0a2fb36..2c332bd 100644 --- a/docs/features/ai/langchain.md +++ b/docs/features/ai/langchain.md @@ -98,6 +98,11 @@ with `max_retries=0` and no python-wrap layers. The guard is a LangChain Runnable. Use it in a pipe such as `prompt | guarded | parser`. `batch` and `abatch` run each input through the guard. Tool bindings, structured output, configuration bindings, and fallbacks retain the guard settings. +For structured output, pass `include_raw=True` to keep the provider message and its +token usage alongside the parsed response. Calls through `invoke` or `ainvoke` that +return without usage charge estimated input tokens when the budget has no custom +usage reader. Use `invoke`, `batch`, `stream` or their +async forms to keep calls inside the guard. Use `guard_embeddings(model, budget=budget, limiter=limiter)` for sync and async document and query embeddings. The guard charges estimated input tokens. diff --git a/docs/llms-full.txt b/docs/llms-full.txt index 81628d2..b245950 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -2119,6 +2119,11 @@ with `max_retries=0` and no python-wrap layers. The guard is a LangChain Runnable. Use it in a pipe such as `prompt | guarded | parser`. `batch` and `abatch` run each input through the guard. Tool bindings, structured output, configuration bindings, and fallbacks retain the guard settings. +For structured output, pass `include_raw=True` to keep the provider message and its +token usage alongside the parsed response. Calls through `invoke` or `ainvoke` that +return without usage charge estimated input tokens when the budget has no custom +usage reader. Use `invoke`, `batch`, `stream` or their +async forms to keep calls inside the guard. Use `guard_embeddings(model, budget=budget, limiter=limiter)` for sync and async document and query embeddings. The guard charges estimated input tokens. diff --git a/scripts/check_release.py b/scripts/check_release.py index 324917b..18e1906 100644 --- a/scripts/check_release.py +++ b/scripts/check_release.py @@ -2,7 +2,7 @@ Usage: python scripts/check_release.py [--tag] ---tag also fails when the *Unreleased* changelog section still has entries. +--tag also requires a dated section for the packaged version and an empty *Unreleased* section. Run it with --tag at tag time. Stability rule: while stability.md lists a provisional module with a target @@ -74,6 +74,14 @@ def unreleased_entries(text: str) -> list[str]: ) +def tag_changelog_problems(text: str, version: str) -> list[str]: + problems = unreleased_entries(text) + heading = re.compile(rf"^## \[{re.escape(version)}\] - \d{{4}}-\d{{2}}-\d{{2}}$", re.MULTILINE) + if len(heading.findall(text)) != 1: + problems.append(f"expected one dated changelog heading for [{version}]") + return problems + + def package_version() -> str: match = re.search(r'__version__\s*=\s*"([^"]+)"', INIT.read_text(encoding="utf-8")) if not match: @@ -105,13 +113,13 @@ def version_and_classifier_problems() -> list[str]: def main() -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument( - "--tag", action="store_true", help="also require an empty Unreleased section" + "--tag", action="store_true", help="check the changelog is ready for this version's tag" ) args = parser.parse_args() text = CHANGELOG.read_text(encoding="utf-8") problems = duplicate_entries(text) + version_and_classifier_problems() if args.tag: - problems += unreleased_entries(text) + problems += tag_changelog_problems(text, package_version()) for problem in problems: print(f"FAIL: {problem}") if not problems: diff --git a/src/python_wrap/adapters/langchain.py b/src/python_wrap/adapters/langchain.py index ebf28b4..43cb4ec 100644 --- a/src/python_wrap/adapters/langchain.py +++ b/src/python_wrap/adapters/langchain.py @@ -23,11 +23,18 @@ import time import uuid from collections.abc import Callable, Mapping +from dataclasses import dataclass from typing import Any from python_wrap import _core, _fork from python_wrap.adapters._sdk import GuardedClient, ResumableStream -from python_wrap.llm import Budget, TokenRateLimiter, estimate_tokens, read_usage +from python_wrap.llm import ( + Budget, + TokenRateLimiter, + _langchain_message, + estimate_tokens, + read_usage, +) __all__ = [ "GuardedChatModel", @@ -109,10 +116,16 @@ def _stream_config(config: Any) -> dict[str, Any]: def _headers(result: Any) -> Any: - meta = getattr(result, "response_metadata", None) + meta = getattr(_langchain_message(result), "response_metadata", None) return meta.get("headers") if isinstance(meta, Mapping) else None +@dataclass(frozen=True) +class _EstimatedChatReply: + value: Any + usage: dict[str, int] + + class GuardedChatModel: """The wrapper `guard_chat_model` returns. @@ -155,6 +168,12 @@ def with_fallbacks(self, fallbacks: Any, **kwargs: Any) -> GuardedChatModel: def with_retry(self, *args: Any, **kwargs: Any) -> Any: raise ValueError("python-wrap owns the retries") + def _chargeable_reply(self, result: Any, request: dict[str, str]) -> Any: + budget = self._sync.budget + if budget is None or budget.usage is not None or read_usage(result) is not None: + return result + return _EstimatedChatReply(result, {"input_tokens": estimate_tokens(**request)}) + def _attempt(self, input: Any, config: Any = None, **kwargs: Any) -> Any: request = {"input": _text(input)} cost = self._sync._reserve((), request, "langchain.invoke") @@ -167,7 +186,7 @@ def _attempt(self, input: Any, config: Any = None, **kwargs: Any) -> Any: finally: _guard_active.reset(token) self._sync._settled(cost, result, _headers(result), request) - return result + return self._chargeable_reply(result, request) async def _aattempt(self, input: Any, config: Any = None, **kwargs: Any) -> Any: request = {"input": _text(input)} @@ -181,13 +200,15 @@ async def _aattempt(self, input: Any, config: Any = None, **kwargs: Any) -> Any: finally: _guard_active.reset(token) self._async._settled(cost, result, _headers(result), request) - return result + return self._chargeable_reply(result, request) def invoke(self, input: Any, config: Any = None, **kwargs: Any) -> Any: - return self._invoke(input, config, **kwargs) + result = self._invoke(input, config, **kwargs) + return result.value if isinstance(result, _EstimatedChatReply) else result async def ainvoke(self, input: Any, config: Any = None, **kwargs: Any) -> Any: - return await self._ainvoke(input, config, **kwargs) + result = await self._ainvoke(input, config, **kwargs) + return result.value if isinstance(result, _EstimatedChatReply) else result def stream(self, input: Any, config: Any = None, **kwargs: Any) -> ResumableStream[Any]: """Chunks of the model's stream; reopened on a transient error before output.""" @@ -216,7 +237,10 @@ async def astream(self, input: Any, config: Any = None, **kwargs: Any) -> Any: def __getattr__(self, name: str) -> Any: if name.startswith("_"): raise AttributeError(name) - return getattr(self.model, name) + value = getattr(self.model, name) + if callable(value): + raise AttributeError(f"{name} is not a guarded operation; use invoke, batch or stream") + return value def __repr__(self) -> str: return f"GuardedChatModel({type(self.raw).__name__}, attempts={self._sync.attempts})" diff --git a/src/python_wrap/llm.py b/src/python_wrap/llm.py index 946722b..9f09fd6 100644 --- a/src/python_wrap/llm.py +++ b/src/python_wrap/llm.py @@ -582,6 +582,12 @@ def _count(raw: Any, *names: str) -> int | None: return None +def _langchain_message(response: Any) -> Any: + if isinstance(response, Mapping) and {"raw", "parsed", "parsing_error"} <= response.keys(): + return response["raw"] + return response + + def read_usage(response: Any) -> Usage | None: """Read token usage from a provider response without importing its SDK. @@ -609,6 +615,7 @@ def read_usage(response: Any) -> Usage | None: return response raw = _field(response, "usage") if raw is None: + response = _langchain_message(response) raw = _field(response, "usage_metadata") # LangChain AIMessage if raw is None: return None diff --git a/tests/test_langchain_adapter.py b/tests/test_langchain_adapter.py index a41af23..2dedee4 100644 --- a/tests/test_langchain_adapter.py +++ b/tests/test_langchain_adapter.py @@ -123,6 +123,26 @@ def test_runnable_composes_and_batch_retains_budget() -> None: assert budget.spent().tokens == 30 +def test_provider_generation_cannot_bypass_the_guard() -> None: + guarded = guard_chat_model(FlakyModel(calls=[])) + with pytest.raises(AttributeError, match="not a guarded operation"): + guarded.generate([]) + + +def test_reply_without_usage_charges_estimated_input_tokens() -> None: + from langchain_core.runnables import RunnableLambda + + from python_wrap.llm import estimate_tokens + + budget = Budget(tokens=1000) + parsed_model = RunnableLambda(lambda prompt: {"name": "Paris"}) + guarded = guard_chat_model(parsed_model, budget=budget) + prompt = "Return the name of the French capital" + assert guarded.invoke(prompt) == {"name": "Paris"} + assert asyncio.run(guarded.ainvoke(prompt)) == {"name": "Paris"} + assert budget.spent().tokens == 2 * estimate_tokens(input=prompt) + + def test_callback_charges_only_unguarded_calls() -> None: budget = Budget(tokens=1000) callback = PythonWrapCallback(budget=budget) diff --git a/tests/test_langchain_providers.py b/tests/test_langchain_providers.py index 7703b10..2fb0bd4 100644 --- a/tests/test_langchain_providers.py +++ b/tests/test_langchain_providers.py @@ -15,13 +15,13 @@ @pytest.mark.parametrize( - ("provider", "agent"), - [("openai", False), ("anthropic", False), ("openai", True)], - ids=["openai", "anthropic", "openai-agent"], + ("provider", "operation"), + [("openai", "tools"), ("anthropic", "tools"), ("openai", "agent"), ("openai", "structured")], + ids=["openai", "anthropic", "openai-agent", "openai-structured"], ) -def test_bound_provider_retries_and_charges_once(provider, agent): +def test_bound_provider_retries_and_charges_once(provider, operation): integration = pytest.importorskip(f"langchain_{provider}") - agents = pytest.importorskip("langchain.agents") if agent else None + agents = pytest.importorskip("langchain.agents") if operation == "agent" else None model_type = integration.ChatOpenAI if provider == "openai" else integration.ChatAnthropic sdk = import_module(provider) http = import_module( @@ -38,13 +38,14 @@ def respond(request): if len(requests) <= 2: return http.Response(429, json={"error": {"message": "slow down"}}) if provider == "openai": + content = '{"answer":"done"}' if operation == "structured" else "done" return http.Response( 200, json={ "id": "chatcmpl-test", "object": "chat.completion", "model": "gpt-4o-mini", - "choices": [{"index": 0, "message": {"role": "assistant", "content": "done"}}], + "choices": [{"index": 0, "message": {"role": "assistant", "content": content}}], "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}, }, ) @@ -78,12 +79,24 @@ def lookup(city: str) -> str: events = [] config = {"callbacks": [PythonWrapCallback(budget=budget)]} with fake_clock(), listening(events.append): - if agents is None: - result = guarded.bind_tools([lookup]).invoke("hello", config=config) - else: + if agents is not None: graph = agents.create_agent(guarded, tools=[lookup]) outcome = graph.invoke({"messages": [{"role": "user", "content": "hello"}]}, config) result = outcome["messages"][-1] + elif operation == "structured": + from pydantic import BaseModel + + class Reply(BaseModel): + answer: str + + structured = guarded.with_structured_output( + Reply, method="json_mode", include_raw=True + ) + parsed = structured.invoke("Return JSON", config=config) + assert parsed["parsed"].answer == "done" + result = parsed["raw"] + else: + result = guarded.bind_tools([lookup]).invoke("hello", config=config) assert result.usage_metadata["total_tokens"] == 15 assert guarded.model.max_retries == 0 diff --git a/tests/test_release_metadata.py b/tests/test_release_metadata.py index 21d3c5a..933679b 100644 --- a/tests/test_release_metadata.py +++ b/tests/test_release_metadata.py @@ -39,6 +39,12 @@ def test_version_and_classifier_are_consistent() -> None: assert check_release.version_and_classifier_problems() == [] +def test_tag_requires_dated_notes_for_the_packaged_version() -> None: + text = "## [Unreleased]\n\n## [0.5.0b1] - 2026-12-04\n\n- New defaults\n" + assert check_release.tag_changelog_problems(text, "0.5.0b1") == [] + assert check_release.tag_changelog_problems(text, "0.5.0") + + def test_provisional_modules_say_so_in_docstring() -> None: for name in PROVISIONAL_MODULES: source = (ROOT / "src" / "python_wrap" / f"{name}.py").read_text(encoding="utf-8") From 085f0b0e1bb3538437fca1cc38d51d8ab79c468f Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 4 Dec 2026 13:37:13 +0200 Subject: [PATCH 35/38] Keep inherited SQL sessions out of child finalizers --- CHANGELOG.md | 2 ++ docs/features/concurrency/leases-and-idempotency.md | 12 ++++++------ src/python_wrap/coordination.py | 10 +++++++--- tests/test_sql_backends_live.py | 2 ++ 4 files changed, 17 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eeb17dc..db5a60a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,6 +60,8 @@ Breaking changes are listed under **Breaking changes**, each with its migration. ### Fixed +- Forked PostgreSQL and SQL Server lock backends preserve the parent's active SQL sessions + while opening a separate pool in the child. - Celery deliveries waiting on an idempotency lease preserve the task retry counter. - Shared caches batch tag reads and recreate missing version tokens so deleting diff --git a/docs/features/concurrency/leases-and-idempotency.md b/docs/features/concurrency/leases-and-idempotency.md index 535bfb7..5f0f00a 100644 --- a/docs/features/concurrency/leases-and-idempotency.md +++ b/docs/features/concurrency/leases-and-idempotency.md @@ -73,12 +73,12 @@ exposes that behavior for function calls. `PgAdvisoryLock(engine)` and `SqlAppLock(engine)` accept a SQLAlchemy engine and hold a dedicated session connection while the lease is held. SQL session locks last for the -session rather than a wall-clock TTL. Capacity must be one. Create engines and SQL -lock backends before a fork (for example at import time in a preloading server). In a -forked child, the backend forgets the parent's connections without closing them, disposes -the inherited engine without closing its shared sockets, and then works normally. A lease -the parent holds stays with the parent: the child's `release` for that token returns -`False`. An engine without `dispose` still raises `RuntimeError` in a child. Use client/database +session rather than a wall-clock TTL. Capacity must be one. Create engines after a fork +when possible. If a preloading server creates the engine before forking, the child's +first lock operation opens a fresh pool. The child retains references to the inherited +pool and connections so driver finalizers cannot interfere with the parent's sessions. +A lease the parent holds stays with the parent. The child's `release` for that token +returns `False`. An engine without `dispose` raises `RuntimeError` in a child. Use client/database timeouts. Unlock failures invalidate the dedicated connection rather than returning a potentially locked session to its pool. These adapters need your application's SQLAlchemy installation and database driver; python-wrap does not install them. diff --git a/src/python_wrap/coordination.py b/src/python_wrap/coordination.py index e407fce..6864d19 100644 --- a/src/python_wrap/coordination.py +++ b/src/python_wrap/coordination.py @@ -216,6 +216,9 @@ class AsyncRedisSemaphore(AsyncRedisLock): """`AsyncRedisLock` with capacity supplied by Lease(limit=...).""" +_inherited_sql_resources: list[tuple[Any, dict[str, tuple[str, Any, Any]]]] = [] + + class _SQLLock: dialect: str @@ -234,10 +237,11 @@ def _process(self) -> None: with self._lock: if os.getpid() == self._pid: return - # Connections opened before the fork belong to the parent: forget them - # without closing, and discard pooled sockets the child must not reuse. - self._connections = {} + # Dropping the last reference can finalize a driver connection from the + # child and send protocol traffic on the parent's SQL session. + _inherited_sql_resources.append((getattr(self.engine, "pool", None), self._connections)) dispose(close=False) + self._connections = {} self._pid = os.getpid() def _resource(self, key: str) -> Any: diff --git a/tests/test_sql_backends_live.py b/tests/test_sql_backends_live.py index d21c84c..11b8697 100644 --- a/tests/test_sql_backends_live.py +++ b/tests/test_sql_backends_live.py @@ -105,6 +105,7 @@ def job() -> str: @pytest.mark.skipif(not hasattr(os, "fork"), reason="POSIX fork only") def test_sql_lock_backend_rebinds_after_fork(lock_backend): + import gc import multiprocessing backend, _ = lock_backend @@ -113,6 +114,7 @@ def test_sql_lock_backend_rebinds_after_fork(lock_backend): def use_in_child(): assert not backend.acquire(key, "child", 30) + gc.collect() assert backend.acquire(key + "-child", "child", 30) assert backend.release(key + "-child", "child") From 7d1b04b34e3e5c63e368af5d079a08c4cd723bb5 Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 4 Dec 2026 13:56:52 +0200 Subject: [PATCH 36/38] Remove deprecated compatibility APIs for 0.6.0 --- CHANGELOG.md | 11 ++ docs/api/celery.md | 2 + docs/api/coordination.md | 2 + docs/api/http.md | 2 + docs/api/quotas.md | 2 + docs/api/shared.md | 2 + docs/api/stores.md | 2 + docs/cookbook/framework-integrations.md | 2 +- docs/features/ai/agent-frameworks.md | 2 +- docs/features/ai/agent-safety.md | 2 +- .../ai/shared-limits-and-cassettes.md | 2 +- docs/features/caching/memoize.md | 2 +- .../caching/stores-and-credentials.md | 6 +- .../concurrency/leases-and-idempotency.md | 6 +- docs/features/concurrency/shared-limits.md | 5 +- docs/features/observability/metrics.md | 1 - docs/features/observability/production.md | 1 - docs/llms-full.txt | 26 ++-- docs/llms.txt | 2 +- docs/project/migration.md | 22 +++- docs/project/stability.md | 6 + src/python_wrap/__init__.py | 119 +----------------- src/python_wrap/_backend.py | 33 ++--- src/python_wrap/_data/agent_guide.md | 2 +- src/python_wrap/_data/recipes.json | 8 +- src/python_wrap/_runtime.py | 4 - src/python_wrap/agents.py | 9 +- src/python_wrap/async_cache.py | 6 +- src/python_wrap/celery.py | 4 +- src/python_wrap/coordination.py | 5 +- src/python_wrap/events.py | 5 - src/python_wrap/idempotency.py | 4 +- src/python_wrap/llm_shared.py | 49 +++----- src/python_wrap/observability.py | 4 - src/python_wrap/stores.py | 6 +- src/python_wrap/web.py | 2 +- tests/test_async_cache.py | 2 +- tests/test_backend_rules.py | 24 ++-- tests/test_effect_ledger.py | 4 +- tests/test_llm_shared.py | 30 ++--- tests/test_public_api.py | 21 ++-- tests/test_redis_backends.py | 16 ++- tests/test_redis_scripts_live.py | 2 +- tests/test_release_metadata.py | 2 +- tests/test_stability.py | 4 +- 45 files changed, 173 insertions(+), 300 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index db5a60a..64dbda0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,17 @@ Breaking changes are listed under **Breaking changes**, each with its migration. ## [Unreleased] +### Breaking changes + +- Redis cache stores and shared token windows no longer accept `fail_open=`. Use + `on_backend_error="raise"` for `False` or `on_backend_error="allow"` for `True`. +- The token-window event `rate_limit.store_error` and its dedicated counters are retired. + Use `backend.error` and filter events on `backend="tokens"` for token-window failures. +- The private `_runtime.digest` alias is removed. `name_digest` preserves the existing + digests for internal names, while `stable_digest` is for caller-supplied keys. +- The deprecated LLM, agent and MCP imports leave the `python_wrap` package root. + Use the documented submodule imports. The `mcp_guard` top-level entry point stays available. + ## [0.5.0b1] - 2026-12-04 ### Security diff --git a/docs/api/celery.md b/docs/api/celery.md index 31f6144..766f3a4 100644 --- a/docs/api/celery.md +++ b/docs/api/celery.md @@ -1,3 +1,5 @@ +This module is [provisional](../project/stability.md#provisional-apis) and may change in a minor release. + ::: python_wrap.celery See the idempotent task scopes and the "what runs twice, what does not" table in the diff --git a/docs/api/coordination.md b/docs/api/coordination.md index 0b24d6a..66c7fdb 100644 --- a/docs/api/coordination.md +++ b/docs/api/coordination.md @@ -1 +1,3 @@ +This module is [provisional](../project/stability.md#provisional-apis) and may change in a minor release. + ::: python_wrap.coordination diff --git a/docs/api/http.md b/docs/api/http.md index 9ebf2f4..e8be7dd 100644 --- a/docs/api/http.md +++ b/docs/api/http.md @@ -1 +1,3 @@ +This module is [provisional](../project/stability.md#provisional-apis) and may change in a minor release. + ::: python_wrap.http diff --git a/docs/api/quotas.md b/docs/api/quotas.md index 1f16259..afd209d 100644 --- a/docs/api/quotas.md +++ b/docs/api/quotas.md @@ -1 +1,3 @@ +This module is [provisional](../project/stability.md#provisional-apis) and may change in a minor release. + ::: python_wrap.quotas diff --git a/docs/api/shared.md b/docs/api/shared.md index 0bfe100..9d51540 100644 --- a/docs/api/shared.md +++ b/docs/api/shared.md @@ -1 +1,3 @@ +This module is [provisional](../project/stability.md#provisional-apis) and may change in a minor release. + ::: python_wrap.shared diff --git a/docs/api/stores.md b/docs/api/stores.md index e7f05ab..005f3c1 100644 --- a/docs/api/stores.md +++ b/docs/api/stores.md @@ -1 +1,3 @@ +This module is [provisional](../project/stability.md#provisional-apis) and may change in a minor release. + ::: python_wrap.stores diff --git a/docs/cookbook/framework-integrations.md b/docs/cookbook/framework-integrations.md index 0318953..f20c43f 100644 --- a/docs/cookbook/framework-integrations.md +++ b/docs/cookbook/framework-integrations.md @@ -162,7 +162,7 @@ install(app) # soft limit, else hard limit minus hard_margin=5 s, becomes the d @app.task(bind=True, acks_late=True, max_retries=8, time_limit=300) -@idempotent_task(scope="delivery", store=result_store) # RedisStore(client, "tasks:", fail_open=False) +@idempotent_task(scope="delivery", store=result_store) # RedisStore(client, "tasks:", on_backend_error="raise") @resilient_task(vendor_policy, delays=[30, 120, 600]) def sync_orders(self, account_id: int) -> None: ... ``` diff --git a/docs/features/ai/agent-frameworks.md b/docs/features/ai/agent-frameworks.md index 920e9f2..3dcf1af 100644 --- a/docs/features/ai/agent-frameworks.md +++ b/docs/features/ai/agent-frameworks.md @@ -124,7 +124,7 @@ assert bank == ["B-2"] # never charged twice | --- | --- | | `None` / `MemoryEffectStore()` | One process. | | a path / `SQLiteEffectStore(path)` | Every process on the host; survives restarts. | -| `RedisEffectStore(client)` or a `RedisStore(..., fail_open=False)` | Every worker; claims and outcomes are Lua scripts, so they are atomic. | +| `RedisEffectStore(client)` or a `RedisStore(..., on_backend_error="raise")` | Every worker; claims and outcomes are Lua scripts, so they are atomic. | Only the attempt that owns a record can write its outcome: a slow attempt whose lease was taken over cannot overwrite the newer one. SQLite and Redis serialise records as JSON diff --git a/docs/features/ai/agent-safety.md b/docs/features/ai/agent-safety.md index cf29fed..e47ffce 100644 --- a/docs/features/ai/agent-safety.md +++ b/docs/features/ai/agent-safety.md @@ -64,7 +64,7 @@ with agent_run(run_id="order-42-attempt"): assert charged == ["o-42"] ``` -The default store is an in-process `MemoryResultStore`. Pass `store=RedisStore(client, fail_open=False)` to deduplicate across processes; see [Leases and idempotency](../concurrency/leases-and-idempotency.md) for the guarantees and their limits. +The default store is an in-process `MemoryResultStore`. Pass `store=RedisStore(client, on_backend_error="raise")` to deduplicate across processes; see [Leases and idempotency](../concurrency/leases-and-idempotency.md) for the guarantees and their limits. `retry=` and `timeout=` are applied **inside** the deduplication, so a replay never re-runs them: diff --git a/docs/features/ai/shared-limits-and-cassettes.md b/docs/features/ai/shared-limits-and-cassettes.md index 4c105c8..d66a487 100644 --- a/docs/features/ai/shared-limits-and-cassettes.md +++ b/docs/features/ai/shared-limits-and-cassettes.md @@ -46,7 +46,7 @@ Every worker must use the same `tokens_per_minute`; the window name picks the bu ### When storage fails -By default a token window uses `on_backend_error="local"`: if the file is locked or Redis is unreachable it emits `backend.error` (and the older `rate_limit.store_error`, removed in 0.6.0) and uses a private in-memory bucket for that call, so an outage degrades to per-process limiting instead of stopping every LLM call. Pass `on_backend_error="allow"` to admit calls without accounting, or `on_backend_error="raise"` to raise. The `fail_open=` argument still works but is deprecated (removed in 0.6.0). `configure(backend_errors=...)` sets the default for windows built without an explicit mode. +By default a token window uses `on_backend_error="local"`: if the file is locked or Redis is unreachable it emits `backend.error` and uses a private in-memory bucket for that call, so an outage degrades to per-process limiting instead of stopping every LLM call. Pass `on_backend_error="allow"` to admit calls without accounting, or `on_backend_error="raise"` to raise. `configure(backend_errors=...)` sets the default for windows built without an explicit mode. ### Backing off together diff --git a/docs/features/caching/memoize.md b/docs/features/caching/memoize.md index 4702079..fdf22bd 100644 --- a/docs/features/caching/memoize.md +++ b/docs/features/caching/memoize.md @@ -348,7 +348,7 @@ from python_wrap import RedisStore, memoize client = redis.Redis(socket_timeout=2, socket_connect_timeout=2) -@memoize(store=RedisStore(client, prefix="pricing:v1:", fail_open=False), ttl=300) +@memoize(store=RedisStore(client, prefix="pricing:v1:", on_backend_error="raise"), ttl=300) def price(sku: str) -> float: return load_price(sku) ``` diff --git a/docs/features/caching/stores-and-credentials.md b/docs/features/caching/stores-and-credentials.md index e773668..34aa4ef 100644 --- a/docs/features/caching/stores-and-credentials.md +++ b/docs/features/caching/stores-and-credentials.md @@ -71,10 +71,8 @@ Set `on_backend_error="raise"` when persistence is part of correctness, especial for [idempotency](../concurrency/leases-and-idempotency.md#idempotency). The async store (`AsyncRedisStore`) follows the same rules. -The mode resolves in this order: the `on_backend_error=` argument, then the deprecated -`fail_open=` argument (it emits a `DeprecationWarning` and is removed in 0.6.0), then -`configure(backend_errors=...)`, then `"allow"`. Set `configure(backend_errors="raise")` to make -every cache built without an explicit mode strict. +The explicit `on_backend_error=` argument takes precedence over +`configure(backend_errors=...)`. A shared cache defaults to `"allow"` when neither is set. ### Cache keys diff --git a/docs/features/concurrency/leases-and-idempotency.md b/docs/features/concurrency/leases-and-idempotency.md index 5f0f00a..8c588d6 100644 --- a/docs/features/concurrency/leases-and-idempotency.md +++ b/docs/features/concurrency/leases-and-idempotency.md @@ -29,7 +29,7 @@ worker thread. An async backend such as `AsyncRedisLock` awaits every round trip heartbeat renewal, release and `check_async`) on the event loop, with no thread. Using an async backend with a synchronous `with` or `check()` raises `TypeError`. Likewise, `@idempotent` on an `async def` function awaits an `AsyncCacheStore` directly, such as -`AsyncRedisStore(..., fail_open=False)` or `AsyncMemoryStore`; an `AsyncRedisStore` gets a +`AsyncRedisStore(..., on_backend_error="raise")` or `AsyncMemoryStore`; an `AsyncRedisStore` gets a matching `AsyncRedisLock` automatically. Cancellation cleanup waits for already-started client I/O to settle and releases an acquired token; clients therefore need finite I/O timeouts. By default a heartbeat renews the lease while the function runs. A lost lease @@ -111,7 +111,7 @@ releases the lease. Duplicates during execution follow `in_progress=`: `"raise"` of result retention; renewal is automatic. For waits, `timeout=` bounds acquisition. Cross-process behavior needs **both** shared result storage and shared lease ownership. -`RedisStore(fail_open=False)` automatically supplies a matching `RedisLock` when +`RedisStore(on_backend_error="raise")` automatically supplies a matching `RedisLock` when `backend=` is omitted. Other shared stores need an explicit shared lease backend; you can also pass one to choose a separate Redis lease namespace. A distributed lease with the default local result store is rejected. Backend write failures must propagate, @@ -122,7 +122,7 @@ so fail-open result stores are rejected. from python_wrap import RedisLock, RedisStore, idempotent @idempotent(key=lambda event: f"event:{event['id']}", ttl="1d", - store=RedisStore(client, "myapp:idempotency:", fail_open=False), + store=RedisStore(client, "myapp:idempotency:", on_backend_error="raise"), backend=RedisLock(client, "myapp:idempotency-leases:"), in_progress="wait", timeout=30) def handle_event(event): diff --git a/docs/features/concurrency/shared-limits.md b/docs/features/concurrency/shared-limits.md index cad2be8..b04c1a2 100644 --- a/docs/features/concurrency/shared-limits.md +++ b/docs/features/concurrency/shared-limits.md @@ -194,9 +194,8 @@ breaker = CircuitBreaker(name="vendor", backend=RedisBreakerState(client), The first error logs a WARNING and emits `backend.error` (fields `backend`, `operation`, `error`); the next success emits `backend.recovered`. Repeated failures while the store stays down log one WARNING per interval, not one per call. While a fallback is active `health.summary()` reports -`degraded`. Idempotency result stores always raise. `RedisStore` and `AsyncRedisStore` keep -`fail_open` as a deprecated alias (removed in 0.6.0; `True` is `"allow"`, `False` is `"raise"`); -`RedisSource` takes `on_backend_error` and answers its `default`. +`degraded`. Idempotency result stores always raise. `RedisSource` accepts +`on_backend_error` and serves its configured fallback during an outage. See [quotas API](../../api/quotas.md), [shared backends API](../../api/shared.md), and [bulkhead API](../../api/bulkhead.md). diff --git a/docs/features/observability/metrics.md b/docs/features/observability/metrics.md index 110f5db..02fdc95 100644 --- a/docs/features/observability/metrics.md +++ b/docs/features/observability/metrics.md @@ -128,7 +128,6 @@ unsubscribe() | `llm.validation_failed` | `attempt`, `error` | | `llm.repair_exhausted` | `attempts`, `reason` | | `llm.cassette_recorded` | `status`, `key` | -| `rate_limit.store_error` | `error`, `op` (a shared token window fell back to a local bucket) | | `llm.stream_resumed` | `attempt` (the attempt that failed), `exception`, `delay` (seconds before reopening) | | `llm.stream_interrupted` | `chars` (partial text length), `tool_calls` (completed tool calls), `exception` | | `llm.prompt_cache_cold` | `calls`, `hit_rate`, `reasons` (likely causes) | diff --git a/docs/features/observability/production.md b/docs/features/observability/production.md index 995c859..aefa6a5 100644 --- a/docs/features/observability/production.md +++ b/docs/features/observability/production.md @@ -88,7 +88,6 @@ For an actual operation-duration span, keep `@trace(otel=True)` around that oper | Rate limit rejected | counter | `pw_rate_limit_rejected_total` | `python_wrap.rate_limit.rejected` | | Timeout | counter | `pw_timeouts_total` | `python_wrap.timeouts` | | Backend error | counter | `pw_backend_errors_total` | `python_wrap.backend.errors` | -| Token-window store error | counter | `pw_rate_limit_store_errors_total` | `python_wrap.rate_limit.store_errors` | | Limiter wait (seconds) | histogram | `pw_limiter_wait_seconds` | `python_wrap.rate_limit.wait` | | Breaker state (0 closed, 1 half-open, 2 open) | observable gauge | `pw_breaker_state` | `python_wrap.circuit.state` | | Component health | observable gauge | `pw_health_up` | `python_wrap.health.up` | diff --git a/docs/llms-full.txt b/docs/llms-full.txt index b245950..54dc961 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -58,7 +58,7 @@ When stacking by hand, the decorator at the top is the outermost. So: deduplication: **no retry layer**. Pass `idempotent=False` to presets (the retry layer is left out) and use `@idempotent(key=...)` to deduplicate repeated requests. - `@idempotent` across processes needs a shared result store **and** a shared lease - backend (`RedisStore(fail_open=False)` supplies a matching `RedisLock`). It cannot give + backend (`RedisStore(on_backend_error='raise')` supplies a matching `RedisLock`). It cannot give exactly-once effects across a crash; use an outbox or database idempotency keys for that. ## What never to retry @@ -2425,7 +2425,7 @@ Every worker must use the same `tokens_per_minute`; the window name picks the bu #### When storage fails -By default a token window uses `on_backend_error="local"`: if the file is locked or Redis is unreachable it emits `backend.error` (and the older `rate_limit.store_error`, removed in 0.6.0) and uses a private in-memory bucket for that call, so an outage degrades to per-process limiting instead of stopping every LLM call. Pass `on_backend_error="allow"` to admit calls without accounting, or `on_backend_error="raise"` to raise. The `fail_open=` argument still works but is deprecated (removed in 0.6.0). `configure(backend_errors=...)` sets the default for windows built without an explicit mode. +By default a token window uses `on_backend_error="local"`: if the file is locked or Redis is unreachable it emits `backend.error` and uses a private in-memory bucket for that call, so an outage degrades to per-process limiting instead of stopping every LLM call. Pass `on_backend_error="allow"` to admit calls without accounting, or `on_backend_error="raise"` to raise. `configure(backend_errors=...)` sets the default for windows built without an explicit mode. #### Backing off together @@ -2739,7 +2739,7 @@ with agent_run(run_id="order-42-attempt"): assert charged == ["o-42"] ``` -The default store is an in-process `MemoryResultStore`. Pass `store=RedisStore(client, fail_open=False)` to deduplicate across processes; see [Leases and idempotency](../concurrency/leases-and-idempotency.md) for the guarantees and their limits. +The default store is an in-process `MemoryResultStore`. Pass `store=RedisStore(client, on_backend_error="raise")` to deduplicate across processes; see [Leases and idempotency](../concurrency/leases-and-idempotency.md) for the guarantees and their limits. `retry=` and `timeout=` are applied **inside** the deduplication, so a replay never re-runs them: @@ -3092,7 +3092,7 @@ assert bank == ["B-2"] # never charged twice | --- | --- | | `None` / `MemoryEffectStore()` | One process. | | a path / `SQLiteEffectStore(path)` | Every process on the host; survives restarts. | -| `RedisEffectStore(client)` or a `RedisStore(..., fail_open=False)` | Every worker; claims and outcomes are Lua scripts, so they are atomic. | +| `RedisEffectStore(client)` or a `RedisStore(..., on_backend_error="raise")` | Every worker; claims and outcomes are Lua scripts, so they are atomic. | Only the attempt that owns a record can write its outcome: a slow attempt whose lease was taken over cannot overwrite the newer one. SQLite and Redis serialise records as JSON @@ -4275,7 +4275,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm `RedisLock` for ``redis.asyncio`` clients: every round trip is awaited, not threaded. - `python_wrap.AsyncRedisSemaphore`: `AsyncRedisSemaphore(client: Any, prefix: str = 'python-wrap:lease:')` `AsyncRedisLock` with capacity supplied by Lease(limit=...). -- `python_wrap.AsyncRedisStore`: `AsyncRedisStore(client: Any, prefix: str, *, dumps: Callable[[Any], bytes] | None = None, loads: Callable[[bytes], Any] | None = None, key_format: Callable[[Hashable], str] | None = None, on_backend_error: str | None = None, fail_open: Any = , retry_backend_after: float = 1.0, version: int | None = None)` +- `python_wrap.AsyncRedisStore`: `AsyncRedisStore(client: Any, prefix: str, *, dumps: Callable[[Any], bytes] | None = None, loads: Callable[[bytes], Any] | None = None, key_format: Callable[[Hashable], str] | None = None, on_backend_error: str | None = None, retry_backend_after: float = 1.0, version: int | None = None)` A namespaced `AsyncCacheStore` for ``redis.asyncio``-compatible clients. - `python_wrap.AsyncRedisWindow`: `AsyncRedisWindow(client: Any, key: str, *, calls: int, period: float | str, on_backend_error: str | None = None, retry_backend_after: float = 1.0)` `RedisWindow` for ``redis.asyncio`` clients: the round trip is awaited, not threaded. @@ -4399,7 +4399,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm The same atomic lease backend, with capacity supplied by Lease(limit=...). - `python_wrap.RedisSource`: `RedisSource(client: Any, prefix: str = 'python-wrap:switch:', *, default: bool = True, on_backend_error: str | None = None, retry_backend_after: float = 1.0)` Read a boolean flag from a supplied Redis client. -- `python_wrap.RedisStore`: `RedisStore(client: Any, prefix: str, *, dumps: Callable[[Any], bytes] | None = None, loads: Callable[[bytes], Any] | None = None, key_format: Callable[[Hashable], str] | None = None, on_backend_error: str | None = None, fail_open: Any = , retry_backend_after: float = 1.0, version: int | None = None)` +- `python_wrap.RedisStore`: `RedisStore(client: Any, prefix: str, *, dumps: Callable[[Any], bytes] | None = None, loads: Callable[[bytes], Any] | None = None, key_format: Callable[[Hashable], str] | None = None, on_backend_error: str | None = None, retry_backend_after: float = 1.0, version: int | None = None)` A namespaced `CacheStore` with opaque hashed keys and configurable serialization. - `python_wrap.RedisWindow`: `RedisWindow(client: Any, key: str, *, calls: int, period: float | str, on_backend_error: str | None = None, retry_backend_after: float = 1.0)` Atomic sliding-window admission using the Redis server's clock. @@ -4442,7 +4442,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm - `python_wrap.WebhookAlerter`: `WebhookAlerter(url: str, *, format: str = 'json', on: Iterable[str | CircuitState] = ('open',), cooldown: float = 300.0, timeout: float = 5.0, sender: Sender | None = None, include_recovery: bool = True, context: Mapping[str, Any] | None = None)` Post a chat message when a circuit breaker reaches a chosen state. - `python_wrap.__version__` - Constant: '0.5.0b1' + Constant: '0.6.0b1' - `python_wrap.ainvalidate_tags`: `ainvalidate_tags(*names: str, client: Any = None, require_shared: bool = False) -> int` `invalidate_tags` for ``redis.asyncio`` clients (amemoize with AsyncRedisStore). - `python_wrap.amap_iter`: `amap_iter(fn: Callable[[T], Awaitable[R]], items: Iterable[T] | AsyncIterable[T], *, limit: int, ordered: bool = True, return_exceptions: bool = False) -> AsyncGenerator[Any, None]` @@ -4846,7 +4846,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm - `python_wrap.decorators` Compatibility module: v0.1 imported everything from ``python_wrap.decorators``. - `python_wrap.decorators.__version__` - Constant: '0.5.0b1' + Constant: '0.6.0b1' - `python_wrap.devtools` Developer tools: deprecation warnings, mock data and decorator composition. - `python_wrap.django` @@ -5045,17 +5045,17 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm LLM fault rules that act on HTTP exchanges; reach it as ``chaos.llm_http``. - `python_wrap.llm_shared` Token limits and budgets shared by several worker processes. -- `python_wrap.llm_shared.AsyncRedisTokenWindow`: `AsyncRedisTokenWindow(client: Any, name: str = 'tokens', *, prefix: str = 'python-wrap:tokens', on_backend_error: str | None = None, fail_open: Any = )` +- `python_wrap.llm_shared.AsyncRedisTokenWindow`: `AsyncRedisTokenWindow(client: Any, name: str = 'tokens', *, prefix: str = 'python-wrap:tokens', on_backend_error: str | None = None)` `RedisTokenWindow` for ``redis.asyncio`` clients: round trips are awaited. - `python_wrap.llm_shared.RateLimitHint`: `RateLimitHint(remaining_tokens: float | None = None, reset_seconds: float | None = None, retry_after: float | None = None)` What a provider's rate-limit headers said, in plain numbers. -- `python_wrap.llm_shared.RedisTokenWindow`: `RedisTokenWindow(client: Any, name: str = 'tokens', *, prefix: str = 'python-wrap:tokens', on_backend_error: str | None = None, fail_open: Any = )` +- `python_wrap.llm_shared.RedisTokenWindow`: `RedisTokenWindow(client: Any, name: str = 'tokens', *, prefix: str = 'python-wrap:tokens', on_backend_error: str | None = None)` A `SharedTokenWindow` on Redis, shared by every worker on every host. - `python_wrap.llm_shared.SQLiteBudgetBackend`: `SQLiteBudgetBackend(path: str | os.PathLike[str], *, timeout: float = 10.0)` A `python_wrap.llm.BudgetBackend` in SQLite: one budget shared by local processes. -- `python_wrap.llm_shared.SQLiteTokenWindow`: `SQLiteTokenWindow(path: str | os.PathLike[str], name: str = 'tokens', *, timeout: float = 10.0, on_backend_error: str | None = None, fail_open: Any = )` +- `python_wrap.llm_shared.SQLiteTokenWindow`: `SQLiteTokenWindow(path: str | os.PathLike[str], name: str = 'tokens', *, timeout: float = 10.0, on_backend_error: str | None = None)` A `SharedTokenWindow` in one SQLite file, shared by processes on one host. -- `python_wrap.llm_shared.SharedTokenWindow`: `SharedTokenWindow(name: str = 'tokens', *, on_backend_error: str | None = None, fail_open: Any = )` +- `python_wrap.llm_shared.SharedTokenWindow`: `SharedTokenWindow(name: str = 'tokens', *, on_backend_error: str | None = None)` A token bucket held in shared storage; the base of the concrete windows. - `python_wrap.llm_shared.parse_rate_limit_headers`: `parse_rate_limit_headers(headers: Any) -> RateLimitHint` Read token-window hints from provider response headers; never raises. @@ -5136,7 +5136,7 @@ Every public name: `python_wrap.__all__` first, then names public only in a subm - `python_wrap.observability.Breadcrumbs`: `Breadcrumbs(sentry: Any, prefixes: tuple[str, ...])` Subscription handle returned by `sentry_breadcrumbs`; `close()` stops recording. - `python_wrap.observability.COUNTERS` - Constant: {'retry.attempt_failed': ('pw_retry_retries_total', 'python_wrap.retry.retries', '{retry}', 'Failed attempts that were followed by a retry.'), 'retry.gave_up': ('pw_retry_gave_up_total', 'python_wrap.retry.gave_up', '{call}', 'Calls whose retries were exhausted.'), 'retry.budget_exhausted': ('pw_retry_budget_exhausted_total', 'python_wrap.retry.budget_exhausted', '{call}', 'Calls stopped because the retry budget was used up.'), 'cache.hit': ('pw_cache_hits_total', 'python_wrap.cache.hits', '{hit}', 'Cache hits.'), 'cache.miss': ('pw_cache_misses_total', 'python_wrap.cache.misses', '{miss}', 'Cache misses.'), 'bulkhead.rejected': ('pw_bulkhead_rejected_total', 'python_wrap.bulkhead.rejected', '{call}', 'Calls refused by a full bulkhead.'), 'circuit.rejected': ('pw_breaker_rejected_total', 'python_wrap.circuit.rejected', '{call}', 'Calls refused by an open circuit breaker.'), 'rate_limit.rejected': ('pw_rate_limit_rejected_total', 'python_wrap.rate_limit.rejected', '{call}', 'Calls refused by a rate limiter.'), 'timeout.expired': ('pw_timeouts_total', 'python_wrap.timeouts', '{call}', 'Calls that hit their time limit.'), 'backend.error': ('pw_backend_errors_total', 'python_wrap.backend.errors', '{error}', 'Errors from a shared backend (function is the backend name).'), 'rate_limit.store_error': ('pw_rate_limit_store_errors_total', 'python_wrap.rate_limit.store_errors', '{error}', "Errors from a shared token window's storage.")} + Constant: {'retry.attempt_failed': ('pw_retry_retries_total', 'python_wrap.retry.retries', '{retry}', 'Failed attempts that were followed by a retry.'), 'retry.gave_up': ('pw_retry_gave_up_total', 'python_wrap.retry.gave_up', '{call}', 'Calls whose retries were exhausted.'), 'retry.budget_exhausted': ('pw_retry_budget_exhausted_total', 'python_wrap.retry.budget_exhausted', '{call}', 'Calls stopped because the retry budget was used up.'), 'cache.hit': ('pw_cache_hits_total', 'python_wrap.cache.hits', '{hit}', 'Cache hits.'), 'cache.miss': ('pw_cache_misses_total', 'python_wrap.cache.misses', '{miss}', 'Cache misses.'), 'bulkhead.rejected': ('pw_bulkhead_rejected_total', 'python_wrap.bulkhead.rejected', '{call}', 'Calls refused by a full bulkhead.'), 'circuit.rejected': ('pw_breaker_rejected_total', 'python_wrap.circuit.rejected', '{call}', 'Calls refused by an open circuit breaker.'), 'rate_limit.rejected': ('pw_rate_limit_rejected_total', 'python_wrap.rate_limit.rejected', '{call}', 'Calls refused by a rate limiter.'), 'timeout.expired': ('pw_timeouts_total', 'python_wrap.timeouts', '{call}', 'Calls that hit their time limit.'), 'backend.error': ('pw_backend_errors_total', 'python_wrap.backend.errors', '{error}', 'Errors from a shared backend (function is the backend name).')} - `python_wrap.observability.GenAITelemetry`: `GenAITelemetry(tracer: Any)` Subscription that turns ``genai.*`` events into OpenTelemetry spans. - `python_wrap.observability.Telemetry`: `Telemetry(tracer: Any, meter: Any, *, max_functions: int = 100, spans: str = 'events', attempt_spans: bool = False, wait_spans: bool = False, naming: str = 'legacy', current_span: Any = None, registry: Any = None)` diff --git a/docs/llms.txt b/docs/llms.txt index 1256668..9be457c 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -215,7 +215,7 @@ Install with `pip install python-wrap` (Python 3.10+, no runtime dependencies). - [Performance](https://pythonwrap.readthedocs.io/project/performance/): What does a decorator cost on every call? - [Limitations](https://pythonwrap.readthedocs.io/project/limitations/): python-wrap tries to do the obvious thing, and where it cannot, to say so. -- [Migrating to 0.2](https://pythonwrap.readthedocs.io/project/migration/): Version 0.2 is a rewrite of the internals with a handful of deliberate breaking changes. +- [Migrating to 0.2](https://pythonwrap.readthedocs.io/project/migration/): with `on_backend_error="allow"` on Redis cache stores and shared token windows. - [Migrating to 0.3](https://pythonwrap.readthedocs.io/project/migration-0.3/): 0.3 keeps the existing decorator toolkit and adds production integration helpers. - [API stability](https://pythonwrap.readthedocs.io/project/stability/): python-wrap is below 1.0, but it is no longer "anything may change". - [Operations runbook](https://pythonwrap.readthedocs.io/project/operations/): How to watch python-wrap in production, what to do when something looks stuck, and how stored state behaves across upgrades. diff --git a/docs/project/migration.md b/docs/project/migration.md index 2c43627..87ae275 100644 --- a/docs/project/migration.md +++ b/docs/project/migration.md @@ -1,4 +1,24 @@ -# Migrating from 0.1 to 0.2 +# Migration guide + +## Upgrading to 0.6 + +- Replace `fail_open=False` with `on_backend_error="raise"` and `fail_open=True` + with `on_backend_error="allow"` on Redis cache stores and shared token windows. + Keep `"raise"` for stores that record idempotency or side effects. +- Subscribe to `backend.error` for token-window outages and match `backend="tokens"`. + The old event used `op`, while `backend.error` supplies `operation`. Move dashboards + from the dedicated store-error counters to `pw_backend_errors_total` (Prometheus) + or `python_wrap.backend.errors` (OpenTelemetry), scoped to your window names. +- Replace `_runtime.digest` with `name_digest` for internal names. Use `stable_digest` + for caller-supplied values. Existing cache and coordination keys keep their encoding. +- Import former package-root AI helpers from their submodules. Use `python_wrap.llm` + for `Budget` and `llm_retry`, `python_wrap.agents` for `RunGuard` and `tool`, + `python_wrap.genai` for `traced_llm`, and `python_wrap.adapters` for `guard_openai` + and `guard_anthropic`. The [API index](../api/index.md) lists the related submodules. + Import `fake_llm` from `python_wrap.llm_testing` and `validated` from + `python_wrap.llm_validate`. + +## Upgrading from 0.1 to 0.2 Version 0.2 is a rewrite of the internals with a handful of deliberate breaking changes. Most v0.1 code keeps working: `from python_wrap.decorators import x` still resolves (a compatibility module re-exports everything), and the exceptions with a natural built-in counterpart subclass it (`TimeoutExpired` is a `TimeoutError`, `ValidationError` a `ValueError`). diff --git a/docs/project/stability.md b/docs/project/stability.md index a70553c..94cf18a 100644 --- a/docs/project/stability.md +++ b/docs/project/stability.md @@ -31,6 +31,8 @@ What "frozen" covers: original exceptions are re-raised unchanged by `retry`. - **Ordering.** `ROLES` keeps its order; a new role may be inserted where it belongs. - **Events.** Event names are not renamed; fields may be added, not removed. + The previously announced retirement of the provisional token-window event + `rate_limit.store_error` is documented in the [0.6 migration notes](migration.md#upgrading-to-06). Not covered: `repr()` text, log message wording, private names (leading underscore), undocumented attributes, and exact timing beyond what is documented. @@ -67,6 +69,10 @@ A provisional module graduates when all four hold: The storage formats of the backends above are already frozen: a change to them fails the stability test and needs a migration note, even before the module graduates. +The target versions are planning milestones. The Redis soak covers the four layers +listed in its report. It leaves HTTP and Celery soak evidence and the quiet minor +release requirement open. + ## Support window After a new minor release, the previous minor release gets security fixes for six months. diff --git a/src/python_wrap/__init__.py b/src/python_wrap/__init__.py index 6508214..8958be6 100644 --- a/src/python_wrap/__init__.py +++ b/src/python_wrap/__init__.py @@ -281,7 +281,7 @@ validate_args, ) -__version__ = "0.5.0b1" +__version__ = "0.6.0b1" # A library must never configure logging; this only silences "no handler" warnings. logging.getLogger("python_wrap").addHandler(logging.NullHandler()) @@ -500,120 +500,3 @@ def disabled() -> AbstractContextManager[None]: from .testing import disabled as scope return scope() - - -# LLM, agent and MCP helpers live in their submodules. The old top-level names keep -# working (with a DeprecationWarning) until 0.6.0. -_MOVED: dict[str, str] = { - "AgentError": "python_wrap.agents", - "AgentRun": "python_wrap.agents", - "ApprovalDenied": "python_wrap.agents", - "ApprovalTimeout": "python_wrap.agents", - "AsyncRedisTokenWindow": "python_wrap.llm_shared", - "AuditTape": "python_wrap.genai", - "Budget": "python_wrap.llm", - "BudgetBackend": "python_wrap.llm", - "BudgetExceeded": "python_wrap.llm", - "CacheGuard": "python_wrap.adapters._sdk", - "Cassette": "python_wrap.llm_cassette", - "CassetteError": "python_wrap.llm_cassette", - "CassetteMiss": "python_wrap.llm_cassette", - "DryRun": "python_wrap.agents", - "EffectConflict": "python_wrap.agents", - "EffectLedger": "python_wrap.agents", - "EffectRecord": "python_wrap.agents", - "EffectResolved": "python_wrap.agents", - "EffectStore": "python_wrap.agents", - "EffectUnknown": "python_wrap.agents", - "FakeProvider": "python_wrap.llm_testing", - "FakeResponse": "python_wrap.llm_testing", - "FakeStream": "python_wrap.llm_testing", - "LLMFaults": "python_wrap.llm_testing", - "LoopDetected": "python_wrap.agents", - "MCPGuard": "python_wrap.mcp_guard", - "MemoryEffectStore": "python_wrap.agents", - "RecordingTransport": "python_wrap.llm_cassette", - "Redactor": "python_wrap.genai", - "RedisBudgetBackend": "python_wrap.llm", - "RedisEffectStore": "python_wrap.agents", - "RedisTokenWindow": "python_wrap.llm_shared", - "ReplayMismatch": "python_wrap.genai", - "ReplayProvider": "python_wrap.genai", - "ReplayTransport": "python_wrap.llm_cassette", - "ReplayedError": "python_wrap.genai", - "ResumableStream": "python_wrap.adapters._sdk", - "RunBudgetExceeded": "python_wrap.agents", - "RunCancelled": "python_wrap.agents", - "RunContext": "python_wrap.genai", - "RunGuard": "python_wrap.agents", - "RunTimeout": "python_wrap.agents", - "SQLiteBudgetBackend": "python_wrap.llm_shared", - "SQLiteEffectStore": "python_wrap.agents", - "SQLiteTokenWindow": "python_wrap.llm_shared", - "SharedTokenWindow": "python_wrap.llm_shared", - "Spend": "python_wrap.llm", - "Step": "python_wrap.agents", - "StepLimitExceeded": "python_wrap.agents", - "StreamInterrupted": "python_wrap.adapters._sdk", - "StreamTimeout": "python_wrap.llm", - "TapeRecord": "python_wrap.genai", - "TokenRateLimiter": "python_wrap.llm", - "ToolCall": "python_wrap.agents", - "ToolNotAllowed": "python_wrap.agents", - "ToolPolicy": "python_wrap.agents", - "ToolRegistry": "python_wrap.agents", - "ToolSpec": "python_wrap.agents", - "Usage": "python_wrap.llm", - "ValidationRepairExhausted": "python_wrap.llm_validate", - "agent_run": "python_wrap.agents", - "budget": "python_wrap.llm", - "current_run": "python_wrap.agents", - "estimate_tokens": "python_wrap.llm", - "extract_usage": "python_wrap.genai", - "fake_llm": "python_wrap.llm_testing", - "fallback_models": "python_wrap.llm", - "guard_anthropic": "python_wrap.adapters.anthropic", - "guard_openai": "python_wrap.adapters.openai", - "instrument": "python_wrap.genai", - "llm_cache": "python_wrap.llm", - "llm_retry": "python_wrap.llm", - "llm_retry_after": "python_wrap.llm", - "llm_transient": "python_wrap.llm", - "mcp_breaker": "python_wrap.mcp_guard", - "no_sdk_retries": "python_wrap.adapters._sdk", - "parse_rate_limit_headers": "python_wrap.llm_shared", - "read_usage": "python_wrap.llm", - "record_step": "python_wrap.agents", - "replay": "python_wrap.genai", - "resume_safe": "python_wrap.adapters._sdk", - "run_context": "python_wrap.genai", - "stream_timeout": "python_wrap.llm", - "token_rate_limit": "python_wrap.llm", - "tool": "python_wrap.agents", - "tool_call_id": "python_wrap.agents", - "tool_spec": "python_wrap.agents", - "traced_llm": "python_wrap.genai", - "traced_tool": "python_wrap.genai", - "validated": "python_wrap.llm_validate", - "with_call_id": "python_wrap.agents", -} - - -def __getattr__(name: str) -> object: - module = _MOVED.get(name) - if module is None: - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - import importlib - import warnings - - warnings.warn( - f"python_wrap.{name} moved: import it from {module} (the top-level name is " - "removed in 0.6.0)", - DeprecationWarning, - stacklevel=2, - ) - return getattr(importlib.import_module(module), name) - - -def __dir__() -> list[str]: - return sorted({*globals(), *_MOVED}) diff --git a/src/python_wrap/_backend.py b/src/python_wrap/_backend.py index 8d2f58a..38d82cc 100644 --- a/src/python_wrap/_backend.py +++ b/src/python_wrap/_backend.py @@ -10,7 +10,6 @@ from __future__ import annotations import time -import warnings from collections.abc import Awaitable, Callable from typing import Any, TypeVar @@ -22,9 +21,6 @@ BACKEND_ERROR_MODES = ("raise", "local", "allow") -_NOT_GIVEN: Any = object() -"""Sentinel for an argument that was not passed (so ``None`` stays a valid value).""" - _project_default: str | None = None """Mirror of ``configure(backend_errors=)``; kept in step by `python_wrap.config`.""" @@ -40,28 +36,13 @@ def default_mode() -> str: return _project_default or "local" -def resolve_mode(on_backend_error: str | None, fail_open: Any, owner: str, default: str) -> str: - """Resolve a backend's mode: explicit argument, deprecated ``fail_open``, project default. - - ``default`` applies when neither is given and nothing is configured. ``fail_open`` is - deprecated (removed in 0.6.0): ``True`` maps to ``allow``, ``False`` to ``raise``, and - it is ignored when ``on_backend_error`` is given (but still warns). - Call it directly from the constructor so the warning points at the caller. - """ - if fail_open is not _NOT_GIVEN: - warnings.warn( - f"{owner}(fail_open=) is deprecated and is removed in 0.6.0; " - "pass on_backend_error='allow' or on_backend_error='raise' instead", - DeprecationWarning, - stacklevel=3, - ) - if on_backend_error is not None: - if on_backend_error not in BACKEND_ERROR_MODES: - raise ValueError(f"on_backend_error must be one of {BACKEND_ERROR_MODES}") - return on_backend_error - if fail_open is not _NOT_GIVEN: - return "allow" if fail_open else "raise" - return _project_default or default +def resolve_mode(on_backend_error: str | None, default: str) -> str: + """Resolve a backend mode from its argument, project configuration or built-in default.""" + if on_backend_error is None: + return _project_default or default + if on_backend_error not in BACKEND_ERROR_MODES: + raise ValueError(f"on_backend_error must be one of {BACKEND_ERROR_MODES}") + return on_backend_error class BackendMonitor: diff --git a/src/python_wrap/_data/agent_guide.md b/src/python_wrap/_data/agent_guide.md index 9009f09..4d66a47 100644 --- a/src/python_wrap/_data/agent_guide.md +++ b/src/python_wrap/_data/agent_guide.md @@ -52,7 +52,7 @@ When stacking by hand, the decorator at the top is the outermost. So: deduplication: **no retry layer**. Pass `idempotent=False` to presets (the retry layer is left out) and use `@idempotent(key=...)` to deduplicate repeated requests. - `@idempotent` across processes needs a shared result store **and** a shared lease - backend (`RedisStore(fail_open=False)` supplies a matching `RedisLock`). It cannot give + backend (`RedisStore(on_backend_error='raise')` supplies a matching `RedisLock`). It cannot give exactly-once effects across a crash; use an outbox or database idempotency keys for that. ## What never to retry diff --git a/src/python_wrap/_data/recipes.json b/src/python_wrap/_data/recipes.json index 98856b2..2dd99fd 100644 --- a/src/python_wrap/_data/recipes.json +++ b/src/python_wrap/_data/recipes.json @@ -537,7 +537,7 @@ "StepLimitExceeded", "LoopDetected" ], - "snippet": "from python_wrap import StepLimitExceeded, agent_run, record_step\n\nwith agent_run(max_steps=3, max_seconds=30) as run:\n try:\n while True:\n record_step('llm', 'model')\n except StepLimitExceeded:\n pass\nassert run.steps == 3\n", + "snippet": "from python_wrap.agents import StepLimitExceeded, agent_run, record_step\n\nwith agent_run(max_steps=3, max_seconds=30) as run:\n try:\n while True:\n record_step('llm', 'model')\n except StepLimitExceeded:\n pass\nassert run.steps == 3\n", "notes": "Bound every agent loop with max_steps, max_seconds and max_repeats; pass a Budget to stop on spend. Tool calls count as steps automatically.", "docs": "features/ai/agent-safety.md" }, @@ -566,7 +566,7 @@ "ToolPolicy", "RunGuard" ], - "snippet": "import json\n\nfrom python_wrap import RunGuard, ToolRegistry\n\nsent: list[str] = []\ntools = ToolRegistry(guard=RunGuard(max_steps=10))\n\n@tools.tool\ndef send_email(to: str) -> str:\n sent.append(to)\n return 'sent'\n\nwith tools.run(run_id='demo-run'):\n assert tools.call('send_email', json.dumps({'to': 'a@example.com'})) == 'sent'\n tools.call('send_email', json.dumps({'to': 'a@example.com'})) # replay: not sent again\nassert sent == ['a@example.com']\n", + "snippet": "import json\n\nfrom python_wrap.agents import RunGuard, ToolRegistry\n\nsent: list[str] = []\ntools = ToolRegistry(guard=RunGuard(max_steps=10))\n\n@tools.tool\ndef send_email(to: str) -> str:\n sent.append(to)\n return 'sent'\n\nwith tools.run(run_id='demo-run'):\n assert tools.call('send_email', json.dumps({'to': 'a@example.com'})) == 'sent'\n tools.call('send_email', json.dumps({'to': 'a@example.com'})) # replay: not sent again\nassert sent == ['a@example.com']\n", "notes": "Side-effecting tools are replay-proof within a run; mark pure reads read_only=True, gate risky ones with requires_approval=True, and use ToolPolicy(dry_run=True) to plan without acting.", "docs": "features/ai/agent-safety.md" }, @@ -594,7 +594,7 @@ "LLMFaults", "fake_clock" ], - "snippet": "from python_wrap import fake_llm, retry\nfrom python_wrap.chaos import chaos\nfrom python_wrap.llm_testing import RateLimitError\nfrom python_wrap.testing import fake_clock\n\nllm = fake_llm(['ok'])\n\n@retry(max_attempts=3, delay=1, on=RateLimitError)\ndef ask() -> str:\n return llm.complete(messages=[{'role': 'user', 'content': 'hi'}]).text\n\nwith fake_clock():\n chaos.llm.rate_limit('llm.*', times=1, retry_after=1)\n try:\n assert ask() == 'ok'\n finally:\n chaos.clear()\n", + "snippet": "from python_wrap import retry\nfrom python_wrap.chaos import chaos\nfrom python_wrap.llm_testing import RateLimitError, fake_llm\nfrom python_wrap.testing import fake_clock\n\nllm = fake_llm(['ok'])\n\n@retry(max_attempts=3, delay=1, on=RateLimitError)\ndef ask() -> str:\n return llm.complete(messages=[{'role': 'user', 'content': 'hi'}]).text\n\nwith fake_clock():\n chaos.llm.rate_limit('llm.*', times=1, retry_after=1)\n try:\n assert ask() == 'ok'\n finally:\n chaos.clear()\n", "notes": "No network and no SDK: fake_llm scripts replies, chaos.llm injects 429/529/timeouts/malformed JSON, fake_clock removes the waiting.", "docs": "features/ai/testing-agents.md" }, @@ -622,7 +622,7 @@ "traced_tool", "replay" ], - "snippet": "from python_wrap import AuditTape, traced_llm\n\ntape = AuditTape()\n\n@traced_llm(model='demo-1', tape=tape)\ndef ask(prompt: str) -> dict[str, object]:\n return {'text': 'ok', 'usage': {'input_tokens': 5, 'output_tokens': 2}}\n\nask('mail ada@example.com')\n[record] = tape.records()\nassert record.kind == 'llm' and record.input_tokens == 5\nassert 'ada@example.com' not in str(record.input)\n", + "snippet": "from python_wrap.genai import AuditTape, traced_llm\n\ntape = AuditTape()\n\n@traced_llm(model='demo-1', tape=tape)\ndef ask(prompt: str) -> dict[str, object]:\n return {'text': 'ok', 'usage': {'input_tokens': 5, 'output_tokens': 2}}\n\nask('mail ada@example.com')\n[record] = tape.records()\nassert record.kind == 'llm' and record.input_tokens == 5\nassert 'ada@example.com' not in str(record.input)\n", "notes": "The tape stores redacted inputs and outputs with tokens and cost; replay(tape) serves recorded results in tests without calling a provider or running tools.", "docs": "features/ai/observability.md" }, diff --git a/src/python_wrap/_runtime.py b/src/python_wrap/_runtime.py index fcbb14e..90718ef 100644 --- a/src/python_wrap/_runtime.py +++ b/src/python_wrap/_runtime.py @@ -47,10 +47,6 @@ def name_digest(value: Any) -> str: return hashlib.sha256(pickle.dumps(value, protocol=4)).hexdigest() -# Deprecated alias for `name_digest`; kept so existing imports keep working. -digest = name_digest - - def _enc(value: Any, out: list[bytes]) -> None: kind = type(value) if value is None: diff --git a/src/python_wrap/agents.py b/src/python_wrap/agents.py index 10efd41..f779344 100644 --- a/src/python_wrap/agents.py +++ b/src/python_wrap/agents.py @@ -1237,7 +1237,7 @@ def __init__( def from_store(cls, store: Any) -> RedisEffectStore: """Reuse a `python_wrap.stores.RedisStore`'s client, prefix and serialisers.""" if getattr(store, "fail_open", False): - raise ValueError("an effect ledger requires a RedisStore with fail_open=False") + raise ValueError("an effect ledger requires a RedisStore with on_backend_error='raise'") return cls(store.client, store.prefix + "effects:", dumps=store.dumps, loads=store.loads) def _key(self, key: str) -> str: @@ -1288,7 +1288,8 @@ def _effect_store(store: Any) -> EffectStore: if isinstance(store, str) or hasattr(store, "__fspath__"): return SQLiteEffectStore(store) raise TypeError( - "store must be an EffectStore, a RedisStore(fail_open=False), a SQLite file path or None" + "store must be an EffectStore, a RedisStore(on_backend_error='raise'), " + "a SQLite file path or None" ) @@ -1315,7 +1316,7 @@ class EffectLedger: Args: store: `MemoryEffectStore` (default), `SQLiteEffectStore`, `RedisEffectStore`, a - `python_wrap.stores.RedisStore` with ``fail_open=False``, or a file path + `python_wrap.stores.RedisStore` with ``on_backend_error='raise'``, or a file path (SQLite). Anything implementing `EffectStore` works. ttl: How long records (and replayable results) are kept (``"1d"``). lease: How long a ``started`` record is trusted before it counts as crashed; @@ -2037,7 +2038,7 @@ def tool( dry_result: Returned in a dry run instead of running (a callable is called with the tool's arguments); a `DryRun` marker by default. store: Result store for deduplication (shared across processes with - ``RedisStore(fail_open=False)``); in-process `MemoryResultStore` by default. + ``RedisStore(on_backend_error='raise')``); in-process `MemoryResultStore` by default. ttl: How long a result is replayed (``"1d"`` by default). ledger: An `EffectLedger` to deduplicate with instead of ``store``: the key is the provider's tool-call id when one is current (`with_call_id`; adapters diff --git a/src/python_wrap/async_cache.py b/src/python_wrap/async_cache.py index 3191e59..c242089 100644 --- a/src/python_wrap/async_cache.py +++ b/src/python_wrap/async_cache.py @@ -29,7 +29,7 @@ from typing import Any, Protocol, TypeVar, runtime_checkable from python_wrap import _core, _fork -from python_wrap._backend import _NOT_GIVEN, BackendMonitor, resolve_mode +from python_wrap._backend import BackendMonitor, resolve_mode from python_wrap._runtime import name_digest, stable_digest from python_wrap.caching import ( CacheInfo, @@ -182,7 +182,6 @@ class AsyncRedisStore: on_backend_error: ``"allow"`` (a miss; writes are dropped), ``"raise"`` or ``"local"`` (same as ``"allow"`` for a cache). Defaults to ``configure(backend_errors=)``, then ``"allow"``. Every error emits ``backend.error``. - fail_open: Deprecated alias (removed in 0.6.0): ``True`` is ``"allow"``, ``False`` is ``"raise"``. Ignored when ``on_backend_error`` is given. Raises: @@ -198,7 +197,6 @@ def __init__( loads: Callable[[bytes], Any] | None = None, key_format: Callable[[Hashable], str] | None = None, on_backend_error: str | None = None, - fail_open: Any = _NOT_GIVEN, retry_backend_after: float = 1.0, version: int | None = None, ) -> None: @@ -216,7 +214,7 @@ def __init__( self.dumps, self.loads = dumps or pickle.dumps, loads or pickle.loads # Plain pickle on a shared store: doctor reports it (PW026). self.implicit_pickle = self.dumps is pickle.dumps - mode = resolve_mode(on_backend_error, fail_open, type(self).__name__, "allow") + mode = resolve_mode(on_backend_error, "allow") mode = "allow" if mode == "local" else mode # a miss is already the local answer self.key_format, self.on_backend_error = key_format, mode self.fail_open = mode != "raise" # derived; idempotency and web read it diff --git a/src/python_wrap/celery.py b/src/python_wrap/celery.py index 1aa207b..b37d473 100644 --- a/src/python_wrap/celery.py +++ b/src/python_wrap/celery.py @@ -539,8 +539,8 @@ def idempotent_task( ``x_pw_requeues`` header, up to ``requeue_limit`` (default: enough for a crashed owner's lease to expire, ``ceil(lease_ttl / requeue_delay) + 2``). Then `AlreadyRunning` is raised. - Use a shared ``store`` (``RedisStore(client, prefix, fail_open=False)``) so every worker - sees the same results; the default is per process. Same crash gap as `idempotent`: an + Use a shared ``store`` such as ``RedisStore(client, prefix, on_backend_error='raise')`` + so every worker sees the same results. The default is per process. As with `idempotent`, an external effect and its recorded result are not one atomic step. Args: diff --git a/src/python_wrap/coordination.py b/src/python_wrap/coordination.py index 6864d19..f709dad 100644 --- a/src/python_wrap/coordination.py +++ b/src/python_wrap/coordination.py @@ -1,4 +1,7 @@ -"""Local and distributed owner-checked leases and single-instance decorators.""" +"""Local and distributed owner-checked leases and single-instance decorators. + +Provisional: may change in a minor release. +""" from __future__ import annotations diff --git a/src/python_wrap/events.py b/src/python_wrap/events.py index 790cb39..1bd077c 100644 --- a/src/python_wrap/events.py +++ b/src/python_wrap/events.py @@ -129,11 +129,6 @@ "A Cassette recorded one HTTP exchange. function is 'cassette'. " "Fields: status (int), key (str, the first 12 characters of the request key)." ), - "rate_limit.store_error": ( - "A shared token window could not reach its storage and fell back to a local " - "bucket (or raised, with fail_open=False). function is the window name. " - "Fields: error (str, the exception class), op (str)." - ), "backend.error": ( "A shared backend (breaker state, window, quota, cache store, switch source) " "raised. function is the backend name. Fields: backend (str kind), operation " diff --git a/src/python_wrap/idempotency.py b/src/python_wrap/idempotency.py index 18190ff..d49ebd2 100644 --- a/src/python_wrap/idempotency.py +++ b/src/python_wrap/idempotency.py @@ -336,7 +336,7 @@ def idempotent( `python_wrap.async_cache.AsyncCacheStore` (for ``async def`` functions): it is awaited directly, and an `AsyncRedisStore` gets a matching `AsyncRedisLock`. Failed calls release their lease without caching. Distributed use requires BOTH a - shared result store and shared lease backend; RedisStore(fail_open=False) + shared result store and shared lease backend; RedisStore(on_backend_error='raise') automatically supplies a matching RedisLock unless a backend is explicitly given. Other shared stores need an explicitly supplied shared lease backend. This cannot guarantee exactly-once external effects across a process crash between @@ -360,7 +360,7 @@ def idempotent( raise ValueError("in_progress must be raise, wait or return_none") results: Any = MemoryResultStore() if store is None else store if getattr(results, "fail_open", False): - raise ValueError("idempotency requires a result store with fail_open=False") + raise ValueError("idempotency requires a result store with on_backend_error='raise'") if backend is not None and not isinstance(backend, LocalLease) and store is None: raise ValueError("a distributed lease requires an explicitly shared result store") async_sql = isinstance(results, SqlResultStore) and hasattr(results.engine, "sync_engine") diff --git a/src/python_wrap/llm_shared.py b/src/python_wrap/llm_shared.py index c31235a..4271b14 100644 --- a/src/python_wrap/llm_shared.py +++ b/src/python_wrap/llm_shared.py @@ -35,7 +35,7 @@ from typing import Any from python_wrap import _core, _fork -from python_wrap._backend import _NOT_GIVEN, BackendMonitor, resolve_mode +from python_wrap._backend import BackendMonitor, resolve_mode from python_wrap._scripts import Script __all__ = [ @@ -312,12 +312,11 @@ class SharedTokenWindow: project default when nothing is configured) serves the call from a private in-memory bucket, so an outage degrades to per-process limiting instead of stopping every LLM call. ``"allow"`` admits the call without accounting. ``"raise"`` raises. Every error - emits ``backend.error`` and ``rate_limit.store_error``. + emits ``backend.error``. Attributes: name: Identifies the bucket inside the storage; share it to share the quota. on_backend_error: The resolved mode (``"raise"``, ``"local"`` or ``"allow"``). - fail_open: Derived from the mode (true unless it is ``"raise"``); deprecated. """ def __init__( @@ -325,14 +324,12 @@ def __init__( name: str = "tokens", *, on_backend_error: str | None = None, - fail_open: Any = _NOT_GIVEN, ) -> None: if not name: raise ValueError("a window needs a nonempty name") self.name = name - mode = resolve_mode(on_backend_error, fail_open, type(self).__name__, "local") + mode = resolve_mode(on_backend_error, "local") self.on_backend_error = mode - self.fail_open = mode != "raise" self._monitor = BackendMonitor("tokens", name, mode) self._fallback: _State | None = None self._flock = _fork.ForkSafeLock() @@ -352,10 +349,6 @@ def _local(self, op: str, a: float, b: float, capacity: float, rate: float) -> f ) return result - def _store_error(self, exc: Exception, op: str) -> None: - # Kept until 0.6.0; the generic backend.error event is emitted by the monitor. - _core.emit("rate_limit.store_error", self.name, error=type(exc).__name__, op=op) - def _degraded(self, op: str, a: float, b: float, capacity: float, rate: float) -> float: """Answer for a failed store: the local bucket, or admission without accounting.""" if self._monitor.mode == "local": @@ -363,14 +356,11 @@ def _degraded(self, op: str, a: float, b: float, capacity: float, rate: float) - return float(capacity) if op == "level" else 0.0 def _run(self, op: str, a: float, b: float, capacity: float, rate: float) -> float: - def store() -> float: - try: - return self._transact(op, a, b, capacity, rate) - except Exception as exc: - self._store_error(exc, op) - raise - - return self._monitor.call(op, store, lambda: self._degraded(op, a, b, capacity, rate)) + return self._monitor.call( + op, + lambda: self._transact(op, a, b, capacity, rate), + lambda: self._degraded(op, a, b, capacity, rate), + ) # -- the limiter-facing operations -------------------------------------------- def reserve(self, tokens: int, capacity: float, rate: float) -> float: @@ -524,7 +514,6 @@ class SQLiteTokenWindow(SharedTokenWindow): failed (see ``on_backend_error``). on_backend_error: ``"local"`` (default: an in-memory bucket), ``"allow"`` or ``"raise"``. Defaults to ``configure(backend_errors=)``. - fail_open: Deprecated alias (removed in 0.6.0) for ``on_backend_error``. Example: ```python @@ -550,9 +539,8 @@ def __init__( *, timeout: float = 10.0, on_backend_error: str | None = None, - fail_open: Any = _NOT_GIVEN, ) -> None: - super().__init__(name, on_backend_error=on_backend_error, fail_open=fail_open) + super().__init__(name, on_backend_error=on_backend_error) self._file = _SQLiteFile( path, timeout, @@ -709,7 +697,6 @@ class RedisTokenWindow(SharedTokenWindow): prefix: Namespace for the key. on_backend_error: ``"local"`` (default: an in-memory bucket), ``"allow"`` or ``"raise"`` when Redis fails. Defaults to ``configure(backend_errors=)``. - fail_open: Deprecated alias (removed in 0.6.0) for ``on_backend_error``. """ def __init__( @@ -719,9 +706,8 @@ def __init__( *, prefix: str = "python-wrap:tokens", on_backend_error: str | None = None, - fail_open: Any = _NOT_GIVEN, ) -> None: - super().__init__(name, on_backend_error=on_backend_error, fail_open=fail_open) + super().__init__(name, on_backend_error=on_backend_error) if not prefix: raise ValueError("RedisTokenWindow needs a nonempty prefix") self.client, self.prefix = client, prefix @@ -757,9 +743,8 @@ def __init__( *, prefix: str = "python-wrap:tokens", on_backend_error: str | None = None, - fail_open: Any = _NOT_GIVEN, ) -> None: - super().__init__(name, on_backend_error=on_backend_error, fail_open=fail_open) + super().__init__(name, on_backend_error=on_backend_error) if not prefix: raise ValueError("AsyncRedisTokenWindow needs a nonempty prefix") self.client, self.prefix = client, prefix @@ -779,14 +764,10 @@ def _transact(self, op: str, a: float, b: float, capacity: float, rate: float) - async def _arun(self, op: str, a: float, b: float, capacity: float, rate: float) -> float: async def store() -> float: - try: - reply = await _LUA_STEP_SCRIPT.arun( - self.client, *_redis_args(self.name, self.prefix, op, a, b, capacity, rate) - ) - return float(reply) - except Exception as exc: - self._store_error(exc, op) - raise + reply = await _LUA_STEP_SCRIPT.arun( + self.client, *_redis_args(self.name, self.prefix, op, a, b, capacity, rate) + ) + return float(reply) return await self._monitor.acall( op, store, lambda: self._degraded(op, a, b, capacity, rate) diff --git a/src/python_wrap/observability.py b/src/python_wrap/observability.py index 1f1ead0..34beacf 100644 --- a/src/python_wrap/observability.py +++ b/src/python_wrap/observability.py @@ -60,10 +60,6 @@ "pw_backend_errors_total", "python_wrap.backend.errors", "{error}", "Errors from a shared backend (function is the backend name).", ), - "rate_limit.store_error": ( - "pw_rate_limit_store_errors_total", "python_wrap.rate_limit.store_errors", "{error}", - "Errors from a shared token window's storage.", - ), } # fmt: skip WAIT = ("pw_limiter_wait_seconds", "python_wrap.rate_limit.wait") BREAKER_STATE = ("pw_breaker_state", "python_wrap.circuit.state") diff --git a/src/python_wrap/stores.py b/src/python_wrap/stores.py index 3ebece0..02b0027 100644 --- a/src/python_wrap/stores.py +++ b/src/python_wrap/stores.py @@ -15,7 +15,7 @@ from collections.abc import Callable, Hashable from typing import Any -from python_wrap._backend import _NOT_GIVEN, BackendMonitor, resolve_mode +from python_wrap._backend import BackendMonitor, resolve_mode from python_wrap._runtime import stable_digest KEY_FORMAT = "k2:" # key encoding version: entries written by 0.4.0b1 expire unread @@ -107,7 +107,6 @@ class RedisStore: on_backend_error: ``"allow"`` (a miss; writes are dropped), ``"raise"`` or ``"local"`` (same as ``"allow"`` for a cache). Defaults to ``configure(backend_errors=)``, then ``"allow"``. Every error emits ``backend.error``. - fail_open: Deprecated alias (removed in 0.6.0): ``True`` is ``"allow"``, ``False`` is ``"raise"``. Ignored when ``on_backend_error`` is given. `size()` is unknown (None); `cache_info()` never scans Redis. `clear()` scans only @@ -127,7 +126,6 @@ def __init__( loads: Callable[[bytes], Any] | None = None, key_format: Callable[[Hashable], str] | None = None, on_backend_error: str | None = None, - fail_open: Any = _NOT_GIVEN, retry_backend_after: float = 1.0, version: int | None = None, ) -> None: @@ -146,7 +144,7 @@ def __init__( # Plain pickle on a shared store lets anyone who can write the namespace run code # in every reader; doctor reports it (PW026). self.implicit_pickle = self.dumps is pickle.dumps - mode = resolve_mode(on_backend_error, fail_open, type(self).__name__, "allow") + mode = resolve_mode(on_backend_error, "allow") mode = "allow" if mode == "local" else mode # a miss is already the local answer self.key_format, self.on_backend_error = key_format, mode self.fail_open = mode != "raise" # derived; idempotency and web read it diff --git a/src/python_wrap/web.py b/src/python_wrap/web.py index 76c1551..5c1ad53 100644 --- a/src/python_wrap/web.py +++ b/src/python_wrap/web.py @@ -130,7 +130,7 @@ def __init__( if isinstance(max_body, bool) or not isinstance(max_body, int) or max_body < 0: raise ValueError("max_body must be a non-negative integer") if getattr(store, "fail_open", False): - raise ValueError("idempotency requires a result store with fail_open=False") + raise ValueError("idempotency requires a result store with on_backend_error='raise'") self.store = MemoryResultStore() if store is None else store self.backend = LocalLease() if backend is None else backend self.methods = frozenset(m.upper() for m in methods) diff --git a/tests/test_async_cache.py b/tests/test_async_cache.py index 5103377..79d655b 100644 --- a/tests/test_async_cache.py +++ b/tests/test_async_cache.py @@ -390,7 +390,7 @@ async def test_redis_store_fail_open_true(caplog: pytest.LogCaptureFixture) -> N async def test_redis_store_fail_open_false() -> None: client = FakeAsyncRedis() client.fail = True - store = AsyncRedisStore(client, "p:", fail_open=False) + store = AsyncRedisStore(client, "p:", on_backend_error="raise") with pytest.raises(ConnectionError): await store.get("k") with pytest.raises(ConnectionError): diff --git a/tests/test_backend_rules.py b/tests/test_backend_rules.py index 8f9674d..19d97a8 100644 --- a/tests/test_backend_rules.py +++ b/tests/test_backend_rules.py @@ -21,7 +21,7 @@ from python_wrap.config import configured from python_wrap.coordination import AsyncRedisLock, Lease, RedisLock from python_wrap.events import listening -from python_wrap.llm_shared import RedisTokenWindow +from python_wrap.llm_shared import AsyncRedisTokenWindow, RedisTokenWindow, SQLiteTokenWindow from python_wrap.quotas import Quota from python_wrap.shared import RedisBreakerState, SharedBulkhead from python_wrap.stores import RedisStore, json_codec @@ -65,20 +65,12 @@ def test_cache_store_reads_project_default() -> None: assert explicit.get("k") is None # the argument wins over the project default -def test_fail_open_alias_warns_and_maps() -> None: - with pytest.warns(DeprecationWarning, match="0.6.0"): - strict = _store("alias-strict:", fail_open=False) - assert strict.fail_open is False - with pytest.raises(ConnectionError): - strict.get("k") - with pytest.warns(DeprecationWarning, match="0.6.0"): - lenient = _store("alias-lenient:", fail_open=True) - assert lenient.fail_open is True and lenient.get("k") is None - with pytest.warns(DeprecationWarning, match="0.6.0"): - ignored = _store("alias-ignored:", on_backend_error="raise", fail_open=True) - assert ignored.on_backend_error == "raise" - with pytest.raises(ValueError): - _store("alias-bad:", on_backend_error="nope") +def test_fail_open_keyword_was_removed() -> None: + for store_type in (RedisStore, AsyncRedisStore, RedisTokenWindow, AsyncRedisTokenWindow): + with pytest.raises(TypeError, match="fail_open"): + store_type(Dead(), "legacy:", fail_open=False) + with pytest.raises(TypeError, match="fail_open"): + SQLiteTokenWindow("never-opened.db", fail_open=False) def test_token_window_emits_backend_error_and_falls_back_local() -> None: @@ -91,7 +83,7 @@ def test_token_window_emits_backend_error_and_falls_back_local() -> None: window.force(10, 100, 1.0) names = _names(events) assert names.count("backend.error") == 1 # later calls skip the dead store - assert "rate_limit.store_error" in names + assert "rate_limit.store_error" not in names def test_token_window_allow_admits() -> None: diff --git a/tests/test_effect_ledger.py b/tests/test_effect_ledger.py index ea64387..d57e260 100644 --- a/tests/test_effect_ledger.py +++ b/tests/test_effect_ledger.py @@ -278,8 +278,8 @@ def test_ledger_argument_validation(tmp_path: Path) -> None: def test_redis_store_reuses_redis_store_settings() -> None: client = FakeRedis() with pytest.raises(ValueError): - EffectLedger(RedisStore(client, "pfx:")) # fail_open=True by default - ledger = EffectLedger(RedisStore(client, "pfx:", fail_open=False)) + EffectLedger(RedisStore(client, "pfx:")) # cache writes are skipped by default + ledger = EffectLedger(RedisStore(client, "pfx:", on_backend_error="raise")) assert isinstance(ledger.store, RedisEffectStore) assert ledger.store.prefix == "pfx:effects:" diff --git a/tests/test_llm_shared.py b/tests/test_llm_shared.py index 1bf742d..91a6e77 100644 --- a/tests/test_llm_shared.py +++ b/tests/test_llm_shared.py @@ -336,22 +336,22 @@ def test_unusable_path_falls_open_to_a_local_bucket(self, tmp_path: Path) -> Non assert window.reserve(60, 100, 1.0) > 0 # the fallback still limits, per process finally: _core.listeners.pop() - assert "rate_limit.store_error" in events + assert "backend.error" in events def test_fail_closed_raises(self, tmp_path: Path) -> None: - window = SQLiteTokenWindow(tmp_path / "missing" / "t.db", fail_open=False) + window = SQLiteTokenWindow(tmp_path / "missing" / "t.db", on_backend_error="raise") with pytest.raises(sqlite3.OperationalError): window.reserve(1, 100, 1.0) def test_corrupt_database_is_quarantined_and_rebuilt(self, db: str) -> None: Path(db).write_bytes(b"this is definitely not a sqlite database" * 50) - window = SQLiteTokenWindow(db, fail_open=False) + window = SQLiteTokenWindow(db, on_backend_error="raise") assert window.reserve(10, 100, 1.0) == 0 assert window.level(100, 1.0) == pytest.approx(90, abs=0.5) assert Path(db + ".corrupt").exists() def test_database_corrupted_mid_life_recovers(self, db: str) -> None: - window = SQLiteTokenWindow(db, fail_open=False) + window = SQLiteTokenWindow(db, on_backend_error="raise") window.reserve(10, 100, 1.0) size = os.path.getsize(db) with open(db, "r+b") as handle: # overwrite the header and a page: a partial write @@ -362,7 +362,7 @@ def test_database_corrupted_mid_life_recovers(self, db: str) -> None: assert window.reserve(10, 100, 1.0) == 0 # rebuilt, never an exception def test_truncated_database_file(self, db: str) -> None: - window = SQLiteTokenWindow(db, fail_open=False) + window = SQLiteTokenWindow(db, on_backend_error="raise") window.reserve(10, 100, 1.0) for suffix in ("-wal", "-shm"): if os.path.exists(db + suffix): @@ -378,7 +378,7 @@ def test_locked_database_times_out_then_falls_open(self, db: str) -> None: blocker.execute("BEGIN IMMEDIATE") try: assert window.reserve(1, 100, 1.0) == 0 # fell open, did not hang or raise - strict = SQLiteTokenWindow(db, timeout=0.05, fail_open=False) + strict = SQLiteTokenWindow(db, timeout=0.05, on_backend_error="raise") with pytest.raises(sqlite3.OperationalError): strict.reserve(1, 100, 1.0) finally: @@ -391,7 +391,7 @@ def test_name_required(self, db: str) -> None: def test_base_class_is_abstract(self) -> None: with pytest.raises(NotImplementedError): - SharedTokenWindow("x", fail_open=False).reserve(1, 1, 1) + SharedTokenWindow("x", on_backend_error="raise").reserve(1, 1, 1) # ---------------------------------------------------------------- budget backend (SQLite) @@ -447,7 +447,7 @@ def ask() -> Any: def test_sqlite_samples_time_after_acquiring_the_write_lock( db: str, fake_clock: Any, monkeypatch: pytest.MonkeyPatch ) -> None: - window = SQLiteTokenWindow(db, fail_open=False) + window = SQLiteTokenWindow(db, on_backend_error="raise") assert window.reserve(10, 10, 1) == 0 connection = window._file.connection @@ -469,7 +469,7 @@ def delayed_connection() -> Any: from python_wrap.llm_shared import SQLiteTokenWindow path, tries, tokens, capacity, rate, start = sys.argv[1:7] - window = SQLiteTokenWindow(path, fail_open=False, timeout=60) + window = SQLiteTokenWindow(path, on_backend_error="raise", timeout=60) while time.time() < float(start): time.sleep(0.001) admitted = 0 @@ -602,7 +602,7 @@ def test_outage_falls_open_or_raises(self) -> None: client.fail = True assert RedisTokenWindow(client).reserve(1, 100, 1.0) == 0 with pytest.raises(ConnectionError): - RedisTokenWindow(client, fail_open=False).reserve(1, 100, 1.0) + RedisTokenWindow(client, on_backend_error="raise").reserve(1, 100, 1.0) def test_bad_prefix(self) -> None: with pytest.raises(ValueError): @@ -631,7 +631,7 @@ async def main() -> None: def test_async_window_refuses_sync_use_and_falls_open_on_outage(self) -> None: client = AsyncFakeRedis() - window = AsyncRedisTokenWindow(client, fail_open=False) + window = AsyncRedisTokenWindow(client, on_backend_error="raise") with pytest.raises(RuntimeError, match="async-only"): window.reserve(1, 1, 1) client.fail = True @@ -649,8 +649,8 @@ class TestRedisWindowLive: """The Lua script against a real redis-server, including parity with the Python mirror.""" def test_script_matches_mirror_and_is_shared(self, redis_client: Any) -> None: - a = RedisTokenWindow(redis_client, "live-a", prefix="pw-test", fail_open=False) - b = RedisTokenWindow(redis_client, "live-a", prefix="pw-test", fail_open=False) + a = RedisTokenWindow(redis_client, "live-a", prefix="pw-test", on_backend_error="raise") + b = RedisTokenWindow(redis_client, "live-a", prefix="pw-test", on_backend_error="raise") assert a.reserve(400, 600, RATE) == 0 assert b.level(600, RATE) == pytest.approx(200, abs=2) wait = b.reserve(400, 600, RATE) @@ -661,14 +661,14 @@ def test_script_matches_mirror_and_is_shared(self, redis_client: Any) -> None: assert a.level(600, RATE) == pytest.approx(-400, abs=2) def test_observe_blocks_and_expires_with_ttl(self, redis_client: Any) -> None: - w = RedisTokenWindow(redis_client, "live-b", prefix="pw-test", fail_open=False) + w = RedisTokenWindow(redis_client, "live-b", prefix="pw-test", on_backend_error="raise") w.observe_headers({"retry-after": "30"}, capacity=600, rate=RATE) assert 28 < w.reserve(1, 600, RATE) <= 30 ttl = redis_client.execute("PTTL", "pw-test:live-b") assert ttl > 30000 def test_concurrent_reservations_never_over_admit(self, redis_client: Any) -> None: - w = RedisTokenWindow(redis_client, "live-c", prefix="pw-test", fail_open=False) + w = RedisTokenWindow(redis_client, "live-c", prefix="pw-test", on_backend_error="raise") def take(_: int) -> bool: return w.reserve(1, 40, 0.0001) == 0 diff --git a/tests/test_public_api.py b/tests/test_public_api.py index 396f9e5..75d39aa 100644 --- a/tests/test_public_api.py +++ b/tests/test_public_api.py @@ -64,13 +64,14 @@ async def coro(x: int) -> int: assert inspect.signature(wrapped) == inspect.signature(coro) -def test_moved_llm_and_agent_names_still_work_with_a_deprecation_warning(): - from python_wrap import llm - - with pytest.warns(DeprecationWarning, match="python_wrap.llm"): - assert python_wrap.Budget is llm.Budget - assert "Budget" not in python_wrap.__all__ - assert "Budget" in dir(python_wrap) - assert python_wrap.mcp_guard.__module__ == "python_wrap.mcp_guard" # stays a function - with pytest.raises(AttributeError): - python_wrap.no_such_name # noqa: B018 +def test_removed_llm_and_agent_names_require_submodule_imports(): + from python_wrap.agents import RunGuard + from python_wrap.llm import Budget + + assert Budget.__module__ == "python_wrap.llm" + assert RunGuard.__module__ == "python_wrap.agents" + for name in ("Budget", "RunGuard", "guard_openai", "fake_llm", "traced_llm"): + assert name not in dir(python_wrap) + with pytest.raises(AttributeError): + getattr(python_wrap, name) + assert python_wrap.mcp_guard.__module__ == "python_wrap.mcp_guard" diff --git a/tests/test_redis_backends.py b/tests/test_redis_backends.py index d7d0c07..f3cf000 100644 --- a/tests/test_redis_backends.py +++ b/tests/test_redis_backends.py @@ -147,8 +147,8 @@ def redis_client(): def test_store_roundtrip_ttl_unknown_size_and_escaped_clear(redis_client): - store = RedisStore(redis_client, "cache[*]?:", fail_open=False) - other = RedisStore(redis_client, "cacheABC:", fail_open=False) + store = RedisStore(redis_client, "cache[*]?:", on_backend_error="raise") + other = RedisStore(redis_client, "cacheABC:", on_backend_error="raise") store.set(("a",), {"value": 3}, 0.04) other.set(("a",), "keep", 60) assert store.get(("a",)) == {"value": 3} @@ -235,7 +235,7 @@ def bad(): def test_redis_idempotency_shared_result_and_lease(redis_client): - store = RedisStore(redis_client, "idem:", fail_open=False) + store = RedisStore(redis_client, "idem:", on_backend_error="raise") backend = RedisLock(redis_client, "idem-locks:") calls = [] @@ -318,8 +318,12 @@ def body(): calls.append(1) return 11 - a = idempotent(key="auto", store=RedisStore(redis_client, "auto-idem:", fail_open=False))(body) - b = idempotent(key="auto", store=RedisStore(redis_client, "auto-idem:", fail_open=False))(body) + a = idempotent( + key="auto", store=RedisStore(redis_client, "auto-idem:", on_backend_error="raise") + )(body) + b = idempotent( + key="auto", store=RedisStore(redis_client, "auto-idem:", on_backend_error="raise") + )(body) assert a() == b() == 11 and calls == [1] @@ -433,7 +437,7 @@ def test_redis_tags_and_stampede_lease_across_wrappers(redis_client): from python_wrap import invalidate_tags from python_wrap.caching import _tag_keys - store = RedisStore(redis_client, "tagged:", fail_open=False) + store = RedisStore(redis_client, "tagged:", on_backend_error="raise") calls = [] def price(sku): diff --git a/tests/test_redis_scripts_live.py b/tests/test_redis_scripts_live.py index ea3d1b5..0434907 100644 --- a/tests/test_redis_scripts_live.py +++ b/tests/test_redis_scripts_live.py @@ -198,7 +198,7 @@ def test_window_script_runs_live(redis_client): def test_token_window_script_runs_live(redis_client): rec = Recording(redis_client) - window = RedisTokenWindow(rec, _name("live-tokens"), fail_open=False) + window = RedisTokenWindow(rec, _name("live-tokens"), on_backend_error="raise") assert window.reserve(4, capacity=10, rate=1.0) == 0.0 level = window.level(10, 1.0) assert 5.0 < level < 6.5 # 10 - 4, plus the refill since the reserve diff --git a/tests/test_release_metadata.py b/tests/test_release_metadata.py index 933679b..5725d2c 100644 --- a/tests/test_release_metadata.py +++ b/tests/test_release_metadata.py @@ -7,7 +7,7 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -PROVISIONAL_MODULES = ["shared", "quotas", "stores", "http", "celery"] +PROVISIONAL_MODULES = ["shared", "coordination", "quotas", "stores", "http", "celery"] def _load_check_release(): diff --git a/tests/test_stability.py b/tests/test_stability.py index 72bb144..f93239e 100644 --- a/tests/test_stability.py +++ b/tests/test_stability.py @@ -107,7 +107,7 @@ def test_retry_parameters_stay_keyword_only(): def test_shared_backend_key_formats_are_frozen(): from types import SimpleNamespace - from python_wrap._runtime import digest + from python_wrap._runtime import name_digest from python_wrap.caching import _TAG_PREFIX from python_wrap.coordination import RedisLock from python_wrap.http import _pause_key @@ -115,7 +115,7 @@ def test_shared_backend_key_formats_are_frozen(): from python_wrap.shared import RedisBreakerState, RedisRetryBudget from python_wrap.stores import KEY_FORMAT - assert digest("vendor") == VENDOR_DIGEST + assert name_digest("vendor") == VENDOR_DIGEST breaker = SimpleNamespace( name="vendor", failure_threshold=5, window=None, recovery_timeout=30, half_open_max_calls=1, success_threshold=1, From 50dc07a98a095ae0d2345887e3c522751539193c Mon Sep 17 00:00:00 2001 From: Pythondeveloper6 Date: Fri, 4 Dec 2026 14:14:19 +0200 Subject: [PATCH 37/38] Consolidate pending features on the 0.6 release branch --- CHANGELOG.md | 13 +++++++++---- RELEASING.md | 13 ++++++++----- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 64dbda0..d1b27b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,12 @@ Breaking changes are listed under **Breaking changes**, each with its migration. ## [Unreleased] +## [0.6.0b1] - 2026-12-04 + +This beta consolidates the feature work, fixes, default changes and API removals +since the last published `0.4.0` release. See the [0.6 migration guide] for the +replacement APIs and metrics. + ### Breaking changes - Redis cache stores and shared token windows no longer accept `fail_open=`. Use @@ -21,8 +27,6 @@ Breaking changes are listed under **Breaking changes**, each with its migration. - The deprecated LLM, agent and MCP imports leave the `python_wrap` package root. Use the documented submodule imports. The `mcp_guard` top-level entry point stays available. -## [0.5.0b1] - 2026-12-04 - ### Security - Shared SQLite token windows now sample time after taking the writer lock and keep stored @@ -993,8 +997,9 @@ Core: Initial release. -[Unreleased]: https://github.com/LitePy/PythonWrap/compare/v0.5.0b1...HEAD -[0.5.0b1]: https://github.com/LitePy/PythonWrap/compare/v0.4.0...v0.5.0b1 +[Unreleased]: https://github.com/LitePy/PythonWrap/compare/v0.6.0b1...HEAD +[0.6.0b1]: https://github.com/LitePy/PythonWrap/compare/v0.4.0...v0.6.0b1 +[0.6 migration guide]: https://pythonwrap.readthedocs.io/en/latest/project/migration/#upgrading-to-06 [0.4.0]: https://github.com/LitePy/PythonWrap/compare/v0.4.0b2...v0.4.0 [0.4.0b1]: https://github.com/LitePy/PythonWrap/compare/v0.3.0...v0.4.0b1 [0.3.0]: https://github.com/LitePy/PythonWrap/compare/v0.2.1...v0.3.0 diff --git a/RELEASING.md b/RELEASING.md index 283f3db..0dee5f6 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -27,12 +27,15 @@ was removed; revoke the token it used at Date: Fri, 4 Dec 2026 15:41:12 +0200 Subject: [PATCH 38/38] Keep migrated and documented retry schedules under the new defaults --- CHANGELOG.md | 3 ++ docs/cookbook/testing-your-code.md | 2 +- docs/features/ai/testing-agents.md | 2 +- docs/features/resilience/retry.md | 2 +- docs/llms-full.txt | 6 +-- docs/project/migrate-tool.md | 4 +- docs/project/migrating-from-tenacity.md | 4 +- docs/testing/index.md | 4 +- src/python_wrap/migrate.py | 6 ++- tests/test_migrate.py | 70 +++++++++++++++++-------- 10 files changed, 69 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d1b27b5..770cc8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -75,6 +75,9 @@ replacement APIs and metrics. ### Fixed +- `python_wrap migrate` writes `jitter=0` and `max_delay=None` for source schedules that set + neither, so migrated waits are no longer jittered or capped by the new retry defaults. + - Forked PostgreSQL and SQL Server lock backends preserve the parent's active SQL sessions while opening a separate pool in the child. - Celery deliveries waiting on an idempotency lease preserve the task retry counter. diff --git a/docs/cookbook/testing-your-code.md b/docs/cookbook/testing-your-code.md index bae98eb..0ca82b7 100644 --- a/docs/cookbook/testing-your-code.md +++ b/docs/cookbook/testing-your-code.md @@ -55,7 +55,7 @@ gateway = Gateway() breaker = CircuitBreaker(failure_threshold=3, recovery_timeout=60, on=ConnectionError) -@retry(max_attempts=5, delay=30, backoff=2, on=ConnectionError) # up to 7.5 minutes of waiting! +@retry(max_attempts=5, delay=30, backoff=2, jitter=0, max_delay=300, on=ConnectionError) # up to 7.5 minutes of waiting! def charge_with_retry(amount: int) -> str: return gateway.charge(amount) diff --git a/docs/features/ai/testing-agents.md b/docs/features/ai/testing-agents.md index c72fe2f..84c8340 100644 --- a/docs/features/ai/testing-agents.md +++ b/docs/features/ai/testing-agents.md @@ -175,7 +175,7 @@ from python_wrap.testing import fake_clock llm = fake_llm(['{"answer": 42}'], usage=(20, 6)) -@retry(max_attempts=5, delay=30.0, backoff=2, on=(RateLimitError, OverloadedError)) +@retry(max_attempts=5, delay=30.0, backoff=2, jitter=0, max_delay=300, on=(RateLimitError, OverloadedError)) def agent(question: str) -> dict: return json.loads(llm.complete(messages=[{"role": "user", "content": question}]).text) diff --git a/docs/features/resilience/retry.md b/docs/features/resilience/retry.md index 64183b3..c159d1c 100644 --- a/docs/features/resilience/retry.md +++ b/docs/features/resilience/retry.md @@ -499,7 +499,7 @@ from python_wrap import attempt_history, retry from python_wrap.testing import fake_clock -@retry(max_attempts=3, delay=1, backoff=2, on=ConnectionError) +@retry(max_attempts=3, delay=1, backoff=2, jitter=0, on=ConnectionError) def fetch() -> None: raise ConnectionError("refused") diff --git a/docs/llms-full.txt b/docs/llms-full.txt index 54dc961..931b0d1 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -2345,7 +2345,7 @@ from python_wrap.testing import fake_clock llm = fake_llm(['{"answer": 42}'], usage=(20, 6)) -@retry(max_attempts=5, delay=30.0, backoff=2, on=(RateLimitError, OverloadedError)) +@retry(max_attempts=5, delay=30.0, backoff=2, jitter=0, max_delay=300, on=(RateLimitError, OverloadedError)) def agent(question: str) -> dict: return json.loads(llm.complete(messages=[{"role": "user", "content": question}]).text) @@ -3873,7 +3873,7 @@ from python_wrap.testing import fake_clock calls = [] -@retry(max_attempts=4, delay=1.0, backoff=2, on=ConnectionError) +@retry(max_attempts=4, delay=1.0, backoff=2, jitter=0, on=ConnectionError) def flaky() -> str: calls.append(1) if len(calls) < 4: @@ -4013,7 +4013,7 @@ from python_wrap import _core, retry sleeps: list[float] = [] calls = [] -@retry(max_attempts=4, delay=1.0, backoff=2, on=ConnectionError) +@retry(max_attempts=4, delay=1.0, backoff=2, jitter=0, on=ConnectionError) def flaky() -> str: calls.append(1) if len(calls) < 4: diff --git a/docs/project/migrate-tool.md b/docs/project/migrate-tool.md index cc3926c..065f11c 100644 --- a/docs/project/migrate-tool.md +++ b/docs/project/migrate-tool.md @@ -41,7 +41,7 @@ def fetch(): ... """ result = migrate_source(source) print(result.text) -assert "@retry(max_attempts=5, delay=1, backoff=2, max_delay=30)" in result.text +assert "@retry(max_attempts=5, delay=1, backoff=2, max_delay=30, jitter=0)" in result.text assert result.unsupported == [] assert result.changes[0].line == 3 ``` @@ -50,6 +50,8 @@ assert result.changes[0].line == 3 ## What it rewrites +`retry` jitters and caps waits at 30 s by default. When the source waits between attempts, the tool also writes `jitter=0` and `max_delay=None` wherever the source set neither, so the schedule does not change. The tables below leave those two out. + ### tenacity `@retry(...)` and `@tenacity.retry(...)` | tenacity | becomes | diff --git a/docs/project/migrating-from-tenacity.md b/docs/project/migrating-from-tenacity.md index 091d1e6..6b0fdad 100644 --- a/docs/project/migrating-from-tenacity.md +++ b/docs/project/migrating-from-tenacity.md @@ -24,7 +24,7 @@ python-wrap's `retry` covers the common tenacity patterns with one decorator and ```python from python_wrap import retry - @retry(on=ConnectionError, max_attempts=5, delay=1, backoff=2, max_delay=30) + @retry(on=ConnectionError, max_attempts=5, delay=1, backoff=2, max_delay=30, jitter=0) def fetch() -> str: return "ok" @@ -46,6 +46,8 @@ python-wrap's `retry` covers the common tenacity patterns with one decorator and ## Wait strategies +`retry` jitters and caps waits at 30 s by default, tenacity does not. Add `jitter=0` and `max_delay=None` to any row below that does not set them. + | tenacity | python-wrap | | --- | --- | | `wait_fixed(s)` | `delay=s, backoff=1` | diff --git a/docs/testing/index.md b/docs/testing/index.md index dbfbdc3..021cb8f 100644 --- a/docs/testing/index.md +++ b/docs/testing/index.md @@ -71,7 +71,7 @@ from python_wrap.testing import fake_clock calls = [] -@retry(max_attempts=4, delay=1.0, backoff=2, on=ConnectionError) +@retry(max_attempts=4, delay=1.0, backoff=2, jitter=0, on=ConnectionError) def flaky() -> str: calls.append(1) if len(calls) < 4: @@ -211,7 +211,7 @@ from python_wrap import _core, retry sleeps: list[float] = [] calls = [] -@retry(max_attempts=4, delay=1.0, backoff=2, on=ConnectionError) +@retry(max_attempts=4, delay=1.0, backoff=2, jitter=0, on=ConnectionError) def flaky() -> str: calls.append(1) if len(calls) < 4: diff --git a/src/python_wrap/migrate.py b/src/python_wrap/migrate.py index 6e5c2ce..235aa8f 100644 --- a/src/python_wrap/migrate.py +++ b/src/python_wrap/migrate.py @@ -18,7 +18,7 @@ ... ) >>> print(result.text) from python_wrap import retry - @retry(max_attempts=3, delay=2, backoff=1) + @retry(max_attempts=3, delay=2, backoff=1, max_delay=None, jitter=0) def f(): ... """ @@ -264,6 +264,10 @@ def set(self, key: str, value: str) -> None: self.values[key] = value def render(self, name: str, indent: str, col: int) -> str: + if self.values.get("delay") != "0": + # retry() jitters and caps waits by default; the source schedule did neither. + self.values.setdefault("jitter", "0") + self.values.setdefault("max_delay", "None") items = [f"{k}={self.values[k]}" for k in self.ORDER if k in self.values] one = f"{name}({', '.join(items)})" if col + len(one) + 1 <= _LINE_LIMIT and "\n" not in one: diff --git a/tests/test_migrate.py b/tests/test_migrate.py index d627278..6f9464d 100644 --- a/tests/test_migrate.py +++ b/tests/test_migrate.py @@ -8,6 +8,7 @@ import pytest from python_wrap.migrate import main, migrate_source +from python_wrap.testing import fake_clock TENACITY_IMPORT = ( "from tenacity import retry, stop_after_attempt, stop_after_delay, wait_fixed, " @@ -33,36 +34,36 @@ def _rewrite(decorator: str, imports: str = TENACITY_IMPORT) -> str: [ ( "@retry(stop=stop_after_attempt(3), wait=wait_fixed(2))", - "@retry(max_attempts=3, delay=2, backoff=1)", + "@retry(max_attempts=3, delay=2, backoff=1, max_delay=None, jitter=0)", ), ( "@retry(stop=stop_after_attempt(5) | stop_after_delay(30), wait=wait_fixed(1))", - "@retry(max_attempts=5, delay=1, backoff=1, max_time=30)", + "@retry(max_attempts=5, delay=1, backoff=1, max_delay=None, jitter=0, max_time=30)", ), ( "@retry(stop=stop_after_attempt(4), wait=wait_exponential(multiplier=2, max=60))", - "@retry(max_attempts=4, delay=2, backoff=2, max_delay=60)", + "@retry(max_attempts=4, delay=2, backoff=2, max_delay=60, jitter=0)", ), ( "@retry(stop=stop_after_attempt(4), " "wait=wait_exponential(multiplier=1, min=4, max=10))", - "@retry(max_attempts=4, delay=4, backoff=2, max_delay=10)", + "@retry(max_attempts=4, delay=4, backoff=2, max_delay=10, jitter=0)", ), ( "@retry(stop=stop_after_attempt(4), wait=wait_exponential(exp_base=3))", - "@retry(max_attempts=4, delay=1, backoff=3)", + "@retry(max_attempts=4, delay=1, backoff=3, max_delay=None, jitter=0)", ), ( "@retry(stop=stop_after_attempt(2), wait=wait_random(1, 3))", - "@retry(max_attempts=2, delay=1, backoff=1, jitter=2)", + "@retry(max_attempts=2, delay=1, backoff=1, max_delay=None, jitter=2)", ), ( "@retry(stop=stop_after_attempt(2), wait=wait_fixed(2) + wait_random(0, 1))", - "@retry(max_attempts=2, delay=2, backoff=1, jitter=1)", + "@retry(max_attempts=2, delay=2, backoff=1, max_delay=None, jitter=1)", ), ( "@retry(stop=stop_after_attempt(2), wait=wait_fixed(2) + wait_random(1, 3))", - "@retry(max_attempts=2, delay=3, backoff=1, jitter=2)", + "@retry(max_attempts=2, delay=3, backoff=1, max_delay=None, jitter=2)", ), ( "@retry(stop=stop_after_attempt(6), " @@ -76,7 +77,8 @@ def _rewrite(decorator: str, imports: str = TENACITY_IMPORT) -> str: ( "@retry(stop=stop_after_attempt(3), wait=wait_fixed(1), " "retry=retry_if_exception_type(ConnectionError))", - "@retry(on=ConnectionError, max_attempts=3, delay=1, backoff=1)", + "@retry(on=ConnectionError, max_attempts=3, delay=1, backoff=1, " + "max_delay=None, jitter=0)", ), ( "@retry(stop=stop_after_attempt(3), retry=retry_if_exception_type((A, B)))", @@ -102,13 +104,13 @@ def _rewrite(decorator: str, imports: str = TENACITY_IMPORT) -> str: ), ( "@retry(wait=wait_fixed(1))", - "@retry(max_attempts=None, delay=1, backoff=1)", + "@retry(max_attempts=None, delay=1, backoff=1, max_delay=None, jitter=0)", ), ("@retry", "@retry(max_attempts=None, delay=0, backoff=1)"), ("@retry()", "@retry(max_attempts=None, delay=0, backoff=1)"), ( "@retry(stop=stop_never, wait=wait_fixed(1))", - "@retry(max_attempts=None, delay=1, backoff=1)", + "@retry(max_attempts=None, delay=1, backoff=1, max_delay=None, jitter=0)", ), ], ) @@ -127,7 +129,7 @@ def test_tenacity_module_attribute_and_alias_forms() -> None: assert result.text == ( "from python_wrap import retry\n" "\n" - "@retry(max_attempts=3, delay=1, backoff=1)\n" + "@retry(max_attempts=3, delay=1, backoff=1, max_delay=None, jitter=0)\n" "def f(): ...\n" ) aliased = migrate_source( @@ -170,32 +172,38 @@ def test_long_decorator_is_wrapped() -> None: [ ( "@backoff.on_exception(backoff.expo, ConnectionError, max_tries=5, jitter=None)", - "@retry(on=ConnectionError, max_attempts=5, delay=1, backoff=2)", + "@retry(on=ConnectionError, max_attempts=5, delay=1, backoff=2, " + "max_delay=None, jitter=0)", ), ( "@backoff.on_exception(backoff.expo, (A, B), max_tries=3, max_time=60, " "factor=2, base=3, max_value=30, jitter=None)", - "@retry(on=(A, B), max_attempts=3, delay=2, backoff=3, max_delay=30, max_time=60)", + "@retry(on=(A, B), max_attempts=3, delay=2, backoff=3, " + "max_delay=30, jitter=0, max_time=60)", ), ( "@backoff.on_exception(backoff.constant, OSError, interval=4, max_tries=2, " "jitter=None)", - "@retry(on=OSError, max_attempts=2, delay=4, backoff=1)", + "@retry(on=OSError, max_attempts=2, delay=4, backoff=1, max_delay=None, jitter=0)", ), ( "@backoff.on_exception(backoff.expo, OSError, jitter=None)", - "@retry(on=OSError, max_attempts=None, delay=1, backoff=2)", + "@retry(on=OSError, max_attempts=None, delay=1, backoff=2, max_delay=None, jitter=0)", ), ( "@backoff.on_predicate(backoff.constant, interval=3, max_tries=4, jitter=None)", - "@retry(on=(), max_attempts=4, delay=3, backoff=1, " - "retry_if_result=lambda result: not result)", + "@" + "retry(\n on=(),\n max_attempts=4,\n delay=3,\n backoff=1,\n" + " max_delay=None,\n" + " jitter=0,\n retry_if_result=lambda result: not result,\n)", ), ( "@backoff.on_predicate(backoff.expo, lambda r: r.status == 429, max_tries=4, " "jitter=None)", - "@retry(on=(), max_attempts=4, delay=1, backoff=2, " - "retry_if_result=lambda r: r.status == 429)", + "@" + "retry(\n on=(),\n max_attempts=4,\n delay=1,\n backoff=2,\n" + " max_delay=None,\n" + " jitter=0,\n retry_if_result=lambda r: r.status == 429,\n)", ), ], ) @@ -218,7 +226,8 @@ def test_backoff_from_import_form() -> None: "def f(): ...\n" ) assert result.text.startswith("from python_wrap import retry\n") - assert "@retry(on=OSError, max_attempts=2, delay=1, backoff=2)" in result.text + expected = "@retry(on=OSError, max_attempts=2, delay=1, backoff=2, max_delay=None, jitter=0)" + assert expected in result.text @pytest.mark.parametrize( @@ -482,7 +491,8 @@ def test_changed_decorator_is_valid_python_runtime() -> None: "def f(): ...\n" ) REWRITTEN = ( - "from python_wrap import retry\n\n@retry(max_attempts=3, delay=2, backoff=1)\ndef f(): ...\n" + "from python_wrap import retry\n\n@retry(max_attempts=3, delay=2, backoff=1, " + "max_delay=None, jitter=0)\ndef f(): ...\n" ) @@ -514,7 +524,7 @@ def test_cli_diff_prints_unified_diff_without_writing( out = capsys.readouterr().out assert "--- a/" in out and "+++ b/" in out assert "-from tenacity import" in out - assert "+@retry(max_attempts=3, delay=2, backoff=1)" in out + assert "+@retry(max_attempts=3, delay=2, backoff=1, max_delay=None, jitter=0)" in out assert (root / "pkg" / "a.py").read_text() == SAMPLE @@ -695,3 +705,17 @@ def test_llm_loop_cli_dry_run_diff_and_write( assert target.read_text() == original assert main(["--write", str(target)]) == 0 assert target.read_text() == (_FIXTURES / "sync_anthropic_after.txt").read_text() + + +def test_migrated_fixed_wait_keeps_its_schedule() -> None: + source = ( + "from tenacity import retry, stop_after_attempt, wait_fixed\n" + "@retry(stop=stop_after_attempt(3), wait=wait_fixed(60))\n" + "def f():\n" + " raise ConnectionError\n" + ) + namespace: dict[str, object] = {} + exec(migrate_source(source).text, namespace) + with fake_clock() as clock, pytest.raises(ConnectionError): + namespace["f"]() # type: ignore[operator] + assert clock.sleeps == [60, 60] # not jittered, not capped at the 30 s default