Repository navigation
fix(knowledge-pgvector): read only the passages in scope for a metadata-scoped search, through a GIN index on metadata - #38758
Conversation
…on metadata Claude-Session: https://claude.ai/code/session_01ADHkmTLwBddAv8qQwmLzdk Co-authored-by: Claude <noreply@anthropic.com>
…d per-kind equivalence Claude-Session: https://claude.ai/code/session_01ADHkmTLwBddAv8qQwmLzdk Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ADHkmTLwBddAv8qQwmLzdk Co-authored-by: Claude <noreply@anthropic.com>
📓 Docs Drift Check12 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
Coarse fallback — 3 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # 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 |
…ades to the scan with one warning Claude-Session: https://claude.ai/code/session_01ADHkmTLwBddAv8qQwmLzdk Co-authored-by: Claude <noreply@anthropic.com>
|
repo:objectstack#3 · os-steve · session_01ADHkmT9HTWLMN33WUVxVWB 席位核对ACCEPT @ 6f65533 (card #38747,
Checks at this head (read before writing): 41 success, 20 skipped, 0 failure, 0 pending. |
|
repo:objectstack#3 · os-steve · session_01ADHkmTLwBddAv8qQwmLzdk Landing · 2026-11-30T12:23Z · head
Checks: |
…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>
Requested by Steve · project thread
Fixes #38747
Clause-②: no
Metadata-protocol: none
维护者速读
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-checkreads the two as merging cleanly in either order.What changes
sql.ts— a GIN index onmetadatawithjsonb_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 anumeric(optional minus, no leading zero, optional fraction, no exponent),{field: id}and{field: [id]}as numbers.pgvector-adapter.ts, the metadata scope-term block — eachmetadataterm is now(metadata @> ANY($N::jsonb[]) AND EXACT), whereEXACTis today's predicate byte for byte (thejsonb_array_elementsEXISTS) and$Nbinds 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 stored1.50whose text the exact match compares as1.50. The oneinScopestring still feeds thevecCTE, thecandCTE and thestatscount, so all three read through the index.@> ANY(jsonb[])is one bound parameter per term rather than an explicitORof 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 carriesmetadata @> 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 ofensureKeywordIndex, called from the scope-term block when a search holds ametadataterm. It looks the index up withto_regclassfirst and creates it only when absent.Existing tables: does the DDL path already run, and what the first time costs
vectorTableDdlruns fromensureVectorTable, which is reached only byupsertandbeginBuild, and is skipped for the life of the process once any search has found the table (tableExistsfills the sametablesset). 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.CREATE INDEXtakes 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), andANALYZE264 ms (the ensure does not runANALYZE; autovacuum does). The card's acceptance DB measured 0.27 s build and 2.1 sANALYZEwith real metadata.CONCURRENTLY: an interrupted concurrent build leaves an INVALID index under the name, andIF NOT EXISTSthen 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.CREATE INDEX IF NOT EXISTSon an index that already exists still waits for the table lock — with a writer's transaction open it was cancelled by a 800 mslock_timeout, whileto_regclassanswered at once. The lookup keeps the steady state lock-free.ensureMetadataIndexrecords the width inmetadataUnindexed(the failure twin ofmetadataIndexed), logs ONEwarnnaming the consequence and the fullCREATE INDEXstatement 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, sowarn, noterror(AGENTS.md degradation levels). Coded refusals insrc/errors.ts,ensureKeywordIndexand B2'sSET LOCAL statement_timeoutare untouched.Before / after: one scoped
vecstatementSeeded table, local PostgreSQL 16.15 + pgvector 0.6.0,
jit = off: 58,500 passages, 1024 dimensions,owning_unitover 350 units (a tenth of the passages list two units), scopeowning_unit = u7(336 passages hold it, 81 below distance 1). Statement: the adapter's ownvecCTE, recorded from a real search and re-run underEXPLAIN (ANALYZE, BUFFERS); four runs each. Shared container, so treat absolute milliseconds as indicative.knowledge_vec_d1024_metadataIn the plans
COSINE_DISTANCE_OPstands for pgvector's cosine-distance operator andLESS_THANfor the less-than sign; the query vector is elided.Before: EXPLAIN (ANALYZE, BUFFERS), run 4
After: EXPLAIN (ANALYZE, BUFFERS), run 4
Tests
New:
src/__tests__/scope-containment-38747.test.ts(no database: statement shape and index DDL) andsrc/__tests__/scope-containment-38747.live-postgres.test.ts(live PostgreSQL + pgvector vialive-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:
u1,u2,7,U1, empty string,1.50u1;u1,u2;7;U1;1.5;1.50;nope1.5holds nothing7,7.5,-3,0,1e21,1.50(raw),1007,7.5,-3,0,1000000000000000000000,1e+21,1.50,1.5,100,7.0,07,1e2,+7,-01.50held by1.50not1.5;1e21by its printed digits; no other spelling[u1,u2],[u3],[]u1;u2,x;u3;x[7,8],[1.5],[-3],[1.50,2](raw)7;8,-3;1.5;1.50;2[7, "u1", null, {id: u2}, true, ["u3"]]7,u1,u2,u3,true,nullunitkey;{}u1,xnullnull,u1"null"control holds){id: u1},{u1: true}u1,{"id": "u1"},idtrue,falsetrue,false"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, oneCREATE INDEXattempt, 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 gotmust be owner of table knowledge_vec_d384; both searches answeredp0: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'sEXPLAINon 20,000 seeded passages namesBitmap Index Scan on knowledge_vec_d384_metadataand noSeq Scan(planner left at its defaults, afterANALYZE); 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 invec,candandstats; 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 emptygit diff HEAD):sql.tsand the adapter at f782a12, new tests kept)vectorTableDdlmetadataUnindexedcheck removed)Local readings at head 6f65533
pnpm --filter @objectstack/knowledge-pgvector testwith 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 --noEmitandcheck:test-typecheck).node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstackderived 70 families over the 6 changed paths, run after a fullturbo 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.Acceptance notes
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.tsis over 1,000 lines; the ensure method sits beside its twinensureKeywordIndexrather than in a new module because the claim's file surface admits no new source file.ensureKeywordIndexstill sendsCREATE INDEX IF NOT EXISTSwithout a lookup first, so its once-per-process run waits on an open writer; not changed here.Verification
Read first, by risk:
pgvector-adapter.tsscope-term block (the AND of containment and exact match);sql.tsmetadataScopeForms(the number-text rule);pgvector-adapter.tsensureMetadataIndex.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