canic-core 0.39.13

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
use super::super::manager::{self, RawStableMemoryState};
use super::super::registry::{
    MemoryRange, MemoryRangeEntry, MemoryRangeSnapshot, MemoryRegistry, MemoryRegistryEntry,
    MemoryRegistryError, PendingRegistration, drain_pending_ranges, drain_pending_registrations,
};
use super::super::{ledger, policy::CanicMemoryManagerPolicy};
use ic_memory::{
    AllocationDeclaration, AllocationPolicy, AllocationSlotDescriptor, AllocationValidationError,
    DeclarationSnapshot, DeclarationSnapshotError, MemoryManagerSlotError, SchemaMetadata,
    StableKey, ValidatedAllocations, validate_allocations,
};
#[cfg(test)]
use std::cell::Cell;
#[cfg(not(test))]
use std::sync::atomic::{AtomicBool, Ordering};
use std::{cell::RefCell, collections::BTreeMap};

#[cfg(not(test))]
static MEMORY_REGISTRY_INITIALIZED: AtomicBool = AtomicBool::new(false);

#[cfg(test)]
thread_local! {
    static MEMORY_REGISTRY_INITIALIZED: Cell<bool> = const { Cell::new(false) };
}

thread_local! {
    static VALIDATED_ALLOCATIONS: RefCell<Option<ValidatedAllocations>> = const {
        RefCell::new(None)
    };
}

///
/// MemoryRegistryInitSummary
///
/// Substrate-level summary of registry state after initialization.
/// This is intended for diagnostics and testing only.
/// It is NOT a stable API contract or external view.
///

#[derive(Debug)]
pub struct MemoryRegistryInitSummary {
    /// Reserved owner ranges after initialization completes.
    pub ranges: Vec<(String, MemoryRange)>,
    /// Registered memory IDs after initialization completes.
    pub entries: Vec<(u8, MemoryRegistryEntry)>,
}

///
/// MemoryRegistryRuntime
///
/// Substrate runtime controller responsible for initializing the
/// global memory registry.
///
/// This type performs mechanical coordination only:
/// - ordering
/// - conflict detection
/// - idempotent initialization
///
/// It encodes no application semantics.
///
pub struct MemoryRegistryRuntime;

impl MemoryRegistryRuntime {
    /// Initialize the memory registry.
    ///
    /// - Optionally reserves an initial range for the caller.
    /// - Applies all deferred range reservations.
    /// - Applies all deferred ID registrations.
    ///
    /// This function is idempotent for the same initial range.
    pub fn init(
        initial_range: Option<(&str, u8, u8)>,
    ) -> Result<MemoryRegistryInitSummary, MemoryRegistryError> {
        let raw_state = manager::classify_raw_stable_memory();
        validate_raw_stable_memory_state(raw_state)?;
        ledger::validate_bootstrap_state_before_cell_init(raw_state)?;

        // Apply deferred range reservations deterministically
        let mut ranges = drain_pending_ranges();
        ranges.sort_by_key(|(_, start, _)| *start);

        // Apply deferred registrations deterministically
        let mut regs = drain_pending_registrations();
        regs.sort_by_key(|registration| registration.id);
        let has_runtime_declarations = !regs.is_empty();
        let declaration_snapshot = validate_current_registration_snapshot(&regs)?;

        MemoryRegistry::reserve_internal_layout_ledger()?;
        let validated_allocations =
            validate_pending_ledger_claims(initial_range, &ranges, &regs, declaration_snapshot)?;

        // Reserve the caller's initial range first (if provided)
        if let Some((crate_name, start, end)) = initial_range {
            MemoryRegistry::reserve_range(crate_name, start, end)?;
        }

        for (crate_name, start, end) in ranges {
            MemoryRegistry::reserve_range(&crate_name, start, end)?;
        }

        for registration in regs {
            MemoryRegistry::register_with_key_metadata(
                registration.id,
                &registration.crate_name,
                &registration.label,
                &registration.stable_key,
                registration.schema_version,
                registration.schema_fingerprint.as_deref(),
            )?;
        }

        let summary = MemoryRegistryInitSummary {
            ranges: MemoryRegistry::export_ranges(),
            entries: MemoryRegistry::export(),
        };
        if !Self::is_initialized() || has_runtime_declarations {
            set_validated_allocations(Some(validated_allocations));
        }
        set_initialized(true);

        Ok(summary)
    }

    /// Return whether the memory registry has completed initialization.
    #[must_use]
    pub fn is_initialized() -> bool {
        initialized()
    }

    /// Snapshot all registry entries.
    #[must_use]
    pub fn snapshot_entries() -> Vec<(u8, MemoryRegistryEntry)> {
        MemoryRegistry::export()
    }

    /// Snapshot all reserved memory ranges.
    #[must_use]
    pub fn snapshot_ranges() -> Vec<(String, MemoryRange)> {
        MemoryRegistry::export_ranges()
    }

    /// Snapshot all reserved memory ranges with owners.
    #[must_use]
    pub fn snapshot_range_entries() -> Vec<MemoryRangeEntry> {
        MemoryRegistry::export_range_entries()
    }

    /// Snapshot registry entries grouped by range.
    #[must_use]
    pub fn snapshot_ids_by_range() -> Vec<MemoryRangeSnapshot> {
        MemoryRegistry::export_ids_by_range()
    }

    /// Retrieve a single registry entry by ID.
    #[must_use]
    pub fn get(id: u8) -> Option<MemoryRegistryEntry> {
        MemoryRegistry::get(id)
    }

    /// Return the sealed validated allocation set published by bootstrap.
    pub fn validated_allocations() -> Result<ValidatedAllocations, MemoryRegistryError> {
        if !Self::is_initialized() {
            return Err(MemoryRegistryError::RegistryNotBootstrapped);
        }

        VALIDATED_ALLOCATIONS.with_borrow(|validated| {
            validated
                .clone()
                .ok_or(MemoryRegistryError::RegistryNotBootstrapped)
        })
    }

    /// Apply any newly deferred registrations/ranges after runtime init.
    ///
    /// This is a no-op until initialization has completed. Once initialized,
    /// this drains pending range/ID registrations so lazily touched statics can
    /// become visible during the same request.
    pub fn commit_pending_if_initialized() -> Result<(), MemoryRegistryError> {
        if !Self::is_initialized() || super::is_eager_tls_initializing() {
            return Ok(());
        }

        let ranges = drain_pending_ranges();
        let regs = drain_pending_registrations();

        if ranges.is_empty() && regs.is_empty() {
            return Ok(());
        }

        Err(MemoryRegistryError::RegistrationAfterBootstrap {
            ranges: ranges.len(),
            registrations: regs.len(),
        })
    }
}

const fn validate_raw_stable_memory_state(
    raw_state: RawStableMemoryState,
) -> Result<(), MemoryRegistryError> {
    match raw_state {
        RawStableMemoryState::Empty | RawStableMemoryState::MemoryManager => Ok(()),
        RawStableMemoryState::ForeignOrCorrupt => Err(MemoryRegistryError::LedgerCorrupt {
            reason: "foreign or corrupt raw stable memory state",
        }),
    }
}

fn validate_current_registration_snapshot(
    regs: &[PendingRegistration],
) -> Result<DeclarationSnapshot, MemoryRegistryError> {
    let declarations = regs
        .iter()
        .map(allocation_declaration_from_pending)
        .collect::<Result<Vec<_>, _>>()?;

    DeclarationSnapshot::new(declarations).map_err(memory_registry_error_from_snapshot_error)
}

fn allocation_declaration_from_pending(
    registration: &PendingRegistration,
) -> Result<AllocationDeclaration, MemoryRegistryError> {
    let slot = AllocationSlotDescriptor::memory_manager_checked(registration.id)
        .map_err(memory_registry_error_from_slot_error)?;
    let schema = SchemaMetadata::new(
        registration.schema_version,
        registration.schema_fingerprint.clone(),
    )
    .map_err(|err| MemoryRegistryError::InvalidSchemaMetadata {
        stable_key: registration.stable_key.clone(),
        reason: super::super::registry::schema_metadata_reason(err),
    })?;

    AllocationDeclaration::new(
        &registration.stable_key,
        slot,
        Some(registration.label.clone()),
        schema,
    )
    .map_err(memory_registry_error_from_snapshot_error)
}

fn memory_registry_error_from_snapshot_error(err: DeclarationSnapshotError) -> MemoryRegistryError {
    match err {
        DeclarationSnapshotError::Key(err) => MemoryRegistryError::InvalidStableKey {
            stable_key: err.stable_key,
            reason: err.reason,
        },
        DeclarationSnapshotError::SchemaMetadata(err) => {
            MemoryRegistryError::InvalidSchemaMetadata {
                stable_key: "<unknown>".to_string(),
                reason: super::super::registry::schema_metadata_reason(err),
            }
        }
        DeclarationSnapshotError::DuplicateStableKey(key) => {
            MemoryRegistryError::DuplicateStableKey(key.into_string())
        }
        DeclarationSnapshotError::DuplicateSlot(slot) => match slot.memory_manager_id() {
            Ok(id) => MemoryRegistryError::DuplicateId(id),
            Err(err) => memory_registry_error_from_slot_error(err),
        },
    }
}

fn memory_registry_error_from_slot_error(err: MemoryManagerSlotError) -> MemoryRegistryError {
    match err {
        MemoryManagerSlotError::InvalidMemoryManagerId { id } => {
            MemoryRegistryError::ReservedInternalId { id }
        }
        MemoryManagerSlotError::UnsupportedSlot
        | MemoryManagerSlotError::UnsupportedSubstrate { .. }
        | MemoryManagerSlotError::UnsupportedDescriptorVersion { .. } => {
            MemoryRegistryError::LedgerCorrupt {
                reason: "unsupported MemoryManager allocation slot descriptor",
            }
        }
    }
}

fn validate_pending_ledger_claims(
    initial_range: Option<(&str, u8, u8)>,
    ranges: &[(String, u8, u8)],
    regs: &[PendingRegistration],
    declaration_snapshot: DeclarationSnapshot,
) -> Result<ValidatedAllocations, MemoryRegistryError> {
    if let Some((owner, start, end)) = initial_range {
        ledger::validate_range(owner, MemoryRange { start, end })?;
    }

    for (owner, start, end) in ranges {
        ledger::validate_range(
            owner,
            MemoryRange {
                start: *start,
                end: *end,
            },
        )?;
    }

    for registration in regs {
        ledger::validate_entry(
            registration.id,
            &registration.crate_name,
            &registration.label,
            &registration.stable_key,
        )?;
    }

    let historical_ledger = ledger::try_allocation_ledger_snapshot()?;
    let policy = RuntimeDeclarationPolicy::from_registrations(regs);
    validate_allocations(&historical_ledger, declaration_snapshot, &policy)
        .map_err(|err| memory_registry_error_from_allocation_validation(err, regs))
}

///
/// RuntimeDeclarationPolicy
///
/// Adapter that lets generic `ic-memory` validation apply Canic's per-crate
/// namespace/range policy to a sealed multi-crate declaration snapshot.
struct RuntimeDeclarationPolicy {
    declaring_crates: BTreeMap<String, String>,
}

impl RuntimeDeclarationPolicy {
    fn from_registrations(regs: &[PendingRegistration]) -> Self {
        let declaring_crates = regs
            .iter()
            .map(|registration| {
                (
                    registration.stable_key.clone(),
                    registration.crate_name.clone(),
                )
            })
            .collect();
        Self { declaring_crates }
    }
}

impl AllocationPolicy for RuntimeDeclarationPolicy {
    type Error = MemoryRegistryError;

    fn validate_key(&self, _key: &StableKey) -> Result<(), Self::Error> {
        Ok(())
    }

    fn validate_slot(
        &self,
        key: &StableKey,
        slot: &AllocationSlotDescriptor,
    ) -> Result<(), Self::Error> {
        let declaring_crate =
            self.declaring_crates
                .get(key.as_str())
                .ok_or(MemoryRegistryError::LedgerCorrupt {
                    reason: "validated declaration is missing runtime crate ownership metadata",
                })?;
        let policy = CanicMemoryManagerPolicy::for_declaring_crate(declaring_crate);
        AllocationPolicy::validate_slot(&policy, key, slot)
    }

    fn validate_reserved_slot(
        &self,
        key: &StableKey,
        slot: &AllocationSlotDescriptor,
    ) -> Result<(), Self::Error> {
        let declaring_crate =
            self.declaring_crates
                .get(key.as_str())
                .ok_or(MemoryRegistryError::LedgerCorrupt {
                    reason: "validated declaration is missing runtime crate ownership metadata",
                })?;
        let policy = CanicMemoryManagerPolicy::for_declaring_crate(declaring_crate);
        AllocationPolicy::validate_reserved_slot(&policy, key, slot)
    }
}

fn memory_registry_error_from_allocation_validation(
    err: AllocationValidationError<MemoryRegistryError>,
    regs: &[PendingRegistration],
) -> MemoryRegistryError {
    match err {
        AllocationValidationError::Policy(err) => err,
        AllocationValidationError::StableKeySlotConflict {
            stable_key,
            historical_slot,
            declared_slot,
        } => MemoryRegistryError::HistoricalStableKeyConflict {
            stable_key: stable_key.into_string(),
            existing_id: memory_manager_id_from_allocation_slot(&historical_slot),
            new_id: memory_manager_id_from_allocation_slot(&declared_slot),
        },
        AllocationValidationError::SlotStableKeyConflict {
            slot,
            historical_key,
            declared_key,
        } => {
            let requested = regs
                .iter()
                .find(|registration| registration.stable_key == declared_key.as_str());
            MemoryRegistryError::HistoricalIdConflict {
                id: memory_manager_id_from_allocation_slot(&slot),
                existing_crate: historical_key.as_str().to_string(),
                existing_label: historical_key.as_str().to_string(),
                new_crate: requested.map_or_else(
                    || declared_key.as_str().to_string(),
                    |reg| reg.crate_name.clone(),
                ),
                new_label: requested.map_or_else(
                    || declared_key.as_str().to_string(),
                    |reg| reg.label.clone(),
                ),
                new_stable_key: declared_key.into_string(),
            }
        }
        AllocationValidationError::RetiredAllocation { .. } => MemoryRegistryError::LedgerCorrupt {
            reason: "allocation was explicitly retired and cannot be redeclared",
        },
    }
}

fn memory_manager_id_from_allocation_slot(slot: &AllocationSlotDescriptor) -> u8 {
    slot.memory_manager_id()
        .unwrap_or(ic_memory::MEMORY_MANAGER_INVALID_ID)
}

#[cfg(test)]
pub(crate) fn reset_initialized_for_tests() {
    set_initialized(false);
    set_validated_allocations(None);
}

#[cfg(not(test))]
fn initialized() -> bool {
    MEMORY_REGISTRY_INITIALIZED.load(Ordering::SeqCst)
}

#[cfg(test)]
fn initialized() -> bool {
    MEMORY_REGISTRY_INITIALIZED.with(Cell::get)
}

#[cfg(not(test))]
fn set_initialized(value: bool) {
    MEMORY_REGISTRY_INITIALIZED.store(value, Ordering::SeqCst);
}

#[cfg(test)]
fn set_initialized(value: bool) {
    MEMORY_REGISTRY_INITIALIZED.with(|initialized| initialized.set(value));
}

fn set_validated_allocations(value: Option<ValidatedAllocations>) {
    VALIDATED_ALLOCATIONS.with_borrow_mut(|validated| {
        *validated = value;
    });
}

///
/// TESTS
///

#[cfg(test)]
mod tests {
    use super::*;
    use crate::memory::registry::{
        defer_register, defer_register_with_key, defer_reserve_range, reset_for_tests,
    };

    #[test]
    fn init_applies_initial_and_pending() {
        reset_for_tests();
        defer_reserve_range("crate_b", 110, 111).expect("defer range");
        defer_register(110, "crate_b", "B110").expect("defer register");

        let summary =
            MemoryRegistryRuntime::init(Some(("crate_a", 100, 102))).expect("init should succeed");

        assert_eq!(summary.ranges.len(), 3);
        assert_eq!(summary.entries.len(), 2);
        assert!(summary.entries.iter().any(|(id, entry)| {
            *id == 110 && entry.crate_name == "crate_b" && entry.label == "B110"
        }));
    }

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

        MemoryRegistryRuntime::init(Some(("crate_a", 100, 102)))
            .expect("first init should succeed");
        MemoryRegistryRuntime::init(Some(("crate_a", 100, 102)))
            .expect("second init should succeed");
    }

    #[test]
    fn init_returns_error_on_conflict() {
        reset_for_tests();
        defer_reserve_range("crate_a", 100, 102).expect("defer range A");
        defer_reserve_range("crate_b", 102, 104).expect("defer range B");

        let err = MemoryRegistryRuntime::init(None).unwrap_err();
        assert!(matches!(err, MemoryRegistryError::Overlap { .. }));
    }

    #[test]
    fn init_rejects_duplicate_current_snapshot_id_before_user_ledger_mutation() {
        reset_for_tests();
        defer_reserve_range("crate_a", 100, 102).expect("defer range");
        defer_register_with_key(100, "crate_a", "slot_a", "app.crate_a.slot_a.v1")
            .expect("defer first register");
        defer_register_with_key(100, "crate_a", "slot_b", "app.crate_a.slot_b.v1")
            .expect("defer second register");

        let err = MemoryRegistryRuntime::init(None)
            .expect_err("duplicate id in one snapshot should fail");
        assert!(matches!(err, MemoryRegistryError::DuplicateId(100)));
        assert!(
            !MemoryRegistry::export_historical()
                .iter()
                .any(|(id, _)| *id == 100)
        );
    }

    #[test]
    fn init_rejects_duplicate_current_snapshot_stable_key_before_user_ledger_mutation() {
        reset_for_tests();
        defer_reserve_range("crate_a", 100, 102).expect("defer range");
        defer_register_with_key(100, "crate_a", "slot_a", "app.crate_a.slot.v1")
            .expect("defer first register");
        defer_register_with_key(101, "crate_a", "slot_b", "app.crate_a.slot.v1")
            .expect("defer second register");

        let err = MemoryRegistryRuntime::init(None)
            .expect_err("duplicate stable key in one snapshot should fail");
        assert!(
            matches!(err, MemoryRegistryError::DuplicateStableKey(key) if key == "app.crate_a.slot.v1")
        );
        assert!(
            !MemoryRegistry::export_historical()
                .iter()
                .any(|(_, entry)| entry.stable_key == "app.crate_a.slot.v1")
        );
    }

    #[test]
    fn init_rejects_exact_duplicate_current_snapshot_declaration() {
        reset_for_tests();
        defer_reserve_range("crate_a", 100, 102).expect("defer range");
        defer_register_with_key(100, "crate_a", "slot", "app.crate_a.slot.v1")
            .expect("defer first register");
        defer_register_with_key(100, "crate_a", "slot", "app.crate_a.slot.v1")
            .expect("defer second register");

        let err = MemoryRegistryRuntime::init(None)
            .expect_err("exact duplicate declaration in one snapshot should fail");
        assert!(matches!(err, MemoryRegistryError::DuplicateId(100)));
    }

    #[test]
    fn init_rejects_historical_conflict_before_user_ledger_mutation() {
        reset_for_tests();
        ledger::record_range(
            "crate_a",
            MemoryRange {
                start: 100,
                end: 102,
            },
        )
        .expect("record historical range");
        ledger::record_entry(100, "crate_a", "slot", "app.crate_a.slot.v1", None, None)
            .expect("record historical entry");
        defer_reserve_range("crate_a", 100, 102).expect("defer range");
        defer_register_with_key(101, "crate_a", "new_slot", "app.crate_a.new_slot.v1")
            .expect("defer non-conflicting register");
        defer_register_with_key(102, "crate_a", "moved_slot", "app.crate_a.slot.v1")
            .expect("defer conflicting register");

        let err = MemoryRegistryRuntime::init(None)
            .expect_err("historical stable key movement should fail before commit");
        assert!(matches!(
            err,
            MemoryRegistryError::HistoricalStableKeyConflict { .. }
        ));
        assert!(
            !MemoryRegistry::export_historical()
                .iter()
                .any(|(id, _)| *id == 101)
        );
    }

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

        MemoryRegistryRuntime::init(Some(("core", 100, 109))).expect("init should succeed");
        defer_reserve_range("late", 110, 120).expect("defer late range");
        defer_register(112, "late", "late_slot").expect("defer late register");

        let err = MemoryRegistryRuntime::commit_pending_if_initialized()
            .expect_err("late pending commit should fail after bootstrap seal");
        assert!(matches!(
            err,
            MemoryRegistryError::RegistrationAfterBootstrap {
                ranges: 1,
                registrations: 1,
            }
        ));
        assert!(MemoryRegistryRuntime::get(112).is_none());
    }
}