Skip to content

Commit f782a12

Browse files
fix(knowledge-pgvector): a failed search is a coded refusal, its statement has a time limit, and its pool size is a setting (#38726)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8VZtjriPRDBMFWChF2eLFkE)_ Fixes #38718 Clause-②: yes Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:私有部署企业版在 PostgreSQL 上检索知识时,数据库忙、连接等不到或语句超时,助手会收到明确的「超时 / 暂不可用」拒绝,不再拿到「0 条命中」;检索语句默认最多跑 10 秒;连接池大小可以由运维通过设置调整。 - 为什么做:属于「私有部署企业版知识检索 10 人同时提问不超时」专题第一期,目标之一是出错不能变成空结果,首个用户是 BrightRule 制度问询。 - 出错会怎样:最坏情况是本来能跑完的超长检索(超过 10 秒)现在被拒绝为超时,运维可调大时限设置;改动只在知识检索的 PostgreSQL 适配器内,撤回即恢复原样。 - 要你做什么:无。 ## What changes Topic #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 #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 (#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 #38700). carrier: #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, #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>
1 parent 855c3e1 commit f782a12

9 files changed

Lines changed: 699 additions & 20 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/knowledge-pgvector': patch
3+
---
4+
5+
fix(knowledge-pgvector): a search the database fails is a coded refusal, never an empty answer; its statement has a time limit; the pool size is a setting
6+
7+
Clause-②: yes
8+
Metadata-protocol: none
9+
10+
- A search the store's database fails is now refused with an ADR-0112 code, chosen by the error's SQLSTATE: a statement past its time limit or cancelled (`57014`) is `TIMEOUT` (504); a full pool whose wait timed out, a dropped or refused connection, or a database out of capacity (`too_many_connections`) is `SERVICE_UNAVAILABLE` (503); any other database error is `DATABASE_ERROR` (500). Before, these errors carried no code, so the knowledge service logged them and skipped the source, and the caller was answered as if nothing matched. The message is one sentence naming the source; the SQLSTATE, the driver's text and the setting to change are in `remedy`.
11+
- A search's ranking statement now runs under PostgreSQL's `statement_timeout`, set with `SET LOCAL` in the statement's own transaction (no session state, so it holds behind a transaction-mode pooler). Default 10000 ms: the plugin option `statementTimeoutMs`, else the setting `OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS`. Before, a search statement had no limit.
12+
- The store's pool size is read from the setting `OS_KNOWLEDGE_POOL_MAX` when the plugin option `poolMax` is not given, and its default rises from 4 to 20: over 59,949 indexed passages with hybrid search, a pool of 4 left a third of the searches at 20 concurrent callers waiting past the connect timeout, and a pool of 20 left none. **A deployment with `OS_KNOWLEDGE_POOL_MAX` unset may now open up to 20 store connections per replica instead of 4.** It is a ceiling reached under load, not a count opened at boot: the pool opens a connection only when a search finds none idle. Against `max_connections=200` with 20 kept as headroom, the platform pool at 5 and one build, a replica reaches up to 26, so up to 6 replicas fit (60 store connections with 3). With more replicas or a smaller server, set `OS_KNOWLEDGE_POOL_MAX` 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`. A setting that is not a positive integer stops the boot, naming it. The README states how to size it across replicas.

‎content/docs/deployment/environment-variables.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ read at startup unless noted otherwise. Boolean variables accept `true` / `false
5353
| `OS_DATABASE_DRIVER` | enum | inferred | Force a specific driver when the URL is ambiguous. `sqlite` \| `sqlite-wasm` \| `postgres` \| `mysql` \| `mongodb` \| `turso`. `memory` / `mingo` / `in-memory` are refused at boot: the in-memory engine cannot serve a tenant-scoped read, so use `os dev --fresh` or `OS_DATABASE_URL=:memory:` instead. `mysql` is a supported deployment target that carries three dialect caveats — two of them integrity guarantees MySQL cannot enforce at the database. Read [MySQL dialect caveats](/docs/data-modeling/drivers#mysql-dialect-caveats) before choosing it. |
5454
| `OS_DATABASE_SQLITE_JOURNAL_MODE` | enum | `wal` | Journal mode for **file-backed** SQLite. `wal` (default) lets a dev server and CLI commands share one file without blocking each other, and is what makes the `os migrate` occupancy check reliable. Set to `delete` for SQLite's rollback journal — required when the database lives on a **network filesystem** (NFS/SMB), where WAL cannot work. The setting is applied, not merely skipped: `delete` converts a database that already adopted WAL back. Ignored for `:memory:`, for the WASM SQLite driver, and for non-SQLite drivers. A per-datasource `sqliteJournalMode` in driver config outranks it. See [Journal mode](/docs/data-modeling/drivers#journal-mode-wal-and-cross-process-access). |
5555
| `OS_DATABASE_POOL_MAX` | integer | `5` | Maximum pooled connections **each replica** opens to `postgres` / `mysql`. The pool, not the database, is usually what caps authed throughput on a multi-replica deployment: at the default of 5 a 3-replica cluster reaches at most ~15 connections, which can plateau the data API while the database still has most of its `max_connections` free. Size it so **`replicas × OS_DATABASE_POOL_MAX` stays below the database's `max_connections`**, leaving headroom for migrations and admin connections — e.g. 3 replicas × 40 = 120 against `max_connections=200`. A per-datasource `pool.max` in the datasource's own definition outranks it, and with the variable unset nothing changes. A value that is not a positive integer refuses the boot rather than falling back to the default. Ignored by `memory` / `sqlite` / `sqlite-wasm` / `turso`, which open no pool — declaring a `pool` block on those is an error, not a silent drop. |
56+
| `OS_KNOWLEDGE_POOL_MAX` | integer | `20` | Connections in the `knowledge-pgvector` store's own pool, opened by **each replica** beside its `OS_DATABASE_POOL_MAX` pool (both reach the same server when the store is in the platform database, and a running build holds one more). The plugin's `poolMax` option wins over it. Keep `replicas × (OS_DATABASE_POOL_MAX + OS_KNOWLEDGE_POOL_MAX + builds running at once)` plus headroom below the database's `max_connections`; at the default, 3 replicas take 60 store connections, and the [store's README](https://github.com/objectstack-ai/objectstack/tree/main/packages/plugins/knowledge-pgvector#pool-size-and-time-limit) gives the formula and figures for `max_connections=200`. A value that is not a positive integer refuses the boot, naming the variable; blank reads as unset. A larger pool does not make one search faster. |
57+
| `OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS` | integer | `10000` | The longest **one search statement** of the `knowledge-pgvector` store may run, in milliseconds: PostgreSQL's `statement_timeout`, set with `SET LOCAL` in that statement's own transaction, so it holds behind a transaction-mode pooler and touches no session setting. A statement past it is stopped and the search refused `TIMEOUT` (504), never answered empty. The plugin's `statementTimeoutMs` option wins over it. A value that is not a positive integer refuses the boot, naming the variable; blank reads as unset. |
5658
| `OS_ALLOW_DRIVER_CONNECT_FAILURE` | boolean | `false` | Escape hatch for the driver-connect boot guard. By default a data driver that fails to connect at startup **refuses the boot** — a server that cannot reach its database must not report itself started and then fail every request. The same guard covers a **declared datasource** that objects bind to via `datasource: '…'`, or an `external` one with `validation.onMismatch: 'fail'`: those objects have no fallback datasource, so an unconnected one means they are all dead. Set to `1` to boot anyway, in an explicitly degraded state logged loudly at startup. There is **no reconnection**: whatever failed stays dead for the process lifetime and every query and schema sync routed to it fails. |
5759
| `OS_STORAGE_LOCAL_ROOT` | path | `./.objectstack/data/uploads` | Root directory for the local file storage adapter, relative to the process cwd (used by `os serve`'s default `storage` capability wiring). This is the same value as **Setup → Settings → File Storage → Root directory**; setting it here pins that field (it shows as locked-by-env). Renamed from `OS_STORAGE_ROOT` — see below. |
5860
| `OS_STORAGE_ROOT` | path | — | **Deprecated alias for `OS_STORAGE_LOCAL_ROOT`.** Still read for one release, with a startup warning; it will be removed in a future major. Rename it now. Before the rename the two halves of the platform spelled this value differently — the CLI wrote `OS_STORAGE_ROOT` while the settings service read `OS_STORAGE_LOCAL_ROOT` — so **any value other than the default was silently discarded** at startup and uploads landed in `./.objectstack/data/uploads` regardless. If you set `OS_STORAGE_ROOT` on an older release, check where your uploads actually are before assuming a backup covered them. |

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -736,10 +736,10 @@ service. It takes the service's passages, embeds them with the kernel's
736736
an exact scan.
737737

738738
- **Which database.** The `url` option when it is given, else the platform
739-
database when that is PostgreSQL (`OS_DATABASE_URL`). Its own small pool
740-
(`poolMax`, default 4; a connection that takes more than
741-
`connectTimeoutMs`, default 5000, fails); no pooled connection waits on the
742-
embedder. Where organizations
739+
database when that is PostgreSQL (`OS_DATABASE_URL`). Its own small pool,
740+
per process, sized by `poolMax`, else the setting `OS_KNOWLEDGE_POOL_MAX`,
741+
else 20 (a connection that takes more than `connectTimeoutMs`, default 5000,
742+
fails); no pooled connection waits on the embedder. Where organizations
743743
have databases of their own, the store is still the ONE database the
744744
plugin connects to; organizations are kept apart by its
745745
`organization_id` column, which every search filters on before ranking.
@@ -773,6 +773,14 @@ an exact scan.
773773
are one `WHERE`, run in both legs before either ranks.
774774
`queryPrefix` is put before every query before it is embedded, for a model
775775
that embeds questions and passages differently.
776+
The ranking statement runs in a transaction of its own under
777+
`SET LOCAL statement_timeout` (`statementTimeoutMs`, else
778+
`OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS`, else 10000 ms), so the limit holds no
779+
session state.
780+
A search the database fails is refused by its SQLSTATE, never answered
781+
empty: `TIMEOUT` (504) for a statement stopped or cancelled,
782+
`SERVICE_UNAVAILABLE` (503) when no connection or capacity was available,
783+
`DATABASE_ERROR` (500) for any other database error.
776784
- **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is
777785
not embedded again; its row's metadata is rewritten.
778786
- **Rebuilds.** A write or a search under another fingerprint is refused

‎packages/plugins/knowledge-pgvector/README.md‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,9 @@ A source is usually a `knowledge_source` metadata item (a `*.knowledge-source.ts
2424
| `id` | `'pgvector'` | The adapter id a source names in `adapter`. |
2525
| `url` | the platform database | A `postgres://` URL. Absent: `OS_DATABASE_URL` (else the legacy `DATABASE_URL`) when it is PostgreSQL. |
2626
| `schema` | `'os_knowledge'` | The schema the store's tables live in. |
27-
| `poolMax` | `4` | Connections in the store's own pool. |
28-
| `connectTimeoutMs` | `5000` | How long a new connection may take before it fails; boot waits on the store's first check. |
27+
| `poolMax` | the setting `OS_KNOWLEDGE_POOL_MAX`, else `20` | Connections in the store's own pool, per process (per replica). See [Pool size and time limit](#pool-size-and-time-limit). |
28+
| `connectTimeoutMs` | `5000` | How long a new connection may take before it fails, and how long a search waits for a free connection of the pool; boot waits on the store's first check. |
29+
| `statementTimeoutMs` | the setting `OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS`, else `10000` | The longest a search's ranking statement may run, in milliseconds (PostgreSQL's `statement_timeout`). |
2930
| `queryPrefix` | `''` | Text put before every query before it is embedded (BGE's `'Represent this sentence for searching relevant passages: '`). Passages are embedded as they are. |
3031
| `embedder` | the kernel's `embedder` service | The embedder to call. |
3132

@@ -62,6 +63,40 @@ Two legs in one statement (one snapshot), merged by reciprocal rank fusion (RRF,
6263
- **Keyword index.** An expression index: no column is added and no row rewritten, and PostgreSQL keeps it in step with every write. It is made with the passage table; a table made by a release without one gets it from the first write or search of that width (`CREATE INDEX IF NOT EXISTS`, which blocks writes to the table while it builds).
6364
- **Vector leg.** An exact cosine scan; a passage whose cosine similarity is not positive is not ranked by it.
6465

66+
## Pool size and time limit
67+
68+
Two settings, read from the environment at boot when the plugin option is not given (a plugin option wins):
69+
70+
| Setting | Default | |
71+
|:--|:--|:--|
72+
| `OS_KNOWLEDGE_POOL_MAX` | `20` | Connections in the store's own pool, in each process. |
73+
| `OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS` | `10000` | The longest a search's ranking statement may run. |
74+
75+
A value that is not a positive integer stops the boot, naming the setting; a blank one reads as unset.
76+
77+
**Sizing the pool.** The store's pool is its own, beside the platform's (`OS_DATABASE_POOL_MAX`, default 5), and both open connections to the same server when the store is in the platform database. A build of a source also holds one connection of its own (its builder lock) while it runs. Across every replica, keep
78+
79+
```text
80+
replicas × (OS_DATABASE_POOL_MAX + OS_KNOWLEDGE_POOL_MAX + builds running at once) + headroom ≤ max_connections
81+
```
82+
83+
where the headroom covers migrations, admin sessions and `superuser_reserved_connections`. With `max_connections = 200` and 20 kept as headroom, each replica may hold `180 / replicas` connections. The default is a ceiling, not a count opened at boot: the pool opens a connection only when a search finds none idle, and closes idle ones again. Under load, a replica at the defaults reaches up to 26 (5 for the platform, 20 for the store, one build), so the store takes up to `20 × replicas`: 60 with 3 replicas (78 with the platform pools and a build each). That fits up to 6 replicas (6 × 26 = 156 ≤ 180; 7 × 26 = 182 does not). A deployment that sets nothing used to stop at 4 store connections per replica and may now reach 20. With more replicas or a smaller server, lower `OS_KNOWLEDGE_POOL_MAX` (its ceiling is 84 with 2 replicas, 54 with 3, 39 with 4) or raise `max_connections`: a server out of connection slots refuses new connections (`too_many_connections`, class 53), and the searches that needed them are refused `SERVICE_UNAVAILABLE`. The default of 20 is measured: over 59,949 indexed passages with hybrid search, a pool of 4 left a third of the searches at 20 concurrent callers waiting past `connectTimeoutMs`, and a pool of 20 left none. A search holds a connection only while its statement runs; a search that finds every connection busy for `connectTimeoutMs` is refused `SERVICE_UNAVAILABLE`, never answered empty. A larger pool lets more searches wait in the database instead of in the pool: it does not make one search faster.
84+
85+
**The time limit** is set with `SET LOCAL statement_timeout` inside the search statement's own transaction, so it lasts exactly as long as that statement, touches no session setting and holds behind a transaction-mode pooler. (The store as a whole still needs a direct or session-mode connection for its builder lock; see [Rebuilds](#rebuilds).) Only the ranking statement is limited: the catalog reads around it are cheap, and writes and builds are not limited by it.
86+
87+
## When a search fails
88+
89+
A search the database fails is refused with an ADR-0112 code, which the knowledge service hands to its caller in place of that source's hits: never an empty answer. The code is chosen by the error's SQLSTATE, never by the server's message (which `lc_messages` translates):
90+
91+
| What failed | Code |
92+
|:--|:--|
93+
| The statement ran past the time limit, or was cancelled (`57014`) | `TIMEOUT` (504) |
94+
| The database has no capacity: `too_many_connections` and the rest of class `53` | `SERVICE_UNAVAILABLE` (503) |
95+
| No connection: the pool's wait timed out, the connection ended, the server is shutting down or unreachable (class `08`, `57P01`–`57P05`, a socket error) | `SERVICE_UNAVAILABLE` (503) |
96+
| Any other database error | `DATABASE_ERROR` (500) |
97+
98+
The message is one sentence naming the source; the SQLSTATE, the driver's text and the setting to change are in the error's `remedy`, which the knowledge service logs for the operator.
99+
65100
## An approximate index is an operator's step
66101

67102
The store creates no approximate index: every search is an exact scan, which is right for small and medium sources and works at any width. When a table outgrows it, add an index by hand:
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The errors a real `pg` pool throws, read as a search reads them: a statement
5+
* past the `statement_timeout` set with `SET LOCAL` is `TIMEOUT` (504), a wait
6+
* for a connection of a full pool is `SERVICE_UNAVAILABLE` (503), and the
7+
* limit does not outlive its transaction on the pooled connection. The
8+
* doubles in `search-refusals.test.ts` are shaped after these. Needs no
9+
* pgvector, only `OS_TEST_POSTGRES_URL`; the pins are codes and settings,
10+
* never durations (each limit here is far below what it stops).
11+
*/
12+
13+
import { afterAll, describe, expect, it } from 'vitest';
14+
import pg from 'pg';
15+
import { poolFromPg } from '../index.js';
16+
import { searchRefusalOf } from '../errors.js';
17+
import { PG_URL, requireLiveCell } from './live-pg.testkit.js';
18+
19+
requireLiveCell('knowledge-pgvector search refusals');
20+
21+
const LIMITS = { statementTimeoutMs: 50 };
22+
23+
describe.skipIf(!PG_URL)('knowledge-pgvector search refusals — live PostgreSQL', () => {
24+
const pools: pg.Pool[] = [];
25+
const open = (config: pg.PoolConfig): pg.Pool => {
26+
const pool = new pg.Pool({ connectionString: PG_URL, ...config });
27+
pools.push(pool);
28+
return pool;
29+
};
30+
afterAll(async () => {
31+
for (const pool of pools) await pool.end();
32+
});
33+
34+
it('a statement past SET LOCAL statement_timeout is TIMEOUT (504), and the limit ends with its transaction', async () => {
35+
const pool = poolFromPg(open({ max: 1 }));
36+
const client = await pool.connect();
37+
try {
38+
const before = await client.query<{ statement_timeout: string }>('SHOW statement_timeout');
39+
await client.query('BEGIN');
40+
await client.query(`SET LOCAL statement_timeout = ${LIMITS.statementTimeoutMs}`);
41+
const err = await client.query('SELECT pg_sleep(30)').then(
42+
() => undefined,
43+
(e: unknown) => e,
44+
);
45+
await client.query('ROLLBACK');
46+
expect(err).toMatchObject({ code: '57014' });
47+
expect(searchRefusalOf(err, 'policies', LIMITS)).toMatchObject({ code: 'TIMEOUT', status: 504 });
48+
// The same pooled connection, after the transaction: the session's own setting, untouched.
49+
const after = await client.query<{ statement_timeout: string }>('SHOW statement_timeout');
50+
expect(after.rows[0].statement_timeout).toBe(before.rows[0].statement_timeout);
51+
} finally {
52+
client.release();
53+
}
54+
});
55+
56+
it("a full pool's wait timing out is SERVICE_UNAVAILABLE (503), through poolFromPg", async () => {
57+
const pool = poolFromPg(open({ max: 1, connectionTimeoutMillis: 50 }));
58+
const held = await pool.connect();
59+
try {
60+
const viaQuery = await pool.query('SELECT 1').then(
61+
() => undefined,
62+
(e: unknown) => e,
63+
);
64+
const viaConnect = await pool.connect().then(
65+
(c) => {
66+
c.release();
67+
return undefined;
68+
},
69+
(e: unknown) => e,
70+
);
71+
for (const err of [viaQuery, viaConnect]) {
72+
expect(err).toBeInstanceOf(Error);
73+
expect(searchRefusalOf(err, 'policies', LIMITS)).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
74+
}
75+
} finally {
76+
held.release();
77+
}
78+
});
79+
});

0 commit comments

Comments
 (0)