From 6e532c91ca168962c8675664bae3a3e099dc4d2d Mon Sep 17 00:00:00 2001 From: Amp Date: Thu, 17 Sep 2026 18:15:24 +0000 Subject: [PATCH 1/3] perf/fts: add search benchmarks and profiling Compare SQLite FTS5 with Turso WAL and MVCC using shared documents and separate latency and throughput measurements. Add CPU profiles and query-phase peak heap measurements so regressions can be investigated without mixing instrumentation overhead into timing comparisons. Match existing benchmark plot styles and show absolute values and SQLite-relative speedups. Document workload limits, reproducible commands, and test coverage. Amp-Thread-ID: https://ampcode.com/threads/T-01a0ac34-f93d-7693-9947-ee9ec864450f Co-authored-by: pedro muniz --- Cargo.lock | 14 ++ Cargo.toml | 1 + perf/fts/Cargo.toml | 18 ++ perf/fts/README.md | 224 +++++++++++++++++ perf/fts/plot/plot-fts.py | 272 ++++++++++++++++++++ perf/fts/plot/test_plot.py | 156 ++++++++++++ perf/fts/scripts/memory.py | 91 +++++++ perf/fts/scripts/run.sh | 41 +++ perf/fts/scripts/sweep.sh | 47 ++++ perf/fts/src/latency.rs | 116 +++++++++ perf/fts/src/main.rs | 493 +++++++++++++++++++++++++++++++++++++ perf/fts/src/profiling.rs | 98 ++++++++ perf/fts/src/sqlite.rs | 191 ++++++++++++++ perf/memory/src/fts.rs | 31 ++- 14 files changed, 1783 insertions(+), 10 deletions(-) create mode 100644 perf/fts/Cargo.toml create mode 100644 perf/fts/README.md create mode 100644 perf/fts/plot/plot-fts.py create mode 100644 perf/fts/plot/test_plot.py create mode 100644 perf/fts/scripts/memory.py create mode 100644 perf/fts/scripts/run.sh create mode 100644 perf/fts/scripts/sweep.sh create mode 100644 perf/fts/src/latency.rs create mode 100644 perf/fts/src/main.rs create mode 100644 perf/fts/src/profiling.rs create mode 100644 perf/fts/src/sqlite.rs diff --git a/Cargo.lock b/Cargo.lock index fa8a8c41c..c43909e18 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2250,6 +2250,20 @@ dependencies = [ "winapi", ] +[[package]] +name = "fts-benchmark" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "memory-benchmark", + "pprof", + "rusqlite", + "serde_json", + "tempfile", + "tokio", +] + [[package]] name = "funty" version = "2.0.0" diff --git a/Cargo.toml b/Cargo.toml index 86097d13a..f8e5da533 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,7 @@ members = [ "testing/concurrent-simulator", "perf/throughput", "perf/latency", + "perf/fts", "perf/join-benchmark", "perf/encryption", "perf/memory", diff --git a/perf/fts/Cargo.toml b/perf/fts/Cargo.toml new file mode 100644 index 000000000..37445ce91 --- /dev/null +++ b/perf/fts/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "fts-benchmark" +version = "0.1.0" +edition = "2024" +license.workspace = true + +[features] +flamegraph = ["dep:pprof"] + +[dependencies] +anyhow.workspace = true +clap = { workspace = true, features = ["derive"] } +memory-benchmark = { path = "../memory", features = ["fts"] } +pprof = { version = "0.14.0", features = ["flamegraph"], optional = true } +rusqlite.workspace = true +serde_json.workspace = true +tempfile.workspace = true +tokio = { workspace = true, features = ["full"] } diff --git a/perf/fts/README.md b/perf/fts/README.md new file mode 100644 index 000000000..d455f3559 --- /dev/null +++ b/perf/fts/README.md @@ -0,0 +1,224 @@ +# FTS search latency and throughput + +Two separate benchmarks compare SQLite FTS5/WAL, Turso/WAL, and Turso/MVCC. +Both use the same deterministic document generator from `perf/memory/src/fts.rs`. +Both are read-only during measurement, not ingestion or mixed read/write benchmarks. + +## Search latency + +The search benchmark times individual queries with one OS worker thread per connection. +By default, it measures 10,000 total queries per case and reports p50, p95, and p99 in milliseconds. +It divides that fixed sample budget evenly across workers, then pools their individual durations within each run. +Workers start together and execute independent query loops without a barrier between queries. +These are nearest-rank percentiles of individual query durations, not total wall time divided by completed queries. +Each query includes SQL preparation, execution, result draining, and the workload adapter's overhead. + +Run from the repository root with Rust and `uv` installed, using a new output directory: + +```sh +bash perf/fts/scripts/run.sh /tmp/fts-search --benchmark search \ + --documents 10000 --queries 10000 --runs 5 +bash perf/fts/scripts/run.sh /tmp/fts-first --benchmark search \ + --documents 10000 --state first --runs 5 +BENCHMARK=search CONNECTIONS="1 2 4 8 16 32" QUERIES=10000 RUNS=3 \ + bash perf/fts/scripts/sweep.sh /tmp/fts-latency-sweep +``` + +Warm search runs execute one unmeasured query per connection before the measured queries. +First-query runs measure exactly one query per connection against each freshly reopened fixture without warm-up. +They do not represent a cold OS cache, because setup just wrote the database. +Search rejects duration arguments and sample counts smaller than the connection count. +The search sweep produces separate p50, p95, and p99 graphs in PNG, PDF, and SVG. +These are closed-loop clients: each worker waits for its query to finish before starting another. +Their latency excludes waiting for an externally scheduled request to be submitted. + +## Search throughput + +The throughput benchmark measures completed searches per second over a shared wall-time interval. +Each sample runs for at least five seconds by default, finishing its last batch before stopping. +Query counts differ between engines and connection counts, and the CSV records the actual count and elapsed time. +Throughput does not collect per-query latency samples. + +```sh +bash perf/fts/scripts/run.sh /tmp/fts-throughput --benchmark throughput \ + --documents 10000 --connections 8 --seconds 5 --runs 3 +bash perf/fts/scripts/sweep.sh /tmp/fts-throughput-sweep +CONNECTIONS="1 4 16 32" SECONDS_PER_RUN=10 DOCUMENTS=10000 RUNS=6 \ + bash perf/fts/scripts/sweep.sh /tmp/fts-longer-sweep +``` + +The sweep defaults to 1, 2, 4, 8, 16, and 32 connections, three repetitions, and five seconds per sample. +That is at least 27 minutes of measurement plus fixture creation, compilation, and plotting. +Throughput requires warm queries and rejects a fixed query count. +Each batch executes one query per connection and waits for all connections before the next batch. +The measurement includes this scheduling and synchronization, so it is not a measurement of independent clients without a batch barrier. +There are no explicit transactions or concurrent writes in either benchmark. + +## Engines, fixtures, and build configuration + +Every invocation runs `sqlite-wal,turso-wal,turso-mvcc` unless `--targets` selects a subset. +SQLite has no Turso MVCC journal mode, so there is no `sqlite-mvcc` target. +The target order rotates after each repetition to reduce systematic order effects. +The six cases are `rare`, `common`, `and`, `or`, `phrase`, and BM25-ranked top ten. + +Each case, target, and repetition gets a fresh temporary on-disk database with 10,000 documents by default. +Common terms occur in every document, rare terms in 1%, alpha in half, and beta in roughly one-third. +The phrase case distinguishes ordered words from reversed words. +The corpus contains simple ASCII terms, not representative natural-language text. +Fixture files are deleted after each measurement. +See [the shared workload documentation](../memory/README.md) for the corpus details. + +SQLite uses bundled SQLite through `rusqlite`, external-content FTS5, and the `unicode61` tokenizer. +Both engines load documents in 500-row transactions, then build the full-text index outside measurement. +SQLite returns matching FTS5 `rowid` values, equivalent to Turso document IDs. +Ranked queries use each engine's BM25 implementation, ascending SQLite scores and descending Turso scores. +Score magnitudes and tied result order can differ. + +Turso connections share a reopened database handle. +SQLite opens a separate connection to the same file for each worker, with default private page caches. +For search latency, each connection has a dedicated OS thread and Turso uses a current-thread Tokio runtime there. +For throughput, Turso uses one Tokio worker per connection and SQLite uses Tokio's blocking pool, +limited to one blocking worker per connection; one-connection runs execute directly on the calling task. +Each engine uses its default page cache, and no command clears the OS cache or requires privileged access. + +The scripts use optimized `bench-profile`, which inherits release settings but disables LTO and retains debug information. +LTO means link-time optimization. +No command uses `--release`, in accordance with repository guidance. +Use `PROFILE=dev` only for correctness tests, not performance claims. +The output directory contains CSV results, a build log with the SQLite version, machine details, Rust version, source revision, and arguments. + +## Plot and interpret results + +The plotter keeps search and throughput results separate and rejects mixed configurations or incomplete runs. +Search plots show the median of per-run p50 latency by default, with whiskers spanning the run-level values. +Use `--percentile p95` or `--percentile p99` to plot those latency statistics instead. +Throughput plots show the median completed searches per second and the observed range across repetitions. +Neither type of whisker is a confidence interval, and run-level latency percentiles are not pooled across runs. + +```sh +uv run perf/fts/plot/plot-fts.py /tmp/fts-search/results.csv \ + --percentile p95 -o /tmp/fts-search/p95.png -o /tmp/fts-search/p95.pdf +uv run perf/fts/plot/plot-fts.py --sweep /tmp/fts-throughput-sweep/c*/results.csv \ + -o /tmp/fts-throughput-sweep/fts-throughput.png +uv run perf/fts/plot/plot-fts.py --sweep --relative /tmp/fts-latency-sweep/c*/results.csv \ + --percentile p99 -o /tmp/fts-latency-sweep/fts-p99-speedup.png +``` + +Figures use the existing SciencePlots serif style and Okabe-Ito palette, with PNG, PDF, and SVG output. +SQLite is orange, Turso WAL is blue, and Turso MVCC uses stripes or hollow dashed markers. +The grouped-bar layout follows TPC-H. +Connection sweeps use six panels, linear measurement axes starting at zero, and logarithmic connection axes. +Each panel has a table of rounded values, with thousands separators for large numbers; CSV files retain full precision. +Timing sweeps also produce `*-speedup` figures: 1× equals SQLite, 2× means faster, and 0.5× means slower. +For latency, the ratio is SQLite's median run-level percentile divided by Turso's; for throughput, it is Turso's median divided by SQLite's. +Relative whiskers transform the observed Turso range using the fixed SQLite median, not paired runs or confidence intervals. +Older CSV files containing only amortized wall time are not search-latency results and are rejected by this plotter. + +## Peak query heap + +Run the memory sweep separately from timing and CPU profiling: + +```sh +python3 perf/fts/scripts/memory.py /tmp/fts-heap \ + --documents 10000 --connections 1 2 4 8 16 32 --queries 3 --runs 3 +python3 perf/fts/scripts/memory.py /tmp/fts-first-heap \ + --documents 10000 --connections 1 4 --state first --queries 1 --runs 3 +python3 perf/memory/analyze-dhat.py /tmp/fts-heap/c4/wal-common-run1.dhat.json --modules --top 15 +``` + +This reuses `perf/memory`'s `fts-memory` binary with optimized `bench-profile` builds. +It measures all six query cases under Turso WAL and MVCC, using a fresh process and fixture for each sample. +The default is three queries per connection and three repetitions at each connection count. +Queries execute in synchronized batches, one query per connection, using one Tokio worker per connection. +This does not include the latency runner's sample buffers or independent client loops. +Use `--profile dev` only for correctness checks. + +The plotted value is **peak simultaneous live bytes allocated during the query phase**, summed across all threads. +It is not divided by query count and is not cumulative allocated bytes, process RSS, or the complete database heap. +Setup, opening, warm-up, and their existing caches are outside tracking, as is cleanup. +The `first` state skips warm-up, so allocations needed for the first search are included. +The Rust allocator tracker does not measure SQLite's C allocations, so these graphs deliberately exclude SQLite. +Both modes remain read-only during measurement; this is not a test of concurrent MVCC updates. + +Outputs include per-connection CSVs, per-run JSON reports and dhat allocation stacks, build/phase logs, +an environment record, and `fts-peak-heap` PNG/PDF/SVG figures in MiB (1 MiB = 1,048,576 bytes). +Tables show median per-run peaks; whiskers span the observed range. +The CSV also records retained bytes, cumulative allocated bytes, and allocation counts for diagnosis. +Allocation tracking changes scheduling and adds overhead; never use its elapsed times as latency or throughput results. + +## CPU flamegraphs + +Set `FLAMEGRAPH=1` to build with the optional `flamegraph` feature and collect CPU stack samples at 99 Hz. +This uses the repository's `pprof` dependency on Linux or macOS, without `perf`, root access, or cache clearing. +The default build remains optimized `bench-profile` with debug information for function names. +Select the journal modes, query cases, and connection count you want to investigate: + +```sh +FLAMEGRAPH=1 bash perf/fts/scripts/run.sh /tmp/fts-cpu \ + --benchmark throughput --targets turso-wal,turso-mvcc --cases common,ranked \ + --documents 10000 --connections 4 --seconds 30 --runs 1 +FLAMEGRAPH=1 bash perf/fts/scripts/run.sh /tmp/fts-search-cpu \ + --benchmark search --targets turso-wal --cases common \ + --documents 10000 --connections 8 --queries 10000 --runs 1 +``` + +Each case, engine/mode, and repetition produces an interactive `.svg` flamegraph and a `.folded` file +of stack paths and sample counts under `profiles/`. +Open the SVG in a browser; click a frame to zoom and use Search to find a function. +Frame width shows the fraction of collected CPU samples containing that frame, not elapsed latency. +The horizontal position is not a timeline. +Use the folded counts for aggregate analysis, counting a function only once per stack for inclusive totals. + +Sampling starts after fixture creation, index building, reopening, and warm-up. +It stops before fixture cleanup, result validation, and percentile calculation. +Worker startup, query preparation, query execution, result draining, and scheduling during the measured phase can appear. +The sampler covers the process, including worker threads; 99 Hz is not a separate guarantee for each thread. +No-sample runs fail with a request to increase the query count or duration. + +Profiled timings go to `profiled-results.csv` with `profiled=true`, and comparison plots reject them. +Run again without `FLAMEGRAPH` to measure an optimization's effect on latency or throughput. +`FLAMEGRAPH=1` also works with `sweep.sh`; it collects profiles at each connection count and skips comparison plots. +Normal comparison plots still require all six cases, so use `--cases` with profiling or direct binary runs. + +These profiles show sampled on-CPU work, not time waiting on locks, I/O, or an external request queue. +The profiler excludes libc, libgcc, pthread, and vdso frames on supported architectures to reduce unsafe-unwinding risk; +samples can also be dropped, so percentages describe collected samples rather than complete CPU accounting. +Very short first-query runs rarely provide enough samples. +Compare repeated profiles with the same fixture, case, connections, and build before choosing an optimization. +Windows profiling is not supported; ordinary benchmark builds do not enable the profiler dependency. + +## Real-text extensions and limitations + +These benchmarks remain synthetic read-only tests, not a production workload or a test of concurrent MVCC updates. +Shared-host noise, cache differences, scheduling overhead, and fixed connection-count order can affect results. +Collect repeated optimized runs on a documented, otherwise idle machine before making release-performance claims. +Keep the CSV, environment file, and build log with the figure, and record storage and compiler overrides separately. + +For a real-text suite, reuse the existing FiQA harness rather than inventing another mutation scheduler. +The following are recommendations, not workloads implemented by this binary: + +- [BEIR FiQA](https://ir-datasets.com/beir.html#beir/fiqa/test): 57,638 documents and 648 test queries with relevance judgments. +- [BEIR SciFact](https://ir-datasets.com/beir.html#beir/scifact/test): 5,183 documents and 300 test queries for quick real-text regressions. +- [Rally Wikipedia](https://github.com/elastic/rally-tracks/tree/master/wikipedia): existing-document replacements alongside searches, using clickstream-derived article-title queries. +- [Rally PMC](https://github.com/elastic/rally-tracks/tree/master/pmc): 574,199 articles with a half-load followed by concurrent ingestion and search. + +Label ports or corpus subsets as adaptations, not original Rally results. +Keep query IDs, dataset hashes, tokenizer choices, and expected document states with real-text results. +For mixed writes, use the same offered operation sequence and rate across engines when making direct comparisons. +Verify visibility and final index contents, and report retrieval quality separately from execution speed. + +## Tests + +These commands cover both measurement methods, cross-engine query results, and plot input validation. +Smoke runs use small fixtures and counts only to test correctness. +Inspect generated figures before publication. + +```sh +cargo test -p fts-benchmark +cargo test -p memory-benchmark --features fts --lib +uv run --with numpy python -m unittest discover -s perf/fts/plot -v +PROFILE=dev bash perf/fts/scripts/run.sh /tmp/fts-search-smoke \ + --benchmark search --documents 203 --connections 3 --queries 17 --runs 1 +PROFILE=dev CONNECTIONS="1 4" DOCUMENTS=203 RUNS=1 SECONDS_PER_RUN=0.05 \ + bash perf/fts/scripts/sweep.sh /tmp/fts-throughput-smoke +``` diff --git a/perf/fts/plot/plot-fts.py b/perf/fts/plot/plot-fts.py new file mode 100644 index 000000000..739994f79 --- /dev/null +++ b/perf/fts/plot/plot-fts.py @@ -0,0 +1,272 @@ +# /// script +# dependencies = ["matplotlib", "numpy", "scienceplots"] +# /// + +import argparse +import csv +from pathlib import Path + +import numpy as np + +QUERIES = ("rare", "common", "and", "or", "phrase", "ranked") +SERIES = { + ("sqlite", "wal"): ("SQLite FTS5 (WAL)", "#E69F00", ""), + ("turso", "wal"): ("Turso (WAL)", "#0072B2", ""), + ("turso", "mvcc"): ("Turso (MVCC)", "#0072B2", "///"), +} +CONFIGURATION = ("benchmark", "state", "documents", "connections", "requested_queries", + "min_seconds", "debug_assertions") + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("csv_files", nargs="+", type=Path) + parser.add_argument("-o", "--output", action="append", type=Path) + parser.add_argument("--sweep", action="store_true") + parser.add_argument("--relative", action="store_true", help="plot speedup relative to SQLite (sweeps only)") + parser.add_argument("--percentile", choices=["p50", "p95", "p99"], default="p50") + args = parser.parse_args() + if args.relative and not args.sweep: + parser.error("--relative requires --sweep") + configuration, samples = read_sweep(args.csv_files, args.percentile) if args.sweep else read_runs(args.csv_files, args.percentile) + for output in args.output or [Path("fts.png"), Path("fts.pdf")]: + if args.sweep: + plot_sweep(configuration, samples, output, args.relative) + else: + plot(configuration, samples, output) + print(f"wrote {output}") + + +def read_sweep(paths, percentile="p50"): + configuration = None + points = {} + for path in paths: + current, samples = read_runs([path], percentile) + connections = int(current.pop("connections")) + if connections <= 0 or connections in points: + raise ValueError("each sweep file must have a distinct positive connection count") + if configuration is None: + configuration = current + if current != configuration or (points and set(samples) != set(next(iter(points.values())))): + raise ValueError("sweep files must match benchmark, sample budget, fixture and engine/mode series") + points[connections] = samples + if not points: + raise ValueError("no sweep results found") + return configuration, dict(sorted(points.items())) + + +def read_runs(paths, percentile="p50"): + configuration = None + samples = {} + expected_series = None + for path in paths: + runs = {} + with path.open(newline="") as stream: + reader = csv.DictReader(stream) + required = set(CONFIGURATION) | {"engine", "mode", "run", "query", "queries"} + if not required <= set(reader.fieldnames or []): + raise ValueError(f"{path}: missing benchmark columns") + for row in reader: + if row.get("profiled", "false") != "false": + raise ValueError("profiled timings must not be used for benchmark comparisons") + current = tuple(row[key] for key in CONFIGURATION) + if configuration is None: + configuration = current + if configuration != current: + raise ValueError("plot only one configuration at a time") + key = (row["engine"], row["mode"]) + if key not in SERIES: + raise ValueError(f"unsupported engine/mode: {key}") + series = samples.setdefault(key, {query: [] for query in QUERIES}) + query = row["query"] + seen = runs.setdefault(row["run"], {}).setdefault(key, set()) + if query not in QUERIES or query in seen: + raise ValueError(f"{path}: unknown or duplicate query {query}") + seen.add(query) + queries = int(row["queries"]) + if queries <= 0: + raise ValueError("query count must be positive") + if row["benchmark"] != "memory": + seconds = float(row["seconds"]) + if not np.isfinite(seconds) or seconds <= 0: + raise ValueError(f"{path}: timing must be positive") + if row["benchmark"] == "memory": + if row["engine"] != "turso" or queries != int(row["requested_queries"]) * int(row["connections"]): + raise ValueError("heap results require Turso and the requested queries per connection") + value = float(row["peak_heap_bytes"]) / (1024 * 1024) + elif row["benchmark"] == "search": + if not 0 < int(row["connections"]) <= queries or queries != int(row["requested_queries"]): + raise ValueError("search results require at least one sample per connection and the requested query count") + value = float(row[f"{percentile}_ms"]) + elif row["benchmark"] == "throughput": + minimum = float(row["min_seconds"]) + if not np.isfinite(minimum) or minimum <= 0 or seconds < minimum: + raise ValueError("throughput results must meet a positive minimum duration") + value = queries / seconds + else: + raise ValueError("unknown benchmark") + if not np.isfinite(value) or value <= 0: + raise ValueError("measurements must be finite and positive") + series[query].append(value) + if not runs: + raise ValueError(f"{path}: no results found") + for run in runs.values(): + if expected_series is None: + expected_series = set(run) + if set(run) != expected_series or any(seen != set(QUERIES) for seen in run.values()): + raise ValueError(f"{path}: each run must contain the same series and all six query cases") + if configuration is None: + raise ValueError("no results found") + configuration = dict(zip(CONFIGURATION, configuration)) + configuration["percentile"] = percentile + return configuration, samples + + +def plot_sweep(configuration, points, output, relative=False): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + import scienceplots + from matplotlib.ticker import FuncFormatter, MaxNLocator, NullLocator + + plt.style.use(["science", "no-latex"]) + fig, axes = plt.subplots(2, 3, figsize=(11, 8), dpi=300) + connections = list(points) + if relative and (configuration["benchmark"] == "memory" or ("sqlite", "wal") not in points[connections[0]]): + raise ValueError("speedup plots require SQLite timing results") + for index, (query, ax) in enumerate(zip(QUERIES, axes.flat)): + table_rows = [] + for key in SERIES: + if key not in points[connections[0]]: + continue + label, color, hatch = SERIES[key] + medians, lows, highs = sweep_values(points, key, query, configuration["benchmark"], relative) + short_label = "SQLite" if key[0] == "sqlite" else key[1].upper() + table_rows.append([short_label, *[format_value(value) for value in medians]]) + ax.errorbar(connections, medians, yerr=[medians - lows, highs - medians], + label=label, color=color, marker="s" if key[0] == "sqlite" else "o", + markerfacecolor="white" if hatch else color, + linestyle="--" if hatch else "-", linewidth=1.3, markersize=4, + capsize=2, elinewidth=0.9) + ax.set_xscale("log", base=2) + ax.set_ylim(bottom=0) + ax.yaxis.set_major_locator(MaxNLocator(nbins=5)) + ax.set_xticks(connections) + ax.xaxis.set_major_formatter(FuncFormatter(lambda value, _: f"{value:g}")) + ax.xaxis.set_minor_locator(NullLocator()) + ax.yaxis.set_major_formatter(FuncFormatter(lambda value, _: format_value(value))) + ax.yaxis.set_minor_locator(NullLocator()) + ax.set_title(query) + ax.grid(True, which="major", linewidth=0.5, linestyle=(0, (2, 2)), color="0.7") + ax.set_axisbelow(True) + ax.set_xlabel("Connections") + ax.set_ylabel("Speedup vs SQLite (×)" if relative else measurement_label(configuration)) + if relative: + ax.axhline(1, color="0.4", linewidth=0.8, linestyle=":") + table = ax.table(cellText=table_rows, colLabels=["conn.", *connections], cellLoc="center", + bbox=(0, -0.59, 1, 0.34)) + table.auto_set_font_size(False) + table.set_fontsize(7) + for cell in table.get_celld().values(): + cell.set_linewidth(0.4) + handles, labels = axes.flat[0].get_legend_handles_labels() + fig.legend(handles, labels, loc="lower center", ncol=len(labels), frameon=False) + build = "debug assertions" if configuration["debug_assertions"] == "true" else "no debug assertions" + budget = (f'{configuration["requested_queries"]} queries/connection' if configuration["benchmark"] == "memory" + else f'{configuration["requested_queries"]} samples per case/run' if configuration["benchmark"] == "search" + else f'{configuration["min_seconds"]} s minimum per case/run') + direction = " · above 1× = faster than SQLite" if relative else "" + fig.suptitle(f'{int(configuration["documents"]):,} synthetic documents · {configuration["state"]} · ' + f'{budget} · {build}{direction}', fontsize=10) + fig.subplots_adjust(left=0.075, right=0.98, top=0.91, bottom=0.22, hspace=1.15, wspace=0.35) + fig.savefig(output, bbox_inches="tight") + plt.close(fig) + + +def sweep_values(points, key, query, benchmark, relative): + values = [point[key][query] for point in points.values()] + medians = np.array([np.median(value) for value in values]) + lows = np.array([min(value) for value in values]) + highs = np.array([max(value) for value in values]) + if relative: + baseline = np.array([np.median(point[("sqlite", "wal")][query]) for point in points.values()]) + if key == ("sqlite", "wal"): + return np.ones_like(medians), np.ones_like(medians), np.ones_like(medians) + if benchmark == "search": + return baseline / medians, baseline / highs, baseline / lows + return medians / baseline, lows / baseline, highs / baseline + return medians, lows, highs + + +def plot(configuration, samples, output): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + import scienceplots + from matplotlib.ticker import FuncFormatter, NullLocator + + plt.style.use(["science", "no-latex"]) + fig, ax = plt.subplots(figsize=(7.2, 2.8), dpi=300) + ax.set_yscale("log") + ax.grid(True, axis="y", which="major", linewidth=0.5, + linestyle=(0, (2, 2)), color="0.7") + ax.set_axisbelow(True) + table_rows, labels, all_values = [], [], [] + width = 0.8 / len(samples) + for index, key in enumerate(key for key in SERIES if key in samples): + label, color, hatch = SERIES[key] + values = samples[key] + medians = np.array([np.median(values[q]) for q in QUERIES]) + lows = np.array([min(values[q]) for q in QUERIES]) + highs = np.array([max(values[q]) for q in QUERIES]) + all_values.extend([*lows, *highs]) + table_rows.append([format_value(value) for value in medians]) + labels.append(label) + offset = (index - (len(samples) - 1) / 2) * width + ax.bar(np.arange(len(QUERIES)) + offset, medians, width, color=color, + hatch=hatch, edgecolor="white", linewidth=0, label=label, zorder=3, + yerr=[medians - lows, highs - medians], capsize=1.2, + error_kw={"linewidth": 0.5, "capthick": 0.5, "zorder": 4}) + ax.set_ylim(10 ** np.floor(np.log10(min(all_values))), + 10 ** (np.ceil(np.log10(max(all_values))) + 0.5)) + ax.set_xlim(-0.5, len(QUERIES) - 0.5) + ax.set_xticks([]) + ax.xaxis.set_minor_locator(NullLocator()) + ax.yaxis.set_minor_locator(NullLocator()) + ax.yaxis.set_major_formatter(FuncFormatter(lambda value, _: f"{value:g}")) + ax.set_ylabel(measurement_label(configuration)) + table = ax.table(cellText=table_rows, + rowLabels=labels, colLabels=QUERIES, cellLoc="center", + loc="bottom", colWidths=[1 / len(QUERIES)] * len(QUERIES)) + table.auto_set_font_size(False) + table.set_fontsize(5.5) + table.scale(1, 1.1) + for cell in table.get_celld().values(): + cell.set_linewidth(0.4) + cell.set_edgecolor("black") + ax.legend(loc="upper left", ncol=len(samples), frameon=False, handlelength=1, + handletextpad=0.4, columnspacing=1.8) + build = "debug assertions" if configuration["debug_assertions"] == "true" else "no debug assertions" + ax.set_title(f'{configuration["benchmark"]} · {int(configuration["documents"]):,} synthetic documents · ' + f'{configuration["state"]} · ' + f'{configuration["connections"]} connection(s) · {build}', fontsize=8) + fig.savefig(output, bbox_inches="tight") + plt.close(fig) + + +def measurement_label(configuration): + if configuration["benchmark"] == "memory": + return "Peak live query heap (MiB)" + if configuration["benchmark"] == "search": + return f'{configuration["percentile"]} query latency (ms)' + return "Searches per second" + + +def format_value(value): + return f"{value:,.0f}" if round(value) >= 1000 else f"{value:.3g}" + + +if __name__ == "__main__": + main() diff --git a/perf/fts/plot/test_plot.py b/perf/fts/plot/test_plot.py new file mode 100644 index 000000000..6e77977ea --- /dev/null +++ b/perf/fts/plot/test_plot.py @@ -0,0 +1,156 @@ +import csv +import importlib.util +from pathlib import Path +import tempfile +import unittest + +spec = importlib.util.spec_from_file_location("plot_fts", Path(__file__).with_name("plot-fts.py")) +plot_fts = importlib.util.module_from_spec(spec) +spec.loader.exec_module(plot_fts) + +memory_spec = importlib.util.spec_from_file_location("fts_memory", Path(__file__).parents[1] / "scripts/memory.py") +fts_memory = importlib.util.module_from_spec(memory_spec) +memory_spec.loader.exec_module(fts_memory) + + +class PlotTests(unittest.TestCase): + def read(self, rows, other=None, percentile="p50"): + with tempfile.TemporaryDirectory() as directory: + paths = [] + for index, batch in enumerate([rows] if other is None else [rows, other]): + path = Path(directory) / f"synthetic-{index}.csv" + with path.open("w", newline="") as stream: + writer = csv.DictWriter(stream, fieldnames=batch[0].keys()) + writer.writeheader() + writer.writerows(batch) + paths.append(path) + return plot_fts.read_runs(paths, percentile) if other is None else plot_fts.read_sweep(paths, percentile) + + def rows(self): + return [dict(engine="turso", mode="wal", state="warm", documents="103", + connections="1", queries="4", benchmark="throughput", debug_assertions="true", + requested_queries="0", min_seconds="0.001", p50_ms="", p95_ms="", p99_ms="", + run="1", query=query, seconds="0.008") for query in plot_fts.QUERIES] + + def test_throughput_is_completed_queries_per_second(self): + rows = self.rows() + [dict(row, run="2", queries="8", seconds="0.016") for row in self.rows()] + _, samples = self.read(rows) + self.assertEqual(samples[("turso", "wal")]["rare"], [500.0, 500.0]) + + def test_search_uses_individual_query_percentiles_not_wall_time_average(self): + rows = [dict(row, benchmark="search", requested_queries="4", min_seconds="0", + p50_ms="1", p95_ms="5", p99_ms="6") for row in self.rows()] + _, samples = self.read(rows) + self.assertEqual(samples[("turso", "wal")]["rare"], [1.0]) + _, samples = self.read(rows, percentile="p95") + self.assertEqual(samples[("turso", "wal")]["rare"], [5.0]) + with self.assertRaises(ValueError): + self.read(rows + self.rows()) + + def test_sweep_keeps_connections_separate_and_requires_equal_duration(self): + four = [dict(row, connections="4", seconds="0.004") for row in self.rows()] + _, points = self.read(four, self.rows()) + self.assertEqual(list(points), [1, 4]) + self.assertEqual(points[4][("turso", "wal")]["rare"], [1000.0]) + self.assertEqual(points[1][("turso", "wal")]["rare"], [500.0]) + for change in ({"min_seconds": "0.002"}, {"connections": "1"}, {"engine": "sqlite"}): + with self.assertRaises(ValueError): + self.read(self.rows(), [dict(row, **change) for row in four]) + + def test_latency_sweep_uses_p99_individual_samples_at_each_connection_count(self): + one = [dict(row, benchmark="search", requested_queries="4", min_seconds="0", + p50_ms="1", p95_ms="5", p99_ms="6") for row in self.rows()] + four = [dict(row, connections="4", p50_ms="2", p95_ms="8", p99_ms="11") for row in one] + configuration, points = self.read(one, four, percentile="p99") + self.assertEqual(configuration["percentile"], "p99") + self.assertEqual(points[1][("turso", "wal")]["rare"], [6.0]) + self.assertEqual(points[4][("turso", "wal")]["rare"], [11.0]) + with self.assertRaises(ValueError): + self.read(one, [dict(row, requested_queries="8", queries="8") for row in four]) + + def test_keeps_engine_modes_and_repetitions_separate(self): + rows = [] + for run, seconds in [("1", "0.004"), ("2", "0.020")]: + for index, (engine, mode) in enumerate(plot_fts.SERIES, 1): + rows.extend(dict(row, run=run, engine=engine, mode=mode, + seconds=str(float(seconds) * index)) for row in self.rows()) + _, samples = self.read(rows) + self.assertEqual(samples[("sqlite", "wal")]["rare"], [1000.0, 200.0]) + self.assertEqual(samples[("turso", "wal")]["rare"], [500.0, 100.0]) + self.assertEqual(samples[("turso", "mvcc")]["rare"], [4 / 0.012, 4 / 0.060]) + with self.assertRaises(ValueError): + self.read(rows[:-6]) + + def test_rejects_sqlite_mvcc(self): + with self.assertRaises(ValueError): + self.read([dict(row, engine="sqlite", mode="mvcc") for row in self.rows()]) + + def test_rejects_profiled_timings(self): + with self.assertRaisesRegex(ValueError, "profiled timings"): + self.read([dict(row, profiled="true") for row in self.rows()]) + _, samples = self.read([dict(row, profiled="false") for row in self.rows()]) + self.assertEqual(samples[("turso", "wal")]["rare"], [500.0]) + + def test_rejects_incomplete_duplicate_and_mixed_runs(self): + rows = self.rows() + with self.assertRaises(ValueError): + self.read(rows[:-1]) + with self.assertRaises(ValueError): + self.read(rows + [rows[0]]) + rows[-1]["documents"] = "104" + with self.assertRaises(ValueError): + self.read(rows) + + def test_rejects_invalid_measurements(self): + for seconds in ("nan", "inf", "0", "-1", "0.0009"): + rows = self.rows() + rows[0]["seconds"] = seconds + with self.assertRaises(ValueError): + self.read(rows) + + def test_speedup_uses_ratio_of_medians_and_correct_direction(self): + points = {1: {("sqlite", "wal"): {"rare": [4, 8]}, ("turso", "wal"): {"rare": [2, 6]}}, + 4: {("sqlite", "wal"): {"rare": [3]}, ("turso", "wal"): {"rare": [9]}}} + medians, lows, highs = plot_fts.sweep_values(points, ("turso", "wal"), "rare", "search", True) + self.assertEqual(list(medians), [1.5, 1 / 3]) + self.assertEqual(list(lows), [1, 1 / 3]) + self.assertEqual(list(highs), [3, 1 / 3]) + medians, _, _ = plot_fts.sweep_values(points, ("turso", "wal"), "rare", "throughput", True) + self.assertEqual(list(medians), [2 / 3, 3]) + for values in plot_fts.sweep_values(points, ("sqlite", "wal"), "rare", "search", True): + self.assertEqual(list(values), [1, 1]) + + def test_large_values_use_thousands_separators(self): + for value, expected in [(12345, "12,345"), (999.6, "1,000"), (999.4, "999"), (0.01234, "0.0123")]: + self.assertEqual(plot_fts.format_value(value), expected) + + def test_memory_plots_peak_bytes_as_mib_without_timing(self): + one = [dict(row, benchmark="memory", requested_queries="4", min_seconds="0", + peak_heap_bytes="1572864") for row in self.rows()] + for row in one: + del row["seconds"] + four = [dict(row, connections="4", queries="16", peak_heap_bytes="5242880") for row in one] + _, points = self.read(one, four) + self.assertEqual(points[1][("turso", "wal")]["rare"], [1.5]) + self.assertEqual(points[4][("turso", "wal")]["rare"], [5]) + with self.assertRaises(ValueError): + self.read([dict(row, engine="sqlite") for row in one]) + with self.assertRaises(ValueError): + self.read([dict(row, queries="4") for row in four]) + + def test_memory_summary_preserves_peak_not_total_or_per_query(self): + report = dict(query="common", documents=203, rows_per_query=203, mode="wal", state="warm", + queries=6, connections=3, transactions=0, peak_live_query_bytes=8192, + retained_query_bytes=4096, total_allocated_bytes=48000, total_allocations=700) + row = fts_memory.measurement(report, 2, 1, "bench-profile") + self.assertEqual(row["peak_heap_bytes"], 8192) + self.assertEqual(row["queries"], 6) + self.assertEqual(row["requested_queries"], 2) + for change in (dict(queries=2), dict(rows_per_query=202), dict(retained_query_bytes=8193), + dict(total_allocated_bytes=8191)): + with self.assertRaises(ValueError): + fts_memory.measurement(report | change, 2, 1, "bench-profile") + + +if __name__ == "__main__": + unittest.main() diff --git a/perf/fts/scripts/memory.py b/perf/fts/scripts/memory.py new file mode 100644 index 000000000..6f2a92de4 --- /dev/null +++ b/perf/fts/scripts/memory.py @@ -0,0 +1,91 @@ +import argparse +import csv +import json +import os +from pathlib import Path +import platform +import subprocess + + +def main(): + parser = argparse.ArgumentParser(description="Measure Turso FTS query-phase peak heap with dhat") + parser.add_argument("output", type=Path) + parser.add_argument("--documents", type=int, default=10000) + parser.add_argument("--connections", type=int, nargs="+", default=[1, 2, 4, 8, 16, 32]) + parser.add_argument("--queries", type=int, default=3, help="queries per connection") + parser.add_argument("--runs", type=int, default=3) + parser.add_argument("--state", choices=["first", "warm"], default="warm") + parser.add_argument("--profile", choices=["dev", "bench-profile"], default="bench-profile") + args = parser.parse_args() + if min(args.documents, args.queries, args.runs, *args.connections) <= 0: + parser.error("counts must be positive") + if len(set(args.connections)) != len(args.connections): + parser.error("connection counts must be distinct") + if args.state == "first" and args.queries != 1: + parser.error("first-query measurement requires --queries 1") + root = Path(__file__).resolve().parents[3] + args.output.mkdir() + output = args.output.resolve() + metadata = dict(arguments=vars(args) | {"output": str(output)}, machine=platform.platform(), + cpus=os.cpu_count(), allocator="dhat", scope="query-phase Rust allocations") + for name, command in (("rustc", ["rustc", "-Vv"]), ("revision", ["git", "rev-parse", "HEAD"]), + ("worktree", ["git", "status", "--short"])): + metadata[name] = subprocess.check_output(command, cwd=root, text=True).strip() + (output / "environment.json").write_text(json.dumps(metadata, indent=2) + "\n") + csv_paths = [] + for connections in args.connections: + directory = output / f"c{connections}" + directory.mkdir() + csv_path = directory / "results.csv" + csv_paths.append(str(csv_path)) + with csv_path.open("w", newline="") as stream: + writer = None + for run in range(1, args.runs + 1): + for query in ("rare", "common", "and", "or", "phrase", "ranked"): + modes = ("wal", "mvcc") if run % 2 else ("mvcc", "wal") + for mode in modes: + stem = directory / f"{mode}-{query}-run{run}" + print(f"Heap: c{connections} {mode} {query} run {run}", flush=True) + command = ["cargo", "run", "--profile", args.profile, "-p", "memory-benchmark", + "--features", "fts", "--bin", "fts-memory", "--", + "--query", query, "--state", args.state, "--mode", mode, + "--documents", str(args.documents), "--connections", str(connections), + "--queries", str(args.queries), "--dhat-file", str(stem) + ".dhat.json"] + with Path(str(stem) + ".json").open("w") as report_file, stem.with_suffix(".log").open("w") as log: + subprocess.run(command, cwd=root, stdout=report_file, stderr=log, check=True) + report = json.loads(Path(str(stem) + ".json").read_text()) + row = measurement(report, args.queries, run, args.profile) + if writer is None: + writer = csv.DictWriter(stream, fieldnames=row.keys()) + writer.writeheader() + writer.writerow(row) + stream.flush() + command = ["uv", "run", str(root / "perf/fts/plot/plot-fts.py"), "--sweep", *csv_paths] + for extension in ("png", "pdf", "svg"): + command += ["-o", str(output / f"fts-peak-heap.{extension}")] + subprocess.run(command, cwd=root, check=True) + + +def measurement(report, queries_per_connection, run, profile): + if report["queries"] != queries_per_connection * report["connections"] or report["transactions"] != 0: + raise ValueError("memory run did not complete the requested queries") + documents = report["documents"] + either = (documents + 1) // 2 + (documents + 2) // 3 - (documents + 5) // 6 + expected = {"rare": (documents + 99) // 100, "common": documents, "and": (documents + 5) // 6, + "or": either, "phrase": (documents + 199) // 200, "ranked": min(10, either)} + query = report["query"] + if report["rows_per_query"] != expected[query]: + raise ValueError("unexpected query result count") + peak = report["peak_live_query_bytes"] + if not 0 <= report["retained_query_bytes"] <= peak <= report["total_allocated_bytes"]: + raise ValueError("inconsistent heap measurements") + return dict(benchmark="memory", engine="turso", mode=report["mode"], state=report["state"], + documents=documents, connections=report["connections"], queries=report["queries"], run=run, + query=query, requested_queries=queries_per_connection, min_seconds=0, + debug_assertions=str(profile == "dev").lower(), peak_heap_bytes=peak, + retained_heap_bytes=report["retained_query_bytes"], + total_allocated_bytes=report["total_allocated_bytes"], total_allocations=report["total_allocations"]) + + +if __name__ == "__main__": + main() diff --git a/perf/fts/scripts/run.sh b/perf/fts/scripts/run.sh new file mode 100644 index 000000000..e37445633 --- /dev/null +++ b/perf/fts/scripts/run.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +set -euo pipefail + +root=$(git -C "$(dirname "$0")" rev-parse --show-toplevel) +output=${1:?Usage: bash perf/fts/scripts/run.sh NEW_OUTPUT_DIRECTORY [benchmark options]} +shift +mkdir "$output" +output=$(realpath "$output") +profile=${PROFILE:-bench-profile} +case "$profile" in + dev|bench-profile) ;; + *) echo 'PROFILE must be dev or bench-profile' >&2; exit 1 ;; +esac +cargo_options=() +results=results.csv +case "${FLAMEGRAPH:-0}" in + 0) ;; + 1) + cargo_options=(--features flamegraph) + set -- "$@" --flamegraph "$output/profiles" + results=profiled-results.csv + ;; + *) echo 'FLAMEGRAPH must be 0 or 1' >&2; exit 1 ;; +esac +{ + date -u + uname -a + rustc -Vv + git -C "$root" rev-parse HEAD + git -C "$root" status --short + printf 'profile=%s\narguments=' "$profile" + printf '%q ' "$@" + printf '\n' + if command -v lscpu >/dev/null; then lscpu; fi +} > "$output/environment.txt" +cargo run --manifest-path "$root/Cargo.toml" --profile "$profile" -p fts-benchmark "${cargo_options[@]}" -- "$@" \ + > "$output/$results" 2> "$output/bench.log" +if [[ "${FLAMEGRAPH:-0}" == 0 ]]; then + uv run "$root/perf/fts/plot/plot-fts.py" "$output/results.csv" \ + -o "$output/fts.png" -o "$output/fts.pdf" -o "$output/fts.svg" +fi diff --git a/perf/fts/scripts/sweep.sh b/perf/fts/scripts/sweep.sh new file mode 100644 index 000000000..bc428d659 --- /dev/null +++ b/perf/fts/scripts/sweep.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +set -euo pipefail + +script_dir=$(dirname "$(realpath "$0")") +output=${1:?Usage: bash perf/fts/scripts/sweep.sh NEW_OUTPUT_DIRECTORY} +benchmark=${BENCHMARK:-throughput} +connections=${CONNECTIONS:-1 2 4 8 16 32} +seconds=${SECONDS_PER_RUN:-5} +queries=${QUERIES:-10000} +documents=${DOCUMENTS:-10000} +runs=${RUNS:-3} +case "$benchmark" in + search) options=(--queries "$queries") ;; + throughput) options=(--seconds "$seconds") ;; + *) echo 'BENCHMARK must be search or throughput' >&2; exit 1 ;; +esac +for count in $connections; do + if (( count <= 0 )); then + echo 'Every connection count must be positive' >&2 + exit 1 + fi +done +mkdir "$output" +output=$(realpath "$output") +inputs=() +for count in $connections; do + echo "Benchmarking $benchmark at $count connections" + bash "$script_dir/run.sh" "$output/c$count" --benchmark "$benchmark" --documents "$documents" \ + --runs "$runs" --connections "$count" "${options[@]}" + inputs+=("$output/c$count/results.csv") +done +if [[ "${FLAMEGRAPH:-0}" == 1 ]]; then + exit 0 +fi +if [[ "$benchmark" == search ]]; then + for percentile in p50 p95 p99; do + uv run "$script_dir/../plot/plot-fts.py" --sweep "${inputs[@]}" --percentile "$percentile" \ + -o "$output/fts-$percentile.png" -o "$output/fts-$percentile.pdf" -o "$output/fts-$percentile.svg" + uv run "$script_dir/../plot/plot-fts.py" --sweep --relative "${inputs[@]}" --percentile "$percentile" \ + -o "$output/fts-$percentile-speedup.png" -o "$output/fts-$percentile-speedup.pdf" -o "$output/fts-$percentile-speedup.svg" + done +else + uv run "$script_dir/../plot/plot-fts.py" --sweep "${inputs[@]}" \ + -o "$output/fts-throughput.png" -o "$output/fts-throughput.pdf" -o "$output/fts-throughput.svg" + uv run "$script_dir/../plot/plot-fts.py" --sweep --relative "${inputs[@]}" \ + -o "$output/fts-throughput-speedup.png" -o "$output/fts-throughput-speedup.pdf" -o "$output/fts-throughput-speedup.svg" +fi diff --git a/perf/fts/src/latency.rs b/perf/fts/src/latency.rs new file mode 100644 index 000000000..43aa21cae --- /dev/null +++ b/perf/fts/src/latency.rs @@ -0,0 +1,116 @@ +use std::sync::Barrier; +use std::time::Instant; + +use anyhow::{Result, ensure}; +use memory_benchmark::fts::RunResult; +use tokio::runtime::Runtime; + +use crate::Measurement; + +pub fn measure( + sessions: Vec, + queries: usize, + execute: impl Fn(&mut S, &Runtime) -> Result + Sync, +) -> Result { + let connections = sessions.len(); + ensure!( + connections > 0 && queries >= connections, + "need at least one query per connection" + ); + let workers = sessions + .into_iter() + .map(|session| { + Ok(( + session, + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?, + )) + }) + .collect::>>()?; + let barrier = Barrier::new(connections + 1); + std::thread::scope(|scope| { + let handles: Vec<_> = workers + .into_iter() + .enumerate() + .map(|(index, (mut session, runtime))| { + let execute = &execute; + let barrier = &barrier; + scope.spawn(move || { + let count = queries / connections + usize::from(index < queries % connections); + let mut latencies = Vec::with_capacity(count); + let mut result = RunResult::default(); + barrier.wait(); + for _ in 0..count { + let start = Instant::now(); + let completed = execute(&mut session, &runtime)?; + latencies.push(start.elapsed().as_secs_f64() * 1000.0); + assert_eq!(completed.queries, 1); + result.queries += 1; + result.rows += completed.rows; + result.id_sum += completed.id_sum; + } + Ok::<_, anyhow::Error>((result, latencies)) + }) + }) + .collect(); + let start = Instant::now(); + barrier.wait(); + let outcomes: Vec<_> = handles.into_iter().map(|handle| handle.join()).collect(); + let seconds = start.elapsed().as_secs_f64(); + let mut measurement = Measurement { + result: RunResult::default(), + seconds, + latencies: Vec::with_capacity(queries), + }; + for outcome in outcomes { + let (result, latencies) = + outcome.map_err(|_| anyhow::anyhow!("latency worker panicked"))??; + measurement.result.queries += result.queries; + measurement.result.rows += result.rows; + measurement.result.id_sum += result.id_sum; + measurement.latencies.extend(latencies); + } + Ok(measurement) + }) +} + +#[cfg(test)] +mod tests { + use std::collections::HashSet; + use std::sync::Mutex; + + use super::*; + + #[test] + fn uses_distinct_threads_and_records_each_query_with_uneven_work() -> Result<()> { + let counts = Mutex::new([0; 3]); + let threads = Mutex::new(HashSet::new()); + let start = Barrier::new(3); + let result = measure(vec![0, 1, 2], 10, |index, _| { + let first = { + let mut counts = counts.lock().unwrap(); + counts[*index] += 1; + counts[*index] == 1 + }; + if first { + start.wait(); + } + threads.lock().unwrap().insert(std::thread::current().id()); + Ok(RunResult { + queries: 1, + rows: *index + 1, + id_sum: *index as i64 * 7, + ..Default::default() + }) + })?; + assert_eq!(*counts.lock().unwrap(), [4, 3, 3]); + assert_eq!(threads.lock().unwrap().len(), 3); + assert_eq!(result.latencies.len(), 10); + assert_eq!(result.result.queries, 10); + assert_eq!(result.result.rows, 19); + assert_eq!(result.result.id_sum, 63); + assert!(measure(vec![0, 1], 1, |_, _| unreachable!()).is_err()); + Ok(()) + } +} diff --git a/perf/fts/src/main.rs b/perf/fts/src/main.rs new file mode 100644 index 000000000..6bd24a668 --- /dev/null +++ b/perf/fts/src/main.rs @@ -0,0 +1,493 @@ +use anyhow::{Result, ensure}; +use clap::{Parser, ValueEnum}; +use memory_benchmark::fts::{ + CorpusConfig, Execution, FtsConfig, FtsWorkload, QueryCase, QueryState, RunResult, +}; +use memory_benchmark::workload::JournalMode; +use std::io::{Write, stdout}; +use std::time::Instant; + +mod latency; +#[cfg(feature = "flamegraph")] +mod profiling; +mod sqlite; + +#[derive(Parser)] +struct Args { + #[arg(long, value_enum)] + benchmark: Benchmark, + #[arg(long, default_value_t = 10_000)] + documents: usize, + #[arg(long, default_value_t = 5)] + runs: usize, + #[arg(long, value_enum, default_value = "warm")] + state: QueryState, + #[arg(long)] + queries: Option, + #[arg(long, conflicts_with = "queries")] + seconds: Option, + #[arg( + long, + value_enum, + value_delimiter = ',', + default_value = "sqlite-wal,turso-wal,turso-mvcc" + )] + targets: Vec, + #[arg(long, default_value_t = 1)] + connections: usize, + #[arg( + long, + value_enum, + value_delimiter = ',', + default_value = "rare,common,and,or,phrase,ranked" + )] + cases: Vec, + #[cfg(feature = "flamegraph")] + #[arg(long)] + flamegraph: Option, +} + +fn main() -> Result<()> { + let args = Args::parse(); + ensure!(args.runs > 0, "runs must be positive"); + ensure!(args.connections > 0, "connections must be positive"); + eprintln!("bundled SQLite version: {}", rusqlite::version()); + let runtime = match args.benchmark { + Benchmark::Search => tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?, + Benchmark::Throughput => tokio::runtime::Builder::new_multi_thread() + .worker_threads(args.connections) + .max_blocking_threads(args.connections) + .enable_all() + .build()?, + }; + runtime.block_on(run(args)) +} + +async fn run(mut args: Args) -> Result<()> { + let (query_limit, min_seconds) = match args.benchmark { + Benchmark::Search => { + ensure!( + args.seconds.is_none(), + "--seconds requires --benchmark throughput" + ); + let queries = args + .queries + .unwrap_or(if matches!(args.state, QueryState::First) { + args.connections + } else { + 10_000 + }); + ensure!( + queries >= args.connections, + "need at least one query per connection" + ); + ensure!( + !matches!(args.state, QueryState::First) || queries == args.connections, + "first-query latency requires one query per connection" + ); + (queries, 0.0) + } + Benchmark::Throughput => { + ensure!( + args.queries.is_none(), + "--queries requires --benchmark search" + ); + ensure!( + matches!(args.state, QueryState::Warm), + "throughput requires --state warm" + ); + let seconds = args.seconds.unwrap_or(5.0); + ensure!( + seconds.is_finite() && seconds > 0.0, + "seconds must be finite and positive" + ); + (0, seconds) + } + }; + #[cfg(feature = "flamegraph")] + let profiled = args.flamegraph.is_some(); + #[cfg(not(feature = "flamegraph"))] + let profiled = false; + #[cfg(feature = "flamegraph")] + if let Some(directory) = &args.flamegraph { + std::fs::create_dir(directory)?; + } + let mut output = stdout().lock(); + writeln!( + output, + "benchmark,engine,mode,state,documents,connections,queries,run,query,seconds,rows,id_sum,debug_assertions,requested_queries,min_seconds,p50_ms,p95_ms,p99_ms,profiled" + )?; + for repetition in 1..=args.runs { + for &query in &args.cases { + for &target in &args.targets { + #[cfg(feature = "flamegraph")] + let profile_path = args.flamegraph.as_ref().map(|directory| { + directory.join(format!( + "{}-{}-{}-c{}-run{}-{}", + args.benchmark.to_possible_value().unwrap().get_name(), + target.engine(), + target.mode(), + args.connections, + repetition, + query.to_possible_value().unwrap().get_name() + )) + }); + let config = FtsConfig { + query, + state: args.state, + documents: args.documents, + corpus: CorpusConfig::default(), + mode: target.mode(), + connections: args.connections, + execution: Execution::Queries(1), + }; + let mut measured = match target { + Target::SqliteWal => { + let mut workload = sqlite::SqliteWorkload::prepare(config).await?; + #[cfg(feature = "flamegraph")] + let profiler = profiling::start(profiled)?; + let measured = match args.benchmark { + Benchmark::Search => latency::measure( + workload.sessions().iter_mut().collect(), + query_limit, + |session, _| sqlite::query_batch(session, query, 1), + )?, + Benchmark::Throughput => { + measure_throughput(min_seconds, async || workload.run().await) + .await? + } + }; + #[cfg(feature = "flamegraph")] + profiling::finish(profiler, profile_path.as_deref())?; + measured + } + Target::TursoWal | Target::TursoMvcc => { + let workload = FtsWorkload::prepare(config, &mut ()).await?; + #[cfg(feature = "flamegraph")] + let profiler = profiling::start(profiled)?; + let measured = match args.benchmark { + Benchmark::Search => latency::measure( + workload.sessions().to_vec(), + query_limit, + |session, runtime| { + let result = runtime.block_on(session.query(query))?; + Ok(RunResult { + queries: 1, + rows: result.rows, + id_sum: result.id_sum, + ..Default::default() + }) + }, + )?, + Benchmark::Throughput => { + measure_throughput(min_seconds, async || { + workload.run(&mut ()).await + }) + .await? + } + }; + #[cfg(feature = "flamegraph")] + profiling::finish(profiler, profile_path.as_deref())?; + workload.finish(&mut ()); + measured + } + }; + let result = measured.result; + validate_result( + query, + args.documents, + result.queries, + result.rows, + result.id_sum, + )?; + writeln!( + output, + "{},{},{},{},{},{},{},{},{},{:.9},{},{},{},{},{},{},{},{},{}", + args.benchmark.to_possible_value().unwrap().get_name(), + target.engine(), + target.mode(), + serde_json::to_value(args.state)?.as_str().unwrap(), + args.documents, + args.connections, + result.queries, + repetition, + serde_json::to_value(query)?.as_str().unwrap(), + measured.seconds, + result.rows, + result.id_sum, + cfg!(debug_assertions), + query_limit, + min_seconds, + percentile(&mut measured.latencies, 50), + percentile(&mut measured.latencies, 95), + percentile(&mut measured.latencies, 99), + profiled + )?; + } + } + args.targets.rotate_left(1); + } + Ok(()) +} + +async fn measure_throughput( + min_seconds: f64, + mut batch: impl AsyncFnMut() -> Result, +) -> Result { + let start = Instant::now(); + let mut result = RunResult::default(); + loop { + let completed = batch().await?; + result.queries += completed.queries; + result.transactions += completed.transactions; + result.rows += completed.rows; + result.id_sum += completed.id_sum; + result.max_active_transactions = result + .max_active_transactions + .max(completed.max_active_transactions); + let seconds = start.elapsed().as_secs_f64(); + if seconds >= min_seconds { + return Ok(Measurement { + result, + seconds, + latencies: Vec::new(), + }); + } + } +} + +#[derive(Clone, Copy, ValueEnum)] +enum Benchmark { + Search, + Throughput, +} + +struct Measurement { + result: RunResult, + seconds: f64, + latencies: Vec, +} + +fn percentile(latencies: &mut [f64], percent: usize) -> String { + if latencies.is_empty() { + return String::new(); + } + latencies.sort_unstable_by(f64::total_cmp); + let index = (latencies.len() * percent).div_ceil(100) - 1; + format!("{:.9}", latencies[index]) +} + +#[derive(Clone, Copy, ValueEnum)] +enum Target { + SqliteWal, + TursoWal, + TursoMvcc, +} + +impl Target { + fn mode(self) -> JournalMode { + match self { + Self::SqliteWal | Self::TursoWal => JournalMode::Wal, + Self::TursoMvcc => JournalMode::Mvcc, + } + } + + fn engine(self) -> &'static str { + match self { + Self::SqliteWal => "sqlite", + Self::TursoWal | Self::TursoMvcc => "turso", + } + } +} + +fn validate_result( + case: QueryCase, + documents: usize, + queries: usize, + rows: usize, + sum: i64, +) -> Result<()> { + let ids = (0..documents).filter(|id| match case { + QueryCase::Rare => id % 100 == 0, + QueryCase::Common => true, + QueryCase::And => id % 6 == 0, + QueryCase::Or | QueryCase::Ranked => id % 2 == 0 || id % 3 == 0, + QueryCase::Phrase => id % 200 == 0, + }); + let expected_rows = ids.clone().count(); + if matches!(case, QueryCase::Ranked) { + ensure!( + rows == expected_rows.min(10) * queries, + "ranked row count mismatch" + ); + } else { + ensure!( + rows == expected_rows * queries, + "row count mismatch for {case:?}" + ); + ensure!( + sum == ids.map(|id| id as i64).sum::() * queries as i64, + "ID sum mismatch for {case:?}" + ); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn rejects_mixing_search_latency_and_throughput_options() -> Result<()> { + for options in [ + vec![ + "--benchmark", + "search", + "--connections", + "2", + "--queries", + "1", + ], + vec!["--benchmark", "search", "--seconds", "1"], + vec!["--benchmark", "throughput", "--queries", "10000"], + vec!["--benchmark", "throughput", "--state", "first"], + vec!["--benchmark", "throughput", "--seconds", "NaN"], + vec!["--benchmark", "throughput", "--seconds", "0"], + ] { + let args = Args::try_parse_from(std::iter::once("fts-benchmark").chain(options))?; + assert!(run(args).await.is_err()); + } + Ok(()) + } + + #[tokio::test] + async fn throughput_runs_for_the_requested_duration_without_latency_samples() -> Result<()> { + for minimum in [0.001, 0.005] { + let mut batches = 0; + let measured = measure_throughput(minimum, async || { + batches += 1; + Ok(RunResult { + queries: 1, + transactions: 0, + rows: 3, + id_sum: 7, + max_active_transactions: 0, + }) + }) + .await?; + assert!(measured.seconds >= minimum); + assert!(measured.latencies.is_empty()); + assert_eq!(measured.result.queries, batches); + assert_eq!(measured.result.rows, batches * 3); + assert_eq!(measured.result.id_sum, batches as i64 * 7); + } + Ok(()) + } + + #[test] + fn latency_percentiles_use_individual_samples_and_nearest_rank() { + let mut samples = [100.0, 1.0, 4.0, 2.0, 3.0]; + assert_eq!(percentile(&mut samples, 50), "3.000000000"); + assert_eq!(percentile(&mut samples, 95), "100.000000000"); + assert_eq!(percentile(&mut samples, 99), "100.000000000"); + assert_eq!(percentile(&mut [], 50), ""); + let mut samples: Vec = (1..=100).rev().map(f64::from).collect(); + assert_eq!(percentile(&mut samples, 50), "50.000000000"); + assert_eq!(percentile(&mut samples, 95), "95.000000000"); + assert_eq!(percentile(&mut samples, 99), "99.000000000"); + } + + #[tokio::test] + async fn concurrent_search_validates_all_targets_with_uneven_query_counts() -> Result<()> { + for (state, queries) in [("warm", "17"), ("first", "3")] { + run(Args::try_parse_from([ + "fts-benchmark", + "--benchmark", + "search", + "--documents", + "203", + "--connections", + "3", + "--queries", + queries, + "--state", + state, + "--runs", + "1", + ])?) + .await?; + } + Ok(()) + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn sqlite_fts5_matches_turso_wal_and_mvcc() -> Result<()> { + for (state, connections, execution) in [ + (QueryState::First, 1, Execution::Queries(1)), + (QueryState::Warm, 1, Execution::Queries(3)), + ( + QueryState::Warm, + 2, + Execution::Transactions { + per_connection: 3, + queries_per_transaction: 2, + }, + ), + ] { + for &query in QueryCase::value_variants() { + let mut config = FtsConfig { + query, + state, + documents: 203, + corpus: CorpusConfig::default(), + mode: JournalMode::Wal, + connections, + execution, + }; + let mut sqlite = sqlite::SqliteWorkload::prepare(config).await?; + let expected = sqlite.run().await?; + validate_result(query, 203, expected.queries, expected.rows, expected.id_sum)?; + assert_eq!( + expected.queries, + if connections == 2 { + 12 + } else if matches!(state, QueryState::First) { + 1 + } else { + 3 + } + ); + assert_eq!(expected.transactions, if connections == 2 { 6 } else { 0 }); + for mode in [JournalMode::Wal, JournalMode::Mvcc] { + config.mode = mode; + let turso = FtsWorkload::prepare(config, &mut ()).await?; + let actual = turso.run(&mut ()).await?; + assert_eq!(actual.queries, expected.queries); + assert_eq!(actual.transactions, expected.transactions); + assert_eq!( + actual.max_active_transactions, + expected.max_active_transactions + ); + assert_eq!(actual.rows, expected.rows); + if !matches!(query, QueryCase::Ranked) { + assert_eq!(actual.id_sum, expected.id_sum); + } + } + } + } + Ok(()) + } + + #[test] + fn checks_phrase_order_and_non_multiple_document_counts() { + assert!(validate_result(QueryCase::Rare, 103, 3, 6, 300).is_ok()); + assert!(validate_result(QueryCase::Phrase, 103, 3, 3, 0).is_ok()); + assert!(validate_result(QueryCase::Phrase, 103, 3, 6, 300).is_err()); + assert!(validate_result(QueryCase::And, 7, 2, 4, 12).is_ok()); + assert!(validate_result(QueryCase::And, 7, 2, 4, 10).is_err()); + assert!(validate_result(QueryCase::Ranked, 5, 2, 8, 18).is_ok()); + assert!(validate_result(QueryCase::Ranked, 5, 2, 20, 18).is_err()); + } +} diff --git a/perf/fts/src/profiling.rs b/perf/fts/src/profiling.rs new file mode 100644 index 000000000..23045afc7 --- /dev/null +++ b/perf/fts/src/profiling.rs @@ -0,0 +1,98 @@ +use std::collections::BTreeMap; +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::Path; + +use anyhow::{Result, ensure}; + +pub fn start(enabled: bool) -> Result>> { + if !enabled { + return Ok(None); + } + let builder = pprof::ProfilerGuardBuilder::default().frequency(99); + #[cfg(any( + target_arch = "x86_64", + target_arch = "aarch64", + target_arch = "riscv64", + target_arch = "loongarch64" + ))] + let builder = builder.blocklist(&["libc", "libgcc", "pthread", "vdso"]); + Ok(Some(builder.build()?)) +} + +pub fn finish(profiler: Option>, path: Option<&Path>) -> Result<()> { + let Some(profiler) = profiler else { + assert!(path.is_none()); + return Ok(()); + }; + let report = profiler.report().build()?; + drop(profiler); + let path = path.expect("enabled profiler must have an output path"); + ensure!( + !report.data.is_empty(), + "no CPU samples collected; increase --queries or --seconds" + ); + let mut stacks = BTreeMap::::new(); + for (frames, count) in &report.data { + let mut names = vec![frames.thread_name_or_id()]; + for frame in frames.frames.iter().rev() { + for symbol in frame.iter().rev() { + names.push(symbol.name().replace(';', ":")); + } + } + *stacks.entry(names.join(";")).or_default() += count; + } + let mut folded = BufWriter::new(File::create_new(path.with_extension("folded"))?); + for (stack, count) in stacks { + writeln!(folded, "{stack} {count}")?; + } + folded.flush()?; + report.flamegraph(File::create_new(path.with_extension("svg"))?)?; + eprintln!( + "profile {}: {} CPU samples", + path.display(), + report.data.values().sum::() + ); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn records_worker_cpu_and_preserves_sample_counts() -> Result<()> { + use std::time::{Duration, Instant}; + + let directory = tempfile::tempdir()?; + let path = directory.path().join("workers"); + finish(start(false)?, None)?; + let profiler = start(true)?; + std::thread::scope(|scope| { + for _ in 0..2 { + scope.spawn(|| { + let start = Instant::now(); + while start.elapsed() < Duration::from_secs(1) { + for value in 0..1000_u64 { + std::hint::black_box(value.wrapping_mul(31)); + } + } + }); + } + }); + finish(profiler, Some(&path))?; + let folded = std::fs::read_to_string(path.with_extension("folded"))?; + let count: usize = folded + .lines() + .map(|line| line.rsplit_once(' ').unwrap().1.parse::().unwrap()) + .sum(); + assert!(count > 0); + assert!(folded.contains("records_worker_cpu_and_preserves_sample_counts")); + let svg = std::fs::read_to_string(path.with_extension("svg"))?; + assert!(svg.contains("all (").nth(1).unwrap(); + let total = total.split(" samples,").next().unwrap().replace(',', ""); + assert_eq!(total.parse::()?, count); + Ok(()) + } +} diff --git a/perf/fts/src/sqlite.rs b/perf/fts/src/sqlite.rs new file mode 100644 index 000000000..f86888769 --- /dev/null +++ b/perf/fts/src/sqlite.rs @@ -0,0 +1,191 @@ +use anyhow::{Result, ensure}; +use memory_benchmark::fts::{Execution, FtsConfig, QueryCase, QueryState, RunResult, document}; +use rusqlite::Connection; +use tempfile::TempDir; + +pub struct SqliteWorkload { + sessions: Vec, + _directory: TempDir, + config: FtsConfig, +} + +impl SqliteWorkload { + pub async fn prepare(config: FtsConfig) -> Result { + config.validate()?; + let directory = tempfile::tempdir()?; + let path = directory.path().join("fts.db"); + let mut conn = Connection::open(&path)?; + conn.pragma_update(None, "journal_mode", "wal")?; + conn.execute_batch("CREATE TABLE docs(id INTEGER PRIMARY KEY, title TEXT, body TEXT)")?; + for start in (0..config.documents).step_by(500) { + let transaction = conn.transaction()?; + { + let mut insert = transaction.prepare("INSERT INTO docs VALUES (?1, ?2, ?3)")?; + for id in start..config.documents.min(start + 500) { + let (title, body) = document(id); + insert.execute(rusqlite::params![id as i64, title, body])?; + } + } + transaction.commit()?; + } + conn.execute_batch( + "CREATE VIRTUAL TABLE docs_fts USING fts5(title, body, content='docs', content_rowid='id', tokenize='unicode61'); + INSERT INTO docs_fts(docs_fts) VALUES ('rebuild');", + )?; + drop(conn); + let sessions = (0..config.connections) + .map(|_| Connection::open(&path)) + .collect::>>()?; + let mut workload = Self { + sessions, + _directory: directory, + config, + }; + if matches!(config.state, QueryState::Warm) { + workload.batch(1).await?; + } + Ok(workload) + } + + pub fn sessions(&mut self) -> &mut [Connection] { + &mut self.sessions + } + + pub async fn run(&mut self) -> Result { + let queries = match self.config.execution { + Execution::Queries(_) => 1, + Execution::Transactions { + queries_per_transaction, + .. + } => queries_per_transaction, + }; + let mut result = RunResult::default(); + for _ in 0..self.config.execution.batches() { + let batch = self.batch(queries).await?; + result.queries += batch.queries; + result.transactions += batch.transactions; + result.rows += batch.rows; + result.id_sum += batch.id_sum; + result.max_active_transactions = batch.max_active_transactions; + } + Ok(result) + } + + async fn batch(&mut self, queries: usize) -> Result { + let transactions = matches!(self.config.execution, Execution::Transactions { .. }); + if transactions { + for conn in &self.sessions { + conn.execute_batch("BEGIN")?; + ensure!(!conn.is_autocommit(), "BEGIN must start a transaction"); + } + } + let mut result = RunResult::default(); + if self.sessions.len() == 1 { + result = query_batch(&self.sessions[0], self.config.query, queries)?; + } else { + let mut workers = tokio::task::JoinSet::new(); + for conn in self.sessions.drain(..) { + let case = self.config.query; + workers.spawn_blocking(move || { + let result = query_batch(&conn, case, queries); + (conn, result) + }); + } + let mut outcomes = Vec::new(); + while let Some(outcome) = workers.join_next().await { + outcomes.push(outcome); + } + for outcome in outcomes { + let (conn, batch) = outcome?; + self.sessions.push(conn); + let batch = batch?; + result.queries += batch.queries; + result.rows += batch.rows; + result.id_sum += batch.id_sum; + } + } + if transactions { + for conn in &self.sessions { + conn.execute_batch("COMMIT")?; + ensure!(conn.is_autocommit(), "COMMIT must end the transaction"); + } + result.transactions = self.sessions.len(); + result.max_active_transactions = self.sessions.len(); + } + Ok(result) + } +} + +pub(super) fn query_batch(conn: &Connection, case: QueryCase, queries: usize) -> Result { + let mut result = RunResult::default(); + for _ in 0..queries { + let mut statement = conn.prepare(sql(case))?; + let mut rows = statement.query([])?; + while let Some(row) = rows.next()? { + result.rows += 1; + result.id_sum += row.get::<_, i64>(0)?; + } + result.queries += 1; + } + Ok(result) +} + +fn sql(case: QueryCase) -> &'static str { + match case { + QueryCase::Rare => "SELECT rowid FROM docs_fts WHERE docs_fts MATCH 'rare'", + QueryCase::Common => "SELECT rowid FROM docs_fts WHERE docs_fts MATCH 'common'", + QueryCase::And => "SELECT rowid FROM docs_fts WHERE docs_fts MATCH 'alpha AND beta'", + QueryCase::Or => "SELECT rowid FROM docs_fts WHERE docs_fts MATCH 'alpha OR beta'", + QueryCase::Phrase => "SELECT rowid FROM docs_fts WHERE docs_fts MATCH '\"common rare\"'", + QueryCase::Ranked => { + "SELECT rowid, bm25(docs_fts) AS score FROM docs_fts WHERE docs_fts MATCH 'alpha OR beta' ORDER BY score ASC LIMIT 10" + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use memory_benchmark::fts::CorpusConfig; + use memory_benchmark::workload::JournalMode; + + #[tokio::test] + async fn ranked_scores_are_sorted_and_limit_handles_small_corpora() -> Result<()> { + for (documents, expected_rows) in [(5, 4), (203, 10)] { + let workload = SqliteWorkload::prepare(FtsConfig { + query: QueryCase::Ranked, + state: QueryState::First, + documents, + corpus: CorpusConfig::default(), + mode: JournalMode::Wal, + connections: 1, + execution: Execution::Queries(1), + }) + .await?; + let conn = &workload.sessions[0]; + assert_eq!( + conn.pragma_query_value(None, "journal_mode", |row| row.get::<_, String>(0))?, + "wal" + ); + let mut statement = conn.prepare(sql(QueryCase::Ranked))?; + let mut rows = statement.query([])?; + let mut ids = Vec::new(); + let mut previous = f64::NEG_INFINITY; + while let Some(row) = rows.next()? { + let id: i64 = row.get(0)?; + let score: f64 = row.get(1)?; + assert!((0..documents as i64).contains(&id)); + assert!(id % 2 == 0 || id % 3 == 0); + assert!(!ids.contains(&id)); + assert!(score < 0.0 && score >= previous); + if documents == 203 { + assert_eq!(id % 6, 0); + } + previous = score; + ids.push(id); + } + assert_eq!(ids.len(), expected_rows); + } + Ok(()) + } +} diff --git a/perf/memory/src/fts.rs b/perf/memory/src/fts.rs index c690f87b1..888223030 100644 --- a/perf/memory/src/fts.rs +++ b/perf/memory/src/fts.rs @@ -165,6 +165,10 @@ impl FtsWorkload { Ok(workload) } + pub fn sessions(&self) -> &[QuerySession] { + &self.sessions + } + pub async fn run(&self, observer: &mut dyn FtsObserver) -> Result { observer.on_phase(FtsPhase::Run); let mut progress = RunResult::default(); @@ -351,20 +355,12 @@ impl FtsFixture { .prepare("INSERT INTO docs VALUES (?1, ?2, ?3)") .await?; for id in start..documents.min(start + 500) { - let rare = if id % 100 == 0 { "rare" } else { "plain" }; - let alpha = if id % 2 == 0 { "alpha" } else { "gamma" }; - let beta = if id % 3 == 0 { "beta" } else { "delta" }; - let prefix = if id % 200 == 100 { - "rare common".to_string() - } else { - format!("common {rare}") - }; - let mut body = format!("{prefix} {alpha} {beta} search document storage text"); + let (title, mut body) = document(id); for _ in 0..corpus.extra_tokens { write!(body, " x{:016x}", rng.next_u64())?; } insert - .execute(turso::params![id as i64, format!("document {id:08}"), body]) + .execute(turso::params![id as i64, title, body]) .await?; } session.conn.execute("COMMIT", ()).await?; @@ -522,6 +518,21 @@ impl QueryCase { } } +pub fn document(id: usize) -> (String, String) { + let rare = if id % 100 == 0 { "rare" } else { "plain" }; + let alpha = if id % 2 == 0 { "alpha" } else { "gamma" }; + let beta = if id % 3 == 0 { "beta" } else { "delta" }; + let prefix = if id % 200 == 100 { + "rare common".to_string() + } else { + format!("common {rare}") + }; + ( + format!("document {id:08}"), + format!("{prefix} {alpha} {beta} search document storage text"), + ) +} + #[cfg(test)] mod tests { use super::*; From 76d5acbbe3b6824add6fbf5e51595804cd890fca Mon Sep 17 00:00:00 2001 From: Amp Date: Thu, 17 Sep 2026 18:43:38 +0000 Subject: [PATCH 2/3] perf/fts: render flamegraphs with an external tool Keep Inferno out of the FTS dependency graph because its license is not allowed. Export folded stacks and let the run script invoke an independently installed inferno-flamegraph. Use pprof 0.15 without renderer features to prevent feature combination with existing 0.14 benchmark dependencies. Limit the profiler dependency and code to Linux and macOS so Windows all-features builds exclude it. Tests: full workspace license check, nine FTS tests, package Clippy, and optimized WAL/MVCC external-renderer smoke runs with matching sample counts and browser zoom. Amp-Thread-ID: https://ampcode.com/threads/T-01a0ac34-f93d-7693-9947-ee9ec864450f Co-authored-by: pedro muniz --- Cargo.lock | 36 ++++- NOTICE.md | 10 ++ licenses/perf/pprof-apache-license.md | 201 ++++++++++++++++++++++++++ licenses/perf/spin-mit-license.md | 21 +++ perf/fts/Cargo.toml | 4 +- perf/fts/README.md | 14 +- perf/fts/scripts/run.sh | 11 ++ perf/fts/src/main.rs | 32 ++-- perf/fts/src/profiling.rs | 11 +- 9 files changed, 317 insertions(+), 23 deletions(-) create mode 100644 licenses/perf/pprof-apache-license.md create mode 100644 licenses/perf/spin-mit-license.md diff --git a/Cargo.lock b/Cargo.lock index c43909e18..cd54e5efd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2257,7 +2257,7 @@ dependencies = [ "anyhow", "clap", "memory-benchmark", - "pprof", + "pprof 0.15.0", "rusqlite", "serde_json", "tempfile", @@ -4580,6 +4580,27 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "pprof" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a01da47675efa7673b032bf8efd8214f1917d89685e07e395ab125ea42b187" +dependencies = [ + "aligned-vec", + "backtrace", + "cfg-if", + "findshlibs", + "libc", + "log", + "nix 0.26.4", + "once_cell", + "smallvec", + "spin", + "symbolic-demangle", + "tempfile", + "thiserror 2.0.16", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -6095,6 +6116,15 @@ version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d372029cb5195f9ab4e4b9aef550787dce78b124fcaee8d82519925defcd6f0d" +[[package]] +name = "spin" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" +dependencies = [ + "lock_api", +] + [[package]] name = "spki" version = "0.7.3" @@ -7224,7 +7254,7 @@ dependencies = [ "parking_lot", "pastey", "polling", - "pprof", + "pprof 0.14.0", "quickcheck", "quickcheck_macros", "rand 0.9.4", @@ -7316,7 +7346,7 @@ dependencies = [ "fallible-iterator 0.3.0", "memchr", "miette", - "pprof", + "pprof 0.14.0", "serde", "strum", "strum_macros", diff --git a/NOTICE.md b/NOTICE.md index 086bf8072..c145d5660 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -63,3 +63,13 @@ This project depends on SQLAlchemy, distributed by the SQLAlchemy authors: * License: licenses/bindings/python/sqlalchemy-mit-license.md (MIT License) * Homepage: https://github.com/sqlalchemy/sqlalchemy + +The FTS benchmark depends on pprof, distributed by the TiKV project: + +* License: licenses/perf/pprof-apache-license.md (Apache License v2.0) +* Homepage: https://github.com/tikv/pprof-rs + +The FTS profiler depends on spin, distributed by the spin-rs authors: + +* License: licenses/perf/spin-mit-license.md (MIT License) +* Homepage: https://github.com/mvdnes/spin-rs diff --git a/licenses/perf/pprof-apache-license.md b/licenses/perf/pprof-apache-license.md new file mode 100644 index 000000000..9a24e8d42 --- /dev/null +++ b/licenses/perf/pprof-apache-license.md @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2019 TiKV Project Authors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/licenses/perf/spin-mit-license.md b/licenses/perf/spin-mit-license.md new file mode 100644 index 000000000..b2d7f7bbd --- /dev/null +++ b/licenses/perf/spin-mit-license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Mathijs van de Nes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/perf/fts/Cargo.toml b/perf/fts/Cargo.toml index 37445ce91..8920f68da 100644 --- a/perf/fts/Cargo.toml +++ b/perf/fts/Cargo.toml @@ -11,8 +11,10 @@ flamegraph = ["dep:pprof"] anyhow.workspace = true clap = { workspace = true, features = ["derive"] } memory-benchmark = { path = "../memory", features = ["fts"] } -pprof = { version = "0.14.0", features = ["flamegraph"], optional = true } rusqlite.workspace = true serde_json.workspace = true tempfile.workspace = true tokio = { workspace = true, features = ["full"] } + +[target.'cfg(any(target_os = "linux", target_os = "macos"))'.dependencies] +pprof = { version = "0.15.0", optional = true } diff --git a/perf/fts/README.md b/perf/fts/README.md index d455f3559..c36fc9680 100644 --- a/perf/fts/README.md +++ b/perf/fts/README.md @@ -149,8 +149,18 @@ Allocation tracking changes scheduling and adds overhead; never use its elapsed ## CPU flamegraphs Set `FLAMEGRAPH=1` to build with the optional `flamegraph` feature and collect CPU stack samples at 99 Hz. -This uses the repository's `pprof` dependency on Linux or macOS, without `perf`, root access, or cache clearing. +This uses `pprof` on Linux or macOS, without `perf`, root access, or cache clearing. +FTS uses version 0.15 so Cargo does not combine its features with the older benchmark dependency that enables Inferno. The default build remains optimized `bench-profile` with debug information for function names. +Install the external SVG renderer before running the script: + +```sh +cargo install inferno --locked +``` + +The Rust binary writes folded stacks without linking Inferno. +The script calls `inferno-flamegraph` after measurement and records its executable path. +Inferno remains a separate developer tool because its CDDL license is not on the repository's dependency allowlist. Select the journal modes, query cases, and connection count you want to investigate: ```sh @@ -168,6 +178,8 @@ Open the SVG in a browser; click a frame to zoom and use Search to find a functi Frame width shows the fraction of collected CPU samples containing that frame, not elapsed latency. The horizontal position is not a timeline. Use the folded counts for aggregate analysis, counting a function only once per stack for inclusive totals. +Direct binary runs produce only `.folded` files. +To render a saved profile separately, run `inferno-flamegraph < profile.folded > profile.svg`. Sampling starts after fixture creation, index building, reopening, and warm-up. It stops before fixture cleanup, result validation, and percentile calculation. diff --git a/perf/fts/scripts/run.sh b/perf/fts/scripts/run.sh index e37445633..c329d8a09 100644 --- a/perf/fts/scripts/run.sh +++ b/perf/fts/scripts/run.sh @@ -16,6 +16,10 @@ results=results.csv case "${FLAMEGRAPH:-0}" in 0) ;; 1) + if ! command -v inferno-flamegraph >/dev/null; then + echo 'Install the external renderer with: cargo install inferno --locked' >&2 + exit 1 + fi cargo_options=(--features flamegraph) set -- "$@" --flamegraph "$output/profiles" results=profiled-results.csv @@ -32,10 +36,17 @@ esac printf '%q ' "$@" printf '\n' if command -v lscpu >/dev/null; then lscpu; fi + if [[ "${FLAMEGRAPH:-0}" == 1 ]]; then + printf 'flamegraph_renderer=%s\n' "$(command -v inferno-flamegraph)" + fi } > "$output/environment.txt" cargo run --manifest-path "$root/Cargo.toml" --profile "$profile" -p fts-benchmark "${cargo_options[@]}" -- "$@" \ > "$output/$results" 2> "$output/bench.log" if [[ "${FLAMEGRAPH:-0}" == 0 ]]; then uv run "$root/perf/fts/plot/plot-fts.py" "$output/results.csv" \ -o "$output/fts.png" -o "$output/fts.pdf" -o "$output/fts.svg" +else + for folded in "$output"/profiles/*.folded; do + inferno-flamegraph < "$folded" > "${folded%.folded}.svg" + done fi diff --git a/perf/fts/src/main.rs b/perf/fts/src/main.rs index 6bd24a668..8c607de3a 100644 --- a/perf/fts/src/main.rs +++ b/perf/fts/src/main.rs @@ -8,7 +8,7 @@ use std::io::{Write, stdout}; use std::time::Instant; mod latency; -#[cfg(feature = "flamegraph")] +#[cfg(all(feature = "flamegraph", any(target_os = "linux", target_os = "macos")))] mod profiling; mod sqlite; @@ -42,7 +42,7 @@ struct Args { default_value = "rare,common,and,or,phrase,ranked" )] cases: Vec, - #[cfg(feature = "flamegraph")] + #[cfg(all(feature = "flamegraph", any(target_os = "linux", target_os = "macos")))] #[arg(long)] flamegraph: Option, } @@ -106,11 +106,11 @@ async fn run(mut args: Args) -> Result<()> { (0, seconds) } }; - #[cfg(feature = "flamegraph")] + #[cfg(all(feature = "flamegraph", any(target_os = "linux", target_os = "macos")))] let profiled = args.flamegraph.is_some(); - #[cfg(not(feature = "flamegraph"))] + #[cfg(not(all(feature = "flamegraph", any(target_os = "linux", target_os = "macos"))))] let profiled = false; - #[cfg(feature = "flamegraph")] + #[cfg(all(feature = "flamegraph", any(target_os = "linux", target_os = "macos")))] if let Some(directory) = &args.flamegraph { std::fs::create_dir(directory)?; } @@ -122,7 +122,7 @@ async fn run(mut args: Args) -> Result<()> { for repetition in 1..=args.runs { for &query in &args.cases { for &target in &args.targets { - #[cfg(feature = "flamegraph")] + #[cfg(all(feature = "flamegraph", any(target_os = "linux", target_os = "macos")))] let profile_path = args.flamegraph.as_ref().map(|directory| { directory.join(format!( "{}-{}-{}-c{}-run{}-{}", @@ -146,7 +146,10 @@ async fn run(mut args: Args) -> Result<()> { let mut measured = match target { Target::SqliteWal => { let mut workload = sqlite::SqliteWorkload::prepare(config).await?; - #[cfg(feature = "flamegraph")] + #[cfg(all( + feature = "flamegraph", + any(target_os = "linux", target_os = "macos") + ))] let profiler = profiling::start(profiled)?; let measured = match args.benchmark { Benchmark::Search => latency::measure( @@ -159,13 +162,19 @@ async fn run(mut args: Args) -> Result<()> { .await? } }; - #[cfg(feature = "flamegraph")] + #[cfg(all( + feature = "flamegraph", + any(target_os = "linux", target_os = "macos") + ))] profiling::finish(profiler, profile_path.as_deref())?; measured } Target::TursoWal | Target::TursoMvcc => { let workload = FtsWorkload::prepare(config, &mut ()).await?; - #[cfg(feature = "flamegraph")] + #[cfg(all( + feature = "flamegraph", + any(target_os = "linux", target_os = "macos") + ))] let profiler = profiling::start(profiled)?; let measured = match args.benchmark { Benchmark::Search => latency::measure( @@ -188,7 +197,10 @@ async fn run(mut args: Args) -> Result<()> { .await? } }; - #[cfg(feature = "flamegraph")] + #[cfg(all( + feature = "flamegraph", + any(target_os = "linux", target_os = "macos") + ))] profiling::finish(profiler, profile_path.as_deref())?; workload.finish(&mut ()); measured diff --git a/perf/fts/src/profiling.rs b/perf/fts/src/profiling.rs index 23045afc7..56a4ce414 100644 --- a/perf/fts/src/profiling.rs +++ b/perf/fts/src/profiling.rs @@ -47,7 +47,6 @@ pub fn finish(profiler: Option>, path: Option<&Pat writeln!(folded, "{stack} {count}")?; } folded.flush()?; - report.flamegraph(File::create_new(path.with_extension("svg"))?)?; eprintln!( "profile {}: {} CPU samples", path.display(), @@ -61,7 +60,7 @@ mod tests { use super::*; #[test] - fn records_worker_cpu_and_preserves_sample_counts() -> Result<()> { + fn records_worker_cpu_without_rendering_svg() -> Result<()> { use std::time::{Duration, Instant}; let directory = tempfile::tempdir()?; @@ -87,12 +86,8 @@ mod tests { .map(|line| line.rsplit_once(' ').unwrap().1.parse::().unwrap()) .sum(); assert!(count > 0); - assert!(folded.contains("records_worker_cpu_and_preserves_sample_counts")); - let svg = std::fs::read_to_string(path.with_extension("svg"))?; - assert!(svg.contains("all (").nth(1).unwrap(); - let total = total.split(" samples,").next().unwrap().replace(',', ""); - assert_eq!(total.parse::()?, count); + assert!(folded.contains("records_worker_cpu_without_rendering_svg")); + assert!(!path.with_extension("svg").exists()); Ok(()) } } From cbc897428343160e0c42bf27190d12c021112c15 Mon Sep 17 00:00:00 2001 From: Amp Date: Thu, 17 Sep 2026 18:47:20 +0000 Subject: [PATCH 3/3] perf/fts: satisfy Python lint checks Separate CSV measurement parsing and environment recording into smaller functions while preserving the workload and plotting behavior. Load SciencePlots explicitly for its style registration and apply Ruff formatting. Tests: Ruff, 13 Python tests, 12 optimized memory smoke measurements, and regenerated charts. The p99 sweep is pixel-identical to its previous rendering. Amp-Thread-ID: https://ampcode.com/threads/T-01a0ac34-f93d-7693-9947-ee9ec864450f Co-authored-by: pedro muniz --- perf/fts/plot/plot-fts.py | 224 +++++++++++++++++++++++-------------- perf/fts/plot/test_plot.py | 82 ++++++++++---- perf/fts/scripts/memory.py | 97 ++++++++++++---- 3 files changed, 279 insertions(+), 124 deletions(-) diff --git a/perf/fts/plot/plot-fts.py b/perf/fts/plot/plot-fts.py index 739994f79..0a2becbc3 100644 --- a/perf/fts/plot/plot-fts.py +++ b/perf/fts/plot/plot-fts.py @@ -4,6 +4,7 @@ import argparse import csv +import importlib from pathlib import Path import numpy as np @@ -14,8 +15,15 @@ SERIES = { ("turso", "wal"): ("Turso (WAL)", "#0072B2", ""), ("turso", "mvcc"): ("Turso (MVCC)", "#0072B2", "///"), } -CONFIGURATION = ("benchmark", "state", "documents", "connections", "requested_queries", - "min_seconds", "debug_assertions") +CONFIGURATION = ( + "benchmark", + "state", + "documents", + "connections", + "requested_queries", + "min_seconds", + "debug_assertions", +) def main(): @@ -28,7 +36,9 @@ def main(): args = parser.parse_args() if args.relative and not args.sweep: parser.error("--relative requires --sweep") - configuration, samples = read_sweep(args.csv_files, args.percentile) if args.sweep else read_runs(args.csv_files, args.percentile) + configuration, samples = ( + read_sweep(args.csv_files, args.percentile) if args.sweep else read_runs(args.csv_files, args.percentile) + ) for output in args.output or [Path("fts.png"), Path("fts.pdf")]: if args.sweep: plot_sweep(configuration, samples, output, args.relative) @@ -60,56 +70,11 @@ def read_runs(paths, percentile="p50"): samples = {} expected_series = None for path in paths: - runs = {} - with path.open(newline="") as stream: - reader = csv.DictReader(stream) - required = set(CONFIGURATION) | {"engine", "mode", "run", "query", "queries"} - if not required <= set(reader.fieldnames or []): - raise ValueError(f"{path}: missing benchmark columns") - for row in reader: - if row.get("profiled", "false") != "false": - raise ValueError("profiled timings must not be used for benchmark comparisons") - current = tuple(row[key] for key in CONFIGURATION) - if configuration is None: - configuration = current - if configuration != current: - raise ValueError("plot only one configuration at a time") - key = (row["engine"], row["mode"]) - if key not in SERIES: - raise ValueError(f"unsupported engine/mode: {key}") - series = samples.setdefault(key, {query: [] for query in QUERIES}) - query = row["query"] - seen = runs.setdefault(row["run"], {}).setdefault(key, set()) - if query not in QUERIES or query in seen: - raise ValueError(f"{path}: unknown or duplicate query {query}") - seen.add(query) - queries = int(row["queries"]) - if queries <= 0: - raise ValueError("query count must be positive") - if row["benchmark"] != "memory": - seconds = float(row["seconds"]) - if not np.isfinite(seconds) or seconds <= 0: - raise ValueError(f"{path}: timing must be positive") - if row["benchmark"] == "memory": - if row["engine"] != "turso" or queries != int(row["requested_queries"]) * int(row["connections"]): - raise ValueError("heap results require Turso and the requested queries per connection") - value = float(row["peak_heap_bytes"]) / (1024 * 1024) - elif row["benchmark"] == "search": - if not 0 < int(row["connections"]) <= queries or queries != int(row["requested_queries"]): - raise ValueError("search results require at least one sample per connection and the requested query count") - value = float(row[f"{percentile}_ms"]) - elif row["benchmark"] == "throughput": - minimum = float(row["min_seconds"]) - if not np.isfinite(minimum) or minimum <= 0 or seconds < minimum: - raise ValueError("throughput results must meet a positive minimum duration") - value = queries / seconds - else: - raise ValueError("unknown benchmark") - if not np.isfinite(value) or value <= 0: - raise ValueError("measurements must be finite and positive") - series[query].append(value) - if not runs: - raise ValueError(f"{path}: no results found") + current, runs = read_file(path, percentile, samples) + if configuration is None: + configuration = current + if configuration != current: + raise ValueError("plot only one configuration at a time") for run in runs.values(): if expected_series is None: expected_series = set(run) @@ -122,14 +87,75 @@ def read_runs(paths, percentile="p50"): return configuration, samples +def read_file(path, percentile, samples): + configuration = None + runs = {} + with path.open(newline="") as stream: + reader = csv.DictReader(stream) + required = set(CONFIGURATION) | {"engine", "mode", "run", "query", "queries"} + if not required <= set(reader.fieldnames or []): + raise ValueError(f"{path}: missing benchmark columns") + for row in reader: + if row.get("profiled", "false") != "false": + raise ValueError("profiled timings must not be used for benchmark comparisons") + current = tuple(row[key] for key in CONFIGURATION) + if configuration is None: + configuration = current + if configuration != current: + raise ValueError("plot only one configuration at a time") + key = (row["engine"], row["mode"]) + if key not in SERIES: + raise ValueError(f"unsupported engine/mode: {key}") + series = samples.setdefault(key, {query: [] for query in QUERIES}) + query = row["query"] + seen = runs.setdefault(row["run"], {}).setdefault(key, set()) + if query not in QUERIES or query in seen: + raise ValueError(f"{path}: unknown or duplicate query {query}") + seen.add(query) + series[query].append(read_measurement(row, percentile)) + if not runs: + raise ValueError(f"{path}: no results found") + return configuration, runs + + +def read_measurement(row, percentile): + queries = int(row["queries"]) + positive_number(queries) + if row["benchmark"] != "memory": + seconds = positive_number(row["seconds"]) + if row["benchmark"] == "memory": + if row["engine"] != "turso" or queries != int(row["requested_queries"]) * int(row["connections"]): + raise ValueError("heap results require Turso and the requested queries per connection") + value = float(row["peak_heap_bytes"]) / (1024 * 1024) + elif row["benchmark"] == "search": + if not 0 < int(row["connections"]) <= queries or queries != int(row["requested_queries"]): + raise ValueError("search results require at least one sample per connection and the requested query count") + value = float(row[f"{percentile}_ms"]) + elif row["benchmark"] == "throughput": + minimum = positive_number(row["min_seconds"]) + if seconds < minimum: + raise ValueError("throughput results must meet a positive minimum duration") + value = queries / seconds + else: + raise ValueError("unknown benchmark") + return positive_number(value) + + +def positive_number(value): + value = float(value) + if not np.isfinite(value) or value <= 0: + raise ValueError("measurements must be finite and positive") + return value + + def plot_sweep(configuration, points, output, relative=False): import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt - import scienceplots from matplotlib.ticker import FuncFormatter, MaxNLocator, NullLocator + importlib.import_module("scienceplots") plt.style.use(["science", "no-latex"]) fig, axes = plt.subplots(2, 3, figsize=(11, 8), dpi=300) connections = list(points) @@ -144,11 +170,20 @@ def plot_sweep(configuration, points, output, relative=False): medians, lows, highs = sweep_values(points, key, query, configuration["benchmark"], relative) short_label = "SQLite" if key[0] == "sqlite" else key[1].upper() table_rows.append([short_label, *[format_value(value) for value in medians]]) - ax.errorbar(connections, medians, yerr=[medians - lows, highs - medians], - label=label, color=color, marker="s" if key[0] == "sqlite" else "o", - markerfacecolor="white" if hatch else color, - linestyle="--" if hatch else "-", linewidth=1.3, markersize=4, - capsize=2, elinewidth=0.9) + ax.errorbar( + connections, + medians, + yerr=[medians - lows, highs - medians], + label=label, + color=color, + marker="s" if key[0] == "sqlite" else "o", + markerfacecolor="white" if hatch else color, + linestyle="--" if hatch else "-", + linewidth=1.3, + markersize=4, + capsize=2, + elinewidth=0.9, + ) ax.set_xscale("log", base=2) ax.set_ylim(bottom=0) ax.yaxis.set_major_locator(MaxNLocator(nbins=5)) @@ -164,8 +199,9 @@ def plot_sweep(configuration, points, output, relative=False): ax.set_ylabel("Speedup vs SQLite (×)" if relative else measurement_label(configuration)) if relative: ax.axhline(1, color="0.4", linewidth=0.8, linestyle=":") - table = ax.table(cellText=table_rows, colLabels=["conn.", *connections], cellLoc="center", - bbox=(0, -0.59, 1, 0.34)) + table = ax.table( + cellText=table_rows, colLabels=["conn.", *connections], cellLoc="center", bbox=(0, -0.59, 1, 0.34) + ) table.auto_set_font_size(False) table.set_fontsize(7) for cell in table.get_celld().values(): @@ -173,12 +209,19 @@ def plot_sweep(configuration, points, output, relative=False): handles, labels = axes.flat[0].get_legend_handles_labels() fig.legend(handles, labels, loc="lower center", ncol=len(labels), frameon=False) build = "debug assertions" if configuration["debug_assertions"] == "true" else "no debug assertions" - budget = (f'{configuration["requested_queries"]} queries/connection' if configuration["benchmark"] == "memory" - else f'{configuration["requested_queries"]} samples per case/run' if configuration["benchmark"] == "search" - else f'{configuration["min_seconds"]} s minimum per case/run') + budget = ( + f'{configuration["requested_queries"]} queries/connection' + if configuration["benchmark"] == "memory" + else f'{configuration["requested_queries"]} samples per case/run' + if configuration["benchmark"] == "search" + else f'{configuration["min_seconds"]} s minimum per case/run' + ) direction = " · above 1× = faster than SQLite" if relative else "" - fig.suptitle(f'{int(configuration["documents"]):,} synthetic documents · {configuration["state"]} · ' - f'{budget} · {build}{direction}', fontsize=10) + fig.suptitle( + f'{int(configuration["documents"]):,} synthetic documents · {configuration["state"]} · ' + f'{budget} · {build}{direction}', + fontsize=10, + ) fig.subplots_adjust(left=0.075, right=0.98, top=0.91, bottom=0.22, hspace=1.15, wspace=0.35) fig.savefig(output, bbox_inches="tight") plt.close(fig) @@ -204,14 +247,13 @@ def plot(configuration, samples, output): matplotlib.use("Agg") import matplotlib.pyplot as plt - import scienceplots from matplotlib.ticker import FuncFormatter, NullLocator + importlib.import_module("scienceplots") plt.style.use(["science", "no-latex"]) fig, ax = plt.subplots(figsize=(7.2, 2.8), dpi=300) ax.set_yscale("log") - ax.grid(True, axis="y", which="major", linewidth=0.5, - linestyle=(0, (2, 2)), color="0.7") + ax.grid(True, axis="y", which="major", linewidth=0.5, linestyle=(0, (2, 2)), color="0.7") ax.set_axisbelow(True) table_rows, labels, all_values = [], [], [] width = 0.8 / len(samples) @@ -225,33 +267,49 @@ def plot(configuration, samples, output): table_rows.append([format_value(value) for value in medians]) labels.append(label) offset = (index - (len(samples) - 1) / 2) * width - ax.bar(np.arange(len(QUERIES)) + offset, medians, width, color=color, - hatch=hatch, edgecolor="white", linewidth=0, label=label, zorder=3, - yerr=[medians - lows, highs - medians], capsize=1.2, - error_kw={"linewidth": 0.5, "capthick": 0.5, "zorder": 4}) - ax.set_ylim(10 ** np.floor(np.log10(min(all_values))), - 10 ** (np.ceil(np.log10(max(all_values))) + 0.5)) + ax.bar( + np.arange(len(QUERIES)) + offset, + medians, + width, + color=color, + hatch=hatch, + edgecolor="white", + linewidth=0, + label=label, + zorder=3, + yerr=[medians - lows, highs - medians], + capsize=1.2, + error_kw={"linewidth": 0.5, "capthick": 0.5, "zorder": 4}, + ) + ax.set_ylim(10 ** np.floor(np.log10(min(all_values))), 10 ** (np.ceil(np.log10(max(all_values))) + 0.5)) ax.set_xlim(-0.5, len(QUERIES) - 0.5) ax.set_xticks([]) ax.xaxis.set_minor_locator(NullLocator()) ax.yaxis.set_minor_locator(NullLocator()) ax.yaxis.set_major_formatter(FuncFormatter(lambda value, _: f"{value:g}")) ax.set_ylabel(measurement_label(configuration)) - table = ax.table(cellText=table_rows, - rowLabels=labels, colLabels=QUERIES, cellLoc="center", - loc="bottom", colWidths=[1 / len(QUERIES)] * len(QUERIES)) + table = ax.table( + cellText=table_rows, + rowLabels=labels, + colLabels=QUERIES, + cellLoc="center", + loc="bottom", + colWidths=[1 / len(QUERIES)] * len(QUERIES), + ) table.auto_set_font_size(False) table.set_fontsize(5.5) table.scale(1, 1.1) for cell in table.get_celld().values(): cell.set_linewidth(0.4) cell.set_edgecolor("black") - ax.legend(loc="upper left", ncol=len(samples), frameon=False, handlelength=1, - handletextpad=0.4, columnspacing=1.8) + ax.legend(loc="upper left", ncol=len(samples), frameon=False, handlelength=1, handletextpad=0.4, columnspacing=1.8) build = "debug assertions" if configuration["debug_assertions"] == "true" else "no debug assertions" - ax.set_title(f'{configuration["benchmark"]} · {int(configuration["documents"]):,} synthetic documents · ' - f'{configuration["state"]} · ' - f'{configuration["connections"]} connection(s) · {build}', fontsize=8) + ax.set_title( + f'{configuration["benchmark"]} · {int(configuration["documents"]):,} synthetic documents · ' + f'{configuration["state"]} · ' + f'{configuration["connections"]} connection(s) · {build}', + fontsize=8, + ) fig.savefig(output, bbox_inches="tight") plt.close(fig) diff --git a/perf/fts/plot/test_plot.py b/perf/fts/plot/test_plot.py index 6e77977ea..2a08e372c 100644 --- a/perf/fts/plot/test_plot.py +++ b/perf/fts/plot/test_plot.py @@ -1,8 +1,8 @@ import csv import importlib.util -from pathlib import Path import tempfile import unittest +from pathlib import Path spec = importlib.util.spec_from_file_location("plot_fts", Path(__file__).with_name("plot-fts.py")) plot_fts = importlib.util.module_from_spec(spec) @@ -27,10 +27,27 @@ class PlotTests(unittest.TestCase): return plot_fts.read_runs(paths, percentile) if other is None else plot_fts.read_sweep(paths, percentile) def rows(self): - return [dict(engine="turso", mode="wal", state="warm", documents="103", - connections="1", queries="4", benchmark="throughput", debug_assertions="true", - requested_queries="0", min_seconds="0.001", p50_ms="", p95_ms="", p99_ms="", - run="1", query=query, seconds="0.008") for query in plot_fts.QUERIES] + return [ + dict( + engine="turso", + mode="wal", + state="warm", + documents="103", + connections="1", + queries="4", + benchmark="throughput", + debug_assertions="true", + requested_queries="0", + min_seconds="0.001", + p50_ms="", + p95_ms="", + p99_ms="", + run="1", + query=query, + seconds="0.008", + ) + for query in plot_fts.QUERIES + ] def test_throughput_is_completed_queries_per_second(self): rows = self.rows() + [dict(row, run="2", queries="8", seconds="0.016") for row in self.rows()] @@ -38,8 +55,10 @@ class PlotTests(unittest.TestCase): self.assertEqual(samples[("turso", "wal")]["rare"], [500.0, 500.0]) def test_search_uses_individual_query_percentiles_not_wall_time_average(self): - rows = [dict(row, benchmark="search", requested_queries="4", min_seconds="0", - p50_ms="1", p95_ms="5", p99_ms="6") for row in self.rows()] + rows = [ + dict(row, benchmark="search", requested_queries="4", min_seconds="0", p50_ms="1", p95_ms="5", p99_ms="6") + for row in self.rows() + ] _, samples = self.read(rows) self.assertEqual(samples[("turso", "wal")]["rare"], [1.0]) _, samples = self.read(rows, percentile="p95") @@ -58,8 +77,10 @@ class PlotTests(unittest.TestCase): self.read(self.rows(), [dict(row, **change) for row in four]) def test_latency_sweep_uses_p99_individual_samples_at_each_connection_count(self): - one = [dict(row, benchmark="search", requested_queries="4", min_seconds="0", - p50_ms="1", p95_ms="5", p99_ms="6") for row in self.rows()] + one = [ + dict(row, benchmark="search", requested_queries="4", min_seconds="0", p50_ms="1", p95_ms="5", p99_ms="6") + for row in self.rows() + ] four = [dict(row, connections="4", p50_ms="2", p95_ms="8", p99_ms="11") for row in one] configuration, points = self.read(one, four, percentile="p99") self.assertEqual(configuration["percentile"], "p99") @@ -72,8 +93,10 @@ class PlotTests(unittest.TestCase): rows = [] for run, seconds in [("1", "0.004"), ("2", "0.020")]: for index, (engine, mode) in enumerate(plot_fts.SERIES, 1): - rows.extend(dict(row, run=run, engine=engine, mode=mode, - seconds=str(float(seconds) * index)) for row in self.rows()) + rows.extend( + dict(row, run=run, engine=engine, mode=mode, seconds=str(float(seconds) * index)) + for row in self.rows() + ) _, samples = self.read(rows) self.assertEqual(samples[("sqlite", "wal")]["rare"], [1000.0, 200.0]) self.assertEqual(samples[("turso", "wal")]["rare"], [500.0, 100.0]) @@ -109,8 +132,10 @@ class PlotTests(unittest.TestCase): self.read(rows) def test_speedup_uses_ratio_of_medians_and_correct_direction(self): - points = {1: {("sqlite", "wal"): {"rare": [4, 8]}, ("turso", "wal"): {"rare": [2, 6]}}, - 4: {("sqlite", "wal"): {"rare": [3]}, ("turso", "wal"): {"rare": [9]}}} + points = { + 1: {("sqlite", "wal"): {"rare": [4, 8]}, ("turso", "wal"): {"rare": [2, 6]}}, + 4: {("sqlite", "wal"): {"rare": [3]}, ("turso", "wal"): {"rare": [9]}}, + } medians, lows, highs = plot_fts.sweep_values(points, ("turso", "wal"), "rare", "search", True) self.assertEqual(list(medians), [1.5, 1 / 3]) self.assertEqual(list(lows), [1, 1 / 3]) @@ -125,8 +150,10 @@ class PlotTests(unittest.TestCase): self.assertEqual(plot_fts.format_value(value), expected) def test_memory_plots_peak_bytes_as_mib_without_timing(self): - one = [dict(row, benchmark="memory", requested_queries="4", min_seconds="0", - peak_heap_bytes="1572864") for row in self.rows()] + one = [ + dict(row, benchmark="memory", requested_queries="4", min_seconds="0", peak_heap_bytes="1572864") + for row in self.rows() + ] for row in one: del row["seconds"] four = [dict(row, connections="4", queries="16", peak_heap_bytes="5242880") for row in one] @@ -139,15 +166,30 @@ class PlotTests(unittest.TestCase): self.read([dict(row, queries="4") for row in four]) def test_memory_summary_preserves_peak_not_total_or_per_query(self): - report = dict(query="common", documents=203, rows_per_query=203, mode="wal", state="warm", - queries=6, connections=3, transactions=0, peak_live_query_bytes=8192, - retained_query_bytes=4096, total_allocated_bytes=48000, total_allocations=700) + report = dict( + query="common", + documents=203, + rows_per_query=203, + mode="wal", + state="warm", + queries=6, + connections=3, + transactions=0, + peak_live_query_bytes=8192, + retained_query_bytes=4096, + total_allocated_bytes=48000, + total_allocations=700, + ) row = fts_memory.measurement(report, 2, 1, "bench-profile") self.assertEqual(row["peak_heap_bytes"], 8192) self.assertEqual(row["queries"], 6) self.assertEqual(row["requested_queries"], 2) - for change in (dict(queries=2), dict(rows_per_query=202), dict(retained_query_bytes=8193), - dict(total_allocated_bytes=8191)): + for change in ( + dict(queries=2), + dict(rows_per_query=202), + dict(retained_query_bytes=8193), + dict(total_allocated_bytes=8191), + ): with self.assertRaises(ValueError): fts_memory.measurement(report | change, 2, 1, "bench-profile") diff --git a/perf/fts/scripts/memory.py b/perf/fts/scripts/memory.py index 6f2a92de4..53bf3d40a 100644 --- a/perf/fts/scripts/memory.py +++ b/perf/fts/scripts/memory.py @@ -2,9 +2,9 @@ import argparse import csv import json import os -from pathlib import Path import platform import subprocess +from pathlib import Path def main(): @@ -26,12 +26,7 @@ def main(): root = Path(__file__).resolve().parents[3] args.output.mkdir() output = args.output.resolve() - metadata = dict(arguments=vars(args) | {"output": str(output)}, machine=platform.platform(), - cpus=os.cpu_count(), allocator="dhat", scope="query-phase Rust allocations") - for name, command in (("rustc", ["rustc", "-Vv"]), ("revision", ["git", "rev-parse", "HEAD"]), - ("worktree", ["git", "status", "--short"])): - metadata[name] = subprocess.check_output(command, cwd=root, text=True).strip() - (output / "environment.json").write_text(json.dumps(metadata, indent=2) + "\n") + write_environment(args, root, output) csv_paths = [] for connections in args.connections: directory = output / f"c{connections}" @@ -46,12 +41,37 @@ def main(): for mode in modes: stem = directory / f"{mode}-{query}-run{run}" print(f"Heap: c{connections} {mode} {query} run {run}", flush=True) - command = ["cargo", "run", "--profile", args.profile, "-p", "memory-benchmark", - "--features", "fts", "--bin", "fts-memory", "--", - "--query", query, "--state", args.state, "--mode", mode, - "--documents", str(args.documents), "--connections", str(connections), - "--queries", str(args.queries), "--dhat-file", str(stem) + ".dhat.json"] - with Path(str(stem) + ".json").open("w") as report_file, stem.with_suffix(".log").open("w") as log: + command = [ + "cargo", + "run", + "--profile", + args.profile, + "-p", + "memory-benchmark", + "--features", + "fts", + "--bin", + "fts-memory", + "--", + "--query", + query, + "--state", + args.state, + "--mode", + mode, + "--documents", + str(args.documents), + "--connections", + str(connections), + "--queries", + str(args.queries), + "--dhat-file", + str(stem) + ".dhat.json", + ] + with ( + Path(str(stem) + ".json").open("w") as report_file, + stem.with_suffix(".log").open("w") as log, + ): subprocess.run(command, cwd=root, stdout=report_file, stderr=log, check=True) report = json.loads(Path(str(stem) + ".json").read_text()) row = measurement(report, args.queries, run, args.profile) @@ -66,25 +86,60 @@ def main(): subprocess.run(command, cwd=root, check=True) +def write_environment(args, root, output): + metadata = dict( + arguments=vars(args) | {"output": str(output)}, + machine=platform.platform(), + cpus=os.cpu_count(), + allocator="dhat", + scope="query-phase Rust allocations", + ) + for name, command in ( + ("rustc", ["rustc", "-Vv"]), + ("revision", ["git", "rev-parse", "HEAD"]), + ("worktree", ["git", "status", "--short"]), + ): + metadata[name] = subprocess.check_output(command, cwd=root, text=True).strip() + (output / "environment.json").write_text(json.dumps(metadata, indent=2) + "\n") + + def measurement(report, queries_per_connection, run, profile): if report["queries"] != queries_per_connection * report["connections"] or report["transactions"] != 0: raise ValueError("memory run did not complete the requested queries") documents = report["documents"] either = (documents + 1) // 2 + (documents + 2) // 3 - (documents + 5) // 6 - expected = {"rare": (documents + 99) // 100, "common": documents, "and": (documents + 5) // 6, - "or": either, "phrase": (documents + 199) // 200, "ranked": min(10, either)} + expected = { + "rare": (documents + 99) // 100, + "common": documents, + "and": (documents + 5) // 6, + "or": either, + "phrase": (documents + 199) // 200, + "ranked": min(10, either), + } query = report["query"] if report["rows_per_query"] != expected[query]: raise ValueError("unexpected query result count") peak = report["peak_live_query_bytes"] if not 0 <= report["retained_query_bytes"] <= peak <= report["total_allocated_bytes"]: raise ValueError("inconsistent heap measurements") - return dict(benchmark="memory", engine="turso", mode=report["mode"], state=report["state"], - documents=documents, connections=report["connections"], queries=report["queries"], run=run, - query=query, requested_queries=queries_per_connection, min_seconds=0, - debug_assertions=str(profile == "dev").lower(), peak_heap_bytes=peak, - retained_heap_bytes=report["retained_query_bytes"], - total_allocated_bytes=report["total_allocated_bytes"], total_allocations=report["total_allocations"]) + return dict( + benchmark="memory", + engine="turso", + mode=report["mode"], + state=report["state"], + documents=documents, + connections=report["connections"], + queries=report["queries"], + run=run, + query=query, + requested_queries=queries_per_connection, + min_seconds=0, + debug_assertions=str(profile == "dev").lower(), + peak_heap_bytes=peak, + retained_heap_bytes=report["retained_query_bytes"], + total_allocated_bytes=report["total_allocated_bytes"], + total_allocations=report["total_allocations"], + ) if __name__ == "__main__":