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.
910//! 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.
1718use mz_expr::MirRelationExpr;
1920use crate::TransformCtx;
21use crate::analysis::{DerivedBuilder, NonNegative, SubtreeSize};
2223/// Remove Threshold operators that have no effect.
24#[derive(Debug)]
25pub struct ThresholdElision;
2627impl crate::Transform for ThresholdElision {
28fn name(&self) -> &'static str {
29"ThresholdElision"
30}
3132#[mz_ore::instrument(
33 target = "optimizer",
34 level = "debug",
35 fields(path.segment = "threshold_elision")
36 )]
37fn actually_perform_transform(
38&self,
39 relation: &mut MirRelationExpr,
40 ctx: &mut TransformCtx,
41 ) -> Result<(), crate::TransformError> {
42let mut builder = DerivedBuilder::new(ctx.features);
43 builder.require(NonNegative);
44 builder.require(SubtreeSize);
45let derived = builder.visit(&*relation);
4647// Descend the AST, removing `Threshold` operators whose inputs are non-negative.
48let mut todo = vec![(&mut *relation, derived.as_view())];
49while let Some((expr, mut view)) = todo.pop() {
50if let MirRelationExpr::Threshold { input } = expr {
51if *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 }
6263 mz_repr::explain::trace_plan(&*relation);
64Ok(())
65 }
66}