Skip to content

improve(agents): trim large tool results with less CPU - #148718

Merged
vincentkoc merged 1 commit into
mainfrom
fix/tool-result-text-budget-cpu-20260915
Sep 15, 2026
Merged

vincentkoc merged 1 commit into
mainfrom
fix/tool-result-text-budget-cpu-20260915

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

Trimming oversized tool results repeatedly scans overlapping text while searching for the retained prefix or tail, adding synchronous CPU work before the model can continue.

User Impact

The same tool-result text, ordering, truncation notices, and Unicode boundaries are preserved. Large-input cutter measurements now show less CPU work; this is not a gateway end-to-end latency claim.

Why This Change Was Made

For the two integer weight floors used by runtime callers, the canonical cutter updates the measured weight using only the interval that changed between candidates. Other floors keep whole-candidate measurement to preserve per-ASCII-run rounding. The search and its final UTF-16-safe cuts stay unchanged.

Production: +20/-1 lines (net +19) for the incremental measurement state and non-additive rounding branch; tests: +29/-10 lines (net +19). Regression coverage exercises prefix/tail boundaries, fractional-floor rounding, and head-plus-tail truncation with mixed Unicode.

Evidence

Exact head 67bfe84f563340f14b37e0b6905ed448ae38f3fd versus base b45506d663b5c8a84a9b9ae327e098ef348ff193, using the same current estimator and UTF-16 helper in both variants. Independent source review found no actionable P0–P2 defect.

  • 131,880 exact prefix/tail output comparisons passed: 471 strings, 10 floors, 14 budgets, both directions, deterministic seed 0x67bfe. Covers ASCII, CJK, supplementary characters, emoji, unpaired surrogates, fractional floors, and negative/nonfinite bounds.
  • 418 tests passed across six files: 169 cutter/truncation/context-guard tests locally (Node 26.7.0, pnpm 12.3.4; 21.27 s), plus 249 Code Mode/read/Codex dynamic-tool tests on Linux (Node 24.19.0; 33.39 s). Scoped oxfmt and oxlint passed; tracked source and lockfile stayed unchanged.
  • Personally inspected public Codex revision 414782450952a196bbb64b1605a458c2531c47b6: protocol content items and success, lines 61–62 and ordered FunctionToolOutput conversion, lines 152–162. Public source bytes match the inspected sibling checkout; text order and success propagation are unchanged.

Measured on Blacksmith Testbox, Linux x64, Node 24.19.0, AMD EPYC, four available CPUs, on 2026-09-15. The native measurement receipt attested this head and source tree b0458605eb94e9e236b9b2525151eebfa6a75d77 (measurement carrier 6cc17ff7e5946b321f368269eee5c19181d10eb7). Lease tbx_01m2hhjp1cjvzrhc55e3925j6z completed successfully and was stopped.

64 timing scenarios use two warm batches and four alternating baseline/candidate samples. Table values are wall-clock microseconds per call, spanning both directions and integer floors:

Cut input Baseline µs/call Candidate µs/call
ASCII, 16,000 UTF-16 units 10.60–19.56 1.96–2.17
ASCII, 128,000 units 98.75–185.32 12.87–13.02
Mixed Unicode, 16,000 units 105.07–112.88 39.44–39.62
Mixed Unicode, 128,000 units 1009.43–1083.51 315.07–315.47

The worst 32-unit regression was 0.0501 µs/call. Fitting-input ratios ranged 0.979–1.089 (median 1.001), so these samples do not establish an improvement for already-fitting input. No extra small-input branch was added.

A separate 400-cut mixed-text workload ran in four fresh processes, baseline/candidate/candidate/baseline:

Measure Baseline Candidate
Wall seconds 0.12861–0.12888 0.04361–0.04369
CPU seconds 0.12904–0.12937 0.04390–0.04417
Peak RSS MiB 74.883–78.109 77.617–78.242

Peak RSS includes parsing, estimator lookup initialization, and warmup. The ranges overlap; no retained-allocation or memory-reduction claim is made. This is bounded cutter proof, not a production profile or end-to-end benchmark.

ClawSweeper follow-through: the exact-head review found no code defect. Its requested current-estimator CPU/RSS, short-input tradeoff, and parity evidence—and the same Rank-up move—are addressed above. The measured large-input benefit supports keeping the canonical incremental path; fractional rounding stays unchanged. No source change or rating-only re-review is needed. Exact-head CI run 34924254509 completed successfully; required checks are green. Independent review also verified the captured measurements and test receipts.

@vincentkoc vincentkoc self-assigned this Sep 15, 2026
@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@vincentkoc
vincentkoc marked this pull request as ready for review September 15, 2026 03:14
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Sep 15, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 15, 2026
@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 14, 2026, 11:30 PM ET / September 15, 2026, 03:30 UTC (Revision 2).

ClawSweeper review

What this changes

The PR reduces repeated scanning while trimming oversized tool output, retaining existing Unicode-safe cuts and adding coverage for integer and fractional text weights.

Merge readiness

⛔ Blocked before merge - 2 items remain

This remains a distinct, useful optimization candidate with no identified correctness defect. Current main does not implement it, and the scoped performance-validation requirement remains outstanding.

Priority: P2
Reviewed head: 67bfe84f563340f14b37e0b6905ed448ae38f3fd

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused implementation appears correct, but its central performance benefit remains unmeasured against the current estimator.
Proof confidence 🌊 off-meta tidepool Not applicable: The external-contributor proof gate does not apply to this MEMBER-authored PR, and no authority change triggers an exception; scoped before/after cutter performance validation remains separately required.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The external-contributor proof gate does not apply to this MEMBER-authored PR, and no authority change triggers an exception; scoped before/after cutter performance validation remains separately required.
Evidence reviewed 10 items Introduced optimization: The pinned merge-base-to-head patch changes only the cutter and two test files. The cutter updates integer-floor estimates by adding or subtracting the changed interval; other floors retain whole-candidate measurement.
Arithmetic and Unicode contracts: The estimator's floors 1 and 2 use additive integer costs, while other floors preserve per-ASCII-run rounding. The slicing helper moves boundaries out of surrogate pairs, so intervals between retained candidate boundaries contain complete code points.
Current main still measures whole candidates: Fetched main retains the full-candidate estimate inside each binary-search iteration. Its estimator and UTF-16 helper match those inspected at the PR head.
Findings None None.
Security None None.

How this fits together

OpenClaw trims oversized tool results before passing them into model context. The text-budget cutter selects a prefix or diagnostic tail using a shared multilingual character estimator.

flowchart LR
  A[Tool output] --> B[Tool result truncation]
  B --> C[Prefix or tail search]
  C --> D[Weighted text estimator]
  D --> E[Budget decision]
  E --> C
  E --> F[Unicode-safe retained text]
  F --> G[Model context]
Loading

Before merge

  • Resolve merge risk (P1) - Net CPU and RSS effects against the current estimator remain unmeasured, particularly for ASCII and short inputs where added bookkeeping may outweigh saved scanning.
  • Complete next step (P2) - Add current-estimator before/after seconds and RSS, plus prefix/tail output parity for ASCII, mixed Unicode, and fractional floors, to the PR evidence.
Agent review details

Security

None.

PR surface

Source +19, Tests +19. Total +38 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 20 1 +19
Tests 2 29 10 +19
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 49 11 +38

Review metrics

Metric Value Why it matters
Production versus test growth production net +19 lines; tests net +19 lines The body explains the production growth as incremental measurement state plus the fractional-floor fallback; performance measurements must establish its payoff.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep one canonical cutter with unchanged output semantics, retaining incremental accounting where current-estimator measurements demonstrate a worthwhile benefit.
  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 canonical cutter with unchanged output semantics, retaining incremental accounting where current-estimator measurements demonstrate a worthwhile benefit.

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

Yes for the repeated work: current-main source measures overlapping candidates on each search iteration. Its runtime cost and the proposed speedup were not measured in this read-only review.

Is this the best way to solve the issue?

The ownership and arithmetic are appropriate: the existing cutter reuses additive estimates and preserves fractional rounding. Whether the added bookkeeping is worthwhile remains unclear until current-base performance results are available.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against a4a3e5670573.

Labels

Label justifications:

  • P2: This is a bounded agent-runtime performance improvement without evidence of an urgent user-facing regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The external-contributor proof gate does not apply to this MEMBER-authored PR, and no authority change triggers an exception; scoped before/after cutter performance validation remains separately required.

Evidence

What I checked:

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

Rank-up moves

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

  • Record before/after seconds and RSS against the current estimator, with prefix/tail output parity across ASCII, mixed Unicode, and fractional floors.

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 (1 earlier review cycle)
  • reviewed 2026-09-15T03:20:57.396Z sha 67bfe84 :: blocked before merge. :: none

@vincentkoc
vincentkoc merged commit c50f56d into main Sep 15, 2026
279 checks passed
@vincentkoc
vincentkoc deleted the fix/tool-result-text-budget-cpu-20260915 branch September 15, 2026 03:40
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 15, 2026
vincentkoc added a commit that referenced this pull request Sep 15, 2026
* commit 'd8e50a38fd1c4df6dd69bcbc155697c464e1be45': (23 commits)
  fix(cron): release queued reservations when activation fails (#141008)
  fix(gateway): reduce CPU work in session lists and searches (#148713)
  feat(gateway): add admin CPU profile diagnostics (#148004)
  fix(gateway): cap device-required probe cache to prevent unbounded growth (#147708)
  fix(ci): align Gateway E2E expectations (#148653)
  refactor(ai): remove unused overflow wrapper (#148719)
  feat: stage selected chat text as editable comments (#148649)
  fix(ci): admit reachable release refs with large histories (#148161)
  fix(agents): allow authorized email CLI actions (#148521)
  improve(agents): trim large tool results with less CPU (#148718)
  refactor(docker): share image version parsing (#148243)
  fix(ci): retain passing hosted checks after skipped duplicates (#148722)
  fix(update): report configuration failures during repair (#144819)
  refactor(imessage): share handle classification (#148229)
  fix(ui): keep the selected agent across Settings pages (#148667)
  test(telegram): reuse deferred fixture helper (#148501)
  fix(media): resize images before understanding (#122431)
  fix: preserve unfinished work during completed PR cleanup (#148704)
  refactor(migrate-hermes): reuse canonical config record coercion (#148645)
  perf(channels): reduce history worker metadata footprint (#148711)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S 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.

1 participant