You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "asolimando (via GitHub)" <gi...@apache.org> on 2026/03/23 18:03:55 UTC
[PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
asolimando opened a new pull request, #21122:
URL: https://github.com/apache/datafusion/pull/21122
## Which issue does this PR close?
Part of #21120 (framework + projection/filter integration)
## Rationale for this change
DataFusion currently loses expression-level statistics when computing plan metadata. Projected expressions that aren't bare columns or literals get unknown statistics, and filter selectivity falls back to a hardcoded 20% when interval analysis cannot handle the predicate. There is also no extension point for users to provide statistics for their own UDFs.
This PR introduces ExpressionAnalyzer, a pluggable chain-of-responsibility framework that addresses these gaps. It follows the same extensibility pattern used elsewhere in DataFusion (ExprPlanner, OptimizerRule).
Addresses reviewer feedback from #19957: chain delegation, SessionState integration, own folder.
## What changes are included in this PR?
- `ExpressionAnalyzer` trait with `registry` parameter for chain delegation
- `ExpressionAnalyzerRegistry` to chain analyzers (first `Computed` wins)
- `DefaultExpressionAnalyzer`: Selinger-style estimation for columns, literals, binary expressions (AND/OR/NOT/comparisons), arithmetic
- `ExpressionAnalyzerRegistry` stored in `SessionState`, injected into `ProjectionExec` and `FilterExec` by the planner
- `ProjectionExprs` uses registry to estimate NDV, min/max, and null fraction through projected expressions
- `FilterExec` uses registry selectivity as fallback when `check_support` returns false
- Config option `optimizer.enable_expression_analyzer` (default false) to opt in; zero behavior change when disabled
- Limitation: projections/filters created by optimizer rules after planning do not receive the registry and fall back to upstream behavior. Full coverage requires an operator-level statistics registry (orthogonal, will be tracked separately).
## Are these changes tested?
- 15 unit tests for ExpressionAnalyzer (NDV, selectivity, min/max, null fraction, custom analyzers, chain delegation)
- 31 projection tests (including new `test_project_statistics_with_expression_analyzer`)
- 26 filter tests
- 7 session state tests
## Are there any user-facing changes?
New public API (purely additive, non-breaking):
- `ExpressionAnalyzer` trait and `ExpressionAnalyzerRegistry` in `datafusion-physical-expr`
- `SessionState::expression_analyzer_registry()` getter
- `SessionStateBuilder::with_expression_analyzer_registry()` setter
- `ProjectionExprs::with_expression_analyzer_registry()` setter
- `FilterExecBuilder::with_expression_analyzer_registry()` setter
- `ProjectionExec::with_expression_analyzer_registry()` setter
- Config option `datafusion.optimizer.enable_expression_analyzer`
No breaking changes. Default behavior is unchanged (config defaults to false).
---
Disclaimer: I used AI to assist in the code generation, I have manually reviewed the output and it matches my intention and understanding.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3093883429
##########
datafusion/core/src/physical_planner.rs:
##########
@@ -2769,15 +2771,30 @@ impl DefaultPhysicalPlanner {
// to verify that the plan fulfills the base requirements.
InvariantChecker(InvariantLevel::Always).check(&plan)?;
+ let use_expression_analyzer = session_state
+ .config_options()
+ .optimizer
+ .use_expression_analyzer;
let mut new_plan = Arc::clone(&plan);
for optimizer in optimizers {
let before_schema = new_plan.schema();
+ let plan_before_rule = Arc::clone(&new_plan);
new_plan = optimizer
.optimize_with_context(new_plan, session_state)
.map_err(|e| {
DataFusionError::Context(optimizer.name().to_string(), Box::new(e))
})?;
+ // Re-inject ExpressionAnalyzer registry into any exec nodes created or replaced by
+ // this rule. Skip if the rule returned the same plan unchanged to
+ // avoid an O(nodes) walk for no-op rules.
+ if use_expression_analyzer && !Arc::ptr_eq(&plan_before_rule, &new_plan) {
Review Comment:
Addressed as 1. in https://github.com/apache/datafusion/pull/21122#discussion_r3093089736
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4171709705
@2010YOUY01: FYI I took a final pass on the PR and marked it as "reviewable"
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3025779809
##########
datafusion/physical-expr/src/projection.rs:
##########
@@ -713,9 +745,35 @@ impl ProjectionExprs {
byte_size,
}
}
+ } else if let Some(registry) = &self.expression_analyzer_registry {
Review Comment:
I think there is a subtle ordering issue here. `project_statistics` asks the registry for derived expression stats after earlier bare-column projections have already taken their source column stats out of `stats.column_statistics`.
That makes estimation order dependent. For example, with `[a, a + 1]`, we preserve stats for `a`, but then lose them for `a + 1` because the analyzer now sees column 0 as unknown.
Would it make sense to keep an immutable copy of the input stats for analyzer lookups, or defer the `take`, so later expressions can still see the original column metadata?
##########
datafusion/physical-expr/src/expression_analyzer/default.rs:
##########
@@ -0,0 +1,285 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Default expression analyzer with Selinger-style estimation.
+
+use std::sync::Arc;
+
+use datafusion_common::{ColumnStatistics, ScalarValue, Statistics};
+use datafusion_expr::Operator;
+
+use crate::PhysicalExpr;
+use crate::expressions::{BinaryExpr, Column, Literal, NotExpr};
+
+use super::{AnalysisResult, ExpressionAnalyzer, ExpressionAnalyzerRegistry};
+
+/// Default expression analyzer with Selinger-style estimation.
+///
+/// Handles common expression types:
+/// - Column references (uses column statistics)
+/// - Binary expressions (AND, OR, comparison operators)
+/// - Literals (constant selectivity/NDV)
+/// - NOT expressions (1 - child selectivity)
+#[derive(Debug, Default, Clone)]
+pub struct DefaultExpressionAnalyzer;
+
+impl DefaultExpressionAnalyzer {
+ /// Get column index from a Column expression
+ fn get_column_index(expr: &Arc<dyn PhysicalExpr>) -> Option<usize> {
+ expr.as_any().downcast_ref::<Column>().map(|c| c.index())
+ }
+
+ /// Get column statistics for an expression if it's a column reference
+ fn get_column_stats<'a>(
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &'a Statistics,
+ ) -> Option<&'a ColumnStatistics> {
+ Self::get_column_index(expr)
+ .and_then(|idx| input_stats.column_statistics.get(idx))
+ }
+
+ /// Recursive selectivity estimation through the registry chain
+ fn estimate_selectivity_recursive(
+ &self,
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &Statistics,
+ registry: &ExpressionAnalyzerRegistry,
+ ) -> f64 {
+ registry.get_selectivity(expr, input_stats).unwrap_or(0.5)
+ }
+}
+
+impl ExpressionAnalyzer for DefaultExpressionAnalyzer {
+ fn get_selectivity(
+ &self,
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &Statistics,
+ registry: &ExpressionAnalyzerRegistry,
+ ) -> AnalysisResult<f64> {
+ // Binary expressions: AND, OR, comparisons
+ if let Some(binary) = expr.as_any().downcast_ref::<BinaryExpr>() {
+ let sel = match binary.op() {
+ // Logical operators: need child selectivities
+ Operator::And => {
+ let left_sel = self.estimate_selectivity_recursive(
+ binary.left(),
+ input_stats,
+ registry,
+ );
+ let right_sel = self.estimate_selectivity_recursive(
+ binary.right(),
+ input_stats,
+ registry,
+ );
+ left_sel * right_sel
+ }
+ Operator::Or => {
+ let left_sel = self.estimate_selectivity_recursive(
+ binary.left(),
+ input_stats,
+ registry,
+ );
+ let right_sel = self.estimate_selectivity_recursive(
+ binary.right(),
+ input_stats,
+ registry,
+ );
+ left_sel + right_sel - (left_sel * right_sel)
+ }
+
+ // Equality: selectivity = 1/NDV
+ Operator::Eq => {
+ let ndv = Self::get_column_stats(binary.left(), input_stats)
+ .or_else(|| Self::get_column_stats(binary.right(), input_stats))
+ .and_then(|s| s.distinct_count.get_value())
+ .filter(|&&ndv| ndv > 0);
+ if let Some(ndv) = ndv {
+ return AnalysisResult::Computed(1.0 / (*ndv as f64));
+ }
+ 0.1 // Default equality selectivity
+ }
+
+ // Inequality: selectivity = 1 - 1/NDV
+ Operator::NotEq => {
+ let ndv = Self::get_column_stats(binary.left(), input_stats)
+ .or_else(|| Self::get_column_stats(binary.right(), input_stats))
+ .and_then(|s| s.distinct_count.get_value())
+ .filter(|&&ndv| ndv > 0);
+ if let Some(ndv) = ndv {
+ return AnalysisResult::Computed(1.0 - (1.0 / (*ndv as f64)));
+ }
+ 0.9
+ }
+
+ // Range predicates: classic 1/3 estimate
+ Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq => 0.33,
+
+ // LIKE: depends on pattern, use conservative estimate
+ Operator::LikeMatch | Operator::ILikeMatch => 0.25,
+ Operator::NotLikeMatch | Operator::NotILikeMatch => 0.75,
+
+ // Other operators: default
+ _ => 0.5,
+ };
+
+ return AnalysisResult::Computed(sel);
+ }
+
+ // NOT expression: 1 - child selectivity
+ if let Some(not_expr) = expr.as_any().downcast_ref::<NotExpr>() {
+ let child_sel = self.estimate_selectivity_recursive(
+ not_expr.arg(),
+ input_stats,
+ registry,
+ );
+ return AnalysisResult::Computed(1.0 - child_sel);
+ }
+
+ // Literal boolean: 0.0 or 1.0
+ if let Some(b) = expr
+ .as_any()
+ .downcast_ref::<Literal>()
+ .and_then(|lit| match lit.value() {
+ ScalarValue::Boolean(Some(b)) => Some(*b),
+ _ => None,
+ })
+ {
+ return AnalysisResult::Computed(if b { 1.0 } else { 0.0 });
+ }
+
+ // Column reference as predicate (boolean column)
+ if expr.as_any().downcast_ref::<Column>().is_some() {
+ return AnalysisResult::Computed(0.5);
+ }
+
+ AnalysisResult::Delegate
+ }
+
+ fn get_distinct_count(
+ &self,
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &Statistics,
+ registry: &ExpressionAnalyzerRegistry,
+ ) -> AnalysisResult<usize> {
+ // Column reference: use column NDV
+ if let Some(ndv) = Self::get_column_stats(expr, input_stats)
+ .and_then(|col_stats| col_stats.distinct_count.get_value().copied())
+ {
+ return AnalysisResult::Computed(ndv);
+ }
+
+ // Literal: NDV = 1
+ if expr.as_any().downcast_ref::<Literal>().is_some() {
+ return AnalysisResult::Computed(1);
+ }
+
+ // BinaryExpr: for arithmetic with a literal operand, treat as injective
Review Comment:
This looks a bit broader than the comment suggests. Treating every arithmetic-with-literal expression as injective might be risky.
Cases like `col * 0`, integer `col / 2`, or especially `col % 10` can reduce NDV quite a lot, so returning the input NDV could overshoot.
Maybe we could narrow this to clearly safe cases first, like `+` or `-` with literals, and possibly `*` by non-zero constants for floating types. Alternatively, adding a few regression tests to document the intended approximation range could also help.
##########
datafusion/physical-expr/src/expression_analyzer/default.rs:
##########
@@ -0,0 +1,285 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Default expression analyzer with Selinger-style estimation.
+
+use std::sync::Arc;
+
+use datafusion_common::{ColumnStatistics, ScalarValue, Statistics};
+use datafusion_expr::Operator;
+
+use crate::PhysicalExpr;
+use crate::expressions::{BinaryExpr, Column, Literal, NotExpr};
+
+use super::{AnalysisResult, ExpressionAnalyzer, ExpressionAnalyzerRegistry};
+
+/// Default expression analyzer with Selinger-style estimation.
+///
+/// Handles common expression types:
+/// - Column references (uses column statistics)
+/// - Binary expressions (AND, OR, comparison operators)
+/// - Literals (constant selectivity/NDV)
+/// - NOT expressions (1 - child selectivity)
+#[derive(Debug, Default, Clone)]
+pub struct DefaultExpressionAnalyzer;
+
+impl DefaultExpressionAnalyzer {
+ /// Get column index from a Column expression
+ fn get_column_index(expr: &Arc<dyn PhysicalExpr>) -> Option<usize> {
+ expr.as_any().downcast_ref::<Column>().map(|c| c.index())
+ }
+
+ /// Get column statistics for an expression if it's a column reference
+ fn get_column_stats<'a>(
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &'a Statistics,
+ ) -> Option<&'a ColumnStatistics> {
+ Self::get_column_index(expr)
+ .and_then(|idx| input_stats.column_statistics.get(idx))
+ }
+
+ /// Recursive selectivity estimation through the registry chain
+ fn estimate_selectivity_recursive(
+ &self,
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &Statistics,
+ registry: &ExpressionAnalyzerRegistry,
+ ) -> f64 {
+ registry.get_selectivity(expr, input_stats).unwrap_or(0.5)
+ }
+}
+
+impl ExpressionAnalyzer for DefaultExpressionAnalyzer {
+ fn get_selectivity(
+ &self,
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &Statistics,
+ registry: &ExpressionAnalyzerRegistry,
+ ) -> AnalysisResult<f64> {
+ // Binary expressions: AND, OR, comparisons
+ if let Some(binary) = expr.as_any().downcast_ref::<BinaryExpr>() {
+ let sel = match binary.op() {
+ // Logical operators: need child selectivities
+ Operator::And => {
+ let left_sel = self.estimate_selectivity_recursive(
+ binary.left(),
+ input_stats,
+ registry,
+ );
+ let right_sel = self.estimate_selectivity_recursive(
+ binary.right(),
+ input_stats,
+ registry,
+ );
+ left_sel * right_sel
+ }
+ Operator::Or => {
+ let left_sel = self.estimate_selectivity_recursive(
+ binary.left(),
+ input_stats,
+ registry,
+ );
+ let right_sel = self.estimate_selectivity_recursive(
+ binary.right(),
+ input_stats,
+ registry,
+ );
+ left_sel + right_sel - (left_sel * right_sel)
+ }
+
+ // Equality: selectivity = 1/NDV
+ Operator::Eq => {
+ let ndv = Self::get_column_stats(binary.left(), input_stats)
Review Comment:
Right now the equality selectivity path only looks at direct column statistics from the left and right children. That means predicates whose NDV is available through another analyzer still fall back to `0.1`.
For example, `(a + 1) = 42` or `my_udf(a) = 42` would not benefit from the new pluggable NDV estimation, even though `get_distinct_count` could derive it.
Would it be reasonable to call `registry.get_distinct_count(...)` on the non-literal side here? That would let the new framework actually improve selectivity for transformed expressions and UDFs.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3093089736
##########
datafusion/physical-plan/src/operator_statistics/mod.rs:
##########
@@ -782,9 +779,16 @@ impl StatisticsProvider for JoinStatisticsProvider {
return Ok(StatisticsResult::Delegate);
};
- use crate::joins::JoinOnRef;
+ let default_analyzer;
+ let analyzer = match plan.expression_analyzer_registry() {
Review Comment:
Thanks @kosiew, I have addressed both points in the latest two commits:
1. initial injection gap: my first idea was that if no rule ever modifies the plan, we might not need the injection step, but injecting before the optimizer loop is more consistent and safer, so I have added it
2. `JoinStatisticsProvider` config bypass: I have removed the fresh creation of `ExpressionAnalyzerRegistry` which was indeed violating the contract of the `use_expression_analyzer` config flag. The provider now uses the injected registry when present, and falls back to direct `ColumnStatistics` lookup for bare column keys when not (preserving the behavior as of #21483 when `use_expression_analyzer` is false, as expected).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4401819277
FWIW here is a PR to deprecate the "V2" statistics framework
- https://github.com/apache/datafusion/pull/22071
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-5966831118
Thank you! It's always been on my list, though I've had some trouble allocating enough time to it.
I'll share some partial feedback next week, and plan to focus on this project more deeply at some point later.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3046225207
##########
datafusion/core/src/physical_planner.rs:
##########
@@ -2898,7 +2920,11 @@ impl DefaultPhysicalPlanner {
.into_iter()
.map(|(expr, alias)| ProjectionExpr { expr, alias })
.collect();
- Ok(Arc::new(ProjectionExec::try_new(proj_exprs, input_exec)?))
+ let mut proj_exec = ProjectionExec::try_new(proj_exprs, input_exec)?;
Review Comment:
@kosiew: this is a known limitation under the constraint of avoiding breaking changes entirely in this first PR: only the planner has access to `SessionState`, so operator nodes created later by optimizer rules don't receive the registry. The idea was to lift the limitation via an operator-level statistics registry (see #21443, which would be the second and final part of the pluggable design for statistics).
The limitation is documented in [`ProjectionExprs::with_expression_analyzer_registry`](https://github.com/apache/datafusion/pull/21122/files#diff-0a88c8919b631d43ef9be55ec2811b3ed23ec966cef8aff9786c1f1650a3d5b4R201) and [`FilterExecBuilder::with_expression_analyzer_registry`](https://github.com/apache/datafusion/pull/21122/files#diff-ae492510820d46b07e2d7420f4555fcb005408682bf3e8aed85faad7925d4545R185).
Apologies for having you figure it out independently, I should have called this out more prominently in the PR description rather than only in code comments.
If you see a better way to propagate the registry that I might have overlooked or if you think a breaking change is the right call here, I'd be happy to hear more about that.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3029380453
##########
datafusion/physical-expr/src/projection.rs:
##########
@@ -713,9 +745,35 @@ impl ProjectionExprs {
byte_size,
}
}
+ } else if let Some(registry) = &self.expression_analyzer_registry {
Review Comment:
I have also added a couple of tests in that same commit, failing for the previous implementation, and passing now with the fix you have suggested.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4288222752
> Thanks @asolimando!
>
> The algorithmic contribution is genuinely useful, and thanks for your patience in keeping at it.
>
> But the registry-injection plumbing adds three permanent `ExecutionPlan` trait methods and five struct fields to work around a missing parameter that #20184 is poised to add properly.
>
> Before landing, I'd want alignment on whether to (a) wait for #20184 and land this on top of a `StatisticsContext` parameter, or (b) accept the injection design as a permanent API surface
Thanks @xudong963 for your thoughtful feedback, the injection design was meant as a stepping stone, not a permanent API surface, and I totally agree that adding the `StatisticsContext` parameter is the right long term solution, buying us freedom to provide an even richer context in the future. I wanted to mark the new trait methods as "experimental" but I couldn't find a proper mechanism for that in DataFusion.
Re. (b), I was under the impression that #20184 might land pretty soon, so I was basically counting on rebasing before finalizing, or shortly after, as breaking changes within the same unreleased version are generally tolerated, but if the timeline to merge #20184 is uncertain, (b) might not be ideal.
The cons of (a) is the risk of conflicts requiring to force-push, making it harder for reviewers to check incrementally.
In case it makes your decision easier, I can commit on helping with #20184's implementation, under both scenarios, if the current assignee is busy.
WDYT?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3092441214
##########
datafusion/core/src/physical_planner.rs:
##########
@@ -2769,15 +2771,30 @@ impl DefaultPhysicalPlanner {
// to verify that the plan fulfills the base requirements.
InvariantChecker(InvariantLevel::Always).check(&plan)?;
+ let use_expression_analyzer = session_state
+ .config_options()
+ .optimizer
+ .use_expression_analyzer;
let mut new_plan = Arc::clone(&plan);
for optimizer in optimizers {
let before_schema = new_plan.schema();
+ let plan_before_rule = Arc::clone(&new_plan);
new_plan = optimizer
.optimize_with_context(new_plan, session_state)
.map_err(|e| {
DataFusionError::Context(optimizer.name().to_string(), Box::new(e))
})?;
+ // Re-inject ExpressionAnalyzer registry into any exec nodes created or replaced by
+ // this rule. Skip if the rule returned the same plan unchanged to
+ // avoid an O(nodes) walk for no-op rules.
+ if use_expression_analyzer && !Arc::ptr_eq(&plan_before_rule, &new_plan) {
Review Comment:
I looked at the registry injection behavior and I agree the situation is better than it first appeared. Since `inject_expression_analyzer` walks the whole tree via `transform_up` whenever any optimizer rule changes the plan, nodes created earlier do end up getting the registry in most cases.
That said, there is still a narrow gap. If every physical optimizer rule is a no-op, the injection pass never runs, and planner-built nodes remain without a registry. This is probably rare in practice, but it does mean the behavior still depends slightly on whether any rule fires.
It would be good to either close this gap entirely or document that this edge case exists so the behavior is easier to reason about.
##########
datafusion/physical-plan/src/operator_statistics/mod.rs:
##########
@@ -782,9 +779,16 @@ impl StatisticsProvider for JoinStatisticsProvider {
return Ok(StatisticsResult::Delegate);
};
- use crate::joins::JoinOnRef;
+ let default_analyzer;
+ let analyzer = match plan.expression_analyzer_registry() {
Review Comment:
I think there is a small mismatch between the intended behavior and what is implemented for joins. The aggregate path does delegate when no registry is present, which matches the description. However, `JoinStatisticsProvider` creates a fresh `ExpressionAnalyzerRegistry::new()` when none is found.
That effectively enables expression-based NDV estimation for joins even when the planner did not inject a registry, and even if `use_expression_analyzer` is false as long as `use_statistics_registry` is true. So this is not purely additive and it bypasses the usual config gate and the expectation that analyzers come from exec nodes.
It would be good to align this with the aggregate behavior or clarify the intended contract, since right now joins behave differently in a way that may surprise users.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4574439406
@2010YOUY01, thank you for the thoughtful analysis, the distribution perspective is indeed a valuable perspective I haven't considered yet.
I see the distribution assumption differently though: at the base table level the underlying distribution can be known precisely (e.g., from KLL sketches or histograms), but after the first layer of propagation it's already an approximation. I think the distribution belongs in the API request rather than as metadata propagated through the tree. Different consumers want different assumptions for the same expression, e.g., sizing a hash table to avoid OOMs wants the worst case (uniform, highest NDV), while join ordering might want a more conservative estimate. This is also why I think Stats V2 had the right intuition but the wrong model, propagating distribution objects treats an assumption as a fact.
In the framework I had in mind, different distribution assumptions would be different provider implementations. But since different callers want different assumptions for the same expression, the hint should be per-call. The way I see this, would be an extra optional parameter, something like:
```rust
fn estimate_distinct_count(
&self,
input_stats: &Statistics,
ctx: &StatisticsContext,
hint: Option<&DistributionHint>, // None = uniform
) -> Option<usize> { None }
```
This also reinforces keeping methods separate: different consumers ask for different stats under different assumptions, and a unified `analyze()` would conflate these independent concerns.
Regarding lazy computation of stats more broadly, I think #22300 is the right way forward, it introduces granular statistics requests at the `TableProvider` level. It's related but at a different layer (scan-level vs expression-level). I will follow this under the same epic (#21120).
Does this match your understanding? Happy to continue this discussion in the `PhysicalExpr` extension PR, once #21815 lands.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4281177663
> This looks good to me. Looking forward to approving this after merge conflict is resolved.
Thanks @kosiew, I have resolved the conflicts and force-pushed again, mechanical fixes only.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3050242932
##########
datafusion/core/src/physical_planner.rs:
##########
@@ -2898,7 +2920,11 @@ impl DefaultPhysicalPlanner {
.into_iter()
.map(|(expr, alias)| ProjectionExpr { expr, alias })
.collect();
- Ok(Arc::new(ProjectionExec::try_new(proj_exprs, input_exec)?))
+ let mut proj_exec = ProjectionExec::try_new(proj_exprs, input_exec)?;
Review Comment:
@asolimando
Thanks for the detailed explanation. I understand the non-breaking-change constraint here, and the code comments on `ProjectionExprs::with_expression_analyzer_registry` / `FilterExecBuilder::with_expression_analyzer_registry` do make the current boundary clearer. I still think this remains a blocking limitation for the PR as it stands, though, because the feature is exposed behind `datafusion.optimizer.enable_expression_analyzer = true` yet its effect still depends on whether later physical rewrites rebuild the operator. Several common paths still create fresh `ProjectionExec::try_new(...)` nodes without a registry (`datafusion/physical-plan/src/projection.rs`, `datafusion/physical-optimizer/src/projection_pushdown.rs`, `datafusion/physical-optimizer/src/aggregate_statistics.rs`, etc.), so expression stats revert to `unknown` after optimization.
If carrying the registry through optimizer-created operators is not possible in this PR without the broader operator-level design from `#21443`, I think the safer options would be either:
- narrow the current scope/docs so users do not read this as generally-enabled projection/filter expression analysis across the final physical plan, or
- treat the operator-level propagation work as required before we rely on this config as a general optimizer feature.
I do not have a clean non-breaking propagation approach to suggest beyond the operator-level registry direction you mentioned, but I wanted to be explicit that I still see the current plan-shape dependency as an unresolved product/correctness concern rather than just a documentation gap.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3077948333
##########
datafusion/core/src/physical_planner.rs:
##########
@@ -2898,7 +2920,11 @@ impl DefaultPhysicalPlanner {
.into_iter()
.map(|(expr, alias)| ProjectionExpr { expr, alias })
.collect();
- Ok(Arc::new(ProjectionExec::try_new(proj_exprs, input_exec)?))
+ let mut proj_exec = ProjectionExec::try_new(proj_exprs, input_exec)?;
Review Comment:
hi @asolimando
I'll take a look again after you incorporate the merged #21483.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4491522282
> Thank you so much for pushing the staistics forward @asolimando -- this is an area that has been long overdue for improvement. Akso thank you for helping @xudong963
>
> I am sorry for the delay in reviewing this PR as well
Thank you for finding the time and to the many people who helped so far with discussions and reviews, I really appreciate it and, as a maintainer myself, I know how much time and effort it takes.
> I think the core abstraction for `ExpressionAnalyzerRegistry` makes sense here as a way to extend analysis, but I think the plumbing is a bit unwieldy (I left a more detailed comment inline0
I have replied inline, the status quo was meant to be temporary, after https://github.com/apache/datafusion/pull/21815 the integration will be easier and this will allow me to simplify the design along the lines you have suggested.
> Other thoughts:
>
> ## Statistics V2
> 1. This PR seems like it is not using the new statistics framework introduced in #14699 (which is fine, but I think I may make a PR proposing to deprecate that code to make it clear)
I saw the PR for deprecation, makes sense to me.
> ## "Motivating Example" / Usecase
> It would help me evaluate these APIs to see a "motivating example" in the examples crate. Examples make sure we are building an API that is useable for the desired usecase (and it has the bonus of providing documentation for others)
>
> Specifically in this case I think that example would be a program written from an user point of view where the system wants to plug in its own statistics framework. For example, it has some way to know what the cardinality of `join_key=12345` is based on its own statistics) and maybe wants to customize the JoinNode or something
>
> This approach really helped me with the API for custom indexes. Here is what I did for that: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/data_io/parquet_embedded_index.rs
>
> With a motivating example like this
@alamb, that's a great suggestion. I think the right motivating example for `ExpressionAnalyzer` specifically could involve an expression like `a + 1`, injective, for which today we return `Absent`, or a custom UDF scenario, similarly unsupported today.
The "external cardinality for join keys" use case you mentioned (knowing `join_key=12345` matches N rows) is more naturally a `StatisticsRegistry` concern (operator-level, PR #21483) than an `ExpressionAnalyzer` one (expression-level NDV/selectivity).
The operator and expression level statistics are ultimately one and the same concept, so it would probably make sense to build an example that shows both working together, but I can keep them separate if you prefer.
When https://github.com/apache/datafusion/pull/21815 gets finalized I will rebase this PR, rework the points discussed in the inlined comments, and propose an end-to-end example as you suggested.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3286774613
##########
datafusion/physical-expr/src/expression_analyzer/mod.rs:
##########
@@ -0,0 +1,283 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Pluggable expression-level statistics analysis.
+//!
+//! This module provides an extensible mechanism for computing expression-level
+//! statistics metadata (selectivity, NDV, min/max bounds) following the chain
+//! of responsibility pattern.
+//!
+//! # Overview
+//!
+//! Different expressions have different statistical properties:
+//!
+//! - **Injective functions** (UPPER, LOWER, ABS on non-negative): preserve NDV
+//! - **Non-injective functions** (FLOOR, YEAR, SUBSTRING): reduce NDV
+//! - **Monotonic functions**: allow min/max bound propagation
+//! - **Constants**: NDV = 1, selectivity depends on value
+//!
+//! The default implementation uses classic Selinger-style estimation. Users can
+//! register custom [`ExpressionAnalyzer`] implementations to:
+//!
+//! 1. Provide statistics for custom UDFs
+//! 2. Override default estimation with domain-specific knowledge
+//! 3. Plug in advanced approaches (e.g., histogram-based estimation)
+//!
+//! # Example
+//!
+//! ```ignore
+//! use datafusion_physical_expr::expression_analyzer::*;
+//!
+//! // Create registry with default analyzer
+//! let mut registry = ExpressionAnalyzerRegistry::new();
+//!
+//! // Register custom analyzer (higher priority)
+//! registry.register(Arc::new(MyCustomAnalyzer));
+//!
+//! // Query expression statistics
+//! let selectivity = registry.get_selectivity(&predicate, &input_stats);
+//! ```
+
+mod default;
+
+#[cfg(test)]
+mod tests;
+
+pub use default::DefaultExpressionAnalyzer;
+
+use std::fmt::Debug;
+use std::sync::Arc;
+
+use datafusion_common::{ScalarValue, Statistics};
+
+use crate::PhysicalExpr;
+
+/// Result of expression analysis - either computed or delegate to next analyzer.
+#[derive(Debug, Clone)]
+pub enum AnalysisResult<T> {
+ /// Analysis was performed, here's the result
+ Computed(T),
+ /// This analyzer doesn't handle this expression; delegate to next
+ Delegate,
+}
+
+/// Expression-level metadata analysis.
+///
+/// Implementations can handle specific expression types or provide domain
+/// knowledge for custom UDFs. The chain of analyzers is traversed until one
+/// returns [`AnalysisResult::Computed`].
+///
+/// The `registry` parameter allows analyzers to delegate sub-expression
+/// analysis back through the full chain, rather than hard-coding a specific
+/// analyzer. For example, a function analyzer can ask the registry for the
+/// NDV of its input argument, which will traverse the full chain (including
+/// any custom analyzers the user registered).
+///
+/// # Implementing a Custom Analyzer
+///
+/// ```ignore
+/// #[derive(Debug)]
+/// struct MyUdfAnalyzer;
+///
+/// impl ExpressionAnalyzer for MyUdfAnalyzer {
+/// fn get_selectivity(
+/// &self,
+/// expr: &Arc<dyn PhysicalExpr>,
+/// input_stats: &Statistics,
+/// registry: &ExpressionAnalyzerRegistry,
+/// ) -> AnalysisResult<f64> {
+/// // Recognize my custom is_valid_email() UDF
+/// if is_my_email_validator(expr) {
+/// return AnalysisResult::Computed(0.8); // ~80% valid
+/// }
+/// AnalysisResult::Delegate
+/// }
+/// }
+/// ```
+pub trait ExpressionAnalyzer: Debug + Send + Sync {
Review Comment:
I think we could unify those APIs to a single one
```
pub trait ExpressionAnalyzer {
fn analyze(...) -> AnalyzeResult<ExpressionAnalysis>
}
pub enum ExpressionAnalysis {
Predicate(PredicateStats),
Value(ExprStats),
}
pub struct PredicateStats {
pub selectivity: f64,
}
#[derive(Default, Clone)]
pub struct ExprStats {
pub distinct_count: Option<usize>,
pub min_max: Option<(ScalarValue, ScalarValue)>,
pub null_fraction: Option<f64>,
}
```
The reasons are
- Type safety, for example `get_selectivity(a+1)` should return error, the enum approach can handle that easier
- Potentially cleaner -- if this registry grow large, we might want to stat propagation for a single function to stay close to each other. Also I suspect there might be some advanced stat type has to consider several other existing stat type to infer the output, so grouping the stat type can also be useful 🤔
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4308096402
> > In case it makes your decision easier, I can commit on helping with #20184's implementation, under both scenarios, if the current assignee is busy.
>
> Yes, please. If the current assignee is busy, taking that on is probably the fastest path to unblocking this PR in its final form. Happy to review on that side too. Also cc @jonathanc-n
>
> I also want to hear some suggestions from @alamb about the next step!
Hey @xudong963, I have opened https://github.com/apache/datafusion/pull/21815 to close #20184 as requested (I will ping you there too)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3046225207
##########
datafusion/core/src/physical_planner.rs:
##########
@@ -2898,7 +2920,11 @@ impl DefaultPhysicalPlanner {
.into_iter()
.map(|(expr, alias)| ProjectionExpr { expr, alias })
.collect();
- Ok(Arc::new(ProjectionExec::try_new(proj_exprs, input_exec)?))
+ let mut proj_exec = ProjectionExec::try_new(proj_exprs, input_exec)?;
Review Comment:
This is a known limitation under the constraint of avoiding breaking changes entirely in this first PR: only the planner has access to `SessionState`, so operator nodes created later by optimizer rules don't receive the registry. The idea was to lift the limitation via an operator-level statistics registry (see #21443, which would be the second and final part of the pluggable design for statistics).
The limitation is documented in [`ProjectionExprs::with_expression_analyzer_registry`](https://github.com/apache/datafusion/pull/21122/files#diff-0a88c8919b631d43ef9be55ec2811b3ed23ec966cef8aff9786c1f1650a3d5b4R201) and [`FilterExecBuilder::with_expression_analyzer_registry`](https://github.com/apache/datafusion/pull/21122/files#diff-ae492510820d46b07e2d7420f4555fcb005408682bf3e8aed85faad7925d4545R185).
Apologies for having you figure it out independently, I should have called this out more prominently in the PR description rather than only in code comments.
If you see a better way to propagate the registry that I might have overlooked or if you think a breaking change is the right call here, I'd be happy to hear more about that.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3320023662
##########
datafusion/physical-expr/src/expression_analyzer/mod.rs:
##########
@@ -0,0 +1,283 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Pluggable expression-level statistics analysis.
+//!
+//! This module provides an extensible mechanism for computing expression-level
+//! statistics metadata (selectivity, NDV, min/max bounds) following the chain
+//! of responsibility pattern.
+//!
+//! # Overview
+//!
+//! Different expressions have different statistical properties:
+//!
+//! - **Injective functions** (UPPER, LOWER, ABS on non-negative): preserve NDV
+//! - **Non-injective functions** (FLOOR, YEAR, SUBSTRING): reduce NDV
+//! - **Monotonic functions**: allow min/max bound propagation
+//! - **Constants**: NDV = 1, selectivity depends on value
+//!
+//! The default implementation uses classic Selinger-style estimation. Users can
+//! register custom [`ExpressionAnalyzer`] implementations to:
+//!
+//! 1. Provide statistics for custom UDFs
+//! 2. Override default estimation with domain-specific knowledge
+//! 3. Plug in advanced approaches (e.g., histogram-based estimation)
+//!
+//! # Example
+//!
+//! ```ignore
+//! use datafusion_physical_expr::expression_analyzer::*;
+//!
+//! // Create registry with default analyzer
+//! let mut registry = ExpressionAnalyzerRegistry::new();
+//!
+//! // Register custom analyzer (higher priority)
+//! registry.register(Arc::new(MyCustomAnalyzer));
+//!
+//! // Query expression statistics
+//! let selectivity = registry.get_selectivity(&predicate, &input_stats);
+//! ```
+
+mod default;
+
+#[cfg(test)]
+mod tests;
+
+pub use default::DefaultExpressionAnalyzer;
+
+use std::fmt::Debug;
+use std::sync::Arc;
+
+use datafusion_common::{ScalarValue, Statistics};
+
+use crate::PhysicalExpr;
+
+/// Result of expression analysis - either computed or delegate to next analyzer.
+#[derive(Debug, Clone)]
+pub enum AnalysisResult<T> {
+ /// Analysis was performed, here's the result
+ Computed(T),
+ /// This analyzer doesn't handle this expression; delegate to next
+ Delegate,
+}
+
+/// Expression-level metadata analysis.
+///
+/// Implementations can handle specific expression types or provide domain
+/// knowledge for custom UDFs. The chain of analyzers is traversed until one
+/// returns [`AnalysisResult::Computed`].
+///
+/// The `registry` parameter allows analyzers to delegate sub-expression
+/// analysis back through the full chain, rather than hard-coding a specific
+/// analyzer. For example, a function analyzer can ask the registry for the
+/// NDV of its input argument, which will traverse the full chain (including
+/// any custom analyzers the user registered).
+///
+/// # Implementing a Custom Analyzer
+///
+/// ```ignore
+/// #[derive(Debug)]
+/// struct MyUdfAnalyzer;
+///
+/// impl ExpressionAnalyzer for MyUdfAnalyzer {
+/// fn get_selectivity(
+/// &self,
+/// expr: &Arc<dyn PhysicalExpr>,
+/// input_stats: &Statistics,
+/// registry: &ExpressionAnalyzerRegistry,
+/// ) -> AnalysisResult<f64> {
+/// // Recognize my custom is_valid_email() UDF
+/// if is_my_email_validator(expr) {
+/// return AnalysisResult::Computed(0.8); // ~80% valid
+/// }
+/// AnalysisResult::Delegate
+/// }
+/// }
+/// ```
+pub trait ExpressionAnalyzer: Debug + Send + Sync {
Review Comment:
Addressed in https://github.com/apache/datafusion/pull/21122#issuecomment-4567251239 as it linked closely to the broader design questions
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4572728825
@asolimando The implementation plan looks great!
Regarding unified API vs. separate APIs:
1. I think the unified API approach is a better match for the underlying theory. Conceptually, what gets propagated through the expression tree is a **distribution summary**; different statistics such as NDV/null ratio are projections from that same distribution.
In a naive implementation for numeric expressions, the propagated fact seems to be something like `UniformDistribution(min, max, null_ratio)`, and we use that distribution to derive selectivity for predicates.
With separate APIs, the mental model may become that all statistic types are independent. That could make the design harder to extend in the future, especially if we want to handle skewed or correlated distributions.
I now feel the StatisticsV2 design makes a lot of sense from this perspective. Maybe we can revisit that approach and fix the engineering issues from the previous attempt:
* https://github.com/apache/datafusion/pull/22071
2. The requirement for lazily computing only a subset of statistics also makes sense to me. We could try to encode this into a request-based API:
```
estimate_stats(expr, context, request) -> response
```
where the request says something like:
```
I want: null_ratio, ndv, min/max, selectivity, ...
with: cheap_stats_only / build_histogram / ...
```
This probably still needs more thought to design cleanly, though.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-5336588947
Thank you for your contribution. Unfortunately, this pull request is stale because it has been open 60 days with no activity. Please remove the stale label or comment or this will be closed in 7 days.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3035362272
##########
datafusion/core/src/physical_planner.rs:
##########
@@ -2898,7 +2920,11 @@ impl DefaultPhysicalPlanner {
.into_iter()
.map(|(expr, alias)| ProjectionExpr { expr, alias })
.collect();
- Ok(Arc::new(ProjectionExec::try_new(proj_exprs, input_exec)?))
+ let mut proj_exec = ProjectionExec::try_new(proj_exprs, input_exec)?;
Review Comment:
Thanks for wiring the analyzer registry into planner-built projections. I think there is still one hole here though.
Right now this gets attached when the planner initially creates a `ProjectionExec`, but several later paths still rebuild or insert projections with plain `ProjectionExec::try_new(...)`, for example in `datafusion/physical-plan/src/projection.rs`, `datafusion/physical-optimizer/src/projection_pushdown.rs`, and `datafusion/physical-optimizer/src/aggregate_statistics.rs`.
After one of those rewrites, expression stats seem to fall back to `unknown` again even when `datafusion.optimizer.enable_expression_analyzer = true`.
Could we propagate the registry when cloning or rebuilding projections, or store it somewhere rebuilt plan nodes can recover it from? As written, this still looks plan-shape dependent after physical optimization.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3051939949
##########
datafusion/physical-expr/src/expression_analyzer/default.rs:
##########
@@ -0,0 +1,300 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Default expression analyzer with Selinger-style estimation.
+
+use std::sync::Arc;
+
+use datafusion_common::{ColumnStatistics, ScalarValue, Statistics};
+use datafusion_expr::Operator;
+
+use crate::PhysicalExpr;
+use crate::expressions::{BinaryExpr, Column, Literal, NotExpr};
+
+use super::{AnalysisResult, ExpressionAnalyzer, ExpressionAnalyzerRegistry};
+
+/// Default expression analyzer with Selinger-style estimation.
+///
+/// Handles common expression types:
+/// - Column references (uses column statistics)
+/// - Binary expressions (AND, OR, comparison operators)
+/// - Literals (constant selectivity/NDV)
+/// - NOT expressions (1 - child selectivity)
+#[derive(Debug, Default, Clone)]
+pub struct DefaultExpressionAnalyzer;
+
+impl DefaultExpressionAnalyzer {
+ /// Get column index from a Column expression
+ fn get_column_index(expr: &Arc<dyn PhysicalExpr>) -> Option<usize> {
+ expr.as_any().downcast_ref::<Column>().map(|c| c.index())
+ }
+
+ /// Get column statistics for an expression if it's a column reference
+ fn get_column_stats<'a>(
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &'a Statistics,
+ ) -> Option<&'a ColumnStatistics> {
+ Self::get_column_index(expr)
+ .and_then(|idx| input_stats.column_statistics.get(idx))
+ }
+
+ /// Resolve NDV for a binary expression: try direct column stats first,
+ /// then fall back to the registry for arbitrary expressions
+ fn resolve_ndv(
+ left: &Arc<dyn PhysicalExpr>,
+ right: &Arc<dyn PhysicalExpr>,
+ input_stats: &Statistics,
+ registry: &ExpressionAnalyzerRegistry,
+ ) -> Option<usize> {
+ Self::get_column_stats(left, input_stats)
Review Comment:
You are right, I have fixed it in 25e473ad and added some extra tests. While fixing this, I have also simplified the code, using `registry.get_distinct_count` on each side with `max` to cover all cases, "expr-expr, expr-col and col-expr" which are now all fully symmetric, thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3269047077
##########
datafusion/physical-expr/src/projection.rs:
##########
@@ -125,12 +126,22 @@ impl From<ProjectionExpr> for (Arc<dyn PhysicalExpr>, String) {
///
/// See [`ProjectionExprs::from_indices`] to select a subset of columns by
/// indices.
-#[derive(Debug, Clone, PartialEq, Eq)]
+#[derive(Debug, Clone)]
pub struct ProjectionExprs {
/// [`Arc`] used for a cheap clone, which improves physical plan optimization performance.
exprs: Arc<[ProjectionExpr]>,
+ /// Optional expression analyzer registry for statistics estimation
Review Comment:
I totally agree, since the design proposed in https://github.com/apache/datafusion/issues/21443
(`StatisticsRegistry`, working at the relational operator level) and https://github.com/apache/datafusion/issues/21120 (`ExpressionAnalyzer`, working at the expression level) felt like a big architectural change, I decided to start small with a fully opt-in design, which imposed temporary suboptimal decisions like the one discussed here of embedding `ExpressionAnalyzer` in the operators, and re-walking the plan to inject it.
I was waiting for https://github.com/apache/datafusion/pull/21815 to land, hoping I could piggy back on that breaking change and propose something similar to the `StatisticsArgs` you suggested, since we are actively working towards that goal, I am happy to clean up and simplify the integration of both `ExpressionAnalyzer` and `StatisticsRegistry` (merged via https://github.com/apache/datafusion/pull/21483)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4383031506
I am trying to find time to review this. I got very distracted this week working on arrow-rs PRs
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "xudong963 (via GitHub)" <gi...@apache.org>.
xudong963 commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4295469089
> In case it makes your decision easier, I can commit on helping with #20184's implementation, under both scenarios, if the current assignee is busy.
Yes, please. If the current assignee is busy, taking that on is probably the fastest path to unblocking this PR in its final form. Happy to review on that side too. Also cc @jonathanc-n
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3081003006
##########
datafusion/core/src/physical_planner.rs:
##########
@@ -2898,7 +2920,11 @@ impl DefaultPhysicalPlanner {
.into_iter()
.map(|(expr, alias)| ProjectionExpr { expr, alias })
.collect();
- Ok(Arc::new(ProjectionExec::try_new(proj_exprs, input_exec)?))
+ let mut proj_exec = ProjectionExec::try_new(proj_exprs, input_exec)?;
Review Comment:
Thanks a lot @kosiew for your help, I got sidetracked today but I plan to finalize the rebasing in the next few days, I will re-request a review once ready!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3029373659
##########
datafusion/physical-expr/src/expression_analyzer/default.rs:
##########
@@ -0,0 +1,285 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Default expression analyzer with Selinger-style estimation.
+
+use std::sync::Arc;
+
+use datafusion_common::{ColumnStatistics, ScalarValue, Statistics};
+use datafusion_expr::Operator;
+
+use crate::PhysicalExpr;
+use crate::expressions::{BinaryExpr, Column, Literal, NotExpr};
+
+use super::{AnalysisResult, ExpressionAnalyzer, ExpressionAnalyzerRegistry};
+
+/// Default expression analyzer with Selinger-style estimation.
+///
+/// Handles common expression types:
+/// - Column references (uses column statistics)
+/// - Binary expressions (AND, OR, comparison operators)
+/// - Literals (constant selectivity/NDV)
+/// - NOT expressions (1 - child selectivity)
+#[derive(Debug, Default, Clone)]
+pub struct DefaultExpressionAnalyzer;
+
+impl DefaultExpressionAnalyzer {
+ /// Get column index from a Column expression
+ fn get_column_index(expr: &Arc<dyn PhysicalExpr>) -> Option<usize> {
+ expr.as_any().downcast_ref::<Column>().map(|c| c.index())
+ }
+
+ /// Get column statistics for an expression if it's a column reference
+ fn get_column_stats<'a>(
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &'a Statistics,
+ ) -> Option<&'a ColumnStatistics> {
+ Self::get_column_index(expr)
+ .and_then(|idx| input_stats.column_statistics.get(idx))
+ }
+
+ /// Recursive selectivity estimation through the registry chain
+ fn estimate_selectivity_recursive(
+ &self,
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &Statistics,
+ registry: &ExpressionAnalyzerRegistry,
+ ) -> f64 {
+ registry.get_selectivity(expr, input_stats).unwrap_or(0.5)
+ }
+}
+
+impl ExpressionAnalyzer for DefaultExpressionAnalyzer {
+ fn get_selectivity(
+ &self,
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &Statistics,
+ registry: &ExpressionAnalyzerRegistry,
+ ) -> AnalysisResult<f64> {
+ // Binary expressions: AND, OR, comparisons
+ if let Some(binary) = expr.as_any().downcast_ref::<BinaryExpr>() {
+ let sel = match binary.op() {
+ // Logical operators: need child selectivities
+ Operator::And => {
+ let left_sel = self.estimate_selectivity_recursive(
+ binary.left(),
+ input_stats,
+ registry,
+ );
+ let right_sel = self.estimate_selectivity_recursive(
+ binary.right(),
+ input_stats,
+ registry,
+ );
+ left_sel * right_sel
+ }
+ Operator::Or => {
+ let left_sel = self.estimate_selectivity_recursive(
+ binary.left(),
+ input_stats,
+ registry,
+ );
+ let right_sel = self.estimate_selectivity_recursive(
+ binary.right(),
+ input_stats,
+ registry,
+ );
+ left_sel + right_sel - (left_sel * right_sel)
+ }
+
+ // Equality: selectivity = 1/NDV
+ Operator::Eq => {
+ let ndv = Self::get_column_stats(binary.left(), input_stats)
Review Comment:
That's true, thanks, fixed in eeb3b503e. Equality and inequality selectivity now uses the registry to resolve NDV for arbitrary expressions on both sides.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4725515660
I think this has to be reworked on top of #21815 - https://github.com/apache/datafusion/pull/21122#discussion_r3269082502
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3053877511
##########
datafusion/core/src/physical_planner.rs:
##########
@@ -2898,7 +2920,11 @@ impl DefaultPhysicalPlanner {
.into_iter()
.map(|(expr, alias)| ProjectionExpr { expr, alias })
.collect();
- Ok(Arc::new(ProjectionExec::try_new(proj_exprs, input_exec)?))
+ let mut proj_exec = ProjectionExec::try_new(proj_exprs, input_exec)?;
Review Comment:
Thanks for your guidance, @kosiew!
I have implemented option 1 optimistically in 54a0df74: tightened the config description and doc comments to make the scope explicit. But we can drop it in case option 2 is finally retained.
For option 2, I have opened #21483 (it was originally stacked on this PR, but I have reworked it to make it independent, the two can be composed later if #21483 gets in first) if you want to take a concrete look to evaluate whether you'd prefer to hold this PR until that one is ready.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3093089736
##########
datafusion/physical-plan/src/operator_statistics/mod.rs:
##########
@@ -782,9 +779,16 @@ impl StatisticsProvider for JoinStatisticsProvider {
return Ok(StatisticsResult::Delegate);
};
- use crate::joins::JoinOnRef;
+ let default_analyzer;
+ let analyzer = match plan.expression_analyzer_registry() {
Review Comment:
Thanks @kosiew, I have addressed both points in the latest two commits:
1. initial injection gap: my first idea was that if no rule ever modifies the plan, we might not need the injection step, but injecting before the optimizer loop is more consistent and safer, so I have added it
2. `JoinStatisticsProvider` config bypass: I have removed the fresh creation of `ExpressionAnalyzerRegistry` which was indeed violating the contract of the `use_expression_analyzer` config flag. The provider now uses the injected registry when present, and falls back to direct `ColumnStatistics` lookup for bare column keys when not (preserving the behavior as of #21483 when `use_expression_analyzer` is false, as expected).
EDIT: CI [failure](https://github.com/apache/datafusion/actions/runs/24509459889/job/71637302277?pr=21122#step:7:115) looks unrelated:
```
$ sudo apt-get update
$ sudo apt-get install -y protobuf-compiler
[...]
Err:66 http://security.ubuntu.com/ubuntu noble-security/restricted Translation-en
File has unexpected size (653824 != 658356). Mirror sync in progress? [IP: 91.189.91.81 80]
[...]
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4366110464
starting to check it out
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-5339008163
Let's keep it in draft a little longer, as https://github.com/apache/datafusion/pull/23651 is close to be merged and resuming expression-level work is next in line (although I might open a different PR)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3029399061
##########
datafusion/physical-expr/src/expression_analyzer/default.rs:
##########
@@ -0,0 +1,285 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Default expression analyzer with Selinger-style estimation.
+
+use std::sync::Arc;
+
+use datafusion_common::{ColumnStatistics, ScalarValue, Statistics};
+use datafusion_expr::Operator;
+
+use crate::PhysicalExpr;
+use crate::expressions::{BinaryExpr, Column, Literal, NotExpr};
+
+use super::{AnalysisResult, ExpressionAnalyzer, ExpressionAnalyzerRegistry};
+
+/// Default expression analyzer with Selinger-style estimation.
+///
+/// Handles common expression types:
+/// - Column references (uses column statistics)
+/// - Binary expressions (AND, OR, comparison operators)
+/// - Literals (constant selectivity/NDV)
+/// - NOT expressions (1 - child selectivity)
+#[derive(Debug, Default, Clone)]
+pub struct DefaultExpressionAnalyzer;
+
+impl DefaultExpressionAnalyzer {
+ /// Get column index from a Column expression
+ fn get_column_index(expr: &Arc<dyn PhysicalExpr>) -> Option<usize> {
+ expr.as_any().downcast_ref::<Column>().map(|c| c.index())
+ }
+
+ /// Get column statistics for an expression if it's a column reference
+ fn get_column_stats<'a>(
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &'a Statistics,
+ ) -> Option<&'a ColumnStatistics> {
+ Self::get_column_index(expr)
+ .and_then(|idx| input_stats.column_statistics.get(idx))
+ }
+
+ /// Recursive selectivity estimation through the registry chain
+ fn estimate_selectivity_recursive(
+ &self,
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &Statistics,
+ registry: &ExpressionAnalyzerRegistry,
+ ) -> f64 {
+ registry.get_selectivity(expr, input_stats).unwrap_or(0.5)
+ }
+}
+
+impl ExpressionAnalyzer for DefaultExpressionAnalyzer {
+ fn get_selectivity(
+ &self,
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &Statistics,
+ registry: &ExpressionAnalyzerRegistry,
+ ) -> AnalysisResult<f64> {
+ // Binary expressions: AND, OR, comparisons
+ if let Some(binary) = expr.as_any().downcast_ref::<BinaryExpr>() {
+ let sel = match binary.op() {
+ // Logical operators: need child selectivities
+ Operator::And => {
+ let left_sel = self.estimate_selectivity_recursive(
+ binary.left(),
+ input_stats,
+ registry,
+ );
+ let right_sel = self.estimate_selectivity_recursive(
+ binary.right(),
+ input_stats,
+ registry,
+ );
+ left_sel * right_sel
+ }
+ Operator::Or => {
+ let left_sel = self.estimate_selectivity_recursive(
+ binary.left(),
+ input_stats,
+ registry,
+ );
+ let right_sel = self.estimate_selectivity_recursive(
+ binary.right(),
+ input_stats,
+ registry,
+ );
+ left_sel + right_sel - (left_sel * right_sel)
+ }
+
+ // Equality: selectivity = 1/NDV
+ Operator::Eq => {
+ let ndv = Self::get_column_stats(binary.left(), input_stats)
+ .or_else(|| Self::get_column_stats(binary.right(), input_stats))
+ .and_then(|s| s.distinct_count.get_value())
+ .filter(|&&ndv| ndv > 0);
+ if let Some(ndv) = ndv {
+ return AnalysisResult::Computed(1.0 / (*ndv as f64));
+ }
+ 0.1 // Default equality selectivity
+ }
+
+ // Inequality: selectivity = 1 - 1/NDV
+ Operator::NotEq => {
+ let ndv = Self::get_column_stats(binary.left(), input_stats)
+ .or_else(|| Self::get_column_stats(binary.right(), input_stats))
+ .and_then(|s| s.distinct_count.get_value())
+ .filter(|&&ndv| ndv > 0);
+ if let Some(ndv) = ndv {
+ return AnalysisResult::Computed(1.0 - (1.0 / (*ndv as f64)));
+ }
+ 0.9
+ }
+
+ // Range predicates: classic 1/3 estimate
+ Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq => 0.33,
+
+ // LIKE: depends on pattern, use conservative estimate
+ Operator::LikeMatch | Operator::ILikeMatch => 0.25,
+ Operator::NotLikeMatch | Operator::NotILikeMatch => 0.75,
+
+ // Other operators: default
+ _ => 0.5,
+ };
+
+ return AnalysisResult::Computed(sel);
+ }
+
+ // NOT expression: 1 - child selectivity
+ if let Some(not_expr) = expr.as_any().downcast_ref::<NotExpr>() {
+ let child_sel = self.estimate_selectivity_recursive(
+ not_expr.arg(),
+ input_stats,
+ registry,
+ );
+ return AnalysisResult::Computed(1.0 - child_sel);
+ }
+
+ // Literal boolean: 0.0 or 1.0
+ if let Some(b) = expr
+ .as_any()
+ .downcast_ref::<Literal>()
+ .and_then(|lit| match lit.value() {
+ ScalarValue::Boolean(Some(b)) => Some(*b),
+ _ => None,
+ })
+ {
+ return AnalysisResult::Computed(if b { 1.0 } else { 0.0 });
+ }
+
+ // Column reference as predicate (boolean column)
+ if expr.as_any().downcast_ref::<Column>().is_some() {
+ return AnalysisResult::Computed(0.5);
+ }
+
+ AnalysisResult::Delegate
+ }
+
+ fn get_distinct_count(
+ &self,
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &Statistics,
+ registry: &ExpressionAnalyzerRegistry,
+ ) -> AnalysisResult<usize> {
+ // Column reference: use column NDV
+ if let Some(ndv) = Self::get_column_stats(expr, input_stats)
+ .and_then(|col_stats| col_stats.distinct_count.get_value().copied())
+ {
+ return AnalysisResult::Computed(ndv);
+ }
+
+ // Literal: NDV = 1
+ if expr.as_any().downcast_ref::<Literal>().is_some() {
+ return AnalysisResult::Computed(1);
+ }
+
+ // BinaryExpr: for arithmetic with a literal operand, treat as injective
Review Comment:
Agreed, I have tried to sneak in as many cases as possible to show-case what the new analyzer would allow, but this part was a bit too sketchy, thanks for pointing that out.
Since the review surface is already big, and further support for arithmetic expressions can be tackled incrementally later, I have narrowed to addition and subtraction only in 40ae37ed7, let me know if that sounds reasonable to you.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3029362982
##########
datafusion/physical-expr/src/projection.rs:
##########
@@ -713,9 +745,35 @@ impl ProjectionExprs {
byte_size,
}
}
+ } else if let Some(registry) = &self.expression_analyzer_registry {
Review Comment:
Good catch, fixed in c62a5cbcf. When the analyzer registry is present, we now snapshot the input column statistics before the loop so that `std::mem::take` on bare columns doesn't affect analyzer lookups for later expressions.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "2010YOUY01 (via GitHub)" <gi...@apache.org>.
2010YOUY01 commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4575896814
I still got some questions: suppose we have a separated API, and in order to implement each API accurately, the intermediate representation propagated through the expression tree must be some complex-ish model. (Maybe "data synopsis" is a better term here; I used "distribution summary" before)
For example,
```rust
get_ndv(a + b)
a: UniformDistribution(min = 0, max = 100, ndv = 100)
b: UniformDistribution(min = 200, max = 300, ndv = 10)
```
Then we can get `ndv(a + b) = 200` accurately. If we also want to calculate `get_range(a + b)`, the same data synopsis would need to be propagated again, so the separate-API approach might lead to duplicated implementations, and a unified approach seem to be simpler here.
> I see the distribution assumption differently though: at the base table level the underlying distribution can be known precisely (e.g., from KLL sketches or histograms), but after the first layer of propagation it's already an approximation. I think the distribution belongs in the API request rather than as metadata propagated through the tree. Different consumers want different assumptions for the same expression, e.g., sizing a hash table to avoid OOMs wants the worst case (uniform, highest NDV), while join ordering might want a more conservative estimate. This is also why I think Stats V2 had the right intuition but the wrong model, propagating distribution objects treats an assumption as a fact.
I agree that different use cases require different behaviors from stat propagation. This looks like something that could be implemented as a hint argument to guide the propagation strategy.
That's also a solid point: some complex expressions can make the existing statistics invalid or unreliable. I think this requires some fallback data-synopsis representation? I'm not sure if a separate API design can make it easier.
Note that these are still just my intuitions, and I could be missing something. This is really interesting, and I'll think about it more.
Perhaps we can add some concrete examples to the writeup (dataset, SQL query subplan/expr to estimate the stat), and then reason about the design end-to-end. Right now, it feels like we're jumping directly into implementation details, which might make the design decisions unclear to me and others.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4726842675
> I think this has to be reworked on top of #21815 - [#21122 (comment)](https://github.com/apache/datafusion/pull/21122#discussion_r3269082502)
Yes, what I plan to tackle, in order, is the following:
1. #21815
2. #22958
3. [#21122 (comment)](https://github.com/apache/datafusion/pull/21122#discussion_r3269082502)
a. Integrate `StatisticsRegistry` (from #21483) along the line suggested by @alamb (default but no-op if no providers are registered)
4. Extension to PhysicalExpr (new trait methods, default implementation returns None, non-breaking), along the line of https://github.com/apache/datafusion/pull/21122#issuecomment-4567251239
5. [#21122 (comment)](https://github.com/apache/datafusion/pull/21122#discussion_r3269082502)
a. Rework `ExpressionAnalyzer` to make it the default, no-op if no providers are registered (again Andrew's suggestion)
We could mark the current PR as draft, I will see if it makes more sense to open a new one (for 5.) or rebase this one not to lose previous context.
WDYT?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "kosiew (via GitHub)" <gi...@apache.org>.
kosiew commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3050274381
##########
datafusion/physical-expr/src/expression_analyzer/default.rs:
##########
@@ -0,0 +1,300 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+//! Default expression analyzer with Selinger-style estimation.
+
+use std::sync::Arc;
+
+use datafusion_common::{ColumnStatistics, ScalarValue, Statistics};
+use datafusion_expr::Operator;
+
+use crate::PhysicalExpr;
+use crate::expressions::{BinaryExpr, Column, Literal, NotExpr};
+
+use super::{AnalysisResult, ExpressionAnalyzer, ExpressionAnalyzerRegistry};
+
+/// Default expression analyzer with Selinger-style estimation.
+///
+/// Handles common expression types:
+/// - Column references (uses column statistics)
+/// - Binary expressions (AND, OR, comparison operators)
+/// - Literals (constant selectivity/NDV)
+/// - NOT expressions (1 - child selectivity)
+#[derive(Debug, Default, Clone)]
+pub struct DefaultExpressionAnalyzer;
+
+impl DefaultExpressionAnalyzer {
+ /// Get column index from a Column expression
+ fn get_column_index(expr: &Arc<dyn PhysicalExpr>) -> Option<usize> {
+ expr.as_any().downcast_ref::<Column>().map(|c| c.index())
+ }
+
+ /// Get column statistics for an expression if it's a column reference
+ fn get_column_stats<'a>(
+ expr: &Arc<dyn PhysicalExpr>,
+ input_stats: &'a Statistics,
+ ) -> Option<&'a ColumnStatistics> {
+ Self::get_column_index(expr)
+ .and_then(|idx| input_stats.column_statistics.get(idx))
+ }
+
+ /// Resolve NDV for a binary expression: try direct column stats first,
+ /// then fall back to the registry for arbitrary expressions
+ fn resolve_ndv(
+ left: &Arc<dyn PhysicalExpr>,
+ right: &Arc<dyn PhysicalExpr>,
+ input_stats: &Statistics,
+ registry: &ExpressionAnalyzerRegistry,
+ ) -> Option<usize> {
+ Self::get_column_stats(left, input_stats)
Review Comment:
I think there is a subtle issue here.
Right now `resolve_ndv` picks the first available direct-column stats using `left.or_else(right)`. That makes the result dependent on operand order. For example, `a = b` could use `ndv(a)` while `b = a` uses `ndv(b)` when both sides already have stats.
This ends up regressing the selectivity heuristic even before any registry fallback is involved, and it also means we are not handling the two-column case symmetrically.
Would it make sense to use a symmetric rule here, like `max(ndv_left, ndv_right)`, when both sides have NDV available? That would keep estimates stable regardless of operand order and better reflect the intent of equality selectivity.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3204292651
##########
datafusion/core/src/physical_planner.rs:
##########
@@ -1097,12 +1098,12 @@ impl DefaultPhysicalPlanner {
input_schema.as_arrow(),
)? {
PlanAsyncExpr::Sync(PlannedExprResult::Expr(runtime_expr)) => {
- FilterExecBuilder::new(
+ let builder = FilterExecBuilder::new(
Review Comment:
a nit is that these changes seem unrelated
##########
datafusion/physical-expr/src/projection.rs:
##########
@@ -125,12 +126,22 @@ impl From<ProjectionExpr> for (Arc<dyn PhysicalExpr>, String) {
///
/// See [`ProjectionExprs::from_indices`] to select a subset of columns by
/// indices.
-#[derive(Debug, Clone, PartialEq, Eq)]
+#[derive(Debug, Clone)]
pub struct ProjectionExprs {
/// [`Arc`] used for a cheap clone, which improves physical plan optimization performance.
exprs: Arc<[ProjectionExpr]>,
+ /// Optional expression analyzer registry for statistics estimation
Review Comment:
I think this is basically the same thing @xudong963 is saying in this comment:
- https://github.com/apache/datafusion/pull/21122#pullrequestreview-4145718306
##########
datafusion/common/src/config.rs:
##########
@@ -1131,6 +1131,11 @@ config_namespace! {
/// So if you disable `enable_topk_dynamic_filter_pushdown`, then enable `enable_dynamic_filter_pushdown`, the `enable_topk_dynamic_filter_pushdown` will be overridden.
pub enable_dynamic_filter_pushdown: bool, default = true
+ /// When set to true, the pluggable `ExpressionAnalyzerRegistry` from
+ /// `SessionState` is used for expression-level statistics estimation
+ /// (NDV, selectivity, min/max, null fraction) in physical plan operators.
+ pub use_expression_analyzer: bool, default = false
Review Comment:
I wonder why we need a new flag? It seems like in an ideal world, we would add a new extension API but then refactor the existing code so it used the new extension API (but kept the existing behavior)
##########
datafusion/physical-expr/src/projection.rs:
##########
@@ -125,12 +126,22 @@ impl From<ProjectionExpr> for (Arc<dyn PhysicalExpr>, String) {
///
/// See [`ProjectionExprs::from_indices`] to select a subset of columns by
/// indices.
-#[derive(Debug, Clone, PartialEq, Eq)]
+#[derive(Debug, Clone)]
pub struct ProjectionExprs {
/// [`Arc`] used for a cheap clone, which improves physical plan optimization performance.
exprs: Arc<[ProjectionExpr]>,
+ /// Optional expression analyzer registry for statistics estimation
Review Comment:
If feels akward to me that the ProjectionExprs has an expression analyzer on it, as that expression analyzer seems like it is really there to be passed into a call to StatisticsProvider::compute_statistics
In other words, there is one `ExpressionAnalyzerRegistry` per plan, but but putting it on fields it look like it could be per plan node. In fact, this isn't even a plan node (it is a field on a plan node)
I also think that having to set the fields correctly means there is a (real) a danger that it won't be plumbed through properly in the future
It seems to me like a better design would be to pass the `ExpressionAnalyzerRegistry` down in the callsite where it is needed -- for example how about adding it as a method on the StatisticsProvider::compute_statistics? That would ensure it is always passed where needed and it would remove a lot of the boiler plate in this PR
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-5970893039
> Thank you! It's always been on my list, though I've had some trouble allocating enough time to it.
>
> I'll share some partial feedback next week, and plan to focus on this project more deeply at some point later.
@2010YOUY01 no worries, that's totally understandable.
To save you time, I pushed [this branch](https://github.com/apache/datafusion/compare/main...asolimando:datafusion:asolimando/expression-synopsis) to my fork. It has the full implementation of #21120, which I used to validate the design. It keeps the expression-level rules to a minimum: just enough to show the framework's backbone and how operators and providers use it.
The first PR (of five) would be commits 1-9: the synopsis type, the walk over the expression tree, the provider chain, and the aggregate as the first operator that uses them. If you only have time for part of the design at first, feedback on these would be a good start and unblock the first PR. Interval analysis is only used from the second PR, which adds the filter, so my question about it is less urgent.
This is not a code review request, as the code will change based on our discussion, but it is probably easier to ask an LLM what I meant exactly when something is unclear.
Looking forward to your feedback!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3088387725
##########
datafusion/core/src/physical_planner.rs:
##########
@@ -2898,7 +2920,11 @@ impl DefaultPhysicalPlanner {
.into_iter()
.map(|(expr, alias)| ProjectionExpr { expr, alias })
.collect();
- Ok(Arc::new(ProjectionExec::try_new(proj_exprs, input_exec)?))
+ let mut proj_exec = ProjectionExec::try_new(proj_exprs, input_exec)?;
Review Comment:
@kosiew, thanks for your patience, here's what changed since your last review.
### Addressing the plan-shape dependency:
To address this I finally included a re-injection loop in the physical planner that runs after each optimizer rule that modifies the plan (detected via `Arc::ptr_eq`). This ensures optimizer-created nodes (e.g. `FilterExec` from filter pushdown into unions, repositioned filters through joins, etc.) always receive the registry. The walk is entirely skipped when the ExpressionAnalyzer is disabled, no additional overhead for the common path.
Caveat: nodes created within a rule (e.g. a new FilterExec) receive the registry only _after_ that rule completes, before the next rule runs. No such rule (`EnforceDistribution`, `CombinePartialFinalAggregate`, `ProjectionPushdown`, `AggregateStatistics` and `JoinSelection`) reads stats from the nodes it just created within the same rule execution, so there's no gap at the moment.
Since there is no gap and that this concern will go away if we integrate fully with `partitions_statistics` (see the "Future direction" section), which is the natural evolution of this proposal, I consider the integration satisfactory, what do you think?
### Integration with StatisticsRegistry (#21483):
The `AggregateStatisticsProvider` and `JoinStatisticsProvider` providers consume `ExpressionAnalyzer` and this adds support for aggregations and joins. When no registry is injected, they delegate to the existing code path, purely additive as the rest.
### Future direction: removing the injection overhead (just FYI, no action for this PR)
The re-injection loop for `ExpressionAnalyzer` and the separate `StatisticsRegistry` tree walk both exist because `partition_statistics` has no way to receive external context and we don't want breaking changes.
But we could piggyback on #20184 (`child_stats` in `partition_statistics`) as it plans to update `partition_statistics`'s signature anyway.
By generalizing slightly with a `StatisticsContext` parameter that carries both the `ExpressionAnalyzerRegistry` and `StatisticsRegistry` providers, we would get headroom for future changes while limiting breaking changes.
This would collapse both mechanisms into the natural `partition_statistics` recursion, eliminating the injection walks and the separate bottom-up traversal entirely while keeping the config flags to turn either framework on or off.
The separate walks are acceptable now as a trade-off for a purely additive and non-breaking change, but this would be the natural evolution of the proposal.
### New commits in detail:
I had to rebase on #21483, this will make incremental reviewing harder for you, so let me walk you through the changes since your last review (commits 9-12 of 12):
9. Inject ExpressionAnalyzerRegistry into exec nodes and re-inject via optimizer loop - the core change addressing your feedback, includes integration tests
10. test(filter): verify ExpressionAnalyzer inclusion-exclusion selectivity for OR predicates - unit test for OR selectivity in FilterExec
11. refactor(expression_analyzer): delegate when no NDV statistics are available - I realized we were trying to do too much when some columns statistics are unset, now we delegate to built-in
12. test(expression_analyzer): add StatisticsTable and end-to-end SLT for OR selectivity - end-to-end SLT tests verifying the registry survives TopK sort, UNION ALL filter pushdown, and hash join filter pushdown (queries chosen as they generate nodes that would need the `ExpressionAnalyzer`, exactly the gap we had before)
Looking forward to your feedback!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4255326451
@kosiew the CI error seems unrelated, the same test suite passed for `macos` but not `amd64`, I can't reproduce and it doesn't seem it can be caused by changes in this PR, it feels like a flaky test but I'd like to get your opinion.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4723548263
What are we thinking to do with this PR -- it is approved by @kosiew but it seems like we have some outstanding technical design questions. Shall we mark it as a draft? Or close it and work on a follow on?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4567251239
> Thank you — this is a clever approach for enabling external overrides.
>
> I have a suggestion on how to structure this work:
>
> The main motivation for this PR should be to allow external `ExpressionAnalyzer`s to override the internal ones. For example, we may have a naive internal implementation for estimating the NDV of the `regexp_like()` function, while downstream use cases may want to override that estimation with a more accurate one.
>
> In that case, I think only the override implementations should live inside `ExpressionAnalyzerRegistry`, and we may not need to implement `DefaultExpressionAnalyzer`. For internal expressions/UDFs, we can first extend the `PhysicalExpr` trait, so their statistics estimation logic be implemented inside the trait.
>
> The reasons are:
>
> * To cover common built-in expressions/UDFs, `DefaultExpressionAnalyzer` would likely need large match arms covering hundreds of variants, which could increase binary size.
> * Function implementation details would be scattered across multiple places: mostly in the function trait, but partly inside `ExpressionAnalyzer`. I think this would make the code harder to maintain.
>
> So I suggest we first extend the `PhysicalExpr` trait to support expression-level statistics propagation, implement the propagation logic for some common expressions there, and then introduce the external `ExpressionAnalyzerRegistry` mechanism as a follow-up.
@2010YOUY01, thank you for the detailed feedback, I agree with the direction.
Would you be fine tackling the `PhysicalExpr` extension as a separate PR (again part of https://github.com/apache/datafusion/issues/21120)? I would then rebase this PR on top of it and #21815.
At that point AND/OR/NOT can recurse through the same `StatisticsContext` from #21815, with `ExpressionAnalyzerRegistry` as a field on it. One context flows from planner through operators down to expressions, custom overrides on children are picked up naturally, no injection needed (as also suggested by @alamb).
So the proposed order would be:
1. #21815
2. Extension to `PhysicalExpr` (new trait methods, default implementation returns `None`, non-breaking)
3. Resuming this PR and address pending points:
- adding an end to end, motivating example
- making the default implementation backwards compatible
- cleanup post #21815 (avoid extra visits/embedding into operators)
- and the changes we just discussed
Regarding unifying the 4 methods into a single `analyze()` returning a struct/enum - I think keeping them separate works better with the `PhysicalExpr` approach: each expression overrides only the stats it knows (default `None`), and callers ask for exactly what they need. A single method would either force the analyzer to compute all stats even when the caller needs just one (e.g., NDV for a projection, selectivity for a filter), or we'd need a request parameter to specify what's wanted. Stats computation can be expensive for custom analyzers (sampling, external lookups), so lazy per-method evaluation seems safer.
WDYT?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on code in PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#discussion_r3269082502
##########
datafusion/common/src/config.rs:
##########
@@ -1131,6 +1131,11 @@ config_namespace! {
/// So if you disable `enable_topk_dynamic_filter_pushdown`, then enable `enable_dynamic_filter_pushdown`, the `enable_topk_dynamic_filter_pushdown` will be overridden.
pub enable_dynamic_filter_pushdown: bool, default = true
+ /// When set to true, the pluggable `ExpressionAnalyzerRegistry` from
+ /// `SessionState` is used for expression-level statistics estimation
+ /// (NDV, selectivity, min/max, null fraction) in physical plan operators.
+ pub use_expression_analyzer: bool, default = false
Review Comment:
As discussed in https://github.com/apache/datafusion/pull/21122#discussion_r3269047077, I wanted to make it evident that the new components were totally opt-in and would not cause any issues for downstream users.
The idea was to later work my way up to a point where this would become the default mechanism, starting with the same exact behavior by default, and relying the extensibility of the design to modify it.
Happy to update this PR once https://github.com/apache/datafusion/pull/21815 lands, especially since there seems to be consensus that the design is a promising direction.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4179403000
> @asolimando
>
> Thanks for the solid work here. The new analyzer direction looks promising, but I ran into a couple of issues that could affect correctness and usefulness of the stats. Left a few detailed comments below.
Thanks to you @kosiew for the spot-on review, and for sharing your feedback. I have addressed the requested changes, happy to iterate further if needed!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-4400506168
Now that I have the release candidates out for arrow-rs I have more time to review PRs. Back to this one
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-5955682180
@2010YOUY01 resuming this now that #21815, #23051 and #23651 have landed. You asked for concrete examples before the design, so here they are first: seven queries over one dataset, each with the estimate it needs, the operator that consumes it, and the design point it tests. The decisions they lead to follow.
### Examples
Dataset: `sales`, 10,000 rows, values uniform within their range, `c` strongly correlated with `a`.
| column | type | min | max | distinct | nulls |
|---|---|---|---|---|---|
| `a` | INT | 0 | 99 | 100 | 1,000 |
| `b` | INT | 200 | 300 | 10 | 0 |
| `c` | INT | 0 | 99 | 100 | 0 |
| `ts` | TIMESTAMP | 2025-01-01 | 2025-12-31 | ~10,000 | 0 |
| `s` | VARCHAR | | | 5,000 | 0 |
**1. `SELECT a + b AS k, count(*) FROM sales GROUP BY k`.** The range of `a + b` is [200, 399], so there are at most 200 distinct values plus one NULL group: at most 201 groups, where main estimates 10,000. Point: one propagated unit. The distinct count follows from the range, without a distribution assumption.
**2. `... GROUP BY a > 50`.** At most 3 groups (true, false, NULL); main estimates 10,000. Point: a predicate is also a value, so there is no `Predicate | Value` split.
**3. `sales JOIN dims ON sales.b = dims.b WHERE NOT (sales.a > 50)`, `dims` with 5,000 rows.** `NOT p` keeps `1 - 0.441 - 0.1` of the rows, about 4,590, so `sales` is the build side. Ignoring the null share gives about 5,590 and picks `dims`. Point: three-valued logic needs the null share, which comes from the predicate's null count.
**4. `... GROUP BY date_trunc('month', ts)`.** 12 groups, where main estimates 10,000, through a provider that knows `date_trunc`. In a two-phase plan the partial stage publishes the distinct count on its output column and the final stage reads it back. #25611 reports the same shape on TPC-H SF1: 6,001,215 groups estimated for 7 actual.
**5. `... GROUP BY upper(s)`.** A consumer that must not underestimate (for example future hash table presizing) wants the bound, 5,000. A consumer that compares alternatives (join ordering) wants a best guess, such as 3,000. Point: the consumer's need belongs to the request.
**6. `sales JOIN dims ON sales.b = dims.b WHERE sales.a > 50 AND sales.c > 50`, `dims` with 3,000 rows.** Independence gives about 2,160 rows, so `sales` builds. With `c` equal to `a` the answer is up to 4,410, so `dims` builds. Point: no built-in correlation, but a provider holding correlation metadata can answer the `AND`.
**7. `orders JOIN customers ON customer_id = id JOIN regions ON customers.region = regions.id`** (keys 0..99 over 1,000 rows, keys 50..149 over 100 rows, `regions` with 700 rows). The distinct-count formula estimates the first join at 1,000 rows, so `regions` builds the second join. A sketch intersection estimates 500, which is the truth, so the first join's result builds. Point: custom statistics travel per column. A built-in rule drops one it does not understand: with `customer_id + 1 = id` the distinct count carries through, but a hash sketch does not.
Two more edge cases: `a - a` and `a = a` (a rule sees its children, so it can recognise the same column on both sides), and `random() < 0.1 AND random() < 0.1` (0.01, because the two calls are independent; a rule can check volatility).
### Decisions
**You were right about the propagated unit.** What propagates through the expression tree should be one synopsis per expression, not N independent answers. Your duplication argument holds: with separate methods every expression implements N rules, with one synopsis it implements one. The examples add a second reason. In a two-phase aggregate (case 4), the group expression exists only in the partial stage, and the final stage groups on a bare column of the partial output. The partial stage can pass the expression's distinct count upward only as the `distinct_count` of that output column, so the synopsis has to carry `ColumnStatistics`. With four independent getters there is nothing to write into that column.
**My laziness concern from May does not need separate methods.** Built-in rules are local and cheap: each combines the synopses of its children and never walks the tree itself, and the walk caches one synopsis per structurally equal sub-expression. The expensive cases I worried about (sampling, external lookups) belong to providers, which decide for themselves what to compute. Case 5 shows when a request would matter (a bound for one consumer, a best guess for another). I would not add it yet: the per-call inputs go in an arguments struct with private fields, the same pattern as `StatisticsArgs`, so the request can become a field later without changing the `PhysicalExpr` method.
**A flat struct instead of `Predicate | Value`.** I agree `a + 1` must not report a selectivity, but the partition is not total. A predicate is also a value: `GROUP BY a > 50` (case 2) needs the distinct count of a predicate. And a selectivity alone is not enough for three-valued logic (case 3): `NOT p` is `1 - selectivity(p) - null_count(p) / rows`. The type-safety part can be enforced in one place instead: the synopsis carries its data type, set from the schema, and a synopsis that sets a selectivity for a non-Boolean expression is rejected.
**Estimation only, next to the existing mechanisms.** The synopsis never drives a correctness decision such as pruning, because an estimate can be wrong. It does not compute ranges: its min/max come from `evaluate_bounds`, so the careful floating-point rounding stays in one place. The dependency runs one way: the synopsis consumes `evaluate_bounds`, and the correctness users of `evaluate_bounds`, such as the symmetric hash join, never consume the synopsis. For a predicate that interval analysis supports, `analyze()` stays the estimate, and the synopsis rules combine the rest, so `p_size = 15 AND p_type LIKE '%BRASS%'` (#25612) keeps the interval estimate of its first conjunct. It does not overlap with your #19609, which computes sound bounds per container for pruning. Given that work, does this split between interval analysis and the synopsis match how you see the two fitting together?
**No distributions.** I would keep the unification and leave out parametric distributions (the Statistics V2 shape). Skew, correlation or histograms can travel as extensions, supplied by a provider that understands them: case 6 for correlation, case 7 for a set sketch that gets a join right where the distinct-count formula is off by a factor of two.
The shape these decisions give, as a sketch:
```rust
pub struct ExprSynopsis {
pub column: ColumnStatistics, // distinct count, min/max, null count
pub selectivity: Option<f64>, // Boolean expressions only
pub extensions: Extensions, // custom statistics, from providers
pub data_type: DataType,
}
// On PhysicalExpr, with a default that returns None:
fn synopsis_from_inputs(&self, args: &SynopsisArgs, child_synopses: &[ExprSynopsis])
-> Option<ExprSynopsis>;
```
If the decisions work for you, I will open the framework PR (the synopsis, the walk and the provider chain, with the aggregate as the first consumer), as mentioned on #25610.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Add ExpressionAnalyzer for pluggable expression-level statistics estimation [datafusion]
Posted by "asolimando (via GitHub)" <gi...@apache.org>.
asolimando commented on PR #21122:
URL: https://github.com/apache/datafusion/pull/21122#issuecomment-6325627471
@2010YOUY01, did you have time to share an initial feedback on the design?
In case it proves hard to allocate some time for that, I can check if other PMC members/committers that has helped me in the past months merging statistics-related PRs can take a look (@xudong963, @kosiew and more recently @zhuqi-lucas).
@alamb: if you have time, [this](https://github.com/asolimando/datafusion/blob/28609a139175dc6e14c875c1ffc7613f9056c3b0/datafusion-examples/examples/statistics/join_sketch_synopsis.rs) is the example you were asking for. It's in my fork, details are subject to change but the underlying idea is stable, I'd appreciate your reading on the example/general idea, no need to go into the details unless you have time or interest.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org