canic-memory 0.38.1

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

///
/// MemoryRange
///
/// Inclusive stable-memory ID range reserved by one owner crate.

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct MemoryRange {
    /// First stable-memory ID in the range.
    pub start: u8,
    /// Last stable-memory ID in the range.
    pub end: u8,
}

impl MemoryRange {
    /// Return whether `id` is inside this inclusive range.
    #[must_use]
    pub const fn contains(&self, id: u8) -> bool {
        id >= self.start && id <= self.end
    }
}

///
/// MemoryRegistryEntry
///
/// Registered stable-memory slot metadata.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct MemoryRegistryEntry {
    /// Crate name that registered the stable-memory slot.
    pub crate_name: String,
    /// Human-readable label for the registered stable-memory slot.
    pub label: String,
    /// Explicit ABI-stable key that owns this memory ID permanently.
    pub stable_key: String,
    /// Optional in-place schema version metadata for diagnostics.
    pub schema_version: Option<u32>,
    /// Optional opaque schema fingerprint metadata for diagnostics.
    pub schema_fingerprint: Option<String>,
}

///
/// MemoryRangeEntry
///
/// Reserved stable-memory range with explicit owner context.

#[derive(Clone, Debug)]
pub struct MemoryRangeEntry {
    /// Crate name that reserved the range.
    pub owner: String,
    /// Inclusive stable-memory ID range reserved by `owner`.
    pub range: MemoryRange,
}

///
/// MemoryRangeSnapshot
///
/// Registered stable-memory slots grouped under one reserved range.

#[derive(Clone, Debug)]
pub struct MemoryRangeSnapshot {
    /// Crate name that reserved the range.
    pub owner: String,
    /// Inclusive stable-memory ID range reserved by `owner`.
    pub range: MemoryRange,
    /// Registered entries whose IDs fall inside `range`.
    pub entries: Vec<(u8, MemoryRegistryEntry)>,
}

///
/// MemoryRangeAuthority
///
/// Durable allocation-authority range recorded by the ABI ledger.

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct MemoryRangeAuthority {
    /// Authority label for the range.
    pub owner: String,
    /// Inclusive stable-memory ID range controlled by this authority.
    pub range: MemoryRange,
    /// Stable diagnostic purpose for the authority record.
    pub purpose: String,
}

///
/// PendingRegistration
///
/// One stable-memory declaration collected before bootstrap validation.

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct PendingRegistration {
    pub id: u8,
    pub crate_name: String,
    pub label: String,
    pub stable_key: String,
    pub schema_version: Option<u32>,
    pub schema_fingerprint: Option<String>,
}

///
/// MemoryRegistryError
///
/// Errors returned when a memory range or ID registration is invalid.

#[derive(Debug, ThisError)]
pub enum MemoryRegistryError {
    /// A requested owner range overlaps an already reserved range.
    #[error(
        "memory range overlap: crate '{existing_crate}' [{existing_start}-{existing_end}]
conflicts with crate '{new_crate}' [{new_start}-{new_end}]"
    )]
    Overlap {
        /// Crate that already owns the conflicting range.
        existing_crate: String,
        /// First ID in the existing range.
        existing_start: u8,
        /// Last ID in the existing range.
        existing_end: u8,
        /// Crate requesting the new range.
        new_crate: String,
        /// First ID in the requested range.
        new_start: u8,
        /// Last ID in the requested range.
        new_end: u8,
    },

    /// The requested range has `start > end`.
    #[error("memory range is invalid: start={start} end={end}")]
    InvalidRange {
        /// First ID in the requested range.
        start: u8,
        /// Last ID in the requested range.
        end: u8,
    },

    /// The memory ID is already registered.
    #[error("memory id {0} is already registered; each memory id must be globally unique")]
    DuplicateId(u8),

    /// The stable key is declared more than once in one runtime snapshot.
    #[error(
        "memory stable key '{0}' is declared more than once; each stable key must be globally unique"
    )]
    DuplicateStableKey(String),

    /// The crate attempted to register an ID before reserving any range.
    #[error("memory id {id} has no reserved range for crate '{crate_name}'")]
    NoReservedRange {
        /// Crate attempting to register the ID.
        crate_name: String,
        /// Stable-memory ID being registered.
        id: u8,
    },

    /// The ID falls inside a range reserved by another crate.
    #[error(
        "memory id {id} reserved to crate '{owner}' [{owner_start}-{owner_end}], not '{crate_name}'"
    )]
    IdOwnedByOther {
        /// Crate attempting to register the ID.
        crate_name: String,
        /// Stable-memory ID being registered.
        id: u8,
        /// Crate that owns the range containing `id`.
        owner: String,
        /// First ID in the owning range.
        owner_start: u8,
        /// Last ID in the owning range.
        owner_end: u8,
    },

    /// The crate has reserved ranges, but none contain the requested ID.
    #[error("memory id {id} is outside reserved ranges for crate '{crate_name}'")]
    IdOutOfRange {
        /// Crate attempting to register the ID.
        crate_name: String,
        /// Stable-memory ID being registered.
        id: u8,
    },

    /// The ID is the unallocated-bucket sentinel and is not usable.
    #[error(
        "memory id {id} is the unallocated-bucket sentinel and is not a usable virtual memory id"
    )]
    ReservedInternalId {
        /// Invalid sentinel stable-memory ID.
        id: u8,
    },

    /// A requested range conflicts with a range recorded in the stable layout ledger.
    #[error(
        "memory range historical conflict: crate '{existing_crate}' [{existing_start}-{existing_end}]
conflicts with crate '{new_crate}' [{new_start}-{new_end}]"
    )]
    HistoricalRangeConflict {
        /// Crate that historically owns the conflicting range.
        existing_crate: String,
        /// First ID in the historical range.
        existing_start: u8,
        /// Last ID in the historical range.
        existing_end: u8,
        /// Crate requesting the new range.
        new_crate: String,
        /// First ID in the requested range.
        new_start: u8,
        /// Last ID in the requested range.
        new_end: u8,
    },

    /// A requested ID conflicts with an ID recorded in the stable layout ledger.
    #[error(
        "memory id {id} was historically registered to crate '{existing_crate}' label '{existing_label}', not crate '{new_crate}' label '{new_label}'"
    )]
    HistoricalIdConflict {
        /// Stable-memory ID being registered.
        id: u8,
        /// Crate that historically registered the ID.
        existing_crate: String,
        /// Historical label for the ID.
        existing_label: String,
        /// Crate requesting the ID now.
        new_crate: String,
        /// Requested label for the ID now.
        new_label: String,
        /// Requested stable key for the ID now.
        new_stable_key: String,
    },

    /// A requested stable key conflicts with a different historical ID.
    #[error(
        "memory stable key '{stable_key}' was historically registered to id {existing_id}, not id {new_id}"
    )]
    HistoricalStableKeyConflict {
        /// Stable key being registered.
        stable_key: String,
        /// Historical ID for the stable key.
        existing_id: u8,
        /// Requested ID for the stable key now.
        new_id: u8,
    },

    /// The stable key is not canonical.
    #[error("memory stable key '{stable_key}' is invalid: {reason}")]
    InvalidStableKey {
        /// Rejected stable key.
        stable_key: String,
        /// Human-readable reason for the rejection.
        reason: &'static str,
    },

    /// The schema metadata is not canonical.
    #[error("memory schema metadata is invalid for stable key '{stable_key}': {reason}")]
    InvalidSchemaMetadata {
        /// Stable key whose schema metadata was rejected.
        stable_key: String,
        /// Human-readable reason for the rejection.
        reason: &'static str,
    },

    /// The stable key namespace and memory ID range do not match.
    #[error(
        "memory stable key '{stable_key}' with id {id} violates namespace/range authority: {reason}"
    )]
    RangeAuthorityViolation {
        /// Stable key being registered.
        stable_key: String,
        /// Stable-memory ID being registered.
        id: u8,
        /// Human-readable reason for the rejection.
        reason: &'static str,
    },

    /// Registration was attempted after the bootstrap declaration snapshot was sealed.
    #[error(
        "memory registration after bootstrap is sealed is not allowed: {ranges} range(s), {registrations} registration(s)"
    )]
    RegistrationAfterBootstrap {
        /// Number of late range declarations.
        ranges: usize,
        /// Number of late memory ID declarations.
        registrations: usize,
    },

    /// A memory handle was requested before bootstrap validated the declaration snapshot.
    #[error("memory registry has not completed bootstrap validation")]
    RegistryNotBootstrapped,

    /// The persisted ABI ledger cannot be validated.
    #[error("memory layout ledger is corrupt: {reason}")]
    LedgerCorrupt {
        /// Human-readable corruption reason.
        reason: &'static str,
    },
}

//
// Internal global state (substrate-level, single-threaded)
//

thread_local! {
    static RESERVED_RANGES: RefCell<Vec<(String, MemoryRange)>> = const { RefCell::new(Vec::new()) };
    static REGISTRY: RefCell<BTreeMap<u8, MemoryRegistryEntry>> = const { RefCell::new(BTreeMap::new()) };

    // Deferred registrations (used before init)
    static PENDING_RANGES: RefCell<Vec<(String, u8, u8)>> = const { RefCell::new(Vec::new()) };
    static PENDING_REGISTRATIONS: RefCell<Vec<PendingRegistration>> = const { RefCell::new(Vec::new()) };
}

///
/// MemoryRegistry
///
/// Canonical substrate registry for stable memory IDs.
///
pub struct MemoryRegistry;

impl MemoryRegistry {
    /// Reserve the internal persisted layout ledger range and slot.
    pub(crate) fn reserve_internal_layout_ledger() -> Result<(), MemoryRegistryError> {
        Self::reserve_range(
            ledger::MEMORY_LAYOUT_LEDGER_OWNER,
            ledger::MEMORY_LAYOUT_RESERVED_MIN,
            ledger::MEMORY_LAYOUT_RESERVED_MAX,
        )?;

        if let Some(entry) = Self::get(ledger::MEMORY_LAYOUT_LEDGER_ID)
            && entry.crate_name == ledger::MEMORY_LAYOUT_LEDGER_OWNER
            && entry.label == ledger::MEMORY_LAYOUT_LEDGER_LABEL
            && entry.stable_key == ledger::MEMORY_LAYOUT_LEDGER_STABLE_KEY
        {
            return Ok(());
        }

        Self::register_with_key(
            ledger::MEMORY_LAYOUT_LEDGER_ID,
            ledger::MEMORY_LAYOUT_LEDGER_OWNER,
            ledger::MEMORY_LAYOUT_LEDGER_LABEL,
            ledger::MEMORY_LAYOUT_LEDGER_STABLE_KEY,
        )
    }

    /// Reserve an inclusive memory ID range for one crate.
    ///
    /// Exact duplicate reservations by the same crate are accepted so init and
    /// post-upgrade can share the same bootstrap path.
    pub fn reserve_range(crate_name: &str, start: u8, end: u8) -> Result<(), MemoryRegistryError> {
        if start > end {
            return Err(MemoryRegistryError::InvalidRange { start, end });
        }
        validate_range_excludes_reserved_internal_id(start, end)?;
        validate_range_excludes_layout_metadata(crate_name, start, end)?;

        let range = MemoryRange { start, end };
        let mut already_reserved = false;

        RESERVED_RANGES.with_borrow(|ranges| {
            for (existing_crate, existing_range) in ranges {
                if ranges_overlap(*existing_range, range) {
                    if existing_crate == crate_name
                        && existing_range.start == start
                        && existing_range.end == end
                    {
                        // Allow exact duplicate reservations for idempotent init.
                        already_reserved = true;
                        return Ok(());
                    }
                    return Err(MemoryRegistryError::Overlap {
                        existing_crate: existing_crate.clone(),
                        existing_start: existing_range.start,
                        existing_end: existing_range.end,
                        new_crate: crate_name.to_string(),
                        new_start: start,
                        new_end: end,
                    });
                }
            }

            Ok(())
        })?;

        ledger::record_range(crate_name, range)?;

        if already_reserved {
            return Ok(());
        }

        RESERVED_RANGES.with_borrow_mut(|ranges| {
            ranges.push((crate_name.to_string(), range));
        });

        Ok(())
    }

    /// Register one memory ID under an existing owner range.
    pub fn register(id: u8, crate_name: &str, label: &str) -> Result<(), MemoryRegistryError> {
        Self::register_with_key(
            id,
            crate_name,
            label,
            &fallback_stable_key(crate_name, label),
        )
    }

    /// Register one memory ID under an existing owner range using an explicit ABI key.
    pub fn register_with_key(
        id: u8,
        crate_name: &str,
        label: &str,
        stable_key: &str,
    ) -> Result<(), MemoryRegistryError> {
        Self::register_with_key_metadata(id, crate_name, label, stable_key, None, None)
    }

    /// Register one memory ID with explicit ABI key and optional schema metadata.
    pub fn register_with_key_metadata(
        id: u8,
        crate_name: &str,
        label: &str,
        stable_key: &str,
        schema_version: Option<u32>,
        schema_fingerprint: Option<&str>,
    ) -> Result<(), MemoryRegistryError> {
        validate_non_internal_id(id)?;
        validate_id_excludes_layout_metadata(crate_name, id)?;
        validate_registration_range(crate_name, id)?;
        validate_stable_key(stable_key)?;
        validate_schema_metadata(stable_key, schema_version, schema_fingerprint)?;
        validate_id_authority(id, crate_name, stable_key)?;

        REGISTRY.with_borrow(|reg| {
            if reg.contains_key(&id) {
                return Err(MemoryRegistryError::DuplicateId(id));
            }
            Ok(())
        })?;

        ledger::record_entry(
            id,
            crate_name,
            label,
            stable_key,
            schema_version,
            schema_fingerprint,
        )?;

        REGISTRY.with_borrow_mut(|reg| {
            reg.insert(
                id,
                MemoryRegistryEntry {
                    crate_name: crate_name.to_string(),
                    label: label.to_string(),
                    stable_key: stable_key.to_string(),
                    schema_version,
                    schema_fingerprint: schema_fingerprint.map(str::to_string),
                },
            );
        });

        Ok(())
    }

    /// Export all registered entries (canonical snapshot).
    #[must_use]
    pub fn export() -> Vec<(u8, MemoryRegistryEntry)> {
        REGISTRY.with_borrow(|reg| reg.iter().map(|(k, v)| (*k, v.clone())).collect())
    }

    /// Export all reserved ranges.
    #[must_use]
    pub fn export_ranges() -> Vec<(String, MemoryRange)> {
        RESERVED_RANGES.with_borrow(std::clone::Clone::clone)
    }

    /// Export all reserved ranges with explicit owners.
    #[must_use]
    pub fn export_range_entries() -> Vec<MemoryRangeEntry> {
        RESERVED_RANGES.with_borrow(|ranges| {
            ranges
                .iter()
                .map(|(owner, range)| MemoryRangeEntry {
                    owner: owner.clone(),
                    range: *range,
                })
                .collect()
        })
    }

    /// Export registry entries grouped by reserved range.
    #[must_use]
    pub fn export_ids_by_range() -> Vec<MemoryRangeSnapshot> {
        let mut ranges = RESERVED_RANGES.with_borrow(std::clone::Clone::clone);
        let entries = REGISTRY.with_borrow(std::clone::Clone::clone);

        ranges.sort_by_key(|(_, range)| range.start);

        ranges
            .into_iter()
            .map(|(owner, range)| {
                let entries = entries
                    .iter()
                    .filter(|(id, _)| range.contains(**id))
                    .map(|(id, entry)| (*id, entry.clone()))
                    .collect();

                MemoryRangeSnapshot {
                    owner,
                    range,
                    entries,
                }
            })
            .collect()
    }

    /// Retrieve a single registry entry.
    #[must_use]
    pub fn get(id: u8) -> Option<MemoryRegistryEntry> {
        REGISTRY.with_borrow(|reg| reg.get(&id).cloned())
    }

    /// Export all ranges ever recorded in the stable memory layout ledger.
    #[must_use]
    pub fn export_historical_ranges() -> Vec<(String, MemoryRange)> {
        ledger::export_ranges()
    }

    /// Export canonical allocation authorities recorded in the stable memory layout ledger.
    #[must_use]
    pub fn export_historical_authorities() -> Vec<MemoryRangeAuthority> {
        ledger::export_authorities()
    }

    /// Fallibly export all ranges ever recorded in the stable memory layout ledger.
    pub fn try_export_historical_ranges() -> Result<Vec<(String, MemoryRange)>, MemoryRegistryError>
    {
        ledger::try_export_ranges()
    }

    /// Fallibly export canonical allocation authorities recorded in the stable memory layout ledger.
    pub fn try_export_historical_authorities()
    -> Result<Vec<MemoryRangeAuthority>, MemoryRegistryError> {
        ledger::try_export_authorities()
    }

    /// Export all memory IDs ever recorded in the stable memory layout ledger.
    #[must_use]
    pub fn export_historical() -> Vec<(u8, MemoryRegistryEntry)> {
        ledger::export_entries()
    }

    /// Fallibly export all memory IDs ever recorded in the stable memory layout ledger.
    pub fn try_export_historical() -> Result<Vec<(u8, MemoryRegistryEntry)>, MemoryRegistryError> {
        ledger::try_export_entries()
    }
}

//
// Deferred registration helpers (used before runtime init)
//

/// Queue a range reservation for deterministic application during bootstrap.
#[doc(hidden)]
pub fn defer_reserve_range(
    crate_name: &str,
    start: u8,
    end: u8,
) -> Result<(), MemoryRegistryError> {
    if start > end {
        return Err(MemoryRegistryError::InvalidRange { start, end });
    }
    validate_range_excludes_reserved_internal_id(start, end)?;
    validate_range_excludes_layout_metadata(crate_name, start, end)?;

    // Queue range reservations for runtime init to apply deterministically.
    PENDING_RANGES.with_borrow_mut(|ranges| {
        ranges.push((crate_name.to_string(), start, end));
    });

    Ok(())
}

/// Queue an ID registration for deterministic application during bootstrap.
#[doc(hidden)]
pub fn defer_register(id: u8, crate_name: &str, label: &str) -> Result<(), MemoryRegistryError> {
    defer_register_with_key(
        id,
        crate_name,
        label,
        &fallback_stable_key(crate_name, label),
    )
}

/// Queue an ID registration with an explicit ABI-stable key.
#[doc(hidden)]
pub fn defer_register_with_key(
    id: u8,
    crate_name: &str,
    label: &str,
    stable_key: &str,
) -> Result<(), MemoryRegistryError> {
    defer_register_with_key_metadata(id, crate_name, label, stable_key, None, None)
}

/// Queue an explicit-key ID registration with optional schema metadata.
#[doc(hidden)]
pub fn defer_register_with_key_metadata(
    id: u8,
    crate_name: &str,
    label: &str,
    stable_key: &str,
    schema_version: Option<u32>,
    schema_fingerprint: Option<&str>,
) -> Result<(), MemoryRegistryError> {
    validate_non_internal_id(id)?;
    validate_id_excludes_layout_metadata(crate_name, id)?;
    validate_stable_key(stable_key)?;
    validate_schema_metadata(stable_key, schema_version, schema_fingerprint)?;
    validate_id_authority(id, crate_name, stable_key)?;

    // Queue ID registrations for runtime init to apply after ranges are reserved.
    PENDING_REGISTRATIONS.with_borrow_mut(|regs| {
        regs.push(PendingRegistration {
            id,
            crate_name: crate_name.to_string(),
            label: label.to_string(),
            stable_key: stable_key.to_string(),
            schema_version,
            schema_fingerprint: schema_fingerprint.map(str::to_string),
        });
    });

    Ok(())
}

/// Drain all queued range reservations in insertion order.
#[must_use]
pub(crate) fn drain_pending_ranges() -> Vec<(String, u8, u8)> {
    PENDING_RANGES.with_borrow_mut(std::mem::take)
}

/// Drain all queued ID registrations in insertion order.
#[must_use]
pub(crate) fn drain_pending_registrations() -> Vec<PendingRegistration> {
    PENDING_REGISTRATIONS.with_borrow_mut(std::mem::take)
}

//
// Test-only helpers
//

#[cfg(test)]
/// Clear registry and pending queues for isolated unit tests.
pub fn reset_for_tests() {
    reset_runtime_for_tests();
    ledger::reset_for_tests();
    crate::runtime::registry::reset_initialized_for_tests();
}

#[cfg(test)]
fn reset_runtime_for_tests() {
    RESERVED_RANGES.with_borrow_mut(Vec::clear);
    REGISTRY.with_borrow_mut(BTreeMap::clear);
    PENDING_RANGES.with_borrow_mut(Vec::clear);
    PENDING_REGISTRATIONS.with_borrow_mut(Vec::clear);
}

//
// Internal helpers
//

const fn ranges_overlap(a: MemoryRange, b: MemoryRange) -> bool {
    a.start <= b.end && b.start <= a.end
}

const INTERNAL_RESERVED_MEMORY_ID: u8 = u8::MAX;
const CANIC_FRAMEWORK_MAX_ID: u8 = 99;
const APPLICATION_MIN_ID: u8 = 100;

const MEMORY_LAYOUT_RESERVED_RANGE: MemoryRange = MemoryRange {
    start: ledger::MEMORY_LAYOUT_RESERVED_MIN,
    end: ledger::MEMORY_LAYOUT_RESERVED_MAX,
};

const fn validate_non_internal_id(id: u8) -> Result<(), MemoryRegistryError> {
    if id == INTERNAL_RESERVED_MEMORY_ID {
        return Err(MemoryRegistryError::ReservedInternalId { id });
    }
    Ok(())
}

fn fallback_stable_key(crate_name: &str, label: &str) -> String {
    format!(
        "legacy.{}.{}.v1",
        canonical_segment(crate_name),
        canonical_segment(label)
    )
}

fn validate_stable_key(stable_key: &str) -> Result<(), MemoryRegistryError> {
    if stable_key.is_empty() {
        return invalid_stable_key(stable_key, "must not be empty");
    }
    if stable_key.len() > 128 {
        return invalid_stable_key(stable_key, "must be at most 128 bytes");
    }
    if !stable_key.is_ascii() {
        return invalid_stable_key(stable_key, "must be ASCII");
    }
    if stable_key.bytes().any(|b| b.is_ascii_uppercase()) {
        return invalid_stable_key(stable_key, "must be lowercase");
    }
    if stable_key.contains(char::is_whitespace) {
        return invalid_stable_key(stable_key, "must not contain whitespace");
    }
    if stable_key.contains('/') || stable_key.contains('-') {
        return invalid_stable_key(stable_key, "must not contain slashes or hyphens");
    }
    if stable_key.starts_with('.') || stable_key.ends_with('.') {
        return invalid_stable_key(stable_key, "must not start or end with a dot");
    }

    let Some(version_index) = stable_key.rfind(".v") else {
        return invalid_stable_key(stable_key, "must end with .vN");
    };
    let version = &stable_key[version_index + 2..];
    if version.is_empty()
        || version.starts_with('0')
        || !version.bytes().all(|b| b.is_ascii_digit())
    {
        return invalid_stable_key(stable_key, "version suffix must be nonzero .vN");
    }

    let prefix = &stable_key[..version_index];
    if prefix.is_empty() {
        return invalid_stable_key(
            stable_key,
            "must contain at least one segment before version",
        );
    }

    for segment in prefix.split('.') {
        validate_stable_key_segment(stable_key, segment)?;
    }

    Ok(())
}

fn validate_stable_key_segment(stable_key: &str, segment: &str) -> Result<(), MemoryRegistryError> {
    if segment.is_empty() {
        return invalid_stable_key(stable_key, "must not contain empty segments");
    }
    let mut bytes = segment.bytes();
    let Some(first) = bytes.next() else {
        return invalid_stable_key(stable_key, "must not contain empty segments");
    };
    if !first.is_ascii_lowercase() {
        return invalid_stable_key(stable_key, "segments must start with a lowercase letter");
    }
    if !bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') {
        return invalid_stable_key(
            stable_key,
            "segments may contain only lowercase letters, digits, and underscores",
        );
    }
    Ok(())
}

fn validate_schema_metadata(
    stable_key: &str,
    schema_version: Option<u32>,
    schema_fingerprint: Option<&str>,
) -> Result<(), MemoryRegistryError> {
    if schema_version == Some(0) {
        return Err(MemoryRegistryError::InvalidSchemaMetadata {
            stable_key: stable_key.to_string(),
            reason: "schema_version must be greater than zero when present",
        });
    }

    let Some(fingerprint) = schema_fingerprint else {
        return Ok(());
    };

    if fingerprint.is_empty() {
        return Err(MemoryRegistryError::InvalidSchemaMetadata {
            stable_key: stable_key.to_string(),
            reason: "schema_fingerprint must not be empty when present",
        });
    }
    if fingerprint.len() > 256 {
        return Err(MemoryRegistryError::InvalidSchemaMetadata {
            stable_key: stable_key.to_string(),
            reason: "schema_fingerprint must be at most 256 bytes",
        });
    }
    if !fingerprint.is_ascii() {
        return Err(MemoryRegistryError::InvalidSchemaMetadata {
            stable_key: stable_key.to_string(),
            reason: "schema_fingerprint must be ASCII",
        });
    }
    if fingerprint.bytes().any(|byte| byte.is_ascii_control()) {
        return Err(MemoryRegistryError::InvalidSchemaMetadata {
            stable_key: stable_key.to_string(),
            reason: "schema_fingerprint must not contain ASCII control characters",
        });
    }

    Ok(())
}

fn invalid_stable_key<T>(stable_key: &str, reason: &'static str) -> Result<T, MemoryRegistryError> {
    Err(MemoryRegistryError::InvalidStableKey {
        stable_key: stable_key.to_string(),
        reason,
    })
}

fn validate_id_authority(
    id: u8,
    crate_name: &str,
    stable_key: &str,
) -> Result<(), MemoryRegistryError> {
    if stable_key.starts_with("canic.") {
        if !crate_name.starts_with("canic") {
            return Err(MemoryRegistryError::RangeAuthorityViolation {
                stable_key: stable_key.to_string(),
                id,
                reason: "canic.* keys may only be declared by Canic framework crates",
            });
        }

        if id <= CANIC_FRAMEWORK_MAX_ID {
            return Ok(());
        }

        return Err(MemoryRegistryError::RangeAuthorityViolation {
            stable_key: stable_key.to_string(),
            id,
            reason: "canic.* keys must use ids 0-99",
        });
    }

    if (APPLICATION_MIN_ID..INTERNAL_RESERVED_MEMORY_ID).contains(&id) {
        return Ok(());
    }

    Err(MemoryRegistryError::RangeAuthorityViolation {
        stable_key: stable_key.to_string(),
        id,
        reason: "application keys must use ids 100-254",
    })
}

fn canonical_segment(value: &str) -> String {
    let mut out = String::new();
    let mut last_was_underscore = false;

    for ch in value.chars().flat_map(char::to_lowercase) {
        if ch.is_ascii_lowercase() || ch.is_ascii_digit() {
            out.push(ch);
            last_was_underscore = false;
        } else if !last_was_underscore {
            out.push('_');
            last_was_underscore = true;
        }
    }

    let trimmed = out.trim_matches('_');
    if trimmed.is_empty() {
        return "unnamed".to_string();
    }
    if trimmed.as_bytes()[0].is_ascii_digit() {
        return format!("n_{trimmed}");
    }
    trimmed.to_string()
}

const fn validate_range_excludes_reserved_internal_id(
    _start: u8,
    end: u8,
) -> Result<(), MemoryRegistryError> {
    if end == INTERNAL_RESERVED_MEMORY_ID {
        return Err(MemoryRegistryError::ReservedInternalId {
            id: INTERNAL_RESERVED_MEMORY_ID,
        });
    }
    Ok(())
}

fn validate_range_excludes_layout_metadata(
    crate_name: &str,
    start: u8,
    end: u8,
) -> Result<(), MemoryRegistryError> {
    let requested = MemoryRange { start, end };
    if !ranges_overlap(requested, MEMORY_LAYOUT_RESERVED_RANGE) {
        return Ok(());
    }

    if crate_name == ledger::MEMORY_LAYOUT_LEDGER_OWNER
        && start == ledger::MEMORY_LAYOUT_RESERVED_MIN
        && end == ledger::MEMORY_LAYOUT_RESERVED_MAX
    {
        return Ok(());
    }

    Err(MemoryRegistryError::HistoricalRangeConflict {
        existing_crate: ledger::MEMORY_LAYOUT_LEDGER_OWNER.to_string(),
        existing_start: ledger::MEMORY_LAYOUT_RESERVED_MIN,
        existing_end: ledger::MEMORY_LAYOUT_RESERVED_MAX,
        new_crate: crate_name.to_string(),
        new_start: start,
        new_end: end,
    })
}

fn validate_id_excludes_layout_metadata(
    crate_name: &str,
    id: u8,
) -> Result<(), MemoryRegistryError> {
    if !MEMORY_LAYOUT_RESERVED_RANGE.contains(id)
        || crate_name == ledger::MEMORY_LAYOUT_LEDGER_OWNER
    {
        return Ok(());
    }

    Err(MemoryRegistryError::IdOwnedByOther {
        crate_name: crate_name.to_string(),
        id,
        owner: ledger::MEMORY_LAYOUT_LEDGER_OWNER.to_string(),
        owner_start: ledger::MEMORY_LAYOUT_RESERVED_MIN,
        owner_end: ledger::MEMORY_LAYOUT_RESERVED_MAX,
    })
}

fn validate_registration_range(crate_name: &str, id: u8) -> Result<(), MemoryRegistryError> {
    let mut has_range = false;
    let mut owner_match = false;
    let mut owner_for_id: Option<(String, MemoryRange)> = None;

    RESERVED_RANGES.with_borrow(|ranges| {
        for (owner, range) in ranges {
            if owner == crate_name {
                has_range = true;
                if range.contains(id) {
                    owner_match = true;
                    break;
                }
            }

            if owner_for_id.is_none() && range.contains(id) {
                owner_for_id = Some((owner.clone(), *range));
            }
        }
    });

    if owner_match {
        return Ok(());
    }

    if !has_range {
        return Err(MemoryRegistryError::NoReservedRange {
            crate_name: crate_name.to_string(),
            id,
        });
    }

    if let Some((owner, range)) = owner_for_id {
        return Err(MemoryRegistryError::IdOwnedByOther {
            crate_name: crate_name.to_string(),
            id,
            owner,
            owner_start: range.start,
            owner_end: range.end,
        });
    }

    Err(MemoryRegistryError::IdOutOfRange {
        crate_name: crate_name.to_string(),
        id,
    })
}

///
/// TESTS
///

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn allows_in_range() {
        reset_for_tests();

        MemoryRegistry::reserve_range("crate_a", 100, 102).expect("reserve range");
        MemoryRegistry::register(101, "crate_a", "slot").expect("register in range");
    }

    #[test]
    fn rejects_unreserved() {
        reset_for_tests();

        let err = MemoryRegistry::register(100, "crate_a", "slot").expect_err("missing range");
        assert!(matches!(err, MemoryRegistryError::NoReservedRange { .. }));
    }

    #[test]
    fn rejects_other_owner() {
        reset_for_tests();

        MemoryRegistry::reserve_range("crate_a", 100, 102).expect("reserve range A");
        MemoryRegistry::reserve_range("crate_b", 110, 112).expect("reserve range B");

        let err = MemoryRegistry::register(101, "crate_b", "slot").expect_err("owned by other");
        assert!(matches!(err, MemoryRegistryError::IdOwnedByOther { .. }));
    }

    #[test]
    fn export_ids_by_range_groups_entries() {
        reset_for_tests();

        MemoryRegistry::reserve_range("crate_a", 100, 102).expect("reserve range A");
        MemoryRegistry::reserve_range("crate_b", 110, 112).expect("reserve range B");
        MemoryRegistry::register(100, "crate_a", "a100").expect("register a100");
        MemoryRegistry::register(111, "crate_b", "b111").expect("register b111");

        let snapshots = MemoryRegistry::export_ids_by_range();
        assert_eq!(snapshots.len(), 2);
        assert_eq!(snapshots[0].entries.len(), 1);
        assert_eq!(snapshots[1].entries.len(), 1);
    }

    #[test]
    fn historical_range_conflict_survives_runtime_reset() {
        reset_for_tests();

        MemoryRegistry::reserve_range("crate_a", 100, 102).expect("reserve range A");
        reset_runtime_for_tests();

        let err = MemoryRegistry::reserve_range("crate_b", 101, 103)
            .expect_err("historical range overlap should fail");
        assert!(matches!(
            err,
            MemoryRegistryError::HistoricalRangeConflict { .. }
        ));
    }

    #[test]
    fn historical_id_conflict_survives_runtime_reset() {
        reset_for_tests();

        MemoryRegistry::reserve_range("crate_a", 100, 102).expect("reserve range A");
        MemoryRegistry::register_with_key_metadata(
            100,
            "crate_a",
            "slot",
            "app.crate_a.slot.v1",
            Some(1),
            Some("sha256:aaa"),
        )
        .expect("register slot");
        reset_runtime_for_tests();

        MemoryRegistry::reserve_range("crate_a", 100, 102).expect("reserve range A again");
        let err =
            MemoryRegistry::register_with_key(100, "crate_a", "other", "app.crate_a.other.v1")
                .expect_err("historical id label drift should fail");
        assert!(matches!(
            err,
            MemoryRegistryError::HistoricalIdConflict { .. }
        ));
    }

    #[test]
    fn stable_key_allows_owner_and_label_metadata_drift() {
        reset_for_tests();

        MemoryRegistry::reserve_range("crate_a", 100, 102).expect("reserve range A");
        MemoryRegistry::register_with_key(100, "crate_a", "slot", "app.crate_a.slot.v1")
            .expect("register slot");
        reset_runtime_for_tests();

        MemoryRegistry::reserve_range("crate_renamed", 100, 102).expect("reserve range A again");
        MemoryRegistry::register_with_key_metadata(
            100,
            "crate_renamed",
            "SlotRenamed",
            "app.crate_a.slot.v1",
            Some(2),
            Some("sha256:bbb"),
        )
        .expect("stable key should survive owner/label drift");

        let entry = MemoryRegistry::get(100).expect("entry should exist");
        assert_eq!(entry.crate_name, "crate_renamed");
        assert_eq!(entry.label, "SlotRenamed");
        assert_eq!(entry.stable_key, "app.crate_a.slot.v1");
        assert_eq!(entry.schema_version, Some(2));
        assert_eq!(entry.schema_fingerprint.as_deref(), Some("sha256:bbb"));
    }

    #[test]
    fn rejects_invalid_schema_metadata() {
        reset_for_tests();

        MemoryRegistry::reserve_range("crate_a", 100, 102).expect("reserve range A");
        let err = MemoryRegistry::register_with_key_metadata(
            100,
            "crate_a",
            "slot",
            "app.crate_a.slot.v1",
            Some(0),
            None,
        )
        .expect_err("zero schema version should fail");
        assert!(matches!(
            err,
            MemoryRegistryError::InvalidSchemaMetadata { .. }
        ));

        let err = MemoryRegistry::register_with_key_metadata(
            100,
            "crate_a",
            "slot",
            "app.crate_a.slot.v1",
            Some(1),
            Some("fingerprint\nwith-control"),
        )
        .expect_err("control characters should fail");
        assert!(matches!(
            err,
            MemoryRegistryError::InvalidSchemaMetadata { .. }
        ));
    }

    #[test]
    fn rejects_non_canic_key_below_application_range() {
        reset_for_tests();

        MemoryRegistry::reserve_range("crate_a", 1, 4).expect("reserve low framework range");
        let err = MemoryRegistry::register_with_key(1, "crate_a", "slot", "app.crate_a.slot.v1")
            .expect_err("application key below 100 should fail");
        assert!(matches!(
            err,
            MemoryRegistryError::RangeAuthorityViolation { .. }
        ));
    }

    #[test]
    fn rejects_canic_key_above_framework_range() {
        reset_for_tests();

        MemoryRegistry::reserve_range("canic-core", 100, 102).expect("reserve app range");
        let err =
            MemoryRegistry::register_with_key(100, "canic-core", "slot", "canic.core.slot.v1")
                .expect_err("canic key above 99 should fail");
        assert!(matches!(
            err,
            MemoryRegistryError::RangeAuthorityViolation { .. }
        ));
    }

    #[test]
    fn rejects_canic_namespace_from_non_framework_crate() {
        reset_for_tests();

        MemoryRegistry::reserve_range("crate_a", 11, 12).expect("reserve framework range");
        let err = MemoryRegistry::register_with_key(11, "crate_a", "slot", "canic.core.slot.v1")
            .expect_err("non-framework crate must not claim canic namespace");
        assert!(matches!(
            err,
            MemoryRegistryError::RangeAuthorityViolation { .. }
        ));
    }

    #[test]
    fn rejects_non_canonical_stable_key() {
        reset_for_tests();

        MemoryRegistry::reserve_range("crate_a", 100, 102).expect("reserve range A");
        let err = MemoryRegistry::register_with_key(100, "crate_a", "slot", "App.Crate.Slot.v1")
            .expect_err("uppercase stable key should fail");
        assert!(matches!(err, MemoryRegistryError::InvalidStableKey { .. }));
    }

    #[test]
    fn internal_layout_ledger_uses_only_id_zero_self_record() {
        reset_for_tests();

        MemoryRegistry::reserve_internal_layout_ledger().expect("reserve ledger");

        assert_eq!(
            MemoryRegistry::export_ranges(),
            vec![(
                ledger::MEMORY_LAYOUT_LEDGER_OWNER.to_string(),
                MemoryRange { start: 0, end: 0 },
            )]
        );
        assert_eq!(
            MemoryRegistry::get(0).map(|entry| entry.stable_key),
            Some(ledger::MEMORY_LAYOUT_LEDGER_STABLE_KEY.to_string())
        );
        for id in 1..=4 {
            assert!(MemoryRegistry::get(id).is_none());
        }
    }

    #[test]
    fn historical_stable_key_conflict_survives_runtime_reset() {
        reset_for_tests();

        MemoryRegistry::reserve_range("crate_a", 100, 102).expect("reserve range A");
        MemoryRegistry::register_with_key(100, "crate_a", "slot", "app.crate_a.slot.v1")
            .expect("register slot");
        reset_runtime_for_tests();

        MemoryRegistry::reserve_range("crate_a", 100, 102).expect("reserve range A again");
        let err = MemoryRegistry::register_with_key(101, "crate_a", "slot", "app.crate_a.slot.v1")
            .expect_err("stable key must not move to another ID");
        assert!(matches!(
            err,
            MemoryRegistryError::HistoricalStableKeyConflict { .. }
        ));
    }

    #[test]
    fn rejects_internal_reserved_id_on_register() {
        reset_for_tests();

        MemoryRegistry::reserve_range("crate_a", 5, 254).expect("reserve range");
        let err = MemoryRegistry::register(u8::MAX, "crate_a", "slot")
            .expect_err("reserved id should be rejected");
        assert!(matches!(
            err,
            MemoryRegistryError::ReservedInternalId { .. }
        ));
    }

    #[test]
    fn rejects_layout_metadata_range_reservation() {
        reset_for_tests();

        let err = MemoryRegistry::reserve_range("crate_a", 0, 4)
            .expect_err("layout metadata range must not be reservable by applications");
        assert!(matches!(
            err,
            MemoryRegistryError::HistoricalRangeConflict { .. }
        ));
    }

    #[test]
    fn rejects_layout_metadata_range_overlap() {
        reset_for_tests();

        let err = MemoryRegistry::reserve_range("crate_a", 0, 8)
            .expect_err("layout metadata overlap must not be reservable by applications");
        assert!(matches!(
            err,
            MemoryRegistryError::HistoricalRangeConflict { .. }
        ));
    }

    #[test]
    fn rejects_layout_metadata_range_on_deferred_reservation() {
        reset_for_tests();

        let err = defer_reserve_range("crate_a", 0, 4)
            .expect_err("layout metadata range should fail before init");
        assert!(matches!(
            err,
            MemoryRegistryError::HistoricalRangeConflict { .. }
        ));
    }

    #[test]
    fn rejects_layout_metadata_id_on_register() {
        reset_for_tests();

        MemoryRegistry::reserve_range("crate_a", 100, 108).expect("reserve range");
        let err = MemoryRegistry::register(0, "crate_a", "slot")
            .expect_err("layout metadata ID must not be registrable by applications");
        assert!(matches!(err, MemoryRegistryError::IdOwnedByOther { .. }));
    }

    #[test]
    fn rejects_layout_metadata_id_on_deferred_register() {
        reset_for_tests();

        let err = defer_register(0, "crate_a", "slot")
            .expect_err("layout metadata ID should fail before init");
        assert!(matches!(err, MemoryRegistryError::IdOwnedByOther { .. }));
    }

    #[test]
    fn rejects_internal_reserved_id_on_range_reservation() {
        reset_for_tests();

        let err = MemoryRegistry::reserve_range("crate_a", 250, u8::MAX)
            .expect_err("reserved internal id must not be reservable");
        assert!(matches!(
            err,
            MemoryRegistryError::ReservedInternalId { .. }
        ));
    }

    #[test]
    fn rejects_internal_reserved_id_on_deferred_register() {
        reset_for_tests();

        let err = defer_register(u8::MAX, "crate_a", "slot")
            .expect_err("reserved id should fail before init");
        assert!(matches!(
            err,
            MemoryRegistryError::ReservedInternalId { .. }
        ));
    }

    #[test]
    fn rejects_internal_reserved_id_on_deferred_range_reservation() {
        reset_for_tests();

        let err = defer_reserve_range("crate_a", 240, u8::MAX)
            .expect_err("reserved id should fail before init");
        assert!(matches!(
            err,
            MemoryRegistryError::ReservedInternalId { .. }
        ));
    }
}