T-159: tests
This commit is contained in:
parent
d65016c851
commit
ae01904cd6
2 changed files with 388 additions and 0 deletions
|
|
@ -418,3 +418,108 @@ describe('createPostgresTrialRefLookupPort wired into createFileFindingTool', ()
|
|||
expect(appended).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createPostgresTrialRefLookupPort (QA edge cases)', () => {
|
||||
test('queries in-range 19-digit refs and rejects 19-digit refs above the signed BIGINT max', async () => {
|
||||
const fake = createFakeExecutor([{ visible: 1 }]);
|
||||
const port = createPostgresTrialRefLookupPort({
|
||||
executor: fake.executor,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
|
||||
expect(await port.hasResearchVisibleTrial('1000000000000000000')).toBe(true);
|
||||
expect(await port.hasResearchVisibleTrial('9223372036854775806')).toBe(true);
|
||||
expect(await port.hasResearchVisibleTrial('9223372036854775900')).toBe(false);
|
||||
expect(await port.hasResearchVisibleTrial('9999999999999999999')).toBe(false);
|
||||
|
||||
expect(fake.calls.map(c => c.params?.[0])).toEqual([
|
||||
'1000000000000000000',
|
||||
'9223372036854775806',
|
||||
]);
|
||||
});
|
||||
|
||||
test('rejects trailing-newline, tab, fullwidth-digit, and boxed-String refs without querying', async () => {
|
||||
const fake = createFakeExecutor([{ visible: 1 }]);
|
||||
const port = createPostgresTrialRefLookupPort({
|
||||
executor: fake.executor,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
|
||||
for (const ref of ['42\n', '\n42', '4\t2', '42', '42\u0000', new String('42')] as unknown[]) {
|
||||
expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false);
|
||||
}
|
||||
expect(fake.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('accepts the four-digit PostgreSQL calendar bounds 0001-01-01 and 9999-12-31 as cutoff dates', async () => {
|
||||
const earliest = Date.parse('0001-01-01T00:00:00.000Z');
|
||||
const latest = Date.parse('9999-12-31T23:59:59.999Z');
|
||||
|
||||
for (const [ts, expected] of [
|
||||
[earliest, '0001-01-01'],
|
||||
[latest, '9999-12-31'],
|
||||
[Date.UTC(1969, 11, 31, 23, 59, 59, 999), '1969-12-31'],
|
||||
] as const) {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresTrialRefLookupPort({ executor: fake.executor, vaultCutoffTs: ts });
|
||||
await port.hasResearchVisibleTrial('5');
|
||||
expect(fake.calls[0]!.params).toEqual(['5', expected]);
|
||||
}
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
createPostgresTrialRefLookupPort({
|
||||
executor: createFakeExecutor().executor,
|
||||
vaultCutoffTs: latest + 1,
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect((caught as PostgresTrialRefError).code).toBe('INVALID_VAULT_CUTOFF');
|
||||
});
|
||||
|
||||
test('freezes the cutoff date and SQL text at construction across repeated lookups', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const options = { executor: fake.executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS };
|
||||
const port = createPostgresTrialRefLookupPort(options);
|
||||
|
||||
await port.hasResearchVisibleTrial('1');
|
||||
(options as { vaultCutoffTs: number }).vaultCutoffTs = Date.UTC(2030, 0, 1);
|
||||
await port.hasResearchVisibleTrial('2');
|
||||
|
||||
expect(fake.calls).toHaveLength(2);
|
||||
expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text);
|
||||
expect(fake.calls[1]!.params).toEqual(['2', '2025-06-30']);
|
||||
});
|
||||
|
||||
test('returns true for multiple matching rows and rejects (not false) on a malformed executor response', async () => {
|
||||
const many = createFakeExecutor([{ visible: 1 }, { visible: 1 }]);
|
||||
const manyPort = createPostgresTrialRefLookupPort({
|
||||
executor: many.executor,
|
||||
vaultCutoffTs: CUTOFF_MIDNIGHT_TS,
|
||||
});
|
||||
expect(await manyPort.hasResearchVisibleTrial('3')).toBe(true);
|
||||
|
||||
for (const response of [null, {}, { rows: 'x' }, { rows: null }]) {
|
||||
const executor: TrialRefExecutor = {
|
||||
async query() {
|
||||
return response as unknown as { readonly rows: readonly never[] };
|
||||
},
|
||||
};
|
||||
const port = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS });
|
||||
await expect(port.hasResearchVisibleTrial('3')).rejects.toBeInstanceOf(TypeError);
|
||||
}
|
||||
});
|
||||
|
||||
test('propagates a synchronous executor throw as a rejection with the same error', async () => {
|
||||
const failure = new Error('pool exhausted');
|
||||
const executor = {
|
||||
query() {
|
||||
throw failure;
|
||||
},
|
||||
} as unknown as TrialRefExecutor;
|
||||
const port = createPostgresTrialRefLookupPort({ executor, vaultCutoffTs: CUTOFF_MIDNIGHT_TS });
|
||||
|
||||
await expect(port.hasResearchVisibleTrial('42')).rejects.toBe(failure);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
283
test/postgres/mcp-trial-ref-adapter.test.ts
Normal file
283
test/postgres/mcp-trial-ref-adapter.test.ts
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
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]);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue