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
python_wrap/presets.py ADDED
@@ -0,0 +1,378 @@
1
+ """Opinionated, documented starting points for the most common resilience stacks.
2
+
3
+ Choosing numbers is the hard part of resilience. Each preset returns an ordinary
4
+ `Policy` with a per-attempt timeout, a bounded retry guarded by a `RetryBudget`, and a
5
+ circuit breaker, using values that are safe for typical traffic:
6
+
7
+ - `http_client`: 10 s timeout, 3 attempts, waits 0.2 s then 0.4 s (plus up to 0.1 s
8
+ jitter), breaker opens after 5 failures for 30 s.
9
+ - `db_call`: 5 s timeout, 3 attempts on transient database errors only, waits 0.05 s then
10
+ 0.1 s, no breaker by default.
11
+ - `third_party_api`: 15 s timeout, 4 attempts, waits 0.5, 1, 2 s (plus up to 0.5 s),
12
+ breaker opens after 5 failures for 60 s; optional rate limit and bulkhead.
13
+ - `llm_client`: 60 s timeout, 4 attempts on transient LLM errors only (429, 529,
14
+ overloaded, 5xx, timeouts, connection errors), waits 1, 2, 4 s (plus up to 0.5 s) or the
15
+ provider's ``Retry-After``, breaker counting only those errors opens after 5 for 60 s;
16
+ optional spend `Budget`.
17
+
18
+ Every retry layer gets ``max_time`` larger than ``timeout * attempts`` so a slow
19
+ attempt never consumes the whole budget, and a `RetryBudget` (20 % of traffic plus 5
20
+ retries/s) so retries cannot multiply load during an outage. Pass ``idempotent=False``
21
+ for operations that must not run twice: the retry layer is then left out entirely.
22
+
23
+ The presets are part of the stable core: the defaults may only change in a minor
24
+ release with a CHANGELOG entry, never in a patch release.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from collections.abc import Callable
30
+ from typing import Any
31
+
32
+ from python_wrap.bulkhead import Bulkhead
33
+ from python_wrap.circuit import CircuitBreaker
34
+ from python_wrap.concurrency import RateLimiter, timeout
35
+ from python_wrap.errors import CircuitOpenError, TimeoutExpired
36
+ from python_wrap.llm import Budget, TokenRateLimiter, _BreakerLayer, _llm_breaker, llm_retry
37
+ from python_wrap.policy import Policy, policy
38
+ from python_wrap.predicates import db_transient
39
+ from python_wrap.retry import RetryBudget, retry
40
+ from python_wrap.shared import SharedBackends, resolve_shared
41
+
42
+ __all__ = ["TRANSPORT_ERRORS", "db_call", "http_client", "llm_client", "third_party_api"]
43
+
44
+ #: Exceptions every preset treats as transient: lost/refused connections and timeouts
45
+ #: (`TimeoutExpired` is a `TimeoutError`). HTTP libraries' own transport errors subclass
46
+ #: neither, so pass ``on=`` (or use `python_wrap.http`) for them.
47
+ TRANSPORT_ERRORS: tuple[type[BaseException], ...] = (ConnectionError, TimeoutError)
48
+
49
+
50
+ def _budget(
51
+ budget: RetryBudget | None, name: str = "", shared: SharedBackends | None = None
52
+ ) -> RetryBudget:
53
+ if budget is not None:
54
+ return budget
55
+ backend = None if shared is None else shared.budget_backend(name)
56
+ return RetryBudget(ratio=0.2, min_per_second=5, backend=backend)
57
+
58
+
59
+ def _breaker(shared: SharedBackends | None, **options: Any) -> CircuitBreaker:
60
+ return CircuitBreaker(backend=None if shared is None else shared.breaker(), **options)
61
+
62
+
63
+ def _retry(
64
+ *,
65
+ idempotent: bool,
66
+ attempts: int,
67
+ seconds: float,
68
+ delay: float,
69
+ max_delay: float,
70
+ jitter: float,
71
+ on: tuple[type[BaseException], ...] | type[BaseException],
72
+ retry_if: Callable[[Any], bool] | None,
73
+ budget: RetryBudget | None,
74
+ name: str = "",
75
+ shared: SharedBackends | None = None,
76
+ ) -> Any:
77
+ if not idempotent or attempts <= 1:
78
+ return None
79
+ return retry(
80
+ max_attempts=attempts,
81
+ delay=delay,
82
+ backoff=2,
83
+ max_delay=max_delay,
84
+ jitter=jitter,
85
+ max_time=seconds * attempts + delay * 2**attempts + 1,
86
+ on=on,
87
+ retry_if=retry_if,
88
+ budget=_budget(budget, name, shared),
89
+ )
90
+
91
+
92
+ def http_client(
93
+ name: str,
94
+ *,
95
+ timeout_seconds: float = 10.0,
96
+ attempts: int = 3,
97
+ idempotent: bool = True,
98
+ breaker: bool = True,
99
+ on: tuple[type[BaseException], ...] = TRANSPORT_ERRORS,
100
+ budget: RetryBudget | None = None,
101
+ shared: Any = None,
102
+ ) -> Policy:
103
+ """A policy for calls to an internal HTTP service you own.
104
+
105
+ Args:
106
+ name: Policy and breaker name (used in events, metrics and errors).
107
+ timeout_seconds: Per-attempt time limit.
108
+ attempts: Total attempts, including the first.
109
+ idempotent: False leaves the retry layer out (POSTs without an idempotency key).
110
+ breaker: Include a `CircuitBreaker` (5 failures, 30 s recovery).
111
+ on: Exception types that are retried and counted by the breaker.
112
+ budget: Share one `RetryBudget` between several policies; a new one otherwise.
113
+ shared: A Redis client or `SharedBackends`: the breaker state and the retry budget
114
+ then live in Redis, keyed by ``name``, so every worker process shares them
115
+ (default: ``configure(shared=...)``, else per-process state).
116
+
117
+ Returns:
118
+ A `Policy`, usable as a decorator.
119
+
120
+ Example:
121
+ ```python
122
+ from python_wrap.presets import http_client
123
+
124
+ users = http_client("users-service")
125
+
126
+ @users
127
+ def get_user(user_id: int) -> dict[str, int]:
128
+ return {"id": user_id}
129
+
130
+ assert get_user(7) == {"id": 7}
131
+ assert users.explain().ok
132
+ ```
133
+ """
134
+ sb = resolve_shared(shared)
135
+ return policy(
136
+ name=name,
137
+ breaker=(
138
+ _breaker(sb, failure_threshold=5, recovery_timeout=30.0, on=on, name=name)
139
+ if breaker
140
+ else None
141
+ ),
142
+ retry=_retry(
143
+ idempotent=idempotent,
144
+ attempts=attempts,
145
+ seconds=timeout_seconds,
146
+ delay=0.2,
147
+ max_delay=2.0,
148
+ jitter=0.1,
149
+ on=on,
150
+ retry_if=None,
151
+ budget=budget,
152
+ name=name,
153
+ shared=sb,
154
+ ),
155
+ timeout=timeout(timeout_seconds),
156
+ )
157
+
158
+
159
+ def db_call(
160
+ name: str,
161
+ *,
162
+ timeout_seconds: float = 5.0,
163
+ attempts: int = 3,
164
+ idempotent: bool = True,
165
+ breaker: bool = False,
166
+ retry_if: Callable[[Any], bool] = db_transient,
167
+ budget: RetryBudget | None = None,
168
+ shared: Any = None,
169
+ ) -> Policy:
170
+ """A policy for a database unit of work (a whole transaction, not one statement).
171
+
172
+ Retries only errors `db_transient` classifies as transient (deadlocks, serialization
173
+ failures, dropped connections, Azure SQL reconfiguration), so constraint violations
174
+ and syntax errors fail at once. The breaker is off by default: a database is usually
175
+ a hard dependency, and failing fast rarely helps. Turn it on for optional/secondary
176
+ databases; it then counts only connection-level failures (`TRANSPORT_ERRORS`).
177
+
178
+ Args:
179
+ name: Policy name.
180
+ timeout_seconds: Per-attempt time limit (keep it above your statement timeout).
181
+ attempts: Total attempts.
182
+ idempotent: False leaves the retry layer out.
183
+ breaker: Include a `CircuitBreaker` (10 failures, 15 s recovery).
184
+ retry_if: Which exceptions are transient; default `db_transient`.
185
+ budget: A shared `RetryBudget`, or None for a new one.
186
+ shared: A Redis client or `SharedBackends` for breaker state and the retry budget
187
+ (see `http_client`).
188
+
189
+ Returns:
190
+ A `Policy`.
191
+ """
192
+ sb = resolve_shared(shared)
193
+ return policy(
194
+ name=name,
195
+ breaker=(
196
+ _breaker(
197
+ sb, failure_threshold=10, recovery_timeout=15.0, on=TRANSPORT_ERRORS, name=name
198
+ )
199
+ if breaker
200
+ else None
201
+ ),
202
+ retry=_retry(
203
+ idempotent=idempotent,
204
+ attempts=attempts,
205
+ seconds=timeout_seconds,
206
+ delay=0.05,
207
+ max_delay=1.0,
208
+ jitter=0.05,
209
+ on=Exception,
210
+ retry_if=lambda exc: (
211
+ not isinstance(exc, (CircuitOpenError, TimeoutExpired)) and retry_if(exc)
212
+ ),
213
+ budget=budget,
214
+ name=name,
215
+ shared=sb,
216
+ ),
217
+ timeout=timeout(timeout_seconds),
218
+ )
219
+
220
+
221
+ def third_party_api(
222
+ name: str,
223
+ *,
224
+ timeout_seconds: float = 15.0,
225
+ attempts: int = 4,
226
+ idempotent: bool = True,
227
+ on: tuple[type[BaseException], ...] = TRANSPORT_ERRORS,
228
+ calls: int | None = None,
229
+ period: float = 1.0,
230
+ max_concurrent: int | None = None,
231
+ budget: RetryBudget | None = None,
232
+ shared: Any = None,
233
+ ) -> Policy:
234
+ """A policy for an external vendor API (payment gateway, ERP, SMS/e-mail provider).
235
+
236
+ Slower backoff than `http_client` and a longer breaker recovery, because vendors
237
+ recover on their own schedule. Optional client-side rate limit (``calls`` per
238
+ ``period``, rejecting with `RateLimitExceeded`) and bulkhead (``max_concurrent``)
239
+ keep you inside the vendor's quota and stop one slow vendor from tying up every
240
+ worker.
241
+
242
+ Args:
243
+ name: Policy, breaker and bulkhead name.
244
+ timeout_seconds: Per-attempt time limit.
245
+ attempts: Total attempts.
246
+ idempotent: False leaves the retry layer out (charges, sends).
247
+ on: Exception types that are retried and counted by the breaker.
248
+ calls: Rate limit: calls allowed per ``period`` (None: no limiter).
249
+ period: Rate-limit period in seconds.
250
+ max_concurrent: Bulkhead size (None: no bulkhead).
251
+ budget: A shared `RetryBudget`, or None for a new one.
252
+ shared: A Redis client or `SharedBackends`: breaker state, the rate window, the
253
+ bulkhead lease and the retry budget are then shared by every worker process,
254
+ so ``calls`` is a fleet-wide limit (see `http_client`).
255
+
256
+ Returns:
257
+ A `Policy`.
258
+ """
259
+ sb = resolve_shared(shared)
260
+ window = None if sb is None or calls is None else sb.rate_window(name, calls, period)
261
+ lease = None if sb is None else sb.lease_backend()
262
+ return policy(
263
+ name=name,
264
+ limiter=(
265
+ None
266
+ if calls is None
267
+ else RateLimiter(calls, period, name=name, backend=window)
268
+ if window is not None
269
+ else RateLimiter(calls, period, name=name)
270
+ ),
271
+ bulkhead=(
272
+ None if max_concurrent is None else Bulkhead(max_concurrent, name=name, backend=lease)
273
+ ),
274
+ breaker=_breaker(sb, failure_threshold=5, recovery_timeout=60.0, on=on, name=name),
275
+ retry=_retry(
276
+ idempotent=idempotent,
277
+ attempts=attempts,
278
+ seconds=timeout_seconds,
279
+ delay=0.5,
280
+ max_delay=8.0,
281
+ jitter=0.5,
282
+ on=on,
283
+ retry_if=None,
284
+ budget=budget,
285
+ name=name,
286
+ shared=sb,
287
+ ),
288
+ timeout=timeout(timeout_seconds),
289
+ )
290
+
291
+
292
+ def llm_client(
293
+ name: str,
294
+ *,
295
+ timeout_seconds: float = 60.0,
296
+ attempts: int = 4,
297
+ idempotent: bool = True,
298
+ breaker: bool = True,
299
+ max_delay: float = 60.0,
300
+ budget: RetryBudget | None = None,
301
+ spend: Budget | None = None,
302
+ tokens: TokenRateLimiter | None = None,
303
+ shared: Any = None,
304
+ ) -> Policy:
305
+ """A policy for calls to an LLM provider (chat/completions/messages endpoints).
306
+
307
+ Retries only what `python_wrap.llm.llm_transient` accepts: 408/409/429/529, every
308
+ 5xx, overloaded bodies, timeouts and connection errors. Bad requests, auth errors and
309
+ content-policy refusals fail at once. Waits double from 1 s (plus up to 0.5 s jitter)
310
+ unless the provider sends ``Retry-After`` / ``retry-after-ms``, which is honoured up
311
+ to ``max_delay``. The breaker counts only those transient errors, so a burst of
312
+ refused prompts never opens it. The 60 s per-attempt timeout suits non-streamed
313
+ answers of a few thousand tokens; raise it for long outputs and use
314
+ `python_wrap.llm.stream_timeout` for streams.
315
+
316
+ Args:
317
+ name: Policy and breaker name.
318
+ timeout_seconds: Per-attempt time limit.
319
+ attempts: Total attempts, including the first.
320
+ idempotent: False leaves the retry layer out.
321
+ breaker: Include a breaker (5 transient failures, 60 s recovery).
322
+ max_delay: Longest wait between attempts, also the cap on ``Retry-After``.
323
+ budget: A shared `RetryBudget`, or None for a new one (20 %, 5/s).
324
+ spend: A token/dollar `python_wrap.llm.Budget`, placed in the ``limiter`` role
325
+ (checked once per logical call; usage recorded from the final response).
326
+ tokens: A `python_wrap.llm.TokenRateLimiter`, also in the ``limiter`` role.
327
+ shared: A Redis client or `SharedBackends` for the breaker state and the retry
328
+ budget (see `http_client`).
329
+
330
+ Returns:
331
+ A `Policy`.
332
+
333
+ Example:
334
+ ```python
335
+ from python_wrap.llm import Budget
336
+ from python_wrap.presets import llm_client
337
+
338
+ chat = llm_client("chat", spend=Budget(tokens=100_000))
339
+
340
+ @chat
341
+ def complete(prompt: str) -> dict[str, object]:
342
+ return {"usage": {"input_tokens": 10, "output_tokens": 5}}
343
+
344
+ complete("hi")
345
+ assert chat.explain().findings == ()
346
+ ```
347
+ """
348
+ sb = resolve_shared(shared)
349
+ limiters = [layer for layer in (spend, tokens) if layer is not None]
350
+ return policy(
351
+ name=name,
352
+ limiter=limiters or None,
353
+ breaker=(
354
+ _BreakerLayer(
355
+ _llm_breaker(
356
+ failure_threshold=5,
357
+ recovery_timeout=60.0,
358
+ name=name,
359
+ backend=None if sb is None else sb.breaker(),
360
+ )
361
+ )
362
+ if breaker
363
+ else None
364
+ ),
365
+ retry=(
366
+ llm_retry(
367
+ max_attempts=attempts,
368
+ delay=1.0,
369
+ max_delay=max_delay,
370
+ jitter=0.5,
371
+ max_time=timeout_seconds * attempts + max_delay * (attempts - 1) + 1,
372
+ budget=_budget(budget, name, sb),
373
+ )
374
+ if idempotent and attempts > 1
375
+ else None
376
+ ),
377
+ timeout=timeout(timeout_seconds),
378
+ )
@@ -0,0 +1,227 @@
1
+ """Per-item batch outcomes and explicit checkpoints for resumable processing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ from collections.abc import Awaitable, Callable, Iterable, Mapping
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Generic, TypeVar, overload
9
+
10
+ from python_wrap import _core
11
+ from python_wrap._runtime import offload_settled
12
+
13
+ __all__ = [
14
+ "BatchResult",
15
+ "MemoryCheckpoint",
16
+ "Outcome",
17
+ "RedisCheckpoint",
18
+ "aprocess_batches",
19
+ "process_batches",
20
+ ]
21
+ T = TypeVar("T")
22
+ R = TypeVar("R")
23
+ _STATUSES = {"failed", "parked", "skipped", "conflict"}
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Outcome(Generic[T, R]):
28
+ """One input's result, classification and original exception when it failed."""
29
+
30
+ index: int
31
+ item: T
32
+ status: str
33
+ result: R | None = None
34
+ exception: Exception | None = None
35
+
36
+
37
+ @dataclass
38
+ class BatchResult(Generic[T, R]):
39
+ """Collected outcomes, preserving input order. O(number of processed items) storage."""
40
+
41
+ outcomes: list[Outcome[T, R]] = field(default_factory=list)
42
+
43
+ @property
44
+ def succeeded(self) -> list[Outcome[T, R]]:
45
+ return [item for item in self.outcomes if item.status == "succeeded"]
46
+
47
+ @property
48
+ def failed(self) -> list[Outcome[T, R]]:
49
+ return [item for item in self.outcomes if item.status != "succeeded"]
50
+
51
+ def to_rows(self, *, reason_column: str = "reason") -> list[dict[str, Any]]:
52
+ """Convert failed items into rows with an error reason and classification."""
53
+ return [
54
+ {
55
+ **(dict(o.item) if isinstance(o.item, Mapping) else {"item": o.item}),
56
+ "status": o.status,
57
+ reason_column: str(o.exception),
58
+ }
59
+ for o in self.failed
60
+ ]
61
+
62
+
63
+ class MemoryCheckpoint:
64
+ """A local next-index checkpoint; use one instance per input stream."""
65
+
66
+ def __init__(self) -> None:
67
+ self.index = 0
68
+
69
+ def load(self) -> int:
70
+ return self.index
71
+
72
+ def save(self, index: int) -> None:
73
+ self.index = index
74
+
75
+
76
+ class RedisCheckpoint:
77
+ """Persistent next-index checkpoint; input ordering must remain stable on restart."""
78
+
79
+ def __init__(self, client: Any, key: str) -> None:
80
+ self.client, self.key = client, key
81
+
82
+ def load(self) -> int:
83
+ return int(self.client.get(self.key) or 0)
84
+
85
+ def save(self, index: int) -> None:
86
+ self.client.set(self.key, index)
87
+
88
+
89
+ def _failed(
90
+ index: int, item: Any, exc: Exception, classify: Callable[[Exception], str]
91
+ ) -> Outcome[Any, Any]:
92
+ status = classify(exc)
93
+ if status not in _STATUSES:
94
+ raise ValueError(f"unknown batch classification: {status!r}")
95
+ return Outcome(index, item, status, exception=exc)
96
+
97
+
98
+ def process_batches(
99
+ items: Iterable[T],
100
+ handler: Callable[[T], R],
101
+ *,
102
+ chunk_size: int = 500,
103
+ classify: Callable[[Exception], str] = lambda exc: "failed",
104
+ checkpoint: Any = None,
105
+ on_progress: Callable[[int, int], Any] | None = None,
106
+ ) -> BatchResult[T, R]:
107
+ """Process items independently, persisting the next index after each chunk.
108
+
109
+ Failed items are recorded and count as processed. A crash before a chunk checkpoint
110
+ can replay that chunk: handlers must be idempotent when side effects matter. One
111
+ caller must own the checkpoint (use single_instance for distributed exclusion).
112
+ on_progress receives (processed_this_call, next_input_index).
113
+ """
114
+ if isinstance(chunk_size, bool) or not isinstance(chunk_size, int) or chunk_size < 1:
115
+ raise ValueError("chunk_size must be a positive integer")
116
+ if _core.is_async(handler):
117
+ raise TypeError("use aprocess_batches for an async handler")
118
+ result: BatchResult[T, R] = BatchResult()
119
+ start = checkpoint.load() if checkpoint is not None else 0
120
+ if isinstance(start, bool) or not isinstance(start, int) or start < 0:
121
+ raise ValueError("checkpoint must contain a nonnegative next index")
122
+ next_index = start
123
+ for index, item in enumerate(items):
124
+ if index < start:
125
+ continue
126
+ try:
127
+ value = handler(item)
128
+ if inspect.isawaitable(value):
129
+ if inspect.iscoroutine(value):
130
+ value.close()
131
+ raise TypeError("synchronous batch handler returned an awaitable")
132
+ except Exception as exc:
133
+ outcome = _failed(index, item, exc, classify)
134
+ else:
135
+ outcome = Outcome(index, item, "succeeded", value)
136
+ result.outcomes.append(outcome)
137
+ next_index = index + 1
138
+ if len(result.outcomes) % chunk_size == 0:
139
+ if checkpoint is not None:
140
+ checkpoint.save(next_index)
141
+ if on_progress:
142
+ on_progress(len(result.outcomes), next_index)
143
+ if result.outcomes and len(result.outcomes) % chunk_size:
144
+ if checkpoint is not None:
145
+ checkpoint.save(next_index)
146
+ if on_progress:
147
+ on_progress(len(result.outcomes), next_index)
148
+ return result
149
+
150
+
151
+ @overload
152
+ async def aprocess_batches(
153
+ items: Iterable[T],
154
+ handler: Callable[[T], Awaitable[R]],
155
+ *,
156
+ chunk_size: int = 500,
157
+ classify: Callable[[Exception], str] = ...,
158
+ checkpoint: Any = None,
159
+ on_progress: Callable[[int, int], Any] | None = None,
160
+ ) -> BatchResult[T, R]: ...
161
+ @overload
162
+ async def aprocess_batches(
163
+ items: Iterable[T],
164
+ handler: Callable[[T], R],
165
+ *,
166
+ chunk_size: int = 500,
167
+ classify: Callable[[Exception], str] = ...,
168
+ checkpoint: Any = None,
169
+ on_progress: Callable[[int, int], Any] | None = None,
170
+ ) -> BatchResult[T, R]: ...
171
+ async def aprocess_batches(
172
+ items: Iterable[Any],
173
+ handler: Callable[[Any], Any],
174
+ *,
175
+ chunk_size: int = 500,
176
+ classify: Callable[[Exception], str] = lambda exc: "failed",
177
+ checkpoint: Any = None,
178
+ on_progress: Callable[[int, int], Any] | None = None,
179
+ ) -> BatchResult[Any, Any]:
180
+ """Await per-item processing with the same checkpoint and outcome semantics.
181
+
182
+ Synchronous handlers and checkpoint I/O run in threads and are settled before
183
+ cancellation exits, so an enclosing lease is not released while they still write.
184
+ Configure client-level I/O timeouts for synchronous work. Cancellation is not classified as an
185
+ item failure, and the uncheckpointed chunk may be replayed on restart.
186
+ """
187
+ import asyncio
188
+
189
+ if isinstance(chunk_size, bool) or not isinstance(chunk_size, int) or chunk_size < 1:
190
+ raise ValueError("chunk_size must be a positive integer")
191
+ start = await asyncio.to_thread(checkpoint.load) if checkpoint is not None else 0
192
+ if isinstance(start, bool) or not isinstance(start, int) or start < 0:
193
+ raise ValueError("checkpoint must contain a nonnegative next index")
194
+ result: BatchResult[Any, Any] = BatchResult()
195
+
196
+ async def progress(next_index: int) -> None:
197
+ if checkpoint is not None:
198
+ await offload_settled(checkpoint.save, next_index)
199
+ if on_progress:
200
+ if _core.is_async(on_progress):
201
+ value = on_progress(len(result.outcomes), next_index)
202
+ else:
203
+ value = await asyncio.to_thread(on_progress, len(result.outcomes), next_index)
204
+ if inspect.isawaitable(value):
205
+ await value
206
+
207
+ next_index = start
208
+ for index, item in enumerate(items):
209
+ if index < start:
210
+ continue
211
+ try:
212
+ value = (
213
+ handler(item) if _core.is_async(handler) else await offload_settled(handler, item)
214
+ )
215
+ if inspect.isawaitable(value):
216
+ value = await value
217
+ except Exception as exc:
218
+ outcome = _failed(index, item, exc, classify)
219
+ else:
220
+ outcome = Outcome(index, item, "succeeded", value)
221
+ result.outcomes.append(outcome)
222
+ next_index = index + 1
223
+ if len(result.outcomes) % chunk_size == 0:
224
+ await progress(next_index)
225
+ if result.outcomes and len(result.outcomes) % chunk_size:
226
+ await progress(next_index)
227
+ return result
@@ -0,0 +1,62 @@
1
+ """Carry the request id and the remaining deadline across process boundaries.
2
+
3
+ One header pair, configurable with `set_headers`: ``X-Request-ID`` and
4
+ ``X-Request-Deadline`` (remaining milliseconds). Inbound web middleware reads them
5
+ (`trust_deadline_header=True`), `python_wrap.http` sends them (`propagate=True`) and the
6
+ Celery integration copies them into task headers. Trace context is out of scope: leave
7
+ it to the OpenTelemetry instrumentations.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from typing import Any
14
+
15
+ from python_wrap.deadline import remaining
16
+ from python_wrap.logs import current_log_context
17
+
18
+ __all__ = ["deadline_budget", "outgoing_headers", "set_headers"]
19
+
20
+ _names = {"request_id": "X-Request-ID", "deadline": "X-Request-Deadline"}
21
+
22
+
23
+ def set_headers(*, request_id: str | None = None, deadline: str | None = None) -> None:
24
+ """Rename the request-id and/or deadline header for this process."""
25
+ if request_id:
26
+ _names["request_id"] = request_id
27
+ if deadline:
28
+ _names["deadline"] = deadline
29
+
30
+
31
+ def header_names() -> tuple[str, str]:
32
+ """The ``(request_id, deadline)`` header names in force."""
33
+ return _names["request_id"], _names["deadline"]
34
+
35
+
36
+ def outgoing_headers() -> dict[str, str]:
37
+ """Headers for an outgoing call: the bound request id and the remaining deadline in ms."""
38
+ headers: dict[str, str] = {}
39
+ request_id = current_log_context().get("request_id")
40
+ if request_id:
41
+ headers[_names["request_id"]] = str(request_id)
42
+ left = remaining()
43
+ if left is not None:
44
+ headers[_names["deadline"]] = str(math.floor(left * 1000))
45
+ return headers
46
+
47
+
48
+ def deadline_budget(header: Any, budget: float | None, *, trust: bool) -> float | None:
49
+ """The budget for an inbound request: the smaller of ``budget`` and the header, if trusted.
50
+
51
+ ``header`` holds the remaining milliseconds; a missing, unparseable or negative value
52
+ is ignored, so a client can shorten the budget but never extend it.
53
+ """
54
+ if not trust or header is None:
55
+ return budget
56
+ try:
57
+ value = float(header) / 1000
58
+ except (TypeError, ValueError):
59
+ return budget
60
+ if not math.isfinite(value) or value < 0:
61
+ return budget
62
+ return value if budget is None else min(budget, value)