mz_transform/
threshold_elision.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//! Remove Threshold operators when we are certain no records have negative multiplicity.
11//!
12//! If we have Threshold(A - Subset(A)) and we believe that A has no negative multiplicities,
13//! then we can replace this with A - Subset(A).
14//!
15//! The Subset(X) notation means that the collection is a multiset subset of X:
16//! multiplicities of each record in Subset(X) are at most that of X.
17
18use mz_expr::MirRelationExpr;
19
20use crate::TransformCtx;
21use crate::analysis::{DerivedBuilder, NonNegative, SubtreeSize};
22
23/// Remove Threshold operators that have no effect.
24#[derive(Debug)]
25pub struct ThresholdElision;
26
27impl crate::Transform for ThresholdElision {
28    fn name(&self) -> &'static str {
29        "ThresholdElision"
30    }
31
32    #[mz_ore::instrument(
33        target = "optimizer",
34        level = "debug",
35        fields(path.segment = "threshold_elision")
36    )]
37    fn actually_perform_transform(
38        &self,
39        relation: &mut MirRelationExpr,
40        ctx: &mut TransformCtx,
41    ) -> Result<(), crate::TransformError> {
42        let mut builder = DerivedBuilder::new(ctx.features);
43        builder.require(NonNegative);
44        builder.require(SubtreeSize);
45        let derived = builder.visit(&*relation);
46
47        // Descend the AST, removing `Threshold` operators whose inputs are non-negative.
48        let mut todo = vec![(&mut *relation, derived.as_view())];
49        while let Some((expr, mut view)) = todo.pop() {
50            if let MirRelationExpr::Threshold { input } = expr {
51                if *view
52                    .last_child()
53                    .value::<NonNegative>()
54                    .expect("NonNegative required")
55                {
56                    *expr = input.take_dangerous();
57                    view = view.last_child();
58                }
59            }
60            todo.extend(expr.children_mut().rev().zip(view.children_rev()))
61        }
62
63        mz_repr::explain::trace_plan(&*relation);
64        Ok(())
65    }
66}