falkordb 0.10.3

A FalkorDB Rust client
Documentation
#!/usr/bin/env python3
"""Parse criterion estimates from the async_strategies benchmark and write
blog/data/benchmarks.toml — a dated sample run with provenance metadata.

Invoked by scripts/bench-export.sh (`just bench-export`). Reads the mean point estimate
(nanoseconds per iteration) criterion writes for each benchmark id and renders a small
pooled-vs-multiplexed table for connection count 8. Not a CI gate — numbers are illustrative
and reproducible with `just bench`.
"""

from __future__ import annotations

import datetime
import json
import os
import platform
import subprocess

ROOT = os.getcwd()
GROUP_DIR = os.path.join(ROOT, "target", "criterion", "async_read_throughput")
CONCURRENCIES = [1, 8, 64, 256]
OUT = os.path.join(ROOT, "blog", "data", "benchmarks.toml")


def mean_ns(function_id: str, param: int) -> float | None:
    path = os.path.join(GROUP_DIR, function_id, str(param), "new", "estimates.json")
    try:
        with open(path) as fh:
            return json.load(fh)["mean"]["point_estimate"]
    except (FileNotFoundError, KeyError, json.JSONDecodeError):
        return None


def fmt_time(ns: float) -> str:
    us = ns / 1_000.0
    if us >= 1_000.0:
        return f"{us / 1_000.0:.2f} ms"
    return f"{us:.1f} \u00b5s"  # microseconds


def sh(cmd: list[str], default: str = "") -> str:
    """Run a command (no shell) and return its stripped stdout, or `default` on any failure."""
    try:
        return subprocess.check_output(cmd, text=True).strip() or default
    except (OSError, subprocess.SubprocessError):
        return default


def cpu_model() -> str:
    if platform.system() == "Darwin":
        return sh(["sysctl", "-n", "machdep.cpu.brand_string"], "Apple silicon")
    try:
        with open("/proc/cpuinfo") as fh:
            for line in fh:
                if line.startswith("model name"):
                    return line.split(":", 1)[1].strip()
    except OSError:
        # /proc/cpuinfo is Linux-only and may be unreadable; fall back to platform.processor() below.
        pass
    return platform.processor() or "unknown CPU"


def toml_escape(value: str) -> str:
    return value.replace("\\", "\\\\").replace('"', '\\"')


def main() -> None:
    rows: list[tuple[str, str, str, str]] = []
    for c in CONCURRENCIES:
        pooled = mean_ns("pooled_8", c)
        mux = mean_ns("multiplexed_8", c)
        if pooled is None or mux is None:
            continue
        speedup = pooled / mux if mux else 0.0
        rows.append((str(c), fmt_time(pooled), fmt_time(mux), f"{speedup:.2f}\u00d7"))

    if not rows:
        raise SystemExit(
            "bench_export: no criterion estimates found under target/criterion/"
            "async_read_throughput/ — did the benchmark run against a server?"
        )

    image = sh(["docker", "inspect", "--format", "{{index .RepoDigests 0}}", "falkordb/falkordb:edge"],
               "falkordb/falkordb:edge")
    meta = {
        "date": datetime.date.today().isoformat(),
        "commit": sh(["git", "rev-parse", "--short", "HEAD"], "unknown"),
        "falkordb_image": image,
        "cpu": cpu_model(),
        "os": f"{platform.system()} {platform.machine()}",
        "criterion": "0.8",
    }

    lines = [
        "# Benchmark sample-run data rendered by the `bench_table` shortcode.",
        "# Regenerated by `just bench-export` (scripts/bench-export.sh + bench_export.py).",
        "# A dated SAMPLE RUN with provenance — NOT an exact-match CI gate. Reproduce with",
        "# `just bench`.",
        "",
        "[meta]",
    ]
    for key, value in meta.items():
        lines.append(f'{key} = "{toml_escape(value)}"')
    lines += [
        "",
        "[async_strategies]",
        'title = "Async read throughput at 8 connections — pooled vs multiplexed"',
        'headers = ["Concurrent reads", "Pooled (mean)", "Multiplexed (mean)", "Speedup"]',
        "rows = [",
    ]
    for row in rows:
        cells = ", ".join(f'"{toml_escape(cell)}"' for cell in row)
        lines.append(f"    [{cells}],")
    lines += ["]", ""]

    with open(OUT, "w") as fh:
        fh.write("\n".join(lines))
    print(f"bench_export: wrote {OUT} ({len(rows)} row(s))")


if __name__ == "__main__":
    main()