mz_transform/
analysis.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Traits and types for reusable expression analysis
11
12pub mod equivalences;
13pub mod monotonic;
14
15use mz_expr::MirRelationExpr;
16
17pub use arity::Arity;
18pub use cardinality::Cardinality;
19pub use column_names::{ColumnName, ColumnNames};
20pub use common::{Derived, DerivedBuilder, DerivedView};
21pub use explain::annotate_plan;
22pub use non_negative::NonNegative;
23pub use subtree::SubtreeSize;
24pub use types::RelationType;
25pub use unique_keys::UniqueKeys;
26
27/// An analysis that can be applied bottom-up to a `MirRelationExpr`.
28pub trait Analysis: 'static {
29    /// The type of value this analysis associates with an expression.
30    type Value: std::fmt::Debug;
31    /// Announce any dependencies this analysis has on other analyses.
32    ///
33    /// The method should invoke `builder.require::<Foo>()` for each other
34    /// analysis `Foo` this analysis depends upon.
35    fn announce_dependencies(_builder: &mut DerivedBuilder) {}
36    /// The analysis value derived for an expression, given other analysis results.
37    ///
38    /// The other analysis results include the results of this analysis for all children,
39    /// in `results`, and the results of other analyses this analysis has expressed a
40    /// dependence upon, in `depends`, for children and the expression itself.
41    /// The analysis results for `Self` can only be found in `results`, and are not
42    /// available in `depends`.
43    ///
44    /// Implementors of this method must defensively check references into `results`, as
45    /// it may be invoked on `LetRec` bindings that have not yet been populated. It is up
46    /// to the analysis what to do in that case, but conservative behavior is recommended.
47    ///
48    /// The `index` indicates the post-order index for the expression, for use in finding
49    /// the corresponding information in `results` and `depends`.
50    ///
51    /// The returned result will be associated with this expression for this analysis,
52    /// and the analyses will continue.
53    fn derive(
54        &self,
55        expr: &MirRelationExpr,
56        index: usize,
57        results: &[Self::Value],
58        depends: &Derived,
59    ) -> Self::Value;
60
61    /// When available, provide a lattice interface to allow optimistic recursion.
62    ///
63    /// Providing a non-`None` output indicates that the analysis intends re-iteration.
64    fn lattice() -> Option<Box<dyn Lattice<Self::Value>>> {
65        None
66    }
67}
68
69/// Lattice methods for repeated analysis
70pub trait Lattice<T> {
71    /// An element greater than all other elements.
72    fn top(&self) -> T;
73    /// Set `a` to the greatest lower bound of `a` and `b`, and indicate if `a` changed as a result.
74    fn meet_assign(&self, a: &mut T, b: T) -> bool;
75}
76
77/// Types common across multiple analyses
78pub mod common {
79
80    use std::any::{Any, TypeId};
81    use std::collections::BTreeMap;
82
83    use mz_expr::LocalId;
84    use mz_expr::MirRelationExpr;
85    use mz_ore::assert_none;
86    use mz_repr::optimize::OptimizerFeatures;
87
88    use super::Analysis;
89    use super::subtree::SubtreeSize;
90
91    /// Container for analysis state and binding context.
92    #[derive(Default)]
93    #[allow(missing_debug_implementations)]
94    pub struct Derived {
95        /// A record of active analyses and their results, indexed by their type id.
96        analyses: BTreeMap<TypeId, Box<dyn AnalysisBundle>>,
97        /// Analyses ordered where each depends only on strictly prior analyses.
98        order: Vec<TypeId>,
99        /// Map from local identifier to result offset for analysis values.
100        bindings: BTreeMap<LocalId, usize>,
101    }
102
103    impl Derived {
104        /// Return the analysis results derived so far.
105        ///
106        /// # Panics
107        ///
108        /// This method panics if `A` was not installed as a required analysis.
109        pub fn results<A: Analysis>(&self) -> &[A::Value] {
110            let type_id = TypeId::of::<Bundle<A>>();
111            if let Some(bundle) = self.analyses.get(&type_id) {
112                if let Some(bundle) = bundle.as_any().downcast_ref::<Bundle<A>>() {
113                    return &bundle.results[..];
114                }
115            }
116            panic!("Analysis {:?} missing", std::any::type_name::<A>());
117        }
118        /// Bindings from local identifiers to result offsets for analysis values.
119        pub fn bindings(&self) -> &BTreeMap<LocalId, usize> {
120            &self.bindings
121        }
122        /// Result offsets for the state of a various number of children of the current expression.
123        ///
124        /// The integers are the zero-offset locations in the `SubtreeSize` analysis. The order of
125        /// the children is descending, from last child to first, because of how the information is
126        /// laid out, and the non-reversibility of the look-ups.
127        ///
128        /// It is an error to call this method with more children than expression has.
129        pub fn children_of_rev<'a>(
130            &'a self,
131            start: usize,
132            count: usize,
133        ) -> impl Iterator<Item = usize> + 'a {
134            let sizes = self.results::<SubtreeSize>();
135            let offset = 1;
136            (0..count).scan(offset, move |offset, _| {
137                let result = start - *offset;
138                *offset += sizes[result];
139                Some(result)
140            })
141        }
142
143        /// Recast the derived data as a view that can be subdivided into views over child state.
144        pub fn as_view<'a>(&'a self) -> DerivedView<'a> {
145            DerivedView {
146                derived: self,
147                lower: 0,
148                upper: self.results::<SubtreeSize>().len(),
149            }
150        }
151    }
152
153    /// The subset of a `Derived` corresponding to an expression and its children.
154    ///
155    /// Specifically, bounds an interval `[lower, upper)` that ends with the state
156    /// of an expression, at `upper-1`, and is preceded by the state of descendents.
157    ///
158    /// This is best thought of as a node in a tree rather
159    #[allow(missing_debug_implementations)]
160    #[derive(Copy, Clone)]
161    pub struct DerivedView<'a> {
162        derived: &'a Derived,
163        lower: usize,
164        upper: usize,
165    }
166
167    impl<'a> DerivedView<'a> {
168        /// The value associated with the expression.
169        pub fn value<A: Analysis>(&self) -> Option<&'a A::Value> {
170            self.results::<A>().last()
171        }
172
173        /// The post-order traversal index for the expression.
174        ///
175        /// This can be used to index into the full set of results, as provided by an
176        /// instance of `Derived`.
177        pub fn index(&self) -> usize {
178            self.upper - 1
179        }
180
181        /// The value bound to an identifier, if it has been derived.
182        ///
183        /// There are several reasons the value could not be derived, and this method
184        /// does not distinguish between them.
185        pub fn bound<A: Analysis>(&self, id: LocalId) -> Option<&'a A::Value> {
186            self.derived
187                .bindings
188                .get(&id)
189                .and_then(|index| self.derived.results::<A>().get(*index))
190        }
191
192        /// The results for expression and its children.
193        ///
194        /// The results for the expression itself will be the last element.
195        ///
196        /// # Panics
197        ///
198        /// This method panics if `A` was not installed as a required analysis.
199        pub fn results<A: Analysis>(&self) -> &'a [A::Value] {
200            &self.derived.results::<A>()[self.lower..self.upper]
201        }
202
203        /// Bindings from local identifiers to result offsets for analysis values.
204        ///
205        /// This method returns all bindings, which may include bindings not in scope for
206        /// the expression and its children; they should be ignored.
207        pub fn bindings(&self) -> &'a BTreeMap<LocalId, usize> {
208            self.derived.bindings()
209        }
210
211        /// Subviews over `self` corresponding to the children of the expression, in reverse order.
212        ///
213        /// These views should disjointly cover the same interval as `self`, except for the last element
214        /// which corresponds to the expression itself.
215        ///
216        /// The number of produced items should exactly match the number of children, which need not
217        /// be provided as an argument. This relies on the well-formedness of the view, which should
218        /// exhaust itself just as it enumerates its last (the first) child view.
219        pub fn children_rev(&self) -> impl Iterator<Item = DerivedView<'a>> + 'a {
220            // This logic is copy/paste from `Derived::children_of_rev` but it was annoying to layer
221            // it over the output of that function, and perhaps clearer to rewrite in any case.
222
223            // Discard the last element (the size of the expression's subtree).
224            // Repeatedly read out the last element, then peel off that many elements.
225            // Each extracted slice corresponds to a child of the current expression.
226            // We should end cleanly with an empty slice, otherwise there is an issue.
227            let sizes = self.results::<SubtreeSize>();
228            let sizes = &sizes[..sizes.len() - 1];
229
230            let offset = self.lower;
231            let derived = self.derived;
232            (0..).scan(sizes, move |sizes, _| {
233                if let Some(size) = sizes.last() {
234                    *sizes = &sizes[..sizes.len() - size];
235                    Some(Self {
236                        derived,
237                        lower: offset + sizes.len(),
238                        upper: offset + sizes.len() + size,
239                    })
240                } else {
241                    None
242                }
243            })
244        }
245
246        /// A convenience method for the view over the expressions last child.
247        ///
248        /// This method is appropriate to call on expressions with multiple children,
249        /// and in particular for `Let` and `LetRecv` variants where the body is the
250        /// last child.
251        ///
252        /// It is an error to call this on a view for an expression with no children.
253        pub fn last_child(&self) -> DerivedView<'a> {
254            self.children_rev().next().unwrap()
255        }
256    }
257
258    /// A builder wrapper to accumulate announced dependencies and construct default state.
259    #[allow(missing_debug_implementations)]
260    pub struct DerivedBuilder<'a> {
261        result: Derived,
262        features: &'a OptimizerFeatures,
263    }
264
265    impl<'a> DerivedBuilder<'a> {
266        /// Create a new [`DerivedBuilder`] parameterized by [`OptimizerFeatures`].
267        pub fn new(features: &'a OptimizerFeatures) -> Self {
268            // The default builder should include `SubtreeSize` to facilitate navigation.
269            let mut builder = DerivedBuilder {
270                result: Derived::default(),
271                features,
272            };
273            builder.require(SubtreeSize);
274            builder
275        }
276    }
277
278    impl<'a> DerivedBuilder<'a> {
279        /// Announces a dependence on an analysis `A`.
280        ///
281        /// This ensures that `A` will be performed, and before any analysis that
282        /// invokes this method.
283        pub fn require<A: Analysis>(&mut self, analysis: A) {
284            // The method recursively descends through required analyses, first
285            // installing each in `result.analyses` and second in `result.order`.
286            // The first is an obligation, and serves as an indication that we have
287            // found a cycle in dependencies.
288            let type_id = TypeId::of::<Bundle<A>>();
289            if !self.result.order.contains(&type_id) {
290                // If we have not sequenced `type_id` but have a bundle, it means
291                // we are in the process of fulfilling its requirements: a cycle.
292                if self.result.analyses.contains_key(&type_id) {
293                    panic!("Cyclic dependency detected: {}", std::any::type_name::<A>());
294                }
295                // Insert the analysis bundle first, so that we can detect cycles.
296                self.result.analyses.insert(
297                    type_id,
298                    Box::new(Bundle::<A> {
299                        analysis,
300                        results: Vec::new(),
301                        fuel: 100,
302                        allow_optimistic: self.features.enable_letrec_fixpoint_analysis,
303                    }),
304                );
305                A::announce_dependencies(self);
306                // All dependencies are successfully sequenced; sequence `type_id`.
307                self.result.order.push(type_id);
308            }
309        }
310        /// Complete the building: perform analyses and return the resulting `Derivation`.
311        pub fn visit(mut self, expr: &MirRelationExpr) -> Derived {
312            // A stack of expressions to process (`Ok`) and let bindings to fill (`Err`).
313            let mut todo = vec![Ok(expr)];
314            // Expressions in reverse post-order: each expression, followed by its children in reverse order.
315            // We will reverse this to get the post order, but must form it in reverse.
316            let mut rev_post_order = Vec::new();
317            while let Some(command) = todo.pop() {
318                match command {
319                    // An expression to visit.
320                    Ok(expr) => {
321                        match expr {
322                            MirRelationExpr::Let { id, value, body } => {
323                                todo.push(Ok(value));
324                                todo.push(Err(*id));
325                                todo.push(Ok(body));
326                            }
327                            MirRelationExpr::LetRec {
328                                ids, values, body, ..
329                            } => {
330                                for (id, value) in ids.iter().zip(values) {
331                                    todo.push(Ok(value));
332                                    todo.push(Err(*id));
333                                }
334                                todo.push(Ok(body));
335                            }
336                            _ => {
337                                todo.extend(expr.children().map(Ok));
338                            }
339                        }
340                        rev_post_order.push(expr);
341                    }
342                    // A local id to install
343                    Err(local_id) => {
344                        // Capture the *remaining* work, which we'll need to flip around.
345                        let prior = self.result.bindings.insert(local_id, rev_post_order.len());
346                        assert_none!(prior, "Shadowing not allowed");
347                    }
348                }
349            }
350            // Flip the offsets now that we know a length.
351            for value in self.result.bindings.values_mut() {
352                *value = rev_post_order.len() - *value - 1;
353            }
354            // Visit the pre-order in reverse order: post-order.
355            rev_post_order.reverse();
356
357            // Apply each analysis to `expr` in order.
358            for id in self.result.order.iter() {
359                if let Some(mut bundle) = self.result.analyses.remove(id) {
360                    bundle.analyse(&rev_post_order[..], &self.result);
361                    self.result.analyses.insert(*id, bundle);
362                }
363            }
364
365            self.result
366        }
367    }
368
369    /// An abstraction for an analysis and associated state.
370    trait AnalysisBundle: Any {
371        /// Populates internal state for all of `exprs`.
372        ///
373        /// Result indicates whether new information was produced for `exprs.last()`.
374        fn analyse(&mut self, exprs: &[&MirRelationExpr], depends: &Derived) -> bool;
375        /// Upcasts `self` to a `&dyn Any`.
376        ///
377        /// NOTE: This is required until <https://github.com/rust-lang/rfcs/issues/2765> is fixed
378        fn as_any(&self) -> &dyn std::any::Any;
379    }
380
381    /// A wrapper for analysis state.
382    struct Bundle<A: Analysis> {
383        /// The algorithm instance used to derive the results.
384        analysis: A,
385        /// A vector of results.
386        results: Vec<A::Value>,
387        /// Counts down with each `LetRec` re-iteration, to avoid unbounded effort.
388        /// Should it reach zero, the analysis should discard its results and restart as if pessimistic.
389        fuel: usize,
390        /// Allow optimistic analysis for `A` (otherwise we always do pesimistic
391        /// analysis, even if a [`crate::analysis::Lattice`] is available for `A`).
392        allow_optimistic: bool,
393    }
394
395    impl<A: Analysis> AnalysisBundle for Bundle<A> {
396        fn analyse(&mut self, exprs: &[&MirRelationExpr], depends: &Derived) -> bool {
397            self.results.clear();
398            // Attempt optimistic analysis, and if that fails go pessimistic.
399            let update = A::lattice()
400                .filter(|_| self.allow_optimistic)
401                .and_then(|lattice| {
402                    for _ in exprs.iter() {
403                        self.results.push(lattice.top());
404                    }
405                    self.analyse_optimistic(exprs, 0, exprs.len(), depends, &*lattice)
406                        .ok()
407                })
408                .unwrap_or_else(|| {
409                    self.results.clear();
410                    self.analyse_pessimistic(exprs, depends)
411                });
412            assert_eq!(self.results.len(), exprs.len());
413            update
414        }
415        fn as_any(&self) -> &dyn std::any::Any {
416            self
417        }
418    }
419
420    impl<A: Analysis> Bundle<A> {
421        /// Analysis that starts optimistically but is only correct at a fixed point.
422        ///
423        /// Will fail out to `analyse_pessimistic` if the lattice is missing, or `self.fuel` is exhausted.
424        /// When successful, the result indicates whether new information was produced for `exprs.last()`.
425        fn analyse_optimistic(
426            &mut self,
427            exprs: &[&MirRelationExpr],
428            lower: usize,
429            upper: usize,
430            depends: &Derived,
431            lattice: &dyn crate::analysis::Lattice<A::Value>,
432        ) -> Result<bool, ()> {
433            // Repeatedly re-evaluate the whole tree bottom up, until no changes of fuel spent.
434            let mut changed = true;
435            while changed {
436                changed = false;
437
438                // Bail out if we have done too many `LetRec` passes in this analysis.
439                self.fuel -= 1;
440                if self.fuel == 0 {
441                    return Err(());
442                }
443
444                // Track if repetitions may be required, to avoid iteration if they are not.
445                let mut is_recursive = false;
446                // Update each derived value and track if any have changed.
447                for index in lower..upper {
448                    let value = self.derive(exprs[index], index, depends);
449                    changed = lattice.meet_assign(&mut self.results[index], value) || changed;
450                    if let MirRelationExpr::LetRec { .. } = &exprs[index] {
451                        is_recursive = true;
452                    }
453                }
454
455                // Un-set the potential loop if there was no recursion.
456                if !is_recursive {
457                    changed = false;
458                }
459            }
460            Ok(true)
461        }
462
463        /// Analysis that starts conservatively and can be stopped at any point.
464        ///
465        /// Result indicates whether new information was produced for `exprs.last()`.
466        fn analyse_pessimistic(&mut self, exprs: &[&MirRelationExpr], depends: &Derived) -> bool {
467            // TODO: consider making iterative, from some `bottom()` up using `join_assign()`.
468            self.results.clear();
469            for (index, expr) in exprs.iter().enumerate() {
470                self.results.push(self.derive(expr, index, depends));
471            }
472            true
473        }
474
475        #[inline]
476        fn derive(&self, expr: &MirRelationExpr, index: usize, depends: &Derived) -> A::Value {
477            self.analysis
478                .derive(expr, index, &self.results[..], depends)
479        }
480    }
481}
482
483/// Expression subtree sizes
484///
485/// This analysis counts the number of expressions in each subtree, and is most useful
486/// for navigating the results of other analyses that are offset by subtree sizes.
487pub mod subtree {
488
489    use super::{Analysis, Derived};
490    use mz_expr::MirRelationExpr;
491
492    /// Analysis that determines the size in child expressions of relation expressions.
493    #[derive(Debug)]
494    pub struct SubtreeSize;
495
496    impl Analysis for SubtreeSize {
497        type Value = usize;
498
499        fn derive(
500            &self,
501            expr: &MirRelationExpr,
502            index: usize,
503            results: &[Self::Value],
504            _depends: &Derived,
505        ) -> Self::Value {
506            match expr {
507                MirRelationExpr::Constant { .. } | MirRelationExpr::Get { .. } => 1,
508                _ => {
509                    let mut offset = 1;
510                    for _ in expr.children() {
511                        offset += results[index - offset];
512                    }
513                    offset
514                }
515            }
516        }
517    }
518}
519
520/// Expression arities
521mod arity {
522
523    use super::{Analysis, Derived};
524    use mz_expr::MirRelationExpr;
525
526    /// Analysis that determines the number of columns of relation expressions.
527    #[derive(Debug)]
528    pub struct Arity;
529
530    impl Analysis for Arity {
531        type Value = usize;
532
533        fn derive(
534            &self,
535            expr: &MirRelationExpr,
536            index: usize,
537            results: &[Self::Value],
538            depends: &Derived,
539        ) -> Self::Value {
540            let mut offsets = depends
541                .children_of_rev(index, expr.children().count())
542                .map(|child| results[child])
543                .collect::<Vec<_>>();
544            offsets.reverse();
545            expr.arity_with_input_arities(offsets.into_iter())
546        }
547    }
548}
549
550/// Expression types
551mod types {
552
553    use super::{Analysis, Derived, Lattice};
554    use mz_expr::MirRelationExpr;
555    use mz_repr::ColumnType;
556
557    /// Analysis that determines the type of relation expressions.
558    ///
559    /// The value is `Some` when it discovers column types, and `None` in the case that
560    /// it has discovered no constraining information on the column types. The `None`
561    /// variant should only occur in the course of iteration, and should not be revealed
562    /// as an output of the analysis. One can `unwrap()` the result, and if it errors then
563    /// either the expression is malformed or the analysis has a bug.
564    ///
565    /// The analysis will panic if an expression is not well typed (i.e. if `try_col_with_input_cols`
566    /// returns an error).
567    #[derive(Debug)]
568    pub struct RelationType;
569
570    impl Analysis for RelationType {
571        type Value = Option<Vec<ColumnType>>;
572
573        fn derive(
574            &self,
575            expr: &MirRelationExpr,
576            index: usize,
577            results: &[Self::Value],
578            depends: &Derived,
579        ) -> Self::Value {
580            let offsets = depends
581                .children_of_rev(index, expr.children().count())
582                .map(|child| &results[child])
583                .collect::<Vec<_>>();
584
585            // For most expressions we'll apply `try_col_with_input_cols`, but for `Get` expressions
586            // we'll want to combine what we know (iteratively) with the stated `Get::typ`.
587            match expr {
588                MirRelationExpr::Get {
589                    id: mz_expr::Id::Local(i),
590                    typ,
591                    ..
592                } => {
593                    let mut result = typ.column_types.clone();
594                    if let Some(o) = depends.bindings().get(i) {
595                        if let Some(t) = results.get(*o) {
596                            if let Some(rec_typ) = t {
597                                // Reconcile nullability statements.
598                                // Unclear if we should trust `typ`.
599                                assert_eq!(result.len(), rec_typ.len());
600                                result.clone_from(rec_typ);
601                                for (res, col) in result.iter_mut().zip(typ.column_types.iter()) {
602                                    if !col.nullable {
603                                        res.nullable = false;
604                                    }
605                                }
606                            } else {
607                                // Our `None` information indicates that we are optimistically
608                                // assuming the best, including that all columns are non-null.
609                                // This should only happen in the first visit to a `Get` expr.
610                                // Use `typ`, but flatten nullability.
611                                for col in result.iter_mut() {
612                                    col.nullable = false;
613                                }
614                            }
615                        }
616                    }
617                    Some(result)
618                }
619                _ => {
620                    // Every expression with inputs should have non-`None` inputs at this point.
621                    let input_cols = offsets.into_iter().rev().map(|o| {
622                        o.as_ref()
623                            .expect("RelationType analysis discovered type-less expression")
624                    });
625                    Some(expr.try_col_with_input_cols(input_cols).unwrap())
626                }
627            }
628        }
629
630        fn lattice() -> Option<Box<dyn Lattice<Self::Value>>> {
631            Some(Box::new(RTLattice))
632        }
633    }
634
635    struct RTLattice;
636
637    impl Lattice<Option<Vec<ColumnType>>> for RTLattice {
638        fn top(&self) -> Option<Vec<ColumnType>> {
639            None
640        }
641        fn meet_assign(&self, a: &mut Option<Vec<ColumnType>>, b: Option<Vec<ColumnType>>) -> bool {
642            match (a, b) {
643                (_, None) => false,
644                (Some(a), Some(b)) => {
645                    let mut changed = false;
646                    assert_eq!(a.len(), b.len());
647                    for (at, bt) in a.iter_mut().zip(b.iter()) {
648                        assert_eq!(at.scalar_type, bt.scalar_type);
649                        if !at.nullable && bt.nullable {
650                            at.nullable = true;
651                            changed = true;
652                        }
653                    }
654                    changed
655                }
656                (a, b) => {
657                    *a = b;
658                    true
659                }
660            }
661        }
662    }
663}
664
665/// Expression unique keys
666mod unique_keys {
667
668    use super::arity::Arity;
669    use super::{Analysis, Derived, DerivedBuilder, Lattice};
670    use mz_expr::MirRelationExpr;
671
672    /// Analysis that determines the unique keys of relation expressions.
673    ///
674    /// The analysis value is a `Vec<Vec<usize>>`, which should be interpreted as a list
675    /// of sets of column identifiers, each set of which has the property that there is at
676    /// most one instance of each assignment of values to those columns.
677    ///
678    /// The sets are minimal, in that any superset of another set is removed from the list.
679    /// Any superset of unique key columns are also unique key columns.
680    #[derive(Debug)]
681    pub struct UniqueKeys;
682
683    impl Analysis for UniqueKeys {
684        type Value = Vec<Vec<usize>>;
685
686        fn announce_dependencies(builder: &mut DerivedBuilder) {
687            builder.require(Arity);
688        }
689
690        fn derive(
691            &self,
692            expr: &MirRelationExpr,
693            index: usize,
694            results: &[Self::Value],
695            depends: &Derived,
696        ) -> Self::Value {
697            let mut offsets = depends
698                .children_of_rev(index, expr.children().count())
699                .collect::<Vec<_>>();
700            offsets.reverse();
701
702            match expr {
703                MirRelationExpr::Get {
704                    id: mz_expr::Id::Local(i),
705                    typ,
706                    ..
707                } => {
708                    // We have information from `typ` and from the analysis.
709                    // We should "join" them, unioning and reducing the keys.
710                    let mut keys = typ.keys.clone();
711                    if let Some(o) = depends.bindings().get(i) {
712                        if let Some(ks) = results.get(*o) {
713                            for k in ks.iter() {
714                                antichain_insert(&mut keys, k.clone());
715                            }
716                            keys.extend(ks.iter().cloned());
717                            keys.sort();
718                            keys.dedup();
719                        }
720                    }
721                    keys
722                }
723                _ => {
724                    let arity = depends.results::<Arity>();
725                    expr.keys_with_input_keys(
726                        offsets.iter().map(|o| arity[*o]),
727                        offsets.iter().map(|o| &results[*o]),
728                    )
729                }
730            }
731        }
732
733        fn lattice() -> Option<Box<dyn Lattice<Self::Value>>> {
734            Some(Box::new(UKLattice))
735        }
736    }
737
738    fn antichain_insert(into: &mut Vec<Vec<usize>>, item: Vec<usize>) {
739        // Insert only if there is not a dominating element of `into`.
740        if into.iter().all(|key| !key.iter().all(|k| item.contains(k))) {
741            into.retain(|key| !key.iter().all(|k| item.contains(k)));
742            into.push(item);
743        }
744    }
745
746    /// Lattice for sets of columns that define a unique key.
747    ///
748    /// An element `Vec<Vec<usize>>` describes all sets of columns `Vec<usize>` that are a
749    /// superset of some set of columns in the lattice element.
750    struct UKLattice;
751
752    impl Lattice<Vec<Vec<usize>>> for UKLattice {
753        fn top(&self) -> Vec<Vec<usize>> {
754            vec![vec![]]
755        }
756        fn meet_assign(&self, a: &mut Vec<Vec<usize>>, b: Vec<Vec<usize>>) -> bool {
757            a.sort();
758            a.dedup();
759            let mut c = Vec::new();
760            for cols_a in a.iter_mut() {
761                cols_a.sort();
762                cols_a.dedup();
763                for cols_b in b.iter() {
764                    let mut cols_c = cols_a.iter().chain(cols_b).cloned().collect::<Vec<_>>();
765                    cols_c.sort();
766                    cols_c.dedup();
767                    antichain_insert(&mut c, cols_c);
768                }
769            }
770            c.sort();
771            c.dedup();
772            std::mem::swap(a, &mut c);
773            a != &mut c
774        }
775    }
776}
777
778/// Determines if accumulated frequences can be negative.
779///
780/// This analysis assumes that globally identified collection have the property, and it is
781/// incorrect to apply it to expressions that reference external collections that may have
782/// negative accumulations.
783mod non_negative {
784
785    use super::{Analysis, Derived, Lattice};
786    use crate::analysis::common_lattice::BoolLattice;
787    use mz_expr::{Id, MirRelationExpr};
788
789    /// Analysis that determines if all accumulations at all times are non-negative.
790    ///
791    /// The analysis assumes that `Id::Global` references only refer to non-negative collections.
792    #[derive(Debug)]
793    pub struct NonNegative;
794
795    impl Analysis for NonNegative {
796        type Value = bool;
797
798        fn derive(
799            &self,
800            expr: &MirRelationExpr,
801            index: usize,
802            results: &[Self::Value],
803            depends: &Derived,
804        ) -> Self::Value {
805            match expr {
806                MirRelationExpr::Constant { rows, .. } => rows
807                    .as_ref()
808                    .map(|r| r.iter().all(|(_, diff)| *diff >= mz_repr::Diff::ZERO))
809                    .unwrap_or(true),
810                MirRelationExpr::Get { id, .. } => match id {
811                    Id::Local(id) => {
812                        let index = *depends
813                            .bindings()
814                            .get(id)
815                            .expect("Dependency info not found");
816                        *results.get(index).unwrap_or(&false)
817                    }
818                    Id::Global(_) => true,
819                },
820                // Negate must be false unless input is "non-positive".
821                MirRelationExpr::Negate { .. } => false,
822                // Threshold ensures non-negativity.
823                MirRelationExpr::Threshold { .. } => true,
824                // Reduce errors on negative input.
825                MirRelationExpr::Reduce { .. } => true,
826                MirRelationExpr::Join { .. } => {
827                    // If all inputs are non-negative, the join is non-negative.
828                    depends
829                        .children_of_rev(index, expr.children().count())
830                        .all(|off| results[off])
831                }
832                MirRelationExpr::Union { base, inputs } => {
833                    // If all inputs are non-negative, the union is non-negative.
834                    let all_non_negative = depends
835                        .children_of_rev(index, expr.children().count())
836                        .all(|off| results[off]);
837
838                    if all_non_negative {
839                        return true;
840                    }
841
842                    // We look for the pattern `Union { base, Negate(Subset(base)) }`.
843                    // TODO: take some care to ensure that union fusion does not introduce a regression.
844                    if inputs.len() == 1 {
845                        if let MirRelationExpr::Negate { input } = &inputs[0] {
846                            // If `base` is non-negative, and `is_superset_of(base, input)`, return true.
847                            // TODO: this is not correct until we have `is_superset_of` validate non-negativity
848                            // as it goes, but it matches the current implementation.
849                            let mut children = depends.children_of_rev(index, 2);
850                            let _negate = children.next().unwrap();
851                            let base_id = children.next().unwrap();
852                            debug_assert_eq!(children.next(), None);
853                            if results[base_id] && is_superset_of(&*base, &*input) {
854                                return true;
855                            }
856                        }
857                    }
858
859                    false
860                }
861                _ => results[index - 1],
862            }
863        }
864
865        fn lattice() -> Option<Box<dyn Lattice<Self::Value>>> {
866            Some(Box::new(BoolLattice))
867        }
868    }
869
870    /// Returns true only if `rhs.negate().union(lhs)` contains only non-negative multiplicities
871    /// once consolidated.
872    ///
873    /// Informally, this happens when `rhs` is a multiset subset of `lhs`, meaning the multiplicity
874    /// of any record in `rhs` is at most the multiplicity of the same record in `lhs`.
875    ///
876    /// This method recursively descends each of `lhs` and `rhs` and performs a great many equality
877    /// tests, which has the potential to be quadratic. We should consider restricting its attention
878    /// to `Get` identifiers, under the premise that equal AST nodes would necessarily be identified
879    /// by common subexpression elimination. This requires care around recursively bound identifiers.
880    ///
881    /// These rules are .. somewhat arbitrary, and likely reflect observed opportunities. For example,
882    /// while we do relate `distinct(filter(A)) <= distinct(A)`, we do not relate `distinct(A) <= A`.
883    /// Further thoughts about the class of optimizations, and whether there should be more or fewer,
884    /// can be found here: <https://github.com/MaterializeInc/database-issues/issues/4044>.
885    fn is_superset_of(mut lhs: &MirRelationExpr, mut rhs: &MirRelationExpr) -> bool {
886        // This implementation is iterative.
887        // Before converting this implementation to recursive (e.g. to improve its accuracy)
888        // make sure to use the `CheckedRecursion` struct to avoid blowing the stack.
889        while lhs != rhs {
890            match rhs {
891                MirRelationExpr::Filter { input, .. } => rhs = &**input,
892                MirRelationExpr::TopK { input, .. } => rhs = &**input,
893                // Descend in both sides if the current roots are
894                // projections with the same `outputs` vector.
895                MirRelationExpr::Project {
896                    input: rhs_input,
897                    outputs: rhs_outputs,
898                } => match lhs {
899                    MirRelationExpr::Project {
900                        input: lhs_input,
901                        outputs: lhs_outputs,
902                    } if lhs_outputs == rhs_outputs => {
903                        rhs = &**rhs_input;
904                        lhs = &**lhs_input;
905                    }
906                    _ => return false,
907                },
908                // Descend in both sides if the current roots are reduces with empty aggregates
909                // on the same set of keys (that is, a distinct operation on those keys).
910                MirRelationExpr::Reduce {
911                    input: rhs_input,
912                    group_key: rhs_group_key,
913                    aggregates: rhs_aggregates,
914                    monotonic: _,
915                    expected_group_size: _,
916                } if rhs_aggregates.is_empty() => match lhs {
917                    MirRelationExpr::Reduce {
918                        input: lhs_input,
919                        group_key: lhs_group_key,
920                        aggregates: lhs_aggregates,
921                        monotonic: _,
922                        expected_group_size: _,
923                    } if lhs_aggregates.is_empty() && lhs_group_key == rhs_group_key => {
924                        rhs = &**rhs_input;
925                        lhs = &**lhs_input;
926                    }
927                    _ => return false,
928                },
929                _ => {
930                    // TODO: Imagine more complex reasoning here!
931                    return false;
932                }
933            }
934        }
935        true
936    }
937}
938
939mod column_names {
940    use std::ops::Range;
941
942    use super::Analysis;
943    use mz_expr::{AggregateFunc, Id, MirRelationExpr, MirScalarExpr};
944    use mz_repr::GlobalId;
945    use mz_repr::explain::ExprHumanizer;
946
947    /// An abstract type denoting an inferred column name.
948    #[derive(Debug, Clone)]
949    pub enum ColumnName {
950        /// A column with name inferred to be equal to a GlobalId schema column.
951        Global(GlobalId, usize),
952        /// An anonymous expression named after the top-level function name.
953        Aggregate(AggregateFunc, Box<ColumnName>),
954        /// An column with an unknown name.
955        Unknown,
956    }
957
958    impl ColumnName {
959        /// Return `true` iff this the variant is not unknown.
960        pub fn is_known(&self) -> bool {
961            matches!(self, Self::Global(..) | Self::Aggregate(..))
962        }
963
964        /// Humanize the column to a [`String`], returns an empty [`String`] for
965        /// unknown columns.
966        pub fn humanize(&self, humanizer: &dyn ExprHumanizer) -> String {
967            match self {
968                Self::Global(id, c) => humanizer.humanize_column(*id, *c).unwrap_or_default(),
969                Self::Aggregate(func, expr) => {
970                    let func = func.name();
971                    let expr = expr.humanize(humanizer);
972                    if expr.is_empty() {
973                        String::from(func)
974                    } else {
975                        format!("{func}_{expr}")
976                    }
977                }
978                Self::Unknown => String::new(),
979            }
980        }
981    }
982
983    /// Compute the column types of each subtree of a [MirRelationExpr] from the
984    /// bottom-up.
985    #[derive(Debug)]
986    pub struct ColumnNames;
987
988    impl ColumnNames {
989        /// fallback schema consisting of ordinal column names: #0, #1, ...
990        fn anonymous(range: Range<usize>) -> impl Iterator<Item = ColumnName> {
991            range.map(|_| ColumnName::Unknown)
992        }
993
994        /// fallback schema consisting of ordinal column names: #0, #1, ...
995        fn extend_with_scalars(column_names: &mut Vec<ColumnName>, scalars: &Vec<MirScalarExpr>) {
996            for scalar in scalars {
997                column_names.push(match scalar {
998                    MirScalarExpr::Column(c) => column_names[*c].clone(),
999                    _ => ColumnName::Unknown,
1000                });
1001            }
1002        }
1003    }
1004
1005    impl Analysis for ColumnNames {
1006        type Value = Vec<ColumnName>;
1007
1008        fn derive(
1009            &self,
1010            expr: &MirRelationExpr,
1011            index: usize,
1012            results: &[Self::Value],
1013            depends: &crate::analysis::Derived,
1014        ) -> Self::Value {
1015            use MirRelationExpr::*;
1016
1017            match expr {
1018                Constant { rows: _, typ } => {
1019                    // Fallback to an anonymous schema for constants.
1020                    ColumnNames::anonymous(0..typ.arity()).collect()
1021                }
1022                Get {
1023                    id: Id::Global(id),
1024                    typ,
1025                    access_strategy: _,
1026                } => {
1027                    // Emit ColumnName::Global instances for each column in the
1028                    // `Get` type. Those can be resolved to real names later when an
1029                    // ExpressionHumanizer is available.
1030                    (0..typ.columns().len())
1031                        .map(|c| ColumnName::Global(*id, c))
1032                        .collect()
1033                }
1034                Get {
1035                    id: Id::Local(id),
1036                    typ,
1037                    access_strategy: _,
1038                } => {
1039                    let index_child = *depends.bindings().get(id).expect("id in scope");
1040                    if index_child < results.len() {
1041                        results[index_child].clone()
1042                    } else {
1043                        // Possible because we infer LetRec bindings in order. This
1044                        // can be improved by introducing a fixpoint loop in the
1045                        // Env<A>::schedule_tasks LetRec handling block.
1046                        ColumnNames::anonymous(0..typ.arity()).collect()
1047                    }
1048                }
1049                Let {
1050                    id: _,
1051                    value: _,
1052                    body: _,
1053                } => {
1054                    // Return the column names of the `body`.
1055                    results[index - 1].clone()
1056                }
1057                LetRec {
1058                    ids: _,
1059                    values: _,
1060                    limits: _,
1061                    body: _,
1062                } => {
1063                    // Return the column names of the `body`.
1064                    results[index - 1].clone()
1065                }
1066                Project { input: _, outputs } => {
1067                    // Permute the column names of the input.
1068                    let input_column_names = &results[index - 1];
1069                    let mut column_names = vec![];
1070                    for col in outputs {
1071                        column_names.push(input_column_names[*col].clone());
1072                    }
1073                    column_names
1074                }
1075                Map { input: _, scalars } => {
1076                    // Extend the column names of the input with anonymous columns.
1077                    let mut column_names = results[index - 1].clone();
1078                    Self::extend_with_scalars(&mut column_names, scalars);
1079                    column_names
1080                }
1081                FlatMap {
1082                    input: _,
1083                    func,
1084                    exprs: _,
1085                } => {
1086                    // Extend the column names of the input with anonymous columns.
1087                    let mut column_names = results[index - 1].clone();
1088                    let func_output_start = column_names.len();
1089                    let func_output_end = column_names.len() + func.output_arity();
1090                    column_names.extend(Self::anonymous(func_output_start..func_output_end));
1091                    column_names
1092                }
1093                Filter {
1094                    input: _,
1095                    predicates: _,
1096                } => {
1097                    // Return the column names of the `input`.
1098                    results[index - 1].clone()
1099                }
1100                Join {
1101                    inputs: _,
1102                    equivalences: _,
1103                    implementation: _,
1104                } => {
1105                    let mut input_results = depends
1106                        .children_of_rev(index, expr.children().count())
1107                        .map(|child| &results[child])
1108                        .collect::<Vec<_>>();
1109                    input_results.reverse();
1110
1111                    let mut column_names = vec![];
1112                    for input_column_names in input_results {
1113                        column_names.extend(input_column_names.iter().cloned());
1114                    }
1115                    column_names
1116                }
1117                Reduce {
1118                    input: _,
1119                    group_key,
1120                    aggregates,
1121                    monotonic: _,
1122                    expected_group_size: _,
1123                } => {
1124                    // We clone and extend the input vector and then remove the part
1125                    // associated with the input at the end.
1126                    let mut column_names = results[index - 1].clone();
1127                    let input_arity = column_names.len();
1128
1129                    // Infer the group key part.
1130                    Self::extend_with_scalars(&mut column_names, group_key);
1131                    // Infer the aggregates part.
1132                    for aggregate in aggregates.iter() {
1133                        // The inferred name will consist of (1) the aggregate
1134                        // function name and (2) the aggregate expression (iff
1135                        // it is a simple column reference).
1136                        let func = aggregate.func.clone();
1137                        let expr = match aggregate.expr.as_column() {
1138                            Some(c) => column_names.get(c).unwrap_or(&ColumnName::Unknown).clone(),
1139                            None => ColumnName::Unknown,
1140                        };
1141                        column_names.push(ColumnName::Aggregate(func, Box::new(expr)));
1142                    }
1143                    // Remove the prefix associated with the input
1144                    column_names.drain(0..input_arity);
1145
1146                    column_names
1147                }
1148                TopK {
1149                    input: _,
1150                    group_key: _,
1151                    order_key: _,
1152                    limit: _,
1153                    offset: _,
1154                    monotonic: _,
1155                    expected_group_size: _,
1156                } => {
1157                    // Return the column names of the `input`.
1158                    results[index - 1].clone()
1159                }
1160                Negate { input: _ } => {
1161                    // Return the column names of the `input`.
1162                    results[index - 1].clone()
1163                }
1164                Threshold { input: _ } => {
1165                    // Return the column names of the `input`.
1166                    results[index - 1].clone()
1167                }
1168                Union { base: _, inputs: _ } => {
1169                    // Use the first non-empty column across all inputs.
1170                    let mut column_names = vec![];
1171
1172                    let mut inputs_results = depends
1173                        .children_of_rev(index, expr.children().count())
1174                        .map(|child| &results[child])
1175                        .collect::<Vec<_>>();
1176
1177                    let base_results = inputs_results.pop().unwrap();
1178                    inputs_results.reverse();
1179
1180                    for (i, mut column_name) in base_results.iter().cloned().enumerate() {
1181                        for input_results in inputs_results.iter() {
1182                            if !column_name.is_known() && input_results[i].is_known() {
1183                                column_name = input_results[i].clone();
1184                                break;
1185                            }
1186                        }
1187                        column_names.push(column_name);
1188                    }
1189
1190                    column_names
1191                }
1192                ArrangeBy { input: _, keys: _ } => {
1193                    // Return the column names of the `input`.
1194                    results[index - 1].clone()
1195                }
1196            }
1197        }
1198    }
1199}
1200
1201mod explain {
1202    //! Derived Analysis framework and definitions.
1203
1204    use std::collections::BTreeMap;
1205
1206    use mz_expr::MirRelationExpr;
1207    use mz_expr::explain::{ExplainContext, HumanizedExplain, HumanizerMode};
1208    use mz_ore::stack::RecursionLimitError;
1209    use mz_repr::explain::{Analyses, AnnotatedPlan};
1210
1211    use crate::analysis::equivalences::{Equivalences, HumanizedEquivalenceClasses};
1212
1213    // Analyses should have shortened paths when exported.
1214    use super::DerivedBuilder;
1215
1216    impl<'c> From<&ExplainContext<'c>> for DerivedBuilder<'c> {
1217        fn from(context: &ExplainContext<'c>) -> DerivedBuilder<'c> {
1218            let mut builder = DerivedBuilder::new(context.features);
1219            if context.config.subtree_size {
1220                builder.require(super::SubtreeSize);
1221            }
1222            if context.config.non_negative {
1223                builder.require(super::NonNegative);
1224            }
1225            if context.config.types {
1226                builder.require(super::RelationType);
1227            }
1228            if context.config.arity {
1229                builder.require(super::Arity);
1230            }
1231            if context.config.keys {
1232                builder.require(super::UniqueKeys);
1233            }
1234            if context.config.cardinality {
1235                builder.require(super::Cardinality::with_stats(
1236                    context.cardinality_stats.clone(),
1237                ));
1238            }
1239            if context.config.column_names || context.config.humanized_exprs {
1240                builder.require(super::ColumnNames);
1241            }
1242            if context.config.equivalences {
1243                builder.require(Equivalences);
1244            }
1245            builder
1246        }
1247    }
1248
1249    /// Produce an [`AnnotatedPlan`] wrapping the given [`MirRelationExpr`] along
1250    /// with [`Analyses`] derived from the given context configuration.
1251    pub fn annotate_plan<'a>(
1252        plan: &'a MirRelationExpr,
1253        context: &'a ExplainContext,
1254    ) -> Result<AnnotatedPlan<'a, MirRelationExpr>, RecursionLimitError> {
1255        let mut annotations = BTreeMap::<&MirRelationExpr, Analyses>::default();
1256        let config = context.config;
1257
1258        // We want to annotate the plan with analyses in the following cases:
1259        // 1. An Analysis was explicitly requested in the ExplainConfig.
1260        // 2. Humanized expressions were requested in the ExplainConfig (in which
1261        //    case we need to derive the ColumnNames Analysis).
1262        if config.requires_analyses() || config.humanized_exprs {
1263            // get the annotation keys
1264            let subtree_refs = plan.post_order_vec();
1265            // get the annotation values
1266            let builder = DerivedBuilder::from(context);
1267            let derived = builder.visit(plan);
1268
1269            if config.subtree_size {
1270                for (expr, subtree_size) in std::iter::zip(
1271                    subtree_refs.iter(),
1272                    derived.results::<super::SubtreeSize>().into_iter(),
1273                ) {
1274                    let analyses = annotations.entry(expr).or_default();
1275                    analyses.subtree_size = Some(*subtree_size);
1276                }
1277            }
1278            if config.non_negative {
1279                for (expr, non_negative) in std::iter::zip(
1280                    subtree_refs.iter(),
1281                    derived.results::<super::NonNegative>().into_iter(),
1282                ) {
1283                    let analyses = annotations.entry(expr).or_default();
1284                    analyses.non_negative = Some(*non_negative);
1285                }
1286            }
1287
1288            if config.arity {
1289                for (expr, arity) in std::iter::zip(
1290                    subtree_refs.iter(),
1291                    derived.results::<super::Arity>().into_iter(),
1292                ) {
1293                    let analyses = annotations.entry(expr).or_default();
1294                    analyses.arity = Some(*arity);
1295                }
1296            }
1297
1298            if config.types {
1299                for (expr, types) in std::iter::zip(
1300                    subtree_refs.iter(),
1301                    derived.results::<super::RelationType>().into_iter(),
1302                ) {
1303                    let analyses = annotations.entry(expr).or_default();
1304                    analyses.types = Some(types.clone());
1305                }
1306            }
1307
1308            if config.keys {
1309                for (expr, keys) in std::iter::zip(
1310                    subtree_refs.iter(),
1311                    derived.results::<super::UniqueKeys>().into_iter(),
1312                ) {
1313                    let analyses = annotations.entry(expr).or_default();
1314                    analyses.keys = Some(keys.clone());
1315                }
1316            }
1317
1318            if config.cardinality {
1319                for (expr, card) in std::iter::zip(
1320                    subtree_refs.iter(),
1321                    derived.results::<super::Cardinality>().into_iter(),
1322                ) {
1323                    let analyses = annotations.entry(expr).or_default();
1324                    analyses.cardinality = Some(card.to_string());
1325                }
1326            }
1327
1328            if config.column_names || config.humanized_exprs {
1329                for (expr, column_names) in std::iter::zip(
1330                    subtree_refs.iter(),
1331                    derived.results::<super::ColumnNames>().into_iter(),
1332                ) {
1333                    let analyses = annotations.entry(expr).or_default();
1334                    let value = column_names
1335                        .iter()
1336                        .map(|column_name| column_name.humanize(context.humanizer))
1337                        .collect();
1338                    analyses.column_names = Some(value);
1339                }
1340            }
1341
1342            if config.equivalences {
1343                for (expr, equivs) in std::iter::zip(
1344                    subtree_refs.iter(),
1345                    derived.results::<Equivalences>().into_iter(),
1346                ) {
1347                    let analyses = annotations.entry(expr).or_default();
1348                    analyses.equivalences = Some(match equivs.as_ref() {
1349                        Some(equivs) => HumanizedEquivalenceClasses {
1350                            equivalence_classes: equivs,
1351                            cols: analyses.column_names.as_ref(),
1352                            mode: HumanizedExplain::new(config.redacted),
1353                        }
1354                        .to_string(),
1355                        None => "<empty collection>".to_string(),
1356                    });
1357                }
1358            }
1359        }
1360
1361        Ok(AnnotatedPlan { plan, annotations })
1362    }
1363}
1364
1365/// Definition and helper structs for the [`Cardinality`] Analysis.
1366mod cardinality {
1367    use std::collections::{BTreeMap, BTreeSet};
1368
1369    use mz_expr::{
1370        BinaryFunc, Id, JoinImplementation, MirRelationExpr, MirScalarExpr, TableFunc, UnaryFunc,
1371        VariadicFunc,
1372    };
1373    use mz_ore::cast::{CastFrom, CastLossy, TryCastFrom};
1374    use mz_repr::GlobalId;
1375
1376    use ordered_float::OrderedFloat;
1377
1378    use super::{Analysis, Arity, SubtreeSize, UniqueKeys};
1379
1380    /// Compute the estimated cardinality of each subtree of a [MirRelationExpr] from the bottom up.
1381    #[allow(missing_debug_implementations)]
1382    pub struct Cardinality {
1383        /// Cardinalities for globally named entities
1384        pub stats: BTreeMap<GlobalId, usize>,
1385    }
1386
1387    impl Cardinality {
1388        /// A cardinality estimator with provided statistics for the given global identifiers
1389        pub fn with_stats(stats: BTreeMap<GlobalId, usize>) -> Self {
1390            Cardinality { stats }
1391        }
1392    }
1393
1394    impl Default for Cardinality {
1395        fn default() -> Self {
1396            Cardinality {
1397                stats: BTreeMap::new(),
1398            }
1399        }
1400    }
1401
1402    /// Cardinality estimates
1403    #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
1404    pub enum CardinalityEstimate {
1405        Unknown,
1406        Estimate(OrderedFloat<f64>),
1407    }
1408
1409    impl CardinalityEstimate {
1410        pub fn max(lhs: CardinalityEstimate, rhs: CardinalityEstimate) -> CardinalityEstimate {
1411            use CardinalityEstimate::*;
1412            match (lhs, rhs) {
1413                (Estimate(lhs), Estimate(rhs)) => Estimate(std::cmp::max(lhs, rhs)),
1414                _ => Unknown,
1415            }
1416        }
1417
1418        pub fn rounded(&self) -> Option<usize> {
1419            match self {
1420                CardinalityEstimate::Estimate(OrderedFloat(f)) => {
1421                    let rounded = f.ceil();
1422                    let flattened = usize::cast_from(
1423                        u64::try_cast_from(rounded)
1424                            .expect("positive and representable cardinality estimate"),
1425                    );
1426
1427                    Some(flattened)
1428                }
1429                CardinalityEstimate::Unknown => None,
1430            }
1431        }
1432    }
1433
1434    impl std::ops::Add for CardinalityEstimate {
1435        type Output = CardinalityEstimate;
1436
1437        fn add(self, rhs: Self) -> Self::Output {
1438            use CardinalityEstimate::*;
1439            match (self, rhs) {
1440                (Estimate(lhs), Estimate(rhs)) => Estimate(lhs + rhs),
1441                _ => Unknown,
1442            }
1443        }
1444    }
1445
1446    impl std::ops::Sub for CardinalityEstimate {
1447        type Output = CardinalityEstimate;
1448
1449        fn sub(self, rhs: Self) -> Self::Output {
1450            use CardinalityEstimate::*;
1451            match (self, rhs) {
1452                (Estimate(lhs), Estimate(rhs)) => Estimate(lhs - rhs),
1453                _ => Unknown,
1454            }
1455        }
1456    }
1457
1458    impl std::ops::Sub<CardinalityEstimate> for f64 {
1459        type Output = CardinalityEstimate;
1460
1461        fn sub(self, rhs: CardinalityEstimate) -> Self::Output {
1462            use CardinalityEstimate::*;
1463            if let Estimate(OrderedFloat(rhs)) = rhs {
1464                Estimate(OrderedFloat(self - rhs))
1465            } else {
1466                Unknown
1467            }
1468        }
1469    }
1470
1471    impl std::ops::Mul for CardinalityEstimate {
1472        type Output = CardinalityEstimate;
1473
1474        fn mul(self, rhs: Self) -> Self::Output {
1475            use CardinalityEstimate::*;
1476            match (self, rhs) {
1477                (Estimate(lhs), Estimate(rhs)) => Estimate(lhs * rhs),
1478                _ => Unknown,
1479            }
1480        }
1481    }
1482
1483    impl std::ops::Mul<f64> for CardinalityEstimate {
1484        type Output = CardinalityEstimate;
1485
1486        fn mul(self, rhs: f64) -> Self::Output {
1487            if let CardinalityEstimate::Estimate(OrderedFloat(lhs)) = self {
1488                CardinalityEstimate::Estimate(OrderedFloat(lhs * rhs))
1489            } else {
1490                CardinalityEstimate::Unknown
1491            }
1492        }
1493    }
1494
1495    impl std::ops::Div for CardinalityEstimate {
1496        type Output = CardinalityEstimate;
1497
1498        fn div(self, rhs: Self) -> Self::Output {
1499            use CardinalityEstimate::*;
1500            match (self, rhs) {
1501                (Estimate(lhs), Estimate(rhs)) => Estimate(lhs / rhs),
1502                _ => Unknown,
1503            }
1504        }
1505    }
1506
1507    impl std::ops::Div<f64> for CardinalityEstimate {
1508        type Output = CardinalityEstimate;
1509
1510        fn div(self, rhs: f64) -> Self::Output {
1511            use CardinalityEstimate::*;
1512            if let Estimate(lhs) = self {
1513                Estimate(lhs / OrderedFloat(rhs))
1514            } else {
1515                Unknown
1516            }
1517        }
1518    }
1519
1520    impl std::iter::Sum for CardinalityEstimate {
1521        fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
1522            iter.fold(CardinalityEstimate::from(0.0), |acc, elt| acc + elt)
1523        }
1524    }
1525
1526    impl std::iter::Product for CardinalityEstimate {
1527        fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
1528            iter.fold(CardinalityEstimate::from(1.0), |acc, elt| acc * elt)
1529        }
1530    }
1531
1532    impl From<usize> for CardinalityEstimate {
1533        fn from(value: usize) -> Self {
1534            Self::Estimate(OrderedFloat(f64::cast_lossy(value)))
1535        }
1536    }
1537
1538    impl From<f64> for CardinalityEstimate {
1539        fn from(value: f64) -> Self {
1540            Self::Estimate(OrderedFloat(value))
1541        }
1542    }
1543
1544    /// The default selectivity for predicates we know nothing about.
1545    ///
1546    /// But see also expr/src/scalar.rs for `FilterCharacteristics::worst_case_scaling_factor()` for a more nuanced take.
1547    pub const WORST_CASE_SELECTIVITY: OrderedFloat<f64> = OrderedFloat(0.1);
1548
1549    // This section defines how we estimate cardinality for each syntactic construct.
1550    //
1551    // We split it up into functions to make it all a bit more tractable to work with.
1552    impl Cardinality {
1553        fn flat_map(&self, tf: &TableFunc, input: CardinalityEstimate) -> CardinalityEstimate {
1554            match tf {
1555                TableFunc::Wrap { types, width } => {
1556                    input * (f64::cast_lossy(types.len()) / f64::cast_lossy(*width))
1557                }
1558                _ => {
1559                    // TODO(mgree) what explosion factor should we make up?
1560                    input * CardinalityEstimate::from(4.0)
1561                }
1562            }
1563        }
1564
1565        fn predicate(
1566            &self,
1567            predicate_expr: &MirScalarExpr,
1568            unique_columns: &BTreeSet<usize>,
1569        ) -> OrderedFloat<f64> {
1570            let index_selectivity = |expr: &MirScalarExpr| -> Option<OrderedFloat<f64>> {
1571                match expr {
1572                    MirScalarExpr::Column(col) => {
1573                        if unique_columns.contains(col) {
1574                            // TODO(mgree): when we have index cardinality statistics, they should go here when `expr` is a `MirScalarExpr::Column` that's in `unique_columns`
1575                            None
1576                        } else {
1577                            None
1578                        }
1579                    }
1580                    _ => None,
1581                }
1582            };
1583
1584            match predicate_expr {
1585                MirScalarExpr::Column(_)
1586                | MirScalarExpr::Literal(_, _)
1587                | MirScalarExpr::CallUnmaterializable(_) => OrderedFloat(1.0),
1588                MirScalarExpr::CallUnary { func, expr } => match func {
1589                    UnaryFunc::Not(_) => OrderedFloat(1.0) - self.predicate(expr, unique_columns),
1590                    UnaryFunc::IsTrue(_) | UnaryFunc::IsFalse(_) => OrderedFloat(0.5),
1591                    UnaryFunc::IsNull(_) => {
1592                        if let Some(icard) = index_selectivity(expr) {
1593                            icard
1594                        } else {
1595                            WORST_CASE_SELECTIVITY
1596                        }
1597                    }
1598                    _ => WORST_CASE_SELECTIVITY,
1599                },
1600                MirScalarExpr::CallBinary { func, expr1, expr2 } => {
1601                    match func {
1602                        BinaryFunc::Eq => {
1603                            match (index_selectivity(expr1), index_selectivity(expr2)) {
1604                                (Some(isel1), Some(isel2)) => std::cmp::max(isel1, isel2),
1605                                (Some(isel), None) | (None, Some(isel)) => isel,
1606                                (None, None) => WORST_CASE_SELECTIVITY,
1607                            }
1608                        }
1609                        // 1.0 - the Eq case
1610                        BinaryFunc::NotEq => {
1611                            match (index_selectivity(expr1), index_selectivity(expr2)) {
1612                                (Some(isel1), Some(isel2)) => {
1613                                    OrderedFloat(1.0) - std::cmp::max(isel1, isel2)
1614                                }
1615                                (Some(isel), None) | (None, Some(isel)) => OrderedFloat(1.0) - isel,
1616                                (None, None) => OrderedFloat(1.0) - WORST_CASE_SELECTIVITY,
1617                            }
1618                        }
1619                        BinaryFunc::Lt | BinaryFunc::Lte | BinaryFunc::Gt | BinaryFunc::Gte => {
1620                            // TODO(mgree) if we have high/low key values and one of the columns is an index, we can do better
1621                            OrderedFloat(0.33)
1622                        }
1623                        _ => OrderedFloat(1.0), // TOOD(mgree): are there other interesting cases?
1624                    }
1625                }
1626                MirScalarExpr::CallVariadic { func, exprs } => match func {
1627                    VariadicFunc::And => exprs
1628                        .iter()
1629                        .map(|expr| self.predicate(expr, unique_columns))
1630                        .product(),
1631                    VariadicFunc::Or => {
1632                        // TODO(mgree): BETWEEN will get compiled down to an AND of appropriate bounds---we could try to detect it and be clever
1633
1634                        // F(expr1 OR expr2) = F(expr1) + F(expr2) - F(expr1) * F(expr2), but generalized
1635                        let mut exprs = exprs.into_iter();
1636
1637                        let mut expr1;
1638
1639                        if let Some(first) = exprs.next() {
1640                            expr1 = self.predicate(first, unique_columns);
1641                        } else {
1642                            return OrderedFloat(1.0);
1643                        }
1644
1645                        for expr2 in exprs {
1646                            let expr2 = self.predicate(expr2, unique_columns);
1647                            expr1 = expr1 + expr2 - expr1 * expr2;
1648                        }
1649                        expr1
1650                    }
1651                    _ => OrderedFloat(1.0),
1652                },
1653                MirScalarExpr::If { cond: _, then, els } => std::cmp::max(
1654                    self.predicate(then, unique_columns),
1655                    self.predicate(els, unique_columns),
1656                ),
1657            }
1658        }
1659
1660        fn filter(
1661            &self,
1662            predicates: &Vec<MirScalarExpr>,
1663            keys: &Vec<Vec<usize>>,
1664            input: CardinalityEstimate,
1665        ) -> CardinalityEstimate {
1666            // TODO(mgree): should we try to do something for indices built on multiple columns?
1667            let mut unique_columns = BTreeSet::new();
1668            for key in keys {
1669                if key.len() == 1 {
1670                    unique_columns.insert(key[0]);
1671                }
1672            }
1673
1674            let mut estimate = input;
1675            for expr in predicates {
1676                let selectivity = self.predicate(expr, &unique_columns);
1677                debug_assert!(
1678                    OrderedFloat(0.0) <= selectivity && selectivity <= OrderedFloat(1.0),
1679                    "predicate selectivity {selectivity} should be in the range [0,1]"
1680                );
1681                estimate = estimate * selectivity.0;
1682            }
1683
1684            estimate
1685        }
1686
1687        fn join(
1688            &self,
1689            equivalences: &Vec<Vec<MirScalarExpr>>,
1690            _implementation: &JoinImplementation,
1691            unique_columns: BTreeMap<usize, usize>,
1692            mut inputs: Vec<CardinalityEstimate>,
1693        ) -> CardinalityEstimate {
1694            if inputs.is_empty() {
1695                return CardinalityEstimate::from(0.0);
1696            }
1697
1698            for equiv in equivalences {
1699                // those sources which have a unique key
1700                let mut unique_sources = BTreeSet::new();
1701                let mut all_unique = true;
1702
1703                for expr in equiv {
1704                    if let MirScalarExpr::Column(col) = expr {
1705                        if let Some(idx) = unique_columns.get(col) {
1706                            unique_sources.insert(*idx);
1707                        } else {
1708                            all_unique = false;
1709                        }
1710                    } else {
1711                        all_unique = false;
1712                    }
1713                }
1714
1715                // no unique columns in this equivalence
1716                if unique_sources.is_empty() {
1717                    continue;
1718                }
1719
1720                // ALL unique columns in this equivalence
1721                if all_unique {
1722                    // these inputs have unique keys for _all_ of the equivalence, so they're a bound on how many rows we'll get from those sources
1723                    // we'll find the leftmost such input and use it to hold the minimum; the other sources we set to 1.0 (so they have no effect)
1724                    let mut sources = unique_sources.iter();
1725
1726                    let lhs_idx = *sources.next().unwrap();
1727                    let mut lhs =
1728                        std::mem::replace(&mut inputs[lhs_idx], CardinalityEstimate::from(1.0));
1729                    for &rhs_idx in sources {
1730                        let rhs =
1731                            std::mem::replace(&mut inputs[rhs_idx], CardinalityEstimate::from(1.0));
1732                        lhs = CardinalityEstimate::min(lhs, rhs);
1733                    }
1734
1735                    inputs[lhs_idx] = lhs;
1736
1737                    // best option! go look at the next equivalence
1738                    continue;
1739                }
1740
1741                // some unique columns in this equivalence
1742                for idx in unique_sources {
1743                    // when joining R and S on R.x = S.x, if R.x is unique and S.x is not, we're bounded above by the cardinality of S
1744                    inputs[idx] = CardinalityEstimate::from(1.0);
1745                }
1746            }
1747
1748            let mut product = CardinalityEstimate::from(1.0);
1749            for input in inputs {
1750                product = product * input;
1751            }
1752            product
1753        }
1754
1755        fn reduce(
1756            &self,
1757            group_key: &Vec<MirScalarExpr>,
1758            expected_group_size: &Option<u64>,
1759            input: CardinalityEstimate,
1760        ) -> CardinalityEstimate {
1761            // TODO(mgree): if no `group_key` is present, we can do way better
1762
1763            if let Some(group_size) = expected_group_size {
1764                input / f64::cast_lossy(*group_size)
1765            } else if group_key.is_empty() {
1766                CardinalityEstimate::from(1.0)
1767            } else {
1768                // in the worst case, every row is its own group
1769                input
1770            }
1771        }
1772
1773        fn topk(
1774            &self,
1775            group_key: &Vec<usize>,
1776            limit: &Option<MirScalarExpr>,
1777            expected_group_size: &Option<u64>,
1778            input: CardinalityEstimate,
1779        ) -> CardinalityEstimate {
1780            // TODO: support simple arithmetic expressions
1781            let k = limit
1782                .as_ref()
1783                .and_then(|l| l.as_literal_int64())
1784                .map_or(1, |l| std::cmp::max(0, l));
1785
1786            if let Some(group_size) = expected_group_size {
1787                input * (f64::cast_lossy(k) / f64::cast_lossy(*group_size))
1788            } else if group_key.is_empty() {
1789                CardinalityEstimate::from(f64::cast_lossy(k))
1790            } else {
1791                // in the worst case, every row is its own group
1792                input.clone()
1793            }
1794        }
1795
1796        fn threshold(&self, input: CardinalityEstimate) -> CardinalityEstimate {
1797            // worst case scaling factor is 1
1798            input.clone()
1799        }
1800    }
1801
1802    impl Analysis for Cardinality {
1803        type Value = CardinalityEstimate;
1804
1805        fn announce_dependencies(builder: &mut crate::analysis::DerivedBuilder) {
1806            builder.require(crate::analysis::Arity);
1807            builder.require(crate::analysis::UniqueKeys);
1808        }
1809
1810        fn derive(
1811            &self,
1812            expr: &MirRelationExpr,
1813            index: usize,
1814            results: &[Self::Value],
1815            depends: &crate::analysis::Derived,
1816        ) -> Self::Value {
1817            use MirRelationExpr::*;
1818
1819            let sizes = depends.as_view().results::<SubtreeSize>();
1820            let arity = depends.as_view().results::<Arity>();
1821            let keys = depends.as_view().results::<UniqueKeys>();
1822
1823            match expr {
1824                Constant { rows, .. } => {
1825                    CardinalityEstimate::from(rows.as_ref().map_or_else(|_| 0, |v| v.len()))
1826                }
1827                Get { id, .. } => match id {
1828                    Id::Local(id) => depends
1829                        .bindings()
1830                        .get(id)
1831                        .and_then(|id| results.get(*id))
1832                        .copied()
1833                        .unwrap_or(CardinalityEstimate::Unknown),
1834                    Id::Global(id) => self
1835                        .stats
1836                        .get(id)
1837                        .copied()
1838                        .map(CardinalityEstimate::from)
1839                        .unwrap_or(CardinalityEstimate::Unknown),
1840                },
1841                Let { .. } | Project { .. } | Map { .. } | ArrangeBy { .. } | Negate { .. } => {
1842                    results[index - 1].clone()
1843                }
1844                LetRec { .. } =>
1845                // TODO(mgree): implement a recurrence-based approach (or at least identify common idioms, e.g. transitive closure)
1846                {
1847                    CardinalityEstimate::Unknown
1848                }
1849                Union { base: _, inputs: _ } => depends
1850                    .children_of_rev(index, expr.children().count())
1851                    .map(|off| results[off].clone())
1852                    .sum(),
1853                FlatMap { func, .. } => {
1854                    let input = results[index - 1];
1855                    self.flat_map(func, input)
1856                }
1857                Filter { predicates, .. } => {
1858                    let input = results[index - 1];
1859                    let keys = depends.results::<UniqueKeys>();
1860                    let keys = &keys[index - 1];
1861                    self.filter(predicates, keys, input)
1862                }
1863                Join {
1864                    equivalences,
1865                    implementation,
1866                    inputs,
1867                    ..
1868                } => {
1869                    let mut input_results = Vec::with_capacity(inputs.len());
1870
1871                    // maps a column to the index in `inputs` that it belongs to
1872                    let mut unique_columns = BTreeMap::new();
1873                    let mut key_offset = 0;
1874
1875                    let mut offset = 1;
1876                    for idx in 0..inputs.len() {
1877                        let input = results[index - offset];
1878                        input_results.push(input);
1879
1880                        let arity = arity[index - offset];
1881                        let keys = &keys[index - offset];
1882                        for key in keys {
1883                            if key.len() == 1 {
1884                                unique_columns.insert(key_offset + key[0], idx);
1885                            }
1886                        }
1887                        key_offset += arity;
1888
1889                        offset += &sizes[index - offset];
1890                    }
1891
1892                    self.join(equivalences, implementation, unique_columns, input_results)
1893                }
1894                Reduce {
1895                    group_key,
1896                    expected_group_size,
1897                    ..
1898                } => {
1899                    let input = results[index - 1];
1900                    self.reduce(group_key, expected_group_size, input)
1901                }
1902                TopK {
1903                    group_key,
1904                    limit,
1905                    expected_group_size,
1906                    ..
1907                } => {
1908                    let input = results[index - 1];
1909                    self.topk(group_key, limit, expected_group_size, input)
1910                }
1911                Threshold { .. } => {
1912                    let input = results[index - 1];
1913                    self.threshold(input)
1914                }
1915            }
1916        }
1917    }
1918
1919    impl std::fmt::Display for CardinalityEstimate {
1920        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1921            match self {
1922                CardinalityEstimate::Estimate(OrderedFloat(estimate)) => write!(f, "{estimate}"),
1923                CardinalityEstimate::Unknown => write!(f, "<UNKNOWN>"),
1924            }
1925        }
1926    }
1927}
1928
1929mod common_lattice {
1930    use crate::analysis::Lattice;
1931
1932    pub struct BoolLattice;
1933
1934    impl Lattice<bool> for BoolLattice {
1935        // `true` > `false`.
1936        fn top(&self) -> bool {
1937            true
1938        }
1939        // `false` is the greatest lower bound. `into` changes if it's true and `item` is false.
1940        fn meet_assign(&self, into: &mut bool, item: bool) -> bool {
1941            let changed = *into && !item;
1942            *into = *into && item;
1943            changed
1944        }
1945    }
1946}