optimizer: correct join cardinality estimates

Count constant filters that share a compound lookup with a join key. Keep unmatched outer rows and price common outer-join null tests.

Continue through unavailable duplicate constraints until an index prefix has a real gap.

Tests: cargo test -p core_tester --test integration_tests test_eqp_json
This commit is contained in:
Jussi Saurio
2026-09-06 15:15:20 +03:00
committed by GitHub
parent 342dfbe267
commit 8d55eb621a
6 changed files with 331 additions and 8 deletions

1
Cargo.lock generated
View File

@@ -1194,6 +1194,7 @@ dependencies = [
"rand 0.9.4",
"rand_chacha 0.9.0",
"rusqlite",
"serde_json",
"serial_test",
"similar-asserts",
"sql_generation",

View File

@@ -1302,7 +1302,7 @@ pub fn usable_constraints_for_lhs_mask(
if other_side_refers_to_self {
// Self-referential constraints cannot seed a lookup, but if they are
// on a later index column they also terminate the usable prefix.
if cref.index_col_pos != current_required_column_pos {
if cref.index_col_pos > current_required_column_pos {
break;
}
continue;
@@ -1311,7 +1311,7 @@ pub fn usable_constraints_for_lhs_mask(
// Join-dependent constraints are only usable when every referenced
// outer table is already on the left side of the join order. As
// above, a missing earlier prefix column terminates the prefix.
if cref.index_col_pos != current_required_column_pos {
if cref.index_col_pos > current_required_column_pos {
break;
}
continue;

View File

@@ -289,8 +289,10 @@ pub(crate) fn estimate_rows_per_seek(
base_row_count: RowCountEstimate,
analyze_ctx: Option<&AnalyzeCtx>,
) -> f64 {
let join_probe_constant_selectivity =
join_probe_constant_selectivity(constraints, usable_constraint_refs);
if is_unique_point_lookup(index_info, usable_constraint_refs) {
return 1.0;
return join_probe_constant_selectivity;
}
if let Some(ctx) = analyze_ctx {
@@ -318,7 +320,8 @@ pub(crate) fn estimate_rows_per_seek(
sel
})
.product();
return (eq_prefix_rows * range_selectivity).max(1.0);
return (eq_prefix_rows * range_selectivity).max(1.0)
* join_probe_constant_selectivity;
}
}
}
@@ -340,7 +343,27 @@ pub(crate) fn estimate_rows_per_seek(
})
.product();
(selectivity_multiplier * *base_row_count).max(1.0)
(selectivity_multiplier * *base_row_count).max(1.0) * join_probe_constant_selectivity
}
fn join_probe_constant_selectivity(
constraints: &[Constraint],
usable_constraint_refs: &[RangeConstraintRef],
) -> f64 {
let equality_constraints = usable_constraint_refs
.iter()
.take_while(|constraint| constraint.eq.is_some())
.map(|constraint| &constraints[constraint.eq.as_ref().unwrap().constraint_pos]);
if !equality_constraints
.clone()
.any(|constraint| !constraint.lhs_mask.is_empty())
{
return 1.0;
}
equality_constraints
.filter(|constraint| constraint.lhs_mask.is_empty())
.map(|constraint| constraint.selectivity)
.product()
}
/// Estimate rows per seek using ANALYZE stats (sqlite_stat1 histogram data).

View File

@@ -74,7 +74,31 @@ fn constraint_output_multipliers(
rhs_self_mask: TableMask,
consumed_where_terms: &BitSet<usize>,
skipped_where_terms: &BitSet<usize>,
where_clause: &[WhereTerm],
params: &CostModelParams,
) -> f64 {
constraint_output_multipliers_for(
rhs_constraints,
lhs_mask,
rhs_self_mask,
consumed_where_terms,
skipped_where_terms,
where_clause,
params,
|_| true,
)
}
#[allow(clippy::too_many_arguments)]
fn constraint_output_multipliers_for(
rhs_constraints: &TableConstraints,
lhs_mask: &TableMask,
rhs_self_mask: TableMask,
consumed_where_terms: &BitSet<usize>,
skipped_where_terms: &BitSet<usize>,
where_clause: &[WhereTerm],
params: &CostModelParams,
include: impl Fn(&super::constraints::Constraint) -> bool,
) -> f64 {
let mut multiplier = 1.0;
let mut bounds: SmallVec<[(Option<usize>, bool, bool); 4]> = SmallVec::new();
@@ -100,6 +124,8 @@ fn constraint_output_multipliers(
|| constraint.lhs_mask.is_empty())
&& !consumed_where_terms.get(constraint.where_clause_pos.0)
&& !skipped_where_terms.get(constraint.where_clause_pos.0)
&& !where_clause[constraint.where_clause_pos.0].consumed
&& include(constraint)
}) {
multiplier *= constraint.selectivity;
@@ -125,6 +151,7 @@ fn constraint_output_multipliers(
}
/// Return the row count after one table and its ready filters.
#[allow(clippy::too_many_arguments)]
fn rows_after_join(
input_cardinality: f64,
method: &AccessMethod,
@@ -132,6 +159,7 @@ fn rows_after_join(
lhs_mask: &TableMask,
rhs_mask: TableMask,
rhs_table: &JoinedTable,
where_clause: &[WhereTerm],
params: &CostModelParams,
) -> f64 {
if rhs_table
@@ -141,15 +169,82 @@ fn rows_after_join(
{
return input_cardinality;
}
let remaining_filter_selectivity = constraint_output_multipliers(
let is_outer_join = rhs_table
.join_info
.as_ref()
.is_some_and(|join_info| join_info.is_outer());
if !is_outer_join {
let remaining_filter_selectivity = constraint_output_multipliers(
rhs_constraints,
lhs_mask,
rhs_mask,
&method.consumed_where_terms,
&Default::default(),
where_clause,
params,
);
return input_cardinality
* method.estimated_rows_per_outer_row
* remaining_filter_selectivity;
}
let is_on_term = |constraint: &super::constraints::Constraint| {
where_clause[constraint.where_clause_pos.0].from_outer_join == Some(rhs_table.internal_id)
};
let on_selectivity = constraint_output_multipliers_for(
rhs_constraints,
lhs_mask,
rhs_mask.clone(),
&method.consumed_where_terms,
&Default::default(),
where_clause,
params,
is_on_term,
);
let matching_rows_per_input = method.estimated_rows_per_outer_row * on_selectivity;
// Statistics give an average match count, but not its distribution.
// A Poisson model estimates the chance that an input row has no match.
let unmatched_probability = (-matching_rows_per_input).exp();
let outer_join_rows_per_input = matching_rows_per_input + unmatched_probability;
let selects_unmatched_rows = |constraint: &super::constraints::Constraint| {
if is_on_term(constraint)
|| !matches!(constraint.operator.as_ast_operator(), Some(Operator::Is))
{
return false;
}
matches!(
constraint.get_constraining_expr_ref(where_clause),
turso_parser::ast::Expr::Literal(turso_parser::ast::Literal::Null)
) && constraint.table_col_pos.is_some_and(|column_pos| {
rhs_table
.table
.get_column_at(column_pos)
.is_some_and(|column| column.is_rowid_alias() || column.notnull())
})
};
let selects_only_unmatched_rows = rhs_constraints.constraints.iter().any(|constraint| {
!method
.consumed_where_terms
.get(constraint.where_clause_pos.0)
&& selects_unmatched_rows(constraint)
});
let where_selectivity = constraint_output_multipliers_for(
rhs_constraints,
lhs_mask,
rhs_mask,
&method.consumed_where_terms,
&Default::default(),
where_clause,
params,
|constraint| !is_on_term(constraint) && !selects_unmatched_rows(constraint),
);
input_cardinality * method.estimated_rows_per_outer_row * remaining_filter_selectivity
let rows_per_input = if selects_only_unmatched_rows {
unmatched_probability
} else {
outer_join_rows_per_input
};
input_cardinality * rows_per_input * where_selectivity
}
/// Count calls to each subquery when all of its outer tables have been read.
@@ -212,6 +307,7 @@ fn count_subquery_calls_after_join(
new_table_mask.clone(),
&method.consumed_where_terms,
&skipped_where_terms,
where_clause,
params,
);
let rows = rows_before_filters * multiplier;
@@ -264,6 +360,7 @@ pub(super) fn count_subquery_calls_for_plan(
&prior_tables,
table_mask,
&joined_tables[*table_number],
where_clause,
params,
);
prior_tables.set(*table_number)?;
@@ -922,6 +1019,7 @@ fn join_lhs_and_rhs<'a>(
&lhs_mask,
rhs_self_mask,
&joined_tables[rhs_table_number],
where_clause,
params,
);

View File

@@ -36,6 +36,7 @@ log = "0.4.22"
assert_cmd = "^2"
rand_chacha = { workspace = true }
rand = { workspace = true }
serde_json = { workspace = true }
zerocopy = "0.8.26"
ctor = "0.5.0"
twox-hash = "2.1.1"

View File

@@ -1,11 +1,14 @@
use crate::common::{limbo_exec_rows, TempDatabase};
use rusqlite::types::Value;
use std::sync::Arc;
use turso_core::Connection;
const SCHEMA: [&str; 2] = [
"CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)",
"CREATE INDEX idx_users_age ON users(age)",
];
fn connect_with_schema(tmp_db: &TempDatabase) -> std::sync::Arc<turso_core::Connection> {
fn connect_with_schema(tmp_db: &TempDatabase) -> Arc<Connection> {
let conn = tmp_db.connect_limbo();
for ddl in SCHEMA {
limbo_exec_rows(&conn, ddl);
@@ -22,3 +25,200 @@ fn format_json_statement_reports_one_text_column(tmp_db: TempDatabase) -> anyhow
assert_eq!(stmt.get_column_decltype(0).as_deref(), Some("TEXT"));
Ok(())
}
#[turso_macros::test]
fn join_access_nodes_report_cost_and_row_estimates(tmp_db: TempDatabase) -> anyhow::Result<()> {
let conn = connect_with_schema(&tmp_db);
limbo_exec_rows(
&conn,
"CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER, total INTEGER)",
);
limbo_exec_rows(&conn, "CREATE INDEX idx_orders_user ON orders(user_id)");
let plan = explain_query_plan(
&conn,
"SELECT users.name, orders.total
FROM users JOIN orders ON orders.user_id = users.id
WHERE users.id = 1",
)?;
let access_nodes: Vec<_> = plan["nodes"]
.as_array()
.unwrap()
.iter()
.filter(|node| matches!(node["op"]["type"].as_str(), Some("scan" | "search")))
.collect();
assert_eq!(access_nodes.len(), 2);
assert_eq!(access_nodes[0]["op"]["estimate"]["input_rows"], 1.0);
for node in access_nodes {
let estimate = &node["op"]["estimate"];
assert!(estimate["rows_per_input"].as_f64().unwrap() > 0.0);
assert!(estimate["output_rows"].as_f64().unwrap() > 0.0);
assert!(estimate["access_cost"].as_f64().unwrap() > 0.0);
assert!(estimate["total_cost"].as_f64().unwrap() > 0.0);
}
Ok(())
}
#[turso_macros::test]
fn outer_join_null_test_estimates_unmatched_rows(tmp_db: TempDatabase) -> anyhow::Result<()> {
let conn = tmp_db.connect_limbo();
create_parent_child_data(&conn, "CREATE INDEX child_parent ON child(parent_id)");
let query = "SELECT parent.id
FROM parent
LEFT JOIN child ON child.parent_id = parent.id AND child.kind = 1
WHERE child.id IS NULL";
assert_eq!(limbo_exec_rows(&conn, query).len(), 90);
let plan = explain_query_plan(&conn, query)?;
let estimated_rows = final_output_rows(&plan);
assert!(
(80.0..99.0).contains(&estimated_rows),
"expected 80 to 99 rows, got {estimated_rows}"
);
Ok(())
}
#[turso_macros::test]
fn nullable_primary_key_null_test_keeps_matched_rows(tmp_db: TempDatabase) -> anyhow::Result<()> {
let conn = tmp_db.connect_limbo();
limbo_exec_rows(&conn, "CREATE TABLE parent (id INTEGER PRIMARY KEY)");
limbo_exec_rows(
&conn,
"CREATE TABLE child (
key TEXT PRIMARY KEY,
nullable_value TEXT,
parent_id INTEGER
)",
);
limbo_exec_rows(&conn, "CREATE INDEX child_parent ON child(parent_id)");
limbo_exec_rows(&conn, "INSERT INTO parent VALUES (1), (2)");
limbo_exec_rows(
&conn,
"INSERT INTO child VALUES (NULL, NULL, 1), ('two', 'two', 2)",
);
limbo_exec_rows(&conn, "ANALYZE");
let primary_key_plan = explain_query_plan(
&conn,
"SELECT parent.id
FROM parent LEFT JOIN child ON child.parent_id = parent.id
WHERE child.key IS NULL",
)?;
let nullable_column_plan = explain_query_plan(
&conn,
"SELECT parent.id
FROM parent LEFT JOIN child ON child.parent_id = parent.id
WHERE child.nullable_value IS NULL",
)?;
assert_eq!(
final_output_rows(&primary_key_plan),
final_output_rows(&nullable_column_plan)
);
Ok(())
}
#[turso_macros::test]
fn compound_join_lookup_estimates_its_constant_filter(tmp_db: TempDatabase) -> anyhow::Result<()> {
let conn = tmp_db.connect_limbo();
create_parent_child_data(
&conn,
"CREATE INDEX child_parent_kind ON child(parent_id, kind)",
);
let query = "SELECT parent.id
FROM parent CROSS JOIN child
WHERE child.parent_id = parent.id AND child.kind = 1";
assert_eq!(limbo_exec_rows(&conn, query).len(), 10);
let plan = explain_query_plan(&conn, query)?;
let child_estimate = plan["nodes"]
.as_array()
.unwrap()
.iter()
.find(|node| node["op"]["table"] == "child")
.map(|node| &node["op"]["estimate"])
.unwrap();
assert_eq!(child_estimate["input_rows"], 100.0);
let output_rows = child_estimate["output_rows"].as_f64().unwrap();
assert!(
(5.0..=20.0).contains(&output_rows),
"expected 5 to 20 rows, got {output_rows}"
);
Ok(())
}
#[turso_macros::test]
fn unavailable_duplicate_does_not_stop_a_compound_lookup(
tmp_db: TempDatabase,
) -> anyhow::Result<()> {
let conn = tmp_db.connect_limbo();
limbo_exec_rows(&conn, "CREATE TABLE first (a INTEGER, b INTEGER)");
limbo_exec_rows(&conn, "CREATE TABLE middle (x INTEGER, y INTEGER)");
limbo_exec_rows(&conn, "CREATE INDEX middle_xy ON middle(x, y)");
limbo_exec_rows(&conn, "CREATE TABLE last (z INTEGER)");
let plan = explain_query_plan(
&conn,
"SELECT *
FROM first CROSS JOIN middle CROSS JOIN last
WHERE middle.x = first.a
AND middle.x = last.z
AND middle.y = first.b",
)?;
let middle_constraints = plan["nodes"]
.as_array()
.unwrap()
.iter()
.find(|node| node["op"]["table"] == "middle")
.map(|node| node["op"]["constraints"].as_array().unwrap())
.unwrap();
assert_eq!(middle_constraints.len(), 2);
assert_eq!(middle_constraints[0], "x=?");
assert_eq!(middle_constraints[1], "y=?");
Ok(())
}
fn explain_query_plan(conn: &Arc<Connection>, query: &str) -> anyhow::Result<serde_json::Value> {
let rows = limbo_exec_rows(conn, &format!("EXPLAIN QUERY PLAN FORMAT=JSON {query}"));
let Value::Text(plan) = &rows[0][0] else {
panic!("query plan must be text");
};
Ok(serde_json::from_str(plan.as_str())?)
}
fn final_output_rows(plan: &serde_json::Value) -> f64 {
plan["nodes"]
.as_array()
.unwrap()
.iter()
.filter_map(|node| node["op"]["estimate"]["output_rows"].as_f64())
.next_back()
.unwrap()
}
fn create_parent_child_data(conn: &Arc<Connection>, index_sql: &str) {
limbo_exec_rows(conn, "CREATE TABLE parent (id INTEGER PRIMARY KEY)");
limbo_exec_rows(
conn,
"CREATE TABLE child (id INTEGER PRIMARY KEY, parent_id INTEGER, kind INTEGER)",
);
limbo_exec_rows(conn, index_sql);
let parent_values = (1..=100)
.map(|value| format!("({value})"))
.collect::<Vec<_>>()
.join(",");
let child_values = (1..=100)
.map(|value| {
let kind = if value <= 10 { 1 } else { 2 };
format!("({value},{value},{kind})")
})
.collect::<Vec<_>>()
.join(",");
limbo_exec_rows(conn, &format!("INSERT INTO parent VALUES {parent_values}"));
limbo_exec_rows(conn, &format!("INSERT INTO child VALUES {child_values}"));
limbo_exec_rows(conn, "ANALYZE");
}