ic-memory 0.25.5

Durable stable-memory allocation governance for Internet Computer canisters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
use super::request_tests::snapshot;
use super::*;
use crate::{
    AllocationPolicy, BootstrapAdmissionError as AdmissionError, MemoryManagerSlot, StableKey,
};
use ic_stable_structures::VectorMemory;
use std::cell::Cell as Counter;

#[derive(Default)]
pub(super) struct AdmissionPolicy {
    pub calls: Counter<usize>,
    pub selections: Vec<(&'static str, &'static str)>,
    pub discover: bool,
    pub reject: bool,
    pub deny_journals: bool,
}

impl AllocationPolicy for AdmissionPolicy {
    type Error = &'static str;
    fn validate_key(&self, key: &StableKey) -> Result<(), Self::Error> {
        if self.deny_journals && key.as_str().ends_with(".journal.v1") {
            Err("revoked")
        } else {
            Ok(())
        }
    }
    fn validate_slot(&self, _: &StableKey, _: &MemoryManagerSlot) -> Result<(), Self::Error> {
        Ok(())
    }
    fn validate_reserved_slot(
        &self,
        _: &StableKey,
        _: &MemoryManagerSlot,
    ) -> Result<(), Self::Error> {
        Ok(())
    }
}
impl RuntimeBootstrapPolicy for AdmissionPolicy {
    fn runtime_bootstrap_identity(&self) -> Result<PolicyIdentity, crate::PolicyIdentityError> {
        PolicyIdentity::new("test.admission", 1)
    }
    fn prepare_bootstrap(&self, admission: &mut BootstrapAdmission<'_>) -> Result<(), Self::Error> {
        self.calls.set(self.calls.get() + 1);
        if self.reject {
            return Err("identity rejected");
        }
        let mut selected = Vec::new();
        if self.discover {
            for record in admission.recovered_allocations() {
                if record.stable_key.as_str().ends_with(".control.v1")
                    && !admission.is_declared(record.stable_key)
                {
                    return Err("identity rejected");
                }
                if record.stable_key.as_str().ends_with(".journal.v1")
                    && !admission.is_declared(record.stable_key)
                {
                    selected.push(record.stable_key.clone());
                }
            }
        }
        for key in selected {
            let _ = admission.include_historical("app", key.as_str());
        }
        // Deliberately ignore returned errors: the attempt must still fail closed.
        for (authority, key) in &self.selections {
            let _ = admission.include_historical(authority, key);
        }
        Ok(())
    }
}

const CONTROL: &str = "app.main.control.v1";
const JOURNAL: &str = "app.old.journal.v1";

#[test]
fn declared_membership_covers_original_inputs_and_retains_poisoned_selections() {
    let runtime = MemoryRuntime::new(seeded()).unwrap();
    let recovered = runtime
        .ledger_record_from_memory()
        .unwrap()
        .store()
        .recover()
        .unwrap();
    // Neither fixed registrations nor requests arrive in canonical key order.
    let original = snapshot(
        &["app.z.v1", "app.a.v1"],
        "app",
        100,
        110,
        &[("zoo.fixed.v1", 105), ("app.fixed.v1", 104)],
    );
    let mut admission = BootstrapAdmission::new(recovered.ledger(), &original);
    for name in [
        crate::IC_MEMORY_LEDGER_STABLE_KEY,
        "app.a.v1",
        "app.z.v1",
        "app.fixed.v1",
        "zoo.fixed.v1",
    ] {
        assert!(admission.is_declared(&StableKey::parse(name).unwrap()));
    }
    for name in [CONTROL, JOURNAL, "ic_memory.other.v1", "app.unknown.v1"] {
        assert!(!admission.is_declared(&StableKey::parse(name).unwrap()));
    }
    // Selection order is deliberately descending; it is independent of sealing.
    admission.include_historical("app", JOURNAL).unwrap();
    admission.include_historical("app", CONTROL).unwrap();
    let failure = admission
        .include_historical("app", "app.unknown.v1")
        .unwrap_err();
    assert!(matches!(failure, AdmissionError::Unknown(_)));
    for name in [JOURNAL, CONTROL] {
        assert!(admission.is_declared(&StableKey::parse(name).unwrap()));
    }
    assert!(!admission.is_declared(&StableKey::parse("app.unknown.v1").unwrap()));
    assert_eq!(admission.complete().unwrap_err(), failure);
}

pub(super) fn seeded() -> VectorMemory {
    let backing = VectorMemory::default();
    let mut runtime =
        MemoryRuntime::new_with_config(backing.clone(), MemoryManagerConfig::new(1).unwrap())
            .unwrap();
    runtime
        .bootstrap(
            &snapshot(&[CONTROL, JOURNAL], "app", 100, 110, &[]),
            &GenericRangePolicy,
        )
        .unwrap();
    let journal = runtime.open_memory_by_key(JOURNAL).unwrap();
    journal.grow(1).unwrap();
    journal.write(0, b"pending/debt");
    backing
}

#[test]
fn discovers_omitted_journal_before_one_commit_and_skips_warm_admission() {
    let backing = seeded();
    let current = snapshot(&[CONTROL, "app.new.journal.v1"], "app", 100, 110, &[]);
    let policy = AdmissionPolicy {
        discover: true,
        ..Default::default()
    };
    let mut runtime = MemoryRuntime::new(backing.clone()).unwrap();
    assert!(matches!(
        runtime.open_memory_by_key(JOURNAL),
        Err(RuntimeOpenError::NotBootstrapped)
    ));
    assert_eq!(
        runtime.bootstrap(&current, &policy).unwrap().generation(),
        2
    );
    let mut marker = [0; 12];
    runtime
        .open_memory_by_key(JOURNAL)
        .unwrap()
        .read(0, &mut marker);
    assert_eq!(&marker, b"pending/debt");
    assert_eq!(
        runtime
            .committed_allocations()
            .unwrap()
            .slot_for(&StableKey::parse(JOURNAL).unwrap())
            .unwrap()
            .id(),
        101
    );
    let before = backing.borrow().clone();
    assert_eq!(
        runtime.bootstrap(&current, &policy).unwrap().generation(),
        2
    );
    let _ = runtime.doctor_report(&current, &policy);
    assert_eq!(policy.calls.get(), 1);
    assert_eq!(runtime.memory_manager_config().bucket_size_pages(), 1);
    assert_eq!(*backing.borrow(), before);
    assert!(matches!(
        runtime.bootstrap(&current, &GenericRangePolicy),
        Err(RuntimeBootstrapError::PolicyIdentityMismatch { .. })
    ));
}

#[test]
fn bad_selections_and_consumer_rejections_leave_mapping_unchanged() {
    for (selections, kind) in [
        (vec![("app", "app.unknown.v1")], "unknown"),
        (vec![("foreign", JOURNAL)], "foreign"),
        (vec![("app", JOURNAL), ("app", JOURNAL)], "duplicate"),
    ] {
        let backing = seeded();
        let before = backing.borrow().clone();
        let mut runtime = MemoryRuntime::new(backing.clone()).unwrap();
        let policy = AdmissionPolicy {
            selections,
            ..Default::default()
        };
        let err = runtime
            .bootstrap(&snapshot(&[CONTROL], "app", 100, 110, &[]), &policy)
            .unwrap_err();
        match (kind, err) {
            ("unknown", RuntimeBootstrapError::Admission(AdmissionError::Unknown(_)))
            | ("foreign", RuntimeBootstrapError::Admission(AdmissionError::Range { .. }))
            | ("duplicate", RuntimeBootstrapError::Admission(AdmissionError::Duplicate(_))) => (),
            (_, error) => panic!("unexpected {error:?}"),
        }
        assert!(!runtime.is_bootstrapped());
        assert_eq!(*backing.borrow(), before);
    }
    let backing = seeded();
    let before = backing.borrow().clone();
    let mut runtime = MemoryRuntime::new(backing.clone()).unwrap();
    let current = snapshot(&["replacement.control.v1"], "app", 100, 110, &[]);
    let policy = AdmissionPolicy {
        discover: true,
        ..Default::default()
    };
    assert!(matches!(
        runtime.bootstrap(&current, &policy),
        Err(RuntimeBootstrapError::AdmissionPolicy("identity rejected"))
    ));
    assert_eq!(*backing.borrow(), before);
    assert!(matches!(
        runtime.bootstrap(
            &snapshot(&["other.control.v1"], "other_owner", 100, 110, &[]),
            &policy
        ),
        Err(RuntimeBootstrapError::AdmissionPolicy("identity rejected"))
    ));
    assert_eq!(*backing.borrow(), before);
    // Retry uses unchanged evidence; an allowed addition succeeds in one generation.
    assert_eq!(
        runtime
            .bootstrap(
                &snapshot(&[CONTROL, "app.added.v1"], "app", 100, 110, &[]),
                &policy
            )
            .unwrap()
            .generation(),
        2
    );
    assert_eq!(policy.calls.get(), 3);
}

#[test]
fn current_policy_revoked_grants_and_retirement_still_reject() {
    let backing = seeded();
    let before = backing.borrow().clone();
    let mut runtime = MemoryRuntime::new(backing.clone()).unwrap();
    let policy = AdmissionPolicy {
        selections: vec![("app", JOURNAL)],
        deny_journals: true,
        ..Default::default()
    };
    assert!(matches!(
        runtime.bootstrap(&snapshot(&[CONTROL], "app", 100, 110, &[]), &policy),
        Err(RuntimeBootstrapError::Validation(_))
    ));
    assert_eq!(*backing.borrow(), before);
    let policy = AdmissionPolicy {
        selections: vec![("app", JOURNAL)],
        ..Default::default()
    };
    assert!(matches!(
        runtime.bootstrap(
            &snapshot(&[CONTROL], "app", 100, 110, &[("app.conflict.v1", 101)]),
            &policy
        ),
        Err(RuntimeBootstrapError::Resolution(_))
    ));
    assert_eq!(*backing.borrow(), before);
    assert!(matches!(
        runtime.bootstrap(&snapshot(&[], "app", 102, 110, &[]), &policy),
        Err(RuntimeBootstrapError::Admission(
            AdmissionError::Range { .. }
        ))
    ));
    assert_eq!(*backing.borrow(), before);
    let mut record = runtime.ledger_record_from_memory().unwrap();
    AllocationBootstrap::new(record.store_mut())
        .retire_and_commit(
            &crate::AllocationRetirement::new(JOURNAL, MemoryManagerSlot::new(101).unwrap())
                .unwrap(),
            None,
        )
        .unwrap();
    let _cell = Cell::new(runtime.memory(MEMORY_MANAGER_LEDGER_ID), record);
    drop(runtime);
    let before = backing.borrow().clone();
    let mut runtime = MemoryRuntime::new(backing.clone()).unwrap();
    assert!(matches!(
        runtime.bootstrap(&snapshot(&[CONTROL], "app", 100, 110, &[]), &policy),
        Err(RuntimeBootstrapError::Admission(AdmissionError::Retired(_)))
    ));
    assert_eq!(*backing.borrow(), before);
}

#[test]
fn corruption_precedes_admission_and_exhaustion_follows_it_without_commit() {
    let backing = seeded();
    let mut runtime = MemoryRuntime::new(backing.clone()).unwrap();
    let current = snapshot(&["app.new.v1"], "app", 100, 101, &[]);
    let policy = AdmissionPolicy {
        selections: vec![("app", JOURNAL)],
        ..Default::default()
    };
    let before = backing.borrow().clone();
    assert!(matches!(
        runtime.bootstrap(&current, &policy),
        Err(RuntimeBootstrapError::Resolution(
            MemoryResolutionError::Exhausted { .. }
        ))
    ));
    assert_eq!(policy.calls.get(), 1);
    assert_eq!(*backing.borrow(), before);
    runtime.memory(0).write(STABLE_CELL_VALUE_OFFSET, &[0xff]);
    let before = backing.borrow().clone();
    for reopen in [false, true] {
        if reopen {
            runtime = MemoryRuntime::new(backing.clone()).unwrap();
        }
        assert!(matches!(
            runtime.bootstrap(&current, &policy),
            Err(RuntimeBootstrapError::StableCellLedger(_))
        ));
        assert_eq!(policy.calls.get(), 1);
        assert_eq!(*backing.borrow(), before);
        assert!(!runtime.is_bootstrapped());
    }
}

#[test]
fn failed_persistence_retries_admission_without_partial_publication() {
    struct Limited {
        backing: VectorMemory,
        limit: std::rc::Rc<Counter<u64>>,
    }
    impl Memory for Limited {
        fn size(&self) -> u64 {
            self.backing.size()
        }
        fn grow(&self, pages: u64) -> i64 {
            if self.size() + pages > self.limit.get() {
                -1
            } else {
                self.backing.grow(pages)
            }
        }
        fn read(&self, offset: u64, bytes: &mut [u8]) {
            self.backing.read(offset, bytes);
        }
        fn write(&self, offset: u64, bytes: &[u8]) {
            self.backing.write(offset, bytes);
        }
    }
    let backing = seeded();
    let before = backing.borrow().clone();
    let limit = std::rc::Rc::new(Counter::new(backing.size()));
    // Long valid keys force capacity growth even with compact byte-string payloads.
    let keys: Vec<_> = (0..240)
        .map(|i| format!("app.new{i}.{}.v1", "x".repeat(110)))
        .collect();
    let refs: Vec<_> = keys.iter().map(String::as_str).collect();
    let current = snapshot(&refs, "app", 10, 254, &[]);
    let policy = AdmissionPolicy {
        selections: vec![("app", JOURNAL)],
        ..Default::default()
    };
    let mut runtime = MemoryRuntime::new(Limited {
        backing: backing.clone(),
        limit: limit.clone(),
    })
    .unwrap();
    let result = runtime.bootstrap(&current, &policy);
    assert!(
        matches!(
            result,
            Err(RuntimeBootstrapError::LedgerGrowth(
                super::RuntimeGrowError::BackingRefused { .. }
            ))
        ),
        "{:?}",
        result.err()
    );
    assert!(!runtime.is_bootstrapped());
    assert_eq!(*backing.borrow(), before);
    limit.set(100);
    assert_eq!(
        runtime.bootstrap(&current, &policy).unwrap().generation(),
        2
    );
    assert_eq!(policy.calls.get(), 2);
    let mut marker = [0; 12];
    runtime
        .open_memory_by_key(JOURNAL)
        .unwrap()
        .read(0, &mut marker);
    assert_eq!(&marker, b"pending/debt");
}

#[test]
fn fresh_rejection_can_acquire_root_but_cannot_commit_genesis() {
    let backing = VectorMemory::default();
    let mut runtime = MemoryRuntime::new(backing.clone()).unwrap();
    let current = snapshot(&[CONTROL], "app", 100, 110, &[]);
    let policy = AdmissionPolicy {
        reject: true,
        ..Default::default()
    };
    assert!(matches!(
        runtime.bootstrap(&current, &policy),
        Err(RuntimeBootstrapError::AdmissionPolicy(_))
    ));
    assert!(!runtime.is_bootstrapped());
    // A fresh rejection still initializes a readable cell, without committing
    // genesis. Retrying the rejection must leave that initialized root unchanged.
    assert_eq!(runtime.memory(MEMORY_MANAGER_LEDGER_ID).size(), 1);
    assert!(
        runtime
            .ledger_record_from_memory()
            .unwrap()
            .store()
            .physical()
            .is_uninitialized()
    );
    let before = backing.borrow().clone();
    assert!(matches!(
        runtime.bootstrap(&current, &policy),
        Err(RuntimeBootstrapError::AdmissionPolicy(_))
    ));
    assert_eq!(*backing.borrow(), before);
    assert!(!runtime.is_bootstrapped());
    let policy = AdmissionPolicy::default();
    assert_eq!(
        runtime.bootstrap(&current, &policy).unwrap().generation(),
        1
    );
}

#[test]
fn completion_bound_and_reservation_activation_preserve_evidence() {
    let backing = seeded();
    let before = backing.borrow().clone();
    let mut runtime = MemoryRuntime::new(backing.clone()).unwrap();
    let keys: Vec<_> = (0..254).map(|i| format!("app.request{i}.v1")).collect();
    let refs: Vec<_> = keys.iter().map(String::as_str).collect();
    let policy = AdmissionPolicy {
        selections: vec![("app", JOURNAL)],
        ..Default::default()
    };
    assert!(matches!(
        runtime.bootstrap(&snapshot(&refs, "app", 10, 254, &[]), &policy),
        Err(RuntimeBootstrapError::Admission(
            AdmissionError::TooManyDeclarations
        ))
    ));
    assert_eq!(*backing.borrow(), before);
    let mut record = runtime.ledger_record_from_memory().unwrap();
    AllocationBootstrap::new(record.store_mut())
        .reserve_and_commit(
            &[
                crate::AllocationDeclaration::memory_manager_unlabeled_with_schema(
                    "app.reserved.journal.v1",
                    102,
                    crate::SchemaMetadata::new(Some(5)).unwrap(),
                )
                .unwrap(),
            ],
            &GenericRangePolicy,
            None,
        )
        .unwrap();
    let _cell = Cell::new(runtime.memory(MEMORY_MANAGER_LEDGER_ID), record);
    drop(runtime);
    let mut runtime = MemoryRuntime::new(backing).unwrap();
    let policy = AdmissionPolicy {
        selections: vec![("app", "app.reserved.journal.v1")],
        ..Default::default()
    };
    let committed = runtime
        .bootstrap(&snapshot(&[CONTROL], "app", 100, 110, &[]), &policy)
        .unwrap();
    assert_eq!(committed.generation(), 3);
    let declaration = committed
        .declarations()
        .iter()
        .find(|d| d.stable_key().as_str() == "app.reserved.journal.v1")
        .unwrap();
    assert_eq!(
        declaration.schema(),
        &crate::SchemaMetadata::new(Some(5)).unwrap()
    );
    assert_eq!(declaration.slot().id(), 102);
}