diff --git a/.changeset/37735-knowledge-record-sync-queue.md b/.changeset/37735-knowledge-record-sync-queue.md new file mode 100644 index 00000000000..ab775ad448a --- /dev/null +++ b/.changeset/37735-knowledge-record-sync-queue.md @@ -0,0 +1,20 @@ +--- +'@objectstack/service-knowledge': patch +--- + +feat(service-knowledge): record changes sync through the queue service — a save does not wait for the embedder, a failed sync is retried, a rolled-back write is never indexed + +Clause-②: yes (widening) — `KnowledgeServicePluginOptions` gains the optional `recordSyncRetry`; `KnowledgeService` gains `routeRecordSyncs`, `recordSyncQueued`, `enqueueRecordSync` and `processRecordSync`; the package exports `KNOWLEDGE_RECORD_SYNC_QUEUE`, `RECORD_SYNC_RETRY_DEFAULTS` and the `KnowledgeRecordSync*` types +Metadata-protocol: none + +A save of a record a knowledge source indexes used to sync its document inside the write: with a realtime service composed, the save waited for the re-read, the split, the embedding call and the store write, all before the write's unit of work committed. A failed sync was one `warn` line and was never retried, and a write that then rolled back could leave a document built from a row that never committed, or delete the document of a row that still matched. + +Where the kernel composes a durable `queue` service (the platform's `QueueServicePlugin` over a data engine, which the standard runtime mounts on every preset but `minimal`) and a data engine is bound, the sync now runs through the `knowledge-record-sync` queue: + +- **A save publishes and returns.** Either trigger — the realtime subscription, or the after-write hooks on a kernel without one — publishes one message per source that indexes the object on record change: the source's index key, the object, the record id and the reason (`event`, or `freshness` for the repair a search starts). Never a field value. The save does not wait for the embedder. +- **After the commit, and never for a rollback.** The message is published through the engine's `runAfterOpenUnitsCommit`, once the write's own unit or a caller's `engine.transaction()` commits, and not at all when it rolls back. So nothing is processed before the write commits, and after a rollback the index equals the committed database. +- **Retried, then a dead letter.** The worker re-reads the row and writes or removes its document; a failure is thrown to the queue, which runs it up to eight times, 5 s doubling to a 2 min cap between attempts (`recordSyncRetry` changes it). Then the message is a dead letter `listFailed` lists, naming the source and the record, logged once at `error`; the reconcile repairs it. A source no longer registered, or no longer indexing the object on record change, completes its message with no write and no retry; a source whose adapter is not mounted is retried like a failure. +- **One queue row per source per save**, no idempotency key: a keyed message would suppress a save made while the record's sync runs, and every later save for a day after one completed. +- **The freshness repair** a search starts is a `freshness` message too, so it survives a restart and is retried. + +With only the kernel's in-memory fallback queue, a queue with no dead-letter surface (`listFailed`), or no data engine, the sync runs inline as before, and the boot says so once at `warn`. A host that mounts the service by hand adds `new QueueServicePlugin()` from `@objectstack/service-queue` to get the queued sync. `enableEventSync: false` and `refresh.onRecordChange: false` publish nothing. Nothing to migrate. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 79205a676c9..36ba579e3f9 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -218,7 +218,7 @@ The answer never says how many hits the permission re-check or the scope removed ## What you get for free - **Permission-aware retrieval.** Every hit with a `sourceRecordId` is re-checked against the caller's `ExecutionContext` via `IDataEngine` — the same RLS that gates plain ObjectQL queries. A salesperson asking "find proposals about ACME" only sees the proposals they could already read directly. Before a source is searched, the caller's field-level read rules and the object's API exposure are asked too: a source serving a field the caller may not query is not searched for them (see [the protocol's source admission](/docs/protocol/knowledge#source-admission-exposure-and-field-level-rules)). File / HTTP hits pass through (ACL is the adapter's problem). -- **Inline event sync.** When records on indexed objects change, the kernel's `IRealtimeService` events drive `KnowledgeService.handleRecordUpsert/Delete` automatically. No cron, no queue (yet — Phase 2). +- **Record sync through the queue.** When a record of an indexed object is saved, restored or deleted, the save publishes one message per source to the `knowledge-record-sync` queue, once its unit of work commits and never for a write that rolls back; a worker re-reads the row and writes or removes its document. The message holds the source, the object, the record id and the reason, never a field value. The save does not wait for the embedder; a failed sync is retried (eight attempts over about six and a half minutes, `recordSyncRetry`) and then kept as a dead letter (`listFailed`) that the daily reconcile repairs; messages survive a restart. Without a durable queue (only the kernel's in-memory fallback) the sync runs inline, as before, and the boot says so once at `warn`: compose `QueueServicePlugin` over the ObjectQL engine. Details in [the protocol's sync model](/docs/protocol/knowledge#through-the-queue). - **Adapter swap, zero caller changes.** Move from `memory` to `pgvector` or `turso`, or to a custom adapter, without touching your `search` calls, the `search_knowledge` tool, or any agent prompt. ## Configuring the embedder from Settings diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index a4b04b385e7..c64b917916a 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -333,8 +333,9 @@ system-context read per source of only the records about to be answered `where` since it was indexed, or whose document hash computed now differs from the hit's `docHash`, is not answered, and the next record moves up (at most three rounds; a hit still unchecked after them is not answered). Its -document is repaired in the background, through the event sync's path, once -until its hash matches again — except in a source with +document is repaired in the background — a record-sync message with reason +`freshness` [through the queue](#through-the-queue), or the inline sync +without one — once until its hash matches again — except in a source with `refresh.onRecordChange: false`, whose index an external indexer owns: the service writes nothing there, and the hit is only not answered. A hit whose adapter stores no hash is checked for membership only. Record granularity @@ -971,21 +972,88 @@ when the source has no `where`). builds the document from the event's `after`, and a source with `where` is not synced, which the service logs once per source as a warning. -A delete removes the document named by the event's required `recordId`. Syncs -of one document run one after another in the process, so two events for the -same row cannot interleave: each re-reads after the previous one finished, and -the last leaves the index agreeing with the database. Because the sync is -inline, a write's sync can wait behind an earlier in-flight sync of the same -document (on a single-connection pool, up to the pool's acquire timeout); the -index still ends consistent. - -**When the sync runs.** The engine publishes `data.record.created` and -`data.record.updated` from inside the write, after its `after*` hooks — before -any unit of work around the write commits (the write's own unit, opened when a -metadata hook can abort it, or a caller's `engine.transaction(…)`). The -in-process realtime service awaits each subscriber, so the re-read runs inside -the same open transaction and sees the row the write just made. If that unit -then rolls back, the index is wrong in one of two ways: +A delete removes the row's document: through the queue, by the same re-read +(no row comes back); inline, by the event's required `recordId`. Syncs of one +document run one after another in the process, so two syncs of the same row +cannot interleave: each re-reads after the previous one finished, and the last +leaves the index agreeing with the database. + +### Through the queue + +Where the kernel composes a durable `queue` service — the platform's +`QueueServicePlugin` over a data engine, whose database adapter keeps messages +in `sys_job_queue` — and a data engine is bound, the sync runs through that +queue (ADR-0161 K1). The standard runtime mounts `queue` on every preset but `minimal`. + +- **A save publishes; it does not sync.** For each source that indexes the + written object on record change, either trigger (the realtime subscription, + or the after-write hooks [below](#without-a-realtime-service-the-after-write-hooks)) + publishes one message to the `knowledge-record-sync` queue: the source's + index key, the object, the record id, and why (`event`, or `freshness` for + the repair a search starts). Never a field value: `sys_job_queue` is an + object an administrator can list, and a record body there would be a copy of + the row outside its permissions. The save does not wait for the re-read, the + split, the embedding call or the store write. +- **After the commit, and never for a rollback.** The message is published + through the engine's `runAfterOpenUnitsCommit`: once the unit of work open + at the write commits (the write's own unit, or a caller's + `engine.transaction(…)`), and not at all when it rolls back. So nothing is + processed before the write commits, and a write that rolls back leaves the + index as it was. With no unit open the message is published at once. A + publish that fails is logged at `error`; the document is stale until the + record's next save, a search that finds it stale, or the reconcile. +- **The worker** subscribes in `kernel:ready`, resolves the source by its + index key when it processes the message, and re-reads the row as above: a + row comes back → its document is written; none → its document is deleted. +- **Retries.** A failure a retry can change — the re-read, the split, the + embedding call, the store write — is thrown to the queue, which retries it + with backoff: eight attempts, 5 s doubling to a 2 min cap, so a provider + outage of six and a half minutes is ridden out (the plugin's + `recordSyncRetry` option). Then the message is a dead letter the queue lists + (`listFailed`), naming the source and the record in its metadata, and the + plugin says so once at `error`. The [reconcile](#reconcile-keeping-the-index-correct) + repairs what a dead letter names. +- **Not retried**, because a retry cannot change them, and completed with no + write: a source no longer registered, or no longer indexing the object on + record change. A `whole` document over the embedder's budget is removed from + the index and reported at `error`, as on every path. A source whose adapter + is not mounted is retried like a failure, so a store that registers late is + met by a later attempt, and one that never does leaves a dead letter. +- **A burst of saves.** Every save publishes its own message — one queue row + per source per save; completed rows are kept for `sys_job_queue`'s declared + retention (7 days). No message is keyed by its document: the queue + suppresses a keyed publish while a message with the key is pending **or + running**, and for a day after it completed, so a save made while a sync of + the record runs would be lost, and a completed sync would block the record's + later saves. Each message re-reads the row as it is when it is processed, so + the last one leaves the last committed version. +- **A delete** leaves the index when its message is processed. Until then a + member's search (each hit re-read as the member) and a `granularity: + 'record'` search (each hit checked against its record) do not answer it: the + record no longer exists. A system-identity search at chunk granularity + re-reads nothing, so it can answer the deleted record's chunks until the + message is processed. +- **A restart** loses nothing published: messages wait in `sys_job_queue` and + are processed after it. + +### Without a durable queue + +With only the kernel's built-in fallback queue (synchronous, in-process, no +durability, no retry; it labels itself `degraded`), a queue with no dead-letter +surface (`listFailed` — the in-memory `MemoryQueueAdapter` has none), or no data +engine bound, the sync runs inline and the plugin says so once at boot, at `warn`. A +host that mounts the service by hand adds `QueueServicePlugin` over the +ObjectQL engine to get the queued sync. + +**When the inline sync runs.** On the realtime trigger the engine publishes +`data.record.created` and `data.record.updated` from inside the write, after +its `after*` hooks — before any unit of work around the write commits (the +write's own unit, opened when a metadata hook can abort it, or a caller's +`engine.transaction(…)`). The in-process realtime service awaits each +subscriber, so the save waits for the embedder, the re-read runs inside the +same open transaction and sees the row the write just made, and a failed sync +is logged and not retried. If that unit then rolls back, the index is wrong in +one of two ways: - **The uncommitted row matched** — the document stays built from a row that never committed. @@ -995,17 +1063,14 @@ then rolls back, the index is wrong in one of two ways: The row's next event or a `reindexSource` repairs a row that still exists. A document built from an **insert** that rolled back has no row left to repair it from; it stays until a complete reindex purges it (below) — at the latest, the -next [reconcile](#reconcile-keeping-the-index-correct). +next [reconcile](#reconcile-keeping-the-index-correct). Inline, a write's sync +can also wait behind an earlier in-flight sync of the same document (on a +single-connection pool, up to the pool's acquire timeout); the index still ends +consistent. `data.record.restored` is published after the restore's own unit has committed. -- **MVP (Phase 1):** synchronous, inline with the originating mutation. - Fast for low-volume dev / demo. Indexing failures are logged but do - not block the originating write. -- **Phase 2:** async via `service-queue` for batching, retries, and - back-pressure. - **A predicate write leaves the index stale until its reconcile.** A `multi: true` update/delete reaches `updateMany` / `deleteMany`, which report @@ -1029,10 +1094,12 @@ A kernel that composes no `realtime` service publishes no `data.record.*` event (the ObjectQL plugin bridges that same service to the engine). There, `KnowledgeServicePlugin` registers the data engine's `afterInsert`, `afterUpdate` and `afterDelete` hooks on every object a source with -`refresh.onRecordChange` not `false` indexes, and each hook calls the same -`handleRecordUpsert` / `handleRecordDelete` the subscription calls — the -re-read under `where`, the field rules and the per-document ordering above all -apply. The plugin takes exactly one of the two triggers, chosen at +`refresh.onRecordChange` not `false` indexes, and each hook does what the +subscription does: [through the queue](#through-the-queue) it publishes the +record's message on the same commit, and without one it calls the same +`handleRecordUpsert` / `handleRecordDelete` — the re-read under `where`, the +field rules and the per-document ordering above all apply. The points below +describe that inline sync. The plugin takes exactly one of the two triggers, chosen at `kernel:ready`, so a write is never synced twice. A source registered or loaded later for a new object gets its hooks when it arrives. @@ -1058,8 +1125,9 @@ later for a new object gets its hooks when it arrives. D2), so on such a kernel a restored row is not re-indexed by itself; a `reindexSource` brings it back. -The sync is in-process: a sync that has not finished when the process stops is -lost, and the next `reindexSource` repairs it. +The inline sync is in-process: a sync that has not finished when the process +stops is lost, and the next reconcile or `reindexSource` repairs it. Through the +queue, a message survives the restart. ### Reindex: skip and purge @@ -1128,8 +1196,9 @@ de-indexed too. - **Batching** is the sweep's: 500 rows per batch, 20 batches per sweep, the backlog draining across sweeps. - **Opt-out.** `refresh.onRecordChange: false` on a source — or - `enableEventSync: false` on the plugin — turns off inline index sync in both - directions, event subscription and reap-time de-index alike. An index an + `enableEventSync: false` on the plugin — turns off the record sync in both + directions, the record-change sync (queued or inline: nothing is published, + nothing subscribed) and reap-time de-index alike. An index an external indexer owns is never a reason to hold up another package's retention. @@ -1207,9 +1276,8 @@ followed (§4.1, §4.2) are the adapters to run in production. | `knowledge-memory` | ✅ | In-process; deterministic fake embedder | | `knowledge-ragflow` | retired | Shipped in Phase 1; its requests did not match the RAGFlow HTTP API, and the package was removed. Use `knowledge-pgvector`, `knowledge-turso` or an adapter of your own | | `search_knowledge` AI tool | ✅ | Threads `ToolExecutionContext` | -| Event-driven sync | ✅ (sync) | MVP synchronous; queue in Phase 2 | +| Event-driven sync | ✅ | Through the queue service when one is durable (retries, dead letters); inline otherwise | | Console source-management UI | ⏳ Phase 2 | | -| Async indexer (queue) | ⏳ Phase 2 | | | Audit + metrics | ⏳ Phase 2 | | | `knowledge-llamaindex` | ⏳ Phase 2 | | | `knowledge-dify` | ⏳ Phase 3 / community | | diff --git a/packages/services/service-knowledge/README.md b/packages/services/service-knowledge/README.md index f8cb5921697..db6cb316c4f 100644 --- a/packages/services/service-knowledge/README.md +++ b/packages/services/service-knowledge/README.md @@ -19,6 +19,24 @@ matches `where`, and embeds nothing that did not change. `new KnowledgeServicePlugin({ reconcile: { cron, timezone } })` moves the daily run and `reconcile: false` turns it off. +A record change reaches the index through the queue service. The save +publishes one message per source to the `knowledge-record-sync` queue (the +source, the object, the record id — never a field value) once its unit of work +commits, and nothing for a write that rolls back; a worker re-reads the row and +writes or removes its document. The save does not wait for the embedder. A +failed sync is retried (`recordSyncRetry`, eight attempts over about six and a +half minutes by default), then kept as a dead letter (`listFailed`) that the +reconcile repairs. This needs a durable `queue` service — the platform's +`QueueServicePlugin` over the ObjectQL engine, which the standard runtime mounts +on every preset but `minimal`; with only the kernel's in-memory fallback the sync runs inline, as the +boot says once at `warn`. A host that mounts the service by hand adds: + +```ts +import { QueueServicePlugin } from '@objectstack/service-queue'; + +kernel.use(new QueueServicePlugin()); +``` + ```ts import { KnowledgeServicePlugin } from '@objectstack/service-knowledge'; import { KnowledgeMemoryPlugin } from '@objectstack/knowledge-memory'; diff --git a/packages/services/service-knowledge/package.json b/packages/services/service-knowledge/package.json index 569300c3eee..0c1e6664949 100644 --- a/packages/services/service-knowledge/package.json +++ b/packages/services/service-knowledge/package.json @@ -38,8 +38,10 @@ "@objectstack/spec": "workspace:*" }, "devDependencies": { + "@objectstack/driver-sql": "workspace:*", "@objectstack/objectql": "workspace:*", "@objectstack/platform-objects": "workspace:*", + "@objectstack/service-queue": "workspace:*", "@types/node": "^26.6.5", "tsx": "^4.23.15", "typescript": "^6.0.3", diff --git a/packages/services/service-knowledge/src/__tests__/record-sync-queue.test.ts b/packages/services/service-knowledge/src/__tests__/record-sync-queue.test.ts new file mode 100644 index 00000000000..dca115a50e1 --- /dev/null +++ b/packages/services/service-knowledge/src/__tests__/record-sync-queue.test.ts @@ -0,0 +1,607 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The record sync through the queue service (ADR-0161 K1), on a REAL kernel: + * `ObjectQLPlugin` over a real SQL driver (`SqlDriver`, better-sqlite3 on a + * file), the platform's `QueueServicePlugin` (its database adapter over + * `sys_job_queue`) and `KnowledgeServicePlugin` — each trigger, the realtime + * subscription and the after-write hooks, driven by real writes. + * + * What is pinned: + * + * - a save publishes a message and returns; it does not wait for the embedder, + * and the document appears once the embedder answers, with no further event; + * - a message carries identifiers only (the stored queue row is read); + * - a failed sync is retried, and once its attempts are spent the message is a + * dead letter the queue lists, naming the source and the record; + * - nothing is published before the write's unit of work commits — the write's + * own unit and a caller's `transaction()` — and nothing for a write that + * rolls back: after the rollback the index equals the committed database; + * - two saves of one record leave the last committed version; a save after a + * completed sync is synced (no completed message suppresses it); one save + * costs one queue row per source; + * - a delete leaves the index once processed, and no search answers the + * record in between; + * - messages published before a restart are processed after it; + * - a source unregistered before its message is processed: completed, no + * write, no retry; + * - the freshness repair publishes a `freshness` message; + * - with only the kernel's fallback queue: one boot line at `warn`, and the + * sync runs inline as before; + * - `enableEventSync: false` and `refresh.onRecordChange: false` publish + * nothing. + */ + +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import type { Plugin, PluginContext } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { QueueServicePlugin, type DbQueueAdapter } from '@objectstack/service-queue'; +import type { + IKnowledgeAdapter, + IRealtimeService, + RealtimeEventHandler, + RealtimeEventPayload, +} from '@objectstack/spec/contracts'; +import type { KnowledgeDocument, KnowledgeHit, KnowledgeSource } from '@objectstack/spec/ai'; +import { KnowledgeServicePlugin, type KnowledgeServicePluginOptions } from '../knowledge-service-plugin.js'; +import type { KnowledgeService } from '../knowledge-service.js'; +import { KNOWLEDGE_RECORD_SYNC_QUEUE } from '../knowledge-record-sync-queue.js'; + +type Row = Record; + +const SYSTEM = { isSystem: true, positions: [], permissions: [], systemPermissions: [] } as never; +const SEARCH = { executionContext: { positions: [], permissions: [], systemPermissions: [], isSystem: true } }; +/** A signed-in member: every hit is re-read as them before it is answered. */ +const MEMBER = { + executionContext: { userId: 'u_member', tenantId: 'org_default', positions: [], permissions: [], systemPermissions: [] }, +}; +/** The system identity under record granularity: every hit is checked against its record as it reads now. */ +const SYSTEM_BY_RECORD = { ...SEARCH, granularity: 'record' as const }; + +/** A short retry budget, so a test sees a retry and a dead letter in milliseconds. */ +const FAST_RETRY = { maxAttempts: 3, backoffMs: 20, maxBackoffMs: 40 }; + +const KB_ARTICLE = { + name: 'kb_article', + label: 'KB article', + fields: { + title: { name: 'title', type: 'text', label: 'Title' }, + body: { name: 'body', type: 'textarea', label: 'Body' }, + status: { name: 'status', type: 'text', label: 'Status' }, + }, +}; + +function source(overrides: Partial = {}): KnowledgeSource { + return { + name: 'kb', + label: 'kb', + adapter: 'memory', + source: { kind: 'object', object: 'kb_article', content: ['title', 'body'], where: { status: 'published' } }, + ...overrides, + } as KnowledgeSource; +} + +/** + * An adapter that keeps documents by id and answers a search by substring. Its + * embedding step can be held (`hold()` → release) or made to fail the next + * `failures` calls (`failNext(n)`), or every call (`failNext(Infinity)`). + */ +function makeAdapter() { + const docs = new Map(); + let gate: Promise | undefined; + let failures = 0; + const embedCalls: string[] = []; + const adapter: IKnowledgeAdapter = { + id: 'memory', + upsert: vi.fn(async (batch: KnowledgeDocument[]) => { + embedCalls.push(...batch.map((doc) => doc.content)); + if (gate) await gate; + if (failures > 0) { + failures--; + throw new Error('the embedding provider answered 503'); + } + for (const doc of batch) docs.set(doc.id, doc); + }), + delete: vi.fn(async (ids: string[]) => { + for (const id of ids) docs.delete(id); + }), + search: vi.fn(async (query: string): Promise => + [...docs.values()] + .filter((doc) => doc.content.includes(query)) + .map((doc) => ({ + chunkId: doc.id, + documentId: doc.id, + sourceId: doc.sourceId, + sourceRecordId: doc.sourceRecordId, + score: 1, + snippet: doc.content, + ...(doc.docHash !== undefined ? { docHash: doc.docHash } : {}), + }))), + }; + return { + adapter, + docs, + embedCalls, + hold(): () => void { + let release!: () => void; + gate = new Promise((resolve) => { release = resolve; }); + return () => { gate = undefined; release(); }; + }, + failNext(n: number): void { failures = n; }, + }; +} + +/** A `realtime` service that awaits each subscriber in turn, as the in-memory adapter does. */ +function makeRealtime() { + const handlers = new Map(); + let n = 0; + const service = { + async publish(event: RealtimeEventPayload) { + for (const handler of handlers.values()) await handler(event); + }, + async subscribe(_channel: string, handler: RealtimeEventHandler) { + const id = `sub-${++n}`; + handlers.set(id, handler); + return id; + }, + async unsubscribe(id: string) { + handlers.delete(id); + }, + }; + return service as unknown as IRealtimeService & typeof service; +} + +/** + * Registers the SQL driver, the test object and, when asked, a realtime + * service, in init(); the knowledge adapter in start(), as a store plugin does. + */ +function hostPlugin( + file: string, + realtime: IRealtimeService | undefined, + adapter: IKnowledgeAdapter, + others: Record = {}, +): Plugin { + return { + name: 'test.knowledge-queue-host', + version: '1.0.0', + type: 'standard', + dependencies: ['com.objectstack.engine.objectql'], + async init(ctx: PluginContext) { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: file }, useNullAsDefault: true }); + await driver.connect(); + ctx.registerService('driver.default', driver); + ctx.getService('objectql').registry.registerObject(KB_ARTICLE as never, 'test.knowledge-queue-host'); + if (realtime) ctx.registerService('realtime', realtime); + }, + async start(ctx: PluginContext) { + const service = ctx.getService('knowledge'); + service.registerAdapter('memory', adapter); + for (const [id, other] of Object.entries(others)) service.registerAdapter(id, other); + }, + } as unknown as Plugin; +} + +/** + * A `single` install's Default Organization, as a real boot seeds it: a system + * write of a fresh object derives it (ADR-0131 D9), and the NOT NULL tenant + * column requires one. Seeded through the driver, so no write under test sees it. + */ +async function installDefaultOrganization(ql: ObjectQL): Promise { + if (!ql.getSchema('sys_organization')) { + ql.registry.registerObject( + { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: { type: 'text', label: 'Name' } } } as never, + 'test.knowledge-queue-host', + ); + } + await ql.syncSchemas(); + const driver = ql.getDriverForObject('sys_organization') as unknown as { + create(o: string, d: Row): Promise; + findOne(o: string, q: unknown): Promise; + }; + if (await driver.findOne('sys_organization', { where: { id: 'org_default' } })) return; + await driver.create('sys_organization', { id: 'org_default', name: 'Default' }); +} + +const kernels: ObjectKernel[] = []; +let dir: string | undefined; + +afterEach(async () => { + for (const k of kernels.splice(0)) { + try { await k.shutdown(); } catch { /* noop */ } + } + if (dir) { rmSync(dir, { recursive: true, force: true }); dir = undefined; } +}); + +function freshFile(): string { + dir = mkdtempSync(join(tmpdir(), 'os-knowledge-queue-')); + return join(dir, 'data.db'); +} + +interface BootOptions { + file?: string; + realtime?: boolean; + queue?: boolean; + knowledge?: KnowledgeServicePluginOptions; + /** Further stores, registered beside `memory`. */ + adapters?: Record; +} + +async function boot(opts: BootOptions = {}) { + const file = opts.file ?? freshFile(); + const realtime = opts.realtime ? makeRealtime() : undefined; + const memory = makeAdapter(); + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), child() { return logger; } }; + const kernel = new ObjectKernel({ logger: { level: 'fatal' }, gracefulShutdown: false } as never); + kernels.push(kernel); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(hostPlugin(file, realtime, memory.adapter, opts.adapters)); + if (opts.queue !== false) { + await kernel.use(new QueueServicePlugin({ adapter: 'db', db: { pollIntervalMs: 10, maxIdleIntervalMs: 20 } })); + } + const knowledge = new KnowledgeServicePlugin({ + sources: [source()], + buildAtBoot: false, + reconcile: false, + recordSyncRetry: FAST_RETRY, + ...opts.knowledge, + }); + // The plugin's own log lines, captured: the kernel's logger is silenced. + const plugin = knowledge as unknown as { init(ctx: PluginContext): Promise; start(ctx: PluginContext): Promise }; + const init = plugin.init.bind(knowledge); + const start = plugin.start.bind(knowledge); + const withLogger = (ctx: PluginContext): PluginContext => + new Proxy(ctx, { get: (target, key) => (key === 'logger' ? logger : Reflect.get(target, key)) }); + plugin.init = (ctx) => init(withLogger(ctx)); + plugin.start = (ctx) => start(withLogger(ctx)); + await kernel.use(knowledge); + await kernel.bootstrap(); + + const ql = kernel.getService('objectql'); + await installDefaultOrganization(ql); + const service = kernel.getService('knowledge'); + const queue = kernel.getService('queue'); + + /** The stored rows of the record-sync queue. */ + const queueRows = async (): Promise => + (await ql.find('sys_job_queue', { where: { queue: KNOWLEDGE_RECORD_SYNC_QUEUE }, context: SYSTEM } as never)) as Row[]; + /** + * Resolves once the record-sync queue holds at least `rows` messages (a + * message is published after its write commits, so a beat after the write + * resolves) and every one is completed or a dead letter. + */ + const drained = async (rows = 1): Promise => { + await vi.waitFor(async () => { + const stored = await queueRows(); + if (stored.length < rows) throw new Error(`${stored.length} of ${rows} record-sync message(s) published`); + const open = stored.filter((r) => r.status === 'pending' || r.status === 'running'); + if (open.length > 0) throw new Error(`${open.length} record-sync message(s) still open`); + }, { timeout: 5000, interval: 10 }); + }; + const found = async (text: string, opts: Parameters[1] = SEARCH): Promise => + (await service.search(text, opts as never)).map((hit) => String(hit.sourceRecordId)); + const insert = (data: Row): Promise => ql.insert('kb_article', data, { context: SYSTEM } as never) as Promise; + const update = (id: unknown, data: Row): Promise => + ql.update('kb_article', data, { where: { id }, context: SYSTEM } as never); + const remove = (id: unknown): Promise => ql.delete('kb_article', { where: { id }, context: SYSTEM } as never); + + return { kernel, ql, service, queue, realtime, logger, knowledge, ...memory, queueRows, drained, found, insert, update, remove }; +} + +const TRIGGERS = [ + ['the realtime subscription', true], + ['the after-write hooks', false], +] as const; + +describe.each(TRIGGERS)('record sync through the queue — %s', (_label, realtime) => { + it('a save returns while the embedder does not answer; the document appears once it does, with no further event', async () => { + const t = await boot({ realtime }); + expect(t.logger.info.mock.calls.map((c) => String(c[0])).some((l) => l.includes(`through queue '${KNOWLEDGE_RECORD_SYNC_QUEUE}'`))).toBe(true); + const release = t.hold(); + const row = await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + // The save resolved; the worker is held inside the embedding call. + await vi.waitFor(() => expect(t.embedCalls).toHaveLength(1), { timeout: 3000, interval: 10 }); + expect(t.docs.size).toBe(0); + release(); + await t.drained(); + expect(await t.found('paid leave')).toEqual([String(row.id)]); + }); + + it('a message carries identifiers only: the stored queue row holds no field value', async () => { + const t = await boot({ realtime }); + const row = await t.insert({ title: 'Salary bands', body: 'Band four starts at ninety thousand', status: 'published' }); + await t.drained(); + const rows = await t.queueRows(); + expect(rows).toHaveLength(1); + const stored = rows[0]!; + expect(JSON.parse(String(stored.payload_json))).toEqual({ + source: 'kb', + object: 'kb_article', + recordId: String(row.id), + reason: 'event', + }); + const text = JSON.stringify(stored); + expect(text).not.toContain('Salary bands'); + expect(text).not.toContain('ninety thousand'); + expect(text).not.toContain('published'); + expect(stored.idempotency_key ?? null).toBeNull(); + }); + + it('a sync that fails is retried, and indexed by the retry', async () => { + const t = await boot({ realtime }); + t.failNext(2); + const row = await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + await t.drained(); + expect(await t.found('paid leave')).toEqual([String(row.id)]); + const [stored] = await t.queueRows(); + expect(stored!.status).toBe('completed'); + expect(Number(stored!.attempts)).toBe(3); + }); + + it('a sync that keeps failing is a dead letter naming its source and record; the save never failed', async () => { + const t = await boot({ realtime }); + t.failNext(Infinity); + const row = await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + expect(row.id).toBeDefined(); + await t.drained(); + const failed = await t.queue.listFailed(KNOWLEDGE_RECORD_SYNC_QUEUE); + expect(failed).toHaveLength(1); + expect(failed[0]!.attempts).toBe(FAST_RETRY.maxAttempts); + expect(failed[0]!.metadata).toMatchObject({ source: 'kb', object: 'kb_article', recordId: String(row.id) }); + expect(JSON.stringify(failed[0])).not.toContain('paid leave'); + const errors = t.logger.error.mock.calls.map((c) => String(c[0])); + expect(errors.filter((l) => l.includes('is now a dead letter'))).toHaveLength(1); + }); + + it("nothing is published inside a caller's transaction, and the committed write is synced once it commits", async () => { + const t = await boot({ realtime }); + let insideRows = -1; + await t.ql.transaction(async () => { + await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + await new Promise((resolve) => setTimeout(resolve, 100)); + insideRows = t.embedCalls.length + t.docs.size; + }); + expect(insideRows).toBe(0); + await vi.waitFor(async () => expect(await t.queueRows()).toHaveLength(1), { timeout: 3000, interval: 10 }); + await t.drained(); + expect(await t.found('paid leave')).toHaveLength(1); + }); + + it('a rolled-back insert that matched leaves no document, and publishes nothing', async () => { + const t = await boot({ realtime }); + await expect(t.ql.transaction(async () => { + await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + throw new Error('the caller gives up'); + })).rejects.toThrow('the caller gives up'); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(await t.ql.find('kb_article', { context: SYSTEM } as never)).toEqual([]); + expect(await t.queueRows()).toEqual([]); + expect(t.docs.size).toBe(0); + expect(t.embedCalls).toEqual([]); + }); + + it('a rolled-back update that stopped matching leaves the committed row indexed', async () => { + const t = await boot({ realtime }); + const row = await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + await t.drained(); + expect(await t.found('paid leave')).toEqual([String(row.id)]); + + await expect(t.ql.transaction(async () => { + await t.update(row.id, { status: 'draft' }); + throw new Error('the caller gives up'); + })).rejects.toThrow('the caller gives up'); + await new Promise((resolve) => setTimeout(resolve, 100)); + await t.drained(); + const committed = (await t.ql.find('kb_article', { context: SYSTEM } as never)) as Row[]; + expect(committed.map((r) => r.status)).toEqual(['published']); + expect(await t.queueRows()).toHaveLength(1); + expect(await t.found('paid leave')).toEqual([String(row.id)]); + }); + + it('two saves in quick succession leave the last committed version; one save costs one queue row', async () => { + const t = await boot({ realtime }); + const row = await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + await t.update(row.id, { body: 'Thirty days of annual leave' }); + await t.update(row.id, { body: 'Forty days of sabbatical leave' }); + await t.drained(3); + expect(await t.queueRows()).toHaveLength(3); + expect(await t.found('sabbatical')).toEqual([String(row.id)]); + expect(await t.found('paid leave')).toEqual([]); + expect(await t.found('annual leave')).toEqual([]); + }); + + it('a save after a completed sync is synced: a completed message suppresses nothing', async () => { + const t = await boot({ realtime }); + const row = await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + await t.drained(); + expect((await t.queueRows()).map((r) => r.status)).toEqual(['completed']); + await t.update(row.id, { body: 'Thirty days of annual leave' }); + await t.drained(2); + expect(await t.found('annual leave')).toEqual([String(row.id)]); + expect((await t.queueRows()).map((r) => r.status)).toEqual(['completed', 'completed']); + }); + + it('a delete leaves the index once processed, and no search answers the record in between', async () => { + const t = await boot({ realtime }); + const row = await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + await t.drained(); + expect(t.docs.size).toBe(1); + expect(await t.found('paid leave', MEMBER)).toEqual([String(row.id)]); + expect(await t.found('paid leave', SYSTEM_BY_RECORD)).toEqual([String(row.id)]); + + await t.queue.stop(); + await t.remove(row.id); + // The worker is stopped: the document is still in the index, and neither + // a member's search (each hit re-read as the member) nor a record-level + // search (each hit checked against its record) answers it. + expect(t.docs.size).toBe(1); + expect(await t.found('paid leave', MEMBER)).toEqual([]); + expect(await t.found('paid leave', SYSTEM_BY_RECORD)).toEqual([]); + + t.queue.start(); + await t.drained(2); + expect(t.docs.size).toBe(0); + }); + + it("a source that names no adapter syncs through the queue to the deployment's store", async () => { + const { adapter: _named, ...unplaced } = source(); + const decoy = makeAdapter(); + const t = await boot({ + realtime, + adapters: { decoy: decoy.adapter }, + knowledge: { sources: [unplaced as KnowledgeSource], deploymentAdapter: 'memory' }, + }); + expect(t.service.recordSyncQueued).toBe(true); + const row = await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + await t.drained(); + const rows = await t.queueRows(); + expect(rows.map((r) => r.status)).toEqual(['completed']); + expect(t.docs.size).toBe(1); + expect(decoy.docs.size).toBe(0); + expect(await t.found('paid leave')).toEqual([String(row.id)]); + }); + + it('a source unregistered before its message is processed: completed, no write, no retry', async () => { + const t = await boot({ realtime }); + await t.queue.stop(); + await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + await vi.waitFor(async () => expect(await t.queueRows()).toHaveLength(1), { timeout: 3000, interval: 10 }); + t.service.unregisterSource('kb'); + t.queue.start(); + await t.drained(); + const [stored] = await t.queueRows(); + expect(stored!.status).toBe('completed'); + expect(Number(stored!.attempts)).toBe(1); + expect(t.adapter.upsert).not.toHaveBeenCalled(); + expect(t.adapter.delete).not.toHaveBeenCalled(); + }); +}); + +describe('record sync through the queue — the write, the restart and the freshness repair', () => { + it("nothing is published before the write's own unit of work commits", async () => { + const t = await boot({ realtime: true }); + // A blocking `afterInsert` metadata hook makes the write open its own unit + // (`opensAfterAbortUnit`); a second realtime subscriber holds the write + // open after the knowledge subscription has run, so the unit is open + // while the message would be published. + t.ql.registerHook('afterInsert', async () => undefined, { + object: 'kb_article', + meta: { name: 'audit_probe', events: ['afterInsert'] }, + } as never); + let release!: () => void; + const held = new Promise((resolve) => { release = resolve; }); + let reached = false; + await t.realtime!.subscribe('test.hold', async () => { + reached = true; + await held; + }); + const publish = vi.spyOn(t.queue, 'publish'); + const write = t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + try { + await vi.waitFor(() => expect(reached).toBe(true), { timeout: 3000, interval: 5 }); + await new Promise((resolve) => setTimeout(resolve, 100)); + // Read nothing from the database here: on SQLite the open unit holds + // the only connection until the write returns. + expect(publish).not.toHaveBeenCalled(); + expect(t.embedCalls).toEqual([]); + } finally { + release(); + } + await write; + await vi.waitFor(async () => expect(await t.queueRows()).toHaveLength(1), { timeout: 3000, interval: 10 }); + await t.drained(); + expect(await t.found('paid leave')).toHaveLength(1); + }); + + it("an afterInsert hook that aborts the write's own unit after the knowledge hook ran publishes nothing", async () => { + const t = await boot({ realtime: false }); + t.ql.registerHook('afterInsert', async () => { + throw new Error('the probe refuses this write'); + }, { + object: 'kb_article', + priority: 1000, + meta: { name: 'refusing_probe', events: ['afterInsert'] }, + } as never); + await expect(t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' })) + .rejects.toThrow(); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(await t.ql.find('kb_article', { context: SYSTEM } as never)).toEqual([]); + expect(await t.queueRows()).toEqual([]); + expect(t.docs.size).toBe(0); + }); + + it('messages published before a restart are processed after it', async () => { + const file = freshFile(); + const first = await boot({ file }); + await first.queue.stop(); + const row = await first.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + await vi.waitFor(async () => expect(await first.queueRows()).toHaveLength(1), { timeout: 3000, interval: 10 }); + expect(first.docs.size).toBe(0); + await first.kernel.shutdown(); + kernels.splice(kernels.indexOf(first.kernel), 1); + + const second = await boot({ file }); + await second.drained(); + expect(await second.found('paid leave')).toEqual([String(row.id)]); + }); + + it('a search that finds a document stale publishes a freshness message, and the worker repairs it', async () => { + const t = await boot({ realtime: true }); + const row = await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + await t.drained(); + // The row changes behind the engine's back: no event, no hook. + const driver = t.ql.getDriverForObject('kb_article') as unknown as { update(o: string, id: unknown, d: Row): Promise }; + await driver.update('kb_article', row.id, { body: 'Twenty days of unpaid leave' }); + expect(await t.found('paid leave', SYSTEM_BY_RECORD)).toEqual([]); + await t.drained(2); + const freshness = (await t.queueRows()).map((r) => JSON.parse(String(r.payload_json)).reason); + expect(freshness.sort()).toEqual(['event', 'freshness']); + expect(await t.found('unpaid leave')).toEqual([String(row.id)]); + }); +}); + +describe('record sync without a durable queue, and the switches', () => { + it.each(TRIGGERS)("with only the kernel's fallback queue (%s): one boot line at warn, and the sync runs inline", async (_label, realtime) => { + const t = await boot({ realtime, queue: false }); + const inline = t.logger.warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('record changes are synced inline')); + expect(inline).toHaveLength(1); + expect(t.service.recordSyncQueued).toBe(false); + const row = await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + await vi.waitFor(async () => expect(await t.found('paid leave')).toEqual([String(row.id)]), { timeout: 3000, interval: 10 }); + }); + + it.each(TRIGGERS)('enableEventSync: false publishes nothing and subscribes nothing (%s)', async (_label, realtime) => { + const t = await boot({ realtime, knowledge: { enableEventSync: false } }); + expect(t.service.recordSyncQueued).toBe(false); + await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(await t.queueRows()).toEqual([]); + expect(t.docs.size).toBe(0); + }); + + it.each(TRIGGERS)('a source with refresh.onRecordChange: false is never enqueued (%s)', async (_label, realtime) => { + const t = await boot({ + realtime, + knowledge: { sources: [source({ refresh: { onRecordChange: false } } as Partial)] }, + }); + await t.insert({ title: 'Leave policy', body: 'Twenty days of paid leave', status: 'published' }); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(await t.queueRows()).toEqual([]); + expect(t.docs.size).toBe(0); + }); + + it('destroy() leaves the queue subscription: a message published later waits for the next start', async () => { + const t = await boot({ realtime: true }); + await (t.knowledge as unknown as { destroy(): Promise }).destroy(); + const publish = await t.queue.publish(KNOWLEDGE_RECORD_SYNC_QUEUE, { source: 'kb', object: 'kb_article', recordId: 'y', reason: 'event' }); + expect(publish).toBeTruthy(); + await new Promise((resolve) => setTimeout(resolve, 100)); + const stored = (await t.queueRows()).find((r) => JSON.parse(String(r.payload_json)).recordId === 'y'); + expect(stored?.status).toBe('pending'); + }); +}); diff --git a/packages/services/service-knowledge/src/index.ts b/packages/services/service-knowledge/src/index.ts index 02dd36e73b6..d0ed0d83500 100644 --- a/packages/services/service-knowledge/src/index.ts +++ b/packages/services/service-knowledge/src/index.ts @@ -76,3 +76,10 @@ export type { KnowledgeSettingsContribution, KnowledgeSettingsContributionOptions, } from './knowledge-settings-contribution.js'; +export { KNOWLEDGE_RECORD_SYNC_QUEUE, RECORD_SYNC_RETRY_DEFAULTS } from './knowledge-record-sync-queue.js'; +export type { + KnowledgeRecordSyncMessage, + KnowledgeRecordSyncOutcome, + KnowledgeRecordSyncReason, + KnowledgeRecordSyncRetry, +} from './knowledge-record-sync-queue.js'; diff --git a/packages/services/service-knowledge/src/knowledge-record-hooks.ts b/packages/services/service-knowledge/src/knowledge-record-hooks.ts index cc4d66b45a2..c33b774dbe6 100644 --- a/packages/services/service-knowledge/src/knowledge-record-hooks.ts +++ b/packages/services/service-knowledge/src/knowledge-record-hooks.ts @@ -40,7 +40,10 @@ export function recordHookEngineOf(engine: unknown): KnowledgeRecordHookEngine | } /** The slice of `KnowledgeService` the record sync drives. */ -type RecordSyncService = Pick; +type RecordSyncService = Pick< + KnowledgeService, + 'indexedSources' | 'handleRecordUpsert' | 'handleRecordDelete' | 'recordSyncQueued' | 'enqueueRecordSync' +>; /** The after-write hook context fields the sync reads (`HookContext`, single-record shape). */ interface AfterWriteContext { @@ -93,6 +96,11 @@ function rowOf(value: unknown): Record | undefined { * never when it rolls back, so a rolled-back write leaves the index as it * was. With no unit open the sync starts at once, outside every unit. * + * Where record syncs run through the queue (`KnowledgeService.routeRecordSyncs`) + * the hook asks for the sync instead (`KnowledgeService.enqueueRecordSync`), + * which publishes the message on the same commit, and never on a rollback; + * the worker then syncs, retrying a failure. + * * ## The objects follow the sources * * Registered for every object a record-change source indexes now, and for @@ -160,12 +168,17 @@ export class KnowledgeRecordHooks { if (event === 'afterDelete') { const id = idOf(context?.input?.id) ?? idOf(rowOf(context?.previous)?.id); if (id === undefined) return; - this.deferRecordSync(() => this.service.handleRecordDelete(object, id)); + if (this.service.recordSyncQueued) this.service.enqueueRecordSync(object, id); + else this.deferRecordSync(() => this.service.handleRecordDelete(object, id)); return; } const result = rowOf(context?.result); const id = idOf(context?.input?.id) ?? idOf(result?.id); if (id === undefined) return; + if (this.service.recordSyncQueued) { + this.service.enqueueRecordSync(object, id); + return; + } // A copy, taken now: the engine strips the row it hands the caller after // this hook. The service re-reads the row by its id under the source's // `where` anyway; the copy is what a source with no engine would index. @@ -174,11 +187,9 @@ export class KnowledgeRecordHooks { } /** - * The one seam the hook path's sync leaves through: start `run` once the - * unit of work open at the write commits, never when it rolls back, and - * never on the write's response path. A queue that takes the sync work - * over replaces this body and nothing else — the hooks hand it the same - * `handleRecordUpsert` / `handleRecordDelete` call. + * The inline sync's seam: start `run` once the unit of work open at the + * write commits, never when it rolls back, and never on the write's + * response path. */ private deferRecordSync(run: () => Promise): void { const start = (): void => { diff --git a/packages/services/service-knowledge/src/knowledge-record-sync-queue.ts b/packages/services/service-knowledge/src/knowledge-record-sync-queue.ts new file mode 100644 index 00000000000..509c844fa54 --- /dev/null +++ b/packages/services/service-knowledge/src/knowledge-record-sync-queue.ts @@ -0,0 +1,142 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { IQueueService, QueuePublishOptions } from '@objectstack/spec/contracts'; + +/** + * The queue the record sync runs through (ADR-0161 K1): the save of an + * indexed record publishes one message here per source over its object, and + * the plugin's worker, subscribed in `kernel:ready`, syncs the document. + */ +export const KNOWLEDGE_RECORD_SYNC_QUEUE = 'knowledge-record-sync'; + +/** + * Why a record sync was asked for: a record change (`event`, from either + * trigger — the realtime subscription or the after-write hooks), or a search + * that found the record's document stale (`freshness`). + */ +export type KnowledgeRecordSyncReason = 'event' | 'freshness'; + +/** + * One record-sync message: identifiers only. ⛔ Never a field value: + * `sys_job_queue` is an object an administrator can list, and a record body + * there would be a copy of the row outside its permissions. The worker + * re-reads the row, so it needs nothing else. + */ +export interface KnowledgeRecordSyncMessage { + /** The source's index key (the registry's key, never its face). */ + source: string; + /** The object the record belongs to. */ + object: string; + /** The record's id. */ + recordId: string; + reason: KnowledgeRecordSyncReason; +} + +/** + * The retry budget of a queued record sync: a failed attempt is thrown to the + * queue, which runs it again after an exponential backoff (`backoffMs`, + * doubled each attempt, capped at `maxBackoffMs`); after `maxAttempts` the + * message is a dead letter (`IQueueService.listFailed`). + */ +export interface KnowledgeRecordSyncRetry { + maxAttempts: number; + backoffMs: number; + maxBackoffMs: number; +} + +/** + * The default budget: eight attempts, 5 s doubling to a 2 min cap. The seven + * waits between them sum to 395 s, so a provider outage of six and a half + * minutes is ridden out before a message becomes a dead letter; the reconcile + * repairs what a dead letter names. + */ +export const RECORD_SYNC_RETRY_DEFAULTS: Readonly = Object.freeze({ + maxAttempts: 8, + backoffMs: 5_000, + maxBackoffMs: 120_000, +}); + +/** `retry` with every member it leaves out taken from {@link RECORD_SYNC_RETRY_DEFAULTS}. */ +export function resolveRecordSyncRetry(retry: Partial | undefined): KnowledgeRecordSyncRetry { + const positive = (value: unknown, fallback: number): number => + typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : fallback; + return { + maxAttempts: positive(retry?.maxAttempts, RECORD_SYNC_RETRY_DEFAULTS.maxAttempts), + backoffMs: positive(retry?.backoffMs, RECORD_SYNC_RETRY_DEFAULTS.backoffMs), + maxBackoffMs: positive(retry?.maxBackoffMs, RECORD_SYNC_RETRY_DEFAULTS.maxBackoffMs), + }; +} + +/** + * The publish options of one message: the retry budget, and the source and + * record in the message metadata, so a dead letter names them. No + * `idempotencyKey`, deliberately: the database queue suppresses a publish + * while a message with the same key is `pending` or `running`, and for its + * idempotency window after it completed. Keyed by document, a save made while + * a sync of the same record runs — the sync has already read the row — would + * be lost, and a completed sync would block every later save of that record + * for the window. So every save publishes its own message, and each worker + * run re-reads the row as it is then. + */ +export function recordSyncPublishOptions( + message: KnowledgeRecordSyncMessage, + retry: KnowledgeRecordSyncRetry, +): QueuePublishOptions { + return { + maxAttempts: retry.maxAttempts, + backoff: { type: 'exponential', delayMs: retry.backoffMs, maxDelayMs: retry.maxBackoffMs }, + metadata: { source: message.source, object: message.object, recordId: message.recordId, reason: message.reason }, + }; +} + +/** `data` as a {@link KnowledgeRecordSyncMessage}, or `undefined` when it is not one. */ +export function readRecordSyncMessage(data: unknown): KnowledgeRecordSyncMessage | undefined { + if (!data || typeof data !== 'object' || Array.isArray(data)) return undefined; + const { source, object, recordId, reason } = data as Record; + const text = (value: unknown): value is string => typeof value === 'string' && value !== ''; + if (!text(source) || !text(object) || !text(recordId)) return undefined; + if (reason !== 'event' && reason !== 'freshness') return undefined; + return { source, object, recordId, reason }; +} + +/** + * The `queue` service the record sync can run through, else `undefined`: + * none registered, one that cannot publish and subscribe, the kernel's + * built-in fallback (it labels itself `degraded`: synchronous in-process + * delivery, no durability, no retry — the reading of `resolveDurableQueue` + * in `@objectstack/plugin-email`), or one with no dead-letter surface + * (`listFailed`). The last is this sync's own condition: a sync that fails + * every attempt must stay somewhere an operator can list, and an in-memory + * queue (`MemoryQueueAdapter`) retries nothing and keeps nothing, so a failed + * sync there would be lost without a line in any log. The platform's + * database queue (`DbQueueAdapter`) has one. + */ +export function resolveRecordSyncQueue(getService: (name: string) => unknown): IQueueService | undefined { + let queue: unknown; + try { + queue = getService('queue'); + } catch { + return undefined; + } + const candidate = queue as (Partial & { __serviceInfo?: { status?: unknown } }) | undefined; + if (!candidate || typeof candidate.publish !== 'function' || typeof candidate.subscribe !== 'function') return undefined; + if (candidate.__serviceInfo?.status === 'degraded') return undefined; + if (typeof candidate.listFailed !== 'function') return undefined; + return candidate as IQueueService; +} + +/** + * What one worker run of a message did. Every outcome but a throw completes + * the message: the ones below are not retried, because a retry cannot change + * them. + * + * - `synced` — the document was written from the row, or deleted because no + * row matches the source's `where` (a `whole` document over the embedder's + * budget is removed and reported at `error`, as on every path); + * - `source-gone` — no source has the message's index key any more; + * - `not-synced` — the source no longer indexes the message's object on + * record change (`refresh.onRecordChange: false`, or another object), or + * no data engine is bound to re-read the row; + * - `malformed` — the message is not a record-sync message. + */ +export type KnowledgeRecordSyncOutcome = 'synced' | 'source-gone' | 'not-synced' | 'malformed'; diff --git a/packages/services/service-knowledge/src/knowledge-service-plugin.ts b/packages/services/service-knowledge/src/knowledge-service-plugin.ts index 3abf42ad62a..328f730a9c8 100644 --- a/packages/services/service-knowledge/src/knowledge-service-plugin.ts +++ b/packages/services/service-knowledge/src/knowledge-service-plugin.ts @@ -6,8 +6,10 @@ import type { IDataEngine, IEmbedder, IJobService, + IQueueService, IRealtimeService, JobRunOutcome, + QueueMessage, } from '@objectstack/spec/contracts'; import type { KnowledgeSource } from '@objectstack/spec/ai'; import { EMBEDDER_SERVICE, KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; @@ -33,6 +35,14 @@ import { import type { KnowledgeFieldSecurity } from './knowledge-source-admission.js'; import { createKnowledgeReapGuard, guardedObjectsFor } from './knowledge-reap-guard.js'; import { KnowledgeRecordHooks, recordHookEngineOf } from './knowledge-record-hooks.js'; +import { + KNOWLEDGE_RECORD_SYNC_QUEUE, + readRecordSyncMessage, + recordSyncPublishOptions, + resolveRecordSyncQueue, + resolveRecordSyncRetry, + type KnowledgeRecordSyncRetry, +} from './knowledge-record-sync-queue.js'; import { KnowledgeSourceLoader } from './knowledge-source-loader.js'; import { KNOWLEDGE_SOURCE_TYPE } from './knowledge-source-registry.js'; import { contributeKnowledgeSettings } from './knowledge-settings-contribution.js'; @@ -342,6 +352,16 @@ export interface KnowledgeServicePluginOptions { * commits, off the write's response (`KnowledgeRecordHooks`). One of the * two, never both: each write is synced once. * + * Where the kernel composes a durable `queue` service (the platform's + * `QueueServicePlugin` over a data engine) and a data engine is bound, the + * sync runs through that queue (`KNOWLEDGE_RECORD_SYNC_QUEUE`): either + * trigger publishes one message per source — identifiers only — once the + * write's unit of work commits, and nothing for a write that rolls back; the + * save does not wait for the embedder, and a failed sync is retried + * ({@link recordSyncRetry}) and then kept as a dead letter the reconcile + * repairs. Without a durable queue the sync runs inline, as the boot says + * once at `warn`. + * * A created, updated or restored row is re-read against each source's * `where` (with a data engine bound): a matching row is indexed from the * re-read row, and a row that does not match has its document removed — @@ -356,6 +376,16 @@ export interface KnowledgeServicePluginOptions { * @default true */ enableEventSync?: boolean; + /** + * The retry budget of a queued record sync ({@link enableEventSync}): a + * failed attempt is retried after `backoffMs`, doubled each attempt up to + * `maxBackoffMs`; after `maxAttempts` the message is a dead letter the + * queue lists (`IQueueService.listFailed`), naming the source and the + * record in its metadata. A member left out takes its default. + * @default { maxAttempts: 8, backoffMs: 5000, maxBackoffMs: 120000 } — the + * seven waits sum to 395 s, so a provider outage of six minutes is ridden out + */ + recordSyncRetry?: Partial; /** * Offer the embedder section (`ai.embedder_*`) and its **Test embedder** * action (`ai/test_embedder`) on the `ai` settings page. Set to `false` on a @@ -486,6 +516,14 @@ export class KnowledgeServicePlugin implements Plugin { private readonly guardedObjects = new Set(); /** The job service the reconcile is scheduled on, kept to cancel it at destroy ({@link scheduleReconcile}). */ private jobs: IJobService | undefined; + /** + * The durable queue the record sync runs through, captured where the worker + * subscribes ({@link startRecordSyncQueue}) for the same reason as + * {@link realtime}; `undefined` while the sync runs inline. + */ + private syncQueue: IQueueService | undefined; + /** Whether init() bound a data engine to the service: the queued sync's worker re-reads through it. */ + private dataEngineBound = false; constructor(private readonly options: KnowledgeServicePluginOptions = {}) {} @@ -515,6 +553,7 @@ export class KnowledgeServicePlugin implements Plugin { }; this.logger = logger; + this.dataEngineBound = engine !== undefined; this.service = new KnowledgeService({ dataEngine: engine, logger, @@ -675,6 +714,10 @@ export class KnowledgeServicePlugin implements Plugin { // Reap-path de-indexing first: it is independent of the realtime service, // and the branch below returns early when that one is absent. this.syncReapGuards(ctx, service); + // The queue the record sync runs through, before either trigger starts: + // the queue plugin swapped its database adapter in during its own + // `kernel:ready` handler, registered in its init(), so before this one. + await this.startRecordSyncQueue(ctx, service); let realtime: IRealtimeService | null = null; try { @@ -717,8 +760,18 @@ export class KnowledgeServicePlugin implements Plugin { // plus a `payload.record ?? payload` fallback for a shape nobody sends. // An event type this handler does not name — those, and `metadata.*` // too — falls through without a sync. + // + // Through the queue ({@link startRecordSyncQueue}) the four ask for the + // same thing — the sync of the row's document, published once the + // write's unit commits — because the worker re-reads the row: its id is + // all a message carries. if (type === 'data.record.created' || type === 'data.record.updated' || type === RECORD_RESTORED_EVENT) { const record = payload.after as Record | undefined; + if (service.recordSyncQueued) { + const recordId = payload.recordId ?? record?.id; + if (typeof recordId === 'string' || typeof recordId === 'number') service.enqueueRecordSync(object, recordId); + return; + } if (record && typeof record === 'object') { await service.handleRecordUpsert(object, record); } @@ -727,7 +780,8 @@ export class KnowledgeServicePlugin implements Plugin { if (type === 'data.record.deleted') { const recordId = payload.recordId; if (typeof recordId === 'string' && recordId !== '') { - await service.handleRecordDelete(object, recordId); + if (service.recordSyncQueued) service.enqueueRecordSync(object, recordId); + else await service.handleRecordDelete(object, recordId); } return; } @@ -757,6 +811,66 @@ export class KnowledgeServicePlugin implements Plugin { }); } + /** + * Run the record sync through the composed `queue` service when it is + * durable ({@link resolveRecordSyncQueue}) and the service has a data engine + * (the worker re-reads the row): subscribe the worker on + * {@link KNOWLEDGE_RECORD_SYNC_QUEUE} and route the service's syncs there + * (`KnowledgeService.routeRecordSyncs`). Otherwise the sync stays inline, + * said once at `warn`: the save waits for the embedder, a failed sync is + * logged and not retried, and on the realtime trigger a sync runs inside + * the write's unit of work, before it commits. + * + * The worker throws what a retry can change, so the queue retries it on the + * {@link KnowledgeServicePluginOptions.recordSyncRetry} budget; on the last + * attempt it also says, at `error`, that the message is now a dead letter. + */ + private async startRecordSyncQueue(ctx: PluginContext, service: KnowledgeService): Promise { + const hasEngine = this.dataEngineBound; + const queue = resolveRecordSyncQueue((name) => ctx.getService(name)); + if (!queue || !hasEngine) { + ctx.logger.warn?.( + `KnowledgeServicePlugin: ${ + !hasEngine + ? 'no data engine is bound to re-read a row' + : 'no durable queue service is composed (the kernel\'s fallback queue and an in-memory queue keep no message across a restart and no dead letter)' + }, ` + + 'so record changes are synced inline: a save of an indexed record waits for the embedder, a failed sync is ' + + "logged and not retried, and with a realtime service the sync runs inside the write's unit of work, so a " + + 'write that rolls back can leave its document in the index until the reconcile. Compose the queue ' + + 'capability over a data engine (QueueServicePlugin) to sync through the queue.', + ); + return; + } + const retry = resolveRecordSyncRetry(this.options.recordSyncRetry); + await queue.subscribe(KNOWLEDGE_RECORD_SYNC_QUEUE, async (message: QueueMessage) => { + try { + await service.processRecordSync(message.data); + } catch (err) { + if (message.attempts >= retry.maxAttempts) { + const named = readRecordSyncMessage(message.data); + const report = + `KnowledgeServicePlugin: the sync of record '${named?.recordId ?? '?'}' of source '${named?.source ?? '?'}' ` + + `failed its last attempt (${message.attempts} of ${retry.maxAttempts}: ${err instanceof Error ? err.message : String(err)}) ` + + `and is now a dead letter on queue '${KNOWLEDGE_RECORD_SYNC_QUEUE}'. The record's document stays as it was ` + + 'until the record\'s next save or the reconcile; replay the message, or rebuild the source with os knowledge rebuild.'; + if (ctx.logger.error) ctx.logger.error(report); + else ctx.logger.warn?.(report); + } + throw err; + } + }); + this.syncQueue = queue; + service.routeRecordSyncs((message) => + queue.publish(KNOWLEDGE_RECORD_SYNC_QUEUE, message, recordSyncPublishOptions(message, retry)), + ); + ctx.logger.info?.( + `KnowledgeServicePlugin: record sync runs through queue '${KNOWLEDGE_RECORD_SYNC_QUEUE}' (up to ` + + `${retry.maxAttempts} attempts, backoff ${retry.backoffMs} ms doubling to ${retry.maxBackoffMs} ms): a save ` + + "publishes once its unit of work commits and does not wait for the embedder.", + ); + } + /** * One aggregate event of a predicate write (`multi: true`) on `object`: ask * for a reconcile of every source over it (`KnowledgeService.requestReconcile`) @@ -1140,6 +1254,16 @@ export class KnowledgeServicePlugin implements Plugin { // best-effort } } + const syncQueue = this.syncQueue; + this.syncQueue = undefined; + if (syncQueue) { + // Messages already published stay in the queue, for the next start. + try { + await syncQueue.unsubscribe(KNOWLEDGE_RECORD_SYNC_QUEUE); + } catch { + // best-effort + } + } if (!this.subscriptionId) return; try { await this.realtime?.unsubscribe(this.subscriptionId); diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 3fb05548b72..d3c81260d6b 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -73,6 +73,12 @@ import { type KnowledgeReconcileReport, type KnowledgeReconcileRequest, } from './knowledge-build.js'; +import { + readRecordSyncMessage, + type KnowledgeRecordSyncMessage, + type KnowledgeRecordSyncOutcome, + type KnowledgeRecordSyncReason, +} from './knowledge-record-sync-queue.js'; /** * Minimal logger shape; falls back to no-op when none is provided. @@ -222,6 +228,11 @@ export class KnowledgeService implements IKnowledgeService { private reconcileTail: Promise = Promise.resolve(); /** Told after the set of registered sources changed ({@link onSourcesChanged}). */ private readonly sourceListeners = new Set<() => void>(); + /** + * Where record syncs are published while they run through the queue + * ({@link routeRecordSyncs}); `undefined` while they run inline. + */ + private recordSyncPublisher: ((message: KnowledgeRecordSyncMessage) => Promise) | undefined; constructor(private readonly options: KnowledgeServiceOptions = {}) { this.defaultTopK = options.defaultTopK ?? 10; @@ -2145,8 +2156,15 @@ export class KnowledgeService implements IKnowledgeService { * it answers without it. Single-flight per document, and at most once per * document until a later search finds its hash matching. Never throws into * the search. The scheduled reconcile does not take it over: the reconcile - * walks whole sources, and this repairs one document now. It moves onto the - * queue with the record-change sync, whose path it is. + * walks whole sources, and this repairs one document now. That is the + * inline path. + * + * While record syncs run through the queue ({@link routeRecordSyncs}) the + * repair is a record-sync message with reason `freshness`, for this source + * alone: it survives a restart of the process that searched and is retried + * like any other sync. A message that could not be published is reported + * at `error` and the document is left to the next search that finds it + * stale. * * A source with `refresh.onRecordChange: false` is never repaired: it is * asked through {@link objectSourcesFor}, the one predicate that keeps the @@ -2158,6 +2176,10 @@ export class KnowledgeService implements IKnowledgeService { const docId = documentIdFor(source.name, recordId); if (this.freshnessRepairs.has(docId)) return; this.freshnessRepairs.add(docId); + if (this.recordSyncPublisher) { + this.publishRecordSyncs([source], objSource.object, recordId, 'freshness', () => this.freshnessRepairs.delete(docId)); + return; + } void this.serializeRecordSync(docId, () => this.syncRecord(source, objSource.object, recordId, { id: recordId })); } @@ -2336,13 +2358,151 @@ export class KnowledgeService implements IKnowledgeService { return kept; } - // ── Sync entrypoints (called by the host plugin's event bridge) ─── + // ── Sync entrypoints (called by the host plugin's triggers and worker) ─── + + /** + * Run record syncs through a queue (ADR-0161 K1): from now on + * {@link enqueueRecordSync} and the freshness repair publish one + * {@link KnowledgeRecordSyncMessage} per source through `publish`, and the + * host's worker hands each message to {@link processRecordSync}. + * `undefined` returns to the inline sync. `KnowledgeServicePlugin` calls it + * in `kernel:ready`, when the composed `queue` service is durable and a + * data engine is bound (the worker re-reads the row, so it needs one). + */ + routeRecordSyncs(publish: ((message: KnowledgeRecordSyncMessage) => Promise) | undefined): void { + this.recordSyncPublisher = publish; + } + + /** Whether record syncs run through the queue ({@link routeRecordSyncs}). */ + get recordSyncQueued(): boolean { + return this.recordSyncPublisher !== undefined; + } + + /** + * A record of `object` was created, updated, restored or deleted: ask for + * the sync of its document in every source that indexes `object` on record + * change ({@link objectSourcesFor}) — one message per source, carrying the + * source's index key, the object, the record id and the reason, never a + * field value. Nothing is synced here: the worker re-reads the row when it + * processes the message, so a create, an update and a delete ask for the + * same thing (the document follows the row as it is then, or leaves the + * index when no row matches). + * + * The messages are published once the unit of work open here commits, and + * never when it rolls back (`runAfterOpenUnitsCommit` of the ObjectQL + * engine): a trigger runs inside the write, before the write's own unit or + * a caller's `transaction()` commits, so a message published at once could + * be processed before the commit, and one for a write that rolls back would + * be processed at all. With no unit open they are published at once, + * outside every unit. Never awaited and never throws: a publish that fails + * is reported at `error` (the save stands, its document is stale until the + * record's next save, a search that finds it stale, or the reconcile). + * + * Requires {@link routeRecordSyncs}; inline, the triggers call + * {@link handleRecordUpsert} / {@link handleRecordDelete} instead. + */ + enqueueRecordSync(object: string, recordId: string | number, reason: KnowledgeRecordSyncReason = 'event'): void { + if (!isRecordId(recordId)) return; + const sources = this.sourcesForObject(object); + if (sources.length === 0) return; + this.publishRecordSyncs(sources, object, String(recordId), reason); + } + + /** + * Publish one record-sync message per source in `sources`, once the unit + * open here commits ({@link enqueueRecordSync}). `onFailed` runs for each + * message that could not be published. + */ + private publishRecordSyncs( + sources: KnowledgeSource[], + object: string, + recordId: string, + reason: KnowledgeRecordSyncReason, + onFailed?: () => void, + ): void { + const publish = this.recordSyncPublisher; + if (!publish) return; + const send = (): void => { + for (const source of sources) { + const message: KnowledgeRecordSyncMessage = { source: source.name, object, recordId, reason }; + void Promise.resolve() + .then(() => publish(message)) + .catch((err: unknown) => { + onFailed?.(); + const report = + `[knowledge] the sync of record '${recordId}' of source '${this.label(source)}' could not be queued ` + + `(${errorText(err)}): the write stands, and the record's document stays as it was until the record's ` + + 'next save, a search that finds it stale, or the reconcile.'; + if (this.options.logger?.error) this.options.logger.error(report); + else this.options.logger?.warn?.(report); + }); + } + }; + const engine = this.options.dataEngine as { runAfterOpenUnitsCommit?(body: () => void): void } | undefined; + if (typeof engine?.runAfterOpenUnitsCommit === 'function') engine.runAfterOpenUnitsCommit(send); + else send(); + } + + /** + * The worker's body: sync the document one {@link KnowledgeRecordSyncMessage} + * names. The source is resolved by its index key now, at processing time, + * and the row re-read under the source's `where` as the system identity + * ({@link handleRecordUpsert}, "What decides a document"): a row comes back → + * its document is written; none → its document is deleted. Serialized with + * every other sync of the same document in this process. + * + * A failure that a retry can change — the re-read, the split, the + * embedding call, the store write — is THROWN, so the queue retries the + * message on its backoff and, once its attempts are spent, keeps it as a + * dead letter. Every other outcome completes the message and is answered + * ({@link KnowledgeRecordSyncOutcome}). + */ + async processRecordSync(data: unknown): Promise { + const message = readRecordSyncMessage(data); + if (!message) { + this.options.logger?.warn?.( + `[knowledge] a message on the record-sync queue is not a record-sync message (${describeValue(data)}); completed without a sync.`, + ); + return 'malformed'; + } + const source = this.handed(message.source); + if (!source) { + this.options.logger?.debug?.( + `[knowledge] record sync of '${message.recordId}' skipped: source '${message.source}' is no longer registered.`, + ); + return 'source-gone'; + } + if (objectSourcesFor([source], message.object).length === 0) return 'not-synced'; + const engine = this.options.dataEngine; + if (!engine) { + this.options.logger?.warn?.( + `[knowledge] record sync of '${message.recordId}' for source '${this.label(source)}' skipped: no data engine is ` + + 'bound to re-read the row.', + ); + return 'not-synced'; + } + // The source's adapter is resolved now ({@link adapterFor}): the one it + // names, else the deployment's store, else the only one registered. Where + // none can be resolved it throws its coded refusal — the named adapter is + // not mounted, no adapter is mounted (`503 SERVICE_UNAVAILABLE`), or + // several are and none is the deployment's (`400 VALIDATION_ERROR`) — so + // the message is retried: a store that registers late is met by a later + // attempt, and one that never does leaves a dead letter naming the source + // and the record. + const adapter = this.adapterFor(source); + await chainAfter(this.recordSyncTails, documentIdFor(source.name, message.recordId), () => + this.syncRow(source, adapter, message.object, message.recordId, engine), + ); + return 'synced'; + } /** * Apply an ObjectQL `data.record.created`, `data.record.updated` or * `data.record.restored` event to every source bound to the - * matching object. `record` is the event payload's `after`; its `id` names + * matching object, inline. `record` is the event payload's `after`; its `id` names * the row. Failures are logged but never thrown — sync must not block writes. + * The plugin calls this only where record syncs do not run through the + * queue ({@link routeRecordSyncs}). * * ## What decides a document (ADR-0049: a declared key holds on every path) * @@ -2367,32 +2527,38 @@ export class KnowledgeService implements IKnowledgeService { * * ## When this runs, measured against the engine * - * The engine publishes `data.record.created` / `data.record.updated` from - * inside the write's engine body (`insert` / `update`), after its `after*` - * hooks, and so BEFORE any unit of work around the write commits — the - * write's own unit (opened when a metadata hook can abort it) or a caller's - * `engine.transaction(…)`. The in-process realtime service awaits each - * subscriber in turn, so this handler runs inside the write's async context, - * and its system-context re-read rides the same open transaction through the - * engine's ambient transaction store: it sees the row the write just made. + * Only on the inline path: a kernel whose `queue` service is not durable + * (the kernel's own fallback queue), or a service with no data engine. + * There the realtime subscription calls this from inside the write: the + * engine publishes `data.record.created` / `data.record.updated` from the + * write's engine body, after its `after*` hooks and BEFORE any unit of work + * around the write commits — the write's own unit (opened when a metadata + * hook can abort it) or a caller's `engine.transaction(…)` — and the + * in-process realtime service awaits each subscriber, so the save waits for + * the re-read, the split, the embedding call and the store write, and the + * re-read rides the open transaction through the engine's ambient store. * If that unit then rolls back, the index is wrong in one of two ways: on a * match, the document stays built from a row that never committed; on a - * miss, the uncommitted row did not match and the document was deleted, so - * the committed row — which may still match — is missing from the index. - * The row's next event or a `reindexSource` repairs a row that still exists; - * a document built from an INSERT that rolled back has no row left to - * repair it from — it stays until a complete `reindexSource` purges it. + * miss, the document was deleted although the committed row may still + * match. The reconcile, a later event of the row or a `reindexSource` + * repairs it. The after-write hooks (the trigger on a kernel with no + * `realtime` service) start this once the unit commits and never on a + * rollback, off the write's response (`knowledge-record-hooks.ts`). * `data.record.restored` is published after the restore's own unit has * committed. Bulk events (`data.records.*`) carry a count, not records, and * are not synced here — see the plugin's event bridge. * + * Through the queue none of this holds: the triggers publish a message once + * the write's unit commits and nothing for one that rolls back, the save + * does not wait for the sync, and a failed sync is retried + * ({@link enqueueRecordSync}, {@link processRecordSync}). + * * Syncs of one document are serialized in this process * ({@link serializeRecordSync}), so two opposite events for one row cannot * interleave: each sync re-reads after the previous one finished, and the - * last one leaves the index agreeing with the database. The chain is awaited - * inline, so a write's sync can wait behind an earlier in-flight sync of the - * same document (on a single-connection pool, up to the pool's acquire - * timeout); the index still ends consistent. + * 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. */ async handleRecordUpsert(object: string, record: Record): Promise { const recordId = record.id; @@ -2405,7 +2571,8 @@ export class KnowledgeService implements IKnowledgeService { } /** - * One source's sync of one row — see {@link handleRecordUpsert}. Never throws. + * One source's inline sync of one row — see {@link handleRecordUpsert}. + * Never throws: a failure is one `warn` line. */ private async syncRecord( source: KnowledgeSource, @@ -2433,14 +2600,7 @@ export class KnowledgeService implements IKnowledgeService { ); return; } - const row = await rereadRow(engine, objSource, recordId); - if (row) { - const doc = recordToDocument(source, objSource, row, this.schemaFor(object), await this.readTenancyPosture()); - await this.writeSynced(source, adapter, doc, recordId); - } else { - const plan = await this.planIndex(source, adapter); - await adapter.delete([documentIdFor(source.name, String(recordId))], plan.context('event-sync')); - } + await this.syncRow(source, adapter, object, recordId, engine); } catch (err) { this.options.logger?.warn?.( `[knowledge] event-sync failed for source '${this.label(source)}': ${(err as Error).message}`, @@ -2448,6 +2608,31 @@ export class KnowledgeService implements IKnowledgeService { } } + /** + * THE sync of one row's document, both paths' ({@link syncRecord} inline, + * {@link processRecordSync} from the queue): re-read the row under the + * source's `where` as the system identity ({@link rereadRow}) and write its + * document, or delete the document when no row matches. Throws what the + * re-read, the split, the embedding call or the store throws. + */ + private async syncRow( + source: KnowledgeSource, + adapter: IKnowledgeAdapter, + object: string, + recordId: string | number, + engine: IDataEngine, + ): Promise { + const objSource = source.source; + const row = await rereadRow(engine, objSource, recordId); + if (row) { + const doc = recordToDocument(source, objSource, row, this.schemaFor(object), await this.readTenancyPosture()); + await this.writeSynced(source, adapter, doc, recordId); + } else { + const plan = await this.planIndex(source, adapter); + await adapter.delete([documentIdFor(source.name, String(recordId))], plan.context('event-sync')); + } + } + /** * The event sync's write of one document: split as every path splits * ({@link prepareDocuments}) and upserted. A document the split cannot diff --git a/packages/services/service-knowledge/vitest.config.ts b/packages/services/service-knowledge/vitest.config.ts index b4989e65c48..f3da4783055 100644 --- a/packages/services/service-knowledge/vitest.config.ts +++ b/packages/services/service-knowledge/vitest.config.ts @@ -37,6 +37,14 @@ export default defineConfig({ find: /^@objectstack\/embedder-openai$/, replacement: path.resolve(__dirname, '../../plugins/embedder-openai/src/index.ts'), }, + // The record-sync queue suite boots a real kernel over the SQL driver and + // the platform's queue service; their source, like every sibling here. + { find: /^@objectstack\/driver-sql$/, replacement: path.resolve(__dirname, '../../drivers/driver-sql/src/index.ts') }, + { find: /^@objectstack\/service-queue$/, replacement: path.resolve(__dirname, '../service-queue/src/index.ts') }, + { + find: /^@objectstack\/platform-objects\/audit$/, + replacement: path.resolve(__dirname, '../../platform-objects/src/audit/index.ts'), + }, { find: /^@objectstack\/platform-objects\/system$/, replacement: path.resolve(__dirname, '../../platform-objects/src/system/index.ts'), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d2d843e03e7..2a0c7ecb37c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3254,12 +3254,18 @@ importers: specifier: workspace:* version: link:../../spec devDependencies: + '@objectstack/driver-sql': + specifier: workspace:* + version: link:../../drivers/driver-sql '@objectstack/objectql': specifier: workspace:* version: link:../../objectql '@objectstack/platform-objects': specifier: workspace:* version: link:../../platform-objects + '@objectstack/service-queue': + specifier: workspace:* + version: link:../service-queue '@types/node': specifier: ^26.6.5 version: 26.6.5