Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/38479-knowledge-boot-window.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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<Record<string, unknown>>) => Promise<Array<string | number>>;

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<string, unknown>[] = [{ id: 'r1', body: 'Seeded article' }];
const engine = {
find: vi.fn(async (_object: string, q: { where?: Record<string, unknown> } = {}) => {
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<ReapGuard>) {}
async init(): Promise<void> {}
async start(ctx: PluginContext): Promise<void> {
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<ReapGuard> = [];
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<KnowledgeService>('knowledge').registerAdapter('vec', adapter);
},
} satisfies Plugin);
kernel.use(new BootSweepPlugin(order, guards));
await kernel.bootstrap();

expect(kernel.getService<KnowledgeService>('knowledge').heldReading()).toBeUndefined();
expect(order).toEqual(['guard kb_article', 'sweep (guards: 1)']);
expect(deletedDocs).toEqual(['kb:k1']);
await kernel.shutdown();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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'];
Expand Down Expand Up @@ -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<KnowledgeIndexingHost, 'buildsStopped' | 'cancelPendingReconcile' | 'pendingReconciles'>,
this: Pick<KnowledgeIndexingHost, 'buildsStopped' | 'cancelPendingReconcile' | 'enablementWaiters' | 'pendingReconciles'>,
): 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);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'];
Expand Down Expand Up @@ -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<KnowledgeRecordSyncHost, 'buildsStopped' | 'enablementPending' | 'enablementWaiters'>,
): Promise<boolean> | undefined {
if (!host.enablementPending) return undefined;
if (host.buildsStopped) return Promise.resolve(false);
return new Promise<boolean>((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<KnowledgeRecordSyncHost, 'adapterFor' | 'recordSyncTails' | 'resolveRecordSync' | 'syncRow'>,
this: Pick<
KnowledgeRecordSyncHost,
'adapterFor' | 'buildsStopped' | 'enablementPending' | 'enablementWaiters' | 'recordSyncTails' |
'resolveRecordSync' | 'syncRow'
>,
data: unknown,
publishedAt?: number,
): Promise<KnowledgeRecordSyncOutcome> {
// [#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;
Expand Down Expand Up @@ -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<KnowledgeRecordSyncHost, 'considerBacklogReconcile' | 'resolveRecordSync' | 'syncRecordGroup'>,
this: Pick<
KnowledgeRecordSyncHost,
'buildsStopped' | 'considerBacklogReconcile' | 'enablementPending' | 'enablementWaiters' | 'resolveRecordSync' |
'syncRecordGroup'
>,
batch: readonly KnowledgeRecordSyncBatchItem[],
): Promise<KnowledgeRecordSyncBatchResult[]> {
// [#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<string, RecordSyncGroup>();
batch.forEach((item, index) => {
Expand Down Expand Up @@ -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<KnowledgeRecordSyncHost, 'held' | 'serializeRecordSync' | 'sourcesForObject' | 'syncRecord'>,
this: Pick<
KnowledgeRecordSyncHost,
'buildsStopped' | 'enablementPending' | 'enablementWaiters' | 'held' | 'options' | 'serializeRecordSync' |
'sourcesForObject' | 'syncRecord'
>,
object: string,
record: Record<string, unknown>,
): Promise<void> {
// [#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)) {
Expand Down Expand Up @@ -1008,15 +1058,30 @@ export function schemaFor(this: Pick<KnowledgeRecordSyncHost, 'options'>, object
}
}

/** A record sync deferred past the boot's reading that failed where nothing awaits it: one `warn` line. */
function deferredSyncFailed(host: Pick<KnowledgeRecordSyncHost, 'options'>, 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<void> {
// [#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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'];
Expand All @@ -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<KnowledgeSourcesHost, 'cancelPendingReconcile' | 'enablementPending' | 'held' | 'pendingReconciles'>,
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);
}
Expand Down
Loading
Loading