Skip to content

fix: CJK tool results stay within context budgets - #114755

Merged
steipete merged 4 commits into
mainfrom
codex/fix-cjk-tool-result-budget
Jul 27, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/fix-cjk-tool-result-budget

Conversation

@steipete

@steipete steipete commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Closes #103847

AI-assisted. Thanks to @yetval for the precise report and source reproduction.

What Problem This Solves

Fixes an issue where CJK-heavy tool output could consume up to roughly four times the intended context budget because live truncation, aggregate prompt budgeting, persisted recovery, and the mid-turn guard did not share language-aware accounting.

The same multi-block allocator could also exceed its total cap through independent minimums, starve later blocks, spend suffix budget on empty blocks, and underreport omissions in suffix-only truncation.

Why This Change Was Made

This introduces one canonical CJK-aware, UTF-16-safe budget-and-slice abstraction and routes every affected tool-result path through it. ASCII behavior and the context guard's existing safety floor remain intact, while the allocator now owns one bounded total budget across all text blocks.

The committed QA scenario exercises a real Gateway agent loop through qa-channel and the mock provider, then inspects the provider-bound tool result rather than relying only on helper tests. Its final marker check requires exact trimmed equality to avoid false-positive live proof.

During exact-head CI, an unrelated 3,545-line auto-reply suite timed out while sequentially importing modules and running a synthetic reply in beforeAll. The test harness now uses normal mocked imports and preloads the three real lazy runtime seams in parallel, removing the synthetic turn and its registry/session side effects instead of merely extending the timeout.

User Impact

CJK-heavy tool sessions now stay within the same context-pressure limits as ASCII-heavy sessions, reducing avoidable overflow, compaction, and lost-progress behavior. Mixed and multi-block tool results also remain within their declared aggregate cap without starving later output.

Evidence

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling extensions: qa-lab size: L maintainer Maintainer-authored PR labels Jul 27, 2026
@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. P2 Normal backlog priority with limited blast radius. labels Jul 27, 2026
@clawsweeper

clawsweeper Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 27, 2026, 6:26 PM ET / 22:26 UTC.

ClawSweeper review

What this changes

The PR makes tool-result trimming CJK-aware and UTF-16-safe across live prompt truncation and the context guard, adds unit and Gateway QA coverage, and simplifies an auto-reply test harness to preload mocked runtime seams.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

This remains a useful fix for the linked CJK context-budget bug. The refreshed branch appears to route the affected truncation and guard paths through one weighted, UTF-16-safe helper, carries focused regression coverage and a real Gateway QA claim, and has no concrete patch defect from the supplied diff; its protected maintainer label means final merge judgment should stay with maintainers after review of the exact refreshed merge result. Likely related people: steipete is the low-confidence routing candidate from the current agent-runtime commits.

Priority: P2
Reviewed head: ad262083eadd83c42c741ad81524e5d149c95786
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The PR has strong live behavior evidence and focused coverage, with the remaining work being exact-head rebase and maintainer merge review rather than a demonstrated patch defect.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body supplies after-fix Gateway QA evidence that inspects the provider-bound truncated tool result and exact final response; no sensitive data is shown in the reported proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body supplies after-fix Gateway QA evidence that inspects the provider-bound truncated tool result and exact final response; no sensitive data is shown in the reported proof.
Evidence reviewed 5 items Shared budget implementation: The branch adds a provider-independent CJK-aware estimator and UTF-16-safe prefix/tail slicers, then imports that helper into the truncation and context-guard paths rather than retaining independent raw-length accounting.
Affected runtime paths: The patch replaces the context guard’s raw character-budget comparison with weighted estimation and bounded slicing, and updates live tool-result truncation to use the same helper for suffix and retained-text budgeting.
Regression coverage: Focused tests cover dense CJK accounting, ASCII safety-floor behavior, UTF-16 boundaries, context-guard truncation, multi-block truncation behavior, and omission reporting.
Findings None None.
Security None None.

How this fits together

Embedded-agent tool results are generated by tools and then projected into the next provider request. This change measures and slices that text consistently before live truncation, aggregate recovery, and the mid-turn context guard send bounded content back to the model.

flowchart LR
  A[Tool result text] --> B[Shared weighted text budget]
  B --> C[Live truncation]
  B --> D[Aggregate recovery]
  B --> E[Context guard]
  C --> F[Provider-bound prompt]
  D --> F
  E --> F
  F --> G[Next model turn]
Loading

Decision needed

Question Recommendation
Should this protected maintainer-labeled PR be rebased and merged after the exact refreshed merge result completes its remaining required checks? Rebase and merge after exact-head validation: Refresh the branch against current main, confirm the completed required checks cover the merge result, then merge the shared-budget fix.

Why: The supplied patch and proof are strong enough to avoid inventing an automated repair, but the protected label and current-base drift reserve the final merge decision for maintainers.

Before merge

  • Resolve merge risk (P1) - The branch is behind current main, and the refreshed head includes an adjacent auto-reply harness change; merge review should use the rebased exact merge result after the remaining required checks complete.
Agent review details

Security

None.

PR surface

Source +167, Tests +182, Other +101. Total +450 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 4 268 101 +167
Tests 5 212 30 +182
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 101 0 +101
Total 10 581 131 +450

Review metrics

None.

Stored data model

Persistent data-model change detected: persistent cache schema: src/agents/embedded-agent-runner/tool-result-char-estimator.test.ts, serialized state: qa/scenarios/runtime/cjk-tool-result-budget.yaml. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #103847
Summary: This PR is the candidate implementation for the source-reproduced CJK undercount reported in the canonical issue.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep one shared weighted budget abstraction for every provider-bound tool-result path, rebase it onto current main, and land only after the exact merged head retains the focused CJK regressions and Gateway QA behavior.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep one shared weighted budget abstraction for every provider-bound tool-result path, rebase it onto current main, and land only after the exact merged head retains the focused CJK regressions and Gateway QA behavior.

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

Yes. The linked report provides a concrete dense-CJK tool-result path, and the branch adds a Gateway QA scenario that drives the same provider-bound truncation behavior; this review did not execute the scenario itself.

Is this the best way to solve the issue?

Yes. Sharing one weighted, UTF-16-safe budget helper across live truncation and the context guard is narrower and less drift-prone than applying separate CJK multipliers to each path.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This fixes bounded context handling for CJK-heavy tool output, an important but non-emergency agent-runtime reliability issue.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body supplies after-fix Gateway QA evidence that inspects the provider-bound truncated tool result and exact final response; no sensitive data is shown in the reported proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body supplies after-fix Gateway QA evidence that inspects the provider-bound truncated tool result and exact final response; no sensitive data is shown in the reported proof.

Evidence

What I checked:

Likely related people:

  • steipete: Authored the four current branch commits spanning the shared tool-result budget helper, its runtime integrations, QA scenario, and adjacent auto-reply harness adjustment; broader current-main ownership history was not available in the supplied review evidence. (role: recent area contributor; confidence: low; commits: a0dd15061b80, 7425f8e99a34, 71e6c78e6e88; files: src/agents/embedded-agent-runner/tool-result-text-budget.ts, src/agents/embedded-agent-runner/tool-result-truncation.ts, src/agents/embedded-agent-runner/tool-result-context-guard.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Rebase onto current main and confirm the completed required checks apply to the exact merge result.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-07-27T21:46:39.459Z sha 8923aa9 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-27T22:07:04.609Z sha 3f1d080 :: needs maintainer review before merge. :: none

steipete added 4 commits July 27, 2026 15:17
Use one weighted, UTF-16-safe budget across live truncation, aggregate recovery, persisted sessions, and the mid-turn context guard. Preserve ASCII behavior, bound mixed blocks, and add a real Gateway QA scenario.\n\nFixes #103847.
@steipete
steipete force-pushed the codex/fix-cjk-tool-result-budget branch from 3f1d080 to ad26208 Compare July 27, 2026 22:21
@steipete

Copy link
Copy Markdown
Contributor Author

Rank-up move reviewed: this branch was rebased onto 0d32f85155f, then exact head ad262083eadd passed all 57 jobs in CI run https://github.com/openclaw/openclaw/actions/runs/30310423556 and the repo-native prepare-run gate.

main advanced again afterward, but GitHub reports the head mergeable with no conflicts, no pending checks, and no failed checks. Per the repository-native landing policy, behind-main drift is advisory unless strict drift is enabled. I am therefore not invalidating the completed proof loop with another no-conflict rebase; the explicit maintainer landing instruction supplies the owner decision requested by the review.

@steipete
steipete merged commit 69e8d40 into main Jul 27, 2026
124 checks passed
@steipete
steipete deleted the codex/fix-cjk-tool-result-budget branch July 27, 2026 22:36
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 28, 2026
* fix(agents): make tool-result budgets CJK-aware

Use one weighted, UTF-16-safe budget across live truncation, aggregate recovery, persisted sessions, and the mid-turn context guard. Preserve ASCII behavior, bound mixed blocks, and add a real Gateway QA scenario.\n\nFixes openclaw#103847.

* fix(agents): satisfy tool-budget lint

* test(qa): require exact CJK scenario reply

* test(auto-reply): preload reply runtimes without a synthetic turn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling extensions: qa-lab maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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.

embedded-agent-runner: live tool-result truncation cap undercounts CJK content by up to 4x with no correction

1 participant