Skip to content

improve: reduce CPU spent on multilingual context estimates - #148663

Merged
steipete merged 2 commits into
mainfrom
codex/cjk-estimator-lookup
Sep 15, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/cjk-estimator-lookup

Conversation

@steipete

@steipete steipete commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Multilingual prompt, compaction, and tool-result budgeting repeatedly scans the same text for different character weights, adding synchronous CPU work to agent turns.

User Impact

Weighted text estimates use less CPU while preserving the same token counts, safety floors, and text cuts. The tradeoff is a fixed 205 KiB lookup table per loaded module instance. No configuration, schema, or API changes are required.

Why This Change Was Made

A single range declaration now builds the category lookup and a native prefilter. ASCII and text without weighted characters return early; the numeric scan starts at the first weighted character. This removes the repeated category scans and duplicated range union without changing the weighting policy.

Evidence

All 2,268,082 differential comparisons passed on the final source, covering every Unicode code point at both optimized floors, mixed boundaries, lone surrogates, repeated calls, fractional floors, Infinity, and NaN. The candidate also passed 229 tests across the actual estimator, compaction, request budgeting, tool-result truncation, review transcripts, and memory chunking. Targeted type-aware lint passed. Independent review through P2 found no actionable issues.

One bounded ABBA screen on Node 26.7.0 used text up to 16,384 UTF-16 units. Mean CPU per 128 calls fell from 32.94 to 3.43 ms for common CJK, 29.91 to 4.04 ms for rare/supplementary text, and 27.06 to 3.88 ms for alternating categories. Additional cases cover early accents, early and sparse common CJK, supplementary prefixes, short mixed text, and single code points. The accented-text case stayed near baseline; ASCII wall time differed by about 0.027 ms per 128 calls. ASCII and single-code-point CPU readings were small and noisy, so they do not establish a speedup. These are synthetic component measurements, not a whole-Gateway or startup-speed claim.

The full local build and complete changed-file checks passed, including core/test type checks, lint, dead-export scans, storage guards and import-cycle checks. Hosted CI passed on 614228c974042e89dc0159b648f446144c4147d0.

Use one character-range declaration for a native prefilter and fixed lookup.
Preserve token estimates, raw safety floors, and UTF-16 budget boundaries
while reducing CPU spent on multilingual prompt and tool-result text.
@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 complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added size: S maintainer Maintainer-authored PR labels Sep 15, 2026
@steipete
steipete marked this pull request as ready for review September 15, 2026 01:01
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 15, 2026
@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 14, 2026, 9:23 PM ET / September 15, 2026, 01:23 UTC (Revision 2).

ClawSweeper review

What this changes

Replace repeated multilingual character scans with a shared lookup table while preserving context estimates, safety floors, and text cuts.

Merge readiness

✅ Ready for maintainer review

This remains a useful performance improvement: current main still performs repeated category scans. No actionable correctness or security defect was found in the introduced changes.

Priority: P2
Reviewed head: 614228c974042e89dc0159b648f446144c4147d0

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with preserved contracts, useful boundary coverage, and appropriately limited performance claims.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied repository state identifies a maintainer-authored PR, so the external-contributor proof gate does not apply. Reported Node component measurements exercise the changed estimator and show lower multilingual counting CPU; they do not establish whole-Gateway performance.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied repository state identifies a maintainer-authored PR, so the external-contributor proof gate does not apply. Reported Node component measurements exercise the changed estimator and show lower multilingual counting CPU; they do not establish whole-Gateway performance.
Evidence reviewed 8 items Introduced implementation: Read the complete estimator and its tests. The five lookup buckets match the removed regular-expression ranges; surrogate pairs retain their original UTF-16 base cost, and fractional/nonfinite floors retain the existing fallback arithmetic.
Current-main necessity: The fetched main revision still uses separate category-counting scans. The lookup optimization is not already present.
Latest-release comparison: v2026.9.4 also contains the repeated-scan implementation, rather than this lookup optimization.
Findings None None.
Security None None.

How this fits together

OpenClaw’s shared text estimator converts prompt and tool-result text into approximate context costs. Compaction and truncation callers use those costs to keep requests within their budgets.

flowchart TD
  A[Prompt and tool-result text] --> B[Shared text estimator]
  B --> C{Weighted characters present?}
  C -->|No| D[Raw text cost]
  C -->|Yes| E[Unicode category lookup]
  E --> F[Weighted context cost]
  D --> G[Compaction and truncation budgets]
  F --> G
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +79, Tests +4. Total +83 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 106 27 +79
Tests 1 4 0 +4
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 110 27 +83

Review metrics

Metric Value Why it matters
Fixed lookup memory 210,048 bytes per loaded module instance The bounded allocation replaces repeated scans and is explicitly acknowledged in the PR’s performance tradeoff.
Production versus test growth Production net +79 lines; tests net +4 lines Production growth is justified by a single declarative range table and numeric scan replacing duplicated regex categories.

Technical review

Best possible solution:

Keep one shared estimator with identical budgeting semantics and the explicitly bounded lookup-memory tradeoff.

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

Not applicable as a correctness bug: this is a performance optimization. Source confirms repeated scans on main, and the PR reports bounded before/after component measurements.

Is this the best way to solve the issue?

Yes. The patch optimizes the existing owner, preserves its public contracts, and uses one range declaration for both filtering and lookup.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded CPU improvement in frequently used context budgeting, without an urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; 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 supplied repository state identifies a maintainer-authored PR, so the external-contributor proof gate does not apply. Reported Node component measurements exercise the changed estimator and show lower multilingual counting CPU; they do not establish whole-Gateway performance.

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)

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-15T01:07:50.971Z sha 2a1f2e1 :: needs maintainer review before merge. :: none

@steipete
steipete merged commit 25155c4 into main Sep 15, 2026
146 of 147 checks passed
@steipete
steipete deleted the codex/cjk-estimator-lookup branch September 15, 2026 01:43
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 15, 2026
…#148663)

* perf: avoid repeated scans in weighted text estimates

Use one character-range declaration for a native prefilter and fixed lookup.
Preserve token estimates, raw safety floors, and UTF-16 budget boundaries
while reducing CPU spent on multilingual prompt and tool-result text.

* fix: handle unweighted character lookup results explicitly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. 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