diff --git a/.crumb b/.crumb index 00637f5f..f6ca8755 100644 --- a/.crumb +++ b/.crumb @@ -65,68 +65,68 @@ "children": [ { "digest": "4e7f370019e67f6c71565d1544530851eb1b3b1bed61c2712f4ac7d9614a89bf", - "last_commit": "9de5838", + "last_commit": "6bbe2ec", "name": "crates/aien-allen", "purpose": "ALLEN identity gate: resolve-only subject check, host pin record, deployment record (ADR 0035). " }, { "digest": "40a231c50dba92af7de2527ab33879c5d1eaaa6e7ea5d6a5ebaa9d60c7542075", - "last_commit": "9de5838", + "last_commit": "b9b52f9", "name": "crates/aien-allen-memory", "purpose": "ALLEN scoped memory store: scopes enforced at recall, inspect/correct/export, key-destroying for" }, { "digest": "44dc482b8c9db8919a68ec69b019cd77967232a6ec8b1910c0dfe3cd4d71f141", - "last_commit": "9de5838", + "last_commit": "b9b52f9", "name": "crates/aien-allen-profile", "purpose": "ALLEN persona profile v1: versioned, user-editable profile bound to the engaged ALLEN identity; " }, { "digest": "a465a3baa617027d8691348299a41c84173db5c04339c611a861275e78fa926f", - "last_commit": "9de5838", + "last_commit": "e10a8b5", "name": "crates/aien-cli", "purpose": "" }, { "digest": "993b935d7caf400fb82e46e89f0f5c931899405c9326c49cba08467d4ea058b7", - "last_commit": "9de5838", + "last_commit": "fa73e77", "name": "crates/aien-scheduler/src/bin", "purpose": "" }, { "digest": "4373c3bab53d983d82429e6eabe0ac65d2376e4a82f0263a562c31983bb040e9", - "last_commit": "9de5838", + "last_commit": "e10a8b5", "name": "crates/spark-cockpit-rs", "purpose": "" }, { "digest": "4696ee460c13e9a19a44104036e26407ddefd300f9d2221b4308208ba249980e", - "last_commit": "e37bed5", + "last_commit": "360b251", "name": "scripts", "purpose": "" }, { "digest": "75e439cb2ae120e1807af894b70b6454971028f5527f56451f9d6558f503c88b", - "last_commit": "9de5838", + "last_commit": "fa73e77", "name": "skills", "purpose": "" }, { "digest": "c9e1e35fbf8735db1837680b11a5c69af41decd500691470f1091f861867b4da", - "last_commit": "9de5838", + "last_commit": "076585a", "name": "tools/aien-local-ci", "purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health " } ], "children_root": "sha256:ae01b8c79c2072b524de0b6d93e85a82159dee5db6884c0b703391d262e35f26", - "compiled_at": "2026-10-15T18:17:11Z", + "compiled_at": "2026-10-15T18:57:48Z", "compiler": "crumb-compile/1", - "digest": "sha256:21593a5d69ae61291494e5f0066045c9e76c5e3e42af0283ee36cf14fb3e8ce7", + "digest": "sha256:315ffa3655495fce926f308987ad63bcdc9daaa5887b802fa079f57499f3bbef", "evidence_files": 1473, "evidence_root": "sha256:4b50c518bd48f66d380c02c38af70107336af0c384a988a43d7c3233a0e5a95c", - "files": 5427, - "generated_at_commit": "465e8eb2100280f9fc3e788f8fd9d5fe548716cc", - "source_tree": "sha256:7669f2d6cbd09a211056487e873760d989582e42c26892b79c3a62ce8f7d0cbe" + "files": 5431, + "generated_at_commit": "58d1b1666c9ee89c492127c5998e57b0dace2c66", + "source_tree": "sha256:52bf329dcf226a544975e6adb96dffcc274abc386c3f5d70875d8d0ce62e96e4" } }, "history": [], diff --git a/crates/spark-supervisor/examples/readiness_timing.rs b/crates/spark-supervisor/examples/readiness_timing.rs new file mode 100644 index 00000000..a3a24aa9 --- /dev/null +++ b/crates/spark-supervisor/examples/readiness_timing.rs @@ -0,0 +1,108 @@ +//! Measures time from supervisor start to each service being reported Ready (issue #534). +//! +//! Sample config: `bare` = `sleep 30`, no health_url; `web` = `sleep 30` with a health_url +//! served in-process that answers 503 until BOOT_MS after start, then 200 (a service that +//! needs BOOT_MS to come up). Prints one raw line per service per run. +//! +//! cargo run -p spark-supervisor --example readiness_timing -- [runs] [probe_interval_ms] + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use spark_supervisor::config::{ServiceConfig, SupervisorConfig}; +use spark_supervisor::supervisor::{ServiceState, Supervisor, SupervisorOptions}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; + +const BOOT_MS: u128 = 500; + +async fn boot_delayed_responder(t0: Instant) -> String { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/health", listener.local_addr().unwrap()); + tokio::spawn(async move { + while let Ok((mut sock, _)) = listener.accept().await { + tokio::spawn(async move { + let mut buf = [0u8; 2048]; + let _ = sock.read(&mut buf).await; + let code = if t0.elapsed().as_millis() >= BOOT_MS { + 200 + } else { + 503 + }; + let resp = + format!("HTTP/1.1 {code} X\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + let _ = sock.write_all(resp.as_bytes()).await; + }); + } + }); + url +} + +fn sleeper(health_url: Option) -> ServiceConfig { + ServiceConfig { + command: "sleep".into(), + args: vec!["30".into()], + env: HashMap::new(), + restart: "always".into(), + health_url, + } +} + +#[tokio::main] +async fn main() { + let args: Vec = std::env::args().collect(); + let runs: usize = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(3); + let mut options = SupervisorOptions::default(); + if let Some(ms) = args.get(2).and_then(|s| s.parse().ok()) { + options.probe_interval = Duration::from_millis(ms); + } + println!( + "branch run probe_interval_ms={} boot_ms={BOOT_MS}", + options.probe_interval.as_millis() + ); + + for run in 1..=runs { + let t0 = Instant::now(); + let url = boot_delayed_responder(t0).await; + let mut services = HashMap::new(); + services.insert("bare".to_string(), sleeper(None)); + services.insert("web".to_string(), sleeper(Some(url))); + let sup = Arc::new(Supervisor::with_options( + SupervisorConfig { services }, + options.clone(), + )); + let (tx, rx) = tokio::sync::oneshot::channel::<()>(); + let s = sup.clone(); + let task = tokio::spawn(async move { + s.run_until(async { + let _ = rx.await; + }) + .await + }); + + let mut spawned: HashMap = HashMap::new(); + let mut ready: HashMap = HashMap::new(); + while ready.len() < 2 && t0.elapsed() < Duration::from_secs(20) { + for (name, st) in sup.snapshot().await { + let now = t0.elapsed().as_millis(); + if st.pid.is_some() { + spawned.entry(name.clone()).or_insert(now); + } + if st.state == ServiceState::Ready { + ready.entry(name).or_insert(now); + } + } + tokio::time::sleep(Duration::from_millis(1)).await; + } + let _ = tx.send(()); + let _ = task.await; + for name in ["bare", "web"] { + println!( + "run={run} service={name} spawned_ms={:?} reported_ready_ms={:?}", + spawned.get(name), + ready.get(name) + ); + } + } +} diff --git a/crates/spark-supervisor/src/lib.rs b/crates/spark-supervisor/src/lib.rs new file mode 100644 index 00000000..abaee602 --- /dev/null +++ b/crates/spark-supervisor/src/lib.rs @@ -0,0 +1,6 @@ +//! Library target for spark-supervisor so integration tests and tools can drive the +//! supervisor in-process. The `spark-supervisor` binary is a thin CLI over it. + +pub mod config; +pub mod proc_telemetry; +pub mod supervisor; diff --git a/crates/spark-supervisor/src/main.rs b/crates/spark-supervisor/src/main.rs index 11e80b8c..7a55b34c 100644 --- a/crates/spark-supervisor/src/main.rs +++ b/crates/spark-supervisor/src/main.rs @@ -9,12 +9,15 @@ use clap::{Parser, Subcommand}; use std::path::PathBuf; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; -mod config; -mod proc_telemetry; -mod supervisor; +use spark_supervisor::config::SupervisorConfig; +use spark_supervisor::supervisor::Supervisor; -use config::SupervisorConfig; -use supervisor::Supervisor; +/// Exit code for `status`: live state is only held inside the running daemon. +const EXIT_STATUS_UNAVAILABLE: i32 = 2; + +const STATUS_UNAVAILABLE_MSG: &str = "spark-supervisor status: live status is not available from a separate process. \ +The supervisor keeps service state in the memory of the `run` process and exposes no IPC or status endpoint, \ +so a new process cannot see it. Check the daemon's log output instead."; #[derive(Parser, Debug)] #[command( @@ -32,6 +35,7 @@ struct Cli { #[derive(Subcommand, Debug)] enum Commands { Run, + /// Refuses with a non-zero exit: there is no channel to a running daemon. Status, Check, } @@ -39,6 +43,13 @@ enum Commands { #[tokio::main] async fn main() -> Result<(), Box> { let cli = Cli::parse(); + let command = cli.command.unwrap_or(Commands::Run); + + // Refuse before touching the config so `status` never writes a default file. + if matches!(command, Commands::Status) { + eprintln!("{}", STATUS_UNAVAILABLE_MSG); + std::process::exit(EXIT_STATUS_UNAVAILABLE); + } tracing_subscriber::registry() .with( @@ -66,15 +77,12 @@ async fn main() -> Result<(), Box> { } let config = SupervisorConfig::load_from_file(&cli.config)?; - let supervisor = Supervisor::new(config); - match cli.command.unwrap_or(Commands::Run) { + match command { Commands::Run => { - supervisor.run_daemon().await?; - } - Commands::Status => { - supervisor.print_status().await; + Supervisor::new(config).run_daemon().await?; } + Commands::Status => unreachable!("handled above"), Commands::Check => { println!("Configuration {:?} is valid.", cli.config); } diff --git a/crates/spark-supervisor/src/proc_telemetry.rs b/crates/spark-supervisor/src/proc_telemetry.rs index 4464e4d7..92459689 100644 --- a/crates/spark-supervisor/src/proc_telemetry.rs +++ b/crates/spark-supervisor/src/proc_telemetry.rs @@ -10,10 +10,30 @@ pub struct ProcessStats { pub cmdline: String, } +/// Reads the state letter, field (3) of `/proc//stat`. Field (2) `comm` is in +/// parentheses and may itself contain spaces or `)`, so the state is the first token +/// after the last `)` (proc_pid_stat(5)). +pub fn parse_stat_state(stat: &str) -> Option { + let rest = &stat[stat.rfind(')')? + 1..]; + rest.split_whitespace().next()?.chars().next() +} + +/// A pid counts as alive unless its state is Z (zombie: exited, not yet reaped) or +/// X/x (dead), per proc_pid_stat(5). A zombie still has a `/proc/` directory, so +/// directory existence alone would report an exited child as alive. +pub fn stat_state_is_alive(state: char) -> bool { + !matches!(state, 'Z' | 'X' | 'x') +} + pub fn get_process_stats(pid: u32) -> ProcessStats { let proc_dir = format!("/proc/{}", pid); let path = Path::new(&proc_dir); - if !path.exists() { + // Unreadable or unparsable stat (the process vanished mid-read) counts as not alive. + let alive = fs::read_to_string(path.join("stat")) + .ok() + .and_then(|s| parse_stat_state(&s)) + .is_some_and(stat_state_is_alive); + if !alive { return ProcessStats { pid, is_alive: false, @@ -44,3 +64,53 @@ pub fn get_process_stats(pid: u32) -> ProcessStats { cmdline, } } + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, Instant}; + + #[test] + fn parses_state_after_last_paren() { + assert_eq!(parse_stat_state("123 (sleep) S 1 123 123"), Some('S')); + assert_eq!(parse_stat_state("123 (a) b) Z 1 123"), Some('Z')); + assert_eq!(parse_stat_state("123 (sleep"), None); + assert_eq!(parse_stat_state(""), None); + } + + #[test] + fn zombie_and_dead_are_not_alive() { + for s in ['Z', 'X', 'x'] { + assert!(!stat_state_is_alive(s), "{s}"); + } + for s in ['R', 'S', 'D', 'T', 't'] { + assert!(stat_state_is_alive(s), "{s}"); + } + } + + #[test] + fn own_process_is_alive_missing_pid_is_not() { + assert!(get_process_stats(std::process::id()).is_alive); + assert!(!get_process_stats(u32::MAX).is_alive); + } + + #[test] + fn unreaped_child_zombie_is_not_alive() { + let mut child = std::process::Command::new("true").spawn().unwrap(); + let pid = child.id(); + let stat = format!("/proc/{pid}/stat"); + let deadline = Instant::now() + Duration::from_secs(5); + // Not reaped yet: wait for the kernel to show it as a zombie. + loop { + let s = fs::read_to_string(&stat).expect("zombie keeps its /proc entry"); + if parse_stat_state(&s) == Some('Z') { + break; + } + assert!(Instant::now() < deadline, "never became a zombie: {s}"); + std::thread::sleep(Duration::from_millis(1)); + } + assert!(Path::new(&format!("/proc/{pid}")).exists()); + assert!(!get_process_stats(pid).is_alive); + child.wait().unwrap(); + } +} diff --git a/crates/spark-supervisor/src/supervisor.rs b/crates/spark-supervisor/src/supervisor.rs index 5ade2351..e4c0e46e 100644 --- a/crates/spark-supervisor/src/supervisor.rs +++ b/crates/spark-supervisor/src/supervisor.rs @@ -1,37 +1,268 @@ -pub fn compute_restart_delay(restart_count: u32, base_secs: u64, max_secs: u64) -> Duration { - let factor = 2u64.saturating_pow(restart_count.saturating_sub(1)); - let secs = std::cmp::min(base_secs.saturating_mul(factor), max_secs); - Duration::from_secs(secs) -} +//! Process supervision with typed, generation-scoped readiness (issue #534). +//! +//! Readiness contract: +//! - Every successful spawn increments the service's `generation` and puts it in +//! [`ServiceState::Spawned`]. A spawned child is never [`ServiceState::Ready`] until a +//! probe taken for that same pid and generation succeeds. +//! - With `health_url`: `Ready` only after an HTTP GET to that URL returns a 2xx status +//! while the pid is alive. A non-2xx status, a connection error or a timeout gives +//! [`ServiceState::Unhealthy`]. +//! - Without `health_url`: `Ready` once the liveness check finds the pid alive in `/proc`. +//! This is liveness, not readiness: it says the process exists, not that it serves. +//! - Probes run with the state mutex released. Each result carries the (pid, generation) +//! it was taken for and is discarded when the service has since restarted or stopped, +//! so a slow answer for an old child can never mark its replacement ready. + use std::collections::HashMap; +use std::future::Future; use std::sync::Arc; -use std::time::Duration; -use tokio::sync::{broadcast, Mutex}; -use tokio::time::sleep; +use std::time::{Duration, Instant}; +use tokio::sync::{broadcast, Mutex, Notify}; +use tokio::task::JoinSet; +use tokio::time::{interval, sleep, MissedTickBehavior}; use tracing::{error, info, warn}; use crate::config::{ServiceConfig, SupervisorConfig}; use crate::proc_telemetry::get_process_stats; +pub fn compute_restart_delay(restart_count: u32, base_secs: u64, max_secs: u64) -> Duration { + let factor = 2u64.saturating_pow(restart_count.saturating_sub(1)); + let secs = std::cmp::min(base_secs.saturating_mul(factor), max_secs); + Duration::from_secs(secs) +} + +/// Lifecycle state of one managed service. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ServiceState { + /// Not running and not scheduled to run (initial state, shutdown, or `restart = "no"`). + Stopped, + /// Child spawned; no probe has been dispatched for this generation yet. + Spawned, + /// First probe for this generation is in flight; not ready. + Probing, + /// Readiness condition met for the current generation (see module docs). + Ready, + /// Last probe failed, the child exited and awaits restart, or the spawn failed. + Unhealthy, +} + +impl ServiceState { + pub fn is_ready(self) -> bool { + self == ServiceState::Ready + } +} + #[derive(Debug, Clone)] -#[allow(dead_code)] pub struct ManagedServiceState { pub name: String, pub config: ServiceConfig, pub pid: Option, + /// Incremented on every successful spawn; 0 means never spawned. + pub generation: u64, + pub state: ServiceState, pub restart_count: u32, - pub is_healthy: bool, pub uptime_secs: u64, pub rss_mb: f64, + pub spawned_at: Option, +} + +/// Tunables. `Default` keeps the previous fixed values: 3 s probe tick, 1500 ms HTTP +/// timeout, restart backoff base 2 s capped at 60 s, 5 s retry after a failed spawn. +#[derive(Debug, Clone)] +pub struct SupervisorOptions { + pub probe_interval: Duration, + pub probe_timeout: Duration, + pub restart_base_secs: u64, + pub restart_max_secs: u64, + pub spawn_retry_delay: Duration, + /// How long shutdown waits for supervise tasks to kill and reap their children. + pub shutdown_grace: Duration, +} + +impl Default for SupervisorOptions { + fn default() -> Self { + Self { + probe_interval: Duration::from_secs(3), + probe_timeout: Duration::from_millis(1500), + restart_base_secs: 2, + restart_max_secs: 60, + spawn_retry_delay: Duration::from_secs(5), + shutdown_grace: Duration::from_secs(5), + } + } +} + +/// What a probe was taken for, captured under the mutex before the lock is dropped. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProbeTicket { + pub name: String, + pub pid: u32, + pub generation: u64, + pub health_url: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ProbeOutcome { + /// Pid alive and, when a health_url is configured, it answered 2xx. + Healthy, + /// health_url answered with this non-2xx status. + HttpFailure(u16), + /// health_url could not be reached (connect error, timeout, protocol error). + HttpError(String), + /// The pid is no longer alive. + ProcessGone, +} + +#[derive(Debug, Clone)] +pub struct ProbeReport { + pub ticket: ProbeTicket, + pub outcome: ProbeOutcome, + pub rss_bytes: u64, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ApplyResult { + Applied { + from: ServiceState, + to: ServiceState, + }, + /// The service restarted or stopped since the ticket was taken; result discarded. + Stale, + UnknownService, +} + +/// Records a successful spawn and returns the new generation. +pub fn record_spawn( + states: &mut HashMap, + name: &str, + pid: Option, +) -> u64 { + match states.get_mut(name) { + Some(st) => { + st.generation += 1; + st.pid = pid; + st.state = ServiceState::Spawned; + st.spawned_at = Some(Instant::now()); + st.uptime_secs = 0; + st.rss_mb = 0.0; + st.generation + } + None => 0, + } +} + +/// Records that the child of `generation` is gone. `next` is `Unhealthy` while a restart +/// is pending, `Stopped` for shutdown or `restart = "no"`. Returns the restart count. +pub fn record_exit( + states: &mut HashMap, + name: &str, + generation: u64, + next: ServiceState, + count_restart: bool, +) -> u32 { + match states.get_mut(name) { + Some(st) if st.generation == generation => { + st.pid = None; + st.state = next; + st.spawned_at = None; + if count_restart { + st.restart_count += 1; + } + st.restart_count + } + Some(st) => st.restart_count, + None => 0, + } } +/// Takes probe tickets for every running service and moves `Spawned` to `Probing`. +/// Call with the lock held; it does no I/O. +pub fn begin_probe_round(states: &mut HashMap) -> Vec { + let mut tickets = Vec::new(); + for st in states.values_mut() { + let Some(pid) = st.pid else { continue }; + if st.state == ServiceState::Stopped { + continue; + } + if st.state == ServiceState::Spawned { + st.state = ServiceState::Probing; + } + tickets.push(ProbeTicket { + name: st.name.clone(), + pid, + generation: st.generation, + health_url: st.config.health_url.clone(), + }); + } + tickets +} + +/// Applies one probe result if, and only if, it still describes the current child. +/// Call with the lock held; it does no I/O. +pub fn apply_probe_report( + states: &mut HashMap, + report: &ProbeReport, +) -> ApplyResult { + let Some(st) = states.get_mut(&report.ticket.name) else { + return ApplyResult::UnknownService; + }; + if st.pid != Some(report.ticket.pid) + || st.generation != report.ticket.generation + || st.state == ServiceState::Stopped + { + return ApplyResult::Stale; + } + let from = st.state; + let to = match report.outcome { + ProbeOutcome::Healthy => ServiceState::Ready, + ProbeOutcome::HttpFailure(_) | ProbeOutcome::HttpError(_) | ProbeOutcome::ProcessGone => { + ServiceState::Unhealthy + } + }; + st.state = to; + if report.outcome != ProbeOutcome::ProcessGone { + st.rss_mb = report.rss_bytes as f64 / (1024.0 * 1024.0); + } + st.uptime_secs = st.spawned_at.map(|t| t.elapsed().as_secs()).unwrap_or(0); + ApplyResult::Applied { from, to } +} + +/// Runs one probe with no lock held. The HTTP request is bounded by the client timeout. +pub async fn probe_one(client: reqwest::Client, ticket: ProbeTicket) -> ProbeReport { + let stats = get_process_stats(ticket.pid); + let outcome = if !stats.is_alive { + ProbeOutcome::ProcessGone + } else { + match ticket.health_url.as_deref() { + None => ProbeOutcome::Healthy, + Some(url) => match client.get(url).send().await { + Ok(res) if res.status().is_success() => ProbeOutcome::Healthy, + Ok(res) => ProbeOutcome::HttpFailure(res.status().as_u16()), + Err(e) => ProbeOutcome::HttpError(e.to_string()), + }, + } + }; + ProbeReport { + ticket, + outcome, + rss_bytes: stats.rss_bytes, + } +} + +type StateMap = Arc>>; + pub struct Supervisor { config: SupervisorConfig, - states: Arc>>, + options: SupervisorOptions, + states: StateMap, } impl Supervisor { pub fn new(config: SupervisorConfig) -> Self { + Self::with_options(config, SupervisorOptions::default()) + } + + pub fn with_options(config: SupervisorConfig, options: SupervisorOptions) -> Self { let mut states = HashMap::new(); for (name, s_cfg) in &config.services { states.insert( @@ -40,79 +271,126 @@ impl Supervisor { name: name.clone(), config: s_cfg.clone(), pid: None, + generation: 0, + state: ServiceState::Stopped, restart_count: 0, - is_healthy: false, uptime_secs: 0, rss_mb: 0.0, + spawned_at: None, }, ); } Self { config, + options, states: Arc::new(Mutex::new(states)), } } + /// Copy of the in-process state. There is no IPC: only the process running the + /// daemon can see this. + pub async fn snapshot(&self) -> HashMap { + self.states.lock().await.clone() + } + + /// Runs until Ctrl-C. pub async fn run_daemon(&self) -> Result<(), Box> { + self.run_until(async { + let _ = tokio::signal::ctrl_c().await; + info!("Received termination signal. Shutting down all managed services gracefully..."); + }) + .await?; + Ok(()) + } + + /// Runs until `shutdown` completes, then kills and reaps every child. + pub async fn run_until(&self, shutdown: F) -> Result<(), reqwest::Error> + where + F: Future, + { info!( "Starting SparkOS Sovereign Supervisor with {} service(s)...", self.config.services.len() ); + let client = reqwest::Client::builder() + .timeout(self.options.probe_timeout) + .connect_timeout(self.options.probe_timeout) + .build()?; let (shutdown_tx, _) = broadcast::channel::<()>(1); - + let kick = Arc::new(Notify::new()); + let mut supervisors = JoinSet::new(); for (name, s_cfg) in self.config.services.clone() { - let states = self.states.clone(); - let mut shutdown_rx = shutdown_tx.subscribe(); - tokio::spawn(async move { - Self::supervise_loop(name, s_cfg, states, &mut shutdown_rx).await; - }); + supervisors.spawn(Self::supervise_loop( + name, + s_cfg, + self.states.clone(), + shutdown_tx.subscribe(), + kick.clone(), + self.options.clone(), + )); } - let states = self.states.clone(); - let http_client = reqwest::Client::builder() - .timeout(Duration::from_millis(1500)) - .build() - .unwrap_or_default(); - - let mut shutdown_rx = shutdown_tx.subscribe(); + tokio::pin!(shutdown); + let mut tick = interval(self.options.probe_interval); + tick.set_missed_tick_behavior(MissedTickBehavior::Delay); loop { tokio::select! { - _ = tokio::signal::ctrl_c() => { - info!("Received termination signal. Shutting down all managed services gracefully..."); - let _ = shutdown_tx.send(()); - // Allow child processes brief grace period to terminate - sleep(Duration::from_millis(1000)).await; - break; - } - _ = shutdown_rx.recv() => { - break; - } - _ = sleep(Duration::from_secs(3)) => { - let mut map = states.lock().await; - for state in map.values_mut() { - if let Some(pid) = state.pid { - let p_stats = get_process_stats(pid); - if p_stats.is_alive { - state.rss_mb = p_stats.rss_bytes as f64 / (1024.0 * 1024.0); - state.uptime_secs += 3; - } else { - state.is_healthy = false; - } + biased; + _ = &mut shutdown => break, + _ = tick.tick() => {} + _ = kick.notified() => {} + } - if let Some(ref h_url) = state.config.health_url { - if let Ok(res) = http_client.get(h_url).send().await { - state.is_healthy = res.status().is_success(); - } else { - state.is_healthy = false; - } - } else { - state.is_healthy = p_stats.is_alive; - } + let tickets = { + let mut map = self.states.lock().await; + begin_probe_round(&mut map) + }; + let mut probes = JoinSet::new(); + for ticket in tickets { + probes.spawn(probe_one(client.clone(), ticket)); + } + let stop = loop { + tokio::select! { + biased; + _ = &mut shutdown => { + probes.abort_all(); + break true; + } + joined = probes.join_next() => match joined { + None => break false, + Some(Ok(report)) => { + let applied = { + let mut map = self.states.lock().await; + apply_probe_report(&mut map, &report) + }; + log_apply(&report, applied); } + Some(Err(e)) => warn!("Health probe task failed: {}", e), } } + }; + if stop { + break; + } + } + + let _ = shutdown_tx.send(()); + let deadline = tokio::time::Instant::now() + self.options.shutdown_grace; + while !supervisors.is_empty() { + match tokio::time::timeout_at(deadline, supervisors.join_next()).await { + Ok(Some(Err(e))) => warn!("Supervise task failed: {}", e), + Ok(_) => {} + Err(_) => { + warn!( + "{} supervise task(s) did not stop within {:?}; aborting them", + supervisors.len(), + self.options.shutdown_grace + ); + supervisors.abort_all(); + break; + } } } @@ -123,8 +401,10 @@ impl Supervisor { async fn supervise_loop( name: String, config: ServiceConfig, - states: Arc>>, - shutdown_rx: &mut broadcast::Receiver<()>, + states: StateMap, + mut shutdown_rx: broadcast::Receiver<()>, + kick: Arc, + options: SupervisorOptions, ) { loop { let command_path = if let Some(stripped) = config.command.strip_prefix("~/") { @@ -148,15 +428,15 @@ impl Supervisor { match cmd.spawn() { Ok(mut child) => { let pid = child.id(); - { + let generation = { let mut map = states.lock().await; - if let Some(st) = map.get_mut(&name) { - st.pid = pid; - st.uptime_secs = 0; - st.is_healthy = true; - } - } - info!("[{}] Running with PID {:?}", name, pid); + record_spawn(&mut map, &name, pid) + }; + kick.notify_one(); + info!( + "[{}] Running with PID {:?} (generation {}); not ready until probed", + name, pid, generation + ); tokio::select! { _ = shutdown_rx.recv() => { @@ -164,10 +444,7 @@ impl Supervisor { let _ = child.kill().await; let _ = child.wait().await; let mut map = states.lock().await; - if let Some(st) = map.get_mut(&name) { - st.pid = None; - st.is_healthy = false; - } + record_exit(&mut map, &name, generation, ServiceState::Stopped, false); return; } status_res = child.wait() => { @@ -182,16 +459,14 @@ impl Supervisor { } } + let next = if config.restart == "no" { + ServiceState::Stopped + } else { + ServiceState::Unhealthy + }; let st_restarts = { let mut map = states.lock().await; - if let Some(st) = map.get_mut(&name) { - st.pid = None; - st.is_healthy = false; - st.restart_count += 1; - st.restart_count - } else { - 1 - } + record_exit(&mut map, &name, generation, next, true) }; if config.restart == "no" { @@ -199,53 +474,78 @@ impl Supervisor { break; } - let delay = compute_restart_delay(st_restarts, 2, 60); + let delay = compute_restart_delay( + st_restarts, + options.restart_base_secs, + options.restart_max_secs, + ); info!( "[{}] Restarting in {}s (restart #{})...", name, delay.as_secs(), st_restarts ); - sleep(delay).await; + tokio::select! { + _ = shutdown_rx.recv() => { + mark_stopped(&states, &name).await; + return; + } + _ = sleep(delay) => {} + } } Err(e) => { error!( - "[{}] Failed to spawn: {}. Retrying in 5 seconds...", - name, e + "[{}] Failed to spawn: {}. Retrying in {:?}...", + name, e, options.spawn_retry_delay ); - sleep(Duration::from_secs(5)).await; + { + let mut map = states.lock().await; + if let Some(st) = map.get_mut(&name) { + st.state = ServiceState::Unhealthy; + } + } + tokio::select! { + _ = shutdown_rx.recv() => { + mark_stopped(&states, &name).await; + return; + } + _ = sleep(options.spawn_retry_delay) => {} + } } } } } +} - pub async fn print_status(&self) { - let map = self.states.lock().await; - println!(); - println!("=== SparkOS Sovereign Supervisor Services ==="); - println!( - "{:<18} {:<10} {:<10} {:<12} {:<10} {:<10}", - "SERVICE", "STATUS", "PID", "MEMORY", "RESTARTS", "HEALTH" - ); - println!("{}", "-".repeat(74)); - - for (name, st) in map.iter() { - let pid_str = st.pid.map(|p| p.to_string()).unwrap_or_else(|| "-".into()); - let status_str = if st.pid.is_some() { - "RUNNING" - } else { - "STOPPED" - }; - let mem_str = format!("{:.1} MB", st.rss_mb); - let health_str = if st.is_healthy { "OK" } else { "UNHEALTHY" }; +/// Used only when no child is running (restart backoff or spawn retry). +async fn mark_stopped(states: &StateMap, name: &str) { + let mut map = states.lock().await; + if let Some(st) = map.get_mut(name) { + st.pid = None; + st.state = ServiceState::Stopped; + st.spawned_at = None; + } +} - println!( - "{:<18} {:<10} {:<10} {:<12} {:<10} {:<10}", - name, status_str, pid_str, mem_str, st.restart_count, health_str - ); - } - println!("{}", "-".repeat(74)); - println!(); +fn log_apply(report: &ProbeReport, applied: ApplyResult) { + let t = &report.ticket; + match applied { + ApplyResult::Applied { from, to } if from != to => match to { + ServiceState::Ready => info!( + "[{}] {:?} -> Ready (pid {}, generation {})", + t.name, from, t.pid, t.generation + ), + _ => warn!( + "[{}] {:?} -> {:?} (pid {}, generation {}): {:?}", + t.name, from, to, t.pid, t.generation, report.outcome + ), + }, + ApplyResult::Applied { .. } => {} + ApplyResult::Stale => info!( + "[{}] Discarded stale probe result for pid {} generation {}", + t.name, t.pid, t.generation + ), + ApplyResult::UnknownService => warn!("[{}] Probe result for unknown service", t.name), } } @@ -253,6 +553,31 @@ impl Supervisor { mod tests { use super::*; + fn svc(name: &str, health_url: Option<&str>) -> HashMap { + let mut config = SupervisorConfig { + services: HashMap::new(), + }; + config.services.insert( + name.to_string(), + ServiceConfig { + command: "sleep".into(), + args: vec!["30".into()], + env: HashMap::new(), + restart: "always".into(), + health_url: health_url.map(String::from), + }, + ); + Supervisor::new(config).states.try_lock().unwrap().clone() + } + + fn report(ticket: &ProbeTicket, outcome: ProbeOutcome) -> ProbeReport { + ProbeReport { + ticket: ticket.clone(), + outcome, + rss_bytes: 4096, + } + } + #[test] fn test_compute_restart_delay_backoff() { assert_eq!(compute_restart_delay(1, 2, 60), Duration::from_secs(2)); @@ -262,4 +587,128 @@ mod tests { assert_eq!(compute_restart_delay(5, 2, 60), Duration::from_secs(32)); assert_eq!(compute_restart_delay(6, 2, 60), Duration::from_secs(60)); // capped at max } + + #[test] + fn default_options_keep_previous_fixed_values() { + let o = SupervisorOptions::default(); + assert_eq!(o.probe_interval, Duration::from_secs(3)); + assert_eq!(o.probe_timeout, Duration::from_millis(1500)); + assert_eq!((o.restart_base_secs, o.restart_max_secs), (2, 60)); + assert_eq!(o.spawn_retry_delay, Duration::from_secs(5)); + } + + #[test] + fn new_service_starts_stopped_generation_zero() { + let m = svc("a", None); + assert_eq!(m["a"].state, ServiceState::Stopped); + assert_eq!(m["a"].generation, 0); + } + + #[test] + fn spawn_is_not_ready_and_probing_is_not_ready() { + let mut m = svc("a", None); + assert_eq!(record_spawn(&mut m, "a", Some(100)), 1); + assert_eq!(m["a"].state, ServiceState::Spawned); + assert!(!m["a"].state.is_ready()); + let tickets = begin_probe_round(&mut m); + assert_eq!(tickets.len(), 1); + assert_eq!(m["a"].state, ServiceState::Probing); + assert!(!m["a"].state.is_ready()); + } + + #[test] + fn healthy_report_makes_ready_failures_make_unhealthy() { + let mut m = svc("a", Some("http://127.0.0.1:1/health")); + record_spawn(&mut m, "a", Some(100)); + let t = begin_probe_round(&mut m).remove(0); + assert_eq!( + apply_probe_report(&mut m, &report(&t, ProbeOutcome::Healthy)), + ApplyResult::Applied { + from: ServiceState::Probing, + to: ServiceState::Ready + } + ); + for bad in [ + ProbeOutcome::HttpFailure(500), + ProbeOutcome::HttpError("refused".into()), + ProbeOutcome::ProcessGone, + ] { + assert_eq!( + apply_probe_report(&mut m, &report(&t, bad)), + ApplyResult::Applied { + from: ServiceState::Ready, + to: ServiceState::Unhealthy + } + ); + apply_probe_report(&mut m, &report(&t, ProbeOutcome::Healthy)); + } + } + + #[test] + fn stale_generation_is_ignored_even_with_reused_pid() { + let mut m = svc("a", None); + record_spawn(&mut m, "a", Some(100)); + let old = begin_probe_round(&mut m).remove(0); + record_exit(&mut m, "a", 1, ServiceState::Unhealthy, true); + // Same pid again: only the generation tells the two children apart. + assert_eq!(record_spawn(&mut m, "a", Some(100)), 2); + assert_eq!( + apply_probe_report(&mut m, &report(&old, ProbeOutcome::Healthy)), + ApplyResult::Stale + ); + assert_eq!(m["a"].state, ServiceState::Spawned); + } + + #[test] + fn stale_pid_is_ignored() { + let mut m = svc("a", None); + record_spawn(&mut m, "a", Some(100)); + let mut t = begin_probe_round(&mut m).remove(0); + t.pid = 101; + assert_eq!( + apply_probe_report(&mut m, &report(&t, ProbeOutcome::Healthy)), + ApplyResult::Stale + ); + assert_eq!(m["a"].state, ServiceState::Probing); + } + + #[test] + fn result_after_stop_is_ignored() { + let mut m = svc("a", None); + record_spawn(&mut m, "a", Some(100)); + let t = begin_probe_round(&mut m).remove(0); + record_exit(&mut m, "a", 1, ServiceState::Stopped, false); + assert_eq!( + apply_probe_report(&mut m, &report(&t, ProbeOutcome::Healthy)), + ApplyResult::Stale + ); + assert_eq!(m["a"].state, ServiceState::Stopped); + assert!(begin_probe_round(&mut m).is_empty()); + } + + #[test] + fn unknown_service_is_reported() { + let mut m = svc("a", None); + let t = ProbeTicket { + name: "ghost".into(), + pid: 1, + generation: 1, + health_url: None, + }; + assert_eq!( + apply_probe_report(&mut m, &report(&t, ProbeOutcome::Healthy)), + ApplyResult::UnknownService + ); + } + + #[test] + fn exit_for_old_generation_does_not_touch_new_child() { + let mut m = svc("a", None); + record_spawn(&mut m, "a", Some(100)); + record_spawn(&mut m, "a", Some(200)); + record_exit(&mut m, "a", 1, ServiceState::Unhealthy, true); + assert_eq!(m["a"].pid, Some(200)); + assert_eq!(m["a"].state, ServiceState::Spawned); + assert_eq!(m["a"].restart_count, 0); + } } diff --git a/crates/spark-supervisor/tests/readiness.rs b/crates/spark-supervisor/tests/readiness.rs new file mode 100644 index 00000000..a4c3e7f3 --- /dev/null +++ b/crates/spark-supervisor/tests/readiness.rs @@ -0,0 +1,412 @@ +//! Tokio integration tests for typed readiness (issue #534). Real short-lived children +//! (`sleep`) and a tiny local HTTP responder on a tokio TcpListener. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU16, AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use spark_supervisor::config::{ServiceConfig, SupervisorConfig}; +use spark_supervisor::proc_telemetry::{get_process_stats, parse_stat_state}; +use spark_supervisor::supervisor::{ + probe_one, ManagedServiceState, ProbeOutcome, ProbeTicket, ServiceState, Supervisor, + SupervisorOptions, +}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; +use tokio::sync::{oneshot, Semaphore}; +use tokio::task::JoinHandle; + +const WAIT: Duration = Duration::from_secs(5); +/// No probe may hold the state lock: a snapshot that takes longer than this fails fast. +const LOCK_BOUND: Duration = Duration::from_secs(2); + +/// Status code the responder answers with; 0 means hold the connection open, never answer. +struct Responder { + url: String, + status: Arc, + hits: Arc, +} + +async fn responder(status: u16, delay: Duration) -> Responder { + responder_with(status, delay, None).await +} + +/// With `gate`, each answer first takes one permit, so the test decides when it is sent. +async fn responder_with(status: u16, delay: Duration, gate: Option>) -> Responder { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/health", listener.local_addr().unwrap()); + let status = Arc::new(AtomicU16::new(status)); + let hits = Arc::new(AtomicUsize::new(0)); + let (s, h) = (status.clone(), hits.clone()); + tokio::spawn(async move { + loop { + let Ok((mut sock, _)) = listener.accept().await else { + return; + }; + let (s, h, gate) = (s.clone(), h.clone(), gate.clone()); + tokio::spawn(async move { + let mut buf = vec![0u8; 2048]; + let mut got = Vec::new(); + while !got.windows(4).any(|w| w == b"\r\n\r\n") { + match sock.read(&mut buf).await { + Ok(0) | Err(_) => return, + Ok(n) => got.extend_from_slice(&buf[..n]), + } + } + h.fetch_add(1, Ordering::SeqCst); + if let Some(g) = gate { + g.acquire().await.unwrap().forget(); + } + tokio::time::sleep(delay).await; + let code = s.load(Ordering::SeqCst); + if code == 0 { + tokio::time::sleep(Duration::from_secs(3600)).await; + return; + } + let resp = + format!("HTTP/1.1 {code} X\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + let _ = sock.write_all(resp.as_bytes()).await; + let _ = sock.shutdown().await; + }); + } + }); + Responder { url, status, hits } +} + +/// A URL whose port has nothing listening (bound, then released). +async fn refused_url() -> String { + let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + drop(l); + format!("http://{addr}/health") +} + +fn service(args: &[&str], restart: &str, health_url: Option<&str>) -> ServiceConfig { + ServiceConfig { + command: "sleep".into(), + args: args.iter().map(|s| s.to_string()).collect(), + env: HashMap::new(), + restart: restart.into(), + health_url: health_url.map(String::from), + } +} + +fn fast_options() -> SupervisorOptions { + SupervisorOptions { + probe_interval: Duration::from_millis(30), + probe_timeout: Duration::from_millis(500), + restart_base_secs: 0, + restart_max_secs: 0, + spawn_retry_delay: Duration::from_millis(50), + shutdown_grace: Duration::from_secs(5), + } +} + +struct Running { + sup: Arc, + stop: Option>, + task: JoinHandle<()>, +} + +fn start(services: Vec<(&str, ServiceConfig)>, options: SupervisorOptions) -> Running { + let config = SupervisorConfig { + services: services + .into_iter() + .map(|(n, c)| (n.to_string(), c)) + .collect(), + }; + let sup = Arc::new(Supervisor::with_options(config, options)); + let (tx, rx) = oneshot::channel::<()>(); + let s = sup.clone(); + let task = tokio::spawn(async move { + s.run_until(async { + let _ = rx.await; + }) + .await + .expect("run_until"); + }); + Running { + sup, + stop: Some(tx), + task, + } +} + +impl Running { + async fn state(&self, name: &str) -> ManagedServiceState { + tokio::time::timeout(LOCK_BOUND, self.sup.snapshot()) + .await + .expect("state lock held too long: is a probe awaiting HTTP under the mutex?")[name] + .clone() + } + + /// Polls until `pred` holds; returns every state observed on the way (in order). + async fn wait_for( + &self, + name: &str, + pred: impl Fn(&ManagedServiceState) -> bool, + ) -> Vec { + let deadline = Instant::now() + WAIT; + let mut seen = Vec::new(); + loop { + let st = self.state(name).await; + if seen.last() != Some(&st.state) { + seen.push(st.state); + } + if pred(&st) { + return seen; + } + assert!( + Instant::now() < deadline, + "timed out waiting on {name}; seen {seen:?}; last {st:?}" + ); + tokio::time::sleep(Duration::from_millis(2)).await; + } + } + + async fn shutdown(mut self) -> Arc { + let _ = self.stop.take().unwrap().send(()); + tokio::time::timeout(WAIT, &mut self.task) + .await + .expect("shutdown within bound") + .unwrap(); + self.sup + } +} + +#[tokio::test] +async fn healthy_probe_reaches_ready() { + let r = responder(200, Duration::ZERO).await; + let run = start( + vec![("svc", service(&["30"], "always", Some(&r.url)))], + fast_options(), + ); + let seen = run + .wait_for("svc", |s| s.state == ServiceState::Ready) + .await; + let st = run.state("svc").await; + assert_eq!(st.generation, 1); + assert!(st.pid.is_some()); + assert!(r.hits.load(Ordering::SeqCst) >= 1); + assert!(!seen.contains(&ServiceState::Unhealthy), "seen {seen:?}"); + run.shutdown().await; +} + +#[tokio::test] +async fn no_health_url_is_ready_by_liveness() { + let run = start( + vec![("svc", service(&["30"], "always", None))], + fast_options(), + ); + run.wait_for("svc", |s| s.state == ServiceState::Ready) + .await; + run.shutdown().await; +} + +#[tokio::test] +async fn http_500_is_unhealthy_never_ready() { + let r = responder(500, Duration::ZERO).await; + let run = start( + vec![("svc", service(&["30"], "always", Some(&r.url)))], + fast_options(), + ); + let mut seen = run + .wait_for("svc", |s| s.state == ServiceState::Unhealthy) + .await; + // Keep watching across several more probe rounds. + let hits = r.hits.load(Ordering::SeqCst); + seen.extend( + run.wait_for("svc", |_| r.hits.load(Ordering::SeqCst) >= hits + 3) + .await, + ); + assert!(!seen.contains(&ServiceState::Ready), "seen {seen:?}"); + assert_eq!(run.state("svc").await.state, ServiceState::Unhealthy); + run.shutdown().await; +} + +#[tokio::test] +async fn connection_refused_is_unhealthy() { + let url = refused_url().await; + let run = start( + vec![("svc", service(&["30"], "always", Some(&url)))], + fast_options(), + ); + let seen = run + .wait_for("svc", |s| s.state == ServiceState::Unhealthy) + .await; + assert!(!seen.contains(&ServiceState::Ready), "seen {seen:?}"); + run.shutdown().await; +} + +#[tokio::test] +async fn delayed_readiness_not_ready_until_responder_answers_200() { + let r = responder(503, Duration::ZERO).await; + let run = start( + vec![("svc", service(&["30"], "always", Some(&r.url)))], + fast_options(), + ); + let before = run + .wait_for("svc", |_| r.hits.load(Ordering::SeqCst) >= 3) + .await; + assert!(!before.contains(&ServiceState::Ready), "seen {before:?}"); + assert_ne!(run.state("svc").await.state, ServiceState::Ready); + + r.status.store(200, Ordering::SeqCst); + run.wait_for("svc", |s| s.state == ServiceState::Ready) + .await; + assert_eq!(run.state("svc").await.generation, 1); + run.shutdown().await; +} + +#[tokio::test] +async fn spawned_process_not_ready_while_probe_in_flight_and_shutdown_mid_probe() { + // Responder accepts but never answers; the probe stays in flight. + let r = responder(0, Duration::ZERO).await; + let mut opts = fast_options(); + opts.probe_timeout = Duration::from_secs(30); + let run = start( + vec![("svc", service(&["30"], "always", Some(&r.url)))], + opts, + ); + // The probe is now stuck in HTTP for up to 30 s. Reading state must still be quick; + // if the lock were held across the HTTP await this fails at LOCK_BOUND, not at 30 s. + let (seen, st) = tokio::time::timeout(LOCK_BOUND, async { + let seen = run + .wait_for("svc", |_| r.hits.load(Ordering::SeqCst) >= 1) + .await; + (seen, run.state("svc").await) + }) + .await + .expect("state readable while a probe is in flight"); + assert_eq!(st.state, ServiceState::Probing, "seen {seen:?}"); + assert!(!seen.contains(&ServiceState::Ready)); + let pid = st.pid.unwrap(); + + let t0 = Instant::now(); + let sup = run.shutdown().await; + assert!(t0.elapsed() < Duration::from_secs(2), "{:?}", t0.elapsed()); + let st = &sup.snapshot().await["svc"]; + assert_eq!(st.state, ServiceState::Stopped); + assert_eq!(st.pid, None); + assert!(!get_process_stats(pid).is_alive, "child {pid} still alive"); +} + +#[tokio::test] +async fn stale_probe_after_rapid_restart_never_marks_ready() { + // Event-driven, no timing margin: the responder holds every 200 until the test has + // seen the generation advance past the one that was alive when the request arrived. + // Every answer therefore belongs to a child that already exited, so the only way to + // report Ready would be to apply a stale result. + let gate = Arc::new(Semaphore::new(0)); + let r = responder_with(200, Duration::ZERO, Some(gate.clone())).await; + let mut opts = fast_options(); + opts.probe_timeout = Duration::from_secs(30); + let run = start( + vec![("svc", service(&["0.15"], "always", Some(&r.url)))], + opts, + ); + let mut seen = Vec::new(); + for k in 1..=3 { + seen.extend( + run.wait_for("svc", |_| r.hits.load(Ordering::SeqCst) >= k) + .await, + ); + let g = run.state("svc").await.generation; + seen.extend(run.wait_for("svc", |s| s.generation > g).await); + gate.add_permits(1); + } + // Rounds are serialized, so a 4th request means the 3rd answer was already handled. + seen.extend( + run.wait_for("svc", |_| r.hits.load(Ordering::SeqCst) >= 4) + .await, + ); + assert!(!seen.contains(&ServiceState::Ready), "seen {seen:?}"); + let st = run.state("svc").await; + assert!(st.generation >= 4 && st.restart_count >= 3, "{st:?}"); + gate.add_permits(1000); + run.shutdown().await; +} + +#[tokio::test] +async fn probe_of_unreaped_zombie_is_process_gone() { + // No health_url: liveness only. An exited child that is not yet reaped keeps its + // /proc entry; it must not count as alive. + let mut child = std::process::Command::new("true").spawn().unwrap(); + let pid = child.id(); + let deadline = Instant::now() + WAIT; + while std::fs::read_to_string(format!("/proc/{pid}/stat")) + .ok() + .and_then(|s| parse_stat_state(&s)) + != Some('Z') + { + assert!(Instant::now() < deadline, "child never became a zombie"); + tokio::time::sleep(Duration::from_millis(1)).await; + } + let ticket = ProbeTicket { + name: "svc".into(), + pid, + generation: 1, + health_url: None, + }; + let report = probe_one(reqwest::Client::new(), ticket).await; + assert_eq!(report.outcome, ProbeOutcome::ProcessGone); + child.wait().unwrap(); +} + +#[tokio::test] +async fn shutdown_stops_all_children_and_marks_stopped() { + let r = responder(200, Duration::ZERO).await; + let run = start( + vec![ + ("web", service(&["30"], "always", Some(&r.url))), + ("bare", service(&["30"], "always", None)), + ], + fast_options(), + ); + run.wait_for("web", |s| s.state == ServiceState::Ready) + .await; + run.wait_for("bare", |s| s.state == ServiceState::Ready) + .await; + let pids: Vec = run + .sup + .snapshot() + .await + .values() + .map(|s| s.pid.unwrap()) + .collect(); + + let sup = run.shutdown().await; + for st in sup.snapshot().await.values() { + assert_eq!(st.state, ServiceState::Stopped, "{st:?}"); + assert_eq!(st.pid, None); + } + for pid in pids { + assert!(!get_process_stats(pid).is_alive, "child {pid} still alive"); + } +} + +#[tokio::test] +async fn exit_with_restart_no_is_stopped() { + let run = start( + vec![("once", service(&["0.05"], "no", None))], + fast_options(), + ); + run.wait_for("once", |s| s.generation == 1).await; + run.wait_for("once", |s| s.state == ServiceState::Stopped) + .await; + let st = run.state("once").await; + assert_eq!((st.generation, st.restart_count, st.pid), (1, 1, None)); + run.shutdown().await; +} + +#[tokio::test] +async fn crashed_child_is_restarted_with_new_generation() { + let run = start( + vec![("flaky", service(&["0.05"], "always", None))], + fast_options(), + ); + run.wait_for("flaky", |s| s.generation >= 3).await; + assert!(run.state("flaky").await.restart_count >= 2); + run.shutdown().await; +} diff --git a/crates/spark-supervisor/tests/status_cli.rs b/crates/spark-supervisor/tests/status_cli.rs new file mode 100644 index 00000000..b7a72d7d --- /dev/null +++ b/crates/spark-supervisor/tests/status_cli.rs @@ -0,0 +1,54 @@ +//! `spark-supervisor status` must refuse instead of printing a table that looks live. + +use std::process::Command; + +#[test] +fn status_refuses_with_nonzero_exit_and_writes_nothing() { + let dir = std::env::temp_dir().join(format!("spark-supervisor-status-{}", std::process::id())); + let config = dir.join("supervisor.toml"); + let _ = std::fs::remove_dir_all(&dir); + + let out = Command::new(env!("CARGO_BIN_EXE_spark-supervisor")) + .arg("--config") + .arg(&config) + .arg("status") + .output() + .expect("run binary"); + + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!( + out.status.code(), + Some(2), + "stdout={stdout} stderr={stderr}" + ); + assert!( + stderr.contains("live status is not available from a separate process"), + "stderr={stderr}" + ); + assert!(!stdout.contains("SERVICE"), "table printed: {stdout}"); + assert!(!stdout.contains("RUNNING") && !stdout.contains("STOPPED")); + assert!(!config.exists(), "status must not generate a config file"); +} + +#[test] +fn check_still_succeeds_on_valid_config() { + let dir = std::env::temp_dir().join(format!("spark-supervisor-check-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let config = dir.join("supervisor.toml"); + std::fs::write( + &config, + "[services.a]\ncommand = \"sleep\"\nargs = [\"1\"]\n", + ) + .unwrap(); + + let out = Command::new(env!("CARGO_BIN_EXE_spark-supervisor")) + .arg("--config") + .arg(&config) + .arg("check") + .output() + .expect("run binary"); + assert!(out.status.success(), "{out:?}"); + assert!(String::from_utf8_lossy(&out.stdout).contains("is valid")); + let _ = std::fs::remove_dir_all(&dir); +}