Skip to content

fix(knowledge-pgvector): read only the passages in scope for a metadata-scoped search, through a GIN index on metadata - #38758

Merged
objectstack-fleet[bot] merged 4 commits into
mainfrom
claude/issue-38747-pgvector-scope-gin
Nov 30, 2026
Merged

objectstack-fleet[bot] merged 4 commits into
mainfrom
claude/issue-38747-pgvector-scope-gin

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Requested by Steve · project thread

Fixes #38747

Clause-②: no
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:自建 PostgreSQL 上按单位范围检索知识库时,数据库先取出范围内的条款再算相似度,不再把全部条款都算一遍;种子表上向量这一路从约 300 毫秒降到约 2 毫秒,检索结果不变。
  • 为什么做:知识库检索提速专题的第一项,替首家客户(政策问答,总是按提问人所在单位范围检索)解决带范围检索和不带范围一样慢、并发时超时的问题。
  • 出错会怎样:碰到的是带单位范围检索的用户;数据库账号没有建索引权限时,检索不会被拒绝,照旧慢速返回同样的结果,并在日志里记一条警告、写明要执行的建索引语句;回退本合并即可撤回,已建的索引留着无害。
  • 要你做什么:无。

This PR lands on its own once reviewed; it no longer waits for #38745 (the retrieval-mode PR that edits the same file's search() legs; maintainer ruling 2026-11-30 12:02:57Z). overlap-check reads the two as merging cleanly in either order.

What changes

  • sql.ts — a GIN index on metadata with jsonb_path_ops, knowledge_vec_dWIDTH_metadata, added to the passage table's DDL beside the other three indexes (metadataIndexDdl, metadataIndexName). metadataScopeForms(field, ids) returns the containment values of one scope term as JSON text: per id, {field: "id"} and {field: ["id"]}, and, when the id is how PostgreSQL prints a numeric (optional minus, no leading zero, optional fraction, no exponent), {field: id} and {field: [id]} as numbers.
  • pgvector-adapter.ts, the metadata scope-term block — each metadata term is now (metadata @> ANY($N::jsonb[]) AND EXACT), where EXACT is today's predicate byte for byte (the jsonb_array_elements EXISTS) and $N binds the forms above. The containment is a superset of the exact match (card What 3: "Keep today's exact predicate as a recheck ANDed with the containment disjunction"), so results cannot change; the recheck is required, not decorative: containment compares numbers by value, so {"unit": 1.5} contains a stored 1.50 whose text the exact match compares as 1.50. The one inScope string still feeds the vec CTE, the cand CTE and the stats count, so all three read through the index.
    • @> ANY(jsonb[]) is one bound parameter per term rather than an explicit OR of 2-4 parameters per id: the planner runs it as one Bitmap Index Scan over the array (plan below), and a term at the contract's bound (500 ids) stays one parameter instead of up to 2,000.
  • bench/instrument.test.mjs — the one params pin at :189 (claim amendment, seat 11:32Z) now lists the containment-forms array this change binds as $5, and asserts the WHERE carries metadata @> ANY($5::jsonb[]). No other line in that file changes, so the comment above it still names only the ids and the field.
  • pgvector-adapter.ts, ensureMetadataIndex — the existing-table path (card What 1), the twin of ensureKeywordIndex, called from the scope-term block when a search holds a metadata term. It looks the index up with to_regclass first and creates it only when absent.

Existing tables: does the DDL path already run, and what the first time costs

  • vectorTableDdl runs from ensureVectorTable, which is reached only by upsert and beginBuild, and is skipped for the life of the process once any search has found the table (tableExists fills the same tables set). So a process whose first touch of a width is a search would never run the DDL: a table made by an earlier release would stay without the index until a process happened to write first. That is why the search-time ensure exists, exactly as the keyword index has one.
  • Lock: plain CREATE INDEX takes a SHARE lock — reads go on, writes (upsert, purge, build pages) wait for the build. Measured here: on 58,500 passages of 1024 dimensions (338 MB table) the build took 32 ms (index 256 kB), and ANALYZE 264 ms (the ensure does not run ANALYZE; autovacuum does). The card's acceptance DB measured 0.27 s build and 2.1 s ANALYZE with real metadata.
  • Why not CONCURRENTLY: an interrupted concurrent build leaves an INVALID index under the name, and IF NOT EXISTS then takes it for a made one forever, so scoped searches would silently stay on the sequential scan; it also cannot run inside a transaction block and waits for every older transaction. The table's other three indexes are plain for the same reason.
  • Why look up first: measured on this PG16, CREATE INDEX IF NOT EXISTS on an index that already exists still waits for the table lock — with a writer's transaction open it was cancelled by a 800 ms lock_timeout, while to_regclass answered at once. The lookup keeps the steady state lock-free.
  • A role that may not create it (seat ruling 2026-11-30 11:32Z, option B): the search is not refused. ensureMetadataIndex records the width in metadataUnindexed (the failure twin of metadataIndexed), logs ONE warn naming the consequence and the full CREATE INDEX statement to run as a database owner, and never tries again in that process; the search runs the same statement, which the planner answers by today's sequential scan, so the hits are today's. Once an owner runs the statement, the next search reads through the index with no restart (the statement text does not change). A missing index is a functional degradation, so warn, not error (AGENTS.md degradation levels). Coded refusals in src/errors.ts, ensureKeywordIndex and B2's SET LOCAL statement_timeout are untouched.

Before / after: one scoped vec statement

Seeded table, local PostgreSQL 16.15 + pgvector 0.6.0, jit = off: 58,500 passages, 1024 dimensions, owning_unit over 350 units (a tenth of the passages list two units), scope owning_unit = u7 (336 passages hold it, 81 below distance 1). Statement: the adapter's own vec CTE, recorded from a real search and re-run under EXPLAIN (ANALYZE, BUFFERS); four runs each. Shared container, so treat absolute milliseconds as indicative.

plan execution time (4 runs) top 5
before (base f782a12, no metadata index) Seq Scan, 58,420 rows removed by filter 296.7 / 338.5 / 295.7 / 306.5 ms c56007, c35707, c3857, c39557, c53557
after (this branch) Bitmap Index Scan on knowledge_vec_d1024_metadata 2.27 / 1.95 / 1.80 / 1.67 ms c56007, c35707, c3857, c39557, c53557 (same)

In the plans COSINE_DISTANCE_OP stands for pgvector's cosine-distance operator and LESS_THAN for the less-than sign; the query vector is elided.

Before: EXPLAIN (ANALYZE, BUFFERS), run 4
Subquery Scan on vec  (cost=113850.70..113850.86 rows=5 width=14) (actual time=306.476..306.483 rows=5 loops=1)
  Buffers: shared hit=214374 read=40771
  ->  Limit  (cost=113850.70..113850.81 rows=5 width=22) (actual time=306.473..306.479 rows=5 loops=1)
        Buffers: shared hit=214374 read=40771
        InitPlan 1 (returns $0)
          ->  Index Scan using knowledge_generation_active on knowledge_generation g  (cost=0.14..8.16 rows=1 width=0) (actual time=0.013..0.013 rows=1 loops=1)
                Index Cond: (source_id = 'policy'::text)
                Filter: (generation = 1)
                Buffers: shared hit=1 read=1
        ->  WindowAgg  (cost=113842.53..114061.91 rows=9750 width=22) (actual time=306.472..306.475 rows=5 loops=1)
              Buffers: shared hit=214374 read=40771
              ->  Sort  (cost=113842.53..113866.91 rows=9750 width=14) (actual time=306.461..306.463 rows=5 loops=1)
                    Sort Key: ((knowledge_vec_d1024.embedding COSINE_DISTANCE_OP '[QUERY_VECTOR_1024]'::vector)), knowledge_vec_d1024.chunk_id
                    Sort Method: quicksort  Memory: 28kB
                    Buffers: shared hit=214374 read=40771
                    ->  Result  (cost=0.00..113196.54 rows=9750 width=14) (actual time=5.417..306.362 rows=81 loops=1)
                          One-Time Filter: $0
                          Buffers: shared hit=214374 read=40771
                          ->  Seq Scan on knowledge_vec_d1024  (cost=0.00..113172.16 rows=9750 width=24) (actual time=5.398..305.971 rows=81 loops=1)
                                Filter: ((source_id = 'policy'::text) AND (generation = 1) AND ((embedding COSINE_DISTANCE_OP '[QUERY_VECTOR_1024]'::vector) LESS_THAN '1'::double precision) AND (SubPlan 2))
                                Rows Removed by Filter: 58420
                                Buffers: shared hit=214023 read=40770
                                SubPlan 2
                                  ->  Function Scan on jsonb_array_elements e  (cost=0.02..1.89 rows=1 width=0) (actual time=0.001..0.001 rows=0 loops=29101)
                                        Filter: (((v #>> '{}'::text[]) = ANY ('{u7}'::text[])) AND (jsonb_typeof(v) = ANY ('{string,number}'::text[])))
                                        Rows Removed by Filter: 1
Planning:
  Buffers: shared read=1
Planning Time: 0.239 ms
Execution Time: 306.523 ms
After: EXPLAIN (ANALYZE, BUFFERS), run 4
Subquery Scan on vec  (cost=96.94..97.01 rows=2 width=14) (actual time=1.625..1.631 rows=5 loops=1)
  Buffers: shared hit=1254
  ->  Limit  (cost=96.94..96.99 rows=2 width=22) (actual time=1.624..1.628 rows=5 loops=1)
        Buffers: shared hit=1254
        InitPlan 1 (returns $0)
          ->  Index Scan using knowledge_generation_active on knowledge_generation g  (cost=0.14..8.16 rows=1 width=0) (actual time=0.008..0.009 rows=1 loops=1)
                Index Cond: (source_id = 'policy'::text)
                Filter: (generation = 1)
                Buffers: shared hit=2
        ->  WindowAgg  (cost=88.78..88.82 rows=2 width=22) (actual time=1.623..1.626 rows=5 loops=1)
              Buffers: shared hit=1254
              ->  Sort  (cost=88.78..88.78 rows=2 width=14) (actual time=1.619..1.620 rows=5 loops=1)
                    Sort Key: ((knowledge_vec_d1024.embedding COSINE_DISTANCE_OP '[QUERY_VECTOR_1024]'::vector)), knowledge_vec_d1024.chunk_id
                    Sort Method: quicksort  Memory: 28kB
                    Buffers: shared hit=1254
                    ->  Result  (cost=21.26..88.77 rows=2 width=14) (actual time=0.108..1.593 rows=81 loops=1)
                          One-Time Filter: $0
                          Buffers: shared hit=1254
                          ->  Bitmap Heap Scan on knowledge_vec_d1024  (cost=21.26..88.76 rows=2 width=24) (actual time=0.094..1.320 rows=81 loops=1)
                                Recheck Cond: (metadata @> ANY ('{"{\"owning_unit\": \"u7\"}","{\"owning_unit\": [\"u7\"]}"}'::jsonb[]))
                                Filter: ((source_id = 'policy'::text) AND (generation = 1) AND ((embedding COSINE_DISTANCE_OP '[QUERY_VECTOR_1024]'::vector) LESS_THAN '1'::double precision) AND (SubPlan 2))
                                Rows Removed by Filter: 87
                                Heap Blocks: exact=168
                                Buffers: shared hit=902
                                ->  Bitmap Index Scan on knowledge_vec_d1024_metadata  (cost=0.00..21.26 rows=12 width=0) (actual time=0.032..0.032 rows=336 loops=1)
                                      Index Cond: (metadata @> ANY ('{"{\"owning_unit\": \"u7\"}","{\"owning_unit\": [\"u7\"]}"}'::jsonb[]))
                                      Buffers: shared hit=6
                                SubPlan 2
                                  ->  Function Scan on jsonb_array_elements e  (cost=0.02..1.89 rows=1 width=0) (actual time=0.002..0.002 rows=1 loops=81)
                                        Filter: (((v #>> '{}'::text[]) = ANY ('{u7}'::text[])) AND (jsonb_typeof(v) = ANY ('{string,number}'::text[])))
Planning:
  Buffers: shared hit=2
Planning Time: 0.243 ms
Execution Time: 1.668 ms

Tests

New: src/__tests__/scope-containment-38747.test.ts (no database: statement shape and index DDL) and src/__tests__/scope-containment-38747.live-postgres.test.ts (live PostgreSQL + pgvector via live-pg.testkit.ts). No test reads wall-clock time.

Per-shape equivalence (card: "One equivalence test per shape"). Each live case seeds passages of that shape plus controls, runs the real search for each id list, and asserts the hits equal both an explicit expected list and today's exact predicate evaluated in SQL on the same rows, written independently of the adapter:

stored shape stored values id lists checked hits
string u1, u2, 7, U1, empty string, 1.50 u1; u1,u2; 7; U1; 1.5; 1.50; nope exactly the equal string; 1.5 holds nothing
number 7, 7.5, -3, 0, 1e21, 1.50 (raw), 100 7, 7.5, -3, 0, 1000000000000000000000, 1e+21, 1.50, 1.5, 100, 7.0, 07, 1e2, +7, -0 only the stored text: 1.50 held by 1.50 not 1.5; 1e21 by its printed digits; no other spelling
list of strings [u1,u2], [u3], [] u1; u2,x; u3; x any equal element
list of numbers [7,8], [1.5], [-3], [1.50,2] (raw) 7; 8,-3; 1.5; 1.50; 2 any element by stored text
mixed list [7, "u1", null, {id: u2}, true, ["u3"]] 7, u1, u2, u3, true, null only the string and number elements
missing no unit key; {} u1, x none
null null null, u1 none (the string "null" control holds)
object {id: u1}, {u1: true} u1, {"id": "u1"}, id none
boolean true, false true, false none (the string "true" control holds)

Plus: a database that refuses the metadata CREATE INDEX (live PostgreSQL, the refusal stubbed at the pool so the case needs no role privileges on CI): the scoped search answers the same top 5, ids and scores, as the indexed path for two queries, one CREATE INDEX attempt, exactly one warning carrying the statement, index still absent. The same with a REAL role, as a one-off probe outside the suite: a role owning the store's schema and generation table but not the passage table got must be owner of table knowledge_vec_d384; both searches answered p0:1.0000, p15:0.9839, p28:0.9683, p7:0.9531, p22:0.9385, the indexed top 5; one warning; index absent. And: the vector leg's EXPLAIN on 20,000 seeded passages names Bitmap Index Scan on knowledge_vec_d384_metadata and no Seq Scan (planner left at its defaults, after ANALYZE); a table whose metadata index was dropped gets it back at a new process's first metadata-scoped search (a record-scoped search does not make it) and answers as before. Unit: index DDL string; forms for string, number-text, non-number-text, escaping, lone surrogates; the term's text and bound values in vec, cand and stats; union with a record term; no containment for a record-only scope; the ensure runs once and looks up before creating; when the create fails the search still ranks, warns once with the statement, and neither looks up nor creates again.

Counts at head 6f65533: the two new files hold 12 unit + 12 live cases; package total 165 tests in 18 files, all passing with live PostgreSQL (OS_EXPECT_LIVE_DIALECT_MATRIX=1).

Red first / ablations (both new files, live PG; every mutation through scripts/ablation-replace.mjs, restore proven by blob hash and an empty git diff HEAD):

leg result
base code (sql.ts and the adapter at f782a12, new tests kept) 13 red: 11 unit + the live EXPLAIN and existing-table cases; the record-only preservation case and the 9 equivalence cases green, as invariance pins must be on the code they are measured against
recheck neutralised (exact match ORed with TRUE) 4 red: number, list of numbers, and the two statement-shape pins
array forms dropped 7 red: list of strings, mixed list, existing table, 4 unit
number forms dropped 5 red: number, list of numbers, mixed list, existing table, 1 unit
search-time ensure call deleted 4 red: existing table + 3 unit
DDL line deleted from vectorTableDdl 2 red: DDL pin + existing table
fallback ablated: the 503 refusal put back where the create fails 2 red: the unit fallback case and the live refused-index case
failure not remembered (metadataUnindexed check removed) 2 red: the same two (a second attempt, a second warning)
Local readings at head 6f65533
  • pnpm --filter @objectstack/knowledge-pgvector test with live PostgreSQL 16.15 + pgvector 0.6.0 (OS_EXPECT_LIVE_DIALECT_MATRIX=1): Test Files 18 passed (18); Tests 165 passed (165). pnpm --filter @objectstack/knowledge-pgvector typecheck: exit 0 (tsc --noEmit and check:test-typecheck).
  • node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack derived 70 families over the 6 changed paths, run after a full turbo run build (exit 0); each with stdin from /dev/null, exit captured before any pipe; all 70 exit 0; reconciliation --ran: 70 run, 0 NOT-MEASURED, 0 UNRUN.
  • node scripts/pm/overlap-check.mjs --branch=claude/issue-38747-pgvector-scope-gin (run before the push and again at 6f65533): VERDICT clean; merges cleanly with origin/main and with feat(knowledge-pgvector): run one leg or both by the search's retrieval mode; report the three modes, hybrid by default #38745.
  • CI at 6f65533: 57 check-runs, 39 success, 18 skipped, 0 failure — including Lint & Repo Gates, TypeScript Type Check, Build Core, Test Core (12/12 shards), Check Changeset.
node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0
node scripts/check-adr-0087-registration.mjs --self-test :: exit 0
node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0
node scripts/check-closing-keyword-parity.mjs :: exit 0
node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0
node scripts/check-comment-mask-adoption.mjs :: exit 0
node scripts/check-comment-mask-adoption.mjs --self-test :: exit 0
node scripts/check-comment-mask-corpus.mjs :: exit 0
node scripts/check-dts-emitted.mjs --self-test :: exit 0
node scripts/check-empty-changeset.mjs --base origin/main :: exit 0
node scripts/check-empty-changeset.mjs --self-test :: exit 0
node scripts/check-issue-citations.mjs :: exit 0
node scripts/check-plugin-teardown-shape.mjs :: exit 0
node scripts/check-plugin-teardown-shape.mjs --self-test :: exit 0
node scripts/check-temporal-live-filter.mjs :: exit 0
node scripts/check-temporal-live-filter.mjs --self-test :: exit 0
node scripts/check-tenant-audit-census.mjs :: exit 0
node scripts/check-tenant-audit-census.mjs --self-test :: exit 0
node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0
node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0
node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0
node scripts/ci/snapshot-next.mjs --self-test :: exit 0
node scripts/docs-audit/check-affected-docs.mjs :: exit 0
node scripts/docs-audit/check-drift-comment.mjs :: exit 0
node scripts/pm/check-governed-queue-guard.mjs --self-test :: exit 0
node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0
node scripts/release-pending-publish.mjs --self-test :: exit 0
pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0
pnpm --filter @objectstack/spec run check:error-code-provenance :: exit 0
pnpm check:adr-anchors :: exit 0
pnpm check:adr-symbol-anchors :: exit 0
pnpm check:changeset-gate-self-tests :: exit 0
pnpm check:ci-filter-parity :: exit 0
pnpm check:closed-ceremony-text :: exit 0
pnpm check:cross-package-test-inputs :: exit 0
pnpm check:dispatcher-error-vocabulary :: exit 0
pnpm check:doc-authoring :: exit 0
pnpm check:driver-memory-census :: exit 0
pnpm check:dts-closure :: exit 0
pnpm check:dual-build-cjs-loads :: exit 0
pnpm check:engine-double-contract :: exit 0
pnpm check:error-status-conformance :: exit 0
pnpm check:gitlink-declared :: exit 0
pnpm check:issue-citations :: exit 0
pnpm check:keyed-text-bounds :: exit 0
pnpm check:lean-entry-closure :: exit 0
pnpm check:logger-receiver-detach :: exit 0
pnpm check:nul-bytes :: exit 0
pnpm check:object-def-param-keys :: exit 0
pnpm check:objectql-double-limit :: exit 0
pnpm check:optional-error-sink :: exit 0
pnpm check:org-identifier :: exit 0
pnpm check:page-declaration-shape :: exit 0
pnpm check:platform-object-tenancy-census :: exit 0
pnpm check:published-files :: exit 0
pnpm check:query-options-erasure :: exit 0
pnpm check:refd-timer-probe :: exit 0
pnpm check:registry-log-declared :: exit 0
pnpm check:rest-log-spy-declared :: exit 0
pnpm check:slot-lookup :: exit 0
pnpm check:sourcemap-no-sources-content :: exit 0
pnpm check:system-context-census :: exit 0
pnpm check:test-source-alias :: exit 0
pnpm check:tier-file-adoption :: exit 0
pnpm check:type-check-coverage :: exit 0
pnpm check:type-check-debt :: exit 0
pnpm check:undeclared-dep-imports :: exit 0
pnpm check:vouch-for-reference-callers :: exit 0
pnpm check:watch-hint-literal :: exit 0
pnpm check:where-matcher :: exit 0

Acceptance notes

  • The bench params pin (bench/instrument.test.mjs:189) is updated in this PR under the claim amendment; it was red at 620fadf and is green at 6f65533.
  • pgvector-adapter.ts is over 1,000 lines; the ensure method sits beside its twin ensureKeywordIndex rather than in a new module because the claim's file surface admits no new source file.
  • ensureKeywordIndex still sends CREATE INDEX IF NOT EXISTS without a lookup first, so its once-per-process run waits on an open writer; not changed here.

Verification

Read first, by risk: pgvector-adapter.ts scope-term block (the AND of containment and exact match); sql.ts metadataScopeForms (the number-text rule); pgvector-adapter.ts ensureMetadataIndex.

Two-minute check: with a pgvector PostgreSQL in OS_TEST_POSTGRES_URL, pnpm --filter @objectstack/knowledge-pgvector exec vitest run src/__tests__/scope-containment-38747.live-postgres.test.ts — expect 12 passed, including "the vector leg reads the passages in scope through the metadata index" and "a database that refuses the metadata index".


Generated by Claude Code

@github-actions github-actions Bot added size/l 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 30, 2026
@github-actions

github-actions Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

12 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 252 client-bound route-ledger rows — the other 183 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 183: 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; 124 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 — 3 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 acf3b33e311be863984f685092cd2347dfb51272 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 74ef49473dc6ef6645051fb0d6cf88cd81f9da0b — the merge of head 6f655337877653528de9879cd2756d0be0de41bb into base acf3b33e311be863984f685092cd2347dfb51272, 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 74ef49473dc6ef6645051fb0d6cf88cd81f9da0b && git checkout 74ef49473dc6ef6645051fb0d6cf88cd81f9da0b
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin acf3b33e311be863984f685092cd2347dfb51272 6f655337877653528de9879cd2756d0be0de41bb && git checkout -B drift-repro acf3b33e311be863984f685092cd2347dfb51272 && git merge --no-ff 6f655337877653528de9879cd2756d0be0de41bb

node scripts/docs-audit/affected-docs.mjs --json acf3b33e311be863984f685092cd2347dfb51272

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

…ades to the scan with one warning

Claude-Session: https://claude.ai/code/session_01ADHkmTLwBddAv8qQwmLzdk
Co-authored-by: Claude <noreply@anthropic.com>
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#3 · os-steve · session_01ADHkmT9HTWLMN33WUVxVWB
L1-b, the seat's L1 thread · 2026-11-30T12:20Z · first review

席位核对

ACCEPT @ 6f65533 (card #38747, Fixes; 6 files, one package)

  • Relation. Fixes #38747 delivers the card:

    • What 1: the GIN jsonb_path_ops index in the DDL, and the existing-table path at search time.
    • What 2: containment forms bound as jsonb[].
    • What 3: today's exact predicate kept byte for byte, ANDed.
    • The acceptance items: before/after EXPLAIN ANALYZE, the first-build cost, and a live-PG EXPLAIN pin.

    @> ANY($N::jsonb[]) in place of an explicit OR of forms is a sound reading of What 2, and the body gives the plan. The landing order changed under Steve's 12:02:57Z ruling, as the body records. No closing keyword binds any other card.

  • Superset, read on the code. metadataScopeForms gives each id {f:"id"} and {f:["id"]}. It adds the number pair when the id matches NUMERIC_TEXT (^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$). That is every text PostgreSQL prints for a jsonb number: numeric never prints an exponent, and -0 prints 0. So every stored string, number or list element the exact match accepts is contained by one of the forms, and the containment cannot drop a hit. The ANDed recheck keeps the hits exact (the 1.5/1.50 case). Lone surrogates are written the way the driver sends the exact match's text.

  • The existing-table path. ensureMetadataIndex is the twin of ensureKeywordIndex. It looks up with to_regclass before it creates, so the steady state is lock-free. When the create fails it looks up again, so a lost race reads as made. On a create the role may not make, the width goes into metadataUnindexed, one warn carries the full statement, and the search runs today's statement by a scan. That is the seat's 11:32Z ruling, option B.

    • Nit: on the first scoped search, the create waits behind any open write transaction on the table (SHARE vs ROW EXCLUSIVE). That search waits too. The changeset's "holds the table's writes, not its reads, while it builds" is true of the build, but it does not say the triggering search can wait. This does not block.
  • Declarations. Clause-②: no and Metadata-protocol: none match: there is no signature, wire or published-schema change. The changeset is patch for the one package touched, and I read it sentence by sentence; each sentence is true to the code. The bench/instrument.test.mjs:189 pin is in the surface by the seat's claim amendment.

  • My runs at this head (fresh worktree, offline install, @objectstack/knowledge-pgvector^... built):

    • scope-containment-38747.test.ts: 12/12 passed.
    • The whole package: 58 passed and 107 skipped (no PG_URL here, so the live files skip).
    • Ablations, each restored to HEAD:
      • A, the number forms never added: 1 red ("adds the two number forms…").
      • B, metadataUnindexed.add removed: 1 red ("…warns once… and never tries again").
      • C, the recheck AND turned to OR: 3 red (the two statement-shape pins, plus the refusal case's statement check).
  • NOT MEASURED by me: the live-PG file. That covers the per-shape equivalence, the index named in EXPLAIN, the refused-index fallback and the pre-index table. The dev ran it, 165/165 on local PG16 with pgvector 0.6.0. In CI, Temporal Conformance (live PG + MySQL) never runs on pull_request. It runs in the merge queue when temporal_live paths are hit, and packages/plugins/knowledge-pgvector/** is one of them, on pgvector 0.8.7. So the live pins are read for the first time at the queue.

Checks at this head (read before writing): 41 success, 20 skipped, 0 failure, 0 pending. mergeable_state is clean, and Check Changeset has re-run green. The opt-in Dogfood battery skips are expected; it is not owed, since there is no ! and no (narrowing) arm.
L2: not owed. Clause-②: no, Metadata-protocol: none, and nothing governed. The zone lands it.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#3 · os-steve · session_01ADHkmTLwBddAv8qQwmLzdk

Landing · 2026-11-30T12:23Z · head 6f655337877653528de9879cd2756d0be0de41bb · ACCEPT → PR #38758 comment 7278324503 (L1-b, first review) · no contract review owed (Clause-②: no, Metadata-protocol: none)

Probe Reading
check-governed-merges.mjs --pr 38758 NOT governed (0 of 6 paths hit the register); 651 changed lines ≤ 3000
landing-k.mjs --pr 38758 K = 0 < 15; no locale pack; no shared book moved under this PR

Checks: pr-state.mjs at this head reads 41 success · 20 expected skip · 0 failed · 0 pending; mergeable_state clean. Landing order: by the maintainer's ruling at 2026-11-30 12:02:57Z (recorded on #38747), this PR no longer waits for #38745. Shared-file note: PR #38761 also edits bench/instrument.test.mjs, on different lines; whichever lands second merges main. State: ready + auto-merge armed through the relay; Fixes #38747 closes the card on merge.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 30, 2026 12:24
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 30, 2026
Merged via the queue into main with commit 111ad63 Nov 30, 2026
62 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-38747-pgvector-scope-gin branch November 30, 2026 12:55
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…ut a code is refused, never answered as no hits (objectstack-ai#38761)

<!-- claude-projects-attribution: {"github_login":"os-steve"} -->
_Requested by **Steve** · [project
thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9DAwBxBGNv4CexdUyBYJXSw)_
Fixes objectstack-ai#38728
repo:objectstack#3 · os-steve · session_01ADHkmPDtfMCw4FJfyFfQ7v

Clause-②: no (narrowing)
Metadata-protocol: none

## 维护者速读

- 变化:知识库检索时,某个来源的检索服务出错(如向量服务连不上)不再显示成「什么都没搜到」,而是列为「该来源未能检索」。
- 谁会碰到:只在某来源检索抛出无错误码的异常时出现;若它是本次唯一被检索的来源,整次检索改为报「服务不可用」(503),其他来源照常返回结果。
- 出错会怎样:最坏是把出错来源误报为不可用;改动集中在一处,可直接撤回。
- 要你做什么:无。

## BREAKING

**BREAKING** for a caller of a knowledge search (the `search_knowledge`
tool, its MCP HTTP and stdio faces, and in-process
`KnowledgeService.search` / `searchWithRefusals`) when a source's
adapter throws from `search` with an error that does not carry both an
ADR-0112 `code` and `status` (an embedder that cannot be reached, a
timeout outside the store). The search now names that source in
`refused`, coded `SERVICE_UNAVAILABLE` (503), with a platform sentence
naming the source; before, the source read as if it had matched nothing.
The thrown message is not shown to the caller; the operator's `error`
log line keeps it. Sources that answer are still served beside the
refusal. A source that matches nothing is unchanged, and so is a coded
refusal's own `refused` entry; a whole rejection that also names an
uncoded throw may take that throw's top-level code (cell 2 below).
Declared as a narrowing per L1 REWORK 7279138481; registered in the
ADR-0087 ledger as semantic entry
`knowledge-search-uncoded-adapter-throw-refused`
(`packages/spec/src/migrations/entries/semantic/19.knowledge-search-uncoded-adapter-throw-refused.ts`,
a new file; the registry is generated, no existing spec file edited),
added to the file surface by claim amendment 2 (comment 7279244160).

FROM → TO:
- No searched source answers and at least one threw without a code — two
cells:
1. Every searched source throws without a code (one source, or several
failing on the same embedder outage). FROM: the search succeeded with `{
hits: [] }`. TO: rejected `SERVICE_UNAVAILABLE` / 503 with `refused`
naming each source (the `search_knowledge` executor and in-process
`search` reject with `refused`; MCP answers an error result whose
envelope is `code`, `message` and `status`, the sources named in the
message).
2. A source throws without a code beside a source refused with a code,
none answering. FROM: rejected with the coded source's `code` / `status`
and `refused` naming it alone. TO: `refused` names both, and the
rejection's top-level `code` / `status` are the first refusal's in
source order, so a 409 `KNOWLEDGE_REBUILD_REQUIRED` rejection may now
read 503 `SERVICE_UNAVAILABLE`.
- A refill fails without a code. FROM: the source's round-one survivors
were served. TO: they are dropped and the source is refused for the
whole search, as a coded refusal of the refill already was.

Fix for each reader: a caller reads `refused` and the 503 instead of
treating an empty answer as no match; an operator repairs the adapter or
embedder the `error` line names.

## What changes

`searchRound`
(`packages/services/service-knowledge/src/knowledge-service-search.ts`)
catches an adapter's throw from `search`. A coded refusal (ADR-0112
`code` + `status`) was already pushed to `refused`; any other throw was
only logged at `error`, so the source read as zero hits. Now an uncoded
throw is pushed to `refused` as `{ sourceId, code:
'SERVICE_UNAVAILABLE', status: 503, message }`, where `message` is a
platform sentence naming the source and its adapter id (never the thrown
text, which can carry hosts, SQL or keys). The operator `error` line is
unchanged and still carries the thrown message. The docblock states the
new outcome.

Code choice: the existing `SERVICE_UNAVAILABLE` (503), the code this
package already answers for an adapter that cannot serve
(`UNMOUNTED_ADAPTER_CODE`, `knowledge-service-top-level.ts`). No new
code is minted, so no ledger or `StandardErrorCode` change. The literal
is written in the catch (not the constant imported) to stay inside the
claimed hunk.

Consequences that follow from the existing refusal machinery, unchanged
by this diff:
- When no searched source answers (`first.size === 0 && refused.length >
0`), the search is refused whole (`wholeRefusal`), so a search whose
only source's embedder is down now rejects with `SERVICE_UNAVAILABLE` /
503 and `refused`, instead of resolving `[]`.
- Refill: a source refilled is one that answered round one, so it is
never refused twice in one search. A source that fails the refill
uncoded is now refused for the whole search and its round-one hits
dropped, as a coded refusal of the refill already was
(`refusedInRefill`).

## Public doors

Measured on `origin/main` acf3b33 plus this branch; there is no REST
knowledge search route (a grep of `packages/rest/src` and
`packages/runtime/src` for a knowledge search route finds none; the same
grep finds the `search_knowledge` registrations below).
- `search_knowledge` executor,
`packages/services/service-knowledge/src/knowledge-tools.ts:662-671`:
with other sources answering, the tool output now carries `refused: [{
sourceId, code: 'SERVICE_UNAVAILABLE', message }]` beside their hits
(before: no `refused`, the source silent). When it is the only searched
source, the executor rejects with the whole refusal (`wholeRefusal`,
thrown at `knowledge-service-search.ts:231`, or `:258` on a refill):
`code: 'SERVICE_UNAVAILABLE'`, `status: 503`, `refused` naming the
source (before: `{ hits: [] }`).
- MCP `search_knowledge`, `packages/mcp/src/mcp-http-tools.ts:3824-3826`
(registered for HTTP at `mcp-http-tools.ts:3428` via
`packages/runtime/src/domains/mcp.ts:1786`, and for stdio at
`packages/mcp/src/plugin.ts:1068` via `stdio-data-bridge.ts:1998`): the
partial case returns the text result with `refused`; the only-source
case returns `errorResultWithCode` (`mcp-http-tools.ts:1636`), an error
result with the ADR-0112 envelope `SERVICE_UNAVAILABLE` / 503 (before: a
text result with no hits).
- In-process `KnowledgeService.search` / `searchWithRefusals` callers
(no other non-test caller in this repo): same as the executor.

## Tests

New `src/__tests__/search-uncoded-throw-38728.test.ts` (5 cases): plain
`Error` gives one `refused` entry naming the source (code + status
asserted, thrown text absent from the caller's message, present in the
`error` line), other sources' hits still served; only source throwing
uncoded refuses the search whole (503); coded refusal unchanged; source
matching nothing answers no hits and no refusal; refill failure refused
once, round-one hits dropped.

Flipped pins of the old "logged, zero hits" outcome (each now asserts
the refusal's sourceId/code/status):
- `knowledge-service.test.ts` "a refill the adapter fails keeps the
source's round-one survivors" -> refused as a coded refill refusal is.
- `knowledge-tools.test.ts` "control: a failure without a code is logged
and skipped as before" -> refused `SERVICE_UNAVAILABLE`, text withheld.
- `knowledge-settings-contribution.test.ts`: "no settings: ... search
answer an error", "the API key is in no log line and no error", "a
plugin a host mounts itself, no embedder" -> search rejects
`SERVICE_UNAVAILABLE` / 503 naming `docs`.
- `packages/plugins/knowledge-pgvector/bench/instrument.test.mjs` "a
failed embed is counted, and the search answers no hit with the
service's "search failed" line" (`s.ok` true, `s.hits` 0) -> "a failed
embed is counted, and the search is refused SERVICE_UNAVAILABLE naming
the source, with the service's "search failed" line": `s.ok` false,
`s.errorCode` `SERVICE_UNAVAILABLE`, the thrown refusal
`SERVICE_UNAVAILABLE` / 503 with `refused` naming `clauses`;
`embedFailures` 1, `calls.ranking` 0 and the one "search failed"
operator line kept.

This sixth pin was added to the file surface by claim amendment 1
(comment 7278305559).

Files changed (8):
- `packages/services/service-knowledge/src/knowledge-service-search.ts`
-
`packages/services/service-knowledge/src/__tests__/search-uncoded-throw-38728.test.ts`
-
`packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts`
-
`packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts`
-
`packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts`
- `packages/plugins/knowledge-pgvector/bench/instrument.test.mjs`
- `.changeset/38728-uncoded-search-throw.md`
(`@objectstack/service-knowledge` and `@objectstack/spec` patch,
`fix(service-knowledge)!:`, `Clause-②: no (narrowing)`, the ADR-0087
`registered` marker)
-
`packages/spec/src/migrations/entries/semantic/19.knowledge-search-uncoded-adapter-throw-refused.ts`
(new; claim amendment 2, comment 7279244160)

<details><summary>Readings (tests at 43def1f; e52b762 adds only the
changeset sentence)</summary>

- `pnpm --filter @objectstack/service-knowledge test`: Test Files 26
passed (26), Tests 841 passed (841).
- `pnpm --filter @objectstack/service-knowledge typecheck` (tsc over
`src`, tests included, plus `check:test-typecheck`): exit 0.
- Ablation: catch reverted to `acf3b33e` on disk, new file run: 3 failed
/ 2 passed (the three uncoded pins red; coded and no-match pins green).
Fix restored.
- Local derived gates: 40 of 69 run, all exit 0 except
`check-plugin-teardown-shape --self-test` (exit 3, shallow-clone
prerequisite, NOT MEASURED) and `check:type-check-debt` (local 100 s
timeout, NOT MEASURED). The other 29 are left to CI.
- `overlap-check.mjs`: VERDICT clean exit 0 (merges cleanly with main,
objectstack-ai#38722, objectstack-ai#38730, objectstack-ai#38732).
- Round 2 (6348efa): `bench/instrument.test.mjs` alone 8 passed (8);
`pnpm --filter @objectstack/knowledge-pgvector test` 46 passed, 95
skipped (live-postgres); knowledge-turso 301 passed; knowledge-memory 66
passed; overlap-check VERDICT clean exit 0 (also objectstack-ai#38758).
</details>

## Acceptance notes

- Read first: the catch block in `searchRound` (the only runtime hunk);
then the refill pin flip in `knowledge-service.test.ts`, which is the
one behaviour change beyond the card's literal Ask (a refill failure now
drops round-one survivors instead of keeping them, to match the coded
path).
- The stand-in embedder's "No embedder is configured ... restart" text
is uncoded, so the caller now reads the generic platform sentence and
the remedy stays on the operator line. Coding that error at its producer
would let the caller read the remedy; noted, not filed.
- `content/docs/protocol/knowledge.mdx` not edited (open PRs edit it;
skipped per dispatch).

## Verification

Two-minute check: `pnpm --filter @objectstack/service-knowledge exec
vitest run src/__tests__/search-uncoded-throw-38728.test.ts` -> 5
passed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01ADHkmPDtfMCw4FJfyFfQ7v
<!-- signed: repo:objectstack#3 · os-steve ·
session_01ADHkmPDtfMCw4FJfyFfQ7v -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
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/l tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

knowledge-pgvector:带范围检索先按范围取行再算距离(metadata GIN 索引 + 包含式范围条件,专题 #38703)

2 participants