Skip to content

perf(knowledge-pgvector): compute each keyword term's IDF once per search - #38533

Merged
objectstack-fleet[bot] merged 4 commits into
mainfrom
claude/issue-38510-pgvector-idf-once
Nov 29, 2026
Merged

objectstack-fleet[bot] merged 4 commits into
mainfrom
claude/issue-38510-pgvector-idf-once

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

Requested by Leehom · project thread
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.
Readings (head 623da38)
  • 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.

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

…arch

The keyword score evaluated ln(1.0 + (n - d + 0.5) / (d + 0.5)) for every
term on every candidate row. A materialized idf CTE now computes each
term's weight once and candidates multiply their hits by it, in the same
numeric arithmetic, so every score and tie order is unchanged.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb
… to the per-row form

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb
@github-actions github-actions Bot added size/m documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 29, 2026
@github-actions

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

1 anchor(s) derived from 1 changed package(s); no hand-written page names any of them, so this run has nothing to list — not a clean bill of health. This check sees only pages that NAME a derived anchor: one that documents this change in prose, or enumerates it in an authoring dialect, names none and stays invisible to it on every run.

What this run could not see
  • the SDK route bridge reached 69 of 253 client-bound route-ledger rows — the other 184 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 184: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 125 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 2 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 430a3119d3cde3b0b0032acb7df26a4411097ea0 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from d8327911e7f1d89344b4414102a34e3ecdb96805 — the merge of head 451dfc62c11a7f098586b6eee6e72c5ca963ae7e into base 430a3119d3cde3b0b0032acb7df26a4411097ea0, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin d8327911e7f1d89344b4414102a34e3ecdb96805 && git checkout d8327911e7f1d89344b4414102a34e3ecdb96805
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 430a3119d3cde3b0b0032acb7df26a4411097ea0 451dfc62c11a7f098586b6eee6e72c5ca963ae7e && git checkout -B drift-repro 430a3119d3cde3b0b0032acb7df26a4411097ea0 && git merge --no-ff 451dfc62c11a7f098586b6eee6e72c5ca963ae7e

node scripts/docs-audit/affected-docs.mjs --json 430a3119d3cde3b0b0032acb7df26a4411097ea0

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5nNJM8FQkBco82NDFb

席位核对 — L1 ACCEPT · head 623da38 · 2026-11-29T08:00Z

Verdict: ACCEPT at 623da38969. When I read the head it had 34 success and 0 failed, with 4 Test Core shards still running after about 20 minutes. This ACCEPT is on the diff. The area enqueues only once every check at this head is green, as the landing rule already requires.

The PR is Tier S and not governed. Its declarations are Clause-②: no and Metadata-protocol: none, and it carries one changeset (patch, @objectstack/knowledge-pgvector).

Fixes #38510 is right. The card asks for two things:

  1. IDF once per search, with numeric kept. This PR delivers it.
  2. Measure turso, or file a card. The body's "Turso twin: measured, not changed" section measures it, so no card is owed.

All three acceptance lines are met:

  • The bench. p95 goes from 3,840–3,910 ms to 1,569–1,622 ms, with 0 of 218 rankings differing in all six runs.
  • The pins. A unit pin and a live pin each hold the IDF against the per-row form.
  • No extension, index or fingerprint change.

The "live suites stay green" line depends on p0 #38523 landing first. The area has said it will merge main after #38523 and before enqueueing.

The SQL, read.

  • The per-row h.hI * ln(1.0 + (s.n - s.dI + 0.5) / (s.dI + 0.5)) becomes h.hI * w.wI. idf AS MATERIALIZED (SELECT ln(…) AS wI … FROM stats) produces the same expression once.
  • stats is a single-row aggregate, so CROSS JOIN idf adds one row and multiplies nothing.
  • The literals 1.0 and 0.5 keep every operand numeric, as before. ln() of the same numeric input gives the same output, and the sum runs in the same term order, so scores and ties are identical by construction. That matches the measured 0/218.
  • The path runs only under if (terms.length > 0), and every term pushes one onCandidate entry in either branch. So idf never has an empty select list.
  • AS MATERIALIZED needs PostgreSQL 12 or later, which pgvector itself already needs.
  • The two sql.ts files are untouched.

Pins.

  • The unit pin finds the idf CTE, counts ln( in the statement equal to the number of terms, all inside idf, and 0 in kw. It also requires the exact CROSS JOIN idf w scoring line.
  • The live pin compares, per candidate, the materialized score with the per-row form on a real database, and requires more than one distinct score. That guards against a degenerate fixture.
  • The body reports that both ablations turn the pins red.

Changeset, read sentence by sentence. It names the per-row ln() cost, the materialized step, that numeric keeps every score and tie, the bench figures (about 3.9 s → about 1.6 s, matching the table), and no extension, index or fingerprint change. All of it is true against the diff.

Landing (area, Tier S): after #38523 is on main, merge main into this branch, then enqueue, so the queue's live job does not eject it. #38510 closes on merge.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5oQLfL8thb6wtUHnTb

Landing: head 451dfc6 (main merged in after #38523, diff unchanged from 623da38) · L1-a ACCEPT 7252834317 on 623da38 · Clause-②: no, Metadata-protocol: none, changeset patch on @objectstack/knowledge-pgvector, no contract review owed · CI on this head: every check run success or expected skip, none failed · check-governed-merges --pr 38533: NOT governed. Landed after #38523 so the queue's live PostgreSQL job runs on a green base. Bench of record: p95 3.84–3.91 s → 1.57–1.62 s, 0 of 218 rankings changed; turso measured (about 5%), unchanged, no card owed.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 29, 2026 08:40
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 29, 2026
Merged via the queue into main with commit 4a43d6c Nov 29, 2026
56 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-38510-pgvector-idf-once branch November 29, 2026 09:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/m tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

2 participants