stackdoctor-cli 1.0.1__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 (40) hide show
  1. stackdoctor/__init__.py +15 -0
  2. stackdoctor/__main__.py +6 -0
  3. stackdoctor/agent/__init__.py +5 -0
  4. stackdoctor/agent/compaction.py +66 -0
  5. stackdoctor/agent/diagnosis.py +398 -0
  6. stackdoctor/agent/loop.py +801 -0
  7. stackdoctor/agent/prompts.py +85 -0
  8. stackdoctor/agent/providers/__init__.py +295 -0
  9. stackdoctor/agent/providers/base.py +210 -0
  10. stackdoctor/agent/providers/claude.py +285 -0
  11. stackdoctor/agent/providers/gemini.py +312 -0
  12. stackdoctor/agent/providers/openai_compat.py +537 -0
  13. stackdoctor/agent/providers/prices.py +90 -0
  14. stackdoctor/benchmark/__init__.py +11 -0
  15. stackdoctor/benchmark/__main__.py +198 -0
  16. stackdoctor/benchmark/holmes.py +386 -0
  17. stackdoctor/benchmark/report.py +362 -0
  18. stackdoctor/benchmark/runner.py +710 -0
  19. stackdoctor/benchmark/scenarios.py +153 -0
  20. stackdoctor/benchmark/scoring.py +184 -0
  21. stackdoctor/cli.py +882 -0
  22. stackdoctor/dependencies.py +221 -0
  23. stackdoctor/discovery.py +361 -0
  24. stackdoctor/evidence.py +134 -0
  25. stackdoctor/github.py +168 -0
  26. stackdoctor/live.py +808 -0
  27. stackdoctor/mcp_server.py +233 -0
  28. stackdoctor/models.py +275 -0
  29. stackdoctor/pglog.py +55 -0
  30. stackdoctor/postgres.py +294 -0
  31. stackdoctor/probes.py +172 -0
  32. stackdoctor/py.typed +0 -0
  33. stackdoctor/redaction.py +215 -0
  34. stackdoctor/rules.py +303 -0
  35. stackdoctor/validation.py +61 -0
  36. stackdoctor_cli-1.0.1.dist-info/METADATA +177 -0
  37. stackdoctor_cli-1.0.1.dist-info/RECORD +40 -0
  38. stackdoctor_cli-1.0.1.dist-info/WHEEL +4 -0
  39. stackdoctor_cli-1.0.1.dist-info/entry_points.txt +3 -0
  40. stackdoctor_cli-1.0.1.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,362 @@
1
+ """The benchmark report: results.md and summary.json, from the saved run files.
2
+
3
+ Counts are raw (2/3): with three runs per cell, a percentage would overstate
4
+ the precision. Totals over all scenarios also show a percentage.
5
+
6
+ Runs in which the provider, the server or every tool call failed say nothing
7
+ about the agent:
8
+ they are left out of every accuracy count and shown on their own.
9
+ """
10
+
11
+ import json
12
+ import statistics
13
+ from collections import Counter
14
+ from collections.abc import Iterable, Mapping, Sequence
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from stackdoctor.benchmark.runner import RUNS_DIR, Job, RunRecord
20
+ from stackdoctor.benchmark.scenarios import Group, Scenario
21
+
22
+ RESULTS_FILE = "results.md"
23
+ SUMMARY_FILE = "summary.json"
24
+
25
+ GROUP_TITLES: dict[Group, str] = {
26
+ "rule": "Faults a rule detects",
27
+ "healthy": "Healthy project",
28
+ "decoy": "Healthy decoys",
29
+ "no_rule": "Faults no rule detects",
30
+ "two_bugs": "Two faults in one project",
31
+ }
32
+
33
+
34
+ def load_records(out: Path) -> list[RunRecord]:
35
+ return [
36
+ RunRecord.model_validate_json(path.read_text(encoding="utf-8"))
37
+ for path in sorted((out / RUNS_DIR).rglob("run-*.json"))
38
+ ]
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class Column:
43
+ agent: str
44
+ model: str | None
45
+ # Runs per scenario planned for this column, and for most of the others.
46
+ runs: int = 1
47
+ usual_runs: int = 1
48
+
49
+ @property
50
+ def fewer_runs(self) -> bool:
51
+ return self.model is not None and self.runs < self.usual_runs
52
+
53
+ @property
54
+ def title(self) -> str:
55
+ if self.model is None:
56
+ return "validate (rules only)"
57
+ title = f"{self.agent}: {self.model}"
58
+ if self.fewer_runs:
59
+ title += f" ({_runs(self.runs)} per scenario, not {self.usual_runs})"
60
+ return title
61
+
62
+
63
+ def write_report(
64
+ out: Path, scenarios: Sequence[Scenario], jobs: Sequence[Job], notes: Sequence[str] = ()
65
+ ) -> None:
66
+ """Write results.md and summary.json from the saved runs that are in the plan."""
67
+ saved = load_records(out)
68
+ records = in_plan(saved, jobs)
69
+ text = render(records, scenarios, jobs, notes, outside=len(saved) - len(records))
70
+ (out / RESULTS_FILE).write_text(text, encoding="utf-8")
71
+ summary = json.dumps(summarize(records, jobs), indent=2)
72
+ (out / SUMMARY_FILE).write_text(summary + "\n", encoding="utf-8")
73
+
74
+
75
+ def dropped_notes(dropped: Mapping[str, str], records: Sequence[RunRecord]) -> list[str]:
76
+ """What the report says about each model taken out of the plan, from its saved runs.
77
+
78
+ Runs that a rate limit or quota stopped are never saved, so they are not
79
+ in these counts.
80
+ """
81
+ notes = []
82
+ for model, reason in dropped.items():
83
+ runs = [r for r in records if r.model == model]
84
+ note = f"**Dropped:** `{model}`, {reason}."
85
+ if runs:
86
+ failed = [r for r in runs if r.failed]
87
+ stops = ", ".join(
88
+ f"{k} {v}" for k, v in sorted(Counter(r.stop_reason for r in runs).items())
89
+ )
90
+ errors = sum(r.provider_errors for r in runs)
91
+ note += (
92
+ f" Its {len(runs)} saved {'run' if len(runs) == 1 else 'runs'}, not counted: "
93
+ f"{len(runs) - len(failed)} finished, {len(failed)} failed ({stops}), with "
94
+ f"{errors} provider {'error' if errors == 1 else 'errors'} in all. Runs a rate "
95
+ "limit or quota stopped are not saved, so they are not in these counts."
96
+ )
97
+ else:
98
+ note += " None of its runs were saved."
99
+ notes.append(note)
100
+ return notes
101
+
102
+
103
+ def in_plan(records: Sequence[RunRecord], jobs: Sequence[Job]) -> list[RunRecord]:
104
+ """The records of planned runs: a saved run the plan no longer has is not counted."""
105
+ planned = {
106
+ (job.scenario.name, job.agent, str(job.model) if job.model else None, job.run)
107
+ for job in jobs
108
+ }
109
+ return [r for r in records if (r.scenario, r.agent, r.model, r.run) in planned]
110
+
111
+
112
+ def columns(jobs: Iterable[Job]) -> list[Column]:
113
+ runs: dict[tuple[str, str | None], int] = {}
114
+ for job in jobs:
115
+ key = (job.agent, str(job.model) if job.model is not None else None)
116
+ runs[key] = max(runs.get(key, 0), job.run)
117
+ usual = max((n for (_, model), n in runs.items() if model is not None), default=1)
118
+ return [Column(agent, model, n, usual) for (agent, model), n in runs.items()]
119
+
120
+
121
+ def summarize(records: Sequence[RunRecord], jobs: Sequence[Job]) -> dict[str, Any]:
122
+ return {
123
+ "planned_runs": len(jobs),
124
+ "finished_runs": len(records),
125
+ "prompt_hashes": sorted({r.prompt_hash for r in records}),
126
+ "git_commits": sorted({r.git_commit for r in records if r.git_commit}),
127
+ "columns": [
128
+ {
129
+ "agent": c.agent,
130
+ "model": c.model,
131
+ "runs_per_scenario": c.runs,
132
+ **_totals(_of(records, c)),
133
+ }
134
+ for c in columns(jobs)
135
+ ],
136
+ }
137
+
138
+
139
+ def render(
140
+ records: Sequence[RunRecord],
141
+ scenarios: Sequence[Scenario],
142
+ jobs: Sequence[Job],
143
+ notes: Sequence[str] = (),
144
+ outside: int = 0,
145
+ ) -> str:
146
+ cols = columns(jobs)
147
+ lines = ["# Benchmark results", ""]
148
+ lines += _header(records, jobs)
149
+ if outside:
150
+ lines.append(f"Saved runs no longer in the plan, not counted: {outside}.")
151
+ for note in notes:
152
+ lines += ["", note]
153
+ lines += ["", "## Totals", ""]
154
+ lines += _totals_table(records, cols)
155
+ lines += ["", "## By group", ""]
156
+ lines += [
157
+ "Bugs found for groups with faults, correct verdicts for healthy groups. "
158
+ "The rules-only column is what `validate` alone gets.",
159
+ "",
160
+ ]
161
+ lines += _table(
162
+ ["Group", *(c.title for c in cols)],
163
+ [
164
+ [GROUP_TITLES[group], *(_cell(_group(records, c, group)) for c in cols)]
165
+ for group in GROUP_TITLES
166
+ if any(s.answer.group == group for s in scenarios)
167
+ ],
168
+ )
169
+ lines += ["", "## By scenario", ""]
170
+ lines += _table(
171
+ ["Scenario", "Group", *(c.title for c in cols)],
172
+ [
173
+ [
174
+ f"`{s.name}`",
175
+ s.answer.group,
176
+ *(_cell([r for r in _of(records, c) if r.scenario == s.name]) for c in cols),
177
+ ]
178
+ for s in scenarios
179
+ ],
180
+ )
181
+ lines += ["", "## Stop reasons", ""]
182
+ lines += _table(
183
+ ["Agent and model", "Stop reasons"],
184
+ [
185
+ [c.title, ", ".join(f"{k} {v}" for k, v in sorted(_stops(records, c).items())) or "-"]
186
+ for c in cols
187
+ ],
188
+ )
189
+ lines += ["", _NOTES]
190
+ return "\n".join(lines) + "\n"
191
+
192
+
193
+ # --- Sections ------------------------------------------------------------------------
194
+
195
+
196
+ def _header(records: Sequence[RunRecord], jobs: Sequence[Job]) -> list[str]:
197
+ lines = [f"Finished runs: {len(records)} of {len(jobs)} planned."]
198
+ if records:
199
+ first = min(r.finished_at for r in records).date()
200
+ last = max(r.finished_at for r in records).date()
201
+ lines.append(f"Run between {first} and {last} (UTC).")
202
+ hashes = sorted({r.prompt_hash for r in records})
203
+ if len(hashes) > 1:
204
+ lines.append(
205
+ f"**Warning:** these results mix {len(hashes)} prompt versions "
206
+ f"({', '.join(hashes)}); compare only runs with the same prompts."
207
+ )
208
+ elif hashes:
209
+ lines.append(f"Prompt version: `{hashes[0]}`.")
210
+ commits = sorted({r.git_commit for r in records if r.git_commit})
211
+ if commits:
212
+ lines.append(f"StackDoctor commits: {', '.join(f'`{c}`' for c in commits)}.")
213
+ return lines
214
+
215
+
216
+ def _totals_table(records: Sequence[RunRecord], cols: Sequence[Column]) -> list[str]:
217
+ rows = []
218
+ for column in cols:
219
+ t = _totals(_of(records, column))
220
+ rows.append(
221
+ [
222
+ column.title,
223
+ str(column.runs),
224
+ _ratio(t["status_correct"], t["scored_runs"]),
225
+ _ratio(t["bugs_found"], t["bugs_total"]),
226
+ _ratio(t["root_cause_correct"], t["root_cause_runs"]),
227
+ _ratio(t["false_alarms"], t["healthy_runs"]),
228
+ _ratio(t["citations_on_key"], t["citations"])
229
+ if t["citations"] is not None
230
+ else "n/a",
231
+ str(t["unsupported_claims"]) if t["unsupported_claims"] is not None else "n/a",
232
+ str(t["provider_failures"]),
233
+ _number(t["median_seconds"], "{:.1f} s"),
234
+ _number(t["median_tokens"], "{:,.0f}"),
235
+ _number(t["median_cost_usd"], "${:.4f}"),
236
+ ]
237
+ )
238
+ return _table(
239
+ [
240
+ "Agent and model",
241
+ "Runs per scenario",
242
+ "Right verdict",
243
+ "Bugs found",
244
+ "Right root cause",
245
+ "False alarms",
246
+ "Citations on the key",
247
+ "Unsupported claims",
248
+ "Provider failures",
249
+ "Median time",
250
+ "Median tokens",
251
+ "Median cost",
252
+ ],
253
+ rows,
254
+ )
255
+
256
+
257
+ def _totals(records: Sequence[RunRecord]) -> dict[str, Any]:
258
+ scored = [r for r in records if not r.failed]
259
+ healthy = [r for r in scored if r.score.bugs_total == 0]
260
+ with_cause = [r for r in scored if r.score.root_cause_correct is not None]
261
+ cited = [r for r in scored if r.score.citations is not None]
262
+ unsupported = [r.score.unsupported_claims for r in scored]
263
+ return {
264
+ "runs": len(records),
265
+ "scored_runs": len(scored),
266
+ "provider_failures": len(records) - len(scored),
267
+ "status_correct": sum(r.score.status_correct for r in scored),
268
+ "bugs_found": sum(len(r.score.bugs_found) for r in scored),
269
+ "bugs_total": sum(r.score.bugs_total for r in scored),
270
+ "root_cause_correct": sum(bool(r.score.root_cause_correct) for r in with_cause),
271
+ "root_cause_runs": len(with_cause),
272
+ "false_alarms": sum(r.score.false_alarm for r in healthy),
273
+ "healthy_runs": len(healthy),
274
+ "citations": sum(r.score.citations or 0 for r in cited) if cited else None,
275
+ "citations_on_key": sum(r.score.citations_on_key or 0 for r in cited) if cited else None,
276
+ "unsupported_claims": (
277
+ None if any(u is None for u in unsupported) else sum(u or 0 for u in unsupported)
278
+ ),
279
+ "median_seconds": _median(r.duration_seconds for r in scored),
280
+ "median_tokens": _median(
281
+ r.input_tokens + r.output_tokens + r.thinking_tokens for r in scored
282
+ ),
283
+ "median_cost_usd": _median(
284
+ r.estimated_cost_usd for r in scored if r.estimated_cost_usd is not None
285
+ ),
286
+ "total_cost_usd": round(sum(r.estimated_cost_usd or 0.0 for r in records), 6),
287
+ }
288
+
289
+
290
+ def _cell(records: Sequence[RunRecord]) -> str:
291
+ """Bugs found (with faults) or correct verdicts (healthy), with failures noted."""
292
+ if not records:
293
+ return "-"
294
+ scored = [r for r in records if not r.failed]
295
+ failed = len(records) - len(scored)
296
+ if any(r.score.bugs_total for r in records):
297
+ text = (
298
+ f"{sum(len(r.score.bugs_found) for r in scored)}/"
299
+ f"{sum(r.score.bugs_total for r in scored)}"
300
+ )
301
+ else:
302
+ text = f"{sum(r.score.status_correct for r in scored)}/{len(scored)}"
303
+ return f"{text} ({failed} failed)" if failed else text
304
+
305
+
306
+ def _of(records: Sequence[RunRecord], column: Column) -> list[RunRecord]:
307
+ return [r for r in records if r.agent == column.agent and r.model == column.model]
308
+
309
+
310
+ def _group(records: Sequence[RunRecord], column: Column, group: Group) -> list[RunRecord]:
311
+ return [r for r in _of(records, column) if r.group == group]
312
+
313
+
314
+ def _stops(records: Sequence[RunRecord], column: Column) -> Counter[str]:
315
+ return Counter(r.stop_reason for r in _of(records, column))
316
+
317
+
318
+ def _median(values: Iterable[float]) -> float | None:
319
+ listed = list(values)
320
+ return statistics.median(listed) if listed else None
321
+
322
+
323
+ def _runs(count: int) -> str:
324
+ return f"{count} run" if count == 1 else f"{count} runs"
325
+
326
+
327
+ def _ratio(count: int, total: int) -> str:
328
+ if total == 0:
329
+ return "-"
330
+ return f"{count}/{total} ({100 * count / total:.0f}%)"
331
+
332
+
333
+ def _number(value: float | None, form: str) -> str:
334
+ return "-" if value is None else form.format(value)
335
+
336
+
337
+ def _table(header: Sequence[str], rows: Sequence[Sequence[str]]) -> list[str]:
338
+ return [
339
+ "| " + " | ".join(header) + " |",
340
+ "|" + "---|" * len(header),
341
+ *("| " + " | ".join(row) + " |" for row in rows),
342
+ ]
343
+
344
+
345
+ _NOTES = """\
346
+ ## How to read this
347
+
348
+ - **Right verdict:** problem found when there is one, none when there is
349
+ none. A run that stopped without an answer has no verdict.
350
+ - **Bugs found:** a supported claim cites one of the bug's config paths and
351
+ names no service outside it. Two-fault scenarios count each fault.
352
+ - **Right root cause:** the root cause is one of the bugs (the rules-only
353
+ baseline has no root cause).
354
+ - **False alarms:** problems reported on a healthy project or a decoy.
355
+ - **Citations on the key:** citations that point at an answer path; citing
356
+ more context is not penalized.
357
+ - **Provider failures** (provider or server errors) are left out of every
358
+ accuracy count. Runs a rate limit or quota stopped are not saved; they run
359
+ again when the benchmark resumes.
360
+ - **Cost** is estimated at the paid price, even for free-tier runs.
361
+
362
+ Scoring is described in [docs/benchmark.md](../../../docs/benchmark.md)."""