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/celery.py ADDED
@@ -0,0 +1,528 @@
1
+ """Celery integration: task context, Celery-aware retry countdowns and shared breakers.
2
+
3
+ Imported only when used; Celery itself is never imported at module level.
4
+
5
+ Two layers of retry exist in a Celery app: python-wrap's in-process `retry` (fast, a
6
+ few seconds, inside one task run) and Celery's own task retry (re-queued, minutes,
7
+ survives worker restarts). `retry_countdown` and `retry_task` make the second layer
8
+ follow the same schedule rules (explicit delays, exponential backoff with a cap, and
9
+ the dependency's own ``retry_after`` from `CircuitOpenError`, `RateLimitExceeded` or a
10
+ ``Retry-After`` header). `shared_breaker` builds a breaker whose state is shared by all
11
+ prefork children, which otherwise each keep their own.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import contextvars
17
+ from collections.abc import Sequence
18
+ from typing import Any, NoReturn
19
+
20
+ from python_wrap import _fork
21
+ from python_wrap._integration import scope
22
+
23
+ __all__ = [
24
+ "TaskContext",
25
+ "check_visibility",
26
+ "idempotent_task",
27
+ "install",
28
+ "resilient_task",
29
+ "retry_countdown",
30
+ "retry_task",
31
+ "shared_breaker",
32
+ ]
33
+
34
+
35
+ class TaskContext:
36
+ """Signal subscription handle; close disconnects only this app's handlers."""
37
+
38
+ def __init__(
39
+ self,
40
+ app: Any,
41
+ *,
42
+ use_soft_deadline: bool = True,
43
+ hard_margin: float = 5.0,
44
+ inherit_deadline: bool = False,
45
+ ) -> None:
46
+ import importlib
47
+
48
+ signals = importlib.import_module("celery.signals")
49
+ task_postrun, task_prerun = signals.task_postrun, signals.task_prerun
50
+
51
+ self.app, self.use_soft_deadline = app, use_soft_deadline
52
+ self.hard_margin, self.inherit_deadline = hard_margin, inherit_deadline
53
+ signals.before_task_publish.connect(self._publish, weak=False)
54
+ self.closed = False
55
+ self._active = 0
56
+ self._lock = _fork.ForkSafeLock()
57
+ self._scopes: contextvars.ContextVar[tuple[Any, ...]] = contextvars.ContextVar(
58
+ "python_wrap_task_scopes", default=()
59
+ )
60
+ task_prerun.connect(self._before, weak=False)
61
+ task_postrun.connect(self._after, weak=False)
62
+ _fork.register(self)
63
+
64
+ def _reset_after_fork(self) -> None:
65
+ self._scopes.set(())
66
+ self._active = 0
67
+
68
+ def _publish(self, sender: Any = None, headers: Any = None, **kw: Any) -> None:
69
+ """Copy the request id (and, if enabled, the absolute deadline) into task headers."""
70
+ if headers is None:
71
+ return
72
+ import time
73
+
74
+ from python_wrap.deadline import remaining
75
+ from python_wrap.logs import current_log_context
76
+
77
+ request_id = current_log_context().get("request_id")
78
+ if request_id:
79
+ headers.setdefault("x_request_id", str(request_id))
80
+ left = remaining()
81
+ if self.inherit_deadline and left is not None:
82
+ headers.setdefault("x_deadline_at", time.time() + left)
83
+
84
+ def _before(
85
+ self, sender: Any = None, task_id: str | None = None, task: Any = None, **kw: Any
86
+ ) -> None:
87
+ task = task if task is not None else sender
88
+ if getattr(task, "app", None) is not self.app:
89
+ return
90
+ with self._lock:
91
+ if self.closed:
92
+ return
93
+ self._active += 1
94
+ budget = getattr(task, "soft_time_limit", None) if self.use_soft_deadline else None
95
+ limits = getattr(getattr(task, "request", None), "timelimit", None)
96
+ if self.use_soft_deadline and limits and len(limits) > 1 and limits[1] is not None:
97
+ budget = limits[1]
98
+ if self.use_soft_deadline and budget is None:
99
+ # Only a hard limit: stop cooperatively a little before the worker kills the task.
100
+ hard = (
101
+ limits[0] if limits and limits[0] is not None else getattr(task, "time_limit", None)
102
+ )
103
+ if hard:
104
+ budget = max(hard - self.hard_margin, hard * 0.5)
105
+ request = getattr(task, "request", None)
106
+ fields = {"task_id": task_id, "task_name": getattr(task, "name", None)}
107
+ inherited = getattr(request, "x_request_id", None)
108
+ if inherited:
109
+ from python_wrap._integration import request_id
110
+
111
+ fields["request_id"] = request_id(inherited)
112
+ deadline_at = getattr(request, "x_deadline_at", None)
113
+ if self.inherit_deadline and isinstance(deadline_at, (int, float)):
114
+ import time
115
+
116
+ left = max(deadline_at - time.time(), 0.0)
117
+ budget = left if budget is None else min(budget, left)
118
+ try:
119
+ stack = scope(fields, budget)
120
+ except BaseException:
121
+ with self._lock:
122
+ self._active -= 1
123
+ disconnect = self.closed and self._active == 0
124
+ if disconnect:
125
+ self._disconnect_after()
126
+ raise
127
+ self._scopes.set((*self._scopes.get(), (task_id, stack)))
128
+
129
+ def _after(
130
+ self, sender: Any = None, task: Any = None, task_id: str | None = None, **kw: Any
131
+ ) -> None:
132
+ task = task if task is not None else sender
133
+ if getattr(task, "app", None) is not self.app:
134
+ return
135
+ stacks = self._scopes.get()
136
+ if stacks and stacks[-1][0] == task_id:
137
+ self._scopes.set(stacks[:-1])
138
+ try:
139
+ stacks[-1][1].close()
140
+ finally:
141
+ with self._lock:
142
+ self._active -= 1
143
+ disconnect = self.closed and self._active == 0
144
+ if disconnect:
145
+ self._disconnect_after()
146
+
147
+ def _disconnect_after(self) -> None:
148
+ import importlib
149
+
150
+ importlib.import_module("celery.signals").task_postrun.disconnect(self._after)
151
+
152
+ def close(self) -> None:
153
+ """Refuse future tasks; active task contexts still restore at postrun."""
154
+ with self._lock:
155
+ if self.closed:
156
+ return
157
+ self.closed = True
158
+ disconnect = self._active == 0
159
+ import importlib
160
+
161
+ signals = importlib.import_module("celery.signals")
162
+ signals.task_prerun.disconnect(self._before)
163
+ signals.before_task_publish.disconnect(self._publish)
164
+ if disconnect:
165
+ self._disconnect_after()
166
+
167
+
168
+ def install(
169
+ app: Any,
170
+ *,
171
+ use_soft_deadline: bool = True,
172
+ hard_margin: float = 5.0,
173
+ inherit_deadline: bool = False,
174
+ ) -> TaskContext:
175
+ """Bind task_id/name and a deadline from the task's time limit around task execution.
176
+
177
+ The deadline is the soft time limit; with only a hard limit it is the hard limit minus
178
+ ``hard_margin`` seconds (at least half of it), so cooperative code stops before the
179
+ worker kills the task. Published tasks carry the request id in their headers and the
180
+ worker binds it again, so logs from the web request and the task join. With
181
+ ``inherit_deadline=True`` the publisher's remaining deadline is sent too and the task
182
+ runs under the smaller of it and its time limit (opt in: most tasks should outlive the
183
+ request that queued them).
184
+
185
+ Fork-safe python-wrap components reset through their POSIX hooks automatically;
186
+ this adapter never starts background loops or opens backend connections at import.
187
+ """
188
+ existing = getattr(app, "_python_wrap_context", None)
189
+ if existing is not None and not existing.closed:
190
+ return existing # type: ignore[no-any-return]
191
+ handle = TaskContext(
192
+ app,
193
+ use_soft_deadline=use_soft_deadline,
194
+ hard_margin=hard_margin,
195
+ inherit_deadline=inherit_deadline,
196
+ )
197
+ app._python_wrap_context = handle
198
+ return handle
199
+
200
+
201
+ def retry_countdown(
202
+ task: Any,
203
+ exc: BaseException | None = None,
204
+ *,
205
+ delays: Sequence[float] | None = None,
206
+ delay: float = 5.0,
207
+ backoff: float = 2.0,
208
+ max_delay: float = 600.0,
209
+ jitter: float | str = 0.0,
210
+ respect_retry_after: bool = True,
211
+ ) -> float:
212
+ """Seconds to wait before Celery runs ``task`` again, following python-wrap rules.
213
+
214
+ The retry number comes from ``task.request.retries`` (0 on the first failure). A
215
+ wait requested by the failure itself wins: ``exc.retry_after`` (set by
216
+ `CircuitOpenError` and `RateLimitExceeded`) or a ``Retry-After`` header on
217
+ ``exc.response``, capped at ``max_delay``. Otherwise entry ``n`` of ``delays``
218
+ (repeating the last one), or ``delay * backoff ** n`` capped at ``max_delay``, plus
219
+ up to ``jitter`` random seconds.
220
+
221
+ Args:
222
+ task: A bound Celery task (``bind=True``) or anything with ``request.retries``.
223
+ exc: The exception that caused the retry.
224
+ delays: Explicit schedule, e.g. ``[10, 60, 300]``.
225
+ delay: First wait for the exponential schedule.
226
+ backoff: Multiplier per retry (>= 1).
227
+ max_delay: Upper bound for every wait.
228
+ jitter: Random extra seconds added to scheduled (not server-requested) waits.
229
+ respect_retry_after: Honour a wait carried by the exception.
230
+
231
+ Returns:
232
+ Non-negative seconds, suitable for ``task.retry(countdown=...)``.
233
+
234
+ Raises:
235
+ ValueError: For a negative delay/jitter/max_delay, backoff below 1 or an empty
236
+ ``delays``.
237
+
238
+ Example:
239
+ ```python
240
+ from types import SimpleNamespace
241
+
242
+ from python_wrap import CircuitOpenError
243
+ from python_wrap.celery import retry_countdown
244
+
245
+ task = SimpleNamespace(request=SimpleNamespace(retries=2))
246
+ assert retry_countdown(task, delays=[10, 60, 300]) == 300
247
+ assert retry_countdown(task, CircuitOpenError("open", retry_after=42)) == 42
248
+ ```
249
+ """
250
+ from python_wrap.retry import _compute_delay, _validate, retry_after_header
251
+
252
+ _validate(1, delay, backoff, max_delay, jitter)
253
+ if delays is not None and not delays:
254
+ raise ValueError("delays must not be empty")
255
+ if respect_retry_after and exc is not None:
256
+ hinted = retry_after_header(exc)
257
+ if hinted is not None:
258
+ return min(hinted, max_delay)
259
+ retries = int(getattr(getattr(task, "request", None), "retries", 0) or 0)
260
+ if delays is not None:
261
+ base = float(delays[min(retries, len(delays) - 1)])
262
+ else:
263
+ base = delay * backoff**retries
264
+ return _compute_delay(1, base, 1, max_delay, jitter)
265
+
266
+
267
+ def retry_task(
268
+ task: Any,
269
+ exc: BaseException,
270
+ *,
271
+ max_retries: int | None = None,
272
+ delays: Sequence[float] | None = None,
273
+ delay: float = 5.0,
274
+ backoff: float = 2.0,
275
+ max_delay: float = 600.0,
276
+ jitter: float | str = 0.0,
277
+ respect_retry_after: bool = True,
278
+ ) -> NoReturn:
279
+ """Ask Celery to retry ``task`` later with a `retry_countdown` schedule.
280
+
281
+ Raises whatever ``task.retry`` raises (Celery's ``Retry``, or ``exc`` itself once
282
+ ``max_retries`` is exhausted). Use it inside ``except`` in a bound task, typically
283
+ after an in-process `retry` gave up or a breaker is open::
284
+
285
+ @app.task(bind=True, max_retries=5)
286
+ def sync_orders(self, account_id):
287
+ try:
288
+ return fetch_orders(account_id) # decorated with retry + breaker
289
+ except (ConnectionError, CircuitOpenError) as exc:
290
+ retry_task(self, exc, delays=[30, 120, 600])
291
+
292
+ Args:
293
+ task: The bound Celery task.
294
+ exc: The failure; re-raised by Celery when retries are exhausted.
295
+ max_retries: Overrides the task's ``max_retries`` when given.
296
+ delays: Passed to `retry_countdown`, as are the remaining options.
297
+ delay: See `retry_countdown`.
298
+ backoff: See `retry_countdown`.
299
+ max_delay: See `retry_countdown`.
300
+ jitter: See `retry_countdown`.
301
+ respect_retry_after: See `retry_countdown`.
302
+
303
+ Raises:
304
+ Exception: Always; this function never returns.
305
+ """
306
+ countdown = retry_countdown(
307
+ task,
308
+ exc,
309
+ delays=delays,
310
+ delay=delay,
311
+ backoff=backoff,
312
+ max_delay=max_delay,
313
+ jitter=jitter,
314
+ respect_retry_after=respect_retry_after,
315
+ )
316
+ options: dict[str, Any] = {"exc": exc, "countdown": countdown}
317
+ if max_retries is not None:
318
+ options["max_retries"] = max_retries
319
+ raise task.retry(**options)
320
+
321
+
322
+ def shared_breaker(name: str, backend: Any, **options: Any) -> Any:
323
+ """A `CircuitBreaker` whose state lives in ``backend``, shared by every worker process.
324
+
325
+ Prefork Celery workers (and gunicorn/uvicorn workers) each hold their own in-process
326
+ breaker state, so a dead vendor is probed by every child separately. Give one stable
327
+ ``name`` per dependency and a shared backend: a Redis client (wrapped in
328
+ `RedisBreakerState`), or any object with an ``operate`` method such as
329
+ `RedisBreakerState` or a single-host SQLite state backend.
330
+
331
+ Args:
332
+ name: Stable breaker name, identical in every process (e.g. ``"vendor-a"``).
333
+ backend: A Redis client, or a ready breaker state backend.
334
+ **options: Other `CircuitBreaker` options (failure_threshold, on, ...).
335
+
336
+ Returns:
337
+ A `CircuitBreaker`.
338
+
339
+ Example:
340
+ ```python
341
+ from python_wrap.celery import shared_breaker
342
+
343
+
344
+ class StateBackend: # stands in for RedisBreakerState in this example
345
+ def operate(self, breaker, operation, generation=0, trial=False):
346
+ return {"admitted": 1, "state": "closed", "generation": 0, "trial": 0,
347
+ "wait": 0, "failures": 0, "total_failures": 0,
348
+ "total_successes": 0, "total_rejected": 0, "opened": 0,
349
+ "old": "closed"}
350
+
351
+
352
+ breaker = shared_breaker("vendor-a", StateBackend(), failure_threshold=3)
353
+ assert breaker.name == "vendor-a"
354
+ ```
355
+ """
356
+ from python_wrap.circuit import CircuitBreaker
357
+ from python_wrap.shared import RedisBreakerState
358
+
359
+ if not name:
360
+ raise ValueError("shared breakers need a stable, nonempty name")
361
+ state = backend if hasattr(backend, "operate") else RedisBreakerState(backend)
362
+ return CircuitBreaker(name=name, backend=state, **options)
363
+
364
+
365
+ def _bound(args: tuple[Any, ...], what: str) -> Any:
366
+ if not args or not hasattr(args[0], "request"):
367
+ raise TypeError(f"{what} needs a bound task: use @app.task(bind=True) above it")
368
+ return args[0]
369
+
370
+
371
+ def resilient_task(
372
+ policy: Any = None,
373
+ *,
374
+ requeue_on: tuple[type[BaseException], ...] | None = None,
375
+ delays: Sequence[float] | None = None,
376
+ max_retries: int | None = None,
377
+ requeue_when_limited: bool = True,
378
+ **schedule: Any,
379
+ ) -> Any:
380
+ """Run a bound task body through ``policy`` and re-queue it when the dependency is busy.
381
+
382
+ Place it under ``@app.task(bind=True)``. An open breaker (`CircuitOpenError`), a used-up
383
+ rate limit (`RateLimitExceeded`) or a full bulkhead (`BulkheadFull`) calls `retry_task`
384
+ with the error's own ``retry_after`` as the countdown, so the task waits in the queue
385
+ instead of holding a worker slot. With ``requeue_when_limited`` a limiter that would
386
+ sleep raises instead, so a long wait never keeps a prefork child busy (or outlives the
387
+ broker's visibility timeout).
388
+
389
+ Args:
390
+ policy: A `python_wrap.policy.Policy` (or any decorator) applied to the body.
391
+ requeue_on: Exceptions that re-queue; default the three above.
392
+ delays: Fallback countdown schedule when the error carries no ``retry_after``.
393
+ max_retries: Overrides the task's ``max_retries``.
394
+ requeue_when_limited: Make blocking limiters raise instead of sleeping.
395
+ **schedule: Other `retry_countdown` options (``delay``, ``backoff``, ``max_delay``...).
396
+
397
+ Example:
398
+ ```python
399
+ from python_wrap.celery import resilient_task
400
+
401
+ # @app.task(bind=True, max_retries=8, acks_late=True)
402
+ # @resilient_task(vendor_policy, delays=[30, 120, 600])
403
+ # def sync_orders(self, account_id): ...
404
+ assert callable(resilient_task())
405
+ ```
406
+ """
407
+ from python_wrap import _core
408
+ from python_wrap.errors import BulkheadFull, CircuitOpenError, RateLimitExceeded
409
+
410
+ caught = requeue_on or (CircuitOpenError, RateLimitExceeded, BulkheadFull)
411
+
412
+ def decorate(func: Any) -> Any:
413
+ body = policy(func) if policy is not None else func
414
+
415
+ import functools
416
+
417
+ @functools.wraps(func)
418
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
419
+ task = _bound(args, "resilient_task")
420
+ token = _core.no_block.set(True) if requeue_when_limited else None
421
+ try:
422
+ return body(*args, **kwargs)
423
+ except caught as exc:
424
+ retry_task(task, exc, max_retries=max_retries, delays=delays, **schedule)
425
+ finally:
426
+ if token is not None:
427
+ _core.no_block.reset(token)
428
+
429
+ return wrapper
430
+
431
+ return decorate
432
+
433
+
434
+ def idempotent_task(
435
+ *,
436
+ key: Any = None,
437
+ store: Any = None,
438
+ ttl: float | str = "1d",
439
+ backend: Any = None,
440
+ lease_ttl: float | str = 600,
441
+ requeue_delay: float = 30.0,
442
+ max_retries: int | None = None,
443
+ ) -> Any:
444
+ """Run a bound task once per name and arguments, even when the broker delivers it twice.
445
+
446
+ With late acknowledgement a task is delivered again after a worker dies, and a task that
447
+ outlives the visibility timeout is delivered while it still runs. The result is stored
448
+ under the task name plus its arguments (override with ``key=``): a repeat delivery returns
449
+ the stored result without running the body, and a delivery that arrives while the first
450
+ still runs is re-queued after ``requeue_delay`` seconds instead of run.
451
+
452
+ Use a shared ``store`` (``RedisStore(client, prefix, fail_open=False)``) so every worker
453
+ sees the same results; the default is per process. Same crash gap as `idempotent`: an
454
+ external effect and its recorded result are not one atomic step.
455
+
456
+ Args:
457
+ key: ``str`` or ``callable(task, *args, **kwargs)``; default task name + arguments.
458
+ store: Result store (see `python_wrap.idempotency.idempotent`).
459
+ ttl: How long a result is kept.
460
+ backend: Shared lease backend (derived from a `RedisStore`).
461
+ lease_ttl: Lease held while the body runs (renewed automatically).
462
+ requeue_delay: Countdown for a delivery that finds the task running.
463
+ max_retries: Overrides the task's ``max_retries`` for that re-queue.
464
+ """
465
+ import functools
466
+
467
+ from python_wrap._runtime import stable_digest
468
+ from python_wrap.coordination import AlreadyRunning
469
+ from python_wrap.idempotency import idempotent
470
+
471
+ def derive(task: Any, *args: Any, **kwargs: Any) -> str:
472
+ if isinstance(key, str):
473
+ return key
474
+ if key is not None:
475
+ return str(key(task, *args, **kwargs))
476
+ return f"celery:{task.name}:{stable_digest((args, sorted(kwargs.items())))}"
477
+
478
+ def decorate(func: Any) -> Any:
479
+ once = idempotent(key=derive, ttl=ttl, store=store, backend=backend, lease_ttl=lease_ttl)(
480
+ func
481
+ )
482
+
483
+ @functools.wraps(func)
484
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
485
+ task = _bound(args, "idempotent_task")
486
+ try:
487
+ return once(*args, **kwargs)
488
+ except AlreadyRunning as exc:
489
+ retry_task(task, exc, delays=[requeue_delay], max_retries=max_retries)
490
+
491
+ return wrapper
492
+
493
+ return decorate
494
+
495
+
496
+ def check_visibility(target: Any, visibility_timeout: float) -> tuple[Any, ...]:
497
+ """PW023: blocking waits that can outlive the broker's ``visibility_timeout``.
498
+
499
+ A task that waits in a blocking limiter or a bulkhead queue holds a worker slot; if it
500
+ runs longer than the visibility timeout (Redis/SQS brokers) the broker delivers it again
501
+ while it still runs. Pass a decorated function or policy and the timeout in seconds.
502
+
503
+ Returns:
504
+ A tuple of `python_wrap.doctor.Finding`.
505
+ """
506
+ from python_wrap.doctor import Finding, explain
507
+
508
+ found: list[Finding] = []
509
+ for layer in explain(target).layers:
510
+ s = layer.settings
511
+ reason = None
512
+ if layer.role == "limiter" and s.get("block"):
513
+ reason = "a blocking rate limiter can wait without a bound"
514
+ elif layer.role == "bulkhead" and s.get("timeout") is None and s.get("max_waiting") is None:
515
+ reason = "a bulkhead queue with no timeout can wait without a bound"
516
+ elif layer.role == "retry" and (s.get("max_time") or 0) > visibility_timeout:
517
+ reason = f"retry max_time {s['max_time']:g}s exceeds the visibility timeout"
518
+ if reason:
519
+ found.append(
520
+ Finding(
521
+ "PW023",
522
+ "warning",
523
+ f"{reason}; the broker redelivers a task that runs longer than "
524
+ f"{visibility_timeout:g}s. Use resilient_task(requeue_when_limited=True), "
525
+ "set a bulkhead timeout or lower max_time.",
526
+ )
527
+ )
528
+ return tuple(found)