stock-bot/test/postgres/mcp-copilot-executor.test.ts

365 lines
12 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 {
type FiledFindingRecord,
createPostgresFindingWritePort,
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));
// 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> | 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 buildSchemaUrl(
connectionString: string,
schema: string,
extraQuery?: Record<string, string>
): 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 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,
};
}
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();
});
await admin.query(`CREATE SCHEMA ${schema}`);
const migrationPool = new Pool(buildIsolatedPoolConfig(safeUrl, schema));
cleanup.push(async () => {
await migrationPool.end();
});
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'));
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', {
get: () => ({
connect: () => migrationPool.connect(),
}),
});
await runPostgresMigrations(postgres, { track: 'research' });
return { admin, migrationPool, safeUrl, schema };
}
async function waitForZeroBackends(
admin: Pool,
appName: string,
timeoutMs = 3000
): Promise<number> {
const deadline = Date.now() + timeoutMs;
let lastCount = -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]
);
lastCount = Number(rows[0]?.count ?? '0');
if (lastCount === 0) {
return 0;
}
await new Promise(resolve => setTimeout(resolve, 25));
}
return lastCount;
}
describe('PostgreSQL MCP copilot executor safety guard', () => {
test('rejects unsafe database targets before connecting', () => {
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');
});
});
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 () => {
const f = await createIsolatedFixture();
const appName = `copilot_exec_${randomUUID().replaceAll('-', '').slice(0, 12)}`;
const postgresUrl = buildSchemaUrl(f.safeUrl, f.schema, { application_name: appName });
const handle = await openResearchCopilotExecutor(
{ postgresUrl, postgresSchema: f.schema },
{ env: {} }
);
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`
);
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);
});
test('preserves PGOPTIONS search_path while overriding weakening timeouts', async () => {
const f = await createIsolatedFixture();
const parsed = new URL(f.safeUrl);
parsed.searchParams.delete('options');
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` } }
);
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`
);
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);
await handle.close();
});
test('supports idempotent finding replay (same-ID and same-key) and Vault-fenced trial visibility in migrated schema', async () => {
const f = await createIsolatedFixture();
const postgresUrl = buildSchemaUrl(f.safeUrl, f.schema);
// Seed one trial strictly before the 2025-06-30 UTC Vault cutoff and one on the cutoff.
await f.migrationPool.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[])`
);
const handle = await openResearchCopilotExecutor(
{ postgresUrl, postgresSchema: f.schema },
{ env: {} }
);
cleanup.push(() => handle.close());
// 1. Vault-fenced trial_ledger visibility check.
const trialLookup = createPostgresTrialRefLookupPort({
executor: handle.executor,
schema: f.schema,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
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,
});
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
);
expect(sameKeyReplay).toEqual({
status: 'replayed',
id: findingId,
createdAt: FIXED_TS,
});
// Same-ID replay with the same idempotencyKey triggers PostgreSQL PK SQLSTATE 23505;
// executor must preserve SQLSTATE 23505 so the adapter resolves the original finding.
const sameIdReplay = await writePort.appendFinding(
{
...baseFinding,
createdAt: '2026-03-01T00:00:00.000Z',
},
idempotencyKey
);
expect(sameIdReplay).toEqual({
status: 'replayed',
id: findingId,
createdAt: FIXED_TS,
});
const rowCount = await handle.executor.query<{ count: string }>(
`SELECT count(*)::text AS count FROM ${f.schema}.findings`
);
expect(rowCount.rows[0]?.count).toBe('1');
await handle.close();
});
});