Skip to main content

ic_memory/ledger/
record.rs

1use super::{AllocationRetirementError, LedgerIntegrityError};
2use crate::{
3    declaration::{AllocationDeclaration, DeclarationSnapshotError, validate_runtime_fingerprint},
4    key::StableKey,
5    schema::SchemaMetadata,
6    slot::MemoryManagerSlot,
7};
8use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
9
10///
11/// AllocationLedger
12///
13/// Durable root of allocation history.
14///
15/// Decoded ledgers are input from persistent storage and should be treated as
16/// untrusted until current-format and integrity validation pass. Public
17/// construction goes through [`AllocationLedger::new`], which validates
18/// structural history invariants before returning a value. Use
19/// [`AllocationLedger::new_committed`] when the value should also satisfy the
20/// strict committed-generation chain required by recovery and commit.
21///
22/// Public staging APIs clone this DTO before applying a logical generation;
23/// bootstrap transfers its owned ledger into the same staging implementation.
24/// The ledger contains allocation metadata only, bounded by the number of
25/// stable allocation identities and committed bootstrap generations, not user
26/// collection contents.
27///
28
29#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
30#[serde(deny_unknown_fields)]
31pub struct AllocationLedger {
32    /// Current committed generation selected by recovery.
33    pub(crate) current_generation: u64,
34    /// Historical allocation facts.
35    pub(crate) allocation_history: AllocationHistory,
36}
37
38///
39/// AllocationHistory
40///
41/// Durable allocation records and generation history.
42///
43/// This is the durable DTO embedded in an [`AllocationLedger`]. It records
44/// allocation facts and generation diagnostics; callers should prefer ledger
45/// staging/validation methods over mutating histories directly.
46#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
47#[serde(deny_unknown_fields)]
48pub struct AllocationHistory {
49    /// Stable-key allocation records.
50    #[serde(deserialize_with = "crate::cbor::deserialize_records")]
51    pub(crate) records: Vec<AllocationRecord>,
52    /// Committed generation records.
53    #[serde(deserialize_with = "crate::cbor::deserialize_history")]
54    pub(crate) generations: Vec<GenerationRecord>,
55}
56
57///
58/// AllocationRecord
59///
60/// Durable ownership record for one stable key.
61///
62/// Records are historical facts, not live handles. Fields are private so stale
63/// or invalid ownership state cannot be assembled through public struct
64/// literals; use accessors for diagnostics and ledger methods for mutation.
65///
66
67#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
68#[serde(deny_unknown_fields)]
69pub struct AllocationRecord {
70    /// Stable key that owns the slot.
71    pub(crate) stable_key: StableKey,
72    /// Durable allocation slot owned by the key.
73    pub(crate) slot: MemoryManagerSlot,
74    /// Current allocation lifecycle state.
75    pub(crate) state: AllocationState,
76    /// First committed generation that recorded this allocation.
77    pub(crate) first_generation: u64,
78    /// Latest committed generation that observed this allocation declaration.
79    pub(crate) last_seen_generation: u64,
80    /// Per-generation schema metadata history.
81    #[serde(deserialize_with = "crate::cbor::deserialize_history")]
82    pub(crate) schema_history: Vec<SchemaMetadataRecord>,
83}
84
85///
86/// AllocationRetirement
87///
88/// Explicit request to tombstone one historical allocation identity.
89///
90/// Retirement prevents a stable key from being redeclared. It does not make the
91/// physical slot safe for another active stable key.
92/// Its key and slot are checked during construction and decoding; staging still
93/// verifies the historical assignment and retirement eligibility.
94///
95
96#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
97#[serde(deny_unknown_fields)]
98pub struct AllocationRetirement {
99    /// Stable key being retired.
100    pub(crate) stable_key: StableKey,
101    /// Allocation slot historically owned by the stable key.
102    pub(crate) slot: MemoryManagerSlot,
103}
104
105impl AllocationRetirement {
106    /// Build an explicit retirement request from raw parts.
107    pub fn new(
108        stable_key: impl AsRef<str>,
109        slot: MemoryManagerSlot,
110    ) -> Result<Self, AllocationRetirementError> {
111        let stable_key = StableKey::parse(stable_key).map_err(AllocationRetirementError::Key)?;
112        Ok(Self { stable_key, slot })
113    }
114
115    /// Return the stable key being retired.
116    #[must_use]
117    pub const fn stable_key(&self) -> &StableKey {
118        &self.stable_key
119    }
120
121    /// Return the allocation slot historically owned by the stable key.
122    #[must_use]
123    pub const fn slot(&self) -> &MemoryManagerSlot {
124        &self.slot
125    }
126}
127
128///
129/// AllocationState
130///
131/// Allocation lifecycle state.
132///
133
134#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
135#[serde(deny_unknown_fields)]
136pub enum AllocationState {
137    /// Slot is reserved for a future allocation identity.
138    Reserved,
139    /// Slot is active and may be opened after validation.
140    Active,
141    /// Slot was explicitly retired and remains tombstoned.
142    Retired {
143        /// Committed generation that retired the allocation.
144        generation: u64,
145    },
146}
147
148///
149/// SchemaMetadataRecord
150///
151/// Schema metadata observed in one committed generation.
152///
153/// Schema metadata is diagnostic ledger history. It is validated for bounded
154/// durable encoding, but `ic-memory` does not prove application schema
155/// support or data migration correctness.
156#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
157#[serde(deny_unknown_fields)]
158pub struct SchemaMetadataRecord {
159    /// Generation that declared this schema metadata.
160    pub(crate) generation: u64,
161    /// Schema metadata declared by that generation.
162    pub(crate) schema: SchemaMetadata,
163}
164
165///
166/// GenerationRecord
167///
168/// Diagnostic metadata for one committed ledger generation.
169/// Construction and decoding require an absent or bounded printable ASCII
170/// runtime fingerprint. Generation ordering and chain integrity remain ledger
171/// validation responsibilities.
172///
173
174#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
175#[serde(deny_unknown_fields)]
176pub struct GenerationRecord {
177    /// Committed generation number.
178    pub(crate) generation: u64,
179    /// Parent generation.
180    pub(crate) parent_generation: u64,
181    /// Optional binary/runtime fingerprint.
182    #[serde(deserialize_with = "deserialize_runtime_fingerprint")]
183    pub(crate) runtime_fingerprint: Option<String>,
184    /// Number of declarations in the generation.
185    pub(crate) declaration_count: u32,
186    /// Optional commit timestamp supplied by the integration layer.
187    #[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
188    pub(crate) committed_at: Option<u64>,
189}
190
191///
192/// RecoveredLedger
193///
194/// Proof object for an allocation ledger that has crossed physical recovery,
195/// logical payload-envelope routing, current-format checks, and committed
196/// integrity validation.
197///
198/// Recovery checks that physical and logical generations agree before
199/// constructing this proof; both generation accessors report that one value.
200///
201/// This type is not serializable and has no public constructor. It is the
202/// provenance boundary required before declarations can mint pre-commit
203/// [`crate::ValidatedAllocations`].
204///
205
206#[derive(Clone, Debug, Eq, PartialEq)]
207pub struct RecoveredLedger {
208    ledger: AllocationLedger,
209}
210
211impl RecoveredLedger {
212    pub(crate) const fn from_trusted_ledger(ledger: AllocationLedger) -> Self {
213        Self { ledger }
214    }
215
216    /// Borrow the recovered canonical allocation ledger.
217    ///
218    /// The returned ledger is diagnostic/staging state. It is not itself an
219    /// authority token; callers must keep passing the `RecoveredLedger` proof
220    /// across validation boundaries.
221    #[must_use]
222    pub const fn ledger(&self) -> &AllocationLedger {
223        &self.ledger
224    }
225
226    /// Return the selected physical committed generation.
227    /// Recovery has established that it equals the current logical generation.
228    #[must_use]
229    pub const fn physical_generation(&self) -> u64 {
230        self.ledger.current_generation
231    }
232
233    /// Return the recovered ledger's current logical generation.
234    #[must_use]
235    pub const fn current_generation(&self) -> u64 {
236        self.ledger.current_generation
237    }
238
239    pub(crate) fn into_ledger(self) -> AllocationLedger {
240        self.ledger
241    }
242}
243
244impl AllocationHistory {
245    #[cfg(test)]
246    pub(crate) const fn from_parts(
247        records: Vec<AllocationRecord>,
248        generations: Vec<GenerationRecord>,
249    ) -> Self {
250        Self {
251            records,
252            generations,
253        }
254    }
255
256    /// Borrow stable-key allocation records in durable order.
257    #[must_use]
258    pub fn records(&self) -> &[AllocationRecord] {
259        &self.records
260    }
261
262    /// Borrow committed generation records in durable order.
263    #[must_use]
264    pub fn generations(&self) -> &[GenerationRecord] {
265        &self.generations
266    }
267
268    /// Return true when the history has no allocation records and no generation records.
269    #[must_use]
270    pub const fn is_empty(&self) -> bool {
271        self.records.is_empty() && self.generations.is_empty()
272    }
273}
274
275impl SchemaMetadataRecord {
276    /// Build a history record from checked schema metadata.
277    /// Ledger integrity validation checks its generation against the history.
278    #[must_use]
279    pub const fn new(generation: u64, schema: SchemaMetadata) -> Self {
280        Self { generation, schema }
281    }
282
283    /// Return the generation that declared this schema metadata.
284    #[must_use]
285    pub const fn generation(&self) -> u64 {
286        self.generation
287    }
288
289    /// Return the schema metadata declared by that generation.
290    #[must_use]
291    pub const fn schema(&self) -> &SchemaMetadata {
292        &self.schema
293    }
294}
295
296impl GenerationRecord {
297    /// Build a committed generation diagnostic record after validating metadata.
298    pub fn new(
299        generation: u64,
300        parent_generation: u64,
301        runtime_fingerprint: Option<String>,
302        declaration_count: u32,
303        committed_at: Option<u64>,
304    ) -> Result<Self, DeclarationSnapshotError> {
305        validate_runtime_fingerprint(runtime_fingerprint.as_deref())?;
306        Ok(Self {
307            generation,
308            parent_generation,
309            runtime_fingerprint,
310            declaration_count,
311            committed_at,
312        })
313    }
314
315    /// Return the committed generation number.
316    #[must_use]
317    pub const fn generation(&self) -> u64 {
318        self.generation
319    }
320
321    /// Return the parent generation.
322    #[must_use]
323    pub const fn parent_generation(&self) -> u64 {
324        self.parent_generation
325    }
326
327    /// Borrow the optional binary/runtime fingerprint.
328    #[must_use]
329    pub fn runtime_fingerprint(&self) -> Option<&str> {
330        self.runtime_fingerprint.as_deref()
331    }
332
333    /// Return the number of declarations in the generation.
334    #[must_use]
335    pub const fn declaration_count(&self) -> u32 {
336        self.declaration_count
337    }
338
339    /// Return the optional commit timestamp supplied by the integration layer.
340    #[must_use]
341    pub const fn committed_at(&self) -> Option<u64> {
342        self.committed_at
343    }
344}
345
346// Require explicit presence and the constructor's text rules while retaining
347// the decoded string without another owned representation.
348fn deserialize_runtime_fingerprint<'de, D: Deserializer<'de>>(
349    deserializer: D,
350) -> Result<Option<String>, D::Error> {
351    let fingerprint = Option::<String>::deserialize(deserializer)?;
352    validate_runtime_fingerprint(fingerprint.as_deref()).map_err(D::Error::custom)?;
353    Ok(fingerprint)
354}
355
356impl AllocationRecord {
357    // SchemaMetadata establishes its own version invariant before staging.
358    // Copy only persisted fields; declaration labels are not ledger history.
359    fn from_declaration(
360        generation: u64,
361        declaration: &AllocationDeclaration,
362        state: AllocationState,
363    ) -> Self {
364        Self {
365            stable_key: declaration.stable_key.clone(),
366            slot: declaration.slot.clone(),
367            state,
368            first_generation: generation,
369            last_seen_generation: generation,
370            schema_history: vec![SchemaMetadataRecord {
371                generation,
372                schema: declaration.schema.clone(),
373            }],
374        }
375    }
376
377    /// Create an active record from a declaration with validated schema metadata.
378    pub(crate) fn active(generation: u64, declaration: &AllocationDeclaration) -> Self {
379        Self::from_declaration(generation, declaration, AllocationState::Active)
380    }
381
382    /// Create a reserved record from a declaration with validated schema metadata.
383    pub(crate) fn reserved(generation: u64, declaration: &AllocationDeclaration) -> Self {
384        Self::from_declaration(generation, declaration, AllocationState::Reserved)
385    }
386
387    /// Return the stable key that owns this allocation record.
388    #[must_use]
389    pub const fn stable_key(&self) -> &StableKey {
390        &self.stable_key
391    }
392
393    /// Return the durable allocation slot owned by this record.
394    #[must_use]
395    pub const fn slot(&self) -> &MemoryManagerSlot {
396        &self.slot
397    }
398
399    /// Return the current allocation lifecycle state.
400    #[must_use]
401    pub const fn state(&self) -> AllocationState {
402        self.state
403    }
404
405    /// Return the first committed generation that recorded this allocation.
406    #[must_use]
407    pub const fn first_generation(&self) -> u64 {
408        self.first_generation
409    }
410
411    /// Return the latest committed generation that observed this allocation.
412    #[must_use]
413    pub const fn last_seen_generation(&self) -> u64 {
414        self.last_seen_generation
415    }
416
417    /// Return the per-generation schema metadata history.
418    #[must_use]
419    pub fn schema_history(&self) -> &[SchemaMetadataRecord] {
420        &self.schema_history
421    }
422
423    pub(super) fn observe_schema(&mut self, generation: u64, schema: &SchemaMetadata) {
424        self.last_seen_generation = generation;
425
426        let latest_schema = self.schema_history.last().map(|record| &record.schema);
427        if latest_schema != Some(schema) {
428            self.schema_history.push(SchemaMetadataRecord {
429                generation,
430                schema: schema.clone(),
431            });
432        }
433    }
434}
435
436impl AllocationLedger {
437    /// Build the known empty genesis used by runtime bootstrap and diagnostics.
438    pub(crate) fn empty_genesis() -> Self {
439        // An empty history at generation zero satisfies committed integrity
440        // without decoded input or declaration references to validate.
441        Self {
442            current_generation: 0,
443            allocation_history: AllocationHistory::default(),
444        }
445    }
446
447    /// Build a ledger DTO and validate structural ledger invariants.
448    ///
449    /// This constructor validates duplicate records, lifecycle state, record
450    /// generation bounds, and schema metadata records. It does not require a
451    /// complete committed-generation chain. Use
452    /// [`AllocationLedger::new_committed`] when constructing an authoritative
453    /// committed ledger DTO.
454    pub fn new(
455        current_generation: u64,
456        allocation_history: AllocationHistory,
457    ) -> Result<Self, LedgerIntegrityError> {
458        let ledger = Self {
459            current_generation,
460            allocation_history,
461        };
462        ledger.validate_integrity()?;
463        Ok(ledger)
464    }
465
466    /// Build a committed ledger DTO and validate strict committed-history invariants.
467    ///
468    /// This constructor runs the same committed-integrity checks used by
469    /// recovery and commit. Use it when the value should be treated as an
470    /// authoritative committed ledger, not merely as a structurally valid DTO.
471    pub fn new_committed(
472        current_generation: u64,
473        allocation_history: AllocationHistory,
474    ) -> Result<Self, LedgerIntegrityError> {
475        let ledger = Self {
476            current_generation,
477            allocation_history,
478        };
479        ledger.validate_committed_integrity()?;
480        Ok(ledger)
481    }
482
483    /// Return the current committed generation selected by recovery.
484    #[must_use]
485    pub const fn current_generation(&self) -> u64 {
486        self.current_generation
487    }
488
489    /// Return the historical allocation facts.
490    #[must_use]
491    pub const fn allocation_history(&self) -> &AllocationHistory {
492        &self.allocation_history
493    }
494}