datafusion-match-recognize 0.55.0

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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
// 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.

//! Managed-aggregate extraction, anchor rewriting, and per-symbol planning for
//! match-aware `DEFINE` predicates.

use super::{
    CandidatePredicate, LocalHistoryPredicate, is_safe_input_expr,
    replace_managed_columns,
};
use crate::core::MatchMetadataColumn;
use crate::planning::expr_safety::{
    scalar_ordering_type_is_safe, scalar_value_type_is_safe,
};
use crate::planning::extract::is_plain_aggregate;
use crate::planning::logical::utils::{ExprBindings, build_match_aware_schema};
use crate::planning::phases::{SymbolPlan, SymbolPlanPredicate};
use crate::planning::static_extraction::StaticAnalysis;
use crate::planning::{ManagedAggregate, NamedExpr, extract};
use datafusion::arrow::compute::SortOptions;
use datafusion::arrow::datatypes::{DataType, FieldRef, Schema};
use datafusion::common::config::ConfigOptions;
use datafusion::common::tree_node::{
    Transformed, TreeNode, TreeNodeRecursion, TreeNodeRewriter,
};
use datafusion::common::{Column, DFSchema, Result};
use datafusion::logical_expr::expr::{AggregateFunction, BinaryExpr, NullTreatment};
use datafusion::logical_expr::type_coercion::functions::fields_with_udf;
use datafusion::logical_expr::{
    Expr, ExprSchemable, Operator, Volatility, WindowFunctionDefinition,
};
use datafusion::optimizer::analyzer::type_coercion::TypeCoercionRewriter;
use datafusion::physical_expr::aggregate::AggregateExprBuilder;
use datafusion::physical_expr::expressions::{Column as PhysicalColumn, Literal};
use datafusion::physical_expr::{PhysicalExpr, PhysicalSortExpr};
use std::collections::BTreeMap;
use std::str::FromStr;
use std::sync::Arc;

fn is_local_metadata_column(meta: MatchMetadataColumn) -> bool {
    matches!(
        meta,
        MatchMetadataColumn::MatchNumber
            | MatchMetadataColumn::MatchSequenceNumber
            | MatchMetadataColumn::Excluded
    )
}

pub(super) fn expr_uses_match_metadata(
    expr: &Expr,
    classifier_symbols: &BTreeMap<String, String>,
) -> bool {
    expr.exists(|node| {
        if let Expr::Column(col) = node {
            return Ok(MatchMetadataColumn::from_str(&col.name).is_ok()
                || classifier_symbols.contains_key(&col.name));
        }
        Ok(false)
    })
    .unwrap_or(false)
}

pub(super) fn expr_uses_local_match_metadata(expr: &Expr) -> bool {
    let mut found = false;
    let _ = expr.apply(|node| {
        if matches!(node, Expr::AggregateFunction(_) | Expr::WindowFunction(_)) {
            return Ok(TreeNodeRecursion::Jump);
        }
        if let Expr::Column(col) = node
            && MatchMetadataColumn::from_str(&col.name)
                .is_ok_and(is_local_metadata_column)
        {
            found = true;
            return Ok(TreeNodeRecursion::Stop);
        }
        Ok(TreeNodeRecursion::Continue)
    });
    found
}

pub(super) fn expr_uses_deferred_match_metadata(
    expr: &Expr,
    classifier_symbols: &BTreeMap<String, String>,
) -> bool {
    let direct_column_requires_deferred = |name: &str| {
        MatchMetadataColumn::from_str(name)
            .is_ok_and(|meta| !is_local_metadata_column(meta))
            || classifier_symbols.contains_key(name)
    };

    let mut found = false;
    let _ = expr.apply(|node| {
        if matches!(node, Expr::AggregateFunction(_) | Expr::WindowFunction(_)) {
            if expr_uses_match_metadata(node, classifier_symbols) {
                found = true;
                return Ok(TreeNodeRecursion::Stop);
            }
            return Ok(TreeNodeRecursion::Jump);
        }
        if matches!(node, Expr::Column(col) if direct_column_requires_deferred(&col.name))
        {
            found = true;
            return Ok(TreeNodeRecursion::Stop);
        }
        Ok(TreeNodeRecursion::Continue)
    });
    found
}

pub(super) fn prepare_aggregate_args(
    aggregates: &mut [ManagedAggregate],
    bindings: &mut ExprBindings,
    base_schema: &DFSchema,
) {
    for aggregate in aggregates {
        let is_anchor = matches!(
            crate::planning::navigation_names::NavigationFunctionFamily::from_aggregate_udf(
                aggregate.func.func.as_ref()
            ),
            Some(
                crate::planning::navigation_names::NavigationFunctionFamily::First
                    | crate::planning::navigation_names::NavigationFunctionFamily::Last
            )
        );
        if is_anchor && aggregate.func.params.args.len() == 1 {
            let arg = &aggregate.func.params.args[0];
            if !matches!(arg, Expr::Column(_)) && is_safe_input_expr(arg, base_schema) {
                aggregate.func.params.args[0] =
                    Expr::Column(bindings.register(arg.clone()));
            }
            continue;
        }
        let is_sum = aggregate.func.func.as_ref()
            == datafusion::functions_aggregate::sum::sum_udaf().as_ref();
        let is_avg = aggregate.func.func.as_ref()
            == datafusion::functions_aggregate::average::avg_udaf().as_ref();
        let is_count = aggregate.func.func.as_ref()
            == datafusion::functions_aggregate::count::count_udaf().as_ref();
        let prepares_value = is_sum
            || is_avg
            || is_count
            || aggregate.func.func.as_ref()
                == datafusion::functions_aggregate::min_max::min_udaf().as_ref()
            || aggregate.func.func.as_ref()
                == datafusion::functions_aggregate::min_max::max_udaf().as_ref();
        if !prepares_value
            || aggregate.func.params.args.len() != 1
            || (!is_sum && !is_plain_aggregate(&aggregate.func))
        {
            continue;
        }

        let mut arg = aggregate.func.params.args[0].clone();
        // COUNT(*) lowers to a literal. Its canonical shape also enables
        // predictive rejection; it has no scalar work to move into the input.
        if is_count && matches!(arg, Expr::Literal(..)) {
            continue;
        }
        if !is_safe_input_expr(&arg, base_schema) {
            continue;
        }
        if is_sum || is_avg {
            // Resolve aggregate widening before preparing its input. Any outer
            // cast preserves the scalar expression's own evaluation width.
            let Ok(Expr::AggregateFunction(coerced)) =
                TypeCoercionRewriter::new(base_schema)
                    .f_up(Expr::AggregateFunction(aggregate.func.clone()))
                    .map(|rewritten| rewritten.data)
            else {
                continue;
            };
            arg = coerced.params.args[0].clone();
            if !is_safe_input_expr(&arg, base_schema) {
                continue;
            }
        }
        if matches!(arg.clone().unalias(), Expr::Column(_)) {
            continue;
        }
        // Keep the coerced expression for DataFusion accumulators. A register
        // writer can widen the raw column while loading its existing word.
        if is_plain_aggregate(&aggregate.func)
            && direct_widening_column(&arg, base_schema).is_some()
        {
            aggregate.func.params.args[0] = arg;
            continue;
        }
        aggregate.func.params.args[0] = Expr::Column(bindings.register(arg));
    }
}

/// Primitive casts whose result is exact for every input and can be decoded
/// from one register word. A cast of a computed expression retains its own
/// evaluation width, errors and NULL handling.
pub(crate) fn direct_widening_column<'a>(
    expr: &'a Expr,
    schema: &DFSchema,
) -> Option<(&'a Column, &'a DataType)> {
    let Expr::Cast(cast) = expr else { return None };
    let Expr::Column(column) = cast.expr.as_ref() else {
        return None;
    };
    let source = schema
        .qualified_field_from_column(column)
        .ok()?
        .1
        .data_type();
    let target = cast.field.data_type();
    use DataType::*;
    matches!(
        (source, target),
        (Int8 | Int16 | Int32, Int64 | Float64)
            | (UInt8 | UInt16 | UInt32, UInt64 | Float64)
            | (Float32, Float64)
    )
    .then_some((column, target))
}

/// On a proposed transition the current label has already consumed this row.
pub(super) fn current_row_last<'a>(
    aggregate: &'a ManagedAggregate,
    symbol: &str,
    schema: &DFSchema,
) -> Option<&'a Column> {
    use crate::planning::navigation_names::NavigationFunctionFamily;

    let params = &aggregate.func.params;
    if NavigationFunctionFamily::from_aggregate_udf(&aggregate.func.func)
        != Some(NavigationFunctionFamily::Last)
        || aggregate
            .symbol
            .as_deref()
            .is_some_and(|owner| owner != symbol)
        || params.distinct
        || params.filter.is_some()
        || matches!(params.null_treatment, Some(NullTreatment::IgnoreNulls))
        || !(params.order_by.is_empty()
            || matches!(params.order_by.as_slice(), [sort] if crate::planning::logical::is_internal_sequence_ordering(sort)))
    {
        return None;
    }
    let [Expr::Column(column)] = params.args.as_slice() else {
        return None;
    };
    if column.name == MatchMetadataColumn::Classifier.as_ref() {
        return None;
    }
    schema
        .qualified_field_from_column(column)
        .ok()
        .map(|_| column)
}

pub(super) fn canonicalize_managed_aggregates(
    rewritten_expr: &mut Expr,
    extracted: &mut [ManagedAggregate],
    canonical: &mut Vec<ManagedAggregate>,
) -> Result<()> {
    let mut column_replacements = BTreeMap::new();

    for aggregate in extracted {
        let extracted_column = aggregate.column_name();
        let canonical_id = extract::matching_managed_aggregate_id(canonical, aggregate)
            .unwrap_or_else(|| {
                let id = canonical.len();
                aggregate.id = id;
                canonical.push(aggregate.clone());
                id
            });
        aggregate.id = canonical_id;

        let canonical_column = aggregate.column_name();
        if extracted_column != canonical_column {
            column_replacements
                .insert(extracted_column, Column::from_name(canonical_column));
        }
    }
    replace_managed_columns(rewritten_expr, &column_replacements)
}

/// Probe direct accumulator construction and empty-state evaluation using
/// coerced synthetic column types while preserving typed literal parameters.
fn probe_managed_accumulator(
    func: &AggregateFunction,
    schema: &DFSchema,
) -> Option<Vec<FieldRef>> {
    let params = &func.params;
    let arg_fields = params
        .args
        .iter()
        .map(|arg| arg.to_field(schema).ok().map(|(_, f)| f))
        .collect::<Option<Vec<_>>>()?;
    let coerced = fields_with_udf(&arg_fields, func.func.as_ref()).ok()?;
    if coerced.len() != params.args.len() {
        return None;
    }

    let mut fields = Vec::with_capacity(coerced.len() + params.order_by.len());
    let mut push_col = |field: &FieldRef| -> Arc<dyn PhysicalExpr> {
        let idx = fields.len();
        let name = format!("c{idx}");
        let column = Arc::new(PhysicalColumn::new(&name, idx));
        fields.push(field.as_ref().clone().with_name(name));
        column
    };
    let exprs: Vec<_> = params
        .args
        .iter()
        .zip(&coerced)
        .map(|(arg, field)| match arg {
            Expr::Literal(scalar, _) if &scalar.data_type() == field.data_type() => {
                Arc::new(Literal::new(scalar.clone())) as Arc<dyn PhysicalExpr>
            }
            _ => push_col(field),
        })
        .collect();
    let order_bys = params
        .order_by
        .iter()
        .map(|sort| {
            let (_, field) = sort.expr.to_field(schema).ok()?;
            if !scalar_ordering_type_is_safe(field.data_type()) {
                return None;
            }
            let expr = params
                .args
                .iter()
                .enumerate()
                .find(|&(i, a)| {
                    a == &sort.expr && coerced[i].data_type() == field.data_type()
                })
                .map_or_else(|| push_col(&field), |(i, _)| Arc::clone(&exprs[i]));
            Some(PhysicalSortExpr::new(
                expr,
                SortOptions::new(!sort.asc, sort.nulls_first),
            ))
        })
        .collect::<Option<Vec<_>>>()?;

    let agg = AggregateExprBuilder::new(Arc::clone(&func.func), exprs)
        .schema(Arc::new(Schema::new(fields)))
        .alias(func.func.name())
        .order_by(order_bys)
        .with_ignore_nulls(params.null_treatment == Some(NullTreatment::IgnoreNulls))
        .with_distinct(params.distinct)
        .build()
        .ok()?;
    if !agg
        .state_fields()
        .ok()?
        .iter()
        .all(|field| scalar_value_type_is_safe(field.data_type()))
    {
        return None;
    }
    let mut acc = agg.create_accumulator().ok()?;
    acc.evaluate().ok()?;
    // NFA forks clone empty accumulators via `state() -> merge_batch()`.
    let arrays = acc
        .state()
        .ok()?
        .into_iter()
        .map(|value| value.to_array_of_size(1))
        .collect::<Result<Vec<_>>>()
        .ok()?;
    agg.create_accumulator().ok()?.merge_batch(&arrays).ok()?;
    Some(coerced)
}

/// A managed aggregate is updated on its contributing symbol, which need not
/// be the DEFINE that reads it. Preserve candidate demand for observable input
/// expressions and opaque UDAFs before publishing any managed state or inputs.
/// The schema must include prepared bindings and runtime metadata used by lowering.
/// Register-capable inputs remain eligible here; checking their accumulator-only
/// fallback requires the final backend decision after any capacity downgrade.
pub(super) fn aggregate_requires_define_demand(
    aggregate: &ManagedAggregate,
    defining_symbol: &str,
    only_pattern_symbol: bool,
    schema: &DFSchema,
) -> bool {
    let func = &aggregate.func;
    let params = &func.params;
    let known_implementation =
        crate::planning::bound_expr_lowering::builtin_aggregate_udf(func.func.name())
            .is_some_and(|known| known.as_ref() == func.func.as_ref())
            || crate::planning::navigation_names::NavigationFunctionFamily::from_aggregate_udf(
                func.func.as_ref(),
            )
            .is_some();
    // Even when no row contributes, the managed runtime constructs, evaluates,
    // and clones (on NFA forks) every accumulator without SingleDistinctToGroupBy.
    // Keep opaque, volatile, unsupported-DISTINCT, or non-constructible/clonable
    // accumulators on Deferred.
    if !known_implementation || func.func.signature().volatility != Volatility::Immutable
    {
        return true;
    }
    let Some(coerced_fields) = probe_managed_accumulator(func, schema) else {
        return true;
    };
    if aggregate.symbol.as_deref() == Some(defining_symbol)
        || (aggregate.symbol.is_none() && only_pattern_symbol)
    {
        // Arguments are demanded only on this symbol's transitions, after its
        // static precheck. Aggregate inputs precede the match-wide predicate;
        // a sibling COUNT conjunct does not short-circuit their evaluation.
        return false;
    }
    // Decimal256 has no register recipe. Its AVG accumulator scales the sum
    // before dividing, even on another symbol's transition. Reserve 20 digits
    // for a u64 row count and four for AVG's scale-up; narrower inputs cannot
    // overflow that intermediate and keep their existing accumulator route.
    if func.func.as_ref() == datafusion::functions_aggregate::average::avg_udaf().as_ref()
        && matches!(
            coerced_fields.first().map(|field| field.data_type()),
            Some(&DataType::Decimal256(precision, _)) if precision > 76 - 20 - 4
        )
    {
        return true;
    }
    // MIN/MAX accumulators fail on Null and non-orderable nested/encoded
    // types during update_batch, even on another symbol's transition.
    if (func.func.as_ref()
        == datafusion::functions_aggregate::min_max::min_udaf().as_ref()
        || func.func.as_ref()
            == datafusion::functions_aggregate::min_max::max_udaf().as_ref())
        && !params.args.iter().all(|arg| {
            arg.get_type(schema)
                .is_ok_and(|ty| !ty.is_null() && scalar_ordering_type_is_safe(&ty))
        })
    {
        return true;
    }
    !params
        .args
        .iter()
        .all(|arg| is_safe_input_expr(arg, schema))
        || params
            .filter
            .as_deref()
            .is_some_and(|filter| !is_safe_input_expr(filter, schema))
        || params
            .order_by
            .iter()
            .any(|sort| !is_safe_input_expr(&sort.expr, schema))
}

/// Shared aggregate and input-projection state; each call plans one symbol.
pub(super) struct SymbolPlanner<'a> {
    pub(super) managed_aggregates: Vec<ManagedAggregate>,
    pub(super) bindings: ExprBindings,
    partition_by: &'a [Expr],
}

impl<'a> SymbolPlanner<'a> {
    pub(super) fn new(schema: &DFSchema, partition_by: &'a [Expr]) -> Self {
        Self {
            managed_aggregates: Vec::new(),
            bindings: ExprBindings::new(schema, []),
            partition_by,
        }
    }

    fn build_aggregate_demand_schema(
        &self,
        schema: &DFSchema,
        classifier_symbols: &BTreeMap<String, String>,
    ) -> Result<DFSchema> {
        let aggregate_schema = build_match_aware_schema(
            &Arc::new(schema.clone()),
            &classifier_symbols.values().cloned().collect(),
        )?;
        let mut fields = aggregate_schema
            .iter()
            .map(|(qualifier, field)| (qualifier.cloned(), Arc::clone(field)))
            .collect::<Vec<_>>();
        for expr in self.bindings.aliased_expressions_from(0) {
            fields.push(expr.to_field(schema)?);
        }
        DFSchema::new_with_metadata(fields, aggregate_schema.metadata().clone())
    }

    pub(super) fn plan_symbol(
        &mut self,
        definition: NamedExpr,
        schema: &DFSchema,
        classifier_symbols: &BTreeMap<String, String>,
        static_analysis: StaticAnalysis<'_>,
        disable_managed: bool,
        options: &ConfigOptions,
    ) -> Result<SymbolPlan> {
        let NamedExpr {
            name,
            expr: prepared_expr,
        } = definition;
        let expr = prepared_expr.clone();
        let expr = if disable_managed {
            expr
        } else {
            prepare_anchor_arithmetic(expr, schema, options)?
        };
        // IDs belong to this attempt until canonicalization publishes them.
        let mut next_id = self.managed_aggregates.len();
        let mut extraction = if !disable_managed {
            extract::extract_managed_aggregates(
                expr,
                &mut next_id,
                classifier_symbols,
                static_analysis,
                self.partition_by,
            )?
        } else {
            let has_deferred_dependent_subexpr =
                extract::contains_match_scoped_call(&expr, static_analysis)?;
            extract::ManagedAggregateExtraction {
                rewritten_expr: expr,
                managed_aggregates: Vec::new(),
                has_deferred_dependent_subexpr,
            }
        };

        // The physical fallback binds a Hybrid predicate as one expression.
        // If a raw match-scoped aggregate or window remains, that expression
        // is not bindable. Keep the complete predicate Deferred instead of
        // retaining managed state that cannot be evaluated locally.
        let requires_define_demand = if extraction.has_deferred_dependent_subexpr
            || extraction.managed_aggregates.is_empty()
        {
            false
        } else {
            // Lowered navigation reads prepared input columns and runtime metadata.
            // Prove scalar safety against their actual types, not just the raw
            // table schema. Only registered bindings gain this trust; a private
            // column-name prefix alone is not a safety proof.
            let aggregate_schema =
                self.build_aggregate_demand_schema(schema, classifier_symbols)?;
            let only_pattern_symbol = classifier_symbols.len() == 1
                && classifier_symbols.values().any(|symbol| symbol == &name);
            extraction.managed_aggregates.iter().any(|aggregate| {
                // Managed state needs a typed NULL placeholder in the input
                // projection, even when the aggregate itself stays demanded.
                !Expr::AggregateFunction(aggregate.func.clone())
                    .get_type(&aggregate_schema)
                    .is_ok_and(|data_type| scalar_value_type_is_safe(&data_type))
                    || aggregate_requires_define_demand(
                        aggregate,
                        &name,
                        only_pattern_symbol,
                        &aggregate_schema,
                    )
            })
        };
        if extraction.has_deferred_dependent_subexpr || requires_define_demand {
            return Ok(SymbolPlan {
                name,
                predicate: SymbolPlanPredicate::candidate(CandidatePredicate::History {
                    expr: prepared_expr,
                    local: None,
                }),
            });
        }

        let has_cross_symbol_dependency =
            extraction.managed_aggregates.iter().any(|agg| {
                agg.symbol
                    .as_deref()
                    .is_some_and(|symbol| symbol != name.as_str())
            });
        let has_local_metadata_dependency =
            expr_uses_local_match_metadata(&extraction.rewritten_expr);
        let has_metadata_dependency = expr_uses_deferred_match_metadata(
            &extraction.rewritten_expr,
            classifier_symbols,
        );
        let has_deferred_dependency =
            has_cross_symbol_dependency || has_metadata_dependency;
        let has_local_incremental =
            !extraction.managed_aggregates.is_empty() || has_local_metadata_dependency;

        if has_local_incremental {
            // Substitute only in this local consumer, after its candidate mode is
            // fixed. Other symbols and the original Deferred expression can still
            // require the same LAST as history. Nested aggregates were declined by
            // extraction before any of their internal placeholders could escape.
            let mut current_columns = BTreeMap::new();
            extraction.managed_aggregates.retain(|aggregate| {
                if let Some(column) = current_row_last(aggregate, &name, schema) {
                    current_columns.insert(aggregate.column_name(), column.clone());
                    return false;
                }
                true
            });
            replace_managed_columns(&mut extraction.rewritten_expr, &current_columns)?;
            prepare_aggregate_args(
                &mut extraction.managed_aggregates,
                &mut self.bindings,
                schema,
            );
            canonicalize_managed_aggregates(
                &mut extraction.rewritten_expr,
                &mut extraction.managed_aggregates,
                &mut self.managed_aggregates,
            )?;
            log::debug!(
                "prepare_input: extracted {} managed aggs for symbol {}",
                extraction.managed_aggregates.len(),
                name
            );
        }
        let predicate = if has_deferred_dependency {
            let local = has_local_incremental.then(|| LocalHistoryPredicate {
                expr: extraction.rewritten_expr,
                history_columns: extraction
                    .managed_aggregates
                    .iter()
                    .filter(|agg| {
                        agg.symbol
                            .as_deref()
                            .is_some_and(|symbol| symbol != name.as_str())
                    })
                    .map(|aggregate| aggregate.column_name())
                    .collect(),
            });
            SymbolPlanPredicate::candidate(CandidatePredicate::History {
                expr: prepared_expr,
                local,
            })
        } else if has_local_incremental {
            SymbolPlanPredicate::candidate(CandidatePredicate::Local(
                extraction.rewritten_expr,
            ))
        } else if !crate::planning::expr_safety::can_precompute(
            &extraction.rewritten_expr,
            schema,
        ) {
            // Mixed programs already have a demanded evaluator. Giving it
            // the row-only predicate keeps fallible work out of the child.
            SymbolPlanPredicate::candidate(CandidatePredicate::Local(
                extraction.rewritten_expr,
            ))
        } else {
            SymbolPlanPredicate::Static(extraction.rewritten_expr)
        };
        Ok(SymbolPlan { name, predicate })
    }
}

pub(super) fn prepare_anchor_arithmetic(
    expr: Expr,
    schema: &DFSchema,
    options: &ConfigOptions,
) -> Result<Expr> {
    Ok(expr
        .transform_up(|node| {
            let Expr::BinaryExpr(binary) = &node else {
                return Ok(Transformed::no(node));
            };
            if !matches!(
                binary.op,
                Operator::Plus | Operator::Minus | Operator::Multiply
            ) {
                return Ok(Transformed::no(node));
            }
            let (anchor, literal, anchor_left) =
                match (binary.left.as_ref(), binary.right.as_ref()) {
                    (Expr::WindowFunction(anchor), literal) => (anchor, literal, true),
                    (literal, Expr::WindowFunction(anchor)) => (anchor, literal, false),
                    _ => return Ok(Transformed::no(node)),
                };
            let literal = match literal {
                Expr::Literal(..) => literal.clone(),
                // Typed SQL constants commonly arrive before constant folding.
                // Fold only a cast of a literal, and decline on failure: neither
                // arbitrary functions nor input expressions are executed here.
                Expr::Cast(cast) if matches!(cast.expr.as_ref(), Expr::Literal(..)) => {
                    let Some(literal) =
                        crate::planning::bound_expr_lowering::simplified_literal(
                            literal, options,
                        )
                    else {
                        return Ok(Transformed::no(node));
                    };
                    literal
                }
                _ => return Ok(Transformed::no(node)),
            };
            let WindowFunctionDefinition::WindowUDF(function) = &anchor.fun else {
                return Ok(Transformed::no(node));
            };
            use crate::functions::udwf::{mr_first_udwf, mr_last_udwf};
            if (function.as_ref() != mr_first_udwf().as_ref()
                && function.as_ref() != mr_last_udwf().as_ref())
                || !(1..=2).contains(&anchor.params.args.len())
                || anchor.params.filter.is_some()
                || anchor.params.distinct
                || anchor.params.null_treatment.is_some()
            {
                return Ok(Transformed::no(node));
            }
            let value = anchor.params.args[0].clone();
            let (left, right) = if anchor_left {
                (value, literal)
            } else {
                (literal, value)
            };
            let value = Expr::BinaryExpr(BinaryExpr::new(
                Box::new(left),
                binary.op,
                Box::new(right),
            ));
            if !is_safe_input_expr(&value, schema) {
                return Ok(Transformed::no(node));
            }
            // These operators propagate NULL. Preserve the selected row, mask,
            // frame and ordering, including an absent or NULL anchor. IGNORE NULLS
            // is deliberately excluded: a transformation can create a NULL value.
            let mut rewritten = anchor.clone();
            rewritten.params.args[0] = value;
            Ok(Transformed::yes(Expr::WindowFunction(rewritten)))
        })?
        .data)
}