From 4def05e8bd1cfb0c7527c266297742ceedffddde Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 01:51:57 +0000 Subject: [PATCH 1/4] feat(service-knowledge): a narrow caller's search ranks only the records they may read Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../plugins/knowledge-pgvector/src/sql.ts | 3 + packages/plugins/knowledge-turso/src/sql.ts | 3 + .../src/knowledge-search-scope.ts | 40 ++++++ .../src/knowledge-service.ts | 123 +++++++++++++++++- 4 files changed, 167 insertions(+), 2 deletions(-) diff --git a/packages/plugins/knowledge-pgvector/src/sql.ts b/packages/plugins/knowledge-pgvector/src/sql.ts index 5dd6d58ba33..903a78a8ddc 100644 --- a/packages/plugins/knowledge-pgvector/src/sql.ts +++ b/packages/plugins/knowledge-pgvector/src/sql.ts @@ -90,6 +90,9 @@ export function vectorTableDdl(schema: string, dimensions: number, vectorType: s PRIMARY KEY (source_id, generation, chunk_id) )`, `CREATE INDEX IF NOT EXISTS "${table}_document" ON ${qualified(schema, table)} (source_id, generation, document_id)`, + // A search narrowed to the records its caller may read (a `record` scope + // term) reads only those records' passages of the generation. + `CREATE INDEX IF NOT EXISTS "${table}_record" ON ${qualified(schema, table)} (source_id, generation, source_record_id)`, keywordIndexDdl(schema, dimensions), ]; } diff --git a/packages/plugins/knowledge-turso/src/sql.ts b/packages/plugins/knowledge-turso/src/sql.ts index fd3f5c345fb..86c5d9c604d 100644 --- a/packages/plugins/knowledge-turso/src/sql.ts +++ b/packages/plugins/knowledge-turso/src/sql.ts @@ -148,6 +148,9 @@ export function passageTableDdl(table: string, dimensions: number): string[] { embedding F32_BLOB(${dimensions}) NOT NULL )`, `CREATE INDEX ${quoted(`${table}_document`)} ON ${quoted(table)} (document_id)`, + // A search narrowed to the records its caller may read (a `record` scope + // term) reads only those records' passages, never the whole table. + `CREATE INDEX ${quoted(`${table}_record`)} ON ${quoted(table)} (source_record_id)`, ...keywordIndexDdl(table), ]; } diff --git a/packages/services/service-knowledge/src/knowledge-search-scope.ts b/packages/services/service-knowledge/src/knowledge-search-scope.ts index 3de3422314d..533b355a80e 100644 --- a/packages/services/service-knowledge/src/knowledge-search-scope.ts +++ b/packages/services/service-knowledge/src/knowledge-search-scope.ts @@ -163,6 +163,46 @@ function parentLinksOf(objSource: ObjectKnowledgeSource, schema: unknown): Map term.kind !== 'record')) return undefined; + const readable = new Set(visible); + const ids = new Set(); + for (const term of terms) for (const id of term.ids) if (readable.has(id)) ids.add(id); + return [{ kind: 'record', ids: [...ids] }]; +} + /** * The check every hit passes after its adapter answers, whatever the adapter * did: `true` when some term holds for the hit, judged on the hit's diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index 1da51f71bb3..e9e6c757e86 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -53,7 +53,14 @@ import { type KnowledgeSourceAdmission, type ObjectAdmission, } from './knowledge-source-admission.js'; -import { readSearchScope, scopeCheck, scopeTermsFor, type SearchScopeEntry } from './knowledge-search-scope.js'; +import { + narrowToVisible, + readSearchScope, + scopeCheck, + scopeTermsFor, + SEARCH_VISIBLE_IDS_MAX, + type SearchScopeEntry, +} from './knowledge-search-scope.js'; import { BUILD_LEASE_MS, BUILD_PROGRESS_LOG_INTERVAL_MS, @@ -1809,6 +1816,18 @@ export class KnowledgeService implements IKnowledgeService { * The system identity gets one round of `topK`. A caller the service cannot * re-check (no context, no engine) is served no source at all. * + * ## Ranking only what the caller may read + * + * The refill is a cap: a caller whose readable rows all rank below + * `topK × SEARCH_REFILL_FACTOR` would get none of them. So before the first + * round, each source of a caller who is re-checked is narrowed to the records + * that caller may read ({@link sourcesNarrowedToVisible}): when they number + * no more than `SEARCH_VISIBLE_IDS_MAX`, their ids become the source's + * `record` term — intersected with the caller's own scope, never added to + * it — and the adapter ranks only those rows. More than that, a parent term + * in the caller's scope, or a read that fails, and the source is searched as + * above. The rounds, the refill and the re-check are the same either way. + * * ## Records, not chunks (`granularity: 'record'`, `groupBy`) * * Several passages of one record would fill `topK` with one record, so @@ -1906,6 +1925,11 @@ export class KnowledgeService implements IKnowledgeService { await this.admitSources(this.resolveSearchTargets(opts.sourceIds), ctx); if (scope !== undefined) admitted = this.sourcesInScope(admitted, scope); if (groupBy !== undefined) admitted = this.sourcesGroupableBy(admitted, groupBy); + const engine = this.options.dataEngine; + const filtered = ctx !== undefined && ctx.isSystem !== true && engine !== undefined; + // A caller the re-check can remove hits for: each source ranks only the + // records they may read, when those are few enough to name. + if (filtered && admitted.length > 0) admitted = await this.sourcesNarrowedToVisible(admitted, ctx, engine); if (admitted.length === 0) return { hits: [], refused: [] }; const refused: KnowledgeSearchRefusal[] = []; const sources = await this.planSearches(admitted, refused); @@ -1915,7 +1939,6 @@ export class KnowledgeService implements IKnowledgeService { 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; const firstAsk = (_source: KnowledgeSource): number => widened ? topK * SEARCH_FIRST_ROUND_FACTOR : topK; @@ -2575,6 +2598,102 @@ export class KnowledgeService implements IKnowledgeService { return out; } + /** + * Narrow each source's search to the records a non-system caller may read + * ({@link narrowToVisible}). Per source, the ids of the records it indexes + * that the caller may read are read first — as the caller, under the + * source's `where`, ids only, at most {@link SEARCH_VISIBLE_IDS_MAX} + 1 — + * once per object and `where` the search asks. When the caller may read no + * more than {@link SEARCH_VISIBLE_IDS_MAX}, the source is handed them as a + * `record` term, intersected with the caller's own scope, so its adapter + * ranks only those rows and a narrow caller's answers are not crowded out of + * the refill cap by rows they could never be served. A source whose narrowed + * term holds no id is not searched: the caller may read none of what it + * could answer. + * + * A source is searched as before — on the caller's own scope, its hits + * re-checked within the refill cap — when the caller may read more than + * that, when the caller's scope holds a parent (`metadata`) term, or when the + * read fails (logged at `warn`). Nothing here decides access: every hit is + * still re-checked as the caller ({@link applyPermissionFilter}), and the + * organization filter each source carries is not touched. + */ + private async sourcesNarrowedToVisible( + sources: T[], + ctx: ExecutionContext, + engine: IDataEngine, + ): Promise { + const reads = new Map>(); + const visibleOf = (objSource: ObjectKnowledgeSource): Promise => { + const key = JSON.stringify([objSource.object, objSource.where ?? null]); + let read = reads.get(key); + if (read === undefined) { + read = this.readVisibleIds(objSource, ctx, engine); + reads.set(key, read); + } + return read; + }; + const visible = sources.map((entry) => + entry.scope?.some((term) => term.kind !== 'record') === true + ? Promise.resolve(undefined) + : visibleOf(entry.source.source)); + const out: T[] = []; + for (const [i, entry] of sources.entries()) { + const ids = await visible[i]; + const narrowed = ids === undefined ? undefined : narrowToVisible(entry.scope, ids); + if (narrowed === undefined) { + out.push(entry); + continue; + } + if (narrowed.every((term) => term.ids.length === 0)) { + this.options.logger?.debug?.( + `[knowledge] source '${this.label(entry.source)}' not searched: the caller may read none of the records it could answer.`, + ); + continue; + } + out.push({ ...entry, scope: narrowed }); + } + return out; + } + + /** + * The ids of the records of `objSource` the caller may read, read as the + * caller under the source's `where`; `undefined` when there are more than + * {@link SEARCH_VISIBLE_IDS_MAX} or the read fails. + */ + private async readVisibleIds( + objSource: ObjectKnowledgeSource, + ctx: ExecutionContext, + engine: IDataEngine, + ): Promise { + let rows: unknown; + try { + rows = await engine.find( + objSource.object, + { + ...(objSource.where === undefined ? {} : { where: objSource.where }), + fields: ['id'], + limit: SEARCH_VISIBLE_IDS_MAX + 1, + }, + { context: ctx }, + ); + 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 caller's readable records of object='${objSource.object}' could not be read ` + + `(${errorText(err)}); its sources are searched unnarrowed, every hit re-checked.`, + ); + return undefined; + } + if (rows.length > SEARCH_VISIBLE_IDS_MAX) return undefined; + const ids: string[] = []; + for (const row of rows as Array<{ id?: unknown } | null | undefined>) { + const id = row?.id; + if ((typeof id === 'string' && id.length > 0) || typeof id === 'number') ids.push(String(id)); + } + return ids; + } + /** * The hits of `source` that some scope term holds for ({@link scopeCheck}); * the rest are dropped, and the first time an adapter's answer loses a hit From 70305ba38f1724883a76d03df1587ada3a1ff4a8 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 02:23:52 +0000 Subject: [PATCH 2/4] test(service-knowledge): pin the narrowed search and the intersection with the caller scope Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../__tests__/knowledge-search-scope.test.ts | 35 ++++ .../src/__tests__/knowledge-service.test.ts | 189 +++++++++++++++++- .../src/__tests__/knowledge-tools.test.ts | 3 +- .../src/knowledge-search-scope.ts | 2 +- .../src/knowledge-service.ts | 37 ++-- .../services/service-knowledge/src/testing.ts | 12 +- 6 files changed, 247 insertions(+), 31 deletions(-) diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts index 66884553136..1b27a6c8b84 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-search-scope.test.ts @@ -9,6 +9,8 @@ import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@obje import { SEARCH_SCOPE_MAX_ENTRIES, SEARCH_SCOPE_MAX_IDS, + SEARCH_VISIBLE_IDS_MAX, + narrowToVisible, readSearchScope, scopeCheck, scopeTermsFor, @@ -223,3 +225,36 @@ describe('scopeCheck — every hit, after the adapter answers', () => { expect(scopeCheck([])(hit('c1', { policy: 'p1' }))).toBe(false); }); }); + +describe('narrowToVisible: the visible ids intersect the caller\'s scope, never widen it', () => { + it('the bound is the scope entry\'s: 500', () => { + expect(SEARCH_VISIBLE_IDS_MAX).toBe(500); + }); + + it('no caller scope: one record term holding the visible ids, once each', () => { + expect(narrowToVisible(undefined, ['a', 'b', 'a'])).toEqual([{ kind: 'record', ids: ['a', 'b'] }]); + }); + + it('record terms: their ids that are visible, in the caller\'s order, once each — one term', () => { + const terms = [{ kind: 'record' as const, ids: ['c', 'x', 'a'] }, { kind: 'record' as const, ids: ['a', 'y', 'b'] }]; + expect(narrowToVisible(terms, ['a', 'b', 'c', 'd'])).toEqual([{ kind: 'record', ids: ['c', 'a', 'b'] }]); + }); + + it('a one-record scope stays one record however many ids are visible', () => { + expect(narrowToVisible([{ kind: 'record', ids: ['a'] }], ['a', 'b', 'c'])).toEqual([{ kind: 'record', ids: ['a'] }]); + }); + + it('nothing visible in scope: a term with no ids', () => { + expect(narrowToVisible([{ kind: 'record', ids: ['x'] }], ['a'])).toEqual([{ kind: 'record', ids: [] }]); + }); + + it('a metadata (parent) term: not narrowed', () => { + expect(narrowToVisible([{ kind: 'record', ids: ['a'] }, { kind: 'metadata', field: 'policy', ids: ['p1'] }], ['a'])).toBeUndefined(); + }); + + it('the caller\'s terms are not mutated', () => { + const terms = [{ kind: 'record' as const, ids: ['a', 'x'] }]; + narrowToVisible(terms, ['a']); + expect(terms).toEqual([{ kind: 'record', ids: ['a', 'x'] }]); + }); +}); 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 c1a0c5a8c60..809ebfd18e6 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts @@ -134,11 +134,15 @@ describe('KnowledgeService — permission-aware search', () => { executionContext: { userId: 'u1', positions: ['member'], permissions: [], isSystem: false }, }); expect(out.map((h) => h.documentId)).toEqual(['d1']); - expect(findSpy).toHaveBeenCalledOnce(); - const [obj, opts] = findSpy.mock.calls[0]; - expect(obj).toBe('task'); - expect(opts.context.isSystem).toBe(false); - expect(opts.where).toEqual({ id: { $in: ['rec_1', 'rec_2'] } }); + // Two reads, both as the caller: the records they may read (which narrows + // the search to rec_1), then the re-check of the hits that search answered. + expect(findSpy).toHaveBeenCalledTimes(2); + for (const [obj, opts] of findSpy.mock.calls) { + expect(obj).toBe('task'); + expect(opts.context.isSystem).toBe(false); + } + expect(findSpy.mock.calls[0][1]).toEqual({ fields: ['id'], limit: 501, context: expect.objectContaining({ userId: 'u1' }) }); + expect(findSpy.mock.calls[1][1].where).toEqual({ id: { $in: ['rec_1'] } }); }); it('topK honoured + hits sorted by score desc', async () => { @@ -1800,6 +1804,175 @@ describe('KnowledgeService — search scope (ADR-0161 K8, item 17)', () => { }); }); +describe('KnowledgeService — a narrow caller\'s search ranks only the records they may read', () => { + const MEMBER = { userId: 'u1', tenantId: 'org_a', accessible_org_ids: ['org_a'], positions: ['member'], permissions: [], isSystem: false }; + const SYSTEM = { positions: [], permissions: [], isSystem: true }; + type Term = { kind: 'record'; ids: string[] } | { kind: 'metadata'; field: string; ids: string[] }; + type Query = { where?: Record; fields?: string[]; limit?: number; context?: { isSystem?: boolean } }; + + /** 1,000 records of `task`, one passage each: `rec_i` ranks i-th, in policy `p${i % 4}`. */ + const corpus: KnowledgeHit[] = Array.from({ length: 1000 }, (_, i) => ({ + chunkId: `s1:rec_${i}#0`, documentId: `s1:rec_${i}`, sourceId: 's1', sourceRecordId: `rec_${i}`, + score: 1 - i / 10_000, snippet: `passage ${i}`, metadata: { status: 'open', policy: `p${i % 4}` }, + })); + /** The 20 records the member may read: they rank 900th to 919th, far below 20 × topK. */ + const READABLE = Array.from({ length: 20 }, (_, i) => `rec_${900 + i}`); + + /** An adapter that ranks like a real one: the terms it is handed are a union, applied before `topK`. */ + function rankingAdapter() { + const holds = (hit: KnowledgeHit, scope: Term[]): boolean => + scope.some((t) => (t.kind === 'record' ? t.ids.includes(String(hit.sourceRecordId)) : t.ids.includes(String(hit.metadata?.[t.field])))); + const searchSpy = vi.fn(async (_q: string, opts: { topK: number; scope?: Term[] }) => + (opts.scope === undefined ? corpus : corpus.filter((h) => holds(h, opts.scope!))).slice(0, opts.topK)); + return { id: 'memory', upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search: searchSpy, searchSpy }; + } + + /** + * An engine whose caller reads admit only `readable`: the re-check (`id: { $in }`) and the read of the + * records the caller may read (ids, at most `limit`). `visible` overrides what that second read answers. + */ + function engineReading(readable: string[], visible?: (q: Query) => Array<{ id: string }>) { + const find = vi.fn(async (_obj: string, q: Query) => { + const inIds = (q.where?.id as { $in?: string[] } | undefined)?.$in; + if (inIds !== undefined) return inIds.filter((id) => q.context?.isSystem || readable.includes(id)).map((id) => ({ id })); + if (visible !== undefined) return visible(q); + return readable.slice(0, q.limit).map((id) => ({ id })); + }); + return { find, getSchema: () => undefined } as unknown as IDataEngine & { find: typeof find }; + } + + function setup(opts: { + readable?: string[]; + visible?: (q: Query) => Array<{ id: string }>; + sources?: KnowledgeSource[]; + posture?: 'isolated'; + } = {}) { + const adapter = rankingAdapter(); + const engine = engineReading(opts.readable ?? READABLE, opts.visible); + const warn = vi.fn(); + const svc = new KnowledgeService({ + dataEngine: engine, + logger: { warn, debug: vi.fn(), error: vi.fn() }, + ...(opts.posture === undefined ? {} : { resolveTenancyPosture: async () => opts.posture }), + }); + svc.registerAdapter('memory', adapter); + for (const s of opts.sources ?? [objectSource('s1', 'task')]) svc.registerSource(s); + const handed = () => adapter.searchSpy.mock.calls.map((c) => c[1] as { topK: number; scope?: Term[]; organizationIds?: string[] }); + const visibleReads = () => engine.find.mock.calls.filter(([, q]) => (q.where?.id as { $in?: unknown } | undefined)?.$in === undefined); + return { svc, adapter, engine, warn, handed, visibleReads }; + } + + const recordsOf = (hits: KnowledgeHit[]) => hits.map((h) => h.sourceRecordId); + + it('a caller who may read 20 of 1,000 records is answered from their 20, though all rank below topK × 20', async () => { + const { svc, handed, visibleReads } = setup(); + const out = await svc.search('q', { topK: 5, executionContext: MEMBER }); + expect(recordsOf(out)).toEqual(['rec_900', 'rec_901', 'rec_902', 'rec_903', 'rec_904']); + // The read: as the caller, ids only, one more than the bound. + expect(visibleReads()).toHaveLength(1); + expect(visibleReads()[0][1]).toEqual({ fields: ['id'], limit: 501, context: MEMBER }); + // One round: the adapter ranked only the 20, so every hit survived the re-check. + expect(handed()).toEqual([expect.objectContaining({ topK: 25, scope: [{ kind: 'record', ids: READABLE }] })]); + }); + + it('control: a caller who may read more than 500 records takes the path before — the 20 are not reached', async () => { + const many = (q: Query) => Array.from({ length: q.limit ?? 0 }, (_, i) => ({ id: `other_${i}` })); + const { svc, handed } = setup({ visible: many }); + expect(await svc.search('q', { topK: 5, executionContext: MEMBER })).toEqual([]); + expect(handed().map((o) => o.scope)).toEqual([undefined, undefined]); + expect(handed().map((o) => o.topK)).toEqual([25, 100]); + }); + + it('exactly 500 readable records still narrow; 501 do not', async () => { + const ids = (n: number) => Array.from({ length: n }, (_, i) => `rec_${999 - i}`); + const at500 = setup({ readable: ids(500) }); + await at500.svc.search('q', { topK: 5, executionContext: MEMBER }); + expect(at500.handed()[0].scope).toEqual([{ kind: 'record', ids: ids(500) }]); + const at501 = setup({ readable: ids(501) }); + await at501.svc.search('q', { topK: 5, executionContext: MEMBER }); + expect(at501.handed()[0].scope).toBeUndefined(); + }); + + it('a caller\'s one-record scope stays one record: the visible ids are intersected with it, never added to it', async () => { + const { svc, handed } = setup(); + const out = await svc.search('q', { topK: 5, scope: [{ object: 'task', ids: ['rec_905'] }], executionContext: MEMBER }); + expect(recordsOf(out)).toEqual(['rec_905']); + expect(handed().map((o) => o.scope)).toEqual([[{ kind: 'record', ids: ['rec_905'] }]]); + }); + + it('a caller scope naming readable and unreadable records: only the readable ones, in the caller\'s order', async () => { + const { svc, handed } = setup(); + const scope = [{ object: 'task', ids: ['rec_910', 'rec_3', 'rec_902'] }, { object: 'task', ids: ['rec_902', 'rec_7'] }]; + const out = await svc.search('q', { topK: 5, scope, executionContext: MEMBER }); + expect(recordsOf(out)).toEqual(['rec_902', 'rec_910']); + expect(handed()[0].scope).toEqual([{ kind: 'record', ids: ['rec_910', 'rec_902'] }]); + }); + + it('a caller scope naming no readable record is searched on the caller\'s terms, as before, and answers nothing', async () => { + const { svc, handed } = setup(); + expect(await svc.search('q', { topK: 5, scope: [{ object: 'task', ids: ['rec_3'] }], executionContext: MEMBER })).toEqual([]); + expect(handed()[0].scope).toEqual([{ kind: 'record', ids: ['rec_3'] }]); + }); + + it('a caller who may read no record of the source is searched as before', async () => { + const { svc, handed } = setup({ readable: [] }); + expect(await svc.search('q', { topK: 5, executionContext: MEMBER })).toEqual([]); + expect(handed().map((o) => o.scope)).toEqual([undefined, undefined]); + }); + + it('a parent (metadata) term in the caller\'s scope: no read, and the caller\'s terms are handed unchanged', async () => { + const source: KnowledgeSource = { ...objectSource('s1', 'task'), source: { ...objectSource('s1', 'task').source, metadataFields: ['status', 'policy'] } as ObjectKnowledgeSource }; + const { svc, engine, handed, visibleReads } = setup({ sources: [source] }); + (engine as unknown as { getSchema: () => unknown }).getSchema = () => ({ + name: 'task', fields: { title: { type: 'text' }, notes: { type: 'textarea' }, status: { type: 'select' }, policy: { type: 'lookup', reference: 'policy' } }, + }); + await svc.search('q', { topK: 5, scope: [{ object: 'policy', ids: ['p0'] }], executionContext: MEMBER }); + expect(visibleReads()).toEqual([]); + for (const o of handed()) expect(o.scope).toEqual([{ kind: 'metadata', field: 'policy', ids: ['p0'] }]); + }); + + it('the system identity: no read, no scope handed, one round of topK', async () => { + const { svc, engine, handed } = setup(); + expect(await svc.search('q', { topK: 5, executionContext: SYSTEM })).toHaveLength(5); + expect(engine.find).not.toHaveBeenCalled(); + expect(handed()).toEqual([expect.not.objectContaining({ scope: expect.anything() })]); + expect(handed()[0].topK).toBe(5); + }); + + it('the organization filter is handed as before beside the narrowed term', async () => { + const narrowed = setup({ posture: 'isolated' }); + await narrowed.svc.search('q', { topK: 5, executionContext: MEMBER }); + const wide = setup({ posture: 'isolated', visible: (q) => Array.from({ length: q.limit ?? 0 }, (_, i) => ({ id: `o${i}` })) }); + await wide.svc.search('q', { topK: 5, executionContext: MEMBER }); + expect(narrowed.handed()[0].organizationIds).toEqual(['org_a']); + expect(narrowed.handed()[0].organizationIds).toEqual(wide.handed()[0].organizationIds); + expect(narrowed.handed()[0].scope).toEqual([{ kind: 'record', ids: READABLE }]); + }); + + it('the source\'s where is the read\'s where, and two sources over one object and where share one read', async () => { + const where = { status: 'open' }; + const over = (id: string): KnowledgeSource => ({ ...objectSource(id, 'task'), source: { ...objectSource(id, 'task').source, where } as ObjectKnowledgeSource }); + const { svc, visibleReads } = setup({ sources: [over('s1'), over('s2')] }); + await svc.search('q', { topK: 5, executionContext: MEMBER }); + expect(visibleReads()).toHaveLength(1); + expect(visibleReads()[0][1]).toEqual({ where, fields: ['id'], limit: 501, context: MEMBER }); + }); + + it('a read that fails: reported at warn, and the source is searched as before', async () => { + const { svc, warn, handed } = setup({ visible: () => { throw new Error('db down'); } }); + expect(await svc.search('q', { topK: 5, executionContext: MEMBER })).toEqual([]); + expect(handed().map((o) => o.scope)).toEqual([undefined, undefined]); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('could not be read (db down)')); + }); + + it('every hit is still re-checked: a record the read answered but the re-check refuses is not served', async () => { + // The read answers rec_900 too, the re-check does not admit it (it changed between the two reads). + const { svc } = setup({ readable: READABLE.slice(1), visible: () => READABLE.map((id) => ({ id })) }); + const out = await svc.search('q', { topK: 5, executionContext: MEMBER }); + expect(recordsOf(out)).toEqual(['rec_901', 'rec_902', 'rec_903', 'rec_904', 'rec_905']); + }); +}); + describe('recordToDocument reads the title from the object\'s display field', () => { const src: KnowledgeSource = { name: 's1', label: 's1', adapter: 'memory', @@ -2144,9 +2317,11 @@ describe('KnowledgeService — record-level search (granularity, groupBy, freshn }); const out = await h.svc.search('q', { granularity: 'record', executionContext: MEMBER }); expect(out.map((x) => x.title)).toEqual(['Leave policy (2026)']); + // As the caller: the records they may read (ids only), then ONE re-read of the hits. const callerReads = h.engine!.find.mock.calls.filter((c) => !isSystemCall(c)); - expect(callerReads).toHaveLength(1); - expect(callerReads[0][1]).toMatchObject({ where: { id: { $in: ['c1'] } }, fields: ['id', 'name'], context: MEMBER }); + expect(callerReads).toHaveLength(2); + expect(callerReads[0][1]).toMatchObject({ fields: ['id'], limit: 501, context: MEMBER }); + expect(callerReads[1][1]).toMatchObject({ where: { id: { $in: ['c1'] } }, fields: ['id', 'name'], context: MEMBER }); // The freshness read is projected to the fields assembly reads. expect(h.freshnessReads()[0][1]).toEqual({ where: { id: { $in: ['c1'] } }, fields: ['id', 'body', 'policy', 'name'] }); expect(h.freshnessReads()[0][2]).toEqual({ context: expect.objectContaining({ isSystem: true }) }); diff --git a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts index 35115df52b1..581733e84f2 100644 --- a/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts +++ b/packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts @@ -151,7 +151,8 @@ describe('search_knowledge — the caller\'s execution context', () => { it('passes the caller\'s context to the row-level re-check, which drops a record the caller cannot read', async () => { const { service, contexts } = setup(['p2']); const answer = await service.knowledgeTools().searchKnowledge({ query: 'q' }, caller); - expect(contexts).toEqual([caller]); + // Both reads run as the caller: the records they may read, then the re-check. + expect(contexts).toEqual([caller, caller]); expect(answer.hits.map((h) => h.record?.id)).toEqual(['p2']); }); diff --git a/packages/services/service-knowledge/src/knowledge-search-scope.ts b/packages/services/service-knowledge/src/knowledge-search-scope.ts index 533b355a80e..d9534f839d7 100644 --- a/packages/services/service-knowledge/src/knowledge-search-scope.ts +++ b/packages/services/service-knowledge/src/knowledge-search-scope.ts @@ -189,7 +189,7 @@ export const SEARCH_VISIBLE_IDS_MAX = SEARCH_SCOPE_MAX_IDS; * on the caller's terms alone, as before, and its hits re-checked one by one. * * A returned term may hold no ids: the caller may read none of the records the - * search could answer. + * search could answer. The service does not apply such a narrowing. */ export function narrowToVisible( terms: readonly AdapterScopeTerm[] | undefined, diff --git a/packages/services/service-knowledge/src/knowledge-service.ts b/packages/services/service-knowledge/src/knowledge-service.ts index e9e6c757e86..22af3824d0a 100644 --- a/packages/services/service-knowledge/src/knowledge-service.ts +++ b/packages/services/service-knowledge/src/knowledge-service.ts @@ -2607,14 +2607,14 @@ export class KnowledgeService implements IKnowledgeService { * more than {@link SEARCH_VISIBLE_IDS_MAX}, the source is handed them as a * `record` term, intersected with the caller's own scope, so its adapter * ranks only those rows and a narrow caller's answers are not crowded out of - * the refill cap by rows they could never be served. A source whose narrowed - * term holds no id is not searched: the caller may read none of what it - * could answer. + * the refill cap by rows they could never be served. * * A source is searched as before — on the caller's own scope, its hits * re-checked within the refill cap — when the caller may read more than - * that, when the caller's scope holds a parent (`metadata`) term, or when the - * read fails (logged at `warn`). Nothing here decides access: every hit is + * that, when the caller's scope holds a parent (`metadata`) term, when the + * narrowing names no record (the caller may read none of what the source + * could answer: answered as before, no hit or the source's refusal, never a + * new kind of empty), or when the read fails (logged at `warn`). Nothing here decides access: every hit is * still re-checked as the caller ({@link applyPermissionFilter}), and the * organization filter each source carries is not touched. */ @@ -2641,16 +2641,13 @@ export class KnowledgeService implements IKnowledgeService { for (const [i, entry] of sources.entries()) { const ids = await visible[i]; const narrowed = ids === undefined ? undefined : narrowToVisible(entry.scope, ids); - if (narrowed === undefined) { + // A narrowing that names no record is not applied: the source is + // searched as before, so a caller who may read none of its records is + // answered as before too — no hit, or the source's refusal. + if (narrowed === undefined || narrowed.every((term) => term.ids.length === 0)) { out.push(entry); continue; } - if (narrowed.every((term) => term.ids.length === 0)) { - this.options.logger?.debug?.( - `[knowledge] source '${this.label(entry.source)}' not searched: the caller may read none of the records it could answer.`, - ); - continue; - } out.push({ ...entry, scope: narrowed }); } return out; @@ -2668,15 +2665,13 @@ export class KnowledgeService implements IKnowledgeService { ): Promise { let rows: unknown; try { - rows = await engine.find( - objSource.object, - { - ...(objSource.where === undefined ? {} : { where: objSource.where }), - fields: ['id'], - limit: SEARCH_VISIBLE_IDS_MAX + 1, - }, - { context: ctx }, - ); + // As the caller, in the query, as the permission re-read asks. + rows = await engine.find(objSource.object, { + ...(objSource.where === undefined ? {} : { where: objSource.where }), + fields: ['id'], + limit: SEARCH_VISIBLE_IDS_MAX + 1, + context: ctx, + } as never); if (!Array.isArray(rows)) throw new Error(`the read answered ${describeValue(rows)} instead of a list of rows`); } catch (err) { this.options.logger?.warn?.( diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 3cfd023558d..9df12e342a2 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -228,7 +228,9 @@ type Row = Record; * * The permission re-read (`where: { id: { $in } }`, the caller's context in * the query) answers the rows `wall` admits for that context; without a - * `wall`, every row. The record-level search's freshness check passes its + * `wall`, every row. So does the read of the records a caller may read + * (`fields: ['id']`, the source's `where` and a `limit`, the caller's context in + * the query), ids only. The record-level search's freshness check passes its * system context in the trailing options, never in the query, so it is * answered as any other read: the rows its `where` (`id: { $in }`, alone or * under `$and`) matches, whole. @@ -275,6 +277,14 @@ function rowsEngine(rows: Row[], wall?: (row: Row, context: ExecutionContext) => if (!pinsIds && (typeof query?.limit !== 'number' || !(query.limit > 0))) { throw new Error('engine double: an unbounded find'); } + const caller = query?.context; + if (caller !== undefined) { + return rows + .filter((r) => matches(r, query.where) && (wall === undefined || wall(r, caller))) + .sort((a, b) => (String(a.id) < String(b.id) ? -1 : String(a.id) > String(b.id) ? 1 : 0)) + .slice(0, typeof query.limit === 'number' ? query.limit : undefined) + .map((r) => ({ id: r.id })); + } return rows .filter((r) => matches(r, query.where)) .sort((a, b) => (String(a.id) < String(b.id) ? -1 : String(a.id) > String(b.id) ? 1 : 0)) From 66488be1be1ea21e56af05ce165537b87d78d17a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 02:34:49 +0000 Subject: [PATCH 3/4] test(knowledge): pin the narrowed search through real adapters and the turso record index Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- ...knowledge-search-ranks-readable-records.md | 18 +++++++++ content/docs/protocol/knowledge.mdx | 19 ++++++++-- .../src/__tests__/acceptance.test.ts | 37 +++++++++++++++++++ .../services/service-knowledge/src/testing.ts | 19 ++++++++++ 4 files changed, 90 insertions(+), 3 deletions(-) create mode 100644 .changeset/knowledge-search-ranks-readable-records.md diff --git a/.changeset/knowledge-search-ranks-readable-records.md b/.changeset/knowledge-search-ranks-readable-records.md new file mode 100644 index 00000000000..6f8530461c8 --- /dev/null +++ b/.changeset/knowledge-search-ranks-readable-records.md @@ -0,0 +1,18 @@ +--- +'@objectstack/service-knowledge': patch +'@objectstack/knowledge-turso': patch +'@objectstack/knowledge-pgvector': patch +--- + +feat(service-knowledge): a caller who may read few of a source's records is answered from them, wherever they rank + +Clause-②: no +Metadata-protocol: none + +A knowledge search re-checks every hit as the caller after ranking, and refills once at `topK × 20`. A caller who may read only a few of a source's rows (20 of 1,000, say) could find none of them within that cap and be answered nothing, though the store held their answer. + +- **`@objectstack/service-knowledge`.** Before the first round, for a caller who is not the system identity, the service reads the ids of each source's records that caller may read: as the caller, under the source's `where`, ids only, at most 501. When there are 500 or fewer, the source is handed them as a `record` scope term, so its adapter ranks only those rows. A caller's own `scope` is intersected with them, never widened: a one-record scope stays one record. A scope with a parent (metadata) term, more than 500 readable records, a read that fails (logged at `warn`), or no readable record in scope, and the source is searched as before. Every hit is still re-checked one by one, the organization filter is unchanged, and the system identity's search is unchanged. The conformance harness's engine double (`@objectstack/service-knowledge/testing`) answers that read as the caller too. +- **`@objectstack/knowledge-turso`.** Each new generation's passage table carries an index on `source_record_id`, so a narrowed search reads only those records' passages. A generation made before gets it from its next build; nothing to run. +- **`@objectstack/knowledge-pgvector`.** Each passage table carries an index on `(source_id, generation, source_record_id)`. A table made before gets it on the first write after the upgrade (`CREATE INDEX IF NOT EXISTS`, which holds writes to that table while it builds). + +Nothing to migrate. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 02f6517158b..b9027f6d2cc 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -301,7 +301,15 @@ re-check name fewer than `topK` records (several passages of one record count once), every 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 +hits. So before the first round the service reads, as the caller, the ids of +the source's records they may read (under the source's `where`, ids only, at +most 501). When there are 500 or fewer, the source is handed them as a +`record` term of the [record scope](#record-scope) — intersected with the +caller's own scope, never added to it — and the adapter ranks only those +rows, so a caller who may read 20 of 1,000 records is answered from their 20 +wherever they rank. More than 500, a scope with a parent term, a read that +fails, or no readable record in scope, and the source is searched as above. +Every hit is still re-checked, and the organization filter is unchanged. An adapter that answers fewer than it was asked (one that caps `topK`) is not asked again. For the system identity every source is asked for `topK` once. The answer is at most `topK` hits. @@ -678,7 +686,10 @@ an exact scan. `organization_id` column, which every search filters on before ranking. - **Where the tables are.** In their own schema, `os_knowledge` (option `schema`): `knowledge_generation`, one row per source and generation, and - one passage table per vector width, `knowledge_vec_d`. Object + one passage table per vector width, `knowledge_vec_d`, indexed on + each passage's record so a search narrowed to a caller's few readable + records reads only their passages (made with the table, or on the first + write after an upgrade for a table made before). Object tables live in the connection's own schema, and the platform's drift checks read only that one — so no store table can collide with an object table or be reported as drift. @@ -754,7 +765,9 @@ the `embedder` it is given), and answers a search by an exact scan. way when its fingerprint is the same, and replaces it otherwise, so the first builder's writes are then refused), and one passage table per source and generation, `knowledge__g`, its vector column sized for that generation - (`` is the source's index key). A key that is not snake_case is + (`` is the source's index key) and indexed on `source_record_id`, so + a search narrowed to a caller's few readable records reads only their + passages; a generation made before carries the index from its next build. A key that is not snake_case is refused before any SQL. - **Search.** Two legs merged by reciprocal rank fusion (`k` = 60, each leg at most `topK`) before the service's re-check: an exact scan by cosine diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 14cd3182ef6..6554b84253e 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -426,6 +426,43 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { expect((await adapter.search('long name', { source: long, topK: 1 })).length).toBe(1); await expect(adapter.search('x', { source: bad, topK: 1 })).rejects.toThrow(/cannot name a table/); }); + + it('a search narrowed to a few records reads them through the source_record_id index, never by scanning the table', async () => { + // Every statement the adapter runs, so the search's own SQL is planned below. + const client = store.client(); + const ran: Array<{ sql: string; args: unknown }> = []; + const recording = new Proxy(client, { + get(target, prop) { + const value: unknown = Reflect.get(target, prop, target); + if (prop === 'execute') { + return (stmt: { sql: string; args?: unknown }) => { + ran.push({ sql: stmt.sql, args: stmt.args }); + return target.execute(stmt as never); + }; + } + return typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(target) : value; + }, + }); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: recording, embedder: new FakeEmbedder() }); + const s = source('narrowed'); + await adapter.upsert( + Array.from({ length: 40 }, (_, i) => doc(s, `r${i}`, `harbour crane passage ${i}`)), + ctx(s), + ); + ran.length = 0; + const hits = await adapter.search('harbour crane', { + source: s, topK: 5, organizationIds: ['org_a'], scope: [{ kind: 'record', ids: ['r3', 'r7'] }], + }); + expect(hits).toEqual([]); // no passage carries org_a: the organization filter still applies + const search = ran.find((r) => r.sql.trimStart().startsWith('WITH')); + expect(search).toBeDefined(); + const plan = await client.execute({ sql: `EXPLAIN QUERY PLAN ${search!.sql}`, args: search!.args as never }); + const details = plan.rows.map((r) => String(r.detail)); + const table = `knowledge_${s.name}_g1`; + expect(details.some((d) => d.includes(`USING INDEX ${table}_record`))).toBe(true); + // Neither leg nor the keyword statistics reads the passage table whole. + expect(details.filter((d) => new RegExp(`^SCAN (${table}|p)\\b`).test(d))).toEqual([]); + }); }); } diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 9df12e342a2..2c419b06bc0 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -768,6 +768,25 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption } }); + it('a caller who may read only the two clauses every other outranks is answered from them, past the refill cap', async () => { + const source = clauseSource('scope_readable'); + const readable = new Set(['c03', 'c07']); + const h = await serviceOver(make, clauseRows(), source, { + schemas: { article: CLAUSE_SCHEMA }, + wall: (row) => readable.has(String(row.id)), + }); + await h.svc.reindexSource(source.name); + // topK 1: the refill reaches 20 passages, and the eighteen better clauses hold more than that. + const hits = await h.svc.search(SCOPE_QUERY, { topK: 1, executionContext: READER }); + expect(h.searched[0]?.scope).toEqual([{ kind: 'record', ids: ['c03', 'c07'] }]); + for (const hit of hits) expect(readable.has(String(hit.sourceRecordId))).toBe(true); + if (opts.implements.scope) expect(hits).toHaveLength(1); + // A caller scope of one of them stays that one. + const one = await h.svc.search(SCOPE_QUERY, { topK: 5, scope: [{ object: 'article', ids: ['c07'] }], executionContext: READER }); + expect(lastOf(h.searched)?.scope).toEqual([{ kind: 'record', ids: ['c07'] }]); + for (const hit of one) expect(hit.sourceRecordId).toBe('c07'); + }); + it('a parent scope: only the clauses whose listed lookup holds one of the policy ids', async () => { const source = clauseSource('scope_parent'); const h = await serviceOver(make, clauseRows(), source, { schemas: { article: CLAUSE_SCHEMA } }); From 6747f6f6e781a916a5fffba1540d9f365e55482b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 03:32:02 +0000 Subject: [PATCH 4/4] test(knowledge-turso): the keyword index's own MATCH plan is not a scan of the passage table Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP --- .../plugins/knowledge-turso/src/__tests__/acceptance.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index 6554b84253e..444792dc6af 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -460,8 +460,9 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { const details = plan.rows.map((r) => String(r.detail)); const table = `knowledge_${s.name}_g1`; expect(details.some((d) => d.includes(`USING INDEX ${table}_record`))).toBe(true); - // Neither leg nor the keyword statistics reads the passage table whole. - expect(details.filter((d) => new RegExp(`^SCAN (${table}|p)\\b`).test(d))).toEqual([]); + // Neither leg nor the keyword statistics reads the passage table whole (its + // keyword index, `-fts`, is searched by MATCH, a virtual table's own plan). + expect(details.filter((d) => new RegExp(`^SCAN (${table}|p)(\\s|$)`).test(d))).toEqual([]); }); }); }