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,85 @@
1
+ """Opt-in pytest fixtures for LLM cassettes and HTTP-level chaos.
2
+
3
+ Enable it explicitly, in a top-level ``conftest.py``::
4
+
5
+ pytest_plugins = ["python_wrap.pytest_plugin"]
6
+
7
+ It is deliberately not registered through the ``pytest11`` entry point: installing the
8
+ library must never change how an unrelated test suite starts. Fixtures:
9
+
10
+ - ``llm_cassette``: a factory ``llm_cassette(name=None, **options) -> Cassette`` whose file
11
+ lives in ``<test dir>/cassettes/<test module>/<test name>.json`` (override the folder with
12
+ ``--llm-cassette-dir``); saved when the test ends. Build the client with
13
+ ``transport=llm_cassette().transport()``. The mode comes from ``--llm-cassette-mode``
14
+ (``once`` by default; use ``replay`` in CI so an unrecorded request fails instead of
15
+ calling the network) or the ``PYTHON_WRAP_CASSETTE_MODE`` environment variable.
16
+ - ``chaos_llm_http``: a fresh `python_wrap.llm_http_chaos.LLMHTTPFaults` on its own
17
+ injector; add rules and wrap your transport with ``chaos_llm_http.transport(inner)``.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ import re
24
+ from collections.abc import Callable, Iterator
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ import pytest
29
+
30
+ from python_wrap.chaos import FaultInjector
31
+ from python_wrap.llm_cassette import Cassette
32
+ from python_wrap.llm_http_chaos import LLMHTTPFaults
33
+
34
+ __all__ = ["chaos_llm_http", "llm_cassette", "pytest_addoption"]
35
+
36
+ _SAFE = re.compile(r"[^A-Za-z0-9_.-]+")
37
+
38
+
39
+ def pytest_addoption(parser: pytest.Parser) -> None:
40
+ """Register ``--llm-cassette-mode`` and ``--llm-cassette-dir``."""
41
+ group = parser.getgroup("python-wrap")
42
+ group.addoption(
43
+ "--llm-cassette-mode",
44
+ default=None,
45
+ choices=("once", "record", "replay", "new"),
46
+ help="how llm_cassette behaves (default: PYTHON_WRAP_CASSETTE_MODE or 'once')",
47
+ )
48
+ group.addoption(
49
+ "--llm-cassette-dir",
50
+ default=None,
51
+ help="folder for cassette files (default: <test dir>/cassettes)",
52
+ )
53
+
54
+
55
+ def _slug(text: str) -> str:
56
+ return _SAFE.sub("_", text).strip("._") or "cassette"
57
+
58
+
59
+ @pytest.fixture
60
+ def llm_cassette(request: pytest.FixtureRequest) -> Iterator[Callable[..., Cassette]]:
61
+ """Factory for `Cassette` objects named after the running test."""
62
+ made: list[Cassette] = []
63
+ option = request.config.getoption("--llm-cassette-mode", default=None)
64
+ mode = option or os.environ.get("PYTHON_WRAP_CASSETTE_MODE") or "once"
65
+ root = request.config.getoption("--llm-cassette-dir", default=None)
66
+ base = Path(root) if root else Path(str(request.node.path)).parent / "cassettes"
67
+
68
+ def make(name: str | None = None, **options: Any) -> Cassette:
69
+ label = _slug(name) if name else _slug(request.node.name)
70
+ folder = base / _slug(request.node.path.stem)
71
+ options.setdefault("mode", mode)
72
+ cassette = Cassette(folder / f"{label}.json", **options)
73
+ made.append(cassette)
74
+ return cassette
75
+
76
+ yield make
77
+ for cassette in made:
78
+ if cassette.recorded:
79
+ cassette.save()
80
+
81
+
82
+ @pytest.fixture
83
+ def chaos_llm_http() -> LLMHTTPFaults:
84
+ """HTTP-level LLM fault rules on a private injector, cleaned up with the test."""
85
+ return LLMHTTPFaults(FaultInjector())
python_wrap/quotas.py ADDED
@@ -0,0 +1,319 @@
1
+ """Atomic Redis rate windows and explicit run budgets."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import functools
7
+ import math
8
+ import uuid
9
+ from collections.abc import Callable
10
+ from typing import Any, TypeVar, cast
11
+
12
+ from python_wrap import _core, _fork
13
+ from python_wrap._backend import BackendMonitor
14
+ from python_wrap._runtime import digest, seconds
15
+ from python_wrap.errors import RateLimitExceeded
16
+
17
+ __all__ = ["AsyncRedisWindow", "Quota", "QuotaExhausted", "RedisWindow", "shared_rate_limit"]
18
+ F = TypeVar("F", bound=Callable[..., Any])
19
+
20
+
21
+ class QuotaExhausted(RuntimeError):
22
+ """A named run quota has no remaining allowance."""
23
+
24
+
25
+ class Quota:
26
+ """A thread-safe explicit run budget; optionally shared via a Redis counter.
27
+
28
+ Redis quotas need a unique key per run, not one forever-growing global key. An
29
+ optional TTL bounds retention; reset is an explicit administrative operation.
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ limit: int,
35
+ name: str = "quota",
36
+ *,
37
+ client: Any = None,
38
+ key: str | None = None,
39
+ ttl: float | str | None = None,
40
+ on_backend_error: str | None = None,
41
+ retry_backend_after: float = 1.0,
42
+ ) -> None:
43
+ if isinstance(limit, bool) or not isinstance(limit, int) or limit < 0:
44
+ raise ValueError("limit must be nonnegative")
45
+ if client is not None and limit > 2**53 - 1:
46
+ raise ValueError("Redis quota limit exceeds exact Lua integer range")
47
+ if key is not None and not key:
48
+ raise ValueError("quota key must not be empty")
49
+ self.limit, self.name, self.client = limit, name, client
50
+ self.key = key or f"python-wrap:quota:{name}"
51
+ self.ttl = None if ttl is None else seconds(ttl)
52
+ self._used = 0
53
+ self._lock = _fork.ForkSafeLock()
54
+ self._monitor = (
55
+ None
56
+ if client is None
57
+ else BackendMonitor("quota", name, on_backend_error, retry_backend_after)
58
+ )
59
+
60
+ def _take_local(self, amount: int) -> int:
61
+ with self._lock:
62
+ if self._used + amount > self.limit:
63
+ raise QuotaExhausted(self.name)
64
+ self._used += amount
65
+ return self.limit - self._used
66
+
67
+ def take(self, amount: int = 1) -> int:
68
+ """Consume an amount atomically and return remaining allowance."""
69
+ if isinstance(amount, bool) or not isinstance(amount, int) or amount < 0:
70
+ raise ValueError("amount must be nonnegative")
71
+ if self.client is not None and amount > 2**53 - 1:
72
+ raise ValueError("Redis quota amount exceeds exact Lua integer range")
73
+ if self.client is None:
74
+ return self._take_local(amount)
75
+ script = """
76
+ local used=tonumber(redis.call('GET',KEYS[1]) or '0')
77
+ if used+tonumber(ARGV[1])>tonumber(ARGV[2]) then return -1 end
78
+ used=redis.call('INCRBY',KEYS[1],ARGV[1])
79
+ if tonumber(ARGV[3])>0 and redis.call('PTTL',KEYS[1])<0 then
80
+ redis.call('PEXPIRE',KEYS[1],ARGV[3]) end
81
+ return tonumber(ARGV[2])-used
82
+ """
83
+ assert self._monitor is not None
84
+ monitor = self._monitor
85
+ result = monitor.call(
86
+ "take",
87
+ lambda: int(
88
+ self.client.eval(
89
+ script,
90
+ 1,
91
+ self.key,
92
+ amount,
93
+ self.limit,
94
+ 0 if self.ttl is None else math.ceil(self.ttl * 1000),
95
+ )
96
+ ),
97
+ lambda: self._take_local(amount) if monitor.mode == "local" else self.limit,
98
+ )
99
+ if result < 0:
100
+ raise QuotaExhausted(self.name)
101
+ return result
102
+
103
+ @property
104
+ def remaining(self) -> int:
105
+ if self.client is None:
106
+ with self._lock:
107
+ used = self._used
108
+ else:
109
+ used = int(self.client.get(self.key) or 0)
110
+ return max(0, self.limit - used)
111
+
112
+ def reset(self) -> None:
113
+ if self.client is None:
114
+ with self._lock:
115
+ self._used = 0
116
+ else:
117
+ self.client.delete(self.key)
118
+
119
+
120
+ _WINDOW = """
121
+ local t=redis.call('TIME'); local now=t[1]*1000+math.floor(t[2]/1000)
122
+ local horizon=now-tonumber(ARGV[2]); redis.call('ZREMRANGEBYSCORE',KEYS[1],'-inf',horizon)
123
+ if redis.call('ZCARD',KEYS[1])>=tonumber(ARGV[1]) then
124
+ local first=redis.call('ZRANGE',KEYS[1],0,0,'WITHSCORES')
125
+ return math.max(1,tonumber(first[2])+tonumber(ARGV[2])-now)
126
+ end
127
+ redis.call('ZADD',KEYS[1],now,ARGV[3]); redis.call('PEXPIRE',KEYS[1],ARGV[2]); return 0
128
+ """
129
+
130
+
131
+ class _WindowConfig:
132
+ def __init__(
133
+ self,
134
+ client: Any,
135
+ key: str,
136
+ *,
137
+ calls: int,
138
+ period: float | str,
139
+ on_backend_error: str | None = None,
140
+ retry_backend_after: float = 1.0,
141
+ ) -> None:
142
+ if isinstance(calls, bool) or not isinstance(calls, int) or calls < 1 or not key:
143
+ raise ValueError("calls must be positive and key nonempty")
144
+ if calls > 2**53 - 1:
145
+ raise ValueError("Redis window capacity exceeds exact Lua integer range")
146
+ self.client, self.key, self.calls = client, key, calls
147
+ self.period = seconds(period)
148
+ self._monitor = BackendMonitor("window", key, on_backend_error, retry_backend_after)
149
+ self._local: Any = None
150
+
151
+ def _fallback(self, key: Any) -> float:
152
+ """Serve a call while the store is down: this process's own window, or admit."""
153
+ if self._monitor.mode != "local":
154
+ return 0.0
155
+ if self._local is None:
156
+ from python_wrap.ratelimit import _SlidingWindow
157
+
158
+ self._local = _SlidingWindow(((self.calls, self.period),))
159
+ return float(self._local.acquire(key))
160
+
161
+ def _eval_args(self, key: Any) -> tuple[Any, ...]:
162
+ return (
163
+ _WINDOW,
164
+ 1,
165
+ self.key + ":" + digest(key),
166
+ self.calls,
167
+ max(1, math.ceil(self.period * 1000)),
168
+ uuid.uuid4().hex,
169
+ )
170
+
171
+ def _pattern(self) -> str:
172
+ import re
173
+
174
+ return re.sub(r"([\\*?\[\]])", r"\\\1", self.key + ":") + "*"
175
+
176
+ def admit(self, key: Any = None) -> None:
177
+ # Test-only forced admission; no backend write is needed when limits are bypassed.
178
+ return None
179
+
180
+
181
+ class RedisWindow(_WindowConfig):
182
+ """Atomic sliding-window admission using the Redis server's clock.
183
+
184
+ Takes a synchronous ``redis.Redis``-compatible client. Async callers (`RateLimiter`,
185
+ `shared_rate_limit`) run each round trip in a worker thread; use `AsyncRedisWindow`
186
+ with a ``redis.asyncio`` client to stay on the event loop instead.
187
+ """
188
+
189
+ def acquire(self, key: Any = None) -> float:
190
+ """Return zero when admitted, otherwise seconds until the oldest slot expires."""
191
+ return self._monitor.call(
192
+ "acquire",
193
+ lambda: float(self.client.eval(*self._eval_args(key))) / 1000,
194
+ lambda: self._fallback(key),
195
+ )
196
+
197
+ def clear(self) -> None:
198
+ """Delete every key of this window (all limiter keys)."""
199
+ for key in self.client.scan_iter(match=self._pattern(), count=200):
200
+ self.client.delete(key)
201
+
202
+
203
+ class AsyncRedisWindow(_WindowConfig):
204
+ """`RedisWindow` for ``redis.asyncio`` clients: the round trip is awaited, not threaded.
205
+
206
+ Same Lua script, keys and semantics as `RedisWindow`, so sync and async processes can
207
+ share one window. Use it with `shared_rate_limit` or ``RateLimiter(backend=...)`` on
208
+ ``async def`` functions; synchronous code needs `RedisWindow`. python-wrap never
209
+ imports redis: pass any client with an awaitable ``eval``/``delete`` and an
210
+ async-iterator ``scan_iter``.
211
+
212
+ Example:
213
+ ```python
214
+ import asyncio
215
+
216
+ from python_wrap.errors import RateLimitExceeded
217
+ from python_wrap.quotas import AsyncRedisWindow, shared_rate_limit
218
+
219
+
220
+ class FakeAsyncRedis: # stands in for redis.asyncio.Redis in this example
221
+ def __init__(self) -> None:
222
+ self.calls = 0
223
+
224
+ async def eval(self, *args: object) -> int:
225
+ self.calls += 1
226
+ return 0 if self.calls <= 2 else 500
227
+
228
+
229
+ window = AsyncRedisWindow(FakeAsyncRedis(), "api", calls=2, period=1)
230
+
231
+
232
+ @shared_rate_limit(window)
233
+ async def call() -> str:
234
+ return "ok"
235
+
236
+
237
+ async def main() -> None:
238
+ assert [await call(), await call()] == ["ok", "ok"]
239
+ try:
240
+ await call()
241
+ except RateLimitExceeded as exc:
242
+ assert exc.retry_after == 0.5
243
+
244
+
245
+ asyncio.run(main())
246
+ ```
247
+ """
248
+
249
+ async def acquire(self, key: Any = None) -> float:
250
+ """Return zero when admitted, otherwise seconds until the oldest slot expires."""
251
+
252
+ async def run() -> float:
253
+ return float(await self.client.eval(*self._eval_args(key))) / 1000
254
+
255
+ return await self._monitor.acall("acquire", run, lambda: self._fallback(key))
256
+
257
+ async def clear(self) -> None:
258
+ """Delete every key of this window (all limiter keys)."""
259
+ async for key in self.client.scan_iter(match=self._pattern(), count=200):
260
+ await self.client.delete(key)
261
+
262
+
263
+ def shared_rate_limit(
264
+ backend: RedisWindow | AsyncRedisWindow, *, block: bool = False
265
+ ) -> Callable[[F], F]:
266
+ """Apply a shared Redis window to sync/async functions, respecting test overrides.
267
+
268
+ With a `RedisWindow`, async functions run each Redis round trip in a worker thread.
269
+ With an `AsyncRedisWindow` the round trip is awaited on the event loop; it can only
270
+ decorate ``async def`` functions.
271
+
272
+ Raises:
273
+ TypeError: If an `AsyncRedisWindow` decorates a synchronous function.
274
+ """
275
+
276
+ async def acquire() -> float:
277
+ if isinstance(backend, AsyncRedisWindow):
278
+ return await backend.acquire()
279
+ return await asyncio.to_thread(backend.acquire)
280
+
281
+ def decorate(func: F) -> F:
282
+ if _core.is_async(func):
283
+
284
+ @functools.wraps(func)
285
+ async def aw(*args: Any, **kw: Any) -> Any:
286
+ while not _core.overrides.disable_rate_limits:
287
+ wait = await acquire()
288
+ if wait <= 0:
289
+ break
290
+ if not block or _core.no_block.get():
291
+ raise RateLimitExceeded("shared rate limit exceeded", retry_after=wait)
292
+ await asyncio.sleep(wait)
293
+ return await func(*args, **kw)
294
+
295
+ return cast(F, aw)
296
+
297
+ if isinstance(backend, AsyncRedisWindow):
298
+ raise TypeError(
299
+ f"{_core.qualname(func)} is synchronous; AsyncRedisWindow needs async def "
300
+ "functions (use RedisWindow for synchronous code)"
301
+ )
302
+ sync_backend = backend
303
+
304
+ @functools.wraps(func)
305
+ def sw(*args: Any, **kw: Any) -> Any:
306
+ import time
307
+
308
+ while not _core.overrides.disable_rate_limits:
309
+ wait = sync_backend.acquire()
310
+ if wait <= 0:
311
+ break
312
+ if not block or _core.no_block.get():
313
+ raise RateLimitExceeded("shared rate limit exceeded", retry_after=wait)
314
+ time.sleep(wait)
315
+ return func(*args, **kw)
316
+
317
+ return cast(F, sw)
318
+
319
+ return decorate