Skip to content

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

fix(tinyagents): bound the restored results and the artifact contents list\n\nBoth from CodeRabbit's review on #6068, and both are the same mistake in\ndifferent places: a message this branch adds that nothing downstream can shrink.\n\n**The contents list could not be shrunk by anything.**\n`ArtifactIndexTocMiddleware` emits a system message, chosen precisely so the\nladder cannot take it — compression keeps system messages verbatim and\n`ImageAwareMessageTrimMiddleware` never evicts one. That is what makes an\nartifact pointer survive; it also means a turn that persisted enough oversized\nresults would grow an unbounded, un-evictable message, and the guarantee that\nmade the pointers safe would be the thing that broke the request. The list is\nnow capped against a tenth of the input allowance and reports how many results\nit left out, so the model still knows they exist.\n\n**Restoration could provoke an eviction.** `FinalCallWrapUpMiddleware` restores\ncleared tool bodies after compression has already run, so an unbounded restore\npushes the request past the window and the trim then evicts whole messages —\nstrictly more destructive than the blanking being undone, and able to discard\nthe very results just restored.\n\nThe review proposed a compression phase after restoration. That is a second\nsummarizer model call on the one call already about to produce the conclusion,\nand it repairs an overflow that is preventable instead: restoring under the same\nallowance the trim enforces means the trim never has cause to fire. Restoration\nis now budget-aware and newest-first — recency is relevance here, because the\nfinal round's results are the ones the model has not seen (the cap is checked\nbefore the request is built) and the earliest are the most likely to be\nreflected in the compression summary already. What does not fit stays cleared,\nand the count of what stayed cleared is logged rather than left silent.\n\nAdds a test for each bound: restoration stops short of the allowance and\nrestores newest-first, and the contents list stays inside its cap while\ndisclosing the omitted count.\n

sanil-238a6953c5dd24
diff --git a/src/openhuman/agent/tinyagents/middleware_part_06.rs b/src/openhuman/agent/tinyagents/middleware_part_06.rs
index adf08d10b8..87575f2a2d 100644
--- a/src/openhuman/agent/tinyagents/middleware_part_06.rs
+++ b/src/openhuman/agent/tinyagents/middleware_part_06.rs
@@ -58,6 +58,10 @@ pub(crate) struct FinalCallWrapUpMiddleware {
/// Every tool call's captured outcome, so the concluding call can be given
/// back the results microcompact blanked (see `before_model`).
outcomes: crate::openhuman::agent::tinyagents::ToolOutcomeSink,
+ /// The input-token allowance the trim downstream enforces, so restoration
+ /// can stay under it rather than provoking an eviction. `0` disables the
+ /// bound (a model advertising no context window).
+ input_budget: u64,
/// Set when the injection fires, so the caller can report the turn as
/// capped. Necessary because this turn now ends *naturally* — the model
/// returns text and requests no tools, which is the loop's ordinary
@@ -70,10 +74,12 @@ impl FinalCallWrapUpMiddleware {
pub(crate) fn new(
instruction: &'static str,
outcomes: crate::openhuman::agent::tinyagents::ToolOutcomeSink,
+ input_budget: u64,
) -> Self {
Self {
instruction,
outcomes,
+ input_budget,
fired: Arc::new(std::sync::atomic::AtomicBool::new(false)),
}
}
@@ -145,10 +151,36 @@ impl Middleware<()> for FinalCallWrapUpMiddleware {
// the one this call wants — everything when it fits, an LLM summary of
// the older slice when it does not, and oldest-first eviction only in
// extremis. What it never does again is silently blank the middle.
+ // Restore newest-first, and only while the request still fits.
+ //
+ // CodeRabbit on #6068: restoration runs AFTER `ContextCompressionMiddleware`
+ // and before `ImageAwareMessageTrimMiddleware`, so an unbounded restore can
+ // push the request over the window and the trim then evicts whole
+ // messages — which is strictly more destructive than the blanking being
+ // undone, and can discard the very results just restored.
+ //
+ // The review suggested a compression phase after restoration. That is a
+ // second summarizer model call on the one call already about to produce
+ // the conclusion, and it is avoidable: the overflow is preventable
+ // rather than repairable. Restoring under the same budget the trim
+ // enforces means the trim never has cause to fire, so nothing is
+ // evicted and nothing needs re-summarising.
+ //
+ // Newest-first because recency is relevance here: the last rounds'
+ // results are the ones the model has not seen (the cap is checked
+ // before the request is built), and the earliest ones are most likely
+ // already reflected in the compression summary above.
+ let budget = self.input_budget;
+ let mut used: u64 = request
+ .messages
+ .iter()
+ .map(estimate_message_tokens)
+ .sum();
let restored = match self.outcomes.lock() {
Ok(outcomes) => {
let mut restored = 0usize;
- for message in request.messages.iter_mut() {
+ let mut skipped = 0usize;
+ for message in request.messages.iter_mut().rev() {
let TaMessage::Tool(tool) = message else {
continue;
};
@@ -172,9 +204,32 @@ impl Middleware<()> for FinalCallWrapUpMiddleware {
if outcome.trim().is_empty() {
continue;
}
+ // What restoring this body would add, against what the
+ // placeholder already costs.
+ let added = estimate_text_tokens(&outcome)
+ .saturating_sub(estimate_text_tokens(CLEARED_PLACEHOLDER));
+ if budget > 0 && used.saturating_add(added) > budget {
+ // Everything older is at least as likely to overflow, but
+ // keep counting so the log reports the true shortfall
+ // rather than stopping at the first one that did not fit.
+ skipped += 1;
+ continue;
+ }
+ used = used.saturating_add(added);
tool.content = vec![ContentBlock::Text(outcome)];
restored += 1;
}
+ if skipped > 0 {
+ tracing::info!(
+ skipped,
+ restored,
+ budget,
+ used,
+ "[tinyagents::mw] left some cleared tool results cleared: restoring them \
+ would have pushed the concluding call past its input budget, and an \
+ eviction there costs whole messages rather than one body"
+ );
+ }
restored
}
Err(_) => {
@@ -257,7 +312,18 @@ const ARTIFACT_INDEX_NAMESPACE: &str = "tool_results";
/// says where the data went is the one thing the ladder may not take. It is
/// appended at the tail rather than the head so the cacheable prompt prefix is
/// untouched.
-pub(crate) struct ArtifactIndexTocMiddleware;
+pub(crate) struct ArtifactIndexTocMiddleware {
+ /// The input-token allowance the trim enforces, so the contents list can be
+ /// capped against it. `0` disables the cap (no advertised window, and no
+ /// trim installed either).
+ input_budget: u64,
+}
+
+impl ArtifactIndexTocMiddleware {
+ pub(crate) fn new(input_budget: u64) -> Self {
+ Self { input_budget }
+ }
+}
#[async_trait]
impl Middleware<()> for ArtifactIndexTocMiddleware {
@@ -313,7 +379,38 @@ impl Middleware<()> for ArtifactIndexTocMiddleware {
// ordering would rewrite this message on every call for no reason,
// costing cache and making the diff unreadable in a trace.
rows.sort();
- let count = rows.len();
+ let total = rows.len();
+ // Cap the list against the input allowance (CodeRabbit on #6068).
+ //
+ // This message is a system message precisely so the ladder cannot take
+ // it — compression keeps system messages verbatim and the trim never
+ // evicts one — which means nothing downstream can shrink it either. A
+ // turn that persisted enough oversized results would otherwise grow an
+ // un-evictable message without limit, and the guarantee that made the
+ // pointers safe would be the thing that broke the request.
+ //
+ // A tenth of the input allowance: generous for the realistic case (a
+ // handful of artifacts is a few hundred bytes) and firm about the
+ // pathological one. The omitted count is reported rather than the list
+ // silently ending, so the model knows more exist — the same disclosure
+ // rule the rest of this ladder follows, and the reason the artifacts are
+ // findable at all.
+ if self.input_budget > 0 {
+ let cap = (self.input_budget / 10).max(1);
+ let mut used: u64 = 0;
+ let mut kept = 0usize;
+ for row in &rows {
+ used = used.saturating_add(estimate_text_tokens(row));
+ if used > cap {
+ break;
+ }
+ kept += 1;
+ }
+ rows.truncate(kept.max(1));
+ }
+ let shown = rows.len();
+ let omitted = total - shown;
+ let count = total;
tracing::debug!(
artifacts = count,
"[tinyagents::mw] rendering the persisted-artifact contents list"
@@ -323,8 +420,16 @@ impl Middleware<()> for ArtifactIndexTocMiddleware {
{count} tool result(s) were too large to keep inline and were written to disk. The \
text you saw for them is a preview; the full content is at the path below and can be \
read with the file-reading tool when you need detail the preview does not carry.\n\n\
- {}",
- rows.join("\n")
+ {}{}",
+ rows.join("\n"),
+ if omitted > 0 {
+ format!(
+ "\n\n_({omitted} more stored result(s) not listed here — ask for the one you \
+ need by tool name and it can be located.)_"
+ )
+ } else {
+ String::new()
+ }
)));
Ok(())
}
diff --git a/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs b/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs
index 515b9c2b99..7f8af33803 100644
--- a/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs
+++ b/src/openhuman/agent/tinyagents/middleware_tests_part_03_tests.rs
@@ -149,7 +149,7 @@ fn sink_with(entries: &[(&str, &str)]) -> crate::openhuman::agent::tinyagents::T
/// A run with calls left is untouched: no instruction, and the tool belt intact.
#[tokio::test]
async fn wrap_up_leaves_a_call_with_budget_remaining_alone() {
- let mw = FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&[]));
+ let mw = FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&[]), 0);
let mut ctx = RunContext::new(RunConfig::new("mw-test").with_max_model_calls(5), ());
ctx.limits.record_model_call().unwrap();
let mut request = ModelRequest {
@@ -172,7 +172,7 @@ async fn wrap_up_leaves_a_call_with_budget_remaining_alone() {
/// asking — and the wrap-up instruction is appended as the final turn.
#[tokio::test]
async fn wrap_up_withdraws_tools_and_appends_the_instruction_on_the_last_call() {
- let mw = FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&[]));
+ let mw = FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&[]), 0);
let mut ctx = RunContext::new(RunConfig::new("mw-test").with_max_model_calls(2), ());
ctx.limits.record_model_call().unwrap();
ctx.limits.record_model_call().unwrap(); // now the final call
@@ -212,6 +212,9 @@ async fn wrap_up_restores_tool_results_microcompact_cleared() {
("call-old", "issue #41: auth bypass"),
("call-new", "issue #42: leak"),
]),
+ // Unbounded: this case is about restoring what was cleared, not about
+ // the budget that stops it (covered by its own test below).
+ 0,
);
let mut ctx = RunContext::new(RunConfig::new("mw-test").with_max_model_calls(2), ());
ctx.limits.record_model_call().unwrap();
@@ -243,7 +246,8 @@ async fn wrap_up_restores_tool_results_microcompact_cleared() {
/// the sink holds a different (e.g. later-truncated) copy for that id.
#[tokio::test]
async fn wrap_up_does_not_rewrite_a_result_that_was_never_cleared() {
- let mw = FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&[("call-1", "FROM SINK")]));
+ let mw =
+ FinalCallWrapUpMiddleware::new("CONCLUDE NOW", sink_with(&[("call-1", "FROM SINK")]), 0);
let mut ctx = RunContext::new(RunConfig::new("mw-test").with_max_model_calls(2), ());
ctx.limits.record_model_call().unwrap();
ctx.limits.record_model_call().unwrap();
@@ -299,7 +303,7 @@ async fn ctx_with_artifacts(entries: &[(&str, &str, &str, u64)]) -> RunContext<(
/// saying that there is nothing to point at.
#[tokio::test]
async fn toc_is_absent_when_no_result_was_offloaded() {
- let mw = ArtifactIndexTocMiddleware;
+ let mw = ArtifactIndexTocMiddleware::new(0);
let mut ctx = ctx_with_artifacts(&[]).await;
let mut request = ModelRequest {
messages: vec![TaMessage::user("hi")],
@@ -316,7 +320,7 @@ async fn toc_is_absent_when_no_result_was_offloaded() {
/// what the reduction steps act on.
#[tokio::test]
async fn toc_lists_every_persisted_artifact_as_a_system_message() {
- let mw = ArtifactIndexTocMiddleware;
+ let mw = ArtifactIndexTocMiddleware::new(0);
let mut ctx = ctx_with_artifacts(&[
("call-1", "fetch_issues", "outputs/issues-p1.json", 240_000),
("call-2", "web_search", "outputs/search-2.json", 91_000),
@@ -355,7 +359,7 @@ async fn toc_lists_every_persisted_artifact_as_a_system_message() {
/// Rendered fresh per request, so repeated passes cannot stack stale lists.
#[tokio::test]
async fn toc_does_not_accumulate_across_calls() {
- let mw = ArtifactIndexTocMiddleware;
+ let mw = ArtifactIndexTocMiddleware::new(0);
let mut ctx = ctx_with_artifacts(&[("call-1", "fetch", "outputs/a.json", 100)]).await;
let mut first = ModelRequest {
@@ -379,3 +383,100 @@ async fn toc_does_not_accumulate_across_calls() {
"exactly one contents list per request"
);
}
+
+// ── the bounds CodeRabbit asked for on #6068 ────────────────────────────────
+
+/// Restoration stops at the input allowance instead of overflowing it.
+///
+/// It runs after compression and before the trim, so an unbounded restore
+/// pushes the request over and the trim evicts whole messages — strictly more
+/// destructive than the blanking being undone, and able to discard the very
+/// results just restored. Preventing the overflow beats repairing it.
+#[tokio::test]
+async fn wrap_up_stops_restoring_at_the_input_budget() {
+ let big = "x".repeat(4_000);
+ let mw = FinalCallWrapUpMiddleware::new(
+ "CONCLUDE NOW",
+ sink_with(&[("call-1", &big), ("call-2", &big), ("call-3", &big)]),
+ // Room for roughly one of them, not three.
+ 1_200,
+ );
+ let mut ctx = RunContext::new(RunConfig::new("mw-test").with_max_model_calls(2), ());
+ ctx.limits.record_model_call().unwrap();
+ ctx.limits.record_model_call().unwrap();
+ let mut request = ModelRequest {
+ messages: vec![
+ TaMessage::tool("call-1", CLEARED_PLACEHOLDER),
+ TaMessage::tool("call-2", CLEARED_PLACEHOLDER),
+ TaMessage::tool("call-3", CLEARED_PLACEHOLDER),
+ ],
+ ..Default::default()
+ };
+
+ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
+
+ let restored = request
+ .messages
+ .iter()
+ .filter(|m| m.text().starts_with("xxx"))
+ .count();
+ assert!(
+ restored >= 1 && restored < 3,
+ "some restored, not all — budget 1200 cannot hold three 4k bodies, got {restored}"
+ );
+ // Newest-first: the last tool result is the one the model never saw (the
+ // cap is checked before the request is built). Not `messages.last()` —
+ // that is the wrap-up instruction this middleware just appended.
+ let newest_tool = request
+ .messages
+ .iter()
+ .rev()
+ .find(|m| matches!(m, TaMessage::Tool(_)))
+ .map(|m| m.text())
+ .unwrap_or_default();
+ assert!(
+ newest_tool.starts_with("xxx"),
+ "the newest cleared result is restored first, got: {}",
+ &newest_tool[..newest_tool.len().min(60)]
+ );
+}
+
+/// The contents list is capped, and says how many it left out.
+///
+/// It is a system message so the ladder cannot take it — which also means
+/// nothing downstream can shrink it, so it has to bound itself.
+#[tokio::test]
+async fn toc_is_capped_and_reports_what_it_omitted() {
+ let entries: Vec<(String, String, String, u64)> = (0..200)
+ .map(|i| {
+ (
+ format!("call-{i}"),
+ format!("tool_with_a_long_name_{i}"),
+ format!("outputs/a-fairly-long-artifact-path-{i}.json"),
+ 1_000,
+ )
+ })
+ .collect();
+ let borrowed: Vec<(&str, &str, &str, u64)> = entries
+ .iter()
+ .map(|(a, b, c, d)| (a.as_str(), b.as_str(), c.as_str(), *d))
+ .collect();
+ let mut ctx = ctx_with_artifacts(&borrowed).await;
+ let mw = ArtifactIndexTocMiddleware::new(2_000);
+ let mut request = ModelRequest {
+ messages: vec![TaMessage::user("what did you find?")],
+ ..Default::default()
+ };
+
+ mw.before_model(&mut ctx, &(), &mut request).await.unwrap();
+
+ let text = request.messages.last().expect("a contents list").text();
+ assert!(
+ text.contains("not listed here"),
+ "an omitted count must be disclosed, not silently dropped: {text}"
+ );
+ assert!(
+ estimate_text_tokens(&text) < 2_000,
+ "the list must stay inside the allowance it was given"
+ );
+}
diff --git a/src/openhuman/agent/tinyagents/mod_part_04.rs b/src/openhuman/agent/tinyagents/mod_part_04.rs
index 061e00defa..2038837c75 100644
--- a/src/openhuman/agent/tinyagents/mod_part_04.rs
+++ b/src/openhuman/agent/tinyagents/mod_part_04.rs
@@ -619,6 +619,15 @@ fn assemble_turn_harness(
Arc::new(middleware::FinalCallWrapUpMiddleware::new(
crate::openhuman::agent::harness::session::turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,
tool_outcome_sink.clone(),
+ // The same allowance the trim below enforces, so restoration stops
+ // short of provoking an eviction instead of relying on one to clean
+ // up after it. `0` when the model advertises no window, which
+ // disables the bound — there is no budget to measure against, and
+ // no trim installed either.
+ context_window
+ .filter(|w| *w > 0)
+ .map(|w| middleware::legacy_max_input_tokens(w).max(1))
+ .unwrap_or(0),
))
});
let wrap_up_fired = wrap_up_mw.as_ref().map(|mw| mw.fired());
@@ -631,7 +640,18 @@ fn assemble_turn_harness(
// renders whatever survived them, and before the trim so its message is
// counted in that budget — the trim never drops a system message, so being
// counted costs nothing and being uncounted could push the request over.
- harness.push_middleware(Arc::new(middleware::ArtifactIndexTocMiddleware));
+ harness.push_middleware(Arc::new(middleware::ArtifactIndexTocMiddleware::new(
+ // CodeRabbit on #6068: the contents list is a system message, and
+ // `ImageAwareMessageTrimMiddleware` never evicts one — the property that
+ // makes it survive the ladder also makes it the one message nothing can
+ // shrink. A turn that persists enough artifacts could therefore grow an
+ // unbounded, un-evictable message. It is bounded here instead, against
+ // the same allowance the trim enforces.
+ context_window
+ .filter(|w| *w > 0)
+ .map(|w| middleware::legacy_max_input_tokens(w).max(1))
+ .unwrap_or(0),
+ )));
if let Some(window) = context_window.filter(|w| *w > 0) {
// Deterministic hard-cap trim (issue #4462), last in the ladder: it drops