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