aegis-runtime-mv
Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
aegis-runtime-mv / tests / failure_provenance_tests.rs
| 1 | //! Failure provenance and effect-safe retry tests (issue #38). |
| 2 | //! Deterministic: scripted model turns, scripted tool dispatcher, no network. |
| 3 | |
| 4 | use aegis::agent::FailurePolicy; |
| 5 | use aegis::{ |
| 6 | root_cause, AegisEvent, AgentEngine, CancelToken, ChatStream, ChatTurnResponse, |
| 7 | EffectCertainty, EventBus, FailureClass, FailureRecord, InferenceEngine, RetryPolicy, |
| 8 | SkillRegistry, ToolCallFunction, ToolCallItem, ToolDispatcher, ToolFault, |
| 9 | }; |
| 10 | use async_trait::async_trait; |
| 11 | use std::collections::{HashMap, VecDeque}; |
| 12 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 13 | use std::sync::{Arc, Mutex}; |
| 14 | use std::time::Duration; |
| 15 | |
| 16 | const SECRET: &str = "sk-live-SEEDED-SECRET-9f3a77"; |
| 17 | |
| 18 | struct ScriptedModel { |
| 19 | turns: Mutex<VecDeque<ChatTurnResponse>>, |
| 20 | asked: AtomicUsize, |
| 21 | seen: Mutex<Vec<String>>, |
| 22 | } |
| 23 | |
| 24 | impl ScriptedModel { |
| 25 | fn new(turns: Vec<ChatTurnResponse>) -> Arc<Self> { |
| 26 | Arc::new(Self { |
| 27 | turns: Mutex::new(turns.into()), |
| 28 | asked: AtomicUsize::new(0), |
| 29 | seen: Mutex::new(Vec::new()), |
| 30 | }) |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | fn calls(items: &[(&str, &str, serde_json::Value)]) -> ChatTurnResponse { |
| 35 | ChatTurnResponse { |
| 36 | content: None, |
| 37 | reasoning: None, |
| 38 | tool_calls: Some( |
| 39 | items |
| 40 | .iter() |
| 41 | .map(|(id, name, args)| ToolCallItem { |
| 42 | id: id.to_string(), |
| 43 | call_type: "function".to_string(), |
| 44 | function: ToolCallFunction { |
| 45 | name: name.to_string(), |
| 46 | arguments: args.to_string(), |
| 47 | }, |
| 48 | }) |
| 49 | .collect(), |
| 50 | ), |
| 51 | finish_reason: Some("tool_calls".to_string()), |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | fn done() -> ChatTurnResponse { |
| 56 | ChatTurnResponse { |
| 57 | content: Some("finished".to_string()), |
| 58 | reasoning: None, |
| 59 | tool_calls: None, |
| 60 | finish_reason: Some("stop".to_string()), |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | #[async_trait] |
| 65 | impl InferenceEngine for ScriptedModel { |
| 66 | fn model_id(&self) -> String { |
| 67 | "scripted".into() |
| 68 | } |
| 69 | fn endpoint(&self) -> String { |
| 70 | "none".into() |
| 71 | } |
| 72 | async fn generate_with_tokens( |
| 73 | &self, |
| 74 | _p: &str, |
| 75 | _s: Option<&str>, |
| 76 | _t: Option<f32>, |
| 77 | _m: Option<u32>, |
| 78 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { |
| 79 | Ok(String::new()) |
| 80 | } |
| 81 | async fn generate_chat( |
| 82 | &self, |
| 83 | _m: &[serde_json::Value], |
| 84 | _t: Option<f32>, |
| 85 | _x: Option<u32>, |
| 86 | ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> { |
| 87 | Ok(String::new()) |
| 88 | } |
| 89 | async fn generate_chat_with_tools( |
| 90 | &self, |
| 91 | m: &[serde_json::Value], |
| 92 | _tools: Option<&[serde_json::Value]>, |
| 93 | _t: Option<f32>, |
| 94 | _x: Option<u32>, |
| 95 | ) -> Result<ChatTurnResponse, Box<dyn std::error::Error + Send + Sync>> { |
| 96 | self.asked.fetch_add(1, Ordering::SeqCst); |
| 97 | self.seen |
| 98 | .lock() |
| 99 | .unwrap() |
| 100 | .push(serde_json::to_string(m).unwrap()); |
| 101 | Ok(self.turns.lock().unwrap().pop_front().unwrap_or_else(done)) |
| 102 | } |
| 103 | async fn stream_chat( |
| 104 | &self, |
| 105 | _m: &[serde_json::Value], |
| 106 | _t: Option<f32>, |
| 107 | _x: Option<u32>, |
| 108 | ) -> Result<ChatStream, Box<dyn std::error::Error + Send + Sync>> { |
| 109 | Err("not used".into()) |
| 110 | } |
| 111 | async fn check_health(&self) -> bool { |
| 112 | true |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | #[derive(Clone)] |
| 117 | enum Behavior { |
| 118 | Ok, |
| 119 | Fault(ToolFault), |
| 120 | Hang, |
| 121 | } |
| 122 | |
| 123 | /// Scripted tool path: per tool name, a queue of behaviours; empty queue = ok. |
| 124 | struct Script { |
| 125 | queues: Mutex<HashMap<String, VecDeque<Behavior>>>, |
| 126 | dispatches: AtomicUsize, |
| 127 | } |
| 128 | |
| 129 | impl Script { |
| 130 | fn new(entries: Vec<(&str, Vec<Behavior>)>) -> Arc<Self> { |
| 131 | Arc::new(Self { |
| 132 | queues: Mutex::new( |
| 133 | entries |
| 134 | .into_iter() |
| 135 | .map(|(k, v)| (k.to_string(), v.into())) |
| 136 | .collect(), |
| 137 | ), |
| 138 | dispatches: AtomicUsize::new(0), |
| 139 | }) |
| 140 | } |
| 141 | fn count(&self) -> usize { |
| 142 | self.dispatches.load(Ordering::SeqCst) |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | #[async_trait] |
| 147 | impl ToolDispatcher for Script { |
| 148 | async fn dispatch( |
| 149 | &self, |
| 150 | skill_name: &str, |
| 151 | _arguments: &serde_json::Value, |
| 152 | ) -> Result<String, ToolFault> { |
| 153 | self.dispatches.fetch_add(1, Ordering::SeqCst); |
| 154 | let next = self |
| 155 | .queues |
| 156 | .lock() |
| 157 | .unwrap() |
| 158 | .get_mut(skill_name) |
| 159 | .and_then(|q| q.pop_front()); |
| 160 | match next { |
| 161 | None | Some(Behavior::Ok) => Ok("ok".to_string()), |
| 162 | Some(Behavior::Fault(f)) => Err(f), |
| 163 | Some(Behavior::Hang) => { |
| 164 | tokio::time::sleep(Duration::from_secs(30)).await; |
| 165 | Ok("late".to_string()) |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | fn engine(model: Arc<ScriptedModel>, script: Arc<Script>) -> AgentEngine { |
| 172 | AgentEngine::new(model, Arc::new(SkillRegistry::new()), None) |
| 173 | .with_dispatcher(script) |
| 174 | .with_run_id("run_test") |
| 175 | } |
| 176 | |
| 177 | fn path() -> serde_json::Value { |
| 178 | serde_json::json!({"path": "a.txt"}) |
| 179 | } |
| 180 | |
| 181 | fn retry(n: u32) -> FailurePolicy { |
| 182 | FailurePolicy { |
| 183 | retry: RetryPolicy { max_attempts: n }, |
| 184 | tool_timeout: None, |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | fn all_failures(res: &aegis::AgentExecutionResult) -> Vec<FailureRecord> { |
| 189 | res.steps |
| 190 | .iter() |
| 191 | .flat_map(|s| s.tool_calls.iter()) |
| 192 | .flat_map(|t| t.retry_failures.iter().chain(t.failure.iter())) |
| 193 | .cloned() |
| 194 | .collect() |
| 195 | } |
| 196 | |
| 197 | #[tokio::test] |
| 198 | async fn failing_tool_identifies_step_cause_and_flows_through_event_bus() { |
| 199 | let model = ScriptedModel::new(vec![calls(&[("c1", "read_file", path())]), done()]); |
| 200 | let script = Script::new(vec![( |
| 201 | "read_file", |
| 202 | vec![Behavior::Fault(ToolFault::new( |
| 203 | FailureClass::Failed, |
| 204 | EffectCertainty::NoEffect, |
| 205 | "disk read error", |
| 206 | ))], |
| 207 | )]); |
| 208 | let bus = EventBus::default(); |
| 209 | let mut rx = bus.subscribe(); |
| 210 | let res = engine(model, script) |
| 211 | .with_event_bus(bus, Some("sess_1".into())) |
| 212 | .execute_task("goal", Some("sys"), 5) |
| 213 | .await |
| 214 | .unwrap(); |
| 215 | |
| 216 | let rec = &res.steps[0].tool_calls[0]; |
| 217 | assert!(!rec.success); |
| 218 | assert_eq!(rec.output, "disk read error"); |
| 219 | let f = rec.failure.as_ref().unwrap(); |
| 220 | assert_eq!(f.run_id, "run_test"); |
| 221 | assert_eq!(f.step_index, 1); |
| 222 | assert_eq!(f.tool_call_id, "c1"); |
| 223 | assert_eq!(f.class, FailureClass::Failed); |
| 224 | assert_eq!(f.cause[0].message, "disk read error"); |
| 225 | assert!(f.failed_at >= f.created_at); |
| 226 | assert!(!res.completed); |
| 227 | |
| 228 | let env = rx.try_recv().unwrap(); |
| 229 | assert_eq!(env.sequence, 1); |
| 230 | match env.event { |
| 231 | AegisEvent::StepFailed { failure } => assert_eq!(&failure, f), |
| 232 | other => panic!("unexpected event {:?}", other), |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | #[tokio::test] |
| 237 | async fn chained_dependent_failure_resolves_to_original() { |
| 238 | let model = ScriptedModel::new(vec![ |
| 239 | calls(&[("a", "read_file", path()), ("b", "list_dir", path())]), |
| 240 | calls(&[("c", "git_status", path())]), |
| 241 | done(), |
| 242 | ]); |
| 243 | let fail = |m: &str| { |
| 244 | Behavior::Fault(ToolFault::new( |
| 245 | FailureClass::Failed, |
| 246 | EffectCertainty::NoEffect, |
| 247 | m, |
| 248 | )) |
| 249 | }; |
| 250 | let script = Script::new(vec![ |
| 251 | ("read_file", vec![fail("root failure")]), |
| 252 | ("list_dir", vec![fail("downstream one")]), |
| 253 | ("git_status", vec![fail("downstream two")]), |
| 254 | ]); |
| 255 | let res = engine(model, script) |
| 256 | .execute_task("goal", Some("sys"), 5) |
| 257 | .await |
| 258 | .unwrap(); |
| 259 | let all = all_failures(&res); |
| 260 | assert_eq!(all.len(), 3); |
| 261 | let seqs: Vec<u64> = all.iter().map(|f| f.sequence).collect(); |
| 262 | assert_eq!(seqs, vec![1, 2, 3]); |
| 263 | assert_eq!(all[0].parent_call_id, None); |
| 264 | assert_eq!(all[1].parent_call_id.as_deref(), Some("a")); |
| 265 | assert_eq!(all[2].parent_call_id.as_deref(), Some("b")); |
| 266 | let root = root_cause(&all, &all[2]).unwrap(); |
| 267 | assert_eq!(root.tool_call_id, "a"); |
| 268 | assert_eq!(root.step_index, 1); |
| 269 | assert_eq!(root.cause[0].message, "root failure"); |
| 270 | } |
| 271 | |
| 272 | #[tokio::test] |
| 273 | async fn success_between_failures_breaks_the_chain() { |
| 274 | let model = ScriptedModel::new(vec![ |
| 275 | calls(&[ |
| 276 | ("a", "read_file", path()), |
| 277 | ("b", "list_dir", path()), |
| 278 | ("c", "git_status", path()), |
| 279 | ]), |
| 280 | done(), |
| 281 | ]); |
| 282 | let fail = Behavior::Fault(ToolFault::new( |
| 283 | FailureClass::Failed, |
| 284 | EffectCertainty::NoEffect, |
| 285 | "x", |
| 286 | )); |
| 287 | let script = Script::new(vec![ |
| 288 | ("read_file", vec![fail.clone()]), |
| 289 | ("git_status", vec![fail]), |
| 290 | ]); |
| 291 | let res = engine(model, script) |
| 292 | .execute_task("goal", Some("sys"), 5) |
| 293 | .await |
| 294 | .unwrap(); |
| 295 | let all = all_failures(&res); |
| 296 | assert_eq!(all.len(), 2); |
| 297 | assert_eq!(all[1].tool_call_id, "c"); |
| 298 | assert_eq!(all[1].parent_call_id, None); |
| 299 | } |
| 300 | |
| 301 | #[tokio::test] |
| 302 | async fn cancellation_in_flight_write_is_uncertain_and_halts_the_run() { |
| 303 | let model = ScriptedModel::new(vec![ |
| 304 | calls(&[("w", "write_file", path()), ("never", "read_file", path())]), |
| 305 | done(), |
| 306 | ]); |
| 307 | let script = Script::new(vec![("write_file", vec![Behavior::Hang])]); |
| 308 | let token = CancelToken::new(); |
| 309 | let t2 = token.clone(); |
| 310 | tokio::spawn(async move { |
| 311 | tokio::time::sleep(Duration::from_millis(40)).await; |
| 312 | t2.cancel(); |
| 313 | }); |
| 314 | let res = engine(model.clone(), script.clone()) |
| 315 | .with_cancel_token(token) |
| 316 | .execute_task("goal", Some("sys"), 5) |
| 317 | .await |
| 318 | .unwrap(); |
| 319 | let f = res.steps[0].tool_calls[0].failure.as_ref().unwrap(); |
| 320 | assert_eq!(f.class, FailureClass::Cancelled); |
| 321 | assert_eq!(f.effect_certainty, EffectCertainty::Uncertain); |
| 322 | assert!(!res.completed); |
| 323 | assert_eq!(res.steps[0].tool_calls.len(), 1, "later call must not run"); |
| 324 | assert_eq!(script.count(), 1); |
| 325 | assert_eq!(model.asked.load(Ordering::SeqCst), 1); |
| 326 | } |
| 327 | |
| 328 | #[tokio::test] |
| 329 | async fn cancellation_of_read_is_no_effect_and_before_dispatch_never_dispatches() { |
| 330 | let script = Script::new(vec![("read_file", vec![Behavior::Hang])]); |
| 331 | let token = CancelToken::new(); |
| 332 | let t2 = token.clone(); |
| 333 | tokio::spawn(async move { |
| 334 | tokio::time::sleep(Duration::from_millis(40)).await; |
| 335 | t2.cancel(); |
| 336 | }); |
| 337 | let res = engine( |
| 338 | ScriptedModel::new(vec![calls(&[("r", "read_file", path())])]), |
| 339 | script.clone(), |
| 340 | ) |
| 341 | .with_cancel_token(token) |
| 342 | .execute_task("goal", Some("sys"), 5) |
| 343 | .await |
| 344 | .unwrap(); |
| 345 | let f = res.steps[0].tool_calls[0].failure.as_ref().unwrap(); |
| 346 | assert_eq!(f.class, FailureClass::Cancelled); |
| 347 | assert_eq!(f.effect_certainty, EffectCertainty::NoEffect); |
| 348 | |
| 349 | let pre = CancelToken::new(); |
| 350 | pre.cancel(); |
| 351 | let script2 = Script::new(vec![]); |
| 352 | let res2 = engine( |
| 353 | ScriptedModel::new(vec![calls(&[("w", "write_file", path())])]), |
| 354 | script2.clone(), |
| 355 | ) |
| 356 | .with_cancel_token(pre) |
| 357 | .execute_task("goal", Some("sys"), 5) |
| 358 | .await |
| 359 | .unwrap(); |
| 360 | let f2 = res2.steps[0].tool_calls[0].failure.as_ref().unwrap(); |
| 361 | assert_eq!(f2.class, FailureClass::Cancelled); |
| 362 | assert_eq!(f2.effect_certainty, EffectCertainty::NoEffect); |
| 363 | assert_eq!(script2.count(), 0); |
| 364 | } |
| 365 | |
| 366 | #[tokio::test] |
| 367 | async fn timeout_certainty_follows_skill_contract_and_is_never_retried() { |
| 368 | let policy = FailurePolicy { |
| 369 | retry: RetryPolicy { max_attempts: 4 }, |
| 370 | tool_timeout: Some(Duration::from_millis(30)), |
| 371 | }; |
| 372 | let script = Script::new(vec![ |
| 373 | ("write_file", vec![Behavior::Hang, Behavior::Hang]), |
| 374 | ("read_file", vec![Behavior::Hang, Behavior::Hang]), |
| 375 | ]); |
| 376 | let res = engine( |
| 377 | ScriptedModel::new(vec![calls(&[ |
| 378 | ("w", "write_file", path()), |
| 379 | ("r", "read_file", path()), |
| 380 | ])]), |
| 381 | script.clone(), |
| 382 | ) |
| 383 | .with_failure_policy(policy) |
| 384 | .execute_task("goal", Some("sys"), 3) |
| 385 | .await |
| 386 | .unwrap(); |
| 387 | let w = res.steps[0].tool_calls[0].failure.as_ref().unwrap(); |
| 388 | let r = res.steps[0].tool_calls[1].failure.as_ref().unwrap(); |
| 389 | assert_eq!(w.class, FailureClass::Timeout); |
| 390 | assert_eq!(w.effect_certainty, EffectCertainty::Uncertain); |
| 391 | assert_eq!(r.class, FailureClass::Timeout); |
| 392 | assert_eq!(r.effect_certainty, EffectCertainty::NoEffect); |
| 393 | assert_eq!(script.count(), 2, "one dispatch each, no timeout retry"); |
| 394 | } |
| 395 | |
| 396 | #[tokio::test] |
| 397 | async fn unavailable_backend_is_unavailable_with_no_effect() { |
| 398 | let script = Script::new(vec![( |
| 399 | "cortex_recall", |
| 400 | vec![Behavior::Fault(ToolFault::unavailable( |
| 401 | "Unavailable: backend not reachable", |
| 402 | ))], |
| 403 | )]); |
| 404 | let res = engine( |
| 405 | ScriptedModel::new(vec![calls(&[("u", "cortex_recall", path())]), done()]), |
| 406 | script, |
| 407 | ) |
| 408 | .execute_task("goal", Some("sys"), 3) |
| 409 | .await |
| 410 | .unwrap(); |
| 411 | let f = res.steps[0].tool_calls[0].failure.as_ref().unwrap(); |
| 412 | assert_eq!(f.class, FailureClass::Unavailable); |
| 413 | assert_eq!(f.effect_certainty, EffectCertainty::NoEffect); |
| 414 | } |
| 415 | |
| 416 | #[tokio::test] |
| 417 | async fn real_registry_paths_classify_refusal_and_keep_old_output_text() { |
| 418 | let model = ScriptedModel::new(vec![ |
| 419 | calls(&[("x", "nonexistent_custom_skill", serde_json::json!({}))]), |
| 420 | done(), |
| 421 | ]); |
| 422 | let agent = AgentEngine::new(model, Arc::new(SkillRegistry::new()), None).with_run_id("run_r"); |
| 423 | let res = agent.execute_task("goal", Some("sys"), 3).await.unwrap(); |
| 424 | let rec = &res.steps[0].tool_calls[0]; |
| 425 | assert!(rec.output.contains("not on the dispatch allowlist")); |
| 426 | let f = rec.failure.as_ref().unwrap(); |
| 427 | assert_eq!(f.class, FailureClass::Rejected); |
| 428 | assert_eq!(f.effect_certainty, EffectCertainty::NoEffect); |
| 429 | |
| 430 | // Registered but unconnected handler reports Unavailable. The probe gate |
| 431 | // may refuse first depending on its deterministic verdict, which is also |
| 432 | // an acceptable no-effect outcome; both must be NoEffect and not Failed. |
| 433 | let model2 = ScriptedModel::new(vec![ |
| 434 | calls(&[("y", "cortex_recall", serde_json::json!({"query": "q"}))]), |
| 435 | done(), |
| 436 | ]); |
| 437 | let agent2 = AgentEngine::new(model2, Arc::new(SkillRegistry::new()), None); |
| 438 | let res2 = agent2.execute_task("goal", Some("sys"), 3).await.unwrap(); |
| 439 | let f2 = res2.steps[0].tool_calls[0].failure.as_ref().unwrap(); |
| 440 | assert!(matches!( |
| 441 | f2.class, |
| 442 | FailureClass::Unavailable | FailureClass::Rejected |
| 443 | )); |
| 444 | assert_eq!(f2.effect_certainty, EffectCertainty::NoEffect); |
| 445 | } |
| 446 | |
| 447 | #[tokio::test] |
| 448 | async fn idempotent_read_retries_with_bounded_attempts_and_provenance() { |
| 449 | let un = || Behavior::Fault(ToolFault::unavailable("Unavailable: warming up")); |
| 450 | // Succeeds on third attempt. |
| 451 | let script = Script::new(vec![("read_file", vec![un(), un(), Behavior::Ok])]); |
| 452 | let res = engine( |
| 453 | ScriptedModel::new(vec![calls(&[("r", "read_file", path())]), done()]), |
| 454 | script.clone(), |
| 455 | ) |
| 456 | .with_failure_policy(retry(3)) |
| 457 | .execute_task("goal", Some("sys"), 3) |
| 458 | .await |
| 459 | .unwrap(); |
| 460 | let rec = &res.steps[0].tool_calls[0]; |
| 461 | assert!(rec.success); |
| 462 | assert!(rec.failure.is_none()); |
| 463 | assert_eq!(script.count(), 3, "each attempt is a new dispatch"); |
| 464 | let attempts: Vec<u32> = rec.retry_failures.iter().map(|f| f.attempt).collect(); |
| 465 | assert_eq!(attempts, vec![1, 2]); |
| 466 | assert!(rec.retry_failures[0].sequence < rec.retry_failures[1].sequence); |
| 467 | |
| 468 | // Budget exhausted at the policy bound, not beyond it. |
| 469 | let script2 = Script::new(vec![("read_file", vec![un(), un(), un(), un(), un()])]); |
| 470 | let res2 = engine( |
| 471 | ScriptedModel::new(vec![calls(&[("r", "read_file", path())]), done()]), |
| 472 | script2.clone(), |
| 473 | ) |
| 474 | .with_failure_policy(retry(2)) |
| 475 | .execute_task("goal", Some("sys"), 3) |
| 476 | .await |
| 477 | .unwrap(); |
| 478 | let rec2 = &res2.steps[0].tool_calls[0]; |
| 479 | assert!(!rec2.success); |
| 480 | assert_eq!(script2.count(), 2); |
| 481 | assert_eq!(rec2.failure.as_ref().unwrap().attempt, 2); |
| 482 | assert_eq!(rec2.retry_failures.len(), 1); |
| 483 | } |
| 484 | |
| 485 | #[tokio::test] |
| 486 | async fn default_policy_does_not_retry() { |
| 487 | let script = Script::new(vec![( |
| 488 | "read_file", |
| 489 | vec![Behavior::Fault(ToolFault::unavailable("Unavailable: x"))], |
| 490 | )]); |
| 491 | let res = engine( |
| 492 | ScriptedModel::new(vec![calls(&[("r", "read_file", path())]), done()]), |
| 493 | script.clone(), |
| 494 | ) |
| 495 | .execute_task("goal", Some("sys"), 3) |
| 496 | .await |
| 497 | .unwrap(); |
| 498 | assert_eq!(script.count(), 1); |
| 499 | assert!(!res.steps[0].tool_calls[0].success); |
| 500 | } |
| 501 | |
| 502 | #[tokio::test] |
| 503 | async fn uncertain_or_mutating_failures_are_never_retried() { |
| 504 | let cases: Vec<(&str, ToolFault)> = vec![ |
| 505 | ( |
| 506 | "write_file", |
| 507 | ToolFault::new(FailureClass::Uncertain, EffectCertainty::Uncertain, "lost"), |
| 508 | ), |
| 509 | // Even a no-effect refusal is not retried for a non idempotent write. |
| 510 | ("write_file", ToolFault::rejected("refused")), |
| 511 | ( |
| 512 | "read_file", |
| 513 | ToolFault::rejected("not on the dispatch allowlist"), |
| 514 | ), |
| 515 | ( |
| 516 | "read_file", |
| 517 | ToolFault::new(FailureClass::Uncertain, EffectCertainty::Uncertain, "lost"), |
| 518 | ), |
| 519 | ( |
| 520 | "read_file", |
| 521 | ToolFault::new(FailureClass::Failed, EffectCertainty::NoEffect, "boom"), |
| 522 | ), |
| 523 | ( |
| 524 | "read_file", |
| 525 | ToolFault::new( |
| 526 | FailureClass::Malformed, |
| 527 | EffectCertainty::NoEffect, |
| 528 | "bad shape", |
| 529 | ), |
| 530 | ), |
| 531 | ( |
| 532 | "read_file", |
| 533 | ToolFault::new( |
| 534 | FailureClass::Unavailable, |
| 535 | EffectCertainty::Uncertain, |
| 536 | "maybe ran", |
| 537 | ), |
| 538 | ), |
| 539 | ]; |
| 540 | for (tool, fault) in cases { |
| 541 | let script = Script::new(vec![(tool, vec![Behavior::Fault(fault.clone())])]); |
| 542 | let res = engine( |
| 543 | ScriptedModel::new(vec![calls(&[("c", tool, path())]), done()]), |
| 544 | script.clone(), |
| 545 | ) |
| 546 | .with_failure_policy(retry(5)) |
| 547 | .execute_task("goal", Some("sys"), 3) |
| 548 | .await |
| 549 | .unwrap(); |
| 550 | assert_eq!(script.count(), 1, "{} {:?} was replayed", tool, fault); |
| 551 | assert!(!res.steps[0].tool_calls[0].success); |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | #[tokio::test] |
| 556 | async fn approval_pending_is_never_auto_continued() { |
| 557 | let script = Script::new(vec![( |
| 558 | "read_file", |
| 559 | vec![Behavior::Fault(ToolFault::new( |
| 560 | FailureClass::ApprovalPending, |
| 561 | EffectCertainty::NoEffect, |
| 562 | "needs a human", |
| 563 | ))], |
| 564 | )]); |
| 565 | let model = ScriptedModel::new(vec![ |
| 566 | calls(&[("p", "read_file", path()), ("q", "list_dir", path())]), |
| 567 | done(), |
| 568 | ]); |
| 569 | let res = engine(model.clone(), script.clone()) |
| 570 | .with_failure_policy(retry(5)) |
| 571 | .execute_task("goal", Some("sys"), 5) |
| 572 | .await |
| 573 | .unwrap(); |
| 574 | assert_eq!(script.count(), 1, "no replay and no following call"); |
| 575 | assert_eq!(model.asked.load(Ordering::SeqCst), 1, "model not re-asked"); |
| 576 | assert!(!res.completed); |
| 577 | assert!(res.final_response.contains("waiting for approval")); |
| 578 | assert_eq!( |
| 579 | res.steps[0].tool_calls[0].failure.as_ref().unwrap().class, |
| 580 | FailureClass::ApprovalPending |
| 581 | ); |
| 582 | } |
| 583 | |
| 584 | #[tokio::test] |
| 585 | async fn seeded_secret_never_appears_in_failure_output() { |
| 586 | let args = serde_json::json!({"path": "a.txt", "api_key": SECRET}); |
| 587 | let script = Script::new(vec![( |
| 588 | "write_file", |
| 589 | vec![Behavior::Fault(ToolFault::new( |
| 590 | FailureClass::Failed, |
| 591 | EffectCertainty::EffectOccurred, |
| 592 | format!("handler rejected value {} at offset 3", SECRET), |
| 593 | ))], |
| 594 | )]); |
| 595 | let bus = EventBus::default(); |
| 596 | let mut rx = bus.subscribe(); |
| 597 | let model = ScriptedModel::new(vec![calls(&[("w", "write_file", args)]), done()]); |
| 598 | let res = engine(model.clone(), script) |
| 599 | .with_event_bus(bus, None) |
| 600 | .execute_task("goal", Some("sys"), 3) |
| 601 | .await |
| 602 | .unwrap(); |
| 603 | let f = res.steps[0].tool_calls[0].failure.as_ref().unwrap(); |
| 604 | let ser = serde_json::to_string(f).unwrap(); |
| 605 | let dbg = format!("{:?}", f); |
| 606 | assert!(!ser.contains(SECRET), "serialized: {}", ser); |
| 607 | assert!(!dbg.contains(SECRET), "debug: {}", dbg); |
| 608 | assert!(ser.contains("sha256:")); |
| 609 | // The tool message sent back to the model and the record output are redacted too. |
| 610 | assert!(!res.steps[0].tool_calls[0].output.contains(SECRET)); |
| 611 | assert!(res.steps[0].tool_calls[0].output.contains("[redacted]")); |
| 612 | assert!(model.seen.lock().unwrap().len() >= 2); |
| 613 | // The model's own earlier tool call (its arguments) is history it wrote; the |
| 614 | // tool result message that we send back must be redacted. |
| 615 | let mut tool_msgs = 0; |
| 616 | for seen in model.seen.lock().unwrap().iter() { |
| 617 | let msgs: Vec<serde_json::Value> = serde_json::from_str(seen).unwrap(); |
| 618 | for m in msgs.iter().filter(|m| m["role"] == "tool") { |
| 619 | tool_msgs += 1; |
| 620 | assert!(!m["content"].as_str().unwrap().contains(SECRET)); |
| 621 | } |
| 622 | } |
| 623 | assert!(tool_msgs >= 1); |
| 624 | let ev = rx.try_recv().unwrap(); |
| 625 | assert!(!serde_json::to_string(&ev).unwrap().contains(SECRET)); |
| 626 | assert!(!format!("{:?}", ev).contains(SECRET)); |
| 627 | } |
| 628 | |
| 629 | #[tokio::test] |
| 630 | async fn cause_message_is_bounded_in_a_real_run() { |
| 631 | let long = "z".repeat(5000); |
| 632 | let script = Script::new(vec![( |
| 633 | "read_file", |
| 634 | vec![Behavior::Fault(ToolFault::new( |
| 635 | FailureClass::Failed, |
| 636 | EffectCertainty::NoEffect, |
| 637 | long, |
| 638 | ))], |
| 639 | )]); |
| 640 | let res = engine( |
| 641 | ScriptedModel::new(vec![calls(&[("r", "read_file", path())]), done()]), |
| 642 | script, |
| 643 | ) |
| 644 | .execute_task("goal", Some("sys"), 3) |
| 645 | .await |
| 646 | .unwrap(); |
| 647 | let f = res.steps[0].tool_calls[0].failure.as_ref().unwrap(); |
| 648 | assert!(f.cause.len() <= aegis::failure::MAX_CAUSE_ENTRIES); |
| 649 | assert!(f.cause[0].message.len() <= aegis::failure::MAX_CAUSE_MESSAGE_BYTES); |
| 650 | } |