fusiontest 0.2.20__tar.gz → 0.2.22__tar.gz

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 (57) hide show
  1. {fusiontest-0.2.20 → fusiontest-0.2.22}/PKG-INFO +1 -1
  2. fusiontest-0.2.22/fusiontest/bench/__init__.py +663 -0
  3. fusiontest-0.2.22/fusiontest/bench/sites/shop/bugs.js +3 -0
  4. fusiontest-0.2.22/fusiontest/bench/sites/shop/help.html +14 -0
  5. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/bench/sites/shop/index.html +70 -10
  6. fusiontest-0.2.22/fusiontest/bench/suites/shop-bugs.yaml +70 -0
  7. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/cli.py +93 -13
  8. fusiontest-0.2.22/fusiontest/core/app_errors.py +95 -0
  9. fusiontest-0.2.22/fusiontest/core/promise_checker.py +258 -0
  10. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/core/runner.py +79 -1
  11. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/desktop/playwright_adapter.py +66 -0
  12. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest.egg-info/PKG-INFO +1 -1
  13. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest.egg-info/SOURCES.txt +5 -0
  14. {fusiontest-0.2.20 → fusiontest-0.2.22}/pyproject.toml +1 -1
  15. fusiontest-0.2.20/fusiontest/bench/__init__.py +0 -347
  16. {fusiontest-0.2.20 → fusiontest-0.2.22}/README.md +0 -0
  17. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/__init__.py +0 -0
  18. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/bench/suites/shop.yaml +0 -0
  19. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/bench/suites/todomvc.yaml +0 -0
  20. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/core/__init__.py +0 -0
  21. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/core/action_model.py +0 -0
  22. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/core/goal_verifier.py +0 -0
  23. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/core/netguard.py +0 -0
  24. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/core/replay.py +0 -0
  25. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/core/screen_parser.py +0 -0
  26. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/core/secrets.py +0 -0
  27. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/core/shared_traces.py +0 -0
  28. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/core/tokens.py +0 -0
  29. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/demos/__init__.py +0 -0
  30. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/demos/fusiontest_dashboard.yaml +0 -0
  31. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/demos/github.yaml +0 -0
  32. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/demos/hacker_news.yaml +0 -0
  33. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/demos/httpbin.yaml +0 -0
  34. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/demos/todomvc.yaml +0 -0
  35. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/demos/wikipedia.yaml +0 -0
  36. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/desktop/__init__.py +0 -0
  37. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/desktop/macos_adapter.py +0 -0
  38. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/desktop/windows_adapter.py +0 -0
  39. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/discovery/__init__.py +0 -0
  40. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/discovery/goal_generator.py +0 -0
  41. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/guardrails/__init__.py +0 -0
  42. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/guardrails/engine.py +0 -0
  43. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/mobile/__init__.py +0 -0
  44. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/mobile/android_adapter.py +0 -0
  45. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/mobile/ios_adapter.py +0 -0
  46. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/reporting/__init__.py +0 -0
  47. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/reporting/reporter.py +0 -0
  48. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/training/__init__.py +0 -0
  49. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/training/data_collector.py +0 -0
  50. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/training/dataset_builder.py +0 -0
  51. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest/training/trainer.py +0 -0
  52. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest.egg-info/dependency_links.txt +0 -0
  53. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest.egg-info/entry_points.txt +0 -0
  54. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest.egg-info/not-zip-safe +0 -0
  55. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest.egg-info/requires.txt +0 -0
  56. {fusiontest-0.2.20 → fusiontest-0.2.22}/fusiontest.egg-info/top_level.txt +0 -0
  57. {fusiontest-0.2.20 → fusiontest-0.2.22}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fusiontest
3
- Version: 0.2.20
3
+ Version: 0.2.22
4
4
  Summary: AI-powered UI testing for mobile and desktop — by FusionLeap.io
5
5
  Author-email: FusionLeap <hello@fusionleap.io>
6
6
  License: MIT
@@ -0,0 +1,663 @@
1
+ """
2
+ fusiontest.bench — the evaluation harness (ADR-008 Phase 1).
3
+
4
+ A *suite* is an ordered list of goals with a known expected outcome
5
+ (`expect: pass | fail`). Running a suite against a backend, with replay off so
6
+ the model is what's measured, scores each case:
7
+
8
+ correct outcome matches the expectation
9
+ false_pass expected fail, got pass (the worst error for a testing product)
10
+ false_fail expected pass, got fail
11
+ error couldn't be evaluated (LLM capacity, infra) — neither right nor wrong
12
+
13
+ Suites ship in fusiontest/bench/suites/. A suite either names a public `url`
14
+ or a local fixture `site` (fusiontest/bench/sites/<site>/), which is served
15
+ from 127.0.0.1 for the duration of the run so results don't drift.
16
+
17
+ A *bug suite* (`kind: bugs`, ADR-009) measures bug finding instead. It runs
18
+ the same neutral tasks on several variants of a fixture site, each with
19
+ different planted bugs (or none), and matches what FusionTest reports against
20
+ what was planted:
21
+
22
+ precision reports that match a planted bug ÷ all reports
23
+ recall planted bugs found ÷ planted bugs
24
+ false bugs reports on clean variants — must stay at zero
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import functools
30
+ import http.server
31
+ import json
32
+ import threading
33
+ from collections.abc import Callable, Iterator
34
+ from contextlib import contextmanager
35
+ from dataclasses import asdict, dataclass, field
36
+ from importlib.resources import as_file, files
37
+ from pathlib import Path
38
+
39
+ import yaml
40
+
41
+ from fusiontest.core.runner import FusionTestRunner, RunnerConfig, RunResult, StepResult
42
+
43
+ EXPECTATIONS = ("pass", "fail")
44
+ BUG_KINDS = ("universal", "broken_promise", "inconsistency", "regression")
45
+
46
+
47
+ # ── Suites ─────────────────────────────────────────────────────────────────────
48
+
49
+ @dataclass
50
+ class Case:
51
+ goal: str
52
+ expect: str
53
+
54
+
55
+ @dataclass
56
+ class Suite:
57
+ name: str
58
+ cases: list[Case]
59
+ version: int = 1
60
+ description: str = ""
61
+ platform: str = "playwright"
62
+ url: str = "" # public site …
63
+ site: str = "" # … or a fixture served locally
64
+
65
+
66
+ @dataclass
67
+ class PlantedBug:
68
+ id: str
69
+ kind: str
70
+ description: str
71
+ match: list[str] # keywords; a report mentioning them is about this bug
72
+
73
+
74
+ @dataclass
75
+ class Variant:
76
+ name: str
77
+ bugs: list[str]
78
+
79
+
80
+ @dataclass
81
+ class BugSuite:
82
+ name: str
83
+ tasks: list[str]
84
+ bugs: dict[str, PlantedBug]
85
+ variants: list[Variant]
86
+ version: int = 1
87
+ description: str = ""
88
+ platform: str = "playwright"
89
+ site: str = ""
90
+ kind: str = "bugs"
91
+
92
+
93
+ def builtin_suites() -> list[str]:
94
+ return sorted(p.name[:-5] for p in files("fusiontest.bench").joinpath("suites").iterdir()
95
+ if p.name.endswith(".yaml"))
96
+
97
+
98
+ def load_suite(name_or_path: str) -> Suite | BugSuite:
99
+ """A built-in suite by name, or a suite YAML file by path."""
100
+ path = Path(name_or_path)
101
+ if path.suffix in (".yaml", ".yml") and path.exists():
102
+ text = path.read_text()
103
+ else:
104
+ resource = files("fusiontest.bench").joinpath("suites", f"{name_or_path}.yaml")
105
+ if not resource.is_file():
106
+ raise ValueError(f"Unknown suite {name_or_path!r} (built-in: {', '.join(builtin_suites())})")
107
+ text = resource.read_text()
108
+ data = yaml.safe_load(text) or {}
109
+ if data.get("kind") == "bugs":
110
+ return _load_bug_suite(data, name_or_path)
111
+ cases = []
112
+ for i, raw in enumerate(data.get("cases") or [], 1):
113
+ expect = str(raw.get("expect", "")).lower()
114
+ if expect not in EXPECTATIONS or not raw.get("goal"):
115
+ raise ValueError(f"Suite {data.get('name')!r} case {i}: needs a goal and expect: pass|fail")
116
+ cases.append(Case(goal=str(raw["goal"]), expect=expect))
117
+ if not cases:
118
+ raise ValueError(f"Suite {name_or_path!r} has no cases")
119
+ if bool(data.get("url")) == bool(data.get("site")):
120
+ raise ValueError(f"Suite {name_or_path!r} needs exactly one of url / site")
121
+ return Suite(
122
+ name=str(data.get("name") or path.stem), cases=cases, version=int(data.get("version", 1)),
123
+ description=str(data.get("description", "")), platform=str(data.get("platform", "playwright")),
124
+ url=str(data.get("url", "")), site=str(data.get("site", "")),
125
+ )
126
+
127
+
128
+ def _load_bug_suite(data: dict, source: str) -> BugSuite:
129
+ name = str(data.get("name") or Path(source).stem)
130
+
131
+ def bad(msg: str) -> ValueError:
132
+ return ValueError(f"Bug suite {name!r}: {msg}")
133
+
134
+ if not data.get("site"):
135
+ raise bad("needs a fixture site (planted bugs are switched on by the benchmark server)")
136
+ tasks = [str(t) for t in data.get("tasks") or []]
137
+ if not tasks:
138
+ raise bad("has no tasks")
139
+ bugs = {}
140
+ for bug_id, raw in (data.get("bugs") or {}).items():
141
+ kind = str((raw or {}).get("kind", ""))
142
+ match = [str(k).lower() for k in (raw or {}).get("match") or []]
143
+ if kind not in BUG_KINDS or not match:
144
+ raise bad(f"bug {bug_id!r} needs a kind ({' | '.join(BUG_KINDS)}) and match keywords")
145
+ bugs[str(bug_id)] = PlantedBug(id=str(bug_id), kind=kind,
146
+ description=str(raw.get("description", "")), match=match)
147
+ variants = []
148
+ for raw in data.get("variants") or []:
149
+ variant = Variant(name=str(raw.get("name", "")), bugs=[str(b) for b in raw.get("bugs") or []])
150
+ unknown = [b for b in variant.bugs if b not in bugs]
151
+ if not variant.name or unknown:
152
+ raise bad(f"variant {variant.name or '?'!r} needs a name and known bugs (unknown: {unknown})")
153
+ shared = _shared_keywords([bugs[b] for b in variant.bugs])
154
+ if shared:
155
+ raise bad(f"variant {variant.name!r}: bugs share match keywords {sorted(shared)}, "
156
+ "so a report can't be attributed")
157
+ variants.append(variant)
158
+ if not any(not v.bugs for v in variants):
159
+ raise bad("needs a clean variant (no bugs), or false bugs go unmeasured")
160
+ unplanted = set(bugs) - {b for v in variants for b in v.bugs}
161
+ if unplanted:
162
+ raise bad(f"bugs never planted in a variant: {sorted(unplanted)}")
163
+ return BugSuite(name=name, tasks=tasks, bugs=bugs, variants=variants,
164
+ version=int(data.get("version", 1)), description=str(data.get("description", "")),
165
+ platform=str(data.get("platform", "playwright")), site=str(data["site"]))
166
+
167
+
168
+ def _shared_keywords(bugs: list[PlantedBug]) -> set[str]:
169
+ seen: set[str] = set()
170
+ shared: set[str] = set()
171
+ for bug in bugs:
172
+ shared |= seen & set(bug.match)
173
+ seen |= set(bug.match)
174
+ return shared
175
+
176
+
177
+ # ── Fixture server ─────────────────────────────────────────────────────────────
178
+
179
+ class _FixtureHandler(http.server.SimpleHTTPRequestHandler):
180
+ """Static files, plus the server side of planted bugs (ADR-009).
181
+
182
+ bugs.js tells the page which bugs are on; api/order takes orders (or fails
183
+ with 500 under checkout-500); help.html is missing under dead-link.
184
+ """
185
+
186
+ bugs: frozenset[str] = frozenset()
187
+
188
+ def __init__(self, *args, bugs: frozenset[str] = frozenset(), **kwargs):
189
+ self.bugs = bugs
190
+ super().__init__(*args, **kwargs)
191
+
192
+ def do_GET(self) -> None: # noqa: N802 — http.server naming
193
+ path = self.path.split("?", 1)[0]
194
+ if path == "/bugs.js":
195
+ self._send(200, "text/javascript",
196
+ f"window.PLANTED_BUGS = {json.dumps(sorted(self.bugs))};\n")
197
+ elif path == "/help.html" and "dead-link" in self.bugs:
198
+ self.send_error(404, "Not Found")
199
+ else:
200
+ super().do_GET()
201
+
202
+ def do_POST(self) -> None: # noqa: N802
203
+ self.rfile.read(int(self.headers.get("Content-Length") or 0))
204
+ if self.path.split("?", 1)[0] != "/api/order":
205
+ self.send_error(404, "Not Found")
206
+ elif "checkout-500" in self.bugs:
207
+ self._send(500, "application/json", '{"error": "internal server error"}')
208
+ else:
209
+ self._send(200, "application/json", '{"order": "ACME-1001"}')
210
+
211
+ def _send(self, status: int, content_type: str, body: str) -> None:
212
+ data = body.encode()
213
+ self.send_response(status)
214
+ self.send_header("Content-Type", content_type)
215
+ self.send_header("Content-Length", str(len(data)))
216
+ self.send_header("Cache-Control", "no-store")
217
+ self.end_headers()
218
+ self.wfile.write(data)
219
+
220
+ def log_message(self, *args) -> None: # keep benchmark output clean
221
+ pass
222
+
223
+
224
+ @contextmanager
225
+ def serve_site(site: str, bugs: tuple[str, ...] | list[str] = ()) -> Iterator[str]:
226
+ """Serve fusiontest/bench/sites/<site>/ on 127.0.0.1; yields its base URL.
227
+
228
+ bugs: planted bugs to switch on for this session (ADR-009); none by default.
229
+ """
230
+ with as_file(files("fusiontest.bench").joinpath("sites", site)) as root:
231
+ if not (root / "index.html").is_file():
232
+ raise ValueError(f"Unknown fixture site {site!r}")
233
+ handler = functools.partial(_FixtureHandler, directory=str(root), bugs=frozenset(bugs))
234
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
235
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
236
+ thread.start()
237
+ try:
238
+ yield f"http://127.0.0.1:{server.server_address[1]}/index.html"
239
+ finally:
240
+ server.shutdown()
241
+ server.server_close()
242
+
243
+
244
+ # ── Scoring ────────────────────────────────────────────────────────────────────
245
+
246
+ @dataclass
247
+ class CaseResult:
248
+ goal: str
249
+ expect: str
250
+ outcome: str # pass | fail | error | not_run
251
+ steps: int = 0
252
+ seconds: float = 0.0
253
+ tokens: int = 0
254
+ input_tokens: int = 0
255
+ output_tokens: int = 0
256
+ error: str = ""
257
+ actions: list[str] = field(default_factory=list) # what the model did (secrets redacted)
258
+
259
+ @property
260
+ def correct(self) -> bool:
261
+ return self.outcome == self.expect
262
+
263
+
264
+ def score_cases(suite: Suite, run: RunResult) -> list[CaseResult]:
265
+ """Pair each case with its goal result; cases after an early stop are not_run."""
266
+ results: list[CaseResult] = []
267
+ for i, case in enumerate(suite.cases):
268
+ step: StepResult | None = run.steps[i] if i < len(run.steps) else None
269
+ if step is None:
270
+ results.append(CaseResult(case.goal, case.expect, "not_run", error=run.error))
271
+ continue
272
+ outcome = "error" if step.infra_error else ("pass" if step.success else "fail")
273
+ results.append(CaseResult(
274
+ goal=case.goal, expect=case.expect, outcome=outcome, steps=step.steps_taken,
275
+ seconds=round(step.duration_seconds, 2), tokens=step.token_usage.total_tokens,
276
+ input_tokens=step.token_usage.input_tokens, output_tokens=step.token_usage.output_tokens,
277
+ error=step.error, actions=list(step.actions),
278
+ ))
279
+ return results
280
+
281
+
282
+ @dataclass
283
+ class SuiteRun:
284
+ suite: str
285
+ suite_version: int
286
+ backend: str
287
+ repeat: int
288
+ cases: list[CaseResult]
289
+ llm_calls: dict[str, int] = field(default_factory=dict)
290
+ seconds: float = 0.0
291
+ cost_usd: float | None = None # None when the model's price isn't known
292
+ stopped_for_budget: bool = False
293
+
294
+ def to_dict(self) -> dict:
295
+ return {**asdict(self), "cases": [{**asdict(c), "correct": c.correct} for c in self.cases]}
296
+
297
+
298
+ @dataclass
299
+ class Summary:
300
+ """Aggregate over the repeats of one suite × backend."""
301
+ suite: str
302
+ backend: str
303
+ runs: int
304
+ cases: int
305
+ evaluated: int
306
+ correct: int
307
+ false_pass: int
308
+ false_fail: int
309
+ errors: int
310
+ consistent: int # cases with the same outcome in every repeat
311
+ steps_per_case: float
312
+ calls_per_case: float
313
+ tokens_per_case: float
314
+ seconds_per_case: float
315
+
316
+ @property
317
+ def accuracy(self) -> float:
318
+ return self.correct / self.evaluated if self.evaluated else 0.0
319
+
320
+ def to_dict(self) -> dict:
321
+ return {**asdict(self), "accuracy": round(self.accuracy, 4)}
322
+
323
+
324
+ def summarize(runs: list[SuiteRun]) -> Summary:
325
+ all_cases = [c for r in runs for c in r.cases]
326
+ evaluated = [c for c in all_cases if c.outcome in EXPECTATIONS]
327
+ per_case = len(runs[0].cases) if runs else 0
328
+ consistent = sum(
329
+ 1 for i in range(per_case)
330
+ if len({r.cases[i].outcome for r in runs}) == 1 and runs[0].cases[i].outcome in EXPECTATIONS
331
+ )
332
+ n = len(all_cases) or 1
333
+ return Summary(
334
+ suite=runs[0].suite if runs else "", backend=runs[0].backend if runs else "",
335
+ runs=len(runs), cases=len(all_cases), evaluated=len(evaluated),
336
+ correct=sum(c.correct for c in evaluated),
337
+ false_pass=sum(c.expect == "fail" and c.outcome == "pass" for c in evaluated),
338
+ false_fail=sum(c.expect == "pass" and c.outcome == "fail" for c in evaluated),
339
+ errors=len(all_cases) - len(evaluated),
340
+ consistent=consistent,
341
+ steps_per_case=round(sum(c.steps for c in all_cases) / n, 2),
342
+ calls_per_case=round(sum(sum(r.llm_calls.values()) for r in runs) / n, 2),
343
+ tokens_per_case=round(sum(c.tokens for c in all_cases) / n, 1),
344
+ seconds_per_case=round(sum(c.seconds for c in all_cases) / n, 2),
345
+ )
346
+
347
+
348
+ # ── Bug scoring (ADR-009) ──────────────────────────────────────────────────────
349
+
350
+ def match_report(report: str, planted: list[PlantedBug]) -> str | None:
351
+ """The planted bug a report is about: the one whose keywords it mentions most."""
352
+ text = report.lower()
353
+ best, best_hits = None, 0
354
+ for bug in planted:
355
+ hits = sum(keyword in text for keyword in bug.match)
356
+ if hits > best_hits:
357
+ best, best_hits = bug.id, hits
358
+ return best
359
+
360
+
361
+ @dataclass
362
+ class VariantResult:
363
+ variant: str
364
+ planted: list[str]
365
+ outcome: str = "run" # run | error | not_run
366
+ reports: list[str] = field(default_factory=list) # bugs FusionTest reported
367
+ matches: list[str | None] = field(default_factory=list) # planted id per report, or None
368
+ tasks_passed: int = 0
369
+ tasks: int = 0
370
+ failed_tasks: list[str] = field(default_factory=list) # "task — why", for diagnosis
371
+ seconds: float = 0.0
372
+ tokens: int = 0
373
+ error: str = ""
374
+
375
+ @property
376
+ def found(self) -> list[str]:
377
+ return [b for b in self.planted if b in self.matches]
378
+
379
+ @property
380
+ def false_reports(self) -> int:
381
+ return sum(m is None for m in self.matches)
382
+
383
+
384
+ def score_variant(suite: BugSuite, variant: Variant, run: RunResult) -> VariantResult:
385
+ planted = [suite.bugs[b] for b in variant.bugs]
386
+ reports = [str(r) for r in run.bugs_detected]
387
+ evaluated = run.steps and not run.errored
388
+ return VariantResult(
389
+ variant=variant.name, planted=list(variant.bugs),
390
+ outcome="run" if evaluated else "error",
391
+ reports=reports, matches=[match_report(r, planted) for r in reports],
392
+ tasks_passed=sum(s.success for s in run.steps), tasks=len(suite.tasks),
393
+ failed_tasks=[f"{s.goal} — {s.error}" for s in run.steps if not s.success],
394
+ seconds=round(sum(s.duration_seconds for s in run.steps), 2),
395
+ tokens=sum(s.token_usage.total_tokens for s in run.steps),
396
+ error=run.error or next((s.error for s in run.steps if s.infra_error), ""),
397
+ )
398
+
399
+
400
+ @dataclass
401
+ class BugSuiteRun:
402
+ suite: str
403
+ suite_version: int
404
+ backend: str
405
+ repeat: int
406
+ variants: list[VariantResult]
407
+ llm_calls: dict[str, int] = field(default_factory=dict)
408
+ seconds: float = 0.0
409
+ cost_usd: float | None = None
410
+ stopped_for_budget: bool = False
411
+
412
+ def to_dict(self) -> dict:
413
+ return {**asdict(self), "variants": [
414
+ {**asdict(v), "found": v.found, "false_reports": v.false_reports} for v in self.variants]}
415
+
416
+
417
+ @dataclass
418
+ class BugSummary:
419
+ """Bug finding over the repeats of one bug suite × backend.
420
+
421
+ Variants that errored (LLM capacity, infra) or didn't run are left out:
422
+ neither their reports nor their planted bugs count.
423
+ """
424
+ suite: str
425
+ backend: str
426
+ runs: int
427
+ variants: int # evaluated variant runs
428
+ errors: int # variant runs not evaluated
429
+ planted: int
430
+ found: int
431
+ reports: int
432
+ true_reports: int
433
+ false_reports: int
434
+ false_on_clean: int # reports on variants with nothing planted
435
+
436
+ @property
437
+ def precision(self) -> float | None:
438
+ return self.true_reports / self.reports if self.reports else None
439
+
440
+ @property
441
+ def recall(self) -> float:
442
+ return self.found / self.planted if self.planted else 0.0
443
+
444
+ def to_dict(self) -> dict:
445
+ precision = self.precision
446
+ return {**asdict(self), "precision": None if precision is None else round(precision, 4),
447
+ "recall": round(self.recall, 4)}
448
+
449
+
450
+ def summarize_bugs(runs: list[BugSuiteRun]) -> BugSummary:
451
+ all_variants = [v for r in runs for v in r.variants]
452
+ evaluated = [v for v in all_variants if v.outcome == "run"]
453
+ reports = sum(len(v.reports) for v in evaluated)
454
+ false_reports = sum(v.false_reports for v in evaluated)
455
+ return BugSummary(
456
+ suite=runs[0].suite if runs else "", backend=runs[0].backend if runs else "",
457
+ runs=len(runs), variants=len(evaluated), errors=len(all_variants) - len(evaluated),
458
+ planted=sum(len(v.planted) for v in evaluated), found=sum(len(v.found) for v in evaluated),
459
+ reports=reports, true_reports=reports - false_reports, false_reports=false_reports,
460
+ false_on_clean=sum(len(v.reports) for v in evaluated if not v.planted),
461
+ )
462
+
463
+
464
+ # ── Cost ───────────────────────────────────────────────────────────────────────
465
+
466
+ # USD per million tokens (input, output) for the model each backend is pinned to.
467
+ # Anthropic list prices; keep in step with default_model_for_backend(). Backends
468
+ # without an entry (free-tier Groq, local Ollama, …) have no known cost and can't
469
+ # run under a cost limit.
470
+ PRICES_PER_MTOK: dict[str, tuple[float, float]] = {
471
+ "claude-sonnet-4-6": (3.00, 15.00),
472
+ }
473
+
474
+
475
+ def model_price(backend: str) -> tuple[float, float] | None:
476
+ from fusiontest.core.action_model import default_model_for_backend
477
+ return PRICES_PER_MTOK.get(default_model_for_backend(backend))
478
+
479
+
480
+ def cost_of(input_tokens: int, output_tokens: int, price: tuple[float, float]) -> float:
481
+ return (input_tokens * price[0] + output_tokens * price[1]) / 1_000_000
482
+
483
+
484
+ class Ledger:
485
+ """Month-to-date benchmark spend, persisted as JSON (CI keeps it in the cache).
486
+
487
+ A new calendar month (UTC) starts from zero.
488
+ """
489
+
490
+ def __init__(self, path: Path, month: str):
491
+ self.path, self.month = path, month
492
+ self.spent_usd, self.runs = 0.0, 0
493
+ try:
494
+ data = json.loads(path.read_text())
495
+ except (OSError, ValueError):
496
+ data = {}
497
+ if data.get("month") == month:
498
+ self.spent_usd = float(data.get("spent_usd", 0.0))
499
+ self.runs = int(data.get("runs", 0))
500
+
501
+ def add(self, usd: float) -> None:
502
+ self.spent_usd = round(self.spent_usd + usd, 4)
503
+ self.runs += 1
504
+ self.path.parent.mkdir(parents=True, exist_ok=True)
505
+ self.path.write_text(json.dumps(
506
+ {"month": self.month, "spent_usd": self.spent_usd, "runs": self.runs}, indent=2))
507
+
508
+
509
+ # ── Running ────────────────────────────────────────────────────────────────────
510
+
511
+ AdapterFactory = Callable[[str, str], object] # (platform, url) -> started adapter
512
+
513
+
514
+ def run_suite(
515
+ suite: Suite,
516
+ backend: str,
517
+ adapter_factory: AdapterFactory,
518
+ repeat: int = 1,
519
+ runner_factory: Callable[..., FusionTestRunner] = FusionTestRunner,
520
+ max_cost_usd: float | None = None,
521
+ ) -> SuiteRun:
522
+ """One pass over the suite in a fresh app session.
523
+
524
+ Replay is off (no trace store) and the backend is pinned to its default
525
+ model with no fallback, so the model named is the model measured. When it
526
+ is rate-limited, cases become errors — reported, but not scored.
527
+
528
+ max_cost_usd: stop before the next case once this run's spend reaches it
529
+ (the remaining cases are reported as not run). Requires a priced model.
530
+ """
531
+ price = _price_for_limit(backend, max_cost_usd)
532
+ session = _session(suite.site, suite.url, suite.platform, [c.goal for c in suite.cases],
533
+ f"bench:{suite.name}", backend, adapter_factory, runner_factory,
534
+ price, max_cost_usd)
535
+ return SuiteRun(suite=suite.name, suite_version=suite.version, backend=backend, repeat=repeat,
536
+ cases=score_cases(suite, session.run), llm_calls=dict(session.run.llm_calls),
537
+ seconds=session.seconds,
538
+ cost_usd=round(session.spent, 4) if price is not None else None,
539
+ stopped_for_budget=session.cancelled)
540
+
541
+
542
+ def run_bug_suite(
543
+ suite: BugSuite,
544
+ backend: str,
545
+ adapter_factory: AdapterFactory,
546
+ repeat: int = 1,
547
+ runner_factory: Callable[..., FusionTestRunner] = FusionTestRunner,
548
+ max_cost_usd: float | None = None,
549
+ ) -> BugSuiteRun:
550
+ """Run the suite's tasks once per variant, each in a fresh session with
551
+ that variant's bugs switched on, and score what FusionTest reported.
552
+
553
+ Same conditions as run_suite (replay off, backend pinned). max_cost_usd
554
+ covers all variants; once it's spent, the remaining variants don't run.
555
+ """
556
+ price = _price_for_limit(backend, max_cost_usd)
557
+ spent, seconds, stopped = 0.0, 0.0, False
558
+ calls: dict[str, int] = {}
559
+ results: list[VariantResult] = []
560
+ for variant in suite.variants:
561
+ left = None if max_cost_usd is None else max_cost_usd - spent
562
+ if stopped or (left is not None and left <= 0):
563
+ stopped = True
564
+ results.append(VariantResult(variant=variant.name, planted=list(variant.bugs),
565
+ outcome="not_run", tasks=len(suite.tasks)))
566
+ continue
567
+ session = _session(suite.site, "", suite.platform, suite.tasks,
568
+ f"bench:{suite.name}:{variant.name}", backend, adapter_factory,
569
+ runner_factory, price, left, bugs=variant.bugs, detect_bugs=True)
570
+ result = score_variant(suite, variant, session.run)
571
+ if session.cancelled:
572
+ stopped = True
573
+ if len(session.run.steps) < len(suite.tasks): # stopped part-way: not scored
574
+ result.outcome = "not_run"
575
+ results.append(result)
576
+ spent += session.spent
577
+ seconds += session.seconds
578
+ for key, n in session.run.llm_calls.items():
579
+ calls[key] = calls.get(key, 0) + n
580
+ return BugSuiteRun(suite=suite.name, suite_version=suite.version, backend=backend,
581
+ repeat=repeat, variants=results, llm_calls=calls, seconds=round(seconds, 1),
582
+ cost_usd=round(spent, 4) if price is not None else None,
583
+ stopped_for_budget=stopped)
584
+
585
+
586
+ def _price_for_limit(backend: str, max_cost_usd: float | None) -> tuple[float, float] | None:
587
+ price = model_price(backend)
588
+ if max_cost_usd is not None and price is None:
589
+ raise ValueError(f"No price known for {backend}'s model; can't enforce a cost limit")
590
+ return price
591
+
592
+
593
+ @dataclass
594
+ class _Session:
595
+ run: RunResult
596
+ seconds: float
597
+ spent: float
598
+ cancelled: bool
599
+
600
+
601
+ def _session(site: str, url: str, platform: str, goals: list[str], name: str, backend: str,
602
+ adapter_factory: AdapterFactory, runner_factory: Callable[..., FusionTestRunner],
603
+ price: tuple[float, float] | None, max_cost_usd: float | None,
604
+ bugs: list[str] | tuple[str, ...] = (), detect_bugs: bool = False) -> _Session:
605
+ """Run goals in order in one fresh app session, replay off, backend pinned."""
606
+ import time
607
+
608
+ spent = 0.0
609
+ cancel = threading.Event()
610
+
611
+ def on_goal_done(_i: int, _n: int, step: StepResult) -> None:
612
+ nonlocal spent
613
+ if price is not None:
614
+ spent += cost_of(step.token_usage.input_tokens, step.token_usage.output_tokens, price)
615
+ if max_cost_usd is not None and spent >= max_cost_usd:
616
+ cancel.set()
617
+
618
+ with (serve_site(site, bugs) if site else _nullcontext(url)) as start_url, \
619
+ _pinned_chain(backend):
620
+ adapter = adapter_factory(platform, start_url)
621
+ try:
622
+ runner = runner_factory(adapter, RunnerConfig(
623
+ backend=backend, trace_store=None, screenshot_on_failure=False,
624
+ detect_bugs=detect_bugs,
625
+ ))
626
+ start = time.time()
627
+ # No url= here: the runner would reload it before every goal, and
628
+ # goals share state (signed in, cart contents).
629
+ run = runner.run(goals=goals, name=name, platform=platform,
630
+ on_goal_done=on_goal_done, cancel_event=cancel)
631
+ elapsed = time.time() - start
632
+ finally:
633
+ stop = getattr(adapter, "stop", None)
634
+ if callable(stop):
635
+ try:
636
+ stop()
637
+ except Exception: # noqa: BLE001 — the browser may already be gone
638
+ pass
639
+ return _Session(run=run, seconds=round(elapsed, 1), spent=spent, cancelled=cancel.is_set())
640
+
641
+
642
+ @contextmanager
643
+ def _nullcontext(value: str) -> Iterator[str]:
644
+ yield value
645
+
646
+
647
+ @contextmanager
648
+ def _pinned_chain(backend: str) -> Iterator[None]:
649
+ """No fallback during a benchmark run: LLMCaller reads FUSIONTEST_FALLBACK_CHAIN."""
650
+ import os
651
+
652
+ from fusiontest.core.action_model import default_model_for_backend
653
+
654
+ previous = os.environ.get("FUSIONTEST_FALLBACK_CHAIN")
655
+ model = default_model_for_backend(backend)
656
+ os.environ["FUSIONTEST_FALLBACK_CHAIN"] = f"{backend}:{model}" if model else backend
657
+ try:
658
+ yield
659
+ finally:
660
+ if previous is None:
661
+ os.environ.pop("FUSIONTEST_FALLBACK_CHAIN", None)
662
+ else:
663
+ os.environ["FUSIONTEST_FALLBACK_CHAIN"] = previous
@@ -0,0 +1,3 @@
1
+ // Planted bugs to turn on (ADR-009). Empty: the shop works as designed.
2
+ // `fusiontest bench` serves its own copy of this file for each suite variant.
3
+ window.PLANTED_BUGS = [];
@@ -0,0 +1,14 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>Help · Acme Shop</title>
6
+ <style>body { font-family: system-ui, sans-serif; margin: 2rem auto; max-width: 720px; color: #1d1d1f; }</style>
7
+ </head>
8
+ <body>
9
+ <h1>Help centre</h1>
10
+ <p>Orders ship within two working days. Standard shipping is free; Express costs $9.00.</p>
11
+ <p>Coupon codes are entered in your cart. Questions? Email help@acme.test.</p>
12
+ <p><a href="index.html">Back to Acme Shop</a></p>
13
+ </body>
14
+ </html>