Skip to content

fix(agents): cap tool results at LLM boundary - #92613

Closed
TurboTheTurtle wants to merge 2 commits into
openclaw:mainfrom
TurboTheTurtle:codex/92315-tool-result-history
Closed

TurboTheTurtle wants to merge 2 commits into
openclaw:mainfrom
TurboTheTurtle:codex/92315-tool-result-history

Conversation

@TurboTheTurtle

@TurboTheTurtle TurboTheTurtle commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Cap provider-boundary replay to the latest 24 toolResult messages so histories with 25+ completed tool results do not cross the model boundary intact.
  • Drop the matching oldest assistant tool-call blocks when old tool results are omitted, avoiding dangling tool-call/result pairs in the provider-facing replay.
  • Add a direct regression with 30 completed tool-call/result pairs proving the boundary keeps only the newest 24 and leaves the persisted input untouched.

Closes #92315.

Duplicate PR check

  • gh pr list --repo openclaw/openclaw --state open --search "92315" --json number,title,url,headRefName,author returned no open PRs.
  • Closest open overlap found: Handle Codex toolResult blocks in tool-result truncation #87912, but that PR changes text-size truncation of Codex-shaped tool-result blocks in tool-result-truncation.*; this PR is a count-based LLM-boundary replay guard in attempt.llm-boundary.*.

Real behavior proof

  • Behavior or issue addressed: Histories with 25+ completed tool results should not send all historical toolResult messages through the LLM boundary, because that can produce an invalid provider request schema. The boundary should keep the newest tool-result context and avoid dangling assistant tool calls.
  • Real environment tested: Local OpenClaw source checkout at a local OpenClaw checkout, branch codex/92315-tool-result-history, running the actual normalizeMessagesForLlmBoundary implementation with node --import tsx.
  • Exact steps or command run after this patch: Ran a local node --import tsx probe that imported src/agents/embedded-agent-runner/run/attempt.llm-boundary.ts, built 30 completed assistant tool-call / toolResult pairs with public synthetic output, passed them through normalizeMessagesForLlmBoundary, and printed sanitized boundary metrics.
  • Evidence after fix: Copied terminal output from that OpenClaw source-level boundary probe:
{
  "status": "ok",
  "setup": "OpenClaw source LLM boundary normalizer",
  "inputToolResults": 30,
  "outputToolResults": 24,
  "firstOutputToolResult": "call_6",
  "lastOutputToolResult": "call_29",
  "assistantToolCalls": 24,
  "noDanglingAssistantToolCalls": true,
  "oldestToolResultDropped": true,
  "newestToolResultKept": true
}
  • Observed result after fix: The real OpenClaw boundary normalizer accepted a 30-tool-result replay and returned a provider-facing history with 24 tool results, keeping the newest result (call_29), dropping the oldest result (call_0), and preserving tool-call/result pairing for all assistant tool calls that remained.
  • What was not tested: I did not run a live provider API call or a Telegram/message-delivery flow. This issue is scoped to source/provider-boundary serialization, so the direct boundary probe plus regression tests cover the changed behavior without requiring transport proof.

Proof

pnpm exec oxfmt --check --threads=1 src/agents/embedded-agent-runner/run/attempt.llm-boundary.ts src/agents/embedded-agent-runner/run/attempt.llm-boundary.test.ts
git diff --check
pnpm tsgo:test:src
node scripts/run-vitest.mjs run --config test/vitest/vitest.unit-fast.config.ts src/agents/embedded-agent-runner/run/attempt.llm-boundary.test.ts src/agents/embedded-agent-runner/run/attempt.llm-boundary.cache-stability.test.ts
node scripts/test-projects.mjs src/agents/embedded-agent-runner/run/attempt.llm-boundary.test.ts src/agents/embedded-agent-runner/run/attempt.llm-boundary.cache-stability.test.ts

Risk

  • Scope is limited to provider-boundary serialization; persisted session history is not rewritten.
  • Main risk is old tool output context being omitted earlier than before when a replay has more than 24 tool results. The guard keeps the newest tool results, matching the current prompt's most relevant execution context.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels Jun 13, 2026
@clawsweeper

clawsweeper Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 15, 2026, 2:37 PM ET / 18:37 UTC.

Summary
The PR adds LLM-boundary pruning for excess historical toolResult messages, preserves the newest assistant tool-call batch, prunes matching assistant tool-call blocks, and adds focused regression tests.

PR surface: Source +179, Tests +100. Total +279 across 2 files.

Reproducibility: yes. at source level: current main has no toolResult count cap in the LLM-boundary normalizer, and PR head adds tests that exercise the 30-pair replay behavior. I did not reproduce the original live provider rejection.

Review metrics: 1 noteworthy metric.

  • Provider-boundary retention policy: 1 added: latest-24 tool-result cap with latest-batch exemption. This changes how much historical tool output the model can see during long-session replay, so maintainers should notice the policy before merge.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🐚 platinum hermit
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Get maintainer re-review on the latest head after the active-batch preservation commit.
  • [P2] Add or run a focused provider-payload conversion check for a pruned long history.

Risk before merge

  • [P1] The PR intentionally changes model-visible session replay by omitting older toolResult messages at the provider boundary; maintainers still need to accept the 24-result policy and latest-batch exception.
  • [P1] The supplied real proof exercises the actual normalizer, but it does not show the final Anthropic/OpenAI converted provider payload or a live provider accepting the originally failing shape.
  • [P1] GitHub still reports CHANGES_REQUESTED from the member review on the first commit, even though the latest commit appears to address that active-batch blocker.

Maintainer options:

  1. Validate The Final Provider Payload (recommended)
    Run or add a focused check that feeds a 30-plus pair replay through the relevant Anthropic/OpenAI conversion path and confirms the remaining tool calls and tool results stay paired.
  2. Accept The Replay Policy
    Maintainers can intentionally accept pruning older tool-result context while preserving every result from the latest assistant tool-call batch.
  3. Pause For Provider-Specific Rules
    If the 24-result limit must be provider-specific or hard even for the latest batch, pause this PR and replace it with provider-aware pruning or a clear fail-fast error.

Next step before merge

  • [P2] The remaining action is maintainer re-review and acceptance of the session-state retention policy, not a narrow automated repair.

Security
Cleared: The diff only changes agent boundary normalization and focused tests; it does not touch dependencies, workflows, secrets, package metadata, or external code execution surfaces.

Review details

Best possible solution:

Land the boundary guard after maintainer re-review accepts the latest-batch retention policy, ideally with one focused provider-payload conversion check for a pruned long history.

Do we have a high-confidence way to reproduce the issue?

Yes at source level: current main has no toolResult count cap in the LLM-boundary normalizer, and PR head adds tests that exercise the 30-pair replay behavior. I did not reproduce the original live provider rejection.

Is this the best way to solve the issue?

Yes as a boundary-layer mitigation if maintainers accept the policy: it runs immediately before provider conversion and leaves persisted history untouched. The safer alternative is a provider-payload check or provider-specific cap if a hard limit is required.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against c40db057da33.

Label changes

Label justifications:

  • P1: The linked bug reports long-session provider request failures that can block active agent workflows and require manual recovery.
  • merge-risk: 🚨 session-state: The PR intentionally drops older tool-result context from provider replay while preserving persisted history, changing model-visible session state.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body supplies terminal proof from a real source checkout invoking the actual normalizer with 30 synthetic tool-result pairs and observing paired pruned output.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies terminal proof from a real source checkout invoking the actual normalizer with 30 synthetic tool-result pairs and observing paired pruned output.
Evidence reviewed

PR surface:

Source +179, Tests +100. Total +279 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 180 1 +179
Tests 1 100 0 +100
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 280 1 +279

What I checked:

Likely related people:

  • Marvinthebored: Authored the recent prompt-cache/user-turn serialization change that touched the current LLM boundary normalizer. (role: recent area contributor; confidence: medium; commits: 1af55bc6654f; files: src/agents/embedded-agent-runner/run/attempt.llm-boundary.ts)
  • jalehman: Reviewed and merged the recent LLM-boundary serialization work that current main builds on. (role: reviewer and merger; confidence: medium; commits: 1af55bc6654f; files: src/agents/embedded-agent-runner/run/attempt.llm-boundary.ts)
  • steipete: Authored major agent-runtime internalization and recent provider-schema hardening in the same provider-boundary area. (role: adjacent owner; confidence: high; commits: bb46b79d3c14, 439a9e97fd61; files: src/agents/tool-call-id.ts, src/llm/providers/openai-responses-shared.ts, src/llm/providers/anthropic.ts)
  • vincentkoc: Reviewed this PR's first commit and identified the active-batch pairing blocker; also has recent Anthropic/provider-boundary work in this area. (role: reviewer and adjacent provider contributor; confidence: medium; commits: 7cb3b21d90a6, 7acedeaf11df; files: src/agents/embedded-agent-runner/run/attempt.llm-boundary.ts, src/llm/providers/anthropic.ts)
  • Pluviobyte: Recently changed tool-call ID pairing behavior in the helper family this PR relies on for matching assistant calls to results. (role: recent adjacent contributor; confidence: medium; commits: 4a6666796f46; files: src/agents/tool-call-id.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jun 13, 2026
@TurboTheTurtle
TurboTheTurtle marked this pull request as ready for review June 13, 2026 06:49

@vincentkoc vincentkoc left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the focused fix. I found one blocker that makes this unsafe to land as-is.

Blocking finding:

  • The new cap keeps the last 24 toolResult messages globally. If the most recent assistant turn emits 25 parallel tool calls, the boundary drops the first current-batch result and the matching assistant tool call before the continuation LLM call. That means the model proceeds without seeing output for a tool it just requested.

Why this matters:

  • The boundary should trim old replay context, not silently remove current tool outputs from the active/recent assistant tool-call batch.
  • A safe shape likely needs to preserve all results for the latest assistant tool-call batch, then prune older completed batches or hand off to compaction/summarization.

Verification I ran before stopping:

  • node_modules/.bin/oxfmt --check src/agents/embedded-agent-runner/run/attempt.llm-boundary.ts src/agents/embedded-agent-runner/run/attempt.llm-boundary.test.ts
  • node scripts/run-vitest.mjs src/agents/embedded-agent-runner/run/attempt.llm-boundary.test.ts src/agents/embedded-agent-runner/run/attempt.llm-boundary.cache-stability.test.ts
  • Maintainer autoreview found the active-batch regression after several smaller replay-shape edge cases.

@vincentkoc

Copy link
Copy Markdown
Member

Closing this rather than landing it. The 24-result policy is not supported by the reported evidence or a provider contract, and the branch can introduce the same class of malformed replay it is meant to prevent.

What I verified:

  • Truncated 25 tool result(s) counts result messages whose text was shortened. The current aggregate truncator does not remove toolResult messages or their matching assistant calls.
  • Current replay policy defaults repairToolUseResultPairing on and repairs again after history limiting, context-engine assembly, ID normalization, and strict-provider replay sanitization.
  • A current-main payload probe kept all 29 assistant tool calls and all 29 Anthropic tool_result blocks paired after per-result and aggregate truncation.
  • A live OpenAI Responses request with 30 completed function-call/output pairs succeeded. That disproves a generic provider-boundary limit of 24.
  • No Anthropic contract or SDK source establishes a 24-result limit. The surfaced message is generic and is also used for unrelated 400s, including thinking-signature failures; #92201: Embedded runner: freshly streamed thinking signatures intermittently invalid on replay (Anthropic); recovery wrapper never fires because error text is genericized #92916 fixed one such recovery path.
  • Focused local tests passed: 157 tests across the boundary, truncation, transcript-repair, and transcript-policy suites.
  • Blacksmith Testbox tbx_01kv7bn8wan99xsca12khd2vwz passed the same focused PR-head suites: 153 tests.

Concrete blocker on this head:

  • Autoreview found that legacy/provider-shaped assistant blocks use pairing IDs such as function_call.call_id, while this patch reads only id.
  • I reproduced that on the PR head in the same Linux Testbox: with 25 paired results, the patch dropped toolResult(call_0) but retained the matching function_call(call_id=call_0). The resulting provider replay is orphaned.

The original Anthropic failure may still be real, but the count-threshold hypothesis is not proven and this patch is not the best fix. A useful follow-up needs the exact sanitized rawError.error.message and the final provider payload shape from a failing request; the generic user-facing error is not enough to choose a retention policy.

@vincentkoc vincentkoc closed this Jun 16, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 16, 2026
@TurboTheTurtle
TurboTheTurtle deleted the codex/92315-tool-result-history branch June 16, 2026 04:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Tool-result truncation bug: 25+ tool_results in history produces invalid request schema

2 participants