openai-mock 4.0.0__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.
bench/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """GPT-Zero benchmark harness.
2
+
3
+ 只通过 HTTP 与 mock 服务交互(不 import ``gptzero`` 内部实现,tokenizer 计数除外,
4
+ 见 CONTRACT.md §4)。入口:``python -m bench`` 或 ``gptzero-bench``。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ __version__ = "0.1.0"
10
+
11
+ __all__ = ["__version__"]
bench/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Allow ``python -m bench ...``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from .cli import main
8
+
9
+ if __name__ == "__main__": # pragma: no cover - thin wrapper
10
+ sys.exit(main())
bench/aggregate.py ADDED
@@ -0,0 +1,185 @@
1
+ """分位数与聚合。
2
+
3
+ 输入是 runner 记录的逐请求字典(``bench.client.RequestResult.to_dict()``),
4
+ 输出是可直接 JSON 序列化、并驱动报告/图表的汇总结构。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ from typing import Any, Iterable, Sequence
11
+
12
+ from .util import flatten, safe_div
13
+
14
+ PERCENTILES = (50.0, 90.0, 95.0, 99.0)
15
+
16
+
17
+ def percentile(values: Sequence[float], p: float) -> float | None:
18
+ """线性插值分位数(与 numpy 默认 ``linear`` 一致)。
19
+
20
+ * 空样本 → ``None``(报告里显示 ``-``,不伪造 0);
21
+ * 单样本 → 该值;
22
+ * 非有限值会被忽略。
23
+ """
24
+ if not values:
25
+ return None
26
+ clean = sorted(float(v) for v in values if v is not None and math.isfinite(float(v)))
27
+ n = len(clean)
28
+ if n == 0:
29
+ return None
30
+ if n == 1:
31
+ return clean[0]
32
+ if p <= 0:
33
+ return clean[0]
34
+ if p >= 100:
35
+ return clean[-1]
36
+ rank = (n - 1) * p / 100.0
37
+ lo = math.floor(rank)
38
+ hi = math.ceil(rank)
39
+ if lo == hi:
40
+ return clean[lo]
41
+ weight = rank - lo
42
+ return clean[lo] * (1.0 - weight) + clean[hi] * weight
43
+
44
+
45
+ def mean(values: Sequence[float]) -> float | None:
46
+ if not values:
47
+ return None
48
+ clean = [float(v) for v in values if v is not None and math.isfinite(float(v))]
49
+ if not clean:
50
+ return None
51
+ return sum(clean) / len(clean)
52
+
53
+
54
+ def summarize(values: Sequence[float] | None) -> dict[str, float | int | None]:
55
+ """p50/p90/p95/p99/mean/max/min + count。空样本返回全 None、count=0。"""
56
+ data = list(values or [])
57
+ clean = [float(v) for v in data if v is not None and math.isfinite(float(v))]
58
+ if not clean:
59
+ return {
60
+ "count": 0,
61
+ "p50": None,
62
+ "p90": None,
63
+ "p95": None,
64
+ "p99": None,
65
+ "mean": None,
66
+ "max": None,
67
+ "min": None,
68
+ }
69
+ return {
70
+ "count": len(clean),
71
+ "p50": percentile(clean, 50),
72
+ "p90": percentile(clean, 90),
73
+ "p95": percentile(clean, 95),
74
+ "p99": percentile(clean, 99),
75
+ "mean": mean(clean),
76
+ "max": max(clean),
77
+ "min": min(clean),
78
+ }
79
+
80
+
81
+ def cache_hit_rate(hit_tokens: float | int | None, query_tokens: float | int | None) -> float | None:
82
+ return safe_div(hit_tokens, query_tokens)
83
+
84
+
85
+ def _samples(records: Iterable[dict[str, Any]], key: str) -> list[float]:
86
+ out: list[float] = []
87
+ for rec in records:
88
+ value = rec.get(key)
89
+ if value is not None:
90
+ out.append(float(value))
91
+ return out
92
+
93
+
94
+ def _itl_samples(records: Iterable[dict[str, Any]]) -> list[float]:
95
+ out: list[float] = []
96
+ for rec in records:
97
+ out.extend(float(v) for v in (rec.get("itl_ms") or []))
98
+ return out
99
+
100
+
101
+ def summarize_records(records: Sequence[dict[str, Any]]) -> dict[str, Any]:
102
+ """对一组成功请求统计延迟(TTFT/TPOT/E2E 按请求,ITL 按帧)。"""
103
+ return {
104
+ "ttft_ms": summarize(_samples(records, "ttft_ms")),
105
+ "tpot_ms": summarize(_samples(records, "tpot_ms")),
106
+ "e2e_ms": summarize(_samples(records, "e2e_ms")),
107
+ "itl_ms": summarize(_itl_samples(records)),
108
+ }
109
+
110
+
111
+ def _tokens(records: Sequence[dict[str, Any]]) -> dict[str, int]:
112
+ prompt = sum(int(r.get("prompt_tokens") or 0) for r in records)
113
+ completion = sum(int(r.get("completion_tokens") or 0) for r in records)
114
+ tool_calls = sum(int(r.get("tool_calls") or 0) for r in records)
115
+ return {"prompt": prompt, "completion": completion, "tool_calls": tool_calls}
116
+
117
+
118
+ def aggregate_records(records: Sequence[dict[str, Any]], wall_s: float | None) -> dict[str, Any]:
119
+ """汇总一个并发点。``wall_s`` 为实测窗口(用于 RPS / tok/s)。
120
+
121
+ 失败请求计入失败率与总请求数,但不进入延迟分位数。
122
+ """
123
+ total = len(records)
124
+ success = [r for r in records if r.get("ok")]
125
+ failed = [r for r in records if not r.get("ok")]
126
+ tokens = _tokens(success)
127
+ wall = wall_s if wall_s and wall_s > 0 else None
128
+ summary = summarize_records(success)
129
+
130
+ per_profile: dict[str, Any] = {}
131
+ for profile in sorted({str(r.get("profile") or "unknown") for r in records}):
132
+ group_all = [r for r in records if str(r.get("profile") or "unknown") == profile]
133
+ group_ok = [r for r in group_all if r.get("ok")]
134
+ group_tokens = _tokens(group_ok)
135
+ per_profile[profile] = {
136
+ "requests": {"total": len(group_all), "success": len(group_ok), "failed": len(group_all) - len(group_ok)},
137
+ "tokens": group_tokens,
138
+ "summary": summarize_records(group_ok),
139
+ "rps": safe_div(len(group_ok), wall),
140
+ "input_tokens_per_s": safe_div(group_tokens["prompt"], wall),
141
+ "output_tokens_per_s": safe_div(group_tokens["completion"], wall),
142
+ "samples": {
143
+ "ttft_ms": sorted(float(r["ttft_ms"]) for r in group_ok if r.get("ttft_ms") is not None),
144
+ "e2e_ms": sorted(float(r["e2e_ms"]) for r in group_ok if r.get("e2e_ms") is not None),
145
+ },
146
+ }
147
+
148
+ return {
149
+ "requests": {
150
+ "total": total,
151
+ "success": len(success),
152
+ "failed": len(failed),
153
+ "failure_rate": safe_div(len(failed), total),
154
+ "sub_requests": sum(1 for r in records if r.get("label") == "sub"),
155
+ "tool_call_requests": sum(1 for r in success if int(r.get("tool_calls") or 0) > 0),
156
+ },
157
+ "tokens": tokens,
158
+ "rates": {
159
+ "rps": safe_div(total, wall),
160
+ "success_rps": safe_div(len(success), wall),
161
+ "input_tokens_per_s": safe_div(tokens["prompt"], wall),
162
+ "output_tokens_per_s": safe_div(tokens["completion"], wall),
163
+ "total_tokens_per_s": safe_div(tokens["prompt"] + tokens["completion"], wall),
164
+ },
165
+ "summary": summary,
166
+ "per_profile": per_profile,
167
+ "errors": _error_summary(failed),
168
+ "samples": {
169
+ "ttft_ms": sorted(float(r["ttft_ms"]) for r in success if r.get("ttft_ms") is not None),
170
+ "e2e_ms": sorted(float(r["e2e_ms"]) for r in success if r.get("e2e_ms") is not None),
171
+ },
172
+ }
173
+
174
+
175
+ def _error_summary(failed: Sequence[dict[str, Any]], limit: int = 5) -> list[dict[str, Any]]:
176
+ counts: dict[str, int] = {}
177
+ for rec in failed:
178
+ key = str(rec.get("error") or "unknown")[:240]
179
+ counts[key] = counts.get(key, 0) + 1
180
+ ordered = sorted(counts.items(), key=lambda kv: kv[1], reverse=True)[:limit]
181
+ return [{"error": msg, "count": count} for msg, count in ordered]
182
+
183
+
184
+ def combined_itl(records: Sequence[dict[str, Any]]) -> list[float]:
185
+ return flatten(rec.get("itl_ms") or [] for rec in records)
bench/cli.py ADDED
@@ -0,0 +1,352 @@
1
+ """命令行入口:``python -m bench`` / ``gptzero-bench``。
2
+
3
+ 子命令::
4
+
5
+ python -m bench run --url http://127.0.0.1:8090 --profile coding \
6
+ --concurrency 8 --duration 20 --out results/x.json
7
+ python -m bench sweep --url http://127.0.0.1:8090 --profiles chat,coding,agentic \
8
+ --concurrency 1,2,4,8,16 --duration 10 --name sweep
9
+ python -m bench report results/x.json
10
+ python -m bench serve-sweep --launch-server --port 8099 --ttft-ms 120 --tpot-ms 8 \
11
+ --max-concurrency 64 --profiles coding --concurrency 1,2,4,8,16
12
+
13
+ 默认端口是 **8090**(本机 8080 被其他常驻服务占用,见 CONTRACT/文档)。
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import asyncio
20
+ import socket
21
+ import subprocess
22
+ import sys
23
+ import time
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ from . import __version__
28
+ from .report import write_outputs
29
+ from .runner import BenchConfig, build_document, run_point, run_sweep
30
+ from .util import REPO_ROOT, RESULTS_DIR, now_iso, write_json
31
+
32
+ DEFAULT_URL = "http://127.0.0.1:8090"
33
+
34
+
35
+ # ---------------------------------------------------------------------------
36
+ # 参数
37
+ # ---------------------------------------------------------------------------
38
+
39
+
40
+ def _parse_list(value: str) -> list[str]:
41
+ return [item.strip() for item in value.split(",") if item.strip()]
42
+
43
+
44
+ def _parse_int_list(value: str) -> list[int]:
45
+ try:
46
+ items = [int(item) for item in _parse_list(value)]
47
+ except ValueError as exc:
48
+ raise argparse.ArgumentTypeError(f"invalid concurrency list: {value!r}") from exc
49
+ if not items:
50
+ raise argparse.ArgumentTypeError("concurrency list is empty")
51
+ return items
52
+
53
+
54
+ def _add_bench_options(parser: argparse.ArgumentParser) -> None:
55
+ parser.add_argument("--url", default=DEFAULT_URL, help=f"mock 服务地址(默认 {DEFAULT_URL})")
56
+ parser.add_argument("--model", default="gpt-3.5-turbo", help="模型名")
57
+ parser.add_argument("--duration", type=float, default=20.0, help="每个并发点的测量时长(秒)")
58
+ parser.add_argument("--warmup", type=int, default=3, help="预热请求数(不计入统计)")
59
+ parser.add_argument("--seed", type=int, default=42, help="会话生成种子")
60
+ parser.add_argument("--timeout", type=float, default=300.0, help="单请求读超时(秒)")
61
+ parser.add_argument("--max-tokens", type=int, default=None, help="覆盖 profile 默认输出长度")
62
+ parser.add_argument("--fail-fast", action="store_true", help="首个请求失败立即中止")
63
+ parser.add_argument("--no-charts", action="store_true", help="不生成图表")
64
+ parser.add_argument("--charts-dir", default=None, help="图表目录(默认 <结果目录>/charts)")
65
+ parser.add_argument("--notes", default=None, help="写入结果 JSON 的备注(分号分隔)")
66
+
67
+
68
+ def build_parser() -> argparse.ArgumentParser:
69
+ parser = argparse.ArgumentParser(
70
+ prog="python -m bench",
71
+ description="GPT-Zero mock 推理服务压测 harness(闭环并发 + SSE 精确时延 + 图表)",
72
+ )
73
+ parser.add_argument("--version", action="version", version=f"gptzero-bench {__version__}")
74
+ sub = parser.add_subparsers(dest="command", required=True)
75
+
76
+ run = sub.add_parser("run", help="单并发点压测")
77
+ _add_bench_options(run)
78
+ run.add_argument("--profile", default="coding", help="chat|coding|agentic|longctx")
79
+ run.add_argument("--concurrency", type=int, default=8, help="闭环会话数")
80
+ run.add_argument("--out", default=str(RESULTS_DIR / "run.json"), help="结果 JSON 路径")
81
+ run.add_argument("--report", action="store_true", help="同时生成 md/csv/图")
82
+
83
+ sweep = sub.add_parser("sweep", help="多并发/多 profile 扫描")
84
+ _add_bench_options(sweep)
85
+ sweep.add_argument("--profiles", default="coding", help="逗号分隔:chat,coding,agentic,longctx")
86
+ sweep.add_argument("--concurrency", type=_parse_int_list, default=[1, 2, 4, 8, 16], help="如 1,2,4,8,16")
87
+ sweep.add_argument("--name", default="sweep", help="结果文件名(results/<name>.json|md|csv)")
88
+ sweep.add_argument("--out-dir", default=str(RESULTS_DIR), help="结果目录")
89
+
90
+ report = sub.add_parser("report", help="由结果 JSON 重新生成 md/csv/图")
91
+ report.add_argument("json", help="结果 JSON 路径")
92
+ report.add_argument("--no-charts", action="store_true", help="不生成图表")
93
+ report.add_argument("--charts-dir", default=None, help="图表目录")
94
+
95
+ serve = sub.add_parser("serve-sweep", help="自行启动 mock 再跑 sweep(一条命令复现)")
96
+ _add_bench_options(serve)
97
+ serve.add_argument("--launch-server", action="store_true", help="必须显式声明会启动子进程")
98
+ serve.add_argument("--port", type=int, default=8099, help="mock 监听端口(默认 8099)")
99
+ serve.add_argument("--ttft-ms", type=float, default=120.0, help="服务端基础 TTFT(ms)")
100
+ serve.add_argument("--tpot-ms", type=float, default=8.0, help="服务端 TPOT(ms/token)")
101
+ serve.add_argument("--max-concurrency", type=int, default=64, help="服务端并发槽位")
102
+ serve.add_argument("--cache-blocks", type=int, default=8192, help="prefix cache 块数")
103
+ serve.add_argument("--tokenizer", default="deepseek_v3_tokenizer", help="服务端 tokenizer")
104
+ serve.add_argument("--profiles", default="coding")
105
+ serve.add_argument("--concurrency", type=_parse_int_list, default=[1, 2, 4, 8, 16])
106
+ serve.add_argument("--name", default="serve_sweep")
107
+ serve.add_argument("--out-dir", default=str(RESULTS_DIR))
108
+ return parser
109
+
110
+
111
+ # ---------------------------------------------------------------------------
112
+ # 打印
113
+ # ---------------------------------------------------------------------------
114
+
115
+
116
+ def _fmt(value: Any, digits: int = 1) -> str:
117
+ if value is None:
118
+ return "-"
119
+ try:
120
+ return f"{float(value):.{digits}f}"
121
+ except (TypeError, ValueError):
122
+ return str(value)
123
+
124
+
125
+ def _print_point(point: dict[str, Any]) -> None:
126
+ summary = point.get("summary") or {}
127
+ rates = point.get("rates") or {}
128
+ requests = point.get("requests") or {}
129
+ cache = point.get("cache") or {}
130
+ total = int(requests.get("total") or 0)
131
+ success = int(requests.get("success") or 0)
132
+ rate = (success / total * 100.0) if total else 0.0
133
+ print(
134
+ f"[c={int(point.get('concurrency') or 0):>3}] {str(point.get('profile')):<8} "
135
+ f"req={total:>5} ok={rate:>6.2f}% "
136
+ f"rps={_fmt(rates.get('rps'), 2):>7} "
137
+ f"ttft_p50={_fmt((summary.get('ttft_ms') or {}).get('p50')):>9} "
138
+ f"p90={_fmt((summary.get('ttft_ms') or {}).get('p90')):>9} "
139
+ f"tpot_p50={_fmt((summary.get('tpot_ms') or {}).get('p50'), 2):>7} "
140
+ f"out_tok/s={_fmt(rates.get('output_tokens_per_s')):>9} "
141
+ f"cache={_fmt((cache.get('hit_rate') or 0) * 100, 1):>6}%",
142
+ flush=True,
143
+ )
144
+
145
+
146
+ def _print_server(point: dict[str, Any]) -> None:
147
+ cfg = point.get("server_config") or {}
148
+ print(
149
+ f"server: ttft_ms={cfg.get('ttft_ms')} tpot_ms={cfg.get('tpot_ms')} "
150
+ f"max_concurrency={cfg.get('max_concurrency')} cache_blocks={cfg.get('cache_blocks')}",
151
+ flush=True,
152
+ )
153
+
154
+
155
+ def _notes(args: argparse.Namespace) -> list[str]:
156
+ if not getattr(args, "notes", None):
157
+ return []
158
+ return [item.strip() for item in str(args.notes).split(";") if item.strip()]
159
+
160
+
161
+ def _config_from_args(args: argparse.Namespace, *, profiles: list[str], concurrency: list[int]) -> BenchConfig:
162
+ return BenchConfig(
163
+ url=str(args.url).rstrip("/"),
164
+ model=args.model,
165
+ profiles=profiles,
166
+ concurrency=concurrency,
167
+ duration=float(args.duration),
168
+ warmup=int(args.warmup),
169
+ seed=int(args.seed),
170
+ timeout=float(args.timeout),
171
+ fail_fast=bool(args.fail_fast),
172
+ max_tokens=args.max_tokens,
173
+ notes=_notes(args),
174
+ )
175
+
176
+
177
+ # ---------------------------------------------------------------------------
178
+ # 子命令
179
+ # ---------------------------------------------------------------------------
180
+
181
+
182
+ def _cmd_run(args: argparse.Namespace) -> int:
183
+ cfg = _config_from_args(args, profiles=[args.profile], concurrency=[int(args.concurrency)])
184
+ out = Path(args.out)
185
+ print(f"bench run: {cfg.url} profile={args.profile} concurrency={args.concurrency} duration={cfg.duration}s")
186
+ point = asyncio.run(run_point(cfg, int(args.concurrency), args.profile))
187
+ document = build_document(cfg, [point], name=out.stem)
188
+ _print_server(point)
189
+ _print_point(point)
190
+ if args.report:
191
+ paths = write_outputs(document, out, charts=not args.no_charts, charts_dir=args.charts_dir)
192
+ print(f"written: {paths['json']}\n {paths['md']}\n {paths['csv']}")
193
+ for chart in paths["charts"]:
194
+ print(f"chart: {chart}")
195
+ else:
196
+ write_json(out, document)
197
+ print(f"written: {out}")
198
+ return 0
199
+
200
+
201
+ def _cmd_sweep(args: argparse.Namespace) -> int:
202
+ profiles = _parse_list(args.profiles)
203
+ cfg = _config_from_args(args, profiles=profiles, concurrency=list(args.concurrency))
204
+ out = Path(args.out_dir) / f"{args.name}.json"
205
+ print(
206
+ f"bench sweep: {cfg.url} profiles={','.join(profiles)} "
207
+ f"concurrency={','.join(str(c) for c in cfg.concurrency)} duration={cfg.duration}s"
208
+ )
209
+ points = asyncio.run(run_sweep(cfg, progress=_print_point))
210
+ document = build_document(cfg, points, name=args.name)
211
+ if points:
212
+ _print_server(points[0])
213
+ paths = write_outputs(document, out, charts=not args.no_charts, charts_dir=args.charts_dir)
214
+ print(f"written: {paths['json']}\n {paths['md']}\n {paths['csv']}")
215
+ for chart in paths["charts"]:
216
+ print(f"chart: {chart}")
217
+ return 0
218
+
219
+
220
+ def _cmd_report(args: argparse.Namespace) -> int:
221
+ from .report import report_from_file
222
+
223
+ paths = report_from_file(args.json, charts=not args.no_charts, charts_dir=args.charts_dir)
224
+ print(f"written: {paths['json']}\n {paths['md']}\n {paths['csv']}")
225
+ for chart in paths["charts"]:
226
+ print(f"chart: {chart}")
227
+ return 0
228
+
229
+
230
+ def _port_in_use(port: int, host: str = "127.0.0.1") -> bool:
231
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
232
+ sock.settimeout(0.5)
233
+ return sock.connect_ex((host, port)) == 0
234
+
235
+
236
+ def _wait_health(url: str, timeout_s: float = 90.0) -> bool:
237
+ import httpx
238
+
239
+ deadline = time.monotonic() + timeout_s
240
+ with httpx.Client(trust_env=False, timeout=3.0) as client:
241
+ while time.monotonic() < deadline:
242
+ try:
243
+ response = client.get(f"{url}/health")
244
+ if response.status_code == 200:
245
+ return True
246
+ except httpx.HTTPError:
247
+ pass
248
+ time.sleep(0.4)
249
+ return False
250
+
251
+
252
+ def _cmd_serve_sweep(args: argparse.Namespace) -> int:
253
+ if not args.launch_server:
254
+ print("error: serve-sweep 会启动子进程,请显式加 --launch-server", file=sys.stderr)
255
+ return 2
256
+ server_py = REPO_ROOT / "server.py"
257
+ if not server_py.exists():
258
+ print(f"error: 找不到 {server_py}", file=sys.stderr)
259
+ return 2
260
+ if _port_in_use(args.port):
261
+ print(f"error: 端口 {args.port} 已被占用,请换 --port", file=sys.stderr)
262
+ return 2
263
+ url = f"http://127.0.0.1:{args.port}"
264
+ command = [
265
+ sys.executable,
266
+ str(server_py),
267
+ "--port",
268
+ str(args.port),
269
+ "--tokenizer",
270
+ str(args.tokenizer),
271
+ "--ttft-ms",
272
+ str(args.ttft_ms),
273
+ "--tpot-ms",
274
+ str(args.tpot_ms),
275
+ "--max-concurrency",
276
+ str(args.max_concurrency),
277
+ "--cache-blocks",
278
+ str(args.cache_blocks),
279
+ ]
280
+ print("launching:", " ".join(command), flush=True)
281
+ process = subprocess.Popen(command, cwd=str(REPO_ROOT), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
282
+ try:
283
+ if not _wait_health(url):
284
+ print("error: mock 未在 90s 内就绪(查看 server.py 输出)", file=sys.stderr)
285
+ return 1
286
+ profiles = _parse_list(args.profiles)
287
+ cfg = _config_from_args(args, profiles=profiles, concurrency=list(args.concurrency))
288
+ cfg.url = url
289
+ out = Path(args.out_dir) / f"{args.name}.json"
290
+ print(
291
+ f"bench serve-sweep: {url} profiles={','.join(profiles)} "
292
+ f"concurrency={','.join(str(c) for c in cfg.concurrency)} duration={cfg.duration}s"
293
+ )
294
+ points = asyncio.run(run_sweep(cfg, progress=_print_point))
295
+ document = build_document(cfg, points, name=args.name)
296
+ if points:
297
+ _print_server(points[0])
298
+ document["server"]["launched"] = {
299
+ "command": command,
300
+ "ttft_ms": args.ttft_ms,
301
+ "tpot_ms": args.tpot_ms,
302
+ "max_concurrency": args.max_concurrency,
303
+ "cache_blocks": args.cache_blocks,
304
+ "tokenizer": args.tokenizer,
305
+ "started_at": now_iso(),
306
+ }
307
+ document["notes"].append(
308
+ f"serve-sweep 自启 mock:ttft={args.ttft_ms}ms tpot={args.tpot_ms}ms "
309
+ f"max_concurrency={args.max_concurrency} cache_blocks={args.cache_blocks}"
310
+ )
311
+ paths = write_outputs(document, out, charts=not args.no_charts, charts_dir=args.charts_dir)
312
+ print(f"written: {paths['json']}\n {paths['md']}\n {paths['csv']}")
313
+ for chart in paths["charts"]:
314
+ print(f"chart: {chart}")
315
+ return 0
316
+ finally:
317
+ process.terminate()
318
+ try:
319
+ process.wait(timeout=10)
320
+ except subprocess.TimeoutExpired:
321
+ process.kill()
322
+
323
+
324
+ # ---------------------------------------------------------------------------
325
+ # main
326
+ # ---------------------------------------------------------------------------
327
+
328
+
329
+ def main(argv: list[str] | None = None) -> int:
330
+ parser = build_parser()
331
+ args = parser.parse_args(argv)
332
+ try:
333
+ if args.command == "run":
334
+ return _cmd_run(args)
335
+ if args.command == "sweep":
336
+ return _cmd_sweep(args)
337
+ if args.command == "report":
338
+ return _cmd_report(args)
339
+ if args.command == "serve-sweep":
340
+ return _cmd_serve_sweep(args)
341
+ parser.error(f"unknown command {args.command}") # pragma: no cover
342
+ except KeyboardInterrupt: # pragma: no cover - 交互中断
343
+ print("interrupted", file=sys.stderr)
344
+ return 130
345
+ except Exception as exc: # 压测/网络错误:给出简洁错误而非堆栈
346
+ print(f"error: {type(exc).__name__}: {exc}", file=sys.stderr)
347
+ return 1
348
+ return 0
349
+
350
+
351
+ if __name__ == "__main__": # pragma: no cover
352
+ sys.exit(main())