Skip to main content

ic_memory/
diagnostics.rs

1use crate::{
2    constants::WASM_PAGE_SIZE_BYTES,
3    declaration::AllocationDeclaration,
4    ledger::{AllocationLedger, AllocationRecord, GenerationRecord},
5    physical::CommitStoreDiagnostic,
6    policy::PolicyIdentity,
7    registry::SealedDeclarationFingerprint,
8    slot::{AllocationSlotDescriptor, MemoryManagerAuthorityRecord, MemoryManagerRangeAuthority},
9};
10use serde::{Deserialize, Serialize};
11
12///
13/// DiagnosticExport
14///
15/// Read-only machine-readable allocation ledger export.
16#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
17#[serde(deny_unknown_fields)]
18pub struct DiagnosticExport {
19    /// Current committed generation.
20    pub current_generation: u64,
21    /// Ledger anchor descriptor.
22    pub ledger_anchor: AllocationSlotDescriptor,
23    /// Allocation records.
24    pub records: Vec<DiagnosticRecord>,
25    /// Generation records.
26    pub generations: Vec<GenerationRecord>,
27    /// Optional protected commit recovery diagnostic.
28    #[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
29    pub commit_recovery: Option<CommitStoreDiagnostic>,
30}
31
32///
33/// DiagnosticRuntimeBinding
34///
35/// Operator-facing view of the policy identity and declaration snapshot bound
36/// to one successful memory-runtime bootstrap.
37///
38
39#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
40#[serde(deny_unknown_fields)]
41pub struct DiagnosticRuntimeBinding {
42    /// Bounded semantic identity of the bootstrap policy.
43    pub policy_identity: PolicyIdentity,
44    /// Deterministic fingerprint of the sealed declaration snapshot.
45    pub declaration_fingerprint: SealedDeclarationFingerprint,
46}
47
48impl DiagnosticRuntimeBinding {
49    /// Build one runtime binding diagnostic.
50    #[must_use]
51    pub const fn new(
52        policy_identity: PolicyIdentity,
53        declaration_fingerprint: SealedDeclarationFingerprint,
54    ) -> Self {
55        Self {
56            policy_identity,
57            declaration_fingerprint,
58        }
59    }
60}
61
62///
63/// MemoryRuntimeDoctorReport
64///
65/// Preflight and runtime diagnostic report for one concrete
66/// [`crate::MemoryRuntime`].
67///
68/// This report is intended for operator-facing diagnostics. Recoverable
69/// runtime problems, such as corrupt stable-cell bytes or commit recovery
70/// failure, are represented as fields instead of aborting report construction.
71///
72
73#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
74#[serde(deny_unknown_fields)]
75pub struct MemoryRuntimeDoctorReport {
76    /// Whether this runtime has completed bootstrap validation.
77    pub bootstrapped: bool,
78    /// Policy identity supplied for this diagnostic evaluation.
79    pub tested_policy_identity: Result<PolicyIdentity, DiagnosticFailure>,
80    /// Sealed declaration fingerprint supplied for this diagnostic evaluation.
81    pub tested_declaration_fingerprint: SealedDeclarationFingerprint,
82    /// Binding published by this runtime's successful bootstrap, when present.
83    #[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
84    pub established_bootstrap_binding: Option<DiagnosticRuntimeBinding>,
85    /// Whether the tested identity and declarations match the established
86    /// bootstrap binding.
87    pub bootstrap_binding: DiagnosticCheck,
88    /// Ledger anchor descriptor used by this runtime.
89    pub ledger_anchor: AllocationSlotDescriptor,
90    /// Stable-cell ledger storage status.
91    pub stable_cell: DiagnosticStableCell,
92    /// Protected commit recovery status when a ledger record was readable.
93    #[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
94    pub commit_recovery: Option<CommitStoreDiagnostic>,
95    /// Recovered allocation ledger export when protected recovery succeeded.
96    #[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
97    pub ledger: Option<DiagnosticExport>,
98    /// Static declarations registered by linked crates.
99    pub registered_declarations: Vec<DiagnosticDeclaration>,
100    /// Static range authority registered by linked crates and the effective
101    /// authority table supplied to this runtime.
102    pub range_authority: DiagnosticRangeAuthority,
103    /// Declaration validation result under the tested caller-supplied policy.
104    pub validation: DiagnosticCheck,
105}
106
107///
108/// DiagnosticDeclaration
109///
110/// Read-only diagnostic view of one static allocation declaration.
111///
112
113#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
114#[serde(deny_unknown_fields)]
115pub struct DiagnosticDeclaration {
116    /// Crate or integration authority that registered the declaration.
117    pub authority: String,
118    /// Allocation declaration registered by that authority.
119    pub declaration: AllocationDeclaration,
120}
121
122impl DiagnosticDeclaration {
123    /// Build a diagnostic declaration record.
124    #[must_use]
125    pub fn new(authority: impl Into<String>, declaration: AllocationDeclaration) -> Self {
126        Self {
127            authority: authority.into(),
128            declaration,
129        }
130    }
131}
132
133///
134/// DiagnosticCode
135///
136/// Stable machine-readable category for an operator diagnostic failure.
137///
138
139#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
140pub enum DiagnosticCode {
141    /// Stable-cell storage could not be decoded.
142    #[serde(rename = "stable_cell")]
143    StableCell,
144    /// Persisted bytes use a recognized but unsupported durable format.
145    #[serde(rename = "unsupported_format")]
146    UnsupportedFormat,
147    /// Protected ledger recovery failed.
148    #[serde(rename = "ledger_recovery")]
149    LedgerRecovery,
150    /// Current declarations failed allocation validation.
151    #[serde(rename = "allocation_validation")]
152    AllocationValidation,
153    /// Runtime bootstrap policy identity was invalid.
154    #[serde(rename = "policy_identity")]
155    PolicyIdentity,
156    /// Tested bootstrap identity or declarations differ from runtime state.
157    #[serde(rename = "runtime_binding")]
158    RuntimeBinding,
159}
160
161///
162/// DiagnosticFailure
163///
164/// Machine-readable diagnostic code paired with an operator-facing message.
165///
166
167#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
168#[serde(deny_unknown_fields)]
169pub struct DiagnosticFailure {
170    /// Stable diagnostic category.
171    pub code: DiagnosticCode,
172    /// Human-readable failure detail.
173    pub message: String,
174}
175
176impl DiagnosticFailure {
177    /// Build a coded diagnostic failure.
178    #[must_use]
179    pub fn new(code: DiagnosticCode, message: impl Into<String>) -> Self {
180        Self {
181            code,
182            message: message.into(),
183        }
184    }
185}
186
187///
188/// DiagnosticRangeAuthority
189///
190/// Read-only diagnostic view of registered and effective range authority.
191///
192
193#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
194#[serde(deny_unknown_fields)]
195pub struct DiagnosticRangeAuthority {
196    /// Range records registered directly by linked crates.
197    pub registered_records: Vec<MemoryManagerAuthorityRecord>,
198    /// Validated effective range authority from the sealed declarations.
199    pub effective_authority: MemoryManagerRangeAuthority,
200}
201
202impl DiagnosticRangeAuthority {
203    /// Build a range-authority diagnostic.
204    #[must_use]
205    pub const fn new(
206        registered_records: Vec<MemoryManagerAuthorityRecord>,
207        effective_authority: MemoryManagerRangeAuthority,
208    ) -> Self {
209        Self {
210            registered_records,
211            effective_authority,
212        }
213    }
214}
215
216///
217/// DiagnosticStableCell
218///
219/// Read-only diagnostic view of the stable-cell ledger storage envelope.
220///
221
222#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
223#[serde(deny_unknown_fields)]
224pub struct DiagnosticStableCell {
225    /// Stable-cell status.
226    pub status: DiagnosticStableCellStatus,
227    /// Backing memory size for the ledger cell.
228    pub memory_size: DiagnosticMemorySize,
229}
230
231impl DiagnosticStableCell {
232    /// Build a stable-cell diagnostic.
233    #[must_use]
234    pub const fn new(
235        status: DiagnosticStableCellStatus,
236        memory_size: DiagnosticMemorySize,
237    ) -> Self {
238        Self {
239            status,
240            memory_size,
241        }
242    }
243}
244
245///
246/// DiagnosticStableCellStatus
247///
248/// Stable-cell ledger storage status.
249///
250
251#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
252#[serde(deny_unknown_fields)]
253pub enum DiagnosticStableCellStatus {
254    /// The ledger memory is empty and can be initialized.
255    Empty,
256    /// The stable-cell envelope and ledger record decoded successfully.
257    Readable,
258    /// The ledger memory is present but could not be decoded as the expected
259    /// stable-cell ledger record.
260    Corrupt {
261        /// Stable-cell envelope or ledger-record decode failure.
262        failure: DiagnosticFailure,
263    },
264}
265
266///
267/// DiagnosticCheck
268///
269/// Read-only diagnostic status for a preflight check.
270///
271
272#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
273#[serde(deny_unknown_fields)]
274pub enum DiagnosticCheck {
275    /// The check could not run because prerequisite state was unavailable.
276    NotRun {
277        /// Stable diagnostic category.
278        code: DiagnosticCode,
279        /// Reason the check could not run.
280        message: String,
281    },
282    /// The check completed successfully.
283    Passed,
284    /// The check ran and found a problem.
285    Failed {
286        /// Stable diagnostic category.
287        code: DiagnosticCode,
288        /// Validation failure.
289        message: String,
290    },
291}
292
293impl DiagnosticCheck {
294    /// Build a passed diagnostic check.
295    #[must_use]
296    pub const fn passed() -> Self {
297        Self::Passed
298    }
299
300    /// Build a failed diagnostic check.
301    #[must_use]
302    pub fn failed(code: DiagnosticCode, message: impl Into<String>) -> Self {
303        Self::Failed {
304            code,
305            message: message.into(),
306        }
307    }
308
309    /// Build a skipped diagnostic check.
310    #[must_use]
311    pub fn not_run(code: DiagnosticCode, message: impl Into<String>) -> Self {
312        Self::NotRun {
313            code,
314            message: message.into(),
315        }
316    }
317}
318
319impl DiagnosticExport {
320    /// Build a read-only diagnostic export from an allocation ledger.
321    ///
322    /// Records start unmeasured and without commit recovery observations. The
323    /// exporter can fill those public fields from its own backing and recovery
324    /// evidence; this DTO constructor neither recovers nor measures memory.
325    #[must_use]
326    pub fn from_ledger(ledger: &AllocationLedger, ledger_anchor: AllocationSlotDescriptor) -> Self {
327        Self {
328            current_generation: ledger.current_generation,
329            ledger_anchor,
330            records: ledger
331                .allocation_history()
332                .records()
333                .iter()
334                .cloned()
335                .map(|allocation| DiagnosticRecord {
336                    allocation,
337                    memory_size: None,
338                })
339                .collect(),
340            generations: ledger.allocation_history().generations().to_vec(),
341            commit_recovery: None,
342        }
343    }
344}
345
346///
347/// DiagnosticRecord
348///
349/// Read-only diagnostic allocation record.
350#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
351#[serde(deny_unknown_fields)]
352pub struct DiagnosticRecord {
353    /// Allocation record.
354    pub allocation: AllocationRecord,
355    /// Live backing memory size, when the exporter measured one.
356    ///
357    /// This is allocation size reported by the backing memory, not logical user
358    /// payload size inside the stable structure.
359    #[serde(skip_serializing_if = "Option::is_none")]
360    pub memory_size: Option<DiagnosticMemorySize>,
361}
362
363///
364/// DiagnosticMemorySize
365///
366/// Live size reported by a backing stable memory.
367///
368
369#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
370#[serde(deny_unknown_fields)]
371pub struct DiagnosticMemorySize {
372    /// WebAssembly pages reported by the memory.
373    pub wasm_pages: u64,
374    /// Bytes represented by the page count.
375    pub bytes: u64,
376}
377
378impl DiagnosticMemorySize {
379    /// Build a size from a WebAssembly page count.
380    #[must_use]
381    pub const fn from_wasm_pages(wasm_pages: u64) -> Self {
382        Self {
383            wasm_pages,
384            bytes: wasm_pages.saturating_mul(WASM_PAGE_SIZE_BYTES),
385        }
386    }
387}
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392    use crate::{
393        declaration::AllocationDeclaration,
394        ledger::{AllocationHistory, AllocationRecord},
395        physical::{CommitRecoveryError, CommitSlotDiagnostic, CommitStoreDiagnostic},
396        schema::SchemaMetadata,
397    };
398
399    #[test]
400    fn diagnostic_export_copies_ledger_records() {
401        let declaration = AllocationDeclaration::new(
402            "app.users.v1",
403            AllocationSlotDescriptor::memory_manager(100).expect("usable slot"),
404            None,
405            SchemaMetadata::default(),
406        )
407        .expect("declaration");
408        let ledger = AllocationLedger {
409            current_generation: 3,
410            allocation_history: AllocationHistory::from_parts(
411                vec![AllocationRecord::active(3, declaration)],
412                vec![GenerationRecord {
413                    generation: 3,
414                    parent_generation: 2,
415                    runtime_fingerprint: Some("wasm:abc123".to_string()),
416                    declaration_count: 1,
417                    committed_at: None,
418                }],
419            ),
420        };
421
422        let export = DiagnosticExport::from_ledger(
423            &ledger,
424            AllocationSlotDescriptor::memory_manager(0).expect("usable slot"),
425        );
426
427        assert_eq!(export.current_generation, 3);
428        assert_eq!(export.records.len(), 1);
429        assert_eq!(export.records[0].memory_size, None);
430        assert_eq!(export.generations.len(), 1);
431        assert_eq!(
432            export.ledger_anchor,
433            AllocationSlotDescriptor::memory_manager(0).expect("usable slot")
434        );
435        assert_eq!(export.commit_recovery, None);
436        assert_eq!(
437            export.generations,
438            ledger.allocation_history().generations()
439        );
440        let wire = serde_json::to_value(&export).expect("diagnostic JSON");
441        assert_eq!(
442            wire["generations"][0],
443            serde_json::json!({
444                "generation": 3,
445                "parent_generation": 2,
446                "runtime_fingerprint": "wasm:abc123",
447                "declaration_count": 1,
448                "committed_at": null,
449            })
450        );
451        let decoded: DiagnosticExport = serde_json::from_value(wire).expect("current JSON shape");
452        assert_eq!(decoded, export);
453    }
454
455    #[test]
456    fn diagnostic_export_rejects_unknown_top_level_fields() {
457        use crate::test_cbor::Value;
458
459        let export = DiagnosticExport {
460            current_generation: 0,
461            ledger_anchor: AllocationSlotDescriptor::memory_manager(0).expect("usable slot"),
462            records: Vec::new(),
463            generations: Vec::new(),
464            commit_recovery: None,
465        };
466        let Value::Map(mut map) = crate::test_cbor::to_value(export).expect("diagnostic value")
467        else {
468            panic!("diagnostic export encodes as a map");
469        };
470        crate::test_cbor::map_insert(
471            &mut map,
472            Value::Text("future_field".to_string()),
473            Value::Bool(true),
474        );
475        let bytes = crate::test_cbor::to_vec(&Value::Map(map)).expect("diagnostic bytes");
476
477        let err = crate::test_cbor::from_slice::<DiagnosticExport>(&bytes)
478            .expect_err("unknown diagnostic field must fail closed");
479
480        assert!(err.to_string().contains("future_field"));
481    }
482
483    #[test]
484    fn diagnostic_outcome_states_round_trip() {
485        let stable_cell = DiagnosticStableCell::new(
486            DiagnosticStableCellStatus::Corrupt {
487                failure: DiagnosticFailure::new(
488                    DiagnosticCode::StableCell,
489                    "bad stable-cell record",
490                ),
491            },
492            DiagnosticMemorySize::from_wasm_pages(1),
493        );
494        let range_authority =
495            DiagnosticRangeAuthority::new(Vec::new(), MemoryManagerRangeAuthority::default());
496        let check = DiagnosticCheck::failed(
497            DiagnosticCode::AllocationValidation,
498            "duplicate declaration",
499        );
500
501        for value in [DiagnosticCheck::passed(), check] {
502            let bytes = crate::test_cbor::to_vec(&value).expect("check bytes");
503            let decoded: DiagnosticCheck =
504                crate::test_cbor::from_slice(&bytes).expect("check round trip");
505            assert_eq!(decoded, value);
506        }
507
508        let bytes = crate::test_cbor::to_vec(&stable_cell).expect("stable-cell diagnostic bytes");
509        let decoded: DiagnosticStableCell =
510            crate::test_cbor::from_slice(&bytes).expect("stable-cell round trip");
511        assert_eq!(decoded, stable_cell);
512
513        let bytes = crate::test_cbor::to_vec(&range_authority).expect("range diagnostic bytes");
514        let decoded: DiagnosticRangeAuthority =
515            crate::test_cbor::from_slice(&bytes).expect("range round trip");
516        assert_eq!(decoded, range_authority);
517    }
518
519    #[test]
520    fn diagnostic_codes_have_stable_wire_names() {
521        let cases = [
522            (DiagnosticCode::StableCell, "stable_cell"),
523            (DiagnosticCode::UnsupportedFormat, "unsupported_format"),
524            (DiagnosticCode::LedgerRecovery, "ledger_recovery"),
525            (
526                DiagnosticCode::AllocationValidation,
527                "allocation_validation",
528            ),
529            (DiagnosticCode::PolicyIdentity, "policy_identity"),
530            (DiagnosticCode::RuntimeBinding, "runtime_binding"),
531        ];
532
533        for (code, expected) in cases {
534            assert_eq!(
535                crate::test_cbor::to_value(code).expect("diagnostic code value"),
536                crate::test_cbor::Value::Text(expected.to_string())
537            );
538        }
539    }
540
541    #[test]
542    fn diagnostic_export_can_include_commit_recovery_state() {
543        let ledger = AllocationLedger {
544            current_generation: 3,
545            allocation_history: AllocationHistory::default(),
546        };
547        let commit_recovery = CommitStoreDiagnostic {
548            slot0: CommitSlotDiagnostic::Valid { generation: 3 },
549            slot1: CommitSlotDiagnostic::Empty,
550            recovery: Ok(3),
551        };
552
553        let mut export = DiagnosticExport::from_ledger(
554            &ledger,
555            AllocationSlotDescriptor::memory_manager(0).expect("usable slot"),
556        );
557        export.commit_recovery = Some(commit_recovery);
558
559        assert_eq!(export.commit_recovery, Some(commit_recovery));
560    }
561
562    #[test]
563    fn diagnostic_export_can_include_memory_sizes() {
564        let declaration = AllocationDeclaration::new(
565            "app.users.v1",
566            AllocationSlotDescriptor::memory_manager(100).expect("usable slot"),
567            None,
568            SchemaMetadata::default(),
569        )
570        .expect("declaration");
571        let ledger = AllocationLedger {
572            current_generation: 3,
573            allocation_history: AllocationHistory::from_parts(
574                vec![AllocationRecord::active(3, declaration)],
575                Vec::new(),
576            ),
577        };
578
579        let mut export = DiagnosticExport::from_ledger(
580            &ledger,
581            AllocationSlotDescriptor::memory_manager(0).expect("usable slot"),
582        );
583        export.records[0].memory_size = Some(DiagnosticMemorySize::from_wasm_pages(2));
584
585        assert_eq!(
586            export.records[0].memory_size,
587            Some(DiagnosticMemorySize {
588                wasm_pages: 2,
589                bytes: 131_072,
590            })
591        );
592        let wire = serde_json::to_value(&export).expect("diagnostic JSON");
593        assert_eq!(
594            wire["records"][0]["memory_size"],
595            serde_json::json!({"wasm_pages": 2, "bytes": 131_072})
596        );
597    }
598
599    #[test]
600    fn diagnostic_export_can_report_recovery_failure() {
601        let ledger = AllocationLedger {
602            current_generation: 0,
603            allocation_history: AllocationHistory::default(),
604        };
605        let commit_recovery = CommitStoreDiagnostic {
606            slot0: CommitSlotDiagnostic::Empty,
607            slot1: CommitSlotDiagnostic::Empty,
608            recovery: Err(CommitRecoveryError::NoValidGeneration),
609        };
610
611        let mut export = DiagnosticExport::from_ledger(
612            &ledger,
613            AllocationSlotDescriptor::memory_manager(0).expect("usable slot"),
614        );
615        export.commit_recovery = Some(commit_recovery);
616
617        assert_eq!(
618            export.commit_recovery.expect("commit recovery").recovery,
619            Err(CommitRecoveryError::NoValidGeneration)
620        );
621    }
622}