icydb-core 0.120.2

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
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
use crate::{
    db::{
        numeric::{NumericArithmeticOp, apply_numeric_arithmetic},
        predicate::CompareOp,
        query::plan::{
            expr::{
                BinaryOp, CaseWhenArm, Expr, Function, UnaryOp,
                function_is_compare_operand_coarse_family,
            },
            render_scalar_filter_expr_sql_label,
        },
    },
    value::Value,
};

const MAX_BOOL_CASE_CANONICALIZATION_ARMS: usize = 8;

///
/// TruthWrapperScope
///
/// Bounded truth-wrapper collapse scope for planner-owned boolean
/// canonicalization.
///
/// Scalar `WHERE` and grouped `HAVING` share the same admitted `= TRUE` /
/// `= FALSE` wrapper family, but grouped `HAVING` still needs a slightly wider
/// candidate set because aggregate and `COALESCE(...)` shapes can already act
/// as grouped truth conditions there.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum TruthWrapperScope {
    ScalarWhere,
    GroupedHaving,
}

/// Resolve one planner truth-condition compare operator onto the binary
/// expression family used by normalized expression trees.
#[must_use]
pub(in crate::db) const fn truth_condition_compare_binary_op(op: CompareOp) -> Option<BinaryOp> {
    match op {
        CompareOp::Eq => Some(BinaryOp::Eq),
        CompareOp::Ne => Some(BinaryOp::Ne),
        CompareOp::Lt => Some(BinaryOp::Lt),
        CompareOp::Lte => Some(BinaryOp::Lte),
        CompareOp::Gt => Some(BinaryOp::Gt),
        CompareOp::Gte => Some(BinaryOp::Gte),
        CompareOp::In
        | CompareOp::NotIn
        | CompareOp::Contains
        | CompareOp::StartsWith
        | CompareOp::EndsWith => None,
    }
}

/// Resolve one planner binary compare operator back onto the admitted
/// truth-condition compare family.
#[must_use]
pub(in crate::db) const fn truth_condition_binary_compare_op(op: BinaryOp) -> Option<CompareOp> {
    match op {
        BinaryOp::Eq => Some(CompareOp::Eq),
        BinaryOp::Ne => Some(CompareOp::Ne),
        BinaryOp::Lt => Some(CompareOp::Lt),
        BinaryOp::Lte => Some(CompareOp::Lte),
        BinaryOp::Gt => Some(CompareOp::Gt),
        BinaryOp::Gte => Some(CompareOp::Gte),
        BinaryOp::And
        | BinaryOp::Or
        | BinaryOp::Add
        | BinaryOp::Sub
        | BinaryOp::Mul
        | BinaryOp::Div => None,
    }
}

/// Normalize one planner-owned boolean expression without changing
/// three-valued semantics inside subexpressions.
#[must_use]
pub(in crate::db) fn normalize_bool_expr(expr: Expr) -> Expr {
    match expr {
        Expr::Unary {
            op: UnaryOp::Not,
            expr,
        } => match normalize_bool_expr(*expr) {
            Expr::Unary {
                op: UnaryOp::Not,
                expr,
            } => *expr,
            Expr::Literal(Value::Bool(value)) => Expr::Literal(Value::Bool(!value)),
            Expr::Literal(Value::Null) => Expr::Literal(Value::Null),
            expr => Expr::Unary {
                op: UnaryOp::Not,
                expr: Box::new(expr),
            },
        },
        Expr::Binary {
            op: BinaryOp::And,
            left,
            right,
        } => normalize_bool_associative_expr(BinaryOp::And, *left, *right),
        Expr::Binary {
            op: BinaryOp::Or,
            left,
            right,
        } => normalize_bool_associative_expr(BinaryOp::Or, *left, *right),
        Expr::Binary { op, left, right } => normalize_bool_compare_expr(
            op,
            normalize_bool_compare_operand(*left),
            normalize_bool_compare_operand(*right),
        ),
        Expr::FunctionCall { function, args } => normalize_bool_function_call(function, args),
        other => other,
    }
}

/// Canonicalize one scalar-WHERE boolean expression onto the shipped `0.107`
/// searched-`CASE` boolean seam after the shared structural normalization pass
/// has already settled the planner-owned tree shape.
#[must_use]
pub(in crate::db) fn canonicalize_scalar_where_bool_expr(expr: Expr) -> Expr {
    let expr = normalize_bool_expr(expr);
    let expr = canonicalize_normalized_bool_case_in_bool_context(
        expr,
        true,
        Some(TruthWrapperScope::ScalarWhere),
    );
    let expr = normalize_bool_expr(expr);

    debug_assert!(is_normalized_bool_expr(&expr));

    expr
}

/// Canonicalize one grouped-HAVING boolean expression onto the bounded
/// searched-`CASE` boolean seam after the shared structural normalization pass
/// has already settled the planner-owned grouped tree shape.
///
/// Unlike scalar `WHERE`, grouped `HAVING` does not collapse a final
/// `ELSE NULL` arm to `FALSE`. Grouped canonicalization therefore preserves
/// the explicit grouped boolean result tree unless the shipped searched-`CASE`
/// expansion is already semantically identical without null-arm collapse.
#[must_use]
pub(in crate::db) fn canonicalize_grouped_having_bool_expr(expr: Expr) -> Expr {
    let expr = normalize_bool_expr(expr);
    let expr = canonicalize_normalized_bool_case_in_bool_context(
        expr,
        false,
        Some(TruthWrapperScope::GroupedHaving),
    );

    normalize_bool_expr(expr)
}

/// Report whether one boolean expression is already in the canonical
/// normalized shape required by predicate compilation.
#[must_use]
pub(in crate::db) fn is_normalized_bool_expr(expr: &Expr) -> bool {
    match expr {
        Expr::Field(_) => true,
        Expr::Literal(Value::Bool(_) | Value::Null) => true,
        Expr::Unary {
            op: UnaryOp::Not,
            expr,
        } => {
            !matches!(
                expr.as_ref(),
                Expr::Unary {
                    op: UnaryOp::Not,
                    ..
                }
            ) && is_normalized_bool_expr(expr.as_ref())
        }
        Expr::Binary {
            op: BinaryOp::And | BinaryOp::Or,
            ..
        } => is_normalized_bool_associative_expr(expr),
        Expr::Binary { op, left, right } => is_normalized_bool_compare_expr(*op, left, right),
        Expr::FunctionCall { function, args } => {
            is_normalized_bool_function_call(*function, args.as_slice())
        }
        Expr::Case {
            when_then_arms,
            else_expr,
        } => {
            when_then_arms.iter().all(|arm| {
                is_normalized_bool_expr(arm.condition()) && is_normalized_bool_expr(arm.result())
            }) && is_normalized_bool_expr(else_expr.as_ref())
        }
        Expr::Aggregate(_) | Expr::Literal(_) => false,
        #[cfg(test)]
        Expr::Alias { .. } => false,
    }
}

/// Collapse one evaluated boolean-context value through the shared TRUE-only
/// admission boundary used by WHERE-style row filtering, grouped HAVING, and
/// aggregate FILTER semantics.
pub(in crate::db) fn collapse_true_only_boolean_admission<E>(
    value: Value,
    invalid: impl FnOnce(Box<Value>) -> E,
) -> Result<bool, E> {
    match value {
        Value::Bool(true) => Ok(true),
        Value::Bool(false) | Value::Null => Ok(false),
        other => Err(invalid(Box::new(other))),
    }
}

/// Rewrite the planner-owned affine numeric compare family that can already
/// reduce onto the existing field-vs-literal predicate lane.
#[must_use]
pub(in crate::db) fn rewrite_affine_numeric_compare_expr(expr: Expr) -> Expr {
    match expr {
        Expr::Unary { op, expr } => Expr::Unary {
            op,
            expr: Box::new(rewrite_affine_numeric_compare_expr(*expr)),
        },
        Expr::Binary {
            op: logical @ (BinaryOp::And | BinaryOp::Or),
            left,
            right,
        } => Expr::Binary {
            op: logical,
            left: Box::new(rewrite_affine_numeric_compare_expr(*left)),
            right: Box::new(rewrite_affine_numeric_compare_expr(*right)),
        },
        Expr::Binary { op, left, right } => {
            let left = rewrite_affine_numeric_compare_expr(*left);
            let right = rewrite_affine_numeric_compare_expr(*right);

            rewrite_affine_compare_binary(op, left, right)
        }
        Expr::FunctionCall { function, args } => Expr::FunctionCall {
            function,
            args: args
                .into_iter()
                .map(rewrite_affine_numeric_compare_expr)
                .collect(),
        },
        Expr::Case {
            when_then_arms,
            else_expr,
        } => Expr::Case {
            when_then_arms: when_then_arms
                .into_iter()
                .map(|arm| {
                    CaseWhenArm::new(
                        rewrite_affine_numeric_compare_expr(arm.condition().clone()),
                        rewrite_affine_numeric_compare_expr(arm.result().clone()),
                    )
                })
                .collect(),
            else_expr: Box::new(rewrite_affine_numeric_compare_expr(*else_expr)),
        },
        other => other,
    }
}

/// Simplify mixed boolean trees after constant folding so downstream predicate
/// extraction can keep reusing one derived lane when one side has collapsed.
#[must_use]
pub(in crate::db) fn simplify_bool_expr_constants(expr: Expr) -> Expr {
    match expr {
        Expr::Binary {
            op: BinaryOp::And,
            left,
            right,
        } => simplify_boolean_and(
            simplify_bool_expr_constants(*left),
            simplify_bool_expr_constants(*right),
        ),
        Expr::Binary {
            op: BinaryOp::Or,
            left,
            right,
        } => simplify_boolean_or(
            simplify_bool_expr_constants(*left),
            simplify_bool_expr_constants(*right),
        ),
        Expr::Unary { op, expr } => Expr::Unary {
            op,
            expr: Box::new(simplify_bool_expr_constants(*expr)),
        },
        Expr::FunctionCall { function, args } => Expr::FunctionCall {
            function,
            args: args.into_iter().map(simplify_bool_expr_constants).collect(),
        },
        Expr::Case {
            when_then_arms,
            else_expr,
        } => Expr::Case {
            when_then_arms: when_then_arms
                .into_iter()
                .map(|arm| {
                    CaseWhenArm::new(
                        simplify_bool_expr_constants(arm.condition().clone()),
                        simplify_bool_expr_constants(arm.result().clone()),
                    )
                })
                .collect(),
            else_expr: Box::new(simplify_bool_expr_constants(*else_expr)),
        },
        Expr::Binary { op, left, right } => Expr::Binary {
            op,
            left: Box::new(simplify_bool_expr_constants(*left)),
            right: Box::new(simplify_bool_expr_constants(*right)),
        },
        #[cfg(test)]
        Expr::Alias { expr, name } => Expr::Alias {
            expr: Box::new(simplify_bool_expr_constants(*expr)),
            name,
        },
        other => other,
    }
}

// Normalize one associative boolean chain onto one flattened, deterministically
// ordered left-associated shape so equivalent `AND` / `OR` spellings feed the
// same extracted predicate and residual contracts downstream.
fn normalize_bool_associative_expr(op: BinaryOp, left: Expr, right: Expr) -> Expr {
    let mut children = Vec::new();
    collect_normalized_bool_associative_children(op, normalize_bool_expr(left), &mut children);
    collect_normalized_bool_associative_children(op, normalize_bool_expr(right), &mut children);
    children.sort_by(bool_expr_normalized_order);
    children.dedup();

    rebuild_normalized_bool_associative_chain(op, children)
}

// Canonicalize one planner-owned boolean searched `CASE` onto the bounded
// first-match boolean expansion when the resulting expression size stays within
// the shipped `0.107` threshold. Otherwise preserve the normalized `CASE`
// shape so canonicalization remains explicit and fail-closed.
fn normalize_bool_case_expr(
    when_then_arms: Vec<CaseWhenArm>,
    else_expr: Expr,
    top_level_where_null_collapse: bool,
) -> Expr {
    canonicalize_normalized_bool_case_expr(
        when_then_arms.as_slice(),
        &else_expr,
        top_level_where_null_collapse,
    )
    .unwrap_or_else(|| Expr::Case {
        when_then_arms,
        else_expr: Box::new(else_expr),
    })
}

// Recurse across boolean-context planner nodes only so searched `CASE`
// canonicalization stays scoped to scalar filter semantics instead of
// rewriting generic value-expression surfaces like grouped WHERE, HAVING, or
// arbitrary compare operands.
fn canonicalize_normalized_bool_case_in_bool_context(
    expr: Expr,
    top_level_where_null_collapse: bool,
    truth_wrapper_scope: Option<TruthWrapperScope>,
) -> Expr {
    match expr {
        Expr::Unary {
            op: UnaryOp::Not,
            expr,
        } => Expr::Unary {
            op: UnaryOp::Not,
            expr: Box::new(canonicalize_normalized_bool_case_in_bool_context(
                *expr,
                false,
                truth_wrapper_scope,
            )),
        },
        Expr::Binary {
            op: logical @ (BinaryOp::And | BinaryOp::Or),
            left,
            right,
        } => Expr::Binary {
            op: logical,
            left: Box::new(canonicalize_normalized_bool_case_in_bool_context(
                *left,
                top_level_where_null_collapse,
                truth_wrapper_scope,
            )),
            right: Box::new(canonicalize_normalized_bool_case_in_bool_context(
                *right,
                top_level_where_null_collapse,
                truth_wrapper_scope,
            )),
        },
        Expr::Case {
            when_then_arms,
            else_expr,
        } => {
            let when_then_arms = when_then_arms
                .into_iter()
                .map(|arm| {
                    CaseWhenArm::new(
                        canonicalize_normalized_bool_case_in_bool_context(
                            arm.condition().clone(),
                            true,
                            truth_wrapper_scope,
                        ),
                        canonicalize_normalized_bool_case_in_bool_context(
                            arm.result().clone(),
                            top_level_where_null_collapse,
                            truth_wrapper_scope,
                        ),
                    )
                })
                .collect::<Vec<_>>();
            let else_expr = canonicalize_normalized_bool_case_in_bool_context(
                *else_expr,
                top_level_where_null_collapse,
                truth_wrapper_scope,
            );

            normalize_bool_case_expr(when_then_arms, else_expr, top_level_where_null_collapse)
        }
        other => maybe_collapse_truth_wrapper_in_bool_context(other, truth_wrapper_scope),
    }
}

// Collapse the admitted `= TRUE` / `= FALSE` wrapper family through one
// planner-owned truth-condition authority instead of keeping separate local
// wrapper semantics in grouped-only or predicate-adjacent paths.
fn maybe_collapse_truth_wrapper_in_bool_context(
    expr: Expr,
    scope: Option<TruthWrapperScope>,
) -> Expr {
    let Some(scope) = scope else {
        return expr;
    };

    match expr {
        Expr::Binary {
            op: BinaryOp::Eq,
            left,
            right,
        } if matches!(right.as_ref(), Expr::Literal(Value::Bool(true)))
            && truth_wrapper_candidate(left.as_ref(), scope) =>
        {
            *left
        }
        Expr::Binary {
            op: BinaryOp::Eq,
            left,
            right,
        } if matches!(left.as_ref(), Expr::Literal(Value::Bool(true)))
            && truth_wrapper_candidate(right.as_ref(), scope) =>
        {
            *right
        }
        Expr::Binary {
            op: BinaryOp::Eq,
            left,
            right,
        } if matches!(right.as_ref(), Expr::Literal(Value::Bool(false)))
            && truth_wrapper_candidate(left.as_ref(), scope) =>
        {
            Expr::Unary {
                op: UnaryOp::Not,
                expr: left,
            }
        }
        Expr::Binary {
            op: BinaryOp::Eq,
            left,
            right,
        } if matches!(left.as_ref(), Expr::Literal(Value::Bool(false)))
            && truth_wrapper_candidate(right.as_ref(), scope) =>
        {
            Expr::Unary {
                op: UnaryOp::Not,
                expr: right,
            }
        }
        other => other,
    }
}

// Recognize the admitted truth-condition family where outer bool equality
// wrappers are semantically redundant in boolean filter contexts.
fn truth_wrapper_candidate(expr: &Expr, scope: TruthWrapperScope) -> bool {
    match scope {
        TruthWrapperScope::ScalarWhere => scalar_where_truth_condition_is_admitted(expr),
        TruthWrapperScope::GroupedHaving => grouped_truth_wrapper_candidate(expr),
    }
}

/// Report whether one planner expression belongs to the admitted scalar-WHERE
/// truth-condition family.
///
/// This is the single planner-owned admission rule for scalar filter truth
/// meaning. Lowering may still decide clause ownership, but it should not keep
/// a parallel compare/null-test truth-family ladder.
pub(in crate::db) fn scalar_where_truth_condition_is_admitted(expr: &Expr) -> bool {
    match expr {
        Expr::Field(_) | Expr::Literal(Value::Bool(_) | Value::Null) => true,
        Expr::Unary {
            op: UnaryOp::Not,
            expr,
        } => scalar_where_truth_condition_is_admitted(expr.as_ref()),
        Expr::Binary {
            op: BinaryOp::Eq,
            left,
            right,
        } if matches!(right.as_ref(), Expr::Literal(Value::Bool(true | false))) => {
            scalar_where_truth_condition_is_admitted(left.as_ref())
        }
        Expr::Binary {
            op: BinaryOp::Eq,
            left,
            right,
        } if matches!(left.as_ref(), Expr::Literal(Value::Bool(true | false))) => {
            scalar_where_truth_condition_is_admitted(right.as_ref())
        }
        Expr::Binary {
            op: BinaryOp::And | BinaryOp::Or,
            left,
            right,
        } => {
            scalar_where_truth_condition_is_admitted(left.as_ref())
                && scalar_where_truth_condition_is_admitted(right.as_ref())
        }
        Expr::Binary { op, left, right } if truth_condition_binary_compare_op(*op).is_some() => {
            scalar_where_truth_compare_operand_is_admitted(left.as_ref())
                && scalar_where_truth_compare_operand_is_admitted(right.as_ref())
        }
        Expr::Binary { .. } => false,
        Expr::FunctionCall { function, args } => {
            scalar_where_truth_function_call_is_admitted(*function, args.as_slice())
        }
        Expr::Case {
            when_then_arms,
            else_expr,
        } => {
            when_then_arms.iter().all(|arm| {
                scalar_where_truth_condition_is_admitted(arm.condition())
                    && scalar_where_truth_condition_is_admitted(arm.result())
            }) && scalar_where_truth_condition_is_admitted(else_expr.as_ref())
        }
        Expr::Aggregate(_) | Expr::Literal(_) => false,
        #[cfg(test)]
        Expr::Alias { expr, .. } => scalar_where_truth_condition_is_admitted(expr.as_ref()),
    }
}

// Keep scalar compare admission aligned with the shipped scalar residual family
// so compare/null-test truth shaping and wrapper collapse read from one owner.
fn scalar_where_truth_compare_operand_is_admitted(expr: &Expr) -> bool {
    match expr {
        Expr::Field(_) | Expr::Literal(_) => true,
        Expr::FunctionCall { function, args }
            if function_is_compare_operand_coarse_family(*function) =>
        {
            args.iter()
                .all(scalar_where_truth_compare_operand_is_admitted)
        }
        Expr::Binary { op, left, right }
            if matches!(
                op,
                BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div
            ) =>
        {
            scalar_where_truth_compare_operand_is_admitted(left.as_ref())
                && scalar_where_truth_compare_operand_is_admitted(right.as_ref())
        }
        Expr::Case {
            when_then_arms,
            else_expr,
        } => {
            when_then_arms.iter().all(|arm| {
                scalar_where_truth_condition_is_admitted(arm.condition())
                    && scalar_where_truth_compare_operand_is_admitted(arm.result())
            }) && scalar_where_truth_compare_operand_is_admitted(else_expr.as_ref())
        }
        Expr::Aggregate(_)
        | Expr::Unary { .. }
        | Expr::FunctionCall { .. }
        | Expr::Binary { .. } => false,
        #[cfg(test)]
        Expr::Alias { expr, .. } => scalar_where_truth_compare_operand_is_admitted(expr.as_ref()),
    }
}

// Keep scalar truth-condition admission aligned with the bounded boolean
// function family already consumed by scalar WHERE lowering and predicate
// compilation.
fn scalar_where_truth_function_call_is_admitted(function: Function, args: &[Expr]) -> bool {
    match function {
        Function::Coalesce => args.iter().all(scalar_where_truth_condition_is_admitted),
        Function::IsNull | Function::IsNotNull => {
            matches!(args, [arg] if scalar_where_truth_compare_operand_is_admitted(arg))
        }
        Function::StartsWith | Function::EndsWith | Function::Contains => {
            matches!(
                args,
                [left, right]
                    if scalar_where_truth_compare_operand_is_admitted(left)
                        && scalar_where_truth_compare_operand_is_admitted(right)
            )
        }
        Function::IsMissing | Function::IsEmpty | Function::IsNotEmpty => {
            matches!(args, [Expr::Field(_)])
        }
        Function::CollectionContains => matches!(args, [Expr::Field(_), Expr::Literal(_)]),
        _ => false,
    }
}

// Recognize the bounded grouped boolean-expression family where an outer bool
// equality wrapper is already redundant in grouped truth semantics.
fn grouped_truth_wrapper_candidate(expr: &Expr) -> bool {
    match expr {
        Expr::Field(_) | Expr::Literal(Value::Bool(_) | Value::Null) => true,
        Expr::Unary {
            op: UnaryOp::Not,
            expr,
        } => grouped_truth_wrapper_candidate(expr.as_ref()),
        Expr::Binary {
            op: BinaryOp::And | BinaryOp::Or,
            left,
            right,
        } => {
            grouped_truth_wrapper_candidate(left.as_ref())
                || grouped_truth_wrapper_candidate(right.as_ref())
        }
        Expr::Binary { op, .. } if truth_condition_binary_compare_op(*op).is_some() => true,
        Expr::Binary { .. } => false,
        Expr::Case {
            when_then_arms,
            else_expr,
        } => {
            when_then_arms.iter().all(|arm| {
                grouped_truth_wrapper_candidate(arm.condition())
                    && grouped_truth_wrapper_candidate(arm.result())
            }) && grouped_truth_wrapper_candidate(else_expr.as_ref())
        }
        Expr::FunctionCall {
            function: Function::Coalesce,
            args,
        } => args.iter().all(grouped_truth_wrapper_candidate),
        Expr::FunctionCall {
            function:
                Function::IsNull
                | Function::IsNotNull
                | Function::IsMissing
                | Function::IsEmpty
                | Function::IsNotEmpty
                | Function::StartsWith
                | Function::EndsWith
                | Function::Contains,
            ..
        } => true,
        Expr::Aggregate(_) | Expr::Literal(_) => false,
        #[cfg(test)]
        Expr::Alias { expr, .. } => grouped_truth_wrapper_candidate(expr.as_ref()),
        Expr::FunctionCall { .. } => false,
    }
}

// Expand one already-normalized scalar-WHERE searched `CASE` onto the shipped
// first-match boolean form. In scalar filter semantics, a final `ELSE NULL`
// arm is equivalent to `ELSE FALSE` because both outcomes reject the row.
fn canonicalize_normalized_bool_case_expr(
    arms: &[CaseWhenArm],
    else_expr: &Expr,
    top_level_where_null_collapse: bool,
) -> Option<Expr> {
    if arms.is_empty() || arms.len() > MAX_BOOL_CASE_CANONICALIZATION_ARMS {
        return None;
    }

    let mut canonical = match (top_level_where_null_collapse, else_expr) {
        (true, Expr::Literal(Value::Null)) => Expr::Literal(Value::Bool(false)),
        (_, other) => other.clone(),
    };
    for arm in arms.iter().rev() {
        canonical = normalize_bool_expr(Expr::Binary {
            op: BinaryOp::Or,
            left: Box::new(guarded_bool_case_branch(
                searched_case_match_guard(arm.condition().clone()),
                arm.result().clone(),
            )),
            right: Box::new(guarded_bool_case_branch(
                Expr::Unary {
                    op: UnaryOp::Not,
                    expr: Box::new(searched_case_match_guard(arm.condition().clone())),
                },
                canonical,
            )),
        });
    }

    Some(canonical)
}

// Build one guarded boolean branch while preserving the small three-valued
// identities that keep searched `CASE` canonicalization from emitting obvious
// `guard AND TRUE` / `guard AND FALSE` shells.
fn guarded_bool_case_branch(guard: Expr, result: Expr) -> Expr {
    match result {
        Expr::Literal(Value::Bool(true)) => guard,
        Expr::Literal(Value::Bool(false)) => Expr::Literal(Value::Bool(false)),
        other => Expr::Binary {
            op: BinaryOp::And,
            left: Box::new(guard),
            right: Box::new(other),
        },
    }
}

// Lower one searched-`CASE` branch condition onto the planner-owned boolean
// match contract where only `TRUE` selects the branch and both `FALSE` and
// `NULL` fall through to the next arm.
fn searched_case_match_guard(condition: Expr) -> Expr {
    Expr::FunctionCall {
        function: Function::Coalesce,
        args: vec![condition, Expr::Literal(Value::Bool(false))],
    }
}

// Collect one associative boolean subtree onto one flat child list after each
// child has already been normalized independently.
fn collect_normalized_bool_associative_children(op: BinaryOp, expr: Expr, out: &mut Vec<Expr>) {
    match expr {
        Expr::Binary {
            op: child_op,
            left,
            right,
        } if child_op == op => {
            collect_normalized_bool_associative_children(op, *left, out);
            collect_normalized_bool_associative_children(op, *right, out);
        }
        other => out.push(other),
    }
}

// Rebuild one normalized associative child list onto one stable left-associated
// binary tree because the current planner and predicate compiler still operate
// on binary boolean expression nodes.
fn rebuild_normalized_bool_associative_chain(op: BinaryOp, children: Vec<Expr>) -> Expr {
    let mut children = children.into_iter();
    let Some(first) = children.next() else {
        return Expr::Literal(Value::Bool(matches!(op, BinaryOp::And)));
    };

    children.fold(first, |left, right| Expr::Binary {
        op,
        left: Box::new(left),
        right: Box::new(right),
    })
}

// Order one normalized boolean child by its rendered planner-owned label first
// and its debug shape second so equivalent associative trees settle onto one
// deterministic extraction order without inventing a new expression hash.
fn bool_expr_normalized_order(left: &Expr, right: &Expr) -> std::cmp::Ordering {
    let left_rendered = render_scalar_filter_expr_sql_label(left);
    let right_rendered = render_scalar_filter_expr_sql_label(right);

    left_rendered
        .cmp(&right_rendered)
        .then_with(|| format!("{left:?}").cmp(&format!("{right:?}")))
}

// Report whether one associative boolean chain is already flattened onto one
// deterministically ordered child sequence.
fn is_normalized_bool_associative_expr(expr: &Expr) -> bool {
    let Expr::Binary { op, .. } = expr else {
        return false;
    };
    if !matches!(op, BinaryOp::And | BinaryOp::Or) {
        return false;
    }

    let mut children = Vec::new();
    collect_bool_associative_chain_refs(expr, *op, &mut children);

    children.iter().all(|child| is_normalized_bool_expr(child))
        && children
            .windows(2)
            .all(|window| bool_expr_normalized_order(window[0], window[1]).is_le())
}

// Traverse one associative boolean chain as shared references so the
// normalized-shape checker can validate ordering without rebuilding the tree.
fn collect_bool_associative_chain_refs<'a>(expr: &'a Expr, op: BinaryOp, out: &mut Vec<&'a Expr>) {
    match expr {
        Expr::Binary {
            op: child_op,
            left,
            right,
        } if *child_op == op => {
            collect_bool_associative_chain_refs(left.as_ref(), op, out);
            collect_bool_associative_chain_refs(right.as_ref(), op, out);
        }
        other => out.push(other),
    }
}

fn normalize_bool_compare_expr(op: BinaryOp, left: Expr, right: Expr) -> Expr {
    match (&left, &right) {
        (Expr::Literal(_), right_expr)
            if !matches!(right_expr, Expr::Literal(_))
                && is_normalized_bool_compare_operand(right_expr) =>
        {
            Expr::Binary {
                op: flip_bool_compare_op(op),
                left: Box::new(right),
                right: Box::new(left),
            }
        }
        (Expr::Field(left_field), Expr::Field(right_field))
            if matches!(op, BinaryOp::Eq | BinaryOp::Ne) && left_field < right_field =>
        {
            Expr::Binary {
                op,
                left: Box::new(right),
                right: Box::new(left),
            }
        }
        _ => Expr::Binary {
            op,
            left: Box::new(left),
            right: Box::new(right),
        },
    }
}

fn normalize_bool_compare_operand(expr: Expr) -> Expr {
    match expr {
        Expr::FunctionCall {
            function: Function::Upper | Function::Lower,
            args,
        } => match args.as_slice() {
            [Expr::Field(field)] => Expr::FunctionCall {
                function: Function::Lower,
                args: vec![Expr::Field(field.clone())],
            },
            _ => Expr::FunctionCall {
                function: Function::Lower,
                args: args
                    .into_iter()
                    .map(normalize_bool_compare_operand)
                    .collect(),
            },
        },
        Expr::FunctionCall { function, args } => Expr::FunctionCall {
            function,
            args: args
                .into_iter()
                .map(normalize_bool_compare_operand)
                .collect(),
        },
        Expr::Binary { op, left, right }
            if matches!(
                op,
                BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div
            ) =>
        {
            Expr::Binary {
                op,
                left: Box::new(normalize_bool_compare_operand(*left)),
                right: Box::new(normalize_bool_compare_operand(*right)),
            }
        }
        Expr::Case {
            when_then_arms,
            else_expr,
        } => Expr::Case {
            when_then_arms: when_then_arms
                .into_iter()
                .map(|arm| {
                    CaseWhenArm::new(
                        normalize_bool_expr(arm.condition().clone()),
                        normalize_bool_compare_operand(arm.result().clone()),
                    )
                })
                .collect(),
            else_expr: Box::new(normalize_bool_compare_operand(*else_expr)),
        },
        expr => expr,
    }
}

fn normalize_bool_function_call(function: Function, args: Vec<Expr>) -> Expr {
    match function {
        Function::Coalesce => Expr::FunctionCall {
            function,
            args: args.into_iter().map(normalize_bool_expr).collect(),
        },
        Function::StartsWith | Function::EndsWith | Function::Contains => {
            let [left, right] = <[Expr; 2]>::try_from(args)
                .expect("validated boolean text predicate should keep two arguments");

            Expr::FunctionCall {
                function,
                args: vec![
                    normalize_bool_compare_operand(left),
                    normalize_bool_compare_operand(right),
                ],
            }
        }
        _ => Expr::FunctionCall { function, args },
    }
}

fn is_normalized_bool_compare_expr(op: BinaryOp, left: &Expr, right: &Expr) -> bool {
    match (left, right) {
        (Expr::Literal(_), right_expr)
            if !matches!(right_expr, Expr::Literal(_))
                && is_normalized_bool_compare_operand(right_expr) =>
        {
            false
        }
        (Expr::Field(left_field), Expr::Field(right_field))
            if matches!(op, BinaryOp::Eq | BinaryOp::Ne) && left_field < right_field =>
        {
            false
        }
        _ => is_normalized_bool_compare_operand(left) && is_normalized_bool_compare_operand(right),
    }
}

fn is_normalized_bool_compare_operand(expr: &Expr) -> bool {
    match expr {
        Expr::Field(_) | Expr::Literal(_) => true,
        Expr::FunctionCall { function, args }
            if function_is_compare_operand_coarse_family(*function) =>
        {
            args.iter().all(is_normalized_bool_compare_operand)
        }
        Expr::Binary { op, left, right }
            if matches!(
                op,
                BinaryOp::Add | BinaryOp::Sub | BinaryOp::Mul | BinaryOp::Div
            ) =>
        {
            is_normalized_bool_compare_operand(left.as_ref())
                && is_normalized_bool_compare_operand(right.as_ref())
        }
        Expr::Case {
            when_then_arms,
            else_expr,
        } => {
            when_then_arms.iter().all(|arm| {
                is_normalized_bool_expr(arm.condition())
                    && is_normalized_bool_compare_operand(arm.result())
            }) && is_normalized_bool_compare_operand(else_expr.as_ref())
        }
        Expr::Aggregate(_)
        | Expr::Unary { .. }
        | Expr::Binary { .. }
        | Expr::FunctionCall { .. } => false,
        #[cfg(test)]
        Expr::Alias { .. } => false,
    }
}

fn is_normalized_bool_function_call(function: Function, args: &[Expr]) -> bool {
    match function {
        Function::Coalesce => !args.is_empty() && args.iter().all(is_normalized_bool_expr),
        Function::IsNull | Function::IsNotNull => {
            matches!(args, [arg] if is_normalized_bool_compare_operand(arg))
        }
        Function::StartsWith | Function::EndsWith | Function::Contains => {
            matches!(
                args,
                [left, right]
                    if is_normalized_bool_compare_operand(left)
                        && is_normalized_bool_compare_operand(right)
            )
        }
        Function::IsMissing | Function::IsEmpty | Function::IsNotEmpty => {
            matches!(args, [Expr::Field(_)])
        }
        Function::CollectionContains => matches!(args, [Expr::Field(_), Expr::Literal(_)]),
        _ => false,
    }
}

// Keep the affine binary rewrite intentionally narrow:
// - only boolean compare operators participate
// - only one direct field plus/minus one numeric literal is rewritten
// - everything else stays fail-closed for the existing validator
fn rewrite_affine_compare_binary(op: BinaryOp, left: Expr, right: Expr) -> Expr {
    let Some(compare_op) = affine_compare_op(op) else {
        return Expr::Binary {
            op,
            left: Box::new(left),
            right: Box::new(right),
        };
    };

    if let Some((field, value)) = rewrite_affine_field_compare(&left, &right) {
        return Expr::Binary {
            op,
            left: Box::new(field),
            right: Box::new(Expr::Literal(value)),
        };
    }

    if let Some((field, value)) = rewrite_affine_field_compare(&right, &left) {
        return Expr::Binary {
            op: flip_compare_binary_op(compare_op),
            left: Box::new(field),
            right: Box::new(Expr::Literal(value)),
        };
    }

    Expr::Binary {
        op,
        left: Box::new(left),
        right: Box::new(right),
    }
}

// Recognize one affine compare side of the form:
// - field + literal
// - literal + field
// - field - literal
// and move the offset onto the literal side.
fn rewrite_affine_field_compare(affine_side: &Expr, literal_side: &Expr) -> Option<(Expr, Value)> {
    let Expr::Literal(target) = literal_side else {
        return None;
    };

    let (field, offset, arithmetic_op) = affine_field_offset(affine_side)?;
    let rewritten = match arithmetic_op {
        NumericArithmeticOp::Add => {
            apply_numeric_arithmetic(NumericArithmeticOp::Sub, target, offset)?
        }
        NumericArithmeticOp::Sub => {
            apply_numeric_arithmetic(NumericArithmeticOp::Add, target, offset)?
        }
        NumericArithmeticOp::Mul | NumericArithmeticOp::Div => return None,
    };

    Some((field.clone(), Value::Decimal(rewritten)))
}

// Extract the direct field plus/minus literal offset pattern admitted by this
// first affine boolean compare rewrite slice.
fn affine_field_offset(expr: &Expr) -> Option<(&Expr, &Value, NumericArithmeticOp)> {
    let Expr::Binary { op, left, right } = expr else {
        return None;
    };

    match (op, left.as_ref(), right.as_ref()) {
        (BinaryOp::Add, Expr::Field(_), Expr::Literal(offset))
            if offset.supports_numeric_coercion() =>
        {
            Some((left.as_ref(), offset, NumericArithmeticOp::Add))
        }
        (BinaryOp::Add, Expr::Literal(offset), Expr::Field(_))
            if offset.supports_numeric_coercion() =>
        {
            Some((right.as_ref(), offset, NumericArithmeticOp::Add))
        }
        (BinaryOp::Sub, Expr::Field(_), Expr::Literal(offset))
            if offset.supports_numeric_coercion() =>
        {
            Some((left.as_ref(), offset, NumericArithmeticOp::Sub))
        }
        _ => None,
    }
}

fn simplify_boolean_and(left: Expr, right: Expr) -> Expr {
    match (left, right) {
        (Expr::Literal(Value::Bool(false)), _) | (_, Expr::Literal(Value::Bool(false))) => {
            Expr::Literal(Value::Bool(false))
        }
        (Expr::Literal(Value::Bool(true)), expr) | (expr, Expr::Literal(Value::Bool(true))) => expr,
        (left, right) => Expr::Binary {
            op: BinaryOp::And,
            left: Box::new(left),
            right: Box::new(right),
        },
    }
}

fn simplify_boolean_or(left: Expr, right: Expr) -> Expr {
    match (left, right) {
        (Expr::Literal(Value::Bool(true)), _) | (_, Expr::Literal(Value::Bool(true))) => {
            Expr::Literal(Value::Bool(true))
        }
        (Expr::Literal(Value::Bool(false)), expr) | (expr, Expr::Literal(Value::Bool(false))) => {
            expr
        }
        (left, right) => Expr::Binary {
            op: BinaryOp::Or,
            left: Box::new(left),
            right: Box::new(right),
        },
    }
}

const fn affine_compare_op(op: BinaryOp) -> Option<BinaryOp> {
    match op {
        BinaryOp::Eq
        | BinaryOp::Ne
        | BinaryOp::Lt
        | BinaryOp::Lte
        | BinaryOp::Gt
        | BinaryOp::Gte => Some(op),
        BinaryOp::Or
        | BinaryOp::And
        | BinaryOp::Add
        | BinaryOp::Sub
        | BinaryOp::Mul
        | BinaryOp::Div => None,
    }
}

fn flip_compare_binary_op(op: BinaryOp) -> BinaryOp {
    match op {
        BinaryOp::Eq => BinaryOp::Eq,
        BinaryOp::Ne => BinaryOp::Ne,
        BinaryOp::Lt => BinaryOp::Gt,
        BinaryOp::Lte => BinaryOp::Gte,
        BinaryOp::Gt => BinaryOp::Lt,
        BinaryOp::Gte => BinaryOp::Lte,
        BinaryOp::Or
        | BinaryOp::And
        | BinaryOp::Add
        | BinaryOp::Sub
        | BinaryOp::Mul
        | BinaryOp::Div => {
            unreachable!("only compare operators can be flipped")
        }
    }
}

const fn flip_bool_compare_op(op: BinaryOp) -> BinaryOp {
    match op {
        BinaryOp::Eq => BinaryOp::Eq,
        BinaryOp::Ne => BinaryOp::Ne,
        BinaryOp::Lt => BinaryOp::Gt,
        BinaryOp::Lte => BinaryOp::Gte,
        BinaryOp::Gt => BinaryOp::Lt,
        BinaryOp::Gte => BinaryOp::Lte,
        BinaryOp::Or
        | BinaryOp::And
        | BinaryOp::Add
        | BinaryOp::Sub
        | BinaryOp::Mul
        | BinaryOp::Div => op,
    }
}