Skip to main content

ic_memory/runtime/
mod.rs

1mod admission;
2#[cfg(test)]
3mod admission_tests;
4mod adoption;
5#[cfg(test)]
6mod adoption_tests;
7mod allocations;
8mod backing;
9mod config;
10mod default;
11mod diagnostics;
12mod error;
13mod layout;
14mod policy;
15
16#[cfg(test)]
17mod allocation_tests;
18#[cfg(test)]
19mod growth_tests;
20#[cfg(test)]
21#[expect(
22    unsafe_code,
23    reason = "exercise raw reads with valid uninitialized destinations"
24)]
25mod read_tests;
26#[cfg(test)]
27mod request_tests;
28#[cfg(test)]
29mod tests;
30
31pub use admission::{BootstrapAdmission, BootstrapAdmissionError, RecoveredAllocationMetadata};
32pub use adoption::RuntimeAdoptionError;
33
34pub use allocations::{
35    AllocationBinding, AllocationRangeClaim, MemoryAllocation, MemoryAllocationSummary,
36    MemoryAllocations, MemoryBindingSummary,
37};
38pub use backing::RuntimeMemory;
39pub use config::MemoryManagerConfig;
40pub use default::{
41    bootstrap_default_memory_manager, bootstrap_default_memory_manager_with_config,
42    bootstrap_default_memory_manager_with_policy, committed_allocations,
43    default_memory_manager_commit_recovery_diagnostic, default_memory_manager_diagnostic_export,
44    default_memory_manager_doctor_report, default_memory_manager_doctor_report_with_policy,
45    default_memory_manager_memory_allocation_summary, default_memory_manager_memory_allocations,
46    default_memory_manager_memory_id, is_default_memory_manager_bootstrapped,
47    open_default_memory_manager_memory, open_default_memory_manager_memory_by_key,
48    verify_default_memory_manager_authority,
49};
50pub use error::{
51    MemoryResolutionError, RuntimeBootstrapError, RuntimeConstructionError, RuntimeDiagnosticError,
52    RuntimeGrowError, RuntimeOpenError, RuntimePolicyError, RuntimeStateError,
53};
54pub use layout::MemoryManagerLayoutError;
55pub use policy::GenericRangePolicy;
56
57use self::policy::{RuntimeMemoryManagerPolicy, runtime_bootstrap_error_from_bootstrap};
58use crate::{
59    AllocationBootstrap, AllocationLedger, CommittedAllocations, PolicyIdentity,
60    RuntimeBootstrapPolicy, STABLE_CELL_VALUE_OFFSET, StableCellLedgerError,
61    StableCellLedgerRecord, StableKey, registry::SealedDeclarationSnapshot,
62    slot::MEMORY_MANAGER_LEDGER_ID, stable_cell::decode_stable_cell_ledger_record_from_memory,
63};
64use ic_stable_structures::{
65    Cell, Memory,
66    memory_manager::{MemoryId, MemoryManager},
67};
68
69use std::rc::Rc;
70
71enum RuntimeLifecycle {
72    Unbootstrapped,
73    Bootstrapped {
74        committed_allocations: CommittedAllocations,
75        binding: RuntimeBootstrapBinding,
76    },
77}
78
79struct RuntimeBootstrapBinding {
80    source: SealedDeclarationSnapshot,
81    declarations: SealedDeclarationSnapshot,
82    policy_identity: PolicyIdentity,
83}
84
85///
86/// MemoryRuntime
87///
88/// Canonical owner of allocation bootstrap state for one backing memory.
89///
90/// The runtime owns its `MemoryManager`, allocation-ledger persistence, bootstrap
91/// lifecycle, committed allocation capability, opens, and diagnostics. Static
92/// linked-program declarations are supplied separately as one immutable
93/// [`SealedDeclarationSnapshot`].
94///
95/// Each bootstrap attempt fallibly decodes its ledger record from persisted
96/// memory. Capacity-checked writes use `Cell`; diagnostics also read persisted
97/// memory directly.
98///
99/// `M` needs only [`Memory`]. The runtime does not require the backing memory
100/// to be `Send`, `Sync`, `Clone`, or `'static`.
101///
102
103pub struct MemoryRuntime<M: Memory> {
104    memory_manager: MemoryManager<Rc<M>>,
105    // Shared backing, immutable geometry and live accounting belong to growth.
106    // Handles reserve physical capacity; the manager owns bucket metadata.
107    growth: Rc<backing::GrowthState<M>>,
108    lifecycle: RuntimeLifecycle,
109}
110
111impl<M: Memory> MemoryRuntime<M> {
112    /// Construct an unbootstrapped runtime without overwriting foreign memory.
113    ///
114    /// Empty backing memory is initialized as an
115    /// `ic_stable_structures::MemoryManager`. Nonempty memory must pass bounded
116    /// validation of the current manager header, bucket table, and extents; otherwise
117    /// construction returns a typed error before the manager can
118    /// write its header or allocation table. A pre-grown blank memory is
119    /// nonempty and is therefore rejected rather than assumed disposable.
120    ///
121    /// # Errors
122    ///
123    /// Returns [`RuntimeConstructionError::ForeignMemory`] for nonempty memory
124    /// without `MemoryManager` magic, or
125    /// [`RuntimeConstructionError::UnsupportedMemoryManagerVersion`] when the
126    /// magic is recognized but the layout version is not current. Invalid
127    /// metadata returns [`RuntimeConstructionError::Layout`]. Refused fresh
128    /// metadata growth returns [`RuntimeConstructionError::Growth`] without
129    /// writes, allowing the same backing memory to be retried. Reopening honors
130    /// the actual persisted bucket size; only fresh memory uses 128 pages.
131    pub fn new(memory: M) -> Result<Self, RuntimeConstructionError> {
132        Self::construct(memory, None)
133    }
134
135    /// Construct with an explicit immutable bucket policy. Existing memory must
136    /// match exactly; mismatches fail before manager initialization or writes.
137    ///
138    /// # Errors
139    ///
140    /// Returns the construction errors described by [`Self::new`], or
141    /// [`RuntimeConstructionError::BucketSizeMismatch`] when existing geometry
142    /// differs from `config`.
143    pub fn new_with_config(
144        memory: M,
145        config: MemoryManagerConfig,
146    ) -> Result<Self, RuntimeConstructionError> {
147        Self::construct(memory, Some(config))
148    }
149
150    fn construct(
151        memory: M,
152        requested: Option<MemoryManagerConfig>,
153    ) -> Result<Self, RuntimeConstructionError> {
154        if cfg!(target_endian = "big") {
155            return Err(MemoryManagerLayoutError::UnsupportedByteOrder.into());
156        }
157        let (bucket_size_pages, allocated_buckets) = if memory.size() == 0 {
158            // Reserve the metadata page before the dependency writes its header.
159            // This fresh allocation is owned here; caller-supplied nonempty
160            // memory still passes the layout checks below before any writes.
161            if memory.grow(1) == -1 {
162                return Err(RuntimeGrowError::BackingRefused {
163                    additional_pages: 1,
164                }
165                .into());
166            }
167            (requested.unwrap_or_default().bucket_size_pages(), 0)
168        } else {
169            let measured = layout::read(&memory)?;
170            let actual = measured.bucket_pages;
171            if let Some(config) = requested {
172                check_bucket_size(actual, config)?;
173            }
174            (actual, measured.allocated_buckets)
175        };
176        let backing = Rc::new(memory);
177        let growth = Rc::new(backing::GrowthState {
178            backing: Rc::clone(&backing),
179            bucket_size_pages,
180            allocated_buckets: std::cell::RefCell::new(allocated_buckets),
181        });
182        Ok(Self {
183            memory_manager: MemoryManager::init_with_bucket_size(
184                Rc::clone(&backing),
185                bucket_size_pages,
186            ),
187            growth,
188            lifecycle: RuntimeLifecycle::Unbootstrapped,
189        })
190    }
191
192    /// Return the immutable bucket configuration bound to this runtime's manager.
193    #[must_use]
194    pub fn memory_manager_config(&self) -> MemoryManagerConfig {
195        // Construction has already validated the nonzero persisted setting.
196        MemoryManagerConfig::from_validated(self.growth.bucket_size_pages)
197    }
198
199    /// Return whether this runtime has published committed allocation authority.
200    #[must_use]
201    pub const fn is_bootstrapped(&self) -> bool {
202        matches!(self.lifecycle, RuntimeLifecycle::Bootstrapped { .. })
203    }
204
205    /// Bootstrap this backing memory from one immutable declaration snapshot.
206    ///
207    /// Recovery, metadata admission, logical resolution, policy evaluation,
208    /// staging, persistence and capability publication are local to this runtime.
209    /// A repeated call is idempotent only when the sealed declaration snapshot and
210    /// [`RuntimeBootstrapPolicy::runtime_bootstrap_identity`] match the
211    /// successful bootstrap. A mismatch returns a typed error without
212    /// advancing the durable generation or re-evaluating policy.
213    /// Independently sealed snapshots match when their canonical contents are equal.
214    ///
215    /// # Panics
216    ///
217    /// Panics if a private runtime or encoding invariant is broken, or backing
218    /// memory or a policy callback panics.
219    pub fn bootstrap<P: RuntimeBootstrapPolicy>(
220        &mut self,
221        declarations: &SealedDeclarationSnapshot,
222        policy: &P,
223    ) -> Result<&CommittedAllocations, RuntimeBootstrapError<P::Error>> {
224        let policy_identity = policy.runtime_bootstrap_identity()?;
225        let already_bootstrapped = match &self.lifecycle {
226            RuntimeLifecycle::Unbootstrapped => false,
227            RuntimeLifecycle::Bootstrapped { binding, .. } => {
228                binding.validate(declarations, &policy_identity)?;
229                true
230            }
231        };
232        if !already_bootstrapped {
233            self.bootstrap_unbootstrapped(declarations, policy, policy_identity)?;
234        }
235        match &self.lifecycle {
236            RuntimeLifecycle::Bootstrapped {
237                committed_allocations,
238                ..
239            } => Ok(committed_allocations),
240            RuntimeLifecycle::Unbootstrapped => {
241                unreachable!("successful bootstrap publishes committed allocations")
242            }
243        }
244    }
245
246    fn bootstrap_unbootstrapped<P: RuntimeBootstrapPolicy>(
247        &mut self,
248        declarations: &SealedDeclarationSnapshot,
249        policy: &P,
250        policy_identity: PolicyIdentity,
251    ) -> Result<(), RuntimeBootstrapError<P::Error>> {
252        let memory = self.memory(MEMORY_MANAGER_LEDGER_ID);
253        let mut record = decode_stable_cell_ledger_record_from_memory(&memory)?;
254        if memory.size() == 0 {
255            // Empty memory decodes to an uninitialized record. Preserve fresh
256            // cell acquisition before admission without persisting genesis.
257            ensure_ledger_cell_capacity(&memory, &record)?;
258            drop(Cell::new(memory.clone(), StableCellLedgerRecord::default()));
259        }
260        let genesis = AllocationLedger::empty_genesis();
261        let recovered = record.store_mut().recover_or_initialize(&genesis)?;
262        let mut admission = BootstrapAdmission::new(recovered.ledger(), declarations);
263        let preparation = policy.prepare_bootstrap(&mut admission);
264        let historical = admission.complete()?;
265        preparation.map_err(RuntimeBootstrapError::AdmissionPolicy)?;
266        let resolved = declarations.resolve(recovered.ledger(), historical)?;
267        let runtime_policy = RuntimeMemoryManagerPolicy {
268            declarations: &resolved,
269            custom_policy: policy,
270        };
271        let commit = AllocationBootstrap::new(record.store_mut())
272            .validate_against(
273                recovered,
274                resolved.allocation_snapshot().clone(),
275                &runtime_policy,
276                None,
277            )
278            .map_err(runtime_bootstrap_error_from_bootstrap)?;
279        ensure_ledger_cell_capacity(&memory, &record)?;
280        drop(Cell::new(memory, record));
281        let committed = commit.confirm_persisted().into_application_allocations();
282        self.lifecycle = RuntimeLifecycle::Bootstrapped {
283            committed_allocations: committed,
284            binding: RuntimeBootstrapBinding {
285                source: declarations.clone(),
286                declarations: resolved,
287                policy_identity,
288            },
289        };
290        Ok(())
291    }
292
293    /// Borrow this runtime's committed allocation-open capability.
294    pub const fn committed_allocations(&self) -> Result<&CommittedAllocations, RuntimeOpenError> {
295        match &self.lifecycle {
296            RuntimeLifecycle::Unbootstrapped => Err(RuntimeOpenError::NotBootstrapped),
297            RuntimeLifecycle::Bootstrapped {
298                committed_allocations,
299                ..
300            } => Ok(committed_allocations),
301        }
302    }
303
304    /// Open by durable key using only this runtime's persisted current capability.
305    pub fn open_memory_by_key(
306        &self,
307        stable_key: &str,
308    ) -> Result<RuntimeMemory<M>, RuntimeOpenError> {
309        Ok(self.memory(self.memory_id(stable_key)?))
310    }
311
312    /// Open this runtime's committed memory by stable key and expected ID.
313    pub fn open_memory(
314        &self,
315        stable_key: &str,
316        expected_id: u8,
317    ) -> Result<RuntimeMemory<M>, RuntimeOpenError> {
318        let committed_id = self.memory_id(stable_key)?;
319        if committed_id != expected_id {
320            return Err(RuntimeOpenError::MemoryIdMismatch {
321                stable_key: stable_key.to_string(),
322                committed_id,
323                requested_id: expected_id,
324            });
325        }
326        Ok(self.memory(committed_id))
327    }
328
329    /// Resolve an application key's committed ID without opening memory,
330    /// reading history, or changing the host's policy or bucket configuration.
331    pub fn memory_id(&self, stable_key: &str) -> Result<u8, RuntimeOpenError> {
332        let key = StableKey::parse(stable_key)?;
333        if crate::is_ic_memory_stable_key(key.as_str()) {
334            return Err(RuntimeOpenError::ReservedStableKey {
335                stable_key: stable_key.to_string(),
336            });
337        }
338        let slot = self
339            .committed_allocations()?
340            .slot_for(&key)
341            .ok_or_else(|| RuntimeOpenError::StableKeyNotCommitted(stable_key.to_string()))?;
342        Ok(slot.id())
343    }
344
345    fn memory(&self, id: u8) -> RuntimeMemory<M> {
346        RuntimeMemory {
347            memory: self.memory_manager.get(MemoryId::new(id)),
348            growth: Rc::clone(&self.growth),
349        }
350    }
351
352    fn ledger_record_from_memory(&self) -> Result<StableCellLedgerRecord, StableCellLedgerError> {
353        decode_stable_cell_ledger_record_from_memory(&self.memory(MEMORY_MANAGER_LEDGER_ID))
354    }
355}
356
357impl RuntimeBootstrapBinding {
358    fn validate<P>(
359        &self,
360        declarations: &SealedDeclarationSnapshot,
361        policy_identity: &PolicyIdentity,
362    ) -> Result<(), RuntimeBootstrapError<P>> {
363        if &self.source != declarations {
364            return Err(RuntimeBootstrapError::DeclarationSnapshotMismatch);
365        }
366        if &self.policy_identity != policy_identity {
367            return Err(RuntimeBootstrapError::PolicyIdentityMismatch {
368                established: self.policy_identity.clone(),
369                requested: policy_identity.clone(),
370            });
371        }
372        Ok(())
373    }
374}
375
376fn ensure_ledger_cell_capacity<M: Memory, P>(
377    memory: &RuntimeMemory<M>,
378    record: &StableCellLedgerRecord,
379) -> Result<(), RuntimeBootstrapError<P>> {
380    let value_size = record.encoded_size();
381    if value_size > crate::constants::MAX_LEDGER_RECORD_BYTES {
382        return Err(RuntimeBootstrapError::StableCellLedgerWriteTooLarge { value_size });
383    }
384    // The record limit is below u32::MAX, including the eight-byte cell header.
385    let required_bytes = STABLE_CELL_VALUE_OFFSET + value_size as u64;
386    let available_bytes = memory.size().saturating_mul(crate::WASM_PAGE_SIZE_BYTES);
387    if required_bytes <= available_bytes {
388        return Ok(());
389    }
390    let grow_by = (required_bytes - available_bytes).div_ceil(crate::WASM_PAGE_SIZE_BYTES);
391    memory.grow(grow_by)?;
392    Ok(())
393}
394
395const fn check_bucket_size(
396    actual: u16,
397    requested: MemoryManagerConfig,
398) -> Result<(), RuntimeConstructionError> {
399    if actual != requested.bucket_size_pages() {
400        return Err(RuntimeConstructionError::BucketSizeMismatch {
401            persisted: actual,
402            requested: requested.bucket_size_pages(),
403        });
404    }
405    Ok(())
406}