diff --git a/packages/plugins/knowledge-pgvector/bench/README.md b/packages/plugins/knowledge-pgvector/bench/README.md new file mode 100644 index 00000000000..00c4d9b0f07 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/bench/README.md @@ -0,0 +1,97 @@ +# knowledge-pgvector search bench + +Real `search_knowledge` calls — the tool executor of `@objectstack/service-knowledge` +over a real `KnowledgeService`, this store and ObjectQL + SqlDriver — on any PostgreSQL +with pgvector, timed per segment at each record-scope fraction × concurrency. It +measures and fixes nothing. Nothing here is published: the package's `files` is +`dist`, `README.md` and `CHANGELOG.md`, and vitest runs only `instrument.test.mjs`. + +## Run it + +```bash +pnpm --filter '@objectstack/knowledge-pgvector...' build # the bench loads the built dist; OS_SKIP_DTS=1 is fine +node packages/plugins/knowledge-pgvector/bench/run.mjs \ + --pg-url postgres://USER@HOST:5432/DB --passages 60000 --dims 1024 --isolate-scope --keep +node packages/plugins/knowledge-pgvector/bench/run.mjs --pg-url … --passages 60000 --dims 1024 --reuse --cache cold +``` + +The role needs `CREATE` on the database (the run makes two schemas) and the `vector` +extension installed or installable. `--help` lists every flag; the ones that shape a +reading: + +| flag | default | meaning | +|:--|:--|:--| +| `--pg-url` | `$OS_BENCH_PG_URL` | the database; the run makes `os_kbench_` (records) and `os_kbench__k` (the store) there and drops both at the end unless `--keep` | +| `--passages` / `--dims` / `--units` | 2000 / 1024 / 100 | one passage per record, spread evenly over the units | +| `--scopes` | `1,10,30,100,none` | the record scope as a % of units (so of passages); `none` is the unscoped run | +| `--concurrency` | `1,5,10,20` | closed-loop clients, each issuing its next search when the last returns | +| `--searches` | 100 | timed searches per cell (the sample count of every percentile in that cell) | +| `--searches-per-question` | 1 | searches one simulated question issues back to back | +| `--top-k`, `--granularity`, `--group-by unit` | 5, chunk | the `search_knowledge` arguments | +| `--cache` | `warm` | `warm`: `--warmup` untimed searches before each cell; `cold`: a fresh store pool per cell and no warm-up (see below) | +| `--pool-max`, `--connect-timeout-ms` | 4, 5000 | the store's pool, as `KnowledgePgvectorPlugin` builds it by default | +| `--embedder` | `fake` | `fake`: words hashed into slots, in process, no network; `openai`: an OpenAI-compatible `/embeddings` at `OS_BENCH_EMBEDDER_URL` with `OS_BENCH_EMBEDDER_MODEL` (and `OS_BENCH_EMBEDDER_API_KEY`); every passage is embedded once at build | +| `--queries FILE` | synthetic | a JSON array of question strings | +| `--isolate-scope` | off | the derived scope-predicate pass after each scoped cell | +| `--reuse` / `--keep` | off | keep a seeded dataset between runs (a reuse still walks every record once: a no-op rebuild) | + +It writes the JSON to `--out` (default `$TMPDIR/os-kbench/-.json`) and +prints a markdown table. + +## What one search records + +Each search runs inside its own `AsyncLocalStorage` store, so concurrent searches through +the same wrappers are attributed to the right one. Every segment is read through a seam the +code already takes — no file under either package's `src/` is changed: + +| segment | seam | what it is | +|:--|:--|:--| +| `embed` | the adapter's `embedder` option | each embed call of the search (one per round per source) | +| `pool_wait` | the adapter's `pool` option | each checkout of a pooled connection: a one-shot query's, or one the store holds for a transaction | +| `ranking` | the same pool | the ranking statement's execution, one-shot or inside the store's transaction: vector leg, keyword leg when the query has keyword terms, and the scope predicate | +| `other_sql` | the same pool | the store's other statements: the generation read, and a transaction's own `BEGIN`, `SET LOCAL` and `COMMIT` | +| `visible_ids` | the service's `dataEngine` option | the caller's readable record ids, read before ranking | +| `permission_recheck` | the same engine | every hit re-read as the caller after ranking | +| `system_read` | the same engine | reads the service runs as the system (freshness, verification) | +| `unaccounted` | — | the call's wall time minus every segment: the service's, the tool's and the adapter's own work | + +Per cell: p50 / p95 / max / mean of the total and of each segment, each with its sample +count; hit count; `backfillShare` (the share of searches whose source was searched a +second time, the refill round; scoped and unscoped cells are separate rows); adapter calls +per search; embedding-call failures; failed and refused searches with their codes; empty +answers; the service's `error` lines and how many of them say `search failed`; the +ranking statements' shapes (how many carried the keyword leg or each scope term); the +store tables' block reads and hits during the cell; and the machine shape (client CPUs and +memory; server version, pgvector version and memory settings). + +The unit test pins which statement is the ranking one, what its WHERE holds, and how many +calls of each kind one search makes, over the real adapter and service from source. It +never pins a duration. + +## The scope predicate is not an in-situ segment + +The store sends the record scope as a conjunct of the ranking statement's one WHERE, so +inside a search its cost cannot be told from the vector leg's: `ranking` carries both, +and the table says `NOT MEASURED` for it. With `--isolate-scope` each scoped cell is +followed by a derived pass, out of situ: on one connection, serially, the cell's last +ranking statement, the same WHERE as a bare `count(*)`, and the source-and-generation +WHERE as a bare `count(*)`, each `--isolate-repeats` times, timed by the server +(`EXPLAIN (ANALYZE, TIMING OFF)`). `scopePredicateMsP50` is scoped count − base count; +`rankingBeyondPredicateMsP50` is ranking − scoped count. The plans' scan nodes are +recorded beside them, so a reader sees whether the three read the table the same way, and +the rows in scope give the real selectivity. Measuring it in situ needs the store to time +its own statement parts, a change to `src/` this bench does not make. + +## Cold and warm + +`warm` runs `--warmup` untimed searches before each cell on the same pool. `cold` builds a +fresh store pool for each cell and runs no warm-up; a client cannot flush the server's +buffer cache or the OS page cache, so for a true cold read restart PostgreSQL and drop the +OS cache before the run. `knowledgeTableBlocks.read` in each cell shows how cold it was. + +## Quoting a number + +A number from this bench is quoted only from a run that has passed review, with the +JSON's `machine`, `parameters` and `dataset` beside it. The data is synthetic (a +3,000-word vocabulary, about 60 words a passage) and the caller is a non-system user over +an engine with no security plugin, so the re-check reads every row it asks for. diff --git a/packages/plugins/knowledge-pgvector/bench/instrument.mjs b/packages/plugins/knowledge-pgvector/bench/instrument.mjs new file mode 100644 index 00000000000..6b2b2356f81 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/bench/instrument.mjs @@ -0,0 +1,362 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Per-search segment timing of a `search_knowledge` call over this store, + * read entirely through seams the code already takes — nothing in `src/` of + * this package or of `@objectstack/service-knowledge` is changed or patched: + * + * | segment | seam | + * |:-------------------|:------------------------------------------------------------| + * | `embed` | the adapter's `embedder` option (an `IEmbedder` wrapper) | + * | `pool_wait` | the adapter's `pool` option (a `PgPoolLike` wrapper): each checkout, one-shot or held | + * | `ranking` | the same pool: the ranking statement's execution, one-shot or inside a transaction | + * | `other_sql` | the same pool: every other statement of a search, a transaction's own included | + * | `visible_ids` | the service's `dataEngine` option: the caller's readable ids | + * | `permission_recheck` | the same engine: the re-read of every hit as the caller | + * | `system_read` | the same engine: reads the service runs as the system | + * | `adapter` | the adapter as registered with the service (a wrapper) | + * + * The SCOPE PREDICATE is not a segment here: the store sends the record scope + * as a conjunct of the ranking statement's one WHERE, so its cost is inside + * `ranking` and no seam above can separate it. `run.mjs --isolate-scope` + * derives it out of situ ({@link extractRankingWhere}); see README.md. + * + * Each search runs inside an `AsyncLocalStorage` store, so concurrent + * searches through the same wrappers are attributed to the right search. A + * segment is the SUM of the awaited calls of that kind in one search; the + * service issues them one after another for one source, so with one source + * they do not overlap. + * + * This module imports no workspace package: the unit test drives it over the + * real adapter and service from source, `run.mjs` over their built `dist`. + */ + +import { AsyncLocalStorage } from 'node:async_hooks'; +import { performance } from 'node:perf_hooks'; + +/** The segments a search record carries, each a sum of milliseconds. */ +export const SEGMENTS = Object.freeze([ + 'embed', + 'pool_wait', + 'ranking', + 'other_sql', + 'visible_ids', + 'permission_recheck', + 'system_read', + 'other_engine', +]); + +/** A fresh, empty record of one search. */ +function emptyRecord(meta) { + const ms = {}; + const calls = {}; + for (const name of SEGMENTS) { + ms[name] = 0; + calls[name] = 0; + } + return { + meta, + ms, + calls, + embedFailures: 0, + /** One entry per `adapter.search` call: what it was asked, what it answered, how long it took. */ + adapterCalls: [], + /** The ranking statements, in order: their shape, and (when kept) text and parameters. */ + rankings: [], + /** Statement kinds sent outside the ranking statement, by kind. */ + otherSqlKinds: {}, + }; +} + +/** + * The recorder every wrapper reports to. `run(meta, fn)` runs `fn` as one + * search and answers `{ value, error, record, totalMs }`; a call made outside + * any `run` is not recorded. + */ +export function createSearchRecorder({ keepStatements = false } = {}) { + const als = new AsyncLocalStorage(); + return { + keepStatements, + current: () => als.getStore(), + add(segment, ms) { + const record = als.getStore(); + if (record === undefined) return; + record.ms[segment] += ms; + record.calls[segment] += 1; + }, + async run(meta, fn) { + const record = emptyRecord(meta); + const started = performance.now(); + try { + const value = await als.run(record, fn); + return { value, record, totalMs: performance.now() - started }; + } catch (error) { + return { error, record, totalMs: performance.now() - started }; + } + }, + }; +} + +/** What a statement is, by the text the store sends. */ +export function classifyStatement(text) { + if (/\bAS distance\b/.test(text) && /\bWITH\s+(vec|cand)\s+AS\s*\(/.test(text)) return 'ranking'; + if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) return 'generations'; + if (text.includes('to_regclass')) return 'table_check'; + if (text.includes('FROM pg_extension')) return 'extension'; + if (/^\s*(BEGIN|COMMIT|ROLLBACK|SET LOCAL)\b/i.test(text)) return 'transaction'; + return 'other'; +} + +/** + * The shape of a ranking statement: which legs it carries, and which scope + * terms its WHERE holds. The flags are read from the statement text, so a + * change of the store's SQL that this no longer recognises reads as `false` + * everywhere — the unit test pins them against the real adapter. + */ +export function rankingShape(text) { + return { + vectorLeg: /\bvec\s+AS\s*\(/.test(text), + keywordLeg: /\bkw\s+AS\s*\(/.test(text), + organizationFilter: /organization_id = ANY\(/.test(text), + recordScope: /source_record_id = ANY\(/.test(text), + metadataScope: /jsonb_array_elements\(CASE jsonb_typeof\(/.test(text), + }; +} + +/** + * The passage table, the WHERE of the vector leg and the parameters it reads, + * from one ranking statement and its parameters: the WHERE is everything the + * store filters on (source, generation, organizations, record scope, metadata + * filter) and references `$1` up to the parameter before the leg's `LIMIT`. + * `undefined` when the statement has no vector leg or its text is not the + * shape this reads (then `run.mjs --isolate-scope` says NOT MEASURED). + */ +export function extractRankingWhere(text, params) { + const leg = /vec\s+AS\s*\([\s\S]*?FROM\s+(\S+)\s+WHERE\s+([\s\S]*?)\s*\)\s*ranked\s+WHERE\s+distance\s*<\s*1\s+ORDER BY distance, chunk_id LIMIT \$(\d+)\)/.exec( + text, + ); + if (leg === null) return undefined; + const limitParam = Number(leg[3]); + if (!Number.isInteger(limitParam) || limitParam < 3 || !Array.isArray(params) || params.length < limitParam) return undefined; + return { table: leg[1], where: leg[2], params: params.slice(0, limitParam - 1) }; +} + +/** + * An `IEmbedder` that times each `embed` call into `embed` and counts the + * calls that throw. `dimensions`, `model` and `id` are read through, so the + * store's fingerprint is the wrapped embedder's. + */ +export function timedEmbedder(embedder, recorder) { + return { + get id() { + return embedder.id; + }, + get dimensions() { + return embedder.dimensions; + }, + get model() { + return embedder.model; + }, + async embed(texts) { + const started = performance.now(); + try { + return await embedder.embed(texts); + } catch (err) { + const record = recorder.current(); + if (record !== undefined) record.embedFailures += 1; + throw err; + } finally { + recorder.add('embed', performance.now() - started); + } + }, + }; +} + +/** + * A checked-out connection whose `query` is timed into `ranking` or + * `other_sql` by {@link classifyStatement} — the transaction's own `BEGIN`, + * `SET LOCAL …` and `COMMIT` / `ROLLBACK` included, as `transaction` — and + * whose `release` is the connection's own, called with what the caller passes. + */ +function timedClient(client, recorder) { + return { + async query(text, params) { + const kind = classifyStatement(text); + const started = performance.now(); + try { + return await client.query(text, params); + } finally { + const ms = performance.now() - started; + const record = recorder.current(); + if (record !== undefined) { + if (kind === 'ranking') { + recorder.add('ranking', ms); + record.rankings.push({ + ms, + shape: rankingShape(text), + ...(recorder.keepStatements ? { text, params } : {}), + }); + } else { + recorder.add('other_sql', ms); + record.otherSqlKinds[kind] = (record.otherSqlKinds[kind] ?? 0) + 1; + } + } + } + }, + release: (err) => client.release(err), + }; +} + +/** + * A `PgPoolLike` over `base` (a `poolFromPg(pg.Pool)`, or any pool of that + * shape), timing BOTH ways the store sends a statement: + * + * - a one-shot `query`, taken apart as a pooled query is: a checkout (timed + * into `pool_wait`), the statement on that connection, the release — with + * the error, when the statement failed, as `pg.Pool#query` does; + * - a checkout the store holds itself (`connect`, its transactions — the + * ranking statement runs in one once it carries a `SET LOCAL` time limit): + * the checkout timed into `pool_wait`, every statement on the connection + * timed as above, `release` passed through as the store calls it. + * + * `connectSession` (a build's builder lock, a connection outside the pool) is + * passed through untimed: a search takes none. + */ +export function timedPool(base, recorder) { + const checkout = async () => { + const waitStarted = performance.now(); + try { + return timedClient(await base.connect(), recorder); + } finally { + recorder.add('pool_wait', performance.now() - waitStarted); + } + }; + return { + async query(text, params) { + const client = await checkout(); + let failed; + try { + return await client.query(text, params); + } catch (err) { + failed = err instanceof Error ? err : new Error(String(err)); + throw err; + } finally { + client.release(failed); + } + }, + connect: checkout, + ...(typeof base.connectSession === 'function' ? { connectSession: () => base.connectSession() } : {}), + }; +} + +/** + * What one `IDataEngine#find` of a search is for, by the arguments the + * knowledge service passes (`knowledge-service.ts`): a read under a SYSTEM + * context (freshness, verification) is `system_read`; as the caller, a read + * of hits by `id $in` is the `permission_recheck`, a read of ids only with a + * `limit` is `visible_ids` (the caller's readable records, before ranking). + */ +export function classifyEngineRead(query, options) { + const ctx = (query && query.context) ?? (options && options.context); + if (ctx && ctx.isSystem === true) return 'system_read'; + const where = query && query.where; + const byIds = where && typeof where === 'object' && where.id && typeof where.id === 'object' && Array.isArray(where.id.$in); + if (ctx && byIds) return 'permission_recheck'; + const fields = query && query.fields; + if (ctx && Array.isArray(fields) && fields.length === 1 && fields[0] === 'id' && typeof query.limit === 'number') { + return 'visible_ids'; + } + return 'other_engine'; +} + +/** + * The data engine the service is constructed with, with its `find` timed by + * {@link classifyEngineRead}; every other member is the engine's own. + */ +export function timedEngine(engine, recorder) { + return new Proxy(engine, { + get(target, prop, receiver) { + if (prop === 'find') { + return async (object, query, options) => { + const kind = classifyEngineRead(query, options); + const started = performance.now(); + try { + return await target.find(object, query, options); + } finally { + recorder.add(kind, performance.now() - started); + } + }; + } + const value = Reflect.get(target, prop, target); + return typeof value === 'function' ? value.bind(target) : value; + }, + }); +} + +/** + * The adapter as the service sees it, recording each `search` call: the + * `topK` it was asked (a refill round asks `topK × 20`), how many hits it + * answered, how long it took. Every other member is the adapter's own. + */ +export function timedAdapter(adapter, recorder) { + return Object.assign(Object.create(adapter), { + async search(query, opts) { + const started = performance.now(); + let answered; + try { + const hits = await adapter.search(query, opts); + answered = hits.length; + return hits; + } finally { + const record = recorder.current(); + if (record !== undefined) { + record.adapterCalls.push({ + source: opts.source.name, + asked: opts.topK, + answered: answered ?? null, + scoped: opts.scope !== undefined, + ms: performance.now() - started, + }); + } + } + }, + }); +} + +/** + * What one finished search record says, flat: the segments, how many rounds + * each source was searched (two = a refill ran), and the time no segment + * accounts for (the service's own work, the tool's, the adapter's JS). + */ +export function summarizeRecord(outcome) { + const { record, totalMs } = outcome; + const roundsBySource = {}; + for (const call of record.adapterCalls) roundsBySource[call.source] = (roundsBySource[call.source] ?? 0) + 1; + const rounds = Math.max(0, ...Object.values(roundsBySource)); + const accounted = SEGMENTS.reduce((sum, name) => sum + record.ms[name], 0); + return { + totalMs, + ok: outcome.error === undefined, + ...(outcome.error === undefined + ? { hits: Array.isArray(outcome.value?.hits) ? outcome.value.hits.length : 0 } + : { errorCode: outcome.error?.code ?? null, errorMessage: String(outcome.error?.message ?? outcome.error) }), + refused: Array.isArray(outcome.value?.refused) ? outcome.value.refused.length : 0, + ms: { ...record.ms }, + calls: { ...record.calls }, + embedFailures: record.embedFailures, + adapterCalls: record.adapterCalls.length, + rounds, + refilled: rounds > 1, + rankingShapes: record.rankings.map((r) => r.shape), + otherSqlKinds: { ...record.otherSqlKinds }, + unaccountedMs: Math.max(0, totalMs - accounted), + }; +} + +/** The nearest-rank percentile `p` (0–100) of `values`; `null` for none. */ +export function percentile(values, p) { + if (values.length === 0) return null; + const sorted = [...values].sort((a, b) => a - b); + const rank = Math.max(1, Math.ceil((p / 100) * sorted.length)); + return sorted[Math.min(rank, sorted.length) - 1]; +} diff --git a/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs b/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs new file mode 100644 index 00000000000..0f75ace6f3c --- /dev/null +++ b/packages/plugins/knowledge-pgvector/bench/instrument.test.mjs @@ -0,0 +1,297 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The bench's segment seams over the REAL adapter and the REAL knowledge + * service (from source), with no database: a fake pool answers the store's + * statements and a fake engine the service's reads. Pinned: which statement is + * the ranking one and what its WHERE holds, how many calls of each kind one + * `search_knowledge` makes, and that a failed embed is counted — statement + * shape and call counts only, never a duration. When the store's SQL or the + * service's read shapes change, this file reds before `run.mjs` mislabels a + * segment. + */ + +import { describe, expect, it } from 'vitest'; +import { KnowledgeService, createKnowledgeTools } from '@objectstack/service-knowledge'; +import { PgvectorKnowledgeAdapter } from '../src/index.ts'; +import { + classifyStatement, + createSearchRecorder, + extractRankingWhere, + rankingShape, + summarizeRecord, + timedAdapter, + timedEmbedder, + timedEngine, + timedPool, +} from './instrument.mjs'; + +const DIMS = 8; +const TOP_K = 5; + +const CLAUSE_SCHEMA = { + name: 'clause', + fields: { + title: { type: 'text' }, + body: { type: 'textarea' }, + unit: { type: 'lookup', reference: 'unit' }, + }, +}; +const UNIT_SCHEMA = { name: 'unit', fields: { name: { type: 'text' } } }; +const SOURCE = { + name: 'clauses', + label: 'clauses', + adapter: 'pgvector', + source: { kind: 'object', object: 'clause', content: ['title', 'body'], metadataFields: ['unit'] }, +}; +const CALLER = { userId: 'reader', isSystem: false }; +const SYSTEM = { userId: 'system', isSystem: true }; + +/** A store with one active generation whose fingerprint is the one the service searches under, and 30 ranked passages. */ +function fakeStore() { + const sent = []; + const state = { fingerprint: undefined }; + const answer = async (text, params) => { + sent.push({ text, params }); + if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.7' }] }; + if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] }; + if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) { + return { rows: [{ generation: 1, fingerprint: state.fingerprint ?? null, recipe_hash: null, dim: DIMS, state: 'active' }] }; + } + if (classifyStatement(text) === 'ranking') { + return { + rows: Array.from({ length: 30 }, (_, i) => ({ + chunk_id: `ch_${i}`, + document_id: `doc_${i}`, + source_record_id: `rec_${i}`, + content: `passage ${i}`, + title: null, + metadata: { unit: 'u1' }, + doc_hash: null, + heading_path: null, + vpos: i + 1, + kpos: null, + })), + }; + } + return { rows: [] }; + }; + const pool = { query: answer, connect: async () => ({ query: answer, release: () => undefined }) }; + return { pool, sent, state }; +} + +/** Reads as the service makes them: hits by `id $in`, the caller reads only `rec_0`; the system reads all. */ +function fakeEngine() { + const reads = []; + return { + reads, + engine: { + getSchema: (name) => (name === 'clause' ? CLAUSE_SCHEMA : name === 'unit' ? UNIT_SCHEMA : undefined), + async find(object, query, options) { + reads.push({ object, query, options }); + const ctx = query?.context ?? options?.context; + const ids = query?.where?.id?.$in ?? []; + return ids.filter((id) => ctx?.isSystem || id === 'rec_0').map((id) => ({ id })); + }, + }, + }; +} + +function setup({ failEmbed = false } = {}) { + const recorder = createSearchRecorder({ keepStatements: true }); + const store = fakeStore(); + const { engine, reads } = fakeEngine(); + const embedder = { + id: 'unit', + dimensions: DIMS, + model: 'unit-model', + embed: async (texts) => { + if (failEmbed) throw new Error('embedder down'); + return texts.map(() => Array.from({ length: DIMS }, (_, i) => (i === 0 ? 1 : 0))); + }, + }; + const adapter = new PgvectorKnowledgeAdapter({ + id: 'pgvector', + pool: timedPool(store.pool, recorder), + embedder: timedEmbedder(embedder, recorder), + }); + // The store answers under whatever fingerprint the service searches with. + const fingerprinted = Object.assign(Object.create(adapter), { + search(query, opts) { + store.state.fingerprint = opts.index?.fingerprint; + return adapter.search(query, opts); + }, + }); + const errors = []; + const svc = new KnowledgeService({ + dataEngine: timedEngine(engine, recorder), + logger: { debug: () => undefined, warn: () => undefined, error: (m) => errors.push(m) }, + }); + svc.registerAdapter('pgvector', timedAdapter(fingerprinted, recorder)); + svc.registerSource(SOURCE); + const tools = createKnowledgeTools(svc); + const search = async (input, ctx) => recorder.run({}, () => tools.searchKnowledge(input, ctx)); + return { search, store, reads, errors }; +} + +describe('bench instrument — segment seams over the real adapter and service', () => { + it('a caller the re-check narrows: two rounds, each one embed, one ranking statement and one re-check', async () => { + const { search } = setup(); + const outcome = await search({ query: 'leave policy', topK: TOP_K }, CALLER); + expect(outcome.error).toBeUndefined(); + const s = summarizeRecord(outcome); + expect(s.hits).toBe(1); + // topK × 5, then the refill's topK × 20 (the service's SEARCH_FIRST_ROUND_FACTOR and SEARCH_REFILL_FACTOR). + expect(outcome.record.adapterCalls.map((c) => c.asked)).toEqual([TOP_K * 5, TOP_K * 20]); + expect(s.rounds).toBe(2); + expect(s.refilled).toBe(true); + expect(s.calls.embed).toBe(2); + expect(s.calls.ranking).toBe(2); + expect(s.calls.permission_recheck).toBe(2); + // The caller's readable ids, read once before ranking (unscoped search). + expect(s.calls.visible_ids).toBe(1); + // Every ranking statement went out on a timed checkout, one-shot or held for a transaction. + expect(s.calls.pool_wait).toBeGreaterThanOrEqual(s.calls.ranking); + expect(s.embedFailures).toBe(0); + }); + + it('the system identity: one round, no re-check, no readable-id read', async () => { + const { search } = setup(); + const s = summarizeRecord(await search({ query: 'leave policy', topK: TOP_K }, SYSTEM)); + expect(s.rounds).toBe(1); + expect(s.refilled).toBe(false); + expect(s.calls.ranking).toBe(1); + expect(s.calls.permission_recheck).toBe(0); + expect(s.calls.visible_ids).toBe(0); + }); + + it('a parent scope is a metadata conjunct of the ranking statement WHERE, which extractRankingWhere returns with its parameters', async () => { + const { search } = setup(); + const outcome = await search({ query: 'leave policy', topK: TOP_K, scope: [{ object: 'unit', ids: ['u1', 'u2'] }] }, CALLER); + expect(outcome.error).toBeUndefined(); + const s = summarizeRecord(outcome); + // A parent term skips the readable-id narrowing. + expect(s.calls.visible_ids).toBe(0); + const [first] = outcome.record.rankings; + expect(first.shape).toEqual({ + vectorLeg: true, + keywordLeg: true, + organizationFilter: false, + recordScope: false, + metadataScope: true, + }); + const parts = extractRankingWhere(first.text, first.params); + expect(parts).toBeDefined(); + expect(parts.table).toMatch(/"knowledge_vec_d8"$/); + 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']); + const highest = Math.max(...[...parts.where.matchAll(/\$(\d+)/g)].map((m) => Number(m[1]))); + expect(highest).toBe(parts.params.length); + }); + + it('a record scope is a record conjunct; a statement with no vector leg is not taken apart', () => { + expect(rankingShape("WITH vec AS (SELECT 1 AS distance FROM t WHERE source_record_id = ANY($3::text[]))").recordScope).toBe(true); + expect(extractRankingWhere('WITH cand AS (SELECT chunk_id, 0 AS distance FROM t WHERE x)', ['a', 1, 5])).toBeUndefined(); + }); + + it('a failed embed is counted, and the search answers no hit with the service\'s "search failed" line', async () => { + const { search, errors } = setup({ failEmbed: true }); + const outcome = await search({ query: 'leave policy', topK: TOP_K }, CALLER); + const s = summarizeRecord(outcome); + expect(s.embedFailures).toBe(1); + expect(s.calls.ranking).toBe(0); + expect(s.ok).toBe(true); + expect(s.hits).toBe(0); + expect(errors.filter((m) => /search failed/.test(m))).toHaveLength(1); + }); +}); + +describe('bench instrument — the pool seam, both ways a statement is sent', () => { + const RANKING = + 'WITH vec AS (SELECT chunk_id, row_number() OVER (ORDER BY distance, chunk_id) AS pos FROM (SELECT chunk_id, ' + + 'embedding <=> $3 AS distance FROM t WHERE source_id = $1 AND generation = $2) ranked) SELECT 1'; + + /** A base pool that counts checkouts and releases, and answers every statement after a turn of the event loop. */ + function countingBase({ fail } = {}) { + const released = []; + const sent = []; + let checkouts = 0; + const base = { + async connect() { + checkouts += 1; + await new Promise((r) => setImmediate(r)); + return { + async query(text) { + sent.push(text); + await new Promise((r) => setImmediate(r)); + if (fail !== undefined && text === fail) throw new Error('statement failed'); + return { rows: [] }; + }, + release: (err) => released.push(err), + }; + }, + }; + return { base, released, sent, checkouts: () => checkouts }; + } + + /** The store's transaction shape: BEGIN, SET LOCAL statement_timeout, the statement, COMMIT, release. */ + async function inTransaction(pool) { + const client = await pool.connect(); + await client.query('BEGIN'); + await client.query('SET LOCAL statement_timeout = 1000'); + await client.query(RANKING, ['s', 1, '[1]']); + await client.query('COMMIT'); + client.release(); + } + + it('a held checkout: one checkout timed, the ranking statement inside the transaction is ranking, its own three statements are transaction, release passed through', async () => { + const recorder = createSearchRecorder(); + const counted = countingBase(); + const pool = timedPool(counted.base, recorder); + const { record, error } = await recorder.run({}, () => inTransaction(pool)); + expect(error).toBeUndefined(); + expect(record.calls.pool_wait).toBe(1); + expect(record.calls.ranking).toBe(1); + expect(record.calls.other_sql).toBe(3); + expect(record.otherSqlKinds).toEqual({ transaction: 3 }); + expect(record.rankings.map((r) => r.shape.vectorLeg)).toEqual([true]); + expect(counted.sent).toHaveLength(4); + expect(counted.released).toEqual([undefined]); + }); + + it('a one-shot query: one checkout, one statement, released once — with the error when the statement fails', async () => { + const recorder = createSearchRecorder(); + const counted = countingBase({ fail: 'SELECT broken' }); + const pool = timedPool(counted.base, recorder); + const { record } = await recorder.run({}, async () => { + await pool.query(RANKING, ['s', 1, '[1]']); + await pool.query('SELECT broken').catch(() => undefined); + }); + expect(record.calls.pool_wait).toBe(2); + expect(record.calls.ranking).toBe(1); + expect(record.calls.other_sql).toBe(1); + expect(counted.released).toHaveLength(2); + expect(counted.released[0]).toBeUndefined(); + expect(counted.released[1]).toBeInstanceOf(Error); + }); + + it('concurrent searches through one pool are each attributed their own checkouts and statements; a call outside any search is not recorded', async () => { + const recorder = createSearchRecorder(); + const counted = countingBase(); + const pool = timedPool(counted.base, recorder); + const [a, b] = await Promise.all([ + recorder.run({}, async () => { + await inTransaction(pool); + await inTransaction(pool); + }), + recorder.run({}, () => pool.query(RANKING, ['s', 1, '[1]'])), + inTransaction(pool), + ]); + expect([a.record.calls.pool_wait, a.record.calls.ranking, a.record.calls.other_sql]).toEqual([2, 2, 6]); + expect([b.record.calls.pool_wait, b.record.calls.ranking, b.record.calls.other_sql]).toEqual([1, 1, 0]); + expect(counted.checkouts()).toBe(4); + expect(counted.released).toHaveLength(4); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/bench/run.mjs b/packages/plugins/knowledge-pgvector/bench/run.mjs new file mode 100644 index 00000000000..0e461fd9d8c --- /dev/null +++ b/packages/plugins/knowledge-pgvector/bench/run.mjs @@ -0,0 +1,651 @@ +#!/usr/bin/env node +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * knowledge-pgvector search bench: real `search_knowledge` calls over a real + * KnowledgeService, this store and ObjectQL + SqlDriver, on any PostgreSQL + * with pgvector, timed per segment (`instrument.mjs`) at each record-scope + * fraction × concurrency. README.md beside this file is the manual. + * + * node packages/plugins/knowledge-pgvector/bench/run.mjs --pg-url postgres://… [flags] + * + * Nothing here is published (the package's `files` is `dist`, README, CHANGELOG). + */ + +import { createHash, randomUUID } from 'node:crypto'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import { dirname, resolve } from 'node:path'; +import { performance } from 'node:perf_hooks'; + +import { parseArgs } from 'node:util'; +import pg from 'pg'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { KnowledgeService, createKnowledgeTools } from '@objectstack/service-knowledge'; +import { + SEGMENTS, + createSearchRecorder, + extractRankingWhere, + percentile, + summarizeRecord, + timedAdapter, + timedEmbedder, + timedEngine, + timedPool, +} from './instrument.mjs'; + +const USAGE = `usage: node bench/run.mjs --pg-url URL [flags] (see bench/README.md) + + --pg-url URL PostgreSQL with pgvector available [$OS_BENCH_PG_URL] + --passages N passages (one record each) to seed [2000] + --dims N embedding width [1024] + --units N parent units the passages spread over [100] + --scopes LIST scope fractions in %, and/or "none" [1,10,30,100,none] + --concurrency LIST closed-loop clients [1,5,10,20] + --searches N timed searches per cell [100] + --searches-per-question N searches one simulated question issues [1] + --top-k N search_knowledge topK [5] + --granularity chunk|record [chunk] + --group-by FIELD groupBy (implies record granularity; "unit" is the seeded one) + --cache warm|cold warm: an untimed pass first; cold: fresh pool, none [warm] + --warmup N untimed searches per cell when warm [20] + --pool-max N the store's pool size (plugin default 4) [4] + --connect-timeout-ms N the store's pool checkout timeout [5000] + --embedder fake|openai fake: hashed bag of words, in process [fake] + --queries FILE JSON array of question strings (default: synthetic) + --isolate-scope after each scoped cell, the derived scope-predicate pass + --isolate-repeats N repeats of each isolation statement [5] + --dataset NAME schema tag; the run uses os_kbench_NAME(_k) [p_d] + --reuse keep an already seeded dataset of that name + --keep do not drop the dataset at the end + --samples write every search's record into the JSON + --out FILE the JSON result [$TMPDIR/os-kbench/-.json] + --seed N PRNG seed [38719]`; + +// ── Arguments ──────────────────────────────────────────────────────── + +const { values: args } = parseArgs({ + options: { + 'pg-url': { type: 'string' }, + passages: { type: 'string', default: '2000' }, + dims: { type: 'string', default: '1024' }, + units: { type: 'string', default: '100' }, + scopes: { type: 'string', default: '1,10,30,100,none' }, + concurrency: { type: 'string', default: '1,5,10,20' }, + searches: { type: 'string', default: '100' }, + 'searches-per-question': { type: 'string', default: '1' }, + 'top-k': { type: 'string', default: '5' }, + granularity: { type: 'string', default: 'chunk' }, + 'group-by': { type: 'string' }, + cache: { type: 'string', default: 'warm' }, + warmup: { type: 'string', default: '20' }, + 'pool-max': { type: 'string', default: '4' }, + 'connect-timeout-ms': { type: 'string', default: '5000' }, + embedder: { type: 'string', default: 'fake' }, + queries: { type: 'string' }, + 'isolate-scope': { type: 'boolean', default: false }, + 'isolate-repeats': { type: 'string', default: '5' }, + dataset: { type: 'string' }, + reuse: { type: 'boolean', default: false }, + keep: { type: 'boolean', default: false }, + samples: { type: 'boolean', default: false }, + out: { type: 'string' }, + seed: { type: 'string', default: '38719' }, + help: { type: 'boolean', default: false }, + }, + strict: true, +}); + +if (args.help) { + console.log(USAGE); + process.exit(0); +} + +function fail(message) { + console.error(`bench: ${message}\n\n${USAGE}`); + process.exit(2); +} + +function positiveInt(name) { + const n = Number(args[name]); + if (!Number.isInteger(n) || n < 1) fail(`--${name} must be a positive integer, got '${args[name]}'.`); + return n; +} + +function intList(name) { + return args[name].split(',').map((s) => { + const n = Number(s.trim()); + if (!Number.isInteger(n) || n < 1) fail(`--${name} takes positive integers, got '${s}'.`); + return n; + }); +} + +const PG_URL = args['pg-url'] ?? process.env.OS_BENCH_PG_URL; +if (!PG_URL || !/^postgres(ql)?:\/\//i.test(PG_URL)) fail('--pg-url (or OS_BENCH_PG_URL) must be a postgres:// URL.'); +const PASSAGES = positiveInt('passages'); +const DIMS = positiveInt('dims'); +const UNITS = positiveInt('units'); +const SEARCHES = positiveInt('searches'); +const PER_QUESTION = positiveInt('searches-per-question'); +const TOP_K = positiveInt('top-k'); +const POOL_MAX = positiveInt('pool-max'); +const CONNECT_TIMEOUT_MS = positiveInt('connect-timeout-ms'); +const ISOLATE_REPEATS = positiveInt('isolate-repeats'); +const CONCURRENCY = intList('concurrency'); +const SCOPES = args.scopes.split(',').map((s) => { + const t = s.trim(); + if (t === 'none') return 'none'; + const n = Number(t); + if (!Number.isFinite(n) || n <= 0 || n > 100) fail(`--scopes takes percentages in (0, 100] or "none", got '${s}'.`); + return n; +}); +if (!['chunk', 'record'].includes(args.granularity)) fail(`--granularity is chunk or record, got '${args.granularity}'.`); +if (!['warm', 'cold'].includes(args.cache)) fail(`--cache is warm or cold, got '${args.cache}'.`); +if (!['fake', 'openai'].includes(args.embedder)) fail(`--embedder is fake or openai, got '${args.embedder}'.`); +const WARMUP = args.cache === 'warm' ? Number(args.warmup) : 0; +if (!Number.isInteger(WARMUP) || WARMUP < 0) fail(`--warmup must be a non-negative integer, got '${args.warmup}'.`); +const DATASET = args.dataset ?? `p${PASSAGES}_d${DIMS}`; +if (!/^[a-z0-9_]{1,40}$/.test(DATASET)) fail(`--dataset must match [a-z0-9_]{1,40}, got '${DATASET}'.`); +const OBJECT_SCHEMA = `os_kbench_${DATASET}`; +const KNOWLEDGE_SCHEMA = `os_kbench_${DATASET}_k`; +const OUT = resolve(args.out ?? resolve(os.tmpdir(), 'os-kbench', `${DATASET}-${args.cache}.json`)); + +// ── Deterministic data ─────────────────────────────────────────────── + +/** mulberry32: a small seeded PRNG, so two runs of one dataset name seed the same text. */ +function prng(seed) { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +const random = prng(Number(args.seed)); +const VOCABULARY = Array.from({ length: 3000 }, (_, i) => `term${i.toString(36)}x`); +const pick = () => VOCABULARY[Math.floor(Math.pow(random(), 1.6) * VOCABULARY.length)]; +const words = (n) => Array.from({ length: n }, pick).join(' '); + +const UNIT_OBJECT = 'kbench_unit'; +const CLAUSE_OBJECT = 'kbench_clause'; +const UNIT_DEF = { + name: UNIT_OBJECT, + label: 'Bench unit', + fields: { name: { name: 'name', type: 'text' } }, +}; +const CLAUSE_DEF = { + name: CLAUSE_OBJECT, + label: 'Bench clause', + fields: { + title: { name: 'title', type: 'text' }, + body: { name: 'body', type: 'textarea' }, + unit: { name: 'unit', type: 'lookup', reference: UNIT_OBJECT }, + }, +}; +const SOURCE = { + name: 'kbench_clauses', + label: 'Bench clauses', + adapter: 'pgvector', + source: { kind: 'object', object: CLAUSE_OBJECT, content: ['title', 'body'], metadataFields: ['unit'] }, +}; +const unitId = (i) => `u${String(i).padStart(4, '0')}`; + +// ── Embedders ──────────────────────────────────────────────────────── + +/** In-process: each word hashed into a slot, unit length. Costs CPU only — no network, no failure. */ +function fakeEmbedder(dimensions) { + const vector = (text) => { + const v = new Float64Array(dimensions); + for (const word of text.toLowerCase().split(/[^a-z0-9]+/)) { + if (word === '') continue; + v[createHash('sha256').update(word).digest().readUInt32BE(0) % dimensions] += 1; + } + const norm = Math.hypot(...v); + return Array.from(v, (x) => (norm === 0 ? 0 : x / norm)); + }; + return { id: 'kbench-fake', dimensions, model: `kbench-fake-bow-${dimensions}`, embed: async (texts) => texts.map(vector) }; +} + +/** An OpenAI-compatible `/embeddings` endpoint: OS_BENCH_EMBEDDER_URL, _MODEL, _API_KEY. */ +function openAiEmbedder(dimensions) { + const url = process.env.OS_BENCH_EMBEDDER_URL; + const model = process.env.OS_BENCH_EMBEDDER_MODEL; + if (!url || !model) fail('--embedder openai needs OS_BENCH_EMBEDDER_URL and OS_BENCH_EMBEDDER_MODEL.'); + const key = process.env.OS_BENCH_EMBEDDER_API_KEY; + return { + id: 'kbench-openai', + dimensions, + model, + async embed(texts) { + const res = await fetch(`${url.replace(/\/$/, '')}/embeddings`, { + method: 'POST', + headers: { 'content-type': 'application/json', ...(key ? { authorization: `Bearer ${key}` } : {}) }, + body: JSON.stringify({ model, input: texts, dimensions }), + }); + if (!res.ok) throw new Error(`embedder answered HTTP ${res.status}`); + const body = await res.json(); + return body.data.sort((a, b) => a.index - b.index).map((d) => d.embedding); + }, + }; +} + +// ── Machine shape ──────────────────────────────────────────────────── + +async function machineShape(pool) { + const one = async (sql) => (await pool.query(sql)).rows[0]; + const setting = async (name) => (await one(`SELECT current_setting('${name}') AS v`)).v; + const ext = await one(`SELECT extversion FROM pg_extension WHERE extname = 'vector'`).catch(() => undefined); + return { + client: { + node: process.version, + platform: `${os.platform()} ${os.release()}`, + cpus: os.cpus().length, + cpuModel: os.cpus()[0]?.model ?? null, + memoryGiB: Math.round((os.totalmem() / 2 ** 30) * 10) / 10, + }, + server: { + version: (await one('SELECT version() AS v')).v, + pgvector: ext?.extversion ?? null, + shared_buffers: await setting('shared_buffers'), + work_mem: await setting('work_mem'), + effective_cache_size: await setting('effective_cache_size'), + max_connections: await setting('max_connections'), + max_parallel_workers_per_gather: await setting('max_parallel_workers_per_gather'), + host: new URL(PG_URL).hostname, + }, + }; +} + +// ── Seeding ────────────────────────────────────────────────────────── + +async function tableRows(pool, schema, table) { + const found = await pool.query('SELECT to_regclass($1) AS t', [`"${schema}"."${table}"`]); + if (found.rows[0].t === null) return undefined; + return Number((await pool.query(`SELECT count(*)::int AS n FROM "${schema}"."${table}"`)).rows[0].n); +} + +async function seed(driver) { + const units = Array.from({ length: UNITS }, (_, i) => ({ id: unitId(i), name: `Unit ${i}` })); + await driver.bulkCreate(UNIT_OBJECT, units); + const batch = 1000; + for (let from = 0; from < PASSAGES; from += batch) { + const rows = []; + for (let i = from; i < Math.min(PASSAGES, from + batch); i++) { + rows.push({ id: `c${String(i).padStart(7, '0')}`, title: `Clause ${i} ${words(3)}`, body: words(55), unit: unitId(i % UNITS) }); + } + await driver.bulkCreate(CLAUSE_OBJECT, rows); + } +} + +// ── Questions and scopes ───────────────────────────────────────────── + +function questions() { + if (args.queries) { + const list = JSON.parse(readFileSync(resolve(args.queries), 'utf8')); + if (!Array.isArray(list) || list.length === 0 || !list.every((q) => typeof q === 'string' && q.trim() !== '')) { + fail(`--queries must name a JSON array of non-empty strings.`); + } + return list; + } + return Array.from({ length: 200 }, () => words(6)); +} + +/** The scope entry of a fraction: the first ceil(f × units) units — each unit holds the same share of passages. */ +function scopeFor(fraction) { + if (fraction === 'none') return undefined; + const n = Math.max(1, Math.ceil((fraction / 100) * UNITS)); + const ids = Array.from({ length: n }, (_, i) => unitId(i)); + const entries = []; + for (let i = 0; i < ids.length; i += 500) entries.push({ object: UNIT_OBJECT, ids: ids.slice(i, i + 500) }); + return entries; +} + +// ── One cell ───────────────────────────────────────────────────────── + +const CALLER = { userId: 'kbench_reader', isSystem: false }; + +async function runCell({ tools, recorder, scopeFraction, concurrency, qs, total, timed, logCounts }) { + const scope = scopeFor(scopeFraction); + const outcomes = []; + let issued = 0; + let questionsAsked = 0; + const logBefore = { ...logCounts }; + const started = performance.now(); + const worker = async (w) => { + for (;;) { + if (issued >= total) return; + const question = qs[(questionsAsked++ + w * 7) % qs.length]; + for (let s = 0; s < PER_QUESTION && issued < total; s++) { + issued += 1; + const input = { + query: question, + topK: TOP_K, + ...(scope ? { scope } : {}), + ...(args.granularity === 'record' ? { granularity: 'record' } : {}), + ...(args['group-by'] ? { groupBy: args['group-by'] } : {}), + }; + const outcome = await recorder.run({ scope: scopeFraction, concurrency }, () => tools.searchKnowledge(input, CALLER)); + if (timed) outcomes.push({ outcome, summary: summarizeRecord(outcome) }); + } + } + }; + await Promise.all(Array.from({ length: concurrency }, (_, w) => worker(w))); + return { + outcomes, + wallMs: performance.now() - started, + questions: questionsAsked, + logDelta: Object.fromEntries(Object.entries(logCounts).map(([k, v]) => [k, v - (logBefore[k] ?? 0)])), + }; +} + +function stats(values) { + const n = values.length; + return { + n, + p50: round(percentile(values, 50)), + p95: round(percentile(values, 95)), + max: round(n === 0 ? null : Math.max(...values)), + mean: round(n === 0 ? null : values.reduce((a, b) => a + b, 0) / n), + }; +} + +function round(x) { + return x === null || x === undefined ? null : Math.round(x * 100) / 100; +} + +function summarizeCell(cell, scopeFraction, concurrency) { + const all = cell.outcomes.map((o) => o.summary); + const ok = all.filter((s) => s.ok); + const failed = all.filter((s) => !s.ok); + const segments = {}; + for (const name of SEGMENTS) segments[name] = stats(ok.map((s) => s.ms[name])); + const calls = {}; + for (const name of SEGMENTS) calls[name] = stats(ok.map((s) => s.calls[name])); + const errorCodes = {}; + for (const s of failed) errorCodes[s.errorCode ?? 'UNCODED'] = (errorCodes[s.errorCode ?? 'UNCODED'] ?? 0) + 1; + const shapes = ok.flatMap((s) => s.rankingShapes); + return { + scope: scopeFraction === 'none' ? 'none' : `${scopeFraction}%`, + concurrency, + samples: all.length, + succeeded: ok.length, + failed: failed.length, + errorCodes, + refusedSearches: ok.filter((s) => s.refused > 0).length, + emptyAnswers: ok.filter((s) => s.hits === 0).length, + throughputPerSec: round((all.length / cell.wallMs) * 1000), + questions: cell.questions, + searchesPerQuestion: PER_QUESTION, + totalMs: stats(ok.map((s) => s.totalMs)), + hits: stats(ok.map((s) => s.hits)), + segmentsMs: segments, + segmentCalls: calls, + unaccountedMs: stats(ok.map((s) => s.unaccountedMs)), + backfillShare: ok.length === 0 ? null : round(ok.filter((s) => s.refilled).length / ok.length), + adapterCalls: stats(ok.map((s) => s.adapterCalls)), + embedFailures: all.reduce((sum, s) => sum + s.embedFailures, 0), + rankingStatements: { + total: shapes.length, + withKeywordLeg: shapes.filter((s) => s.keywordLeg).length, + withMetadataScope: shapes.filter((s) => s.metadataScope).length, + withRecordScope: shapes.filter((s) => s.recordScope).length, + }, + serviceLog: cell.logDelta, + }; +} + +// ── The derived scope-predicate pass ──────────────────────────────── + +/** + * Out of situ, serially, on one connection: the cell's last ranking + * statement, the same WHERE as a bare count, and the source+generation WHERE + * as a bare count, each `ISOLATE_REPEATS` times, timed by the server + * (`EXPLAIN (ANALYZE, TIMING OFF)` "Execution Time"). scope ≈ where − base; + * the rest of the ranking ≈ ranking − where. The plans' top scan nodes are + * recorded so a reader sees whether the three read the table the same way. + */ +async function isolateScope(adminPool, statement) { + const parts = statement && extractRankingWhere(statement.text, statement.params); + if (!parts) { + return { status: 'NOT MEASURED', reason: 'no ranking statement with a recognised vector leg was captured for this cell' }; + } + const client = await adminPool.connect(); + try { + const explain = async (sql, params) => { + const times = []; + let scan; + for (let i = 0; i < ISOLATE_REPEATS; i++) { + const plan = (await client.query(`EXPLAIN (ANALYZE, TIMING OFF, BUFFERS, FORMAT JSON) ${sql}`, params)).rows[0]['QUERY PLAN'][0]; + times.push(plan['Execution Time']); + scan = scanNodes(plan.Plan); + } + return { ms: stats(times), scans: scan }; + }; + const ranking = await explain(statement.text, statement.params); + const where = await explain(`SELECT count(*) FROM ${parts.table} WHERE ${parts.where}`, parts.params); + const base = await explain(`SELECT count(*) FROM ${parts.table} WHERE source_id = $1 AND generation = $2`, parts.params.slice(0, 2)); + const rows = async (sql, params) => Number((await client.query(sql, params)).rows[0].n); + return { + status: 'DERIVED', + method: 'paired predicate-only statements, serial, after the load pass; server Execution Time (EXPLAIN ANALYZE, TIMING OFF)', + rowsInSourceGeneration: await rows(`SELECT count(*)::int AS n FROM ${parts.table} WHERE source_id = $1 AND generation = $2`, parts.params.slice(0, 2)), + rowsInScope: await rows(`SELECT count(*)::int AS n FROM ${parts.table} WHERE ${parts.where}`, parts.params), + rankingStatementMs: ranking.ms, + scopedCountMs: where.ms, + baseCountMs: base.ms, + scopePredicateMsP50: round(where.ms.p50 - base.ms.p50), + rankingBeyondPredicateMsP50: round(ranking.ms.p50 - where.ms.p50), + scans: { ranking: ranking.scans, scopedCount: where.scans, baseCount: base.scans }, + }; + } finally { + client.release(); + } +} + +function scanNodes(node, out = []) { + if (!node) return out; + if (/Scan/.test(node['Node Type']) && node['Relation Name']) out.push(`${node['Node Type']} on ${node['Relation Name']}`); + for (const child of node.Plans ?? []) scanNodes(child, out); + return out; +} + +async function tableIo(pool) { + const r = await pool.query( + `SELECT coalesce(sum(heap_blks_read), 0)::bigint AS read, coalesce(sum(heap_blks_hit), 0)::bigint AS hit + FROM pg_statio_user_tables WHERE schemaname = $1`, + [KNOWLEDGE_SCHEMA], + ); + return { read: Number(r.rows[0].read), hit: Number(r.rows[0].hit) }; +} + +// ── Main ───────────────────────────────────────────────────────────── + +async function main() { + const { PgvectorKnowledgeAdapter, poolFromPg, vectorTable } = await import('../dist/index.mjs').catch((err) => { + fail(`cannot load ../dist/index.mjs (${err.message}) — build first: pnpm --filter '@objectstack/knowledge-pgvector...' build`); + }); + const adminPool = new pg.Pool({ connectionString: PG_URL, max: 2 }); + const shape = await machineShape(adminPool); + console.error(`bench: ${shape.server.version.split(',')[0]} · pgvector ${shape.server.pgvector ?? 'not installed'} · dataset ${DATASET}`); + + const existing = await tableRows(adminPool, OBJECT_SCHEMA, CLAUSE_OBJECT); + const reused = args.reuse && existing === PASSAGES; + if (!reused) { + await adminPool.query(`DROP SCHEMA IF EXISTS "${OBJECT_SCHEMA}" CASCADE`); + await adminPool.query(`DROP SCHEMA IF EXISTS "${KNOWLEDGE_SCHEMA}" CASCADE`); + await adminPool.query(`CREATE SCHEMA "${OBJECT_SCHEMA}"`); + } + + const driver = new SqlDriver({ client: 'pg', connection: PG_URL, searchPath: [OBJECT_SCHEMA] }); + await driver.initObjects([UNIT_DEF, CLAUSE_DEF]); + const engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject(UNIT_DEF, 'com.objectstack.bench.knowledge-pgvector'); + engine.registry.registerObject(CLAUSE_DEF, 'com.objectstack.bench.knowledge-pgvector'); + + let seedMs = 0; + if (!reused) { + const t = performance.now(); + await seed(driver); + seedMs = performance.now() - t; + console.error(`bench: seeded ${PASSAGES} clauses over ${UNITS} units in ${(seedMs / 1000).toFixed(1)} s`); + } + + const recorder = createSearchRecorder({ keepStatements: args['isolate-scope'] }); + const embedder = args.embedder === 'openai' ? openAiEmbedder(DIMS) : fakeEmbedder(DIMS); + const logCounts = { error: 0, warn: 0, searchFailed: 0 }; + const logger = { + debug: () => undefined, + info: () => undefined, + warn: (m) => { + logCounts.warn += 1; + if (process.env.OS_BENCH_VERBOSE) console.error(`[warn] ${m}`); + }, + error: (m) => { + logCounts.error += 1; + if (/search failed/.test(String(m))) logCounts.searchFailed += 1; + console.error(`[error] ${m}`); + }, + }; + + const makeStore = () => { + const storePool = new pg.Pool({ connectionString: PG_URL, max: POOL_MAX, connectionTimeoutMillis: CONNECT_TIMEOUT_MS }); + storePool.on('error', () => undefined); + const adapter = new PgvectorKnowledgeAdapter({ + id: 'pgvector', + pool: timedPool(poolFromPg(storePool), recorder), + embedder: timedEmbedder(embedder, recorder), + schema: KNOWLEDGE_SCHEMA, + logger, + }); + const svc = new KnowledgeService({ dataEngine: timedEngine(engine, recorder), logger }); + svc.registerAdapter('pgvector', timedAdapter(adapter, recorder)); + svc.registerSource(SOURCE); + return { storePool, adapter, svc, tools: createKnowledgeTools(svc) }; + }; + + let store = makeStore(); + const buildStarted = performance.now(); + const build = await store.svc.reindexSource(SOURCE.name); + const buildMs = performance.now() - buildStarted; + if (!build.ok) throw new Error(`the build of the bench source failed: ${JSON.stringify(build)}`); + const indexed = await tableRows(adminPool, KNOWLEDGE_SCHEMA, vectorTable(DIMS)).catch(() => undefined); + await adminPool.query(`ANALYZE "${OBJECT_SCHEMA}"."${CLAUSE_OBJECT}"`); + await adminPool.query(`ANALYZE`).catch(() => undefined); + console.error(`bench: build ${JSON.stringify({ indexed: build.indexed, skipped: build.skipped })} in ${(buildMs / 1000).toFixed(1)} s`); + + const qs = questions(); + const cells = []; + for (const scopeFraction of SCOPES) { + for (const concurrency of CONCURRENCY) { + if (args.cache === 'cold') { + // A fresh pool and no untimed pass: new connections, no prepared state in this process. + await store.adapter.close().catch(() => undefined); + await store.storePool.end().catch(() => undefined); + store = makeStore(); + } + if (WARMUP > 0) { + await runCell({ tools: store.tools, recorder, scopeFraction, concurrency, qs, total: WARMUP, timed: false, logCounts }); + } + const ioBefore = await tableIo(adminPool); + const cell = await runCell({ tools: store.tools, recorder, scopeFraction, concurrency, qs, total: SEARCHES, timed: true, logCounts }); + const ioAfter = await tableIo(adminPool); + const summary = summarizeCell(cell, scopeFraction, concurrency); + summary.knowledgeTableBlocks = { read: ioAfter.read - ioBefore.read, hit: ioAfter.hit - ioBefore.hit }; + if (args['isolate-scope'] && scopeFraction !== 'none') { + const last = [...cell.outcomes].reverse().find((o) => o.outcome.record.rankings.some((r) => r.text)); + const statement = last?.outcome.record.rankings.find((r) => r.text); + summary.scopePredicate = await isolateScope(adminPool, statement); + } else { + summary.scopePredicate = { + status: 'NOT MEASURED', + reason: + scopeFraction === 'none' + ? 'unscoped cell: no scope predicate' + : 'in situ the scope predicate is a conjunct of the ranking statement; pass --isolate-scope for the derived pass', + }; + } + if (args.samples) summary.records = cell.outcomes.map((o) => o.summary); + cells.push(summary); + console.error( + `bench: scope ${summary.scope} × ${concurrency}: n=${summary.samples} p50 ${summary.totalMs.p50} ms p95 ${summary.totalMs.p95} ms` + + ` · failed ${summary.failed} · backfill ${summary.backfillShare}`, + ); + } + } + + const result = { + bench: 'knowledge-pgvector search_knowledge segments', + runId: randomUUID(), + at: new Date().toISOString(), + machine: shape, + parameters: { + passages: PASSAGES, + dims: DIMS, + units: UNITS, + scopes: SCOPES, + concurrency: CONCURRENCY, + searchesPerCell: SEARCHES, + searchesPerQuestion: PER_QUESTION, + topK: TOP_K, + granularity: args['group-by'] ? 'record' : args.granularity, + groupBy: args['group-by'] ?? null, + cache: args.cache, + warmupPerCell: WARMUP, + poolMax: POOL_MAX, + connectTimeoutMs: CONNECT_TIMEOUT_MS, + embedder: { kind: args.embedder, model: embedder.model, dimensions: embedder.dimensions }, + queries: args.queries ? resolve(args.queries) : 'synthetic (200, six vocabulary words each)', + caller: 'a non-system caller; ObjectQL + SqlDriver with no security plugin, so the re-check reads every row it asks for', + }, + dataset: { name: DATASET, objectSchema: OBJECT_SCHEMA, knowledgeSchema: KNOWLEDGE_SCHEMA, reused, seedMs: round(seedMs), buildMs: round(buildMs), indexedRows: indexed ?? null }, + cacheNote: + args.cache === 'cold' + ? 'cold = a fresh store pool per cell and no untimed pass; the server buffer cache and the OS page cache are NOT flushed (a client cannot). knowledgeTableBlocks.read shows how cold each cell was.' + : 'warm = an untimed pass of --warmup searches before each cell, on the same pool.', + segmentNotes: { + embed: 'measured: the adapter embedder seam (each embed call of the search)', + vector: 'measured as `ranking`: the ranking statement execution; it also carries the keyword leg when the query has keyword terms (rankingStatements.withKeywordLeg) and the scope predicate', + scopePredicate: 'NOT MEASURED in situ (one WHERE with the vector leg); per cell, scopePredicate is the derived out-of-situ pass when --isolate-scope is given', + permissionRecheck: 'measured: the service dataEngine seam — permission_recheck (hits re-read as the caller) and visible_ids (readable ids before ranking)', + poolWait: 'measured: the checkout of a pooled connection for each one-shot statement', + }, + cells, + }; + mkdirSync(dirname(OUT), { recursive: true }); + writeFileSync(OUT, `${JSON.stringify(result, null, 2)}\n`); + console.log(table(cells)); + console.error(`bench: wrote ${OUT}`); + + await store.adapter.close().catch(() => undefined); + await store.storePool.end().catch(() => undefined); + await engine.destroy?.().catch?.(() => undefined); + if (!args.keep) { + await adminPool.query(`DROP SCHEMA IF EXISTS "${OBJECT_SCHEMA}" CASCADE`); + await adminPool.query(`DROP SCHEMA IF EXISTS "${KNOWLEDGE_SCHEMA}" CASCADE`); + } + await adminPool.end(); +} + +function table(cells) { + const head = + '| scope | conc | n | ok | p50 ms | p95 ms | embed p50 | wait p50 | ranking p50 | recheck p50 | other sql p50 | unacc. p50 | hits p50 | backfill | embed fail | scope pred. p50 |'; + const rule = '|' + head.split('|').slice(1, -1).map(() => '---').join('|') + '|'; + const rows = cells.map((c) => + `| ${c.scope} | ${c.concurrency} | ${c.samples} | ${c.succeeded} | ${c.totalMs.p50} | ${c.totalMs.p95} | ${c.segmentsMs.embed.p50} | ` + + `${c.segmentsMs.pool_wait.p50} | ${c.segmentsMs.ranking.p50} | ${c.segmentsMs.permission_recheck.p50} | ${c.segmentsMs.other_sql.p50} | ` + + `${c.unaccountedMs.p50} | ${c.hits.p50} | ${c.backfillShare} | ${c.embedFailures} | ` + + `${c.scopePredicate.status === 'DERIVED' ? `${c.scopePredicate.scopePredicateMsP50} (derived)` : c.scopePredicate.status} |`, + ); + return [head, rule, ...rows].join('\n'); +} + +main().catch((err) => { + console.error(`bench: failed — ${err?.stack ?? err}`); + process.exit(1); +});