Skip to main content

datafusion_physical_expr/statistics/
stats_solver.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! DAG-based statistics propagation for the Statistics V2 framework.
6//!
7//! All public items in this module are **deprecated** as of `54.0.0`.
8//! See <https://github.com/apache/datafusion/pull/22071> for details.
9
10#![allow(deprecated)]
11
12use std::sync::Arc;
13
14use crate::expressions::Literal;
15use crate::intervals::cp_solver::PropagationResult;
16use crate::physical_expr::PhysicalExpr;
17use crate::utils::{ExprTreeNode, build_dag};
18
19use arrow::datatypes::{DataType, Schema};
20use datafusion_common::{Result, ScalarValue};
21use datafusion_expr::statistics::Distribution;
22use datafusion_expr_common::interval_arithmetic::Interval;
23
24use petgraph::Outgoing;
25use petgraph::adj::DefaultIx;
26use petgraph::prelude::Bfs;
27use petgraph::stable_graph::{NodeIndex, StableGraph};
28use petgraph::visit::DfsPostOrder;
29
30/// This object implements a directed acyclic expression graph (DAEG) that
31/// is used to compute statistics/distributions for expressions hierarchically.
32#[deprecated(
33    since = "54.0.0",
34    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
35)]
36#[derive(Clone, Debug)]
37pub struct ExprStatisticsGraph {
38    graph: StableGraph<ExprStatisticsGraphNode, usize>,
39    root: NodeIndex,
40}
41
42/// This is a node in the DAEG; it encapsulates a reference to the actual
43/// [`PhysicalExpr`] as well as its statistics/distribution.
44#[deprecated(
45    since = "54.0.0",
46    note = "Part of the unused Statistics V2 framework; see https://github.com/apache/datafusion/pull/22071"
47)]
48#[derive(Clone, Debug)]
49pub struct ExprStatisticsGraphNode {
50    expr: Arc<dyn PhysicalExpr>,
51    dist: Distribution,
52}
53
54impl ExprStatisticsGraphNode {
55    /// Constructs a new DAEG node based on the given interval with a
56    /// `Uniform` distribution.
57    fn new_uniform(expr: Arc<dyn PhysicalExpr>, interval: Interval) -> Result<Self> {
58        Distribution::new_uniform(interval)
59            .map(|dist| ExprStatisticsGraphNode { expr, dist })
60    }
61
62    /// Constructs a new DAEG node with a `Bernoulli` distribution having an
63    /// unknown success probability.
64    fn new_bernoulli(expr: Arc<dyn PhysicalExpr>) -> Result<Self> {
65        Distribution::new_bernoulli(ScalarValue::Float64(None))
66            .map(|dist| ExprStatisticsGraphNode { expr, dist })
67    }
68
69    /// Constructs a new DAEG node with a `Generic` distribution having no
70    /// definite summary statistics.
71    fn new_generic(expr: Arc<dyn PhysicalExpr>, dt: &DataType) -> Result<Self> {
72        let interval = Interval::make_unbounded(dt)?;
73        let dist = Distribution::new_from_interval(interval)?;
74        Ok(ExprStatisticsGraphNode { expr, dist })
75    }
76
77    /// Get the [`Distribution`] object representing the statistics of the
78    /// expression.
79    pub fn distribution(&self) -> &Distribution {
80        &self.dist
81    }
82
83    /// This function creates a DAEG node from DataFusion's [`ExprTreeNode`]
84    /// object. Literals are created with `Uniform` distributions with a
85    /// definite, singleton interval. Expressions with a `Boolean` data type
86    /// result in a`Bernoulli` distribution with an unknown success probability.
87    /// Any other expression starts with an `Unknown` distribution with an
88    /// indefinite range (i.e. `[-∞, ∞]`).
89    pub fn make_node(node: &ExprTreeNode<NodeIndex>, schema: &Schema) -> Result<Self> {
90        let expr = Arc::clone(&node.expr);
91        if let Some(literal) = expr.downcast_ref::<Literal>() {
92            let value = literal.value();
93            Interval::try_new(value.clone(), value.clone())
94                .and_then(|interval| Self::new_uniform(expr, interval))
95        } else {
96            expr.data_type(schema).and_then(|dt| {
97                if dt.eq(&DataType::Boolean) {
98                    Self::new_bernoulli(expr)
99                } else {
100                    Self::new_generic(expr, &dt)
101                }
102            })
103        }
104    }
105}
106
107impl ExprStatisticsGraph {
108    pub fn try_new(expr: Arc<dyn PhysicalExpr>, schema: &Schema) -> Result<Self> {
109        // Build the full graph:
110        let (root, graph) = build_dag(expr, &|node| {
111            ExprStatisticsGraphNode::make_node(node, schema)
112        })?;
113        Ok(Self { graph, root })
114    }
115
116    /// This function assigns given distributions to expressions in the DAEG.
117    /// The argument `assignments` associates indices of sought expressions
118    /// with their corresponding new distributions.
119    pub fn assign_statistics(&mut self, assignments: &[(usize, Distribution)]) {
120        for (index, stats) in assignments {
121            let node_index = NodeIndex::from(*index as DefaultIx);
122            self.graph[node_index].dist = stats.clone();
123        }
124    }
125
126    /// Computes statistics/distributions for an expression via a bottom-up
127    /// traversal.
128    pub fn evaluate_statistics(&mut self) -> Result<&Distribution> {
129        let mut dfs = DfsPostOrder::new(&self.graph, self.root);
130        while let Some(idx) = dfs.next(&self.graph) {
131            let neighbors = self.graph.neighbors_directed(idx, Outgoing);
132            let mut children_statistics = neighbors
133                .map(|child| self.graph[child].distribution())
134                .collect::<Vec<_>>();
135            // Note that all distributions are assumed to be independent.
136            if !children_statistics.is_empty() {
137                // Reverse to align with `PhysicalExpr`'s children:
138                children_statistics.reverse();
139                self.graph[idx].dist = self.graph[idx]
140                    .expr
141                    .evaluate_statistics(&children_statistics)?;
142            }
143        }
144        Ok(self.graph[self.root].distribution())
145    }
146
147    /// Runs a propagation mechanism in a top-down manner to update statistics
148    /// of leaf nodes.
149    pub fn propagate_statistics(
150        &mut self,
151        given_stats: Distribution,
152    ) -> Result<PropagationResult> {
153        // Adjust the root node with the given statistics:
154        let root_range = self.graph[self.root].dist.range()?;
155        let given_range = given_stats.range()?;
156        if let Some(interval) = root_range.intersect(&given_range)? {
157            if interval != root_range {
158                // If the given statistics enable us to obtain a more precise
159                // range for the root, update it:
160                let subset = root_range.contains(given_range)?;
161                self.graph[self.root].dist = if subset == Interval::TRUE {
162                    // Given statistics is strictly more informative, use it as is:
163                    given_stats
164                } else {
165                    // Intersecting ranges gives us a more precise range:
166                    Distribution::new_from_interval(interval)?
167                };
168            }
169        } else {
170            return Ok(PropagationResult::Infeasible);
171        }
172
173        let mut bfs = Bfs::new(&self.graph, self.root);
174
175        while let Some(node) = bfs.next(&self.graph) {
176            let neighbors = self.graph.neighbors_directed(node, Outgoing);
177            let mut children = neighbors.collect::<Vec<_>>();
178            // If the current expression is a leaf, its statistics is now final.
179            // So, just continue with the propagation procedure:
180            if children.is_empty() {
181                continue;
182            }
183            // Reverse to align with `PhysicalExpr`'s children:
184            children.reverse();
185            let children_stats = children
186                .iter()
187                .map(|child| self.graph[*child].distribution())
188                .collect::<Vec<_>>();
189            let node_statistics = self.graph[node].distribution();
190            let propagated_statistics = self.graph[node]
191                .expr
192                .propagate_statistics(node_statistics, &children_stats)?;
193            if let Some(propagated_stats) = propagated_statistics {
194                for (child_idx, stats) in children.into_iter().zip(propagated_stats) {
195                    self.graph[child_idx].dist = stats;
196                }
197            } else {
198                // The constraint is infeasible, report:
199                return Ok(PropagationResult::Infeasible);
200            }
201        }
202        Ok(PropagationResult::Success)
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use std::sync::Arc;
209
210    use crate::expressions::{Column, binary, try_cast};
211    use crate::intervals::cp_solver::PropagationResult;
212    use crate::statistics::stats_solver::ExprStatisticsGraph;
213
214    use arrow::datatypes::{DataType, Field, Schema};
215    use datafusion_common::{Result, ScalarValue};
216    use datafusion_expr_common::interval_arithmetic::Interval;
217    use datafusion_expr_common::operator::Operator;
218    use datafusion_expr_common::statistics::Distribution;
219    use datafusion_expr_common::type_coercion::binary::BinaryTypeCoercer;
220    use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
221
222    pub fn binary_expr(
223        left: Arc<dyn PhysicalExpr>,
224        op: Operator,
225        right: Arc<dyn PhysicalExpr>,
226        schema: &Schema,
227    ) -> Result<Arc<dyn PhysicalExpr>> {
228        let left_type = left.data_type(schema)?;
229        let right_type = right.data_type(schema)?;
230        let binary_type_coercer = BinaryTypeCoercer::new(&left_type, &op, &right_type);
231        let (lhs, rhs) = binary_type_coercer.get_input_types()?;
232
233        let left_expr = try_cast(left, schema, lhs)?;
234        let right_expr = try_cast(right, schema, rhs)?;
235        binary(left_expr, op, right_expr, schema)
236    }
237
238    #[test]
239    fn test_stats_integration() -> Result<()> {
240        let schema = &Schema::new(vec![
241            Field::new("a", DataType::Float64, false),
242            Field::new("b", DataType::Float64, false),
243            Field::new("c", DataType::Float64, false),
244            Field::new("d", DataType::Float64, false),
245        ]);
246
247        let a = Arc::new(Column::new("a", 0)) as _;
248        let b = Arc::new(Column::new("b", 1)) as _;
249        let c = Arc::new(Column::new("c", 2)) as _;
250        let d = Arc::new(Column::new("d", 3)) as _;
251
252        let left = binary_expr(a, Operator::Plus, b, schema)?;
253        let right = binary_expr(c, Operator::Minus, d, schema)?;
254        let expr = binary_expr(left, Operator::Eq, right, schema)?;
255
256        let mut graph = ExprStatisticsGraph::try_new(expr, schema)?;
257        // 2, 5 and 6 are BinaryExpr
258        graph.assign_statistics(&[
259            (
260                0usize,
261                Distribution::new_uniform(Interval::make(Some(0.), Some(1.))?)?,
262            ),
263            (
264                1usize,
265                Distribution::new_uniform(Interval::make(Some(0.), Some(2.))?)?,
266            ),
267            (
268                3usize,
269                Distribution::new_uniform(Interval::make(Some(1.), Some(3.))?)?,
270            ),
271            (
272                4usize,
273                Distribution::new_uniform(Interval::make(Some(1.), Some(5.))?)?,
274            ),
275        ]);
276        let ev_stats = graph.evaluate_statistics()?;
277        assert_eq!(
278            ev_stats,
279            &Distribution::new_bernoulli(ScalarValue::Float64(None))?
280        );
281
282        let one = ScalarValue::new_one(&DataType::Float64)?;
283        assert_eq!(
284            graph.propagate_statistics(Distribution::new_bernoulli(one)?)?,
285            PropagationResult::Success
286        );
287        Ok(())
288    }
289}