Skip to content

fix: account for CJK text in compaction estimates (issue #103930) - #114386

Merged
steipete merged 4 commits into
openclaw:mainfrom
qingminglong:issue-pr/103930-cjk-compaction-estimate-v2
Jul 27, 2026
Merged

steipete merged 4 commits into
openclaw:mainfrom
qingminglong:issue-pr/103930-cjk-compaction-estimate-v2

Conversation

@qingminglong

@qingminglong qingminglong commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Closes #103930

What Problem This Solves

The compaction estimator used UTF-16 length divided by four for all text. On current main, a natural Chinese sample was estimated at 15 tokens while o200k_base measured roughly 2.2–2.8 times more tokens; findCutPoint(..., 100) consequently retained about 287 actual tokenizer tokens for a 100-token target. CJK-heavy sessions could therefore miss the intended retained-tail budget and approach context overflow.

Fix

Move the existing shared CJK-aware estimator into @openclaw/normalization-core and use it throughout agent-core compaction accounting. The weights are calibrated against real tiktoken==0.13.0 measurements for both o200k_base and cl100k_base, including natural Chinese/Japanese/Korean, decomposed Hangul, halfwidth and compatibility forms, rare BMP characters, supplementary ideographs and kana, and script-extension marks.

This is the owner-boundary fix: both compaction triggering and retained-tail selection consume the same estimator, agent-core already depends on normalization-core, and the root utility now delegates to that owner instead of duplicating policy. Latin and image accounting remain unchanged.

Evidence

  • Exact head: 0a66f66dfd1747376351c2820205577056d450d5.
  • Current-main reproduction: Chinese sample estimated at 15 tokens; a 100-token retained-tail target kept about 287 actual o200k_base tokens.
  • Real tokenizer probe: tiktoken==0.13.0, o200k_base and cl100k_base, covering the Unicode categories listed above.
  • Focused Blacksmith Testbox proof: 77 tests passed across five compaction/estimator files.
  • Full pnpm build and full pnpm check passed on the reviewed tree.
  • Targeted formatting/lint and git diff --check passed.
  • Autoreview: clean.
  • Independent adversarial review: NO-ACTIONABLE-OBJECTION.
  • Exact-head hosted CI is required before merge.

ClawSweeper rank-up move: the branch is not rebased solely for behind-main drift because the repository landing workflow preserves hosted contributor ancestry unless merge verification finds relevant drift. Focused retained-tail proof passed on the reviewed tree; exact-head CI plus scripts/pr prepare-run and merge verification fail closed before landing.

AI-assisted: yes. The maintainer rewrite was reviewed against current main, real tokenizer measurements, sibling compaction surfaces, and contributor credit is preserved.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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, 8:36 AM ET / 12:36 UTC.

ClawSweeper review

What this changes

The PR moves CJK-aware character weighting into Normalization Core and uses it when Agent Core estimates transcript tokens for compaction triggering and retained-tail selection.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

This PR addresses a confirmed current-main compaction bug and is still necessary: current main estimates the retained transcript tail with raw UTF-16 length divided by four, while the proposed branch applies a shared CJK-aware estimate across that decision path. The patch follows the repository’s owner-boundary direction by placing the reusable heuristic in Normalization Core, and the supplied real-tokenizer and focused Testbox evidence supports the behavior change. It should remain open for maintainer landing review and exact merge-result verification, not be closed as obsolete.

Priority: P2
Reviewed head: 0a66f66dfd1747376351c2820205577056d450d5

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, owner-aligned bug fix with substantive real-behavior evidence; remaining review work is merge-result verification for a session-context boundary.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR documents after-fix real tokenizer probes against both o200k_base and cl100k_base, a current-main retained-tail reproduction, and focused Testbox results; the existing proof: sufficient label is consistent with that evidence.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR documents after-fix real tokenizer probes against both o200k_base and cl100k_base, a current-main retained-tail reproduction, and focused Testbox results; the existing proof: sufficient label is consistent with that evidence.
Evidence reviewed 5 items Current-main behavior: Current main computes compaction message estimates with raw .length values and Math.ceil(chars / 4), including the findCutPoint retention loop; it does not use the existing CJK-aware estimator.
Existing shared heuristic: Current main already provides estimateStringChars() specifically to inflate CJK text before a chars-per-token estimate, confirming the reported discrepancy and the supported estimation pattern.
Issue-to-patch fit: The linked report identifies the same compaction estimator and cut-point loop, documents the CJK undercount mechanism, and distinguishes it from earlier preemptive-compaction and tool-result fixes.
Findings None None.
Security None None.

How this fits together

Agent Core compaction estimates the token size of session messages, decides whether context is too large, and selects the recent transcript tail to retain while older content is summarized. This PR changes the shared text-size heuristic that feeds those compaction decisions for CJK-heavy user, assistant, tool, and summary content.

flowchart TD
  A[Session transcript entries] --> B[Agent Core token estimation]
  B --> C[CJK-aware character heuristic]
  C --> D[Context-size estimate]
  D --> E[Compaction threshold decision]
  D --> F[Retained-tail cut point]
  E --> G[Summary generation]
  F --> G
  G --> H[Updated session context]
Loading

Before merge

  • Resolve merge risk (P1) - Compaction’s estimator determines which transcript entries remain in live session context; although the CJK correction is intentional and focused proof is supplied, landing should verify the retained-tail behavior on the actual merge result because the branch is behind current main.
  • Complete next step (P2) - No mechanical repair is identified; a maintainer should complete exact-head merge verification because the patch intentionally changes the retained session-context boundary.
Agent review details

Security

None.

PR surface

Source -17, Tests +191, Config +8. Total +182 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 4 79 96 -17
Tests 4 199 8 +191
Docs 0 0 0 0
Config 2 9 1 +8
Generated 0 0 0 0
Other 0 0 0 0
Total 10 287 105 +182

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #103930
Summary: This PR is a concrete candidate fix for the canonical open report about CJK-blind compaction tail estimation.

Members:

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

Merge-risk options

Maintainer options:

  1. Verify the merge-result compaction path (recommended)
    Run the focused retained-tail/compaction proof against the exact merge result, then land if the CJK budget correction and unchanged Latin/image behavior hold.
  2. Pause for a refreshed compaction review
    Pause only if merge verification exposes a behavior interaction with current-main compaction changes; otherwise the patch has a bounded owner-aligned path.

Technical review

Best possible solution:

Keep one canonical CJK-aware estimator in packages/normalization-core, route all compaction message-text accounting through it, and land only after exact merge-result validation confirms both CJK tail budgeting and unchanged Latin/image behavior.

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

Yes, at source level: current main visibly applies raw UTF-16 length divided by four throughout the compaction estimator and cut-point loop, while the existing CJK helper shows the missing correction. The supplied PR evidence also records a current-main tokenizer reproduction, but this review did not independently execute it.

Is this the best way to solve the issue?

Yes. Reusing one CJK-aware estimator at the Normalization Core boundary and consuming it in every compaction text-accounting branch is narrower and more maintainable than introducing a compaction-only duplicate heuristic.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: CJK-heavy sessions can retain an incorrectly oversized compaction tail, but the issue is bounded to approximate session-context accounting rather than an emergency outage.
  • merge-risk: 🚨 session-state: The patch deliberately changes how much session transcript is retained versus summarized, so merge-result validation must confirm the intended context boundary.
  • 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 (terminal): The PR documents after-fix real tokenizer probes against both o200k_base and cl100k_base, a current-main retained-tail reproduction, and focused Testbox results; the existing proof: sufficient label is consistent with that evidence.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR documents after-fix real tokenizer probes against both o200k_base and cl100k_base, a current-main retained-tail reproduction, and focused Testbox results; the existing proof: sufficient label is consistent with that evidence.

Evidence

What I checked:

Likely related people:

  • steipete: steipete authored the reviewed head’s final lint-safety commit, is assigned on this PR, and is the strongest available history signal for the current shared-estimator/compaction shape. (role: recent compaction-area contributor and assigned reviewer; confidence: medium; commits: 0a66f66dfd17; files: packages/normalization-core/src/cjk-chars.ts, packages/agent-core/src/harness/compaction/compaction.ts)

Rank-up moves

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

  • Verify the focused retained-tail behavior on the exact merge result before landing.

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 (7 earlier review cycles)
  • reviewed 2026-07-27T06:54:29.065Z sha 5f3aa573a3c1dce228c7378f2a771edda7778a33 :: needs real behavior proof before merge. :: [P1] Reuse one canonical CJK estimator
  • reviewed 2026-07-27T07:33:08.833Z sha 820eb6eb9eac9c3aa97b5cec188667487fb584d6 :: needs real behavior proof before merge. :: [P1] Reuse the canonical CJK estimator
  • reviewed 2026-07-27T08:29:23.973Z sha ceee7bd :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-27T09:01:41.101Z sha e11aad2 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-27T09:16:51.268Z sha e11aad2 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-27T09:25:05.461Z sha e11aad2 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-27T09:31:51.177Z sha e11aad2 :: needs maintainer review before merge. :: none

@qingminglong
qingminglong force-pushed the issue-pr/103930-cjk-compaction-estimate-v2 branch from 5f3aa57 to 820eb6e Compare July 27, 2026 07:28
@qingminglong
qingminglong force-pushed the issue-pr/103930-cjk-compaction-estimate-v2 branch from 7f7abc5 to 013f2cf Compare July 27, 2026 07:56
@qingminglong
qingminglong force-pushed the issue-pr/103930-cjk-compaction-estimate-v2 branch from 013f2cf to ceee7bd Compare July 27, 2026 08:13
@steipete steipete self-assigned this Jul 27, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Jul 27, 2026
@qingminglong

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 27, 2026
@openclaw-barnacle openclaw-barnacle Bot added triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. and removed triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 27, 2026
@steipete
steipete merged commit a01319b into openclaw:main Jul 27, 2026
138 of 142 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 28, 2026
) (openclaw#114386)

* fix: account for CJK text in compaction estimates

* fix: share CJK compaction estimator

* fix: format CJK compaction estimator

* fix: make CJK regexes lint-safe

Co-authored-by: qingminlong <[email protected]>

---------

Co-authored-by: Peter Steinberger <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. 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: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

2 participants