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::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: domain.storage.as_str().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
368fn split_timer_label(label: &str) -> (String, String) {
369    label.split_once(':').map_or_else(
370        || {
371            (
372                "runtime".to_string(),
373                bounded_runtime_text(label, MAX_TIMER_NAME_BYTES),
374            )
375        },
376        |(subsystem, name)| {
377            (
378                bounded_runtime_text(subsystem, MAX_TIMER_SUBSYSTEM_BYTES),
379                bounded_runtime_text(name, MAX_TIMER_NAME_BYTES),
380            )
381        },
382    )
383}
384
385fn bounded_runtime_text(value: &str, max_bytes: usize) -> String {
386    let sanitized = value
387        .chars()
388        .map(|character| {
389            if character.is_control() {
390                ' '
391            } else {
392                character
393            }
394        })
395        .collect::<String>();
396
397    if sanitized.len() <= max_bytes {
398        return sanitized;
399    }
400
401    let mut end = 0;
402    for (index, character) in sanitized.char_indices() {
403        let next = index + character.len_utf8();
404        if next > max_bytes {
405            break;
406        }
407        end = next;
408    }
409
410    sanitized[..end].to_string()
411}
412
413fn runtime_visibility() -> Vec<RuntimeVisibilityEntry> {
414    [
415        ("schema_version", RuntimeFieldVisibility::PublicSafe),
416        ("observed_at_ns", RuntimeFieldVisibility::PublicSafe),
417        ("canister_id", RuntimeFieldVisibility::OperatorOnly),
418        ("role", RuntimeFieldVisibility::OperatorOnly),
419        ("root", RuntimeFieldVisibility::OperatorOnly),
420        ("network", RuntimeFieldVisibility::OperatorOnly),
421        ("build", RuntimeFieldVisibility::OperatorOnly),
422        ("features", RuntimeFieldVisibility::OperatorOnly),
423        ("topology", RuntimeFieldVisibility::ControllerOnly),
424        ("timers", RuntimeFieldVisibility::OperatorOnly),
425        ("state", RuntimeFieldVisibility::OperatorOnly),
426        ("auth", RuntimeFieldVisibility::OperatorOnly),
427        ("blob_storage", RuntimeFieldVisibility::FeatureGated),
428        ("recent_failures", RuntimeFieldVisibility::OperatorOnly),
429        ("readiness", RuntimeFieldVisibility::OperatorOnly),
430        ("status", RuntimeFieldVisibility::OperatorOnly),
431        ("visibility", RuntimeFieldVisibility::OperatorOnly),
432    ]
433    .into_iter()
434    .map(|(field, visibility)| RuntimeVisibilityEntry {
435        field: field.to_string(),
436        visibility,
437    })
438    .collect()
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444    use crate::ops::runtime::bootstrap::{BootstrapPhaseLabel, BootstrapStatusOps};
445    use crate::ops::runtime::recent_failure::RecentFailureOps;
446    use crate::{domain::runtime::TimerMode, ops::runtime::metrics::timer::TimerMetrics};
447    use std::time::Duration;
448
449    #[test]
450    fn health_is_minimal_and_schema_versioned() {
451        let health = RuntimeIntrospectionApi::health(Some(42));
452
453        assert_eq!(health.schema_version, RUNTIME_INTROSPECTION_SCHEMA_VERSION);
454        assert_eq!(health.status, HealthStatus::Healthy);
455        assert_eq!(health.observed_at_ns, Some(42));
456        assert_eq!(health.checks.len(), 1);
457        assert_eq!(health.checks[0].code, "canister_responsive");
458    }
459
460    #[test]
461    fn runtime_status_embeds_guarded_readiness_and_build_info() {
462        let status = RuntimeIntrospectionApi::runtime_status_for(
463            Principal::anonymous(),
464            100,
465            "test-canister",
466            "1.2.3",
467            "0.81.0",
468            7,
469        );
470
471        assert_eq!(status.schema_version, RUNTIME_INTROSPECTION_SCHEMA_VERSION);
472        assert_eq!(status.observed_at_ns, 100);
473        assert_eq!(status.canister_id, Principal::anonymous());
474        assert_eq!(status.build.package_name, "test-canister");
475        assert_eq!(status.build.package_version, "1.2.3");
476        assert_eq!(status.build.canic_version, "0.81.0");
477        assert_eq!(status.build.canister_version, 7);
478        assert_eq!(status.readiness.observed_at_ns, 100);
479        assert!(
480            status
481                .visibility
482                .iter()
483                .any(|entry| entry.field == "topology"
484                    && entry.visibility == RuntimeFieldVisibility::ControllerOnly)
485        );
486    }
487
488    #[test]
489    fn runtime_status_classifies_each_top_level_field_visibility() {
490        let status = RuntimeIntrospectionApi::runtime_status_for(
491            Principal::anonymous(),
492            100,
493            "test-canister",
494            "1.2.3",
495            "0.81.0",
496            7,
497        );
498        let expected = [
499            ("schema_version", RuntimeFieldVisibility::PublicSafe),
500            ("observed_at_ns", RuntimeFieldVisibility::PublicSafe),
501            ("canister_id", RuntimeFieldVisibility::OperatorOnly),
502            ("role", RuntimeFieldVisibility::OperatorOnly),
503            ("root", RuntimeFieldVisibility::OperatorOnly),
504            ("network", RuntimeFieldVisibility::OperatorOnly),
505            ("build", RuntimeFieldVisibility::OperatorOnly),
506            ("features", RuntimeFieldVisibility::OperatorOnly),
507            ("topology", RuntimeFieldVisibility::ControllerOnly),
508            ("timers", RuntimeFieldVisibility::OperatorOnly),
509            ("state", RuntimeFieldVisibility::OperatorOnly),
510            ("auth", RuntimeFieldVisibility::OperatorOnly),
511            ("blob_storage", RuntimeFieldVisibility::FeatureGated),
512            ("recent_failures", RuntimeFieldVisibility::OperatorOnly),
513            ("readiness", RuntimeFieldVisibility::OperatorOnly),
514            ("status", RuntimeFieldVisibility::OperatorOnly),
515            ("visibility", RuntimeFieldVisibility::OperatorOnly),
516        ];
517
518        assert_eq!(status.visibility.len(), expected.len());
519        for (index, (field, visibility)) in expected.into_iter().enumerate() {
520            assert_eq!(status.visibility[index].field, field);
521            assert_eq!(status.visibility[index].visibility, visibility);
522        }
523    }
524
525    #[test]
526    fn runtime_status_reports_compile_features_deterministically() {
527        let status = RuntimeIntrospectionApi::runtime_status_for(
528            Principal::anonymous(),
529            100,
530            "test-canister",
531            "1.2.3",
532            "0.81.0",
533            7,
534        );
535        assert_eq!(status.features.len(), RUNTIME_FEATURE_FLAGS.len());
536        for (index, (name, enabled)) in RUNTIME_FEATURE_FLAGS.into_iter().enumerate() {
537            assert_eq!(status.features[index].name, name);
538            assert_eq!(status.features[index].enabled, enabled);
539            assert_eq!(
540                status.features[index].visibility,
541                RuntimeFieldVisibility::OperatorOnly
542            );
543            assert_eq!(status.features[index].source, RUNTIME_FEATURE_SOURCE);
544        }
545    }
546
547    #[test]
548    fn runtime_status_reports_auth_and_blob_storage_feature_summaries() {
549        let status = RuntimeIntrospectionApi::runtime_status_for(
550            Principal::anonymous(),
551            100,
552            "test-canister",
553            "1.2.3",
554            "0.81.0",
555            7,
556        );
557
558        let auth = status.auth.expect("auth feature summary");
559        assert!(
560            auth.auth_features
561                .windows(2)
562                .all(|features| features[0].name <= features[1].name)
563        );
564        assert_runtime_feature(
565            &auth.auth_features,
566            "auth-chain-key-ecdsa",
567            cfg!(feature = "auth-chain-key-ecdsa"),
568        );
569        assert_runtime_feature(
570            &auth.auth_features,
571            "auth-delegated-token-verify",
572            cfg!(feature = "auth-delegated-token-verify"),
573        );
574        assert_runtime_feature(
575            &auth.auth_features,
576            "auth-issuer-canister-sig-create",
577            cfg!(feature = "auth-issuer-canister-sig-create"),
578        );
579
580        if cfg!(any(
581            feature = "blob-storage",
582            feature = "blob-storage-billing"
583        )) {
584            let blob_storage = status.blob_storage.expect("blob-storage feature summary");
585            assert_runtime_feature(
586                &blob_storage.blob_storage_features,
587                "blob-storage",
588                cfg!(feature = "blob-storage"),
589            );
590            assert_runtime_feature(
591                &blob_storage.blob_storage_features,
592                "blob-storage-billing",
593                cfg!(feature = "blob-storage-billing"),
594            );
595        } else {
596            assert!(status.blob_storage.is_none());
597        }
598    }
599
600    fn assert_runtime_feature(
601        features: &[RuntimeFeatureStatus],
602        name: &str,
603        expected_enabled: bool,
604    ) {
605        let feature = features
606            .iter()
607            .find(|feature| feature.name == name)
608            .unwrap_or_else(|| panic!("expected runtime feature {name}"));
609
610        assert_eq!(feature.enabled, expected_enabled);
611        assert_eq!(feature.visibility, RuntimeFieldVisibility::OperatorOnly);
612        assert_eq!(feature.source, RUNTIME_FEATURE_SOURCE);
613    }
614
615    #[test]
616    fn runtime_status_projects_registered_timer_metrics() {
617        TimerMetrics::reset();
618        TimerMetrics::record_timer_scheduled(
619            TimerMode::Interval,
620            Duration::from_mins(1),
621            "cycles:interval",
622        );
623        TimerMetrics::record_timer_scheduled(
624            TimerMode::Once,
625            Duration::from_secs(1),
626            "auth_renewal:init",
627        );
628        TimerMetrics::record_timer_tick(
629            TimerMode::Once,
630            Duration::from_secs(1),
631            "auth_renewal:init",
632        );
633
634        let status = RuntimeIntrospectionApi::runtime_status_for(
635            Principal::anonymous(),
636            100,
637            "test-canister",
638            "1.2.3",
639            "0.81.0",
640            7,
641        );
642
643        assert_eq!(status.timers.len(), 2);
644        assert_eq!(status.timers[0].subsystem, "auth_renewal");
645        assert_eq!(status.timers[0].name, "init");
646        assert_eq!(status.timers[0].status, TimerStatus::Healthy);
647        assert_eq!(status.timers[1].subsystem, "cycles");
648        assert_eq!(status.timers[1].name, "interval");
649        assert_eq!(status.timers[1].status, TimerStatus::Unknown);
650
651        TimerMetrics::reset();
652    }
653
654    #[test]
655    fn runtime_status_bounds_timer_labels() {
656        TimerMetrics::reset();
657
658        let label = format!("{}\n:{}\n", "subsystem".repeat(12), "timer_name".repeat(16));
659        TimerMetrics::record_timer_scheduled(TimerMode::Once, Duration::from_secs(1), &label);
660
661        let status = RuntimeIntrospectionApi::runtime_status_for(
662            Principal::anonymous(),
663            100,
664            "test-canister",
665            "1.2.3",
666            "0.81.0",
667            7,
668        );
669
670        assert_eq!(status.timers.len(), 1);
671        assert!(status.timers[0].subsystem.len() <= MAX_TIMER_SUBSYSTEM_BYTES);
672        assert!(status.timers[0].name.len() <= MAX_TIMER_NAME_BYTES);
673        assert!(!status.timers[0].subsystem.contains('\n'));
674        assert!(!status.timers[0].name.contains('\n'));
675
676        TimerMetrics::reset();
677    }
678
679    #[test]
680    fn state_summary_uses_declared_metadata_without_value_counts() {
681        let summary = state_summary(Some("root")).expect("root state declarations");
682
683        assert_eq!(
684            summary.manifest_schema_version,
685            u32::from(crate::state_contract::STATE_MANIFEST_SCHEMA_VERSION)
686        );
687        assert!(summary.total_stable_memory_pages.is_none());
688        assert!(summary.domains.iter().any(|domain| {
689            domain.domain == "env"
690                && domain.storage == "stable_memory"
691                && domain.status == RuntimeStateDomainStatus::Ok
692        }));
693        assert!(state_summary(Some("unknown_role")).is_none());
694        assert!(state_summary(None).is_none());
695    }
696
697    #[test]
698    fn runtime_status_includes_recent_failure_snapshot() {
699        RecentFailureOps::reset();
700        RuntimeIntrospectionApi::record_recent_failure(
701            77,
702            "runtime",
703            "readiness_failed",
704            FailureSeverity::Error,
705            "bounded failure summary",
706            Some("runtime-check".to_string()),
707        );
708
709        let status = RuntimeIntrospectionApi::runtime_status_for(
710            Principal::anonymous(),
711            100,
712            "test-canister",
713            "1.2.3",
714            "0.81.0",
715            7,
716        );
717
718        assert_eq!(status.recent_failures.len(), 1);
719        assert_eq!(status.recent_failures[0].occurred_at_ns, 77);
720        assert_eq!(status.recent_failures[0].subsystem, "runtime");
721        assert_eq!(status.recent_failures[0].code, "readiness_failed");
722
723        RecentFailureOps::reset();
724    }
725
726    #[test]
727    fn runtime_status_includes_bootstrap_failure_metadata() {
728        RecentFailureOps::reset();
729        BootstrapStatusOps::set_phase(BootstrapPhaseLabel::ROOT_INIT);
730        BootstrapStatusOps::mark_failed("raw bootstrap failure detail");
731
732        let status = RuntimeIntrospectionApi::runtime_status_for(
733            Principal::anonymous(),
734            100,
735            "test-canister",
736            "1.2.3",
737            "0.81.0",
738            7,
739        );
740
741        let failure = status
742            .recent_failures
743            .iter()
744            .find(|failure| failure.code == "bootstrap_failed")
745            .expect("bootstrap failure metadata");
746
747        assert_eq!(failure.subsystem, "runtime_bootstrap");
748        assert_eq!(failure.severity, FailureSeverity::Error);
749        assert_eq!(failure.correlation_id.as_deref(), Some("root:init"));
750        assert!(
751            !failure.summary.contains("raw bootstrap failure detail"),
752            "runtime status recent failures should not mirror raw bootstrap errors"
753        );
754
755        RecentFailureOps::reset();
756    }
757}