404 lines
15 KiB
TypeScript
404 lines
15 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { readFileSync } from 'node:fs';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { afterEach, describe, expect, test } from 'bun:test';
|
|
import { Client, Pool, type PoolConfig } from 'pg';
|
|
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
|
import {
|
|
PostgreSQLClient,
|
|
RESEARCH_COPILOT_PG_POOL_MAX,
|
|
ResearchCopilotExecutorError,
|
|
openResearchCopilotExecutor,
|
|
runPostgresMigrations,
|
|
} from '@stock-bot/postgres';
|
|
import {
|
|
createPostgresFindingWritePort,
|
|
createPostgresKnowledgeReaders,
|
|
createPostgresTrialRefLookupPort,
|
|
} from '../../libs/research/src/mcp/index';
|
|
|
|
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
|
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));
|
|
|
|
const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 0, 0, 0, 0);
|
|
const FIXED_TS = '2026-01-15T12:34:56.789Z';
|
|
|
|
const cleanup: Array<() => Promise<void> | void> = [];
|
|
afterEach(async () => {
|
|
let firstError: unknown;
|
|
for (const close of cleanup.splice(0).reverse()) {
|
|
try {
|
|
await close();
|
|
} catch (err) {
|
|
firstError ??= err;
|
|
}
|
|
}
|
|
if (firstError !== undefined) {
|
|
throw firstError;
|
|
}
|
|
});
|
|
|
|
function assertSafetyDatabaseUrl(connectionString: string | undefined): string {
|
|
if (!connectionString) {
|
|
throw new Error('Dedicated stock_bot_safety database required');
|
|
}
|
|
let parsed: URL;
|
|
try {
|
|
parsed = new URL(connectionString);
|
|
} catch {
|
|
throw new Error('Dedicated stock_bot_safety database required');
|
|
}
|
|
if (parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') {
|
|
throw new Error('Dedicated stock_bot_safety database required');
|
|
}
|
|
const client = new Client({ connectionString });
|
|
const effectiveDb = (
|
|
client as unknown as { connectionParameters?: { database?: unknown } }
|
|
).connectionParameters?.database;
|
|
if (
|
|
typeof effectiveDb !== 'string' ||
|
|
!effectiveDb.startsWith('stock_bot_safety') ||
|
|
!parsed.pathname.startsWith('/stock_bot_safety')
|
|
) {
|
|
throw new Error('Dedicated stock_bot_safety database required');
|
|
}
|
|
return connectionString;
|
|
}
|
|
|
|
function buildIsolatedPoolConfig(connectionString: string, schema: string): PoolConfig {
|
|
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<Record<string, string>>
|
|
): 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(() => admin.end());
|
|
await admin.query(`CREATE SCHEMA ${schema}`);
|
|
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 setupPool.query(readFileSync(`${initDir}${filename}`, 'utf8'));
|
|
}
|
|
|
|
const postgres = new PostgreSQLClient(
|
|
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
|
logger
|
|
);
|
|
Object.defineProperty(postgres, 'connectionPool', {
|
|
get: () => ({
|
|
connect: () => setupPool.connect(),
|
|
}),
|
|
});
|
|
|
|
await runPostgresMigrations(postgres, { track: 'research' });
|
|
|
|
return { admin, setupPool, schema, safeUrl };
|
|
}
|
|
|
|
async function waitForZeroBackends(admin: Pool, applicationName: string): Promise<number> {
|
|
const deadline = Date.now() + 2_000;
|
|
let count = -1;
|
|
while (Date.now() < deadline) {
|
|
const { rows } = await admin.query<{ c: number }>(
|
|
'SELECT count(*)::int AS c FROM pg_stat_activity WHERE application_name = $1',
|
|
[applicationName]
|
|
);
|
|
count = rows[0]?.c ?? -1;
|
|
if (count === 0) {
|
|
return 0;
|
|
}
|
|
await new Promise(resolve => setTimeout(resolve, 25));
|
|
}
|
|
return count;
|
|
}
|
|
|
|
describe('PostgreSQL MCP copilot executor safety guard', () => {
|
|
test('rejects missing or non-safety database URLs', () => {
|
|
expect(() => assertSafetyDatabaseUrl(undefined)).toThrow(
|
|
'Dedicated stock_bot_safety database required'
|
|
);
|
|
expect(() =>
|
|
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot')
|
|
).toThrow('Dedicated stock_bot_safety database required');
|
|
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 (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_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: executorUrl });
|
|
cleanup.push(() => handle.close());
|
|
|
|
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(stmtRows[0]?.statement_timeout).toBe('10s');
|
|
expect(lockRows[0]?.lock_timeout).toBe('2s');
|
|
});
|
|
|
|
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 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 { 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(schemaRows[0]?.current_schema).toBe(f.schema);
|
|
expect(stmtRows[0]?.statement_timeout).toBe('10s');
|
|
expect(lockRows[0]?.lock_timeout).toBe('2s');
|
|
|
|
// 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 migrated findings writes, reads, idempotent replay, and real 23505 preservation', async () => {
|
|
const f = await createIsolatedFixture();
|
|
const appName = `copilot_findings_${randomUUID().slice(0, 8)}`;
|
|
const executorUrl = buildExecutorUrl(f.safeUrl, f.schema, appName);
|
|
|
|
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('a', 64), '2020-01-01'::date, '2025-06-30'::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])`
|
|
);
|
|
|
|
const appName = `copilot_vault_${randomUUID().slice(0, 8)}`;
|
|
const handle = await openResearchCopilotExecutor({
|
|
postgresUrl: buildExecutorUrl(f.safeUrl, f.schema, appName),
|
|
});
|
|
cleanup.push(() => handle.close());
|
|
|
|
const trialLookup = createPostgresTrialRefLookupPort({
|
|
executor: handle.executor,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
schema: f.schema,
|
|
});
|
|
|
|
expect(await trialLookup.hasResearchVisibleTrial('1')).toBe(true);
|
|
expect(await trialLookup.hasResearchVisibleTrial('2')).toBe(false);
|
|
});
|
|
|
|
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 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)'
|
|
)
|
|
)
|
|
);
|
|
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');
|
|
});
|
|
});
|