Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(search): a search transaction sets everything it needs in one statement (#6721)
garrytan32038c4c5829
diff --git a/src/core/engine-sql/cjk-search.ts b/src/core/engine-sql/cjk-search.tsindex 196ce253c0..299348352a 100644--- a/src/core/engine-sql/cjk-search.ts+++ b/src/core/engine-sql/cjk-search.ts@@ -44,8 +44,13 @@ import { buildCJKCandidateSql, buildCJKKeywordSql, type CjkKeywordCtx, type CjkKimport { scopedRead, type ScopedRead } from './brands.ts';import type { SqlExecutor } from './executor.ts';-/** Runs `read` on the engine's scoped read executor. */-export type ScopedReadRunner = <T>(read: (exec: ScopedRead) => Promise<T>) => Promise<T>;+/**+ * Runs `read` on the engine's scoped read executor. `settings` (setting name+ * to transaction-local value) are applied before `read` in the same scoped+ * transaction: Postgres folds them into its one settings statement+ * (postgres-engine/search-settings.ts); PGLite's dialects never ask for any.+ */+export type ScopedReadRunner = <T>(read: (exec: ScopedRead) => Promise<T>, settings?: Readonly<Record<string, string>>) => Promise<T>;export const CJK_CANDIDATE_CAP = 2000;export const PGLITE_CJK_CAPPED_CHUNKS = 50_000;diff --git a/src/core/engine-sql/keyword-pages.ts b/src/core/engine-sql/keyword-pages.tsindex 5cee7a838a..b819d76a43 100644--- a/src/core/engine-sql/keyword-pages.ts+++ b/src/core/engine-sql/keyword-pages.ts@@ -23,10 +23,8 @@ export async function countKeywordPages(const statement = buildKeywordCountStatement(query, opts);if (!statement) return 0;const timeout = dialect.statementTimeout && dialect.timeoutMs ? `${Math.max(1, Math.floor(dialect.timeoutMs))}ms` : dialect.statementTimeout;- const rows = await scoped(async (exec) => {- if (timeout) await exec.query(`SELECT set_config('statement_timeout', $1, true)`, [timeout]);- return (await exec.unsafe<{ n: number }>(statement.sql, statement.params)).rows;- });+ const rows = await scoped(async exec => (await exec.unsafe<{ n: number }>(statement.sql, statement.params)).rows,+ timeout ? { statement_timeout: timeout } : undefined);return Number(rows[0]?.n ?? 0);}@@ -36,9 +34,7 @@ export async function searchKeywordPages(): Promise<SearchResult[]> {const statement = buildKeywordPagesStatement(query, opts, page);if (!statement) return [];- const rows = await scoped(async (exec) => {- if (dialect.statementTimeout) await exec.query(`SELECT set_config('statement_timeout', $1, true)`, [dialect.statementTimeout]);- return (await exec.unsafe(statement.sql, statement.params)).rows;- });+ const rows = await scoped(async exec => (await exec.unsafe(statement.sql, statement.params)).rows,+ dialect.statementTimeout ? { statement_timeout: dialect.statementTimeout } : undefined);return rows.map(rowToSearchResult);}diff --git a/src/core/engine-sql/titles.ts b/src/core/engine-sql/titles.tsindex 123d6efe88..ca50bf52be 100644--- a/src/core/engine-sql/titles.ts+++ b/src/core/engine-sql/titles.ts@@ -63,22 +63,16 @@ export async function searchTitles(console.warn(`[gbrain] Warning: search limit clamped from ${opts.limit} to ${searchLimitCap()}`);}const statement = buildSearchTitlesStatement(query, opts, dialect);- const run = (queryText: string, relaxed: boolean) =>- scoped(async (exec) => {- if (dialect.statementTimeout) {- await exec.query(`SELECT set_config('statement_timeout', $1, true)`, [dialect.statementTimeout]);- }- const preferIndex = relaxed && dialect.relaxedPrefersIndex && !statement.safeChunks;- const previous = preferIndex- ? (await exec.query<{ enable_seqscan: string }>(`SHOW enable_seqscan`)).rows[0].enable_seqscan- : '';- if (preferIndex) await exec.query(`SELECT set_config('enable_seqscan', 'off', true)`);- const params = [...statement.params];- params[0] = queryText;- const { rows } = await exec.unsafe(statement.sql, params);- if (preferIndex) await exec.query(`SELECT set_config('enable_seqscan', $1, true)`, [previous]);- return rows;- });+ const run = (queryText: string, relaxed: boolean) => {+ const preferIndex = relaxed && dialect.relaxedPrefersIndex && !statement.safeChunks;+ const settings = {+ ...(dialect.statementTimeout ? { statement_timeout: dialect.statementTimeout } : {}),+ ...(preferIndex ? { enable_seqscan: 'off' } : {}),+ };+ const params = [...statement.params];+ params[0] = queryText;+ return scoped(async exec => (await exec.unsafe(statement.sql, params)).rows, Object.keys(settings).length ? settings : undefined);+ };const strictQuery = statement.params[0] as string;const rows = await run(strictQuery, false);diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex ffed3f184d..d06f8e827c 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -69,8 +69,8 @@ import { SCHEMA_SQL } from './schema-embedded.generated.ts';import { verifySchema } from './schema-verify.ts';import { applyChunkEmbeddingIndexPolicy, dropZombieIndexes, supportsHnswIterativeScan } from './vector-index.ts';import { searchIndexWalk, searchVectorPool, readVectorPool, remainingVectorBudget, type VectorPoolAttempt, POOL_MAX_SCAN_TUPLES } from './search/vector-pool.ts';-import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, SCOPE_CHUNKS_SQL, SET_STATEMENT_TIMEOUT_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeLoader, type PageSourceStats, type ScopeChunkCount, type VectorSearchStatement } from './search/vector-statement.ts';-import { withVectorSettings } from './search/vector-settings.ts';+import { buildVectorSearchStatement, PAGE_SOURCE_STATS_SQL, SCOPE_CHUNKS_SQL, VECTOR_EXTENSION_VERSION_SQL, vectorScopeLoader, type PageSourceStats, type ScopeChunkCount, type VectorSearchStatement } from './search/vector-statement.ts';+import { VECTOR_SETTING_DEFAULTS, vectorScanSettings } from './search/vector-settings.ts';import { guardSearchStatistics } from './search/projection-statistics.ts';import {vectorCastSuffix,@@ -120,7 +120,7 @@ import { DELETE_BATCH_SIZE, TRAVERSE_PATH_ROW_CAP, TRAVERSE_WALK_ROW_CAP } fromimport { PageMissingError } from './engine-errors.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from './embed-skip.ts';import { acquireInitSchemaAdvisoryLock } from './postgres-engine/init-schema-lock.ts';-import { withSearchJitOff } from './postgres-engine/search-settings.ts';+import { SEARCH_JIT_OFF, withSearchJitOff, withSearchSettings, type SearchSettings } from './postgres-engine/search-settings.ts';import { loadKeywordStatementTimeout } from './postgres-engine/keyword-statement-timeout.ts';import { applyPostgresForwardReferenceBootstrap } from './engine-sql/bootstrap.ts';import * as factsImpl from './engine-sql/facts.ts';@@ -341,7 +341,7 @@ export class PostgresEngine implements BrainEngine {sourceIds: string[] | undefined,sourceId: string | undefined,callback: (tx: ReturnType<typeof postgres>) => Promise<T>,- opts?: { alwaysTransaction?: boolean; jitOff?: boolean },+ opts?: { alwaysTransaction?: boolean; jitOff?: boolean; settings?: SearchSettings | (() => SearchSettings) },): Promise<T> {// Flag off + no pre-existing transaction need: call through on the// shared pool exactly as master does. No tx round-trip, no pool slot@@ -360,14 +360,18 @@ export class PostgresEngine implements BrainEngine {}return this.transaction(async engine => {const tx = (engine as PostgresEngine).sql;- const previous = this.rlsScopeBindingEnabled- ? await tx`SELECT current_setting('app.scopes', true) AS scopes` : [];- if (this.rlsScopeBindingEnabled) await tx`SELECT set_config('app.scopes', ${scopesValue}, true)`;- const result = opts?.jitOff ? await withSearchJitOff(tx, this._pageTransaction, () => callback(tx)) : await callback(tx);- // Successful RELEASE SAVEPOINT retains SET LOCAL; a failed callback- // rolls it back with the savepoint and must preserve its original error.- if (this.rlsScopeBindingEnabled) await tx`SELECT set_config('app.scopes', ${previous[0]?.scopes ?? ''}, true)`;- return result;+ // One settings statement for the scope binding, JIT off and the+ // caller's settings (a thunk is read here, after BEGIN, so a deadline+ // budget is measured one round trip before the query). A savepoint in+ // a caller's transaction restores the caller's values afterwards; a+ // failed callback rolls them back with the savepoint and keeps its+ // original error (postgres-engine/search-settings.ts).+ const settings = {+ ...(this.rlsScopeBindingEnabled ? { 'app.scopes': scopesValue } : {}),+ ...(opts?.jitOff ? SEARCH_JIT_OFF : {}),+ ...(typeof opts?.settings === 'function' ? opts.settings() : opts?.settings),+ };+ return withSearchSettings(tx, this._pageTransaction, settings, () => callback(tx), VECTOR_SETTING_DEFAULTS);});}@@ -1132,22 +1136,17 @@ export class PostgresEngine implements BrainEngine {// RLS scope binding (opt-in via GBRAIN_RLS_SCOPE_BINDING) + search-only// timeout. alwaysTransaction: this method needed sql.begin() on master- // already (SET LOCAL statement_timeout must be transaction-scoped so- // the GUC can never leak onto a pooled connection). Flag off → the- // wrap is identical to master's; flag on → set_config('app.scopes')- // shares the same transaction as the timeout.+ // already (a transaction-local statement_timeout can never leak onto a+ // pooled connection). The scope, JIT off, the timeout and the relaxed+ // attempt's enable_seqscan are one settings statement+ // (postgres-engine/search-settings.ts).const statementTimeout = await this.keywordStatementTimeoutSetting();const runKeyword = (queryText: string, relaxed = false) =>- this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {- await tx`SELECT set_config('statement_timeout', ${statementTimeout}, true)`;- const previous = relaxed ? await tx`SHOW enable_seqscan` : [];- if (relaxed) await tx`SET LOCAL enable_seqscan = off`;+ this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, (tx) => {const boundParams = [...params];boundParams[0] = collapseWebsearchDashRuns(queryText);- const rows = await tx.unsafe(rawQuery, boundParams as Parameters<typeof tx.unsafe>[1]);- if (relaxed) await tx`SELECT set_config('enable_seqscan', ${previous[0].enable_seqscan}, true)`;- return rows;- }, { alwaysTransaction: true, jitOff: true });+ return tx.unsafe(rawQuery, boundParams as Parameters<typeof tx.unsafe>[1]);+ }, { alwaysTransaction: true, jitOff: true, settings: relaxed ? { statement_timeout: statementTimeout, enable_seqscan: 'off' } : { statement_timeout: statementTimeout } });let rows = await runKeyword(query);// D2 fix (fix/title-retrieval-arm): websearch AND semantics at chunk// grain mean one non-co-occurring token zeroes keyword recall. When the@@ -1179,15 +1178,15 @@ export class PostgresEngine implements BrainEngine {*//** Cat 40 Hard F2 strict keyword count and keyword-mode pages; SQL in engine-sql/keyword-pages.ts. */async countKeywordPages(query: string, opts?: SearchOpts & { timeoutMs?: number }): Promise<number> {- return keywordPagesImpl.countKeywordPages((read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true }), query, opts, { statementTimeout: await this.keywordStatementTimeoutSetting(), timeoutMs: opts?.timeoutMs });+ return keywordPagesImpl.countKeywordPages((read, settings) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true, settings }), query, opts, { statementTimeout: await this.keywordStatementTimeoutSetting(), timeoutMs: opts?.timeoutMs });}async searchKeywordPages(query: string, opts: SearchOpts | undefined, page: KeywordPageWindow): Promise<SearchResult[]> {- return keywordPagesImpl.searchKeywordPages((read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true }), query, opts, page, { statementTimeout: await this.keywordStatementTimeoutSetting() });+ return keywordPagesImpl.searchKeywordPages((read, settings) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true, settings }), query, opts, page, { statementTimeout: await this.keywordStatementTimeoutSetting() });}async searchTitles(query: string, opts?: SearchOpts): Promise<SearchResult[]> {return titlesImpl.searchTitles(- (read) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true }),+ (read, settings) => this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => read(scopedRead(this.engineSqlOn(tx))), { alwaysTransaction: true, jitOff: true, settings }),query,opts,{ statementTimeout: await this.keywordStatementTimeoutSetting(), relaxedPrefersIndex: true, staleProbe: false },@@ -1331,13 +1330,12 @@ export class PostgresEngine implements BrainEngine {`;// RLS scope binding + search-only timeout. alwaysTransaction: master- // already wrapped this in sql.begin() for the SET LOCAL; flag off is- // identical to that wrap, flag on adds set_config in the same tx.+ // already wrapped this in sql.begin() for the transaction-local timeout;+ // scope, JIT off and the timeout are one settings statement.const statementTimeout = await this.keywordStatementTimeoutSetting();- const rows = await this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async (tx) => {- await tx`SELECT set_config('statement_timeout', ${statementTimeout}, true)`;- return await tx.unsafe(rawQuery, params as Parameters<typeof tx.unsafe>[1]);- }, { alwaysTransaction: true, jitOff: true });+ const rows = await this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId,+ tx => tx.unsafe(rawQuery, params as Parameters<typeof tx.unsafe>[1]),+ { alwaysTransaction: true, jitOff: true, settings: { statement_timeout: statementTimeout } });return rows.map(rowToSearchResult);}@@ -1352,12 +1350,11 @@ export class PostgresEngine implements BrainEngine {return searchKeywordCJKImpl(async (read) =>await this.withScopedReadTransaction(ctx.opts?.sourceIds, ctx.opts?.sourceId, async (tx) => {- await tx`SELECT set_config('statement_timeout', ${statementTimeout}, true)`;return await read(scopedRead(postgresExecutor(tx, {runUnsafe: (conn, sql, params, opts) => this.runUnsafe(conn, sql, params, opts),gauge: this.checkoutGauge,})));- }, { alwaysTransaction: true, jitOff: true }),+ }, { alwaysTransaction: true, jitOff: true, settings: { statement_timeout: statementTimeout } }),query,ctx,);@@ -1385,12 +1382,9 @@ export class PostgresEngine implements BrainEngine {async (pool, remainingMs) => {const deadline = performance.now() + remainingMs;return this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async tx => {- const previous = await tx`SHOW statement_timeout`;- await tx.unsafe(SET_STATEMENT_TIMEOUT_SQL, [String(remainingVectorBudget(deadline))]);const rows = await tx.unsafe(stmt.hasMoreSql, [...stmt.params.slice(0, stmt.innerLimitIdx), pool + 1] as Parameters<typeof tx.unsafe>[1]);- await tx.unsafe(SET_STATEMENT_TIMEOUT_SQL, [previous[0].statement_timeout]);return Number(rows[0].eligible) > pool;- }, { alwaysTransaction: true, jitOff: true });+ }, { alwaysTransaction: true, jitOff: true, settings: () => ({ statement_timeout: String(remainingVectorBudget(deadline)) }) });},opts?.onVectorPoolMeta,);@@ -1437,15 +1431,12 @@ export class PostgresEngine implements BrainEngine {run: (tx: ReturnType<typeof postgres>, sql: string, bound: Parameters<ReturnType<typeof postgres>['unsafe']>[1]) => Promise<Record<string, unknown>[]>,): Promise<Record<string, unknown>[]> {const deadline = performance.now() + remainingMs;- return this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, async tx => {- const walk = indexWalk && stmt.indexWalkSql;- return withVectorSettings((sql, values) => tx.unsafe(sql, values as Parameters<typeof tx.unsafe>[1]), iterative, innerLimit, maxScanTuples, async () => {- const bound = [...stmt.params];- bound[stmt.innerLimitIdx] = exact ? null : innerLimit;- await tx.unsafe(SET_STATEMENT_TIMEOUT_SQL, [String(remainingVectorBudget(deadline))]);- return run(tx, (scopeScan && stmt.scopeScanSql) || walk || (exact ? stmt.exactSql : stmt.sql), bound as Parameters<typeof tx.unsafe>[1]);- }, deadline, opts?.hnswIterativeScan, walk ? stmt.indexWalkOverfetch : undefined);- }, { alwaysTransaction: true, jitOff: true });+ const walk = indexWalk && stmt.indexWalkSql;+ return this.withScopedReadTransaction(opts?.sourceIds, opts?.sourceId, tx => {+ const bound = [...stmt.params];+ bound[stmt.innerLimitIdx] = exact ? null : innerLimit;+ return run(tx, (scopeScan && stmt.scopeScanSql) || walk || (exact ? stmt.exactSql : stmt.sql), bound as Parameters<typeof tx.unsafe>[1]);+ }, { alwaysTransaction: true, jitOff: true, settings: () => vectorScanSettings(iterative, innerLimit, maxScanTuples, deadline, opts?.hnswIterativeScan, walk ? stmt.indexWalkOverfetch : undefined) });}async getEmbeddingsByChunkIds(ids: number[], column: string = 'embedding'): Promise<Map<number, Float32Array>> {diff --git a/src/core/postgres-engine/search-settings.ts b/src/core/postgres-engine/search-settings.tsindex 5f9b50a319..3fed4d2e06 100644--- a/src/core/postgres-engine/search-settings.ts+++ b/src/core/postgres-engine/search-settings.ts@@ -1,5 +1,5 @@/**- * Session settings for the Postgres search statements (#6039).+ * Transaction-local settings for the Postgres search reads (#6039, #6721).** JIT off. The search statements (keyword, keyword chunks, CJK, title,* vector candidates and the vector `hasMore` witness) are short interactive@@ -12,20 +12,81 @@* candidate statement 990 of 1,394 ms. JIT never pays back on a statement* that executes in milliseconds.*- * `SET LOCAL` ends with a top-level transaction. Inside a caller's- * transaction the search runs in a savepoint, and a released savepoint keeps- * the setting, so the caller's value is restored afterwards; a failed search- * rolls the savepoint back, which reverts it too.+ * One statement (#6721). Every setting a search transaction needs (`jit`,+ * the RLS `app.scopes`, `statement_timeout`, the relaxed arms'+ * `enable_seqscan`, the vector scan settings) is applied by a single+ * `SELECT set_config(...), set_config(...)`: each separate statement was a+ * round trip in series with the query, about 30 ms each to a remote pooler.+ * At the top level nothing is read first or restored after: `set_config(...,+ * true)` ends with the transaction. Inside a caller's transaction the read+ * runs in a savepoint, and a released savepoint keeps the settings, so one+ * statement reads the caller's values first and one restores them after; a+ * failed read rolls the savepoint back, which reverts them too.*- * Postgres only: PGLite has no JIT provider, so its engine never calls this.+ * Each setting name is a literal in the statement and each value a bound+ * parameter, so the vendored driver reads a `statement_timeout` change from+ * the text and budgets the next statement by it (#6543).+ *+ * Postgres only: PGLite has no JIT provider, no RLS binding and no+ * statement timeout, so its engine never calls this.*/import type postgres from '#postgres';-// engine-sql-ok: jit is a Postgres server setting; PGLite has no JIT provider-export async function withSearchJitOff<T>(tx: ReturnType<typeof postgres>, nested: boolean, run: () => Promise<T>): Promise<T> {- const previous = nested ? await tx`SELECT current_setting('jit') AS jit` : [];- await tx`SET LOCAL jit = off`;+/** Setting name to transaction-local value. */+export type SearchSettings = Readonly<Record<string, string>>;++export const SEARCH_JIT_OFF: SearchSettings = { jit: 'off' };++const SETTING_NAME = /^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)?$/;++function names(settings: SearchSettings): string[] {+ const keys = Object.keys(settings);+ for (const name of keys) if (!SETTING_NAME.test(name)) throw new Error(`search setting name not allowed: ${name}`);+ return keys;+}++/** `SELECT set_config('<name>', $1, true), …`: one statement for every setting, values bound. */+export function searchSettingsStatement(settings: SearchSettings): { sql: string; params: string[] } {+ const keys = names(settings);+ return {+ sql: `SELECT ${keys.map((name, i) => `set_config('${name}', $${i + 1}, true)`).join(', ')}`,+ params: keys.map(name => settings[name]!),+ };+}++/** `SELECT current_setting('<name>', true) AS "<name>", …`: the caller's values, one row. */+function currentSettingsStatement(keys: string[]): string {+ return `SELECT ${keys.map(name => `current_setting('${name}', true) AS "${name}"`).join(', ')}`;+}++/**+ * Apply `settings` for `run` on the search transaction `tx`. `nested`: `tx`+ * is a savepoint in a caller's transaction, whose values are restored after+ * `run`; a value the caller never set restores to `fallback[name]`+ * (an extension setting not yet loaded reads as NULL), else ''.+ */+// engine-sql-ok: jit, statement_timeout, enable_seqscan and the hnsw settings are Postgres server settings+export async function withSearchSettings<T>(+ tx: ReturnType<typeof postgres>,+ nested: boolean,+ settings: SearchSettings,+ run: () => Promise<T>,+ fallback: SearchSettings = {},+): Promise<T> {+ const keys = names(settings);+ if (keys.length === 0) return run();+ const previous = nested ? (await tx.unsafe(currentSettingsStatement(keys)))[0] as Record<string, string | null> : undefined;+ const set = searchSettingsStatement(settings);+ await tx.unsafe(set.sql, set.params);const result = await run();- if (nested) await tx`SELECT set_config('jit', ${previous[0]!.jit}, true)`;+ if (previous) {+ const restore = searchSettingsStatement(Object.fromEntries(keys.map(name => [name, previous[name] ?? fallback[name] ?? ''])));+ await tx.unsafe(restore.sql, restore.params);+ }return result;}++/** JIT off for `run` alone (the unscoped jit-off reads). */+export function withSearchJitOff<T>(tx: ReturnType<typeof postgres>, nested: boolean, run: () => Promise<T>): Promise<T> {+ return withSearchSettings(tx, nested, SEARCH_JIT_OFF, run);+}diff --git a/src/core/search/vector-settings.ts b/src/core/search/vector-settings.tsindex 967d1254f3..14892f93a3 100644--- a/src/core/search/vector-settings.ts+++ b/src/core/search/vector-settings.ts@@ -10,30 +10,51 @@ import { INDEX_WALK_SETTINGS } from './vector-statement.ts';* an iterative one past it orders less exactly (recall@50 0.96 against 0.995).*/-export async function withVectorSettings<T>(- query: (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>,+/** What each scan setting reads as when nothing set it (pgvector's defaults; NULL before the extension loads). */+export const VECTOR_SETTING_DEFAULTS: Readonly<Record<string, string>> = { 'hnsw.ef_search': String(HNSW_EF_SEARCH_DEFAULT), 'hnsw.iterative_scan': 'off', 'hnsw.max_scan_tuples': '20000' };++/** The transaction-local scan settings for one vector attempt; `statement_timeout` is what remains of `deadline`, read now. */+export function vectorScanSettings(iterative: boolean,candidateLimit: number,maxScanTuples: number,- run: () => Promise<T>,deadline?: number,iterativeMode: HnswIterativeScanMode = HNSW_ITERATIVE_SCAN_DEFAULT,walkOverfetch?: number,-): Promise<T> {+): Record<string, string> {const window = walkOverfetch ? candidateLimit * walkOverfetch : candidateLimit;const settings: Record<string, string> = { 'hnsw.ef_search': String(hnswEfSearchFor(window)), ...(walkOverfetch ? INDEX_WALK_SETTINGS : {}) };- const defaults: Record<string, string> = { 'hnsw.ef_search': String(HNSW_EF_SEARCH_DEFAULT), 'hnsw.iterative_scan': 'off', 'hnsw.max_scan_tuples': '20000' };if (iterative) {settings['hnsw.iterative_scan'] = iterativeMode;settings['hnsw.max_scan_tuples'] = String(maxScanTuples);}if (deadline !== undefined) settings.statement_timeout = String(remainingVectorBudget(deadline));+ return settings;+}++/**+ * Read, set and restore the scan settings around `run` through `query`+ * (PGLite and the fact-relevance read). Postgres search attempts set them in+ * their transaction's one settings statement instead+ * (postgres-engine/search-settings.ts).+ */+export async function withVectorSettings<T>(+ query: (sql: string, params: unknown[]) => Promise<Record<string, unknown>[]>,+ iterative: boolean,+ candidateLimit: number,+ maxScanTuples: number,+ run: () => Promise<T>,+ deadline?: number,+ iterativeMode: HnswIterativeScanMode = HNSW_ITERATIVE_SCAN_DEFAULT,+ walkOverfetch?: number,+): Promise<T> {+ const settings = vectorScanSettings(iterative, candidateLimit, maxScanTuples, deadline, iterativeMode, walkOverfetch);const names = Object.keys(settings);const previous = await query(`SELECT name, current_setting(name, true) AS value FROM unnest($1::text[]) AS settings(name)`, [names]);const setSql = `SELECT set_config(name, value, true) FROM unnest($1::text[], $2::text[]) AS settings(name, value)`;if (deadline !== undefined) settings.statement_timeout = String(remainingVectorBudget(deadline));await query(setSql, [names, names.map(name => settings[name])]);const result = await run();- await query(setSql, [previous.map(row => row.name), previous.map(row => row.value ?? defaults[String(row.name)])]);+ await query(setSql, [previous.map(row => row.name), previous.map(row => row.value ?? VECTOR_SETTING_DEFAULTS[String(row.name)])]);return result;}diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.tsindex 2d63dca342..1edba7f7aa 100644--- a/src/core/search/vector-statement.ts+++ b/src/core/search/vector-statement.ts@@ -66,7 +66,6 @@ import { buildBestPerPagePoolCte, buildHardExcludeClause, buildSourceFactorCase,import { chunkGenerationProbe } from './safe-chunks.ts';export const VECTOR_EXTENSION_VERSION_SQL = `SELECT extversion FROM pg_extension WHERE extname = 'vector'`;-export const SET_STATEMENT_TIMEOUT_SQL = `SELECT set_config('statement_timeout', $1, true)`;export interface VectorSearchStatementInput {dialect: 'postgres' | 'pglite';diff --git a/test/e2e/search-query-contract-postgres.test.ts b/test/e2e/search-query-contract-postgres.test.tsindex b0f092dc59..12d1a11aca 100644--- a/test/e2e/search-query-contract-postgres.test.ts+++ b/test/e2e/search-query-contract-postgres.test.ts@@ -27,6 +27,20 @@ import { withEnv } from '../helpers/with-env.ts';expect(await engine.executeRaw(`SHOW enable_seqscan`)).toEqual(before);});+ test("search reads inside a caller's transaction restore every setting they change (#6721)", async () => {+ // Each read sets its settings in one statement; nested, it reads the caller's values first and restores them.+ // A nested keyword, title or count read used to leave its own statement_timeout on the caller's transaction.+ const after = await engine.transaction(async tx => {+ await tx.executeRaw(`SELECT set_config('jit', 'on', true), set_config('statement_timeout', '45s', true), set_config('enable_seqscan', 'on', true)`);+ expect((await tx.searchKeyword('ordertoken impossibleterm', { sourceId: 'query-order', orFallback: true })).length).toBeGreaterThan(0);+ await tx.searchTitles('ordertoken impossibleterm', { sourceId: 'query-order' });+ await tx.countKeywordPages('ordertoken', { sourceId: 'query-order' });+ await tx.searchVector(vector, { sourceId: 'query-order', limit: 3 });+ return tx.executeRaw(`SELECT current_setting('jit') AS jit, current_setting('statement_timeout') AS timeout, current_setting('enable_seqscan') AS seqscan`);+ });+ expect(after).toEqual([{ jit: 'on', timeout: '45s', seqscan: 'on' }]);+ });+test('restricted runtime roles retain RLS and local settings through relaxed retries', async () => {await engine.executeRaw('CREATE ROLE query_contract_reader NOLOGIN');const tables = ['pages', 'content_chunks', 'sources'];diff --git a/test/keyword-statement-timeout-knob-6495.test.ts b/test/keyword-statement-timeout-knob-6495.test.tsindex 6cc3a57580..36842f601c 100644--- a/test/keyword-statement-timeout-knob-6495.test.ts+++ b/test/keyword-statement-timeout-knob-6495.test.ts@@ -33,10 +33,15 @@ import {keywordStatementTimeoutValueProblem,resolveKeywordStatementTimeoutMs,} from '../src/core/postgres-engine/keyword-statement-timeout.ts';+import { searchSettingsStatement, type SearchSettings } from '../src/core/postgres-engine/search-settings.ts';import { installFixtureChunks } from './helpers/page-projection.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';+const { default: Connection } = await import(new URL('../vendor/postgres/src/connection.js', import.meta.url).href) as {+ default: { statementTimeoutChanges: (text: string, parameters?: unknown[]) => Array<{ kind: string; ms?: number }> };+};+interface Recorded { sql: string; params: unknown[] }/** The six engine entry points that bind the keyword statement timeout. */@@ -63,14 +68,19 @@ async function recordingEngine(opts: { dbValue?: string | null; fileValue?: unkn{ unsafe: async (sql: string, params?: unknown[]) => { recorded.push({ sql, params: params ?? [] }); return rows(sql); } },);const priv = engine as unknown as {- withScopedReadTransaction: (ids: unknown, id: unknown, cb: (tx: unknown) => Promise<unknown>) => Promise<unknown>;+ withScopedReadTransaction: (ids: unknown, id: unknown, cb: (tx: unknown) => Promise<unknown>, opts?: { settings?: SearchSettings | (() => SearchSettings) }) => Promise<unknown>;getConfig: (key: string) => Promise<string | null>;executeRaw: (sql: string, params?: unknown[]) => Promise<unknown[]>;_savedConfig: { keyword_statement_timeout_ms?: unknown } | undefined;_pageTransaction: boolean;};let configReads = 0;- priv.withScopedReadTransaction = (_ids, _id, cb) => cb(tx);+ // The transaction's one settings statement, as withScopedReadTransaction sends it (postgres-engine/search-settings.ts).+ priv.withScopedReadTransaction = async (_ids, _id, cb, txOpts) => {+ const settings = typeof txOpts?.settings === 'function' ? txOpts.settings() : txOpts?.settings;+ if (settings) { const set = searchSettingsStatement(settings); await tx.unsafe(set.sql, set.params); }+ return cb(tx);+ };priv.getConfig = async key => { configReads++; return key === KEYWORD_STATEMENT_TIMEOUT_KEY ? opts.dbValue ?? null : null; };priv.executeRaw = async (sql, params) => {if (opts.connected === false) throw new Error('No database connection');@@ -84,15 +94,10 @@ async function recordingEngine(opts: { dbValue?: string | null; fileValue?: unknreturn { engine, recorded, configReads: () => configReads };}-/** Every statement timeout a recording set: the `set_config('statement_timeout', $1, true)` argument or a `SET LOCAL` literal. */+/** Every statement timeout a recording set, as the vendored driver reads it from the statement it sends (#6543). */function timeoutsSet(recorded: Recorded[]): string[] {- const out: string[] = [];- for (const { sql, params } of recorded) {- if (/set_config\('statement_timeout'/.test(sql)) out.push(String(params[0]));- const literal = /SET LOCAL statement_timeout\s*=\s*'([^']+)'/.exec(sql);- if (literal) out.push(literal[1]);- }- return out;+ return recorded.flatMap(({ sql, params }) => Connection.statementTimeoutChanges(sql, params)+ .map(change => (change.kind === 'set' ? `${change.ms}ms` : `unreadable ${change.kind}`)));}async function timeoutFor(site: string, opts: { dbValue?: string | null; fileValue?: unknown }, countTimeoutMs?: number): Promise<string[]> {diff --git a/test/postgres-engine-rls-scope.test.ts b/test/postgres-engine-rls-scope.test.tsindex 1dc028c388..7c0bfd67a0 100644--- a/test/postgres-engine-rls-scope.test.ts+++ b/test/postgres-engine-rls-scope.test.ts@@ -11,6 +11,9 @@* - flag ON: sql.begin() + SELECT set_config('app.scopes', $1, true)* with federated-array > scalar > '*' precedence, and the CSV value* carried as a BOUND PARAMETER, never interpolated into the SQL text.+ * At the top level that one statement is all (the setting ends with the+ * transaction); inside a caller's transaction the caller's scope is read+ * first and restored after (postgres-engine/search-settings.ts).*/import { describe, test, expect } from 'bun:test';@@ -22,21 +25,25 @@ type Recorded = { text: string; params: unknown[]; lane: 'pool' | 'transaction'function makeFakeSql() {const queries: Recorded[] = [];let beginCalls = 0; let savepointCalls = 0; let scopes = 'outside';- const record = (lane: Recorded['lane'], strings: TemplateStringsArray, ...params: unknown[]) => {- // Join the literal segments with a placeholder marker so the test can- // assert the exact SQL text shape around each bound parameter.- const text = strings.join('${}'); queries.push({ text, params, lane });- if (text.includes('current_setting')) return Promise.resolve([{ scopes }]);- if (text.includes('set_config')) scopes = String(params[0]);+ // Tagged templates join their literal segments with a placeholder marker+ // so the test can assert the exact SQL text around each bound parameter;+ // `unsafe` statements keep their $n text.+ const record = (lane: Recorded['lane'], text: string, params: unknown[]) => {+ queries.push({ text, params, lane });+ if (text.includes("current_setting('app.scopes'")) return Promise.resolve([{ 'app.scopes': scopes }]);+ const bound = /set_config\('app\.scopes', \$(\d+)/.exec(text);+ if (bound) scopes = String(params[Number(bound[1]) - 1]);return Promise.resolve([]);};- const sql = ((strings: TemplateStringsArray, ...params: unknown[]) =>- record('pool', strings, ...params)) as unknown as Record<string, unknown> & {+ const handle = (lane: Recorded['lane']) => Object.assign(+ (strings: TemplateStringsArray, ...params: unknown[]) => record(lane, strings.join('${}'), params),+ { unsafe: (text: string, params: unknown[] = []) => record(lane, text, params) },+ );+ const sql = handle('pool') as unknown as Record<string, unknown> & {(strings: TemplateStringsArray, ...params: unknown[]): Promise<unknown[]>;begin: (cb: (tx: unknown) => Promise<unknown>) => Promise<unknown>;};- const tx = ((strings: TemplateStringsArray, ...params: unknown[]) =>- record('transaction', strings, ...params)) as unknown as Record<string, unknown>;+ const tx = handle('transaction') as unknown as Record<string, unknown>;tx.savepoint = async (cb: (tx: unknown) => Promise<unknown>) => {savepointCalls++; const prior = scopes;try { return await cb(tx); } catch (error) { scopes = prior; throw error; }@@ -54,10 +61,12 @@ interface ScopedEngine {withScopedReadTransaction<T>(sourceIds: string[] | undefined, sourceId: string | undefined,cb: (tx: unknown) => Promise<T>, opts?: { alwaysTransaction?: boolean }): Promise<T>;}-function makeEngine(fake: ReturnType<typeof makeFakeSql>): ScopedEngine {+function makeEngine(fake: ReturnType<typeof makeFakeSql>, inTransaction = false): ScopedEngine {const e = new PostgresEngine();(e as unknown as { _sql: unknown })._sql = fake.sql;(e as unknown as { _connectionStyle: string })._connectionStyle = 'instance';+ // An engine over a transaction handle is a page transaction, as transaction() builds it.+ if (inTransaction) Object.defineProperty(e, '_pageTransaction', { value: true });// private method, invoked directly for the pinreturn e as unknown as ScopedEngine;}@@ -128,12 +137,13 @@ describe('withScopedReadTransaction / flag on', () => {});expect(fake.beginCalls()).toBe(1);const sc = setConfigQueries(fake.queries);- expect(sc).toHaveLength(2);+ // Top level: one settings statement, nothing read first or restored after.+ expect(sc).toHaveLength(1);expect(sc[0].params).toEqual(['src-a']);- expect(sc[1].params).toEqual(['outside']);+ expect(fake.queries).toHaveLength(1);// set_config was emitted before the callback ran- expect(queriesAtCallback).toBe(2);- expect(fake.queries[1]).toBe(sc[0]);+ expect(queriesAtCallback).toBe(1);+ expect(fake.queries[0]).toBe(sc[0]);});});@@ -142,7 +152,7 @@ describe('withScopedReadTransaction / flag on', () => {const fake = makeFakeSql();const engine = makeEngine(fake);await engine.withScopedReadTransaction(undefined, 'src-a', async () => null);- expect(setConfigQueries(fake.queries)).toHaveLength(2);+ expect(setConfigQueries(fake.queries)).toHaveLength(1);});});@@ -181,7 +191,7 @@ describe('withScopedReadTransaction / flag on', () => {await engine.withScopedReadTransaction(undefined, hostile, async () => null);const sc = setConfigQueries(fake.queries)[0];// Exact literal-segment shape: the value slot is the tagged-template hole.- expect(sc.text).toBe("SELECT set_config('app.scopes', ${}, true)");+ expect(sc.text).toBe("SELECT set_config('app.scopes', $1, true)");expect(sc.params).toEqual([hostile]);expect(sc.text).not.toContain(hostile);});@@ -193,7 +203,7 @@ describe('withScopedReadTransaction / flag on', () => {await engine.transaction(async outer => {await outer.withScopedReadTransaction(undefined, 'parent', async tx => {// Nested work uses the scoped handle, never its waiting parent.- const nested = makeEngine({ ...fake, sql: tx as typeof fake.sql });+ const nested = makeEngine({ ...fake, sql: tx as typeof fake.sql }, true);expect(fake.scopes()).toBe('parent');await nested.withScopedReadTransaction(undefined, 'child', async () => { expect(fake.scopes()).toBe('child'); });expect(fake.scopes()).toBe('parent');@@ -205,6 +215,9 @@ describe('withScopedReadTransaction / flag on', () => {});expect(fake.beginCalls()).toBe(1); expect(fake.savepointCalls()).toBe(3);expect(fake.queries.every(query => query.lane === 'transaction')).toBe(true);+ // Each savepoint reads the caller's scope, sets its own, and restores the caller's on success.+ expect(fake.queries.map(query => query.text.startsWith('SELECT current_setting') ? 'read' : query.params[0])).toEqual(+ ['read', 'parent', 'read', 'child', 'parent', 'read', 'failing-child', 'outside']);});});});diff --git a/test/postgres-engine.test.ts b/test/postgres-engine.test.tsindex ce2e24f437..a1fd3d9a2f 100644--- a/test/postgres-engine.test.ts+++ b/test/postgres-engine.test.ts@@ -71,20 +71,20 @@ describe('postgres-engine / search path timeout isolation', () => {const helper = stripComments(SRC).split('private async withScopedReadTransaction<T>')[1]!.split('async connect(')[0]!;expect(helper).toMatch(/this\.transaction\(async engine =>/);expect(helper).toMatch(/const tx = \(engine as PostgresEngine\)\.sql;/);- expect(helper).toMatch(/await callback\(tx\)/);+ // One settings statement (scope, JIT off, the caller's settings) runs before the callback; nested reads restore.+ expect(helper).toMatch(/withSearchSettings\(tx, this\._pageTransaction, settings, \(\) => callback\(tx\), VECTOR_SETTING_DEFAULTS\)/);// Flag off without a transaction requirement preserves pool passthrough.expect(helper).toMatch(/if\s*\(!this\.rlsScopeBindingEnabled\s*&&\s*!opts\?\.alwaysTransaction\)\s*\{\s*return\s+await\s+callback\(this\.sql\);/,);});- test('both search methods use SET LOCAL for the timeout', () => {- const keyword = extractMethod(SRC, 'searchKeyword');+ test('both search methods bind a transaction-local timeout through the transaction settings', () => {+ const keyword = stripComments(extractMethod(SRC, 'searchKeyword'));const attempt = stripComments(SRC).split('private runVectorAttempt(')[1]!.split('async getEmbeddingsByChunkIds(')[0]!;- expect(keyword).toMatch(/SET\s+LOCAL\s+statement_timeout/);- expect(VECTOR_STATEMENT_SRC).toContain("export const SET_STATEMENT_TIMEOUT_SQL = `SELECT set_config('statement_timeout', $1, true)`;");- expect(attempt).toMatch(/tx\.unsafe\(SET_STATEMENT_TIMEOUT_SQL, \[String\(remainingVectorBudget\(deadline\)\)\]\)/);- expect(attempt).toContain('withVectorSettings');+ expect(keyword).toMatch(/settings: relaxed \? \{ statement_timeout: statementTimeout, enable_seqscan: 'off' \} : \{ statement_timeout: statementTimeout \}/);+ // A thunk: the deadline's remaining budget is read after BEGIN, one round trip before the query.+ expect(attempt).toMatch(/settings: \(\) => vectorScanSettings\(iterative, innerLimit, maxScanTuples, deadline,/);});test('connect() with poolSize honors resolvePrepare (PgBouncer regression guard)', () => {diff --git a/test/postgres-rls-scope-inventory.test.ts b/test/postgres-rls-scope-inventory.test.tsindex 69b7a1afb1..557b815609 100644--- a/test/postgres-rls-scope-inventory.test.ts+++ b/test/postgres-rls-scope-inventory.test.ts@@ -98,6 +98,28 @@ function lanesOf(trace: Awaited<ReturnType<typeof runCase>>['trace']): string[]return [...new Set(trace.filter((t): t is RecordedStatement => t.kind === 'query').map((t) => t.lane))].sort();}+/**+ * The scope statements that enter a scoped read, in order. A top-level read+ * sets the scope once (it ends with the transaction); a read nested in a+ * caller's transaction reads the caller's scope, sets its own, and restores+ * the caller's after (postgres-engine/search-settings.ts), so a set that+ * follows an entered nested read is its restore.+ */+function scopesEntered(trace: Awaited<ReturnType<typeof runCase>>['trace']): RecordedStatement[] {+ const nested: Array<'read' | 'entered'> = [];+ const entered: RecordedStatement[] = [];+ for (const t of trace) {+ if (t.kind !== 'query') continue;+ if (t.text.startsWith("SELECT current_setting('app.scopes'")) nested.push('read');+ else if (t.text.startsWith("SELECT set_config('app.scopes'")) {+ if (nested.at(-1) === 'entered') { nested.pop(); continue; }+ if (nested.at(-1) === 'read') nested[nested.length - 1] = 'entered';+ entered.push(t);+ }+ }+ return entered;+}+async function observe(cases: SqlCase[]): Promise<Record<string, RuntimeObservation>> {const out: Record<string, RuntimeObservation> = {};const on = await withPinnedSqlEnvironment('1', async () => Promise.all(cases.map(runCase)));@@ -105,7 +127,7 @@ async function observe(cases: SqlCase[]): Promise<Record<string, RuntimeObservatcases.forEach((c, i) => {const onTrace = on[i].trace;const sets = onTrace.filter((t): t is RecordedStatement => t.kind === 'query' && t.text.startsWith("SELECT set_config('app.scopes'"));- const entered = sets.filter((_, k) => k % 2 === 0);+ const entered = scopesEntered(onTrace);if (on[i].error || off[i].error) throw new Error(`${c.method}#${c.variant}: ${on[i].error ?? off[i].error}`);out[`${c.method}#${c.variant}`] = {flagOn: sets.length > 0 ? 'scoped' : 'unscoped',diff --git a/test/search-settings-one-statement.test.ts b/test/search-settings-one-statement.test.tsnew file mode 100644index 0000000000..8764b21889--- /dev/null+++ b/test/search-settings-one-statement.test.ts@@ -0,0 +1,133 @@+/**+ * #6721: a Postgres search transaction applies every setting it needs in one+ * statement. Each separate settings statement (`SET LOCAL jit = off`, the+ * `statement_timeout` set_config, the relaxed arms' `SHOW enable_seqscan` /+ * set / restore, the vector settings' read / set / restore) was a round trip+ * in series with the query, about 30 ms each to a remote pooler.+ *+ * Contract: at the top level a search transaction sends one settings+ * statement and then its query (nothing read first, nothing restored after:+ * the settings end with the transaction); inside a caller's transaction it+ * reads the caller's values, sets its own and restores the caller's; the+ * vendored driver reads the `statement_timeout` it binds (#6543); a setting+ * name is never spliced from outside the code. Regression that fails it on+ * master: the strict keyword attempt sends three statements in its+ * transaction and the relaxed one six.+ *+ * Unit test over a recording postgres.js handle; the Postgres behavior+ * (settings in effect for the query, caller values restored) is pinned by+ * test/e2e/search-query-contract-postgres.test.ts and+ * test/e2e/jit-off-reads-postgres.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { PostgresEngine } from '../src/core/postgres-engine.ts';+import { searchSettingsStatement, withSearchSettings } from '../src/core/postgres-engine/search-settings.ts';+import { vectorScanSettings } from '../src/core/search/vector-settings.ts';++const { default: Connection } = await import(new URL('../vendor/postgres/src/connection.js', import.meta.url).href) as {+ default: { statementTimeoutChanges: (text: string, parameters?: unknown[]) => Array<{ kind: string; local?: boolean; ms?: number }> };+};++type Statement = { sql: string; params: unknown[] };++/** A transaction handle that records `unsafe` statements and answers a current_setting read with `current`. */+function recordingTx(current: Record<string, string | null> = {}) {+ const statements: Statement[] = [];+ const unsafe = async (sql: string, params: unknown[] = []) => {+ statements.push({ sql, params });+ return sql.startsWith('SELECT current_setting') ? [current] : [];+ };+ return { tx: { unsafe } as never, statements };+}++describe('withSearchSettings', () => {+ test('top level: one statement, every value bound, nothing read or restored', async () => {+ const { tx, statements } = recordingTx();+ const result = await withSearchSettings(tx, false, { jit: 'off', statement_timeout: '8000ms', enable_seqscan: 'off' }, async () => 'rows');+ expect(result).toBe('rows');+ expect(statements).toEqual([{+ sql: "SELECT set_config('jit', $1, true), set_config('statement_timeout', $2, true), set_config('enable_seqscan', $3, true)",+ params: ['off', '8000ms', 'off'],+ }]);+ // The driver budgets the next statement by the timeout this one binds (#6543).+ expect(Connection.statementTimeoutChanges(statements[0]!.sql, statements[0]!.params)).toEqual([{ kind: 'set', local: true, ms: 8000 }]);+ });++ test("nested: reads the caller's values, sets its own, restores the caller's (fallback for an unloaded extension setting)", async () => {+ const { tx, statements } = recordingTx({ jit: 'on', 'hnsw.ef_search': null });+ let during = -1;+ await withSearchSettings(tx, true, { jit: 'off', 'hnsw.ef_search': '120' }, async () => { during = statements.length; }, { 'hnsw.ef_search': '40' });+ expect(during).toBe(2);+ expect(statements).toEqual([+ { sql: `SELECT current_setting('jit', true) AS "jit", current_setting('hnsw.ef_search', true) AS "hnsw.ef_search"`, params: [] },+ { sql: "SELECT set_config('jit', $1, true), set_config('hnsw.ef_search', $2, true)", params: ['off', '120'] },+ { sql: "SELECT set_config('jit', $1, true), set_config('hnsw.ef_search', $2, true)", params: ['on', '40'] },+ ]);+ });++ test('a failed read propagates its own error and sends no restore (the savepoint rollback reverts the settings)', async () => {+ const { tx, statements } = recordingTx({ jit: 'on' });+ await expect(withSearchSettings(tx, true, { jit: 'off' }, async () => { throw new Error('read sentinel'); })).rejects.toThrow('read sentinel');+ expect(statements.map(s => s.sql.slice(0, 22))).toEqual(['SELECT current_setting', 'SELECT set_config(\'jit']);+ });++ test('no settings: no statement', async () => {+ const { tx, statements } = recordingTx();+ expect(await withSearchSettings(tx, true, {}, async () => 1)).toBe(1);+ expect(statements).toEqual([]);+ });++ test('a setting name outside [a-z0-9_.] is refused before anything is sent', async () => {+ const { tx, statements } = recordingTx();+ await expect(withSearchSettings(tx, false, { "jit', 'on', true); DROP TABLE pages; --": 'off' }, async () => 1)).rejects.toThrow('search setting name not allowed');+ expect(() => searchSettingsStatement({ 'Upper.Case': 'x' })).toThrow('search setting name not allowed');+ expect(statements).toEqual([]);+ });++ test('the vector scan settings carry the attempt deadline as a timeout the driver reads', () => {+ const settings = vectorScanSettings(true, 100, 20_000, performance.now() + 5_000);+ const { sql, params } = searchSettingsStatement({ jit: 'off', ...settings });+ const [change] = Connection.statementTimeoutChanges(sql, params);+ expect(change).toMatchObject({ kind: 'set', local: true });+ expect(change!.ms).toBeGreaterThan(4_000);+ expect(change!.ms).toBeLessThanOrEqual(5_000);+ });+});++describe('PostgresEngine.searchKeyword: statements per search transaction', () => {+ /** An engine over a fake pool whose transactions record their statements; every query returns no rows. */+ function recordingEngine() {+ const transactions: Statement[][] = [];+ const handle = (into: () => Statement[]) => Object.assign(+ async (strings: TemplateStringsArray, ...params: unknown[]) => { into().push({ sql: strings.join('$'), params }); return []; },+ { unsafe: async (sql: string, params: unknown[] = []) => { into().push({ sql, params }); return []; } },+ );+ const pool: Statement[] = [];+ const sql = Object.assign(handle(() => pool), {+ begin: async (fn: (tx: unknown) => Promise<unknown>) => {+ const statements: Statement[] = [];+ transactions.push(statements);+ return fn(Object.assign(handle(() => statements), { savepoint: (inner: (tx: unknown) => Promise<unknown>) => inner(handle(() => statements)) }));+ },+ });+ const engine = new PostgresEngine();+ const priv = engine as unknown as { _sql: unknown; _connectionStyle: string; _savedConfig: unknown; registerBeforeDisconnect: () => () => void };+ priv._sql = sql;+ priv._connectionStyle = 'instance';+ priv._savedConfig = { keyword_statement_timeout_ms: 8000 };+ priv.registerBeforeDisconnect = () => () => {};+ return { engine, transactions };+ }++ test('strict attempt: settings then query; OR fallback: the same two, with enable_seqscan off in the one settings statement', async () => {+ const { engine, transactions } = recordingEngine();+ expect(await engine.searchKeyword('alpha beta', { orFallback: true })).toEqual([]);+ expect(transactions).toHaveLength(2);+ const [strict, relaxed] = transactions.map(statements => statements.map(s => s.sql.trim().split('\n')[0]!.slice(0, 60)));+ expect(strict).toEqual(["SELECT set_config('jit', $1, true), set_config('statement_ti", 'WITH ranked_chunks AS (']);+ expect(relaxed).toEqual(["SELECT set_config('jit', $1, true), set_config('statement_ti", 'WITH ranked_chunks AS (']);+ expect(transactions[0]![0]!.params).toEqual(['off', '8000ms']);+ expect(transactions[1]![0]!.sql).toBe("SELECT set_config('jit', $1, true), set_config('statement_timeout', $2, true), set_config('enable_seqscan', $3, true)");+ expect(transactions[1]![0]!.params).toEqual(['off', '8000ms', 'off']);+ });+});