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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
17#[serde(deny_unknown_fields)]
18pub struct DiagnosticExport {
19 pub current_generation: u64,
21 pub ledger_anchor: AllocationSlotDescriptor,
23 pub records: Vec<DiagnosticRecord>,
25 pub generations: Vec<GenerationRecord>,
27 #[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
29 pub commit_recovery: Option<CommitStoreDiagnostic>,
30}
31
32#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
40#[serde(deny_unknown_fields)]
41pub struct DiagnosticRuntimeBinding {
42 pub policy_identity: PolicyIdentity,
44 pub declaration_fingerprint: SealedDeclarationFingerprint,
46}
47
48impl DiagnosticRuntimeBinding {
49 #[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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
74#[serde(deny_unknown_fields)]
75pub struct MemoryRuntimeDoctorReport {
76 pub bootstrapped: bool,
78 pub tested_policy_identity: Result<PolicyIdentity, DiagnosticFailure>,
80 pub tested_declaration_fingerprint: SealedDeclarationFingerprint,
82 #[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
84 pub established_bootstrap_binding: Option<DiagnosticRuntimeBinding>,
85 pub bootstrap_binding: DiagnosticCheck,
88 pub ledger_anchor: AllocationSlotDescriptor,
90 pub stable_cell: DiagnosticStableCell,
92 #[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
94 pub commit_recovery: Option<CommitStoreDiagnostic>,
95 #[serde(deserialize_with = "crate::cbor::deserialize_present_option")]
97 pub ledger: Option<DiagnosticExport>,
98 pub registered_declarations: Vec<DiagnosticDeclaration>,
100 pub range_authority: DiagnosticRangeAuthority,
103 pub validation: DiagnosticCheck,
105}
106
107#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
114#[serde(deny_unknown_fields)]
115pub struct DiagnosticDeclaration {
116 pub authority: String,
118 pub declaration: AllocationDeclaration,
120}
121
122impl DiagnosticDeclaration {
123 #[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#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
140pub enum DiagnosticCode {
141 #[serde(rename = "stable_cell")]
143 StableCell,
144 #[serde(rename = "unsupported_format")]
146 UnsupportedFormat,
147 #[serde(rename = "ledger_recovery")]
149 LedgerRecovery,
150 #[serde(rename = "allocation_validation")]
152 AllocationValidation,
153 #[serde(rename = "policy_identity")]
155 PolicyIdentity,
156 #[serde(rename = "runtime_binding")]
158 RuntimeBinding,
159}
160
161#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
168#[serde(deny_unknown_fields)]
169pub struct DiagnosticFailure {
170 pub code: DiagnosticCode,
172 pub message: String,
174}
175
176impl DiagnosticFailure {
177 #[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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
194#[serde(deny_unknown_fields)]
195pub struct DiagnosticRangeAuthority {
196 pub registered_records: Vec<MemoryManagerAuthorityRecord>,
198 pub effective_authority: MemoryManagerRangeAuthority,
200}
201
202impl DiagnosticRangeAuthority {
203 #[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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
223#[serde(deny_unknown_fields)]
224pub struct DiagnosticStableCell {
225 pub status: DiagnosticStableCellStatus,
227 pub memory_size: DiagnosticMemorySize,
229}
230
231impl DiagnosticStableCell {
232 #[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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
252#[serde(deny_unknown_fields)]
253pub enum DiagnosticStableCellStatus {
254 Empty,
256 Readable,
258 Corrupt {
261 failure: DiagnosticFailure,
263 },
264}
265
266#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
273#[serde(deny_unknown_fields)]
274pub enum DiagnosticCheck {
275 NotRun {
277 code: DiagnosticCode,
279 message: String,
281 },
282 Passed,
284 Failed {
286 code: DiagnosticCode,
288 message: String,
290 },
291}
292
293impl DiagnosticCheck {
294 #[must_use]
296 pub const fn passed() -> Self {
297 Self::Passed
298 }
299
300 #[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 #[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 #[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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
351#[serde(deny_unknown_fields)]
352pub struct DiagnosticRecord {
353 pub allocation: AllocationRecord,
355 #[serde(skip_serializing_if = "Option::is_none")]
360 pub memory_size: Option<DiagnosticMemorySize>,
361}
362
363#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
370#[serde(deny_unknown_fields)]
371pub struct DiagnosticMemorySize {
372 pub wasm_pages: u64,
374 pub bytes: u64,
376}
377
378impl DiagnosticMemorySize {
379 #[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}