Repository navigation
Expand file tree
/
Copy pathidf-once.live-postgres.test.ts
More file actions
117 lines (105 loc) · 5.07 KB
/
Copy pathidf-once.live-postgres.test.ts
File metadata and controls
117 lines (105 loc) · 5.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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);
});
}
});