mirror of
https://github.com/allankoechke/turso.git
synced 2026-11-30 11:12:58 +00:00
perf: add join execution benchmark
Run SQL files without printing result rows. Report elapsed time and stable statement work counters as JSON. Document the TPC-H and graph baseline study. Tests: cargo clippy -p turso-join-benchmark --all-targets
This commit is contained in:
10
Cargo.lock
generated
10
Cargo.lock
generated
@@ -7022,6 +7022,16 @@ dependencies = [
|
||||
"turso_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "turso-join-benchmark"
|
||||
version = "0.8.0-pre.8"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
"serde_json",
|
||||
"turso_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "turso-txn-latency"
|
||||
version = "0.8.0-pre.8"
|
||||
|
||||
@@ -41,6 +41,7 @@ members = [
|
||||
"testing/concurrent-simulator",
|
||||
"perf/throughput",
|
||||
"perf/latency",
|
||||
"perf/join-benchmark",
|
||||
"perf/encryption",
|
||||
"perf/memory",
|
||||
"perf/memory/codspeed",
|
||||
|
||||
24
perf/join-benchmark/Cargo.toml
Normal file
24
perf/join-benchmark/Cargo.toml
Normal file
@@ -0,0 +1,24 @@
|
||||
# Copyright 2026 the Turso authors. All rights reserved. MIT license.
|
||||
|
||||
[package]
|
||||
name = "turso-join-benchmark"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
description = "Execution benchmark for join plans"
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "turso-join-benchmark"
|
||||
path = "main.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
turso_core = { workspace = true }
|
||||
43
perf/join-benchmark/README.md
Normal file
43
perf/join-benchmark/README.md
Normal file
@@ -0,0 +1,43 @@
|
||||
# Join execution benchmark
|
||||
|
||||
This tool measures query execution without printing result rows. It reports one JSON record for each measured execution.
|
||||
|
||||
The records include elapsed time and stable work counters.
|
||||
Use release builds for runtime tests so the engine uses its production settings.
|
||||
|
||||
Run the graph query set with analyzed statistics:
|
||||
|
||||
```bash
|
||||
cargo run --release -p turso-join-benchmark -- \
|
||||
--database perf/graph-queries/graph-queries-analyzed.db \
|
||||
--query-dir perf/graph-queries/queries
|
||||
```
|
||||
|
||||
Use `--filter cooccurrence` to select a small query set. Use `--repetitions 1` for a fast diagnostic run.
|
||||
|
||||
Use `--query 5 --query 9` to select exact file stems. This option prevents `--filter 1` from also selecting `10`.
|
||||
|
||||
Print the structured query plans without query execution:
|
||||
|
||||
```bash
|
||||
cargo run --release -p turso-join-benchmark -- \
|
||||
--database perf/graph-queries/graph-queries-analyzed.db \
|
||||
--query-dir perf/graph-queries/queries \
|
||||
--plans
|
||||
```
|
||||
|
||||
The tool uses warm-cache execution by default. Set `--warmups 0` to include the first execution.
|
||||
|
||||
Each query has a 30-second timeout by default. Set `--timeout-seconds 0` to disable the timeout.
|
||||
|
||||
Run selected TPC-H queries with a longer timeout:
|
||||
|
||||
```bash
|
||||
cargo run --release -p turso-join-benchmark -- \
|
||||
--database perf/tpc-h/TPC-H.db \
|
||||
--query-dir perf/tpc-h/queries \
|
||||
--query 5 --query 9 \
|
||||
--timeout-seconds 300
|
||||
```
|
||||
|
||||
See [RESULTS.md](RESULTS.md) for the first join optimizer study.
|
||||
126
perf/join-benchmark/RESULTS.md
Normal file
126
perf/join-benchmark/RESULTS.md
Normal file
@@ -0,0 +1,126 @@
|
||||
# Join optimizer study: 2026-09-06
|
||||
|
||||
This study uses debug builds because repository rules prohibit release builds.
|
||||
Execution work is the primary measure.
|
||||
Planning time is outside the study.
|
||||
|
||||
## Measures
|
||||
|
||||
The runner consumes every result row and records statement metrics.
|
||||
The main measures are VM steps and rows read.
|
||||
These counters are more stable than elapsed time on a shared machine.
|
||||
|
||||
Elapsed time remains useful for large changes.
|
||||
Each TPC-H query uses the same database and warm cache unless noted.
|
||||
|
||||
The study also saves the JSON query plan.
|
||||
Each access node reports input rows, output rows, local cost, and total prefix cost.
|
||||
|
||||
## Baseline
|
||||
|
||||
The baseline used commit `b04d329547` and the analyzed benchmark databases.
|
||||
|
||||
| Query | VM steps | Rows read | Time |
|
||||
|---|---:|---:|---:|
|
||||
| TPC-H 5 | 19,424,408 | 3,555,780 | 26.37 s |
|
||||
| TPC-H 9 | 58,993,989 | 6,649,413 | 107.76 s |
|
||||
| Graph `a_cooccurrence` | 427,457 | 40,171 | 0.88 s |
|
||||
| Graph `c_edge_counts` | 2,396,740 | 161,336 | 0.43 s |
|
||||
|
||||
The other six graph queries provide guard coverage.
|
||||
Their baseline VM counts range from 1,060 to 289,758.
|
||||
|
||||
## Hypotheses
|
||||
|
||||
### Finish connected components first
|
||||
|
||||
TPC-H 5 placed `region` after `orders` without a join condition.
|
||||
This order scanned the small table once for each order row.
|
||||
|
||||
A forced connected order reduced VM steps to 16,100,394.
|
||||
It reduced rows read to 2,445,401.
|
||||
The result validated connected-prefix pruning.
|
||||
|
||||
### Build equality classes
|
||||
|
||||
TPC-H 5 contains `customer.nation = supplier.nation` and `supplier.nation = nation.id`.
|
||||
The old optimizer could not infer `customer.nation = nation.id`.
|
||||
|
||||
A forced query with that implied equality used 12,447,183 VM steps.
|
||||
It read 1,898,579 rows.
|
||||
The result justified equality classes.
|
||||
|
||||
The implementation uses one representative column for each class.
|
||||
It adds missing links in a star shape.
|
||||
This shape avoids unnecessary links and unstable symmetric plans.
|
||||
|
||||
### Count constant filters inside compound lookups
|
||||
|
||||
The `region` lookup used both its join key and `region.name`.
|
||||
The old estimate treated every joined key as a hit.
|
||||
It therefore missed the tenfold reduction from the name filter.
|
||||
|
||||
The new estimate applies a consumed constant filter when a lookup also uses a join key.
|
||||
This estimate moved `nation` and `region` before `lineitem`.
|
||||
|
||||
### Count unmatched outer rows
|
||||
|
||||
The old model counted matches for a left join but did not count preserved unmatched rows.
|
||||
It also mispriced `WHERE right.key IS NULL` anti-joins.
|
||||
|
||||
The new model estimates the chance of no match from the average match count.
|
||||
It uses that value for null tests on non-null right-side columns.
|
||||
|
||||
### Keep looking after an unavailable duplicate
|
||||
|
||||
An early equality-class version exposed a compound-index bug in TPC-H 9.
|
||||
An unavailable duplicate on one index column stopped the next usable column.
|
||||
|
||||
The search now skips the unavailable duplicate.
|
||||
It only stops when a later index column creates a real prefix gap.
|
||||
|
||||
## Final results
|
||||
|
||||
| Query | Baseline VM | Final VM | VM change | Baseline rows | Final rows | Row change |
|
||||
|---|---:|---:|---:|---:|---:|---:|
|
||||
| TPC-H 5 | 19,424,408 | 12,447,165 | -35.9% | 3,555,780 | 1,898,579 | -46.6% |
|
||||
| TPC-H 9 | 58,993,989 | 58,993,419 | 0.0% | 6,649,413 | 6,649,413 | 0.0% |
|
||||
| Graph `a_cooccurrence` | 427,457 | 427,457 | 0.0% | 40,171 | 40,171 | 0.0% |
|
||||
| Graph `c_edge_counts` | 2,396,740 | 101,243 | -95.8% | 161,336 | 8,077 | -95.0% |
|
||||
|
||||
TPC-H 5 measured time fell from 26.37 seconds to 9.82 seconds.
|
||||
TPC-H 9 kept the same work and completed in 100.63 seconds.
|
||||
|
||||
All other graph queries kept the same VM steps and rows read.
|
||||
The graph suite found no deterministic work regression.
|
||||
|
||||
## Commands
|
||||
|
||||
Print plans:
|
||||
|
||||
```bash
|
||||
cargo run -p turso-join-benchmark -- \
|
||||
--database perf/tpc-h/TPC-H.db \
|
||||
--query-dir perf/tpc-h/queries \
|
||||
--query 5 --query 9 --plans
|
||||
```
|
||||
|
||||
Measure TPC-H execution:
|
||||
|
||||
```bash
|
||||
cargo run -p turso-join-benchmark -- \
|
||||
--database perf/tpc-h/TPC-H.db \
|
||||
--query-dir perf/tpc-h/queries \
|
||||
--query 5 --query 9 \
|
||||
--warmups 1 --repetitions 3 \
|
||||
--timeout-seconds 300
|
||||
```
|
||||
|
||||
Measure the analyzed graph suite:
|
||||
|
||||
```bash
|
||||
cargo run -p turso-join-benchmark -- \
|
||||
--database perf/graph-queries/graph-queries-analyzed.db \
|
||||
--query-dir perf/graph-queries/queries \
|
||||
--warmups 1 --repetitions 3
|
||||
```
|
||||
184
perf/join-benchmark/main.rs
Normal file
184
perf/join-benchmark/main.rs
Normal file
@@ -0,0 +1,184 @@
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use anyhow::{bail, Context, Result};
|
||||
use clap::Parser;
|
||||
use serde_json::{json, Value as JsonValue};
|
||||
use turso_core::{Database, OpenFlags, OpenOptions, PlatformIO, SqliteDialect, StepResult, Value};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "turso-join-benchmark")]
|
||||
#[command(about = "Measure join query execution without printing result rows")]
|
||||
struct Args {
|
||||
/// Database file that contains the benchmark data.
|
||||
#[arg(long)]
|
||||
database: PathBuf,
|
||||
|
||||
/// Directory that contains one SQL query per file.
|
||||
#[arg(long)]
|
||||
query_dir: PathBuf,
|
||||
|
||||
/// Run only queries whose file stem contains this text.
|
||||
#[arg(long)]
|
||||
filter: Option<String>,
|
||||
|
||||
/// Run a query with this exact file stem. This option can occur more than once.
|
||||
#[arg(long = "query")]
|
||||
query_names: Vec<String>,
|
||||
|
||||
/// Number of unmeasured executions before each measured query.
|
||||
#[arg(long, default_value_t = 1)]
|
||||
warmups: usize,
|
||||
|
||||
/// Number of measured executions for each query.
|
||||
#[arg(long, default_value_t = 5)]
|
||||
repetitions: usize,
|
||||
|
||||
/// Stop an execution after this many seconds. Zero disables the timeout.
|
||||
#[arg(long, default_value_t = 30)]
|
||||
timeout_seconds: u64,
|
||||
|
||||
/// Print each query plan as one JSON record. Do not execute the query.
|
||||
#[arg(long)]
|
||||
plans: bool,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
let queries = load_queries(&args.query_dir, args.filter.as_deref(), &args.query_names)?;
|
||||
if queries.is_empty() {
|
||||
bail!("no SQL files matched the query selection");
|
||||
}
|
||||
|
||||
#[allow(clippy::arc_with_non_send_sync)]
|
||||
let io = Arc::new(PlatformIO::new()?);
|
||||
let database = Database::open(
|
||||
io,
|
||||
&args.database.to_string_lossy(),
|
||||
OpenOptions::new(Arc::new(SqliteDialect)).flags(OpenFlags::ReadOnly),
|
||||
)?;
|
||||
let connection = database.connect()?;
|
||||
|
||||
for query in queries {
|
||||
if args.plans {
|
||||
print_plan(&connection, &query)?;
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut statement = connection
|
||||
.prepare(&query.sql)
|
||||
.with_context(|| format!("prepare query {}", query.name))?;
|
||||
set_timeout(&mut statement, args.timeout_seconds);
|
||||
|
||||
for _ in 0..args.warmups {
|
||||
execute(&database, &mut statement)?;
|
||||
statement.reset()?;
|
||||
}
|
||||
|
||||
for repetition in 0..args.repetitions {
|
||||
statement.reset_metrics();
|
||||
let start = Instant::now();
|
||||
let result_rows = execute(&database, &mut statement)?;
|
||||
let elapsed = start.elapsed();
|
||||
let metrics = statement.metrics();
|
||||
println!(
|
||||
"{}",
|
||||
json!({
|
||||
"query": query.name,
|
||||
"repetition": repetition,
|
||||
"elapsed_ns": elapsed.as_nanos().min(u64::MAX as u128) as u64,
|
||||
"result_rows": result_rows,
|
||||
"rows_read": metrics.rows_read,
|
||||
"vm_steps": metrics.vm_steps,
|
||||
"instructions": metrics.insn_executed,
|
||||
"fullscan_steps": metrics.fullscan_steps,
|
||||
"index_steps": metrics.index_steps,
|
||||
"btree_seeks": metrics.btree_seeks,
|
||||
"btree_next": metrics.btree_next,
|
||||
"btree_prev": metrics.btree_prev,
|
||||
"sort_operations": metrics.sort_operations,
|
||||
"hash_spill_bytes": metrics.hash_join.spill_bytes_written,
|
||||
"hash_load_bytes": metrics.hash_join.load_bytes_read,
|
||||
"hash_probe_calls": metrics.hash_join.probe_calls,
|
||||
})
|
||||
);
|
||||
statement.reset()?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Query {
|
||||
name: String,
|
||||
sql: String,
|
||||
}
|
||||
|
||||
fn load_queries(
|
||||
query_dir: &Path,
|
||||
filter: Option<&str>,
|
||||
query_names: &[String],
|
||||
) -> Result<Vec<Query>> {
|
||||
let mut paths = fs::read_dir(query_dir)
|
||||
.with_context(|| format!("read query directory {}", query_dir.display()))?
|
||||
.map(|entry| entry.map(|entry| entry.path()))
|
||||
.collect::<std::io::Result<Vec<_>>>()?;
|
||||
paths.sort();
|
||||
|
||||
let mut queries = Vec::new();
|
||||
for path in paths {
|
||||
if path.extension().and_then(|value| value.to_str()) != Some("sql") {
|
||||
continue;
|
||||
}
|
||||
let name = path
|
||||
.file_stem()
|
||||
.and_then(|value| value.to_str())
|
||||
.context("query file name is not UTF-8")?
|
||||
.to_string();
|
||||
if filter.is_some_and(|filter| !name.contains(filter)) {
|
||||
continue;
|
||||
}
|
||||
if !query_names.is_empty() && !query_names.contains(&name) {
|
||||
continue;
|
||||
}
|
||||
queries.push(Query {
|
||||
name,
|
||||
sql: fs::read_to_string(&path)
|
||||
.with_context(|| format!("read query file {}", path.display()))?,
|
||||
});
|
||||
}
|
||||
Ok(queries)
|
||||
}
|
||||
|
||||
fn set_timeout(statement: &mut turso_core::Statement, timeout_seconds: u64) {
|
||||
let timeout = (timeout_seconds != 0).then(|| Duration::from_secs(timeout_seconds));
|
||||
statement.set_query_timeout_override(Some(timeout));
|
||||
}
|
||||
|
||||
fn execute(database: &Database, statement: &mut turso_core::Statement) -> Result<u64> {
|
||||
let mut result_rows = 0_u64;
|
||||
loop {
|
||||
match statement.step()? {
|
||||
StepResult::Row => result_rows = result_rows.saturating_add(1),
|
||||
StepResult::IO | StepResult::Yield | StepResult::Sleep { .. } => database.io.step()?,
|
||||
StepResult::Done => return Ok(result_rows),
|
||||
StepResult::Interrupt => bail!("query was interrupted"),
|
||||
StepResult::Busy => bail!("database was busy"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn print_plan(connection: &Arc<turso_core::Connection>, query: &Query) -> Result<()> {
|
||||
let sql = format!("EXPLAIN QUERY PLAN FORMAT=JSON {}", query.sql);
|
||||
let rows = connection.prepare(sql)?.run_collect_rows()?;
|
||||
let Some(Value::Text(plan)) = rows.first().and_then(|row| row.first()) else {
|
||||
bail!("query {} did not return a JSON plan", query.name);
|
||||
};
|
||||
let plan: JsonValue = serde_json::from_str(plan.as_str())?;
|
||||
println!("{}", json!({"query": query.name, "plan": plan}));
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user