From 0bbacd18dd22b91424e1fb4acfa108d8d0f9eeaf Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 08:26:37 +0000 Subject: [PATCH 1/8] feat(knowledge-pgvector): build a new generation beside the active one and switch to it (wip) Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude --- .../src/pgvector-adapter.ts | 596 ++++++++++++++---- .../plugins/knowledge-pgvector/src/plugin.ts | 24 + .../plugins/knowledge-pgvector/src/sql.ts | 11 + 3 files changed, 495 insertions(+), 136 deletions(-) diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 2911b98c9d2..dab3b203054 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -15,6 +15,7 @@ import type { KnowledgeDocument, KnowledgeHit } from '@objectstack/spec/ai'; import { DEFAULT_KNOWLEDGE_SCHEMA, GENERATION_TABLE, + type GenerationState, SAFE_IDENTIFIER, qualified, schemaDdl, @@ -42,6 +43,13 @@ export interface PgClientLike { export interface PgPoolLike { query>(text: string, params?: unknown[]): Promise>; connect(): Promise; + /** + * A connection of its own, outside the pool, which `release` closes. A build + * holds its source's builder lock (a session advisory lock) on one for as + * long as it runs, so a long build never takes a pooled connection from the + * writes. Absent: the lock is held on a pooled connection from `connect`. + */ + connectSession?(): Promise; } /** Options of {@link PgvectorKnowledgeAdapter}. */ @@ -75,20 +83,53 @@ export interface PgvectorKnowledgeAdapterOptions { * of the index fingerprint (ADR-0161 K8, item 15). */ queryPrefix?: string; + /** + * How long a build may go without a call for its source (a page written, + * the listing, a delete) before its builder lock is let go, so a build that + * stopped part-way on a process that keeps running does not keep every + * other process from building the source. A process that stops lets go at + * once. @default 900000 (15 minutes) + */ + buildLockIdleMs?: number; + /** How many passage rows of a replaced generation one DELETE removes. @default 1000 */ + deleteBatchSize?: number; + /** Where the adapter reports what it cannot hand to a caller: an old generation it could not delete. */ + logger?: { warn?(message: string): void }; } /** The ADR-0112 code of a write or a search refused under another fingerprint (ADR-0161 K7, rules 4 and 5). */ export const KNOWLEDGE_REBUILD_REQUIRED = 'KNOWLEDGE_REBUILD_REQUIRED'; +/** The standard ADR-0112 code of a build refused because another process is building the source. */ +const LOCK_CONFLICT = 'LOCK_CONFLICT'; + /** How many times {@link PgvectorKnowledgeAdapter.upsert} plans a batch again when a concurrent write removed a passage it meant to keep. */ const UPSERT_ATTEMPTS = 3; +/** How many times {@link PgvectorKnowledgeAdapter.search} runs again when the active generation was switched under it. */ +const SEARCH_ATTEMPTS = 3; + /** A generation row: one complete index of one source under one fingerprint. */ interface GenerationRow { generation: number; fingerprint: string | null; recipe_hash: string | null; dim: number; + state: GenerationState; +} + +/** A source's generations: the active one, the one under construction, and those being deleted. */ +interface SourceGenerations { + active?: GenerationRow; + building?: GenerationRow; + retired: GenerationRow[]; +} + +/** A source's builder lock this adapter holds: the session it is held on, its key, and its idle timer. */ +interface BuilderLock { + client: PgClientLike; + key: string; + timer?: ReturnType; } /** What the store learned when it became ready. */ @@ -125,19 +166,52 @@ interface Readiness { * `WHERE`, before ranking. A passage whose cosine similarity is not positive is * not a hit. * - * ## The index fingerprint (ADR-0161 K7; K8, item 8) + * ## Generations (ADR-0161 K7; K8, item 8) + * + * A generation row holds the fingerprint its passages were built under. A + * source holds one `active` generation, the one searched, and, while a build + * under another fingerprint runs, one `building` generation beside it — one + * of each per source, by two unique indexes. A source that holds nothing + * takes the first fingerprint it is handed as its active one, and passage + * rows of the source left without a generation row are deleted as any + * generation opens: a generation never adopts vectors of another fingerprint. + * + * - `beginBuild` takes the source's builder lock (below), then: under the + * active fingerprint it rebuilds inside the active generation; under the + * fingerprint of the generation under construction it takes that one up + * with what it already holds (a build is RESUMABLE: the walk skips every + * document whose hash the new generation already holds); under a third it + * retires the one under construction and opens a new one. + * - A write carrying `ctx.index` goes to the generation of that fingerprint: + * during a build, event-sync writes carry the new fingerprint and land in + * the new generation only. A write whose fingerprint neither holds is + * refused `KNOWLEDGE_REBUILD_REQUIRED`, and nothing is written to the + * active generation under another fingerprint. + * - A search carrying another fingerprint than the active one's is refused + * `KNOWLEDGE_REBUILD_REQUIRED` and never answered from the active + * generation; while the generation of the searched fingerprint is under + * construction, the refusal says the source is being rebuilt. + * - `completeBuild`, after the walk and its purge, makes the generation under + * construction active and the old one `retired` in one transaction, then + * deletes the retired generation's passages in batches + * ({@link PgvectorKnowledgeAdapterOptions.deleteBatchSize} rows per + * statement) and its row last. A deletion that stops part-way is finished + * by the source's next build; a retired generation is never searched. + * Under the active fingerprint it records the recipe hash. * - * The generation row holds the fingerprint the source was built under. A write - * or a search carrying another is refused `KNOWLEDGE_REBUILD_REQUIRED` and is - * never served from the stored generation. A source that holds nothing takes - * the first fingerprint it is handed, and passage rows of the source left - * without a generation row are deleted as that generation opens: it never - * adopts vectors of another fingerprint. `beginBuild` under the stored - * fingerprint rebuilds inside the generation; under another it is refused, - * its `remedy` carrying the exact statements that clear the source (one - * DELETE per passage table, then the generation row) — this store does not - * yet build a second generation beside the first. `completeBuild` records - * the recipe hash; `indexStatus` answers both. + * ## One builder per source + * + * `beginBuild` takes a PostgreSQL session advisory lock on the source (a key + * hashed from the schema and the source id), on a connection of its own + * ({@link PgPoolLike.connectSession}), and holds it until `completeBuild`. + * A second `beginBuild` from another process is refused `LOCK_CONFLICT` + * (409) and its walk does not run. The lock goes when the build completes, + * when the process or its connection dies (PostgreSQL frees it), or after + * {@link PgvectorKnowledgeAdapterOptions.buildLockIdleMs} without a call for + * the source, so a walk that failed on a running process does not hold it. + * The knowledge service runs one walk of a source at a time, so a lock this + * adapter still holds when it begins a build again is the earlier build's, + * and is kept for the new one. * * ## Writes * @@ -172,9 +246,14 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { private readonly resolveEmbedder: () => IEmbedder | undefined; private readonly schema: string; private readonly queryPrefix: string; + private readonly buildLockIdleMs: number; + private readonly deleteBatchSize: number; + private readonly logger?: { warn?(message: string): void }; private readiness?: Readiness; /** Widths whose passage table this adapter has created or found. */ private readonly tables = new Set(); + /** The builder locks this adapter holds, by source id. */ + private readonly builders = new Map(); constructor(opts: PgvectorKnowledgeAdapterOptions) { this.id = opts.id ?? 'pgvector'; @@ -189,6 +268,12 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { ); } this.queryPrefix = opts.queryPrefix ?? ''; + this.buildLockIdleMs = opts.buildLockIdleMs ?? 15 * 60 * 1000; + this.deleteBatchSize = opts.deleteBatchSize ?? 1000; + if (!Number.isInteger(this.deleteBatchSize) || this.deleteBatchSize < 1) { + throw new RangeError(`knowledge-pgvector: deleteBatchSize must be a positive integer, got ${String(opts.deleteBatchSize)}`); + } + this.logger = opts.logger; } /** What the adapter reports about its embedder (ADR-0161 K8, item 6), read now. */ @@ -207,18 +292,21 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { this.requirePool(); const readiness = await this.ready(); const embedder = this.requireEmbedder(); - const generation = (await this.writeTarget(ctx, embedder, true))!; - await this.ensureVectorTable(generation.dim, readiness); + this.touchBuilderLock(ctx.source.id); // An unchanged passage is rewritten in place, keeping its vector. When its // row is gone by the time the write runs (a concurrent rewrite of the same - // document removed it), the write is rolled back and planned again, so the - // passage is embedded and inserted rather than lost. + // document removed it), or its generation was switched or retired, the + // write is rolled back and planned again, so the passage is embedded and + // inserted, into the generation that holds the fingerprint now, rather + // than lost. for (let attempt = 1; ; attempt++) { + const generation = (await this.writeTarget(ctx, embedder, true))!; + await this.ensureVectorTable(generation.dim, readiness); const missing = await this.writePassages(docs, ctx.source.id, generation, readiness, embedder); if (missing === undefined) return; if (attempt >= UPSERT_ATTEMPTS) { throw new Error( - `knowledge-pgvector: passage '${missing}' of source '${ctx.source.id}' was removed by a concurrent write ` + + `knowledge-pgvector: ${missing} of source '${ctx.source.id}' was removed by a concurrent write ` + `${UPSERT_ATTEMPTS} times while this write ran; nothing of this batch was written. Retry the write.`, ); } @@ -227,9 +315,12 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { /** * One attempt of {@link upsert}: read the stored chunk hashes, embed what - * changed, write in one transaction. Answers `undefined` when written, or the - * id of an unchanged passage whose row was gone (the transaction is rolled - * back). + * changed, write in one transaction. Answers `undefined` when written, or + * what was gone (the transaction is rolled back): an unchanged passage's + * row, or the generation itself, retired or replaced while the embedder + * answered. The generation row is share-locked for the transaction, so a + * switch or a retirement waits for the write and the batched deletion that + * follows it sees every row the write put there. */ private async writePassages( docs: KnowledgeDocument[], @@ -274,6 +365,17 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { let missing: string | undefined; const written = await this.transaction(async (client) => { + const target = await client.query( + `SELECT 1 FROM ${qualified(this.schema, GENERATION_TABLE)} + WHERE source_id = $1 AND generation = $2 AND fingerprint IS NOT DISTINCT FROM $3 AND dim = $4 + AND state IN ('active', 'building') + FOR SHARE`, + [sourceId, generation.generation, generation.fingerprint, generation.dim], + ); + if (target.rows.length === 0) { + missing = `generation ${generation.generation}`; + return false; + } for (const { doc, passages } of planned) { await client.query( `DELETE FROM ${table} WHERE source_id = $1 AND generation = $2 AND document_id = $3 AND NOT (chunk_id = ANY($4::text[]))`, @@ -305,7 +407,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { common, ); if (updated.rows.length === 0) { - missing = p.id; + missing = `passage '${p.id}'`; return false; } } else { @@ -332,6 +434,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { if (documentIds.length === 0) return; const pool = this.requirePool(); await this.ready(); + this.touchBuilderLock(ctx.source.id); // From every generation of the source: a removed document leaves them all. const widths = await pool.query<{ dim: number }>( `SELECT DISTINCT dim FROM ${qualified(this.schema, GENERATION_TABLE)} WHERE source_id = $1`, @@ -356,7 +459,9 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { // fingerprint carries no model or width, and comparing it would refuse a // healthy index as one to rebuild. No embedder is SERVICE_UNAVAILABLE. const embedder = this.requireEmbedder(); - // The generation the writes go to (ADR-0161 K8, item 1). + this.touchBuilderLock(ctx.source.id); + // The generation the writes go to (ADR-0161 K8, item 1): during a build, + // the one under construction, so the walk skips what it already holds. const generation = await this.writeTarget(ctx, embedder, false); if (!generation || !(await this.tableExists(generation.dim))) return { documents: [] }; // In byte order ("C"), both the order and the cursor's comparison, so a @@ -382,19 +487,43 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { if (opts.organizationIds !== undefined && opts.organizationIds.length === 0) return []; // A record scope with no term that has ids ranks nothing (ADR-0161 K8, item 17). if (opts.scope !== undefined && !opts.scope.some((term) => term.ids.length > 0)) return []; + for (let attempt = 1; ; attempt++) { + const hits = await this.searchAttempt(query, opts); + if (hits !== undefined) return hits; + if (attempt >= SEARCH_ATTEMPTS) { + throw new Error( + `knowledge-pgvector: the active generation of source '${opts.source.id}' changed ${SEARCH_ATTEMPTS} times during one search; retry it.`, + ); + } + } + } + + /** + * One attempt of {@link search}. Answers `undefined` when the generation it + * ranked was switched out by a completed build between the read of the + * generations and the ranking (the ranking statement holds only while its + * generation is the active one, so it never reads a generation whose + * passages are being deleted). + */ + private async searchAttempt(query: string, opts: AdapterSearchOptions): Promise { const pool = this.requirePool(); const readiness = await this.ready(); // The embedder first: without one the service's fingerprint carries no // model or width, and comparing it would refuse a healthy index as one to // rebuild. No embedder is SERVICE_UNAVAILABLE, as on every other call. const embedder = this.requireEmbedder(); - const generation = await this.activeGeneration(opts.source.id); + const { active: generation, building } = await this.generations(opts.source.id); if (!generation) return []; - // Vectors of two fingerprints are never ranked against each other (K7, rule 5). - if (opts.index !== undefined && generation.fingerprint !== opts.index.fingerprint) { - throw rebuildRequired(opts.source.id, await this.clearSql(opts.source.id, generation.dim)); + // Vectors of two fingerprints are never ranked against each other (K7, + // rule 5); while the searched fingerprint's generation is being built, the + // refusal says so. + const searched = opts.index?.fingerprint; + if (searched !== undefined && generation.fingerprint !== searched) { + throw rebuildRequired(opts.source.id, building !== undefined && building.fingerprint === searched); + } + if (embedder.dimensions !== generation.dim) { + throw rebuildRequired(opts.source.id, building !== undefined && building.dim === embedder.dimensions); } - if (embedder.dimensions !== generation.dim) throw rebuildRequired(opts.source.id, await this.clearSql(opts.source.id, generation.dim)); if (!(await this.tableExists(generation.dim))) return []; const topK = Math.max(0, Math.floor(opts.topK)); if (topK === 0) return []; @@ -411,7 +540,15 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const ext = readiness.extensionSchema; const params: unknown[] = [opts.source.id, generation.generation, vectorLiteral(vector), topK]; - const where = ['source_id = $1', 'generation = $2']; + const where = [ + 'source_id = $1', + 'generation = $2', + // Holds only while the generation is the active one: a completed build + // retires it and then deletes its passages, after this statement's + // snapshot or before it, never inside it. + `EXISTS (SELECT 1 FROM ${qualified(this.schema, GENERATION_TABLE)} g + WHERE g.source_id = $1 AND g.generation = $2 AND g.state = 'active')`, + ]; if (opts.organizationIds !== undefined) { params.push(opts.organizationIds); where.push(`organization_id = ANY($${params.length}::text[])`); @@ -467,6 +604,11 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { LIMIT $4`, params, ); + if (result.rows.length === 0) { + // No hit, or a generation switched out meanwhile: read which. + const now = await this.generations(opts.source.id); + if (now.active?.generation !== generation.generation) return undefined; + } return result.rows.map((r) => ({ chunkId: r.chunk_id, documentId: r.document_id, @@ -487,53 +629,111 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { async indexStatus(ctx: AdapterContext): Promise { this.requirePool(); await this.ready(); - const generation = await this.activeGeneration(ctx.source.id); + const { active, building } = await this.generations(ctx.source.id); const status: AdapterIndexStatus = {}; - if (generation?.fingerprint != null) status.fingerprint = generation.fingerprint; - if (generation?.recipe_hash != null) status.recipeHash = generation.recipe_hash; + if (active?.fingerprint != null) status.fingerprint = active.fingerprint; + if (active?.recipe_hash != null) status.recipeHash = active.recipe_hash; + if (building !== undefined) status.building = true; return status; } + /** + * The start of a complete build (ADR-0161 K7, rule 3). Takes the source's + * builder lock — refused `LOCK_CONFLICT` while another process holds it — + * then rebuilds inside the active generation, takes up the generation under + * construction for this fingerprint (resumed: what it holds is kept), or + * opens one beside the active generation. A generation under construction + * for another fingerprint is abandoned: retired, and deleted in batches. So + * is any generation a switch left retired. + */ async beginBuild(ctx: AdapterContext): Promise { const index = requireIndex(ctx, 'beginBuild'); this.requirePool(); - await this.ready(); + const readiness = await this.ready(); const embedder = this.requireEmbedder(); - const generation = (await this.activeGeneration(ctx.source.id)) - ?? (await this.openFirstGeneration(ctx.source.id, index.fingerprint, embedder)); - if (generation.fingerprint === index.fingerprint && generation.dim === embedder.dimensions) return; - const sql = await this.clearSql(ctx.source.id, generation.dim); - throw Object.assign( - new Error( - `Knowledge source '${ctx.source.id}' was indexed under another embedding model, split or content recipe, ` + - 'and this store does not yet build a second index beside the first.', - ), - { - code: KNOWLEDGE_REBUILD_REQUIRED, - status: 409, - remedy: - 'Either restore the earlier embedding and split configuration, or clear the source\'s index and run a ' + - `complete reindex. Run as a database owner:\n${sql.join('\n')}`, - }, - ); + const sourceId = ctx.source.id; + await this.takeBuilderLock(sourceId); + try { + const target = await this.inTransaction(async (client) => { + const { active, building } = await this.generations(sourceId, client, true); + const fits = (g: GenerationRow | undefined): boolean => + g !== undefined && g.fingerprint === index.fingerprint && g.dim === embedder.dimensions; + if (building !== undefined && fits(building)) return building; + // A build of another fingerprint left unfinished: abandoned, one per source. + if (building !== undefined) await this.retire(client, sourceId, building.generation); + if (active !== undefined && fits(active)) return active; + // A source that holds nothing takes the fingerprint as its active one; + // beside an active generation, the new one is built aside. + return this.openGeneration(client, sourceId, index.fingerprint, embedder, active === undefined ? 'active' : 'building'); + }); + await this.ensureVectorTable(target.dim, readiness); + await this.sweepRetired(sourceId); + } catch (err) { + await this.releaseBuilderLock(sourceId); + throw err; + } } + /** + * The end of a complete build (ADR-0161 K8, item 8 c), called after the walk + * and its purge. The generation built under `ctx.index.fingerprint` becomes + * the active one and records the recipe hash; the generation it replaces is + * retired in the same transaction, then its passages are deleted in batches + * and its row last. Under the active fingerprint, the recipe hash is + * recorded. The builder lock is let go either way. + */ async completeBuild(ctx: AdapterContext): Promise { const index = requireIndex(ctx, 'completeBuild'); - const pool = this.requirePool(); + this.requirePool(); await this.ready(); - const updated = await pool.query( - `UPDATE ${qualified(this.schema, GENERATION_TABLE)} SET recipe_hash = $3 - WHERE source_id = $1 AND state = 'active' AND fingerprint = $2 RETURNING generation`, - [ctx.source.id, index.fingerprint, index.recipeHash], - ); - if (updated.rows.length === 0) { - throw new Error( - `completeBuild: source '${ctx.source.id}' holds no active generation under this fingerprint; call beginBuild first.`, - ); + const sourceId = ctx.source.id; + try { + await this.inTransaction(async (client) => { + const { active, building } = await this.generations(sourceId, client, true); + const t = qualified(this.schema, GENERATION_TABLE); + if (building !== undefined && building.fingerprint === index.fingerprint) { + // The switch: one statement retires the old generation, the next + // makes the new one active (one active row per source at a time). + if (active) await this.retire(client, sourceId, active.generation); + await client.query(`UPDATE ${t} SET state = 'active', recipe_hash = $3 WHERE source_id = $1 AND generation = $2`, [ + sourceId, + building.generation, + index.recipeHash, + ]); + return; + } + if (active !== undefined && active.fingerprint === index.fingerprint) { + await client.query(`UPDATE ${t} SET recipe_hash = $3 WHERE source_id = $1 AND generation = $2`, [ + sourceId, + active.generation, + index.recipeHash, + ]); + return; + } + throw new Error( + `completeBuild: source '${sourceId}' holds no generation under this fingerprint; call beginBuild first.`, + ); + }); + try { + await this.sweepRetired(sourceId); + } catch (err) { + // The switch is recorded and the old generation is never searched + // again; only its rows are left. Not the caller's failure. + this.logger?.warn?.( + `knowledge-pgvector: the replaced index of source '${sourceId}' was not fully deleted (${errorText(err)}); ` + + 'it is never searched, and the source\'s next build deletes the rest.', + ); + } + } finally { + await this.releaseBuilderLock(sourceId); } } + /** Let go of every builder lock this adapter holds; the plugin calls it before it closes its pool. */ + async close(): Promise { + for (const sourceId of [...this.builders.keys()]) await this.releaseBuilderLock(sourceId); + } + async healthCheck(): Promise<{ ok: boolean; message?: string }> { try { this.requirePool(); @@ -655,40 +855,102 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { return present; } - private async activeGeneration(sourceId: string): Promise { - const found = await this.requirePool().query( - `SELECT generation, fingerprint, recipe_hash, dim FROM ${qualified(this.schema, GENERATION_TABLE)} - WHERE source_id = $1 AND state = 'active' ORDER BY generation DESC LIMIT 1`, + /** The source's generations; `forUpdate` locks their rows for the transaction `client` runs. */ + private async generations( + sourceId: string, + client: Pick = this.requirePool(), + forUpdate = false, + ): Promise { + const found = await client.query( + `SELECT generation, fingerprint, recipe_hash, dim, state FROM ${qualified(this.schema, GENERATION_TABLE)} + WHERE source_id = $1 ORDER BY generation${forUpdate ? ' FOR UPDATE' : ''}`, [sourceId], ); - const row = found.rows[0]; - return row === undefined ? undefined : { ...row, generation: Number(row.generation), dim: Number(row.dim) }; + const out: SourceGenerations = { retired: [] }; + for (const r of found.rows) { + const state: GenerationState = r.state === 'building' ? 'building' : r.state === 'retired' ? 'retired' : 'active'; + const row: GenerationRow = { ...r, generation: Number(r.generation), dim: Number(r.dim), state }; + if (state === 'retired') out.retired.push(row); + else out[state] = row; + } + return out; } /** - * A source that holds nothing takes the first fingerprint it is handed - * (there is nothing to mix with). "Holds nothing" is made true: passage rows - * of the source left in any passage table without a generation row (a - * generation row deleted by hand, its passages not) are deleted in the same - * transaction that opens the generation, so a first generation never adopts - * vectors embedded under another fingerprint. Only the call whose insert - * opened the generation clears; a concurrent one waits on the key and finds - * it open. + * Open a generation of `sourceId` under `fingerprint`, numbered past every + * generation the source has. Passage rows of the source left without a + * generation row (a row deleted by hand, its passages not) are deleted + * first, in the same transaction, so no generation ever adopts vectors + * embedded under another fingerprint. When a concurrent call opened the + * generation of that state first, that one is answered. */ - private async openFirstGeneration(sourceId: string, fingerprint: string | undefined, embedder: IEmbedder): Promise { - await this.transaction(async (client) => { - const opened = await client.query( - `INSERT INTO ${qualified(this.schema, GENERATION_TABLE)} (source_id, generation, fingerprint, dim, model, state) - VALUES ($1, 1, $2, $3, $4, 'active') ON CONFLICT (source_id, generation) DO NOTHING RETURNING generation`, - [sourceId, fingerprint ?? null, embedder.dimensions, embedder.model ?? null], + private async openGeneration( + client: PgClientLike, + sourceId: string, + fingerprint: string | undefined, + embedder: IEmbedder, + state: 'active' | 'building', + ): Promise { + const t = qualified(this.schema, GENERATION_TABLE); + for (const width of await this.passageWidths(client)) { + const passages = qualified(this.schema, vectorTable(width)); + await client.query( + `DELETE FROM ${passages} p WHERE p.source_id = $1 + AND NOT EXISTS (SELECT 1 FROM ${t} g WHERE g.source_id = p.source_id AND g.generation = p.generation)`, + [sourceId], ); - if (opened.rows.length === 0) return true; - for (const width of await this.passageWidths(client)) { - await client.query(`DELETE FROM ${qualified(this.schema, vectorTable(width))} WHERE source_id = $1`, [sourceId]); + } + const opened = await client.query( + `INSERT INTO ${t} (source_id, generation, fingerprint, dim, model, state) + SELECT $1, COALESCE(max(generation), 0) + 1, $2, $3, $4, $5 FROM ${t} WHERE source_id = $1 + ON CONFLICT DO NOTHING + RETURNING generation, fingerprint, recipe_hash, dim, state`, + [sourceId, fingerprint ?? null, embedder.dimensions, embedder.model ?? null, state], + ); + const row = opened.rows[0] ?? (await this.generations(sourceId, client))[state]; + if (row === undefined) { + throw new Error(`knowledge-pgvector: no ${state} generation of source '${sourceId}' could be opened; retry.`); + } + return { ...row, generation: Number(row.generation), dim: Number(row.dim), state }; + } + + /** Mark a generation `retired`: held by no write and no search; {@link sweepRetired} deletes it. */ + private async retire(client: PgClientLike, sourceId: string, generation: number): Promise { + await client.query(`UPDATE ${qualified(this.schema, GENERATION_TABLE)} SET state = 'retired' WHERE source_id = $1 AND generation = $2`, [ + sourceId, + generation, + ]); + } + + /** + * Delete the retired generations of `sourceId`: their passages in batches of + * {@link deleteBatchSize} rows, one statement and one short transaction + * each, so no long lock is held over a large source; the generation row last, + * so no passage is ever left without one. + */ + private async sweepRetired(sourceId: string): Promise { + const pool = this.requirePool(); + const { retired } = await this.generations(sourceId); + for (const g of retired) { + if (await this.tableExists(g.dim)) { + const table = qualified(this.schema, vectorTable(g.dim)); + for (;;) { + const deleted = await pool.query<{ n: number }>( + `WITH gone AS ( + DELETE FROM ${table} WHERE (source_id, generation, chunk_id) IN ( + SELECT source_id, generation, chunk_id FROM ${table} WHERE source_id = $1 AND generation = $2 LIMIT $3) + RETURNING 1) + SELECT count(*)::int AS n FROM gone`, + [sourceId, g.generation, this.deleteBatchSize], + ); + if (Number(deleted.rows[0]?.n ?? 0) < this.deleteBatchSize) break; + } } - return true; - }); - return (await this.activeGeneration(sourceId))!; + await pool.query( + `DELETE FROM ${qualified(this.schema, GENERATION_TABLE)} WHERE source_id = $1 AND generation = $2 AND state = 'retired'`, + [sourceId, g.generation], + ); + } } /** The widths of the passage tables that exist in the store's schema. */ @@ -702,57 +964,105 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { } /** - * The generation a write carrying `ctx.index` goes to: the active one, when - * its fingerprint is the one carried (or none is carried); refused when it is - * another, or when the embedder's width is not the generation's. A source - * that holds nothing gets its first generation (`create`), or none. + * The generation a call carrying `ctx.index` writes to or lists: the one + * under construction when it holds that fingerprint, else the active one + * when it holds it (or none is carried); refused when neither does, or when + * the embedder's width is not the generation's. A source that holds nothing + * gets its first generation (`create`), or none. */ private async writeTarget( ctx: AdapterContext, - embedder: IEmbedder | undefined, + embedder: IEmbedder, create: boolean, ): Promise { - const active = await this.activeGeneration(ctx.source.id); - if (!active) { - if (!create || !embedder) return undefined; - const opened = await this.openFirstGeneration(ctx.source.id, ctx.index?.fingerprint, embedder); - return this.checkTarget(ctx, opened, embedder); + const sourceId = ctx.source.id; + const fingerprint = ctx.index?.fingerprint; + const { active, building } = await this.generations(sourceId); + const checked = (g: GenerationRow): GenerationRow => { + if (embedder.dimensions !== g.dim) throw rebuildRequired(sourceId, false); + return g; + }; + if (building !== undefined && fingerprint !== undefined && building.fingerprint === fingerprint) return checked(building); + if (active === undefined) { + if (!create) return undefined; + const opened = await this.inTransaction((client) => this.openGeneration(client, sourceId, fingerprint, embedder, 'active')); + if (fingerprint !== undefined && opened.fingerprint !== fingerprint) throw rebuildRequired(sourceId, false); + return checked(opened); } - return this.checkTarget(ctx, active, embedder); + if (fingerprint === undefined || active.fingerprint === fingerprint) return checked(active); + throw rebuildRequired(sourceId, false); } - private async checkTarget( - ctx: AdapterContext, - generation: GenerationRow, - embedder: IEmbedder | undefined, - ): Promise { - const fingerprint = ctx.index?.fingerprint; - if (fingerprint !== undefined && generation.fingerprint !== fingerprint) { - throw rebuildRequired(ctx.source.id, await this.clearSql(ctx.source.id, generation.dim)); - } - if (embedder !== undefined && embedder.dimensions !== generation.dim) { - throw rebuildRequired(ctx.source.id, await this.clearSql(ctx.source.id, generation.dim)); - } - return generation; + // ── The builder lock ────────────────────────────────────────────── + + /** The advisory lock key of a source: 64 bits of a hash of the schema and the source id. */ + private lockKey(sourceId: string): string { + const digest = createHash('sha256').update(`knowledge-pgvector\u0000${this.schema}\u0000${sourceId}`).digest(); + return digest.readBigInt64BE(0).toString(); } /** - * The statements that clear everything this store holds for a source, so it - * can be built afresh: one DELETE per passage table that exists, then the - * generation rows — passages first, so no generation row is ever missing - * while its passages remain. + * Take the source's builder lock on a session of its own, or keep the one + * this adapter already holds (the knowledge service runs one walk of a + * source at a time, so that one is an earlier build's that ended without + * `completeBuild`). Refused `LOCK_CONFLICT` while another session holds it. */ - private async clearSql(sourceId: string, knownWidth: number): Promise { - const literal = `'${sourceId.replace(/'/g, "''")}'`; - // The tables found in the schema, and always the width the source's - // generation records: should the catalogue read fail, the statements still - // clear that table before the generation row, never the row alone. - const found = await this.passageWidths().catch(() => [] as number[]); - const widths = [...new Set([...found, knownWidth])].sort((a, b) => a - b); - return [ - ...widths.map((width) => `DELETE FROM ${qualified(this.schema, vectorTable(width))} WHERE source_id = ${literal};`), - `DELETE FROM ${qualified(this.schema, GENERATION_TABLE)} WHERE source_id = ${literal};`, - ]; + private async takeBuilderLock(sourceId: string): Promise { + if (this.builders.has(sourceId)) { + this.touchBuilderLock(sourceId); + return; + } + const pool = this.requirePool(); + const client = pool.connectSession ? await pool.connectSession() : await pool.connect(); + const key = this.lockKey(sourceId); + let locked: boolean; + try { + const got = await client.query<{ locked: boolean }>('SELECT pg_try_advisory_lock($1::bigint) AS locked', [key]); + locked = got.rows[0]?.locked === true; + } catch (err) { + client.release(err instanceof Error ? err : true); + throw err; + } + if (!locked) { + client.release(); + throw builderBusy(sourceId, this.buildLockIdleMs); + } + this.builders.set(sourceId, { client, key }); + this.touchBuilderLock(sourceId); + } + + /** A call for the source while this adapter builds it: the lock's idle time starts again. */ + private touchBuilderLock(sourceId: string): void { + const held = this.builders.get(sourceId); + if (!held) return; + if (held.timer !== undefined) clearTimeout(held.timer); + held.timer = setTimeout(() => void this.releaseBuilderLock(sourceId), this.buildLockIdleMs); + held.timer.unref?.(); + } + + /** Let go of the source's builder lock, when this adapter holds it. */ + private async releaseBuilderLock(sourceId: string): Promise { + const held = this.builders.get(sourceId); + if (!held) return; + this.builders.delete(sourceId); + if (held.timer !== undefined) clearTimeout(held.timer); + try { + await held.client.query('SELECT pg_advisory_unlock($1::bigint)', [held.key]); + held.client.release(); + } catch (err) { + // A session that is gone has let go of its lock already. + held.client.release(err instanceof Error ? err : true); + } + } + + /** Run `work` in one transaction: committed when it resolves, rolled back when it throws. */ + private async inTransaction(work: (client: PgClientLike) => Promise): Promise { + let value: T | undefined; + await this.transaction(async (client) => { + value = await work(client); + return true; + }); + return value as T; } /** Run `work` in one transaction: committed when it answers `true`, rolled back when it answers `false` or throws. */ @@ -794,23 +1104,37 @@ function requireIndex(ctx: AdapterContext, member: string): NonNullable client.release(err), }; }, + // A connection of its own, outside the pool, for a build's builder lock: + // the pool's settings, one client, closed by `release`. + connectSession: async () => { + const client = new pg.Client(pool.options); + // A session that drops lets go of its advisory lock in the server; its + // error must not end the process, and the next query on it fails. + client.on('error', () => undefined); + await client.connect(); + return { + query: async (text: string, params?: unknown[]) => { + const result = await client.query(text, params as unknown[] | undefined); + return { rows: result.rows as R[] }; + }, + release: () => { + void client.end().catch(() => undefined); + }, + }; + }, }; } @@ -109,6 +127,7 @@ export class KnowledgePgvectorPlugin implements Plugin { private readonly opts: KnowledgePgvectorPluginOptions; private pool?: pg.Pool; + private adapter?: PgvectorKnowledgeAdapter; constructor(opts: KnowledgePgvectorPluginOptions = {}) { this.opts = opts; @@ -158,7 +177,9 @@ export class KnowledgePgvectorPlugin implements Plugin { embedder, schema: this.opts.schema, queryPrefix: this.opts.queryPrefix, + logger: ctx.logger, }); + this.adapter = adapter; svc.registerAdapter(adapter.id, adapter); const health = await adapter.healthCheck(); @@ -173,6 +194,9 @@ export class KnowledgePgvectorPlugin implements Plugin { } async destroy(): Promise { + // The builder locks first: each is held on a session of its own. + await this.adapter?.close(); + this.adapter = undefined; const pool = this.pool; this.pool = undefined; await pool?.end(); diff --git a/packages/plugins/knowledge-pgvector/src/sql.ts b/packages/plugins/knowledge-pgvector/src/sql.ts index e30000a1a78..d5f1705e09c 100644 --- a/packages/plugins/knowledge-pgvector/src/sql.ts +++ b/packages/plugins/knowledge-pgvector/src/sql.ts @@ -23,6 +23,13 @@ export const DEFAULT_KNOWLEDGE_SCHEMA = 'os_knowledge'; /** The generation table: one row per generation of a source. */ export const GENERATION_TABLE = 'knowledge_generation'; +/** + * The state of a generation row: `active` (the one searched), `building` (the + * one a build under a new fingerprint fills), `retired` (replaced, its + * passages being deleted in batches). + */ +export type GenerationState = 'active' | 'building' | 'retired'; + /** The passage table of one vector width: `knowledge_vec_d`. */ export function vectorTable(dimensions: number): string { if (!Number.isInteger(dimensions) || dimensions < 1) { @@ -51,6 +58,10 @@ export function schemaDdl(schema: string): string[] { created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (source_id, generation) )`, + // One active generation per source, and one under construction (ADR-0161 + // K7). A generation being deleted is `retired` and held by neither. + `CREATE UNIQUE INDEX IF NOT EXISTS "${GENERATION_TABLE}_active" ON ${qualified(schema, GENERATION_TABLE)} (source_id) WHERE state = 'active'`, + `CREATE UNIQUE INDEX IF NOT EXISTS "${GENERATION_TABLE}_building" ON ${qualified(schema, GENERATION_TABLE)} (source_id) WHERE state = 'building'`, ]; } From cc0cd9ef66afcff6df4f9875ee61c5203884f84e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 08:29:07 +0000 Subject: [PATCH 2/8] test(knowledge-pgvector): generation build, switch, lock and resume cases (wip) Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude --- .../acceptance.live-postgres.test.ts | 59 +--- .../__tests__/contract.live-postgres.test.ts | 6 +- .../generations.live-postgres.test.ts | 299 ++++++++++++++++++ .../src/__tests__/live-pg.testkit.ts | 11 +- 4 files changed, 325 insertions(+), 50 deletions(-) create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/generations.live-postgres.test.ts 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 07bec7cf942..8cc4a9b4c91 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 @@ -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'; @@ -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); }); @@ -252,23 +226,20 @@ 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 }); + 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 () => { diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts index 4b5b9b00d58..2cfb8e2152a 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts @@ -2,8 +2,8 @@ // The `IKnowledgeAdapter` contract suite (ADR-0161 K8, rule 1) against a LIVE // PostgreSQL with pgvector: the same suite the reference adapter runs, each -// case on a fresh adapter in a schema of its own. It does not build a second -// generation beside the first yet (#37101), so `generations` is false. +// case on a fresh adapter in a schema of its own, `generations` included: a +// build under a new fingerprint fills a generation beside the active one. import { afterAll, describe } from 'vitest'; import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/testing'; @@ -26,7 +26,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => { indexStatus: true, builds: true, refusesOtherFingerprint: true, - generations: false, + generations: true, scope: true, }, }); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/generations.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/generations.live-postgres.test.ts new file mode 100644 index 00000000000..c7b5f6311a5 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/generations.live-postgres.test.ts @@ -0,0 +1,299 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Generations on a LIVE PostgreSQL with pgvector (ADR-0161 K7, rules 1 to 4): + * a changed fingerprint builds a new generation beside the active one, the + * event-sync writes of the build land in the new generation only, a search + * during the build is refused as "being rebuilt" and never answered from the + * old generation, the purge reconciles once, the switch makes the new one + * active, and the old one is deleted in batches. One builder per source, by a + * PostgreSQL advisory lock: a second build is refused `LOCK_CONFLICT`, and a + * build whose session died is resumed by the next one with what it wrote. + */ + +import { afterAll, describe, expect, it } from 'vitest'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import type { AdapterContext } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { KnowledgeService } from '@objectstack/service-knowledge'; +import { KNOWLEDGE_REBUILD_REQUIRED, poolFromPg, type PgPoolLike, type PgvectorKnowledgeAdapter } from '../index.js'; +import { FakeEmbedder, PG_URL, liveStore, requireLiveCell } from './live-pg.testkit.js'; + +requireLiveCell('knowledge-pgvector generations'); + +const store = liveStore('kpg_gen'); + +const SYSTEM = { positions: [], permissions: [], systemPermissions: [], isSystem: true } as unknown as ExecutionContext; + +const FP_A = { fingerprint: 'fp-gen:a', recipeHash: 'rh-gen:1' }; +const FP_B = { fingerprint: 'fp-gen:b', recipeHash: 'rh-gen:1' }; +const FP_C = { fingerprint: 'fp-gen:c', recipeHash: 'rh-gen:1' }; + +const source = (id: string): KnowledgeSource => + ({ + id, + label: id, + adapter: 'under_test', + source: { kind: 'object', object: 'article', contentFields: ['body'], metadataFields: ['status'] }, + }) as KnowledgeSource; + +const ctx = (s: KnowledgeSource, index: { fingerprint: string; recipeHash: string } = FP_A): AdapterContext => ({ + source: s, + reason: 'manual', + index, +}); + +function doc(s: KnowledgeSource, n: string, content: string): KnowledgeDocument { + const id = `${s.id}:${n}`; + return { + id, + sourceId: s.id, + sourceRecordId: n, + content, + docHash: `h:${content}`, + metadata: {}, + chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }], + }; +} + +/** A {@link FakeEmbedder} whose next `embed` call can be held until the test lets it go. */ +class GatedEmbedder extends FakeEmbedder { + private gate?: { entered: () => void; released: Promise }; + + /** Hold the next `embed` call: `entered` resolves when it starts, `release` lets it run. */ + holdNext(): { entered: Promise; release: () => void } { + let release!: () => void; + let entered!: () => void; + const released = new Promise((r) => (release = r)); + const enteredP = new Promise((r) => (entered = r)); + this.gate = { entered, released }; + return { entered: enteredP, release }; + } + + override async embed(texts: string[]): Promise { + const gate = this.gate; + this.gate = undefined; + if (gate) { + gate.entered(); + await gate.released; + } + return super.embed(texts); + } +} + +/** A data engine over a live list of rows: `find` with a keyset on `id`, equality and `$in`, and `count`. */ +function liveRowsEngine(rows: Array>) { + const matches = (row: Record, where: Record | undefined): boolean => { + if (!where) return true; + return Object.entries(where).every(([k, v]) => { + if (k === '$and') return (v as Array>).every((w) => matches(row, w)); + if (v !== null && typeof v === 'object') { + const cond = v as Record; + if ('$gt' in cond) return String(row[k]) > String(cond.$gt); + if ('$in' in cond) return (cond.$in as unknown[]).includes(row[k]); + throw new Error(`liveRowsEngine: condition ${JSON.stringify(v)} is not implemented`); + } + return row[k] === v; + }); + }; + const sorted = () => [...rows].sort((a, b) => (String(a.id) < String(b.id) ? -1 : String(a.id) > String(b.id) ? 1 : 0)); + return { + async find(_object: string, query: { where?: Record; limit?: number }) { + const out = sorted().filter((r) => matches(r, query?.where)); + return query?.limit === undefined ? out : out.slice(0, query.limit); + }, + async count(_object: string, query: { where?: Record }) { + return sorted().filter((r) => matches(r, query?.where)).length; + }, + } as never; +} + +const schemaOf = (adapter: PgvectorKnowledgeAdapter): string => (adapter as unknown as { schema: string }).schema; + +/** The generation rows of a source, oldest first. */ +async function generationRows(schema: string, sourceId: string) { + const found = await store.pool().query<{ generation: number; fingerprint: string | null; state: string }>( + `SELECT generation, fingerprint, state FROM "${schema}"."knowledge_generation" WHERE source_id = $1 ORDER BY generation`, + [sourceId], + ); + return found.rows; +} + +/** How many passage rows each generation of a source holds in the 384-wide table. */ +async function passagesByGeneration(schema: string, sourceId: string): Promise> { + const found = await store.pool().query<{ generation: number; n: string }>( + `SELECT generation, count(*) AS n FROM "${schema}"."knowledge_vec_d384" WHERE source_id = $1 GROUP BY generation`, + [sourceId], + ); + return Object.fromEntries(found.rows.map((r) => [Number(r.generation), Number(r.n)])); +} + +describe.skipIf(!PG_URL)('knowledge-pgvector generations on a LIVE PostgreSQL', () => { + afterAll(() => store.dropAll()); + + it('same width, model changed: a new generation is built beside the old, which no search reads, then switched to and deleted', async () => { + const embedder = new GatedEmbedder(384, 'model-one'); + const adapter = store.adapter({ embedder }); + const schema = schemaOf(adapter); + const rows: Array> = [ + { id: 'r1', body: 'granite quarry', status: 'published' }, + { id: 'r2', body: 'marble quarry', status: 'published' }, + ]; + const svc = new KnowledgeService({ dataEngine: liveRowsEngine(rows) }); + svc.registerAdapter('under_test', adapter); + const s = source('model_change'); + svc.registerSource(s); + expect(await svc.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 2 }); + const before = await adapter.indexStatus({ source: s, reason: 'manual' }); + expect(await generationRows(schema, s.id)).toEqual([{ generation: 1, fingerprint: before.fingerprint, state: 'active' }]); + + // Another model of the same width: the fingerprint moves, and the boot reading says so. + embedder.model = 'model-two'; + expect(await svc.readIndexState(s.id)).toMatchObject({ state: 'new-fingerprint', due: true }); + + // The build starts, and its first page's embed call is held. + const gate = embedder.holdNext(); + const build = svc.reindexSource(s.id); + await gate.entered; + expect(await adapter.indexStatus({ source: s, reason: 'manual' })).toEqual({ + fingerprint: before.fingerprint, + recipeHash: before.recipeHash, + building: true, + }); + expect((await generationRows(schema, s.id)).map((g) => [g.generation, g.state])).toEqual([ + [1, 'active'], + [2, 'building'], + ]); + + // A search during the build is refused as "being rebuilt", by code; the old generation answers nothing. + const refused = await svc.search('granite', { topK: 3, executionContext: SYSTEM }).then( + () => undefined, + (e: unknown) => e as { code?: string; status?: number; message?: string }, + ); + expect(refused).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409 }); + expect(refused?.message).toContain('is being rebuilt'); + + // An event-sync write during the build (a record the walk has passed) lands in the new generation only. + const late = { id: 'r0', body: 'basalt columns', status: 'published' }; + rows.push(late); + await svc.handleRecordUpsert('article', late); + expect(await passagesByGeneration(schema, s.id)).toEqual({ 1: 2, 2: 1 }); + + gate.release(); + // The walk wrote both rows, the purge removed nothing written during the build, and the switch ran. + expect(await build).toMatchObject({ ok: true, indexed: 2, skipped: 0, purged: 0 }); + + const after = await adapter.indexStatus({ source: s, reason: 'manual' }); + expect(after.fingerprint).not.toBe(before.fingerprint); + expect(after.building).toBeUndefined(); + expect(await generationRows(schema, s.id)).toEqual([{ generation: 2, fingerprint: after.fingerprint, state: 'active' }]); + // The old generation is deleted; the write made during the build is there. + expect(await passagesByGeneration(schema, s.id)).toEqual({ 2: 3 }); + expect((await svc.search('basalt', { topK: 3, executionContext: SYSTEM })).map((h) => h.documentId)).toEqual([`${s.id}:r0`]); + expect((await svc.search('granite', { topK: 3, executionContext: SYSTEM })).map((h) => h.documentId)).toEqual([`${s.id}:r1`]); + expect(await svc.readIndexState(s.id)).toMatchObject({ state: 'current', due: false }); + }); + + it('two concurrent builds of one source: one builds, the other is refused LOCK_CONFLICT and walks nothing', async () => { + const first = new GatedEmbedder(384, 'model-one'); + const second = new FakeEmbedder(384, 'model-one'); + const a = store.adapter({ embedder: first }); + // Another process: its own adapter, on the same tables. + const b = store.adapter({ embedder: second, schema: schemaOf(a) }); + const rows = [{ id: 'r1', body: 'granite quarry', status: 'published' }]; + const s = source('two_builders'); + const svcA = new KnowledgeService({ dataEngine: liveRowsEngine(rows) }); + const svcB = new KnowledgeService({ dataEngine: liveRowsEngine(rows) }); + svcA.registerAdapter('under_test', a); + svcB.registerAdapter('under_test', b); + svcA.registerSource(s); + svcB.registerSource(s); + + const gate = first.holdNext(); + const buildA = svcA.reindexSource(s.id); + await gate.entered; + const refusedB = await svcB.reindexSource(s.id); + expect(refusedB).toMatchObject({ ok: false, indexed: 0, discovered: 0 }); + expect(refusedB.message).toContain('is being built by another process'); + expect(second.calls).toBe(0); + await expect(b.beginBuild(ctx(s, FP_A))).rejects.toMatchObject({ code: 'LOCK_CONFLICT', status: 409 }); + + gate.release(); + expect(await buildA).toMatchObject({ ok: true, indexed: 1 }); + // The lock went with the completed build: the other process may build now. + expect(await svcB.reindexSource(s.id)).toMatchObject({ ok: true, indexed: 0, skipped: 1 }); + }); + + it('a build whose session died is resumed by the next one: what it wrote is kept, and only the rest is written', async () => { + const a = store.adapter(); + const schema = schemaOf(a); + const s = source('resume'); + await a.upsert([doc(s, '1', 'granite quarry'), doc(s, '2', 'marble quarry')], ctx(s, FP_A)); + await a.beginBuild(ctx(s, FP_B)); + await a.upsert([doc(s, '1', 'granite quarry')], ctx(s, FP_B)); + + // The process dies: PostgreSQL ends its session, and the advisory lock with it. + const lock = (a as unknown as { builders: Map }).builders.get(s.id)!; + const pid = (await lock.client.query<{ pid: number }>('SELECT pg_backend_pid() AS pid')).rows[0].pid; + await store.pool().query('SELECT pg_terminate_backend($1)', [pid]); + + const b = store.adapter({ schema }); + await expect(b.beginBuild(ctx(s, FP_B))).resolves.toBeUndefined(); + // Resumed, not restarted: the generation under construction keeps the passage written before. + const listed = await b.listDocuments(ctx(s, FP_B), { limit: 10 }); + expect(listed.documents).toEqual([{ documentId: `${s.id}:1`, docHash: 'h:granite quarry' }]); + expect(await passagesByGeneration(schema, s.id)).toEqual({ 1: 2, 2: 1 }); + await b.upsert([doc(s, '2', 'marble quarry')], ctx(s, FP_B)); + await b.completeBuild(ctx(s, FP_B)); + expect(await passagesByGeneration(schema, s.id)).toEqual({ 2: 2 }); + expect(await b.indexStatus(ctx(s))).toEqual({ fingerprint: FP_B.fingerprint, recipeHash: FP_B.recipeHash }); + }); + + it('a build that stops on a running process lets go of its lock after the idle time', async () => { + const a = store.adapter({ buildLockIdleMs: 150 }); + const b = store.adapter({ schema: schemaOf(a) }); + const s = source('idle'); + await a.upsert([doc(s, '1', 'granite quarry')], ctx(s, FP_A)); + await a.beginBuild(ctx(s, FP_B)); + await expect(b.beginBuild(ctx(s, FP_B))).rejects.toMatchObject({ code: 'LOCK_CONFLICT', status: 409 }); + await new Promise((r) => setTimeout(r, 400)); + await expect(b.beginBuild(ctx(s, FP_B))).resolves.toBeUndefined(); + await b.completeBuild(ctx(s, FP_B)); + }); + + it('the old generation is deleted in batches, and a build for a third fingerprint abandons the one under construction', async () => { + const base = poolFromPg(store.pool()); + const batches: string[] = []; + const pool: PgPoolLike = { + ...base, + query: (text, params) => { + if (/^WITH gone AS \(\s*DELETE/.test(text.trim())) batches.push(String(params?.[1])); + return base.query(text, params); + }, + }; + const adapter = store.adapter({ pool, deleteBatchSize: 2 }); + const schema = schemaOf(adapter); + const s = source('batches'); + await adapter.upsert(['1', '2', '3', '4', '5'].map((n) => doc(s, n, `stone ${n}`)), ctx(s, FP_A)); + + // A build under B is abandoned for one under C: B's generation is retired and deleted. + await adapter.beginBuild(ctx(s, FP_B)); + await adapter.upsert([doc(s, '1', 'stone 1')], ctx(s, FP_B)); + await adapter.beginBuild(ctx(s, FP_C)); + expect((await generationRows(schema, s.id)).map((g) => [g.generation, g.fingerprint, g.state])).toEqual([ + [1, FP_A.fingerprint, 'active'], + [3, FP_C.fingerprint, 'building'], + ]); + expect(await passagesByGeneration(schema, s.id)).toEqual({ 1: 5 }); + // A write under the abandoned fingerprint is refused; nothing reaches the active generation. + await expect(adapter.upsert([doc(s, '9', 'stone 9')], ctx(s, FP_B))).rejects.toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED }); + + await adapter.upsert([doc(s, '1', 'stone 1')], ctx(s, FP_C)); + batches.length = 0; + await adapter.completeBuild(ctx(s, FP_C)); + // Five passages, two a statement: three statements, all for generation 1. + expect(batches).toEqual(['1', '1', '1']); + expect(await generationRows(schema, s.id)).toEqual([{ generation: 3, fingerprint: FP_C.fingerprint, state: 'active' }]); + expect(await passagesByGeneration(schema, s.id)).toEqual({ 3: 1 }); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/live-pg.testkit.ts b/packages/plugins/knowledge-pgvector/src/__tests__/live-pg.testkit.ts index ec0439f0112..0cecc07c327 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/live-pg.testkit.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/live-pg.testkit.ts @@ -68,13 +68,15 @@ export class FakeEmbedder implements IEmbedder { } /** - * One pool per file, and a fresh schema per adapter it makes; `dropAll` drops - * every schema it made. + * One pool per file, and a fresh schema per adapter it makes; `dropAll` lets + * go of every builder lock its adapters hold (each on a session of its own), + * then drops every schema it made. */ export function liveStore(prefix: string) { let pool: pg.Pool | undefined; let n = 0; const schemas: string[] = []; + const adapters: PgvectorKnowledgeAdapter[] = []; const run = `${process.pid}_${Date.now().toString(36)}`; return { pool(): pg.Pool { @@ -88,15 +90,18 @@ export function liveStore(prefix: string) { return name; }, adapter(opts: Partial & { embedder?: PgvectorKnowledgeAdapterOptions['embedder'] } = {}) { - return new PgvectorKnowledgeAdapter({ + const adapter = new PgvectorKnowledgeAdapter({ id: 'under_test', pool: poolFromPg(this.pool()), schema: this.schema(), embedder: new FakeEmbedder(), ...opts, }); + adapters.push(adapter); + return adapter; }, async dropAll(): Promise { + for (const adapter of adapters.splice(0)) await adapter.close(); if (!pool) return; for (const schema of schemas) await pool.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`); await pool.end(); From bc0cab45f7d7835d744447e8747d9f34f25efbe8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 08:32:06 +0000 Subject: [PATCH 3/8] docs(knowledge-rag): generations section; changeset for pgvector generations Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude --- .changeset/37101-pgvector-generations.md | 17 +++++++++++++++++ content/docs/ai/knowledge-rag.mdx | 11 +++++++++++ 2 files changed, 28 insertions(+) create mode 100644 .changeset/37101-pgvector-generations.md diff --git a/.changeset/37101-pgvector-generations.md b/.changeset/37101-pgvector-generations.md new file mode 100644 index 00000000000..624aab0468d --- /dev/null +++ b/.changeset/37101-pgvector-generations.md @@ -0,0 +1,17 @@ +--- +'@objectstack/knowledge-pgvector': patch +--- + +feat(knowledge-pgvector): a changed fingerprint builds a new generation beside the active one and switches to it + +Clause-②: no +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 for the source (`buildLockIdleMs` on the adapter). The plugin frees every lock it holds when it is destroyed. +- **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. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index aae5f7fc79f..dedbb38d0d0 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -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. +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 progress. 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: @@ -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. From dc620cdb69845cd8b7cacea8a7a1fa5eaf0dfcf5 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:17:08 +0000 Subject: [PATCH 4/8] docs(knowledge-pgvector): the Rebuilds text describes generations, not hand-run clear SQL Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude --- content/docs/protocol/knowledge.mdx | 24 +++++++++++++------ packages/plugins/knowledge-pgvector/README.md | 12 +++++++++- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index babfc92160b..1b67576e25c 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -558,13 +558,23 @@ 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 + progress. 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 diff --git a/packages/plugins/knowledge-pgvector/README.md b/packages/plugins/knowledge-pgvector/README.md index ec7b9b480e1..0f665c0b5e1 100644 --- a/packages/plugins/knowledge-pgvector/README.md +++ b/packages/plugins/knowledge-pgvector/README.md @@ -62,7 +62,17 @@ 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 progress (`buildLockIdleMs`). +- 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. From fb4146c9bcd06c62ced36f37f28d3e79fb909f2f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 09:58:41 +0000 Subject: [PATCH 5/8] fix(knowledge-pgvector): only the build's own calls hold the builder lock; warn on a release the session no longer held Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude --- .changeset/37101-pgvector-generations.md | 5 +- content/docs/ai/knowledge-rag.mdx | 4 +- content/docs/protocol/knowledge.mdx | 6 +- packages/plugins/knowledge-pgvector/README.md | 3 +- .../acceptance.live-postgres.test.ts | 3 + .../src/__tests__/builder-lock.test.ts | 51 ++++++++++++++++ .../generations.live-postgres.test.ts | 24 ++++++-- .../src/pgvector-adapter.ts | 61 +++++++++++++------ 8 files changed, 129 insertions(+), 28 deletions(-) create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/builder-lock.test.ts diff --git a/.changeset/37101-pgvector-generations.md b/.changeset/37101-pgvector-generations.md index 624aab0468d..a0a6ffaad94 100644 --- a/.changeset/37101-pgvector-generations.md +++ b/.changeset/37101-pgvector-generations.md @@ -4,7 +4,7 @@ feat(knowledge-pgvector): a changed fingerprint builds a new generation beside the active one and switches to it -Clause-②: no +Clause-②: yes (widening) Metadata-protocol: none ADR-0161 K7, rules 1 to 4, for the PostgreSQL store. @@ -12,6 +12,7 @@ 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 for the source (`buildLockIdleMs` on the adapter). The plugin frees every lock it holds when it is destroyed. +- **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 search that meets three generation switches in a row is refused `CONCURRENT_MODIFICATION` (409). - **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. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index dedbb38d0d0..6a4ca67e489 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -227,8 +227,8 @@ A store that keeps **generations** (pgvector and Turso) does not throw the old i 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. -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 progress. A build under yet another fingerprint abandons the unfinished generation and deletes it. +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 diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 1b67576e25c..9d96e25acab 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -571,8 +571,10 @@ an exact scan. 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 - progress. A stopped build is resumed by the next `beginBuild` under the same + 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 diff --git a/packages/plugins/knowledge-pgvector/README.md b/packages/plugins/knowledge-pgvector/README.md index 0f665c0b5e1..53e4ed9a5bd 100644 --- a/packages/plugins/knowledge-pgvector/README.md +++ b/packages/plugins/knowledge-pgvector/README.md @@ -69,7 +69,8 @@ When the fingerprint changes, a complete reindex builds a **new generation** bes - 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 progress (`buildLockIdleMs`). +- 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. 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 8cc4a9b4c91..0a98b0a39df 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 @@ -239,6 +239,9 @@ describe.skipIf(!PG_URL)('knowledge-pgvector acceptance on a LIVE PostgreSQL', ( ); expect(err).toMatchObject({ code: KNOWLEDGE_REBUILD_REQUIRED, status: 409, message: expect.stringContaining('needs a rebuild') }); expect(err?.message).not.toContain('DELETE'); + // 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 }); }); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/builder-lock.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/builder-lock.test.ts new file mode 100644 index 00000000000..4793ae494ec --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/builder-lock.test.ts @@ -0,0 +1,51 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The builder lock's release, without a database: a session advisory lock + * that its session no longer holds when the build lets go of it (a + * transaction-mode pooler ran the lock and the unlock on different server + * connections) is reported at `warn`, naming the connection the store needs. + */ + +import { describe, expect, it, vi } from 'vitest'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import { PgvectorKnowledgeAdapter, type PgClientLike, type PgPoolLike } from '../index.js'; +import { FakeEmbedder } from './live-pg.testkit.js'; + +const source = { id: 'locked', label: 'locked', adapter: 'pgvector', source: { kind: 'object', object: 'a', contentFields: ['b'] } } as KnowledgeSource; +const index = { fingerprint: 'fp', recipeHash: 'rh' }; + +/** A store that answers every statement the build's start and end run; the unlock answers `unlocked`. */ +function fakePool(unlocked: boolean): PgPoolLike { + const answer = async (text: string): Promise<{ rows: R[] }> => { + if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.0' }] as R[] }; + if (text.includes('pg_try_advisory_lock')) return { rows: [{ locked: true }] as R[] }; + if (text.includes('pg_advisory_unlock')) return { rows: [{ unlocked }] as R[] }; + if (text.includes('RETURNING generation')) { + return { rows: [{ generation: 1, fingerprint: 'fp', recipe_hash: null, dim: 384, state: 'active' }] as R[] }; + } + if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] as R[] }; + return { rows: [] as R[] }; + }; + const client = (): PgClientLike => ({ query: answer, release: () => undefined }); + return { query: answer, connect: async () => client(), connectSession: async () => client() }; +} + +describe('knowledge-pgvector builder lock release', () => { + it('warns when the session no longer held the lock it releases', async () => { + const warn = vi.fn(); + const adapter = new PgvectorKnowledgeAdapter({ pool: fakePool(false), embedder: new FakeEmbedder(), logger: { warn } }); + await adapter.beginBuild({ source, reason: 'reindex', index }); + await adapter.close(); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0][0]).toContain('direct or session-mode PostgreSQL connection'); + }); + + it('says nothing when the session held it', async () => { + const warn = vi.fn(); + const adapter = new PgvectorKnowledgeAdapter({ pool: fakePool(true), embedder: new FakeEmbedder(), logger: { warn } }); + await adapter.beginBuild({ source, reason: 'reindex', index }); + await adapter.close(); + expect(warn).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/generations.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/generations.live-postgres.test.ts index c7b5f6311a5..7c05d63c09d 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/generations.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/generations.live-postgres.test.ts @@ -249,15 +249,31 @@ describe.skipIf(!PG_URL)('knowledge-pgvector generations on a LIVE PostgreSQL', expect(await b.indexStatus(ctx(s))).toEqual({ fingerprint: FP_B.fingerprint, recipeHash: FP_B.recipeHash }); }); - it('a build that stops on a running process lets go of its lock after the idle time', async () => { - const a = store.adapter({ buildLockIdleMs: 150 }); + it('a build that stops on a running process lets go after the idle time; event-sync writes do not hold it', async () => { + const a = store.adapter({ buildLockIdleMs: 300 }); const b = store.adapter({ schema: schemaOf(a) }); const s = source('idle'); await a.upsert([doc(s, '1', 'granite quarry')], ctx(s, FP_A)); + const started = Date.now(); await a.beginBuild(ctx(s, FP_B)); await expect(b.beginBuild(ctx(s, FP_B))).rejects.toMatchObject({ code: 'LOCK_CONFLICT', status: 409 }); - await new Promise((r) => setTimeout(r, 400)); - await expect(b.beginBuild(ctx(s, FP_B))).resolves.toBeUndefined(); + // The walk has stopped; record events keep arriving for the source under + // the new fingerprint. They are not progress of the build, so the lock + // still goes once the idle time has passed since the build's last call. + let released = false; + for (let i = 0; i < 60 && !released; i++) { + await a.upsert([doc(s, '2', `marble quarry ${i}`)], { source: s, reason: 'event-sync', index: FP_B }); + await new Promise((r) => setTimeout(r, 50)); + released = await b.beginBuild(ctx(s, FP_B)).then( + () => true, + (e: unknown) => { + if ((e as { code?: string }).code !== 'LOCK_CONFLICT') throw e; + return false; + }, + ); + } + expect(released).toBe(true); + expect(Date.now() - started).toBeGreaterThanOrEqual(300); await b.completeBuild(ctx(s, FP_B)); }); diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index dab3b203054..2bcaa02337d 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -84,11 +84,12 @@ export interface PgvectorKnowledgeAdapterOptions { */ queryPrefix?: string; /** - * How long a build may go without a call for its source (a page written, - * the listing, a delete) before its builder lock is let go, so a build that - * stopped part-way on a process that keeps running does not keep every - * other process from building the source. A process that stops lets go at - * once. @default 900000 (15 minutes) + * How long a build may go without a call of its own (a call whose + * `ctx.reason` is `'reindex'`: the listing, a page written, a removal) + * before its builder lock is let go, so a build that stopped part-way on a + * process that keeps running does not keep every other process from + * building the source. Event-sync writes do not count as progress. A process + * that stops lets go at once. @default 900000 (15 minutes) */ buildLockIdleMs?: number; /** How many passage rows of a replaced generation one DELETE removes. @default 1000 */ @@ -207,8 +208,11 @@ interface Readiness { * A second `beginBuild` from another process is refused `LOCK_CONFLICT` * (409) and its walk does not run. The lock goes when the build completes, * when the process or its connection dies (PostgreSQL frees it), or after - * {@link PgvectorKnowledgeAdapterOptions.buildLockIdleMs} without a call for - * the source, so a walk that failed on a running process does not hold it. + * {@link PgvectorKnowledgeAdapterOptions.buildLockIdleMs} without a call of + * the build (event-sync writes do not count), so a walk that failed on a + * running process does not hold it. A session advisory lock belongs to one + * server session: the store needs a direct or session-mode connection, never + * a transaction-mode pooler; a release the session no longer held is logged. * The knowledge service runs one walk of a source at a time, so a lock this * adapter still holds when it begins a build again is the earlier build's, * and is kept for the new one. @@ -292,7 +296,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { this.requirePool(); const readiness = await this.ready(); const embedder = this.requireEmbedder(); - this.touchBuilderLock(ctx.source.id); + this.touchBuilderLock(ctx); // An unchanged passage is rewritten in place, keeping its vector. When its // row is gone by the time the write runs (a concurrent rewrite of the same // document removed it), or its generation was switched or retired, the @@ -434,7 +438,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { if (documentIds.length === 0) return; const pool = this.requirePool(); await this.ready(); - this.touchBuilderLock(ctx.source.id); + this.touchBuilderLock(ctx); // From every generation of the source: a removed document leaves them all. const widths = await pool.query<{ dim: number }>( `SELECT DISTINCT dim FROM ${qualified(this.schema, GENERATION_TABLE)} WHERE source_id = $1`, @@ -459,7 +463,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { // fingerprint carries no model or width, and comparing it would refuse a // healthy index as one to rebuild. No embedder is SERVICE_UNAVAILABLE. const embedder = this.requireEmbedder(); - this.touchBuilderLock(ctx.source.id); + this.touchBuilderLock(ctx); // The generation the writes go to (ADR-0161 K8, item 1): during a build, // the one under construction, so the walk skips what it already holds. const generation = await this.writeTarget(ctx, embedder, false); @@ -491,8 +495,11 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const hits = await this.searchAttempt(query, opts); if (hits !== undefined) return hits; if (attempt >= SEARCH_ATTEMPTS) { - throw new Error( - `knowledge-pgvector: the active generation of source '${opts.source.id}' changed ${SEARCH_ATTEMPTS} times during one search; retry it.`, + throw Object.assign( + new Error( + `knowledge-pgvector: the active generation of source '${opts.source.id}' changed ${SEARCH_ATTEMPTS} times during one search; retry it.`, + ), + { code: 'CONCURRENT_MODIFICATION', status: 409 }, ); } } @@ -1009,7 +1016,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { */ private async takeBuilderLock(sourceId: string): Promise { if (this.builders.has(sourceId)) { - this.touchBuilderLock(sourceId); + this.restartIdleTimer(sourceId); return; } const pool = this.requirePool(); @@ -1028,11 +1035,21 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { throw builderBusy(sourceId, this.buildLockIdleMs); } this.builders.set(sourceId, { client, key }); - this.touchBuilderLock(sourceId); + this.restartIdleTimer(sourceId); + } + + /** + * A call of the build (`ctx.reason === 'reindex'`: the walk's listing, its + * pages, its removals) while this adapter holds the source's lock: the lock's + * idle time starts again. An event-sync write does not, so a walk that failed + * on a process that keeps receiving record events still lets go. + */ + private touchBuilderLock(ctx: AdapterContext): void { + if (ctx.reason !== 'reindex') return; + this.restartIdleTimer(ctx.source.id); } - /** A call for the source while this adapter builds it: the lock's idle time starts again. */ - private touchBuilderLock(sourceId: string): void { + private restartIdleTimer(sourceId: string): void { const held = this.builders.get(sourceId); if (!held) return; if (held.timer !== undefined) clearTimeout(held.timer); @@ -1047,7 +1064,17 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { this.builders.delete(sourceId); if (held.timer !== undefined) clearTimeout(held.timer); try { - await held.client.query('SELECT pg_advisory_unlock($1::bigint)', [held.key]); + const unlocked = await held.client.query<{ unlocked: boolean }>('SELECT pg_advisory_unlock($1::bigint) AS unlocked', [held.key]); + if (unlocked.rows[0]?.unlocked !== true) { + // The session that took the lock no longer holds it: a connection + // pooler in transaction mode ran the two statements on different + // server connections, or the session was replaced. The lock may stay + // held elsewhere, or two builders may have run. + this.logger?.warn?.( + `knowledge-pgvector: the builder lock of source '${sourceId}' was not held by its session when released. ` + + 'The store needs a direct or session-mode PostgreSQL connection: a transaction-mode pooler breaks session advisory locks.', + ); + } held.client.release(); } catch (err) { // A session that is gone has let go of its lock already. From 937e8342ecca3a55893f47be1cb4d9ea8ae07365 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 10:04:13 +0000 Subject: [PATCH 6/8] fix(knowledge-pgvector): a lost CREATE EXTENSION race re-reads the extension Two sessions that run `CREATE EXTENSION IF NOT EXISTS vector` at the same moment on a fresh database: the loser fails on the catalogue's unique key although the extension now exists. ready() re-reads it after a failed create and refuses only when it is still missing. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ --- packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 2bcaa02337d..275c740338b 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -804,6 +804,10 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { ext = await this.findExtension(pool); } catch (err) { refusal = err; + // Another session may have created it at the same moment: `IF NOT + // EXISTS` does not hold between two concurrent CREATEs, and the loser + // fails on the catalogue's unique key. What counts is whether it exists now. + ext = await this.findExtension(pool).catch(() => undefined); } if (!ext) { throw notReady( From a23d48e9282ca41479300fc85f5d31b2fa7f2c79 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 10:32:07 +0000 Subject: [PATCH 7/8] fix(knowledge-pgvector): the exhausted-search error carries no catalog code Giving it CONCURRENT_MODIFICATION pins a code the error-status baseline lists as unpinned, and check:error-status-conformance then asks for that baseline row to go, a file outside this change. The code is left for a change that owns the baseline. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ --- .changeset/37101-pgvector-generations.md | 2 +- .../plugins/knowledge-pgvector/src/pgvector-adapter.ts | 7 ++----- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/.changeset/37101-pgvector-generations.md b/.changeset/37101-pgvector-generations.md index a0a6ffaad94..e3f7ce16499 100644 --- a/.changeset/37101-pgvector-generations.md +++ b/.changeset/37101-pgvector-generations.md @@ -13,6 +13,6 @@ ADR-0161 K7, rules 1 to 4, for the PostgreSQL store. - **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 search that meets three generation switches in a row is refused `CONCURRENT_MODIFICATION` (409). +- **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. diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 275c740338b..e303dadf5ae 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -495,11 +495,8 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { const hits = await this.searchAttempt(query, opts); if (hits !== undefined) return hits; if (attempt >= SEARCH_ATTEMPTS) { - throw Object.assign( - new Error( - `knowledge-pgvector: the active generation of source '${opts.source.id}' changed ${SEARCH_ATTEMPTS} times during one search; retry it.`, - ), - { code: 'CONCURRENT_MODIFICATION', status: 409 }, + throw new Error( + `knowledge-pgvector: the active generation of source '${opts.source.id}' changed ${SEARCH_ATTEMPTS} times during one search; retry it.`, ); } } From 06d53aa71c61fe68984936f028454bbbd0e66457 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 10:34:06 +0000 Subject: [PATCH 8/8] test(knowledge-pgvector): a lost CREATE EXTENSION race is not a refusal Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ --- .../src/__tests__/not-ready.test.ts | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts index fb9052b3f73..022835958db 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/not-ready.test.ts @@ -117,6 +117,31 @@ describe('knowledge-pgvector when the database is not ready', () => { expect(health).toMatchObject({ ok: false, message: expect.stringContaining('ECONNREFUSED') }); }); + it('a CREATE EXTENSION that loses a race to another session is no refusal: the extension it finds afterwards counts', async () => { + // Two sessions run `CREATE EXTENSION IF NOT EXISTS vector` on a fresh + // database at once; the loser fails on the catalogue's unique key, after + // the winner has installed it. + let installed = false; + const pool: PgPoolLike = { + query: async (text: string) => { + if (text.includes('FROM pg_extension')) { + return { rows: (installed ? [{ schema: 'public', version: '0.8.7' }] : []) as R[] }; + } + if (text.startsWith('CREATE EXTENSION')) { + installed = true; + throw new Error('duplicate key value violates unique constraint "pg_extension_name_index"'); + } + return { rows: [] as R[] }; + }, + connect: async () => { + throw new Error('no transaction expected'); + }, + }; + const adapter = new PgvectorKnowledgeAdapter({ pool, embedder: new FakeEmbedder() }); + const health = await adapter.healthCheck(); + expect(health.ok).toBe(true); + }); + it('with no embedder, a search or a listing is SERVICE_UNAVAILABLE, never a rebuild refusal of a healthy index', async () => { // A ready store holding one generation, searched under a fingerprint that // differs only because the embedder (model, width) is not registered yet.