|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +//! Plug refined cardinality estimation into the optimizer via the `StatisticsRegistry`. |
| 19 | +//! |
| 20 | +//! DataFusion's built-in statistics are intentionally simple defaults; the registry |
| 21 | +//! is the seam for plugging in more refined estimation (formulas or heuristics |
| 22 | +//! suited to your system or data) without changing the core. |
| 23 | +//! |
| 24 | +//! `(SELECT user_id FROM events WHERE amount < 50 GROUP BY user_id) JOIN dims`: a |
| 25 | +//! provider supplies the column stats a catalog knows (`amount` range, `user_id` |
| 26 | +//! distinct count); the built-in `FilterStatisticsProvider` then refines the |
| 27 | +//! post-filter distinct count with the survival formula |
| 28 | +//! `NDV * (1 - (1 - selectivity)^(rows / NDV))` (Yao/Cardenas) to ~32, below `dims` |
| 29 | +//! (48), flipping the join build side. Core's simpler `min(NDV, rows)` cap would |
| 30 | +//! give 50 (> 48) and keep the other order; the refinement is the point. The |
| 31 | +//! ground-truth query prints the true surviving distinct count (below 48), |
| 32 | +//! confirming the flip. |
| 33 | +
|
| 34 | +use std::sync::Arc; |
| 35 | + |
| 36 | +use datafusion::arrow::array::Int32Array; |
| 37 | +use datafusion::arrow::datatypes::{DataType, Field, Schema}; |
| 38 | +use datafusion::arrow::record_batch::RecordBatch; |
| 39 | +use datafusion::arrow::util::pretty::pretty_format_batches; |
| 40 | +use datafusion::catalog::MemTable; |
| 41 | +use datafusion::common::Result; |
| 42 | +use datafusion::common::ScalarValue; |
| 43 | +use datafusion::common::stats::Precision; |
| 44 | +use datafusion::execution::SessionStateBuilder; |
| 45 | +use datafusion::physical_plan::ExecutionPlan; |
| 46 | +use datafusion::physical_plan::operator_statistics::{ |
| 47 | + ClosureStatisticsProvider, ExtendedStatistics, StatisticsRegistry, StatisticsResult, |
| 48 | +}; |
| 49 | +use datafusion::physical_plan::statistics::StatisticsArgs; |
| 50 | +use datafusion::prelude::*; |
| 51 | +use rand::{Rng, SeedableRng, rngs::StdRng}; |
| 52 | + |
| 53 | +/// Matches the base `events` scan: a leaf carrying both `user_id` and `amount`. |
| 54 | +fn catalog_matches(plan: &dyn ExecutionPlan) -> bool { |
| 55 | + let schema = plan.schema(); |
| 56 | + plan.children().is_empty() |
| 57 | + && schema.index_of("user_id").is_ok() |
| 58 | + && schema.index_of("amount").is_ok() |
| 59 | +} |
| 60 | + |
| 61 | +/// Injects the catalog-known `amount` range (for filter selectivity) and |
| 62 | +/// `user_id` distinct count (for post-filter NDV) the in-memory table lacks. |
| 63 | +fn catalog_stats( |
| 64 | + plan: &dyn ExecutionPlan, |
| 65 | + _child_stats: &[ExtendedStatistics], |
| 66 | +) -> Result<StatisticsResult> { |
| 67 | + let schema = plan.schema(); |
| 68 | + let user_id = schema.index_of("user_id")?; |
| 69 | + let amount = schema.index_of("amount")?; |
| 70 | + let mut stats = (*plan.statistics_from_inputs(&[], &StatisticsArgs::new())?).clone(); |
| 71 | + stats.column_statistics[amount].min_value = |
| 72 | + Precision::Inexact(ScalarValue::Int32(Some(0))); |
| 73 | + stats.column_statistics[amount].max_value = |
| 74 | + Precision::Inexact(ScalarValue::Int32(Some(999))); |
| 75 | + stats.column_statistics[user_id].distinct_count = Precision::Inexact(100); |
| 76 | + Ok(StatisticsResult::Computed(ExtendedStatistics::new(stats))) |
| 77 | +} |
| 78 | + |
| 79 | +fn int_col(values: &[i32]) -> Arc<Int32Array> { |
| 80 | + Arc::new(Int32Array::from_iter_values(values.iter().copied())) |
| 81 | +} |
| 82 | + |
| 83 | +fn mem_table(fields: &[(&str, Arc<Int32Array>)]) -> Result<Arc<MemTable>> { |
| 84 | + let schema = Arc::new(Schema::new( |
| 85 | + fields |
| 86 | + .iter() |
| 87 | + .map(|(name, _)| Field::new(*name, DataType::Int32, false)) |
| 88 | + .collect::<Vec<_>>(), |
| 89 | + )); |
| 90 | + let cols = fields.iter().map(|(_, col)| Arc::clone(col) as _).collect(); |
| 91 | + let batch = RecordBatch::try_new(Arc::clone(&schema), cols)?; |
| 92 | + Ok(Arc::new(MemTable::try_new(schema, vec![vec![batch]])?)) |
| 93 | +} |
| 94 | + |
| 95 | +fn build_ctx(with_registry: bool) -> Result<SessionContext> { |
| 96 | + let config = SessionConfig::new() |
| 97 | + .with_target_partitions(4) |
| 98 | + .set_bool("datafusion.explain.physical_plan_only", true) |
| 99 | + .set_bool("datafusion.explain.show_statistics", true) |
| 100 | + // Force Partitioned hash joins so statistics alone drive the build side. |
| 101 | + .set_usize( |
| 102 | + "datafusion.optimizer.hash_join_single_partition_threshold", |
| 103 | + 1, |
| 104 | + ) |
| 105 | + .set_usize( |
| 106 | + "datafusion.optimizer.hash_join_single_partition_threshold_rows", |
| 107 | + 1, |
| 108 | + ); |
| 109 | + |
| 110 | + let mut builder = SessionStateBuilder::new() |
| 111 | + .with_config(config) |
| 112 | + .with_default_features(); |
| 113 | + if with_registry { |
| 114 | + let mut registry = StatisticsRegistry::default_with_builtin_providers(); |
| 115 | + registry.register(Arc::new(ClosureStatisticsProvider::with_matches( |
| 116 | + catalog_matches, |
| 117 | + catalog_stats, |
| 118 | + ))); |
| 119 | + builder = builder.with_statistics_registry(registry); |
| 120 | + } |
| 121 | + let ctx = SessionContext::new_with_state(builder.build()); |
| 122 | + |
| 123 | + let n = 1000i32; |
| 124 | + let user_ids: Vec<i32> = (0..n).map(|v| v % 100).collect(); |
| 125 | + // `amount` independent of `user_id` so the filter keeps a representative sample. |
| 126 | + let mut rng = StdRng::seed_from_u64(2024); |
| 127 | + let amounts: Vec<i32> = (0..n).map(|_| rng.random_range(0..1000)).collect(); |
| 128 | + ctx.register_table( |
| 129 | + "events", |
| 130 | + mem_table(&[ |
| 131 | + ("user_id", int_col(&user_ids)), |
| 132 | + ("amount", int_col(&amounts)), |
| 133 | + ])?, |
| 134 | + )?; |
| 135 | + ctx.register_table( |
| 136 | + "dims", |
| 137 | + mem_table(&[ |
| 138 | + ("user_id", int_col(&(0..48).collect::<Vec<_>>())), |
| 139 | + ("label", int_col(&(0..48).collect::<Vec<_>>())), |
| 140 | + ])?, |
| 141 | + )?; |
| 142 | + Ok(ctx) |
| 143 | +} |
| 144 | + |
| 145 | +const QUERY: &str = "SELECT e.user_id, d.label \ |
| 146 | + FROM (SELECT user_id FROM events WHERE amount < 50 GROUP BY user_id) e \ |
| 147 | + JOIN dims d ON e.user_id = d.user_id"; |
| 148 | + |
| 149 | +async fn explain(ctx: &SessionContext) -> Result<String> { |
| 150 | + let batches = ctx |
| 151 | + .sql(&format!("EXPLAIN {QUERY}")) |
| 152 | + .await? |
| 153 | + .collect() |
| 154 | + .await?; |
| 155 | + Ok(pretty_format_batches(&batches)?.to_string()) |
| 156 | +} |
| 157 | + |
| 158 | +pub async fn join_reorder() -> Result<()> { |
| 159 | + let truth_query = "SELECT count(DISTINCT user_id) AS true_distinct_users \ |
| 160 | + FROM events WHERE amount < 50"; |
| 161 | + println!("-- Ground truth --\n{truth_query}\n"); |
| 162 | + let truth = build_ctx(false)?.sql(truth_query).await?.collect().await?; |
| 163 | + println!("{}\n", pretty_format_batches(&truth)?); |
| 164 | + |
| 165 | + println!("-- Query --\n{QUERY}\n"); |
| 166 | + println!( |
| 167 | + "A hash join builds its in-memory hash table from one input and probes with\n\ |
| 168 | + the other, so the smaller input should be the build side. Default estimation\n\ |
| 169 | + sizes the grouped `events` at 1000 rows and builds from `dims`; the\n\ |
| 170 | + registry's refined ~32 estimate is below `dims` (48 rows), so it flips the\n\ |
| 171 | + build side to `events`. The ground-truth count above (also below 48)\n\ |
| 172 | + confirms `events` really is the smaller, cheaper side.\n" |
| 173 | + ); |
| 174 | + println!("-- Without the registry (default estimation) --"); |
| 175 | + println!("{}\n", explain(&build_ctx(false)?).await?); |
| 176 | + println!("-- With the registry (built-in refinement) --"); |
| 177 | + println!("{}", explain(&build_ctx(true)?).await?); |
| 178 | + Ok(()) |
| 179 | +} |
0 commit comments