Skip to content

Commit 75fcae7

Browse files
committed
fix(service-segmenter): one jieba per process, stop words compared whole, supplied words in any script
Claude-Session: https://claude.ai/code/session_01RKKVnjzReaqV9utX3JueMS Co-authored-by: Claude <noreply@anthropic.com>
1 parent c1c202d commit 75fcae7

11 files changed

Lines changed: 323 additions & 190 deletions

File tree

‎.changeset/38710-service-segmenter.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ feat(service-segmenter): a segmenter service that cuts a Chinese question into r
99
Clause-②: yes
1010
Metadata-protocol: none
1111

12-
New package `@objectstack/service-segmenter`: `SegmenterServicePlugin` registers `ISegmenterService` under the `segmenter` slot. `keywordTerms(query, { purpose, entries })` answers a question's keyword terms in the shape the knowledge adapters' terms have today (distinct, at most 16). A run of Han characters is cut by `@node-rs/jieba` (HMM off, an optional dependency, loaded once per process) after a longest-match pass that keeps the platform's words (年假, 脱密, 应急采购, 超预算, …) and the caller's `word` entries whole; stop words are dropped and adjacent single characters are joined into two-character words. The query is NFKC-normalised first, a Thai, Lao, Khmer or Myanmar run is cut by `Intl.Segmenter`, and everything else (English, figures, codes, kana and Hangul runs) is cut exactly as before. Without jieba (not installed, or failed to load: the boot log names which, and `status()` reports it), the service answers by sliding windows with the layered words still kept whole. The purpose `record_search` is reserved and refused with `NOT_IMPLEMENTED`.
12+
New package `@objectstack/service-segmenter`: `SegmenterServicePlugin` registers `ISegmenterService` under the `segmenter` slot. `keywordTerms(query, { purpose, entries })` answers a question's keyword terms in the shape the knowledge adapters' terms have today (distinct, at most 16). The caller's `word` entries are kept whole wherever the question spells them, in any script. A run of Han characters is cut by `@node-rs/jieba` (HMM off, an optional dependency, one instance per process) with the platform's words (年假, 脱密, 应急采购, 超预算, …) in its dictionary; a word equal to a stop word is dropped, and adjacent single characters are joined into two-character words. The query is NFKC-normalised first, a Thai, Lao, Khmer or Myanmar run is cut by `Intl.Segmenter`, and everything else (English, figures, codes, kana and Hangul runs) is cut exactly as before. Without jieba (not installed, or failed to load: the boot log names which, and `status()` reports it), the service answers by sliding windows with the supplied words still kept whole. The purpose `record_search` is reserved and refused with `NOT_IMPLEMENTED`.
1313

1414
Nothing calls the service yet: the knowledge adapters keep their own terms until they read the slot.
1515

‎packages/core/src/keyword-terms.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,6 @@ describe('keywordTerms (sliding windows)', () => {
6767

6868
it('splits with the same class as the libSQL and PostgreSQL stores', () => {
6969
// Both stores' tests pin the same literal against their own classes: keep the three pins, and so the three classes, identical.
70-
expect(KEYWORD_SEPARATORS).toEqual(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%& -〄〈-〠〪-〰〶〷〽-〿!-/:-@[-`{-・‘-‟…]+/u);
70+
expect(KEYWORD_SEPARATORS).toEqual(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u3004\u3008-\u3020\u302a-\u3030\u3036\u3037\u303d-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u);
7171
});
7272
});

‎packages/core/src/keyword-terms.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ export const MAX_KEYWORD_TERMS = 16;
3232
* 々 (U+3005), 〆 (U+3006) and 〇 (U+3007), named whatever their script (〆
3333
* belongs to none).
3434
*/
35-
export const UNSEGMENTED_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}々-〇ーー]+/gu;
35+
export const UNSEGMENTED_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u3005-\u3007\u30fc\uff70]+/gu;
3636

3737
/**
3838
* Where the keyword leg splits a query into terms: white space, punctuation
@@ -44,7 +44,7 @@ export const UNSEGMENTED_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Kata
4444
* repeat marks 〱–〵, 〼 and the Hangzhou numerals 〡–〩 and 〸–〺.
4545
* The same class as the libSQL and PostgreSQL stores'.
4646
*/
47-
export const KEYWORD_SEPARATORS = /[\s,;:!?()[\]{}<>"'`|\\=*~^$%& -〄〈-〠〪-〰〶〷〽-〿!-/:-@[-`{-・‘-‟…]+/u;
47+
export const KEYWORD_SEPARATORS = /[\s,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u3004\u3008-\u3020\u302a-\u3030\u3036\u3037\u303d-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u;
4848

4949
/**
5050
* The terms of a query for the keyword leg: split at white space and at

‎packages/services/service-segmenter/README.md‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ pnpm add @objectstack/service-segmenter
1717

1818
`@node-rs/jieba` is an optional dependency with prebuilt binaries (Linux glibc and musl, macOS,
1919
Windows). Without it, or when it fails to load, the service still registers and answers by the
20-
sliding windows of `keywordTerms` from `@objectstack/core`, with the platform words and supplied
21-
words still kept whole. The boot log says which, and tells "not installed" apart from "failed to
20+
sliding windows of `keywordTerms` from `@objectstack/core`, with the supplied words still kept
21+
whole. The boot log says which, and tells "not installed" apart from "failed to
2222
load".
2323

2424
## Usage
@@ -40,17 +40,21 @@ segmenter.status(); // { engine: 'dictionary', segmenter: 'jieba', purposes: ['k
4040

4141
## The rule (purpose `knowledge`)
4242

43-
1. NFKC normalisation: fullwidth letters and digits fold to ASCII.
44-
2. A run of Han characters: the layered words are matched first, by longest match (a word is kept
45-
whole, a stop word of two or more characters is dropped); the rest is cut by jieba, stop words
46-
dropped, and adjacent single characters joined into words of two (年|假 → 年假).
47-
3. A run of Thai, Lao, Khmer or Myanmar: cut by `Intl.Segmenter`.
48-
4. Everything else — English words, figures, document numbers, codes, and runs holding kana or
43+
1. NFKC normalisation between separators: fullwidth letters and digits fold to ASCII.
44+
2. The supplied `word` entries are taken out of the whole question by longest match, in any script
45+
(明规条款, `OA审批`, `5G套餐`), and kept whole.
46+
3. A run of Han characters: cut by one process-wide jieba instance, with the platform words in its
47+
dictionary. Words equal to a stop word are dropped (compared whole, so 还是 never eats 归还), and
48+
adjacent single characters are joined into words of two (年|假 → 年假). Without jieba, the stop
49+
words of two characters or more are taken out of the run and the rest is windowed.
50+
4. A run of Thai, Lao, Khmer or Myanmar: cut by `Intl.Segmenter`.
51+
5. Everything else — English words, figures, document numbers, codes, and runs holding kana or
4952
Hangul — exactly as `keywordTerms` from `@objectstack/core` cuts it.
5053

5154
Two layers of words, the later one winning for a term: the platform's (`PLATFORM_WORDS`,
52-
`PLATFORM_STOP_WORDS`), then the `entries` the caller passes. An entry with `enabled: false`
53-
withdraws a platform word or stop word. The purpose `record_search` is reserved and refused with
55+
`PLATFORM_STOP_WORDS`), then the `entries` the caller passes, read afresh on every call. An entry
56+
with `enabled: false` withdraws a platform stop word or an earlier entry; the platform words live in
57+
jieba's dictionary and are not withdrawn. The purpose `record_search` is reserved and refused with
5458
`NOT_IMPLEMENTED`.
5559

5660
## Exports

‎packages/services/service-segmenter/src/jieba-loader.ts‎

Lines changed: 54 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
22

33
import type { SegmenterFallbackReason } from '@objectstack/spec/contracts';
4+
import { PLATFORM_WORDS } from './platform-words.js';
45

56
/** The part of a dictionary segmenter the service calls: a cut with the HMM off. */
67
export interface DictionarySegmenter {
@@ -28,6 +29,7 @@ export type JiebaCutMode = 'cut' | 'cutForSearch';
2829
export const JIEBA_CUT_MODE: JiebaCutMode = 'cut';
2930

3031
interface JiebaInstance {
32+
loadDict(dict: Uint8Array): void;
3133
cut(sentence: string, hmm?: boolean): string[];
3234
cutForSearch(sentence: string, hmm?: boolean): string[];
3335
}
@@ -62,24 +64,60 @@ function cjsExports<T>(mod: unknown): T {
6264
}
6365

6466
/**
65-
* Load `@node-rs/jieba` with its default dictionary, once: one read-only
66-
* instance for the process, with the HMM off (it guesses words a dictionary
67-
* does not hold, and invents some, such as 能付 and 黑后).
67+
* The frequency each platform word is added to jieba's dictionary with: high
68+
* enough that jieba keeps the word whole where the question holds it (一年有几天
69+
* 年假 → 年假), low enough that a likelier split across it still wins (去年假期 →
70+
* 去年 | 假期, never 去 | 年假 | 期). Measured on both kinds of sentence: 10
71+
* splits 年假, and every value from 100 to 10000 cuts both as above.
72+
*/
73+
export const PLATFORM_WORD_FREQUENCY = 1000;
74+
75+
/**
76+
* The one load of jieba in this process, shared by every loader and every
77+
* service built on it: one read-only instance, with its default dictionary and
78+
* the platform words. A load that failed is not retried either.
79+
*/
80+
let processJieba: Promise<{ ok: true; jieba: JiebaInstance } | { ok: false; reason: SegmenterFallbackReason; error: string }> | undefined;
81+
82+
async function loadProcessJieba(): Promise<{ ok: true; jieba: JiebaInstance } | { ok: false; reason: SegmenterFallbackReason; error: string }> {
83+
try {
84+
const { Jieba } = cjsExports<JiebaModule>(await import('@node-rs/jieba'));
85+
const { dict } = cjsExports<JiebaDictModule>(await import('@node-rs/jieba/dict.js'));
86+
const jieba = Jieba.withDict(dict);
87+
jieba.loadDict(new TextEncoder().encode(PLATFORM_WORDS.map((w) => `${w} ${PLATFORM_WORD_FREQUENCY}`).join('\n')));
88+
return { ok: true, jieba };
89+
} catch (e) {
90+
return {
91+
ok: false,
92+
reason: isNotInstalled(e) ? 'not_installed' : 'load_failed',
93+
error: e instanceof Error ? e.message : String(e),
94+
};
95+
}
96+
}
97+
98+
/** The segmenter of each cut mode, built once over the process's one jieba. */
99+
const segmenters = new Map<JiebaCutMode, Promise<SegmenterLoad>>();
100+
101+
/**
102+
* Load `@node-rs/jieba` with its default dictionary and the platform words
103+
* ({@link PLATFORM_WORDS}), once per process: one read-only instance, with the
104+
* HMM off (it guesses words a dictionary does not hold, and invents some, such
105+
* as 能付 and 黑后). Every call of every loader answers the same segmenter for
106+
* a cut mode, and the two cut modes share the one instance.
68107
*/
69108
export function jiebaLoader(mode: JiebaCutMode = JIEBA_CUT_MODE): SegmenterLoader {
70-
return async () => {
71-
try {
72-
const { Jieba } = cjsExports<JiebaModule>(await import('@node-rs/jieba'));
73-
const { dict } = cjsExports<JiebaDictModule>(await import('@node-rs/jieba/dict.js'));
74-
const jieba = Jieba.withDict(dict);
75-
const cut = mode === 'cut' ? (text: string) => jieba.cut(text, false) : (text: string) => jieba.cutForSearch(text, false);
76-
return { ok: true, segmenter: { name: 'jieba', cut } };
77-
} catch (e) {
78-
return {
79-
ok: false,
80-
reason: isNotInstalled(e) ? 'not_installed' : 'load_failed',
81-
error: e instanceof Error ? e.message : String(e),
82-
};
109+
return () => {
110+
let load = segmenters.get(mode);
111+
if (!load) {
112+
processJieba ??= loadProcessJieba();
113+
load = processJieba.then((loaded): SegmenterLoad => {
114+
if (!loaded.ok) return loaded;
115+
const { jieba } = loaded;
116+
const cut = mode === 'cut' ? (text: string) => jieba.cut(text, false) : (text: string) => jieba.cutForSearch(text, false);
117+
return { ok: true, segmenter: Object.freeze({ name: 'jieba', cut }) };
118+
});
119+
segmenters.set(mode, load);
83120
}
121+
return load;
84122
};
85123
}

‎packages/services/service-segmenter/src/platform-words.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,11 @@
99
/**
1010
* Words kept whole, never cut: the terms of everyday policy text (leave,
1111
* expenses, procurement, confidentiality) that the segmenter's own dictionary
12-
* splits, or that a question names in a form it does not hold. Each is matched
13-
* by longest match before the segmenter runs, so it is kept whole on the
14-
* sliding-window fallback too.
12+
* splits, or that a question names in a form it does not hold. They are added
13+
* to jieba's own dictionary (`PLATFORM_WORD_FREQUENCY`), so jieba weighs them
14+
* against the words around them: 一年有几天年假 keeps 年假, while 去年假期 still
15+
* cuts 去年 | 假期. On the sliding-window fallback they are windowed like any
16+
* other text.
1517
*/
1618
export const PLATFORM_WORDS: readonly string[] = Object.freeze([
1719
// Leave and attendance
@@ -27,9 +29,11 @@ export const PLATFORM_WORDS: readonly string[] = Object.freeze([
2729
/**
2830
* Words dropped from every answer: the function words and question words of
2931
* a colloquial question, which nearly every passage holds or none answers
30-
* with. A word of one character is dropped before adjacent single characters
31-
* are joined; a longer one is also matched before the segmenter runs, so it
32-
* is dropped on the sliding-window fallback too.
32+
* with. A segmenter word equal to one is dropped, compared whole, so a stop
33+
* word never removes part of a word (还是 does not touch 归还 in 归还是否); a
34+
* word of one character is dropped before adjacent single characters are
35+
* joined. On the sliding-window fallback, the stop words of two characters or
36+
* more are also taken out of a Han run before the windows run.
3337
*/
3438
export const PLATFORM_STOP_WORDS: readonly string[] = Object.freeze([
3539
// One character

‎packages/services/service-segmenter/src/segmenter-service-plugin.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ export interface SegmenterServicePluginOptions {
1717
* It loads its dictionary segmenter once, in init, and never retries: the
1818
* boot log says which segmentation the process runs, and `status()` answers
1919
* the same for its life. Without the segmenter the service still registers
20-
* and answers by sliding windows, with the layered words still kept whole; the
20+
* and answers by sliding windows, with supplied words still kept whole; the
2121
* log tells "not installed" (install the optional `@node-rs/jieba`) apart
2222
* from "failed to load" (its error is named).
2323
*
@@ -46,13 +46,13 @@ export class SegmenterServicePlugin implements Plugin {
4646
} else if (status.fallbackReason === 'not_installed') {
4747
ctx.logger.warn(
4848
'SegmenterServicePlugin: @node-rs/jieba is not installed, so Han text is cut by sliding windows ' +
49-
'(supplied and platform words are still kept whole). Install the optional dependency @node-rs/jieba ' +
49+
'(supplied words are still kept whole). Install the optional dependency @node-rs/jieba ' +
5050
'to cut it into dictionary words.',
5151
);
5252
} else {
5353
ctx.logger.warn(
5454
`SegmenterServicePlugin: @node-rs/jieba is installed but failed to load (${status.error}), so Han text is ` +
55-
'cut by sliding windows (supplied and platform words are still kept whole). Check that the prebuilt ' +
55+
'cut by sliding windows (supplied words are still kept whole). Check that the prebuilt ' +
5656
'binary for this platform was installed.',
5757
);
5858
}

0 commit comments

Comments
 (0)