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,153 @@
1
+ """Benchmark scenarios: a captured Compose project and its answer key.
2
+
3
+ A scenario is a fixture directory with ``config.json`` (the captured
4
+ ``docker compose config --format json``) and ``answer.json``, the answer key:
5
+
6
+ - ``group``: what the scenario tests (see `Group`);
7
+ - ``status``: the right verdict, ``problem_found`` or ``no_problem_found``;
8
+ - ``baseline``: what ``validate`` alone gets, checked in CI;
9
+ - ``bugs``: each bug, with the services it involves, the config paths that
10
+ show it (``paths``: a citation of one of them, or of a value inside one,
11
+ counts) and, for agents that answer in free text, ``terms``: every group
12
+ must appear, and any one word of a group is enough.
13
+
14
+ Every path must resolve in the scenario's ``config`` evidence item, the
15
+ allowlisted and redacted view an agent sees, so every answer can be found
16
+ with the tools (`check_scenario`).
17
+ """
18
+
19
+ import json
20
+ from collections.abc import Sequence
21
+ from dataclasses import dataclass
22
+ from functools import cached_property
23
+ from pathlib import Path
24
+ from typing import Literal, Self
25
+
26
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
27
+
28
+ from stackdoctor.discovery import parse_compose_config
29
+ from stackdoctor.evidence import EvidenceError, config_item, resolve_path
30
+ from stackdoctor.models import ComposeProject
31
+
32
+ ANSWER_FILE = "answer.json"
33
+ CONFIG_FILE = "config.json"
34
+ # Where the scenarios live, relative to a clone of the repository.
35
+ DEFAULT_ROOT = Path("tests") / "fixtures" / "compose"
36
+
37
+ # rule: a fault a deterministic rule detects. healthy: a correct project.
38
+ # decoy: a correct project that looks wrong. no_rule: a fault no rule detects.
39
+ # two_bugs: two faults in one project.
40
+ Group = Literal["rule", "healthy", "decoy", "no_rule", "two_bugs"]
41
+ Verdict = Literal["problem_found", "no_problem_found"]
42
+ # What `validate` alone gets: every bug, some, none; or, for a correct
43
+ # project, no finding (clean) or a finding anyway (false_alarm).
44
+ Baseline = Literal["found", "partial", "missed", "clean", "false_alarm"]
45
+ ConfigPath = tuple[str | int, ...]
46
+
47
+ _HEALTHY_GROUPS = ("healthy", "decoy")
48
+
49
+
50
+ class _Strict(BaseModel):
51
+ model_config = ConfigDict(frozen=True, extra="forbid")
52
+
53
+
54
+ class Bug(_Strict):
55
+ """One fault in a scenario."""
56
+
57
+ id: str = Field(min_length=1)
58
+ summary: str = Field(min_length=1)
59
+ services: tuple[str, ...] = Field(min_length=1)
60
+ paths: tuple[ConfigPath, ...] = Field(min_length=1)
61
+ terms: tuple[tuple[str, ...], ...] = Field(min_length=1)
62
+
63
+ @model_validator(mode="after")
64
+ def _check(self) -> Self:
65
+ if any(not path for path in self.paths):
66
+ raise ValueError("a path must not be empty")
67
+ if any(not group or not all(group) for group in self.terms):
68
+ raise ValueError("every term group needs at least one non-empty term")
69
+ return self
70
+
71
+
72
+ class AnswerKey(_Strict):
73
+ group: Group
74
+ status: Verdict
75
+ baseline: Baseline
76
+ bugs: tuple[Bug, ...] = ()
77
+
78
+ @model_validator(mode="after")
79
+ def _check(self) -> Self:
80
+ healthy = self.group in _HEALTHY_GROUPS
81
+ if healthy != (self.status == "no_problem_found"):
82
+ raise ValueError("healthy and decoy scenarios, and only they, have no problem")
83
+ if healthy != (not self.bugs):
84
+ raise ValueError("a scenario has bugs exactly when it has a problem")
85
+ if self.group == "two_bugs" and len(self.bugs) != 2:
86
+ raise ValueError("a two_bugs scenario has two bugs")
87
+ if self.group in ("rule", "no_rule") and len(self.bugs) != 1:
88
+ raise ValueError("a rule or no_rule scenario has one bug")
89
+ if healthy != (self.baseline in ("clean", "false_alarm")):
90
+ raise ValueError("the baseline must fit the expected status")
91
+ ids = [bug.id for bug in self.bugs]
92
+ if len(ids) != len(set(ids)):
93
+ raise ValueError("bug ids must be unique")
94
+ return self
95
+
96
+
97
+ @dataclass(frozen=True)
98
+ class Scenario:
99
+ name: str
100
+ directory: Path
101
+ answer: AnswerKey
102
+
103
+ @cached_property
104
+ def project(self) -> ComposeProject:
105
+ config = json.loads((self.directory / CONFIG_FILE).read_text(encoding="utf-8"))
106
+ return parse_compose_config(config)
107
+
108
+
109
+ class ScenarioError(ValueError):
110
+ """A scenario is missing, duplicated or has an invalid answer key."""
111
+
112
+
113
+ def load_scenarios(root: Path = DEFAULT_ROOT, names: Sequence[str] | None = None) -> list[Scenario]:
114
+ """Every scenario under ``root`` (a directory with an answer.json), by name.
115
+
116
+ Raises:
117
+ ScenarioError: if two scenarios share a name, an answer key is
118
+ invalid, or a requested name does not exist.
119
+ """
120
+ found: dict[str, Scenario] = {}
121
+ for answer_file in sorted(root.rglob(ANSWER_FILE)):
122
+ directory = answer_file.parent
123
+ if directory.name in found:
124
+ raise ScenarioError(f"two scenarios are named {directory.name!r}")
125
+ try:
126
+ answer = AnswerKey.model_validate_json(answer_file.read_text(encoding="utf-8"))
127
+ except ValueError as error:
128
+ raise ScenarioError(f"{answer_file}: {error}") from None
129
+ found[directory.name] = Scenario(directory.name, directory, answer)
130
+ if names is None:
131
+ return [found[name] for name in sorted(found)]
132
+ unknown = [name for name in names if name not in found]
133
+ if unknown:
134
+ raise ScenarioError(f"unknown scenario(s): {', '.join(unknown)}")
135
+ return [found[name] for name in dict.fromkeys(names)]
136
+
137
+
138
+ def check_scenario(scenario: Scenario) -> list[str]:
139
+ """Problems with an answer key that loading cannot see: what an agent can find."""
140
+ project = scenario.project
141
+ data = config_item(project).data
142
+ services = {service.name for service in project.services}
143
+ problems = []
144
+ for bug in scenario.answer.bugs:
145
+ for service in bug.services:
146
+ if service not in services:
147
+ problems.append(f"bug {bug.id}: no service {service!r}")
148
+ for path in bug.paths:
149
+ try:
150
+ resolve_path(data, path)
151
+ except EvidenceError as error:
152
+ problems.append(f"bug {bug.id}: {error}")
153
+ return problems
@@ -0,0 +1,184 @@
1
+ """Deterministic scoring of one answer against a scenario's answer key.
2
+
3
+ Three kinds of answer are scored the same way, so they fit in one table:
4
+
5
+ - a `Diagnosis` from StackDoctor's agent (`score_diagnosis`);
6
+ - a `ValidationReport` from ``validate`` alone, the baseline (`score_report`);
7
+ - free text from an agent without structured citations, such as HolmesGPT
8
+ (`score_text`): bugs are matched by their terms, the verdict comes from the
9
+ answer's ``VERDICT:`` line, and evidence is not scored.
10
+
11
+ A bug counts as found when a *supported* claim (one whose citations all
12
+ resolved) cites one of the bug's paths, or a value inside one, and does not
13
+ name a service outside the bug's services. Claims that were flagged as
14
+ unsupported never find a bug; they are counted instead.
15
+ """
16
+
17
+ import re
18
+ from collections.abc import Iterable, Sequence
19
+ from dataclasses import dataclass
20
+ from typing import Literal
21
+
22
+ from pydantic import BaseModel, ConfigDict
23
+
24
+ from stackdoctor.agent.diagnosis import Diagnosis
25
+ from stackdoctor.benchmark.scenarios import AnswerKey, Baseline, Bug, ConfigPath
26
+ from stackdoctor.models import CONFIG_EVIDENCE_ID, EvidenceRef, ValidationReport
27
+
28
+ # The agent's verdict; "none" when it gave none (the run stopped early, or a
29
+ # free-text answer had no VERDICT line).
30
+ Verdict = Literal["problem_found", "no_problem_found", "none"]
31
+
32
+ _VERDICT_LINE = re.compile(r"^\W*VERDICT\W*(problem_found|no_problem_found)\b", re.I | re.M)
33
+
34
+
35
+ class Score(BaseModel):
36
+ """How one answer compares with the answer key. None: not applicable."""
37
+
38
+ model_config = ConfigDict(frozen=True, extra="forbid")
39
+
40
+ verdict: Verdict
41
+ status_correct: bool
42
+ false_alarm: bool
43
+ bugs_found: tuple[str, ...]
44
+ bugs_total: int
45
+ # Whether the root cause is one of the bugs. None for a correct project,
46
+ # and for the baseline, which has findings but no root cause.
47
+ root_cause_correct: bool | None
48
+ # Citations of supported claims, and how many point at an answer path.
49
+ # None when the answer has no structured citations (free text).
50
+ citations: int | None
51
+ citations_on_key: int | None
52
+ unsupported_claims: int | None
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class _Claim:
57
+ service: str | None
58
+ paths: tuple[ConfigPath, ...]
59
+
60
+
61
+ def score_diagnosis(answer: AnswerKey, diagnosis: Diagnosis) -> Score:
62
+ verdict: Verdict
63
+ if diagnosis.status in ("diagnosed", "unsupported"):
64
+ verdict = "problem_found"
65
+ elif diagnosis.status == "no_problem_found":
66
+ verdict = "no_problem_found"
67
+ else:
68
+ verdict = "none"
69
+ root = _Claim(None, _paths(diagnosis.root_cause.evidence)) if diagnosis.root_cause else None
70
+ claims = [
71
+ *([root] if root else []),
72
+ *(_Claim(f.service, _paths(f.evidence)) for f in diagnosis.findings),
73
+ ]
74
+ found = _found(answer.bugs, claims)
75
+ cited = [path for claim in claims for path in claim.paths]
76
+ return _score(
77
+ answer,
78
+ verdict,
79
+ found,
80
+ root_cause_correct=(
81
+ None
82
+ if not answer.bugs
83
+ else root is not None and any(_matches(bug, root) for bug in answer.bugs)
84
+ ),
85
+ citations=len(cited),
86
+ citations_on_key=sum(_on_key(answer.bugs, path) for path in cited),
87
+ unsupported_claims=len(diagnosis.unsupported),
88
+ )
89
+
90
+
91
+ def score_report(answer: AnswerKey, report: ValidationReport) -> Score:
92
+ claims = [_Claim(f.service, _paths(f.evidence)) for f in report.findings]
93
+ cited = [path for claim in claims for path in claim.paths]
94
+ return _score(
95
+ answer,
96
+ "problem_found" if report.findings else "no_problem_found",
97
+ _found(answer.bugs, claims),
98
+ root_cause_correct=None,
99
+ citations=len(cited),
100
+ citations_on_key=sum(_on_key(answer.bugs, path) for path in cited),
101
+ unsupported_claims=0,
102
+ )
103
+
104
+
105
+ def score_text(answer: AnswerKey, text: str) -> Score:
106
+ match = _VERDICT_LINE.findall(text)
107
+ verdict: Verdict = match[-1].lower() if match else "none"
108
+ found = tuple(bug.id for bug in answer.bugs if _mentions(text, bug.terms))
109
+ return _score(
110
+ answer,
111
+ verdict,
112
+ found,
113
+ root_cause_correct=bool(found) if answer.bugs else None,
114
+ citations=None,
115
+ citations_on_key=None,
116
+ unsupported_claims=None,
117
+ )
118
+
119
+
120
+ def baseline_outcome(answer: AnswerKey, score: Score) -> Baseline:
121
+ """Summarize a score the way an answer key's ``baseline`` does."""
122
+ if not answer.bugs:
123
+ return "false_alarm" if score.verdict == "problem_found" else "clean"
124
+ if len(score.bugs_found) == len(answer.bugs):
125
+ return "found"
126
+ return "partial" if score.bugs_found else "missed"
127
+
128
+
129
+ def _score(
130
+ answer: AnswerKey,
131
+ verdict: Verdict,
132
+ found: tuple[str, ...],
133
+ *,
134
+ root_cause_correct: bool | None,
135
+ citations: int | None,
136
+ citations_on_key: int | None,
137
+ unsupported_claims: int | None,
138
+ ) -> Score:
139
+ return Score(
140
+ verdict=verdict,
141
+ status_correct=verdict == answer.status,
142
+ false_alarm=answer.status == "no_problem_found" and verdict == "problem_found",
143
+ bugs_found=found,
144
+ bugs_total=len(answer.bugs),
145
+ root_cause_correct=root_cause_correct,
146
+ citations=citations,
147
+ citations_on_key=citations_on_key,
148
+ unsupported_claims=unsupported_claims,
149
+ )
150
+
151
+
152
+ def _paths(evidence: Iterable[EvidenceRef]) -> tuple[ConfigPath, ...]:
153
+ # Only the configuration is scored; live evidence is not part of M6.
154
+ return tuple(ref.path for ref in evidence if ref.item == CONFIG_EVIDENCE_ID)
155
+
156
+
157
+ def _found(bugs: Sequence[Bug], claims: Sequence[_Claim]) -> tuple[str, ...]:
158
+ return tuple(bug.id for bug in bugs if any(_matches(bug, claim) for claim in claims))
159
+
160
+
161
+ def _matches(bug: Bug, claim: _Claim) -> bool:
162
+ if claim.service is not None and claim.service not in bug.services:
163
+ return False
164
+ return any(_covers(accepted, cited) for cited in claim.paths for accepted in bug.paths)
165
+
166
+
167
+ def _on_key(bugs: Sequence[Bug], cited: ConfigPath) -> bool:
168
+ return any(_covers(accepted, cited) for bug in bugs for accepted in bug.paths)
169
+
170
+
171
+ def _covers(accepted: ConfigPath, cited: ConfigPath) -> bool:
172
+ """Whether ``cited`` is ``accepted`` or a value inside it."""
173
+ if len(cited) < len(accepted):
174
+ return False
175
+ return all(str(a) == str(c) for a, c in zip(accepted, cited, strict=False))
176
+
177
+
178
+ def _mentions(text: str, terms: Sequence[Sequence[str]]) -> bool:
179
+ return all(any(_word(term).search(text) for term in group) for group in terms)
180
+
181
+
182
+ def _word(term: str) -> re.Pattern[str]:
183
+ # A whole word or name, so "db" does not match inside "dbus".
184
+ return re.compile(rf"(?<![\w-]){re.escape(term)}(?![\w-])", re.I)