diff --git a/.changeset/knowledge-hybrid-search.md b/.changeset/knowledge-hybrid-search.md
new file mode 100644
index 00000000000..a5bb449cb9d
--- /dev/null
+++ b/.changeset/knowledge-hybrid-search.md
@@ -0,0 +1,17 @@
+---
+'@objectstack/knowledge-turso': patch
+'@objectstack/knowledge-pgvector': patch
+---
+
+feat(knowledge-turso, knowledge-pgvector): hybrid search — a keyword leg merged with the vector leg by reciprocal rank fusion
+
+Clause-②: no
+Metadata-protocol: none
+
+A vector alone often ranks a passage that names an exact token — an order number, a model code like `X-200`, a person's name, a short term like 「出差」 — below `topK`. Both open stores now search with two legs and merge them by reciprocal rank fusion (`k` = 60, each leg at most `topK`) before the knowledge service re-checks each hit as the caller. The organization filter, the record scope and the metadata `filter` are one `WHERE`, run in both legs before either ranks.
+
+- **Terms.** The query is split at white space and punctuation; a hyphen, dot, slash, underscore, `#`, `@` or `+` inside a term keeps it whole (at most 16 terms). A passage's keyword score sums the BM25 inverse document frequency, among the rows in scope, of the terms it holds.
+- **`@objectstack/knowledge-turso`.** A term of three characters or more is one quoted FTS5 phrase (so `X-200` is never FTS5 syntax) in a contentless trigram index beside each passage table (`
-kw`, `
-fts`), kept in step by triggers on every write and removal and dropped with the table. A shorter term is matched by `LIKE` over the rows in scope. A passage table made by an earlier release gets its keyword index at its first search, built from its rows in one transaction.
+- **`@objectstack/knowledge-pgvector`.** A word of three characters or more is a phrase on `to_tsvector('simple', content)`, served by a GIN expression index on each passage table (`knowledge_vec_d_content_tsv`). A shorter term, or one holding a Han, kana or Hangul character (the parser keeps a run of them as one word), is matched by `ILIKE`. A passage table made by an earlier release gets the index from the first write or search of its width; `CREATE INDEX` blocks writes to that table while it builds.
+
+A hit's `score` is now the fused rank, normalized to `(0, 1]`: 1 for a passage first in both legs, 0.5 for one first in only one. It was the cosine similarity; anything that compared it with a fixed threshold reads it again. Nothing to migrate.
diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx
index 499a52f7233..ae89f71bb45 100644
--- a/content/docs/ai/knowledge-rag.mdx
+++ b/content/docs/ai/knowledge-rag.mdx
@@ -125,6 +125,15 @@ the matching records still gets up to `topK` hits
hit's `title` is the value of the object's display field (`nameField`, else the
derived title field).
+The two open stores, [pgvector](#self-hosted-vector-store-postgresql--pgvector)
+and [libSQL](#local-vector-store-a-libsql-file), search with two legs: the
+vector leg ranks by meaning, and a keyword leg ranks the passages that hold the
+query's terms as written — an order number, a model code like `X-200`, a
+person's name, a short term like 「出差」 — which a vector alone can rank
+below `topK`. The two rankings are merged by reciprocal rank fusion, so a hit's
+`score` is 1 for a passage first in both and 0.5 for one first in only one, and
+the merge happens before the permission re-check.
+
```ts
const knowledge = ctx.getService('knowledge');
@@ -345,7 +354,7 @@ os knowledge rebuild support_articles # start a complete build and follow its p
new KnowledgePgvectorPlugin({ queryPrefix: '' /* e.g. BGE's query instruction */ }),
```
-- It searches by an exact scan, so a 3072-wide model works; the organization filter and the metadata `filter` run in SQL before ranking.
+- It searches with two legs merged by reciprocal rank fusion: an exact cosine scan, so a 3072-wide model works, and a keyword match on a `simple` `tsvector` (a GIN index), with `ILIKE` for a term under three characters or one in Chinese, Japanese or Korean script. The organization filter, the record scope and the metadata `filter` run in SQL in both legs, before ranking.
- An unchanged passage is not sent to the embedder again on a reindex.
- When the embedding model, its dimensions or the split change, it builds the new index beside the old one under a builder lock, then switches to it ([generations](#generations-the-new-index-is-built-beside-the-old-one)).
- Without the `vector` extension (or the right to create it), boot goes on: the plugin warns with the SQL a database owner runs, and its sources answer `SERVICE_UNAVAILABLE` until then.
@@ -361,7 +370,7 @@ Details — the tables, an approximate index as an operator's step, rebuilds —
new KnowledgeTursoPlugin(), // or { url: 'file:/var/lib/app/knowledge.db' }, ':memory:', a libsql:// URL
```
-- It searches by an exact scan; the organization filter, the record scope and the metadata `filter` run in SQL before ranking. 10,000 passages of 1,536 dimensions take about 82 MB and a search about 50 ms; larger sources belong on pgvector.
+- It searches with two legs merged by reciprocal rank fusion: an exact cosine scan, and a keyword match in an FTS5 trigram index beside each passage table, with `LIKE` for a term under three characters (「出差」). The organization filter, the record scope and the metadata `filter` run in SQL in both legs, before ranking. 10,000 passages of 1,536 dimensions take about 82 MB and a search about 50 ms; larger sources belong on pgvector.
- A changed model or split is rebuilt beside the old index, which keeps answering until the reindex completes.
- Where libSQL has no native build (Windows on ARM), boot goes on and its sources answer `SERVICE_UNAVAILABLE`.
diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx
index a1042f86659..70901fc3ea7 100644
--- a/content/docs/protocol/knowledge.mdx
+++ b/content/docs/protocol/knowledge.mdx
@@ -641,10 +641,14 @@ an exact scan.
needed after. A database it cannot reach is reported as unreachable, with
no SQL. A caller reads one sentence; the driver's text and the SQL go only
to the operator — the health check, the boot warning and the log.
-- **Search.** An exact scan by cosine distance, so any width works —
- including a 3072-wide model. The organization filter, the
+- **Search.** Two legs in one statement, merged by reciprocal rank fusion
+ (`k` = 60, each leg at most `topK`) before the service's re-check: an exact
+ 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
[record scope](#record-scope) and the metadata `filter` (equality per key)
- run in the same `WHERE`, before ranking.
+ are one `WHERE`, run in both legs before either ranks.
`queryPrefix` is put before every query before it is embedded, for a model
that embeds questions and passages differently.
- **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is
@@ -702,9 +706,13 @@ the `embedder` it is given), and answers a search by an exact scan.
`knowledge__g`, its vector column sized for that generation
(`` is the source's index key). A key that is not snake_case is
refused before any SQL.
-- **Search.** An exact scan by cosine distance; the organization filter, the
- [record scope](#record-scope) and the metadata `filter` (JSON equality per
- key) run in the same `WHERE`, before ranking. The store creates no DiskANN index: `vector_top_k` ranks
+- **Search.** Two legs merged by reciprocal rank fusion (`k` = 60, each leg
+ at most `topK`) before the service's re-check: an exact scan by cosine
+ distance, 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,
+ the [record scope](#record-scope) and the metadata `filter` (JSON equality
+ per key) are one `WHERE`, run in both legs before either ranks. The store creates no DiskANN index: `vector_top_k` ranks
before it filters, and with one, 1,000 vectors of 1,536 dimensions grew a
file from 8.2 MB to 329 MB and took 21.8 s to index. Without it the same
1,000 passages take 8.3 MB and a search about 5 ms; 10,000 take 82 MB and
@@ -1184,8 +1192,8 @@ followed (§4.1, §4.2) are the adapters to run in production.
| Audit + metrics | ⏳ Phase 2 | |
| `knowledge-llamaindex` | ⏳ Phase 2 | |
| `knowledge-dify` | ⏳ Phase 3 / community | |
-| `knowledge-pgvector` | ✅ | PostgreSQL + pgvector; exact scan, organization, record scope and metadata filter in SQL, index fingerprint (§4.1) |
-| `knowledge-turso` | ✅ | A libSQL file of its own; exact scan, organization, record scope and metadata filter in SQL, a generation built beside the active one (§4.2) |
+| `knowledge-pgvector` | ✅ | PostgreSQL + pgvector; exact scan and a `tsvector` keyword leg merged by RRF, organization, record scope and metadata filter in SQL, index fingerprint (§4.1) |
+| `knowledge-turso` | ✅ | A libSQL file of its own; exact scan and an FTS5 trigram keyword leg merged by RRF, organization, record scope and metadata filter in SQL, a generation built beside the active one (§4.2) |
### 7.1 Non-goals for Phase 1
diff --git a/packages/plugins/knowledge-pgvector/README.md b/packages/plugins/knowledge-pgvector/README.md
index 5e35b12d428..472b1909a3e 100644
--- a/packages/plugins/knowledge-pgvector/README.md
+++ b/packages/plugins/knowledge-pgvector/README.md
@@ -1,6 +1,6 @@
# @objectstack/knowledge-pgvector
-`IKnowledgeAdapter` on PostgreSQL with the [pgvector](https://github.com/pgvector/pgvector) extension — the open vector store for self-hosted ObjectStack deployments. It takes the knowledge service's passages, embeds them with the kernel's `embedder` service, stores passages and vectors in PostgreSQL, and answers `search()` by an exact cosine scan.
+`IKnowledgeAdapter` on PostgreSQL with the [pgvector](https://github.com/pgvector/pgvector) extension — the open vector store for self-hosted ObjectStack deployments. It takes the knowledge service's passages, embeds them with the kernel's `embedder` service, stores passages and vectors in PostgreSQL, and answers `search()` with two legs — an exact cosine scan and a keyword match on a `tsvector` — merged by reciprocal rank fusion.
```ts
import { ObjectKernel } from '@objectstack/core';
@@ -54,6 +54,14 @@ CREATE SCHEMA IF NOT EXISTS "os_knowledge";
The next call retries; no restart is needed. A database the plugin cannot reach is reported as unreachable, with the driver's error and no SQL.
+## Search
+
+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 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.
+
## An approximate index is an operator's step
The store creates no approximate index: every search is an exact scan, which is right for small and medium sources and works at any width. When a table outgrows it, add an index by hand:
diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts
index dbf0dd9eadc..9fcf108f83d 100644
--- a/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts
+++ b/packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts
@@ -16,7 +16,7 @@ import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai';
import type { AdapterContext } from '@objectstack/spec/contracts';
import { KnowledgeService } from '@objectstack/service-knowledge';
import type { ExecutionContext } from '@objectstack/spec/kernel';
-import { KNOWLEDGE_REBUILD_REQUIRED, poolFromPg, type PgPoolLike } from '../index.js';
+import { KNOWLEDGE_REBUILD_REQUIRED, PgvectorKnowledgeAdapter, poolFromPg, type PgPoolLike } from '../index.js';
import { FakeEmbedder, PG_URL, liveStore, requireLiveCell } from './live-pg.testkit.js';
requireLiveCell('knowledge-pgvector acceptance');
@@ -288,3 +288,110 @@ function rowsEngine(rows: Array>) {
},
} as never;
}
+
+/**
+ * Hybrid search on a LIVE PostgreSQL: a keyword leg on the passage's `simple`
+ * `tsvector` (a GIN expression index), `ILIKE` for a term under three
+ * characters or one holding a Han character, merged with the vector leg by
+ * reciprocal rank fusion. A hit's score says which legs ranked it: 1 for first
+ * in both, 0.5 for first in one alone. The fake embedder ranks by shared
+ * words, so the fixtures put the exact code where shared words rank it last.
+ */
+describe.skipIf(!PG_URL)('knowledge-pgvector hybrid search on a LIVE PostgreSQL', () => {
+ const hybrid = liveStore('kpg_hybrid');
+ afterAll(() => hybrid.dropAll());
+ const QUESTION = 'What is the warranty of the X-200 pump?';
+ const CODE = 'Seal kit for model X-200, part 7731.';
+ const fillers = (s: KnowledgeSource) =>
+ ['a', 'b', 'c', 'd', 'e', 'f'].map((n) =>
+ doc(s, `filler_${n}`, `What the pump warranty is, and the scope of the pump warranty (${n})`),
+ );
+
+ /** The rank (from 1) the vector leg alone gives `content` among `docs` for `query`. */
+ async function vectorRank(query: string, docs: KnowledgeDocument[], content: string): Promise {
+ const embedder = new FakeEmbedder();
+ const [q, ...vs] = await embedder.embed([query, ...docs.map((d) => d.content)]);
+ const cos = vs.map((v, i) => ({ content: docs[i].content, cos: v.reduce((sum, x, j) => sum + x * q[j], 0) }));
+ cos.sort((a, b) => b.cos - a.cos);
+ return cos.findIndex((c) => c.content === content) + 1;
+ }
+
+ const schemaOf = (adapter: unknown) => (adapter as { schema: string }).schema;
+
+ it('a question naming an exact code finds the passage the vector leg alone ranks below topK', async () => {
+ const adapter = hybrid.adapter();
+ const s = source('codes');
+ const docs = [...fillers(s), doc(s, 'code', CODE)];
+ await adapter.upsert(docs, ctx(s));
+ expect(await vectorRank(QUESTION, docs, CODE)).toBe(7);
+ const hits = await adapter.search(QUESTION, { source: s, topK: 3 });
+ expect(hits).toHaveLength(3);
+ expect(hits.map((h) => h.snippet)).toContain(CODE);
+ const exact = await adapter.search('X-200', { source: s, topK: 1 });
+ expect(exact.map((h) => h.snippet)).toEqual([CODE]);
+ expect(exact[0].score).toBe(1);
+ });
+
+ it('a 2-character Chinese term hits, and so does a longer one inside an unsplit run, both by ILIKE', async () => {
+ const adapter = hybrid.adapter();
+ const s = source('zh_short');
+ await adapter.upsert(
+ [doc(s, '1', '员工出差住宿标准为每晚三百元'), doc(s, '2', '仓库盘点每月一次,由物流部负责'), doc(s, '3', '合同到期前三十天提醒客户续约')],
+ ctx(s),
+ );
+ for (const query of ['出差', '住宿标准']) {
+ const hits = await adapter.search(query, { source: s, topK: 5 });
+ // The fake embedder holds a Han run as one word, so only the keyword leg ranks these.
+ expect(hits.map((h) => [h.documentId, h.score])).toEqual([[`${s.name}:1`, 0.5]]);
+ }
+ });
+
+ it('the organization filter, the record scope and the metadata filter hold in the keyword leg too', async () => {
+ const adapter = hybrid.adapter();
+ const s = source('kw_scope');
+ await adapter.upsert(
+ [
+ doc(s, 'in1', 'grain silo inspection', { organizationId: 'org_a', metadata: { status: 'published' } }),
+ doc(s, 'in2', 'grain silo moisture', { organizationId: 'org_a', metadata: { status: 'published' } }),
+ doc(s, 'out', 'X-200 出差 grain', { organizationId: 'org_b', metadata: { status: 'draft' } }),
+ ],
+ ctx(s),
+ );
+ const ids = async (o: Partial[1]>, query = 'X-200 出差') =>
+ (await adapter.search(query, { source: s, topK: 5, ...o })).map((h) => h.documentId).sort();
+ expect(await ids({})).toContain(`${s.name}:out`);
+ expect(await ids({ organizationIds: ['org_a'] })).toEqual([]);
+ expect(await ids({ scope: [{ kind: 'record', ids: ['in1', 'in2'] }] })).toEqual([]);
+ expect(await ids({ filter: { status: 'published' } })).toEqual([]);
+ expect(await ids({ organizationIds: ['org_a'] }, 'moisture')).toEqual([`${s.name}:in2`]);
+ });
+
+ it('a passage table made before the keyword index gets it at its first search, which answers from it', async () => {
+ const first = hybrid.adapter();
+ const s = source('kw_legacy');
+ await first.upsert([...fillers(s), doc(s, 'code', CODE)], ctx(s));
+ const schema = schemaOf(first);
+ const index = `"${schema}"."knowledge_vec_d384_content_tsv"`;
+ const present = async () =>
+ (await hybrid.pool().query<{ present: string | null }>('SELECT to_regclass($1) AS present', [index])).rows[0].present;
+ // The table as a release without a keyword index left it.
+ await hybrid.pool().query(`DROP INDEX ${index}`);
+ expect(await present()).toBeNull();
+ // A new process on the same schema: its first search makes the index and answers from it.
+ const second = new PgvectorKnowledgeAdapter({ id: 'under_test', pool: poolFromPg(hybrid.pool()), schema, embedder: new FakeEmbedder() });
+ const hits = await second.search(QUESTION, { source: s, topK: 3 });
+ expect(hits.map((h) => h.snippet)).toContain(CODE);
+ expect(await present()).not.toBeNull();
+ // The index serves the leg: with sequential scans priced out, the plan names it.
+ const client = await hybrid.pool().connect();
+ try {
+ await client.query('SET enable_seqscan = off');
+ const plan = await client.query<{ 'QUERY PLAN': string }>(
+ `EXPLAIN SELECT chunk_id FROM "${schema}".knowledge_vec_d384 WHERE to_tsvector('simple'::regconfig, content) @@ phraseto_tsquery('simple'::regconfig, 'X-200')`,
+ );
+ expect(plan.rows.map((r) => r['QUERY PLAN']).join('\n')).toContain('knowledge_vec_d384_content_tsv');
+ } finally {
+ client.release();
+ }
+ });
+});
diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts
index 7fe1e754fce..458f89fbd54 100644
--- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts
+++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts
@@ -16,7 +16,14 @@ import {
DEFAULT_KNOWLEDGE_SCHEMA,
GENERATION_TABLE,
type GenerationState,
+ PASSAGE_TSVECTOR,
SAFE_IDENTIFIER,
+ TS_CONFIG,
+ containsPattern,
+ isWordTerm,
+ keywordIndexDdl,
+ keywordIndexName,
+ keywordTerms,
qualified,
schemaDdl,
vectorLiteral,
@@ -113,6 +120,9 @@ const SEARCH_ATTEMPTS = 3;
/** The standard ADR-0112 code of a search whose source's index was switched under it on every attempt. */
const CONCURRENT_MODIFICATION = 'CONCURRENT_MODIFICATION';
+/** The `k` of reciprocal rank fusion: a passage at rank `r` of a leg adds `1 / (k + r)` to its score. */
+export const RRF_K = 60;
+
/** A generation row: one complete index of one source under one fingerprint. */
interface GenerationRow {
generation: number;
@@ -163,12 +173,30 @@ interface Readiness {
*
* ## Search
*
- * An exact scan by cosine distance — no approximate index, so a 3072-wide
- * model works (pgvector's HNSW index stops at 2000 dimensions; adding one is an
- * operator's step, documented with the package). The organization filter
- * (ADR-0161 K8, item 9) and the metadata-equality `filter` run in the same
- * `WHERE`, before ranking. A passage whose cosine similarity is not positive is
- * not a hit.
+ * Two legs, merged by reciprocal rank fusion (`k` = {@link RRF_K}) before the
+ * knowledge service re-checks each hit as the caller. Each leg ranks at most
+ * `topK` passages; a passage's score is the sum of `1 / (k + rank)` over the
+ * legs that rank it, divided by the score of a passage first in both, so it
+ * lies in `(0, 1]`. Both legs run in one statement, so in one snapshot.
+ *
+ * - The vector leg: an exact scan by cosine distance — no approximate index,
+ * so a 3072-wide model works (pgvector's HNSW index stops at 2000
+ * dimensions; adding one is an operator's step, documented with the
+ * package). A passage whose cosine similarity is not positive is not ranked
+ * by it.
+ * - The keyword leg: the query's terms (`keywordTerms`). A word of three
+ * characters or more is matched as a phrase (`phraseto_tsquery`) on the
+ * 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,
+ * 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.
+ *
+ * The organization filter (ADR-0161 K8, item 9), the record scope (item 17)
+ * and the metadata-equality `filter` are one `WHERE`, run in both legs before
+ * either ranks. The keyword index of a passage table made before it existed
+ * is made by the first call that writes or searches that table.
*
* ## Generations (ADR-0161 K7; K8, item 8)
*
@@ -259,6 +287,8 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
private readiness?: Readiness;
/** Widths whose passage table this adapter has created or found. */
private readonly tables = new Set();
+ /** Widths whose passage table's keyword index this adapter has created or found. */
+ private readonly keyed = new Set();
/** The builder locks this adapter holds, by source id. */
private readonly builders = new Map();
/**
@@ -555,10 +585,17 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
`vector, and this source's index holds ${generation.dim}-wide vectors.`,
);
}
- if (vector.every((x) => x === 0)) return [];
+ const vectorLeg = !vector.every((x) => x === 0);
+ const terms = keywordTerms(query);
+ if (!vectorLeg && terms.length === 0) return [];
+ if (terms.length > 0) await this.ensureKeywordIndex(generation.dim);
const ext = readiness.extensionSchema;
- const params: unknown[] = [opts.source.name, generation.generation, vectorLiteral(vector), topK];
+ const table = qualified(this.schema, vectorTable(generation.dim));
+ // One WHERE for both legs: the source's active generation, the
+ // organization filter, the record scope and the metadata filter, each
+ // bound as values.
+ const params: unknown[] = [opts.source.name, generation.generation];
const where = [
'source_id = $1',
'generation = $2',
@@ -578,29 +615,82 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
// and field names go as bound parameters. A `metadata` term holds for a
// stored string or number equal to an id as text, or a list with such an
// element; a missing value or any other kind holds for nothing.
- const terms: string[] = [];
+ const scopeTerms: string[] = [];
for (const term of opts.scope) {
if (term.ids.length === 0) continue;
params.push(term.ids);
const ids = `$${params.length}::text[]`;
if (term.kind === 'record') {
- terms.push(`source_record_id = ANY(${ids})`);
+ scopeTerms.push(`source_record_id = ANY(${ids})`);
continue;
}
params.push(term.field);
const value = `(metadata -> $${params.length}::text)`;
- terms.push(
+ scopeTerms.push(
`EXISTS (SELECT 1 FROM jsonb_array_elements(CASE jsonb_typeof(${value}) WHEN 'array' THEN ${value} ` +
`ELSE jsonb_build_array(${value}) END) AS e(v) ` +
`WHERE jsonb_typeof(e.v) IN ('string', 'number') AND e.v #>> '{}' = ANY(${ids}))`,
);
}
- where.push(`(${terms.join(' OR ')})`);
+ where.push(`(${scopeTerms.join(' OR ')})`);
}
for (const [key, value] of Object.entries(opts.filter ?? {})) {
params.push(key, JSON.stringify(value === undefined ? null : value));
where.push(`(metadata -> $${params.length - 1}) = $${params.length}::jsonb`);
}
+ const inScope = where.join(' AND ');
+ params.push(topK);
+ const limit = `$${params.length}`;
+
+ const ctes: string[] = [];
+ const legs: string[] = [];
+ let vectorParam = 0;
+ if (vectorLeg) {
+ params.push(vectorLiteral(vector));
+ vectorParam = params.length;
+ ctes.push(`vec AS (
+ SELECT chunk_id, row_number() OVER (ORDER BY distance, chunk_id) AS pos FROM (
+ SELECT chunk_id, embedding OPERATOR(${ext}.<=>) $${params.length}::${ext}.vector AS distance
+ FROM ${table} WHERE ${inScope}
+ ) ranked WHERE distance < 1 ORDER BY distance, chunk_id LIMIT ${limit})`);
+ legs.push('SELECT chunk_id, pos AS vpos, NULL::bigint AS kpos FROM vec');
+ }
+ if (terms.length > 0) {
+ // A term's match, written twice: on the row's columns where the index
+ // can serve it, and on the candidate's tsvector, computed once per row.
+ const onRow: string[] = [];
+ const onCandidate: string[] = [];
+ for (const term of terms) {
+ if (isWordTerm(term)) {
+ params.push(term);
+ const query = `phraseto_tsquery(${TS_CONFIG}, $${params.length}::text)`;
+ onRow.push(`${PASSAGE_TSVECTOR} @@ ${query}`);
+ 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 idf = onCandidate
+ .map((_, i) => `h.h${i} * ln(1.0 + (s.n - s.d${i} + 0.5) / (s.d${i} + 0.5))`)
+ .join(' + ');
+ ctes.push(
+ // Passages of equal keyword score are ranked by cosine distance, so the
+ // keyword leg never reorders by chunk id what the vector leg ranks.
+ `cand AS (SELECT chunk_id, content, ${vectorLeg ? `embedding OPERATOR(${ext}.<=>) $${vectorParam}::${ext}.vector` : '0'} AS distance
+ FROM ${table} WHERE ${inScope} AND (${onRow.join(' OR ')}))`,
+ `hits AS (SELECT c.chunk_id, c.distance, ${onCandidate.map((m, i) => `(${m})::int AS h${i}`).join(', ')}
+ FROM cand c CROSS JOIN LATERAL (SELECT ${PASSAGE_TSVECTOR.replace('content', 'c.content')} AS tsv) v)`,
+ `stats AS (SELECT (SELECT count(*) FROM ${table} WHERE ${inScope}) AS n,
+ ${onCandidate.map((_, i) => `coalesce(sum(h${i}), 0) AS d${i}`).join(', ')} FROM hits)`,
+ `kw AS (
+ SELECT chunk_id, row_number() OVER (ORDER BY score DESC, distance, chunk_id) AS pos FROM (
+ SELECT h.chunk_id, h.distance, ${idf} AS score FROM hits h CROSS JOIN stats s
+ ) scored ORDER BY score DESC, distance, chunk_id LIMIT ${limit})`,
+ );
+ legs.push('SELECT chunk_id, NULL::bigint AS vpos, pos AS kpos FROM kw');
+ }
const result = await pool.query<{
chunk_id: string;
document_id: string;
@@ -610,17 +700,15 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
metadata: Record | null;
doc_hash: string | null;
heading_path: string[] | null;
- distance: number;
+ vpos: string | number | null;
+ kpos: string | number | null;
}>(
- `SELECT * FROM (
- SELECT chunk_id, document_id, source_record_id, content, title, metadata, doc_hash, heading_path,
- embedding OPERATOR(${ext}.<=>) $3::${ext}.vector AS distance
- FROM ${qualified(this.schema, vectorTable(generation.dim))}
- WHERE ${where.join(' AND ')}
- ) ranked
- WHERE distance < 1
- ORDER BY distance, chunk_id
- LIMIT $4`,
+ `WITH ${ctes.join(',\n')}
+ SELECT p.chunk_id, p.document_id, p.source_record_id, p.content, p.title, p.metadata, p.doc_hash,
+ p.heading_path, u.vpos, u.kpos
+ FROM (SELECT chunk_id, min(vpos) AS vpos, min(kpos) AS kpos FROM (${legs.join(' UNION ALL ')}) l
+ GROUP BY chunk_id) u
+ JOIN ${table} p ON p.source_id = $1 AND p.generation = $2 AND p.chunk_id = u.chunk_id`,
params,
);
if (result.rows.length === 0) {
@@ -628,12 +716,12 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
const now = await this.generations(opts.source.name);
if (now.active?.generation !== generation.generation) return undefined;
}
- return result.rows.map((r) => ({
+ return fuse(result.rows, topK).map(({ row: r, score }) => ({
chunkId: r.chunk_id,
documentId: r.document_id,
sourceId: opts.source.name,
...(r.source_record_id === null ? {} : { sourceRecordId: r.source_record_id }),
- score: 1 - Number(r.distance),
+ score,
snippet: r.content,
...(r.title === null ? {} : { title: r.title }),
metadata: r.metadata ?? {},
@@ -927,6 +1015,33 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
);
}
this.tables.add(dimensions);
+ this.keyed.add(dimensions);
+ }
+
+ /**
+ * Makes the keyword index of a passage table made before the store kept one
+ * (`keywordIndexDdl`); a table this adapter made or already checked is
+ * skipped. Two processes making it at once: the one that loses finds it made.
+ */
+ private async ensureKeywordIndex(dimensions: number): Promise {
+ if (this.keyed.has(dimensions)) return;
+ const pool = this.requirePool();
+ const statement = keywordIndexDdl(this.schema, dimensions);
+ try {
+ await pool.query(statement);
+ } catch (err) {
+ const found = await pool
+ .query<{ present: string | null }>('SELECT to_regclass($1) AS present', [qualified(this.schema, keywordIndexName(dimensions))])
+ .catch(() => undefined);
+ if (found?.rows[0]?.present == null) {
+ throw notReady(
+ `the keyword index of its ${dimensions}-wide passage table could not be created`,
+ `Creating ${keywordIndexName(dimensions)} failed (${errorText(err)}).`,
+ [`${statement};`],
+ );
+ }
+ }
+ this.keyed.add(dimensions);
}
private async tableExists(dimensions: number): Promise {
@@ -1253,6 +1368,30 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
}
}
+/**
+ * Reciprocal rank fusion of the two legs' rows (`vpos`, `kpos`: a row's rank
+ * in each leg, or null): best first, at most `topK`; a tie goes to the better
+ * vector rank, then to the chunk id. The score is the fused sum divided by
+ * that of a row first in both legs.
+ */
+function fuse(
+ rows: readonly R[],
+ topK: number,
+): Array<{ row: R; score: number }> {
+ const best = 2 / (RRF_K + 1);
+ const leg = (pos: string | number | null) => (pos === null ? 0 : 1 / (RRF_K + Number(pos)));
+ const vectorRank = (row: R) => (row.vpos === null ? Infinity : Number(row.vpos));
+ return rows
+ .map((row) => ({ row, score: (leg(row.vpos) + leg(row.kpos)) / best }))
+ .sort(
+ (a, b) =>
+ b.score - a.score ||
+ vectorRank(a.row) - vectorRank(b.row) ||
+ (a.row.chunk_id < b.row.chunk_id ? -1 : 1),
+ )
+ .slice(0, topK);
+}
+
/** The passages of a document: the service's `chunks`, or the whole text as one. Empty passages are not stored. */
function passagesOf(doc: KnowledgeDocument): Array<{ id: string; content: string; headingPath?: string[] }> {
const passages: Array<{ id: string; content: string; headingPath?: string[] }> =
diff --git a/packages/plugins/knowledge-pgvector/src/sql.ts b/packages/plugins/knowledge-pgvector/src/sql.ts
index d5f1705e09c..5dd6d58ba33 100644
--- a/packages/plugins/knowledge-pgvector/src/sql.ts
+++ b/packages/plugins/knowledge-pgvector/src/sql.ts
@@ -90,9 +90,81 @@ export function vectorTableDdl(schema: string, dimensions: number, vectorType: s
PRIMARY KEY (source_id, generation, chunk_id)
)`,
`CREATE INDEX IF NOT EXISTS "${table}_document" ON ${qualified(schema, table)} (source_id, generation, document_id)`,
+ keywordIndexDdl(schema, dimensions),
];
}
+/**
+ * The text-search configuration of the keyword leg: `simple` — lower-cased
+ * words, no stemming and no stop words, so a code or a name is matched as it
+ * is written, in any language the parser splits into words.
+ */
+export const TS_CONFIG = `'simple'::regconfig`;
+
+/** The `tsvector` of a passage the keyword leg matches, the expression its GIN index is built on. */
+export const PASSAGE_TSVECTOR = `to_tsvector(${TS_CONFIG}, content)`;
+
+/** The name of the keyword index of the passage table of one width. */
+export function keywordIndexName(dimensions: number): string {
+ return `${vectorTable(dimensions)}_content_tsv`;
+}
+
+/**
+ * The statement that makes the keyword index of the passage table of one
+ * width: a GIN index on {@link PASSAGE_TSVECTOR}. An expression index, so no
+ * column is added and no row is rewritten; PostgreSQL keeps it in step with
+ * every write, delete and drop of the table's rows.
+ */
+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. */
+export const MAX_KEYWORD_TERMS = 16;
+
+/** The shortest term (in characters) matched on the `tsvector`; a shorter one is matched by `ILIKE`. */
+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.
+ */
+export const UNSEGMENTED = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
+
+/**
+ * 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}.
+ * The same rule as the libSQL store's.
+ */
+export function keywordTerms(query: string): string[] {
+ 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;
+ const key = term.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ terms.push(term);
+ if (terms.length === MAX_KEYWORD_TERMS) break;
+ }
+ return terms;
+}
+
+/** Whether a term is matched on the `tsvector` (a word of three characters or more the parser splits), not by `ILIKE`. */
+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). */
+export function containsPattern(term: string): string {
+ return `%${term.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
+}
+
/** 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 960d16215d0..86f64d6280d 100644
--- a/packages/plugins/knowledge-turso/README.md
+++ b/packages/plugins/knowledge-turso/README.md
@@ -1,6 +1,6 @@
# @objectstack/knowledge-turso
-`IKnowledgeAdapter` on [libSQL](https://github.com/tursodatabase/libsql)'s native vectors — the open vector store for local development (`os dev`) and for deployments not on PostgreSQL. It takes the knowledge service's passages, embeds them with the kernel's `embedder` service, stores passages and vectors in a libSQL database of its own, and answers `search()` by an exact cosine scan.
+`IKnowledgeAdapter` on [libSQL](https://github.com/tursodatabase/libsql)'s native vectors — the open vector store for local development (`os dev`) and for deployments not on PostgreSQL. It takes the knowledge service's passages, embeds them with the kernel's `embedder` service, stores passages and vectors in a libSQL database of its own, and answers `search()` with two legs — an exact cosine scan and a keyword match — merged by reciprocal rank fusion.
```ts
import { ObjectKernel } from '@objectstack/core';
@@ -46,7 +46,13 @@ On a file the store sets WAL and a busy timeout: without them a second process w
## Search
-An exact scan by cosine distance (`vector_distance_cos`). The organization filter, the record scope (a passage's record, or a metadata value equal to an id as text, a list matching by any element) and the metadata `filter` (JSON equality per key) run in the same `WHERE`, before ranking — libSQL's DiskANN index (`vector_top_k`) ranks first and filters after, so the store creates none. Measured on Linux x64 with 1,536-wide vectors: 1,000 passages take 8.3 MB and a search about 5 ms; 10,000 passages take 82 MB and a search about 50 ms. (With a DiskANN index the same 1,000 vectors grew a file to 329 MB, and the index build took 21.8 s.) For larger sources, use `@objectstack/knowledge-pgvector`.
+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 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.** An exact scan by cosine distance (`vector_distance_cos`); a passage whose cosine similarity is not positive is not ranked by it.
+
+The organization filter, the record scope (a passage's record, or a metadata value equal to an id as text, a list matching by any element) and the metadata `filter` (JSON equality per key) are one `WHERE`, run in both legs before either ranks — libSQL's DiskANN index (`vector_top_k`) ranks first and filters after, so the store creates none. Measured on Linux x64 with 1,536-wide vectors: 1,000 passages take 8.3 MB and a search about 5 ms; 10,000 passages take 82 MB and a search about 50 ms. (With a DiskANN index the same 1,000 vectors grew a file to 329 MB, and the index build took 21.8 s.) For larger sources, use `@objectstack/knowledge-pgvector`.
## Rebuilds
diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts
index 98b0aa1a012..75c2178714d 100644
--- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts
+++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts
@@ -18,6 +18,7 @@ import type { AdapterContext, IDataEngine, IEmbedder } from '@objectstack/spec/c
import type { ExecutionContext } from '@objectstack/spec/kernel';
import { KnowledgeService } from '@objectstack/service-knowledge';
import { KNOWLEDGE_REBUILD_REQUIRED, TursoKnowledgeAdapter } from '../index.js';
+import { containsPattern, ftsPhrase, keywordTerms } from '../sql.js';
import { FakeEmbedder, storeOf, type StoreKind } from './turso.testkit.js';
const source = (id: string, extra: Record = {}): KnowledgeSource =>
@@ -80,12 +81,23 @@ function rowsEngine(rows: Row[]): IDataEngine {
async function tables(client: Client, like: string): Promise {
const found = await client.execute({
- sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE ? ORDER BY name",
+ // A passage table's keyword index (`
-kw`, `
-fts` and FTS5's
+ // own tables) is read by `keywordObjects`, never here.
+ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE ? AND instr(name, '-') = 0 ORDER BY name",
args: [like],
});
return found.rows.map((r) => String(r.name));
}
+/** The keyword-index objects (map, FTS5 table, triggers) of a passage table, by name. */
+async function keywordObjects(client: Client, table: string): Promise {
+ const found = await client.execute({
+ sql: "SELECT name FROM sqlite_master WHERE name IN (?, ?, ?, ?, ?) ORDER BY name",
+ args: [`${table}-fts`, `${table}-kw`, `${table}-kw-delete`, `${table}-kw-insert`, `${table}-kw-update`],
+ });
+ return found.rows.map((r) => String(r.name));
+}
+
async function refusal(promise: Promise): Promise> {
return promise.then(
() => {
@@ -692,3 +704,174 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
});
});
}
+
+/**
+ * Hybrid search: a keyword leg (an FTS5 trigram index per passage table, and
+ * `LIKE` for a term under three characters) merged with the vector leg by
+ * reciprocal rank fusion. A hit's score says which legs ranked it: 1 for first
+ * in both, 0.5 for first in one alone. The fake embedder ranks by shared
+ * words, so the fixtures put the exact code where shared words rank it last.
+ */
+for (const kind of ['memory', 'file'] as StoreKind[]) {
+ describe(`knowledge-turso hybrid search on ${kind === 'memory' ? ':memory:' : 'a file: URL'}`, () => {
+ const store = storeOf(kind);
+ afterAll(() => store.closeAll());
+ const FP_B = { fingerprint: 'fp-test:b', recipeHash: 'rh-test:1' };
+ const QUESTION = 'What is the warranty of the X-200 pump?';
+ const CODE = 'Seal kit for model X-200, part 7731.';
+ const fillers = (s: KnowledgeSource, extra: Partial = {}) =>
+ ['a', 'b', 'c', 'd', 'e', 'f'].map((n) =>
+ doc(s, `filler_${n}`, `What the pump warranty is, and the scope of the pump warranty (${n})`, extra),
+ );
+
+ /** The rank (from 1) the vector leg alone gives `content` among `docs` for `query`. */
+ async function vectorRank(query: string, docs: KnowledgeDocument[], content: string): Promise {
+ const embedder = new FakeEmbedder();
+ const [q, ...vs] = await embedder.embed([query, ...docs.map((d) => d.content)]);
+ const cos = vs.map((v, i) => ({ content: docs[i].content, cos: v.reduce((sum, x, j) => sum + x * q[j], 0) }));
+ cos.sort((a, b) => b.cos - a.cos);
+ return cos.findIndex((c) => c.content === content) + 1;
+ }
+
+ it('a question naming an exact code finds the passage the vector leg alone ranks below topK', async () => {
+ const adapter = store.adapter();
+ const s = source('codes');
+ const docs = [...fillers(s), doc(s, 'code', CODE)];
+ await adapter.upsert(docs, ctx(s));
+ // The fixture holds: by shared words alone the code's passage is last.
+ expect(await vectorRank(QUESTION, docs, CODE)).toBe(7);
+ const hits = await adapter.search(QUESTION, { source: s, topK: 3 });
+ expect(hits).toHaveLength(3);
+ expect(hits.map((h) => h.snippet)).toContain(CODE);
+ // The code alone: first in the keyword leg, and in the vector leg.
+ const exact = await adapter.search('X-200', { source: s, topK: 1 });
+ expect(exact.map((h) => h.snippet)).toEqual([CODE]);
+ expect(exact[0].score).toBe(1);
+ });
+
+ it('quotes every term as an FTS5 phrase: no query text is FTS5 syntax', async () => {
+ const adapter = store.adapter();
+ const s = source('syntax');
+ await adapter.upsert([doc(s, '1', 'Valve "A" NEAR(the X-200) OR * pump^2'), doc(s, '2', 'grain silo')], ctx(s));
+ for (const query of ['X-200', '"A"', 'NEAR(the', 'OR', '* pump^2', 'col:umn', '-x', 'a AND b NOT c']) {
+ await expect(adapter.search(query, { source: s, topK: 5 })).resolves.toBeInstanceOf(Array);
+ }
+ expect((await adapter.search('NEAR(the X-200)', { source: s, topK: 5 })).map((h) => h.documentId)).toEqual([`${s.name}:1`]);
+ });
+
+ it('a 2-character Chinese term hits by LIKE, a longer one by the trigram index; both in the keyword leg', async () => {
+ const adapter = store.adapter();
+ const s = source('zh_short');
+ await adapter.upsert(
+ [doc(s, '1', '员工出差住宿标准为每晚三百元'), doc(s, '2', '仓库盘点每月一次,由物流部负责'), doc(s, '3', '合同到期前三十天提醒客户续约')],
+ ctx(s),
+ );
+ for (const query of ['出差', '住宿标准']) {
+ const hits = await adapter.search(query, { source: s, topK: 1 });
+ expect(hits.map((h) => h.documentId)).toEqual([`${s.name}:1`]);
+ // First in both legs: the keyword leg ranked it.
+ expect(hits[0].score).toBe(1);
+ }
+ // A term no passage holds ranks nothing in the keyword leg.
+ expect((await adapter.search('报销', { source: s, topK: 5 })).every((h) => h.score < 1)).toBe(true);
+ });
+
+ it('splits a query into terms at white space and punctuation, keeping a code whole', () => {
+ 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);
+ expect(containsPattern('a%_\\b')).toBe('%a\\%\\_\\\\b%');
+ expect(ftsPhrase('say "hi"')).toBe('"say ""hi"""');
+ });
+
+ 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');
+ // The out-of-scope passage holds the code; the in-scope ones share no word with it.
+ await adapter.upsert(
+ [
+ doc(s, 'in1', 'grain silo inspection', { organizationId: 'org_a', metadata: { status: 'published' } }),
+ doc(s, 'in2', 'grain silo moisture', { organizationId: 'org_a', metadata: { status: 'published' } }),
+ doc(s, 'out', 'X-200 出差 grain', { organizationId: 'org_b', metadata: { status: 'draft' } }),
+ ],
+ ctx(s),
+ );
+ const ids = async (o: Partial[1]>, query = 'X-200 出差') =>
+ (await adapter.search(query, { source: s, topK: 5, ...o })).map((h) => h.documentId).sort();
+ // Unfiltered, the code finds it.
+ expect(await ids({})).toContain(`${s.name}:out`);
+ expect(await ids({ organizationIds: ['org_a'] })).toEqual([]);
+ expect(await ids({ scope: [{ kind: 'record', ids: ['in1', 'in2'] }] })).toEqual([]);
+ expect(await ids({ filter: { status: 'published' } })).toEqual([]);
+ // In scope, the keyword leg still ranks: a word of the in-scope passages.
+ expect(await ids({ organizationIds: ['org_a'] }, 'moisture')).toEqual([`${s.name}:in2`]);
+ });
+
+ it('keeps the keyword index in step with every write, removal, rebuild and drop', async () => {
+ const client = store.client();
+ const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() });
+ const s = source('kw_step');
+ const keyword = async (query: string) =>
+ (await adapter.search(query, { source: s, topK: 5 })).filter((h) => h.score === 1).map((h) => h.documentId);
+ await adapter.upsert([doc(s, '1', 'pump model Q-118'), doc(s, '2', 'valve model R-220')], ctx(s));
+ expect(await keyword('Q-118')).toEqual([`${s.name}:1`]);
+ // A rewrite of the text: the old code leaves the index, the new one enters.
+ await adapter.upsert([doc(s, '1', 'pump model Q-119')], ctx(s));
+ expect(await keyword('Q-118')).toEqual([]);
+ expect(await keyword('Q-119')).toEqual([`${s.name}:1`]);
+ // A removed document leaves it.
+ await adapter.delete([`${s.name}:2`], ctx(s));
+ expect(await keyword('R-220')).toEqual([]);
+ expect((await client.execute(`SELECT count(*) AS n FROM "knowledge_${s.name}_g1-kw"`)).rows[0].n).toBe(1);
+ // A rebuild under another fingerprint: the new generation has its own index; the old one goes with its table.
+ await adapter.beginBuild(ctx(s, FP_B));
+ await adapter.upsert([doc(s, '1', 'pump model Q-120')], ctx(s, FP_B));
+ await adapter.completeBuild(ctx(s, FP_B));
+ expect(await keywordObjects(client, `knowledge_${s.name}_g1`)).toEqual([]);
+ expect(await keywordObjects(client, `knowledge_${s.name}_g2`)).toHaveLength(5);
+ expect(
+ (await adapter.search('Q-120', { source: s, topK: 5, index: { fingerprint: FP_B.fingerprint } })).map((h) => h.score),
+ ).toEqual([1]);
+ await adapter.dropSource(ctx(s, FP_B));
+ expect(await keywordObjects(client, `knowledge_${s.name}_g2`)).toEqual([]);
+ expect((await client.execute("SELECT name FROM sqlite_master WHERE name LIKE 'knowledge_kw_step%'")).rows).toEqual([]);
+ });
+
+ it('a passage table made before the keyword index gets one, from its rows, at its first search', async () => {
+ const client = store.client();
+ const s = source('kw_legacy');
+ const before = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() });
+ await before.upsert([...fillers(s), doc(s, 'code', CODE)], ctx(s));
+ // The table as a release without a keyword index left it.
+ const table = `knowledge_${s.name}_g1`;
+ for (const name of ['kw-insert', 'kw-delete', 'kw-update']) await client.execute(`DROP TRIGGER "${table}-${name}"`);
+ await client.execute(`DROP TABLE "${table}-fts"`);
+ await client.execute(`DROP TABLE "${table}-kw"`);
+ expect(await keywordObjects(client, table)).toEqual([]);
+ // A new process: its first search makes the index and answers from it.
+ const after = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() });
+ const hits = await after.search(QUESTION, { source: s, topK: 3 });
+ expect(hits.map((h) => h.snippet)).toContain(CODE);
+ expect(await keywordObjects(client, table)).toHaveLength(5);
+ expect((await client.execute(`SELECT count(*) AS n FROM "${table}-kw"`)).rows[0].n).toBe(7);
+ // And keeps it in step from then on.
+ await after.delete([`${s.name}:code`], ctx(s));
+ expect((await after.search('X-200', { source: s, topK: 5 })).filter((h) => h.score >= 0.5)).toEqual([]);
+ });
+
+ it('an object it did not make under a keyword-index name is never dropped; the generation is refused', async () => {
+ const client = store.client();
+ const s = source('kw_taken');
+ await client.execute(`CREATE TABLE "knowledge_${s.name}_g1-kw" (id TEXT PRIMARY KEY, note TEXT)`);
+ await client.execute(`INSERT INTO "knowledge_${s.name}_g1-kw" VALUES ('r1', 'kept')`);
+ const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() });
+ const refused = await refusal(adapter.upsert([doc(s, '1', 'oak table')], ctx(s)));
+ expect(refused).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
+ expect(String(refused.remedy)).toContain(`knowledge_${s.name}_g1-kw`);
+ expect((await client.execute(`SELECT note FROM "knowledge_${s.name}_g1-kw"`)).rows.map((r) => r.note)).toEqual(['kept']);
+ });
+ });
+}
diff --git a/packages/plugins/knowledge-turso/src/sql.ts b/packages/plugins/knowledge-turso/src/sql.ts
index 40d0cf2dc6c..fd3f5c345fb 100644
--- a/packages/plugins/knowledge-turso/src/sql.ts
+++ b/packages/plugins/knowledge-turso/src/sql.ts
@@ -148,9 +148,148 @@ export function passageTableDdl(table: string, dimensions: number): string[] {
embedding F32_BLOB(${dimensions}) NOT NULL
)`,
`CREATE INDEX ${quoted(`${table}_document`)} ON ${quoted(table)} (document_id)`,
+ ...keywordIndexDdl(table),
];
}
+/**
+ * The names of a passage table's keyword index: a map table (`
-kw`, a
+ * stable integer key per passage), an FTS5 table (`
-fts`, contentless,
+ * trigram-tokenized, keyed by the map's integer) and the three triggers that
+ * keep both in step with every write to the passage table. Each name holds a
+ * hyphen, which no source id, no generation table and no object name can
+ * hold, so none can collide with a table the store did not make.
+ */
+export function keywordNames(table: string): { map: string; fts: string; triggers: [string, string, string] } {
+ return {
+ map: `${table}-kw`,
+ fts: `${table}-fts`,
+ triggers: [`${table}-kw-insert`, `${table}-kw-delete`, `${table}-kw-update`],
+ };
+}
+
+/**
+ * The statements that make a passage table's keyword index ({@link
+ * keywordNames}) and fill it from the rows the table already holds. The FTS5
+ * table is contentless: the text stays in the passage table alone, and a
+ * passage's entry is removed with the FTS5 `delete` command and the text as
+ * it was indexed, which the triggers hold as `old.content`. The map's integer
+ * key is an `INTEGER PRIMARY KEY`, so it survives a `VACUUM` (a passage row's
+ * implicit rowid may not). The triggers fire inside the statement that writes
+ * the passage, so the index never lags a committed write.
+ */
+export function keywordIndexDdl(table: string): string[] {
+ const { map, fts, triggers } = keywordNames(table);
+ const t = quoted(table);
+ const m = quoted(map);
+ const f = quoted(fts);
+ const remove = (row: 'old') =>
+ `INSERT INTO ${f} (${f}, rowid, content) SELECT 'delete', id, ${row}.content FROM ${m} WHERE chunk_id = ${row}.chunk_id;`;
+ return [
+ ...dropKeywordIndexDdl(table),
+ `CREATE TABLE ${m} (id INTEGER PRIMARY KEY, chunk_id TEXT NOT NULL UNIQUE)`,
+ `CREATE VIRTUAL TABLE ${f} USING fts5(content, content='', tokenize='trigram')`,
+ `INSERT INTO ${m} (chunk_id) SELECT chunk_id FROM ${t} ORDER BY chunk_id`,
+ `INSERT INTO ${f} (rowid, content) SELECT k.id, p.content FROM ${m} k JOIN ${t} p ON p.chunk_id = k.chunk_id`,
+ `CREATE TRIGGER ${quoted(triggers[0])} AFTER INSERT ON ${t} BEGIN
+ INSERT INTO ${m} (chunk_id) VALUES (new.chunk_id);
+ INSERT INTO ${f} (rowid, content) SELECT id, new.content FROM ${m} WHERE chunk_id = new.chunk_id;
+END`,
+ `CREATE TRIGGER ${quoted(triggers[1])} AFTER DELETE ON ${t} BEGIN
+ ${remove('old')}
+ DELETE FROM ${m} WHERE chunk_id = old.chunk_id;
+END`,
+ `CREATE TRIGGER ${quoted(triggers[2])} AFTER UPDATE OF chunk_id, content ON ${t}
+ WHEN old.chunk_id IS NOT new.chunk_id OR old.content IS NOT new.content BEGIN
+ ${remove('old')}
+ UPDATE ${m} SET chunk_id = new.chunk_id WHERE chunk_id = old.chunk_id;
+ INSERT INTO ${f} (rowid, content) SELECT id, new.content FROM ${m} WHERE chunk_id = new.chunk_id;
+END`,
+ ];
+}
+
+/** The statements that drop a passage table's keyword index; its triggers go with the passage table or here. */
+export function dropKeywordIndexDdl(table: string): string[] {
+ const { map, fts, triggers } = keywordNames(table);
+ return [
+ ...triggers.map((name) => `DROP TRIGGER IF EXISTS ${quoted(name)}`),
+ `DROP TABLE IF EXISTS ${quoted(fts)}`,
+ `DROP TABLE IF EXISTS ${quoted(map)}`,
+ ];
+}
+
+/** What is found under a passage table's keyword-index names, read from `sqlite_master` rows (`type`, `name`, `sql`). */
+export type KeywordIndexShape = 'none' | 'complete' | 'partial' | 'other';
+
+/**
+ * Reads the shape of a passage table's keyword index: `complete` when the
+ * map, the FTS5 table and the three triggers are all there and are this
+ * module's; `none` when nothing is; `partial` when only some of this module's
+ * are (never left by this module, whose statements run in one transaction,
+ * but rebuilt rather than trusted); `other` when an object under one of those
+ * names is not this module's — never dropped or used.
+ */
+export function keywordIndexShape(
+ table: string,
+ rows: ReadonlyArray>,
+ mapColumns: ReadonlyArray>,
+): KeywordIndexShape {
+ const { map, fts, triggers } = keywordNames(table);
+ const byName = new Map(
+ rows.map((r) => [String(r.name), { type: String(r.type), on: String(r.tbl_name), sql: String(r.sql ?? '') }]),
+ );
+ const found = [map, fts, ...triggers].filter((n) => byName.has(n));
+ if (found.length === 0) return 'none';
+ const mapOk =
+ !byName.has(map) ||
+ (byName.get(map)!.type === 'table' &&
+ mapColumns.map((c) => String(c.name)).sort().join(',') === 'chunk_id,id');
+ const ftsOk = !byName.has(fts) || (byName.get(fts)!.type === 'table' && /USING\s+fts5\s*\(/i.test(byName.get(fts)!.sql));
+ const triggersOk = triggers.every(
+ (n) => !byName.has(n) || (byName.get(n)!.type === 'trigger' && byName.get(n)!.on === table),
+ );
+ if (!mapOk || !ftsOk || !triggersOk) return 'other';
+ return found.length === 2 + triggers.length ? 'complete' : 'partial';
+}
+
+/** The most terms of one query the keyword leg matches; the rest are left to the vector leg. */
+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;
+
+/**
+ * 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}.
+ */
+export function keywordTerms(query: string): string[] {
+ 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;
+ const key = term.toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ terms.push(term);
+ if (terms.length === MAX_KEYWORD_TERMS) break;
+ }
+ return terms;
+}
+
+/** A term as one FTS5 phrase: double-quoted, an inner double quote doubled, so no character of it is FTS5 syntax. */
+export function ftsPhrase(term: string): string {
+ return `"${term.replace(/"/g, '""')}"`;
+}
+
+/** A `LIKE … ESCAPE '\\'` pattern that holds `term` anywhere, its `%`, `_` and `\\` matched literally. */
+export function containsPattern(term: string): string {
+ return `%${term.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
+}
+
/** The text a vector is bound as, for `vector32(?)`: `[x,y,…]`. */
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/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts
index 33e1ec282d3..b99f2149b65 100644
--- a/packages/plugins/knowledge-turso/src/turso-adapter.ts
+++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts
@@ -17,11 +17,20 @@ import {
GENERATION_TABLE,
METADATA_VALUE_JSON,
SCOPE_SCALAR_TYPES,
+ TRIGRAM_MIN_CHARS,
+ type KeywordIndexShape,
type TableShape,
tableShape,
assertSourceId,
+ containsPattern,
+ dropKeywordIndexDdl,
+ ftsPhrase,
generationDdl,
generationTable,
+ keywordIndexDdl,
+ keywordIndexShape,
+ keywordNames,
+ keywordTerms,
legacyTable,
passageTableDdl,
quoted,
@@ -79,6 +88,9 @@ const SEARCH_ATTEMPTS = 3;
/** The standard ADR-0112 code of a search whose source's index was switched under it on every attempt. */
const CONCURRENT_MODIFICATION = 'CONCURRENT_MODIFICATION';
+/** The `k` of reciprocal rank fusion: a passage at rank `r` of a leg adds `1 / (k + r)` to its score. */
+export const RRF_K = 60;
+
/** A generation row: one index of one source under one fingerprint. */
interface GenerationRow {
generation: number;
@@ -184,11 +196,31 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise();
+ /** Passage tables whose keyword index is known to be complete. */
+ private readonly keyed = new Set();
constructor(opts: TursoKnowledgeAdapterOptions) {
this.id = opts.id ?? 'turso';
@@ -505,8 +539,12 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
`vector, and this source's index holds ${active.dim}-wide vectors.`,
);
}
- if (vector.every((x) => x === 0)) return [];
+ const vectorLeg = !vector.every((x) => x === 0);
+ const terms = keywordTerms(query);
+ if (!vectorLeg && terms.length === 0) return [];
+ // One WHERE for both legs: the organization filter, the record scope and
+ // the metadata filter, each bound as values. ?1 is the query vector.
const args: unknown[] = [vectorLiteral(vector)];
const where: string[] = [];
if (opts.organizationIds !== undefined) {
@@ -520,24 +558,24 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
// compared with the stored keys (never put into a JSON path). A
// `metadata` term holds for a stored string or number equal to an id as
// text, or a list with such an element; any other value holds for nothing.
- const terms: string[] = [];
+ const scopeTerms: string[] = [];
for (const term of opts.scope) {
if (term.ids.length === 0) continue;
args.push(JSON.stringify(term.ids));
const ids = `(SELECT value FROM json_each(?${args.length}))`;
if (term.kind === 'record') {
- terms.push(`source_record_id IN ${ids}`);
+ scopeTerms.push(`source_record_id IN ${ids}`);
continue;
}
args.push(term.field);
- terms.push(
+ scopeTerms.push(
`EXISTS (SELECT 1 FROM json_each(metadata) AS m WHERE m.key = ?${args.length} AND (` +
`(m.type IN ${SCOPE_SCALAR_TYPES} AND CAST(m.value AS TEXT) IN ${ids}) OR ` +
`(m.type = 'array' AND EXISTS (SELECT 1 FROM json_each(m.value) AS e ` +
`WHERE e.type IN ${SCOPE_SCALAR_TYPES} AND CAST(e.value AS TEXT) IN ${ids}))))`,
);
}
- where.push(`(${terms.join(' OR ')})`);
+ where.push(`(${scopeTerms.join(' OR ')})`);
}
for (const [key, value] of Object.entries(opts.filter ?? {})) {
args.push(key, JSON.stringify(value === undefined ? null : value));
@@ -545,22 +583,64 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
`EXISTS (SELECT 1 FROM json_each(metadata) WHERE key = ?${args.length - 1} AND ${METADATA_VALUE_JSON} = json(?${args.length}))`,
);
}
+ const inScope = where.length === 0 ? 'TRUE' : where.join(' AND ');
args.push(topK);
- const table = quoted(generationTable(opts.source.name, active.generation));
+ const limit = `?${args.length}`;
+ const tableName = generationTable(opts.source.name, active.generation);
+ const table = quoted(tableName);
+
+ const legs: string[] = [];
+ const ctes: string[] = [];
+ if (vectorLeg) {
+ ctes.push(`vec AS (
+ SELECT chunk_id, row_number() OVER (ORDER BY distance, chunk_id) AS pos FROM (
+ SELECT chunk_id, vector_distance_cos(embedding, vector32(?1)) AS distance FROM ${table} WHERE ${inScope}
+ ) WHERE distance < 1 ORDER BY distance, chunk_id LIMIT ${limit})`);
+ legs.push('SELECT chunk_id, pos AS vpos, NULL AS kpos FROM vec');
+ }
+ if (terms.length > 0) {
+ // A term's match: the trigram index for three characters or more, LIKE
+ // over the rows in scope below that.
+ const { map, fts } = keywordNames(tableName);
+ const matches = terms.map((term) => {
+ if ([...term].length >= TRIGRAM_MIN_CHARS) {
+ args.push(ftsPhrase(term));
+ return `(chunk_id IN (SELECT k.chunk_id FROM ${quoted(fts)} JOIN ${quoted(map)} k ON k.id = ${quoted(fts)}.rowid
+ WHERE ${quoted(fts)} MATCH ?${args.length}))`;
+ }
+ args.push(containsPattern(term));
+ return `(content LIKE ?${args.length} ESCAPE '\\')`;
+ });
+ const idf = matches
+ .map((_, i) => `h${i} * ln(1.0 + (stats.n - stats.d${i} + 0.5) / (stats.d${i} + 0.5))`)
+ .join(' + ');
+ // Passages of equal keyword score are ranked by cosine distance, so the
+ // keyword leg never reorders by chunk id what the vector leg ranks.
+ const distance = vectorLeg ? 'vector_distance_cos(embedding, vector32(?1))' : '0';
+ ctes.push(
+ `cand AS (SELECT chunk_id, ${distance} AS distance, ${matches.map((m, i) => `${m} AS h${i}`).join(', ')}
+ FROM ${table} WHERE ${inScope} AND (${matches.join(' OR ')}))`,
+ `stats AS (SELECT (SELECT count(*) FROM ${table} WHERE ${inScope}) AS n,
+ ${matches.map((_, i) => `coalesce(sum(h${i}), 0) AS d${i}`).join(', ')} FROM cand)`,
+ `kw AS (
+ SELECT chunk_id, row_number() OVER (ORDER BY score DESC, distance, chunk_id) AS pos FROM (
+ SELECT cand.chunk_id, cand.distance, ${idf} AS score FROM cand, stats
+ ) ORDER BY score DESC, distance, chunk_id LIMIT ${limit})`,
+ );
+ legs.push('SELECT chunk_id, NULL AS vpos, pos AS kpos FROM kw');
+ }
const result = await this.queued(client, async () => {
// The generation may have been switched while the query was embedded.
const now = await this.generations(opts.source.name);
if (now.active?.generation !== active.generation) return undefined;
+ if (terms.length > 0) await this.ensureKeywordIndex(tableName);
return client.execute({
- sql: `SELECT * FROM (
- SELECT chunk_id, document_id, source_record_id, content, title, metadata, doc_hash, heading_path,
- vector_distance_cos(embedding, vector32(?1)) AS distance
- FROM ${table}
- ${where.length === 0 ? '' : `WHERE ${where.join(' AND ')}`}
- ) ranked
- WHERE distance < 1
- ORDER BY distance, chunk_id
- LIMIT ?${args.length}`,
+ sql: `WITH ${ctes.join(',\n')}
+ SELECT p.chunk_id, p.document_id, p.source_record_id, p.content, p.title, p.metadata, p.doc_hash,
+ p.heading_path, u.vpos, u.kpos
+ FROM (SELECT chunk_id, min(vpos) AS vpos, min(kpos) AS kpos FROM (${legs.join(' UNION ALL ')})
+ GROUP BY chunk_id) u
+ JOIN ${table} p ON p.chunk_id = u.chunk_id`,
args: args as InArgs,
});
});
@@ -574,14 +654,14 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
}
return this.searchAttempt(query, opts, attempt + 1);
}
- return result.rows.map((r) => {
+ return fuse(result.rows, topK).map(({ row: r, score }) => {
const headingPath = parseJson(r.heading_path);
return {
chunkId: String(r.chunk_id),
documentId: String(r.document_id),
sourceId: opts.source.name,
...(r.source_record_id === null ? {} : { sourceRecordId: String(r.source_record_id) }),
- score: 1 - Number(r.distance),
+ score,
snippet: String(r.content),
...(r.title === null ? {} : { title: String(r.title) }),
metadata: asRecord(parseJson(r.metadata)),
@@ -855,7 +935,67 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
'remove that table, or keep the store in a database of its own.',
);
}
+ await this.assertKeywordIndexOurs(tx, table, sourceId, generation);
await tx.execute(`DROP TABLE IF EXISTS ${quoted(table)}`);
+ for (const statement of dropKeywordIndexDdl(table)) await tx.execute(statement);
+ this.keyed.delete(table);
+ }
+
+ /** The shape of the keyword index of the passage table `table` (`keywordIndexShape`). */
+ private async keywordShapeOf(db: Pick, table: string): Promise {
+ const { map, fts, triggers } = keywordNames(table);
+ const names = [map, fts, ...triggers];
+ const rows = await db.execute({
+ sql: `SELECT type, name, tbl_name, sql FROM sqlite_master WHERE name IN (${names.map(() => '?').join(', ')})`,
+ args: names,
+ });
+ const columns = await db.execute({ sql: 'SELECT name FROM pragma_table_info(?)', args: [map] });
+ return keywordIndexShape(table, rows.rows, columns.rows);
+ }
+
+ /**
+ * Refuses, naming it, an object under one of the keyword-index names of
+ * `table` that this store did not make; the transaction is rolled back with
+ * the refusal, so nothing of the call is removed.
+ */
+ private async assertKeywordIndexOurs(db: Pick, table: string, sourceId: string, generation: number): Promise {
+ if ((await this.keywordShapeOf(db, table)) !== 'other') return;
+ const { map, fts } = keywordNames(table);
+ throw notReady(
+ `an object it did not make holds a name of the keyword index of generation ${generation} of source '${sourceId}'`,
+ `The database holds a table or trigger under '${map}', '${fts}' or a '${table}-kw-*' trigger that is not this ` +
+ `store's keyword index, so it is not dropped, and generation ${generation} of source '${sourceId}' cannot be ` +
+ 'built, replaced or removed. Rename or remove it, or keep the store in a database of its own.',
+ );
+ }
+
+ /**
+ * Makes the keyword index of an active passage table made before the store
+ * kept one, from the rows the table holds, in one write transaction, and
+ * never touches an object of those names the store did not make. Runs inside
+ * the client's queue; known complete tables are skipped.
+ */
+ private async ensureKeywordIndex(table: string): Promise {
+ if (this.keyed.has(table)) return;
+ const client = this.requireClient();
+ if ((await this.keywordShapeOf(client, table)) !== 'complete') {
+ await this.transaction(async (tx) => {
+ // Made by another process between the read and this transaction: kept.
+ const shape = await this.keywordShapeOf(tx, table);
+ if (shape === 'complete') return { commit: false, value: undefined };
+ if (shape === 'other') {
+ throw notReady(
+ `an object it did not make holds a name of the keyword index of '${table}'`,
+ `The database holds a table or trigger under a name of the keyword index of '${table}' that is not this ` +
+ "store's, so the keyword index cannot be made and the table is not searched. Rename or remove it, or " +
+ 'keep the store in a database of its own.',
+ );
+ }
+ for (const statement of keywordIndexDdl(table)) await tx.execute(statement);
+ return { commit: true, value: undefined };
+ });
+ }
+ this.keyed.add(table);
}
/** Opens the next generation of a source: its row, and its table made afresh. */
@@ -886,7 +1026,9 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
'the store in a database of its own.',
);
}
+ await this.assertKeywordIndexOurs(tx, table, sourceId, generation);
for (const statement of passageTableDdl(table, embedder.dimensions)) await tx.execute(statement);
+ this.keyed.add(table);
await tx.execute({
sql: `INSERT INTO ${quoted(GENERATION_TABLE)} (source_id, generation, fingerprint, dim, model, state) VALUES (?, ?, ?, ?, ?, ?)`,
args: [sourceId, generation, fingerprint ?? null, embedder.dimensions, embedder.model ?? null, state],
@@ -952,6 +1094,30 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter {
}
}
+/**
+ * Reciprocal rank fusion of the two legs' rows (`vpos`, `kpos`: a row's rank
+ * in each leg, or null): best first, at most `topK`; a tie goes to the better
+ * vector rank, then to the chunk id. The score is the fused sum divided by
+ * that of a row first in both legs.
+ */
+function fuse>(
+ rows: readonly R[],
+ topK: number,
+): Array<{ row: R; score: number }> {
+ const best = 2 / (RRF_K + 1);
+ const leg = (pos: unknown) => (pos === null || pos === undefined ? 0 : 1 / (RRF_K + Number(pos)));
+ const vectorRank = (row: R) => (row.vpos === null || row.vpos === undefined ? Infinity : Number(row.vpos));
+ return rows
+ .map((row) => ({ row, score: (leg(row.vpos) + leg(row.kpos)) / best }))
+ .sort(
+ (a, b) =>
+ b.score - a.score ||
+ vectorRank(a.row) - vectorRank(b.row) ||
+ (String(a.row.chunk_id) < String(b.row.chunk_id) ? -1 : 1),
+ )
+ .slice(0, topK);
+}
+
/** The passages of a document: the service's `chunks`, or the whole text as one. Empty passages are not stored. */
function passagesOf(doc: KnowledgeDocument): Array<{ id: string; content: string; headingPath?: string[] }> {
const passages: Array<{ id: string; content: string; headingPath?: string[] }> =