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.
- python_wrap/__init__.py +348 -1
- python_wrap/__main__.py +57 -0
- python_wrap/_backend.py +133 -0
- python_wrap/_buckets.py +162 -0
- python_wrap/_core.py +12 -3
- python_wrap/_data/agent_guide.md +103 -0
- python_wrap/_data/recipes.json +703 -0
- python_wrap/_fork.py +113 -0
- python_wrap/_integration.py +29 -0
- python_wrap/_runtime.py +157 -0
- python_wrap/adapters/__init__.py +101 -0
- python_wrap/adapters/_frameworks.py +251 -0
- python_wrap/adapters/_sdk.py +1978 -0
- python_wrap/adapters/anthropic.py +139 -0
- python_wrap/adapters/langchain.py +288 -0
- python_wrap/adapters/openai.py +169 -0
- python_wrap/adapters/openai_agents.py +468 -0
- python_wrap/adapters/pydantic_ai.py +459 -0
- python_wrap/adaptive.py +605 -0
- python_wrap/agents.py +2503 -0
- python_wrap/alerts.py +293 -0
- python_wrap/async_cache.py +745 -0
- python_wrap/batching.py +17 -4
- python_wrap/buffering.py +952 -0
- python_wrap/bulkhead.py +58 -6
- python_wrap/caching.py +425 -56
- python_wrap/celery.py +528 -0
- python_wrap/chaos.py +519 -0
- python_wrap/circuit.py +454 -23
- python_wrap/compat.py +267 -0
- python_wrap/concurrency.py +82 -1746
- python_wrap/config.py +25 -4
- python_wrap/coordination.py +638 -0
- python_wrap/credentials.py +126 -0
- python_wrap/dashboard.py +358 -0
- python_wrap/debounce.py +538 -0
- python_wrap/django.py +100 -0
- python_wrap/doctor.py +599 -0
- python_wrap/events.py +145 -4
- python_wrap/exporters.py +663 -0
- python_wrap/fastapi.py +81 -0
- python_wrap/flask.py +61 -0
- python_wrap/genai.py +1101 -0
- python_wrap/health.py +187 -0
- python_wrap/http.py +940 -0
- python_wrap/idempotency.py +446 -0
- python_wrap/introspect.py +738 -0
- python_wrap/lifecycle.py +620 -0
- python_wrap/llm.py +2574 -0
- python_wrap/llm_cassette.py +948 -0
- python_wrap/llm_http_chaos.py +326 -0
- python_wrap/llm_shared.py +772 -0
- python_wrap/llm_testing.py +990 -0
- python_wrap/llm_validate.py +383 -0
- python_wrap/local_state.py +395 -0
- python_wrap/logs.py +82 -26
- python_wrap/mcp.py +490 -0
- python_wrap/mcp_guard.py +357 -0
- python_wrap/metrics.py +6 -3
- python_wrap/migrate.py +1452 -0
- python_wrap/observability.py +484 -0
- python_wrap/periodic.py +24 -2
- python_wrap/policies.py +396 -0
- python_wrap/policy.py +14 -0
- python_wrap/predicates.py +276 -0
- python_wrap/presets.py +378 -0
- python_wrap/processing.py +227 -0
- python_wrap/propagation.py +62 -0
- python_wrap/pytest_plugin.py +85 -0
- python_wrap/quotas.py +319 -0
- python_wrap/ratelimit.py +560 -0
- python_wrap/redaction.py +228 -0
- python_wrap/retry.py +448 -70
- python_wrap/shared.py +653 -0
- python_wrap/singleflight.py +255 -0
- python_wrap/slow.py +72 -0
- python_wrap/stores.py +168 -0
- python_wrap/switches.py +164 -0
- python_wrap/testing.py +34 -8
- python_wrap/timeouts.py +874 -0
- python_wrap/timing.py +239 -17
- python_wrap/validation.py +187 -12
- python_wrap/web.py +723 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
- python_wrap-0.4.0.dist-info/RECORD +95 -0
- python_wrap-0.2.1.dist-info/RECORD +0 -29
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,772 @@
|
|
|
1
|
+
"""Token limits and budgets shared by several worker processes.
|
|
2
|
+
|
|
3
|
+
A `TokenRateLimiter` keeps its bucket in memory, so ten workers each believe they own
|
|
4
|
+
the whole tokens-per-minute quota and together trigger a 429 storm. The windows here move
|
|
5
|
+
the bucket into storage every worker can reach, so the whole fleet draws from one bucket
|
|
6
|
+
and backs off together:
|
|
7
|
+
|
|
8
|
+
- `SQLiteTokenWindow`: one database file (WAL mode, ``BEGIN IMMEDIATE`` transactions);
|
|
9
|
+
works across processes on one host with no server.
|
|
10
|
+
- `RedisTokenWindow` / `AsyncRedisTokenWindow`: one hash updated by a Lua script that
|
|
11
|
+
reads the Redis server's clock, so hosts with skewed clocks still agree.
|
|
12
|
+
- `SQLiteBudgetBackend`: a `python_wrap.llm.BudgetBackend` on SQLite, so a `Budget`
|
|
13
|
+
can be shared the same way.
|
|
14
|
+
|
|
15
|
+
Plug a window into ``token_rate_limit(..., store=window)``. `observe_headers` (also a
|
|
16
|
+
method of the windows and of the limiter) feeds the provider's own rate-limit headers
|
|
17
|
+
(``x-ratelimit-remaining-tokens``, ``anthropic-ratelimit-*``, ``retry-after``) back into
|
|
18
|
+
the window, so one worker's 429 makes every worker wait.
|
|
19
|
+
|
|
20
|
+
Nothing here imports redis or a provider SDK. Clocks come from ``python_wrap._core``, so
|
|
21
|
+
`python_wrap.testing.fake_clock` controls them.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import contextlib
|
|
27
|
+
import dataclasses
|
|
28
|
+
import math
|
|
29
|
+
import os
|
|
30
|
+
import re
|
|
31
|
+
import sqlite3
|
|
32
|
+
import threading
|
|
33
|
+
from collections.abc import Iterable, Iterator
|
|
34
|
+
from datetime import datetime, timezone
|
|
35
|
+
from email.utils import parsedate_to_datetime
|
|
36
|
+
from typing import Any
|
|
37
|
+
|
|
38
|
+
from python_wrap import _core
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
"AsyncRedisTokenWindow",
|
|
42
|
+
"RateLimitHint",
|
|
43
|
+
"RedisTokenWindow",
|
|
44
|
+
"SQLiteBudgetBackend",
|
|
45
|
+
"SQLiteTokenWindow",
|
|
46
|
+
"SharedTokenWindow",
|
|
47
|
+
"parse_rate_limit_headers",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
# --------------------------------------------------------------------- header parsing
|
|
51
|
+
|
|
52
|
+
_DURATION = re.compile(r"(\d+(?:\.\d+)?)(ms|s|m|h|d)")
|
|
53
|
+
_UNITS = {"ms": 0.001, "s": 1.0, "m": 60.0, "h": 3600.0, "d": 86400.0}
|
|
54
|
+
|
|
55
|
+
_REMAINING = (
|
|
56
|
+
"x-ratelimit-remaining-tokens",
|
|
57
|
+
"anthropic-ratelimit-tokens-remaining",
|
|
58
|
+
"anthropic-ratelimit-input-tokens-remaining",
|
|
59
|
+
"anthropic-ratelimit-output-tokens-remaining",
|
|
60
|
+
)
|
|
61
|
+
_RESET = (
|
|
62
|
+
"x-ratelimit-reset-tokens",
|
|
63
|
+
"anthropic-ratelimit-tokens-reset",
|
|
64
|
+
"anthropic-ratelimit-input-tokens-reset",
|
|
65
|
+
"anthropic-ratelimit-output-tokens-reset",
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclasses.dataclass(frozen=True)
|
|
70
|
+
class RateLimitHint:
|
|
71
|
+
"""What a provider's rate-limit headers said, in plain numbers.
|
|
72
|
+
|
|
73
|
+
Attributes:
|
|
74
|
+
remaining_tokens: Tokens the provider says are left in the window (the smallest
|
|
75
|
+
figure when input and output limits are reported separately), or None.
|
|
76
|
+
reset_seconds: Seconds until the window refills (the latest figure), or None.
|
|
77
|
+
retry_after: Seconds from ``Retry-After`` / ``retry-after-ms``, or None.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
remaining_tokens: float | None = None
|
|
81
|
+
reset_seconds: float | None = None
|
|
82
|
+
retry_after: float | None = None
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def block_seconds(self) -> float | None:
|
|
86
|
+
"""How long to stop sending: ``retry_after``, else ``reset_seconds`` at zero tokens."""
|
|
87
|
+
if self.retry_after is not None:
|
|
88
|
+
return self.retry_after
|
|
89
|
+
if self.remaining_tokens is not None and self.remaining_tokens <= 0:
|
|
90
|
+
return self.reset_seconds
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _lookup(headers: Any, name: str) -> str | None:
|
|
95
|
+
"""Case-insensitive header read from a mapping, pair list or httpx-like object."""
|
|
96
|
+
if headers is None:
|
|
97
|
+
return None
|
|
98
|
+
try:
|
|
99
|
+
items: Iterable[Any] = headers.items() if hasattr(headers, "items") else headers
|
|
100
|
+
for key, value in items:
|
|
101
|
+
if isinstance(key, bytes):
|
|
102
|
+
key = key.decode("latin-1")
|
|
103
|
+
if isinstance(key, str) and key.lower() == name:
|
|
104
|
+
if isinstance(value, bytes):
|
|
105
|
+
value = value.decode("latin-1")
|
|
106
|
+
return str(value)
|
|
107
|
+
except (TypeError, ValueError, AttributeError):
|
|
108
|
+
return None
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _timestamp(text: str) -> float | None:
|
|
113
|
+
"""Seconds from now until an RFC 3339 or HTTP date (never negative)."""
|
|
114
|
+
moment: datetime | None = None
|
|
115
|
+
try:
|
|
116
|
+
moment = datetime.fromisoformat(text.replace("Z", "+00:00").replace("z", "+00:00"))
|
|
117
|
+
except ValueError:
|
|
118
|
+
try:
|
|
119
|
+
moment = parsedate_to_datetime(text)
|
|
120
|
+
except (TypeError, ValueError, IndexError):
|
|
121
|
+
return None
|
|
122
|
+
if moment.tzinfo is None:
|
|
123
|
+
moment = moment.replace(tzinfo=timezone.utc)
|
|
124
|
+
return max(moment.timestamp() - _core.wall_time(), 0.0)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _seconds(text: str | None) -> float | None:
|
|
128
|
+
"""A duration (``"6m0s"``, ``"20ms"``, ``"1.5"``) or a date as seconds from now."""
|
|
129
|
+
if text is None:
|
|
130
|
+
return None
|
|
131
|
+
value = text.strip()
|
|
132
|
+
if not value:
|
|
133
|
+
return None
|
|
134
|
+
try:
|
|
135
|
+
number = float(value)
|
|
136
|
+
except ValueError:
|
|
137
|
+
pass
|
|
138
|
+
else:
|
|
139
|
+
return max(number, 0.0) if math.isfinite(number) else None
|
|
140
|
+
pos, total = 0, 0.0
|
|
141
|
+
while pos < len(value):
|
|
142
|
+
found = _DURATION.match(value, pos)
|
|
143
|
+
if found is None:
|
|
144
|
+
return _timestamp(value)
|
|
145
|
+
total += float(found.group(1)) * _UNITS[found.group(2)]
|
|
146
|
+
pos = found.end()
|
|
147
|
+
return total
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _count(text: str | None) -> float | None:
|
|
151
|
+
if text is None:
|
|
152
|
+
return None
|
|
153
|
+
try:
|
|
154
|
+
number = float(text.strip())
|
|
155
|
+
except ValueError:
|
|
156
|
+
return None
|
|
157
|
+
return number if math.isfinite(number) else None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def parse_rate_limit_headers(headers: Any) -> RateLimitHint:
|
|
161
|
+
"""Read token-window hints from provider response headers; never raises.
|
|
162
|
+
|
|
163
|
+
Understands the OpenAI style (``x-ratelimit-remaining-tokens``,
|
|
164
|
+
``x-ratelimit-reset-tokens`` as ``"6m0s"`` / ``"20ms"``), the Anthropic style
|
|
165
|
+
(``anthropic-ratelimit-tokens-remaining`` / ``-reset`` as an RFC 3339 time, plus the
|
|
166
|
+
separate ``input-tokens`` / ``output-tokens`` variants) and ``Retry-After`` (seconds
|
|
167
|
+
or HTTP date) or ``retry-after-ms``. Header names are case-insensitive. Unparseable
|
|
168
|
+
values are ignored.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
headers: A mapping, a list of ``(name, value)`` pairs, or any object with
|
|
172
|
+
``items()`` (such as ``httpx.Headers``).
|
|
173
|
+
|
|
174
|
+
Example:
|
|
175
|
+
>>> hint = parse_rate_limit_headers(
|
|
176
|
+
... {"X-RateLimit-Remaining-Tokens": "0", "X-RateLimit-Reset-Tokens": "1m30s"}
|
|
177
|
+
... )
|
|
178
|
+
>>> hint.remaining_tokens, hint.reset_seconds, hint.block_seconds
|
|
179
|
+
(0.0, 90.0, 90.0)
|
|
180
|
+
"""
|
|
181
|
+
counts = [c for c in (_count(_lookup(headers, n)) for n in _REMAINING) if c is not None]
|
|
182
|
+
resets = [r for r in (_seconds(_lookup(headers, n)) for n in _RESET) if r is not None]
|
|
183
|
+
retry = _seconds(_lookup(headers, "retry-after"))
|
|
184
|
+
millis = _count(_lookup(headers, "retry-after-ms"))
|
|
185
|
+
if millis is not None and millis >= 0:
|
|
186
|
+
retry = millis / 1000.0 if retry is None else max(retry, millis / 1000.0)
|
|
187
|
+
return RateLimitHint(
|
|
188
|
+
remaining_tokens=min(counts) if counts else None,
|
|
189
|
+
reset_seconds=max(resets) if resets else None,
|
|
190
|
+
retry_after=retry,
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# ------------------------------------------------------------------- the bucket maths
|
|
195
|
+
|
|
196
|
+
_State = tuple[float | None, float, float] # level (None = unknown), stamp, blocked-until
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _step(
|
|
200
|
+
state: _State | None,
|
|
201
|
+
op: str,
|
|
202
|
+
a: float,
|
|
203
|
+
b: float,
|
|
204
|
+
capacity: float,
|
|
205
|
+
rate: float,
|
|
206
|
+
now: float,
|
|
207
|
+
) -> tuple[_State, float]:
|
|
208
|
+
"""One atomic bucket operation; the Lua script below mirrors it line for line.
|
|
209
|
+
|
|
210
|
+
``capacity`` 0 means "unknown" (an observation from a worker that does not know the
|
|
211
|
+
limit): the level is then left as it is. Ops: ``reserve`` (``a`` tokens; returns the
|
|
212
|
+
wait, 0 when admitted), ``force`` (``a`` tokens), ``settle`` (``a`` reserved, ``b``
|
|
213
|
+
actual), ``level`` and ``observe`` (``a`` remaining or -1, ``b`` block seconds or -1).
|
|
214
|
+
"""
|
|
215
|
+
level, stamp, blocked = (None, now, 0.0) if state is None else state
|
|
216
|
+
if capacity > 0:
|
|
217
|
+
grown = capacity if level is None else level + max(now - stamp, 0.0) * rate
|
|
218
|
+
level = min(capacity, grown)
|
|
219
|
+
stamp = max(stamp, now)
|
|
220
|
+
result = 0.0
|
|
221
|
+
if op == "reserve":
|
|
222
|
+
assert level is not None
|
|
223
|
+
if blocked > now:
|
|
224
|
+
result = blocked - now
|
|
225
|
+
else:
|
|
226
|
+
need = min(a, capacity)
|
|
227
|
+
if level + 1e-9 >= need:
|
|
228
|
+
level -= a
|
|
229
|
+
else:
|
|
230
|
+
result = (need - level) / rate
|
|
231
|
+
elif op == "force":
|
|
232
|
+
assert level is not None
|
|
233
|
+
level -= a
|
|
234
|
+
elif op == "settle":
|
|
235
|
+
assert level is not None
|
|
236
|
+
level = min(capacity, level + a - b)
|
|
237
|
+
elif op == "level":
|
|
238
|
+
assert level is not None
|
|
239
|
+
result = level
|
|
240
|
+
elif op == "observe":
|
|
241
|
+
if a >= 0:
|
|
242
|
+
level = a if level is None else min(level, a)
|
|
243
|
+
stamp = max(stamp, now)
|
|
244
|
+
if b > 0:
|
|
245
|
+
blocked = max(blocked, now + b)
|
|
246
|
+
result = max(blocked - now, 0.0)
|
|
247
|
+
else:
|
|
248
|
+
raise ValueError(f"unknown window operation {op!r}")
|
|
249
|
+
return (level, stamp, blocked), result
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
_LUA_STEP = """
|
|
253
|
+
local t=redis.call('TIME')
|
|
254
|
+
local now=tonumber(t[1])+tonumber(t[2])/1000000
|
|
255
|
+
local h=redis.call('HMGET',KEYS[1],'level','stamp','blocked')
|
|
256
|
+
local op=ARGV[1]
|
|
257
|
+
local a=tonumber(ARGV[2])
|
|
258
|
+
local b=tonumber(ARGV[3])
|
|
259
|
+
local cap=tonumber(ARGV[4])
|
|
260
|
+
local rate=tonumber(ARGV[5])
|
|
261
|
+
local level=tonumber(h[1])
|
|
262
|
+
local stamp=tonumber(h[2]) or now
|
|
263
|
+
local blocked=tonumber(h[3]) or 0
|
|
264
|
+
if cap>0 then
|
|
265
|
+
if level==nil then level=cap else level=math.min(cap, level+math.max(now-stamp,0)*rate) end
|
|
266
|
+
stamp=math.max(stamp,now)
|
|
267
|
+
end
|
|
268
|
+
local result=0
|
|
269
|
+
if op=='reserve' then
|
|
270
|
+
if blocked>now then result=blocked-now
|
|
271
|
+
else
|
|
272
|
+
local need=math.min(a,cap)
|
|
273
|
+
if level+1e-9>=need then level=level-a else result=(need-level)/rate end
|
|
274
|
+
end
|
|
275
|
+
elseif op=='force' then level=level-a
|
|
276
|
+
elseif op=='settle' then level=math.min(cap, level+a-b)
|
|
277
|
+
elseif op=='level' then result=level
|
|
278
|
+
elseif op=='observe' then
|
|
279
|
+
if a>=0 then
|
|
280
|
+
if level==nil then level=a else level=math.min(level,a) end
|
|
281
|
+
stamp=math.max(stamp,now)
|
|
282
|
+
end
|
|
283
|
+
if b>0 then blocked=math.max(blocked, now+b) end
|
|
284
|
+
result=math.max(blocked-now,0)
|
|
285
|
+
end
|
|
286
|
+
if level~=nil then
|
|
287
|
+
redis.call('HSET',KEYS[1],'level',string.format('%.9f',level),'stamp',string.format('%.6f',stamp),'blocked',string.format('%.6f',blocked))
|
|
288
|
+
else
|
|
289
|
+
redis.call('HSET',KEYS[1],'stamp',string.format('%.6f',stamp),'blocked',string.format('%.6f',blocked))
|
|
290
|
+
end
|
|
291
|
+
local ttl=math.ceil((cap/math.max(rate,1e-9)+math.max(blocked-now,0))*1000)+60000
|
|
292
|
+
redis.call('PEXPIRE',KEYS[1],ttl)
|
|
293
|
+
return string.format('%.9f',result)
|
|
294
|
+
"""
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
# --------------------------------------------------------------------------- the base
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
class SharedTokenWindow:
|
|
301
|
+
"""A token bucket held in shared storage; the base of the concrete windows.
|
|
302
|
+
|
|
303
|
+
A limiter calls `reserve`, `force`, `settle` and `level` with its own capacity and
|
|
304
|
+
refill rate, so every process using one window must agree on those numbers. Time is
|
|
305
|
+
wall-clock (via ``python_wrap._core.wall_time``) because processes do not share a
|
|
306
|
+
monotonic clock. A subclass implements ``_transact``.
|
|
307
|
+
|
|
308
|
+
When the storage fails (locked database, unreachable Redis, an exception from the
|
|
309
|
+
client) and ``fail_open`` is true, the window logs a ``rate_limit.store_error`` event
|
|
310
|
+
and falls back to a private in-memory bucket for that call, so an outage degrades to
|
|
311
|
+
per-process limiting instead of stopping every LLM call. ``fail_open=False`` raises.
|
|
312
|
+
|
|
313
|
+
Attributes:
|
|
314
|
+
name: Identifies the bucket inside the storage; share it to share the quota.
|
|
315
|
+
fail_open: Whether storage errors fall back to a local bucket.
|
|
316
|
+
"""
|
|
317
|
+
|
|
318
|
+
def __init__(self, name: str = "tokens", *, fail_open: bool = True) -> None:
|
|
319
|
+
if not name:
|
|
320
|
+
raise ValueError("a window needs a nonempty name")
|
|
321
|
+
self.name = name
|
|
322
|
+
self.fail_open = fail_open
|
|
323
|
+
self._fallback: _State | None = None
|
|
324
|
+
self._flock = threading.Lock()
|
|
325
|
+
|
|
326
|
+
# -- storage hook ------------------------------------------------------------
|
|
327
|
+
def _transact(self, op: str, a: float, b: float, capacity: float, rate: float) -> float:
|
|
328
|
+
raise NotImplementedError
|
|
329
|
+
|
|
330
|
+
def _local(self, op: str, a: float, b: float, capacity: float, rate: float) -> float:
|
|
331
|
+
with self._flock:
|
|
332
|
+
self._fallback, result = _step(
|
|
333
|
+
self._fallback, op, a, b, capacity, rate, _core.wall_time()
|
|
334
|
+
)
|
|
335
|
+
return result
|
|
336
|
+
|
|
337
|
+
def _run(self, op: str, a: float, b: float, capacity: float, rate: float) -> float:
|
|
338
|
+
try:
|
|
339
|
+
return self._transact(op, a, b, capacity, rate)
|
|
340
|
+
except Exception as exc:
|
|
341
|
+
_core.emit("rate_limit.store_error", self.name, error=type(exc).__name__, op=op)
|
|
342
|
+
if not self.fail_open:
|
|
343
|
+
raise
|
|
344
|
+
return self._local(op, a, b, capacity, rate)
|
|
345
|
+
|
|
346
|
+
# -- the limiter-facing operations --------------------------------------------
|
|
347
|
+
def reserve(self, tokens: int, capacity: float, rate: float) -> float:
|
|
348
|
+
"""Reserve ``tokens``: 0.0 when admitted, else seconds to wait."""
|
|
349
|
+
return self._run("reserve", float(tokens), 0.0, float(capacity), float(rate))
|
|
350
|
+
|
|
351
|
+
def force(self, tokens: int, capacity: float, rate: float) -> None:
|
|
352
|
+
"""Take ``tokens`` without checking (goes into debt)."""
|
|
353
|
+
self._run("force", float(tokens), 0.0, float(capacity), float(rate))
|
|
354
|
+
|
|
355
|
+
def settle(self, reserved: int, actual: int, capacity: float, rate: float) -> None:
|
|
356
|
+
"""Replace a reservation by the real usage."""
|
|
357
|
+
self._run("settle", float(reserved), float(actual), float(capacity), float(rate))
|
|
358
|
+
|
|
359
|
+
def level(self, capacity: float, rate: float) -> float:
|
|
360
|
+
"""Tokens available now (negative while in debt)."""
|
|
361
|
+
return self._run("level", 0.0, 0.0, float(capacity), float(rate))
|
|
362
|
+
|
|
363
|
+
def observe(
|
|
364
|
+
self,
|
|
365
|
+
*,
|
|
366
|
+
remaining: float | None = None,
|
|
367
|
+
block_for: float | None = None,
|
|
368
|
+
capacity: float = 0.0,
|
|
369
|
+
rate: float = 1.0,
|
|
370
|
+
) -> float:
|
|
371
|
+
"""Apply provider knowledge: cap the level at ``remaining`` and/or block for seconds.
|
|
372
|
+
|
|
373
|
+
Returns the seconds the window is blocked for after the update (0 when open).
|
|
374
|
+
"""
|
|
375
|
+
return self._run(
|
|
376
|
+
"observe",
|
|
377
|
+
-1.0 if remaining is None else max(float(remaining), 0.0),
|
|
378
|
+
-1.0 if block_for is None else max(float(block_for), 0.0),
|
|
379
|
+
float(capacity),
|
|
380
|
+
float(rate),
|
|
381
|
+
)
|
|
382
|
+
|
|
383
|
+
def observe_headers(
|
|
384
|
+
self, headers: Any, *, capacity: float = 0.0, rate: float = 1.0
|
|
385
|
+
) -> RateLimitHint:
|
|
386
|
+
"""Update the window from provider rate-limit headers; see `parse_rate_limit_headers`.
|
|
387
|
+
|
|
388
|
+
``remaining`` lowers the level (never raises it), and ``Retry-After`` (or the reset
|
|
389
|
+
time when no tokens remain) blocks every worker until then. A limiter calls this
|
|
390
|
+
with its own ``capacity`` and ``rate``; called alone, only blocking and the
|
|
391
|
+
remaining count are applied.
|
|
392
|
+
"""
|
|
393
|
+
hint = parse_rate_limit_headers(headers)
|
|
394
|
+
block = hint.block_seconds
|
|
395
|
+
if hint.remaining_tokens is not None or block is not None:
|
|
396
|
+
self.observe(
|
|
397
|
+
remaining=hint.remaining_tokens, block_for=block, capacity=capacity, rate=rate
|
|
398
|
+
)
|
|
399
|
+
return hint
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
# ---------------------------------------------------------------------------- SQLite
|
|
403
|
+
|
|
404
|
+
_QUARANTINE_ERRORS = ("not a database", "malformed", "disk image", "corrupt")
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _is_corrupt(exc: BaseException) -> bool:
|
|
408
|
+
text = str(exc).lower()
|
|
409
|
+
return isinstance(exc, sqlite3.DatabaseError) and any(m in text for m in _QUARANTINE_ERRORS)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
class _SQLiteFile:
|
|
413
|
+
"""Connection handling shared by the SQLite window and budget backend."""
|
|
414
|
+
|
|
415
|
+
def __init__(self, path: str | os.PathLike[str], timeout: float, schema: str) -> None:
|
|
416
|
+
self.path = os.fspath(path)
|
|
417
|
+
self.timeout = timeout
|
|
418
|
+
self._schema = schema
|
|
419
|
+
self._prepared = False
|
|
420
|
+
self._plock = threading.Lock()
|
|
421
|
+
|
|
422
|
+
@contextlib.contextmanager
|
|
423
|
+
def connection(self) -> Iterator[sqlite3.Connection]:
|
|
424
|
+
"""A fresh connection inside a ``BEGIN IMMEDIATE`` transaction (commit or rollback)."""
|
|
425
|
+
self._prepare()
|
|
426
|
+
conn = sqlite3.connect(self.path, timeout=self.timeout, isolation_level=None)
|
|
427
|
+
try:
|
|
428
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
429
|
+
try:
|
|
430
|
+
yield conn
|
|
431
|
+
except BaseException:
|
|
432
|
+
conn.execute("ROLLBACK")
|
|
433
|
+
raise
|
|
434
|
+
conn.execute("COMMIT")
|
|
435
|
+
finally:
|
|
436
|
+
conn.close()
|
|
437
|
+
|
|
438
|
+
def _prepare(self) -> None:
|
|
439
|
+
if self._prepared:
|
|
440
|
+
return
|
|
441
|
+
with self._plock:
|
|
442
|
+
if self._prepared:
|
|
443
|
+
return
|
|
444
|
+
try:
|
|
445
|
+
self._create()
|
|
446
|
+
except sqlite3.DatabaseError as exc:
|
|
447
|
+
if not _is_corrupt(exc):
|
|
448
|
+
raise
|
|
449
|
+
self.quarantine()
|
|
450
|
+
self._create()
|
|
451
|
+
self._prepared = True
|
|
452
|
+
|
|
453
|
+
def _create(self) -> None:
|
|
454
|
+
conn = sqlite3.connect(self.path, timeout=self.timeout, isolation_level=None)
|
|
455
|
+
try:
|
|
456
|
+
with contextlib.suppress(sqlite3.DatabaseError):
|
|
457
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
458
|
+
conn.execute(self._schema)
|
|
459
|
+
finally:
|
|
460
|
+
conn.close()
|
|
461
|
+
|
|
462
|
+
def quarantine(self) -> None:
|
|
463
|
+
"""Move an unreadable database aside (``<path>.corrupt``) so a fresh one is created."""
|
|
464
|
+
for suffix in ("", "-wal", "-shm"):
|
|
465
|
+
source = self.path + suffix
|
|
466
|
+
if os.path.exists(source):
|
|
467
|
+
with contextlib.suppress(OSError):
|
|
468
|
+
os.replace(source, self.path + ".corrupt" + suffix)
|
|
469
|
+
self._prepared = False
|
|
470
|
+
|
|
471
|
+
def guard(self, action: Any) -> Any:
|
|
472
|
+
"""Run ``action`` once more after quarantining a corrupt file."""
|
|
473
|
+
try:
|
|
474
|
+
return action()
|
|
475
|
+
except sqlite3.DatabaseError as exc:
|
|
476
|
+
if not _is_corrupt(exc):
|
|
477
|
+
raise
|
|
478
|
+
with self._plock:
|
|
479
|
+
self.quarantine()
|
|
480
|
+
return action()
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
class SQLiteTokenWindow(SharedTokenWindow):
|
|
484
|
+
"""A `SharedTokenWindow` in one SQLite file, shared by processes on one host.
|
|
485
|
+
|
|
486
|
+
Every operation is a ``BEGIN IMMEDIATE`` transaction on a short-lived connection
|
|
487
|
+
(WAL journal), so it is atomic across processes, threads and ``fork``. A corrupt
|
|
488
|
+
file is moved aside to ``<path>.corrupt`` and rebuilt. Several named windows can
|
|
489
|
+
share one file.
|
|
490
|
+
|
|
491
|
+
Args:
|
|
492
|
+
path: The database file (created if missing).
|
|
493
|
+
name: Bucket name inside the file.
|
|
494
|
+
timeout: Seconds to wait for a competing writer before the storage counts as
|
|
495
|
+
failed (see ``fail_open``).
|
|
496
|
+
fail_open: Fall back to an in-memory bucket when storage fails.
|
|
497
|
+
|
|
498
|
+
Example:
|
|
499
|
+
```python
|
|
500
|
+
import os
|
|
501
|
+
import tempfile
|
|
502
|
+
|
|
503
|
+
from python_wrap.llm import token_rate_limit
|
|
504
|
+
from python_wrap.llm_shared import SQLiteTokenWindow
|
|
505
|
+
|
|
506
|
+
path = os.path.join(tempfile.mkdtemp(), "tokens.db")
|
|
507
|
+
limit = token_rate_limit(1000, estimate=400, block=False, store=SQLiteTokenWindow(path))
|
|
508
|
+
other_worker = SQLiteTokenWindow(path) # another process would open the same file
|
|
509
|
+
assert other_worker.level(1000, 1000 / 60) == 1000
|
|
510
|
+
limit.try_reserve(400)
|
|
511
|
+
assert other_worker.level(1000, 1000 / 60) < 700
|
|
512
|
+
```
|
|
513
|
+
"""
|
|
514
|
+
|
|
515
|
+
def __init__(
|
|
516
|
+
self,
|
|
517
|
+
path: str | os.PathLike[str],
|
|
518
|
+
name: str = "tokens",
|
|
519
|
+
*,
|
|
520
|
+
timeout: float = 10.0,
|
|
521
|
+
fail_open: bool = True,
|
|
522
|
+
) -> None:
|
|
523
|
+
super().__init__(name, fail_open=fail_open)
|
|
524
|
+
self._file = _SQLiteFile(
|
|
525
|
+
path,
|
|
526
|
+
timeout,
|
|
527
|
+
"CREATE TABLE IF NOT EXISTS windows ("
|
|
528
|
+
"name TEXT PRIMARY KEY, level REAL, stamp REAL NOT NULL, blocked REAL NOT NULL)",
|
|
529
|
+
)
|
|
530
|
+
|
|
531
|
+
@property
|
|
532
|
+
def path(self) -> str:
|
|
533
|
+
"""The database file."""
|
|
534
|
+
return self._file.path
|
|
535
|
+
|
|
536
|
+
def _once(self, op: str, a: float, b: float, capacity: float, rate: float) -> float:
|
|
537
|
+
with self._file.connection() as conn:
|
|
538
|
+
now = _core.wall_time()
|
|
539
|
+
row = conn.execute(
|
|
540
|
+
"SELECT level, stamp, blocked FROM windows WHERE name=?", (self.name,)
|
|
541
|
+
).fetchone()
|
|
542
|
+
state: _State | None = None if row is None else (row[0], row[1], row[2])
|
|
543
|
+
new, result = _step(state, op, a, b, capacity, rate, now)
|
|
544
|
+
conn.execute(
|
|
545
|
+
"INSERT OR REPLACE INTO windows(name, level, stamp, blocked) VALUES (?,?,?,?)",
|
|
546
|
+
(self.name, new[0], new[1], new[2]),
|
|
547
|
+
)
|
|
548
|
+
return float(result)
|
|
549
|
+
|
|
550
|
+
def _transact(self, op: str, a: float, b: float, capacity: float, rate: float) -> float:
|
|
551
|
+
result: float = self._file.guard(lambda: self._once(op, a, b, capacity, rate))
|
|
552
|
+
return result
|
|
553
|
+
|
|
554
|
+
def clear(self) -> None:
|
|
555
|
+
"""Forget this bucket (it starts full again)."""
|
|
556
|
+
with self._file.connection() as conn:
|
|
557
|
+
conn.execute("DELETE FROM windows WHERE name=?", (self.name,))
|
|
558
|
+
|
|
559
|
+
|
|
560
|
+
class SQLiteBudgetBackend:
|
|
561
|
+
"""A `python_wrap.llm.BudgetBackend` in SQLite: one budget shared by local processes.
|
|
562
|
+
|
|
563
|
+
``add`` is one ``BEGIN IMMEDIATE`` transaction, so concurrent workers never lose
|
|
564
|
+
spend; ``ttl`` expiry (windowed budgets) is honoured with the wall clock.
|
|
565
|
+
|
|
566
|
+
Args:
|
|
567
|
+
path: The database file (created if missing; a corrupt file is moved aside).
|
|
568
|
+
timeout: Seconds to wait for a competing writer.
|
|
569
|
+
|
|
570
|
+
Example:
|
|
571
|
+
```python
|
|
572
|
+
import os
|
|
573
|
+
import tempfile
|
|
574
|
+
|
|
575
|
+
from python_wrap.llm import Budget
|
|
576
|
+
from python_wrap.llm_shared import SQLiteBudgetBackend
|
|
577
|
+
|
|
578
|
+
path = os.path.join(tempfile.mkdtemp(), "budget.db")
|
|
579
|
+
budget = Budget(tokens=1000, backend=SQLiteBudgetBackend(path))
|
|
580
|
+
budget.record({"input_tokens": 300, "output_tokens": 100})
|
|
581
|
+
assert Budget(tokens=1000, backend=SQLiteBudgetBackend(path)).spent().tokens == 400
|
|
582
|
+
```
|
|
583
|
+
"""
|
|
584
|
+
|
|
585
|
+
def __init__(self, path: str | os.PathLike[str], *, timeout: float = 10.0) -> None:
|
|
586
|
+
self._file = _SQLiteFile(
|
|
587
|
+
path,
|
|
588
|
+
timeout,
|
|
589
|
+
"CREATE TABLE IF NOT EXISTS budgets ("
|
|
590
|
+
"key TEXT PRIMARY KEY, tokens INTEGER NOT NULL, usd REAL NOT NULL, expires REAL)",
|
|
591
|
+
)
|
|
592
|
+
|
|
593
|
+
@property
|
|
594
|
+
def path(self) -> str:
|
|
595
|
+
"""The database file."""
|
|
596
|
+
return self._file.path
|
|
597
|
+
|
|
598
|
+
def _add(self, key: str, tokens: int, usd: float, ttl: float | None) -> tuple[int, float]:
|
|
599
|
+
now = _core.wall_time()
|
|
600
|
+
with self._file.connection() as conn:
|
|
601
|
+
row = conn.execute(
|
|
602
|
+
"SELECT tokens, usd, expires FROM budgets WHERE key=?", (key,)
|
|
603
|
+
).fetchone()
|
|
604
|
+
used_tokens, used_usd, expires = 0, 0.0, None
|
|
605
|
+
if row is not None and (row[2] is None or now < row[2]):
|
|
606
|
+
used_tokens, used_usd, expires = row
|
|
607
|
+
if expires is None and ttl is not None:
|
|
608
|
+
expires = now + ttl
|
|
609
|
+
total = (int(used_tokens) + tokens, float(used_usd) + usd)
|
|
610
|
+
conn.execute(
|
|
611
|
+
"INSERT OR REPLACE INTO budgets(key, tokens, usd, expires) VALUES (?,?,?,?)",
|
|
612
|
+
(key, total[0], total[1], expires),
|
|
613
|
+
)
|
|
614
|
+
return total
|
|
615
|
+
|
|
616
|
+
def add(self, key: str, tokens: int, usd: float, ttl: float | None, /) -> tuple[int, float]:
|
|
617
|
+
"""Add to a counter atomically and return its new ``(tokens, usd)``."""
|
|
618
|
+
result: tuple[int, float] = self._file.guard(lambda: self._add(key, tokens, usd, ttl))
|
|
619
|
+
return result
|
|
620
|
+
|
|
621
|
+
def _get(self, key: str) -> tuple[int, float]:
|
|
622
|
+
now = _core.wall_time()
|
|
623
|
+
with self._file.connection() as conn:
|
|
624
|
+
row = conn.execute(
|
|
625
|
+
"SELECT tokens, usd, expires FROM budgets WHERE key=?", (key,)
|
|
626
|
+
).fetchone()
|
|
627
|
+
if row is None or (row[2] is not None and now >= row[2]):
|
|
628
|
+
return 0, 0.0
|
|
629
|
+
return int(row[0]), float(row[1])
|
|
630
|
+
|
|
631
|
+
def get(self, key: str, /) -> tuple[int, float]:
|
|
632
|
+
"""Return the counter's ``(tokens, usd)``; ``(0, 0.0)`` when unknown or expired."""
|
|
633
|
+
result: tuple[int, float] = self._file.guard(lambda: self._get(key))
|
|
634
|
+
return result
|
|
635
|
+
|
|
636
|
+
def delete(self, key: str, /) -> None:
|
|
637
|
+
"""Forget a counter."""
|
|
638
|
+
|
|
639
|
+
def action() -> None:
|
|
640
|
+
with self._file.connection() as conn:
|
|
641
|
+
conn.execute("DELETE FROM budgets WHERE key=?", (key,))
|
|
642
|
+
|
|
643
|
+
self._file.guard(action)
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
# ----------------------------------------------------------------------------- Redis
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def _redis_args(
|
|
650
|
+
name: str, prefix: str, op: str, a: float, b: float, cap: float, rate: float
|
|
651
|
+
) -> Any:
|
|
652
|
+
return (_LUA_STEP, 1, f"{prefix}:{name}", op, repr(a), repr(b), repr(cap), repr(rate))
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
class RedisTokenWindow(SharedTokenWindow):
|
|
656
|
+
"""A `SharedTokenWindow` on Redis, shared by every worker on every host.
|
|
657
|
+
|
|
658
|
+
Takes a synchronous ``redis.Redis``-compatible client (only ``eval`` is used) and
|
|
659
|
+
never imports redis. Each operation is one Lua script that reads the server's
|
|
660
|
+
clock (``TIME``), so workers with skewed clocks agree, and keys expire on their own
|
|
661
|
+
once the bucket would be full again. Async limiters run the round trip in a worker
|
|
662
|
+
thread; use `AsyncRedisTokenWindow` with a ``redis.asyncio`` client to stay on the
|
|
663
|
+
loop.
|
|
664
|
+
|
|
665
|
+
Args:
|
|
666
|
+
client: The Redis client.
|
|
667
|
+
name: Bucket name; share it to share the quota.
|
|
668
|
+
prefix: Namespace for the key.
|
|
669
|
+
fail_open: Fall back to an in-memory bucket when Redis fails.
|
|
670
|
+
"""
|
|
671
|
+
|
|
672
|
+
def __init__(
|
|
673
|
+
self,
|
|
674
|
+
client: Any,
|
|
675
|
+
name: str = "tokens",
|
|
676
|
+
*,
|
|
677
|
+
prefix: str = "python-wrap:tokens",
|
|
678
|
+
fail_open: bool = True,
|
|
679
|
+
) -> None:
|
|
680
|
+
super().__init__(name, fail_open=fail_open)
|
|
681
|
+
if not prefix:
|
|
682
|
+
raise ValueError("RedisTokenWindow needs a nonempty prefix")
|
|
683
|
+
self.client, self.prefix = client, prefix
|
|
684
|
+
|
|
685
|
+
def _transact(self, op: str, a: float, b: float, capacity: float, rate: float) -> float:
|
|
686
|
+
reply = self.client.eval(*_redis_args(self.name, self.prefix, op, a, b, capacity, rate))
|
|
687
|
+
return float(reply)
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
class AsyncRedisTokenWindow(SharedTokenWindow):
|
|
691
|
+
"""`RedisTokenWindow` for ``redis.asyncio`` clients: round trips are awaited.
|
|
692
|
+
|
|
693
|
+
Same script and keys as `RedisTokenWindow`, so sync and async workers can share one
|
|
694
|
+
bucket. The ``a``-prefixed methods (`areserve`, `aforce`, `asettle`, `alevel`,
|
|
695
|
+
`aobserve`, `aobserve_headers`) are the native ones; a limiter built on this window
|
|
696
|
+
must be used from async code.
|
|
697
|
+
"""
|
|
698
|
+
|
|
699
|
+
def __init__(
|
|
700
|
+
self,
|
|
701
|
+
client: Any,
|
|
702
|
+
name: str = "tokens",
|
|
703
|
+
*,
|
|
704
|
+
prefix: str = "python-wrap:tokens",
|
|
705
|
+
fail_open: bool = True,
|
|
706
|
+
) -> None:
|
|
707
|
+
super().__init__(name, fail_open=fail_open)
|
|
708
|
+
if not prefix:
|
|
709
|
+
raise ValueError("AsyncRedisTokenWindow needs a nonempty prefix")
|
|
710
|
+
self.client, self.prefix = client, prefix
|
|
711
|
+
|
|
712
|
+
def _transact(self, op: str, a: float, b: float, capacity: float, rate: float) -> float:
|
|
713
|
+
raise RuntimeError(
|
|
714
|
+
"AsyncRedisTokenWindow is async-only: use token_rate_limit(...) on async functions"
|
|
715
|
+
)
|
|
716
|
+
|
|
717
|
+
async def _arun(self, op: str, a: float, b: float, capacity: float, rate: float) -> float:
|
|
718
|
+
try:
|
|
719
|
+
reply = await self.client.eval(
|
|
720
|
+
*_redis_args(self.name, self.prefix, op, a, b, capacity, rate)
|
|
721
|
+
)
|
|
722
|
+
return float(reply)
|
|
723
|
+
except Exception as exc:
|
|
724
|
+
_core.emit("rate_limit.store_error", self.name, error=type(exc).__name__, op=op)
|
|
725
|
+
if not self.fail_open:
|
|
726
|
+
raise
|
|
727
|
+
return self._local(op, a, b, capacity, rate)
|
|
728
|
+
|
|
729
|
+
async def areserve(self, tokens: int, capacity: float, rate: float) -> float:
|
|
730
|
+
"""Async `reserve`."""
|
|
731
|
+
return await self._arun("reserve", float(tokens), 0.0, float(capacity), float(rate))
|
|
732
|
+
|
|
733
|
+
async def aforce(self, tokens: int, capacity: float, rate: float) -> None:
|
|
734
|
+
"""Async `force`."""
|
|
735
|
+
await self._arun("force", float(tokens), 0.0, float(capacity), float(rate))
|
|
736
|
+
|
|
737
|
+
async def asettle(self, reserved: int, actual: int, capacity: float, rate: float) -> None:
|
|
738
|
+
"""Async `settle`."""
|
|
739
|
+
await self._arun("settle", float(reserved), float(actual), float(capacity), float(rate))
|
|
740
|
+
|
|
741
|
+
async def alevel(self, capacity: float, rate: float) -> float:
|
|
742
|
+
"""Async `level`."""
|
|
743
|
+
return await self._arun("level", 0.0, 0.0, float(capacity), float(rate))
|
|
744
|
+
|
|
745
|
+
async def aobserve(
|
|
746
|
+
self,
|
|
747
|
+
*,
|
|
748
|
+
remaining: float | None = None,
|
|
749
|
+
block_for: float | None = None,
|
|
750
|
+
capacity: float = 0.0,
|
|
751
|
+
rate: float = 1.0,
|
|
752
|
+
) -> float:
|
|
753
|
+
"""Async `observe`."""
|
|
754
|
+
return await self._arun(
|
|
755
|
+
"observe",
|
|
756
|
+
-1.0 if remaining is None else max(float(remaining), 0.0),
|
|
757
|
+
-1.0 if block_for is None else max(float(block_for), 0.0),
|
|
758
|
+
float(capacity),
|
|
759
|
+
float(rate),
|
|
760
|
+
)
|
|
761
|
+
|
|
762
|
+
async def aobserve_headers(
|
|
763
|
+
self, headers: Any, *, capacity: float = 0.0, rate: float = 1.0
|
|
764
|
+
) -> RateLimitHint:
|
|
765
|
+
"""Async `observe_headers`."""
|
|
766
|
+
hint = parse_rate_limit_headers(headers)
|
|
767
|
+
block = hint.block_seconds
|
|
768
|
+
if hint.remaining_tokens is not None or block is not None:
|
|
769
|
+
await self.aobserve(
|
|
770
|
+
remaining=hint.remaining_tokens, block_for=block, capacity=capacity, rate=rate
|
|
771
|
+
)
|
|
772
|
+
return hint
|