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 / tool_batch.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 #666: run one reply's tool calls as a planned batch. |
| 17 | //! |
| 18 | //! Mechanism after Hermes Agent (Nous Research, MIT, commit 5480918), |
| 19 | //! re-implemented; no code copied. |
| 20 | //! |
| 21 | //! For each segment of the plan (`tool_plan`), in order: |
| 22 | //! 1. every request of the segment is written to the session journal first |
| 23 | //! (persist-before-act, #665), so a crash mid-segment leaves each one |
| 24 | //! recorded as in doubt and none half-known; |
| 25 | //! 2. the calls run: one alone, or up to eight together on scoped threads; |
| 26 | //! 3. oversized results spill to files (`tool_spill`), file before journal; |
| 27 | //! 4. the results are journaled and added to the conversation in the order |
| 28 | //! the model asked for them, whatever order they finished in. |
| 29 | |
| 30 | use crate::tool_plan::{plan, Access, MAX_PARALLEL}; |
| 31 | use crate::tool_spill::{self, SpillBudget}; |
| 32 | use crate::turn_journal::{tool_response_message, Journal, TurnStop}; |
| 33 | use serde_json::{json, Value}; |
| 34 | use std::path::PathBuf; |
| 35 | |
| 36 | pub struct BatchConfig { |
| 37 | pub max_parallel: usize, |
| 38 | pub budget: SpillBudget, |
| 39 | /// Folder for spilled results; `None` keeps an inline preview only. |
| 40 | pub spill_dir: Option<PathBuf>, |
| 41 | } |
| 42 | |
| 43 | impl BatchConfig { |
| 44 | pub fn new(window_tokens: usize, spill_dir: Option<PathBuf>) -> Self { |
| 45 | Self { |
| 46 | max_parallel: MAX_PARALLEL, |
| 47 | budget: SpillBudget::for_window(window_tokens), |
| 48 | spill_dir, |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | /// What a batch did, for the operator's screen. |
| 54 | #[derive(Debug, Default, Clone, PartialEq)] |
| 55 | pub struct BatchReport { |
| 56 | pub segments: usize, |
| 57 | /// Calls that ran together with at least one other call. |
| 58 | pub ran_together: usize, |
| 59 | pub spilled: Vec<PathBuf>, |
| 60 | } |
| 61 | |
| 62 | fn persist(e: crate::turn_journal::JournalError) -> TurnStop { |
| 63 | TurnStop::PersistFailed(e.to_string()) |
| 64 | } |
| 65 | |
| 66 | /// Runs `calls` under the plan. `access` says what each call touches; |
| 67 | /// `dispatch` runs one call and must be safe to call from several threads. |
| 68 | pub fn run_batch<A, D>( |
| 69 | journal: &mut Journal, |
| 70 | messages: &mut Vec<Value>, |
| 71 | calls: Vec<(String, Value)>, |
| 72 | cfg: &BatchConfig, |
| 73 | access: A, |
| 74 | dispatch: D, |
| 75 | ) -> Result<BatchReport, TurnStop> |
| 76 | where |
| 77 | A: Fn(&str, &Value) -> Access, |
| 78 | D: Fn(&str, &Value) -> Value + Sync, |
| 79 | { |
| 80 | let accesses: Vec<Access> = calls.iter().map(|(n, a)| access(n, a)).collect(); |
| 81 | let segments = plan(&accesses, cfg.max_parallel); |
| 82 | let mut report = BatchReport { |
| 83 | segments: segments.len(), |
| 84 | ..BatchReport::default() |
| 85 | }; |
| 86 | let mut turn_used = 0usize; |
| 87 | for seg in &segments { |
| 88 | // 1. Every request of the segment is on disk before any of them runs. |
| 89 | let mut intents = Vec::with_capacity(seg.calls.len()); |
| 90 | for &i in &seg.calls { |
| 91 | intents.push(journal.intent(&calls[i].0, &calls[i].1).map_err(persist)?); |
| 92 | } |
| 93 | // 2. Run. |
| 94 | let results: Vec<Value> = if seg.calls.len() == 1 { |
| 95 | let (n, a) = &calls[seg.calls[0]]; |
| 96 | vec![dispatch(n, a)] |
| 97 | } else { |
| 98 | report.ran_together += seg.calls.len(); |
| 99 | let d = &dispatch; |
| 100 | std::thread::scope(|s| { |
| 101 | let handles: Vec<_> = seg |
| 102 | .calls |
| 103 | .iter() |
| 104 | .map(|&i| { |
| 105 | let (n, a) = &calls[i]; |
| 106 | s.spawn(move || d(n, a)) |
| 107 | }) |
| 108 | .collect(); |
| 109 | handles |
| 110 | .into_iter() |
| 111 | .map(|h| { |
| 112 | h.join().unwrap_or_else( |
| 113 | |_| json!({"error": "the tool stopped with an internal fault (panic)"}), |
| 114 | ) |
| 115 | }) |
| 116 | .collect() |
| 117 | }) |
| 118 | }; |
| 119 | // 3. Spill what is too large, file before journal. |
| 120 | let texts: Vec<String> = results |
| 121 | .iter() |
| 122 | .map(|r| serde_json::to_string(r).unwrap_or_default()) |
| 123 | .collect(); |
| 124 | let sizes: Vec<usize> = texts.iter().map(|t| t.chars().count()).collect(); |
| 125 | let exempt: Vec<bool> = seg |
| 126 | .calls |
| 127 | .iter() |
| 128 | .map(|&i| tool_spill::exempt(&calls[i].0)) |
| 129 | .collect(); |
| 130 | let room = cfg.budget.per_turn.saturating_sub(turn_used); |
| 131 | let spill = tool_spill::choose(&sizes, &exempt, &cfg.budget, room); |
| 132 | // 4. Results in call order. |
| 133 | for (k, &i) in seg.calls.iter().enumerate() { |
| 134 | let name = &calls[i].0; |
| 135 | let shown = if spill[k] { |
| 136 | let full = tool_spill::render_full(name, &intents[k].call_id, &results[k]); |
| 137 | let path = cfg |
| 138 | .spill_dir |
| 139 | .as_ref() |
| 140 | .and_then(|d| tool_spill::write_spill(d, &full).ok()); |
| 141 | if let Some(p) = &path { |
| 142 | report.spilled.push(p.clone()); |
| 143 | } |
| 144 | tool_spill::stub(&results[k], sizes[k], path.as_deref(), &cfg.budget) |
| 145 | } else { |
| 146 | results[k].clone() |
| 147 | }; |
| 148 | let message = tool_response_message(name, &shown); |
| 149 | turn_used += message["content"].as_str().map_or(0, |c| c.chars().count()); |
| 150 | journal.outcome(messages, &intents[k], message)?; |
| 151 | } |
| 152 | } |
| 153 | Ok(report) |
| 154 | } |
| 155 | |
| 156 | #[cfg(test)] |
| 157 | mod tests { |
| 158 | use super::*; |
| 159 | use crate::tool_plan::access_of; |
| 160 | use crate::turn_journal::replay; |
| 161 | use std::path::Path; |
| 162 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 163 | use std::sync::Mutex; |
| 164 | use std::time::Duration; |
| 165 | |
| 166 | fn journal() -> (tempfile::TempDir, Journal, PathBuf) { |
| 167 | let d = tempfile::tempdir().unwrap(); |
| 168 | let p = d.path().join("s.journal.jsonl"); |
| 169 | let j = Journal::create(&p).unwrap(); |
| 170 | (d, j, p) |
| 171 | } |
| 172 | |
| 173 | fn cfg(spill: Option<PathBuf>) -> BatchConfig { |
| 174 | BatchConfig::new(24_000, spill) |
| 175 | } |
| 176 | |
| 177 | fn acc(n: &str, a: &Value) -> Access { |
| 178 | access_of(n, a, Path::new("/w")) |
| 179 | } |
| 180 | |
| 181 | fn body(message: &Value) -> Value { |
| 182 | let c = message["content"].as_str().unwrap(); |
| 183 | let start = c.find('\n').unwrap() + 1; |
| 184 | let end = c.rfind("\n</tool_response>").unwrap(); |
| 185 | serde_json::from_str(&c[start..end]).unwrap() |
| 186 | } |
| 187 | |
| 188 | /// Counts how many calls run at the same moment. |
| 189 | struct Overlap { |
| 190 | now: AtomicUsize, |
| 191 | max: AtomicUsize, |
| 192 | } |
| 193 | impl Overlap { |
| 194 | fn new() -> Self { |
| 195 | Self { |
| 196 | now: AtomicUsize::new(0), |
| 197 | max: AtomicUsize::new(0), |
| 198 | } |
| 199 | } |
| 200 | fn run(&self) -> Value { |
| 201 | let n = self.now.fetch_add(1, Ordering::SeqCst) + 1; |
| 202 | self.max.fetch_max(n, Ordering::SeqCst); |
| 203 | std::thread::sleep(Duration::from_millis(150)); |
| 204 | self.now.fetch_sub(1, Ordering::SeqCst); |
| 205 | json!({"ok": true}) |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | #[test] |
| 210 | fn two_readers_of_one_path_run_together() { |
| 211 | let (_d, mut j, _p) = journal(); |
| 212 | let mut msgs = Vec::new(); |
| 213 | let o = Overlap::new(); |
| 214 | let calls = vec![ |
| 215 | ("view_file".to_string(), json!({"path": "/w/a"})), |
| 216 | ("view_file".to_string(), json!({"path": "/w/a"})), |
| 217 | ]; |
| 218 | let r = run_batch(&mut j, &mut msgs, calls, &cfg(None), acc, |_, _| o.run()).unwrap(); |
| 219 | assert_eq!(o.max.load(Ordering::SeqCst), 2); |
| 220 | assert_eq!((r.segments, r.ran_together), (1, 2)); |
| 221 | assert_eq!(msgs.len(), 2); |
| 222 | } |
| 223 | |
| 224 | #[test] |
| 225 | fn two_writers_on_one_path_never_run_together() { |
| 226 | let (_d, mut j, _p) = journal(); |
| 227 | let mut msgs = Vec::new(); |
| 228 | let o = Overlap::new(); |
| 229 | let calls = vec![ |
| 230 | ( |
| 231 | "write_to_file".to_string(), |
| 232 | json!({"path": "/w/a", "content": "1"}), |
| 233 | ), |
| 234 | ( |
| 235 | "write_to_file".to_string(), |
| 236 | json!({"path": "/w/a", "content": "2"}), |
| 237 | ), |
| 238 | ("view_file".to_string(), json!({"path": "/w/a"})), |
| 239 | ]; |
| 240 | let r = run_batch(&mut j, &mut msgs, calls, &cfg(None), acc, |_, _| o.run()).unwrap(); |
| 241 | assert_eq!(o.max.load(Ordering::SeqCst), 1); |
| 242 | assert_eq!((r.segments, r.ran_together), (3, 0)); |
| 243 | } |
| 244 | |
| 245 | #[test] |
| 246 | fn a_shell_command_never_runs_beside_anything() { |
| 247 | let (_d, mut j, _p) = journal(); |
| 248 | let mut msgs = Vec::new(); |
| 249 | let o = Overlap::new(); |
| 250 | let calls = vec![ |
| 251 | ("view_file".to_string(), json!({"path": "/w/a"})), |
| 252 | ("run_command".to_string(), json!({"command": "ls"})), |
| 253 | ("view_file".to_string(), json!({"path": "/w/b"})), |
| 254 | ]; |
| 255 | run_batch(&mut j, &mut msgs, calls, &cfg(None), acc, |_, _| o.run()).unwrap(); |
| 256 | assert_eq!(o.max.load(Ordering::SeqCst), 1); |
| 257 | } |
| 258 | |
| 259 | #[test] |
| 260 | fn every_request_of_a_segment_is_on_disk_before_any_runs() { |
| 261 | let (_d, mut j, p) = journal(); |
| 262 | let mut msgs = Vec::new(); |
| 263 | let seen = Mutex::new(Vec::new()); |
| 264 | let calls = vec![ |
| 265 | ("view_file".to_string(), json!({"path": "/w/a"})), |
| 266 | ("view_file".to_string(), json!({"path": "/w/b"})), |
| 267 | ("view_file".to_string(), json!({"path": "/w/c"})), |
| 268 | ]; |
| 269 | run_batch(&mut j, &mut msgs, calls, &cfg(None), acc, |_, _| { |
| 270 | let rep = replay(&std::fs::read_to_string(&p).unwrap()).unwrap(); |
| 271 | seen.lock().unwrap().push(rep.in_doubt.len()); |
| 272 | json!({"ok": true}) |
| 273 | }) |
| 274 | .unwrap(); |
| 275 | assert_eq!(*seen.lock().unwrap(), vec![3, 3, 3]); |
| 276 | let rep = replay(&std::fs::read_to_string(&p).unwrap()).unwrap(); |
| 277 | assert!(rep.in_doubt.is_empty()); |
| 278 | assert_eq!(rep.messages, msgs); |
| 279 | } |
| 280 | |
| 281 | #[test] |
| 282 | fn results_come_back_in_call_order_whatever_finishes_first() { |
| 283 | let (_d, mut j, _p) = journal(); |
| 284 | let mut msgs = Vec::new(); |
| 285 | let calls: Vec<(String, Value)> = (0..4) |
| 286 | .map(|i| ("view_file".to_string(), json!({"path": format!("/w/{i}")}))) |
| 287 | .collect(); |
| 288 | run_batch(&mut j, &mut msgs, calls, &cfg(None), acc, |_, a| { |
| 289 | let i: u64 = a["path"].as_str().unwrap()[3..].parse().unwrap(); |
| 290 | std::thread::sleep(Duration::from_millis(40 * (4 - i))); |
| 291 | json!({"i": i}) |
| 292 | }) |
| 293 | .unwrap(); |
| 294 | let order: Vec<u64> = msgs |
| 295 | .iter() |
| 296 | .map(|m| body(m)["i"].as_u64().unwrap()) |
| 297 | .collect(); |
| 298 | assert_eq!(order, vec![0, 1, 2, 3]); |
| 299 | } |
| 300 | |
| 301 | #[test] |
| 302 | fn a_one_megabyte_result_spills_and_the_file_is_addressable() { |
| 303 | let (d, mut j, _p) = journal(); |
| 304 | let spill = d.path().join("spill"); |
| 305 | let mut msgs = Vec::new(); |
| 306 | let big: String = (0..45_000) |
| 307 | .map(|i| format!("line {i:05} of the output\n")) |
| 308 | .collect(); |
| 309 | assert!(big.len() >= 1_000_000); |
| 310 | let c = cfg(Some(spill.clone())); |
| 311 | let r = run_batch( |
| 312 | &mut j, |
| 313 | &mut msgs, |
| 314 | vec![("run_command".to_string(), json!({"command": "big"}))], |
| 315 | &c, |
| 316 | acc, |
| 317 | |_, _| json!({"stdout": big, "exit_code": 0}), |
| 318 | ) |
| 319 | .unwrap(); |
| 320 | let content = msgs[0]["content"].as_str().unwrap(); |
| 321 | assert!( |
| 322 | content.chars().count() < c.budget.per_result, |
| 323 | "{} chars", |
| 324 | content.len() |
| 325 | ); |
| 326 | let b = body(&msgs[0]); |
| 327 | assert_eq!(b["spilled"], json!(true)); |
| 328 | let path = PathBuf::from(b["path"].as_str().unwrap()); |
| 329 | assert_eq!(r.spilled, vec![path.clone()]); |
| 330 | assert!(path.starts_with(&spill)); |
| 331 | let file = std::fs::read_to_string(&path).unwrap(); |
| 332 | assert!( |
| 333 | file.contains(&format!("## stdout\n{big}")), |
| 334 | "the spill file holds the whole output" |
| 335 | ); |
| 336 | assert!(b["preview"].as_str().unwrap().contains("TRUNCATED")); |
| 337 | } |
| 338 | |
| 339 | #[test] |
| 340 | fn a_large_file_read_is_never_spilled() { |
| 341 | let (d, mut j, _p) = journal(); |
| 342 | let mut msgs = Vec::new(); |
| 343 | let big = "x".repeat(200_000); |
| 344 | run_batch( |
| 345 | &mut j, |
| 346 | &mut msgs, |
| 347 | vec![("view_file".to_string(), json!({"path": "/w/a"}))], |
| 348 | &cfg(Some(d.path().join("spill"))), |
| 349 | acc, |
| 350 | |_, _| json!({"content": big}), |
| 351 | ) |
| 352 | .unwrap(); |
| 353 | assert_eq!(body(&msgs[0])["content"].as_str().unwrap().len(), 200_000); |
| 354 | assert!(!d.path().join("spill").exists()); |
| 355 | } |
| 356 | |
| 357 | #[test] |
| 358 | fn when_the_spill_file_cannot_be_written_a_preview_is_still_kept() { |
| 359 | let (d, mut j, _p) = journal(); |
| 360 | let blocker = d.path().join("not-a-dir"); |
| 361 | std::fs::write(&blocker, b"x").unwrap(); |
| 362 | let mut msgs = Vec::new(); |
| 363 | run_batch( |
| 364 | &mut j, |
| 365 | &mut msgs, |
| 366 | vec![("run_command".to_string(), json!({"command": "big"}))], |
| 367 | &cfg(Some(blocker)), |
| 368 | acc, |
| 369 | |_, _| json!({"stdout": "y".repeat(50_000), "status": "ok"}), |
| 370 | ) |
| 371 | .unwrap(); |
| 372 | let b = body(&msgs[0]); |
| 373 | assert_eq!(b["spilled"], json!(false)); |
| 374 | assert!(b["note"].as_str().unwrap().contains("could not be saved")); |
| 375 | assert_eq!(b["status"], json!("ok"), "the status is carried over"); |
| 376 | } |
| 377 | |
| 378 | #[test] |
| 379 | fn a_panicking_tool_in_a_parallel_segment_does_not_lose_the_others() { |
| 380 | let (_d, mut j, _p) = journal(); |
| 381 | let mut msgs = Vec::new(); |
| 382 | let calls = vec![ |
| 383 | ("view_file".to_string(), json!({"path": "/w/a"})), |
| 384 | ("view_file".to_string(), json!({"path": "/w/boom"})), |
| 385 | ]; |
| 386 | run_batch(&mut j, &mut msgs, calls, &cfg(None), acc, |_, a| { |
| 387 | if a["path"] == "/w/boom" { |
| 388 | panic!("tool fault"); |
| 389 | } |
| 390 | json!({"ok": true}) |
| 391 | }) |
| 392 | .unwrap(); |
| 393 | assert_eq!(body(&msgs[0]), json!({"ok": true})); |
| 394 | assert!(body(&msgs[1])["error"].as_str().unwrap().contains("panic")); |
| 395 | } |
| 396 | } |