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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
// 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.

//! Conservative proof for scalar expressions prepared before candidate selection.

use datafusion::arrow::array::{Array, StringArray};
use datafusion::arrow::compute::{DatePart, ilike, like};
use datafusion::arrow::datatypes::{
    DECIMAL32_MAX_PRECISION, DECIMAL64_MAX_PRECISION, DECIMAL128_MAX_PRECISION,
    DECIMAL256_MAX_PRECISION, DataType, Field, FieldRef, TimeUnit,
};
use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion::common::{DFSchema, Result, ScalarValue, plan_datafusion_err};
use datafusion::logical_expr::expr::{Between, BinaryExpr, Case, Like, ScalarFunction};
use datafusion::logical_expr::type_coercion::binary::{
    BinaryTypeCoercer, comparison_coercion, like_coercion, string_coercion,
};
use datafusion::logical_expr::type_coercion::functions::fields_with_udf;
use datafusion::logical_expr::type_coercion::other::get_coerce_type_for_case_expression;
use datafusion::logical_expr::{Expr, ExprSchemable, Operator, ReturnFieldArgs};
use std::collections::HashMap;
use std::sync::Arc;

type ProvenTypes = HashMap<*const Expr, DataType>;

/// Whether a scalar type supports total ordering without nested or dictionary
/// comparison scratch/errors in DataFusion built-in aggregates.
pub(crate) fn scalar_ordering_type_is_safe(data_type: &DataType) -> bool {
    !data_type.is_nested()
        && !matches!(
            data_type,
            DataType::Dictionary(_, _)
                | DataType::RunEndEncoded(_, _)
                | DataType::Union(_, _)
        )
        && scalar_value_type_is_safe(data_type)
}

fn decimal_precision_and_scale_is_valid(
    precision: u8,
    scale: i8,
    max_precision: u8,
) -> bool {
    (1..=max_precision).contains(&precision)
        && (-i16::from(precision)..=i16::from(precision)).contains(&i16::from(scale))
}

/// Whether an Arrow type converts cleanly to and from `ScalarValue` and Arrow
/// null arrays without `NotImplemented` errors, invalid decimal/time bounds,
/// run-end overflow, or unsupported container errors/panics.
pub(crate) fn scalar_value_type_is_safe(data_type: &DataType) -> bool {
    match data_type {
        DataType::RunEndEncoded(_, _) | DataType::Union(_, _) => false,
        DataType::Decimal32(precision, scale) => decimal_precision_and_scale_is_valid(
            *precision,
            *scale,
            DECIMAL32_MAX_PRECISION,
        ),
        DataType::Decimal64(precision, scale) => decimal_precision_and_scale_is_valid(
            *precision,
            *scale,
            DECIMAL64_MAX_PRECISION,
        ),
        DataType::Decimal128(precision, scale) => decimal_precision_and_scale_is_valid(
            *precision,
            *scale,
            DECIMAL128_MAX_PRECISION,
        ),
        DataType::Decimal256(precision, scale) => decimal_precision_and_scale_is_valid(
            *precision,
            *scale,
            DECIMAL256_MAX_PRECISION,
        ),
        DataType::Time32(unit) => {
            matches!(unit, TimeUnit::Second | TimeUnit::Millisecond)
        }
        DataType::Time64(unit) => {
            matches!(unit, TimeUnit::Microsecond | TimeUnit::Nanosecond)
        }
        DataType::Dictionary(key, value) => {
            key.is_integer() && scalar_value_type_is_safe(value)
        }
        DataType::List(field)
        | DataType::LargeList(field)
        | DataType::ListView(field)
        | DataType::LargeListView(field) => scalar_value_type_is_safe(field.data_type()),
        DataType::FixedSizeList(field, len) => {
            *len >= 0 && scalar_value_type_is_safe(field.data_type())
        }
        DataType::FixedSizeBinary(len) => *len >= 0,
        DataType::Map(entries, _) => {
            !entries.is_nullable()
                && matches!(
                    entries.data_type(),
                    DataType::Struct(fields)
                        if fields.len() == 2 && !fields[0].is_nullable()
                )
                && scalar_value_type_is_safe(entries.data_type())
        }
        DataType::Struct(fields) => fields
            .iter()
            .all(|field| scalar_value_type_is_safe(field.data_type())),
        _ => ScalarValue::try_from(data_type).is_ok(),
    }
}

/// Whether a literal `ScalarValue` can be expanded via `to_array_of_size` for
/// any batch size (`0`, `1`, or `> 1`) without panicking or erroring.
fn literal_value_is_safe(value: &ScalarValue) -> bool {
    if !scalar_value_type_is_safe(&value.data_type()) {
        return false;
    }
    match value {
        ScalarValue::FixedSizeBinary(len, Some(bytes)) => {
            usize::try_from(*len).is_ok_and(|expected| bytes.len() == expected)
        }
        ScalarValue::Dictionary(_, inner) => literal_value_is_safe(inner),
        ScalarValue::List(arr) => arr.len() == 1,
        ScalarValue::LargeList(arr) => arr.len() == 1,
        ScalarValue::FixedSizeList(arr) => arr.len() == 1,
        ScalarValue::ListView(arr) => arr.len() == 1,
        ScalarValue::LargeListView(arr) => arr.len() == 1,
        ScalarValue::Struct(arr) => arr.len() == 1,
        ScalarValue::Map(arr) => arr.len() == 1 && arr.entries().null_count() == 0,
        _ => true,
    }
}

/// Removing scalar work must preserve errors, volatility and nested evaluation.
/// Unlike preparation, removal cannot treat aggregates or windows as opaque.
pub(crate) fn can_discard_scalar(expr: &Expr, schema: Option<&DFSchema>) -> bool {
    !expr.is_volatile()
        && !expr
            .exists(|node| {
                Ok(matches!(
                    node,
                    Expr::AggregateFunction(_) | Expr::WindowFunction(_)
                ))
            })
            .unwrap_or(true)
        && schema.map_or_else(
            || can_precompute(expr, &DFSchema::empty()),
            |schema| can_precompute(expr, schema),
        )
}

pub(crate) fn can_precompute(expr: &Expr, schema: &DFSchema) -> bool {
    let mut pending = vec![expr];
    let mut coercions = Vec::new();
    while let Some(node) = pending.pop() {
        match node {
            // Existing aggregates and navigation retain their evaluation scope.
            Expr::AggregateFunction(_) | Expr::WindowFunction(_) => continue,
            Expr::Column(_) | Expr::Alias(_) | Expr::IsNull(_) | Expr::IsNotNull(_) => {}
            // `ScalarValue::to_array_of_size` fails on `RunEndEncoded` for empty batches
            // (`run_ends = [0]`) and `Int16` run-end overflow (`num_rows > 32767`), and
            // `Union` / invalid decimals / invalid container or `FixedSizeBinary`
            // scalars can error or panic when materialized.
            Expr::Literal(value, _) if literal_value_is_safe(value) => {}
            Expr::BinaryExpr(binary)
                if matches!(
                    binary.op,
                    Operator::And
                        | Operator::Or
                        | Operator::Eq
                        | Operator::NotEq
                        | Operator::Lt
                        | Operator::LtEq
                        | Operator::Gt
                        | Operator::GtEq
                        | Operator::IsDistinctFrom
                        | Operator::IsNotDistinctFrom
                        | Operator::Plus
                        | Operator::Minus
                        | Operator::Multiply
                        | Operator::Divide
                        | Operator::Modulo
                ) =>
            {
                coercions.push(node)
            }
            Expr::Not(_)
            | Expr::IsTrue(_)
            | Expr::IsFalse(_)
            | Expr::IsUnknown(_)
            | Expr::IsNotTrue(_)
            | Expr::IsNotFalse(_)
            | Expr::IsNotUnknown(_)
            | Expr::Cast(_)
            | Expr::Between(_)
            | Expr::InList(_)
            | Expr::Like(_)
            | Expr::Case(_)
            | Expr::ScalarFunction(_) => coercions.push(node),
            // Expressions outside the proof retain their candidate evaluation.
            _ => return false,
        }
        if node
            .apply_children(|child| {
                pending.push(child);
                Ok(TreeNodeRecursion::Continue)
            })
            .is_err()
        {
            return false;
        }
    }
    // Reverse preorder proves children before their parents. Cache derived
    // types by node identity to avoid deriving nested types again.
    let mut proven_types = ProvenTypes::new();
    coercions.into_iter().rev().all(|node| match node {
        Expr::BinaryExpr(binary) => match binary.op {
            Operator::Plus
            | Operator::Minus
            | Operator::Multiply
            | Operator::Divide
            | Operator::Modulo => {
                let Some(data_type) = arithmetic_type(binary, schema, &proven_types)
                else {
                    return false;
                };
                proven_types.insert(std::ptr::from_ref(node), data_type);
                true
            }
            Operator::And | Operator::Or => [&binary.left, &binary.right]
                .iter()
                .all(|value| is_boolean(value, schema, &proven_types)),
            op => {
                comparison_is_safe(&binary.left, op, &binary.right, schema, &proven_types)
            }
        },
        Expr::Cast(cast) => {
            scalar_type(&cast.expr, schema, &proven_types).is_ok_and(|source| {
                input_cast_is_safe(&cast.expr, &source, cast.field.data_type())
            })
        }
        Expr::Between(between) => between_is_safe(between, schema, &proven_types),
        Expr::InList(list) => {
            let Ok(value) = scalar_type(&list.expr, schema, &proven_types) else {
                return false;
            };
            let Ok(types) = list
                .list
                .iter()
                .map(|item| scalar_type(item, schema, &proven_types))
                .collect::<Result<Vec<_>>>()
            else {
                return false;
            };
            // DataFusion casts the whole list to one type. Pairwise checks
            // miss casts introduced by later members when the probe is NULL.
            let target = types.iter().try_fold(value.clone(), |left, right| {
                comparison_coercion(&left, right)
            });
            // This proof has no session settings. Timestamp conversions are
            // rejected below, so timezone-dependent casts remain candidate-local.
            // `InListExpr` also expands its probe via `into_array(num_rows)`,
            // which fails for `RunEndEncoded` scalars on empty or >32767-row batches.
            target.is_some_and(|target| {
                !matches!(target, DataType::RunEndEncoded(_, _))
                    && comparison_type_is_safe(&target, false)
                    && std::iter::once(&value).chain(&types).all(|source| {
                        !matches!(source, DataType::RunEndEncoded(_, _))
                            && comparison_type_is_safe(source, false)
                            && cast_is_safe(source, &target)
                    })
            })
        }
        Expr::Like(like_expr) => like_is_safe(like_expr, schema, &proven_types),
        Expr::Case(case_expr) => {
            let Some(data_type) = case_type(case_expr, schema, &proven_types) else {
                return false;
            };
            proven_types.insert(std::ptr::from_ref(node), data_type);
            true
        }
        Expr::ScalarFunction(func) => {
            let Some(data_type) = scalar_function_type(func, schema, &proven_types)
            else {
                return false;
            };
            proven_types.insert(std::ptr::from_ref(node), data_type);
            true
        }
        Expr::Not(value)
        | Expr::IsTrue(value)
        | Expr::IsFalse(value)
        | Expr::IsUnknown(value)
        | Expr::IsNotTrue(value)
        | Expr::IsNotFalse(value)
        | Expr::IsNotUnknown(value) => is_boolean(value, schema, &proven_types),
        _ => unreachable!("only coercion-sensitive nodes were collected"),
    })
}

fn is_boolean(expr: &Expr, schema: &DFSchema, proven_types: &ProvenTypes) -> bool {
    matches!(
        scalar_type(expr, schema, proven_types),
        Ok(DataType::Boolean)
    )
}

fn scalar_type(
    mut expr: &Expr,
    schema: &DFSchema,
    proven_types: &ProvenTypes,
) -> Result<DataType> {
    while let Expr::Alias(alias) = expr {
        expr = &alias.expr;
    }
    // Arithmetic and proven scalar-function children were already proved;
    // Boolean operators need no recursive type derivation along a long AND/OR chain.
    if matches!(
        expr,
        Expr::BinaryExpr(BinaryExpr {
            op: Operator::Plus
                | Operator::Minus
                | Operator::Multiply
                | Operator::Divide
                | Operator::Modulo,
            ..
        }) | Expr::Case(_)
            | Expr::ScalarFunction(_)
    ) {
        return proven_types
            .get(&std::ptr::from_ref(expr))
            .cloned()
            .ok_or_else(|| {
                plan_datafusion_err!(
                    "expression cannot be prepared before candidate selection"
                )
            });
    }
    match expr {
        Expr::BinaryExpr(_)
        | Expr::Not(_)
        | Expr::IsNull(_)
        | Expr::IsNotNull(_)
        | Expr::IsTrue(_)
        | Expr::IsFalse(_)
        | Expr::IsUnknown(_)
        | Expr::IsNotTrue(_)
        | Expr::IsNotFalse(_)
        | Expr::IsNotUnknown(_)
        | Expr::Between(_)
        | Expr::InList(_)
        | Expr::Like(_) => Ok(DataType::Boolean),
        _ => expr.get_type(schema),
    }
}

fn like_is_safe(like_expr: &Like, schema: &DFSchema, proven_types: &ProvenTypes) -> bool {
    if like_expr.escape_char.is_some() {
        return false;
    }
    let (Ok(expr_type), Ok(pattern_type)) = (
        scalar_type(&like_expr.expr, schema, proven_types),
        scalar_type(&like_expr.pattern, schema, proven_types),
    ) else {
        return false;
    };
    let Some(target) = like_coercion(&expr_type, &pattern_type) else {
        return false;
    };
    if !matches!(
        target,
        DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
    ) || !cast_is_safe(&expr_type, &target)
        || !cast_is_safe(&pattern_type, &target)
    {
        return false;
    }
    // Only literal patterns can be proven not to fail regex compilation (e.g.
    // CompiledTooBig) at evaluation time. Probe Arrow's kernel with a non-ASCII
    // value so both ASCII and Unicode case-folding paths are validated.
    let mut pattern = like_expr.pattern.as_ref();
    while let Expr::Alias(alias) = pattern {
        pattern = alias.expr.as_ref();
    }
    let Expr::Literal(value, _) = pattern else {
        return false;
    };
    let pat = match value {
        ScalarValue::Null
        | ScalarValue::Utf8(None)
        | ScalarValue::LargeUtf8(None)
        | ScalarValue::Utf8View(None) => return true,
        ScalarValue::Utf8(Some(pat))
        | ScalarValue::LargeUtf8(Some(pat))
        | ScalarValue::Utf8View(Some(pat)) => pat.as_str(),
        _ => return false,
    };
    like_pattern_is_safe(pat, like_expr.case_insensitive)
}

fn like_pattern_is_safe(pattern: &str, case_insensitive: bool) -> bool {
    let probe = StringArray::from(vec!["é"]);
    let scalar_pattern = StringArray::new_scalar(pattern);
    if case_insensitive {
        ilike(&probe, &scalar_pattern).is_ok()
    } else {
        like(&probe, &scalar_pattern).is_ok()
    }
}

fn case_type(
    case: &Case,
    schema: &DFSchema,
    proven_types: &ProvenTypes,
) -> Option<DataType> {
    if case.when_then_expr.is_empty() {
        return None;
    }
    if let Some(base) = &case.expr {
        let base_type = scalar_type(base, schema, proven_types).ok()?;
        let when_types = case
            .when_then_expr
            .iter()
            .map(|(when, _)| scalar_type(when, schema, proven_types))
            .collect::<Result<Vec<_>>>()
            .ok()?;
        // DataFusion coerces the CASE base expression and all WHEN values to one
        // common comparison type. Pairwise checks miss casts introduced across
        // multiple WHEN branches (e.g. a NULL base or mixed decimal scales).
        let target = when_types
            .iter()
            .try_fold(base_type.clone(), |left, right| {
                comparison_coercion(&left, right)
            })?;
        // `CaseBody::case_when_with_expr` expands the base expression via
        // `into_array(batch.num_rows())`, which fails for `RunEndEncoded`
        // scalars on empty or >32767-row batches.
        if matches!(target, DataType::RunEndEncoded(_, _))
            || !comparison_type_is_safe(&target, false)
            || matches!(base_type, DataType::RunEndEncoded(_, _))
            || !comparison_type_is_safe(&base_type, false)
            || !input_cast_is_safe(base, &base_type, &target)
            || !case.when_then_expr.iter().zip(&when_types).all(
                |((when, _), when_type)| {
                    !matches!(when_type, DataType::RunEndEncoded(_, _))
                        && comparison_type_is_safe(when_type, false)
                        && input_cast_is_safe(when, when_type, &target)
                },
            )
        {
            return None;
        }
    } else if !case
        .when_then_expr
        .iter()
        .all(|(when, _)| is_boolean(when, schema, proven_types))
    {
        return None;
    }
    let then_types = case
        .when_then_expr
        .iter()
        .map(|(_, then)| scalar_type(then, schema, proven_types))
        .collect::<Result<Vec<_>>>()
        .ok()?;
    let else_type = case
        .else_expr
        .as_ref()
        .map(|else_expr| scalar_type(else_expr, schema, proven_types))
        .transpose()
        .ok()?;
    let target = get_coerce_type_for_case_expression(&then_types, else_type.as_ref())?;
    // Merging values from separate dictionaries can exhaust the result's key type,
    // RunEndEncoded results can fail on non-nullable nullif or Int16 run-end
    // overflow, Union results can fail on non-nullable fields or panic when
    // empty, and invalid scalar/container bounds fail null-array creation.
    if contains_unsupported_merge_type(&target) || !scalar_value_type_is_safe(&target) {
        return None;
    }
    let then_safe = case
        .when_then_expr
        .iter()
        .zip(&then_types)
        .all(|((_, then), from)| input_cast_is_safe(then, from, &target));
    let else_safe = case
        .else_expr
        .as_deref()
        .zip(else_type.as_ref())
        .is_none_or(|(else_expr, from)| input_cast_is_safe(else_expr, from, &target));
    (then_safe && else_safe).then_some(target)
}

fn scalar_function_type(
    func: &ScalarFunction,
    schema: &DFSchema,
    proven_types: &ProvenTypes,
) -> Option<DataType> {
    if func.func == datafusion::functions::unicode::substr() {
        return substr_type(&func.args, schema, proven_types);
    }
    if func.func == datafusion::functions::unicode::character_length()
        || func.func == datafusion::functions::string::bit_length()
    {
        return character_length_type(&func.args, schema, proven_types);
    }
    if func.func == datafusion::functions::string::octet_length() {
        return octet_length_type(&func.args, schema, proven_types);
    }
    if func.func == datafusion::functions::string::ascii()
        || func.func == datafusion::functions::unicode::strpos()
        || func.func == datafusion::functions::unicode::translate()
    {
        return coerced_udf_type(func, schema, proven_types, |coerced, _| {
            coerced.iter().all(is_plain_string)
        });
    }
    if func.func == datafusion::functions::string::lower()
        || func.func == datafusion::functions::string::upper()
        || func.func == datafusion::functions::unicode::reverse()
        || func.func == datafusion::functions::unicode::initcap()
    {
        return unary_string_type(&func.args, schema, proven_types);
    }
    if func.func == datafusion::functions::string::btrim()
        || func.func == datafusion::functions::string::ltrim()
        || func.func == datafusion::functions::string::rtrim()
    {
        return trim_type(&func.args, schema, proven_types);
    }
    if func.func == datafusion::functions::string::replace() {
        return coerced_udf_type(func, schema, proven_types, |coerced, _| {
            coerced
                .split_first()
                .and_then(|(first, rest)| {
                    rest.iter()
                        .try_fold(first.clone(), |acc, dt| string_coercion(&acc, dt))
                })
                .is_some_and(|target| {
                    is_plain_string(&target)
                        && coerced
                            .iter()
                            .all(|t| is_plain_string(t) && cast_is_safe(t, &target))
                })
        });
    }
    let is_concat_ws = func.func == datafusion::functions::string::concat_ws();
    if is_concat_ws || func.func == datafusion::functions::string::concat() {
        if !concat_args_are_safe(&func.args, is_concat_ws) {
            return None;
        }
        return coerced_udf_type(func, schema, proven_types, |coerced, ret| {
            is_plain_string(ret)
                && coerced
                    .iter()
                    .all(|t| (is_plain_string(t) || t.is_null()) && cast_is_safe(t, ret))
        });
    }
    if func.func == datafusion::functions::unicode::left()
        || func.func == datafusion::functions::unicode::right()
    {
        return coerced_udf_type(
            func,
            schema,
            proven_types,
            |coerced, _| matches!(coerced, [s, DataType::Int64] if is_plain_string(s)),
        );
    }
    if func.func == datafusion::functions::string::starts_with() {
        return binary_string_predicate_type(&func.args, schema, proven_types, true);
    }
    if func.func == datafusion::functions::string::ends_with()
        || func.func == datafusion::functions::string::contains()
    {
        return binary_string_predicate_type(&func.args, schema, proven_types, false);
    }
    if func.func == datafusion::functions::math::abs() {
        return abs_type(&func.args, schema, proven_types);
    }
    if func.func == datafusion::functions::math::signum()
        || func.func == datafusion::functions::math::nanvl()
    {
        return coerced_udf_type(func, schema, proven_types, |coerced, _| {
            coerced.iter().all(|t| t.is_floating() || t.is_null())
        });
    }
    if func.func == datafusion::functions::math::isnan()
        || func.func == datafusion::functions::math::iszero()
    {
        return coerced_udf_type(func, schema, proven_types, |coerced, _| {
            coerced
                .iter()
                .all(|t| t.is_null() || (t.is_numeric() && scalar_value_type_is_safe(t)))
        });
    }
    if func.func == datafusion::functions::core::nullif() {
        let [left, right] = func.args.as_slice() else {
            return None;
        };
        let left_type = scalar_type(left, schema, proven_types).ok()?;
        let right_type = scalar_type(right, schema, proven_types).ok()?;
        let target = comparison_coercion(&left_type, &right_type)?;
        // DataFusion's Comparable signature coerces all-NULL inputs to Utf8View.
        let target = if target.is_null() {
            DataType::Utf8View
        } else {
            target
        };
        // NULLIF compares the coerced arrays, then replaces equal values with
        // NULL. Encoded/container values require additional kernel guarantees.
        return (scalar_ordering_type_is_safe(&target)
            && input_cast_is_safe(left, &left_type, &target)
            && input_cast_is_safe(right, &right_type, &target))
        .then_some(target);
    }
    if func.func == datafusion::functions::core::coalesce()
        || func.func == datafusion::functions::core::nvl()
    {
        return coerced_udf_type(func, schema, proven_types, |coerced, ret| {
            !coerced.is_empty()
                && coerced.iter().all(|ty| ty == ret)
                && !contains_unsupported_merge_type(ret)
        });
    }
    if func.func == datafusion::functions::core::greatest()
        || func.func == datafusion::functions::core::least()
    {
        return coerced_udf_type(func, schema, proven_types, |coerced, ret| {
            !coerced.is_empty()
                && !ret.is_null()
                && scalar_ordering_type_is_safe(ret)
                && !contains_unsupported_merge_type(ret)
        });
    }
    if func.func == datafusion::functions::datetime::date_part() {
        return date_part_type(&func.args, schema, proven_types);
    }
    None
}

/// Delegate signature coercion and return-type resolution directly to
/// DataFusion's `ScalarUDF`, enforcing safe input casts and caller-supplied
/// kernel invariants on the coerced argument and return types.
fn coerced_udf_type(
    func: &ScalarFunction,
    schema: &DFSchema,
    proven_types: &ProvenTypes,
    check_types: impl FnOnce(&[DataType], &DataType) -> bool,
) -> Option<DataType> {
    let arg_types = func
        .args
        .iter()
        .map(|arg| scalar_type(arg, schema, proven_types))
        .collect::<Result<Vec<_>>>()
        .ok()?;
    let input_fields: Vec<FieldRef> = arg_types
        .iter()
        .map(|dt| Arc::new(Field::new("", dt.clone(), true)))
        .collect();
    let coerced_fields = fields_with_udf(&input_fields, func.func.as_ref()).ok()?;
    let coerced: Vec<DataType> = coerced_fields
        .iter()
        .map(|field| field.data_type().clone())
        .collect();
    if coerced.len() != arg_types.len()
        || !func
            .args
            .iter()
            .zip(arg_types.iter().zip(&coerced))
            .all(|(arg, (from, to))| input_cast_is_safe(arg, from, to))
    {
        return None;
    }
    let scalar_arguments = vec![None; coerced_fields.len()];
    let ret = func
        .func
        .return_field_from_args(ReturnFieldArgs {
            arg_fields: &coerced_fields,
            scalar_arguments: &scalar_arguments,
        })
        .ok()?
        .data_type()
        .clone();
    (scalar_value_type_is_safe(&ret) && check_types(&coerced, &ret)).then_some(ret)
}

fn is_plain_string(data_type: &DataType) -> bool {
    matches!(
        data_type,
        DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
    )
}

fn is_null_string_literal(expr: &Expr) -> bool {
    matches!(
        expr,
        Expr::Literal(
            ScalarValue::Null
                | ScalarValue::Utf8(None)
                | ScalarValue::LargeUtf8(None)
                | ScalarValue::Utf8View(None),
            _
        )
    )
}

fn is_non_empty_string_literal(expr: &Expr) -> bool {
    matches!(
        expr,
        Expr::Literal(
            ScalarValue::Utf8(Some(s))
                | ScalarValue::LargeUtf8(Some(s))
                | ScalarValue::Utf8View(Some(s)),
            _
        ) if !s.is_empty()
    )
}

fn concat_args_are_safe(args: &[Expr], is_concat_ws: bool) -> bool {
    // DataFusion's `ConcatFunc::simplify` strips NULL and empty string literals
    // and can collapse to 0-arg `concat()`, which fails `coerce_types` and
    // drops `Utf8View`/`LargeUtf8` return types. `ConcatWsFunc::simplify` folds
    // a literal NULL separator directly to a typed NULL, but for other
    // separators strips NULL values (which can collapse to an invalid 1-arg
    // `concat_ws`) and delegates empty separators to `simplify_concat`.
    // Requiring a literal NULL separator (for `concat_ws`) or a non-empty plain
    // string literal value keeps at least one typed argument alive even after
    // `OptimizeProjections` inlines columns.
    if is_concat_ws {
        let Some((sep, values)) = args.split_first() else {
            return false;
        };
        !values.is_empty()
            && (is_null_string_literal(sep)
                || values.iter().any(is_non_empty_string_literal))
    } else {
        args.iter().any(is_non_empty_string_literal)
    }
}

fn character_length_type(
    args: &[Expr],
    schema: &DFSchema,
    proven_types: &ProvenTypes,
) -> Option<DataType> {
    let [arg] = args else {
        return None;
    };
    match scalar_type(arg, schema, proven_types).ok()? {
        DataType::Utf8 | DataType::Utf8View => Some(DataType::Int32),
        DataType::LargeUtf8 => Some(DataType::Int64),
        _ => None,
    }
}

fn octet_length_type(
    args: &[Expr],
    schema: &DFSchema,
    proven_types: &ProvenTypes,
) -> Option<DataType> {
    let [arg] = args else {
        return None;
    };
    match scalar_type(arg, schema, proven_types).ok()? {
        DataType::Utf8 | DataType::Utf8View | DataType::Binary | DataType::BinaryView => {
            Some(DataType::Int32)
        }
        DataType::FixedSizeBinary(len) if len >= 0 => Some(DataType::Int32),
        DataType::LargeUtf8 | DataType::LargeBinary => Some(DataType::Int64),
        _ => None,
    }
}

fn unary_string_type(
    args: &[Expr],
    schema: &DFSchema,
    proven_types: &ProvenTypes,
) -> Option<DataType> {
    let [arg] = args else {
        return None;
    };
    let str_type = scalar_type(arg, schema, proven_types).ok()?;
    is_plain_string(&str_type).then_some(str_type)
}

fn trim_type(
    args: &[Expr],
    schema: &DFSchema,
    proven_types: &ProvenTypes,
) -> Option<DataType> {
    if !(1..=2).contains(&args.len()) {
        return None;
    }
    let str_type = scalar_type(&args[0], schema, proven_types).ok()?;
    if !is_plain_string(&str_type) {
        return None;
    }
    if let Some(chars) = args.get(1) {
        let chars_type = scalar_type(chars, schema, proven_types).ok()?;
        if !is_plain_string(&chars_type) || !cast_is_safe(&chars_type, &str_type) {
            return None;
        }
    }
    Some(str_type)
}

fn binary_string_predicate_type(
    args: &[Expr],
    schema: &DFSchema,
    proven_types: &ProvenTypes,
    probe_starts_with_like: bool,
) -> Option<DataType> {
    let [left, right] = args else {
        return None;
    };
    let left_type = scalar_type(left, schema, proven_types).ok()?;
    let right_type = scalar_type(right, schema, proven_types).ok()?;
    let target = string_coercion(&left_type, &right_type)?;
    (is_plain_string(&target)
        && cast_is_safe(&left_type, &target)
        && cast_is_safe(&right_type, &target)
        && (!probe_starts_with_like || starts_with_literal_is_safe(right)))
    .then_some(DataType::Boolean)
}

fn starts_with_literal_is_safe(mut expr: &Expr) -> bool {
    while let Expr::Alias(alias) = expr {
        expr = alias.expr.as_ref();
    }
    match expr {
        // OptimizeProjections can inline a literal prefix column before a later
        // SimplifyExpressions pass rewrites starts_with into a fallible LIKE regex.
        Expr::Column(_) => false,
        Expr::Literal(
            ScalarValue::Null
            | ScalarValue::Utf8(None)
            | ScalarValue::LargeUtf8(None)
            | ScalarValue::Utf8View(None),
            _,
        ) => true,
        Expr::Literal(
            ScalarValue::Utf8(Some(prefix))
            | ScalarValue::LargeUtf8(Some(prefix))
            | ScalarValue::Utf8View(Some(prefix)),
            _,
        ) => {
            if !prefix.contains(['%', '_', '\\']) {
                return true;
            }
            // DataFusion's `StartsWithFunc::simplify` rewrites literal `starts_with`
            // calls into `LIKE '<escaped>%'` with `\`, `%`, and `_` escaped. Arrow's
            // LIKE kernel compiles a regex whenever the prefix contains those bytes,
            // which can fail with `CompiledTooBig`.
            let escaped = prefix
                .replace('\\', "\\\\")
                .replace('%', "\\%")
                .replace('_', "\\_");
            like_pattern_is_safe(&format!("{escaped}%"), false)
        }
        // Any other prefix expression (functions, casts, CASE, COALESCE, etc.)
        // may constant-fold into a literal during `SimplifyExpressions` and then
        // rewrite into a failing `LIKE` regex.
        _ => false,
    }
}

fn abs_type(
    args: &[Expr],
    schema: &DFSchema,
    proven_types: &ProvenTypes,
) -> Option<DataType> {
    let [arg] = args else {
        return None;
    };
    let arg_type = scalar_type(arg, schema, proven_types).ok()?;
    // DataFusion's Numeric signature coerces an untyped NULL to Float64.
    // Cache that result type so enclosing expressions see their implicit casts.
    if arg_type.is_null() {
        return Some(DataType::Float64);
    }
    // Signed integers can overflow on `abs(MIN)` and remain candidate-local.
    // Floats, unsigned integers, and valid decimals (`wrapping_abs` in
    // DataFusion's `AbsFunc`) cannot error.
    (matches!(
        arg_type,
        DataType::Float16
            | DataType::Float32
            | DataType::Float64
            | DataType::UInt8
            | DataType::UInt16
            | DataType::UInt32
            | DataType::UInt64
            | DataType::Decimal32(_, _)
            | DataType::Decimal64(_, _)
            | DataType::Decimal128(_, _)
            | DataType::Decimal256(_, _)
    ) && scalar_value_type_is_safe(&arg_type))
    .then_some(arg_type)
}

fn substr_type(
    args: &[Expr],
    schema: &DFSchema,
    proven_types: &ProvenTypes,
) -> Option<DataType> {
    if !(2..=3).contains(&args.len()) {
        return None;
    }
    let str_type = scalar_type(&args[0], schema, proven_types).ok()?;
    if !matches!(
        str_type,
        DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View
    ) {
        return None;
    }
    // DataFusion's `substr` errors only on `start == i64::MIN` (start - 1
    // overflow) or `count < 0`. Require literal Int32/Int64/Null bounds matching
    // `SubstrFunc`'s signature.
    let start = literal_substr_index(&args[1])?;
    if start == Some(i64::MIN) {
        return None;
    }
    if let Some(count_expr) = args.get(2) {
        let count = literal_substr_index(count_expr)?;
        if count.is_some_and(|c| c < 0) {
            return None;
        }
    }
    Some(str_type)
}

fn literal_substr_index(mut expr: &Expr) -> Option<Option<i64>> {
    while let Expr::Alias(alias) = expr {
        expr = alias.expr.as_ref();
    }
    let Expr::Literal(value, _) = expr else {
        return None;
    };
    match value {
        ScalarValue::Null | ScalarValue::Int64(None) | ScalarValue::Int32(None) => {
            Some(None)
        }
        ScalarValue::Int64(Some(v)) => Some(Some(*v)),
        ScalarValue::Int32(Some(v)) => Some(Some(i64::from(*v))),
        _ => None,
    }
}

/// Returns `true` when `data_type` is or contains a type whose Arrow merge,
/// `nullif`, or null-creation kernels can error or panic (`Dictionary`,
/// `RunEndEncoded`, or `Union`).
fn contains_unsupported_merge_type(data_type: &DataType) -> bool {
    match data_type {
        DataType::Dictionary(_, _)
        | DataType::RunEndEncoded(_, _)
        | DataType::Union(_, _) => true,
        DataType::List(field)
        | DataType::ListView(field)
        | DataType::FixedSizeList(field, _)
        | DataType::LargeList(field)
        | DataType::LargeListView(field)
        | DataType::Map(field, _) => contains_unsupported_merge_type(field.data_type()),
        DataType::Struct(fields) => fields
            .iter()
            .any(|f| contains_unsupported_merge_type(f.data_type())),
        _ => false,
    }
}

fn date_part_type(
    args: &[Expr],
    schema: &DFSchema,
    proven_types: &ProvenTypes,
) -> Option<DataType> {
    let [part_expr, value_expr] = args else {
        return None;
    };
    let mut part_expr = part_expr;
    while let Expr::Alias(alias) = part_expr {
        part_expr = alias.expr.as_ref();
    }
    let Expr::Literal(
        ScalarValue::Utf8(Some(part)) | ScalarValue::Utf8View(Some(part)),
        _,
    ) = part_expr
    else {
        return None;
    };
    let Ok(part) = part.parse::<DatePart>() else {
        return None;
    };
    if matches!(
        part,
        DatePart::Millisecond | DatePart::Microsecond | DatePart::Nanosecond
    ) {
        return None;
    }
    // Arrow's `date_part` on Date32, Date64, and timezone-naive Timestamp returns
    // `Ok(Int32Array)` unconditionally (out-of-range dates become NULL).
    // Timezone-aware timestamps are rejected because timezone parsing can fail.
    let value_type = scalar_type(value_expr, schema, proven_types).ok()?;
    matches!(
        value_type,
        DataType::Date32 | DataType::Date64 | DataType::Timestamp(_, None)
    )
    .then_some(DataType::Int32)
}

fn arithmetic_type(
    binary: &BinaryExpr,
    schema: &DFSchema,
    proven_types: &ProvenTypes,
) -> Option<DataType> {
    let left = scalar_type(&binary.left, schema, proven_types).ok()?;
    let right = scalar_type(&binary.right, schema, proven_types).ok()?;
    // Same-width IEEE 754 floating-point arithmetic (+, -, *, /, %) uses
    // Arrow's `float_op` (`*_wrapping`), returning Inf/NaN without erroring.
    // Keep each operation's original width, including nested Float32 rounding.
    if left == right && matches!(left, DataType::Float32 | DataType::Float64) {
        return Some(left);
    }
    let coercer = BinaryTypeCoercer::new(&left, &binary.op, &right);
    if binary.op == Operator::Modulo {
        // Arrow's integer remainder wraps MIN % -1. Only zero can throw
        // once both operands have been losslessly coerced to the same integer.
        let Expr::Literal(divisor, _) = binary.right.as_ref() else {
            return None;
        };
        let (lhs, rhs) = coercer.get_input_types().ok()?;
        return (left.is_integer()
            && right.is_integer()
            && lhs.is_integer()
            && lhs == rhs
            && cast_is_safe(&left, &lhs)
            && cast_is_safe(&right, &rhs)
            && integer_literal_is_nonzero(divisor))
        .then_some(lhs);
    }
    if binary.op == Operator::Divide {
        return None;
    }
    // Limit coercion probes to the numeric types covered by this proof,
    // including Decimal128 operands with nonnegative scales.
    for operand in [&left, &right] {
        if decimal128_parts(operand).is_none()
            && integer_range(operand).is_none()
            && !matches!(operand, DataType::Null)
        {
            return None;
        }
    }
    if !matches!(left, DataType::Decimal128(..))
        && !matches!(right, DataType::Decimal128(..))
    {
        return None;
    }
    let (coerced_left, coerced_right) = coercer.get_input_types().ok()?;
    if !cast_is_safe(&left, &coerced_left) || !cast_is_safe(&right, &coerced_right) {
        return None;
    }
    let (lp, ls) = decimal128_parts(&coerced_left)?;
    let (rp, rs) = decimal128_parts(&coerced_right)?;

    // Arrow checks decimal coefficients even in wrapping mode. Addition and
    // subtraction align scales before operating and need one carry digit.
    // Multiplication uses the raw product: p_left + p_right digits suffice,
    // including a safe clamp from DataFusion's requested precision 39 to 38.
    let (required_precision, scale) = match binary.op {
        Operator::Plus | Operator::Minus => {
            let scale = ls.max(rs);
            let left_digits = lp + scale - ls;
            let right_digits = rp + scale - rs;
            (left_digits.max(right_digits) + 1, scale)
        }
        Operator::Multiply => (lp + rp, ls + rs),
        _ => return None,
    };
    // Parents rely on the declared result precision as their coefficient bound.
    // Merely fitting i128 is insufficient if a clamped result exceeds that bound.
    if required_precision > 38 {
        return None;
    }
    let result = coercer.get_result_type().ok()?;
    matches!(&result, DataType::Decimal128(precision, result_scale)
        if i16::from(*precision) >= required_precision
            && *precision <= 38 && i16::from(*result_scale) == scale)
    .then_some(result)
}

fn decimal128_parts(data_type: &DataType) -> Option<(i16, i16)> {
    match data_type {
        DataType::Decimal128(precision, scale)
            if (1..=38).contains(precision)
                && *scale >= 0
                && *scale as u8 <= *precision =>
        {
            Some((i16::from(*precision), i16::from(*scale)))
        }
        _ => None,
    }
}

fn is_ordering_operator(op: Operator) -> bool {
    matches!(
        op,
        Operator::Lt | Operator::LtEq | Operator::Gt | Operator::GtEq
    )
}

fn comparison_is_safe(
    left: &Expr,
    op: Operator,
    right: &Expr,
    schema: &DFSchema,
    proven_types: &ProvenTypes,
) -> bool {
    let ordering = is_ordering_operator(op);
    let (Ok(left_type), Ok(right_type)) = (
        scalar_type(left, schema, proven_types),
        scalar_type(right, schema, proven_types),
    ) else {
        return false;
    };
    if !comparison_type_is_safe(&left_type, ordering)
        || !comparison_type_is_safe(&right_type, ordering)
    {
        return false;
    }
    BinaryTypeCoercer::new(&left_type, &op, &right_type)
        .get_input_types()
        .is_ok_and(|(coerced_left, coerced_right)| {
            comparison_type_is_safe(&coerced_left, ordering)
                && comparison_type_is_safe(&coerced_right, ordering)
                && input_cast_is_safe(left, &left_type, &coerced_left)
                && input_cast_is_safe(right, &right_type, &coerced_right)
        })
}

fn between_is_safe(
    between: &Between,
    schema: &DFSchema,
    proven_types: &ProvenTypes,
) -> bool {
    let types = [&between.expr, &between.low, &between.high]
        .map(|value| scalar_type(value, schema, proven_types));
    let [Ok(value), Ok(low), Ok(high)] = types else {
        return false;
    };
    // DataFusion coerces `(expr, low)` then `(low_coerced, high)` to one
    // common target type and casts all three operands to it.
    let Ok((low_coerced, _)) =
        BinaryTypeCoercer::new(&value, &Operator::GtEq, &low).get_input_types()
    else {
        return false;
    };
    let Ok((target, _)) =
        BinaryTypeCoercer::new(&low_coerced, &Operator::LtEq, &high).get_input_types()
    else {
        return false;
    };
    comparison_type_is_safe(&target, true)
        && [&value, &low, &high].into_iter().all(|source| {
            comparison_type_is_safe(source, true) && cast_is_safe(source, &target)
        })
}

// Top-level Arrow comparison unwraps at most one run-end encoding and one
// dictionary over a plain scalar leaf. Nested comparisons recurse into
// container children and reject unsupported containers (`ListView`,
// `LargeListView`, `Union`, `Map` under ordering, and nested
// `Dictionary`/`RunEndEncoded` fields).
fn comparison_type_is_safe(data_type: &DataType, ordering: bool) -> bool {
    match data_type {
        DataType::Dictionary(key, value) => {
            key.is_integer() && scalar_ordering_type_is_safe(value)
        }
        DataType::RunEndEncoded(run_ends, field) => {
            matches!(
                run_ends.data_type(),
                DataType::Int16 | DataType::Int32 | DataType::Int64
            ) && match field.data_type() {
                DataType::Dictionary(key, value) => {
                    key.is_integer() && scalar_ordering_type_is_safe(value)
                }
                inner => scalar_ordering_type_is_safe(inner),
            }
        }
        _ => nested_comparison_type_is_safe(data_type, ordering),
    }
}

fn nested_comparison_type_is_safe(data_type: &DataType, ordering: bool) -> bool {
    match data_type {
        DataType::List(field) | DataType::LargeList(field) => {
            nested_comparison_type_is_safe(field.data_type(), ordering)
        }
        DataType::FixedSizeList(field, len) => {
            *len >= 0 && nested_comparison_type_is_safe(field.data_type(), ordering)
        }
        DataType::Struct(fields) => fields
            .iter()
            .all(|field| nested_comparison_type_is_safe(field.data_type(), ordering)),
        DataType::Map(field, _) => {
            !ordering
                && matches!(
                    field.data_type(),
                    DataType::Struct(fields) if fields.len() == 2
                )
                && nested_comparison_type_is_safe(field.data_type(), false)
        }
        DataType::ListView(_)
        | DataType::LargeListView(_)
        | DataType::Union(_, _)
        | DataType::Dictionary(_, _)
        | DataType::RunEndEncoded(_, _) => false,
        _ => scalar_ordering_type_is_safe(data_type),
    }
}

fn input_cast_is_safe(expr: &Expr, from: &DataType, to: &DataType) -> bool {
    if cast_is_safe(from, to) {
        return true;
    }
    // The type alone cannot prove a floating threshold fits a decimal, or
    // that a string parses as an integer. Check the actual SQL literal.
    matches!(expr, Expr::Literal(value, _)
        if to.is_numeric()
            && (from.is_numeric() || matches!(from, DataType::Utf8 | DataType::Utf8View | DataType::LargeUtf8))
            && value.cast_to(to).is_ok_and(|v| value.is_null() || !v.is_null()))
}

fn cast_is_safe(source: &DataType, target: &DataType) -> bool {
    if source == target {
        return true;
    }
    if matches!(source, DataType::Null) {
        return scalar_value_type_is_safe(target);
    }
    if let (Some((low, high)), Some((target_low, target_high))) =
        (integer_range(source), integer_range(target))
    {
        return target_low <= low && high <= target_high;
    }
    match (source, target) {
        (_, DataType::Float64) => {
            integer_range(source).is_some()
                || matches!(source, DataType::Float32)
                || decimal128_parts(source).is_some()
        }
        (_, DataType::Float32) => integer_range(source).is_some(),
        (DataType::Utf8, DataType::LargeUtf8 | DataType::Utf8View)
        | (DataType::Utf8View, DataType::LargeUtf8) => true,
        (DataType::Decimal128(..), DataType::Decimal128(..)) => {
            let (Some((precision, scale)), Some((target_precision, target_scale))) =
                (decimal128_parts(source), decimal128_parts(target))
            else {
                return false;
            };
            // Raising the scale appends zeros to the coefficient. Every input
            // fits exactly when target precision covers those extra digits.
            let extra = target_scale - scale;
            extra >= 0 && precision + extra <= target_precision
        }
        (_, DataType::Decimal128(..)) => {
            let Some((precision, scale)) = decimal128_parts(target) else {
                return false;
            };
            integer_range(source).is_some_and(|(low, high)| {
                let digits = low.unsigned_abs().max(high.unsigned_abs()).ilog10() + 1;
                i32::from(precision) - i32::from(scale) >= digits as i32
            })
        }
        _ => false,
    }
}

fn integer_range(data_type: &DataType) -> Option<(i128, i128)> {
    match data_type {
        DataType::Int8 => Some((i8::MIN.into(), i8::MAX.into())),
        DataType::Int16 => Some((i16::MIN.into(), i16::MAX.into())),
        DataType::Int32 => Some((i32::MIN.into(), i32::MAX.into())),
        DataType::Int64 => Some((i64::MIN.into(), i64::MAX.into())),
        DataType::UInt8 => Some((0, u8::MAX.into())),
        DataType::UInt16 => Some((0, u16::MAX.into())),
        DataType::UInt32 => Some((0, u32::MAX.into())),
        DataType::UInt64 => Some((0, u64::MAX.into())),
        _ => None,
    }
}

#[cfg(test)]
mod tests;

fn integer_literal_is_nonzero(value: &ScalarValue) -> bool {
    match value {
        ScalarValue::Int8(Some(value)) => *value != 0,
        ScalarValue::Int16(Some(value)) => *value != 0,
        ScalarValue::Int32(Some(value)) => *value != 0,
        ScalarValue::Int64(Some(value)) => *value != 0,
        ScalarValue::UInt8(Some(value)) => *value != 0,
        ScalarValue::UInt16(Some(value)) => *value != 0,
        ScalarValue::UInt32(Some(value)) => *value != 0,
        ScalarValue::UInt64(Some(value)) => *value != 0,
        _ => false,
    }
}