interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aegis-runtime-mv / src / failure.rs

562 lines · 18114 bytes Raw Blame History
1//! Structured failure provenance and effect-safe retry classification.
2//!
3//! This module is the single public surface for failure vocabulary in AEGIS.
4//! It adds no scheduler and no authority. It only describes what happened to
5//! a tool call, and derives (never grants) whether an automatic retry is
6//! allowed. Every attempt, including a retry, is a fresh dispatch through the
7//! normal gated path, so the gate stays authoritative on each new request.
8//!
9//! Vocabulary follows aien-mcp `CallOutcome {Finished, Rejected, Uncertain}`:
10//! `Rejected` means no effect, `Uncertain` means the effect may have happened.
11
12use serde::{Deserialize, Serialize};
13use sha2::{Digest, Sha256};
14use std::future::Future;
15
16/// Maximum number of entries kept in a cause chain.
17pub const MAX_CAUSE_ENTRIES: usize = 8;
18/// Maximum size in bytes of one cause message.
19pub const MAX_CAUSE_MESSAGE_BYTES: usize = 512;
20/// Hard ceiling on attempts per tool call, whatever the policy says.
21pub const MAX_ATTEMPTS_CEILING: u32 = 5;
22/// Text that replaces a secret-looking argument value found in a message.
23pub const REDACTION_PLACEHOLDER: &str = "[redacted]";
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(rename_all = "snake_case")]
27pub enum FailureClass {
28 /// Refused before acting (allowlist, probe gate, invalid arguments, not found).
29 Rejected,
30 /// Backend, authority or runtime not reachable before any effect.
31 Unavailable,
32 /// Deadline hit; certainty comes from the skill contract.
33 Timeout,
34 /// Cancelled by operator or parent; certainty comes from the skill contract.
35 Cancelled,
36 /// The effect may have happened (lost response).
37 Uncertain,
38 /// The handler ran and reported an error.
39 Failed,
40 /// The tool result was unparsable or broke its schema.
41 Malformed,
42 /// Not a failure: waiting for a human. Terminal for this attempt.
43 ApprovalPending,
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
47#[serde(rename_all = "snake_case")]
48pub enum EffectCertainty {
49 NoEffect,
50 Uncertain,
51 EffectOccurred,
52}
53
54/// Derived, never stored as a grant.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum RetryEligibility {
58 Retryable { max_attempts: u32 },
59 NotRetryable,
60}
61
62/// Retry policy. The default is one attempt, which means no retry.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct RetryPolicy {
65 pub max_attempts: u32,
66}
67
68impl Default for RetryPolicy {
69 fn default() -> Self {
70 Self { max_attempts: 1 }
71 }
72}
73
74/// Pure retry rule. A retry is possible only when the backend was unreachable
75/// before acting (`Unavailable`), no effect occurred, the capability is marked
76/// idempotent, and the policy allows more than one attempt. A `Rejected`
77/// outcome (policy or gate denial) is never retried.
78pub fn retry_eligibility(
79 class: FailureClass,
80 certainty: EffectCertainty,
81 idempotent: bool,
82 policy: &RetryPolicy,
83) -> RetryEligibility {
84 let class_ok = class == FailureClass::Unavailable;
85 let attempts = policy.max_attempts.min(MAX_ATTEMPTS_CEILING);
86 if class_ok && certainty == EffectCertainty::NoEffect && idempotent && attempts > 1 {
87 RetryEligibility::Retryable {
88 max_attempts: attempts,
89 }
90 } else {
91 RetryEligibility::NotRetryable
92 }
93}
94
95/// What the skill contract says about a capability. Unknown names are treated
96/// as mutating (not idempotent).
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct SkillEffectProfile {
99 pub idempotent: bool,
100}
101
102pub fn skill_effect_profile(skill_name: &str) -> SkillEffectProfile {
103 let idempotent = matches!(
104 skill_name,
105 "read_file" | "list_dir" | "git_status" | "cortex.search" | "cortex_recall"
106 );
107 SkillEffectProfile { idempotent }
108}
109
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111pub struct CauseEntry {
112 pub source: String,
113 /// Truncated to `MAX_CAUSE_MESSAGE_BYTES`.
114 pub message: String,
115 /// sha256 of the canonical payload; the payload itself is never stored.
116 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub payload_digest: Option<String>,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121pub struct FailureRecord {
122 /// Stable order among failures of one run (starts at 1).
123 pub sequence: u64,
124 pub run_id: String,
125 pub step_index: usize,
126 pub tool_call_id: String,
127 #[serde(default)]
128 pub parent_call_id: Option<String>,
129 pub tool_name: String,
130 /// 1 based attempt number for this tool call.
131 pub attempt: u32,
132 pub class: FailureClass,
133 pub effect_certainty: EffectCertainty,
134 /// Scheduling point, milliseconds since the Unix epoch.
135 pub created_at: i64,
136 /// Terminal failure point, milliseconds since the Unix epoch.
137 pub failed_at: i64,
138 pub cause: Vec<CauseEntry>,
139 #[serde(default)]
140 pub cause_truncated: bool,
141}
142
143/// Keeps at most `max` bytes, cutting on a character boundary.
144pub fn truncate_bytes(s: &str, max: usize) -> String {
145 if s.len() <= max {
146 return s.to_string();
147 }
148 let mut end = max;
149 while end > 0 && !s.is_char_boundary(end) {
150 end -= 1;
151 }
152 s[..end].to_string()
153}
154
155/// sha256 of the compact JSON form, as `sha256:<hex>`.
156pub fn payload_digest(payload: &serde_json::Value) -> String {
157 let bytes = serde_json::to_vec(payload).unwrap_or_default();
158 let digest = Sha256::digest(&bytes);
159 let mut out = String::from("sha256:");
160 for b in digest {
161 out.push_str(&format!("{:02x}", b));
162 }
163 out
164}
165
166fn collect_strings(v: &serde_json::Value, out: &mut Vec<String>) {
167 match v {
168 serde_json::Value::String(s) => {
169 if s.len() >= 4 {
170 out.push(s.clone());
171 }
172 }
173 serde_json::Value::Array(a) => a.iter().for_each(|x| collect_strings(x, out)),
174 serde_json::Value::Object(m) => m.values().for_each(|x| collect_strings(x, out)),
175 _ => {}
176 }
177}
178
179/// Replaces every argument string value (4 bytes or longer) that appears in
180/// `message`, so an error text that echoes a caller payload cannot leak it.
181pub fn redact_payload_echoes(message: &str, args: &serde_json::Value) -> String {
182 let mut values = Vec::new();
183 collect_strings(args, &mut values);
184 // Longest first so a long value is not half replaced by a shorter one.
185 values.sort_by_key(|v| std::cmp::Reverse(v.len()));
186 let mut out = message.to_string();
187 for v in values {
188 if out.contains(&v) {
189 out = out.replace(&v, REDACTION_PLACEHOLDER);
190 }
191 }
192 out
193}
194
195pub fn now_millis() -> i64 {
196 chrono::Utc::now().timestamp_millis()
197}
198
199impl FailureRecord {
200 #[allow(clippy::too_many_arguments)]
201 pub fn new(
202 sequence: u64,
203 run_id: impl Into<String>,
204 step_index: usize,
205 tool_call_id: impl Into<String>,
206 parent_call_id: Option<String>,
207 tool_name: impl Into<String>,
208 attempt: u32,
209 class: FailureClass,
210 effect_certainty: EffectCertainty,
211 created_at: i64,
212 failed_at: i64,
213 ) -> Self {
214 Self {
215 sequence,
216 run_id: run_id.into(),
217 step_index,
218 tool_call_id: tool_call_id.into(),
219 parent_call_id,
220 tool_name: tool_name.into(),
221 attempt,
222 class,
223 effect_certainty,
224 created_at,
225 failed_at,
226 cause: Vec::new(),
227 cause_truncated: false,
228 }
229 }
230
231 /// Appends one cause. The message is cut to 512 bytes. Past 8 entries the
232 /// extra causes are dropped and `cause_truncated` is set.
233 pub fn push_cause(
234 &mut self,
235 source: impl Into<String>,
236 message: &str,
237 payload: Option<&serde_json::Value>,
238 ) {
239 if self.cause.len() >= MAX_CAUSE_ENTRIES {
240 self.cause_truncated = true;
241 return;
242 }
243 self.cause.push(CauseEntry {
244 source: source.into(),
245 message: truncate_bytes(message, MAX_CAUSE_MESSAGE_BYTES),
246 payload_digest: payload.map(payload_digest),
247 });
248 }
249
250 pub fn with_cause(
251 mut self,
252 source: impl Into<String>,
253 message: &str,
254 payload: Option<&serde_json::Value>,
255 ) -> Self {
256 self.push_cause(source, message, payload);
257 self
258 }
259}
260
261/// Follows `parent_call_id` links to the original failure. Bounded by the
262/// number of records, so a cycle cannot loop forever. Returns the record
263/// itself when it has no known parent among `records`.
264pub fn root_cause<'a>(
265 records: &'a [FailureRecord],
266 start: &FailureRecord,
267) -> Option<&'a FailureRecord> {
268 let mut current = records
269 .iter()
270 .find(|r| r.tool_call_id == start.tool_call_id && r.attempt == start.attempt)?;
271 for _ in 0..=records.len() {
272 let parent = current
273 .parent_call_id
274 .as_ref()
275 .and_then(|pid| records.iter().rfind(|r| &r.tool_call_id == pid));
276 match parent {
277 Some(p) if p.sequence != current.sequence => current = p,
278 _ => return Some(current),
279 }
280 }
281 Some(current)
282}
283
284/// A classified tool-level fault, before it is stamped with run identifiers.
285#[derive(Debug, Clone, PartialEq, Eq)]
286pub struct ToolFault {
287 pub class: FailureClass,
288 pub certainty: EffectCertainty,
289 pub message: String,
290}
291
292impl ToolFault {
293 pub fn new(
294 class: FailureClass,
295 certainty: EffectCertainty,
296 message: impl Into<String>,
297 ) -> Self {
298 Self {
299 class,
300 certainty,
301 message: message.into(),
302 }
303 }
304
305 pub fn rejected(message: impl Into<String>) -> Self {
306 Self::new(FailureClass::Rejected, EffectCertainty::NoEffect, message)
307 }
308
309 pub fn unavailable(message: impl Into<String>) -> Self {
310 Self::new(
311 FailureClass::Unavailable,
312 EffectCertainty::NoEffect,
313 message,
314 )
315 }
316}
317
318/// One failed attempt with its own timing.
319#[derive(Debug, Clone)]
320pub struct AttemptFailure {
321 pub attempt: u32,
322 pub fault: ToolFault,
323 pub created_at: i64,
324 pub failed_at: i64,
325}
326
327/// Bounded retry helper. `attempt_fn` is called once per attempt with the
328/// 1 based attempt number and must perform a brand new gated dispatch each
329/// time; nothing from an earlier attempt is reused. Retries happen only when
330/// `retry_eligibility` says so. Returns the final result and every failed
331/// attempt in order.
332pub async fn retry_loop<T, F, Fut>(
333 policy: &RetryPolicy,
334 idempotent: bool,
335 mut attempt_fn: F,
336) -> (Result<T, ToolFault>, Vec<AttemptFailure>)
337where
338 F: FnMut(u32) -> Fut,
339 Fut: Future<Output = Result<T, ToolFault>>,
340{
341 let mut failures = Vec::new();
342 let mut attempt = 1u32;
343 loop {
344 let created_at = now_millis();
345 match attempt_fn(attempt).await {
346 Ok(v) => return (Ok(v), failures),
347 Err(fault) => {
348 failures.push(AttemptFailure {
349 attempt,
350 fault: fault.clone(),
351 created_at,
352 failed_at: now_millis(),
353 });
354 let again =
355 match retry_eligibility(fault.class, fault.certainty, idempotent, policy) {
356 RetryEligibility::Retryable { max_attempts } => attempt < max_attempts,
357 RetryEligibility::NotRetryable => false,
358 };
359 if !again {
360 return (Err(fault), failures);
361 }
362 attempt += 1;
363 }
364 }
365 }
366}
367
368/// Seam between the agent loop and the gated tool path. The default
369/// implementation is `SkillRegistry`, whose dispatch runs the allowlist and
370/// the probe gate on every call. Tests and other runtimes may supply their own.
371#[async_trait::async_trait]
372pub trait ToolDispatcher: Send + Sync {
373 async fn dispatch(
374 &self,
375 skill_name: &str,
376 arguments: &serde_json::Value,
377 ) -> Result<String, ToolFault>;
378}
379
380/// Cooperative cancellation flag that can also wake an in-flight await.
381#[derive(Clone, Default)]
382pub struct CancelToken {
383 flag: std::sync::Arc<std::sync::atomic::AtomicBool>,
384 notify: std::sync::Arc<tokio::sync::Notify>,
385}
386
387impl CancelToken {
388 pub fn new() -> Self {
389 Self::default()
390 }
391
392 pub fn cancel(&self) {
393 self.flag.store(true, std::sync::atomic::Ordering::SeqCst);
394 self.notify.notify_waiters();
395 }
396
397 pub fn is_cancelled(&self) -> bool {
398 self.flag.load(std::sync::atomic::Ordering::SeqCst)
399 }
400
401 pub async fn cancelled(&self) {
402 loop {
403 let waiter = self.notify.notified();
404 if self.is_cancelled() {
405 return;
406 }
407 waiter.await;
408 }
409 }
410}
411
412#[cfg(test)]
413mod tests {
414 use super::*;
415 use serde_json::json;
416
417 fn rec(seq: u64, call: &str, parent: Option<&str>) -> FailureRecord {
418 FailureRecord::new(
419 seq,
420 "run_1",
421 1,
422 call,
423 parent.map(|p| p.to_string()),
424 "read_file",
425 1,
426 FailureClass::Failed,
427 EffectCertainty::NoEffect,
428 1,
429 2,
430 )
431 }
432
433 #[test]
434 fn eligibility_only_for_no_effect_idempotent_rejected_or_unavailable() {
435 let policy = RetryPolicy { max_attempts: 3 };
436 let classes = [
437 FailureClass::Rejected,
438 FailureClass::Unavailable,
439 FailureClass::Timeout,
440 FailureClass::Cancelled,
441 FailureClass::Uncertain,
442 FailureClass::Failed,
443 FailureClass::Malformed,
444 FailureClass::ApprovalPending,
445 ];
446 let certainties = [
447 EffectCertainty::NoEffect,
448 EffectCertainty::Uncertain,
449 EffectCertainty::EffectOccurred,
450 ];
451 for c in classes {
452 for e in certainties {
453 for idem in [true, false] {
454 let got = retry_eligibility(c, e, idem, &policy);
455 let expect_retry =
456 c == FailureClass::Unavailable && e == EffectCertainty::NoEffect && idem;
457 assert_eq!(
458 got == RetryEligibility::Retryable { max_attempts: 3 },
459 expect_retry,
460 "{:?} {:?} idempotent={}",
461 c,
462 e,
463 idem
464 );
465 }
466 }
467 }
468 }
469
470 #[test]
471 fn default_policy_never_retries_and_ceiling_applies() {
472 let d = RetryPolicy::default();
473 assert_eq!(
474 retry_eligibility(
475 FailureClass::Unavailable,
476 EffectCertainty::NoEffect,
477 true,
478 &d
479 ),
480 RetryEligibility::NotRetryable
481 );
482 let big = RetryPolicy { max_attempts: 1000 };
483 assert_eq!(
484 retry_eligibility(
485 FailureClass::Unavailable,
486 EffectCertainty::NoEffect,
487 true,
488 &big
489 ),
490 RetryEligibility::Retryable {
491 max_attempts: MAX_ATTEMPTS_CEILING
492 }
493 );
494 }
495
496 #[test]
497 fn cause_chain_is_bounded_and_messages_truncated() {
498 let mut r = rec(1, "c1", None);
499 for i in 0..20 {
500 r.push_cause("test", &format!("{}{}", i, "x".repeat(2000)), None);
501 }
502 assert_eq!(r.cause.len(), MAX_CAUSE_ENTRIES);
503 assert!(r.cause_truncated);
504 assert!(r
505 .cause
506 .iter()
507 .all(|c| c.message.len() <= MAX_CAUSE_MESSAGE_BYTES));
508 // Multi byte text is cut on a character boundary.
509 let s = "é".repeat(600);
510 let t = truncate_bytes(&s, MAX_CAUSE_MESSAGE_BYTES);
511 assert!(t.len() <= MAX_CAUSE_MESSAGE_BYTES);
512 assert!(t.chars().all(|c| c == 'é'));
513 }
514
515 #[test]
516 fn payload_is_digest_only_and_secret_never_serialized() {
517 let secret = "sk-live-SEEDED-SECRET-9f3a";
518 let args = json!({"path": "/x", "token": secret, "nested": [{"k": secret}]});
519 let echoed = format!("cannot open {} for reading", secret);
520 let msg = redact_payload_echoes(&echoed, &args);
521 let rec = rec(1, "c1", None).with_cause("tool", &msg, Some(&args));
522 let ser = serde_json::to_string(&rec).unwrap();
523 let dbg = format!("{:?}", rec);
524 assert!(!ser.contains(secret), "serialized leaked: {}", ser);
525 assert!(!dbg.contains(secret), "debug leaked: {}", dbg);
526 assert!(ser.contains("sha256:"));
527 assert!(ser.contains(REDACTION_PLACEHOLDER));
528 }
529
530 #[test]
531 fn root_cause_follows_parents_and_survives_cycles() {
532 let records = vec![
533 rec(1, "a", None),
534 rec(2, "b", Some("a")),
535 rec(3, "c", Some("b")),
536 ];
537 assert_eq!(root_cause(&records, &records[2]).unwrap().tool_call_id, "a");
538 let cyc = vec![rec(1, "a", Some("b")), rec(2, "b", Some("a"))];
539 assert!(root_cause(&cyc, &cyc[0]).is_some());
540 }
541
542 #[test]
543 fn old_json_without_new_fields_still_loads() {
544 let old =
545 r#"{"call_id":"c","tool_name":"read_file","arguments":{},"output":"o","success":true}"#;
546 let r: crate::agent::ToolExecutionRecord = serde_json::from_str(old).unwrap();
547 assert!(r.failure.is_none());
548 assert!(r.retry_failures.is_empty());
549 }
550
551 #[tokio::test]
552 async fn cancel_token_wakes_waiter() {
553 let t = CancelToken::new();
554 let t2 = t.clone();
555 let h = tokio::spawn(async move { t2.cancelled().await });
556 tokio::task::yield_now().await;
557 t.cancel();
558 h.await.unwrap();
559 // Already cancelled: returns immediately.
560 t.cancelled().await;
561 }
562}