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

484 lines
18 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 {
type AppendFindingResult,
FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF,
type FileFindingResultPayload,
type FiledFindingRecord,
type TrialRefExecutor,
createFileFindingTool,
createMcpServer,
createPostgresFindingWritePort,
createPostgresTrialRefLookupPort,
} 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 FIXED_TS = '2026-01-15T12:34:56.789Z';
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 () => {
// 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,
extraOptions?: 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 = extraOptions
? `-c search_path=${schema} ${extraOptions}`
: `-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 readOnlyPool = new Pool(
buildIsolatedPoolConfig(
safeUrl,
schema,
'-c default_transaction_read_only=on -c statement_timeout=5000'
)
);
cleanup.push(() => readOnlyPool.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' });
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('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 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]);
});
test('composes with createFileFindingTool and createPostgresFindingWritePort through MCP', async () => {
const f = await createIsolatedFixture();
const executor = createPgExecutor(f.pool);
const trialLookup = createPostgresTrialRefLookupPort({
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: ['1'],
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: ['1'],
},
]);
// Vault-only (equal to cutoff, after cutoff) and unknown citations all return the same error with zero rows added.
for (const deniedRef of ['2', '3', '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);
});
});