Skip to content

fix(knowledge-turso): a scoped search reads its passage table once a statement; a request past its bound answers TIMEOUT - #38693

Merged
objectstack-fleet[bot] merged 2 commits into
mainfrom
claude/project-thread-slovhl
Nov 30, 2026
Merged

objectstack-fleet[bot] merged 2 commits into
mainfrom
claude/project-thread-slovhl

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

Requested by Warren · project thread

Fixes #38675

What changes

packages/plugins/knowledge-turso only.

  1. A scoped search reads its passage table once a statement. When a search carries a record scope or a metadata filter, the statement now opens with scope AS MATERIALIZED (SELECT chunk_id FROM <table> WHERE <the same WHERE>). The vector leg (exact and approximate), the keyword candidates and the keyword count of passages in scope read from that set by chunk_id, a primary-key lookup. Before, each of those three ran the WHERE row by row over the whole table, and a metadata scope term parses each row's JSON (json_each(metadata)). A search with only the organization filter is unchanged (no scope set).
  2. The keyword candidates are read once. cand becomes cand AS MATERIALIZED. Both stats and kw read it, and SQLite inlined it into each, so every term was matched twice per statement. The fix applies to scoped and unscoped searches.
  3. A request past requestTimeoutMs answers TIMEOUT (504). The message is "The knowledge store (libSQL) did not answer in time: a request to its database took longer than N ms." Before, the refusal was SERVICE_UNAVAILABLE (503) with "The knowledge store (libSQL) is not ready: its database did not answer in time." That told the model and the employee the store was down when one statement was slow. remedy (operator text) still names requestTimeoutMs and keeps the commit warning. TIMEOUT/504 is the ADR-0112 code for an operation that timed out. Nothing in service-knowledge branches on the old code; it passes any coded refusal through (codedRefusalOf).

Docs: the README requestTimeoutMs row and the Search section, the requestTimeoutMs option doc in plugin.ts, and the adapter's class comment.

Why

The premise, read on main at 5ac1ee0 and measured.

  • Why a scoped statement is slower than an unscoped one. In the plan of a scoped statement, the passage table is read in full three times: by the vector leg, by the keyword candidates (twice, since cand is inlined into stats and kw) and by the count in stats. Each read evaluates the metadata scope term per row. An unscoped statement reads it twice: the count in stats is a covering-index count, and cand is still inlined twice. A narrow scope also fails the approximate leg's pool floor, so a scoped search runs two or three such statements (approximate, maybe wide, then exact). An unscoped search runs one.

  • Reproduced locally (no remote Turso here). A file: libSQL store was built through the adapter: 59,621 one-passage records, 1,024 dimensions, clustered vectors, one organization, Chinese clause text, metadata {business_unit: [root, division, leaf], policy, clause_hash}, approximate index built (completeBuild, threshold 20,000). The search was topK 40 (the service's first round) with the card's question 「我在集团干了12年了,一年有几天年假?」 (16 terms). Times are per statement, before → after:

    Search Before After
    No scope (organization filter) 1 statement, 1.14–1.32 s 1 statement, 0.63–0.69 s
    3 policies (90 passages) 0.88–0.91 s + 1.03–1.05 s 0.13 s + 0.08 s
    One leaf unit (~1.7%) 0.97–0.99 s + 1.13–1.22 s 0.19 s + 0.15 s
    One division (~10%) 0.99–1.18 s + 1.18–1.23 s 0.25 s + 0.31 s
    Group root (100%) 1 statement, 1.26–1.28 s 1 statement, 0.85–0.97 s

    The card's hosted timings (25.6 s for an unscoped search, a scoped statement over 10 s) are about 8 to 10 times these local ones. On that ratio, a scoped statement now lands well under the bound. That is an inference from the ratio, not a remote measurement: the remote store was not reachable from here.

  • Responsibility. The cause is in this plugin's search SQL (turso-adapter.ts), not in service-knowledge. The approximate index (the card's second suspicion) is not the cause in the reproduction: the slow statements are slow with the index built and used. Whether the hosted table has its index was not readable from here.

Out of scope, left to the cards the seat named: the keyword leg recomputed across the approximate → wide → exact statements, the approximate pass under a narrow scope, and the query embedded twice per refill (#38676); the keyword leg's ranking quality (#38671).

Verification

  • src/__tests__/scope-plan.test.ts (new) pins the plan, not a clock. For a metadata scope term, a record scope term, both terms together, and a metadata filter, each on the exact and the approximate vector leg, every search statement's EXPLAIN QUERY PLAN reads the passage table once outside a chunk-id lookup, under MATERIALIZE scope, and holds one MATERIALIZE cand. A search with no scope makes no scope set. Scoped hits equal the terms' row-by-row meaning. A stalled search statement answers TIMEOUT/504 with the new sentence and no "not ready". With the adapter change stashed, 9 of the 11 cases fail: the 8 plan pins and the timeout pin. The 2 behaviour-equivalence cases pass on both.
  • acceptance.test.ts: the stalled-write case now expects TIMEOUT/504.
  • pnpm --filter @objectstack/knowledge-turso test: 5 files, 301 tests pass. pnpm typecheck passes for the package. eslint on the changed files is clean.
  • Local gates from dispatch-gates.mjs that pass: check:issue-citations, check:doc-authoring, check:keyed-text-bounds, check:closed-ceremony-text, check:objectql-double-limit, check:where-matcher, check:duration-unit-keys, check:changeset-fixed and check:empty-changeset.

Clause-②: no
Metadata-protocol: none

Human Minimum

  • 1. Schemas start as Zod; packages/spec holds no runtime logic. (not touched)
  • 2. Every name I added uses the casing for its kind.
  • 3. No formatter ran. eslint is clean on the changed files; the repo-wide pnpm lint was not run locally.
  • 4. One issue, one branch off an up-to-date main, one pull request.
  • 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset.
  • 6. packages/spec touched: not touched.
  • 7. No hand edits to content/docs/references/, packages/*/CHANGELOG.md or content/docs/releases/.
  • 8. Title, body and comments are in English.
  • The Before Submitting list in CONTRIBUTING.md is done. The full repo-wide suite was not run; CI runs it.

🤖 Generated with Claude Code

https://claude.ai/code/session_01JQwxbaAVoqUQiPmxMVpLst

…statement; a request past its bound answers TIMEOUT

A search with a record scope or a metadata filter read its WHERE row by
row in the vector leg, the keyword candidates and the keyword count, and
the keyword candidates were computed twice in one statement. Each was a
pass over the passage table; on a remote libSQL database a scoped
statement went past the 10 s request bound. The WHERE is now read once a
statement into a materialized scope set that every other read looks up
by chunk id, and the keyword candidates are materialized.

A request past requestTimeoutMs answers TIMEOUT (504), "did not answer in
time", instead of SERVICE_UNAVAILABLE "is not ready".

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JQwxbaAVoqUQiPmxMVpLst
@github-actions github-actions Bot added 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

4 anchor(s) derived from 1 changed package(s); no hand-written page names any of them. ⚠️ 1 changed file(s) yielded no anchor (packages/plugins/knowledge-turso/README.md), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

What this run could not see
  • 1 changed file(s) yielded no anchor (packages/plugins/knowledge-turso/README.md) — pages documenting those are invisible to this run
  • 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 5ac1ee0bc8a79ab2238ded80123ba91623ad6081 → packageMentionDocs.

Which tree this was computed on

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

node scripts/docs-audit/affected-docs.mjs --json 5ac1ee0bc8a79ab2238ded80123ba91623ad6081

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

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu

维护者速读

  • 用户能看到什么变化:远程 Turso 知识库上,带检索范围的「在知识库中查找」不再超时报错。本地 6 万段数据上,3 条制度的范围从约 1 秒降到约 0.1 秒,不带范围从 1.2 秒降到 0.65 秒,检索结果不变。
  • 另一处变化:数据库某条请求超时,现在报「超时」(504),不再报「知识库没准备好」(503)。写入也一样。
  • 风险:只改 knowledge-turso 插件内部的检索 SQL 和超时报错;远程环境的提速是按本地测量推断的,未在远程实测。
  • 要你做什么:无;发布冻结解除后席位入队。

席位核对

ACCEPT · L1 · area o2-A · Head-sha d3c750a86e0e50b389bab5fb4a782217c44da965 · 2026-11-30T05:41Z

  • Face: plugin-internal only. The file list is not governed (check-governed-merges --pr 38693: NOT governed, 290 lines). Clause-②: no / Metadata-protocol: none / @objectstack/knowledge-turso patch accepted.
  • Design read against the diff:
    • A record scope or metadata filter is read once into scope AS MATERIALIZED, and every leg reads passages by chunk_id IN scope.
    • The keyword candidates are MATERIALIZED and read once by stats and kw.
    • The organization filter alone stays inline (no narrowing). The scope is pushed into SQL, with no in-app filter.
  • Error code: withTimeout now rejects with TIMEOUT/504 for every request, writes included. The seat accepted this (amendment 7269451771): no consumer in service-knowledge or knowledge-turso branches on the adapter's 503. The changeset states the write case.
  • Pins: 9 of 11 plan pins red with the fix stashed (report 7269378240). They are plan-shaped, not wall-clock. Package: 301 tests and typecheck pass.
  • Checks at this head: all green (check suites done 2026-11-30T05:39Z); mergeable, clean against main. The earlier Lint & Repo Gates failure was on superseded head 3034d99bc4 (cancelled by the push).
  • Changeset read sentence by sentence against the diff: true.
  • Landing: Tier S (not governed). Held as a draft under the release freeze; the seat readies and enqueues it when the freeze lifts. Fixes #38675 closes the card on merge. perf(knowledge-turso): compute the keyword leg once a search; send a scope too narrow for the approximate pass straight to the exact scan #38697 (knowledge-turso 检索慢:关键词一路随向量重试重复执行、窄范围下近似检索反而比精确扫描慢、补查轮重复生成问题向量 #38676) is stacked on this branch and retargets to main after it lands.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu

2026-11-30T07:09Z · Landing · seat ACCEPT 7269924689 at d3c750a86e stands (head unchanged). All checks green, mergeable_state clean against main.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 30, 2026 07:10
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 30, 2026
Merged via the queue into main with commit 43eaf5e Nov 30, 2026
56 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/project-thread-slovhl branch November 30, 2026 07:36
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…scope too narrow for the approximate pass straight to the exact scan (objectstack-ai#38697)

<!-- claude-projects-attribution: {"github_login":"os-warren"} -->
_Requested by **Warren** · [project
thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8Es8AjkqFCZ7RyXPBkdgAD3)_

Part of objectstack-ai#38676

**Stacked on objectstack-ai#38693.** The base is that PR's branch, so this diff shows
only objectstack-ai#38676's commit. After objectstack-ai#38693 lands, main is merged in and the PR
is retargeted to `main`.

## What changes

`packages/plugins/knowledge-turso` only (`turso-adapter.ts`, `sql.ts`,
tests, README).

1. **The keyword leg is computed once a search.** The first statement of
a search computes it, as before. When the approximate pass falls short
and a wider pass or the exact scan follows, that statement binds the
keyword ranks the first one answered (`kw AS (SELECT … FROM
json_each(?n))`) instead of matching up to 16 terms again. A statement
binds only the shared values (query vector, scope and filter values,
`topK`), the ranks, and its candidate count.
2. **A scope too narrow for the approximate pass goes straight to the
exact scan, judged by its share of the rows.** Before, only a scope of
record terms alone was checked (through the record index). Now a scope
with a parent (metadata) term, or a metadata `filter`, has its share
estimated by `scopeSampleSql`: 256 rows at evenly spread rowids, with
`min(rowid)`/`max(rowid)` seeks for the bounds, so no pass over the
table. The cut is the record scope's (`VECTOR_RECORD_SCOPE_POOL`: 25% of
the passages at the default over-fetch of 40).

**Not built here: cause 3, the question embedded again on the second
round.** The adapter embeds once per `search()` call. The repeat comes
from `service-knowledge`'s second `searchRound` calling `adapter.search`
again. That file is held by objectstack-ai#38660 and is outside this order's surface,
so objectstack-ai#38676 stays open for it (see the os-dev report on the card).

## Why

Re-measured on objectstack-ai#38693's head (d3c750a), on the same local corpus as
objectstack-ai#38693: a `file:` libSQL with 59,621 one-passage records, 1,024
dimensions, approximate index built, and the 16-term Chinese question.
Total per search (statements):

| Search, `topK` 40 | objectstack-ai#38693 head | This PR |
|---|---|---|
| 3 policies (0.15%) | 190 ms (approx+kw 120, exact+kw 74) | 80 ms
(sample 5, exact+kw 75) |
| Leaf unit (1.7%) | 310–680 ms (approx+kw, wide+kw, exact+kw) | 150 ms
(sample 5, exact+kw 145) |
| Division (10%) | 570–700 ms (approx+kw 240, wide+kw 330–440) | 230–280
ms (sample 5, exact+kw 225–274) |
| Root (100%) | 810–900 ms (approx+kw) | 820–880 ms (sample 5,
approx+kw) |
| No scope | 620–690 ms | 620–660 ms (unchanged path) |

`topK` 8 shows the same pattern: the leaf unit went from 318–372 to
143–147 ms and the division from 227–507 to 210–214 ms.

- Cause 1 held: every vector statement of one search carried the keyword
CTE.
- Cause 2 held: under a parent-term scope of 1.7% or 10%, the search ran
2–3 statements where 1 exact scan answered.
- Cause 3: the adapter embedded once per call (31 embeds for 31
searches), so the repeat lives in the caller.

## Verification

- **Pins**, all from plans and statement shape, none on wall-clock. With
`turso-adapter.ts` and `sql.ts` reverted to objectstack-ai#38693's head, 10 of 301
tests fail:
- `scope-plan.test.ts`: across one search's statements, `MATERIALIZE
cand` appears once, in the first.
- `acceptance.test.ts` retry case, rewritten for the new routing: the
wide pass and the exact scan after a short first pass bind the keyword
ranks (`computed: 1, bound: 1`); a 1% scope goes exact alone; the
sample's plan reads the table by `SEARCH` only, never `SCAN`; each pass
binds exactly what it reads.
- Filter, record-cut and termless cases: a parent term or filter under
the cut now runs `{approximate: 0, exact: 1}`, and a parent-term scope
over the cut still takes the first pass.
- Hits still equal the exact-scan adapter's in every routed case (the
existing `exact` twin comparisons).
- `pnpm --filter @objectstack/knowledge-turso test`: 5 files, 301 tests
pass. `pnpm typecheck` passes. eslint on the changed files is clean.
`check:issue-citations`, `check:doc-authoring`,
`check:objectql-double-limit`, `check:where-matcher` and
`check:empty-changeset` exit 0.

Clause-②: no
Metadata-protocol: none

## 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 is clean on the changed files; the
repo-wide `pnpm lint` was not run locally.
- [x] 4. One issue, one branch, one pull request. It is stacked on
objectstack-ai#38693 by the seat's order.
- [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: not touched.
- [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 *Before Submitting* list in CONTRIBUTING.md is done. The full
repo-wide suite was not run; CI runs it.

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

https://claude.ai/code/session_01JQwxbaAVoqUQiPmxMVpLst

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

knowledge-turso:远程 Turso 上带检索范围的 search_knowledge 稳定超时(单条 SQL 超过 10 秒),不带范围也要 25 秒

2 participants