From 5d504bf7a7c3e28a6b80f1b61973bdba808e6f34 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:02:51 +0000 Subject: [PATCH 1/5] fix(knowledge): the keyword leg cuts an unspaced CJK run into 2- and 3-character pieces keywordTerms in knowledge-turso and knowledge-pgvector (one body, kept identical) cuts a run of Han, kana or Hangul inside a term into overlapping pieces of three characters and of two; figures and codes around a run stay whole terms. Under the unchanged cap of 16: words first, then the pieces of three and the runs of two, then the pieces of two. The shared adapter contract suite gains an optional implements.keywordLeg member and one case: an unspaced question ranks the passage holding its figure and exception words. Both stores declare it. Claude-Session: https://claude.ai/code/session_01FEkQ5pfJqySEaVD3CKvevm Co-Authored-By: Claude --- .../__tests__/contract.live-postgres.test.ts | 1 + .../src/__tests__/keyword-terms.test.ts | 44 +++++++++++++++++ .../plugins/knowledge-pgvector/src/sql.ts | 49 +++++++++++++++++-- .../src/__tests__/acceptance.test.ts | 22 ++++++++- .../src/__tests__/contract.test.ts | 1 + packages/plugins/knowledge-turso/src/sql.ts | 49 +++++++++++++++++-- .../services/service-knowledge/src/testing.ts | 30 ++++++++++++ 7 files changed, 187 insertions(+), 9 deletions(-) create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts index d1f51dcddcd..4a8be8ed477 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts @@ -29,6 +29,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => { generations: true, scope: true, dropSource: true, + keywordLeg: true, }, }); }); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts new file mode 100644 index 00000000000..bb74912dbfd --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts @@ -0,0 +1,44 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +// The keyword leg's terms, without a database: the same rule as the libSQL +// store's, pinned with the same cases, and how each kind of term is matched. + +import { describe, expect, it } from 'vitest'; +import { isWordTerm, keywordTerms } from '../sql.js'; + +describe('knowledge-pgvector keywordTerms', () => { + it('splits a query into terms at white space and punctuation, keeping a code whole', () => { + // Latin-script and spaced terms: the terms they always had. + expect(keywordTerms('What is the X-200 pump? v1.2, a/b; #tag (part 7731)')).toEqual([ + 'What', 'is', 'the', 'X-200', 'pump', 'v1.2', 'a/b', 'tag', 'part', '7731', + ]); + expect(keywordTerms('出差 住宿')).toEqual(['出差', '住宿']); + expect(keywordTerms('pump PUMP Pump')).toEqual(['pump']); + expect(keywordTerms(Array.from({ length: 40 }, (_, i) => `w${i}`).join(' '))).toHaveLength(16); + }); + + it('cuts a run of Han, kana or Hangul into pieces of three characters and of two, keeping figures and codes whole', () => { + // An unspaced question: its figure, then the pieces of three, then those of two, up to the cap. + expect(keywordTerms('出差住宿费2000元以下需要审批吗')).toEqual([ + '2000', '出差住', '差住宿', '住宿费', '元以下', '以下需', '下需要', '需要审', '要审批', '审批吗', + '出差', '差住', '住宿', '宿费', '元以', '以下', + ]); + expect(keywordTerms('X-200型号的保修期')).toEqual([ + 'X-200', '型号的', '号的保', '的保修', '保修期', '型号', '号的', '的保', '保修', '修期', + ]); + // A run of two is one piece, kept with the pieces of three; a run of one is dropped; a repeat counts once. + expect(keywordTerms('出差的住宿标准,「三十天」。出差')).toEqual([ + '出差的', '差的住', '的住宿', '住宿标', '宿标准', '三十天', '出差', '差的', '的住', '住宿', '宿标', '标准', '三十', '十天', + ]); + expect(keywordTerms('费 2000元')).toEqual(['2000']); + // Katakana with its prolonged sound mark, which belongs to no script, and Hangul. + expect(keywordTerms('コーヒー代')).toEqual(['コーヒ', 'ーヒー', 'ヒー代', 'コー', 'ーヒ', 'ヒー', 'ー代']); + expect(keywordTerms('휴가는')).toEqual(['휴가는', '휴가', '가는']); + }); + + it('matches a piece by ILIKE and a figure or a code of three characters or more on the tsvector', () => { + expect(keywordTerms('住宿费2000元以下').map((t) => [t, isWordTerm(t)])).toEqual([ + ['2000', true], ['住宿费', false], ['元以下', false], ['住宿', false], ['宿费', false], ['元以', false], ['以下', false], + ]); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/sql.ts b/packages/plugins/knowledge-pgvector/src/sql.ts index 903a78a8ddc..9cfcdb8978b 100644 --- a/packages/plugins/knowledge-pgvector/src/sql.ts +++ b/packages/plugins/knowledge-pgvector/src/sql.ts @@ -122,7 +122,13 @@ export function keywordIndexDdl(schema: string, dimensions: number): string { return `CREATE INDEX IF NOT EXISTS "${keywordIndexName(dimensions)}" ON ${qualified(schema, vectorTable(dimensions))} USING gin (${PASSAGE_TSVECTOR})`; } -/** The most terms of one query the keyword leg matches; the rest are left to the vector leg. */ +/** + * The most terms of one query the keyword leg matches; the rest are left to the + * vector leg. Kept at 16 for pieces, by measurement on a table of about 67,000 + * passages and over 200 unspaced Chinese questions: each piece of two + * characters is a scan of the rows in scope, so a higher cap bought about one + * point of recall for each further 40% of latency. + */ export const MAX_KEYWORD_TERMS = 16; /** The shortest term (in characters) matched on the `tsvector`; a shorter one is matched by `ILIKE`. */ @@ -135,20 +141,55 @@ export const WORD_MIN_CHARS = 3; */ export const UNSEGMENTED = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u; +/** + * A run of characters written without spaces between words: Han, Hiragana, + * Katakana (with the prolonged sound mark, which belongs to no script) and + * Hangul. + */ +const UNSEGMENTED_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u30fc\uff70]+/gu; + /** * The terms of a query for the keyword leg: split at white space and at * punctuation that never sits inside a code (a hyphen, a dot, a slash, an * underscore, `#`, `@` and `+` stay inside one, so `X-200`, `v1.2` and * `a/b` are each one term), stripped of what is not a letter or a digit at * either end, compared case-insensitively, at most {@link MAX_KEYWORD_TERMS}. + * + * A run of Han, kana or Hangul inside a term (an unspaced question is one + * such run, or a few) is cut into overlapping pieces of three characters and + * of two; a run of two characters is one piece, a run of one is dropped (it + * would match nearly every passage). What surrounds a run in the term, a + * figure or a code (`2000`, `X-200`), is a term of its own, whole. Under the + * cap, the terms come in this order, each kind in query order: the figures, + * codes and words, then the pieces of three characters and the runs of two, + * then the pieces of two characters, so a long question keeps the pieces an + * index serves and a short one fills the cap with pieces of two. * The same rule as the libSQL store's. */ export function keywordTerms(query: string): string[] { + const words: string[] = []; + const longer: string[] = []; + const pairs: string[] = []; + const word = (text: string): void => { + const stripped = text.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ''); + if (stripped !== '') words.push(stripped); + }; + for (const term of query.split(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u)) { + let at = 0; + for (const run of term.matchAll(UNSEGMENTED_RUN)) { + word(term.slice(at, run.index)); + at = run.index + run[0].length; + const chars = [...run[0]]; + if (chars.length === 2) longer.push(run[0]); + if (chars.length < 3) continue; + for (let i = 0; i + 2 < chars.length; i++) longer.push(chars[i] + chars[i + 1] + chars[i + 2]); + for (let i = 0; i + 1 < chars.length; i++) pairs.push(chars[i] + chars[i + 1]); + } + word(term.slice(at)); + } const seen = new Set(); const terms: string[] = []; - for (const raw of query.split(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u)) { - const term = raw.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ''); - if (term === '') continue; + for (const term of [...words, ...longer, ...pairs]) { const key = term.toLowerCase(); if (seen.has(key)) continue; seen.add(key); diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 0435cbfa125..c68a9c32200 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -980,16 +980,36 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { }); it('splits a query into terms at white space and punctuation, keeping a code whole', () => { + // Latin-script and spaced terms: the terms they always had. expect(keywordTerms('What is the X-200 pump? v1.2, a/b; #tag (part 7731)')).toEqual([ 'What', 'is', 'the', 'X-200', 'pump', 'v1.2', 'a/b', 'tag', 'part', '7731', ]); - expect(keywordTerms('出差的住宿标准,「三十天」。出差')).toEqual(['出差的住宿标准', '三十天', '出差']); + expect(keywordTerms('出差 住宿')).toEqual(['出差', '住宿']); expect(keywordTerms('pump PUMP Pump')).toEqual(['pump']); expect(keywordTerms(Array.from({ length: 40 }, (_, i) => `w${i}`).join(' '))).toHaveLength(16); expect(containsPattern('a%_\\b')).toBe('%a\\%\\_\\\\b%'); expect(ftsPhrase('say "hi"')).toBe('"say ""hi"""'); }); + it('cuts a run of Han, kana or Hangul into pieces of three characters and of two, keeping figures and codes whole', () => { + // An unspaced question: its figure, then the pieces of three, then those of two, up to the cap. + expect(keywordTerms('出差住宿费2000元以下需要审批吗')).toEqual([ + '2000', '出差住', '差住宿', '住宿费', '元以下', '以下需', '下需要', '需要审', '要审批', '审批吗', + '出差', '差住', '住宿', '宿费', '元以', '以下', + ]); + expect(keywordTerms('X-200型号的保修期')).toEqual([ + 'X-200', '型号的', '号的保', '的保修', '保修期', '型号', '号的', '的保', '保修', '修期', + ]); + // A run of two is one piece, kept with the pieces of three; a run of one is dropped; a repeat counts once. + expect(keywordTerms('出差的住宿标准,「三十天」。出差')).toEqual([ + '出差的', '差的住', '的住宿', '住宿标', '宿标准', '三十天', '出差', '差的', '的住', '住宿', '宿标', '标准', '三十', '十天', + ]); + expect(keywordTerms('费 2000元')).toEqual(['2000']); + // Katakana with its prolonged sound mark, which belongs to no script, and Hangul. + expect(keywordTerms('コーヒー代')).toEqual(['コーヒ', 'ーヒー', 'ヒー代', 'コー', 'ーヒ', 'ヒー', 'ー代']); + expect(keywordTerms('휴가는')).toEqual(['휴가는', '휴가', '가는']); + }); + it('the organization filter, the record scope and the metadata filter hold in the keyword leg too', async () => { const adapter = store.adapter(); const s = source('kw_scope'); diff --git a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts index 6c0b111351b..903aba6ac35 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts @@ -27,6 +27,7 @@ for (const kind of ['memory', 'file'] as const) { generations: true, scope: true, dropSource: true, + keywordLeg: true, }, }); }); diff --git a/packages/plugins/knowledge-turso/src/sql.ts b/packages/plugins/knowledge-turso/src/sql.ts index abc5a0c1ea0..e3790a963c4 100644 --- a/packages/plugins/knowledge-turso/src/sql.ts +++ b/packages/plugins/knowledge-turso/src/sql.ts @@ -379,25 +379,66 @@ export function vectorIndexShape( return found.length === own.length ? 'complete' : 'partial'; } -/** The most terms of one query the keyword leg matches; the rest are left to the vector leg. */ +/** + * The most terms of one query the keyword leg matches; the rest are left to the + * vector leg. Kept at 16 for pieces, by measurement on a table of about 67,000 + * passages and over 200 unspaced Chinese questions: each piece of two + * characters is a scan of the rows in scope, so a higher cap bought about one + * point of recall for each further 40% of latency. + */ export const MAX_KEYWORD_TERMS = 16; /** The shortest term (in characters) the trigram index can match; a shorter one is matched by `LIKE`. */ export const TRIGRAM_MIN_CHARS = 3; +/** + * A run of characters written without spaces between words: Han, Hiragana, + * Katakana (with the prolonged sound mark, which belongs to no script) and + * Hangul. + */ +const UNSEGMENTED_RUN = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\u30fc\uff70]+/gu; + /** * The terms of a query for the keyword leg: split at white space and at * punctuation that never sits inside a code (a hyphen, a dot, a slash, an * underscore, `#`, `@` and `+` stay inside one, so `X-200`, `v1.2` and * `a/b` are each one term), stripped of what is not a letter or a digit at * either end, compared case-insensitively, at most {@link MAX_KEYWORD_TERMS}. + * + * A run of Han, kana or Hangul inside a term (an unspaced question is one + * such run, or a few) is cut into overlapping pieces of three characters and + * of two; a run of two characters is one piece, a run of one is dropped (it + * would match nearly every passage). What surrounds a run in the term, a + * figure or a code (`2000`, `X-200`), is a term of its own, whole. Under the + * cap, the terms come in this order, each kind in query order: the figures, + * codes and words, then the pieces of three characters and the runs of two, + * then the pieces of two characters, so a long question keeps the pieces an + * index serves and a short one fills the cap with pieces of two. */ export function keywordTerms(query: string): string[] { + const words: string[] = []; + const longer: string[] = []; + const pairs: string[] = []; + const word = (text: string): void => { + const stripped = text.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ''); + if (stripped !== '') words.push(stripped); + }; + for (const term of query.split(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u)) { + let at = 0; + for (const run of term.matchAll(UNSEGMENTED_RUN)) { + word(term.slice(at, run.index)); + at = run.index + run[0].length; + const chars = [...run[0]]; + if (chars.length === 2) longer.push(run[0]); + if (chars.length < 3) continue; + for (let i = 0; i + 2 < chars.length; i++) longer.push(chars[i] + chars[i + 1] + chars[i + 2]); + for (let i = 0; i + 1 < chars.length; i++) pairs.push(chars[i] + chars[i + 1]); + } + word(term.slice(at)); + } const seen = new Set(); const terms: string[] = []; - for (const raw of query.split(/[\s,;:!?()[\]{}<>"'`|\\=*~^$%&\u3000-\u303f\uff01-\uff0f\uff1a-\uff20\uff3b-\uff40\uff5b-\uff65\u2018-\u201f\u2026]+/u)) { - const term = raw.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ''); - if (term === '') continue; + for (const term of [...words, ...longer, ...pairs]) { const key = term.toLowerCase(); if (seen.has(key)) continue; seen.add(key); diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 2c419b06bc0..036bf9be61c 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -69,6 +69,11 @@ * source indexes and by a parent object reached through a listed lookup, and * over the adapter with the member stripped from its search: no out-of-scope * hit is answered, and the service logs once. + * + * An adapter that declares `keywordLeg` is asked an unspaced Chinese question + * whose figure and exception words one passage holds, among passages that + * hold the question's characters one by one and none of its words: the + * passage is ranked. */ import { describe, expect, it, vi } from 'vitest'; @@ -135,6 +140,14 @@ export interface KnowledgeAdapterContractOptions { * recorded about the index. */ dropSource: boolean; + /** + * The adapter's search has a keyword leg beside its vector leg, and that + * leg cuts a run of Han, kana or Hangul in the query into pieces, so a + * question written without spaces ranks the passage that holds some of its + * words, which the vector leg alone ranks below `topK`. Asserted by + * behaviour. Absent: `false`. + */ + keywordLeg?: boolean; }; } @@ -538,6 +551,23 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); }); + if (opts.implements.keywordLeg) { + describe('the keyword leg', () => { + it('an unspaced question ranks the passage holding its figure and words, which the vector leg alone ranks below topK', async () => { + const adapter: IKnowledgeAdapter = await make(); + const a = objectSource('kw_unspaced'); + // The other passages hold the question's characters one by one, so a + // bag-of-words embedder ranks them first, and none of its words. + const spread = ['a', 'b', 'c', 'd', 'e'].map((n) => + doc(a, `spread_${n}`, `出 差 住 宿 费 超 标 部 门 经 理 审 批 情 况 ${n}`), + ); + await adapter.upsert([...spread, doc(a, 'clause', '采购单笔金额2000元以下除外,其余一律公开招标')], ctxOf(a)); + const hits = await adapter.search('出差住宿费超标的话2000元以下除外的情况还要部门经理审批吗', { source: a, topK: 3 }); + expect(hits.map((h) => h.documentId)).toContain(`${a.name}:clause`); + }); + }); + } + if (opts.implements.organizationIds) { describe('organizationIds (ADR-0161 K8, item 9)', () => { /** B's document outranks A's; a third document carries no organization. */ From b511770162f97084e11ca8c87188fe5a62846a3c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 03:25:44 +0000 Subject: [PATCH 2/5] chore(changeset): 38411 CJK keyword pieces Claude-Session: https://claude.ai/code/session_01FEkQ5pfJqySEaVD3CKvevm Co-Authored-By: Claude --- .changeset/38411-cjk-keyword-pieces.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .changeset/38411-cjk-keyword-pieces.md diff --git a/.changeset/38411-cjk-keyword-pieces.md b/.changeset/38411-cjk-keyword-pieces.md new file mode 100644 index 00000000000..d3a05ee00fb --- /dev/null +++ b/.changeset/38411-cjk-keyword-pieces.md @@ -0,0 +1,16 @@ +--- +'@objectstack/knowledge-turso': patch +'@objectstack/knowledge-pgvector': patch +'@objectstack/service-knowledge': patch +--- + +fix(knowledge): the keyword leg of hybrid search ranks passages for a Chinese, Japanese or Korean question written without spaces + +Clause-②: yes (widening) +Metadata-protocol: none + +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. + +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. + +`@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. From 923c0092709d6b0a14e49a0f720cba51d177627c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:00:59 +0000 Subject: [PATCH 3/5] perf(knowledge-pgvector): match a caseless keyword piece by LIKE, not ILIKE A substring term with no cased letter (a Han, kana or Hangul piece, a figure) gains nothing from ILIKE's case folding and costs about five times as much per row read; it is matched by LIKE, and a term holding a cased letter keeps ILIKE. Both READMEs describe the pieces and the operator. Claude-Session: https://claude.ai/code/session_01FEkQ5pfJqySEaVD3CKvevm Co-Authored-By: Claude --- .changeset/38411-cjk-keyword-pieces.md | 2 +- packages/plugins/knowledge-pgvector/README.md | 2 +- .../src/__tests__/keyword-terms.test.ts | 49 +++++++++++++++++-- .../src/pgvector-adapter.ts | 9 ++-- .../plugins/knowledge-pgvector/src/sql.ts | 18 +++++-- packages/plugins/knowledge-turso/README.md | 2 +- 6 files changed, 69 insertions(+), 13 deletions(-) diff --git a/.changeset/38411-cjk-keyword-pieces.md b/.changeset/38411-cjk-keyword-pieces.md index d3a05ee00fb..85462be9043 100644 --- a/.changeset/38411-cjk-keyword-pieces.md +++ b/.changeset/38411-cjk-keyword-pieces.md @@ -11,6 +11,6 @@ Metadata-protocol: none 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. -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. +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. `@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. diff --git a/packages/plugins/knowledge-pgvector/README.md b/packages/plugins/knowledge-pgvector/README.md index 472b1909a3e..726f6f9fba5 100644 --- a/packages/plugins/knowledge-pgvector/README.md +++ b/packages/plugins/knowledge-pgvector/README.md @@ -58,7 +58,7 @@ The next call retries; no restart is needed. A database the plugin cannot reach 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. -- **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_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. +- **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_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. - **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). - **Vector leg.** An exact cosine scan; a passage whose cosine similarity is not positive is not ranked by it. diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts index bb74912dbfd..b34f7468b9d 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts @@ -1,10 +1,14 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. // The keyword leg's terms, without a database: the same rule as the libSQL -// store's, pinned with the same cases, and how each kind of term is matched. +// store's, pinned with the same cases, and how each kind of term is matched, +// down to the operator in the statement a search sends. import { describe, expect, it } from 'vitest'; -import { isWordTerm, keywordTerms } from '../sql.js'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import { PgvectorKnowledgeAdapter, type PgPoolLike } from '../index.js'; +import { containsOperator, isWordTerm, keywordTerms } from '../sql.js'; +import { FakeEmbedder } from './live-pg.testkit.js'; describe('knowledge-pgvector keywordTerms', () => { it('splits a query into terms at white space and punctuation, keeping a code whole', () => { @@ -36,9 +40,48 @@ describe('knowledge-pgvector keywordTerms', () => { expect(keywordTerms('휴가는')).toEqual(['휴가는', '휴가', '가는']); }); - it('matches a piece by ILIKE and a figure or a code of three characters or more on the tsvector', () => { + it('matches a piece as a substring and a figure or a code of three characters or more on the tsvector', () => { expect(keywordTerms('住宿费2000元以下').map((t) => [t, isWordTerm(t)])).toEqual([ ['2000', true], ['住宿费', false], ['元以下', false], ['住宿', false], ['宿费', false], ['元以', false], ['以下', false], ]); }); + + it('matches a substring term without a cased letter by LIKE, and one holding a cased letter by ILIKE', () => { + for (const term of ['元以下', '出差', 'コー', '휴가', '42']) expect(containsOperator(term)).toBe('LIKE'); + for (const term of ['ab', 'X-200', 'É']) expect(containsOperator(term)).toBe('ILIKE'); + }); +}); + +describe('knowledge-pgvector keyword leg statement', () => { + const source = { name: 'kw', label: 'kw', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource; + + /** A store with one stable active generation, which records each ranking statement and its values. */ + function recordingPool(): { pool: PgPoolLike; ranked: Array<{ text: string; values: unknown[] }> } { + const ranked: Array<{ text: string; values: unknown[] }> = []; + const answer = async (text: string, values: unknown[] = []): Promise<{ rows: R[] }> => { + if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.0' }] as R[] }; + if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] as R[] }; + if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) { + return { rows: [{ generation: 1, fingerprint: 'fp', recipe_hash: 'rh', dim: 384, state: 'active' }] as R[] }; + } + if (text.includes('AS distance')) ranked.push({ text, values }); + return { rows: [] as R[] }; + }; + return { pool: { query: answer, connect: async () => ({ query: answer, release: () => undefined }) }, ranked }; + } + + it('sends a caseless Chinese piece as content LIKE and a cased Latin term as content ILIKE', async () => { + const { pool, ranked } = recordingPool(); + const adapter = new PgvectorKnowledgeAdapter({ id: 'kw', pool, embedder: new FakeEmbedder() }); + await adapter.search('出差 ab', { source, topK: 5, index: { fingerprint: 'fp', recipeHash: 'rh' } }); + expect(ranked).toHaveLength(1); + const { text, values } = ranked[0]; + // The operator in front of the placeholder a pattern is bound to, read from the statement itself. + const operatorOf = (pattern: string): string | undefined => { + const at = values.indexOf(pattern) + 1; + return at === 0 ? undefined : new RegExp(`content (I?LIKE) \\$${at}::text`).exec(text)?.[1]; + }; + expect(operatorOf('%出差%')).toBe('LIKE'); + expect(operatorOf('%ab%')).toBe('ILIKE'); + }); }); diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 458f89fbd54..fbc0e2efe86 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -19,6 +19,7 @@ import { PASSAGE_TSVECTOR, SAFE_IDENTIFIER, TS_CONFIG, + containsOperator, containsPattern, isWordTerm, keywordIndexDdl, @@ -189,7 +190,8 @@ interface Readiness { * passage's `simple` `tsvector`, which a GIN expression index serves; a * shorter term (「出差」), or one holding a Han, kana or Hangul character — * which the parser never splits, so a `tsvector` holds the whole run as one - * word — by `ILIKE` over the rows in scope. A passage's keyword score sums, + * word — as a substring over the rows in scope: by `LIKE` for a term + * without a cased letter, by `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 term most passages hold weighs little. * @@ -668,8 +670,9 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { onCandidate.push(`v.tsv @@ ${query}`); } else { params.push(containsPattern(term)); - onRow.push(`content ILIKE $${params.length}::text`); - onCandidate.push(`c.content ILIKE $${params.length}::text`); + const op = containsOperator(term); + onRow.push(`content ${op} $${params.length}::text`); + onCandidate.push(`c.content ${op} $${params.length}::text`); } } const idf = onCandidate diff --git a/packages/plugins/knowledge-pgvector/src/sql.ts b/packages/plugins/knowledge-pgvector/src/sql.ts index 9cfcdb8978b..26c13bb1586 100644 --- a/packages/plugins/knowledge-pgvector/src/sql.ts +++ b/packages/plugins/knowledge-pgvector/src/sql.ts @@ -131,13 +131,13 @@ export function keywordIndexDdl(schema: string, dimensions: number): string { */ export const MAX_KEYWORD_TERMS = 16; -/** The shortest term (in characters) matched on the `tsvector`; a shorter one is matched by `ILIKE`. */ +/** The shortest term (in characters) matched on the `tsvector`; a shorter one is matched as a substring ({@link containsOperator}). */ export const WORD_MIN_CHARS = 3; /** * A character the `simple` parser does not split a run of text at: Han, * Hiragana, Katakana and Hangul. A run of them is one `tsvector` word, so a - * term holding one is matched by `ILIKE`, as a substring, never as a word. + * term holding one is matched as a substring ({@link containsOperator}), never as a word. */ export const UNSEGMENTED = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u; @@ -199,16 +199,26 @@ export function keywordTerms(query: string): string[] { return terms; } -/** Whether a term is matched on the `tsvector` (a word of three characters or more the parser splits), not by `ILIKE`. */ +/** Whether a term is matched on the `tsvector` (a word of three characters or more the parser splits), not as a substring. */ export function isWordTerm(term: string): boolean { return [...term].length >= WORD_MIN_CHARS && !UNSEGMENTED.test(term); } -/** An `ILIKE` pattern that holds `term` anywhere, its `%`, `_` and `\\` matched literally (the default escape). */ +/** A `LIKE` / `ILIKE` pattern that holds `term` anywhere, its `%`, `_` and `\\` matched literally (the default escape). */ export function containsPattern(term: string): string { return `%${term.replace(/[\\%_]/g, (c) => `\\${c}`)}%`; } +/** + * The operator a term not matched on the `tsvector` is matched by: `LIKE` for + * a term without a cased letter (a piece of Han, kana or Hangul, a figure), + * where the case folding of `ILIKE` can find nothing more and costs several + * times as much on every row it reads; `ILIKE` for a term holding one. + */ +export function containsOperator(term: string): 'LIKE' | 'ILIKE' { + return term.toLowerCase() === term.toUpperCase() ? 'LIKE' : 'ILIKE'; +} + /** The text a vector is bound as: pgvector's `[x,y,…]` literal. */ export function vectorLiteral(vector: readonly number[]): string { return `[${vector.map((x) => (Number.isFinite(x) ? String(x) : '0')).join(',')}]`; diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index edb881b94f9..b7380be2aa8 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -51,7 +51,7 @@ On a file the store sets WAL and a busy timeout: without them a second process w Two legs, 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. -- **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` and `v1.2` are one term each (at most 16 terms). A term of three characters or more is matched as one quoted FTS5 phrase in the passage table's trigram index — so `X-200` is text, never FTS5 syntax, and 「住宿标准」 matches inside 「员工出差住宿标准」. A shorter term, which a trigram index cannot match (「出差」), is matched by `content LIKE '%…%'` over the rows in scope. 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. There is no word segmentation: a Chinese question is one term unless it holds spaces or punctuation, so the keyword leg finds a code, a name or a phrase as written, and the vector leg answers the question's meaning. +- **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` and `v1.2` are one term each (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 term of three characters or more is matched as one quoted FTS5 phrase in the passage table's trigram index — so `X-200` is text, never FTS5 syntax, and 「住宿标准」 matches inside 「员工出差住宿标准」. A shorter term, which a trigram index cannot match (「出差」), is matched by `content LIKE '%…%'` over the rows in scope. 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. There is no dictionary segmentation: the pieces find a code, a name or a phrase as written, and the vector leg answers the question's meaning. - **Keyword index.** Each passage table `knowledge__g` has one beside it: a map table `…-kw`, a contentless FTS5 table `…-fts` (`tokenize='trigram'`) and three triggers that keep both in step with every insert, rewrite and removal of a passage, inside the statement that writes it. It is made with the table and dropped with it. A table made by a release without one gets it at its first search, built from the rows it holds in one transaction; until then nothing else changes. Its names hold a hyphen, which no source, generation or object name can, and an object under one of them that the store did not make is never dropped or used: the generation is refused `SERVICE_UNAVAILABLE`, naming it. - **Vector leg.** Passages ranked by the cosine distance of their stored vector (`vector_distance_cos`); a passage whose cosine similarity is not positive is not ranked by it. Its ranks 1…`topK` feed the fusion, whichever of the two ways below found the passages. From 81be16f5b8ffa34947c1def033d4603066c3fd76 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:03:18 +0000 Subject: [PATCH 4/5] test(knowledge-pgvector): the statement pin passes the index fingerprint alone Claude-Session: https://claude.ai/code/session_01FEkQ5pfJqySEaVD3CKvevm Co-Authored-By: Claude --- .../knowledge-pgvector/src/__tests__/keyword-terms.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts index b34f7468b9d..e72fcb0db02 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/keyword-terms.test.ts @@ -73,7 +73,7 @@ describe('knowledge-pgvector keyword leg statement', () => { it('sends a caseless Chinese piece as content LIKE and a cased Latin term as content ILIKE', async () => { const { pool, ranked } = recordingPool(); const adapter = new PgvectorKnowledgeAdapter({ id: 'kw', pool, embedder: new FakeEmbedder() }); - await adapter.search('出差 ab', { source, topK: 5, index: { fingerprint: 'fp', recipeHash: 'rh' } }); + await adapter.search('出差 ab', { source, topK: 5, index: { fingerprint: 'fp' } }); expect(ranked).toHaveLength(1); const { text, values } = ranked[0]; // The operator in front of the placeholder a pattern is bound to, read from the statement itself. From cde0bbe28a47e3cbeac3947796bdf287315b24b0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:04:17 +0000 Subject: [PATCH 5/5] docs(knowledge): the keyword legs cut a CJK run into pieces; pgvector matches a caseless piece by LIKE; the contract's keywordLeg case Claude-Session: https://claude.ai/code/session_01FEkQ5pfJqySEaVD3CKvevm Co-Authored-By: Claude --- content/docs/protocol/knowledge.mdx | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index fe293cc7d3a..30ff15fd66b 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -546,7 +546,8 @@ one that does not keeps receiving whole documents, and a `whole` document over the embedder's budget is removed and reported; and the index fingerprint of §3.6 — that every call carries one, that a write or a search under another is refused by code, a complete reindex as one build, and, for an adapter that -keeps generations, the switch at the end of a build. `implements` declares the optional members, and the suite +keeps generations, the switch at the end of a build; and, for an adapter that declares the optional +`keywordLeg`, an unspaced Chinese question that ranks the passage holding its figure and words. `implements` declares the optional members, and the suite checks the declaration against the adapter. `./testing` is a test-only, ESM-only entry that imports `vitest`; nothing in the runtime entry reaches it. `knowledge-memory` runs it as the reference implementation; `knowledge-pgvector` @@ -727,7 +728,9 @@ an exact scan. scan by cosine distance, so any width works — including a 3072-wide model — and a keyword leg on `to_tsvector('simple', content)` (a GIN expression index), a word of three characters or more as a phrase, a shorter term or - one in Han, kana or Hangul script by `ILIKE`. The organization filter, the + one in Han, kana or Hangul script as a substring (`LIKE` for a term without + a cased letter, `ILIKE` otherwise); a run of Han, kana or Hangul in the + query is cut into overlapping pieces of three characters and of two. The organization filter, the [record scope](#record-scope) and the metadata `filter` (equality per key) are one `WHERE`, run in both legs before either ranks. `queryPrefix` is put before every query before it is embedded, for a model @@ -794,7 +797,9 @@ large source of one organization, through an approximate index. at most `topK`) before the service's re-check: a vector leg by cosine distance (an exact scan, or the approximate index below), and a keyword leg in a contentless FTS5 trigram index beside each passage table (kept in step by triggers), a term of three characters or - more as a quoted phrase, a shorter one by `LIKE`. The organization filter, + more as a quoted phrase, a shorter one by `LIKE`; a run of Han, kana or + Hangul in the query is cut into overlapping pieces of three characters and + of two. The organization filter, the [record scope](#record-scope) and the metadata `filter` (JSON equality per key) are one `WHERE`, run in both legs. Without the approximate index the vector leg reads every row in scope: 1,000 passages of 1,536 dimensions take 8.3 MB and a search about