ic_memory/lib.rs
1#![deny(unsafe_code, unsafe_op_in_unsafe_fn)]
2#![deny(rustdoc::broken_intra_doc_links)]
3#![doc = include_str!("../README.md")]
4
5//! Stable-memory allocation-governance primitives for Internet Computer
6//! canister upgrades.
7//!
8//! `ic-memory` prevents stable-memory slot drift.
9//!
10//! Once a stable key is committed to a physical allocation slot, future binaries
11//! must either reopen that same stable key on that same slot or declare a new
12//! stable key.
13//!
14//! The crate records and validates durable ownership in both directions: an
15//! active stable key cannot move to a different physical slot, and an active
16//! physical slot cannot be reused by a different stable key.
17//!
18//! The intended runtime integration flow is:
19//!
20//! 1. Recover the persisted allocation ledger.
21//! 2. Admit consumer identity and authorized historical selections from bounded
22//! metadata under the host's `RuntimeBootstrapPolicy`.
23//! 3. Resolve key requests in the host-wide pool under current namespace grants,
24//! then validate retained key-to-ID bindings and application policy.
25//! 4. Stage and durably persist the next generation.
26//! 5. Only then open stable-memory handles through committed allocation
27//! authority.
28//!
29//! This crate owns allocation invariants, not framework policy. Namespace
30//! rules, controller authorization, endpoint lifecycle, schema migrations, and
31//! application validation belong to the framework or application.
32//!
33//! The host supplies one [`MemoryAllocationPool`] with explicit namespace grants
34//! and physical exclusions. Linked components request permanent keys and name
35//! their owner; they do not select numeric IDs or reserve component subranges.
36//! Namespace grants are current host policy, not caller authentication or
37//! persisted ownership labels. Application admission remains host-owned.
38//!
39//! Use these primitives before opening stable-memory handles. Integrations
40//! should recover the historical ledger, declare the stores expected by the
41//! current binary, admit recovered identity, resolve requests, validate against
42//! history and policy, persist a new generation, and only then publish authority
43//! before opening slots through the storage owner.
44//!
45//! Bounded physical attribution is available through
46//! [`MemoryRuntime::memory_allocations`] and
47//! [`MemoryRuntime::memory_allocation_summary`]. It reports actual persisted
48//! buckets and explicit residuals without decoding retained ownership. Virtual
49//! extent is not payload occupancy. Opens return [`RuntimeMemory`]; explicit
50//! [`MemoryManagerConfig`] selects fresh-state buckets or checks a persisted
51//! setting without migration. The default remains 128 pages.
52//!
53//! [`MemoryRuntime`] is the canonical owner for one backing memory instance. It
54//! owns that memory's manager, ledger persistence, bootstrap lifecycle, committed
55//! bindings, opens, and diagnostics. Each bootstrap attempt fallibly decodes
56//! its ledger record and uses a temporary cell for capacity-checked writes.
57//! Linked code contributes declarations to
58//! one immutable [`SealedDeclarationSnapshot`], which is supplied to each
59//! runtime independently.
60//!
61//! The host supplies the complete checked request snapshot, allocation pool and
62//! admission policy directly to the runtime. Component factories and generators
63//! contribute request lists; opening a store never registers a declaration.
64//! Exactly one runtime owns bootstrap and persistence for each backing memory.
65//!
66//! `ic-stable-structures` `MemoryManager` IDs are the first-class supported
67//! physical slot substrate. That ID domain is `u8`: IDs `0..=254` are usable,
68//! and ID `255` is always the `ic-stable-structures` unallocated sentinel.
69//! Protected current-snapshot commits and stable-cell encoding remain internal to the
70//! runtime. Public diagnostics describe their state without granting a manual
71//! commit or persistence-confirmation route.
72//!
73//! Hosts use [`DefaultMemoryImpl`], [`VectorMemory`] and [`Memory`] for backing
74//! setup. [`RuntimeMemory`] is an exclusive allocation lease; production typed
75//! collections consume these leases through IC Storage’s governed wrappers.
76
77mod allocation_pool;
78mod bounded_writer;
79mod cbor;
80mod constants;
81mod declaration;
82mod diagnostics;
83mod hash;
84mod key;
85mod ledger;
86mod physical;
87mod policy;
88mod requests;
89mod runtime;
90mod slot;
91mod sort;
92mod stable_cell;
93mod text;
94mod validation;
95
96#[cfg(test)]
97mod test_cbor {
98 use serde::{Serialize, de::DeserializeOwned};
99
100 pub use ciborium::Value;
101
102 pub fn to_vec<T: Serialize>(
103 value: &T,
104 ) -> Result<Vec<u8>, ciborium::ser::Error<std::io::Error>> {
105 let mut bytes = Vec::new();
106 ciborium::into_writer(value, &mut bytes)?;
107 Ok(bytes)
108 }
109
110 pub fn from_slice<T: DeserializeOwned>(
111 bytes: &[u8],
112 ) -> Result<T, ciborium::de::Error<std::io::Error>> {
113 crate::cbor::from_slice_exact(bytes)
114 }
115
116 pub fn to_value<T: Serialize>(value: T) -> Result<Value, ciborium::value::Error> {
117 Value::serialized(&value)
118 }
119
120 pub fn hex_fixture(contents: &str) -> Vec<u8> {
121 let hex = contents
122 .chars()
123 .filter(|char| !char.is_whitespace())
124 .collect::<String>();
125 assert_eq!(hex.len() % 2, 0, "fixture hex must have byte pairs");
126 hex.as_bytes()
127 .as_chunks::<2>()
128 .0
129 .iter()
130 .map(|pair| {
131 let pair = std::str::from_utf8(pair).expect("fixture hex is utf8");
132 u8::from_str_radix(pair, 16).expect("fixture hex byte")
133 })
134 .collect()
135 }
136}
137
138/// Backing setup and IO interfaces from the exact substrate dependency.
139/// Hosts own backing custody; production collections belong behind IC Storage's
140/// governed wrappers and consume [`RuntimeMemory`] leases. Import visibility is
141/// not admission: implementing `Memory` does not construct a checked handle.
142/// Collection codec traits belong to Storage; metric records and restoration
143/// belong to IC Metrics Stable.
144pub use ic_stable_structures::{DefaultMemoryImpl, Memory, VectorMemory};
145
146pub use allocation_pool::{MemoryAllocationPool, MemoryAllocationPoolError, MemoryAuthority};
147pub use constants::{
148 MAX_LEDGER_BYTES, MAX_LEDGER_NESTING, MAX_LEDGER_RECORD_BYTES, WASM_PAGE_SIZE_BYTES,
149};
150pub use declaration::AllocationDeclaration;
151pub use diagnostics::{DiagnosticExport, DiagnosticMemorySize, DiagnosticRecord};
152pub use key::{StableKey, StableKeyError};
153use ledger::{AllocationLedger, LedgerCommitStore, RecoveredLedger};
154pub use ledger::{AllocationRecord, AllocationStageError, LedgerCommitError, LedgerIntegrityError};
155pub use physical::{CommitRecoveryError, CommitSnapshotDiagnostic};
156pub use policy::{PolicyIdentity, RuntimeBootstrapPolicy};
157pub use requests::{MemoryDeclarationError, MemoryRequest, SealedDeclarationSnapshot};
158pub use runtime::{
159 BootstrapAdmission, BootstrapAdmissionError, GenericAllocationPolicy, MemoryAllocation,
160 MemoryAllocationSummary, MemoryAllocations, MemoryBindingSummary, MemoryManagerConfig,
161 MemoryManagerLayoutError, MemoryResolutionError, MemoryRuntime, RuntimeAdoptionError,
162 RuntimeBootstrapError, RuntimeConstructionError, RuntimeDiagnosticError, RuntimeGrowError,
163 RuntimeMemory, RuntimeOpenError,
164};
165pub use slot::{
166 IC_MEMORY_AUTHORITY_OWNER, IC_MEMORY_LEDGER_STABLE_KEY, IC_MEMORY_STABLE_KEY_PREFIX,
167 MEMORY_MANAGER_GOVERNANCE_MAX_ID, MEMORY_MANAGER_INVALID_ID, MEMORY_MANAGER_LEDGER_ID,
168 MEMORY_MANAGER_MAX_ID, MEMORY_MANAGER_MIN_ID, MemoryManagerSlot, MemoryManagerSlotError,
169 is_ic_memory_stable_key, validate_memory_manager_id,
170};
171pub use stable_cell::{
172 STABLE_CELL_HEADER_SIZE, STABLE_CELL_LAYOUT_VERSION, STABLE_CELL_MAGIC,
173 STABLE_CELL_VALUE_OFFSET, StableCellLedgerError, StableCellPayloadError,
174 decode_stable_cell_payload,
175};
176#[cfg(test)]
177use stable_cell::{decode_stable_cell_commit_store, decode_stable_cell_commit_store_from_memory};
178pub use validation::AllocationValidationError;
179
180#[cfg(test)]
181mod allocation_measurements_tests;
182
183#[cfg(any(test, feature = "test-support"))]
184pub mod testing;