Skip to main content

ic_memory/
declaration.rs

1use crate::{
2    key::{StableKey, StableKeyError},
3    schema::SchemaMetadata,
4    slot::{MemoryManagerSlot, MemoryManagerSlotError},
5    text::{DiagnosticTextError, validate_diagnostic_text},
6};
7use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
8use std::collections::BTreeSet;
9
10///
11/// AllocationDeclaration
12///
13/// Checked runtime claim that a stable key should own an allocation slot.
14///
15/// Declarations are supplied by the current binary before opening storage.
16/// Construction and decoding check the stable key, label, slot and schema
17/// metadata. A declaration becomes authoritative only after validation against
18/// the recovered ledger and commitment in a generation.
19///
20
21#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
22#[serde(deny_unknown_fields)]
23pub struct AllocationDeclaration {
24    /// Durable stable key.
25    pub(crate) stable_key: StableKey,
26    /// Claimed allocation slot.
27    pub(crate) slot: MemoryManagerSlot,
28    /// Optional diagnostic label.
29    #[serde(deserialize_with = "deserialize_label")]
30    pub(crate) label: Option<String>,
31    /// Optional diagnostic schema metadata.
32    pub(crate) schema: SchemaMetadata,
33}
34
35impl AllocationDeclaration {
36    /// Build a declaration from raw parts after validating diagnostic metadata.
37    pub fn new(
38        stable_key: impl AsRef<str>,
39        slot: MemoryManagerSlot,
40        label: Option<String>,
41        schema: SchemaMetadata,
42    ) -> Result<Self, DeclarationSnapshotError> {
43        let stable_key = StableKey::parse(stable_key).map_err(DeclarationSnapshotError::Key)?;
44        validate_label(label.as_deref())?;
45        Ok(Self {
46            stable_key,
47            slot,
48            label,
49            schema,
50        })
51    }
52
53    /// Build a `MemoryManager` declaration with a diagnostic label.
54    pub fn memory_manager(
55        stable_key: impl AsRef<str>,
56        id: u8,
57        label: impl Into<String>,
58    ) -> Result<Self, DeclarationSnapshotError> {
59        Self::memory_manager_with_schema(stable_key, id, label, SchemaMetadata::default())
60    }
61
62    /// Build an unlabeled `MemoryManager` declaration.
63    pub fn memory_manager_unlabeled(
64        stable_key: impl AsRef<str>,
65        id: u8,
66    ) -> Result<Self, DeclarationSnapshotError> {
67        Self::memory_manager_unlabeled_with_schema(stable_key, id, SchemaMetadata::default())
68    }
69
70    /// Build a `MemoryManager` declaration with a diagnostic label and schema metadata.
71    pub fn memory_manager_with_schema(
72        stable_key: impl AsRef<str>,
73        id: u8,
74        label: impl Into<String>,
75        schema: SchemaMetadata,
76    ) -> Result<Self, DeclarationSnapshotError> {
77        let slot =
78            MemoryManagerSlot::new(id).map_err(DeclarationSnapshotError::MemoryManagerSlot)?;
79        Self::new(stable_key, slot, Some(label.into()), schema)
80    }
81
82    /// Build an unlabeled `MemoryManager` declaration with schema metadata.
83    pub fn memory_manager_unlabeled_with_schema(
84        stable_key: impl AsRef<str>,
85        id: u8,
86        schema: SchemaMetadata,
87    ) -> Result<Self, DeclarationSnapshotError> {
88        let slot =
89            MemoryManagerSlot::new(id).map_err(DeclarationSnapshotError::MemoryManagerSlot)?;
90        Self::new(stable_key, slot, None, schema)
91    }
92
93    /// Return the durable stable key claimed by this declaration.
94    #[must_use]
95    pub const fn stable_key(&self) -> &StableKey {
96        &self.stable_key
97    }
98
99    /// Return the allocation slot claimed by this declaration.
100    #[must_use]
101    pub const fn slot(&self) -> &MemoryManagerSlot {
102        &self.slot
103    }
104
105    /// Return the optional diagnostic label.
106    #[must_use]
107    pub fn label(&self) -> Option<&str> {
108        self.label.as_deref()
109    }
110
111    /// Return the optional schema metadata.
112    #[must_use]
113    pub const fn schema(&self) -> &SchemaMetadata {
114        &self.schema
115    }
116}
117
118///
119/// DeclarationSnapshot
120///
121/// Immutable runtime declaration snapshot ready for policy and history validation.
122///
123/// Construction and decoding enforce the declaration count, unique keys and
124/// slots, and bounded printable ASCII runtime fingerprint. A snapshot is still
125/// not permission to open storage. Integrations should call
126/// [`crate::validate_allocations`], commit the staged generation, and only then
127/// expose committed allocation authority.
128///
129
130#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
131pub struct DeclarationSnapshot {
132    /// Runtime declarations.
133    declarations: Vec<AllocationDeclaration>,
134    /// Optional binary/runtime identity for generation diagnostics.
135    runtime_fingerprint: Option<String>,
136}
137
138impl<'de> Deserialize<'de> for DeclarationSnapshot {
139    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
140        #[derive(Deserialize)]
141        #[serde(rename = "DeclarationSnapshot", deny_unknown_fields)]
142        struct Snapshot {
143            #[serde(deserialize_with = "crate::cbor::deserialize_records")]
144            declarations: Vec<AllocationDeclaration>,
145            #[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
146            runtime_fingerprint: Option<String>,
147        }
148
149        let snapshot = Snapshot::deserialize(deserializer)?;
150        // Keep constructor refusal order: count and uniqueness precede the
151        // optional fingerprint, without copying or reordering declarations.
152        let checked = Self::new(snapshot.declarations).map_err(D::Error::custom)?;
153        match snapshot.runtime_fingerprint {
154            Some(fingerprint) => checked
155                .with_runtime_fingerprint(fingerprint)
156                .map_err(D::Error::custom),
157            None => Ok(checked),
158        }
159    }
160}
161
162impl DeclarationSnapshot {
163    /// Create and validate a declaration snapshot.
164    pub fn new(declarations: Vec<AllocationDeclaration>) -> Result<Self, DeclarationSnapshotError> {
165        validate_declaration_set(&declarations)?;
166        Ok(Self {
167            declarations,
168            runtime_fingerprint: None,
169        })
170    }
171
172    /// Attach an optional runtime fingerprint.
173    pub fn with_runtime_fingerprint(
174        mut self,
175        fingerprint: impl Into<String>,
176    ) -> Result<Self, DeclarationSnapshotError> {
177        let fingerprint = fingerprint.into();
178        validate_runtime_fingerprint(Some(&fingerprint))?;
179        self.runtime_fingerprint = Some(fingerprint);
180        Ok(self)
181    }
182
183    /// Return true when the snapshot has no declarations.
184    #[must_use]
185    pub const fn is_empty(&self) -> bool {
186        self.declarations.is_empty()
187    }
188
189    /// Return the number of declarations in the snapshot.
190    #[must_use]
191    pub const fn len(&self) -> usize {
192        self.declarations.len()
193    }
194
195    /// Borrow the sealed declarations.
196    #[must_use]
197    pub fn declarations(&self) -> &[AllocationDeclaration] {
198        &self.declarations
199    }
200
201    /// Borrow the optional runtime fingerprint.
202    #[must_use]
203    pub fn runtime_fingerprint(&self) -> Option<&str> {
204        self.runtime_fingerprint.as_deref()
205    }
206
207    pub(crate) fn into_parts(self) -> (Vec<AllocationDeclaration>, Option<String>) {
208        (self.declarations, self.runtime_fingerprint)
209    }
210}
211
212///
213/// DeclarationSnapshotError
214///
215/// Declaration snapshot validation failure.
216#[non_exhaustive]
217#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
218pub enum DeclarationSnapshotError {
219    #[error("at most 255 allocation declarations are supported")]
220    TooManyDeclarations,
221    /// Stable-key grammar failure.
222    #[error(transparent)]
223    Key(StableKeyError),
224    /// `MemoryManager` slot validation failure.
225    #[error(transparent)]
226    MemoryManagerSlot(MemoryManagerSlotError),
227    /// A stable key appeared more than once in one snapshot.
228    #[error("stable key '{0}' is declared more than once")]
229    DuplicateStableKey(StableKey),
230    /// An allocation slot appeared more than once in one snapshot.
231    #[error("allocation slot '{0:?}' is declared more than once")]
232    DuplicateSlot(MemoryManagerSlot),
233    /// Present declaration labels must be non-empty.
234    #[error("allocation declaration label must not be empty when present")]
235    EmptyLabel,
236    /// Declaration labels must stay bounded for durable ledger storage.
237    #[error("allocation declaration label must be at most 256 bytes")]
238    LabelTooLong,
239    /// Declaration labels must not require Unicode normalization.
240    #[error("allocation declaration label must be ASCII")]
241    NonAsciiLabel,
242    /// Declaration labels must be printable metadata.
243    #[error("allocation declaration label must not contain ASCII control characters")]
244    ControlCharacterLabel,
245    /// Present runtime fingerprints must be non-empty.
246    #[error("runtime_fingerprint must not be empty when present")]
247    EmptyRuntimeFingerprint,
248    /// Runtime fingerprints must stay bounded for durable ledger storage.
249    #[error("runtime_fingerprint must be at most 256 bytes")]
250    RuntimeFingerprintTooLong,
251    /// Runtime fingerprints must not require Unicode normalization.
252    #[error("runtime_fingerprint must be ASCII")]
253    NonAsciiRuntimeFingerprint,
254    /// Runtime fingerprints must be printable metadata.
255    #[error("runtime_fingerprint must not contain ASCII control characters")]
256    ControlCharacterRuntimeFingerprint,
257}
258
259fn validate_label(label: Option<&str>) -> Result<(), DeclarationSnapshotError> {
260    let Some(label) = label else {
261        return Ok(());
262    };
263    validate_diagnostic_text(label).map_err(|error| match error {
264        DiagnosticTextError::Empty => DeclarationSnapshotError::EmptyLabel,
265        DiagnosticTextError::TooLong => DeclarationSnapshotError::LabelTooLong,
266        DiagnosticTextError::NonAscii => DeclarationSnapshotError::NonAsciiLabel,
267        DiagnosticTextError::ControlCharacter => DeclarationSnapshotError::ControlCharacterLabel,
268    })
269}
270
271// Decode explicitly present optional labels through the same constructor rule.
272// Retain the owned string; no intermediate label type or compatibility default.
273fn deserialize_label<'de, D: Deserializer<'de>>(
274    deserializer: D,
275) -> Result<Option<String>, D::Error> {
276    let label = Option::<String>::deserialize(deserializer)?;
277    validate_label(label.as_deref()).map_err(D::Error::custom)?;
278    Ok(label)
279}
280
281pub fn validate_runtime_fingerprint(
282    fingerprint: Option<&str>,
283) -> Result<(), DeclarationSnapshotError> {
284    let Some(fingerprint) = fingerprint else {
285        return Ok(());
286    };
287    validate_diagnostic_text(fingerprint).map_err(|error| match error {
288        DiagnosticTextError::Empty => DeclarationSnapshotError::EmptyRuntimeFingerprint,
289        DiagnosticTextError::TooLong => DeclarationSnapshotError::RuntimeFingerprintTooLong,
290        DiagnosticTextError::NonAscii => DeclarationSnapshotError::NonAsciiRuntimeFingerprint,
291        DiagnosticTextError::ControlCharacter => {
292            DeclarationSnapshotError::ControlCharacterRuntimeFingerprint
293        }
294    })
295}
296
297fn validate_declaration_set(
298    declarations: &[AllocationDeclaration],
299) -> Result<(), DeclarationSnapshotError> {
300    if declarations.len() > crate::constants::MAX_ALLOCATIONS {
301        return Err(DeclarationSnapshotError::TooManyDeclarations);
302    }
303    let mut keys = BTreeSet::new();
304    let mut slots = [false; crate::constants::MAX_ALLOCATIONS];
305
306    for declaration in declarations {
307        let occupied = &mut slots[usize::from(declaration.slot.id())];
308        if *occupied {
309            return Err(DeclarationSnapshotError::DuplicateSlot(
310                declaration.slot.clone(),
311            ));
312        }
313        *occupied = true;
314        if !keys.insert(&declaration.stable_key) {
315            return Err(DeclarationSnapshotError::DuplicateStableKey(
316                declaration.stable_key.clone(),
317            ));
318        }
319    }
320
321    Ok(())
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327    use crate::slot::MemoryManagerSlot;
328
329    fn declaration(key: &str, id: u8) -> AllocationDeclaration {
330        AllocationDeclaration::new(
331            key,
332            MemoryManagerSlot::new(id).expect("usable slot"),
333            None,
334            SchemaMetadata::default(),
335        )
336        .expect("declaration")
337    }
338
339    #[test]
340    fn declaration_rejects_unbounded_label_metadata() {
341        let err = AllocationDeclaration::new(
342            "app.users.v1",
343            MemoryManagerSlot::new(100).expect("usable slot"),
344            Some("x".repeat(257)),
345            SchemaMetadata::default(),
346        )
347        .expect_err("label too long");
348
349        assert_eq!(err, DeclarationSnapshotError::LabelTooLong);
350    }
351
352    #[test]
353    fn memory_manager_declaration_constructor_builds_common_declaration() {
354        let declaration = AllocationDeclaration::memory_manager("app.orders.v1", 100, "orders")
355            .expect("declaration");
356
357        assert_eq!(declaration.stable_key.as_str(), "app.orders.v1");
358        assert_eq!(
359            declaration.slot,
360            MemoryManagerSlot::new(100).expect("usable slot")
361        );
362        assert_eq!(declaration.label.as_deref(), Some("orders"));
363        assert_eq!(declaration.schema, SchemaMetadata::default());
364    }
365
366    #[test]
367    fn memory_manager_declaration_constructor_rejects_invalid_slot() {
368        let err = AllocationDeclaration::memory_manager("app.orders.v1", u8::MAX, "orders")
369            .expect_err("sentinel must fail");
370
371        assert!(matches!(
372            err,
373            DeclarationSnapshotError::MemoryManagerSlot(_)
374        ));
375    }
376
377    #[test]
378    fn snapshot_decode_rejects_unusable_memory_manager_slot() {
379        let snapshot = DeclarationSnapshot::new(vec![declaration("app.orders.v1", 100)]).unwrap();
380        let mut value = serde_json::to_value(snapshot).unwrap();
381        value["declarations"][0]["slot"]["slot"]["MemoryManagerId"] = serde_json::json!(255);
382        assert!(serde_json::from_value::<DeclarationSnapshot>(value).is_err());
383    }
384
385    #[test]
386    fn snapshot_rejects_unbounded_runtime_fingerprint() {
387        let snapshot =
388            DeclarationSnapshot::new(vec![declaration("app.users.v1", 100)]).expect("snapshot");
389
390        let err = snapshot
391            .with_runtime_fingerprint("x".repeat(257))
392            .expect_err("fingerprint too long");
393
394        assert_eq!(err, DeclarationSnapshotError::RuntimeFingerprintTooLong);
395    }
396
397    #[test]
398    fn rejects_duplicate_keys() {
399        let err = DeclarationSnapshot::new(vec![
400            declaration("app.users.v1", 100),
401            declaration("app.users.v1", 101),
402        ])
403        .expect_err("duplicate key");
404
405        assert_eq!(
406            err,
407            DeclarationSnapshotError::DuplicateStableKey(StableKey::parse("app.users.v1").unwrap())
408        );
409    }
410
411    #[test]
412    fn rejects_duplicate_slots() {
413        for second_key in ["app.orders.v1", "app.users.v1"] {
414            let err = DeclarationSnapshot::new(vec![
415                declaration("app.users.v1", 100),
416                declaration(second_key, 100),
417            ])
418            .expect_err("duplicate slot precedes duplicate key");
419
420            assert_eq!(
421                err,
422                DeclarationSnapshotError::DuplicateSlot(MemoryManagerSlot::new(100).unwrap())
423            );
424        }
425    }
426}