From afeb711410410d548926b6913c642f0fccbf288b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 12:49:21 +0000 Subject: [PATCH 1/8] fix(service-knowledge): a build stops before its next page once its lease is lost, and is cancelled when it stalls Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude --- .../service-knowledge/src/knowledge-build.ts | 191 +++++++++++++++++- .../src/knowledge-service.ts | 101 +++++++-- 2 files changed, 267 insertions(+), 25 deletions(-) diff --git a/packages/services/service-knowledge/src/knowledge-build.ts b/packages/services/service-knowledge/src/knowledge-build.ts index ba44c994343..d3ad6be6491 100644 --- a/packages/services/service-knowledge/src/knowledge-build.ts +++ b/packages/services/service-knowledge/src/knowledge-build.ts @@ -24,6 +24,25 @@ * operator rebuild asks again). Beneath the lease, a store that keeps * generations takes its own builder lock in `beginBuild` (K7, rule 2). * + * ## A build that loses its lease stops; a build that stalls is cancelled + * + * Before each page the walk asks the build's fence ({@link startBuildFence}) + * whether it may go on. A lease the lock reports lost, or one not renewed + * within its {@link BUILD_LEASE_MS} (the lock store unreachable, or a renewal + * that hangs), stops the build there: no further page is read or embedded, + * nothing is purged or completed, and the record says `lease-lost`. Another + * node may build the source from then on; what this one wrote stays, and the + * next build skips it as unchanged. + * + * A build that finishes no page for {@link BUILD_STALL_LIMIT_MS} (an + * embedding call or a store call that never answers) is cancelled: the walk + * stops waiting on that call, the lease is released, and the record says + * `timed-out`. The bound is a fixed ceiling on the time between two pages, not + * on a whole build, so a large source that keeps making progress is never + * cut short. A call the build stopped waiting on cannot be withdrawn: if it + * answers later its write lands in the store as any page's would, and the + * walk never continues after it. + * * ## What a build costs * * A complete build reads every row its source's `where` matches and sends the @@ -113,6 +132,15 @@ export interface KnowledgeBuildProgress { * - `not-run` — no walk ran: another node holds the build, the cluster lock * did not answer, or (at boot) the adapter turned out to be current when * the lock was held. `message` says which. + * - `lease-lost` — the walk stopped before a page because the build's + * cluster lease was lost; nothing was purged or completed, and another node + * may build the source. `message` says how it was lost. + * - `timed-out` — no page finished for {@link BUILD_STALL_LIMIT_MS}: the + * build was cancelled and its lease released; nothing was purged or + * completed. + * + * Like `failed`, the last two leave the adapter with what it held, and the + * next build starts again. * * Kept in memory, one per source, replaced by the next build: a node answers * for the builds it ran, and a restarted node remembers none. @@ -120,7 +148,7 @@ export interface KnowledgeBuildProgress { export interface KnowledgeBuildRecord { sourceId: string; trigger: KnowledgeBuildTrigger; - status: 'running' | 'done' | 'failed' | 'not-run'; + status: 'running' | 'done' | 'failed' | 'not-run' | 'lease-lost' | 'timed-out'; /** ISO-8601 time the build was asked for. */ startedAt: string; /** ISO-8601 time it ended; absent while it runs. */ @@ -149,6 +177,16 @@ export interface KnowledgeBuildLock { /** The lease a build takes on {@link buildLockKey}; renewed every third of it while the build runs. */ export const BUILD_LEASE_MS = 60_000; +/** + * The longest a build may go without finishing a page (its read, its + * embedding and its write), or between its start and its first page, or + * between its last page and its end: past it the build is cancelled, its + * lease released and its record `timed-out`. A fixed ceiling: a page is at + * most `REINDEX_PAGE_SIZE` rows, so one that has not finished in this long + * is waiting on a call that does not answer. + */ +export const BUILD_STALL_LIMIT_MS = 15 * 60_000; + /** The least time between two progress lines of one running build. */ export const BUILD_PROGRESS_LOG_INTERVAL_MS = 10_000; @@ -159,23 +197,28 @@ export function buildLockKey(sourceId: string): string { /** * Renew `handle`'s lease every `leaseMs / 3` until the returned stop function - * is called. A failed renewal never stops the build: `onRenewFailure` is told - * once per failure, and renewal stops for good once the handle reports the - * lease lost. Each renewal is armed after the previous one settles, and the - * timer never holds the process open. + * is called. `onRenewed` is told when each renewal that started at + * `startedAt` succeeded; `onRenewFailure` once per failed one, and renewal + * stops for good once the handle reports the lease lost. Each renewal is + * armed after the previous one settles, so a renewal that hangs arms no + * other, and the timer never holds the process open. Whether the build goes + * on is the fence's question ({@link startBuildFence}), not this one's. */ export function keepBuildLeaseAlive( handle: KnowledgeBuildLockHandle, leaseMs: number, onRenewFailure: (err: unknown, stillHeld: boolean) => void, + onRenewed?: (startedAt: number) => void, ): () => void { if (typeof handle.renew !== 'function') return () => {}; const periodMs = Math.max(1, Math.floor(leaseMs / 3)); let stopped = false; let timer: ReturnType | undefined; const beat = async (): Promise => { + const startedAt = Date.now(); try { await handle.renew!(leaseMs); + if (!stopped) onRenewed?.(startedAt); } catch (err) { if (stopped) return; const held = handle.isHeld?.() === true; @@ -200,3 +243,141 @@ export function keepBuildLeaseAlive( export function emptyBuildProgress(): KnowledgeBuildProgress { return { pages: 0, discovered: 0, indexed: 0, skipped: 0, failed: 0 }; } + +/** Why a build was stopped before it ended: its record's status. */ +export type KnowledgeBuildStopReason = 'lease-lost' | 'timed-out'; + +/** A build's stop: why, and one sentence saying so. */ +export interface KnowledgeBuildStop { + reason: KnowledgeBuildStopReason; + message: string; +} + +/** + * What a running build asks before each page, and races what it waits on + * against (`KnowledgeService.rebuildSource` starts one per build). + */ +export interface KnowledgeBuildFence { + /** Why the build must stop now, or `undefined` while it may go on. */ + stop(): KnowledgeBuildStop | undefined; + /** Settles with the stop once the build passed {@link BUILD_STALL_LIMIT_MS} without a page; never rejects. */ + readonly cancelled: Promise; + /** A page finished: the stall bound starts again. */ + progressed(): void; + /** The build ended: renewal stops and the bound is disarmed. */ + close(): void; +} + +/** + * Start the fence of one build: renew `handle`'s lease + * ({@link keepBuildLeaseAlive}) and arm the stall bound. + * + * The lease reads as lost once the handle says it is not held, once a + * renewal failed and the handle no longer holds it, or once `leaseMs` passed + * since the last renewal that succeeded (since the fence started, before the + * first) — the case of a lock store that does not answer, where neither a + * renewal nor its failure ever arrives. A handle with no `renew` is judged by + * `isHeld` alone. With no handle (a composition with no cluster service) only + * the bound applies. The first stop seen is the one kept. + */ +export function startBuildFence(opts: { + handle?: KnowledgeBuildLockHandle | null; + leaseMs: number; + stallMs: number; + onRenewFailure?: (err: unknown, stillHeld: boolean) => void; +}): KnowledgeBuildFence { + const { handle, leaseMs, stallMs } = opts; + let stopped: KnowledgeBuildStop | undefined; + let closed = false; + let renewalLost = false; + const renews = typeof handle?.renew === 'function'; + let heldUntil = Date.now() + leaseMs; + const stopRenewal = handle + ? keepBuildLeaseAlive( + handle, + leaseMs, + (err, stillHeld) => { + if (!stillHeld) renewalLost = true; + opts.onRenewFailure?.(err, stillHeld); + }, + (startedAt) => { + heldUntil = Math.max(heldUntil, startedAt + leaseMs); + }, + ) + : () => {}; + + let settle: (stop: KnowledgeBuildStop) => void = () => {}; + const cancelled = new Promise((resolve) => { + settle = resolve; + }); + let timer: ReturnType | undefined; + const arm = (): void => { + if (timer) clearTimeout(timer); + if (closed || stopped) return; + timer = setTimeout(() => { + if (closed || stopped) return; + const minutes = Math.round(stallMs / 60_000); + stopped = { + reason: 'timed-out', + message: + `no page finished for ${minutes >= 1 ? `${minutes} minute(s)` : `${stallMs} ms`} (a call to the embedding ` + + 'provider or to the store that does not answer), so the build was cancelled and its lease released.', + }; + settle(stopped); + }, stallMs); + (timer as { unref?: () => void } | undefined)?.unref?.(); + }; + arm(); + + const leaseLost = (): string | undefined => { + if (!handle) return undefined; + if (renewalLost || handle.isHeld?.() === false) return 'the cluster lock reports the lease is no longer held'; + if (renews && Date.now() >= heldUntil) { + return `the lease was not renewed within its ${Math.round(leaseMs / 1000)} s (the lock store did not answer, or a renewal hangs)`; + } + return undefined; + }; + + return { + stop() { + if (stopped) return stopped; + if (closed) return undefined; + const lost = leaseLost(); + if (lost !== undefined) { + stopped = { + reason: 'lease-lost', + message: + `the build's cluster lease was lost (${lost}), so it stopped before its next page; another node may ` + + 'build the source now.', + }; + } + return stopped; + }, + cancelled, + progressed() { + arm(); + }, + close() { + closed = true; + if (timer) clearTimeout(timer); + stopRenewal(); + }, + }; +} + +/** + * `work`, raced against `fence`'s bound: answers `work`'s outcome, or throws + * the stop once the build is cancelled. A `work` that settles after that is + * dropped (its rejection is handled here, never left unhandled). No fence: + * `work` itself. + */ +export function fencedCall(fence: KnowledgeBuildFence | undefined, work: Promise): Promise { + if (!fence) return work; + work.catch(() => undefined); + return Promise.race([ + work, + fence.cancelled.then((stop): never => { + throw new Error(stop.message); + }), + ]); +} diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 079e1b1af8c..6f341f7b977 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -46,9 +46,12 @@ import { readSearchScope, scopeCheck, scopeTermsFor, type SearchScopeEntry } fro import { BUILD_LEASE_MS, BUILD_PROGRESS_LOG_INTERVAL_MS, + BUILD_STALL_LIMIT_MS, buildLockKey, emptyBuildProgress, - keepBuildLeaseAlive, + fencedCall, + startBuildFence, + type KnowledgeBuildFence, type KnowledgeBuildLock, type KnowledgeBuildLockHandle, type KnowledgeBuildProgress, @@ -452,11 +455,16 @@ export class KnowledgeService implements IKnowledgeService { return this.reindexWith(this.requireSource(sourceId), opts); } - /** {@link reindexSource}, with a sink a build's progress is reported to after each page. */ + /** + * {@link reindexSource}, with a sink a build's progress is reported to after + * each page, and the build's fence (`knowledge-build.ts`) the walk asks + * before each page. + */ private async reindexWith( source: KnowledgeSource, opts: KnowledgeReindexOptions, progress?: (step: KnowledgeBuildProgress) => void, + fence?: KnowledgeBuildFence, ): Promise { const adapter = this.getAdapter(source.adapter); @@ -491,11 +499,17 @@ export class KnowledgeService implements IKnowledgeService { } return chainAfter(this.reindexTails, source.id, () => - this.walkObjectSource(source, source.source as ObjectKnowledgeSource, adapter, engine, opts, progress), + this.walkObjectSource(source, source.source as ObjectKnowledgeSource, adapter, engine, opts, progress, fence), ); } - /** The paged walk of {@link reindexSource}; runs inside that source's chain. */ + /** + * The paged walk of {@link reindexSource}; runs inside that source's chain. + * Under a build's `fence` it stops before a page once the fence says so + * (and before its purge and completion), and stops waiting on a read, a + * write or `beginBuild` once the build is cancelled, so the source's chain + * is not held by a call that never answers. + */ private async walkObjectSource( source: KnowledgeSource, objSource: ObjectKnowledgeSource, @@ -503,6 +517,7 @@ export class KnowledgeService implements IKnowledgeService { engine: IDataEngine, opts: KnowledgeReindexOptions, progress?: (step: KnowledgeBuildProgress) => void, + fence?: KnowledgeBuildFence, ): Promise { const object = objSource.object; // `limit` keeps its meaning: a cap on the TOTAL rows the walk takes. A @@ -569,7 +584,7 @@ export class KnowledgeService implements IKnowledgeService { const build = cap === undefined; if (build && typeof adapter.beginBuild === 'function') { try { - await adapter.beginBuild(ctx); + await fencedCall(fence, adapter.beginBuild(ctx)); } catch (err) { return { ok: false, @@ -620,11 +635,15 @@ export class KnowledgeService implements IKnowledgeService { failures: [...failures], message: `reindex of source '${source.id}' stopped at page ${page}${after}: ${what}`, }); + // A build that lost its lease, or was cancelled, reads and embeds no + // further page (the fence, `knowledge-build.ts`). + const halt = fence?.stop(); + if (halt !== undefined) return stopped(halt.message); const byCursor = cursor === undefined ? undefined : { id: { $gt: cursor } }; let rows: Array>; try { - rows = await engine.find( + rows = await fencedCall(fence, engine.find( object, { where: @@ -635,7 +654,7 @@ export class KnowledgeService implements IKnowledgeService { limit: want, }, { context }, - ); + )); } catch (err) { return stopped(`the read failed: ${errorText(err)}`); } @@ -668,7 +687,7 @@ export class KnowledgeService implements IKnowledgeService { const prepared = this.prepareDocuments(plan, changed); if (prepared.ready.length > 0) { try { - await adapter.upsert(prepared.ready, ctx); + await fencedCall(fence, adapter.upsert(prepared.ready, ctx)); } catch (err) { return stopped(`the adapter upsert failed: ${operatorText(err)}`); } @@ -678,7 +697,7 @@ export class KnowledgeService implements IKnowledgeService { // reported, never truncated. if (prepared.failed.length > 0) { try { - await adapter.delete(prepared.failed.map((f) => f.documentId), ctx); + await fencedCall(fence, adapter.delete(prepared.failed.map((f) => f.documentId), ctx)); } catch (err) { return stopped(`removing the page's documents that cannot be indexed failed: ${operatorText(err)}`); } @@ -706,6 +725,23 @@ export class KnowledgeService implements IKnowledgeService { cursor = lastId; } + // A build that lost its lease after its last page neither purges nor + // completes: another node may be building the source. + const halted = fence?.stop(); + if (halted !== undefined) { + return { + ok: false, + object, + discovered, + indexed, + skipped, + purged: null, + failed, + failures: [...failures], + message: `reindex of source '${source.id}' read every page, and stopped before its purge and completion: ${halted.message}`, + }; + } + // The purge runs only after a COMPLETE walk: a `limit` walk saw part of // the source, so "not seen" there means nothing (a failed page returned // above; `dryRun` returned before the walk). @@ -909,6 +945,11 @@ export class KnowledgeService implements IKnowledgeService { * only when a build is still due; an `operator` build always walks. * - The walk is {@link reindexSource} with no `limit` and no `dryRun`: a * complete build, with `beginBuild` and `completeBuild`. + * - The walk runs under the build's fence (`knowledge-build.ts`): a lost + * lease stops it before its next page (`lease-lost`), and a build that + * finishes no page for {@link BUILD_STALL_LIMIT_MS} is cancelled + * (`timed-out`); either way the lease is released and nothing is purged + * or completed. * * Progress is logged at `info` when the build starts (with what it costs), * at most every {@link BUILD_PROGRESS_LOG_INTERVAL_MS} while it walks, and @@ -966,15 +1007,19 @@ export class KnowledgeService implements IKnowledgeService { return finish('not-run', message); } } - const stopLease = handle - ? keepBuildLeaseAlive(handle, BUILD_LEASE_MS, (err, held) => { + const fence = startBuildFence({ + handle, + leaseMs: BUILD_LEASE_MS, + stallMs: BUILD_STALL_LIMIT_MS, + onRenewFailure: (err, held) => { logger?.warn( - `${label}: the cluster lease could not be renewed (${errorText(err)}). The build continues; once the lease ` + - "lapses another node's boot or an operator rebuild may build the same source. " + - (held ? 'Renewal is retried.' : 'The lease is lost; renewal stops for this build.'), + `${label}: the cluster lease could not be renewed (${errorText(err)}). ` + + (held + ? 'Renewal is retried; the build stops before its next page if the lease lapses.' + : 'The lease is lost; the build stops before its next page.'), ); - }) - : () => {}; + }, + }); try { if (opts.trigger === 'boot') { const reading = await this.readIndexState(sourceId); @@ -989,7 +1034,10 @@ export class KnowledgeService implements IKnowledgeService { 'adapter does not already hold unchanged are sent to the embedding provider, which bills for them.', ); let lastLogged = Date.now(); - const result = await this.reindexWith(source, {}, (step) => { + const walk = this.reindexWith(source, {}, (step) => { + // A walk the build stopped waiting on writes no progress into its ended record. + if (record.status !== 'running') return; + fence.progressed(); record.progress = { ...step }; const now = Date.now(); if (now - lastLogged < BUILD_PROGRESS_LOG_INTERVAL_MS) return; @@ -998,7 +1046,19 @@ export class KnowledgeService implements IKnowledgeService { `${label}: page ${step.pages}, ${step.discovered} row(s) read, ${step.indexed} written, ` + `${step.skipped} unchanged, ${step.failed} cannot be indexed.`, ); - }); + }, fence); + // Cancelled at the stall bound: the walk is no longer waited on (it + // stops at its next page if the call it waits on ever answers). + walk.catch(() => undefined); + const raced = await Promise.race([walk, fence.cancelled.then((stop) => ({ stop }))]); + if ('stop' in raced) { + logger?.warn( + `${label} was cancelled: ${raced.stop.message} The adapter keeps what it held; ` + + 'the next boot or an operator rebuild builds again.', + ); + return finish(raced.stop.reason, raced.stop.message); + } + const result = raced; record.progress = { pages: record.progress.pages, discovered: result.discovered, @@ -1009,12 +1069,13 @@ export class KnowledgeService implements IKnowledgeService { const totals = `${result.discovered} row(s) read, ${result.indexed} written, ${result.skipped ?? 0} unchanged, ` + `${result.purged ?? 'none'} purged, ${result.failed ?? 0} cannot be indexed`; + const stop = result.ok ? undefined : fence.stop(); if (!result.ok) { logger?.warn( `${label} did not finish (${totals}): ${result.message ?? 'no reason given'} ` + 'The adapter keeps what it held; the next boot or an operator rebuild builds again.', ); - return finish('failed', result.message, result); + return finish(stop?.reason ?? 'failed', result.message, result); } logger?.info?.(`${label} finished: ${totals}.${result.message === undefined ? '' : ` ${result.message}`}`); return finish('done', result.message, result); @@ -1023,7 +1084,7 @@ export class KnowledgeService implements IKnowledgeService { logger?.warn(`${label} did not finish: ${message} The adapter keeps what it held; the next boot or an operator rebuild builds again.`); return finish('failed', message); } finally { - stopLease(); + fence.close(); if (handle) { try { await handle.release(); From e0ce7f2e76d32b0793befc73e437cdeca1e31bc7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 12:54:18 +0000 Subject: [PATCH 2/8] test(service-knowledge): pin the lease fence and the stall bound Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude --- .../__tests__/knowledge-build-fence.test.ts | 291 ++++++++++++++++++ 1 file changed, 291 insertions(+) create mode 100644 packages/services/service-knowledge/src/__tests__/knowledge-build-fence.test.ts diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-build-fence.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-build-fence.test.ts new file mode 100644 index 00000000000..b477affbc10 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/knowledge-build-fence.test.ts @@ -0,0 +1,291 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A build's fence (`knowledge-build.ts`, "A build that loses its lease stops; + * a build that stalls is cancelled"): + * + * - a lease that lapses mid-walk stops the build before its next page: no + * further page is read or embedded, nothing is completed, the record says + * `lease-lost`, and the lease is released; + * - a lease the lock store stops answering for (no renewal succeeds within + * the lease) reads as lost too; + * - an embedding call that never answers is cancelled at the stall bound: the + * record says `timed-out`, the lease is released, and the source's walk + * chain is free for the next build; + * - a build that keeps making progress is never cut by the bound. + */ + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { AdapterContext, IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import { KnowledgeService } from '../knowledge-service.js'; +import { + BUILD_LEASE_MS, + BUILD_STALL_LIMIT_MS, + startBuildFence, + type KnowledgeBuildLock, + type KnowledgeBuildLockHandle, +} from '../knowledge-build.js'; + +type Row = Record; + +/** `count` rows with zero-padded ids, so string order is id order. */ +function rows(count: number): Row[] { + return Array.from({ length: count }, (_, i) => ({ id: `r${String(i + 1).padStart(4, '0')}`, title: `Row ${i + 1}`, body: `Body ${i + 1}` })); +} + +/** A data-engine double: `find` honours `id: { $gt }` (alone or in `$and`), orders by id and takes `limit`. */ +function makeEngine(initial: Row[]) { + const all = [...initial].sort((a, b) => String(a.id).localeCompare(String(b.id))); + const after = (where: Record | undefined): string | undefined => { + if (!where) return undefined; + const and = where.$and as Array> | undefined; + const cond = (and ? and.find((c) => 'id' in c) : where) as { id?: { $gt?: unknown } } | undefined; + const gt = cond?.id?.$gt; + return gt === undefined ? undefined : String(gt); + }; + const find = vi.fn(async (_object: string, query?: { where?: Record; limit?: number }) => { + const cursor = after(query?.where); + const page = all.filter((r) => cursor === undefined || String(r.id) > cursor); + return (typeof query?.limit === 'number' ? page.slice(0, query.limit) : page).map((r) => ({ ...r })); + }); + const count = vi.fn(async () => all.length); + return { find, engine: { find, count } as unknown as IDataEngine }; +} + +/** An adapter that records every page it is handed and the build calls. */ +function makeAdapter() { + const pages: string[][] = []; + const calls = { beginBuild: 0, completeBuild: 0 }; + const adapter: IKnowledgeAdapter = { + id: 'memory', + embedding: { model: 'model-a', dimensions: 3 }, + async upsert(batch: KnowledgeDocument[], _ctx: AdapterContext) { + pages.push(batch.map((d) => d.id)); + }, + async delete() {}, + async search() { + return []; + }, + async beginBuild() { + calls.beginBuild += 1; + }, + async completeBuild() { + calls.completeBuild += 1; + }, + }; + return { adapter, pages, calls }; +} + +function source(): KnowledgeSource { + return { + id: 'kb', + label: 'Knowledge base', + adapter: 'memory', + source: { kind: 'object', object: 'kb_article', contentFields: ['title', 'body'] }, + }; +} + +function makeLogger() { + return { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; +} + +/** A cluster lock whose one handle the test steers: `held` flips the lease, `renew` can be made to hang. */ +function makeLock() { + const state = { held: true, released: 0, renewals: 0, renew: async (): Promise => {} }; + const handle: KnowledgeBuildLockHandle = { + async release() { + state.released += 1; + state.held = false; + }, + async renew() { + state.renewals += 1; + await state.renew(); + }, + isHeld: () => state.held, + }; + const lock: KnowledgeBuildLock = { acquire: async () => handle }; + return { lock, state }; +} + +function makeService(engine: IDataEngine, adapter: IKnowledgeAdapter, lock?: KnowledgeBuildLock) { + const logger = makeLogger(); + const service = new KnowledgeService({ dataEngine: engine, logger, ...(lock ? { resolveBuildLock: () => lock } : {}) }); + service.registerAdapter('memory', adapter); + service.registerSource(source()); + return { service, logger }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('a build whose lease lapses mid-walk stops before its next page', () => { + it('embeds no further page, completes nothing, records lease-lost and releases the lease', async () => { + const db = makeEngine(rows(250)); // three pages of at most 100 rows + const { adapter, pages, calls } = makeAdapter(); + const { lock, state } = makeLock(); + const upsert = adapter.upsert.bind(adapter); + adapter.upsert = async (batch, ctx) => { + await upsert(batch, ctx); + // The lease lapses while the first page is written. + state.held = false; + }; + const { service, logger } = makeService(db.engine, adapter, lock); + + const record = await service.rebuildSource('kb', { trigger: 'operator' }); + + expect(pages).toHaveLength(1); + expect(db.find).toHaveBeenCalledTimes(1); + expect(calls.completeBuild).toBe(0); + expect(record).toMatchObject({ status: 'lease-lost', progress: { pages: 1, discovered: 100 }, result: { ok: false } }); + expect(record.message).toMatch(/stopped at page 2/); + expect(record.message).toMatch(/lease was lost/); + expect(state.released).toBe(1); + expect(logger.warn.mock.calls.some((c) => String(c[0]).includes('did not finish'))).toBe(true); + }); + + it('a lease that lapses after the last page neither purges nor completes', async () => { + const db = makeEngine(rows(50)); + const { adapter, calls } = makeAdapter(); + const { lock, state } = makeLock(); + db.find.mockImplementationOnce(async () => rows(50)).mockImplementationOnce(async () => { + state.held = false; + return []; + }); + const { service } = makeService(db.engine, adapter, lock); + + const record = await service.rebuildSource('kb', { trigger: 'operator' }); + + expect(calls.completeBuild).toBe(0); + expect(record).toMatchObject({ status: 'lease-lost', result: { ok: false, purged: null } }); + expect(record.message).toMatch(/before its purge and completion/); + }); + + it('a lease no renewal kept alive within its term (a lock store that does not answer) reads as lost', async () => { + vi.useFakeTimers(); + const db = makeEngine(rows(250)); + const { adapter, pages, calls } = makeAdapter(); + const { lock, state } = makeLock(); + // Every renewal hangs: neither a success nor a failure ever arrives, and the handle still says held. + state.renew = () => new Promise(() => {}); + const upsert = adapter.upsert.bind(adapter); + let first = true; + adapter.upsert = async (batch, ctx) => { + await upsert(batch, ctx); + if (first) { + first = false; + // The first page takes longer than the lease. + await new Promise((resolve) => setTimeout(resolve, BUILD_LEASE_MS + 1_000)); + } + }; + const { service } = makeService(db.engine, adapter, lock); + + const pending = service.rebuildSource('kb', { trigger: 'operator' }); + await vi.advanceTimersByTimeAsync(BUILD_LEASE_MS + 2_000); + const record = await pending; + + expect(state.held).toBe(false); // released + expect(state.renewals).toBeGreaterThanOrEqual(1); + expect(pages).toHaveLength(1); + expect(calls.completeBuild).toBe(0); + expect(record.status).toBe('lease-lost'); + expect(record.message).toMatch(/not renewed within its 60 s/); + }); +}); + +describe('a build that stalls is cancelled at the bound', () => { + it('a never-answering embed call: timed-out, lease released, nothing completed, the next build runs', async () => { + vi.useFakeTimers(); + const db = makeEngine(rows(250)); + const { adapter, pages, calls } = makeAdapter(); + const { lock, state } = makeLock(); + const upsert = adapter.upsert.bind(adapter); + let hang = true; + adapter.upsert = async (batch, ctx) => { + // The second page's embedding call never answers. + if (pages.length === 1 && hang) return new Promise(() => {}); + await upsert(batch, ctx); + }; + const { service, logger } = makeService(db.engine, adapter, lock); + + const pending = service.rebuildSource('kb', { trigger: 'operator' }); + await vi.advanceTimersByTimeAsync(BUILD_STALL_LIMIT_MS - 1_000); + expect(service.buildRecord('kb')?.status).toBe('running'); + expect(state.released).toBe(0); + + await vi.advanceTimersByTimeAsync(2_000); + const record = await pending; + + expect(record).toMatchObject({ status: 'timed-out', progress: { pages: 1, discovered: 100 } }); + expect(record.message).toMatch(/no page finished for 15 minute\(s\)/); + expect(record.finishedAt).toBeDefined(); + expect(state.released).toBe(1); + expect(calls.completeBuild).toBe(0); + expect(pages).toHaveLength(1); + expect(logger.warn.mock.calls.some((c) => String(c[0]).includes('was cancelled'))).toBe(true); + + // The walk stopped waiting on the hung call, so the source's chain is + // free: the next build runs at once and completes. + hang = false; + state.held = true; + const next = await service.rebuildSource('kb', { trigger: 'operator' }); + expect(next.status).toBe('done'); + expect(calls.completeBuild).toBe(1); + }); + + it('a build that finishes a page within each bound is never cancelled, however long it runs', async () => { + vi.useFakeTimers(); + const db = makeEngine(rows(350)); // four pages + const { adapter, calls } = makeAdapter(); + const { lock } = makeLock(); + const upsert = adapter.upsert.bind(adapter); + adapter.upsert = async (batch, ctx) => { + // Each page takes most of the bound; the four together take far longer than it. + await new Promise((resolve) => setTimeout(resolve, BUILD_STALL_LIMIT_MS - 60_000)); + await upsert(batch, ctx); + }; + const { service } = makeService(db.engine, adapter, lock); + + const pending = service.rebuildSource('kb', { trigger: 'operator' }); + await vi.advanceTimersByTimeAsync(4 * BUILD_STALL_LIMIT_MS); + const record = await pending; + + expect(record.status).toBe('done'); + expect(calls.completeBuild).toBe(1); + }); + + it('applies with no cluster service too (one node): the bound needs no lock', async () => { + vi.useFakeTimers(); + const db = makeEngine(rows(10)); + const { adapter } = makeAdapter(); + adapter.upsert = () => new Promise(() => {}); + const { service } = makeService(db.engine, adapter); + + const pending = service.rebuildSource('kb', { trigger: 'operator' }); + await vi.advanceTimersByTimeAsync(BUILD_STALL_LIMIT_MS + 1_000); + expect((await pending).status).toBe('timed-out'); + }); +}); + +describe('startBuildFence', () => { + it('keeps the first stop it saw, and close() disarms the bound', async () => { + vi.useFakeTimers(); + let held = true; + const fence = startBuildFence({ handle: { release: async () => {}, isHeld: () => held }, leaseMs: 1_000, stallMs: 5_000 }); + expect(fence.stop()).toBeUndefined(); + held = false; + expect(fence.stop()?.reason).toBe('lease-lost'); + held = true; + expect(fence.stop()?.reason).toBe('lease-lost'); + fence.close(); + + const quiet = startBuildFence({ leaseMs: 1_000, stallMs: 5_000 }); + quiet.close(); + let settled = false; + void quiet.cancelled.then(() => { settled = true; }); + await vi.advanceTimersByTimeAsync(10_000); + expect(settled).toBe(false); + expect(quiet.stop()).toBeUndefined(); + }); +}); From fc10d38a31499d14c7c23d4f086d38dc5ed4e516 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 12:59:28 +0000 Subject: [PATCH 3/8] fix(knowledge-pgvector): a build that lost its builder lock writes and completes nothing; an exhausted search is CONCURRENT_MODIFICATION Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude --- .../build-fence.live-postgres.test.ts | 206 ++++++++++++++++++ .../src/__tests__/search-switches.test.ts | 54 +++++ .../src/pgvector-adapter.ts | 132 ++++++++++- scripts/error-status-unpinned-baseline.json | 2 - 4 files changed, 383 insertions(+), 11 deletions(-) create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/build-fence.live-postgres.test.ts create mode 100644 packages/plugins/knowledge-pgvector/src/__tests__/search-switches.test.ts diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/build-fence.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/build-fence.live-postgres.test.ts new file mode 100644 index 00000000000..3238b4be060 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/build-fence.live-postgres.test.ts @@ -0,0 +1,206 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The builder lock as a fence, on a LIVE PostgreSQL with pgvector (ADR-0161 + * K7, rule 2): + * + * - a build whose session advisory lock is gone mid-walk embeds no further + * page: its next write is refused `LOCK_CONFLICT`, and the walk stops; + * - `completeBuild` completes only the build this adapter began, and only + * the generation it began: with two builders, the first one's lock lapsing + * and the second taking the source up, the first one's completion is + * refused and switches nothing; + * - a kept lock is re-checked at the next `beginBuild`: a session that ended + * is not taken for a lock still held; + * - a building generation is retired at `beginBuild` when the fingerprint + * went back to the active one's. + */ + +import { afterAll, describe, expect, it } from 'vitest'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import type { AdapterContext } from '@objectstack/spec/contracts'; +import { KnowledgeService } from '@objectstack/service-knowledge'; +import type { PgPoolLike, PgvectorKnowledgeAdapter } from '../index.js'; +import { FakeEmbedder, PG_URL, liveStore, requireLiveCell } from './live-pg.testkit.js'; + +requireLiveCell('knowledge-pgvector build fence'); + +const store = liveStore('kpg_fence'); + +const FP_A = { fingerprint: 'fp-fence:a', recipeHash: 'rh-fence:1' }; +const FP_B = { fingerprint: 'fp-fence:b', recipeHash: 'rh-fence:1' }; + +const source = (id: string): KnowledgeSource => + ({ id, label: id, adapter: 'under_test', source: { kind: 'object', object: 'article', contentFields: ['body'] } }) as KnowledgeSource; + +const ctx = (s: KnowledgeSource, index = FP_A, reason: AdapterContext['reason'] = 'reindex'): AdapterContext => ({ source: s, reason, 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 }] }; +} + +const schemaOf = (adapter: PgvectorKnowledgeAdapter): string => (adapter as unknown as { schema: string }).schema; + +/** End the database session the adapter holds the source's builder lock on, as a dropped connection would. */ +async function endLockSession(adapter: PgvectorKnowledgeAdapter, sourceId: string): Promise { + const lock = (adapter as unknown as { builders: Map }).builders.get(sourceId)!; + 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]); +} + +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; +} + +/** A data engine over a list of rows: `find` with a keyset on `id`, ordered by id. */ +function rowsEngine(rows: Array>) { + const after = (where: Record | undefined): string | undefined => { + const and = where?.$and as Array> | undefined; + const cond = (and ? and.find((c) => 'id' in c) : where) as { id?: { $gt?: unknown } } | undefined; + return cond?.id?.$gt === undefined ? undefined : String(cond.id.$gt); + }; + return { + async find(_object: string, query: { where?: Record; limit?: number }) { + const cursor = after(query?.where); + const out = rows.filter((r) => cursor === undefined || String(r.id) > cursor); + return query?.limit === undefined ? out : out.slice(0, query.limit); + }, + async count() { + return rows.length; + }, + } as never; +} + +afterAll(async () => { + await store.dropAll(); +}); + +describe.skipIf(!PG_URL)('knowledge-pgvector build fence on a LIVE PostgreSQL', () => { + it('a build whose lock session ends mid-walk embeds no further page and completes nothing', async () => { + const embedder = new FakeEmbedder(384, 'model-fence'); + const adapter = store.adapter({ embedder }); + const s = source('lost_mid_walk'); + const rows = Array.from({ length: 250 }, (_, i) => ({ id: `r${String(i + 1).padStart(4, '0')}`, body: `granite ${i + 1}` })); + const service = new KnowledgeService({ dataEngine: rowsEngine(rows) }); + const upsert = adapter.upsert.bind(adapter); + let pages = 0; + adapter.upsert = async (batch, c) => { + await upsert(batch, c); + pages += 1; + // The session holding the builder lock drops after the first page. + if (pages === 1) await endLockSession(adapter, s.id); + }; + service.registerAdapter('under_test', adapter); + service.registerSource(s); + + const result = await service.reindexSource(s.id); + + expect(result).toMatchObject({ ok: false, discovered: 100, indexed: 100 }); + expect(result.message).toContain('stopped at page 2'); + expect(result.message).toContain("no longer holds the source's builder lock"); + expect(pages).toBe(1); + expect(embedder.calls).toBe(1); + // Not completed: no recipe hash was recorded, so the source still reads as due. + expect((await adapter.indexStatus(ctx(s))).recipeHash).toBeUndefined(); + }); + + it('two builders, the first one\'s lock lapses: its completion is refused and switches nothing', async () => { + const a = store.adapter({ buildLockIdleMs: 200 }); + const b = store.adapter({ schema: schemaOf(a) }); + const schema = schemaOf(a); + const s = source('two_builders_lapse'); + await a.upsert([doc(s, '1', 'granite quarry'), doc(s, '2', 'marble quarry')], ctx(s, FP_A, 'manual')); + + await a.beginBuild(ctx(s, FP_B)); + await a.upsert([doc(s, '1', 'granite quarry')], ctx(s, FP_B)); + // The first builder stops making progress; its lock goes after the idle time. + await new Promise((r) => setTimeout(r, 400)); + + // The second takes the source up: the same generation, under construction. + await b.beginBuild(ctx(s, FP_B)); + // The first builder's next page is refused before it is embedded ... + await expect(a.upsert([doc(s, '2', 'marble quarry')], ctx(s, FP_B))).rejects.toMatchObject({ code: 'LOCK_CONFLICT', status: 409 }); + // ... and so is its completion, which would switch the generation the second one is still writing. + await expect(a.completeBuild(ctx(s, FP_B))).rejects.toMatchObject({ code: 'LOCK_CONFLICT', status: 409 }); + // Nothing switched: the old generation is still the active one, the new one still building. + expect((await generationRows(schema, s.id)).map((g) => [g.fingerprint, g.state])).toEqual([ + [FP_A.fingerprint, 'active'], + [FP_B.fingerprint, 'building'], + ]); + + // The second builder finishes its build. + await b.upsert([doc(s, '2', 'marble quarry')], ctx(s, FP_B)); + await b.completeBuild(ctx(s, FP_B)); + expect(await b.indexStatus(ctx(s))).toEqual({ fingerprint: FP_B.fingerprint, recipeHash: FP_B.recipeHash }); + }); + + it('a builder whose lock lapsed with no write since is refused at its completion alone', async () => { + const a = store.adapter({ buildLockIdleMs: 200 }); + const b = store.adapter({ schema: schemaOf(a) }); + const s = source('lapsed_then_complete'); + await a.upsert([doc(s, '1', 'granite quarry')], ctx(s, FP_A, 'manual')); + await a.beginBuild(ctx(s, FP_B)); + await new Promise((r) => setTimeout(r, 400)); + await b.beginBuild(ctx(s, FP_B)); + + await expect(a.completeBuild(ctx(s, FP_B))).rejects.toMatchObject({ code: 'LOCK_CONFLICT', status: 409 }); + expect((await generationRows(schemaOf(a), s.id)).map((g) => g.state)).toEqual(['active', 'building']); + await b.completeBuild(ctx(s, FP_B)); + }); + + it('a build whose generation was replaced while it held the lock completes nothing', async () => { + const a = store.adapter(); + const schema = schemaOf(a); + const s = source('replaced_generation'); + await a.upsert([doc(s, '1', 'granite quarry')], ctx(s, FP_A, 'manual')); + await a.beginBuild(ctx(s, FP_B)); + // Another generation under the same fingerprint takes the place of the one this build began. + const t = `"${schema}"."knowledge_generation"`; + await store.pool().query(`UPDATE ${t} SET state = 'retired' WHERE source_id = $1 AND state = 'building'`, [s.id]); + await store.pool().query( + `INSERT INTO ${t} (source_id, generation, fingerprint, dim, model, state) VALUES ($1, 9, $2, 384, 'x', 'building')`, + [s.id, FP_B.fingerprint], + ); + + await expect(a.completeBuild(ctx(s, FP_B))).rejects.toMatchObject({ code: 'LOCK_CONFLICT', status: 409 }); + expect((await generationRows(schema, s.id)).find((g) => g.state === 'active')?.fingerprint).toBe(FP_A.fingerprint); + }); + + it('a lock kept from an earlier build is re-checked: a session that ended is not taken for a held lock', async () => { + const a = store.adapter(); + const b = store.adapter({ schema: schemaOf(a) }); + const s = source('kept_session'); + await a.beginBuild(ctx(s, FP_A)); + await endLockSession(a, s.id); + + // The lock went with the session: another process takes it. + await b.beginBuild(ctx(s, FP_A)); + // The first process begins again: it must not build beside the second. + await expect(a.beginBuild(ctx(s, FP_A))).rejects.toMatchObject({ code: 'LOCK_CONFLICT', status: 409 }); + await b.completeBuild(ctx(s, FP_A)); + }); + + it('a building generation is retired at beginBuild when the fingerprint went back to the active one', async () => { + const adapter = store.adapter(); + const schema = schemaOf(adapter); + const s = source('reverted'); + await adapter.upsert([doc(s, '1', 'granite quarry')], ctx(s, FP_A, 'manual')); + await adapter.beginBuild(ctx(s, FP_B)); + await adapter.upsert([doc(s, '1', 'granite quarry')], ctx(s, FP_B)); + // The change is reverted before the build completes: the next build is under the active fingerprint. + await adapter.beginBuild(ctx(s, FP_A)); + expect((await generationRows(schema, s.id)).map((g) => [g.fingerprint, g.state])).toEqual([[FP_A.fingerprint, 'active']]); + const passages = await store.pool().query<{ n: string }>( + `SELECT count(*) AS n FROM "${schema}"."knowledge_vec_d384" WHERE source_id = $1 AND generation <> 1`, + [s.id], + ); + expect(Number(passages.rows[0].n)).toBe(0); + await adapter.completeBuild(ctx(s, FP_A)); + expect(await adapter.indexStatus(ctx(s))).toEqual({ fingerprint: FP_A.fingerprint, recipeHash: FP_A.recipeHash }); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/search-switches.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/search-switches.test.ts new file mode 100644 index 00000000000..b4ca54863ef --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/search-switches.test.ts @@ -0,0 +1,54 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A search whose source's index is switched under it on every attempt, + * without a database: after three attempts it is refused with the ADR-0112 + * code `CONCURRENT_MODIFICATION` (409), so a caller can tell it from a fault + * and retry. + */ + +import { describe, expect, it } 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: 'switching', label: 'switching', adapter: 'pgvector', source: { kind: 'object', object: 'a', contentFields: ['b'] } } as KnowledgeSource; + +/** A store whose active generation is a new one at every read of the generations, and whose ranking finds nothing. */ +function switchingPool(): { pool: PgPoolLike; rankings: () => number } { + let generation = 0; + let rankings = 0; + 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('to_regclass')) return { rows: [{ present: 'x' }] as R[] }; + if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) { + generation += 1; + return { rows: [{ generation, fingerprint: 'fp', recipe_hash: 'rh', dim: 384, state: 'active' }] as R[] }; + } + if (text.includes('AS distance')) { + rankings += 1; + return { rows: [] as R[] }; + } + return { rows: [] as R[] }; + }; + const client = (): PgClientLike => ({ query: answer, release: () => undefined }); + return { pool: { query: answer, connect: async () => client() }, rankings: () => rankings }; +} + +describe('knowledge-pgvector search under repeated switches', () => { + it('is refused CONCURRENT_MODIFICATION (409) after three attempts', async () => { + const store = switchingPool(); + const adapter = new PgvectorKnowledgeAdapter({ pool: store.pool, embedder: new FakeEmbedder() }); + + const refusal = await adapter + .search('granite', { source, topK: 5, index: { fingerprint: 'fp', recipeHash: 'rh' } }) + .then( + () => undefined, + (err: unknown) => err, + ); + + expect(refusal).toMatchObject({ code: 'CONCURRENT_MODIFICATION', status: 409 }); + expect(String((refusal as Error).message)).toContain("Knowledge source 'switching'"); + expect(store.rankings()).toBe(3); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index e303dadf5ae..75feea8dc7b 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -110,6 +110,9 @@ const UPSERT_ATTEMPTS = 3; /** How many times {@link PgvectorKnowledgeAdapter.search} runs again when the active generation was switched under it. */ const SEARCH_ATTEMPTS = 3; +/** The standard ADR-0112 code of a search whose source's index was switched under it on every attempt. */ +const CONCURRENT_MODIFICATION = 'CONCURRENT_MODIFICATION'; + /** A generation row: one complete index of one source under one fingerprint. */ interface GenerationRow { generation: number; @@ -258,6 +261,12 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { private readonly tables = new Set(); /** The builder locks this adapter holds, by source id. */ private readonly builders = new Map(); + /** + * The builds this adapter began and has not ended, by source id: the + * generation each one builds into. A build's writes, removals and + * completion are refused once its lock is gone (the fence). + */ + private readonly builds = new Map(); constructor(opts: PgvectorKnowledgeAdapterOptions) { this.id = opts.id ?? 'pgvector'; @@ -296,6 +305,8 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { this.requirePool(); const readiness = await this.ready(); const embedder = this.requireEmbedder(); + // A build's page is embedded only while its builder lock holds. + await this.fenceBuild(ctx); 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 @@ -438,6 +449,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { if (documentIds.length === 0) return; const pool = this.requirePool(); await this.ready(); + await this.fenceBuild(ctx); this.touchBuilderLock(ctx); // From every generation of the source: a removed document leaves them all. const widths = await pool.query<{ dim: number }>( @@ -495,8 +507,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 source '${opts.source.id}' switched to a newly built index ${SEARCH_ATTEMPTS} times during one search; retry it.`, + ), + { code: CONCURRENT_MODIFICATION, status: 409 }, ); } } @@ -647,8 +662,11 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { * 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. + * for another fingerprint is abandoned: retired, and deleted in batches — + * also when the fingerprint went back to the active one's, so a reverted + * change leaves no generation behind. So is any generation a switch left + * retired. The generation taken is the one this build writes into and + * completes. */ async beginBuild(ctx: AdapterContext): Promise { const index = requireIndex(ctx, 'beginBuild'); @@ -672,7 +690,9 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { }); await this.ensureVectorTable(target.dim, readiness); await this.sweepRetired(sourceId); + this.builds.set(sourceId, target.generation); } catch (err) { + this.builds.delete(sourceId); await this.releaseBuilderLock(sourceId); throw err; } @@ -685,6 +705,12 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { * 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. + * + * Only the build this adapter began completes, and only the generation it + * began: a build whose builder lock is gone (let go after its idle time, or + * its session ended), or whose generation is no longer the one under this + * fingerprint, is refused `LOCK_CONFLICT` (409) and switches, records and + * deletes nothing — another process may have taken the source up since. */ async completeBuild(ctx: AdapterContext): Promise { const index = requireIndex(ctx, 'completeBuild'); @@ -692,9 +718,16 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { await this.ready(); const sourceId = ctx.source.id; try { + const mine = this.builds.get(sourceId); + if (mine === undefined || !(await this.holdsBuilderLock(sourceId))) throw builderLost(sourceId); await this.inTransaction(async (client) => { const { active, building } = await this.generations(sourceId, client, true); const t = qualified(this.schema, GENERATION_TABLE); + const target = + building !== undefined && building.fingerprint === index.fingerprint + ? building + : active !== undefined && active.fingerprint === index.fingerprint ? active : undefined; + if (target !== undefined && target.generation !== mine) throw generationReplaced(sourceId); 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). @@ -729,12 +762,14 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { ); } } finally { + this.builds.delete(sourceId); 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 { + this.builds.clear(); for (const sourceId of [...this.builders.keys()]) await this.releaseBuilderLock(sourceId); } @@ -1011,14 +1046,20 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { /** * 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. + * this adapter already holds when its session still holds it (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 takeBuilderLock(sourceId: string): Promise { if (this.builders.has(sourceId)) { - this.restartIdleTimer(sourceId); - return; + // Kept only while its session still holds it: a session that ended + // took the lock with it, and another process may hold it now. + if (await this.holdsBuilderLock(sourceId)) { + this.restartIdleTimer(sourceId); + return; + } + await this.releaseBuilderLock(sourceId); } const pool = this.requirePool(); const client = pool.connectSession ? await pool.connectSession() : await pool.connect(); @@ -1039,6 +1080,48 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { this.restartIdleTimer(sourceId); } + /** + * Whether the session this adapter holds the source's builder lock on + * still holds it, read from `pg_locks` on that session. A session that + * cannot answer holds nothing: PostgreSQL frees a lock with its session. + */ + private async holdsBuilderLock(sourceId: string): Promise { + const held = this.builders.get(sourceId); + if (!held) return false; + // An advisory lock on one bigint key shows in pg_locks as its high 32 + // bits (classid) and low 32 bits (objid), objsubid 1. + const key = BigInt.asUintN(64, BigInt(held.key)); + try { + const found = await held.client.query<{ held: boolean }>( + `SELECT EXISTS (SELECT 1 FROM pg_locks + WHERE locktype = 'advisory' AND pid = pg_backend_pid() AND granted AND objsubid = 1 + AND classid = $1::bigint::oid AND objid = $2::bigint::oid) AS held`, + [(key >> 32n).toString(), (key & 0xffffffffn).toString()], + ); + return found.rows[0]?.held === true; + } catch { + return false; + } + } + + /** + * The fence of a build this adapter began (ADR-0161 K7, rule 2): a call of + * the build (`ctx.reason === 'reindex'`) is refused `LOCK_CONFLICT` once the + * source's builder lock is gone — let go after its idle time, or its + * session ended — so a build that lost the lock embeds no further page and + * removes nothing. The build is ended here; its completion is refused too. + * A call outside a build this adapter began is not fenced. + */ + private async fenceBuild(ctx: AdapterContext): Promise { + if (ctx.reason !== 'reindex') return; + const sourceId = ctx.source.id; + if (!this.builds.has(sourceId)) return; + if (await this.holdsBuilderLock(sourceId)) return; + this.builds.delete(sourceId); + await this.releaseBuilderLock(sourceId); + throw builderLost(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 @@ -1167,6 +1250,37 @@ function builderBusy(sourceId: string, idleMs: number): Error { ); } +/** A build refused because it no longer holds the source's builder lock. */ +function builderLost(sourceId: string): Error { + return Object.assign( + new Error( + `This build of knowledge source '${sourceId}' no longer holds the source's builder lock; it writes and completes nothing more.`, + ), + { + code: LOCK_CONFLICT, + status: 409, + remedy: + 'The lock was let go after the build made no progress for its idle time, or its database session ended, and ' + + 'another process may be building the source. What this build wrote is kept and skipped by the next build; ' + + 'start a reindex again if none is running.', + }, + ); +} + +/** A completion refused because the generation the build began is no longer the one under its fingerprint. */ +function generationReplaced(sourceId: string): Error { + return Object.assign( + new Error( + `The index this build of knowledge source '${sourceId}' began was replaced by another build; this one completes nothing.`, + ), + { + code: LOCK_CONFLICT, + status: 409, + remedy: 'Another build took the source up after this one lost its builder lock. Start a reindex again if none is running.', + }, + ); +} + /** * The store is not ready. The message is one sentence with no database * detail, as a search caller may read it; what went wrong and the SQL to run diff --git a/scripts/error-status-unpinned-baseline.json b/scripts/error-status-unpinned-baseline.json index 72a5ed4d6fe..58cdee43dfb 100644 --- a/scripts/error-status-unpinned-baseline.json +++ b/scripts/error-status-unpinned-baseline.json @@ -1,7 +1,6 @@ { "note": "StandardErrorCode members documented with an HTTP status that NO producer this gate can read declares a status for — nothing pins the doc claim on either side. Shrink-only: a new entry is a gate failure, and a row that becomes pinned must be removed. Regenerate with `node scripts/check-error-status-conformance.mjs --update`.", "unpinned": [ - "CONCURRENT_MODIFICATION", "DUPLICATE_VALUE", "EMAIL_NOT_VERIFIED", "EXPIRED_TOKEN", @@ -11,7 +10,6 @@ "INVALID_FORMAT", "IP_RESTRICTED", "LICENSE_REQUIRED", - "LOCK_CONFLICT", "MFA_REQUIRED", "QUOTA_EXCEEDED", "SESSION_EXPIRED", From d75f38c6069ec3e5c8b652154464493d5a045b6d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:00:25 +0000 Subject: [PATCH 4/8] docs(knowledge): state the lease stop, the stall bound and the pgvector fence; changeset Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude --- .changeset/37465-knowledge-build-lease-fence.md | 16 ++++++++++++++++ content/docs/ai/knowledge-rag.mdx | 8 +++++++- .../src/__tests__/search-switches.test.ts | 2 +- 3 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 .changeset/37465-knowledge-build-lease-fence.md diff --git a/.changeset/37465-knowledge-build-lease-fence.md b/.changeset/37465-knowledge-build-lease-fence.md new file mode 100644 index 00000000000..11a332286ec --- /dev/null +++ b/.changeset/37465-knowledge-build-lease-fence.md @@ -0,0 +1,16 @@ +--- +'@objectstack/service-knowledge': patch +'@objectstack/knowledge-pgvector': patch +--- + +fix(service-knowledge, knowledge-pgvector): a build that loses its lease stops at the next page, and a build that stalls is cancelled + +Clause-②: yes (widening) +Metadata-protocol: none + +- **A build that loses its cluster lease stops.** Before each page, a build checks that it still holds its cluster lease. The lease counts as lost when the lock says so, or when no renewal has succeeded within the 60-second lease (the lock store is unreachable, or a renewal hangs). The build then stops before reading or embedding another page. It neither purges nor completes, and its record (`buildRecord`, `os knowledge status`) reads the new status `lease-lost`. Before this change the build only logged a warning and went on, so a second node could build the same source and the embedding spend doubled. +- **A build that stalls is cancelled.** A build that finishes no page for 15 minutes (a fixed ceiling, not a setting) is cancelled, for example when an embedding call never answers. The walk stops waiting on that call and the lease is released. The record reads the new status `timed-out`, and a new rebuild can start without a restart. The limit applies to the time between two pages, not to the whole build, so a large source that keeps making progress is never cut short. +- **pgvector: a build that lost its builder lock writes and completes nothing.** Each write and removal of a build checks, on the lock's own session, that the source's session advisory lock is still held. Once the lock is gone (freed after `buildLockIdleMs`, or its session ended), the write is refused `LOCK_CONFLICT` (409) before anything is embedded. `completeBuild` completes only the build this adapter began, and only the generation that build began. Otherwise it is refused `LOCK_CONFLICT` and switches, records and deletes nothing, so a build that lost its lock can no longer switch a generation another build has taken up since. A lock kept from an earlier build is re-checked at the next `beginBuild`, so a session that ended is never taken for a lock that is still held. +- **pgvector: a search whose source's index was switched under it three times** is now refused `CONCURRENT_MODIFICATION` (409) instead of throwing an error with no code. + +Widening: the exported `KnowledgeBuildRecord.status` type gains `lease-lost` and `timed-out`. A consumer that switches over it should handle both the way it handles `failed`. No other export changes: the fence and its 15-minute limit are internal to the service. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 0ae7c592b16..5b0d3090ffe 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -227,7 +227,8 @@ A store that keeps **generations** (pgvector and Turso) does not throw the old i 2. **Search during the build is refused, never answered from the old index.** A search of the source answers `KNOWLEDGE_REBUILD_REQUIRED` (409) and says the source *is being rebuilt*. A search over several sources still answers from the others, and `search_knowledge` names this one in `refused`. 3. **At the end, the switch.** Once the walk is done, the purge runs once. Then the new generation becomes the active one, and the old one is deleted. pgvector deletes it in batches of 1,000 rows, so no long lock is held over a large source. If the deletion stops part-way, the source's next build finishes it, and the old rows are never searched meanwhile. 4. **One builder per source.** pgvector takes a PostgreSQL advisory lock on the source when its build begins and holds it until the switch. A second build of the source, from another node or process, is refused `LOCK_CONFLICT` (409) and walks nothing. This is a *session* lock, so the store needs a direct or session-mode PostgreSQL connection. Behind a transaction-mode pooler (PgBouncer transaction pooling, or a hosted provider's pooled URL), the lock does not stay with the store's session. Point the store's `url` at a direct or session-mode endpoint. A release whose session no longer held the lock is logged as a warning. -5. **A build that stops is resumed, not restarted.** The generation under construction is kept, with everything written into it so far. The next build under the same fingerprint takes it up, and skips every document it already holds unchanged, so only the rest is sent to the embedding provider. If the process stops, PostgreSQL frees the lock at once. If the build fails on a process that keeps running, the lock is freed after 15 minutes without a call of the build itself. Record events that keep arriving for the source do not hold it. A build under yet another fingerprint abandons the unfinished generation and deletes it. +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, and so does a build under the active fingerprint, when the change was reverted before the new index was finished. +6. **A build that lost the lock writes nothing more.** Before each page it writes, pgvector checks that its session still holds the source's lock. Once the lock is gone (freed after the idle time, or its session dropped), the next page is refused `LOCK_CONFLICT` (409) before it is embedded, and the walk stops. Its switch is refused the same way, so a build that lost the lock never switches or deletes a generation another build has taken up since. ## The first build, and rebuilding a source @@ -242,6 +243,11 @@ Event sync keeps an index in step with rows as they are written; it never indexe A source with `refresh.onRecordChange: false` is left to its external indexer, and an adapter that reports neither an index status nor its documents is never built automatically: the boot log says so, and you rebuild it by hand. With several server nodes sharing a cluster lock driver (`OS_CLUSTER_DRIVER=redis`, [Cluster](/docs/kernel/cluster)), only one builds a source: the build runs under the `cluster` service's lock, and a node that finds the source built when it gets the lock builds nothing. `KnowledgeServicePlugin({ buildAtBoot: false })` turns the boot builds off. +Two things stop a build before it ends. Neither purges or completes anything. The store keeps what was written, and the next build skips it as unchanged: + +- **The build lost its lease.** Before each page, the build checks that it still holds its cluster lease. The lease is lost when the lock says so, or when no renewal has succeeded within the 60-second lease (the lock store is unreachable, or a renewal hangs). Then the build stops before the next page, so no further page is read or sent to the embedding provider. Its record reads `lease-lost`, and another node may build the source from then on. +- **The build stalled.** If no page finishes for 15 minutes, for example because an embedding call or a store call never answers, the build is cancelled. Its lease is released and its record reads `timed-out`, so a new rebuild can start without a restart. The limit is on the time between two pages, not on the whole build, so a large source that keeps making progress is never cut short. A call the build stopped waiting on cannot be withdrawn: if it answers later, its page is written, and the walk does not go on after it. + **A build costs money.** A complete build reads every row the source's `where` matches and sends the listed content fields of each one the index does not already hold unchanged to your embedding provider, which bills for them. The first build of a large source, or a rebuild after you change the embedding model or the split, sends all of it. The boot log line that starts a build says so. diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/search-switches.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/search-switches.test.ts index b4ca54863ef..fb787971e49 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/search-switches.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/search-switches.test.ts @@ -41,7 +41,7 @@ describe('knowledge-pgvector search under repeated switches', () => { const adapter = new PgvectorKnowledgeAdapter({ pool: store.pool, embedder: new FakeEmbedder() }); const refusal = await adapter - .search('granite', { source, topK: 5, index: { fingerprint: 'fp', recipeHash: 'rh' } }) + .search('granite', { source, topK: 5, index: { fingerprint: 'fp' } }) .then( () => undefined, (err: unknown) => err, From 9c8ea6d3817f142e0fbca37e663491eff783d41c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:01:24 +0000 Subject: [PATCH 5/8] test(service-knowledge): a stall outside the page loop is cancelled at the bound Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude --- .../src/__tests__/knowledge-build-fence.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-build-fence.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-build-fence.test.ts index b477affbc10..71fc4c07633 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-build-fence.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-build-fence.test.ts @@ -255,6 +255,20 @@ describe('a build that stalls is cancelled at the bound', () => { expect(calls.completeBuild).toBe(1); }); + it('a call outside the page loop that never answers (here completeBuild) is cancelled at the bound too', async () => { + vi.useFakeTimers(); + const db = makeEngine(rows(10)); + const { adapter } = makeAdapter(); + adapter.completeBuild = () => new Promise(() => {}); + const { lock, state } = makeLock(); + const { service } = makeService(db.engine, adapter, lock); + + const pending = service.rebuildSource('kb', { trigger: 'operator' }); + await vi.advanceTimersByTimeAsync(BUILD_STALL_LIMIT_MS + 1_000); + expect((await pending).status).toBe('timed-out'); + expect(state.released).toBe(1); + }); + it('applies with no cluster service too (one node): the bound needs no lock', async () => { vi.useFakeTimers(); const db = makeEngine(rows(10)); From 01488b87cf5598552dd5fbf6994b11cd1fac1970 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 13:23:30 +0000 Subject: [PATCH 6/8] test(knowledge-pgvector): the fence test's engine double filters and bounds like a find Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude --- .../build-fence.live-postgres.test.ts | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/build-fence.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/build-fence.live-postgres.test.ts index 3238b4be060..d2388113a39 100644 --- a/packages/plugins/knowledge-pgvector/src/__tests__/build-fence.live-postgres.test.ts +++ b/packages/plugins/knowledge-pgvector/src/__tests__/build-fence.live-postgres.test.ts @@ -57,18 +57,24 @@ async function generationRows(schema: string, sourceId: string) { return found.rows; } -/** A data engine over a list of rows: `find` with a keyset on `id`, ordered by id. */ +/** A data engine over a list of rows: `find` with equality, `$and` and a keyset on `id`, ordered by id. */ function rowsEngine(rows: Array>) { - const after = (where: Record | undefined): string | undefined => { - const and = where?.$and as Array> | undefined; - const cond = (and ? and.find((c) => 'id' in c) : where) as { id?: { $gt?: unknown } } | undefined; - return cond?.id?.$gt === undefined ? undefined : String(cond.id.$gt); + 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); + throw new Error(`rowsEngine: condition ${JSON.stringify(v)} is not implemented`); + } + return row[k] === v; + }); }; return { - async find(_object: string, query: { where?: Record; limit?: number }) { - const cursor = after(query?.where); - const out = rows.filter((r) => cursor === undefined || String(r.id) > cursor); - return query?.limit === undefined ? out : out.slice(0, query.limit); + async find(_object: string, query?: { where?: Record; limit?: number }) { + const page = rows.filter((r) => matches(r, query?.where)); + return (typeof query?.limit === 'number' ? page.slice(0, query.limit) : page).map((r) => ({ ...r })); }, async count() { return rows.length; From f9d6498ede7f60d05c4a5e431b53cdf76278c8c9 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:43:21 +0000 Subject: [PATCH 7/8] fix(service-knowledge): a lease lost during the purge completes nothing, and a hung listing, purge or completion frees the source's walk Also: the pgvector lost-lock remedy names the transaction-mode pooler; the CLI's build view knows lease-lost and timed-out; the docs cross-reference the builder lock's idle time. Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude --- .../37465-knowledge-build-lease-fence.md | 5 +- content/docs/ai/knowledge-rag.mdx | 2 +- .../cli/src/commands/knowledge/rebuild.ts | 8 +- packages/cli/src/utils/knowledge-actions.ts | 2 +- .../src/pgvector-adapter.ts | 5 +- .../__tests__/knowledge-build-fence.test.ts | 94 ++++++++++++++++--- .../src/knowledge-service.ts | 66 ++++++++++--- 7 files changed, 149 insertions(+), 33 deletions(-) diff --git a/.changeset/37465-knowledge-build-lease-fence.md b/.changeset/37465-knowledge-build-lease-fence.md index 11a332286ec..81303a1366d 100644 --- a/.changeset/37465-knowledge-build-lease-fence.md +++ b/.changeset/37465-knowledge-build-lease-fence.md @@ -1,6 +1,7 @@ --- '@objectstack/service-knowledge': patch '@objectstack/knowledge-pgvector': patch +'@objectstack/cli': patch --- fix(service-knowledge, knowledge-pgvector): a build that loses its lease stops at the next page, and a build that stalls is cancelled @@ -10,7 +11,9 @@ Metadata-protocol: none - **A build that loses its cluster lease stops.** Before each page, a build checks that it still holds its cluster lease. The lease counts as lost when the lock says so, or when no renewal has succeeded within the 60-second lease (the lock store is unreachable, or a renewal hangs). The build then stops before reading or embedding another page. It neither purges nor completes, and its record (`buildRecord`, `os knowledge status`) reads the new status `lease-lost`. Before this change the build only logged a warning and went on, so a second node could build the same source and the embedding spend doubled. - **A build that stalls is cancelled.** A build that finishes no page for 15 minutes (a fixed ceiling, not a setting) is cancelled, for example when an embedding call never answers. The walk stops waiting on that call and the lease is released. The record reads the new status `timed-out`, and a new rebuild can start without a restart. The limit applies to the time between two pages, not to the whole build, so a large source that keeps making progress is never cut short. -- **pgvector: a build that lost its builder lock writes and completes nothing.** Each write and removal of a build checks, on the lock's own session, that the source's session advisory lock is still held. Once the lock is gone (freed after `buildLockIdleMs`, or its session ended), the write is refused `LOCK_CONFLICT` (409) before anything is embedded. `completeBuild` completes only the build this adapter began, and only the generation that build began. Otherwise it is refused `LOCK_CONFLICT` and switches, records and deletes nothing, so a build that lost its lock can no longer switch a generation another build has taken up since. A lock kept from an earlier build is re-checked at the next `beginBuild`, so a session that ended is never taken for a lock that is still held. +- **pgvector: a build that lost its builder lock writes and completes nothing.** Each write and removal of a build checks, on the lock's own session, that the source's session advisory lock is still held. Once the lock is gone (freed after `buildLockIdleMs`, or its session ended), the write is refused `LOCK_CONFLICT` (409) before anything is embedded. `completeBuild` completes only the build this adapter began, and only the generation that build began. Otherwise it is refused `LOCK_CONFLICT` and switches, records and deletes nothing, so a build that lost its lock can no longer switch a generation another build has taken up since. A lock kept from an earlier build is re-checked at the next `beginBuild`, so a session that ended is never taken for a lock that is still held. **Behind a transaction-mode connection pooler** (PgBouncer transaction pooling, or a hosted provider's pooled URL), a deployment the store already did not support, the advisory lock does not stay with the session that took it. The check therefore reads a held lock as lost, and every complete build is now refused `LOCK_CONFLICT` at its first page, where before it ran with a release warning. Point the store's `url` at a direct or session-mode endpoint; the refusal's remedy says so. - **pgvector: a search whose source's index was switched under it three times** is now refused `CONCURRENT_MODIFICATION` (409) instead of throwing an error with no code. Widening: the exported `KnowledgeBuildRecord.status` type gains `lease-lost` and `timed-out`. A consumer that switches over it should handle both the way it handles `failed`. No other export changes: the fence and its 15-minute limit are internal to the service. + +`os knowledge rebuild` and `os knowledge status` know the two new statuses: a followed rebuild that ends `lease-lost` or `timed-out` exits 1 with the build's message, as a `failed` one does. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 5b0d3090ffe..ca3ade0612d 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -245,7 +245,7 @@ A source with `refresh.onRecordChange: false` is left to its external indexer, a Two things stop a build before it ends. Neither purges or completes anything. The store keeps what was written, and the next build skips it as unchanged: -- **The build lost its lease.** Before each page, the build checks that it still holds its cluster lease. The lease is lost when the lock says so, or when no renewal has succeeded within the 60-second lease (the lock store is unreachable, or a renewal hangs). Then the build stops before the next page, so no further page is read or sent to the embedding provider. Its record reads `lease-lost`, and another node may build the source from then on. +- **The build lost its lease.** Before each page, the build checks that it still holds its cluster lease. The lease is lost when the lock says so, or when no renewal has succeeded within the 60-second lease (the lock store is unreachable, or a renewal hangs). Then the build stops before the next page, so no further page is read or sent to the embedding provider. Its record reads `lease-lost`, and another node may build the source from then on. On pgvector, the stopped build's own builder lock stays with this node until its idle time passes ([item 5 above](#generations-the-new-index-is-built-beside-the-old-one)), so another node's build is refused `LOCK_CONFLICT` until then. - **The build stalled.** If no page finishes for 15 minutes, for example because an embedding call or a store call never answers, the build is cancelled. Its lease is released and its record reads `timed-out`, so a new rebuild can start without a restart. The limit is on the time between two pages, not on the whole build, so a large source that keeps making progress is never cut short. A call the build stopped waiting on cannot be withdrawn: if it answers later, its page is written, and the walk does not go on after it. diff --git a/packages/cli/src/commands/knowledge/rebuild.ts b/packages/cli/src/commands/knowledge/rebuild.ts index 4d3e99def2b..dba716aad51 100644 --- a/packages/cli/src/commands/knowledge/rebuild.ts +++ b/packages/cli/src/commands/knowledge/rebuild.ts @@ -20,8 +20,10 @@ import { * seconds and prints the build's progress until it ends. Exits 0 when the * build finished, 1 when it did not run or did not finish. With `--no-wait` * it exits 0 once the build has started and reports no outcome: the build - * may still end `not-run` (another node holds the source's lock) or - * `failed`, which only `os knowledge status` then shows. + * may still end `not-run` (another node holds the source's lock), `failed`, + * `lease-lost` (its cluster lease was lost mid-build) or `timed-out` (no page + * finished within the build's bound), which only `os knowledge status` then + * shows. * * A build sends the content fields of every row the source's `where` matches, * except those the index already holds unchanged, to the embedding provider, @@ -64,7 +66,7 @@ export default class KnowledgeRebuild extends Command { const startedBuild = started.details.build as KnowledgeBuildView | null | undefined; if (!flags.wait) { // Exit 0 here says "started", never "built": the build can still end - // not-run (another node holds the lock) or failed. + // not-run (another node holds the lock), failed, lease-lost or timed-out. this.log('Not followed (--no-wait): the build may still not run or fail. Read its outcome with os knowledge status.'); return; } diff --git a/packages/cli/src/utils/knowledge-actions.ts b/packages/cli/src/utils/knowledge-actions.ts index c77eb5c02f7..05cad208a03 100644 --- a/packages/cli/src/utils/knowledge-actions.ts +++ b/packages/cli/src/utils/knowledge-actions.ts @@ -40,7 +40,7 @@ export interface KnowledgeBuildProgressView { /** A build record, as the server reports it. */ export interface KnowledgeBuildView { trigger?: string; - status?: 'running' | 'done' | 'failed' | 'not-run'; + status?: 'running' | 'done' | 'failed' | 'not-run' | 'lease-lost' | 'timed-out'; startedAt?: string; finishedAt?: string; progress?: KnowledgeBuildProgressView; diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 75feea8dc7b..3306c28b7cb 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -1262,7 +1262,10 @@ function builderLost(sourceId: string): Error { remedy: 'The lock was let go after the build made no progress for its idle time, or its database session ended, and ' + 'another process may be building the source. What this build wrote is kept and skipped by the next build; ' + - 'start a reindex again if none is running.', + 'start a reindex again if none is running. If every build stops this way at its first page, the store is ' + + 'behind a transaction-mode connection pooler (PgBouncer transaction pooling, or a hosted pooled URL): its ' + + 'session advisory lock does not stay with the session that took it, so the lock always reads as lost. Point ' + + "the store's url at a direct or session-mode PostgreSQL endpoint. }, ); } diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-build-fence.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-build-fence.test.ts index 71fc4c07633..48b442a6b86 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-build-fence.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-build-fence.test.ts @@ -34,19 +34,23 @@ function rows(count: number): Row[] { return Array.from({ length: count }, (_, i) => ({ id: `r${String(i + 1).padStart(4, '0')}`, title: `Row ${i + 1}`, body: `Body ${i + 1}` })); } -/** A data-engine double: `find` honours `id: { $gt }` (alone or in `$and`), orders by id and takes `limit`. */ +/** A data-engine double: `find` honours equality, `$and` and `id: { $gt }`, orders by id and takes `limit`. */ function makeEngine(initial: Row[]) { const all = [...initial].sort((a, b) => String(a.id).localeCompare(String(b.id))); - const after = (where: Record | undefined): string | undefined => { - if (!where) return undefined; - const and = where.$and as Array> | undefined; - const cond = (and ? and.find((c) => 'id' in c) : where) as { id?: { $gt?: unknown } } | undefined; - const gt = cond?.id?.$gt; - return gt === undefined ? undefined : String(gt); + const matches = (row: Row, where: Record | undefined): boolean => { + if (!where) return true; + return Object.entries(where).every(([key, value]) => { + if (key === '$and') return (value as Array>).every((c) => matches(row, c)); + if (value !== null && typeof value === 'object') { + const gt = (value as { $gt?: unknown }).$gt; + if (gt === undefined) throw new Error(`engine double: condition on '${key}' is not implemented`); + return String(row[key]) > String(gt); + } + return row[key] === value; + }); }; const find = vi.fn(async (_object: string, query?: { where?: Record; limit?: number }) => { - const cursor = after(query?.where); - const page = all.filter((r) => cursor === undefined || String(r.id) > cursor); + const page = all.filter((r) => matches(r, query?.where)); return (typeof query?.limit === 'number' ? page.slice(0, query.limit) : page).map((r) => ({ ...r })); }); const count = vi.fn(async () => all.length); @@ -162,6 +166,29 @@ describe('a build whose lease lapses mid-walk stops before its next page', () => expect(record.message).toMatch(/before its purge and completion/); }); + it('a lease lost during the purge completes nothing', async () => { + const db = makeEngine(rows(50)); + const { adapter, calls } = makeAdapter(); + // The store holds one document whose row is gone: the purge removes it. + adapter.listDocuments = async () => ({ documents: [{ documentId: 'kb:gone', docHash: 'h' }] }); + const { lock, state } = makeLock(); + const removed: string[][] = []; + adapter.delete = async (ids) => { + removed.push(ids); + // The lease lapses while the purge deletes. + state.held = false; + }; + const { service } = makeService(db.engine, adapter, lock); + + const record = await service.rebuildSource('kb', { trigger: 'operator' }); + + expect(removed).toEqual([['kb:gone']]); + expect(calls.completeBuild).toBe(0); + expect(record).toMatchObject({ status: 'lease-lost', result: { ok: false } }); + expect(record.message).toMatch(/stopped before its completion/); + expect(state.released).toBe(1); + }); + it('a lease no renewal kept alive within its term (a lock store that does not answer) reads as lost', async () => { vi.useFakeTimers(); const db = makeEngine(rows(250)); @@ -255,11 +282,13 @@ describe('a build that stalls is cancelled at the bound', () => { expect(calls.completeBuild).toBe(1); }); - it('a call outside the page loop that never answers (here completeBuild) is cancelled at the bound too', async () => { + it('a call outside the page loop that never answers (here completeBuild) is cancelled, and frees the source for the next build', async () => { vi.useFakeTimers(); const db = makeEngine(rows(10)); - const { adapter } = makeAdapter(); - adapter.completeBuild = () => new Promise(() => {}); + const { adapter, calls } = makeAdapter(); + const complete = adapter.completeBuild!.bind(adapter); + let hang = true; + adapter.completeBuild = (ctx) => (hang ? new Promise(() => {}) : complete(ctx)); const { lock, state } = makeLock(); const { service } = makeService(db.engine, adapter, lock); @@ -267,6 +296,47 @@ describe('a build that stalls is cancelled at the bound', () => { await vi.advanceTimersByTimeAsync(BUILD_STALL_LIMIT_MS + 1_000); expect((await pending).status).toBe('timed-out'); expect(state.released).toBe(1); + + // The walk stopped waiting on the hung completion, so the next build is not queued behind it. + hang = false; + state.held = true; + const next = await service.rebuildSource('kb', { trigger: 'operator' }); + expect(next.status).toBe('done'); + expect(calls.completeBuild).toBe(1); + }); + + it('a hung listing or a hung purge is cancelled at the bound, completes nothing, and frees the source', async () => { + for (const where of ['listing', 'purge'] as const) { + vi.useFakeTimers(); + const db = makeEngine(rows(10)); + const { adapter, calls } = makeAdapter(); + let hang = true; + adapter.listDocuments = async () => { + if (hang && where === 'listing') return new Promise(() => {}); + return { documents: [{ documentId: 'kb:gone', docHash: 'h' }] }; + }; + adapter.delete = async () => { + if (hang && where === 'purge') return new Promise(() => {}); + }; + const { lock, state } = makeLock(); + const { service } = makeService(db.engine, adapter, lock); + + const pending = service.rebuildSource('kb', { trigger: 'operator' }); + await vi.advanceTimersByTimeAsync(BUILD_STALL_LIMIT_MS + 1_000); + expect((await pending).status, where).toBe('timed-out'); + expect(state.released, where).toBe(1); + expect(calls.completeBuild, where).toBe(0); + + hang = false; + state.held = true; + // The hung removal still holds that one document's own sync chain (a + // per-document chain, not the source's walk chain), so the next build + // is run against a store that no longer lists it. + if (where === 'purge') adapter.listDocuments = async () => ({ documents: [] }); + expect((await service.rebuildSource('kb', { trigger: 'operator' })).status, where).toBe('done'); + expect(calls.completeBuild, where).toBe(1); + vi.useRealTimers(); + } }); it('applies with no cluster service too (one node): the bound needs no lock', async () => { diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 6f341f7b977..5199b979204 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -602,7 +602,24 @@ export class KnowledgeService implements IKnowledgeService { // What the adapter holds before the walk: the skip's hashes, and the // purge's candidates once the walk is complete. - const listing = await listAdapterDocuments(source, adapter, plan.index); + // Raced against the build's bound like every call of the walk, so a store + // that never answers frees the source's chain. + let listing: Awaited>; + try { + listing = await fencedCall(fence, listAdapterDocuments(source, adapter, plan.index)); + } catch (err) { + return { + ok: false, + object, + discovered: 0, + indexed: 0, + skipped: 0, + purged: null, + failed: 0, + failures: [], + message: `reindex of source '${source.id}' stopped before its first page: ${errorText(err)}`, + }; + } const listed = listing.ok ? listing.documents : undefined; const listingNote = listing.ok || listing.reason === undefined ? undefined @@ -762,19 +779,28 @@ export class KnowledgeService implements IKnowledgeService { }; if (listingNote) return { ...done, message: failedNote === undefined ? listingNote : `${listingNote} ${failedNote}` }; if (listed === undefined || cap !== undefined || (source.refresh?.onRecordChange ?? true) === false) { - return build ? this.completeBuild(source, adapter, ctx, done) : done; + return build ? this.completeBuild(source, adapter, ctx, done, fence) : done; } const candidates = [...listed.keys()].filter((id) => !seen.has(id)); - const purge = await purgeDocuments({ - source, - objSource, - adapter, - engine, - candidates, - serialize: (documentId, task) => chainAfter(this.recordSyncTails, documentId, task), - index: plan.index, - }); + let purge: PurgeDocumentsOutcome; + try { + purge = await fencedCall(fence, purgeDocuments({ + source, + objSource, + adapter, + engine, + candidates, + serialize: (documentId, task) => chainAfter(this.recordSyncTails, documentId, task), + index: plan.index, + })); + } catch (err) { + return { + ...done, + ok: false, + message: `reindex of source '${source.id}' walked every page, and stopped during its purge: ${errorText(err)}`, + }; + } if (purge.failure !== undefined) { return { ...done, @@ -793,9 +819,9 @@ export class KnowledgeService implements IKnowledgeService { `${purge.foreign} listed document(s) carry an id that is not one this source derives from a record ` + `('${source.id}:' and the record id); they were kept, because no row can confirm them.` + (failedNote === undefined ? '' : ` ${failedNote}`), - }); + }, fence); } - return this.completeBuild(source, adapter, ctx, { ...done, purged: purge.purged }); + return this.completeBuild(source, adapter, ctx, { ...done, purged: purge.purged }, fence); } /** @@ -804,16 +830,28 @@ export class KnowledgeService implements IKnowledgeService { * carried. An adapter without it records nothing. One that throws turns the * walk's result into `ok: false`: every page was written, but the adapter * did not record what it holds, so the next complete walk builds again. + * Under a build's `fence`, a build that must stop (its lease lost during + * the purge, or its bound passed) completes nothing, and the call is raced + * against the bound. */ private async completeBuild( source: KnowledgeSource, adapter: IKnowledgeAdapter, ctx: AdapterContext, done: KnowledgeReindexResult, + fence?: KnowledgeBuildFence, ): Promise { + const halt = fence?.stop(); + if (halt !== undefined) { + return { + ...done, + ok: false, + message: `reindex of source '${source.id}' walked every page, and stopped before its completion: ${halt.message}`, + }; + } if (typeof adapter.completeBuild !== 'function') return done; try { - await adapter.completeBuild(ctx); + await fencedCall(fence, adapter.completeBuild(ctx)); return done; } catch (err) { return { From fda121f9a6edf2713f0a03d3a622b0819ee6fd05 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 14:45:38 +0000 Subject: [PATCH 8/8] fix(knowledge-pgvector): close the lost-lock remedy string Claude-Session: https://claude.ai/code/session_01Utp6Cb4BAjgQ43tqy1DvVJ Co-authored-by: Claude --- packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 3306c28b7cb..f2e3e75a57e 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -1265,7 +1265,7 @@ function builderLost(sourceId: string): Error { 'start a reindex again if none is running. If every build stops this way at its first page, the store is ' + 'behind a transaction-mode connection pooler (PgBouncer transaction pooling, or a hosted pooled URL): its ' + 'session advisory lock does not stay with the session that took it, so the lock always reads as lost. Point ' + - "the store's url at a direct or session-mode PostgreSQL endpoint. + "the store's url at a direct or session-mode PostgreSQL endpoint.", }, ); }