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/migrate.py ADDED
@@ -0,0 +1,1452 @@
1
+ """Codemod that rewrites tenacity and backoff decorators to ``python_wrap.retry``.
2
+
3
+ Run it as ``python -m python_wrap migrate [--write] [--diff] PATH...``. By default it only
4
+ reports what it would change. It understands the common decorator shapes (``stop_after_*``,
5
+ ``wait_fixed`` / ``wait_exponential`` / ``wait_random`` / ``wait_exponential_jitter``,
6
+ ``retry_if_*``, ``backoff.on_exception`` / ``backoff.on_predicate``) and leaves anything else
7
+ untouched, reporting it with a line and column instead. The output is always checked with
8
+ `ast.parse`; if a rewrite would produce invalid Python the file is left as it was.
9
+
10
+ The module uses only the standard library and does not import tenacity or backoff.
11
+
12
+ Example:
13
+ >>> from python_wrap.migrate import migrate_source
14
+ >>> result = migrate_source(
15
+ ... "from tenacity import retry, stop_after_attempt, wait_fixed\\n"
16
+ ... "@retry(stop=stop_after_attempt(3), wait=wait_fixed(2))\\n"
17
+ ... "def f(): ...\\n"
18
+ ... )
19
+ >>> print(result.text)
20
+ from python_wrap import retry
21
+ @retry(max_attempts=3, delay=2, backoff=1)
22
+ def f(): ...
23
+ <BLANKLINE>
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import ast
30
+ import dataclasses
31
+ import difflib
32
+ import re
33
+ import sys
34
+ import tokenize
35
+ from collections.abc import Callable, Sequence
36
+ from dataclasses import dataclass, field
37
+ from pathlib import Path
38
+
39
+ __all__ = ["Change", "MigrationResult", "Unsupported", "main", "migrate_source"]
40
+
41
+ _SKIP_DIRS = {".venv", "venv", ".git", "__pycache__", ".tox", ".mypy_cache", "node_modules"}
42
+ _LINE_LIMIT = 100
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Change:
47
+ """One decorator that was rewritten.
48
+
49
+ Attributes:
50
+ line: 1-based line of the decorator.
51
+ col: 0-based column of the decorator expression.
52
+ before: The original decorator source.
53
+ after: The replacement decorator source.
54
+ notes: Behaviour differences the author should review.
55
+ kind: ``"decorator"`` for a tenacity/backoff decorator, ``"loop"`` for a hand-rolled
56
+ LLM retry loop replaced by ``@llm_retry``.
57
+ """
58
+
59
+ line: int
60
+ col: int
61
+ before: str
62
+ after: str
63
+ notes: tuple[str, ...] = ()
64
+ kind: str = "decorator"
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class Unsupported:
69
+ """A construct the tool did not rewrite.
70
+
71
+ Attributes:
72
+ line: 1-based line.
73
+ col: 0-based column.
74
+ message: What was not understood and what to do about it.
75
+ """
76
+
77
+ line: int
78
+ col: int
79
+ message: str
80
+
81
+
82
+ @dataclass
83
+ class MigrationResult:
84
+ """Outcome of `migrate_source`.
85
+
86
+ Attributes:
87
+ text: The new source (identical to the input when nothing changed).
88
+ changes: Rewritten decorators, in source order.
89
+ unsupported: Findings left for manual migration, in source order.
90
+ """
91
+
92
+ text: str
93
+ changes: list[Change] = field(default_factory=list)
94
+ unsupported: list[Unsupported] = field(default_factory=list)
95
+
96
+
97
+ class _Skip(Exception):
98
+ """Raised while translating one decorator that cannot be migrated."""
99
+
100
+
101
+ # ---------------------------------------------------------------------------- source helpers
102
+
103
+
104
+ def _split_lines(text: str) -> list[str]:
105
+ return re.findall(r"[^\r\n]*(?:\r\n|\r|\n)|[^\r\n]+", text)
106
+
107
+
108
+ class _Source:
109
+ """Maps ``ast`` (line, utf-8 byte column) positions to string offsets."""
110
+
111
+ def __init__(self, text: str) -> None:
112
+ self.text = text
113
+ self.lines = _split_lines(text)
114
+ self.starts: list[int] = []
115
+ pos = 0
116
+ for line in self.lines:
117
+ self.starts.append(pos)
118
+ pos += len(line)
119
+
120
+ def offset(self, lineno: int, col: int) -> int:
121
+ line = self.lines[lineno - 1]
122
+ return self.starts[lineno - 1] + len(line.encode("utf-8")[:col].decode("utf-8", "ignore"))
123
+
124
+ def span(self, node: ast.AST) -> tuple[int, int]:
125
+ lineno, col = node.lineno, node.col_offset # type: ignore[attr-defined]
126
+ end_lineno, end_col = node.end_lineno, node.end_col_offset # type: ignore[attr-defined]
127
+ return self.offset(lineno, col), self.offset(end_lineno, end_col)
128
+
129
+ def segment(self, node: ast.AST) -> str:
130
+ start, end = self.span(node)
131
+ return self.text[start:end]
132
+
133
+ def indent(self, lineno: int) -> str:
134
+ line = self.lines[lineno - 1]
135
+ return line[: len(line) - len(line.lstrip(" \t"))]
136
+
137
+
138
+ # ---------------------------------------------------------------------------- name resolution
139
+
140
+
141
+ class _Names:
142
+ """Resolve names/attributes to canonical ``tenacity.x`` / ``backoff.x`` strings."""
143
+
144
+ def __init__(self, tree: ast.Module) -> None:
145
+ self.aliases: dict[str, str] = {}
146
+ self.imports: list[ast.stmt] = []
147
+ self.star: list[ast.ImportFrom] = []
148
+ for stmt in tree.body:
149
+ if isinstance(stmt, ast.Import):
150
+ hit = False
151
+ for alias in stmt.names:
152
+ root = alias.name.split(".")[0]
153
+ if root in ("tenacity", "backoff"):
154
+ hit = True
155
+ if alias.asname:
156
+ self.aliases[alias.asname] = alias.name
157
+ else:
158
+ self.aliases[root] = root
159
+ if hit:
160
+ self.imports.append(stmt)
161
+ elif (
162
+ isinstance(stmt, ast.ImportFrom)
163
+ and stmt.level == 0
164
+ and stmt.module
165
+ and stmt.module.split(".")[0] in ("tenacity", "backoff")
166
+ ):
167
+ self.imports.append(stmt)
168
+ for alias in stmt.names:
169
+ if alias.name == "*":
170
+ self.star.append(stmt)
171
+ else:
172
+ self.aliases[alias.asname or alias.name] = f"{stmt.module}.{alias.name}"
173
+
174
+ def resolve(self, node: ast.expr) -> str | None:
175
+ if isinstance(node, ast.Name):
176
+ return self.aliases.get(node.id)
177
+ if isinstance(node, ast.Attribute):
178
+ base = self.resolve(node.value)
179
+ return None if base is None else f"{base}.{node.attr}"
180
+ return None
181
+
182
+ def leaf(self, node: ast.expr) -> str | None:
183
+ """The last component (``stop_after_attempt``) of a resolved name, or None."""
184
+ full = self.resolve(node)
185
+ return None if full is None else full.rsplit(".", 1)[-1]
186
+
187
+ def library(self, node: ast.expr) -> str | None:
188
+ full = self.resolve(node)
189
+ return None if full is None else full.split(".")[0]
190
+
191
+
192
+ # ---------------------------------------------------------------------------- value helpers
193
+
194
+
195
+ def _number(node: ast.expr | None) -> int | float | None:
196
+ if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
197
+ return None if isinstance(node.value, bool) else node.value
198
+ if (
199
+ isinstance(node, ast.UnaryOp)
200
+ and isinstance(node.op, ast.USub)
201
+ and isinstance(node.operand, ast.Constant)
202
+ and isinstance(node.operand.value, (int, float))
203
+ and not isinstance(node.operand.value, bool)
204
+ ):
205
+ return -node.operand.value
206
+ return None
207
+
208
+
209
+ def _fmt(value: int | float) -> str:
210
+ if isinstance(value, float):
211
+ value = round(value, 10)
212
+ if value == int(value) and abs(value) < 1e15:
213
+ return repr(float(value))
214
+ return repr(value)
215
+
216
+
217
+ def _bind(call: ast.Call, params: Sequence[str]) -> dict[str, ast.expr]:
218
+ """Bind positional/keyword args to ``params``; raise _Skip on anything odd."""
219
+ bound: dict[str, ast.expr] = {}
220
+ for i, arg in enumerate(call.args):
221
+ if isinstance(arg, ast.Starred) or i >= len(params):
222
+ raise _Skip("unsupported positional arguments")
223
+ bound[params[i]] = arg
224
+ for kw in call.keywords:
225
+ if kw.arg is None or kw.arg not in params:
226
+ raise _Skip(f"unsupported argument {kw.arg or '**kwargs'!r}")
227
+ if kw.arg in bound:
228
+ raise _Skip(f"argument {kw.arg!r} given twice")
229
+ bound[kw.arg] = kw.value
230
+ return bound
231
+
232
+
233
+ def _flatten(node: ast.expr, op: type[ast.operator]) -> list[ast.expr]:
234
+ if isinstance(node, ast.BinOp) and isinstance(node.op, op):
235
+ return _flatten(node.left, op) + _flatten(node.right, op)
236
+ return [node]
237
+
238
+
239
+ # ---------------------------------------------------------------------------- translation
240
+
241
+
242
+ class _Settings:
243
+ """Keyword arguments for the new ``retry(...)`` plus notes."""
244
+
245
+ ORDER = (
246
+ "on",
247
+ "max_attempts",
248
+ "delay",
249
+ "backoff",
250
+ "max_delay",
251
+ "jitter",
252
+ "max_time",
253
+ "retry_if",
254
+ "retry_if_result",
255
+ )
256
+
257
+ def __init__(self) -> None:
258
+ self.values: dict[str, str] = {}
259
+ self.notes: list[str] = []
260
+
261
+ def set(self, key: str, value: str) -> None:
262
+ if key in self.values:
263
+ raise _Skip(f"{key} would be set twice")
264
+ self.values[key] = value
265
+
266
+ def render(self, name: str, indent: str, col: int) -> str:
267
+ items = [f"{k}={self.values[k]}" for k in self.ORDER if k in self.values]
268
+ one = f"{name}({', '.join(items)})"
269
+ if col + len(one) + 1 <= _LINE_LIMIT and "\n" not in one:
270
+ return one
271
+ inner = indent + " "
272
+ body = "".join(f"{inner}{item},\n" for item in items)
273
+ return f"{name}(\n{body}{indent})"
274
+
275
+
276
+ class _Translator:
277
+ def __init__(self, src: _Source, names: _Names) -> None:
278
+ self.src = src
279
+ self.names = names
280
+
281
+ def text(self, node: ast.expr) -> str:
282
+ seg = self.src.segment(node)
283
+ try:
284
+ ast.parse(seg, mode="eval")
285
+ return seg
286
+ except SyntaxError:
287
+ return ast.unparse(node)
288
+
289
+ def call_of(self, node: ast.expr, library: str) -> tuple[str, ast.Call] | None:
290
+ if isinstance(node, ast.Call) and self.names.library(node.func) == library:
291
+ leaf = self.names.leaf(node.func)
292
+ if leaf:
293
+ return leaf, node
294
+ return None
295
+
296
+ # -- tenacity ------------------------------------------------------------------------
297
+
298
+ def tenacity(self, deco: ast.expr) -> _Settings:
299
+ out = _Settings()
300
+ args: dict[str, ast.expr] = {}
301
+ if isinstance(deco, ast.Call):
302
+ if deco.args:
303
+ raise _Skip("positional arguments to tenacity.retry are not supported")
304
+ args = _bind(
305
+ deco,
306
+ (
307
+ "stop",
308
+ "wait",
309
+ "retry",
310
+ "reraise",
311
+ "before_sleep",
312
+ "before",
313
+ "after",
314
+ "sleep",
315
+ "retry_error_cls",
316
+ "retry_error_callback",
317
+ "statistics",
318
+ ),
319
+ )
320
+ for key in ("before_sleep", "before", "after"):
321
+ if key in args:
322
+ raise _Skip(
323
+ f"{key}= hooks receive tenacity's RetryState; port the callback to "
324
+ "on_retry=(python_wrap.RetryState) or logger=/log_level= by hand"
325
+ )
326
+ for key in ("sleep", "retry_error_cls", "retry_error_callback", "statistics"):
327
+ if key in args:
328
+ raise _Skip(f"{key}= has no direct python_wrap equivalent")
329
+ self._stop(args.get("stop"), out)
330
+ self._wait(args.get("wait"), out)
331
+ self._retry_cond(args.get("retry"), out)
332
+ reraise = args.get("reraise")
333
+ if not (isinstance(reraise, ast.Constant) and reraise.value is True):
334
+ out.notes.append(
335
+ "tenacity raised RetryError when attempts ran out; python_wrap re-raises the "
336
+ "original exception, so update any `except RetryError` handlers"
337
+ )
338
+ return out
339
+
340
+ def _stop(self, node: ast.expr | None, out: _Settings) -> None:
341
+ if node is None:
342
+ out.set("max_attempts", "None")
343
+ out.notes.append("tenacity retries forever by default; max_attempts=None keeps that")
344
+ return
345
+ parts = _flatten(node, ast.BitOr)
346
+ seen: set[str] = set()
347
+ for part in parts:
348
+ found = self.call_of(part, "tenacity") or (
349
+ ("stop_never", None) if self._is_name(part, "stop_never") else None
350
+ )
351
+ if found is None:
352
+ raise _Skip("stop expression not understood")
353
+ leaf, call = found
354
+ if leaf in seen:
355
+ raise _Skip("repeated stop condition")
356
+ seen.add(leaf)
357
+ if leaf == "stop_never":
358
+ out.set("max_attempts", "None")
359
+ elif leaf == "stop_after_attempt" and call is not None:
360
+ bound = _bind(call, ("max_attempt_number",))
361
+ if "max_attempt_number" not in bound:
362
+ raise _Skip("stop_after_attempt needs an argument")
363
+ out.set("max_attempts", self.text(bound["max_attempt_number"]))
364
+ elif leaf == "stop_after_delay" and call is not None:
365
+ bound = _bind(call, ("max_delay",))
366
+ if "max_delay" not in bound:
367
+ raise _Skip("stop_after_delay needs an argument")
368
+ out.set("max_time", self.text(bound["max_delay"]))
369
+ out.notes.append(
370
+ "stop_after_delay becomes max_time: python_wrap stops when the next wait "
371
+ "would pass the budget instead of after the budget has passed"
372
+ )
373
+ else:
374
+ raise _Skip(f"stop condition {leaf} is not supported")
375
+ if "max_attempts" not in out.values:
376
+ out.set("max_attempts", "None")
377
+
378
+ def _is_name(self, node: ast.expr, leaf: str) -> bool:
379
+ return self.names.library(node) == "tenacity" and self.names.leaf(node) == leaf
380
+
381
+ def _wait(self, node: ast.expr | None, out: _Settings) -> None:
382
+ if node is None:
383
+ out.set("delay", "0")
384
+ out.set("backoff", "1")
385
+ return
386
+ base: tuple[str, dict[str, ast.expr]] | None = None
387
+ rand: dict[str, ast.expr] | None = None
388
+ for part in _flatten(node, ast.Add):
389
+ found = self.call_of(part, "tenacity")
390
+ if found is None:
391
+ raise _Skip("wait expression not understood")
392
+ leaf, call = found
393
+ if leaf == "wait_random":
394
+ if rand is not None:
395
+ raise _Skip("two wait_random terms cannot be combined")
396
+ rand = _bind(call, ("min", "max"))
397
+ elif leaf in ("wait_fixed", "wait_none", "wait_exponential", "wait_exponential_jitter"):
398
+ if base is not None:
399
+ raise _Skip("several base wait strategies cannot be combined")
400
+ params = {
401
+ "wait_fixed": ("wait",),
402
+ "wait_none": (),
403
+ "wait_exponential": ("multiplier", "max", "exp_base", "min"),
404
+ "wait_exponential_jitter": ("initial", "max", "exp_base", "jitter"),
405
+ }[leaf]
406
+ base = (leaf, _bind(call, params))
407
+ else:
408
+ raise _Skip(f"wait strategy {leaf} is not supported")
409
+ assert base is not None or rand is not None
410
+ jitter_from_random: str | None = None
411
+ rand_min: ast.expr | None = None
412
+ if rand is not None:
413
+ lo, hi = rand.get("min"), rand.get("max")
414
+ lo_n = 0 if lo is None else _number(lo)
415
+ hi_n = 1 if hi is None else _number(hi)
416
+ if lo_n is not None and hi_n is not None:
417
+ jitter_from_random = _fmt(hi_n - lo_n)
418
+ else:
419
+ hi_t = "1" if hi is None else self.text(hi)
420
+ lo_t = "0" if lo is None else self.text(lo)
421
+ jitter_from_random = f"({hi_t}) - ({lo_t})"
422
+ rand_min = lo
423
+ if base is None:
424
+ assert rand is not None
425
+ out.set("delay", "0" if rand_min is None else self.text(rand_min))
426
+ out.set("backoff", "1")
427
+ out.set("jitter", jitter_from_random or "0")
428
+ return
429
+ leaf, b = base
430
+ if leaf == "wait_none":
431
+ out.set("delay", "0")
432
+ out.set("backoff", "1")
433
+ elif leaf == "wait_fixed":
434
+ if "wait" not in b:
435
+ raise _Skip("wait_fixed needs an argument")
436
+ out.set("delay", self.text(b["wait"]))
437
+ out.set("backoff", "1")
438
+ elif leaf == "wait_exponential":
439
+ mult = b.get("multiplier")
440
+ mult_n = 1 if mult is None else _number(mult)
441
+ min_n = 0 if b.get("min") is None else _number(b.get("min"))
442
+ if b.get("min") is not None and _number(b.get("min")) != 0:
443
+ if mult_n is not None and min_n is not None:
444
+ out.set("delay", _fmt(max(mult_n, min_n)))
445
+ else:
446
+ mult_t = "1" if mult is None else self.text(mult)
447
+ out.set("delay", f"max({mult_t}, {self.text(b['min'])})")
448
+ out.notes.append(
449
+ "wait_exponential(min=...) is approximated: delay=max(multiplier, min) "
450
+ "grows by backoff from there, tenacity clamps every wait to min"
451
+ )
452
+ else:
453
+ out.set("delay", "1" if mult is None else self.text(mult))
454
+ exp_base = b.get("exp_base")
455
+ out.set("backoff", "2" if exp_base is None else self.text(exp_base))
456
+ if b.get("max") is not None:
457
+ out.set("max_delay", self.text(b["max"]))
458
+ else: # wait_exponential_jitter
459
+ if rand is not None:
460
+ raise _Skip("wait_exponential_jitter cannot be combined with wait_random")
461
+ out.set("delay", "1" if b.get("initial") is None else self.text(b["initial"]))
462
+ out.set("backoff", "2" if b.get("exp_base") is None else self.text(b["exp_base"]))
463
+ if b.get("max") is not None:
464
+ out.set("max_delay", self.text(b["max"]))
465
+ out.set("jitter", "1" if b.get("jitter") is None else self.text(b["jitter"]))
466
+ if rand is not None:
467
+ if leaf == "wait_fixed":
468
+ # fixed + random(a, b): delay = s + a, jitter = b - a
469
+ if rand_min is not None and _number(rand_min) != 0:
470
+ fixed = out.values["delay"]
471
+ fx, rn = _number(b["wait"]), _number(rand_min)
472
+ out.values["delay"] = (
473
+ _fmt(fx + rn)
474
+ if fx is not None and rn is not None
475
+ else f"{fixed} + {self.text(rand_min)}"
476
+ )
477
+ elif rand_min is not None and _number(rand_min) != 0:
478
+ raise _Skip("wait_random with a nonzero minimum added to a backoff strategy")
479
+ out.set("jitter", jitter_from_random or "0")
480
+
481
+ def _retry_cond(self, node: ast.expr | None, out: _Settings) -> None:
482
+ if node is None:
483
+ return
484
+ if self._is_name(node, "retry_if_exception_type"):
485
+ return
486
+ parts: list[ast.expr]
487
+ if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.BitOr, ast.BitAnd)):
488
+ parts = _flatten(node, type(node.op))
489
+ kind = "or" if isinstance(node.op, ast.BitOr) else "and"
490
+ else:
491
+ parts, kind = [node], "single"
492
+ seen: dict[str, ast.Call] = {}
493
+ for part in parts:
494
+ found = self.call_of(part, "tenacity")
495
+ if found is None:
496
+ raise _Skip("retry condition not understood")
497
+ leaf, call = found
498
+ if (
499
+ leaf
500
+ not in (
501
+ "retry_if_exception_type",
502
+ "retry_if_result",
503
+ "retry_if_exception",
504
+ )
505
+ or leaf in seen
506
+ ):
507
+ raise _Skip(f"retry condition {leaf} is not supported")
508
+ seen[leaf] = call
509
+ if kind == "or" and set(seen) != {"retry_if_exception_type", "retry_if_result"}:
510
+ raise _Skip("only `retry_if_exception_type(...) | retry_if_result(...)` is supported")
511
+ if kind == "and" and set(seen) != {"retry_if_exception_type", "retry_if_exception"}:
512
+ raise _Skip(
513
+ "only `retry_if_exception_type(...) & retry_if_exception(...)` is supported"
514
+ )
515
+ if "retry_if_exception_type" in seen:
516
+ bound = _bind(seen["retry_if_exception_type"], ("exception_types",))
517
+ if "exception_types" in bound:
518
+ out.set("on", self.text(bound["exception_types"]))
519
+ if "retry_if_exception" in seen:
520
+ bound = _bind(seen["retry_if_exception"], ("predicate",))
521
+ if "predicate" not in bound:
522
+ raise _Skip("retry_if_exception needs a predicate")
523
+ out.set("retry_if", self.text(bound["predicate"]))
524
+ if "retry_if_result" in seen:
525
+ bound = _bind(seen["retry_if_result"], ("predicate",))
526
+ if "predicate" not in bound:
527
+ raise _Skip("retry_if_result needs a predicate")
528
+ out.set("retry_if_result", self.text(bound["predicate"]))
529
+ if kind == "single":
530
+ out.set("on", "()") # tenacity does not retry exceptions in this mode
531
+ if kind == "single" and "retry_if_exception" in seen:
532
+ pass # on= stays the default Exception, same as tenacity's behaviour
533
+ if "retry_if_result" in seen:
534
+ out.notes.append(
535
+ "when attempts run out python_wrap returns the last rejected value; tenacity "
536
+ "raised RetryError"
537
+ )
538
+
539
+ # -- backoff -------------------------------------------------------------------------
540
+
541
+ def backoff(self, deco: ast.expr, leaf: str) -> _Settings:
542
+ out = _Settings()
543
+ if not isinstance(deco, ast.Call):
544
+ raise _Skip(f"backoff.{leaf} needs arguments")
545
+ call = deco
546
+ extra_ok = {"expo": ("factor", "base", "max_value"), "constant": ("interval",)}
547
+ positional = ("wait_gen", "exception") if leaf == "on_exception" else ("wait_gen",)
548
+ wait_gen = call.args[0] if call.args else None
549
+ bound: dict[str, ast.expr] = {}
550
+ wait_kwargs: dict[str, ast.expr] = {}
551
+ known = {
552
+ "wait_gen",
553
+ "exception",
554
+ "predicate",
555
+ "max_tries",
556
+ "max_time",
557
+ "jitter",
558
+ "giveup",
559
+ "on_success",
560
+ "on_backoff",
561
+ "on_giveup",
562
+ "raise_on_giveup",
563
+ "logger",
564
+ "backoff_log_level",
565
+ "giveup_log_level",
566
+ "max_value",
567
+ "factor",
568
+ "base",
569
+ "interval",
570
+ }
571
+ if len(call.args) > len(positional) and leaf == "on_exception":
572
+ raise _Skip("unsupported positional arguments")
573
+ if leaf == "on_predicate" and len(call.args) > 2:
574
+ raise _Skip("unsupported positional arguments")
575
+ names = ("wait_gen", "predicate") if leaf == "on_predicate" else positional
576
+ for i, arg in enumerate(call.args):
577
+ if isinstance(arg, ast.Starred):
578
+ raise _Skip("unsupported positional arguments")
579
+ bound[names[i]] = arg
580
+ for kw in call.keywords:
581
+ if kw.arg is None:
582
+ raise _Skip("**kwargs are not supported")
583
+ if kw.arg not in known:
584
+ raise _Skip(f"wait_gen argument {kw.arg!r} is not supported")
585
+ if kw.arg in ("factor", "base", "max_value", "interval"):
586
+ wait_kwargs[kw.arg] = kw.value
587
+ else:
588
+ bound[kw.arg] = kw.value
589
+ wait_gen = bound.get("wait_gen")
590
+ if wait_gen is None:
591
+ raise _Skip("wait_gen not given")
592
+ gen = self.names.leaf(wait_gen) if self.names.library(wait_gen) == "backoff" else None
593
+ if gen not in extra_ok:
594
+ raise _Skip("only backoff.expo and backoff.constant are supported")
595
+ assert gen is not None
596
+ for k in wait_kwargs:
597
+ if k not in extra_ok[gen]:
598
+ raise _Skip(f"argument {k!r} does not apply to backoff.{gen}")
599
+ for key in ("on_success", "on_backoff", "on_giveup", "giveup"):
600
+ if key in bound:
601
+ raise _Skip(f"{key}= has no direct equivalent; use on_retry= or retry_if= by hand")
602
+ for key in ("backoff_log_level", "giveup_log_level"):
603
+ if key in bound:
604
+ raise _Skip(f"{key}= has no direct equivalent; see log_level= and logger=")
605
+ rg = bound.get("raise_on_giveup")
606
+ if rg is not None and not (isinstance(rg, ast.Constant) and rg.value is True):
607
+ raise _Skip("raise_on_giveup=False has no equivalent; python_wrap always re-raises")
608
+ if leaf == "on_exception":
609
+ if "exception" not in bound:
610
+ raise _Skip("exception argument missing")
611
+ out.set("on", self.text(bound["exception"]))
612
+ else:
613
+ pred = bound.get("predicate")
614
+ out.set("on", "()")
615
+ out.set(
616
+ "retry_if_result", "lambda result: not result" if pred is None else self.text(pred)
617
+ )
618
+ mt = bound.get("max_tries")
619
+ if mt is None or (isinstance(mt, ast.Constant) and mt.value is None):
620
+ out.set("max_attempts", "None")
621
+ elif isinstance(mt, (ast.Lambda, ast.Call)) and not isinstance(mt, ast.Constant):
622
+ raise _Skip("callable max_tries is not supported")
623
+ else:
624
+ out.set("max_attempts", self.text(mt))
625
+ mtm = bound.get("max_time")
626
+ if mtm is not None and not (isinstance(mtm, ast.Constant) and mtm.value is None):
627
+ if isinstance(mtm, (ast.Lambda, ast.Call)):
628
+ raise _Skip("callable max_time is not supported")
629
+ out.set("max_time", self.text(mtm))
630
+ if gen == "expo":
631
+ out.set(
632
+ "delay", "1" if "factor" not in wait_kwargs else self.text(wait_kwargs["factor"])
633
+ )
634
+ out.set("backoff", "2" if "base" not in wait_kwargs else self.text(wait_kwargs["base"]))
635
+ mv = wait_kwargs.get("max_value")
636
+ if mv is not None and not (isinstance(mv, ast.Constant) and mv.value is None):
637
+ out.set("max_delay", self.text(mv))
638
+ else:
639
+ out.set(
640
+ "delay",
641
+ "1" if "interval" not in wait_kwargs else self.text(wait_kwargs["interval"]),
642
+ )
643
+ out.set("backoff", "1")
644
+ jit = bound.get("jitter")
645
+ if jit is None or (
646
+ self.names.library(jit) == "backoff" and self.names.leaf(jit) == "full_jitter"
647
+ ):
648
+ out.notes.append(
649
+ "backoff's default full_jitter randomises the whole wait; python_wrap adds "
650
+ "up to jitter= seconds on top. No jitter was added; set jitter= if you want some"
651
+ )
652
+ elif isinstance(jit, ast.Constant) and jit.value is None:
653
+ pass
654
+ else:
655
+ raise _Skip("custom jitter functions are not supported")
656
+ lg = bound.get("logger")
657
+ if lg is not None:
658
+ out.values["logger"] = self.text(lg)
659
+ return out
660
+
661
+
662
+ # ---------------------------------------------------------------------------- the driver
663
+
664
+
665
+ def _fn_decorators(tree: ast.Module) -> list[ast.expr]:
666
+ found: list[ast.expr] = []
667
+ for node in ast.walk(tree):
668
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
669
+ found.extend(node.decorator_list)
670
+ return found
671
+
672
+
673
+ def _refs(tree: ast.Module, names: _Names, skip: set[int]) -> list[ast.expr]:
674
+ """Remaining references to tenacity/backoff names outside ``skip`` nodes."""
675
+ out: list[ast.expr] = []
676
+
677
+ def visit(node: ast.AST) -> None:
678
+ if id(node) in skip:
679
+ return
680
+ if (
681
+ isinstance(node, (ast.Name, ast.Attribute))
682
+ and isinstance(node.ctx, ast.Load)
683
+ and names.resolve(node) is not None
684
+ ):
685
+ out.append(node)
686
+ return
687
+ for child in ast.iter_child_nodes(node):
688
+ visit(child)
689
+
690
+ for stmt in tree.body:
691
+ if stmt in names.imports:
692
+ continue
693
+ visit(stmt)
694
+ return out
695
+
696
+
697
+ def _module_bindings(tree: ast.Module, names: _Names) -> set[str]:
698
+ bound: set[str] = set()
699
+ for stmt in tree.body:
700
+ if stmt in names.imports:
701
+ continue
702
+ for node in (
703
+ ast.walk(stmt)
704
+ if not isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))
705
+ else [stmt]
706
+ ):
707
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
708
+ bound.add(node.name)
709
+ elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
710
+ bound.add(node.id)
711
+ elif isinstance(node, (ast.Import, ast.ImportFrom)):
712
+ for a in node.names:
713
+ bound.add((a.asname or a.name).split(".")[0])
714
+ return bound
715
+
716
+
717
+ def migrate_source(text: str, filename: str = "<string>") -> MigrationResult:
718
+ """Rewrite tenacity/backoff decorators and LLM retry loops in ``text``.
719
+
720
+ Decorators become ``python_wrap.retry``. Hand-rolled retry loops around LLM client
721
+ calls (``for``/``while`` with try/except and a sleep around ``*.messages.create``,
722
+ ``*.chat.completions.create``, ``*.responses.create`` or ``*.generate_content``) become
723
+ a function decorated with ``llm_retry`` when that is provably safe, and are otherwise
724
+ reported with a suggestion and line numbers. No import of any LLM SDK is needed.
725
+
726
+ Args:
727
+ text: Python source code.
728
+ filename: Used only in parse error messages.
729
+
730
+ Returns:
731
+ A `MigrationResult`. ``text`` equals the input when nothing was rewritten or when
732
+ the input does not parse (reported as an `Unsupported` finding).
733
+
734
+ Example:
735
+ >>> migrate_source("x = 1\\n").text
736
+ 'x = 1\\n'
737
+ """
738
+ result = _migrate_decorators(text, filename)
739
+ if result.unsupported and result.unsupported[0].message.startswith("cannot parse file"):
740
+ return result
741
+ try:
742
+ tree = ast.parse(result.text)
743
+ except SyntaxError: # pragma: no cover - rewrites are checked before they are returned
744
+ return result
745
+ loops = _migrate_loops(result.text, tree)
746
+ if not loops.unsupported and not loops.changes:
747
+ return result
748
+ if result.text != text:
749
+ mapping = _line_map(text, result.text)
750
+
751
+ def shift(n: int) -> int:
752
+ return mapping[min(n, len(mapping) - 1)]
753
+
754
+ else:
755
+
756
+ def shift(n: int) -> int:
757
+ return n
758
+
759
+ result.text = loops.text
760
+ result.changes.extend(dataclasses.replace(c, line=shift(c.line)) for c in loops.changes)
761
+ result.unsupported.extend(dataclasses.replace(u, line=shift(u.line)) for u in loops.unsupported)
762
+ result.changes.sort(key=lambda c: (c.line, c.col))
763
+ result.unsupported.sort(key=lambda u: (u.line, u.col))
764
+ return result
765
+
766
+
767
+ def _migrate_decorators(text: str, filename: str) -> MigrationResult:
768
+ """The tenacity/backoff pass of `migrate_source`."""
769
+ result = MigrationResult(text)
770
+ try:
771
+ tree = ast.parse(text, filename=filename)
772
+ except (SyntaxError, ValueError) as exc:
773
+ line = getattr(exc, "lineno", None) or 1
774
+ col = max((getattr(exc, "offset", None) or 1) - 1, 0)
775
+ result.unsupported.append(Unsupported(line, col, f"cannot parse file: {exc}"))
776
+ return result
777
+ names = _Names(tree)
778
+ if not names.aliases and not names.star:
779
+ return result
780
+ src = _Source(text)
781
+ tr = _Translator(src, names)
782
+ for star in names.star:
783
+ result.unsupported.append(
784
+ Unsupported(star.lineno, star.col_offset, "star import: migrate this file by hand")
785
+ )
786
+
787
+ converted: list[tuple[ast.expr, _Settings]] = []
788
+ skipped_nodes: set[int] = set()
789
+ for deco in _fn_decorators(tree):
790
+ target = deco.func if isinstance(deco, ast.Call) else deco
791
+ lib, leaf = names.library(target), names.leaf(target)
792
+ if lib is None or leaf is None:
793
+ continue
794
+ if (lib, leaf) == ("tenacity", "retry"):
795
+ attempt: Callable[[], _Settings] = lambda d=deco: tr.tenacity(d) # type: ignore[misc] # noqa: E731
796
+ elif lib == "backoff" and leaf in ("on_exception", "on_predicate"):
797
+ attempt = lambda d=deco, k=leaf: tr.backoff(d, k) # type: ignore[misc] # noqa: E731
798
+ else:
799
+ continue
800
+ try:
801
+ converted.append((deco, attempt()))
802
+ except _Skip as why:
803
+ result.unsupported.append(Unsupported(deco.lineno, deco.col_offset, f"{why}"))
804
+ skipped_nodes.update(id(n) for n in ast.walk(deco))
805
+ if not converted:
806
+ _report_leftovers(tree, names, skipped_nodes, result)
807
+ result.unsupported.sort(key=lambda u: (u.line, u.col))
808
+ return result
809
+
810
+ converted_ids: set[int] = set()
811
+ for deco, _ in converted:
812
+ converted_ids.update(id(n) for n in ast.walk(deco))
813
+ # Every reference that survives the rewrite (including inside unsupported decorators)
814
+ # decides which tenacity/backoff imports must stay; only the ones outside unsupported
815
+ # decorators still need a finding of their own.
816
+ alive = _refs(tree, names, converted_ids)
817
+ leftovers = _refs(tree, names, converted_ids | skipped_nodes)
818
+
819
+ # Pick the name the new decorator is called by.
820
+ bound = _module_bindings(tree, names)
821
+ tenacity_retry_alive = any(
822
+ names.library(r) == "tenacity" and names.leaf(r) == "retry" for r in alive
823
+ )
824
+ # a still-used tenacity `retry` import also collides with the new `retry`
825
+ local_retry = [k for k, v in names.aliases.items() if v == "tenacity.retry"]
826
+ clash = "retry" in bound or (tenacity_retry_alive and "retry" in local_retry)
827
+ already = _has_python_wrap_retry(tree)
828
+ if already:
829
+ use_name, need_import = already, False
830
+ else:
831
+ use_name, need_import = ("python_wrap_retry" if clash else "retry"), True
832
+
833
+ edits: list[tuple[int, int, str]] = []
834
+ for deco, settings in converted:
835
+ start, end = src.span(deco)
836
+ indent = src.indent(deco.lineno)
837
+ col = len(indent) + 1
838
+ new = settings.render(use_name, indent, col)
839
+ before = src.segment(deco)
840
+ result.changes.append(
841
+ Change(deco.lineno, deco.col_offset, before, new, tuple(settings.notes))
842
+ )
843
+ edits.append((start, end, new))
844
+
845
+ # Imports.
846
+ still_used: set[str] = set()
847
+ for ref in alive:
848
+ root: ast.expr = ref
849
+ while isinstance(root, ast.Attribute):
850
+ root = root.value
851
+ if isinstance(root, ast.Name):
852
+ still_used.add(root.id)
853
+ for ref in leftovers:
854
+ result.unsupported.append(
855
+ Unsupported(
856
+ ref.lineno,
857
+ ref.col_offset,
858
+ f"{names.resolve(ref)} is still used and has no automatic migration; "
859
+ "see the migration guide",
860
+ )
861
+ )
862
+ import_line = f"from python_wrap import retry{'' if use_name == 'retry' else ' as ' + use_name}"
863
+ newline = "\r\n" if "\r\n" in text else "\n"
864
+ pending_import = need_import
865
+ first_import = True
866
+ # statements sharing a line with another statement are left alone
867
+ for stmt in names.imports:
868
+ assert isinstance(stmt, (ast.Import, ast.ImportFrom))
869
+ if _shares_line(tree, stmt):
870
+ continue
871
+ keep: list[str] = []
872
+ if isinstance(stmt, ast.ImportFrom):
873
+ for alias in stmt.names:
874
+ local = alias.asname or alias.name
875
+ if local in still_used:
876
+ keep.append(_alias_text(alias))
877
+ kept_text = f"from {stmt.module} import {', '.join(keep)}" if keep else ""
878
+ all_kept = len(keep) == len(stmt.names)
879
+ else:
880
+ for alias in stmt.names:
881
+ root_name = (alias.asname or alias.name).split(".")[0]
882
+ if (
883
+ alias.name.split(".")[0] not in ("tenacity", "backoff")
884
+ or root_name in still_used
885
+ ):
886
+ keep.append(_alias_text(alias))
887
+ kept_text = f"import {', '.join(keep)}" if keep else ""
888
+ all_kept = len(keep) == len(stmt.names)
889
+ if all_kept:
890
+ kept_text = src.segment(stmt)
891
+ pieces = [p for p in (kept_text,) if p]
892
+ if first_import and pending_import:
893
+ pieces.append(import_line)
894
+ pending_import = False
895
+ first_import = False
896
+ s_start, s_end = src.span(stmt)
897
+ indent = src.indent(stmt.lineno)
898
+ replacement = newline.join(pieces[:1] + [indent + p for p in pieces[1:]]) if pieces else ""
899
+ if not pieces:
900
+ # drop the whole line(s) including the newline
901
+ line_start = src.starts[stmt.lineno - 1]
902
+ s_start = line_start
903
+ s_end = _line_end_offset(src, stmt.end_lineno or stmt.lineno)
904
+ edits.append((s_start, s_end, replacement))
905
+ if pending_import: # no module-level import statement could host it
906
+ result.unsupported.append(
907
+ Unsupported(1, 0, f"could not insert `{import_line}`; add it by hand")
908
+ )
909
+
910
+ new_text = text
911
+ for start, end, repl in sorted(edits, key=lambda e: e[0], reverse=True):
912
+ new_text = new_text[:start] + repl + new_text[end:]
913
+ try:
914
+ ast.parse(new_text)
915
+ except SyntaxError as exc:
916
+ return MigrationResult(
917
+ text,
918
+ [],
919
+ [*result.unsupported, Unsupported(exc.lineno or 1, 0, f"rewrite aborted: {exc.msg}")],
920
+ )
921
+ result.text = new_text
922
+ result.changes.sort(key=lambda c: (c.line, c.col))
923
+ result.unsupported.sort(key=lambda u: (u.line, u.col))
924
+ return result
925
+
926
+
927
+ def _report_leftovers(
928
+ tree: ast.Module, names: _Names, skip: set[int], result: MigrationResult
929
+ ) -> None:
930
+ for ref in _refs(tree, names, skip):
931
+ result.unsupported.append(
932
+ Unsupported(
933
+ ref.lineno,
934
+ ref.col_offset,
935
+ f"{names.resolve(ref)} has no automatic migration; see the migration guide",
936
+ )
937
+ )
938
+
939
+
940
+ def _has_python_wrap_retry(tree: ast.Module) -> str | None:
941
+ for stmt in tree.body:
942
+ if isinstance(stmt, ast.ImportFrom) and stmt.module == "python_wrap" and stmt.level == 0:
943
+ for alias in stmt.names:
944
+ if alias.name == "retry":
945
+ return alias.asname or "retry"
946
+ return None
947
+
948
+
949
+ def _alias_text(alias: ast.alias) -> str:
950
+ return f"{alias.name} as {alias.asname}" if alias.asname else alias.name
951
+
952
+
953
+ def _line_end_offset(src: _Source, lineno: int) -> int:
954
+ return src.starts[lineno - 1] + len(src.lines[lineno - 1])
955
+
956
+
957
+ def _shares_line(tree: ast.Module, stmt: ast.stmt) -> bool:
958
+ lo, hi = stmt.lineno, stmt.end_lineno or stmt.lineno
959
+ for other in tree.body:
960
+ if other is stmt:
961
+ continue
962
+ o_lo, o_hi = other.lineno, other.end_lineno or other.lineno
963
+ if o_lo <= hi and lo <= o_hi:
964
+ return True
965
+ return False
966
+
967
+
968
+ # ---------------------------------------------------------------------------- LLM retry loops
969
+
970
+ _LLM_CALL_SUFFIXES: tuple[tuple[str, ...], ...] = (
971
+ ("messages", "create"),
972
+ ("chat", "completions", "create"),
973
+ ("completions", "create"),
974
+ ("responses", "create"),
975
+ ("generate_content",),
976
+ ("generate_content_async",),
977
+ )
978
+ _IMPORT_LLM_RETRY = "from python_wrap.llm import llm_retry"
979
+
980
+
981
+ def _attr_chain(node: ast.expr) -> tuple[str, ...]:
982
+ parts: list[str] = []
983
+ while isinstance(node, ast.Attribute):
984
+ parts.append(node.attr)
985
+ node = node.value
986
+ parts.reverse()
987
+ return tuple(parts)
988
+
989
+
990
+ def _is_llm_call(node: ast.AST) -> bool:
991
+ if not isinstance(node, ast.Call):
992
+ return False
993
+ chain = _attr_chain(node.func)
994
+ return any(chain[-len(s) :] == s for s in _LLM_CALL_SUFFIXES if len(chain) >= len(s))
995
+
996
+
997
+ def _is_sleep_call(node: ast.AST) -> bool:
998
+ if not isinstance(node, ast.Call):
999
+ return False
1000
+ func = node.func
1001
+ return (isinstance(func, ast.Name) and func.id == "sleep") or (
1002
+ isinstance(func, ast.Attribute) and func.attr == "sleep"
1003
+ )
1004
+
1005
+
1006
+ def _walk_same_scope(node: ast.AST) -> list[ast.AST]:
1007
+ """Descendants of ``node`` that run in the same function (not nested defs)."""
1008
+ out: list[ast.AST] = []
1009
+ stack = list(ast.iter_child_nodes(node))
1010
+ while stack:
1011
+ cur = stack.pop()
1012
+ out.append(cur)
1013
+ if isinstance(cur, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):
1014
+ continue
1015
+ stack.extend(ast.iter_child_nodes(cur))
1016
+ return out
1017
+
1018
+
1019
+ def _is_retry_loop(loop: ast.For | ast.AsyncFor | ast.While) -> ast.Call | None:
1020
+ """The LLM call when ``loop`` looks like a hand-rolled retry loop around one."""
1021
+ inner = _walk_same_scope(loop)
1022
+ if not any(isinstance(n, ast.Try) for n in inner):
1023
+ return None
1024
+ if not any(_is_sleep_call(n) for n in inner):
1025
+ return None
1026
+ for n in inner:
1027
+ if _is_llm_call(n):
1028
+ assert isinstance(n, ast.Call)
1029
+ return n
1030
+ return None
1031
+
1032
+
1033
+ def _const_number(node: ast.expr) -> float | None:
1034
+ if (
1035
+ isinstance(node, ast.Constant)
1036
+ and isinstance(node.value, (int, float))
1037
+ and not isinstance(node.value, bool)
1038
+ ):
1039
+ return float(node.value)
1040
+ return None
1041
+
1042
+
1043
+ def _is_pow2(node: ast.expr, var: str) -> bool:
1044
+ return (
1045
+ isinstance(node, ast.BinOp)
1046
+ and isinstance(node.op, ast.Pow)
1047
+ and _const_number(node.left) == 2.0
1048
+ and isinstance(node.right, ast.Name)
1049
+ and node.right.id == var
1050
+ )
1051
+
1052
+
1053
+ def _sleep_delay(arg: ast.expr, var: str) -> tuple[float, bool] | None:
1054
+ """(first delay in seconds, doubles each time) for the sleep argument shapes we know."""
1055
+ const = _const_number(arg)
1056
+ if const is not None:
1057
+ return const, False
1058
+ if _is_pow2(arg, var):
1059
+ return 1.0, True
1060
+ if isinstance(arg, ast.BinOp) and isinstance(arg.op, ast.Mult):
1061
+ for scale, power in ((arg.left, arg.right), (arg.right, arg.left)):
1062
+ base = _const_number(scale)
1063
+ if base is not None and _is_pow2(power, var):
1064
+ return base, True
1065
+ return None
1066
+
1067
+
1068
+ def _names_in(nodes: Sequence[ast.AST]) -> set[str]:
1069
+ return {n.id for root in nodes for n in ast.walk(root) if isinstance(n, ast.Name)}
1070
+
1071
+
1072
+ def _fmt_num(value: float) -> str:
1073
+ return str(int(value)) if value == int(value) else repr(value)
1074
+
1075
+
1076
+ @dataclass
1077
+ class _LoopPlan:
1078
+ """A safe rewrite of one retry loop."""
1079
+
1080
+ func: ast.FunctionDef | ast.AsyncFunctionDef
1081
+ loop: ast.For
1082
+ call_expr: ast.expr
1083
+ attempts: int
1084
+ delay: float
1085
+ notes: list[str]
1086
+
1087
+
1088
+ def _plan_loop(func: ast.FunctionDef | ast.AsyncFunctionDef, loop: ast.stmt) -> _LoopPlan | str:
1089
+ """A `_LoopPlan` when ``loop`` can be rewritten safely, else why it cannot."""
1090
+ if not isinstance(loop, ast.For):
1091
+ return "only `for ... in range(N)` loops are rewritten automatically"
1092
+ if not (
1093
+ isinstance(loop.target, ast.Name)
1094
+ and isinstance(loop.iter, ast.Call)
1095
+ and isinstance(loop.iter.func, ast.Name)
1096
+ and loop.iter.func.id == "range"
1097
+ and len(loop.iter.args) == 1
1098
+ and not loop.iter.keywords
1099
+ ):
1100
+ return "the loop is not `for <name> in range(<integer literal>)`"
1101
+ count = loop.iter.args[0]
1102
+ if not (
1103
+ isinstance(count, ast.Constant)
1104
+ and isinstance(count.value, int)
1105
+ and not isinstance(count.value, bool)
1106
+ and count.value >= 2
1107
+ ):
1108
+ return "the attempt count is not an integer literal of at least 2"
1109
+ var, attempts = loop.target.id, count.value
1110
+ if loop.orelse:
1111
+ return "the loop has an `else` clause"
1112
+ body = list(func.body)
1113
+ if (
1114
+ body
1115
+ and isinstance(body[0], ast.Expr)
1116
+ and isinstance(body[0].value, ast.Constant)
1117
+ and isinstance(body[0].value.value, str)
1118
+ ):
1119
+ body = body[1:]
1120
+ if body != [loop]:
1121
+ return (
1122
+ "the function has other statements besides the loop (code before the loop would "
1123
+ "be retried too; code after it, such as a final `raise`, would change what callers see)"
1124
+ )
1125
+ if len(loop.body) != 1 or not isinstance(loop.body[0], ast.Try):
1126
+ return "the loop body is not a single try/except"
1127
+ attempt = loop.body[0]
1128
+ if attempt.orelse or attempt.finalbody or not attempt.handlers:
1129
+ return "the try has an `else` or `finally` clause"
1130
+ if len(attempt.body) != 1 or not isinstance(attempt.body[0], ast.Return):
1131
+ return "the try body is not a single `return <llm call>`"
1132
+ value = attempt.body[0].value
1133
+ if value is None:
1134
+ return "the try body is not a single `return <llm call>`"
1135
+ inner = value.value if isinstance(value, ast.Await) else value
1136
+ if not _is_llm_call(inner):
1137
+ return "the try body does not return the LLM call directly"
1138
+ if var in _names_in([value]):
1139
+ return f"the call uses the loop variable `{var}`"
1140
+ sleeps: list[ast.Call] = []
1141
+ for handler in attempt.handlers:
1142
+ bound = handler.name
1143
+ for stmt in handler.body:
1144
+ if isinstance(stmt, (ast.Pass, ast.Continue)):
1145
+ continue
1146
+ if isinstance(stmt, ast.Expr):
1147
+ expr = stmt.value.value if isinstance(stmt.value, ast.Await) else stmt.value
1148
+ if _is_sleep_call(expr):
1149
+ assert isinstance(expr, ast.Call)
1150
+ sleeps.append(expr)
1151
+ continue
1152
+ if _is_last_attempt_reraise(stmt, var, attempts):
1153
+ continue
1154
+ return (
1155
+ "an except block does more than sleep (logging, state changes or other "
1156
+ f"statements; line {stmt.lineno})"
1157
+ )
1158
+ if bound and bound in _names_in(handler.body):
1159
+ return f"an except block uses the caught exception `{bound}`"
1160
+ if len(sleeps) != 1:
1161
+ return "expected exactly one sleep call in the except blocks"
1162
+ sleep = sleeps[0]
1163
+ if len(sleep.args) != 1 or sleep.keywords:
1164
+ return "the sleep call is not `sleep(<seconds>)`"
1165
+ parsed = _sleep_delay(sleep.args[0], var)
1166
+ if parsed is None:
1167
+ return "the sleep duration is not a number or `<number> * 2 ** <attempt>`"
1168
+ delay, doubling = parsed
1169
+ if delay <= 0:
1170
+ return "the sleep duration is not positive"
1171
+ notes = [
1172
+ "llm_retry retries only transient errors (rate limits, overloaded, 5xx, timeouts, "
1173
+ "connection errors) and fails at once on anything else",
1174
+ "waits double from delay= with up to 0.5s of jitter, and a Retry-After header from "
1175
+ "the provider is honoured",
1176
+ "when all attempts fail the last error is raised",
1177
+ ]
1178
+ if not doubling:
1179
+ notes.append(f"the fixed {_fmt_num(delay)}s sleep becomes a doubling wait")
1180
+ return _LoopPlan(func, loop, value, attempts, delay, notes)
1181
+
1182
+
1183
+ def _is_last_attempt_reraise(stmt: ast.stmt, var: str, attempts: int) -> bool:
1184
+ """``if attempt == N - 1: raise`` (or ``>=``): the loop's own give-up rule."""
1185
+ if not (
1186
+ isinstance(stmt, ast.If)
1187
+ and not stmt.orelse
1188
+ and len(stmt.body) == 1
1189
+ and isinstance(stmt.body[0], ast.Raise)
1190
+ and stmt.body[0].exc is None
1191
+ and isinstance(stmt.test, ast.Compare)
1192
+ and len(stmt.test.ops) == 1
1193
+ and isinstance(stmt.test.ops[0], (ast.Eq, ast.GtE))
1194
+ and isinstance(stmt.test.left, ast.Name)
1195
+ and stmt.test.left.id == var
1196
+ ):
1197
+ return False
1198
+ right = stmt.test.comparators[0]
1199
+ if _const_number(right) == float(attempts - 1):
1200
+ return True
1201
+ return (
1202
+ isinstance(right, ast.BinOp)
1203
+ and isinstance(right.op, ast.Sub)
1204
+ and _const_number(right.left) == float(attempts)
1205
+ and _const_number(right.right) == 1.0
1206
+ )
1207
+
1208
+
1209
+ def _find_retry_loops(
1210
+ tree: ast.Module,
1211
+ ) -> list[tuple[ast.FunctionDef | ast.AsyncFunctionDef | None, ast.stmt, ast.Call]]:
1212
+ """Outermost retry loops with their enclosing function (None outside a function)."""
1213
+ found: list[tuple[ast.FunctionDef | ast.AsyncFunctionDef | None, ast.stmt, ast.Call]] = []
1214
+
1215
+ def visit(node: ast.AST, func: ast.FunctionDef | ast.AsyncFunctionDef | None) -> None:
1216
+ for child in ast.iter_child_nodes(node):
1217
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
1218
+ visit(child, child)
1219
+ elif isinstance(child, (ast.For, ast.AsyncFor, ast.While)):
1220
+ call = _is_retry_loop(child)
1221
+ if call is not None:
1222
+ found.append((func, child, call))
1223
+ else:
1224
+ visit(child, func)
1225
+ else:
1226
+ visit(child, func)
1227
+
1228
+ visit(tree, None)
1229
+ return found
1230
+
1231
+
1232
+ def _llm_retry_name(tree: ast.Module) -> tuple[str | None, bool]:
1233
+ """(name `llm_retry` is imported as, whether `llm_retry` is bound to something else)."""
1234
+ for stmt in tree.body:
1235
+ if (
1236
+ isinstance(stmt, ast.ImportFrom)
1237
+ and stmt.level == 0
1238
+ and stmt.module in ("python_wrap", "python_wrap.llm")
1239
+ ):
1240
+ for alias in stmt.names:
1241
+ if alias.name == "llm_retry":
1242
+ return alias.asname or "llm_retry", False
1243
+ taken = any(
1244
+ (isinstance(n, ast.Name) and n.id == "llm_retry")
1245
+ or (
1246
+ isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))
1247
+ and n.name == "llm_retry"
1248
+ )
1249
+ or (isinstance(n, ast.alias) and (n.asname or n.name) == "llm_retry")
1250
+ for n in ast.walk(tree)
1251
+ )
1252
+ return None, taken
1253
+
1254
+
1255
+ def _migrate_loops(text: str, tree: ast.Module) -> MigrationResult:
1256
+ result = MigrationResult(text)
1257
+ loops = _find_retry_loops(tree)
1258
+ if not loops:
1259
+ return result
1260
+ src = _Source(text)
1261
+ name, taken = _llm_retry_name(tree)
1262
+ use = name or "llm_retry"
1263
+ plans: list[_LoopPlan] = []
1264
+ for func, loop, call in loops:
1265
+ callee = ast.unparse(call.func)
1266
+ end = loop.end_lineno or loop.lineno
1267
+ where = f"line {loop.lineno}" if end == loop.lineno else f"lines {loop.lineno}-{end}"
1268
+ if func is None:
1269
+ why: _LoopPlan | str = "the loop is not inside a function"
1270
+ elif taken and name is None:
1271
+ why = "the name `llm_retry` is already used for something else in this module"
1272
+ else:
1273
+ why = _plan_loop(func, loop)
1274
+ if isinstance(why, str):
1275
+ result.unsupported.append(
1276
+ Unsupported(
1277
+ loop.lineno,
1278
+ loop.col_offset,
1279
+ f"hand-rolled retry loop around `{callee}(...)` "
1280
+ f"({where}) not rewritten: {why}. Move the single call into its own "
1281
+ "function decorated with "
1282
+ "`@llm_retry(max_attempts=..., delay=...)` (from python_wrap.llm) and "
1283
+ "delete the loop, the sleep and the except block",
1284
+ )
1285
+ )
1286
+ else:
1287
+ plans.append(why)
1288
+ if not plans:
1289
+ return result
1290
+
1291
+ newline = "\r\n" if "\r\n" in text else "\n"
1292
+ edits: list[tuple[int, int, str]] = []
1293
+ for plan in plans:
1294
+ func, loop = plan.func, plan.loop
1295
+ value_text = src.segment(plan.call_expr)
1296
+ ret_stmt = loop.body[0].body[0] # type: ignore[attr-defined]
1297
+ shift = ret_stmt.col_offset - loop.col_offset
1298
+ pieces = value_text.splitlines(keepends=True)
1299
+ value_text = pieces[0] + "".join(
1300
+ ln[shift:] if ln[:shift].strip() == "" else ln for ln in pieces[1:]
1301
+ )
1302
+ start, end = src.span(loop)
1303
+ edits.append((start, end, f"return {value_text}"))
1304
+ indent = src.indent(func.lineno)
1305
+ deco = (
1306
+ f"{indent}@{use}(max_attempts={plan.attempts}, delay={_fmt_num(plan.delay)}){newline}"
1307
+ )
1308
+ at = src.starts[func.lineno - 1]
1309
+ edits.append((at, at, deco))
1310
+ before = src.lines[loop.lineno - 1].strip()
1311
+ result.changes.append(
1312
+ Change(
1313
+ loop.lineno,
1314
+ loop.col_offset,
1315
+ before,
1316
+ deco.strip(),
1317
+ tuple(plan.notes),
1318
+ kind="loop",
1319
+ )
1320
+ )
1321
+ if name is None:
1322
+ imports = [s for s in tree.body if isinstance(s, (ast.Import, ast.ImportFrom))]
1323
+ if imports and not any(_shares_line(tree, s) for s in imports[-1:]):
1324
+ last = imports[-1]
1325
+ at = _line_end_offset(src, last.end_lineno or last.lineno)
1326
+ prefix = "" if src.text[:at].endswith(("\n", "\r")) else newline
1327
+ edits.append((at, at, f"{prefix}{_IMPORT_LLM_RETRY}{newline}"))
1328
+ else:
1329
+ first = tree.body[0]
1330
+ doc = (
1331
+ isinstance(first, ast.Expr)
1332
+ and isinstance(first.value, ast.Constant)
1333
+ and isinstance(first.value.value, str)
1334
+ )
1335
+ line = (first.end_lineno or first.lineno) if doc else 0
1336
+ at = _line_end_offset(src, line) if line else 0
1337
+ edits.append((at, at, f"{_IMPORT_LLM_RETRY}{newline}"))
1338
+
1339
+ new_text = text
1340
+ for start, end, repl in sorted(edits, key=lambda e: e[0], reverse=True):
1341
+ new_text = new_text[:start] + repl + new_text[end:]
1342
+ try:
1343
+ ast.parse(new_text)
1344
+ except SyntaxError as exc:
1345
+ result.unsupported.append(Unsupported(exc.lineno or 1, 0, f"rewrite aborted: {exc.msg}"))
1346
+ result.changes.clear()
1347
+ return result
1348
+ result.text = new_text
1349
+ return result
1350
+
1351
+
1352
+ def _line_map(old: str, new: str) -> list[int]:
1353
+ """For each 1-based line of ``new`` (index 0 unused), the matching line of ``old``."""
1354
+ a, b = old.splitlines(), new.splitlines()
1355
+ mapping = [1] * (len(b) + 2)
1356
+ for tag, i1, _i2, j1, j2 in difflib.SequenceMatcher(None, a, b, autojunk=False).get_opcodes():
1357
+ for j in range(j1, j2):
1358
+ mapping[j + 1] = i1 + 1 + (j - j1 if tag == "equal" else 0)
1359
+ return mapping
1360
+
1361
+
1362
+ # ---------------------------------------------------------------------------- CLI
1363
+
1364
+
1365
+ def _iter_files(paths: Sequence[str]) -> list[Path]:
1366
+ files: list[Path] = []
1367
+ for raw in paths:
1368
+ path = Path(raw)
1369
+ if path.is_dir():
1370
+ for found in sorted(path.rglob("*.py")):
1371
+ if not any(part in _SKIP_DIRS for part in found.relative_to(path).parts):
1372
+ files.append(found)
1373
+ else:
1374
+ files.append(path)
1375
+ return files
1376
+
1377
+
1378
+ def _read(path: Path) -> tuple[str, str]:
1379
+ data = path.read_bytes()
1380
+ encoding, _ = tokenize.detect_encoding(iter(data.splitlines(keepends=True)).__next__)
1381
+ return data.decode(encoding), encoding
1382
+
1383
+
1384
+ def main(argv: list[str] | None = None) -> int:
1385
+ """Command-line entry point for ``python -m python_wrap migrate``.
1386
+
1387
+ Args:
1388
+ argv: Arguments (default ``sys.argv[1:]``).
1389
+
1390
+ Returns:
1391
+ 0 when nothing needs manual attention, 1 when unsupported constructs were found,
1392
+ 2 on usage or file errors.
1393
+ """
1394
+ parser = argparse.ArgumentParser(
1395
+ prog="python -m python_wrap migrate",
1396
+ description="Rewrite tenacity/backoff decorators and LLM retry loops to python_wrap.",
1397
+ )
1398
+ parser.add_argument("paths", nargs="+", metavar="PATH", help="files or directories")
1399
+ parser.add_argument("--write", action="store_true", help="write the rewritten files")
1400
+ parser.add_argument("--diff", action="store_true", help="print a unified diff")
1401
+ args = parser.parse_args(argv)
1402
+
1403
+ unsupported_total = 0
1404
+ changed_files = 0
1405
+ errors = 0
1406
+ for path in _iter_files(args.paths):
1407
+ try:
1408
+ text, encoding = _read(path)
1409
+ except (OSError, UnicodeDecodeError, SyntaxError) as exc:
1410
+ print(f"{path}: cannot read: {exc}", file=sys.stderr)
1411
+ errors += 1
1412
+ continue
1413
+ result = migrate_source(text, str(path))
1414
+ for item in result.unsupported:
1415
+ print(f"{path}:{item.line}:{item.col + 1}: unsupported: {item.message}")
1416
+ unsupported_total += len(result.unsupported)
1417
+ if result.text == text:
1418
+ continue
1419
+ changed_files += 1
1420
+ for change in result.changes:
1421
+ what = "retry loop" if change.kind == "loop" else "decorator"
1422
+ print(f"{path}:{change.line}:{change.col + 1}: rewrote {what}")
1423
+ for note in change.notes:
1424
+ print(f" note: {note}")
1425
+ if args.diff:
1426
+ sys.stdout.writelines(
1427
+ difflib.unified_diff(
1428
+ text.splitlines(keepends=True),
1429
+ result.text.splitlines(keepends=True),
1430
+ fromfile=f"a/{path}",
1431
+ tofile=f"b/{path}",
1432
+ )
1433
+ )
1434
+ if args.write:
1435
+ path.write_bytes(result.text.encode(encoding))
1436
+ print(f"{path}: written")
1437
+ else:
1438
+ decos = sum(1 for c in result.changes if c.kind == "decorator")
1439
+ loops_n = len(result.changes) - decos
1440
+ parts = ([f"{decos} decorator(s)"] if decos else []) + (
1441
+ [f"{loops_n} retry loop(s)"] if loops_n else []
1442
+ )
1443
+ print(f"{path}: would rewrite {' and '.join(parts)}")
1444
+ verb = "rewrote" if args.write else "would rewrite"
1445
+ print(f"{verb} {changed_files} file(s); {unsupported_total} unsupported finding(s)")
1446
+ if errors:
1447
+ return 2
1448
+ return 1 if unsupported_total else 0
1449
+
1450
+
1451
+ if __name__ == "__main__": # pragma: no cover
1452
+ raise SystemExit(main())