Repository navigation
improve(ai): speed up Unicode message preparation - #151950
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed September 18, 2026, 1:02 PM ET / 17:02 UTC (Revision 2). ClawSweeper reviewWhat this changesSkip 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 Review scores
Verification
How this fits togetherThe 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
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +5. Total +5 across 1 file. View PR surface stats
Review metrics
Technical reviewBest 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. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
Yigtwxx
left a comment
There was a problem hiding this comment.
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/aiwithtsdown.ai.config.tsand declarations on — 33.d.mtsfiles, zero occurrences ofreference libores2024indist/. 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.
|
Merged via squash.
|
…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) ...
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.
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.
git diff --checkpassed; formatted source is identical to the measured candidate.