Skip to content

improve(ai): speed up Unicode message preparation - #151950

Merged
steipete merged 1 commit into
mainfrom
codex/perf-unicode-wellformed
Sep 18, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/perf-unicode-wellformed

Conversation

@steipete

@steipete steipete commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Preparing model messages repeatedly runs the surrogate-removal regex over text that is already valid Unicode, adding CPU cost to long multilingual and emoji transcripts.

User Impact

Less CPU time spent preparing those messages, with identical text sent to providers. This is a message-preparation improvement, not a claim about total turn or network latency. One 65,536-code-unit ASCII tool-result fixture regressed 6.4%; malformed-input sanitation was approximately unchanged.

Why This Change Was Made

Return valid strings immediately using the runtime's native isWellFormed() check. Malformed strings still use the existing regex, preserving removal of unpaired surrogates. The supported Node runtime already supplies this API; a narrow TypeScript library reference supplies its type without changing the compiler target or package runtime requirement.

Evidence

An isolated Linux Blacksmith Testbox experiment used Node 26.8.2 and the actual message-conversion and tool-result exports. Parity passed 4,096 surrogate-boundary combinations and 48 caller/concatenation cases. Timing used three warmup pairs and seven alternating measured pairs per case; all measurements, including regressions, were retained.

Actual message conversion fixture 4,096 UTF-16 code units 65,536 UTF-16 code units
Multilingual BMP text 93.2% 98.8%
Emoji text 89.3% 92.4%
ASCII text 6.5% 3.8%

Each table cell improved in all seven measured pairs. These are paired median reductions in component execution time; the smaller ASCII timings are less informative than the larger non-ASCII cases.

  • 119 existing tests passed across OpenAI conversion, Google conversion, tool-result text, and transport helpers.
  • Canonical formatting and git diff --check passed; formatted source is identical to the measured candidate.
  • All 28 changed-file checks passed, including core and test type checking, lint, and repository guards.
  • AI package JavaScript/declaration build passed; 42 declaration files retain the existing signature without leaking the private library reference. Built-export sanitation smoke passed.
  • Independent review completed with no actionable P0–P2 findings.
  • Hosted CI and the required gate passed on the exact PR commit.
  • ClawSweeper review completed with no actionable findings.

@clawsweeper

clawsweeper Bot commented Sep 18, 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: XS maintainer Maintainer-authored PR labels Sep 18, 2026
@steipete
steipete marked this pull request as ready for review September 18, 2026 16:30
@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 18, 2026
@clawsweeper

clawsweeper Bot commented Sep 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 18, 2026, 1:02 PM ET / 17:02 UTC (Revision 2).

ClawSweeper review

What this changes

Skip Unicode cleanup for already-valid model-message text while preserving existing removal of unpaired surrogates.

Merge readiness

✅ Ready for maintainer review

Keep open: this useful optimization is absent from current main and the latest release. No actionable correctness or security findings remain, and the protected maintainer PR is ready for normal review.

Priority: P2
Reviewed head: 9e5fc71e508d3df8cd06b288030a4312ff48f57f

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, compatible optimization with useful production-path measurements and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured body reports paired before/after measurements through actual message-conversion and tool-result exports on Linux Node 26.8.2, with output parity and observed component speedups; its disclosed ASCII regression limits the claim appropriately.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured body reports paired before/after measurements through actual message-conversion and tool-result exports on Linux Node 26.8.2, with output parity and observed component speedups; its disclosed ASCII regression limits the claim appropriately.
Evidence reviewed 8 items Introduced change preserves sanitation: The pinned introduction delta adds a native validity check and a TypeScript library reference; the existing removal regex remains unchanged. The predicate skips precisely the strings for which removal is unnecessary.
Still useful on current main: Fetched main still runs the removal regex unconditionally; it does not contain this fast path.
Latest release comparison: The supplied latest release, v2026.9.4, also contains the unconditional regex implementation.
Findings None None.
Security None None.

How this fits together

The AI package converts conversation and tool-result text into provider requests. Its shared Unicode sanitizer removes malformed surrogate characters before those requests are sent.

flowchart TD
  A[Conversation and tool results] --> B[Provider message preparation]
  B --> C{Valid Unicode?}
  C -->|Yes| D[Keep original text]
  C -->|No| E[Remove unpaired surrogates]
  D --> F[Provider request]
  E --> F
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +5. Total +5 across 1 file.

View PR surface stats
Area Files Added Removed Net
Source 1 5 0 +5
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 1 5 0 +5

Review metrics

Metric Value Why it matters
Reported component performance Multilingual/emoji conversion: 89.3–98.8% faster; one ASCII tool-result fixture: 6.4% slower The paired measurements support the targeted optimization while explicitly bounding its workload-dependent benefit.

Technical review

Best possible solution:

Retain one shared sanitizer with the native valid-text fast path and unchanged malformed-text removal.

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

Not applicable as a functional bug reproduction: this is a performance improvement, supported by reported paired measurements through actual production exports.

Is this the best way to solve the issue?

Yes. The native predicate avoids unnecessary regex work without changing malformed-input behavior, adding configuration, or creating a second sanitation owner.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The captured body reports paired before/after measurements through actual message-conversion and tool-result exports on Linux Node 26.8.2, with output parity and observed component speedups; its disclosed ASCII regression limits the claim appropriately.

Label justifications:

  • P2: A bounded message-preparation performance improvement with no demonstrated urgent user-facing failure.
  • 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): The captured body reports paired before/after measurements through actual message-conversion and tool-result exports on Linux Node 26.8.2, with output parity and observed component speedups; its disclosed ASCII regression limits the claim appropriately.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured body reports paired before/after measurements through actual message-conversion and tool-result exports on Linux Node 26.8.2, with output parity and observed component speedups; its disclosed ASCII regression limits the claim appropriately.

Evidence

What I checked:

  • Introduced change preserves sanitation: The pinned introduction delta adds a native validity check and a TypeScript library reference; the existing removal regex remains unchanged. The predicate skips precisely the strings for which removal is unnecessary. (packages/ai/src/utils/sanitize-unicode.ts:23, 9e5fc71e508d)
  • Still useful on current main: Fetched main still runs the removal regex unconditionally; it does not contain this fast path. (packages/ai/src/utils/sanitize-unicode.ts:21, 234e9e0c3766)
  • Latest release comparison: The supplied latest release, v2026.9.4, also contains the unconditional regex implementation. (packages/ai/src/utils/sanitize-unicode.ts:21, 3a9d69db306c)
  • Package runtime contract: The independently published AI package requires Node >=22.19.0; the change does not raise that requirement or alter exported signatures. (packages/ai/package.json:132, 9e5fc71e508d)
  • Native API compatibility and semantics: Node.js 20 release notes document isWellFormed support before the package's runtime floor. MDN confirms that it returns true exactly when no lone surrogates occur.
  • Production callers and supplied performance evidence: Read the message-conversion and tool-result owners that call the sanitizer. The captured PR body reports exercising their actual exports on Linux Testbox with Node 26.8.2: parity across 4,096 surrogate combinations and 48 caller cases, seven alternating measured pairs, substantial multilingual/emoji improvements, and one disclosed 6.4% ASCII tool-result slowdown. These are component measurements, not total-turn latency claims. Source snapshot: 192ea16207a74cad0e72becfaeb6b938c4643a757c682048da9bf5d2a03504f0. (packages/ai/src/openai-completions-messages.ts:97, 9e5fc71e508d)

Likely related people:

  • 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-18T16:36:04.422Z sha 9e5fc71 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 18, 2026

@Yigtwxx Yigtwxx left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 9e5fc71e508. The guard is semantically exact (the regex only ever removes lone surrogates, which is precisely what isWellFormed() tests), and I confirmed the two claims I could measure locally. One design point on how the type is supplied.

The /// <reference lib> is program-wide, not file-scoped

A triple-slash lib reference is merged into the program, so every file compiled together with sanitize-unicode.ts gets isWellFormed/toWellFormed typed — and the typing silently depends on this one file staying in the include set. Checked with tsc 6.0.3, lib: ["ES2023"]:

files: [other.ts, packages/ai/src/utils/sanitize-unicode.ts]  ->  other.ts using s.isWellFormed() / s.toWellFormed(): OK
files: [other.ts]                                             ->  TS2550 Property 'isWellFormed' does not exist on type 'string'

Mapped onto this repo's programs: tsconfig.core.json includes src/** + packages/**, so all of src/ gains the API; tsconfig.extensions.json includes only extensions/**, so an extension gets it only if its import graph reaches @openclaw/ai source through the paths mapping. Two tests currently hand-roll UNPAIRED_SURROGATE_RE explicitly "without relying on the ES2024 String.prototype.isWellFormed() runtime API" (extensions/imap/src/prompt.test.ts:6, extensions/msteams/src/thread-parent-context.test.ts:26); after this PR that constraint holds in some programs and not others, decided by import graph rather than config.

Since the compiler treats the directive and a lib entry identically, the explicit form is the safer spelling: add "ES2024.String" to lib in tsconfig.json (and tsconfig.core.json, which overrides lib) and drop the directive. target stays es2023, no runtime requirement changes (the package's engines is >=22.19.0; the API shipped in Node 20). If you prefer to keep the directive, a sentence in the body saying it widens the whole core program would keep future readers from assuming it is local.

Verified

  • No declaration leak: built packages/ai with tsdown.ai.config.ts and declarations on — 33 .d.mts files, zero occurrences of reference lib or es2024 in dist/. Matches the body.
  • Timing shape (Node 24.21, 2000 iterations, 64 KiB inputs): CJK 105 → 24 µs, emoji 260 → 17 µs, malformed 326 → 322 µs (unchanged, as expected). ASCII is ~0.1 µs in both paths — V8 short-circuits one-byte strings for the surrogate regex as well as for isWellFormed — so the 6.4% ASCII regression in the body is noise on a ~100 ns operation, not a real cost; I would not list it as a regression.

@steipete
steipete merged commit 0a6ff95 into main Sep 18, 2026
214 checks passed
@steipete
steipete deleted the codex/perf-unicode-wellformed branch September 18, 2026 17:10
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 18, 2026
…49090-prep

* 'main' of https://github.com/openclaw/openclaw: (1719 commits)
  test: remove redundant catalog benchmark gate (#151892)
  improve(ai): speed up Unicode message preparation (#151950)
  improve(logging): reduce filesystem work when polling logs (#151961)
  fix(cron): preserve scheduled work after creator turns end (#151919)
  improve(telegram): avoid rescanning expired rich-text spans (#151965)
  refactor(testing): share plugin assertion file scanner (#151960)
  fix: publish acknowledged managed task receipts (#151590)
  fix(qa): preserve denial warnings during A2A finalization (#150556)
  fix(subagents): clear expired blocks after successful delivery (#151949)
  test: share fresh CLI output fixtures (#151954)
  refactor: reuse channel status preparation (#151906)
  fix(plugins): avoid duplicate initialization and mixed registrations (#151927)
  fix: updates fail for plugins selected from local load paths (#151851)
  fix(msteams): reactions target the current inbound message (#151382)
  fix(state): keep the meeting transcript migration result when stage cleanup fails (#151370)
  improve(gateway): reduce allocations when selecting sessions by store (#151940)
  fix: finish Crabbox wrapper cancellation cleanup (#151862)
  fix(discord): preserve text when replying to bot messages (#151821)
  perf(fleet): run registry operations in SQLite workers (#148290)
  fix: keep I/O responsive across busy agent databases (#151909)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 19, 2026
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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS 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.

2 participants