Repository navigation
refactor(service-knowledge): split KnowledgeService into five concern modules behind a delegating facade - #38700
Conversation
…ts (wip) Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude <noreply@anthropic.com>
…gate Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude <noreply@anthropic.com>
…s can read Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude <noreply@anthropic.com>
…evel headers Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude <noreply@anthropic.com>
…o on its facet body Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude <noreply@anthropic.com>
…ies at their modules Claude-Session: https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd Co-authored-by: Claude <noreply@anthropic.com>
📓 Docs Drift CheckThis PR changes 2 package(s): 51 hand-written doc(s) name something this change touched — list omitted above 15 rows. Re-derive on the tree named below: ⛔ 19 release-owned page(s) also affected — read-only, see AGENTS.md Documentation Guardrails. What this run could not see
Coarse fallback — 182 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 a09134dda9acf85c8e7b85333f334b13ff4903ea && git checkout a09134dda9acf85c8e7b85333f334b13ff4903ea
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 5ac1ee0bc8a79ab2238ded80123ba91623ad6081 ad4f458a7cee52716072fa5581efa57f89d6d4e3 && git checkout -B drift-repro 5ac1ee0bc8a79ab2238ded80123ba91623ad6081 && git merge --no-ff ad4f458a7cee52716072fa5581efa57f89d6d4e3
node scripts/docs-audit/affected-docs.mjs --json 5ac1ee0bc8a79ab2238ded80123ba91623ad6081
|
|
repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu 维护者速读
席位核对ACCEPT · L1 · area o2-A · Head-sha
|
|
repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu Contract-review-claim: session_01JQwxbXyLoBzNYY1U8SNPFu · head ad4f458 · 2026-11-30T06:05Z |
|
repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu Contract reviewServed-tier: PR #38700 on card #38660, reviewed for its size (10,495 changed lines), not for a contract path: ① Derived judgments
② Semver levelClause-②: no — matches the PR body and the changeset; no arm.
③ Boundary flagsThe report's
SQL push-down: no finding. The diff adds no query, no id materialisation and no in-app join; every engine call sits on a line identical to the base. Security: the moved bodies include the permission and admission paths ( Escalated: nothing. ④ Design judgmentHow the move was read: the base blob of
Findings:
Observation, not a finding: ADR-0096 and ADR-0161 cite No must-fix, no should-fix. Implemented-by: VERDICT: PASS |
|
repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu Contract reviewServed-tier: PR #38700 on card #38660, reviewed for its size (10,495 changed lines), not for a contract path: ① Derived judgments
② Semver levelClause-②: no — matches the PR body and the changeset; no arm.
③ Boundary flagsThe report's
SQL push-down: no finding. The diff adds no query, no id materialisation and no in-app join; every engine call sits on a line identical to the base. Security: the moved bodies include the permission and admission paths ( Escalated: nothing. ④ Design judgmentHow the move was read: the base blob of
Findings:
Observation, not a finding: ADR-0096 and ADR-0161 cite No must-fix, no should-fix. Implemented-by: VERDICT: PASS |
|
repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu 2026-11-30T06:14Z · L1 ACCEPT and hand-off · #38660 (KnowledgeService split, move-only) at
|
⛔ merge queue 构建失败 — 先分诊,再决定要不要重排队列构建 46372721759 红了。队列跑的是全量套件(PR 侧 CI 只跑 affected 子集), 分类: 失败的 job(日志抽取,best effort):
跨 PR 相同签名(24h,按失败测试文件聚合):
历史信号:
分诊清单:
Generated by Claude Code · merge-queue-triage workflow (#4859) |
|
repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu 2026-11-30T07:46Z · Queue ejection is inherited, not this PR's. Build 46372721759 failed Head is unchanged at |
… for search_knowledge (objectstack-ai#38729) <!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ88oxgpPaPHgsNM7N7PvvwbS)_ Refs objectstack-ai#38719 (part 1) — the committed segment timing and the load bench. Part 2, the baseline on the A4 environment, stays on the card, which this PR does not close. Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户无感:只新增一个提交进仓库的测速脚本,产品行为不变。 - 属于「私有部署企业版知识检索 10 人同时提问不超时」专题的基线一项,给第三期每项做不做提供数据。 - 出错只会让测速读数不准,不影响任何客户;脚本不随软件包发布,可直接撤回。 - 无。 ## What changes A new, unpublished directory `packages/plugins/knowledge-pgvector/bench/` (the package's `files` is `dist`, `README.md`, `CHANGELOG.md`, so nothing here ships): - `instrument.mjs` — per-search segment timing read through seams the code already takes. Nothing under `src/` of this package or of `service-knowledge` is changed: - `embed` — the adapter's `embedder` option; - `pool_wait` + `ranking` + `other_sql` — the adapter's `pool` option, a `PgPoolLike` whose one-shot query is split into checkout, statement and release, the same steps `pg.Pool#query` runs; - `visible_ids` + `permission_recheck` + `system_read` — the service's `dataEngine` option, each read classified by the arguments the service passes; - adapter rounds (a refill round = backfill) — the adapter as registered with the service. Concurrent searches are kept apart by an `AsyncLocalStorage` store per search. - `run.mjs` — the load bench, runnable against any PostgreSQL URL with pgvector. It seeds a synthetic dataset into two throwaway schemas, builds the index through the real `KnowledgeService`, then makes real `search_knowledge` calls (the tool executor, as a non-system caller) over record-scope fraction × concurrency. Default grid: 1/10/30/100 % and unscoped × 1/5/10/20 clients, closed loop. - Per cell: p50/p95/max/mean of the total and of every segment, each with its sample count; hit count; searches per question; backfill share (scoped and unscoped cells are separate rows); embedding-call failures; failed and refused searches with their codes; empty answers; the service's `search failed` log lines; block reads of the store's tables. - It also records the machine shape (client CPUs and memory; server version, pgvector version and memory settings) and whether the cell ran cold or warm. - `instrument.test.mjs` — pins statement shape and call counts over the real adapter and service from source, with no database. It never pins a duration. - `README.md` — the manual. ### Segment status | segment (card) | status | seam | |:--|:--|:--| | embed | measured | adapter `embedder` option | | vector statement | measured as `ranking` | adapter `pool` option; the statement also carries the keyword leg for any query with keyword terms (counted per cell) and the scope predicate | | scope predicate | **NOT MEASURED in situ** | it is a conjunct of the ranking statement's one WHERE. `--isolate-scope` adds a DERIVED out-of-situ number: the same WHERE as a bare count minus the source-and-generation WHERE as a bare count, run serially and timed by the server. An in-situ number needs the store to time its statement parts itself, a change under `knowledge-pgvector/src` (held by objectstack-ai#38692) | | permission re-check | measured | service `dataEngine` option (`permission_recheck` after ranking, `visible_ids` before it) | | pool wait | measured (not on the card) | adapter `pool` option | ## Tests - `pnpm --filter @objectstack/knowledge-pgvector test` at `8e3e522f`: 6 files passed, 8 skipped (the live-PostgreSQL files: no `OS_TEST_POSTGRES_URL`); 29 tests passed, 93 skipped. - `pnpm --filter @objectstack/knowledge-pgvector typecheck`: exit 0. The bench files are `.mjs` and outside the package's TS programs. - Ablation: with `permission_recheck` reclassified on disk, `bench/instrument.test.mjs` went red (1 failed / 4 passed); restored with `git restore`. <details><summary>Local smoke run — 5,000 passages, 1024 dims, 40 searches a cell (NOT a baseline, not quotable)</summary> Machine: 4 vCPU, 15.7 GiB, shared container. PostgreSQL 16.15 with pgvector **0.6.0** (Ubuntu package; the kit ships 0.8.7), `shared_buffers` 512MB, pool 4, fake in-process embedder, warm. Its job is to show the script runs the whole grid; it is not the A4 baseline. Columns: scope · concurrency · n · total p50/p95 ms · pool wait p50 · ranking p50 · re-check p50 · backfill · `search failed` lines · rows in scope. ``` 1% | 1 | 40 | 53.73 / 73.57 | 0.1 | 50.46 | 1.95 | 0 | 0 | 50 1% | 20 | 40 | 434.59 / 625.09 | 350.72 | 71.83 | 2.21 | 0 | 0 | 50 10% | 1 | 40 | 73.35 / 106.8 | 0.09 | 70.21 | 1.87 | 0 | 0 | 500 30% | 1 | 40 | 114.04 / 205.01 | 0.08 | 111.08 | 1.73 | 0 | 0 | 1500 100% | 1 | 40 | 263.53 / 453.83 | 0.07 | 260.75 | 1.69 | 0 | 0 | 5000 100% | 20 | 40 | 1776.19 / 2117.96 | 1451.12 | 323.8 | 5.45 | 0 | 0 | 5000 none | 1 | 40 | 250.89 / 491.17 | 0.07 | 245.3 | 1.82 | 0 | 0 | - none | 20 | 40 | 1295.42 / 1570.26 | 1046.31 | 241.46 | 1.56 | 0 | 0 | - ``` All 20 cells completed with 0 failed searches; the full table is in the run's JSON. </details> ## Acceptance notes - **First files to read:** 1. `bench/instrument.mjs` — `classifyEngineRead`, which decides what counts as the permission re-check, and `timedPool`, which reproduces `pg.Pool#query`'s checkout, statement and release. 2. `bench/run.mjs` — `isolateScope`, the derived scope-predicate pass, and its stated method. 3. `bench/instrument.test.mjs` — the pins over the real adapter and service. - The bench composes its own service over synthetic data (ObjectQL + SqlDriver, no security plugin), so the re-check reads every row it asks for. It cannot yet point at an already-indexed source in a kit deployment (the BrightRule source on A4); part 2 has to decide that. - At concurrency 10–20, the smoke run's time goes mostly to waiting for one of the pool's 4 connections. That is the topic's B2 (pool size from settings), not new scope. - No changeset: no published file moves (`skip-changeset`). - Seat routing (2026-11-30T08:16Z), part 2 composition: B — on A4 the bench composes the source itself at 60k×1024; an existing-source option (A) may follow after objectstack-ai#38700 only if needed. - Seat routing (2026-11-30T08:16Z), scope predicate: keep the labelled DERIVED number (`--isolate-scope`); no store seam under objectstack-ai#38692's files. ## Verification Two-minute check, against any PostgreSQL where the role can `CREATE` and the `vector` extension is available: ```bash pnpm --filter '@objectstack/knowledge-pgvector...' build node packages/plugins/knowledge-pgvector/bench/run.mjs --pg-url postgres://USER@HOST:5432/DB --passages 500 --scopes 10,none --concurrency 1,5 --searches 20 --isolate-scope ``` Expected: a markdown table with four rows, every `ok` equal to `n`, the 10% rows showing `… (derived)` in the last column and the unscoped rows `NOT MEASURED`; the JSON path printed on stderr. Both schemas are dropped at the end. --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbXQcnpisuAAJRr8yNr <!-- signed: repo:objectstack@os-warren · os-warren · session_01JQwxbXQcnpisuAAJRr8yNr --> --------- Co-authored-by: Claude <noreply@anthropic.com>
…ement has a time limit, and its pool size is a setting (objectstack-ai#38726) <!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8VZtjriPRDBMFWChF2eLFkE)_ Fixes objectstack-ai#38718 Clause-②: yes Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:私有部署企业版在 PostgreSQL 上检索知识时,数据库忙、连接等不到或语句超时,助手会收到明确的「超时 / 暂不可用」拒绝,不再拿到「0 条命中」;检索语句默认最多跑 10 秒;连接池大小可以由运维通过设置调整。 - 为什么做:属于「私有部署企业版知识检索 10 人同时提问不超时」专题第一期,目标之一是出错不能变成空结果,首个用户是 BrightRule 制度问询。 - 出错会怎样:最坏情况是本来能跑完的超长检索(超过 10 秒)现在被拒绝为超时,运维可调大时限设置;改动只在知识检索的 PostgreSQL 适配器内,撤回即恢复原样。 - 要你做什么:无。 ## What changes Topic objectstack-ai#38703 row B2, in `@objectstack/knowledge-pgvector` only (no change to `service-knowledge` or `core`). 1. **Coded refusals.** `search()` now answers every failure of the store's database as an ADR-0112 refusal, judged by SQLSTATE (never by the server's message, which `lc_messages` translates): `57014` (statement past its limit, or cancelled) is `TIMEOUT` 504; class `53` (`too_many_connections`, out of memory, disk full) is `SERVICE_UNAVAILABLE` 503; no connection (the pool's wait timed out, class `08`, `57P01`–`57P05`, a socket error) is `SERVICE_UNAVAILABLE` 503; any other SQLSTATE is `DATABASE_ERROR` 500. The message is one sentence naming the source; the SQLSTATE, the driver text and the setting to change go to `remedy` (operator text the service logs). An already-coded error (the adapter's own refusals) and a non-database error (the embedder's) pass through unchanged. New module `src/errors.ts`. - The pool's wait timeout carries no code at all, so `poolFromPg` now marks every error its pool and connections throw (a non-enumerable symbol; message, code and keys untouched, so write paths read exactly what `pg` threw), and the classifier treats a marked uncoded error as "no connection". - Placement: the translation is one `try/catch` in `search()` around the attempts loop (moved into a private `searchAttempts`); the ranking statement's body is untouched (the objectstack-ai#38692 phase-1a pgvector PR follows this one). 2. **Statement time limit.** The ranking statement runs through a new `searchStatement` helper: its own transaction, `SET LOCAL statement_timeout = N` first. Chosen form: `SET LOCAL` in a transaction, so the limit lasts exactly one statement, touches no session state and holds behind a transaction-mode pooler (the builder lock still needs session mode; README says so). Default 10000 ms, the same bound the Turso store uses for a remote request (objectstack-ai#38693); `statementTimeoutMs` plugin/adapter option, else the setting `OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS`. Only the ranking statement is limited; catalog reads, writes and builds are not. 3. **Pool size from a named setting.** `OS_KNOWLEDGE_POOL_MAX` (plugin option `poolMax` wins), default **20** (raised from 4 in Rework 2 below, on os-bob's measurement). Strict like `OS_DATABASE_POOL_MAX`: a value that is not a positive integer stops the boot naming the setting; blank reads as unset. The plugin reads it (as it already reads the URL from the environment), so a composed boot (`os serve` hands `process.env`) and a host that mounts the plugin directly read the same setting; `resolveKnowledgeStore` in `core` needed no change. The boot line now says the pool size, the limit and where each was read from. - **Ratio to `max_connections = 200`** (README, "Pool size and time limit"): `replicas × (OS_DATABASE_POOL_MAX + OS_KNOWLEDGE_POOL_MAX + builds running at once) + headroom ≤ max_connections`. With 20 kept as headroom, platform pool at its default 5 and one build running, the default of 20 fits up to 6 replicas (3 replicas = 60 store connections); the ceiling is 84 with 2 replicas, 54 with 3, 39 with 4. A larger pool moves waiting from the pool into the database; it does not make one search faster. This is the setting key and ratio B12 (the delivery note) carries. ## Why Premise re-read on `origin/main` d2caaec before code: `codedRefusalOf` (`knowledge-service.ts:4974`) accepts only a SCREAMING_SNAKE `code` with an integer `status` 400–599; `searchRound` (`:3237-3249`) logs an uncoded throw at `error` and `continue`s, and `search()` throws `wholeRefusal` only when `refused` is non-empty (`:2561`). A `pg` error's `code` is a SQLSTATE (`57014`) or absent, so a single-source search answered `{ hits: [] }`. The ablation below reproduces exactly that. ## Tests - `src/__tests__/search-refusals.test.ts` (unit, runs everywhere, 14 cases): the statement shape (`BEGIN`, `SET LOCAL statement_timeout = 10000`, the ranking, `COMMIT`; the ranking never on a bare pooled query; a given limit; a bad limit refused at construction); one case per error class (statement timeout `57014`, cancel `57014` with a translated server message, pool wait through `poolFromPg` at the ranking's connect and at a pooled read, `53300`, `57P01`, `42P01`), each pinned on `code` + `status`; the embedder's uncoded error passed through by identity; **through `KnowledgeService.search`: the caller is refused `TIMEOUT` 504 instead of an empty list**; the settings reader (precedence, blank, strict refusals). - `src/__tests__/search-refusals.live-postgres.test.ts` (live, `OS_TEST_POSTGRES_URL`, no pgvector needed): a real `pg_sleep` past `SET LOCAL statement_timeout` answers `57014` and classifies `TIMEOUT` 504, and `SHOW statement_timeout` on the same pooled connection after the transaction reads the session's own value; a real full pool (`max: 1`) times out through `poolFromPg` and classifies `SERVICE_UNAVAILABLE` 503 on both `query` and `connect`. Pins codes, never durations. <details><summary>Local readings at head 9a39db7</summary> - `pnpm --filter @objectstack/knowledge-pgvector test`: exit 0, Test Files 6 passed / 9 skipped (live files, no URL), Tests 38 passed / 95 skipped. - `vitest run src/__tests__/search-refusals.live-postgres.test.ts` with `OS_TEST_POSTGRES_URL` at a local PostgreSQL 16.15: exit 0, 2/2. - `pnpm --filter @objectstack/knowledge-pgvector typecheck`: exit 0 (incl. `check:test-typecheck`, 0 debt). - `eslint --no-inline-config` on the five changed source/test files: exit 0. `scripts/check-nul-bytes.mjs`: exit 0. - `dispatch-gates.mjs --commands` (7 paths, 694 changed lines): 26 of 27 commands exit 0; `check-plugin-teardown-shape.mjs --self-test` exit 3 — NOT MEASURED locally, reason: shallow clone cannot reach its pinned fixture commit (the script says so); CI runs it. - **Ablation** (fix committed first, restored with `git checkout HEAD --`): with `search()` rethrowing the raw error, 8 of 14 cases go red, and the `KnowledgeService` case receives `{ hits: [] }` — the defect as filed. With `poolFromPg`'s marking removed, the two pool-wait cases go red. </details> ## Acceptance notes - `Clause-②: yes` is copied from the claim. Behaviour that changes for a caller: a database failure that used to read as zero hits from that source is now a refusal (`refused[]`, or a whole-search refusal when it was the only source); a search statement over 10 s is now stopped where it used to run to completion. - Out of scope, noted, not filed: an uncoded throw from something other than the database (the embedder failing, a mis-sized query vector) is still logged and skipped by `searchRound`, so it still reads as zero hits for that source. The general fix sits in `service-knowledge` (`searchRound` treating any uncoded throw as a refusal), which this card was told not to touch (held by objectstack-ai#38700). carrier: objectstack-ai#38703 (topic owner) · noted, not filed. - `connectTimeoutMs` (also the pool's wait) stays a plugin option only, default 5000; the card asked for the pool size and the time limit, not this. ## Verification Two-minute check: `pnpm --filter @objectstack/knowledge-pgvector exec vitest run src/__tests__/search-refusals.test.ts` — expect 14 passed, among them "through KnowledgeService: the caller is refused TIMEOUT, not answered an empty hit list". Read first, by risk: `src/errors.ts` (the SQLSTATE table), `src/pgvector-adapter.ts` `search()` / `searchStatement()`, `src/plugin.ts` `poolFromPg` and `resolveStoreSettings`. ## Rework (L1 7272964718, docs only) Head `4340f85d` adds the two should-fix doc edits and nothing else; nits N1–N3 not taken this round. - `content/docs/deployment/environment-variables.mdx` (Database & Storage, beside `OS_DATABASE_POOL_MAX`): `OS_KNOWLEDGE_POOL_MAX` (integer, `4`, per replica, plugin option wins, the sizing formula with a link to the README section, a non-integer refuses the boot) and `OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS` (integer, `10000`, per search statement, `SET LOCAL`, refused `TIMEOUT` past it, plugin option wins, a non-integer refuses the boot). - `content/docs/protocol/knowledge.mdx` §4.1: one sentence each for the pool precedence (`poolMax`, else `OS_KNOWLEDGE_POOL_MAX`, else 4), the ranking statement under `SET LOCAL statement_timeout` (default 10000 ms), and the three refusals by SQLSTATE. Regen-provenance: 7272956301 · 9a39db7 → 4340f85 · `git diff --name-only 9a39db7 4340f85` → content/docs/deployment/environment-variables.mdx, content/docs/protocol/knowledge.mdx (prose faces only, no code path moved) ## Rework 2 (pool default 4 → 20, on new data) Head `4f6b7d85`. The only behaviour change is `DEFAULT_POOL_MAX` 4 → 20 in `src/plugin.ts`; the rest is its pins and prose. Nits N1–N3 not taken. `statement_timeout` stays 10000 ms. Evidence (not this PR's bench reading): os-bob's measurement on the card, objectstack-ai#38718 comment 7273601824 — local PostgreSQL 17 + pgvector 0.8.7, 59,949 indexed BrightRule clauses, end to end over MCP `search_knowledge`, scoped, 15 questions in rotation: > | 配置 | 20 并发:空结果 | 40 并发:空结果 | > |---|---|---| > | 混合检索 · 连接池 4(现默认) | 15 / 45 | 52 / 90 | > | 混合检索 · 连接池 20 | 0 / 45 | 8 / 90 | > | 只用向量 · 连接池 20 | 0 / 45 | 0 / 90 | > > 空结果全部来自等连接超时:平台日志里有 225 次 `timeout exceeded when trying to connect` … **建议默认值从 4 改为 20**(不只是可配置)。… 语句时限 10 秒:单人串行时,只用向量的主语句 234–445 ms,混合检索 1.1–1.7 s,都远低于 10 秒。 (Those empty results are what this PR turns into `SERVICE_UNAVAILABLE` refusals; the larger pool is what keeps them from happening at 20 concurrent callers.) - `src/plugin.ts`: `DEFAULT_POOL_MAX = 20`; its docblock rewritten to justify the move (the measurement, a lazy ceiling rather than a count opened at boot, fits up to 6 replicas at `max_connections=200`, class 53 refusals past that), replacing the old "not moved" note. The two option docblocks say 20. - **Upgrade effect, stated in the changeset and README:** a deployment with `OS_KNOWLEDGE_POOL_MAX` unset may now open up to 20 store connections per replica under load instead of 4. With the README's formula (platform pool 5, one build, 20 kept as headroom, `max_connections=200`) a replica reaches up to 26, so up to 6 replicas fit (6 × 26 = 156 ≤ 180; 7 × 26 = 182 does not); 3 replicas take 60 store connections. More replicas or a smaller server must set it lower (`4` keeps the old size) or raise `max_connections`, otherwise the server refuses connections (`too_many_connections`, class 53) and those searches are refused `SERVICE_UNAVAILABLE`. - Every pin of 4 moved together: `search-refusals.test.ts` (`DEFAULT_POOL_MAX` and the blank-setting case), the README options and settings tables, `environment-variables.mdx`'s `OS_KNOWLEDGE_POOL_MAX` row, `knowledge.mdx` §4.1, the changeset. - Local at `4f6b7d85`: `search-refusals.test.ts` 14/14, `tsc --noEmit` exit 0. Regen-provenance: 7272956301 · 4340f85 → 4f6b7d8 · `git diff --name-only 4340f85 4f6b7d8` → .changeset/knowledge-pgvector-coded-search-refusals.md, content/docs/deployment/environment-variables.mdx, content/docs/protocol/knowledge.mdx, packages/plugins/knowledge-pgvector/README.md, packages/plugins/knowledge-pgvector/src/__tests__/search-refusals.test.ts, packages/plugins/knowledge-pgvector/src/plugin.ts (NOT prose-only: one constant and its docblock in `plugin.ts`, one test pin; the record does not carry across this hop by itself) ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (not touched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; eslint passes on the changed files. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: n/a. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English (the 维护者速读 block excepted by AGENTS.md's Communication rule). --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbYVKM5Jf2J5JbHJ8Aj)_ <!-- signed: repo:objectstack@os-warren · os-warren · session_01JQwxbYVKM5Jf2J5JbHJ8Aj --> --------- Co-authored-by: Claude <noreply@anthropic.com>
…mode its store does not run (objectstack-ai#38722) <!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8QCBjsNDZa4iwo35VN5fKKg)_ Part of objectstack-ai#38692 Clause-②: no Metadata-protocol: none ## 维护者速读 - 知识源声明了检索方式后,搜索就按它执行;没声明的按存储默认。存储不支持所声明的方式时,保存时直接报错并列出可选方式,启动后记一次错误日志,每次搜索都把它列为未检索,绝不悄悄换成别的方式。 - 属于知识管理专题「一期 a:检索方式」。 - 出错会是本该能搜的知识源被拒;未声明方式的知识源行为不变,可直接撤回。 - 无。 ## Stack Base: `main`. objectstack-ai#38700 (the facade split) has merged and `main` is merged in. The spec PR objectstack-ai#38720 merged as f576dee and `main` is merged in, so this diff is the service's own 15 files. The phase-0 ADR note (objectstack-ai#38714) is merged too. Independent of the adapter PRs. The Studio form PR stacks on this one. ## What changes - New `knowledge-retrieval-mode.ts`: the effective mode is the source's `source.retrieval.mode`, else the adapter's `capabilities.retrieval.default`; an adapter reporting no modes is never told one. - The four refusal points for a declared mode the adapter does not list, never searched another way: 1. save (`admitAuthoredSource`): `400 VALIDATION_ERROR`, listing the modes the store runs; 2. registration in code (`registerSource`): the same refusal, only when the adapter already resolves (startup registry reads). A published item (`registerMetadataSource`, the loader) is not refused there: the loader runs after every store has started, so a refusal would drop it whole; it is registered and indexed, and points 3 and 4 refuse it (review M1); 3. once after boot (`reportUnsupportedRetrieval`, called at `kernel:bootstrapped` beside `reportUnmountedAdapters`), at `error`; 4. every search (`planSearches`): listed in `refused` with `SERVICE_UNAVAILABLE` (503), the code an unmounted adapter's source already carries. - Every search hands the store `AdapterSearchOptions.retrieval` and logs the mode and its origin at `debug`; the caller's answer carries neither. - `index_status` entries carry `retrieval` (declared, effective mode, origin, the store's modes, refused), and the answer lists each mounted store's modes (`details.adapters`) and the store a source naming none binds to (`details.defaultAdapter`), the data the Studio form PR reads. New service member `describeRetrieval`. - Contract suite: service-level cases for every adapter (a listed mode is handed through; an unlisted one is refused at registration in code and at every search, and still indexes; a published item loaded after its store started is registered, indexes, is named by the boot reading and is refused on every search). - Liveness row flips to `live`; protocol doc §3.1 and the save guard; patch changeset. ## Tests - New `retrieval-mode-38692.test.ts` (16 cases): resolution, refusal text, each refusal point, debug log and its absence from the answer, still indexes, the loader path (a published item with its store already started), plugin hook, `index_status`. - `service-knowledge`: 861 passed (26 files, at 1a7ba24); typecheck clean. `knowledge-memory` 70 passed and `knowledge-turso` contract 110 passed against this head's suite. `knowledge-memory` contract 54 passed; `knowledge-turso` 110 contract passed; live pgvector contract 55 passed. - With each adapter PR merged in locally: turso 326 passed, pgvector against live PostgreSQL 133 passed. ## Acceptance notes - The per-search refusal code is reused rather than added: `SERVICE_UNAVAILABLE` (503), the code an unmounted adapter's source already carries. The ruling and the phase-0 note say only "with its code"; open question C, confirmed by Warren on 2026-11-30 at 12:40Z (「同意」): the refusal stays 503. - Declared `Metadata-protocol: none`: what an author can write was added by the spec PR; this PR reads it. The save refusal of a mode the store does not run is the shape the ruling gives the key from birth, in the same release. - Facade gate: `knowledge-service.ts` 1681 lines of 1758; both new members are one-call delegations. ## Verification - Two-minute check: `pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/retrieval-mode-38692.test.ts` → 16 passed. - Related local gates (26 of `dispatch-gates.mjs --commands`: docs, liveness, changeset, facade, error-code, ledger): all green. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [ ] 4. One issue, one branch off an up-to-date `main`, one pull request. (Stacked: see "Stack" above.) - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf <!-- signed: repo:objectstack#2 · os-warren · session_01JQwxbaASqBozmmj1n5tbUf --> --------- Co-authored-by: Claude <noreply@anthropic.com>
…odes its store runs (objectstack-ai#38730) <!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8QCBjsNDZa4iwo35VN5fKKg)_ Part of objectstack-ai#38692 Clause-②: no Metadata-protocol: none ## 维护者速读 - 管理员在 Studio 编辑知识源时,「检索方式」下拉只列出该知识源所用存储支持的方式,并写明「存储默认」是哪一种;存储未声明时显示「驱动未声明检索方式」。 - 属于知识管理专题「一期 a:检索方式」。 - 出错只会是下拉列错选项;保存时服务端仍会把不支持的方式拒掉,可直接撤回。 - 无。 ## Stack Base: `main`. Stacked on the service PR objectstack-ai#38722 (it reads `index_status`'s `adapters` and `defaultAdapter`, which objectstack-ai#38722 adds) and through it on objectstack-ai#38720; until those merge, this diff carries their commits. Lands after both and after the phase-0 ADR note (objectstack-ai#38714). ## What changes - The knowledge source form's `source.retrieval.mode` row names a new widget, `knowledge-retrieval-mode` (spec form hint). A host whose registry lacks the picker draws its unregistered-widget face (the JSON editor), not a select; the three static `options` stay because the form's generated translations carry their labels. - `ResourceEditPage` loads, only for a form that declares the widget, the store the draft binds to (its `adapter`, else `defaultAdapter`) and the modes it reports, from `POST /api/settings/knowledge/index_status` (`knowledgeRetrieval.ts`), into `WidgetContext.knowledgeRetrieval`. - The picker: the store's listed modes plus a blank choice that names the default ("Store default (Hybrid (both))"); a store that reports none offers the default alone with "驱动未声明检索方式(STORE),此项请留空。"; a mode already written that the store does not run is kept and flagged; no store answer (refused read for an author who is not a platform administrator, store not mounted, no host) offers the three modes and the save judges. - en and zh strings in the studio namespace; registry cases in the two widget registry tests; changeset (spec, app-shell, i18n patch). ## Tests - New `KnowledgeRetrievalModeWidget-38692.test.tsx` (12): form row names the widget, labelling, offered options per store shape, undeclared sentence, flagged stored mode, fallbacks, writes and default removal, disabled states, `storeRetrievalOf` parsing. - Related UI suites: 180 files / 2,791 tests passed (widgets, metadata-form, SchemaForm, i18n, console registry parity), `ResourceEditPage*` 67 files / 342 passed; app-shell `tsc --noEmit` and `tsconfig.test.json` clean before the main merge; spec form test 9 passed. ## Acceptance notes - `index_status` is gated on `manage_platform_settings`; an author without it gets the three-mode fallback, never an error card. - The draft's `adapter` re-reads the store on change (one request per distinct value). - After merging `main` (with objectstack-ai#38700) the app-shell `tsc` reports one error in `RecordDetailView.tsx` (`pinOverview`), outside this diff, from a stale local build of a sibling package; not measured further here. ## Verification - Two-minute check: `pnpm --dir ui exec vitest run packages/app-shell/src/views/metadata-admin/KnowledgeRetrievalModeWidget-38692.test.tsx` → 12 passed. - UI gates run: `check:i18n-keys`, `check:i18n-drift`, `check:i18n-dead-keys`, `check-sdui-manifest`, `ui/scripts` vitest, changeset gates: all green. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [ ] 4. One issue, one branch off an up-to-date `main`, one pull request. (Stacked: see "Stack" above.) - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf <!-- signed: repo:objectstack#2 · os-warren · session_01JQwxbaASqBozmmj1n5tbUf --> --------- Co-authored-by: Claude <noreply@anthropic.com>
Requested by Warren · project thread
Fixes #38660
Clause-②: no
Metadata-protocol: none
维护者速读
What changes
packages/services/service-knowledge/src/knowledge-service.tsgoes from 5,571 to 1,658 lines and is now a facade:KnowledgeServicekeeps every field, its constructor and every member with its name, signature and (for a public member) docblock, and each moved member forwards to its body in one call. Move-only: no member is renamed, no behaviour changes, nothing is added to or removed from the package entry (index.tsis untouched).The shape is the one the earlier facade splits use (
SqlDriverand objectqlengine.ts): each body is a module-level function whosethisis typed as the part of a per-module host interface it reads; each host member is typed as the class member (KnowledgeService['x']), so a member renamed or retyped on the class is a compile error in the facet. The class's one static block builds the host once per service (knowledge-service-host.ts): methods go as closures that call the service at call time (an instance spy or a subclass override is still the one reached), fields as getters, plus a setter for the six fields a body assigns.knowledge-service-sources.tsknowledge-service-indexing.tsknowledge-service-record-sync.tsknowledge-service-search.tsknowledge-service-admission.tsknowledge-service-top-level.tsknowledge-service-host.tsNone of the names collides with the existing
knowledge-build.ts,knowledge-build-actions.ts,knowledge-record-sync-queue.ts,knowledge-sync-state.ts,knowledge-source-admission.ts,knowledge-search-scope.ts,knowledge-organization-scope.tsorsplit/, and nothing was folded into those modules.Every moved member and its new file
*marks a public member (its docblock stays on the class); every other member is private and its docblock moved with its body.knowledge-service-sources.tssettleEnablement,registerAdapter,getAdapter,adapterIdFor,boundAdapterId,refuseUnplacedSource,reportUnmountedAdapters,listAdapters,registerSource,registerMetadataSource,metadataSources,onSourcesChanged,sourcesChanged,unregisterSource,dropMetadataSource,forget,listSources,describeSources,getSource,describeSource*,handed,handedSources,adapterLabel,faceOfKey,requireEntryknowledge-service-indexing.tsplanIndex,prepareDocuments,readChunkTarget,reindexSource,reindexWith,walkObjectSource,completeBuild,readIndexStateOf,buildRecord,rebuildSource,rebuildOf,buildUnderLease,syncStateIdentity,syncStateWriteFailed,storedCounts,recordBuildStart,recordBuildProgress,recordBuildEnd,closeStaleBuild,closeInterruptedBuilds,buildSourcesAtBoot,buildReloadedSource,buildIfDue,stopBuilds,reconcileSources,enqueueReconcile,reconcilePass,reconcileOf,reconcileExclusion,requestReconcile*,armReconcile,cancelPendingReconcileknowledge-service-record-sync.tsrecordSources,hasDurableSyncState,syncStateOf,pendingRecordSyncs,recordSyncFailure,requestSourceReconcile,clearRepairedFailures,deadLettersOf,recordSyncQueued(getter),enqueueRecordSync,publishRecordSyncs,processRecordSync,resolveRecordSync,coveredByBuild,processRecordSyncBatch,syncRecordGroup,recordSyncWaiting,sourceRowCount,considerBacklogReconcile,syncRows,handleRecordUpsert,syncRecord,syncRow,writeSynced,reportUnindexable,reportWhereUnenforceable,serializeRecordSync,schemaFor,handleRecordDelete*knowledge-service-search.tssearch,searchWithRefusals,searchByKey,sourcesGroupableBy,groupKeyOf,affinityOrderFor,affinityFactsOf,answerByRecord,checkFreshness,dropUnverifiedHits,repairStale,planSearches,unprovenIndex,searchRound,sourcesInScope,sourcesNarrowedToVisible,readVisibleIds,checkScope,resolveSearchTargetsknowledge-service-admission.tsadmitSources,admissionDeps,admitAuthoredSource*,unmountedAdapterSaveText,reportGateFailure,readTenancyPosture,scopeByOrganization,sourcesForObject,applyPermissionFilter114 members moved. Stay on the class, as they were: the 25 fields; eight members that were already one-call delegations at the base (
heldReading,adapterFor,indexedSources,label,readIndexState,useRecordSyncQueue,facedRefusals,routeRecordSyncs); and twoexceptionsrows (below).The facade gate
scripts/facade-delegation-registry.jsongains afacadesrow forKnowledgeService, aceilingsrow forknowledge-service.ts(baseLines1658 atbaseCommit4c4a984,maxLines1758 =CEILING_MARGIN100, ruling 6897467376), and twoexceptionsrows (card #38660):constructor: state-owning, it readsdefaultTopKandenabledByConfigurationoff the options into the instance's own fields (the card's "facade keeps fields, constructor").knowledgeTools: bare-this, its body hands the service itself tocreateKnowledgeTools(this); a facet body is handed the host, so moving it would hand the tool executor the host instead of the service.The gate's self-test (N7) holds
DECLARED_WATCH_HINTSequal to the registry's facade files, soscripts/check-facade-delegation-only.mjsgains the one path string; nothing else in the gate changes.Three generated or ledgered consequences of the move
content/docs/permissions/system-context.mdx: the fourisSystemread sites (admitAuthoredSource,admitSources,applyPermissionFilter,searchByKey) now live in the admission and search modules; the generated site register was rewritten bynode scripts/check-system-context-census.mjs --write(four anchor paths, nothing else on the page).scripts/tenant-audit-census.mjs: oneUNTYPED_RECEIVERSrow forknowledge-service-record-sync.ts, receiveradapter(this.adapterFor(source)read through the host,engine: false), the same receiver the existingknowledge-reap-guard.tsrow already rules on. Inside the class the census read the method's return type; through the host it cannot.packages/spec/liveness/knowledge_source.json: the ledger cited ten bodies asknowledge-service.ts#NAME;check:livenessresolves the symbol in the cited file, anddocumentKeyOfno longer lives there, so the gate turned red. Each of the ten citations now names the module that holds the body (dropMetadataSourcein sources;walkObjectSource,reindexWith,buildIfDuein indexing;syncRecordin record sync;admitAuthoredSourcein admission;affinityOrderForin search;recordToDocument,objectSourcesFor,documentKeyOfin top-level). No verdict or other text changes. The ledger ships in@objectstack/spec, so the changeset names that package with apatchtoo.Net growth beyond a pure move (package source: 5,571 lines before, 7,356 after)
?on the stub and stay on the facet, which emits the same declaration;asyncdropped on the stubs so each returns the facet's own promise, theSqlDriverprecedent).thisparameter on each facet function that reads the service (110 of 114).knowledge-service.ts(every name it exported before is still exported from it), andexportadded to 43 top-level declarations a facet or the facade reads (none reachesindex.ts).knowledge-service-host.ts: 62 lines.Published bytes and the changeset
The package's
distchanges (its code moves between chunks), so this is notskip-changeset: onepatchchangeset for@objectstack/service-knowledge(and@objectstack/spec, for the ledger above). The published declaration is unchanged where it is public: built before and after,dist/index.d.tscarries the same 95 top-level declarations with the same text (94 byte-identical, imports and the export list equal as sets); the one that differs isKnowledgeService, whose declaration is line-for-line identical once comments are set aside: the 70 private members whose docblocks moved with their bodies lose those comments. The bundle lists its declarations in another order.dist/testing.d.tsis byte-identical.Tests
No test file changed. Every moved body was checked as a move, not a rewrite: a throwaway verifier (not committed) proves each of the 114 functions' body, parameters, type parameters, return type and
asyncare token-identical to the base member, every string and template literal byte-identical, and each of the 68 top-level declarations byte-identical but for an addedexport; it reds on a one-character change (negative control).Readings at head
ad4f458a7cunless a block says otherwise.service-knowledge suite and typecheck at ad4f458: 25 files, 836 tests pass
os-verify-lock.sh -c 'pnpm --filter @objectstack/service-knowledge test && pnpm --filter @objectstack/service-knowledge typecheck':Test Files 25 passed (25),Tests 836 passed (836), typecheck (tsc pluscheck:test-typecheck) clean,VERDICT command-exit 0. The same 25 files and 836 tests as onmain; no test file changed.knowledge pins in other packages at 5fffac6: all pass
Run at the merge head
5fffac643b; between it andad4f458a7cthe package source differs only in seven comment lines (facet docblock wording and two module headers), plus the liveness ledger and the changeset.Derived gate families at ad4f458: 121 derived, 118 exit 0, 3 NOT MEASURED
node scripts/pm/dispatch-gates.mjs --commands(no paths; derived from the tree of objectstack-ai/objectstack atad4f458a7c) named 121 commands; all 121 were run, each exit code captured before any pipe, and--ranreconciled the record:121 derived famil(ies) accounted for — 118 run, 3 NOT-MEASURED (3 DERIVED from a recorded exit 3).Among the 118 at exit 0:
check-facade-delegation-only(KnowledgeService: 150 members, 123 delegations, 25 fields, 2 named exceptions;knowledge-service.ts1658 lines, ceiling 1758) and its self-test,tenant-audit-censusand its self-test,check:system-context-census, speccheck:liveness,check:empty-state, the changeset gates,check-plugin-teardown-shape --self-test,check:platform-checklistandcheck:pm-dispatch-gates.NOT MEASURED (each exited 3, prerequisite not met: they read the built
dist/of every package, and this container did not build the whole workspace; CI runs them):pnpm --filter @objectstack/spec run check:skill-examplespnpm check:dual-build-cjs-loadspnpm check:published-readme-exportsnode scripts/check-platform-checklist.mjs --changed-from origin/main: exit 0, no anchored file in the change set.Published declaration, built before and after
dist/index.d.ts: 95 top-level declarations before and after; 94 byte-identical, imports and the export list equal as sets.KnowledgeServiceis line-for-line identical once comments are set aside (70 private members lose the docblocks that moved with their bodies).dist/testing.d.ts: byte-identical.Acceptance notes
knowledge-service.tsis 1,658 lines, below the 2,000 bar; what remains is the public docblocks (the published contract), the 25 documented fields, the stubs and the host block.isSystemregister on the system-context page, and theknowledge_sourceliveness ledger. These are additions to the claim's file surface, declared here.knowledge-service-indexing.ts,knowledge-service-admission.tsandknowledge-service-search.tsrespectively.Verification
Read first, by risk:
knowledge-service.ts, thestaticblock at the end of the class: every field a body assigns needs its setter there (six do), or the write lands on nothing; the five host interfaces type-check that every member a body reads is there.knowledge-service-host.ts: the host is built once per service and cached, so a body'sthisis the same object across calls.knowledge-service.ts, the stubs ofregisterMetadataSource,planIndex,reindexSource,reconcileSources,search,searchWithRefusalsandanswerByRecord, whose non-literal defaults moved to the facet.Two-minute check:
pnpm --filter @objectstack/service-knowledge test(expect 25 files, 836 tests passing, the same suite asmain) andnode scripts/check-facade-delegation-only.mjs(expect theKnowledgeServiceline: 150 members, 123 delegations, 25 fields, 2 named exceptions, andknowledge-service.ts: 1658 lines, ceiling 1758).Signed: repo:objectstack#2 · os-warren · session_01JQwxbZLuMpo8YX4ACmyoNd
Generated by Claude Code
🤖 Generated with Claude Code
https://claude.ai/code/session_01JQwxbZLuMpo8YX4ACmyoNd