From d195041491440778a9194161e1b1141fababe1bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tr=E1=BA=A7n=20Ho=C3=A0ng=20T=C3=BA?= Date: Sat, 28 Nov 2026 15:32:54 +0700 Subject: [PATCH] feat(daemon): add bounded-backoff crash recovery and daemon build docs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Trần Hoàng Tú --- README.md | 18 ++ daemon/src/engine.rs | 19 ++ daemon/src/lib.rs | 2 + daemon/src/lifecycle/backoff.rs | 267 +++++++++++++++++++++++++++++ daemon/src/lifecycle/mod.rs | 166 +++++++++++++++++- daemon/src/lifecycle/project.rs | 44 +++-- daemon/src/lifecycle/reconciler.rs | 112 ++++++++++-- daemon/src/lifecycle/state.rs | 38 +++- daemon/src/lifecycle/tests.rs | 259 +++++++++++++++++++++++++++- daemon/src/main.rs | 2 + 10 files changed, 879 insertions(+), 48 deletions(-) create mode 100644 daemon/src/lifecycle/backoff.rs diff --git a/README.md b/README.md index b574ce8f0..5e6623762 100644 --- a/README.md +++ b/README.md @@ -190,9 +190,27 @@ hanzo-chain: --rpc and --mesh cannot be one address --help print this text, and exit ``` +## Daemon (`hanzod`) + +`hanzod` (`daemon/`) is the local machine daemon exposing HTTP (`127.0.0.1:3690`) and ZAP-HTTP Unix socket routes (`/healthz`, `/v1/hanzod`, `/v1/lifecycle`, `/v1/engine`, `/v1/chain`). + +### Build Prerequisites + +- Rust 1.85+ (`cargo`, `rustc`) +- C/C++ compiler toolchain + `cmake` (`aws-lc-rs` and bundled `rusqlite`) +- On Windows (`x86_64-pc-windows-msvc`): `nasm` (when building `aws-lc-rs` assembly targets) + +```bash +cargo build --locked -p hanzod +./target/debug/hanzod --version +``` + +The lifecycle supervisor (`POST /v1/lifecycle/reconcile` and the background 1s tick) monitors managed workloads and reconciles unexpected child exits back to desired state using bounded exponential backoff (`1s` initial, `30s` cap, `60s` healthy reset). + ## Test ``` +cargo test --locked -p hanzod -p steward -p zaphttp cargo test --release ``` diff --git a/daemon/src/engine.rs b/daemon/src/engine.rs index 00079647a..939bc2cbd 100644 --- a/daemon/src/engine.rs +++ b/daemon/src/engine.rs @@ -46,6 +46,25 @@ impl Engine { pub fn port(&self) -> Option { *self.port.lock().unwrap() } + + /// Verify whether the managed child process is still alive and clear stale port state on exit. + pub async fn refresh_liveness(&self) -> Option { + let exited = { + let mut slot = self.child.lock().await; + match slot.as_mut().map(|c| c.try_wait()) { + Some(Ok(None)) => false, + Some(_) => { + *slot = None; + true + } + None => false, + } + }; + if exited { + *self.port.lock().unwrap() = None; + } + self.port() + } } fn config() -> serde_json::Value { diff --git a/daemon/src/lib.rs b/daemon/src/lib.rs index bd0655360..f5fbfbaf6 100644 --- a/daemon/src/lib.rs +++ b/daemon/src/lib.rs @@ -149,6 +149,7 @@ pub extern "C" fn hanzod_ffi_start(data_dir: *const c_char, port: u16) -> c_int dev_sub.clone(), ledger.clone(), )); + let supervisor = lifecycle_sub.spawn_supervisor(std::time::Duration::from_secs(1)); let tasks_worker = tasks_worker::TasksWorker::new( dev_sub.clone(), research_sub.clone(), @@ -232,6 +233,7 @@ pub extern "C" fn hanzod_ffi_start(data_dir: *const c_char, port: u16) -> c_int if let Some(tr) = target_runner { tr.shutdown(); } + supervisor.shutdown(); tasks_worker.shutdown(); table.stop_all().await; let _ = std::fs::remove_file(paths::socket()); diff --git a/daemon/src/lifecycle/backoff.rs b/daemon/src/lifecycle/backoff.rs new file mode 100644 index 000000000..819ce03f2 --- /dev/null +++ b/daemon/src/lifecycle/backoff.rs @@ -0,0 +1,267 @@ +// Copyright (C) 2026, Hanzo AI, Inc. All rights reserved. +// SPDX-License-Identifier: BSD-3-Clause-Eco + +//! Crash backoff tracker and periodic desired-state recovery pass. + +use super::reconciler::Reconciler; +use super::state::{default_service_endpoint, now_unix, BackoffPolicy, PLATFORM_SERVICES}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +use std::sync::Mutex as StdMutex; +use std::time::Instant; + +#[derive(Debug, Clone)] +struct BackoffEntry { + failures: u32, + next_retry_at: Instant, + armed_for_crash: bool, + last_recovered_at: Option, +} + +impl Default for BackoffEntry { + fn default() -> Self { + Self { + failures: 0, + next_retry_at: Instant::now(), + armed_for_crash: false, + last_recovered_at: None, + } + } +} + +pub(super) struct BackoffTracker { + policy: BackoffPolicy, + entries: StdMutex>, +} + +impl BackoffTracker { + pub(super) fn new(policy: BackoffPolicy) -> Self { + Self { + policy, + entries: StdMutex::new(BTreeMap::new()), + } + } + + pub(super) fn clear_key(&self, key: &str) { + self.entries.lock().unwrap().remove(key); + } + + pub(super) fn clear_all(&self) { + self.entries.lock().unwrap().clear(); + } + + pub(super) fn reset_if_healthy(&self, key: &str, actual_running: bool, now: Instant) { + if !actual_running { + return; + } + let mut guard = self.entries.lock().unwrap(); + if let Some(entry) = guard.get_mut(key) { + entry.armed_for_crash = false; + if let Some(recovered_at) = entry.last_recovered_at { + if now.saturating_duration_since(recovered_at) >= self.policy.reset_after { + entry.failures = 0; + entry.last_recovered_at = None; + } + } + } + } + + pub(super) fn gate(&self, key: &str, now: Instant) -> Option { + let mut guard = self.entries.lock().unwrap(); + let entry = guard.entry(key.to_string()).or_default(); + if !entry.armed_for_crash { + if let Some(recovered_at) = entry.last_recovered_at { + if now.saturating_duration_since(recovered_at) >= self.policy.reset_after { + entry.failures = 0; + } + } + let delay = self.policy.delay_for(entry.failures); + entry.failures = entry.failures.saturating_add(1); + entry.next_retry_at = now + delay; + entry.armed_for_crash = true; + if !delay.is_zero() { + return Some(delay.as_millis().max(1) as u64); + } + } + if now < entry.next_retry_at { + let rem = entry + .next_retry_at + .saturating_duration_since(now) + .as_millis() + .max(1) as u64; + return Some(rem); + } + None + } + + pub(super) fn record_success(&self, key: &str, now: Instant) { + let mut guard = self.entries.lock().unwrap(); + let entry = guard.entry(key.to_string()).or_default(); + entry.armed_for_crash = false; + entry.last_recovered_at = Some(now); + } + + pub(super) fn record_failure(&self, key: &str, now: Instant) { + let mut guard = self.entries.lock().unwrap(); + let entry = guard.entry(key.to_string()).or_default(); + let delay = self.policy.delay_for(entry.failures); + entry.failures = entry.failures.saturating_add(1); + entry.next_retry_at = now + delay; + entry.armed_for_crash = true; + } + + pub(super) fn failures_snapshot(&self) -> BTreeMap { + self.entries + .lock() + .unwrap() + .iter() + .map(|(k, v)| (k.clone(), v.failures)) + .collect() + } +} + +impl Reconciler { + /// Observe actual runtime/platform/application health and restart crashed desired workloads + /// subject to per-target bounded exponential backoff. + pub async fn reconcile_once(&self, who: &str) -> Result { + let mut st = self.state.lock().await; + let drifted = self.sync_locked(&mut st).await; + let now = Instant::now(); + let mut mutated = drifted; + let mut recovered: Vec = Vec::new(); + let mut deferred: Vec = Vec::new(); + + self.backoff.reset_if_healthy( + "runtime", + st.runtime.desired == "running" && st.runtime.actual == "running", + now, + ); + for name in PLATFORM_SERVICES { + let healthy = st + .platform + .services + .get(name) + .is_some_and(|s| s.desired == "running" && s.actual == "running"); + self.backoff + .reset_if_healthy(&format!("service:{name}"), healthy, now); + } + for (slug, app) in &st.applications { + self.backoff.reset_if_healthy( + &format!("app:{slug}"), + app.desired == "running" && app.actual == "running", + now, + ); + } + + if st.runtime.desired == "running" + && matches!(st.runtime.actual.as_str(), "stopped" | "crashed") + { + let key = "runtime".to_string(); + if let Some(retry_in_ms) = self.backoff.gate(&key, now) { + deferred.push(json!({ "target": key, "retry_in_ms": retry_in_ms })); + } else if self.ensure_runtime_running_locked(who, &mut st).await.is_ok() { + self.backoff.record_success(&key, Instant::now()); + self.ledger.record(who, "lifecycle.reconcile.recover", &key); + recovered.push(key); + mutated = true; + } else { + self.backoff.record_failure(&key, Instant::now()); + } + } + + for name in PLATFORM_SERVICES { + let needs_recovery = st + .platform + .services + .get(name) + .is_some_and(|s| s.desired == "running" && s.actual != "running"); + if !needs_recovery { + continue; + } + let key = format!("service:{name}"); + if let Some(retry_in_ms) = self.backoff.gate(&key, now) { + deferred.push(json!({ "target": key, "retry_in_ms": retry_in_ms })); + continue; + } + match self + .executor + .reconcile_service(name, "running", true, &st.runtime, &st.platform) + .await + { + Ok((actual, endpoint)) => { + let ok = actual == "running"; + if let Some(svc) = st.platform.services.get_mut(name) { + svc.actual = actual; + svc.endpoint = ok + .then(|| endpoint.or_else(|| default_service_endpoint(name))) + .flatten(); + } + if ok { + self.backoff.record_success(&key, Instant::now()); + self.ledger.record(who, "lifecycle.reconcile.recover", &key); + recovered.push(key); + mutated = true; + } else { + self.backoff.record_failure(&key, Instant::now()); + } + } + Err(_) => { + self.backoff.record_failure(&key, Instant::now()); + } + } + } + + let app_slugs: Vec = st.applications.keys().cloned().collect(); + for slug in app_slugs { + let Some(app_clone) = st.applications.get(&slug).cloned() else { + continue; + }; + if app_clone.desired != "running" || app_clone.actual == "running" { + continue; + } + let key = format!("app:{slug}"); + if let Some(retry_in_ms) = self.backoff.gate(&key, now) { + deferred.push(json!({ "target": key, "retry_in_ms": retry_in_ms })); + continue; + } + match self.executor.reconcile_app(&app_clone, "running").await { + Ok(out) => { + let ok = out.actual == "running"; + if let Some(app) = st.applications.get_mut(&slug) { + app.actual = out.actual; + app.pid = out.pid; + app.updated_at = now_unix(); + if ok { + app.restart_count = app.restart_count.saturating_add(1); + } + } + if ok { + self.backoff.record_success(&key, Instant::now()); + self.ledger.record(who, "lifecycle.reconcile.recover", &key); + recovered.push(key); + mutated = true; + } else { + self.backoff.record_failure(&key, Instant::now()); + } + } + Err(_) => { + self.backoff.record_failure(&key, Instant::now()); + } + } + } + + if mutated { + self.store + .save(&mut st) + .map_err(|e| (500, format!("persist reconcile state: {e}")))?; + } + + let failures = self.backoff.failures_snapshot(); + Ok(json!({ + "ok": true, + "recovered": recovered, + "deferred": deferred, + "failures": failures, + })) + } +} diff --git a/daemon/src/lifecycle/mod.rs b/daemon/src/lifecycle/mod.rs index 980789f0c..a78156503 100644 --- a/daemon/src/lifecycle/mod.rs +++ b/daemon/src/lifecycle/mod.rs @@ -8,6 +8,7 @@ //! 2. Platform (`Hanzo Cloud` — OSS Cloud, IAM, Engine, Datastore, Analytics, Insights, Storage, Commerce, Search) //! 3. Workloads / Applications (`hanzo-app-` multi-project isolation + Sandboxes + Dev) +mod backoff; pub mod project; pub mod reconciler; pub mod state; @@ -23,8 +24,9 @@ use crate::proc; use crate::table::{Fut, Reply, Subsystem}; use crate::zap::{Request, Response}; use reconciler::{ - AppActionReq, AppExecOutcome, BootOutcome, EnvironmentActionReq, LifecycleExecutor, - Observation, Reconciler, ResetReq, RuntimeActionReq, SandboxActionReq, ServiceActionReq, + AppActionReq, AppExecOutcome, AppProcessObs, BootOutcome, EnvironmentActionReq, + LifecycleExecutor, Observation, Reconciler, ResetReq, RuntimeActionReq, SandboxActionReq, + ServiceActionReq, }; use serde::de::DeserializeOwned; use serde_json::json; @@ -36,6 +38,7 @@ use std::collections::BTreeMap; use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::process::Stdio; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::time::Duration; use tokio::process::Child; @@ -48,6 +51,7 @@ pub struct SystemExecutor { dev: Arc, paths: StorePaths, app_children: Mutex>, + engine_was_alive: AtomicBool, } impl SystemExecutor { @@ -65,9 +69,22 @@ impl SystemExecutor { dev, paths, app_children: Mutex::new(BTreeMap::new()), + engine_was_alive: AtomicBool::new(false), }) } + #[cfg(test)] + pub async fn kill_app_child(&self, slug: &str) -> bool { + let mut children = self.app_children.lock().await; + if let Some(child) = children.get_mut(slug) { + let _ = child.start_kill(); + let _ = tokio::time::timeout(Duration::from_secs(2), child.wait()).await; + true + } else { + false + } + } + fn find_host_bin(name: &str) -> Option { if let Some(p) = proc::find(name) { return Some(p); @@ -142,7 +159,7 @@ impl SystemExecutor { } impl LifecycleExecutor for SystemExecutor { - fn observe<'a>(&'a self, _state: &'a LifecycleState) -> Fut<'a, Observation> { + fn observe<'a>(&'a self, state: &'a LifecycleState) -> Fut<'a, Observation> { Box::pin(async move { let ext = self.paths.inspect_external(); let runtime_running = if ext.vm_alive @@ -179,9 +196,13 @@ impl LifecycleExecutor for SystemExecutor { None => (None, None), }; - let eng_port = self.engine.port(); + let eng_port = self.engine.refresh_liveness().await; let (engine_running, engine_endpoint) = match eng_port { - Some(p) => (Some(true), Some(format!("http://127.0.0.1:{p}/v1"))), + Some(p) => { + self.engine_was_alive.store(true, Ordering::SeqCst); + (Some(true), Some(format!("http://127.0.0.1:{p}/v1"))) + } + None if self.engine_was_alive.swap(false, Ordering::SeqCst) => (Some(false), None), None => (None, None), }; @@ -201,6 +222,59 @@ impl LifecycleExecutor for SystemExecutor { ) }; + let mut app_processes = BTreeMap::new(); + let mut exited_logs: Vec<(String, String)> = Vec::new(); + { + let mut children = self.app_children.lock().await; + let slugs: Vec = children.keys().cloned().collect(); + for slug in slugs { + let outcome = match children.get_mut(&slug).map(|c| c.try_wait()) { + Some(Ok(None)) => { + let pid = children.get(&slug).and_then(|c| c.id()); + app_processes.insert( + slug.clone(), + AppProcessObs { alive: true, pid, exit_reason: None }, + ); + None + } + Some(Ok(Some(status))) => Some(status.to_string()), + Some(Err(e)) => Some(e.to_string()), + None => None, + }; + if let Some(reason) = outcome { + children.remove(&slug); + exited_logs.push((slug.clone(), reason.clone())); + app_processes.insert( + slug, + AppProcessObs { + alive: false, + pid: None, + exit_reason: Some(reason), + }, + ); + } + } + } + for (slug, reason) in exited_logs { + self.append_app_log(&slug, &format!("managed child exited unexpectedly: {reason}")); + } + for (slug, app) in &state.applications { + if !app.command.is_empty() + && app.desired == "running" + && app.actual == "running" + && !app_processes.contains_key(slug) + { + app_processes.insert( + slug.clone(), + AppProcessObs { + alive: false, + pid: None, + exit_reason: Some("managed process handle missing".to_string()), + }, + ); + } + } + Observation { runtime_running, components, @@ -210,6 +284,7 @@ impl LifecycleExecutor for SystemExecutor { engine_endpoint, dev_status, dev_detail, + app_processes, } }) } @@ -493,6 +568,56 @@ impl LifecycleExecutor for SystemExecutor { }); } + if let Some((bin, rest)) = app.command.split_first() { + let mut children = self.app_children.lock().await; + if let Some(existing) = children.get_mut(&app.slug) { + if matches!(existing.try_wait(), Ok(None)) { + return Ok(AppExecOutcome { + actual: "running".to_string(), + pid: existing.id(), + }); + } + children.remove(&app.slug); + } + + let _ = std::fs::create_dir_all(&self.paths.logs_dir); + let log_path = self.paths.logs_dir.join(format!("{}.log", app.slug)); + let (stdout_cfg, stderr_cfg) = match std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&log_path) + { + Ok(out) => match out.try_clone() { + Ok(err) => (Stdio::from(out), Stdio::from(err)), + Err(_) => (Stdio::from(out), Stdio::null()), + }, + Err(_) => (Stdio::null(), Stdio::null()), + }; + + let mut cmd = proc::bg_tokio_cmd(bin); + cmd.args(rest) + .stdin(Stdio::null()) + .stdout(stdout_cfg) + .stderr(stderr_cfg) + .kill_on_drop(true); + if Path::new(&app.project_dir).is_dir() { + cmd.current_dir(&app.project_dir); + } + let child = cmd.spawn()?; + let pid = child.id(); + children.insert(app.slug.clone(), child); + drop(children); + + self.append_app_log( + &app.slug, + &format!("started managed child {} (pid={pid:?})", bin), + ); + return Ok(AppExecOutcome { + actual: "running".to_string(), + pid, + }); + } + let _ = self .kubectl_if_ready(&["create", "namespace", &app.namespace]) .await; @@ -570,6 +695,20 @@ impl LifecycleExecutor for SystemExecutor { } } +pub struct SupervisorGuard(tokio::task::JoinHandle<()>); + +impl SupervisorGuard { + pub fn shutdown(self) { + self.0.abort(); + } +} + +impl Drop for SupervisorGuard { + fn drop(&mut self) { + self.0.abort(); + } +} + pub struct Lifecycle { pub reconciler: Arc, } @@ -590,6 +729,20 @@ impl Lifecycle { } } + pub fn spawn_supervisor(&self, interval: Duration) -> SupervisorGuard { + let reconciler = self.reconciler.clone(); + let handle = tokio::spawn(async move { + let mut ticker = tokio::time::interval(interval); + ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + ticker.tick().await; + loop { + ticker.tick().await; + let _ = reconciler.reconcile_once("system/supervisor").await; + } + }); + SupervisorGuard(handle) + } + #[cfg(test)] pub fn with_reconciler(reconciler: Arc) -> Self { Self { reconciler } @@ -673,9 +826,10 @@ impl Lifecycle { Err(resp) => resp, } } + ("POST", "reconcile") => into_response(self.reconciler.reconcile_once(who).await), _ => Response::error( 404, - "use GET /v1/lifecycle/{status,ps,doctor} or POST /v1/lifecycle/{runtime,environment,service,app,sandbox,reset}", + "use GET /v1/lifecycle/{status,ps,doctor} or POST /v1/lifecycle/{runtime,environment,service,app,sandbox,reset,reconcile}", ), } } diff --git a/daemon/src/lifecycle/project.rs b/daemon/src/lifecycle/project.rs index 8e5443c22..e6677b7b5 100644 --- a/daemon/src/lifecycle/project.rs +++ b/daemon/src/lifecycle/project.rs @@ -26,6 +26,7 @@ pub struct DiscoveredApp { pub namespace: String, pub manifest_kind: String, pub preferred_port: Option, + pub command: Vec, } impl DiscoveredApp { @@ -108,16 +109,15 @@ pub fn discover_project(dir: &Path) -> Option { .and_then(|n| n.to_str()) .unwrap_or("app"); - let (manifest_kind, raw_slug, raw_display, preferred_port) = + let (manifest_kind, raw_slug, raw_display, preferred_port, command) = if canon.join("hanzo.toml").is_file() { - let (s, n, p) = inspect_hanzo_toml(&canon.join("hanzo.toml")); - ("hanzo.toml", s, n, p) + inspect_hanzo_toml(&canon.join("hanzo.toml")) } else if canon.join("hanzo.yaml").is_file() { let (s, n, p) = inspect_yaml_like(&canon.join("hanzo.yaml")); - ("hanzo.yaml", s, n, p) + ("hanzo.yaml", s, n, p, Vec::new()) } else if canon.join("hanzo.yml").is_file() { let (s, n, p) = inspect_yaml_like(&canon.join("hanzo.yml")); - ("hanzo.yaml", s, n, p) + ("hanzo.yaml", s, n, p, Vec::new()) } else if let Some(cfg_path) = find_first_file( &canon, &[ @@ -128,7 +128,7 @@ pub fn discover_project(dir: &Path) -> Option { ], ) { let (s, n, p) = inspect_hanzo_config(&cfg_path); - ("hanzo.config", s, n, p) + ("hanzo.config", s, n, p, Vec::new()) } else if let Some(comp_path) = find_first_file( &canon, &[ @@ -139,19 +139,19 @@ pub fn discover_project(dir: &Path) -> Option { ], ) { let (s, n, p) = inspect_compose(&comp_path); - ("compose", s, n, p) + ("compose", s, n, p, Vec::new()) } else if let Some(df_path) = find_first_file(&canon, &["Dockerfile", "Containerfile"]) { let p = inspect_dockerfile_port(&df_path); - ("dockerfile", None, None, p) + ("dockerfile", None, None, p, Vec::new()) } else if canon.join("package.json").is_file() { let (s, n, p) = inspect_package_json(&canon.join("package.json")); - ("node", s, n, p) + ("node", s, n, p, Vec::new()) } else if canon.join("Cargo.toml").is_file() { let (s, p) = inspect_cargo_toml(&canon.join("Cargo.toml")); - ("rust", s, None, p) + ("rust", s, None, p, Vec::new()) } else if canon.join("go.mod").is_file() { let s = inspect_go_mod(&canon.join("go.mod")); - ("go", s, None, None) + ("go", s, None, None, Vec::new()) } else { return None; }; @@ -177,6 +177,7 @@ pub fn discover_project(dir: &Path) -> Option { namespace, manifest_kind: manifest_kind.to_string(), preferred_port, + command, })) } @@ -332,12 +333,14 @@ pub fn find_app_by_dir(apps: &BTreeMap, dir: &Path) -> Option< None } -fn inspect_hanzo_toml(path: &Path) -> (Option, Option, Option) { +fn inspect_hanzo_toml( + path: &Path, +) -> (&'static str, Option, Option, Option, Vec) { let Ok(raw) = std::fs::read_to_string(path) else { - return (None, None, None); + return ("hanzo.toml", None, None, None, Vec::new()); }; let Ok(tbl) = raw.parse::() else { - return (None, None, None); + return ("hanzo.toml", None, None, None, Vec::new()); }; let section = tbl.get("project").or_else(|| tbl.get("app")); let slug = section @@ -356,7 +359,18 @@ fn inspect_hanzo_toml(path: &Path) -> (Option, Option, Option>() + }) + .unwrap_or_default(); + ("hanzo.toml", slug.or_else(|| name.clone()), name, port, command) } fn inspect_yaml_like(path: &Path) -> (Option, Option, Option) { diff --git a/daemon/src/lifecycle/reconciler.rs b/daemon/src/lifecycle/reconciler.rs index e10921c66..9064ca390 100644 --- a/daemon/src/lifecycle/reconciler.rs +++ b/daemon/src/lifecycle/reconciler.rs @@ -3,6 +3,7 @@ //! Desired-state reconciler and 3-layer lifecycle state machine. +use super::backoff::BackoffTracker; use super::project::{ canonical_dir, discover_project, find_app_by_dir, resolve_app_slug, DetectedRepo, DiscoveredApp, }; @@ -12,9 +13,9 @@ pub use super::state::{ }; use super::state::{ build_doctor_checks, build_ps_rows, canonical_service_name, default_service_endpoint, - effective_cloud_image, format_ps_table, now_unix, AppState, CachePreservation, LifecycleState, - PlatformState, RuntimeComponents, RuntimeState, SandboxState, StateStore, StorePaths, - DEFAULT_SANDBOX_IMAGE, PLATFORM_SERVICES, + effective_cloud_image, format_ps_table, now_unix, AppState, BackoffPolicy, CachePreservation, + LifecycleState, PlatformState, RuntimeComponents, RuntimeState, SandboxState, StateStore, + StorePaths, DEFAULT_SANDBOX_IMAGE, PLATFORM_SERVICES, }; use crate::ledger::Ledger; use crate::table::Fut; @@ -25,6 +26,13 @@ use std::path::Path; use std::sync::Arc; use tokio::sync::Mutex; +#[derive(Debug, Clone, Default)] +pub struct AppProcessObs { + pub alive: bool, + pub pid: Option, + pub exit_reason: Option, +} + #[derive(Debug, Clone, Default)] pub struct Observation { pub runtime_running: Option, @@ -35,6 +43,7 @@ pub struct Observation { pub engine_endpoint: Option, pub dev_status: &'static str, pub dev_detail: Option, + pub app_processes: BTreeMap, } #[derive(Debug, Clone)] @@ -91,18 +100,35 @@ pub trait LifecycleExecutor: Send + Sync { pub struct Reconciler { pub store: StateStore, - state: Mutex, - executor: Arc, - ledger: Arc, + pub(super) state: Mutex, + pub(super) executor: Arc, + pub(super) ledger: Arc, + pub(super) backoff: BackoffTracker, } impl Reconciler { pub fn new(store: StateStore, executor: Arc, ledger: Arc) -> Self { + Self::with_backoff(store, executor, ledger, BackoffPolicy::default()) + } + + pub fn with_backoff( + store: StateStore, + executor: Arc, + ledger: Arc, + policy: BackoffPolicy, + ) -> Self { let initial = store.load(); - Self { store, state: Mutex::new(initial), executor, ledger } + Self { + store, + state: Mutex::new(initial), + executor, + ledger, + backoff: BackoffTracker::new(policy), + } } - async fn sync_locked(&self, st: &mut LifecycleState) { + pub(super) async fn sync_locked(&self, st: &mut LifecycleState) -> bool { + let mut drifted = false; let ext = self.store.paths.inspect_external(); let obs = self.executor.observe(st).await; @@ -126,7 +152,10 @@ impl Reconciler { } else if let Some(running) = obs.runtime_running { if running { st.runtime.actual = "running".to_string(); - } else if st.runtime.desired == "stopped" { + } else { + if st.runtime.actual != "stopped" { + drifted = true; + } st.runtime.actual = "stopped".to_string(); } if let Some(comp) = obs.components { @@ -134,25 +163,56 @@ impl Reconciler { } } - if obs.cloud_running == Some(true) { + if let Some(cloud_up) = obs.cloud_running { if let Some(svc) = st.platform.services.get_mut("cloud") { - svc.actual = "running".to_string(); - if obs.cloud_endpoint.is_some() { - svc.endpoint = obs.cloud_endpoint; + if cloud_up { + svc.actual = "running".to_string(); + if obs.cloud_endpoint.is_some() { + svc.endpoint = obs.cloud_endpoint; + } + } else if svc.actual == "running" { + svc.actual = "stopped".to_string(); + svc.endpoint = None; + drifted = true; } } } - if obs.engine_running == Some(true) { + if let Some(eng_up) = obs.engine_running { if let Some(svc) = st.platform.services.get_mut("engine") { - svc.actual = "running".to_string(); - if obs.engine_endpoint.is_some() { - svc.endpoint = obs.engine_endpoint; + if eng_up { + svc.actual = "running".to_string(); + if obs.engine_endpoint.is_some() { + svc.endpoint = obs.engine_endpoint; + } + } else if svc.actual == "running" { + svc.actual = "stopped".to_string(); + svc.endpoint = None; + drifted = true; } } } + + for (slug, proc_obs) in &obs.app_processes { + if let Some(app) = st.applications.get_mut(slug) { + if proc_obs.alive { + app.pid = proc_obs.pid.or(app.pid); + if app.desired == "running" { + app.actual = "running".to_string(); + } + } else if app.actual == "running" { + app.actual = "crashed".to_string(); + app.pid = None; + app.last_exit = proc_obs.exit_reason.clone(); + app.updated_at = now_unix(); + drifted = true; + } + } + } + + drifted } - async fn ensure_runtime_running_locked( + pub(super) async fn ensure_runtime_running_locked( &self, who: &str, st: &mut LifecycleState, @@ -268,6 +328,7 @@ impl Reconciler { match req.action.trim() { "start" => { + self.backoff.clear_key("runtime"); self.ensure_runtime_running_locked(who, &mut st).await?; } "stop" => { @@ -281,6 +342,7 @@ impl Reconciler { .await .map_err(|e| (502, format!("runtime stop failed: {e}")))?; mark_all_stopped_after_drain(&mut st); + self.backoff.clear_all(); self.ledger.record(who, "lifecycle.runtime.stop", "drained-and-stopped"); } "restart" => { @@ -491,11 +553,15 @@ impl Reconciler { app.updated_at = now_unix(); } } + self.backoff.clear_key(&format!("app:{slug}")); self.ledger.record(who, "lifecycle.environment.down", &format!("project:{slug}")); } else if scope == "project" { return Err((400, "scope 'project' requires a user application project_dir".to_string())); } else { st.platform.desired = "down".to_string(); + for name in PLATFORM_SERVICES { + self.backoff.clear_key(&format!("service:{name}")); + } for svc in st.platform.services.values_mut() { svc.desired = "stopped".to_string(); } @@ -522,6 +588,7 @@ impl Reconciler { app.updated_at = now_unix(); } } + self.backoff.clear_key(&format!("app:{slug}")); } let sb_names: Vec = st.sandboxes.keys().cloned().collect(); for name in sb_names { @@ -578,6 +645,7 @@ impl Reconciler { other => return Err((400, format!("unknown service action '{other}'"))), }; + self.backoff.clear_key(&format!("service:{canon}")); if desired == "running" { self.ensure_runtime_running_locked(who, &mut st).await?; } @@ -638,9 +706,11 @@ impl Reconciler { match action { "start" => { + self.backoff.clear_key(&format!("app:{slug}")); self.ensure_runtime_running_locked(who, &mut st).await?; if let Some(app) = st.applications.get_mut(&slug) { app.desired = "running".to_string(); + app.last_exit = None; } let app_clone = st.applications.get(&slug).cloned().unwrap(); let out = self @@ -656,6 +726,7 @@ impl Reconciler { self.ledger.record(who, "lifecycle.app.start", &slug); } "stop" => { + self.backoff.clear_key(&format!("app:{slug}")); if let Some(app) = st.applications.get_mut(&slug) { app.desired = "stopped".to_string(); } @@ -802,6 +873,7 @@ impl Reconciler { fresh.caches.kube_system_preserved = false; } *st = fresh; + self.backoff.clear_all(); self.store.save(&mut st).map_err(|e| (500, format!("persist reset state: {e}")))?; self.ledger.record(who, "lifecycle.reset", if req.all { "all" } else { "state-and-runtime" }); drop(st); @@ -865,15 +937,19 @@ fn upsert_discovered_app(st: &mut LifecycleState, disc: DiscoveredApp) -> String manifest_kind: disc_with_port.manifest_kind.clone(), desired: "running".to_string(), actual: "stopped".to_string(), + command: disc_with_port.command.clone(), port: Some(port), endpoints: endpoints.clone(), pid: None, + restart_count: 0, + last_exit: None, updated_at: now_unix(), }); entry.name = disc_with_port.name; entry.project_dir = dir_str; entry.namespace = disc_with_port.namespace; entry.manifest_kind = disc_with_port.manifest_kind; + entry.command = disc_with_port.command; entry.desired = "running".to_string(); entry.port = Some(port); entry.endpoints = endpoints; diff --git a/daemon/src/lifecycle/state.rs b/daemon/src/lifecycle/state.rs index a691a1a52..50a49c769 100644 --- a/daemon/src/lifecycle/state.rs +++ b/daemon/src/lifecycle/state.rs @@ -224,6 +224,31 @@ impl PlatformState { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BackoffPolicy { + pub initial: Duration, + pub max: Duration, + pub reset_after: Duration, +} + +impl Default for BackoffPolicy { + fn default() -> Self { + Self { + initial: Duration::from_secs(1), + max: Duration::from_secs(30), + reset_after: Duration::from_secs(60), + } + } +} + +impl BackoffPolicy { + /// Bounded exponential backoff: `min(initial * 2^attempt, max)`. + pub fn delay_for(&self, attempt: u32) -> Duration { + let factor = 1u32.checked_shl(attempt.min(16)).unwrap_or(u32::MAX); + self.initial.saturating_mul(factor).min(self.max) + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct AppState { pub slug: String, @@ -233,12 +258,18 @@ pub struct AppState { pub manifest_kind: String, pub desired: String, pub actual: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub command: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub port: Option, #[serde(default)] pub endpoints: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub pid: Option, + #[serde(default)] + pub restart_count: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_exit: Option, pub updated_at: i64, } @@ -465,11 +496,16 @@ pub fn build_ps_rows(st: &LifecycleState, dev_status: &str, dev_detail: Option "Running", + "crashed" => "Crashed", + _ => "Stopped", + }; rows.push(PsRow { component: app.name.clone(), layer: "application".to_string(), desired: app.desired.clone(), - status: if app.actual == "running" { "Running" } else { "Stopped" }.to_string(), + status: status.to_string(), namespace: Some(app.namespace.clone()), endpoint: app.endpoints.first().cloned(), detail: Some(format!("slug={} kind={}", app.slug, app.manifest_kind)), diff --git a/daemon/src/lifecycle/tests.rs b/daemon/src/lifecycle/tests.rs index 47436f8c8..4b7cb9de4 100644 --- a/daemon/src/lifecycle/tests.rs +++ b/daemon/src/lifecycle/tests.rs @@ -5,17 +5,23 @@ use super::project::{discover_project, resolve_app_slug, DetectedRepo}; use super::reconciler::{ - AppActionReq, AppExecOutcome, BootOutcome, EnvironmentActionReq, LifecycleExecutor, - Observation, Reconciler, ResetReq, RuntimeActionReq, SandboxActionReq, ServiceActionReq, + AppActionReq, AppExecOutcome, AppProcessObs, BootOutcome, EnvironmentActionReq, + LifecycleExecutor, Observation, Reconciler, ResetReq, RuntimeActionReq, SandboxActionReq, + ServiceActionReq, }; use super::state::{ - default_service_endpoint, AppState, LifecycleState, PlatformState, RuntimeComponents, - RuntimeState, SandboxState, StateStore, StorePaths, DEFAULT_CLOUD_IMAGE, STRICT_CLOUD_IMAGE, + default_service_endpoint, AppState, BackoffPolicy, LifecycleState, PlatformState, + RuntimeComponents, RuntimeState, SandboxState, StateStore, StorePaths, DEFAULT_CLOUD_IMAGE, + STRICT_CLOUD_IMAGE, }; -use super::Lifecycle; +use super::{Lifecycle, SystemExecutor}; use crate::auth::Verifier; +use crate::cluster::ClusterCore; use crate::daemon::{Daemon, Via}; +use crate::dev::Dev; +use crate::engine::Engine; use crate::ledger::Ledger; +use crate::pins::Pins; use crate::table::{Fut, Reply, Table}; use crate::zap::Request; use serde_json::Value; @@ -24,6 +30,7 @@ use std::io; use std::net::TcpListener; use std::path::Path; use std::sync::{Arc, Mutex}; +use std::time::Duration; #[derive(Default)] struct MockWorld { @@ -39,6 +46,8 @@ struct MockWorld { service_starts: BTreeMap, service_in_place_reconciles: BTreeMap, running_apps: BTreeSet, + app_crashes: BTreeMap, + next_pid: u32, running_sandboxes: BTreeSet, app_logs: BTreeMap>, image_cache_warm: bool, @@ -54,6 +63,7 @@ impl MockExecutor { fn new() -> Arc { Arc::new(Self { world: Mutex::new(MockWorld { + next_pid: 42000, image_cache_warm: true, volumes_preserved: true, model_weights_preserved: true, @@ -62,6 +72,17 @@ impl MockExecutor { }) } + fn kill_app(&self, slug: &str, reason: &str) { + let mut w = self.world.lock().unwrap(); + w.running_apps.remove(slug); + w.app_crashes.insert(slug.to_string(), reason.to_string()); + } + + fn kill_service(&self, name: &str) { + let mut w = self.world.lock().unwrap(); + w.running_services.remove(name); + } + fn snapshot(&self) -> (usize, usize, usize, usize, BTreeSet, BTreeSet) { let w = self.world.lock().unwrap(); let cloud_starts = *w.service_starts.get("cloud").unwrap_or(&0); @@ -92,6 +113,23 @@ impl LifecycleExecutor for MockExecutor { fn observe<'a>(&'a self, _state: &'a LifecycleState) -> Fut<'a, Observation> { Box::pin(async move { let w = self.world.lock().unwrap(); + let mut app_processes = BTreeMap::new(); + for slug in &w.running_apps { + app_processes.insert( + slug.clone(), + AppProcessObs { alive: true, pid: Some(w.next_pid), exit_reason: None }, + ); + } + for (slug, reason) in &w.app_crashes { + app_processes.insert( + slug.clone(), + AppProcessObs { + alive: false, + pid: None, + exit_reason: Some(reason.clone()), + }, + ); + } Observation { runtime_running: Some(w.runtime_up), components: Some(if w.runtime_up { @@ -105,6 +143,7 @@ impl LifecycleExecutor for MockExecutor { engine_endpoint: w.running_services.contains("engine").then(|| "http://127.0.0.1:3690/v1/engine".to_string()), dev_status: "Ready", dev_detail: Some("native harness (hanzo-gen)".to_string()), + app_processes, } }) } @@ -204,12 +243,16 @@ impl LifecycleExecutor for MockExecutor { let mut w = self.world.lock().unwrap(); if desired == "stopped" { w.running_apps.remove(&app.slug); + w.app_crashes.remove(&app.slug); w.app_logs.entry(app.slug.clone()).or_default().push(format!("stopped {}", app.namespace)); Ok(AppExecOutcome { actual: "stopped".to_string(), pid: None }) } else { + w.next_pid += 1; + let pid = w.next_pid; w.running_apps.insert(app.slug.clone()); - w.app_logs.entry(app.slug.clone()).or_default().push(format!("started {} on {:?}", app.namespace, app.port)); - Ok(AppExecOutcome { actual: "running".to_string(), pid: Some(42000) }) + w.app_crashes.remove(&app.slug); + w.app_logs.entry(app.slug.clone()).or_default().push(format!("started {} on {:?} pid={pid}", app.namespace, app.port)); + Ok(AppExecOutcome { actual: "running".to_string(), pid: Some(pid) }) } }) } @@ -555,9 +598,209 @@ async fn service_app_prefix_sandbox_ps_doctor_reset_external_sync_and_http_probe map.insert(s.to_string(), AppState { slug: s.to_string(), name: s.to_string(), project_dir: "/tmp".into(), namespace: format!("hanzo-app-{s}"), manifest_kind: "hanzo.toml".into(), - desired: "stopped".into(), actual: "stopped".into(), port: None, endpoints: vec![], pid: None, updated_at: 0, + desired: "stopped".into(), actual: "stopped".into(), command: Vec::new(), port: None, endpoints: vec![], pid: None, restart_count: 0, last_exit: None, updated_at: 0, }); } assert!(resolve_app_slug(&map, "solar").is_err()); assert_eq!(resolve_app_slug(&map, "solar-crm").unwrap(), "solar-crm"); } + +#[tokio::test] +async fn killed_workload_reconciles_with_bounded_backoff() { + let policy = BackoffPolicy { + initial: Duration::from_millis(150), + max: Duration::from_millis(360), + reset_after: Duration::from_millis(550), + }; + assert_eq!(policy.delay_for(0), Duration::from_millis(150)); + assert_eq!(policy.delay_for(1), Duration::from_millis(300)); + assert_eq!(policy.delay_for(2), Duration::from_millis(360)); + assert_eq!(policy.delay_for(5), Duration::from_millis(360)); + + let tmp = tempfile::tempdir().unwrap(); + let paths = StorePaths::for_root(tmp.path(), dead_probe_port()); + let exec = MockExecutor::new(); + let ledger = Arc::new(Ledger::open(tmp.path().join("ledger"))); + let rec = Arc::new(Reconciler::with_backoff( + StateStore::new(paths), + exec.clone(), + ledger, + policy, + )); + + let solar_dir = create_app_repo( + tmp.path(), + "solar-crm", + "hanzo.toml", + "[project]\nname = \"Solar CRM\"\nslug = \"solar-crm\"\n", + ); + let started = rec + .environment_action( + "hanzo/z", + EnvironmentActionReq { + action: "up".into(), + project_dir: Some(solar_dir), + ..Default::default() + }, + ) + .await + .unwrap(); + let pid0 = started["workloads"]["applications"]["solar-crm"]["pid"].as_u64(); + assert!(pid0.is_some()); + + // Simulate unexpected app process crash (`desired == "running"`, child gone) + exec.kill_app("solar-crm", "SIGKILL (9)"); + let r1 = rec.reconcile_once("supervisor").await.unwrap(); + assert!(r1["recovered"].as_array().unwrap().is_empty()); + assert_eq!(r1["deferred"].as_array().unwrap()[0]["target"], "app:solar-crm"); + assert_eq!(r1["failures"]["app:solar-crm"], 1); + + // Still inside `initial` (150ms) backoff window -> restart stays deferred + tokio::time::sleep(Duration::from_millis(15)).await; + let r2 = rec.reconcile_once("supervisor").await.unwrap(); + assert!(r2["recovered"].as_array().unwrap().is_empty()); + + let st_crashed = rec.status_json().await; + assert_eq!(st_crashed["workloads"]["applications"]["solar-crm"]["actual"], "crashed"); + assert_eq!(st_crashed["workloads"]["applications"]["solar-crm"]["last_exit"], "SIGKILL (9)"); + let doc = rec.doctor_json().await; + assert_eq!(doc["drift_detected"], true); + let ps = rec.ps_json().await; + assert_eq!( + ps["rows"].as_array().unwrap().iter().find(|r| r["component"] == "Solar CRM").unwrap()["status"], + "Crashed" + ); + + // Past 150ms backoff window -> app reconciles back to running with new PID + tokio::time::sleep(Duration::from_millis(165)).await; + let r3 = rec.reconcile_once("supervisor").await.unwrap(); + assert_eq!(r3["recovered"], serde_json::json!(["app:solar-crm"])); + let st_rec1 = rec.status_json().await; + assert_eq!(st_rec1["workloads"]["applications"]["solar-crm"]["actual"], "running"); + assert_eq!(st_rec1["workloads"]["applications"]["solar-crm"]["restart_count"], 1); + let pid1 = st_rec1["workloads"]["applications"]["solar-crm"]["pid"].as_u64(); + assert!(pid1.is_some() && pid1 != pid0); + + // Second crash doubles backoff to 300ms + exec.kill_app("solar-crm", "exit code 137"); + let r4 = rec.reconcile_once("supervisor").await.unwrap(); + assert_eq!(r4["failures"]["app:solar-crm"], 2); + tokio::time::sleep(Duration::from_millis(20)).await; + let r5 = rec.reconcile_once("supervisor").await.unwrap(); + assert!(r5["recovered"].as_array().unwrap().is_empty()); + tokio::time::sleep(Duration::from_millis(300)).await; + let r6 = rec.reconcile_once("supervisor").await.unwrap(); + assert_eq!(r6["recovered"], serde_json::json!(["app:solar-crm"])); + + // Repeated crashes cap strictly at `max = 360ms` + for expected_failures in 3u32..=4u32 { + exec.kill_app("solar-crm", "SIGTERM"); + let arm = rec.reconcile_once("supervisor").await.unwrap(); + assert_eq!(arm["failures"]["app:solar-crm"], expected_failures); + let retry_ms = arm["deferred"][0]["retry_in_ms"].as_u64().unwrap(); + assert!(retry_ms <= 360, "backoff exceeded cap: {retry_ms}ms"); + tokio::time::sleep(Duration::from_millis(380)).await; + let rec_done = rec.reconcile_once("supervisor").await.unwrap(); + assert_eq!(rec_done["recovered"], serde_json::json!(["app:solar-crm"])); + } + + // Remaining healthy >= `reset_after` (550ms) resets consecutive failure count back to 0 + tokio::time::sleep(Duration::from_millis(580)).await; + let after_reset = rec.reconcile_once("supervisor").await.unwrap(); + assert_eq!(after_reset["failures"]["app:solar-crm"], 0); + + // Also verify killed platform service recovers via HTTP/Socket `POST /v1/lifecycle/reconcile` + exec.kill_service("cloud"); + let sub: Arc = Arc::new(Lifecycle::with_reconciler(rec.clone())); + let daemon = Daemon { table: Arc::new(Table::new(vec![sub])), verifier: Arc::new(Verifier::new("https://hanzo.ai".into())) }; + let _ = daemon.handle(Via::Socket, Request { method: "POST".into(), target: "/v1/lifecycle/reconcile".into(), headers: vec![], body: vec![] }).await; + tokio::time::sleep(Duration::from_millis(175)).await; + let (reply, _) = daemon.handle(Via::Socket, Request { method: "POST".into(), target: "/v1/lifecycle/reconcile".into(), headers: vec![], body: vec![] }).await; + match reply { + Reply::Whole(resp) => { + assert_eq!(resp.status, 200); + let v: Value = serde_json::from_slice(&resp.body).unwrap(); + assert!(v["recovered"].as_array().unwrap().iter().any(|x| x == "service:cloud")); + } + _ => panic!("expected whole reply from POST /v1/lifecycle/reconcile"), + } + + // Explicit stop clears desired state so reconcile does NOT restart intentionally stopped workloads + rec.app_action("hanzo/z", AppActionReq { action: "stop".into(), name: Some("solar-crm".into()), ..Default::default() }).await.unwrap(); + let idle = rec.reconcile_once("supervisor").await.unwrap(); + assert!(idle["recovered"].as_array().unwrap().is_empty()); + let final_st = rec.status_json().await; + assert_eq!(final_st["workloads"]["applications"]["solar-crm"]["actual"], "stopped"); +} + +#[tokio::test] +async fn system_executor_recovers_killed_os_child_process() { + let tmp = tempfile::tempdir().unwrap(); + let paths = StorePaths::for_root(tmp.path(), dead_probe_port()); + let ledger = Arc::new(Ledger::open(tmp.path().join("ledger"))); + let pins = Arc::new(Pins::load(&tmp.path().join("pins.json"))); + let upstream: crate::cloud::Upstream = Arc::new(Mutex::new(None)); + let engine = Arc::new(Engine::new(pins)); + let cluster = ClusterCore::new(ledger.clone(), upstream.clone()); + let dev = Arc::new(Dev::new(ledger.clone(), Some(engine.clone()))); + let sys_exec = SystemExecutor::new(cluster, engine, upstream, dev, paths.clone()); + + let policy = BackoffPolicy { + initial: Duration::from_millis(80), + max: Duration::from_millis(240), + reset_after: Duration::from_secs(5), + }; + let rec = Arc::new(Reconciler::with_backoff( + StateStore::new(paths.clone()), + sys_exec.clone(), + ledger, + policy, + )); + + let cmd_toml = if cfg!(target_os = "windows") { + "[project]\nname = \"Sleeper App\"\nslug = \"sleeper-app\"\ncommand = [\"cmd.exe\", \"/C\", \"ping\", \"-n\", \"30\", \"127.0.0.1\"]\n" + } else { + "[project]\nname = \"Sleeper App\"\nslug = \"sleeper-app\"\ncommand = [\"sh\", \"-c\", \"sleep 30\"]\n" + }; + let app_dir = create_app_repo(tmp.path(), "sleeper-app", "hanzo.toml", cmd_toml); + + let started = rec + .app_action( + "hanzo/z", + AppActionReq { action: "start".into(), project_dir: Some(app_dir), ..Default::default() }, + ) + .await + .unwrap(); + let pid1 = started["application"]["pid"].as_u64().expect("OS child PID"); + assert_eq!(started["application"]["actual"], "running"); + + // Kill the real OS child process unexpectedly + assert!(sys_exec.kill_app_child("sleeper-app").await); + + // First reconcile observes exit, marks crashed, and arms bounded backoff + let arm = rec.reconcile_once("supervisor").await.unwrap(); + assert_eq!(arm["deferred"].as_array().unwrap()[0]["target"], "app:sleeper-app"); + let crashed = rec.status_json().await; + assert_eq!(crashed["workloads"]["applications"]["sleeper-app"]["actual"], "crashed"); + assert!(crashed["workloads"]["applications"]["sleeper-app"]["pid"].is_null()); + + // After backoff expires, real OS child respawns under a fresh PID + tokio::time::sleep(Duration::from_millis(115)).await; + let recovered = rec.reconcile_once("supervisor").await.unwrap(); + assert_eq!(recovered["recovered"], serde_json::json!(["app:sleeper-app"])); + let post = rec.status_json().await; + let pid2 = post["workloads"]["applications"]["sleeper-app"]["pid"].as_u64().expect("respawned OS child PID"); + assert_ne!(pid1, pid2); + assert_eq!(post["workloads"]["applications"]["sleeper-app"]["restart_count"], 1); + assert_eq!(post["workloads"]["applications"]["sleeper-app"]["actual"], "running"); + + let logs = rec + .app_action("hanzo/z", AppActionReq { action: "logs".into(), name: Some("sleeper-app".into()), tail: Some(20), ..Default::default() }) + .await + .unwrap(); + let log_lines: Vec<&str> = logs["logs"].as_array().unwrap().iter().filter_map(|v| v.as_str()).collect(); + assert!(log_lines.iter().any(|l| l.contains("exited unexpectedly"))); + + // Cleanly terminate respawned child process + rec.app_action("hanzo/z", AppActionReq { action: "stop".into(), name: Some("sleeper-app".into()), ..Default::default() }).await.unwrap(); +} diff --git a/daemon/src/main.rs b/daemon/src/main.rs index 56c788521..0a7f2f828 100644 --- a/daemon/src/main.rs +++ b/daemon/src/main.rs @@ -199,6 +199,7 @@ async fn run() -> std::io::Result<()> { dev_sub.clone(), ledger.clone(), )); + let supervisor = lifecycle_sub.spawn_supervisor(std::time::Duration::from_secs(1)); let tasks_worker = tasks_worker::TasksWorker::new( dev_sub.clone(), research_sub.clone(), @@ -304,6 +305,7 @@ async fn run() -> std::io::Result<()> { if let Some(tr) = target_runner { tr.shutdown(); } + supervisor.shutdown(); tasks_worker.shutdown(); table.stop_all().await; let _ = std::fs::remove_file(paths::socket());