Skip to content

fix(agents): scale aggregate tool-result budget by context window - #246

Merged
insomnius merged 4 commits into
boonfrom
fix-aggregate-tool-result-budget
Sep 30, 2026
Merged

insomnius merged 4 commits into
boonfrom
fix-aggregate-tool-result-budget

Conversation

@insomnius

@insomnius insomnius commented Sep 24, 2026 •

Copy link
Copy Markdown

Problem

The aggregate tool-result budget is perResultCap * 4, computed with no reference to the context window. On a 500k-token window that is 256,000 chars, about 13% of the window.

Once summed tool-result text crosses it, older results are flattened to a bare notice with zero content bytes, and the model is shown its own successful tool calls as:

[... 39610 more characters truncated; rerun with narrower args if needed]

An agent cannot distinguish that from a tool failure. In a long-lived session this reproduces as the agent reporting that its tooling is broken while every tool call in the transcript actually succeeded.

Worse, the truncated array is also what the compaction trigger measures. attempt.ts assigns it to promptHistoryMessages, which flows into both estimateLlmBoundaryTokenPressure and shouldPreemptivelyCompactBeforePrompt. So the measured prompt size stays pinned while real session content grows, and compaction never fires on tool-result pressure at all. Measured: the trigger's estimate held at roughly 157,850 tokens across a 3.4x growth in real content, against a bar of 483,616.

Fix

Backport of upstream d45b8be939a and 168a4890bb4 (both released in v2026.7.1), which apply cleanly to this file, plus a notice-text change.

  • Aggregate budget becomes max(perResultCap * 4, window * 4 * 0.5) — 1,000,000 chars on a 500k window.
  • calculateRecoveryAggregateToolResultChars no longer falls back to maxCharsOverride. That fallback silently made the aggregate equal the per-result cap (64,000) on the two persisted precheck routes, which rewrite the transcript, so it was destructive rather than merely lossy.
  • The second truncation pass writes a marker instead of clearing text to "", and its accounting uses the post-first-pass length instead of the original, which had over-credited every cleared result and stopped the pass early.
  • Fresh trailing tool results are protected from aggregate elision.
  • Aggregate elision gets its own notice text stating the call succeeded. DEFAULT_SUFFIX keeps "rerun with narrower args" on the single-oversized-fresh-result path, where that advice is correct.

Upstream's comment on the new resolver names this exact failure: "If this drifts, truncation can hide pressure that compaction routing should see."

Why not a floor instead

Raising minKeepChars on the prompt path was considered and rejected. It activates the second pass at ~124 results, and before d45b8be939a that pass emitted empty text, which reaches the model as (no output) — strictly worse than the notice for this symptom. It also leaves the prompt over budget because of the accounting bug. The budget is the root cause; the floor is not.

Risk

  • Prompt size grows on tool-heavy sessions, up to ~1M chars of tool history per turn instead of 256k. More input tokens, latency and cost per turn, and more prompt-cache churn.
  • Compaction will start firing on sessions that previously coasted. That is the intended outcome, but it exercises the summarizer path on large sessions, so roll to a canary first and watch for compaction timeouts.
  • Elision order changes — the trailing fresh batch is now protected, and the second pass marks rather than empties.
  • Log fingerprints change. Fewer [tool-result-truncation] Truncated N tool result(s) for prompt history lines, and a new warning when aggregate pressure is detected. Anything keyed on the old line needs updating.
  • Windows under 128k are unchanged. 128k gives 256k chars, 200k gives 400k.

Testing

  • tool-result-truncation.test.ts and run/preemptive-compaction.test.ts: 132/132 pass. Upstream's test updates applied via three-way merge, no conflicts.
  • Full tree typechecks with zero errors.
  • The wider embedded-agent-runner suite is order-flaky independent of this change: baseline showed 38 failures, this branch 37, and the failing file sets are disjoint between consecutive runs of the same tree. Every file implicated in any single run passes in isolation on this branch.

Local runtime A/B (2026-09-30)

Same scripted session on a baseline build (merge-base cc005593361) and this branch, through the real embedded runtime: openclaw agent --local, real exec tool, real prompt assembly, truncation and precheck. The model was a scripted anthropic-messages mock on a 500k window (contextTokenBudget=500000 in the precheck logs); the local LLM gateway could not authenticate without boon-core running. Six cat calls of 60,000 chars each (360k total), then a new turn asking for the first line of the FIRST result.

Baseline This PR
First result as sent to the model 69 chars: [... 60000 more characters truncated; rerun with narrower args if nee 60,000 chars, first line RESULT_1_MARKER ZEBRA-4417-KESTREL
Freshest results during the turn result 5 cut to 15,937 chars; result 6 sent as (no output) whole
Next-turn log Truncated 2 tool result(s) for prompt history (maxChars=64000 aggregateBudgetChars=256000) no truncation line
Pre-prompt pressure estimate, 360k→720k chars of real tool text pinned at 165,716 → 166,887 tokens 228,813 → 445,937 of 480,000 (compaction about to fire)

Cost: the request body grew from 359KB to 467KB at six results. The new "call succeeded" notice and the fresh-trailing protection were not reached live: on a 500k window the mid-turn overflow guard fires first, so they rest on unit tests.

Review follow-up

  • The warn-once session-key set is bounded (evicts the oldest past 1000), with a red-first test.
  • The mixed-tail routing test now asserts the per-result savings the route actually uses, since the aggregate budget cannot bind at the routing window.
  • boon merged in; focused suites 67/67, both tsgo lanes, oxlint and oxfmt clean.

Local end-to-end test, real stack (2026-09-30)

This change ran through the full local Boon stack before merge.

  • OpenClaw gateway on :18789, built from this branch at 1becdc4a1e5.
  • anychat-boon-web plugin, loaded from its built dist/.
  • boon-core on :3000, with Sidekiq.
  • boon-llm-gateway on :8080, calling the real claude-opus-4-8-anthropic model (500k context window).

The agent was driven from the Boon Web chat UI in a browser.

Scenario: in one turn, the agent ran cat on six files one at a time. Each file held 60,000 characters with a random marker on its first line, for 360k characters of tool output in total. That is above boon's old 256k aggregate budget and below the new 1M budget for a 500k window. After the sixth call, the agent had to repeat each file's first line from the tool output it had received, without re-reading.

Check Observed Verdict
All six first lines returned exactly (FILE1_MARKER 16D91E7F-OMEGA … FILE6_MARKER 792E055A-OMEGA) 6/6 match the generated markers pass
Agent reports any output missing, elided or truncated "none were missing, elided, or truncated" pass
Tool calls UI: "Verification · 7 tools succeeded" pass
Gateway log truncation/elision lines (Truncated N tool result(s), aggregate notice) 0 pass
Turn outcome outcome=completed, 64s pass

On boon, the local A/B above shows the same shape of session cutting the first result down to a 69-character "rerun" notice.

Boon Web chat: the agent returns all six markers intact

https://claude.ai/code/session_01DE9xpUY96ZgRsL9khtAVYS


Summary by cubic

Fixes aggregate tool-result truncation so successful tool calls are no longer elided into empty notices that read as failures, and no longer hidden from compaction routing.

The aggregate budget was a fixed perResultCap * 4 (256k chars on a 500k-token window); crossing it flattened older results to zero-content notices the model interpreted as tool failures. That truncated array also fed the compaction trigger's pressure estimate, so real session growth never fired compaction. The budget now scales with the context window (max(perResultCap * 4, window * 4 * 0.5), 1M chars on 500k), aggregate elision writes a notice stating the call succeeded, fresh trailing results are protected, persisted precheck routes no longer fall back to the per-result cap, and the aggregate-recovery warning is warn-once per session against a bounded set that evicts the oldest past 1,000 sessions.

Rollout notes

  • Prompt size on tool-heavy sessions grows up to ~1M chars per turn instead of 256k, raising latency, cost, and prompt-cache churn.
  • Compaction now fires on sessions that previously coasted; canary first and watch for summarizer timeouts.
  • Windows under 128k are unchanged.

Written for commit 1becdc4. Summary will update on new commits.

Review in cubic

Backport of upstream d45b8be and 168a489, plus a notice-text fix.

The aggregate tool-result budget was perResultCap * 4 with no reference to
the context window: 256,000 chars on a 500k window, roughly 13% of it. Once
the summed tool-result text crossed that, older results were flattened to a
bare notice carrying zero content bytes, and the model was shown its own
successful tool calls as:

  [... 39610 more characters truncated; rerun with narrower args if needed]

which it cannot distinguish from a tool failure.

The same truncated array is what the compaction trigger measures
(attempt.ts assigns it to promptHistoryMessages, which reaches both
estimateLlmBoundaryTokenPressure and shouldPreemptivelyCompactBeforePrompt),
so the measured prompt size stayed pinned while real session content grew and
compaction never fired on tool-result pressure at all.

Changes:

- Aggregate budget is now max(perResultCap * 4, window * 4 * 0.5), so a 500k
  window allows 1,000,000 chars instead of 256,000.
- calculateRecoveryAggregateToolResultChars no longer falls back to
  maxCharsOverride, which had silently made the aggregate equal the
  per-result cap (64,000) on the two persisted precheck routes. Those routes
  rewrite the transcript, so that fallback was destructive.
- The second truncation pass writes a marker instead of clearing text to the
  empty string, and its accounting now uses the post-first-pass length rather
  than the original, which had over-credited each cleared result.
- Fresh trailing tool results are protected from aggregate elision.
- attempt.ts resolves the aggregate budget via
  resolveLiveToolResultAggregateMaxChars at both prompt-assembly sites; the
  local PROMPT_TOOL_RESULT_AGGREGATE_CAP_MULTIPLIER is removed.
- Aggregate elision gets its own notice text stating the call succeeded.
  DEFAULT_SUFFIX keeps "rerun with narrower args" for the single oversized
  fresh result, where that advice is correct.

Tests: tool-result-truncation and preemptive-compaction suites pass 132/132.
Upstream test updates applied via three-way merge.

Claude-Session: https://claude.ai/code/session_01DE9xpUY96ZgRsL9khtAVYS
@insomnius
insomnius requested a review from a team September 24, 2026 13:53

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 4 files

Heads up: you’re close to your included review allowance. Set a flex budget so reviews don’t pause.

Reply with feedback, questions, or to request a fix.

Fix all with cubic | Re-trigger cubic

…iew notes

Address review on #246:
- The warn-once set of session keys now evicts the oldest entry past 1000
  sessions, so a long-lived gateway no longer retains every key; covered by a
  red-first test through truncateOversizedToolResultsInSessionManager.
- The aggregate-suffix comment is cut to the invariant it protects.
- The mixed oversized-plus-medium routing test no longer asserts aggregate
  savings at a synthetic 20k window the route never uses; at the routing window
  the aggregate budget cannot bind, so the test now pins the per-result savings
  the route actually relies on (the 20k estimator claims stay covered in
  tool-result-truncation.test.ts).

Claude-Session: https://claude.ai/code/session_01FSeHegCidN6qEU1sTf2KzG

@boon-hermes-bot boon-hermes-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: APPROVE

Verified at head 847f769e92576c8aa808f9f1b833d02dcadb4008 (base boon).

Backport authenticity. Upstream commits d45b8be939a1 ("preserve fresh tool result text under aggregate cap") and 168a4890bb4b ("scale aggregate tool-result budget by context") both exist in openclaw/openclaw and are ancestors of the v2026.7.1 tag commit (compare: ahead=0) — released as claimed. The upstream patches carry the same mechanisms this PR lands: trailing-result protection (protectTrailingToolResults: Boolean(projectionState)), marker-instead-of-empty with post-first-pass accounting (clearToolResultText(baseMessage, targetTextChars)), the max(perResultMaxChars * 4, window * 4 * 0.5) formula, and the "if this drifts, truncation can hide pressure that compaction routing should see" comment. The fork's notice-text change is disclosed in the body and is stricter about the failure mode ("call succeeded … not an error") than upstream's marker.

Diff vs claims.

  • resolveLiveToolResultAggregateMaxChars implements the window-scaled budget and is wired into both attempt.ts call sites; the old PROMPT_TOOL_RESULT_AGGREGATE_CAP_MULTIPLIER usage is gone from attempt.ts.
  • calculateRecoveryAggregateToolResultChars no longer falls back to maxCharsOverride, so the persisted precheck routes get the real aggregate budget instead of the 64k per-result cap.
  • Second aggregate pass writes AGGREGATE_ELISION_MARKER instead of clearing to "", and accounts from the post-first-pass length — the over-credit fix checks out.
  • Warn-once aggregate-recovery warning is bounded (AGGREGATE_RECOVERY_WARNING_MAX_SESSIONS = 1000, oldest evicted; Set iterates in insertion order) with a red-first test driving it through truncateOversizedToolResultsInSessionManager.

Cubic threads (3/3). All resolved with replies citing 847f769e925 (= current head). Re-adjudicated each against head code: the resolved-but-not-outdated unbounded-Set finding is genuinely fixed at head (bounded with eviction + test); the misleading-test-assertions finding is fixed (renamed test asserting toolResultReducibleChars === 45_000 - 16_000 and overflowTokens === 2_000 exactly); the over-long-comment nit is fixed (trimmed to two lines).

CI. At head, every job is green except security-fast, whose failure log is the brace-expansion advisory GHSA-qhr7-859c-m2p7 — unrelated to this diff and addressed by #257. checks-node-agentic-agents-embedded (which owns the touched suites) is green at head.

Caveats. Suites not run locally (no installed deps in the shared clone); the local runtime A/B numbers (69 chars → 60k intact) are the author's measurement — the mechanism is consistent with the code but I did not reproduce the live session. Agree with the rollout note: canary first and watch compaction/summarizer behavior, since compaction will now fire on sessions that previously coasted.

@insomnius
insomnius merged commit 221aa11 into boon Sep 30, 2026
146 of 147 checks passed
@insomnius
insomnius deleted the fix-aggregate-tool-result-budget branch September 30, 2026 14:20
convyusboy added a commit that referenced this pull request Oct 2, 2026
…263)

Root version, 135 plugin manifests synced via scripts/sync-plugin-versions.ts
(pnpm plugins:sync), root + 68 extension npm-shrinkwrap.json version fields
and openclaw peerDependency ranges bumped, CHANGELOG section for boon.49.

Shipping: #246 (tool-result aggregate budget scales with context window
instead of a fixed 256k-char cap, so long tool-heavy sessions stop reading
their own successful calls as failures and compaction actually fires on real
pressure), #253/ENG-20866 (Chrome MCP handshake/navigate timeouts raised for
real npx cold-start cost, unblocking browser-handoff live attach), #256/
ENG-20876 (session_id promoted to a real Sentry tag for the per-session
reliability dashboard), #260/ENG-20968 (msteams SharePoint/OneDrive download
failures surfaced through MediaFailures instead of silently dropped), #261/
ENG-21009 (Sentry node 8.49 -> 10.75.3, clearing ~12 medium Vanta/Inspector
findings from its pinned otel/Prisma instrumentation chain), plus undici/
brace-expansion/axios security bumps and markdown-it/dompurify/golang.org/x/net
dependency bumps.

Base = 2026.6.11-boon.48. Gateway plus @openclaw/slack, @openclaw/msteams and
@openclaw/diagnostics-prometheus bumped in lockstep; only @openclaw/msteams
source changed in this train (#260), so a fleet-msteams.sh pass is needed on
Teams hosts alongside the gateway roll.

Co-authored-by: Claude Sonnet 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants