Skip to content

fix(memory): Unicode support for MMR and FTS tokenizers - #38945

Closed
jarimustonen wants to merge 3 commits into
openclaw:mainfrom
jarimustonen:fix/memory-unicode-tokenization
Closed

jarimustonen wants to merge 3 commits into
openclaw:mainfrom
jarimustonen:fix/memory-unicode-tokenization

Conversation

@jarimustonen

Copy link
Copy Markdown
Contributor

Summary

  • Problem: MMR tokenizer (src/memory/mmr.ts) used /[a-z0-9_]+/g, dropping all non-ASCII characters. Non-English memory snippets got empty token sets, making Jaccard similarity return 1.0 (identical) for all of them. This caused MMR diversity re-ranking to actively penalize non-English results as "duplicates". FTS tokenizer (src/memory/hybrid.ts) was missing \p{M} (combining marks), splitting Thai/Hindi/Arabic words at tone marks and virama.
  • Why it matters: Memory search and diversity ranking were broken for all non-English users. FTS queries with combining mark scripts produced fragmented tokens that wouldn't match stored content.
  • What changed: Both tokenizers now use [\p{L}\p{M}\p{N}_]+ with the u flag and NFC normalization. \p{L} = letters, \p{M} = combining marks (Thai tone marks, Devanagari virama, Arabic diacritics), \p{N} = numbers. NFC normalization prevents NFD/NFC mismatches (e.g. macOS filesystem returns NFD paths).
  • What did NOT change (scope boundary): No changes to query-expansion tokenizer, memory storage format, or MMR algorithm logic. Only the regex patterns and normalization.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

  • Related: query-expansion tokenizer in src/memory/query-expansion.ts already uses Unicode-aware patterns; this aligns the remaining two tokenizers.

User-visible / Behavior Changes

  • Memory search results may change order for non-English users (improvement: queries now actually match non-ASCII content)
  • MMR diversity re-ranking now works correctly for non-English memory snippets (previously treated all as identical)
  • English-language behavior is unchanged

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No
  • Command/tool execution surface changed? No
  • Data access scope changed? No

Repro + Verification

Environment

  • OS: macOS
  • Runtime: Node 24
  • Relevant config: default memory configuration

Steps

  1. Store memories containing non-ASCII text (e.g. Finnish "päätös", "aikavyöhyke")
  2. Query memory using those non-ASCII terms
  3. Observe search results

Expected

  • Non-ASCII queries match stored memories correctly
  • MMR re-ranking produces diverse results across languages

Actual (before fix)

  • MMR tokenizer returned empty sets for non-English → all treated as duplicates
  • FTS tokenizer split Thai/Hindi words at combining marks → no matches

Evidence

  • Failing test/log before + passing after
  • 30 unit tests covering: English, Finnish, French, Chinese, Japanese, Korean, Russian, Arabic, Hebrew, Thai, Hindi, NFC normalization
  • All tests pass

Human Verification (required)

  • Verified scenarios: I have tested that a) memory continues to work and b) enables memory queries with non-latin characters. I did not check other languages than my native Finnish in which I do have a memory in OpenClaw.
  • Edge cases checked: I did not figure out any edge cases that would require checking.
  • What I did not verify: CJK languages, Arabic, Hebrew, Thai, Hindi in live environment (covered by unit tests only).

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No
  • Migration needed? No

Failure Recovery (if this breaks)

  • How to disable/revert this change quickly: revert both commits; tokenizer changes are isolated to two functions
  • Files/config to restore: src/memory/mmr.ts, src/memory/hybrid.ts
  • Known bad symptoms reviewers should watch for: memory search returning no results, or unexpected results for English queries

Risks and Mitigations

  • Risk: FTS query tokenization change affects all users (not opt-in like MMR)
    • Mitigation: The change is additive — \p{M} only affects scripts that use combining marks; \p{L}\p{N} behavior unchanged. NFC normalization is idempotent for already-NFC text.

@greptile-apps

greptile-apps Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes Unicode handling in two memory search tokenizers — src/memory/mmr.ts and src/memory/hybrid.ts — by upgrading the regex patterns from ASCII-only or \p{M}-missing variants to the correct [\p{L}\p{M}\p{N}_]+ with the u flag and NFC normalization, resolving broken memory search and MMR diversity re-ranking for all non-English users.

Key changes:

  • mmr.ts tokenize(): replaces /[a-z0-9_]+/g with /[\p{L}\p{M}\p{N}_]+/gu and adds .normalize("NFC"). Before this fix, any non-ASCII snippet produced an empty token set, causing Jaccard similarity to return 1.0 between all non-English snippets and actively penalizing them as duplicates during MMR re-ranking.
  • hybrid.ts buildFtsQuery(): adds \p{M} and .normalize("NFC"). Without \p{M}, Thai tone marks, Devanagari virama, and Arabic diacritics acted as token delimiters, fragmenting words mid-character and breaking FTS queries for those scripts.
  • Both changes are additive and backward-compatible: English/ASCII behavior is unchanged.
  • 30 new unit tests cover English, Finnish, French, Chinese, Japanese, Korean, Russian, Arabic, Hebrew, Thai, Hindi, and NFC normalization round-trips.

Minor note: In mmr.ts, .toLowerCase() is called before .normalize("NFC"). While this produces correct results for all known real-world scripts, the Unicode-recommended order is normalize first, then case-fold — and hybrid.ts already follows that convention. Consider swapping the order for consistency and future-proofing.

Confidence Score: 4/5

  • Safe to merge — changes are isolated, additive, and well-tested; no English/ASCII behavior is affected.
  • The fix is conceptually correct and well-supported by 30 targeted unit tests covering a wide range of scripts. The scope is strictly limited to two tokenizer functions. The only minor concern is the toLowerCase().normalize("NFC") ordering in mmr.ts, which is the inverse of Unicode best-practice order (normalize before fold) and inconsistent with hybrid.ts. This has no practical impact on any known input but is worth tidying up.
  • src/memory/mmr.ts line 37: normalization order (toLowerCase() before normalize("NFC")) should ideally be swapped to align with Unicode best practices and the style used in hybrid.ts.

Last reviewed commit: 0826768

Comment thread src/memory/mmr.ts Resolved
The MMR tokenizer used /[a-z0-9_]+/g which dropped all non-ASCII
characters, causing Jaccard similarity to treat all non-English
snippets as identical (empty token sets → similarity 1.0). This made
MMR diversity re-ranking actively harmful for non-English users.

Replace with /[\p{L}\p{M}\p{N}_]+/gu to support all Unicode scripts
including combining marks (Thai tone marks, Devanagari virama, Arabic
diacritics). Add NFC normalization to prevent NFD/NFC mismatches.

Add test cases for Finnish, French, Chinese, Japanese, Korean, Russian,
Arabic, Hebrew, Thai, Hindi, and NFC normalization.
…okenizer

buildFtsQuery used /[\p{L}\p{N}_]+/gu which missed \p{M} (combining
marks), splitting Thai/Hindi/Arabic words at tone marks and virama.
Add \p{M} and .normalize("NFC") for consistent tokenization across
Unicode normalization forms.
Swap toLowerCase().normalize("NFC") → normalize("NFC").toLowerCase()
to follow Unicode best-practice order (normalize before fold) and
align with the style used in hybrid.ts.
@jarimustonen
jarimustonen force-pushed the fix/memory-unicode-tokenization branch from 439fb7c to 7398a23 Compare March 18, 2026 08:32
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Apr 22, 2026
@clawsweeper

clawsweeper Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Keep open: the Unicode/NFC bug direction is still valid, but this PR is not merge-ready because it edits stale src/memory files, misses active extensions/memory-core tokenizers, would need to preserve shipped CJK MMR behavior, and lacks artifact-backed real behavior proof.

Canonical path: Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review.

So I’m closing this here because the remaining work is already tracked in the canonical issue.

Review details

Best possible solution:

Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review.

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

Yes, at source level. Current main still omits \p{M}/NFC in active FTS token regexes, and active MMR still does not tokenize non-CJK Unicode words correctly; I did not run a persisted memory-search flow in this read-only review.

Is this the best way to solve the issue?

No. The Unicode/NFC direction is right, but this branch targets stale files and needs a memory-core port that extends, rather than replaces, the current CJK tokenizer contract.

Security review:

Security review cleared: No concrete security or supply-chain concern found; the PR only changes tokenizer logic and colocated tests.

What I checked:

  • stale F-rated PR: PR was opened 2026-03-07T15:07:14Z, is older than 60 days, and the latest review rated it F.
  • proof blocker: real behavior proof is missing and proof tier is F, so this branch is not merge-ready without contributor follow-up.
  • no human follow-up: live comments and timeline hydrated by apply contain no non-automation activity after the ClawSweeper review.

Likely related people:

  • buyitsydney: Authored the merged CJK/Kana/Hangul MMR tokenization behavior and tests that a Unicode tokenizer port must preserve. (role: CJK MMR behavior contributor; confidence: high; commits: 4b69c6d3f169, 921bb89b1a65; files: extensions/memory-core/src/memory/mmr.ts, extensions/memory-core/src/memory/mmr.test.ts)
  • Takhoffman: Authored the merged configurable FTS5 tokenizer and CJK trigram search-planning work in the active memory-core search path. (role: recent FTS search-planning contributor; confidence: high; commits: 3ce48aff660a; files: extensions/memory-core/src/memory/manager-search.ts, extensions/memory-core/src/memory/manager-search.test.ts, src/agents/memory-search.ts)
  • steipete: Moved the memory engine into the memory-core plugin and later touched shared lowercase helper usage around the active memory files. (role: recent memory-core refactor contributor; confidence: high; commits: cad83db8b2f7, dffa88f39615; files: extensions/memory-core/src/memory/hybrid.ts, extensions/memory-core/src/memory/mmr.ts, extensions/memory-core/src/memory/manager-search.ts)
  • vignesh07: Authored the earlier Unicode letter/number FTS query tokenizer change that this PR extends with combining marks and normalization. (role: query tokenizer history contributor; confidence: medium; commits: 501e89367602; files: src/memory/hybrid.ts, src/memory/hybrid.test.ts)

Codex review notes: model gpt-5.5, reasoning high; reviewed against 9ff1a4371f68.

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Apr 26, 2026
@clawsweeper clawsweeper Bot added the P2 Normal backlog priority with limited blast radius. label May 16, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 16, 2026
@clawsweeper clawsweeper Bot added impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. 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. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. and removed impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. labels May 17, 2026
@clawsweeper

clawsweeper Bot commented May 19, 2026 •

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@clawsweeper

clawsweeper Bot commented May 23, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

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. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant