Skip to content

improve: reduce allocations while budgeting multilingual tool results - #138646

Merged
steipete merged 1 commit into
mainfrom
codex/perf9-text-budget-hotspot
Sep 5, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/perf9-text-budget-hotspot

Conversation

@steipete

@steipete steipete commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Budgeting large multilingual tool results creates substantial temporary allocation as results are checked and trimmed for model context. The context guard's raw-weight floor makes this particularly expensive for dense CJK text.

Why This Change Was Made

Move weighted counting into the shared CJK owner, count the existing character categories without materializing match arrays, and calculate the common raw-weight floors over the whole string. Preserve the one-argument public estimator, existing Unicode weights, UTF-16 boundaries, and the original rounding and nonfinite arithmetic for other floors.

User Impact

Tool-result budgets and truncation output remain identical. Dense multilingual inputs use less temporary allocation in the measured counting path; some default-weight and sparse-input cases are slower, as detailed below.

Production LOC: +48/-46 (net +2). Tests: +32/-0. The small production increase retains the public callback contract while consolidating the weighted owner and removing the previous local weighted path.

Evidence

Exact baseline/candidate output hashes match for all 1,114,112 Unicode code points, 4,352 mixed-weight cases, 34,816 prefix/tail boundary cases, and six real context-guard/read-page scenarios. Coverage includes unpaired surrogates, fractional and very large weights, NaN/Infinity, notices, continuations, and unchanged input messages.

In baseline/candidate/candidate/baseline microbenchmarks, the following means cover 32 estimates of 65,536 UTF-16 units at raw weight 2:

Input Before After
Common CJK 166.97 ms 27.59 ms
Rare/supplementary CJK 219.32 ms 24.00 ms
Emoji 66.22 ms 6.99 ms
Mixed multilingual 104.40 ms 16.11 ms
Sparse CJK in ASCII 3.92 ms 5.29 ms

Default-weight rare/supplementary and multilingual cases were 15% and 11% slower. The sparse weight-2 difference is about 0.043 ms per 64K call. These are two observations per arm, not an end-to-end latency claim.

In a separate fixed six-fixture workload, allocation sampling estimated 2.12/2.14 GB of cumulative allocations in the baseline estimator stacks and recorded no samples there after the change. Sampling does not measure retained heap, and zero samples do not prove zero engine allocation.

All 443 focused tests across nine files passed. The full build, native imports of the built SDK, exhaustive packaged Unicode comparison, complete changed-file gate, and independent managed Codex review through P2 passed. The native check also verifies shared-owner identity and callback behavior. An initial gate rejected global NaN literals in the new test table; changing them to Number.NaN, rerunning the affected 19 tests, and rerunning the complete gate resolved it.

Integrated Gateway comparison

The controlled built-Gateway comparison is complete: baseline/candidate/candidate/baseline, two observations per arm and ten model turns per run across Code Mode and ToolSearch. Candidate 15216423e92c contains all 20 changes, including this exact patch. The independent audit verified the 40 turns, unchanged history prefixes, exact file output and Unicode truncation, and recomputed the recorded comparison values.

Sampled allocation volume Baseline mean Combined candidate mean Change
All sampled stages 1,088.02 MiB 986.56 MiB −9.33%
Code Mode 757.17 MiB 656.67 MiB −13.27%
ToolSearch 330.85 MiB 329.89 MiB −0.29%

These are main-isolate sampled allocation estimates, including collected objects, for the combined candidate; they do not isolate this PR's contribution. ToolSearch's two paired differences have opposite signs. Post-GC idle memory did not decrease: Code Mode RSS was 484.88→485.78 MiB and main heap 268.43→268.45 MiB; ToolSearch RSS was 480.64→480.71 MiB and main heap 259.92→260.13 MiB. RSS includes Gateway workers, while heap and allocation sampling cover the main isolate.

Latency was mixed: instrumented stage totals changed by −1.75% for Code Mode and +0.95% for ToolSearch. Those intervals include fixed settling and sampling overhead, with live provider and cache variability. Two observations per arm establish neither statistical significance nor a uniform latency or retained-memory improvement. Normal native landing gates still apply.

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@steipete
steipete marked this pull request as ready for review September 4, 2026 21:51
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Sep 4, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. 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. labels Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 4, 2026, 7:17 PM ET / 23:17 UTC.

ClawSweeper review

What this changes

The PR moves weighted multilingual text counting into the shared estimator and avoids temporary match arrays while preserving tool-result budgets and truncation output.

Merge readiness

✅ Ready for maintainer review

This remains a useful optimization absent from the reviewed main and release sources. The updated Gateway comparison addresses the previous review’s proof request, and no introduced correctness defect remains.

Priority: P3
Reviewed head: 15ec362ad29985efefddb2b97e6c8bcabfc340c1

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A compact owner-level refactor and completed Gateway comparison support normal mergeable quality, with performance claims appropriately limited to the measured workloads.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Captured before/after results exercise the shared counter through built-Gateway Code Mode and ToolSearch across 40 turns, with unchanged history, file output, and Unicode truncation. This addresses the prior composition-proof request; the combined candidate’s performance gains are not attributed solely to this patch.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Captured before/after results exercise the shared counter through built-Gateway Code Mode and ToolSearch across 40 turns, with unchanged history, file output, and Unicode truncation. This addresses the prior composition-proof request; the combined candidate’s performance gains are not attributed solely to this patch.
Evidence reviewed 10 items Pinned introduction and merge ownership: The checkout matches the original PR head and its recorded parent. The test merge has the pinned base followed by that exact head as parents; its delta contains only the same four introduced files, not the unrelated endpoint drift.
Shared counting owner preserves arithmetic: The one-argument estimator remains a wrapper, preserving callback use. Floors 1 and 2 use whole-string accounting with unchanged Unicode categories; other floors retain the previous segmentation, rounding, and nonfinite arithmetic. Every counting regex consumes characters and is exhausted before returning.
Production callers and truncation boundary: The message estimator supplies the existing raw-weight floor of 2. The context guard invokes weighted truncation, while read-page pagination checks both ordinary and context budgets. Prefix/tail searches still use the unchanged surrogate-safe slicer; truncation notices and continuation ownership are unchanged.
Findings None None.
Security None None.

How this fits together

OpenClaw estimates tool-output size before passing it into model context. The shared Unicode counter feeds context guards, truncation, and file-read pagination so multilingual text stays within existing limits.

flowchart TD
  A[Tool output and file pages] --> B[Shared Unicode counter]
  C[Existing caller safety floor] --> B
  B --> D{Fits text budget?}
  D -->|Yes| E[Unchanged output]
  D -->|No| F[Unicode-safe truncation]
  E --> G[Model context]
  F --> G
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +2, Tests +32. Total +34 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 2 48 46 +2
Tests 2 32 0 +32
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 80 46 +34

Review metrics

Metric Value Why it matters
Production versus test LOC Production net +2; tests +32 Weighted logic moves into its shared owner; the small remaining growth preserves the one-argument callback contract rather than adding another budgeting policy.

Technical review

Best possible solution:

Keep one shared weighted counter while preserving existing estimator signatures, numeric semantics, and Unicode-safe truncation boundaries.

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

Not applicable to a correctness bug: this is an allocation optimization, supported by captured baseline/candidate measurements and output-equivalence checks rather than a reported functional failure.

Is this the best way to solve the issue?

Yes. Moving weighted arithmetic into the existing Unicode owner removes the local counting path while preserving callers; replacing the heuristic with a tokenizer would change the contract and broaden scope unnecessarily.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. Captured before/after results exercise the shared counter through built-Gateway Code Mode and ToolSearch across 40 turns, with unchanged history, file output, and Unicode truncation. This addresses the prior composition-proof request; the combined candidate’s performance gains are not attributed solely to this patch.
  • remove merge-risk: 🚨 other: Current PR review selected no merge-risk labels.

Label justifications:

  • P3: This is a bounded allocation optimization with intentionally unchanged user-visible budgeting behavior, not an urgent functional regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Captured before/after results exercise the shared counter through built-Gateway Code Mode and ToolSearch across 40 turns, with unchanged history, file output, and Unicode truncation. This addresses the prior composition-proof request; the combined candidate’s performance gains are not attributed solely to this patch.
  • proof: sufficient: Contributor real behavior proof is sufficient. Captured before/after results exercise the shared counter through built-Gateway Code Mode and ToolSearch across 40 turns, with unchanged history, file output, and Unicode truncation. This addresses the prior composition-proof request; the combined candidate’s performance gains are not attributed solely to this patch.

Evidence

What I checked:

  • Pinned introduction and merge ownership: The checkout matches the original PR head and its recorded parent. The test merge has the pinned base followed by that exact head as parents; its delta contains only the same four introduced files, not the unrelated endpoint drift. (182dfeaf141b)
  • Shared counting owner preserves arithmetic: The one-argument estimator remains a wrapper, preserving callback use. Floors 1 and 2 use whole-string accounting with unchanged Unicode categories; other floors retain the previous segmentation, rounding, and nonfinite arithmetic. Every counting regex consumes characters and is exhausted before returning. (packages/normalization-core/src/cjk-chars.ts:27, 15ec362ad299)
  • Production callers and truncation boundary: The message estimator supplies the existing raw-weight floor of 2. The context guard invokes weighted truncation, while read-page pagination checks both ordinary and context budgets. Prefix/tail searches still use the unchanged surrogate-safe slicer; truncation notices and continuation ownership are unchanged. (src/agents/embedded-agent-runner/tool-result-char-estimator.ts:80, 15ec362ad299)
  • Existing API and implementation boundary: The existing text-utility SDK names continue to expose the same estimator contracts; the new implementation lives in the private normalization workspace package. OpenClaw Code Mode is implemented by OpenClaw’s QuickJS controller, and its documentation explicitly distinguishes it from Codex Code Mode. Neither the patch nor its runtime proof depends on a Codex protocol contract. (src/plugin-sdk/text-utility-runtime.ts:5, 15ec362ad299)
  • Focused contract coverage: Added cases cover fractional floors, NaN/Infinity, unpaired surrogates, supplementary CJK, repeated estimates, and direct Array.map callback use. Existing context-guard coverage verifies that dense CJK is truncated within the weighted cap without modifying input messages; existing Code Mode tests check producer-to-context and persisted-output consistency. (src/agents/embedded-agent-runner/tool-result-text-budget.test.ts:22, 15ec362ad299)
  • Still necessary on reviewed main: Fetched main retains match-array counting and the separate per-segment weighted estimator. Both production files have identical blobs in the supplied latest release, v2026.9.1, so this allocation optimization is absent from both reviewed versions. (packages/normalization-core/src/cjk-chars.ts:24, dcdeede2fa47)

Likely related people:

  • qingminlong: Raw commit a01319b adds packages/normalization-core/src/cjk-chars.ts:13 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: a01319b27fe5; files: packages/normalization-core/src/cjk-chars.ts)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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-04T21:58:42.914Z sha 15ec362 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Sep 4, 2026
@steipete
steipete merged commit 1f3b806 into main Sep 5, 2026
255 of 256 checks passed
@steipete
steipete deleted the codex/perf9-text-budget-hotspot branch September 5, 2026 00:08
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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 P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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