Repository navigation
Commit 430bbbf
fix(knowledge): the keyword leg ranks unspaced Chinese, Japanese and Korean questions by 2- and 3-character pieces (#38469)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"}
-->
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XJFhX5XfWT8anspjCw9gfjz)_
Part of #38411. This PR covers Ask 1, Ask 2 and the first two Acceptance
items, plus the model-free half of the eval, and on pgvector the cheaper
matcher for a caseless piece (`LIKE` instead of `ILIKE`). Still open:
the BrightRule model-graded before/after (needs a running BrightRule
environment and model credentials), and Ask 3 (not measured, see below).
Clause-②: yes (widening)
Metadata-protocol: none
## 维护者速读
- 用户能看到什么变化:在本地 libSQL 和 PostgreSQL
两种存储上,用中文、日文或韩文不加空格整句提问时,知识检索的关键词一路终于能匹配到段落;英文提问不受影响。
- 为什么做:属于知识平台专题,解决混合检索在中文问题上实际只剩向量一路的问题。
- 出错会怎样:代价是检索变慢(数字见下),最坏情况是关键词一路排序变差,向量一路照常作答;不改索引、不需重建,可直接撤回。
- 要你做什么:无。
取舍数字(合成制度题集,约 6.7 万段落,218 道中文题):
- 中文题关键词一路前 5 名命中率:0.028 → 0.495。
- 本地 libSQL 关键词一路 p95:约 0.12 秒 → 约 0.5 秒。
- 本地 libSQL 混合检索 p95:0.41 秒 → 0.84 秒。
- PostgreSQL 关键词一路 p95:约 0.6 秒 → 约 1.9 秒(本 PR 已把中文片段改成更便宜的匹配方式,排序不变;改之前约
3 秒)。
- 检索词上限 16 是实测拐点:再往上每多约 40% 耗时只多约 1 个点命中率。
- 想再降延迟的两个杠杆:把上限降到 12(命中率 0.459,libSQL 关键词 p95 约 0.31 秒);PostgreSQL
上给段落正文加三元组索引,已立后续卡 #38473,不在本 PR。
- 未测:BrightRule 模型评分的前后对比,需要运行环境和模型凭据。
## What changes
- `keywordTerms` in `knowledge-turso/src/sql.ts` and
`knowledge-pgvector/src/sql.ts` (one body, kept identical) cuts a run of
Han, Hiragana, Katakana (including the prolonged sound mark) or Hangul
inside a term into overlapping pieces of three characters and of two. A
run of two characters is one piece. A run of one is dropped, because it
would match nearly every passage. Figures and codes next to a run
(`2000`, `X-200`) stay whole terms. Latin-script and spaced queries get
exactly the terms they had before.
- **Selection rule (Ask 2).** `MAX_KEYWORD_TERMS` stays at 16,
re-decided by measurement (below). The cap is filled in this order:
figures, codes and words; then pieces of three characters and runs of
two; then pieces of two characters. A long question therefore keeps the
pieces the libSQL trigram index serves; a short one fills the cap with
pieces of two. Matching is unchanged. No index change, no fingerprint
change, no reindex.
- **pgvector matcher (round 2).** A keyword term the `tsvector` does not
serve is matched as a substring by `LIKE` when it holds no cased letter
(`containsOperator` in `knowledge-pgvector/src/sql.ts`:
`term.toLowerCase() === term.toUpperCase()`; a Han, kana or Hangul
piece, a figure), and by `ILIKE` otherwise. Case folding can find
nothing more for such a term, so the rankings are identical. Nothing
else in the Search section changes. libSQL is unchanged.
- **Docs.** `content/docs/protocol/knowledge.mdx` (the contract's
optional `keywordLeg` case; both Search bullets: the CJK pieces, and on
pgvector `LIKE` / `ILIKE`) and both plugin READMEs. The turso README
said "a Chinese question is one term", which this change made false.
- **Contract (H2 placement, Clause-② yes).**
`@objectstack/service-knowledge/testing`:
`KnowledgeAdapterContractOptions.implements` gains an **optional**
`keywordLeg` member (absent means `false`). When an adapter declares it,
the shared suite asks the unspaced question
「出差住宿费超标的话2000元以下除外的情况还要部门经理审批吗」 over one passage holding 「2000元以下除外」
and five passages holding the question's characters one by one but none
of its words. The passage must be ranked at `topK` 3. knowledge-turso
and knowledge-pgvector declare it. knowledge-memory and the service
stubs have no keyword leg and are untouched. No placement with zero new
exported members exists: the memory adapter and the stubs run the same
suite and have no keyword leg, and the spec contract has no capability
flag to read. The member is optional, so existing callers compile
unchanged; that makes it widening.
## Tests
<details><summary>Unit pins, contract case, ablation (head
b511770)</summary>
- knowledge-turso `acceptance.test.ts`: the Latin and spaced pin is kept
exactly (`What is the X-200 pump? …` gives today's 10 terms; `出差 住宿`
gives `['出差','住宿']`; cap 16). New pin: an unspaced question gives its
figure and then its pieces; `X-200型号的保修期` keeps `X-200`; runs of two and
one; kana and Hangul.
- knowledge-pgvector `keyword-terms.test.ts` (new, no database): the
same pins, plus which matcher each term goes to (`isWordTerm`).
- Contract case: knowledge-turso on `:memory:` and on a `file:` URL, and
knowledge-pgvector on a live PostgreSQL 16 with pgvector 0.6.0 started
in this container.
- Results, local: knowledge-turso `Test Files 4 passed, Tests 284
passed`; knowledge-pgvector live (`OS_TEST_POSTGRES_URL` set,
`OS_EXPECT_LIVE_DIALECT_MATRIX=1`) `Test Files 11 passed, Tests 108
passed`; service-knowledge `21 files, 726 tests passed`;
knowledge-memory `3 files, 66 tests passed`. Type check is green for
knowledge-turso, knowledge-pgvector, service-knowledge and
knowledge-memory.
- Ablation (base `sql.ts` swapped in, checked by blob hash, then
restored and checked by hash again): turso goes red with 4 failures (the
piece pin and the contract case, on both store kinds; the Latin pin
stays green); pgvector, live, goes red with 3 failures (the contract
case and two pins).
- Reverse type check: the turso type check first read a
`dist/testing.d.ts` built before this change and refused `keywordLeg`
(TS2353). After the rebuild it passes.
</details>
<details><summary>Round 2: the pgvector matcher (head cde0bbe; code
identical to 81be16f)</summary>
- `keyword-terms.test.ts` gains two pins. `containsOperator` gives
`LIKE` for `元以下`, `出差`, `コー`, `휴가`, `42` and `ILIKE` for `ab`, `X-200`,
`É`. A statement pin runs `adapter.search('出差 ab', …)` against a
recording pool and reads, from the ranking statement itself, the
operator in front of the placeholder each pattern is bound to: `%出差%`
gets `content LIKE`, `%ab%` gets `content ILIKE`.
- knowledge-pgvector live (PostgreSQL 16 + pgvector 0.6.0,
`OS_EXPECT_LIVE_DIALECT_MATRIX=1`), contract case included: `Test Files
11 passed (11)`, `Tests 110 passed (110)`, verify lock `VERDICT
command-exit 0`.
- `pnpm --filter @objectstack/knowledge-pgvector typecheck`: `VERDICT
command-exit 0`.
- Ablation: with the adapter reverted to b511770 (blob hash checked,
then restored and checked again), the statement pin fails: `Tests 1
failed | 4 passed (5)`.
- CI on b511770 (job 141221631158) and on 923c009 (jobs 141222136228
and 141222139195): every failing step is an aggregator reading a
`cancelled` lane (for example "type-check lane `typecheck-workspace`
concluded `cancelled` -- expected `success`"). Each later push to this
branch cancelled the run in flight. 923c009 also held one real error,
TS2353 in the new statement pin (`recipeHash` is not a member of the
search options' `index`), fixed in 81be16f and green locally as above.
</details>
## Measurement
Every harness is a scratch script outside the repository. Corpus: the
BrightRule synthetic set (`scripts/eval/build.ts --distractors 1500`,
brightrule @ 07e21ac). Passages are cut one per article or section, with
attachments kept on their own and each passage prefixed
`【unit|title|attachment】 path`, as the app's clause hook does. Each
document is indexed through `TursoKnowledgeAdapter.upsert` (the real
write path). Two tables:
- 11k: 1,577 documents, 11,025 passages.
- 67k: the same plus 8,000 distractors from seeds 11 to 14, giving 9,577
documents and **67,421 passages**. The card's table had 67,379.
Questions: the **218 zh questions whose expected policies are Chinese**
(230 counting the zh-to-English ones). A hit means a passage of an
expected policy (P) or of the expected article (C) in the keyword leg's
top 5 or top 10. The keyword leg is isolated with an all-zero query
vector, which turns the vector leg off. Intervals are 95% bootstrap
intervals over questions (2,000 resamples). Retrieval is deterministic:
**each side was run 3 times and the rankings were identical on every
run**, on both stores and both tables. So the interval comes from the
question sample, not from run noise.
<details><summary>Keyword leg, libSQL store, before and after</summary>
| table | side | P@5 | P@10 | C@5 | C@10 | questions with any hit | p50
| p95 |
|---|---|---|---|---|---|---|---|---|
| 11k | before | 0.032 [0.009, 0.055] | 0.037 [0.014, 0.064] | 0.028
[0.009, 0.051] | 0.032 [0.009, 0.060] | 31 | 0.7 ms | 20 ms |
| 11k | after | **0.500** [0.431, 0.569] | 0.514 [0.450, 0.583] | 0.486
[0.421, 0.556] | 0.500 [0.435, 0.569] | 206 | 52 to 56 ms | 80 to 93 ms
|
| 67k | before | 0.028 [0.009, 0.050] | 0.032 [0.009, 0.060] | 0.028
[0.009, 0.051] | 0.032 [0.009, 0.060] | 31 | 1.4 ms | 113 to 132 ms |
| 67k | after | **0.495** [0.427, 0.564] | 0.500 [0.431, 0.569] | 0.486
[0.421, 0.556] | 0.491 [0.421, 0.560] | 206 | 305 to 328 ms | **491 to
516 ms** |
All 230 zh questions, 67k: P@5 goes from 0.026 [0.009, 0.048] to 0.470
[0.404, 0.530].
</details>
<details><summary>Choosing the cap and the order (67k, keyword leg
alone)</summary>
| order / cap | P@5 | p50 | p95 |
|---|---|---|---|
| pieces of three and runs of two only (no pieces of two) | 0.404 | 7 ms
| 155 ms |
| three-first, cap 12 | 0.459 | 136 ms | 314 ms |
| **three-first, cap 16 (shipped)** | **0.495** | 321 ms | 507 ms |
| three-first, cap 20 | 0.505 | 440 ms | 690 ms |
| three-first, cap 24 | 0.509 | 552 ms | 910 ms |
| by position, cap 16 | 0.495 | 445 ms | 746 ms |
| by position, cap 32 (every piece of every question but a few) | 0.518
| 670 ms | 1,277 ms |
The questions are 16 characters at the median and 24 at p90, which gives
23 uncapped terms at the median and 34 at p90; 202 of 230 exceed 16. On
the 67k table, a piece of two characters costs one scan of the rows in
scope, about 23 ms (`LIKE` and `instr` cost the same). A piece of three
is served by the trigram index and is nearly free, except for a trigram
most passages hold: about 30 ms to materialise one held by 48,000 rows.
Past 16, recall gains about one point for each further 40% of latency,
and every interval overlaps. Cap 16 with the three-first order is the
knee. Keeping a one-character run measured no recall change.
</details>
<details><summary>Hybrid search latency, libSQL 67k with a 1024-wide
vector column (exact scan)</summary>
| side | p50 | p95 |
|---|---|---|
| before | 258 ms | 410 ms |
| pieces of three only | 266 ms | 429 ms |
| after (three-first, cap 16) | 563 ms | 837 ms |
| three-first, cap 24 | 818 ms | 1,244 ms |
The vector leg here is a bag-of-characters fake embedder, used for its
cost only. Its fused ranking is not reported: a lexical stand-in for an
embedder measures the fusion of two lexical legs, not hybrid retrieval.
</details>
<details><summary>pgvector, live PostgreSQL 16 + pgvector 0.6.0, the
same 67k passages, keyword leg alone</summary>
| side | P@5 | p50 | p95 |
|---|---|---|---|
| before (3 runs) | 0.028 | 132 to 150 ms | 617 to 691 ms |
| pieces, every substring term by `ILIKE` (b511770, 3 runs) | 0.495 |
538 to 563 ms | 2,883 to 3,085 ms |
| **pieces, a caseless term by `LIKE` (this head, 3 runs)** | 0.495 |
187 to 195 ms | **1,832 to 1,925 ms** |
The rankings are identical on every run, identical between the `ILIKE`
and the `LIKE` heads, and the same hit set as libSQL. The tail is
questions holding 公司: its pieces are held by 67,125 of 67,421 passages,
because every clause prefix names its company, so nearly every row
becomes a candidate. On this server `ILIKE '%公司%'` costs 90 ms per scan
against 18 ms for `LIKE` or `strpos`, with identical counts; that is the
matcher change in this PR. What remains of the tail is one substring
scan per piece over nearly every row, and the candidate `tsvector`
computed for each of them.
</details>
Commands, all run from a scratch directory outside the repository:
```
pnpm run eval:build -- --distractors 1500 --out EVALSET (in a scratch copy of brightrule, pnpm install --ignore-scripts)
pnpm run eval:build -- --distractors 2000 --seed 11..14 --out EVALSET-sN (distractors only, keys suffixed)
python3 -I prep.py CORPUS docs.json (clause passages)
tsx eval.ts index docs.json DB 8 zero and tsx eval.ts search docs.json DB questions.json VARIANT out.json
tsx eval.mts index / search (pgvector, the same shape)
python3 -I score.py zh RUN.json … (recall, bootstrap intervals, p50/p95)
```
All timings are seconds on a shared 4-core container, with sibling
agents running.
- NOT MEASURED: BrightRule model-graded eval, reason: it needs a running
BrightRule environment and model credentials, and this container has
neither. The keyword-leg retrieval above is the model-free stand-in.
- NOT MEASURED: fused hybrid recall, reason: no real embedder in this
container. A lexical stand-in would measure the fusion of two lexical
legs.
- NOT MEASURED: Ask 3 (a larger per-leg pool before fusion), reason: it
is judged on fused ranking, which needs a real embedder. Ask 3 also
reaches `knowledge-tools.ts`, which is outside this claim.
## Acceptance notes
- **pgvector keyword-leg cost (carrier: #38473, filed by the seat).**
With the `LIKE` matcher in, pgvector's keyword-leg p95 on the 67k table
goes from about 0.6 s to about 1.9 s. Two levers remain, both outside
this claim. First, compute the candidate `tsvector` only when a word
term needs it (a Search-section change). Second, a pg_trgm GIN index on
the passage content, which serves `LIKE` / `ILIKE` substrings. That is
an index change: a second DDL beside `keywordIndexDdl`
(`knowledge-pgvector/src/sql.ts`), created through `ensureKeywordIndex`
(`pgvector-adapter.ts`), plus a `pg_trgm` extension dependency next to
the `vector` one. It is not a fingerprint change: the index fingerprint
hashes only the embedding model, variant, dimensions and split, and an
older table gets the keyword index at its first search without a
rebuild.
- A lower cap is the cheapest lever on both stores: cap 12 measured P@5
0.459 and libSQL keyword p95 314 ms (cap 16: 0.495 and 507 ms).
- libSQL: a piece of two characters costs one scan of the rows in scope.
Scoring pieces of two only among the candidates that the index-served
terms recruit would remove that scan. It is a Search-section change and
moves each piece's document frequency, so it needs its own measurement.
- **Separator class takes 々, 〆 and 〇 (carrier: #38411, a remaining item
there, filed by the seat).** The class `\u3000-\u303f` holds 々 (U+3005),
〆 (U+3006) and 〇 (U+3007, the ideographic zero), in both stores. With
this PR's rule that drops a one-character run, 「人々」 yields no keyword
term (on main it kept 「人」) and 「二〇二四年」 loses 「二」. The fix (take
U+3005–U+3007 out of the separator class and into the run, pins in both
stores) lands as a follow-up PR on #38411 after this one merges, so this
approved head does not move (L1 7250902792).
- To run the pgvector live suites, this container installed
`postgresql-16-pgvector` (0.6.0, Ubuntu noble) and ran a private cluster
on a random port, removed afterwards.
## Verification
- Read first: `packages/plugins/knowledge-turso/src/sql.ts`
(`keywordTerms`: the run split and the final order and cap),
`packages/services/service-knowledge/src/testing.ts` (the optional
`keywordLeg` member and its case),
`packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts` (the
keyword branch of the ranking statement, where `containsOperator` picks
`LIKE` or `ILIKE`).
- Two-minute check: `pnpm --filter @objectstack/knowledge-turso exec
vitest run --maxWorkers=2 src/__tests__/contract.test.ts` should show
the case `the keyword leg › an unspaced question ranks the passage …`
passing on both `:memory:` and `file:`.
<details><summary>Local gate subset at cde0bbe (CI runs the full
farm)</summary>
- Tests and type checks: listed under Tests above.
- `node scripts/pm/dispatch-gates.mjs --commands` derived 101 families
for the 12 changed files (70 at b511770, plus 31 the docs edit brings
in). Each ran with its exit code captured before any pipe. The 31 docs
families and 8 families that read the round-2 files were run at
cde0bbe; the others read files unchanged since b511770 and carry that
reading. `--ran` reconciliation at cde0bbe: `101 derived, 101 run, 0
NOT-MEASURED, 0 UNRUN`. Exit codes: **96 exit 0**, and five not
measured:
- NOT MEASURED: `check:skill-examples`, reason: exit 3, PREREQUISITE NOT
MET, it needs the client SDK's `dist/`. No skill file is touched.
- NOT MEASURED: `check-plugin-teardown-shape.mjs --self-test`, reason:
PREREQUISITE NOT MET, its pinned positive-control commit is beyond this
shallow clone.
- NOT MEASURED: `check:dual-build-cjs-loads`, reason: PREREQUISITE NOT
MET, it needs every package's `dist/`.
- NOT MEASURED: `check:query-options-erasure` and
`check:type-check-debt`, reason: repo-wide ESLint and `tsc` scans that
passed the 240 s per-gate limit. CI's Lint & Repo Gates and TypeScript
Type Check carry them.
- `overlap-check` before the push: `VERDICT clean` against origin/main
and the two open PRs that share `knowledge.mdx` (#38468, #38470), and
clean against `origin/claude/project-thread-mu3i0t`.
- Self-scan of the changed files for control bytes: no hits.
</details>
🤖 Generated with [Claude Code](https://claude.com/claude-code)
https://claude.ai/code/session_01FEkQ5pfJqySEaVD3CKvevm
<!-- signed: repo:objectstack#5 · os-project-manager ·
session_01FEkQ5pfJqySEaVD3CKvevm -->
---------
Co-authored-by: Claude <noreply@anthropic.com>1 parent 70d2d48 commit 430bbbf
12 files changed
Lines changed: 276 additions & 21 deletions
File tree
- .changeset
- content/docs/protocol
- packages
- plugins
- knowledge-pgvector
- src
- __tests__
- knowledge-turso
- src
- __tests__
- services/service-knowledge/src
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
546 | 546 | | |
547 | 547 | | |
548 | 548 | | |
549 | | - | |
| 549 | + | |
| 550 | + | |
550 | 551 | | |
551 | 552 | | |
552 | 553 | | |
| |||
738 | 739 | | |
739 | 740 | | |
740 | 741 | | |
741 | | - | |
| 742 | + | |
| 743 | + | |
| 744 | + | |
742 | 745 | | |
743 | 746 | | |
744 | 747 | | |
| |||
805 | 808 | | |
806 | 809 | | |
807 | 810 | | |
808 | | - | |
| 811 | + | |
| 812 | + | |
| 813 | + | |
809 | 814 | | |
810 | 815 | | |
811 | 816 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
58 | 58 | | |
59 | 59 | | |
60 | 60 | | |
61 | | - | |
| 61 | + | |
62 | 62 | | |
63 | 63 | | |
64 | 64 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
29 | 29 | | |
30 | 30 | | |
31 | 31 | | |
| 32 | + | |
32 | 33 | | |
33 | 34 | | |
34 | 35 | | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
| 61 | + | |
| 62 | + | |
| 63 | + | |
| 64 | + | |
| 65 | + | |
| 66 | + | |
| 67 | + | |
| 68 | + | |
| 69 | + | |
| 70 | + | |
| 71 | + | |
| 72 | + | |
| 73 | + | |
| 74 | + | |
| 75 | + | |
| 76 | + | |
| 77 | + | |
| 78 | + | |
| 79 | + | |
| 80 | + | |
| 81 | + | |
| 82 | + | |
| 83 | + | |
| 84 | + | |
| 85 | + | |
| 86 | + | |
| 87 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
19 | 19 | | |
20 | 20 | | |
21 | 21 | | |
| 22 | + | |
22 | 23 | | |
23 | 24 | | |
24 | 25 | | |
| |||
189 | 190 | | |
190 | 191 | | |
191 | 192 | | |
192 | | - | |
| 193 | + | |
| 194 | + | |
193 | 195 | | |
194 | 196 | | |
195 | 197 | | |
| |||
668 | 670 | | |
669 | 671 | | |
670 | 672 | | |
671 | | - | |
672 | | - | |
| 673 | + | |
| 674 | + | |
| 675 | + | |
673 | 676 | | |
674 | 677 | | |
675 | 678 | | |
| |||
0 commit comments