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
11 changes: 11 additions & 0 deletions .changeset/38747-knowledge-pgvector-scope-gin.md
Original file line number Diff line number Diff line change
@@ -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<width>_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.
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Expand Down
Original file line number Diff line number Diff line change
@@ -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<string, unknown>): 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<string, unknown>, raw: Record<string, string> = {}) {
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<string[]> =>
(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<string[]> =>
(
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<string[]> => {
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();
});
});
Loading
Loading