Skip to content

Commit b172943

Browse files
committed
fix(service-knowledge): release record syncs waiting for the enablement reading when the service stops
A boot that fails before the reading left the record-sync worker waiting, so destroy() hung on the queue unsubscribe. stopBuilds() now completes every waiting sync without one, and a sync that arrives after the stop does not wait. The contract docblocks now say syncs wait for the reading. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Utp6CYvu4t9zSjsTHiUubP
1 parent b4a5b82 commit b172943

7 files changed

Lines changed: 65 additions & 20 deletions

File tree

‎.changeset/38479-knowledge-boot-window.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,4 @@ Metadata-protocol: none
99

1010
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.
1111

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.
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. 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.

‎packages/services/service-knowledge/src/__tests__/boot-window-38479.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,24 @@ describe('[#38479] a record write before the boot reads a runtime-composed servi
110110
expect(upserted).toEqual(['kb:r1', 'kb:r1']);
111111
});
112112

113+
it('stopped before the reading (a boot that failed first): every waiting sync completes without one, and none waits after', async () => {
114+
const { service, calls } = setup({ runtimeComposed: true });
115+
116+
await service.handleRecordUpsert('kb_article', { id: 'r1', body: 'Seeded article' });
117+
const one = service.processRecordSync(MESSAGE);
118+
const batch = service.processRecordSyncBatch([{ data: MESSAGE }]);
119+
await settle();
120+
121+
service.stopBuilds();
122+
123+
await expect(one).resolves.toBe('not-synced');
124+
await expect(batch).resolves.toEqual([{ ok: true, outcome: 'not-synced' }]);
125+
// A message taken after the stop does not wait either.
126+
await expect(service.processRecordSync(MESSAGE)).resolves.toBe('not-synced');
127+
await settle();
128+
expect(calls).toEqual([]);
129+
});
130+
113131
it('control: a service a host mounts itself syncs at once, as it always did', async () => {
114132
const { service, adapter } = setup({ runtimeComposed: false });
115133
await service.handleRecordUpsert('kb_article', { id: 'r1', body: 'Seeded article' });

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ export interface KnowledgeIndexingHost {
109109
readonly buildUnderLease: KnowledgeService['buildUnderLease'];
110110
readonly builds: KnowledgeService['builds'];
111111
buildsStopped: KnowledgeService['buildsStopped'];
112+
readonly enablementWaiters: KnowledgeService['enablementWaiters'];
112113
readonly cancelPendingReconcile: KnowledgeService['cancelPendingReconcile'];
113114
readonly clearRepairedFailures: KnowledgeService['clearRepairedFailures'];
114115
readonly closeStaleBuild: KnowledgeService['closeStaleBuild'];
@@ -1277,9 +1278,13 @@ export async function buildIfDue(
12771278

12781279
/** The body of {@link KnowledgeService.stopBuilds}; the member's docblock there is its contract. */
12791280
export function stopBuilds(
1280-
this: Pick<KnowledgeIndexingHost, 'buildsStopped' | 'cancelPendingReconcile' | 'pendingReconciles'>,
1281+
this: Pick<KnowledgeIndexingHost, 'buildsStopped' | 'cancelPendingReconcile' | 'enablementWaiters' | 'pendingReconciles'>,
12811282
): void {
12821283
this.buildsStopped = true;
1284+
// [#38479] A record sync still waiting for the boot's enablement reading
1285+
// (a boot that failed before it) completes without a sync, so the queue's
1286+
// worker is not left waiting while it is unsubscribed.
1287+
for (const wake of this.enablementWaiters.splice(0)) wake(false);
12831288
for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key);
12841289
}
12851290

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

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -396,27 +396,33 @@ export function publishRecordSyncs(
396396
* window waits for the reading and calls no store meanwhile; once it is read,
397397
* held completes the sync without one and enabled runs it as ever. The answer
398398
* is `undefined` when there is nothing to wait for: a service a host mounts
399-
* itself, and one whose reading is settled.
399+
* itself, and one whose reading is settled. Otherwise it resolves `true` once
400+
* the reading is taken, or `false` when the service stops first
401+
* (`KnowledgeService.stopBuilds`, a boot that failed before the reading):
402+
* the sync then completes without one, so a stopping worker never waits on a
403+
* reading that will not come.
400404
*/
401405
function enablementSettled(
402-
host: Pick<KnowledgeRecordSyncHost, 'enablementPending' | 'enablementWaiters'>,
403-
): Promise<void> | undefined {
406+
host: Pick<KnowledgeRecordSyncHost, 'buildsStopped' | 'enablementPending' | 'enablementWaiters'>,
407+
): Promise<boolean> | undefined {
404408
if (!host.enablementPending) return undefined;
405-
return new Promise<void>((wake) => host.enablementWaiters.push(wake));
409+
if (host.buildsStopped) return Promise.resolve(false);
410+
return new Promise<boolean>((wake) => host.enablementWaiters.push(wake));
406411
}
407412

408413
/** The body of {@link KnowledgeService.processRecordSync}; the member's docblock there is its contract. */
409414
export async function processRecordSync(
410415
this: Pick<
411416
KnowledgeRecordSyncHost,
412-
'adapterFor' | 'enablementPending' | 'enablementWaiters' | 'recordSyncTails' | 'resolveRecordSync' | 'syncRow'
417+
'adapterFor' | 'buildsStopped' | 'enablementPending' | 'enablementWaiters' | 'recordSyncTails' |
418+
'resolveRecordSync' | 'syncRow'
413419
>,
414420
data: unknown,
415421
publishedAt?: number,
416422
): Promise<KnowledgeRecordSyncOutcome> {
417423
// [#38479] The worker may take a message before the boot's reading: it
418424
// waits for it, so a held deployment calls no store for it.
419-
await enablementSettled(this);
425+
if ((await enablementSettled(this)) === false) return 'not-synced';
420426
const resolved = this.resolveRecordSync(data, publishedAt);
421427
if ('outcome' in resolved) return resolved.outcome;
422428
const { source, message, engine } = resolved;
@@ -520,13 +526,14 @@ export function coveredByBuild(
520526
export async function processRecordSyncBatch(
521527
this: Pick<
522528
KnowledgeRecordSyncHost,
523-
'considerBacklogReconcile' | 'enablementPending' | 'enablementWaiters' | 'resolveRecordSync' | 'syncRecordGroup'
529+
'buildsStopped' | 'considerBacklogReconcile' | 'enablementPending' | 'enablementWaiters' | 'resolveRecordSync' |
530+
'syncRecordGroup'
524531
>,
525532
batch: readonly KnowledgeRecordSyncBatchItem[],
526533
): Promise<KnowledgeRecordSyncBatchResult[]> {
527534
// [#38479] As on the per-message path: a batch taken before the boot's
528535
// reading waits for it.
529-
await enablementSettled(this);
536+
if ((await enablementSettled(this)) === false) return batch.map(() => ({ ok: true, outcome: 'not-synced' }));
530537
const results: KnowledgeRecordSyncBatchResult[] = new Array(batch.length);
531538
const groups = new Map<string, RecordSyncGroup>();
532539
batch.forEach((item, index) => {
@@ -870,8 +877,8 @@ export async function syncRows(
870877
export async function handleRecordUpsert(
871878
this: Pick<
872879
KnowledgeRecordSyncHost,
873-
'enablementPending' | 'enablementWaiters' | 'held' | 'options' | 'serializeRecordSync' | 'sourcesForObject' |
874-
'syncRecord'
880+
'buildsStopped' | 'enablementPending' | 'enablementWaiters' | 'held' | 'options' | 'serializeRecordSync' |
881+
'sourcesForObject' | 'syncRecord'
875882
>,
876883
object: string,
877884
record: Record<string, unknown>,
@@ -881,7 +888,7 @@ export async function handleRecordUpsert(
881888
// otherwise wait for a reading that comes after it.
882889
const settled = enablementSettled(this);
883890
if (settled) {
884-
void settled.then(() => handleRecordUpsert.call(this, object, record)).catch((err: unknown) => deferredSyncFailed(this, object, err));
891+
void settled.then((go) => (go ? handleRecordUpsert.call(this, object, record) : undefined)).catch((err: unknown) => deferredSyncFailed(this, object, err));
885892
return;
886893
}
887894
if (this.held) return;
@@ -1063,7 +1070,7 @@ function deferredSyncFailed(host: Pick<KnowledgeRecordSyncHost, 'options'>, obje
10631070
export async function handleRecordDelete(
10641071
this: Pick<
10651072
KnowledgeRecordSyncHost,
1066-
'adapterFor' | 'enablementPending' | 'enablementWaiters' | 'held' | 'label' | 'options' | 'planIndex' |
1073+
'adapterFor' | 'buildsStopped' | 'enablementPending' | 'enablementWaiters' | 'held' | 'label' | 'options' | 'planIndex' |
10671074
'serializeRecordSync' | 'sourcesForObject'
10681075
>,
10691076
object: string,
@@ -1072,7 +1079,7 @@ export async function handleRecordDelete(
10721079
// [#38479] Deferred past the boot's reading, as {@link handleRecordUpsert}.
10731080
const settled = enablementSettled(this);
10741081
if (settled) {
1075-
void settled.then(() => handleRecordDelete.call(this, object, recordId)).catch((err: unknown) => deferredSyncFailed(this, object, err));
1082+
void settled.then((go) => (go ? handleRecordDelete.call(this, object, recordId) : undefined)).catch((err: unknown) => deferredSyncFailed(this, object, err));
10761083
return;
10771084
}
10781085
if (this.held) return;

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ export function settleEnablement(
108108
this.held = held;
109109
// [#38479] The record syncs that waited for this reading go on now: held,
110110
// each completes without a sync; enabled, each runs.
111-
for (const wake of this.enablementWaiters.splice(0)) wake();
111+
for (const wake of this.enablementWaiters.splice(0)) wake(true);
112112
if (!held) return;
113113
for (const key of [...this.pendingReconciles.keys()]) this.cancelPendingReconcile(key);
114114
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,8 +107,8 @@ export interface KnowledgeServiceOptions {
107107
* [ADR-0161 K8, the dated note on item 12] The runtime composed this
108108
* service, so it is enabled by configuration: until the boot's reading
109109
* settles it ({@link KnowledgeService.settleEnablement}), the service hands
110-
* out no tool definition, and once settled it either serves or holds its
111-
* sources. `KnowledgeServicePlugin` sets it from its `runtimeComposed`
110+
* out no tool definition and a record sync waits for the reading, calling
111+
* no store, and once settled it either serves or holds its sources. `KnowledgeServicePlugin` sets it from its `runtimeComposed`
112112
* option. Omitted (a host that mounts the service itself), the service
113113
* serves from the start, as it always has.
114114
*/

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

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -201,8 +201,10 @@ export class KnowledgeService implements IKnowledgeService {
201201
* [#38479] The record syncs that arrived while {@link enablementPending}:
202202
* each waits here, calling no store, until {@link settleEnablement} reads
203203
* the boot. Held ⇒ each then completes without a sync; enabled ⇒ each runs.
204+
* Woken `true` by the reading, `false` by {@link stopBuilds} (the service
205+
* stopped first): then each completes without a sync.
204206
*/
205-
private readonly enablementWaiters: Array<() => void> = [];
207+
private readonly enablementWaiters: Array<(proceed: boolean) => void> = [];
206208

207209
constructor(private readonly options: KnowledgeServiceOptions = {}) {
208210
this.defaultTopK = options.defaultTopK ?? 10;
@@ -228,6 +230,12 @@ export class KnowledgeService implements IKnowledgeService {
228230
* The state is the whole service's, whichever store a source names (the
229231
* note's point 2). Called once, by `KnowledgeServicePlugin`; a later boot
230232
* reads the state again.
233+
*
234+
* [#38479] Until this reading, a record sync calls no store: one that
235+
* arrives first (a seed, a package's sample data) waits for it, and then
236+
* completes without a sync when held, or runs when enabled. The queue's
237+
* worker awaits the reading; an inline sync is deferred past it, so the
238+
* write is not held up.
231239
*/
232240
settleEnablement(held: KnowledgeHeldReading | undefined): void {
233241
return KnowledgeSourcesFacet.settleEnablement.call(knowledgeServiceHost.of(this), held);
@@ -821,7 +829,9 @@ export class KnowledgeService implements IKnowledgeService {
821829
/**
822830
* Stop the boot pass and the reconcile from starting another build, and
823831
* drop every reconcile a predicate write asked for that has not started. A
824-
* build already walking runs to its end.
832+
* build already walking runs to its end. A record sync still waiting for the
833+
* boot's enablement reading ({@link settleEnablement}) completes without a
834+
* sync.
825835
*/
826836
stopBuilds(): void {
827837
return KnowledgeIndexingFacet.stopBuilds.call(knowledgeServiceHost.of(this));
@@ -1369,6 +1379,11 @@ export class KnowledgeService implements IKnowledgeService {
13691379
* last one leaves the index agreeing with the database. Inline, the chain
13701380
* is awaited, so a write's sync can wait behind an earlier in-flight sync
13711381
* of the same document; the index still ends consistent.
1382+
*
1383+
* [#38479] On a service the runtime composed, a call made before the boot's
1384+
* enablement reading ({@link settleEnablement}) returns at once: the sync
1385+
* is deferred past the reading, then skipped when held or run when enabled.
1386+
* The same holds for {@link handleRecordDelete}.
13721387
*/
13731388
handleRecordUpsert(object: string, record: Record<string, unknown>): Promise<void> {
13741389
return KnowledgeRecordSyncFacet.handleRecordUpsert.call(knowledgeServiceHost.of(this), object, record);

0 commit comments

Comments
 (0)