Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/knowledge-pgvector-coded-search-refusals.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/knowledge-pgvector': patch
---

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

Clause-②: yes
Metadata-protocol: none

- 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`.
- 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.
- 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.
2 changes: 2 additions & 0 deletions content/docs/deployment/environment-variables.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ read at startup unless noted otherwise. Boolean variables accept `true` / `false
| `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. |
| `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). |
| `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. |
| `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. |
| `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. |
| `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. |
| `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. |
| `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. |
Expand Down
16 changes: 12 additions & 4 deletions content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -736,10 +736,10 @@ service. It takes the service's passages, embeds them with the kernel's
an exact scan.

- **Which database.** The `url` option when it is given, else the platform
database when that is PostgreSQL (`OS_DATABASE_URL`). Its own small pool
(`poolMax`, default 4; a connection that takes more than
`connectTimeoutMs`, default 5000, fails); no pooled connection waits on the
embedder. Where organizations
database when that is PostgreSQL (`OS_DATABASE_URL`). Its own small pool,
per process, sized by `poolMax`, else the setting `OS_KNOWLEDGE_POOL_MAX`,
else 20 (a connection that takes more than `connectTimeoutMs`, default 5000,
fails); no pooled connection waits on the embedder. Where organizations
have databases of their own, the store is still the ONE database the
plugin connects to; organizations are kept apart by its
`organization_id` column, which every search filters on before ranking.
Expand Down Expand Up @@ -773,6 +773,14 @@ an exact scan.
are one `WHERE`, run in both legs before either ranks.
`queryPrefix` is put before every query before it is embedded, for a model
that embeds questions and passages differently.
The ranking statement runs in a transaction of its own under
`SET LOCAL statement_timeout` (`statementTimeoutMs`, else
`OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS`, else 10000 ms), so the limit holds no
session state.
A search the database fails is refused by its SQLSTATE, never answered
empty: `TIMEOUT` (504) for a statement stopped or cancelled,
`SERVICE_UNAVAILABLE` (503) when no connection or capacity was available,
`DATABASE_ERROR` (500) for any other database error.
- **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is
not embedded again; its row's metadata is rewritten.
- **Rebuilds.** A write or a search under another fingerprint is refused
Expand Down
39 changes: 37 additions & 2 deletions packages/plugins/knowledge-pgvector/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ A source is usually a `knowledge_source` metadata item (a `*.knowledge-source.ts
| `id` | `'pgvector'` | The adapter id a source names in `adapter`. |
| `url` | the platform database | A `postgres://` URL. Absent: `OS_DATABASE_URL` (else the legacy `DATABASE_URL`) when it is PostgreSQL. |
| `schema` | `'os_knowledge'` | The schema the store's tables live in. |
| `poolMax` | `4` | Connections in the store's own pool. |
| `connectTimeoutMs` | `5000` | How long a new connection may take before it fails; boot waits on the store's first check. |
| `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). |
| `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. |
| `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`). |
| `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. |
| `embedder` | the kernel's `embedder` service | The embedder to call. |

Expand Down Expand Up @@ -62,6 +63,40 @@ Two legs in one statement (one snapshot), merged by reciprocal rank fusion (RRF,
- **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).
- **Vector leg.** An exact cosine scan; a passage whose cosine similarity is not positive is not ranked by it.

## Pool size and time limit

Two settings, read from the environment at boot when the plugin option is not given (a plugin option wins):

| Setting | Default | |
|:--|:--|:--|
| `OS_KNOWLEDGE_POOL_MAX` | `20` | Connections in the store's own pool, in each process. |
| `OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS` | `10000` | The longest a search's ranking statement may run. |

A value that is not a positive integer stops the boot, naming the setting; a blank one reads as unset.

**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

```text
replicas × (OS_DATABASE_POOL_MAX + OS_KNOWLEDGE_POOL_MAX + builds running at once) + headroom ≤ max_connections
```

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.

**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.

## When a search fails

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):

| What failed | Code |
|:--|:--|
| The statement ran past the time limit, or was cancelled (`57014`) | `TIMEOUT` (504) |
| The database has no capacity: `too_many_connections` and the rest of class `53` | `SERVICE_UNAVAILABLE` (503) |
| 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) |
| Any other database error | `DATABASE_ERROR` (500) |

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.

## An approximate index is an operator's step

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:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* The errors a real `pg` pool throws, read as a search reads them: a statement
* past the `statement_timeout` set with `SET LOCAL` is `TIMEOUT` (504), a wait
* for a connection of a full pool is `SERVICE_UNAVAILABLE` (503), and the
* limit does not outlive its transaction on the pooled connection. The
* doubles in `search-refusals.test.ts` are shaped after these. Needs no
* pgvector, only `OS_TEST_POSTGRES_URL`; the pins are codes and settings,
* never durations (each limit here is far below what it stops).
*/

import { afterAll, describe, expect, it } from 'vitest';
import pg from 'pg';
import { poolFromPg } from '../index.js';
import { searchRefusalOf } from '../errors.js';
import { PG_URL, requireLiveCell } from './live-pg.testkit.js';

requireLiveCell('knowledge-pgvector search refusals');

const LIMITS = { statementTimeoutMs: 50 };

describe.skipIf(!PG_URL)('knowledge-pgvector search refusals — live PostgreSQL', () => {
const pools: pg.Pool[] = [];
const open = (config: pg.PoolConfig): pg.Pool => {
const pool = new pg.Pool({ connectionString: PG_URL, ...config });
pools.push(pool);
return pool;
};
afterAll(async () => {
for (const pool of pools) await pool.end();
});

it('a statement past SET LOCAL statement_timeout is TIMEOUT (504), and the limit ends with its transaction', async () => {
const pool = poolFromPg(open({ max: 1 }));
const client = await pool.connect();
try {
const before = await client.query<{ statement_timeout: string }>('SHOW statement_timeout');
await client.query('BEGIN');
await client.query(`SET LOCAL statement_timeout = ${LIMITS.statementTimeoutMs}`);
const err = await client.query('SELECT pg_sleep(30)').then(
() => undefined,
(e: unknown) => e,
);
await client.query('ROLLBACK');
expect(err).toMatchObject({ code: '57014' });
expect(searchRefusalOf(err, 'policies', LIMITS)).toMatchObject({ code: 'TIMEOUT', status: 504 });
// The same pooled connection, after the transaction: the session's own setting, untouched.
const after = await client.query<{ statement_timeout: string }>('SHOW statement_timeout');
expect(after.rows[0].statement_timeout).toBe(before.rows[0].statement_timeout);
} finally {
client.release();
}
});

it("a full pool's wait timing out is SERVICE_UNAVAILABLE (503), through poolFromPg", async () => {
const pool = poolFromPg(open({ max: 1, connectionTimeoutMillis: 50 }));
const held = await pool.connect();
try {
const viaQuery = await pool.query('SELECT 1').then(
() => undefined,
(e: unknown) => e,
);
const viaConnect = await pool.connect().then(
(c) => {
c.release();
return undefined;
},
(e: unknown) => e,
);
for (const err of [viaQuery, viaConnect]) {
expect(err).toBeInstanceOf(Error);
expect(searchRefusalOf(err, 'policies', LIMITS)).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
}
} finally {
held.release();
}
});
});
Loading
Loading