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.
- stackdoctor/__init__.py +15 -0
- stackdoctor/__main__.py +6 -0
- stackdoctor/agent/__init__.py +5 -0
- stackdoctor/agent/compaction.py +66 -0
- stackdoctor/agent/diagnosis.py +398 -0
- stackdoctor/agent/loop.py +801 -0
- stackdoctor/agent/prompts.py +85 -0
- stackdoctor/agent/providers/__init__.py +295 -0
- stackdoctor/agent/providers/base.py +210 -0
- stackdoctor/agent/providers/claude.py +285 -0
- stackdoctor/agent/providers/gemini.py +312 -0
- stackdoctor/agent/providers/openai_compat.py +537 -0
- stackdoctor/agent/providers/prices.py +90 -0
- stackdoctor/benchmark/__init__.py +11 -0
- stackdoctor/benchmark/__main__.py +198 -0
- stackdoctor/benchmark/holmes.py +386 -0
- stackdoctor/benchmark/report.py +362 -0
- stackdoctor/benchmark/runner.py +710 -0
- stackdoctor/benchmark/scenarios.py +153 -0
- stackdoctor/benchmark/scoring.py +184 -0
- stackdoctor/cli.py +882 -0
- stackdoctor/dependencies.py +221 -0
- stackdoctor/discovery.py +361 -0
- stackdoctor/evidence.py +134 -0
- stackdoctor/github.py +168 -0
- stackdoctor/live.py +808 -0
- stackdoctor/mcp_server.py +233 -0
- stackdoctor/models.py +275 -0
- stackdoctor/pglog.py +55 -0
- stackdoctor/postgres.py +294 -0
- stackdoctor/probes.py +172 -0
- stackdoctor/py.typed +0 -0
- stackdoctor/redaction.py +215 -0
- stackdoctor/rules.py +303 -0
- stackdoctor/validation.py +61 -0
- stackdoctor_cli-1.0.1.dist-info/METADATA +177 -0
- stackdoctor_cli-1.0.1.dist-info/RECORD +40 -0
- stackdoctor_cli-1.0.1.dist-info/WHEEL +4 -0
- stackdoctor_cli-1.0.1.dist-info/entry_points.txt +3 -0
- stackdoctor_cli-1.0.1.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,710 @@
|
|
|
1
|
+
"""Run the benchmark: every scenario, agent, model and run, one result file each.
|
|
2
|
+
|
|
3
|
+
The runner is resumable. Each run is written to its own file as soon as it
|
|
4
|
+
finishes (``runs/<scenario>/<agent>/<model>/run-<n>.json``) and skipped when
|
|
5
|
+
it already exists, so an interrupted benchmark, or one spread over several
|
|
6
|
+
days of free-tier limits, continues where it stopped.
|
|
7
|
+
|
|
8
|
+
A run that ends on a rate limit or quota (HTTP 429, or a quota the provider
|
|
9
|
+
calls exhausted) is not saved: it was not the model's fault, and the next
|
|
10
|
+
invocation runs it again. That model is skipped for the rest of the
|
|
11
|
+
invocation; the other models go on. Any other provider failure is saved and
|
|
12
|
+
reported apart from wrong answers, and so is a StackDoctor run in which every
|
|
13
|
+
tool call returned an error (``tool_failure``): the model never saw the
|
|
14
|
+
project. Two of those in a row stop the benchmark.
|
|
15
|
+
|
|
16
|
+
The order interleaves runs, scenarios and models (run 1 of everything first),
|
|
17
|
+
so a partial benchmark stays balanced, and a pause per provider spaces the
|
|
18
|
+
runs out for free-tier limits.
|
|
19
|
+
|
|
20
|
+
StackDoctor's agent runs in-process against an MCP server that serves the
|
|
21
|
+
scenario's captured ``docker compose config``; HolmesGPT gets the same server
|
|
22
|
+
over stdio (`stackdoctor.benchmark.holmes`). No Docker, and every agent and
|
|
23
|
+
run gets identical input. Every setting is the default: the default thinking
|
|
24
|
+
level, no fallback model, the provider's run limits.
|
|
25
|
+
|
|
26
|
+
The served capture names the project ``compose-project``. The fixtures' own
|
|
27
|
+
project names (``stackdoctor-bench-wrong-service-port``) would give the
|
|
28
|
+
answer away.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
import asyncio
|
|
32
|
+
import functools
|
|
33
|
+
import hashlib
|
|
34
|
+
import inspect
|
|
35
|
+
import json
|
|
36
|
+
import subprocess
|
|
37
|
+
import time
|
|
38
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
39
|
+
from dataclasses import dataclass, field
|
|
40
|
+
from datetime import UTC, datetime
|
|
41
|
+
from pathlib import Path
|
|
42
|
+
from typing import Any, Literal
|
|
43
|
+
|
|
44
|
+
from mcp.server.mcpserver import MCPServer
|
|
45
|
+
from pydantic import AwareDatetime, BaseModel, ConfigDict, JsonValue
|
|
46
|
+
|
|
47
|
+
from stackdoctor import __version__
|
|
48
|
+
from stackdoctor.agent import prompts
|
|
49
|
+
from stackdoctor.agent.diagnosis import SUBMIT_DESCRIPTION, SUBMIT_PARAMETERS
|
|
50
|
+
from stackdoctor.agent.loop import Limits, run_agent
|
|
51
|
+
from stackdoctor.agent.providers import create_provider, provider_spec
|
|
52
|
+
from stackdoctor.agent.providers.base import (
|
|
53
|
+
LLMProvider,
|
|
54
|
+
Price,
|
|
55
|
+
ProviderError,
|
|
56
|
+
ProviderUnavailableError,
|
|
57
|
+
Session,
|
|
58
|
+
ToolResult,
|
|
59
|
+
ToolSpec,
|
|
60
|
+
Turn,
|
|
61
|
+
)
|
|
62
|
+
from stackdoctor.benchmark import holmes
|
|
63
|
+
from stackdoctor.benchmark.scenarios import Group, Scenario
|
|
64
|
+
from stackdoctor.benchmark.scoring import Score, score_diagnosis, score_report
|
|
65
|
+
from stackdoctor.discovery import RunResult
|
|
66
|
+
from stackdoctor.mcp_server import create_server
|
|
67
|
+
from stackdoctor.validation import validate_project
|
|
68
|
+
|
|
69
|
+
Agent = Literal["baseline", "stackdoctor", "holmesgpt"]
|
|
70
|
+
AGENTS: tuple[Agent, ...] = ("baseline", "stackdoctor", "holmesgpt")
|
|
71
|
+
# The project name every agent sees (see the module docstring).
|
|
72
|
+
NEUTRAL_PROJECT = "compose-project"
|
|
73
|
+
DEFAULT_MODELS = (
|
|
74
|
+
"gemini:gemini-3.5-flash-lite",
|
|
75
|
+
"groq:openai/gpt-oss-120b",
|
|
76
|
+
)
|
|
77
|
+
# Models taken out of the M6 plan, and why. Their saved runs stay on disk, and
|
|
78
|
+
# the report says how they ended (report.dropped_notes).
|
|
79
|
+
DROPPED_MODELS: Mapping[str, str] = {
|
|
80
|
+
"gemini:gemini-3.8-flash": "too often unavailable on the free tier to benchmark",
|
|
81
|
+
"groq:qwen/qwen3.8-27b": (
|
|
82
|
+
"rejected by Groq's free-tier limit of 1,000 output tokens per minute, "
|
|
83
|
+
"which it applies to each request's expected output"
|
|
84
|
+
),
|
|
85
|
+
}
|
|
86
|
+
DEFAULT_RUNS = 3
|
|
87
|
+
# Runs per scenario where M6 runs fewer than DEFAULT_RUNS, to fit the free
|
|
88
|
+
# tiers' daily quotas (Groq: 200,000 tokens a day per model). A key is
|
|
89
|
+
# "provider:model" (every agent) or "agent:provider:model" (one agent, which
|
|
90
|
+
# wins); 0 means not run at all. The report shows the runs per scenario of
|
|
91
|
+
# every column and lists the trim.
|
|
92
|
+
DEFAULT_RUNS_FOR: Mapping[str, int] = {
|
|
93
|
+
"holmesgpt:groq:openai/gpt-oss-120b": 1,
|
|
94
|
+
"holmesgpt:gemini:gemini-3.5-flash-lite": 1,
|
|
95
|
+
}
|
|
96
|
+
TRIM_REASON = (
|
|
97
|
+
"to fit the free tiers' daily quotas (Groq, for one, allows 200,000 tokens a day per model)"
|
|
98
|
+
)
|
|
99
|
+
DEFAULT_OUT = Path("benchmarks") / "results" / "m6"
|
|
100
|
+
RUNS_DIR = "runs"
|
|
101
|
+
PLAN_FILE = "plan.json"
|
|
102
|
+
# Seconds between the starts of two runs on one provider, for free-tier limits
|
|
103
|
+
# (Groq's free tier allows 8K tokens per minute per model; Gemini's a few
|
|
104
|
+
# requests per minute).
|
|
105
|
+
PAUSES: Mapping[str, float] = {"gemini": 20.0, "groq": 30.0}
|
|
106
|
+
# Seconds to wait before trying a rate-limited HolmesGPT run once more.
|
|
107
|
+
RATE_LIMIT_WAIT = 65.0
|
|
108
|
+
# Tries for a run that ends in a provider failure, over all invocations.
|
|
109
|
+
MAX_ATTEMPTS = 3
|
|
110
|
+
# Progress lines, flushed so a redirected log shows each run as it ends.
|
|
111
|
+
_print = functools.partial(print, flush=True)
|
|
112
|
+
# A StackDoctor run in which every tool call returned an error: the model never
|
|
113
|
+
# saw the project. Saved as a failure, not scored as a wrong answer.
|
|
114
|
+
TOOL_FAILURE = "tool_failure"
|
|
115
|
+
# Tool failures in a row (StackDoctor runs) after which the benchmark stops:
|
|
116
|
+
# the capture server is deterministic, so they point at a bug, and every
|
|
117
|
+
# further run would spend quota for nothing.
|
|
118
|
+
MAX_TOOL_FAILURES = 2
|
|
119
|
+
# Stop reasons that are the provider's, the server's or the tools' failure,
|
|
120
|
+
# not the agent's.
|
|
121
|
+
FAILURE_REASONS = frozenset({"provider_error", "server_error", TOOL_FAILURE})
|
|
122
|
+
RATE_LIMITED = 429
|
|
123
|
+
# Characters of a tool error kept in a tool failure's stop detail.
|
|
124
|
+
ERROR_EXCERPT = 200
|
|
125
|
+
|
|
126
|
+
Sleep = Callable[[float], Awaitable[None]]
|
|
127
|
+
Log = Callable[[str], None]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class RunRecord(BaseModel):
|
|
131
|
+
"""One finished run: what was run, how it went, and its score."""
|
|
132
|
+
|
|
133
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
134
|
+
|
|
135
|
+
scenario: str
|
|
136
|
+
group: Group
|
|
137
|
+
agent: str
|
|
138
|
+
# "provider:model"; None for the baseline, which uses no model.
|
|
139
|
+
model: str | None
|
|
140
|
+
run: int
|
|
141
|
+
finished_at: AwareDatetime
|
|
142
|
+
git_commit: str | None
|
|
143
|
+
prompt_hash: str
|
|
144
|
+
agent_version: str
|
|
145
|
+
settings: dict[str, str]
|
|
146
|
+
stop_reason: str
|
|
147
|
+
stop_detail: str | None
|
|
148
|
+
duration_seconds: float
|
|
149
|
+
input_tokens: int
|
|
150
|
+
output_tokens: int
|
|
151
|
+
thinking_tokens: int
|
|
152
|
+
estimated_cost_usd: float | None
|
|
153
|
+
tool_calls: int | None
|
|
154
|
+
model_calls: int | None
|
|
155
|
+
score: Score
|
|
156
|
+
# The full answer: the Diagnosis, the validation report, or free text.
|
|
157
|
+
answer: dict[str, JsonValue]
|
|
158
|
+
# Provider errors during the run, retried or not.
|
|
159
|
+
provider_errors: int = 0
|
|
160
|
+
# Which try this is: a provider failure is tried again, up to MAX_ATTEMPTS.
|
|
161
|
+
attempts: int = 1
|
|
162
|
+
# Tool calls whose result was an error (StackDoctor runs).
|
|
163
|
+
tool_errors: int = 0
|
|
164
|
+
|
|
165
|
+
@property
|
|
166
|
+
def failed(self) -> bool:
|
|
167
|
+
"""The provider, the server or the tools failed: the run says nothing about the agent.
|
|
168
|
+
|
|
169
|
+
A timeout counts too when the provider kept failing during the run:
|
|
170
|
+
the time went to retries, not to the agent.
|
|
171
|
+
"""
|
|
172
|
+
if self.stop_reason in FAILURE_REASONS:
|
|
173
|
+
return True
|
|
174
|
+
return self.stop_reason == "timeout" and self.provider_errors > 0
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
@dataclass(frozen=True)
|
|
178
|
+
class ModelSpec:
|
|
179
|
+
provider: str
|
|
180
|
+
model: str
|
|
181
|
+
|
|
182
|
+
@classmethod
|
|
183
|
+
def parse(cls, text: str) -> "ModelSpec":
|
|
184
|
+
provider, colon, model = text.partition(":")
|
|
185
|
+
if not colon or not provider or not model:
|
|
186
|
+
raise ValueError(f"expected PROVIDER:MODEL, got {text!r}")
|
|
187
|
+
return cls(provider, model)
|
|
188
|
+
|
|
189
|
+
def __str__(self) -> str:
|
|
190
|
+
return f"{self.provider}:{self.model}"
|
|
191
|
+
|
|
192
|
+
@property
|
|
193
|
+
def slug(self) -> str:
|
|
194
|
+
"""A directory name: ':' and '/' are not allowed in file names everywhere."""
|
|
195
|
+
return f"{self.provider}__{self.model.replace('/', '_')}"
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@dataclass(frozen=True)
|
|
199
|
+
class Job:
|
|
200
|
+
scenario: Scenario
|
|
201
|
+
agent: str
|
|
202
|
+
model: ModelSpec | None
|
|
203
|
+
run: int
|
|
204
|
+
|
|
205
|
+
def path(self, out: Path) -> Path:
|
|
206
|
+
model = self.model.slug if self.model is not None else "rules"
|
|
207
|
+
return out / RUNS_DIR / self.scenario.name / self.agent / model / f"run-{self.run}.json"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def plan(
|
|
211
|
+
scenarios: Sequence[Scenario],
|
|
212
|
+
agents: Sequence[str],
|
|
213
|
+
models: Sequence[ModelSpec],
|
|
214
|
+
runs: int,
|
|
215
|
+
runs_for: Mapping[str, int] | None = None,
|
|
216
|
+
) -> list[Job]:
|
|
217
|
+
"""Every job, run 1 of everything first. The deterministic baseline runs once.
|
|
218
|
+
|
|
219
|
+
``runs_for`` gives a model, or one agent on a model, its own number of runs
|
|
220
|
+
(see DEFAULT_RUNS_FOR).
|
|
221
|
+
"""
|
|
222
|
+
jobs = []
|
|
223
|
+
for run in range(1, runs + 1):
|
|
224
|
+
for scenario in scenarios:
|
|
225
|
+
for agent in agents:
|
|
226
|
+
if agent == "baseline":
|
|
227
|
+
if run == 1:
|
|
228
|
+
jobs.append(Job(scenario, agent, None, 1))
|
|
229
|
+
continue
|
|
230
|
+
jobs.extend(
|
|
231
|
+
Job(scenario, agent, model, run)
|
|
232
|
+
for model in models
|
|
233
|
+
if run <= runs_of(agent, model, runs, runs_for)
|
|
234
|
+
)
|
|
235
|
+
return jobs
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def runs_of(
|
|
239
|
+
agent: str, model: ModelSpec, runs: int, runs_for: Mapping[str, int] | None = None
|
|
240
|
+
) -> int:
|
|
241
|
+
"""Runs per scenario for one agent on one model."""
|
|
242
|
+
given = runs_for or {}
|
|
243
|
+
return given.get(f"{agent}:{model}", given.get(str(model), runs))
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def trim_notes(
|
|
247
|
+
agents: Sequence[str],
|
|
248
|
+
models: Sequence[ModelSpec],
|
|
249
|
+
runs: int,
|
|
250
|
+
runs_for: Mapping[str, int] | None = None,
|
|
251
|
+
) -> list[str]:
|
|
252
|
+
"""What the report says about agents and models run fewer times, or not at all."""
|
|
253
|
+
fewer, dropped = [], []
|
|
254
|
+
for agent in agents:
|
|
255
|
+
if agent == "baseline":
|
|
256
|
+
continue
|
|
257
|
+
for model in models:
|
|
258
|
+
count = runs_of(agent, model, runs, runs_for)
|
|
259
|
+
if count == 0:
|
|
260
|
+
dropped.append(f"{agent} on `{model}`")
|
|
261
|
+
elif count < runs:
|
|
262
|
+
fewer.append(f"{agent} on `{model}` ({count})")
|
|
263
|
+
notes = []
|
|
264
|
+
if fewer:
|
|
265
|
+
notes.append(
|
|
266
|
+
f"**Fewer runs.** Most columns ran {runs} times per scenario; these ran fewer, "
|
|
267
|
+
f"{TRIM_REASON}: {', '.join(fewer)}. Their counts are out of fewer runs, so they say "
|
|
268
|
+
"less about how consistent each one is."
|
|
269
|
+
)
|
|
270
|
+
if dropped:
|
|
271
|
+
notes.append(f"**Not run**, for the same reason: {', '.join(dropped)}.")
|
|
272
|
+
return notes
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class Deferred(Exception):
|
|
276
|
+
"""A rate limit or quota stopped the run: run it again later."""
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
@dataclass
|
|
280
|
+
class Outcome:
|
|
281
|
+
done: int = 0
|
|
282
|
+
skipped: int = 0
|
|
283
|
+
deferred: int = 0
|
|
284
|
+
deferred_models: list[str] = field(default_factory=list)
|
|
285
|
+
# Why the benchmark stopped before the end, if it did.
|
|
286
|
+
stopped: str | None = None
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
ProviderFactory = Callable[[ModelSpec], LLMProvider]
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def default_provider(spec: ModelSpec, max_output_tokens: int | None = None) -> LLMProvider:
|
|
293
|
+
return create_provider(spec.provider, model=spec.model, max_output_tokens=max_output_tokens)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
async def run_benchmark(
|
|
297
|
+
jobs: Sequence[Job],
|
|
298
|
+
out: Path,
|
|
299
|
+
*,
|
|
300
|
+
provider_factory: ProviderFactory = default_provider,
|
|
301
|
+
holmes_path: str | None = None,
|
|
302
|
+
holmes_runner: holmes.Runner = subprocess.run,
|
|
303
|
+
git_commit: str | None = None,
|
|
304
|
+
pauses: Mapping[str, float] = PAUSES,
|
|
305
|
+
sleep: Sleep = asyncio.sleep,
|
|
306
|
+
clock: Callable[[], float] = time.monotonic,
|
|
307
|
+
log: Log = _print,
|
|
308
|
+
) -> Outcome:
|
|
309
|
+
"""Run every job whose result file does not exist yet.
|
|
310
|
+
|
|
311
|
+
Stops early, with ``Outcome.stopped`` set, after MAX_TOOL_FAILURES
|
|
312
|
+
StackDoctor runs in a row in which every tool call returned an error.
|
|
313
|
+
|
|
314
|
+
Raises:
|
|
315
|
+
ProviderUnavailableError: before any run, if a model's provider
|
|
316
|
+
cannot be created (a missing key or SDK), or HolmesGPT is
|
|
317
|
+
needed and not installed at its pinned version.
|
|
318
|
+
"""
|
|
319
|
+
# Checked first, so a missing key stops the benchmark before any run.
|
|
320
|
+
created = {
|
|
321
|
+
str(spec): provider_factory(spec)
|
|
322
|
+
for spec in dict.fromkeys(
|
|
323
|
+
job.model for job in jobs if job.model is not None and job.agent == "stackdoctor"
|
|
324
|
+
)
|
|
325
|
+
}
|
|
326
|
+
holmes_jobs = [job for job in jobs if job.agent == "holmesgpt" and job.model is not None]
|
|
327
|
+
agent = _HolmesAgent(holmes_path, holmes_runner)
|
|
328
|
+
if holmes_jobs:
|
|
329
|
+
agent.prepare({job.model.provider for job in holmes_jobs if job.model is not None})
|
|
330
|
+
fingerprint = await prompt_hash()
|
|
331
|
+
outcome = Outcome()
|
|
332
|
+
last_start: dict[str, float] = {}
|
|
333
|
+
tool_failures = 0
|
|
334
|
+
for job in jobs:
|
|
335
|
+
path = job.path(out)
|
|
336
|
+
attempts = 1
|
|
337
|
+
if path.exists():
|
|
338
|
+
previous = _read(path)
|
|
339
|
+
if not previous.failed or previous.attempts >= MAX_ATTEMPTS:
|
|
340
|
+
outcome.skipped += 1
|
|
341
|
+
continue
|
|
342
|
+
# A provider failure is tried again, up to MAX_ATTEMPTS in all.
|
|
343
|
+
attempts = previous.attempts + 1
|
|
344
|
+
label = _label(job)
|
|
345
|
+
if label in outcome.deferred_models:
|
|
346
|
+
outcome.deferred += 1
|
|
347
|
+
continue
|
|
348
|
+
context = _Context(created, agent, fingerprint, git_commit, clock, sleep, attempts)
|
|
349
|
+
result = await _attempt(job, context, last_start, pauses)
|
|
350
|
+
if isinstance(result, Deferred) and job.agent == "holmesgpt":
|
|
351
|
+
# HolmesGPT has no backoff of its own for a per-minute limit:
|
|
352
|
+
# wait for it to reset and try once more.
|
|
353
|
+
log(f"rate-limited: {label}; waiting {RATE_LIMIT_WAIT:.0f} s to try again")
|
|
354
|
+
await sleep(RATE_LIMIT_WAIT)
|
|
355
|
+
result = await _attempt(job, context, last_start, pauses)
|
|
356
|
+
if isinstance(result, Deferred):
|
|
357
|
+
outcome.deferred += 1
|
|
358
|
+
outcome.deferred_models.append(label)
|
|
359
|
+
log(f"deferred {label}: {result}; its remaining runs wait for the next invocation")
|
|
360
|
+
continue
|
|
361
|
+
record = result
|
|
362
|
+
_write(path, record)
|
|
363
|
+
outcome.done += 1
|
|
364
|
+
log(_line(record))
|
|
365
|
+
if job.agent == "stackdoctor":
|
|
366
|
+
tool_failures = tool_failures + 1 if record.stop_reason == TOOL_FAILURE else 0
|
|
367
|
+
if tool_failures >= MAX_TOOL_FAILURES:
|
|
368
|
+
outcome.stopped = (
|
|
369
|
+
f"{tool_failures} StackDoctor runs in a row got only errors from every "
|
|
370
|
+
f"tool call, the last: {record.stop_detail}"
|
|
371
|
+
)
|
|
372
|
+
log(f"stopping: {outcome.stopped}")
|
|
373
|
+
break
|
|
374
|
+
return outcome
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def remaining(jobs: Sequence[Job], out: Path) -> int:
|
|
378
|
+
"""Jobs without a final result: not run yet, or a provider failure to try again."""
|
|
379
|
+
left = 0
|
|
380
|
+
for job in jobs:
|
|
381
|
+
path = job.path(out)
|
|
382
|
+
if not path.exists():
|
|
383
|
+
left += 1
|
|
384
|
+
continue
|
|
385
|
+
record = _read(path)
|
|
386
|
+
if record.failed and record.attempts < MAX_ATTEMPTS:
|
|
387
|
+
left += 1
|
|
388
|
+
return left
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
async def _pace(
|
|
392
|
+
provider: str,
|
|
393
|
+
last_start: dict[str, float],
|
|
394
|
+
pauses: Mapping[str, float],
|
|
395
|
+
sleep: Sleep,
|
|
396
|
+
clock: Callable[[], float],
|
|
397
|
+
) -> None:
|
|
398
|
+
if provider in last_start:
|
|
399
|
+
wait = last_start[provider] + pauses.get(provider, 0.0) - clock()
|
|
400
|
+
if wait > 0:
|
|
401
|
+
await sleep(wait)
|
|
402
|
+
last_start[provider] = clock()
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
@dataclass(frozen=True)
|
|
406
|
+
class _Context:
|
|
407
|
+
"""What every run of one invocation shares."""
|
|
408
|
+
|
|
409
|
+
created: Mapping[str, LLMProvider]
|
|
410
|
+
agent: "_HolmesAgent"
|
|
411
|
+
fingerprint: str
|
|
412
|
+
git_commit: str | None
|
|
413
|
+
clock: Callable[[], float]
|
|
414
|
+
sleep: Sleep
|
|
415
|
+
attempts: int
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
async def _attempt(
|
|
419
|
+
job: Job, context: _Context, last_start: dict[str, float], pauses: Mapping[str, float]
|
|
420
|
+
) -> "RunRecord | Deferred":
|
|
421
|
+
if job.model is not None:
|
|
422
|
+
await _pace(job.model.provider, last_start, pauses, context.sleep, context.clock)
|
|
423
|
+
try:
|
|
424
|
+
return await _run(job, context)
|
|
425
|
+
except Deferred as error:
|
|
426
|
+
return error
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _label(job: Job) -> str:
|
|
430
|
+
return f"{job.agent} {job.model}"
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _read(path: Path) -> RunRecord:
|
|
434
|
+
return RunRecord.model_validate_json(path.read_text(encoding="utf-8"))
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
async def prompt_hash() -> str:
|
|
438
|
+
"""A fingerprint of everything the model is told: prompts and tool descriptions.
|
|
439
|
+
|
|
440
|
+
Every result records this, and a test pins it, so results from
|
|
441
|
+
different prompts are never mixed by accident (docs/benchmark.md).
|
|
442
|
+
"""
|
|
443
|
+
server = create_server([Path()], live_tools=False)
|
|
444
|
+
tools = await server.list_tools()
|
|
445
|
+
parts = [
|
|
446
|
+
prompts.SYSTEM_PROMPT,
|
|
447
|
+
prompts.INITIAL_MESSAGE,
|
|
448
|
+
prompts.LIMIT_REACHED,
|
|
449
|
+
prompts.TEXT_ONLY,
|
|
450
|
+
prompts.handover_message("{collected}"),
|
|
451
|
+
prompts.repair_message(["{problem}"]),
|
|
452
|
+
prompts.rejected_message("{problem}", ["{tool}"]),
|
|
453
|
+
SUBMIT_DESCRIPTION,
|
|
454
|
+
json.dumps(SUBMIT_PARAMETERS, sort_keys=True),
|
|
455
|
+
# Normalized as the agent normalizes them: Python 3.13 strips
|
|
456
|
+
# docstring indentation itself, and the hash must not depend on it.
|
|
457
|
+
*(
|
|
458
|
+
f"{tool.name}: {inspect.cleandoc(tool.description or '')}"
|
|
459
|
+
for tool in sorted(tools, key=lambda t: t.name)
|
|
460
|
+
),
|
|
461
|
+
]
|
|
462
|
+
return hashlib.sha256("\n\x00\n".join(parts).encode()).hexdigest()[:16]
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def served_config(directory: Path) -> str:
|
|
466
|
+
"""The scenario's capture as agents see it: with a neutral project name."""
|
|
467
|
+
text = (directory / "config.json").read_text(encoding="utf-8")
|
|
468
|
+
name = json.loads(text)["name"]
|
|
469
|
+
return text.replace(name, NEUTRAL_PROJECT)
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def capture_server(directory: Path) -> MCPServer:
|
|
473
|
+
"""StackDoctor's MCP server, serving a scenario's capture instead of running Compose."""
|
|
474
|
+
captured = RunResult(0, served_config(directory), "")
|
|
475
|
+
|
|
476
|
+
def runner(args: Sequence[str], *, cwd: Path, timeout: float) -> RunResult:
|
|
477
|
+
return captured
|
|
478
|
+
|
|
479
|
+
return create_server([directory], runner=runner, live_tools=False, log_level="WARNING")
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
# --- One run ------------------------------------------------------------------------
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
async def _run(job: Job, context: _Context) -> RunRecord:
|
|
486
|
+
created, agent, clock, sleep = context.created, context.agent, context.clock, context.sleep
|
|
487
|
+
common: dict[str, Any] = {
|
|
488
|
+
"scenario": job.scenario.name,
|
|
489
|
+
"group": job.scenario.answer.group,
|
|
490
|
+
"agent": job.agent,
|
|
491
|
+
"run": job.run,
|
|
492
|
+
"git_commit": context.git_commit,
|
|
493
|
+
"prompt_hash": context.fingerprint,
|
|
494
|
+
"attempts": context.attempts,
|
|
495
|
+
"agent_version": __version__,
|
|
496
|
+
"model": str(job.model) if job.model is not None else None,
|
|
497
|
+
}
|
|
498
|
+
started = clock()
|
|
499
|
+
if job.model is None:
|
|
500
|
+
report = validate_project(job.scenario.project)
|
|
501
|
+
return RunRecord(
|
|
502
|
+
**common,
|
|
503
|
+
finished_at=datetime.now(UTC),
|
|
504
|
+
settings={},
|
|
505
|
+
stop_reason="completed",
|
|
506
|
+
stop_detail=None,
|
|
507
|
+
duration_seconds=round(clock() - started, 3),
|
|
508
|
+
input_tokens=0,
|
|
509
|
+
output_tokens=0,
|
|
510
|
+
thinking_tokens=0,
|
|
511
|
+
estimated_cost_usd=0.0,
|
|
512
|
+
tool_calls=None,
|
|
513
|
+
model_calls=None,
|
|
514
|
+
score=score_report(job.scenario.answer, report),
|
|
515
|
+
answer=report.model_dump(mode="json"),
|
|
516
|
+
)
|
|
517
|
+
|
|
518
|
+
if job.agent == "holmesgpt":
|
|
519
|
+
assert job.model is not None # the baseline returned above
|
|
520
|
+
try:
|
|
521
|
+
fields = await holmes.run_holmes(
|
|
522
|
+
agent.path,
|
|
523
|
+
job.scenario.directory,
|
|
524
|
+
job.model.provider,
|
|
525
|
+
job.model.model,
|
|
526
|
+
job.scenario.answer,
|
|
527
|
+
runner=agent.runner,
|
|
528
|
+
clock=clock,
|
|
529
|
+
)
|
|
530
|
+
except holmes.HolmesRateLimited as error:
|
|
531
|
+
raise Deferred(str(error)) from None
|
|
532
|
+
return RunRecord(
|
|
533
|
+
**{**common, "agent_version": holmes.HOLMES_VERSION},
|
|
534
|
+
finished_at=datetime.now(UTC),
|
|
535
|
+
settings={"max_steps": str(holmes.MAX_STEPS)},
|
|
536
|
+
**fields,
|
|
537
|
+
)
|
|
538
|
+
|
|
539
|
+
watched = _Watched(created[str(job.model)])
|
|
540
|
+
spec = provider_spec(job.model.provider)
|
|
541
|
+
# Absolute: the server resolves a relative project_dir against its root,
|
|
542
|
+
# which is the scenario directory itself, so a relative path (as the
|
|
543
|
+
# command line loads scenarios) would point inside it and every tool call
|
|
544
|
+
# would fail. The model never sees project_dir: the loop passes it.
|
|
545
|
+
directory = job.scenario.directory.resolve()
|
|
546
|
+
diagnosis = await run_agent(
|
|
547
|
+
watched,
|
|
548
|
+
capture_server(directory),
|
|
549
|
+
project_dir=str(directory),
|
|
550
|
+
limits=Limits(
|
|
551
|
+
timeout_seconds=spec.max_time_seconds,
|
|
552
|
+
max_backoff_seconds=spec.max_backoff_seconds,
|
|
553
|
+
),
|
|
554
|
+
sleep=sleep,
|
|
555
|
+
)
|
|
556
|
+
run = diagnosis.run
|
|
557
|
+
if run.stop_reason == "provider_error" and watched.rate_limited:
|
|
558
|
+
raise Deferred(run.stop_detail or "rate limited")
|
|
559
|
+
stop_reason: str = run.stop_reason
|
|
560
|
+
stop_detail = run.stop_detail
|
|
561
|
+
if watched.tool_results and watched.tool_errors == watched.tool_results:
|
|
562
|
+
# The model never saw the project, so its answer says nothing about it.
|
|
563
|
+
stop_reason = TOOL_FAILURE
|
|
564
|
+
stop_detail = (
|
|
565
|
+
f"all {watched.tool_errors} tool calls returned an error "
|
|
566
|
+
f"(first: {watched.first_tool_error}); the run stopped with {run.stop_reason}"
|
|
567
|
+
+ (f": {run.stop_detail}" if run.stop_detail else "")
|
|
568
|
+
)
|
|
569
|
+
return RunRecord(
|
|
570
|
+
**common,
|
|
571
|
+
finished_at=datetime.now(UTC),
|
|
572
|
+
settings=dict(run.settings),
|
|
573
|
+
stop_reason=stop_reason,
|
|
574
|
+
stop_detail=stop_detail,
|
|
575
|
+
duration_seconds=run.duration_seconds,
|
|
576
|
+
input_tokens=run.input_tokens,
|
|
577
|
+
output_tokens=run.output_tokens,
|
|
578
|
+
thinking_tokens=run.thinking_tokens,
|
|
579
|
+
estimated_cost_usd=run.estimated_cost_usd,
|
|
580
|
+
tool_calls=run.tool_calls,
|
|
581
|
+
model_calls=run.model_calls,
|
|
582
|
+
score=score_diagnosis(job.scenario.answer, diagnosis),
|
|
583
|
+
answer=diagnosis.model_dump(mode="json"),
|
|
584
|
+
provider_errors=watched.errors,
|
|
585
|
+
tool_errors=watched.tool_errors,
|
|
586
|
+
)
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
@dataclass
|
|
590
|
+
class _HolmesAgent:
|
|
591
|
+
"""Where HolmesGPT is and how to start it; checked once, before any run."""
|
|
592
|
+
|
|
593
|
+
configured: str | None
|
|
594
|
+
runner: holmes.Runner
|
|
595
|
+
path: str = ""
|
|
596
|
+
|
|
597
|
+
def prepare(self, providers: set[str]) -> None:
|
|
598
|
+
self.path = self.configured or holmes.find_holmes()
|
|
599
|
+
found = self.runner(
|
|
600
|
+
[self.path, "version"], capture_output=True, text=True, check=False, timeout=120
|
|
601
|
+
)
|
|
602
|
+
installed = (found.stdout or "").strip().splitlines()
|
|
603
|
+
if not installed or installed[-1].strip() != holmes.HOLMES_VERSION:
|
|
604
|
+
raise ProviderUnavailableError(
|
|
605
|
+
f"The benchmark needs HolmesGPT {holmes.HOLMES_VERSION}; found "
|
|
606
|
+
f"{installed[-1] if installed else 'no version'}. Install it with: {holmes.INSTALL}"
|
|
607
|
+
)
|
|
608
|
+
for provider in sorted(providers):
|
|
609
|
+
holmes.check_key(provider)
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
class _Watched:
|
|
613
|
+
"""A provider that remembers the last error its sessions raised.
|
|
614
|
+
|
|
615
|
+
It also counts the tool results the model received, and those that were
|
|
616
|
+
errors: a result the loop wraps as tool output whose payload is an error.
|
|
617
|
+
The loop's own notes (an unknown tool, the call limit) are not tool output.
|
|
618
|
+
"""
|
|
619
|
+
|
|
620
|
+
def __init__(self, provider: LLMProvider) -> None:
|
|
621
|
+
self._provider = provider
|
|
622
|
+
self.last_error: ProviderError | None = None
|
|
623
|
+
self.errors = 0
|
|
624
|
+
self.tool_results = 0
|
|
625
|
+
self.tool_errors = 0
|
|
626
|
+
self.first_tool_error: str | None = None
|
|
627
|
+
|
|
628
|
+
def count(self, message: str | Sequence[ToolResult]) -> None:
|
|
629
|
+
"""Count the tool results in a message the provider accepted."""
|
|
630
|
+
if isinstance(message, str):
|
|
631
|
+
return
|
|
632
|
+
for result in message:
|
|
633
|
+
output = result.content.get("untrusted_tool_output")
|
|
634
|
+
if output is None:
|
|
635
|
+
continue
|
|
636
|
+
self.tool_results += 1
|
|
637
|
+
if isinstance(output, dict) and "error" in output:
|
|
638
|
+
self.tool_errors += 1
|
|
639
|
+
if self.first_tool_error is None:
|
|
640
|
+
self.first_tool_error = str(output["error"])[:ERROR_EXCERPT]
|
|
641
|
+
|
|
642
|
+
@property
|
|
643
|
+
def rate_limited(self) -> bool:
|
|
644
|
+
error = self.last_error
|
|
645
|
+
return error is not None and (error.kind == "exhausted" or error.status == RATE_LIMITED)
|
|
646
|
+
|
|
647
|
+
@property
|
|
648
|
+
def name(self) -> str:
|
|
649
|
+
return self._provider.name
|
|
650
|
+
|
|
651
|
+
@property
|
|
652
|
+
def model(self) -> str:
|
|
653
|
+
return self._provider.model
|
|
654
|
+
|
|
655
|
+
@property
|
|
656
|
+
def settings(self) -> Mapping[str, str]:
|
|
657
|
+
return self._provider.settings
|
|
658
|
+
|
|
659
|
+
@property
|
|
660
|
+
def can_force_tool(self) -> bool:
|
|
661
|
+
return self._provider.can_force_tool
|
|
662
|
+
|
|
663
|
+
@property
|
|
664
|
+
def max_request_tokens(self) -> int | None:
|
|
665
|
+
return self._provider.max_request_tokens
|
|
666
|
+
|
|
667
|
+
def price(self) -> Price | None:
|
|
668
|
+
return self._provider.price()
|
|
669
|
+
|
|
670
|
+
def start(self, system: str, tools: Sequence[ToolSpec]) -> Session:
|
|
671
|
+
return _WatchedSession(self, self._provider.start(system, tools))
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
@dataclass
|
|
675
|
+
class _WatchedSession:
|
|
676
|
+
owner: _Watched
|
|
677
|
+
session: Session
|
|
678
|
+
|
|
679
|
+
async def send(
|
|
680
|
+
self, message: str | Sequence[ToolResult], *, force_tool: str | None = None
|
|
681
|
+
) -> Turn:
|
|
682
|
+
try:
|
|
683
|
+
turn = await self.session.send(message, force_tool=force_tool)
|
|
684
|
+
except ProviderError as error:
|
|
685
|
+
self.owner.last_error = error
|
|
686
|
+
self.owner.errors += 1
|
|
687
|
+
raise
|
|
688
|
+
self.owner.last_error = None
|
|
689
|
+
# Counted once accepted: a message that failed is sent again, and
|
|
690
|
+
# would otherwise be counted twice.
|
|
691
|
+
self.owner.count(message)
|
|
692
|
+
return turn
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def _write(path: Path, record: RunRecord) -> None:
|
|
696
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
697
|
+
partial = path.with_suffix(".partial")
|
|
698
|
+
partial.write_text(record.model_dump_json(indent=2) + "\n", encoding="utf-8")
|
|
699
|
+
# A whole file or none: an interrupted write is never mistaken for a run.
|
|
700
|
+
partial.replace(path)
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
def _line(record: RunRecord) -> str:
|
|
704
|
+
score = record.score
|
|
705
|
+
bugs = f"bugs {len(score.bugs_found)}/{score.bugs_total}" if score.bugs_total else ""
|
|
706
|
+
verdict = "ok" if score.status_correct else "wrong"
|
|
707
|
+
return (
|
|
708
|
+
f"{record.scenario} | {record.agent} {record.model or ''} #{record.run} | "
|
|
709
|
+
f"{record.stop_reason}, verdict {verdict} {bugs} | {record.duration_seconds:.1f}s"
|
|
710
|
+
)
|