Skip to content
Merged
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
17 changes: 17 additions & 0 deletions .changeset/knowledge-hybrid-search.md
Original file line number Diff line number Diff line change
@@ -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 (`<table>-kw`, `<table>-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<width>_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.
13 changes: 11 additions & 2 deletions content/docs/ai/knowledge-rag.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down Expand Up @@ -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.
Expand All @@ -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`.

Expand Down
24 changes: 16 additions & 8 deletions content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -702,9 +706,13 @@ the `embedder` it is given), and answers a search by an exact scan.
`knowledge_<source>_g<n>`, its vector column sized for that generation
(`<source>` 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
Expand Down Expand Up @@ -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

Expand Down
10 changes: 9 additions & 1 deletion packages/plugins/knowledge-pgvector/README.md
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<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 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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -288,3 +288,110 @@ function rowsEngine(rows: Array<Record<string, unknown>>) {
},
} 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<number> {
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<Parameters<typeof adapter.search>[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();
}
});
});
Loading
Loading