Skip to content

Commit 4a43d6c

Browse files
perf(knowledge-pgvector): compute each keyword term's IDF once per search (#38533)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XDXvJPPtrTGfdDYhWWpihq5)_ Fixes #38510 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:用 PostgreSQL 存储知识库的部署,中文整句检索的关键词一路 p95 从约 3.9 秒降到约 1.6 秒,排名一致(六次实测,218 个问题全部相同)。 - 为什么做:属于 AI 知识库检索这条主线,解决中日韩问题拆成多达 16 个词后、每个词的权重在每一行候选上重复计算拖慢检索的问题。 - 出错会怎样:碰到的是用 PostgreSQL 知识库检索的用户,最坏是检索变慢或排序变化;只改了一条查询语句,可直接撤回。 - 要你做的:无。 ## What changes The pgvector keyword score evaluated `ln(1.0 + (n - d + 0.5) / (d + 0.5))` for every term on every candidate row. A new materialized `idf` CTE computes each term's weight once per search from the one-row `stats`, and the keyword leg scores a candidate as `h.hN * w.wN` summed over its terms. The arithmetic stays `numeric` (no `float8`), so every score is digit-for-digit the per-row one and every tie keeps its order. No extension, no index, no fingerprint change, no new export; `sql.ts` is untouched. Read first, by risk: 1. `packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts`, the keyword-leg hunk in `search` (the `idf` CTE and the `kw` score): the only behaviour change. 2. `packages/plugins/knowledge-pgvector/src/__tests__/idf-once.live-postgres.test.ts`: takes the adapter's own statement and compares its score against an independently written per-row form on a live PostgreSQL. 3. `packages/plugins/knowledge-pgvector/src/__tests__/idf-once.test.ts`: the shape pin (one `ln()` per term, all inside `idf`, none in `kw`). ### Before / after (pgvector) Bench: PostgreSQL 16.15 + pgvector 0.6.0, 67,447 synthetic passages (10,368 docs; the piece 公司 is in 99.7% of passages), 218 unspaced zh questions, keyword leg alone (all-zero query vector), topK 10, 3 interleaved runs per side. Before = `origin/main` dccf836, after = this branch. Shared box, load average 4 to 7 during the runs, so read the ratio, not the absolutes. | run | p50 ms | p95 ms | max ms | rankings vs before1 | |:--|--:|--:|--:|:--| | before1 | 488 | 3,903 | 4,151 | (reference) | | after1 | 354 | 1,602 | 1,793 | 0 of 218 differ | | before2 | 490 | 3,840 | 4,054 | 0 of 218 differ | | after2 | 359 | 1,569 | 1,808 | 0 of 218 differ | | before3 | 596 | 3,910 | 4,318 | 0 of 218 differ | | after3 | 448 | 1,622 | 1,769 | 0 of 218 differ | By class, p95 before vs after: questions holding 公司 (33) 3,958-4,261 vs 1,747-1,784 ms; any 2-character piece (123) 3,931-3,975 vs 1,646-1,697 ms; only 3-character pieces (95) 514-658 vs 392-521 ms. ### Turso twin: measured, not changed `knowledge-turso` evaluates the same per-row expression in SQLite double arithmetic. Same corpus indexed through the real `TursoKnowledgeAdapter.upsert` into a local libSQL file, same 218 questions, 3 interleaved runs per side, with a scratch once-form (an `idf AS MATERIALIZED` CTE) against `origin/main`: | side | p50 ms | p95 ms | rankings | |:--|--:|--:|:--| | before (3 runs) | 405-422 | 1,026-1,066 | reference | | once-form (3 runs) | 411-419 | 973-999 | 0 of 218 differ in all 3 | About 5% on p95: a double `ln()` per row is cheap, and turso's time goes to the candidate scan of 2-character pieces (LIKE). Not worth a second adapter change in this PR, so `turso-adapter.ts` is untouched. ## Tests - New `idf-once.test.ts` (no database): for a 16-term unspaced question and a mixed word/substring question, the ranking statement holds exactly one `ln(` per term, all inside `idf AS MATERIALIZED (... FROM stats)`, none in `kw`, and `kw` scores `h.hN * w.wN ... FROM hits h CROSS JOIN idf w`; no `float8` anywhere. - New `idf-once.live-postgres.test.ts`: indexes a 7-passage fixture, records the statement the adapter sends, and re-runs its CTEs with a final SELECT comparing, as text, the adapter's own score expression against `hits x ln(1.0 + (n - d + 0.5) / (d + 0.5))` per row. Every candidate equal, the scores not all one value, `idf` exactly one row. - One-off ablations, not kept: the adapter restored to dccf836 turns all 4 new cases red; the weight mutated to `(d + 1.5)` turns both live cases red on the equality assertion, restored by blob hash. <details><summary>Readings (head 623da38)</summary> - `pnpm --filter @objectstack/knowledge-pgvector exec vitest run --maxWorkers=2` with `OS_TEST_POSTGRES_URL` and `OS_EXPECT_LIVE_DIALECT_MATRIX=1`: `Test Files 1 failed | 12 passed (13)`, `Tests 112 passed | 2 skipped (114)`. The failed file is `capability-mount.live-postgres.test.ts` at its line 119: it expects `resolveCapabilityArgument('knowledge', ...)` to equal `{ deploymentAdapter: 'pgvector' }`, and `@objectstack/core` now also answers `runtimeComposed: { declared: false }`. It fails the same way with this diff reverted, so it was already red on main (see Acceptance notes). - `pnpm --filter @objectstack/knowledge-pgvector typecheck`: exit 0; the test-layer check compiles both new files (`--listFiles` counts them in `tsconfig.json` and `tsconfig.test.json`). - `dispatch-gates --commands`: 67 families derived and run locally, 66 exit 0. `check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET, needs a full `pnpm build`): NOT MEASURED locally, CI runs it. `--ran`: 67 accounted, 66 run, 1 NOT MEASURED. </details> ## Acceptance notes - Already red on main, outside this claim's file surface: `capability-mount.live-postgres.test.ts` pins the knowledge capability argument as `{ deploymentAdapter: 'pgvector' }`, and core's `resolveCapabilityArgument` added `runtimeComposed` (merge 91fc398). CI runs the pgvector live files only when a PR touches `packages/plugins/knowledge-pgvector/**` (the `temporal_live` paths filter), so `Temporal Conformance (live PG + MySQL)` is expected to go red here on that file. Reported to the area seat; not fixed in this PR. - The class numbers come from a synthetic corpus, not a customer one. The ratio (about 2.4x on p95) is the reading to keep; the absolutes are from a loaded shared box. ## Verification Two minutes, against any PostgreSQL with pgvector: ``` OS_TEST_POSTGRES_URL=postgres://USER@HOST:PORT/DB pnpm --filter @objectstack/knowledge-pgvector exec vitest run src/__tests__/idf-once.live-postgres.test.ts src/__tests__/idf-once.test.ts ``` Expected: `Test Files 2 passed (2)`, `Tests 4 passed (4)`. To reproduce the bench: the scratch harness (a deterministic corpus generator, an `adapter.search` timer and a ranking diff) indexes the corpus through `PgvectorKnowledgeAdapter.upsert` with a dim-8 zero embedder, then times `adapter.search(q, { topK: 10 })` per question for the `origin/main` copy and the branch copy of `pgvector-adapter.ts` in alternation, and compares the rankings question by question. https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 3b900a8 commit 4a43d6c

4 files changed

Lines changed: 216 additions & 4 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/knowledge-pgvector': patch
3+
---
4+
5+
perf(knowledge-pgvector): the keyword leg computes each term's IDF once per search, not once per candidate row
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The keyword leg's IDF on a LIVE PostgreSQL: the statement a search sends
5+
* computes each term's weight once (`idf-once.test.ts` pins its shape), and
6+
* every candidate's score equals, digit for digit, the per-row form it
7+
* replaced, `hits × ln(1.0 + (n - d + 0.5) / (d + 0.5))` evaluated on each
8+
* row in the same `numeric` arithmetic — so the ranking, ties included, is
9+
* the one the per-row form gave.
10+
*/
11+
12+
import { afterAll, describe, expect, it } from 'vitest';
13+
import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai';
14+
import { poolFromPg, type PgPoolLike } from '../index.js';
15+
import { FakeEmbedder, PG_URL, liveStore, requireLiveCell } from './live-pg.testkit.js';
16+
17+
requireLiveCell('knowledge-pgvector keyword IDF');
18+
19+
const store = liveStore('kpg_idf');
20+
21+
const source: KnowledgeSource = {
22+
name: 'idf_once',
23+
label: 'idf_once',
24+
adapter: 'under_test',
25+
source: { kind: 'object', object: 'article', content: ['body'] },
26+
} as KnowledgeSource;
27+
28+
function doc(n: string, content: string): KnowledgeDocument {
29+
const id = `${source.name}:${n}`;
30+
return { id, sourceId: source.name, sourceRecordId: n, content, metadata: {}, chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }] };
31+
}
32+
33+
/** A pool that hands every statement on, and records each ranking statement with its values. */
34+
function recording(inner: PgPoolLike): { pool: PgPoolLike; ranked: Array<{ text: string; values: unknown[] }> } {
35+
const ranked: Array<{ text: string; values: unknown[] }> = [];
36+
const note = (text: string, values?: unknown[]) => {
37+
if (/\bkw AS \(/.test(text)) ranked.push({ text, values: values ?? [] });
38+
};
39+
return {
40+
ranked,
41+
pool: {
42+
query: async (text, values) => {
43+
note(text, values);
44+
return inner.query(text, values);
45+
},
46+
connect: async () => {
47+
const client = await inner.connect();
48+
return {
49+
query: async (text, values) => {
50+
note(text, values);
51+
return client.query(text, values);
52+
},
53+
release: (err) => client.release(err),
54+
};
55+
},
56+
} as PgPoolLike,
57+
};
58+
}
59+
60+
// Terms held by every passage, by most, by a few and by one, so the weights
61+
// span the range, and both kinds of match: a word term on the tsvector and a
62+
// substring term by LIKE.
63+
const PASSAGES = [
64+
'公司员工出差住宿标准为每晚三百元,pump X-200 维修',
65+
'公司仓库盘点每月一次,由物流部负责',
66+
'公司合同到期前三十天提醒客户续约',
67+
'公司出差审批由部门经理负责,pump 保修一年',
68+
'公司住宿费报销需要发票',
69+
'公司年假每年十天',
70+
'公司 X-200 型号的保修期为两年',
71+
];
72+
73+
describe.skipIf(!PG_URL)('knowledge-pgvector keyword IDF on a LIVE PostgreSQL', () => {
74+
afterAll(() => store.dropAll());
75+
76+
for (const query of ['公司出差住宿标准需要审批吗', 'pump X-200 公司 出差']) {
77+
it(`scores every candidate exactly as the per-row form does: ${query}`, async () => {
78+
const live = recording(poolFromPg(store.pool()));
79+
const adapter = store.adapter({ pool: live.pool, embedder: new FakeEmbedder() });
80+
await adapter.upsert(
81+
PASSAGES.map((p, i) => doc(String(i + 1), p)),
82+
{ source, reason: 'manual', index: { fingerprint: 'fp-idf', recipeHash: 'rh-idf' } },
83+
);
84+
const hits = await adapter.search(query, { source, topK: PASSAGES.length });
85+
expect(hits.length).toBeGreaterThan(0);
86+
expect(live.ranked).toHaveLength(1);
87+
const { text, values } = live.ranked[0];
88+
89+
// The statement's own steps (every CTE, so every bound value keeps its
90+
// place and type), and its own score expression.
91+
const steps = text.slice(0, text.search(/\s+SELECT p\.chunk_id, p\.document_id/));
92+
expect(steps).toMatch(/^WITH .*\bidf AS MATERIALIZED \(.*\bkw AS \(/s);
93+
const score = /SELECT h\.chunk_id, h\.distance, (.+?) AS score FROM hits h CROSS JOIN idf w/.exec(text)?.[1];
94+
expect(score).toBeDefined();
95+
const terms = (steps.match(/ AS h\d+\b/g) ?? []).length;
96+
expect(terms).toBeGreaterThan(1);
97+
98+
// The per-row form, written independently of the adapter.
99+
const perRow = Array.from(
100+
{ length: terms },
101+
(_, i) => `h.h${i} * ln(1.0 + (s.n - s.d${i} + 0.5) / (s.d${i} + 0.5))`,
102+
).join(' + ');
103+
const compared = await store.pool().query<{ chunk_id: string; once: string; per_row: string; weights: number }>(
104+
`${steps}
105+
SELECT h.chunk_id, (${score})::text AS once, (${perRow})::text AS per_row,
106+
(SELECT count(*) FROM idf)::int AS weights
107+
FROM hits h CROSS JOIN stats s CROSS JOIN idf w ORDER BY h.chunk_id`,
108+
values,
109+
);
110+
expect(compared.rows.length).toBeGreaterThan(1);
111+
expect(compared.rows[0].weights).toBe(1);
112+
for (const row of compared.rows) expect([row.chunk_id, row.once]).toEqual([row.chunk_id, row.per_row]);
113+
// The scores are not all one value, so the comparison sees the weights.
114+
expect(new Set(compared.rows.map((r) => r.once)).size).toBeGreaterThan(1);
115+
});
116+
}
117+
});
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The keyword leg's IDF, without a database: the statement a search sends
5+
* computes each term's weight once, in its own materialized step, and scores
6+
* a candidate by multiplying its hits by those weights, so no `ln()` runs per
7+
* candidate row. The live counterpart, `idf-once.live-postgres.test.ts`, holds
8+
* the scores equal to the per-row form.
9+
*/
10+
11+
import { describe, expect, it } from 'vitest';
12+
import type { KnowledgeSource } from '@objectstack/spec/ai';
13+
import { PgvectorKnowledgeAdapter, type PgPoolLike } from '../index.js';
14+
import { keywordTerms } from '../sql.js';
15+
import { FakeEmbedder } from './live-pg.testkit.js';
16+
17+
const source = { name: 'idf', label: 'idf', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource;
18+
19+
/** A store with one stable active generation, which records each ranking statement. */
20+
function recordingPool(): { pool: PgPoolLike; ranked: string[] } {
21+
const ranked: string[] = [];
22+
const answer = async <R>(text: string): Promise<{ rows: R[] }> => {
23+
if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.0' }] as R[] };
24+
if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] as R[] };
25+
if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) {
26+
return { rows: [{ generation: 1, fingerprint: 'fp', recipe_hash: 'rh', dim: 384, state: 'active' }] as R[] };
27+
}
28+
if (text.includes('AS distance')) ranked.push(text);
29+
return { rows: [] as R[] };
30+
};
31+
return { pool: { query: answer, connect: async () => ({ query: answer, release: () => undefined }) }, ranked };
32+
}
33+
34+
/** The text of the CTE `name` in `sql`, from its opening parenthesis to the one that closes it. */
35+
function cte(sql: string, name: string): string {
36+
const head = new RegExp(`\\b${name} AS (MATERIALIZED )?\\(`).exec(sql);
37+
expect(head, `the statement holds a CTE named ${name}`).not.toBeNull();
38+
let depth = 0;
39+
const start = head!.index + head![0].length - 1;
40+
for (let i = start; i < sql.length; i++) {
41+
if (sql[i] === '(') depth += 1;
42+
if (sql[i] === ')' && --depth === 0) return sql.slice(head!.index, i + 1);
43+
}
44+
throw new Error(`the CTE ${name} is not closed`);
45+
}
46+
47+
const lnCount = (text: string) => (text.match(/\bln\(/g) ?? []).length;
48+
49+
describe('knowledge-pgvector keyword IDF', () => {
50+
// A 16-term unspaced question (a figure, pieces of three and of two), and a
51+
// spaced one mixing a word term with a substring term.
52+
for (const query of ['出差住宿费2000元以下需要审批吗', 'pump X-200 出差']) {
53+
it(`computes each term's IDF once per search, not per candidate row: ${query}`, async () => {
54+
const { pool, ranked } = recordingPool();
55+
const adapter = new PgvectorKnowledgeAdapter({ id: 'idf', pool, embedder: new FakeEmbedder() });
56+
await adapter.search(query, { source, topK: 5, index: { fingerprint: 'fp' } });
57+
expect(ranked).toHaveLength(1);
58+
const sql = ranked[0];
59+
const terms = keywordTerms(query).length;
60+
expect(terms).toBeGreaterThan(1);
61+
62+
// One ln() per term in the whole statement, every one of them in the
63+
// materialized idf step, which reads the one-row stats and nothing else.
64+
const idf = cte(sql, 'idf');
65+
expect(idf).toMatch(/^idf AS MATERIALIZED \(/);
66+
expect(idf).toMatch(/ FROM stats\)$/);
67+
expect(lnCount(sql)).toBe(terms);
68+
expect(lnCount(idf)).toBe(terms);
69+
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}`);
70+
71+
// The score a candidate gets: its hits times the weights, no ln() per row.
72+
const kw = cte(sql, 'kw');
73+
expect(lnCount(kw)).toBe(0);
74+
const score = Array.from({ length: terms }, (_, i) => `h.h${i} * w.w${i}`).join(' + ');
75+
expect(kw).toContain(`SELECT h.chunk_id, h.distance, ${score} AS score FROM hits h CROSS JOIN idf w`);
76+
// No float8 cast anywhere in the arithmetic: numeric keeps every tie as it was.
77+
expect(sql).not.toMatch(/float8|double precision/);
78+
});
79+
}
80+
});

‎packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -675,9 +675,11 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
675675
onCandidate.push(`c.content ${op} $${params.length}::text`);
676676
}
677677
}
678-
const idf = onCandidate
679-
.map((_, i) => `h.h${i} * ln(1.0 + (s.n - s.d${i} + 0.5) / (s.d${i} + 0.5))`)
680-
.join(' + ');
678+
// Each term's IDF is computed once per search, in `idf`, and a candidate's
679+
// score multiplies its hits by those weights: written per row, the 16
680+
// `ln()` terms of a CJK question ran on every candidate. The arithmetic
681+
// stays `numeric`, so every score, and so every tie, is the per-row one.
682+
const score = onCandidate.map((_, i) => `h.h${i} * w.w${i}`).join(' + ');
681683
ctes.push(
682684
// Passages of equal keyword score are ranked by cosine distance, so the
683685
// keyword leg never reorders by chunk id what the vector leg ranks.
@@ -687,9 +689,12 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
687689
FROM cand c CROSS JOIN LATERAL (SELECT ${PASSAGE_TSVECTOR.replace('content', 'c.content')} AS tsv) v)`,
688690
`stats AS (SELECT (SELECT count(*) FROM ${table} WHERE ${inScope}) AS n,
689691
${onCandidate.map((_, i) => `coalesce(sum(h${i}), 0) AS d${i}`).join(', ')} FROM hits)`,
692+
`idf AS MATERIALIZED (SELECT ${onCandidate
693+
.map((_, i) => `ln(1.0 + (n - d${i} + 0.5) / (d${i} + 0.5)) AS w${i}`)
694+
.join(', ')} FROM stats)`,
690695
`kw AS (
691696
SELECT chunk_id, row_number() OVER (ORDER BY score DESC, distance, chunk_id) AS pos FROM (
692-
SELECT h.chunk_id, h.distance, ${idf} AS score FROM hits h CROSS JOIN stats s
697+
SELECT h.chunk_id, h.distance, ${score} AS score FROM hits h CROSS JOIN idf w
693698
) scored ORDER BY score DESC, distance, chunk_id LIMIT ${limit})`,
694699
);
695700
legs.push('SELECT chunk_id, NULL::bigint AS vpos, pos AS kpos FROM kw');

0 commit comments

Comments
 (0)