diff --git a/.changeset/38747-knowledge-pgvector-scope-gin.md b/.changeset/38747-knowledge-pgvector-scope-gin.md new file mode 100644 index 00000000000..53ae22825bf --- /dev/null +++ b/.changeset/38747-knowledge-pgvector-scope-gin.md @@ -0,0 +1,11 @@ +--- +'@objectstack/knowledge-pgvector': patch +--- + +fix(knowledge-pgvector): a search narrowed by a metadata scope term reads only the passages in scope, through a GIN index on `metadata` + +Clause-②: no +Metadata-protocol: none + +- The passage table of each width now has a GIN index on `metadata` (`jsonb_path_ops`), named `knowledge_vec_d_metadata`. A new table is made with it. A table made by an earlier release gets it at its first search with a `metadata` scope term: the store looks the index up and creates it when absent (`CREATE INDEX IF NOT EXISTS`, not `CONCURRENTLY`), which holds the table's writes, not its reads, while it builds — on 58,500 passages of 1024 dimensions it took about 32 ms, then about 0.26 s of `ANALYZE`. When the database role may not create it, the scoped search is not refused: it answers as before, by a scan of the source's passages, and the store logs one warning naming the `CREATE INDEX` statement to run as a database owner, then does not try again in that process; once an owner runs it, the next search reads through it, with no restart. +- A `metadata` scope term is now written as containment the index serves — for each id, `{field: id}` and `{field: [id]}`, and the same two as a number when the id is how PostgreSQL prints a number — ANDed with the exact match it had before. So the vector leg, the keyword leg's candidates and its passage count read the passages in scope through the index instead of computing the distance of every passage of the generation; on a seeded table of 58,500 passages, one scoped vector-leg statement went from about 300 ms (sequential scan) to about 2 ms (bitmap index scan). Results are unchanged for every kind of stored value: a string, a number, a list of strings or numbers, a missing value, `null`, an object, a boolean. diff --git a/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs b/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs index 0f75ace6f3c..eb5d5fa7386 100644 --- a/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs +++ b/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs @@ -186,7 +186,14 @@ describe('bench instrument — segment seams over the real adapter and service', expect(parts.where).toMatch(/^source_id = \$1 AND generation = \$2 AND EXISTS/); expect(parts.where).toContain('jsonb_array_elements(CASE jsonb_typeof('); // $1 source, $2 generation, the scope's ids and its field: the leg's LIMIT is the next one. - expect(parts.params).toEqual(['clauses', 1, ['u1', 'u2'], 'unit']); + expect(parts.params).toEqual([ + 'clauses', + 1, + ['u1', 'u2'], + 'unit', + ['{"unit":"u1"}', '{"unit":["u1"]}', '{"unit":"u2"}', '{"unit":["u2"]}'], + ]); + expect(parts.where).toContain('metadata @> ANY($5::jsonb[])'); const highest = Math.max(...[...parts.where.matchAll(/\$(\d+)/g)].map((m) => Number(m[1]))); expect(highest).toBe(parts.params.length); }); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/scope-containment-38747.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/scope-containment-38747.live-postgres.test.ts new file mode 100644 index 00000000000..628c84fc206 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/scope-containment-38747.live-postgres.test.ts @@ -0,0 +1,304 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A search narrowed by a `metadata` scope term on a LIVE PostgreSQL with + * pgvector. The term is written as containment the metadata GIN index serves, + * beside the exact match the search always had, so: + * + * - for every kind of stored value (a string, a number, a list of strings, a + * list of numbers, a missing value, `null`, an object, a boolean) the search + * ranks exactly the passages that exact match holds for — computed here on + * the same rows, independently of the adapter — and the ones the contract + * names (`String(v)` is an id); + * - the vector leg's plan reads the passages in scope through the index, not + * by a sequential scan of the generation; + * - a passage table made before the index gets it at its first such search; + * - a database that refuses to make it still answers the scoped search, with + * the indexed top 5, by a scan, and the store warns once. + */ + +import { afterAll, describe, expect, it } from 'vitest'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import { PgvectorKnowledgeAdapter, poolFromPg, type PgPoolLike } from '../index.js'; +import { FakeEmbedder, PG_URL, liveStore, requireLiveCell } from './live-pg.testkit.js'; + +requireLiveCell('knowledge-pgvector metadata scope containment'); + +const store = liveStore('kpg_scope'); + +const source: KnowledgeSource = { + name: 'scoped', + label: 'scoped', + adapter: 'under_test', + source: { kind: 'object', object: 'clause', content: ['body'] }, +} as KnowledgeSource; +const ctx = { source, reason: 'manual' as const, index: { fingerprint: 'fp-scope', recipeHash: 'rh-scope' } }; +const TABLE = 'knowledge_vec_d384'; + +/** A passage every search below ranks in both legs: it shares the query's word. */ +function doc(n: string, metadata: Record): KnowledgeDocument { + const id = `${source.name}:${n}`; + const content = `granite quarry ${n}`; + return { id, sourceId: source.name, sourceRecordId: n, content, metadata, chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }] }; +} + +/** Today's exact match of a `metadata` term, written independently of the adapter: `$1` the field, `$2` the ids. */ +const EXACT = `EXISTS (SELECT 1 FROM jsonb_array_elements(CASE jsonb_typeof(metadata -> $1::text) WHEN 'array' THEN metadata -> $1::text + ELSE jsonb_build_array(metadata -> $1::text) END) AS e(v) + WHERE jsonb_typeof(e.v) IN ('string', 'number') AND e.v #>> '{}' = ANY($2::text[]))`; + +/** A pool that hands every statement on, and records each ranking statement with its values. */ +function recording(inner: PgPoolLike): { pool: PgPoolLike; ranked: Array<{ text: string; values: unknown[] }> } { + const ranked: Array<{ text: string; values: unknown[] }> = []; + const note = (text: string, values?: unknown[]) => { + if (/\bvec AS \(/.test(text)) ranked.push({ text, values: values ?? [] }); + }; + return { + ranked, + pool: { + query: async (text, values) => { + note(text, values); + return inner.query(text, values); + }, + connect: async () => { + const client = await inner.connect(); + return { + query: async (text, values) => { + note(text, values); + return client.query(text, values); + }, + release: (err) => client.release(err), + }; + }, + } as PgPoolLike, + }; +} + +/** + * A store of `rows` (`n` → the passage's `unit`; `undefined` leaves it out), + * and `raw` values written straight into `metadata` as JSON text (a number + * whose stored text is not the shortest one of its value, which a write + * through JSON never makes). + */ +async function seeded(rows: Record, raw: Record = {}) { + const schema = store.schema(); + const adapter = store.adapter({ schema }); + await adapter.upsert( + Object.entries(rows).map(([n, unit]) => doc(n, unit === undefined ? { other: 'x' } : { unit })), + ctx, + ); + for (const [n, json] of Object.entries(raw)) { + await adapter.upsert([doc(n, {})], ctx); + await store.pool().query(`UPDATE "${schema}".${TABLE} SET metadata = $1::jsonb WHERE source_record_id = $2`, [json, n]); + } + const scoped = async (ids: string[]): Promise => + (await adapter.search('granite', { source, topK: 100, scope: [{ kind: 'metadata', field: 'unit', ids }] })) + .map((h) => h.sourceRecordId as string) + .sort(); + const exact = async (ids: string[]): Promise => + ( + await store + .pool() + .query<{ n: string }>(`SELECT source_record_id AS n FROM "${schema}".${TABLE} WHERE ${EXACT} ORDER BY 1`, ['unit', ids]) + ).rows + .map((r) => r.n) + .sort(); + /** The search's passages for `ids`, after checking they are today's exact match's. */ + const check = async (ids: string[]): Promise => { + const got = await scoped(ids); + expect(got, `ids ${JSON.stringify(ids)}`).toEqual(await exact(ids)); + return got; + }; + return { schema, adapter, check }; +} + +describe.skipIf(!PG_URL)('knowledge-pgvector metadata scope on a LIVE PostgreSQL', () => { + afterAll(() => store.dropAll()); + + it('a stored string: held by the id equal to it, nothing else', async () => { + const { check } = await seeded({ s1: 'u1', s2: 'u2', s3: '7', s4: 'U1', s5: '', s6: '1.50' }); + expect(await check(['u1'])).toEqual(['s1']); + expect(await check(['u1', 'u2'])).toEqual(['s1', 's2']); + expect(await check(['7'])).toEqual(['s3']); + expect(await check(['U1'])).toEqual(['s4']); + expect(await check(['1.5'])).toEqual([]); + expect(await check(['1.50'])).toEqual(['s6']); + expect(await check(['nope'])).toEqual([]); + }); + + it('a stored number: held by the id equal to its stored text, by no other spelling of its value', async () => { + const { check } = await seeded({ n1: 7, n2: 7.5, n3: -3, n4: 0, n5: 1e21, c1: 'u1' }, { n6: '{"unit": 1.50}', n7: '{"unit": 100}' }); + expect(await check(['7'])).toEqual(['n1']); + expect(await check(['7.5'])).toEqual(['n2']); + expect(await check(['-3'])).toEqual(['n3']); + expect(await check(['0'])).toEqual(['n4']); + // `1e21` is stored as the numeric it denotes, and printed in full. + expect(await check(['1000000000000000000000'])).toEqual(['n5']); + expect(await check(['1e+21'])).toEqual([]); + // Containment holds 1.50 for the id 1.5 (equal values); the exact match does not. + expect(await check(['1.50'])).toEqual(['n6']); + expect(await check(['1.5'])).toEqual([]); + expect(await check(['100'])).toEqual(['n7']); + for (const spelling of ['7.0', '07', '1e2', '+7', '-0']) expect(await check([spelling])).toEqual([]); + }); + + it('a stored list of strings: held by an id equal to any element', async () => { + const { check } = await seeded({ a1: ['u1', 'u2'], a2: ['u3'], a3: [], c1: 'u2' }); + expect(await check(['u1'])).toEqual(['a1']); + expect(await check(['u2', 'x'])).toEqual(['a1', 'c1']); + expect(await check(['u3'])).toEqual(['a2']); + expect(await check(['x'])).toEqual([]); + }); + + it('a stored list of numbers: held by an id equal to any element as stored text', async () => { + const { check } = await seeded({ b1: [7, 8], b2: [1.5], b3: [-3] }, { b4: '{"unit": [1.50, 2]}' }); + expect(await check(['7'])).toEqual(['b1']); + expect(await check(['8', '-3'])).toEqual(['b1', 'b3']); + expect(await check(['1.5'])).toEqual(['b2']); + expect(await check(['1.50'])).toEqual(['b4']); + expect(await check(['2'])).toEqual(['b4']); + }); + + it('a stored list of mixed elements: only its strings and numbers hold', async () => { + const { check } = await seeded({ m1: [7, 'u1', null, { id: 'u2' }, true, ['u3']] }); + expect(await check(['7'])).toEqual(['m1']); + expect(await check(['u1'])).toEqual(['m1']); + for (const id of ['u2', 'u3', 'true', 'null']) expect(await check([id])).toEqual([]); + }); + + it('a missing value holds for no id', async () => { + const { check } = await seeded({ x1: undefined, c1: 'u1' }, { x2: '{}' }); + expect(await check(['u1'])).toEqual(['c1']); + expect(await check(['x'])).toEqual([]); + }); + + it('a stored null holds for no id', async () => { + const { check } = await seeded({ z1: null, c1: 'null' }); + expect(await check(['null'])).toEqual(['c1']); + expect(await check(['u1'])).toEqual([]); + }); + + it('a stored object holds for no id', async () => { + const { check } = await seeded({ o1: { id: 'u1' }, o2: { u1: true }, c1: 'u1' }); + expect(await check(['u1'])).toEqual(['c1']); + expect(await check(['{"id": "u1"}', 'id'])).toEqual([]); + }); + + it('a stored boolean holds for no id', async () => { + const { check } = await seeded({ t1: true, t2: false, c1: 'true' }); + expect(await check(['true'])).toEqual(['c1']); + expect(await check(['false'])).toEqual([]); + }); + + it("the vector leg reads the passages in scope through the metadata index, not by a sequential scan", async () => { + const schema = store.schema(); + const live = recording(poolFromPg(store.pool())); + const adapter = store.adapter({ schema, pool: live.pool }); + await adapter.upsert([doc('seed', { unit: 'u0' })], ctx); + // 20,000 passages of 200 units, a tenth of them listing two: about 110 per unit. + await store.pool().query( + `INSERT INTO "${schema}".${TABLE} (source_id, generation, chunk_id, document_id, source_record_id, content, chunk_hash, metadata, embedding) + SELECT $1, generation, 'c' || i, 'd' || i, 'r' || i, 'granite quarry ' || i, md5(i::text), + CASE WHEN i % 10 = 0 THEN jsonb_build_object('unit', jsonb_build_array('u' || (i % 200), 'u' || ((i + 1) % 200))) + ELSE jsonb_build_object('unit', 'u' || (i % 200)) END, + embedding + FROM "${schema}".${TABLE}, generate_series(1, 20000) i WHERE source_record_id = 'seed'`, + [source.name], + ); + await store.pool().query(`ANALYZE "${schema}".${TABLE}`); + + const hits = await adapter.search('granite', { source, topK: 5, scope: [{ kind: 'metadata', field: 'unit', ids: ['u7'] }] }); + expect(hits.length).toBe(5); + const { text, values } = live.ranked[live.ranked.length - 1]; + const vec = /vec AS \(([\s\S]*?LIMIT \$\d+)\)/.exec(text)?.[1]; + expect(vec).toContain('metadata @> ANY('); + // The vector leg alone, with the values it reads. + const last = Math.max(...[...vec!.matchAll(/\$(\d+)/g)].map((m) => Number(m[1]))); + const plan = ( + await store.pool().query<{ 'QUERY PLAN': string }>(`EXPLAIN WITH vec AS (${vec}) SELECT chunk_id FROM vec`, values.slice(0, last)) + ).rows + .map((r) => r['QUERY PLAN']) + .join('\n'); + expect(plan).toMatch(/Bitmap Index Scan on knowledge_vec_d384_metadata/); + expect(plan).not.toMatch(/Seq Scan on knowledge_vec_d384\b/); + }); + + it('a database that refuses the metadata index: the scoped search answers the indexed top 5 by a scan, with one warning', async () => { + const units = ['u1', 'u2', 7, ['u1', 'u3'], 'u4']; + const schema = store.schema(); + const adapter = store.adapter({ schema }); + // Passages that differ in how near they are to the query, so the top 5 is an order, not a tie. + await adapter.upsert( + Array.from({ length: 40 }, (_, i) => { + const id = `${source.name}:p${i}`; + const content = `granite ${'quarry '.repeat(i % 7)}basalt ${'slate '.repeat(i % 3)}${i}`; + return { + id, + sourceId: source.name, + sourceRecordId: `p${i}`, + content, + metadata: { unit: units[i % units.length] }, + chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }], + }; + }), + ctx, + ); + const scope = [{ kind: 'metadata' as const, field: 'unit', ids: ['u1', '7'] }]; + const top = async (a: PgvectorKnowledgeAdapter, query: string) => + (await a.search(query, { source, topK: 5, scope })).map((h) => [h.sourceRecordId, h.score]); + const indexed = { granite: await top(adapter, 'granite'), quarry: await top(adapter, 'quarry granite') }; + expect(indexed.granite).toHaveLength(5); + + const index = `"${schema}"."${TABLE}_metadata"`; + await store.pool().query(`DROP INDEX ${index}`); + // A new process whose role may not create it: the database refuses the statement. + const inner = poolFromPg(store.pool()); + let attempts = 0; + const refusing: PgPoolLike = { + ...inner, + query: async (text, values) => { + if (text.startsWith('CREATE INDEX') && text.includes(`${TABLE}_metadata"`)) { + attempts += 1; + throw Object.assign(new Error(`must be owner of table ${TABLE}`), { code: '42501' }); + } + return inner.query(text, values); + }, + }; + const warnings: string[] = []; + const second = new PgvectorKnowledgeAdapter({ + id: 'under_test', + pool: refusing, + schema, + embedder: new FakeEmbedder(), + logger: { warn: (m) => warnings.push(m) }, + }); + expect(await top(second, 'granite')).toEqual(indexed.granite); + expect(await top(second, 'quarry granite')).toEqual(indexed.quarry); + expect(attempts).toBe(1); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain(`CREATE INDEX IF NOT EXISTS "${TABLE}_metadata" ON "${schema}"."${TABLE}" USING gin (metadata jsonb_path_ops);`); + expect((await store.pool().query<{ present: string | null }>('SELECT to_regclass($1) AS present', [index])).rows[0].present).toBeNull(); + await second.close(); + }); + + it('a passage table made before the metadata index gets it at its first scoped search, which answers as before', async () => { + const { schema, check } = await seeded({ s1: 'u1', s2: ['u1', 'u2'], s3: 7, s4: 'u3' }); + const index = `"${schema}"."${TABLE}_metadata"`; + const present = async () => + (await store.pool().query<{ present: string | null }>('SELECT to_regclass($1) AS present', [index])).rows[0].present; + expect(await present()).not.toBeNull(); + // The table as a release without the metadata index left it. + await store.pool().query(`DROP INDEX ${index}`); + expect(await present()).toBeNull(); + // A new process on the same schema: a search scoped by record does not make it … + const second = new PgvectorKnowledgeAdapter({ id: 'under_test', pool: poolFromPg(store.pool()), schema, embedder: new FakeEmbedder() }); + await second.search('granite', { source, topK: 10, scope: [{ kind: 'record', ids: ['s1'] }] }); + expect(await present()).toBeNull(); + // … its first search with a metadata term does, and answers as the exact match does. + const hits = await second.search('granite', { source, topK: 10, scope: [{ kind: 'metadata', field: 'unit', ids: ['u1', '7'] }] }); + expect(hits.map((h) => h.sourceRecordId).sort()).toEqual(['s1', 's2', 's3']); + expect(await present()).not.toBeNull(); + expect(await check(['u1', '7'])).toEqual(['s1', 's2', 's3']); + await second.close(); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/scope-containment-38747.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/scope-containment-38747.test.ts new file mode 100644 index 00000000000..e1837b78fc7 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/scope-containment-38747.test.ts @@ -0,0 +1,207 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The shape of a search narrowed by a `metadata` scope term, without a + * database: the passage table carries a GIN index on `metadata` + * (`jsonb_path_ops`), the term is written as containment over bound `jsonb` + * values that index serves, ANDed with the exact match it always had, in every + * place the search's WHERE is read (the vector leg, the keyword leg's + * candidates and its passage count), and a table made before the index gets it + * at its first such search — or, when it cannot be made, is searched by a scan + * with one warning. The results a stored value of each kind gets are + * pinned on a live PostgreSQL (`scope-containment-38747.live-postgres.test.ts`). + */ + +import { describe, expect, it } from 'vitest'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import type { AdapterScopeTerm } from '@objectstack/spec/contracts'; +import { PgvectorKnowledgeAdapter, type PgClientLike, type PgPoolLike } from '../index.js'; +import { metadataIndexDdl, metadataIndexName, metadataScopeForms, vectorTableDdl } from '../sql.js'; +import { FakeEmbedder } from './live-pg.testkit.js'; + +const source = { name: 'scoped', label: 'scoped', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource; + +const INDEX_DDL = + 'CREATE INDEX IF NOT EXISTS "knowledge_vec_d384_metadata" ON "os_knowledge"."knowledge_vec_d384" USING gin (metadata jsonb_path_ops)'; + +/** Today's exact match of a `metadata` term, as the search wrote it before the containment form. */ +const exactMatch = (field: number, ids: number) => + `EXISTS (SELECT 1 FROM jsonb_array_elements(CASE jsonb_typeof((metadata -> $${field}::text)) WHEN 'array' THEN (metadata -> $${field}::text) ` + + `ELSE jsonb_build_array((metadata -> $${field}::text)) END) AS e(v) ` + + `WHERE jsonb_typeof(e.v) IN ('string', 'number') AND e.v #>> '{}' = ANY($${ids}::text[]))`; + +interface Store { + pool: PgPoolLike; + /** Every statement sent, in order, each followed by its values when it has any. */ + statements: string[]; + /** The ranking statements, with their values. */ + ranked: Array<{ text: string; values: unknown[] }>; +} + +/** + * A store with one active generation of 384-wide passages, whose metadata index + * is `present` or not; creating it fails when `createFails` says so. The + * ranking finds nothing. + */ +function store(opts: { present?: boolean; createFails?: boolean } = {}): Store { + const statements: string[] = []; + const ranked: Store['ranked'] = []; + let present = opts.present ?? true; + const answer = async (text: string, values?: unknown[]): Promise<{ rows: R[] }> => { + // A statement with its values, so a lookup by name shows which name. + statements.push(values !== undefined && values.length > 0 ? `${text} ${JSON.stringify(values)}` : text); + if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.0' }] as R[] }; + if (text.includes('to_regclass')) { + const name = String(values?.[0] ?? ''); + return { rows: [{ present: name.endsWith('_metadata"') && !present ? null : 'x' }] as R[] }; + } + if (text.startsWith('CREATE INDEX') && text.includes('_metadata"')) { + if (opts.createFails) throw new Error('permission denied for schema os_knowledge'); + present = true; + return { rows: [] as R[] }; + } + if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) { + return { rows: [{ generation: 1, fingerprint: 'fp', recipe_hash: 'rh', dim: 384, state: 'active' }] as R[] }; + } + if (text.includes('AS distance')) ranked.push({ text, values: values ?? [] }); + return { rows: [] as R[] }; + }; + const client = (): PgClientLike => ({ query: answer, release: () => undefined }); + return { pool: { query: answer, connect: async () => client() }, statements, ranked }; +} + +async function search(s: Store, scope: AdapterScopeTerm[], query = 'granite quarry') { + const adapter = new PgvectorKnowledgeAdapter({ pool: s.pool, embedder: new FakeEmbedder() }); + await adapter.search(query, { source, topK: 5, scope }); + return adapter; +} + +describe('knowledge-pgvector metadata index', () => { + it('is a GIN index on metadata with jsonb_path_ops, made with the passage table', () => { + expect(metadataIndexName(384)).toBe('knowledge_vec_d384_metadata'); + expect(metadataIndexDdl('os_knowledge', 384)).toBe(INDEX_DDL); + expect(vectorTableDdl('os_knowledge', 384, 'public.vector')).toContain(INDEX_DDL); + }); +}); + +describe('knowledge-pgvector metadata scope forms', () => { + it('holds a string id as a scalar and as a one-element list', () => { + expect(metadataScopeForms('owning_unit', ['u7', 'B-2'])).toEqual([ + '{"owning_unit":"u7"}', + '{"owning_unit":["u7"]}', + '{"owning_unit":"B-2"}', + '{"owning_unit":["B-2"]}', + ]); + }); + + it('adds the two number forms for an id a stored number prints as', () => { + expect(metadataScopeForms('policy', ['7'])).toEqual(['{"policy":"7"}', '{"policy":["7"]}', '{"policy":7}', '{"policy":[7]}']); + for (const id of ['0', '-3', '1.50', '0.001', '12345678901234567890123']) { + expect(metadataScopeForms('f', [id])).toEqual([`{"f":"${id}"}`, `{"f":["${id}"]}`, `{"f":${id}}`, `{"f":[${id}]}`]); + } + }); + + it('gives no number form for text no stored number prints as', () => { + // A leading zero, an exponent, a plus sign, a bare point, white space: PostgreSQL + // prints a numeric as none of these, so no stored number matches them as text. + for (const id of ['01', '1e2', '+1', '1.', '.5', ' 1', '-', 'NaN', 'Infinity']) { + expect(metadataScopeForms('f', [id])).toEqual([`{"f":${JSON.stringify(id)}}`, `{"f":[${JSON.stringify(id)}]}`]); + } + }); + + it('writes every form as JSON text, the field and the id escaped', () => { + const forms = metadataScopeForms('a "quoted" \\ field', ['he said "hi"', 'back\\slash', '单位/7']); + for (const form of forms) expect(() => JSON.parse(form)).not.toThrow(); + expect(JSON.parse(forms[0])).toEqual({ 'a "quoted" \\ field': 'he said "hi"' }); + expect(JSON.parse(forms[5])).toEqual({ 'a "quoted" \\ field': ['单位/7'] }); + }); + + it('writes a lone surrogate as U+FFFD, as the driver sends the exact match its text', () => { + const forms = metadataScopeForms('f\uD800', ['a\uDC00b']); + expect(JSON.parse(forms[0])).toEqual({ 'f�': 'a�b' }); + expect(forms[0]).not.toMatch(/\\u[dD][89abAB]/); + }); +}); + +describe('knowledge-pgvector search with a metadata scope term', () => { + it('binds the containment forms as jsonb[] and keeps the exact match, in all three reads of the WHERE', async () => { + const s = store(); + await search(s, [{ kind: 'metadata', field: 'owning_unit', ids: ['u7', '7'] }]); + expect(s.ranked).toHaveLength(1); + const { text, values } = s.ranked[0]; + // $3 ids, $4 field, $5 forms. + expect(values[2]).toEqual(['u7', '7']); + expect(values[3]).toBe('owning_unit'); + expect(values[4]).toEqual(metadataScopeForms('owning_unit', ['u7', '7'])); + const term = `((metadata @> ANY($5::jsonb[]) AND ${exactMatch(4, 3)}))`; + // The vector leg, the keyword leg's candidates, and its passage count. + expect(text.split(term)).toHaveLength(4); + expect(text).toMatch(/vec AS \([\s\S]*?WHERE [\s\S]*?metadata @> ANY\(\$5::jsonb\[\]\)[\s\S]*?\) ranked/); + expect(text).toMatch(/cand AS \([\s\S]*?metadata @> ANY\(\$5::jsonb\[\]\)/); + expect(text).toMatch(/stats AS \(SELECT \(SELECT count\(\*\) FROM [^)]*WHERE [\s\S]*?metadata @> ANY\(\$5::jsonb\[\]\)/); + }); + + it('writes each metadata term with its own forms, a union beside a record term', async () => { + const s = store(); + await search(s, [ + { kind: 'record', ids: ['r1'] }, + { kind: 'metadata', field: 'policy', ids: ['p1'] }, + { kind: 'metadata', field: 'unit', ids: ['u1'] }, + ]); + const { text, values } = s.ranked[0]; + expect(text).toContain( + `(source_record_id = ANY($3::text[]) OR (metadata @> ANY($6::jsonb[]) AND ${exactMatch(5, 4)}) OR ` + + `(metadata @> ANY($9::jsonb[]) AND ${exactMatch(8, 7)}))`, + ); + expect(values[5]).toEqual(metadataScopeForms('policy', ['p1'])); + expect(values[8]).toEqual(metadataScopeForms('unit', ['u1'])); + }); + + it('writes no containment for a record term alone, and looks for no metadata index', async () => { + const s = store(); + await search(s, [{ kind: 'record', ids: ['r1'] }]); + expect(s.ranked[0].text).not.toContain('jsonb[]'); + expect(s.statements.some((t) => t.includes('to_regclass') && t.includes('_metadata'))).toBe(false); + }); +}); + +describe('knowledge-pgvector metadata index on a table made before it', () => { + const lookups = (s: Store) => s.statements.filter((t) => t.includes('to_regclass') && t.includes('_metadata')).length; + const creates = (s: Store) => s.statements.filter((t) => t === INDEX_DDL); + + it('is made at the first search with a metadata term, once, before the ranking', async () => { + const s = store({ present: false }); + const adapter = await search(s, [{ kind: 'metadata', field: 'unit', ids: ['u1'] }]); + expect(creates(s)).toHaveLength(1); + expect(s.statements.indexOf(INDEX_DDL)).toBeLessThan(s.statements.findIndex((t) => t.includes('AS distance'))); + const before = s.statements.length; + await adapter.search('granite', { source, topK: 5, scope: [{ kind: 'metadata', field: 'unit', ids: ['u2'] }] }); + expect(creates(s)).toHaveLength(1); + expect(s.statements.slice(before).some((t) => t.includes('_metadata'))).toBe(false); + }); + + it('is looked up, never created, when the table has it', async () => { + const s = store({ present: true }); + const before = lookups(s); + await search(s, [{ kind: 'metadata', field: 'unit', ids: ['u1'] }]); + expect(lookups(s)).toBeGreaterThan(before); + expect(creates(s)).toHaveLength(0); + }); + + it('when it cannot be made, the search still ranks, warns once with the statement to run, and never tries again', async () => { + const s = store({ present: false, createFails: true }); + const warnings: string[] = []; + const adapter = new PgvectorKnowledgeAdapter({ pool: s.pool, embedder: new FakeEmbedder(), logger: { warn: (m) => warnings.push(m) } }); + const scope: AdapterScopeTerm[] = [{ kind: 'metadata', field: 'unit', ids: ['u1'] }]; + await expect(adapter.search('granite', { source, topK: 5, scope })).resolves.toEqual([]); + await expect(adapter.search('quarry', { source, topK: 5, scope })).resolves.toEqual([]); + // Both searches ranked, with the same statement as an indexed table gets. + expect(s.ranked).toHaveLength(2); + for (const { text } of s.ranked) expect(text).toContain(`(metadata @> ANY($5::jsonb[]) AND ${exactMatch(4, 3)})`); + // One attempt, one warning naming the statement; the second search neither looks nor tries. + expect(creates(s)).toHaveLength(1); + expect(lookups(s)).toBe(2); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain(`${INDEX_DDL};`); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index 0b54319ee9d..6fe750f9cf7 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -25,6 +25,9 @@ import { keywordIndexDdl, keywordIndexName, keywordTerms, + metadataIndexDdl, + metadataIndexName, + metadataScopeForms, qualified, schemaDdl, vectorLiteral, @@ -304,6 +307,10 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { private readonly tables = new Set(); /** Widths whose passage table's keyword index this adapter has created or found. */ private readonly keyed = new Set(); + /** Widths whose passage table's metadata index this adapter has found or created. */ + private readonly metadataIndexed = new Set(); + /** Widths whose passage table's metadata index this adapter could not create: searched by a scan, warned once. */ + private readonly metadataUnindexed = new Set(); /** The builder locks this adapter holds, by source id. */ private readonly builders = new Map(); /** @@ -647,7 +654,10 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { // organization filter so `topK` is filled from in-scope documents. Ids // and field names go as bound parameters. A `metadata` term holds for a // stored string or number equal to an id as text, or a list with such an - // element; a missing value or any other kind holds for nothing. + // element; a missing value or any other kind holds for nothing. It is + // written twice: as containment, a superset the metadata index serves + // (`metadataScopeForms`), so only the passages in scope are read and + // ranked, and as that exact match on each passage the index finds. const scopeTerms: string[] = []; for (const term of opts.scope) { if (term.ids.length === 0) continue; @@ -657,12 +667,15 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { scopeTerms.push(`source_record_id = ANY(${ids})`); continue; } + await this.ensureMetadataIndex(generation.dim); params.push(term.field); const value = `(metadata -> $${params.length}::text)`; + params.push(metadataScopeForms(term.field, term.ids)); scopeTerms.push( - `EXISTS (SELECT 1 FROM jsonb_array_elements(CASE jsonb_typeof(${value}) WHEN 'array' THEN ${value} ` + + `(metadata @> ANY($${params.length}::jsonb[]) AND ` + + `EXISTS (SELECT 1 FROM jsonb_array_elements(CASE jsonb_typeof(${value}) WHEN 'array' THEN ${value} ` + `ELSE jsonb_build_array(${value}) END) AS e(v) ` + - `WHERE jsonb_typeof(e.v) IN ('string', 'number') AND e.v #>> '{}' = ANY(${ids}))`, + `WHERE jsonb_typeof(e.v) IN ('string', 'number') AND e.v #>> '{}' = ANY(${ids})))`, ); } where.push(`(${scopeTerms.join(' OR ')})`); @@ -1083,6 +1096,45 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { this.keyed.add(dimensions); } + /** + * Makes the metadata index of a passage table made before the store kept one + * (`metadataIndexDdl`), at its first search with a `metadata` scope term; a + * table already checked is skipped. Looked up before it is made, so a table + * that has it is never locked for the statement. Making it holds the table's + * writes, not its reads, for as long as the build takes. Two processes making + * it at once: the one that loses finds it made. + * + * An index this adapter cannot create (a role without the right to) does not + * refuse the search: the index only makes a scoped search fast, and the + * statement holds the same exact match without it, so the search answers + * what it answered before the index existed, by a scan of the generation. + * Said once, with the statement to run, and not tried again by this adapter. + */ + private async ensureMetadataIndex(dimensions: number): Promise { + if (this.metadataIndexed.has(dimensions) || this.metadataUnindexed.has(dimensions)) return; + const pool = this.requirePool(); + const name = qualified(this.schema, metadataIndexName(dimensions)); + const present = async (): Promise => + (await pool.query<{ present: string | null }>('SELECT to_regclass($1) AS present', [name])).rows[0]?.present != null; + if (!(await present())) { + const statement = metadataIndexDdl(this.schema, dimensions); + try { + await pool.query(statement); + } catch (err) { + if (!(await present().catch(() => false))) { + this.metadataUnindexed.add(dimensions); + this.logger?.warn?.( + `knowledge-pgvector: the metadata index of the ${dimensions}-wide passage table could not be created ` + + `(${errorText(err)}); searches narrowed by a metadata scope term still answer, by a scan of every ` + + `passage of the source, and stay slow until a database owner runs: ${statement};`, + ); + return; + } + } + } + this.metadataIndexed.add(dimensions); + } + private async tableExists(dimensions: number): Promise { if (this.tables.has(dimensions)) return true; const found = await this.requirePool().query<{ present: string | null }>( diff --git a/packages/plugins/knowledge-pgvector/src/sql.ts b/packages/plugins/knowledge-pgvector/src/sql.ts index 17d60f70787..dbcc379307f 100644 --- a/packages/plugins/knowledge-pgvector/src/sql.ts +++ b/packages/plugins/knowledge-pgvector/src/sql.ts @@ -94,9 +94,71 @@ export function vectorTableDdl(schema: string, dimensions: number, vectorType: s // 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), + metadataIndexDdl(schema, dimensions), ]; } +/** The name of the metadata index of the passage table of one width. */ +export function metadataIndexName(dimensions: number): string { + return `${vectorTable(dimensions)}_metadata`; +} + +/** + * The statement that makes the metadata index of the passage table of one + * width: a GIN index on `metadata` with the `jsonb_path_ops` operator class, + * which serves `@>` (containment) and nothing else. A search narrowed by a + * `metadata` scope term ({@link metadataScopeForms}) reads the passages in + * scope through it instead of computing the distance of every passage of the + * generation. Built without `CONCURRENTLY`, as the table's other indexes: an + * interrupted concurrent build leaves an invalid index of this name, which + * `IF NOT EXISTS` would then take for a made one. + */ +export function metadataIndexDdl(schema: string, dimensions: number): string { + return `CREATE INDEX IF NOT EXISTS "${metadataIndexName(dimensions)}" ON ${qualified(schema, vectorTable(dimensions))} USING gin (metadata jsonb_path_ops)`; +} + +/** + * A scope id that a stored JSON number can print as: the text form + * PostgreSQL gives a `numeric` (`jsonb` keeps its numbers as one) — an + * optional minus, digits without a leading zero, an optional fraction, never + * an exponent. + */ +const NUMERIC_TEXT = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/; + +/** A surrogate without its pair, which the driver sends as U+FFFD. */ +const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? value`), which the metadata index + * ({@link metadataIndexDdl}) serves: for each id, `{field: id}` and + * `{field: [id]}` as strings, and, for an id a stored number prints as, the + * same two with the id as a number. + * + * A superset of the term's matches, never the match itself: a stored number + * is contained by every number of equal value (`1.50` by `1.5`), whatever its + * text, so the search keeps the exact match beside this one. Each value is + * JSON text for a bound `jsonb[]`; the id and the field are written well-formed + * first, as the driver sends a text parameter (a lone surrogate as U+FFFD), so + * the containment compares the same characters the exact match does. + */ +export function metadataScopeForms(field: string, ids: readonly string[]): string[] { + const key = JSON.stringify(wellFormed(field)); + const forms: string[] = []; + for (const raw of ids) { + const id = wellFormed(raw); + const text = JSON.stringify(id); + forms.push(`{${key}:${text}}`, `{${key}:[${text}]}`); + if (NUMERIC_TEXT.test(id)) forms.push(`{${key}:${id}}`, `{${key}:[${id}]}`); + } + return forms; +} + /** * The text-search configuration of the keyword leg: `simple` — lower-cased * words, no stemming and no stop words, so a code or a name is matched as it