stock-bot/test/postgres/mcp-trial-ref-adapter.test.ts
2026-12-02 11:11:27 -05:00

364 lines
13 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 PoolClient, type PoolConfig } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
import {
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
type FileFindingResultPayload,
type TrialRefExecutor,
createFileFindingTool,
createMcpServer,
createPostgresFindingWritePort,
createPostgresTrialRefPort,
} from '../../libs/research/src/mcp/index';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('mcp-trial-ref-adapter-pg-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url));
// Non-midnight UTC cutoff on 2025-06-30; research-visible requires sample_end < 2025-06-30.
const VAULT_CUTOFF_TS = Date.UTC(2025, 5, 30, 15, 45, 30, 500);
const FIXED_TS = '2026-01-15T12:34:56.789Z';
const cleanup: (() => Promise<void> | void)[] = [];
afterEach(async () => {
// Run every cleanup step even if an earlier one fails, then surface the first failure.
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 createPgExecutor(
queryable: Pick<Pool, 'query'> | Pick<PoolClient, 'query'>
): TrialRefExecutor {
return {
query<Row = Record<string, unknown>>(
text: string,
params?: readonly unknown[]
): Promise<{ readonly rows: readonly Row[] }> {
return queryable.query(
text,
params === undefined ? undefined : [...params]
) as unknown as Promise<{ readonly rows: readonly Row[] }>;
},
};
}
function buildIsolatedPoolConfig(connectionString: string | undefined, 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 schemaOptions = `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`;
const options = [...existingOptions, schemaOptions].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 });
// Registered before CREATE SCHEMA so the admin pool closes even if creation or teardown fails.
cleanup.push(() => admin.end());
await admin.query(`CREATE SCHEMA ${schema}`);
cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`).then(() => undefined));
const pool = new Pool(buildIsolatedPoolConfig(safeUrl, schema));
cleanup.push(() => pool.end());
const { rows: schemaRows } = await pool.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)}`
);
}
// Bootstrap pre-additive tables needed by the research migration track.
for (const filename of [
'06-create-backtest-tables.sql',
'07-fix-execution-time-type.sql',
'08-create-runs-table.sql',
]) {
await pool.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: () => pool.connect(),
}),
});
await runPostgresMigrations(postgres, { track: 'research' });
return { admin, pool, schema };
}
async function insertTrialRow(
pool: Pool,
sampleEnd: string,
hashChar: string
): Promise<string> {
const { rows } = await pool.query<{ trial_id: string }>(
`INSERT INTO trial_ledger (
principal_id,
stage,
universe_market,
horizon_bucket,
expression_hash,
sample_start,
sample_end,
n_obs,
sharpe_unann,
skewness,
kurtosis,
daily_series
)
VALUES (
'operator',
'signal_ic',
'US_EQ',
'swing_1_10d',
$1,
'2024-01-02'::date,
$2::date,
252,
0.05,
-0.1,
3.2,
ARRAY[0.01, -0.005]::real[]
)
RETURNING trial_id::text AS trial_id`,
[hashChar.repeat(64), sampleEnd]
);
return rows[0]!.trial_id;
}
describe('PostgreSQL trial-ref adapter 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');
expect(() =>
assertSafetyDatabaseUrl('socket:/stock_bot_safety?db=trading_bot')
).toThrow('Dedicated stock_bot_safety database required');
expect(() =>
assertSafetyDatabaseUrl('http://127.0.0.1:5432/stock_bot_safety_test')
).toThrow('Dedicated stock_bot_safety database required');
expect(() => assertSafetyDatabaseUrl('not-a-valid-url')).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');
});
test('preserves isolated schema search_path precedence over URL startup options', () => {
const schema = 'stock_bot_safety_trial_ref_options';
const urlWithOptions =
'postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test?options=-c%20statement_timeout%3D30000%20-c%20search_path%3Dpublic';
const poolConfig = buildIsolatedPoolConfig(urlWithOptions, schema);
expect(new URL(poolConfig.connectionString!).searchParams.has('options')).toBe(false);
const client = new Client(poolConfig);
const resolvedOptions = (client as unknown as { connectionParameters: { options?: string } })
.connectionParameters.options;
expect(resolvedOptions).toBe(
`-c statement_timeout=30000 -c search_path=public -c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`
);
});
});
describe.skipIf(!url)('PostgreSQL MCP trial-ref adapter', () => {
test('enforces strict sample_end < vaultCutoffDate across default search_path and explicit schema', async () => {
const f = await createIsolatedFixture();
const beforeCutoffId = await insertTrialRow(f.pool, '2025-06-29', 'a');
const onCutoffId = await insertTrialRow(f.pool, '2025-06-30', 'b');
const afterCutoffId = await insertTrialRow(f.pool, '2025-07-01', 'c');
const defaultPort = createPostgresTrialRefPort({
executor: createPgExecutor(f.pool),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(await defaultPort.hasResearchVisibleTrial(beforeCutoffId)).toBe(true);
expect(await defaultPort.hasResearchVisibleTrial(onCutoffId)).toBe(false);
expect(await defaultPort.hasResearchVisibleTrial(afterCutoffId)).toBe(false);
expect(await defaultPort.hasResearchVisibleTrial('999999999')).toBe(false);
expect(await defaultPort.hasResearchVisibleTrial('1; DROP TABLE trial_ledger')).toBe(false);
// Largest bigint binds through $1::bigint without overflow and is simply unknown.
expect(await defaultPort.hasResearchVisibleTrial('9223372036854775807')).toBe(false);
const { rows: ledgerCount } = await f.pool.query<{ c: number }>(
'SELECT count(*)::int AS c FROM trial_ledger'
);
expect(ledgerCount[0]?.c).toBe(3);
// Explicit schema option against the admin pool (default search_path)
const scopedPort = createPostgresTrialRefPort({
executor: createPgExecutor(f.admin),
vaultCutoffTs: VAULT_CUTOFF_TS,
schema: f.schema,
});
expect(await scopedPort.hasResearchVisibleTrial(beforeCutoffId)).toBe(true);
expect(await scopedPort.hasResearchVisibleTrial(onCutoffId)).toBe(false);
expect(await scopedPort.hasResearchVisibleTrial(afterCutoffId)).toBe(false);
expect(await scopedPort.hasResearchVisibleTrial('999999999')).toBe(false);
});
test('composes with createFileFindingTool and createPostgresFindingWritePort through MCP', async () => {
const f = await createIsolatedFixture();
const visibleTrialId = await insertTrialRow(f.pool, '2025-06-29', '1');
const equalCutoffTrialId = await insertTrialRow(f.pool, '2025-06-30', '2');
const afterCutoffTrialId = await insertTrialRow(f.pool, '2025-07-01', '3');
const executor = createPgExecutor(f.pool);
const trialLookup = createPostgresTrialRefPort({
executor,
vaultCutoffTs: VAULT_CUTOFF_TS,
});
const writePort = createPostgresFindingWritePort({ executor });
let idSeq = 0;
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [
createFileFindingTool({
port: writePort,
trialLookup,
newId: () => {
idSeq += 1;
return `finding-trial-ref-${idSeq}`;
},
now: () => new Date(FIXED_TS),
}),
],
});
const callFileFinding = async (args: Record<string, unknown>) => {
const raw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 'req-file-finding',
method: 'tools/call',
params: {
name: 'file_finding',
arguments: args,
},
})
);
expect(raw).not.toBeNull();
const parsed = JSON.parse(raw!) as {
result: { isError?: boolean; content: Array<{ text: string }> };
};
return parsed.result;
};
// Visible trial (sample_end = 2025-06-29 < 2025-06-30) succeeds and persists pending_review row.
const okRes = await callFileFinding({
kind: 'finding',
title: 'Pre-cutoff signal holds across US equities',
summary: 'Positive IC verified strictly before the Vault cutoff.',
trialRefs: [visibleTrialId],
evidenceRefs: ['snap:2025-06-29:ic'],
});
expect(okRes.isError).toBeUndefined();
const receipt = JSON.parse(okRes.content[0]!.text) as FileFindingResultPayload;
expect(receipt).toEqual({
id: 'finding-trial-ref-1',
createdAt: FIXED_TS,
created: true,
});
const storedRows = (
await f.pool.query<{ id: string; status: string; trial_refs: string[] }>(
'SELECT id, status, trial_refs FROM findings ORDER BY id ASC'
)
).rows;
expect(storedRows).toEqual([
{
id: 'finding-trial-ref-1',
status: 'pending_review',
trial_refs: [visibleTrialId],
},
]);
// Vault-only (equal to cutoff, after cutoff) and unknown citations all return the same error with zero rows added.
for (const deniedRef of [equalCutoffTrialId, afterCutoffTrialId, '999999999']) {
const deniedRes = await callFileFinding({
kind: 'dead_end',
title: 'Should be rejected by Vault fence',
summary: 'References non-visible trial.',
trialRefs: [deniedRef],
});
expect(deniedRes.isError).toBe(true);
expect(deniedRes.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
}
const totalFindings = (
await f.pool.query<{ c: number }>('SELECT count(*)::int AS c FROM findings')
).rows[0]?.c;
expect(totalFindings).toBe(1);
});
});