Skip to main content

ic_memory/runtime/
admission.rs

1use crate::{
2    AllocationLedger, AllocationSlotDescriptor, AllocationState, MemoryRequest, SchemaMetadata,
3    SealedDeclarationSnapshot, StableKey,
4};
5
6///
7/// RecoveredAllocationMetadata
8///
9/// Validated allocation evidence borrowed during bootstrap preparation. This
10/// metadata grants no memory access and contains no application payload or
11/// historical authority identity. Host grants supply current authorization.
12///
13
14#[derive(Clone, Copy, Debug)]
15pub struct RecoveredAllocationMetadata<'a> {
16    /// Durable allocation identity.
17    pub stable_key: &'a StableKey,
18    /// Persisted assignment, not permission to open it.
19    pub slot: &'a AllocationSlotDescriptor,
20    /// Current generic allocation lifecycle state.
21    pub state: AllocationState,
22    /// Latest diagnostic schema metadata, not application schema validation.
23    pub schema: &'a SchemaMetadata,
24}
25
26///
27/// BootstrapAdmissionError
28///
29/// Historical declaration completion rejected before staging or persistence.
30///
31
32#[non_exhaustive]
33#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
34pub enum BootstrapAdmissionError {
35    #[error("historical key {0} is unknown")]
36    Unknown(StableKey),
37    #[error("historical key {0} is retired")]
38    Retired(StableKey),
39    #[error("key {0} is already declared or selected")]
40    Duplicate(StableKey),
41    #[error("completed declarations exceed 254 external allocations")]
42    TooManyDeclarations,
43    #[error("historical selection {stable_key} by {authority} lacks a current grant: {source}")]
44    Range {
45        stable_key: StableKey,
46        authority: String,
47        source: crate::MemoryManagerRangeAuthorityError,
48    },
49    #[error(transparent)]
50    Registry(#[from] crate::StaticMemoryDeclarationError),
51}
52
53///
54/// BootstrapAdmission
55///
56/// Bounded preparation context supplied only after validated ledger recovery.
57/// Consumers may reject identity transitions or explicitly include known
58/// historical allocations before the existing resolve/validate/commit boundary.
59/// No memory handles or mutable recovered state are exposed. Failed selections
60/// poison this attempt even if a consumer ignores their returned errors.
61///
62
63pub struct BootstrapAdmission<'a> {
64    ledger: &'a AllocationLedger,
65    declarations: &'a SealedDeclarationSnapshot,
66    selected: Vec<MemoryRequest>,
67    failure: Option<BootstrapAdmissionError>,
68}
69
70impl<'a> BootstrapAdmission<'a> {
71    pub(super) const fn new(
72        ledger: &'a AllocationLedger,
73        declarations: &'a SealedDeclarationSnapshot,
74    ) -> Self {
75        Self {
76            ledger,
77            declarations,
78            selected: Vec::new(),
79            failure: None,
80        }
81    }
82
83    /// Original sealed input; preparation cannot remove declarations or add grants.
84    #[must_use]
85    pub const fn declarations(&self) -> &SealedDeclarationSnapshot {
86        self.declarations
87    }
88
89    /// At most 255 validated allocation summaries, including governance records.
90    ///
91    /// # Panics
92    ///
93    /// Panics only if an internal validated-ledger invariant is broken.
94    pub fn recovered_allocations(
95        &self,
96    ) -> impl ExactSizeIterator<Item = RecoveredAllocationMetadata<'_>> {
97        self.ledger
98            .allocation_history()
99            .records()
100            .iter()
101            .map(|record| RecoveredAllocationMetadata {
102                stable_key: record.stable_key(),
103                slot: record.slot(),
104                state: record.state(),
105                schema: record
106                    .schema_history()
107                    .last()
108                    .expect("validated schema history")
109                    .schema(),
110            })
111    }
112
113    /// Whether the original input or an earlier selection already names this key.
114    #[must_use]
115    pub fn is_declared(&self, key: &StableKey) -> bool {
116        self.declarations
117            .allocation_snapshot()
118            .declarations()
119            .iter()
120            .any(|d| d.stable_key() == key)
121            || self
122                .declarations
123                .requests()
124                .iter()
125                .chain(&self.selected)
126                .any(|r| r.stable_key() == key)
127    }
128
129    /// Include a known, nonretired key under an explicit current host grant.
130    /// Retains its slot and latest schema metadata. Final current policy and all
131    /// ordinary collision/retirement checks still run after preparation.
132    pub fn include_historical(
133        &mut self,
134        authority: &str,
135        stable_key: &str,
136    ) -> Result<(), BootstrapAdmissionError> {
137        if let Some(error) = &self.failure {
138            return Err(error.clone());
139        }
140        let result = self.select(authority, stable_key);
141        if let Err(error) = &result {
142            self.failure = Some(error.clone());
143        }
144        result
145    }
146
147    fn select(&mut self, authority: &str, stable_key: &str) -> Result<(), BootstrapAdmissionError> {
148        // Constructor bounds names before they can enter selection diagnostics.
149        let request = MemoryRequest::new(authority, stable_key, SchemaMetadata::default())?;
150        let key = request.stable_key();
151        if self.is_declared(key) {
152            return Err(BootstrapAdmissionError::Duplicate(key.clone()));
153        }
154        if self.declarations.registered_declarations().len()
155            + self.declarations.requests().len()
156            + self.selected.len()
157            >= 254
158        {
159            return Err(BootstrapAdmissionError::TooManyDeclarations);
160        }
161        let record = self
162            .ledger
163            .allocation_history()
164            .records()
165            .iter()
166            .find(|r| r.stable_key() == key)
167            .ok_or_else(|| BootstrapAdmissionError::Unknown(key.clone()))?;
168        if matches!(record.state(), AllocationState::Retired { .. }) {
169            return Err(BootstrapAdmissionError::Retired(key.clone()));
170        }
171        self.declarations
172            .range_authority()
173            .validate_slot_authority(record.slot(), authority)
174            .map_err(|source| BootstrapAdmissionError::Range {
175                stable_key: key.clone(),
176                authority: authority.to_string(),
177                source,
178            })?;
179        self.selected.push(
180            request
181                .with_schema(
182                    record
183                        .schema_history()
184                        .last()
185                        .expect("validated schema history")
186                        .schema()
187                        .clone(),
188                )
189                .map_err(crate::StaticMemoryDeclarationError::Declaration)?,
190        );
191        Ok(())
192    }
193
194    pub(super) fn complete(self) -> Result<Vec<MemoryRequest>, BootstrapAdmissionError> {
195        if let Some(error) = self.failure {
196            return Err(error);
197        }
198        Ok(self.selected)
199    }
200}