diff --git a/test/postgres/security-master-persist-qa.test.ts b/test/postgres/security-master-persist-qa.test.ts new file mode 100644 index 00000000..61a0c26f --- /dev/null +++ b/test/postgres/security-master-persist-qa.test.ts @@ -0,0 +1,384 @@ +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 { + DEFAULT_OTC_MICS, + formatListingNaturalKey, + linkDelistingChains, + matchInstrumentsStageA, + matchListingsStageB, + persistSecurityMaster, + type SecurityType, +} from '../../apps/stock/data-pipeline/src/security-master'; + +// QA edge cases for persistSecurityMaster that complement security-master-persist.test.ts: +// mutable-field updates on existing rows, re-runs without Pass 6, price_corr retention, +// and instruments that become un-persistable after a successful load. + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('security-master-persist-qa-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() { + 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=15000 -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 }; +} + +async function withClient(pool: Pool, fn: (client: PoolClient) => Promise): Promise { + const client = await pool.connect(); + try { + return await fn(client); + } finally { + client.release(); + } +} + +const AAPL_KEY = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', +}; +const SIVB_KEY = { + primaryIsin: 'US78486Q1013', + mic: 'XNAS', + tickerRoot: 'SIVB', + classSuffix: '', + currency: 'USD', +}; +const SIVBQ_KEY = { ...SIVB_KEY, mic: 'OTCM', tickerRoot: 'SIVBQ' }; + +/** AAPL + SIVB->SIVBQ via the real matchers; `aaplLastBar` varies per run. */ +function buildFixture(opts: { aaplLastBar?: string } = {}) { + const stageA = matchInstrumentsStageA([ + { + source: 'eod', + sourceId: 'AAPL.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc.', + }, + { + 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', + }, + ]); + const stageB = matchListingsStageB({ + instruments: stageA.instruments, + eodListings: [ + { + sourceId: 'AAPL.US', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '1980-12-12', lastBarDate: opts.aaplLastBar ?? '2026-11-27' }, + }, + { + sourceId: 'SIVB.US', + ticker: 'SIVB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '1987-10-26', lastBarDate: '2023-03-10' }, + }, + { + sourceId: 'SIVBQ.US', + ticker: 'SIVBQ', + mic: 'OTCM', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2023-03-28', lastBarDate: '2024-11-07' }, + }, + ], + ibContracts: [], + tickerSources: [], + }); + const pass6 = linkDelistingChains( + { listings: stageB.listings, otcMics: DEFAULT_OTC_MICS }, + { asOfDate: '2026-11-27' } + ); + const securityTypeByIsin = new Map([ + ['US0378331005', 'common'], + ['US78486Q1013', 'common'], + ]); + return { stageA, stageB, pass6, securityTypeByIsin }; +} + +describe.skipIf(!url)('persistSecurityMaster PostgreSQL QA edge cases', () => { + test('updates changed instrument fields in place, keeps instrument_id, and appends (never replaces) CUSIP history', async () => { + const f = await createIsolatedFixture(); + const run1 = await withClient(f.pool, c => persistSecurityMaster(c, buildFixture())); + const aaplInstrumentId = run1.instrumentIdByIsin.get('US0378331005'); + const aaplListingId = run1.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY)); + expect(aaplInstrumentId).toBeDefined(); + + // Stage A would quarantine an ISIN/CUSIP mismatch, so emulate a corrected upstream CUSIP and + // renamed issuer by editing the matcher output directly. + const base = buildFixture(); + const renamed = { + ...base, + stageA: { + ...base.stageA, + instruments: base.stageA.instruments.map(inst => + inst.primaryIsin === 'US0378331005' + ? { ...inst, primaryCusip: '037833101', canonicalName: 'Apple Incorporated' } + : inst + ), + }, + }; + const run2 = await withClient(f.pool, c => persistSecurityMaster(c, renamed)); + + expect(run2.instrumentsInserted).toBe(0); + expect(run2.instrumentsUpdated).toBe(1); + expect(run2.instrumentsUnchanged).toBe(1); + expect(run2.identifierHistoryInserted).toBe(1); // new CUSIP only + expect(run2.instrumentIdByIsin.get('US0378331005')).toBe(aaplInstrumentId!); + expect(run2.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY))).toBe(aaplListingId!); + + const inst = ( + await f.pool.query<{ instrument_id: number; primary_cusip: string; canonical_name: string }>( + `SELECT instrument_id, btrim(primary_cusip) AS primary_cusip, canonical_name + FROM instrument WHERE primary_isin = 'US0378331005'` + ) + ).rows; + expect(inst).toEqual([ + { instrument_id: aaplInstrumentId!, primary_cusip: '037833101', canonical_name: 'Apple Incorporated' }, + ]); + + const history = ( + await f.pool.query<{ id_type: string; id_value: string }>( + `SELECT id_type, id_value FROM instrument_identifier_history + WHERE instrument_id = $1 ORDER BY id_type, id_value`, + [aaplInstrumentId] + ) + ).rows; + expect(history).toEqual([ + { id_type: 'CUSIP', id_value: '037833100' }, + { id_type: 'CUSIP', id_value: '037833101' }, + { id_type: 'ISIN', id_value: 'US0378331005' }, + ]); + }); + + test('extending listed_to updates the listing and its single symbol-history row in place', async () => { + const f = await createIsolatedFixture(); + const run1 = await withClient(f.pool, c => persistSecurityMaster(c, buildFixture())); + const aaplListingId = run1.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY))!; + + const run2 = await withClient(f.pool, c => + persistSecurityMaster(c, buildFixture({ aaplLastBar: '2026-12-31' })) + ); + expect(run2.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY))).toBe(aaplListingId); + expect(run2.listingsInserted).toBe(0); + expect(run2.listingsUpdated).toBe(1); + expect(run2.listingsUnchanged).toBe(2); + expect(run2.listingSymbolHistoryInserted).toBe(0); + expect(run2.listingSymbolHistoryUpdated).toBe(1); + expect(run2.listingSymbolHistoryUnchanged).toBe(2); + + const listing = ( + await f.pool.query<{ listed_to: string }>( + `SELECT to_char(listed_to, 'YYYY-MM-DD') AS listed_to FROM listing WHERE listing_id = $1`, + [aaplListingId] + ) + ).rows; + expect(listing).toEqual([{ listed_to: '2026-12-31' }]); + + const symbols = ( + await f.pool.query<{ ticker: string; valid_from: string; valid_to: string | null }>( + `SELECT ticker, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, + to_char(valid_to, 'YYYY-MM-DD') AS valid_to + FROM listing_symbol_history WHERE listing_id = $1`, + [aaplListingId] + ) + ).rows; + expect(symbols).toEqual([{ ticker: 'AAPL', valid_from: '1980-12-12', valid_to: '2026-12-31' }]); + }); + + test('a re-run without pass6 leaves delist_reason, terminal_return and continuities untouched', async () => { + const f = await createIsolatedFixture(); + const full = buildFixture(); + const run1 = await withClient(f.pool, c => persistSecurityMaster(c, full)); + expect(run1.continuitiesInserted).toBe(1); + + const snapshot = async () => + ( + await f.pool.query( + `SELECT listing_id, delist_reason, terminal_return::text AS terminal_return + FROM listing ORDER BY listing_id` + ) + ).rows; + const before = await snapshot(); + const continuityBefore = (await f.pool.query('SELECT * FROM corporate_action_continuity')).rows; + + const run2 = await withClient(f.pool, c => + persistSecurityMaster(c, { + stageA: full.stageA, + stageB: full.stageB, + securityTypeByIsin: full.securityTypeByIsin, + }) + ); + + expect(run2.listingsUpdated).toBe(0); + expect(run2.listingsUnchanged).toBe(3); + expect(run2.pass6OutcomesApplied).toBe(0); + expect(run2.continuitiesInserted + run2.continuitiesUpdated + run2.continuitiesUnchanged).toBe(0); + expect(await snapshot()).toEqual(before); + expect((await f.pool.query('SELECT * FROM corporate_action_continuity')).rows).toEqual( + continuityBefore + ); + + const sivbId = run2.listingIdByKey.get(formatListingNaturalKey(SIVB_KEY)); + const sivbRow = before.find(r => r.listing_id === sivbId); + expect(sivbRow?.delist_reason).toBe('moved_to_otc'); + expect(run2.listingIdByKey.get(formatListingNaturalKey(SIVBQ_KEY))).toBeDefined(); + }); + + test('keeps price_corr when a matcher update keeps the same listing and clears it when the listing changes', async () => { + const f = await createIsolatedFixture(); + const base = buildFixture(); + const run1 = await withClient(f.pool, c => persistSecurityMaster(c, base)); + const aaplListingId = run1.listingIdByKey.get(formatListingNaturalKey(AAPL_KEY))!; + const sivbListingId = run1.listingIdByKey.get(formatListingNaturalKey(SIVB_KEY))!; + + const aaplMapping = base.stageB.providerMappings.find(m => m.sourceId === 'AAPL.US'); + expect(aaplMapping).toBeDefined(); + const validFrom = aaplMapping!.validFrom ?? '1900-01-01'; + await f.pool.query( + `UPDATE provider_mapping SET price_corr = 0.9876 + WHERE source = 'eod' AND source_id = 'AAPL.US' AND valid_from = $1::date`, + [validFrom] + ); + + const readMapping = async () => + ( + await f.pool.query<{ listing_id: number; valid_to: string | null; price_corr: string | null }>( + `SELECT listing_id, to_char(valid_to, 'YYYY-MM-DD') AS valid_to, price_corr::text AS price_corr + FROM provider_mapping + WHERE source = 'eod' AND source_id = 'AAPL.US' AND valid_from = $1::date`, + [validFrom] + ) + ).rows; + + // Same listing, new valid_to -> updated, price_corr retained. + const withNewValidTo = { + ...base, + stageB: { + ...base.stageB, + providerMappings: base.stageB.providerMappings.map(m => + m === aaplMapping ? { ...m, validTo: '2030-01-01' } : m + ), + }, + }; + const run2 = await withClient(f.pool, c => persistSecurityMaster(c, withNewValidTo)); + expect(run2.providerMappingsUpdated).toBe(1); + expect(await readMapping()).toEqual([ + { listing_id: aaplListingId, valid_to: '2030-01-01', price_corr: '0.9876' }, + ]); + + // Redirected to a different listing -> price_corr must not carry over. + const redirected = { + ...base, + stageB: { + ...base.stageB, + providerMappings: base.stageB.providerMappings.map(m => + m === aaplMapping ? { ...m, validTo: '2030-01-01', listingKey: SIVB_KEY } : m + ), + }, + }; + const run3 = await withClient(f.pool, c => persistSecurityMaster(c, redirected)); + expect(run3.providerMappingsUpdated).toBe(1); + expect(await readMapping()).toEqual([ + { listing_id: sivbListingId, valid_to: '2030-01-01', price_corr: null }, + ]); + }); + + test('an instrument that loses its security type on a later run is skipped without deleting or altering persisted rows', async () => { + const f = await createIsolatedFixture(); + const base = buildFixture(); + await withClient(f.pool, c => persistSecurityMaster(c, base)); + + const dump = async () => { + const out: Record = {}; + for (const [table, order] of [ + ['instrument', 'instrument_id'], + ['instrument_identifier_history', 'id_type, id_value'], + ['listing', 'listing_id'], + ['listing_symbol_history', 'listing_id, ticker, valid_from'], + ['provider_mapping', 'source, source_id, valid_from'], + ['corporate_action_continuity', 'from_listing_id, effective_date'], + ] as const) { + out[table] = (await f.pool.query(`SELECT * FROM ${table} ORDER BY ${order}`)).rows; + } + return out; + }; + const before = await dump(); + + const run2 = await withClient(f.pool, c => + persistSecurityMaster(c, { + ...base, + securityTypeByIsin: new Map([['US0378331005', 'common']]), + }) + ); + + expect(run2.instrumentsSkipped).toBe(1); + expect(run2.skippedByReason.instruments.missing_security_type).toBe(1); + expect(run2.skippedByReason.listings.skipped_instrument).toBe(2); + expect(run2.pass6OutcomesSkipped).toBe(2); // SIVB + SIVBQ + expect(run2.skippedByReason.continuities.missing_both_listings).toBe(1); + expect(run2.instrumentIdByIsin.has('US78486Q1013')).toBe(false); + expect(run2.instrumentsInserted + run2.instrumentsUpdated).toBe(0); + expect(run2.listingsInserted + run2.listingsUpdated).toBe(0); + expect(run2.providerMappingsInserted + run2.providerMappingsUpdated).toBe(0); + expect(await dump()).toEqual(before); + }); +});