ic-memory 0.6.1

Memory ID registry wrapper for ic-stable-structures on 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
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
use super::{AllocationRetirementError, LedgerCompatibilityError, LedgerIntegrityError};
use crate::{
    declaration::{AllocationDeclaration, DeclarationSnapshotError, validate_runtime_fingerprint},
    key::StableKey,
    schema::{SchemaMetadata, SchemaMetadataError},
    slot::AllocationSlotDescriptor,
};
use serde::{Deserialize, Serialize};

/// Current allocation ledger schema version.
pub const CURRENT_LEDGER_SCHEMA_VERSION: u32 = 1;

/// Current protected physical ledger format identifier.
pub const CURRENT_PHYSICAL_FORMAT_ID: u32 = 1;

///
/// AllocationLedger
///
/// Durable root of allocation history.
///
/// Decoded ledgers are input from persistent storage and should be treated as
/// untrusted until compatibility and integrity validation pass. Public
/// construction goes through [`AllocationLedger::new`], which validates
/// structural history invariants before returning a value. Use
/// [`AllocationLedger::new_committed`] when the value should also satisfy the
/// strict committed-generation chain required by recovery and commit.
///
/// Staging APIs clone this DTO before applying a logical generation. The ledger
/// is expected to contain allocation metadata only, bounded by the number of
/// stable allocation identities and committed bootstrap generations, not user
/// collection contents.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AllocationLedger {
    /// Ledger schema version.
    pub(crate) ledger_schema_version: u32,
    /// Physical encoding format identifier.
    pub(crate) physical_format_id: u32,
    /// Current committed generation selected by recovery.
    pub(crate) current_generation: u64,
    /// Historical allocation facts.
    pub(crate) allocation_history: AllocationHistory,
}

///
/// AllocationHistory
///
/// Durable allocation records and generation history.
///
/// This is the durable DTO embedded in an [`AllocationLedger`]. It records
/// allocation facts and generation diagnostics; callers should prefer ledger
/// staging/validation methods over mutating histories directly.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AllocationHistory {
    /// Stable-key allocation records.
    pub(crate) records: Vec<AllocationRecord>,
    /// Committed generation records.
    pub(crate) generations: Vec<GenerationRecord>,
}

///
/// AllocationRecord
///
/// Durable ownership record for one stable key.
///
/// Records are historical facts, not live handles. Fields are private so stale
/// or invalid ownership state cannot be assembled through public struct
/// literals; use accessors for diagnostics and ledger methods for mutation.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AllocationRecord {
    /// Stable key that owns the slot.
    pub(crate) stable_key: StableKey,
    /// Durable allocation slot owned by the key.
    pub(crate) slot: AllocationSlotDescriptor,
    /// Current allocation lifecycle state.
    pub(crate) state: AllocationState,
    /// First committed generation that recorded this allocation.
    pub(crate) first_generation: u64,
    /// Latest committed generation that observed this allocation declaration.
    pub(crate) last_seen_generation: u64,
    /// Generation that explicitly retired this allocation.
    pub(crate) retired_generation: Option<u64>,
    /// Per-generation schema metadata history.
    pub(crate) schema_history: Vec<SchemaMetadataRecord>,
}

///
/// AllocationRetirement
///
/// Explicit request to tombstone one historical allocation identity.
///
/// Retirement prevents a stable key from being redeclared. It does not make the
/// physical slot safe for another active stable key.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AllocationRetirement {
    /// Stable key being retired.
    pub stable_key: StableKey,
    /// Allocation slot historically owned by the stable key.
    pub slot: AllocationSlotDescriptor,
}

impl AllocationRetirement {
    /// Build an explicit retirement request from raw parts.
    pub fn new(
        stable_key: impl AsRef<str>,
        slot: AllocationSlotDescriptor,
    ) -> Result<Self, AllocationRetirementError> {
        Ok(Self {
            stable_key: StableKey::parse(stable_key).map_err(AllocationRetirementError::Key)?,
            slot,
        })
    }
}

///
/// AllocationState
///
/// Allocation lifecycle state.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum AllocationState {
    /// Slot is reserved for a future allocation identity.
    Reserved,
    /// Slot is active and may be opened after validation.
    Active,
    /// Slot was explicitly retired and remains tombstoned.
    Retired,
}

///
/// SchemaMetadataRecord
///
/// Schema metadata observed in one committed generation.
///
/// Schema metadata is diagnostic ledger history. It is validated for bounded
/// durable encoding, but `ic-memory` does not prove application schema
/// compatibility or data migration correctness.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SchemaMetadataRecord {
    /// Generation that declared this schema metadata.
    pub(crate) generation: u64,
    /// Schema metadata declared by that generation.
    pub(crate) schema: SchemaMetadata,
}

///
/// GenerationRecord
///
/// Diagnostic metadata for one committed ledger generation.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct GenerationRecord {
    /// Committed generation number.
    pub(crate) generation: u64,
    /// Parent generation, if recorded.
    pub(crate) parent_generation: Option<u64>,
    /// Optional binary/runtime fingerprint.
    pub(crate) runtime_fingerprint: Option<String>,
    /// Number of declarations in the generation.
    pub(crate) declaration_count: u32,
    /// Optional commit timestamp supplied by the integration layer.
    pub(crate) committed_at: Option<u64>,
}

///
/// LedgerCompatibility
///
/// Supported logical and physical ledger format versions.
///
/// Run this check on recovered ledgers before treating them as authoritative
/// state. Integrity validation then checks allocation history invariants.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct LedgerCompatibility {
    /// Minimum supported ledger schema version.
    pub min_ledger_schema_version: u32,
    /// Maximum supported ledger schema version.
    pub max_ledger_schema_version: u32,
    /// Required physical encoding format identifier.
    pub physical_format_id: u32,
}

impl LedgerCompatibility {
    /// Return the compatibility supported by this crate version.
    #[must_use]
    pub const fn current() -> Self {
        Self {
            min_ledger_schema_version: CURRENT_LEDGER_SCHEMA_VERSION,
            max_ledger_schema_version: CURRENT_LEDGER_SCHEMA_VERSION,
            physical_format_id: CURRENT_PHYSICAL_FORMAT_ID,
        }
    }

    /// Validate a decoded ledger before it is used as authoritative state.
    pub const fn validate(
        &self,
        ledger: &AllocationLedger,
    ) -> Result<(), LedgerCompatibilityError> {
        self.validate_versions(ledger.ledger_schema_version, ledger.physical_format_id)
    }

    pub(crate) const fn validate_versions(
        &self,
        ledger_schema_version: u32,
        physical_format_id: u32,
    ) -> Result<(), LedgerCompatibilityError> {
        if ledger_schema_version < self.min_ledger_schema_version {
            return Err(LedgerCompatibilityError::UnsupportedLedgerSchemaVersion {
                found: ledger_schema_version,
                min_supported: self.min_ledger_schema_version,
                max_supported: self.max_ledger_schema_version,
            });
        }
        if ledger_schema_version > self.max_ledger_schema_version {
            return Err(LedgerCompatibilityError::UnsupportedLedgerSchemaVersion {
                found: ledger_schema_version,
                min_supported: self.min_ledger_schema_version,
                max_supported: self.max_ledger_schema_version,
            });
        }
        if physical_format_id != self.physical_format_id {
            return Err(LedgerCompatibilityError::UnsupportedPhysicalFormat {
                found: physical_format_id,
                supported: self.physical_format_id,
            });
        }
        Ok(())
    }
}

impl Default for LedgerCompatibility {
    fn default() -> Self {
        Self::current()
    }
}

///
/// RecoveredLedger
///
/// Proof object for an allocation ledger that has crossed physical recovery,
/// logical payload-envelope routing, compatibility checks, and committed
/// integrity validation.
///
/// This type is not serializable and has no public constructor. It is the
/// provenance boundary required before declarations can mint
/// [`crate::ValidatedAllocations`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RecoveredLedger {
    ledger: AllocationLedger,
    physical_generation: u64,
    ledger_schema_version: u32,
    envelope_version: u16,
}

impl RecoveredLedger {
    pub(crate) const fn from_trusted_parts(
        ledger: AllocationLedger,
        physical_generation: u64,
        envelope_version: u16,
    ) -> Self {
        let ledger_schema_version = ledger.ledger_schema_version;
        Self {
            ledger,
            physical_generation,
            ledger_schema_version,
            envelope_version,
        }
    }

    /// Borrow the recovered canonical allocation ledger.
    ///
    /// The returned ledger is diagnostic/staging state. It is not itself an
    /// authority token; callers must keep passing the `RecoveredLedger` proof
    /// across validation boundaries.
    #[must_use]
    pub const fn ledger(&self) -> &AllocationLedger {
        &self.ledger
    }

    /// Return the selected physical committed generation.
    #[must_use]
    pub const fn physical_generation(&self) -> u64 {
        self.physical_generation
    }

    /// Return the recovered ledger's current logical generation.
    #[must_use]
    pub const fn current_generation(&self) -> u64 {
        self.ledger.current_generation
    }

    /// Return the schema version routed by the logical payload envelope.
    #[must_use]
    pub const fn ledger_schema_version(&self) -> u32 {
        self.ledger_schema_version
    }

    /// Return the payload envelope version used during recovery.
    #[must_use]
    pub const fn envelope_version(&self) -> u16 {
        self.envelope_version
    }

    pub(crate) fn into_ledger(self) -> AllocationLedger {
        self.ledger
    }
}

impl AllocationHistory {
    #[cfg(test)]
    pub(crate) const fn from_parts(
        records: Vec<AllocationRecord>,
        generations: Vec<GenerationRecord>,
    ) -> Self {
        Self {
            records,
            generations,
        }
    }

    /// Borrow stable-key allocation records in durable order.
    #[must_use]
    pub fn records(&self) -> &[AllocationRecord] {
        &self.records
    }

    /// Borrow committed generation records in durable order.
    #[must_use]
    pub fn generations(&self) -> &[GenerationRecord] {
        &self.generations
    }

    /// Return true when the history has no allocation records and no generation records.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.records.is_empty() && self.generations.is_empty()
    }

    pub(crate) const fn records_mut(&mut self) -> &mut Vec<AllocationRecord> {
        &mut self.records
    }

    #[cfg(test)]
    pub(crate) const fn generations_mut(&mut self) -> &mut Vec<GenerationRecord> {
        &mut self.generations
    }

    pub(crate) fn push_record(&mut self, record: AllocationRecord) {
        self.records.push(record);
    }

    pub(crate) fn push_generation(&mut self, generation: GenerationRecord) {
        self.generations.push(generation);
    }
}

impl SchemaMetadataRecord {
    /// Build a schema metadata history record after validating the metadata.
    pub fn new(generation: u64, schema: SchemaMetadata) -> Result<Self, SchemaMetadataError> {
        schema.validate()?;
        Ok(Self { generation, schema })
    }

    /// Return the generation that declared this schema metadata.
    #[must_use]
    pub const fn generation(&self) -> u64 {
        self.generation
    }

    /// Return the schema metadata declared by that generation.
    #[must_use]
    pub const fn schema(&self) -> &SchemaMetadata {
        &self.schema
    }
}

impl GenerationRecord {
    /// Build a committed generation diagnostic record after validating metadata.
    pub fn new(
        generation: u64,
        parent_generation: Option<u64>,
        runtime_fingerprint: Option<String>,
        declaration_count: u32,
        committed_at: Option<u64>,
    ) -> Result<Self, DeclarationSnapshotError> {
        validate_runtime_fingerprint(runtime_fingerprint.as_deref())?;
        Ok(Self {
            generation,
            parent_generation,
            runtime_fingerprint,
            declaration_count,
            committed_at,
        })
    }

    /// Return the committed generation number.
    #[must_use]
    pub const fn generation(&self) -> u64 {
        self.generation
    }

    /// Return the parent generation, if recorded.
    #[must_use]
    pub const fn parent_generation(&self) -> Option<u64> {
        self.parent_generation
    }

    /// Borrow the optional binary/runtime fingerprint.
    #[must_use]
    pub fn runtime_fingerprint(&self) -> Option<&str> {
        self.runtime_fingerprint.as_deref()
    }

    /// Return the number of declarations in the generation.
    #[must_use]
    pub const fn declaration_count(&self) -> u32 {
        self.declaration_count
    }

    /// Return the optional commit timestamp supplied by the integration layer.
    #[must_use]
    pub const fn committed_at(&self) -> Option<u64> {
        self.committed_at
    }
}

impl AllocationRecord {
    /// Create a new allocation record from a declaration.
    #[must_use]
    pub(crate) fn from_declaration(
        generation: u64,
        declaration: AllocationDeclaration,
        state: AllocationState,
    ) -> Self {
        Self {
            stable_key: declaration.stable_key,
            slot: declaration.slot,
            state,
            first_generation: generation,
            last_seen_generation: generation,
            retired_generation: None,
            schema_history: vec![
                SchemaMetadataRecord::new(generation, declaration.schema)
                    .expect("declarations validate schema metadata"),
            ],
        }
    }

    /// Create a new reserved allocation record from a declaration.
    #[must_use]
    pub(crate) fn reserved(generation: u64, declaration: AllocationDeclaration) -> Self {
        Self::from_declaration(generation, declaration, AllocationState::Reserved)
    }

    /// Return the stable key that owns this allocation record.
    #[must_use]
    pub const fn stable_key(&self) -> &StableKey {
        &self.stable_key
    }

    /// Return the durable allocation slot owned by this record.
    #[must_use]
    pub const fn slot(&self) -> &AllocationSlotDescriptor {
        &self.slot
    }

    /// Return the current allocation lifecycle state.
    #[must_use]
    pub const fn state(&self) -> AllocationState {
        self.state
    }

    /// Return the first committed generation that recorded this allocation.
    #[must_use]
    pub const fn first_generation(&self) -> u64 {
        self.first_generation
    }

    /// Return the latest committed generation that observed this allocation.
    #[must_use]
    pub const fn last_seen_generation(&self) -> u64 {
        self.last_seen_generation
    }

    /// Return the generation that explicitly retired this allocation, if any.
    #[must_use]
    pub const fn retired_generation(&self) -> Option<u64> {
        self.retired_generation
    }

    /// Return the per-generation schema metadata history.
    #[must_use]
    pub fn schema_history(&self) -> &[SchemaMetadataRecord] {
        &self.schema_history
    }

    pub(crate) fn observe_declaration(
        &mut self,
        generation: u64,
        declaration: &AllocationDeclaration,
    ) {
        self.last_seen_generation = generation;
        if self.state == AllocationState::Reserved {
            self.state = AllocationState::Active;
        }

        let latest_schema = self.schema_history.last().map(|record| &record.schema);
        if latest_schema != Some(&declaration.schema) {
            self.schema_history.push(
                SchemaMetadataRecord::new(generation, declaration.schema.clone())
                    .expect("declarations validate schema metadata"),
            );
        }
    }

    pub(crate) fn observe_reservation(
        &mut self,
        generation: u64,
        reservation: &AllocationDeclaration,
    ) {
        self.last_seen_generation = generation;

        let latest_schema = self.schema_history.last().map(|record| &record.schema);
        if latest_schema != Some(&reservation.schema) {
            self.schema_history.push(
                SchemaMetadataRecord::new(generation, reservation.schema.clone())
                    .expect("reservations validate schema metadata"),
            );
        }
    }
}

impl AllocationLedger {
    /// Build a ledger DTO and validate structural ledger invariants.
    ///
    /// This constructor validates duplicate records, lifecycle state, record
    /// generation bounds, and schema metadata records. It does not require a
    /// complete committed-generation chain. Use
    /// [`AllocationLedger::new_committed`] when constructing an authoritative
    /// committed ledger DTO.
    pub fn new(
        ledger_schema_version: u32,
        physical_format_id: u32,
        current_generation: u64,
        allocation_history: AllocationHistory,
    ) -> Result<Self, LedgerIntegrityError> {
        let ledger = Self {
            ledger_schema_version,
            physical_format_id,
            current_generation,
            allocation_history,
        };
        ledger.validate_integrity()?;
        Ok(ledger)
    }

    /// Build a committed ledger DTO and validate strict committed-history invariants.
    ///
    /// This constructor runs the same committed-integrity checks used by
    /// recovery and commit. Use it when the value should be treated as an
    /// authoritative committed ledger, not merely as a structurally valid DTO.
    pub fn new_committed(
        ledger_schema_version: u32,
        physical_format_id: u32,
        current_generation: u64,
        allocation_history: AllocationHistory,
    ) -> Result<Self, LedgerIntegrityError> {
        let ledger = Self::new(
            ledger_schema_version,
            physical_format_id,
            current_generation,
            allocation_history,
        )?;
        ledger.validate_committed_integrity()?;
        Ok(ledger)
    }

    /// Return the ledger schema version.
    #[must_use]
    pub const fn ledger_schema_version(&self) -> u32 {
        self.ledger_schema_version
    }

    /// Return the protected physical format identifier.
    #[must_use]
    pub const fn physical_format_id(&self) -> u32 {
        self.physical_format_id
    }

    /// Return the current committed generation selected by recovery.
    #[must_use]
    pub const fn current_generation(&self) -> u64 {
        self.current_generation
    }

    /// Return the historical allocation facts.
    #[must_use]
    pub const fn allocation_history(&self) -> &AllocationHistory {
        &self.allocation_history
    }
}