The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix: retain active memory budgets and refund cancelled calls
Steven Enamakelc6d3c401af8e
diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lockindex 25dd7ce3b7..36e02922d8 100644--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@ -135,7 +135,7 @@ dependencies = ["objc2-foundation 0.3.2","parking_lot","percent-encoding",- "windows-sys 0.52.0",+ "windows-sys 0.59.0","x11rb",]@@ -715,7 +715,7 @@ dependencies = ["cap-primitives","cap-std","io-lifetimes 3.0.1",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -732,7 +732,7 @@ dependencies = ["maybe-owned","rustix","rustix-linux-procfs",- "windows-sys 0.60.2",+ "windows-sys 0.61.2","winx",]@@ -1896,7 +1896,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.52.0",+ "windows-sys 0.59.0",][[package]]@@ -2105,7 +2105,7 @@ checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"dependencies = ["io-lifetimes 2.0.4","rustix",- "windows-sys 0.52.0",+ "windows-sys 0.59.0",][[package]]@@ -2841,7 +2841,7 @@ dependencies = ["js-sys","log","wasm-bindgen",- "windows-core 0.58.0",+ "windows-core 0.57.0",][[package]]@@ -3031,7 +3031,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"dependencies = ["io-lifetimes 3.0.1",- "windows-sys 0.52.0",+ "windows-sys 0.59.0",][[package]]@@ -3743,7 +3743,7 @@ dependencies = ["png 0.18.1","serde","thiserror 2.0.20",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -5292,7 +5292,7 @@ dependencies = ["once_cell","socket2","tracing",- "windows-sys 0.52.0",+ "windows-sys 0.59.0",][[package]]@@ -5711,7 +5711,7 @@ dependencies = ["errno","libc","linux-raw-sys",- "windows-sys 0.52.0",+ "windows-sys 0.59.0",][[package]]@@ -5779,7 +5779,7 @@ dependencies = ["security-framework 3.7.0","security-framework-sys","webpki-root-certs",- "windows-sys 0.52.0",+ "windows-sys 0.59.0",][[package]]@@ -6413,7 +6413,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"dependencies = ["libc",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -7181,10 +7181,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = ["fastrand",- "getrandom 0.3.4",+ "getrandom 0.4.3","once_cell","rustix",- "windows-sys 0.52.0",+ "windows-sys 0.59.0",][[package]]@@ -8060,7 +8060,7 @@ dependencies = [[[package]]name = "tinymemory-api"-version = "1.27.1"+version = "1.27.2"dependencies = ["async-trait","chrono",@@ -8073,7 +8073,7 @@ dependencies = [[[package]]name = "tinymemory-integrations"-version = "1.27.1"+version = "1.27.2"dependencies = ["async-trait","calamine",@@ -8100,7 +8100,7 @@ dependencies = [[[package]]name = "tinymemory-tools"-version = "1.27.1"+version = "1.27.2"dependencies = ["chrono","futures",@@ -8734,7 +8734,7 @@ dependencies = ["png 0.18.1","serde","thiserror 2.0.20",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -8845,7 +8845,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"dependencies = ["memoffset","tempfile",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -9465,7 +9465,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.48.0",+ "windows-sys 0.59.0",][[package]]@@ -10166,7 +10166,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"dependencies = ["bitflags 2.13.2",- "windows-sys 0.52.0",+ "windows-sys 0.59.0",][[package]]diff --git a/crates/openhuman-core/src/memory/README.md b/crates/openhuman-core/src/memory/README.mdindex c33d4f41e1..fa60ad7e9c 100644--- a/crates/openhuman-core/src/memory/README.md+++ b/crates/openhuman-core/src/memory/README.md@@ -300,7 +300,9 @@ The agent `memory` tool applies the same confinement and overwrites anycall, and `source.kind = agent`.`MemoryTool` bounds optional engine work with [`tool_budget.rs`](./tool_budget.rs):15 seconds per call, 30 seconds of aggregate engine time and eight attempts- per harness run. Concurrent reads reserve from the same time budget. A timeout+ per tracked harness run. The bounded tracker retains 128 run records and never+ evicts an outstanding reservation; idle records may age out under run churn.+ Concurrent reads reserve from the same time budget. A timeoutdisables further memory calls in that run and returns a tool error asking themodel to continue without memory; the next run starts fresh. A timed-out writecan already have reached the server, so the error warns against retrying it.diff --git a/crates/openhuman-core/src/memory/tool_budget.rs b/crates/openhuman-core/src/memory/tool_budget.rsindex 4b2cf4c200..ce2d8fda1e 100644--- a/crates/openhuman-core/src/memory/tool_budget.rs+++ b/crates/openhuman-core/src/memory/tool_budget.rs@@ -1,4 +1,6 @@//! OpenHuman's latency and call budget for optional memory in a chat turn.+//! Keeps 128 run records; outstanding reservations cannot be evicted. Idle+//! records may age out under churn, so aggregate limits apply while tracked.use std::collections::{HashMap, VecDeque};use std::future::Future;@@ -27,6 +29,7 @@ struct RunBudget {calls: usize,remaining: Duration,disabled: bool,+ in_flight: usize,}impl Default for RunBudget {@@ -35,6 +38,35 @@ impl Default for RunBudget {calls: 0,remaining: RUN_TIME_BUDGET,disabled: false,+ in_flight: 0,+ }+ }+}++/// Pins a run until its action returns or the caller drops the future. Keeping+/// settlement in Drop also refunds unused time on cooperative cancellation.+struct Reservation<'a> {+ budget: &'a ToolBudget,+ run_id: Option<String>,+ allowance: Duration,+ started: tokio::time::Instant,+ timed_out: bool,+}++impl Drop for Reservation<'_> {+ fn drop(&mut self) {+ let Some(run_id) = self.run_id.as_deref() else {+ return;+ };+ let mut runs = self+ .budget+ .runs+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if let Some(state) = runs.states.get_mut(run_id) {+ state.remaining += self.allowance.saturating_sub(self.started.elapsed());+ state.disabled |= self.timed_out;+ state.in_flight -= 1;}}}@@ -53,19 +85,37 @@ impl ToolBudget {.unwrap_or_else(std::sync::PoisonError::into_inner);if !runs.states.contains_key(run_id) {if runs.order.len() == MAX_TRACKED_RUNS {- if let Some(oldest) = runs.order.pop_front() {- runs.states.remove(&oldest);- }+ let Some(index) = runs+ .order+ .iter()+ .position(|id| runs.states[id].in_flight == 0)+ else {+ tracing::debug!(run_id, cutoff = "tracking_full", "[memory:budget] cutoff");+ return Err(ToolResult::error(format!(+ "Memory is busy with other runs. {CONTINUE}"+ )));+ };+ let oldest = runs.order.remove(index).expect("position is in the queue");+ runs.states.remove(&oldest);}runs.order.push_back(run_id.to_string());}let state = runs.states.entry(run_id.to_string()).or_default();if state.disabled || state.calls >= MAX_CALLS || state.remaining.is_zero() {+ tracing::debug!(+ run_id,+ cutoff = "exhausted",+ calls = state.calls,+ disabled = state.disabled,+ remaining_ms = state.remaining.as_millis(),+ "[memory:budget] cutoff"+ );return Err(ToolResult::error(format!("Memory budget exhausted for this run. {CONTINUE}")));}state.calls += 1;+ state.in_flight += 1;let allowance = state.remaining.min(CALL_TIMEOUT);state.remaining -= allowance;Ok(allowance)@@ -82,18 +132,24 @@ impl ToolBudget {Ok(allowance) => allowance,Err(result) => return result,};- let started = tokio::time::Instant::now();+ let mut reservation = Reservation {+ budget: self,+ run_id,+ allowance,+ started: tokio::time::Instant::now(),+ timed_out: false,+ };let result = tokio::time::timeout(allowance, action).await;- if let Some(run_id) = run_id.as_deref() {- let mut runs = self- .runs- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- if let Some(state) = runs.states.get_mut(run_id) {- state.remaining += allowance.saturating_sub(started.elapsed());- state.disabled |= result.is_err();- }+ reservation.timed_out = result.is_err();+ if reservation.timed_out {+ tracing::debug!(+ run_id = reservation.run_id.as_deref().unwrap_or("unscoped"),+ cutoff = "timeout",+ allowance_ms = allowance.as_millis(),+ "[memory:budget] cutoff"+ );}+ drop(reservation);result.unwrap_or_else(|_| ToolResult::error(format!("Memory did not finish within its latency budget and is unavailable for this run. {CONTINUE}")))diff --git a/crates/openhuman-core/src/memory/tool_budget_tests.rs b/crates/openhuman-core/src/memory/tool_budget_tests.rsindex 2997e34895..790c3ba8f9 100644--- a/crates/openhuman-core/src/memory/tool_budget_tests.rs+++ b/crates/openhuman-core/src/memory/tool_budget_tests.rs@@ -54,18 +54,38 @@ async fn successful_memory_churn_is_bounded_without_blocking_the_next_turn() {#[tokio::test(start_paused = true)]async fn successful_memory_calls_share_one_latency_budget() {let budget = ToolBudget::default();- for _ in 0..3 {+ let started = tokio::time::Instant::now();+ for i in 0..3 {let result = budget.run(Some("turn".into()), async {tokio::time::sleep(Duration::from_secs(12)).await;ToolResult::success("saved")}).await;- if result.is_error {- return;- }+ assert_eq!(result.is_error, i == 2);}- panic!("memory consumed more than thirty seconds in one turn");+ assert_eq!(started.elapsed(), RUN_TIME_BUDGET);+}++#[tokio::test(start_paused = true)]+async fn an_ordinary_tool_error_refunds_unused_time_without_opening_the_circuit() {+ let budget = ToolBudget::default();+ let error = budget+ .run(Some("turn".into()), async {+ tokio::time::sleep(Duration::from_secs(3)).await;+ ToolResult::error("invalid memory arguments")+ })+ .await;+ assert!(error.is_error);+ let next = budget+ .run(Some("turn".into()), async {+ ToolResult::success("healthy")+ })+ .await;+ assert!(!next.is_error);+ let runs = budget.runs.lock().unwrap();+ assert!(!runs.states["turn"].disabled);+ assert_eq!(runs.states["turn"].remaining, Duration::from_secs(27));}#[tokio::test(start_paused = true)]@@ -118,3 +138,66 @@ async fn completed_run_tracking_is_bounded() {assert_eq!(runs.states.len(), MAX_TRACKED_RUNS);assert_eq!(runs.order.len(), MAX_TRACKED_RUNS);}++#[tokio::test(start_paused = true)]+async fn an_outstanding_memory_call_survives_other_runs_and_keeps_its_timeout_circuit() {+ let budget = ToolBudget::default();+ let call = budget.run(Some("active".into()), std::future::pending());+ tokio::pin!(call);+ assert!(futures::poll!(call.as_mut()).is_pending());+ for i in 0..MAX_TRACKED_RUNS {+ budget+ .run(Some(format!("other-{i}")), async {+ ToolResult::success("saved")+ })+ .await;+ }+ assert!(budget.runs.lock().unwrap().states.contains_key("active"));+ assert!(call.await.is_error);+ let calls = AtomicUsize::new(0);+ let result = budget+ .run(Some("active".into()), async {+ calls.fetch_add(1, Ordering::SeqCst);+ ToolResult::success("must not execute")+ })+ .await;+ assert!(result.is_error);+ assert_eq!(calls.load(Ordering::SeqCst), 0);+}++#[tokio::test(start_paused = true)]+async fn full_tracking_refuses_new_work_until_an_active_reservation_is_released() {+ let budget = ToolBudget::default();+ let mut pending = Vec::new();+ for i in 0..MAX_TRACKED_RUNS {+ let mut call = Box::pin(budget.run(Some(format!("active-{i}")), std::future::pending()));+ assert!(futures::poll!(call.as_mut()).is_pending());+ pending.push(call);+ }+ let calls = AtomicUsize::new(0);+ let result = budget+ .run(Some("new".into()), async {+ calls.fetch_add(1, Ordering::SeqCst);+ ToolResult::success("must not execute")+ })+ .await;+ assert!(result.is_error);+ assert_eq!(calls.load(Ordering::SeqCst), 0);+ drop(pending);+ assert!(+ !budget+ .run(Some("new".into()), async { ToolResult::success("healthy") })+ .await+ .is_error+ );+}++#[tokio::test(start_paused = true)]+async fn cancelling_a_call_returns_its_unused_time_reservation() {+ let budget = ToolBudget::default();+ let mut call = Box::pin(budget.run(Some("cancelled".into()), std::future::pending()));+ assert!(futures::poll!(call.as_mut()).is_pending());+ drop(call);+ let runs = budget.runs.lock().unwrap();+ assert_eq!(runs.states["cancelled"].remaining, RUN_TIME_BUDGET);+}