| 1 | #!/usr/bin/env python3 |
| 2 | """Reproducible A/B parity and performance benchmark: Python vs Rust core accelerator. |
| 3 | |
| 4 | Usage: |
| 5 | uv run python scripts/bench_rust_vs_python.py |
| 6 | uv run python scripts/bench_rust_vs_python.py --library-dir /path/to/saved-reports |
| 7 | """ |
| 8 | |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import argparse |
| 12 | import os |
| 13 | import random |
| 14 | import sqlite3 |
| 15 | import sys |
| 16 | import tempfile |
| 17 | import time |
| 18 | from pathlib import Path |
| 19 | |
| 20 | REPO_ROOT = Path(__file__).resolve().parents[1] |
| 21 | sys.path.insert(0, str(REPO_ROOT / "skills" / "last30days" / "scripts")) |
| 22 | |
| 23 | from lib import cluster, dedupe, library, library_index, rust_accel, schema, signals |
| 24 | |
| 25 | |
| 26 | def _make_items(n: int, seed: int = 42) -> list[schema.SourceItem]: |
| 27 | rng = random.Random(seed) |
| 28 | vocab = [f"word{k}" for k in range(800)] + [ |
| 29 | "Rust", "Python", "Tokio", "Claude", "Codex", "Cargo", "Linux", |
| 30 | "Apple", "Chrome", "GitHub", "Redis", "Postgres", "Docker", |
| 31 | "Kubernetes", "Anthropic", "Benchmark", "Latency", "Memory", |
| 32 | ] |
| 33 | sources = ["reddit", "x", "youtube", "hackernews", "github", "web"] |
| 34 | items: list[schema.SourceItem] = [] |
| 35 | for i in range(n): |
| 36 | src = sources[i % len(sources)] |
| 37 | if i > 10 and i % 8 == 0: |
| 38 | title = items[i - 7].title + " update" |
| 39 | body = items[i - 7].body |
| 40 | else: |
| 41 | title = " ".join(rng.sample(vocab, 10)) |
| 42 | body = " ".join(rng.sample(vocab, 65)) |
| 43 | items.append( |
| 44 | schema.SourceItem( |
| 45 | item_id=f"{src}-{i}", |
| 46 | source=src, |
| 47 | title=title, |
| 48 | body=body, |
| 49 | url=f"https://example.com/{src}/{i}", |
| 50 | author=f"user_{i % 60}", |
| 51 | container=f"r/sub{i % 15}" if src == "reddit" else src, |
| 52 | published_at=f"2026-11-{(i % 25) + 1:02d}", |
| 53 | date_confidence="high", |
| 54 | engagement={ |
| 55 | "score": 10 + rng.randint(0, 5000), |
| 56 | "num_comments": rng.randint(0, 400), |
| 57 | "views": rng.randint(500, 500_000), |
| 58 | "likes": rng.randint(10, 10_000), |
| 59 | }, |
| 60 | relevance_hint=0.5, |
| 61 | why_relevant="", |
| 62 | snippet=body[:240], |
| 63 | ) |
| 64 | ) |
| 65 | return items |
| 66 | |
| 67 | |
| 68 | def _clone_items(items: list[schema.SourceItem]) -> list[schema.SourceItem]: |
| 69 | return [ |
| 70 | schema.SourceItem( |
| 71 | **{ |
| 72 | **it.__dict__, |
| 73 | "engagement": dict(it.engagement), |
| 74 | "metadata": dict(it.metadata), |
| 75 | } |
| 76 | ) |
| 77 | for it in items |
| 78 | ] |
| 79 | |
| 80 | |
| 81 | def _make_candidates(items: list[schema.SourceItem]) -> list[schema.Candidate]: |
| 82 | return [ |
| 83 | schema.Candidate( |
| 84 | candidate_id=f"c-{i}", |
| 85 | item_id=it.item_id, |
| 86 | source=it.source, |
| 87 | sources=[it.source], |
| 88 | title=it.title, |
| 89 | url=it.url, |
| 90 | snippet=it.snippet, |
| 91 | subquery_labels=["primary"], |
| 92 | native_ranks={"primary": i + 1}, |
| 93 | local_relevance=it.local_relevance or 0.5, |
| 94 | freshness=it.freshness or 80, |
| 95 | engagement=it.engagement_score or 50, |
| 96 | source_quality=it.source_quality or 0.8, |
| 97 | rrf_score=1.0 / (60 + i), |
| 98 | final_score=70.0 + (i % 25), |
| 99 | source_items=[it], |
| 100 | ) |
| 101 | for i, it in enumerate(items) |
| 102 | ] |
| 103 | |
| 104 | |
| 105 | def _time_fn(fn, repeats: int = 3): |
| 106 | best_ms = float("inf") |
| 107 | last = None |
| 108 | for _ in range(repeats): |
| 109 | t0 = time.perf_counter() |
| 110 | last = fn() |
| 111 | elapsed = (time.perf_counter() - t0) * 1000.0 |
| 112 | best_ms = min(best_ms, elapsed) |
| 113 | return best_ms, last |
| 114 | |
| 115 | |
| 116 | def bench_dedupe() -> list[tuple[str, float, float, bool]]: |
| 117 | rows = [] |
| 118 | for n in (100, 250, 500, 1000): |
| 119 | items = _make_items(n) |
| 120 | os.environ["LAST30DAYS_ENGINE"] = "python" |
| 121 | py_ms, py_out = _time_fn(lambda: dedupe.dedupe_items(items, threshold=0.7), repeats=1 if n >= 500 else 3) |
| 122 | os.environ["LAST30DAYS_ENGINE"] = "rust" |
| 123 | rs_ms, rs_out = _time_fn(lambda: dedupe.dedupe_items(items, threshold=0.7), repeats=3) |
| 124 | parity = [x.item_id for x in py_out] == [x.item_id for x in rs_out] |
| 125 | rows.append((f"dedupe_items (N={n})", py_ms, rs_ms, parity)) |
| 126 | return rows |
| 127 | |
| 128 | |
| 129 | def bench_annotate() -> list[tuple[str, float, float, bool]]: |
| 130 | rows = [] |
| 131 | for n in (100, 500, 2000): |
| 132 | items = _make_items(n) |
| 133 | os.environ["LAST30DAYS_ENGINE"] = "python" |
| 134 | py_ms, py_out = _time_fn( |
| 135 | lambda: signals.annotate_stream( |
| 136 | _clone_items(items), |
| 137 | "Rust Python performance benchmark CLI", |
| 138 | "balanced_recent", |
| 139 | reference_date="2026-11-26", |
| 140 | ), |
| 141 | repeats=3, |
| 142 | ) |
| 143 | os.environ["LAST30DAYS_ENGINE"] = "rust" |
| 144 | rs_ms, rs_out = _time_fn( |
| 145 | lambda: signals.annotate_stream( |
| 146 | _clone_items(items), |
| 147 | "Rust Python performance benchmark CLI", |
| 148 | "balanced_recent", |
| 149 | reference_date="2026-11-26", |
| 150 | ), |
| 151 | repeats=3, |
| 152 | ) |
| 153 | parity = [x.item_id for x in py_out] == [x.item_id for x in rs_out] and all( |
| 154 | abs((a.local_rank_score or 0.0) - (b.local_rank_score or 0.0)) < 1e-9 |
| 155 | for a, b in zip(py_out, rs_out) |
| 156 | ) |
| 157 | rows.append((f"annotate_stream (N={n})", py_ms, rs_ms, parity)) |
| 158 | return rows |
| 159 | |
| 160 | |
| 161 | def bench_cluster() -> list[tuple[str, float, float, bool]]: |
| 162 | rows = [] |
| 163 | plan = schema.QueryPlan( |
| 164 | intent="breaking_news", |
| 165 | freshness_mode="strict_recent", |
| 166 | cluster_mode="story", |
| 167 | raw_topic="Rust Python performance", |
| 168 | subqueries=[], |
| 169 | source_weights={}, |
| 170 | ) |
| 171 | for n in (50, 200, 400): |
| 172 | items = _make_items(n) |
| 173 | os.environ["LAST30DAYS_ENGINE"] = "python" |
| 174 | py_ms, py_out = _time_fn( |
| 175 | lambda: cluster.cluster_candidates(_make_candidates(items), plan), |
| 176 | repeats=1 if n >= 400 else 3, |
| 177 | ) |
| 178 | os.environ["LAST30DAYS_ENGINE"] = "rust" |
| 179 | rs_ms, rs_out = _time_fn( |
| 180 | lambda: cluster.cluster_candidates(_make_candidates(items), plan), |
| 181 | repeats=3, |
| 182 | ) |
| 183 | parity = [ |
| 184 | (c.title, c.candidate_ids, c.representative_ids, c.sources, round(c.score, 6), c.uncertainty) |
| 185 | for c in py_out |
| 186 | ] == [ |
| 187 | (c.title, c.candidate_ids, c.representative_ids, c.sources, round(c.score, 6), c.uncertainty) |
| 188 | for c in rs_out |
| 189 | ] |
| 190 | rows.append((f"cluster_candidates (N={n})", py_ms, rs_ms, parity)) |
| 191 | return rows |
| 192 | |
| 193 | |
| 194 | def bench_library_sync(library_dir: Path) -> list[tuple[str, float, float, bool]]: |
| 195 | if not library_dir.is_dir(): |
| 196 | return [] |
| 197 | md_count = len(list(library_dir.glob("*.md"))) |
| 198 | if md_count == 0: |
| 199 | return [] |
| 200 | rows = [] |
| 201 | with tempfile.TemporaryDirectory(prefix="l30-bench-") as tmp: |
| 202 | tmp_path = Path(tmp) |
| 203 | empty_briefs = tmp_path / "empty-briefs" |
| 204 | py_db = tmp_path / "py-library.db" |
| 205 | rs_db = tmp_path / "rs-library.db" |
| 206 | |
| 207 | # Cold initial index (populates SQLite DB from scratch) |
| 208 | os.environ["LAST30DAYS_ENGINE"] = "python" |
| 209 | t0 = time.perf_counter() |
| 210 | py_cold = library_index.sync_library(library_dir, empty_briefs, db_path=py_db) |
| 211 | py_cold_ms = (time.perf_counter() - t0) * 1000.0 |
| 212 | |
| 213 | # Warm incremental sync (the hot path on EVERY /last30days run!) |
| 214 | t0 = time.perf_counter() |
| 215 | py_warm = library_index.sync_library(library_dir, empty_briefs, db_path=py_db) |
| 216 | py_warm_ms = (time.perf_counter() - t0) * 1000.0 |
| 217 | |
| 218 | # Warm Rust incremental sync against the SAME DB populated by Python! |
| 219 | # Proves exact fingerprint + entry_id + metadata parity across every single file. |
| 220 | os.environ["LAST30DAYS_ENGINE"] = "rust" |
| 221 | t0 = time.perf_counter() |
| 222 | rs_warm_on_py = library_index.sync_library(library_dir, empty_briefs, db_path=py_db) |
| 223 | rs_warm_ms = (time.perf_counter() - t0) * 1000.0 |
| 224 | |
| 225 | # Also benchmark Rust cold initial index into a fresh DB |
| 226 | t0 = time.perf_counter() |
| 227 | rs_cold = library_index.sync_library(library_dir, empty_briefs, db_path=rs_db) |
| 228 | rs_cold_ms = (time.perf_counter() - t0) * 1000.0 |
| 229 | |
| 230 | # Compare SQLite document tables row-for-row |
| 231 | with sqlite3.connect(py_db) as c_py, sqlite3.connect(rs_db) as c_rs: |
| 232 | py_docs = sorted( |
| 233 | c_py.execute( |
| 234 | "SELECT entry_id, content_hash, topic, published_date, headline, summary FROM library_documents" |
| 235 | ).fetchall() |
| 236 | ) |
| 237 | rs_docs = sorted( |
| 238 | c_rs.execute( |
| 239 | "SELECT entry_id, content_hash, topic, published_date, headline, summary FROM library_documents" |
| 240 | ).fetchall() |
| 241 | ) |
| 242 | |
| 243 | cold_parity = ( |
| 244 | py_cold.indexed == rs_cold.indexed |
| 245 | and len(py_docs) == len(rs_docs) |
| 246 | and py_docs == rs_docs |
| 247 | ) |
| 248 | warm_parity = ( |
| 249 | rs_warm_on_py.indexed == 0 |
| 250 | and rs_warm_on_py.removed == 0 |
| 251 | and rs_warm_on_py.unchanged == py_warm.unchanged |
| 252 | ) |
| 253 | if not cold_parity: |
| 254 | py_map = {r[0]: r for r in py_docs} |
| 255 | rs_map = {r[0]: r for r in rs_docs} |
| 256 | only_py = set(py_map) - set(rs_map) |
| 257 | only_rs = set(rs_map) - set(py_map) |
| 258 | diff_rows = [k for k in set(py_map) & set(rs_map) if py_map[k] != rs_map[k]] |
| 259 | print( |
| 260 | f" [DEBUG] library diff: py_count={len(py_docs)}, rs_count={len(rs_docs)}, " |
| 261 | f"only_py={len(only_py)}, only_rs={len(only_rs)}, diff_rows={len(diff_rows)}", |
| 262 | file=sys.stderr, |
| 263 | ) |
| 264 | for k in list(only_py)[:3]: |
| 265 | print(f" only_py: {py_map[k][:4]}", file=sys.stderr) |
| 266 | for k in list(only_rs)[:3]: |
| 267 | print(f" only_rs: {rs_map[k][:4]}", file=sys.stderr) |
| 268 | for k in diff_rows[:3]: |
| 269 | print(f" diff {k}:\n py={py_map[k]}\n rs={rs_map[k]}", file=sys.stderr) |
| 270 | |
| 271 | rows.append((f"library_sync warm ({md_count} files)", py_warm_ms, rs_warm_ms, warm_parity)) |
| 272 | rows.append((f"library_sync cold ({md_count} files)", py_cold_ms, rs_cold_ms, cold_parity)) |
| 273 | return rows |
| 274 | |
| 275 | |
| 276 | def main() -> int: |
| 277 | parser = argparse.ArgumentParser(description="A/B benchmark Python vs Rust core accelerator") |
| 278 | parser.add_argument( |
| 279 | "--library-dir", |
| 280 | type=Path, |
| 281 | default=library.DEFAULT_MEMORY_DIR, |
| 282 | help="Directory of saved Markdown reports for real-world library sync benchmark", |
| 283 | ) |
| 284 | args = parser.parse_args() |
| 285 | |
| 286 | bin_path = rust_accel.find_binary() |
| 287 | if not bin_path: |
| 288 | print("ERROR: last30days-core binary not found. Run `cd rust && cargo build --release`.", file=sys.stderr) |
| 289 | return 1 |
| 290 | |
| 291 | # Warm the Rust worker once before timing. |
| 292 | os.environ["LAST30DAYS_ENGINE"] = "rust" |
| 293 | assert rust_accel.is_available(), "Rust worker ping failed" |
| 294 | print(f"Binary: {bin_path}") |
| 295 | print() |
| 296 | |
| 297 | rows: list[tuple[str, float, float, bool]] = [] |
| 298 | rows.extend(bench_dedupe()) |
| 299 | rows.extend(bench_annotate()) |
| 300 | rows.extend(bench_cluster()) |
| 301 | rows.extend(bench_library_sync(args.library_dir.expanduser())) |
| 302 | |
| 303 | print(f"{'Benchmark':<38} {'Python (ms)':>12} {'Rust (ms)':>11} {'Speedup':>9} {'Parity':>8}") |
| 304 | print("-" * 82) |
| 305 | all_ok = True |
| 306 | for name, py_ms, rs_ms, parity in rows: |
| 307 | speedup = py_ms / rs_ms if rs_ms > 0 else float("inf") |
| 308 | status = "EXACT" if parity else "DIFF" |
| 309 | if not parity: |
| 310 | all_ok = False |
| 311 | print(f"{name:<38} {py_ms:>12.1f} {rs_ms:>11.1f} {speedup:>8.1f}x {status:>8}") |
| 312 | |
| 313 | rust_accel.shutdown() |
| 314 | return 0 if all_ok else 2 |
| 315 | |
| 316 | |
| 317 | if __name__ == "__main__": |
| 318 | raise SystemExit(main()) |
| 319 |