diff --git a/Cargo.toml b/Cargo.toml index 1b3afdd..ac3f680 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ aien-inference-protocol = { path = "../aien-protocols/crates/aien-inference-prot aien-inference-client = { path = "../aien-protocols/crates/aien-inference-client" } [dev-dependencies] +tokio = { version = "1.40", features = ["test-util"] } tempfile = "3.17" tokio-tungstenite = "0.24" diff --git a/README.md b/README.md index 74aaaa2..4246433 100644 --- a/README.md +++ b/README.md @@ -46,9 +46,18 @@ aegis-runtime is an attachment of [AienOS](https://github.com/aien-dev/aienix), 1. **Axum control plane** (`src/gateway.rs`). WebSockets (`/ws`, `/api/v1/ws`), server-sent events (`/api/v1/events`, `/events`), and REST on port 18096: `/health`, `/api/v1/health`, `/api/v1/chat`, `/api/v1/agent/run`, `/api/v1/heartbeat/tick`, `/api/v1/tasks`, `/api/v1/skills`, `/api/v1/skills/execute`, `/api/v1/shell`, `/api/v1/discord/relay`, plus OpenAI-style `/v1/chat/completions` and `/v1/models`, and `/v1/probe`. + Agent runs return `status: "completed"` only for nonempty terminal text with finish reason `stop` and no terminal tool failure. Failed attempts recovered by the configured retry policy do not count as terminal failures. Truncated (`length`), empty-text and turn-budget-limited results are `incomplete`; an empty inference choices array is an execution error, not a synthesized answer. The producer and workflow adapter share the terminal-tool-failure classifier. HTTP 200 means the run returned a result, not that its objective completed. WebSocket `agent_result` messages carry the same top-level status and retain `result.completed`; execution errors remain `agent_error`. 2. **Heartbeat engine** (`src/heartbeat.rs`). - A polling loop that claims each pending task before running it, runs it, and emits a pulse receipt. + A polling loop that claims each pending task before running it and emits a pulse receipt. Only successful actions become `completed` tasks and `task_completed` transcript events. Unhealthy model checks, rejected or failed shell execution, failed memory writes, and unknown task types become `failed` tasks with the error in `result` and a `task_failed` event. Failed tasks are not automatically retried. A pulse is `degraded` if any action, task persistence operation, or queue read/claim fails, otherwise `nominal`; `actions_dispatched` counts claimed actions, not successful completions. + Claims carry fresh owner and claim IDs. Completion/failure updates require the matching running claim and refuse second terminal writes. Task state and one uniquely identified event commit in a single SQLite transaction (`task_terminal_events`). JSONL is a retryable projection of those stored events; consumers should deduplicate by `event_id`. An interrupted trailing append is discarded before retry. A transcript export or heartbeat receipt write failure degrades the returned/broadcast pulse; it does not undo a committed task outcome. A heartbeat receipt's JSONL projection failure changes its receipt and SQLite row to `degraded` before the receipt transaction commits, matching the returned receipt, broadcast and crumb command vector. + + Failed persistence retains the original outcome on the database owner for later pulses, including after replacing the heartbeat engine. Only persistence is retried, never task execution. Flushing a retained failure or cancellation degrades that pulse even when it dispatches no new work. Cancellation retains `abandoned: outcome unknown`; action panics become failures and do not kill the heartbeat loop. At open and before each pending-work scan, a per-owner lifetime `flock` distinguishes live owners from abandoned running claims, including a peer that dies after this database handle was opened. Dead-owner claims become failed with `abandoned: outcome unknown`, once, without replay. Lock files live beside the canonical database under `.task-owners` and are not unlinked while owners can reference them. + + Legacy running rows without owner/claim metadata fail closed during normal open. An operator must first stop **all** processes using this database, including old binaries that do not hold owner locks, and keep them stopped until migration exits. Then run `aegis migrate-legacy-tasks --db-path /absolute/path/to/aegis.sqlite --quiescent` before restarting the runtime. This explicit acknowledgement does not stop services for you. Migration additionally refuses detected live owners and never creates a missing database. It preserves legacy task identity, payload and creation time, assigns migration owner/claim IDs, and atomically marks every unknown running task `failed` with `abandoned: outcome unknown` plus one unique event. It never executes or requeues those tasks; rerunning it does not duplicate terminal events. A transcript projection failure can be retried by rerunning the same command after fixing the transcript path. + + Each model health action has a 15 second deadline, including a backend's `check_health` future. The direct HTTP fallback also has connection and total-request deadlines. Expiry records a failed unknown outcome without replay; later pulses can process other tasks. + 3. **Local model seat inference** (optional, `src/inference.rs`). With `--inference http`, requests go to the OpenAI-style endpoint given by `--model-url` (default `http://127.0.0.1:18006/v1/chat/completions`) with the model name `atlas-lightning-omni`. Without it, the mock backend (`MockInferenceClient` from aien-protocols) answers. `aegis status` then reports the backend as `mock-protocol-model`; the words "NativeTransformer" in that output name the mock, not a real model. diff --git a/src/agent.rs b/src/agent.rs index c86c0b0..c22c23b 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -55,6 +55,25 @@ pub struct AgentExecutionResult { pub completed: bool, } +/// Terminal failures exclude recovered attempts (`retry_failures` on a successful call). +/// Shared by the producer and workflow adapter so transport success cannot mask tool failure. +pub fn terminal_tool_failure(steps: &[AgentStep]) -> Option { + let calls = || steps.iter().flat_map(|step| step.tool_calls.iter()); + if let Some(failure) = calls().filter_map(|call| call.failure.as_ref()).next_back() { + return Some(ToolFault::new( + failure.class, + failure.effect_certainty, + failure.cause.first().map(|cause| cause.message.as_str()) + .unwrap_or("agent tool call failed"), + )); + } + calls().any(|call| !call.success).then(|| ToolFault::new( + FailureClass::Failed, + EffectCertainty::Uncertain, + "agent tool call failed without a failure record", + )) +} + #[derive(Clone)] pub struct AgentEngine { inference: Arc, @@ -248,6 +267,18 @@ impl AgentEngine { .await?; let thought = turn_res.reasoning.clone(); + if turn_res.finish_reason.as_deref() == Some("length") { + final_response = turn_res + .content + .filter(|content| !content.trim().is_empty()) + .unwrap_or_else(|| "Inference truncated before terminal output.".to_string()); + steps.push(AgentStep { + step_index: turn, + thought, + tool_calls: Vec::new(), + }); + break; + } let has_tool_calls = turn_res .tool_calls .as_ref() @@ -380,12 +411,12 @@ impl AgentEngine { } } else { let content = turn_res.content.unwrap_or_default(); - final_response = if !content.trim().is_empty() { - content - } else if let Some(r) = turn_res.reasoning { - r + let terminal_text = !content.trim().is_empty() + && turn_res.finish_reason.as_deref() == Some("stop"); + final_response = if content.trim().is_empty() { + "Inference ended without terminal text.".to_string() } else { - "Task processed with zero textual output.".to_string() + content }; steps.push(AgentStep { @@ -394,7 +425,7 @@ impl AgentEngine { tool_calls: Vec::new(), }); - completed = true; + completed = terminal_text && terminal_tool_failure(&steps).is_none(); break; } } diff --git a/src/gateway.rs b/src/gateway.rs index 83f37af..4713577 100644 --- a/src/gateway.rs +++ b/src/gateway.rs @@ -125,6 +125,7 @@ pub struct AgentRunRequest { #[derive(Serialize)] pub struct AgentRunResponse { + /// `completed` only for terminal output, otherwise `incomplete`. pub status: &'static str, pub prompt: String, pub final_response: String, @@ -146,7 +147,11 @@ pub async fn agent_run_handler( .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?; Ok(Json(AgentRunResponse { - status: "completed", + status: if result.completed { + "completed" + } else { + "incomplete" + }, prompt: payload.prompt, final_response: result.final_response, steps: result.steps, @@ -536,6 +541,7 @@ async fn handle_socket(mut socket: WebSocket, state: GatewayState) { Ok(exec_result) => { let out = json!({ "type": "agent_result", + "status": if exec_result.completed { "completed" } else { "incomplete" }, "result": exec_result, }); let _ = socket.send(Message::Text(out.to_string())).await; diff --git a/src/heartbeat.rs b/src/heartbeat.rs index c098852..e91acd1 100644 --- a/src/heartbeat.rs +++ b/src/heartbeat.rs @@ -1,4 +1,6 @@ use chrono::Utc; +use futures_util::FutureExt; +use std::panic::AssertUnwindSafe; use serde::{Deserialize, Serialize}; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; @@ -11,6 +13,16 @@ use crate::inference::InferenceEngine; use crate::persistence::Database; use crate::security::WorkspaceCapability; +const HEALTH_ACTION_TIMEOUT: Duration = Duration::from_secs(15); + +async fn http_model_health(endpoint: &str) -> Result { + let client = reqwest::Client::builder() + .connect_timeout(HEALTH_ACTION_TIMEOUT) + .timeout(HEALTH_ACTION_TIMEOUT) + .build()?; + Ok(client.get(endpoint).send().await?.status().is_success()) +} + #[derive(Serialize, Deserialize, Clone, Debug)] pub struct PulseReceipt { pub tick_id: u64, @@ -95,9 +107,24 @@ impl HeartbeatEngine { let tick = self.tick_counter.fetch_add(1, Ordering::SeqCst) + 1; let now = Utc::now().to_rfc3339(); + let mut degraded = match self.db.recover_abandoned_tasks() { + Ok(recovered) => recovered != 0, + Err(error) => { + warn!("Heartbeat could not recover abandoned claims: {}", error); + true + } + }; + degraded |= match self.db.retry_task_outcomes() { + Ok(summary) => summary.failed != 0, + Err(error) => { + warn!("Heartbeat retained finalization or transcript export for retry: {}", error); + true + } + }; let pending_tasks = match self.db.list_pending_tasks() { Ok(tasks) => tasks, Err(e) => { + degraded = true; warn!( "Heartbeat pulse #{} could not list pending tasks: {}", tick, e @@ -110,86 +137,100 @@ impl HeartbeatEngine { for task in pending_tasks { // Another pulse may have taken this task since the list was read. - match self.db.claim_task(&task.id) { - Ok(true) => {} - Ok(false) => continue, + let claim = match self.db.claim_task(&task.id) { + Ok(Some(claim)) => claim, + Ok(None) => continue, Err(e) => { + degraded = true; warn!("Heartbeat could not claim task {}: {}", task.id, e); continue; } - } - - let res_text = match task.task_type.as_str() { - // "max_health" is the former name, kept so tasks already queued under it still run. - "model_health" | "max_health" => { - let is_healthy = if let Some(ref inf) = self.inference { - inf.check_health().await - } else { - reqwest::Client::new() - .get("http://127.0.0.1:18006/v1/models") - .send() + }; + let execution = self.db.hold_claim(claim); + + let action = async { + match task.task_type.as_str() { + // "max_health" is the former name, kept so tasks already queued under it still run. + "model_health" | "max_health" => { + let health = async { + if let Some(ref inf) = self.inference { + inf.check_health().await + } else { + http_model_health("http://127.0.0.1:18006/v1/models").await.unwrap_or(false) + } + }; + let is_healthy = tokio::time::timeout(HEALTH_ACTION_TIMEOUT, health) .await - .map(|r| r.status().is_success()) - .unwrap_or(false) - }; - - if is_healthy { - "Local model seat verified ACTIVE on port 18006".to_string() - } else { - "Local model seat unreachable or offline on port 18006".to_string() + .map_err(|_| "Model health deadline exceeded: outcome unknown".to_string())?; + + if is_healthy { + Ok("Local model seat verified ACTIVE on port 18006".to_string()) + } else { + Err("Local model seat unreachable or offline on port 18006".to_string()) + } } - } - "build_monitor" | "shell_exec" => { - let cmd_to_run = if task.payload.is_empty() { - "echo 'empty build task'" - } else { - &task.payload - }; - - match self - .workspace - .dispatch_shell_gated(cmd_to_run, None, 15) - .await - { - Ok(stdout) => format!("Exit code 0: {}", stdout.trim()), - Err(e) => format!("Execution failure: {}", e), + "build_monitor" | "shell_exec" => { + let cmd_to_run = if task.payload.is_empty() { + "echo 'empty build task'" + } else { + &task.payload + }; + + match self + .workspace + .dispatch_shell_gated(cmd_to_run, None, 15) + .await + { + Ok(stdout) => Ok(format!("Exit code 0: {}", stdout.trim())), + Err(e) => Err(format!("Execution failure: {}", e)), + } } + "consolidate_memory" => { + let crumb_key = format!("consolidation_tick_{}", tick); + self.db + .store_crumb( + &crumb_key, + "Episodic memory consolidated into WAL", + "heartbeat", + ) + .map(|()| "Memory crumbs recorded".to_string()) + .map_err(|e| format!("Memory consolidation failure: {}", e)) + } + "system_telemetry" => Ok("System telemetry nominal: GB10 aarch64".to_string()), + _ => Err(format!("Unknown task type: {}", task.task_type)), } - "consolidate_memory" => { - let crumb_key = format!("consolidation_tick_{}", tick); - let _ = self.db.store_crumb( - &crumb_key, - "Episodic memory consolidated into WAL", - "heartbeat", - ); - "Memory crumbs recorded".to_string() - } - "system_telemetry" => "System telemetry nominal: GB10 aarch64".to_string(), - _ => "Autonomous task processed by heartbeat loop".to_string(), }; + let outcome = AssertUnwindSafe(action).catch_unwind().await + .unwrap_or_else(|_| Err("Task action panicked: outcome unknown".into())); - if let Err(e) = self.db.complete_task(&task.id, &res_text) { - warn!( - "Heartbeat could not record the result of task {}: {}", - task.id, e - ); - } + degraded |= outcome.is_err(); + execution.finish(outcome); actions += 1; } + degraded |= match self.db.retry_task_outcomes() { + Ok(summary) => summary.failed != 0, + Err(error) => { + warn!("Heartbeat retained finalization or transcript export for retry: {}", error); + true + } + }; - let receipt = PulseReceipt { + let mut receipt = PulseReceipt { tick_id: tick, timestamp: now, - status: "nominal", + status: if degraded { "degraded" } else { "nominal" }, tasks_scanned: tasks_count, actions_dispatched: actions, notes: format!( - "Autonomous tick #{} processed {} pending tasks", - tick, tasks_count + "Autonomous tick #{} scanned {} pending tasks, dispatched {} actions", + tick, tasks_count, actions ), }; - let _ = self.db.record_heartbeat_tick(&receipt); + if let Err(error) = self.db.record_heartbeat_tick(&mut receipt) { + receipt.status = "degraded"; + receipt.notes.push_str(&format!("; receipt persistence failed: {}", error)); + } let _ = self.tx_pulse.send(receipt.clone()); // Record operational pulse event to the Crumb ledger (.crumb) @@ -216,8 +257,8 @@ impl HeartbeatEngine { "Sovereign runtime heartbeat pulse", "--vector", &format!( - "Tick #{} nominal | tasks: {} | actions: {}", - tick, tasks_count, actions + "Tick #{} {} | tasks: {} | actions: {}", + tick, receipt.status, tasks_count, actions ), ".", ]) @@ -257,14 +298,53 @@ impl HeartbeatEngine { #[cfg(test)] mod tests { use super::*; + use crate::inference::{ChatStream, ChatTurnResponse}; + use serde_json::Value; + + struct HealthyProbe; + #[async_trait::async_trait] + impl InferenceEngine for HealthyProbe { + fn model_id(&self)->String { "test-health".into() } + fn endpoint(&self)->String { "test-only".into() } + async fn generate_with_tokens(&self,_:&str,_:Option<&str>,_:Option,_:Option)->Result> { unreachable!() } + async fn generate_chat(&self,_:&[Value],_:Option,_:Option)->Result> { unreachable!() } + async fn generate_chat_with_tools(&self,_:&[Value],_:Option<&[Value]>,_:Option,_:Option)->Result> { unreachable!() } + async fn stream_chat(&self,_:&[Value],_:Option,_:Option)->Result> { unreachable!() } + async fn check_health(&self)->bool { tokio::task::yield_now().await; true } + } + + #[tokio::test] + async fn test_http_health_client_deadline() { + use tokio::io::AsyncReadExt; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + let accepted = Arc::new(tokio::sync::Notify::new()); + let server_accepted = accepted.clone(); + let server = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await.unwrap(); + let mut request = [0; 1024]; + assert!(socket.read(&mut request).await.unwrap() != 0); + server_accepted.notify_one(); + std::future::pending::<()>().await; + drop(socket); + }); + let client = tokio::spawn(async move { http_model_health(&endpoint).await }); + tokio::time::timeout(Duration::from_secs(2), accepted.notified()).await.unwrap(); + tokio::time::pause(); + tokio::time::advance(HEALTH_ACTION_TIMEOUT).await; + tokio::time::resume(); + let result = tokio::time::timeout(Duration::from_secs(2), client).await; + server.abort(); + let error = result.expect("HTTP client must have its own request deadline").unwrap().unwrap_err(); + assert!(error.is_timeout()); + } #[tokio::test] async fn test_heartbeat_pulse_and_task_execution() { let db = Arc::new(Database::open_in_memory().unwrap()); - db.create_task("hb1", "model_health", "check").unwrap(); + db.create_task("hb1", "system_telemetry", "check").unwrap(); db.create_task("hb2", "consolidate_memory", "sync").unwrap(); - db.create_task("hb3", "shell_exec", "echo 'heartbeat task success'") - .unwrap(); + db.create_task("hb3", "shell_exec", "git status").unwrap(); let engine = HeartbeatEngine::new(60, db.clone()); let receipt = engine.pulse_once().await; @@ -286,7 +366,7 @@ mod tests { // The first pulse awaits the health probe while the second one lists // tasks, so both see the task unless the first one claimed it. - let engine = HeartbeatEngine::new(60, db.clone()); + let engine = HeartbeatEngine::with_inference(60, db.clone(), Arc::new(HealthyProbe)); let (a, b) = tokio::join!(engine.pulse_once(), engine.pulse_once()); assert_eq!(a.actions_dispatched + b.actions_dispatched, 1); diff --git a/src/inference.rs b/src/inference.rs index 9cd8459..d20a895 100644 --- a/src/inference.rs +++ b/src/inference.rs @@ -262,12 +262,7 @@ impl InferenceEngine for HttpInferenceBackend { finish_reason: choice.finish_reason, }); } - Ok(ChatTurnResponse { - content: Some("Zero response received from engine".to_string()), - reasoning: None, - tool_calls: None, - finish_reason: Some("stop".to_string()), - }) + Err(anyhow::anyhow!("Inference returned an empty choices array").into()) } else { let err_status = res.status(); let err_text = res.text().await.unwrap_or_default(); diff --git a/src/main.rs b/src/main.rs index 28d4068..16cb872 100644 --- a/src/main.rs +++ b/src/main.rs @@ -47,6 +47,14 @@ enum Commands { #[arg(long, default_value = "60")] heartbeat_secs: u64, }, + /// Fail unknown legacy running tasks without executing them. Stop every database writer first. + MigrateLegacyTasks { + #[arg(long, default_value = "aegis.sqlite")] + db_path: String, + /// Acknowledge all task writers, including old binaries, are stopped. + #[arg(long)] + quiescent: bool, + }, /// Run a single heartbeat tick immediately Tick { #[arg(long, default_value = "aegis.sqlite")] @@ -169,9 +177,10 @@ async fn main() -> Result<(), Box> { .finish(); tracing::subscriber::set_global_default(subscriber).ok(); - migrate_legacy_db_if_needed(); - let cli = Cli::parse(); + if !matches!(&cli.command, Some(Commands::MigrateLegacyTasks { .. })) { + migrate_legacy_db_if_needed(); + } match cli.command.unwrap_or(Commands::Serve { port: 18096, @@ -237,6 +246,10 @@ async fn main() -> Result<(), Box> { info!("Starting Axum sub-millisecond gateway on {}", addr); start_gateway(state, addr).await?; } + Commands::MigrateLegacyTasks { db_path, quiescent } => { + let migrated = Database::migrate_legacy_running_tasks(Path::new(&db_path), quiescent)?; + println!("Migrated {} legacy running tasks to failed: abandoned: outcome unknown", migrated); + } Commands::Tick { db_path } => { info!("Executing single autonomous heartbeat tick..."); let db = Arc::new(Database::open(Path::new(&db_path))?); diff --git a/src/orchestration/workflow.rs b/src/orchestration/workflow.rs index e9e6eae..c34ca7c 100644 --- a/src/orchestration/workflow.rs +++ b/src/orchestration/workflow.rs @@ -953,36 +953,12 @@ fn scrub_message(message: &str) -> String { /// This is the whole adapter seam: the agent already gates every tool call, /// so the DAG adds no authority here. pub fn agent_outcome(result: &crate::agent::AgentExecutionResult) -> TaskOutcome { - let last_failure = result - .steps - .iter() - .flat_map(|s| s.tool_calls.iter()) - .filter_map(|c| c.failure.as_ref()) - .next_back(); - if let Some(f) = last_failure { - if f.class == FailureClass::ApprovalPending { - return TaskOutcome::ApprovalPending; - } - let msg = f - .cause - .first() - .map(|c| c.message.clone()) - .unwrap_or_else(|| "agent tool call failed".into()); - return TaskOutcome::Failed(ToolFault::new(f.class, f.effect_certainty, msg)); - } - // Deny by default: a failed call with no provenance record (older - // records) is still a failure, and its effect is unknown. - let unrecorded_failure = result - .steps - .iter() - .flat_map(|s| s.tool_calls.iter()) - .any(|c| !c.success); - if unrecorded_failure { - return TaskOutcome::Failed(ToolFault::new( - FailureClass::Failed, - EffectCertainty::Uncertain, - "agent tool call failed without a failure record", - )); + if let Some(fault) = crate::agent::terminal_tool_failure(&result.steps) { + return if fault.class == FailureClass::ApprovalPending { + TaskOutcome::ApprovalPending + } else { + TaskOutcome::Failed(fault) + }; } if result.completed { TaskOutcome::Completed(serde_json::json!({ "final_response": result.final_response })) diff --git a/src/persistence/legacy.rs b/src/persistence/legacy.rs index 88ed2d4..e74677e 100644 --- a/src/persistence/legacy.rs +++ b/src/persistence/legacy.rs @@ -10,6 +10,7 @@ use tracing::info; use super::async_db::AsyncDatabase; use super::sqlite::schema::initialize_schema; use crate::heartbeat::PulseReceipt; +use super::task_lifecycle::{lock_file, TaskOwner}; #[derive(Serialize, Deserialize, Clone, Debug)] pub struct TaskRecord { @@ -42,8 +43,9 @@ pub struct TurnRecord { } pub struct Database { - conn: Arc>, - transcript_path: Option, + pub(super) conn: Arc>, + pub(super) transcript_path: Option, + pub(super) owner: TaskOwner, } impl Database { @@ -53,8 +55,11 @@ impl Database { let db = Self { conn: Arc::new(Mutex::new(conn)), transcript_path, + owner: TaskOwner::new(Some(path))?, }; db.init_tables()?; + db.recover_abandoned_tasks()?; + db.export_terminal_events()?; Ok(db) } @@ -63,6 +68,7 @@ impl Database { let db = Self { conn: Arc::new(Mutex::new(conn)), transcript_path: None, + owner: TaskOwner::new(None)?, }; db.init_tables()?; Ok(db) @@ -108,7 +114,7 @@ impl Database { "response": response, "duration_ms": duration_ms, }), - ); + )?; Ok(()) } @@ -138,9 +144,11 @@ impl Database { Ok(turns) } - pub fn record_heartbeat_tick(&self, receipt: &PulseReceipt) -> Result<(), rusqlite::Error> { - let conn = self.conn.lock().unwrap(); - conn.execute( + /// Projection failure changes the receipt before its authoritative SQLite transaction commits. + pub fn record_heartbeat_tick(&self, receipt: &mut PulseReceipt) -> Result<(), rusqlite::Error> { + let mut conn = self.conn.lock().unwrap(); + let tx = conn.transaction()?; + tx.execute( "INSERT OR REPLACE INTO heartbeats (tick_id, timestamp, status, tasks_scanned, actions_dispatched, notes) VALUES (?1, ?2, ?3, ?4, ?5, ?6)", params![ @@ -152,9 +160,16 @@ impl Database { receipt.notes ], )?; - - self.record_transcript("heartbeat_tick", &receipt); - Ok(()) + if let Err(error) = self.record_transcript("heartbeat_tick", receipt) { + receipt.status = "degraded"; + receipt.notes.push_str(&format!("; receipt projection failed: {}", error)); + tracing::warn!("Heartbeat transcript projection failed: {}", error); + tx.execute( + "UPDATE heartbeats SET status=?2,notes=?3 WHERE tick_id=?1", + params![receipt.tick_id as i64, receipt.status, receipt.notes], + )?; + } + tx.commit() } pub fn create_task( @@ -178,7 +193,7 @@ impl Database { "task_type": task_type, "payload": payload, }), - ); + )?; Ok(()) } @@ -207,35 +222,6 @@ impl Database { Ok(tasks) } - /// Moves a pending task to `running`. Returns `false` when another caller - /// already claimed it, so each task runs at most once. - pub fn claim_task(&self, id: &str) -> Result { - let conn = self.conn.lock().unwrap(); - let changed = conn.execute( - "UPDATE tasks SET status = 'running' WHERE id = ?1 AND status = 'pending'", - params![id], - )?; - Ok(changed == 1) - } - - pub fn complete_task(&self, id: &str, result: &str) -> Result<(), rusqlite::Error> { - let conn = self.conn.lock().unwrap(); - let now = Utc::now().to_rfc3339(); - conn.execute( - "UPDATE tasks SET status = 'completed', result = ?1, completed_at = ?2 WHERE id = ?3", - params![result, now, id], - )?; - - self.record_transcript( - "task_completed", - &serde_json::json!({ - "id": id, - "result": result, - "completed_at": now, - }), - ); - Ok(()) - } pub fn store_crumb( &self, @@ -258,7 +244,7 @@ impl Database { "value": value, "namespace": namespace, }), - ); + )?; Ok(()) } @@ -288,18 +274,21 @@ impl Database { Ok(crumbs) } - pub fn record_transcript(&self, event_type: &str, data: &T) { - if let Some(ref path) = self.transcript_path { + pub fn record_transcript(&self, event_type: &str, data: &T) -> Result<(), rusqlite::Error> { + if let Some(path) = &self.transcript_path { let event = serde_json::json!({ "timestamp": Utc::now().to_rfc3339(), "event_type": event_type, "data": data, }); - if let Ok(line) = serde_json::to_string(&event) { - if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) { - let _ = writeln!(file, "{}", line); - } - } + let write = || -> std::io::Result<()> { + let _writer = lock_file(&path.with_extension("jsonl.lock"), false)?; + let mut file = OpenOptions::new().create(true).append(true).open(path)?; + writeln!(file, "{}", event)?; + file.sync_all() + }; + write().map_err(|error| rusqlite::Error::ToSqlConversionFailure(Box::new(error)))?; } + Ok(()) } } diff --git a/src/persistence/mod.rs b/src/persistence/mod.rs index f96ea10..5ef4118 100644 --- a/src/persistence/mod.rs +++ b/src/persistence/mod.rs @@ -2,10 +2,12 @@ pub mod async_db; pub mod error; pub mod legacy; pub mod sqlite; +mod task_lifecycle; pub use async_db::AsyncDatabase; pub use error::PersistenceError; pub use legacy::{CrumbRecord, Database, TaskRecord, TurnRecord}; +pub use task_lifecycle::TaskClaim; pub use sqlite::{ SqliteActionStore, SqliteApprovalStore, SqliteMessageStore, SqliteRunStore, SqliteSessionStore, }; diff --git a/src/persistence/sqlite/schema.rs b/src/persistence/sqlite/schema.rs index e088d20..f00b9c2 100644 --- a/src/persistence/sqlite/schema.rs +++ b/src/persistence/sqlite/schema.rs @@ -123,6 +123,14 @@ pub fn initialize_schema(conn: &Connection) -> Result<(), rusqlite::Error> { completed_at TEXT ); + CREATE TABLE IF NOT EXISTS task_terminal_events ( + event_id TEXT PRIMARY KEY, + task_id TEXT NOT NULL UNIQUE, + claim_id TEXT NOT NULL, + event_json TEXT NOT NULL, + exported INTEGER NOT NULL DEFAULT 0 + ); + CREATE TABLE IF NOT EXISTS memory_crumbs ( key TEXT PRIMARY KEY, value TEXT NOT NULL, @@ -138,5 +146,15 @@ pub fn initialize_schema(conn: &Connection) -> Result<(), rusqlite::Error> { ); ", )?; + let columns = { + let mut stmt = conn.prepare("PRAGMA table_info(tasks)")?; + let rows = stmt.query_map([], |row| row.get::<_, String>(1))?; + rows.collect::, _>>()? + }; + for column in ["claim_id", "owner_id"] { + if !columns.iter().any(|name| name == column) { + conn.execute_batch(&format!("ALTER TABLE tasks ADD COLUMN {column} TEXT"))?; + } + } Ok(()) } diff --git a/src/persistence/task_lifecycle.rs b/src/persistence/task_lifecycle.rs new file mode 100644 index 0000000..1aebbb9 --- /dev/null +++ b/src/persistence/task_lifecycle.rs @@ -0,0 +1,400 @@ +//! Local task claims and the durable terminal-event outbox. Retrying persistence never replays work. +use super::legacy::Database; +use chrono::Utc; +use rusqlite::{params, TransactionBehavior}; +use std::collections::HashSet; +use std::fs::{File, OpenOptions}; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::os::fd::AsRawFd; +use std::os::unix::fs::OpenOptionsExt; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use uuid::Uuid; + +type DbResult = Result; + +fn io_error(error: std::io::Error) -> rusqlite::Error { + rusqlite::Error::ToSqlConversionFailure(Box::new(error)) +} + +fn refused(message: &str) -> rusqlite::Error { + io_error(std::io::Error::other(message)) +} + +pub(crate) fn lock_file(path: &Path, nonblocking: bool) -> std::io::Result { + let file = OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .mode(0o600) + .open(path)?; + let flags = libc::LOCK_EX | if nonblocking { libc::LOCK_NB } else { 0 }; + // The owned descriptor stays alive for the whole protected operation or owner lifetime. + if unsafe { libc::flock(file.as_raw_fd(), flags) } != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(file) +} + +#[derive(Clone, Debug)] +pub struct TaskClaim { + pub id: String, + pub token: String, + pub owner: String, +} + +pub(crate) struct TaskOwner { + id: String, + directory: Option, + _lock: Option, + pending: Mutex>, +} + +impl TaskOwner { + pub(crate) fn new(path: Option<&Path>) -> DbResult { + let id = Uuid::new_v4().to_string(); + let directory = path + .map(|path| { + let canonical = std::fs::canonicalize(path)?; + let mut name = canonical.as_os_str().to_os_string(); + name.push(".task-owners"); + let directory = PathBuf::from(name); + std::fs::create_dir_all(&directory)?; + Ok::<_, std::io::Error>(directory) + }) + .transpose() + .map_err(io_error)?; + let lock = directory + .as_ref() + .map(|dir| lock_file(&dir.join(&id), true)) + .transpose() + .map_err(io_error)?; + Ok(Self { + id, + directory, + _lock: lock, + pending: Mutex::new(Vec::new()), + }) + } +} + +struct TerminalOutcome { + claim: TaskClaim, + success: bool, + result: String, + timestamp: String, + event_id: String, +} + +impl TerminalOutcome { + fn new(claim: TaskClaim, result: Result) -> Self { + let (success, result) = match result { + Ok(text) => (true, text), + Err(text) => (false, text), + }; + Self { + claim, + success, + result, + timestamp: Utc::now().to_rfc3339(), + event_id: Uuid::new_v4().to_string(), + } + } +} + +#[derive(Default)] +pub(crate) struct TaskFlushSummary { + pub completed: usize, + pub failed: usize, +} + +/// A cancelled pulse cannot silently forget a claimed task while its owner remains alive. +pub(crate) struct TaskExecution<'a> { + db: &'a Database, + claim: Option, +} + +impl TaskExecution<'_> { + pub(crate) fn finish(mut self, outcome: Result) { + self.db + .retain_task_outcome(self.claim.take().unwrap(), outcome); + } +} + +impl Drop for TaskExecution<'_> { + fn drop(&mut self) { + if let Some(claim) = self.claim.take() { + self.db + .retain_task_outcome(claim, Err("abandoned: outcome unknown".into())); + } + } +} + +impl Database { + pub fn claim_task(&self, id: &str) -> DbResult> { + let claim = TaskClaim { + id: id.into(), + token: Uuid::new_v4().to_string(), + owner: self.owner.id.clone(), + }; + let conn = self.conn.lock().unwrap(); + let changed = conn.execute( + "UPDATE tasks SET status='running', claim_id=?2, owner_id=?3 WHERE id=?1 AND status='pending'", + params![id, claim.token, claim.owner], + )?; + Ok((changed == 1).then_some(claim)) + } + + pub(crate) fn hold_claim(&self, claim: TaskClaim) -> TaskExecution<'_> { + TaskExecution { + db: self, + claim: Some(claim), + } + } + + fn retain_task_outcome(&self, claim: TaskClaim, result: Result) { + self.owner + .pending + .lock() + .unwrap() + .push(TerminalOutcome::new(claim, result)); + } + + /// Retries immutable outcomes before scanning new tasks, even when there is no queued work. + pub(crate) fn retry_task_outcomes(&self) -> DbResult { + let mut pending = self.owner.pending.lock().unwrap(); + let mut first_error = None; + let mut summary = TaskFlushSummary::default(); + pending.retain(|outcome| match self.commit_terminal(outcome) { + Ok(()) => { + if outcome.success { summary.completed += 1; } else { summary.failed += 1; } + false + } + Err(error) => { + if first_error.is_none() { + first_error = Some(error); + } + true + } + }); + drop(pending); + let export = self.export_terminal_events(); + if let Some(error) = first_error { + Err(error) + } else { + export.map(|()| summary) + } + } + + pub fn complete_task(&self, claim: &TaskClaim, result: &str) -> DbResult<()> { + self.commit_terminal(&TerminalOutcome::new(claim.clone(), Ok(result.into())))?; + self.export_terminal_events() + } + + pub fn fail_task(&self, claim: &TaskClaim, error: &str) -> DbResult<()> { + self.commit_terminal(&TerminalOutcome::new(claim.clone(), Err(error.into())))?; + self.export_terminal_events() + } + + fn commit_terminal(&self, outcome: &TerminalOutcome) -> DbResult<()> { + let mut conn = self.conn.lock().unwrap(); + let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; + Self::write_terminal(&tx, outcome)?; + tx.commit() + } + + fn write_terminal(tx: &rusqlite::Transaction<'_>, outcome: &TerminalOutcome) -> DbResult<()> { + let status = if outcome.success { "completed" } else { "failed" }; + let changed = tx.execute( + "UPDATE tasks SET status=?1, result=?2, completed_at=?3 WHERE id=?4 AND status='running' AND claim_id=?5 AND owner_id=?6", + params![ + status, + outcome.result, + outcome.success.then_some(&outcome.timestamp), + outcome.claim.id, + outcome.claim.token, + outcome.claim.owner + ], + )?; + if changed != 1 { + return Err(refused("task finalization refused: stale claim or terminal task")); + } + let event_type = if outcome.success { "task_completed" } else { "task_failed" }; + let data = if outcome.success { + serde_json::json!({ + "id": outcome.claim.id, + "result": outcome.result, + "completed_at": outcome.timestamp + }) + } else { + serde_json::json!({ + "id": outcome.claim.id, + "error": outcome.result, + "failed_at": outcome.timestamp + }) + }; + let event = serde_json::json!({ + "event_id": outcome.event_id, + "timestamp": outcome.timestamp, + "event_type": event_type, + "claim_id": outcome.claim.token, + "data": data + }) + .to_string(); + tx.execute( + "INSERT INTO task_terminal_events(event_id,task_id,claim_id,event_json,exported) VALUES(?1,?2,?3,?4,0)", + params![outcome.event_id, outcome.claim.id, outcome.claim.token, event], + )?; + Ok(()) + } + + /// A live owner's lock is never stolen. Unknown legacy owners need a quiescent migration. + pub(crate) fn recover_abandoned_tasks(&self) -> DbResult { + let claims: Vec = { + let conn = self.conn.lock().unwrap(); + let unknown: i64 = conn.query_row( + "SELECT count(*) FROM tasks WHERE status='running' AND (owner_id IS NULL OR claim_id IS NULL)", + [], + |row| row.get(0), + )?; + if unknown != 0 { + return Err(refused("ownerless running tasks require a quiescent migration; outcomes unknown")); + } + let mut stmt = conn.prepare("SELECT id,claim_id,owner_id FROM tasks WHERE status='running'")?; + let rows = stmt.query_map([], |row| { + Ok(TaskClaim { + id: row.get(0)?, + token: row.get(1)?, + owner: row.get(2)?, + }) + })?; + rows.collect::>()? + }; + let mut recovered = 0; + if let Some(directory) = &self.owner.directory { + for claim in claims { + if claim.owner == self.owner.id { + continue; + } + Uuid::parse_str(&claim.owner).map_err(|_| refused("invalid task owner identity"))?; + let _dead_owner = match lock_file(&directory.join(&claim.owner), true) { + Ok(lock) => lock, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => continue, + Err(error) => return Err(io_error(error)), + }; + let still_running: bool = self.conn.lock().unwrap().query_row( + "SELECT EXISTS(SELECT 1 FROM tasks WHERE id=?1 AND status='running' AND claim_id=?2 AND owner_id=?3)", + params![claim.id, claim.token, claim.owner], + |row| row.get(0), + )?; + if !still_running { + continue; + } + self.commit_terminal(&TerminalOutcome::new( + claim, + Err("abandoned: outcome unknown".into()), + ))?; + recovered += 1; + } + } + Ok(recovered) + } + + /// Operator-only migration. All old and new task writers must be stopped first. + /// `quiescent` acknowledges that pre-claim binaries cannot be detected with owner locks. + pub fn migrate_legacy_running_tasks(path: &Path, quiescent: bool) -> DbResult { + if !quiescent { + return Err(refused("legacy migration requires --quiescent after stopping all task writers")); + } + // A mistyped path must not create a new database and appear to migrate successfully. + let conn = rusqlite::Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE)?; + let db = Self { + conn: Arc::new(Mutex::new(conn)), + transcript_path: path.parent().map(|parent| parent.join("transcript.jsonl")), + owner: TaskOwner::new(Some(path))?, + }; + let mut owner_locks = Vec::new(); + for entry in std::fs::read_dir(db.owner.directory.as_ref().unwrap()).map_err(io_error)? { + let entry = entry.map_err(io_error)?; + let name = entry.file_name(); + let name = name.to_str().ok_or_else(|| refused("invalid task owner identity"))?; + Uuid::parse_str(name).map_err(|_| refused("invalid task owner identity"))?; + if name == db.owner.id { continue; } + match lock_file(&entry.path(), true) { + Ok(lock) => owner_locks.push(lock), + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + return Err(refused("legacy migration refused: live task owner; stop all task writers")); + } + Err(error) => return Err(io_error(error)), + } + } + db.init_tables()?; + let migrated = { + let mut conn = db.conn.lock().unwrap(); + let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; + let ids = { + let mut stmt = tx.prepare("SELECT id FROM tasks WHERE status='running' AND (owner_id IS NULL OR claim_id IS NULL)")?; + let rows = stmt.query_map([], |row| row.get::<_, String>(0))?; + rows.collect::>>()? + }; + for id in &ids { + let claim = TaskClaim { id: id.clone(), token: Uuid::new_v4().to_string(), owner: db.owner.id.clone() }; + let changed = tx.execute( + "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)", + params![claim.id, claim.token, claim.owner], + )?; + if changed != 1 { return Err(refused("legacy migration refused: task changed")); } + Self::write_terminal(&tx, &TerminalOutcome::new(claim, Err("abandoned: outcome unknown".into())))?; + } + tx.commit()?; + ids.len() + }; + db.export_terminal_events()?; + drop(owner_locks); + Ok(migrated) + } + + /// SQLite is authoritative. JSONL is a retryable projection identified by stable event IDs. + pub(crate) fn export_terminal_events(&self) -> DbResult<()> { + let Some(path) = &self.transcript_path else { + return Ok(()); + }; + let conn = self.conn.lock().unwrap(); + let mut stmt = conn.prepare("SELECT event_id,event_json FROM task_terminal_events WHERE exported=0 ORDER BY rowid")?; + let rows = stmt.query_map([], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + })?; + let events = rows.collect::>>()?; + if events.is_empty() { + return Ok(()); + } + let _writer = lock_file(&path.with_extension("jsonl.lock"), false).map_err(io_error)?; + let mut file = OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(path) + .map_err(io_error)?; + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes).map_err(io_error)?; + // Discard only an interrupted trailing append; committed complete records are immutable. + let end = bytes.iter().rposition(|b| *b == b'\n').map_or(0, |pos| pos + 1); + file.set_len(end as u64).map_err(io_error)?; + file.seek(SeekFrom::End(0)).map_err(io_error)?; + let seen: HashSet = bytes[..end] + .split(|b| *b == b'\n') + .filter_map(|line| serde_json::from_slice::(line).ok()) + .filter_map(|event| event.get("event_id").and_then(|id| id.as_str()).map(str::to_owned)) + .collect(); + for (id, json) in events { + if !seen.contains(&id) { + writeln!(file, "{json}").map_err(io_error)?; + file.sync_all().map_err(io_error)?; + } + conn.execute("UPDATE task_terminal_events SET exported=1 WHERE event_id=?1", params![id])?; + } + Ok(()) + } +} diff --git a/tests/aegis_tests.rs b/tests/aegis_tests.rs index 828294a..805603f 100644 --- a/tests/aegis_tests.rs +++ b/tests/aegis_tests.rs @@ -1128,3 +1128,251 @@ async fn test_gateway_probe_endpoint() { assert_eq!(body["model"], "aien-sovereign-gb10"); assert!(body["answers"].as_array().is_some()); } + +#[tokio::test] +async fn completion_truth_http_turn_exhaustion_is_incomplete() { + let app = create_router(create_test_state().await); + let response = app + .oneshot( + Request::builder() + .method("POST") + .uri("/api/v1/agent/run") + .header("Authorization", auth_header()) + .header("Content-Type", "application/json") + .body(Body::from(r#"{"prompt":"no turn budget","max_turns":0}"#)) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let body: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(body["completed"], false); + assert!(body["final_response"] + .as_str() + .unwrap() + .contains("maximum turn limit (0)")); + assert_eq!(body["status"], "incomplete"); +} + +#[tokio::test] +async fn completion_truth_ws_turn_exhaustion_is_incomplete() { + let app = create_router(create_test_state().await); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let (mut ws, _) = tokio_tungstenite::connect_async(authed_ws_request(&format!( + "ws://{addr}/ws" + ))) + .await + .unwrap(); + ws.send(tokio_tungstenite::tungstenite::Message::Text( + r#"{"type":"agent_run","prompt":"no turn budget","max_turns":0}"#.into(), + )) + .await + .unwrap(); + let body: Value = loop { + let message = tokio::time::timeout(std::time::Duration::from_secs(5), ws.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + if let Ok(text) = message.to_text() { + let body: Value = serde_json::from_str(text).unwrap(); + if body["type"] == "agent_result" { + break body; + } + } + }; + ws.close(None).await.unwrap(); + server.abort(); + assert_eq!(body["result"]["completed"], false); + assert!(body["result"]["final_response"] + .as_str() + .unwrap() + .contains("maximum turn limit (0)")); + assert_eq!(body["status"], "incomplete"); +} + +async fn assert_heartbeat_completion_truth( + task_type: &str, + payload: &str, + reject_crumb: bool, + successful: bool, + expected_result: &str, +) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("aegis.sqlite"); + let db = Arc::new(Database::open(&path).unwrap()); + let observer = rusqlite::Connection::open(&path).unwrap(); + if reject_crumb { + observer + .execute_batch( + "CREATE TRIGGER reject_heartbeat_crumb BEFORE INSERT ON memory_crumbs + BEGIN SELECT RAISE(FAIL, 'injected crumb write failure'); END;", + ) + .unwrap(); + } + db.create_task("completion-truth", task_type, payload).unwrap(); + let mut health_server = None; + let engine = if task_type == "model_health" { + let app = axum::Router::new().route( + "/v1/models", + axum::routing::get(|| async { StatusCode::SERVICE_UNAVAILABLE }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + health_server = Some(tokio::spawn(async move { + axum::serve(listener, app).await.unwrap() + })); + HeartbeatEngine::with_inference( + 60, db, Arc::new(HttpInferenceBackend::new( + Some(format!("http://{addr}/v1/chat/completions")), None, + )), + ) + } else if task_type == "shell_exec" && !successful { + // `git status` is admitted, but fails in a workspace with no repository. + HeartbeatEngine::with_workspace( + 60, db, aegis::WorkspaceCapability::new(dir.path()).unwrap(), + ) + } else { + HeartbeatEngine::new(60, db) + }; + let receipt = engine.pulse_once().await; + if let Some(server) = health_server { + server.abort(); + } + assert_eq!(receipt.actions_dispatched, 1); + let (status, result): (String, String) = observer + .query_row( + "SELECT status, result FROM tasks WHERE id = 'completion-truth'", + [], + |row| Ok((row.get(0)?, row.get(1)?)), + ) + .unwrap(); + assert!(result.contains(expected_result), "{result}"); + assert_eq!(status, if successful { "completed" } else { "failed" }); + assert_eq!(receipt.status, if successful { "nominal" } else { "degraded" }); + let stored_status: String = observer + .query_row("SELECT status FROM heartbeats WHERE tick_id = 1", [], |row| row.get(0)) + .unwrap(); + assert_eq!(stored_status, receipt.status); + let transcript = std::fs::read_to_string(dir.path().join("transcript.jsonl")).unwrap(); + let events: Vec = transcript + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert!(events.iter().any(|event| event["event_type"] + == if successful { "task_completed" } else { "task_failed" })); + assert!(!events.iter().any(|event| event["event_type"] + == if successful { "task_failed" } else { "task_completed" })); + if reject_crumb { + assert!(!result.contains("Memory crumbs recorded")); + assert!(engine.pulse_once().await.status == "nominal"); + } +} + +#[tokio::test] +async fn completion_truth_heartbeat_shell_failure() { + assert_heartbeat_completion_truth("shell_exec", PROBE_ADMITTED_COMMAND, false, false, "Execution failure") + .await; +} + +#[tokio::test] +async fn completion_truth_heartbeat_crumb_failure() { + assert_heartbeat_completion_truth( + "consolidate_memory", "", true, false, "injected crumb write failure", + ) + .await; +} + +#[tokio::test] +async fn completion_truth_heartbeat_unknown_task_failure() { + assert_heartbeat_completion_truth("not-a-task", "", false, false, "Unknown task type").await; +} + +#[tokio::test] +async fn completion_truth_heartbeat_success() { + assert_heartbeat_completion_truth( + "consolidate_memory", "", false, true, "Memory crumbs recorded", + ) + .await; +} + +#[tokio::test] +async fn completion_truth_heartbeat_unhealthy_model_failure() { + assert_heartbeat_completion_truth( + "model_health", "", false, false, "unreachable or offline", + ) + .await; +} + +#[tokio::test] +async fn completion_truth_heartbeat_shell_success() { + assert_heartbeat_completion_truth( + "shell_exec", PROBE_ADMITTED_COMMAND, false, true, "Exit code 0", + ) + .await; +} + +#[tokio::test] +async fn completion_truth_http_executed_turn_budget_exhaustion() { + // A real inference turn produces a successful tool call, but never terminal output. + let app = axum::Router::new().route( + "/v1/chat/completions", + axum::routing::post(|| async { + axum::Json(serde_json::json!({ + "choices": [{ + "message": { + "content": null, + "tool_calls": [{ + "id": "inspect-once", + "type": "function", + "function": { + "name": "bash_eval", + "arguments": "{\"command\":\"git status\"}" + } + }] + }, + "finish_reason": "tool_calls" + }] + })) + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let mut state = create_test_state().await; + state.inference = Arc::new(HttpInferenceBackend::new( + Some(format!("http://{addr}/v1/chat/completions")), + None, + )); + state.agent = Arc::new(AgentEngine::new( + state.inference.clone(), state.skills.clone(), Some(state.db.clone()), + )); + let response = create_router(state) + .oneshot( + Request::builder() + .method("POST") + .uri("/api/v1/agent/run") + .header("Authorization", auth_header()) + .header("Content-Type", "application/json") + .body(Body::from(r#"{"prompt":"keep using tools","max_turns":1}"#)) + .unwrap(), + ) + .await + .unwrap(); + server.abort(); + assert_eq!(response.status(), StatusCode::OK); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let body: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(body["turns_taken"], 1); + assert_eq!(body["steps"][0]["tool_calls"][0]["success"], true); + assert_eq!(body["completed"], false); + assert!(body["final_response"].as_str().unwrap().contains("maximum turn limit (1)")); + assert_eq!(body["status"], "incomplete"); +} diff --git a/tests/failure_provenance_tests.rs b/tests/failure_provenance_tests.rs index f49b9d8..dceb2aa 100644 --- a/tests/failure_provenance_tests.rs +++ b/tests/failure_provenance_tests.rs @@ -223,7 +223,7 @@ async fn failing_tool_identifies_step_cause_and_flows_through_event_bus() { assert_eq!(f.class, FailureClass::Failed); assert_eq!(f.cause[0].message, "disk read error"); assert!(f.failed_at >= f.created_at); - assert!(res.completed); + assert!(!res.completed); let env = rx.try_recv().unwrap(); assert_eq!(env.sequence, 1); diff --git a/tests/round2_completion_tests.rs b/tests/round2_completion_tests.rs new file mode 100644 index 0000000..01f276e --- /dev/null +++ b/tests/round2_completion_tests.rs @@ -0,0 +1,124 @@ +//! Round-two completion contract: real loopback transports, deterministic faults, no model service. +use aegis::{create_router, AgentEngine, Database, GatewayState, HeartbeatEngine, HttpInferenceBackend, + SkillRegistry, ToolDispatcher, ToolFault, FailureClass, EffectCertainty}; +use axum::{body::Body, http::{Request, StatusCode}}; +use futures_util::{SinkExt, StreamExt}; +use serde_json::{json, Value}; +use std::sync::{Arc, atomic::{AtomicUsize, Ordering}}; +use std::time::{Duration, Instant}; +use tower::ServiceExt; + +const TOKEN: &str = "round-two-operator-0123456789abcdef"; +struct Server(tokio::task::JoinHandle<()>); +impl Drop for Server { fn drop(&mut self) { self.0.abort(); } } +async fn serve(app: axum::Router) -> (std::net::SocketAddr, Server) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let handle = tokio::spawn(async move { axum::serve(listener, app).await.unwrap(); }); + (address, Server(handle)) +} +struct Dispatch { attempts: AtomicUsize, recover: bool } +#[async_trait::async_trait] +impl ToolDispatcher for Dispatch { + async fn dispatch(&self, _: &str, _: &Value) -> Result { + let attempt = self.attempts.fetch_add(1, Ordering::SeqCst); + if self.recover && attempt > 0 { return Ok("retried read succeeded".into()); } + Err(ToolFault::new( + if self.recover { FailureClass::Unavailable } else { FailureClass::Failed }, + EffectCertainty::NoEffect, "injected read failure", + )) + } +} +async fn transport_case(websocket: bool, case: &'static str) { + let model = axum::Router::new().route("/v1/chat/completions", axum::routing::post( + move |axum::Json(body): axum::Json| async move { + let tool_done = body["messages"].as_array().unwrap().iter().any(|m| m["role"] == "tool"); + let response = if case == "empty_choices" { json!({"choices":[]}) } + else if matches!(case, "tool_failure" | "retry_success" | "length_tools") && !tool_done { + json!({"choices":[{"message":{"tool_calls":[{"id":"read","type":"function", + "function":{"name":"read_file","arguments":"{\"path\":\"fixture\"}"}}]},"finish_reason":if case == "length_tools" { "length" } else { "tool_calls" }}]}) + } else { + json!({"choices":[{"message":{"content":if case == "empty_text" { " " } else { "final text" }, + "reasoning":"Reasoning is not a terminal answer"},"finish_reason":if case == "length" { "length" } else { "stop" }}]}) + }; + axum::Json(response) + } + )); + let (model_address, _model_server) = serve(model).await; + let db = Arc::new(Database::open_in_memory().unwrap()); + let inference = Arc::new(HttpInferenceBackend::new(Some(format!("http://{model_address}/v1/chat/completions")), None)); + let skills = Arc::new(SkillRegistry::new()); + let dispatch = Arc::new(Dispatch { attempts: AtomicUsize::new(0), recover: case == "retry_success" }); + let agent = AgentEngine::new(inference.clone(), skills.clone(), Some(db.clone())) + .with_dispatcher(dispatch.clone()).with_failure_policy(aegis::agent::FailurePolicy { + retry: aegis::RetryPolicy { max_attempts: 2 }, tool_timeout: None, + }); + let state = GatewayState { + start_time: Instant::now(), db: db.clone(), inference: inference.clone(), skills, + heartbeat: Arc::new(HeartbeatEngine::with_inference(60, db, inference)), agent: Arc::new(agent), + operator: aegis::OperatorAuth::with_token(TOKEN).unwrap(), + }; + let app = create_router(state); + let body = if websocket { + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + let (address, _gateway_server) = serve(app).await; + let mut request = format!("ws://{address}/ws").into_client_request().unwrap(); + request.headers_mut().insert("authorization", format!("Bearer {TOKEN}").parse().unwrap()); + let (mut ws, _) = tokio_tungstenite::connect_async(request).await.unwrap(); + ws.send(tokio_tungstenite::tungstenite::Message::Text(json!({"type":"agent_run","prompt":"read then answer","max_turns":3}).to_string())).await.unwrap(); + let body = tokio::time::timeout(Duration::from_secs(5), async { + loop { + let message = ws.next().await.unwrap().unwrap(); + if let Ok(text) = message.to_text() { + let body: Value = serde_json::from_str(text).unwrap(); + if matches!(body["type"].as_str(), Some("agent_result" | "agent_error")) { break body; } + } + } + }).await.unwrap(); + ws.close(None).await.unwrap(); + body + } else { + let response = app.oneshot(Request::builder().method("POST").uri("/api/v1/agent/run") + .header("Authorization", format!("Bearer {TOKEN}")).header("Content-Type","application/json") + .body(Body::from(r#"{"prompt":"read then answer","max_turns":3}"#)).unwrap()).await.unwrap(); + assert_eq!(response.status(), if case == "empty_choices" { StatusCode::INTERNAL_SERVER_ERROR } else { StatusCode::OK }); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); + if case == "empty_choices" { json!({"error": String::from_utf8(bytes.to_vec()).unwrap()}) } + else { serde_json::from_slice(&bytes).unwrap() } + }; + if case == "empty_choices" { + if websocket { assert_eq!(body["type"], "agent_error"); } + assert!(body.to_string().contains("empty choices"), "{body}"); + } else { + let result = if websocket { &body["result"] } else { &body }; + let completed = case == "retry_success"; + assert_eq!(result["completed"], completed, "{body}"); + assert_eq!(body["status"], if completed { "completed" } else { "incomplete" }); + if case == "tool_failure" { + assert_eq!(result["steps"][0]["tool_calls"][0]["success"], false); + assert_eq!(result["final_response"], "final text"); + } + if case == "length_tools" { + assert_eq!(dispatch.attempts.load(Ordering::SeqCst), 0, "truncated tool call must not dispatch"); + } + if completed { + assert_eq!(dispatch.attempts.load(Ordering::SeqCst), 2); + assert_eq!(result["steps"][0]["tool_calls"][0]["retry_failures"].as_array().unwrap().len(), 1); + } + } +} +macro_rules! transport_test { + ($name:ident, $ws:expr, $case:expr) => { #[tokio::test] async fn $name() { transport_case($ws, $case).await; } }; +} +transport_test!(round2_http_failed_tool_final_text, false, "tool_failure"); +transport_test!(round2_ws_failed_tool_final_text, true, "tool_failure"); +transport_test!(round2_http_retry_success, false, "retry_success"); +transport_test!(round2_ws_retry_success, true, "retry_success"); +transport_test!(round2_http_length, false, "length"); +transport_test!(round2_ws_length, true, "length"); +transport_test!(round2_http_empty_text, false, "empty_text"); +transport_test!(round2_ws_empty_text, true, "empty_text"); +transport_test!(round2_http_empty_choices, false, "empty_choices"); +transport_test!(round2_ws_empty_choices, true, "empty_choices"); +transport_test!(round2_http_length_tools, false, "length_tools"); +transport_test!(round2_ws_length_tools, true, "length_tools"); diff --git a/tests/round2_heartbeat_tests.rs b/tests/round2_heartbeat_tests.rs new file mode 100644 index 0000000..9e19137 --- /dev/null +++ b/tests/round2_heartbeat_tests.rs @@ -0,0 +1,260 @@ +//! Task interruption, terminal transaction and projection-failure tests, all on private SQLite files. +use aegis::{Database, HeartbeatEngine, InferenceEngine, ChatStream, ChatTurnResponse}; +use aegis::persistence::TaskClaim; +use rusqlite::Connection; +use serde_json::Value; +use std::sync::{Arc, atomic::{AtomicUsize, Ordering}}; +use std::time::Duration; + +fn fixture() -> (tempfile::TempDir, Arc, Connection) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("tasks.sqlite"); + let db = Arc::new(Database::open(&path).unwrap()); + let observer = Connection::open(&path).unwrap(); + (dir, db, observer) +} +fn claim(db: &Database, id: &str) -> TaskClaim { db.claim_task(id).unwrap().unwrap() } +fn state(observer: &Connection, id: &str) -> (String, Option) { + observer.query_row("SELECT status,result FROM tasks WHERE id=?1", [id], |row| Ok((row.get(0)?,row.get(1)?))).unwrap() +} +fn event_count(observer: &Connection) -> i64 { + observer.query_row("SELECT count(*) FROM task_terminal_events", [], |row| row.get(0)).unwrap() +} +fn exported_events(dir: &tempfile::TempDir) -> Vec { + std::fs::read_to_string(dir.path().join("transcript.jsonl")).unwrap().lines() + .map(|line| serde_json::from_str::(line).unwrap()) + .filter(|event| matches!(event["event_type"].as_str(), Some("task_completed" | "task_failed"))).collect() +} + + +// Re-exec isolates HOME and command capture from other concurrently running tests. +fn capture_crumbs_in_child(test_name: &str) -> bool { + if std::env::var_os("AEGIS_TEST_CRUMB_ARGV").is_some() { + return false; + } + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let bin = dir.path().join(".local/bin"); + std::fs::create_dir_all(&bin).unwrap(); + let executable = bin.join("spark-crumbs"); + std::fs::write(&executable, "#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"$AEGIS_TEST_CRUMB_ARGV\"\n").unwrap(); + std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o700)).unwrap(); + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", test_name, "--nocapture"]) + .env("HOME", dir.path()) + .env("AEGIS_TEST_CRUMB_ARGV", dir.path().join("crumb-argv")) + .status().unwrap(); + assert!(status.success()); + true +} + +fn assert_crumb_receipt(receipt: &aegis::PulseReceipt) { + let path = std::env::var_os("AEGIS_TEST_CRUMB_ARGV").expect("isolated command capture"); + let arguments = std::fs::read_to_string(path).unwrap(); + let arguments: Vec<_> = arguments.lines().collect(); + let vector = arguments.windows(2).filter(|pair| pair[0] == "--vector").last().unwrap()[1]; + assert_eq!(vector, format!("Tick #{} {} | tasks: {} | actions: {}", + receipt.tick_id, receipt.status, receipt.tasks_scanned, receipt.actions_dispatched)); +} +#[tokio::test] +async fn round2_interrupted_claim_reopen_abandons_once_without_replay() { + let (dir, db, observer) = fixture(); + db.create_task("interrupted", "consolidate_memory", "").unwrap(); + let _claim = claim(&db, "interrupted"); + // An independently opened live owner must not be stolen. + let live = Database::open(&dir.path().join("tasks.sqlite")).unwrap(); + assert_eq!(state(&observer,"interrupted").0, "running"); + drop(live); + drop(db); + let reopened = Arc::new(Database::open(&dir.path().join("tasks.sqlite")).unwrap()); + assert_eq!(state(&observer,"interrupted"), ("failed".into(),Some("abandoned: outcome unknown".into()))); + let receipt = HeartbeatEngine::new(60, reopened.clone()).pulse_once().await; + assert_eq!(receipt.actions_dispatched, 0); + assert_eq!(event_count(&observer), 1); + let events = exported_events(&dir); + assert_eq!(events.len(), 1); + assert_eq!(events[0]["event_type"], "task_failed"); + drop(reopened); + let _reopened = Database::open(&dir.path().join("tasks.sqlite")).unwrap(); + assert_eq!(event_count(&observer), 1); + assert_eq!(exported_events(&dir).len(), 1); +} + +#[test] +fn round2_ownerless_legacy_claim_requires_quiescence() { + let (dir, db, observer) = fixture(); + db.create_task("legacy", "system_telemetry", "").unwrap(); + observer.execute("UPDATE tasks SET status='running' WHERE id='legacy'", []).unwrap(); + drop(db); + let result = Database::open(&dir.path().join("tasks.sqlite")); + assert!(result.is_err()); + assert!(result.err().unwrap().to_string().contains("quiescent migration")); +} + +#[test] +fn round2_claim_identity_and_duplicate_finalization_are_refused() { + let (_dir, db, observer) = fixture(); + db.create_task("once", "system_telemetry", "").unwrap(); + let valid = claim(&db,"once"); + let mut wrong = valid.clone(); + wrong.token = "wrong-token".into(); + assert!(db.complete_task(&wrong,"wrong").is_err()); + assert_eq!(state(&observer,"once").0, "running"); + assert_eq!(event_count(&observer), 0); + wrong = valid.clone(); wrong.owner = "wrong-owner".into(); + assert!(db.fail_task(&wrong,"wrong").is_err()); + wrong = valid.clone(); wrong.id = "missing-task".into(); + assert!(db.complete_task(&wrong,"missing").is_err()); + assert_eq!(event_count(&observer), 0); + db.complete_task(&valid,"finished").unwrap(); + assert!(db.complete_task(&valid,"again").is_err()); + assert!(db.fail_task(&valid,"conflicting").is_err()); + assert_eq!(state(&observer,"once"), ("completed".into(),Some("finished".into()))); + assert_eq!(event_count(&observer), 1); + assert!(observer.execute("INSERT INTO task_terminal_events(event_id,task_id,claim_id,event_json) VALUES('duplicate','once','other','{}')", []).is_err()); + db.create_task("failed", "unknown", "").unwrap(); + let failed = claim(&db,"failed"); + db.fail_task(&failed,"original failure").unwrap(); + assert!(db.fail_task(&failed,"again").is_err()); + assert!(db.complete_task(&failed,"false completion").is_err()); + assert_eq!(event_count(&observer), 2); +} + +async fn finalization_retry(successful: bool) { + let (_dir, db, observer) = fixture(); + db.create_task("retry", if successful {"consolidate_memory"} else {"unknown"}, "").unwrap(); + observer.execute_batch("CREATE TRIGGER reject_terminal BEFORE INSERT ON task_terminal_events BEGIN SELECT RAISE(FAIL,'injected terminal event failure'); END;").unwrap(); + let engine = HeartbeatEngine::new(60, db.clone()); + let first = engine.pulse_once().await; + assert_eq!(first.status, "degraded"); + assert_eq!(first.actions_dispatched, 1); + assert_eq!(state(&observer,"retry").0, "running", "terminal state must roll back with its event"); + assert_eq!(event_count(&observer), 0); + observer.execute_batch("DROP TRIGGER reject_terminal").unwrap(); + // Retained outcomes belong to the DB owner, not a replaceable heartbeat engine. + drop(engine); + let engine = HeartbeatEngine::new(60, db); + let mut rx = engine.subscribe(); + let second = engine.pulse_once().await; + assert_eq!(second.status, if successful { "nominal" } else { "degraded" }); + assert_eq!(rx.recv().await.unwrap().status, second.status); + if !successful { assert_crumb_receipt(&second); } + assert_eq!(second.actions_dispatched, 0); + assert_eq!(state(&observer,"retry").0, if successful {"completed"} else {"failed"}); + assert!(state(&observer,"retry").1.unwrap().contains(if successful {"Memory crumbs recorded"} else {"Unknown task type"})); + assert_eq!(event_count(&observer), 1); + let crumbs: i64 = observer.query_row("SELECT count(*) FROM memory_crumbs", [], |row| row.get(0)).unwrap(); + assert_eq!(crumbs, if successful {1} else {0}); +} +#[tokio::test] +async fn round2_successful_outcome_retained_after_failed_finalization() { finalization_retry(true).await; } +#[tokio::test] +async fn round2_failed_outcome_retained_after_failed_finalization() { + if capture_crumbs_in_child("round2_failed_outcome_retained_after_failed_finalization") { return; } + finalization_retry(false).await; +} + +#[tokio::test] +async fn round2_unwritable_transcript_keeps_one_durable_event_and_retries_export() { + let (dir, db, observer) = fixture(); + db.create_task("export", "system_telemetry", "").unwrap(); + let path = dir.path().join("transcript.jsonl"); + let saved = dir.path().join("transcript.saved"); + std::fs::rename(&path,&saved).unwrap(); + std::fs::create_dir(&path).unwrap(); + let engine = HeartbeatEngine::new(60, db); + let first = engine.pulse_once().await; + assert_eq!(first.status,"degraded"); + assert_eq!(state(&observer,"export").0,"completed"); + assert_eq!(event_count(&observer),1); + let (event_id, exported): (String,i64) = observer.query_row("SELECT event_id,exported FROM task_terminal_events",[],|row|Ok((row.get(0)?,row.get(1)?))).unwrap(); + assert_eq!(exported,0); + std::fs::remove_dir(&path).unwrap(); + std::fs::rename(saved,&path).unwrap(); + // Simulate a torn trailing append; retry must not leave malformed JSONL. + use std::io::Write; + std::fs::OpenOptions::new().append(true).open(&path).unwrap().write_all(b"{\"interrupted").unwrap(); + let second = engine.pulse_once().await; + assert_eq!(second.status,"nominal"); + assert_eq!(second.actions_dispatched,0); + assert_eq!(event_count(&observer),1); + let events = exported_events(&dir); + assert_eq!(events.len(),1); + assert_eq!(events[0]["event_id"],event_id); + assert_eq!(events[0]["event_type"],"task_completed"); + observer.execute("UPDATE task_terminal_events SET exported=0",[]).unwrap(); + assert_eq!(engine.pulse_once().await.status,"nominal"); + assert_eq!(exported_events(&dir).len(),1, "append-before-ack retry must deduplicate by stable event identity"); +} + +#[tokio::test] +async fn round2_receipt_insert_failure_degrades_return_and_broadcast() { + let (_dir, db, observer) = fixture(); + observer.execute_batch("CREATE TRIGGER reject_heartbeat BEFORE INSERT ON heartbeats BEGIN SELECT RAISE(FAIL,'injected heartbeat failure'); END;").unwrap(); + let engine = HeartbeatEngine::new(60, db); + let mut rx = engine.subscribe(); + let receipt = engine.pulse_once().await; + assert_eq!(receipt.status,"degraded"); + assert!(receipt.notes.contains("injected heartbeat failure")); + assert_eq!(rx.recv().await.unwrap().status,"degraded"); + let count: i64 = observer.query_row("SELECT count(*) FROM heartbeats",[],|row|row.get(0)).unwrap(); + assert_eq!(count,0); + observer.execute_batch("DROP TRIGGER reject_heartbeat").unwrap(); + assert_eq!(engine.pulse_once().await.status,"nominal"); +} + +struct HealthProbe { calls: AtomicUsize, hang: bool } +#[async_trait::async_trait] +impl InferenceEngine for HealthProbe { + fn model_id(&self)->String { "test-health".into() } + fn endpoint(&self)->String { "test-only".into() } + async fn generate_with_tokens(&self,_:&str,_:Option<&str>,_:Option,_:Option)->Result> { unreachable!() } + async fn generate_chat(&self,_:&[Value],_:Option,_:Option)->Result> { unreachable!() } + async fn generate_chat_with_tools(&self,_:&[Value],_:Option<&[Value]>,_:Option,_:Option)->Result> { unreachable!() } + async fn stream_chat(&self,_:&[Value],_:Option,_:Option)->Result> { unreachable!() } + async fn check_health(&self)->bool { + self.calls.fetch_add(1,Ordering::SeqCst); + if self.hang { std::future::pending::<()>().await; } + panic!("injected health action panic"); + } +} +#[tokio::test] +async fn round2_panicking_health_action_does_not_kill_loop() { + let (_dir,db,observer)=fixture(); + db.create_task("panic","model_health","").unwrap(); + let health=Arc::new(HealthProbe{calls:AtomicUsize::new(0),hang:false}); + let engine=Arc::new(HeartbeatEngine::with_inference(1,db.clone(),health.clone())); + let mut rx=engine.subscribe(); + engine.start_loop().await; + let first=tokio::time::timeout(Duration::from_secs(5),rx.recv()).await.unwrap().unwrap(); + assert_eq!(first.status,"degraded"); + assert_eq!(state(&observer,"panic").0,"failed"); + assert!(state(&observer,"panic").1.unwrap().contains("panicked")); + db.create_task("after-panic","system_telemetry","").unwrap(); + let next=tokio::time::timeout(Duration::from_secs(5),rx.recv()).await.unwrap().unwrap(); + assert_eq!(next.status,"nominal"); + assert_eq!(state(&observer,"after-panic").0,"completed"); + assert_eq!(health.calls.load(Ordering::SeqCst),1); +} +#[tokio::test] +async fn round2_cancelled_claim_retains_unknown_failure_without_reexecution() { + if capture_crumbs_in_child("round2_cancelled_claim_retains_unknown_failure_without_reexecution") { return; } + let (_dir,db,observer)=fixture(); + db.create_task("cancel","model_health","").unwrap(); + let health=Arc::new(HealthProbe{calls:AtomicUsize::new(0),hang:true}); + let engine=Arc::new(HeartbeatEngine::with_inference(60,db.clone(),health.clone())); + let running=tokio::spawn(async move { engine.pulse_once().await }); + tokio::time::timeout(Duration::from_secs(5),async { while health.calls.load(Ordering::SeqCst)==0 { tokio::task::yield_now().await; } }).await.unwrap(); + running.abort(); + assert!(running.await.unwrap_err().is_cancelled()); + let engine = HeartbeatEngine::new(60,db); + let mut rx = engine.subscribe(); + let receipt = engine.pulse_once().await; + assert_eq!(receipt.status,"degraded"); + assert_eq!(rx.recv().await.unwrap().status,"degraded"); + assert_crumb_receipt(&receipt); + assert_eq!(receipt.actions_dispatched,0); + assert_eq!(state(&observer,"cancel"),("failed".into(),Some("abandoned: outcome unknown".into()))); + assert_eq!(event_count(&observer),1); + assert_eq!(health.calls.load(Ordering::SeqCst),1); +} diff --git a/tests/round3_heartbeat_tests.rs b/tests/round3_heartbeat_tests.rs new file mode 100644 index 0000000..506d5c6 --- /dev/null +++ b/tests/round3_heartbeat_tests.rs @@ -0,0 +1,196 @@ +//! Host-only regressions for maintenance recovery, explicit migration and bounded health work. +use aegis::{ChatStream, ChatTurnResponse, Database, HeartbeatEngine, InferenceEngine}; +use rusqlite::Connection; +use serde_json::{json, Value}; +use std::io::Read; +use std::process::{Child, Command, Stdio}; +use std::sync::{atomic::{AtomicUsize, Ordering}, Arc}; +use std::time::Duration; + +fn state(conn: &Connection, id: &str) -> (String, Option) { + conn.query_row("SELECT status,result FROM tasks WHERE id=?1", [id], |r| Ok((r.get(0)?, r.get(1)?))).unwrap() +} +fn events(conn: &Connection) -> i64 { + conn.query_row("SELECT count(*) FROM task_terminal_events", [], |r| r.get(0)).unwrap() +} +struct OwnerProcess(Child); +impl Drop for OwnerProcess { + fn drop(&mut self) { + if self.0.try_wait().unwrap().is_none() { self.0.kill().unwrap(); } + self.0.wait().unwrap(); + } +} + +#[test] +fn round3_owner_process_helper() { + let Some(path) = std::env::var_os("AEGIS_TEST_OWNER_DATABASE") else { return; }; + let db = Database::open(std::path::Path::new(&path)).unwrap(); + db.create_task("peer", "consolidate_memory", "must not replay").unwrap(); + assert!(db.claim_task("peer").unwrap().is_some()); + std::fs::write(std::env::var_os("AEGIS_TEST_OWNER_READY").unwrap(), b"claimed").unwrap(); + let mut release = [0]; + let _ = std::io::stdin().read_exact(&mut release); + drop(db); +} + +#[tokio::test] +async fn round3_live_peer_death_recovers_without_reopening_observer() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("peer.sqlite"); + let ready = dir.path().join("ready"); + let mut child = OwnerProcess(Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "round3_owner_process_helper", "--nocapture"]) + .env("AEGIS_TEST_OWNER_DATABASE", &path).env("AEGIS_TEST_OWNER_READY", &ready) + .stdin(Stdio::piped()).stdout(Stdio::null()).spawn().unwrap()); + tokio::time::timeout(Duration::from_secs(5), async { + while !ready.exists() { tokio::time::sleep(Duration::from_millis(10)).await; } + }).await.unwrap(); + let db = Arc::new(Database::open(&path).unwrap()); + let observer = Connection::open(&path).unwrap(); + let engine = HeartbeatEngine::new(60, db); + assert_eq!(engine.pulse_once().await.status, "nominal"); + assert_eq!(state(&observer, "peer").0, "running", "live process owns the flock"); + assert_eq!(events(&observer), 0); + child.0.kill().unwrap(); + child.0.wait().unwrap(); + let receipt = engine.pulse_once().await; + assert_eq!(receipt.status, "degraded"); + assert_eq!(receipt.actions_dispatched, 0); + assert_eq!(state(&observer, "peer"), ("failed".into(), Some("abandoned: outcome unknown".into()))); + assert_eq!(events(&observer), 1); + assert_eq!(engine.pulse_once().await.status, "nominal"); + assert_eq!(events(&observer), 1); + let crumbs: i64 = observer.query_row("SELECT count(*) FROM memory_crumbs", [], |r| r.get(0)).unwrap(); + assert_eq!(crumbs, 0); +} + +fn legacy_fixture(path: &std::path::Path) -> Connection { + let conn = Connection::open(path).unwrap(); + 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); + INSERT INTO tasks VALUES('legacy','consolidate_memory','preserve payload','running',NULL,'preserve timestamp',NULL);").unwrap(); + conn +} +fn migrate(path: &std::path::Path, quiescent: bool) -> std::process::Output { + let mut command = Command::new(env!("CARGO_BIN_EXE_aegis")); + command.arg("migrate-legacy-tasks").arg("--db-path").arg(path); + if quiescent { command.arg("--quiescent"); } + command.output().unwrap() +} + +#[tokio::test] +async fn round3_explicit_legacy_migration_preserves_and_fails_unknown_once() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("legacy.sqlite"); + let observer = legacy_fixture(&path); + assert!(Database::open(&path).is_err(), "normal startup must fail closed without migration"); + let refused = migrate(&path, false); + assert!(!refused.status.success(), "explicit quiescence acknowledgement is required"); + assert_eq!(state(&observer,"legacy").0,"running"); + assert_eq!(events(&observer),0); + let migrated = migrate(&path,true); + assert!(migrated.status.success(), "{}", String::from_utf8_lossy(&migrated.stderr)); + let db = Arc::new(Database::open(&path).unwrap()); + assert_eq!(state(&observer,"legacy"),("failed".into(),Some("abandoned: outcome unknown".into()))); + let (payload,created,claim,owner): (String,String,String,String) = observer.query_row("SELECT payload,created_at,claim_id,owner_id FROM tasks WHERE id='legacy'",[],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?))).unwrap(); + assert_eq!(payload,"preserve payload"); + assert_eq!(created,"preserve timestamp"); + assert!(uuid::Uuid::parse_str(&claim).is_ok()); + assert!(uuid::Uuid::parse_str(&owner).is_ok()); + assert_eq!(events(&observer),1); + assert_eq!(HeartbeatEngine::new(60,db.clone()).pulse_once().await.actions_dispatched,0); + drop(db); + assert!(migrate(&path,true).status.success()); + assert_eq!(events(&observer),1); +} + +#[test] +fn round3_legacy_migration_rolls_back_claim_metadata_and_terminal_event_together() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("legacy.sqlite"); + let observer = legacy_fixture(&path); + assert!(Database::open(&path).is_err()); + observer.execute_batch("CREATE TRIGGER reject_migration_event BEFORE INSERT ON task_terminal_events BEGIN SELECT RAISE(FAIL,'injected migration event failure'); END;").unwrap(); + let result = migrate(&path,true); + assert!(!result.status.success()); + assert!(String::from_utf8_lossy(&result.stderr).contains("injected migration event failure")); + assert_eq!(state(&observer,"legacy").0,"running"); + let metadata: (Option,Option) = observer.query_row("SELECT claim_id,owner_id FROM tasks WHERE id='legacy'",[],|r|Ok((r.get(0)?,r.get(1)?))).unwrap(); + assert_eq!(metadata,(None,None)); + assert_eq!(events(&observer),0); + observer.execute_batch("DROP TRIGGER reject_migration_event").unwrap(); + assert!(migrate(&path,true).status.success()); + assert_eq!(events(&observer),1); +} + +#[test] +fn round3_legacy_migration_refuses_a_live_owner_even_with_acknowledgement() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("legacy.sqlite"); + let db = Database::open(&path).unwrap(); + let observer = Connection::open(&path).unwrap(); + observer.execute("INSERT INTO tasks(id,task_type,payload,status,created_at) VALUES('legacy','consolidate_memory','','running','now')",[]).unwrap(); + let refused = migrate(&path,true); + assert!(!refused.status.success()); + assert!(String::from_utf8_lossy(&refused.stderr).contains("live task owner")); + assert_eq!(state(&observer,"legacy").0,"running"); + drop(db); + assert!(migrate(&path,true).status.success()); +} + +#[tokio::test] +async fn round3_receipt_projection_failure_without_tasks_matches_sqlite_and_broadcast() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("receipt.sqlite"); + let db = Arc::new(Database::open(&path).unwrap()); + let observer = Connection::open(&path).unwrap(); + std::fs::create_dir(dir.path().join("transcript.jsonl")).unwrap(); + let engine = HeartbeatEngine::new(60,db); + let mut rx = engine.subscribe(); + let receipt = engine.pulse_once().await; + assert_eq!(receipt.status,"degraded"); + 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(); + assert_eq!(stored,serde_json::to_value(&receipt).unwrap()); + assert_eq!(serde_json::to_value(rx.recv().await.unwrap()).unwrap(),stored); + assert_eq!(events(&observer),0); +} + +struct PendingHealth(AtomicUsize); +#[async_trait::async_trait] +impl InferenceEngine for PendingHealth { + fn model_id(&self)->String { "pending-health".into() } + fn endpoint(&self)->String { "test-only".into() } + async fn generate_with_tokens(&self,_:&str,_:Option<&str>,_:Option,_:Option)->Result> { unreachable!() } + async fn generate_chat(&self,_:&[Value],_:Option,_:Option)->Result> { unreachable!() } + async fn generate_chat_with_tools(&self,_:&[Value],_:Option<&[Value]>,_:Option,_:Option)->Result> { unreachable!() } + async fn stream_chat(&self,_:&[Value],_:Option,_:Option)->Result> { unreachable!() } + async fn check_health(&self)->bool { self.0.fetch_add(1,Ordering::SeqCst); std::future::pending().await } +} +#[tokio::test(start_paused = true)] +async fn round3_health_deadline_fails_once_and_later_pulses_continue() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("deadline.sqlite"); + let db = Arc::new(Database::open(&path).unwrap()); + let observer = Connection::open(&path).unwrap(); + db.create_task("never","model_health","").unwrap(); + let health = Arc::new(PendingHealth(AtomicUsize::new(0))); + let engine = Arc::new(HeartbeatEngine::with_inference(60,db.clone(),health.clone())); + let mut rx = engine.subscribe(); + let action_engine = engine.clone(); + let action = tokio::spawn(async move { action_engine.pulse_once().await }); + while health.0.load(Ordering::SeqCst) == 0 { tokio::task::yield_now().await; } + tokio::time::advance(Duration::from_secs(30)).await; + tokio::time::resume(); + let receipt = tokio::time::timeout(Duration::from_secs(2),action).await.expect("health action must have its own deadline").unwrap(); + assert_eq!(receipt.status,"degraded"); + assert_eq!(rx.recv().await.unwrap().status,"degraded"); + let failed = state(&observer,"never"); + assert_eq!(failed.0,"failed"); + assert!(failed.1.unwrap().contains("deadline")); + assert_eq!(events(&observer),1); + db.create_task("next","system_telemetry","").unwrap(); + let next = engine.pulse_once().await; + assert_eq!(next.status,"nominal"); + assert_eq!(next.actions_dispatched,1); + assert_eq!(health.0.load(Ordering::SeqCst),1); + assert_eq!(events(&observer),2, "one deadline failure and one successful subsequent action"); +} diff --git a/tests/stage3_4_persistence_tests.rs b/tests/stage3_4_persistence_tests.rs index 16f87ac..20bfa0b 100644 --- a/tests/stage3_4_persistence_tests.rs +++ b/tests/stage3_4_persistence_tests.rs @@ -268,11 +268,11 @@ fn test_legacy_task_claim_is_exclusive() { db.create_task("task_claim", "shell_exec", "echo once") .unwrap(); - assert!(db.claim_task("task_claim").unwrap()); - assert!(!db.claim_task("task_claim").unwrap()); - assert!(!db.claim_task("no_such_task").unwrap()); + let claim = db.claim_task("task_claim").unwrap().unwrap(); + assert!(db.claim_task("task_claim").unwrap().is_none()); + assert!(db.claim_task("no_such_task").unwrap().is_none()); assert!(db.list_pending_tasks().unwrap().is_empty()); - db.complete_task("task_claim", "done").unwrap(); - assert!(!db.claim_task("task_claim").unwrap()); + db.complete_task(&claim, "done").unwrap(); + assert!(db.claim_task("task_claim").unwrap().is_none()); }