icydb-core 0.183.16

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
//! Module: db::index::predicate::tests
//! Covers index-predicate derivation and normalization behavior.
//! Does not own: cross-module orchestration outside this module.
//! Boundary: exposes this module API while keeping implementation details internal.

use crate::{
    db::{
        index::{
            IndexCompareOp, IndexId, IndexKey, IndexKeyKind, IndexLiteral, IndexPredicateProgram,
            predicate::literal_index_component_bytes,
        },
        predicate::{
            CoercionId, CoercionSpec, CompareOp, ExecutableComparePredicate, ExecutablePredicate,
            IndexCompileTarget, Predicate, compare_eq, compare_order,
        },
    },
    error::{ErrorClass, ErrorOrigin},
    model::index::{IndexExpression, IndexKeyItem, IndexModel, IndexPredicateMetadata},
    types::Decimal,
    types::EntityTag,
    value::Value,
};
use std::{cmp::Ordering, sync::LazyLock};

use super::{
    IndexCompilePolicy, canonical_index_predicate, compile_index_program,
    compile_index_program_for_targets, eval_index_compare, eval_index_program_on_decoded_key,
    eval_index_program_on_prefix_components,
};

static ACTIVE_TRUE_PREDICATE: LazyLock<Predicate> =
    LazyLock::new(|| Predicate::eq("active".to_string(), true.into()));

fn active_true_predicate() -> &'static Predicate {
    &ACTIVE_TRUE_PREDICATE
}

const fn active_true_predicate_metadata() -> IndexPredicateMetadata {
    IndexPredicateMetadata::generated("active = true", active_true_predicate)
}

// Match index compare operations to strict predicate semantics for expected results.
fn expected_strict_compare(
    op: IndexCompareOp,
    left: &Value,
    right: &Value,
    strict: &CoercionSpec,
) -> bool {
    match op {
        IndexCompareOp::Eq => compare_eq(left, right, strict).unwrap_or(false),
        IndexCompareOp::Ne => compare_eq(left, right, strict).is_some_and(|equal| !equal),
        IndexCompareOp::Lt => compare_order(left, right, strict).is_some_and(Ordering::is_lt),
        IndexCompareOp::Lte => compare_order(left, right, strict).is_some_and(Ordering::is_le),
        IndexCompareOp::Gt => compare_order(left, right, strict).is_some_and(Ordering::is_gt),
        IndexCompareOp::Gte => compare_order(left, right, strict).is_some_and(Ordering::is_ge),
        IndexCompareOp::In | IndexCompareOp::NotIn => {
            unreachable!("expected_strict_compare only handles one-literal compare operators")
        }
    }
}

#[test]
fn canonical_index_predicate_reuses_parsed_predicate_for_equivalent_sql_text() {
    static INDEX_A: IndexModel = IndexModel::generated_with_predicate(
        "idx_entity__active",
        "entity::index",
        &["active"],
        false,
        Some(active_true_predicate_metadata()),
    );
    static INDEX_B: IndexModel = IndexModel::generated_with_predicate(
        "idx_entity__active_alt",
        "entity::index",
        &["active"],
        false,
        Some(active_true_predicate_metadata()),
    );

    let first = canonical_index_predicate(&INDEX_A).expect("predicate should exist");
    let second = canonical_index_predicate(&INDEX_A).expect("predicate should exist");
    let third = canonical_index_predicate(&INDEX_B).expect("predicate should exist");

    assert!(
        std::ptr::eq(first, second),
        "same index predicate should return the same canonical predicate instance",
    );
    assert!(
        std::ptr::eq(first, third),
        "equivalent predicate SQL should resolve to the same canonical predicate instance",
    );
}

#[test]
fn canonical_index_predicate_is_absent_for_unfiltered_index() {
    static INDEX: IndexModel =
        IndexModel::generated("idx_entity__active", "entity::index", &["active"], false);

    assert!(canonical_index_predicate(&INDEX).is_none());
}

#[test]
fn compile_index_program_maps_field_slot_to_component_index() {
    let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
        Some(7),
        CompareOp::Eq,
        Value::Nat64(11),
        CoercionSpec::new(CoercionId::Strict),
    ));

    let program = compile_index_program(
        &predicate,
        &[3, 7, 9],
        IndexCompilePolicy::ConservativeSubset,
    )
    .expect("strict EQ over indexed slot should compile");
    let expected =
        literal_index_component_bytes(&Value::Nat64(11)).expect("nat literal should convert");

    assert_eq!(
        program,
        IndexPredicateProgram::Compare {
            component_index: 1,
            op: IndexCompareOp::Eq,
            literal: IndexLiteral::One(expected),
        }
    );
}

#[test]
fn prefix_component_predicate_evaluation_rejects_known_false_prefixes() {
    let collection = literal_index_component_bytes(&Value::Text("collection-a".to_string()))
        .expect("collection literal should encode");
    let draft =
        literal_index_component_bytes(&Value::Text("Draft".to_string())).expect("draft literal");
    let review =
        literal_index_component_bytes(&Value::Text("Review".to_string())).expect("review literal");
    let program = IndexPredicateProgram::Compare {
        component_index: 1,
        op: IndexCompareOp::Ne,
        literal: IndexLiteral::One(review.clone()),
    };

    assert_eq!(
        eval_index_program_on_prefix_components(&[collection.clone(), draft], &program,),
        Some(true),
        "known Draft branch prefix should pass stage != Review",
    );
    assert_eq!(
        eval_index_program_on_prefix_components(&[collection.clone(), review], &program),
        Some(false),
        "known Review branch prefix should be pruned before scanning",
    );
    assert_eq!(
        eval_index_program_on_prefix_components(&[collection], &program),
        None,
        "predicates on unbound suffix components must remain unknown",
    );
}

#[test]
fn compile_index_program_rejects_non_strict_coercion() {
    let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
        Some(1),
        CompareOp::Eq,
        Value::Nat64(11),
        CoercionSpec::new(CoercionId::NumericWiden),
    ));

    let program = compile_index_program(&predicate, &[1], IndexCompilePolicy::ConservativeSubset);
    assert!(program.is_none());
}

#[test]
fn compile_index_program_operator_matrix_matches_strict_subset() {
    let eligible = [
        (CompareOp::Eq, Value::Nat64(11)),
        (CompareOp::Ne, Value::Nat64(11)),
        (CompareOp::Lt, Value::Nat64(11)),
        (CompareOp::Lte, Value::Nat64(11)),
        (CompareOp::Gt, Value::Nat64(11)),
        (CompareOp::Gte, Value::Nat64(11)),
        (
            CompareOp::In,
            Value::List(vec![Value::Nat64(11), Value::Nat64(12)]),
        ),
        (
            CompareOp::NotIn,
            Value::List(vec![Value::Nat64(11), Value::Nat64(12)]),
        ),
        (CompareOp::StartsWith, Value::Text("x".to_string())),
    ];
    for (op, value) in eligible {
        let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
            Some(1),
            op,
            value,
            CoercionSpec::new(CoercionId::Strict),
        ));
        let program =
            compile_index_program(&predicate, &[1], IndexCompilePolicy::ConservativeSubset);

        assert!(
            program.is_some(),
            "strict compare op {op:?} should compile into an index predicate program",
        );
    }

    let ineligible = [
        (CompareOp::Contains, Value::Text("x".to_string())),
        (CompareOp::EndsWith, Value::Text("x".to_string())),
    ];
    for (op, value) in ineligible {
        let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
            Some(1),
            op,
            value,
            CoercionSpec::new(CoercionId::Strict),
        ));
        let program =
            compile_index_program(&predicate, &[1], IndexCompilePolicy::ConservativeSubset);

        assert!(
            program.is_none(),
            "op {op:?} should stay on fallback execution",
        );
    }
}

#[test]
fn compile_index_program_starts_with_compiles_to_bounded_range_compare_pair() {
    let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
        Some(1),
        CompareOp::StartsWith,
        Value::Text("foo".to_string()),
        CoercionSpec::new(CoercionId::Strict),
    ));

    let program = compile_index_program(&predicate, &[1], IndexCompilePolicy::ConservativeSubset)
        .expect("strict starts-with should compile for index prefilter");
    let expected_lower =
        literal_index_component_bytes(&Value::Text("foo".to_string())).expect("lower bytes");
    let expected_upper =
        literal_index_component_bytes(&Value::Text("fop".to_string())).expect("upper bytes");

    assert_eq!(
        program,
        IndexPredicateProgram::And(vec![
            IndexPredicateProgram::Compare {
                component_index: 0,
                op: IndexCompareOp::Gte,
                literal: IndexLiteral::One(expected_lower),
            },
            IndexPredicateProgram::Compare {
                component_index: 0,
                op: IndexCompareOp::Lt,
                literal: IndexLiteral::One(expected_upper),
            },
        ]),
    );
}

#[test]
fn compile_index_program_starts_with_rejects_empty_prefix() {
    let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
        Some(1),
        CompareOp::StartsWith,
        Value::Text(String::new()),
        CoercionSpec::new(CoercionId::Strict),
    ));

    let program = compile_index_program(&predicate, &[1], IndexCompilePolicy::ConservativeSubset);
    assert!(program.is_none());
}

#[test]
fn compile_index_program_starts_with_high_unicode_skips_surrogate_gap_upper_bound() {
    let prefix = format!("foo{}", char::from_u32(0xD7FF).expect("valid scalar"));
    let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
        Some(1),
        CompareOp::StartsWith,
        Value::Text(prefix.clone()),
        CoercionSpec::new(CoercionId::Strict),
    ));

    let program = compile_index_program(&predicate, &[1], IndexCompilePolicy::ConservativeSubset)
        .expect("strict starts-with should compile for high-unicode prefix");
    let expected_lower =
        literal_index_component_bytes(&Value::Text(prefix)).expect("lower bytes should convert");
    let expected_upper = literal_index_component_bytes(&Value::Text(format!(
        "foo{}",
        char::from_u32(0xE000).expect("valid scalar")
    )))
    .expect("upper bytes should skip surrogate gap");

    assert_eq!(
        program,
        IndexPredicateProgram::And(vec![
            IndexPredicateProgram::Compare {
                component_index: 0,
                op: IndexCompareOp::Gte,
                literal: IndexLiteral::One(expected_lower),
            },
            IndexPredicateProgram::Compare {
                component_index: 0,
                op: IndexCompareOp::Lt,
                literal: IndexLiteral::One(expected_upper),
            },
        ]),
    );
}

#[test]
fn compile_index_program_starts_with_max_unicode_compiles_to_lower_bound_only() {
    let prefix = char::from_u32(0x10_FFFF).expect("valid scalar").to_string();
    let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
        Some(1),
        CompareOp::StartsWith,
        Value::Text(prefix.clone()),
        CoercionSpec::new(CoercionId::Strict),
    ));

    let program = compile_index_program(&predicate, &[1], IndexCompilePolicy::ConservativeSubset)
        .expect("max-unicode starts-with should compile to one lower-bound compare");
    let expected_lower =
        literal_index_component_bytes(&Value::Text(prefix)).expect("lower bytes should convert");

    assert_eq!(
        program,
        IndexPredicateProgram::Compare {
            component_index: 0,
            op: IndexCompareOp::Gte,
            literal: IndexLiteral::One(expected_lower),
        },
    );
}

#[test]
fn compile_index_program_strict_mode_accepts_starts_with_bounded_prefix() {
    let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
        Some(1),
        CompareOp::StartsWith,
        Value::Text("foo".to_string()),
        CoercionSpec::new(CoercionId::Strict),
    ));

    let program = compile_index_program(&predicate, &[1], IndexCompilePolicy::StrictAllOrNone)
        .expect("strict-all-or-none should compile starts-with when fully index-expressible");
    let expected_lower =
        literal_index_component_bytes(&Value::Text("foo".to_string())).expect("lower bytes");
    let expected_upper =
        literal_index_component_bytes(&Value::Text("fop".to_string())).expect("upper bytes");

    assert_eq!(
        program,
        IndexPredicateProgram::And(vec![
            IndexPredicateProgram::Compare {
                component_index: 0,
                op: IndexCompareOp::Gte,
                literal: IndexLiteral::One(expected_lower),
            },
            IndexPredicateProgram::Compare {
                component_index: 0,
                op: IndexCompareOp::Lt,
                literal: IndexLiteral::One(expected_upper),
            },
        ]),
    );
}

#[test]
fn compile_index_program_strict_mode_accepts_starts_with_max_unicode_prefix() {
    let prefix = char::from_u32(0x10_FFFF).expect("valid scalar").to_string();
    let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
        Some(1),
        CompareOp::StartsWith,
        Value::Text(prefix.clone()),
        CoercionSpec::new(CoercionId::Strict),
    ));

    let program = compile_index_program(&predicate, &[1], IndexCompilePolicy::StrictAllOrNone)
        .expect("strict-all-or-none should compile max-unicode starts-with lower-bound form");
    let expected_lower =
        literal_index_component_bytes(&Value::Text(prefix)).expect("lower bytes should convert");

    assert_eq!(
        program,
        IndexPredicateProgram::Compare {
            component_index: 0,
            op: IndexCompareOp::Gte,
            literal: IndexLiteral::One(expected_lower),
        },
    );
}

#[test]
fn compile_index_program_targets_accept_text_casefold_strict_range() {
    let predicate = ExecutablePredicate::And(vec![
        ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
            Some(1),
            CompareOp::Gte,
            Value::Text("BR".to_string()),
            CoercionSpec::new(CoercionId::TextCasefold),
        )),
        ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
            Some(1),
            CompareOp::Lt,
            Value::Text("BS".to_string()),
            CoercionSpec::new(CoercionId::TextCasefold),
        )),
    ]);
    let compile_targets = [IndexCompileTarget {
        component_index: 0,
        field_slot: 1,
        key_item: IndexKeyItem::Expression(IndexExpression::Lower("name")),
    }];

    let program = compile_index_program_for_targets(
        &predicate,
        &compile_targets,
        IndexCompilePolicy::StrictAllOrNone,
    )
    .expect("strict-all-or-none should compile text-casefold range for expression target");
    let expected_lower =
        literal_index_component_bytes(&Value::Text("br".to_string())).expect("lower bytes");
    let expected_upper =
        literal_index_component_bytes(&Value::Text("bs".to_string())).expect("upper bytes");

    assert_eq!(
        program,
        IndexPredicateProgram::And(vec![
            IndexPredicateProgram::Compare {
                component_index: 0,
                op: IndexCompareOp::Gte,
                literal: IndexLiteral::One(expected_lower),
            },
            IndexPredicateProgram::Compare {
                component_index: 0,
                op: IndexCompareOp::Lt,
                literal: IndexLiteral::One(expected_upper),
            },
        ]),
    );
}

#[test]
fn compile_index_program_rejects_non_strict_coercion_across_operator_subset() {
    let operators = [
        (CompareOp::Eq, Value::Nat64(11)),
        (CompareOp::Ne, Value::Nat64(11)),
        (CompareOp::Lt, Value::Nat64(11)),
        (CompareOp::Lte, Value::Nat64(11)),
        (CompareOp::Gt, Value::Nat64(11)),
        (CompareOp::Gte, Value::Nat64(11)),
        (
            CompareOp::In,
            Value::List(vec![Value::Nat64(11), Value::Nat64(12)]),
        ),
        (
            CompareOp::NotIn,
            Value::List(vec![Value::Nat64(11), Value::Nat64(12)]),
        ),
    ];

    for (op, value) in operators {
        let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
            Some(1),
            op,
            value,
            CoercionSpec::new(CoercionId::NumericWiden),
        ));
        let program =
            compile_index_program(&predicate, &[1], IndexCompilePolicy::ConservativeSubset);

        assert!(
            program.is_none(),
            "non-strict coercion for op {op:?} must remain unsupported in index subset",
        );
    }
}

#[test]
fn compile_index_program_rejects_in_with_non_list_literal() {
    let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
        Some(1),
        CompareOp::In,
        Value::Nat64(11),
        CoercionSpec::new(CoercionId::Strict),
    ));

    let program = compile_index_program(&predicate, &[1], IndexCompilePolicy::ConservativeSubset);
    assert!(program.is_none());
}

#[test]
fn compile_index_program_rejects_in_with_empty_list_literal() {
    let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
        Some(1),
        CompareOp::In,
        Value::List(Vec::new()),
        CoercionSpec::new(CoercionId::Strict),
    ));

    let program = compile_index_program(&predicate, &[1], IndexCompilePolicy::ConservativeSubset);
    assert!(program.is_none());
}

#[test]
fn compile_index_program_keeps_small_in_literals_linear() {
    let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
        Some(1),
        CompareOp::In,
        Value::List(vec![
            Value::Text("gamma".to_string()),
            Value::Text("alpha".to_string()),
            Value::Text("beta".to_string()),
            Value::Text("alpha".to_string()),
        ]),
        CoercionSpec::new(CoercionId::Strict),
    ));

    let program = compile_index_program(&predicate, &[1], IndexCompilePolicy::ConservativeSubset)
        .expect("strict IN should compile to an index predicate");
    let alpha = literal_index_component_bytes(&Value::Text("alpha".to_string()))
        .expect("alpha literal should encode");
    let beta = literal_index_component_bytes(&Value::Text("beta".to_string()))
        .expect("beta literal should encode");
    let gamma = literal_index_component_bytes(&Value::Text("gamma".to_string()))
        .expect("gamma literal should encode");

    assert_eq!(
        program,
        IndexPredicateProgram::Compare {
            component_index: 0,
            op: IndexCompareOp::In,
            literal: IndexLiteral::Many(vec![gamma, alpha.clone(), beta, alpha]),
        },
        "small index membership literals should keep linear caller-order evaluation",
    );
}

#[test]
fn compile_index_program_canonicalizes_large_in_literals_for_binary_membership() {
    let mut values = (0..40)
        .rev()
        .map(|idx| Value::Text(format!("v{idx:02}")))
        .collect::<Vec<_>>();
    values.push(Value::Text("v07".to_string()));
    let predicate = ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
        Some(1),
        CompareOp::In,
        Value::List(values),
        CoercionSpec::new(CoercionId::Strict),
    ));

    let program = compile_index_program(&predicate, &[1], IndexCompilePolicy::ConservativeSubset)
        .expect("strict IN should compile to an index predicate");
    let mut expected = (0..40)
        .map(|idx| {
            literal_index_component_bytes(&Value::Text(format!("v{idx:02}")))
                .expect("expected literal should encode")
        })
        .collect::<Vec<_>>();
    expected.sort();
    expected.dedup();
    let hit = literal_index_component_bytes(&Value::Text("v07".to_string()))
        .expect("hit literal should encode");

    let IndexPredicateProgram::Compare { literal, .. } = &program else {
        panic!("expected compare program");
    };
    assert_eq!(
        program,
        IndexPredicateProgram::Compare {
            component_index: 0,
            op: IndexCompareOp::In,
            literal: IndexLiteral::ManySorted(expected),
        },
        "large index membership literals must be sorted and deduplicated for binary search",
    );
    assert!(
        eval_index_compare(hit.as_slice(), IndexCompareOp::In, literal),
        "canonicalized compiled membership should preserve strict IN semantics",
    );
}

#[test]
fn compile_index_program_and_subset_compiles_supported_children_only() {
    let predicate = ExecutablePredicate::And(vec![
        ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
            Some(1),
            CompareOp::Eq,
            Value::Nat64(11),
            CoercionSpec::new(CoercionId::Strict),
        )),
        ExecutablePredicate::TextContains {
            field_slot: Some(1),
            value: Value::Text("x".to_string()),
        },
        ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
            Some(2),
            CompareOp::Gt,
            Value::Nat64(9),
            CoercionSpec::new(CoercionId::Strict),
        )),
    ]);

    let program =
        compile_index_program(&predicate, &[1, 2], IndexCompilePolicy::ConservativeSubset)
            .expect("subset mode should keep supported children");

    let expected_left =
        literal_index_component_bytes(&Value::Nat64(11)).expect("left should convert");
    let expected_right =
        literal_index_component_bytes(&Value::Nat64(9)).expect("right should convert");

    assert_eq!(
        program,
        IndexPredicateProgram::And(vec![
            IndexPredicateProgram::Compare {
                component_index: 0,
                op: IndexCompareOp::Eq,
                literal: IndexLiteral::One(expected_left),
            },
            IndexPredicateProgram::Compare {
                component_index: 1,
                op: IndexCompareOp::Gt,
                literal: IndexLiteral::One(expected_right),
            },
        ]),
    );
}

#[test]
fn compile_index_program_and_subset_drops_fully_unsupported_and() {
    let predicate = ExecutablePredicate::And(vec![
        ExecutablePredicate::TextContains {
            field_slot: Some(1),
            value: Value::Text("x".to_string()),
        },
        ExecutablePredicate::IsNull {
            field_slot: Some(2),
        },
    ]);

    let program =
        compile_index_program(&predicate, &[1, 2], IndexCompilePolicy::ConservativeSubset);
    assert!(program.is_none());
}

#[test]
fn compile_index_program_strict_rejects_partial_and_support() {
    let predicate = ExecutablePredicate::And(vec![
        ExecutablePredicate::Compare(ExecutableComparePredicate::field_literal(
            Some(1),
            CompareOp::Eq,
            Value::Nat64(11),
            CoercionSpec::new(CoercionId::Strict),
        )),
        ExecutablePredicate::TextContains {
            field_slot: Some(1),
            value: Value::Text("x".to_string()),
        },
    ]);

    let program = compile_index_program(&predicate, &[1], IndexCompilePolicy::StrictAllOrNone);
    assert!(program.is_none());
}

#[test]
fn eval_index_compare_matches_strict_semantics_for_one_literal_ops() {
    let strict = CoercionSpec::new(CoercionId::Strict);
    let cases = vec![
        (Value::Int64(-2), Value::Int64(7)),
        (
            Value::Decimal(Decimal::new(10, 1)),
            Value::Decimal(Decimal::new(1, 0)),
        ),
        (
            Value::Text("alpha".to_string()),
            Value::Text("beta".to_string()),
        ),
    ];
    let operators = [
        IndexCompareOp::Eq,
        IndexCompareOp::Ne,
        IndexCompareOp::Lt,
        IndexCompareOp::Lte,
        IndexCompareOp::Gt,
        IndexCompareOp::Gte,
    ];

    for (left, right) in cases {
        let component = literal_index_component_bytes(&left).expect("left value should encode");
        let literal = IndexLiteral::One(
            literal_index_component_bytes(&right).expect("right value should encode"),
        );

        for op in operators {
            let expected = expected_strict_compare(op, &left, &right, &strict);
            let actual = eval_index_compare(component.as_slice(), op, &literal);

            assert_eq!(
                actual, expected,
                "index compare drifted from strict predicate semantics for op={op:?} left={left:?} right={right:?}",
            );
        }
    }
}

#[test]
fn eval_index_compare_in_and_not_in_match_strict_membership_semantics() {
    let strict = CoercionSpec::new(CoercionId::Strict);
    let target = Value::Text("beta".to_string());
    let candidates = [
        Value::Text("alpha".to_string()),
        Value::Text("beta".to_string()),
        Value::Text("gamma".to_string()),
    ];
    let component = literal_index_component_bytes(&target).expect("target should encode");
    let literal = IndexLiteral::Many(
        candidates
            .iter()
            .map(literal_index_component_bytes)
            .collect::<Option<Vec<_>>>()
            .expect("all candidate literals should encode"),
    );

    let expected_in = candidates
        .iter()
        .any(|candidate| compare_eq(&target, candidate, &strict).unwrap_or(false));
    let expected_not_in = candidates
        .iter()
        .all(|candidate| compare_eq(&target, candidate, &strict).is_some_and(|eq| !eq));

    assert_eq!(
        eval_index_compare(component.as_slice(), IndexCompareOp::In, &literal),
        expected_in,
    );
    assert_eq!(
        eval_index_compare(component.as_slice(), IndexCompareOp::NotIn, &literal),
        expected_not_in,
    );
}

#[test]
fn eval_index_program_missing_component_is_index_invariant() {
    let (key, _) = IndexKey::bounds_for_prefix_with_kind(
        &IndexId::new(EntityTag::new(7), 0),
        IndexKeyKind::User,
        0,
        &[] as &[Vec<u8>],
    );
    let program = IndexPredicateProgram::Compare {
        component_index: 0,
        op: IndexCompareOp::Eq,
        literal: IndexLiteral::One(vec![0x01]),
    };

    let err = eval_index_program_on_decoded_key(&key, &program)
        .expect_err("missing component must fail closed");

    assert_eq!(err.class, ErrorClass::InvariantViolation);
    assert_eq!(err.origin, ErrorOrigin::Index);
}