Skip to main content

datafusion_match_recognize/planning/define/
mod.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//! Common semantic admission and preparation of complete static DEFINEs.
17//!
18//! Dependency is independent of evaluator selection and compiler diagnostics.
19//! Input-only predicates can still be volatile or fallible. Preparation keeps
20//! those predicates on the matcher so only a reached transition observes them.
21
22use crate::core::{MatchMetadataColumn, classifier_bits_col_name};
23use crate::planning::logical::{BoundMatchSource, LoweredMatchSpec};
24use crate::planning::{
25    BoundMatchSpec, MatchRecognizePlanningCapabilities, MatchRecognizePlanningContext,
26};
27use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
28use datafusion::common::{Result, plan_err};
29use datafusion::logical_expr::{Expr, LogicalPlan, WindowFunctionDefinition};
30use std::collections::BTreeSet;
31use std::str::FromStr;
32
33mod cross_symbol_navigation;
34pub(crate) mod preparation;
35
36/// Borrowed semantic identities used to recognize candidate-state reads.
37///
38/// Lowered expressions never encode pattern-variable references as
39/// `Expr::Column` table qualifiers; those are already lowered into navigation
40/// windows or classifier masks. Any remaining `Expr::Column` whose name is
41/// neither a generated match column nor a fixed match metadata column is an
42/// ordinary input column, even when its table qualifier shares a pattern
43/// variable's name.
44#[derive(Clone, Copy)]
45pub(crate) struct StaticAnalysis<'a> {
46    generated_match_columns: &'a BTreeSet<String>,
47}
48
49impl<'a> StaticAnalysis<'a> {
50    pub(crate) fn new(generated_match_columns: &'a BTreeSet<String>) -> Self {
51        Self {
52            generated_match_columns,
53        }
54    }
55}
56
57/// Recognize unresolved built-in placeholders by implementation identity.
58/// Same-named user functions remain ordinary scalar input work.
59pub(crate) fn is_metadata_placeholder(
60    function: &datafusion::logical_expr::ScalarUDF,
61) -> bool {
62    use crate::functions::udf::metadata::{
63        ClassifierUdf, ExcludedUdf, MatchNumberUdf, MatchSequenceNumberUdf,
64    };
65    let implementation = function.inner();
66    implementation.is::<ClassifierUdf>()
67        || implementation.is::<ExcludedUdf>()
68        || implementation.is::<MatchNumberUdf>()
69        || implementation.is::<MatchSequenceNumberUdf>()
70}
71
72/// Direct navigation window implementations require structured source leaves.
73/// Distinct same-named user windows remain ordinary input work.
74pub(crate) fn is_navigation_window(function: &WindowFunctionDefinition) -> bool {
75    match function {
76        WindowFunctionDefinition::WindowUDF(udf) => crate::functions::udwf::functions()
77            .iter()
78            .any(|known| known.as_ref() == udf.as_ref()),
79        WindowFunctionDefinition::AggregateUDF(udaf) => {
80            crate::functions::udaf::functions()
81                .iter()
82                .any(|known| known.as_ref() == udaf.as_ref())
83        }
84    }
85}
86
87/// Semantic support required by a single normalized symbol predicate.
88#[derive(Clone, Debug, PartialEq)]
89pub struct DefineRequirement {
90    symbol: String,
91    expression: Expr,
92    match_aware: bool,
93}
94
95impl DefineRequirement {
96    /// Defining symbol in canonical spelling.
97    pub fn symbol(&self) -> &str {
98        &self.symbol
99    }
100    /// Predicate after the common safe semantic normalization.
101    pub fn expression(&self) -> &Expr {
102        &self.expression
103    }
104    /// Whether the normalized DEFINE remains match-aware.
105    pub const fn requires_match_aware_defines(&self) -> bool {
106        self.match_aware
107    }
108}
109
110/// Normalized DEFINE requirements for each pattern symbol.
111#[derive(Clone, Debug, Default, PartialEq)]
112pub struct MatchRecognizeRequirements {
113    definitions: Vec<DefineRequirement>,
114}
115
116impl MatchRecognizeRequirements {
117    /// Per-symbol requirements in source order.
118    pub fn definitions(&self) -> &[DefineRequirement] {
119        &self.definitions
120    }
121    /// Whether any normalized DEFINE remains match-aware.
122    pub fn requires_match_aware_defines(&self) -> bool {
123        self.definitions
124            .iter()
125            .any(DefineRequirement::requires_match_aware_defines)
126    }
127}
128
129pub(crate) fn requirements_for_lowered(
130    spec: &LoweredMatchSpec,
131) -> MatchRecognizeRequirements {
132    let generated = spec
133        .symbols
134        .iter()
135        .map(|symbol| classifier_bits_col_name(symbol))
136        .collect();
137    let analysis = StaticAnalysis::new(&generated);
138    MatchRecognizeRequirements {
139        definitions: spec
140            .definitions
141            .iter()
142            .map(|definition| DefineRequirement {
143                symbol: definition.symbol.clone(),
144                expression: definition.predicate.clone(),
145                match_aware: !is_static(&definition.predicate, analysis),
146            })
147            .collect(),
148    }
149}
150
151/// Analyze a request using the same validation and safe normalization as planning.
152///
153/// Source-adapter capabilities restrict which expressions the adapter can represent.
154///
155/// # Errors
156/// Returns source validation, binding, normalization, or type-resolution errors.
157pub fn analyze_match_recognize_requirements(
158    context: &mut dyn MatchRecognizePlanningContext,
159    input: &LogicalPlan,
160    spec: &BoundMatchSpec,
161    capabilities: MatchRecognizePlanningCapabilities,
162) -> Result<MatchRecognizeRequirements> {
163    let source =
164        BoundMatchSource::try_new(context, input.clone(), spec.clone(), capabilities)?;
165    Ok(source.requirements().clone())
166}
167
168/// Check a constructor-supplied static expression independently of its tag.
169pub(crate) fn validate_static_predicate(
170    symbol: &str,
171    expression: &Expr,
172    symbols: &BTreeSet<String>,
173) -> Result<()> {
174    let generated = symbols
175        .iter()
176        .flat_map(|name| {
177            [
178                crate::core::symbol_col_name(name),
179                classifier_bits_col_name(name),
180            ]
181        })
182        .collect();
183    if expression
184        .column_refs()
185        .iter()
186        .any(|column| column.name.starts_with("__mr_managed_agg_"))
187        || !is_static(expression, StaticAnalysis::new(&generated))
188    {
189        return plan_err!(
190            "MATCH_RECOGNIZE symbol '{symbol}' has a match-aware DEFINE predicate '{expression}' supplied as static input. Use 'plan_match_recognize_from_source' or supply a prepared match-aware 'LogicalSymbolInput'."
191        );
192    }
193    Ok(())
194}
195
196#[cfg(test)]
197mod tests;
198
199/// Return whether one node reads candidate-match state.
200///
201/// Match state includes columns generated by this planning pass, fixed matcher
202/// metadata, match aggregates, and match navigation window functions.
203fn is_match_aware_node(expr: &Expr, analysis: StaticAnalysis<'_>) -> bool {
204    match expr {
205        Expr::Column(col) => {
206            let name = &col.name;
207            analysis.generated_match_columns.contains(name)
208                || MatchMetadataColumn::from_str(name).is_ok()
209        }
210        // Lowering normally replaces these; a raw aggregate is still match-scoped.
211        Expr::AggregateFunction(_) => true,
212        // Low-level callers can supply unresolved placeholder objects without
213        // going through structured source normalization. Their scalar return
214        // types do not make them input-only expressions.
215        Expr::ScalarFunction(call) => is_metadata_placeholder(&call.func),
216        // Low-level callers can also supply raw match navigation window UDFs or
217        // UDAFs without metadata arguments; those still depend on candidate-match state.
218        Expr::WindowFunction(window) => is_navigation_window(&window.fun),
219        _ => false,
220    }
221}
222
223/// Return whether a window function or any of its semantic inputs reads
224/// candidate-match state.
225pub(crate) fn is_match_scoped_window(
226    wf: &datafusion::logical_expr::expr::WindowFunction,
227    analysis: StaticAnalysis<'_>,
228) -> bool {
229    is_navigation_window(&wf.fun)
230        || wf
231            .params
232            .args
233            .iter()
234            .chain(&wf.params.partition_by)
235            .chain(wf.params.filter.as_deref())
236            .chain(wf.params.order_by.iter().map(|sort| &sort.expr))
237            .any(|expr| contains_match_aware_expr(expr, analysis))
238}
239
240/// Return whether an expression tree references match state.
241fn contains_match_aware_expr(expr: &Expr, analysis: StaticAnalysis<'_>) -> bool {
242    let mut found = false;
243    // DataFusion's visitor includes window arguments, partition keys, filters,
244    // and ordering expressions.
245    let _ = expr.apply(|node| {
246        if is_match_aware_node(node, analysis) {
247            found = true;
248            return Ok(TreeNodeRecursion::Stop);
249        }
250        Ok(TreeNodeRecursion::Continue)
251    });
252    found
253}
254
255/// Return whether the expression depends only on ordered input rows.
256/// Volatility and fallibility are checked separately before eager preparation.
257pub(crate) fn is_static(expr: &Expr, analysis: StaticAnalysis<'_>) -> bool {
258    !contains_match_aware_expr(expr, analysis)
259}
260
261#[cfg(test)]
262mod analysis_tests {
263    use super::*;
264    use datafusion::logical_expr::{
265        SortExpr, WindowFunctionDefinition, col, expr::WindowFunction,
266    };
267    use std::collections::BTreeSet;
268
269    fn test_window(value: Expr) -> WindowFunction {
270        WindowFunction::new(
271            WindowFunctionDefinition::AggregateUDF(
272                datafusion::functions_aggregate::sum::sum_udaf(),
273            ),
274            vec![value],
275        )
276    }
277
278    #[test]
279    fn static_analysis_treats_input_table_qualifiers_as_static() {
280        use datafusion::common::{Column, TableReference};
281
282        let generated = BTreeSet::from(["__mr_classifier_a".into()]);
283        let analysis = StaticAnalysis::new(&generated);
284        for qualifier in [
285            TableReference::bare("src.A"),
286            TableReference::partial("schema", "src.A"),
287            TableReference::full("catalog", "schema", "src.A"),
288            TableReference::bare("a"),
289            TableReference::partial("src.with.dots", "a"),
290            TableReference::full("cat.with.dots", "schema", "A"),
291        ] {
292            let expression = Expr::Column(Column::new(Some(qualifier.clone()), "value"));
293            assert!(is_static(&expression, analysis), "{qualifier:?}");
294        }
295
296        let generated_col = Expr::Column(Column::new(
297            Some(TableReference::bare("a")),
298            "__mr_classifier_a",
299        ));
300        assert!(!is_static(&generated_col, analysis));
301    }
302
303    #[test]
304    fn window_scope_checks_each_expression_input_independently() {
305        let mut filtered = test_window(col("value"));
306        filtered.params.filter = Some(Box::new(col("__mr_classifier_a")));
307        let mut ordered = test_window(col("value"));
308        ordered.params.order_by = vec![SortExpr::new(col("__mr_path_id"), true, false)];
309        let mut partitioned = test_window(col("value"));
310        partitioned.params.partition_by = vec![col("__mr_path_id")];
311        let nested =
312            |value| test_window(Expr::WindowFunction(Box::new(test_window(value))));
313        let generated = BTreeSet::from(["__mr_classifier_a".into()]);
314        let analysis = StaticAnalysis::new(&generated);
315        for (window, match_scoped) in [
316            (nested(col("value")), false),
317            (filtered, true),
318            (ordered, true),
319            (partitioned, true),
320            (nested(col("__mr_classifier_a")), true),
321        ] {
322            assert_eq!(is_match_scoped_window(&window, analysis), match_scoped);
323            let expression = Expr::WindowFunction(Box::new(window));
324            assert_eq!(
325                is_static(&expression, analysis),
326                !match_scoped,
327                "{expression}"
328            );
329        }
330    }
331}