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 <pedro.muniz.carlo@gmail.com>
This commit is contained in:
Amp
2026-09-17 18:15:24 +00:00
parent 9a082e5bc3
commit 6e532c91ca
14 changed files with 1783 additions and 10 deletions

14
Cargo.lock generated
View File

@@ -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"

View File

@@ -41,6 +41,7 @@ members = [
"testing/concurrent-simulator",
"perf/throughput",
"perf/latency",
"perf/fts",
"perf/join-benchmark",
"perf/encryption",
"perf/memory",

18
perf/fts/Cargo.toml Normal file
View File

@@ -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"] }

224
perf/fts/README.md Normal file
View File

@@ -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
```

272
perf/fts/plot/plot-fts.py Normal file
View File

@@ -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()

156
perf/fts/plot/test_plot.py Normal file
View File

@@ -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()

View File

@@ -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()

41
perf/fts/scripts/run.sh Normal file
View File

@@ -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

47
perf/fts/scripts/sweep.sh Normal file
View File

@@ -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

116
perf/fts/src/latency.rs Normal file
View File

@@ -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<S: Send>(
sessions: Vec<S>,
queries: usize,
execute: impl Fn(&mut S, &Runtime) -> Result<RunResult> + Sync,
) -> Result<Measurement> {
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::<Result<Vec<_>>>()?;
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(())
}
}

493
perf/fts/src/main.rs Normal file
View File

@@ -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<usize>,
#[arg(long, conflicts_with = "queries")]
seconds: Option<f64>,
#[arg(
long,
value_enum,
value_delimiter = ',',
default_value = "sqlite-wal,turso-wal,turso-mvcc"
)]
targets: Vec<Target>,
#[arg(long, default_value_t = 1)]
connections: usize,
#[arg(
long,
value_enum,
value_delimiter = ',',
default_value = "rare,common,and,or,phrase,ranked"
)]
cases: Vec<QueryCase>,
#[cfg(feature = "flamegraph")]
#[arg(long)]
flamegraph: Option<std::path::PathBuf>,
}
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<RunResult>,
) -> Result<Measurement> {
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<f64>,
}
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::<i64>() * 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<f64> = (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());
}
}

98
perf/fts/src/profiling.rs Normal file
View File

@@ -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<Option<pprof::ProfilerGuard<'static>>> {
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<pprof::ProfilerGuard<'static>>, 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::<String, isize>::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::<isize>()
);
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::<usize>().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("<svg"));
let total = svg.split("<title>all (").nth(1).unwrap();
let total = total.split(" samples,").next().unwrap().replace(',', "");
assert_eq!(total.parse::<usize>()?, count);
Ok(())
}
}

191
perf/fts/src/sqlite.rs Normal file
View File

@@ -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<Connection>,
_directory: TempDir,
config: FtsConfig,
}
impl SqliteWorkload {
pub async fn prepare(config: FtsConfig) -> Result<Self> {
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::<rusqlite::Result<Vec<_>>>()?;
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<RunResult> {
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<RunResult> {
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<RunResult> {
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(())
}
}

View File

@@ -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<RunResult> {
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::*;