diff --git a/test/unit/security-master-listing-stage-b-edge.test.ts b/test/unit/security-master-listing-stage-b-edge.test.ts new file mode 100644 index 00000000..a088570f --- /dev/null +++ b/test/unit/security-master-listing-stage-b-edge.test.ts @@ -0,0 +1,546 @@ +import { describe, expect, test } from 'bun:test'; +import { + matchListingsStageB, + MAX_TICKER_ROOT_LENGTH, + STAGE_B_SOURCES, + type StageAInstrumentCandidate, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBInput, + type StageBMatchResult, + type StageBTickerSourceInput, +} from '../../apps/stock/data-pipeline/src/security-master'; +import { MAX_CLASS_SUFFIX_LENGTH } from '../../apps/stock/data-pipeline/src/normalization/ticker'; + +// QA edge cases for Pass 3 Stage B (T-56) not covered by security-master-listing-stage-b.test.ts. + +type Member = StageAInstrumentCandidate['members'][number]; + +function instrument(primaryIsin: string, members: Member[]): StageAInstrumentCandidate { + return { primaryIsin, primaryCusip: null, issuerCountry: 'US', canonicalName: null, members }; +} + +function eodMember(sourceId: string, currency = 'USD'): Member { + return { source: 'eod', sourceId, currency, method: 'tier1_isin' }; +} + +function ibMember(sourceId: string, currency = 'USD'): Member { + return { source: 'ib', sourceId, currency, method: 'tier2_cusip' }; +} + +function eod( + sourceId: string, + ticker: string, + mic: string, + span: [string, string] | null, + currency: string | null | undefined = 'USD' +): StageBEodListingInput { + return { + sourceId, + ticker, + mic, + role: 'primary_venue', + currency, + span: span === null ? null : { firstBarDate: span[0], lastBarDate: span[1] }, + }; +} + +function qm( + sourceId: string, + ticker: string, + mic: string, + span: [string, string] | null, + currency = 'USD', + source: 'qm' | 'ceo' = 'qm' +): StageBTickerSourceInput { + return { + source, + sourceId, + ticker, + mic, + role: 'primary_venue', + currency, + span: span === null ? null : { firstBarDate: span[0], lastBarDate: span[1] }, + }; +} + +function assertReconciles(result: StageBMatchResult): void { + expect(result.stats.totalListings).toBe(result.listings.length); + expect(result.stats.totalProviderMappings).toBe(result.providerMappings.length); + for (const source of STAGE_B_SOURCES) { + const s = result.stats.bySource[source]; + expect(s.matched).toBe(result.providerMappings.filter(m => m.source === source).length); + expect(s.unresolved).toBe(result.unresolved.filter(u => u.source === source).length); + expect(s.conflict).toBe(result.conflicts.filter(c => c.source === source).length); + expect(s.matched + s.unresolved + s.conflict).toBe(s.total); + } +} + +function makeRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function shuffle(items: readonly T[], seed: number): T[] { + const copy = [...items]; + const rng = makeRng(seed); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + const a = copy[i] as T; + copy[i] = copy[j] as T; + copy[j] = a; + } + return copy; +} + +function deepFreeze(value: T): T { + if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) { + Object.freeze(value); + for (const key of Object.keys(value)) { + deepFreeze((value as Record)[key]); + } + } + return value; +} + +const FB_OLD_ISIN = 'US30303M1027'; +const FB_NEW_ISIN = 'US0000000026'; + +function reusedFbInput(tickerSources: StageBTickerSourceInput[]): StageBInput { + return { + instruments: [ + instrument(FB_OLD_ISIN, [eodMember('FB_OLD')]), + instrument(FB_NEW_ISIN, [eodMember('FB_NEW')]), + ], + eodListings: [ + eod('FB_OLD', 'FB', 'XNAS', ['2012-05-18', '2022-06-08']), + eod('FB_NEW', 'FB', 'XNAS', ['2025-01-02', '2025-11-26']), + ], + ibContracts: [], + tickerSources, + }; +} + +describe('Pass 3 Stage B listing matcher — QA edge cases', () => { + test('span overlap is inclusive on both edges of a reused-ticker boundary and tolerance only widens it', () => { + const tickerSources = [ + qm('QM_LAST_DAY_OLD', 'FB', 'XNAS', ['2022-06-08', '2022-06-08']), + qm('QM_DAY_AFTER_OLD', 'FB', 'XNAS', ['2022-06-09', '2022-06-09']), + qm('QM_DAY_BEFORE_NEW', 'FB', 'XNAS', ['2025-01-01', '2025-01-01']), + qm('QM_FIRST_DAY_NEW', 'FB', 'XNAS', ['2025-01-02', '2025-01-02']), + ]; + + const strict = matchListingsStageB(reusedFbInput(tickerSources)); + const strictMap = Object.fromEntries( + strict.providerMappings + .filter(m => m.source === 'qm') + .map(m => [m.sourceId, m.listingKey.primaryIsin]) + ); + expect(strictMap).toEqual({ QM_LAST_DAY_OLD: FB_OLD_ISIN, QM_FIRST_DAY_NEW: FB_NEW_ISIN }); + expect(strict.unresolved.map(u => [u.sourceId, u.reason])).toEqual([ + ['QM_DAY_AFTER_OLD', 'no_span_overlap'], + ['QM_DAY_BEFORE_NEW', 'no_span_overlap'], + ]); + assertReconciles(strict); + + const tolerant = matchListingsStageB(reusedFbInput(tickerSources), { + spanOverlapToleranceDays: 1, + }); + const tolerantMap = Object.fromEntries( + tolerant.providerMappings + .filter(m => m.source === 'qm') + .map(m => [m.sourceId, m.listingKey.primaryIsin]) + ); + expect(tolerantMap).toEqual({ + QM_LAST_DAY_OLD: FB_OLD_ISIN, + QM_DAY_AFTER_OLD: FB_OLD_ISIN, + QM_DAY_BEFORE_NEW: FB_NEW_ISIN, + QM_FIRST_DAY_NEW: FB_NEW_ISIN, + }); + expect(tolerant.unresolved).toEqual([]); + assertReconciles(tolerant); + }); + + test('ticker change FB→META keeps one instrument and never routes a stale FB alias to another security', () => { + // EOD stores Meta's whole history under META; a pre-2022 QM "FB" record must not be silently + // attached to anything, while QM "META" before and after the change resolves to one listing. + const result = matchListingsStageB({ + instruments: [ + instrument(FB_OLD_ISIN, [eodMember('META.US'), ibMember('ib-meta')]), + instrument(FB_NEW_ISIN, [eodMember('FB_NEW')]), + ], + eodListings: [ + eod('META.US', 'META', 'XNAS', ['2012-05-18', '2025-11-26']), + eod('FB_NEW', 'FB', 'XNAS', ['2025-01-02', '2025-11-26']), + ], + ibContracts: [{ sourceId: 'ib-meta', conid: 107113386, currency: 'USD', primaryExchange: 'NASDAQ' }], + tickerSources: [ + qm('QM_FB_2015', 'FB', 'XNAS', ['2015-01-02', '2015-12-31']), + qm('QM_META_PRE', 'META', 'XNAS', ['2022-06-08', '2022-06-08']), + qm('QM_META_POST', 'META', 'XNAS', ['2022-06-09', '2022-06-09']), + ], + }); + + const byId = new Map(result.providerMappings.map(m => [m.sourceId, m.listingKey])); + expect(byId.get('QM_META_PRE')).toEqual(byId.get('QM_META_POST')); + expect(byId.get('QM_META_PRE')?.primaryIsin).toBe(FB_OLD_ISIN); + expect(byId.has('QM_FB_2015')).toBe(false); + expect(result.unresolved).toEqual([ + { source: 'qm', sourceId: 'QM_FB_2015', reason: 'no_span_overlap', primaryIsin: null }, + ]); + const meta = result.listings.filter(l => l.primaryIsin === FB_OLD_ISIN); + expect(meta).toHaveLength(1); + expect(meta[0]?.ibConid).toBe(107113386); + assertReconciles(result); + }); + + test('accepts ticker root of exactly 24 chars and class suffix of exactly MAX_CLASS_SUFFIX_LENGTH', () => { + const root24 = 'R'.repeat(MAX_TICKER_ROOT_LENGTH); + const suffix12 = 'S'.repeat(MAX_CLASS_SUFFIX_LENGTH); + const result = matchListingsStageB({ + instruments: [instrument('US9999999991', [eodMember('BOUND')])], + eodListings: [eod('BOUND', `${root24}.${suffix12}`, 'XNYS', ['2020-01-02', '2024-12-31'])], + ibContracts: [], + tickerSources: [qm('QM_BOUND', `${root24}-${suffix12}`, 'XNYS', ['2021-01-04', '2021-12-31'])], + }); + + expect(result.unresolved).toEqual([]); + expect(result.listings).toHaveLength(1); + expect(result.listings[0]?.tickerRoot).toBe(root24); + expect(result.listings[0]?.classSuffix).toBe(suffix12); + expect(result.providerMappings.map(m => [m.source, m.method])).toEqual([ + ['eod', 'tier1_isin'], + ['qm', 'tier3_ticker_span'], + ]); + assertReconciles(result); + }); + + test('normalizes lowercase MIC/currency and falls back to member currency when provider currency is absent', () => { + const result = matchListingsStageB({ + instruments: [ + instrument('CA1111111111', [ + eodMember('EOD_CAD', 'CAD'), + eodMember('EOD_USD', 'USD'), + ibMember('IB_CAD', 'CAD'), + ibMember('IB_USD', 'usd'), + ]), + ], + eodListings: [ + { ...eod('EOD_CAD', 'abc', ' xtse ', ['2020-01-02', '2024-12-31']), currency: undefined }, + eod('EOD_USD', 'ABC', 'XNYS', ['2020-01-02', '2024-12-31'], null), + ], + ibContracts: [ + { sourceId: 'IB_CAD', conid: 11, currency: 'cad', primaryExchange: ' tse ' }, + { sourceId: 'IB_USD', conid: 12, currency: null, primaryExchange: null }, + ], + tickerSources: [qm('CEO_ABC', 'abc.to', 'xtse', ['2022-01-03', '2022-01-03'], 'cad', 'ceo')], + }); + + expect(result.unresolved).toEqual([]); + expect(result.conflicts).toEqual([]); + expect( + result.listings.map(l => [l.mic, l.currency, l.tickerRoot, l.ibConid, l.ibPrimaryExchange]) + ).toEqual([ + ['XNYS', 'USD', 'ABC', 12, null], + ['XTSE', 'CAD', 'ABC', 11, 'TSE'], + ]); + expect(result.providerMappings.find(m => m.source === 'ceo')?.listingKey.mic).toBe('XTSE'); + assertReconciles(result); + }); + + test('IB conid attaches only within its own instrument, even when another instrument has a same-currency listing', () => { + const result = matchListingsStageB({ + instruments: [ + instrument('US0000000A01', [eodMember('A_CAD', 'CAD'), ibMember('IB_A_USD', 'USD')]), + instrument('US0000000B02', [eodMember('B_USD', 'USD')]), + ], + eodListings: [ + eod('A_CAD', 'AAA', 'XTSE', null, 'CAD'), + eod('B_USD', 'AAA', 'XNYS', null, 'USD'), + ], + ibContracts: [{ sourceId: 'IB_A_USD', conid: 5, currency: 'USD', primaryExchange: 'NYSE' }], + tickerSources: [], + }); + + expect(result.listings.every(l => l.ibConid === null)).toBe(true); + expect(result.unresolved).toEqual([ + { source: 'ib', sourceId: 'IB_A_USD', reason: 'no_listing_for_currency', primaryIsin: 'US0000000A01' }, + ]); + assertReconciles(result); + }); + + test('two IB members carrying the same conid for one listing still conflict and attach nothing', () => { + const result = matchListingsStageB({ + instruments: [instrument('US0000000C03', [eodMember('C'), ibMember('IB_C1'), ibMember('IB_C2')])], + eodListings: [eod('C', 'CCC', 'XNAS', null)], + ibContracts: [ + { sourceId: 'IB_C1', conid: 77, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'IB_C2', conid: 77, currency: 'USD', primaryExchange: 'NASDAQ' }, + ], + tickerSources: [], + }); + + expect(result.listings[0]?.ibConid).toBeNull(); + expect(result.providerMappings.filter(m => m.source === 'ib')).toEqual([]); + expect(result.conflicts.map(c => [c.sourceId, c.conflictKind, c.detail.competingConids])).toEqual([ + ['IB_C1', 'competing_ib_conid', [77]], + ['IB_C2', 'competing_ib_conid', [77]], + ]); + assertReconciles(result); + }); + + test('ambiguous overlap wins over a same-key listing with missing span; a lone missing-span partner blocks a match', () => { + const base = (extraNullSpan: boolean): StageBInput => ({ + instruments: [ + instrument('US00000000D1', [eodMember('D1')]), + instrument('US00000000D2', [eodMember('D2')]), + instrument('US00000000D3', [eodMember('D3')]), + ], + eodListings: [ + eod('D1', 'DDD', 'XNAS', ['2020-01-02', '2024-12-31']), + extraNullSpan ? eod('D2', 'DDD', 'XNAS', null) : eod('D2', 'DDD', 'XNAS', ['2021-01-04', '2022-12-30']), + eod('D3', 'DDD', 'XNAS', null), + ], + ibContracts: [], + tickerSources: [qm('QM_D', 'DDD', 'XNAS', ['2021-06-01', '2021-06-30'])], + }); + + const ambiguous = matchListingsStageB(base(false)); + expect(ambiguous.conflicts.map(c => [c.sourceId, c.conflictKind])).toEqual([ + ['QM_D', 'ambiguous_ticker_span'], + ]); + expect(ambiguous.conflicts[0]?.detail.candidateListingKeys.map(k => k.primaryIsin)).toEqual([ + 'US00000000D1', + 'US00000000D2', + ]); + + const blocked = matchListingsStageB(base(true)); + expect(blocked.providerMappings.filter(m => m.source === 'qm')).toEqual([]); + expect(blocked.unresolved).toEqual([ + { source: 'qm', sourceId: 'QM_D', reason: 'missing_span', primaryIsin: null }, + ]); + assertReconciles(ambiguous); + assertReconciles(blocked); + }); + + test('same-key EOD members merge spans the same way regardless of order, including a null-span member', () => { + const members = [eodMember('E_NULL'), eodMember('E_EARLY'), eodMember('E_LATE')]; + const listings = [ + eod('E_NULL', 'EEE', 'XNAS', null), + eod('E_EARLY', 'EEE', 'XNAS', ['2010-01-04', '2015-12-31']), + eod('E_LATE', 'EEE', 'XNAS', ['2014-01-02', '2025-11-26']), + ]; + const run = (seed: number): StageBMatchResult => + matchListingsStageB({ + instruments: [instrument('US00000000E1', shuffle(members, seed))], + eodListings: shuffle(listings, seed + 1), + ibContracts: [], + tickerSources: [], + }); + + const baseline = run(1); + expect(baseline.listings).toHaveLength(1); + expect(baseline.listings[0]?.listedFrom).toBe('2010-01-04'); + expect(baseline.listings[0]?.listedTo).toBe('2025-11-26'); + expect(baseline.providerMappings).toHaveLength(3); + for (const seed of [2, 3, 4, 5, 6, 7, 8]) { + expect(run(seed)).toEqual(baseline); + } + }); + + test('qm and ceo records sharing a sourceId are not duplicates; duplicate EOD members across instruments are', () => { + const result = matchListingsStageB({ + instruments: [ + instrument('US00000000F1', [eodMember('SHARED_EOD'), eodMember('F1')]), + instrument('US00000000F2', [eodMember('SHARED_EOD')]), + ], + eodListings: [eod('SHARED_EOD', 'FFF', 'XNAS', null), eod('F1', 'FFG', 'XNAS', ['2020-01-02', '2024-12-31'])], + ibContracts: [], + tickerSources: [ + qm('SAME_ID', 'FFG', 'XNAS', ['2021-01-04', '2021-12-31'], 'USD', 'qm'), + qm('SAME_ID', 'FFG', 'XNAS', ['2021-01-04', '2021-12-31'], 'USD', 'ceo'), + ], + }); + + expect(result.conflicts.map(c => [c.source, c.sourceId, c.detail.primaryIsin])).toEqual([ + ['eod', 'SHARED_EOD', 'US00000000F1'], + ['eod', 'SHARED_EOD', 'US00000000F2'], + ]); + expect(result.listings.map(l => l.tickerRoot)).toEqual(['FFG']); + expect(result.providerMappings.map(m => [m.source, m.sourceId])).toEqual([ + ['ceo', 'SAME_ID'], + ['eod', 'F1'], + ['qm', 'SAME_ID'], + ]); + assertReconciles(result); + }); + + test('does not mutate frozen inputs and returns identical output on repeated calls', () => { + const input = deepFreeze( + reusedFbInput([ + qm('QM_FB_2015', 'FB', 'XNAS', ['2015-01-02', '2015-12-31']), + qm('QM_FB_2023', 'FB', 'XNAS', ['2023-01-03', '2023-12-29']), + ]) + ); + const snapshot = JSON.stringify(input); + const first = matchListingsStageB(input); + const second = matchListingsStageB(input); + expect(second).toEqual(first); + expect(JSON.stringify(input)).toBe(snapshot); + }); + + test('failure-heavy input is invariant to array shuffles and to Map insertion order', () => { + const instruments: StageAInstrumentCandidate[] = [ + instrument('US00000000G1', [ + eodMember('G_OK'), + eodMember('G_COMP'), + eodMember('G_FUND'), + eodMember('G_DUP'), + ibMember('IB_G1'), + ibMember('IB_G2'), + ibMember('IB_G_EUR', 'EUR'), + ]), + instrument('US00000000G2', [eodMember('G_DUP'), eodMember('G_X1'), eodMember('G_X2'), ibMember('IB_GX')]), + ]; + const eodListings: StageBEodListingInput[] = [ + eod('G_OK', 'GGG', 'XNAS', ['2018-01-02', '2024-12-31']), + { ...eod('G_COMP', 'GGG', 'XNAS', null), mic: null, role: 'composite' }, + { ...eod('G_FUND', 'GGGFX', 'XNAS', null), mic: null, role: 'excluded_fund' }, + eod('G_DUP', 'GGH', 'XNAS', null), + eod('G_X1', 'GXX', 'XNAS', ['2019-01-02', '2020-12-31']), + eod('G_X2', 'GXX', 'XNYS', ['2019-01-02', '2020-12-31']), + ]; + const ibContracts: StageBIbContractInput[] = [ + { sourceId: 'IB_G1', conid: 1, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'IB_G2', conid: 2, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'IB_G_EUR', conid: 3, currency: 'EUR', primaryExchange: 'IBIS' }, + { sourceId: 'IB_GX', conid: 4, currency: 'USD', primaryExchange: 'NYSE' }, + ]; + const tickerSources: StageBTickerSourceInput[] = [ + qm('QM_G', 'GGG', 'XNAS', ['2020-01-02', '2020-12-31']), + qm('QM_G', 'GGG', 'XNAS', ['2021-01-04', '2021-12-31']), + qm('QM_GX', 'GXX', 'XNYS', ['2020-01-02', '2020-01-02']), + qm('CEO_NONE', 'ZZZ.V', 'XTSX', ['2020-01-02', '2020-01-02'], 'CAD', 'ceo'), + ]; + + const baseline = matchListingsStageB({ instruments, eodListings, ibContracts, tickerSources }); + assertReconciles(baseline); + expect(baseline.stats.excludedFunds).toBe(1); + expect(baseline.conflicts.map(c => c.conflictKind).sort()).toEqual([ + 'ambiguous_ib_listing', + 'competing_ib_conid', + 'competing_ib_conid', + 'duplicate_source_id', + 'duplicate_source_id', + 'duplicate_source_id', + 'duplicate_source_id', + ]); + const baselineJson = JSON.stringify(baseline); + + for (const seed of [11, 23, 97, 4242, 77777]) { + const shuffledEod = shuffle(eodListings, seed + 1); + const shuffledIb = shuffle(ibContracts, seed + 2); + const arrayResult = matchListingsStageB({ + instruments: shuffle(instruments, seed).map((inst, i) => ({ + ...inst, + members: shuffle(inst.members, seed * 31 + i), + })), + eodListings: shuffledEod, + ibContracts: shuffledIb, + tickerSources: shuffle(tickerSources, seed + 3), + }); + expect(JSON.stringify(arrayResult)).toBe(baselineJson); + + const mapResult = matchListingsStageB({ + instruments, + eodListings: new Map(shuffledEod.map(({ sourceId, ...rest }) => [sourceId, rest])), + ibContracts: new Map(shuffledIb.map(({ sourceId, ...rest }) => [sourceId, rest])), + tickerSources, + }); + expect(JSON.stringify(mapResult)).toBe(baselineJson); + } + }); + + test('rejects invalid options and structurally invalid inputs with errors naming the location', () => { + const empty: StageBInput = { instruments: [], eodListings: [], ibContracts: [], tickerSources: [] }; + expect(() => matchListingsStageB(empty, { spanOverlapToleranceDays: Number.NaN })).toThrow(RangeError); + expect(() => matchListingsStageB(empty, { spanOverlapToleranceDays: Infinity })).toThrow(RangeError); + expect(() => + matchListingsStageB(empty, { spanOverlapToleranceDays: '1' as unknown as number }) + ).toThrow(RangeError); + expect(() => matchListingsStageB(empty, null as unknown as object)).toThrow(TypeError); + expect(matchListingsStageB(empty, { spanOverlapToleranceDays: undefined }).listings).toEqual([]); + expect(() => matchListingsStageB(null as unknown as StageBInput)).toThrow(TypeError); + + expect(() => + matchListingsStageB({ + ...empty, + instruments: [instrument('US0000000001', []), instrument('US0000000001', [])], + }) + ).toThrow(/Duplicate primaryIsin.*instruments\[1\]/); + + expect(() => + matchListingsStageB({ + ...empty, + instruments: [ + instrument('US0000000001', [ + eodMember('A'), + { source: 'yahoo', sourceId: 'B', currency: 'USD', method: 'tier1_isin' } as unknown as Member, + ]), + ], + }) + ).toThrow(/instruments\[0\]\.members\[1\]/); + + expect(() => + matchListingsStageB({ + ...empty, + instruments: [ + instrument('US0000000001', [ + { source: 'eod', sourceId: 'A', currency: 'USD', method: 'tier3_ticker_span' } as unknown as Member, + ]), + ], + }) + ).toThrow(/instruments\[0\]\.members\[0\]/); + + expect(() => + matchListingsStageB({ + ...empty, + instruments: [instrument('US0000000001', [{ ...eodMember('A'), sourceId: 42 as unknown as string }])], + }) + ).toThrow(/instruments\[0\]\.members\[0\]/); + + expect(() => + matchListingsStageB({ + ...empty, + ibContracts: [ + { sourceId: 'ok', conid: 1, primaryExchange: null }, + { sourceId: 7 as unknown as string, conid: 2, primaryExchange: null }, + ], + }) + ).toThrow(/ibContracts\[1\]/); + + expect(() => + matchListingsStageB({ + ...empty, + tickerSources: [{ ...qm('Q', 'A', 'XNAS', null), source: 'ib' as unknown as 'qm' }], + }) + ).toThrow(/tickerSources\[0\]/); + + expect(() => + matchListingsStageB({ + ...empty, + eodListings: [{ ...eod('E', 'A', 'XNAS', null), role: 'otc' as unknown as 'composite' }], + }) + ).toThrow(/eodListings\[0\]/); + + expect(() => + matchListingsStageB({ ...empty, eodListings: {} as unknown as StageBEodListingInput[] }) + ).toThrow(TypeError); + }); +});