diff --git a/.changeset/knowledge-pgvector-coded-search-refusals.md b/.changeset/knowledge-pgvector-coded-search-refusals.md new file mode 100644 index 00000000000..6673e4822e1 --- /dev/null +++ b/.changeset/knowledge-pgvector-coded-search-refusals.md @@ -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. diff --git a/content/docs/deployment/environment-variables.mdx b/content/docs/deployment/environment-variables.mdx index 808185687cb..751da2a0864 100644 --- a/content/docs/deployment/environment-variables.mdx +++ b/content/docs/deployment/environment-variables.mdx @@ -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. | diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 105eb543109..77aa903e07d 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -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. @@ -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 diff --git a/packages/plugins/knowledge-pgvector/README.md b/packages/plugins/knowledge-pgvector/README.md index 726f6f9fba5..f84798730c2 100644 --- a/packages/plugins/knowledge-pgvector/README.md +++ b/packages/plugins/knowledge-pgvector/README.md @@ -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. | @@ -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: diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/search-refusals.live-postgres.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/search-refusals.live-postgres.test.ts new file mode 100644 index 00000000000..690a97bb8f3 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/search-refusals.live-postgres.test.ts @@ -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(); + } + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/__tests__/search-refusals.test.ts b/packages/plugins/knowledge-pgvector/src/__tests__/search-refusals.test.ts new file mode 100644 index 00000000000..4f4286c4407 --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/__tests__/search-refusals.test.ts @@ -0,0 +1,256 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A search the database fails is a coded refusal, never an empty answer, and + * its ranking statement runs under PostgreSQL's own `statement_timeout`, set + * with `SET LOCAL` in the statement's transaction. Runs everywhere: the + * database is a double that answers the catalog reads and throws, where asked, + * the errors `pg` throws (a SQLSTATE-coded `DatabaseError`, or the pool's own + * uncoded wait timeout). The pins are codes, statuses and statement shapes; + * nothing here waits on a clock. + */ + +import { describe, expect, it } from 'vitest'; +import type pg from 'pg'; +import type { KnowledgeSource } from '@objectstack/spec/ai'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { KnowledgeService } from '@objectstack/service-knowledge'; +import { PgvectorKnowledgeAdapter, poolFromPg, type PgClientLike, type PgPoolLike } from '../index.js'; +import { DEFAULT_POOL_MAX, POOL_MAX_ENV, STATEMENT_TIMEOUT_ENV, resolveStoreSettings } from '../plugin.js'; +import { FakeEmbedder } from './live-pg.testkit.js'; + +const source = { name: 'policies', label: 'policies', adapter: 'pgvector', source: { kind: 'object', object: 'a', content: ['b'] } } as KnowledgeSource; + +/** A `pg` `DatabaseError` as the server sends it: its SQLSTATE in `code`, a severity. */ +function databaseError(sqlstate: string, message: string): Error { + return Object.assign(new Error(message), { code: sqlstate, severity: 'ERROR' }); +} + +/** The error `pg-pool` throws when no connection frees up within `connectionTimeoutMillis`: no code at all. */ +const poolWaitTimeout = (): Error => new Error('timeout exceeded when trying to connect'); + +interface Fault { + /** Thrown by the ranking statement. */ + ranking?: () => Error; + /** Thrown when a connection is taken for the ranking statement's transaction. */ + connect?: () => Error; + /** Thrown by the read of the source's generations. */ + generations?: () => Error; +} + +/** + * A store with one active generation under `fingerprint()`, a table, and a + * ranking that finds one passage, unless `fault` says what fails. It records + * the statements run outside a transaction (`pooled`) and inside one (`inTx`). + */ +function store(fault: Fault = {}, fingerprint: () => string | undefined = () => 'fp') { + const pooled: string[] = []; + const inTx: string[] = []; + const answer = async (text: string): Promise<{ rows: R[] }> => { + if (text.includes('FROM pg_extension')) return { rows: [{ schema: 'public', version: '0.8.0' }] as R[] }; + if (text.includes('to_regclass')) return { rows: [{ present: 'x' }] as R[] }; + if (/SELECT generation, fingerprint, recipe_hash, dim, state FROM/.test(text)) { + if (fault.generations) throw fault.generations(); + return { rows: [{ generation: 1, fingerprint: fingerprint(), recipe_hash: 'rh', dim: 384, state: 'active' }] as R[] }; + } + if (text.includes('AS distance')) { + if (fault.ranking) throw fault.ranking(); + return { + rows: [ + { + chunk_id: 'c1', document_id: 'policies:r1', source_record_id: 'r1', content: 'granite quarry', title: null, + metadata: {}, doc_hash: null, heading_path: null, vpos: 1, kpos: null, + }, + ] as R[], + }; + } + return { rows: [] as R[] }; + }; + const client = (): PgClientLike => ({ + query: async (text: string) => { + inTx.push(text); + return answer(text); + }, + release: () => undefined, + }); + const pool: PgPoolLike = { + query: async (text: string) => { + pooled.push(text); + return answer(text); + }, + connect: async () => { + if (fault.connect) throw fault.connect(); + return client(); + }, + }; + return { pool, pooled, inTx }; +} + +/** The same store reached through `poolFromPg`, as the plugin reaches a real `pg.Pool`. */ +function throughPg(fault: Fault) { + const inner = store(fault); + const fakePg = { + query: (text: string) => inner.pool.query(text), + connect: async () => { + const c = await inner.pool.connect(); + return { query: (text: string) => c.query(text), release: () => undefined }; + }, + options: {}, + } as unknown as pg.Pool; + return { ...inner, pool: poolFromPg(fakePg) }; +} + +async function refusalOf(adapter: PgvectorKnowledgeAdapter): Promise | undefined> { + return adapter.search('granite', { source, topK: 3, index: { fingerprint: 'fp' } }).then( + () => undefined, + (err: unknown) => err as Record, + ); +} + +describe('knowledge-pgvector: the ranking statement runs under statement_timeout', () => { + it('runs in a transaction of its own, SET LOCAL statement_timeout first, the default 10000 ms', async () => { + const db = store(); + const adapter = new PgvectorKnowledgeAdapter({ pool: db.pool, embedder: new FakeEmbedder() }); + + const hits = await adapter.search('granite', { source, topK: 3, index: { fingerprint: 'fp' } }); + + expect(hits.map((h) => h.documentId)).toEqual(['policies:r1']); + expect(db.inTx).toHaveLength(4); + expect(db.inTx[0]).toBe('BEGIN'); + expect(db.inTx[1]).toBe('SET LOCAL statement_timeout = 10000'); + expect(db.inTx[2]).toContain('AS distance'); + expect(db.inTx[3]).toBe('COMMIT'); + // The ranking statement never runs on a pooled connection outside that transaction. + expect(db.pooled.some((text) => text.includes('AS distance'))).toBe(false); + }); + + it('takes the limit it is given', async () => { + const db = store(); + const adapter = new PgvectorKnowledgeAdapter({ pool: db.pool, embedder: new FakeEmbedder(), statementTimeoutMs: 2500 }); + await adapter.search('granite', { source, topK: 3, index: { fingerprint: 'fp' } }); + expect(db.inTx[1]).toBe('SET LOCAL statement_timeout = 2500'); + }); + + it('refuses a limit that is not a positive integer at construction', () => { + for (const statementTimeoutMs of [0, -1, 1.5, Number.NaN]) { + expect(() => new PgvectorKnowledgeAdapter({ pool: store().pool, embedder: new FakeEmbedder(), statementTimeoutMs })).toThrow( + RangeError, + ); + } + }); +}); + +describe('knowledge-pgvector: a failed search is a coded refusal', () => { + it('a statement past statement_timeout (57014) is TIMEOUT (504), rolled back, the driver text kept out of the message', async () => { + const db = store({ ranking: () => databaseError('57014', 'canceling statement due to statement timeout') }); + const adapter = new PgvectorKnowledgeAdapter({ pool: db.pool, embedder: new FakeEmbedder() }); + + const err = await refusalOf(adapter); + + expect(err).toMatchObject({ code: 'TIMEOUT', status: 504 }); + expect(String(err?.message)).toContain("Knowledge source 'policies' was not searched"); + expect(String(err?.message)).not.toContain('canceling statement'); + expect(String(err?.remedy)).toContain('57014'); + expect(String(err?.remedy)).toContain(STATEMENT_TIMEOUT_ENV); + expect(db.inTx.slice(-1)).toEqual(['ROLLBACK']); + }); + + it('a cancelled statement (57014, a cancel request) is TIMEOUT (504) too: judged by SQLSTATE, never by the server text', async () => { + const db = store({ ranking: () => databaseError('57014', '由于用户请求而正在取消语句') }); + const err = await refusalOf(new PgvectorKnowledgeAdapter({ pool: db.pool, embedder: new FakeEmbedder() })); + expect(err).toMatchObject({ code: 'TIMEOUT', status: 504 }); + }); + + it("the pool's wait timing out (an error with no code, through poolFromPg) is SERVICE_UNAVAILABLE (503)", async () => { + const db = throughPg({ connect: poolWaitTimeout }); + const err = await refusalOf(new PgvectorKnowledgeAdapter({ pool: db.pool, embedder: new FakeEmbedder() })); + expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(String(err?.remedy)).toContain(POOL_MAX_ENV); + expect(String(err?.remedy)).toContain('timeout exceeded when trying to connect'); + }); + + it("the pool's wait timing out on a pooled read (the source's generations) is SERVICE_UNAVAILABLE (503)", async () => { + const db = throughPg({ generations: poolWaitTimeout }); + const err = await refusalOf(new PgvectorKnowledgeAdapter({ pool: db.pool, embedder: new FakeEmbedder() })); + expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + }); + + it('too many connections (53300) is SERVICE_UNAVAILABLE (503), naming max_connections to the operator', async () => { + const db = store({ connect: () => databaseError('53300', 'sorry, too many clients already') }); + const err = await refusalOf(new PgvectorKnowledgeAdapter({ pool: db.pool, embedder: new FakeEmbedder() })); + expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + expect(String(err?.remedy)).toContain('max_connections'); + }); + + it('a connection that ends mid-statement (57P01, admin shutdown) is SERVICE_UNAVAILABLE (503)', async () => { + const db = store({ ranking: () => databaseError('57P01', 'terminating connection due to administrator command') }); + const err = await refusalOf(new PgvectorKnowledgeAdapter({ pool: db.pool, embedder: new FakeEmbedder() })); + expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 }); + }); + + it('any other database error (42P01) is DATABASE_ERROR (500)', async () => { + const db = store({ ranking: () => databaseError('42P01', 'relation "x" does not exist') }); + const err = await refusalOf(new PgvectorKnowledgeAdapter({ pool: db.pool, embedder: new FakeEmbedder() })); + expect(err).toMatchObject({ code: 'DATABASE_ERROR', status: 500 }); + }); + + it("an error that is not the database's (the embedder's) is passed on as it is", async () => { + const db = store(); + const embedder = new FakeEmbedder(); + const thrown = new Error('embedding provider unreachable'); + embedder.embed = async () => { + throw thrown; + }; + const err = await refusalOf(new PgvectorKnowledgeAdapter({ pool: db.pool, embedder })); + expect(err).toBe(thrown); + }); + + it('through KnowledgeService: the caller is refused TIMEOUT, not answered an empty hit list', async () => { + let searched: string | undefined; + const db = store({ ranking: () => databaseError('57014', 'canceling statement due to statement timeout') }, () => searched); + const adapter = new PgvectorKnowledgeAdapter({ pool: db.pool, embedder: new FakeEmbedder() }); + const search = adapter.search.bind(adapter); + adapter.search = (query, opts) => { + searched = opts.index?.fingerprint; + return search(query, opts); + }; + const svc = new KnowledgeService({}); + svc.registerAdapter('pgvector', adapter); + svc.registerSource(source); + + const answer = await svc.search('granite', { topK: 3, executionContext: { isSystem: true } as unknown as ExecutionContext }).then( + (hits) => ({ hits }), + (err: unknown) => ({ err: err as Record }), + ); + + expect(answer).toMatchObject({ err: { code: 'TIMEOUT', status: 504 } }); + }); +}); + +describe('knowledge-pgvector: the pool size and the time limit are settings', () => { + it('reads OS_KNOWLEDGE_POOL_MAX and OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS; a plugin option wins; unset or blank keeps the default', () => { + expect(resolveStoreSettings({ env: {} })).toMatchObject({ poolMax: DEFAULT_POOL_MAX, statementTimeoutMs: 10000 }); + expect(DEFAULT_POOL_MAX).toBe(20); + expect(resolveStoreSettings({ env: { [POOL_MAX_ENV]: ' ', [STATEMENT_TIMEOUT_ENV]: '' } })).toMatchObject({ + poolMax: 20, + statementTimeoutMs: 10000, + }); + expect(resolveStoreSettings({ env: { [POOL_MAX_ENV]: '12', [STATEMENT_TIMEOUT_ENV]: '3000' } })).toMatchObject({ + poolMax: 12, + statementTimeoutMs: 3000, + from: { poolMax: POOL_MAX_ENV, statementTimeoutMs: STATEMENT_TIMEOUT_ENV }, + }); + expect(resolveStoreSettings({ poolMax: 6, statementTimeoutMs: 800, env: { [POOL_MAX_ENV]: '12' } })).toMatchObject({ + poolMax: 6, + statementTimeoutMs: 800, + }); + }); + + it('refuses a setting that is not a positive integer, naming it', () => { + for (const raw of ['0', '-3', '1e3', '0x10', '12.0', 'ten']) { + expect(() => resolveStoreSettings({ env: { [POOL_MAX_ENV]: raw } })).toThrow(POOL_MAX_ENV); + expect(() => resolveStoreSettings({ env: { [STATEMENT_TIMEOUT_ENV]: raw } })).toThrow(STATEMENT_TIMEOUT_ENV); + } + expect(() => resolveStoreSettings({ poolMax: 0, env: {} })).toThrow('poolMax'); + }); +}); diff --git a/packages/plugins/knowledge-pgvector/src/errors.ts b/packages/plugins/knowledge-pgvector/src/errors.ts new file mode 100644 index 00000000000..d56abc9bbac --- /dev/null +++ b/packages/plugins/knowledge-pgvector/src/errors.ts @@ -0,0 +1,157 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * How a failed search reaches its caller: as a coded refusal, never as an + * empty answer. + * + * The knowledge service serves an adapter error as a refusal only when it + * carries an ADR-0112 `code` and an HTTP `status`; any other throw is logged + * and the source skipped, so the caller is answered as if the source held + * nothing. A `pg` error carries neither — a PostgreSQL error's `code` is its + * SQLSTATE (`57014`), a pool's wait timeout carries no code at all — so before + * this module a busy database read as "no passage matches". + * + * {@link searchRefusalOf} turns every error of the store's database met during + * a search into one, judged by the SQLSTATE and never by the server's message + * (which `lc_messages` translates): + * + * | What failed | Code | Status | + * |:--|:--|:--| + * | the statement was stopped (`57014`: the store's `statement_timeout`, or a cancel) | `TIMEOUT` | 504 | + * | the database has no capacity (class `53`: `too_many_connections`, out of memory, disk full) | `SERVICE_UNAVAILABLE` | 503 | + * | no connection (class `08`, `57P01`–`57P05`, a socket error, or no SQLSTATE: the pool's wait timed out, the connection ended) | `SERVICE_UNAVAILABLE` | 503 | + * | any other SQLSTATE | `DATABASE_ERROR` | 500 | + * + * The message is one sentence a search caller may read, with no driver text; + * the driver's text and what to change are operator text, in `remedy`, which + * the knowledge service logs. An error that already carries a code (the + * adapter's own refusals) is passed on as it is, and so is one that is not the + * database's (the embedder's, say). + */ + +/** Marks an error thrown by the store's `pg` pool or one of its connections (see {@link storeError}). */ +const STORE_ERROR = Symbol.for('objectstack.knowledge-pgvector.store-error'); + +/** PostgreSQL's SQLSTATE `query_canceled`: `statement_timeout`, or a cancel request. */ +export const QUERY_CANCELED = '57014'; + +/** + * Marks `err` as one the store's database connection threw, and answers it. + * The error itself is unchanged (no message, code or enumerable key is + * touched), so every other reader of it reads what `pg` threw. + */ +export function storeError(err: unknown): unknown { + if (err !== null && typeof err === 'object' && !Object.prototype.hasOwnProperty.call(err, STORE_ERROR)) { + try { + Object.defineProperty(err, STORE_ERROR, { value: true, enumerable: false }); + } catch { + // A frozen error stays unmarked; one with a SQLSTATE is still judged by it. + } + } + return err; +} + +/** What the refusal's operator text says about the store's limits. */ +export interface SearchLimits { + /** The store's `statement_timeout` for a search statement, in milliseconds. */ + statementTimeoutMs: number; +} + +/** + * The error a search throws for `err`: a coded refusal when `err` is an + * uncoded failure of the store's database, else `err` as it is. + */ +export function searchRefusalOf(err: unknown, sourceId: string, limits: SearchLimits): unknown { + if (isCoded(err)) return err; + const sqlstate = sqlStateOf(err); + if (sqlstate === undefined && !isMarked(err) && !isSocketError(err)) return err; + + const driver = driverText(err, sqlstate); + const refuse = (code: string, status: number, message: string, remedy: string): Error => + Object.assign(new Error(`Knowledge source '${sourceId}' was not searched: ${message}`), { + code, + status, + remedy: `${driver} ${remedy}`, + cause: err, + }); + + if (sqlstate === QUERY_CANCELED) { + return refuse( + 'TIMEOUT', + 504, + 'the knowledge store (pgvector) did not answer in time.', + `The store limits each search statement to ${limits.statementTimeoutMs} ms (PostgreSQL's statement_timeout, ` + + "set with SET LOCAL in the statement's own transaction), or the statement was cancelled. If searches this " + + 'large are expected to take longer, raise OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS (or the plugin option ' + + '`statementTimeoutMs`); if many searches time out at once, the database is saturated.', + ); + } + if (sqlstate !== undefined && sqlstate.startsWith('53')) { + return refuse( + 'SERVICE_UNAVAILABLE', + 503, + 'the knowledge store (pgvector) is busy and has no capacity for this search now.', + "The database refused for lack of resources. When it is too_many_connections, every replica's pools together " + + "(OS_DATABASE_POOL_MAX and OS_KNOWLEDGE_POOL_MAX, each per replica) open more connections than the server's " + + 'max_connections allows: lower them, or raise max_connections.', + ); + } + if (sqlstate === undefined || sqlstate.startsWith('08') || /^57P0[1-5]$/.test(sqlstate)) { + return refuse( + 'SERVICE_UNAVAILABLE', + 503, + 'the knowledge store (pgvector) had no database connection for this search.', + "Every connection of the store's pool stayed busy for as long as a search waits for one, or the database could " + + 'not be reached. Under load, raise the pool (OS_KNOWLEDGE_POOL_MAX, or the plugin option `poolMax`) within ' + + "the database's max_connections; otherwise check that the database is up and reachable.", + ); + } + return refuse( + 'DATABASE_ERROR', + 500, + 'the knowledge store (pgvector) failed with a database error.', + 'Read the SQLSTATE above; a repeated error is a defect of the store or of its database.', + ); +} + +/** An ADR-0112 refusal: a SCREAMING_SNAKE `code` and an HTTP error `status` (the knowledge service's own test). */ +function isCoded(err: unknown): boolean { + if (err === null || typeof err !== 'object') return false; + const { code, status } = err as { code?: unknown; status?: unknown }; + return ( + typeof code === 'string' && + /^[A-Z][A-Z0-9_]*$/.test(code) && + typeof status === 'number' && + Number.isInteger(status) && + status >= 400 && + status <= 599 + ); +} + +/** The SQLSTATE a PostgreSQL error carries (`pg`'s `DatabaseError.code`): five digits or upper-case letters. */ +function sqlStateOf(err: unknown): string | undefined { + if (err === null || typeof err !== 'object') return undefined; + const { code, severity } = err as { code?: unknown; severity?: unknown }; + if (typeof code !== 'string' || !/^[0-9A-Z]{5}$/.test(code)) return undefined; + // A five-letter word is not a SQLSTATE unless the server sent it: its + // errors carry a severity. Every SQLSTATE class but the `P`, `X`, `H`, `F` + // ones starts with a digit. + return /^[0-9]/.test(code) || typeof severity === 'string' ? code : undefined; +} + +function isMarked(err: unknown): boolean { + return err !== null && typeof err === 'object' && (err as Record)[STORE_ERROR] === true; +} + +/** A Node socket error (`ECONNREFUSED`, `ECONNRESET`, `ETIMEDOUT`, …): the database could not be reached. */ +function isSocketError(err: unknown): boolean { + if (err === null || typeof err !== 'object') return false; + const { code, syscall } = err as { code?: unknown; syscall?: unknown }; + return typeof code === 'string' && /^E[A-Z]+$/.test(code) && typeof syscall === 'string'; +} + +/** The driver's text, for the operator: its SQLSTATE when it has one, and its message. */ +function driverText(err: unknown, sqlstate: string | undefined): string { + const message = err instanceof Error ? err.message : String(err); + return sqlstate === undefined ? `The driver answered: ${message}.` : `PostgreSQL answered ${sqlstate}: ${message}.`; +} diff --git a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts index c73f0f0a0b2..0b54319ee9d 100644 --- a/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts +++ b/packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts @@ -31,6 +31,7 @@ import { vectorTable, vectorTableDdl, } from './sql.js'; +import { searchRefusalOf } from './errors.js'; /** One answer of a query: its rows. */ export interface PgQueryResult> { @@ -102,6 +103,14 @@ export interface PgvectorKnowledgeAdapterOptions { buildLockIdleMs?: number; /** How many passage rows of a replaced generation one DELETE removes. @default 1000 */ deleteBatchSize?: number; + /** + * The longest a search's ranking statement may run, in milliseconds: + * PostgreSQL's `statement_timeout`, set with `SET LOCAL` in the statement's + * own transaction (so it holds behind a transaction-mode pooler and never + * outlives the statement). A statement past it is stopped by the server and + * the search refused `TIMEOUT` (504). @default 10000 + */ + statementTimeoutMs?: number; /** Where the adapter reports what it cannot hand to a caller: an old generation it could not delete. */ logger?: { warn?(message: string): void }; } @@ -124,6 +133,9 @@ const CONCURRENT_MODIFICATION = 'CONCURRENT_MODIFICATION'; /** The `k` of reciprocal rank fusion: a passage at rank `r` of a leg adds `1 / (k + r)` to its score. */ export const RRF_K = 60; +/** The default of {@link PgvectorKnowledgeAdapterOptions.statementTimeoutMs}, in milliseconds. */ +export const DEFAULT_STATEMENT_TIMEOUT_MS = 10_000; + /** A generation row: one complete index of one source under one fingerprint. */ interface GenerationRow { generation: number; @@ -285,6 +297,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { private readonly queryPrefix: string; private readonly buildLockIdleMs: number; private readonly deleteBatchSize: number; + private readonly statementTimeoutMs: number; private readonly logger?: { warn?(message: string): void }; private readiness?: Readiness; /** Widths whose passage table this adapter has created or found. */ @@ -318,6 +331,12 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { if (!Number.isInteger(this.deleteBatchSize) || this.deleteBatchSize < 1) { throw new RangeError(`knowledge-pgvector: deleteBatchSize must be a positive integer, got ${String(opts.deleteBatchSize)}`); } + this.statementTimeoutMs = opts.statementTimeoutMs ?? DEFAULT_STATEMENT_TIMEOUT_MS; + if (!Number.isSafeInteger(this.statementTimeoutMs) || this.statementTimeoutMs < 1) { + throw new RangeError( + `knowledge-pgvector: statementTimeoutMs must be a positive integer, got ${String(opts.statementTimeoutMs)}`, + ); + } this.logger = opts.logger; } @@ -535,6 +554,18 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { if (opts.organizationIds !== undefined && opts.organizationIds.length === 0) return []; // A record scope with no term that has ids ranks nothing (ADR-0161 K8, item 17). if (opts.scope !== undefined && !opts.scope.some((term) => term.ids.length > 0)) return []; + try { + return await this.searchAttempts(query, opts); + } catch (err) { + // A failure of the database is a coded refusal, never an empty answer + // (see `errors.ts`): the knowledge service skips a source whose search + // throws an uncoded error, and its caller would read "nothing matches". + throw searchRefusalOf(err, opts.source.name, { statementTimeoutMs: this.statementTimeoutMs }); + } + } + + /** {@link search}'s attempts: again while a completed build switches the source's index under it. */ + private async searchAttempts(query: string, opts: AdapterSearchOptions): Promise { for (let attempt = 1; ; attempt++) { const hits = await this.searchAttempt(query, opts); if (hits !== undefined) return hits; @@ -557,7 +588,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { * passages are being deleted). */ private async searchAttempt(query: string, opts: AdapterSearchOptions): Promise { - const pool = this.requirePool(); + this.requirePool(); const readiness = await this.ready(); // The embedder first: without one the service's fingerprint carries no // model or width, and comparing it would refuse a healthy index as one to @@ -699,7 +730,7 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { ); legs.push('SELECT chunk_id, NULL::bigint AS vpos, pos AS kpos FROM kw'); } - const result = await pool.query<{ + const result = await this.searchStatement<{ chunk_id: string; document_id: string; source_record_id: string | null; @@ -1349,6 +1380,20 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter { } } + /** + * A search's ranking statement, under the store's time limit: in a + * transaction of its own, `SET LOCAL statement_timeout` first, so the limit + * lasts exactly as long as the statement and depends on no session state (it + * holds behind a transaction-mode pooler). The server stops a statement past + * it with SQLSTATE `57014`, which {@link search} answers as `TIMEOUT`. + */ + private async searchStatement(text: string, params: unknown[]): Promise> { + return this.inTransaction(async (client) => { + await client.query(`SET LOCAL statement_timeout = ${this.statementTimeoutMs}`); + return client.query(text, params); + }); + } + /** Run `work` in one transaction: committed when it resolves, rolled back when it throws. */ private async inTransaction(work: (client: PgClientLike) => Promise): Promise { let value: T | undefined; diff --git a/packages/plugins/knowledge-pgvector/src/plugin.ts b/packages/plugins/knowledge-pgvector/src/plugin.ts index 180373cb9cd..8c12df4d9ad 100644 --- a/packages/plugins/knowledge-pgvector/src/plugin.ts +++ b/packages/plugins/knowledge-pgvector/src/plugin.ts @@ -4,7 +4,26 @@ import pg from 'pg'; import type { Plugin, PluginContext } from '@objectstack/core'; import type { IEmbedder, IKnowledgeService } from '@objectstack/spec/contracts'; import { EMBEDDER_SERVICE, KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts'; -import { PgvectorKnowledgeAdapter, type PgPoolLike } from './pgvector-adapter.js'; +import { DEFAULT_STATEMENT_TIMEOUT_MS, PgvectorKnowledgeAdapter, type PgPoolLike } from './pgvector-adapter.js'; +import { storeError } from './errors.js'; + +/** The setting that sizes the store's pool: connections per process (per replica). */ +export const POOL_MAX_ENV = 'OS_KNOWLEDGE_POOL_MAX'; +/** The setting that limits a search statement, in milliseconds. */ +export const STATEMENT_TIMEOUT_ENV = 'OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS'; +/** + * The store's pool size when neither `poolMax` nor {@link POOL_MAX_ENV} is + * set. Raised from 4 on a measurement (PostgreSQL 17 + pgvector 0.8.7, 59,949 + * indexed passages, 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. It is a ceiling, not a count: `pg.Pool` opens a connection only + * when a search finds none idle, and closes idle ones again. Every deployment + * that sets nothing may now reach 20 per replica under load instead of 4; the + * README shows that this fits up to 6 replicas against `max_connections=200`, + * and that a smaller server or more replicas lowers it, since a server out of + * connection slots refuses searches `SERVICE_UNAVAILABLE` (class 53). + */ +export const DEFAULT_POOL_MAX = 20; /** Options of {@link KnowledgePgvectorPlugin}. */ export interface KnowledgePgvectorPluginOptions { @@ -19,7 +38,11 @@ export interface KnowledgePgvectorPluginOptions { url?: string; /** The schema the store's tables live in. @default 'os_knowledge' */ schema?: string; - /** Connections in the store's own pool. @default 4 */ + /** + * Connections in the store's own pool, per process. Absent: the setting + * `OS_KNOWLEDGE_POOL_MAX`, else 20. A search waits for a free one at most + * `connectTimeoutMs`, and is refused `SERVICE_UNAVAILABLE` past it. + */ poolMax?: number; /** * How long a new connection may take before it fails, in milliseconds. Boot @@ -27,11 +50,17 @@ export interface KnowledgePgvectorPluginOptions { * long, once, and each later call as long. @default 5000 */ connectTimeoutMs?: number; + /** + * The longest a search statement may run, in milliseconds (PostgreSQL's + * `statement_timeout`, see the adapter's option). Absent: the setting + * `OS_KNOWLEDGE_STATEMENT_TIMEOUT_MS`, else 10000. + */ + statementTimeoutMs?: number; /** Text put before every query before it is embedded (see the adapter's option). */ queryPrefix?: string; /** The embedder to call. Absent: the kernel's `embedder` service, read at each call. */ embedder?: IEmbedder; - /** The environment the URL is read from. @default process.env */ + /** The environment the URL and the settings are read from. @default process.env */ env?: Record; } @@ -60,22 +89,71 @@ export function resolveStoreUrl( return { reason: 'it was given no `url`, and the platform database URL (OS_DATABASE_URL) is not set.' }; } +/** + * The store's pool size and search time limit, and where each was read from: + * the plugin option, else its setting ({@link POOL_MAX_ENV}, + * {@link STATEMENT_TIMEOUT_ENV}), else the default. A setting that is not a + * positive integer throws, naming it: a pool size is tuned only under load, so + * a typo must stop the boot rather than quietly keep the default the operator + * meant to change. A blank setting reads as unset. + */ +export function resolveStoreSettings( + opts: Pick, +): { poolMax: number; statementTimeoutMs: number; from: { poolMax: string; statementTimeoutMs: string } } { + const env = opts.env ?? process.env; + const read = (option: number | undefined, optionName: string, name: string, fallback: number): [number, string] => { + if (option !== undefined) { + if (!Number.isSafeInteger(option) || option < 1) { + throw new RangeError(`KnowledgePgvectorPlugin: \`${optionName}\` must be a positive integer, got ${String(option)}.`); + } + return [option, `the plugin option \`${optionName}\``]; + } + const raw = env[name]; + if (raw === undefined || raw.trim() === '') return [fallback, 'the default']; + const trimmed = raw.trim(); + const value = /^[0-9]+$/.test(trimmed) ? Number(trimmed) : NaN; + if (!Number.isSafeInteger(value) || value < 1) { + throw new RangeError( + `${name} must be a positive integer, got ${JSON.stringify(raw)}. Unset it to keep the default of ${fallback}.`, + ); + } + return [value, name]; + }; + const [poolMax, poolFrom] = read(opts.poolMax, 'poolMax', POOL_MAX_ENV, DEFAULT_POOL_MAX); + const [statementTimeoutMs, timeoutFrom] = read( + opts.statementTimeoutMs, + 'statementTimeoutMs', + STATEMENT_TIMEOUT_ENV, + DEFAULT_STATEMENT_TIMEOUT_MS, + ); + return { poolMax, statementTimeoutMs, from: { poolMax: poolFrom, statementTimeoutMs: timeoutFrom } }; +} + function isPostgresUrl(url: string): boolean { return /^postgres(ql)?:\/\//i.test(url); } -/** A `pg.Pool` seen as the adapter's {@link PgPoolLike}. */ +/** + * A `pg.Pool` seen as the adapter's {@link PgPoolLike}. Every error it or one + * of its connections throws is marked as the database's (`storeError`), so a + * search can answer one that carries no SQLSTATE — the pool's wait timed out, + * the connection ended — as a coded refusal; nothing else of the error changes. + */ export function poolFromPg(pool: pg.Pool): PgPoolLike { + const marked = (work: Promise): Promise => + work.catch((err: unknown) => { + throw storeError(err); + }); return { query: async (text: string, params?: unknown[]) => { - const result = await pool.query(text, params as unknown[] | undefined); + const result = await marked(pool.query(text, params as unknown[] | undefined)); return { rows: result.rows as R[] }; }, connect: async () => { - const client = await pool.connect(); + const client = await marked(pool.connect()); return { query: async (text: string, params?: unknown[]) => { - const result = await client.query(text, params as unknown[] | undefined); + const result = await marked(client.query(text, params as unknown[] | undefined)); return { rows: result.rows as R[] }; }, release: (err?: Error | boolean) => client.release(err), @@ -88,10 +166,10 @@ export function poolFromPg(pool: pg.Pool): PgPoolLike { // A session that drops lets go of its advisory lock in the server; its // error must not end the process, and the next query on it fails. client.on('error', () => undefined); - await client.connect(); + await marked(client.connect()); return { query: async (text: string, params?: unknown[]) => { - const result = await client.query(text, params as unknown[] | undefined); + const result = await marked(client.query(text, params as unknown[] | undefined)); return { rows: result.rows as R[] }; }, release: () => { @@ -106,7 +184,8 @@ export function poolFromPg(pool: pg.Pool): PgPoolLike { * `KnowledgePgvectorPlugin` — registers a {@link PgvectorKnowledgeAdapter} * with the host's `IKnowledgeService` during `start()`. * - * It opens a small pool of its own (`poolMax`, default 4) to the store's + * It opens a small pool of its own (`poolMax`, else the setting + * `OS_KNOWLEDGE_POOL_MAX`, default 20) to the store's * database: the `url` it is given, else the platform database when that is * PostgreSQL. A connection that takes longer than `connectTimeoutMs` (default * 5000) fails, so an unreachable host does not hold boot. When the database cannot hold the store yet (no pgvector @@ -149,10 +228,11 @@ export class KnowledgePgvectorPlugin implements Plugin { } const target = resolveStoreUrl(this.opts); + const settings = resolveStoreSettings(this.opts); if (target.url !== undefined) { this.pool = new pg.Pool({ connectionString: target.url, - max: this.opts.poolMax ?? 4, + max: settings.poolMax, connectionTimeoutMillis: this.opts.connectTimeoutMs ?? 5000, }); // An idle connection's error (the server restarted) must not end the process. @@ -176,6 +256,7 @@ export class KnowledgePgvectorPlugin implements Plugin { ...(this.pool ? { pool: poolFromPg(this.pool) } : { unavailable: target.url === undefined ? target.reason : undefined }), embedder, schema: this.opts.schema, + statementTimeoutMs: settings.statementTimeoutMs, queryPrefix: this.opts.queryPrefix, logger: ctx.logger, }); @@ -184,7 +265,11 @@ export class KnowledgePgvectorPlugin implements Plugin { const health = await adapter.healthCheck(); if (health.ok) { - ctx.logger.info?.(`KnowledgePgvectorPlugin: adapter '${adapter.id}' registered (${health.message}).`); + ctx.logger.info?.( + `KnowledgePgvectorPlugin: adapter '${adapter.id}' registered (${health.message}; pool ${settings.poolMax} ` + + `from ${settings.from.poolMax}, search statements limited to ${settings.statementTimeoutMs} ms from ` + + `${settings.from.statementTimeoutMs}).`, + ); } else { ctx.logger.warn?.( `KnowledgePgvectorPlugin: adapter '${adapter.id}' registered but not ready; its sources answer ` +