datafusion-match-recognize 0.56.1

SQL MATCH_RECOGNIZE row-pattern matching for Apache DataFusion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
// Licensed under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

//! Preserves window filters and null treatment around DataFusion's codec.

use super::schema::to_substrait_type;
use super::*;
use datafusion::logical_expr::ExprSchemable;
use datafusion::logical_expr::expr::{
    NullTreatment, WindowFunction as DataFusionWindowFunction,
};
use datafusion_substrait::logical_plan::consumer::from_window_function as decode_standard_window;
use datafusion_substrait::logical_plan::producer::from_window_function as encode_standard_window;
use datafusion_substrait::substrait::proto::expression::RexType;
use datafusion_substrait::substrait::proto::expression::WindowFunction as SubstraitWindowFunction;
use datafusion_substrait::substrait::proto::function_argument::ArgType;
use datafusion_substrait::substrait::proto::sort_field::{SortDirection, SortKind};
use datafusion_substrait::substrait::proto::{
    Expression, FunctionArgument, FunctionOption,
};

const WRAPPER_PREFIX: &str = "match_recognize_window_modifiers_v1__";
const OPTION_PREFIX: &str = "match_recognize.window_modifiers_v1.";
const FILTER_OPTION: &str = "match_recognize.window_modifiers_v1.filter";
const NULL_TREATMENT_OPTION: &str = "match_recognize.window_modifiers_v1.null_treatment";
const FILTER_LAYOUT: &str = "LAST_ARGUMENT_V1";
const IGNORE_NULLS: &str = "IGNORE_NULLS";
const RESPECT_NULLS: &str = "RESPECT_NULLS";

pub(super) fn encode_window_function(
    producer: &mut impl SubstraitProducer,
    window_fn: &DataFusionWindowFunction,
    schema: &DFSchemaRef,
) -> Result<Expression> {
    let params = &window_fn.params;
    let has_private_modifiers =
        params.filter.is_some() || params.null_treatment.is_some();
    if !has_private_modifiers {
        return encode_standard_window(producer, window_fn, schema);
    }

    let mut standard_window = window_fn.clone();
    standard_window.params.filter = None;
    standard_window.params.null_treatment = None;
    let mut encoded = encode_standard_window(producer, &standard_window, schema)?;
    let RexType::WindowFunction(window) = encoded.rex_type.as_mut().ok_or_else(|| {
        datafusion::common::DataFusionError::Internal(
            "standard Substrait window encoder returned an empty expression".to_string(),
        )
    })?
    else {
        return plan_err!(
            "standard Substrait window encoder returned a non-window expression"
        );
    };

    // Prefixing the function reference makes generic consumers reject this
    // private format instead of mistaking the appended filter for a user argument.
    let original_signature = window_fn.fun.to_string();
    window.function_reference =
        producer.register_function(format!("{WRAPPER_PREFIX}{original_signature}"));

    if let Some(filter) = &params.filter {
        let original_argument_count = window.arguments.len();
        window.arguments.push(FunctionArgument {
            arg_type: Some(ArgType::Value(producer.handle_expr(filter, schema)?)),
        });
        window.options.push(FunctionOption {
            name: FILTER_OPTION.to_string(),
            preference: vec![format!("{FILTER_LAYOUT}:{original_argument_count}")],
        });
    }

    if let Some(null_treatment) = params.null_treatment {
        let preference = match null_treatment {
            NullTreatment::IgnoreNulls => IGNORE_NULLS,
            NullTreatment::RespectNulls => RESPECT_NULLS,
        };
        window.options.push(FunctionOption {
            name: NULL_TREATMENT_OPTION.to_string(),
            preference: vec![preference.to_string()],
        });
    }

    Ok(encoded)
}

pub(super) async fn decode_window_function(
    consumer: &impl SubstraitConsumer,
    window: &SubstraitWindowFunction,
    input_schema: &DFSchema,
) -> Result<Expr> {
    validate_supported_standard_fields(window)?;
    let wrapper_signature = consumer
        .get_extensions()
        .functions
        .get(&window.function_reference)
        .ok_or_else(|| {
            datafusion::common::DataFusionError::Plan(format!(
                "Window function not found: function reference = {}",
                window.function_reference
            ))
        })?
        .clone();
    let wrapped_original = wrapper_signature.strip_prefix(WRAPPER_PREFIX);

    let Some(original_signature) = wrapped_original else {
        validate_unwrapped_options(&window.options)?;
        return decode_standard_window(consumer, window, input_schema).await;
    };
    if original_signature.is_empty() {
        return plan_err!("MATCH_RECOGNIZE window wrapper has no function name");
    }
    let mut window = window.clone();
    let original_anchor = consumer
        .get_extensions()
        .functions
        .iter()
        .find_map(|(anchor, signature)| {
            (signature == original_signature).then_some(*anchor)
        })
        .ok_or_else(|| {
            datafusion::common::DataFusionError::Plan(format!(
                "MATCH_RECOGNIZE window wrapper is missing original function anchor '{original_signature}'"
            ))
        })?;
    window.function_reference = original_anchor;
    let modifiers = decode_options(&mut window.options)?;

    let filter = if let Some(original_argument_count) = modifiers.filter_argument_count {
        let encoded_argument_count =
            original_argument_count.checked_add(1).ok_or_else(|| {
                datafusion::common::DataFusionError::Plan(
                    "MATCH_RECOGNIZE window filter argument count overflows usize"
                        .to_string(),
                )
            })?;
        if window.arguments.len() != encoded_argument_count {
            return plan_err!(
                "MATCH_RECOGNIZE filtered window expected {} function arguments plus one filter argument, got {} total arguments",
                original_argument_count,
                window.arguments.len()
            );
        }
        let filter_argument = window.arguments.pop().ok_or_else(|| {
            datafusion::common::DataFusionError::Plan(
                "MATCH_RECOGNIZE filtered window is missing its final filter argument"
                    .to_string(),
            )
        })?;
        let Some(ArgType::Value(filter)) = filter_argument.arg_type else {
            return plan_err!(
                "MATCH_RECOGNIZE filtered window final argument must be a value expression"
            );
        };
        Some(consumer.consume_expression(&filter, input_schema).await?)
    } else {
        None
    };

    // Delegate the standard expression unchanged after removing the private
    // representation, then restore the two modifiers owned by this envelope.
    let mut decoded = decode_standard_window(consumer, &window, input_schema).await?;
    let Expr::WindowFunction(decoded_window) = &mut decoded else {
        return plan_err!(
            "standard Substrait window decoder returned a non-window expression"
        );
    };
    if modifiers.filter_argument_count.is_none() && modifiers.null_treatment.is_none() {
        return plan_err!("MATCH_RECOGNIZE window wrapper has no modifiers");
    }
    decoded_window.params.filter = filter.map(Box::new);
    decoded_window.params.null_treatment = modifiers.null_treatment;
    validate_output_type(consumer, &window, &decoded, input_schema)?;
    Ok(decoded)
}

fn validate_unwrapped_options(options: &[FunctionOption]) -> Result<()> {
    let Some(option) = options.first() else {
        return Ok(());
    };
    if option.name.to_ascii_lowercase().starts_with(OPTION_PREFIX) {
        return plan_err!(
            "MATCH_RECOGNIZE private window options require the versioned wrapper anchor"
        );
    }
    plan_err!("unsupported Substrait window option '{}'", option.name)
}

#[expect(deprecated)]
fn validate_supported_standard_fields(window: &SubstraitWindowFunction) -> Result<()> {
    if !window.args.is_empty() {
        return plan_err!(
            "MATCH_RECOGNIZE Substrait window does not support deprecated args"
        );
    }
    for (index, sort) in window.sorts.iter().enumerate() {
        if sort.expr.is_none() {
            return plan_err!(
                "MATCH_RECOGNIZE Substrait window sort {index} is missing its expression"
            );
        }
        match &sort.sort_kind {
            Some(SortKind::Direction(direction)) => {
                match SortDirection::try_from(*direction) {
                    Ok(
                        SortDirection::AscNullsFirst
                        | SortDirection::AscNullsLast
                        | SortDirection::DescNullsFirst
                        | SortDirection::DescNullsLast,
                    ) => {}
                    Ok(direction) => {
                        return plan_err!(
                            "MATCH_RECOGNIZE Substrait window sort {index} has unsupported direction {}",
                            direction.as_str_name()
                        );
                    }
                    Err(_) => {
                        return plan_err!(
                            "MATCH_RECOGNIZE Substrait window sort {index} has unknown direction {direction}"
                        );
                    }
                }
            }
            Some(SortKind::ComparisonFunctionReference(_)) => {
                return plan_err!(
                    "MATCH_RECOGNIZE Substrait window sort {index} uses an unsupported comparison function"
                );
            }
            None => {
                return plan_err!(
                    "MATCH_RECOGNIZE Substrait window sort {index} is missing its sort kind"
                );
            }
        }
    }
    Ok(())
}

fn validate_output_type(
    consumer: &impl SubstraitConsumer,
    window: &SubstraitWindowFunction,
    decoded: &Expr,
    input_schema: &DFSchema,
) -> Result<()> {
    let Some(output_type) = &window.output_type else {
        return Ok(());
    };
    let (_, actual) = decoded.to_field(input_schema)?;
    let mut producer = OutputTypeProducer::default();
    let expected =
        to_substrait_type(&mut producer, actual.data_type(), actual.is_nullable())?;
    // Compare the canonical wire contract directly. The general decoder drops
    // some nested nullability and variation information, and container child
    // names are not represented on the wire at all.
    let mut declared = output_type.clone();
    if resolve_type_anchors(
        &mut declared,
        consumer.get_extensions(),
        &producer.extensions,
    )
    .is_none()
        || declared != expected
    {
        return plan_err!(
            "MATCH_RECOGNIZE window wrapper output_type does not match its inferred result: expected {expected:?}, declared {output_type:?}"
        );
    }
    Ok(())
}

// Translate each declared UDT anchor into the inferred type's anchor space.
// The inferred table has exactly one registration per name.
fn resolve_type_anchors(
    ty: &mut proto::Type,
    declared: &Extensions,
    inferred: &Extensions,
) -> Option<()> {
    use proto::r#type::{Kind, parameter::Parameter};

    let resolve = |ty: &mut proto::Type| resolve_type_anchors(ty, declared, inferred);
    match ty.kind.as_mut()? {
        Kind::Struct(fields) => fields.types.iter_mut().try_for_each(resolve)?,
        Kind::List(list) => resolve(list.r#type.as_deref_mut()?)?,
        Kind::Map(map) => {
            resolve(map.key.as_deref_mut()?)?;
            resolve(map.value.as_deref_mut()?)?;
        }
        Kind::Func(func) => {
            func.parameter_types.iter_mut().try_for_each(resolve)?;
            resolve(func.return_type.as_deref_mut()?)?;
        }
        Kind::UserDefined(udt) => {
            let name = declared.types.get(&udt.type_reference)?;
            udt.type_reference = inferred
                .types
                .iter()
                .find_map(|(anchor, candidate)| (candidate == name).then_some(*anchor))?;
            for parameter in &mut udt.type_parameters {
                if let Some(Parameter::DataType(child)) = &mut parameter.parameter {
                    resolve(child)?;
                }
            }
        }
        _ => {}
    }
    Some(())
}

#[derive(Default)]
struct OutputTypeProducer {
    extensions: Extensions,
}

impl SubstraitProducer for OutputTypeProducer {
    fn register_function(&mut self, signature: String) -> u32 {
        self.extensions.register_function(&signature)
    }

    fn register_type(&mut self, name: String) -> u32 {
        self.extensions.register_type(&name)
    }

    fn get_extensions(self) -> Extensions {
        self.extensions
    }
}

#[derive(Default)]
struct DecodedOptions {
    filter_argument_count: Option<usize>,
    null_treatment: Option<NullTreatment>,
}

fn decode_options(options: &mut Vec<FunctionOption>) -> Result<DecodedOptions> {
    let mut decoded = DecodedOptions::default();
    for option in std::mem::take(options) {
        if option.name.eq_ignore_ascii_case(FILTER_OPTION) {
            if decoded.filter_argument_count.is_some() {
                return plan_err!("duplicate MATCH_RECOGNIZE window filter option");
            }
            let preference = single_preference(&option)?;
            let Some((_, argument_count)) = preference
                .split_once(':')
                .filter(|(layout, _)| layout.eq_ignore_ascii_case(FILTER_LAYOUT))
            else {
                return plan_err!(
                    "unsupported MATCH_RECOGNIZE window filter layout '{preference}'"
                );
            };
            decoded.filter_argument_count = Some(argument_count.parse().map_err(
                |_| {
                    datafusion::common::DataFusionError::Plan(format!(
                        "invalid MATCH_RECOGNIZE window filter argument count '{argument_count}'"
                    ))
                },
            )?);
        } else if option.name.eq_ignore_ascii_case(NULL_TREATMENT_OPTION) {
            if decoded.null_treatment.is_some() {
                return plan_err!(
                    "duplicate MATCH_RECOGNIZE window null-treatment option"
                );
            }
            decoded.null_treatment = Some(match single_preference(&option)? {
                value if value.eq_ignore_ascii_case(IGNORE_NULLS) => {
                    NullTreatment::IgnoreNulls
                }
                value if value.eq_ignore_ascii_case(RESPECT_NULLS) => {
                    NullTreatment::RespectNulls
                }
                value => {
                    return plan_err!(
                        "unsupported MATCH_RECOGNIZE window null treatment '{value}'"
                    );
                }
            });
        } else if option.name.to_ascii_lowercase().starts_with(OPTION_PREFIX) {
            return plan_err!(
                "unknown MATCH_RECOGNIZE private window option '{}'",
                option.name
            );
        } else {
            return plan_err!("unsupported Substrait window option '{}'", option.name);
        }
    }
    Ok(decoded)
}

fn single_preference(option: &FunctionOption) -> Result<&str> {
    match option.preference.as_slice() {
        [preference] => Ok(preference),
        _ => plan_err!(
            "MATCH_RECOGNIZE window option '{}' requires exactly one preference",
            option.name
        ),
    }
}