flaky-anything 0.1.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.
- flaky_anything/__init__.py +5 -0
- flaky_anything/cli.py +405 -0
- flaky_anything/config.py +80 -0
- flaky_anything/diagnose.py +514 -0
- flaky_anything/errors.py +8 -0
- flaky_anything/fix/__init__.py +0 -0
- flaky_anything/fix/apply.py +96 -0
- flaky_anything/fix/backends.py +193 -0
- flaky_anything/fix/context.py +150 -0
- flaky_anything/fix/guards.py +345 -0
- flaky_anything/fix/loop.py +168 -0
- flaky_anything/fix/mutate.py +227 -0
- flaky_anything/fix/playbooks.md +61 -0
- flaky_anything/fix/prompt.py +77 -0
- flaky_anything/hints.py +200 -0
- flaky_anything/hunt.py +352 -0
- flaky_anything/knobs/__init__.py +1 -0
- flaky_anything/knobs/base.py +41 -0
- flaky_anything/knobs/clock.py +127 -0
- flaky_anything/knobs/order.py +37 -0
- flaky_anything/knobs/registry.py +45 -0
- flaky_anything/knobs/seeds.py +47 -0
- flaky_anything/knobs/tz.py +41 -0
- flaky_anything/report.py +164 -0
- flaky_anything/repro.py +130 -0
- flaky_anything/runner.py +158 -0
- flaky_anything/selection.py +137 -0
- flaky_anything/signatures.py +89 -0
- flaky_anything/stats.py +46 -0
- flaky_anything/store.py +230 -0
- flaky_anything/trial_plugin.py +196 -0
- flaky_anything/verify.py +124 -0
- flaky_anything-0.1.0.dist-info/METADATA +177 -0
- flaky_anything-0.1.0.dist-info/RECORD +37 -0
- flaky_anything-0.1.0.dist-info/WHEEL +4 -0
- flaky_anything-0.1.0.dist-info/entry_points.txt +2 -0
- flaky_anything-0.1.0.dist-info/licenses/LICENSE +21 -0
flaky_anything/cli.py
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
"""Command-line entry point. Thin: parse args, call core, render."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import shlex
|
|
5
|
+
import sys
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Annotated
|
|
9
|
+
|
|
10
|
+
import typer
|
|
11
|
+
from rich.console import Console
|
|
12
|
+
from rich.markup import escape
|
|
13
|
+
from rich.progress import Progress
|
|
14
|
+
from rich.table import Table
|
|
15
|
+
|
|
16
|
+
from flaky_anything import __version__
|
|
17
|
+
from flaky_anything import diagnose as diagnose_mod
|
|
18
|
+
from flaky_anything import hunt as hunt_mod
|
|
19
|
+
from flaky_anything import report as report_mod
|
|
20
|
+
from flaky_anything import repro as repro_mod
|
|
21
|
+
from flaky_anything import verify as verify_mod
|
|
22
|
+
from flaky_anything.errors import FlakyAnythingError
|
|
23
|
+
from flaky_anything.fix import context as fix_context
|
|
24
|
+
from flaky_anything.fix import loop as fix_loop
|
|
25
|
+
from flaky_anything.fix.backends import backend_from_env
|
|
26
|
+
from flaky_anything.fix.prompt import render_prompt
|
|
27
|
+
from flaky_anything.knobs.registry import DEFAULT as DEFAULT_KNOBS
|
|
28
|
+
from flaky_anything.selection import default_python, find_root
|
|
29
|
+
|
|
30
|
+
app = typer.Typer(help="Find flaky tests, explain why they fail, and prove the fix.")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@app.callback()
|
|
34
|
+
def main() -> None:
|
|
35
|
+
"""flaky-anything."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@app.command("version")
|
|
39
|
+
def version_cmd() -> None:
|
|
40
|
+
"""Print the installed version."""
|
|
41
|
+
typer.echo(__version__)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _more(items: Sequence[object]) -> str:
|
|
45
|
+
return f" +{len(items) - 1}" if len(items) > 1 else ""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _pct(x: float) -> str:
|
|
49
|
+
return f"{100 * x:.0f}%" if x >= 0.1 else f"{100 * x:.1f}%"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def render_hunt(report: hunt_mod.HuntReport, console: Console) -> None:
|
|
53
|
+
findings = [*report.flaky, *report.broken]
|
|
54
|
+
if not findings:
|
|
55
|
+
console.print(f"No flaky tests found in {report.trials} trials.")
|
|
56
|
+
else:
|
|
57
|
+
table = Table(title="Flaky tests", title_justify="left")
|
|
58
|
+
columns = ("test", "verdict", "failed", "fail rate (95% CI)", "signature", "failing config")
|
|
59
|
+
table.add_column(columns[0], overflow="fold") # node ids are copied: never "…"
|
|
60
|
+
for col in columns[1:]:
|
|
61
|
+
table.add_column(col)
|
|
62
|
+
for f in findings:
|
|
63
|
+
top = f.signatures[0] if f.signatures else None
|
|
64
|
+
table.add_row(
|
|
65
|
+
escape(f.nodeid),
|
|
66
|
+
f.verdict,
|
|
67
|
+
f"{f.failed}/{f.passed + f.failed}",
|
|
68
|
+
f"{_pct(f.failure_rate)} ({_pct(f.rate_low)}-{_pct(f.rate_high)})",
|
|
69
|
+
f"{top.exc_type} {top.id[:8]}{_more(f.signatures)}" if top else "-",
|
|
70
|
+
f.failing_config_ids[0] + _more(f.failing_config_ids),
|
|
71
|
+
)
|
|
72
|
+
console.print(table)
|
|
73
|
+
console.print("Rates are over the sampled configs the hunt ran, not a CI failure rate.")
|
|
74
|
+
console.print(
|
|
75
|
+
f"{report.trials} trials, {report.tests_selected} tests, seed {report.seed}, "
|
|
76
|
+
f"knobs {','.join(report.knobs)}."
|
|
77
|
+
)
|
|
78
|
+
if report.trial_errors:
|
|
79
|
+
console.print(
|
|
80
|
+
f"[yellow]{report.trial_errors} trial(s) errored[/] (see the store's stderr_tail)."
|
|
81
|
+
)
|
|
82
|
+
if report.never_ran:
|
|
83
|
+
console.print(
|
|
84
|
+
f"[yellow]{len(report.never_ran)} selected test(s) never ran[/], so nothing is known "
|
|
85
|
+
f"about them, e.g. {escape(report.never_ran[0])} (a node id that changes between "
|
|
86
|
+
"collections?)",
|
|
87
|
+
highlight=False,
|
|
88
|
+
)
|
|
89
|
+
if report.budget_spent:
|
|
90
|
+
console.print("[yellow]Budget spent:[/] tests not listed may still be flaky.")
|
|
91
|
+
if report.flaky:
|
|
92
|
+
console.print(f"Next: flaky-anything diagnose {escape(report.flaky[0].nodeid)}")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@app.command("hunt")
|
|
96
|
+
def hunt_cmd(
|
|
97
|
+
paths: Annotated[list[str] | None, typer.Argument(help="Dirs, files or node ids.")] = None,
|
|
98
|
+
from_junit: Annotated[
|
|
99
|
+
list[Path] | None, typer.Option("--from-junit", help="CI JUnit XML reports.")
|
|
100
|
+
] = None,
|
|
101
|
+
knobs: Annotated[str, typer.Option(help="Knobs to perturb.")] = DEFAULT_KNOBS,
|
|
102
|
+
budget: Annotated[str, typer.Option(help="Wall-clock budget, e.g. 90s, 10m.")] = "10m",
|
|
103
|
+
max_trials: Annotated[int | None, typer.Option(help="Stop after N trials.")] = None,
|
|
104
|
+
seed: Annotated[int, typer.Option(help="Seed; same seed, same hunt.")] = 0,
|
|
105
|
+
jobs: Annotated[int, typer.Option(help="Trials to run in parallel.")] = 1,
|
|
106
|
+
python: Annotated[
|
|
107
|
+
str | None, typer.Option(help="Interpreter of the project (default: its .venv).")
|
|
108
|
+
] = None,
|
|
109
|
+
json_out: Annotated[bool, typer.Option("--json", help="Print the report as JSON.")] = False,
|
|
110
|
+
) -> None:
|
|
111
|
+
"""Find flaky tests by running them under perturbed order, seeds, clock and time zone."""
|
|
112
|
+
root, rel = find_root(paths or [])
|
|
113
|
+
with Console(stderr=True).status(f"hunting in {escape(str(root))} ..."):
|
|
114
|
+
report = hunt_mod.hunt(
|
|
115
|
+
root,
|
|
116
|
+
rel,
|
|
117
|
+
junit=from_junit or [],
|
|
118
|
+
knobs=knobs,
|
|
119
|
+
seed=seed,
|
|
120
|
+
budget=hunt_mod.Budget(max_trials, hunt_mod.parse_duration(budget)),
|
|
121
|
+
jobs=jobs,
|
|
122
|
+
python=python or default_python(root),
|
|
123
|
+
)
|
|
124
|
+
if json_out:
|
|
125
|
+
typer.echo(report.model_dump_json(indent=2))
|
|
126
|
+
else:
|
|
127
|
+
render_hunt(report, Console())
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _node(nodeid: str) -> tuple[Path, str]:
|
|
131
|
+
root, rel = find_root([nodeid])
|
|
132
|
+
if not rel or "::" not in rel[0]:
|
|
133
|
+
raise FlakyAnythingError(
|
|
134
|
+
f"{nodeid} is not a test node id", hint="e.g. tests/test_x.py::test_y"
|
|
135
|
+
)
|
|
136
|
+
return root, rel[0]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def render_diagnosis(d: diagnose_mod.Diagnosis, console: Console) -> None:
|
|
140
|
+
rep = d.replay
|
|
141
|
+
console.print(f"[bold]{escape(d.nodeid)}[/] → [bold cyan]{d.category}[/]", highlight=False)
|
|
142
|
+
narrowed = (
|
|
143
|
+
f" (a subset of {d.config_id}: the victim alone or with its file)"
|
|
144
|
+
if rep.config_id != d.config_id
|
|
145
|
+
else ""
|
|
146
|
+
)
|
|
147
|
+
console.print(
|
|
148
|
+
f"Replayed config {rep.config_id}{narrowed}: "
|
|
149
|
+
f"failed {len(rep.failed_trial_ids)}/{len(rep.trial_ids)}."
|
|
150
|
+
)
|
|
151
|
+
if d.minimal_config is None:
|
|
152
|
+
console.print(
|
|
153
|
+
"[yellow]Not deterministic under our knobs:[/] the cause is outside order, seeds, "
|
|
154
|
+
"clock and time zone (e.g. os.urandom, threads, network). No reproducer."
|
|
155
|
+
)
|
|
156
|
+
return
|
|
157
|
+
for line in d.explanation:
|
|
158
|
+
console.print(f" needs {escape(line)}", highlight=False)
|
|
159
|
+
if d.polluter:
|
|
160
|
+
console.print(f" polluter: {escape(d.polluter)} (runs first, breaks it)", highlight=False)
|
|
161
|
+
if d.state_setter:
|
|
162
|
+
console.print(f" fails alone; passes after: {escape(d.state_setter)}", highlight=False)
|
|
163
|
+
if d.combination:
|
|
164
|
+
console.print(
|
|
165
|
+
f" needs these tests together: {escape(', '.join(d.combination))}", highlight=False
|
|
166
|
+
)
|
|
167
|
+
if d.minimal and d.minimal.capped:
|
|
168
|
+
console.print("[yellow] search capped: that set is small, not proven minimal[/]")
|
|
169
|
+
console.print(f"Next: flaky-anything repro {escape(d.nodeid)}", highlight=False)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@app.command("diagnose")
|
|
173
|
+
def diagnose_cmd(
|
|
174
|
+
nodeid: Annotated[str, typer.Argument(help="Node id of a test the hunt found failing.")],
|
|
175
|
+
config_id: Annotated[
|
|
176
|
+
str | None, typer.Option(help="Failing config to diagnose (default: its first).")
|
|
177
|
+
] = None,
|
|
178
|
+
replays: Annotated[int, typer.Option(help="Replays per step.")] = diagnose_mod.REPLAYS,
|
|
179
|
+
jobs: Annotated[int, typer.Option(help="Trials to run in parallel.")] = 1,
|
|
180
|
+
python: Annotated[
|
|
181
|
+
str | None, typer.Option(help="Interpreter of the project (default: its .venv).")
|
|
182
|
+
] = None,
|
|
183
|
+
json_out: Annotated[bool, typer.Option("--json", help="Print the diagnosis as JSON.")] = False,
|
|
184
|
+
) -> None:
|
|
185
|
+
"""Explain why a test fails: replay its failing config, ablate knobs, find the polluter."""
|
|
186
|
+
root, node = _node(nodeid)
|
|
187
|
+
with Console(stderr=True).status(f"diagnosing {escape(node)} ..."):
|
|
188
|
+
d = diagnose_mod.diagnose(
|
|
189
|
+
root,
|
|
190
|
+
node,
|
|
191
|
+
config_id=config_id,
|
|
192
|
+
replays=replays,
|
|
193
|
+
jobs=jobs,
|
|
194
|
+
python=python or default_python(root),
|
|
195
|
+
)
|
|
196
|
+
if json_out:
|
|
197
|
+
typer.echo(d.model_dump_json(indent=2))
|
|
198
|
+
else:
|
|
199
|
+
render_diagnosis(d, Console())
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@app.command("repro")
|
|
203
|
+
def repro_cmd(
|
|
204
|
+
nodeid: Annotated[str, typer.Argument(help="Node id of a diagnosed test.")],
|
|
205
|
+
check: Annotated[int, typer.Option(help="Run the command N times.")] = repro_mod.CHECKS,
|
|
206
|
+
jobs: Annotated[int, typer.Option(help="Checks to run in parallel.")] = 1,
|
|
207
|
+
python: Annotated[
|
|
208
|
+
str | None, typer.Option(help="Interpreter of the project (default: its .venv).")
|
|
209
|
+
] = None,
|
|
210
|
+
json_out: Annotated[bool, typer.Option("--json", help="Print the result as JSON.")] = False,
|
|
211
|
+
) -> None:
|
|
212
|
+
"""Print a copy-pasteable command that reproduces the failure, and how often it did."""
|
|
213
|
+
root, node = _node(nodeid)
|
|
214
|
+
d = diagnose_mod.load_diagnosis(root, node)
|
|
215
|
+
if d.minimal_config is None:
|
|
216
|
+
raise FlakyAnythingError(
|
|
217
|
+
f"{node} is {d.category}: no deterministic reproducer exists",
|
|
218
|
+
hint="the cause is outside our knobs; see `flaky-anything diagnose`",
|
|
219
|
+
)
|
|
220
|
+
with Console(stderr=True).status(f"checking the reproducer {check}x ..."):
|
|
221
|
+
r = repro_mod.repro(
|
|
222
|
+
d.minimal_config,
|
|
223
|
+
d.necessary_knobs,
|
|
224
|
+
root,
|
|
225
|
+
node,
|
|
226
|
+
runs=check,
|
|
227
|
+
jobs=jobs,
|
|
228
|
+
python=python or default_python(root),
|
|
229
|
+
)
|
|
230
|
+
if json_out:
|
|
231
|
+
typer.echo(r.model_dump_json(indent=2))
|
|
232
|
+
else:
|
|
233
|
+
console = Console()
|
|
234
|
+
console.print(f"# from {escape(str(root))}", highlight=False)
|
|
235
|
+
console.print(escape(r.command), highlight=False, soft_wrap=True)
|
|
236
|
+
style = "green" if r.failed == r.runs else "yellow"
|
|
237
|
+
console.print(f"[{style}]fails {r.failed}/{r.runs}[/] (run verbatim just now)")
|
|
238
|
+
if r.failed != r.runs:
|
|
239
|
+
raise typer.Exit(1)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@app.command("verify")
|
|
243
|
+
def verify_cmd(
|
|
244
|
+
nodeid: Annotated[str, typer.Argument(help="Node id of a diagnosed test.")],
|
|
245
|
+
runs: Annotated[int, typer.Option(help="Perturbed trials to run.")] = verify_mod.RUNS,
|
|
246
|
+
confidence: Annotated[float, typer.Option(help="Confidence of the bound.")] = 0.95,
|
|
247
|
+
seed: Annotated[int, typer.Option(help="Seed for the perturbed configs.")] = 0,
|
|
248
|
+
jobs: Annotated[int, typer.Option(help="Trials to run in parallel.")] = 1,
|
|
249
|
+
python: Annotated[
|
|
250
|
+
str | None, typer.Option(help="Interpreter of the project (default: its .venv).")
|
|
251
|
+
] = None,
|
|
252
|
+
json_out: Annotated[bool, typer.Option("--json", help="Print the result as JSON.")] = False,
|
|
253
|
+
) -> None:
|
|
254
|
+
"""Prove a fix: the reproducer passes, then N perturbed runs pass. Exits 1 on any failure."""
|
|
255
|
+
root, node = _node(nodeid)
|
|
256
|
+
with Progress(console=Console(stderr=True), transient=True) as bar:
|
|
257
|
+
task = bar.add_task("perturbed runs", total=runs)
|
|
258
|
+
v = verify_mod.verify(
|
|
259
|
+
root,
|
|
260
|
+
node,
|
|
261
|
+
runs=runs,
|
|
262
|
+
confidence=confidence,
|
|
263
|
+
seed=seed,
|
|
264
|
+
jobs=jobs,
|
|
265
|
+
python=python or default_python(root),
|
|
266
|
+
progress=lambda done: bar.update(task, completed=done),
|
|
267
|
+
)
|
|
268
|
+
if json_out:
|
|
269
|
+
typer.echo(v.model_dump_json(indent=2))
|
|
270
|
+
else:
|
|
271
|
+
console = Console()
|
|
272
|
+
if v.repro_failures:
|
|
273
|
+
console.print(f"[red]reproducer still fails {v.repro_failures}/{v.repro_runs}[/]")
|
|
274
|
+
elif v.failures:
|
|
275
|
+
console.print(f"[red]failed in perturbed run {v.runs}[/]")
|
|
276
|
+
else:
|
|
277
|
+
if v.repro_runs:
|
|
278
|
+
console.print(f"reproducer passes {v.repro_runs}/{v.repro_runs}")
|
|
279
|
+
assert v.bound is not None
|
|
280
|
+
console.print(
|
|
281
|
+
f"[green]0/{v.runs} failures → failure rate < {v.bound:.2%} "
|
|
282
|
+
f"({v.confidence:.0%} confidence)[/]"
|
|
283
|
+
)
|
|
284
|
+
if v.failing_config is not None:
|
|
285
|
+
console.print(
|
|
286
|
+
"failing config:", escape(v.failing_config.canonical_json()), highlight=False
|
|
287
|
+
)
|
|
288
|
+
if not v.passed:
|
|
289
|
+
raise typer.Exit(1)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
@app.command("fix")
|
|
293
|
+
def fix_cmd(
|
|
294
|
+
nodeid: Annotated[str, typer.Argument(help="Node id of a diagnosed test.")],
|
|
295
|
+
emit_prompt: Annotated[
|
|
296
|
+
bool, typer.Option("--emit-prompt", help="Print the fix prompt for any agent.")
|
|
297
|
+
] = False,
|
|
298
|
+
apply: Annotated[
|
|
299
|
+
bool, typer.Option("--apply", help="Apply the verified patch to the working tree.")
|
|
300
|
+
] = False,
|
|
301
|
+
attempts: Annotated[int, typer.Option(help="Patches to try.")] = fix_loop.ATTEMPTS,
|
|
302
|
+
runs: Annotated[int, typer.Option(help="Perturbed verify runs.")] = fix_loop.VERIFY_RUNS,
|
|
303
|
+
check: Annotated[int, typer.Option(help="Run the reproducer N times.")] = repro_mod.CHECKS,
|
|
304
|
+
jobs: Annotated[int, typer.Option(help="Checks to run in parallel.")] = 1,
|
|
305
|
+
python: Annotated[
|
|
306
|
+
str | None, typer.Option(help="Interpreter of the project (default: its .venv).")
|
|
307
|
+
] = None,
|
|
308
|
+
json_out: Annotated[bool, typer.Option("--json", help="Print the result as JSON.")] = False,
|
|
309
|
+
) -> None:
|
|
310
|
+
"""Fix a diagnosed test with the model in FLAKY_ANYTHING_MODEL (guards + verify), or
|
|
311
|
+
--emit-prompt to print the prompt for your own agent."""
|
|
312
|
+
root, node = _node(nodeid)
|
|
313
|
+
py = python or default_python(root)
|
|
314
|
+
if not emit_prompt:
|
|
315
|
+
backend = backend_from_env()
|
|
316
|
+
with Console(stderr=True).status(f"fixing with {backend.name} ..."):
|
|
317
|
+
out = fix_loop.run_fix(root, node, backend, apply, attempts, runs, python=py)
|
|
318
|
+
if json_out:
|
|
319
|
+
typer.echo(out.model_dump_json(indent=2))
|
|
320
|
+
else:
|
|
321
|
+
_print_fix(out)
|
|
322
|
+
if not out.ok:
|
|
323
|
+
raise typer.Exit(1)
|
|
324
|
+
return
|
|
325
|
+
d = diagnose_mod.load_diagnosis(root, node)
|
|
326
|
+
r = None
|
|
327
|
+
if d.minimal_config is not None:
|
|
328
|
+
with Console(stderr=True).status(f"checking the reproducer {check}x ..."):
|
|
329
|
+
r = repro_mod.repro(
|
|
330
|
+
d.minimal_config, d.necessary_knobs, root, node, runs=check, jobs=jobs, python=py
|
|
331
|
+
)
|
|
332
|
+
ctx = fix_context.build_context(root, d, r)
|
|
333
|
+
typer.echo(ctx.model_dump_json(indent=2) if json_out else render_prompt(ctx))
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _print_fix(out: fix_loop.FixOutcome) -> None:
|
|
337
|
+
console = Console()
|
|
338
|
+
for a in out.attempts:
|
|
339
|
+
mark = "[red]rejected[/]" if a.rejected else "[green]accepted[/]"
|
|
340
|
+
console.print(f"attempt {a.n}: {mark}")
|
|
341
|
+
for line in a.rejected:
|
|
342
|
+
console.print(f" - {escape(line)}", highlight=False)
|
|
343
|
+
for line in a.flags:
|
|
344
|
+
console.print(f" [yellow]flag:[/] {escape(line)}", highlight=False)
|
|
345
|
+
last = out.attempts[-1] if out.attempts else None
|
|
346
|
+
if not out.ok or last is None:
|
|
347
|
+
console.print(f"[red]no fix after {len(out.attempts)} attempt(s)[/]")
|
|
348
|
+
if out.worktree:
|
|
349
|
+
console.print(f"last attempt left in {escape(str(out.worktree))}")
|
|
350
|
+
return
|
|
351
|
+
v = last.verification
|
|
352
|
+
if v is not None and v.bound is not None:
|
|
353
|
+
console.print(
|
|
354
|
+
f"[green]0/{v.runs} failures → failure rate < {v.bound:.2%} "
|
|
355
|
+
f"({v.confidence:.0%} confidence)[/]"
|
|
356
|
+
)
|
|
357
|
+
if last.patch is not None and last.patch.touches_production_code:
|
|
358
|
+
console.print("[yellow]flag:[/] the fix changes production code")
|
|
359
|
+
console.print(f"patch: {escape(str(out.patch_file))}")
|
|
360
|
+
console.print(
|
|
361
|
+
"applied to the working tree (not committed)"
|
|
362
|
+
if out.applied
|
|
363
|
+
else f"apply from the repo root with: git apply {escape(str(out.patch_file))}"
|
|
364
|
+
)
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
@app.command("report")
|
|
368
|
+
def report_cmd(
|
|
369
|
+
path: Annotated[Path, typer.Argument(help="Project directory.")] = Path("."),
|
|
370
|
+
fmt: Annotated[str, typer.Option("--format", help="md or json.")] = "md",
|
|
371
|
+
pr: Annotated[
|
|
372
|
+
str | None, typer.Option("--pr", help="Print a PR title (stderr) and body for NODEID.")
|
|
373
|
+
] = None,
|
|
374
|
+
) -> None:
|
|
375
|
+
"""Every diagnosis and fix: root cause, reproducer, fix diff, verification bound, flags."""
|
|
376
|
+
if fmt not in ("md", "json"):
|
|
377
|
+
raise FlakyAnythingError(f"--format must be md or json, got {fmt!r}")
|
|
378
|
+
entries = report_mod.build_report(path.resolve())
|
|
379
|
+
if pr is not None:
|
|
380
|
+
match = [e for e in entries if e.nodeid == pr]
|
|
381
|
+
if not match:
|
|
382
|
+
raise FlakyAnythingError(f"no diagnosis of {pr}", hint="run `flaky-anything diagnose`")
|
|
383
|
+
title, body = report_mod.render_pr(match[0])
|
|
384
|
+
if fmt == "json":
|
|
385
|
+
typer.echo(json.dumps({"title": title, "body": body}, indent=2))
|
|
386
|
+
else:
|
|
387
|
+
typer.echo(f"gh pr create --title {shlex.quote(title)} --body-file -", err=True)
|
|
388
|
+
typer.echo(body, nl=False)
|
|
389
|
+
return
|
|
390
|
+
if fmt == "json":
|
|
391
|
+
typer.echo(json.dumps([e.model_dump() for e in entries], indent=2))
|
|
392
|
+
else:
|
|
393
|
+
typer.echo(report_mod.render_markdown(entries), nl=False)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def run() -> None:
|
|
397
|
+
"""Console-script entry point: run the app, render expected errors without a traceback."""
|
|
398
|
+
try:
|
|
399
|
+
app()
|
|
400
|
+
except FlakyAnythingError as e:
|
|
401
|
+
err = Console(stderr=True)
|
|
402
|
+
err.print(f"[bold red]error:[/] {escape(e.message)}", highlight=False)
|
|
403
|
+
if e.hint:
|
|
404
|
+
err.print(f"[yellow]hint:[/] {escape(e.hint)}", highlight=False)
|
|
405
|
+
sys.exit(1)
|
flaky_anything/config.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""TrialConfig: the full, replayable description of one trial (see ARCHITECTURE.md)."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|
8
|
+
|
|
9
|
+
from pydantic import (
|
|
10
|
+
BaseModel,
|
|
11
|
+
ConfigDict,
|
|
12
|
+
Field,
|
|
13
|
+
field_serializer,
|
|
14
|
+
field_validator,
|
|
15
|
+
model_validator,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _Model(BaseModel):
|
|
20
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class OrderSpec(_Model):
|
|
24
|
+
"""How to order `TrialConfig.nodeids`. `explicit` = exactly as listed there (D13)."""
|
|
25
|
+
|
|
26
|
+
mode: Literal["collection", "shuffle", "explicit"] = "collection"
|
|
27
|
+
seed: int | None = None # shuffle only
|
|
28
|
+
|
|
29
|
+
@model_validator(mode="after")
|
|
30
|
+
def _seed_iff_shuffle(self) -> "OrderSpec":
|
|
31
|
+
if (self.mode == "shuffle") != (self.seed is not None):
|
|
32
|
+
raise ValueError("order.seed is required for mode 'shuffle' and only allowed there")
|
|
33
|
+
return self
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ClockSpec(_Model):
|
|
37
|
+
instant: datetime | None = None # None = real clock; stored normalised to UTC
|
|
38
|
+
tick: bool = True
|
|
39
|
+
|
|
40
|
+
@field_validator("instant")
|
|
41
|
+
@classmethod
|
|
42
|
+
def _aware_utc(cls, v: datetime | None) -> datetime | None:
|
|
43
|
+
if v is None:
|
|
44
|
+
return None
|
|
45
|
+
if v.tzinfo is None:
|
|
46
|
+
raise ValueError("clock.instant must be timezone-aware (naive depends on TZ)")
|
|
47
|
+
return v.astimezone(timezone.utc)
|
|
48
|
+
|
|
49
|
+
@field_serializer("instant")
|
|
50
|
+
def _iso(self, v: datetime | None) -> str | None:
|
|
51
|
+
# stdlib isoformat, not pydantic's: config_id must not change across pydantic versions
|
|
52
|
+
return None if v is None else v.isoformat()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class TrialConfig(_Model):
|
|
56
|
+
nodeids: list[str] = Field(min_length=1) # what to run; also the order if order=explicit
|
|
57
|
+
order: OrderSpec = OrderSpec()
|
|
58
|
+
hash_seed: int | None = Field(default=None, ge=0, le=2**32 - 1) # None = PYTHONHASHSEED unset
|
|
59
|
+
random_seed: int | None = None
|
|
60
|
+
clock: ClockSpec = ClockSpec()
|
|
61
|
+
tz: str | None = None # IANA name; None = inherit
|
|
62
|
+
timeout_s: float = Field(default=120, gt=0)
|
|
63
|
+
|
|
64
|
+
@field_validator("tz")
|
|
65
|
+
@classmethod
|
|
66
|
+
def _known_tz(cls, v: str | None) -> str | None:
|
|
67
|
+
if v is not None:
|
|
68
|
+
try:
|
|
69
|
+
ZoneInfo(v)
|
|
70
|
+
except (ZoneInfoNotFoundError, ValueError) as e:
|
|
71
|
+
raise ValueError(f"unknown time zone {v!r}") from e
|
|
72
|
+
return v
|
|
73
|
+
|
|
74
|
+
def canonical_json(self) -> str:
|
|
75
|
+
data: dict[str, Any] = self.model_dump(mode="json")
|
|
76
|
+
return json.dumps(data, sort_keys=True, separators=(",", ":"))
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def config_id(self) -> str:
|
|
80
|
+
return hashlib.sha256(self.canonical_json().encode()).hexdigest()[:16]
|