diff --git a/libs/research/test/mcp-postgres-symbol-search.test.ts b/libs/research/test/mcp-postgres-symbol-search.test.ts index ea9a3edd..d4fb71c5 100644 --- a/libs/research/test/mcp-postgres-symbol-search.test.ts +++ b/libs/research/test/mcp-postgres-symbol-search.test.ts @@ -1,10 +1,10 @@ import { describe, expect, test } from 'bun:test'; import { MarketDataStoreValidationError } from '../src/market-data-store'; import { + createPostgresSymbolSearchPort, PostgresSymbolSearchError, type SymbolSearchExecutor, type SymbolSearchQuery, - createPostgresSymbolSearchPort, } from '../src/mcp/index'; interface RecordedCall { @@ -70,13 +70,7 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { 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, - ]); + 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 () => { @@ -91,13 +85,7 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { 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, - ]); + 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 () => { @@ -173,10 +161,16 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { 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 '\\')"); + 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)'); + 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 () => { @@ -302,7 +296,9 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { for (const opts of invalidOptions) { let caught: unknown; try { - createPostgresSymbolSearchPort(opts as Parameters[0]); + createPostgresSymbolSearchPort( + opts as Parameters[0] + ); } catch (err) { caught = err; } @@ -411,3 +407,83 @@ describe('createPostgresSymbolSearchPort (fake executor)', () => { ); }); }); + +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'); + }); +}); diff --git a/test/postgres/mcp-symbol-search-adapter.test.ts b/test/postgres/mcp-symbol-search-adapter.test.ts index 6f5e253f..d0270313 100644 --- a/test/postgres/mcp-symbol-search-adapter.test.ts +++ b/test/postgres/mcp-symbol-search-adapter.test.ts @@ -4,11 +4,11 @@ import { Client, Pool, type PoolConfig } from 'pg'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; import { - type SearchSymbolsResultPayload, - type SymbolSearchExecutor, createMcpServer, createPostgresSymbolSearchPort, createSearchSymbolsTool, + type SearchSymbolsResultPayload, + type SymbolSearchExecutor, } from '../../libs/research/src/mcp/index'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); @@ -182,7 +182,9 @@ async function seedFixture(pool: Pool): Promise { describe('PostgreSQL symbol search safety guard', () => { test('rejects unsafe database targets before connecting', () => { - expect(() => assertSafetyDatabaseUrl(undefined)).toThrow('Dedicated stock_bot_safety database required'); + 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'); @@ -364,9 +366,7 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { includeDelisted: true, vaultCutoffTs: VAULT_CUTOFF_TS, }); - expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([ - { id: 101, mic: 'XTSE' }, - ]); + expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([{ id: 101, mic: 'XTSE' }]); // (e) Case-insensitive exact ISIN match with partial-ISIN negative const isinRows = await port.searchSymbols({ @@ -486,6 +486,85 @@ describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => { expect(futureDelistPayload.rows[0]!.delistedAt).toBeNull(); }); + test('moves as-of resolution with the cutoff date, including a near-midnight UTC instant', async () => { + const f = await createIsolatedFixture(); + const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) }); + const search = (query: string, vaultCutoffTs: number, includeDelisted = true) => + port.searchSymbols({ query, limit: 20, includeDelisted, vaultCutoffTs }); + const lastMsOfCutoffDay = Date.UTC(2024, 5, 30, 23, 59, 59, 999); + const dayAfterCutoff = Date.UTC(2024, 6, 1, 0, 0, 0, 0); + + // Last millisecond of 2024-06-30 UTC still resolves the pre-rename ticker. + const lateOld = await search('OLDCO', lastMsOfCutoffDay); + expect(lateOld.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ + { id: 101, ticker: 'ZOLD' }, + { id: 113, ticker: 'OLDCO2' }, + { id: 114, ticker: 'OLDCO' }, + ]); + expect(await search('NEWCO', lastMsOfCutoffDay)).toEqual([]); + + // One day later the rename, the GAPNEW start and the IPO become visible, and OLDCO no longer resolves to 114. + const nextOld = await search('OLDCO', dayAfterCutoff); + expect(nextOld.map(r => r.listingId)).toEqual([101, 113]); + const nextNew = await search('NEWCO', dayAfterCutoff); + expect(nextNew.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ + { id: 114, ticker: 'NEWCO' }, + ]); + const nextGap = await search('GAPNEW', dayAfterCutoff); + expect(nextGap.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([ + { id: 102, ticker: 'GAPNEW' }, + ]); + expect(await search('GAPOLD', dayAfterCutoff)).toEqual([]); + expect((await search('IPO25', dayAfterCutoff)).map(r => r.listingId)).toEqual([106]); + + // A cutoff on the future delisting date makes that delisting confirmed and filterable. + const onFutureDelist = await search('Delist Boundary', Date.UTC(2024, 8, 15), false); + expect(onFutureDelist.map(r => r.listingId)).toEqual([109, 110]); + }); + + test('projects identical calendar dates regardless of the session TimeZone', async () => { + const f = await createIsolatedFixture(); + const client = await f.pool.connect(); + try { + await client.query("SET TimeZone = 'Pacific/Kiritimati'"); + const executor: SymbolSearchExecutor = { + query>(text: string, params?: readonly unknown[]) { + return client.query( + text, + params === undefined ? undefined : [...params] + ) as unknown as Promise<{ + readonly rows: readonly Row[]; + }>; + }, + }; + const port = createPostgresSymbolSearchPort({ executor }); + + const rows = await port.searchSymbols({ + query: 'Delist Boundary', + limit: 20, + includeDelisted: true, + vaultCutoffTs: VAULT_CUTOFF_TS, + }); + + expect( + rows.map(r => ({ + id: r.listingId, + first: r.firstBarDate, + last: r.lastBarDate, + delistedAt: r.delistedAt, + })) + ).toEqual([ + { id: 108, first: '2015-01-01', last: '2024-06-30', delistedAt: '2024-06-30' }, + { id: 109, first: '2015-01-01', last: '2024-06-28', delistedAt: null }, + { id: 110, first: '2015-01-01', last: '2024-06-28', delistedAt: null }, + { id: 111, first: '2015-01-01', last: '2024-09-15', delistedAt: '2024-09-15' }, + ]); + } finally { + await client.query('RESET TimeZone'); + client.release(); + } + }); + test('isolates fixture schema even when the safety database URL includes startup options', async () => { const parsed = new URL(assertSafetyDatabaseUrl(url)); parsed.searchParams.set('options', '-c statement_timeout=30000 -c search_path=public');