python-wrap 0.2.1__py3-none-any.whl → 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. python_wrap/__init__.py +348 -1
  2. python_wrap/__main__.py +57 -0
  3. python_wrap/_backend.py +133 -0
  4. python_wrap/_buckets.py +162 -0
  5. python_wrap/_core.py +12 -3
  6. python_wrap/_data/agent_guide.md +103 -0
  7. python_wrap/_data/recipes.json +703 -0
  8. python_wrap/_fork.py +113 -0
  9. python_wrap/_integration.py +29 -0
  10. python_wrap/_runtime.py +157 -0
  11. python_wrap/adapters/__init__.py +101 -0
  12. python_wrap/adapters/_frameworks.py +251 -0
  13. python_wrap/adapters/_sdk.py +1978 -0
  14. python_wrap/adapters/anthropic.py +139 -0
  15. python_wrap/adapters/langchain.py +288 -0
  16. python_wrap/adapters/openai.py +169 -0
  17. python_wrap/adapters/openai_agents.py +468 -0
  18. python_wrap/adapters/pydantic_ai.py +459 -0
  19. python_wrap/adaptive.py +605 -0
  20. python_wrap/agents.py +2503 -0
  21. python_wrap/alerts.py +293 -0
  22. python_wrap/async_cache.py +745 -0
  23. python_wrap/batching.py +17 -4
  24. python_wrap/buffering.py +952 -0
  25. python_wrap/bulkhead.py +58 -6
  26. python_wrap/caching.py +425 -56
  27. python_wrap/celery.py +528 -0
  28. python_wrap/chaos.py +519 -0
  29. python_wrap/circuit.py +454 -23
  30. python_wrap/compat.py +267 -0
  31. python_wrap/concurrency.py +82 -1746
  32. python_wrap/config.py +25 -4
  33. python_wrap/coordination.py +638 -0
  34. python_wrap/credentials.py +126 -0
  35. python_wrap/dashboard.py +358 -0
  36. python_wrap/debounce.py +538 -0
  37. python_wrap/django.py +100 -0
  38. python_wrap/doctor.py +599 -0
  39. python_wrap/events.py +145 -4
  40. python_wrap/exporters.py +663 -0
  41. python_wrap/fastapi.py +81 -0
  42. python_wrap/flask.py +61 -0
  43. python_wrap/genai.py +1101 -0
  44. python_wrap/health.py +187 -0
  45. python_wrap/http.py +940 -0
  46. python_wrap/idempotency.py +446 -0
  47. python_wrap/introspect.py +738 -0
  48. python_wrap/lifecycle.py +620 -0
  49. python_wrap/llm.py +2574 -0
  50. python_wrap/llm_cassette.py +948 -0
  51. python_wrap/llm_http_chaos.py +326 -0
  52. python_wrap/llm_shared.py +772 -0
  53. python_wrap/llm_testing.py +990 -0
  54. python_wrap/llm_validate.py +383 -0
  55. python_wrap/local_state.py +395 -0
  56. python_wrap/logs.py +82 -26
  57. python_wrap/mcp.py +490 -0
  58. python_wrap/mcp_guard.py +357 -0
  59. python_wrap/metrics.py +6 -3
  60. python_wrap/migrate.py +1452 -0
  61. python_wrap/observability.py +484 -0
  62. python_wrap/periodic.py +24 -2
  63. python_wrap/policies.py +396 -0
  64. python_wrap/policy.py +14 -0
  65. python_wrap/predicates.py +276 -0
  66. python_wrap/presets.py +378 -0
  67. python_wrap/processing.py +227 -0
  68. python_wrap/propagation.py +62 -0
  69. python_wrap/pytest_plugin.py +85 -0
  70. python_wrap/quotas.py +319 -0
  71. python_wrap/ratelimit.py +560 -0
  72. python_wrap/redaction.py +228 -0
  73. python_wrap/retry.py +448 -70
  74. python_wrap/shared.py +653 -0
  75. python_wrap/singleflight.py +255 -0
  76. python_wrap/slow.py +72 -0
  77. python_wrap/stores.py +168 -0
  78. python_wrap/switches.py +164 -0
  79. python_wrap/testing.py +34 -8
  80. python_wrap/timeouts.py +874 -0
  81. python_wrap/timing.py +239 -17
  82. python_wrap/validation.py +187 -12
  83. python_wrap/web.py +723 -0
  84. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
  85. python_wrap-0.4.0.dist-info/RECORD +95 -0
  86. python_wrap-0.2.1.dist-info/RECORD +0 -29
  87. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
  88. {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,133 @@
1
+ """One failure rule for every shared backend: ``on_backend_error``.
2
+
3
+ ``"raise"`` propagates the store error, ``"local"`` falls back to the in-process
4
+ implementation and ``"allow"`` admits the call and skips accounting. After an error the
5
+ store is skipped for ``retry_backend_after`` seconds so a dead store does not add its
6
+ connect timeout to every call. Emits ``backend.error`` and ``backend.recovered`` and
7
+ reports ``degraded`` through `python_wrap.health.health` while a fallback is active.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import time
13
+ from collections.abc import Awaitable, Callable
14
+ from typing import Any, TypeVar
15
+
16
+ from python_wrap import _core, _fork
17
+
18
+ __all__ = ["BACKEND_ERROR_MODES", "BackendMonitor"]
19
+
20
+ T = TypeVar("T")
21
+ BACKEND_ERROR_MODES = ("raise", "local", "allow")
22
+
23
+
24
+ def default_mode() -> str:
25
+ from python_wrap.config import get_config
26
+
27
+ return str(get_config()["backend_errors"] or "raise")
28
+
29
+
30
+ class BackendMonitor:
31
+ """Tracks one shared backend's health and applies its ``on_backend_error`` mode."""
32
+
33
+ def __init__(
34
+ self,
35
+ kind: str,
36
+ name: str,
37
+ on_backend_error: str | None = None,
38
+ retry_backend_after: float = 1.0,
39
+ *,
40
+ register: bool = True,
41
+ ) -> None:
42
+ if on_backend_error is not None and on_backend_error not in BACKEND_ERROR_MODES:
43
+ raise ValueError(f"on_backend_error must be one of {BACKEND_ERROR_MODES}")
44
+ if retry_backend_after < 0:
45
+ raise ValueError("retry_backend_after must be >= 0")
46
+ self.kind, self.name = kind, name
47
+ self._mode = on_backend_error
48
+ self.retry_backend_after = retry_backend_after
49
+ self._until = 0.0
50
+ self._down = False
51
+ self._lock = _fork.ForkSafeLock()
52
+ _fork.register(self)
53
+ if register:
54
+ from python_wrap.health import health
55
+
56
+ health.register(f"backend:{kind}:{name}", self)
57
+
58
+ def _reset_after_fork(self) -> None:
59
+ self._until, self._down = 0.0, False
60
+
61
+ @property
62
+ def mode(self) -> str:
63
+ return self._mode or default_mode()
64
+
65
+ @property
66
+ def degraded(self) -> bool:
67
+ return self._down
68
+
69
+ def _skipping(self) -> bool:
70
+ return self.mode != "raise" and time.monotonic() < self._until
71
+
72
+ def failed(self, exc: BaseException, operation: str) -> None:
73
+ with self._lock:
74
+ self._down = True
75
+ self._until = time.monotonic() + self.retry_backend_after
76
+ _core.get_logger(None).warning(
77
+ "%s backend %r: %s failed (%s); on_backend_error=%s",
78
+ self.kind,
79
+ self.name,
80
+ operation,
81
+ type(exc).__name__,
82
+ self.mode,
83
+ )
84
+ _core.emit(
85
+ "backend.error",
86
+ self.name,
87
+ backend=self.kind,
88
+ operation=operation,
89
+ error=type(exc).__name__,
90
+ )
91
+
92
+ def succeeded(self) -> None:
93
+ if self._down:
94
+ with self._lock:
95
+ recovered, self._down = self._down, False
96
+ if recovered:
97
+ _core.emit("backend.recovered", self.name, backend=self.kind)
98
+
99
+ def call(self, operation: str, fn: Callable[[], T], fallback: Callable[[], T]) -> T:
100
+ """Run ``fn``; on a store error apply the mode (``fallback`` serves local/allow)."""
101
+ if self._skipping():
102
+ return fallback()
103
+ try:
104
+ result = fn()
105
+ except Exception as exc:
106
+ self.failed(exc, operation)
107
+ if self.mode == "raise":
108
+ raise
109
+ return fallback()
110
+ self.succeeded()
111
+ return result
112
+
113
+ async def acall(
114
+ self, operation: str, fn: Callable[[], Awaitable[T]], fallback: Callable[[], Any]
115
+ ) -> T:
116
+ """`call` for awaitable store operations; ``fallback`` may be sync or async."""
117
+ import inspect
118
+
119
+ async def fall() -> Any:
120
+ value = fallback()
121
+ return await value if inspect.isawaitable(value) else value
122
+
123
+ if self._skipping():
124
+ return await fall() # type: ignore[no-any-return]
125
+ try:
126
+ result = await fn()
127
+ except Exception as exc:
128
+ self.failed(exc, operation)
129
+ if self.mode == "raise":
130
+ raise
131
+ return await fall() # type: ignore[no-any-return]
132
+ self.succeeded()
133
+ return result
@@ -0,0 +1,162 @@
1
+ """Per-key state buckets shared by the rate limiter, throttle and debounce."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import weakref
6
+ from collections.abc import Callable, Hashable
7
+ from typing import (
8
+ Any,
9
+ Generic,
10
+ ParamSpec,
11
+ TypeVar,
12
+ )
13
+
14
+ from python_wrap import _fork
15
+
16
+ T = TypeVar("T")
17
+ R_co = TypeVar("R_co", covariant=True)
18
+ P2 = ParamSpec("P2")
19
+ S = TypeVar("S")
20
+
21
+ _SWEEP_BUCKETS_EVERY = 1024
22
+
23
+
24
+ class _Buckets(Generic[S]):
25
+ """Decorator state split by ``key(*args, **kwargs)`` and/or by the instance (``args[0]``).
26
+
27
+ With neither ``key`` nor ``per_instance`` there is a single state, so the decorator
28
+ behaves as it always did. With ``per_instance`` each instance gets its own states,
29
+ found by identity through a weak reference: instances need not be hashable, are not
30
+ kept alive, and their state goes with them. Keyed states for which ``idle(state)`` is
31
+ true are dropped every ``_SWEEP_BUCKETS_EVERY`` lookups, so the keys cannot pile up.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ factory: Callable[[], S],
37
+ *,
38
+ key: Callable[..., Hashable] | None = None,
39
+ per_instance: bool = False,
40
+ idle: Callable[[S], bool] | None = None,
41
+ what: str = "decorator",
42
+ ) -> None:
43
+ self._factory = factory
44
+ self._key = key
45
+ self._per_instance = per_instance
46
+ self._idle = idle
47
+ self._what = what
48
+ self._lock = _fork.ForkSafeLock()
49
+ self._plain: dict[Hashable, S] = {}
50
+ # per_instance: id(instance) -> (weak reference, that instance's keyed states)
51
+ self._instances: dict[int, tuple[weakref.ref[Any], dict[Hashable, S]]] = {}
52
+ self._lookups = 0
53
+ _fork.register(self)
54
+
55
+ def _reset_after_fork(self) -> None:
56
+ self._plain.clear()
57
+ self._instances.clear()
58
+ self._lookups = 0
59
+
60
+ def _scope(self, args: tuple[Any, ...]) -> dict[Hashable, S]:
61
+ if not self._per_instance:
62
+ return self._plain
63
+ if not args:
64
+ raise TypeError(
65
+ f"{self._what}(per_instance=True): call the function with the instance "
66
+ "as its first positional argument"
67
+ )
68
+ obj = args[0]
69
+ i = id(obj)
70
+ slot = self._instances.get(i)
71
+ if slot is not None and slot[0]() is obj:
72
+ return slot[1]
73
+
74
+ def forget(ref: weakref.ref[Any], i: int = i) -> None:
75
+ # Runs while the instance is destroyed, maybe in a thread holding the lock:
76
+ # no locking here (dict operations are atomic). The id cannot be reused
77
+ # before this callback has run.
78
+ current = self._instances.get(i)
79
+ if current is not None and current[0] is ref:
80
+ self._instances.pop(i, None)
81
+
82
+ try:
83
+ ref = weakref.ref(obj, forget)
84
+ except TypeError:
85
+ raise TypeError(
86
+ f"{self._what}(per_instance=True) needs weak-referenceable instances, but "
87
+ f"{type(obj).__name__!r} is not (a __slots__ class must also list "
88
+ "'__weakref__')"
89
+ ) from None
90
+ with self._lock:
91
+ slot = self._instances.get(i)
92
+ if slot is not None and slot[0]() is obj:
93
+ return slot[1]
94
+ states: dict[Hashable, S] = {}
95
+ self._instances[i] = (ref, states)
96
+ return states
97
+
98
+ def get(self, args: tuple[Any, ...], kwargs: dict[str, Any]) -> S:
99
+ """The state for this call, created on first use."""
100
+ k = None if self._key is None else self._key(*args, **kwargs)
101
+ scope = self._scope(args)
102
+ with self._lock:
103
+ state = scope.get(k)
104
+ if state is None:
105
+ state = scope[k] = self._factory()
106
+ if self._key is not None and self._idle is not None:
107
+ self._lookups += 1
108
+ if self._lookups >= _SWEEP_BUCKETS_EVERY:
109
+ self._sweep()
110
+ return state
111
+
112
+ def _sweep(self) -> None:
113
+ # Caller holds the lock.
114
+ self._lookups = 0
115
+ idle = self._idle
116
+ assert idle is not None
117
+ scopes = (
118
+ [self._plain] if not self._per_instance else [s for _, s in self._instances.values()]
119
+ )
120
+ for scope in scopes:
121
+ for k in [k for k, state in scope.items() if idle(state)]:
122
+ del scope[k]
123
+
124
+ def states(self) -> list[S]:
125
+ """Every live state (a snapshot)."""
126
+ with self._lock:
127
+ scopes = (
128
+ [self._plain]
129
+ if not self._per_instance
130
+ else [s for ref, s in self._instances.values() if ref() is not None]
131
+ )
132
+ return [state for scope in scopes for state in scope.values()]
133
+
134
+ def find(self, args: tuple[Any, ...], kwargs: dict[str, Any]) -> S | None:
135
+ """The existing state for these call arguments, or ``None`` (never creates one)."""
136
+ k = None if self._key is None else self._key(*args, **kwargs)
137
+ if self._per_instance:
138
+ if not args:
139
+ return None
140
+ slot = self._instances.get(id(args[0]))
141
+ if slot is None or slot[0]() is not args[0]:
142
+ return None
143
+ scope = slot[1]
144
+ else:
145
+ scope = self._plain
146
+ with self._lock:
147
+ return scope.get(k)
148
+
149
+ @property
150
+ def selective(self) -> bool:
151
+ """True when ``cancel``/``flush`` need the call's arguments to pick a state."""
152
+ return self._key is not None or self._per_instance
153
+
154
+ def clear(self) -> None:
155
+ with self._lock:
156
+ self._plain.clear()
157
+ self._instances.clear()
158
+
159
+
160
+ # ---------------------------------------------------------------------------------------
161
+ # timeout
162
+ # ---------------------------------------------------------------------------------------
python_wrap/_core.py CHANGED
@@ -48,15 +48,17 @@ time**, not at decoration time, so a test can flip it after import:
48
48
  from __future__ import annotations
49
49
 
50
50
  import asyncio
51
+ import contextvars
51
52
  import functools
52
53
  import inspect
53
54
  import logging
54
- import threading
55
55
  import time
56
56
  from collections.abc import Callable
57
57
  from dataclasses import dataclass, fields
58
58
  from typing import Any, NoReturn, ParamSpec, TypeVar
59
59
 
60
+ from python_wrap import _fork
61
+
60
62
  P = ParamSpec("P")
61
63
  R = TypeVar("R")
62
64
  F = TypeVar("F", bound=Callable[..., Any])
@@ -68,6 +70,9 @@ LoggerLike = logging.Logger | str | None
68
70
  # Time sources, patched by tests. Call them as ``_core.monotonic()``.
69
71
  monotonic: Callable[[], float] = time.monotonic
70
72
  perf_counter: Callable[[], float] = time.perf_counter
73
+ # Wall-clock source for values shared across processes (cache deadlines in an external
74
+ # store). Unlike an offset frozen at import, this follows an NTP step.
75
+ wall_time: Callable[[], float] = time.time
71
76
 
72
77
 
73
78
  @dataclass
@@ -81,7 +86,7 @@ class Overrides:
81
86
 
82
87
 
83
88
  overrides = Overrides()
84
- overrides_lock = threading.RLock()
89
+ overrides_lock = _fork.ForkSafeRLock()
85
90
 
86
91
 
87
92
  def set_overrides(**values: Any) -> dict[str, Any]:
@@ -156,6 +161,10 @@ def qualname(func: Callable[..., Any]) -> str:
156
161
  return getattr(func, "__qualname__", None) or getattr(func, "__name__", None) or repr(func)
157
162
 
158
163
 
164
+ #: Set (by `python_wrap.celery.resilient_task`) so limiters raise instead of sleeping.
165
+ no_block: contextvars.ContextVar[bool] = contextvars.ContextVar("pw_no_block", default=False)
166
+
167
+
159
168
  def refuse_pickle(obj: object, advice: str | None = None) -> NoReturn:
160
169
  """Raise a clear ``TypeError`` from ``__reduce__`` of an object with per-process state.
161
170
 
@@ -197,7 +206,7 @@ class Event:
197
206
 
198
207
 
199
208
  listeners: list[Callable[[Event], None]] = []
200
- listeners_lock = threading.Lock()
209
+ listeners_lock = _fork.ForkSafeLock()
201
210
 
202
211
 
203
212
  def emit(name: str, function: str, **fields: Any) -> None:
@@ -0,0 +1,103 @@
1
+ # Using python-wrap correctly (guide for coding agents)
2
+
3
+ python-wrap is a typed, zero-dependency resilience toolkit: retry, circuit breakers,
4
+ timeouts, rate limits, caching, bulkheads, idempotency and policies. Every decorator
5
+ works on sync functions, `async def` functions and methods.
6
+
7
+ ## Find the right API before writing code
8
+
9
+ python -m python_wrap recipe "retry http calls" # plain-language need -> API
10
+ python -m python_wrap api search circuit breaker # search names and docstrings
11
+ python -m python_wrap api retry # signature, params, raises, example
12
+ python -m python_wrap api --json # the whole index, machine-readable
13
+ python -m python_wrap mcp # the same, as an MCP server
14
+
15
+ Do not guess parameter names: check them with `api SYMBOL`.
16
+
17
+ ## Prefer a policy or a preset over hand-stacked decorators
18
+
19
+ `policy(...)` puts layers in the canonical order wherever you pass them. The presets in
20
+ `python_wrap.presets` (`http_client`, `db_call`, `third_party_api`) come with timeouts,
21
+ bounded attempts, jittered backoff, a `RetryBudget` and a breaker.
22
+
23
+ from python_wrap.presets import http_client
24
+ users_api = http_client("users", timeout_seconds=3)
25
+
26
+ @users_api
27
+ def get_user(user_id: int) -> dict: ...
28
+
29
+ ## Layer order (outermost first)
30
+
31
+ observe -> validate -> fallback -> cache -> limiter -> bulkhead -> breaker -> retry -> timeout -> guard
32
+
33
+ When stacking by hand, the decorator at the top is the outermost. So:
34
+
35
+ @circuit_breaker(...) # counts calls whose retries were all used up
36
+ @retry(...) # retries each failed attempt
37
+ @timeout(2) # bounds each single attempt
38
+ def call(): ...
39
+
40
+ - `timeout` goes **inside** `retry` (per attempt). A `timeout` above `retry` bounds the
41
+ whole call; then narrow `retry(on=...)` so it does not swallow `TimeoutExpired`.
42
+ - `circuit_breaker` goes **outside** `retry`; below it, one unlucky call trips the breaker.
43
+ - `memoize` goes outside `retry` and limits: a cache hit should skip them, and failures
44
+ are not cached.
45
+ - `rate_limit` outside `retry` spends one token per logical call.
46
+
47
+ ## Idempotency rules
48
+
49
+ - Only retry operations that are safe to repeat: reads, PUT/DELETE, writes keyed by an
50
+ idempotency key.
51
+ - Payments, e-mails, SMS, webhooks, non-idempotent POSTs, queue publishes without
52
+ deduplication: **no retry layer**. Pass `idempotent=False` to presets (the retry layer is
53
+ left out) and use `@idempotent(key=...)` to deduplicate repeated requests.
54
+ - `@idempotent` across processes needs a shared result store **and** a shared lease
55
+ backend (`RedisStore(fail_open=False)` supplies a matching `RedisLock`). It cannot give
56
+ exactly-once effects across a crash; use an outbox or database idempotency keys for that.
57
+
58
+ ## What never to retry
59
+
60
+ - Programming errors (`TypeError`, `KeyError`, `AttributeError`, `ValueError` from your
61
+ own validation): always name the transient exceptions with `on=` (or `retry_if=`);
62
+ `on=Exception` retries bugs (doctor PW003).
63
+ - HTTP 4xx other than 408, 425 and 429 (bad request, auth, not found, conflict on a
64
+ non-idempotent write). Honour `Retry-After` with `delay_from=retry_after_header`.
65
+ - Authentication and permission failures, validation errors, `CircuitOpenError`,
66
+ `RateLimitExceeded` from your own limiter, `QuotaExhausted`.
67
+ - Cancellation (`asyncio.CancelledError`, `KeyboardInterrupt`, `SystemExit`): python-wrap
68
+ never retries these, do not try to.
69
+
70
+ Always bound retries with `max_attempts` or `max_time` (PW001) and share a `RetryBudget`
71
+ between callers of one dependency (PW008).
72
+
73
+ ## Common mistakes
74
+
75
+ - Unbounded retries, or retries with no per-attempt timeout (PW001, PW004).
76
+ - Timeout not shorter than the retry `max_time` (PW005).
77
+ - Two retry layers (for example an HTTP client with built-in retries plus `@retry`):
78
+ attempts multiply (PW007).
79
+ - A sync `timeout` cannot preempt code off the main thread or on Windows (PW009): poll
80
+ `checkpoint()` in long loops, or use `async def`.
81
+ - `memoize` on a method with no bound pins every instance (PW011): use
82
+ `per_instance=True`, `maxsize=` or `ttl=`.
83
+ - Breakers, bulkheads and rate limits are **per process** by default. Under gunicorn,
84
+ uvicorn workers, Celery prefork or process pools, N workers allow N times the limit
85
+ (PW012): use `RedisBreakerState`/`SQLiteBreakerState`, `RedisWindow` and lease backends.
86
+ - Calling `time.sleep` in tests: use `python_wrap.testing.fake_clock()` instead.
87
+ - Logging raw arguments: use `log_args`/`audit`, which redact sensitive names.
88
+ - Configuring logging inside library code: python-wrap never does, neither should you.
89
+
90
+ ## Check your work with the doctor
91
+
92
+ python -m python_wrap doctor package.module:policy_or_function
93
+ python -m python_wrap doctor --non-idempotent package.payments:charge
94
+ python -m python_wrap doctor --multiprocess --strict package.clients:users_api
95
+
96
+ In tests:
97
+
98
+ from python_wrap.doctor import explain
99
+ assert explain(users_api, idempotent=True).ok
100
+
101
+ Exit status 1 means an error (or any finding with `--strict`). Fix every error; review
102
+ every warning. Finding codes PW001-PW019 are listed in the docs
103
+ (features/resilience/presets-and-doctor).