interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

GitHub aien-dev/aien-sovereign-core-mv#540 (code only)

closed derived 779562deefc8d66f #540

Imported from GitHub aien-dev/aien-sovereign-core-mv#540 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base 4c83e389e8fa8790af6f3199958e6570f976db2d · Head 7ffdd3ef8600749add1d16410355179c804909b2

Apply it

git checkout -b patch-779562deefc8d66f 4c83e389e8fa8790af6f3199958e6570f976db2d
curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/779562deefc8d66f.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aien-sovereign-core-mv
540
7ffdd3ef8600749add1d16410355179c804909b2
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":540,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/540","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:25Z","metadata":"unavailable","state_derived":true}

Changes

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<String>) -> 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<String> = 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<String, u128> = HashMap::new();
+        let mut ready: HashMap<String, u128> = 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<dyn std::error::Error>> {
     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<dyn std::error::Error>> {
     }
 
     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/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<u32>,
+    /// 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<Instant>,
+}
+
+/// 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<String>,
+}
+
+#[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<String, ManagedServiceState>,
+    name: &str,
+    pid: Option<u32>,
+) -> 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<String, ManagedServiceState>,
+    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<String, ManagedServiceState>) -> Vec<ProbeTicket> {
+    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<String, ManagedServiceState>,
+    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<Mutex<HashMap<String, ManagedServiceState>>>;
+
 pub struct Supervisor {
     config: SupervisorConfig,
-    states: Arc<Mutex<HashMap<String, ManagedServiceState>>>,
+    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<String, ManagedServiceState> {
+        self.states.lock().await.clone()
+    }
+
+    /// Runs until Ctrl-C.
     pub async fn run_daemon(&self) -> Result<(), Box<dyn std::error::Error>> {
+        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<F>(&self, shutdown: F) -> Result<(), reqwest::Error>
+    where
+        F: Future<Output = ()>,
+    {
         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<Mutex<HashMap<String, ManagedServiceState>>>,
-        shutdown_rx: &mut broadcast::Receiver<()>,
+        states: StateMap,
+        mut shutdown_rx: broadcast::Receiver<()>,
+        kick: Arc<Notify>,
+        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<String, ManagedServiceState> {
+        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..5374e7df
--- /dev/null
+++ b/crates/spark-supervisor/tests/readiness.rs
@@ -0,0 +1,352 @@
+//! 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;
+use spark_supervisor::supervisor::{
+    ManagedServiceState, ServiceState, Supervisor, SupervisorOptions,
+};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpListener;
+use tokio::sync::oneshot;
+use tokio::task::JoinHandle;
+
+const WAIT: Duration = Duration::from_secs(5);
+
+/// Status code the responder answers with; 0 means hold the connection open, never answer.
+struct Responder {
+    url: String,
+    status: Arc<AtomicU16>,
+    hits: Arc<AtomicUsize>,
+}
+
+async fn responder(status: u16, delay: Duration) -> 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) = (s.clone(), h.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);
+                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<Supervisor>,
+    stop: Option<oneshot::Sender<()>>,
+    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 {
+        self.sup.snapshot().await[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<ServiceState> {
+        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<Supervisor> {
+        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,
+    );
+    let seen = run
+        .wait_for("svc", |_| r.hits.load(Ordering::SeqCst) >= 1)
+        .await;
+    let st = run.state("svc").await;
+    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() {
+    // Each child lives 150 ms; the health endpoint answers 200 only after 400 ms.
+    // Every successful answer therefore belongs to a generation that already exited,
+    // so the only way to report Ready would be to apply a stale result.
+    let r = responder(200, Duration::from_millis(400)).await;
+    let run = start(
+        vec![("svc", service(&["0.15"], "always", Some(&r.url)))],
+        fast_options(),
+    );
+    // At least two answered probes (each answer takes 400 ms) across four generations.
+    let seen = run
+        .wait_for("svc", |s| {
+            s.generation >= 4 && r.hits.load(Ordering::SeqCst) >= 3
+        })
+        .await;
+    assert!(!seen.contains(&ServiceState::Ready), "seen {seen:?}");
+    let st = run.state("svc").await;
+    assert!(st.restart_count >= 3);
+    run.shutdown().await;
+}
+
+#[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<u32> = 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);
+}