diff --git a/test/unit/security-master-run-qa.test.ts b/test/unit/security-master-run-qa.test.ts new file mode 100644 index 00000000..e575e783 --- /dev/null +++ b/test/unit/security-master-run-qa.test.ts @@ -0,0 +1,481 @@ +import { describe, expect, test } from 'bun:test'; +import { + BarSpanIndex, + type BarSpan, + type ComputeBarSpansResult, +} from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; +import { + classifySourceExchanges, + composeSecurityMasterRun, + type ComposeSecurityMasterRunInput, + type ComposeSecurityMasterRunResult, + type FxRateByDateRecord, + type SampleCloseRecord, + type SecurityMasterSourcesResult, + type SecurityType, + type StageASourceRecord, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBTickerSourceInput, +} from '../../apps/stock/data-pipeline/src/security-master'; + +// QA edge cases for composeSecurityMasterRun (T-88): input immutability, repeat-call purity, +// bar-span input-shape equivalence, empty-vs-omitted Pass 4, out-of-window Pass 4 closes, +// multi-seed shuffle determinism, and duplicate source records. In-memory only. + +const AS_OF = '2025-11-28'; + +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 tmp = copy[i] as T; + copy[i] = copy[j] as T; + copy[j] = tmp; + } + return copy; +} + +function emptyCollectionStats( + 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 makeSources(p: { + stageARecords: StageASourceRecord[]; + eodListings: StageBEodListingInput[]; + ibContracts: StageBIbContractInput[]; + tickerSources: StageBTickerSourceInput[]; + securityTypeByIsin: Map; +}): SecurityMasterSourcesResult { + const typeStats = { + totalRecords: 0, + mapped: 0, + missingType: 0, + unknownType: 0, + invalidIsin: 0, + isinsResolved: p.securityTypeByIsin.size, + isinsConflicting: 0, + conflictsTruncated: 0, + }; + return { + stageARecords: p.stageARecords, + stageBInput: { + eodListings: p.eodListings, + ibContracts: p.ibContracts, + tickerSources: p.tickerSources, + symbolChanges: [], + }, + securityTypeRecords: [], + securityTypeByIsin: p.securityTypeByIsin, + securityTypeStats: typeStats, + securityTypeLoaderStats: { ...typeStats }, + unknownSecurityTypes: [], + securityTypeConflicts: [], + stats: { + eodSymbols: emptyCollectionStats('eodSymbols'), + ibSymbols: emptyCollectionStats('ibSymbols'), + qmSymbols: emptyCollectionStats('qmSymbols'), + ceoSymbols: emptyCollectionStats('ceoSymbols'), + eodSymbolChange: emptyCollectionStats('eodSymbolChange'), + }, + }; +} + +interface Fixture { + stageARecords: StageASourceRecord[]; + eodListings: StageBEodListingInput[]; + ibContracts: StageBIbContractInput[]; + tickerSources: StageBTickerSourceInput[]; + securityTypeByIsin: Map; + barSpans: BarSpan[]; + sampleCloses: SampleCloseRecord[]; + fxRates: FxRateByDateRecord[]; +} + +function buildFixture(): Fixture { + const rec = ( + source: 'eod' | 'ib', + sourceId: string, + isin: string, + cusip: string, + country: string, + currency: string, + name: string + ): StageASourceRecord => ({ source, sourceId, isin, cusip, country, currency, name }); + + const stageARecords: StageASourceRecord[] = [ + rec('ib', '265598', 'US0378331005', '037833100', 'US', 'USD', 'Apple Inc.'), + rec('eod', 'AAPL.US', 'US0378331005', '037833100', 'US', 'USD', 'Apple Inc'), + rec('eod', 'FB_OLD.US', 'US30303M1027', '30303M102', 'US', 'USD', 'Meta Platforms Inc'), + rec('eod', 'FB_ETF.US', 'US4642872000', '464287200', 'US', 'USD', 'FB Thematic ETF'), + rec('eod', 'SIVB.US', 'US78486Q1013', '78486Q101', 'US', 'USD', 'SVB Financial Group'), + rec('eod', 'SIVBQ.US', 'US78486Q1013', '78486Q101', 'US', 'USD', 'SVB Financial Group'), + rec('eod', 'SHOP.TO', 'CA82509L1076', '82509L107', 'CA', 'CAD', 'Shopify Inc.'), + rec('eod', 'SHOP.US', 'CA82509L1076', '82509L107', 'CA', 'USD', 'Shopify Inc.'), + rec('ib', '2001', 'CA82509L1076', '82509L107', 'CA', 'CAD', 'Shopify Inc.'), + rec('ib', '2002', 'CA82509L1076', '82509L107', 'CA', 'USD', 'Shopify Inc.'), + ]; + + const eod = (sourceId: string, ticker: string, mic: string, currency: string): StageBEodListingInput => ({ + sourceId, + ticker, + mic, + role: 'primary_venue', + currency, + span: null, + }); + const eodListings: StageBEodListingInput[] = [ + eod('AAPL.US', 'AAPL', 'XNAS', 'USD'), + eod('FB_OLD.US', 'FB', 'XNAS', 'USD'), + eod('FB_ETF.US', 'FB', 'XNAS', 'USD'), + eod('SIVB.US', 'SIVB', 'XNAS', 'USD'), + eod('SIVBQ.US', 'SIVBQ', 'OTCM', 'USD'), + eod('SHOP.TO', 'SHOP', 'XTSE', 'CAD'), + eod('SHOP.US', 'SHOP', 'XNYS', 'USD'), + ]; + + 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 span = ( + source: 'eod' | 'qm', + sourceId: string, + firstBarDate: string, + lastBarDate: string, + barCount: number + ): BarSpan => ({ source, sourceId, firstBarDate, lastBarDate, barCount }); + const barSpans: BarSpan[] = [ + span('eod', 'AAPL.US', '2010-01-04', '2025-11-28', 4000), + span('eod', 'FB_OLD.US', '2012-05-18', '2022-06-08', 2530), + span('eod', 'FB_ETF.US', '2025-01-02', '2025-11-28', 230), + span('eod', 'SIVB.US', '2015-01-02', '2023-03-10', 2060), + span('eod', 'SIVBQ.US', '2023-03-28', '2024-11-07', 410), + span('eod', 'SHOP.TO', '2015-05-21', '2025-11-28', 2650), + span('eod', 'SHOP.US', '2015-05-21', '2025-11-28', 2650), + span('qm', 'AAPL:US', '2015-01-02', '2025-11-28', 2700), + span('qm', 'FB_OLD:US', '2014-01-02', '2022-06-08', 2100), + span('qm', 'FB_ETF:US', '2025-02-03', '2025-11-28', 205), + span('qm', 'SHOP:CA', '2018-01-02', '2025-11-28', 1980), + ]; + + const securityTypeByIsin = new Map([ + ['US0378331005', 'common'], + ['US30303M1027', 'common'], + ['US4642872000', 'etf'], + ['US78486Q1013', 'common'], + ['CA82509L1076', 'common'], + ]); + + const dates = ['2025-01-02', '2025-01-03', '2025-01-06', '2025-01-07', '2025-01-08', '2025-01-09']; + const aapl = [185.0, 188.5, 184.2, 191.0, 195.4, 193.1]; + const shop = [140.0, 145.0, 138.0, 148.5, 152.0, 149.0]; + const sampleCloses: SampleCloseRecord[] = []; + const fxRates: FxRateByDateRecord[] = []; + dates.forEach((date, i) => { + fxRates.push({ date, usdCad: 1.38 + i * 0.005 }); + sampleCloses.push({ source: 'eod', sourceId: 'AAPL.US', date, close: aapl[i]! }); + sampleCloses.push({ source: 'qm', sourceId: 'AAPL:US', date, close: aapl[i]! * 1.001 }); + sampleCloses.push({ source: 'eod', sourceId: 'SHOP.TO', date, close: shop[i]! }); + sampleCloses.push({ source: 'qm', sourceId: 'SHOP:CA', date, close: shop[i]! * 1.5 }); + }); + + return { + stageARecords, + eodListings, + ibContracts, + tickerSources, + securityTypeByIsin, + barSpans, + sampleCloses, + fxRates, + }; +} + +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' }, +]); + +function toInput(f: Fixture, withPass4: boolean): ComposeSecurityMasterRunInput { + return { + sources: makeSources(f), + barSpans: f.barSpans, + exchanges: EXCHANGES, + ...(withPass4 ? { sampleCloses: f.sampleCloses, fxRates: f.fxRates } : {}), + }; +} + +function deepFreeze(value: T): T { + if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) { + if (!(value instanceof Map) && !(value instanceof BarSpanIndex)) { + Object.freeze(value); + } + for (const v of Object.values(value as Record)) { + deepFreeze(v); + } + } + return value; +} + +function expectSameOutputs( + a: ComposeSecurityMasterRunResult, + b: ComposeSecurityMasterRunResult +): void { + expect(b.reportMarkdown).toBe(a.reportMarkdown); + expect(b.conflictsCsv).toBe(a.conflictsCsv); + expect(b.overrideTemplateSql).toBe(a.overrideTemplateSql); + expect(b.persistInput).toEqual(a.persistInput); + expect(Array.from(b.persistInput.securityTypeByIsin.entries())).toEqual( + Array.from(a.persistInput.securityTypeByIsin.entries()) + ); +} + +describe('composeSecurityMasterRun QA edge cases', () => { + test('does not mutate any input (deep-frozen arrays/records, Map unchanged) and does not alias securityTypeByIsin', () => { + const f = buildFixture(); + const input = toInput(f, true); + const before = JSON.stringify({ + a: f.stageARecords, + e: f.eodListings, + i: f.ibContracts, + t: f.tickerSources, + b: f.barSpans, + s: f.sampleCloses, + x: f.fxRates, + m: Array.from(f.securityTypeByIsin.entries()), + }); + deepFreeze(input); + + const result = composeSecurityMasterRun(input, { asOfDate: AS_OF }); + + const after = JSON.stringify({ + a: f.stageARecords, + e: f.eodListings, + i: f.ibContracts, + t: f.tickerSources, + b: f.barSpans, + s: f.sampleCloses, + x: f.fxRates, + m: Array.from(f.securityTypeByIsin.entries()), + }); + expect(after).toBe(before); + // Spans were attached to clones, not to the caller's listings. + expect(f.eodListings.every(l => l.span === null)).toBe(true); + expect(result.persistInput.securityTypeByIsin).not.toBe(f.securityTypeByIsin); + expect(result.stats.barSpans.attachedEodListings).toBe(7); + }); + + test('repeated calls on the same input are deep-equal (no hidden state between runs)', () => { + const f = buildFixture(); + const first = composeSecurityMasterRun(toInput(f, true), { asOfDate: AS_OF }); + const second = composeSecurityMasterRun(toInput(f, true), { asOfDate: AS_OF }); + expectSameOutputs(first, second); + expect(second.stats).toEqual(first.stats); + }); + + test('BarSpan[], BarSpanIndex and ComputeBarSpansResult carrying the same spans compose identical reports and persist input', () => { + const f = buildFixture(); + const index = new BarSpanIndex(); + for (const s of f.barSpans) { + index.merge(s); + } + const computed: ComputeBarSpansResult = { + index, + bySource: {}, + skipped: { invalidId: 0, invalidDate: 0, invalidCount: 0, total: 0 }, + totalRowsRead: f.barSpans.length, + totalSpans: index.size, + }; + + const fromArray = composeSecurityMasterRun(toInput(f, true), { asOfDate: AS_OF }); + const fromIndex = composeSecurityMasterRun( + { ...toInput(f, true), barSpans: index }, + { asOfDate: AS_OF } + ); + const fromComputed = composeSecurityMasterRun( + { ...toInput(f, true), barSpans: computed }, + { asOfDate: AS_OF } + ); + + expectSameOutputs(fromArray, fromIndex); + expectSameOutputs(fromArray, fromComputed); + for (const r of [fromArray, fromIndex, fromComputed]) { + expect(r.stats.barSpans.recordsIn).toBe(11); + expect(r.stats.barSpans.resolved).toBe(11); + expect(r.stats.barSpans.skipped).toBe(0); + expect(r.stats.barSpans.indexedSpans).toBe(11); + } + }); + + test('an empty sampleCloses array is treated exactly like omitted sampleCloses (Pass 4 skipped, never passed)', () => { + const f = buildFixture(); + const omitted = composeSecurityMasterRun(toInput(f, false), { asOfDate: AS_OF }); + const empty = composeSecurityMasterRun( + { ...toInput(f, false), sampleCloses: [], fxRates: f.fxRates }, + { asOfDate: AS_OF } + ); + + expectSameOutputs(omitted, empty); + expect(empty.pass4).toBeNull(); + expect(empty.persistInput.pass4).toBeUndefined(); + expect('pass4' in empty.persistInput).toBe(false); + expect(empty.stats.pass4.status).toBe('skipped'); + expect(empty.stats.pass4.resolved).toBe(0); + expect(empty.stats.pass4.conflicts).toBe(0); + expect(empty.reportMarkdown).toContain('- Status: skipped (no sample closes supplied)'); + expect(empty.conflictsCsv).not.toContain('price_ratio_mismatch'); + }); + + test('sample closes only for series with no provider mapping execute Pass 4 with zero confirmations and zero conflicts', () => { + const f = buildFixture(); + const dates = ['2025-01-02', '2025-01-03', '2025-01-06', '2025-01-07', '2025-01-08', '2025-01-09']; + const closes: SampleCloseRecord[] = []; + dates.forEach((date, i) => { + closes.push({ source: 'eod', sourceId: 'UNMAPPED.US', date, close: 100 + i }); + closes.push({ source: 'qm', sourceId: 'UNMAPPED:US', date, close: (100 + i) * 3 }); + }); + + const result = composeSecurityMasterRun( + { ...toInput(f, false), sampleCloses: closes, fxRates: f.fxRates }, + { asOfDate: AS_OF } + ); + + // Executed (closes were supplied) but nothing may pass or be disputed without usable data. + expect(result.stats.pass4.status).toBe('executed'); + expect(result.pass4).not.toBeNull(); + expect(result.pass4!.stats.pairsIn).toBe(result.pass4CandidatePairs.length); + expect(result.pass4CandidatePairs.length).toBeGreaterThan(0); + expect(result.pass4!.results.every(r => r.verdict !== 'confirmed')).toBe(true); + expect(result.pass4!.conflicts).toEqual([]); + expect(result.stats.pass4.resolved).toBe(0); + expect(result.stats.conflicts.pass4).toBe(0); + const s = result.stats.pass4; + expect(s.recordsIn).toBe(s.resolved + s.unresolved + s.skipped); + expect(result.persistInput.pass4).toBe(result.pass4!); + expect(result.reportMarkdown).not.toContain('Status: skipped'); + }); + + test('determinism holds across several independent shuffle seeds, including exchange classification input order', () => { + const f = buildFixture(); + const baseline = composeSecurityMasterRun(toInput(f, true), { asOfDate: AS_OF }); + const exchangeRows = [ + { source: 'eod' as const, sourceCode: 'NASDAQ', name: 'NASDAQ', country: 'US', operatingMic: 'XNAS' }, + { source: 'eod' as const, sourceCode: 'NYSE', name: 'NYSE', country: 'US', operatingMic: 'XNYS' }, + { source: 'eod' as const, sourceCode: 'TO', name: 'TSX', country: 'CA', operatingMic: 'XTSE' }, + { source: 'eod' as const, sourceCode: 'OTC', name: 'OTC', country: 'US', operatingMic: 'OTCM' }, + ]; + + for (const seed of [1, 2, 3, 1234, 987654]) { + const shuffled: Fixture = { + stageARecords: shuffle(f.stageARecords, seed), + eodListings: shuffle(f.eodListings, seed + 1), + ibContracts: shuffle(f.ibContracts, seed + 2), + tickerSources: shuffle(f.tickerSources, seed + 3), + securityTypeByIsin: new Map(shuffle(Array.from(f.securityTypeByIsin.entries()), seed + 4)), + barSpans: shuffle(f.barSpans, seed + 5), + sampleCloses: shuffle(f.sampleCloses, seed + 6), + fxRates: shuffle(f.fxRates, seed + 7), + }; + const run = composeSecurityMasterRun( + { + ...toInput(shuffled, true), + exchanges: classifySourceExchanges(shuffle(exchangeRows, seed + 8)), + }, + { asOfDate: AS_OF } + ); + expectSameOutputs(baseline, run); + expect(run.stats).toEqual(baseline.stats); + } + }); + + test('a duplicated Stage A source record is quarantined (duplicate_source_id) and carried into report, CSV and persist input without throwing or breaking other listings', () => { + const f = buildFixture(); + const fbOld = f.stageARecords.find(r => r.sourceId === 'FB_OLD.US')!; + const dup: Fixture = { ...f, stageARecords: [...f.stageARecords, { ...fbOld }] }; + + const result = composeSecurityMasterRun(toInput(dup, true), { asOfDate: AS_OF }); + + for (const step of [ + result.stats.barSpans, + result.stats.stageA, + result.stats.stageB, + result.stats.pass6, + result.stats.pass4, + ]) { + expect(step.recordsIn).toBe(step.resolved + step.unresolved + step.skipped); + } + expect(result.stats.stageA.recordsIn).toBe(11); + const c = result.stats.conflicts; + expect(c.total).toBe(c.stageA + c.stageB + c.pass4 + c.pass6); + expect(result.report.conflicts.length).toBe(c.total); + + const dupConflicts = result.stageA.conflicts.filter( + x => x.sourceId === 'FB_OLD.US' && x.conflictKind === 'duplicate_source_id' + ); + expect(dupConflicts.length).toBeGreaterThan(0); + expect(result.persistInput.stageA.conflicts).toEqual(result.stageA.conflicts); + expect(result.conflictsCsv).toContain('duplicate_source_id'); + expect(result.conflictsCsv).toContain('FB_OLD.US'); + + // The quarantined issuer gets no listing; the FB ETF, SIVB chain and Pass 4 are unaffected. + const fbListings = result.persistInput.stageB.listings.filter(l => l.tickerRoot === 'FB'); + expect(fbListings.map(l => l.primaryIsin)).toEqual(['US4642872000']); + const sivbTransfers = result.pass6.continuities.filter( + x => x.fromListingKey.tickerRoot === 'SIVB' && x.toListingKey.tickerRoot === 'SIVBQ' + ); + expect(sivbTransfers.length).toBe(1); + expect(result.pass4!.conflicts.some(x => x.conflictKind === 'price_ratio_mismatch')).toBe(true); + // A record lost to quarantine must not be reported as 100% resolved. + const eodRow = result.report.resolutionBySource.find(r => r.source === 'eod')!; + expect(eodRow.eligibleResolvedPct).not.toBeNull(); + expect(eodRow.eligibleResolvedPct!).toBeLessThan(1); + }); +});