import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { describe, expect, test } from 'bun:test'; import { cusipToIsin, isValidCusip, } from '../../apps/stock/data-pipeline/src/normalization/identifiers'; import { isStageASource, matchInstrumentsStageA, STAGE_A_SOURCES, type StageAMatchResult, type StageASource, type StageASourceRecord, } from '../../apps/stock/data-pipeline/src/security-master'; const stageASourcePath = fileURLToPath( new URL( '../../apps/stock/data-pipeline/src/security-master/instrument-stage-a.ts', import.meta.url ) ); const ISIN_SCHEMA_PATTERN = /^[A-Z]{2}[A-Z0-9]{9}[0-9]$/; const ALLOWED_METHODS = new Set(['tier1_isin', 'tier2_cusip']); function assertConservationAndSchema(result: StageAMatchResult, inputLength: number): void { expect(result.stats.totalInputRecords).toBe(inputLength); expect(result.stats.totalInstruments).toBe(result.instruments.length); const ibStats = result.stats.bySource.ib; const eodStats = result.stats.bySource.eod; expect(ibStats.total + eodStats.total).toBe(inputLength); expect(ibStats.tier1Isin + ibStats.tier2Cusip + ibStats.unresolved + ibStats.conflict).toBe( ibStats.total ); expect(eodStats.tier1Isin + eodStats.tier2Cusip + eodStats.unresolved + eodStats.conflict).toBe( eodStats.total ); let totalMembers = 0; for (const instrument of result.instruments) { expect(ISIN_SCHEMA_PATTERN.test(instrument.primaryIsin)).toBe(true); expect(instrument.issuerCountry).toHaveLength(2); expect(instrument.issuerCountry).toBe(instrument.primaryIsin.slice(0, 2)); if (instrument.primaryCusip !== null) { expect(instrument.primaryCusip).toHaveLength(9); expect(isValidCusip(instrument.primaryCusip)).toBe(true); } for (const member of instrument.members) { expect(ALLOWED_METHODS.has(member.method)).toBe(true); totalMembers += 1; } } expect(totalMembers + result.unresolved.length + result.conflicts.length).toBe(inputLength); } 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 shuffleWithSeed(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]; const swap = copy[j]; if (tmp !== undefined && swap !== undefined) { copy[i] = swap; copy[j] = tmp; } } return copy; } // Shared fixture: appends the CUSIP check digit; supports alphanumeric and private-placement (*@#) bases. const CUSIP_CHARSET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#'; function withCusipCheckDigit(base8: string): string { let sum = 0; for (let i = 0; i < 8; i++) { let val = CUSIP_CHARSET.indexOf(base8.charAt(i)); if (val < 0) { throw new Error(`Unsupported CUSIP character in ${base8}`); } if ((i & 1) === 1) { val *= 2; } sum += Math.floor(val / 10) + (val % 10); } return base8 + String((10 - (sum % 10)) % 10); } describe('security master Pass 3 Stage A instrument matcher', () => { test('is exported from security-master barrel and performs zero I/O imports', () => { expect(typeof matchInstrumentsStageA).toBe('function'); expect(STAGE_A_SOURCES).toEqual(['ib', 'eod']); expect(isStageASource('ib')).toBe(true); expect(isStageASource('eod')).toBe(true); expect(isStageASource('qm')).toBe(false); const sourceText = readFileSync(stageASourcePath, 'utf8'); const forbiddenImports = [ '@stock-bot/mongodb', '@stock-bot/postgres', 'node:fs', 'node:http', 'node:https', 'node:net', 'bun:sqlite', "'fs'", '"fs"', "'http'", '"http"', "'https'", '"https"', "'net'", '"net"', ]; for (const forbidden of forbiddenImports) { expect(sourceText).not.toContain(forbidden); } }); test('merges IB and EOD records sharing a Luhn-valid ISIN into one tier1_isin instrument', () => { const result = matchInstrumentsStageA([ { source: 'ib', sourceId: '265598', isin: ' us0378331005 ', currency: ' usd ', name: 'Apple Inc.', }, { source: 'eod', sourceId: 'AAPL.US', isin: 'US0378331005', currency: 'USD', name: 'APPLE INC', }, ]); expect(result.unresolved).toEqual([]); expect(result.conflicts).toEqual([]); expect(result.instruments).toEqual([ { primaryIsin: 'US0378331005', primaryCusip: '037833100', issuerCountry: 'US', canonicalName: 'Apple Inc.', members: [ { source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }, { source: 'ib', sourceId: '265598', currency: 'USD', method: 'tier1_isin' }, ], }, ]); assertConservationAndSchema(result, 2); }); test('keeps interlisted USD and CAD members under one instrument while preserving both currencies', () => { const result = matchInstrumentsStageA([ { source: 'ib', sourceId: '11666', isin: 'CA7800871021', currency: 'USD', name: 'Royal Bank of Canada', }, { source: 'eod', sourceId: 'RY.TO', isin: 'CA7800871021', currency: 'CAD', name: 'ROYAL BANK OF CANADA', }, ]); expect(result.unresolved).toEqual([]); expect(result.conflicts).toEqual([]); expect(result.instruments).toEqual([ { primaryIsin: 'CA7800871021', primaryCusip: '780087102', issuerCountry: 'CA', canonicalName: 'Royal Bank of Canada', members: [ { source: 'eod', sourceId: 'RY.TO', currency: 'CAD', method: 'tier1_isin' }, { source: 'ib', sourceId: '11666', currency: 'USD', method: 'tier1_isin' }, ], }, ]); assertConservationAndSchema(result, 2); }); test('recovers tier2_cusip from explicit or embedded US/CA CUSIP and rejects placeholder ISINs', () => { const result = matchInstrumentsStageA([ { source: 'eod', sourceId: 'BAD_ISIN_WITH_CUSIP', isin: 'CA8131391062', cusip: '813137106', country: 'CA', currency: 'CAD', name: 'Recovered Via Explicit CUSIP', }, { source: 'ib', sourceId: 'EMBEDDED_CUSIP_RECOVERY', isin: 'CA7800871029', currency: 'CAD', name: 'Recovered Via Embedded CUSIP', }, { source: 'eod', sourceId: 'TEST_PLACEHOLDER_1', isin: 'CATSETEST001', country: 'CA', }, { source: 'eod', sourceId: 'TEST_PLACEHOLDER_2', isin: 'CA00149WBAD4', country: 'CA', }, ]); expect(result.conflicts).toEqual([]); expect(result.instruments).toEqual([ { primaryIsin: 'CA7800871021', primaryCusip: '780087102', issuerCountry: 'CA', canonicalName: 'Recovered Via Embedded CUSIP', members: [ { source: 'ib', sourceId: 'EMBEDDED_CUSIP_RECOVERY', currency: 'CAD', method: 'tier2_cusip', }, ], }, { primaryIsin: 'CA8131371061', primaryCusip: '813137106', issuerCountry: 'CA', canonicalName: 'Recovered Via Explicit CUSIP', members: [ { source: 'eod', sourceId: 'BAD_ISIN_WITH_CUSIP', currency: 'CAD', method: 'tier2_cusip', }, ], }, ]); expect(result.unresolved).toEqual([ { source: 'eod', sourceId: 'TEST_PLACEHOLDER_1', reason: 'invalid_isin_and_no_valid_cusip', }, { source: 'eod', sourceId: 'TEST_PLACEHOLDER_2', reason: 'invalid_isin_and_no_valid_cusip', }, ]); assertConservationAndSchema(result, 4); }); test('routes missing, invalid-CUSIP, and unsupported-country records to unresolved without throwing', () => { const result = matchInstrumentsStageA([ { source: 'eod', sourceId: 'NO_IDS', name: 'Missing Everything' }, { source: 'ib', sourceId: 'BLANK_IDS', isin: ' ', cusip: '' }, { source: 'eod', sourceId: 'BAD_CUSIP_ONLY', cusip: '813137109', country: 'CA' }, { source: 'eod', sourceId: 'GB_CUSIP_ONLY', cusip: '813137106', country: 'GB' }, { source: 'ib', sourceId: 'NO_COUNTRY_CUSIP', cusip: '037833100' }, ]); expect(result.instruments).toEqual([]); expect(result.conflicts).toEqual([]); expect(result.unresolved).toEqual([ { source: 'eod', sourceId: 'BAD_CUSIP_ONLY', reason: 'invalid_cusip' }, { source: 'eod', sourceId: 'GB_CUSIP_ONLY', reason: 'unsupported_country_for_cusip' }, { source: 'eod', sourceId: 'NO_IDS', reason: 'missing_identifiers' }, { source: 'ib', sourceId: 'BLANK_IDS', reason: 'missing_identifiers' }, { source: 'ib', sourceId: 'NO_COUNTRY_CUSIP', reason: 'unsupported_country_for_cusip' }, ]); assertConservationAndSchema(result, 5); }); test('rejects sparse input arrays instead of silently skewing stats (T-54)', () => { const sparse = new Array(2) as unknown as Parameters[0]; sparse[1] = { source: 'eod', sourceId: 'AAPL.US', isin: 'US0378331005', cusip: '037833100', country: 'US', }; expect(() => matchInstrumentsStageA(sparse)).toThrow(TypeError); }); test('does not quarantine interlisted US/CA shares when listing country differs from issuer country (T-55)', () => { const result = matchInstrumentsStageA([ { 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: 'US', currency: 'USD', name: 'Shopify Inc.', }, ]); expect(result.conflicts).toEqual([]); expect(result.unresolved).toEqual([]); expect(result.instruments).toHaveLength(1); expect(result.instruments[0]?.primaryIsin).toBe('CA82509L1076'); expect(result.instruments[0]?.issuerCountry).toBe('CA'); expect(result.instruments[0]?.members.map(m => m.sourceId)).toEqual(['SHOP.TO', 'SHOP.US']); assertConservationAndSchema(result, 2); }); test('quarantines isin_cusip_mismatch and duplicate_source_id without joining any instrument', () => { const result = matchInstrumentsStageA([ // Explicit CA country mismatch { source: 'eod', sourceId: 'MISMATCH_EXPLICIT_CA', isin: 'CA8131371061', cusip: '780087102', country: 'CA', }, // Missing country falls back to CA ISIN prefix and still detects mismatch { source: 'ib', sourceId: 'MISMATCH_PREFIX_CA', isin: 'CA8131371061', cusip: '780087102', country: null, }, // Non-US/CA ISIN with explicit US country + valid CUSIP triggers mismatch { source: 'eod', sourceId: 'MISMATCH_AU_WITH_US_CUSIP', isin: 'AU0000XVGZA3', cusip: '037833100', country: 'US', }, // Non-US/CA ISIN with AU country or null country joins with primaryCusip: null { source: 'eod', sourceId: 'VALID_AU_WITH_AU_COUNTRY', isin: 'AU0000XVGZA3', cusip: '037833100', country: 'AU', currency: 'AUD', }, { source: 'ib', sourceId: 'VALID_AU_NULL_COUNTRY', isin: 'AU0000XVGZA3', cusip: '037833100', country: null, currency: 'AUD', }, // Valid ISIN + invalid CUSIP is NOT a mismatch and joins as tier1_isin { source: 'eod', sourceId: 'VALID_ISIN_BAD_CUSIP', isin: 'US0378331005', cusip: '037833109', country: 'US', currency: 'USD', }, // Duplicate (source, sourceId) with identical ISIN { source: 'ib', sourceId: 'DUP_SAME', isin: 'CA7800871021', currency: 'CAD', }, { source: 'ib', sourceId: 'DUP_SAME', isin: 'CA7800871021', currency: 'USD', }, // Duplicate (source, sourceId) with differing ISINs { source: 'eod', sourceId: 'DUP_DIFF', isin: 'CA7800871021', }, { source: 'eod', sourceId: 'DUP_DIFF', isin: 'CA8131371061', }, ]); expect(result.unresolved).toEqual([]); expect(result.instruments).toEqual([ { primaryIsin: 'AU0000XVGZA3', primaryCusip: null, issuerCountry: 'AU', canonicalName: null, members: [ { source: 'eod', sourceId: 'VALID_AU_WITH_AU_COUNTRY', currency: 'AUD', method: 'tier1_isin', }, { source: 'ib', sourceId: 'VALID_AU_NULL_COUNTRY', currency: 'AUD', method: 'tier1_isin', }, ], }, { primaryIsin: 'US0378331005', primaryCusip: '037833100', issuerCountry: 'US', canonicalName: null, members: [ { source: 'eod', sourceId: 'VALID_ISIN_BAD_CUSIP', currency: 'USD', method: 'tier1_isin', }, ], }, ]); expect(result.conflicts).toEqual([ { source: 'eod', sourceId: 'DUP_DIFF', conflictKind: 'duplicate_source_id', detail: { isin: 'CA7800871021', cusip: null, country: null, derivedIsin: null }, }, { source: 'eod', sourceId: 'DUP_DIFF', conflictKind: 'duplicate_source_id', detail: { isin: 'CA8131371061', cusip: null, country: null, derivedIsin: null }, }, { source: 'eod', sourceId: 'MISMATCH_AU_WITH_US_CUSIP', conflictKind: 'isin_cusip_mismatch', detail: { isin: 'AU0000XVGZA3', cusip: '037833100', country: 'US', derivedIsin: 'US0378331005', }, }, { source: 'eod', sourceId: 'MISMATCH_EXPLICIT_CA', conflictKind: 'isin_cusip_mismatch', detail: { isin: 'CA8131371061', cusip: '780087102', country: 'CA', derivedIsin: 'CA7800871021', }, }, { source: 'ib', sourceId: 'DUP_SAME', conflictKind: 'duplicate_source_id', detail: { isin: 'CA7800871021', cusip: null, country: null, derivedIsin: null }, }, { source: 'ib', sourceId: 'DUP_SAME', conflictKind: 'duplicate_source_id', detail: { isin: 'CA7800871021', cusip: null, country: null, derivedIsin: null }, }, { source: 'ib', sourceId: 'MISMATCH_PREFIX_CA', conflictKind: 'isin_cusip_mismatch', detail: { isin: 'CA8131371061', cusip: '780087102', country: null, derivedIsin: 'CA7800871021', }, }, ]); assertConservationAndSchema(result, 10); }); test('applies IB -> EOD canonicalName precedence with ASCII sourceId tie-breaking and fallback', () => { const result = matchInstrumentsStageA([ // Instrument 1: multiple IB members + EOD member -> lowest-ASCII IB sourceId with non-empty name wins { source: 'eod', sourceId: 'A_EOD', isin: 'US0378331005', name: 'EOD Name' }, { source: 'ib', sourceId: '200', isin: 'US0378331005', name: 'IB Higher SourceId' }, { source: 'ib', sourceId: '050', isin: 'US0378331005', name: ' ' }, { source: 'ib', sourceId: '100', isin: 'US0378331005', name: ' IB Lowest Non-Empty ' }, // Instrument 2: IB names are null/undefined/blank -> falls back to lowest-ASCII EOD name { source: 'ib', sourceId: '1', isin: 'CA7800871021', name: null }, { source: 'ib', sourceId: '2', isin: 'CA7800871021', name: ' ' }, { source: 'eod', sourceId: 'Z.TO', isin: 'CA7800871021', name: 'EOD Later' }, { source: 'eod', sourceId: 'A.TO', isin: 'CA7800871021', name: 'EOD First' }, // Instrument 3: all members lack a name -> null { source: 'ib', sourceId: '999', isin: 'CA8131371061' }, { source: 'eod', sourceId: 'NO_NAME.TO', isin: 'CA8131371061', name: '' }, ]); expect(result.instruments.map(inst => [inst.primaryIsin, inst.canonicalName])).toEqual([ ['CA7800871021', 'EOD First'], ['CA8131371061', null], ['US0378331005', 'IB Lowest Non-Empty'], ]); const eodFirst = matchInstrumentsStageA( [ { source: 'ib', sourceId: '100', isin: 'US0378331005', name: 'IB Name' }, { source: 'eod', sourceId: 'AAPL.US', isin: 'US0378331005', name: 'EOD Name' }, ], { nameSourcePrecedence: ['eod', 'ib'] } ); expect(eodFirst.instruments[0]?.canonicalName).toBe('EOD Name'); }); test('preserves sourceId verbatim without trimming and throws on empty sourceId or unknown source', () => { const result = matchInstrumentsStageA([ { source: 'eod', sourceId: ' AAPL.US', isin: 'US0378331005', currency: 'USD' }, { source: 'eod', sourceId: 'AAPL.US', isin: 'US0378331005', currency: 'USD' }, { source: 'eod', sourceId: ' MISSING ', isin: null }, { source: 'ib', sourceId: ' CON ', isin: 'CA8131371061', cusip: '780087102', country: 'CA' }, ]); expect(result.instruments[0]?.members.map(m => m.sourceId)).toEqual([' AAPL.US', 'AAPL.US']); expect(result.unresolved[0]?.sourceId).toBe(' MISSING '); expect(result.conflicts[0]?.sourceId).toBe(' CON '); assertConservationAndSchema(result, 4); expect(() => matchInstrumentsStageA([{ source: 'eod', sourceId: '', isin: 'US0378331005' }]) ).toThrow(/sourceId/i); expect(() => matchInstrumentsStageA([ { source: 'qm' as unknown as StageASource, sourceId: 'AAPL', isin: 'US0378331005' }, ]) ).toThrow(/qm.*AAPL/); expect(() => matchInstrumentsStageA([], { nameSourcePrecedence: ['qm' as unknown as StageASource], }) ).toThrow(/qm/); }); test('produces byte-identical JSON output across shuffled input orderings and preserves conservation', () => { const corpus: StageASourceRecord[] = [ { source: 'ib', sourceId: '100', isin: 'US0378331005', currency: 'USD', name: 'Apple IB' }, { source: 'eod', sourceId: 'AAPL.US', isin: 'US0378331005', currency: 'USD', name: 'Apple EOD', }, { source: 'ib', sourceId: '11666', isin: 'CA7800871021', currency: 'USD', name: 'RBC US' }, { source: 'eod', sourceId: 'RY.TO', isin: 'CA7800871021', currency: 'CAD', name: 'RBC CA' }, { source: 'eod', sourceId: 'TIER2_CA', isin: 'CA8131391062', cusip: '813137106', country: 'CA', currency: 'CAD', name: 'Tier 2', }, { source: 'ib', sourceId: 'TIER2_EMBED', isin: 'CA7800871029', currency: 'CAD' }, { source: 'eod', sourceId: 'UNRES_MISSING' }, { source: 'eod', sourceId: 'UNRES_PLACEHOLDER', isin: 'CATSETEST001', country: 'CA' }, { source: 'eod', sourceId: 'CONF_MISMATCH', isin: 'CA8131371061', cusip: '780087102', country: 'CA', }, { source: 'ib', sourceId: 'CONF_DUP', isin: 'US0378331005', country: 'US' }, { source: 'ib', sourceId: 'CONF_DUP', isin: 'CA7800871021', country: 'CA' }, ]; const baseline = matchInstrumentsStageA(corpus); const baselineJson = JSON.stringify(baseline); assertConservationAndSchema(baseline, corpus.length); const reversed = matchInstrumentsStageA([...corpus].reverse()); expect(JSON.stringify(reversed)).toBe(baselineJson); for (const seed of [1, 42, 1337, 99999]) { const shuffled = shuffleWithSeed(corpus, seed); const res = matchInstrumentsStageA(shuffled); expect(JSON.stringify(res)).toBe(baselineJson); assertConservationAndSchema(res, corpus.length); } }); test('local benchmark: 300,000 synthetic records complete in under 2 seconds', () => { const TOTAL_RECORDS = 300_000; const UNIQUE_INSTRUMENTS = 100_000; const records: StageASourceRecord[] = new Array(TOTAL_RECORDS); // Pre-generate 100k valid US/CA CUSIPs and derived ISINs outside the timed window. const validCusips: string[] = new Array(UNIQUE_INSTRUMENTS); const validIsins: string[] = new Array(UNIQUE_INSTRUMENTS); for (let i = 0; i < UNIQUE_INSTRUMENTS; i++) { const base8 = String(10000000 + i); const cusip = withCusipCheckDigit(base8); const country = (i & 1) === 0 ? 'US' : 'CA'; const isin = cusipToIsin(cusip, country); if (isin === null) { throw new Error(`Failed to generate synthetic ISIN for base8=${base8}`); } validCusips[i] = cusip; validIsins[i] = isin; } let idx = 0; // 100k IB tier1_isin records for (let i = 0; i < UNIQUE_INSTRUMENTS; i++) { const isin = validIsins[i] ?? 'US0378331005'; records[idx++] = { source: 'ib', sourceId: `IB${i}`, isin, currency: (i & 1) === 0 ? 'USD' : 'CAD', name: `Issuer ${i}`, }; } // 100k EOD tier1_isin records pairing with the IB records for (let i = 0; i < UNIQUE_INSTRUMENTS; i++) { const isin = validIsins[i] ?? 'US0378331005'; records[idx++] = { source: 'eod', sourceId: `EOD${i}`, isin, currency: (i & 1) === 0 ? 'USD' : 'CAD', name: `ISSUER ${i} CORP`, }; } // 60k CUSIP-only tier2_cusip records for (let i = 0; i < 60_000; i++) { const cusip = validCusips[i] ?? '037833100'; const country = (i & 1) === 0 ? 'US' : 'CA'; records[idx++] = { source: 'eod', sourceId: `CUSIP${i}`, cusip, country, currency: country === 'US' ? 'USD' : 'CAD', }; } // 35k unresolved records (missing + placeholders) for (let i = 0; i < 35_000; i++) { records[idx++] = (i & 1) === 0 ? { source: 'eod', sourceId: `UNRES${i}` } : { source: 'ib', sourceId: `UNRES_PH${i}`, isin: 'CATSETEST001', country: 'CA' }; } // 5k conflict records (3k isin_cusip_mismatch + 2k duplicate_source_id) for (let i = 0; i < 3_000; i++) { records[idx++] = { source: 'eod', sourceId: `MISMATCH${i}`, isin: validIsins[i] ?? 'US0378331005', cusip: validCusips[i + 1] ?? '780087102', country: (i & 1) === 0 ? 'US' : 'CA', }; } for (let i = 0; i < 1_000; i++) { const dupId = `DUP${i}`; const isin = validIsins[i] ?? 'US0378331005'; records[idx++] = { source: 'ib', sourceId: dupId, isin, currency: 'USD' }; records[idx++] = { source: 'ib', sourceId: dupId, isin, currency: 'CAD' }; } expect(idx).toBe(TOTAL_RECORDS); const startMs = performance.now(); const result = matchInstrumentsStageA(records); const elapsedMs = performance.now() - startMs; process.stdout.write( `[benchmark] matchInstrumentsStageA(${TOTAL_RECORDS} records): ${elapsedMs.toFixed(1)} ms (${result.stats.totalInstruments} instruments)\n` ); expect(elapsedMs).toBeLessThan(2000); expect(result.stats.totalInputRecords).toBe(TOTAL_RECORDS); expect(result.stats.totalInstruments).toBe(UNIQUE_INSTRUMENTS); expect(result.unresolved).toHaveLength(35_000); expect(result.conflicts).toHaveLength(5_000); // Reconcile the stats counters with the emitted rows, not just with each other. let benchmarkMembers = 0; for (const instrument of result.instruments) { benchmarkMembers += instrument.members.length; } expect(benchmarkMembers).toBe(260_000); expect(benchmarkMembers + result.unresolved.length + result.conflicts.length).toBe( TOTAL_RECORDS ); expect(result.stats.bySource.ib.total + result.stats.bySource.eod.total).toBe(TOTAL_RECORDS); expect( result.stats.bySource.ib.tier1Isin + result.stats.bySource.ib.tier2Cusip + result.stats.bySource.ib.unresolved + result.stats.bySource.ib.conflict ).toBe(result.stats.bySource.ib.total); expect( result.stats.bySource.eod.tier1Isin + result.stats.bySource.eod.tier2Cusip + result.stats.bySource.eod.unresolved + result.stats.bySource.eod.conflict ).toBe(result.stats.bySource.eod.total); }); }); function deepFreezeRecords(records: StageASourceRecord[]): readonly StageASourceRecord[] { for (const record of records) { Object.freeze(record); } return Object.freeze(records); } describe('security master Pass 3 Stage A instrument matcher — QA edge cases', () => { test('empty input yields an empty, fully zeroed result', () => { const result = matchInstrumentsStageA([]); expect(result).toEqual({ instruments: [], unresolved: [], conflicts: [], stats: { totalInputRecords: 0, totalInstruments: 0, bySource: { ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, eod: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, }, }, }); }); test('tier1 and tier2 members resolving to the same ISIN merge into one instrument keeping per-member methods', () => { const result = matchInstrumentsStageA([ { source: 'ib', sourceId: '4001', isin: 'CA8131371061', currency: 'CAD', name: 'IB Name' }, // Checksum-corrupted ISIN recovered through explicit CUSIP { source: 'eod', sourceId: 'SCU-UN.TO', isin: 'CA8131391062', cusip: '813137106', country: 'CA', currency: 'CAD', }, // CUSIP-only record recovered through explicit country { source: 'eod', sourceId: 'SCU-UN.V', cusip: '813137106', country: 'ca', currency: 'cad' }, ]); expect(result.instruments).toHaveLength(1); expect(result.instruments[0]?.primaryIsin).toBe('CA8131371061'); expect(result.instruments[0]?.members).toEqual([ { source: 'eod', sourceId: 'SCU-UN.TO', currency: 'CAD', method: 'tier2_cusip' }, { source: 'eod', sourceId: 'SCU-UN.V', currency: 'CAD', method: 'tier2_cusip' }, { source: 'ib', sourceId: '4001', currency: 'CAD', method: 'tier1_isin' }, ]); expect(result.stats.bySource.ib).toEqual({ total: 1, tier1Isin: 1, tier2Cusip: 0, unresolved: 0, conflict: 0, }); expect(result.stats.bySource.eod).toEqual({ total: 2, tier1Isin: 0, tier2Cusip: 2, unresolved: 0, conflict: 0, }); assertConservationAndSchema(result, 3); }); test('a valid ISIN with a valid private-placement CUSIP (*, @, #) is not flagged as a mismatch', () => { const privatePlacementCusips = [ withCusipCheckDigit('12345*67'), withCusipCheckDigit('1234@567'), withCusipCheckDigit('123#4567'), ]; for (const cusip of privatePlacementCusips) { // Arrange: guard that the vector really is a valid CUSIP that cannot become an ISIN. expect(isValidCusip(cusip)).toBe(true); expect(cusipToIsin(cusip, 'US')).toBeNull(); } const result = matchInstrumentsStageA( privatePlacementCusips.map((cusip, i) => ({ source: 'ib' as const, sourceId: `PP${i}`, isin: 'US0378331005', cusip, country: 'US', })) ); expect(result.conflicts).toEqual([]); expect(result.instruments).toHaveLength(1); expect(result.instruments[0]?.members.map(m => m.method)).toEqual([ 'tier1_isin', 'tier1_isin', 'tier1_isin', ]); assertConservationAndSchema(result, 3); }); test('a valid ISIN whose own CUSIP matches is accepted regardless of case and padding', () => { const result = matchInstrumentsStageA([ { source: 'eod', sourceId: 'RY.US', isin: 'ca7800871021', cusip: ' 780087102 ', country: ' ca ', }, { source: 'ib', sourceId: '11666', isin: 'CA7800871021', cusip: '780087102', country: undefined, }, ]); expect(result.conflicts).toEqual([]); expect(result.instruments).toHaveLength(1); expect(result.instruments[0]?.members.map(m => [m.sourceId, m.method])).toEqual([ ['RY.US', 'tier1_isin'], ['11666', 'tier1_isin'], ]); }); test('mismatch conflict detail normalizes cusip and country to trimmed upper case', () => { const result = matchInstrumentsStageA([ { source: 'eod', sourceId: 'MIX', isin: 'CA8131371061', cusip: ' 780087102 ', country: ' ca ', }, ]); expect(result.instruments).toEqual([]); expect(result.conflicts).toEqual([ { source: 'eod', sourceId: 'MIX', conflictKind: 'isin_cusip_mismatch', detail: { isin: 'CA8131371061', cusip: '780087102', country: 'CA', derivedIsin: 'CA7800871021', }, }, ]); expect(result.stats.bySource.eod.conflict).toBe(1); }); test('the same sourceId under different sources is not a duplicate', () => { const result = matchInstrumentsStageA([ { source: 'ib', sourceId: 'SAME', isin: 'US0378331005' }, { source: 'eod', sourceId: 'SAME', isin: 'US0378331005' }, ]); expect(result.conflicts).toEqual([]); expect(result.instruments[0]?.members.map(m => `${m.source}:${m.sourceId}`)).toEqual([ 'eod:SAME', 'ib:SAME', ]); }); test('duplicate detection takes precedence over unresolved and mismatch, and every occurrence is quarantined', () => { const result = matchInstrumentsStageA([ { source: 'eod', sourceId: 'TRIPLE', isin: 'US0378331005' }, { source: 'eod', sourceId: 'TRIPLE' }, { source: 'eod', sourceId: 'TRIPLE', isin: 'CA8131371061', cusip: '780087102', country: 'CA', }, { source: 'eod', sourceId: 'SOLO', isin: 'US0378331005' }, ]); expect(result.unresolved).toEqual([]); expect(result.conflicts.map(c => [c.sourceId, c.conflictKind])).toEqual([ ['TRIPLE', 'duplicate_source_id'], ['TRIPLE', 'duplicate_source_id'], ['TRIPLE', 'duplicate_source_id'], ]); expect(result.conflicts.every(c => c.detail.derivedIsin === null)).toBe(true); expect(result.instruments).toHaveLength(1); expect(result.instruments[0]?.members.map(m => m.sourceId)).toEqual(['SOLO']); expect(result.stats.bySource.eod).toEqual({ total: 4, tier1Isin: 1, tier2Cusip: 0, unresolved: 0, conflict: 3, }); assertConservationAndSchema(result, 4); }); test('members, names and unresolved rows sort by ASCII code unit, not locale', () => { const result = matchInstrumentsStageA([ { source: 'ib', sourceId: 'a1', isin: 'US0378331005', name: 'Lowercase Id' }, { source: 'ib', sourceId: 'B1', isin: 'US0378331005', name: 'Uppercase Id' }, { source: 'ib', sourceId: '_1', isin: 'US0378331005' }, { source: 'eod', sourceId: 'z' }, { source: 'eod', sourceId: 'Z' }, ]); // ASCII: 'B' (66) < '_' (95) < 'a' (97); locale collation would put 'a1' before 'B1'. expect(result.instruments[0]?.members.map(m => m.sourceId)).toEqual(['B1', '_1', 'a1']); expect(result.instruments[0]?.canonicalName).toBe('Uppercase Id'); expect(result.unresolved.map(u => u.sourceId)).toEqual(['Z', 'z']); }); test('nameSourcePrecedence restricted to one source ignores the other source names', () => { const records: StageASourceRecord[] = [ { source: 'ib', sourceId: '1', isin: 'US0378331005', name: 'IB Only' }, { source: 'eod', sourceId: 'X.TO', isin: 'CA7800871021', name: 'EOD Only' }, ]; const precedence: readonly StageASource[] = Object.freeze(['eod'] as StageASource[]); const eodOnly = matchInstrumentsStageA(records, { nameSourcePrecedence: precedence }); const none = matchInstrumentsStageA(records, { nameSourcePrecedence: [] }); expect(eodOnly.instruments.map(i => [i.primaryIsin, i.canonicalName])).toEqual([ ['CA7800871021', 'EOD Only'], ['US0378331005', null], ]); expect(none.instruments.map(i => i.canonicalName)).toEqual([null, null]); expect(precedence).toEqual(['eod']); }); test('does not mutate frozen inputs and repeated calls share no state', () => { const makeInput = (): StageASourceRecord[] => [ { source: 'ib', sourceId: '2', isin: ' us0378331005 ', currency: ' usd ', name: ' Apple ' }, { source: 'ib', sourceId: '1', isin: 'US0378331005', currency: 'USD' }, { source: 'eod', sourceId: 'BAD', isin: 'CATSETEST001' }, { source: 'eod', sourceId: 'D', isin: 'US0378331005' }, { source: 'eod', sourceId: 'D', isin: 'US0378331005' }, ]; const frozen = deepFreezeRecords(makeInput()); const snapshot = JSON.stringify(frozen); const first = matchInstrumentsStageA(frozen); const firstJson = JSON.stringify(first); // Mutating a returned result must not leak into a later call. first.instruments[0]?.members.push({ source: 'ib', sourceId: 'INJECTED', currency: null, method: 'tier1_isin', }); first.stats.bySource.ib.total = 999; const second = matchInstrumentsStageA(frozen); expect(JSON.stringify(frozen)).toBe(snapshot); expect(JSON.stringify(second)).toBe(firstJson); expect(JSON.stringify(matchInstrumentsStageA(makeInput()))).toBe(firstJson); }); test('a larger seeded mixed corpus is byte-identical under shuffling and conserves every record', () => { const rng = makeRng(20261127); const isins: string[] = []; const cusips: string[] = []; for (let i = 0; i < 200; i++) { const cusip = withCusipCheckDigit(String(20000000 + i * 7)); const isin = cusipToIsin(cusip, (i & 1) === 0 ? 'US' : 'CA'); if (isin === null) { throw new Error(`Failed to build ISIN for ${cusip}`); } cusips.push(cusip); isins.push(isin); } const corpus: StageASourceRecord[] = []; for (let i = 0; i < 2_000; i++) { const source: StageASource = rng() < 0.5 ? 'ib' : 'eod'; const k = Math.floor(rng() * isins.length); const isin = isins[k] ?? 'US0378331005'; const cusip = cusips[k] ?? '037833100'; const country = isin.slice(0, 2); const roll = rng(); // sourceIds intentionally collide sometimes to create duplicates. const sourceId = `S${Math.floor(rng() * 1_800)}`; const name = rng() < 0.3 ? null : `Name ${Math.floor(rng() * 5)}`; const currency = rng() < 0.5 ? 'USD' : 'CAD'; if (roll < 0.4) { corpus.push({ source, sourceId, isin, currency, name }); } else if (roll < 0.6) { corpus.push({ source, sourceId, cusip, country, currency, name }); } else if (roll < 0.7) { corpus.push({ source, sourceId, isin: `${isin.slice(0, 11)}${(Number(isin.charAt(11)) + 1) % 10}`, currency, name, }); } else if (roll < 0.8) { const otherCusip = cusips[(k + 1) % cusips.length] ?? '780087102'; corpus.push({ source, sourceId, isin, cusip: otherCusip, country, currency, name }); } else if (roll < 0.9) { corpus.push({ source, sourceId, isin: 'CATSETEST001', country: 'CA', name }); } else { corpus.push({ source, sourceId, name }); } } const baseline = matchInstrumentsStageA(corpus); const baselineJson = JSON.stringify(baseline); assertConservationAndSchema(baseline, corpus.length); expect(baseline.conflicts.some(c => c.conflictKind === 'duplicate_source_id')).toBe(true); expect(baseline.conflicts.some(c => c.conflictKind === 'isin_cusip_mismatch')).toBe(true); expect(baseline.unresolved.length).toBeGreaterThan(0); expect( baseline.stats.bySource.ib.tier2Cusip + baseline.stats.bySource.eod.tier2Cusip ).toBeGreaterThan(0); for (const seed of [7, 8, 9]) { expect(JSON.stringify(matchInstrumentsStageA(shuffleWithSeed(corpus, seed)))).toBe( baselineJson ); } }); });