import { randomUUID } from 'node:crypto'; 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 { BarSpan } from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; import { classifySourceExchanges, composeSecurityMasterRun, CONTINUITY_KIND_OTC_DELIST_TRANSFER, formatListingNaturalKey, persistSecurityMaster, type FxRateByDateRecord, type SampleCloseRecord, type SecurityMasterQueryable, type SecurityMasterSourcesResult, type SecurityType, type StageASourceRecord, type StageBEodListingInput, type StageBIbContractInput, type StageBTickerSourceInput, } from '../../apps/stock/data-pipeline/src/security-master'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('security-master-run-pg-test'); const url = process.env.PIPELINE_TEST_DATABASE_URL; const cleanup: (() => Promise | void)[] = []; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) { await close(); } }); async function createIsolatedFixture(statementTimeoutMs = 15_000) { if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { throw new Error('Dedicated stock_bot_safety database required'); } const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: url }); await admin.query(`CREATE SCHEMA ${schema}`); const pool = new Pool({ connectionString: url, options: `-c search_path=${schema} -c statement_timeout=${statementTimeoutMs} -c lock_timeout=15000`, }); cleanup.push(async () => { await pool.end(); await admin.query(`DROP SCHEMA ${schema} CASCADE`); await admin.end(); }); 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: 'master' }); return { pool, schema, postgres }; } async function withClient(pool: Pool, fn: (client: PoolClient) => Promise): Promise { const client = await pool.connect(); try { return await fn(client); } finally { client.release(); } } async function getSevenTableCounts(pool: Pool): Promise> { const tables = [ 'instrument', 'instrument_identifier_history', 'listing', 'listing_symbol_history', 'provider_mapping', 'resolution_conflict', 'corporate_action_continuity', ] as const; const counts: Record = {}; for (const table of tables) { const res = await pool.query<{ count: number }>(`SELECT count(*)::int AS count FROM ${table}`); counts[table] = res.rows[0]?.count ?? -1; } return counts; } function makeEmptyCollectionStats( collection: 'eodSymbols' | 'ibSymbols' | 'qmSymbols' | 'ceoSymbols' | 'eodSymbolChange' ) { return { collection, docsRead: 0, emitted: 0, invalidIdentifiersNulled: 0, skips: { missingId: 0, invalidFieldType: 0, invalidIdentifier: 0, excludedMutualFund: 0, unmappedExchange: 0, outOfScopeCountry: 0, }, }; } function buildComposedExitCriterionRun() { const stageARecords: StageASourceRecord[] = [ { source: 'ib', sourceId: '265598', isin: 'US0378331005', cusip: '037833100', country: 'US', currency: 'USD', name: 'Apple Inc.', }, { source: 'eod', sourceId: 'AAPL.US', isin: 'US0378331005', cusip: '037833100', country: 'US', currency: 'USD', name: 'Apple Inc', }, { source: 'eod', sourceId: 'FB_OLD.US', isin: 'US30303M1027', cusip: '30303M102', country: 'US', currency: 'USD', name: 'Meta Platforms Inc', }, { source: 'eod', sourceId: 'FB_ETF.US', isin: 'US4642872000', cusip: '464287200', country: 'US', currency: 'USD', name: 'FB Thematic ETF', }, { source: 'eod', sourceId: 'SIVB.US', isin: 'US78486Q1013', cusip: '78486Q101', country: 'US', currency: 'USD', name: 'SVB Financial Group', }, { source: 'eod', sourceId: 'SIVBQ.US', isin: 'US78486Q1013', cusip: '78486Q101', country: 'US', currency: 'USD', name: 'SVB Financial Group', }, { source: 'eod', sourceId: 'SHOP.TO', isin: 'CA82509L1076', cusip: '82509L107', country: 'CA', currency: 'CAD', name: 'Shopify Inc.', }, { source: 'eod', sourceId: 'SHOP.US', isin: 'CA82509L1076', cusip: '82509L107', country: 'CA', currency: 'USD', name: 'Shopify Inc.', }, { source: 'ib', sourceId: '2001', isin: 'CA82509L1076', cusip: '82509L107', country: 'CA', currency: 'CAD', name: 'Shopify Inc.', }, { source: 'ib', sourceId: '2002', isin: 'CA82509L1076', cusip: '82509L107', country: 'CA', currency: 'USD', name: 'Shopify Inc.', }, ]; const eodListings: StageBEodListingInput[] = [ { sourceId: 'AAPL.US', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, { sourceId: 'FB_OLD.US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, { sourceId: 'FB_ETF.US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, { sourceId: 'SIVB.US', ticker: 'SIVB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, { sourceId: 'SIVBQ.US', ticker: 'SIVBQ', mic: 'OTCM', role: 'primary_venue', currency: 'USD', span: null }, { sourceId: 'SHOP.TO', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue', currency: 'CAD', span: null }, { sourceId: 'SHOP.US', ticker: 'SHOP', mic: 'XNYS', role: 'primary_venue', currency: 'USD', span: null }, ]; const ibContracts: StageBIbContractInput[] = [ { sourceId: '265598', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ' }, { sourceId: '2001', conid: 2001, currency: 'CAD', primaryExchange: 'TSE' }, { sourceId: '2002', conid: 2002, currency: 'USD', primaryExchange: 'NYSE' }, ]; const tickerSources: StageBTickerSourceInput[] = [ { source: 'qm', sourceId: 'AAPL:US', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, { source: 'qm', sourceId: 'FB_OLD:US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, { source: 'qm', sourceId: 'FB_ETF:US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, { source: 'qm', sourceId: 'SHOP:CA', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue', currency: 'CAD', span: null }, { source: 'ceo', sourceId: 'ceo:SHOP', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue', currency: 'CAD', span: { firstBarDate: '2020-01-02', lastBarDate: '2025-11-28' }, }, ]; const barSpans: BarSpan[] = [ { source: 'eod', sourceId: 'AAPL.US', firstBarDate: '2010-01-04', lastBarDate: '2025-11-28', barCount: 4000 }, { source: 'eod', sourceId: 'FB_OLD.US', firstBarDate: '2012-05-18', lastBarDate: '2022-06-08', barCount: 2530 }, { source: 'eod', sourceId: 'FB_ETF.US', firstBarDate: '2025-01-02', lastBarDate: '2025-11-28', barCount: 230 }, { source: 'eod', sourceId: 'SIVB.US', firstBarDate: '2015-01-02', lastBarDate: '2023-03-10', barCount: 2060 }, { source: 'eod', sourceId: 'SIVBQ.US', firstBarDate: '2023-03-28', lastBarDate: '2024-11-07', barCount: 410 }, { source: 'eod', sourceId: 'SHOP.TO', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 }, { source: 'eod', sourceId: 'SHOP.US', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 }, { source: 'qm', sourceId: 'AAPL:US', firstBarDate: '2015-01-02', lastBarDate: '2025-11-28', barCount: 2700 }, { source: 'qm', sourceId: 'FB_OLD:US', firstBarDate: '2014-01-02', lastBarDate: '2022-06-08', barCount: 2100 }, { source: 'qm', sourceId: 'FB_ETF:US', firstBarDate: '2025-02-03', lastBarDate: '2025-11-28', barCount: 205 }, { source: 'qm', sourceId: 'SHOP:CA', firstBarDate: '2018-01-02', lastBarDate: '2025-11-28', barCount: 1980 }, ]; const securityTypeByIsin = new Map([ ['US0378331005', 'common'], ['US30303M1027', 'common'], ['US4642872000', 'etf'], ['US78486Q1013', 'common'], ['CA82509L1076', 'common'], ]); const sources: SecurityMasterSourcesResult = { stageARecords, stageBInput: { eodListings, ibContracts, tickerSources, symbolChanges: [], }, securityTypeRecords: [], securityTypeByIsin, securityTypeStats: { totalRecords: 0, mapped: 0, missingType: 0, unknownType: 0, invalidIsin: 0, isinsResolved: securityTypeByIsin.size, isinsConflicting: 0, conflictsTruncated: 0, }, securityTypeLoaderStats: { totalRecords: 0, mapped: 0, missingType: 0, unknownType: 0, invalidIsin: 0, isinsResolved: securityTypeByIsin.size, isinsConflicting: 0, conflictsTruncated: 0, }, unknownSecurityTypes: [], securityTypeConflicts: [], stats: { eodSymbols: makeEmptyCollectionStats('eodSymbols'), ibSymbols: makeEmptyCollectionStats('ibSymbols'), qmSymbols: makeEmptyCollectionStats('qmSymbols'), ceoSymbols: makeEmptyCollectionStats('ceoSymbols'), eodSymbolChange: makeEmptyCollectionStats('eodSymbolChange'), }, }; const exchanges = classifySourceExchanges([ { source: 'eod', sourceCode: 'NASDAQ', name: 'NASDAQ', country: 'US', operatingMic: 'XNAS' }, { source: 'eod', sourceCode: 'NYSE', name: 'NYSE', country: 'US', operatingMic: 'XNYS' }, { source: 'eod', sourceCode: 'TO', name: 'TSX', country: 'CA', operatingMic: 'XTSE' }, { source: 'eod', sourceCode: 'OTC', name: 'OTC', country: 'US', operatingMic: 'OTCM' }, ]); const dates = [ '2025-01-02', '2025-01-03', '2025-01-06', '2025-01-07', '2025-01-08', '2025-01-09', ]; const aaplPrices = [185.0, 188.5, 184.2, 191.0, 195.4, 193.1]; const shopCadPrices = [140.0, 145.0, 138.0, 148.5, 152.0, 149.0]; const sampleCloses: SampleCloseRecord[] = []; const fxRates: FxRateByDateRecord[] = []; for (let i = 0; i < dates.length; i++) { const date = dates[i]!; const aapl = aaplPrices[i]!; const shop = shopCadPrices[i]!; fxRates.push({ date, usdCad: 1.38 + i * 0.005 }); // AAPL: confirmed sampleCloses.push({ source: 'eod', sourceId: 'AAPL.US', date, close: aapl }); sampleCloses.push({ source: 'qm', sourceId: 'AAPL:US', date, close: aapl * 1.001 }); // SHOP XTSE: two Pass 4 mismatches sharing left endpoint (ceo:SHOP vs eod:SHOP.TO, ceo:SHOP vs qm:SHOP:CA) // and eod:SHOP.TO vs qm:SHOP:CA -> all three pairs mismatch! sampleCloses.push({ source: 'ceo', sourceId: 'ceo:SHOP', date, close: shop }); sampleCloses.push({ source: 'eod', sourceId: 'SHOP.TO', date, close: shop * 1.5 }); sampleCloses.push({ source: 'qm', sourceId: 'SHOP:CA', date, close: shop * 2.2 }); } return composeSecurityMasterRun( { sources, barSpans, exchanges, sampleCloses, fxRates }, { asOfDate: '2025-11-28' } ); } describe('composeSecurityMasterRun -> persistSecurityMaster PostgreSQL integration', () => { test('persists FB vs FB-ETF distinct listing_ids, SIVB -> SIVBQ continuity, Pass 4 conflicts (including shared left endpoint), and is idempotent on re-run', async () => { const { pool } = await createIsolatedFixture(); const composed = buildComposedExitCriterionRun(); // First run const first = await withClient(pool, client => persistSecurityMaster(client as unknown as SecurityMasterQueryable, composed.persistInput) ); expect(first.instrumentsInserted).toBe(5); expect(first.listingsInserted).toBe(7); expect(first.continuitiesInserted).toBe(1); expect(first.conflictsInserted).toBe(composed.pass4!.conflicts.length); expect(first.conflictsInserted).toBeGreaterThanOrEqual(3); // 1. Two distinct listing_ids and instrument_ids for FB common vs FB ETF const fbCommonKey = formatListingNaturalKey({ primaryIsin: 'US30303M1027', mic: 'XNAS', tickerRoot: 'FB', classSuffix: '', currency: 'USD', }); const fbEtfKey = formatListingNaturalKey({ primaryIsin: 'US4642872000', mic: 'XNAS', tickerRoot: 'FB', classSuffix: '', currency: 'USD', }); const fbCommonListingId = first.listingIdByKey.get(fbCommonKey); const fbEtfListingId = first.listingIdByKey.get(fbEtfKey); expect(fbCommonListingId).toBeDefined(); expect(fbEtfListingId).toBeDefined(); expect(fbCommonListingId).not.toBe(fbEtfListingId); const fbRows = await pool.query<{ listing_id: number; instrument_id: number; primary_isin: string; security_type: string; }>( `SELECT l.listing_id, l.instrument_id, i.primary_isin, i.security_type FROM listing l JOIN instrument i ON i.instrument_id = l.instrument_id WHERE l.ticker_root = 'FB' ORDER BY i.primary_isin` ); expect(fbRows.rows.length).toBe(2); expect(fbRows.rows[0]?.primary_isin).toBe('US30303M1027'); expect(fbRows.rows[0]?.security_type).toBe('common'); expect(fbRows.rows[1]?.primary_isin).toBe('US4642872000'); expect(fbRows.rows[1]?.security_type).toBe('etf'); expect(fbRows.rows[0]?.listing_id).not.toBe(fbRows.rows[1]?.listing_id); // 2. SIVB -> SIVBQ continuity row and delist outcomes const sivbKey = formatListingNaturalKey({ primaryIsin: 'US78486Q1013', mic: 'XNAS', tickerRoot: 'SIVB', classSuffix: '', currency: 'USD', }); const sivbqKey = formatListingNaturalKey({ primaryIsin: 'US78486Q1013', mic: 'OTCM', tickerRoot: 'SIVBQ', classSuffix: '', currency: 'USD', }); const sivbListingId = first.listingIdByKey.get(sivbKey); const sivbqListingId = first.listingIdByKey.get(sivbqKey); expect(sivbListingId).toBeDefined(); expect(sivbqListingId).toBeDefined(); const continuityRows = await pool.query<{ from_listing_id: number; to_listing_id: number; kind: string; effective_date: string; }>( `SELECT from_listing_id, to_listing_id, kind, effective_date::text FROM corporate_action_continuity` ); expect(continuityRows.rows.length).toBe(1); expect(continuityRows.rows[0]).toEqual({ from_listing_id: sivbListingId!, to_listing_id: sivbqListingId!, kind: CONTINUITY_KIND_OTC_DELIST_TRANSFER, effective_date: '2023-03-28', }); const sivbDelistRows = await pool.query<{ ticker_root: string; delist_reason: string | null; terminal_return: string | null; }>( `SELECT ticker_root, delist_reason, terminal_return::text FROM listing WHERE listing_id IN ($1, $2) ORDER BY ticker_root`, [sivbListingId, sivbqListingId] ); expect(sivbDelistRows.rows).toEqual([ { ticker_root: 'SIVB', delist_reason: 'moved_to_otc', terminal_return: null }, { ticker_root: 'SIVBQ', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1.000000' }, ]); // 3. Pass 4 price_ratio_mismatch rows persisted with both endpoints in JSONB detail const conflictRows = await pool.query<{ source: string; source_id: string; conflict_kind: string; detail: { left: { source: string; sourceId: string }; right: { source: string; sourceId: string } }; status: string; }>( `SELECT source, source_id, conflict_kind, detail, status FROM resolution_conflict ORDER BY source, source_id, detail::text` ); expect(conflictRows.rows.length).toBe(composed.pass4!.conflicts.length); const sharedLeftRows = conflictRows.rows.filter( r => r.source === 'ceo' && r.source_id === 'ceo:SHOP' && r.conflict_kind === 'price_ratio_mismatch' ); expect(sharedLeftRows.length).toBe(2); expect(sharedLeftRows.map(r => r.detail.right.sourceId).sort()).toEqual([ 'SHOP.TO', 'SHOP:CA', ]); for (const row of conflictRows.rows) { expect(row.status).toBe('open'); expect(row.detail.left.sourceId).toBe(row.source_id); expect(row.detail.right.sourceId.length).toBeGreaterThan(0); } const countsAfterFirst = await getSevenTableCounts(pool); // 4. Second identical run changes zero IDs and inserts zero rows across all 7 tables const second = await withClient(pool, client => persistSecurityMaster(client as unknown as SecurityMasterQueryable, composed.persistInput) ); expect(second.instrumentsInserted).toBe(0); expect(second.instrumentsUpdated).toBe(0); expect(second.identifierHistoryInserted).toBe(0); expect(second.listingsInserted).toBe(0); expect(second.listingsUpdated).toBe(0); expect(second.listingSymbolHistoryInserted).toBe(0); expect(second.listingSymbolHistoryUpdated).toBe(0); expect(second.providerMappingsInserted).toBe(0); expect(second.providerMappingsUpdated).toBe(0); expect(second.conflictsInserted).toBe(0); expect(second.conflictsUnchanged).toBe(composed.pass4!.conflicts.length); expect(second.continuitiesInserted).toBe(0); expect(second.continuitiesUpdated).toBe(0); expect(second.continuitiesUnchanged).toBe(1); expect(Array.from(second.instrumentIdByIsin.entries())).toEqual( Array.from(first.instrumentIdByIsin.entries()) ); expect(Array.from(second.listingIdByKey.entries())).toEqual( Array.from(first.listingIdByKey.entries()) ); const countsAfterSecond = await getSevenTableCounts(pool); expect(countsAfterSecond).toEqual(countsAfterFirst); }); });