icydb-core 0.213.35

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
use super::*;

use crate::{
    db::write_context::MutationMode,
    db::{
        commit::CommitSchemaFingerprint,
        data::AcceptedFieldWriteProvenance,
        schema::{
            AcceptedCompositeCatalog, AcceptedConstraintKind, AcceptedSchemaFingerprint,
            AcceptedSchemaRevision, AcceptedSchemaSnapshot, AcceptedValueCatalogHandle,
            ConstraintId, ConstraintOrigin, FieldId, PersistedFieldSnapshot,
            PersistedIndexFieldPathSnapshot, PersistedIndexKeySnapshot, PersistedIndexSnapshot,
            PersistedSchemaSnapshot, SchemaFieldSlot, SchemaIndexId, SchemaInsertDefault,
            SchemaRowLayout, SchemaVersion,
            composite_catalog::{
                AcceptedCompositeElement, AcceptedCompositeShape, CompositeTypeId,
            },
            enum_catalog::build_initial_accepted_enum_catalog,
        },
    },
    model::field::{FieldStorageDecode, LeafCodec, ScalarCodec},
    value::{InputValue, Value},
};
use icydb_schema::Decimal;
use std::collections::BTreeMap;

const FINGERPRINT: CommitSchemaFingerprint = [7; 16];

fn field(
    id: u32,
    slot: u16,
    name: &str,
    kind: AcceptedFieldKind,
    nullable: bool,
    leaf_codec: LeafCodec,
) -> PersistedFieldSnapshot {
    PersistedFieldSnapshot::new_initial(
        FieldId::new(id),
        name.to_string(),
        SchemaFieldSlot::new(slot),
        kind,
        Vec::new(),
        nullable,
        SchemaInsertDefault::None,
        if matches!(leaf_codec, LeafCodec::Structural) {
            FieldStorageDecode::CatalogValue
        } else {
            FieldStorageDecode::ByKind
        },
        leaf_codec,
    )
}

fn snapshot() -> PersistedSchemaSnapshot {
    let fields = vec![
        field(
            1,
            0,
            "id",
            AcceptedFieldKind::Ulid,
            false,
            LeafCodec::Scalar(ScalarCodec::Ulid),
        ),
        field(
            2,
            1,
            "score",
            AcceptedFieldKind::Int64,
            false,
            LeafCodec::Scalar(ScalarCodec::Int64),
        ),
        field(
            3,
            2,
            "nickname",
            AcceptedFieldKind::Text { max_len: Some(64) },
            true,
            LeafCodec::Scalar(ScalarCodec::Text),
        ),
        field(
            4,
            3,
            "tags",
            AcceptedFieldKind::List(Box::new(AcceptedFieldKind::Text { max_len: Some(16) })),
            false,
            LeafCodec::Structural,
        ),
        field(
            5,
            4,
            "payload",
            AcceptedFieldKind::Blob { max_len: Some(64) },
            false,
            LeafCodec::Scalar(ScalarCodec::Blob),
        ),
    ];
    PersistedSchemaSnapshot::new(
        SchemaVersion::initial(),
        "tests::CheckedEntity".to_string(),
        "CheckedEntity".to_string(),
        FieldId::new(1),
        SchemaRowLayout::initial(
            fields
                .iter()
                .map(|field| (field.id(), field.slot()))
                .collect(),
        ),
        fields,
    )
}

fn value_catalog() -> AcceptedValueCatalogHandle {
    let enum_catalog =
        build_initial_accepted_enum_catalog(&[]).expect("empty enum catalog should build");
    AcceptedValueCatalogHandle::new_for_tests(
        enum_catalog,
        AcceptedCompositeCatalog::empty(),
        AcceptedSchemaRevision::INITIAL,
    )
}

fn accepted_with_check(
    input: CheckExprV1Input,
) -> (
    AcceptedSchemaSnapshot,
    AcceptedValueCatalogHandle,
    ConstraintId,
) {
    let snapshot = snapshot();
    let value_catalog = value_catalog();
    let expression = bind_check_expr_v1(
        input,
        &snapshot,
        value_catalog.enum_catalog(),
        value_catalog.composite_catalog(),
    )
    .expect("test check expression should bind");
    let catalog = snapshot
        .constraint_catalog()
        .clone()
        .with_added_check(
            "score_policy".to_string(),
            ConstraintOrigin::Generated,
            expression,
        )
        .expect("test check constraint should allocate");
    let constraint_id = catalog
        .constraints()
        .iter()
        .find_map(|constraint| {
            matches!(constraint.kind(), AcceptedConstraintKind::Check { .. })
                .then_some(constraint.id())
        })
        .expect("test check constraint should be present");
    let accepted = AcceptedSchemaSnapshot::try_new(snapshot.with_constraint_catalog(catalog))
        .expect("test check schema should be accepted");

    (accepted, value_catalog, constraint_id)
}

fn values(score: i64, nickname: Value, tags: Vec<Value>) -> Vec<Option<Value>> {
    vec![
        None,
        Some(Value::Int64(score)),
        Some(nickname),
        Some(Value::List(tags)),
    ]
}

#[test]
fn binder_lowers_ranges_and_canonicalizes_commutative_children() {
    let snapshot = snapshot();
    let catalog = value_catalog();
    let score_nonnegative = CheckExprV1Input::Compare {
        left: CheckValueExprV1Input::Field("score".to_string()),
        op: AcceptedCheckCompareOpV1::Gte,
        right: CheckValueExprV1Input::Literal(InputValue::Int64(0)),
    };
    let expression = bind_check_expr_v1(
        CheckExprV1Input::And(vec![
            CheckExprV1Input::Between {
                value: CheckValueExprV1Input::Field("score".to_string()),
                lower: InputValue::Int64(0),
                upper: InputValue::Int64(100),
            },
            score_nonnegative.clone(),
            score_nonnegative,
        ]),
        &snapshot,
        catalog.enum_catalog(),
        catalog.composite_catalog(),
    )
    .expect("bounded range should bind");

    assert_eq!(expression.dependencies(), vec![FieldId::new(2)]);
    let AcceptedCheckExprV1::And(children) = expression else {
        panic!("range and duplicate comparison should canonicalize to one AND");
    };
    assert_eq!(children.len(), 2);
    assert!(children[0].canonical_key() < children[1].canonical_key());
}

#[test]
fn binder_covers_boolean_null_and_octet_length_nodes() {
    let snapshot = snapshot();
    let catalog = value_catalog();
    let expression = bind_check_expr_v1(
        CheckExprV1Input::And(vec![
            CheckExprV1Input::Or(vec![CheckExprV1Input::True, CheckExprV1Input::False]),
            CheckExprV1Input::Not(Box::new(CheckExprV1Input::False)),
            CheckExprV1Input::IsNull(CheckValueExprV1Input::Field("nickname".to_string())),
            CheckExprV1Input::IsNotNull(CheckValueExprV1Input::Field("score".to_string())),
            CheckExprV1Input::Compare {
                left: CheckValueExprV1Input::OctetLength("payload".to_string()),
                op: AcceptedCheckCompareOpV1::Lte,
                right: CheckValueExprV1Input::Literal(InputValue::Nat64(64)),
            },
        ]),
        &snapshot,
        catalog.enum_catalog(),
        catalog.composite_catalog(),
    )
    .expect("supported boolean and length nodes should bind");

    assert_eq!(
        expression.dependencies(),
        vec![FieldId::new(2), FieldId::new(3), FieldId::new(5)]
    );
}

#[test]
fn accepted_check_renderer_uses_current_field_names_and_canonical_literals() {
    let snapshot = snapshot();
    let catalog = value_catalog();
    let numeric = bind_check_expr_v1(
        CheckExprV1Input::Compare {
            left: CheckValueExprV1Input::Field("score".to_string()),
            op: AcceptedCheckCompareOpV1::Gte,
            right: CheckValueExprV1Input::Literal(InputValue::Int64(0)),
        },
        &snapshot,
        catalog.enum_catalog(),
        catalog.composite_catalog(),
    )
    .expect("numeric check should bind");
    let text = bind_check_expr_v1(
        CheckExprV1Input::Compare {
            left: CheckValueExprV1Input::Field("nickname".to_string()),
            op: AcceptedCheckCompareOpV1::Ne,
            right: CheckValueExprV1Input::Literal(InputValue::Text("O'Reilly".to_string())),
        },
        &snapshot,
        catalog.enum_catalog(),
        catalog.composite_catalog(),
    )
    .expect("text check should bind");

    assert_eq!(
        render_accepted_check_expr_sql(&numeric, &snapshot, &catalog)
            .expect("accepted numeric check should render"),
        "score >= 0",
    );
    assert_eq!(
        render_accepted_check_expr_sql(&text, &snapshot, &catalog)
            .expect("accepted text check should render"),
        "nickname != 'O''Reilly'",
    );
}

#[test]
fn compiled_checks_apply_sql_three_valued_semantics_and_stable_violation_identity() {
    let (accepted, catalog, constraint_id) = accepted_with_check(CheckExprV1Input::And(vec![
        CheckExprV1Input::Compare {
            left: CheckValueExprV1Input::Field("score".to_string()),
            op: AcceptedCheckCompareOpV1::Gte,
            right: CheckValueExprV1Input::Literal(InputValue::Int64(0)),
        },
        CheckExprV1Input::Compare {
            left: CheckValueExprV1Input::Field("nickname".to_string()),
            op: AcceptedCheckCompareOpV1::Ne,
            right: CheckValueExprV1Input::Literal(InputValue::Text("blocked".to_string())),
        },
    ]));
    let program = CompiledAcceptedRowConstraints::compile(&accepted, &catalog, FINGERPRINT)
        .expect("accepted checks should compile");

    program
        .evaluate(FINGERPRINT, &values(1, Value::Null, Vec::new()))
        .expect("UNKNOWN nickname comparison should satisfy CHECK");
    let error = program
        .evaluate(
            FINGERPRINT,
            &values(-1, Value::Text("allowed".to_string()), Vec::new()),
        )
        .expect_err("false score comparison should reject");
    assert_eq!(
        error,
        AcceptedRowConstraintEvaluationError::Violation {
            constraint_id,
            constraint_name: "score_policy".to_string(),
            kind: AcceptedRowConstraintViolationKind::Check,
            field_paths: vec!["score".to_string(), "nickname".to_string()],
        }
    );
}

#[test]
fn compiled_checks_include_pending_check_activation_gates() {
    let snapshot = snapshot();
    let catalog = value_catalog();
    let expression = bind_check_expr_v1(
        CheckExprV1Input::Compare {
            left: CheckValueExprV1Input::Field("score".to_string()),
            op: AcceptedCheckCompareOpV1::Gte,
            right: CheckValueExprV1Input::Literal(InputValue::Int64(0)),
        },
        &snapshot,
        catalog.enum_catalog(),
        catalog.composite_catalog(),
    )
    .expect("activation expression should bind");
    let constraint_catalog = snapshot
        .constraint_catalog()
        .clone()
        .with_added_check_activation(
            "pending_score_policy".to_string(),
            ConstraintOrigin::Generated,
            expression,
            AcceptedSchemaFingerprint::new([0xA5; 32]),
            2,
        )
        .expect("activation should reserve identity");
    let activation_id = constraint_catalog.activations()[0].id();
    let accepted =
        AcceptedSchemaSnapshot::try_new(snapshot.with_constraint_catalog(constraint_catalog))
            .expect("activation snapshot should close");
    let program = CompiledAcceptedRowConstraints::compile(&accepted, &catalog, FINGERPRINT)
        .expect("pending gate should compile");

    assert_eq!(
        program.evaluate(FINGERPRINT, &values(-1, Value::Null, Vec::new()),),
        Err(AcceptedRowConstraintEvaluationError::Violation {
            constraint_id: activation_id,
            constraint_name: "pending_score_policy".to_string(),
            kind: AcceptedRowConstraintViolationKind::Check,
            field_paths: vec!["score".to_string()],
        }),
    );
}

#[test]
fn integrity_check_program_excludes_pending_activation_semantics() {
    let snapshot = snapshot();
    let catalog = value_catalog();
    let expression = bind_check_expr_v1(
        CheckExprV1Input::Compare {
            left: CheckValueExprV1Input::Field("score".to_string()),
            op: AcceptedCheckCompareOpV1::Gte,
            right: CheckValueExprV1Input::Literal(InputValue::Int64(0)),
        },
        &snapshot,
        catalog.enum_catalog(),
        catalog.composite_catalog(),
    )
    .expect("activation expression should bind");
    let constraint_catalog = snapshot
        .constraint_catalog()
        .clone()
        .with_added_check_activation(
            "pending_score_policy".to_string(),
            ConstraintOrigin::Generated,
            expression,
            AcceptedSchemaFingerprint::new([0xA5; 32]),
            2,
        )
        .expect("activation should reserve identity");
    let accepted =
        AcceptedSchemaSnapshot::try_new(snapshot.with_constraint_catalog(constraint_catalog))
            .expect("activation snapshot should close");
    let program = CompiledAcceptedRowConstraints::compile(&accepted, &catalog, FINGERPRINT)
        .expect("shared write/integrity program should compile");

    assert_eq!(program.integrity_check_count(), 0);
}

#[test]
fn integrity_check_program_evaluates_each_validated_check_by_stable_ordinal() {
    let snapshot = snapshot();
    let catalog = value_catalog();
    let score = bind_check_expr_v1(
        CheckExprV1Input::Compare {
            left: CheckValueExprV1Input::Field("score".to_string()),
            op: AcceptedCheckCompareOpV1::Gte,
            right: CheckValueExprV1Input::Literal(InputValue::Int64(0)),
        },
        &snapshot,
        catalog.enum_catalog(),
        catalog.composite_catalog(),
    )
    .expect("score check should bind");
    let nickname = bind_check_expr_v1(
        CheckExprV1Input::Compare {
            left: CheckValueExprV1Input::Field("nickname".to_string()),
            op: AcceptedCheckCompareOpV1::Ne,
            right: CheckValueExprV1Input::Literal(InputValue::Text("blocked".to_string())),
        },
        &snapshot,
        catalog.enum_catalog(),
        catalog.composite_catalog(),
    )
    .expect("nickname check should bind");
    let constraint_catalog = snapshot
        .constraint_catalog()
        .clone()
        .with_added_check(
            "score_policy".to_string(),
            ConstraintOrigin::Generated,
            score,
        )
        .expect("score check should allocate")
        .with_added_check(
            "nickname_policy".to_string(),
            ConstraintOrigin::Generated,
            nickname,
        )
        .expect("nickname check should allocate");
    let accepted =
        AcceptedSchemaSnapshot::try_new(snapshot.with_constraint_catalog(constraint_catalog))
            .expect("validated checks should close");
    let program = CompiledAcceptedRowConstraints::compile(&accepted, &catalog, FINGERPRINT)
        .expect("shared write/integrity program should compile");
    let row = values(-1, Value::Text("blocked".to_string()), Vec::new());

    assert_eq!(program.integrity_check_count(), 2);
    for ordinal in 0..program.integrity_check_count() {
        assert!(matches!(
            program.evaluate_integrity_check(ordinal, FINGERPRINT, row.as_slice()),
            Err(AcceptedRowConstraintEvaluationError::Violation { .. }),
        ));
    }
}

#[test]
fn compiled_row_constraints_include_pending_not_null_activation_gates() {
    let snapshot = snapshot();
    let catalog = value_catalog();
    let nullable_field = snapshot
        .fields()
        .iter()
        .find(|field| field.name() == "nickname")
        .expect("nullable test field should exist");
    let constraint_catalog = snapshot
        .constraint_catalog()
        .clone()
        .with_added_not_null_activation(
            nullable_field,
            AcceptedSchemaFingerprint::new([0xA5; 32]),
            3,
        )
        .expect("not-null activation should reserve identity");
    let activation_id = constraint_catalog.activations()[0].id();
    let activation_name = constraint_catalog.activations()[0].name().to_string();
    let accepted =
        AcceptedSchemaSnapshot::try_new(snapshot.with_constraint_catalog(constraint_catalog))
            .expect("not-null activation snapshot should close");
    let program = CompiledAcceptedRowConstraints::compile(&accepted, &catalog, FINGERPRINT)
        .expect("pending not-null gate should compile");

    assert_eq!(program.required_slots(), &[2]);
    assert_eq!(
        program.evaluate(FINGERPRINT, &values(1, Value::Null, Vec::new())),
        Err(AcceptedRowConstraintEvaluationError::Violation {
            constraint_id: activation_id,
            constraint_name: activation_name,
            kind: AcceptedRowConstraintViolationKind::NotNull,
            field_paths: vec!["nickname".to_string()],
        }),
    );
    program
        .evaluate(
            FINGERPRINT,
            &values(1, Value::Text("Ada".to_string()), Vec::new()),
        )
        .expect("non-null final value should pass the pending gate");
}

#[test]
fn compiled_unique_activation_blocks_inserts_and_dependency_changes_only() {
    let snapshot = snapshot();
    let candidate = PersistedIndexSnapshot::new(
        SchemaIndexId::new(1).expect("test schema index identity should be non-zero"),
        1,
        "unique_score".to_string(),
        "tests::CheckedEntity::unique_score".to_string(),
        true,
        PersistedIndexKeySnapshot::FieldPath(vec![PersistedIndexFieldPathSnapshot::new(
            FieldId::new(2),
            SchemaFieldSlot::new(1),
            vec!["score".to_string()],
            AcceptedFieldKind::Int64,
            false,
        )]),
        None,
    )
    .clone_with_schema_identity(
        SchemaIndexId::new(1).expect("test schema index identity should be non-zero"),
        1,
        9,
    );
    let snapshot = snapshot
        .with_added_unique_activation(candidate, AcceptedSchemaFingerprint::new([0xA5; 32]), 9)
        .expect("unique activation should close");
    let activation_id = snapshot.constraint_activations()[0].id();
    let accepted =
        AcceptedSchemaSnapshot::try_new(snapshot).expect("unique activation snapshot should close");
    let program = CompiledAcceptedRowConstraints::compile(&accepted, &value_catalog(), FINGERPRINT)
        .expect("unique write barrier should compile");
    let mut provenance = vec![Some(AcceptedFieldWriteProvenance::Preserved); 5];

    assert!(
        !program.is_empty(),
        "an activation gate makes the compiled constraint authority non-empty",
    );
    let insert_barrier = program
        .unique_activation_write_blocker(MutationMode::Insert, &provenance)
        .expect("insert barrier should evaluate")
        .expect("insert should be blocked");
    assert_eq!(insert_barrier.constraint_id(), activation_id);
    assert!(!insert_barrier.constraint_name().is_empty());
    assert_eq!(insert_barrier.field_paths(), &["score".to_string()]);
    assert!(
        program
            .unique_activation_write_blocker(MutationMode::Update, &provenance)
            .expect("unrelated update barrier should evaluate")
            .is_none(),
    );
    provenance[2] = Some(AcceptedFieldWriteProvenance::Authored);
    assert!(
        program
            .unique_activation_write_blocker(MutationMode::Update, &provenance)
            .expect("unrelated authored field should evaluate")
            .is_none(),
    );
    provenance[1] = Some(AcceptedFieldWriteProvenance::Authored);
    assert_eq!(
        program
            .unique_activation_write_blocker(MutationMode::Update, &provenance)
            .expect("dependency barrier should evaluate")
            .map(super::compile::CompiledUniqueWriteBarrier::constraint_id),
        Some(activation_id),
    );
}

#[test]
fn length_and_cardinality_use_one_prebound_slot_set() {
    let (accepted, catalog, _) = accepted_with_check(CheckExprV1Input::And(vec![
        CheckExprV1Input::Compare {
            left: CheckValueExprV1Input::CharLength("nickname".to_string()),
            op: AcceptedCheckCompareOpV1::Lte,
            right: CheckValueExprV1Input::Literal(InputValue::Nat64(4)),
        },
        CheckExprV1Input::Compare {
            left: CheckValueExprV1Input::Cardinality("tags".to_string()),
            op: AcceptedCheckCompareOpV1::Lte,
            right: CheckValueExprV1Input::Literal(InputValue::Nat64(2)),
        },
    ]));
    let program = CompiledAcceptedRowConstraints::compile(&accepted, &catalog, FINGERPRINT)
        .expect("accepted checks should compile");

    assert_eq!(program.required_slots(), &[2, 3]);
    program
        .evaluate(
            FINGERPRINT,
            &values(
                10,
                Value::Text("éé".to_string()),
                vec![Value::Text("a".to_string()), Value::Text("b".to_string())],
            ),
        )
        .expect("valid length and cardinality should pass");
}

#[test]
fn compiled_checks_reject_stale_fingerprint_and_missing_required_slot() {
    let (accepted, catalog, _) = accepted_with_check(CheckExprV1Input::Compare {
        left: CheckValueExprV1Input::Field("score".to_string()),
        op: AcceptedCheckCompareOpV1::Gte,
        right: CheckValueExprV1Input::Literal(InputValue::Int64(0)),
    });
    let program = CompiledAcceptedRowConstraints::compile(&accepted, &catalog, FINGERPRINT)
        .expect("accepted checks should compile");

    assert_eq!(
        program.evaluate([8; 16], &values(1, Value::Null, Vec::new())),
        Err(AcceptedRowConstraintEvaluationError::FingerprintMismatch)
    );
    assert_eq!(
        program.evaluate(FINGERPRINT, &[None]),
        Err(AcceptedRowConstraintEvaluationError::MissingSlot)
    );
}

#[test]
fn binder_rejects_empty_or_oversized_membership() {
    let snapshot = snapshot();
    let catalog = value_catalog();
    assert_eq!(
        bind_check_expr_v1(
            CheckExprV1Input::EnumIn {
                field: "score".to_string(),
                members: Vec::new(),
            },
            &snapshot,
            catalog.enum_catalog(),
            catalog.composite_catalog(),
        ),
        Err(AcceptedCheckExprV1Error::MembershipEmpty)
    );
    assert_eq!(
        bind_check_expr_v1(
            CheckExprV1Input::EnumIn {
                field: "score".to_string(),
                members: vec![InputValue::Int64(1); MAX_CHECK_EXPR_V1_MEMBERSHIP_ITEMS + 1],
            },
            &snapshot,
            catalog.enum_catalog(),
            catalog.composite_catalog(),
        ),
        Err(AcceptedCheckExprV1Error::MembershipTooWide)
    );
}

#[test]
fn local_validation_defers_composite_meaning_but_exact_validation_rejects_non_newtypes() {
    let mut fields = snapshot().fields().to_vec();
    let type_id = CompositeTypeId::new(1).expect("test composite type ID should be non-zero");
    fields.push(field(
        6,
        5,
        "details",
        AcceptedFieldKind::Composite { type_id },
        true,
        LeafCodec::Structural,
    ));
    let expression = AcceptedCheckExprV1::IsNull(AcceptedCheckValueExprV1::Field(FieldId::new(6)));

    assert!(
        expression
            .validate_snapshot_local(fields.as_slice())
            .is_ok()
    );
    let enum_catalog =
        build_initial_accepted_enum_catalog(&[]).expect("empty enum catalog should build");
    let composite_catalog = AcceptedCompositeCatalog::from_initial_definitions(
        BTreeMap::from([(
            type_id,
            (
                "tests::Details".to_string(),
                AcceptedCompositeShape::Tuple(vec![AcceptedCompositeElement::new(
                    AcceptedFieldKind::Nat64,
                    false,
                )]),
            ),
        )]),
        &enum_catalog,
    )
    .expect("tuple composite fixture should build");
    let snapshot = PersistedSchemaSnapshot::new(
        SchemaVersion::initial(),
        "tests::CheckedEntity".to_string(),
        "CheckedEntity".to_string(),
        FieldId::new(1),
        SchemaRowLayout::initial(
            fields
                .iter()
                .map(|field| (field.id(), field.slot()))
                .collect(),
        ),
        fields,
    );
    assert_eq!(
        expression.validate(&snapshot, &composite_catalog),
        Err(AcceptedCheckExprV1Error::UnsupportedFieldKind)
    );
}

#[test]
#[expect(
    clippy::too_many_lines,
    reason = "one compiled-program fixture proves numeric, decimal, and length nominal-newtype semantics together"
)]
fn accepted_checks_resolve_nominal_newtype_values_through_catalog_authority() {
    let type_id = CompositeTypeId::new(1).expect("test composite type ID should be non-zero");
    let label_type_id = CompositeTypeId::new(2).expect("test composite type ID should be non-zero");
    let amount_type_id =
        CompositeTypeId::new(3).expect("test composite type ID should be non-zero");
    let enum_catalog =
        build_initial_accepted_enum_catalog(&[]).expect("empty enum catalog should build");
    let composite_catalog = AcceptedCompositeCatalog::from_initial_definitions(
        BTreeMap::from([
            (
                type_id,
                (
                    "tests::Degrees".to_string(),
                    AcceptedCompositeShape::Newtype(AcceptedCompositeElement::new(
                        AcceptedFieldKind::Nat16,
                        false,
                    )),
                ),
            ),
            (
                label_type_id,
                (
                    "tests::Label".to_string(),
                    AcceptedCompositeShape::Newtype(AcceptedCompositeElement::new(
                        AcceptedFieldKind::Text { max_len: None },
                        false,
                    )),
                ),
            ),
            (
                amount_type_id,
                (
                    "tests::Amount".to_string(),
                    AcceptedCompositeShape::Newtype(AcceptedCompositeElement::new(
                        AcceptedFieldKind::Decimal { scale: 8 },
                        false,
                    )),
                ),
            ),
        ]),
        &enum_catalog,
    )
    .expect("newtype composite fixture should build");
    let fields = vec![
        field(
            1,
            0,
            "id",
            AcceptedFieldKind::Ulid,
            false,
            LeafCodec::Scalar(ScalarCodec::Ulid),
        ),
        field(
            2,
            1,
            "degrees",
            AcceptedFieldKind::Composite { type_id },
            false,
            LeafCodec::Structural,
        ),
        field(
            3,
            2,
            "label",
            AcceptedFieldKind::Composite {
                type_id: label_type_id,
            },
            false,
            LeafCodec::Structural,
        ),
        field(
            4,
            3,
            "amount",
            AcceptedFieldKind::Composite {
                type_id: amount_type_id,
            },
            false,
            LeafCodec::Structural,
        ),
    ];
    let snapshot = PersistedSchemaSnapshot::new(
        SchemaVersion::initial(),
        "tests::Compass".to_string(),
        "Compass".to_string(),
        FieldId::new(1),
        SchemaRowLayout::initial(
            fields
                .iter()
                .map(|field| (field.id(), field.slot()))
                .collect(),
        ),
        fields,
    );
    let expression = bind_check_expr_v1(
        CheckExprV1Input::And(vec![
            CheckExprV1Input::Compare {
                left: CheckValueExprV1Input::Field("degrees".to_string()),
                op: AcceptedCheckCompareOpV1::Lte,
                right: CheckValueExprV1Input::Literal(InputValue::Nat64(360)),
            },
            CheckExprV1Input::Compare {
                left: CheckValueExprV1Input::CharLength("label".to_string()),
                op: AcceptedCheckCompareOpV1::Gte,
                right: CheckValueExprV1Input::Literal(InputValue::Nat64(2)),
            },
            CheckExprV1Input::Compare {
                left: CheckValueExprV1Input::Field("amount".to_string()),
                op: AcceptedCheckCompareOpV1::Gte,
                right: CheckValueExprV1Input::Literal(InputValue::Decimal(
                    Decimal::from_i128_with_scale(0, 8),
                )),
            },
        ]),
        &snapshot,
        &enum_catalog,
        &composite_catalog,
    )
    .expect("newtype scalar check should bind through accepted catalog authority");
    let catalog = snapshot
        .constraint_catalog()
        .clone()
        .with_added_check(
            "degrees_range".to_string(),
            ConstraintOrigin::Generated,
            expression,
        )
        .expect("newtype check constraint should allocate");
    let accepted = AcceptedSchemaSnapshot::try_new(snapshot.with_constraint_catalog(catalog))
        .expect("catalog-bound newtype check schema should be structurally accepted");
    let value_catalog = AcceptedValueCatalogHandle::new_for_tests(
        enum_catalog,
        composite_catalog,
        AcceptedSchemaRevision::INITIAL,
    );
    let program = CompiledAcceptedRowConstraints::compile(&accepted, &value_catalog, FINGERPRINT)
        .expect("newtype check should compile once through accepted authority");

    program
        .evaluate(
            FINGERPRINT,
            &[
                None,
                Some(Value::Nat64(360)),
                Some(Value::Text("ok".to_string())),
                Some(Value::Decimal(Decimal::from_i128_with_scale(1, 8))),
            ],
        )
        .expect("inclusive newtype bound should pass");
    assert!(matches!(
        program.evaluate(
            FINGERPRINT,
            &[
                None,
                Some(Value::Nat64(361)),
                Some(Value::Text("ok".to_string())),
                Some(Value::Decimal(Decimal::from_i128_with_scale(1, 8))),
            ],
        ),
        Err(AcceptedRowConstraintEvaluationError::Violation { .. })
    ));
    assert!(matches!(
        program.evaluate(
            FINGERPRINT,
            &[
                None,
                Some(Value::Nat64(360)),
                Some(Value::Text("x".to_string())),
                Some(Value::Decimal(Decimal::from_i128_with_scale(1, 8))),
            ],
        ),
        Err(AcceptedRowConstraintEvaluationError::Violation { .. })
    ));
    assert!(matches!(
        program.evaluate(
            FINGERPRINT,
            &[
                None,
                Some(Value::Nat64(360)),
                Some(Value::Text("ok".to_string())),
                Some(Value::Decimal(Decimal::from_i128_with_scale(-1, 8))),
            ],
        ),
        Err(AcceptedRowConstraintEvaluationError::Violation { .. })
    ));
}