Skip to content

Commit fc7bdeb

Browse files
feat(knowledge-pgvector): a changed fingerprint builds a new generation and switches to it (#37492)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg3zXREECfPtgrM8TPQaxn1v)_ Fixes #37101 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 用 PostgreSQL 存知识库的部署,换了嵌入模型或切分设置后,重建会在旧索引旁边建一套新索引,建好才切过去,旧的分批删掉;以前这种情况会拒绝重建、要运维手工清表。 - 属于「知识库平台」大项的第二阶段,替自建 PostgreSQL 的部署解决换模型后必须手工清索引的问题。 - 出错时最坏是重建期间该知识源检索一直返回「重建中」或旧索引未删干净占空间,不会返回新旧模型混排的错结果;这个包的改动可以直接撤回。 - 无。 ## What changes `@objectstack/knowledge-pgvector` builds a new generation beside the active one when the index fingerprint changes, and switches to it (ADR-0161 K7, rules 1 to 4). Before, `beginBuild` under a new fingerprint was refused and the reindex result carried hand-run SQL that cleared the source. - **Generations.** The generation table holds one `active` and at most one `building` generation per source (two unique partial indexes, created `IF NOT EXISTS` on the next boot), plus `retired` ones being deleted. Passage tables are unchanged: they are per vector width and already keyed by generation. - **`beginBuild`** takes the builder lock, then: same fingerprint as the active one, rebuild in place; same as the one under construction, take it up (resumed with what it holds); otherwise retire any unfinished one and open a new `building` generation numbered past every generation the source has. Orphan passages (generation row deleted by hand) are deleted before any generation opens, as the first generation already did. - **Writes** go to the generation of the fingerprint they carry: during a build, the walk and event-sync writes carry the new one and land in the new generation only. Each write share-locks its generation row inside its transaction, so a switch or a retirement waits for it, and a write that finds its generation retired is planned again. - **Search** under the new fingerprint while its generation is building answers `KNOWLEDGE_REBUILD_REQUIRED` (409), message "is being rebuilt" (the same code and wording as knowledge-turso). The ranking statement holds only while its generation is active (an `EXISTS` on the generation row in the same statement), and a search that meets a switch runs again, at most three times; the third answers an error rather than an empty result. - **`completeBuild`** (the service calls it after the walk and its single purge) retires the active generation and activates the new one in one transaction, then deletes the retired generation's passages in batches of `deleteBatchSize` rows (default 1000) and its row last. A deletion that stops is logged at `warn` and finished by the next build; a retired generation is never read. - **One builder per source:** a PostgreSQL session advisory lock (key: 64 bits of a hash of schema and source id) held from `beginBuild` to `completeBuild` on a connection outside the pool (`PgPoolLike.connectSession`, provided by `poolFromPg`). A second builder gets `LOCK_CONFLICT` (409, standard catalog), so its walk reads and embeds nothing. Freed on completion, on process or connection death (PostgreSQL), after `buildLockIdleMs` (15 minutes) without a call of the build itself (calls with reason `reindex`; event-sync writes do not hold it), and on plugin `destroy`. It is a session lock, so the store needs a direct or session-mode PostgreSQL connection: a transaction-mode pooler breaks it. When `pg_advisory_unlock` answers false (the session no longer held the lock), the release is logged at `warn` and names that requirement. A crashed build is **resumable**: the next build under the same fingerprint keeps what was written and the walk skips it by document hash. - **Fresh database.** Two sessions that ran `CREATE EXTENSION IF NOT EXISTS vector` at the same moment: the loser failed on the catalogue's unique key, and `ready()` refused although the extension existed. It now re-reads the extension after a failed create and refuses only when it is still missing (pre-existing, seen as a flaky first reindex on a fresh database while the live suite ran its files in parallel). - **New exports, all optional (widening):** adapter options `buildLockIdleMs`, `deleteBatchSize`, `logger`; `PgPoolLike.connectSession`; `PgvectorKnowledgeAdapter.close()`. The changeset stays `patch` and carries the same `Clause-②` line. - No contract member is added: `beginBuild`, `completeBuild`, `indexStatus.building` and `ctx.index` are ADR-0161 K8 item 8, already on main. No error code is added. `service-knowledge` needs no change: its walk already calls `beginBuild`, purges once and calls `completeBuild`. - Docs: a "Generations" subsection in `content/docs/ai/knowledge-rag.mdx`, and one bullet in its pgvector section. The "Rebuilds" section of `packages/plugins/knowledge-pgvector/README.md` (it ships in the npm tarball) and the "Rebuilds" bullet of `content/docs/protocol/knowledge.mdx` section 4.1 now describe generations; the hand-run clear-SQL instructions are gone (claim amend 7187694971). All three say the builder lock needs a direct or session-mode connection. ## Tests - New file `generations.live-postgres.test.ts` (live PostgreSQL + pgvector, the package's existing live pattern): same width with the model changed, through `KnowledgeService` (generation 2 built beside generation 1; search during the build refused "being rebuilt"; an event-sync write during the build lands only in generation 2 and is present after the switch; purge 0; generation 1 deleted; reading `current`). Also: two concurrent builds (one builds, the other gets `LOCK_CONFLICT` and embeds nothing); a build whose session is terminated is resumed by another adapter with its passage kept; the idle release while event-sync writes keep arriving (they do not extend the lock; released after `buildLockIdleMs`); batched deletion (5 rows at batch 2 = 3 statements) and abandoning a generation for a third fingerprint. - New file `builder-lock.test.ts` (no database): a release whose `pg_advisory_unlock` answers false logs one warning naming the direct or session-mode connection; one that answers true logs nothing. - Contract suite: `generations: true` for pgvector (it was `false`, pending this card). - `acceptance.live-postgres.test.ts`: two cases that pinned the retired behaviour (reindex refused with hand-run clear SQL; `beginBuild` under another fingerprint refused) are rewritten to the new behaviour. The case that ran the printed clear SQL is removed, because that SQL is no longer printed. The rebuild-required remedy is pinned to say "complete reindex" and to carry no `DELETE FROM`, `DROP` or `TRUNCATE`. ## Acceptance notes - Fixed in this PR (dc620cd): the README "Rebuilds" section and the protocol section 4.1 "Rebuilds" bullet said the store does not yet build a second generation and printed clear SQL. Both now describe the generations behaviour, after the claim amend added the two files to the surface. Left as is, being generic and still true: protocol section 3.6's sentence about an adapter that does not keep generations. - The builder lock is held on a dedicated session for the whole build. A walk that fails on a process that keeps running keeps it until `buildLockIdleMs` passes; another process is refused `LOCK_CONFLICT` meanwhile, and that refusal's remedy says when it frees. Fencing a build that lost its lock mid-walk is #37465 (service lease), not this PR. - Carried, not fixed here (seat note 7188645663): N1 (fencing a builder that lost its lock) goes to #37465. N2, a `building` generation that stays after the fingerprint is reverted to the active one, is deleted at the next build under another fingerprint; until then it holds rows and is never read. N4, two sweeps of the same retired generation at once, can leave passage rows behind when one deletes the generation row first; the sweep no longer sees them (it walks generation rows); they are never read, and the orphan cleanup deletes them when the source next opens a generation. N3 (that third error carries no code): giving it `CONCURRENT_MODIFICATION` (409) pins a code that `scripts/error-status-unpinned-baseline.json` lists as unpinned, and `check:error-status-conformance` then requires that row to be removed. The file is outside the claim surface, so the code was taken back out; it needs a one-line claim amend. Protocol section 9's table row is outside the claim surface and left as is. - A second builder that took over after an idle release writes the same documents under the same fingerprint into the same generation, so the index stays correct; only embedding spend is doubled. ## Verification Read first, by risk: `pgvector-adapter.ts` `completeBuild` and `sweepRetired` (the switch and the batched delete), `searchAttempt` (the `EXISTS` guard and the retry), `takeBuilderLock` and `releaseBuilderLock`. Two-minute check: with `OS_TEST_POSTGRES_URL` pointing at a PostgreSQL that has pgvector, run `pnpm --filter @objectstack/knowledge-pgvector exec vitest run src/__tests__/generations.live-postgres.test.ts`. You should see 5 passed, among them the idle release under event-sync writes and the "model changed" case that is refused "being rebuilt" mid-build. <details><summary>Local test runs (head 06d53aa; PostgreSQL 16.16 + pgvector 0.8.7, a local instance, fresh database)</summary> - Package suite with the live files on, `vitest run --maxWorkers=2 --reporter=verbose` under the verify lock: `Test Files 6 passed (6)`, `Tests 75 passed (75)`, lock VERDICT command-exit 0. All 5 generation cases and both builder-lock cases passed. Run at tree 06d53aa (the same tree as d1c735dce, whose commits were reworded only), plus `not-ready.test.ts` 11/11 with the new race case. - `pnpm typecheck` and `pnpm build` of the package: exit 0, check-dts-emitted 2/2. - Correction: the runs reported at bc0cab4 and dc620cd as "pgvector 0.8" were on pgvector 0.6.0. Every run since fb4146c is on 0.8.7, the version the CI live job uses. </details> <details><summary>Ablations (each restored, git diff empty afterwards)</summary> - A: writes no longer go to the generation under construction. Red: 3 failed of 5 (model changed; session died and resumed; batches and third fingerprint). - B: the advisory lock answer is ignored. Red: 2 failed of 5 (two concurrent builds; idle release). - C: one delete batch only. Red: 1 failed of 5 (batched deletion). - D (round 3): event-sync calls touch the lock again (`reason` check removed). Red: 1 failed of 5, the idle release while event-sync writes arrive. - E (round 3): no re-read after a failed CREATE EXTENSION. Red: 1 failed of 11 in `not-ready.test.ts`, the lost-race case. </details> <details><summary>Derived gates (dispatch-gates, 102 families over the whole change)</summary> `--ran` reconciliation at 06d53aa: 102 derived, 100 run, 2 NOT-MEASURED, 0 unrun. The two are PREREQUISITE NOT MET (exit 3) on this checkout: `check-plugin-teardown-shape --self-test` (shallow clone) and `spec check:skill-examples` (client-react not built). This round ran 98 families for the round-3 paths, then 61 again for the adapter and changeset after the last code change, and 6 more for `not-ready.test.ts`. One went red in between: `check:error-status-conformance`, which N3's `CONCURRENT_MODIFICATION` tripped (see Acceptance notes). It is green after that code was taken out. `overlap-check`: clean against origin/main 54ea3c8, #37477 and #37442. PR check-runs at 06d53aa: 53 completed, 38 success, 15 skipped, 0 failure. The CI check-runs are the authority. The live pgvector job (`Temporal Conformance`) runs in the merge queue, not on the PR. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ)_ <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6Cb4BAjgQ43tqy1DvVJ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c8e9bec commit fc7bdeb

13 files changed

Lines changed: 1001 additions & 192 deletions
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@objectstack/knowledge-pgvector': patch
3+
---
4+
5+
feat(knowledge-pgvector): a changed fingerprint builds a new generation beside the active one and switches to it
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: none
9+
10+
ADR-0161 K7, rules 1 to 4, for the PostgreSQL store.
11+
12+
- **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.
13+
- **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.
14+
- **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.
15+
- **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`.
16+
- **New exports, all optional (widening).** On the adapter's options: `buildLockIdleMs`, `deleteBatchSize` and `logger`. On `PgPoolLike`: `connectSession`. On the adapter: `close()`.
17+
- **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.
18+
- 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.

‎content/docs/ai/knowledge-rag.mdx‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,16 @@ Known residual: text made mostly of random hex or base64 — UUIDs, sha256 diges
220220

221221
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).
222222

223+
### Generations: the new index is built beside the old one
224+
225+
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:
226+
227+
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.
228+
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`.
229+
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.
230+
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.
231+
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.
232+
223233
## The first build, and rebuilding a source
224234

225235
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:
@@ -258,6 +268,7 @@ new KnowledgePgvectorPlugin({ queryPrefix: '' /* e.g. BGE's query instruction */
258268

259269
- It searches by an exact scan, so a 3072-wide model works; the organization filter and the metadata `filter` run in SQL before ranking.
260270
- An unchanged passage is not sent to the embedder again on a reindex.
271+
- 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)).
261272
- 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.
262273
- It stores each passage's text, which is as sensitive as the record it came from and is in every backup.
263274

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -558,13 +558,25 @@ an exact scan.
558558
that embeds questions and passages differently.
559559
- **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is
560560
not embedded again; its row's metadata is rewritten.
561-
- **Rebuilds.** A changed fingerprint is refused (§3.6). This store does not
562-
yet build a second generation beside the first: `beginBuild` under a new
563-
fingerprint is refused, and the reindex result carries the exact
564-
statements that clear the source — one `DELETE` per passage table, then
565-
the generation row — after which a complete reindex builds it afresh. A
566-
first generation never takes over passage rows left behind without a
567-
generation row: they are deleted when it opens.
561+
- **Rebuilds.** A write or a search under another fingerprint is refused
562+
(§3.6). `beginBuild` under a new fingerprint opens a generation beside the
563+
active one, so a complete reindex rebuilds the source with nothing cleared
564+
by hand. The walk and the event-sync writes of the build carry the new
565+
fingerprint and land in the new generation only. A search during the build
566+
is refused `KNOWLEDGE_REBUILD_REQUIRED`, saying the source is being
567+
rebuilt. `completeBuild` makes the new generation active and retires the
568+
old one in one transaction. It then deletes the old one's passages in
569+
batches (`deleteBatchSize`, default 1,000) and its row last; a deletion
570+
that stops is finished by the next build. One builder per source: a
571+
PostgreSQL advisory lock, held on a connection of its own from
572+
`beginBuild` to `completeBuild`. A second builder is refused
573+
`LOCK_CONFLICT` (409). The lock is freed at completion, when the process or
574+
its connection dies, or after `buildLockIdleMs` (15 minutes) without a
575+
call of the build (event-sync writes do not count). It is a session lock,
576+
so the store needs a direct or session-mode connection, never a
577+
transaction-mode pooler. A stopped build is resumed by the next `beginBuild` under the same
578+
fingerprint, with what it wrote. A generation never takes over passage rows
579+
left without a generation row: they are deleted before any generation opens.
568580
- **An approximate index is an operator's step.** The store creates no
569581
HNSW or IVFFlat index; add one by hand when a table outgrows an exact scan
570582
(`CREATE INDEX ON os_knowledge.knowledge_vec_d1536 USING hnsw (embedding

‎packages/plugins/knowledge-pgvector/README.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,18 @@ pgvector's HNSW index takes at most 2,000 dimensions (`vector` type); a 3072-wid
6262

6363
## Rebuilds
6464

65-
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.
65+
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.
66+
67+
When the fingerprint changes, a complete reindex builds a **new generation** beside the active one; nothing has to be cleared by hand:
68+
69+
- 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.
70+
- 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.
71+
- 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.
72+
- 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).
73+
- **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.
74+
- 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.
75+
76+
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.
6677

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

‎packages/plugins/knowledge-pgvector/src/__tests__/acceptance.live-postgres.test.ts‎

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

1314
import { afterAll, describe, expect, it } from 'vitest';
@@ -162,39 +163,12 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', (
162163
);
163164
expect(refused).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 });
164165
expect(refused?.message).toContain(s.id);
165-
// The caller is told the source needs a rebuild, never the SQL.
166+
// The caller is told the source needs a rebuild, never SQL.
166167
expect(refused?.message).not.toContain('DELETE');
167-
// A complete reindex under the new model is refused before anything is written, naming the SQL that clears the source.
168-
const rebuilt = await svc.reindexSource(s.id);
169-
expect(rebuilt.ok).toBe(false);
170-
expect(rebuilt.message).toContain('DELETE FROM');
171-
});
172-
173-
it('the printed statements clear the source exactly; run as printed, the next complete reindex embeds afresh', async () => {
174-
const embedder = new FakeEmbedder(384, 'model-one');
175-
const adapter = store.adapter({ embedder });
176-
const schema = (adapter as unknown as { schema: string }).schema;
177-
const svc = new KnowledgeService({ dataEngine: rowsEngine([{ id: 'r1', body: 'granite quarry', status: 'published' }]) });
178-
svc.registerAdapter('under_test', adapter);
179-
const s = source('svc_clear');
180-
svc.registerSource(s);
181-
expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 });
182-
183-
embedder.model = 'model-two';
184-
const refused = await svc.reindexSource(s.id);
185-
expect(refused.ok).toBe(false);
186-
const statements = (refused.message ?? '').split('\n').filter((line) => line.startsWith('DELETE FROM'));
187-
// Passages first, then the generation row; every table named exactly.
188-
expect(statements).toEqual([
189-
`DELETE FROM "${schema}"."knowledge_vec_d384" WHERE source_id = '${s.id}';`,
190-
`DELETE FROM "${schema}"."knowledge_generation" WHERE source_id = '${s.id}';`,
191-
]);
192-
for (const statement of statements) await store.pool().query(statement);
193-
168+
// A complete reindex under the new model builds the new generation, and search answers again.
194169
const before = embedder.calls;
195-
expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1 });
170+
expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 1, skipped: 0 });
196171
expect(embedder.calls).toBe(before + 1);
197-
expect(await adapter.indexStatus({ source: s, reason: 'manual' })).toMatchObject({ fingerprint: expect.any(String) });
198172
expect(await svc.search('granite', { topK: 3, executionContext: SYSTEM })).toHaveLength(1);
199173
});
200174

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

255-
it('beginBuild under another fingerprint is refused with the SQL that clears the source; under its own it is a no-op', async () => {
229+
it('beginBuild under its own fingerprint opens nothing; a search under another is refused and never served', async () => {
256230
const adapter = store.adapter();
257231
const s = source('build');
258232
await adapter.upsert([doc(s, '1', 'granite quarry')], ctx(s, FP_A));
259233
await expect(adapter.beginBuild(ctx(s, FP_A))).resolves.toBeUndefined();
260-
const err = await adapter.beginBuild(ctx(s, FP_B)).then(
234+
expect(await adapter.indexStatus(ctx(s))).toEqual({ fingerprint: FP_A.fingerprint });
235+
await adapter.completeBuild(ctx(s, FP_A));
236+
const err = await adapter.search('granite', { source: s, topK: 3, index: { fingerprint: FP_B.fingerprint } }).then(
261237
() => undefined,
262-
(e: unknown) => e as { code?: string; message?: string; remedy?: string },
238+
(e: unknown) => e as { code?: string; status?: number; message?: string; remedy?: string },
263239
);
264-
expect(err).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 });
240+
expect(err).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409, message: expect.stringContaining('needs a rebuild') });
265241
expect(err?.message).not.toContain('DELETE');
266-
expect(err?.remedy).toContain(`WHERE source_id = '${s.id}'`);
267-
// Nothing was served from, or written to, the stored generation under B.
268-
await expect(adapter.search('granite', { source: s, topK: 3, index: { fingerprint: FP_B.fingerprint } })).rejects.toMatchObject({
269-
code: KNOWLEDGE_REBUILD_REQUIRED,
270-
});
271-
expect(await adapter.indexStatus(ctx(s))).toEqual({ fingerprint: FP_A.fingerprint });
242+
// The operator's remedy is a complete reindex, never statements to run by hand.
243+
expect(err?.remedy).toContain('complete reindex');
244+
expect(err?.remedy).not.toMatch(/DELETE FROM|DROP |TRUNCATE/);
245+
expect(await adapter.indexStatus(ctx(s))).toEqual({ fingerprint: FP_A.fingerprint, recipeHash: FP_A.recipeHash });
272246
});
273247

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

0 commit comments

Comments
 (0)