Repository navigation
Expand file tree
/
Copy patheval.py
More file actions
219 lines (184 loc) · 8.93 KB
/
Copy patheval.py
File metadata and controls
219 lines (184 loc) · 8.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
"""
eval.py - Strict benchmark runner for DevContext.
A scenario counts as correct only if the predicted root_cause_type equals the
ground truth, and (for bad_deploy) the blamed commit equals the culprit commit.
There is no pass-by-default branch.
Usage:
python eval.py # handwritten + generated, rule-based
python eval.py --set generated
python eval.py --method rule --json results/rule.json
python eval.py --verbose # print every failure
# LLM methods (need GROQ_API_KEY):
python eval.py --method llm_raw --runs 3 --json results/llm_raw.json
python eval.py --method agent --runs 3 --json results/agent.json
python eval.py --method agent_verified --runs 3 --json results/agent_verified.json
--split dev|test|all dev = handwritten + seed 0, test = seeds 1-2. Tune prompts on
dev only, then report test, so the numbers are not fitted.
--filter TEXT only scenarios whose name contains TEXT (cheap smoke runs)
"""
import argparse
import json
import os
import subprocess
import sys
from collections import Counter, defaultdict
from pathlib import Path
from tools import diagnose
_HERE = Path(__file__).parent
_HANDWRITTEN = _HERE / "eval_scenarios"
_GENERATED = _HERE / "benchmark" / "scenarios"
# Older handwritten scenarios use "bad_migration"; it is a bad deploy.
_TYPE_ALIASES = {"bad_migration": "bad_deploy"}
# --------------------------------------------------------------------------
# Methods: (scenario_dir, service) -> {"root_cause_type": str, "commit": str|None}
# --------------------------------------------------------------------------
def method_rule(scenario_dir: Path, service: str, run: int = 0) -> dict:
res = diagnose(service, data_dir=scenario_dir)
return {"root_cause_type": res["root_cause_type"], "commit": res.get("suspect_commit")}
def get_method(name: str):
if name == "rule":
return method_rule
import agent # lazy: the rule-based path needs no LLM dependencies
return {"llm_raw": agent.method_llm_raw, "agent": agent.method_agent,
"agent_verified": agent.method_agent_verified}[name]
METHOD_NAMES = ["rule", "llm_raw", "agent", "agent_verified"]
# --------------------------------------------------------------------------
def load_scenarios(which: str, split: str = "all", name_filter: str = ""):
dirs = []
if which in ("handwritten", "all"):
dirs += sorted(d for d in _HANDWRITTEN.iterdir() if d.is_dir())
if which in ("generated", "all"):
if not _GENERATED.exists():
subprocess.run([sys.executable, str(_HERE / "benchmark" / "generate.py")], check=True)
dirs += sorted(d for d in _GENERATED.iterdir() if d.is_dir())
if split != "all":
def seed(d): # generated names end with __<seed>; handwritten ones count as dev
tail = d.name.rsplit("__", 1)[-1]
return int(tail) if tail.isdigit() and "__" in d.name else 0
dirs = [d for d in dirs if (seed(d) == 0) == (split == "dev")]
if name_filter:
dirs = [d for d in dirs if name_filter in d.name]
return dirs
def score(scenario_dir: Path, method, run: int = 0) -> dict:
exp = json.loads((scenario_dir / "expected_diagnosis.json").read_text(encoding="utf-8"))
truth = _TYPE_ALIASES.get(exp["root_cause_type"], exp["root_cause_type"])
try:
pred = method(scenario_dir, exp["service"], run)
pred_type = pred["root_cause_type"]
commit_ok = truth != "bad_deploy" or pred.get("commit") == exp.get("correct_commit")
correct = pred_type == truth and commit_ok
err = None
except Exception as e: # a crash is a failure, not a skipped scenario
if type(e).__name__ == "DailyLimitError":
raise # no point continuing: every remaining call would fail the same way
pred_type, correct, err = "crash", False, f"{type(e).__name__}: {e}"
return {
"scenario": scenario_dir.name,
"family": truth,
"variant": exp.get("variant", "handwritten"),
"log_format": exp.get("log_format", "text"),
"predicted": pred_type,
"correct": correct,
"error": err,
"run": run,
"usage": pred.get("usage") if err is None else None,
}
def pct(c, n):
return f"{100 * c / n:5.1f}% ({c}/{n})" if n else "n/a"
def breakdown(results, key):
groups = defaultdict(lambda: [0, 0])
for r in results:
groups[r[key]][1] += 1
groups[r[key]][0] += r["correct"]
for k in sorted(groups):
print(f" {k:<26} {pct(*groups[k])}")
def list_models():
base_url = os.getenv("DEVCONTEXT_BASE_URL")
api_key = os.getenv("DEVCONTEXT_API_KEY")
missing = []
if not base_url:
missing.append("DEVCONTEXT_BASE_URL")
if not api_key:
missing.append("DEVCONTEXT_API_KEY")
if missing:
if len(missing) == 1:
raise ValueError(f"Missing required environment variable for --list-models: {missing[0]}")
raise ValueError(f"Missing required environment variables for --list-models: {', '.join(missing)}")
from openai import OpenAI
client = OpenAI(base_url=base_url, api_key=api_key)
res = client.models.list()
ids = sorted(getattr(m, "id", str(m)) for m in res)
for mid in ids:
print(mid)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--list-models", action="store_true", help="print model IDs from endpoint and exit")
ap.add_argument("--set", default="all", choices=["handwritten", "generated", "all"])
ap.add_argument("--split", default="all", choices=["dev", "test", "all"])
ap.add_argument("--method", default="rule", choices=METHOD_NAMES)
ap.add_argument("--runs", type=int, default=1, help="repeat each scenario N times")
ap.add_argument("--filter", default="", help="only scenarios whose name contains this")
ap.add_argument("--json", help="write per-run results to this path")
ap.add_argument("--verbose", action="store_true")
args = ap.parse_args()
if args.list_models:
list_models()
return
method = get_method(args.method)
dirs = load_scenarios(args.set, args.split, args.filter)
results = []
jobs = [(d, run) for d in dirs for run in range(args.runs)]
try:
for i, (d, run) in enumerate(jobs, 1):
r = score(d, method, run)
results.append(r)
tok = f" {r['usage']['tokens']} tok" if r.get("usage") else ""
status = "ok " if r["correct"] else "FAIL"
print(f"[{i}/{len(jobs)}] {status} {d.name} run{run} -> {r['predicted']}{tok}"
f"{' ' + r['error'] if r['error'] else ''}", flush=True)
except (KeyboardInterrupt, RuntimeError) as e:
print(f"\nStopped early: {e}\nReporting {len(results)}/{len(jobs)} completed runs. "
f"Rerun the same command to resume; finished scenarios come from the cache.")
total = len(results)
if not total:
return
correct = sum(r["correct"] for r in results)
print(f"\nMETHOD: {args.method} SET: {args.set} SPLIT: {args.split} "
f"SCENARIOS: {len(dirs)} RUNS: {args.runs}")
print(f"OVERALL: {pct(correct, total)}")
print("\nBy family:"); breakdown(results, "family")
print("\nBy variant:"); breakdown(results, "variant")
print("\nBy log format:"); breakdown(results, "log_format")
used = [r["usage"] for r in results if r.get("usage")]
if used:
n = len(used)
print(f"\nCost per scenario: {sum(u['tokens'] for u in used) / n:.0f} tokens, "
f"{sum(u['latency_s'] for u in used) / n:.1f}s API latency, "
f"{sum(u['calls'] for u in used) / n:.1f} LLM calls")
if args.runs > 1:
by_scn = defaultdict(list)
for r in results:
by_scn[r["scenario"]].append(r["correct"])
unstable = sum(0 < sum(v) < len(v) for v in by_scn.values())
print(f"Unstable scenarios (correct in some runs, not others): {unstable}/{len(by_scn)}")
confusions = Counter((r["family"], r["predicted"]) for r in results if not r["correct"])
if confusions:
print("\nTop failure modes (truth -> predicted):")
for (t, p), n in confusions.most_common(6):
print(f" {t:<24} -> {p:<24} x{n}")
crashes = [r for r in results if r["error"]]
if crashes:
print(f"\nCRASHES: {len(crashes)}. First error: {crashes[0]['error']}")
if args.verbose:
print("\nFailures:")
for r in results:
if not r["correct"]:
print(f" {r['scenario']:<40} run={r['run']} predicted={r['predicted']} {r['error'] or ''}")
if args.json:
Path(args.json).parent.mkdir(parents=True, exist_ok=True)
Path(args.json).write_text(json.dumps(
{"method": args.method, "set": args.set, "split": args.split, "runs": args.runs,
"accuracy": correct / total if total else None, "n": total, "results": results},
indent=2), encoding="utf-8")
if __name__ == "__main__":
main()