import { describe, expect, test } from 'bun:test'; import { MarketDataStoreValidationError } from '../src/market-data-store'; import { createPostgresSymbolSearchPort, PostgresSymbolSearchError, type SymbolSearchExecutor, type SymbolSearchQuery, } from '../src/mcp/index'; interface RecordedCall { readonly text: string; readonly params: readonly unknown[] | undefined; } function createFakeExecutor(rows: readonly Record[] = []): { readonly calls: RecordedCall[]; readonly executor: SymbolSearchExecutor; } { const calls: RecordedCall[] = []; const executor: SymbolSearchExecutor = { 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 }; } function makeRawRow(overrides: Record = {}): Record { return { listing_id: 101, instrument_id: 1001, ticker: 'ACME', class_suffix: '', name: 'Acme Corporation', mic: 'XNAS', currency: 'USD', isin: 'US0000001015', first_bar_date: '2018-01-02', last_bar_date: '2024-06-28', delisted_at: null, ...overrides, }; } const BASE_QUERY: SymbolSearchQuery = { query: 'ACME', limit: 20, includeDelisted: true, vaultCutoffTs: Date.UTC(2024, 5, 30, 0, 0, 0, 0), // 2024-06-30T00:00:00.000Z }; describe('createPostgresSymbolSearchPort (fake executor)', () => { test('issues a single parameterized SELECT and never interpolates injection-shaped queries', async () => { const injection = "'; DROP TABLE listing; --"; const fake = createFakeExecutor([makeRawRow()]); const port = createPostgresSymbolSearchPort({ executor: fake.executor }); await port.searchSymbols({ ...BASE_QUERY, query: injection, }); expect(fake.calls).toHaveLength(1); const call = fake.calls[0]!; expect(call.text.trimStart().startsWith('SELECT')).toBe(true); expect(call.text).not.toContain(';'); expect(call.text).not.toContain(injection); expect(call.text).not.toContain('DROP TABLE'); expect(call.params).toEqual(['2024-06-30', `%${injection}%`, injection, null, true]); }); test('escapes %, _, and backslash literals in the ILIKE pattern while preserving raw query for ISIN', async () => { const fake = createFakeExecutor([]); const port = createPostgresSymbolSearchPort({ executor: fake.executor }); await port.searchSymbols({ ...BASE_QUERY, query: 'A%B_C\\D', }); expect(fake.calls).toHaveLength(1); const call = fake.calls[0]!; expect(call.text).toContain("ESCAPE '\\'"); expect(call.params).toEqual(['2024-06-30', '%A\\%B\\_C\\\\D%', 'A%B_C\\D', null, true]); }); test('converts vaultCutoffTs epoch-ms to UTC calendar date across midnight boundaries', async () => { const fake = createFakeExecutor([]); const port = createPostgresSymbolSearchPort({ executor: fake.executor }); await port.searchSymbols({ ...BASE_QUERY, vaultCutoffTs: Date.UTC(2024, 5, 30, 23, 59, 59, 999), }); await port.searchSymbols({ ...BASE_QUERY, vaultCutoffTs: Date.UTC(2024, 6, 1, 0, 0, 0, 0), }); expect(fake.calls).toHaveLength(2); expect(fake.calls[0]!.params?.[0]).toBe('2024-06-30'); expect(fake.calls[1]!.params?.[0]).toBe('2024-07-01'); }); test('binds optional country filter and both includeDelisted flags', async () => { const fake = createFakeExecutor([]); const port = createPostgresSymbolSearchPort({ executor: fake.executor }); await port.searchSymbols({ ...BASE_QUERY, country: 'CA', includeDelisted: false, }); await port.searchSymbols({ ...BASE_QUERY, country: 'US', includeDelisted: true, }); expect(fake.calls).toHaveLength(2); expect(fake.calls[0]!.params?.[3]).toBe('CA'); expect(fake.calls[0]!.params?.[4]).toBe(false); expect(fake.calls[1]!.params?.[3]).toBe('US'); expect(fake.calls[1]!.params?.[4]).toBe(true); }); test('ignores q.limit in SQL and returns all candidates without truncation', async () => { const rows = [ makeRawRow({ listing_id: 1, instrument_id: 10, ticker: 'AA' }), makeRawRow({ listing_id: 2, instrument_id: 20, ticker: 'AAB' }), makeRawRow({ listing_id: 3, instrument_id: 30, ticker: 'AAC' }), ]; const fake = createFakeExecutor(rows); const port = createPostgresSymbolSearchPort({ executor: fake.executor }); const r1 = await port.searchSymbols({ ...BASE_QUERY, limit: 1 }); const r2 = await port.searchSymbols({ ...BASE_QUERY, limit: 100 }); expect(r1).toHaveLength(3); expect(r2).toHaveLength(3); expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text); expect(fake.calls[0]!.params).toEqual(fake.calls[1]!.params); // Outer query has ORDER BY listing_id ASC with no outer LIMIT clause expect(fake.calls[0]!.text.trimEnd().endsWith('ORDER BY l.listing_id ASC')).toBe(true); }); test('gates ticker_root fallback and matching on cutoff-aware history suppression and derives delisted_at', async () => { const fake = createFakeExecutor([]); const port = createPostgresSymbolSearchPort({ executor: fake.executor }); await port.searchSymbols(BASE_QUERY); const sql = fake.calls[0]!.text; // Root-suppression subquery checks upper(ticker) = upper(ticker_root) and cutoff $1::date expect(sql).toContain('upper(h_any.ticker) = upper(l.ticker_root)'); expect(sql).toContain('upper(h_past.ticker) = upper(l.ticker_root)'); expect(sql).toContain('h_past.valid_from <= $1::date'); // Both fallback resolution and root ILIKE predicate are gated by NOT root_state.is_future expect(sql).toContain('WHEN NOT root_state.is_future THEN l.ticker_root'); expect(sql).toContain( "OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')" ); // delisted_at derivation and $5 filter expect(sql).toContain( "WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to" ); expect(sql).toContain( '($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)' ); }); test('quotes optional validated schema on all security-master tables and omits prefix when unset', async () => { const fakeDefault = createFakeExecutor([]); const defaultPort = createPostgresSymbolSearchPort({ executor: fakeDefault.executor }); await defaultPort.searchSymbols(BASE_QUERY); expect(fakeDefault.calls[0]!.text).toContain('FROM listing l'); expect(fakeDefault.calls[0]!.text).toContain('INNER JOIN instrument i'); expect(fakeDefault.calls[0]!.text).toContain('INNER JOIN exchange e'); expect(fakeDefault.calls[0]!.text).toContain('FROM listing_symbol_history'); const fakeScoped = createFakeExecutor([]); const scopedPort = createPostgresSymbolSearchPort({ executor: fakeScoped.executor, schema: 'custom_master_1', }); await scopedPort.searchSymbols(BASE_QUERY); expect(fakeScoped.calls[0]!.text).toContain('FROM "custom_master_1".listing l'); expect(fakeScoped.calls[0]!.text).toContain('INNER JOIN "custom_master_1".instrument i'); expect(fakeScoped.calls[0]!.text).toContain('INNER JOIN "custom_master_1".exchange e'); expect(fakeScoped.calls[0]!.text).toContain('FROM "custom_master_1".listing_symbol_history'); }); test('maps raw rows into SymbolSearchRow with classSuffix, ISIN trimming, nullable dates, and delistedAt', async () => { const fake = createFakeExecutor([ makeRawRow({ listing_id: 101, instrument_id: 501, ticker: 'ACME', class_suffix: '', name: 'Acme Corp', mic: 'XNAS', currency: 'USD ', isin: ' US0000001015 ', first_bar_date: '2020-02-29', last_bar_date: '2024-06-28', delisted_at: null, }), makeRawRow({ listing_id: 102, instrument_id: 502, ticker: 'BRK', class_suffix: 'B', name: 'Berkshire Example', mic: 'XNYS', currency: 'USD', isin: ' ', first_bar_date: null, last_bar_date: '2023-12-15', delisted_at: '2023-12-15', }), makeRawRow({ listing_id: 103, instrument_id: 503, ticker: 'NULLY', class_suffix: null, name: 'Nullable Fields Co', mic: 'XTSE', currency: 'CAD', isin: null, first_bar_date: null, last_bar_date: null, delisted_at: null, }), ]); const port = createPostgresSymbolSearchPort({ executor: fake.executor }); const rows = await port.searchSymbols(BASE_QUERY); expect(rows).toEqual([ { listingId: 101, instrumentId: 501, ticker: 'ACME', classSuffix: null, name: 'Acme Corp', mic: 'XNAS', currency: 'USD', isin: 'US0000001015', firstBarDate: '2020-02-29', lastBarDate: '2024-06-28', delistedAt: null, }, { listingId: 102, instrumentId: 502, ticker: 'BRK', classSuffix: 'B', name: 'Berkshire Example', mic: 'XNYS', currency: 'USD', isin: null, firstBarDate: null, lastBarDate: '2023-12-15', delistedAt: '2023-12-15', }, { listingId: 103, instrumentId: 503, ticker: 'NULLY', classSuffix: null, name: 'Nullable Fields Co', mic: 'XTSE', currency: 'CAD', isin: null, firstBarDate: null, lastBarDate: null, delistedAt: null, }, ]); }); test('rejects invalid executors and options with INVALID_EXECUTOR before any query', () => { const invalidOptions: unknown[] = [ null, undefined, {}, { executor: null }, { executor: {} }, { executor: { query: 'not-a-fn' } }, ]; for (const opts of invalidOptions) { let caught: unknown; try { createPostgresSymbolSearchPort( opts as Parameters[0] ); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(PostgresSymbolSearchError); expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_EXECUTOR'); } }); test('rejects invalid schema names with INVALID_SCHEMA before any query', () => { const fake = createFakeExecutor([]); const badSchemas: unknown[] = [ '', 'Public', '1schema', 'bad-name', 'bad.name', 'public"; DROP TABLE listing; --', 'space name', 123, null, ]; for (const schema of badSchemas) { let caught: unknown; try { createPostgresSymbolSearchPort({ executor: fake.executor, schema: schema as string, }); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(PostgresSymbolSearchError); expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_SCHEMA'); } expect(fake.calls).toHaveLength(0); }); test('rejects invalid vaultCutoffTs before executing any query', async () => { const fake = createFakeExecutor([]); const port = createPostgresSymbolSearchPort({ executor: fake.executor }); await expect( port.searchSymbols({ ...BASE_QUERY, vaultCutoffTs: Number.NaN }) ).rejects.toBeInstanceOf(MarketDataStoreValidationError); expect(fake.calls).toHaveLength(0); }); test('rejects malformed rows (fractional/unsafe IDs, malformed/impossible dates, invalid types) with INVALID_ROW', async () => { const badRows: readonly Record[] = [ makeRawRow({ listing_id: 1.5 }), makeRawRow({ listing_id: Number.MAX_SAFE_INTEGER + 1 }), makeRawRow({ listing_id: '101' }), makeRawRow({ listing_id: Number.NaN }), makeRawRow({ instrument_id: 2.25 }), makeRawRow({ instrument_id: Number.POSITIVE_INFINITY }), makeRawRow({ ticker: '' }), makeRawRow({ ticker: null }), makeRawRow({ name: '' }), makeRawRow({ mic: null }), makeRawRow({ currency: '' }), makeRawRow({ class_suffix: 42 }), makeRawRow({ isin: 12345 }), makeRawRow({ first_bar_date: '2024-6-1' }), makeRawRow({ first_bar_date: '2023-02-29' }), makeRawRow({ last_bar_date: '2024-02-30' }), makeRawRow({ last_bar_date: '2024-13-01' }), makeRawRow({ delisted_at: '2024-06-30T00:00:00Z' }), makeRawRow({ delisted_at: new Date('2024-06-30T00:00:00Z') }), ]; for (const badRow of badRows) { const fake = createFakeExecutor([badRow]); const port = createPostgresSymbolSearchPort({ executor: fake.executor }); let caught: unknown; try { await port.searchSymbols(BASE_QUERY); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(PostgresSymbolSearchError); expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_ROW'); } // Non-object row / invalid result shape const nullRowExecutor: SymbolSearchExecutor = { async query>() { return { rows: [null as unknown as Row] }; }, }; const portNullRow = createPostgresSymbolSearchPort({ executor: nullRowExecutor }); await expect(portNullRow.searchSymbols(BASE_QUERY)).rejects.toBeInstanceOf( PostgresSymbolSearchError ); const badResultExecutor: SymbolSearchExecutor = { async query() { return { rows: 'not-an-array' as unknown as readonly never[] }; }, }; const portBadResult = createPostgresSymbolSearchPort({ executor: badResultExecutor }); await expect(portBadResult.searchSymbols(BASE_QUERY)).rejects.toBeInstanceOf( PostgresSymbolSearchError ); }); }); describe('createPostgresSymbolSearchPort (QA edge cases)', () => { test('accepts a pg.Pool-shaped executor whose query method lives on the prototype', async () => { class PrototypeExecutor { readonly calls: RecordedCall[] = []; async query>( text: string, params?: readonly unknown[] ): Promise<{ readonly rows: readonly Row[] }> { this.calls.push({ text, params }); return { rows: [makeRawRow()] as unknown as readonly Row[] }; } } const executor = new PrototypeExecutor(); const port = createPostgresSymbolSearchPort({ executor }); const rows = await port.searchSymbols(BASE_QUERY); expect(rows.map(r => r.listingId)).toEqual([101]); expect(executor.calls).toHaveLength(1); }); test('accepts minimal valid schema identifiers and quotes them', async () => { for (const schema of ['_', 'a', 'stock_bot_safety_0abc']) { const fake = createFakeExecutor([]); const port = createPostgresSymbolSearchPort({ executor: fake.executor, schema }); await port.searchSymbols(BASE_QUERY); expect(fake.calls[0]!.text).toContain(`FROM "${schema}".listing l`); } }); test('propagates executor failures unchanged without retrying', async () => { const failure = new Error('connection terminated'); let attempts = 0; const executor: SymbolSearchExecutor = { async query() { attempts += 1; throw failure; }, }; const port = createPostgresSymbolSearchPort({ executor }); await expect(port.searchSymbols(BASE_QUERY)).rejects.toBe(failure); expect(attempts).toBe(1); }); test('binds the UTC calendar date for an instant that is already the next day east of UTC', async () => { const fake = createFakeExecutor([]); const port = createPostgresSymbolSearchPort({ executor: fake.executor }); // 2024-02-29T23:30Z is 2024-03-01 in UTC+1 zones; the adapter must still bind the UTC date. await port.searchSymbols({ ...BASE_QUERY, vaultCutoffTs: Date.UTC(2024, 1, 29, 23, 30) }); expect(fake.calls[0]!.params?.[0]).toBe('2024-02-29'); }); test('returns an empty array (not null) when the executor returns no rows', async () => { const fake = createFakeExecutor([]); const port = createPostgresSymbolSearchPort({ executor: fake.executor }); expect(await port.searchSymbols(BASE_QUERY)).toEqual([]); }); test('rejects the whole result when any row in a batch is malformed', async () => { const fake = createFakeExecutor([ makeRawRow(), makeRawRow({ listing_id: 102, last_bar_date: '2024-04-31' }), ]); const port = createPostgresSymbolSearchPort({ executor: fake.executor }); let caught: unknown; try { await port.searchSymbols(BASE_QUERY); } catch (err) { caught = err; } expect(caught).toBeInstanceOf(PostgresSymbolSearchError); expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_ROW'); }); });