ic-memory 0.39.13

Persistent allocation-governance infrastructure for Internet Computer stable memory
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
use crate::{
    declaration::AllocationDeclaration,
    declaration::DeclarationSnapshot,
    ledger::{
        AllocationLedger, AllocationReservationError, AllocationRetirement,
        AllocationRetirementError, LedgerCodec, LedgerCommitError, LedgerCommitStore,
    },
    policy::AllocationPolicy,
    session::ValidatedAllocations,
    validation::{AllocationValidationError, validate_allocations},
};

///
/// AllocationBootstrap
///
/// Generic generation bootstrap pipeline.
///
/// This type owns allocation-governance sequencing only. Frameworks own when
/// the pipeline runs, how the ledger store is backed by stable memory, and when
/// endpoint dispatch is allowed.
#[derive(Debug)]
pub struct AllocationBootstrap<'store> {
    store: &'store mut LedgerCommitStore,
}

impl<'store> AllocationBootstrap<'store> {
    /// Build a bootstrap pipeline over a protected ledger commit store.
    pub const fn new(store: &'store mut LedgerCommitStore) -> Self {
        Self { store }
    }

    /// Recover, validate, stage, commit, and publish one allocation generation.
    pub fn validate_and_commit<C, P>(
        &mut self,
        codec: &C,
        snapshot: DeclarationSnapshot,
        policy: &P,
        committed_at: Option<u64>,
    ) -> Result<BootstrapCommit, BootstrapError<C::Error, P::Error>>
    where
        C: LedgerCodec,
        P: AllocationPolicy,
    {
        let prior = self.store.recover(codec).map_err(BootstrapError::Ledger)?;
        self.validate_against(codec, prior, snapshot, policy, committed_at)
    }

    /// Initialize an empty ledger store explicitly, then validate and commit.
    ///
    /// This is the generic genesis path. The supplied `genesis` ledger is a
    /// framework decision; the generic crate only guarantees that it is used
    /// when the protected physical store is empty, never when recovery sees
    /// corrupt or partially written state.
    pub fn initialize_validate_and_commit<C, P>(
        &mut self,
        codec: &C,
        genesis: &AllocationLedger,
        snapshot: DeclarationSnapshot,
        policy: &P,
        committed_at: Option<u64>,
    ) -> Result<BootstrapCommit, BootstrapError<C::Error, P::Error>>
    where
        C: LedgerCodec,
        P: AllocationPolicy,
    {
        let prior = self
            .store
            .recover_or_initialize(codec, genesis)
            .map_err(BootstrapError::Ledger)?;
        self.validate_against(codec, prior, snapshot, policy, committed_at)
    }

    /// Recover, policy-check, reserve, and commit one reservation generation.
    pub fn reserve_and_commit<C, P>(
        &mut self,
        codec: &C,
        reservations: &[AllocationDeclaration],
        policy: &P,
        committed_at: Option<u64>,
    ) -> Result<AllocationLedger, BootstrapReservationError<C::Error, P::Error>>
    where
        C: LedgerCodec,
        P: AllocationPolicy,
    {
        let prior = self
            .store
            .recover(codec)
            .map_err(BootstrapReservationError::Ledger)?;
        self.reserve_against(codec, prior, reservations, policy, committed_at)
    }

    /// Initialize an empty ledger store, then reserve and commit.
    pub fn initialize_reserve_and_commit<C, P>(
        &mut self,
        codec: &C,
        genesis: &AllocationLedger,
        reservations: &[AllocationDeclaration],
        policy: &P,
        committed_at: Option<u64>,
    ) -> Result<AllocationLedger, BootstrapReservationError<C::Error, P::Error>>
    where
        C: LedgerCodec,
        P: AllocationPolicy,
    {
        let prior = self
            .store
            .recover_or_initialize(codec, genesis)
            .map_err(BootstrapReservationError::Ledger)?;
        self.reserve_against(codec, prior, reservations, policy, committed_at)
    }

    /// Recover, retire, and commit one explicit retirement generation.
    pub fn retire_and_commit<C>(
        &mut self,
        codec: &C,
        retirement: &AllocationRetirement,
        committed_at: Option<u64>,
    ) -> Result<AllocationLedger, BootstrapRetirementError<C::Error>>
    where
        C: LedgerCodec,
    {
        let prior = self
            .store
            .recover(codec)
            .map_err(BootstrapRetirementError::Ledger)?;
        self.retire_against(codec, prior, retirement, committed_at)
    }

    fn reserve_against<C, P>(
        &mut self,
        codec: &C,
        prior: AllocationLedger,
        reservations: &[AllocationDeclaration],
        policy: &P,
        committed_at: Option<u64>,
    ) -> Result<AllocationLedger, BootstrapReservationError<C::Error, P::Error>>
    where
        C: LedgerCodec,
        P: AllocationPolicy,
    {
        for reservation in reservations {
            policy
                .validate_key(&reservation.stable_key)
                .map_err(BootstrapReservationError::Policy)?;
            policy
                .validate_reserved_slot(&reservation.stable_key, &reservation.slot)
                .map_err(BootstrapReservationError::Policy)?;
        }

        let staged = prior
            .stage_reservation_generation(reservations, committed_at)
            .map_err(BootstrapReservationError::Reservation)?;
        self.store
            .commit(&staged, codec)
            .map_err(BootstrapReservationError::Ledger)
    }

    fn retire_against<C>(
        &mut self,
        codec: &C,
        prior: AllocationLedger,
        retirement: &AllocationRetirement,
        committed_at: Option<u64>,
    ) -> Result<AllocationLedger, BootstrapRetirementError<C::Error>>
    where
        C: LedgerCodec,
    {
        let staged = prior
            .stage_retirement_generation(retirement, committed_at)
            .map_err(BootstrapRetirementError::Retirement)?;
        self.store
            .commit(&staged, codec)
            .map_err(BootstrapRetirementError::Ledger)
    }

    fn validate_against<C, P>(
        &mut self,
        codec: &C,
        prior: AllocationLedger,
        snapshot: DeclarationSnapshot,
        policy: &P,
        committed_at: Option<u64>,
    ) -> Result<BootstrapCommit, BootstrapError<C::Error, P::Error>>
    where
        C: LedgerCodec,
        P: AllocationPolicy,
    {
        let validated =
            validate_allocations(&prior, snapshot, policy).map_err(BootstrapError::Validation)?;
        let staged = prior.stage_validated_generation(&validated, committed_at);
        let committed = self
            .store
            .commit(&staged, codec)
            .map_err(BootstrapError::Ledger)?;

        Ok(BootstrapCommit {
            validated: validated.with_generation(committed.current_generation),
            ledger: committed,
        })
    }
}

///
/// BootstrapCommit
///
/// Result of a successful generic allocation bootstrap commit.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BootstrapCommit {
    /// Ledger recovered after the protected generation commit.
    pub ledger: AllocationLedger,
    /// Validated allocation declarations tied to the committed generation.
    pub validated: ValidatedAllocations,
}

///
/// BootstrapError
///
/// Failure to recover, validate, or commit an allocation generation.
#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
pub enum BootstrapError<C, P> {
    /// Ledger recovery or protected commit failed.
    #[error(transparent)]
    Ledger(LedgerCommitError<C>),
    /// Policy or historical allocation validation failed.
    #[error(transparent)]
    Validation(AllocationValidationError<P>),
}

///
/// BootstrapReservationError
///
/// Failure to policy-check, stage, or commit an allocation reservation.
#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
pub enum BootstrapReservationError<C, P> {
    /// Ledger recovery or protected commit failed.
    #[error(transparent)]
    Ledger(LedgerCommitError<C>),
    /// Policy adapter rejected a reservation declaration.
    #[error("allocation policy rejected a reservation")]
    Policy(P),
    /// Reservation conflicted with historical allocation facts.
    #[error(transparent)]
    Reservation(AllocationReservationError),
}

///
/// BootstrapRetirementError
///
/// Failure to stage or commit an explicit allocation retirement.
#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
pub enum BootstrapRetirementError<C> {
    /// Ledger recovery or protected commit failed.
    #[error(transparent)]
    Ledger(LedgerCommitError<C>),
    /// Retirement conflicted with historical allocation facts.
    #[error(transparent)]
    Retirement(AllocationRetirementError),
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        declaration::AllocationDeclaration,
        ledger::{AllocationHistory, AllocationLedger, AllocationState},
        schema::SchemaMetadata,
        slot::AllocationSlotDescriptor,
    };
    use std::cell::RefCell;

    #[derive(Debug, Default)]
    struct TestCodec {
        encoded: RefCell<Option<AllocationLedger>>,
    }

    impl LedgerCodec for TestCodec {
        type Error = &'static str;

        fn encode(&self, ledger: &AllocationLedger) -> Result<Vec<u8>, Self::Error> {
            *self.encoded.borrow_mut() = Some(ledger.clone());
            Ok(ledger.current_generation.to_le_bytes().to_vec())
        }

        fn decode(&self, _bytes: &[u8]) -> Result<AllocationLedger, Self::Error> {
            self.encoded
                .borrow()
                .clone()
                .ok_or("ledger was not encoded")
        }
    }

    #[derive(Debug, Eq, PartialEq)]
    struct TestPolicy;

    impl AllocationPolicy for TestPolicy {
        type Error = &'static str;

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

        fn validate_slot(
            &self,
            _key: &crate::StableKey,
            _slot: &AllocationSlotDescriptor,
        ) -> Result<(), Self::Error> {
            Ok(())
        }

        fn validate_reserved_slot(
            &self,
            _key: &crate::StableKey,
            _slot: &AllocationSlotDescriptor,
        ) -> Result<(), Self::Error> {
            Ok(())
        }
    }

    #[derive(Debug, Eq, PartialEq)]
    struct RejectReservedPolicy;

    impl AllocationPolicy for RejectReservedPolicy {
        type Error = &'static str;

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

        fn validate_slot(
            &self,
            _key: &crate::StableKey,
            _slot: &AllocationSlotDescriptor,
        ) -> Result<(), Self::Error> {
            Ok(())
        }

        fn validate_reserved_slot(
            &self,
            _key: &crate::StableKey,
            _slot: &AllocationSlotDescriptor,
        ) -> Result<(), Self::Error> {
            Err("reserved slot rejected")
        }
    }

    fn ledger() -> AllocationLedger {
        AllocationLedger {
            ledger_schema_version: 1,
            physical_format_id: 1,
            current_generation: 0,
            allocation_history: AllocationHistory::default(),
        }
    }

    fn declaration() -> AllocationDeclaration {
        AllocationDeclaration::new(
            "app.users.v1",
            AllocationSlotDescriptor::memory_manager(100),
            None,
            SchemaMetadata::default(),
        )
        .expect("declaration")
    }

    #[test]
    fn validate_and_commit_publishes_committed_generation() {
        let codec = TestCodec::default();
        let mut store = LedgerCommitStore::default();
        store.commit(&ledger(), &codec).expect("initial ledger");
        let snapshot = DeclarationSnapshot::new(vec![declaration()]).expect("snapshot");

        let commit = AllocationBootstrap::new(&mut store)
            .validate_and_commit(&codec, snapshot, &TestPolicy, Some(42))
            .expect("bootstrap commit");

        assert_eq!(commit.ledger.current_generation, 1);
        assert_eq!(commit.validated.generation(), 1);
        assert_eq!(commit.ledger.allocation_history.records.len(), 1);
        assert_eq!(commit.ledger.allocation_history.generations.len(), 1);
    }

    #[test]
    fn initialize_validate_and_commit_seeds_empty_ledger_store() {
        let codec = TestCodec::default();
        let mut store = LedgerCommitStore::default();
        let snapshot = DeclarationSnapshot::new(vec![declaration()]).expect("snapshot");

        let commit = AllocationBootstrap::new(&mut store)
            .initialize_validate_and_commit(&codec, &ledger(), snapshot, &TestPolicy, Some(42))
            .expect("bootstrap commit");

        assert_eq!(commit.ledger.current_generation, 1);
        assert_eq!(commit.validated.generation(), 1);
        assert_eq!(commit.ledger.allocation_history.records.len(), 1);
    }

    #[test]
    fn initialize_validate_and_commit_fails_closed_on_corrupt_store() {
        let codec = TestCodec::default();
        let mut store = LedgerCommitStore::default();
        store
            .write_corrupt_inactive_ledger(&ledger(), &codec)
            .expect("corrupt ledger");
        let snapshot = DeclarationSnapshot::new(vec![declaration()]).expect("snapshot");

        let err = AllocationBootstrap::new(&mut store)
            .initialize_validate_and_commit(&codec, &ledger(), snapshot, &TestPolicy, Some(42))
            .expect_err("corrupt state");

        assert!(matches!(err, BootstrapError::Ledger(_)));
    }

    #[test]
    fn reserve_and_commit_policy_checks_and_commits_reservation() {
        let codec = TestCodec::default();
        let mut store = LedgerCommitStore::default();
        store.commit(&ledger(), &codec).expect("initial ledger");
        let reservation = declaration();

        let committed = AllocationBootstrap::new(&mut store)
            .reserve_and_commit(&codec, &[reservation], &TestPolicy, Some(42))
            .expect("reservation commit");

        assert_eq!(committed.current_generation, 1);
        assert_eq!(committed.allocation_history.records.len(), 1);
        assert_eq!(
            committed.allocation_history.records[0].state,
            AllocationState::Reserved
        );
    }

    #[test]
    fn initialize_reserve_and_commit_seeds_empty_store() {
        let codec = TestCodec::default();
        let mut store = LedgerCommitStore::default();
        let reservation = declaration();

        let committed = AllocationBootstrap::new(&mut store)
            .initialize_reserve_and_commit(&codec, &ledger(), &[reservation], &TestPolicy, Some(42))
            .expect("reservation commit");

        assert_eq!(committed.current_generation, 1);
        assert_eq!(
            committed.allocation_history.records[0].state,
            AllocationState::Reserved
        );
    }

    #[test]
    fn reserve_and_commit_rejects_policy_failure_before_commit() {
        let codec = TestCodec::default();
        let mut store = LedgerCommitStore::default();
        store.commit(&ledger(), &codec).expect("initial ledger");
        let reservation = declaration();

        let err = AllocationBootstrap::new(&mut store)
            .reserve_and_commit(&codec, &[reservation], &RejectReservedPolicy, Some(42))
            .expect_err("policy failure");
        let recovered = store.recover(&codec).expect("recovered");

        assert!(matches!(err, BootstrapReservationError::Policy(_)));
        assert_eq!(recovered.current_generation, 0);
        assert!(recovered.allocation_history.records.is_empty());
    }

    #[test]
    fn retire_and_commit_tombstones_through_protected_commit() {
        let codec = TestCodec::default();
        let mut store = LedgerCommitStore::default();
        store.commit(&ledger(), &codec).expect("initial ledger");
        let snapshot = DeclarationSnapshot::new(vec![declaration()]).expect("snapshot");
        AllocationBootstrap::new(&mut store)
            .validate_and_commit(&codec, snapshot, &TestPolicy, Some(42))
            .expect("active commit");
        let retirement = AllocationRetirement::new(
            "app.users.v1",
            AllocationSlotDescriptor::memory_manager(100),
        )
        .expect("retirement");

        let committed = AllocationBootstrap::new(&mut store)
            .retire_and_commit(&codec, &retirement, Some(43))
            .expect("retirement commit");

        assert_eq!(committed.current_generation, 2);
        assert_eq!(
            committed.allocation_history.records[0].state,
            AllocationState::Retired
        );
        assert_eq!(
            committed.allocation_history.records[0].retired_generation,
            Some(2)
        );
    }

    #[test]
    fn retire_and_commit_rejects_unknown_key_before_commit() {
        let codec = TestCodec::default();
        let mut store = LedgerCommitStore::default();
        store.commit(&ledger(), &codec).expect("initial ledger");
        let retirement = AllocationRetirement::new(
            "app.users.v1",
            AllocationSlotDescriptor::memory_manager(100),
        )
        .expect("retirement");

        let err = AllocationBootstrap::new(&mut store)
            .retire_and_commit(&codec, &retirement, Some(43))
            .expect_err("unknown key");
        let recovered = store.recover(&codec).expect("recovered");

        assert!(matches!(err, BootstrapRetirementError::Retirement(_)));
        assert_eq!(recovered.current_generation, 0);
        assert!(recovered.allocation_history.records.is_empty());
    }
}