aegis-runtime-mv
Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
aegis-runtime-mv / tests / round3_heartbeat_tests.rs
| 1 | //! Host-only regressions for maintenance recovery, explicit migration and bounded health work. |
| 2 | use aegis::{ChatStream, ChatTurnResponse, Database, HeartbeatEngine, InferenceEngine}; |
| 3 | use rusqlite::Connection; |
| 4 | use serde_json::{json, Value}; |
| 5 | use std::io::Read; |
| 6 | use std::process::{Child, Command, Stdio}; |
| 7 | use std::sync::{ |
| 8 | atomic::{AtomicUsize, Ordering}, |
| 9 | Arc, |
| 10 | }; |
| 11 | use std::time::Duration; |
| 12 | |
| 13 | fn state(conn: &Connection, id: &str) -> (String, Option<String>) { |
| 14 | conn.query_row("SELECT status,result FROM tasks WHERE id=?1", [id], |r| { |
| 15 | Ok((r.get(0)?, r.get(1)?)) |
| 16 | }) |
| 17 | .unwrap() |
| 18 | } |
| 19 | fn events(conn: &Connection) -> i64 { |
| 20 | conn.query_row("SELECT count(*) FROM task_terminal_events", [], |r| { |
| 21 | r.get(0) |
| 22 | }) |
| 23 | .unwrap() |
| 24 | } |
| 25 | struct OwnerProcess(Child); |
| 26 | impl Drop for OwnerProcess { |
| 27 | fn drop(&mut self) { |
| 28 | if self.0.try_wait().unwrap().is_none() { |
| 29 | self.0.kill().unwrap(); |
| 30 | } |
| 31 | self.0.wait().unwrap(); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | #[test] |
| 36 | fn round3_owner_process_helper() { |
| 37 | let Some(path) = std::env::var_os("AEGIS_TEST_OWNER_DATABASE") else { |
| 38 | return; |
| 39 | }; |
| 40 | let db = Database::open(std::path::Path::new(&path)).unwrap(); |
| 41 | db.create_task("peer", "consolidate_memory", "must not replay") |
| 42 | .unwrap(); |
| 43 | assert!(db.claim_task("peer").unwrap().is_some()); |
| 44 | std::fs::write( |
| 45 | std::env::var_os("AEGIS_TEST_OWNER_READY").unwrap(), |
| 46 | b"claimed", |
| 47 | ) |
| 48 | .unwrap(); |
| 49 | let mut release = [0]; |
| 50 | let _ = std::io::stdin().read_exact(&mut release); |
| 51 | drop(db); |
| 52 | } |
| 53 | |
| 54 | #[tokio::test] |
| 55 | async fn round3_live_peer_death_recovers_without_reopening_observer() { |
| 56 | let dir = tempfile::tempdir().unwrap(); |
| 57 | let path = dir.path().join("peer.sqlite"); |
| 58 | let ready = dir.path().join("ready"); |
| 59 | let mut child = OwnerProcess( |
| 60 | Command::new(std::env::current_exe().unwrap()) |
| 61 | .args(["--exact", "round3_owner_process_helper", "--nocapture"]) |
| 62 | .env("AEGIS_TEST_OWNER_DATABASE", &path) |
| 63 | .env("AEGIS_TEST_OWNER_READY", &ready) |
| 64 | .stdin(Stdio::piped()) |
| 65 | .stdout(Stdio::null()) |
| 66 | .spawn() |
| 67 | .unwrap(), |
| 68 | ); |
| 69 | tokio::time::timeout(Duration::from_secs(5), async { |
| 70 | while !ready.exists() { |
| 71 | tokio::time::sleep(Duration::from_millis(10)).await; |
| 72 | } |
| 73 | }) |
| 74 | .await |
| 75 | .unwrap(); |
| 76 | let db = Arc::new(Database::open(&path).unwrap()); |
| 77 | let observer = Connection::open(&path).unwrap(); |
| 78 | let engine = HeartbeatEngine::new(60, db); |
| 79 | assert_eq!(engine.pulse_once().await.status, "nominal"); |
| 80 | assert_eq!( |
| 81 | state(&observer, "peer").0, |
| 82 | "running", |
| 83 | "live process owns the flock" |
| 84 | ); |
| 85 | assert_eq!(events(&observer), 0); |
| 86 | child.0.kill().unwrap(); |
| 87 | child.0.wait().unwrap(); |
| 88 | let receipt = engine.pulse_once().await; |
| 89 | assert_eq!(receipt.status, "degraded"); |
| 90 | assert_eq!(receipt.actions_dispatched, 0); |
| 91 | assert_eq!( |
| 92 | state(&observer, "peer"), |
| 93 | ("failed".into(), Some("abandoned: outcome unknown".into())) |
| 94 | ); |
| 95 | assert_eq!(events(&observer), 1); |
| 96 | assert_eq!(engine.pulse_once().await.status, "nominal"); |
| 97 | assert_eq!(events(&observer), 1); |
| 98 | let crumbs: i64 = observer |
| 99 | .query_row("SELECT count(*) FROM memory_crumbs", [], |r| r.get(0)) |
| 100 | .unwrap(); |
| 101 | assert_eq!(crumbs, 0); |
| 102 | } |
| 103 | |
| 104 | fn legacy_fixture(path: &std::path::Path) -> Connection { |
| 105 | let conn = Connection::open(path).unwrap(); |
| 106 | conn.execute_batch("CREATE TABLE tasks(id TEXT PRIMARY KEY,task_type TEXT NOT NULL,payload TEXT NOT NULL,status TEXT NOT NULL,result TEXT,created_at TEXT NOT NULL,completed_at TEXT); |
| 107 | INSERT INTO tasks VALUES('legacy','consolidate_memory','preserve payload','running',NULL,'preserve timestamp',NULL);").unwrap(); |
| 108 | conn |
| 109 | } |
| 110 | fn migrate(path: &std::path::Path, quiescent: bool) -> std::process::Output { |
| 111 | let mut command = Command::new(env!("CARGO_BIN_EXE_aegis")); |
| 112 | command |
| 113 | .arg("migrate-legacy-tasks") |
| 114 | .arg("--db-path") |
| 115 | .arg(path); |
| 116 | if quiescent { |
| 117 | command.arg("--quiescent"); |
| 118 | } |
| 119 | command.output().unwrap() |
| 120 | } |
| 121 | |
| 122 | #[tokio::test] |
| 123 | async fn round3_explicit_legacy_migration_preserves_and_fails_unknown_once() { |
| 124 | let dir = tempfile::tempdir().unwrap(); |
| 125 | let path = dir.path().join("legacy.sqlite"); |
| 126 | let observer = legacy_fixture(&path); |
| 127 | assert!( |
| 128 | Database::open(&path).is_err(), |
| 129 | "normal startup must fail closed without migration" |
| 130 | ); |
| 131 | let refused = migrate(&path, false); |
| 132 | assert!( |
| 133 | !refused.status.success(), |
| 134 | "explicit quiescence acknowledgement is required" |
| 135 | ); |
| 136 | assert_eq!(state(&observer, "legacy").0, "running"); |
| 137 | assert_eq!(events(&observer), 0); |
| 138 | let migrated = migrate(&path, true); |
| 139 | assert!( |
| 140 | migrated.status.success(), |
| 141 | "{}", |
| 142 | String::from_utf8_lossy(&migrated.stderr) |
| 143 | ); |
| 144 | let db = Arc::new(Database::open(&path).unwrap()); |
| 145 | assert_eq!( |
| 146 | state(&observer, "legacy"), |
| 147 | ("failed".into(), Some("abandoned: outcome unknown".into())) |
| 148 | ); |
| 149 | let (payload, created, claim, owner): (String, String, String, String) = observer |
| 150 | .query_row( |
| 151 | "SELECT payload,created_at,claim_id,owner_id FROM tasks WHERE id='legacy'", |
| 152 | [], |
| 153 | |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)), |
| 154 | ) |
| 155 | .unwrap(); |
| 156 | assert_eq!(payload, "preserve payload"); |
| 157 | assert_eq!(created, "preserve timestamp"); |
| 158 | assert!(uuid::Uuid::parse_str(&claim).is_ok()); |
| 159 | assert!(uuid::Uuid::parse_str(&owner).is_ok()); |
| 160 | assert_eq!(events(&observer), 1); |
| 161 | assert_eq!( |
| 162 | HeartbeatEngine::new(60, db.clone()) |
| 163 | .pulse_once() |
| 164 | .await |
| 165 | .actions_dispatched, |
| 166 | 0 |
| 167 | ); |
| 168 | drop(db); |
| 169 | assert!(migrate(&path, true).status.success()); |
| 170 | assert_eq!(events(&observer), 1); |
| 171 | } |
| 172 | |
| 173 | #[test] |
| 174 | fn round3_legacy_migration_rolls_back_claim_metadata_and_terminal_event_together() { |
| 175 | let dir = tempfile::tempdir().unwrap(); |
| 176 | let path = dir.path().join("legacy.sqlite"); |
| 177 | let observer = legacy_fixture(&path); |
| 178 | assert!(Database::open(&path).is_err()); |
| 179 | observer.execute_batch("CREATE TRIGGER reject_migration_event BEFORE INSERT ON task_terminal_events BEGIN SELECT RAISE(FAIL,'injected migration event failure'); END;").unwrap(); |
| 180 | let result = migrate(&path, true); |
| 181 | assert!(!result.status.success()); |
| 182 | assert!(String::from_utf8_lossy(&result.stderr).contains("injected migration event failure")); |
| 183 | assert_eq!(state(&observer, "legacy").0, "running"); |
| 184 | let metadata: (Option<String>, Option<String>) = observer |
| 185 | .query_row( |
| 186 | "SELECT claim_id,owner_id FROM tasks WHERE id='legacy'", |
| 187 | [], |
| 188 | |r| Ok((r.get(0)?, r.get(1)?)), |
| 189 | ) |
| 190 | .unwrap(); |
| 191 | assert_eq!(metadata, (None, None)); |
| 192 | assert_eq!(events(&observer), 0); |
| 193 | observer |
| 194 | .execute_batch("DROP TRIGGER reject_migration_event") |
| 195 | .unwrap(); |
| 196 | assert!(migrate(&path, true).status.success()); |
| 197 | assert_eq!(events(&observer), 1); |
| 198 | } |
| 199 | |
| 200 | #[test] |
| 201 | fn round3_legacy_migration_refuses_a_live_owner_even_with_acknowledgement() { |
| 202 | let dir = tempfile::tempdir().unwrap(); |
| 203 | let path = dir.path().join("legacy.sqlite"); |
| 204 | let db = Database::open(&path).unwrap(); |
| 205 | let observer = Connection::open(&path).unwrap(); |
| 206 | observer.execute("INSERT INTO tasks(id,task_type,payload,status,created_at) VALUES('legacy','consolidate_memory','','running','now')",[]).unwrap(); |
| 207 | let refused = migrate(&path, true); |
| 208 | assert!(!refused.status.success()); |
| 209 | assert!(String::from_utf8_lossy(&refused.stderr).contains("live task owner")); |
| 210 | assert_eq!(state(&observer, "legacy").0, "running"); |
| 211 | drop(db); |
| 212 | assert!(migrate(&path, true).status.success()); |
| 213 | } |
| 214 | |
| 215 | #[tokio::test] |
| 216 | async fn round3_receipt_projection_failure_without_tasks_matches_sqlite_and_broadcast() { |
| 217 | let dir = tempfile::tempdir().unwrap(); |
| 218 | let path = dir.path().join("receipt.sqlite"); |
| 219 | let db = Arc::new(Database::open(&path).unwrap()); |
| 220 | let observer = Connection::open(&path).unwrap(); |
| 221 | std::fs::create_dir(dir.path().join("transcript.jsonl")).unwrap(); |
| 222 | let engine = HeartbeatEngine::new(60, db); |
| 223 | let mut rx = engine.subscribe(); |
| 224 | let receipt = engine.pulse_once().await; |
| 225 | assert_eq!(receipt.status, "degraded"); |
| 226 | let stored: Value = observer.query_row("SELECT tick_id,timestamp,status,tasks_scanned,actions_dispatched,notes FROM heartbeats WHERE tick_id=?1",[receipt.tick_id],|r|Ok(json!({"tick_id":r.get::<_,u64>(0)?,"timestamp":r.get::<_,String>(1)?,"status":r.get::<_,String>(2)?,"tasks_scanned":r.get::<_,usize>(3)?,"actions_dispatched":r.get::<_,usize>(4)?,"notes":r.get::<_,String>(5)?}))).unwrap(); |
| 227 | assert_eq!(stored, serde_json::to_value(&receipt).unwrap()); |
| 228 | assert_eq!( |
| 229 | serde_json::to_value(rx.recv().await.unwrap()).unwrap(), |
| 230 | stored |
| 231 | ); |
| 232 | assert_eq!(events(&observer), 0); |
| 233 | } |
| 234 | |
| 235 | struct PendingHealth(AtomicUsize); |
| 236 | #[async_trait::async_trait] |
| 237 | impl InferenceEngine for PendingHealth { |
| 238 | fn model_id(&self) -> String { |
| 239 | "pending-health".into() |
| 240 | } |
| 241 | fn endpoint(&self) -> String { |
| 242 | "test-only".into() |
| 243 | } |
| 244 | async fn generate_with_tokens( |
| 245 | &self, |
| 246 | _: &str, |
| 247 | _: Option<&str>, |
| 248 | _: Option<f32>, |
| 249 | _: Option<u32>, |
| 250 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { |
| 251 | unreachable!() |
| 252 | } |
| 253 | async fn generate_chat( |
| 254 | &self, |
| 255 | _: &[Value], |
| 256 | _: Option<f32>, |
| 257 | _: Option<u32>, |
| 258 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { |
| 259 | unreachable!() |
| 260 | } |
| 261 | async fn generate_chat_with_tools( |
| 262 | &self, |
| 263 | _: &[Value], |
| 264 | _: Option<&[Value]>, |
| 265 | _: Option<f32>, |
| 266 | _: Option<u32>, |
| 267 | ) -> Result<ChatTurnResponse, Box<dyn std::error::Error + Send + Sync>> { |
| 268 | unreachable!() |
| 269 | } |
| 270 | async fn stream_chat( |
| 271 | &self, |
| 272 | _: &[Value], |
| 273 | _: Option<f32>, |
| 274 | _: Option<u32>, |
| 275 | ) -> Result<ChatStream, Box<dyn std::error::Error + Send + Sync>> { |
| 276 | unreachable!() |
| 277 | } |
| 278 | async fn check_health(&self) -> bool { |
| 279 | self.0.fetch_add(1, Ordering::SeqCst); |
| 280 | std::future::pending().await |
| 281 | } |
| 282 | } |
| 283 | #[tokio::test(start_paused = true)] |
| 284 | async fn round3_health_deadline_fails_once_and_later_pulses_continue() { |
| 285 | let dir = tempfile::tempdir().unwrap(); |
| 286 | let path = dir.path().join("deadline.sqlite"); |
| 287 | let db = Arc::new(Database::open(&path).unwrap()); |
| 288 | let observer = Connection::open(&path).unwrap(); |
| 289 | db.create_task("never", "model_health", "").unwrap(); |
| 290 | let health = Arc::new(PendingHealth(AtomicUsize::new(0))); |
| 291 | let engine = Arc::new(HeartbeatEngine::with_inference( |
| 292 | 60, |
| 293 | db.clone(), |
| 294 | health.clone(), |
| 295 | )); |
| 296 | let mut rx = engine.subscribe(); |
| 297 | let action_engine = engine.clone(); |
| 298 | let action = tokio::spawn(async move { action_engine.pulse_once().await }); |
| 299 | while health.0.load(Ordering::SeqCst) == 0 { |
| 300 | tokio::task::yield_now().await; |
| 301 | } |
| 302 | tokio::time::advance(Duration::from_secs(30)).await; |
| 303 | tokio::time::resume(); |
| 304 | let receipt = tokio::time::timeout(Duration::from_secs(2), action) |
| 305 | .await |
| 306 | .expect("health action must have its own deadline") |
| 307 | .unwrap(); |
| 308 | assert_eq!(receipt.status, "degraded"); |
| 309 | assert_eq!(rx.recv().await.unwrap().status, "degraded"); |
| 310 | let failed = state(&observer, "never"); |
| 311 | assert_eq!(failed.0, "failed"); |
| 312 | assert!(failed.1.unwrap().contains("deadline")); |
| 313 | assert_eq!(events(&observer), 1); |
| 314 | db.create_task("next", "system_telemetry", "").unwrap(); |
| 315 | let next = engine.pulse_once().await; |
| 316 | assert_eq!(next.status, "nominal"); |
| 317 | assert_eq!(next.actions_dispatched, 1); |
| 318 | assert_eq!(health.0.load(Ordering::SeqCst), 1); |
| 319 | assert_eq!( |
| 320 | events(&observer), |
| 321 | 2, |
| 322 | "one deadline failure and one successful subsequent action" |
| 323 | ); |
| 324 | } |