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
10 changes: 10 additions & 0 deletions .changeset/38510-keyword-idf-once.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@objectstack/knowledge-pgvector': patch
---

perf(knowledge-pgvector): the keyword leg computes each term's IDF once per search, not once per candidate row

Clause-②: no
Metadata-protocol: none

The keyword score evaluated `ln(1.0 + (n - d + 0.5) / (d + 0.5))` for every term on every candidate row. A Chinese, Japanese or Korean question carries up to 16 pieces, and a piece that most passages hold makes nearly every row a candidate, so most of a search went to those `ln()` calls. Each term's weight is now computed once, in a materialized step, and a candidate's score multiplies its hits by those weights. The arithmetic stays `numeric`, so every score, and every tie, is the one the per-row form gave: search results and their order do not change. On a 67,447-passage bench of 218 unspaced Chinese questions, keyword-leg p95 went from about 3.9 s to about 1.6 s. No extension, no index and no fingerprint change; nothing to do on upgrade.
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* The keyword leg's IDF on a LIVE PostgreSQL: the statement a search sends
* computes each term's weight once (`idf-once.test.ts` pins its shape), and
* every candidate's score equals, digit for digit, the per-row form it
* replaced, `hits × ln(1.0 + (n - d + 0.5) / (d + 0.5))` evaluated on each
* row in the same `numeric` arithmetic — so the ranking, ties included, is
* the one the per-row form gave.
*/

import { afterAll, describe, expect, it } from 'vitest';
import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai';
import { poolFromPg, type PgPoolLike } from '../index.js';
import { FakeEmbedder, PG_URL, liveStore, requireLiveCell } from './live-pg.testkit.js';

requireLiveCell('knowledge-pgvector keyword IDF');

const store = liveStore('kpg_idf');

const source: KnowledgeSource = {
name: 'idf_once',
label: 'idf_once',
adapter: 'under_test',
source: { kind: 'object', object: 'article', content: ['body'] },
} as KnowledgeSource;

function doc(n: string, content: string): KnowledgeDocument {
const id = `${source.name}:${n}`;
return { id, sourceId: source.name, sourceRecordId: n, content, metadata: {}, chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }] };
}

/** 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 (/\bkw 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,
};
}

// Terms held by every passage, by most, by a few and by one, so the weights
// span the range, and both kinds of match: a word term on the tsvector and a
// substring term by LIKE.
const PASSAGES = [
'公司员工出差住宿标准为每晚三百元,pump X-200 维修',
'公司仓库盘点每月一次,由物流部负责',
'公司合同到期前三十天提醒客户续约',
'公司出差审批由部门经理负责,pump 保修一年',
'公司住宿费报销需要发票',
'公司年假每年十天',
'公司 X-200 型号的保修期为两年',
];

describe.skipIf(!PG_URL)('knowledge-pgvector keyword IDF on a LIVE PostgreSQL', () => {
afterAll(() => store.dropAll());

for (const query of ['公司出差住宿标准需要审批吗', 'pump X-200 公司 出差']) {
it(`scores every candidate exactly as the per-row form does: ${query}`, async () => {
const live = recording(poolFromPg(store.pool()));
const adapter = store.adapter({ pool: live.pool, embedder: new FakeEmbedder() });
await adapter.upsert(
PASSAGES.map((p, i) => doc(String(i + 1), p)),
{ source, reason: 'manual', index: { fingerprint: 'fp-idf', recipeHash: 'rh-idf' } },
);
const hits = await adapter.search(query, { source, topK: PASSAGES.length });
expect(hits.length).toBeGreaterThan(0);
expect(live.ranked).toHaveLength(1);
const { text, values } = live.ranked[0];

// The statement's own steps (every CTE, so every bound value keeps its
// place and type), and its own score expression.
const steps = text.slice(0, text.search(/\s+SELECT p\.chunk_id, p\.document_id/));
expect(steps).toMatch(/^WITH .*\bidf AS MATERIALIZED \(.*\bkw AS \(/s);
const score = /SELECT h\.chunk_id, h\.distance, (.+?) AS score FROM hits h CROSS JOIN idf w/.exec(text)?.[1];
expect(score).toBeDefined();
const terms = (steps.match(/ AS h\d+\b/g) ?? []).length;
expect(terms).toBeGreaterThan(1);

// The per-row form, written independently of the adapter.
const perRow = Array.from(
{ length: terms },
(_, i) => `h.h${i} * ln(1.0 + (s.n - s.d${i} + 0.5) / (s.d${i} + 0.5))`,
).join(' + ');
const compared = await store.pool().query<{ chunk_id: string; once: string; per_row: string; weights: number }>(
`${steps}
SELECT h.chunk_id, (${score})::text AS once, (${perRow})::text AS per_row,
(SELECT count(*) FROM idf)::int AS weights
FROM hits h CROSS JOIN stats s CROSS JOIN idf w ORDER BY h.chunk_id`,
values,
);
expect(compared.rows.length).toBeGreaterThan(1);
expect(compared.rows[0].weights).toBe(1);
for (const row of compared.rows) expect([row.chunk_id, row.once]).toEqual([row.chunk_id, row.per_row]);
// The scores are not all one value, so the comparison sees the weights.
expect(new Set(compared.rows.map((r) => r.once)).size).toBeGreaterThan(1);
});
}
});
80 changes: 80 additions & 0 deletions packages/plugins/knowledge-pgvector/src/__tests__/idf-once.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* The keyword leg's IDF, without a database: the statement a search sends
* computes each term's weight once, in its own materialized step, and scores
* a candidate by multiplying its hits by those weights, so no `ln()` runs per
* candidate row. The live counterpart, `idf-once.live-postgres.test.ts`, holds
* the scores equal to the per-row form.
*/

import { describe, expect, it } from 'vitest';
import type { KnowledgeSource } from '@objectstack/spec/ai';
import { PgvectorKnowledgeAdapter, type PgPoolLike } from '../index.js';
import { keywordTerms } from '../sql.js';
import { FakeEmbedder } from './live-pg.testkit.js';

const source = { name: 'idf', label: 'idf', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource;

/** A store with one stable active generation, which records each ranking statement. */
function recordingPool(): { pool: PgPoolLike; ranked: string[] } {
const ranked: string[] = [];
const answer = async <R>(text: string): Promise<{ rows: R[] }> => {
if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.0' }] as R[] };
if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] 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);
return { rows: [] as R[] };
};
return { pool: { query: answer, connect: async () => ({ query: answer, release: () => undefined }) }, ranked };
}

/** The text of the CTE `name` in `sql`, from its opening parenthesis to the one that closes it. */
function cte(sql: string, name: string): string {
const head = new RegExp(`\\b${name} AS (MATERIALIZED )?\\(`).exec(sql);
expect(head, `the statement holds a CTE named ${name}`).not.toBeNull();
let depth = 0;
const start = head!.index + head![0].length - 1;
for (let i = start; i < sql.length; i++) {
if (sql[i] === '(') depth += 1;
if (sql[i] === ')' && --depth === 0) return sql.slice(head!.index, i + 1);
}
throw new Error(`the CTE ${name} is not closed`);
}

const lnCount = (text: string) => (text.match(/\bln\(/g) ?? []).length;

describe('knowledge-pgvector keyword IDF', () => {
// A 16-term unspaced question (a figure, pieces of three and of two), and a
// spaced one mixing a word term with a substring term.
for (const query of ['出差住宿费2000元以下需要审批吗', 'pump X-200 出差']) {
it(`computes each term's IDF once per search, not per candidate row: ${query}`, async () => {
const { pool, ranked } = recordingPool();
const adapter = new PgvectorKnowledgeAdapter({ id: 'idf', pool, embedder: new FakeEmbedder() });
await adapter.search(query, { source, topK: 5, index: { fingerprint: 'fp' } });
expect(ranked).toHaveLength(1);
const sql = ranked[0];
const terms = keywordTerms(query).length;
expect(terms).toBeGreaterThan(1);

// One ln() per term in the whole statement, every one of them in the
// materialized idf step, which reads the one-row stats and nothing else.
const idf = cte(sql, 'idf');
expect(idf).toMatch(/^idf AS MATERIALIZED \(/);
expect(idf).toMatch(/ FROM stats\)$/);
expect(lnCount(sql)).toBe(terms);
expect(lnCount(idf)).toBe(terms);
for (let i = 0; i < terms; i++) expect(idf).toContain(`ln(1.0 + (n - d${i} + 0.5) / (d${i} + 0.5)) AS w${i}`);

// The score a candidate gets: its hits times the weights, no ln() per row.
const kw = cte(sql, 'kw');
expect(lnCount(kw)).toBe(0);
const score = Array.from({ length: terms }, (_, i) => `h.h${i} * w.w${i}`).join(' + ');
expect(kw).toContain(`SELECT h.chunk_id, h.distance, ${score} AS score FROM hits h CROSS JOIN idf w`);
// No float8 cast anywhere in the arithmetic: numeric keeps every tie as it was.
expect(sql).not.toMatch(/float8|double precision/);
});
}
});
13 changes: 9 additions & 4 deletions packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -675,9 +675,11 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
onCandidate.push(`c.content ${op} $${params.length}::text`);
}
}
const idf = onCandidate
.map((_, i) => `h.h${i} * ln(1.0 + (s.n - s.d${i} + 0.5) / (s.d${i} + 0.5))`)
.join(' + ');
// Each term's IDF is computed once per search, in `idf`, and a candidate's
// score multiplies its hits by those weights: written per row, the 16
// `ln()` terms of a CJK question ran on every candidate. The arithmetic
// stays `numeric`, so every score, and so every tie, is the per-row one.
const score = onCandidate.map((_, i) => `h.h${i} * w.w${i}`).join(' + ');
ctes.push(
// Passages of equal keyword score are ranked by cosine distance, so the
// keyword leg never reorders by chunk id what the vector leg ranks.
Expand All @@ -687,9 +689,12 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
FROM cand c CROSS JOIN LATERAL (SELECT ${PASSAGE_TSVECTOR.replace('content', 'c.content')} AS tsv) v)`,
`stats AS (SELECT (SELECT count(*) FROM ${table} WHERE ${inScope}) AS n,
${onCandidate.map((_, i) => `coalesce(sum(h${i}), 0) AS d${i}`).join(', ')} FROM hits)`,
`idf AS MATERIALIZED (SELECT ${onCandidate
.map((_, i) => `ln(1.0 + (n - d${i} + 0.5) / (d${i} + 0.5)) AS w${i}`)
.join(', ')} FROM stats)`,
`kw AS (
SELECT chunk_id, row_number() OVER (ORDER BY score DESC, distance, chunk_id) AS pos FROM (
SELECT h.chunk_id, h.distance, ${idf} AS score FROM hits h CROSS JOIN stats s
SELECT h.chunk_id, h.distance, ${score} AS score FROM hits h CROSS JOIN idf w
) scored ORDER BY score DESC, distance, chunk_id LIMIT ${limit})`,
);
legs.push('SELECT chunk_id, NULL::bigint AS vpos, pos AS kpos FROM kw');
Expand Down
Loading