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,874 @@
1
+ """`timeout`, cancellation tokens and the worker pool behind thread timeouts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextvars
7
+ import functools
8
+ import os
9
+ import queue
10
+ import signal
11
+ import sys
12
+ import threading
13
+ import time
14
+ import warnings
15
+ from collections.abc import Awaitable, Callable
16
+ from types import FrameType, TracebackType
17
+ from typing import (
18
+ Any,
19
+ ParamSpec,
20
+ TypeVar,
21
+ cast,
22
+ )
23
+
24
+ from python_wrap import _core
25
+ from python_wrap import deadline as _deadline
26
+ from python_wrap._core import F, P, R
27
+ from python_wrap.errors import TimeoutExpired
28
+
29
+ T = TypeVar("T")
30
+ R_co = TypeVar("R_co", covariant=True)
31
+ P2 = ParamSpec("P2")
32
+ S = TypeVar("S")
33
+
34
+ _HAS_SETITIMER = hasattr(signal, "setitimer") and hasattr(signal, "SIGALRM")
35
+ _BLOCK = "<block>" # the "function" name used in messages and events for `with timeout()`
36
+
37
+
38
+ def _signals_usable() -> bool:
39
+ return _HAS_SETITIMER and threading.current_thread() is threading.main_thread()
40
+
41
+
42
+ def _timeout_message(label: str, seconds: float) -> str:
43
+ return f"{label} did not finish within {seconds:g}s"
44
+
45
+
46
+ def _expired(label: str, seconds: float) -> TimeoutExpired:
47
+ """Build the error for an expiry and emit ``timeout.expired``."""
48
+ _core.emit("timeout.expired", label, seconds=seconds)
49
+ return TimeoutExpired(_timeout_message(label, seconds), seconds=seconds)
50
+
51
+
52
+ class SignalTimerConflictWarning(RuntimeWarning):
53
+ """`timeout` is about to take over ``SIGALRM`` that something else already uses.
54
+
55
+ Signal timers are process-wide: a non-default ``SIGALRM`` handler or an armed
56
+ ``ITIMER_REAL`` timer belongs to other code (a profiler, a watchdog, another
57
+ library). `timeout` restores both afterwards, but while it runs the other code's
58
+ alarm may be delayed or fire into the timeout's handler. Pass ``use_signals=False`` to
59
+ use the worker-thread fallback, or silence it with `warnings.filterwarnings`.
60
+ """
61
+
62
+
63
+ class CancelToken:
64
+ """A flag a sync function can poll to learn that its `timeout` has fired.
65
+
66
+ `timeout` cannot stop a sync function off the main thread (or where ``SIGALRM`` is
67
+ missing): the caller gets `TimeoutExpired` but the function keeps running. Inside a
68
+ `timeout`-wrapped sync function the current token is cancelled when the limit is hit,
69
+ so the function can stop itself at safe points with `checkpoint` or `cancel_requested`.
70
+ A token also reports cancelled when the token of an enclosing `timeout` is.
71
+
72
+ Attributes:
73
+ cancelled: True once `cancel` was called (on this token or an enclosing one).
74
+
75
+ Example:
76
+ ```python
77
+ from python_wrap import checkpoint, timeout
78
+
79
+ @timeout(5)
80
+ def import_rows(rows: list[int]) -> int:
81
+ done = 0
82
+ for _ in rows:
83
+ checkpoint() # raises TimeoutExpired once the 5 s are over
84
+ done += 1
85
+ return done
86
+ ```
87
+ """
88
+
89
+ __slots__ = ("_event", "_parent", "label", "seconds")
90
+
91
+ def __init__(
92
+ self, label: str = "", seconds: float = 0.0, parent: CancelToken | None = None
93
+ ) -> None:
94
+ self.label = label
95
+ self.seconds = seconds
96
+ self._parent = parent
97
+ self._event = threading.Event()
98
+
99
+ def cancel(self) -> None:
100
+ """Mark the token cancelled (what `timeout` does when its limit is hit)."""
101
+ self._event.set()
102
+
103
+ @property
104
+ def cancelled(self) -> bool:
105
+ token: CancelToken | None = self
106
+ while token is not None:
107
+ if token._event.is_set():
108
+ return True
109
+ token = token._parent
110
+ return False
111
+
112
+ def wait(self, timeout: float | None = None) -> bool:
113
+ """Sleep up to ``timeout`` seconds, waking early when cancelled; True if cancelled.
114
+
115
+ Only this token's own cancellation wakes the sleep early; an enclosing token's
116
+ cancellation is seen after the sleep.
117
+ """
118
+ self._event.wait(timeout)
119
+ return self.cancelled
120
+
121
+ def raise_if_cancelled(self) -> None:
122
+ """Raise `TimeoutExpired` if the token is cancelled."""
123
+ token: CancelToken | None = self
124
+ while token is not None:
125
+ if token._event.is_set():
126
+ raise TimeoutExpired(
127
+ _timeout_message(token.label or _BLOCK, token.seconds), seconds=token.seconds
128
+ )
129
+ token = token._parent
130
+
131
+ def __repr__(self) -> str:
132
+ return f"CancelToken(cancelled={self.cancelled!r})"
133
+
134
+
135
+ _current_token: contextvars.ContextVar[CancelToken | None] = contextvars.ContextVar(
136
+ "python_wrap_cancel_token", default=None
137
+ )
138
+
139
+
140
+ def current_token() -> CancelToken | None:
141
+ """The `CancelToken` of the innermost sync `timeout` running here, or None."""
142
+ return _current_token.get()
143
+
144
+
145
+ def cancel_requested() -> bool:
146
+ """True if the enclosing sync `timeout` has fired (False outside any `timeout`).
147
+
148
+ Poll it in long loops of a sync function to stop work that `timeout` cannot
149
+ interrupt (worker-thread fallback, Windows). The worker-thread fallback copies the
150
+ caller's context, so the token is visible there.
151
+ """
152
+ token = _current_token.get()
153
+ return token is not None and token.cancelled
154
+
155
+
156
+ def checkpoint() -> None:
157
+ """Raise `TimeoutExpired` if the enclosing sync `timeout` has fired; else do nothing.
158
+
159
+ A cooperative stop point: call it between units of work so the function ends soon
160
+ after the limit instead of running on in the background.
161
+ """
162
+ token = _current_token.get()
163
+ if token is not None:
164
+ token.raise_if_cancelled()
165
+
166
+
167
+ def _foreign_alarm(previous_handler: Any, previous_delay: float) -> str | None:
168
+ """Describe a ``SIGALRM`` user other than python-wrap, or None if there is none."""
169
+ if getattr(previous_handler, "__python_wrap_alarm__", False):
170
+ return None
171
+ if previous_handler not in (signal.SIG_DFL, None):
172
+ return f"a SIGALRM handler is already installed ({previous_handler!r})"
173
+ if previous_delay:
174
+ return f"an ITIMER_REAL timer is already armed ({previous_delay:g}s left)"
175
+ return None
176
+
177
+
178
+ def foreign_alarm_state() -> str | None:
179
+ """Describe an existing non-default ``SIGALRM`` handler or armed timer, if any.
180
+
181
+ Used by `doctor` (PW010) and by `timeout` before it installs its own handler.
182
+ Returns None where signals are unavailable or nothing foreign is in place.
183
+ """
184
+ if not _HAS_SETITIMER:
185
+ return None
186
+ try:
187
+ handler = signal.getsignal(signal.SIGALRM)
188
+ delay = signal.getitimer(signal.ITIMER_REAL)[0]
189
+ except (ValueError, OSError): # pragma: no cover - platform quirk
190
+ return None
191
+ return _foreign_alarm(handler, delay)
192
+
193
+
194
+ class _Alarm:
195
+ """One SIGALRM/``setitimer`` deadline, cooperating with enclosing ones.
196
+
197
+ Enter it in the main thread only. The previous handler and any armed timer are
198
+ restored on exit; an enclosing timer whose deadline comes first still fires.
199
+ Entering costs two system calls (install the handler, arm the timer — arming also
200
+ reports the enclosing timer, so no separate ``getitimer``) and so does exiting.
201
+ """
202
+
203
+ def __init__(self, label: str, seconds: float) -> None:
204
+ self.label = label
205
+ self.seconds = seconds
206
+ self.error: TimeoutExpired | None = None # built only when the alarm fires
207
+ self.token = CancelToken(label, seconds, _current_token.get())
208
+ self._token_reset: contextvars.Token[CancelToken | None] | None = None
209
+ self._outer_fired = False
210
+ # The enclosing timer's delay; None until known (our timer is not armed yet).
211
+ self._previous_delay: float | None = None
212
+ self._previous_interval = 0.0
213
+
214
+ def __enter__(self) -> None:
215
+ # The itimer counts real time, so the deadline arithmetic does too (a fake clock
216
+ # installed by tests must not move it).
217
+ self._start = time.monotonic()
218
+ deadline = self._start + self.seconds
219
+ self._previous_handler = previous_handler = signal.getsignal(signal.SIGALRM)
220
+
221
+ def handler(signum: int, frame: FrameType | None) -> None:
222
+ previous_delay = self._previous_delay
223
+ if previous_delay is not None and (
224
+ not previous_delay or time.monotonic() >= deadline - 1e-3
225
+ ):
226
+ self.token.cancel()
227
+ self.error = TimeoutExpired(
228
+ _timeout_message(self.label, self.seconds), seconds=self.seconds
229
+ )
230
+ raise self.error
231
+ # The alarm belongs to an enclosing timeout whose deadline comes first (or
232
+ # fired before ours was even armed).
233
+ self._outer_fired = True
234
+ signal.signal(signal.SIGALRM, previous_handler)
235
+ if callable(previous_handler):
236
+ previous_handler(signum, frame)
237
+
238
+ handler.__python_wrap_alarm__ = True # type: ignore[attr-defined]
239
+ signal.signal(signal.SIGALRM, handler)
240
+ previous_delay, self._previous_interval = signal.setitimer(signal.ITIMER_REAL, self.seconds)
241
+ self._token_reset = _current_token.set(self.token)
242
+ foreign = _foreign_alarm(previous_handler, previous_delay)
243
+ if foreign is not None:
244
+ warnings.warn(
245
+ f"timeout({self.seconds:g}s) for {self.label} takes over SIGALRM but {foreign}; "
246
+ "signal timers are process-wide, so the other alarm may be delayed or "
247
+ "misrouted while this runs (use_signals=False avoids signals)",
248
+ SignalTimerConflictWarning,
249
+ stacklevel=3,
250
+ )
251
+ if previous_delay and previous_delay < self.seconds:
252
+ # An enclosing timer is due first: keep its deadline.
253
+ signal.setitimer(signal.ITIMER_REAL, previous_delay)
254
+ self._previous_delay = previous_delay
255
+
256
+ def __exit__(
257
+ self,
258
+ exc_type: type[BaseException] | None,
259
+ exc: BaseException | None,
260
+ tb: TracebackType | None,
261
+ ) -> None:
262
+ signal.setitimer(signal.ITIMER_REAL, 0)
263
+ if self._token_reset is not None:
264
+ _current_token.reset(self._token_reset)
265
+ self._token_reset = None
266
+ if not self._outer_fired:
267
+ signal.signal(signal.SIGALRM, self._previous_handler)
268
+ if self._previous_delay:
269
+ remaining = self._previous_delay - (time.monotonic() - self._start)
270
+ # Re-arm the enclosing timer; if its deadline already passed, fire ASAP.
271
+ signal.setitimer(signal.ITIMER_REAL, max(remaining, 1e-6), self._previous_interval)
272
+ if exc is not None and exc is self.error:
273
+ _core.emit("timeout.expired", self.label, seconds=self.seconds)
274
+
275
+
276
+ # -- thread fallback: a small pool of idle daemon workers ---------------------------------
277
+
278
+ _WORKER_IDLE_SECONDS = 5.0 # an idle worker exits after this long (real time)
279
+ _MAX_IDLE_WORKERS = 8 # idle workers kept for reuse; extra ones exit when done
280
+
281
+
282
+ class _Job:
283
+ """One call handed to a worker; ``done`` is released when it has finished."""
284
+
285
+ __slots__ = (
286
+ "abandoned",
287
+ "args",
288
+ "context",
289
+ "done",
290
+ "error",
291
+ "finished",
292
+ "func",
293
+ "kwargs",
294
+ "result",
295
+ )
296
+
297
+ def __init__(self, func: Callable[..., Any], args: Any, kwargs: Any) -> None:
298
+ self.func = func
299
+ self.args = args
300
+ self.kwargs = kwargs
301
+ self.context = contextvars.copy_context() # per call, as with a fresh thread
302
+ self.done = threading.Lock()
303
+ self.done.acquire()
304
+ self.result: Any = None
305
+ self.error: BaseException | None = None
306
+ self.abandoned = False # the caller timed out and stopped waiting
307
+ self.finished = 0.0 # `time.monotonic()` when the call returned (real time)
308
+
309
+ def run(self) -> None:
310
+ try:
311
+ self.result = self.context.run(self.func, *self.args, **self.kwargs)
312
+ except BaseException as exc:
313
+ self.error = exc
314
+ self.func = self.args = self.kwargs = None # type: ignore[assignment]
315
+ self.finished = time.monotonic()
316
+ self.done.release()
317
+
318
+
319
+ class _WorkerPool:
320
+ """Reusable daemon threads for the `timeout` thread fallback.
321
+
322
+ A finished worker goes back to the idle list (up to ``_MAX_IDLE_WORKERS``); a worker
323
+ whose call timed out is abandoned — it exits when that call eventually returns and
324
+ is never reused. An idle worker exits after ``_WORKER_IDLE_SECONDS`` without work.
325
+ """
326
+
327
+ def __init__(self) -> None:
328
+ self.lock = threading.Lock()
329
+ self.idle: list[queue.SimpleQueue[_Job]] = [] # inboxes of idle workers (LIFO)
330
+ self.count = 0
331
+
332
+ def submit(self, job: _Job) -> None:
333
+ with self.lock:
334
+ inbox = self.idle.pop() if self.idle else None
335
+ if inbox is None:
336
+ self.count += 1
337
+ number = self.count
338
+ if inbox is not None:
339
+ inbox.put(job)
340
+ return
341
+ inbox = queue.SimpleQueue()
342
+ inbox.put(job)
343
+ threading.Thread(
344
+ target=self._work, args=(inbox,), name=f"timeout-worker-{number}", daemon=True
345
+ ).start()
346
+
347
+ def _work(self, inbox: queue.SimpleQueue[_Job]) -> None:
348
+ while True:
349
+ try:
350
+ job = inbox.get(timeout=_WORKER_IDLE_SECONDS)
351
+ except queue.Empty:
352
+ with self.lock:
353
+ if inbox in self.idle:
354
+ self.idle.remove(inbox)
355
+ return
356
+ continue # claimed just as we gave up waiting: the job is on its way
357
+ job.run()
358
+ with self.lock:
359
+ if job.abandoned or len(self.idle) >= _MAX_IDLE_WORKERS:
360
+ return
361
+ self.idle.append(inbox)
362
+ del job
363
+
364
+ def abandon(self, job: _Job) -> None:
365
+ with self.lock:
366
+ job.abandoned = True
367
+
368
+ def reset(self) -> None:
369
+ """After `os.fork`: the parent's workers do not exist in the child."""
370
+ self.lock = threading.Lock()
371
+ self.idle = []
372
+
373
+
374
+ _workers = _WorkerPool()
375
+ if hasattr(os, "register_at_fork"): # pragma: no branch - absent on Windows only
376
+ os.register_at_fork(after_in_child=_workers.reset)
377
+
378
+
379
+ def _call_in_worker(
380
+ func: Callable[P, R], label: str, seconds: float, *args: P.args, **kwargs: P.kwargs
381
+ ) -> R:
382
+ """Run ``func`` in a pooled daemon thread and stop waiting for it after ``seconds``."""
383
+ token = CancelToken(label, seconds, _current_token.get())
384
+ reset = _current_token.set(token)
385
+ try:
386
+ job = _Job(func, args, kwargs) # copies the context, token included
387
+ finally:
388
+ _current_token.reset(reset)
389
+ # Real time, like the wait itself: a fake clock advanced by sleeps inside the call
390
+ # (e.g. a retry) must not turn a quick call into a late one.
391
+ start = time.monotonic()
392
+ _workers.submit(job)
393
+ if not job.done.acquire(timeout=seconds):
394
+ _workers.abandon(job)
395
+ token.cancel()
396
+ raise _expired(label, seconds) from None
397
+ if job.finished - start > seconds:
398
+ # The wait overslept (seen with free-threaded builds) and the call finished
399
+ # late: it still ran over its limit.
400
+ raise _expired(label, seconds) from None
401
+ error = job.error
402
+ if error is not None:
403
+ job.error = None
404
+ try:
405
+ raise error
406
+ finally:
407
+ del error
408
+ return cast(R, job.result)
409
+
410
+
411
+ # Message of the cancellations a timer sends itself. Python 3.10 has no
412
+ # ``Task.cancelling()`` counter, so there the message is how a timer tells its own
413
+ # cancellation apart from one sent by someone else (best effort: two cancellations that
414
+ # arrive before the task resumes are delivered as one, as in the 3.10 stdlib).
415
+ _TIMER_CANCEL = "python_wrap.timeout expired"
416
+
417
+
418
+ def _is_timer_cancel(exc: BaseException | None) -> bool:
419
+ """True if ``exc`` is the CancelledError a timer sent (3.10 path only)."""
420
+ return isinstance(exc, asyncio.CancelledError) and exc.args[:1] == (_TIMER_CANCEL,)
421
+
422
+
423
+ if sys.version_info >= (3, 11):
424
+ _async_timer = asyncio.timeout
425
+
426
+ else: # pragma: no cover - exercised by the Python 3.10 CI job
427
+
428
+ class _CancelTimer:
429
+ """`asyncio.timeout` stand-in for 3.10: cancel the task at the deadline.
430
+
431
+ Like `asyncio.timeout`, the cancellation that it caused is turned into a
432
+ ``TimeoutError`` on exit; any other cancellation propagates unchanged.
433
+ """
434
+
435
+ def __init__(self, seconds: float) -> None:
436
+ self._seconds = seconds
437
+ self._fired = False
438
+
439
+ def expired(self) -> bool:
440
+ return self._fired
441
+
442
+ async def __aenter__(self) -> _CancelTimer:
443
+ task = asyncio.current_task()
444
+ if task is None:
445
+ raise RuntimeError("timeout() must be used inside a task")
446
+
447
+ def fire() -> None:
448
+ self._fired = True
449
+ task.cancel(_TIMER_CANCEL)
450
+
451
+ self._handle = asyncio.get_running_loop().call_later(self._seconds, fire)
452
+ return self
453
+
454
+ async def __aexit__(
455
+ self,
456
+ exc_type: type[BaseException] | None,
457
+ exc: BaseException | None,
458
+ tb: TracebackType | None,
459
+ ) -> None:
460
+ self._handle.cancel()
461
+ if self._fired and _is_timer_cancel(exc):
462
+ raise TimeoutError from exc
463
+
464
+ _async_timer = _CancelTimer
465
+
466
+
467
+ class _GraceTimer:
468
+ """Cancel the current task at the deadline, and again after ``grace`` seconds.
469
+
470
+ The first cancellation lets the block run its ``finally`` / ``except CancelledError``
471
+ cleanup; if the cleanup is still awaiting when the grace period ends, a second
472
+ cancellation interrupts it (with a warning). Only cancellations caused by this timer
473
+ are turned into ``TimeoutError``.
474
+ """
475
+
476
+ def __init__(self, seconds: float, grace: float, label: str) -> None:
477
+ self._seconds = seconds
478
+ self._grace = grace
479
+ self._label = label
480
+ self._fired = False
481
+ self._cancels = 0
482
+ self._cancelling = 0
483
+ self._handles: list[asyncio.TimerHandle] = []
484
+
485
+ def expired(self) -> bool:
486
+ return self._fired
487
+
488
+ async def __aenter__(self) -> _GraceTimer:
489
+ task = asyncio.current_task()
490
+ if task is None: # pragma: no cover - asyncio always runs coroutines in a task
491
+ raise RuntimeError("timeout() must be used inside a task")
492
+ loop = asyncio.get_running_loop()
493
+
494
+ def second() -> None:
495
+ self._cancels += 1
496
+ _core.get_logger(None).warning(
497
+ "%s: cleanup still running %ss after the timeout, cancelling it again",
498
+ self._label,
499
+ self._grace,
500
+ )
501
+ task.cancel(_TIMER_CANCEL)
502
+
503
+ def fire() -> None:
504
+ self._fired = True
505
+ self._cancels += 1
506
+ task.cancel(_TIMER_CANCEL)
507
+ self._handles.append(loop.call_later(self._grace, second))
508
+
509
+ self._task = task
510
+ # Like asyncio.timeout: remember the cancel requests already pending on entry, so
511
+ # on exit only the timer's own ones are converted (3.11+).
512
+ cancelling = getattr(task, "cancelling", None)
513
+ self._cancelling = cancelling() if cancelling is not None else 0
514
+ self._handles.append(loop.call_later(self._seconds, fire))
515
+ return self
516
+
517
+ async def __aexit__(
518
+ self,
519
+ exc_type: type[BaseException] | None,
520
+ exc: BaseException | None,
521
+ tb: TracebackType | None,
522
+ ) -> None:
523
+ for handle in self._handles:
524
+ handle.cancel()
525
+ if not self._fired or exc_type is not asyncio.CancelledError:
526
+ return
527
+ uncancel = getattr(self._task, "uncancel", None)
528
+ if uncancel is not None: # 3.11+: withdraw our own requests, then count the rest
529
+ remaining: int = getattr(self._task, "cancelling")() # noqa: B009 - 3.11+ only
530
+ for _ in range(self._cancels):
531
+ if remaining <= self._cancelling:
532
+ break
533
+ remaining = uncancel()
534
+ if remaining <= self._cancelling:
535
+ raise TimeoutError from exc
536
+ elif _is_timer_cancel(exc): # pragma: no cover - exercised by the 3.10 CI job
537
+ raise TimeoutError from exc
538
+
539
+
540
+ async def _await_with_grace(awaitable: Awaitable[T], label: str, seconds: float, grace: float) -> T:
541
+ """Run ``awaitable`` as a child task; on expiry cancel it and wait ``grace`` for cleanup."""
542
+ task = asyncio.ensure_future(awaitable)
543
+ try:
544
+ await asyncio.wait({task}, timeout=seconds)
545
+ except BaseException:
546
+ # Cancelled from outside: cancel the child too, give its cleanup the same grace,
547
+ # then re-raise the caller's cancellation. Never leave its outcome unretrieved.
548
+ task.cancel()
549
+ try:
550
+ await asyncio.wait({task}, timeout=grace)
551
+ finally:
552
+ _consume_when_done(task)
553
+ raise
554
+ if task.done():
555
+ return task.result()
556
+ task.cancel()
557
+ try:
558
+ await asyncio.wait({task}, timeout=grace)
559
+ except BaseException:
560
+ _consume_when_done(task) # cancelled from outside during the grace period
561
+ raise
562
+ if not task.done():
563
+ _core.get_logger(None).warning(
564
+ "%s: still running %ss after the timeout; abandoning it", label, grace
565
+ )
566
+ _consume_when_done(task)
567
+ raise _expired(label, seconds)
568
+
569
+
570
+ def _consume_when_done(task: asyncio.Future[Any]) -> None:
571
+ """Retrieve ``task``'s outcome now if it is done, otherwise once it is."""
572
+ if task.done():
573
+ _consume_result(task)
574
+ else:
575
+ task.add_done_callback(_consume_result)
576
+
577
+
578
+ def _consume_result(task: asyncio.Future[Any]) -> None:
579
+ """Mark an abandoned task's outcome as retrieved so asyncio does not log it."""
580
+ if not task.cancelled():
581
+ task.exception()
582
+
583
+
584
+ async def _await_with_deadline(awaitable: Awaitable[T], label: str, seconds: float) -> T:
585
+ """Await under a timer; convert only *our* expiry to TimeoutExpired."""
586
+ timer = _async_timer(seconds)
587
+ try:
588
+ async with timer:
589
+ return await awaitable
590
+ except TimeoutError as exc:
591
+ if not timer.expired():
592
+ raise # raised by the wrapped function itself: propagate unchanged
593
+ raise _expired(label, seconds) from exc
594
+
595
+
596
+ class Timeout:
597
+ """A time limit usable as a decorator, `with` block or `async with` block.
598
+
599
+ Created by `timeout`; see there for the strategies and caveats. One instance can
600
+ decorate several functions and be entered several times (also concurrently from
601
+ different tasks); every use gets its own timer.
602
+
603
+ Attributes:
604
+ seconds: The configured limit.
605
+ use_signals: The configured sync strategy (`None` means automatic).
606
+ cleanup_grace: Seconds async code may spend cleaning up after the limit (`None`: no
607
+ separate bound).
608
+ """
609
+
610
+ def __init__(
611
+ self,
612
+ seconds: float,
613
+ *,
614
+ use_signals: bool | None = None,
615
+ cleanup_grace: float | None = None,
616
+ ) -> None:
617
+ if seconds <= 0:
618
+ raise ValueError(f"timeout seconds must be positive, got {seconds!r}")
619
+ if cleanup_grace is not None and cleanup_grace < 0:
620
+ raise ValueError(f"cleanup_grace must be >= 0, got {cleanup_grace!r}")
621
+ self.cleanup_grace = cleanup_grace
622
+ if use_signals and not _HAS_SETITIMER:
623
+ raise RuntimeError("use_signals=True needs signal.setitimer, unavailable here")
624
+ self.seconds = seconds
625
+ self.use_signals = use_signals
626
+ self._alarms: list[_Alarm] = []
627
+ self._timers: dict[asyncio.Task[Any], list[Any]] = {}
628
+
629
+ def _limit(self, label: str) -> float:
630
+ """The limit for a call starting now: ``seconds`` clamped to the deadline."""
631
+ left = _deadline.remaining()
632
+ if left is None or left >= self.seconds:
633
+ return self.seconds
634
+ if left <= 0:
635
+ _core.emit("timeout.expired", label, seconds=0.0)
636
+ raise TimeoutExpired(f"{label} not started: the deadline has passed", seconds=0.0)
637
+ return left
638
+
639
+ # -- decorator ----------------------------------------------------------------------
640
+
641
+ def __call__(self, func: F, /) -> F:
642
+ """Apply the limit to every call of ``func`` (sync or ``async def``)."""
643
+ label = _core.qualname(func)
644
+ use_signals = self.use_signals
645
+ grace = self.cleanup_grace
646
+
647
+ if grace is not None and not _core.is_async(func):
648
+ raise TypeError(
649
+ f"timeout(cleanup_grace=...) only supports async def functions; {label} is "
650
+ "synchronous (signals and worker threads cannot give cleanup a bounded grace)"
651
+ )
652
+
653
+ if _core.is_async(func):
654
+
655
+ @functools.wraps(func)
656
+ async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
657
+ seconds = self._limit(label)
658
+ if grace is not None:
659
+ return await _await_with_grace(func(*args, **kwargs), label, seconds, grace)
660
+ return await _await_with_deadline(func(*args, **kwargs), label, seconds)
661
+
662
+ async_wrapper.__python_wrap_layer__ = ("timeout", self) # type: ignore[attr-defined]
663
+ return cast(F, async_wrapper)
664
+
665
+ @functools.wraps(func)
666
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
667
+ if use_signals and not _signals_usable():
668
+ raise RuntimeError(
669
+ "use_signals=True: signal-based timeouts only work in the main thread"
670
+ )
671
+ seconds = self._limit(label)
672
+ if use_signals or (use_signals is None and _signals_usable()):
673
+ with _Alarm(label, seconds):
674
+ return func(*args, **kwargs)
675
+ return _call_in_worker(func, label, seconds, *args, **kwargs)
676
+
677
+ wrapper.__python_wrap_layer__ = ( # type: ignore[attr-defined]
678
+ "timeout",
679
+ {"seconds": self.seconds, "use_signals": self.use_signals, "sync": True},
680
+ )
681
+ return cast(F, wrapper)
682
+
683
+ # -- sync context manager -----------------------------------------------------------
684
+
685
+ def __enter__(self) -> Timeout:
686
+ if self.cleanup_grace is not None:
687
+ raise TypeError("timeout(cleanup_grace=...) is only supported with `async with`")
688
+ if self.use_signals is False or not _signals_usable():
689
+ raise RuntimeError(
690
+ "`with timeout(...)` needs SIGALRM (Unix) and the main thread, because a "
691
+ "block of code cannot be moved to a worker thread; decorate a function "
692
+ "with @timeout instead, or use `async with timeout(...)` in async code"
693
+ )
694
+ alarm = _Alarm(_BLOCK, self._limit(_BLOCK))
695
+ alarm.__enter__()
696
+ self._alarms.append(alarm)
697
+ return self
698
+
699
+ def __exit__(
700
+ self,
701
+ exc_type: type[BaseException] | None,
702
+ exc: BaseException | None,
703
+ tb: TracebackType | None,
704
+ ) -> None:
705
+ self._alarms.pop().__exit__(exc_type, exc, tb)
706
+
707
+ # -- async context manager ----------------------------------------------------------
708
+
709
+ async def __aenter__(self) -> Timeout:
710
+ task = asyncio.current_task()
711
+ if task is None: # pragma: no cover - asyncio always runs coroutines in a task
712
+ raise RuntimeError("`async with timeout(...)` must run inside an asyncio task")
713
+ seconds = self._limit(_BLOCK)
714
+ timer: Any = (
715
+ _async_timer(seconds)
716
+ if self.cleanup_grace is None
717
+ else _GraceTimer(seconds, self.cleanup_grace, _BLOCK)
718
+ )
719
+ await timer.__aenter__()
720
+ self._timers.setdefault(task, []).append((timer, seconds))
721
+ return self
722
+
723
+ async def __aexit__(
724
+ self,
725
+ exc_type: type[BaseException] | None,
726
+ exc: BaseException | None,
727
+ tb: TracebackType | None,
728
+ ) -> None:
729
+ task = asyncio.current_task()
730
+ assert task is not None
731
+ stack = self._timers[task]
732
+ timer, seconds = stack.pop()
733
+ if not stack:
734
+ del self._timers[task]
735
+ try:
736
+ await timer.__aexit__(exc_type, exc, tb)
737
+ except TimeoutError as error:
738
+ if not timer.expired(): # pragma: no cover - only our own expiry is converted
739
+ raise
740
+ raise _expired(_BLOCK, seconds) from error
741
+
742
+ def __repr__(self) -> str:
743
+ return (
744
+ f"Timeout(seconds={self.seconds!r}, use_signals={self.use_signals!r}, "
745
+ f"cleanup_grace={self.cleanup_grace!r})"
746
+ )
747
+
748
+
749
+ def timeout(
750
+ seconds: float, *, use_signals: bool | None = None, cleanup_grace: float | None = None
751
+ ) -> Timeout:
752
+ """Raise `TimeoutExpired` if a call or block runs longer than ``seconds``.
753
+
754
+ ``TimeoutExpired`` subclasses the built-in ``TimeoutError``. The returned `Timeout`
755
+ works three ways:
756
+
757
+ * ``@timeout(5)`` decorates sync and ``async def`` functions.
758
+ * ``async with timeout(5):`` limits a block in async code (`asyncio.timeout` on
759
+ Python 3.11+, a cancellation timer on 3.10).
760
+ * ``with timeout(5):`` limits a block in sync code, with signals only: it needs
761
+ ``signal.setitimer`` (Unix) and the main thread, otherwise entering it raises
762
+ ``RuntimeError`` (a block cannot be moved to a worker thread; decorate a function
763
+ instead).
764
+
765
+ How each kind of code is stopped:
766
+
767
+ * ``async def`` code is cancelled at the deadline. Only the timeout's own expiry is
768
+ turned into ``TimeoutExpired``: a ``TimeoutError`` raised by the wrapped code
769
+ itself propagates unchanged.
770
+ * Sync code, with signals (the default on Unix when called from the main thread):
771
+ a ``SIGALRM`` timer from `signal.setitimer` interrupts the call. The previous
772
+ ``SIGALRM`` handler and any already-armed timer are restored afterwards, so nested
773
+ timeouts work.
774
+ * Sync functions, without signals (Windows, non-main threads, or
775
+ ``use_signals=False``): the call runs in a daemon worker thread and the caller stops
776
+ waiting at the deadline. **This fallback cannot stop the work** — the function keeps
777
+ running in the background until it returns on its own, and its result is discarded.
778
+ Side effects may therefore continue after `TimeoutExpired`. To make the function
779
+ stop itself, poll `cancel_requested()` or call `checkpoint()` (which raises
780
+ `TimeoutExpired`) in long loops: the call's `CancelToken` is cancelled when the
781
+ limit is hit (with signals too, if the code swallowed the exception).
782
+ Workers are pooled daemon threads: an idle one is reused for the next call (at most
783
+ 8 are kept idle, each exits after about 5 s without work), a worker whose call timed
784
+ out is abandoned and never reused, and the caller's ``contextvars`` are copied into
785
+ the worker on every call.
786
+
787
+ Signals are process-wide. If a non-default ``SIGALRM`` handler or an armed
788
+ ``ITIMER_REAL`` timer already exists when the signal strategy starts, a
789
+ `SignalTimerConflictWarning` is emitted (both are restored afterwards); `doctor`
790
+ reports it as PW010.
791
+
792
+ Inside a `python_wrap.deadline.deadline` block the limit is clamped to the time the
793
+ deadline has left; if the deadline has already passed, the call (or block) is not
794
+ started and ``TimeoutExpired`` is raised at once. Every expiry emits the
795
+ ``timeout.expired`` event.
796
+
797
+ Warning:
798
+ With the signal strategy, ``TimeoutExpired`` is raised *inside* the wrapped
799
+ code, at whatever line it is executing when the alarm fires. A broad
800
+ ``except Exception:`` (or ``except TimeoutError:``) in that code catches it like
801
+ any other error; if the code then carries on, the time limit is silently lost and
802
+ the call returns normally. ``TimeoutExpired`` deliberately stays an ``Exception``
803
+ (it subclasses ``TimeoutError``), so re-raise it explicitly in such handlers::
804
+
805
+ except TimeoutExpired:
806
+ raise
807
+ except Exception:
808
+ ...
809
+
810
+ The same applies to context managers that suppress exceptions and to
811
+ ``finally`` blocks that ``return``. ``async def`` code has the analogous
812
+ caveat for code that swallows ``asyncio.CancelledError``.
813
+
814
+ Args:
815
+ seconds: Time limit in seconds; must be positive.
816
+ use_signals: ``True`` forces the signal strategy, ``False`` forces the thread
817
+ fallback (and so rules out ``with timeout(...)``), ``None`` (default) picks
818
+ signals when they are usable.
819
+ cleanup_grace: Async only. Seconds the code may spend in its ``finally`` /
820
+ ``except CancelledError`` cleanup after the limit is hit. As a decorator, the
821
+ call runs as a child task: at the limit it is cancelled and given
822
+ ``cleanup_grace`` more seconds to finish; then ``TimeoutExpired`` is raised
823
+ (even if the cleanup finished), and a task still running is abandoned with a
824
+ warning logged to the package logger (it keeps running until it ends on its own).
825
+ As ``async with timeout(5, cleanup_grace=1)`` the block cannot be moved to
826
+ another task, so after the grace period the cleanup is cancelled a second time
827
+ (with a warning) rather than abandoned; cleanup that suppresses cancellation
828
+ cannot be stopped. Sync functions and ``with`` blocks are not supported and
829
+ raise ``TypeError`` (signals and worker threads cannot bound cleanup).
830
+ ``None`` (default) keeps the plain behaviour. Real time: not affected by the
831
+ test overrides.
832
+
833
+ Returns:
834
+ A `Timeout`: a decorator that preserves the wrapped function's type, and a sync
835
+ and async context manager.
836
+
837
+ Raises:
838
+ ValueError: If ``seconds`` is not positive or ``cleanup_grace`` is negative.
839
+ TypeError: If ``cleanup_grace`` is set and the target is a sync function or a
840
+ plain ``with`` block.
841
+ RuntimeError: If ``use_signals=True`` but ``signal.setitimer`` does not exist on
842
+ this platform (at creation time); if ``use_signals=True`` and the call is not
843
+ made from the main thread (at call time); or on entering ``with`` where
844
+ signals cannot be used.
845
+ TimeoutExpired: From the wrapped call or block, when the time limit is exceeded.
846
+
847
+ Example:
848
+ ```python
849
+ import asyncio
850
+ from python_wrap.concurrency import timeout
851
+ from python_wrap.errors import TimeoutExpired
852
+
853
+ @timeout(5)
854
+ def fetch() -> str:
855
+ return "done"
856
+
857
+ assert fetch() == "done"
858
+
859
+ async def main() -> None:
860
+ try:
861
+ async with timeout(0.01):
862
+ await asyncio.sleep(1)
863
+ except TimeoutExpired as exc:
864
+ assert exc.seconds == 0.01
865
+
866
+ asyncio.run(main())
867
+ ```
868
+ """
869
+ return Timeout(seconds, use_signals=use_signals, cleanup_grace=cleanup_grace)
870
+
871
+
872
+ # ---------------------------------------------------------------------------------------
873
+ # rate_limit
874
+ # ---------------------------------------------------------------------------------------