diff --git a/.changeset/37467-knowledge-title-arm-retired.md b/.changeset/37467-knowledge-title-arm-retired.md new file mode 100644 index 00000000000..33fcb066a66 --- /dev/null +++ b/.changeset/37467-knowledge-title-arm-retired.md @@ -0,0 +1,20 @@ +--- +'@objectstack/service-knowledge': patch +--- + +fix(service-knowledge): the knowledge field gate stops asking about a field named `title`; a source whose index could still hold an earlier-rule title is searched only once its index is proven built under the current recipe + +Clause-②: yes (narrowing) — narrowed: for a caller other than the system context, a source over an object that declares a field named `title` the index may carry and the source does not serve (the display field is another field, none resolves, or the object's fields cannot be enumerated; the source lists `title` in neither `content` nor `metadataFields`) is now searched only when its adapter's `indexStatus` reports the fingerprint and the recipe hash the service computes now, and the builds that record that hash purge; otherwise the search names it in `refused` as `KNOWLEDGE_REBUILD_REQUIRED` (409), and refuses whole when it was the only source, where it was searched for any caller who may query `title`. That holds until a complete build of the source has completed: on a built-in adapter the boot pass, a source reload or the reconcile runs one, and under `buildAtBoot: false` (no boot or reload build) only the reconcile, where it runs, or `os knowledge rebuild` does. It holds for good, since no build can prove the index, for a source with `refresh.onRecordChange: false` (its builds purge nothing) and on an adapter with no `indexStatus`, no `completeBuild` or no `listDocuments`. Each hit of a proven source is then served only when the record still belongs to the source and the stored `docHash` is the one the current recipe assembles from the record as it reads now (one system read per source per search round); a hit that fails that check, or that the check cannot be made for (the read fails, no record id, no stored hash, a hash that cannot be computed, an unreadable tenancy posture), is dropped, where it was served before. Widened: saving a `knowledge_source` over such an object no longer requires the author to query `title`, which the source never indexes. +Metadata-protocol: none + + + +**BREAKING** for deployments whose knowledge sources sit over an object that declares a field named `title` the source does not serve: + +- **Such a source is refused `KNOWLEDGE_REBUILD_REQUIRED` until a complete build under the current recipe completes.** On a built-in adapter (memory, pgvector, Turso) the boot pass, a source reload or the reconcile builds a source whose index records no recipe hash or another one, and the refusal ends when that build completes. Under `buildAtBoot: false`, which also turns off the build on reload, only the reconcile (where a job service runs it) builds it. Fix: run `os knowledge rebuild `; it also ends the refusal sooner in every other case. +- **A proven source serves a hit only when its stored document matches the record as it reads now.** A document written before an edit the event sync has not caught up with, or left in place by a build's purge, is dropped from the answer until it is rewritten; for a stale or missing record's own document the search starts that repair in the background, once per document until a later search finds it current, and a document under a foreign id is dropped, not repaired. Fix: none needed for a synced source; `os knowledge rebuild ` rewrites every document now. +- **An adapter whose search hits carry no `docHash` serves no hit from such a source**, since a hit with no stored hash cannot be checked against its record and is dropped. The built-in adapters (memory, pgvector, Turso) return the stored `docHash` on every hit. Fix: return each hit's stored `docHash` from the adapter's `search` (ADR-0161 K8, item 3). +- **A source with `refresh.onRecordChange: false` stays refused** to every caller but the system context: an external indexer owns its index, its builds purge nothing, so no recorded recipe hash proves it. Fix: let the service sync the source (drop `refresh.onRecordChange: false`) and rebuild it, or search it as the system context. +- **On an adapter with no `indexStatus`, no `completeBuild` or no `listDocuments`, such a source stays refused**, since no build can prove what its index holds. Fix: implement all three on the adapter (`@objectstack/spec/contracts`, `IKnowledgeAdapter`), then rebuild the source. + +The field gate (ADR-0090 D10 rule 1) kept asking whether the caller may query a declared `title` field alongside the object's display field, because a document indexed before the title became the display field carries the value of `title`. That arm is retired. A complete build under the current recipe rewrites each document it walks whose title changed (its `docHash` covers the title) and, when it purges, removes every document it did not walk; the recipe hash names the title rule (ADR-0161 K7) and was first recorded by code that already read the display field. So the search asks for that proof per source instead, and only for a source where it matters: one over an object that declares no `title` field, whose display field is `title`, whose `title` is credential-class or `internal`, or that serves `title` itself, is searched as before, with no extra read. A proven source's hits are each checked against the live record, since the proof speaks for the index as its last complete build left it and not for a document written after it. Every other arm of the gate (the display field, each `content` and `metadataFields` member, the fields `where` reads, the object-level gates) is unchanged. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 79205a676c9..d18c58ed6a0 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -304,7 +304,7 @@ Vectors from two embedding models are not comparable, and neither are the passag A store that keeps **generations** (pgvector and Turso) does not throw the old index away when the fingerprint changes. The rebuild fills a new generation beside it, and the switch happens only when the build is done: 1. **The build writes into the new generation.** The complete reindex writes every document into it. Record changes that arrive while it runs (event sync) carry the new fingerprint, so they also land in the new generation only. Nothing is written into the old one under the new model. -2. **Search during the build is refused, never answered from the old index.** A search of the source answers `KNOWLEDGE_REBUILD_REQUIRED` (409) and says the source *is being rebuilt*. A search over several sources still answers from the others, and `search_knowledge` names this one in `refused`. +2. **Search during the build is refused, never answered from the old index.** A search of the source answers `KNOWLEDGE_REBUILD_REQUIRED` (409) and says the source *is being rebuilt*. A search over several sources still answers from the others, and `search_knowledge` names this one in `refused`. The same code has a second cause, from the knowledge service itself: a source over an object that declares a `title` field the source does not serve is refused until its index is proven built under the current recipe ([the protocol's title rule](/docs/protocol/knowledge)). 3. **At the end, the switch.** Once the walk is done, the purge runs once. Then the new generation becomes the active one, and the old one is deleted. pgvector deletes it in batches of 1,000 rows, so no long lock is held over a large source. If the deletion stops part-way, the source's next build finishes it, and the old rows are never searched meanwhile. 4. **One builder per source.** pgvector takes a PostgreSQL advisory lock on the source when its build begins and holds it until the switch. A second build of the source, from another node or process, is refused `LOCK_CONFLICT` (409) and walks nothing. This is a *session* lock, so the store needs a direct or session-mode PostgreSQL connection. Behind a transaction-mode pooler (PgBouncer transaction pooling, or a hosted provider's pooled URL), the lock does not stay with the store's session. Point the store's `url` at a direct or session-mode endpoint. A release whose session no longer held the lock is logged as a warning. 5. **A build that stops is resumed, not restarted.** The generation under construction is kept, with everything written into it so far. The next build under the same fingerprint takes it up, and skips every document it already holds unchanged, so only the rest is sent to the embedding provider. If the process stops, PostgreSQL frees the lock at once. If the build fails on a process that keeps running, the lock is freed after 15 minutes without a call of the build itself. Record events that keep arriving for the source do not hold it. A build under yet another fingerprint abandons the unfinished generation and deletes it, and so does a build under the active fingerprint, when the change was reverted before the new index was finished. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index a4b04b385e7..2846df58565 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -350,8 +350,36 @@ credential-class or `internal` field, when the value is empty, and when the object resolves no display field. A source over an object with no registered definition reads a field named `title`. Documents indexed before this rule carry the value of a field named `title` until a complete -reindex writes them again, so the source admission below still asks about a -declared `title` field as well as the display field. +reindex writes them again. So a source over an object that declares a +`title` field the index may carry and the source does not serve (the display +field is another field, none resolves, or the object's fields cannot be +enumerated) is searched for a caller other than the system context only once +its adapter's index status reports the fingerprint and the recipe hash the +service computes now. The recipe hash names the title rule and is recorded +only when a complete build completes, and only a build that purges removes +the documents it did not walk. Until then the search refuses the source +`KNOWLEDGE_REBUILD_REQUIRED` (409), and the boot's build pass, a source +reload, the reconcile or `os knowledge rebuild` builds it. Under +`buildAtBoot: false` (which also turns off the build on reload) nothing but +the reconcile, where it runs, or `os knowledge rebuild` builds it. No build +proves such a source, so it stays refused, when its +`refresh.onRecordChange` is `false` (its builds purge nothing, and the boot +pass and the reconcile leave it alone) or when its adapter has no +`listDocuments`, no `completeBuild` or no index status. + +The proof covers the index as its last complete build left it. So each hit of +a proven source is also checked against its record as it reads now, with one +read per source per search round in the system context. A hit is served only +when the record still belongs to the source (its `where` included) and the +document the store holds is the one the current recipe assembles from it (the +same `docHash`). A document the build's purge left in place, or one written +after the build under an earlier recipe, is never served. The search repairs +a stale or missing record's own document in the background, once per document +until a later search finds it current; a document under a foreign id is +dropped and not repaired. A check that cannot be made drops the hit: the +read fails, the hit names no record or carries no hash, the hash cannot be +computed, or the tenancy posture cannot be read. The read decides only whether +a hit is served; nothing it reads is added to the hit. ### 3.3 `IKnowledgeService` (consumed by the ObjectOS AI runtime, REST, Console) @@ -904,10 +932,9 @@ searched for a non-system caller, the service asks, once per object per search: - **System objects** — a `sys_*` object is searched only when it declares `enable.aiReadable: true` (the AI read tools' posture). - **Field-level rules** — every field the source serves (each `content` - member; each `metadataFields` - member; the display field the title is read from, and a declared `title` - field), less the credential-class and `internal: true` fields an - index never carries, must be one the caller may **query**, per the `security` + member; each `metadataFields` member; the display field the title is read + from), less the credential-class and `internal: true` fields an index never + carries, must be one the caller may **query**, per the `security` service's `getQueryableFields`. Without that answer: its `getReadableFields` less every field declaring a `maskingRule`; with no `security` service at all: every field except those declaring a `maskingRule`. Queryable, not diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts index 80fa752b14d..7ad5883540c 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-source-admission.test.ts @@ -16,11 +16,11 @@ import { describe, it, expect, vi } from 'vitest'; import { LiteKernel } from '@objectstack/core'; import type { Plugin, PluginContext } from '@objectstack/core'; -import type { IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; +import type { AdapterContext, AdapterIndexStatus, IDataEngine, IKnowledgeAdapter } from '@objectstack/spec/contracts'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; -import { KnowledgeService, type KnowledgeLogger } from '../knowledge-service.js'; -import type { KnowledgeFieldSecurity } from '../knowledge-source-admission.js'; +import { KnowledgeService, recordToDocument, type KnowledgeLogger } from '../knowledge-service.js'; +import { mayServeEarlierRuleTitle, type KnowledgeFieldSecurity } from '../knowledge-source-admission.js'; import { KnowledgeServicePlugin, isServiceNotRegisteredError } from '../knowledge-service-plugin.js'; const MEMBER: ExecutionContext = { userId: 'u_member', positions: ['member'], permissions: [], isSystem: false }; @@ -48,9 +48,53 @@ function hitFor(sourceId: string, recordId = 'rec_1'): KnowledgeHit { return { chunkId: `${sourceId}-c`, documentId: `${sourceId}:${recordId}`, sourceId, sourceRecordId: recordId, score: 0.9, snippet: 'passage' }; } -function makeAdapter(): IKnowledgeAdapter & { searchSpy: ReturnType } { +/** + * What the adapter's `indexStatus` answers (absent: it has none). `true`: the + * fingerprint and recipe hash the call carries — an index built under the + * current recipe. `'stateful'`: it holds what its writes and its last + * `completeBuild` recorded, the way a generation-keeping adapter does. + */ +type IndexHeld = true | 'no-recipe' | 'other-recipe' | 'other-fingerprint' | 'throws' | 'stateful' | 'no-list' | 'no-complete'; + +function makeAdapter(proven?: IndexHeld): IKnowledgeAdapter & { + searchSpy: ReturnType; + indexStatus?: ReturnType; +} { const searchSpy = vi.fn(async (_q: string, opts: { source: KnowledgeSource }) => [hitFor(opts.source.name)]); - return { id: 'memory', upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search: searchSpy, searchSpy }; + const adapter = { id: 'memory', upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search: searchSpy, searchSpy }; + if (proven === undefined) return adapter; + const recorded: AdapterIndexStatus = {}; + const indexStatus = vi.fn(async (ctx: AdapterContext): Promise => { + const index = ctx.index!; + switch (proven) { + case true: + case 'no-list': + case 'no-complete': + return { fingerprint: index.fingerprint, recipeHash: index.recipeHash }; + case 'no-recipe': return { fingerprint: index.fingerprint }; + case 'other-recipe': return { fingerprint: index.fingerprint, recipeHash: 'rh1:earlier' }; + case 'other-fingerprint': return { fingerprint: 'fp1:earlier', recipeHash: index.recipeHash }; + case 'throws': throw new Error('store unreachable'); + // Documents written before any complete build: the active generation, no recipe hash. + default: return recorded.recipeHash === undefined ? { fingerprint: index.fingerprint } : { ...recorded }; + } + }); + // A store that lists its documents and records a complete build: what a proof needs besides the status. + const listDocuments = vi.fn(async () => ({ documents: [] })); + const completeBuildStub = vi.fn(async () => undefined); + if (proven === 'no-list') return { ...adapter, indexStatus, completeBuild: completeBuildStub }; + if (proven === 'no-complete') return { ...adapter, indexStatus, listDocuments }; + if (proven !== 'stateful') return { ...adapter, indexStatus, listDocuments, completeBuild: completeBuildStub }; + return { + ...adapter, + indexStatus, + listDocuments, + beginBuild: vi.fn(async () => undefined), + completeBuild: vi.fn(async (ctx: AdapterContext) => { + recorded.fingerprint = ctx.index!.fingerprint; + recorded.recipeHash = ctx.index!.recipeHash; + }), + }; } function objectSource(id: string, object: string, content: string[], metadataFields?: string[]): KnowledgeSource { @@ -62,12 +106,35 @@ function objectSource(id: string, object: string, content: string[], metadataFie }; } +/** + * How the engine double answers a system-context read (the check of a hit + * against its record): `row` gives the record as it reads now (`undefined`: + * none), `throws` makes the read fail. A caller's read answers `{ id }` rows. + */ +interface SystemReads { + row?: (object: string, id: string) => Record | undefined; + throws?: boolean; +} + /** A data engine whose row re-check admits every row, with a schema registry and a disabled-package predicate. */ -function makeEngine(objects: ObjectDef[], opts: { disabled?: string[]; schemaThrows?: boolean } = {}) { +function makeEngine(objects: ObjectDef[], opts: { disabled?: string[]; schemaThrows?: boolean; system?: SystemReads } = {}) { const byName = new Map(objects.map((o) => [o.name, o])); - const findSpy = vi.fn(async (_object: string, q: { where?: { id?: { $in?: string[] } } }) => - (q.where?.id?.$in ?? []).map((id) => ({ id })), - ); + type Where = { id?: { $in?: string[] }; $and?: Array> } & Record; + const idsOf = (where?: Where): string[] => + where?.id?.$in ?? ((where?.$and ?? []).find((c) => 'id' in c) as Where | undefined)?.id?.$in ?? []; + const findSpy = vi.fn(async (object: string, q: { where?: Where }, o?: { context?: ExecutionContext }) => { + if (o?.context?.isSystem === true && opts.system) { + if (opts.system.throws) throw new Error('system read failed'); + const row = opts.system.row ?? ((_obj: string, id: string) => ({ id })); + // An equality conjunct beside the id list is applied, as a driver would. + const conditions = (q.where?.$and ?? []).filter((c) => !('id' in c)); + return idsOf(q.where) + .map((id) => row(object, id)) + .filter((r): r is Record => r !== undefined) + .filter((r) => conditions.every((c) => Object.entries(c).every(([k, v]) => r[k] === v))); + } + return idsOf(q.where).map((id) => ({ id })); + }); return { find: findSpy, getSchema: (name: string) => { @@ -99,18 +166,35 @@ function setup(options: { disabled?: string[]; schemaThrows?: boolean; logger?: KnowledgeLogger; + /** What the adapter's `indexStatus` answers; absent, it has none. */ + proven?: IndexHeld; + system?: SystemReads; + resolveTenancyPosture?: () => Promise; }) { - const adapter = makeAdapter(); - const engine = makeEngine(options.objects ?? [TICKET], { disabled: options.disabled, schemaThrows: options.schemaThrows }); + const adapter = makeAdapter(options.proven); + const engine = makeEngine(options.objects ?? [TICKET], { + disabled: options.disabled, + schemaThrows: options.schemaThrows, + system: options.system ?? {}, + }); + // The store holds the document the current recipe assembles from the record as it reads now. + adapter.searchSpy.mockImplementation(async (_q: string, o: { source: KnowledgeSource }) => [currentHit(o.source)]); + const currentHit = (source: KnowledgeSource, recordId = 'rec_1'): KnowledgeHit => { + const objSource = source.source as ObjectKnowledgeSource; + const row = (options.system?.row ?? ((_o: string, id: string) => ({ id })))(objSource.object, recordId) ?? { id: recordId }; + const schema = (options.objects ?? [TICKET]).find((o) => o.name === objSource.object); + return { ...hitFor(source.name, recordId), docHash: recordToDocument(source, objSource, row, schema).docHash }; + }; const svc = new KnowledgeService({ dataEngine: engine, logger: options.logger, resolveSecurity: options.security ? () => options.security : undefined, + ...(options.resolveTenancyPosture ? { resolveTenancyPosture: options.resolveTenancyPosture } : {}), }); svc.registerAdapter('memory', adapter); for (const s of options.sources) svc.registerSource(s); const searched = () => adapter.searchSpy.mock.calls.map((c) => (c[1] as { source: KnowledgeSource }).source.name); - return { svc, adapter, engine, searched }; + return { svc, adapter, engine, searched, currentHit }; } const ids = (hits: KnowledgeHit[]) => hits.map((h) => h.sourceId).sort(); @@ -408,22 +492,394 @@ describe('field gate — the title field is the object\'s display field', () => expect(searched()).toEqual([]); }); - // A document indexed before the title became the display field carries the - // value of the field named `title`, and stays in the index until a complete - // reindex writes it again: the gate still asks about a declared `title`. - it('refusal: a declared `title` the caller may not query still refuses the source — a stored hit may carry its value', async () => { - const hideTitle = makeSecurity(() => ['id', 'name', 'body']); - const { svc, adapter, searched } = setup({ objects: [ACCOUNT], sources: [objectSource('s', 'account', ['body'])], security: hideTitle }); - adapter.searchSpy.mockImplementation(async () => [{ ...hitFor('s'), title: 'synthetic-old-rule-title-4e1a' }]); - expect(await svc.search('q', { executionContext: MEMBER })).toEqual([]); + it('preservation: a caller who may query the display field gets the hit', async () => { + const all = makeSecurity(() => ['id', 'name', 'title', 'body']); + const { svc } = setup({ objects: [ACCOUNT], sources: [objectSource('s', 'account', ['body'])], security: all, proven: true }); + expect(ids(await svc.search('q', { executionContext: MEMBER }))).toEqual(['s']); + }); +}); + +// The gate's former `title` arm: a document indexed before the title became +// the display field carries the value of a field named `title`. The gate no +// longer asks about that field; instead a source over which such a document +// could be served is searched only once its index is proven built under the +// current recipe (the adapter's `indexStatus` reports the fingerprint and the +// recipe hash the service computes now), and is refused +// KNOWLEDGE_REBUILD_REQUIRED (409) until then — never served through a gate +// that asks about `title`. +describe('field gate — the earlier title rule: searched only once the index is proven built under the current recipe', () => { + const ACCOUNT: ObjectDef = { + name: 'account', + fields: { id: { type: 'text' }, name: { type: 'text' }, title: { type: 'text' }, body: { type: 'textarea' } }, + }; + const hideTitle = makeSecurity(() => ['id', 'name', 'body']); + const queryAll = makeSecurity(() => ['id', 'name', 'title', 'body']); + + it('proven: a caller who may not query `title` is served — the arm is gone for a source built under the current recipe', async () => { + const { svc, adapter, searched } = setup({ objects: [ACCOUNT], sources: [objectSource('s', 'account', ['body'])], security: hideTitle, proven: true }); + expect(ids(await svc.search('q', { executionContext: MEMBER }))).toEqual(['s']); + expect(searched()).toEqual(['s']); + expect(adapter.indexStatus).toHaveBeenCalledOnce(); + }); + + it.each([ + ['an adapter with no indexStatus', undefined, 'never'], + ['an adapter with no completeBuild, whose status reads current', 'no-complete' as const, 'never'], + ['an adapter with no listDocuments, whose status reads current: its builds purge nothing', 'no-list' as const, 'never'], + ['an index that records no recipe hash (no complete build completed)', 'no-recipe' as const, 'rebuild'], + ['an index last completed under another recipe', 'other-recipe' as const, 'rebuild'], + ['an index under another fingerprint', 'other-fingerprint' as const, 'rebuild'], + ['an indexStatus that throws', 'throws' as const, 'unreadable'], + ])('unproven (%s): refused KNOWLEDGE_REBUILD_REQUIRED / 409 for every non-system caller, never searched', async (_label, held, ends) => { + for (const security of [hideTitle, queryAll]) { + const warn = vi.fn(); + const { svc, searched } = setup({ + objects: [ACCOUNT], + sources: [objectSource('s', 'account', ['body'])], + security, + ...(held === undefined ? {} : { proven: held }), + logger: { warn, error: vi.fn() }, + }); + let thrown: unknown; + try { + await svc.searchWithRefusals('q', { executionContext: MEMBER }); + } catch (err) { + thrown = err; + } + expect(thrown).toMatchObject({ code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 }); + expect((thrown as { refused: unknown[] }).refused).toEqual([ + expect.objectContaining({ sourceId: 's', code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 }), + ]); + expect(searched()).toEqual([]); + const line = String(warn.mock.calls[warn.mock.calls.length - 1]?.[0]); + expect(line).toContain("source 's' not searched (KNOWLEDGE_REBUILD_REQUIRED)"); + // A refusal no rebuild can end never promises one, to the caller or the operator. + const said = (thrown as { refused: Array<{ message: string }> }).refused[0].message; + if (ends === 'never') { + expect(said).toContain('No rebuild changes that'); + expect(line).toContain('No rebuild can prove it'); + } else { + expect(said).not.toContain('No rebuild'); + expect(line).not.toContain('No rebuild'); + } + // Preservation: the system context bypasses every gate, this one too. + expect(ids(await svc.search('q', { executionContext: SYSTEM }))).toEqual(['s']); + } + }); + + it('a source with `refresh.onRecordChange: false` is never proven, whatever its status reads: its builds purge nothing', async () => { + const optedOut = objectSource('s', 'account', ['body']); + const source = { ...optedOut, refresh: { onRecordChange: false } } as KnowledgeSource; + const warn = vi.fn(); + const { svc, adapter, searched } = setup({ objects: [ACCOUNT], sources: [source], security: queryAll, proven: true, logger: { warn, error: vi.fn() } }); + const thrown = await svc.searchWithRefusals('q', { executionContext: MEMBER }).catch((err: unknown) => err); + expect(thrown).toMatchObject({ code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 }); + expect((thrown as { refused: Array<{ message: string }> }).refused[0].message).toContain('No rebuild changes that'); + expect(String(warn.mock.calls[warn.mock.calls.length - 1]?.[0])).toContain('refresh.onRecordChange is false'); + expect(adapter.indexStatus).not.toHaveBeenCalled(); expect(searched()).toEqual([]); + // Preservation: the system context bypasses it, and the same source synced by the service is proven. + expect(ids(await svc.search('q', { executionContext: SYSTEM }))).toEqual(['s']); + const synced = setup({ objects: [ACCOUNT], sources: [optedOut], security: queryAll, proven: true }); + expect(ids(await synced.svc.search('q', { executionContext: MEMBER }))).toEqual(['s']); }); - it('preservation: a caller who may query both the display field and `title` gets the hit', async () => { - const all = makeSecurity(() => ['id', 'name', 'title', 'body']); - const { svc } = setup({ objects: [ACCOUNT], sources: [objectSource('s', 'account', ['body'])], security: all }); + it('beside a searchable source, the unproven one is named in `refused` and the other still answers', async () => { + const { svc, searched } = setup({ + objects: [ACCOUNT, TICKET], + sources: [objectSource('unproven', 'account', ['body']), objectSource('tickets', 'ticket', ['body'])], + security: queryAll, + }); + const report = await svc.searchWithRefusals('q', { executionContext: MEMBER }); + expect(ids(report.hits)).toEqual(['tickets']); + expect(report.refused).toEqual([ + expect.objectContaining({ sourceId: 'unproven', code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 }), + ]); + expect(searched()).toEqual(['tickets']); + }); + + it('a source the earlier rule served nothing extra for is searched without asking for the proof', async () => { + // TICKET's display field IS `title`; a source listing `title` serves it; an object with no `title` field. + const NOTE: ObjectDef = { name: 'note', fields: { id: { type: 'text' }, name: { type: 'text' }, body: { type: 'textarea' } } }; + const { svc, adapter, searched } = setup({ + objects: [ACCOUNT, TICKET, NOTE], + sources: [ + objectSource('tickets', 'ticket', ['body']), + objectSource('titled', 'account', ['body', 'title']), + objectSource('notes', 'note', ['body']), + ], + security: makeSecurity((object) => (object === 'note' ? ['id', 'name', 'body'] : ['id', 'name', 'title', 'body'])), + proven: 'throws', + }); + expect(ids(await svc.search('q', { executionContext: MEMBER }))).toEqual(['notes', 'tickets', 'titled']); + expect(searched().sort()).toEqual(['notes', 'tickets', 'titled']); + expect(adapter.indexStatus).not.toHaveBeenCalled(); + }); + + it('rebuilt: a source refused for want of proof is served once a complete build has completed', async () => { + const { svc, adapter, searched } = setup({ objects: [ACCOUNT], sources: [objectSource('s', 'account', ['body'])], security: hideTitle, proven: 'stateful' }); + await expect(svc.search('q', { executionContext: MEMBER })).rejects.toMatchObject({ code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 }); + expect(searched()).toEqual([]); + // A refused search starts no build and writes nothing. + for (const member of ['beginBuild', 'upsert', 'completeBuild'] as const) { + expect((adapter as unknown as Record>)[member]).not.toHaveBeenCalled(); + } + const record = await svc.rebuildSource('s', { trigger: 'operator' }); + expect(record.status).toBe('done'); + expect((await svc.readIndexState('s')).state).toBe('current'); expect(ids(await svc.search('q', { executionContext: MEMBER }))).toEqual(['s']); }); + + // Reverse pins: with the proof in hand, no other arm is weakened — a field + // the caller may not query still never reaches a hit. + it.each([ + ['the display field', ['id', 'title', 'body'], ['body']], + ['a content field', ['id', 'name', 'title'], ['body']], + ['a metadata field', ['id', 'name', 'title', 'body'], ['body'], ['status']], + ])('reverse pin, proven index: %s the caller may not query still refuses the source', async (_label, queryable, content, metadata?: string[]) => { + const withStatus: ObjectDef = { ...ACCOUNT, fields: { ...ACCOUNT.fields, status: { type: 'select' } } }; + const { svc, adapter, searched } = setup({ + objects: [withStatus], + sources: [objectSource('s', 'account', content, metadata)], + security: makeSecurity(() => queryable), + proven: true, + }); + adapter.searchSpy.mockImplementation(async () => [{ ...hitFor('s'), title: 'synthetic-hidden-name-7c2d', metadata: { status: 'hidden' } }]); + expect(await svc.search('q', { executionContext: MEMBER })).toEqual([]); + expect(searched()).toEqual([]); + }); + + // A proven source's hits are each checked against the record as it reads + // now (ADR-0161 K7): a write the store has not caught up with — a record + // whose stored document is not the one the current recipe assembles — is + // never served, and every way the check cannot be made drops the hit. + describe('per-hit check: a proven source serves only documents the current recipe assembles from the live record', () => { + const SECRET = 'synthetic-live-secret-5d8e'; + const live = (_o: string, id: string) => ({ id, name: 'Acme', title: 'synthetic-earlier-title-2b9c', body: 'current body', secret_note: SECRET }); + const proven = (extra: Partial[0]> = {}) => + setup({ objects: [ACCOUNT], sources: [objectSource('s', 'account', ['body'])], security: hideTitle, proven: true, system: { row: live }, ...extra }); + + it('CONTROL: a stored document matching the live record is served, as the store answered it', async () => { + const { svc, engine, currentHit } = proven(); + const stored = currentHit(svc.getSource('s')!); + expect(await svc.search('q', { executionContext: MEMBER })).toEqual([stored]); + const systemReads = engine.find.mock.calls.filter((c) => (c[2] as { context?: ExecutionContext } | undefined)?.context?.isSystem === true); + expect(systemReads).toHaveLength(1); + expect(systemReads[0][1]).toMatchObject({ where: { id: { $in: ['rec_1'] } } }); + }); + + it('the read decides survival only: no field it returns reaches the caller', async () => { + const { svc, adapter, currentHit } = proven(); + const stored = currentHit(svc.getSource('s')!); + adapter.searchSpy.mockImplementation(async () => [{ ...stored }]); + const served = await svc.search('q', { executionContext: MEMBER }); + expect(served).toEqual([stored]); + const text = JSON.stringify(served); + for (const value of [SECRET, 'synthetic-earlier-title-2b9c', 'current body', 'Acme']) expect(text).not.toContain(value); + }); + + it.each([ + ['a write the store has not caught up with (S1): the stored hash is not the current one', (h: KnowledgeHit) => ({ ...h, docHash: 'dh1:written-before-the-edit' })], + ['a document a complete build kept: its record reads differently now', (h: KnowledgeHit) => ({ ...h, docHash: 'dh1:kept-from-an-earlier-build' })], + ['a foreign document: its id is not the one the source derives from the record', (h: KnowledgeHit) => ({ ...h, documentId: 'foreign:rec_1' })], + ['a stored document with no hash', (h: KnowledgeHit) => ({ ...h, docHash: undefined })], + ['a stored document with an empty hash', (h: KnowledgeHit) => ({ ...h, docHash: '' })], + ])('dropped: %s', async (_label, alter) => { + const { svc, adapter, currentHit } = proven(); + const stored = currentHit(svc.getSource('s')!); + adapter.searchSpy.mockImplementation(async () => [alter(stored)]); + expect(await svc.search('q', { executionContext: MEMBER })).toEqual([]); + // Preservation: the system context is not checked, as every gate. + expect(ids(await svc.search('q', { executionContext: SYSTEM }))).toEqual(['s']); + }); + + it('dropped: a hit whose stored docHash differs from the record\'s current build inputs', async () => { + const { svc, adapter } = proven(); + const source = svc.getSource('s')!; + const objSource = source.source as ObjectKnowledgeSource; + // The index proves current throughout: no complete build ran between the change and the change-back. + const whileTitle = { ...ACCOUNT, nameField: 'title' }; + const synced = recordToDocument(source, objSource, live('account', 'rec_1'), whileTitle); + expect(synced.title).toBe('synthetic-earlier-title-2b9c'); + adapter.searchSpy.mockImplementation(async () => [{ ...hitFor('s'), title: synced.title, docHash: synced.docHash }]); + const served = await svc.search('q', { executionContext: MEMBER }); + expect(served).toEqual([]); + expect(JSON.stringify(served)).not.toContain('synthetic-earlier-title-2b9c'); + }); + + it('a source with a `where`: the system read asks for the conjunction of `where` and the hits\' ids, and a record outside `where` is dropped', async () => { + const SCOPED: ObjectDef = { ...ACCOUNT, fields: { ...ACCOUNT.fields, status: { type: 'select' } } }; + const where = { status: 'open' }; + const source = { ...objectSource('s', 'account', ['body']), source: { kind: 'object', object: 'account', content: ['body'], where } } as KnowledgeSource; + for (const status of ['open', 'closed']) { + const row = (o: string, id: string) => ({ ...live(o, id), status }); + const { svc, engine, currentHit } = setup({ + objects: [SCOPED], + sources: [source], + security: makeSecurity(() => ['id', 'name', 'body', 'status']), + proven: true, + system: { row }, + }); + const served = await svc.search('q', { executionContext: MEMBER }); + expect(served).toEqual(status === 'open' ? [currentHit(source)] : []); + const systemReads = engine.find.mock.calls.filter((c) => (c[2] as { context?: ExecutionContext } | undefined)?.context?.isSystem === true); + // The check's own read comes first; a record found outside `where` then has its document repaired. + expect((systemReads[0][1] as { where: unknown }).where).toEqual({ $and: [where, { id: { $in: ['rec_1'] } }] }); + } + }); + + it('the refill round is checked too: a stale hit the second round answers is dropped', async () => { + const { svc, adapter, currentHit } = proven(); + const source = svc.getSource('s')!; + const stale = (n: number): KnowledgeHit => ({ ...currentHit(source, `rec_${n}`), chunkId: `s-c${n}`, docHash: 'dh1:written-before-the-edit' }); + const asked: number[] = []; + adapter.searchSpy.mockImplementation(async (_q: string, o: { topK: number }) => { + asked.push(o.topK); + // The first round answers as many as it was asked, every one stale, so nothing survives it and + // the source is refilled; the refill answers the same stale hits again and one current hit. + const hits = Array.from({ length: 5 }, (_v, i) => stale(i + 2)); + return asked.length === 1 ? hits : [...hits, { ...currentHit(source, 'rec_1'), chunkId: 's-c1', score: 0.1 }]; + }); + const served = await svc.search('q', { executionContext: MEMBER, topK: 1 }); + expect(asked).toEqual([5, 20]); + expect(served.map((hit) => hit.sourceRecordId)).toEqual(['rec_1']); + }); + + it('dropped: a record the system read no longer answers (deleted, or outside the source\'s `where`)', async () => { + const gone = (o: string, id: string) => (id === 'rec_1' ? undefined : live(o, id)); + const { svc, adapter, currentHit } = proven({ system: { row: gone } }); + adapter.searchSpy.mockImplementation(async () => [{ ...currentHit(svc.getSource('s')!), docHash: recordToDocument(svc.getSource('s')!, svc.getSource('s')!.source as ObjectKnowledgeSource, live('account', 'rec_1'), ACCOUNT).docHash }]); + expect(await svc.search('q', { executionContext: MEMBER })).toEqual([]); + }); + + it('fails closed: a system read that throws, or answers no list, drops every hit of the source', async () => { + for (const system of [{ row: live, throws: true }, { row: live }] as SystemReads[]) { + const warn = vi.fn(); + const { svc, engine } = proven({ system, logger: { warn, error: vi.fn() } }); + if (system.throws !== true) { + const callerRead = engine.find.getMockImplementation()!; + engine.find.mockImplementation(async (object, q, o) => (o?.context?.isSystem === true ? ({ rows: [] } as never) : callerRead(object, q, o))); + } + expect(await svc.search('q', { executionContext: MEMBER })).toEqual([]); + expect(String(warn.mock.calls[warn.mock.calls.length - 1]?.[0])).toContain('could not be read to check its hits'); + } + }); + + it('fails closed: a tenancy posture that cannot be read drops every hit of a checked source', async () => { + const warn = vi.fn(); + // The organization scoping reads the posture first and answers; the check's own read is the one that fails. + let reads = 0; + const { svc, searched } = proven({ + logger: { warn, error: vi.fn() }, + resolveTenancyPosture: async () => { + reads += 1; + if (reads > 1) throw new Error('posture store unreachable'); + return undefined; + }, + }); + expect(await svc.search('q', { executionContext: MEMBER })).toEqual([]); + expect(searched()).toEqual(['s']); + expect(warn.mock.calls.map((c) => String(c[0])).join('\n')).toContain('the tenancy posture could not be read'); + }); + + it('fails closed: a hash that cannot be recomputed from the live row drops the hit', async () => { + const poisoned = (_o: string, id: string) => ({ + id, + name: 'Acme', + body: { + toString(): string { + throw new Error('unreadable value'); + }, + toJSON(): never { + throw new Error('unreadable value'); + }, + }, + }); + const { svc, adapter } = proven({ system: { row: poisoned } }); + adapter.searchSpy.mockImplementation(async () => [{ ...hitFor('s'), docHash: 'dh1:anything' }]); + expect(await svc.search('q', { executionContext: MEMBER })).toEqual([]); + }); + + it('fails closed: a hit with no `sourceRecordId` is dropped even where every other check would pass', async () => { + const { svc, adapter } = proven(); + const source = svc.getSource('s')!; + // The worst case: its document id and hash are the ones a record id of `undefined` would give. + const docHash = recordToDocument(source, source.source as ObjectKnowledgeSource, live('account', 'undefined'), ACCOUNT).docHash; + adapter.searchSpy.mockImplementation(async () => [{ ...hitFor('s'), documentId: 's:undefined', sourceRecordId: undefined, docHash }]); + expect(await svc.search('q', { executionContext: MEMBER })).toEqual([]); + }); + + it('a source that needs the index proof is never searched without it: the round searches the adapter the proof was read from', async () => { + const { svc, adapter, currentHit } = proven(); + const source = svc.getSource('s')!; + const unproven = makeAdapter(); + unproven.searchSpy.mockImplementation(async () => [currentHit(source)]); + const readStatus = adapter.indexStatus!.getMockImplementation() as (ctx: AdapterContext) => Promise; + // Another instance takes the adapter id while the proof is being read. + adapter.indexStatus!.mockImplementation(async (ctx: AdapterContext) => { + svc.registerAdapter('memory', unproven); + return readStatus(ctx); + }); + expect(await svc.search('q', { executionContext: MEMBER })).toEqual([currentHit(source)]); + expect(adapter.searchSpy).toHaveBeenCalledOnce(); + expect(unproven.searchSpy).not.toHaveBeenCalled(); + }); + + it('a source that needs the index proof is never searched without it: an adapter that resolves only after the plan is not searched', async () => { + const late = { ...objectSource('late', 'account', ['body']), adapter: 'late' } as KnowledgeSource; + const { svc, adapter } = proven({ sources: [late, objectSource('s', 'account', ['body'])] }); + const lateAdapter = makeAdapter(true); + const readStatus = adapter.indexStatus!.getMockImplementation() as (ctx: AdapterContext) => Promise; + // The adapter `late` names registers after its source was planned, while another source's proof is read. + adapter.indexStatus!.mockImplementation(async (ctx: AdapterContext) => { + if (!svc.listAdapters().includes('late')) svc.registerAdapter('late', lateAdapter); + return readStatus(ctx); + }); + const report = await svc.searchWithRefusals('q', { executionContext: MEMBER }); + expect(ids(report.hits)).toEqual(['s']); + expect(report.refused).toEqual([expect.objectContaining({ sourceId: 'late', code: 'SERVICE_UNAVAILABLE', status: 503 })]); + expect(lateAdapter.searchSpy).not.toHaveBeenCalled(); + expect(lateAdapter.indexStatus).not.toHaveBeenCalled(); + }); + + it('only a proven source is checked: a source searched without the proof is served as the store answered it', async () => { + const { svc, adapter, currentHit } = setup({ + objects: [ACCOUNT, TICKET], + sources: [objectSource('s', 'account', ['body']), objectSource('tickets', 'ticket', ['body'])], + security: makeSecurity((object) => (object === 'ticket' ? Object.keys(TICKET.fields) : ['id', 'name', 'body'])), + proven: true, + system: { row: live }, + }); + adapter.searchSpy.mockImplementation(async (_q: string, o: { source: KnowledgeSource }) => + o.source.name === 'tickets' ? [{ ...hitFor('tickets'), docHash: undefined }] : [currentHit(o.source)], + ); + expect(ids(await svc.search('q', { executionContext: MEMBER })).sort()).toEqual(['s', 'tickets']); + }); + }); + + it('reverse pin, unproven index: a stored hit carrying an earlier-rule `title` never reaches a caller who may not query it', async () => { + const { svc, adapter, searched } = setup({ objects: [ACCOUNT], sources: [objectSource('s', 'account', ['body'])], security: hideTitle, proven: 'no-recipe' }); + adapter.searchSpy.mockImplementation(async () => [{ ...hitFor('s'), title: 'synthetic-old-rule-title-4e1a' }]); + const out = await svc.search('q', { executionContext: MEMBER }).catch((err: unknown) => err); + expect(out).toMatchObject({ code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 }); + expect(JSON.stringify(out)).not.toContain('synthetic-old-rule-title-4e1a'); + expect(searched()).toEqual([]); + }); +}); + +describe('mayServeEarlierRuleTitle — whether an earlier-rule index could serve a field the gate does not ask about', () => { + const src = (content: string[], metadataFields?: string[]) => objectSource('s', 'x', content, metadataFields).source as ObjectKnowledgeSource; + it.each([ + ['an object declaring `title` beside a `name` display field', { fields: { name: { type: 'text' }, title: { type: 'text' } } }, ['body'], true], + ['an object whose display field is `title`', { fields: { title: { type: 'text' }, body: { type: 'textarea' } } }, ['body'], false], + ['an object declaring no `title` field', { fields: { name: { type: 'text' }, body: { type: 'textarea' } } }, ['body'], false], + ['a source that serves `title` itself', { fields: { name: { type: 'text' }, title: { type: 'text' } } }, ['title'], false], + ['an `internal` `title` the index never carries', { fields: { name: { type: 'text' }, title: { type: 'text', internal: true } } }, ['body'], false], + ['fields that cannot be enumerated, display field elsewhere', { nameField: 'subject' }, ['body'], true], + ['no object definition (the title is read from `title`)', undefined, ['body'], false], + ])('%s → %s', (_label, schema, content, expected) => { + expect(mayServeEarlierRuleTitle(src(content), schema)).toBe(expected); + }); }); // [ADR-0161 K4, guard two] The same gates, asked once for the AUTHOR when a @@ -498,6 +954,20 @@ describe('admitAuthoredSource — source admission at save, as the authoring pri expect((verdict as { message: string }).message).toContain("display field"); }); + it('a declared `title` that is not the display field is not indexed, so it is not asked at save; the display field still is', async () => { + const ACCOUNT: ObjectDef = { + name: 'account', + fields: { id: { type: 'text' }, name: { type: 'text' }, title: { type: 'text' }, body: { type: 'textarea' } }, + }; + const hideTitle = makeSecurity(() => ['id', 'name', 'body']); + const admitted = setup({ objects: [ACCOUNT], sources: [], security: hideTitle }); + expect(await admitted.svc.admitAuthoredSource(item('account', ['body']), MEMBER)).toEqual({ admitted: true }); + const hideName = makeSecurity(() => ['id', 'title', 'body']); + const refused = setup({ objects: [ACCOUNT], sources: [], security: hideName }); + expect(await refused.svc.admitAuthoredSource(item('account', ['body']), MEMBER)) + .toMatchObject({ admitted: false, code: 'PERMISSION_DENIED', status: 403, object: 'account', field: 'name' }); + }); + it.each([ ['an object of a disabled package', { objects: [TICKET], disabled: ['ticket'] }, 'ticket', 'disabled package'], ['an object the API does not serve at all', { objects: [sealed] }, 'sealed', 'does not serve object'], diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 3fb05548b72..320244f1804 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -4,6 +4,7 @@ import { createHash } from 'node:crypto'; import type { AdapterContext, AdapterIndexExpectation, + AdapterIndexStatus, AdapterScopeTerm, IDataEngine, IKnowledgeAdapter, @@ -44,6 +45,7 @@ import { import { admitObject, admitSourceFields, + mayServeEarlierRuleTitle, declaredFields, documentTitleField, type KnowledgeAdmissionDeps, @@ -1889,12 +1891,18 @@ export class KnowledgeService implements IKnowledgeService { } const byRecord = opts.granularity === 'record' || groupBy !== undefined; const ctx = opts.executionContext; - let admitted: Array<{ source: KnowledgeSource; organizationIds?: string[]; scope?: AdapterScopeTerm[] }> = + let admitted: Array = await this.admitSources(this.resolveSearchTargets(opts.sourceIds), ctx); if (scope !== undefined) admitted = this.sourcesInScope(admitted, scope); if (groupBy !== undefined) admitted = this.sourcesGroupableBy(admitted, groupBy); if (admitted.length === 0) return { hits: [], refused: [] }; - const sources = await this.planSearches(admitted); + const refused: KnowledgeSearchRefusal[] = []; + const sources = await this.planSearches(admitted, refused); + // The sources whose every hit is checked against its live record before + // it is served: the ones the earlier title rule could serve a field for. + const verified = new Set(sources.filter((target) => target.verifyHits === true).map((target) => target.source.name)); + const served = async (hits: KnowledgeHit[]): Promise => + verified.size === 0 ? hits : this.dropUnverifiedHits(hits, verified); const filtered = ctx !== undefined && ctx.isSystem !== true && this.options.dataEngine !== undefined; const widened = byRecord || filtered; @@ -1903,11 +1911,10 @@ export class KnowledgeService implements IKnowledgeService { const groupOf = byRecord ? (hit: KnowledgeHit): string | undefined => this.groupKeyOf(hit, groupBy) : recordKeyOf; - const refused: KnowledgeSearchRefusal[] = []; const first = await this.searchRound(query, sources, firstAsk, opts.filter, refused); if (first.size === 0 && refused.length > 0) throw wholeRefusal(this.facedRefusals(refused)); const raw = [...first.values()].flatMap((answer) => answer.hits); - let kept = await this.applyPermissionFilter(raw, ctx, byRecord); + let kept = await served(await this.applyPermissionFilter(raw, ctx, byRecord)); let removed = raw.length - kept.length; if ((filtered || byRecord) && distinctGroups(kept, groupOf) < topK) { @@ -1921,7 +1928,7 @@ export class KnowledgeService implements IKnowledgeService { // A refilled source's second answer is a superset of its first: its // first-round survivors are dropped and the whole answer re-checked. const refilledHits = [...refill.values()].flatMap((answer) => answer.hits); - const refilledKept = await this.applyPermissionFilter(refilledHits, ctx, byRecord); + const refilledKept = await served(await this.applyPermissionFilter(refilledHits, ctx, byRecord)); const firstRaw = raw.filter((hit) => refill.has(hit.sourceId)).length; const firstKept = kept.filter((hit) => refill.has(hit.sourceId)).length; kept = [...kept.filter((hit) => !refill.has(hit.sourceId)), ...refilledKept]; @@ -1939,7 +1946,7 @@ export class KnowledgeService implements IKnowledgeService { if (removed > 0) { this.options.logger?.debug?.( - `[knowledge] the permission re-check removed ${removed} hit(s) this caller may not read; ` + + `[knowledge] the permission re-check and the per-hit record check removed ${removed} hit(s); ` + `${Math.min(byRecord ? distinctGroups(kept, groupOf) : kept.length, topK)} of topK=${topK} answered.`, ); } @@ -2138,6 +2145,128 @@ export class KnowledgeService implements IKnowledgeService { } } + /** + * The hits of `verified` sources whose stored document is the one the + * current recipe assembles from the record as it reads now; every other hit + * of those sources is dropped. A hit of any other source passes untouched. + * + * Why: a source the earlier title rule could serve a field for + * (`mayServeEarlierRuleTitle`) is searched without the field gate's former + * `title` arm, and its index may still hold a document assembled under + * another recipe: one a build walked past and did not purge (a store with + * no `listDocuments`, `refresh.onRecordChange: false`, a purge candidate + * kept or listed under a foreign id), or one written between two builds + * while the object's display field was another field. The recipe hash + * cannot see either; this check reads the record. A hit survives only when + * its record still belongs to the source (one system read per source, + * `{ $and: [where, { id: { $in } }] }`, projected to the fields assembly + * reads), its document id is the one the source derives from that record, + * and the `docHash` the store holds equals the one {@link recordToDocument} + * computes from the row under the current object definition (the title is + * part of it). Strict, unlike {@link checkFreshness}: a hit with no record + * id or no stored hash, a read that fails or answers no list, a posture + * that cannot be read and a hash that cannot be computed each drop the hit. + * + * The read decides only whether a hit survives: a surviving hit is returned + * as the store answered it, and nothing the read returned is put on it. A + * stale record's document is repaired in the background ({@link + * repairStale}), as the record-level check repairs it. + */ + private async dropUnverifiedHits(hits: KnowledgeHit[], verified: ReadonlySet): Promise { + const engine = this.options.dataEngine; + const checked = hits.filter((hit) => verified.has(hit.sourceId)); + if (checked.length === 0) return hits; + const passed = new Set(); + const dropped = (sourceId: string, count: number, why: string): void => { + if (count > 0) { + this.options.logger?.debug?.( + `[knowledge] ${count} hit(s) of source '${this.faceOfKey(sourceId)}' not served: ${why}`, + ); + } + }; + let posture: TenancyPosture | undefined; + let postureRead = true; + try { + posture = await this.readTenancyPosture(); + } catch (err) { + postureRead = false; + this.options.logger?.warn?.( + `[knowledge] the tenancy posture could not be read (${errorText(err)}); no hit of a source checked against its ` + + 'record is served this search (fail-closed).', + ); + } + const bySource = new Map(); + for (const hit of checked) bySource.set(hit.sourceId, [...(bySource.get(hit.sourceId) ?? []), hit]); + for (const [sourceId, sourceHits] of bySource) { + const source = this.handed(sourceId); + if (!engine || !postureRead || !source || source.source.kind !== 'object') { + dropped(sourceId, sourceHits.length, 'their records cannot be read to check them.'); + continue; + } + const objSource = source.source; + const usable = sourceHits.filter( + (hit) => isRecordId(hit.sourceRecordId) && typeof hit.docHash === 'string' && hit.docHash !== '', + ); + dropped(sourceId, sourceHits.length - usable.length, 'a hit names no record or carries no stored hash.'); + if (usable.length === 0) continue; + const ids = [...new Set(usable.map((hit) => String(hit.sourceRecordId)))]; + const byId = { id: { $in: ids } }; + const schema = this.schemaFor(objSource.object); + let rows: unknown; + try { + const fields = freshnessFields(objSource, schema, posture); + rows = await engine.find( + objSource.object, + { + where: objSource.where !== undefined ? { $and: [objSource.where, byId] } : byId, + ...(fields === undefined ? {} : { fields }), + }, + { context: systemContext() }, + ); + if (!Array.isArray(rows)) throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); + } catch (err) { + this.options.logger?.warn?.( + `[knowledge] the records of source '${this.faceOfKey(sourceId)}' could not be read to check its hits ` + + `(${errorText(err)}); none is served (fail-closed).`, + ); + continue; + } + const byRow = new Map>(); + for (const row of rows as Array | null | undefined>) { + if (row && isRecordId(row.id)) byRow.set(String(row.id), row); + } + const current = new Map(); + for (const hit of usable) { + const recordId = String(hit.sourceRecordId); + if (hit.documentId !== documentIdFor(sourceId, recordId)) continue; + if (!current.has(recordId)) { + const row = byRow.get(recordId); + let hash: string | undefined; + if (row !== undefined) { + try { + hash = recordToDocument(source, objSource, row, schema, posture).docHash; + } catch { + hash = undefined; + } + } + current.set(recordId, hash); + if (row === undefined || (hash !== undefined && hash !== hit.docHash)) this.repairStale(source, objSource, recordId); + } + const hash = current.get(recordId); + if (hash !== undefined && hash === hit.docHash) { + passed.add(hit); + this.freshnessRepairs.delete(documentIdFor(sourceId, recordId)); + } + } + dropped( + sourceId, + usable.filter((hit) => !passed.has(hit)).length, + 'the record no longer belongs to the source, or the stored document is not the one the current recipe assembles from it.', + ); + } + return hits.filter((hit) => !verified.has(hit.sourceId) || passed.has(hit)); + } + /** * Repair the document of a record the freshness check found stale: the * event sync's own path ({@link syncRecord}, serialized per document), run @@ -2162,30 +2291,148 @@ export class KnowledgeService implements IKnowledgeService { } /** - * Each admitted source paired with the fingerprint its search carries - * ({@link planIndex}); a source whose adapter is not registered carries none - * (the round skips it, as before). + * Each admitted source paired with the adapter it binds to, resolved here + * once for the whole search, and the fingerprint its search carries + * ({@link planIndex}); a source whose adapter does not resolve carries the + * coded refusal instead and is refused by the round, never searched. + * + * A source admitted with `proveIndex` ({@link admitSources}) is searched + * only when its index is proven built under the current recipe + * ({@link unprovenIndex}); otherwise it is not searched and is added to + * `refused` as `KNOWLEDGE_REBUILD_REQUIRED` (409), the operator told why at + * `warn`. Each says whether a rebuild ends the refusal: for a source no + * build can prove, neither promises one. The boot's build pass, a reload, + * the reconcile and the operator's rebuild are what build a source; a + * search never starts a build. */ private async planSearches( - admitted: Array<{ source: KnowledgeSource; organizationIds?: string[]; scope?: AdapterScopeTerm[] }>, + admitted: Array, + refused: KnowledgeSearchRefusal[], ): Promise { const out: SearchTarget[] = []; // The settings page's chunk target, read at most once for the whole search. let target: Promise | undefined; const chunkTarget = (): Promise => (target ??= this.readChunkTarget()); - for (const entry of admitted) { - const adapterId = this.boundAdapterId(entry.source); - const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId); - if (!adapter) { - out.push(entry); + for (const { proveIndex, ...entry } of admitted) { + // The adapter is resolved here, once per search: the proof below is read + // from this instance and both rounds search this instance, so a source + // cannot change binding between the check and the use. + let adapterId: string; + let adapter: IKnowledgeAdapter; + try { + adapterId = this.adapterIdFor(entry.source); + adapter = this.getAdapter(adapterId); + } catch (err) { + // Refused like an adapter that cannot serve, as the round refuses it; a + // source that needs the index proof is never searched without it. + out.push({ ...entry, binding: { refusal: codedRefusalOf(err) } }); continue; } const plan = await this.planIndex(entry.source, adapter, chunkTarget); - out.push({ ...entry, fingerprint: plan.index.fingerprint }); + if (proveIndex === true) { + const unproven = await this.unprovenIndex(plan); + if (unproven !== undefined) { + const label = this.label(entry.source); + refused.push({ + sourceId: entry.source.name, + code: INDEX_NOT_PROVEN_CODE, + status: 409, + message: `Knowledge source '${label}' is not searched: its index is not proven built under the current recipe. ` + + UNPROVEN_CALLER_TEXT[unproven.ends], + }); + this.options.logger?.warn?.( + `[knowledge] source '${label}' not searched (${INDEX_NOT_PROVEN_CODE}): ${unproven.why} Its object declares ` + + "a field named 'title' the source does not serve, and a document indexed under the earlier title rule " + + "carries that field's value, so the source is searched only once its index is proven built under the " + + `current recipe. ${UNPROVEN_OPERATOR_TEXT[unproven.ends]}`, + ); + continue; + } + } + out.push({ + ...entry, + binding: { adapterId, adapter }, + fingerprint: plan.index.fingerprint, + ...(proveIndex === true ? { verifyHits: true as const } : {}), + }); } return out; } + /** + * Why `plan`'s source is not proven built under the current recipe, and + * what ends it, or `undefined` when it is proven: its adapter's + * `indexStatus` reports the fingerprint AND the recipe hash + * {@link planIndex} computes now, and the builds that record that hash + * purge what they did not walk. + * + * The recipe hash names the title rule (ADR-0161 K7), and an adapter + * records it only at `completeBuild`, the end of a complete build. A + * complete build rewrites every document whose title changed (`docHash` + * covers the title) and, when it purges, removes every document it did not + * walk. It does not purge, and still records the hash, for a source with + * `refresh.onRecordChange: false` and on an adapter with no + * `listDocuments` ({@link walkObjectSource}): a document it did not walk, + * such as one whose row left the source's `where`, keeps what it was + * assembled with. So those two shapes are never proven, before any read, + * whatever the hash reads; nor is an adapter with no `indexStatus` (nothing + * to read) or no `completeBuild` (nothing ever records a hash). + * + * The proof covers what the last complete build walked and purged. Read on + * every search that needs it, never cached: another node may rebuild, or + * drop, the index. Fails closed: a status that throws is not proven. + */ + private async unprovenIndex(plan: IndexPlan): Promise<{ why: string; ends: UnprovenEnd } | undefined> { + const { adapter, index, source } = plan; + if ((source.refresh?.onRecordChange ?? true) === false) { + return { + ends: 'never', + why: + 'refresh.onRecordChange is false, so an external indexer owns its index: a build of it purges nothing, ' + + 'so a recorded recipe hash does not prove the index holds no document assembled under an earlier recipe.', + }; + } + if (typeof adapter.indexStatus !== 'function') { + return { + ends: 'never', + why: `the adapter '${adapter.id}' reports no index status (no indexStatus), so what its index was built under cannot be read.`, + }; + } + if (typeof adapter.completeBuild !== 'function') { + return { + ends: 'never', + why: `the adapter '${adapter.id}' has no completeBuild, so no build records a recipe hash for its index.`, + }; + } + if (typeof adapter.listDocuments !== 'function') { + return { + ends: 'never', + why: + `the adapter '${adapter.id}' does not list its documents (no listDocuments), so a complete build cannot purge a ` + + 'document it did not walk, and a recorded recipe hash does not prove the index holds none assembled under an ' + + 'earlier recipe.', + }; + } + let held: AdapterIndexStatus; + try { + held = await adapter.indexStatus(plan.context('search')); + } catch (err) { + return { ends: 'unreadable', why: `the adapter's index status could not be read (${operatorText(err)}).` }; + } + if (held?.fingerprint !== index.fingerprint) { + return { ends: 'rebuild', why: 'the index holds no complete build under the current fingerprint.' }; + } + if (held.recipeHash !== index.recipeHash) { + return { + ends: 'rebuild', + why: held.recipeHash === undefined + ? 'the index records no recipe hash: no complete build of it has completed.' + : "the index was last completed under another recipe (the source's where, metadataFields, title rule or withheld fields).", + }; + } + return undefined; + } + /** * One round of {@link search}: ask each source's adapter for `ask(source)` * hits. Answers, per source that answered, the hits it serves and how many @@ -2211,21 +2458,17 @@ export class KnowledgeService implements IKnowledgeService { refused: KnowledgeSearchRefusal[], ): Promise> { const out = new Map(); - for (const { source, organizationIds, fingerprint, scope } of sources) { + for (const { source, organizationIds, fingerprint, scope, binding } of sources) { // Refused like an adapter that cannot serve: the caller is told which // source was not searched and why; the boot said so at `error` - // (`reportUnmountedAdapters`), so no line per search. A source that - // names no adapter is placed here, as everywhere (`adapterIdFor`). - let adapterId: string; - let adapter: IKnowledgeAdapter; - try { - adapterId = this.adapterIdFor(source); - adapter = this.getAdapter(adapterId); - } catch (err) { - const coded = codedRefusalOf(err); - if (coded !== undefined) refused.push({ sourceId: source.name, ...coded }); + // (`reportUnmountedAdapters`), so no line per search. The adapter was + // resolved once for the whole search ({@link planSearches}); a round + // searches that instance and never looks it up again. + if ('refusal' in binding) { + if (binding.refusal !== undefined) refused.push({ sourceId: source.name, ...binding.refusal }); continue; } + const { adapterId, adapter } = binding; try { const hits = await adapter.search(query, { source, @@ -2592,6 +2835,11 @@ export class KnowledgeService implements IKnowledgeService { * every source over that object, reported once at `error`. The objects' * admissions are asked concurrently. * + * An admitted source over which an index built under the earlier title + * rule could serve a field the gate does not ask about + * (`mayServeEarlierRuleTitle`) carries `proveIndex`: {@link planSearches} + * searches it only once its index is proven built under the current recipe. + * * Each admitted source carries the organizations its search hands the * adapter ({@link scopeByOrganization}, ADR-0161 K8, item 9). The system * context's bypass above covers that scope too: the system identity's @@ -2600,7 +2848,7 @@ export class KnowledgeService implements IKnowledgeService { private async admitSources( sources: KnowledgeSource[], ctx: ExecutionContext | undefined, - ): Promise> { + ): Promise { if (ctx?.isSystem) return sources.map((source) => ({ source })); const engine = this.options.dataEngine; if (!ctx || !engine) { @@ -2628,7 +2876,7 @@ export class KnowledgeService implements IKnowledgeService { }), ); } - const out: KnowledgeSource[] = []; + const out: AdmittedSource[] = []; for (const source of sources) { const objSource = source.source; const objectAdmission = await byObject.get(objSource.object); @@ -2637,7 +2885,10 @@ export class KnowledgeService implements IKnowledgeService { ? { admitted: false, reason: objectAdmission.refused, object: objSource.object } : admitSourceFields(objSource, objectAdmission); if (verdict.admitted) { - out.push(source); + // An index built under the earlier title rule could serve a field + // the gate no longer asks about: searched only once its index is + // proven built under the current recipe ({@link planSearches}). + out.push(mayServeEarlierRuleTitle(objSource, objectAdmission.schema) ? { source, proveIndex: true } : { source }); } else { this.options.logger?.debug?.( `[knowledge] source '${this.label(source)}' not searched for this caller: ${verdict.reason} ` + @@ -2822,9 +3073,9 @@ export class KnowledgeService implements IKnowledgeService { * reported at `error`, `warn` as the fallback. */ private async scopeByOrganization( - sources: KnowledgeSource[], + sources: AdmittedSource[], ctx: ExecutionContext, - ): Promise> { + ): Promise { if (sources.length === 0) return []; let posture: TenancyPosture | undefined; try { @@ -2837,9 +3088,9 @@ export class KnowledgeService implements IKnowledgeService { else this.options.logger?.warn?.(report); return []; } - return sources.map((source) => { - const organizationIds = searchOrganizationIds(ctx, posture, this.schemaFor(source.source.object)); - return organizationIds === undefined ? { source } : { source, organizationIds }; + return sources.map((entry) => { + const organizationIds = searchOrganizationIds(ctx, posture, this.schemaFor(entry.source.source.object)); + return organizationIds === undefined ? entry : { ...entry, organizationIds }; }); } @@ -2997,11 +3248,54 @@ export interface KnowledgeSearchReport { * One source a search round asks: its organizations scope, the fingerprint its * search carries, and the record scope's terms for it (ADR-0161 K8, item 17). */ +/** A source {@link KnowledgeService.admitSources} admitted for a caller. */ +interface AdmittedSource { + source: KnowledgeSource; + organizationIds?: string[]; + /** Searched only once its index is proven built under the current recipe (`mayServeEarlierRuleTitle`). */ + proveIndex?: true; +} + +/** What ends a refusal for want of a proof ({@link KnowledgeService.unprovenIndex}). */ +type UnprovenEnd = 'rebuild' | 'never' | 'unreadable'; + +/** The second sentence of the caller's refusal, by what ends it. */ +const UNPROVEN_CALLER_TEXT: Readonly> = { + rebuild: 'It answers again once a complete rebuild of the source has completed.', + never: 'No rebuild changes that for this source; an administrator can say why.', + unreadable: 'What its index holds could not be read; it is asked again on the next search.', +}; + +/** The last sentence of the operator's `warn` line, by what ends the refusal. */ +const UNPROVEN_OPERATOR_TEXT: Readonly> = { + rebuild: + 'The boot pass, a source reload or the reconcile builds it where they run; os knowledge rebuild builds it now.', + never: + 'No rebuild can prove it for this source as it is configured, so nothing is rebuilt for it; it stays refused to ' + + 'every caller but the system context.', + unreadable: 'It is asked again on the next search.', +}; + +/** + * The code of a source refused because its index is not proven built under + * the current recipe: the one a generation-keeping adapter answers for an + * index built under another fingerprint, as the remedy is the same rebuild. + */ +const INDEX_NOT_PROVEN_CODE = 'KNOWLEDGE_REBUILD_REQUIRED'; + interface SearchTarget { source: KnowledgeSource; + /** + * The adapter the source binds to, resolved once per search + * ({@link KnowledgeService.planSearches}), or the coded refusal its + * resolution answered (`undefined`: an uncoded failure, skipped unsearched). + */ + binding: { adapterId: string; adapter: IKnowledgeAdapter } | { refusal: Omit | undefined }; organizationIds?: string[]; fingerprint?: string; scope?: AdapterScopeTerm[]; + /** Each hit is checked against its live record before it is served ({@link KnowledgeService.dropUnverifiedHits}). */ + verifyHits?: true; } /** An ADR-0112 coded refusal's code, status and message, or `undefined` for any other thrown value. */ diff --git a/packages/services/service-knowledge/src/knowledge-source-admission.ts b/packages/services/service-knowledge/src/knowledge-source-admission.ts index 4d77a9ebb04..d006b781b23 100644 --- a/packages/services/service-knowledge/src/knowledge-source-admission.ts +++ b/packages/services/service-knowledge/src/knowledge-source-admission.ts @@ -34,11 +34,9 @@ * the stored-metadata family never) — the posture the MCP record tools take. * * Then, per source, the **field gate**: every field the source serves (each - * `content` member, each - * `metadataFields` member, the title field — `documentTitleField` — and, - * while the index may hold documents assembled under the earlier title rule, a - * declared `title`), less the credential-class and `internal` fields the index - * never carries, must be QUERYABLE by the caller. + * `content` member, each `metadataFields` member and the title field — + * `documentTitleField`), less the credential-class and `internal` fields the + * index never carries, must be QUERYABLE by the caller. * Queryable, not merely readable: a passage carries the value the index read * under a system context, unmasked, and the search matches on it — a field the * caller is served masked is readable and not queryable, exactly the fields @@ -48,6 +46,32 @@ * one unit), and searching it at all would make row presence an oracle on the * hidden value. * + * ## An index built under an earlier title rule + * + * A document indexed before the title became the display field carries the + * value of a field named `title`, which the field gate no longer asks about + * (it serves the display field, ADR-0161 K5). A complete build under the + * current recipe rewrites every such document it walks (its `docHash` covers + * the title), and removes the rest only when it purges: the recipe hash + * names the title rule (ADR-0161 K7) and was first recorded by code that + * already read the display field. So a source over which such a document + * could be served ({@link mayServeEarlierRuleTitle}) is searched only once + * its adapter's `indexStatus` reports the fingerprint and the recipe hash + * the service computes now, and only where the builds that record that hash + * purge: never for a source with `refresh.onRecordChange: false`, nor on an + * adapter with no `listDocuments`, no `completeBuild` or no `indexStatus` + * (`KnowledgeService.unprovenIndex`). Until then it is refused + * `KNOWLEDGE_REBUILD_REQUIRED` (`KnowledgeService.search`), never served + * through a gate that asks about `title`. + * + * The proof speaks for the index as its last complete build left it, not for + * a document left in place by that build's purge or written after it. So each + * hit of a proven source is also checked against its record as it reads now + * (`KnowledgeService.dropUnverifiedHits`): it is served only when the record + * still belongs to the source and the stored `docHash` is the one the current + * recipe assembles from it. A check that cannot be made drops the hit, and the + * check's read decides only whether a hit is served. + * * The fields the source's `where` reads ({@link selectingFieldsOf}) are judged * by the same rule, at save and at search: the source selects its records by * them, so they are part of what the source reads of the object. None is @@ -261,25 +285,37 @@ export function servedFieldsOf(objSource: ObjectKnowledgeSource, schema: unknown ...collectCredentialWriteResponseFields(schema), ...collectInternalWriteResponseFields(schema), ]); - const declared = declaredFields(schema); const served = new Set(); for (const field of objSource.content) served.add(field); for (const field of objSource.metadataFields ?? []) served.add(field); // `recordToDocument` serves the title field's value whatever the source names. const titleField = documentTitleField(schema); if (titleField !== undefined) served.add(titleField); - // A document indexed before the title became the display field carries the - // value of a field named `title`, and stays in the index until a complete - // reindex writes it again. So `title` stays a served field whenever the - // object declares one (or its fields cannot be enumerated), as it was. - // Retire this arm once the index is proven rebuilt under the display-field - // rule: the recipe hash that names the title rule (ADR-0161 K7) and the - // rebuild of a stale source. - if (!declared || declared.some(([name]) => name === 'title')) served.add('title'); for (const field of withheld) served.delete(field); return served; } +/** + * Whether an index of `objSource` built under the earlier title rule could + * serve a field the field gate does not ask about: the object declares a + * field named `title` (or its fields cannot be enumerated), the index may + * carry it (it is neither credential-class nor `internal`), and the source + * does not serve it ({@link servedFieldsOf}). A source for which this is + * `true` is searched for a caller only once its index is proven built under + * the current recipe; for any other source the earlier rule served nothing + * the gate does not ask about. + */ +export function mayServeEarlierRuleTitle(objSource: ObjectKnowledgeSource, schema: unknown): boolean { + const declared = declaredFields(schema); + if (declared && !declared.some(([name]) => name === 'title')) return false; + const withheld = new Set([ + ...collectCredentialWriteResponseFields(schema), + ...collectInternalWriteResponseFields(schema), + ]); + if (withheld.has('title')) return false; + return !servedFieldsOf(objSource, schema).has('title'); +} + /** Logical keys of the filter grammar: never field names. */ const WHERE_LOGICAL_KEYS: ReadonlySet = new Set(['$and', '$or', '$not']);