Skip to content

Commit 430bbbf

Browse files
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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/knowledge-turso': patch
3+
'@objectstack/knowledge-pgvector': patch
4+
'@objectstack/service-knowledge': patch
5+
---
6+
7+
fix(knowledge): the keyword leg of hybrid search ranks passages for a Chinese, Japanese or Korean question written without spaces
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: none
11+
12+
Before, the keyword leg split a query only at white space and punctuation, so an unspaced question such as 「出差住宿费2000元以下需要审批吗」 was one term. A passage matched only if it held the whole question, so the keyword leg ranked nothing and hybrid search answered from the vector leg alone.
13+
14+
Now `keywordTerms` in `@objectstack/knowledge-turso` and `@objectstack/knowledge-pgvector` (one rule, kept identical) cuts a run of Han, kana or Hangul inside a term into overlapping pieces of three characters and of two. A run of two characters is one piece, and a run of one is dropped. Figures and codes next to a run stay whole terms (`2000`, `X-200`). Latin-script queries get exactly the terms they had before. The cap stays at 16 terms, filled in this order: figures, codes and words; then pieces of three characters and runs of two; then pieces of two characters. Each piece is matched as before: a piece of three characters through the libSQL trigram index or `ILIKE`, a piece of two through `LIKE` / `ILIKE`. The per-term inverse document frequency weights pieces that most passages hold low. Nothing changes in the index or the fingerprint, and no reindex is needed. On PostgreSQL, a substring term without a cased letter (a Han, kana or Hangul piece, a figure) is now matched by `LIKE` instead of `ILIKE`. Case folding could find nothing more for such a term, and `LIKE` returns the same rankings at a fraction of the cost.
15+
16+
`@objectstack/service-knowledge/testing`: `KnowledgeAdapterContractOptions.implements` gains an optional `keywordLeg` member (absent means `false`). When an adapter declares it, the shared contract suite asks an unspaced question and expects the passage holding the question's figure and exception words to be ranked. Existing callers need no change.

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -546,7 +546,8 @@ one that does not keeps receiving whole documents, and a `whole` document over
546546
the embedder's budget is removed and reported; and the index fingerprint of
547547
§3.6 — that every call carries one, that a write or a search under another
548548
is refused by code, a complete reindex as one build, and, for an adapter that
549-
keeps generations, the switch at the end of a build. `implements` declares the optional members, and the suite
549+
keeps generations, the switch at the end of a build; and, for an adapter that declares the optional
550+
`keywordLeg`, an unspaced Chinese question that ranks the passage holding its figure and words. `implements` declares the optional members, and the suite
550551
checks the declaration against the adapter. `./testing` is a test-only,
551552
ESM-only entry that imports `vitest`; nothing in the runtime entry reaches it.
552553
`knowledge-memory` runs it as the reference implementation; `knowledge-pgvector`
@@ -738,7 +739,9 @@ an exact scan.
738739
scan by cosine distance, so any width works — including a 3072-wide model —
739740
and a keyword leg on `to_tsvector('simple', content)` (a GIN expression
740741
index), a word of three characters or more as a phrase, a shorter term or
741-
one in Han, kana or Hangul script by `ILIKE`. The organization filter, the
742+
one in Han, kana or Hangul script as a substring (`LIKE` for a term without
743+
a cased letter, `ILIKE` otherwise); a run of Han, kana or Hangul in the
744+
query is cut into overlapping pieces of three characters and of two. The organization filter, the
742745
[record scope](#record-scope) and the metadata `filter` (equality per key)
743746
are one `WHERE`, run in both legs before either ranks.
744747
`queryPrefix` is put before every query before it is embedded, for a model
@@ -805,7 +808,9 @@ large source of one organization, through an approximate index.
805808
at most `topK`) before the service's re-check: a vector leg by cosine
806809
distance (an exact scan, or the approximate index below), and a keyword leg in a contentless FTS5 trigram index beside each
807810
passage table (kept in step by triggers), a term of three characters or
808-
more as a quoted phrase, a shorter one by `LIKE`. The organization filter,
811+
more as a quoted phrase, a shorter one by `LIKE`; a run of Han, kana or
812+
Hangul in the query is cut into overlapping pieces of three characters and
813+
of two. The organization filter,
809814
the [record scope](#record-scope) and the metadata `filter` (JSON equality
810815
per key) are one `WHERE`, run in both legs. Without the approximate index
811816
the vector leg reads every row in scope: 1,000 passages of 1,536 dimensions take 8.3 MB and a search about

‎packages/plugins/knowledge-pgvector/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ The next call retries; no restart is needed. A database the plugin cannot reach
5858

5959
Two legs in one statement (one snapshot), merged by reciprocal rank fusion (RRF, `k` = 60) before the knowledge service re-checks each hit as the caller. Each leg ranks at most `topK` passages; a hit's `score` is the sum of `1 / (60 + rank)` over the legs that rank it, divided by that of a passage first in both, so it lies in `(0, 1]`: 1 for first in both legs, 0.5 for first in one alone. The organization filter, the record scope and the metadata `filter` are one `WHERE`, run in both legs before either ranks.
6060

61-
- **Keyword leg.** The query is split into terms at white space and punctuation; a hyphen, dot, slash, underscore, `#`, `@` or `+` inside a term keeps it whole, so `X-200` is one term (at most 16 terms). A word of three characters or more is matched as a phrase (`phraseto_tsquery('simple', …)`) on the passage's `to_tsvector('simple', content)`, which a GIN expression index (`knowledge_vec_d<width>_content_tsv`) serves. The `simple` configuration lower-cases and neither stems nor drops stop words, so a code or a name matches as written. A shorter term (「出差」), and a term holding a Han, kana or Hangul character — which the parser never splits, so a `tsvector` holds a whole run of them as one word — is matched by `content ILIKE '%…%'` over the rows in scope, as a substring. A passage's keyword score sums, over the terms it holds, the term's BM25 inverse document frequency among the rows in scope, so a word most passages hold weighs little.
61+
- **Keyword leg.** The query is split into terms at white space and punctuation; a hyphen, dot, slash, underscore, `#`, `@` or `+` inside a term keeps it whole, so `X-200` is one term (at most 16 terms). A run of Han, kana or Hangul inside a term is cut into overlapping pieces of three characters and of two (a run of two is one piece, a run of one is dropped), so a question written without spaces is still matched word by word; a figure or a code next to a run (`2000`, `X-200`) stays one term. Under the cap the figures, codes and words come first, then the pieces of three characters, then those of two. A word of three characters or more is matched as a phrase (`phraseto_tsquery('simple', …)`) on the passage's `to_tsvector('simple', content)`, which a GIN expression index (`knowledge_vec_d<width>_content_tsv`) serves. The `simple` configuration lower-cases and neither stems nor drops stop words, so a code or a name matches as written. A shorter term (「出差」), and a term holding a Han, kana or Hangul character — which the parser never splits, so a `tsvector` holds a whole run of them as one word — is matched as a substring over the rows in scope: by `content LIKE '%…%'` when the term holds no cased letter (a piece of Han, kana or Hangul, a figure), where case folding could find nothing more, and by `content ILIKE '%…%'` otherwise. A passage's keyword score sums, over the terms it holds, the term's BM25 inverse document frequency among the rows in scope, so a word most passages hold weighs little.
6262
- **Keyword index.** An expression index: no column is added and no row rewritten, and PostgreSQL keeps it in step with every write. It is made with the passage table; a table made by a release without one gets it from the first write or search of that width (`CREATE INDEX IF NOT EXISTS`, which blocks writes to the table while it builds).
6363
- **Vector leg.** An exact cosine scan; a passage whose cosine similarity is not positive is not ranked by it.
6464

‎packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => {
2929
generations: true,
3030
scope: true,
3131
dropSource: true,
32+
keywordLeg: true,
3233
},
3334
});
3435
});
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
// The keyword leg's terms, without a database: the same rule as the libSQL
4+
// store's, pinned with the same cases, and how each kind of term is matched,
5+
// down to the operator in the statement a search sends.
6+
7+
import { describe, expect, it } from 'vitest';
8+
import type { KnowledgeSource } from '@objectstack/spec/ai';
9+
import { PgvectorKnowledgeAdapter, type PgPoolLike } from '../index.js';
10+
import { containsOperator, isWordTerm, keywordTerms } from '../sql.js';
11+
import { FakeEmbedder } from './live-pg.testkit.js';
12+
13+
describe('knowledge-pgvector keywordTerms', () => {
14+
it('splits a query into terms at white space and punctuation, keeping a code whole', () => {
15+
// Latin-script and spaced terms: the terms they always had.
16+
expect(keywordTerms('What is the X-200 pump? v1.2, a/b; #tag (part 7731)')).toEqual([
17+
'What', 'is', 'the', 'X-200', 'pump', 'v1.2', 'a/b', 'tag', 'part', '7731',
18+
]);
19+
expect(keywordTerms('出差 住宿')).toEqual(['出差', '住宿']);
20+
expect(keywordTerms('pump PUMP Pump')).toEqual(['pump']);
21+
expect(keywordTerms(Array.from({ length: 40 }, (_, i) => `w${i}`).join(' '))).toHaveLength(16);
22+
});
23+
24+
it('cuts a run of Han, kana or Hangul into pieces of three characters and of two, keeping figures and codes whole', () => {
25+
// An unspaced question: its figure, then the pieces of three, then those of two, up to the cap.
26+
expect(keywordTerms('出差住宿费2000元以下需要审批吗')).toEqual([
27+
'2000', '出差住', '差住宿', '住宿费', '元以下', '以下需', '下需要', '需要审', '要审批', '审批吗',
28+
'出差', '差住', '住宿', '宿费', '元以', '以下',
29+
]);
30+
expect(keywordTerms('X-200型号的保修期')).toEqual([
31+
'X-200', '型号的', '号的保', '的保修', '保修期', '型号', '号的', '的保', '保修', '修期',
32+
]);
33+
// A run of two is one piece, kept with the pieces of three; a run of one is dropped; a repeat counts once.
34+
expect(keywordTerms('出差的住宿标准,「三十天」。出差')).toEqual([
35+
'出差的', '差的住', '的住宿', '住宿标', '宿标准', '三十天', '出差', '差的', '的住', '住宿', '宿标', '标准', '三十', '十天',
36+
]);
37+
expect(keywordTerms('费 2000元')).toEqual(['2000']);
38+
// Katakana with its prolonged sound mark, which belongs to no script, and Hangul.
39+
expect(keywordTerms('コーヒー代')).toEqual(['コーヒ', 'ーヒー', 'ヒー代', 'コー', 'ーヒ', 'ヒー', 'ー代']);
40+
expect(keywordTerms('휴가는')).toEqual(['휴가는', '휴가', '가는']);
41+
});
42+
43+
it('matches a piece as a substring and a figure or a code of three characters or more on the tsvector', () => {
44+
expect(keywordTerms('住宿费2000元以下').map((t) => [t, isWordTerm(t)])).toEqual([
45+
['2000', true], ['住宿费', false], ['元以下', false], ['住宿', false], ['宿费', false], ['元以', false], ['以下', false],
46+
]);
47+
});
48+
49+
it('matches a substring term without a cased letter by LIKE, and one holding a cased letter by ILIKE', () => {
50+
for (const term of ['元以下', '出差', 'コー', '휴가', '42']) expect(containsOperator(term)).toBe('LIKE');
51+
for (const term of ['ab', 'X-200', 'É']) expect(containsOperator(term)).toBe('ILIKE');
52+
});
53+
});
54+
55+
describe('knowledge-pgvector keyword leg statement', () => {
56+
const source = { name: 'kw', label: 'kw', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource;
57+
58+
/** A store with one stable active generation, which records each ranking statement and its values. */
59+
function recordingPool(): { pool: PgPoolLike; ranked: Array<{ text: string; values: unknown[] }> } {
60+
const ranked: Array<{ text: string; values: unknown[] }> = [];
61+
const answer = async <R>(text: string, values: unknown[] = []): Promise<{ rows: R[] }> => {
62+
if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.0' }] as R[] };
63+
if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] as R[] };
64+
if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) {
65+
return { rows: [{ generation: 1, fingerprint: 'fp', recipe_hash: 'rh', dim: 384, state: 'active' }] as R[] };
66+
}
67+
if (text.includes('AS distance')) ranked.push({ text, values });
68+
return { rows: [] as R[] };
69+
};
70+
return { pool: { query: answer, connect: async () => ({ query: answer, release: () => undefined }) }, ranked };
71+
}
72+
73+
it('sends a caseless Chinese piece as content LIKE and a cased Latin term as content ILIKE', async () => {
74+
const { pool, ranked } = recordingPool();
75+
const adapter = new PgvectorKnowledgeAdapter({ id: 'kw', pool, embedder: new FakeEmbedder() });
76+
await adapter.search('出差 ab', { source, topK: 5, index: { fingerprint: 'fp' } });
77+
expect(ranked).toHaveLength(1);
78+
const { text, values } = ranked[0];
79+
// The operator in front of the placeholder a pattern is bound to, read from the statement itself.
80+
const operatorOf = (pattern: string): string | undefined => {
81+
const at = values.indexOf(pattern) + 1;
82+
return at === 0 ? undefined : new RegExp(`content (I?LIKE) \\$${at}::text`).exec(text)?.[1];
83+
};
84+
expect(operatorOf('%出差%')).toBe('LIKE');
85+
expect(operatorOf('%ab%')).toBe('ILIKE');
86+
});
87+
});

‎packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
PASSAGE_TSVECTOR,
2020
SAFE_IDENTIFIER,
2121
TS_CONFIG,
22+
containsOperator,
2223
containsPattern,
2324
isWordTerm,
2425
keywordIndexDdl,
@@ -189,7 +190,8 @@ interface Readiness {
189190
* passage's `simple` `tsvector`, which a GIN expression index serves; a
190191
* shorter term (「出差」), or one holding a Han, kana or Hangul character —
191192
* which the parser never splits, so a `tsvector` holds the whole run as one
192-
* word — by `ILIKE` over the rows in scope. A passage's keyword score sums,
193+
* word — as a substring over the rows in scope: by `LIKE` for a term
194+
* without a cased letter, by `ILIKE` otherwise. A passage's keyword score sums,
193195
* over the terms it holds, the term's BM25 inverse document frequency among
194196
* the rows in scope, so a term most passages hold weighs little.
195197
*
@@ -668,8 +670,9 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
668670
onCandidate.push(`v.tsv @@ ${query}`);
669671
} else {
670672
params.push(containsPattern(term));
671-
onRow.push(`content ILIKE $${params.length}::text`);
672-
onCandidate.push(`c.content ILIKE $${params.length}::text`);
673+
const op = containsOperator(term);
674+
onRow.push(`content ${op} $${params.length}::text`);
675+
onCandidate.push(`c.content ${op} $${params.length}::text`);
673676
}
674677
}
675678
const idf = onCandidate

0 commit comments

Comments
 (0)