import { describe, expect, test } from 'bun:test'; import { MarketDataStoreValidationError } from '../src/market-data-store'; import { PostgresTrialRefError, type TrialRefExecutor, createPostgresTrialRefPort, } from '../src/mcp/index'; interface RecordedCall { readonly text: string; readonly params: readonly unknown[] | undefined; } function createFakeExecutor(rows: readonly Record[] = []): { readonly calls: RecordedCall[]; readonly executor: TrialRefExecutor; } { const calls: RecordedCall[] = []; const executor: TrialRefExecutor = { async query>( text: string, params?: readonly unknown[] ): Promise<{ readonly rows: readonly Row[] }> { calls.push({ text, params }); return { rows: rows as readonly Row[] }; }, }; return { calls, executor }; } const CUTOFF_TS = Date.UTC(2025, 5, 30, 15, 45, 30, 500); // 2025-06-30T15:45:30.500Z const CUTOFF_DATE = '2025-06-30'; describe('createPostgresTrialRefPort (fake executor)', () => { test('issues exact parameterized SELECT with default search_path and explicit quoted schema', async () => { const fakeDefault = createFakeExecutor([{ visible: 1 }]); const defaultPort = createPostgresTrialRefPort({ executor: fakeDefault.executor, vaultCutoffTs: CUTOFF_TS, }); expect(await defaultPort.hasResearchVisibleTrial('42')).toBe(true); expect(fakeDefault.calls).toEqual([ { text: 'SELECT 1 AS visible FROM trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1', params: ['42', CUTOFF_DATE], }, ]); const fakeScoped = createFakeExecutor([{ visible: 1 }]); const scopedPort = createPostgresTrialRefPort({ executor: fakeScoped.executor, vaultCutoffTs: CUTOFF_TS, schema: 'research_iso_1', }); expect(await scopedPort.hasResearchVisibleTrial('42')).toBe(true); expect(fakeScoped.calls).toEqual([ { text: 'SELECT 1 AS visible FROM "research_iso_1".trial_ledger WHERE trial_id = $1::bigint AND sample_end < $2::date LIMIT 1', params: ['42', CUTOFF_DATE], }, ]); }); test('converts vaultCutoffTs once to UTC calendar date across midnight boundaries', async () => { const lateFake = createFakeExecutor([]); // 2025-06-30T23:30:00.000Z is already 2025-07-01 in UTC+1 zones; must bind UTC date 2025-06-30. const latePort = createPostgresTrialRefPort({ executor: lateFake.executor, vaultCutoffTs: Date.UTC(2025, 5, 30, 23, 30, 0, 0), }); expect(await latePort.hasResearchVisibleTrial('7')).toBe(false); expect(lateFake.calls[0]?.params).toEqual(['7', '2025-06-30']); const nextFake = createFakeExecutor([]); const nextPort = createPostgresTrialRefPort({ executor: nextFake.executor, vaultCutoffTs: Date.UTC(2025, 6, 1, 0, 0, 0, 0), }); expect(await nextPort.hasResearchVisibleTrial('7')).toBe(false); expect(nextFake.calls[0]?.params).toEqual(['7', '2025-07-01']); }); test('rejects invalid options and executors with INVALID_EXECUTOR before any query', () => { const invalidOptions: unknown[] = [ null, undefined, {}, { executor: null, vaultCutoffTs: CUTOFF_TS }, { executor: {}, vaultCutoffTs: CUTOFF_TS }, { executor: { query: 'not-a-fn' }, vaultCutoffTs: CUTOFF_TS }, ]; for (const opts of invalidOptions) { let caught: unknown; try { createPostgresTrialRefPort(opts as Parameters[0]); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(PostgresTrialRefError); expect((caught as PostgresTrialRefError).code).toBe('INVALID_EXECUTOR'); } }); test('rejects invalid schema identifiers with INVALID_SCHEMA before any query', () => { const fake = createFakeExecutor([]); const badSchemas: unknown[] = [ '', 'Public', '1schema', 'bad-name', 'bad.name', 'public"; DROP TABLE trial_ledger; --', 'space name', 123, null, ]; for (const schema of badSchemas) { let caught: unknown; try { createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS, schema: schema as string, }); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(PostgresTrialRefError); expect((caught as PostgresTrialRefError).code).toBe('INVALID_SCHEMA'); } expect(fake.calls).toHaveLength(0); }); test('accepts minimal valid schema identifiers and prototype-method pg.Pool-shaped executors', async () => { for (const schema of ['_', 'a', 'stock_bot_safety_0abc']) { const fake = createFakeExecutor([]); const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS, schema, }); await port.hasResearchVisibleTrial('1'); expect(fake.calls[0]?.text).toContain(`FROM "${schema}".trial_ledger `); } class PrototypeExecutor { readonly calls: RecordedCall[] = []; async query>( text: string, params?: readonly unknown[] ): Promise<{ readonly rows: readonly Row[] }> { this.calls.push({ text, params }); return { rows: [{ visible: 1 }] as unknown as readonly Row[] }; } } const executor = new PrototypeExecutor(); const port = createPostgresTrialRefPort({ executor, vaultCutoffTs: CUTOFF_TS }); expect(await port.hasResearchVisibleTrial('101')).toBe(true); expect(executor.calls).toHaveLength(1); }); test('rejects invalid or non-PostgreSQL-date vaultCutoffTs with MarketDataStoreValidationError', () => { const fake = createFakeExecutor([]); const yearZeroTs = new Date('0000-06-15T00:00:00.000Z').getTime(); const negativeYearTs = new Date('-000001-01-01T00:00:00.000Z').getTime(); const fiveDigitYearTs = new Date('+010000-01-01T00:00:00.000Z').getTime(); const invalidCutoffs: unknown[] = [ undefined, null, '2025-06-30', Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, 1.5, Number.MAX_SAFE_INTEGER + 1, 8_640_000_000_000_000, -8_640_000_000_000_000, yearZeroTs, negativeYearTs, fiveDigitYearTs, ]; for (const vaultCutoffTs of invalidCutoffs) { let caught: unknown; try { createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: vaultCutoffTs as number, }); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(MarketDataStoreValidationError); expect((caught as MarketDataStoreValidationError).field).toBe('vaultCutoffTs'); } expect(fake.calls).toHaveLength(0); }); test('returns false with zero executor calls for every invalid, non-canonical, overflow, or injection-shaped ref', async () => { const fake = createFakeExecutor([{ visible: 1 }]); const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS, }); const invalidRefs: unknown[] = [ '', ' ', ' 1', '1 ', '\t1', '1\n', '0', '-1', '+1', '01', '0001', '1.0', '1e2', '1E2', '0x10', '1_000', 'abc', '1; DROP TABLE trial_ledger', '1 OR 1=1', '9223372036854775808', '9999999999999999999', '10000000000000000000', 1, 0, null, undefined, {}, [], 1n, ]; for (const ref of invalidRefs) { expect(await port.hasResearchVisibleTrial(ref as string)).toBe(false); } expect(fake.calls).toHaveLength(0); }); test('passes 9223372036854775807 as an exact string without Number coercion and skips 9223372036854775808', async () => { const fake = createFakeExecutor([{ visible: 1 }]); const port = createPostgresTrialRefPort({ executor: fake.executor, vaultCutoffTs: CUTOFF_TS, }); expect(await port.hasResearchVisibleTrial('9223372036854775807')).toBe(true); expect(fake.calls).toHaveLength(1); expect(fake.calls[0]?.params).toEqual(['9223372036854775807', CUTOFF_DATE]); expect(typeof fake.calls[0]?.params?.[0]).toBe('string'); expect(await port.hasResearchVisibleTrial('9223372036854775808')).toBe(false); expect(fake.calls).toHaveLength(1); }); test('returns false for zero rows and true for exactly one valid visibility row', async () => { const emptyFake = createFakeExecutor([]); const emptyPort = createPostgresTrialRefPort({ executor: emptyFake.executor, vaultCutoffTs: CUTOFF_TS, }); expect(await emptyPort.hasResearchVisibleTrial('123')).toBe(false); const hitFake = createFakeExecutor([{ visible: 1 }]); const hitPort = createPostgresTrialRefPort({ executor: hitFake.executor, vaultCutoffTs: CUTOFF_TS, }); expect(await hitPort.hasResearchVisibleTrial('123')).toBe(true); }); test('throws INVALID_ROW for malformed envelopes, invalid singleton rows, and multiple rows (regression)', async () => { const badResponses: unknown[] = [ null, undefined, {}, { rows: null }, { rows: 'not-an-array' }, { rows: {} }, { rows: [null] }, { rows: [undefined] }, { rows: [1] }, { rows: [{}] }, { rows: [{ visible: '1' }] }, { rows: [{ visible: true }] }, { rows: [{ visible: 0 }] }, { rows: [{ visible: 2 }] }, { rows: [{ visible: null }] }, // Regression: multiple rows must fail closed rather than returning true. { rows: [{ visible: 1 }, { visible: 1 }] }, ]; for (const response of badResponses) { const executor: TrialRefExecutor = { async query() { return response as { readonly rows: readonly never[] }; }, }; const port = createPostgresTrialRefPort({ executor, vaultCutoffTs: CUTOFF_TS, }); let caught: unknown; try { await port.hasResearchVisibleTrial('101'); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(PostgresTrialRefError); expect((caught as PostgresTrialRefError).code).toBe('INVALID_ROW'); } }); test('propagates rejected and synchronously thrown executor errors unchanged without retrying', async () => { const asyncFailure = new Error('connection terminated'); let asyncAttempts = 0; const asyncExecutor: TrialRefExecutor = { async query() { asyncAttempts += 1; throw asyncFailure; }, }; const asyncPort = createPostgresTrialRefPort({ executor: asyncExecutor, vaultCutoffTs: CUTOFF_TS, }); await expect(asyncPort.hasResearchVisibleTrial('101')).rejects.toBe(asyncFailure); expect(asyncAttempts).toBe(1); const syncFailure = new Error('sync driver failure'); let syncAttempts = 0; const syncExecutor: TrialRefExecutor = { query() { syncAttempts += 1; throw syncFailure; }, }; const syncPort = createPostgresTrialRefPort({ executor: syncExecutor, vaultCutoffTs: CUTOFF_TS, }); await expect(syncPort.hasResearchVisibleTrial('101')).rejects.toBe(syncFailure); expect(syncAttempts).toBe(1); }); });