|
| 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('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 | + |
| 131 | + it('control: a service a host mounts itself syncs at once, as it always did', async () => { |
| 132 | + const { service, adapter } = setup({ runtimeComposed: false }); |
| 133 | + await service.handleRecordUpsert('kb_article', { id: 'r1', body: 'Seeded article' }); |
| 134 | + expect(adapter.upsert).toHaveBeenCalledOnce(); |
| 135 | + await expect(service.processRecordSync(MESSAGE)).resolves.toBe('synced'); |
| 136 | + }); |
| 137 | +}); |
| 138 | + |
| 139 | +/** The earliest sweep a host can run: in its own `kernel:bootstrapped` handler, registered after the knowledge plugin's. */ |
| 140 | +class BootSweepPlugin implements Plugin { |
| 141 | + name = 'test.boot-sweep'; |
| 142 | + version = '1.0.0'; |
| 143 | + type = 'standard' as const; |
| 144 | + dependencies = ['com.objectstack.service.knowledge']; |
| 145 | + constructor(private readonly order: string[], private readonly guards: Array<ReapGuard>) {} |
| 146 | + async init(): Promise<void> {} |
| 147 | + async start(ctx: PluginContext): Promise<void> { |
| 148 | + ctx.hook('kernel:bootstrapped', async () => { |
| 149 | + this.order.push(`sweep (guards: ${this.guards.length})`); |
| 150 | + for (const guard of this.guards) await guard('kb_article', [{ id: 'k1' }]); |
| 151 | + }); |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +describe('[#38479] the reap guard of an enabled runtime-composed service is registered before the first sweep', () => { |
| 156 | + it('registered at the reading, so a sweep at kernel:bootstrapped de-indexes before it deletes', async () => { |
| 157 | + const order: string[] = []; |
| 158 | + const guards: Array<ReapGuard> = []; |
| 159 | + const deletedDocs: string[] = []; |
| 160 | + const lifecycle = { |
| 161 | + registerReapGuard: vi.fn((object: string, guard: ReapGuard) => { |
| 162 | + order.push(`guard ${object}`); |
| 163 | + guards.push(guard); |
| 164 | + }), |
| 165 | + }; |
| 166 | + const adapter: IKnowledgeAdapter = { |
| 167 | + id: 'vec', |
| 168 | + upsert: async () => undefined, |
| 169 | + delete: async (ids: string[]) => { deletedDocs.push(...ids); }, |
| 170 | + search: async () => [], |
| 171 | + }; |
| 172 | + const kernel = new LiteKernel(); |
| 173 | + kernel.use({ |
| 174 | + name: 'test.lifecycle-and-embedder', |
| 175 | + version: '1.0.0', |
| 176 | + async init(ctx: PluginContext) { |
| 177 | + ctx.registerService('lifecycle', lifecycle); |
| 178 | + ctx.registerService('embedder', { id: 'own', dimensions: 2, embed: async (t: string[]) => t.map(() => [1, 0]) }); |
| 179 | + }, |
| 180 | + } as Plugin); |
| 181 | + kernel.use(new KnowledgeServicePlugin({ |
| 182 | + sources: [{ ...SOURCE, adapter: undefined }], |
| 183 | + deploymentAdapter: 'vec', |
| 184 | + runtimeComposed: { declared: false }, |
| 185 | + buildAtBoot: false, |
| 186 | + reconcile: false, |
| 187 | + })); |
| 188 | + kernel.use({ |
| 189 | + name: 'test.deployment-store', |
| 190 | + version: '1.0.0', |
| 191 | + dependencies: ['com.objectstack.service.knowledge'], |
| 192 | + async init() {}, |
| 193 | + async start(ctx: PluginContext) { |
| 194 | + ctx.getService<KnowledgeService>('knowledge').registerAdapter('vec', adapter); |
| 195 | + }, |
| 196 | + } satisfies Plugin); |
| 197 | + kernel.use(new BootSweepPlugin(order, guards)); |
| 198 | + await kernel.bootstrap(); |
| 199 | + |
| 200 | + expect(kernel.getService<KnowledgeService>('knowledge').heldReading()).toBeUndefined(); |
| 201 | + expect(order).toEqual(['guard kb_article', 'sweep (guards: 1)']); |
| 202 | + expect(deletedDocs).toEqual(['kb:k1']); |
| 203 | + await kernel.shutdown(); |
| 204 | + }); |
| 205 | +}); |
0 commit comments