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
aien-sovereign-core-mv / crates / spark-supervisor / tests / readiness.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Tokio integration tests for typed readiness (issue #534). Real short-lived children |
| 17 | //! (`sleep`) and a tiny local HTTP responder on a tokio TcpListener. |
| 18 | |
| 19 | use std::collections::HashMap; |
| 20 | use std::sync::atomic::{AtomicU16, AtomicUsize, Ordering}; |
| 21 | use std::sync::Arc; |
| 22 | use std::time::{Duration, Instant}; |
| 23 | |
| 24 | use spark_supervisor::config::{ServiceConfig, SupervisorConfig}; |
| 25 | use spark_supervisor::proc_telemetry::{get_process_stats, parse_stat_state}; |
| 26 | use spark_supervisor::supervisor::{ |
| 27 | probe_one, ManagedServiceState, ProbeOutcome, ProbeTicket, ServiceState, Supervisor, |
| 28 | SupervisorOptions, |
| 29 | }; |
| 30 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 31 | use tokio::net::TcpListener; |
| 32 | use tokio::sync::{oneshot, Semaphore}; |
| 33 | use tokio::task::JoinHandle; |
| 34 | |
| 35 | const WAIT: Duration = Duration::from_secs(5); |
| 36 | /// No probe may hold the state lock: a snapshot that takes longer than this fails fast. |
| 37 | const LOCK_BOUND: Duration = Duration::from_secs(2); |
| 38 | |
| 39 | /// Status code the responder answers with; 0 means hold the connection open, never answer. |
| 40 | struct Responder { |
| 41 | url: String, |
| 42 | status: Arc<AtomicU16>, |
| 43 | hits: Arc<AtomicUsize>, |
| 44 | } |
| 45 | |
| 46 | async fn responder(status: u16, delay: Duration) -> Responder { |
| 47 | responder_with(status, delay, None).await |
| 48 | } |
| 49 | |
| 50 | /// With `gate`, each answer first takes one permit, so the test decides when it is sent. |
| 51 | async fn responder_with(status: u16, delay: Duration, gate: Option<Arc<Semaphore>>) -> Responder { |
| 52 | let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 53 | let url = format!("http://{}/health", listener.local_addr().unwrap()); |
| 54 | let status = Arc::new(AtomicU16::new(status)); |
| 55 | let hits = Arc::new(AtomicUsize::new(0)); |
| 56 | let (s, h) = (status.clone(), hits.clone()); |
| 57 | tokio::spawn(async move { |
| 58 | loop { |
| 59 | let Ok((mut sock, _)) = listener.accept().await else { |
| 60 | return; |
| 61 | }; |
| 62 | let (s, h, gate) = (s.clone(), h.clone(), gate.clone()); |
| 63 | tokio::spawn(async move { |
| 64 | let mut buf = vec![0u8; 2048]; |
| 65 | let mut got = Vec::new(); |
| 66 | while !got.windows(4).any(|w| w == b"\r\n\r\n") { |
| 67 | match sock.read(&mut buf).await { |
| 68 | Ok(0) | Err(_) => return, |
| 69 | Ok(n) => got.extend_from_slice(&buf[..n]), |
| 70 | } |
| 71 | } |
| 72 | h.fetch_add(1, Ordering::SeqCst); |
| 73 | if let Some(g) = gate { |
| 74 | g.acquire().await.unwrap().forget(); |
| 75 | } |
| 76 | tokio::time::sleep(delay).await; |
| 77 | let code = s.load(Ordering::SeqCst); |
| 78 | if code == 0 { |
| 79 | tokio::time::sleep(Duration::from_secs(3600)).await; |
| 80 | return; |
| 81 | } |
| 82 | let resp = |
| 83 | format!("HTTP/1.1 {code} X\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); |
| 84 | let _ = sock.write_all(resp.as_bytes()).await; |
| 85 | let _ = sock.shutdown().await; |
| 86 | }); |
| 87 | } |
| 88 | }); |
| 89 | Responder { url, status, hits } |
| 90 | } |
| 91 | |
| 92 | /// A URL whose port has nothing listening (bound, then released). |
| 93 | async fn refused_url() -> String { |
| 94 | let l = TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 95 | let addr = l.local_addr().unwrap(); |
| 96 | drop(l); |
| 97 | format!("http://{addr}/health") |
| 98 | } |
| 99 | |
| 100 | fn service(args: &[&str], restart: &str, health_url: Option<&str>) -> ServiceConfig { |
| 101 | ServiceConfig { |
| 102 | command: "sleep".into(), |
| 103 | args: args.iter().map(|s| s.to_string()).collect(), |
| 104 | env: HashMap::new(), |
| 105 | restart: restart.into(), |
| 106 | health_url: health_url.map(String::from), |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | fn fast_options() -> SupervisorOptions { |
| 111 | SupervisorOptions { |
| 112 | probe_interval: Duration::from_millis(30), |
| 113 | probe_timeout: Duration::from_millis(500), |
| 114 | restart_base_secs: 0, |
| 115 | restart_max_secs: 0, |
| 116 | spawn_retry_delay: Duration::from_millis(50), |
| 117 | shutdown_grace: Duration::from_secs(5), |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | struct Running { |
| 122 | sup: Arc<Supervisor>, |
| 123 | stop: Option<oneshot::Sender<()>>, |
| 124 | task: JoinHandle<()>, |
| 125 | } |
| 126 | |
| 127 | fn start(services: Vec<(&str, ServiceConfig)>, options: SupervisorOptions) -> Running { |
| 128 | let config = SupervisorConfig { |
| 129 | services: services |
| 130 | .into_iter() |
| 131 | .map(|(n, c)| (n.to_string(), c)) |
| 132 | .collect(), |
| 133 | }; |
| 134 | let sup = Arc::new(Supervisor::with_options(config, options)); |
| 135 | let (tx, rx) = oneshot::channel::<()>(); |
| 136 | let s = sup.clone(); |
| 137 | let task = tokio::spawn(async move { |
| 138 | s.run_until(async { |
| 139 | let _ = rx.await; |
| 140 | }) |
| 141 | .await |
| 142 | .expect("run_until"); |
| 143 | }); |
| 144 | Running { |
| 145 | sup, |
| 146 | stop: Some(tx), |
| 147 | task, |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | impl Running { |
| 152 | async fn state(&self, name: &str) -> ManagedServiceState { |
| 153 | tokio::time::timeout(LOCK_BOUND, self.sup.snapshot()) |
| 154 | .await |
| 155 | .expect("state lock held too long: is a probe awaiting HTTP under the mutex?")[name] |
| 156 | .clone() |
| 157 | } |
| 158 | |
| 159 | /// Polls until `pred` holds; returns every state observed on the way (in order). |
| 160 | async fn wait_for( |
| 161 | &self, |
| 162 | name: &str, |
| 163 | pred: impl Fn(&ManagedServiceState) -> bool, |
| 164 | ) -> Vec<ServiceState> { |
| 165 | let deadline = Instant::now() + WAIT; |
| 166 | let mut seen = Vec::new(); |
| 167 | loop { |
| 168 | let st = self.state(name).await; |
| 169 | if seen.last() != Some(&st.state) { |
| 170 | seen.push(st.state); |
| 171 | } |
| 172 | if pred(&st) { |
| 173 | return seen; |
| 174 | } |
| 175 | assert!( |
| 176 | Instant::now() < deadline, |
| 177 | "timed out waiting on {name}; seen {seen:?}; last {st:?}" |
| 178 | ); |
| 179 | tokio::time::sleep(Duration::from_millis(2)).await; |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | async fn shutdown(mut self) -> Arc<Supervisor> { |
| 184 | let _ = self.stop.take().unwrap().send(()); |
| 185 | tokio::time::timeout(WAIT, &mut self.task) |
| 186 | .await |
| 187 | .expect("shutdown within bound") |
| 188 | .unwrap(); |
| 189 | self.sup |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | #[tokio::test] |
| 194 | async fn healthy_probe_reaches_ready() { |
| 195 | let r = responder(200, Duration::ZERO).await; |
| 196 | let run = start( |
| 197 | vec![("svc", service(&["30"], "always", Some(&r.url)))], |
| 198 | fast_options(), |
| 199 | ); |
| 200 | let seen = run |
| 201 | .wait_for("svc", |s| s.state == ServiceState::Ready) |
| 202 | .await; |
| 203 | let st = run.state("svc").await; |
| 204 | assert_eq!(st.generation, 1); |
| 205 | assert!(st.pid.is_some()); |
| 206 | assert!(r.hits.load(Ordering::SeqCst) >= 1); |
| 207 | assert!(!seen.contains(&ServiceState::Unhealthy), "seen {seen:?}"); |
| 208 | run.shutdown().await; |
| 209 | } |
| 210 | |
| 211 | #[tokio::test] |
| 212 | async fn no_health_url_is_ready_by_liveness() { |
| 213 | let run = start( |
| 214 | vec![("svc", service(&["30"], "always", None))], |
| 215 | fast_options(), |
| 216 | ); |
| 217 | run.wait_for("svc", |s| s.state == ServiceState::Ready) |
| 218 | .await; |
| 219 | run.shutdown().await; |
| 220 | } |
| 221 | |
| 222 | #[tokio::test] |
| 223 | async fn http_500_is_unhealthy_never_ready() { |
| 224 | let r = responder(500, Duration::ZERO).await; |
| 225 | let run = start( |
| 226 | vec![("svc", service(&["30"], "always", Some(&r.url)))], |
| 227 | fast_options(), |
| 228 | ); |
| 229 | let mut seen = run |
| 230 | .wait_for("svc", |s| s.state == ServiceState::Unhealthy) |
| 231 | .await; |
| 232 | // Keep watching across several more probe rounds. |
| 233 | let hits = r.hits.load(Ordering::SeqCst); |
| 234 | seen.extend( |
| 235 | run.wait_for("svc", |_| r.hits.load(Ordering::SeqCst) >= hits + 3) |
| 236 | .await, |
| 237 | ); |
| 238 | assert!(!seen.contains(&ServiceState::Ready), "seen {seen:?}"); |
| 239 | assert_eq!(run.state("svc").await.state, ServiceState::Unhealthy); |
| 240 | run.shutdown().await; |
| 241 | } |
| 242 | |
| 243 | #[tokio::test] |
| 244 | async fn connection_refused_is_unhealthy() { |
| 245 | let url = refused_url().await; |
| 246 | let run = start( |
| 247 | vec![("svc", service(&["30"], "always", Some(&url)))], |
| 248 | fast_options(), |
| 249 | ); |
| 250 | let seen = run |
| 251 | .wait_for("svc", |s| s.state == ServiceState::Unhealthy) |
| 252 | .await; |
| 253 | assert!(!seen.contains(&ServiceState::Ready), "seen {seen:?}"); |
| 254 | run.shutdown().await; |
| 255 | } |
| 256 | |
| 257 | #[tokio::test] |
| 258 | async fn delayed_readiness_not_ready_until_responder_answers_200() { |
| 259 | let r = responder(503, Duration::ZERO).await; |
| 260 | let run = start( |
| 261 | vec![("svc", service(&["30"], "always", Some(&r.url)))], |
| 262 | fast_options(), |
| 263 | ); |
| 264 | let before = run |
| 265 | .wait_for("svc", |_| r.hits.load(Ordering::SeqCst) >= 3) |
| 266 | .await; |
| 267 | assert!(!before.contains(&ServiceState::Ready), "seen {before:?}"); |
| 268 | assert_ne!(run.state("svc").await.state, ServiceState::Ready); |
| 269 | |
| 270 | r.status.store(200, Ordering::SeqCst); |
| 271 | run.wait_for("svc", |s| s.state == ServiceState::Ready) |
| 272 | .await; |
| 273 | assert_eq!(run.state("svc").await.generation, 1); |
| 274 | run.shutdown().await; |
| 275 | } |
| 276 | |
| 277 | #[tokio::test] |
| 278 | async fn spawned_process_not_ready_while_probe_in_flight_and_shutdown_mid_probe() { |
| 279 | // Responder accepts but never answers; the probe stays in flight. |
| 280 | let r = responder(0, Duration::ZERO).await; |
| 281 | let mut opts = fast_options(); |
| 282 | opts.probe_timeout = Duration::from_secs(30); |
| 283 | let run = start( |
| 284 | vec![("svc", service(&["30"], "always", Some(&r.url)))], |
| 285 | opts, |
| 286 | ); |
| 287 | // The probe is now stuck in HTTP for up to 30 s. Reading state must still be quick; |
| 288 | // if the lock were held across the HTTP await this fails at LOCK_BOUND, not at 30 s. |
| 289 | let (seen, st) = tokio::time::timeout(LOCK_BOUND, async { |
| 290 | let seen = run |
| 291 | .wait_for("svc", |_| r.hits.load(Ordering::SeqCst) >= 1) |
| 292 | .await; |
| 293 | (seen, run.state("svc").await) |
| 294 | }) |
| 295 | .await |
| 296 | .expect("state readable while a probe is in flight"); |
| 297 | assert_eq!(st.state, ServiceState::Probing, "seen {seen:?}"); |
| 298 | assert!(!seen.contains(&ServiceState::Ready)); |
| 299 | let pid = st.pid.unwrap(); |
| 300 | |
| 301 | let t0 = Instant::now(); |
| 302 | let sup = run.shutdown().await; |
| 303 | assert!(t0.elapsed() < Duration::from_secs(2), "{:?}", t0.elapsed()); |
| 304 | let st = &sup.snapshot().await["svc"]; |
| 305 | assert_eq!(st.state, ServiceState::Stopped); |
| 306 | assert_eq!(st.pid, None); |
| 307 | assert!(!get_process_stats(pid).is_alive, "child {pid} still alive"); |
| 308 | } |
| 309 | |
| 310 | #[tokio::test] |
| 311 | async fn stale_probe_after_rapid_restart_never_marks_ready() { |
| 312 | // Event-driven, no timing margin: the responder holds every 200 until the test has |
| 313 | // seen the generation advance past the one that was alive when the request arrived. |
| 314 | // Every answer therefore belongs to a child that already exited, so the only way to |
| 315 | // report Ready would be to apply a stale result. |
| 316 | let gate = Arc::new(Semaphore::new(0)); |
| 317 | let r = responder_with(200, Duration::ZERO, Some(gate.clone())).await; |
| 318 | let mut opts = fast_options(); |
| 319 | opts.probe_timeout = Duration::from_secs(30); |
| 320 | let run = start( |
| 321 | vec![("svc", service(&["0.15"], "always", Some(&r.url)))], |
| 322 | opts, |
| 323 | ); |
| 324 | let mut seen = Vec::new(); |
| 325 | for k in 1..=3 { |
| 326 | seen.extend( |
| 327 | run.wait_for("svc", |_| r.hits.load(Ordering::SeqCst) >= k) |
| 328 | .await, |
| 329 | ); |
| 330 | let g = run.state("svc").await.generation; |
| 331 | seen.extend(run.wait_for("svc", |s| s.generation > g).await); |
| 332 | gate.add_permits(1); |
| 333 | } |
| 334 | // Rounds are serialized, so a 4th request means the 3rd answer was already handled. |
| 335 | seen.extend( |
| 336 | run.wait_for("svc", |_| r.hits.load(Ordering::SeqCst) >= 4) |
| 337 | .await, |
| 338 | ); |
| 339 | assert!(!seen.contains(&ServiceState::Ready), "seen {seen:?}"); |
| 340 | let st = run.state("svc").await; |
| 341 | assert!(st.generation >= 4 && st.restart_count >= 3, "{st:?}"); |
| 342 | gate.add_permits(1000); |
| 343 | run.shutdown().await; |
| 344 | } |
| 345 | |
| 346 | #[tokio::test] |
| 347 | async fn probe_of_unreaped_zombie_is_process_gone() { |
| 348 | // No health_url: liveness only. An exited child that is not yet reaped keeps its |
| 349 | // /proc entry; it must not count as alive. |
| 350 | let mut child = std::process::Command::new("true").spawn().unwrap(); |
| 351 | let pid = child.id(); |
| 352 | let deadline = Instant::now() + WAIT; |
| 353 | while std::fs::read_to_string(format!("/proc/{pid}/stat")) |
| 354 | .ok() |
| 355 | .and_then(|s| parse_stat_state(&s)) |
| 356 | != Some('Z') |
| 357 | { |
| 358 | assert!(Instant::now() < deadline, "child never became a zombie"); |
| 359 | tokio::time::sleep(Duration::from_millis(1)).await; |
| 360 | } |
| 361 | let ticket = ProbeTicket { |
| 362 | name: "svc".into(), |
| 363 | pid, |
| 364 | generation: 1, |
| 365 | health_url: None, |
| 366 | }; |
| 367 | let report = probe_one(aien_localhttp::Client::new(), ticket).await; |
| 368 | assert_eq!(report.outcome, ProbeOutcome::ProcessGone); |
| 369 | child.wait().unwrap(); |
| 370 | } |
| 371 | |
| 372 | #[tokio::test] |
| 373 | async fn shutdown_stops_all_children_and_marks_stopped() { |
| 374 | let r = responder(200, Duration::ZERO).await; |
| 375 | let run = start( |
| 376 | vec![ |
| 377 | ("web", service(&["30"], "always", Some(&r.url))), |
| 378 | ("bare", service(&["30"], "always", None)), |
| 379 | ], |
| 380 | fast_options(), |
| 381 | ); |
| 382 | run.wait_for("web", |s| s.state == ServiceState::Ready) |
| 383 | .await; |
| 384 | run.wait_for("bare", |s| s.state == ServiceState::Ready) |
| 385 | .await; |
| 386 | let pids: Vec<u32> = run |
| 387 | .sup |
| 388 | .snapshot() |
| 389 | .await |
| 390 | .values() |
| 391 | .map(|s| s.pid.unwrap()) |
| 392 | .collect(); |
| 393 | |
| 394 | let sup = run.shutdown().await; |
| 395 | for st in sup.snapshot().await.values() { |
| 396 | assert_eq!(st.state, ServiceState::Stopped, "{st:?}"); |
| 397 | assert_eq!(st.pid, None); |
| 398 | } |
| 399 | for pid in pids { |
| 400 | assert!(!get_process_stats(pid).is_alive, "child {pid} still alive"); |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | #[tokio::test] |
| 405 | async fn exit_with_restart_no_is_stopped() { |
| 406 | let run = start( |
| 407 | vec![("once", service(&["0.05"], "no", None))], |
| 408 | fast_options(), |
| 409 | ); |
| 410 | run.wait_for("once", |s| s.generation == 1).await; |
| 411 | run.wait_for("once", |s| s.state == ServiceState::Stopped) |
| 412 | .await; |
| 413 | let st = run.state("once").await; |
| 414 | assert_eq!((st.generation, st.restart_count, st.pid), (1, 1, None)); |
| 415 | run.shutdown().await; |
| 416 | } |
| 417 | |
| 418 | #[tokio::test] |
| 419 | async fn crashed_child_is_restarted_with_new_generation() { |
| 420 | let run = start( |
| 421 | vec![("flaky", service(&["0.05"], "always", None))], |
| 422 | fast_options(), |
| 423 | ); |
| 424 | run.wait_for("flaky", |s| s.generation >= 3).await; |
| 425 | assert!(run.state("flaky").await.restart_count >= 2); |
| 426 | run.shutdown().await; |
| 427 | } |
| 428 | |
| 429 | #[tokio::test] |
| 430 | async fn https_health_url_refuses_to_start_before_spawning_or_connecting() { |
| 431 | // An operator-configured https health_url is a loud config error: run_until |
| 432 | // returns HttpsRefused before any child is spawned or any socket is opened. |
| 433 | let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 434 | let addr = listener.local_addr().unwrap(); |
| 435 | let url = format!("https://{addr}/health"); |
| 436 | let config = SupervisorConfig { |
| 437 | services: [("tls".to_string(), service(&["30"], "always", Some(&url)))] |
| 438 | .into_iter() |
| 439 | .collect(), |
| 440 | }; |
| 441 | let sup = Supervisor::with_options(config, fast_options()); |
| 442 | let err = tokio::time::timeout(WAIT, sup.run_until(std::future::pending())) |
| 443 | .await |
| 444 | .expect("run_until must fail at once, not run") |
| 445 | .unwrap_err(); |
| 446 | assert!( |
| 447 | matches!(err, aien_localhttp::Error::HttpsRefused { .. }), |
| 448 | "{err:?}" |
| 449 | ); |
| 450 | assert!( |
| 451 | err.to_string().contains("service \"tls\" health_url"), |
| 452 | "{err}" |
| 453 | ); |
| 454 | let st = sup.snapshot().await["tls"].clone(); |
| 455 | assert_eq!(st.state, ServiceState::Stopped); |
| 456 | assert!(st.pid.is_none()); |
| 457 | assert!( |
| 458 | tokio::time::timeout(Duration::from_millis(200), listener.accept()) |
| 459 | .await |
| 460 | .is_err(), |
| 461 | "no connection may be made to an https health_url" |
| 462 | ); |
| 463 | } |
| 464 | |
| 465 | #[tokio::test] |
| 466 | async fn probe_one_with_https_url_is_http_error_without_connecting() { |
| 467 | let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 468 | let addr = listener.local_addr().unwrap(); |
| 469 | let ticket = ProbeTicket { |
| 470 | name: "svc".into(), |
| 471 | pid: std::process::id(), |
| 472 | generation: 1, |
| 473 | health_url: Some(format!("https://{addr}/health")), |
| 474 | }; |
| 475 | let report = probe_one(aien_localhttp::Client::new(), ticket).await; |
| 476 | match report.outcome { |
| 477 | ProbeOutcome::HttpError(msg) => assert!(msg.contains("https is refused"), "{msg}"), |
| 478 | other => panic!("expected HttpError, got {other:?}"), |
| 479 | } |
| 480 | assert!( |
| 481 | tokio::time::timeout(Duration::from_millis(200), listener.accept()) |
| 482 | .await |
| 483 | .is_err(), |
| 484 | "probe_one must not connect to an https health_url" |
| 485 | ); |
| 486 | } |