diff --git a/libs/data/postgres/src/index.ts b/libs/data/postgres/src/index.ts index 82a95bc7..de560c90 100644 --- a/libs/data/postgres/src/index.ts +++ b/libs/data/postgres/src/index.ts @@ -10,11 +10,11 @@ export { ResearchCopilotExecutorError, openResearchCopilotExecutor, type ManagedResearchCopilotExecutor, - type OpenResearchCopilotExecutorOptions, type ResearchCopilotExecutor, type ResearchCopilotExecutorConfig, + type ResearchCopilotExecutorDeps, type ResearchCopilotExecutorErrorCode, - type ResearchCopilotPoolLike, + type ResearchCopilotExecutorPool, } from './research-copilot-executor'; export type { ConnectionEvents, diff --git a/libs/data/postgres/src/research-copilot-executor.ts b/libs/data/postgres/src/research-copilot-executor.ts index 66fed43b..cd55c3b7 100644 --- a/libs/data/postgres/src/research-copilot-executor.ts +++ b/libs/data/postgres/src/research-copilot-executor.ts @@ -1,72 +1,72 @@ /** - * Managed PostgreSQL executor factory for the MCP research copilot stdio host - * (`runResearchCopilotStdioHost` in `@stock-bot/research/mcp`). + * Real PostgreSQL executor factory for the MCP research copilot stdio host. * - * - Fail-closed configuration validation before any `pg.Pool` is constructed. - * - Normalizes connection parameters and `options`/`PGOPTIONS` so every pool - * connection enforces bounded pool size (`max = 4`) and timeouts (5 s connect, - * 10 s statement, 15 s query, 2 s lock) while preserving `search_path`. - * - Runs one startup probe (`SELECT 1`), closes the pool on connect failure, - * attaches an idle-client error listener, provides idempotent shutdown, and - * never exposes credentials or raw DSNs in error messages or causes. + * Opens a bounded `pg.Pool` (`max: 4`, 5 s connect timeout, 10 s statement + * timeout, 15 s driver query timeout, 2 s lock timeout), verifies connectivity + * with a single `SELECT 1` probe, attaches an idle-client `'error'` listener, + * and returns a managed `{ executor, close }` handle structurally assignable + * to `ManagedPostgresExecutor` in `@stock-bot/research/mcp` without importing + * `@stock-bot/research` at runtime. + * + * All errors thrown by this module are {@link ResearchCopilotExecutorError} + * instances with fixed, sanitized messages and no `cause`, so connection + * strings, credentials, hostnames, and raw `pg` error text never leak. + * PostgreSQL unique-violation SQLSTATE `'23505'` is preserved on sanitized + * query errors for `createPostgresFindingWritePort` idempotent retries. */ import { Pool, type PoolConfig } from 'pg'; -/** Maximum concurrent PostgreSQL connections opened by the research copilot executor. */ +/** Maximum number of PostgreSQL connections in the copilot executor pool. */ export const RESEARCH_COPILOT_PG_POOL_MAX = 4; -/** TCP/startup connection timeout in milliseconds (5 seconds). */ +/** TCP/startup connection timeout in milliseconds. */ export const RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS = 5_000; -/** PostgreSQL server-side `statement_timeout` in milliseconds (10 seconds). */ +/** Server-side PostgreSQL `statement_timeout` in milliseconds. */ export const RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS = 10_000; -/** Client-side `pg` `query_timeout` in milliseconds (15 seconds). */ +/** Driver-side `pg` `query_timeout` in milliseconds. */ export const RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS = 15_000; -/** PostgreSQL server-side `lock_timeout` in milliseconds (2 seconds). */ +/** Server-side PostgreSQL `lock_timeout` in milliseconds. */ export const RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS = 2_000; -const POSTGRES_URL_PREFIX_RE = /^postgres(?:ql)?:\/\//i; -const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/; -const PORT_DIGITS_RE = /^\d+$/; -const FINDING_REPLAY_SQLSTATE = '23505'; +/** Typed error codes emitted by {@link ResearchCopilotExecutorError}. */ +export type ResearchCopilotExecutorErrorCode = + | 'INVALID_CONFIG' + | 'OPEN_FAILED' + | 'QUERY_FAILED' + | 'EXECUTOR_CLOSED' + | 'CLOSE_FAILED' + | '23505'; -function hasControlChar(value: string): boolean { - for (let i = 0; i < value.length; i += 1) { - const code = value.charCodeAt(i); - if (code <= 0x1f || code === 0x7f) { - return true; - } - } - return false; -} +const ERROR_MESSAGES: Readonly> = { + INVALID_CONFIG: + 'Invalid PostgreSQL configuration: expected a postgres:// or postgresql:// URL with an explicit host and database.', + OPEN_FAILED: 'Failed to open PostgreSQL executor for research copilot.', + QUERY_FAILED: 'PostgreSQL query failed in research copilot executor.', + EXECUTOR_CLOSED: 'Research copilot PostgreSQL executor is closed.', + CLOSE_FAILED: 'Failed to close PostgreSQL executor for research copilot.', + '23505': 'PostgreSQL unique constraint violation in research copilot executor.', +}; -const OVERRIDDEN_QUERY_PARAMS = new Set([ - 'options', +const STRIPPED_TIMEOUT_PARAMS: ReadonlySet = new Set([ 'statement_timeout', 'lock_timeout', 'query_timeout', - 'connectiontimeoutmillis', 'connect_timeout', - 'max', - 'min', - 'idletimeoutmillis', + 'connectiontimeoutmillis', ]); -/** Error codes thrown by {@link ResearchCopilotExecutorError}. */ -export type ResearchCopilotExecutorErrorCode = - | 'INVALID_CONFIG' - | 'CONNECT_FAILED' - | 'EXECUTOR_CLOSED' - | 'CLOSE_FAILED' - | 'QUERY_FAILED' - | 'POOL_ERROR'; +const POSTGRES_URL_PREFIX_RE = /^postgres(?:ql)?:\/\//i; +const PORT_DIGITS_RE = /^\d+$/; +const CONTROL_CHAR_RE = /[\r\n\0]/; /** - * Credential-safe error thrown by {@link openResearchCopilotExecutor} and its - * managed executor handle. Never embeds raw DSNs, passwords, or raw driver causes. + * Sanitized error thrown by {@link openResearchCopilotExecutor} and the + * managed executor it returns. Never attaches a raw `cause` or embeds DSNs, + * credentials, hostnames, or raw driver messages. */ export class ResearchCopilotExecutorError extends Error { readonly code: ResearchCopilotExecutorErrorCode; @@ -79,19 +79,24 @@ export class ResearchCopilotExecutorError extends Error { } } -/** - * Minimal structural configuration accepted by {@link openResearchCopilotExecutor}. - * Compatible with `ResearchCopilotHostConfig` from `@stock-bot/research/mcp`. - */ +/** Configuration accepted by {@link openResearchCopilotExecutor}. */ export interface ResearchCopilotExecutorConfig { readonly postgresUrl: string; - readonly postgresSchema?: string; } -/** - * Structural query executor compatible with `PostgresResearchCopilotExecutor` - * from `@stock-bot/research/mcp`. - */ +/** Minimal `pg.Pool` surface required by {@link openResearchCopilotExecutor}. */ +export interface ResearchCopilotExecutorPool { + query(text: string, values?: unknown[]): Promise<{ readonly rows: readonly unknown[] }>; + end(): Promise; + on(event: 'error', listener: (error: Error) => void): unknown; +} + +/** Optional dependency injection hooks for {@link openResearchCopilotExecutor}. */ +export interface ResearchCopilotExecutorDeps { + readonly createPool?: (poolConfig: PoolConfig) => ResearchCopilotExecutorPool; +} + +/** Structural query executor compatible with MCP research copilot PostgreSQL adapters. */ export interface ResearchCopilotExecutor { query>( text: string, @@ -99,192 +104,107 @@ export interface ResearchCopilotExecutor { ): Promise<{ readonly rows: readonly Row[] }>; } -/** - * Managed executor handle compatible with `ManagedPostgresExecutor` from - * `@stock-bot/research/mcp`. - */ +/** Managed executor handle structurally assignable to `ManagedPostgresExecutor`. */ export interface ManagedResearchCopilotExecutor { readonly executor: ResearchCopilotExecutor; close(): Promise; } -/** - * Minimal structural subset of `pg.Pool` required by {@link openResearchCopilotExecutor}, - * allowing deterministic pool injection in unit tests while accepting real `pg.Pool`. - */ -export interface ResearchCopilotPoolLike { - query( - text: string, - values?: unknown[] - ): Promise<{ readonly rows: readonly unknown[] }>; - end(): Promise; - on(event: 'error', listener: (error: Error) => void): unknown; -} - -/** Optional dependency injection and environment hooks for {@link openResearchCopilotExecutor}. */ -export interface OpenResearchCopilotExecutorOptions { - readonly createPool?: (poolConfig: PoolConfig) => ResearchCopilotPoolLike; - readonly onPoolError?: (error: Error) => void; - readonly env?: Readonly>; -} - -function extractFindingReplaySqlState(error: unknown): '23505' | undefined { - if (typeof error !== 'object' || error === null) { - return undefined; - } - const code = (error as { readonly code?: unknown }).code; - return code === FINDING_REPLAY_SQLSTATE ? FINDING_REPLAY_SQLSTATE : undefined; -} - -function getLastExactQueryParam(parsed: URL, name: string): string | undefined { - let value: string | undefined; - for (const [key, entry] of parsed.searchParams.entries()) { - if (key === name) { - value = entry; - } - } - return value; +function invalidConfigError(): ResearchCopilotExecutorError { + return new ResearchCopilotExecutorError('INVALID_CONFIG', ERROR_MESSAGES.INVALID_CONFIG); } function assertValidPort(rawPort: string): void { if (!PORT_DIGITS_RE.test(rawPort)) { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: URL port must be an integer between 1 and 65535.' - ); + throw invalidConfigError(); } const portNum = Number(rawPort); if (!Number.isInteger(portNum) || portNum < 1 || portNum > 65535) { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: URL port must be an integer between 1 and 65535.' - ); + throw invalidConfigError(); } } -function parsePostgresUrlStrict(raw: string): { readonly url: URL; readonly usedDummyHost: boolean } { - if (raw.length === 0 || raw !== raw.trim()) { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: expected a non-empty postgres:// or postgresql:// URL without surrounding whitespace.' - ); - } - if (hasControlChar(raw)) { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: URL must not contain control characters.' - ); - } - if (!POSTGRES_URL_PREFIX_RE.test(raw)) { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: URL must start with postgres:// or postgresql://.' - ); +function parseAndNormalizePoolConfig(config: ResearchCopilotExecutorConfig): PoolConfig { + if (typeof config !== 'object' || config === null || typeof config.postgresUrl !== 'string') { + throw invalidConfigError(); + } + + const rawUrl = config.postgresUrl; + if ( + rawUrl.length === 0 || + rawUrl !== rawUrl.trim() || + CONTROL_CHAR_RE.test(rawUrl) || + !POSTGRES_URL_PREFIX_RE.test(rawUrl) + ) { + throw invalidConfigError(); } - let usedDummyHost = false; let parsed: URL; try { - parsed = new URL(raw); + parsed = new URL(rawUrl); } catch { - // Support libpq Unix socket URLs with userinfo and empty authority host, - // e.g. postgres://user:pass@/research_db?host=/tmp - if (raw.includes('@/')) { - try { - parsed = new URL(raw.replace('@/', '@___DUMMY_HOST___/')); - usedDummyHost = true; - } catch { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: expected a valid postgres:// or postgresql:// URL.' - ); - } - } else { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: expected a valid postgres:// or postgresql:// URL.' - ); - } + throw invalidConfigError(); } if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: URL must use the postgres:// or postgresql:// scheme.' - ); + throw invalidConfigError(); } - return { url: parsed, usedDummyHost }; -} + const hostQueryParams = parsed.searchParams.getAll('host'); + if (hostQueryParams.length > 1) { + throw invalidConfigError(); + } + const queryHost = hostQueryParams.length === 1 ? (hostQueryParams[0] as string).trim() : ''; + if (hostQueryParams.length === 1 && queryHost.length === 0) { + throw invalidConfigError(); + } -function normalizePgOptions( - urlOptions: readonly string[], - envPgOptions: string | undefined -): string { - const parts: string[] = []; - - if (typeof envPgOptions === 'string') { - const trimmed = envPgOptions.trim(); - if (trimmed.length > 0) { - if (hasControlChar(trimmed)) { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: PGOPTIONS must not contain control characters.' - ); - } - parts.push(trimmed); + const hasAuthorityHost = parsed.hostname.length > 0; + if (hasAuthorityHost) { + let decodedHost: string; + try { + decodedHost = decodeURIComponent(parsed.hostname); + } catch { + throw invalidConfigError(); + } + if (decodedHost.trim().length === 0) { + throw invalidConfigError(); } } - for (let i = 0; i < urlOptions.length; i += 1) { - const trimmed = (urlOptions[i] as string).trim(); - if (trimmed.length > 0) { - if (hasControlChar(trimmed)) { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: URL options parameter must not contain control characters.' - ); - } - parts.push(trimmed); - } + if (!hasAuthorityHost && queryHost.length === 0) { + throw invalidConfigError(); } - parts.push( - `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS}`, - `-c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}` - ); - - return parts.join(' '); -} - -function parseAndNormalizePoolConfig( - config: ResearchCopilotExecutorConfig, - env: Readonly> -): PoolConfig { - if (typeof config !== 'object' || config === null) { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: expected a configuration object.' - ); - } - if (typeof config.postgresUrl !== 'string') { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: postgresUrl must be a non-empty string.' - ); - } - if (config.postgresSchema !== undefined) { - if (typeof config.postgresSchema !== 'string' || !SCHEMA_IDENT_RE.test(config.postgresSchema)) { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: postgresSchema must match ^[a-z_][a-z0-9_]*$.' - ); - } + if (parsed.port.length > 0) { + assertValidPort(parsed.port); } - const { url: parsed, usedDummyHost } = parsePostgresUrlStrict(config.postgresUrl); + const portQueryParams = parsed.searchParams.getAll('port'); + if (portQueryParams.length > 1) { + throw invalidConfigError(); + } + if (portQueryParams.length === 1) { + assertValidPort((portQueryParams[0] as string).trim()); + } + + if (!parsed.pathname.startsWith('/') || parsed.pathname.length <= 1) { + throw invalidConfigError(); + } + const rawDatabase = parsed.pathname.slice(1); + if (rawDatabase.includes('/')) { + throw invalidConfigError(); + } + let decodedDatabase: string; + try { + decodedDatabase = decodeURIComponent(rawDatabase); + } catch { + throw invalidConfigError(); + } + if (decodedDatabase.trim().length === 0) { + throw invalidConfigError(); + } - let decodedHostname = ''; try { if (parsed.username.length > 0) { decodeURIComponent(parsed.username); @@ -292,63 +212,21 @@ function parseAndNormalizePoolConfig( if (parsed.password.length > 0) { decodeURIComponent(parsed.password); } - if (!usedDummyHost && parsed.hostname.length > 0) { - decodedHostname = decodeURIComponent(parsed.hostname).trim(); - } } catch { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: URL contains invalid percent-encoding.' - ); + throw invalidConfigError(); } - // Match pg-connection-string precedence: query ?port=... takes precedence over authority port. - const queryPort = getLastExactQueryParam(parsed, 'port'); - const effectivePort = queryPort && queryPort.length > 0 ? queryPort : parsed.port; - if (effectivePort.length > 0) { - assertValidPort(effectivePort); - } - if (parsed.port.length > 0) { - assertValidPort(parsed.port); - } - - // Match pg-connection-string precedence: query ?host=... takes precedence over authority host. - // pg does not resolve hostaddr as a fallback host. - const queryHost = getLastExactQueryParam(parsed, 'host')?.trim() ?? ''; - const effectiveHost = queryHost.length > 0 ? queryHost : decodedHostname; - if (effectiveHost.length === 0) { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: URL must specify a host or Unix socket host parameter.' - ); - } - - // Match pg-connection-string: pg reads the database strictly from the URL pathname (never ?dbname=). - let decodedDatabase = ''; - try { - decodedDatabase = - parsed.pathname.length > 1 ? decodeURIComponent(parsed.pathname.slice(1)).trim() : ''; - } catch { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: URL database name contains invalid percent-encoding.' - ); - } - if (decodedDatabase.length === 0) { - throw new ResearchCopilotExecutorError( - 'INVALID_CONFIG', - 'Invalid PostgreSQL configuration: URL must specify a non-empty database name in the path.' - ); - } - - const urlOptions: string[] = []; + const existingOptions: string[] = []; const keysToDelete: string[] = []; for (const [key, value] of parsed.searchParams.entries()) { const lower = key.toLowerCase(); if (lower === 'options') { - urlOptions.push(value); + const trimmed = value.trim(); + if (trimmed.length > 0) { + existingOptions.push(trimmed); + } keysToDelete.push(key); - } else if (OVERRIDDEN_QUERY_PARAMS.has(lower)) { + } else if (STRIPPED_TIMEOUT_PARAMS.has(lower)) { keysToDelete.push(key); } } @@ -356,79 +234,101 @@ function parseAndNormalizePoolConfig( parsed.searchParams.delete(keysToDelete[i] as string); } - const normalizedOptions = normalizePgOptions(urlOptions, env.PGOPTIONS); - let normalizedConnectionString = parsed.toString(); - if (usedDummyHost) { - normalizedConnectionString = normalizedConnectionString.replace('@___dummy_host___/', '@/'); - normalizedConnectionString = normalizedConnectionString.replace('@___DUMMY_HOST___/', '@/'); - } + const envOptions = typeof process.env.PGOPTIONS === 'string' ? process.env.PGOPTIONS.trim() : ''; + const baseOptions = existingOptions.length > 0 ? existingOptions.join(' ') : envOptions; - return { - connectionString: normalizedConnectionString, - options: normalizedOptions, + const poolConfig: PoolConfig = { + connectionString: parsed.toString(), max: RESEARCH_COPILOT_PG_POOL_MAX, connectionTimeoutMillis: RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, statement_timeout: RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, query_timeout: RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, lock_timeout: RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, }; + + if (baseOptions.length > 0) { + poolConfig.options = `${baseOptions} -c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}`; + } + + return poolConfig; +} + +function resolveCreatePool( + deps?: ResearchCopilotExecutorDeps +): (poolConfig: PoolConfig) => ResearchCopilotExecutorPool { + if (deps === undefined) { + return poolConfig => new Pool(poolConfig); + } + if (typeof deps !== 'object' || deps === null) { + throw invalidConfigError(); + } + if (deps.createPool === undefined) { + return poolConfig => new Pool(poolConfig); + } + if (typeof deps.createPool !== 'function') { + throw invalidConfigError(); + } + return deps.createPool; +} + +function getPostgresErrorCode(error: unknown): string | undefined { + if (typeof error === 'object' && error !== null) { + const code = (error as { readonly code?: unknown }).code; + if (typeof code === 'string') { + return code; + } + } + return undefined; +} + +async function safeEndPool(pool: ResearchCopilotExecutorPool): Promise { + try { + await pool.end(); + } catch { + // Best-effort cleanup during failed startup; preserve primary OPEN_FAILED error. + } } /** - * Opens a bounded, fail-closed PostgreSQL executor backed by `pg.Pool` for the - * MCP research copilot stdio host (`ResearchCopilotStdioHostDeps['openExecutor']`). + * Opens a bounded, probed PostgreSQL executor for the MCP research copilot + * stdio host. */ export async function openResearchCopilotExecutor( config: ResearchCopilotExecutorConfig, - options?: OpenResearchCopilotExecutorOptions + deps?: ResearchCopilotExecutorDeps ): Promise { - const env = options?.env ?? process.env; - const poolConfig = parseAndNormalizePoolConfig(config, env); + const poolConfig = parseAndNormalizePoolConfig(config); + const createPool = resolveCreatePool(deps); - const createPool = - options?.createPool ?? ((cfg: PoolConfig): ResearchCopilotPoolLike => new Pool(cfg)); - - let pool: ResearchCopilotPoolLike; + let pool: ResearchCopilotExecutorPool; try { pool = createPool(poolConfig); } catch { - throw new ResearchCopilotExecutorError( - 'CONNECT_FAILED', - 'Failed to initialize PostgreSQL pool for research copilot executor.' - ); + throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED); } - const handleIdlePoolError = (_error: Error): void => { - if (options?.onPoolError === undefined) { - return; - } - const safeError = new ResearchCopilotExecutorError( - 'POOL_ERROR', - 'PostgreSQL research copilot pool encountered an idle client error.' - ); - try { - options.onPoolError(safeError); - } catch { - // Never allow an idle-client error callback to crash the host process. - } - }; + if ( + typeof pool !== 'object' || + pool === null || + typeof pool.query !== 'function' || + typeof pool.end !== 'function' || + typeof pool.on !== 'function' + ) { + throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED); + } try { - pool.on('error', handleIdlePoolError); + // Keep idle-client disconnects from becoming unhandled EventEmitter errors. + pool.on('error', () => { + // Intentionally absorbed; subsequent queries surface sanitized QUERY_FAILED errors. + }); await pool.query('SELECT 1'); } catch { - try { - await pool.end(); - } catch { - // Preserve the primary startup connection failure. - } - throw new ResearchCopilotExecutorError( - 'CONNECT_FAILED', - 'Failed to connect PostgreSQL research copilot executor.' - ); + await safeEndPool(pool); + throw new ResearchCopilotExecutorError('OPEN_FAILED', ERROR_MESSAGES.OPEN_FAILED); } - let closing = false; + let closed = false; let closePromise: Promise | null = null; const executor: ResearchCopilotExecutor = { @@ -436,50 +336,44 @@ export async function openResearchCopilotExecutor( text: string, params?: readonly unknown[] ): Promise<{ readonly rows: readonly Row[] }> { - if (closing) { - throw new ResearchCopilotExecutorError( - 'EXECUTOR_CLOSED', - 'PostgreSQL research copilot executor is closed.' - ); + if (closed) { + throw new ResearchCopilotExecutorError('EXECUTOR_CLOSED', ERROR_MESSAGES.EXECUTOR_CLOSED); } + let rawResult: { readonly rows: readonly unknown[] }; try { - const result = await pool.query(text, params === undefined ? undefined : [...params]); - return { rows: result.rows as readonly Row[] }; + rawResult = + params === undefined ? await pool.query(text) : await pool.query(text, [...params]); } catch (error) { - const replaySqlState = extractFindingReplaySqlState(error); - if (replaySqlState !== undefined) { - const sanitized = new Error('PostgreSQL research copilot query failed.'); - Object.defineProperty(sanitized, 'code', { - value: replaySqlState, - enumerable: true, - configurable: true, - }); - throw sanitized; + if (getPostgresErrorCode(error) === '23505') { + throw new ResearchCopilotExecutorError('23505', ERROR_MESSAGES['23505']); } - throw new ResearchCopilotExecutorError( - 'QUERY_FAILED', - 'PostgreSQL research copilot query failed.' - ); + throw new ResearchCopilotExecutorError('QUERY_FAILED', ERROR_MESSAGES.QUERY_FAILED); } + + if ( + typeof rawResult !== 'object' || + rawResult === null || + !Array.isArray(rawResult.rows) + ) { + throw new ResearchCopilotExecutorError('QUERY_FAILED', ERROR_MESSAGES.QUERY_FAILED); + } + + return { rows: rawResult.rows as readonly Row[] }; }, }; const close = (): Promise => { - closing = true; + closed = true; if (closePromise === null) { - closePromise = pool.end().catch(() => { - throw new ResearchCopilotExecutorError( - 'CLOSE_FAILED', - 'Failed to close PostgreSQL research copilot executor.' - ); - }); + closePromise = Promise.resolve() + .then(() => pool.end()) + .catch(() => { + throw new ResearchCopilotExecutorError('CLOSE_FAILED', ERROR_MESSAGES.CLOSE_FAILED); + }); } return closePromise; }; - return { - executor, - close, - }; + return { executor, close }; } diff --git a/libs/data/postgres/test/research-copilot-executor-edge.test.ts b/libs/data/postgres/test/research-copilot-executor-edge.test.ts index cdf130ca..f126bd50 100644 --- a/libs/data/postgres/test/research-copilot-executor-edge.test.ts +++ b/libs/data/postgres/test/research-copilot-executor-edge.test.ts @@ -1,249 +1,428 @@ -import { EventEmitter } from 'node:events'; -import { type Socket, createServer } from 'node:net'; -import { describe, expect, test } from 'bun:test'; -import type { PoolConfig } from 'pg'; +import { readFileSync } from 'node:fs'; +import { createServer, type AddressInfo, type Socket } from 'node:net'; +import { fileURLToPath } from 'node:url'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Client, Pool, type PoolConfig } from 'pg'; import { + RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, + RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, + RESEARCH_COPILOT_PG_POOL_MAX, + RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, + RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, ResearchCopilotExecutorError, - type ResearchCopilotPoolLike, + type ResearchCopilotExecutorPool, openResearchCopilotExecutor, -} from '../src'; +} from '../src/index'; -function createFakePool(options?: { - onQuery?: (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly unknown[] }>; - onEnd?: () => Promise; -}): ResearchCopilotPoolLike { - const emitter = new EventEmitter(); - const pool: ResearchCopilotPoolLike = { - async query(text: string, values?: unknown[]) { - if (options?.onQuery) { - return await options.onQuery(text, values); - } - return { rows: [{ ok: 1 }] }; - }, - async end() { - if (options?.onEnd) { - await options.onEnd(); - } - }, - on(event: 'error', listener: (error: Error) => void) { - emitter.on(event, listener); - return pool; - }, - }; - return pool; -} +const cleanup: Array<() => Promise | void> = []; +afterEach(async () => { + for (const fn of cleanup.splice(0).reverse()) { + await fn(); + } +}); describe('openResearchCopilotExecutor edge cases', () => { - test('redacts query-param passwords and nested causes on query errors while preserving SQLSTATE 23505', async () => { - const querySecret = 'QueryPass#42'; - const dsn = `postgres://copilot@127.0.0.1:5432/research_db?password=${encodeURIComponent(querySecret)}`; - - const pool = createFakePool({ - onQuery: async text => { - if (text === 'SELECT 1') { - return { rows: [{ ok: 1 }] }; - } - if (text === 'DUP_WITH_SECRET') { - const err = Object.assign(new Error(`duplicate key leaked ${querySecret}`), { - code: '23505', - }); - throw err; - } - if (text === 'NESTED_CAUSE') { - const inner = new Error(`inner failure ${querySecret}`); - throw new Error('outer message', { cause: inner }); - } - throw 'non-error string with secret'; + test('strips URL timeout overrides while preserving search_path and enforcing executor timeouts', async () => { + const capturedConfigs: PoolConfig[] = []; + const fakePool: ResearchCopilotExecutorPool = { + async query() { + return { rows: [{ '?column?': 1 }] }; }, - }); + async end() {}, + on() { + return fakePool; + }, + }; + + const hostileUrl = + 'postgres://u:p@127.0.0.1:5432/research_db' + + '?sslmode=disable' + + '&application_name=copilot_edge' + + '&statement_timeout=99999' + + '&LOCK_TIMEOUT=88888' + + '&query_timeout=77777' + + '&connect_timeout=66' + + '&connectionTimeoutMillis=55555' + + '&options=-c%20search_path%3Disolated_schema%20-c%20statement_timeout%3D60000%20-c%20lock_timeout%3D60000'; const handle = await openResearchCopilotExecutor( - { postgresUrl: dsn }, - { createPool: () => pool, env: {} } + { postgresUrl: hostileUrl }, + { + createPool(poolConfig) { + capturedConfigs.push(poolConfig); + return fakePool; + }, + } ); - // SQLSTATE 23505 preserved even when the error message had to be redacted. - let dupErr: unknown; - try { - await handle.executor.query('DUP_WITH_SECRET'); - } catch (error) { - dupErr = error; - } - expect(dupErr).toBeInstanceOf(Error); - expect((dupErr as { code?: string }).code).toBe('23505'); - expect((dupErr as Error).message).not.toContain(querySecret); - expect('cause' in (dupErr as Error)).toBe(false); + expect(capturedConfigs).toHaveLength(1); + const poolConfig = capturedConfigs[0]!; + const normalizedUrl = new URL(poolConfig.connectionString!); + expect(normalizedUrl.searchParams.get('sslmode')).toBe('disable'); + expect(normalizedUrl.searchParams.get('application_name')).toBe('copilot_edge'); + expect(normalizedUrl.searchParams.has('statement_timeout')).toBe(false); + expect(normalizedUrl.searchParams.has('LOCK_TIMEOUT')).toBe(false); + expect(normalizedUrl.searchParams.has('query_timeout')).toBe(false); + expect(normalizedUrl.searchParams.has('connect_timeout')).toBe(false); + expect(normalizedUrl.searchParams.has('connectionTimeoutMillis')).toBe(false); + expect(normalizedUrl.searchParams.has('options')).toBe(false); - // Nested cause containing secret is replaced with credential-free QUERY_FAILED. - let nestedErr: unknown; - try { - await handle.executor.query('NESTED_CAUSE'); - } catch (error) { - nestedErr = error; - } - expect(nestedErr).toBeInstanceOf(ResearchCopilotExecutorError); - expect((nestedErr as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED'); - expect((nestedErr as Error).message).not.toContain(querySecret); - expect('cause' in (nestedErr as Error)).toBe(false); + expect(poolConfig.options).toBe( + `-c search_path=isolated_schema -c statement_timeout=60000 -c lock_timeout=60000 ` + + `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}` + ); - // Non-Error thrown value is wrapped safely. - let nonErr: unknown; - try { - await handle.executor.query('NON_ERROR'); - } catch (error) { - nonErr = error; - } - expect(nonErr).toBeInstanceOf(ResearchCopilotExecutorError); - expect((nonErr as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED'); + // Verify pg's own ConnectionParameters parser resolves the enforced timeouts. + const client = new Client(poolConfig); + const params = ( + client as unknown as { + connectionParameters: { + statement_timeout?: unknown; + lock_timeout?: unknown; + query_timeout?: unknown; + connect_timeout?: unknown; + options?: string; + application_name?: string; + }; + } + ).connectionParameters; + + expect(params.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS); + expect(params.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS); + expect(params.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS); + expect(params.connect_timeout).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS / 1000); + expect(params.application_name).toBe('copilot_edge'); + expect(params.options).toBe(poolConfig.options); await handle.close(); }); - test('rejects control characters in PGOPTIONS and URL options before creating a pool', async () => { - let calls = 0; + test('accepts Unix-domain socket host query parameter and resolves domain-socket parameters in pg', async () => { + const capturedConfigs: PoolConfig[] = []; + const fakePool: ResearchCopilotExecutorPool = { + async query() { + return { rows: [{ '?column?': 1 }] }; + }, + async end() {}, + on() { + return fakePool; + }, + }; - let envErr: unknown; - try { - await openResearchCopilotExecutor( - { postgresUrl: 'postgres://u:p@127.0.0.1:5432/research_db' }, - { - createPool: () => { - calls += 1; - return createFakePool(); - }, - env: { PGOPTIONS: '-c search_path=ok\n-c evil=1' }, - } - ); - } catch (error) { - envErr = error; - } - expect(calls).toBe(0); - expect(envErr).toBeInstanceOf(ResearchCopilotExecutorError); - expect((envErr as ResearchCopilotExecutorError).code).toBe('INVALID_CONFIG'); - - let urlOptErr: unknown; - try { - await openResearchCopilotExecutor( - { postgresUrl: 'postgres://u:p@127.0.0.1:5432/research_db?options=-c%20search_path%3Dok%00' }, - { - createPool: () => { - calls += 1; - return createFakePool(); - }, - env: {}, - } - ); - } catch (error) { - urlOptErr = error; - } - expect(calls).toBe(0); - expect(urlOptErr).toBeInstanceOf(ResearchCopilotExecutorError); - expect((urlOptErr as ResearchCopilotExecutorError).code).toBe('INVALID_CONFIG'); - }); - - test('normalizes case-insensitive query params and combines multiple options entries', async () => { - const captured: PoolConfig[] = []; const handle = await openResearchCopilotExecutor( { postgresUrl: - 'postgres://u:p@127.0.0.1:5432/research_db?OPTIONS=-c%20search_path%3Ds1&options=-c%20work_mem%3D16MB&STATEMENT_TIMEOUT=0&LOCK_TIMEOUT=0&application_name=copilot_edge', + 'postgres:///research_db?host=/var/run/postgresql&statement_timeout=99999&lock_timeout=88888', }, { - createPool: cfg => { - captured.push(cfg); - return createFakePool(); + createPool(poolConfig) { + capturedConfigs.push(poolConfig); + return fakePool; }, - env: {}, } ); - const cfg = captured[0] as PoolConfig; - expect(cfg.options).toBe( - '-c search_path=s1 -c work_mem=16MB -c statement_timeout=10000 -c lock_timeout=2000' - ); - expect(cfg.connectionString).toContain('application_name=copilot_edge'); - expect(cfg.connectionString?.toLowerCase()).not.toContain('statement_timeout='); - expect(cfg.connectionString?.toLowerCase()).not.toContain('lock_timeout='); - expect(cfg.connectionString?.toLowerCase()).not.toContain('options='); + expect(capturedConfigs).toHaveLength(1); + const client = new Client(capturedConfigs[0]); + const params = ( + client as unknown as { + connectionParameters: { + host?: string; + database?: string; + isDomainSocket?: boolean; + statement_timeout?: unknown; + lock_timeout?: unknown; + query_timeout?: unknown; + }; + } + ).connectionParameters; + + expect(params.host).toBe('/var/run/postgresql'); + expect(params.database).toBe('research_db'); + expect(params.isDomainSocket).toBe(true); + expect(params.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS); + expect(params.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS); + expect(params.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS); await handle.close(); }); - test('redacts pool.end() failure as CLOSE_FAILED without leaking credentials', async () => { - const secret = 'close_secret_77'; - const pool = createFakePool({ - onEnd: async () => { - throw new Error(`failed closing pool for ${secret}`); - }, + test('rejects URLs missing host or database even when PGHOST and PGDATABASE are set', async () => { + const previousPgHost = process.env.PGHOST; + const previousPgDatabase = process.env.PGDATABASE; + process.env.PGHOST = '127.0.0.1'; + process.env.PGDATABASE = 'fallback_db'; + cleanup.push(() => { + if (previousPgHost === undefined) { + delete process.env.PGHOST; + } else { + process.env.PGHOST = previousPgHost; + } + if (previousPgDatabase === undefined) { + delete process.env.PGDATABASE; + } else { + process.env.PGDATABASE = previousPgDatabase; + } }); - const handle = await openResearchCopilotExecutor( - { postgresUrl: `postgres://u:${secret}@127.0.0.1:5432/research_db` }, - { createPool: () => pool, env: {} } - ); - - let closeErr: unknown; - try { - await handle.close(); - } catch (error) { - closeErr = error; + let createPoolCalls = 0; + for (const postgresUrl of [ + 'postgres:///research_db', + 'postgres://127.0.0.1:5432/', + 'postgres://127.0.0.1:5432', + ]) { + await expect( + openResearchCopilotExecutor( + { postgresUrl }, + { + createPool() { + createPoolCalls += 1; + return { + async query() { + return { rows: [] }; + }, + async end() {}, + on() { + return undefined; + }, + }; + }, + } + ) + ).rejects.toMatchObject({ + name: 'ResearchCopilotExecutorError', + code: 'INVALID_CONFIG', + }); } - - expect(closeErr).toBeInstanceOf(ResearchCopilotExecutorError); - expect((closeErr as ResearchCopilotExecutorError).code).toBe('CLOSE_FAILED'); - expect((closeErr as Error).message).not.toContain(secret); - expect('cause' in (closeErr as Error)).toBe(false); + expect(createPoolCalls).toBe(0); }); - test( - 'rejects silent local TCP listener via real pg.Pool connectionTimeoutMillis without leaking credentials', - async () => { - const sockets = new Set(); - const server = createServer(socket => { - // Intentionally accept and hold the TCP connection silent without PostgreSQL handshake. - sockets.add(socket); - socket.on('close', () => { - sockets.delete(socket); - }); - socket.on('error', () => {}); - }); - - const listenPort = await new Promise((resolve, reject) => { - server.once('error', reject); - server.listen(0, '127.0.0.1', () => { - const address = server.address(); - if (address === null || typeof address === 'string') { - reject(new Error('Expected TCP address info')); - return; - } - resolve(address.port); - }); - }); - - const secret = 'silent_tcp_secret_99'; - let caught: unknown; - try { - await openResearchCopilotExecutor({ - postgresUrl: `postgres://copilot:${secret}@127.0.0.1:${listenPort}/research_db`, - }); - } catch (error) { - caught = error; - } finally { - for (const socket of sockets) { - socket.destroy(); - } - await new Promise(resolve => { - server.close(() => resolve()); - }); + test('preserves PGOPTIONS startup precedence while enforcing executor timeouts', async () => { + const previousPgOptions = process.env.PGOPTIONS; + cleanup.push(() => { + if (previousPgOptions === undefined) { + delete process.env.PGOPTIONS; + } else { + process.env.PGOPTIONS = previousPgOptions; } + }); - expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); - const err = caught as ResearchCopilotExecutorError; - expect(err.code).toBe('CONNECT_FAILED'); - expect(err.message).not.toContain(secret); - expect(err.stack ?? '').not.toContain(secret); - expect('cause' in err).toBe(false); - }, - 15_000 - ); + const fakePool: ResearchCopilotExecutorPool = { + async query() { + return { rows: [{ '?column?': 1 }] }; + }, + async end() {}, + on() { + return fakePool; + }, + }; + + // 1. No URL options and no PGOPTIONS -> PoolConfig.options omitted. + delete process.env.PGOPTIONS; + let captured: PoolConfig | undefined; + const h1 = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, + { + createPool(poolConfig) { + captured = poolConfig; + return fakePool; + }, + } + ); + expect(captured?.options).toBeUndefined(); + const c1 = new Client(captured); + const p1 = ( + c1 as unknown as { + connectionParameters: { + options?: string; + statement_timeout?: unknown; + lock_timeout?: unknown; + }; + } + ).connectionParameters; + expect(p1.options).toBeUndefined(); + expect(p1.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS); + expect(p1.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS); + await h1.close(); + + // 2. PGOPTIONS set with no URL options -> PGOPTIONS preserved + executor timeouts appended. + process.env.PGOPTIONS = '-c search_path=research -c statement_timeout=99999 -c lock_timeout=88888'; + captured = undefined; + const h2 = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, + { + createPool(poolConfig) { + captured = poolConfig; + return fakePool; + }, + } + ); + expect(captured?.options).toBe( + `-c search_path=research -c statement_timeout=99999 -c lock_timeout=88888 ` + + `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}` + ); + const c2 = new Client(captured); + const p2 = ( + c2 as unknown as { connectionParameters: { options?: string } } + ).connectionParameters; + expect(p2.options).toBe(captured?.options); + await h2.close(); + + // 3. Both URL options and PGOPTIONS set -> URL options wins over PGOPTIONS, timeouts still appended. + process.env.PGOPTIONS = '-c search_path=env_schema'; + captured = undefined; + const h3 = await openResearchCopilotExecutor( + { + postgresUrl: + 'postgres://127.0.0.1:5432/research_db?options=-c%20search_path%3Durl_schema', + }, + { + createPool(poolConfig) { + captured = poolConfig; + return fakePool; + }, + } + ); + expect(captured?.options).toBe( + `-c search_path=url_schema ` + + `-c statement_timeout=${RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS} -c lock_timeout=${RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS}` + ); + await h3.close(); + }); + + test('absorbs idle-client pool error events without crashing the process', async () => { + const errorListeners: Array<(error: Error) => void> = []; + const fakePool: ResearchCopilotExecutorPool = { + async query(text) { + return { rows: [{ sql: text }] }; + }, + async end() {}, + on(event, listener) { + if (event === 'error') { + errorListeners.push(listener); + } + return fakePool; + }, + }; + + const handle = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, + { createPool: () => fakePool } + ); + + expect(errorListeners).toHaveLength(1); + expect(() => errorListeners[0]!(new Error('idle client disconnected'))).not.toThrow(); + + const res = await handle.executor.query<{ sql: string }>('SELECT 2'); + expect(res.rows).toEqual([{ sql: 'SELECT 2' }]); + await handle.close(); + }); + + test('deduplicates concurrent close() calls and rejects queries started during shutdown', async () => { + let resolveEnd!: () => void; + let endCalls = 0; + let queryCalls = 0; + + const fakePool: ResearchCopilotExecutorPool = { + async query() { + queryCalls += 1; + return { rows: [] }; + }, + end() { + endCalls += 1; + return new Promise(resolve => { + resolveEnd = resolve; + }); + }, + on() { + return fakePool; + }, + }; + + const handle = await openResearchCopilotExecutor( + { postgresUrl: 'postgres://127.0.0.1:5432/research_db' }, + { createPool: () => fakePool } + ); + expect(queryCalls).toBe(1); + + const closeA = handle.close(); + const closeB = handle.close(); + + // Even while pool.end() is still in flight, new queries must reject immediately. + await expect(handle.executor.query('SELECT 2')).rejects.toMatchObject({ + name: 'ResearchCopilotExecutorError', + code: 'EXECUTOR_CLOSED', + }); + expect(queryCalls).toBe(1); + expect(endCalls).toBe(1); + + resolveEnd(); + await Promise.all([closeA, closeB]); + expect(endCalls).toBe(1); + }); + + test('rejects with sanitized OPEN_FAILED when a real pg.Pool times out against a silent loopback listener', async () => { + const sockets = new Set(); + const server = createServer(socket => { + sockets.add(socket); + socket.on('close', () => sockets.delete(socket)); + // Intentionally accept and never reply so pg hits its connection timeout. + }); + + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', () => resolve()); + }); + cleanup.push(async () => { + for (const socket of sockets) { + socket.destroy(); + } + await new Promise(resolve => server.close(() => resolve())); + }); + + const { port } = server.address() as AddressInfo; + const secretPass = 'LoopbackSecretPass99'; + const loopbackUrl = `postgres://loopback_user:${secretPass}@127.0.0.1:${port}/research_db`; + + let observedConfig: PoolConfig | undefined; + let caught: unknown; + try { + await openResearchCopilotExecutor( + { postgresUrl: loopbackUrl }, + { + createPool(poolConfig) { + observedConfig = poolConfig; + // Keep the default config assertions intact, but tighten connect timeout for fast local test execution. + return new Pool({ + ...poolConfig, + connectionTimeoutMillis: 150, + }); + }, + } + ); + } catch (err) { + caught = err; + } + + expect(observedConfig?.max).toBe(RESEARCH_COPILOT_PG_POOL_MAX); + expect(observedConfig?.connectionTimeoutMillis).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS); + expect(observedConfig?.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS); + expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); + const typed = caught as ResearchCopilotExecutorError; + expect(typed.code).toBe('OPEN_FAILED'); + expect((typed as { cause?: unknown }).cause).toBeUndefined(); + expect(typed.message).not.toContain('loopback_user'); + expect(typed.message).not.toContain(secretPass); + expect(typed.message).not.toContain('127.0.0.1'); + expect(typed.message).not.toContain(String(port)); + }); + + test('has no runtime import of @stock-bot/research', () => { + const sourcePath = fileURLToPath( + new URL('../src/research-copilot-executor.ts', import.meta.url) + ); + const source = readFileSync(sourcePath, 'utf8'); + expect(source).not.toMatch(/from\s+['"]@stock-bot\/research/); + expect(source).not.toMatch(/require\(\s*['"]@stock-bot\/research/); + }); }); diff --git a/libs/data/postgres/test/research-copilot-executor.test.ts b/libs/data/postgres/test/research-copilot-executor.test.ts index bbe85a57..c014d210 100644 --- a/libs/data/postgres/test/research-copilot-executor.test.ts +++ b/libs/data/postgres/test/research-copilot-executor.test.ts @@ -1,4 +1,3 @@ -import { EventEmitter } from 'node:events'; import { describe, expect, test } from 'bun:test'; import type { PoolConfig } from 'pg'; import { @@ -8,455 +7,417 @@ import { RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, ResearchCopilotExecutorError, - type ResearchCopilotPoolLike, + type ResearchCopilotExecutorPool, openResearchCopilotExecutor, -} from '../src'; +} from '../src/index'; -interface FakePoolControls { - readonly pool: ResearchCopilotPoolLike; - readonly emitter: EventEmitter; +const SECRET_USER = 'copilot_secret_user'; +const SECRET_PASS = 'Sup3rS3cretP@ssw0rd!'; +const SECRET_HOST = 'pg-internal-secret.example.test'; +const VALID_URL = `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`; + +interface FakePoolState { readonly queries: Array<{ readonly text: string; readonly values?: unknown[] }>; - getEndCalls(): number; + readonly errorListeners: Array<(error: Error) => void>; + endCalls: number; + readonly pool: ResearchCopilotExecutorPool; } function createFakePool(options?: { onQuery?: (text: string, values?: unknown[]) => Promise<{ readonly rows: readonly unknown[] }>; onEnd?: () => Promise; -}): FakePoolControls { - const emitter = new EventEmitter(); +}): FakePoolState { const queries: Array<{ readonly text: string; readonly values?: unknown[] }> = []; - let endCalls = 0; - - const pool: ResearchCopilotPoolLike = { - async query(text: string, values?: unknown[]) { - queries.push({ text, values }); - if (options?.onQuery) { - return await options.onQuery(text, values); - } - return { rows: [{ ok: 1 }] }; - }, - async end() { - endCalls += 1; - if (options?.onEnd) { - await options.onEnd(); - } - }, - on(event: 'error', listener: (error: Error) => void) { - emitter.on(event, listener); - return pool; - }, - }; - - return { - pool, - emitter, + const errorListeners: Array<(error: Error) => void> = []; + const state: FakePoolState = { queries, - getEndCalls: () => endCalls, + errorListeners, + endCalls: 0, + pool: { + async query(text: string, values?: unknown[]) { + queries.push(values === undefined ? { text } : { text, values }); + if (options?.onQuery) { + return options.onQuery(text, values); + } + return { rows: [] }; + }, + async end() { + state.endCalls += 1; + if (options?.onEnd) { + return options.onEnd(); + } + }, + on(event: 'error', listener: (error: Error) => void) { + if (event === 'error') { + errorListeners.push(listener); + } + return state.pool; + }, + }, }; + return state; +} + +function assertNoSecretsLeaked(error: unknown): void { + expect(error).toBeInstanceOf(ResearchCopilotExecutorError); + const typed = error as ResearchCopilotExecutorError; + expect((typed as { cause?: unknown }).cause).toBeUndefined(); + expect('cause' in typed).toBe(false); + expect('detail' in typed).toBe(false); + expect('extraDiag' in typed).toBe(false); + const message = typed.message; + for (const needle of [ + VALID_URL, + SECRET_USER, + SECRET_PASS, + encodeURIComponent(SECRET_PASS), + SECRET_HOST, + 'raw-pg-secret', + ]) { + expect(message).not.toContain(needle); + } } describe('openResearchCopilotExecutor', () => { - describe('pre-pool config validation (fail closed)', () => { - const invalidConfigs: ReadonlyArray = [ - ['null config', null], - ['missing postgresUrl', {}], - ['empty postgresUrl', { postgresUrl: '' }], - ['whitespace postgresUrl', { postgresUrl: ' ' }], - [ - 'leading/trailing whitespace around valid URL', - { postgresUrl: ' postgres://u:supersecret@localhost:5432/research_db ' }, - ], - ['http scheme', { postgresUrl: 'http://u:supersecret@localhost:5432/research_db' }], - ['mysql scheme', { postgresUrl: 'mysql://u:supersecret@localhost:5432/research_db' }], - [ - 'single-slash postgres:/ URI (T-189 regression)', - { postgresUrl: 'postgres:/research_db?host=%2Ftmp' }, - ], - [ - 'single-slash postgresql:/ URI', - { postgresUrl: 'postgresql:/research_db?host=%2Fvar%2Frun%2Fpostgresql' }, - ], - ['missing host and host query param', { postgresUrl: 'postgres:///research_db' }], - ['hostaddr-only URL (ignored by pg)', { postgresUrl: 'postgres:///research_db?hostaddr=127.0.0.1' }], - ['empty authority with port only', { postgresUrl: 'postgres://:5432/research_db' }], - ['missing database name', { postgresUrl: 'postgres://u:supersecret@localhost:5432' }], - ['trailing slash only (missing database)', { postgresUrl: 'postgres://u:supersecret@localhost:5432/' }], - [ - 'dbname-only URL with empty path (pg falls back to PGDATABASE)', - { postgresUrl: 'postgres://copilot:supersecret@db.example/?dbname=research' }, - ], - [ - 'dbname-only URL without trailing slash', - { postgresUrl: 'postgres://copilot@db.example?dbname=research' }, - ], - ['blank percent-encoded database', { postgresUrl: 'postgres://u:supersecret@localhost:5432/%20' }], - ['port zero', { postgresUrl: 'postgres://u:supersecret@localhost:0/research_db' }], - ['query port zero overriding authority port', { postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db?port=0' }], - ['query port out of range', { postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db?port=70000' }], - ['non-numeric query port', { postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db?port=abc' }], - ['invalid percent-encoding in password', { postgresUrl: 'postgres://u:%ZZsupersecret@localhost:5432/research_db' }], - ['control character in URL', { postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db\n' }], - [ - 'invalid postgresSchema with uppercase', - { postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db', postgresSchema: 'Public' }, - ], - [ - 'invalid postgresSchema with hyphen', - { postgresUrl: 'postgres://u:supersecret@localhost:5432/research_db', postgresSchema: 'my-schema' }, - ], + test('opens a bounded pg pool, probes once with SELECT 1, and attaches an error listener', async () => { + const previousPgOptions = process.env.PGOPTIONS; + delete process.env.PGOPTIONS; + try { + const capturedConfigs: PoolConfig[] = []; + const fake = createFakePool({ + async onQuery(text) { + if (text === 'SELECT 1') { + return { rows: [{ '?column?': 1 }] }; + } + return { rows: [{ id: 42 }] }; + }, + }); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { + createPool(poolConfig) { + capturedConfigs.push(poolConfig); + return fake.pool; + }, + } + ); + + expect(capturedConfigs).toHaveLength(1); + expect(capturedConfigs[0]).toEqual({ + connectionString: VALID_URL, + max: RESEARCH_COPILOT_PG_POOL_MAX, + connectionTimeoutMillis: RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS, + statement_timeout: RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS, + query_timeout: RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS, + lock_timeout: RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS, + }); + expect(capturedConfigs[0]?.options).toBeUndefined(); + expect(RESEARCH_COPILOT_PG_POOL_MAX).toBe(4); + expect(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS).toBe(5_000); + expect(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS).toBe(10_000); + expect(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS).toBe(15_000); + expect(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS).toBe(2_000); + + expect(fake.errorListeners).toHaveLength(1); + expect(fake.queries).toEqual([{ text: 'SELECT 1' }]); + + const res = await handle.executor.query<{ id: number }>('SELECT $1::int AS id', [42]); + expect(res.rows).toEqual([{ id: 42 }]); + expect(fake.queries).toEqual([ + { text: 'SELECT 1' }, + { text: 'SELECT $1::int AS id', values: [42] }, + ]); + + await handle.close(); + expect(fake.endCalls).toBe(1); + } finally { + if (previousPgOptions === undefined) { + delete process.env.PGOPTIONS; + } else { + process.env.PGOPTIONS = previousPgOptions; + } + } + }); + + test('accepts postgresql:// scheme and Unix-domain socket host query parameters', async () => { + for (const postgresUrl of [ + 'postgresql://127.0.0.1:5432/research_db', + 'postgres:///research_db?host=/var/run/postgresql', + 'postgresql:///research_db?host=/var/run/postgresql', + ]) { + const fake = createFakePool(); + const handle = await openResearchCopilotExecutor( + { postgresUrl }, + { createPool: () => fake.pool } + ); + expect(fake.queries).toEqual([{ text: 'SELECT 1' }]); + await handle.close(); + } + }); + + test('rejects invalid URLs with INVALID_CONFIG before constructing a pool', async () => { + const invalidUrls = [ + '', + ' ', + ` ${VALID_URL} `, + `${VALID_URL}\n`, + 'not-a-url', + `http://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`, + `mysql://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:3306/research_db`, + 'postgres:/research_db?host=%2Ftmp', + 'postgresql:/research_db?host=%2Ftmp', + 'postgres:///research_db', + 'postgres:///research_db?host=', + 'postgres:///research_db?host=%20%20', + 'postgres:///research_db?host=/var/run/postgresql&host=/tmp', + 'postgres:///research_db?HOST=/var/run/postgresql', + 'postgres://copilot@db.example/?dbname=research', + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?host=/a&host=/b`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=0`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=70000`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=abc`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db?port=5432&port=5433`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%20%20`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/db/extra`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:0/research_db`, + `postgres://%ZZ:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/research_db`, + `postgres://${SECRET_USER}:%ZZ@${SECRET_HOST}:5432/research_db`, + `postgres://${SECRET_USER}:${encodeURIComponent(SECRET_PASS)}@${SECRET_HOST}:5432/%ZZ`, ]; - for (const [label, invalidConfig] of invalidConfigs) { - test(`rejects ${label} before creating any pool`, async () => { - let createPoolCalls = 0; - - let caught: unknown; - try { - await openResearchCopilotExecutor(invalidConfig as { postgresUrl: string }, { - createPool: () => { + let createPoolCalls = 0; + for (const postgresUrl of invalidUrls) { + let caught: unknown; + try { + await openResearchCopilotExecutor( + { postgresUrl }, + { + createPool() { createPoolCalls += 1; return createFakePool().pool; }, - env: {}, - }); - } catch (error) { - caught = error; - } - - expect(createPoolCalls).toBe(0); - expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); - const err = caught as ResearchCopilotExecutorError; - expect(err.code).toBe('INVALID_CONFIG'); - expect(err.message).not.toContain('supersecret'); - expect('cause' in err).toBe(false); - }); - } - }); - - describe('valid Unix socket URLs and pool normalization', () => { - const validSocketUrls = [ - 'postgres:///research_db?host=/var/run/postgresql', - 'postgresql:///research_db?host=%2Ftmp', - 'postgres://research_user:socketpass@/research_db?host=/tmp', - 'postgres://%2Fvar%2Frun%2Fpostgresql/research_db', - ]; - - for (const socketUrl of validSocketUrls) { - test(`accepts Unix socket URL: ${socketUrl}`, async () => { - const captured: PoolConfig[] = []; - const fake = createFakePool(); - - const handle = await openResearchCopilotExecutor( - { postgresUrl: socketUrl }, - { - createPool: cfg => { - captured.push(cfg); - return fake.pool; - }, - env: {}, } ); + } catch (err) { + caught = err; + } + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('INVALID_CONFIG'); + } + expect(createPoolCalls).toBe(0); + }); - expect(captured).toHaveLength(1); - expect(fake.queries).toEqual([{ text: 'SELECT 1', values: undefined }]); - await handle.close(); - }); + test('rejects malformed config or deps with INVALID_CONFIG', async () => { + await expect( + openResearchCopilotExecutor(null as unknown as { postgresUrl: string }) + ).rejects.toMatchObject({ + name: 'ResearchCopilotExecutorError', + code: 'INVALID_CONFIG', + }); + + await expect( + openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { createPool: 'not-a-fn' as unknown as () => ResearchCopilotExecutorPool } + ) + ).rejects.toMatchObject({ + name: 'ResearchCopilotExecutorError', + code: 'INVALID_CONFIG', + }); + }); + + test('ends pool and throws sanitized OPEN_FAILED when startup probe fails', async () => { + const fake = createFakePool({ + async onQuery() { + throw new Error(`password authentication failed for ${SECRET_USER} at ${SECRET_HOST} raw-pg-secret`); + }, + }); + + let caught: unknown; + try { + await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool }); + } catch (err) { + caught = err; } - test('applies bounded pool max and timeouts while preserving search_path from URL options and PGOPTIONS', async () => { - const captured: PoolConfig[] = []; - const fake = createFakePool(); - - const handle = await openResearchCopilotExecutor( - { - postgresUrl: - 'postgresql://reader:topsecret@127.0.0.1:5432/research_db?options=-c%20search_path%3Durl_schema&statement_timeout=0&lock_timeout=0&query_timeout=0&connect_timeout=999&max=50', - postgresSchema: 'url_schema', - }, - { - createPool: cfg => { - captured.push(cfg); - return fake.pool; - }, - env: { - PGOPTIONS: '-c search_path=env_schema -c statement_timeout=0', - }, - } - ); - - expect(captured).toHaveLength(1); - const poolConfig = captured[0] as PoolConfig; - expect(poolConfig.max).toBe(RESEARCH_COPILOT_PG_POOL_MAX); - expect(poolConfig.max).toBe(4); - expect(poolConfig.connectionTimeoutMillis).toBe(RESEARCH_COPILOT_PG_CONNECT_TIMEOUT_MS); - expect(poolConfig.connectionTimeoutMillis).toBe(5_000); - expect(poolConfig.statement_timeout).toBe(RESEARCH_COPILOT_PG_STATEMENT_TIMEOUT_MS); - expect(poolConfig.statement_timeout).toBe(10_000); - expect(poolConfig.query_timeout).toBe(RESEARCH_COPILOT_PG_QUERY_TIMEOUT_MS); - expect(poolConfig.query_timeout).toBe(15_000); - expect(poolConfig.lock_timeout).toBe(RESEARCH_COPILOT_PG_LOCK_TIMEOUT_MS); - expect(poolConfig.lock_timeout).toBe(2_000); - - expect(poolConfig.connectionString).not.toContain('statement_timeout='); - expect(poolConfig.connectionString).not.toContain('lock_timeout='); - expect(poolConfig.connectionString).not.toContain('query_timeout='); - expect(poolConfig.connectionString).not.toContain('connect_timeout='); - expect(poolConfig.connectionString).not.toContain('max='); - expect(poolConfig.connectionString).not.toContain('options='); - - expect(poolConfig.options).toBe( - '-c search_path=env_schema -c statement_timeout=0 -c search_path=url_schema -c statement_timeout=10000 -c lock_timeout=2000' - ); - - await handle.close(); - }); + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED'); + expect(fake.endCalls).toBe(1); }); - describe('startup probe, cleanup, and error redaction', () => { - test('runs exactly one SELECT 1 probe and cleans up pool on connect failure without leaking credentials', async () => { - const secret = 'P@ssw0rd_Secret_123'; - const encoded = encodeURIComponent(secret); - const dsn = `postgres://copilot:${encoded}@127.0.0.1:5432/research_db`; + test('still throws OPEN_FAILED when both probe and cleanup end() fail', async () => { + const fake = createFakePool({ + async onQuery() { + throw new Error(`connect ECONNREFUSED ${SECRET_HOST} raw-pg-secret`); + }, + async onEnd() { + throw new Error(`pool end failed ${VALID_URL}`); + }, + }); - const fake = createFakePool({ - onQuery: async () => { - throw new Error(`password authentication failed for ${dsn} (${secret})`); - }, - }); + let caught: unknown; + try { + await openResearchCopilotExecutor({ postgresUrl: VALID_URL }, { createPool: () => fake.pool }); + } catch (err) { + caught = err; + } - let caught: unknown; - try { - await openResearchCopilotExecutor( - { postgresUrl: dsn }, + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('OPEN_FAILED'); + expect(fake.endCalls).toBe(1); + }); + + test('forwards parameters defensively without mutating caller arrays', async () => { + const fake = createFakePool({ + async onQuery(text, values) { + if (values) { + values.push('mutated-by-driver'); + } + return { rows: [{ text }] }; + }, + }); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { createPool: () => fake.pool } + ); + + const callerParams = Object.freeze(['alpha', 7]); + const res = await handle.executor.query('SELECT $1, $2', callerParams); + expect(res.rows).toEqual([{ text: 'SELECT $1, $2' }]); + expect(callerParams).toEqual(['alpha', 7]); + + await handle.executor.query('SELECT 2'); + expect(fake.queries[2]).toEqual({ text: 'SELECT 2' }); + expect('values' in fake.queries[2]!).toBe(false); + + await handle.close(); + }); + + test('preserves SQLSTATE 23505 on sanitized unique-violation query errors without leaking cause or driver fields', async () => { + let callCount = 0; + const rawCause = new Error(`nested pgpass secret ${SECRET_PASS}`); + const fake = createFakePool({ + async onQuery() { + callCount += 1; + if (callCount === 1) { + return { rows: [{ '?column?': 1 }] }; + } + const pgErr = Object.assign( + new Error(`duplicate key value violates unique constraint on ${SECRET_HOST} raw-pg-secret`, { + cause: rawCause, + }), { - createPool: () => fake.pool, - env: {}, + code: '23505', + detail: `Key (id)=(dup-1) already exists (${SECRET_PASS})`, + extraDiag: 'sensitive-driver-field', } ); - } catch (error) { - caught = error; - } - - expect(fake.queries).toEqual([{ text: 'SELECT 1', values: undefined }]); - expect(fake.getEndCalls()).toBe(1); - expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); - const err = caught as ResearchCopilotExecutorError; - expect(err.code).toBe('CONNECT_FAILED'); - expect(err.message).not.toContain(secret); - expect(err.message).not.toContain(encoded); - expect(err.message).not.toContain(dsn); - expect(err.stack ?? '').not.toContain(secret); - expect('cause' in err).toBe(false); + throw pgErr; + }, }); - test('preserves CONNECT_FAILED even when pool.end() also fails during startup cleanup', async () => { - const fake = createFakePool({ - onQuery: async () => { - throw new Error('ECONNREFUSED'); - }, - onEnd: async () => { - throw new Error('pool end failure'); - }, - }); + const handle = await openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { createPool: () => fake.pool } + ); - let caught: unknown; - try { - await openResearchCopilotExecutor( - { postgresUrl: 'postgres://user:secret@127.0.0.1:5432/research_db' }, - { - createPool: () => fake.pool, - env: {}, - } + let caught: unknown; + try { + await handle.executor.query('INSERT INTO findings (id) VALUES ($1)', ['dup-1']); + } catch (err) { + caught = err; + } + + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('23505'); + await handle.close(); + }); + + test('sanitizes generic query errors to QUERY_FAILED with no cause, extra fields, or raw text', async () => { + let callCount = 0; + const rawCause = new Error(`nested env PGPASSWORD=${SECRET_PASS}`); + const fake = createFakePool({ + async onQuery() { + callCount += 1; + if (callCount === 1) { + return { rows: [{ '?column?': 1 }] }; + } + throw Object.assign( + new Error(`relation "missing" does not exist on ${VALID_URL} raw-pg-secret`, { + cause: rawCause, + }), + { code: '42P01', detail: 'driver-detail', extraDiag: 'sensitive-driver-field' } ); - } catch (error) { - caught = error; - } - - expect(fake.getEndCalls()).toBe(1); - expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); - expect((caught as ResearchCopilotExecutorError).code).toBe('CONNECT_FAILED'); + }, }); + + const handle = await openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { createPool: () => fake.pool } + ); + + let caught: unknown; + try { + await handle.executor.query('SELECT * FROM missing'); + } catch (err) { + caught = err; + } + + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED'); + await handle.close(); }); - describe('idle-client error handling', () => { - test('registers error listener and always wraps idle errors with a fixed credential-free error', async () => { - const fake = createFakePool(); - const received: Error[] = []; - const secret = 'idle_secret_99'; + test('close() is idempotent and subsequent queries fail with EXECUTOR_CLOSED', async () => { + const fake = createFakePool(); + const handle = await openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { createPool: () => fake.pool } + ); - const handle = await openResearchCopilotExecutor( - { postgresUrl: `postgres://user:${secret}@127.0.0.1:5432/research_db` }, - { - createPool: () => fake.pool, - onPoolError: err => { - received.push(err); - }, - env: {}, - } - ); + await handle.close(); + await handle.close(); + expect(fake.endCalls).toBe(1); - expect(fake.emitter.listenerCount('error')).toBe(1); + let caught: unknown; + try { + await handle.executor.query('SELECT 1'); + } catch (err) { + caught = err; + } - const benignLookingErr = Object.assign( - new Error('terminating connection due to administrator command', { - cause: new Error('env PGPASSWORD=from_env_secret'), - }), - { detail: 'pgpass credential leak', extraDiag: 'hidden' } - ); - fake.emitter.emit('error', benignLookingErr); - fake.emitter.emit('error', new Error(`fatal idle error with ${secret}`)); - - expect(received).toHaveLength(2); - for (const err of received) { - expect(err).not.toBe(benignLookingErr); - expect(err).toBeInstanceOf(ResearchCopilotExecutorError); - expect((err as ResearchCopilotExecutorError).code).toBe('POOL_ERROR'); - expect(err.message).toBe('PostgreSQL research copilot pool encountered an idle client error.'); - expect('cause' in err).toBe(false); - expect('detail' in err).toBe(false); - expect('extraDiag' in err).toBe(false); - } - - await handle.close(); - }); - - test('does not crash when idle error fires without onPoolError or when callback throws', async () => { - const fake1 = createFakePool(); - const handle1 = await openResearchCopilotExecutor( - { postgresUrl: 'postgres://user:pass@127.0.0.1:5432/research_db' }, - { createPool: () => fake1.pool, env: {} } - ); - expect(() => fake1.emitter.emit('error', new Error('idle reset'))).not.toThrow(); - await handle1.close(); - - const fake2 = createFakePool(); - const handle2 = await openResearchCopilotExecutor( - { postgresUrl: 'postgres://user:pass@127.0.0.1:5432/research_db' }, - { - createPool: () => fake2.pool, - onPoolError: () => { - throw new Error('listener boom'); - }, - env: {}, - } - ); - expect(() => fake2.emitter.emit('error', new Error('idle reset'))).not.toThrow(); - await handle2.close(); - }); + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED'); + expect(fake.queries).toHaveLength(1); // Only the initial SELECT 1 probe ran. }); - describe('shutdown lifecycle and query gating', () => { - test('concurrent and repeated close() calls share one shutdown and reject new queries immediately', async () => { - let releaseEnd: (() => void) | undefined; - const endGate = new Promise(resolve => { - releaseEnd = resolve; - }); - - const fake = createFakePool({ - onEnd: () => endGate, - }); - - const handle = await openResearchCopilotExecutor( - { postgresUrl: 'postgres://user:pass@127.0.0.1:5432/research_db' }, - { createPool: () => fake.pool, env: {} } - ); - - // Start concurrent close() calls while pool.end() is still pending. - const close1 = handle.close(); - const close2 = handle.close(); - - // New query must reject immediately as soon as shutdown starts. - let queryErr: unknown; - try { - await handle.executor.query('SELECT 2'); - } catch (error) { - queryErr = error; - } - - expect(queryErr).toBeInstanceOf(ResearchCopilotExecutorError); - expect((queryErr as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED'); - expect(fake.queries).toHaveLength(1); // Only the initial SELECT 1 ran. - - releaseEnd?.(); - await Promise.all([close1, close2]); - await handle.close(); - - expect(fake.getEndCalls()).toBe(1); + test('sanitizes pool.end() failures to CLOSE_FAILED with no cause or secret leakage', async () => { + const fake = createFakePool({ + async onEnd() { + throw new Error(`failed closing pool for ${VALID_URL} raw-pg-secret`); + }, }); - test('forwards queries with cloned params, copies only SQLSTATE 23505, and never exposes raw driver errors or fields', async () => { - const rawDuplicateErr = Object.assign( - new Error('duplicate key value violates unique constraint', { - cause: new Error('raw driver cause with env password'), - }), - { - code: '23505', - detail: 'Key (id)=(f-1) already exists.', - connectionDiagnostics: { password: 'env_password' }, - } - ); - const rawOtherSqlStateErr = Object.assign( - new Error('relation "missing" does not exist', { - cause: new Error('inner pgpass secret'), - }), - { - code: '42P01', - detail: 'sensitive detail', - } - ); - - const fake = createFakePool({ - onQuery: async (text, values) => { - if (text === 'SELECT 1') { - return { rows: [{ ok: 1 }] }; - } - if (text.startsWith('INSERT')) { - throw rawDuplicateErr; - } - if (text === 'SELECT * FROM missing') { - throw rawOtherSqlStateErr; - } - return { rows: [{ echo: values }] }; - }, - }); - - const handle = await openResearchCopilotExecutor( - { postgresUrl: 'postgres://user:pass@127.0.0.1:5432/research_db' }, - { createPool: () => fake.pool, env: {} } - ); - - const params: readonly unknown[] = ['a', 42]; - const res = await handle.executor.query<{ echo: unknown[] }>('SELECT $1, $2', params); - expect(res.rows).toEqual([{ echo: ['a', 42] }]); - - let duplicateErr: unknown; - try { - await handle.executor.query('INSERT INTO findings VALUES ($1)', ['f-1']); - } catch (error) { - duplicateErr = error; - } - expect(duplicateErr).not.toBe(rawDuplicateErr); - expect(duplicateErr).toBeInstanceOf(Error); - expect((duplicateErr as { code?: string }).code).toBe('23505'); - expect((duplicateErr as Error).message).toBe('PostgreSQL research copilot query failed.'); - expect('cause' in (duplicateErr as Error)).toBe(false); - expect('detail' in (duplicateErr as Error)).toBe(false); - expect('connectionDiagnostics' in (duplicateErr as Error)).toBe(false); - - let otherErr: unknown; - try { - await handle.executor.query('SELECT * FROM missing'); - } catch (error) { - otherErr = error; - } - expect(otherErr).not.toBe(rawOtherSqlStateErr); - expect(otherErr).toBeInstanceOf(ResearchCopilotExecutorError); - expect((otherErr as ResearchCopilotExecutorError).code).toBe('QUERY_FAILED'); - expect((otherErr as Error).message).toBe('PostgreSQL research copilot query failed.'); - expect('cause' in (otherErr as Error)).toBe(false); - expect('detail' in (otherErr as Error)).toBe(false); + const handle = await openResearchCopilotExecutor( + { postgresUrl: VALID_URL }, + { createPool: () => fake.pool } + ); + let caught: unknown; + try { await handle.close(); - }); + } catch (err) { + caught = err; + } + + assertNoSecretsLeaked(caught); + expect((caught as ResearchCopilotExecutorError).code).toBe('CLOSE_FAILED'); + expect(fake.endCalls).toBe(1); }); }); diff --git a/libs/data/postgres/test/research-copilot-executor.type-test.ts b/libs/data/postgres/test/research-copilot-executor.type-test.ts index 7ebb2e65..b022aa18 100644 --- a/libs/data/postgres/test/research-copilot-executor.type-test.ts +++ b/libs/data/postgres/test/research-copilot-executor.type-test.ts @@ -1,32 +1,50 @@ import type { Pool } from 'pg'; import type { ManagedPostgresExecutor, + PostgresResearchCopilotExecutor, ResearchCopilotHostConfig, ResearchCopilotStdioHostDeps, } from '@stock-bot/research/mcp'; import { type ManagedResearchCopilotExecutor, - type ResearchCopilotPoolLike, + type ResearchCopilotExecutor, + type ResearchCopilotExecutorConfig, + type ResearchCopilotExecutorDeps, + type ResearchCopilotExecutorError, + type ResearchCopilotExecutorErrorCode, + type ResearchCopilotExecutorPool, openResearchCopilotExecutor, -} from '../src'; +} from '../src/index'; -// The managed handle returned by openResearchCopilotExecutor must satisfy ManagedPostgresExecutor. +// The factory must plug directly into ResearchCopilotStdioHostDeps.openExecutor. +openResearchCopilotExecutor satisfies ResearchCopilotStdioHostDeps['openExecutor']; + +// Full host config is structurally assignable to the minimal executor config. +declare const hostConfig: ResearchCopilotHostConfig; +hostConfig satisfies ResearchCopilotExecutorConfig; + +// Returned handle and executor are structurally assignable to the MCP host ports. declare const managedHandle: ManagedResearchCopilotExecutor; managedHandle satisfies ManagedPostgresExecutor; -// The factory itself must be directly assignable to ResearchCopilotStdioHostDeps['openExecutor']. -const openExecutor: ResearchCopilotStdioHostDeps['openExecutor'] = openResearchCopilotExecutor; -void openExecutor; +declare const executor: ResearchCopilotExecutor; +executor satisfies PostgresResearchCopilotExecutor; -// Calling openResearchCopilotExecutor with a full ResearchCopilotHostConfig returns ManagedPostgresExecutor. -declare const hostConfig: ResearchCopilotHostConfig; -const opened: Promise = openResearchCopilotExecutor(hostConfig); -void opened; +// Real pg.Pool satisfies the injected pool contract. +declare const pgPool: Pool; +pgPool satisfies ResearchCopilotExecutorPool; -// Real pg.Pool instances must satisfy the structural ResearchCopilotPoolLike interface. -declare const realPool: Pool; -realPool satisfies ResearchCopilotPoolLike; +// Optional deps contract accepts createPool returning pg.Pool. +const validDeps: ResearchCopilotExecutorDeps = { + createPool: () => pgPool, +}; +void validDeps; -// Missing postgresUrl must be rejected at compile time. -// @ts-expect-error postgresUrl is required on ResearchCopilotExecutorConfig. +// Error code union includes all sanitized lifecycle codes plus SQLSTATE 23505. +declare const errorInstance: ResearchCopilotExecutorError; +const errorCode: ResearchCopilotExecutorErrorCode = errorInstance.code; +void errorCode; + +// Negative checks: missing postgresUrl must fail typechecking. +// @ts-expect-error postgresUrl is required. void openResearchCopilotExecutor({}); diff --git a/test/postgres/mcp-copilot-executor.test.ts b/test/postgres/mcp-copilot-executor.test.ts index 67ca1cb1..526f9d78 100644 --- a/test/postgres/mcp-copilot-executor.test.ts +++ b/test/postgres/mcp-copilot-executor.test.ts @@ -12,8 +12,8 @@ import { runPostgresMigrations, } from '@stock-bot/postgres'; import { - type FiledFindingRecord, createPostgresFindingWritePort, + createPostgresKnowledgeReaders, createPostgresTrialRefLookupPort, } from '../../libs/research/src/mcp/index'; @@ -22,11 +22,10 @@ const logger = getLogger('mcp-copilot-executor-pg-test'); const url = process.env.PIPELINE_TEST_DATABASE_URL; const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url)); -// Vault cutoff date 2025-06-30 (exclusive): sample_end must be < 2025-06-30 to be research-visible. const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0); const FIXED_TS = '2026-01-15T12:34:56.789Z'; -const cleanup: (() => Promise | void)[] = []; +const cleanup: Array<() => Promise | void> = []; afterEach(async () => { let firstError: unknown; for (const close of cleanup.splice(0).reverse()) { @@ -68,59 +67,76 @@ function assertSafetyDatabaseUrl(connectionString: string | undefined): string { return connectionString; } -function buildSchemaUrl( - connectionString: string, - schema: string, - extraQuery?: Record -): string { - const parsed = new URL(connectionString); - parsed.searchParams.set('options', `-c search_path=${schema} -c statement_timeout=0 -c lock_timeout=0`); - if (extraQuery) { - for (const [k, v] of Object.entries(extraQuery)) { - parsed.searchParams.set(k, v); - } - } - return parsed.toString(); -} - function buildIsolatedPoolConfig(connectionString: string, schema: string): PoolConfig { - const parsed = new URL(connectionString); + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const parsed = new URL(safeUrl); const existingOptions = parsed.searchParams .getAll('options') .map(value => value.trim()) .filter(value => value.length > 0); parsed.searchParams.delete('options'); + const options = [ ...existingOptions, `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`, ].join(' '); + return { connectionString: parsed.toString(), options, }; } +function buildExecutorUrl( + connectionString: string, + schema: string, + applicationName: string, + extraParams?: Readonly> +): string { + const safeUrl = assertSafetyDatabaseUrl(connectionString); + const parsed = new URL(safeUrl); + const existingOptions = parsed.searchParams + .getAll('options') + .map(value => value.trim()) + .filter(value => value.length > 0); + parsed.searchParams.delete('options'); + const combinedOptions = [...existingOptions, `-c search_path=${schema}`].join(' '); + parsed.searchParams.set('options', combinedOptions); + parsed.searchParams.set('application_name', applicationName); + if (extraParams) { + for (const [k, v] of Object.entries(extraParams)) { + parsed.searchParams.set(k, v); + } + } + return parsed.toString(); +} + async function createIsolatedFixture(connectionString: string | undefined = url) { const safeUrl = assertSafetyDatabaseUrl(connectionString); const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: safeUrl }); - cleanup.push(async () => { - await admin.query(`DROP SCHEMA IF EXISTS ${schema} CASCADE`); - await admin.end(); - }); - + cleanup.push(() => admin.end()); await admin.query(`CREATE SCHEMA ${schema}`); - const migrationPool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); - cleanup.push(async () => { - await migrationPool.end(); - }); + cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`).then(() => undefined)); + + const setupPool = new Pool(buildIsolatedPoolConfig(safeUrl, schema)); + cleanup.push(() => setupPool.end()); + + const { rows: schemaRows } = await setupPool.query<{ current_schema: string | null }>( + 'SELECT current_schema() AS current_schema' + ); + if (schemaRows[0]?.current_schema !== schema) { + throw new Error( + `Isolated fixture pool expected current_schema()=${schema}, got ${String(schemaRows[0]?.current_schema)}` + ); + } for (const filename of [ '06-create-backtest-tables.sql', '07-fix-execution-time-type.sql', '08-create-runs-table.sql', ]) { - await migrationPool.query(readFileSync(`${initDir}${filename}`, 'utf8')); + await setupPool.query(readFileSync(`${initDir}${filename}`, 'utf8')); } const postgres = new PostgreSQLClient( @@ -129,38 +145,34 @@ async function createIsolatedFixture(connectionString: string | undefined = url) ); Object.defineProperty(postgres, 'connectionPool', { get: () => ({ - connect: () => migrationPool.connect(), + connect: () => setupPool.connect(), }), }); await runPostgresMigrations(postgres, { track: 'research' }); - return { admin, migrationPool, safeUrl, schema }; + return { admin, setupPool, schema, safeUrl }; } -async function waitForZeroBackends( - admin: Pool, - appName: string, - timeoutMs = 3000 -): Promise { - const deadline = Date.now() + timeoutMs; - let lastCount = -1; +async function waitForZeroBackends(admin: Pool, applicationName: string): Promise { + const deadline = Date.now() + 2_000; + let count = -1; while (Date.now() < deadline) { - const { rows } = await admin.query<{ count: string }>( - 'SELECT count(*)::text AS count FROM pg_stat_activity WHERE application_name = $1', - [appName] + const { rows } = await admin.query<{ c: number }>( + 'SELECT count(*)::int AS c FROM pg_stat_activity WHERE application_name = $1', + [applicationName] ); - lastCount = Number(rows[0]?.count ?? '0'); - if (lastCount === 0) { + count = rows[0]?.c ?? -1; + if (count === 0) { return 0; } await new Promise(resolve => setTimeout(resolve, 25)); } - return lastCount; + return count; } describe('PostgreSQL MCP copilot executor safety guard', () => { - test('rejects unsafe database targets before connecting', () => { + test('rejects missing or non-safety database URLs', () => { expect(() => assertSafetyDatabaseUrl(undefined)).toThrow( 'Dedicated stock_bot_safety database required' ); @@ -170,212 +182,223 @@ describe('PostgreSQL MCP copilot executor safety guard', () => { expect(() => assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev') ).toThrow('Dedicated stock_bot_safety database required'); + expect( + assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test') + ).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test'); }); }); -describe.skipIf(!url)('PostgreSQL MCP copilot executor integration', () => { - test('enforces effective 10s statement_timeout, 2s lock_timeout, preserved search_path, max 4 backends, and 0 backends after close', async () => { +describe.skipIf(!url)('PostgreSQL MCP copilot executor (real PostgreSQL)', () => { + test('enforces effective 10s statement_timeout and 2s lock_timeout even when URL specifies overrides', async () => { const f = await createIsolatedFixture(); - const appName = `copilot_exec_${randomUUID().replaceAll('-', '').slice(0, 12)}`; - const postgresUrl = buildSchemaUrl(f.safeUrl, f.schema, { application_name: appName }); + const appName = `copilot_timeouts_${randomUUID().slice(0, 8)}`; + const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName, { + statement_timeout: '99999', + lock_timeout: '99999', + query_timeout: '99999', + }); - const handle = await openResearchCopilotExecutor( - { postgresUrl, postgresSchema: f.schema }, - { env: {} } - ); + const handle = await openResearchCopilotExecutor({ postgresUrl: executorUrl }); cleanup.push(() => handle.close()); - const settings = await handle.executor.query<{ - statement_timeout: string; - lock_timeout: string; - search_path: string; - current_schema: string; - }>( - `SELECT - current_setting('statement_timeout') AS statement_timeout, - current_setting('lock_timeout') AS lock_timeout, - current_setting('search_path') AS search_path, - current_schema() AS current_schema` + const { rows: stmtRows } = await handle.executor.query<{ statement_timeout: string }>( + 'SHOW statement_timeout' + ); + const { rows: lockRows } = await handle.executor.query<{ lock_timeout: string }>( + 'SHOW lock_timeout' ); - expect(settings.rows[0]?.statement_timeout).toBe('10s'); - expect(settings.rows[0]?.lock_timeout).toBe('2s'); - expect(settings.rows[0]?.current_schema).toBe(f.schema); - expect(settings.rows[0]?.search_path).toContain(f.schema); - - // Run 8 concurrent queries and observe peak backend count <= 4. - const sleeps = Array.from({ length: 8 }, () => - handle.executor.query('SELECT pg_sleep(0.08)') - ); - await new Promise(resolve => setTimeout(resolve, 30)); - const active = await f.admin.query<{ count: string }>( - 'SELECT count(*)::text AS count FROM pg_stat_activity WHERE application_name = $1', - [appName] - ); - const activeCount = Number(active.rows[0]?.count ?? '0'); - expect(activeCount).toBeGreaterThanOrEqual(1); - expect(activeCount).toBeLessThanOrEqual(RESEARCH_COPILOT_PG_POOL_MAX); - - await Promise.all(sleeps); - - await handle.close(); - // Idempotent second close. - await handle.close(); - - // Post-close query rejects immediately with EXECUTOR_CLOSED. - let closedErr: unknown; - try { - await handle.executor.query('SELECT 1'); - } catch (error) { - closedErr = error; - } - expect(closedErr).toBeInstanceOf(ResearchCopilotExecutorError); - expect((closedErr as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED'); - - const remaining = await waitForZeroBackends(f.admin, appName); - expect(remaining).toBe(0); + expect(stmtRows[0]?.statement_timeout).toBe('10s'); + expect(lockRows[0]?.lock_timeout).toBe('2s'); }); - test('preserves PGOPTIONS search_path while overriding weakening timeouts', async () => { + test('preserves PGOPTIONS search_path when URL omits options while enforcing 10s/2s timeouts', async () => { const f = await createIsolatedFixture(); + const appName = `copilot_pgoptions_${randomUUID().slice(0, 8)}`; + + // Build a URL with NO options query parameter so pg must honor PGOPTIONS. const parsed = new URL(f.safeUrl); parsed.searchParams.delete('options'); + parsed.searchParams.set('application_name', appName); - const handle = await openResearchCopilotExecutor( - { postgresUrl: parsed.toString(), postgresSchema: f.schema }, - { env: { PGOPTIONS: `-c search_path=${f.schema} -c statement_timeout=0 -c lock_timeout=0` } } - ); + const previousPgOptions = process.env.PGOPTIONS; + process.env.PGOPTIONS = `-c search_path=${f.schema} -c statement_timeout=99999 -c lock_timeout=88888`; + cleanup.push(() => { + if (previousPgOptions === undefined) { + delete process.env.PGOPTIONS; + } else { + process.env.PGOPTIONS = previousPgOptions; + } + }); + + const handle = await openResearchCopilotExecutor({ postgresUrl: parsed.toString() }); cleanup.push(() => handle.close()); - const settings = await handle.executor.query<{ - statement_timeout: string; - lock_timeout: string; - current_schema: string; - }>( - `SELECT - current_setting('statement_timeout') AS statement_timeout, - current_setting('lock_timeout') AS lock_timeout, - current_schema() AS current_schema` + const { rows: schemaRows } = await handle.executor.query<{ current_schema: string | null }>( + 'SELECT current_schema() AS current_schema' + ); + const { rows: stmtRows } = await handle.executor.query<{ statement_timeout: string }>( + 'SHOW statement_timeout' + ); + const { rows: lockRows } = await handle.executor.query<{ lock_timeout: string }>( + 'SHOW lock_timeout' ); - expect(settings.rows[0]?.statement_timeout).toBe('10s'); - expect(settings.rows[0]?.lock_timeout).toBe('2s'); - expect(settings.rows[0]?.current_schema).toBe(f.schema); + expect(schemaRows[0]?.current_schema).toBe(f.schema); + expect(stmtRows[0]?.statement_timeout).toBe('10s'); + expect(lockRows[0]?.lock_timeout).toBe('2s'); - await handle.close(); + // Verify unqualified findings writes and reads resolve against the PGOPTIONS search_path. + const writePort = createPostgresFindingWritePort({ executor: handle.executor }); + const readers = createPostgresKnowledgeReaders({ executor: handle.executor }); + const created = await writePort.appendFinding( + { + id: 'finding-pgoptions-0001', + kind: 'finding', + title: 'PGOPTIONS search_path finding', + summary: 'Resolved via PGOPTIONS search_path without explicit schema option.', + status: 'pending_review', + createdAt: FIXED_TS, + trialRefs: [], + evidenceRefs: [], + }, + 'idem-pgoptions-0001' + ); + expect(created.status).toBe('created'); + + const listed = await readers.listFindings({ query: 'PGOPTIONS search_path' }); + expect(listed).toHaveLength(1); + expect(listed[0]?.id).toBe('finding-pgoptions-0001'); }); - test('supports idempotent finding replay (same-ID and same-key) and Vault-fenced trial visibility in migrated schema', async () => { + test('supports migrated findings writes, reads, idempotent replay, and real 23505 preservation', async () => { const f = await createIsolatedFixture(); - const postgresUrl = buildSchemaUrl(f.safeUrl, f.schema); + const appName = `copilot_findings_${randomUUID().slice(0, 8)}`; + const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName); - // Seed one trial strictly before the 2025-06-30 UTC Vault cutoff and one on the cutoff. - await f.migrationPool.query( + const handle = await openResearchCopilotExecutor({ postgresUrl: executorUrl }); + cleanup.push(() => handle.close()); + + const writePort = createPostgresFindingWritePort({ + executor: handle.executor, + schema: f.schema, + }); + const readers = createPostgresKnowledgeReaders({ + executor: handle.executor, + schema: f.schema, + }); + + const record = { + id: 'finding-exec-0001', + kind: 'finding' as const, + title: 'Executor integration finding', + summary: 'Verified against migrated schema via openResearchCopilotExecutor.', + status: 'pending_review' as const, + createdAt: FIXED_TS, + trialRefs: ['101'], + evidenceRefs: ['snap:2025-06-29:ic'], + }; + + const first = await writePort.appendFinding(record, 'idem-key-0001'); + expect(first).toEqual({ + status: 'created', + id: 'finding-exec-0001', + createdAt: FIXED_TS, + }); + + // Same-ID, same-key replay must return the original finding and timestamp. + const replay = await writePort.appendFinding(record, 'idem-key-0001'); + expect(replay).toEqual({ + status: 'replayed', + id: 'finding-exec-0001', + createdAt: FIXED_TS, + }); + + // Unkeyed duplicate-PK insert hits PostgreSQL's primary-key constraint directly; + // verify the executor preserves SQLSTATE 23505 without leaking driver fields. + let pkCollisionErr: unknown; + try { + await writePort.appendFinding(record); + } catch (err) { + pkCollisionErr = err; + } + expect(pkCollisionErr).toBeInstanceOf(ResearchCopilotExecutorError); + expect((pkCollisionErr as ResearchCopilotExecutorError).code).toBe('23505'); + expect('cause' in (pkCollisionErr as object)).toBe(false); + expect('detail' in (pkCollisionErr as object)).toBe(false); + + const listed = await readers.listFindings({ query: 'Executor integration' }); + expect(listed).toHaveLength(1); + expect(listed[0]?.id).toBe('finding-exec-0001'); + expect(listed[0]?.trialRefs).toEqual(['101']); + + // Executor remains usable after 23505 collision. + const { rows } = await handle.executor.query<{ count: number }>( + `SELECT count(*)::int AS count FROM "${f.schema}".findings` + ); + expect(rows[0]?.count).toBe(1); + }); + + test('enforces Vault cutoff when wired into createPostgresTrialRefLookupPort', async () => { + const f = await createIsolatedFixture(); + await f.setupPool.query( `INSERT INTO trial_ledger ( trial_id, principal_id, stage, universe_market, horizon_bucket, expression_hash, sample_start, sample_end, n_obs, sharpe_unann, skewness, kurtosis, daily_series ) OVERRIDING SYSTEM VALUE VALUES - (1, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), - '2020-01-01'::date, '2025-06-29'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[]), - (2, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('b', 64), - '2020-01-01'::date, '2025-06-30'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])` + (1, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), '2020-01-01'::date, '2025-06-29'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[]), + (2, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64), '2020-01-01'::date, '2025-06-30'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])` ); - const handle = await openResearchCopilotExecutor( - { postgresUrl, postgresSchema: f.schema }, - { env: {} } - ); + const appName = `copilot_vault_${randomUUID().slice(0, 8)}`; + const handle = await openResearchCopilotExecutor({ + postgresUrl: buildExecutorUrl(f.safeUrl, f.schema, appName), + }); cleanup.push(() => handle.close()); - // 1. Vault-fenced trial_ledger visibility check. const trialLookup = createPostgresTrialRefLookupPort({ executor: handle.executor, - schema: f.schema, vaultCutoffTs: VAULT_CUTOFF_TS, + schema: f.schema, }); + expect(await trialLookup.hasResearchVisibleTrial('1')).toBe(true); expect(await trialLookup.hasResearchVisibleTrial('2')).toBe(false); + }); - // 2. Findings idempotent replay (both same-key ON CONFLICT and same-ID 23505 paths). - const writePort = createPostgresFindingWritePort({ - executor: handle.executor, - schema: f.schema, + test('caps concurrent backend connections at 4 and disconnects all backends on close()', async () => { + const f = await createIsolatedFixture(); + const appName = `copilot_cap_${randomUUID().slice(0, 8)}`; + const handle = await openResearchCopilotExecutor({ + postgresUrl: buildExecutorUrl(f.safeUrl, f.schema, appName), }); + cleanup.push(() => handle.close()); - const findingId = `finding-${randomUUID()}`; - const idempotencyKey = `key-${randomUUID()}`; - const baseFinding: FiledFindingRecord = { - id: findingId, - kind: 'finding', - title: 'Executor replay verification finding', - status: 'pending_review', - createdAt: FIXED_TS, - summary: 'Verifies SQLSTATE 23505 and ON CONFLICT replay through openResearchCopilotExecutor.', - trialRefs: ['1'], - evidenceRefs: ['evidence:e1'], - }; - - const first = await writePort.appendFinding(baseFinding, idempotencyKey); - expect(first).toEqual({ - status: 'created', - id: findingId, - createdAt: FIXED_TS, - }); - - // Same-key replay with a different ID and later timestamp (ON CONFLICT DO NOTHING path) - // must return the original finding and timestamp. - const sameKeyReplay = await writePort.appendFinding( - { - ...baseFinding, - id: `finding-${randomUUID()}`, - createdAt: '2026-02-01T00:00:00.000Z', - }, - idempotencyKey + const results = await Promise.all( + Array.from({ length: RESEARCH_COPILOT_PG_POOL_MAX + 2 }, () => + handle.executor.query<{ pid: number }>( + 'SELECT pg_backend_pid() AS pid FROM pg_sleep(0.15)' + ) + ) ); - expect(sameKeyReplay).toEqual({ - status: 'replayed', - id: findingId, - createdAt: FIXED_TS, - }); - - // Same-ID, same-key replay must also return the original receipt and keep 1 stored row. - const sameIdReplay = await writePort.appendFinding( - { - ...baseFinding, - createdAt: '2026-03-01T00:00:00.000Z', - }, - idempotencyKey - ); - expect(sameIdReplay).toEqual({ - status: 'replayed', - id: findingId, - createdAt: FIXED_TS, - }); - - // Unkeyed duplicate-PK insert hits PostgreSQL's primary-key constraint directly; - // verify the executor observes and preserves real SQLSTATE 23505 without leaking driver fields. - let pkCollisionErr: unknown; - try { - await writePort.appendFinding({ - ...baseFinding, - createdAt: '2026-04-01T00:00:00.000Z', - }); - } catch (error) { - pkCollisionErr = error; - } - expect(pkCollisionErr).toBeInstanceOf(Error); - expect((pkCollisionErr as { code?: string }).code).toBe('23505'); - expect((pkCollisionErr as Error).message).toBe('PostgreSQL research copilot query failed.'); - expect('cause' in (pkCollisionErr as Error)).toBe(false); - expect('detail' in (pkCollisionErr as Error)).toBe(false); - - const rowCount = await handle.executor.query<{ count: string }>( - `SELECT count(*)::text AS count FROM ${f.schema}.findings` - ); - expect(rowCount.rows[0]?.count).toBe('1'); + const distinctPids = new Set(results.map(r => r.rows[0]?.pid)); + expect(distinctPids.size).toBeGreaterThanOrEqual(1); + expect(distinctPids.size).toBeLessThanOrEqual(RESEARCH_COPILOT_PG_POOL_MAX); await handle.close(); + + const remainingBackends = await waitForZeroBackends(f.admin, appName); + expect(remainingBackends).toBe(0); + + let caught: unknown; + try { + await handle.executor.query('SELECT 1'); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(ResearchCopilotExecutorError); + expect((caught as ResearchCopilotExecutorError).code).toBe('EXECUTOR_CLOSED'); }); });