diff --git a/.changeset/38479-knowledge-boot-window.md b/.changeset/38479-knowledge-boot-window.md new file mode 100644 index 00000000000..60c33e8d033 --- /dev/null +++ b/.changeset/38479-knowledge-boot-window.md @@ -0,0 +1,12 @@ +--- +'@objectstack/service-knowledge': patch +--- + +fix(service-knowledge): a record write before the boot reads a runtime-composed knowledge service calls no store + +Clause-②: no +Metadata-protocol: none + +A knowledge service the runtime composes is read as enabled or held once, at `kernel:bootstrapped` (ADR-0161 K8, the dated note on item 12). A record write could land before that reading, such as a seed or a package's sample data on a new project's first boot, and its sync ran at once. On a deployment with no embedder this called the store, and the boot logged a `[knowledge] a batch of N record syncs of source … failed (… has no embedder …)` warning, although a held service calls no store. + +Now a record sync that arrives before the reading waits for it, on every path: inline, and on the record-sync queue's per-message and batch paths. Nothing calls a store meanwhile. Once the reading is taken, a held service completes each sync without one, and an enabled service runs it as it did before. The inline sync never holds the write up: it is deferred past the reading, so a write the boot itself awaits does not wait on a reading that comes after it. A service a host mounts itself has no such window and syncs as before. If the service stops before the reading (a boot that failed first), every waiting sync completes without one, so the queue's worker is not left waiting at shutdown. diff --git a/packages/services/service-knowledge/src/__tests__/boot-window-38479.test.ts b/packages/services/service-knowledge/src/__tests__/boot-window-38479.test.ts new file mode 100644 index 00000000000..599fdf4a200 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/boot-window-38479.test.ts @@ -0,0 +1,205 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38479, ADR-0161 K8, the dated note on item 12] A service the runtime + * composed is read as enabled or held once, at `kernel:bootstrapped`. A record + * write can land before that reading: a seed, or a package's sample data, on + * a new project's first boot. Its sync — inline, on the queue's per-message + * path or on its batch path — calls no store until the reading: + * + * - held (no embedder, or the deployment's store not mounted): each completes + * without a sync, and no store is ever called for it; + * - enabled: each runs once the reading is taken, as it would have before. + * + * The inline sync never holds the write up: a write the boot itself awaits + * would otherwise wait for a reading that comes after it. A service a host + * mounts itself has no such window and syncs at once, as it always did. + * + * The second half pins the reap guard on an enabled runtime-composed service: + * it is registered at the reading, before the earliest sweep a host can run + * at `kernel:bootstrapped`, so that sweep de-indexes before it deletes. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { LiteKernel } from '@objectstack/core'; +import type { Plugin, PluginContext } from '@objectstack/core'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import { KnowledgeService } from '../knowledge-service.js'; +import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js'; + +/** The lifecycle service's guard shape, as `knowledge-reap-guard.ts` builds it. */ +type ReapGuard = (object: string, rows: Array>) => Promise>; + +const SOURCE: KnowledgeSource = { + name: 'kb', + label: 'KB', + adapter: 'vec', + source: { kind: 'object', object: 'kb_article', content: ['body'] }, +}; + +function setup(opts: { runtimeComposed: boolean }) { + const calls: string[] = []; + const adapter: IKnowledgeAdapter = { + id: 'vec', + upsert: vi.fn(async () => { calls.push('upsert'); }), + delete: vi.fn(async () => { calls.push('delete'); }), + search: vi.fn(async () => { calls.push('search'); return []; }), + }; + const rows: Record[] = [{ id: 'r1', body: 'Seeded article' }]; + const engine = { + find: vi.fn(async (_object: string, q: { where?: Record } = {}) => { + const ids = (q.where as { id?: { $in?: unknown[] } } | undefined)?.id?.$in; + const wanted = (q.where as { id?: unknown } | undefined)?.id; + return rows.filter((r) => (ids ? ids.includes(r.id) : typeof wanted === 'string' ? r.id === wanted : true)); + }), + findOne: vi.fn(async () => rows[0]), + } as unknown as IDataEngine; + const warn = vi.fn(); + const service = new KnowledgeService({ + dataEngine: engine, + logger: { warn, debug: () => undefined, info: () => undefined }, + ...(opts.runtimeComposed ? { enabledByConfiguration: true } : {}), + }); + service.registerAdapter('vec', adapter); + service.registerSource(SOURCE); + return { service, adapter, calls, warn }; +} + +const MESSAGE = { source: 'kb', object: 'kb_article', recordId: 'r1', reason: 'event' }; + +/** Let every queued promise settle. */ +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); + +describe('[#38479] a record write before the boot reads a runtime-composed service calls no store', () => { + it('held: the inline sync, a queued message and a queued batch wait, then complete without a sync; no store is called', async () => { + const { service, calls, warn } = setup({ runtimeComposed: true }); + + // Inline: the write is not held up. + await expect(service.handleRecordUpsert('kb_article', { id: 'r1', body: 'Seeded article' })).resolves.toBeUndefined(); + await expect(service.handleRecordDelete('kb_article', 'r0')).resolves.toBeUndefined(); + // The queue's worker took the messages before the reading. + const one = service.processRecordSync(MESSAGE); + const batch = service.processRecordSyncBatch([{ data: MESSAGE }]); + await settle(); + expect(calls).toEqual([]); + + service.settleEnablement({ embedder: 'no embedder provider is saved' }); + + await expect(one).resolves.toBe('not-synced'); + await expect(batch).resolves.toEqual([{ ok: true, outcome: 'not-synced' }]); + await settle(); + expect(calls).toEqual([]); + expect(warn).not.toHaveBeenCalled(); + }); + + it('enabled: the same syncs wait for the reading, then run as ever', async () => { + const { service, adapter, calls } = setup({ runtimeComposed: true }); + + await service.handleRecordUpsert('kb_article', { id: 'r1', body: 'Seeded article' }); + await service.handleRecordDelete('kb_article', 'r0'); + const one = service.processRecordSync(MESSAGE); + await settle(); + expect(calls).toEqual([]); + + service.settleEnablement(undefined); + + await expect(one).resolves.toBe('synced'); + await vi.waitFor(() => expect(vi.mocked(adapter.delete)).toHaveBeenCalledWith(['kb:r0'], expect.anything())); + const upserted = vi.mocked(adapter.upsert).mock.calls.flatMap(([docs]) => docs.map((d) => d.id)); + expect(upserted).toEqual(['kb:r1', 'kb:r1']); + }); + + it('stopped before the reading (a boot that failed first): every waiting sync completes without one, and none waits after', async () => { + const { service, calls } = setup({ runtimeComposed: true }); + + await service.handleRecordUpsert('kb_article', { id: 'r1', body: 'Seeded article' }); + const one = service.processRecordSync(MESSAGE); + const batch = service.processRecordSyncBatch([{ data: MESSAGE }]); + await settle(); + + service.stopBuilds(); + + await expect(one).resolves.toBe('not-synced'); + await expect(batch).resolves.toEqual([{ ok: true, outcome: 'not-synced' }]); + // A message taken after the stop does not wait either. + await expect(service.processRecordSync(MESSAGE)).resolves.toBe('not-synced'); + await settle(); + expect(calls).toEqual([]); + }); + + it('control: a service a host mounts itself syncs at once, as it always did', async () => { + const { service, adapter } = setup({ runtimeComposed: false }); + await service.handleRecordUpsert('kb_article', { id: 'r1', body: 'Seeded article' }); + expect(adapter.upsert).toHaveBeenCalledOnce(); + await expect(service.processRecordSync(MESSAGE)).resolves.toBe('synced'); + }); +}); + +/** The earliest sweep a host can run: in its own `kernel:bootstrapped` handler, registered after the knowledge plugin's. */ +class BootSweepPlugin implements Plugin { + name = 'test.boot-sweep'; + version = '1.0.0'; + type = 'standard' as const; + dependencies = ['com.objectstack.service.knowledge']; + constructor(private readonly order: string[], private readonly guards: Array) {} + async init(): Promise {} + async start(ctx: PluginContext): Promise { + ctx.hook('kernel:bootstrapped', async () => { + this.order.push(`sweep (guards: ${this.guards.length})`); + for (const guard of this.guards) await guard('kb_article', [{ id: 'k1' }]); + }); + } +} + +describe('[#38479] the reap guard of an enabled runtime-composed service is registered before the first sweep', () => { + it('registered at the reading, so a sweep at kernel:bootstrapped de-indexes before it deletes', async () => { + const order: string[] = []; + const guards: Array = []; + const deletedDocs: string[] = []; + const lifecycle = { + registerReapGuard: vi.fn((object: string, guard: ReapGuard) => { + order.push(`guard ${object}`); + guards.push(guard); + }), + }; + const adapter: IKnowledgeAdapter = { + id: 'vec', + upsert: async () => undefined, + delete: async (ids: string[]) => { deletedDocs.push(...ids); }, + search: async () => [], + }; + const kernel = new LiteKernel(); + kernel.use({ + name: 'test.lifecycle-and-embedder', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService('lifecycle', lifecycle); + ctx.registerService('embedder', { id: 'own', dimensions: 2, embed: async (t: string[]) => t.map(() => [1, 0]) }); + }, + } as Plugin); + kernel.use(new KnowledgeServicePlugin({ + sources: [{ ...SOURCE, adapter: undefined }], + deploymentAdapter: 'vec', + runtimeComposed: { declared: false }, + buildAtBoot: false, + reconcile: false, + })); + kernel.use({ + name: 'test.deployment-store', + version: '1.0.0', + dependencies: ['com.objectstack.service.knowledge'], + async init() {}, + async start(ctx: PluginContext) { + ctx.getService('knowledge').registerAdapter('vec', adapter); + }, + } satisfies Plugin); + kernel.use(new BootSweepPlugin(order, guards)); + await kernel.bootstrap(); + + expect(kernel.getService('knowledge').heldReading()).toBeUndefined(); + expect(order).toEqual(['guard kb_article', 'sweep (guards: 1)']); + expect(deletedDocs).toEqual(['kb:k1']); + await kernel.shutdown(); + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-service-indexing.ts b/packages/services/service-knowledge/src/knowledge-service-indexing.ts index a54344f999a..024851a98ab 100644 --- a/packages/services/service-knowledge/src/knowledge-service-indexing.ts +++ b/packages/services/service-knowledge/src/knowledge-service-indexing.ts @@ -109,6 +109,7 @@ export interface KnowledgeIndexingHost { readonly buildUnderLease: KnowledgeService['buildUnderLease']; readonly builds: KnowledgeService['builds']; buildsStopped: KnowledgeService['buildsStopped']; + readonly enablementWaiters: KnowledgeService['enablementWaiters']; readonly cancelPendingReconcile: KnowledgeService['cancelPendingReconcile']; readonly clearRepairedFailures: KnowledgeService['clearRepairedFailures']; readonly closeStaleBuild: KnowledgeService['closeStaleBuild']; @@ -1277,9 +1278,13 @@ export async function buildIfDue( /** The body of {@link KnowledgeService.stopBuilds}; the member's docblock there is its contract. */ export function stopBuilds( - this: Pick, + this: Pick, ): void { this.buildsStopped = true; + // [#38479] A record sync still waiting for the boot's enablement reading + // (a boot that failed before it) completes without a sync, so the queue's + // worker is not left waiting while it is unsubscribed. + for (const wake of this.enablementWaiters.splice(0)) wake(false); for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key); } diff --git a/packages/services/service-knowledge/src/knowledge-service-record-sync.ts b/packages/services/service-knowledge/src/knowledge-service-record-sync.ts index 8cdba5dc3e6..d95466ef55a 100644 --- a/packages/services/service-knowledge/src/knowledge-service-record-sync.ts +++ b/packages/services/service-knowledge/src/knowledge-service-record-sync.ts @@ -93,6 +93,8 @@ export interface KnowledgeRecordSyncHost { readonly considerBacklogReconcile: KnowledgeService['considerBacklogReconcile']; readonly coveredByBuild: KnowledgeService['coveredByBuild']; readonly deadLettersOf: KnowledgeService['deadLettersOf']; + readonly enablementPending: KnowledgeService['enablementPending']; + readonly enablementWaiters: KnowledgeService['enablementWaiters']; readonly enqueueReconcile: KnowledgeService['enqueueReconcile']; readonly handed: KnowledgeService['handed']; readonly held: KnowledgeService['held']; @@ -386,12 +388,41 @@ export function publishRecordSyncs( else send(); } +/** + * [#38479, ADR-0161 K8] A service the runtime composed is neither held nor + * enabled until the boot reads it at `kernel:bootstrapped` + * (`KnowledgeService.settleEnablement`), and a record write can land before + * that: a seed, or a package's sample data. A record sync that arrives in that + * window waits for the reading and calls no store meanwhile; once it is read, + * held completes the sync without one and enabled runs it as ever. The answer + * is `undefined` when there is nothing to wait for: a service a host mounts + * itself, and one whose reading is settled. Otherwise it resolves `true` once + * the reading is taken, or `false` when the service stops first + * (`KnowledgeService.stopBuilds`, a boot that failed before the reading): + * the sync then completes without one, so a stopping worker never waits on a + * reading that will not come. + */ +function enablementSettled( + host: Pick, +): Promise | undefined { + if (!host.enablementPending) return undefined; + if (host.buildsStopped) return Promise.resolve(false); + return new Promise((wake) => host.enablementWaiters.push(wake)); +} + /** The body of {@link KnowledgeService.processRecordSync}; the member's docblock there is its contract. */ export async function processRecordSync( - this: Pick, + this: Pick< + KnowledgeRecordSyncHost, + 'adapterFor' | 'buildsStopped' | 'enablementPending' | 'enablementWaiters' | 'recordSyncTails' | + 'resolveRecordSync' | 'syncRow' + >, data: unknown, publishedAt?: number, ): Promise { + // [#38479] The worker may take a message before the boot's reading: it + // waits for it, so a held deployment calls no store for it. + if ((await enablementSettled(this)) === false) return 'not-synced'; const resolved = this.resolveRecordSync(data, publishedAt); if ('outcome' in resolved) return resolved.outcome; const { source, message, engine } = resolved; @@ -493,9 +524,16 @@ export function coveredByBuild( /** The body of {@link KnowledgeService.processRecordSyncBatch}; the member's docblock there is its contract. */ export async function processRecordSyncBatch( - this: Pick, + this: Pick< + KnowledgeRecordSyncHost, + 'buildsStopped' | 'considerBacklogReconcile' | 'enablementPending' | 'enablementWaiters' | 'resolveRecordSync' | + 'syncRecordGroup' + >, batch: readonly KnowledgeRecordSyncBatchItem[], ): Promise { + // [#38479] As on the per-message path: a batch taken before the boot's + // reading waits for it. + if ((await enablementSettled(this)) === false) return batch.map(() => ({ ok: true, outcome: 'not-synced' })); const results: KnowledgeRecordSyncBatchResult[] = new Array(batch.length); const groups = new Map(); batch.forEach((item, index) => { @@ -837,10 +875,22 @@ export async function syncRows( /** The body of {@link KnowledgeService.handleRecordUpsert}; the member's docblock there is its contract. */ export async function handleRecordUpsert( - this: Pick, + this: Pick< + KnowledgeRecordSyncHost, + 'buildsStopped' | 'enablementPending' | 'enablementWaiters' | 'held' | 'options' | 'serializeRecordSync' | + 'sourcesForObject' | 'syncRecord' + >, object: string, record: Record, ): Promise { + // [#38479] Before the boot's reading the sync is deferred past it and the + // write is not held up: a write the boot itself awaits (a seed) would + // otherwise wait for a reading that comes after it. + const settled = enablementSettled(this); + if (settled) { + void settled.then((go) => (go ? handleRecordUpsert.call(this, object, record) : undefined)).catch((err: unknown) => deferredSyncFailed(this, object, err)); + return; + } if (this.held) return; const recordId = record.id; for (const source of this.sourcesForObject(object)) { @@ -1008,15 +1058,30 @@ export function schemaFor(this: Pick, object } } +/** A record sync deferred past the boot's reading that failed where nothing awaits it: one `warn` line. */ +function deferredSyncFailed(host: Pick, object: string, err: unknown): void { + host.options.logger?.warn?.( + `[knowledge] a record sync of object '${object}' deferred past the boot's enablement reading failed: ` + + `${err instanceof Error ? err.message : String(err)}`, + ); +} + /** The body of {@link KnowledgeService.handleRecordDelete}; the member's docblock there is its contract. */ export async function handleRecordDelete( this: Pick< KnowledgeRecordSyncHost, - 'adapterFor' | 'held' | 'label' | 'options' | 'planIndex' | 'serializeRecordSync' | 'sourcesForObject' + 'adapterFor' | 'buildsStopped' | 'enablementPending' | 'enablementWaiters' | 'held' | 'label' | 'options' | 'planIndex' | + 'serializeRecordSync' | 'sourcesForObject' >, object: string, recordId: string, ): Promise { + // [#38479] Deferred past the boot's reading, as {@link handleRecordUpsert}. + const settled = enablementSettled(this); + if (settled) { + void settled.then((go) => (go ? handleRecordDelete.call(this, object, recordId) : undefined)).catch((err: unknown) => deferredSyncFailed(this, object, err)); + return; + } if (this.held) return; const targets = this.sourcesForObject(object); for (const source of targets) { diff --git a/packages/services/service-knowledge/src/knowledge-service-sources.ts b/packages/services/service-knowledge/src/knowledge-service-sources.ts index d82fce85087..1c112c60307 100644 --- a/packages/services/service-knowledge/src/knowledge-service-sources.ts +++ b/packages/services/service-knowledge/src/knowledge-service-sources.ts @@ -79,6 +79,7 @@ export interface KnowledgeSourcesHost { readonly cancelPendingReconcile: KnowledgeService['cancelPendingReconcile']; readonly describeSources: KnowledgeService['describeSources']; enablementPending: KnowledgeService['enablementPending']; + readonly enablementWaiters: KnowledgeService['enablementWaiters']; readonly forget: KnowledgeService['forget']; held: KnowledgeService['held']; readonly label: KnowledgeService['label']; @@ -97,11 +98,17 @@ export interface KnowledgeSourcesHost { /** The body of {@link KnowledgeService.settleEnablement}; the member's docblock there is its contract. */ export function settleEnablement( - this: Pick, + this: Pick< + KnowledgeSourcesHost, + 'cancelPendingReconcile' | 'enablementPending' | 'enablementWaiters' | 'held' | 'pendingReconciles' + >, held: KnowledgeHeldReading | undefined, ): void { this.enablementPending = false; this.held = held; + // [#38479] The record syncs that waited for this reading go on now: held, + // each completes without a sync; enabled, each runs. + for (const wake of this.enablementWaiters.splice(0)) wake(true); if (!held) return; for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key); } diff --git a/packages/services/service-knowledge/src/knowledge-service-top-level.ts b/packages/services/service-knowledge/src/knowledge-service-top-level.ts index a50e0ef8038..87dd1ba7ef3 100644 --- a/packages/services/service-knowledge/src/knowledge-service-top-level.ts +++ b/packages/services/service-knowledge/src/knowledge-service-top-level.ts @@ -107,8 +107,8 @@ export interface KnowledgeServiceOptions { * [ADR-0161 K8, the dated note on item 12] The runtime composed this * service, so it is enabled by configuration: until the boot's reading * settles it ({@link KnowledgeService.settleEnablement}), the service hands - * out no tool definition, and once settled it either serves or holds its - * sources. `KnowledgeServicePlugin` sets it from its `runtimeComposed` + * out no tool definition and a record sync waits for the reading, calling + * no store, and once settled it either serves or holds its sources. `KnowledgeServicePlugin` sets it from its `runtimeComposed` * option. Omitted (a host that mounts the service itself), the service * serves from the start, as it always has. */ diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 799d4c309f4..1c7fd455f6f 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -197,6 +197,14 @@ export class KnowledgeService implements IKnowledgeService { * always `false` on a service a host mounted itself. */ private enablementPending: boolean; + /** + * [#38479] The record syncs that arrived while {@link enablementPending}: + * each waits here, calling no store, until {@link settleEnablement} reads + * the boot. Held ⇒ each then completes without a sync; enabled ⇒ each runs. + * Woken `true` by the reading, `false` by {@link stopBuilds} (the service + * stopped first): then each completes without a sync. + */ + private readonly enablementWaiters: Array<(proceed: boolean) => void> = []; constructor(private readonly options: KnowledgeServiceOptions = {}) { this.defaultTopK = options.defaultTopK ?? 10; @@ -222,6 +230,12 @@ export class KnowledgeService implements IKnowledgeService { * The state is the whole service's, whichever store a source names (the * note's point 2). Called once, by `KnowledgeServicePlugin`; a later boot * reads the state again. + * + * [#38479] Until this reading, a record sync calls no store: one that + * arrives first (a seed, a package's sample data) waits for it, and then + * completes without a sync when held, or runs when enabled. The queue's + * worker awaits the reading; an inline sync is deferred past it, so the + * write is not held up. */ settleEnablement(held: KnowledgeHeldReading | undefined): void { return KnowledgeSourcesFacet.settleEnablement.call(knowledgeServiceHost.of(this), held); @@ -815,7 +829,9 @@ export class KnowledgeService implements IKnowledgeService { /** * Stop the boot pass and the reconcile from starting another build, and * drop every reconcile a predicate write asked for that has not started. A - * build already walking runs to its end. + * build already walking runs to its end. A record sync still waiting for the + * boot's enablement reading ({@link settleEnablement}) completes without a + * sync. */ stopBuilds(): void { return KnowledgeIndexingFacet.stopBuilds.call(knowledgeServiceHost.of(this)); @@ -1363,6 +1379,11 @@ export class KnowledgeService implements IKnowledgeService { * last one leaves the index agreeing with the database. Inline, the chain * is awaited, so a write's sync can wait behind an earlier in-flight sync * of the same document; the index still ends consistent. + * + * [#38479] On a service the runtime composed, a call made before the boot's + * enablement reading ({@link settleEnablement}) returns at once: the sync + * is deferred past the reading, then skipped when held or run when enabled. + * The same holds for {@link handleRecordDelete}. */ handleRecordUpsert(object: string, record: Record): Promise { return KnowledgeRecordSyncFacet.handleRecordUpsert.call(knowledgeServiceHost.of(this), object, record); @@ -1600,6 +1621,7 @@ export class KnowledgeService implements IKnowledgeService { dropUnverifiedHits: (...a) => service.dropUnverifiedHits(...a), get enablementPending() { return service.enablementPending; }, set enablementPending(v) { service.enablementPending = v; }, + get enablementWaiters() { return service.enablementWaiters; }, enqueueReconcile: (...a) => service.enqueueReconcile(...a), faceOfKey: (...a) => service.faceOfKey(...a), facedRefusals: (...a) => service.facedRefusals(...a),