Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/knowledge-search-ranks-readable-records.md
Original file line number Diff line number Diff line change
@@ -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.
19 changes: 16 additions & 3 deletions content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<width>`. Object
one passage table per vector width, `knowledge_vec_d<width>`, 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.
Expand Down Expand Up @@ -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_<source>_g<n>`, its vector column sized for that generation
(`<source>` is the source's index key). A key that is not snake_case is
(`<source>` 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
Expand Down
3 changes: 3 additions & 0 deletions packages/plugins/knowledge-pgvector/src/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
];
}
Expand Down
38 changes: 38 additions & 0 deletions packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,44 @@ 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 (its
// keyword index, `<table>-fts`, is searched by MATCH, a virtual table's own plan).
expect(details.filter((d) => new RegExp(`^SCAN (${table}|p)(\\s|$)`).test(d))).toEqual([]);
});
});
}

Expand Down
3 changes: 3 additions & 0 deletions packages/plugins/knowledge-turso/src/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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'] }]);
});
});
Loading
Loading