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
71type LedgerCell<M> = Cell<StableCellLedgerRecord, RuntimeMemory<M>>;
72
73enum RuntimeLifecycle {
74 Unbootstrapped,
75 Bootstrapped {
76 committed_allocations: CommittedAllocations,
77 binding: RuntimeBootstrapBinding,
78 },
79}
80
81struct RuntimeBootstrapBinding {
82 source: SealedDeclarationSnapshot,
83 declarations: SealedDeclarationSnapshot,
84 policy_identity: PolicyIdentity,
85}
86
87pub struct MemoryRuntime<M: Memory> {
102 memory_manager: MemoryManager<Rc<M>>,
103 growth: Rc<backing::GrowthState<M>>,
106 ledger_cell: Option<LedgerCell<M>>,
107 lifecycle: RuntimeLifecycle,
108}
109
110impl<M: Memory> MemoryRuntime<M> {
111 pub fn new(memory: M) -> Result<Self, RuntimeConstructionError> {
131 Self::construct(memory, None)
132 }
133
134 pub fn new_with_config(
143 memory: M,
144 config: MemoryManagerConfig,
145 ) -> Result<Self, RuntimeConstructionError> {
146 Self::construct(memory, Some(config))
147 }
148
149 fn construct(
150 memory: M,
151 requested: Option<MemoryManagerConfig>,
152 ) -> Result<Self, RuntimeConstructionError> {
153 if cfg!(target_endian = "big") {
154 return Err(MemoryManagerLayoutError::UnsupportedByteOrder.into());
155 }
156 let (bucket_size_pages, allocated_buckets) = if memory.size() == 0 {
157 if memory.grow(1) == -1 {
161 return Err(RuntimeGrowError::BackingRefused {
162 additional_pages: 1,
163 }
164 .into());
165 }
166 (requested.unwrap_or_default().bucket_size_pages(), 0)
167 } else {
168 let measured = layout::read(&memory)?;
169 let actual = measured.bucket_pages;
170 if let Some(config) = requested {
171 check_bucket_size(actual, config)?;
172 }
173 (actual, measured.allocated_buckets)
174 };
175 let backing = Rc::new(memory);
176 let growth = Rc::new(backing::GrowthState {
177 backing: Rc::clone(&backing),
178 bucket_size_pages,
179 allocated_buckets: std::cell::RefCell::new(allocated_buckets),
180 });
181 Ok(Self {
182 memory_manager: MemoryManager::init_with_bucket_size(
183 Rc::clone(&backing),
184 bucket_size_pages,
185 ),
186 growth,
187 ledger_cell: None,
188 lifecycle: RuntimeLifecycle::Unbootstrapped,
189 })
190 }
191
192 #[must_use]
194 pub fn memory_manager_config(&self) -> MemoryManagerConfig {
195 MemoryManagerConfig::from_validated(self.growth.bucket_size_pages)
197 }
198
199 #[must_use]
201 pub const fn is_bootstrapped(&self) -> bool {
202 matches!(self.lifecycle, RuntimeLifecycle::Bootstrapped { .. })
203 }
204
205 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 self.initialize_ledger_cell()?;
253 let mut record = self
254 .ledger_cell
255 .as_ref()
256 .expect("successful ledger initialization establishes the cell")
257 .get()
258 .clone();
259 let genesis = AllocationLedger::empty_genesis();
260 let recovered = record.store_mut().recover_or_initialize(&genesis)?;
261 let mut admission = BootstrapAdmission::new(recovered.ledger(), declarations);
262 let preparation = policy.prepare_bootstrap(&mut admission);
263 let historical = admission.complete()?;
264 preparation.map_err(RuntimeBootstrapError::AdmissionPolicy)?;
265 let resolved = declarations.resolve(recovered.ledger(), historical)?;
266 let runtime_policy = RuntimeMemoryManagerPolicy {
267 declarations: &resolved,
268 custom_policy: policy,
269 };
270 let commit = AllocationBootstrap::new(record.store_mut())
271 .validate_against(
272 recovered,
273 resolved.allocation_snapshot().clone(),
274 &runtime_policy,
275 None,
276 )
277 .map_err(runtime_bootstrap_error_from_bootstrap)?;
278 self.persist_ledger_record(record)?;
279 let committed = external_runtime_allocations(commit.confirm_persisted());
280 self.lifecycle = RuntimeLifecycle::Bootstrapped {
281 committed_allocations: committed,
282 binding: RuntimeBootstrapBinding {
283 source: declarations.clone(),
284 declarations: resolved,
285 policy_identity,
286 },
287 };
288 Ok(())
289 }
290
291 pub const fn committed_allocations(&self) -> Result<&CommittedAllocations, RuntimeOpenError> {
293 match &self.lifecycle {
294 RuntimeLifecycle::Unbootstrapped => Err(RuntimeOpenError::NotBootstrapped),
295 RuntimeLifecycle::Bootstrapped {
296 committed_allocations,
297 ..
298 } => Ok(committed_allocations),
299 }
300 }
301
302 pub fn open_memory_by_key(
304 &self,
305 stable_key: &str,
306 ) -> Result<RuntimeMemory<M>, RuntimeOpenError> {
307 Ok(self.memory(self.memory_id(stable_key)?))
308 }
309
310 pub fn open_memory(
312 &self,
313 stable_key: &str,
314 expected_id: u8,
315 ) -> Result<RuntimeMemory<M>, RuntimeOpenError> {
316 let committed_id = self.memory_id(stable_key)?;
317 if committed_id != expected_id {
318 return Err(RuntimeOpenError::MemoryIdMismatch {
319 stable_key: stable_key.to_string(),
320 committed_id,
321 requested_id: expected_id,
322 });
323 }
324 Ok(self.memory(committed_id))
325 }
326
327 pub fn memory_id(&self, stable_key: &str) -> Result<u8, RuntimeOpenError> {
334 let key = StableKey::parse(stable_key)?;
335 if crate::is_ic_memory_stable_key(key.as_str()) {
336 return Err(RuntimeOpenError::ReservedStableKey {
337 stable_key: stable_key.to_string(),
338 });
339 }
340 let slot = self
341 .committed_allocations()?
342 .slot_for(&key)
343 .ok_or_else(|| RuntimeOpenError::StableKeyNotCommitted(stable_key.to_string()))?;
344 Ok(slot.memory_manager_id().expect("committed allocation slot"))
345 }
346
347 fn initialize_ledger_cell<P>(&mut self) -> Result<(), RuntimeBootstrapError<P>> {
348 if self.ledger_cell.is_some() {
349 return Ok(());
350 }
351 let memory = self.memory(MEMORY_MANAGER_LEDGER_ID);
352 crate::validate_stable_cell_ledger_memory(&memory)?;
353 ensure_ledger_cell_capacity(&memory, &StableCellLedgerRecord::default())?;
354 self.ledger_cell = Some(Cell::init(memory, StableCellLedgerRecord::default()));
355 Ok(())
356 }
357
358 fn persist_ledger_record<P>(
359 &mut self,
360 record: StableCellLedgerRecord,
361 ) -> Result<(), RuntimeBootstrapError<P>> {
362 let memory = self.memory(MEMORY_MANAGER_LEDGER_ID);
363 ensure_ledger_cell_capacity(&memory, &record)?;
364 let cell = self
365 .ledger_cell
366 .as_mut()
367 .expect("ledger persistence follows successful initialization");
368 let _previous = cell.set(record);
369 Ok(())
370 }
371
372 fn memory(&self, id: u8) -> RuntimeMemory<M> {
373 RuntimeMemory {
374 memory: self.memory_manager.get(MemoryId::new(id)),
375 growth: Rc::clone(&self.growth),
376 }
377 }
378
379 fn ledger_record_from_memory(&self) -> Result<StableCellLedgerRecord, StableCellLedgerError> {
380 decode_stable_cell_ledger_record_from_memory(&self.memory(MEMORY_MANAGER_LEDGER_ID))
381 }
382}
383
384impl RuntimeBootstrapBinding {
385 fn validate<P>(
386 &self,
387 declarations: &SealedDeclarationSnapshot,
388 policy_identity: &PolicyIdentity,
389 ) -> Result<(), RuntimeBootstrapError<P>> {
390 if &self.source != declarations {
391 return Err(RuntimeBootstrapError::DeclarationSnapshotMismatch);
392 }
393 if &self.policy_identity != policy_identity {
394 return Err(RuntimeBootstrapError::PolicyIdentityMismatch {
395 established: self.policy_identity.clone(),
396 requested: policy_identity.clone(),
397 });
398 }
399 Ok(())
400 }
401}
402
403fn ensure_ledger_cell_capacity<M: Memory, P>(
404 memory: &RuntimeMemory<M>,
405 record: &StableCellLedgerRecord,
406) -> Result<(), RuntimeBootstrapError<P>> {
407 let value_size = record.encoded_size();
408 if value_size > crate::constants::MAX_LEDGER_RECORD_BYTES {
409 return Err(RuntimeBootstrapError::StableCellLedgerWriteTooLarge { value_size });
410 }
411 let required_bytes = STABLE_CELL_VALUE_OFFSET + value_size as u64;
413 let available_bytes = memory.size().saturating_mul(crate::WASM_PAGE_SIZE_BYTES);
414 if required_bytes <= available_bytes {
415 return Ok(());
416 }
417 let grow_by = (required_bytes - available_bytes).div_ceil(crate::WASM_PAGE_SIZE_BYTES);
418 memory.grow(grow_by)?;
419 Ok(())
420}
421
422fn external_runtime_allocations(committed: CommittedAllocations) -> CommittedAllocations {
423 committed.without_stable_key_prefix(crate::IC_MEMORY_STABLE_KEY_PREFIX)
424}
425
426const fn check_bucket_size(
427 actual: u16,
428 requested: MemoryManagerConfig,
429) -> Result<(), RuntimeConstructionError> {
430 if actual != requested.bucket_size_pages() {
431 return Err(RuntimeConstructionError::BucketSizeMismatch {
432 persisted: actual,
433 requested: requested.bucket_size_pages(),
434 });
435 }
436 Ok(())
437}