Skip to content
Merged
18 changes: 18 additions & 0 deletions .changeset/37101-pgvector-generations.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@objectstack/knowledge-pgvector': patch
---

feat(knowledge-pgvector): a changed fingerprint builds a new generation beside the active one and switches to it

Clause-②: yes (widening)
Metadata-protocol: none

ADR-0161 K7, rules 1 to 4, for the PostgreSQL store.

- **A new generation, built beside the old one.** Before, a complete reindex under a new index fingerprint (another embedding model, other dimensions, another split) was refused, and its result carried the statements that clear the source by hand. Now `beginBuild` opens a generation under construction beside the active one. The walk writes into it, and so do the event-sync writes that arrive during the build: they carry the new fingerprint. Nothing is written into the active generation under another fingerprint.
- **Search during the build** is refused `KNOWLEDGE_REBUILD_REQUIRED` (409) with the message that the source is being rebuilt. It is never answered from the old generation. `indexStatus` answers `building: true` while a generation is under construction.
- **The switch.** `completeBuild`, after the walk and its single purge, makes the new generation active and retires the old one in one transaction. The old one's passages are then deleted in batches of 1,000 rows (`deleteBatchSize` on the adapter), and its row last. A deletion that stops part-way is finished by the source's next build; a retired generation is never searched. A search that meets the switch reads the new generation.
- **One builder per source.** `beginBuild` takes a PostgreSQL session advisory lock on the source, on a connection of its own outside the pool (`PgPoolLike.connectSession`, which `poolFromPg` provides), and holds it until `completeBuild`. A second build from another process is refused `LOCK_CONFLICT` (409) before it reads or writes anything. The lock is freed when the build completes, when the process or its connection dies, or after 15 minutes without a call of the build itself (`buildLockIdleMs` on the adapter). Event-sync writes do not extend it. The plugin frees every lock it holds when it is destroyed. The lock is a session advisory lock: the store needs a direct or session-mode PostgreSQL connection, never a transaction-mode pooler. A release whose session no longer held the lock is logged at `warn`.
- **New exports, all optional (widening).** On the adapter's options: `buildLockIdleMs`, `deleteBatchSize` and `logger`. On `PgPoolLike`: `connectSession`. On the adapter: `close()`.
- **A build that stops is resumable.** The generation under construction is kept with what it holds. The next `beginBuild` under the same fingerprint takes it up, and the walk skips every document it already holds unchanged. A build under a third fingerprint abandons the unfinished generation and deletes it.
- The refusal's `remedy` no longer carries SQL: a complete reindex is the remedy. The generation table gains two unique partial indexes (one active and one building generation per source), created with `IF NOT EXISTS` on the next boot.
11 changes: 11 additions & 0 deletions content/docs/ai/knowledge-rag.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,16 @@ Known residual: text made mostly of random hex or base64 — UUIDs, sha256 diges

Vectors from two embedding models are not comparable, and neither are the passages of two splits. So every source's index is built under one **index fingerprint** — the embedding model and dimensions the adapter reports, the resolved split, and the content list — which the knowledge service computes and carries on every write and every search, and the adapter checks against the index it holds. Change any of them and the source's stored index is **refused** (`KNOWLEDGE_REBUILD_REQUIRED`, 409) until a complete reindex rebuilds it — which the next boot starts by itself, or `os knowledge rebuild` (below) does now; it never answers with vectors of the old model ranked against the new one. A search over several sources still answers from the others, and the `search_knowledge` tool names each refused source in `refused`. Changing `where` or `metadataFields` changes no vector: a complete reindex repairs it in place. The full rules are in [the protocol's fingerprint section](/docs/protocol/knowledge#36-the-index-fingerprint).

### Generations: the new index is built beside the old one

A store that keeps **generations** (pgvector and Turso) does not throw the old index away when the fingerprint changes. The rebuild fills a new generation beside it, and the switch happens only when the build is done:

1. **The build writes into the new generation.** The complete reindex writes every document into it. Record changes that arrive while it runs (event sync) carry the new fingerprint, so they also land in the new generation only. Nothing is written into the old one under the new model.
2. **Search during the build is refused, never answered from the old index.** A search of the source answers `KNOWLEDGE_REBUILD_REQUIRED` (409) and says the source *is being rebuilt*. A search over several sources still answers from the others, and `search_knowledge` names this one in `refused`.
3. **At the end, the switch.** Once the walk is done, the purge runs once. Then the new generation becomes the active one, and the old one is deleted. pgvector deletes it in batches of 1,000 rows, so no long lock is held over a large source. If the deletion stops part-way, the source's next build finishes it, and the old rows are never searched meanwhile.
4. **One builder per source.** pgvector takes a PostgreSQL advisory lock on the source when its build begins and holds it until the switch. A second build of the source, from another node or process, is refused `LOCK_CONFLICT` (409) and walks nothing. This is a *session* lock, so the store needs a direct or session-mode PostgreSQL connection. Behind a transaction-mode pooler (PgBouncer transaction pooling, or a hosted provider's pooled URL), the lock does not stay with the store's session. Point the store's `url` at a direct or session-mode endpoint. A release whose session no longer held the lock is logged as a warning.
5. **A build that stops is resumed, not restarted.** The generation under construction is kept, with everything written into it so far. The next build under the same fingerprint takes it up, and skips every document it already holds unchanged, so only the rest is sent to the embedding provider. If the process stops, PostgreSQL frees the lock at once. If the build fails on a process that keeps running, the lock is freed after 15 minutes without a call of the build itself. Record events that keep arriving for the source do not hold it. A build under yet another fingerprint abandons the unfinished generation and deletes it.

## The first build, and rebuilding a source

Event sync keeps an index in step with rows as they are written; it never indexes the rows a source matched before it was mounted. So after every boot the knowledge service reads what each source's adapter holds and builds, once, in the background, every `object` source that needs it — the boot never waits for it:
Expand Down Expand Up @@ -258,6 +268,7 @@ 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.
- 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.
- It stores each passage's text, which is as sensitive as the record it came from and is in every backup.

Expand Down
26 changes: 19 additions & 7 deletions content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -558,13 +558,25 @@ an exact scan.
that embeds questions and passages differently.
- **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is
not embedded again; its row's metadata is rewritten.
- **Rebuilds.** A changed fingerprint is refused (§3.6). This store does not
yet build a second generation beside the first: `beginBuild` under a new
fingerprint is refused, and the reindex result carries the exact
statements that clear the source — one `DELETE` per passage table, then
the generation row — after which a complete reindex builds it afresh. A
first generation never takes over passage rows left behind without a
generation row: they are deleted when it opens.
- **Rebuilds.** A write or a search under another fingerprint is refused
(§3.6). `beginBuild` under a new fingerprint opens a generation beside the
active one, so a complete reindex rebuilds the source with nothing cleared
by hand. The walk and the event-sync writes of the build carry the new
fingerprint and land in the new generation only. A search during the build
is refused `KNOWLEDGE_REBUILD_REQUIRED`, saying the source is being
rebuilt. `completeBuild` makes the new generation active and retires the
old one in one transaction. It then deletes the old one's passages in
batches (`deleteBatchSize`, default 1,000) and its row last; a deletion
that stops is finished by the next build. One builder per source: a
PostgreSQL advisory lock, held on a connection of its own from
`beginBuild` to `completeBuild`. A second builder is refused
`LOCK_CONFLICT` (409). The lock is freed at completion, when the process or
its connection dies, or after `buildLockIdleMs` (15 minutes) without a
call of the build (event-sync writes do not count). It is a session lock,
so the store needs a direct or session-mode connection, never a
transaction-mode pooler. A stopped build is resumed by the next `beginBuild` under the same
fingerprint, with what it wrote. A generation never takes over passage rows
left without a generation row: they are deleted before any generation opens.
- **An approximate index is an operator's step.** The store creates no
HNSW or IVFFlat index; add one by hand when a table outgrows an exact scan
(`CREATE INDEX ON os_knowledge.knowledge_vec_d1536 USING hnsw (embedding
Expand Down
13 changes: 12 additions & 1 deletion packages/plugins/knowledge-pgvector/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,18 @@ pgvector's HNSW index takes at most 2,000 dimensions (`vector` type); a 3072-wid

## Rebuilds

Every source's index is built under one index fingerprint (the embedding model and dimensions, the split, the content list — ADR-0161 K7). A write or a search under another fingerprint is refused `KNOWLEDGE_REBUILD_REQUIRED` (409) and never served from the stored vectors. This store does not yet build a second generation beside the first: when the fingerprint changes, a complete reindex is refused, and its result carries the exact statements that clear the source — one `DELETE` per passage table, then the generation row. Run them as printed, and reindex. A first generation never takes over passage rows left without a generation row: they are deleted when it opens, so deleting only the generation row cannot carry old vectors into the new index.
Every source's index is built under one index fingerprint (the embedding model and dimensions, the split, the content list — ADR-0161 K7). A write or a search under another fingerprint is refused `KNOWLEDGE_REBUILD_REQUIRED` (409) and never served from the stored vectors.

When the fingerprint changes, a complete reindex builds a **new generation** beside the active one; nothing has to be cleared by hand:

- The reindex writes into the new generation, and so do the event-sync writes that arrive while it runs: they carry the new fingerprint. Nothing is written into the active generation under the new one.
- A search of the source during the build is refused `KNOWLEDGE_REBUILD_REQUIRED`, saying the source is being rebuilt. It is never answered from the old generation.
- When the walk and its purge are done, the new generation becomes the active one and the old one is retired, in one transaction. The old one's passages are then deleted in batches of 1,000 rows (`deleteBatchSize` on the adapter), and its generation row last. A deletion that stops part-way is finished by the source's next build; a retired generation is never searched.
- One builder per source: a build holds a PostgreSQL advisory lock on the source, on a connection of its own, from its start to the switch. A second build from another process is refused `LOCK_CONFLICT` (409). The lock is freed when the build completes, when the process or its connection dies, or after 15 minutes without a call of the build itself (`buildLockIdleMs`; record events that arrive meanwhile do not count).
- **The lock needs a direct or session-mode connection.** It is a PostgreSQL *session* advisory lock. Behind a connection pooler in transaction mode (PgBouncer's transaction pooling, or the pooled URL some hosted PostgreSQL services give you), the lock is not held by the store's session, so it can stay held with no build running, or fail to keep a second builder out. Give the store a direct URL or a session-mode one (the `url` option, else `OS_DATABASE_URL`). When the build ends and its session no longer holds the lock, the plugin logs a warning that says so.
- A build that stops is resumed: the next build under the same fingerprint takes up the generation under construction with what it holds, and skips every document it already holds unchanged. A build under yet another fingerprint abandons it and deletes it.

A generation never takes over passage rows left without a generation row (a generation row deleted by hand, its passages not): they are deleted before any generation opens, so old vectors cannot be carried into a new index.

A passage whose text is unchanged is not embedded again on a reindex.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
* The acceptance cases of #37100 on a LIVE PostgreSQL with pgvector, beside
* the contract suite: a 3072-wide model, two organizations that never see each
* other's passages, an unchanged passage that is not embedded again, a changed
* fingerprint that is refused and never served, the printed statements that
* clear a source run as printed, a first generation that never adopts rows left
* behind, a passage removed under a concurrent write that is not lost, and the
* store's tables kept out of the connection's own schema.
* fingerprint that is refused and never served until a complete reindex has
* built its generation, a first generation that never adopts rows left behind,
* a passage removed under a concurrent write that is not lost, and the store's
* tables kept out of the connection's own schema. The generation cases of
* #37101 are in `generations.live-postgres.test.ts`.
*/

import { afterAll, describe, expect, it } from 'vitest';
Expand Down Expand Up @@ -162,39 +163,12 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', (
);
expect(refused).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 });
expect(refused?.message).toContain(s.id);
// The caller is told the source needs a rebuild, never the SQL.
// The caller is told the source needs a rebuild, never SQL.
expect(refused?.message).not.toContain('DELETE');
// A complete reindex under the new model is refused before anything is written, naming the SQL that clears the source.
const rebuilt = await svc.reindexSource(s.id);
expect(rebuilt.ok).toBe(false);
expect(rebuilt.message).toContain('DELETE FROM');
});

it('the printed statements clear the source exactly; run as printed, the next complete reindex embeds afresh', async () => {
const embedder = new FakeEmbedder(384, 'model-one');
const adapter = store.adapter({ embedder });
const schema = (adapter as unknown as { schema: string }).schema;
const svc = new KnowledgeService({ dataEngine: rowsEngine([{ id: 'r1', body: 'granite quarry', status: 'published' }]) });
svc.registerAdapter('under_test', adapter);
const s = source('svc_clear');
svc.registerSource(s);
expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 });

embedder.model = 'model-two';
const refused = await svc.reindexSource(s.id);
expect(refused.ok).toBe(false);
const statements = (refused.message ?? '').split('\n').filter((line) => line.startsWith('DELETE FROM'));
// Passages first, then the generation row; every table named exactly.
expect(statements).toEqual([
`DELETE FROM "${schema}"."knowledge_vec_d384" WHERE source_id = '${s.id}';`,
`DELETE FROM "${schema}"."knowledge_generation" WHERE source_id = '${s.id}';`,
]);
for (const statement of statements) await store.pool().query(statement);

// A complete reindex under the new model builds the new generation, and search answers again.
const before = embedder.calls;
expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 });
expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1, skipped: 0 });
expect(embedder.calls).toBe(before + 1);
expect(await adapter.indexStatus({ source: s, reason: 'manual' })).toMatchObject({ fingerprint: expect.any(String) });
expect(await svc.search('granite', { topK: 3, executionContext: SYSTEM })).toHaveLength(1);
});

Expand Down Expand Up @@ -252,23 +226,23 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', (
expect(hit).toMatchObject({ documentId: `${s.id}:1`, metadata: { status: 'archived' } });
});

it('beginBuild under another fingerprint is refused with the SQL that clears the source; under its own it is a no-op', async () => {
it('beginBuild under its own fingerprint opens nothing; a search under another is refused and never served', async () => {
const adapter = store.adapter();
const s = source('build');
await adapter.upsert([doc(s, '1', 'granite quarry')], ctx(s, FP_A));
await expect(adapter.beginBuild(ctx(s, FP_A))).resolves.toBeUndefined();
const err = await adapter.beginBuild(ctx(s, FP_B)).then(
expect(await adapter.indexStatus(ctx(s))).toEqual({ fingerprint: FP_A.fingerprint });
await adapter.completeBuild(ctx(s, FP_A));
const err = await adapter.search('granite', { source: s, topK: 3, index: { fingerprint: FP_B.fingerprint } }).then(
() => undefined,
(e: unknown) => e as { code?: string; message?: string; remedy?: string },
(e: unknown) => e as { code?: string; status?: number; message?: string; remedy?: string },
);
expect(err).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 });
expect(err).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409, message: expect.stringContaining('needs a rebuild') });
expect(err?.message).not.toContain('DELETE');
expect(err?.remedy).toContain(`WHERE source_id = '${s.id}'`);
// Nothing was served from, or written to, the stored generation under B.
await expect(adapter.search('granite', { source: s, topK: 3, index: { fingerprint: FP_B.fingerprint } })).rejects.toMatchObject({
code: KNOWLEDGE_REBUILD_REQUIRED,
});
expect(await adapter.indexStatus(ctx(s))).toEqual({ fingerprint: FP_A.fingerprint });
// The operator's remedy is a complete reindex, never statements to run by hand.
expect(err?.remedy).toContain('complete reindex');
expect(err?.remedy).not.toMatch(/DELETE FROM|DROP |TRUNCATE/);
expect(await adapter.indexStatus(ctx(s))).toEqual({ fingerprint: FP_A.fingerprint, recipeHash: FP_A.recipeHash });
});

it('keeps its tables in its own schema, never the connection\'s current schema', async () => {
Expand Down
Loading
Loading