Skip to main content

mz_transform/
equivalence_propagation.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//! Propagates expression equivalence from leaves to root, and back down again.
11//!
12//! Expression equivalences are `MirScalarExpr` replacements by simpler expressions.
13//! These equivalences derive from
14//!   Filters:  predicates must evaluate to `Datum::True`.
15//!   Maps:     new columns equal the expressions that define them.
16//!   Joins:    equated columns must be equal.
17//!   Others:   lots of other predicates we might learn (range constraints on aggregates; non-negativity)
18//!
19//! From leaf to root the equivalences are *enforced*, and communicate that the expression will not produce rows that do not satisfy the equivalence.
20//! From root to leaf the equivalences are *advised*, and communicate that the expression may discard any outputs that do not satisfy the equivalence.
21//!
22//! Importantly, in descent the operator *may not* assume any equivalence filtering will be applied to its results.
23//! It cannot therefore produce rows it would otherwise not, even rows that do not satisfy the equivalence.
24//! Operators *may* introduce filtering in descent, and they must do so to take further advantage of the equivalences.
25//!
26//! The subtlety is due to the expressions themselves causing the equivalences, and allowing more rows may invalidate equivalences.
27//! For example, we might learn that `Column(7)` equals `Literal(3)`, but must refrain from introducing that substitution in descent,
28//! because it is possible that the equivalence derives from restrictions in the expression we are visiting. Were we certain that the
29//! equivalence was independent of the expression (e.g. through a more nuanced expression traversal) we could imaging relaxing this.
30
31use std::collections::BTreeMap;
32
33use itertools::Itertools;
34use mz_expr::{Eval, Id, MirRelationExpr, MirScalarExpr};
35use mz_repr::{Datum, ReprScalarType};
36use tracing::debug;
37
38use crate::analysis::equivalences::{
39    EqClassesImpl, EquivalenceClasses, EquivalenceClassesWithholdingErrors, Equivalences,
40    ExpressionReducer,
41};
42use mz_repr::ReprColumnType;
43
44use crate::analysis::{Arity, DerivedView, ReprRelationType};
45
46use crate::{TransformCtx, TransformError};
47
48/// Pulls up and pushes down predicate information represented as equivalences
49#[derive(Debug, Default)]
50pub struct EquivalencePropagation;
51
52impl crate::Transform for EquivalencePropagation {
53    fn name(&self) -> &'static str {
54        "EquivalencePropagation"
55    }
56
57    #[mz_ore::instrument(
58        target = "optimizer"
59        level = "trace",
60        fields(path.segment = "equivalence_propagation")
61    )]
62    fn actually_perform_transform(
63        &self,
64        relation: &mut MirRelationExpr,
65        ctx: &mut TransformCtx,
66    ) -> Result<(), TransformError> {
67        // Perform bottom-up equivalence class analysis.
68        use crate::analysis::DerivedBuilder;
69        let mut builder = DerivedBuilder::new(ctx.features);
70        builder.require(Equivalences);
71        builder.require(ReprRelationType);
72        let derived = builder.visit(relation);
73        let derived = derived.as_view();
74
75        let prior = relation.clone();
76
77        let mut get_equivalences = BTreeMap::default();
78        self.apply(
79            relation,
80            derived,
81            EquivalenceClasses::default(),
82            &mut get_equivalences,
83            ctx,
84        );
85
86        // Trace the plan as the result of `equivalence_propagation` before potentially applying
87        // `ColumnKnowledge`. (If `ColumnKnowledge` runs, it will trace its own result.)
88        mz_repr::explain::trace_plan(&*relation);
89
90        if prior == *relation {
91            let ck = crate::ColumnKnowledge::default();
92            ck.transform(relation, ctx)?;
93            if prior != *relation {
94                // This used to be tracing::error, but it became too common with
95                // dequadratic_eqprop_map.
96                tracing::info!(
97                    ?ctx.global_id,
98                    "ColumnKnowledge performed work after EquivalencePropagation",
99                );
100            }
101        }
102
103        Ok(())
104    }
105}
106
107impl EquivalencePropagation {
108    /// Provides the opportunity to mutate `relation` in response to equivalences enforced by others.
109    ///
110    /// Provides the opportunity to mutate `relation` in response to equivalences enforced by their children,
111    /// as presented in `derived`, and equivalences enforced of their output (by their ancestors), as presented
112    /// in `outer_equivalences` and `get_equivalences`.
113    ///
114    /// The mutations should never invalidate an equivalence the operator has been reported as providing, as that
115    /// information may have already been acted upon by others.
116    ///
117    /// The `expr_index` argument must equal `expr`s position in post-order, so that it can be used as a reference
118    /// into `derived`. The argument can be used with the `SubtreeSize` analysis to determine the range of values
119    /// associated with `expr`.
120    ///
121    /// After the call, `get_equivalences` will be populated with certainly equivalences that will be certainly
122    /// enforced for all uses of each identifier. The information can be harvested and propagated to the definitions
123    /// of those identifiers.
124    pub fn apply(
125        &self,
126        expr: &mut MirRelationExpr,
127        derived: DerivedView,
128        outer_equivalences: EquivalenceClasses,
129        get_equivalences: &mut BTreeMap<Id, EquivalenceClasses>,
130        ctx: &mut TransformCtx,
131    ) {
132        // TODO: The top-down traversal can be coded as a worklist, with arguments tupled and enqueued.
133        // This has the potential to do a lot more cloning (of `outer_equivalences`), and some care is needed
134        // for `get_equivalences` which would be scoped to the whole method rather than tupled and enqueued.
135        //
136        // Until then the descent recurses once per operator, so a deep plan can
137        // run the thread's stack out. `apply` cannot report an error, which
138        // rules out `CheckedRecursion`, so grow the stack instead of failing.
139        mz_ore::stack::maybe_grow(|| {
140            self.apply_stack_safe(expr, derived, outer_equivalences, get_equivalences, ctx)
141        })
142    }
143
144    fn apply_stack_safe(
145        &self,
146        expr: &mut MirRelationExpr,
147        derived: DerivedView,
148        mut outer_equivalences: EquivalenceClasses,
149        get_equivalences: &mut BTreeMap<Id, EquivalenceClasses>,
150        ctx: &mut TransformCtx,
151    ) {
152        let repr_expr_type = derived
153            .value::<ReprRelationType>()
154            .expect("ReprRelationType required");
155        assert!(repr_expr_type.is_some());
156        let expr_type: Option<&Vec<ReprColumnType>> = repr_expr_type.as_ref();
157        let expr_equivalences = derived
158            .value::<Equivalences>()
159            .expect("Equivalences required");
160
161        // `None` analysis values indicate collections that can be pruned.
162        let expr_equivalences = if let Some(e) = expr_equivalences {
163            e
164        } else {
165            expr.take_safely_with_col_types(expr_type.unwrap().clone());
166            return;
167        };
168
169        // Optimize `outer_equivalences` in the context of `expr_type`.
170        // If it ends up unsatisfiable, we can replace `expr` with an empty constant of the same relation type.
171        let reducer = expr_equivalences.reducer();
172        for class in outer_equivalences.classes.iter_mut() {
173            for expr in class.iter_mut() {
174                reducer.reduce_expr(expr);
175            }
176        }
177
178        outer_equivalences.minimize(expr_type.map(|x| &x[..]));
179        if outer_equivalences.unsatisfiable() {
180            expr.take_safely_with_col_types(expr_type.unwrap().clone());
181            return;
182        }
183
184        match expr {
185            MirRelationExpr::Constant { rows, typ: _ } => {
186                if let Ok(rows) = rows {
187                    // Expressions with an unbounded call must not be evaluated, so they take no
188                    // part below. The other members of a class are still all equal, so checking
189                    // only them keeps more rows, never fewer.
190                    let classes: Vec<Vec<_>> = outer_equivalences
191                        .classes
192                        .iter()
193                        .map(|class| class.iter().filter(|e| !e.contains_unbounded()).collect())
194                        .collect();
195                    let mut datum_vec = mz_repr::DatumVec::new();
196                    // Delete any rows that violate the equivalences.
197                    // Do not delete rows that produce errors, as they are semantically important.
198                    rows.retain(|(row, _count)| {
199                        let temp_storage = mz_repr::RowArena::new();
200                        let datums = datum_vec.borrow_with(row);
201                        classes.iter().all(|class| {
202                            // Any subset of `Ok` results must equate, or we can drop the row.
203                            let mut oks = class
204                                .iter()
205                                .filter_map(|e| e.eval(&datums[..], &temp_storage).ok());
206                            if let Some(e1) = oks.next() {
207                                oks.all(|e2| e1 == e2)
208                            } else {
209                                true
210                            }
211                        })
212                    });
213                }
214            }
215            MirRelationExpr::Get { id, .. } => {
216                // Install and intersect with other equivalences from other `Get` sites.
217                // These will be read out by the corresponding `Let` binding's `value`.
218                if let Some(equivs) = get_equivalences.get_mut(id) {
219                    *equivs = equivs.union(&outer_equivalences);
220                } else {
221                    get_equivalences.insert(*id, outer_equivalences);
222                }
223            }
224            MirRelationExpr::Let { id, .. } => {
225                let id = *id;
226                // Traverse `body` first to assemble equivalences to push to `value`.
227                // Descend without a key for `id`, treating the absence as the identity for union.
228                // `Get` nodes with identifier `id` will populate the equivalence classes with the intersection of their guarantees.
229                let mut children_rev = expr.children_mut().rev().zip_eq(derived.children_rev());
230
231                let body = children_rev.next().unwrap();
232                let value = children_rev.next().unwrap();
233
234                self.apply(
235                    body.0,
236                    body.1,
237                    outer_equivalences.clone(),
238                    get_equivalences,
239                    ctx,
240                );
241
242                // We expect to find `id` in `get_equivalences`, as otherwise the binding is
243                // not referenced and can be removed.
244                if let Some(equivalences) = get_equivalences.get(&Id::Local(id)) {
245                    self.apply(
246                        value.0,
247                        value.1,
248                        equivalences.clone(),
249                        get_equivalences,
250                        ctx,
251                    );
252                }
253            }
254            MirRelationExpr::LetRec { .. } => {
255                let mut child_iter = expr.children_mut().rev().zip_eq(derived.children_rev());
256                // Continue in `body` with the outer equivalences.
257                let (body, view) = child_iter.next().unwrap();
258                self.apply(body, view, outer_equivalences, get_equivalences, ctx);
259                // Continue recursively, but without the outer equivalences supplied to `body`.
260                for (child, view) in child_iter {
261                    self.apply(
262                        child,
263                        view,
264                        EquivalenceClasses::default(),
265                        get_equivalences,
266                        ctx,
267                    );
268                }
269            }
270            MirRelationExpr::Project { input, outputs } => {
271                // Transform `outer_equivalences` to one relevant for `input`.
272                outer_equivalences.permute(outputs);
273                self.apply(
274                    input,
275                    derived.last_child(),
276                    outer_equivalences,
277                    get_equivalences,
278                    ctx,
279                );
280            }
281            MirRelationExpr::Map { input, scalars } => {
282                // Optimize `scalars` with respect to input equivalences.
283                let input_equivalences = derived
284                    .last_child()
285                    .value::<Equivalences>()
286                    .expect("Equivalences required");
287
288                if let Some(input_equivalences_orig) = input_equivalences {
289                    // We clone `input_equivalences` only if we want to modify it, which is when
290                    // `enable_dequadratic_eqprop_map` is off. Otherwise, we work with the original
291                    // `input_equivalences`.
292                    let mut input_equivalences_cloned = None;
293                    if !ctx.features.enable_dequadratic_eqprop_map {
294                        // We mutate them for variadic Maps if the feature flag is not set.
295                        input_equivalences_cloned = Some(input_equivalences_orig.clone());
296                    }
297                    // Get all output types, to reveal a prefix to each scaler expr.
298                    let input_types: &Vec<ReprColumnType> = derived
299                        .value::<ReprRelationType>()
300                        .expect("ReprRelationType required")
301                        .as_ref()
302                        .unwrap();
303                    let input_arity = input_types.len() - scalars.len();
304                    for (index, expr) in scalars.iter_mut().enumerate() {
305                        let reducer = if !ctx.features.enable_dequadratic_eqprop_map {
306                            input_equivalences_cloned
307                                .as_ref()
308                                .expect("always filled if feature flag is not set")
309                                .reducer()
310                        } else {
311                            input_equivalences_orig.reducer()
312                        };
313                        let changed = reducer.reduce_expr(expr);
314                        if changed || !ctx.features.enable_less_reduce_in_eqprop {
315                            expr.reduce(&input_types[..(input_arity + index)]);
316                        }
317                        if !ctx.features.enable_dequadratic_eqprop_map {
318                            // Unfortunately, we had to stop doing the following, because it
319                            // was making the `Map` handling quadratic.
320                            // TODO: Get back to this when we have e-graphs.
321                            // https://github.com/MaterializeInc/database-issues/issues/9157
322                            //
323                            // Introduce the fact relating the mapped expression and corresponding
324                            // column. This allows subsequent expressions to be optimized with this
325                            // information.
326                            input_equivalences_cloned
327                                .as_mut()
328                                .expect("always filled if feature flag is not set")
329                                .classes
330                                .push(vec![
331                                    expr.clone(),
332                                    MirScalarExpr::column(input_arity + index),
333                                ]);
334                            input_equivalences_cloned
335                                .as_mut()
336                                .expect("always filled if feature flag is not set")
337                                .minimize(Some(input_types));
338                        }
339                    }
340                    let input_arity = *derived
341                        .last_child()
342                        .value::<Arity>()
343                        .expect("Arity required");
344                    outer_equivalences.project(0..input_arity);
345                    self.apply(
346                        input,
347                        derived.last_child(),
348                        outer_equivalences,
349                        get_equivalences,
350                        ctx,
351                    );
352                }
353            }
354            MirRelationExpr::FlatMap { input, exprs, .. } => {
355                // Transform `exprs` by guarantees from `input` *and* from `outer`???
356                let input_equivalences = derived
357                    .last_child()
358                    .value::<Equivalences>()
359                    .expect("Equivalences required");
360
361                if let Some(input_equivalences) = input_equivalences {
362                    let input_types: &Vec<ReprColumnType> = derived
363                        .last_child()
364                        .value::<ReprRelationType>()
365                        .expect("ReprRelationType required")
366                        .as_ref()
367                        .unwrap();
368                    let reducer = input_equivalences.reducer();
369                    for expr in exprs.iter_mut() {
370                        let changed = reducer.reduce_expr(expr);
371                        if changed || !ctx.features.enable_less_reduce_in_eqprop {
372                            expr.reduce(input_types);
373                        }
374                    }
375                    let input_arity = *derived
376                        .last_child()
377                        .value::<Arity>()
378                        .expect("Arity required");
379                    outer_equivalences.project(0..input_arity);
380                    self.apply(
381                        input,
382                        derived.last_child(),
383                        outer_equivalences,
384                        get_equivalences,
385                        ctx,
386                    );
387                }
388            }
389            MirRelationExpr::Filter { input, predicates } => {
390                // Transform `predicates` by guarantees from `input` *and* from `outer`???
391                // If we reduce based on `input` guarantees, we won't be able to push those
392                // constraints down into input, which may be fine but is worth considering.
393                let input_equivalences = derived
394                    .last_child()
395                    .value::<Equivalences>()
396                    .expect("Equivalences required");
397                if let Some(input_equivalences) = input_equivalences {
398                    let input_types: &Vec<ReprColumnType> = derived
399                        .last_child()
400                        .value::<ReprRelationType>()
401                        .expect("ReprRelationType required")
402                        .as_ref()
403                        .unwrap();
404                    let reducer = input_equivalences.reducer();
405                    for expr in predicates.iter_mut() {
406                        let changed = reducer.reduce_expr(expr);
407                        if changed || !ctx.features.enable_less_reduce_in_eqprop {
408                            expr.reduce(input_types);
409                        }
410                    }
411                    // Incorporate `predicates` into `outer_equivalences`.
412                    let mut class = predicates.clone();
413                    class.push(MirScalarExpr::literal_ok(Datum::True, ReprScalarType::Bool));
414                    outer_equivalences.classes.push(class);
415                    outer_equivalences.minimize(Some(input_types));
416                    self.apply(
417                        input,
418                        derived.last_child(),
419                        outer_equivalences,
420                        get_equivalences,
421                        ctx,
422                    );
423                }
424            }
425
426            MirRelationExpr::Join {
427                inputs,
428                equivalences,
429                ..
430            } => {
431                // Certain equivalences are ensured by each of the inputs.
432                // Other equivalences are imposed by parents of the expression.
433                // We must not weaken the properties provided by the expression to its parents,
434                // meaning we can optimize `equivalences` with respect to input guarantees,
435                // but not with respect to `outer_equivalences`.
436
437                // Each child can be presented with the integration of `join_equivalences`, `outer_equivalences`,
438                // and each input equivalence *other than* their own, projected onto the input's columns.
439
440                // Enumerate locations to find each child's analysis outputs.
441                let mut children: Vec<_> = derived.children_rev().collect::<Vec<_>>();
442                children.reverse();
443
444                // Assemble the appended input types, for use in expression minimization.
445                // Do not use `expr_types`, which may reflect nullability that does not hold for the inputs.
446                let mut input_types = Some(
447                    children
448                        .iter()
449                        .flat_map(|c| {
450                            c.value::<ReprRelationType>()
451                                .expect("ReprRelationType required")
452                                .as_ref()
453                                .unwrap()
454                                .iter()
455                                .cloned()
456                        })
457                        .collect::<Vec<_>>(),
458                );
459
460                // For each child, assemble its equivalences using join-relative column numbers.
461                // Don't do anything with the children yet, as we'll want to revisit each with
462                // this information at hand.
463                let mut columns = 0;
464                let mut input_equivalences = Vec::with_capacity(children.len());
465                for child in children.iter() {
466                    let child_arity = child.value::<Arity>().expect("Arity required");
467                    let equivalences = child
468                        .value::<Equivalences>()
469                        .expect("Equivalences required")
470                        .clone();
471
472                    if let Some(mut equivalences) = equivalences {
473                        let permutation = (columns..(columns + child_arity)).collect::<Vec<_>>();
474                        equivalences.permute(&permutation);
475                        equivalences.minimize(input_types.as_ref().map(|x| &x[..]));
476                        input_equivalences.push(equivalences);
477                    }
478                    columns += child_arity;
479                }
480
481                // Form the equivalences we will use to replace `equivalences`.
482                let mut join_equivalences: EqClassesImpl =
483                    if ctx.features.enable_eq_classes_withholding_errors {
484                        EqClassesImpl::EquivalenceClassesWithholdingErrors(
485                            EquivalenceClassesWithholdingErrors::default(),
486                        )
487                    } else {
488                        EqClassesImpl::EquivalenceClasses(EquivalenceClasses::default())
489                    };
490                join_equivalences.extend_equivalences(equivalences.clone());
491
492                // // Optionally, introduce `outer_equivalences` into `equivalences`.
493                // // This is not required, but it could be very helpful. To be seen.
494                // join_equivalences
495                //     .classes
496                //     .extend(outer_equivalences.classes.clone());
497
498                // Reduce join equivalences by the input equivalences.
499                for input_equivs in input_equivalences.iter() {
500                    let reducer = input_equivs.reducer();
501                    for class in join_equivalences
502                        .equivalence_classes_mut()
503                        .classes
504                        .iter_mut()
505                    {
506                        for expr in class.iter_mut() {
507                            // Semijoin elimination currently fails if you do more advanced simplification than
508                            // literal substitution.
509                            let old = expr.clone();
510                            let changed = reducer.reduce_expr(expr);
511                            let acceptable_sub = literal_domination(&old, expr);
512                            if changed || !ctx.features.enable_less_reduce_in_eqprop {
513                                expr.reduce(input_types.as_ref().unwrap());
514                            }
515                            if !acceptable_sub && !literal_domination(&old, expr)
516                                || expr.contains_err()
517                            {
518                                expr.clone_from(&old);
519                            }
520                        }
521                    }
522                }
523                // Remove nullability information, as it has already been incorporated from input equivalences,
524                // and if it was reduced out relative to input equivalences we don't want to re-introduce it.
525                if let Some(input_types) = input_types.as_mut() {
526                    for col in input_types.iter_mut() {
527                        col.nullable = true;
528                    }
529                }
530                join_equivalences
531                    .equivalence_classes_mut()
532                    .minimize(input_types.as_ref().map(|x| &x[..]));
533
534                // Revisit each child, determining the information to present to it, and recurring.
535                let mut columns = 0;
536                for ((index, child), expr) in
537                    children.into_iter().enumerate().zip_eq(inputs.iter_mut())
538                {
539                    let child_arity = child.value::<Arity>().expect("Arity required");
540
541                    let mut push_equivalences = join_equivalences.clone();
542                    push_equivalences.extend_equivalences(outer_equivalences.classes.clone());
543
544                    for (other, input_equivs) in input_equivalences.iter().enumerate() {
545                        if index != other {
546                            push_equivalences.extend_equivalences(input_equivs.classes.clone());
547                        }
548                    }
549                    push_equivalences.project(columns..(columns + child_arity));
550                    self.apply(
551                        expr,
552                        child,
553                        push_equivalences.equivalence_classes().clone(),
554                        get_equivalences,
555                        ctx,
556                    );
557
558                    columns += child_arity;
559                }
560
561                let extracted_equivalences =
562                    join_equivalences.extract_equivalences(input_types.as_ref().map(|x| &x[..]));
563
564                debug!(
565                    ?inputs,
566                    ?extracted_equivalences,
567                    "Join equivalences extracted"
568                );
569                equivalences.clone_from(&extracted_equivalences);
570            }
571            MirRelationExpr::Reduce {
572                input,
573                group_key,
574                aggregates,
575                ..
576            } => {
577                // TODO: MIN, MAX, ANY, ALL aggregates pass through all certain properties of their columns.
578                // This may involve projection and permutation, to reposition the information appropriately.
579                // TODO: Non-null constraints likely push down into the support of the aggregate expressions.
580
581                // Apply any equivalences about the input to key and aggregate expressions.
582                let input_equivalences = derived
583                    .last_child()
584                    .value::<Equivalences>()
585                    .expect("Equivalences required");
586                if let Some(input_equivalences) = input_equivalences {
587                    let input_type: &Vec<ReprColumnType> = derived
588                        .last_child()
589                        .value::<ReprRelationType>()
590                        .expect("ReprRelationType required")
591                        .as_ref()
592                        .unwrap();
593                    let reducer = input_equivalences.reducer();
594                    for key in group_key.iter_mut() {
595                        // Semijoin elimination currently fails if you do more advanced simplification than
596                        // literal substitution.
597                        let old_key = key.clone();
598                        let changed = reducer.reduce_expr(key);
599                        let acceptable_sub = literal_domination(&old_key, key);
600                        if changed || !ctx.features.enable_less_reduce_in_eqprop {
601                            key.reduce(input_type);
602                        }
603                        if !acceptable_sub && !literal_domination(&old_key, key) {
604                            key.clone_from(&old_key);
605                        }
606                    }
607                    for aggr in aggregates.iter_mut() {
608                        let changed = reducer.reduce_expr(&mut aggr.expr);
609                        if changed || !ctx.features.enable_less_reduce_in_eqprop {
610                            aggr.expr.reduce(input_type);
611                        }
612                        // A count expression over a non-null expression can discard the expression.
613                        if aggr.func == mz_expr::AggregateFunc::Count && !aggr.distinct {
614                            let mut probe = aggr.expr.clone().call_is_null();
615                            reducer.reduce_expr(&mut probe);
616                            if probe.is_literal_false() {
617                                aggr.expr = MirScalarExpr::literal_true();
618                            }
619                        }
620                    }
621                }
622
623                // To transform `outer_equivalences` to one about `input`, we will "pretend" to pre-pend all of
624                // the input columns, introduce equivalences about the evaluation of `group_key` on them
625                // and the key columns themselves, and then project onto these "input" columns.
626                let input_arity = *derived
627                    .last_child()
628                    .value::<Arity>()
629                    .expect("Arity required");
630                let output_arity = *derived.value::<Arity>().expect("Arity required");
631
632                // Permute `outer_equivalences` to reference columns `input_arity` later.
633                let permutation = (input_arity..(input_arity + output_arity)).collect::<Vec<_>>();
634                outer_equivalences.permute(&permutation[..]);
635                for (index, group) in group_key.iter().enumerate() {
636                    outer_equivalences.classes.push(vec![
637                        MirScalarExpr::column(input_arity + index),
638                        group.clone(),
639                    ]);
640                }
641                outer_equivalences.project(0..input_arity);
642                self.apply(
643                    input,
644                    derived.last_child(),
645                    outer_equivalences,
646                    get_equivalences,
647                    ctx,
648                );
649            }
650            MirRelationExpr::TopK {
651                input,
652                group_key,
653                limit,
654                ..
655            } => {
656                // We must be careful when updating `limit` to not install column references
657                // outside of `group_key`. We'll do this for now with `literal_domination`,
658                // which will ensure we only perform substitutions by a literal.
659                let input_equivalences = derived
660                    .last_child()
661                    .value::<Equivalences>()
662                    .expect("Equivalences required");
663                if let Some(input_equivalences) = input_equivalences {
664                    let input_types: &Vec<ReprColumnType> = derived
665                        .last_child()
666                        .value::<ReprRelationType>()
667                        .expect("ReprRelationType required")
668                        .as_ref()
669                        .unwrap();
670                    let reducer = input_equivalences.reducer();
671                    if let Some(expr) = limit {
672                        let old_expr = expr.clone();
673                        let changed = reducer.reduce_expr(expr);
674                        let acceptable_sub = literal_domination(&old_expr, expr);
675                        if changed || !ctx.features.enable_less_reduce_in_eqprop {
676                            expr.reduce(input_types);
677                        }
678                        if !acceptable_sub && !literal_domination(&old_expr, expr) {
679                            expr.clone_from(&old_expr);
680                        }
681                    }
682                }
683
684                // Discard equivalences among non-key columns, as it is not correct that `input` may drop rows
685                // that violate constraints among non-key columns without affecting the result.
686                // Project to the group_key column indices. After project, group_key[i] has been
687                // remapped to position i; permute restores the original indices.
688                outer_equivalences.project(group_key.iter().copied());
689                outer_equivalences.permute(&group_key[..]);
690                self.apply(
691                    input,
692                    derived.last_child(),
693                    outer_equivalences,
694                    get_equivalences,
695                    ctx,
696                );
697            }
698            MirRelationExpr::Negate { input } => {
699                self.apply(
700                    input,
701                    derived.last_child(),
702                    outer_equivalences,
703                    get_equivalences,
704                    ctx,
705                );
706            }
707            MirRelationExpr::Threshold { input } => {
708                self.apply(
709                    input,
710                    derived.last_child(),
711                    outer_equivalences,
712                    get_equivalences,
713                    ctx,
714                );
715            }
716            MirRelationExpr::Union { .. } => {
717                for (child, derived) in expr.children_mut().rev().zip_eq(derived.children_rev()) {
718                    self.apply(
719                        child,
720                        derived,
721                        outer_equivalences.clone(),
722                        get_equivalences,
723                        ctx,
724                    );
725                }
726            }
727            MirRelationExpr::ArrangeBy { input, .. } => {
728                // TODO: Option to alter arrangement keys, though .. terrifying.
729                self.apply(
730                    input,
731                    derived.last_child(),
732                    outer_equivalences,
733                    get_equivalences,
734                    ctx,
735                );
736            }
737        }
738    }
739}
740
741/// Logic encapsulating our willingness to accept an expression simplification.
742///
743/// For reasons of robustness, we cannot yet perform all recommended simplifications.
744/// Certain transforms expect idiomatic expressions, often around precise use of column
745/// identifiers, rather than equivalent identifiers.
746///
747/// The substitutions we are confident with are those that introduce literals for columns,
748/// or which replace column nullability checks with literals.
749fn literal_domination(old: &MirScalarExpr, new: &MirScalarExpr) -> bool {
750    let mut todo = vec![(old, new)];
751    while let Some((old, new)) = todo.pop() {
752        match (old, new) {
753            (_, MirScalarExpr::Literal(_, _)) => {
754                // Substituting a literal is always acceptable; we don't need to consult
755                // the result of the old expression to determine this.
756            }
757            (
758                MirScalarExpr::CallUnary { func: f0, expr: e0 },
759                MirScalarExpr::CallUnary { func: f1, expr: e1 },
760            ) => {
761                if f0 != f1 {
762                    return false;
763                } else {
764                    todo.push((&**e0, &**e1));
765                }
766            }
767            (
768                MirScalarExpr::CallBinary {
769                    func: f0,
770                    expr1: e01,
771                    expr2: e02,
772                },
773                MirScalarExpr::CallBinary {
774                    func: f1,
775                    expr1: e11,
776                    expr2: e12,
777                },
778            ) => {
779                if f0 != f1 {
780                    return false;
781                } else {
782                    todo.push((&**e01, &**e11));
783                    todo.push((&**e02, &**e12));
784                }
785            }
786            (
787                MirScalarExpr::CallVariadic {
788                    func: f0,
789                    exprs: e0s,
790                },
791                MirScalarExpr::CallVariadic {
792                    func: f1,
793                    exprs: e1s,
794                },
795            ) => {
796                use itertools::Itertools;
797                if f0 != f1 || e0s.len() != e1s.len() {
798                    return false;
799                } else {
800                    todo.extend(e0s.iter().zip_eq(e1s));
801                }
802            }
803            (
804                MirScalarExpr::If {
805                    cond: c0,
806                    then: t0,
807                    els: e0,
808                },
809                MirScalarExpr::If {
810                    cond: c1,
811                    then: t1,
812                    els: e1,
813                },
814            ) => {
815                todo.push((&**c0, &**c1));
816                todo.push((&**t0, &**t1));
817                todo.push((&**e0, &**e1))
818            }
819            _ => {
820                if old != new {
821                    return false;
822                }
823            }
824        }
825    }
826    true
827}