返回 last30days-skill
e2e_comparison.py
根目录 / tests / e2e_comparison.py
1 #!/usr/bin/env python3
2 """E2E comparison: run sample queries on both v3 (current branch) and v2.9.5 (main).
3
4 Usage:
5 python3 tests/e2e_comparison.py [--v2-script PATH]
6
7 Outputs a markdown comparison table with per-query metrics.
8 Passed comparisons exit 0; failed or partial comparisons exit 1, including
9 otherwise successful commands that report source errors.
10 Comparison totals sum the metrics of each entity report.
11 """
12
13 import json
14 import subprocess
15 import sys
16 import time
17 from pathlib import Path
18
19 REPO = Path(__file__).resolve().parents[1]
20 V3_SCRIPT = str(REPO / "skills" / "last30days" / "scripts" / "last30days.py")
21
22 # v2.9.5 from plugin cache (main branch equivalent)
23 V2_SCRIPT = str(
24 Path.home()
25 / ".claude/plugins/cache/last30days/last30days/2.9.5/scripts/last30days.py"
26 )
27
28 EVAL_TOPICS_FILE = REPO / "fixtures" / "eval_topics.json"
29
30
31 def _load_queries() -> list[tuple[str, str]]:
32 if EVAL_TOPICS_FILE.exists():
33 rows = json.loads(EVAL_TOPICS_FILE.read_text())
34 return [(row["topic"], row["query_type"]) for row in rows]
35 return [
36 ("openclaw vs nanoclaw vs ironclaw", "comparison"),
37 ("how to deploy on Fly.io", "how_to"),
38 ("kanye west", "breaking_news"),
39 ("odds of recession", "prediction"),
40 ("explain transformer architecture", "concept"),
41 ]
42
43
44 QUERIES = _load_queries()
45
46
47 def _v3_metrics(data: dict) -> dict:
48 items_by_source = data.get("items_by_source", {})
49 errors = list(data.get("errors_by_source", {}))
50 for source, outcome in data.get("source_status", {}).items():
51 if outcome.get("state") in {
52 "partial", "rate-limited", "auth-failed", "payment-required",
53 "unreachable", "timeout", "schema-drift", "error",
54 } and source not in errors:
55 errors.append(source)
56 return {
57 "sources": sum(1 for items in items_by_source.values() if items),
58 "total_items": sum(len(items) for items in items_by_source.values()),
59 "candidates": len(data.get("ranked_candidates", [])),
60 "clusters": len(data.get("clusters", [])),
61 "intent": data["query_plan"].get("intent", "?"),
62 "subqueries": len(data["query_plan"].get("subqueries", [])),
63 "errors": errors,
64 }
65
66
67 def run_query(script: str, topic: str, timeout: int = 180) -> dict:
68 """Run a query and return parsed JSON + timing."""
69 start = time.time()
70 try:
71 result = subprocess.run(
72 [sys.executable, script, topic, "--emit=json", "--json-profile=raw"],
73 capture_output=True,
74 text=True,
75 timeout=timeout,
76 )
77 elapsed = time.time() - start
78 if result.returncode != 0:
79 return {
80 "error": result.stderr[:200] or f"engine exited with status {result.returncode}",
81 "elapsed": elapsed,
82 "sources": 0,
83 "candidates": 0,
84 "intent": "error",
85 "subqueries": 0,
86 }
87 data = json.loads(result.stdout)
88
89 if data.get("comparison"):
90 reports = [(entry["entity"], _v3_metrics(entry["report"])) for entry in data["reports"]]
91 if not reports:
92 raise ValueError("comparison output contains no reports")
93 return {
94 "elapsed": elapsed,
95 **{key: sum(metrics[key] for _, metrics in reports) for key in (
96 "sources", "total_items", "candidates", "clusters", "subqueries",
97 )},
98 "intent": "comparison",
99 "errors": [f"{entity}: {error}" for entity, metrics in reports for error in metrics["errors"]],
100 }
101
102 # v3 shape
103 if "query_plan" in data:
104 return {"elapsed": elapsed, **_v3_metrics(data)}
105
106 # v2 shape
107 sources_with_items = 0
108 total_items = 0
109 for key in ["reddit", "x", "youtube", "tiktok", "instagram", "hackernews",
110 "bluesky", "truthsocial", "polymarket", "web"]:
111 items = data.get(key, [])
112 if items:
113 sources_with_items += 1
114 total_items += len(items)
115 return {
116 "elapsed": elapsed,
117 "sources": sources_with_items,
118 "total_items": total_items,
119 "candidates": total_items,
120 "clusters": 0,
121 "intent": data.get("mode", "?"),
122 "subqueries": 0,
123 "errors": [k for k in ["reddit_error", "x_error", "youtube_error",
124 "tiktok_error", "instagram_error"]
125 if data.get(k)],
126 }
127 except subprocess.TimeoutExpired:
128 return {
129 "error": "timeout",
130 "elapsed": timeout,
131 "sources": 0,
132 "candidates": 0,
133 "intent": "timeout",
134 "subqueries": 0,
135 }
136 except Exception as exc:
137 return {
138 "error": str(exc)[:200],
139 "elapsed": time.time() - start,
140 "sources": 0,
141 "candidates": 0,
142 "intent": "error",
143 "subqueries": 0,
144 }
145
146
147 def main() -> int:
148 v2_script = V2_SCRIPT
149 if len(sys.argv) > 2 and sys.argv[1] == "--v2-script":
150 v2_script = sys.argv[2]
151
152 if not Path(v2_script).exists():
153 print(f"v2 script not found at {v2_script}", file=sys.stderr)
154 print("Use --v2-script PATH to specify", file=sys.stderr)
155 sys.exit(1)
156
157 print("# E2E Comparison: v3.0.0 (branch) vs v2.9.5 (main)")
158 print()
159 print(f"- v3 script: {V3_SCRIPT}")
160 print(f"- v2 script: {v2_script}")
161 print(f"- Queries: {len(QUERIES)}")
162 print()
163
164 results = []
165 for i, (topic, expected_intent) in enumerate(QUERIES, 1):
166 print(f"[{i}/{len(QUERIES)}] {topic}", file=sys.stderr)
167 sys.stderr.flush()
168
169 print(f" v3...", end="", file=sys.stderr)
170 sys.stderr.flush()
171 v3 = run_query(V3_SCRIPT, topic)
172 print(f" {v3.get('elapsed', 0):.1f}s", file=sys.stderr)
173 sys.stderr.flush()
174
175 print(f" v2...", end="", file=sys.stderr)
176 sys.stderr.flush()
177 v2 = run_query(v2_script, topic)
178 print(f" {v2.get('elapsed', 0):.1f}s", file=sys.stderr)
179 sys.stderr.flush()
180
181 results.append({
182 "topic": topic,
183 "expected_intent": expected_intent,
184 "v3": v3,
185 "v2": v2,
186 })
187
188 # Print comparison table
189 print("| Query | Intent | v3 sources | v2 sources | v3 items | v2 items | v3 time | v2 time | v3 source errors | v2 source errors | v3 command error | v2 command error |")
190 print("|-------|--------|-----------|-----------|---------|---------|---------|---------|-----------|-----------|-----------|-----------|")
191 for r in results:
192 v3, v2 = r["v3"], r["v2"]
193 v3_err = ", ".join(v3.get("errors", [])) or "-"
194 v2_err = ", ".join(v2.get("errors", [])) or "-"
195 v3_command_error = str(v3.get("error", "-")).replace("|", "\\|").replace("\n", " ")
196 v2_command_error = str(v2.get("error", "-")).replace("|", "\\|").replace("\n", " ")
197 print(
198 f"| {r['topic'][:45]} | {v3.get('intent', '?')} | "
199 f"{v3.get('sources', 0)} | {v2.get('sources', 0)} | "
200 f"{v3.get('total_items', 0)} | {v2.get('total_items', 0)} | "
201 f"{v3.get('elapsed', 0):.1f}s | {v2.get('elapsed', 0):.1f}s | "
202 f"{v3_err} | {v2_err} | {v3_command_error} | {v2_command_error} |"
203 )
204
205 # Summary
206 print()
207 v3_total_sources = sum(r["v3"].get("sources", 0) for r in results)
208 v2_total_sources = sum(r["v2"].get("sources", 0) for r in results)
209 v3_total_items = sum(r["v3"].get("total_items", 0) for r in results)
210 v2_total_items = sum(r["v2"].get("total_items", 0) for r in results)
211 v3_total_time = sum(r["v3"].get("elapsed", 0) for r in results)
212 v2_total_time = sum(r["v2"].get("elapsed", 0) for r in results)
213 v3_errors = sum(len(r["v3"].get("errors", [])) for r in results)
214 v2_errors = sum(len(r["v2"].get("errors", [])) for r in results)
215 v3_command_errors = sum("error" in r["v3"] for r in results)
216 v2_command_errors = sum("error" in r["v2"] for r in results)
217 command_errors = v3_command_errors + v2_command_errors
218 outcome = (
219 "failed" if command_errors == 2 * len(results)
220 else "partial" if command_errors or v3_errors or v2_errors
221 else "passed"
222 )
223
224 print("## Summary")
225 print()
226 print(f"| Metric | v3.0.0 | v2.9.5 | Delta |")
227 print(f"|--------|--------|--------|-------|")
228 print(f"| Total sources with items | {v3_total_sources} | {v2_total_sources} | {v3_total_sources - v2_total_sources:+d} |")
229 print(f"| Total items retrieved | {v3_total_items} | {v2_total_items} | {v3_total_items - v2_total_items:+d} |")
230 print(f"| Total wall time | {v3_total_time:.1f}s | {v2_total_time:.1f}s | {v3_total_time - v2_total_time:+.1f}s |")
231 print(f"| Source errors | {v3_errors} | {v2_errors} | {v3_errors - v2_errors:+d} |")
232 print(f"| Command errors | {v3_command_errors} | {v2_command_errors} | {v3_command_errors - v2_command_errors:+d} |")
233 print(f"| Avg sources/query | {v3_total_sources/len(results):.1f} | {v2_total_sources/len(results):.1f} | |")
234 print(f"| Avg items/query | {v3_total_items/len(results):.1f} | {v2_total_items/len(results):.1f} | |")
235 print(f"| Avg time/query | {v3_total_time/len(results):.1f}s | {v2_total_time/len(results):.1f}s | |")
236 print(f"\nOutcome: {outcome}")
237 return 0 if outcome == "passed" else 1
238
239
240 if __name__ == "__main__":
241 sys.exit(main())
242
242 lines PYTHON