aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-cli / src / turn_recovery.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! sovereign-core #665: failure classes and one-shot recovery for the `aien` chat loop. |
| 17 | //! |
| 18 | //! Mechanism after Hermes Agent (Nous Research, MIT, commit 5480918), |
| 19 | //! re-implemented; no code copied. |
| 20 | //! |
| 21 | //! A failed model call is put in one class, and each class has at most one |
| 22 | //! recovery per turn. When a class fails a second time the turn stops with a |
| 23 | //! named reason. A recovery can therefore never loop: the number of retries in a |
| 24 | //! turn is bounded by the number of flags. Pure: no I/O, no clock. |
| 25 | |
| 26 | use std::time::Duration; |
| 27 | |
| 28 | /// The output cap the loop starts each turn with (tokens). |
| 29 | pub const BASE_OUTPUT_CAP: usize = 4096; |
| 30 | /// The raised cap used once when a tool call was cut off by the cap. |
| 31 | pub const RAISED_OUTPUT_CAP: usize = 8192; |
| 32 | |
| 33 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 34 | pub enum FailureClass { |
| 35 | /// Network trouble, a dropped stream, or a 5xx from the model seat. |
| 36 | Transient, |
| 37 | /// HTTP 429. |
| 38 | RateLimited, |
| 39 | /// The request was larger than the model's window. |
| 40 | ContextOverflow, |
| 41 | /// The reply ended inside a tool call because it hit the output cap. |
| 42 | OutputTruncated, |
| 43 | /// HTTP 401 or 403: retrying cannot help. |
| 44 | Auth, |
| 45 | /// Anything else. |
| 46 | Fatal, |
| 47 | } |
| 48 | |
| 49 | /// Puts an error from `ChatClient` into a class. The client reports errors as |
| 50 | /// text (`"Model HTTP 429 ..."`, `"Connection failed ..."`, `"Stream error ..."`). |
| 51 | pub fn classify(err: &str) -> FailureClass { |
| 52 | let e = err.to_ascii_lowercase(); |
| 53 | let http = e |
| 54 | .split("model http ") |
| 55 | .nth(1) |
| 56 | .and_then(|rest| rest.get(..3)) |
| 57 | .and_then(|code| code.parse::<u16>().ok()); |
| 58 | let overflow = e.contains("context length") |
| 59 | || e.contains("context_length") |
| 60 | || e.contains("maximum context") |
| 61 | || e.contains("too many tokens") |
| 62 | || e.contains("prompt is too long"); |
| 63 | match http { |
| 64 | _ if overflow => FailureClass::ContextOverflow, |
| 65 | Some(413) => FailureClass::ContextOverflow, |
| 66 | Some(429) => FailureClass::RateLimited, |
| 67 | Some(401) | Some(403) => FailureClass::Auth, |
| 68 | Some(c) if (500..600).contains(&c) => FailureClass::Transient, |
| 69 | Some(_) => FailureClass::Fatal, |
| 70 | None if e.contains("connection failed") |
| 71 | || e.contains("stream error") |
| 72 | || e.contains("timed out") |
| 73 | || e.contains("timeout") => |
| 74 | { |
| 75 | FailureClass::Transient |
| 76 | } |
| 77 | None => FailureClass::Fatal, |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// What the loop does next. |
| 82 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 83 | pub enum Recovery { |
| 84 | /// Ask again after waiting. |
| 85 | Retry { wait: Duration }, |
| 86 | /// Compact the conversation, then ask again. |
| 87 | CompactThenRetry, |
| 88 | /// Ask again with a larger output cap. The cut-off reply is not executed. |
| 89 | RaiseCapThenRetry { max_tokens: usize }, |
| 90 | /// Stop the turn; the reason is shown to the operator. |
| 91 | Stop { reason: &'static str }, |
| 92 | } |
| 93 | |
| 94 | /// One flag per recovery; each is spent at most once per turn. |
| 95 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 96 | pub struct RecoveryFlags { |
| 97 | pub transient_retried: bool, |
| 98 | pub rate_limit_waited: bool, |
| 99 | pub compacted: bool, |
| 100 | pub cap_raised: bool, |
| 101 | } |
| 102 | |
| 103 | impl RecoveryFlags { |
| 104 | /// Picks the recovery for a failure and spends its flag. |
| 105 | pub fn next(&mut self, class: FailureClass) -> Recovery { |
| 106 | fn once(flag: &mut bool, then: Recovery, reason: &'static str) -> Recovery { |
| 107 | if *flag { |
| 108 | Recovery::Stop { reason } |
| 109 | } else { |
| 110 | *flag = true; |
| 111 | then |
| 112 | } |
| 113 | } |
| 114 | match class { |
| 115 | FailureClass::Transient => once( |
| 116 | &mut self.transient_retried, |
| 117 | Recovery::Retry { |
| 118 | wait: Duration::from_secs(2), |
| 119 | }, |
| 120 | "model-unreachable: the model seat failed twice in this turn", |
| 121 | ), |
| 122 | FailureClass::RateLimited => once( |
| 123 | &mut self.rate_limit_waited, |
| 124 | Recovery::Retry { |
| 125 | wait: Duration::from_secs(20), |
| 126 | }, |
| 127 | "rate-limited: still refused after one wait", |
| 128 | ), |
| 129 | FailureClass::ContextOverflow => once( |
| 130 | &mut self.compacted, |
| 131 | Recovery::CompactThenRetry, |
| 132 | "context-overflow: still too long after compacting", |
| 133 | ), |
| 134 | FailureClass::OutputTruncated => once( |
| 135 | &mut self.cap_raised, |
| 136 | Recovery::RaiseCapThenRetry { |
| 137 | max_tokens: RAISED_OUTPUT_CAP, |
| 138 | }, |
| 139 | "tool-call-truncated: the tool call was cut off even at the raised output limit; it was not run", |
| 140 | ), |
| 141 | FailureClass::Auth => Recovery::Stop { |
| 142 | reason: "model-auth: the model seat refused the credentials", |
| 143 | }, |
| 144 | FailureClass::Fatal => Recovery::Stop { |
| 145 | reason: "model-error: an error with no safe recovery", |
| 146 | }, |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | /// True when the reply ends inside an unfinished `<tool_call>` block, which is |
| 152 | /// what a reply cut off by the output cap looks like. Such a call must never |
| 153 | /// run: its arguments are incomplete, and repairing them would be a guess. |
| 154 | pub fn tool_call_truncated(text: &str) -> bool { |
| 155 | match text.rfind("<tool_call>") { |
| 156 | Some(open) => !text[open..].contains("</tool_call>"), |
| 157 | None => false, |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | #[cfg(test)] |
| 162 | mod tests { |
| 163 | use super::*; |
| 164 | |
| 165 | #[test] |
| 166 | fn classifies_the_clients_error_texts() { |
| 167 | assert_eq!( |
| 168 | classify("Model HTTP 429 Too Many Requests: slow down"), |
| 169 | FailureClass::RateLimited |
| 170 | ); |
| 171 | assert_eq!( |
| 172 | classify("Model HTTP 503 Service Unavailable: busy"), |
| 173 | FailureClass::Transient |
| 174 | ); |
| 175 | assert_eq!( |
| 176 | classify("Model HTTP 401 Unauthorized: no"), |
| 177 | FailureClass::Auth |
| 178 | ); |
| 179 | assert_eq!( |
| 180 | classify("Model HTTP 413 Payload Too Large: x"), |
| 181 | FailureClass::ContextOverflow |
| 182 | ); |
| 183 | assert_eq!( |
| 184 | classify( |
| 185 | "Model HTTP 400 Bad Request: This model's maximum context length is 32768 tokens" |
| 186 | ), |
| 187 | FailureClass::ContextOverflow |
| 188 | ); |
| 189 | assert_eq!( |
| 190 | classify("Model HTTP 400 Bad Request: bad json"), |
| 191 | FailureClass::Fatal |
| 192 | ); |
| 193 | assert_eq!( |
| 194 | classify("Connection failed to model seat: refused"), |
| 195 | FailureClass::Transient |
| 196 | ); |
| 197 | assert_eq!(classify("Stream error: reset"), FailureClass::Transient); |
| 198 | assert_eq!(classify("something odd"), FailureClass::Fatal); |
| 199 | } |
| 200 | |
| 201 | #[test] |
| 202 | fn a_forced_failure_loop_stops_after_one_recovery() { |
| 203 | for class in [ |
| 204 | FailureClass::Transient, |
| 205 | FailureClass::RateLimited, |
| 206 | FailureClass::ContextOverflow, |
| 207 | FailureClass::OutputTruncated, |
| 208 | ] { |
| 209 | let mut flags = RecoveryFlags::default(); |
| 210 | assert!( |
| 211 | !matches!(flags.next(class), Recovery::Stop { .. }), |
| 212 | "{class:?}" |
| 213 | ); |
| 214 | assert!( |
| 215 | matches!(flags.next(class), Recovery::Stop { .. }), |
| 216 | "{class:?}" |
| 217 | ); |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | #[test] |
| 222 | fn a_classifier_that_always_fails_terminates() { |
| 223 | // The same failure forever: one recovery, then a stop. |
| 224 | let mut flags = RecoveryFlags::default(); |
| 225 | let mut n = 0; |
| 226 | while !matches!(flags.next(FailureClass::Transient), Recovery::Stop { .. }) { |
| 227 | n += 1; |
| 228 | assert!(n <= 1, "recovery looped"); |
| 229 | } |
| 230 | assert_eq!(n, 1); |
| 231 | |
| 232 | // Every class in turn, forever: at most one recovery per flag, then a stop. |
| 233 | let classes = [ |
| 234 | FailureClass::Transient, |
| 235 | FailureClass::RateLimited, |
| 236 | FailureClass::ContextOverflow, |
| 237 | FailureClass::OutputTruncated, |
| 238 | ]; |
| 239 | let mut flags = RecoveryFlags::default(); |
| 240 | let mut recoveries = 0; |
| 241 | for i in 0.. { |
| 242 | match flags.next(classes[i % classes.len()]) { |
| 243 | Recovery::Stop { .. } => break, |
| 244 | _ => recoveries += 1, |
| 245 | } |
| 246 | assert!(recoveries <= classes.len(), "recovery looped"); |
| 247 | } |
| 248 | assert_eq!(recoveries, classes.len()); |
| 249 | } |
| 250 | |
| 251 | #[test] |
| 252 | fn auth_and_fatal_never_retry() { |
| 253 | let mut flags = RecoveryFlags::default(); |
| 254 | assert!(matches!( |
| 255 | flags.next(FailureClass::Auth), |
| 256 | Recovery::Stop { .. } |
| 257 | )); |
| 258 | assert!(matches!( |
| 259 | flags.next(FailureClass::Fatal), |
| 260 | Recovery::Stop { .. } |
| 261 | )); |
| 262 | } |
| 263 | |
| 264 | #[test] |
| 265 | fn detects_a_tool_call_cut_off_mid_arguments() { |
| 266 | assert!(tool_call_truncated("ok <tool_call>{\"name\":\"write_to_file\",\"arguments\":{\"path\":\"a\",\"content\":\"hal")); |
| 267 | assert!(!tool_call_truncated( |
| 268 | "<tool_call>{\"name\":\"view_file\",\"arguments\":{}}</tool_call>" |
| 269 | )); |
| 270 | assert!(!tool_call_truncated("no tools here")); |
| 271 | // A finished call followed by a cut-off one is still cut off. |
| 272 | assert!(tool_call_truncated( |
| 273 | "<tool_call>{\"name\":\"a\"}</tool_call> then <tool_call>{\"name\":\"b\",\"argu" |
| 274 | )); |
| 275 | } |
| 276 | } |