icydb-core 0.147.22

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
//! Module: db::schema::runtime
//! Responsibility: accepted-schema runtime row-layout descriptors.
//! Does not own: raw row decoding, write execution, or transition policy.
//! Boundary: turns accepted metadata into explicit decode/write layout facts.

use crate::{
    db::schema::{
        AcceptedSchemaSnapshot, FieldId, PersistedFieldKind, PersistedNestedLeafSnapshot,
        SchemaFieldDefault, SchemaFieldSlot, SchemaFieldWritePolicy, SchemaVersion,
    },
    error::InternalError,
    model::{
        entity::EntityModel,
        field::{FieldModel, FieldStorageDecode, LeafCodec},
    },
};

///
/// AcceptedFieldAbsencePolicy
///
/// AcceptedFieldAbsencePolicy describes how runtime row materialization should
/// treat a missing physical payload slot for one accepted field. It exists so
/// future additive-field support has an explicit schema-owned contract instead
/// of asking row decode code to infer missing-field behavior from nullable
/// flags or Rust defaults.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) enum AcceptedFieldAbsencePolicy {
    NullIfMissing,
    Required,
}

///
/// AcceptedRowLayoutRuntimeField
///
/// AcceptedRowLayoutRuntimeField is the per-field fact bundle consumed by
/// runtime decode/write boundaries. It borrows persisted schema metadata while
/// freezing the physical slot from `SchemaRowLayout`, which is the accepted
/// row-layout authority.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) struct AcceptedRowLayoutRuntimeField<'a> {
    field_id: FieldId,
    name: &'a str,
    slot: SchemaFieldSlot,
    kind: &'a PersistedFieldKind,
    nested_leaves: &'a [PersistedNestedLeafSnapshot],
    nullable: bool,
    default: SchemaFieldDefault,
    write_policy: SchemaFieldWritePolicy,
    storage_decode: FieldStorageDecode,
    leaf_codec: LeafCodec,
    absence_policy: AcceptedFieldAbsencePolicy,
}

impl<'a> AcceptedRowLayoutRuntimeField<'a> {
    /// Return the durable accepted field identity.
    #[must_use]
    pub(in crate::db) const fn field_id(&self) -> FieldId {
        self.field_id
    }

    /// Borrow the accepted persisted field name.
    #[must_use]
    pub(in crate::db) const fn name(&self) -> &'a str {
        self.name
    }

    /// Return the accepted physical row slot for this field.
    #[must_use]
    pub(in crate::db) const fn slot(&self) -> SchemaFieldSlot {
        self.slot
    }

    /// Borrow the accepted persisted field kind.
    #[must_use]
    pub(in crate::db) const fn kind(&self) -> &'a PersistedFieldKind {
        self.kind
    }

    /// Borrow accepted nested leaf metadata rooted at this field.
    #[allow(
        dead_code,
        reason = "nested leaf facts are part of the accepted runtime boundary before row decode consumes them directly"
    )]
    #[must_use]
    pub(in crate::db) const fn nested_leaves(&self) -> &'a [PersistedNestedLeafSnapshot] {
        self.nested_leaves
    }

    /// Return whether this field permits explicit persisted `NULL`.
    #[allow(
        dead_code,
        reason = "missing-slot nullability is part of the accepted runtime boundary before additive decode support"
    )]
    #[must_use]
    pub(in crate::db) const fn nullable(&self) -> bool {
        self.nullable
    }

    /// Return the accepted database-level default contract.
    #[allow(
        dead_code,
        reason = "database defaults are part of the accepted runtime boundary before additive write support"
    )]
    #[must_use]
    pub(in crate::db) const fn default(&self) -> SchemaFieldDefault {
        self.default
    }

    /// Return the accepted database-level write policy for this field.
    #[must_use]
    pub(in crate::db) const fn write_policy(&self) -> SchemaFieldWritePolicy {
        self.write_policy
    }

    /// Return the accepted missing-slot policy for this field.
    #[must_use]
    pub(in crate::db) const fn absence_policy(&self) -> AcceptedFieldAbsencePolicy {
        self.absence_policy
    }

    /// Return the accepted field-level payload decode contract.
    #[must_use]
    pub(in crate::db) const fn decode_contract(&self) -> AcceptedFieldDecodeContract<'a> {
        AcceptedFieldDecodeContract {
            field_name: self.name,
            kind: self.kind,
            nullable: self.nullable,
            storage_decode: self.storage_decode,
            leaf_codec: self.leaf_codec,
        }
    }
}

///
/// AcceptedFieldDecodeContract
///
/// AcceptedFieldDecodeContract is the field-level decode shape accepted schema
/// exposes to generated-compatible row-layout checks. It exists so the bridge
/// compares one named contract instead of reopening individual field facts in
/// executor or data decode code.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) struct AcceptedFieldDecodeContract<'a> {
    field_name: &'a str,
    kind: &'a PersistedFieldKind,
    nullable: bool,
    storage_decode: FieldStorageDecode,
    leaf_codec: LeafCodec,
}

impl<'a> AcceptedFieldDecodeContract<'a> {
    /// Borrow the accepted field name that owns this decode contract.
    #[must_use]
    pub(in crate::db) const fn field_name(&self) -> &'a str {
        self.field_name
    }

    /// Borrow the accepted persisted field kind for decode.
    #[must_use]
    pub(in crate::db) const fn kind(&self) -> &'a PersistedFieldKind {
        self.kind
    }

    /// Return whether this accepted field permits explicit persisted `NULL`.
    #[must_use]
    pub(in crate::db) const fn nullable(&self) -> bool {
        self.nullable
    }

    /// Return the accepted storage decode lane.
    #[must_use]
    pub(in crate::db) const fn storage_decode(&self) -> FieldStorageDecode {
        self.storage_decode
    }

    /// Return the accepted scalar/structural leaf codec.
    #[must_use]
    pub(in crate::db) const fn leaf_codec(&self) -> LeafCodec {
        self.leaf_codec
    }
}

///
/// AcceptedGeneratedCompatibleRowShape
///
/// AcceptedGeneratedCompatibleRowShape is the schema-runtime proof that one
/// accepted row layout can still be decoded by generated field codecs.
/// Row decode consumes this small shape instead of recombining descriptor
/// fields after compatibility validation has already succeeded.
///

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::db) struct AcceptedGeneratedCompatibleRowShape {
    required_slot_count: usize,
    primary_key_slot_index: usize,
}

impl AcceptedGeneratedCompatibleRowShape {
    /// Return the accepted physical slot count proven generated-compatible.
    #[must_use]
    pub(in crate::db) const fn required_slot_count(self) -> usize {
        self.required_slot_count
    }

    /// Return the accepted primary-key physical slot proven generated-compatible.
    #[must_use]
    pub(in crate::db) const fn primary_key_slot_index(self) -> usize {
        self.primary_key_slot_index
    }
}

///
/// AcceptedRowLayoutRuntimeDescriptor
///
/// AcceptedRowLayoutRuntimeDescriptor is the schema-owned runtime contract for
/// one accepted row layout. It is intentionally read-only and closed: decode
/// and write code can consume its field facts, but cannot reinterpret raw
/// persisted snapshots or generated model fields to decide slot behavior.
///

#[derive(Debug, Eq, PartialEq)]
pub(in crate::db) struct AcceptedRowLayoutRuntimeDescriptor<'a> {
    version: SchemaVersion,
    required_slot_count: usize,
    primary_key_name: &'a str,
    primary_key_kind: &'a PersistedFieldKind,
    primary_key_slot_index: usize,
    fields: Vec<AcceptedRowLayoutRuntimeField<'a>>,
}

impl<'a> AcceptedRowLayoutRuntimeDescriptor<'a> {
    /// Build one runtime descriptor from an already accepted schema snapshot.
    ///
    /// The constructor still validates local row-layout completeness because
    /// this descriptor will become a trust boundary for decode/write code. A
    /// missing row-layout slot is reported as an internal invariant violation
    /// rather than hidden behind a partial descriptor.
    pub(in crate::db) fn from_accepted_schema(
        accepted: &'a AcceptedSchemaSnapshot,
    ) -> Result<Self, InternalError> {
        let snapshot = accepted.persisted_snapshot();
        let row_layout = snapshot.row_layout();
        let mut required_slot_count = 0usize;
        let mut fields = Vec::with_capacity(snapshot.fields().len());

        // Phase 1: project accepted field metadata through the schema-owned
        // row-layout mapping so duplicated field-slot payloads never become
        // the runtime slot authority.
        for field in snapshot.fields() {
            let Some(slot) = row_layout.slot_for_field(field.id()) else {
                return Err(InternalError::store_invariant(format!(
                    "accepted row layout runtime descriptor missing slot for field_id={}",
                    field.id().get(),
                )));
            };
            let slot_end = usize::from(slot.get()).saturating_add(1);
            required_slot_count = required_slot_count.max(slot_end);

            fields.push(AcceptedRowLayoutRuntimeField {
                field_id: field.id(),
                name: field.name(),
                slot,
                kind: field.kind(),
                nested_leaves: field.nested_leaves(),
                nullable: field.nullable(),
                default: field.default(),
                write_policy: field.write_policy(),
                storage_decode: field.storage_decode(),
                leaf_codec: field.leaf_codec(),
                absence_policy: accepted_field_absence_policy(field.nullable(), field.default()),
            });
        }
        let Some(primary_key_field) = fields
            .iter()
            .find(|field| field.field_id() == snapshot.primary_key_field_id())
        else {
            return Err(InternalError::store_invariant(format!(
                "accepted row layout runtime descriptor missing primary-key field_id={}",
                snapshot.primary_key_field_id().get(),
            )));
        };
        let primary_key_name = primary_key_field.name();
        let primary_key_kind = primary_key_field.kind();
        let primary_key_slot_index = usize::from(primary_key_field.slot().get());

        Ok(Self {
            version: row_layout.version(),
            required_slot_count,
            primary_key_name,
            primary_key_kind,
            primary_key_slot_index,
            fields,
        })
    }

    /// Return the accepted schema version backing this runtime layout.
    #[allow(
        dead_code,
        reason = "schema-version reads are reserved for accepted transition plans beyond exact-match"
    )]
    #[must_use]
    pub(in crate::db) const fn version(&self) -> SchemaVersion {
        self.version
    }

    /// Return the minimum physical slot count required by this layout.
    #[must_use]
    pub(in crate::db) const fn required_slot_count(&self) -> usize {
        self.required_slot_count
    }

    /// Borrow the accepted primary-key field name carried by this layout.
    #[must_use]
    pub(in crate::db) const fn primary_key_name(&self) -> &'a str {
        self.primary_key_name
    }

    /// Borrow the accepted primary-key persisted field kind.
    #[must_use]
    pub(in crate::db) const fn primary_key_kind(&self) -> &'a PersistedFieldKind {
        self.primary_key_kind
    }

    /// Return the accepted primary-key physical slot index.
    #[must_use]
    pub(in crate::db) const fn primary_key_slot_index(&self) -> usize {
        self.primary_key_slot_index
    }

    /// Borrow runtime field facts in accepted snapshot field order.
    #[must_use]
    pub(in crate::db) const fn fields(&self) -> &[AcceptedRowLayoutRuntimeField<'a>] {
        self.fields.as_slice()
    }

    /// Borrow one runtime field by accepted physical row slot.
    #[allow(
        dead_code,
        reason = "slot-indexed accepted field lookup becomes live when decode consumes accepted field contracts directly"
    )]
    #[must_use]
    pub(in crate::db) fn field_for_slot(
        &self,
        slot: SchemaFieldSlot,
    ) -> Option<&AcceptedRowLayoutRuntimeField<'a>> {
        self.fields.iter().find(|field| field.slot() == slot)
    }

    /// Borrow one runtime field by accepted physical row slot index.
    #[must_use]
    pub(in crate::db) fn field_for_slot_index(
        &self,
        slot: usize,
    ) -> Option<&AcceptedRowLayoutRuntimeField<'a>> {
        self.fields
            .iter()
            .find(|field| usize::from(field.slot().get()) == slot)
    }

    /// Borrow one runtime field by durable accepted field identity.
    #[allow(
        dead_code,
        reason = "field-id accepted lookup becomes live when migration plans remap durable field identities"
    )]
    #[must_use]
    pub(in crate::db) fn field_for_id(
        &self,
        field_id: FieldId,
    ) -> Option<&AcceptedRowLayoutRuntimeField<'a>> {
        self.fields
            .iter()
            .find(|field| field.field_id() == field_id)
    }

    /// Borrow one runtime field by accepted persisted field name.
    #[must_use]
    pub(in crate::db) fn field_by_name(
        &self,
        name: &str,
    ) -> Option<&AcceptedRowLayoutRuntimeField<'a>> {
        self.fields.iter().find(|field| field.name() == name)
    }

    /// Return one runtime field's accepted physical slot index by name.
    #[must_use]
    pub(in crate::db) fn field_slot_index_by_name(&self, name: &str) -> Option<usize> {
        self.field_by_name(name)
            .map(|field| usize::from(field.slot().get()))
    }

    /// Borrow one runtime field's accepted persisted kind by name.
    #[must_use]
    pub(in crate::db) fn field_kind_by_name(&self, name: &str) -> Option<&PersistedFieldKind> {
        self.field_by_name(name)
            .map(AcceptedRowLayoutRuntimeField::kind)
    }

    /// Return the row shape when this accepted layout can still use generated field codecs.
    ///
    /// The row decoder remains generated-codec backed until accepted-field
    /// decoders exist. Keeping this bridge check and shape projection in the
    /// descriptor owner makes generated compatibility a schema-runtime contract
    /// instead of an executor side calculation.
    pub(in crate::db) fn generated_compatible_row_shape_for_model(
        &self,
        model: &'static EntityModel,
    ) -> Result<AcceptedGeneratedCompatibleRowShape, InternalError> {
        // Phase 1: require primary-key identity and the accepted row shape to
        // match the generated decoder contract.
        if self.primary_key_name() != model.primary_key.name {
            return Err(InternalError::store_invariant(format!(
                "accepted row layout primary key is not generated-compatible: accepted_primary_key='{}' generated_primary_key='{}'",
                self.primary_key_name(),
                model.primary_key.name,
            )));
        }

        // Phase 2: require the accepted row shape to have the same dense slot
        // count the generated decoder expects.
        if self.required_slot_count() != model.fields().len() {
            return Err(InternalError::store_invariant(format!(
                "accepted row layout field count is not generated-compatible: accepted={} generated={}",
                self.required_slot_count(),
                model.fields().len(),
            )));
        }

        // Phase 3: compare every generated field against the accepted
        // descriptor fact used by runtime decode before executor code can
        // consume the descriptor.
        for (generated_slot, field) in model.fields().iter().enumerate() {
            let Some(accepted_field) = self.field_by_name(field.name()) else {
                return Err(InternalError::store_invariant(format!(
                    "accepted row layout missing generated field '{}'",
                    field.name(),
                )));
            };
            let accepted_slot = usize::from(accepted_field.slot().get());
            if accepted_slot != generated_slot {
                return Err(InternalError::store_invariant(format!(
                    "accepted row layout slot is not generated-compatible: field='{}' accepted_slot={} generated_slot={}",
                    field.name(),
                    accepted_slot,
                    generated_slot,
                )));
            }

            ensure_generated_field_decode_contract_compatible(accepted_field, field)?;
        }

        Ok(AcceptedGeneratedCompatibleRowShape {
            required_slot_count: self.required_slot_count(),
            primary_key_slot_index: self.primary_key_slot_index(),
        })
    }
}

// Prove that one accepted field still has the exact decode contract expected by
// its generated field codec. This is the field-level bridge that lets exact
// schemas keep using generated decoders while additive/remapped layouts remain
// rejected until accepted-field decoders exist.
fn ensure_generated_field_decode_contract_compatible(
    accepted_field: &AcceptedRowLayoutRuntimeField<'_>,
    generated_field: &FieldModel,
) -> Result<(), InternalError> {
    let accepted_contract = accepted_field.decode_contract();
    let generated_kind = PersistedFieldKind::from_model_kind(generated_field.kind());
    if accepted_contract.kind() != &generated_kind {
        return Err(InternalError::store_invariant(format!(
            "accepted row layout kind is not generated-compatible: field='{}' accepted_kind={:?} generated_kind={:?}",
            accepted_contract.field_name(),
            accepted_contract.kind(),
            generated_kind,
        )));
    }

    if accepted_contract.nullable() != generated_field.nullable() {
        return Err(InternalError::store_invariant(format!(
            "accepted row layout nullability is not generated-compatible: field='{}' accepted_nullable={} generated_nullable={}",
            accepted_contract.field_name(),
            accepted_contract.nullable(),
            generated_field.nullable(),
        )));
    }

    if accepted_contract.storage_decode() != generated_field.storage_decode() {
        return Err(InternalError::store_invariant(format!(
            "accepted row layout storage decode is not generated-compatible: field='{}' accepted_storage_decode={:?} generated_storage_decode={:?}",
            accepted_contract.field_name(),
            accepted_contract.storage_decode(),
            generated_field.storage_decode(),
        )));
    }

    if accepted_contract.leaf_codec() != generated_field.leaf_codec() {
        return Err(InternalError::store_invariant(format!(
            "accepted row layout leaf codec is not generated-compatible: field='{}' accepted_leaf_codec={:?} generated_leaf_codec={:?}",
            accepted_contract.field_name(),
            accepted_contract.leaf_codec(),
            generated_field.leaf_codec(),
        )));
    }

    Ok(())
}

// Decide the missing-slot behavior from accepted database metadata only. Rust
// struct defaults are deliberately absent from this calculation.
const fn accepted_field_absence_policy(
    nullable: bool,
    default: SchemaFieldDefault,
) -> AcceptedFieldAbsencePolicy {
    match (nullable, default) {
        (true, SchemaFieldDefault::None) => AcceptedFieldAbsencePolicy::NullIfMissing,
        (false, SchemaFieldDefault::None) => AcceptedFieldAbsencePolicy::Required,
    }
}

///
/// TESTS
///

#[cfg(test)]
mod tests {
    use crate::{
        db::schema::{
            AcceptedSchemaSnapshot, FieldId, PersistedFieldKind, PersistedFieldSnapshot,
            PersistedSchemaSnapshot, SchemaFieldDefault, SchemaFieldSlot, SchemaFieldWritePolicy,
            SchemaRowLayout, SchemaVersion,
            runtime::{
                AcceptedFieldAbsencePolicy, AcceptedRowLayoutRuntimeDescriptor,
                AcceptedRowLayoutRuntimeField,
            },
        },
        model::{
            entity::EntityModel,
            field::{
                FieldInsertGeneration, FieldKind, FieldModel, FieldStorageDecode,
                FieldWriteManagement, LeafCodec, ScalarCodec,
            },
            index::IndexModel,
        },
        testing::entity_model_from_static,
    };

    static RUNTIME_ENTITY_FIELDS: [FieldModel; 2] = [
        FieldModel::generated("id", FieldKind::Ulid),
        FieldModel::generated("nickname", FieldKind::Text { max_len: Some(32) }),
    ];
    static RUNTIME_ENTITY_INDEXES: [&IndexModel; 0] = [];
    static RUNTIME_ENTITY_MODEL: EntityModel = entity_model_from_static(
        "schema::tests::RuntimeEntity",
        "RuntimeEntity",
        &RUNTIME_ENTITY_FIELDS[0],
        0,
        &RUNTIME_ENTITY_FIELDS,
        &RUNTIME_ENTITY_INDEXES,
    );

    static WRITE_POLICY_ENTITY_FIELDS: [FieldModel; 3] = [
        FieldModel::generated("id", FieldKind::Ulid),
        FieldModel::generated_with_storage_decode_nullability_and_write_policies(
            "token",
            FieldKind::Ulid,
            FieldStorageDecode::ByKind,
            false,
            Some(FieldInsertGeneration::Ulid),
            None,
        ),
        FieldModel::generated_with_storage_decode_nullability_and_write_policies(
            "updated_at",
            FieldKind::Timestamp,
            FieldStorageDecode::ByKind,
            false,
            None,
            Some(FieldWriteManagement::UpdatedAt),
        ),
    ];
    static WRITE_POLICY_ENTITY_INDEXES: [&IndexModel; 0] = [];
    static WRITE_POLICY_ENTITY_MODEL: EntityModel = entity_model_from_static(
        "schema::tests::WritePolicyEntity",
        "WritePolicyEntity",
        &WRITE_POLICY_ENTITY_FIELDS[0],
        0,
        &WRITE_POLICY_ENTITY_FIELDS,
        &WRITE_POLICY_ENTITY_INDEXES,
    );

    fn accepted_schema_fixture() -> AcceptedSchemaSnapshot {
        AcceptedSchemaSnapshot::new(PersistedSchemaSnapshot::new(
            SchemaVersion::initial(),
            "schema::tests::RuntimeEntity".to_string(),
            "RuntimeEntity".to_string(),
            FieldId::new(1),
            SchemaRowLayout::new(
                SchemaVersion::initial(),
                vec![
                    (FieldId::new(1), SchemaFieldSlot::new(0)),
                    (FieldId::new(2), SchemaFieldSlot::new(9)),
                ],
            ),
            vec![
                PersistedFieldSnapshot::new(
                    FieldId::new(1),
                    "id".to_string(),
                    SchemaFieldSlot::new(0),
                    PersistedFieldKind::Ulid,
                    Vec::new(),
                    false,
                    SchemaFieldDefault::None,
                    FieldStorageDecode::ByKind,
                    LeafCodec::Scalar(ScalarCodec::Ulid),
                ),
                PersistedFieldSnapshot::new(
                    FieldId::new(2),
                    "nickname".to_string(),
                    SchemaFieldSlot::new(1),
                    PersistedFieldKind::Text { max_len: Some(32) },
                    Vec::new(),
                    true,
                    SchemaFieldDefault::None,
                    FieldStorageDecode::ByKind,
                    LeafCodec::Scalar(ScalarCodec::Text),
                ),
            ],
        ))
    }

    fn generated_compatible_accepted_schema_fixture() -> AcceptedSchemaSnapshot {
        AcceptedSchemaSnapshot::new(PersistedSchemaSnapshot::new(
            SchemaVersion::initial(),
            "schema::tests::RuntimeEntity".to_string(),
            "RuntimeEntity".to_string(),
            FieldId::new(1),
            SchemaRowLayout::new(
                SchemaVersion::initial(),
                vec![
                    (FieldId::new(1), SchemaFieldSlot::new(0)),
                    (FieldId::new(2), SchemaFieldSlot::new(1)),
                ],
            ),
            vec![
                PersistedFieldSnapshot::new(
                    FieldId::new(1),
                    "id".to_string(),
                    SchemaFieldSlot::new(0),
                    PersistedFieldKind::Ulid,
                    Vec::new(),
                    false,
                    SchemaFieldDefault::None,
                    FieldStorageDecode::ByKind,
                    LeafCodec::Scalar(ScalarCodec::Ulid),
                ),
                PersistedFieldSnapshot::new(
                    FieldId::new(2),
                    "nickname".to_string(),
                    SchemaFieldSlot::new(1),
                    PersistedFieldKind::Text { max_len: Some(32) },
                    Vec::new(),
                    false,
                    SchemaFieldDefault::None,
                    FieldStorageDecode::ByKind,
                    LeafCodec::Scalar(ScalarCodec::Text),
                ),
            ],
        ))
    }

    fn generated_slot_compatible_accepted_schema_with_nickname_decode(
        nullable: bool,
        storage_decode: FieldStorageDecode,
        leaf_codec: LeafCodec,
    ) -> AcceptedSchemaSnapshot {
        AcceptedSchemaSnapshot::new(PersistedSchemaSnapshot::new(
            SchemaVersion::initial(),
            "schema::tests::RuntimeEntity".to_string(),
            "RuntimeEntity".to_string(),
            FieldId::new(1),
            SchemaRowLayout::new(
                SchemaVersion::initial(),
                vec![
                    (FieldId::new(1), SchemaFieldSlot::new(0)),
                    (FieldId::new(2), SchemaFieldSlot::new(1)),
                ],
            ),
            vec![
                PersistedFieldSnapshot::new(
                    FieldId::new(1),
                    "id".to_string(),
                    SchemaFieldSlot::new(0),
                    PersistedFieldKind::Ulid,
                    Vec::new(),
                    false,
                    SchemaFieldDefault::None,
                    FieldStorageDecode::ByKind,
                    LeafCodec::Scalar(ScalarCodec::Ulid),
                ),
                PersistedFieldSnapshot::new(
                    FieldId::new(2),
                    "nickname".to_string(),
                    SchemaFieldSlot::new(1),
                    PersistedFieldKind::Text { max_len: Some(32) },
                    Vec::new(),
                    nullable,
                    SchemaFieldDefault::None,
                    storage_decode,
                    leaf_codec,
                ),
            ],
        ))
    }

    fn write_policy_accepted_schema_fixture() -> AcceptedSchemaSnapshot {
        AcceptedSchemaSnapshot::new(PersistedSchemaSnapshot::new(
            SchemaVersion::initial(),
            "schema::tests::WritePolicyEntity".to_string(),
            "WritePolicyEntity".to_string(),
            FieldId::new(1),
            SchemaRowLayout::new(
                SchemaVersion::initial(),
                vec![
                    (FieldId::new(1), SchemaFieldSlot::new(0)),
                    (FieldId::new(2), SchemaFieldSlot::new(1)),
                    (FieldId::new(3), SchemaFieldSlot::new(2)),
                ],
            ),
            vec![
                PersistedFieldSnapshot::new(
                    FieldId::new(1),
                    "id".to_string(),
                    SchemaFieldSlot::new(0),
                    PersistedFieldKind::Ulid,
                    Vec::new(),
                    false,
                    SchemaFieldDefault::None,
                    FieldStorageDecode::ByKind,
                    LeafCodec::Scalar(ScalarCodec::Ulid),
                ),
                PersistedFieldSnapshot::new_with_write_policy(
                    FieldId::new(2),
                    "token".to_string(),
                    SchemaFieldSlot::new(1),
                    PersistedFieldKind::Ulid,
                    Vec::new(),
                    false,
                    SchemaFieldDefault::None,
                    SchemaFieldWritePolicy::from_model_policies(
                        Some(FieldInsertGeneration::Ulid),
                        None,
                    ),
                    FieldStorageDecode::ByKind,
                    LeafCodec::Scalar(ScalarCodec::Ulid),
                ),
                PersistedFieldSnapshot::new_with_write_policy(
                    FieldId::new(3),
                    "updated_at".to_string(),
                    SchemaFieldSlot::new(2),
                    PersistedFieldKind::Timestamp,
                    Vec::new(),
                    false,
                    SchemaFieldDefault::None,
                    SchemaFieldWritePolicy::from_model_policies(
                        None,
                        Some(FieldWriteManagement::UpdatedAt),
                    ),
                    FieldStorageDecode::ByKind,
                    LeafCodec::Scalar(ScalarCodec::Timestamp),
                ),
            ],
        ))
    }

    #[test]
    fn accepted_row_layout_runtime_descriptor_uses_row_layout_slot_authority() {
        let accepted = accepted_schema_fixture();
        let descriptor = AcceptedRowLayoutRuntimeDescriptor::from_accepted_schema(&accepted)
            .expect("accepted runtime descriptor should build");

        assert_eq!(descriptor.version(), SchemaVersion::initial());
        assert_eq!(descriptor.required_slot_count(), 10);
        assert_eq!(descriptor.primary_key_name(), "id");
        assert_eq!(descriptor.primary_key_slot_index(), 0);
        assert_eq!(descriptor.fields().len(), 2);

        let nickname = descriptor
            .fields()
            .iter()
            .find(|field| field.name() == "nickname")
            .expect("nickname field should be present");
        assert_eq!(nickname.field_id(), FieldId::new(2));
        assert_eq!(nickname.slot(), SchemaFieldSlot::new(9));
        assert_eq!(
            nickname.absence_policy(),
            AcceptedFieldAbsencePolicy::NullIfMissing
        );
        assert_eq!(nickname.default(), SchemaFieldDefault::None);
        let nickname_decode_contract = nickname.decode_contract();
        assert!(nickname_decode_contract.nullable());
        assert_eq!(
            nickname_decode_contract.storage_decode(),
            FieldStorageDecode::ByKind,
        );
        assert_eq!(
            nickname_decode_contract.leaf_codec(),
            LeafCodec::Scalar(ScalarCodec::Text),
        );
        assert!(matches!(
            nickname.kind(),
            PersistedFieldKind::Text { max_len: Some(32) },
        ));
        assert_eq!(
            descriptor
                .field_for_slot(SchemaFieldSlot::new(9))
                .expect("nickname should be indexed by accepted slot")
                .name(),
            "nickname",
        );
        assert_eq!(
            descriptor
                .field_for_id(FieldId::new(2))
                .expect("nickname should be indexed by durable field ID")
                .slot(),
            SchemaFieldSlot::new(9),
        );
        assert_eq!(
            descriptor
                .field_by_name("nickname")
                .expect("nickname should be indexed by persisted field name")
                .field_id(),
            FieldId::new(2),
        );
        assert_eq!(descriptor.field_slot_index_by_name("nickname"), Some(9));
        assert!(matches!(
            descriptor.field_kind_by_name("nickname"),
            Some(PersistedFieldKind::Text { max_len: Some(32) }),
        ));
        assert!(nickname.nested_leaves().is_empty());
        assert!(nickname.nullable());
    }

    #[test]
    fn accepted_row_layout_runtime_descriptor_projects_generated_compatible_shape() {
        let accepted = generated_compatible_accepted_schema_fixture();
        let descriptor = AcceptedRowLayoutRuntimeDescriptor::from_accepted_schema(&accepted)
            .expect("generated-compatible schema should build descriptor");

        let shape = descriptor
            .generated_compatible_row_shape_for_model(&RUNTIME_ENTITY_MODEL)
            .expect("matching generated model should produce row shape proof");

        assert_eq!(shape.required_slot_count(), 2);
        assert_eq!(shape.primary_key_slot_index(), 0);
    }

    #[test]
    fn accepted_row_layout_runtime_descriptor_builds_descriptor_and_row_shape_proof() {
        let accepted = generated_compatible_accepted_schema_fixture();
        let descriptor = AcceptedRowLayoutRuntimeDescriptor::from_accepted_schema(&accepted)
            .expect("accepted schema should build descriptor");
        let shape = descriptor
            .generated_compatible_row_shape_for_model(&RUNTIME_ENTITY_MODEL)
            .expect("generated-compatible schema should build row shape proof");

        assert_eq!(descriptor.required_slot_count(), 2);
        assert_eq!(descriptor.primary_key_slot_index(), 0);
        assert_eq!(descriptor.primary_key_name(), "id");
        assert_eq!(descriptor.primary_key_kind(), &PersistedFieldKind::Ulid);
        assert_eq!(shape.required_slot_count(), 2);
        assert_eq!(shape.primary_key_slot_index(), 0);
        assert_eq!(
            descriptor.field_slot_index_by_name("nickname"),
            Some(1),
            "checked descriptor should retain accepted field lookup facts",
        );
        assert_eq!(
            descriptor
                .field_for_slot_index(1)
                .map(AcceptedRowLayoutRuntimeField::name),
            Some("nickname"),
            "checked descriptor should resolve accepted physical slots by index",
        );
        let nickname_field = descriptor
            .field_by_name("nickname")
            .expect("nickname should resolve accepted descriptor field");
        assert_eq!(
            nickname_field.write_policy().insert_generation(),
            None,
            "generated-compatible descriptor should project accepted fields to write-policy facts",
        );
    }

    #[test]
    fn accepted_row_layout_runtime_descriptor_projects_persisted_write_policy() {
        let accepted = write_policy_accepted_schema_fixture();
        let descriptor = AcceptedRowLayoutRuntimeDescriptor::from_accepted_schema(&accepted)
            .expect("write-policy accepted schema should build descriptor");
        descriptor
            .generated_compatible_row_shape_for_model(&WRITE_POLICY_ENTITY_MODEL)
            .expect("write-policy schema should remain generated-compatible");

        let token_field = descriptor
            .field_by_name("token")
            .expect("token should resolve accepted descriptor field");
        let token_policy = token_field.write_policy();
        assert_eq!(
            token_policy.insert_generation(),
            Some(FieldInsertGeneration::Ulid)
        );
        assert_eq!(token_policy.write_management(), None);

        let updated_at_field = descriptor
            .field_by_name("updated_at")
            .expect("updated_at should resolve accepted descriptor field");
        let updated_at_policy_from_field = updated_at_field.write_policy();
        assert_eq!(
            updated_at_policy_from_field.write_management(),
            Some(FieldWriteManagement::UpdatedAt),
            "descriptor-owned field projection should avoid name re-resolution",
        );
    }

    #[test]
    fn accepted_row_layout_runtime_descriptor_rejects_non_generated_compatible_shape() {
        let accepted = accepted_schema_fixture();
        let descriptor = AcceptedRowLayoutRuntimeDescriptor::from_accepted_schema(&accepted)
            .expect("slot-expanded accepted schema should build descriptor");

        let err = descriptor
            .generated_compatible_row_shape_for_model(&RUNTIME_ENTITY_MODEL)
            .expect_err("slot-expanded schema must not produce generated-compatible shape proof");

        assert!(
            err.message
                .contains("accepted row layout field count is not generated-compatible"),
            "unexpected generated-compatible shape error: {}",
            err.message,
        );
    }

    #[test]
    fn accepted_row_layout_runtime_descriptor_rejects_storage_decode_drift() {
        let accepted = generated_slot_compatible_accepted_schema_with_nickname_decode(
            false,
            FieldStorageDecode::Value,
            LeafCodec::Scalar(ScalarCodec::Text),
        );
        let descriptor = AcceptedRowLayoutRuntimeDescriptor::from_accepted_schema(&accepted)
            .expect("slot-compatible accepted schema should build descriptor");

        let err = descriptor
            .generated_compatible_row_shape_for_model(&RUNTIME_ENTITY_MODEL)
            .expect_err("storage decode drift must reject generated decoder bridge");

        assert!(
            err.message
                .contains("accepted row layout storage decode is not generated-compatible"),
            "unexpected generated-compatible storage decode error: {}",
            err.message,
        );
    }

    #[test]
    fn accepted_row_layout_runtime_descriptor_rejects_leaf_codec_drift() {
        let accepted = generated_slot_compatible_accepted_schema_with_nickname_decode(
            false,
            FieldStorageDecode::ByKind,
            LeafCodec::Scalar(ScalarCodec::Blob),
        );
        let descriptor = AcceptedRowLayoutRuntimeDescriptor::from_accepted_schema(&accepted)
            .expect("slot-compatible accepted schema should build descriptor");

        let err = descriptor
            .generated_compatible_row_shape_for_model(&RUNTIME_ENTITY_MODEL)
            .expect_err("leaf codec drift must reject generated decoder bridge");

        assert!(
            err.message
                .contains("accepted row layout leaf codec is not generated-compatible"),
            "unexpected generated-compatible leaf codec error: {}",
            err.message,
        );
    }

    #[test]
    fn accepted_row_layout_runtime_descriptor_rejects_nullability_drift() {
        let accepted = generated_slot_compatible_accepted_schema_with_nickname_decode(
            true,
            FieldStorageDecode::ByKind,
            LeafCodec::Scalar(ScalarCodec::Text),
        );
        let descriptor = AcceptedRowLayoutRuntimeDescriptor::from_accepted_schema(&accepted)
            .expect("slot-compatible accepted schema should build descriptor");

        let err = descriptor
            .generated_compatible_row_shape_for_model(&RUNTIME_ENTITY_MODEL)
            .expect_err("nullability drift must reject generated decoder bridge");

        assert!(
            err.message
                .contains("accepted row layout nullability is not generated-compatible"),
            "unexpected generated-compatible nullability error: {}",
            err.message,
        );
    }

    #[test]
    fn accepted_row_layout_runtime_descriptor_rejects_missing_layout_slot() {
        let accepted = AcceptedSchemaSnapshot::new(PersistedSchemaSnapshot::new(
            SchemaVersion::initial(),
            "schema::tests::BrokenEntity".to_string(),
            "BrokenEntity".to_string(),
            FieldId::new(1),
            SchemaRowLayout::new(
                SchemaVersion::initial(),
                vec![(FieldId::new(1), SchemaFieldSlot::new(0))],
            ),
            vec![
                PersistedFieldSnapshot::new(
                    FieldId::new(1),
                    "id".to_string(),
                    SchemaFieldSlot::new(0),
                    PersistedFieldKind::Ulid,
                    Vec::new(),
                    false,
                    SchemaFieldDefault::None,
                    FieldStorageDecode::ByKind,
                    LeafCodec::Scalar(ScalarCodec::Ulid),
                ),
                PersistedFieldSnapshot::new(
                    FieldId::new(2),
                    "nickname".to_string(),
                    SchemaFieldSlot::new(1),
                    PersistedFieldKind::Text { max_len: None },
                    Vec::new(),
                    true,
                    SchemaFieldDefault::None,
                    FieldStorageDecode::ByKind,
                    LeafCodec::Scalar(ScalarCodec::Text),
                ),
            ],
        ));

        let err = AcceptedRowLayoutRuntimeDescriptor::from_accepted_schema(&accepted)
            .expect_err("missing row-layout slot should fail closed");
        assert!(
            err.to_string().contains("missing slot for field_id=2"),
            "unexpected descriptor error: {err}",
        );
    }
}