diff --git a/.changeset/36993-knowledge-search-refill-display-title.md b/.changeset/36993-knowledge-search-refill-display-title.md new file mode 100644 index 00000000000..1425a587a64 --- /dev/null +++ b/.changeset/36993-knowledge-search-refill-display-title.md @@ -0,0 +1,12 @@ +--- +'@objectstack/service-knowledge': patch +--- + +fix(service-knowledge): search refills after the permission filter, and a hit's title is the object's display field + +Clause-②: no +Metadata-protocol: none + +- **Search refills after the permission filter.** The permission re-check runs after ranking, so a caller who may read few of the matching rows used to get a short or empty answer. For a caller who is not the system identity, each `object` source is now asked for `topK × 5` hits; when the hits that survive the re-check name fewer than `topK` records (several passages of one record count once), each `object` source that answered as many as it was asked is asked once more, for `topK × 20` (the cap). At most two rounds; an adapter that answers fewer than it was asked is not asked again. A `file` / `http` source, and every source for the system identity, is asked for `topK` once. The answer is still at most `topK` hits; how many the re-check removed is logged at `debug`, never returned. +- **A hit's title is the object's display field** (ADR-0161 K5; ADR-0079 `resolveDisplayField`: `nameField`, else the derived title field), not a field that happens to be named `title`. A credential-class or `internal` display field, an empty value, or an object with no display field gives no title; a source over an object with no registered definition still reads `title`. The source admission's field gate asks about the same field: a source whose object's display field the caller may not query is not searched for that caller at all. A declared field named `title` still gates the source too, because documents indexed before this change carry its value until a complete reindex writes them again. +- The title enters `docHash`, so the next complete reindex rewrites the documents whose title changed. diff --git a/content/docs/ai/knowledge-rag.mdx b/content/docs/ai/knowledge-rag.mdx index 923a9c8324e..d8bdd2aa9ad 100644 --- a/content/docs/ai/knowledge-rag.mdx +++ b/content/docs/ai/knowledge-rag.mdx @@ -48,7 +48,13 @@ kernel.use(new KnowledgeMemoryPlugin()); Retrieval is a plain service call — no AI runtime required. Resolve the `knowledge` service and call `search`. Hits are re-checked against the caller's `ExecutionContext` (RLS), sorted by score, and capped at `topK` before they come -back. +back. Because the re-check runs after ranking, for a caller other than the +system identity the service asks each object source for more hits than `topK`, +and asks once more when too few records survive, so a caller who may read few of +the matching records still gets up to `topK` hits +([the protocol](/docs/protocol/knowledge) gives the factors and the cap). A +hit's `title` is the value of the object's display field (`nameField`, else the +derived title field). ```ts const knowledge = ctx.getService('knowledge'); diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 383e9144494..5fb41770505 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -189,7 +189,7 @@ One of the largest consumers of the flag; | 43 | Approval actor / submitter / pending-approver checks bypassed (9 sites) | plugin-approvals | Get: approve, reject, recall, reassign without being a pending approver or the submitter, and a decision or comment that attaches files the actor did not upload (every other caller attaches only files it uploaded, in the request's organization) | `isOverrideActor`, `resolveActor`, `sendBack`, `resubmit`, `reassign`, `remind`, `requestInfo`, `comment`, `assertAttachmentsUploadedByCaller` | | 44 | Attachment access hooks return early (insert + update + delete, the referenced-file check on insert + update, and the read AST) | service-storage | Lose: attachment visibility scoping | `installAttachmentAccessHooks`, `installAttachmentFileReferenceGate`, `installAttachmentReadVisibility` | | 45 | Comment access hooks return early (insert + update + delete, and the read AST), and so do the activity and audit-log read gates (their read AST), the activity field redaction and the audit-log field redaction (the rows a read serves), the activity summary's message code (the rows a read serves), and the query guard over both objects' value-bearing columns (the read AST) | plugin-audit | Get: the whole activity row and the whole `sys_audit_log` row, its before/after snapshots included, and the activity row's stored summary code (`metadata.summary_message`), on `find` / `findOne` — the audit writer, each read gate's bounded probe and the activity backfill — and a filter, sort or grouping by those columns. Lose: comment visibility scoping, the narrowing of `sys_activity` and of `sys_audit_log` to rows whose parent record the caller can read, the redaction of a parent field's value from an activity row's text and recorded change and from a ledger row's before/after snapshots, the withholding of an activity row recording an update whose every changed field the reader is withheld, of a fired milestone row whose watched fields it is not all served, and of an unstamped row (on `count` and `aggregate` too, so a total agrees with the rows), the removal of that summary code from the activity row's `metadata` (its params are field values), and the refusal of a query over those columns for a reader withheld a field of the objects it can reach, and the withholding of those columns from such a reader's server-chosen search set (#34700) | `installCommentAccessHooks`, `installCommentReadVisibility`, `installActivityReadVisibility`, `installAuditLogReadVisibility`, `installActivityFieldRedaction`, `installAuditLogFieldRedaction`, `installActivitySummaryLocale`, `installParentFieldQueryGuard`, `withheldSearchColumns` | -| 46 | Knowledge search returns hits unfiltered, and searches every source | service-knowledge | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched | `applyPermissionFilter`, `admitSources` | +| 46 | Knowledge search returns hits unfiltered, and searches every source | service-knowledge | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched | `applyPermissionFilter`, `admitSources`, `search` | | 47 | The inbound-mail read gates return early (the read AST) | service-mailbox | Get: every `sys_mail_message` and `sys_mail_association` row on `find` / `findOne` — the ingest writer and each gate's own pre-scan, which read the association and mailbox rows a decision needs. Lose: the narrowing of a message to callers who can read a record it is associated with or who own its mailbox (so the unassociated pool is restricted), and of an association to callers who can read the record it names (on `count` and `aggregate` too, so a total agrees with the rows) | `gateMiddleware` | | 47b | The inbound-mail ingest seam: `ingest` admits the system context ALONE, and `rematch` admits it without the organization, owner or `manage_mailboxes` check | service-mailbox | Get: a mail source hands a mailbox its messages, and server code re-matches any mailbox. Lose: nothing a user held — every other caller of `ingest` is refused (`PERMISSION_DENIED`), because an ingested message is shown on every record its correspondents' addresses match and a user who could hand the seam a message could write one in a correspondent's name; every other caller of `rematch` must be in the mailbox's organization and own the mailbox or hold `manage_mailboxes` | `ingest`, `authorizeRematch` | | 47c | The inbound-mail IMAP sync: `syncMailbox` and `syncAll` admit the system context ALONE | service-mailbox | Get: the sync job reads every mailbox row (its organization, address and IMAP cursor), writes the cursor back, and hands each fetched message to `ingest` under the system context. Lose: nothing a user held — every other caller is refused (`PERMISSION_DENIED`), because a sync stores a mailbox's mail and moves its cursor | `syncMailbox`, `syncAll` | @@ -703,6 +703,7 @@ and CI refuses one that differs from what the tree produces. | `packages/services/service-automation/src/runtime-identity.ts#stampSystemInsertOwner` | 1 | 60 | | `packages/services/service-knowledge/src/knowledge-service.ts#admitSources` | 1 | 46 | | `packages/services/service-knowledge/src/knowledge-service.ts#applyPermissionFilter` | 1 | 46 | +| `packages/services/service-knowledge/src/knowledge-service.ts#search` | 1 | 46 | | `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#authorizeRematch` | 1 | 47b | | `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#ingest` | 1 | 47b | | `packages/services/service-mailbox/src/mail-read-visibility.ts#gateMiddleware` | 1 | 47 | diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 74fd8327535..8a14abf46ca 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -183,6 +183,30 @@ caller's `ExecutionContext` and drops hits the user is not allowed to read. **A hit that the user could not have queried directly is never returned.** +The re-check runs after ranking, so the service asks for more than it +answers. For a caller who is not the system identity, each `object` +source is asked for `topK × 5` hits. When the hits that survive the +re-check name fewer than `topK` records (several passages of one record +count once), every `object` source that answered as many hits as it was +asked is asked once more, for `topK × 20`. That is the cap: a caller who may +read fewer than `topK` of the rows within the cap gets fewer than `topK` +hits. An +adapter that answers fewer than it was asked (one that caps `topK`) is not +asked again. A `file` or `http` source is asked for `topK` once, and so is +every source for the system identity. The answer is at most `topK` hits. +How many hits the re-check removed is logged at `debug`, never returned to +the caller. + +A hit's `title` is the value of the object's display field (ADR-0079 +`resolveDisplayField`: `nameField`, else the derived title field), set +when the document is built. It is empty when that field is a +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. + ### 3.3 `IKnowledgeService` (consumed by the ObjectOS AI runtime, REST, Console) ```ts @@ -379,8 +403,8 @@ hashes as before, and the reindex skips it as before. ### Source admission: exposure and field-level rules A passage is built at index time, under a system context, from every -`contentFields` member of its source, the record `title` and the source's -`metadataFields`. A row re-check alone would therefore serve a caller the text +`contentFields` member of its source, the object's display field (the +title) and the source's `metadataFields`. A row re-check alone would therefore serve a caller the text of a field a field-level rule hides from them. So before an `object` source is searched for a non-system caller, the service asks, once per object per search: @@ -394,7 +418,8 @@ searched for a non-system caller, the service asks, once per object per search: `enable.aiReadable: true` (the AI read tools' posture). - **Field-level rules** — every field the source serves (each `contentFields` member, `'*'` meaning every field the object declares except `id`; each `metadataFields` - member; `title`), less the credential-class and `internal: true` fields an + 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` service's `getQueryableFields`. Without that answer: its `getReadableFields` less every field declaring a `maskingRule`; with no `security` service at @@ -444,7 +469,8 @@ when the source has no `where`). the event's `after`, so a write result that omits a field (a projected result, a formula the write did not return) cannot leave the document short. The same field rules as a reindex apply: the fields the source lists - and the record `title`, never a credential-class or `internal` field. + and the object's display field as the title, never a credential-class or + `internal` field. - **No row comes back** — the row does not match (a draft, or a row that stopped matching), and its document is deleted. Deleting an absent document changes nothing. diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts index 485634c77e4..b9217afad82 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -1,6 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. -import { describe, it, expect, vi } from 'vitest'; +import { describe, it, expect, expectTypeOf, vi } from 'vitest'; import { LiteKernel, ObjectKernel } from '@objectstack/core'; import type { Plugin, PluginContext } from '@objectstack/core'; import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js'; @@ -9,6 +9,8 @@ import { KnowledgeService, LIST_DOCUMENTS_PAGE_SIZE, REINDEX_PAGE_SIZE, + SEARCH_FIRST_ROUND_FACTOR, + SEARCH_REFILL_FACTOR, computeDocHash, documentIdFor, recordToDocument, @@ -1466,3 +1468,215 @@ describe('KnowledgeService — an event sync whose tenancy posture cannot be rea expect(warn).toHaveBeenCalledWith(expect.stringContaining('tenancy store down')); }); }); + +// The permission re-check runs after ranking, so a caller who may read few of +// the matching rows must not be answered from what is left of `topK` ranked +// hits: object sources are over-asked, and refilled once when short. +describe('KnowledgeService — search refills after the permission filter', () => { + const MEMBER = { userId: 'u1', positions: ['member'], permissions: [], isSystem: false }; + const SYSTEM = { positions: [], permissions: [], isSystem: true }; + + /** `n` hits of one source, best first: rank i scores 1 - i/1000 and names `rec_i`. */ + function rankedHits(sourceId: string, n: number): KnowledgeHit[] { + return Array.from({ length: n }, (_, i) => ({ + chunkId: `${sourceId}-c${i}`, documentId: `${sourceId}:rec_${i}`, sourceId, + sourceRecordId: `rec_${i}`, score: 1 - i / 1000, snippet: `passage ${i}`, + })); + } + + /** An adapter that ranks like a real one: the best `min(topK, cap)` of `corpus` for the source asked. */ + function rankingAdapter(corpus: Record, cap = Infinity) { + const searchSpy = vi.fn(async (_q: string, opts: { source: KnowledgeSource; topK: number }) => + (corpus[opts.source.id] ?? []).slice(0, Math.min(opts.topK, cap))); + return { id: 'memory', upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search: searchSpy, searchSpy }; + } + + /** An engine whose re-check as a non-system caller admits only `readable` record ids. */ + function engineReading(readable: string[]) { + const find = vi.fn(async (_obj: string, q: { where?: { id?: { $in?: string[] } }; context?: { isSystem?: boolean } }) => + (q.where?.id?.$in ?? []).filter((id) => q.context?.isSystem || readable.includes(id)).map((id) => ({ id }))); + return { find } as unknown as IDataEngine & { find: typeof find }; + } + + function setup(corpus: Record, readable: string[], opts: { cap?: number; sources?: string[] } = {}) { + const adapter = rankingAdapter(corpus, opts.cap); + const engine = engineReading(readable); + const debug = vi.fn(); + const svc = new KnowledgeService({ dataEngine: engine, logger: { debug, warn: vi.fn(), error: vi.fn() } }); + svc.registerAdapter('memory', adapter); + for (const id of opts.sources ?? ['s1']) svc.registerSource(objectSource(id, 'task')); + const asked = () => adapter.searchSpy.mock.calls.map((c) => [(c[1] as { source: KnowledgeSource }).source.id, (c[1] as { topK: number }).topK]); + return { svc, adapter, engine, debug, asked }; + } + + it('the first round asks topK × 5 and the refill topK × 20', () => { + expect(SEARCH_FIRST_ROUND_FACTOR).toBe(5); + expect(SEARCH_REFILL_FACTOR).toBe(20); + }); + + it('100 matching hits, the caller may read 5 spread across them: all 5 are answered, best first', async () => { + const readable = ['rec_3', 'rec_30', 'rec_50', 'rec_70', 'rec_99']; + const { svc, asked } = setup({ s1: rankedHits('s1', 100) }, readable); + const out = await svc.search('q', { topK: 5, executionContext: MEMBER }); + expect(out.map((h) => h.sourceRecordId)).toEqual(readable); + // Round one: 25, one survivor; the source answered all 25, so one refill of 100. + expect(asked()).toEqual([['s1', 25], ['s1', 100]]); + }); + + it('a readable row beyond the refill cap is not reached: fewer than topK are answered', async () => { + const { svc, asked } = setup({ s1: rankedHits('s1', 150) }, ['rec_10', 'rec_120']); + const out = await svc.search('q', { topK: 5, executionContext: MEMBER }); + expect(out.map((h) => h.sourceRecordId)).toEqual(['rec_10']); + expect(asked()).toEqual([['s1', 25], ['s1', 100]]); // two rounds, never a third + }); + + it('enough survivors in round one: no refill', async () => { + const readable = Array.from({ length: 25 }, (_, i) => `rec_${i}`).filter((_, i) => i % 2 === 0); + const { svc, asked } = setup({ s1: rankedHits('s1', 100) }, readable); + const out = await svc.search('q', { topK: 5, executionContext: MEMBER }); + expect(out.map((h) => h.sourceRecordId)).toEqual(['rec_0', 'rec_2', 'rec_4', 'rec_6', 'rec_8']); + expect(asked()).toEqual([['s1', 25]]); + }); + + it('an adapter that caps topK answers fewer than asked, so it is not asked again', async () => { + const { svc, asked } = setup({ s1: rankedHits('s1', 100) }, ['rec_50'], { cap: 10 }); + expect(await svc.search('q', { topK: 5, executionContext: MEMBER })).toEqual([]); + expect(asked()).toEqual([['s1', 25]]); + }); + + it('several sources: only a source that answered all it was asked is refilled; the others keep round one', async () => { + const corpus = { s1: rankedHits('s1', 100), s2: rankedHits('s2', 3) }; + const { svc, asked } = setup(corpus, ['rec_1', 'rec_60'], { sources: ['s1', 's2'] }); + const out = await svc.search('q', { topK: 5, executionContext: MEMBER }); + // s1:rec_1 and s2:rec_1 score the same; their order between them is not pinned. + expect(out.map((h) => h.documentId).sort()).toEqual(['s1:rec_1', 's1:rec_60', 's2:rec_1']); + expect(out[2].documentId).toBe('s1:rec_60'); + expect(asked()).toEqual([['s1', 25], ['s2', 25], ['s1', 100]]); + }); + + it('the refill decision counts records, not passages: two passages of one record leave a slot another source can refill', async () => { + // topK 3. s2 answers two passages of one readable record; s1's readable + // rec_15 lies past its first round (15) and outranks both of them. + const s2: KnowledgeHit[] = [ + { chunkId: 's2-a', documentId: 's2:r', sourceId: 's2', sourceRecordId: 'r', score: 0.5, snippet: 'a' }, + { chunkId: 's2-b', documentId: 's2:r', sourceId: 's2', sourceRecordId: 'r', score: 0.49, snippet: 'b' }, + ]; + const { svc, asked } = setup({ s1: rankedHits('s1', 100), s2 }, ['rec_0', 'rec_15', 'r'], { sources: ['s1', 's2'] }); + const out = await svc.search('q', { topK: 3, executionContext: MEMBER }); + expect(out.map((h) => h.chunkId)).toEqual(['s1-c0', 's1-c15', 's2-a']); + expect(asked()).toEqual([['s1', 15], ['s2', 15], ['s1', 60]]); + }); + + it('a refill the adapter fails keeps the source\'s round-one survivors', async () => { + const { svc, adapter } = setup({ s1: rankedHits('s1', 100) }, ['rec_2']); + const first = adapter.searchSpy.getMockImplementation()!; + adapter.searchSpy.mockImplementationOnce(first).mockImplementationOnce(async () => { + throw new Error('store unavailable'); + }); + const out = await svc.search('q', { topK: 5, executionContext: MEMBER }); + expect(out.map((h) => h.sourceRecordId)).toEqual(['rec_2']); + expect(adapter.searchSpy).toHaveBeenCalledTimes(2); + }); + + it('the system identity: one round of topK, no refill, no re-check', async () => { + const { svc, asked, engine } = setup({ s1: rankedHits('s1', 100) }, []); + const out = await svc.search('q', { topK: 5, executionContext: SYSTEM }); + expect(out).toHaveLength(5); + expect(asked()).toEqual([['s1', 5]]); + expect(engine.find).not.toHaveBeenCalled(); + }); + + it('no context: object sources stay unsearched (fail closed), a file source is asked topK once', async () => { + const { svc, adapter } = setup({ s1: rankedHits('s1', 100), f1: rankedHits('f1', 100) }, []); + svc.registerSource({ id: 'f1', label: 'f1', adapter: 'memory', source: { kind: 'file', prefix: 'docs/' } }); + const out = await svc.search('q', { topK: 5 }); + expect(out.every((h) => h.sourceId === 'f1')).toBe(true); + expect(adapter.searchSpy.mock.calls.map((c) => [(c[1] as { source: KnowledgeSource }).source.id, (c[1] as { topK: number }).topK])) + .toEqual([['f1', 5]]); + }); + + it('a file source beside an object source is asked topK once; only the object source is refilled', async () => { + // The file source answers all 5 it is asked, but only 2 exist; the object source's rows are unreadable. + const { svc, asked } = setup({ s1: rankedHits('s1', 100), f1: rankedHits('f1', 2) }, []); + svc.registerSource({ id: 'f1', label: 'f1', adapter: 'memory', source: { kind: 'file', prefix: 'docs/' } }); + const out = await svc.search('q', { topK: 5, executionContext: MEMBER }); + expect(out.map((h) => h.sourceId)).toEqual(['f1', 'f1']); + expect(asked()).toEqual([['s1', 25], ['f1', 5], ['s1', 100]]); + }); + + it('the count the re-check removed goes to the debug log only; the answer and its type are unchanged', async () => { + const { svc, debug } = setup({ s1: rankedHits('s1', 100) }, ['rec_7']); + const out = await svc.search('q', { topK: 5, executionContext: MEMBER }); + expect(out).toEqual([rankedHits('s1', 100)[7]]); + expect(debug).toHaveBeenCalledWith(expect.stringContaining('removed 99 hit(s)')); + expectTypeOf(svc.search).returns.toEqualTypeOf>(); + }); +}); + +// ADR-0161 K5: the title a document carries is declared — the object's display +// field (ADR-0079 `resolveDisplayField`), never a field that happens to be +// named `title`. +describe('recordToDocument reads the title from the object\'s display field', () => { + const src: KnowledgeSource = { + id: 's1', label: 's1', adapter: 'memory', + source: { kind: 'object', object: 'invoice', contentFields: ['body'] } as ObjectKnowledgeSource, + }; + const title = (record: Record, schema?: unknown) => + recordToDocument(src, src.source as ObjectKnowledgeSource, { id: 'r1', body: 'B', ...record }, schema).title; + + it('an explicit nameField over a field not called title', () => { + const schema = { nameField: 'subject', fields: { subject: { type: 'text' }, title: { type: 'text' }, body: { type: 'textarea' } } }; + expect(title({ subject: 'Quarterly policy', title: 'ignored' }, schema)).toBe('Quarterly policy'); + }); + + it('a derived display field: `name` wins over `title`', () => { + const schema = { fields: { title: { type: 'text' }, name: { type: 'text' }, body: { type: 'textarea' } } }; + expect(title({ name: 'Acme', title: 'Mr' }, schema)).toBe('Acme'); + }); + + it('a formula name field (text result) and an autonumber name field', () => { + const formula = { nameField: 'label', fields: { label: { type: 'formula', returnType: 'text' }, body: { type: 'textarea' } } }; + expect(title({ label: 'INV — Acme' }, formula)).toBe('INV — Acme'); + const autonumber = { nameField: 'number', fields: { number: { type: 'autonumber' }, body: { type: 'textarea' } } }; + expect(title({ number: 'INV-0042' }, autonumber)).toBe('INV-0042'); + expect(title({ number: 42 }, autonumber)).toBe('42'); + }); + + it('a withheld name field (credential-class or internal) gives no title', () => { + const internal = { nameField: 'digest', fields: { digest: { type: 'text', internal: true }, body: { type: 'textarea' } } }; + expect(title({ digest: 'synthetic-internal-91c2' }, internal)).toBeUndefined(); + const secret = { nameField: 'token', fields: { token: { type: 'secret' }, body: { type: 'textarea' } } }; + expect(title({ token: 'synthetic-credential-5b1d' }, secret)).toBeUndefined(); + }); + + it('an empty value, a value that is not text or a number, or no resolvable field gives no title', () => { + const schema = { nameField: 'subject', fields: { subject: { type: 'text' }, body: { type: 'textarea' } } }; + expect(title({ subject: ' ' }, schema)).toBeUndefined(); + expect(title({ subject: { nested: true } }, schema)).toBeUndefined(); + expect(title({ title: 'not the display field' }, { fields: { amount: { type: 'number' }, body: { type: 'json' } } })).toBeUndefined(); + // A nameField the definition does not declare is no title source. + expect(title({ ghost: 'G' }, { nameField: 'ghost', fields: { body: { type: 'textarea' } } })).toBeUndefined(); + }); + + it('no object definition: a field named title, as before', () => { + expect(title({ title: 'Hello' })).toBe('Hello'); + expect(title({ name: 'Acme' })).toBeUndefined(); + }); + + it('the event sync and the reindex walk build the title from the engine\'s definition', async () => { + const schema = { name: 'invoice', nameField: 'subject', fields: { subject: { type: 'text' }, body: { type: 'textarea' } } }; + const row = { id: 'r1', subject: 'Travel policy', body: 'B' }; + const find = vi.fn(async (_obj: string, q: { where?: unknown }) => { + const w = q.where as { id?: unknown; $and?: unknown } | undefined; + return w === undefined || (w as { id?: unknown }).id === 'r1' ? [row] : []; + }); + const svc = new KnowledgeService({ dataEngine: { find, getSchema: () => schema } as unknown as IDataEngine }); + const adapter = makeAdapter('memory'); + svc.registerAdapter('memory', adapter); + svc.registerSource(src); + await svc.handleRecordUpsert('invoice', { id: 'r1' }); + await svc.reindexSource('s1'); + const titles = adapter.upsertSpy.mock.calls.flatMap((c) => (c[0] as KnowledgeDocument[]).map((d) => d.title)); + expect(titles).toEqual(['Travel policy', 'Travel policy']); + }); +}); 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 d5bfdbf10c9..ba2399712a8 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 @@ -377,3 +377,36 @@ describe('KnowledgeServicePlugin wires the field gate to the registered `securit expect(isServiceNotRegisteredError(new Error('boom'), 'security')).toBe(false); }); }); + +// The field gate asks about the field the title is read from — the object's +// display field (`documentTitleField`, ADR-0161 K5) — not a field named `title`. +describe('field gate — the title field is the object\'s display field', () => { + const ACCOUNT: ObjectDef = { + name: 'account', + fields: { id: { type: 'text' }, name: { type: 'text' }, title: { type: 'text' }, body: { type: 'textarea' } }, + }; + + it('refusal: a caller who may not query the display field gets no hit, even with `title` visible', async () => { + const hideName = makeSecurity(() => ['id', 'title', 'body']); + const { svc, searched } = setup({ objects: [ACCOUNT], sources: [objectSource('s', 'account', ['body'])], security: hideName }); + expect(await svc.search('q', { executionContext: MEMBER })).toEqual([]); + 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([]); + expect(searched()).toEqual([]); + }); + + 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 }); + expect(ids(await svc.search('q', { executionContext: MEMBER }))).toEqual(['s']); + }); +}); diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 6f1bfe1e476..3adbdfdd631 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -31,6 +31,7 @@ import { import { admitObject, admitSourceFields, + documentTitleField, type KnowledgeFieldSecurity, type KnowledgeSourceAdmission, type ObjectAdmission, @@ -518,12 +519,94 @@ export class KnowledgeService implements IKnowledgeService { // ── Permission-aware search ─────────────────────────────────────── + /** + * Search every source the caller is admitted to, re-check each object-source + * hit as the caller ({@link applyPermissionFilter}), and answer the best + * `topK` hits by score. + * + * ## The refill after the permission filter + * + * The re-check runs AFTER ranking, so a caller who may read few of the + * matching rows would be answered from what is left of `topK` ranked hits — + * the fewer rows a caller may read, the closer to empty. So when the re-check + * can remove hits (a caller who is not the system identity, with an engine to + * re-check with), each `object` source is asked for + * `topK × SEARCH_FIRST_ROUND_FACTOR` hits. When the survivors name fewer + * than `topK` records ({@link distinctRecords}: several passages of one + * record count once), + * the sources that answered as many hits as they were asked — the only ones + * that may hold more — are asked once more, for + * `topK × SEARCH_REFILL_FACTOR`; that round's hits replace the source's + * first-round hits (a source that fails it keeps them). At most two rounds, + * and each embeds the query once per source it asks. An adapter that caps + * `topK` below what it was asked answers fewer than asked, so it is never + * asked again. + * + * A `file` / `http` source is asked for `topK` once: the re-check never + * removes its hits. The system identity, and a caller the service cannot + * re-check (no context, no engine — object sources are then not searched at + * all), get one round of `topK`. + * + * The answer is at most `topK` hits (`KnowledgeSearchOptions.topK`), chunk- + * level as before. How many hits the re-check removed is logged at `debug`, + * never returned: the count is an oracle on rows the caller may not read. + */ async search(query: string, opts: KnowledgeSearchOptions = {}): Promise { const topK = opts.topK ?? this.defaultTopK; - const sources = await this.admitSources(this.resolveSearchTargets(opts.sourceIds), opts.executionContext); + const ctx = opts.executionContext; + const sources = await this.admitSources(this.resolveSearchTargets(opts.sourceIds), ctx); if (sources.length === 0) return []; - const rawHits: KnowledgeHit[] = []; + const filtered = ctx !== undefined && ctx.isSystem !== true && this.options.dataEngine !== undefined; + const firstAsk = (source: KnowledgeSource): number => + filtered && source.source.kind === 'object' ? topK * SEARCH_FIRST_ROUND_FACTOR : topK; + const first = await this.searchRound(query, sources, firstAsk, opts.filter); + const raw = [...first.values()].flatMap((answer) => answer.hits); + let kept = await this.applyPermissionFilter(raw, ctx); + let removed = raw.length - kept.length; + + if (filtered && distinctRecords(kept) < topK) { + const saturated = sources.filter(({ source }) => { + const answer = first.get(source.id); + return source.source.kind === 'object' && answer !== undefined && answer.answered >= firstAsk(source); + }); + if (saturated.length > 0) { + const refill = await this.searchRound(query, saturated, () => topK * SEARCH_REFILL_FACTOR, opts.filter); + // 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); + 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]; + removed += refilledHits.length - refilledKept.length - (firstRaw - firstKept); + } + } + + if (removed > 0) { + this.options.logger?.debug?.( + `[knowledge] the permission re-check removed ${removed} hit(s) this caller may not read; ` + + `${Math.min(kept.length, topK)} of topK=${topK} answered.`, + ); + } + kept.sort((a, b) => b.score - a.score); + return kept.slice(0, topK); + } + + /** + * 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 + * the adapter returned (`answered`, before a hit naming another source is + * dropped — what decides whether the adapter may hold more). A source whose + * adapter is unknown or throws is absent from the answer, logged. + */ + private async searchRound( + query: string, + sources: Array<{ source: KnowledgeSource; organizationIds?: string[] }>, + ask: (source: KnowledgeSource) => number, + filter: Record | undefined, + ): Promise> { + const out = new Map(); for (const { source, organizationIds } of sources) { const adapter = this.adapters.get(source.adapter); if (!adapter) { @@ -535,35 +618,31 @@ export class KnowledgeService implements IKnowledgeService { try { const hits = await adapter.search(query, { source, - topK, - filter: opts.filter, + topK: ask(source), + filter, ...(organizationIds === undefined ? {} : { organizationIds }), }); // A hit is served as the source it was searched for. One whose // `sourceId` names another source (an adapter answering from a store // two sources share) is dropped: that source's admission was never // asked for this hit, so serving it would skip the gates above. - let foreign = 0; - for (const hit of hits) { - if (hit.sourceId === source.id) rawHits.push(hit); - else foreign++; - } + const served: KnowledgeHit[] = []; + for (const hit of hits) if (hit.sourceId === source.id) served.push(hit); + const foreign = hits.length - served.length; if (foreign > 0) { this.options.logger?.warn?.( `[knowledge] adapter '${source.adapter}' answered ${foreign} hit(s) for source '${source.id}' that name ` + 'another source; dropped — a hit is served only as the source it was searched for.', ); } + out.set(source.id, { hits: served, answered: hits.length }); } catch (err) { this.options.logger?.error?.( `[knowledge] adapter '${source.adapter}' search failed for source '${source.id}': ${(err as Error).message}`, ); } } - - const filtered = await this.applyPermissionFilter(rawHits, opts.executionContext); - filtered.sort((a, b) => b.score - a.score); - return filtered.slice(0, topK); + return out; } // ── Sync entrypoints (called by the host plugin's event bridge) ─── @@ -1087,6 +1166,21 @@ async function rereadRow( */ export const LIST_DOCUMENTS_PAGE_SIZE = 500; +/** + * How many times `topK` a search asks each `object` source for in its first + * round, when the permission re-check can remove hits ({@link + * KnowledgeService.search}). + */ +export const SEARCH_FIRST_ROUND_FACTOR = 5; + +/** + * How many times `topK` the one refill round asks a source for, when the + * survivors of the re-check name fewer than `topK` records — the cap on what a + * search reads: a caller who may read fewer than `topK` of the rows within the + * cap gets fewer than `topK` hits. + */ +export const SEARCH_REFILL_FACTOR = 20; + /** What {@link listAdapterDocuments} learned: every listed id → its stored hash, or why there is no listing. */ type AdapterListing = | { ok: true; documents: Map } @@ -1268,6 +1362,41 @@ function isRecordId(value: unknown): value is string | number { return (typeof value === 'string' && value !== '') || (typeof value === 'number' && Number.isFinite(value)); } +/** + * A document's `title` (ADR-0161 K5): the value of the object's display field + * ({@link documentTitleField}), read from the record when it is non-empty text + * or a finite number. `undefined` when the field is withheld (credential-class + * or `internal`), empty, or not one of those values. Not + * `resolveRecordDisplayName`: its `Record #` floor is a UI label, not + * index content. + */ +function documentTitle( + record: Record, + schema: unknown, + withheld: ReadonlySet, +): string | undefined { + const field = documentTitleField(schema); + if (field === undefined || withheld.has(field)) return undefined; + const value = record[field]; + if (typeof value === 'string') return value.trim().length > 0 ? value : undefined; + if (typeof value === 'number' && Number.isFinite(value)) return String(value); + return undefined; +} + +/** + * How many records `hits` name — what {@link KnowledgeService.search} counts + * toward `topK` when it decides whether to refill: several passages of one + * record count once. An object-source hit is its source and record id; any + * other hit is its document. + */ +function distinctRecords(hits: KnowledgeHit[]): number { + const keys = new Set(); + for (const hit of hits) { + keys.add(hit.sourceRecordId !== undefined ? `record:${hit.sourceId}#${hit.sourceRecordId}` : `document:${hit.documentId}`); + } + return keys.size; +} + /** Deterministic document id derived from the source + record id. */ export function documentIdFor(sourceId: string, recordId: string): string { return `${sourceId}:${recordId}`; @@ -1287,6 +1416,9 @@ export function documentIdFor(sourceId: string, recordId: string): string { * content. Without a schema nothing is withheld here (the engine's event body * and read path still apply their own projection upstream). * + * The `title` is the value of the object's display field ({@link + * documentTitle}); with no schema, of a field named `title`. + * * `posture` (the deployment's effective tenancy posture) decides the * document's `organizationId` (ADR-0161 K8, item 9): the record's * `organization_id` under `group` and `isolated`, none under `single` or with @@ -1328,7 +1460,7 @@ export function recordToDocument( sourceId: source.id, sourceRecordId: recordId || undefined, content: contentParts.join('\n\n'), - title: typeof record.title === 'string' && !withheld.has('title') ? record.title : undefined, + title: documentTitle(record, schema, withheld), metadata, }; const organizationId = documentOrganizationId(record, posture); diff --git a/packages/services/service-knowledge/src/knowledge-source-admission.ts b/packages/services/service-knowledge/src/knowledge-source-admission.ts index 68fb890e4fd..7eb7a9a24fe 100644 --- a/packages/services/service-knowledge/src/knowledge-source-admission.ts +++ b/packages/services/service-knowledge/src/knowledge-source-admission.ts @@ -8,8 +8,8 @@ * ## Why the knowledge service owes them * * A knowledge passage is built at index time, under a system context, from - * every `contentFields` member of its source (plus the record `title` and the - * source's `metadataFields`). The row re-check in `applyPermissionFilter` asks + * every `contentFields` member of its source (plus the object's display field + * as the title, and the source's `metadataFields`). The row re-check in `applyPermissionFilter` asks * only "may this caller read the row?". Every other door that serves object * rows outside the data routes also asks the spec's one exposure decision * (`canServeApiOperation`, ADR-0049) and the caller's field-level read rules — @@ -35,8 +35,10 @@ * * Then, per source, the **field gate**: every field the source serves (each * `contentFields` member — `'*'` meaning every field the object declares — each - * `metadataFields` member, and `title`), less the credential-class and - * `internal` fields the index never carries, must be QUERYABLE by the caller. + * `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. * 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 @@ -66,7 +68,13 @@ * one), as it bypasses the row re-check. */ -import { canServeApiOperation, isAiReadExposed, type EnableLike } from '@objectstack/spec/data'; +import { + canServeApiOperation, + isAiReadExposed, + resolveDisplayField, + type EnableLike, + type TitleEligibleFieldDef, +} from '@objectstack/spec/data'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { ObjectKnowledgeSource } from '@objectstack/spec/ai'; import { @@ -139,6 +147,40 @@ export function declaredFields(schema: unknown): Array<[string, unknown]> | unde return undefined; } +/** + * The field a knowledge document's `title` is read from (ADR-0161 K5: the + * title is the object's display field) — one answer for assembly + * (`recordToDocument`) and for the field gate ({@link servedFieldsOf}), so a + * caller is never served a title from a field the gate did not ask about. + * + * - **An object definition**: its display field, `resolveDisplayField` + * (ADR-0079: `nameField`, its deprecated alias `displayNameField`, else the + * derivation). A resolved field the definition does not declare, when it + * declares its fields, gives no title; so does a definition that resolves + * none. + * - **No object definition**: a field named `title`, as assembly read it + * before it asked the definition. + */ +export function documentTitleField(schema: unknown): string | undefined { + if (schema === undefined || schema === null || typeof schema !== 'object') return 'title'; + const meta = schema as { nameField?: unknown; displayNameField?: unknown }; + const declared = declaredFields(schema); + const field = resolveDisplayField({ + nameField: typeof meta.nameField === 'string' && meta.nameField.length > 0 ? meta.nameField : undefined, + displayNameField: + typeof meta.displayNameField === 'string' && meta.displayNameField.length > 0 ? meta.displayNameField : undefined, + fields: declared + ? (Object.fromEntries(declared.map(([name, def]) => [name, (def ?? {}) as TitleEligibleFieldDef])) as Record< + string, + TitleEligibleFieldDef + >) + : undefined, + }); + if (field === undefined) return undefined; + if (declared && !declared.some(([name]) => name === field)) return undefined; + return field; +} + /** Every field the object declares with a `maskingRule`. */ function maskingRuleFields(schema: unknown): Set { const out = new Set(); @@ -217,8 +259,16 @@ export function servedFieldsOf(objSource: ObjectKnowledgeSource, schema: unknown } } for (const field of objSource.metadataFields ?? []) served.add(field); - // `recordToDocument` serves the record's `title` whatever the source names. - // Required unless the object is known not to declare one. + // `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;