Skip to main content

canic_core/api/runtime/
mod.rs

1pub mod install;
2
3use crate::{
4    cdk::types::Principal,
5    domain::runtime::{
6        FailureSeverity, HealthStatus, ReadinessStatus, RuntimeCheckStatus,
7        RuntimeDiagnosticSeverity, RuntimeFieldVisibility, RuntimeStateDomainStatus, RuntimeStatus,
8        TimerStatus,
9    },
10    dto::{
11        error::Error,
12        runtime::{
13            CanicHealthStatus, CanicReadinessStatus, CanicRuntimeStatus, CanicTimerStatus,
14            RUNTIME_INTROSPECTION_SCHEMA_VERSION, RuntimeAuthStatusSummary,
15            RuntimeBlobStorageStatusSummary, RuntimeBuildInfo, RuntimeCheck, RuntimeDiagnostic,
16            RuntimeFeatureStatus, RuntimeStateDomainSummary, RuntimeStateSummary,
17            RuntimeTopologyStatus, RuntimeVisibilityEntry,
18        },
19    },
20    ops::{
21        ic::IcOps,
22        runtime::{
23            env::EnvOps,
24            memory::MemoryRegistryOps,
25            metrics::timer::TimerMetrics,
26            ready::ReadyOps,
27            recent_failure::{RecentFailureInput, RecentFailureOps},
28        },
29    },
30    state_contract::{StateStorage, canic_state_manifest_for_role},
31};
32
33const MAX_TIMER_SUBSYSTEM_BYTES: usize = 64;
34const MAX_TIMER_NAME_BYTES: usize = 96;
35const RUNTIME_FEATURE_SOURCE: &str = "compile_feature";
36const RUNTIME_FEATURE_FLAGS: [(&str, bool); 10] = [
37    (
38        "auth-chain-key-ecdsa",
39        cfg!(feature = "auth-chain-key-ecdsa"),
40    ),
41    (
42        "auth-chain-key-root-sign",
43        cfg!(feature = "auth-chain-key-root-sign"),
44    ),
45    (
46        "auth-delegated-token-verify",
47        cfg!(feature = "auth-delegated-token-verify"),
48    ),
49    (
50        "auth-issuer-canister-sig-create",
51        cfg!(feature = "auth-issuer-canister-sig-create"),
52    ),
53    (
54        "auth-issuer-canister-sig-verify",
55        cfg!(feature = "auth-issuer-canister-sig-verify"),
56    ),
57    (
58        "auth-root-canister-sig-create",
59        cfg!(feature = "auth-root-canister-sig-create"),
60    ),
61    (
62        "auth-root-canister-sig-verify",
63        cfg!(feature = "auth-root-canister-sig-verify"),
64    ),
65    ("blob-storage", cfg!(feature = "blob-storage")),
66    (
67        "blob-storage-billing",
68        cfg!(feature = "blob-storage-billing"),
69    ),
70    ("sharding", cfg!(feature = "sharding")),
71];
72
73///
74/// MemoryRuntimeApi
75///
76
77pub struct MemoryRuntimeApi;
78
79impl MemoryRuntimeApi {
80    /// Bootstrap Canic's stable-memory declaration snapshot.
81    pub fn bootstrap_registry() -> Result<(), Error> {
82        MemoryRegistryOps::bootstrap_registry().map_err(Error::from)?;
83
84        Ok(())
85    }
86}
87
88///
89/// RuntimeIntrospectionApi
90///
91
92pub struct RuntimeIntrospectionApi;
93
94impl RuntimeIntrospectionApi {
95    /// Record one heap-only recent-failure summary for guarded runtime status.
96    pub fn record_recent_failure(
97        occurred_at_ns: u64,
98        subsystem: impl Into<String>,
99        code: impl Into<String>,
100        severity: FailureSeverity,
101        summary: impl Into<String>,
102        correlation_id: Option<String>,
103    ) {
104        RecentFailureOps::record(RecentFailureInput {
105            occurred_at_ns,
106            subsystem: subsystem.into(),
107            code: code.into(),
108            severity,
109            summary: summary.into(),
110            correlation_id,
111        });
112    }
113
114    /// Return the minimal health status for a canister that answered the query.
115    #[must_use]
116    pub fn health(observed_at_ns: Option<u64>) -> CanicHealthStatus {
117        CanicHealthStatus {
118            schema_version: RUNTIME_INTROSPECTION_SCHEMA_VERSION,
119            status: HealthStatus::Healthy,
120            observed_at_ns,
121            checks: vec![RuntimeCheck {
122                category: "health".to_string(),
123                code: "canister_responsive".to_string(),
124                status: RuntimeCheckStatus::Pass,
125                subject: "canister".to_string(),
126                detail: "canister returned a health response".to_string(),
127                next: None,
128                source: "runtime_observed".to_string(),
129            }],
130        }
131    }
132
133    /// Return guarded readiness status for the local Canic role.
134    #[must_use]
135    pub fn readiness(observed_at_ns: u64) -> CanicReadinessStatus {
136        let ready = ReadyOps::is_ready();
137        let role = EnvOps::canister_role()
138            .ok()
139            .map(crate::ids::CanisterRole::into_string);
140
141        let (status, check_status, detail, next) = if ready {
142            (
143                ReadinessStatus::Ready,
144                RuntimeCheckStatus::Pass,
145                "runtime readiness barrier is marked ready",
146                None,
147            )
148        } else {
149            (
150                ReadinessStatus::NotReady,
151                RuntimeCheckStatus::Fail,
152                "runtime readiness barrier is not ready",
153                Some("wait for bootstrap to complete or inspect canic_bootstrap_status"),
154            )
155        };
156
157        let readiness_check = RuntimeCheck {
158            category: "readiness".to_string(),
159            code: "runtime_ready_barrier".to_string(),
160            status: check_status,
161            subject: role.clone().unwrap_or_else(|| "unknown_role".to_string()),
162            detail: detail.to_string(),
163            next: next.map(str::to_string),
164            source: "runtime_observed".to_string(),
165        };
166
167        let blockers = if ready {
168            Vec::new()
169        } else {
170            vec![RuntimeDiagnostic {
171                category: "readiness".to_string(),
172                code: "runtime_not_ready".to_string(),
173                severity: RuntimeDiagnosticSeverity::Blocked,
174                subject: role.clone().unwrap_or_else(|| "unknown_role".to_string()),
175                detail: "runtime readiness barrier has not completed".to_string(),
176                next: Some(
177                    "inspect bootstrap status before treating the role as ready".to_string(),
178                ),
179                source: "runtime_observed".to_string(),
180            }]
181        };
182
183        CanicReadinessStatus {
184            schema_version: RUNTIME_INTROSPECTION_SCHEMA_VERSION,
185            role,
186            status,
187            observed_at_ns,
188            checks: vec![readiness_check],
189            blockers,
190            warnings: Vec::new(),
191        }
192    }
193
194    /// Return guarded runtime status for the local Canic role.
195    #[must_use]
196    pub fn runtime_status_for(
197        canister_id: Principal,
198        observed_at_ns: u64,
199        package_name: &str,
200        package_version: &str,
201        canic_version: &str,
202        canister_version: u64,
203    ) -> CanicRuntimeStatus {
204        let readiness = Self::readiness(observed_at_ns);
205        let role = readiness.role.clone();
206        let state = state_summary(role.as_deref());
207        let root = EnvOps::root_pid().ok();
208        let parent = EnvOps::parent_pid().ok();
209        let subnet = EnvOps::subnet_pid().ok();
210        let status = match readiness.status {
211            ReadinessStatus::Ready => RuntimeStatus::Ok,
212            ReadinessStatus::Degraded | ReadinessStatus::NotEvaluated => RuntimeStatus::Degraded,
213            ReadinessStatus::NotReady => RuntimeStatus::Failing,
214        };
215
216        CanicRuntimeStatus {
217            schema_version: RUNTIME_INTROSPECTION_SCHEMA_VERSION,
218            observed_at_ns,
219            canister_id,
220            role,
221            root,
222            network: None,
223            build: RuntimeBuildInfo {
224                package_name: package_name.to_string(),
225                package_version: package_version.to_string(),
226                canic_version: canic_version.to_string(),
227                canister_version,
228            },
229            features: runtime_features(),
230            topology: Some(RuntimeTopologyStatus {
231                root,
232                parent,
233                subnet,
234                source: "runtime_observed".to_string(),
235            }),
236            timers: timer_statuses(),
237            state,
238            auth: Some(runtime_auth_status()),
239            blob_storage: runtime_blob_storage_status(),
240            recent_failures: RecentFailureOps::snapshot(),
241            visibility: runtime_visibility(),
242            readiness,
243            status,
244        }
245    }
246
247    /// Return guarded runtime status using ambient IC runtime values.
248    #[must_use]
249    pub fn runtime_status(
250        observed_at_ns: u64,
251        package_name: &str,
252        package_version: &str,
253        canic_version: &str,
254        canister_version: u64,
255    ) -> CanicRuntimeStatus {
256        Self::runtime_status_for(
257            IcOps::canister_self(),
258            observed_at_ns,
259            package_name,
260            package_version,
261            canic_version,
262            canister_version,
263        )
264    }
265}
266
267fn runtime_features() -> Vec<RuntimeFeatureStatus> {
268    RUNTIME_FEATURE_FLAGS
269        .into_iter()
270        .map(|(name, enabled)| runtime_feature_status(name, enabled))
271        .collect()
272}
273
274fn runtime_feature_status(name: &str, enabled: bool) -> RuntimeFeatureStatus {
275    RuntimeFeatureStatus {
276        name: name.to_string(),
277        enabled,
278        visibility: RuntimeFieldVisibility::OperatorOnly,
279        source: RUNTIME_FEATURE_SOURCE.to_string(),
280    }
281}
282
283fn runtime_auth_status() -> RuntimeAuthStatusSummary {
284    RuntimeAuthStatusSummary {
285        auth_features: RUNTIME_FEATURE_FLAGS
286            .into_iter()
287            .filter(|(name, _)| name.starts_with("auth-"))
288            .map(|(name, enabled)| runtime_feature_status(name, enabled))
289            .collect(),
290    }
291}
292
293fn runtime_blob_storage_status() -> Option<RuntimeBlobStorageStatusSummary> {
294    let blob_storage_enabled = cfg!(feature = "blob-storage");
295    let billing_enabled = cfg!(feature = "blob-storage-billing");
296
297    (blob_storage_enabled || billing_enabled).then(|| RuntimeBlobStorageStatusSummary {
298        blob_storage_features: [
299            ("blob-storage", blob_storage_enabled),
300            ("blob-storage-billing", billing_enabled),
301        ]
302        .into_iter()
303        .map(|(name, enabled)| runtime_feature_status(name, enabled))
304        .collect(),
305    })
306}
307
308fn timer_statuses() -> Vec<CanicTimerStatus> {
309    let mut timers = TimerMetrics::snapshot()
310        .entries
311        .into_iter()
312        .map(|(key, ticks)| {
313            let (subsystem, name) = split_timer_label(&key.label);
314            CanicTimerStatus {
315                name,
316                subsystem,
317                status: if ticks > 0 {
318                    TimerStatus::Healthy
319                } else {
320                    TimerStatus::Unknown
321                },
322                enabled: true,
323                registered: true,
324                last_success_at_ns: None,
325                last_failure_at_ns: None,
326                next_due_at_ns: None,
327                consecutive_failures: 0,
328                last_error_code: None,
329                last_error_summary: None,
330            }
331        })
332        .collect::<Vec<_>>();
333    timers.sort_by(|left, right| {
334        left.subsystem
335            .cmp(&right.subsystem)
336            .then_with(|| left.name.cmp(&right.name))
337    });
338    timers
339}
340
341fn state_summary(role: Option<&str>) -> Option<RuntimeStateSummary> {
342    let role = role?;
343    let manifest = canic_state_manifest_for_role(Some(role));
344    let domains = manifest
345        .roles
346        .into_iter()
347        .flat_map(|role| role.state)
348        .map(|domain| RuntimeStateDomainSummary {
349            domain: domain.domain,
350            version: domain.version,
351            storage: state_storage_name(domain.storage).to_string(),
352            memory_id: domain.memory_id,
353            status: RuntimeStateDomainStatus::Ok,
354        })
355        .collect::<Vec<_>>();
356
357    if domains.is_empty() {
358        return None;
359    }
360
361    Some(RuntimeStateSummary {
362        manifest_schema_version: u32::from(manifest.schema_version),
363        domains,
364        total_stable_memory_pages: None,
365    })
366}
367
368const fn state_storage_name(storage: StateStorage) -> &'static str {
369    match storage {
370        StateStorage::StableMemory => "stable_memory",
371        StateStorage::HeapOnly => "heap_only",
372        StateStorage::NotApplicable => "not_applicable",
373    }
374}
375
376fn split_timer_label(label: &str) -> (String, String) {
377    label.split_once(':').map_or_else(
378        || {
379            (
380                "runtime".to_string(),
381                bounded_runtime_text(label, MAX_TIMER_NAME_BYTES),
382            )
383        },
384        |(subsystem, name)| {
385            (
386                bounded_runtime_text(subsystem, MAX_TIMER_SUBSYSTEM_BYTES),
387                bounded_runtime_text(name, MAX_TIMER_NAME_BYTES),
388            )
389        },
390    )
391}
392
393fn bounded_runtime_text(value: &str, max_bytes: usize) -> String {
394    let sanitized = value
395        .chars()
396        .map(|character| {
397            if character.is_control() {
398                ' '
399            } else {
400                character
401            }
402        })
403        .collect::<String>();
404
405    if sanitized.len() <= max_bytes {
406        return sanitized;
407    }
408
409    let mut end = 0;
410    for (index, character) in sanitized.char_indices() {
411        let next = index + character.len_utf8();
412        if next > max_bytes {
413            break;
414        }
415        end = next;
416    }
417
418    sanitized[..end].to_string()
419}
420
421fn runtime_visibility() -> Vec<RuntimeVisibilityEntry> {
422    [
423        ("schema_version", RuntimeFieldVisibility::PublicSafe),
424        ("observed_at_ns", RuntimeFieldVisibility::PublicSafe),
425        ("canister_id", RuntimeFieldVisibility::OperatorOnly),
426        ("role", RuntimeFieldVisibility::OperatorOnly),
427        ("root", RuntimeFieldVisibility::OperatorOnly),
428        ("network", RuntimeFieldVisibility::OperatorOnly),
429        ("build", RuntimeFieldVisibility::OperatorOnly),
430        ("features", RuntimeFieldVisibility::OperatorOnly),
431        ("topology", RuntimeFieldVisibility::ControllerOnly),
432        ("timers", RuntimeFieldVisibility::OperatorOnly),
433        ("state", RuntimeFieldVisibility::OperatorOnly),
434        ("auth", RuntimeFieldVisibility::OperatorOnly),
435        ("blob_storage", RuntimeFieldVisibility::FeatureGated),
436        ("recent_failures", RuntimeFieldVisibility::OperatorOnly),
437        ("readiness", RuntimeFieldVisibility::OperatorOnly),
438        ("status", RuntimeFieldVisibility::OperatorOnly),
439        ("visibility", RuntimeFieldVisibility::OperatorOnly),
440    ]
441    .into_iter()
442    .map(|(field, visibility)| RuntimeVisibilityEntry {
443        field: field.to_string(),
444        visibility,
445    })
446    .collect()
447}
448
449#[cfg(test)]
450mod tests {
451    use super::*;
452    use crate::ops::runtime::bootstrap::BootstrapStatusOps;
453    use crate::ops::runtime::recent_failure::RecentFailureOps;
454    use crate::{domain::runtime::TimerMode, ops::runtime::metrics::timer::TimerMetrics};
455    use std::time::Duration;
456
457    #[test]
458    fn health_is_minimal_and_schema_versioned() {
459        let health = RuntimeIntrospectionApi::health(Some(42));
460
461        assert_eq!(health.schema_version, RUNTIME_INTROSPECTION_SCHEMA_VERSION);
462        assert_eq!(health.status, HealthStatus::Healthy);
463        assert_eq!(health.observed_at_ns, Some(42));
464        assert_eq!(health.checks.len(), 1);
465        assert_eq!(health.checks[0].code, "canister_responsive");
466    }
467
468    #[test]
469    fn runtime_status_embeds_guarded_readiness_and_build_info() {
470        let status = RuntimeIntrospectionApi::runtime_status_for(
471            Principal::anonymous(),
472            100,
473            "test-canister",
474            "1.2.3",
475            "0.81.0",
476            7,
477        );
478
479        assert_eq!(status.schema_version, RUNTIME_INTROSPECTION_SCHEMA_VERSION);
480        assert_eq!(status.observed_at_ns, 100);
481        assert_eq!(status.canister_id, Principal::anonymous());
482        assert_eq!(status.build.package_name, "test-canister");
483        assert_eq!(status.build.package_version, "1.2.3");
484        assert_eq!(status.build.canic_version, "0.81.0");
485        assert_eq!(status.build.canister_version, 7);
486        assert_eq!(status.readiness.observed_at_ns, 100);
487        assert!(
488            status
489                .visibility
490                .iter()
491                .any(|entry| entry.field == "topology"
492                    && entry.visibility == RuntimeFieldVisibility::ControllerOnly)
493        );
494    }
495
496    #[test]
497    fn runtime_status_classifies_each_top_level_field_visibility() {
498        let status = RuntimeIntrospectionApi::runtime_status_for(
499            Principal::anonymous(),
500            100,
501            "test-canister",
502            "1.2.3",
503            "0.81.0",
504            7,
505        );
506        let expected = [
507            ("schema_version", RuntimeFieldVisibility::PublicSafe),
508            ("observed_at_ns", RuntimeFieldVisibility::PublicSafe),
509            ("canister_id", RuntimeFieldVisibility::OperatorOnly),
510            ("role", RuntimeFieldVisibility::OperatorOnly),
511            ("root", RuntimeFieldVisibility::OperatorOnly),
512            ("network", RuntimeFieldVisibility::OperatorOnly),
513            ("build", RuntimeFieldVisibility::OperatorOnly),
514            ("features", RuntimeFieldVisibility::OperatorOnly),
515            ("topology", RuntimeFieldVisibility::ControllerOnly),
516            ("timers", RuntimeFieldVisibility::OperatorOnly),
517            ("state", RuntimeFieldVisibility::OperatorOnly),
518            ("auth", RuntimeFieldVisibility::OperatorOnly),
519            ("blob_storage", RuntimeFieldVisibility::FeatureGated),
520            ("recent_failures", RuntimeFieldVisibility::OperatorOnly),
521            ("readiness", RuntimeFieldVisibility::OperatorOnly),
522            ("status", RuntimeFieldVisibility::OperatorOnly),
523            ("visibility", RuntimeFieldVisibility::OperatorOnly),
524        ];
525
526        assert_eq!(status.visibility.len(), expected.len());
527        for (index, (field, visibility)) in expected.into_iter().enumerate() {
528            assert_eq!(status.visibility[index].field, field);
529            assert_eq!(status.visibility[index].visibility, visibility);
530        }
531    }
532
533    #[test]
534    fn runtime_status_reports_compile_features_deterministically() {
535        let status = RuntimeIntrospectionApi::runtime_status_for(
536            Principal::anonymous(),
537            100,
538            "test-canister",
539            "1.2.3",
540            "0.81.0",
541            7,
542        );
543        assert_eq!(status.features.len(), RUNTIME_FEATURE_FLAGS.len());
544        for (index, (name, enabled)) in RUNTIME_FEATURE_FLAGS.into_iter().enumerate() {
545            assert_eq!(status.features[index].name, name);
546            assert_eq!(status.features[index].enabled, enabled);
547            assert_eq!(
548                status.features[index].visibility,
549                RuntimeFieldVisibility::OperatorOnly
550            );
551            assert_eq!(status.features[index].source, RUNTIME_FEATURE_SOURCE);
552        }
553    }
554
555    #[test]
556    fn runtime_status_reports_auth_and_blob_storage_feature_summaries() {
557        let status = RuntimeIntrospectionApi::runtime_status_for(
558            Principal::anonymous(),
559            100,
560            "test-canister",
561            "1.2.3",
562            "0.81.0",
563            7,
564        );
565
566        let auth = status.auth.expect("auth feature summary");
567        assert!(
568            auth.auth_features
569                .windows(2)
570                .all(|features| features[0].name <= features[1].name)
571        );
572        assert_runtime_feature(
573            &auth.auth_features,
574            "auth-chain-key-ecdsa",
575            cfg!(feature = "auth-chain-key-ecdsa"),
576        );
577        assert_runtime_feature(
578            &auth.auth_features,
579            "auth-delegated-token-verify",
580            cfg!(feature = "auth-delegated-token-verify"),
581        );
582        assert_runtime_feature(
583            &auth.auth_features,
584            "auth-issuer-canister-sig-create",
585            cfg!(feature = "auth-issuer-canister-sig-create"),
586        );
587
588        if cfg!(any(
589            feature = "blob-storage",
590            feature = "blob-storage-billing"
591        )) {
592            let blob_storage = status.blob_storage.expect("blob-storage feature summary");
593            assert_runtime_feature(
594                &blob_storage.blob_storage_features,
595                "blob-storage",
596                cfg!(feature = "blob-storage"),
597            );
598            assert_runtime_feature(
599                &blob_storage.blob_storage_features,
600                "blob-storage-billing",
601                cfg!(feature = "blob-storage-billing"),
602            );
603        } else {
604            assert!(status.blob_storage.is_none());
605        }
606    }
607
608    fn assert_runtime_feature(
609        features: &[RuntimeFeatureStatus],
610        name: &str,
611        expected_enabled: bool,
612    ) {
613        let feature = features
614            .iter()
615            .find(|feature| feature.name == name)
616            .unwrap_or_else(|| panic!("expected runtime feature {name}"));
617
618        assert_eq!(feature.enabled, expected_enabled);
619        assert_eq!(feature.visibility, RuntimeFieldVisibility::OperatorOnly);
620        assert_eq!(feature.source, RUNTIME_FEATURE_SOURCE);
621    }
622
623    #[test]
624    fn runtime_status_projects_registered_timer_metrics() {
625        TimerMetrics::reset();
626        TimerMetrics::record_timer_scheduled(
627            TimerMode::Interval,
628            Duration::from_mins(1),
629            "cycles:interval",
630        );
631        TimerMetrics::record_timer_scheduled(
632            TimerMode::Once,
633            Duration::from_secs(1),
634            "auth_renewal:init",
635        );
636        TimerMetrics::record_timer_tick(
637            TimerMode::Once,
638            Duration::from_secs(1),
639            "auth_renewal:init",
640        );
641
642        let status = RuntimeIntrospectionApi::runtime_status_for(
643            Principal::anonymous(),
644            100,
645            "test-canister",
646            "1.2.3",
647            "0.81.0",
648            7,
649        );
650
651        assert_eq!(status.timers.len(), 2);
652        assert_eq!(status.timers[0].subsystem, "auth_renewal");
653        assert_eq!(status.timers[0].name, "init");
654        assert_eq!(status.timers[0].status, TimerStatus::Healthy);
655        assert_eq!(status.timers[1].subsystem, "cycles");
656        assert_eq!(status.timers[1].name, "interval");
657        assert_eq!(status.timers[1].status, TimerStatus::Unknown);
658
659        TimerMetrics::reset();
660    }
661
662    #[test]
663    fn runtime_status_bounds_timer_labels() {
664        TimerMetrics::reset();
665
666        let label = format!("{}\n:{}\n", "subsystem".repeat(12), "timer_name".repeat(16));
667        TimerMetrics::record_timer_scheduled(TimerMode::Once, Duration::from_secs(1), &label);
668
669        let status = RuntimeIntrospectionApi::runtime_status_for(
670            Principal::anonymous(),
671            100,
672            "test-canister",
673            "1.2.3",
674            "0.81.0",
675            7,
676        );
677
678        assert_eq!(status.timers.len(), 1);
679        assert!(status.timers[0].subsystem.len() <= MAX_TIMER_SUBSYSTEM_BYTES);
680        assert!(status.timers[0].name.len() <= MAX_TIMER_NAME_BYTES);
681        assert!(!status.timers[0].subsystem.contains('\n'));
682        assert!(!status.timers[0].name.contains('\n'));
683
684        TimerMetrics::reset();
685    }
686
687    #[test]
688    fn state_summary_uses_declared_metadata_without_value_counts() {
689        let summary = state_summary(Some("root")).expect("root state declarations");
690
691        assert_eq!(
692            summary.manifest_schema_version,
693            u32::from(crate::state_contract::STATE_MANIFEST_SCHEMA_VERSION)
694        );
695        assert!(summary.total_stable_memory_pages.is_none());
696        assert!(summary.domains.iter().any(|domain| {
697            domain.domain == "env"
698                && domain.storage == "stable_memory"
699                && domain.status == RuntimeStateDomainStatus::Ok
700        }));
701        assert!(state_summary(Some("unknown_role")).is_none());
702        assert!(state_summary(None).is_none());
703    }
704
705    #[test]
706    fn runtime_status_includes_recent_failure_snapshot() {
707        RecentFailureOps::reset();
708        RuntimeIntrospectionApi::record_recent_failure(
709            77,
710            "runtime",
711            "readiness_failed",
712            FailureSeverity::Error,
713            "bounded failure summary",
714            Some("runtime-check".to_string()),
715        );
716
717        let status = RuntimeIntrospectionApi::runtime_status_for(
718            Principal::anonymous(),
719            100,
720            "test-canister",
721            "1.2.3",
722            "0.81.0",
723            7,
724        );
725
726        assert_eq!(status.recent_failures.len(), 1);
727        assert_eq!(status.recent_failures[0].occurred_at_ns, 77);
728        assert_eq!(status.recent_failures[0].subsystem, "runtime");
729        assert_eq!(status.recent_failures[0].code, "readiness_failed");
730
731        RecentFailureOps::reset();
732    }
733
734    #[test]
735    fn runtime_status_includes_bootstrap_failure_metadata() {
736        RecentFailureOps::reset();
737        BootstrapStatusOps::set_phase("root:init");
738        BootstrapStatusOps::mark_failed("raw bootstrap failure detail");
739
740        let status = RuntimeIntrospectionApi::runtime_status_for(
741            Principal::anonymous(),
742            100,
743            "test-canister",
744            "1.2.3",
745            "0.81.0",
746            7,
747        );
748
749        let failure = status
750            .recent_failures
751            .iter()
752            .find(|failure| failure.code == "bootstrap_failed")
753            .expect("bootstrap failure metadata");
754
755        assert_eq!(failure.subsystem, "runtime_bootstrap");
756        assert_eq!(failure.severity, FailureSeverity::Error);
757        assert_eq!(failure.correlation_id.as_deref(), Some("root:init"));
758        assert!(
759            !failure.summary.contains("raw bootstrap failure detail"),
760            "runtime status recent failures should not mirror raw bootstrap errors"
761        );
762
763        RecentFailureOps::reset();
764    }
765}