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,446 @@
1
+ """Result retention guarded by renewable owner-checked leases."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import functools
7
+ import importlib
8
+ import json
9
+ import re
10
+ import uuid
11
+ from collections.abc import Callable
12
+ from contextlib import AsyncExitStack, ExitStack
13
+ from typing import Any, TypeVar, cast
14
+
15
+ from python_wrap import _core, _fork
16
+ from python_wrap._runtime import call_key, digest, seconds
17
+ from python_wrap.coordination import AlreadyRunning, Lease, LocalLease, _drain
18
+
19
+ __all__ = ["MemoryResultStore", "SqlResultStore", "idempotent"]
20
+ F = TypeVar("F", bound=Callable[..., Any])
21
+
22
+
23
+ class MemoryResultStore:
24
+ """A thread-safe, bounded, expiring store for local idempotency results.
25
+
26
+ Expired entries are swept as new ones arrive, and at most ``max_entries`` are kept:
27
+ when full, the entry closest to expiry is evicted first. A key whose result was
28
+ evicted simply runs again, so the bound trades a weaker guarantee under a flood of
29
+ distinct keys for memory that stays bounded (each key may come from an untrusted
30
+ client, for example through `python_wrap.web.IdempotencyMiddleware`).
31
+
32
+ Args:
33
+ max_entries: Most results kept at once (>= 1).
34
+
35
+ Raises:
36
+ ValueError: If ``max_entries`` is not a positive integer.
37
+
38
+ Example:
39
+ >>> store = MemoryResultStore(max_entries=2)
40
+ >>> for key in ("a", "b", "c"):
41
+ ... store.set(key, key.upper(), 60)
42
+ >>> len(store), store.get("a"), store.get("c")
43
+ (2, None, 'C')
44
+ """
45
+
46
+ def __init__(self, max_entries: int = 10_000) -> None:
47
+ if isinstance(max_entries, bool) or not isinstance(max_entries, int) or max_entries < 1:
48
+ raise ValueError("max_entries must be a positive integer")
49
+ self.max_entries = max_entries
50
+ self._data: dict[str, tuple[Any, float]] = {}
51
+ self._lock = _fork.ForkSafeLock()
52
+ _fork.register(self)
53
+
54
+ def _reset_after_fork(self) -> None:
55
+ self._data.clear()
56
+
57
+ def __len__(self) -> int:
58
+ with self._lock:
59
+ return len(self._data)
60
+
61
+ def get(self, key: str) -> Any:
62
+ with self._lock:
63
+ entry = self._data.get(key)
64
+ if entry is None:
65
+ return None
66
+ if entry[1] <= _core.monotonic():
67
+ del self._data[key]
68
+ return None
69
+ return entry[0]
70
+
71
+ def set(self, key: str, value: Any, ttl: float) -> None:
72
+ with self._lock:
73
+ now = _core.monotonic()
74
+ self._data.pop(key, None)
75
+ if len(self._data) >= self.max_entries:
76
+ for old in [k for k, (_, expires) in self._data.items() if expires <= now]:
77
+ del self._data[old]
78
+ while len(self._data) >= self.max_entries:
79
+ del self._data[min(self._data, key=lambda k: self._data[k][1])]
80
+ self._data[key] = (value, now + ttl)
81
+
82
+ def delete(self, key: str) -> bool:
83
+ with self._lock:
84
+ return self._data.pop(key, None) is not None
85
+
86
+
87
+ _IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,62}")
88
+ _TYPES = {
89
+ "postgresql": ("TEXT", "BIGINT"),
90
+ "mssql": ("NVARCHAR(MAX)", "BIGINT"),
91
+ "sqlite": ("TEXT", "INTEGER"),
92
+ }
93
+
94
+
95
+ class SqlResultStore:
96
+ """Idempotency results in a table of the application's own database (SQLAlchemy).
97
+
98
+ Rows hold ``idem_key`` (a SHA-256 of the call key), ``status`` (``running`` or
99
+ ``done``), ``owner``, ``result`` (JSON text by default) and ``expires_at`` (Unix
100
+ milliseconds). The same SQL runs on PostgreSQL, SQL Server and SQLite. The table is
101
+ never created for you: run the statements from `SqlResultStore.ddl` in a migration.
102
+ Call `purge_expired` from a scheduled job to drop old rows.
103
+
104
+ As a plain ``store=`` it records results like any other store (pair it with a shared
105
+ lease backend such as `SqlAppLock` or `PgAdvisoryLock` across processes). With
106
+ ``idempotent(store=..., connection=...)`` the key row is written on the caller's own
107
+ connection, so the key and the function's database writes commit or roll back
108
+ together; the table's primary key turns a concurrent duplicate into a wait or an
109
+ error instead of a second run.
110
+
111
+ Args:
112
+ engine: A SQLAlchemy ``Engine``.
113
+ table: Table name (letters, digits and underscores only).
114
+ dumps: Serializer for results; defaults to ``json.dumps``.
115
+ loads: Deserializer matching ``dumps``.
116
+
117
+ Raises:
118
+ ValueError: If ``table`` is not a plain identifier.
119
+ """
120
+
121
+ fail_open = False
122
+
123
+ def __init__(
124
+ self,
125
+ engine: Any,
126
+ table: str = "pw_idempotency",
127
+ *,
128
+ dumps: Callable[[Any], str] = json.dumps,
129
+ loads: Callable[[str], Any] = json.loads,
130
+ ) -> None:
131
+ if not isinstance(table, str) or not _IDENTIFIER.fullmatch(table):
132
+ raise ValueError("table must be a plain SQL identifier")
133
+ self.engine, self.table, self.dumps, self.loads = engine, table, dumps, loads
134
+
135
+ @staticmethod
136
+ def ddl(dialect: str, table: str = "pw_idempotency") -> list[str]:
137
+ """``CREATE`` statements for ``dialect`` (``postgresql``, ``mssql`` or ``sqlite``)."""
138
+ if dialect not in _TYPES:
139
+ raise ValueError(f"dialect must be one of {sorted(_TYPES)}")
140
+ if not _IDENTIFIER.fullmatch(table):
141
+ raise ValueError("table must be a plain SQL identifier")
142
+ text_type, int_type = _TYPES[dialect]
143
+ return [
144
+ f"CREATE TABLE {table} (idem_key VARCHAR(64) NOT NULL PRIMARY KEY,"
145
+ f" status VARCHAR(8) NOT NULL, owner VARCHAR(64) NOT NULL,"
146
+ f" result {text_type} NULL, expires_at {int_type} NOT NULL)",
147
+ f"CREATE INDEX {table}_expires ON {table} (expires_at)",
148
+ ]
149
+
150
+ @staticmethod
151
+ def _sql(statement: str) -> Any:
152
+ return importlib.import_module("sqlalchemy").text(statement)
153
+
154
+ @staticmethod
155
+ def _duplicate() -> Any:
156
+ """SQLAlchemy's IntegrityError (raised for a primary-key clash)."""
157
+ return importlib.import_module("sqlalchemy.exc").IntegrityError
158
+
159
+ @staticmethod
160
+ def _now() -> int:
161
+ return int(_core.wall_time() * 1000)
162
+
163
+ def _read(self, conn: Any, key: str) -> tuple[Any] | None:
164
+ # The table name was validated as an identifier; values are bound parameters.
165
+ row = conn.execute(
166
+ self._sql(f"SELECT status, result, expires_at FROM {self.table} WHERE idem_key=:k"), # nosec B608
167
+ {"k": digest(key)},
168
+ ).first()
169
+ if row is None or row[0] != "done" or int(row[2]) <= self._now():
170
+ return None
171
+ return (self.loads(row[1]),)
172
+
173
+ def _claim(self, conn: Any, key: str, owner: str, ttl: float) -> bool:
174
+ """Insert a ``running`` row, or take over an expired one. False if it is live."""
175
+ params = {"k": digest(key), "o": owner, "e": self._now() + int(ttl * 1000)}
176
+ try:
177
+ with conn.begin_nested():
178
+ conn.execute(
179
+ self._sql(
180
+ f"INSERT INTO {self.table} (idem_key, status, owner, result, expires_at)" # nosec B608
181
+ " VALUES (:k, 'running', :o, NULL, :e)"
182
+ ),
183
+ params,
184
+ )
185
+ return True
186
+ except self._duplicate():
187
+ pass
188
+ taken = conn.execute(
189
+ self._sql(
190
+ f"UPDATE {self.table} SET status='running', owner=:o, result=NULL," # nosec B608
191
+ " expires_at=:e WHERE idem_key=:k AND expires_at<=:now"
192
+ ),
193
+ {**params, "now": self._now()},
194
+ )
195
+ return bool(taken.rowcount == 1)
196
+
197
+ def _finish(self, conn: Any, key: str, value: Any, ttl: float, owner: str) -> None:
198
+ conn.execute(
199
+ self._sql(
200
+ f"UPDATE {self.table} SET status='done', result=:r, expires_at=:e" # nosec B608
201
+ " WHERE idem_key=:k AND owner=:o"
202
+ ),
203
+ {
204
+ "k": digest(key),
205
+ "o": owner,
206
+ "r": self.dumps(value),
207
+ "e": self._now() + int(ttl * 1000),
208
+ },
209
+ )
210
+
211
+ # -- the result-store contract used by idempotent ------------------------------------
212
+ def get(self, key: str) -> tuple[Any] | None:
213
+ with self.engine.connect() as conn:
214
+ return self._read(conn, key)
215
+
216
+ def set(self, key: str, entry: tuple[Any], ttl: float) -> None:
217
+ params = {
218
+ "k": digest(key),
219
+ "o": "",
220
+ "r": self.dumps(entry[0]),
221
+ "e": self._now() + int(ttl * 1000),
222
+ }
223
+ update = self._sql(
224
+ f"UPDATE {self.table} SET status='done', owner=:o, result=:r, expires_at=:e" # nosec B608
225
+ " WHERE idem_key=:k"
226
+ )
227
+ with self.engine.begin() as conn:
228
+ if conn.execute(update, params).rowcount:
229
+ return
230
+ try:
231
+ with conn.begin_nested():
232
+ conn.execute(
233
+ self._sql(
234
+ f"INSERT INTO {self.table}" # nosec B608
235
+ " (idem_key, status, owner, result, expires_at)"
236
+ " VALUES (:k, 'done', :o, :r, :e)"
237
+ ),
238
+ params,
239
+ )
240
+ except self._duplicate(): # inserted concurrently: last writer wins, as in Redis
241
+ conn.execute(update, params)
242
+
243
+ def delete(self, key: str) -> bool:
244
+ with self.engine.begin() as conn:
245
+ gone = conn.execute(
246
+ self._sql(f"DELETE FROM {self.table} WHERE idem_key=:k"), # nosec B608
247
+ {"k": digest(key)},
248
+ )
249
+ return bool(gone.rowcount)
250
+
251
+ def purge_expired(self, limit: int = 1000) -> int:
252
+ """Delete up to ``limit`` expired rows; returns how many went. Call it on a schedule."""
253
+ if isinstance(limit, bool) or not isinstance(limit, int) or limit < 1:
254
+ raise ValueError("limit must be a positive integer")
255
+ if self.engine.dialect.name == "mssql":
256
+ sql = f"DELETE TOP ({limit}) FROM {self.table} WHERE expires_at<=:now" # nosec B608
257
+ else:
258
+ sql = (
259
+ f"DELETE FROM {self.table} WHERE idem_key IN (SELECT idem_key FROM {self.table}" # nosec B608
260
+ f" WHERE expires_at<=:now LIMIT {limit})"
261
+ )
262
+ with self.engine.begin() as conn:
263
+ return int(conn.execute(self._sql(sql), {"now": self._now()}).rowcount)
264
+
265
+
266
+ def idempotent(
267
+ *,
268
+ key: str | Callable[..., Any] | None = None,
269
+ ttl: float | str = "1d",
270
+ store: Any = None,
271
+ backend: Any = None,
272
+ in_progress: str = "raise",
273
+ lease_ttl: float | str = 60,
274
+ timeout: float | None = None,
275
+ connection: Callable[[], Any] | None = None,
276
+ ) -> Callable[[F], F]:
277
+ """Run once per key within TTL; duplicates return the stored result.
278
+
279
+ `in_progress` is raise, wait, or return_none. ``store`` may also be an
280
+ `python_wrap.async_cache.AsyncCacheStore` (for ``async def`` functions): it is
281
+ awaited directly, and an `AsyncRedisStore` gets a matching `AsyncRedisLock`.
282
+ Failed calls release their lease without caching. Distributed use requires BOTH a
283
+ shared result store and shared lease backend; RedisStore(fail_open=False)
284
+ automatically supplies a matching RedisLock unless a backend is explicitly given.
285
+ Other shared stores need an explicitly supplied shared lease backend.
286
+ This cannot guarantee exactly-once external effects across a process crash between
287
+ writing an external system and recording the result. Use transactional outboxes or
288
+ database idempotency keys for that guarantee. Ownership is checked and extended
289
+ immediately before publishing a result, but a generic result store cannot fence
290
+ writes atomically with lease expiry; client I/O timeouts must be shorter than the
291
+ lease and strict transactional guarantees require an application-level protocol.
292
+
293
+ ``connection`` closes that gap for work whose effect is a database write. Give a
294
+ `SqlResultStore` and a callable returning the SQLAlchemy ``Connection`` the function
295
+ writes with, inside the caller's transaction. The key row is inserted on that
296
+ connection (in a savepoint) and marked done there, so it commits or rolls back with
297
+ the function's own writes: a crash before commit leaves no key and no write, and a
298
+ retry runs once. A concurrent duplicate waits on the row lock and then returns the
299
+ committed result; a live claim the caller committed early follows ``in_progress``.
300
+ Sync functions only.
301
+ """
302
+ retention, lease_seconds = seconds(ttl), seconds(lease_ttl)
303
+ if in_progress not in {"raise", "wait", "return_none"}:
304
+ raise ValueError("in_progress must be raise, wait or return_none")
305
+ results: Any = MemoryResultStore() if store is None else store
306
+ if getattr(results, "fail_open", False):
307
+ raise ValueError("idempotency requires a result store with fail_open=False")
308
+ if backend is not None and not isinstance(backend, LocalLease) and store is None:
309
+ raise ValueError("a distributed lease requires an explicitly shared result store")
310
+ native = _core.is_async(results.get) # an AsyncCacheStore: awaited, never threaded
311
+ if backend is None:
312
+ from python_wrap.async_cache import AsyncRedisStore
313
+ from python_wrap.coordination import AsyncRedisLock, RedisLock
314
+ from python_wrap.stores import RedisStore
315
+
316
+ if isinstance(results, (RedisStore, AsyncRedisStore)):
317
+ lock = AsyncRedisLock if isinstance(results, AsyncRedisStore) else RedisLock
318
+ backend = lock(
319
+ results.client,
320
+ prefix="python-wrap:idempotency-locks:" + digest(results.prefix) + ":",
321
+ )
322
+
323
+ async def read(k: str) -> Any:
324
+ return await (results.get(k) if native else asyncio.to_thread(results.get, k))
325
+
326
+ def write(k: str, value: Any) -> Any:
327
+ if native:
328
+ return asyncio.ensure_future(results.set(k, (value,), retention))
329
+ return asyncio.create_task(asyncio.to_thread(results.set, k, (value,), retention))
330
+
331
+ if connection is not None and not isinstance(results, SqlResultStore):
332
+ raise TypeError("connection= needs store=SqlResultStore(...)")
333
+
334
+ def decorate(func: F) -> F:
335
+ if native and not _core.is_async(func):
336
+ raise TypeError("an async result store needs an async def function")
337
+ if connection is not None:
338
+ if _core.is_async(func):
339
+ raise TypeError("connection= supports sync functions only")
340
+ return cast(
341
+ F,
342
+ _transactional(
343
+ func, key, results, connection, retention, lease_seconds, in_progress
344
+ ),
345
+ )
346
+
347
+ def scope(k: str) -> Lease:
348
+ return Lease(
349
+ "idem:" + k,
350
+ backend=backend,
351
+ ttl=lease_seconds,
352
+ wait=in_progress == "wait",
353
+ timeout=timeout,
354
+ )
355
+
356
+ if _core.is_async(func):
357
+
358
+ @functools.wraps(func)
359
+ async def aw(*args: Any, **kw: Any) -> Any:
360
+ k = call_key(func, key, args, kw)
361
+ found = await read(k)
362
+ if found is not None:
363
+ return found[0]
364
+ lease = scope(k)
365
+ try:
366
+ await lease.__aenter__()
367
+ except AlreadyRunning:
368
+ if in_progress == "return_none":
369
+ return None
370
+ raise
371
+ async with AsyncExitStack() as stack:
372
+ stack.push_async_exit(lease)
373
+ found = await read(k)
374
+ if found is not None:
375
+ return found[0]
376
+ value = await func(*args, **kw)
377
+ # A stalled/failed heartbeat must not publish a stale owner's result.
378
+ await lease.check_async()
379
+ _, error, cancelled = await _drain(write(k, value))
380
+ if cancelled:
381
+ raise asyncio.CancelledError
382
+ if error is not None:
383
+ raise error
384
+ return value
385
+
386
+ return cast(F, aw)
387
+
388
+ @functools.wraps(func)
389
+ def sw(*args: Any, **kw: Any) -> Any:
390
+ k = call_key(func, key, args, kw)
391
+ found = results.get(k)
392
+ if found is not None:
393
+ return found[0]
394
+ lease = scope(k)
395
+ try:
396
+ lease.__enter__()
397
+ except AlreadyRunning:
398
+ if in_progress == "return_none":
399
+ return None
400
+ raise
401
+ with ExitStack() as stack:
402
+ stack.push(lease)
403
+ found = results.get(k)
404
+ if found is not None:
405
+ return found[0]
406
+ value = func(*args, **kw)
407
+ lease.check()
408
+ results.set(k, (value,), retention)
409
+ return value
410
+
411
+ return cast(F, sw)
412
+
413
+ return decorate
414
+
415
+
416
+ def _transactional(
417
+ func: Callable[..., Any],
418
+ key: str | Callable[..., Any] | None,
419
+ store: SqlResultStore,
420
+ connection: Callable[[], Any],
421
+ retention: float,
422
+ lease_seconds: float,
423
+ in_progress: str,
424
+ ) -> Callable[..., Any]:
425
+ """`idempotent` whose key row shares the caller's transaction (see ``connection=``)."""
426
+
427
+ @functools.wraps(func)
428
+ def wrapper(*args: Any, **kw: Any) -> Any:
429
+ k = call_key(func, key, args, kw)
430
+ conn = connection()
431
+ found = store._read(conn, k)
432
+ if found is not None:
433
+ return found[0]
434
+ owner = uuid.uuid4().hex
435
+ if not store._claim(conn, k, owner, lease_seconds):
436
+ found = store._read(conn, k) # a duplicate committed while we waited on its lock
437
+ if found is not None:
438
+ return found[0]
439
+ if in_progress == "return_none":
440
+ return None
441
+ raise AlreadyRunning("idem:" + k)
442
+ value = func(*args, **kw)
443
+ store._finish(conn, k, value, retention, owner)
444
+ return value
445
+
446
+ return wrapper