clawft-kernel 0.5.2

WeftOS kernel: boot sequence, process table, service registry, and health subsystem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! Health monitoring subsystem.
//!
//! The [`HealthSystem`] aggregates health checks from all registered
//! services and produces an overall [`OverallHealth`] status.

use std::sync::Arc;

use serde::{Deserialize, Serialize};
use tracing::{debug, warn};

use crate::service::ServiceRegistry;

/// Health status for a single service.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum HealthStatus {
    /// Service is operating normally.
    Healthy,
    /// Service is operational but degraded.
    Degraded(String),
    /// Service is not operational.
    Unhealthy(String),
    /// Health status could not be determined (e.g. timeout).
    Unknown,
}

impl std::fmt::Display for HealthStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HealthStatus::Healthy => write!(f, "healthy"),
            HealthStatus::Degraded(msg) => write!(f, "degraded: {msg}"),
            HealthStatus::Unhealthy(msg) => write!(f, "unhealthy: {msg}"),
            HealthStatus::Unknown => write!(f, "unknown"),
        }
    }
}

/// Aggregated health status for the entire kernel.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum OverallHealth {
    /// All services are healthy.
    Healthy,
    /// Some services are degraded or unhealthy.
    Degraded {
        /// Services that are not fully healthy.
        unhealthy_services: Vec<String>,
    },
    /// All services are unhealthy or no services registered.
    Down,
}

impl std::fmt::Display for OverallHealth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            OverallHealth::Healthy => write!(f, "healthy"),
            OverallHealth::Degraded { unhealthy_services } => {
                write!(f, "degraded ({})", unhealthy_services.join(", "))
            }
            OverallHealth::Down => write!(f, "down"),
        }
    }
}

/// Health monitoring system.
///
/// Periodically checks all registered services and aggregates their
/// health into an overall status.
pub struct HealthSystem {
    check_interval_secs: u64,
}

impl HealthSystem {
    /// Create a new health system with the given check interval.
    pub fn new(check_interval_secs: u64) -> Self {
        Self {
            check_interval_secs,
        }
    }

    /// Get the configured check interval in seconds.
    pub fn check_interval_secs(&self) -> u64 {
        self.check_interval_secs
    }

    /// Run a single health check cycle against all services.
    pub async fn aggregate(
        &self,
        registry: &Arc<ServiceRegistry>,
    ) -> (OverallHealth, Vec<(String, HealthStatus)>) {
        let results = registry.health_all().await;

        if results.is_empty() {
            return (OverallHealth::Down, results);
        }

        let mut unhealthy = Vec::new();
        let mut all_unhealthy = true;

        for (name, status) in &results {
            match status {
                HealthStatus::Healthy => {
                    debug!(service = %name, "health check: healthy");
                    all_unhealthy = false;
                }
                HealthStatus::Degraded(msg) => {
                    warn!(service = %name, reason = %msg, "health check: degraded");
                    unhealthy.push(name.clone());
                    all_unhealthy = false;
                }
                HealthStatus::Unhealthy(msg) => {
                    warn!(service = %name, reason = %msg, "health check: unhealthy");
                    unhealthy.push(name.clone());
                }
                HealthStatus::Unknown => {
                    warn!(service = %name, "health check: unknown");
                    unhealthy.push(name.clone());
                }
            }
        }

        let overall = if unhealthy.is_empty() {
            OverallHealth::Healthy
        } else if all_unhealthy {
            OverallHealth::Down
        } else {
            OverallHealth::Degraded {
                unhealthy_services: unhealthy,
            }
        };

        (overall, results)
    }
}

// ── K2b-G2: Liveness and readiness probes (os-patterns) ─────────

/// Result of a liveness or readiness probe.
#[non_exhaustive]
#[cfg(feature = "os-patterns")]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProbeResult {
    /// Service is live (responding to probes).
    Live,
    /// Service is not live.
    NotLive { reason: String },
    /// Service is ready to accept traffic.
    Ready,
    /// Service is not ready.
    NotReady { reason: String },
}

/// Configuration for liveness and readiness probes.
#[cfg(feature = "os-patterns")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProbeConfig {
    /// How often to check liveness (default: 10s).
    pub liveness_interval_secs: u64,
    /// How often to check readiness (default: 5s).
    pub readiness_interval_secs: u64,
    /// Number of consecutive failures before marking as failed.
    pub failure_threshold: u32,
    /// Number of consecutive successes before marking as recovered.
    pub success_threshold: u32,
}

#[cfg(feature = "os-patterns")]
impl Default for ProbeConfig {
    fn default() -> Self {
        Self {
            liveness_interval_secs: 10,
            readiness_interval_secs: 5,
            failure_threshold: 3,
            success_threshold: 1,
        }
    }
}

/// Tracks consecutive probe results for threshold-based decisions.
#[cfg(feature = "os-patterns")]
#[derive(Debug, Clone)]
pub struct ProbeState {
    /// Consecutive liveness failures.
    pub liveness_failures: u32,
    /// Consecutive readiness failures.
    pub readiness_failures: u32,
    /// Consecutive readiness successes (for recovery).
    pub readiness_successes: u32,
    /// Whether the service is currently considered live.
    pub is_live: bool,
    /// Whether the service is currently considered ready.
    pub is_ready: bool,
}

#[cfg(feature = "os-patterns")]
impl Default for ProbeState {
    fn default() -> Self {
        Self {
            liveness_failures: 0,
            readiness_failures: 0,
            readiness_successes: 0,
            is_live: true,
            is_ready: true,
        }
    }
}

#[cfg(feature = "os-patterns")]
impl ProbeState {
    /// Record a liveness probe result.
    ///
    /// Returns `true` if the service should be restarted (failures >= threshold).
    pub fn record_liveness(&mut self, result: &ProbeResult, config: &ProbeConfig) -> bool {
        match result {
            ProbeResult::Live => {
                self.liveness_failures = 0;
                self.is_live = true;
                false
            }
            ProbeResult::NotLive { .. } => {
                self.liveness_failures += 1;
                if self.liveness_failures >= config.failure_threshold {
                    self.is_live = false;
                    true
                } else {
                    false
                }
            }
            _ => false, // readiness results ignored here
        }
    }

    /// Record a readiness probe result.
    ///
    /// Returns the readiness state change:
    /// - `Some(false)` if service should be removed from registry
    /// - `Some(true)` if service should be re-added (recovered)
    /// - `None` if no state change
    pub fn record_readiness(&mut self, result: &ProbeResult, config: &ProbeConfig) -> Option<bool> {
        match result {
            ProbeResult::Ready => {
                self.readiness_failures = 0;
                self.readiness_successes += 1;
                if !self.is_ready && self.readiness_successes >= config.success_threshold {
                    self.is_ready = true;
                    Some(true) // recovered
                } else {
                    None
                }
            }
            ProbeResult::NotReady { .. } => {
                self.readiness_successes = 0;
                self.readiness_failures += 1;
                if self.is_ready && self.readiness_failures >= config.failure_threshold {
                    self.is_ready = false;
                    Some(false) // became unready
                } else {
                    None
                }
            }
            _ => None, // liveness results ignored here
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::service::{ServiceType, SystemService};
    use async_trait::async_trait;

    struct HealthyService;

    #[async_trait]
    impl SystemService for HealthyService {
        fn name(&self) -> &str {
            "healthy-svc"
        }
        fn service_type(&self) -> ServiceType {
            ServiceType::Core
        }
        async fn start(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
            Ok(())
        }
        async fn stop(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
            Ok(())
        }
        async fn health_check(&self) -> HealthStatus {
            HealthStatus::Healthy
        }
    }

    struct UnhealthyService;

    #[async_trait]
    impl SystemService for UnhealthyService {
        fn name(&self) -> &str {
            "unhealthy-svc"
        }
        fn service_type(&self) -> ServiceType {
            ServiceType::Core
        }
        async fn start(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
            Ok(())
        }
        async fn stop(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
            Ok(())
        }
        async fn health_check(&self) -> HealthStatus {
            HealthStatus::Unhealthy("test failure".into())
        }
    }

    #[tokio::test]
    async fn aggregate_all_healthy() {
        let registry = Arc::new(ServiceRegistry::new());
        registry.register(Arc::new(HealthyService)).unwrap();

        let health = HealthSystem::new(30);
        let (overall, results) = health.aggregate(&registry).await;

        assert!(matches!(overall, OverallHealth::Healthy));
        assert_eq!(results.len(), 1);
    }

    #[tokio::test]
    async fn aggregate_mixed() {
        let registry = Arc::new(ServiceRegistry::new());
        registry.register(Arc::new(HealthyService)).unwrap();
        registry.register(Arc::new(UnhealthyService)).unwrap();

        let health = HealthSystem::new(30);
        let (overall, results) = health.aggregate(&registry).await;

        assert!(matches!(overall, OverallHealth::Degraded { .. }));
        assert_eq!(results.len(), 2);
    }

    #[tokio::test]
    async fn aggregate_all_unhealthy() {
        let registry = Arc::new(ServiceRegistry::new());
        registry.register(Arc::new(UnhealthyService)).unwrap();

        let health = HealthSystem::new(30);
        let (overall, _) = health.aggregate(&registry).await;

        assert!(matches!(overall, OverallHealth::Down));
    }

    #[tokio::test]
    async fn aggregate_empty_registry() {
        let registry = Arc::new(ServiceRegistry::new());
        let health = HealthSystem::new(30);
        let (overall, results) = health.aggregate(&registry).await;

        assert!(matches!(overall, OverallHealth::Down));
        assert!(results.is_empty());
    }

    #[test]
    fn health_status_display() {
        assert_eq!(HealthStatus::Healthy.to_string(), "healthy");
        assert_eq!(
            HealthStatus::Degraded("slow".into()).to_string(),
            "degraded: slow"
        );
        assert_eq!(
            HealthStatus::Unhealthy("crash".into()).to_string(),
            "unhealthy: crash"
        );
        assert_eq!(HealthStatus::Unknown.to_string(), "unknown");
    }

    #[test]
    fn overall_health_display() {
        assert_eq!(OverallHealth::Healthy.to_string(), "healthy");
        assert_eq!(OverallHealth::Down.to_string(), "down");
        assert_eq!(
            OverallHealth::Degraded {
                unhealthy_services: vec!["svc-a".into(), "svc-b".into()]
            }
            .to_string(),
            "degraded (svc-a, svc-b)"
        );
    }

    #[test]
    fn check_interval() {
        let health = HealthSystem::new(15);
        assert_eq!(health.check_interval_secs(), 15);
    }

    // ── K2b-G2: Probe tests (os-patterns) ────────────────────────

    #[cfg(feature = "os-patterns")]
    mod probe_tests {
        use super::super::*;

        #[test]
        fn probe_config_default() {
            let config = ProbeConfig::default();
            assert_eq!(config.liveness_interval_secs, 10);
            assert_eq!(config.readiness_interval_secs, 5);
            assert_eq!(config.failure_threshold, 3);
            assert_eq!(config.success_threshold, 1);
        }

        #[test]
        fn probe_config_serde_roundtrip() {
            let config = ProbeConfig {
                liveness_interval_secs: 15,
                readiness_interval_secs: 10,
                failure_threshold: 5,
                success_threshold: 2,
            };
            let json = serde_json::to_string(&config).unwrap();
            let restored: ProbeConfig = serde_json::from_str(&json).unwrap();
            assert_eq!(restored.liveness_interval_secs, 15);
            assert_eq!(restored.failure_threshold, 5);
        }

        #[test]
        fn probe_result_serde_roundtrip() {
            let results = vec![
                ProbeResult::Live,
                ProbeResult::NotLive { reason: "oom".into() },
                ProbeResult::Ready,
                ProbeResult::NotReady { reason: "init".into() },
            ];
            for result in results {
                let json = serde_json::to_string(&result).unwrap();
                let restored: ProbeResult = serde_json::from_str(&json).unwrap();
                assert_eq!(restored, result);
            }
        }

        #[test]
        fn probe_state_default_is_live_and_ready() {
            let state = ProbeState::default();
            assert!(state.is_live);
            assert!(state.is_ready);
            assert_eq!(state.liveness_failures, 0);
            assert_eq!(state.readiness_failures, 0);
        }

        #[test]
        fn liveness_resets_on_success() {
            let config = ProbeConfig {
                failure_threshold: 3,
                ..Default::default()
            };
            let mut state = ProbeState::default();
            state.liveness_failures = 2;

            let restart = state.record_liveness(&ProbeResult::Live, &config);
            assert!(!restart);
            assert_eq!(state.liveness_failures, 0);
            assert!(state.is_live);
        }

        #[test]
        fn liveness_triggers_restart_at_threshold() {
            let config = ProbeConfig {
                failure_threshold: 3,
                ..Default::default()
            };
            let mut state = ProbeState::default();

            // 2 failures: no restart
            assert!(!state.record_liveness(&ProbeResult::NotLive { reason: "hang".into() }, &config));
            assert!(!state.record_liveness(&ProbeResult::NotLive { reason: "hang".into() }, &config));
            assert!(state.is_live);

            // 3rd failure: restart
            assert!(state.record_liveness(&ProbeResult::NotLive { reason: "hang".into() }, &config));
            assert!(!state.is_live);
        }

        #[test]
        fn readiness_removes_at_threshold() {
            let config = ProbeConfig {
                failure_threshold: 2,
                ..Default::default()
            };
            let mut state = ProbeState::default();

            assert!(state.record_readiness(&ProbeResult::NotReady { reason: "init".into() }, &config).is_none());
            let change = state.record_readiness(&ProbeResult::NotReady { reason: "init".into() }, &config);
            assert_eq!(change, Some(false)); // should be removed
            assert!(!state.is_ready);
        }

        #[test]
        fn readiness_recovery_re_adds() {
            let config = ProbeConfig {
                failure_threshold: 1,
                success_threshold: 1,
                ..Default::default()
            };
            let mut state = ProbeState::default();

            // Make it unready
            state.record_readiness(&ProbeResult::NotReady { reason: "init".into() }, &config);
            assert!(!state.is_ready);

            // Recover
            let change = state.record_readiness(&ProbeResult::Ready, &config);
            assert_eq!(change, Some(true));
            assert!(state.is_ready);
        }

        #[test]
        fn threshold_prevents_flapping() {
            let config = ProbeConfig {
                failure_threshold: 3,
                success_threshold: 2,
                ..Default::default()
            };
            let mut state = ProbeState::default();

            // One failure shouldn't change anything
            assert!(state.record_readiness(&ProbeResult::NotReady { reason: "x".into() }, &config).is_none());
            assert!(state.is_ready);

            // One success resets failures
            assert!(state.record_readiness(&ProbeResult::Ready, &config).is_none());
            assert!(state.is_ready);
        }

        #[test]
        fn default_probe_returns_live_ready() {
            // Default liveness/readiness should return Live/Ready
            let live = ProbeResult::Live;
            let ready = ProbeResult::Ready;
            assert_eq!(live, ProbeResult::Live);
            assert_eq!(ready, ProbeResult::Ready);
        }
    }
}