Skip to content

Commit b4a5b82

Browse files
committed
fix(service-knowledge): a record write before the boot reads a runtime-composed knowledge service calls no store
A runtime-composed knowledge service is read as enabled or held once, at kernel:bootstrapped. A record write before that reading (a seed, a package's sample data) was synced at once, so a deployment with no embedder called the store and logged a failed-batch warning. Record syncs that arrive while the reading is pending now wait for it: the queue worker paths await it, and the inline paths are deferred past it without holding the write up. Held, each completes with no store call; enabled, each runs as before. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Utp6CYvu4t9zSjsTHiUubP
1 parent 301a378 commit b4a5b82

5 files changed

Lines changed: 276 additions & 5 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/service-knowledge': patch
3+
---
4+
5+
fix(service-knowledge): a record write before the boot reads a runtime-composed knowledge service calls no store
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.
11+
12+
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.
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#38479, ADR-0161 K8, the dated note on item 12] A service the runtime
5+
* composed is read as enabled or held once, at `kernel:bootstrapped`. A record
6+
* write can land before that reading: a seed, or a package's sample data, on
7+
* a new project's first boot. Its sync — inline, on the queue's per-message
8+
* path or on its batch path — calls no store until the reading:
9+
*
10+
* - held (no embedder, or the deployment's store not mounted): each completes
11+
* without a sync, and no store is ever called for it;
12+
* - enabled: each runs once the reading is taken, as it would have before.
13+
*
14+
* The inline sync never holds the write up: a write the boot itself awaits
15+
* would otherwise wait for a reading that comes after it. A service a host
16+
* mounts itself has no such window and syncs at once, as it always did.
17+
*
18+
* The second half pins the reap guard on an enabled runtime-composed service:
19+
* it is registered at the reading, before the earliest sweep a host can run
20+
* at `kernel:bootstrapped`, so that sweep de-indexes before it deletes.
21+
*/
22+
23+
import { describe, it, expect, vi } from 'vitest';
24+
import { LiteKernel } from '@objectstack/core';
25+
import type { Plugin, PluginContext } from '@objectstack/core';
26+
import type { KnowledgeSource } from '@objectstack/spec/ai';
27+
import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts';
28+
import { KnowledgeService } from '../knowledge-service.js';
29+
import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js';
30+
31+
/** The lifecycle service's guard shape, as `knowledge-reap-guard.ts` builds it. */
32+
type ReapGuard = (object: string, rows: Array<Record<string, unknown>>) => Promise<Array<string | number>>;
33+
34+
const SOURCE: KnowledgeSource = {
35+
name: 'kb',
36+
label: 'KB',
37+
adapter: 'vec',
38+
source: { kind: 'object', object: 'kb_article', content: ['body'] },
39+
};
40+
41+
function setup(opts: { runtimeComposed: boolean }) {
42+
const calls: string[] = [];
43+
const adapter: IKnowledgeAdapter = {
44+
id: 'vec',
45+
upsert: vi.fn(async () => { calls.push('upsert'); }),
46+
delete: vi.fn(async () => { calls.push('delete'); }),
47+
search: vi.fn(async () => { calls.push('search'); return []; }),
48+
};
49+
const rows: Record<string, unknown>[] = [{ id: 'r1', body: 'Seeded article' }];
50+
const engine = {
51+
find: vi.fn(async (_object: string, q: { where?: Record<string, unknown> } = {}) => {
52+
const ids = (q.where as { id?: { $in?: unknown[] } } | undefined)?.id?.$in;
53+
const wanted = (q.where as { id?: unknown } | undefined)?.id;
54+
return rows.filter((r) => (ids ? ids.includes(r.id) : typeof wanted === 'string' ? r.id === wanted : true));
55+
}),
56+
findOne: vi.fn(async () => rows[0]),
57+
} as unknown as IDataEngine;
58+
const warn = vi.fn();
59+
const service = new KnowledgeService({
60+
dataEngine: engine,
61+
logger: { warn, debug: () => undefined, info: () => undefined },
62+
...(opts.runtimeComposed ? { enabledByConfiguration: true } : {}),
63+
});
64+
service.registerAdapter('vec', adapter);
65+
service.registerSource(SOURCE);
66+
return { service, adapter, calls, warn };
67+
}
68+
69+
const MESSAGE = { source: 'kb', object: 'kb_article', recordId: 'r1', reason: 'event' };
70+
71+
/** Let every queued promise settle. */
72+
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
73+
74+
describe('[#38479] a record write before the boot reads a runtime-composed service calls no store', () => {
75+
it('held: the inline sync, a queued message and a queued batch wait, then complete without a sync; no store is called', async () => {
76+
const { service, calls, warn } = setup({ runtimeComposed: true });
77+
78+
// Inline: the write is not held up.
79+
await expect(service.handleRecordUpsert('kb_article', { id: 'r1', body: 'Seeded article' })).resolves.toBeUndefined();
80+
await expect(service.handleRecordDelete('kb_article', 'r0')).resolves.toBeUndefined();
81+
// The queue's worker took the messages before the reading.
82+
const one = service.processRecordSync(MESSAGE);
83+
const batch = service.processRecordSyncBatch([{ data: MESSAGE }]);
84+
await settle();
85+
expect(calls).toEqual([]);
86+
87+
service.settleEnablement({ embedder: 'no embedder provider is saved' });
88+
89+
await expect(one).resolves.toBe('not-synced');
90+
await expect(batch).resolves.toEqual([{ ok: true, outcome: 'not-synced' }]);
91+
await settle();
92+
expect(calls).toEqual([]);
93+
expect(warn).not.toHaveBeenCalled();
94+
});
95+
96+
it('enabled: the same syncs wait for the reading, then run as ever', async () => {
97+
const { service, adapter, calls } = setup({ runtimeComposed: true });
98+
99+
await service.handleRecordUpsert('kb_article', { id: 'r1', body: 'Seeded article' });
100+
await service.handleRecordDelete('kb_article', 'r0');
101+
const one = service.processRecordSync(MESSAGE);
102+
await settle();
103+
expect(calls).toEqual([]);
104+
105+
service.settleEnablement(undefined);
106+
107+
await expect(one).resolves.toBe('synced');
108+
await vi.waitFor(() => expect(vi.mocked(adapter.delete)).toHaveBeenCalledWith(['kb:r0'], expect.anything()));
109+
const upserted = vi.mocked(adapter.upsert).mock.calls.flatMap(([docs]) => docs.map((d) => d.id));
110+
expect(upserted).toEqual(['kb:r1', 'kb:r1']);
111+
});
112+
113+
it('control: a service a host mounts itself syncs at once, as it always did', async () => {
114+
const { service, adapter } = setup({ runtimeComposed: false });
115+
await service.handleRecordUpsert('kb_article', { id: 'r1', body: 'Seeded article' });
116+
expect(adapter.upsert).toHaveBeenCalledOnce();
117+
await expect(service.processRecordSync(MESSAGE)).resolves.toBe('synced');
118+
});
119+
});
120+
121+
/** The earliest sweep a host can run: in its own `kernel:bootstrapped` handler, registered after the knowledge plugin's. */
122+
class BootSweepPlugin implements Plugin {
123+
name = 'test.boot-sweep';
124+
version = '1.0.0';
125+
type = 'standard' as const;
126+
dependencies = ['com.objectstack.service.knowledge'];
127+
constructor(private readonly order: string[], private readonly guards: Array<ReapGuard>) {}
128+
async init(): Promise<void> {}
129+
async start(ctx: PluginContext): Promise<void> {
130+
ctx.hook('kernel:bootstrapped', async () => {
131+
this.order.push(`sweep (guards: ${this.guards.length})`);
132+
for (const guard of this.guards) await guard('kb_article', [{ id: 'k1' }]);
133+
});
134+
}
135+
}
136+
137+
describe('[#38479] the reap guard of an enabled runtime-composed service is registered before the first sweep', () => {
138+
it('registered at the reading, so a sweep at kernel:bootstrapped de-indexes before it deletes', async () => {
139+
const order: string[] = [];
140+
const guards: Array<ReapGuard> = [];
141+
const deletedDocs: string[] = [];
142+
const lifecycle = {
143+
registerReapGuard: vi.fn((object: string, guard: ReapGuard) => {
144+
order.push(`guard ${object}`);
145+
guards.push(guard);
146+
}),
147+
};
148+
const adapter: IKnowledgeAdapter = {
149+
id: 'vec',
150+
upsert: async () => undefined,
151+
delete: async (ids: string[]) => { deletedDocs.push(...ids); },
152+
search: async () => [],
153+
};
154+
const kernel = new LiteKernel();
155+
kernel.use({
156+
name: 'test.lifecycle-and-embedder',
157+
version: '1.0.0',
158+
async init(ctx: PluginContext) {
159+
ctx.registerService('lifecycle', lifecycle);
160+
ctx.registerService('embedder', { id: 'own', dimensions: 2, embed: async (t: string[]) => t.map(() => [1, 0]) });
161+
},
162+
} as Plugin);
163+
kernel.use(new KnowledgeServicePlugin({
164+
sources: [{ ...SOURCE, adapter: undefined }],
165+
deploymentAdapter: 'vec',
166+
runtimeComposed: { declared: false },
167+
buildAtBoot: false,
168+
reconcile: false,
169+
}));
170+
kernel.use({
171+
name: 'test.deployment-store',
172+
version: '1.0.0',
173+
dependencies: ['com.objectstack.service.knowledge'],
174+
async init() {},
175+
async start(ctx: PluginContext) {
176+
ctx.getService<KnowledgeService>('knowledge').registerAdapter('vec', adapter);
177+
},
178+
} satisfies Plugin);
179+
kernel.use(new BootSweepPlugin(order, guards));
180+
await kernel.bootstrap();
181+
182+
expect(kernel.getService<KnowledgeService>('knowledge').heldReading()).toBeUndefined();
183+
expect(order).toEqual(['guard kb_article', 'sweep (guards: 1)']);
184+
expect(deletedDocs).toEqual(['kb:k1']);
185+
await kernel.shutdown();
186+
});
187+
});

‎packages/services/service-knowledge/src/knowledge-service-record-sync.ts‎

Lines changed: 62 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,8 @@ export interface KnowledgeRecordSyncHost {
9393
readonly considerBacklogReconcile: KnowledgeService['considerBacklogReconcile'];
9494
readonly coveredByBuild: KnowledgeService['coveredByBuild'];
9595
readonly deadLettersOf: KnowledgeService['deadLettersOf'];
96+
readonly enablementPending: KnowledgeService['enablementPending'];
97+
readonly enablementWaiters: KnowledgeService['enablementWaiters'];
9698
readonly enqueueReconcile: KnowledgeService['enqueueReconcile'];
9799
readonly handed: KnowledgeService['handed'];
98100
readonly held: KnowledgeService['held'];
@@ -386,12 +388,35 @@ export function publishRecordSyncs(
386388
else send();
387389
}
388390

391+
/**
392+
* [#38479, ADR-0161 K8] A service the runtime composed is neither held nor
393+
* enabled until the boot reads it at `kernel:bootstrapped`
394+
* (`KnowledgeService.settleEnablement`), and a record write can land before
395+
* that: a seed, or a package's sample data. A record sync that arrives in that
396+
* window waits for the reading and calls no store meanwhile; once it is read,
397+
* held completes the sync without one and enabled runs it as ever. The answer
398+
* is `undefined` when there is nothing to wait for: a service a host mounts
399+
* itself, and one whose reading is settled.
400+
*/
401+
function enablementSettled(
402+
host: Pick<KnowledgeRecordSyncHost, 'enablementPending' | 'enablementWaiters'>,
403+
): Promise<void> | undefined {
404+
if (!host.enablementPending) return undefined;
405+
return new Promise<void>((wake) => host.enablementWaiters.push(wake));
406+
}
407+
389408
/** The body of {@link KnowledgeService.processRecordSync}; the member's docblock there is its contract. */
390409
export async function processRecordSync(
391-
this: Pick<KnowledgeRecordSyncHost, 'adapterFor' | 'recordSyncTails' | 'resolveRecordSync' | 'syncRow'>,
410+
this: Pick<
411+
KnowledgeRecordSyncHost,
412+
'adapterFor' | 'enablementPending' | 'enablementWaiters' | 'recordSyncTails' | 'resolveRecordSync' | 'syncRow'
413+
>,
392414
data: unknown,
393415
publishedAt?: number,
394416
): Promise<KnowledgeRecordSyncOutcome> {
417+
// [#38479] The worker may take a message before the boot's reading: it
418+
// waits for it, so a held deployment calls no store for it.
419+
await enablementSettled(this);
395420
const resolved = this.resolveRecordSync(data, publishedAt);
396421
if ('outcome' in resolved) return resolved.outcome;
397422
const { source, message, engine } = resolved;
@@ -493,9 +518,15 @@ export function coveredByBuild(
493518

494519
/** The body of {@link KnowledgeService.processRecordSyncBatch}; the member's docblock there is its contract. */
495520
export async function processRecordSyncBatch(
496-
this: Pick<KnowledgeRecordSyncHost, 'considerBacklogReconcile' | 'resolveRecordSync' | 'syncRecordGroup'>,
521+
this: Pick<
522+
KnowledgeRecordSyncHost,
523+
'considerBacklogReconcile' | 'enablementPending' | 'enablementWaiters' | 'resolveRecordSync' | 'syncRecordGroup'
524+
>,
497525
batch: readonly KnowledgeRecordSyncBatchItem[],
498526
): Promise<KnowledgeRecordSyncBatchResult[]> {
527+
// [#38479] As on the per-message path: a batch taken before the boot's
528+
// reading waits for it.
529+
await enablementSettled(this);
499530
const results: KnowledgeRecordSyncBatchResult[] = new Array(batch.length);
500531
const groups = new Map<string, RecordSyncGroup>();
501532
batch.forEach((item, index) => {
@@ -837,10 +868,22 @@ export async function syncRows(
837868

838869
/** The body of {@link KnowledgeService.handleRecordUpsert}; the member's docblock there is its contract. */
839870
export async function handleRecordUpsert(
840-
this: Pick<KnowledgeRecordSyncHost, 'held' | 'serializeRecordSync' | 'sourcesForObject' | 'syncRecord'>,
871+
this: Pick<
872+
KnowledgeRecordSyncHost,
873+
'enablementPending' | 'enablementWaiters' | 'held' | 'options' | 'serializeRecordSync' | 'sourcesForObject' |
874+
'syncRecord'
875+
>,
841876
object: string,
842877
record: Record<string, unknown>,
843878
): Promise<void> {
879+
// [#38479] Before the boot's reading the sync is deferred past it and the
880+
// write is not held up: a write the boot itself awaits (a seed) would
881+
// otherwise wait for a reading that comes after it.
882+
const settled = enablementSettled(this);
883+
if (settled) {
884+
void settled.then(() => handleRecordUpsert.call(this, object, record)).catch((err: unknown) => deferredSyncFailed(this, object, err));
885+
return;
886+
}
844887
if (this.held) return;
845888
const recordId = record.id;
846889
for (const source of this.sourcesForObject(object)) {
@@ -1008,15 +1051,30 @@ export function schemaFor(this: Pick<KnowledgeRecordSyncHost, 'options'>, object
10081051
}
10091052
}
10101053

1054+
/** A record sync deferred past the boot's reading that failed where nothing awaits it: one `warn` line. */
1055+
function deferredSyncFailed(host: Pick<KnowledgeRecordSyncHost, 'options'>, object: string, err: unknown): void {
1056+
host.options.logger?.warn?.(
1057+
`[knowledge] a record sync of object '${object}' deferred past the boot's enablement reading failed: ` +
1058+
`${err instanceof Error ? err.message : String(err)}`,
1059+
);
1060+
}
1061+
10111062
/** The body of {@link KnowledgeService.handleRecordDelete}; the member's docblock there is its contract. */
10121063
export async function handleRecordDelete(
10131064
this: Pick<
10141065
KnowledgeRecordSyncHost,
1015-
'adapterFor' | 'held' | 'label' | 'options' | 'planIndex' | 'serializeRecordSync' | 'sourcesForObject'
1066+
'adapterFor' | 'enablementPending' | 'enablementWaiters' | 'held' | 'label' | 'options' | 'planIndex' |
1067+
'serializeRecordSync' | 'sourcesForObject'
10161068
>,
10171069
object: string,
10181070
recordId: string,
10191071
): Promise<void> {
1072+
// [#38479] Deferred past the boot's reading, as {@link handleRecordUpsert}.
1073+
const settled = enablementSettled(this);
1074+
if (settled) {
1075+
void settled.then(() => handleRecordDelete.call(this, object, recordId)).catch((err: unknown) => deferredSyncFailed(this, object, err));
1076+
return;
1077+
}
10201078
if (this.held) return;
10211079
const targets = this.sourcesForObject(object);
10221080
for (const source of targets) {

‎packages/services/service-knowledge/src/knowledge-service-sources.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ export interface KnowledgeSourcesHost {
7979
readonly cancelPendingReconcile: KnowledgeService['cancelPendingReconcile'];
8080
readonly describeSources: KnowledgeService['describeSources'];
8181
enablementPending: KnowledgeService['enablementPending'];
82+
readonly enablementWaiters: KnowledgeService['enablementWaiters'];
8283
readonly forget: KnowledgeService['forget'];
8384
held: KnowledgeService['held'];
8485
readonly label: KnowledgeService['label'];
@@ -97,11 +98,17 @@ export interface KnowledgeSourcesHost {
9798

9899
/** The body of {@link KnowledgeService.settleEnablement}; the member's docblock there is its contract. */
99100
export function settleEnablement(
100-
this: Pick<KnowledgeSourcesHost, 'cancelPendingReconcile' | 'enablementPending' | 'held' | 'pendingReconciles'>,
101+
this: Pick<
102+
KnowledgeSourcesHost,
103+
'cancelPendingReconcile' | 'enablementPending' | 'enablementWaiters' | 'held' | 'pendingReconciles'
104+
>,
101105
held: KnowledgeHeldReading | undefined,
102106
): void {
103107
this.enablementPending = false;
104108
this.held = held;
109+
// [#38479] The record syncs that waited for this reading go on now: held,
110+
// each completes without a sync; enabled, each runs.
111+
for (const wake of this.enablementWaiters.splice(0)) wake();
105112
if (!held) return;
106113
for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key);
107114
}

‎packages/services/service-knowledge/src/knowledge-service.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,12 @@ export class KnowledgeService implements IKnowledgeService {
197197
* always `false` on a service a host mounted itself.
198198
*/
199199
private enablementPending: boolean;
200+
/**
201+
* [#38479] The record syncs that arrived while {@link enablementPending}:
202+
* each waits here, calling no store, until {@link settleEnablement} reads
203+
* the boot. Held ⇒ each then completes without a sync; enabled ⇒ each runs.
204+
*/
205+
private readonly enablementWaiters: Array<() => void> = [];
200206

201207
constructor(private readonly options: KnowledgeServiceOptions = {}) {
202208
this.defaultTopK = options.defaultTopK ?? 10;
@@ -1600,6 +1606,7 @@ export class KnowledgeService implements IKnowledgeService {
16001606
dropUnverifiedHits: (...a) => service.dropUnverifiedHits(...a),
16011607
get enablementPending() { return service.enablementPending; },
16021608
set enablementPending(v) { service.enablementPending = v; },
1609+
get enablementWaiters() { return service.enablementWaiters; },
16031610
enqueueReconcile: (...a) => service.enqueueReconcile(...a),
16041611
faceOfKey: (...a) => service.faceOfKey(...a),
16051612
facedRefusals: (...a) => service.facedRefusals(...a),

0 commit comments

Comments
 (0)