stock-bot/test/postgres/mcp-trial-ref-adapter.test.ts
2026-12-02 09:25:59 -05:00

283 lines
10 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 { Pool, type PoolClient } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
import {
type AppendFindingResult,
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
type FiledFindingRecord,
createFileFindingTool,
createMcpServer,
createPostgresTrialRefLookupPort,
type TrialRefExecutor,
} 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));
// 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 MAX_BIGINT_REF = '9223372036854775807';
// 2^53 + 1 is not representable as a JS number; Number('9007199254740993') === 9007199254740992.
const ABOVE_SAFE_INT_REF = '9007199254740993';
const ABOVE_SAFE_INT_NEIGHBOR_REF = '9007199254740992';
const cleanup: (() => Promise<void> | void)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
function assertSafetyDatabaseUrl(connectionString: string | undefined): string {
if (!connectionString || !new URL(connectionString).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Dedicated stock_bot_safety database required');
}
return connectionString;
}
function createPgExecutor(queryable: Pool | PoolClient): 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[] }>;
},
};
}
async function createIsolatedFixture() {
const safeUrl = assertSafetyDatabaseUrl(url);
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: safeUrl });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: safeUrl,
options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
});
const readOnlyPool = new Pool({
connectionString: safeUrl,
options: `-c search_path=${schema} -c default_transaction_read_only=on -c statement_timeout=5000`,
});
cleanup.push(async () => {
await readOnlyPool.end();
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
// 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' });
await seedTrials(pool);
return { admin, pool, readOnlyPool, schema };
}
async function seedTrials(pool: Pool): Promise<void> {
const trials: readonly (readonly [string, string])[] = [
['1', '2025-06-29'], // last research-visible day
['2', '2025-06-30'], // sample_end == cutoff: Vault-only
['3', '2025-07-15'], // sample_end after cutoff: Vault-only
[ABOVE_SAFE_INT_REF, '2024-01-31'],
[MAX_BIGINT_REF, '2020-01-31'],
];
for (const [trialId, sampleEnd] of trials) {
await pool.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::bigint, 'operator', 'signal_ic', 'US_EQ', 'swing_1_10d', repeat('a', 64),
'2020-01-01'::date, $2::date, 2, 0, 0, 3, ARRAY[0.1, 0.2]::real[])`,
[trialId, sampleEnd]
);
}
}
describe.skipIf(!url)('PostgreSQL MCP trial-ref lookup adapter', () => {
test('exposes only trials with sample_end strictly before the UTC Vault cutoff date', async () => {
const f = await createIsolatedFixture();
const port = createPostgresTrialRefLookupPort({
executor: createPgExecutor(f.pool),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(await port.hasResearchVisibleTrial('1')).toBe(true);
expect(await port.hasResearchVisibleTrial('2')).toBe(false);
expect(await port.hasResearchVisibleTrial('3')).toBe(false);
expect(await port.hasResearchVisibleTrial('4')).toBe(false); // unknown
expect(await port.hasResearchVisibleTrial(MAX_BIGINT_REF)).toBe(true);
});
test('matches BIGINT ids above 2^53 exactly without numeric coercion', async () => {
const f = await createIsolatedFixture();
const port = createPostgresTrialRefLookupPort({
executor: createPgExecutor(f.pool),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(await port.hasResearchVisibleTrial(ABOVE_SAFE_INT_REF)).toBe(true);
expect(await port.hasResearchVisibleTrial(ABOVE_SAFE_INT_NEIGHBOR_REF)).toBe(false);
});
test('moves the visibility boundary with the cutoff date, including a near-midnight UTC instant', async () => {
const f = await createIsolatedFixture();
const executor = createPgExecutor(f.pool);
const lastMsOfCutoffDay = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: Date.UTC(2025, 5, 30, 23, 59, 59, 999),
});
const nextDay = createPostgresTrialRefLookupPort({
executor,
vaultCutoffTs: Date.UTC(2025, 6, 1, 0, 0, 0, 0),
});
expect(await lastMsOfCutoffDay.hasResearchVisibleTrial('2')).toBe(false);
expect(await nextDay.hasResearchVisibleTrial('2')).toBe(true);
expect(await nextDay.hasResearchVisibleTrial('3')).toBe(false);
});
test('runs in a read-only session and is unaffected by the session TimeZone', async () => {
const f = await createIsolatedFixture();
const client = await f.readOnlyPool.connect();
try {
await client.query("SET TimeZone = 'Pacific/Kiritimati'");
const port = createPostgresTrialRefLookupPort({
executor: createPgExecutor(client),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(await port.hasResearchVisibleTrial('1')).toBe(true);
expect(await port.hasResearchVisibleTrial('2')).toBe(false);
} finally {
await client.query('RESET TimeZone');
client.release();
}
});
test('qualifies trial_ledger with an explicit schema when the session search_path does not include it', async () => {
const f = await createIsolatedFixture();
const client = await f.admin.connect();
try {
// Pin a search_path that cannot contain trial_ledger, independent of the shared public schema.
await client.query('SET search_path TO pg_catalog');
const unqualified = createPostgresTrialRefLookupPort({
executor: createPgExecutor(client),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
const qualified = createPostgresTrialRefLookupPort({
executor: createPgExecutor(client),
vaultCutoffTs: VAULT_CUTOFF_TS,
schema: f.schema,
});
expect(await qualified.hasResearchVisibleTrial('1')).toBe(true);
expect(await qualified.hasResearchVisibleTrial('2')).toBe(false);
// Missing relation must surface as a rejection, never as "not visible".
await expect(unqualified.hasResearchVisibleTrial('1')).rejects.toMatchObject({
code: '42P01',
});
} finally {
await client.query('RESET search_path');
client.release();
}
});
test('leaves trial_ledger untouched and never executes an injection-shaped ref', async () => {
const f = await createIsolatedFixture();
const port = createPostgresTrialRefLookupPort({
executor: createPgExecutor(f.pool),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
expect(await port.hasResearchVisibleTrial('1 OR 1=1')).toBe(false);
expect(await port.hasResearchVisibleTrial("1'; DELETE FROM trial_ledger; --")).toBe(false);
const { rows } = await f.pool.query<{ n: string }>('SELECT count(*)::text AS n FROM trial_ledger');
expect(rows[0]!.n).toBe('5');
});
test('files through createFileFindingTool only when every trial ref is research-visible', async () => {
const f = await createIsolatedFixture();
const trialLookup = createPostgresTrialRefLookupPort({
executor: createPgExecutor(f.pool),
vaultCutoffTs: VAULT_CUTOFF_TS,
});
const appended: FiledFindingRecord[] = [];
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [
createFileFindingTool({
port: {
async appendFinding(record: FiledFindingRecord): Promise<AppendFindingResult> {
appended.push(record);
return { status: 'created', id: record.id, createdAt: record.createdAt };
},
},
trialLookup,
newId: () => 'finding-pg-0001',
now: () => Date.UTC(2025, 5, 29, 12, 0, 0, 0),
}),
],
});
const call = async (trialRefs: readonly string[]) => {
const raw = await server.handleMessage(
JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: {
name: 'file_finding',
arguments: {
kind: 'finding',
title: 'Pre-vault signal',
summary: 'Research-visible evidence only.',
trialRefs,
},
},
})
);
return (JSON.parse(raw!) as { result: { isError?: boolean; content: { text: string }[] } })
.result;
};
const mixed = await call(['1', '2']);
expect(mixed.isError).toBe(true);
expect(mixed.content[0]!.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
expect(appended).toHaveLength(0);
const visible = await call(['1', MAX_BIGINT_REF]);
expect(visible.isError).toBeUndefined();
expect(appended).toHaveLength(1);
expect(appended[0]!.trialRefs).toEqual(['1', MAX_BIGINT_REF]);
});
});