Skip to content

feat(tokenizer): add an optional Russian lemmatizing tokenizer - #781

Open
BeiMu-new wants to merge 1 commit into
agentscope-ai:mainfrom
BeiMu-new:feat/russian-lemmatization-tokenizer
Open

BeiMu-new wants to merge 1 commit into
agentscope-ai:mainfrom
BeiMu-new:feat/russian-lemmatization-tokenizer

Conversation

@BeiMu-new

Copy link
Copy Markdown
Contributor

What Problem This Solves

Russian keyword search misses related word forms when a note and a query use
different cases or numbers (#754):

note:  использую инструментом каждый день
query: инструмента
       -> no match today

RegexTokenizer splits on word boundaries and leaves inflection untouched, so
инструментом and инструмента become two unrelated index terms.

Change

A russian tokenizer that folds Cyrillic tokens to a shared form.

It extends RegexTokenizer instead of replacing it, so Latin and CJK tokens
keep exactly today's behaviour; only Cyrillic words are normalized.

инструментом -> инструмент      инструмента -> инструмент     MATCH
инструмент   -> инструмент      инструменты -> инструмент     MATCH
документы    -> документ        документом  -> документ       MATCH
системы      -> систем          система     -> систем         MATCH
задача       -> задач           задачи      -> задач          MATCH
работает     -> работа          работать    -> работа         MATCH

Two backends:

backend package size output
snowball (default) snowballstemmer ~0.2 MiB, zero dependencies stem — система → систем
pymorphy3 pymorphy3 + 16 MiB dictionary ~16.1 MiB dictionary form — система → система

Both ship as optional extras, so nothing is installed for users who do not ask
for it: reme-ai[russian] and reme-ai[russian-full]. Selecting a backend
without its extra raises an ImportError naming the install command.

One caveat, stated up front: the default backend returns a stem, not a
dictionary form — система becomes систем, which is not a word. That is fine
for retrieval, but these tokens must not be shown in the UI. If a future feature
highlights the matched original word, it needs the source text, not the token.

Also included: the fingerprint learns about backend

BM25Index._tokenizer_config() builds the fingerprint that names the index
file, and it did not include the tokenizer's backend. A backend changes the
tokens a tokenizer emits, so switching between two backends of the same class
kept reading an index the other backend had built.

backend = getattr(self.tokenizer, "backend", None)
if backend:
    config["backend"] = backend

if backend: rather than is not None is deliberate: BaseComponent defaults
backend to "", so a presence check would append the field for every
tokenizer and rebuild every existing index for no reason.

This changes the index file name for existing jieba users once, because
JiebaTokenizer does declare a backend. They get a single rebuild — the
intended outcome, since jieba and rjieba previously shared one index file
despite emitting different tokens.

Evidence

tests/unit/test_russian_tokenizer.py — 7 passed:

test covers
test_case_forms_fold_to_one_token three case forms collapse to one term
test_note_and_query_share_a_term the exact pair from the report now matches
test_non_cyrillic_tokens_are_untouched Latin and CJK identical to RegexTokenizer
test_tokenize_before_start_falls_back_to_regex no crash before start()
test_unknown_backend_is_rejected a bad backend fails fast
test_fingerprint_tracks_the_backend switching backend changes the config
test_tokenizers_without_a_backend_keep_their_config an empty backend adds nothing

Neighbours — test_tokenizer.py, test_keyword_index.py,
test_bm25_live_length.py, test_keyword_upsert_delta.py: 80 passed.

Falsification: replacing if backend: with if False: turns
test_fingerprint_tracks_the_backend red; restoring returns it to green.

pre-commit run --files over the five touched files: all hooks pass.

Not verified

  • The pymorphy3 backend is implemented, but its tests are skipped here because
    the 16 MiB dictionary is not installed in this environment. That path was not
    exercised end to end.
  • Full suite and integration tests were not run.

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@ployts ployts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Found three reproducible issues: the registered Russian tokenizer cannot be constructed through application configuration, the fingerprint change also invalidates default Regex indexes, and normalization bypasses custom Russian stopwords. Details and suggested fixes are attached inline.

Validation on b02a177: the focused existing tokenizer/BM25/keyword-update tests produced 78 passed and 2 skipped. Additional isolated regression checks reproduced all three issues, including stopword filtering with both Snowball and pymorphy3. Basic tokenization smoke checks passed for both backends. Full suite, integration tests, and lint were not run.

def __init__(self, backend: str = "snowball", **kwargs):
super().__init__(**kwargs)
backend = (backend or "snowball").strip().lower()
if backend not in self.SUPPORTED_BACKENDS:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P1] Separate the normalization engine from the component registry backend

Application._instantiate() selects the class using cfg.backend and then forwards the complete cfg.model_dump() to its constructor. Consequently, configuring components.tokenizer.default.backend=russian calls RussianTokenizer(backend="russian"), which raises ValueError: Unsupported Russian tokenizer backend: 'russian'. Setting it to snowball or pymorphy3 instead fails registry lookup, so neither engine is reachable through the normal application configuration path. Please give the normalization engine a separate option while preserving the registry backend, and add an application-level configuration test; the current tests only instantiate the tokenizer directly.

# defaults `backend` to "", and an empty value must not alter the
# fingerprint of tokenizers that never had a backend.
backend = getattr(self.tokenizer, "backend", None)
if backend:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] Preserve the existing fingerprint for configured Regex tokenizers

Application-created RegexTokenizer instances receive backend="regex" from Application._instantiate(), so this condition is true for the default deployment too. I reproduced the default fingerprint changing from 7748e1d5a050 to 004adcb94b66, even though its token output is unchanged. The persisted index is therefore missed and LocalFileStore._sync_keyword_index_from_chunks() performs a full synchronous rebuild at startup. This affects default Regex users, beyond the intended Jieba/backend migration. Please distinguish token-output engine settings from registry-only backend values and cover an application-created Regex tokenizer; the new standalone test has an empty backend and misses this path.

if self._normalize is None:
# Not started yet: behave like the plain regex tokenizer.
return tokens
return [self._normalize(token.lower()) if self.CYRILLIC_PATTERN.search(token) else token for token in tokens]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] Keep custom stopwords in the same representation as filtered tokens

BaseTokenizer.tokenize() runs _postprocess() after _tokenize_one(), while the loaded stopword set contains the original lowercased words. Normalizing here means an exact custom stopword can survive filtering: with a stopword file containing машины, tokenizing машины returns ['машин'] under Snowball and ['машина'] under pymorphy3, whereas Regex correctly returns []. I reproduced this with both real backends and the default filter_stopwords=True. Please filter original tokens before normalization or normalize the stopword set consistently, and add coverage with filtering enabled.

@BeiMu-new
BeiMu-new force-pushed the feat/russian-lemmatization-tokenizer branch from b02a177 to ad12cc7 Compare November 26, 2026 04:06
@BeiMu-new

Copy link
Copy Markdown
Contributor Author

@ployts All three addressed in ad12cc73.

1. [P1] The normalization engine is now a separate option

backend stays the registry key, so it remains russian and Application._instantiate() still resolves the class with it. The folding implementation moved to engine:

def __init__(self, backend: str = "russian", engine: str = "snowball", **kwargs):
    super().__init__(backend=backend, **kwargs)

ComponentConfig allows extra fields, so engine travels through model_dump() alongside the registry key. A configuration test now walks the same two steps the application does — look the class up by cfg.backend, then construct from cfg.model_dump() — instead of instantiating the tokenizer directly. Reverting to the previous signature fails exactly as you described:

ValueError: Unsupported Russian tokenizer engine: 'russian'. Expected one of ('snowball', 'pymorphy3').

2. [P2] A plain Regex tokenizer keeps its fingerprint

The fingerprint no longer reads backend. BaseTokenizer gained token_output_engine, which defaults to None; tokenizers whose tokens depend on a selectable implementation report it themselves — JiebaTokenizer returns its jieba/rjieba choice, RussianTokenizer returns engine. _tokenizer_config() reads that property, so a Regex tokenizer contributes the same three keys as before: class, filter_stopwords, stopwords_sha256.

Two notes on verification:

  • The test asserts the key set rather than a literal digest, because stopwords_sha256 is part of the payload and differs per checkout. On this machine the untouched payload hashes to 70d42d4264ea; the value itself was never the point, the key set was.
  • A second test shows the failure directly: adding backend to that payload moves the digest. That is the change you reproduced, and it is now covered rather than assumed.

3. [P2] Stopwords are folded with the same engine

_start folds the loaded stopword set once the engine is resolved, so _postprocess compares folded tokens against folded stopwords. машины in the file now filters машины from the text:

if self._stopwords:
    self._stopwords = {self._fold(word) for word in self._stopwords}

Reverting that block leaves ['машин'] in the output, matching your reproduction. There is a pymorphy3 variant of the same test; it skips here because the 16 MiB dictionary is not installed in this environment, so that engine's path is covered by the test but not executed locally.

Test scope

  • target: tests/unit/test_russian_tokenizer.py — 12 passed, 1 skipped
  • adjacent: tests/unit -k "tokenizer or keyword or bm25" — 132 passed, 1 skipped
  • pre-commit run --files on the five changed files — every hook passed

@BeiMu-new

Copy link
Copy Markdown
Contributor Author

The only failing job is Unit Tests - py3.12, with a single test:

1 failed, 5670 passed, 53 skipped in 366.12s
FAILED tests/unit/test_cc_active_sessions.py::test_concurrent_append_batches_wait_for_previous_native_persistence

That test drives concurrent append batching in the Claude Code session store. Nothing in this PR touches it — the change is confined to the tokenizer and the keyword index (russian_tokenizer.py, base_tokenizer.py, jieba_tokenizer.py, bm25_index.py, plus one test file).

Three reasons to read it as a flake rather than a regression:

  • the same commit passes Unit Tests - py3.11, py3.13 and py3.14
  • running that single test locally passes (1 passed)
  • the name says what it does: it waits on concurrent persistence, which is exactly the shape that goes timing-sensitive on a loaded runner

Would someone rerun the py3.12 job when convenient?

@ployts ployts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-reviewed ad12cc7. All three findings from the previous review are fixed: application configuration can construct and start both Russian engines, the configured Regex tokenizer retains its original fingerprint, and custom Russian stopwords are filtered with both engines.

One new regression remains: _fold() now lowercases non-Cyrillic tokens even when the caller explicitly requests lower=False. Details and the reproduction are attached inline.

Validation: focused tokenizer/BM25/keyword-update/component-registry/base-component tests produced 128 passed and 2 skipped (optional faiss/zvec dependencies are absent). Independent checks for the previous fixes passed; the new case-preservation regression test failed with both real engines. The same input passed on the previous PR revision. Full suite, integration tests, and lint were not run.

Comment on lines +93 to +95
lowered = token.lower()
if self._normalize is None or not self.CYRILLIC_PATTERN.search(lowered):
return lowered

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P2] Preserve non-Cyrillic tokens when lower=False

_fold() now lowercases every token before checking whether it contains Cyrillic characters, so the inherited lower=False option no longer preserves Latin token casing. After starting RussianTokenizer(filter_stopwords=False), tokenize(["Python OpenAI"], lower=False) returns [["python", "openai"]]; both RegexTokenizer and the previous PR revision return [["Python", "OpenAI"]]. I reproduced this with both Snowball and pymorphy3. This breaks the public lower option and the promised unchanged behavior for non-Cyrillic text. Please return the original token in the non-Cyrillic branch and leave optional lowercasing to BaseTokenizer._postprocess(); add a regression test with lower=False for both engines.

Russian keyword search misses related word forms when a note and a query use
different cases or numbers: a note containing "инструментом" does not match a
query for "инструмента". Add a `russian` tokenizer that folds Cyrillic tokens
to a shared form, so note and query land on the same index term.

It extends RegexTokenizer rather than replacing it, so Latin and CJK tokens
behave exactly as before; only Cyrillic words are normalized. Two backends:

- snowball (default): the Snowball stemmer. A pure algorithm with no
  dictionaries, about 0.2 MiB. It returns a *stem*, not a dictionary form --
  "система" becomes "систем". That is sufficient for retrieval, but the stem is
  not a real word and must not be shown to users.
- pymorphy3: a morphological analyzer returning the dictionary form, at the
  cost of a 16 MiB Russian dictionary.

Both are optional extras (`reme-ai[russian]` and `reme-ai[russian-full]`), and
the tokenizer raises an actionable ImportError when the chosen backend is not
installed.

Also include `backend` in the BM25 tokenizer fingerprint. A backend changes the
tokens a tokenizer emits, so without it, switching between two backends of the
same class keeps reading an index the other backend built. The field is only
added when the tokenizer declares a non-empty backend: BaseComponent defaults
`backend` to "", which must not perturb the fingerprint of tokenizers that
never had one.

Note for existing jieba users: their index file name changes once, because
JiebaTokenizer does declare a backend. That triggers a single rebuild, which is
the intended effect -- rjieba and jieba previously shared one index file.

Refs agentscope-ai#754
@BeiMu-new
BeiMu-new force-pushed the feat/russian-lemmatization-tokenizer branch from ad12cc7 to 7ec24fc Compare November 27, 2026 06:45
@BeiMu-new

Copy link
Copy Markdown
Contributor Author

@ployts Fixed in 7ec24fc7.

1. [P2] lower=False keeps non-Cyrillic casing

_fold() no longer lowercases before the Cyrillic check. The non-Cyrillic branch returns the token as it arrived, so the caller's choice is applied once, in BaseTokenizer._postprocess(). Cyrillic tokens are still folded — that is the tokenizer's job, and folding implies the lowered form.

Reverting only that branch reproduces your report on both engines:

FAILED test_non_cyrillic_tokens_keep_their_case_when_lower_is_false
E       AssertionError: case was not preserved: ['python', 'openai']
E       assert ['python', 'openai'] == ['Python', 'OpenAI']

FAILED test_pymorphy3_keeps_non_cyrillic_case_when_lower_is_false
E       AssertionError: case was not preserved: ['python', 'openai']
E       assert ['python', 'openai'] == ['Python', 'OpenAI']

With the fix, tokenize(["Python OpenAI"], lower=False) returns [["Python", "OpenAI"]] on both engines.

2. Regression tests for both engines

test_non_cyrillic_tokens_keep_their_case_when_lower_is_false (snowball) and test_pymorphy3_keeps_non_cyrillic_case_when_lower_is_false (pymorphy3). I installed pymorphy3 locally this time, so the earlier importorskip skips for that engine actually ran.

Verification

  • target tests/unit/test_russian_tokenizer.py: 15 passed, 0 skipped (was 13 passed / 2 skipped while pymorphy3 was absent)
  • adjacent tests/unit -k "tokenizer or keyword or bm25": 135 passed (ignored tests/unit/test_codex_plugin_mcp.py, which fails collection here on from mcp.shared.exceptions import MCPError — the installed mcp exposes McpError; unrelated to this diff)
  • pre-commit run --files on both files: 12 hooks passed
  • diff: 7 files, +395/−0, still a single commit

On your note about the previous CI run: the only red job was Unit Tests - py3.12, failing test_cc_active_sessions.py::test_concurrent_append_batches_wait_for_previous_native_persistence — the same timeout flake that showed up on #748.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants