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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
// 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.

//! Bound source lookup and one-pass lowering with independent work/stack limits.
use super::*;
use datafusion::arrow::array::types::{
    Decimal128Type, Decimal256Type, DecimalType, validate_decimal_precision_and_scale,
};
use datafusion::arrow::datatypes::{DataType, TimeUnit};
use datafusion::arrow::error::ArrowError;
use datafusion::common::ScalarValue;
use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion::logical_expr::binary::BinaryTypeCoercer;
use datafusion::logical_expr::{Expr, Operator};

pub fn validate_decimal_scalar_value(value: &ScalarValue) -> Result<(), ArrowError> {
    match value {
        ScalarValue::Decimal128(value, precision, scale) => {
            validate_decimal_precision_and_scale::<Decimal128Type>(*precision, *scale)?;
            if let Some(value) = value {
                Decimal128Type::validate_decimal_precision(*value, *precision, *scale)?;
            }
        }
        ScalarValue::Decimal256(value, precision, scale) => {
            validate_decimal_precision_and_scale::<Decimal256Type>(*precision, *scale)?;
            if let Some(value) = value {
                Decimal256Type::validate_decimal_precision(*value, *precision, *scale)?;
            }
        }
        _ => {}
    }
    Ok(())
}

/// Source types remain distinct even when their runtime values share a word.
pub fn vm_type_from_data_type(ty: &DataType, nullable: bool) -> Option<VmType> {
    use VmScalarType as V;
    let scalar = match ty {
        DataType::Boolean => V::Bool,
        DataType::Int8 => V::Int8,
        DataType::Int16 => V::Int16,
        DataType::Int32 => V::Int32,
        DataType::Int64 => V::Int64,
        DataType::UInt8 => V::UInt8,
        DataType::UInt16 => V::UInt16,
        DataType::UInt32 => V::UInt32,
        DataType::UInt64 => V::UInt64,
        DataType::Float32 => V::Float32,
        DataType::Float64 => V::Float64,
        DataType::Utf8 => V::Utf8,
        DataType::LargeUtf8 => V::LargeUtf8,
        DataType::Utf8View => V::Utf8View,
        DataType::Date32 => V::Date32,
        DataType::Date64 => V::Date64,
        DataType::Time32(u @ (TimeUnit::Second | TimeUnit::Millisecond)) => V::Time32(*u),
        DataType::Time64(u @ (TimeUnit::Microsecond | TimeUnit::Nanosecond)) => {
            V::Time64(*u)
        }
        DataType::Duration(u) => V::Duration(*u),
        DataType::Timestamp(unit, zone) => V::Timestamp {
            unit: *unit,
            timezone_aware: zone.is_some(),
        },
        DataType::Decimal128(p, s) => {
            validate_decimal_precision_and_scale::<Decimal128Type>(*p, *s).ok()?;
            V::Decimal128 {
                precision: *p,
                scale: *s,
            }
        }
        DataType::Decimal256(p, s) => {
            validate_decimal_precision_and_scale::<Decimal256Type>(*p, *s).ok()?;
            V::Decimal256 {
                precision: *p,
                scale: *s,
            }
        }
        DataType::FixedSizeBinary(width @ 1..=16) => V::FixedSizeBinary(*width as u8),
        _ => return None,
    };
    Some(VmType { scalar, nullable })
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VmMetadataComparisonColumn {
    MatchNumber,
    MatchSequenceNumber,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VmPredicateInputRole {
    RowValue,
    StaticPredicate { bool_idx: usize },
    StaticScalar { scalar_idx: usize },
    Classifier,
    Metadata(VmMetadataComparisonColumn),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VmManagedPredicateColumn {
    slot_idx: usize,
    column_name: String,
    scalar_type: Option<VmScalarType>,
}
impl VmManagedPredicateColumn {
    pub fn new(
        slot_idx: usize,
        column_name: String,
        scalar_type: Option<VmScalarType>,
    ) -> Self {
        Self {
            slot_idx,
            column_name,
            scalar_type,
        }
    }
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VmPredicateInputColumn {
    column_name: String,
    ty: Option<VmType>,
    role: VmPredicateInputRole,
}
impl VmPredicateInputColumn {
    pub fn new(
        column_name: String,
        ty: Option<VmType>,
        role: VmPredicateInputRole,
    ) -> Self {
        Self {
            column_name,
            ty,
            role,
        }
    }
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct VmCompileContext {
    managed: Vec<VmManagedPredicateColumn>,
    inputs: Vec<VmPredicateInputColumn>,
    limits: VmCompileLimits,
    program_limits: PredicateProgramLimits,
}
impl VmCompileContext {
    pub fn try_new(
        managed: Vec<VmManagedPredicateColumn>,
        inputs: Vec<VmPredicateInputColumn>,
        limits: VmCompileLimits,
    ) -> Result<Self, VmCompileError> {
        use VmCompileError::*;
        let mut names = std::collections::HashSet::new();
        let mut previous = None;
        for c in &managed {
            u16::try_from(c.slot_idx).map_err(|_| ProgramTooLarge)?;
            if !names.insert(&c.column_name) || previous.is_some_and(|p| p >= c.slot_idx)
            {
                return Err(BindingFailure);
            }
            previous = Some(c.slot_idx);
        }
        let (mut bools, mut scalars) = (0, 0);
        for c in &inputs {
            if !names.insert(&c.column_name) {
                return Err(BindingFailure);
            }
            let (next, index) = match c.role {
                VmPredicateInputRole::StaticPredicate { bool_idx } => {
                    (&mut bools, bool_idx)
                }
                VmPredicateInputRole::StaticScalar { scalar_idx } => {
                    (&mut scalars, scalar_idx)
                }
                _ => continue,
            };
            u16::try_from(index).map_err(|_| ProgramTooLarge)?;
            if index != *next {
                return Err(BindingFailure);
            }
            *next += 1;
        }
        Ok(Self {
            managed,
            inputs,
            limits: limits.bounded(),
            program_limits: Default::default(),
        })
    }

    #[cfg(test)]
    pub fn with_program_limits(mut self, limits: PredicateProgramLimits) -> Self {
        self.program_limits = limits.bounded();
        self
    }
}

/// Admission always covers the complete expression, before binding any runtime state.
pub fn compile_direct_predicate(
    expr: &Expr,
    context: &VmCompileContext,
) -> Result<DirectPredicatePlan, VmCompileError> {
    let (mut size, mut literals) = (0, 0);
    // Iterative preflight bounds recursion and work even for hostile source trees.
    expr.apply(|e| {
        size += 1;
        literals += usize::from(matches!(e, Expr::Literal(..)));
        Ok(
            if size > context.limits.max_ir_nodes
                || literals > context.limits.max_constants
            {
                TreeNodeRecursion::Stop
            } else {
                TreeNodeRecursion::Continue
            },
        )
    })
    .map_err(|_| VmCompileError::EmissionFailure)?;
    if size > context.limits.max_ir_nodes || literals > context.limits.max_constants {
        return Err(VmCompileError::ExpressionTooLarge);
    }
    let mut compiler = Compiler {
        context,
        nodes: vec![],
        rows: vec![],
    };
    let (root, ty, slots, work, _) = compiler.lower(expr)?;
    if ty.scalar != VmScalarType::Bool {
        return Err(VmCompileError::TypeResolutionFailure);
    }
    if work + 1 > context.program_limits.max_operations {
        return Err(VmCompileError::ProgramTooLarge);
    }
    if slots > context.program_limits.max_eval_stack {
        return Err(VmCompileError::StackDepthExceeded);
    }
    Ok(DirectPredicatePlan {
        nodes: compiler.nodes,
        root,
        value_slots: slots as u16,
        row_columns: compiler.rows,
    })
}
// Node, exact type, peak live operands, work, literal-only (scalar negation semantics).
type Value = (u16, VmType, usize, usize, bool);
struct Compiler<'a> {
    context: &'a VmCompileContext,
    nodes: Vec<PredicateNode>,
    rows: Vec<String>,
}
impl Compiler<'_> {
    fn lower(&mut self, expr: &Expr) -> Result<Value, VmCompileError> {
        use PredicateNode as N;
        use VmCompileError::*;
        use VmScalarType as T;
        let unsupported = UnsupportedNumericTypeCombination;
        let (node, ty, slots, work, literal) = match expr {
            Expr::Alias(a) => return self.lower(&a.expr),
            Expr::Literal(value, _) => {
                let ty = vm_type_from_data_type(&value.data_type(), value.is_null())
                    .ok_or(UnsupportedSourceDomain)?;
                validate_decimal_scalar_value(value)
                    .map_err(|_| UnsupportedSourceDomain)?;
                (
                    N::Source(VmSourceRef::Literal(value.clone())),
                    ty,
                    1,
                    1,
                    true,
                )
            }
            Expr::Column(c) => {
                let source = if let Some(c) = self
                    .context
                    .managed
                    .iter()
                    .find(|x| x.column_name == c.name)
                {
                    let scalar = c.scalar_type.ok_or(UnsupportedSourceDomain)?;
                    vm_type_from_data_type(&scalar.arrow_type(), true)
                        .ok_or(UnsupportedSourceDomain)?;
                    VmSourceRef::ManagedSlot {
                        slot_idx: c.slot_idx as u16,
                        ty: VmType::nullable(scalar),
                    }
                } else {
                    let c = self
                        .context
                        .inputs
                        .iter()
                        .find(|x| x.column_name == c.name)
                        .ok_or(BindingFailure)?;
                    match c.role {
                        VmPredicateInputRole::Metadata(
                            VmMetadataComparisonColumn::MatchNumber,
                        ) => VmSourceRef::MatchNumber,
                        VmPredicateInputRole::Metadata(_) => {
                            VmSourceRef::MatchSequenceNumber
                        }
                        VmPredicateInputRole::StaticPredicate { bool_idx } => {
                            VmSourceRef::StaticPredicate {
                                bool_idx: bool_idx as u16,
                            }
                        }
                        VmPredicateInputRole::Classifier => {
                            return Err(UnsupportedSourceDomain);
                        }
                        role => {
                            let ty = c.ty.ok_or(UnsupportedSourceDomain)?;
                            vm_type_from_data_type(&ty.scalar.arrow_type(), ty.nullable)
                                .ok_or(UnsupportedSourceDomain)?;
                            if let VmPredicateInputRole::StaticScalar { scalar_idx } =
                                role
                            {
                                VmSourceRef::StaticScalar {
                                    scalar_idx: scalar_idx as u16,
                                    ty,
                                }
                            } else {
                                let id = self
                                    .rows
                                    .iter()
                                    .position(|n| n == &c.column_name)
                                    .unwrap_or_else(|| {
                                        self.rows.push(c.column_name.clone());
                                        self.rows.len() - 1
                                    });
                                VmSourceRef::RowValue {
                                    column_ref: id as u16,
                                    ty,
                                }
                            }
                        }
                    }
                };
                let ty = source.output_type();
                (N::Source(source), ty, 1, 1, false)
            }
            // DataFusion simplifies 2-arg COALESCE(x, y) to
            // `CASE WHEN x IS NOT NULL THEN x ELSE y END`. Lower the shared
            // operand once, preserving short-circuit SQL error timing for `y`.
            Expr::Case(case)
                if case.expr.is_none()
                    && case.when_then_expr.len() == 1
                    && case.else_expr.is_some() =>
            {
                let (when, then) = &case.when_then_expr[0];
                if !matches!(when.as_ref(), Expr::IsNotNull(x) if x == then) {
                    return Err(EmissionFailure);
                }
                let else_expr = case.else_expr.as_deref().expect("checked above");
                self.lower_coalesce(then, else_expr)?
            }
            Expr::Not(e)
            | Expr::Negative(e)
            | Expr::IsNull(e)
            | Expr::IsNotNull(e)
            | Expr::Cast(datafusion::logical_expr::expr::Cast { expr: e, .. }) => {
                let (input, mut ty, slots, work, literal) = self.lower(e)?;
                let node = match expr {
                    Expr::IsNull(_) => {
                        ty = VmType::non_null(T::Bool);
                        N::IsNull { input }
                    }
                    Expr::IsNotNull(_) => {
                        ty = VmType::non_null(T::Bool);
                        N::IsNotNull { input }
                    }
                    Expr::Cast(c) => {
                        // Arrow identity casts preserve even out-of-precision decimals.
                        if ty.scalar.arrow_type() == *c.field.data_type() {
                            return Ok((input, ty, slots, work, literal));
                        }
                        let target =
                            vm_type_from_data_type(c.field.data_type(), ty.nullable)
                                .ok_or(UnsupportedCast)?;
                        if !safe_cast(ty.scalar, target.scalar) {
                            return Err(UnsupportedCast);
                        }
                        ty = target;
                        N::Cast {
                            target_ty: ty,
                            input,
                        }
                    }
                    _ => {
                        let op = if matches!(expr, Expr::Not(_)) {
                            if ty.scalar != T::Bool {
                                return Err(unsupported);
                            }
                            VmUnaryOp::Not
                        } else {
                            if !matches!(
                                ty.scalar,
                                T::Int8
                                    | T::Int16
                                    | T::Int32
                                    | T::Int64
                                    | T::MetadataI64
                                    | T::Float64
                                    | T::Decimal128 { .. }
                            ) {
                                return Err(unsupported);
                            }
                            if literal {
                                VmUnaryOp::CheckedNeg
                            } else {
                                VmUnaryOp::Neg
                            }
                        };
                        N::Unary {
                            op,
                            out_ty: ty,
                            input,
                        }
                    }
                };
                (node, ty, slots, work + 1, literal)
            }
            Expr::BinaryExpr(b) => {
                if matches!(b.op, Operator::Plus | Operator::Minus)
                    && let Some((base_expr, interval_lit)) =
                        match (b.left.as_ref(), b.right.as_ref()) {
                            (lhs, Expr::Literal(lit, _))
                                if is_fixed_interval_literal(lit) =>
                            {
                                Some((lhs, lit))
                            }
                            (Expr::Literal(lit, _), rhs)
                                if b.op == Operator::Plus
                                    && is_fixed_interval_literal(lit) =>
                            {
                                Some((rhs, lit))
                            }
                            _ => None,
                        }
                {
                    let (left, l, ls, lw, ll) = self.lower(base_expr)?;
                    let delta = fixed_temporal_interval_delta(l.scalar, interval_lit)
                        .ok_or(unsupported)?;
                    if self.nodes.len() >= self.context.limits.max_ir_nodes {
                        return Err(ExpressionTooLarge);
                    }
                    let right = self.nodes.len() as u16;
                    let nullable = l.nullable || delta.is_null();
                    self.nodes.push(N::Source(VmSourceRef::Literal(delta)));
                    let out_ty = VmType {
                        scalar: l.scalar,
                        nullable,
                    };
                    let op = if b.op == Operator::Plus {
                        VmBinaryOp::AddInterval
                    } else {
                        VmBinaryOp::SubInterval
                    };
                    (
                        N::Binary {
                            op,
                            out_ty,
                            left,
                            right,
                        },
                        out_ty,
                        ls.max(2),
                        lw + 2,
                        ll,
                    )
                } else {
                    let (left, l, ls, lw, ll) = self.lower(&b.left)?;
                    let (right, r, rs, rw, rl) = self.lower(&b.right)?;
                    let (op, scalar) =
                        binary_type(b.op, l.scalar, r.scalar).ok_or(unsupported)?;
                    let nullable = if matches!(
                        op,
                        VmBinaryOp::IsDistinctFrom | VmBinaryOp::IsNotDistinctFrom
                    ) {
                        false
                    } else {
                        l.nullable || r.nullable
                    };
                    let out_ty = VmType { scalar, nullable };
                    (
                        N::Binary {
                            op,
                            out_ty,
                            left,
                            right,
                        },
                        out_ty,
                        ls.max(rs + 1),
                        lw + rw
                            + 1
                            + usize::from(matches!(op, VmBinaryOp::And | VmBinaryOp::Or)),
                        ll && rl,
                    )
                }
            }
            Expr::TryCast(_) => return Err(UnsupportedCast),
            Expr::ScalarFunction(func)
                if func.func == datafusion::functions::core::coalesce()
                    && func.args.len() == 2 =>
            {
                self.lower_coalesce(&func.args[0], &func.args[1])?
            }
            Expr::ScalarFunction(func)
                if func.func == datafusion::functions::math::abs()
                    && func.args.len() == 1 =>
            {
                let (input, ty, slots, work, literal) = self.lower(&func.args[0])?;
                if !matches!(
                    ty.scalar,
                    T::Int8
                        | T::Int16
                        | T::Int32
                        | T::Int64
                        | T::MetadataI64
                        | T::Float64
                        | T::Decimal128 { .. }
                ) {
                    return Err(unsupported);
                }
                (
                    N::Unary {
                        op: VmUnaryOp::Abs,
                        out_ty: ty,
                        input,
                    },
                    ty,
                    slots,
                    work + 1,
                    literal,
                )
            }
            Expr::ScalarFunction(_) => return Err(UnsupportedFunctionSignature),
            _ => return Err(EmissionFailure),
        };
        // This type mapper also serves aggregate storage admission. Predicate
        // admission is narrower and must not disable retained FIRST storage.
        if matches!(ty.scalar, T::Decimal256 { .. } | T::FixedSizeBinary(_)) {
            return Err(UnsupportedSourceDomain);
        }
        if self.nodes.len() >= self.context.limits.max_ir_nodes {
            return Err(ExpressionTooLarge);
        }
        let id = self.nodes.len() as u16;
        self.nodes.push(node);
        Ok((id, ty, slots, work, literal))
    }

    fn lower_coalesce(
        &mut self,
        first: &Expr,
        second: &Expr,
    ) -> Result<(PredicateNode, VmType, usize, usize, bool), VmCompileError> {
        use PredicateNode as N;
        use VmScalarType as T;

        // Fast path for COALESCE(boolean, false) -> IsTrue(first).
        if matches!(second, Expr::Literal(ScalarValue::Boolean(Some(false)), _)) {
            let (input, ty, slots, work, literal) = self.lower(first)?;
            if ty.scalar != T::Bool {
                return Err(VmCompileError::UnsupportedFunctionSignature);
            }
            let out_ty = VmType::non_null(T::Bool);
            return Ok((
                N::Unary {
                    op: VmUnaryOp::IsTrue,
                    out_ty,
                    input,
                },
                out_ty,
                slots,
                work + 1,
                literal,
            ));
        }

        let (left, l, ls, lw, ll) = self.lower(first)?;
        let (right, r, rs, rw, rl) = self.lower(second)?;
        let scalar = coalesce_scalar_type(l.scalar, r.scalar)
            .ok_or(VmCompileError::UnsupportedFunctionSignature)?;
        let out_ty = VmType {
            scalar,
            nullable: l.nullable && r.nullable,
        };
        Ok((
            N::Coalesce {
                left,
                right,
                out_ty,
            },
            out_ty,
            ls.max(rs),
            lw + rw + 2,
            ll && rl,
        ))
    }
}

fn is_fixed_interval_literal(value: &ScalarValue) -> bool {
    matches!(
        value,
        ScalarValue::IntervalMonthDayNano(_) | ScalarValue::IntervalDayTime(_)
    )
}

/// Convert a month-free interval literal whose sub-unit remainder is zero into
/// native ticks for `Date32`, `Date64`, or any naive `Timestamp(unit, None)`.
///
/// Runtime `AddInterval` / `SubInterval` enforces Arrow/chrono calendar bounds
/// (and `Date64` midnight normalization) so behavior matches Arrow kernels.
fn fixed_temporal_interval_delta(
    target: VmScalarType,
    interval: &ScalarValue,
) -> Option<ScalarValue> {
    use datafusion::arrow::temporal_conversions::{
        MICROSECONDS_IN_DAY, MILLISECONDS_IN_DAY, NANOSECONDS_IN_DAY, SECONDS_IN_DAY,
    };

    let (days, nanos) = match interval {
        ScalarValue::IntervalMonthDayNano(None) | ScalarValue::IntervalDayTime(None) => {
            return Some(match target {
                VmScalarType::Date32 => ScalarValue::Date32(None),
                VmScalarType::Date64 => ScalarValue::Date64(None),
                VmScalarType::Timestamp {
                    unit: TimeUnit::Second,
                    timezone_aware: false,
                } => ScalarValue::TimestampSecond(None, None),
                VmScalarType::Timestamp {
                    unit: TimeUnit::Millisecond,
                    timezone_aware: false,
                } => ScalarValue::TimestampMillisecond(None, None),
                VmScalarType::Timestamp {
                    unit: TimeUnit::Microsecond,
                    timezone_aware: false,
                } => ScalarValue::TimestampMicrosecond(None, None),
                VmScalarType::Timestamp {
                    unit: TimeUnit::Nanosecond,
                    timezone_aware: false,
                } => ScalarValue::TimestampNanosecond(None, None),
                _ => return None,
            });
        }
        ScalarValue::IntervalMonthDayNano(Some(iv))
            if iv.months == 0
                && ((iv.days >= 0 && iv.nanoseconds >= 0)
                    || (iv.days <= 0 && iv.nanoseconds <= 0)) =>
        {
            (iv.days, iv.nanoseconds)
        }
        ScalarValue::IntervalDayTime(Some(iv))
            if (iv.days >= 0 && iv.milliseconds >= 0)
                || (iv.days <= 0 && iv.milliseconds <= 0) =>
        {
            (iv.days, i64::from(iv.milliseconds).checked_mul(1_000_000)?)
        }
        _ => return None,
    };

    let scaled_ticks = |ticks_per_day: i64, nanos_per_tick: i64| -> Option<i64> {
        if nanos % nanos_per_tick != 0 {
            return None;
        }
        i64::from(days)
            .checked_mul(ticks_per_day)?
            .checked_add(nanos / nanos_per_tick)
    };

    match target {
        VmScalarType::Date32 if nanos == 0 => Some(ScalarValue::Date32(Some(days))),
        VmScalarType::Date64 if nanos == 0 => Some(ScalarValue::Date64(Some(
            i64::from(days).checked_mul(MILLISECONDS_IN_DAY)?,
        ))),
        VmScalarType::Timestamp {
            unit: TimeUnit::Second,
            timezone_aware: false,
        } => Some(ScalarValue::TimestampSecond(
            Some(scaled_ticks(SECONDS_IN_DAY, 1_000_000_000)?),
            None,
        )),
        VmScalarType::Timestamp {
            unit: TimeUnit::Millisecond,
            timezone_aware: false,
        } => Some(ScalarValue::TimestampMillisecond(
            Some(scaled_ticks(MILLISECONDS_IN_DAY, 1_000_000)?),
            None,
        )),
        VmScalarType::Timestamp {
            unit: TimeUnit::Microsecond,
            timezone_aware: false,
        } => Some(ScalarValue::TimestampMicrosecond(
            Some(scaled_ticks(MICROSECONDS_IN_DAY, 1_000)?),
            None,
        )),
        VmScalarType::Timestamp {
            unit: TimeUnit::Nanosecond,
            timezone_aware: false,
        } => Some(ScalarValue::TimestampNanosecond(
            Some(scaled_ticks(NANOSECONDS_IN_DAY, 1)?),
            None,
        )),
        _ => None,
    }
}

fn normalize(t: VmScalarType) -> VmScalarType {
    if t == VmScalarType::MetadataI64 {
        VmScalarType::Int64
    } else {
        t
    }
}

fn signed_rank(t: VmScalarType) -> Option<u8> {
    use VmScalarType as T;
    match t {
        T::Int8 => Some(0),
        T::Int16 => Some(1),
        T::Int32 => Some(2),
        T::Int64 => Some(3),
        _ => None,
    }
}

fn unsigned_rank(t: VmScalarType) -> Option<u8> {
    use VmScalarType as T;
    match t {
        T::UInt8 => Some(0),
        T::UInt16 => Some(1),
        T::UInt32 => Some(2),
        T::UInt64 => Some(3),
        _ => None,
    }
}

fn widen_signed(a: VmScalarType, b: VmScalarType) -> Option<VmScalarType> {
    let (ra, rb) = (signed_rank(a)?, signed_rank(b)?);
    Some(if ra >= rb { a } else { b })
}

fn widen_unsigned(a: VmScalarType, b: VmScalarType) -> Option<VmScalarType> {
    let (ra, rb) = (unsigned_rank(a)?, unsigned_rank(b)?);
    Some(if ra >= rb { a } else { b })
}

fn coalesce_scalar_type(a: VmScalarType, b: VmScalarType) -> Option<VmScalarType> {
    use VmScalarType as T;
    let na = normalize(a);
    let nb = normalize(b);
    if na == nb {
        return Some(if a == b { a } else { na });
    }
    if let (
        T::Decimal128 {
            precision: p1,
            scale: s1,
        },
        T::Decimal128 {
            precision: p2,
            scale: s2,
        },
    ) = (na, nb)
        && s1 == s2
    {
        return Some(T::Decimal128 {
            precision: p1.max(p2),
            scale: s1,
        });
    }
    if let Some(widened) = widen_signed(na, nb).or_else(|| widen_unsigned(na, nb)) {
        return Some(widened);
    }
    if na.is_string() && nb.is_string() {
        return Some(na);
    }
    None
}

fn safe_cast(a: VmScalarType, b: VmScalarType) -> bool {
    use VmScalarType::*;
    let a = normalize(a);
    let b = normalize(b);
    a == b
        || signed_rank(a)
            .zip(signed_rank(b))
            .is_some_and(|(ra, rb)| ra <= rb)
        || unsigned_rank(a)
            .zip(unsigned_rank(b))
            .is_some_and(|(ra, rb)| ra <= rb)
        || matches!(
            (a, b),
            (
                Int8 | Int16
                    | Int32
                    | Int64
                    | UInt8
                    | UInt16
                    | UInt32
                    | UInt64
                    | Float32
                    | Decimal128 { .. },
                Float64
            ) | (Float64, Decimal128 { .. })
        )
        || matches!((a,b),(Decimal128 {scale:a,..},Decimal128 {scale:b,..}) if b>=a && i16::from(b) - i16::from(a) <= 38)
}
fn binary_type(
    op: Operator,
    a: VmScalarType,
    b: VmScalarType,
) -> Option<(VmBinaryOp, VmScalarType)> {
    use VmBinaryOp as O;
    use VmScalarType as T;
    let a = normalize(a);
    let b = normalize(b);
    let cmp = match op {
        Operator::Eq => Some(O::Eq),
        Operator::NotEq => Some(O::Ne),
        Operator::Lt => Some(O::Lt),
        Operator::LtEq => Some(O::Le),
        Operator::Gt => Some(O::Gt),
        Operator::GtEq => Some(O::Ge),
        Operator::IsDistinctFrom => Some(O::IsDistinctFrom),
        Operator::IsNotDistinctFrom => Some(O::IsNotDistinctFrom),
        _ => None,
    };
    let same_decimal =
        matches!((a,b),(T::Decimal128 {scale:a,..},T::Decimal128 {scale:b,..}) if a==b);
    if let Some(cmp) = cmp {
        let same = a == b
            || same_decimal
            || (signed_rank(a).is_some() && signed_rank(b).is_some())
            || (unsigned_rank(a).is_some() && unsigned_rank(b).is_some());
        if (same && !a.is_string()) || (a.is_string() && b.is_string()) {
            return Some((cmp, T::Bool));
        }
        return None;
    }
    if a == T::Bool && b == T::Bool {
        return match op {
            Operator::And => Some((O::And, T::Bool)),
            Operator::Or => Some((O::Or, T::Bool)),
            _ => None,
        };
    }
    let binary = match op {
        Operator::Plus => O::Add,
        Operator::Minus => O::Sub,
        Operator::Multiply => O::Mul,
        _ => return None,
    };
    if let Some(widened) = widen_signed(a, b).or_else(|| widen_unsigned(a, b)) {
        return Some((binary, widened));
    }
    if a == b && a == T::Float64 {
        return Some((binary, a));
    }
    if binary != O::Mul {
        match (a, b, binary) {
            (T::Duration(u1), T::Duration(u2), _) if u1 == u2 => {
                return Some((binary, T::Duration(u1)));
            }
            (
                T::Timestamp {
                    unit: u1,
                    timezone_aware: false,
                },
                T::Timestamp {
                    unit: u2,
                    timezone_aware: false,
                },
                O::Sub,
            ) if u1 == u2 => {
                return Some((O::Sub, T::Duration(u1)));
            }
            (
                ts @ T::Timestamp {
                    unit: u1,
                    timezone_aware: false,
                },
                T::Duration(u2),
                _,
            ) if u1 == u2 => {
                return Some((binary, ts));
            }
            (
                T::Duration(u1),
                ts @ T::Timestamp {
                    unit: u2,
                    timezone_aware: false,
                },
                O::Add,
            ) if u1 == u2 => {
                return Some((O::Add, ts));
            }
            _ => {}
        }
    }
    if let (T::Decimal128 { scale: s1, .. }, T::Decimal128 { scale: s2, .. }) = (a, b) {
        let result = BinaryTypeCoercer::new(&a.arrow_type(), &op, &b.arrow_type())
            .get_result_type()
            .ok()?;
        let result = vm_type_from_data_type(&result, true)?.scalar;
        let T::Decimal128 { scale: s_out, .. } = result else {
            return None;
        };
        if binary == O::Mul {
            if i16::from(s_out) != i16::from(s1) + i16::from(s2) {
                return None;
            }
        } else if s_out != s1.max(s2) {
            // Precision-capped additions/subtractions that reduce output scale require
            // rounding; leave them on Arrow's evaluator.
            return None;
        }
        return Some((binary, result));
    }
    None
}