Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aegis-runtime-mv/blob/main/src/persistence/task_lifecycle.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aegis-runtime-mv / src / persistence / task_lifecycle.rs` 451 lines ยท 16191 bytes Raw Blame History 1 //! Local task claims and the durable terminal-event outbox. Retrying persistence never replays work. 2 use super::legacy::Database; 3 use chrono::Utc; 4 use rusqlite::{params, TransactionBehavior}; 5 use std::collections::HashSet; 6 use std::fs::{File, OpenOptions}; 7 use std::io::{Read, Seek, SeekFrom, Write}; 8 use std::os::fd::AsRawFd; 9 use std::os::unix::fs::OpenOptionsExt; 10 use std::path::{Path, PathBuf}; 11 use std::sync::{Arc, Mutex}; 12 use uuid::Uuid; 13 14 type DbResult = Result; 15 16 fn io_error(error: std::io::Error) -> rusqlite::Error { 17 rusqlite::Error::ToSqlConversionFailure(Box::new(error)) 18 } 19 20 fn refused(message: &str) -> rusqlite::Error { 21 io_error(std::io::Error::other(message)) 22 } 23 24 pub(crate) fn lock_file(path: &Path, nonblocking: bool) -> std::io::Result { 25 let file = OpenOptions::new() 26 .create(true) 27 .truncate(false) 28 .read(true) 29 .write(true) 30 .mode(0o600) 31 .open(path)?; 32 let flags = libc::LOCK_EX | if nonblocking { libc::LOCK_NB } else { 0 }; 33 // The owned descriptor stays alive for the whole protected operation or owner lifetime. 34 if unsafe { libc::flock(file.as_raw_fd(), flags) } != 0 { 35 return Err(std::io::Error::last_os_error()); 36 } 37 Ok(file) 38 } 39 40 #[derive(Clone, Debug)] 41 pub struct TaskClaim { 42 pub id: String, 43 pub token: String, 44 pub owner: String, 45 } 46 47 pub(crate) struct TaskOwner { 48 id: String, 49 directory: Option, 50 _lock: Option, 51 pending: Mutex>, 52 } 53 54 impl TaskOwner { 55 pub(crate) fn new(path: Option<&Path>) -> DbResult { 56 let id = Uuid::new_v4().to_string(); 57 let directory = path 58 .map(|path| { 59 let canonical = std::fs::canonicalize(path)?; 60 let mut name = canonical.as_os_str().to_os_string(); 61 name.push(".task-owners"); 62 let directory = PathBuf::from(name); 63 std::fs::create_dir_all(&directory)?; 64 Ok::<_, std::io::Error>(directory) 65 }) 66 .transpose() 67 .map_err(io_error)?; 68 let lock = directory 69 .as_ref() 70 .map(|dir| lock_file(&dir.join(&id), true)) 71 .transpose() 72 .map_err(io_error)?; 73 Ok(Self { 74 id, 75 directory, 76 _lock: lock, 77 pending: Mutex::new(Vec::new()), 78 }) 79 } 80 } 81 82 struct TerminalOutcome { 83 claim: TaskClaim, 84 success: bool, 85 result: String, 86 timestamp: String, 87 event_id: String, 88 } 89 90 impl TerminalOutcome { 91 fn new(claim: TaskClaim, result: Result) -> Self { 92 let (success, result) = match result { 93 Ok(text) => (true, text), 94 Err(text) => (false, text), 95 }; 96 Self { 97 claim, 98 success, 99 result, 100 timestamp: Utc::now().to_rfc3339(), 101 event_id: Uuid::new_v4().to_string(), 102 } 103 } 104 } 105 106 #[derive(Default)] 107 pub(crate) struct TaskFlushSummary { 108 pub completed: usize, 109 pub failed: usize, 110 } 111 112 /// A cancelled pulse cannot silently forget a claimed task while its owner remains alive. 113 pub(crate) struct TaskExecution<'a> { 114 db: &'a Database, 115 claim: Option, 116 } 117 118 impl TaskExecution<'_> { 119 pub(crate) fn finish(mut self, outcome: Result) { 120 self.db 121 .retain_task_outcome(self.claim.take().unwrap(), outcome); 122 } 123 } 124 125 impl Drop for TaskExecution<'_> { 126 fn drop(&mut self) { 127 if let Some(claim) = self.claim.take() { 128 self.db 129 .retain_task_outcome(claim, Err("abandoned: outcome unknown".into())); 130 } 131 } 132 } 133 134 impl Database { 135 pub fn claim_task(&self, id: &str) -> DbResult> { 136 let claim = TaskClaim { 137 id: id.into(), 138 token: Uuid::new_v4().to_string(), 139 owner: self.owner.id.clone(), 140 }; 141 let conn = self.conn.lock().unwrap(); 142 let changed = conn.execute( 143 "UPDATE tasks SET status='running', claim_id=?2, owner_id=?3 WHERE id=?1 AND status='pending'", 144 params![id, claim.token, claim.owner], 145 )?; 146 Ok((changed == 1).then_some(claim)) 147 } 148 149 pub(crate) fn hold_claim(&self, claim: TaskClaim) -> TaskExecution<'_> { 150 TaskExecution { 151 db: self, 152 claim: Some(claim), 153 } 154 } 155 156 fn retain_task_outcome(&self, claim: TaskClaim, result: Result) { 157 self.owner 158 .pending 159 .lock() 160 .unwrap() 161 .push(TerminalOutcome::new(claim, result)); 162 } 163 164 /// Retries immutable outcomes before scanning new tasks, even when there is no queued work. 165 pub(crate) fn retry_task_outcomes(&self) -> DbResult { 166 let mut pending = self.owner.pending.lock().unwrap(); 167 let mut first_error = None; 168 let mut summary = TaskFlushSummary::default(); 169 pending.retain(|outcome| match self.commit_terminal(outcome) { 170 Ok(()) => { 171 if outcome.success { 172 summary.completed += 1; 173 } else { 174 summary.failed += 1; 175 } 176 false 177 } 178 Err(error) => { 179 if first_error.is_none() { 180 first_error = Some(error); 181 } 182 true 183 } 184 }); 185 drop(pending); 186 let export = self.export_terminal_events(); 187 if let Some(error) = first_error { 188 Err(error) 189 } else { 190 export.map(|()| summary) 191 } 192 } 193 194 pub fn complete_task(&self, claim: &TaskClaim, result: &str) -> DbResult<()> { 195 self.commit_terminal(&TerminalOutcome::new(claim.clone(), Ok(result.into())))?; 196 self.export_terminal_events() 197 } 198 199 pub fn fail_task(&self, claim: &TaskClaim, error: &str) -> DbResult<()> { 200 self.commit_terminal(&TerminalOutcome::new(claim.clone(), Err(error.into())))?; 201 self.export_terminal_events() 202 } 203 204 fn commit_terminal(&self, outcome: &TerminalOutcome) -> DbResult<()> { 205 let mut conn = self.conn.lock().unwrap(); 206 let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; 207 Self::write_terminal(&tx, outcome)?; 208 tx.commit() 209 } 210 211 fn write_terminal(tx: &rusqlite::Transaction<'_>, outcome: &TerminalOutcome) -> DbResult<()> { 212 let status = if outcome.success { 213 "completed" 214 } else { 215 "failed" 216 }; 217 let changed = tx.execute( 218 "UPDATE tasks SET status=?1, result=?2, completed_at=?3 WHERE id=?4 AND status='running' AND claim_id=?5 AND owner_id=?6", 219 params![ 220 status, 221 outcome.result, 222 outcome.success.then_some(&outcome.timestamp), 223 outcome.claim.id, 224 outcome.claim.token, 225 outcome.claim.owner 226 ], 227 )?; 228 if changed != 1 { 229 return Err(refused( 230 "task finalization refused: stale claim or terminal task", 231 )); 232 } 233 let event_type = if outcome.success { 234 "task_completed" 235 } else { 236 "task_failed" 237 }; 238 let data = if outcome.success { 239 serde_json::json!({ 240 "id": outcome.claim.id, 241 "result": outcome.result, 242 "completed_at": outcome.timestamp 243 }) 244 } else { 245 serde_json::json!({ 246 "id": outcome.claim.id, 247 "error": outcome.result, 248 "failed_at": outcome.timestamp 249 }) 250 }; 251 let event = serde_json::json!({ 252 "event_id": outcome.event_id, 253 "timestamp": outcome.timestamp, 254 "event_type": event_type, 255 "claim_id": outcome.claim.token, 256 "data": data 257 }) 258 .to_string(); 259 tx.execute( 260 "INSERT INTO task_terminal_events(event_id,task_id,claim_id,event_json,exported) VALUES(?1,?2,?3,?4,0)", 261 params![outcome.event_id, outcome.claim.id, outcome.claim.token, event], 262 )?; 263 Ok(()) 264 } 265 266 /// A live owner's lock is never stolen. Unknown legacy owners need a quiescent migration. 267 pub(crate) fn recover_abandoned_tasks(&self) -> DbResult { 268 let claims: Vec = { 269 let conn = self.conn.lock().unwrap(); 270 let unknown: i64 = conn.query_row( 271 "SELECT count(*) FROM tasks WHERE status='running' AND (owner_id IS NULL OR claim_id IS NULL)", 272 [], 273 |row| row.get(0), 274 )?; 275 if unknown != 0 { 276 return Err(refused( 277 "ownerless running tasks require a quiescent migration; outcomes unknown", 278 )); 279 } 280 let mut stmt = 281 conn.prepare("SELECT id,claim_id,owner_id FROM tasks WHERE status='running'")?; 282 let rows = stmt.query_map([], |row| { 283 Ok(TaskClaim { 284 id: row.get(0)?, 285 token: row.get(1)?, 286 owner: row.get(2)?, 287 }) 288 })?; 289 rows.collect::>()? 290 }; 291 let mut recovered = 0; 292 if let Some(directory) = &self.owner.directory { 293 for claim in claims { 294 if claim.owner == self.owner.id { 295 continue; 296 } 297 Uuid::parse_str(&claim.owner) 298 .map_err(|_| refused("invalid task owner identity"))?; 299 let _dead_owner = match lock_file(&directory.join(&claim.owner), true) { 300 Ok(lock) => lock, 301 Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => continue, 302 Err(error) => return Err(io_error(error)), 303 }; 304 let still_running: bool = self.conn.lock().unwrap().query_row( 305 "SELECT EXISTS(SELECT 1 FROM tasks WHERE id=?1 AND status='running' AND claim_id=?2 AND owner_id=?3)", 306 params![claim.id, claim.token, claim.owner], 307 |row| row.get(0), 308 )?; 309 if !still_running { 310 continue; 311 } 312 self.commit_terminal(&TerminalOutcome::new( 313 claim, 314 Err("abandoned: outcome unknown".into()), 315 ))?; 316 recovered += 1; 317 } 318 } 319 Ok(recovered) 320 } 321 322 /// Operator-only migration. All old and new task writers must be stopped first. 323 /// `quiescent` acknowledges that pre-claim binaries cannot be detected with owner locks. 324 pub fn migrate_legacy_running_tasks(path: &Path, quiescent: bool) -> DbResult { 325 if !quiescent { 326 return Err(refused( 327 "legacy migration requires --quiescent after stopping all task writers", 328 )); 329 } 330 // A mistyped path must not create a new database and appear to migrate successfully. 331 let conn = rusqlite::Connection::open_with_flags( 332 path, 333 rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE, 334 )?; 335 let db = Self { 336 conn: Arc::new(Mutex::new(conn)), 337 transcript_path: path.parent().map(|parent| parent.join("transcript.jsonl")), 338 owner: TaskOwner::new(Some(path))?, 339 }; 340 let mut owner_locks = Vec::new(); 341 for entry in std::fs::read_dir(db.owner.directory.as_ref().unwrap()).map_err(io_error)? { 342 let entry = entry.map_err(io_error)?; 343 let name = entry.file_name(); 344 let name = name 345 .to_str() 346 .ok_or_else(|| refused("invalid task owner identity"))?; 347 Uuid::parse_str(name).map_err(|_| refused("invalid task owner identity"))?; 348 if name == db.owner.id { 349 continue; 350 } 351 match lock_file(&entry.path(), true) { 352 Ok(lock) => owner_locks.push(lock), 353 Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { 354 return Err(refused( 355 "legacy migration refused: live task owner; stop all task writers", 356 )); 357 } 358 Err(error) => return Err(io_error(error)), 359 } 360 } 361 db.init_tables()?; 362 let migrated = { 363 let mut conn = db.conn.lock().unwrap(); 364 let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; 365 let ids = { 366 let mut stmt = tx.prepare("SELECT id FROM tasks WHERE status='running' AND (owner_id IS NULL OR claim_id IS NULL)")?; 367 let rows = stmt.query_map([], |row| row.get::<_, String>(0))?; 368 rows.collect::>>()? 369 }; 370 for id in &ids { 371 let claim = TaskClaim { 372 id: id.clone(), 373 token: Uuid::new_v4().to_string(), 374 owner: db.owner.id.clone(), 375 }; 376 let changed = tx.execute( 377 "UPDATE tasks SET claim_id=?2,owner_id=?3 WHERE id=?1 AND status='running' AND (owner_id IS NULL OR claim_id IS NULL)", 378 params![claim.id, claim.token, claim.owner], 379 )?; 380 if changed != 1 { 381 return Err(refused("legacy migration refused: task changed")); 382 } 383 Self::write_terminal( 384 &tx, 385 &TerminalOutcome::new(claim, Err("abandoned: outcome unknown".into())), 386 )?; 387 } 388 tx.commit()?; 389 ids.len() 390 }; 391 db.export_terminal_events()?; 392 drop(owner_locks); 393 Ok(migrated) 394 } 395 396 /// SQLite is authoritative. JSONL is a retryable projection identified by stable event IDs. 397 pub(crate) fn export_terminal_events(&self) -> DbResult<()> { 398 let Some(path) = &self.transcript_path else { 399 return Ok(()); 400 }; 401 let conn = self.conn.lock().unwrap(); 402 let mut stmt = conn.prepare( 403 "SELECT event_id,event_json FROM task_terminal_events WHERE exported=0 ORDER BY rowid", 404 )?; 405 let rows = stmt.query_map([], |row| { 406 Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) 407 })?; 408 let events = rows.collect::>>()?; 409 if events.is_empty() { 410 return Ok(()); 411 } 412 let _writer = lock_file(&path.with_extension("jsonl.lock"), false).map_err(io_error)?; 413 let mut file = OpenOptions::new() 414 .create(true) 415 .truncate(false) 416 .read(true) 417 .write(true) 418 .open(path) 419 .map_err(io_error)?; 420 let mut bytes = Vec::new(); 421 file.read_to_end(&mut bytes).map_err(io_error)?; 422 // Discard only an interrupted trailing append; committed complete records are immutable. 423 let end = bytes 424 .iter() 425 .rposition(|b| *b == b'\n') 426 .map_or(0, |pos| pos + 1); 427 file.set_len(end as u64).map_err(io_error)?; 428 file.seek(SeekFrom::End(0)).map_err(io_error)?; 429 let seen: HashSet = bytes[..end] 430 .split(|b| *b == b'\n') 431 .filter_map(|line| serde_json::from_slice::(line).ok()) 432 .filter_map(|event| { 433 event 434 .get("event_id") 435 .and_then(|id| id.as_str()) 436 .map(str::to_owned) 437 }) 438 .collect(); 439 for (id, json) in events { 440 if !seen.contains(&id) { 441 writeln!(file, "{json}").map_err(io_error)?; 442 file.sync_all().map_err(io_error)?; 443 } 444 conn.execute( 445 "UPDATE task_terminal_events SET exported=1 WHERE event_id=?1", 446 params![id], 447 )?; 448 } 449 Ok(()) 450 } 451 }