Skip to main content

datafusion_match_recognize/substrait/
export.rs

1// Licensed under the Apache License, Version 2.0 (the
2// "License"); you may not use this file except in compliance
3// with the License.  You may obtain a copy of the License at
4//
5//   http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing,
8// software distributed under the License is distributed on an
9// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
10// KIND, either express or implied.  See the License for the
11// specific language governing permissions and limitations
12// under the License.
13//
14// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.
15
16//! Recover the current source input without moving row-changing boundaries.
17
18use super::*;
19use crate::core::{MatchMetadataColumn, classifier_bits_col_name, symbol_col_name};
20use datafusion::common::ScalarValue;
21use datafusion::common::tree_node::{Transformed, TreeNode, TreeNodeRecursion};
22use datafusion::logical_expr::simplify::SimplifyContext;
23use datafusion::logical_expr::{ExprSchemable, Operator, Projection, Volatility, lit};
24use datafusion::optimizer::simplify_expressions::ExprSimplifier;
25
26/// Derive the input relation to use when exporting a matcher node.
27///
28/// This removes identity projections and generated windows used to prepare
29/// matching. Filters and other source operators remain in their current place.
30/// Custom producers must export this relation alongside the detail returned by
31/// [`encode_match_recognize_detail`].
32///
33/// # Errors
34///
35/// Returns an error if the node has no retained source, source references cannot
36/// be recovered, or a rewrite interleaves row-changing operations with matcher
37/// preparation. Recomputing navigation across such a boundary can change rows.
38pub fn export_input(node: &MatchRecognize) -> Result<LogicalPlan> {
39    let source = node.bound_source().ok_or_else(|| {
40        datafusion::common::DataFusionError::Plan(
41            "MATCH_RECOGNIZE Substrait export requires the logical node's retained BoundMatchSource"
42                .into(),
43        )
44    })?;
45    let spec = source.canonical_spec().as_spec();
46    let mut required = BTreeSet::new();
47    for expression in spec
48        .partition_by
49        .iter()
50        .chain(spec.order_by.iter().map(|sort| &sort.expr))
51        .chain(
52            spec.definitions
53                .iter()
54                .map(|definition| &definition.predicate),
55        )
56        .chain(spec.measures.iter().map(|measure| &measure.expression))
57    {
58        collect_columns(expression, &mut required)?;
59    }
60    if let MatchRecognizeOutputContract::ExplicitNamedExpressions(expressions) =
61        &spec.output
62    {
63        for expression in expressions {
64            collect_columns(&expression.expression, &mut required)?;
65        }
66    }
67    // Visible source values matter even when no predicate or measure uses them.
68    for &index in node.program().output().spec().passthrough_input_indices() {
69        let (qualifier, field) = node.input().schema().qualified_field(index);
70        let column = Column::new(qualifier.cloned(), field.name());
71        if source
72            .input()
73            .schema()
74            .qualified_field_from_column(&column)
75            .is_ok()
76        {
77            required.insert(column);
78        }
79    }
80
81    let mut input = node.input();
82    loop {
83        // A source projection or window can itself expose only source fields.
84        // Keep it rather than peeling into columns excluded by its contract.
85        if has_columns(input.schema(), &required)
86            && source_fields_only(input.schema(), source.input().schema())
87        {
88            return Ok(input.clone());
89        }
90        let child = match input {
91            LogicalPlan::Projection(projection)
92                if can_peel_projection(
93                    projection,
94                    &required,
95                    node,
96                    source.input().schema(),
97                )? =>
98            {
99                &projection.input
100            }
101            LogicalPlan::Window(window) => {
102                // Source windows remain above the boundary checked earlier.
103                // Every expression in a peeled window must be reproducible from preparation.
104                for expr in &window.window_expr {
105                    let (_, name) = expr.qualified_name();
106                    let unchanged = match node.prepared_expr(&name) {
107                        Some(expected) => same_prepared_expression(
108                            &expr.clone().unalias(),
109                            expected,
110                            window.input.schema(),
111                        )?,
112                        None => false,
113                    };
114                    if !unchanged {
115                        return plan_err!(
116                            "MATCH_RECOGNIZE Substrait export cannot preserve rewritten prepared window '{name}'"
117                        );
118                    }
119                }
120                &window.input
121            }
122            _ => break,
123        };
124        input = child;
125    }
126    for column in &required {
127        input.schema().qualified_field_from_column(column).map_err(|error| {
128            datafusion::common::DataFusionError::Plan(format!(
129                "MATCH_RECOGNIZE Substrait export cannot recover source column '{column}' from the current input: {error}"
130            ))
131        })?;
132    }
133    // A retained boundary above prepared fields would change when those fields
134    // are recalculated. In particular, LAG/LEAD must see the same row population.
135    for (qualifier, field) in input.schema().iter() {
136        let column = Column::new(qualifier.cloned(), field.name());
137        if source
138            .input()
139            .schema()
140            .qualified_field_from_column(&column)
141            .is_err()
142        {
143            return plan_err!(
144                "MATCH_RECOGNIZE Substrait export cannot preserve a rewritten input boundary containing prepared column '{column}'"
145            );
146        }
147    }
148    Ok(input.clone())
149}
150
151fn collect_columns(
152    expression: &BoundMatchExpr,
153    columns: &mut BTreeSet<Column>,
154) -> Result<()> {
155    match expression {
156        BoundMatchExpr::InputExpr(expression) => {
157            columns.extend(expression.column_refs().into_iter().cloned());
158        }
159        BoundMatchExpr::InputColumn(column) => {
160            columns.insert(column.clone());
161        }
162        BoundMatchExpr::PatternField(field) => {
163            columns.insert(field.column.clone());
164        }
165        _ => {}
166    }
167    expression.try_for_each_child(|child| collect_columns(child, columns))
168}
169
170fn has_columns(schema: &DFSchema, columns: &BTreeSet<Column>) -> bool {
171    columns
172        .iter()
173        .all(|column| schema.qualified_field_from_column(column).is_ok())
174}
175
176fn source_fields_only(schema: &DFSchema, source: &DFSchema) -> bool {
177    schema.iter().all(|(qualifier, field)| {
178        source
179            .qualified_field_from_column(&Column::new(qualifier.cloned(), field.name()))
180            .is_ok()
181    })
182}
183
184fn can_peel_projection(
185    projection: &Projection,
186    required: &BTreeSet<Column>,
187    node: &MatchRecognize,
188    source: &DFSchema,
189) -> Result<bool> {
190    let child = projection.input.schema();
191    // Required source columns can be pruned across several preparation layers.
192    // Validate each layer, then require those columns at the recovered boundary.
193    validate_prepared_projection(projection, node, source)?;
194    for column in required {
195        // Optimizer pruning can remove a DEFINE input here while its child still
196        // supplies it to a static predicate. Recover it by peeling this layer.
197        let Ok(index) = projection.schema.index_of_column(column) else {
198            continue;
199        };
200        let Expr::Column(projected) = projection.expr[index].clone().unalias() else {
201            return Ok(false);
202        };
203        let (Ok(projected_field), Ok(required_field)) = (
204            child.qualified_field_from_column(&projected),
205            child.qualified_field_from_column(column),
206        ) else {
207            return Ok(false);
208        };
209        if projected_field != required_field {
210            return Ok(false);
211        }
212    }
213    Ok(true)
214}
215
216fn validate_prepared_projection(
217    projection: &Projection,
218    node: &MatchRecognize,
219    source: &DFSchema,
220) -> Result<()> {
221    let child = projection.input.schema();
222    for (index, (qualifier, field)) in projection.schema.iter().enumerate() {
223        let column = Column::new(qualifier.cloned(), field.name());
224        if source.qualified_field_from_column(&column).is_ok() {
225            continue;
226        }
227        let actual = projection.expr[index].clone().unalias();
228        let unchanged = if let Ok(original) = child.qualified_field_from_column(&column) {
229            matches!(&actual, Expr::Column(projected)
230                if child.qualified_field_from_column(projected)? == original)
231        } else if let Some(symbol) = node
232            .program()
233            .symbols()
234            .iter()
235            .find(|symbol| symbol_col_name(symbol.name()) == *field.name())
236        {
237            let expected = match symbol.predicate().static_expr() {
238                _ if symbol.demanded_expr().is_some() => lit(true),
239                Some(expr) => crate::planning::static_define_predicate_expr(expr, child)?,
240                None => lit(true),
241            };
242            same_prepared_expression(&actual, &expected, child)?
243        } else if let Some(expected) = prepared_expression(node, field.name()) {
244            same_prepared_expression(&actual, expected, child)?
245        } else {
246            // Initial preparation also introduces runtime-owned literal placeholders.
247            is_runtime_placeholder_column(node, field.name())
248                && matches!(actual, Expr::Literal(..))
249        };
250        if !unchanged {
251            return plan_err!(
252                "MATCH_RECOGNIZE Substrait export cannot preserve rewritten prepared column '{column}': current expression {actual:?}, retained preparation {:?}",
253                prepared_expression(node, field.name())
254            );
255        }
256    }
257    Ok(())
258}
259
260fn is_runtime_placeholder_column(node: &MatchRecognize, name: &str) -> bool {
261    MatchMetadataColumn::all()
262        .iter()
263        .any(|column| column.as_ref() == name)
264        || node
265            .program()
266            .symbols()
267            .iter()
268            .any(|symbol| classifier_bits_col_name(symbol.name()) == name)
269        || node
270            .program()
271            .managed_aggregates()
272            .iter()
273            .any(|aggregate| aggregate.column_name() == name)
274}
275
276/// Compare retained preparation at the current input types.
277///
278/// First apply DataFusion's type coercion to the retained expression. If the
279/// optimized projection still differs, delegate safe, non-fallible subtrees
280/// (bound columns, lossless widening casts, pure literal expressions,
281/// comparisons, Boolean connectives, `BETWEEN`, and `IN` lists) directly to
282/// DataFusion's own [`ExprSimplifier`] so optimizer rewrites stay in lockstep
283/// without simplifying functions, volatile expressions, or fallible casts.
284pub(super) fn same_prepared_expression(
285    actual: &Expr,
286    expected: &Expr,
287    schema: &DFSchema,
288) -> Result<bool> {
289    if actual == expected {
290        return Ok(true);
291    }
292    let context = SimplifyContext::builder()
293        .with_schema(Arc::new(schema.clone()))
294        .build();
295    let simplifier = ExprSimplifier::new(context);
296    let coerced = simplifier.coerce(expected.clone(), schema)?;
297    if actual == &coerced {
298        return Ok(true);
299    }
300    let actual = canonical_prepared_tree(actual.clone(), schema, &simplifier)?;
301    let coerced = canonical_prepared_tree(coerced, schema, &simplifier)?;
302    Ok(actual == coerced)
303}
304
305fn simplify_to_fixpoint(
306    mut expr: Expr,
307    simplifier: &ExprSimplifier,
308) -> Transformed<Expr> {
309    let mut changed = false;
310    for _ in 0..4 {
311        let Ok(next) = simplifier.simplify(expr.clone()) else {
312            return Transformed::new(
313                expr,
314                changed,
315                if changed {
316                    TreeNodeRecursion::Jump
317                } else {
318                    TreeNodeRecursion::Continue
319                },
320            );
321        };
322        if next == expr {
323            break;
324        }
325        expr = next;
326        changed = true;
327    }
328    Transformed::new(expr, changed, TreeNodeRecursion::Jump)
329}
330
331fn canonical_prepared_tree(
332    expression: Expr,
333    schema: &DFSchema,
334    simplifier: &ExprSimplifier,
335) -> Result<Expr> {
336    Ok(expression
337        .transform_down_up(
338            |node| {
339                if is_simplifier_safe_expr(&node, schema)? {
340                    return Ok(simplify_to_fixpoint(node, simplifier));
341                }
342                Ok(Transformed::no(node))
343            },
344            |node| {
345                if let Expr::BinaryExpr(binary) = &node
346                    && let Some(identity) = match binary.op {
347                        Operator::And => Some(true),
348                        Operator::Or => Some(false),
349                        _ => None,
350                    }
351                {
352                    let (left, right) = (binary.left.as_ref(), binary.right.as_ref());
353                    for (literal, other) in [(left, right), (right, left)] {
354                        if matches!(
355                            literal,
356                            Expr::Literal(ScalarValue::Boolean(Some(v)), None) if *v == identity
357                        ) && other.get_type(schema)? == DataType::Boolean
358                        {
359                            return Ok(Transformed::yes(other.clone()));
360                        }
361                    }
362                }
363                Ok(Transformed::no(node))
364            },
365        )?
366        .data)
367}
368
369fn is_default_cast_field(field: &Field) -> bool {
370    field == &Field::new("", field.data_type().clone(), true)
371}
372
373fn is_pure_literal_expr(expr: &Expr) -> bool {
374    match expr {
375        Expr::Literal(..) => true,
376        Expr::Cast(cast) => {
377            is_default_cast_field(&cast.field) && is_pure_literal_expr(&cast.expr)
378        }
379        Expr::TryCast(cast) => {
380            is_default_cast_field(&cast.field) && is_pure_literal_expr(&cast.expr)
381        }
382        Expr::Negative(inner)
383        | Expr::Not(inner)
384        | Expr::IsNull(inner)
385        | Expr::IsNotNull(inner)
386        | Expr::IsTrue(inner)
387        | Expr::IsFalse(inner)
388        | Expr::IsNotTrue(inner)
389        | Expr::IsNotFalse(inner)
390        | Expr::IsUnknown(inner)
391        | Expr::IsNotUnknown(inner) => is_pure_literal_expr(inner),
392        Expr::BinaryExpr(binary) => {
393            is_pure_literal_expr(&binary.left) && is_pure_literal_expr(&binary.right)
394        }
395        Expr::Between(between) => {
396            is_pure_literal_expr(&between.expr)
397                && is_pure_literal_expr(&between.low)
398                && is_pure_literal_expr(&between.high)
399        }
400        Expr::InList(in_list) => {
401            is_pure_literal_expr(&in_list.expr)
402                && in_list.list.iter().all(is_pure_literal_expr)
403        }
404        Expr::Like(like) => {
405            is_pure_literal_expr(&like.expr) && is_pure_literal_expr(&like.pattern)
406        }
407        Expr::SimilarTo(like) => {
408            is_pure_literal_expr(&like.expr) && is_pure_literal_expr(&like.pattern)
409        }
410        Expr::Case(case) => {
411            case.expr.as_deref().is_none_or(is_pure_literal_expr)
412                && case
413                    .when_then_expr
414                    .iter()
415                    .all(|(w, t)| is_pure_literal_expr(w) && is_pure_literal_expr(t))
416                && case.else_expr.as_deref().is_none_or(is_pure_literal_expr)
417        }
418        Expr::ScalarFunction(func)
419            if func.func.signature().volatility == Volatility::Immutable =>
420        {
421            func.args.iter().all(is_pure_literal_expr)
422        }
423        _ => false,
424    }
425}
426
427fn is_simplifier_safe_expr(expr: &Expr, schema: &DFSchema) -> Result<bool> {
428    if is_pure_literal_expr(expr) {
429        return Ok(true);
430    }
431    match expr {
432        Expr::Column(_) => Ok(true),
433        Expr::Cast(cast) => {
434            if !is_default_cast_field(&cast.field) {
435                return Ok(false);
436            }
437            let Expr::Column(column) = cast.expr.as_ref() else {
438                return Ok(false);
439            };
440            let source_type = schema.qualified_field_from_column(column)?.1.data_type();
441            Ok(source_type == cast.field.data_type()
442                || lossless_integer_widening(source_type, cast.field.data_type())
443                || matches!(
444                    (source_type, cast.field.data_type()),
445                    (DataType::Float32, DataType::Float64)
446                ))
447        }
448        Expr::Not(inner)
449        | Expr::IsNull(inner)
450        | Expr::IsNotNull(inner)
451        | Expr::IsTrue(inner)
452        | Expr::IsFalse(inner)
453        | Expr::IsNotTrue(inner)
454        | Expr::IsNotFalse(inner)
455        | Expr::IsUnknown(inner)
456        | Expr::IsNotUnknown(inner) => is_simplifier_safe_expr(inner, schema),
457        Expr::Between(between) => Ok(is_simplifier_safe_expr(&between.expr, schema)?
458            && is_simplifier_safe_expr(&between.low, schema)?
459            && is_simplifier_safe_expr(&between.high, schema)?),
460        Expr::InList(in_list) => {
461            if !is_simplifier_safe_expr(&in_list.expr, schema)? {
462                return Ok(false);
463            }
464            for item in &in_list.list {
465                if !is_simplifier_safe_expr(item, schema)? {
466                    return Ok(false);
467                }
468            }
469            Ok(true)
470        }
471        Expr::BinaryExpr(binary)
472            if matches!(
473                binary.op,
474                Operator::Eq
475                    | Operator::NotEq
476                    | Operator::Lt
477                    | Operator::LtEq
478                    | Operator::Gt
479                    | Operator::GtEq
480                    | Operator::And
481                    | Operator::Or
482                    | Operator::IsDistinctFrom
483                    | Operator::IsNotDistinctFrom
484            ) =>
485        {
486            Ok(is_simplifier_safe_expr(&binary.left, schema)?
487                && is_simplifier_safe_expr(&binary.right, schema)?)
488        }
489        _ => Ok(false),
490    }
491}
492
493fn integer_domain(data_type: &DataType) -> Option<(bool, u8)> {
494    match data_type {
495        DataType::Int8 => Some((true, 8)),
496        DataType::Int16 => Some((true, 16)),
497        DataType::Int32 => Some((true, 32)),
498        DataType::Int64 => Some((true, 64)),
499        DataType::UInt8 => Some((false, 8)),
500        DataType::UInt16 => Some((false, 16)),
501        DataType::UInt32 => Some((false, 32)),
502        DataType::UInt64 => Some((false, 64)),
503        _ => None,
504    }
505}
506
507fn lossless_integer_widening(source: &DataType, target: &DataType) -> bool {
508    let (Some((source_signed, source_bits)), Some((target_signed, target_bits))) =
509        (integer_domain(source), integer_domain(target))
510    else {
511        return false;
512    };
513    match (source_signed, target_signed) {
514        (true, true) | (false, false) => source_bits <= target_bits,
515        (false, true) => source_bits < target_bits,
516        (true, false) => false,
517    }
518}
519
520fn prepared_expression<'a>(node: &'a MatchRecognize, name: &str) -> Option<&'a Expr> {
521    node.program()
522        .static_extractions()
523        .iter()
524        .find(|extraction| extraction.column_name() == name)
525        .map(|extraction| extraction.expr())
526        .or_else(|| node.prepared_expr(name))
527}