|
| 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 | +}); |
0 commit comments