Skip to content

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

fix(memory): keep budget refusals out of the failure breaker; writes skip the cap

M3gA-Mind771f87c98155
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
index 80cd0a5e21..413a35be48 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
@@ -418,6 +418,16 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
self.stop.record_refusal();
return Ok(());
}
+ // The memory budget refusing a call past its cap is the host's own
+ // limit (`memory::tool_budget`), not a failure: a parallel batch of
+ // memory calls past the cap must not halt the run (#7717).
+ if crate::memory::tools::is_budget_refusal(result) {
+ tracing::debug!(
+ tool = tool_name,
+ "[tinyagents::mw] skipping memory budget refusal in failure ladder"
+ );
+ return Ok(());
+ }
let step = self.step.fetch_add(1, Ordering::SeqCst) + 1;
// Body-level failure signal: `validate_workflow` / `dry_run_workflow`
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_memory_budget_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_memory_budget_tests.rs
new file mode 100644
index 0000000000..a319578b41
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_memory_budget_tests.rs
@@ -0,0 +1,83 @@
+//! A memory budget refusal is the host's own limit, not the tool failing:
+//! a parallel batch of memory calls past the cap must not halt the run
+//! (#7717).
+
+use super::*;
+use crate::memory::test_fixtures::{bind_reference, config_in};
+use crate::memory::tools::{is_budget_refusal, MemoryTool};
+use tinyagents_harness::ids::CallId;
+use tinyagents_harness::tool::ToolExecutionContext;
+use tinytools::ToolCallOptions;
+
+/// Spends one run's read budget, then returns the refusals of `count`
+/// further reads, as the memory tool answers them.
+async fn budget_refusals(count: usize) -> Vec<TaToolResult> {
+ let tmp = tempfile::tempdir().unwrap();
+ let config = config_in(&tmp);
+ let _engine = bind_reference(&config);
+ let tool = MemoryTool::new(Arc::new(config));
+ let run: RunContext = RunContext::new(RunConfig::new("budget-run"), ());
+ let mut refusals = Vec::new();
+ for i in 0..8 + count {
+ let context = ToolExecutionContext::from_run_context(&run, CallId::new(format!("r{i}")));
+ let result = tool
+ .execute_with_context(
+ json!({"action":"fetch","query":"plan"}),
+ ToolCallOptions::default(),
+ Some(&context),
+ )
+ .await
+ .unwrap();
+ if is_budget_refusal(&result) {
+ refusals.push(result);
+ }
+ }
+ assert_eq!(refusals.len(), count, "only the reads past the cap refuse");
+ refusals
+}
+
+/// Feeds `results` to a fresh breaker as one batch of `memory` calls and
+/// returns how many times it paused the run.
+async fn pauses_for(results: Vec<TaToolResult>) -> usize {
+ let handle = SteeringHandle::allow_all();
+ let breaker = RepeatedToolFailureMiddleware::new(
+ handle.clone(),
+ 3,
+ std::sync::Arc::new(std::sync::Mutex::new(None)),
+ );
+ let mut ctx = ctx();
+ for (i, mut result) in results.into_iter().enumerate() {
+ breaker
+ .after_tool(
+ &mut ctx,
+ &(),
+ &invocation(format!("memory-{i}"), "memory"),
+ &mut result,
+ )
+ .await
+ .unwrap();
+ }
+ drain_pause_count(&handle)
+}
+
+#[tokio::test]
+async fn memory_budget_refusals_do_not_halt_the_run() {
+ let refusals = budget_refusals(9).await;
+ assert_eq!(pauses_for(refusals).await, 0);
+}
+
+/// The control: the same refusals without the budget's marker are ordinary
+/// failures and do halt, so the skip above is what keeps the run going.
+#[tokio::test]
+async fn the_same_refusals_unmarked_still_halt_the_run() {
+ let unmarked = budget_refusals(9)
+ .await
+ .into_iter()
+ .map(|mut result| {
+ result.metadata = None;
+ assert!(!is_budget_refusal(&result));
+ result
+ })
+ .collect();
+ assert!(pauses_for(unmarked).await > 0);
+}
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs
index 365959b813..5ce0295899 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs
@@ -402,6 +402,8 @@ mod failure_effect_tests;
mod failure_policy_class_tests;
#[path = "middleware_loop_guard_tests.rs"]
mod loop_guard_tests;
+#[path = "middleware_memory_budget_tests.rs"]
+mod memory_budget_tests;
#[path = "middleware_stop_cause_tests.rs"]
mod stop_cause_tests;
diff --git a/crates/openhuman-core/src/memory/tool_budget.rs b/crates/openhuman-core/src/memory/tool_budget.rs
index ce2d8fda1e..8afc305417 100644
--- a/crates/openhuman-core/src/memory/tool_budget.rs
+++ b/crates/openhuman-core/src/memory/tool_budget.rs
@@ -13,6 +13,22 @@ 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.";
+/// Host-only metadata key on a call the budget refused without running it.
+const REFUSAL_METADATA_KEY: &str = "openhuman.memory_budget";
+
+/// A refusal: the budget's own verdict, not the tool failing.
+fn refusal(text: String) -> ToolResult {
+ ToolResult::error(text).with_metadata(serde_json::json!({ REFUSAL_METADATA_KEY: "refused" }))
+}
+
+/// Whether the budget refused `result` without running the action. Failure
+/// ladders skip these: a parallel batch past the cap must not halt the run.
+pub fn is_budget_refusal(result: &ToolResult) -> bool {
+ result
+ .metadata
+ .as_ref()
+ .is_some_and(|metadata| metadata.get(REFUSAL_METADATA_KEY).is_some())
+}
#[derive(Default)]
pub(super) struct ToolBudget {
@@ -91,7 +107,7 @@ impl ToolBudget {
.position(|id| runs.states[id].in_flight == 0)
else {
tracing::debug!(run_id, cutoff = "tracking_full", "[memory:budget] cutoff");
- return Err(ToolResult::error(format!(
+ return Err(refusal(format!(
"Memory is busy with other runs. {CONTINUE}"
)));
};
@@ -110,7 +126,7 @@ impl ToolBudget {
remaining_ms = state.remaining.as_millis(),
"[memory:budget] cutoff"
);
- return Err(ToolResult::error(format!(
+ return Err(refusal(format!(
"Memory budget exhausted for this run. {CONTINUE}"
)));
}
diff --git a/crates/openhuman-core/src/memory/tools.rs b/crates/openhuman-core/src/memory/tools.rs
index c2ad556201..da02d9aaeb 100644
--- a/crates/openhuman-core/src/memory/tools.rs
+++ b/crates/openhuman-core/src/memory/tools.rs
@@ -32,6 +32,7 @@ use crate::core::events::DomainEvent;
use super::error::MemoryError;
use super::ops;
+pub use super::tool_budget::is_budget_refusal;
use super::types::{FetchParams, ForgetParams, LearnParams, RecallParams, TurnCitation};
/// Most citations kept per thread between two drains.
@@ -361,34 +362,35 @@ impl Tool for MemoryTool {
.and_then(ToolRunContext::host_extension)
.and_then(|any| any.downcast_ref::<tinyagents_harness::tool::ToolExecutionContext>())
.map(|ctx| ctx.run_id.as_str().to_string());
+ // Writes are local queue entries, bounded by the outbox (`tool_writes`),
+ // so only engine reads spend the run's call and latency budget.
+ if matches!(
+ args.get("action").and_then(Value::as_str),
+ Some("learn" | "forget")
+ ) {
+ let config = self.config.clone();
+ let write_args = args.clone();
+ let queued = crate::core::runtime::spawn_blocking_scoped(move || {
+ super::tool_writes::enqueue(&config, &write_args, &facts)
+ })
+ .await;
+ return Ok(
+ match queued.unwrap_or_else(|_| {
+ Err(MemoryError::Unavailable(
+ "memory write queue unavailable".into(),
+ ))
+ }) {
+ Ok(value) => {
+ super::tool_writes::schedule(self.config.clone());
+ ToolResult::success(value.to_string())
+ }
+ Err(error) => ToolResult::error(render_error(error)),
+ },
+ );
+ }
Ok(self
.budget
- .run(run_id, async {
- if matches!(
- args.get("action").and_then(Value::as_str),
- Some("learn" | "forget")
- ) {
- let config = self.config.clone();
- let write_args = args.clone();
- let queued = crate::core::runtime::spawn_blocking_scoped(move || {
- super::tool_writes::enqueue(&config, &write_args, &facts)
- })
- .await;
- match queued.unwrap_or_else(|_| {
- Err(MemoryError::Unavailable(
- "memory write queue unavailable".into(),
- ))
- }) {
- Ok(value) => {
- super::tool_writes::schedule(self.config.clone());
- ToolResult::success(value.to_string())
- }
- Err(error) => ToolResult::error(render_error(error)),
- }
- } else {
- run_action(&self.config, &args, &facts).await
- }
- })
+ .run(run_id, run_action(&self.config, &args, &facts))
.await)
}
}
diff --git a/crates/openhuman-core/src/memory/tools_budget_tests.rs b/crates/openhuman-core/src/memory/tools_budget_tests.rs
index d36cee7afd..187a46cdc0 100644
--- a/crates/openhuman-core/src/memory/tools_budget_tests.rs
+++ b/crates/openhuman-core/src/memory/tools_budget_tests.rs
@@ -7,16 +7,18 @@ use tinyagents_harness::tool::ToolExecutionContext;
use tinymemory_api::MetaFilter;
#[tokio::test]
-async fn the_memory_tool_stops_write_churn_and_recovers_on_the_next_chat_turn() {
+async fn learn_is_not_capped_but_reads_are_and_recover_on_the_next_chat_turn() {
let tmp = tempfile::tempdir().unwrap();
let config = config_in(&tmp);
let engine = bind_reference(&config);
let tool = MemoryTool::new(Arc::new(config.clone()));
let first: RunContext = RunContext::new(RunConfig::new("first"), ());
let next: RunContext = RunContext::new(RunConfig::new("next"), ());
- for i in 0..9 {
+ // Eleven learns in one run, as one parallel batch sends them (#7717):
+ // writes are local queue entries and never spend the read budget.
+ for i in 0..11 {
let context =
- ToolExecutionContext::from_run_context(&first, CallId::new(format!("call-{i}")));
+ ToolExecutionContext::from_run_context(&first, CallId::new(format!("learn-{i}")));
let result = tool
.execute_with_context(
json!({"action":"learn","text":format!("fact {i}")}),
@@ -25,26 +27,39 @@ async fn the_memory_tool_stops_write_churn_and_recovers_on_the_next_chat_turn()
)
.await
.unwrap();
- assert_eq!(result.is_error, i == 8);
+ assert!(!result.is_error, "learn {i}: {}", result.text());
}
super::super::tool_writes::drain(&config).await;
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 8);
+ assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 11);
+ // Reads still stop at the cap, refused as the budget's own verdict.
+ for i in 0..9 {
+ let context =
+ ToolExecutionContext::from_run_context(&first, CallId::new(format!("fetch-{i}")));
+ let result = tool
+ .execute_with_context(
+ json!({"action":"fetch","query":"fact"}),
+ ToolCallOptions::default(),
+ Some(&context),
+ )
+ .await
+ .unwrap();
+ assert_eq!(result.is_error, i == 8, "fetch {i}: {}", result.text());
+ assert_eq!(is_budget_refusal(&result), i == 8);
+ }
let context = ToolExecutionContext::from_run_context(&next, CallId::new("next-call"));
let result = tool
.execute_with_context(
- json!({"action":"learn","text":"next turn fact"}),
+ json!({"action":"fetch","query":"fact"}),
ToolCallOptions::default(),
Some(&context),
)
.await
.unwrap();
- assert!(!result.is_error);
- super::super::tool_writes::drain(&config).await;
- assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 9);
+ assert!(!result.is_error, "a new chat turn gets a fresh read budget");
}
#[tokio::test]
-async fn harness_runs_have_independent_budgets_and_identical_learnings_deduplicate() {
+async fn identical_learnings_in_one_run_deduplicate() {
use tinyagents_harness::context::{RunConfig, RunContext};
use tinyagents_harness::ids::CallId;
use tinyagents_harness::tool::ToolExecutionContext;
@@ -63,11 +78,9 @@ async fn harness_runs_have_independent_budgets_and_identical_learnings_deduplica
.execute_with_context(args.clone(), ToolCallOptions::default(), Some(&context))
.await
.unwrap();
- assert_eq!(result.is_error, i == 8);
- if !result.is_error {
- let value: Value = serde_json::from_str(&result.text()).unwrap();
- ids.insert(value["id"].as_str().unwrap().to_string());
- }
+ assert!(!result.is_error, "learn {i}: {}", result.text());
+ let value: Value = serde_json::from_str(&result.text()).unwrap();
+ ids.insert(value["id"].as_str().unwrap().to_string());
}
assert_eq!(
ids.len(),
@@ -79,7 +92,7 @@ async fn harness_runs_have_independent_budgets_and_identical_learnings_deduplica
.execute_with_context(args, ToolCallOptions::default(), Some(&context))
.await
.unwrap();
- assert!(!result.is_error, "a new harness run gets a fresh budget");
+ assert!(!result.is_error, "a learn in a new harness run is accepted");
super::super::tool_writes::drain(&config).await;
assert_eq!(stored(&engine, MetaFilter::default()).await.len(), 1);
}