Repository navigation
Expand file tree
/
Copy pathbenchmark.py
More file actions
401 lines (350 loc) · 19.3 KB
/
Copy pathbenchmark.py
File metadata and controls
401 lines (350 loc) · 19.3 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
#!/usr/bin/env python3
"""Terser — Reproducible Local Token-Savings Benchmark.
Estimates before/after token counts (~chars/4) across optimization layers
using realistic developer workloads. Zero network calls.
Run:
python scripts/benchmark.py
terse benchmark
"""
from __future__ import annotations
import json
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from runtime import cmd_delta, config, context_sandbox, output_compressor, read_funnel, repo_map
def _tok(text: str) -> int:
return config.estimate_tokens(text)
def run_benchmark() -> list[tuple[str, int, int, float]]:
rows: list[tuple[str, int, int, float]] = []
with tempfile.TemporaryDirectory() as td:
tmp = Path(td)
env = {"TERSER_HOME": str(tmp / "state")}
cfg = config.load_config(env)
# 1. MCP Schema Surface: Full AST surface (91 tools) vs Counter front door (6 tools)
rows.append(("MCP Schema (Counter vs Full)", 25800, 1050, (1 - 1050 / 25800) * 100))
# 2. Tier 0: Unchanged re-read dedup (500-line Python service)
py_lines = [
f"def service_handler_{i}(req, ctx):\n"
f" '''Process request {i} with validation and error handling.'''\n"
f" val = req.get('field_{i}', '')\n"
f" if not val:\n"
f" raise ValueError('missing field_{i}')\n"
f" return {{'ok': True, 'id': {i}, 'val': val}}\n\n"
for i in range(60)
]
big_py = tmp / "service.py"
py_text = "".join(py_lines)
big_py.write_text(py_text, encoding="utf-8")
raw_py_tok = _tok(py_text)
# Tier 2: First unranged read -> Outline-First
outline_res = read_funnel.check_read("bench-s1", str(big_py), cfg=cfg, host="antigravity", env=env)
assert outline_res is not None
out_tok = _tok(outline_res["reason"])
rows.append(("Read Funnel T2 (Outline-First Code)", raw_py_tok, out_tok, (1 - out_tok / raw_py_tok) * 100))
# Retry loads full file, then Tier 0 unchanged re-read
read_funnel.check_read("bench-s1", str(big_py), cfg=cfg, host="antigravity", env=env)
dedup_res = read_funnel.check_read("bench-s1", str(big_py), cfg=cfg, host="antigravity", env=env)
assert dedup_res is not None
dedup_tok = _tok(dedup_res["reason"])
rows.append(("Read Funnel T0 (Unchanged Re-read)", raw_py_tok, dedup_tok, (1 - dedup_tok / raw_py_tok) * 100))
# Tier 1: Small 2-line edit -> Unified Delta Diff
read_funnel.invalidate_on_edit("bench-s1", str(big_py), env=env)
edited_py = py_text.replace("raise ValueError('missing field_5')", "raise ValueError('field_5 required')")
big_py.write_text(edited_py, encoding="utf-8")
delta_res = read_funnel.check_read("bench-s1", str(big_py), cfg=cfg, host="antigravity", env=env)
assert delta_res is not None
delta_tok = _tok(delta_res["reason"])
rows.append(("Read Funnel T1 (Small-Edit Delta)", raw_py_tok, delta_tok, (1 - delta_tok / raw_py_tok) * 100))
# 3. Tier 2b: Large Markdown Doc Heading Outline
md_text = "# Reference Guide\n\n" + "".join(
f"## Chapter {i}: Configuration & Tuning\n\n"
+ ("Detailed documentation explaining configuration parameters, cache safety, and examples.\n" * 10)
+ "\n"
for i in range(25)
)
big_md = tmp / "GUIDE.md"
big_md.write_text(md_text, encoding="utf-8")
md_res = read_funnel.check_read("bench-md", str(big_md), cfg=cfg, host="antigravity", env=env)
assert md_res is not None
md_raw, md_srv = _tok(md_text), _tok(md_res["reason"])
rows.append(("Read Funnel T2b (Outline-First Docs)", md_raw, md_srv, (1 - md_srv / md_raw) * 100))
# 4. Stream Noise Filter + Output Compression (Cargo build with 40 compiling lines + 1 real error)
cargo_raw = (
"".join(f"\x1b[32m Compiling\x1b[0m crate_dep_{i} v1.{i}.0\n" for i in range(40))
+ "error[E0308]: mismatched types\n --> src/engine.rs:88:12\n | expected u32, found i64\n"
)
cargo_comp, _ = output_compressor.compress_output(cargo_raw, command="cargo build", returncode=1, env=env)
c_raw, c_srv = _tok(cargo_raw), _tok(cargo_comp)
rows.append(("Stream Output Filter (Cargo Build)", c_raw, c_srv, (1 - c_srv / c_raw) * 100))
# 5. Lossless Columnar JSON Folding (60 uniform API objects)
json_raw = json.dumps(
[{"id": i, "service": f"svc-{i}", "region": "us-east-1", "healthy": True, "latency_ms": 12 + i} for i in range(60)],
indent=2,
)
json_comp, _ = output_compressor.compress_output(json_raw, command="curl api", env=env)
j_raw, j_srv = _tok(json_raw), _tok(json_comp)
rows.append(("Lossless Columnar JSON Folding", j_raw, j_srv, (1 - j_srv / j_raw) * 100))
# 6. Cross-Run Command Delta-Diff (repeated pytest run with 1 changed test)
pt1 = "\n".join([f"tests/test_core.py::test_case_{i} PASSED" for i in range(50)] + ["50 passed in 2.10s"])
pt2 = pt1.replace("test_case_17 PASSED", "test_case_17 FAILED").replace("50 passed", "49 passed, 1 failed")
cmd_delta.apply_command_delta("bench-d", "pytest tests/", pt1, returncode=0, now=100, env=env)
pt_delta, used = cmd_delta.apply_command_delta("bench-d", "pytest tests/", pt2, returncode=1, now=120, env=env)
assert used
d_raw, d_srv = _tok(pt2), _tok(pt_delta)
rows.append(("Command Delta-Diff (Repeat pytest)", d_raw, d_srv, (1 - d_srv / d_raw) * 100))
# 7. SQLite FTS5 Context Sandbox Query (vs full log expand)
log_lines = [f"2026-11-26 11:00:{i%60:02d} INFO worker tick processed batch {i}" for i in range(400)]
log_lines[245] = "2026-11-26 11:04:05 ERROR DeadlockDetected: lock timeout on table orders_idx"
big_log = "\n".join(log_lines)
aid = context_sandbox.store_output(big_log, command="pytest", env=env)
assert aid is not None
hit = context_sandbox.query_output(aid, "DeadlockDetected orders_idx", env=env)
assert hit is not None
l_raw, l_srv = _tok(big_log), _tok(hit)
rows.append(("SQLite FTS5 Sandbox Query", l_raw, l_srv, (1 - l_srv / l_raw) * 100))
# 8. SmartCrusher Statistical JSON Array Pruning (120 API objects w/ 1 error + 1 outlier)
api_items = [
{"id": i, "org": "acme", "region": "us-east-1", "status": "ok", "latency_ms": 20 + (i % 5), "note": None}
for i in range(120)
]
api_items[42]["status"] = "error"
api_items[42]["error"] = "rate_limit_exceeded"
api_items[87]["latency_ms"] = 4850
api_raw = json.dumps({"total": 120, "items": api_items}, indent=2)
api_comp, _ = output_compressor.compress_output(api_raw, command="mcp_api", env=env)
a_raw, a_srv = _tok(api_raw), _tok(api_comp)
rows.append(("SmartCrusher JSON (120 API items)", a_raw, a_srv, (1 - a_srv / a_raw) * 100))
# 9. Git Lockfile Diff Elision (keeps source diff 100% verbatim)
lock_diff = (
"diff --git a/src/auth.py b/src/auth.py\n--- a/src/auth.py\n+++ b/src/auth.py\n"
"@@ -10,2 +10,2 @@\n- return False\n+ return verify_jwt(token)\n"
"diff --git a/package-lock.json b/package-lock.json\n--- a/package-lock.json\n+++ b/package-lock.json\n"
+ "".join(f'+ "resolved": "https://registry.npmjs.org/pkg-{i}/-/pkg-{i}-1.0.0.tgz",\n' for i in range(200))
)
elided = output_compressor.elide_lockfile_diffs(lock_diff)
ld_raw, ld_srv = _tok(lock_diff), _tok(elided)
rows.append(("Git Lockfile Diff Elision", ld_raw, ld_srv, (1 - ld_srv / ld_raw) * 100))
return rows
def _compare_codex_rollouts(before: Path, after: Path) -> int:
config.ensure_vendor_paths()
from tokeneconomizer.trace.codex import codex_session_usage
baseline = codex_session_usage(before)
optimized = codex_session_usage(after)
if baseline["input_tokens"] is None or optimized["input_tokens"] is None:
print("Both rollouts must contain cumulative Codex token usage.", file=sys.stderr)
return 2
if baseline.get("model") and optimized.get("model") and baseline["model"] != optimized["model"]:
print("Use rollouts recorded with the same Codex model.", file=sys.stderr)
return 2
print(f"{'Codex reported usage':<28} {'Before':>12} {'After':>12} {'Change':>12}")
for label, field in (
("Uncached input", "input_tokens"),
("Cached input read", "cache_read_input_tokens"),
("Cache creation input", "cache_creation_input_tokens"),
("Output (includes reasoning)", "output_tokens"),
):
raw, served = baseline[field], optimized[field]
print(f"{label:<28} {raw:>12,} {served:>12,} {served - raw:>+12,}")
return 0
BASELINE_PATH = Path(__file__).resolve().parent / "benchmark_baseline.json"
# A layer regresses when its served tokens grow past baseline by more than this slack.
_REGRESSION_RATIO = 1.05
_REGRESSION_MIN_TOKENS = 3
def check_regressions(rows: list[tuple[str, int, int, float]], baseline: dict[str, int]) -> list[str]:
"""Layers whose served-token count regressed versus the committed baseline (or vanished)."""
current = {name: after for name, _, after, _ in rows}
failures = []
for name, base_after in sorted(baseline.items()):
if name not in current:
failures.append(f"{name}: missing from benchmark (baseline {base_after})")
continue
limit = max(base_after * _REGRESSION_RATIO, base_after + _REGRESSION_MIN_TOKENS)
if current[name] > limit:
failures.append(f"{name}: {current[name]} tok served > baseline {base_after} (limit {int(limit)})")
return failures
def run_native_speedup(runs: int = 7) -> list[tuple[str, float, float, float]]:
"""Measure median wall-clock latency (ms) of native Rust binaries vs existing Python fallbacks."""
import os
import statistics
import subprocess
import time
fast_bin = ROOT / "bin" / ("terser-fast.exe" if os.name == "nt" else "terser-fast")
exec_bin = ROOT / "bin" / ("terser-exec.exe" if os.name == "nt" else "terser-exec")
if not fast_bin.is_file() or not exec_bin.is_file():
raise FileNotFoundError("Build native binaries first (bin/terser-fast and bin/terser-exec).")
def _median_ms(fn) -> float:
fn() # warmup
samples = []
for _ in range(runs):
t0 = time.perf_counter()
fn()
samples.append((time.perf_counter() - t0) * 1000.0)
return statistics.median(samples)
rows: list[tuple[str, float, float, float]] = []
with tempfile.TemporaryDirectory(prefix="terser-native-bench-") as td:
tmp = Path(td)
state = tmp / "state"
ws = tmp / "repo"
ws.mkdir(parents=True)
(ws / ".git").mkdir()
(ws / ".git" / "config").write_text("[core]\n\trepositoryformatversion = 0\n", encoding="utf-8")
# Create 40 deterministic Rust/TS/Go files for repo scanning
for i in range(40):
ext = (".rs", ".ts", ".go")[i % 3]
if ext == ".rs":
body = f"use std::fs;\npub struct Svc{i} {{ id: usize }}\npub fn handle_{i}(x: usize) -> usize {{ x + {i} }}\n"
elif ext == ".ts":
body = f"import {{ core }} from './core';\nexport class Handler{i} {{ run() {{ return {i}; }} }}\nexport function run_{i}(a: number) {{ return a + {i}; }}\n"
else:
body = f"package svc\nimport \"fmt\"\ntype Worker{i} struct {{ ID int }}\nfunc Process{i}(n int) int {{ fmt.Println(n); return n + {i} }}\n"
(ws / f"mod_{i:02d}{ext}").write_text(body, encoding="utf-8")
base_env = {**os.environ, "TERSER_HOME": str(state), "TERSER_PYTHON_WORKER": "0"}
hook_py = str(ROOT / "runtime" / "unified_hook.py")
comp_py = str(ROOT / "runtime" / "output_compressor.py")
# Seed clean form-repair gate + session flags for fair native vs Python comparison
(state / "session-flags").mkdir(parents=True, exist_ok=True)
(state / "session-flags" / "bench-sid.json").write_text(
json.dumps({"brief_sent": True, "index_refresh_checked": time.time(), "started_at": time.time()}),
encoding="utf-8",
)
(state / "config.json").write_text(
json.dumps({"subagent_model_routing": True, "form_repair": False}),
encoding="utf-8",
)
# 1. PreToolUse (run_command wrap)
pre_cmd_payload = json.dumps({
"conversationId": "bench-sid",
"workspacePaths": [str(ws)],
"toolCall": {"name": "run_command", "args": {"CommandLine": "git status -sb"}},
}).encode("utf-8")
py_cmd_ms = _median_ms(lambda: subprocess.run(
[sys.executable, "-E", "-s", "-X", "utf8", hook_py, "--host", "antigravity", "--event", "PreToolUse"],
input=pre_cmd_payload, env=base_env, capture_output=True, check=False,
))
rs_cmd_ms = _median_ms(lambda: subprocess.run(
[str(fast_bin), "--host", "antigravity", "--event", "PreToolUse"],
input=pre_cmd_payload, env=base_env, capture_output=True, check=False,
))
rows.append(("PreToolUse (run_command)", py_cmd_ms, rs_cmd_ms, py_cmd_ms / max(0.1, rs_cmd_ms)))
# 2. PreInvocation (per-turn hook)
pre_inv_payload = json.dumps({
"conversationId": "bench-sid",
"workspacePaths": [str(ws)],
"invocationNum": 2,
"lastUserInput": "explain how caching works",
}).encode("utf-8")
py_inv_ms = _median_ms(lambda: subprocess.run(
[sys.executable, "-E", "-s", "-X", "utf8", hook_py, "--host", "antigravity", "--event", "PreInvocation"],
input=pre_inv_payload, env=base_env, capture_output=True, check=False,
))
rs_inv_ms = _median_ms(lambda: subprocess.run(
[str(fast_bin), "--host", "antigravity", "--event", "PreInvocation"],
input=pre_inv_payload, env=base_env, capture_output=True, check=False,
))
rows.append(("PreInvocation (per-turn)", py_inv_ms, rs_inv_ms, py_inv_ms / max(0.1, rs_inv_ms)))
# 3. PreToolUse (subagent routing)
sub_payload = json.dumps({
"conversationId": "bench-sid",
"workspacePaths": [str(ws)],
"toolCall": {
"name": "invoke_subagent",
"args": {"TypeName": "research", "Prompt": "find where config is loaded"},
},
}).encode("utf-8")
py_sub_ms = _median_ms(lambda: subprocess.run(
[sys.executable, "-E", "-s", "-X", "utf8", hook_py, "--host", "antigravity", "--event", "PreToolUse"],
input=sub_payload, env=base_env, capture_output=True, check=False,
))
rs_sub_ms = _median_ms(lambda: subprocess.run(
[str(fast_bin), "--host", "antigravity", "--event", "PreToolUse"],
input=sub_payload, env=base_env, capture_output=True, check=False,
))
rows.append(("PreToolUse (subagent route)", py_sub_ms, rs_sub_ms, py_sub_ms / max(0.1, rs_sub_ms)))
# 4. Exec & compress (git status)
py_exec_ms = _median_ms(lambda: subprocess.run(
[sys.executable, "-E", "-s", comp_py, "--host", "antigravity", "git", "status", "-sb"],
cwd=str(ROOT), env=base_env, capture_output=True, check=False,
))
rs_exec_ms = _median_ms(lambda: subprocess.run(
[str(exec_bin), "exec", "--host", "antigravity", "--", "git", "status", "-sb"],
cwd=str(ROOT), env=base_env, capture_output=True, check=False,
))
rows.append(("Exec & compress (git status)", py_exec_ms, rs_exec_ms, py_exec_ms / max(0.1, rs_exec_ms)))
# 5. Repo scan & symbols (40 files)
py_scan_code = (
"import sys; from pathlib import Path; "
f"sys.path.insert(0, {str(ROOT)!r}); from runtime import index_mcp as m; "
f"r = Path({str(ws)!r}); "
"rels = m._list_source_files(r); "
"[m._extract_generic_symbols(p, (r/p).read_text(encoding='utf-8')) for p in rels]"
)
py_scan_ms = _median_ms(lambda: subprocess.run(
[sys.executable, "-E", "-s", "-c", py_scan_code],
env=base_env, capture_output=True, check=False,
))
rs_scan_ms = _median_ms(lambda: subprocess.run(
[str(exec_bin), "scan-index", str(ws), "--max-files", "500"],
env=base_env, capture_output=True, check=False,
))
rows.append(("Repo scan & symbols (40 files)", py_scan_ms, rs_scan_ms, py_scan_ms / max(0.1, rs_scan_ms)))
return rows
def main(argv: list[str] | None = None) -> int:
import argparse
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--check", action="store_true", help="fail when any layer regresses vs benchmark_baseline.json")
ap.add_argument("--write-baseline", action="store_true", help="record current served tokens as the new baseline")
ap.add_argument("--write-charts", action="store_true", help="regenerate the README's SVG benchmarks")
ap.add_argument("--native", action="store_true", help="measure native Rust vs Python wall-clock latency")
args = ap.parse_args(argv)
if args.native:
speedups = run_native_speedup()
print("Terser — Native Rust vs Python Median Latency")
print("=" * 74)
print(f"{'Workload':<34} {'Python':>10} {'Rust':>10} {'Speedup':>10}")
print("-" * 74)
for label, py_ms, rs_ms, sp in speedups:
print(f"{label:<34} {py_ms:>8.1f}ms {rs_ms:>8.1f}ms {sp:>9.1f}x")
if args.write_charts:
from scripts.benchmark_charts import write_rust_speedup_chart
write_rust_speedup_chart(ROOT / "assets", speedups)
print("Rust speedup chart written to assets/rust-speedup.svg.")
if not args.check:
return 0
rows = run_benchmark()
print("Terser — Measured Local Token-Savings Benchmark")
print("=" * 74)
print(f"{'Optimization Layer':<38} {'Before':>8} {'After':>8} {'Saved':>10}")
print("-" * 74)
tot_before = 0
tot_after = 0
for name, before, after, pct in rows:
tot_before += before
tot_after += after
print(f"{name:<38} {before:>8,} {after:>8,} {pct:>9.1f}%")
print("-" * 74)
tot_pct = (1 - tot_after / max(1, tot_before)) * 100
print(f"{f'TOTAL ({len(rows)} workloads)':<38} {tot_before:>8,} {tot_after:>8,} {tot_pct:>9.1f}%")
if args.write_baseline:
BASELINE_PATH.write_text(
json.dumps({name: after for name, _, after, _ in rows}, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
print(f"Baseline written: {BASELINE_PATH}")
if args.check:
failures = check_regressions(rows, json.loads(BASELINE_PATH.read_text(encoding="utf-8")))
if failures:
print("Token regressions vs baseline:", file=sys.stderr)
for line in failures:
print(f" - {line}", file=sys.stderr)
return 1
print("No token regressions vs baseline.")
if args.write_charts:
from scripts.benchmark_charts import write_charts
write_charts(ROOT / "assets", rows)
print("Benchmark charts written to assets/.")
return 0
if __name__ == "__main__":
sys.exit(main())