Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix: bound optional memory work in agent runs

Steven Enamakele0a17dbedf2b
diff --git a/crates/openhuman-core/src/memory/README.md b/crates/openhuman-core/src/memory/README.md
index 99e411e5bf..c33d4f41e1 100644
--- a/crates/openhuman-core/src/memory/README.md
+++ b/crates/openhuman-core/src/memory/README.md
@@ -298,6 +298,14 @@ The agent `memory` tool applies the same confinement and overwrites any
forget` tool. `learn` stamps the item with facts the model does not choose:
workspace, thread id, memory agent id, the learnings namespace, the tool
call, 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
+ disables further memory calls in that run and returns a tool error asking the
+ model to continue without memory; the next run starts fresh. A timed-out write
+ can already have reached the server, so the error warns against retrying it.
+ Calls outside a harness still have the per-call deadline. RPC operations and
+ explicit settings/import/deletion workflows retain their own behavior.
- `deletion::forget_thread` (`deletion.rs`): called by `threads` when a
thread is deleted. `channels::forget_channel` is called by `channels` on
disconnect.
diff --git a/crates/openhuman-core/src/memory/mod.rs b/crates/openhuman-core/src/memory/mod.rs
index 06e6037a86..e3d6183c64 100644
--- a/crates/openhuman-core/src/memory/mod.rs
+++ b/crates/openhuman-core/src/memory/mod.rs
@@ -41,6 +41,7 @@ pub mod schemas;
pub mod scope;
pub mod sources;
pub mod status;
+mod tool_budget;
pub mod tools;
pub mod types;
pub mod user_scope;
diff --git a/crates/openhuman-core/src/memory/tool_budget.rs b/crates/openhuman-core/src/memory/tool_budget.rs
new file mode 100644
index 0000000000..4b2cf4c200
--- /dev/null
+++ b/crates/openhuman-core/src/memory/tool_budget.rs
@@ -0,0 +1,105 @@
+//! OpenHuman's latency and call budget for optional memory in a chat turn.
+
+use std::collections::{HashMap, VecDeque};
+use std::future::Future;
+use std::sync::Mutex;
+use std::time::Duration;
+use tinytools::ToolResult;
+
+const CALL_TIMEOUT: Duration = Duration::from_secs(15);
+const RUN_TIME_BUDGET: Duration = Duration::from_secs(30);
+const MAX_CALLS: usize = 8;
+const MAX_TRACKED_RUNS: usize = 128;
+const CONTINUE: &str = "Continue answering the user's request without memory. Do not retry memory in this run. A timed-out write may already have been accepted; do not claim it failed or repeat it.";
+
+#[derive(Default)]
+pub(super) struct ToolBudget {
+ runs: Mutex<Runs>,
+}
+
+#[derive(Default)]
+struct Runs {
+ states: HashMap<String, RunBudget>,
+ order: VecDeque<String>,
+}
+
+struct RunBudget {
+ calls: usize,
+ remaining: Duration,
+ disabled: bool,
+}
+
+impl Default for RunBudget {
+ fn default() -> Self {
+ Self {
+ calls: 0,
+ remaining: RUN_TIME_BUDGET,
+ disabled: false,
+ }
+ }
+}
+
+impl ToolBudget {
+ // Reserve time before polling the operation, so parallel reads share the
+ // same budget. Return unused time on completion; never hold a lock across
+ // engine I/O. State is scoped to a harness run, not to the conversation.
+ fn reserve(&self, run_id: Option<&str>) -> Result<Duration, ToolResult> {
+ let Some(run_id) = run_id else {
+ return Ok(CALL_TIMEOUT);
+ };
+ let mut runs = self
+ .runs
+ .lock()
+ .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);
+ }
+ }
+ 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() {
+ return Err(ToolResult::error(format!(
+ "Memory budget exhausted for this run. {CONTINUE}"
+ )));
+ }
+ state.calls += 1;
+ let allowance = state.remaining.min(CALL_TIMEOUT);
+ state.remaining -= allowance;
+ Ok(allowance)
+ }
+
+ /// Bounds optional memory work. A timeout opens the circuit for this run;
+ /// the next run gets a fresh budget. Unscoped callers still get a deadline.
+ pub(super) async fn run(
+ &self,
+ run_id: Option<String>,
+ action: impl Future<Output = ToolResult>,
+ ) -> ToolResult {
+ let allowance = match self.reserve(run_id.as_deref()) {
+ Ok(allowance) => allowance,
+ Err(result) => return result,
+ };
+ let started = tokio::time::Instant::now();
+ 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();
+ }
+ }
+ result.unwrap_or_else(|_| ToolResult::error(format!(
+ "Memory did not finish within its latency budget and is unavailable for this run. {CONTINUE}"
+ )))
+ }
+}
+
+#[cfg(test)]
+#[path = "tool_budget_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/memory/tool_budget_tests.rs b/crates/openhuman-core/src/memory/tool_budget_tests.rs
new file mode 100644
index 0000000000..2997e34895
--- /dev/null
+++ b/crates/openhuman-core/src/memory/tool_budget_tests.rs
@@ -0,0 +1,120 @@
+use super::*;
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::time::Duration;
+
+#[tokio::test(start_paused = true)]
+async fn a_slow_memory_call_returns_and_disables_memory_only_for_its_turn() {
+ let budget = ToolBudget::default();
+ let result = budget
+ .run(Some("turn-one".into()), async {
+ tokio::time::sleep(Duration::from_secs(60)).await;
+ ToolResult::success("late")
+ })
+ .await;
+ assert!(result.is_error);
+ assert!(result.text().contains("Continue answering"));
+ let calls = AtomicUsize::new(0);
+ let result = budget
+ .run(Some("turn-one".into()), async {
+ calls.fetch_add(1, Ordering::SeqCst);
+ ToolResult::success("should not run")
+ })
+ .await;
+ assert!(result.is_error);
+ assert_eq!(calls.load(Ordering::SeqCst), 0);
+ let next = budget
+ .run(Some("turn-two".into()), async {
+ ToolResult::success("healthy")
+ })
+ .await;
+ assert!(!next.is_error);
+}
+
+#[tokio::test]
+async fn successful_memory_churn_is_bounded_without_blocking_the_next_turn() {
+ let budget = ToolBudget::default();
+ let calls = AtomicUsize::new(0);
+ for _ in 0..20 {
+ budget
+ .run(Some("turn-one".into()), async {
+ calls.fetch_add(1, Ordering::SeqCst);
+ ToolResult::success("saved with a different id")
+ })
+ .await;
+ }
+ assert_eq!(calls.load(Ordering::SeqCst), 8);
+ let next = budget
+ .run(Some("turn-two".into()), async {
+ ToolResult::success("healthy")
+ })
+ .await;
+ assert!(!next.is_error);
+}
+
+#[tokio::test(start_paused = true)]
+async fn successful_memory_calls_share_one_latency_budget() {
+ let budget = ToolBudget::default();
+ for _ 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;
+ }
+ }
+ panic!("memory consumed more than thirty seconds in one turn");
+}
+
+#[tokio::test(start_paused = true)]
+async fn callers_without_a_run_id_still_have_a_deadline() {
+ let budget = ToolBudget::default();
+ let result = budget
+ .run(None, async {
+ tokio::time::sleep(Duration::from_secs(60)).await;
+ ToolResult::success("late")
+ })
+ .await;
+ assert!(result.is_error);
+}
+
+#[tokio::test(start_paused = true)]
+async fn parallel_memory_reads_reserve_from_the_same_time_budget() {
+ let budget = ToolBudget::default();
+ let calls = AtomicUsize::new(0);
+ let read = || async {
+ calls.fetch_add(1, Ordering::SeqCst);
+ tokio::time::sleep(Duration::from_secs(12)).await;
+ ToolResult::success("read")
+ };
+ let (first, second, third) = tokio::join!(
+ budget.run(Some("turn".into()), read()),
+ budget.run(Some("turn".into()), read()),
+ budget.run(Some("turn".into()), read()),
+ );
+ assert!(!first.is_error);
+ assert!(!second.is_error);
+ assert!(third.is_error);
+ assert_eq!(calls.load(Ordering::SeqCst), 2);
+ assert_eq!(
+ budget.runs.lock().unwrap().states["turn"].remaining,
+ Duration::from_secs(6)
+ );
+}
+
+#[tokio::test]
+async fn completed_run_tracking_is_bounded() {
+ let budget = ToolBudget::default();
+ for i in 0..200 {
+ budget
+ .run(Some(format!("turn-{i}")), async {
+ ToolResult::success("saved")
+ })
+ .await;
+ }
+ let runs = budget.runs.lock().unwrap();
+ assert_eq!(runs.states.len(), MAX_TRACKED_RUNS);
+ assert_eq!(runs.order.len(), MAX_TRACKED_RUNS);
+}
diff --git a/crates/openhuman-core/src/memory/tools.rs b/crates/openhuman-core/src/memory/tools.rs
index f742d798ad..1ce03faccf 100644
--- a/crates/openhuman-core/src/memory/tools.rs
+++ b/crates/openhuman-core/src/memory/tools.rs
@@ -103,13 +103,17 @@ pub const MEMORY_TOOL_NAME: &str = "memory";
/// The `memory` tool.
pub struct MemoryTool {
config: Arc<Config>,
+ budget: super::tool_budget::ToolBudget,
}
impl MemoryTool {
/// A tool bound to `config`'s engine.
#[must_use]
pub fn new(config: Arc<Config>) -> Self {
- Self { config }
+ Self {
+ config,
+ budget: super::tool_budget::ToolBudget::default(),
+ }
}
}
@@ -351,7 +355,15 @@ impl Tool for MemoryTool {
context: Option<&dyn ToolRunContext>,
) -> anyhow::Result<ToolResult> {
let facts = CallFacts::gather(&self.config, context);
- Ok(run_action(&self.config, &args, &facts).await)
+ let run_id = context
+ .and_then(ToolRunContext::host_extension)
+ .and_then(|any| any.downcast_ref::<tinyagents_harness::tool::ToolExecutionContext>())
+ .map(|ctx| ctx.run_id.as_str().to_string())
+ .or_else(crate::agent::turn_origin::current_request_id);
+ Ok(self
+ .budget
+ .run(run_id, run_action(&self.config, &args, &facts))
+ .await)
}
}
diff --git a/crates/openhuman-core/src/memory/tools_tests.rs b/crates/openhuman-core/src/memory/tools_tests.rs
index ddb21909d3..e96843df9b 100644
--- a/crates/openhuman-core/src/memory/tools_tests.rs
+++ b/crates/openhuman-core/src/memory/tools_tests.rs
@@ -41,6 +41,39 @@ fn text(result: &ToolResult) -> String {
result.text()
}
+#[tokio::test]
+async fn the_memory_tool_stops_write_churn_and_recovers_on_the_next_chat_turn() {
+ use crate::agent::turn_origin::{with_origin, AgentTurnOrigin};
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let engine = bind_reference(&config);
+ let tool = MemoryTool::new(Arc::new(config));
+ let origin = |request: &str| AgentTurnOrigin::WebChat {
+ thread_id: "thread-budget".into(),
+ client_id: "client-budget".into(),
+ request_id: Some(request.into()),
+ };
+ with_origin(origin("first"), async {
+ for i in 0..9 {
+ let result = tool
+ .execute(json!({"action":"learn","text":format!("fact {i}")}))
+ .await
+ .unwrap();
+ assert_eq!(result.is_error, i == 8);
+ }
+ })
+ .await;
+ assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 8);
+ let result = with_origin(
+ origin("next"),
+ tool.execute(json!({"action":"learn","text":"next turn fact"})),
+ )
+ .await
+ .unwrap();
+ assert!(!result.is_error);
+ assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 9);
+}
+
#[test]
fn schema_and_permissions_follow_the_action() {
let tool = MemoryTool::new(Arc::new(Config::default()));
diff --git a/vendor/tinymemory b/vendor/tinymemory
index 11a0bb3150..cefb3e9b2e 160000
--- a/vendor/tinymemory
+++ b/vendor/tinymemory
@@ -1 +1 @@
-Subproject commit 11a0bb3150724bb622e4559673b38ec7f8584e51
+Subproject commit cefb3e9b2e81b041635725ed116a08d0cf45a261