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