Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/38411-cjk-keyword-pieces.md
Original file line number Diff line number Diff line change
@@ -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. 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.
11 changes: 8 additions & 3 deletions content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/plugins/knowledge-pgvector/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<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.
- **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.
- **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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => {
generations: true,
scope: true,
dropSource: true,
keywordLeg: true,
},
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// 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,
// down to the operator in the statement a search sends.

import { describe, expect, it } from 'vitest';
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', () => {
// 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 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 <R>(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' } });
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');
});
});
9 changes: 6 additions & 3 deletions packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
PASSAGE_TSVECTOR,
SAFE_IDENTIFIER,
TS_CONFIG,
containsOperator,
containsPattern,
isWordTerm,
keywordIndexDdl,
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading