oxgraph-property 0.2.4

Arrow-backed named property layers for OxGraph topology views.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
//! Core property-layer data model, error type, and shared validation helpers.
//!
//! Holds the domain newtypes/enums, the Arrow-backed layer types, the
//! identity-mode snapshot records, the concrete [`PropertyError`] enum, the
//! snapshot tag codecs for those enums, and the layer-construction validation
//! helpers shared across the crate.

use std::{error::Error, fmt, string::String, sync::Arc, vec::Vec};

use arrow_array::{Array, ArrayRef, PrimitiveArray};
use arrow_schema::Field;
use oxgraph_snapshot::SectionViewError;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

use crate::width::{
    PropertyIndex, PropertySnapshotMetaWord, le_word, le_word_to_u32, le_word_to_usize,
};

/// Stable numeric identifier for one property layer.
///
/// # Performance
///
/// Copying, comparing, ordering, hashing, and debug-formatting are `O(1)`.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct LayerId<Id>(pub Id);

/// Human-facing property layer name.
///
/// # Performance
///
/// Cloning is `O(name.len())`; comparison and display are `O(name.len())`.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct LayerName {
    /// Owned layer name.
    value: String,
}

impl LayerName {
    /// Builds a non-empty layer name.
    ///
    /// # Errors
    ///
    /// Returns [`PropertyError::EmptyLayerName`] when `value` is empty.
    ///
    /// # Performance
    ///
    /// This function is `O(value.len())`.
    pub fn try_new(value: &str) -> Result<Self, PropertyError> {
        if value.is_empty() {
            return Err(PropertyError::EmptyLayerName);
        }
        Ok(Self {
            value: String::from(value),
        })
    }

    /// Returns the layer name as a borrowed string.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn as_str(&self) -> &str {
        self.value.as_str()
    }
}

impl fmt::Display for LayerName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Topology ID family keyed by a property layer.
///
/// # Performance
///
/// Copying, comparing, ordering, hashing, and debug-formatting are `O(1)`.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum IdFamily {
    /// Element/node/vertex-keyed layer.
    Element,
    /// Relation/edge/hyperedge-keyed layer.
    Relation,
    /// Incidence/endpoint/participant-keyed layer.
    Incidence,
}

/// Declared role of a property layer.
///
/// # Performance
///
/// Copying, comparing, ordering, hashing, and debug-formatting are `O(1)`.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum LayerRole {
    /// Layer is intended to be selected as a topology weight capability.
    Weight,
    /// Layer is a named property with no required weight interpretation.
    Property,
}

/// Missing-value policy for sparse property layers.
///
/// The actual default scalar, when present, is stored in Arrow data for the
/// sparse layer. This enum records whether a total default exists.
///
/// # Performance
///
/// Copying, comparing, and debug-formatting are `O(1)`.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum MissingPolicy {
    /// Missing positions are null and therefore not directly weight-total.
    Null,
    /// Missing positions read from an Arrow scalar default stored with the layer.
    Default,
}

/// Physical storage mode for a property layer.
///
/// # Performance
///
/// Copying, comparing, and debug-formatting are `O(1)`.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum StorageMode {
    /// Dense array with one slot per ID index.
    Dense,
    /// Sparse array keyed by explicit indexes plus a missing-value policy.
    Sparse {
        /// Policy used for indexes not present in the sparse index array.
        missing: MissingPolicy,
    },
}

/// Descriptor for one Arrow-backed property layer.
///
/// # Performance
///
/// Cloning is `O(name.len() + arrow field clone cost)`.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct PropertyLayerDescriptor<Id, I>
where
    I: PropertyIndex,
{
    /// Stable layer identifier.
    pub layer_id: LayerId<Id>,
    /// Human-facing layer name.
    pub name: LayerName,
    /// Topology ID family keyed by this layer.
    pub id_family: IdFamily,
    /// Declared layer role.
    pub role: LayerRole,
    /// Physical storage mode.
    pub storage: StorageMode,
    /// Arrow schema field for stored values.
    pub arrow_field: Field,
    /// Sparse/logical index width selected for this layer.
    index_width: core::marker::PhantomData<I>,
}

impl<Id, I> PropertyLayerDescriptor<Id, I>
where
    I: PropertyIndex,
{
    /// Constructs a descriptor and validates the layer name.
    ///
    /// # Errors
    ///
    /// Returns [`PropertyError::EmptyLayerName`] when `name` is empty.
    ///
    /// # Performance
    ///
    /// This function is `O(name.len())` plus Arrow field move cost.
    #[expect(
        clippy::too_many_arguments,
        reason = "descriptor constructor mirrors the six-field descriptor contract"
    )]
    pub fn try_new(
        layer_id: LayerId<Id>,
        name: &str,
        id_family: IdFamily,
        role: LayerRole,
        storage: StorageMode,
        arrow_field: Field,
    ) -> Result<Self, PropertyError> {
        Ok(Self {
            layer_id,
            name: LayerName::try_new(name)?,
            id_family,
            role,
            storage,
            arrow_field,
            index_width: core::marker::PhantomData,
        })
    }
}

/// Errors raised while validating property descriptors, layers, or snapshots.
///
/// # Performance
///
/// Formatting is `O(message length)`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum PropertyError {
    /// Layer names must not be empty.
    EmptyLayerName,
    /// Dense layers must use dense descriptors.
    ExpectedDenseStorage {
        /// Name of the offending layer.
        name: LayerName,
    },
    /// Sparse layers must use sparse descriptors.
    ExpectedSparseStorage {
        /// Name of the offending layer.
        name: LayerName,
    },
    /// A sparse descriptor and default value disagreed.
    DefaultPolicyMismatch {
        /// Name of the offending layer.
        name: LayerName,
    },
    /// A layer's Arrow data type did not match the descriptor field type.
    ArrowTypeMismatch {
        /// Name of the offending layer.
        name: LayerName,
    },
    /// A layer's ID family did not match the requested adapter family.
    IdFamilyMismatch {
        /// Expected ID family.
        expected: IdFamily,
        /// Actual ID family.
        actual: IdFamily,
    },
    /// A layer had too few values for the topology index bound.
    LayerTooShort {
        /// Required minimum length.
        required: usize,
        /// Actual layer length.
        actual: usize,
    },
    /// A non-nullable selected layer contained a null slot.
    UnexpectedNull {
        /// Index of the null slot.
        index: usize,
    },
    /// Sparse index and value arrays differed in length.
    SparseLengthMismatch {
        /// Sparse index count.
        indices: usize,
        /// Sparse value count.
        values: usize,
    },
    /// Sparse indexes must be strictly increasing.
    SparseIndexOrder {
        /// Sparse array position where order failed.
        position: usize,
    },
    /// Sparse index was outside the declared logical length.
    SparseIndexOutOfBounds {
        /// Invalid sparse index.
        index: u64,
        /// Logical layer length.
        len: usize,
    },
    /// A name was reused within an ID-family namespace.
    DuplicateName {
        /// ID family namespace.
        id_family: IdFamily,
        /// Duplicate layer name.
        name: LayerName,
    },
    /// Sparse null-missing policy cannot be selected as a total weight view.
    SparseNullMissingNotTotal {
        /// Name of the offending layer.
        name: LayerName,
    },
    /// A layer ID was reused within one descriptor set.
    DuplicateLayerId {
        /// Duplicate layer ID.
        layer_id: u64,
    },
    /// A snapshot section was missing.
    MissingSnapshotSection {
        /// Missing section kind.
        kind: u32,
    },
    /// A snapshot section had an unsupported version.
    SnapshotSectionVersion {
        /// Section kind.
        kind: u32,
        /// Actual section version.
        version: u32,
    },
    /// A snapshot section could not be borrowed as the expected record type.
    SnapshotSectionView {
        /// Section kind.
        kind: u32,
        /// Underlying typed-view error.
        error: SectionViewError,
    },
    /// Snapshot bytes ended before a declared range.
    SnapshotRangeOutOfBounds {
        /// Byte range start.
        offset: usize,
        /// Byte range length.
        len: usize,
        /// Available section byte length.
        available: usize,
    },
    /// Snapshot string table bytes were not valid UTF-8.
    SnapshotInvalidUtf8 {
        /// Byte offset of the invalid string.
        offset: usize,
    },
    /// Snapshot metadata used an unknown ID family tag.
    UnknownIdFamilyTag {
        /// Invalid tag.
        tag: u32,
    },
    /// Snapshot metadata used an unknown layer role tag.
    UnknownLayerRoleTag {
        /// Invalid tag.
        tag: u32,
    },
    /// Snapshot metadata used an unknown storage tag.
    UnknownStorageTag {
        /// Invalid tag.
        tag: u32,
    },
    /// Snapshot metadata used an unknown missing-policy tag.
    UnknownMissingPolicyTag {
        /// Invalid tag.
        tag: u32,
    },
    /// Snapshot metadata used an unknown Arrow value-family tag.
    UnknownArrowFamilyTag {
        /// Invalid tag.
        tag: u32,
    },
    /// Snapshot metadata used an unknown identity-map mode tag.
    UnknownIdentityModeTag {
        /// Invalid tag.
        tag: u32,
    },
    /// A property snapshot descriptor was structurally inconsistent.
    SnapshotDescriptorMismatch {
        /// Human-readable mismatch reason.
        reason: &'static str,
    },
    /// A property data payload had an invalid byte length.
    SnapshotDataLength {
        /// Human-readable mismatch reason.
        reason: &'static str,
    },
    /// Arrow IPC/schema validation failed.
    Arrow {
        /// Arrow error message.
        message: String,
    },
    /// An explicit identity map was required but missing.
    MissingIdentityMap {
        /// ID family whose map was missing.
        id_family: IdFamily,
    },
    /// An identity map length did not match its mode metadata.
    IdentityMapLength {
        /// ID family whose map had the wrong length.
        id_family: IdFamily,
        /// Required map length.
        required: usize,
        /// Actual map length.
        actual: usize,
    },
    /// A `usize` value could not be represented as `u64`.
    LengthDoesNotFitU64 {
        /// Value that did not fit.
        value: usize,
    },
}

impl fmt::Display for PropertyError {
    #[expect(
        clippy::too_many_lines,
        reason = "property validation has one display branch per concrete error variant"
    )]
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyLayerName => formatter.write_str("property layer name is empty"),
            Self::ExpectedDenseStorage { name } => {
                write!(formatter, "property layer '{name}' is not dense")
            }
            Self::ExpectedSparseStorage { name } => {
                write!(formatter, "property layer '{name}' is not sparse")
            }
            Self::DefaultPolicyMismatch { name } => {
                write!(formatter, "property layer '{name}' default policy mismatch")
            }
            Self::ArrowTypeMismatch { name } => {
                write!(formatter, "property layer '{name}' Arrow type mismatch")
            }
            Self::IdFamilyMismatch { expected, actual } => write!(
                formatter,
                "property ID family mismatch: expected {expected:?}, got {actual:?}"
            ),
            Self::LayerTooShort { required, actual } => write!(
                formatter,
                "property layer too short: required {required}, got {actual}"
            ),
            Self::UnexpectedNull { index } => write!(
                formatter,
                "property layer has unexpected null at index {index}"
            ),
            Self::SparseLengthMismatch { indices, values } => write!(
                formatter,
                "sparse property length mismatch: {indices} indexes for {values} values"
            ),
            Self::SparseIndexOrder { position } => write!(
                formatter,
                "sparse property indexes are not strictly increasing at position {position}"
            ),
            Self::SparseIndexOutOfBounds { index, len } => write!(
                formatter,
                "sparse property index {index} is outside logical length {len}"
            ),
            Self::DuplicateName { id_family, name } => write!(
                formatter,
                "duplicate property name '{name}' in {id_family:?} namespace"
            ),
            Self::SparseNullMissingNotTotal { name } => write!(
                formatter,
                "sparse property layer '{name}' has null missing policy and is not total"
            ),
            Self::DuplicateLayerId { layer_id } => {
                write!(formatter, "duplicate property layer ID {layer_id:?}")
            }
            Self::MissingSnapshotSection { kind } => {
                write!(formatter, "snapshot is missing section kind {kind:#x}")
            }
            Self::SnapshotSectionVersion { kind, version } => write!(
                formatter,
                "snapshot section {kind:#x} has unsupported version {version}"
            ),
            Self::SnapshotSectionView { kind, error } => write!(
                formatter,
                "snapshot section {kind:#x} cannot be borrowed as expected records: {error}"
            ),
            Self::SnapshotRangeOutOfBounds {
                offset,
                len,
                available,
            } => write!(
                formatter,
                "snapshot range {offset}..{} exceeds available {available} bytes",
                offset.saturating_add(*len)
            ),
            Self::SnapshotInvalidUtf8 { offset } => {
                write!(
                    formatter,
                    "snapshot string at byte offset {offset} is not UTF-8"
                )
            }
            Self::UnknownIdFamilyTag { tag } => {
                write!(formatter, "unknown property ID-family tag {tag}")
            }
            Self::UnknownLayerRoleTag { tag } => {
                write!(formatter, "unknown property layer-role tag {tag}")
            }
            Self::UnknownStorageTag { tag } => {
                write!(formatter, "unknown property storage tag {tag}")
            }
            Self::UnknownMissingPolicyTag { tag } => {
                write!(formatter, "unknown property missing-policy tag {tag}")
            }
            Self::UnknownArrowFamilyTag { tag } => {
                write!(formatter, "unknown Arrow value-family tag {tag}")
            }
            Self::UnknownIdentityModeTag { tag } => {
                write!(formatter, "unknown identity-map mode tag {tag}")
            }
            Self::SnapshotDescriptorMismatch { reason } => {
                write!(formatter, "property snapshot descriptor mismatch: {reason}")
            }
            Self::SnapshotDataLength { reason } => {
                write!(
                    formatter,
                    "property snapshot data length mismatch: {reason}"
                )
            }
            Self::Arrow { message } => write!(formatter, "Arrow property error: {message}"),
            Self::MissingIdentityMap { id_family } => {
                write!(formatter, "missing explicit identity map for {id_family:?}")
            }
            Self::IdentityMapLength {
                id_family,
                required,
                actual,
            } => write!(
                formatter,
                "identity map for {id_family:?} has length {actual}, required {required}"
            ),
            Self::LengthDoesNotFitU64 { value } => {
                write!(formatter, "length {value} does not fit u64")
            }
        }
    }
}

impl Error for PropertyError {}

/// Data backing one property layer.
///
/// # Performance
///
/// Cloning is `O(1)` because Arrow arrays are reference-counted.
#[non_exhaustive]
pub enum PropertyLayerData<I>
where
    I: PropertyIndex,
{
    /// Dense Arrow array with one slot per ID index.
    Dense {
        /// Dense values.
        values: ArrayRef,
    },
    /// Sparse Arrow array keyed by explicit indexes.
    Sparse {
        /// Strictly ascending sparse indexes.
        indices: Arc<PrimitiveArray<I::ArrowType>>,
        /// Values aligned with `indices`.
        values: ArrayRef,
        /// Optional Arrow scalar default encoded as a length-one array.
        default: Option<ArrayRef>,
    },
}

impl<I> Clone for PropertyLayerData<I>
where
    I: PropertyIndex,
{
    fn clone(&self) -> Self {
        match self {
            Self::Dense { values } => Self::Dense {
                values: Arc::clone(values),
            },
            Self::Sparse {
                indices,
                values,
                default,
            } => Self::Sparse {
                indices: Arc::clone(indices),
                values: Arc::clone(values),
                default: default.clone(),
            },
        }
    }
}

impl<I> fmt::Debug for PropertyLayerData<I>
where
    I: PropertyIndex,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Dense { values } => formatter
                .debug_struct("Dense")
                .field("len", &values.len())
                .finish(),
            Self::Sparse {
                indices,
                values,
                default,
            } => formatter
                .debug_struct("Sparse")
                .field("indices", &indices.len())
                .field("values", &values.len())
                .field("has_default", &default.is_some())
                .finish(),
        }
    }
}

/// Arrow-backed property layer.
///
/// # Performance
///
/// Cloning is `O(1)` for Arrow buffers plus descriptor clone cost.
#[derive(Clone, Debug)]
#[must_use]
pub struct PropertyLayer<Id, I>
where
    I: PropertyIndex,
{
    /// Layer descriptor.
    descriptor: PropertyLayerDescriptor<Id, I>,
    /// Logical layer length.
    len: usize,
    /// Layer data.
    data: PropertyLayerData<I>,
}

impl<Id, I> PropertyLayer<Id, I>
where
    I: PropertyIndex,
{
    /// Builds a dense Arrow-backed property layer.
    ///
    /// # Errors
    ///
    /// Returns [`PropertyError`] when storage, Arrow type, or nullability is invalid.
    ///
    /// # Performance
    ///
    /// Validation is `O(values.len())` only when nullability must be checked.
    pub fn try_new_dense(
        descriptor: PropertyLayerDescriptor<Id, I>,
        values: ArrayRef,
    ) -> Result<Self, PropertyError> {
        if descriptor.storage != StorageMode::Dense {
            return Err(PropertyError::ExpectedDenseStorage {
                name: descriptor.name,
            });
        }
        ensure_arrow_type(&descriptor, values.as_ref())?;
        if !descriptor.arrow_field.is_nullable() {
            ensure_no_nulls(values.as_ref())?;
        }
        let len = values.len();
        Ok(Self {
            descriptor,
            len,
            data: PropertyLayerData::Dense { values },
        })
    }

    /// Builds a sparse Arrow-backed property layer.
    ///
    /// # Errors
    ///
    /// Returns [`PropertyError`] when storage, Arrow type, default policy,
    /// sparse index ordering, or nullability is invalid.
    ///
    /// # Performance
    ///
    /// Validation is `O(indices.len() + default length)`.
    pub fn try_new_sparse(
        descriptor: PropertyLayerDescriptor<Id, I>,
        len: usize,
        indices: Arc<PrimitiveArray<I::ArrowType>>,
        values: ArrayRef,
        default: Option<ArrayRef>,
    ) -> Result<Self, PropertyError> {
        let StorageMode::Sparse { missing } = descriptor.storage else {
            return Err(PropertyError::ExpectedSparseStorage {
                name: descriptor.name,
            });
        };
        validate_default_policy(&descriptor, missing, default.as_ref())?;
        ensure_arrow_type(&descriptor, values.as_ref())?;
        if indices.len() != values.len() {
            return Err(PropertyError::SparseLengthMismatch {
                indices: indices.len(),
                values: values.len(),
            });
        }
        ensure_no_nulls(indices.as_ref())?;
        if !descriptor.arrow_field.is_nullable() {
            ensure_no_nulls(values.as_ref())?;
        }
        validate_sparse_indices::<I>(indices.as_ref(), len)?;
        Ok(Self {
            descriptor,
            len,
            data: PropertyLayerData::Sparse {
                indices,
                values,
                default,
            },
        })
    }

    /// Returns this layer's descriptor.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn descriptor(&self) -> &PropertyLayerDescriptor<Id, I> {
        &self.descriptor
    }

    /// Returns this layer's data.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn data(&self) -> &PropertyLayerData<I> {
        &self.data
    }

    /// Returns the logical layer length.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns whether the logical layer is empty.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }
}

/// Identity snapshot map mode.
///
/// # Performance
///
/// Copying, comparing, and debug-formatting are `O(1)`.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum IdentityMapMode {
    /// Local IDs are identical to canonical IDs for this family.
    LocalEqualsCanonical,
    /// The snapshot stores an explicit local-to-canonical map section.
    ExplicitMap,
}

impl IdentityMapMode {
    /// Returns the snapshot tag for this mode.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    const fn tag(self) -> u32 {
        match self {
            Self::LocalEqualsCanonical => 0,
            Self::ExplicitMap => 1,
        }
    }

    /// Decodes a snapshot mode tag.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    const fn from_tag(tag: u32) -> Option<Self> {
        match tag {
            0 => Some(Self::LocalEqualsCanonical),
            1 => Some(Self::ExplicitMap),
            _ => None,
        }
    }
}

/// Wire record declaring one identity family map mode.
///
/// # Performance
///
/// Copying and reading fields are `O(1)`.
#[derive(Clone, Copy, Debug, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq)]
#[repr(C)]
pub struct IdentityModeRecord<W>
where
    W: PropertySnapshotMetaWord,
{
    /// ID-family tag.
    id_family: W::LittleEndianWord,
    /// Map-mode tag.
    mode: W::LittleEndianWord,
    /// Number of local IDs covered by the mode.
    local_len: W::LittleEndianWord,
}

impl<W> IdentityModeRecord<W>
where
    W: PropertySnapshotMetaWord,
{
    /// Builds a local-equals-canonical identity mode record.
    ///
    /// # Errors
    ///
    /// Returns [`PropertyError`] when `local_len` cannot be represented by the
    /// selected metadata width.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    pub fn local_equals_canonical(
        id_family: IdFamily,
        local_len: usize,
    ) -> Result<Self, PropertyError> {
        Self::new(id_family, IdentityMapMode::LocalEqualsCanonical, local_len)
    }

    /// Builds an explicit-map identity mode record.
    ///
    /// # Errors
    ///
    /// Returns [`PropertyError`] when `local_len` cannot be represented by the
    /// selected metadata width.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    pub fn explicit_map(id_family: IdFamily, local_len: usize) -> Result<Self, PropertyError> {
        Self::new(id_family, IdentityMapMode::ExplicitMap, local_len)
    }

    /// Builds an identity mode record.
    ///
    /// # Errors
    ///
    /// Returns [`PropertyError`] when `local_len` cannot be represented by the
    /// selected metadata width.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    pub fn new(
        id_family: IdFamily,
        mode: IdentityMapMode,
        local_len: usize,
    ) -> Result<Self, PropertyError> {
        Ok(Self {
            id_family: le_word::<W>(id_family_tag(id_family) as usize)?,
            mode: le_word::<W>(mode.tag() as usize)?,
            local_len: le_word::<W>(local_len)?,
        })
    }

    /// Returns this record's ID family.
    ///
    /// # Errors
    ///
    /// Returns [`PropertyError::UnknownIdFamilyTag`] if the record tag is unknown.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    pub fn id_family(&self) -> Result<IdFamily, PropertyError> {
        id_family_from_tag(le_word_to_u32::<W>(self.id_family)?)
    }

    /// Returns this record's identity map mode.
    ///
    /// # Errors
    ///
    /// Returns [`PropertyError::UnknownIdentityModeTag`] if the record tag is unknown.
    ///
    /// # Performance
    ///
    /// This function is `O(1)`.
    pub fn mode(&self) -> Result<IdentityMapMode, PropertyError> {
        let tag = le_word_to_u32::<W>(self.mode)?;
        IdentityMapMode::from_tag(tag).ok_or(PropertyError::UnknownIdentityModeTag { tag })
    }

    /// Returns the local ID count covered by this mode.
    ///
    /// # Performance
    ///
    /// This function is `O(1)` on targets where `u64` to `usize` fits; values
    /// above `usize::MAX` saturate to `usize::MAX` for validation errors.
    #[must_use]
    pub fn local_len(&self) -> usize {
        le_word_to_usize::<W>(self.local_len).unwrap_or(usize::MAX)
    }
}

/// Summary returned after identity snapshot validation.
///
/// # Performance
///
/// Cloning is `O(f)` for `f` identity-family records.
#[derive(Clone, Debug, Eq, PartialEq)]
#[must_use]
pub struct IdentitySnapshotSummary {
    /// Validated identity records.
    pub records: Vec<IdentityModeSummary>,
}

/// Decoded identity mode summary.
///
/// # Performance
///
/// Copying is `O(1)`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct IdentityModeSummary {
    /// ID family covered by this record.
    pub id_family: IdFamily,
    /// Identity map mode.
    pub mode: IdentityMapMode,
    /// Number of local IDs covered.
    pub local_len: usize,
}

/// Converts an ID family to its snapshot tag.
///
/// # Performance
///
/// This function is `O(1)`.
pub(crate) const fn id_family_tag(id_family: IdFamily) -> u32 {
    match id_family {
        IdFamily::Element => 0,
        IdFamily::Relation => 1,
        IdFamily::Incidence => 2,
    }
}

/// Decodes an ID family snapshot tag.
///
/// # Performance
///
/// This function is `O(1)`.
pub(crate) const fn id_family_from_tag(tag: u32) -> Result<IdFamily, PropertyError> {
    match tag {
        0 => Ok(IdFamily::Element),
        1 => Ok(IdFamily::Relation),
        2 => Ok(IdFamily::Incidence),
        _ => Err(PropertyError::UnknownIdFamilyTag { tag }),
    }
}

/// Converts a layer role to its snapshot tag.
///
/// # Performance
///
/// This function is `O(1)`.
pub(crate) const fn layer_role_tag(role: LayerRole) -> u32 {
    match role {
        LayerRole::Weight => 0,
        LayerRole::Property => 1,
    }
}

/// Decodes a layer role snapshot tag.
///
/// # Performance
///
/// This function is `O(1)`.
pub(crate) const fn layer_role_from_tag(tag: u32) -> Result<LayerRole, PropertyError> {
    match tag {
        0 => Ok(LayerRole::Weight),
        1 => Ok(LayerRole::Property),
        _ => Err(PropertyError::UnknownLayerRoleTag { tag }),
    }
}

/// Converts storage mode to its snapshot tag.
///
/// # Performance
///
/// This function is `O(1)`.
pub(crate) const fn storage_tag(storage: StorageMode) -> u32 {
    match storage {
        StorageMode::Dense => 0,
        StorageMode::Sparse { .. } => 1,
    }
}

/// Converts missing policy to its snapshot tag.
///
/// # Performance
///
/// This function is `O(1)`.
pub(crate) const fn missing_policy_tag(storage: StorageMode) -> u32 {
    match storage {
        StorageMode::Dense => 0,
        StorageMode::Sparse {
            missing: MissingPolicy::Null,
        } => 1,
        StorageMode::Sparse {
            missing: MissingPolicy::Default,
        } => 2,
    }
}

/// Decodes storage and missing policy tags.
///
/// # Performance
///
/// This function is `O(1)`.
pub(crate) const fn storage_from_tags(
    storage: u32,
    missing: u32,
) -> Result<StorageMode, PropertyError> {
    match (storage, missing) {
        (0, 0) => Ok(StorageMode::Dense),
        (1, 1) => Ok(StorageMode::Sparse {
            missing: MissingPolicy::Null,
        }),
        (1, 2) => Ok(StorageMode::Sparse {
            missing: MissingPolicy::Default,
        }),
        (0, _) => Err(PropertyError::UnknownMissingPolicyTag { tag: missing }),
        (_, _) => Err(PropertyError::UnknownStorageTag { tag: storage }),
    }
}

/// Ensures an Arrow array matches a descriptor field data type.
///
/// # Performance
///
/// This function is `O(1)`.
pub(crate) fn ensure_arrow_type<Id, I>(
    descriptor: &PropertyLayerDescriptor<Id, I>,
    values: &dyn Array,
) -> Result<(), PropertyError>
where
    I: PropertyIndex,
{
    if descriptor.arrow_field.data_type() == values.data_type() {
        Ok(())
    } else {
        Err(PropertyError::ArrowTypeMismatch {
            name: descriptor.name.clone(),
        })
    }
}

/// Validates sparse default policy and Arrow type.
///
/// # Performance
///
/// This function is `O(1)`.
fn validate_default_policy<Id, I>(
    descriptor: &PropertyLayerDescriptor<Id, I>,
    missing: MissingPolicy,
    default: Option<&ArrayRef>,
) -> Result<(), PropertyError>
where
    I: PropertyIndex,
{
    match (missing, default) {
        (MissingPolicy::Null, None) => Ok(()),
        (MissingPolicy::Default, Some(array)) => {
            ensure_arrow_type(descriptor, array.as_ref())?;
            if array.len() == 1 && !array.is_null(0) {
                Ok(())
            } else {
                Err(PropertyError::DefaultPolicyMismatch {
                    name: descriptor.name.clone(),
                })
            }
        }
        (MissingPolicy::Null | MissingPolicy::Default, _) => {
            Err(PropertyError::DefaultPolicyMismatch {
                name: descriptor.name.clone(),
            })
        }
    }
}

/// Ensures an Arrow array has no null slots.
///
/// # Performance
///
/// This function is `O(array.len())`.
pub(crate) fn ensure_no_nulls(array: &dyn Array) -> Result<(), PropertyError> {
    for index in 0..array.len() {
        if array.is_null(index) {
            return Err(PropertyError::UnexpectedNull { index });
        }
    }
    Ok(())
}

/// Validates sparse index ordering and bounds.
///
/// # Performance
///
/// This function is `O(indices.len())`.
pub(crate) fn validate_sparse_indices<I>(
    indices: &PrimitiveArray<I::ArrowType>,
    len: usize,
) -> Result<(), PropertyError>
where
    I: PropertyIndex,
{
    let mut previous = None;
    for position in 0..indices.len() {
        let index = indices.value(position);
        let Some(index_usize) = index.to_usize() else {
            return Err(PropertyError::SparseIndexOutOfBounds {
                index: index.to_u64(),
                len,
            });
        };
        if index_usize >= len {
            return Err(PropertyError::SparseIndexOutOfBounds {
                index: index.to_u64(),
                len,
            });
        }
        if let Some(prior) = previous
            && index <= prior
        {
            return Err(PropertyError::SparseIndexOrder { position });
        }
        previous = Some(index);
    }
    Ok(())
}

/// Converts an Arrow error into a property error.
///
/// # Performance
///
/// This function is `O(error message length)`.
#[expect(
    clippy::needless_pass_by_value,
    reason = "Arrow result adapters hand over owned errors and this helper consumes them into messages"
)]
pub(crate) fn map_arrow_error(error: arrow_schema::ArrowError) -> PropertyError {
    PropertyError::Arrow {
        message: error.to_string(),
    }
}