import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { describe, expect, test } from 'bun:test'; import { BANKRUPTCY_CANCELLED_TERMINAL_RETURN, CONTINUITY_KIND_OTC_DELIST_TRANSFER, DEFAULT_ACTIVE_GRACE_DAYS, DEFAULT_MAX_TRANSFER_GAP_DAYS, DEFAULT_OTC_MICS, DEFAULT_OVERLAP_TOLERANCE_DAYS, DELIST_REASONS, linkDelistingChains, SHUMWAY_PRIMARY_TERMINAL_RETURN, type DelistingChainResult, type ListingNaturalKey, type StageBListingCandidate, } from '../../apps/stock/data-pipeline/src/security-master'; const delistingChainsSourcePath = fileURLToPath( new URL( '../../apps/stock/data-pipeline/src/security-master/delisting-chains.ts', import.meta.url ) ); const ALLOWED_DELIST_REASONS = new Set(DELIST_REASONS); function makeListing( overrides: Partial & Pick ): StageBListingCandidate { return { primaryIsin: overrides.primaryIsin, mic: overrides.mic, tickerRoot: overrides.tickerRoot, classSuffix: overrides.classSuffix ?? '', currency: overrides.currency ?? 'USD', ibConid: overrides.ibConid ?? null, ibPrimaryExchange: overrides.ibPrimaryExchange ?? null, listedFrom: overrides.listedFrom === undefined ? '2015-01-02' : overrides.listedFrom, listedTo: overrides.listedTo === undefined ? null : overrides.listedTo, }; } 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; } function makeContinuityPk(key: ListingNaturalKey, effectiveDate: string): string { return `${key.primaryIsin}\u0000${key.mic}\u0000${key.tickerRoot}\u0000${key.classSuffix}\u0000${key.currency}\u0000${effectiveDate}`; } function assertReconciliationAndContracts( result: DelistingChainResult, expectedInputCount: number ): void { expect(result.stats.totalInputListings).toBe(expectedInputCount); expect(result.stats.processedListings).toBe(result.listingOutcomes.length); expect( result.stats.processedListings + result.stats.skippedInvalidDates + result.stats.skippedDuplicateKeys ).toBe(result.stats.totalInputListings); expect(result.stats.continuitiesCreated).toBe(result.continuities.length); expect(result.stats.conflictsDetected).toBe(result.conflicts.length); const counted = { active: 0, moved_to_otc: 0, bankruptcy_cancelled: 0, unknown_involuntary: 0, }; for (const outcome of result.listingOutcomes) { expect(ALLOWED_DELIST_REASONS.has(outcome.delistReason)).toBe(true); expect(outcome.delistReason as string).not.toBe('merger_cash'); counted[outcome.delistReason] += 1; if (outcome.delistReason === 'active' || outcome.delistReason === 'moved_to_otc') { expect(outcome.terminalReturn).toBeNull(); } else if (outcome.delistReason === 'bankruptcy_cancelled') { expect(outcome.terminalReturn).toBe(BANKRUPTCY_CANCELLED_TERMINAL_RETURN); } else { expect(outcome.terminalReturn).toBe(SHUMWAY_PRIMARY_TERMINAL_RETURN); } } expect(result.stats.byOutcome).toEqual(counted); expect( counted.active + counted.moved_to_otc + counted.bankruptcy_cancelled + counted.unknown_involuntary ).toBe(result.stats.processedListings); // Enforce corporate_action_continuity PK uniqueness on (fromListingKey, effectiveDate) and kind enum. const seenContinuityPks = new Set(); for (const c of result.continuities) { expect(c.kind).toBe(CONTINUITY_KIND_OTC_DELIST_TRANSFER); const pk = makeContinuityPk(c.fromListingKey, c.effectiveDate); expect(seenContinuityPks.has(pk)).toBe(false); seenContinuityPks.add(pk); } } describe('security master Pass 6 OTC delisting chain linker', () => { test('is exported from security-master barrel and performs zero I/O imports', () => { expect(typeof linkDelistingChains).toBe('function'); expect(DEFAULT_ACTIVE_GRACE_DAYS).toBe(10); expect(DEFAULT_MAX_TRANSFER_GAP_DAYS).toBe(30); expect(DEFAULT_OVERLAP_TOLERANCE_DAYS).toBe(5); expect(DEFAULT_OTC_MICS.has('OTCM')).toBe(true); expect(DELIST_REASONS).toEqual([ 'active', 'moved_to_otc', 'bankruptcy_cancelled', 'unknown_involuntary', ]); expect(CONTINUITY_KIND_OTC_DELIST_TRANSFER).toBe('otc_delist_transfer'); expect(SHUMWAY_PRIMARY_TERMINAL_RETURN).toBe(-0.3); expect(BANKRUPTCY_CANCELLED_TERMINAL_RETURN).toBe(-1.0); const sourceText = readFileSync(delistingChainsSourcePath, '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"', 'Date.now', ]; for (const forbidden of forbiddenImports) { expect(sourceText).not.toContain(forbidden); } }); test('links SIVB (XNAS) -> SIVBQ (OTCM) happy path and respects point-in-time asOfDate sweep', () => { const listings: StageBListingCandidate[] = [ makeListing({ primaryIsin: 'US78486Q1013', mic: 'XNAS', tickerRoot: 'SIVB', currency: 'USD', listedFrom: '1987-10-26', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US78486Q1013', mic: 'OTCM', tickerRoot: 'SIVBQ', currency: 'USD', listedFrom: '2023-03-28', listedTo: '2024-11-07', }), ]; // Full post-cancellation view (2025-11-27). const finalResult = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2025-11-27' } ); expect(finalResult.conflicts).toEqual([]); expect(finalResult.continuities).toEqual([ { fromListingKey: { primaryIsin: 'US78486Q1013', mic: 'XNAS', tickerRoot: 'SIVB', classSuffix: '', currency: 'USD', }, toListingKey: { primaryIsin: 'US78486Q1013', mic: 'OTCM', tickerRoot: 'SIVBQ', classSuffix: '', currency: 'USD', }, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer', }, ]); expect(finalResult.listingOutcomes).toEqual([ { listingKey: { primaryIsin: 'US78486Q1013', mic: 'OTCM', tickerRoot: 'SIVBQ', classSuffix: '', currency: 'USD', }, delistReason: 'bankruptcy_cancelled', terminalReturn: -1.0, }, { listingKey: { primaryIsin: 'US78486Q1013', mic: 'XNAS', tickerRoot: 'SIVB', classSuffix: '', currency: 'USD', }, delistReason: 'moved_to_otc', terminalReturn: null, }, ]); assertReconciliationAndContracts(finalResult, 2); // As-of 2023-03-15: SIVB is still within 10-day grace window, and SIVBQ has not started yet -> no look-ahead link. // Note: delistReason 'active' is strictly a delisting status (not delisted as of asOfDate), not // universe membership; historical callers must filter listings by listedFrom <= asOfDate. const sweepHalted = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2023-03-15' } ); expect(sweepHalted.continuities).toEqual([]); expect(sweepHalted.conflicts).toEqual([]); expect(sweepHalted.listingOutcomes.find(o => o.listingKey.tickerRoot === 'SIVB')).toMatchObject( { delistReason: 'active', terminalReturn: null } ); expect( sweepHalted.listingOutcomes.find(o => o.listingKey.tickerRoot === 'SIVBQ') ).toMatchObject({ delistReason: 'active', terminalReturn: null }); assertReconciliationAndContracts(sweepHalted, 2); // As-of 2023-03-28: SIVB is ended (18d > 10d grace), SIVBQ starts today -> linked, SIVBQ still active. const sweepOtcOpen = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2023-03-28' } ); expect(sweepOtcOpen.continuities).toHaveLength(1); expect(sweepOtcOpen.continuities[0]?.effectiveDate).toBe('2023-03-28'); expect( sweepOtcOpen.listingOutcomes.find(o => o.listingKey.tickerRoot === 'SIVB') ).toMatchObject({ delistReason: 'moved_to_otc', terminalReturn: null }); expect( sweepOtcOpen.listingOutcomes.find(o => o.listingKey.tickerRoot === 'SIVBQ') ).toMatchObject({ delistReason: 'active', terminalReturn: null }); assertReconciliationAndContracts(sweepOtcOpen, 2); // As-of 2024-12-01: SIVBQ ended 2024-11-07 (> 10d before 2024-12-01) -> bankruptcy_cancelled / -1.0. const sweepCancelled = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2024-12-01' } ); expect(sweepCancelled.continuities).toHaveLength(1); expect( sweepCancelled.listingOutcomes.find(o => o.listingKey.tickerRoot === 'SIVBQ') ).toMatchObject({ delistReason: 'bankruptcy_cancelled', terminalReturn: -1.0 }); assertReconciliationAndContracts(sweepCancelled, 2); }); test('enforces Rule 2 active grace-window boundaries for primary and OTC listings', () => { const listings: StageBListingCandidate[] = [ // Open-ended listing (listedTo: null) -> active. makeListing({ primaryIsin: 'US0000000001', mic: 'XNAS', tickerRoot: 'OPEN', listedTo: null, }), // Ended exactly at asOfDate - activeGraceDays (2025-11-27 - 10 = 2025-11-17) -> active (inclusive). makeListing({ primaryIsin: 'US0000000002', mic: 'XNAS', tickerRoot: 'EDGE', listedTo: '2025-11-17', }), // Ended 1 day before cutoff (2025-11-16) -> ended primary -> unknown_involuntary / -0.3. makeListing({ primaryIsin: 'US0000000003', mic: 'XNAS', tickerRoot: 'DEAD', listedTo: '2025-11-16', }), // Active OTC -Q ticker (still trading inside grace window) -> active / null, NOT bankruptcy_cancelled. makeListing({ primaryIsin: 'US0000000004', mic: 'OTCM', tickerRoot: 'LIVEQ', listedTo: '2025-11-20', }), ]; const result = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2025-11-27', activeGraceDays: 10 } ); const byTicker = new Map(result.listingOutcomes.map(o => [o.listingKey.tickerRoot, o])); expect(byTicker.get('OPEN')).toMatchObject({ delistReason: 'active', terminalReturn: null }); expect(byTicker.get('EDGE')).toMatchObject({ delistReason: 'active', terminalReturn: null }); expect(byTicker.get('DEAD')).toMatchObject({ delistReason: 'unknown_involuntary', terminalReturn: -0.3, }); expect(byTicker.get('LIVEQ')).toMatchObject({ delistReason: 'active', terminalReturn: null }); assertReconciliationAndContracts(result, 4); }); test('enforces Rule 4 exact 5-letter ASCII -Q bankruptcy marker only on ended OTC listings', () => { const listings: StageBListingCandidate[] = [ makeListing({ primaryIsin: 'US1000000001', mic: 'OTCM', tickerRoot: 'SIVBQ', listedTo: '2024-01-10', }), makeListing({ primaryIsin: 'US1000000002', mic: 'OTCM', tickerRoot: 'HTZGQ', listedTo: '2021-06-30', }), makeListing({ primaryIsin: 'US1000000003', mic: 'OTCM', tickerRoot: 'ABCD', listedTo: '2024-01-10', }), makeListing({ primaryIsin: 'US1000000004', mic: 'OTCM', tickerRoot: 'ABCQ', listedTo: '2024-01-10', }), makeListing({ primaryIsin: 'US1000000005', mic: 'OTCM', tickerRoot: 'ABCDEQ', listedTo: '2024-01-10', }), makeListing({ primaryIsin: 'US1000000006', mic: 'OTCM', tickerRoot: '1234Q', listedTo: '2024-01-10', }), // Primary-venue 5-letter ending in Q must NOT be classified as bankruptcy_cancelled. makeListing({ primaryIsin: 'US1000000007', mic: 'XNAS', tickerRoot: 'SIVBQ', listedTo: '2024-01-10', }), ]; const result = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2025-11-27' } ); const byIsin = new Map(result.listingOutcomes.map(o => [o.listingKey.primaryIsin, o])); expect(byIsin.get('US1000000001')).toMatchObject({ delistReason: 'bankruptcy_cancelled', terminalReturn: -1.0, }); expect(byIsin.get('US1000000002')).toMatchObject({ delistReason: 'bankruptcy_cancelled', terminalReturn: -1.0, }); for (const isin of [ 'US1000000003', 'US1000000004', 'US1000000005', 'US1000000006', 'US1000000007', ]) { expect(byIsin.get(isin)).toMatchObject({ delistReason: 'unknown_involuntary', terminalReturn: -0.3, }); } assertReconciliationAndContracts(result, 7); }); test('enforces transfer gap, overlap tolerance, OTC stub rejection, and ISIN/currency/venue isolation', () => { const listings: StageBListingCandidate[] = [ // Gap === maxTransferGapDays (30d: 2023-03-01 -> 2023-03-31) -> links. makeListing({ primaryIsin: 'US2000000001', mic: 'XNAS', tickerRoot: 'GAP30', listedTo: '2023-03-01', }), makeListing({ primaryIsin: 'US2000000001', mic: 'OTCM', tickerRoot: 'GAP30Q', listedFrom: '2023-03-31', listedTo: '2024-01-01', }), // Gap === maxTransferGapDays + 1 (31d: 2023-03-01 -> 2023-04-01) -> no link. makeListing({ primaryIsin: 'US2000000002', mic: 'XNAS', tickerRoot: 'GAP31', listedTo: '2023-03-01', }), makeListing({ primaryIsin: 'US2000000002', mic: 'OTCM', tickerRoot: 'GAP31Q', listedFrom: '2023-04-01', listedTo: '2024-01-01', }), // Overlap === overlapToleranceDays (5d before: 2023-03-05 vs 2023-03-10, otc.listedTo >= primary.listedTo) -> links. makeListing({ primaryIsin: 'US2000000003', mic: 'XNYS', tickerRoot: 'OVLP5', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US2000000003', mic: 'OTCM', tickerRoot: 'OVLPQ', listedFrom: '2023-03-05', listedTo: '2023-09-01', }), // Overlap === overlapToleranceDays + 1 (6d before: 2023-03-04 vs 2023-03-10) -> no link. makeListing({ primaryIsin: 'US2000000004', mic: 'XNYS', tickerRoot: 'OVLP6', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US2000000004', mic: 'OTCM', tickerRoot: 'OVL6Q', listedFrom: '2023-03-04', listedTo: '2023-09-01', }), // OTC stub that ended BEFORE primary ended (2023-03-08 < 2023-03-10) -> no link. makeListing({ primaryIsin: 'US2000000005', mic: 'XNYS', tickerRoot: 'STUB', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US2000000005', mic: 'OTCM', tickerRoot: 'STUBQ', listedFrom: '2023-03-06', listedTo: '2023-03-08', }), // Different ISINs -> never link. makeListing({ primaryIsin: 'US2000000006', mic: 'XNAS', tickerRoot: 'DIFF1', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US2000000007', mic: 'OTCM', tickerRoot: 'DIFFQ', listedFrom: '2023-03-15', listedTo: '2024-01-01', }), // Same ISIN, different currency (CAD primary vs USD OTC interlisted) -> never link. makeListing({ primaryIsin: 'CA2000000008', mic: 'XTSE', tickerRoot: 'INTER', currency: 'CAD', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'CA2000000008', mic: 'OTCM', tickerRoot: 'INTRF', currency: 'USD', listedFrom: '2023-03-15', listedTo: '2024-01-01', }), // OTC -> OTC on same ISIN+currency -> never link. makeListing({ primaryIsin: 'US2000000009', mic: 'OTCM', tickerRoot: 'OTCA', listedFrom: '2020-01-01', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US2000000009', mic: 'OTCM', tickerRoot: 'OTCAQ', listedFrom: '2023-03-15', listedTo: '2024-01-01', }), // Primary -> Primary on same ISIN+currency -> never link. makeListing({ primaryIsin: 'US2000000010', mic: 'XNAS', tickerRoot: 'UPL1', listedFrom: '2020-01-01', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US2000000010', mic: 'XNYS', tickerRoot: 'UPL2', listedFrom: '2023-03-15', listedTo: '2024-01-01', }), ]; const result = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2025-11-27', maxTransferGapDays: 30, overlapToleranceDays: 5 } ); expect(result.conflicts).toEqual([]); expect(result.continuities.map(c => c.fromListingKey.primaryIsin)).toEqual([ 'US2000000001', 'US2000000003', ]); assertReconciliationAndContracts(result, listings.length); }); test('quarantines ambiguous 1-to-2, 2-to-1, and 2x2 components while linking disjoint cycles cleanly', () => { const listings: StageBListingCandidate[] = [ // 1-to-2: one primary with two OTC candidates in window -> conflict, 0 continuities. makeListing({ primaryIsin: 'US3000000001', mic: 'XNAS', tickerRoot: 'ONEP', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US3000000001', mic: 'OTCM', tickerRoot: 'ONEPQ', listedFrom: '2023-03-15', listedTo: '2024-01-01', }), makeListing({ primaryIsin: 'US3000000001', mic: 'OTCM', tickerRoot: 'ONEPA', listedFrom: '2023-03-20', listedTo: '2024-01-01', }), // 2-to-1: two primary listings competing for one OTC listing -> conflict, 0 continuities. makeListing({ primaryIsin: 'US3000000002', mic: 'XNAS', tickerRoot: 'TWOP1', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US3000000002', mic: 'XNYS', tickerRoot: 'TWOP2', listedTo: '2023-03-12', }), makeListing({ primaryIsin: 'US3000000002', mic: 'OTCM', tickerRoot: 'TWOPQ', listedFrom: '2023-03-20', listedTo: '2024-01-01', }), // Mixed 2x2 connected component -> 1 conflict, 0 continuities. makeListing({ primaryIsin: 'US3000000003', mic: 'XNAS', tickerRoot: 'MXP1', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US3000000003', mic: 'XNYS', tickerRoot: 'MXP2', listedTo: '2023-03-15', }), makeListing({ primaryIsin: 'US3000000003', mic: 'OTCM', tickerRoot: 'MXPQ1', listedFrom: '2023-03-18', listedTo: '2024-01-01', }), makeListing({ primaryIsin: 'US3000000003', mic: 'OTCM', tickerRoot: 'MXPQ2', listedFrom: '2023-03-25', listedTo: '2024-01-01', }), // Two disjoint non-overlapping delist -> OTC cycles on the same (primaryIsin, currency) -> both link cleanly! makeListing({ primaryIsin: 'US3000000004', mic: 'XNAS', tickerRoot: 'CYC1', listedFrom: '2015-01-02', listedTo: '2018-06-01', }), makeListing({ primaryIsin: 'US3000000004', mic: 'OTCM', tickerRoot: 'CYC1Q', listedFrom: '2018-06-10', listedTo: '2019-12-31', }), makeListing({ primaryIsin: 'US3000000004', mic: 'XNYS', tickerRoot: 'CYC2', listedFrom: '2020-01-02', listedTo: '2023-06-01', }), makeListing({ primaryIsin: 'US3000000004', mic: 'OTCM', tickerRoot: 'CYC2Q', listedFrom: '2023-06-12', listedTo: '2024-06-01', }), ]; const result = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2025-11-27' } ); expect(result.conflicts).toHaveLength(3); for (const conflict of result.conflicts) { expect(conflict.conflictKind).toBe('ambiguous_otc_continuation'); } expect(result.conflicts.map(c => c.detail.primaryIsin)).toEqual([ 'US3000000001', 'US3000000002', 'US3000000003', ]); expect(result.conflicts[0]?.detail.candidateListingKeys).toHaveLength(3); expect(result.conflicts[1]?.detail.candidateListingKeys).toHaveLength(3); expect(result.conflicts[2]?.detail.candidateListingKeys).toHaveLength(4); // Primaries in ambiguous components fall back to unknown_involuntary / -0.3. const byTicker = new Map(result.listingOutcomes.map(o => [o.listingKey.tickerRoot, o])); for (const ticker of ['ONEP', 'TWOP1', 'TWOP2', 'MXP1', 'MXP2']) { expect(byTicker.get(ticker)).toMatchObject({ delistReason: 'unknown_involuntary', terminalReturn: -0.3, }); } // Disjoint cycles both link cleanly. expect(result.continuities).toHaveLength(2); expect( result.continuities.map(c => [ c.fromListingKey.tickerRoot, c.toListingKey.tickerRoot, c.effectiveDate, ]) ).toEqual([ ['CYC1', 'CYC1Q', '2018-06-10'], ['CYC2', 'CYC2Q', '2023-06-12'], ]); expect(byTicker.get('CYC1')).toMatchObject({ delistReason: 'moved_to_otc', terminalReturn: null, }); expect(byTicker.get('CYC2')).toMatchObject({ delistReason: 'moved_to_otc', terminalReturn: null, }); assertReconciliationAndContracts(result, listings.length); }); test('records typed conflicts on invalid dates, null OTC listedFrom, and duplicate keys without throwing', () => { const listings: StageBListingCandidate[] = [ // Rollover leap date 2023-02-29 makeListing({ primaryIsin: 'US4000000001', mic: 'XNAS', tickerRoot: 'BAD1', listedFrom: '2023-02-29', listedTo: '2024-01-01', }), // Timestamp string instead of YYYY-MM-DD makeListing({ primaryIsin: 'US4000000002', mic: 'XNAS', tickerRoot: 'BAD2', listedFrom: '2020-01-01', listedTo: '2023-03-10T00:00:00Z', }), // Padded date string makeListing({ primaryIsin: 'US4000000003', mic: 'XNAS', tickerRoot: 'BAD3', listedFrom: ' 2023-03-10 ', listedTo: '2024-01-01', }), // Inverted range (listedFrom > listedTo) makeListing({ primaryIsin: 'US4000000004', mic: 'XNAS', tickerRoot: 'BAD4', listedFrom: '2024-05-01', listedTo: '2024-04-01', }), // OTC with null listedFrom alongside ended primary -> missing_otc_listed_from conflict, OTC still classified. makeListing({ primaryIsin: 'US4000000005', mic: 'XNAS', tickerRoot: 'MISS', listedFrom: '2020-01-01', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US4000000005', mic: 'OTCM', tickerRoot: 'MISSQ', listedFrom: null, listedTo: '2024-01-01', }), // Duplicate natural keys -> quarantined as duplicate_listing_key. makeListing({ primaryIsin: 'US4000000006', mic: 'XNAS', tickerRoot: 'DUPX', listedFrom: '2020-01-01', listedTo: '2024-01-01', }), makeListing({ primaryIsin: 'US4000000006', mic: 'XNAS', tickerRoot: 'DUPX', listedFrom: '2021-01-01', listedTo: '2024-06-01', }), ]; const result = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2025-11-27' } ); expect(result.stats.skippedInvalidDates).toBe(4); expect(result.stats.skippedDuplicateKeys).toBe(2); expect(result.stats.processedListings).toBe(2); expect(result.continuities).toEqual([]); const conflictKinds = result.conflicts.map(c => c.conflictKind); expect(conflictKinds.filter(k => k === 'invalid_listing_dates')).toHaveLength(4); expect(conflictKinds.filter(k => k === 'duplicate_listing_key')).toHaveLength(1); expect(conflictKinds.filter(k => k === 'missing_otc_listed_from')).toHaveLength(1); const byTicker = new Map(result.listingOutcomes.map(o => [o.listingKey.tickerRoot, o])); expect(byTicker.get('MISS')).toMatchObject({ delistReason: 'unknown_involuntary', terminalReturn: -0.3, }); expect(byTicker.get('MISSQ')).toMatchObject({ delistReason: 'bankruptcy_cancelled', terminalReturn: -1.0, }); assertReconciliationAndContracts(result, listings.length); }); test('suppresses continuity linking when a (primaryIsin, currency) group contains an undated OTC listing (T-66)', () => { const listings: StageBListingCandidate[] = [ // Group 1 (ended undated OTC): 1 ended primary + 1 dated OTC in window + 1 undated ended OTC. makeListing({ primaryIsin: 'US4500000001', mic: 'XNAS', tickerRoot: 'MIXA', listedFrom: '2018-01-02', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US4500000001', mic: 'OTCM', tickerRoot: 'MIXAQ', listedFrom: '2023-03-15', listedTo: '2024-01-01', }), makeListing({ primaryIsin: 'US4500000001', mic: 'OTCM', tickerRoot: 'MIXAU', listedFrom: null, listedTo: '2024-01-01', }), // Group 2 (open-ended undated OTC): 1 ended primary + 1 dated OTC in window + 1 undated open-ended OTC. makeListing({ primaryIsin: 'US4500000002', mic: 'XNYS', tickerRoot: 'MIXB', listedFrom: '2018-01-02', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US4500000002', mic: 'OTCM', tickerRoot: 'MIXBQ', listedFrom: '2023-03-15', listedTo: '2024-01-01', }), makeListing({ primaryIsin: 'US4500000002', mic: 'OTCM', tickerRoot: 'MIXBU', listedFrom: null, listedTo: null, }), ]; const result = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2025-11-27' } ); expect(result.continuities).toEqual([]); expect(result.conflicts).toHaveLength(2); for (const conflict of result.conflicts) { expect(conflict.conflictKind).toBe('missing_otc_listed_from'); expect(conflict.detail.listedFrom).toBeNull(); } expect(result.conflicts[0]?.detail).toMatchObject({ primaryIsin: 'US4500000001', currency: 'USD', listedFrom: null, listedTo: '2024-01-01', }); expect(result.conflicts[1]?.detail).toMatchObject({ primaryIsin: 'US4500000002', currency: 'USD', listedFrom: null, listedTo: null, }); const byTicker = new Map(result.listingOutcomes.map(o => [o.listingKey.tickerRoot, o])); // Ended primaries fall back conservatively to unknown_involuntary / -0.3 (never moved_to_otc). expect(byTicker.get('MIXA')).toMatchObject({ delistReason: 'unknown_involuntary', terminalReturn: -0.3, }); expect(byTicker.get('MIXB')).toMatchObject({ delistReason: 'unknown_involuntary', terminalReturn: -0.3, }); // Dated and undated OTC rows receive normal Pass 3 classification. expect(byTicker.get('MIXAQ')).toMatchObject({ delistReason: 'bankruptcy_cancelled', terminalReturn: -1.0, }); expect(byTicker.get('MIXAU')).toMatchObject({ delistReason: 'unknown_involuntary', terminalReturn: -0.3, }); expect(byTicker.get('MIXBQ')).toMatchObject({ delistReason: 'bankruptcy_cancelled', terminalReturn: -1.0, }); expect(byTicker.get('MIXBU')).toMatchObject({ delistReason: 'active', terminalReturn: null, }); assertReconciliationAndContracts(result, listings.length); // Point-in-time asOfDate invariant: within activeGraceDays of primary's listedTo, // emit neither conflict nor continuity and keep active / null outcomes. const graceWindowResult = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2023-03-15' } ); expect(graceWindowResult.continuities).toEqual([]); expect(graceWindowResult.conflicts).toEqual([]); for (const outcome of graceWindowResult.listingOutcomes) { expect(outcome.delistReason).toBe('active'); expect(outcome.terminalReturn).toBeNull(); } assertReconciliationAndContracts(graceWindowResult, listings.length); // Shuffle determinism and unique cloned ListingNaturalKey references on mixed dated+undated groups. const baselineJson = JSON.stringify(result); const inputRefs = new Set(listings); const seenKeyRefs = new Set(); const registerKey = (key: ListingNaturalKey): void => { expect(inputRefs.has(key)).toBe(false); expect(seenKeyRefs.has(key)).toBe(false); seenKeyRefs.add(key); }; for (const o of result.listingOutcomes) { registerKey(o.listingKey); } for (const conflict of result.conflicts) { for (const k of conflict.detail.fromListingKeys) { registerKey(k); } for (const k of conflict.detail.toListingKeys) { registerKey(k); } for (const k of conflict.detail.candidateListingKeys) { registerKey(k); } } for (const seed of [7, 42, 1337, 65535]) { const shuffled = shuffleWithSeed(listings, seed); const shuffledResult = linkDelistingChains( { listings: shuffled, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2025-11-27' } ); expect(JSON.stringify(shuffledResult)).toBe(baselineJson); assertReconciliationAndContracts(shuffledResult, listings.length); } }); test('isolates T-66 suppression by (primaryIsin, currency) and suppresses multi-cycle / multi-candidate groups cleanly', () => { const listings: StageBListingCandidate[] = [ // Clean SIVB -> SIVBQ in (US78486Q1013, USD) must still link cleanly... makeListing({ primaryIsin: 'US78486Q1013', mic: 'XNAS', tickerRoot: 'SIVB', currency: 'USD', listedFrom: '1987-10-26', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US78486Q1013', mic: 'OTCM', tickerRoot: 'SIVBQ', currency: 'USD', listedFrom: '2023-03-28', listedTo: '2024-11-07', }), // ...even when the same ISIN has an undated OTC row in a different currency (CAD). makeListing({ primaryIsin: 'US78486Q1013', mic: 'OTCM', tickerRoot: 'SIVBC', currency: 'CAD', listedFrom: null, listedTo: null, }), // Separate suppressed USD group in the same batch. makeListing({ primaryIsin: 'US4500000010', mic: 'XNAS', tickerRoot: 'SUPP', currency: 'USD', listedFrom: '2018-01-02', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US4500000010', mic: 'OTCM', tickerRoot: 'SUPPQ', currency: 'USD', listedFrom: '2023-03-15', listedTo: '2024-01-01', }), makeListing({ primaryIsin: 'US4500000010', mic: 'OTCM', tickerRoot: 'SUPPU', currency: 'USD', listedFrom: null, listedTo: '2024-01-01', }), // Two disjoint valid primary->OTC cycles in one (primaryIsin, currency) group plus 1 undated OTC -> both suppressed. makeListing({ primaryIsin: 'US4500000011', mic: 'XNAS', tickerRoot: 'DCY1', currency: 'USD', listedFrom: '2015-01-02', listedTo: '2018-06-01', }), makeListing({ primaryIsin: 'US4500000011', mic: 'OTCM', tickerRoot: 'DCYAQ', currency: 'USD', listedFrom: '2018-06-10', listedTo: '2019-12-31', }), makeListing({ primaryIsin: 'US4500000011', mic: 'XNYS', tickerRoot: 'DCY2', currency: 'USD', listedFrom: '2020-01-02', listedTo: '2023-06-01', }), makeListing({ primaryIsin: 'US4500000011', mic: 'OTCM', tickerRoot: 'DCYBQ', currency: 'USD', listedFrom: '2023-06-12', listedTo: '2024-06-01', }), makeListing({ primaryIsin: 'US4500000011', mic: 'OTCM', tickerRoot: 'DCYUN', currency: 'USD', listedFrom: null, listedTo: null, }), // 1 ended primary + 2 dated OTCs + 1 undated OTC -> emits only 1 missing_otc_listed_from (no spurious ambiguous_otc_continuation). makeListing({ primaryIsin: 'US4500000012', mic: 'XNAS', tickerRoot: 'AMBU', currency: 'USD', listedFrom: '2018-01-02', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US4500000012', mic: 'OTCM', tickerRoot: 'AMBUQ', currency: 'USD', listedFrom: '2023-03-15', listedTo: '2024-01-01', }), makeListing({ primaryIsin: 'US4500000012', mic: 'OTCM', tickerRoot: 'AMBUA', currency: 'USD', listedFrom: '2023-03-20', listedTo: '2024-01-01', }), makeListing({ primaryIsin: 'US4500000012', mic: 'OTCM', tickerRoot: 'AMBUX', currency: 'USD', listedFrom: null, listedTo: '2024-01-01', }), ]; const result = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2025-11-27' } ); // Only SIVB -> SIVBQ links. expect(result.continuities).toHaveLength(1); expect(result.continuities[0]).toMatchObject({ fromListingKey: { primaryIsin: 'US78486Q1013', mic: 'XNAS', tickerRoot: 'SIVB', currency: 'USD', }, toListingKey: { primaryIsin: 'US78486Q1013', mic: 'OTCM', tickerRoot: 'SIVBQ', currency: 'USD', }, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer', }); // Exactly 3 missing_otc_listed_from conflicts (one per suppressed group) and 0 ambiguous_otc_continuation conflicts. expect(result.conflicts).toHaveLength(3); expect(result.conflicts.map(c => [c.conflictKind, c.detail.primaryIsin])).toEqual([ ['missing_otc_listed_from', 'US4500000010'], ['missing_otc_listed_from', 'US4500000011'], ['missing_otc_listed_from', 'US4500000012'], ]); const byTicker = new Map(result.listingOutcomes.map(o => [o.listingKey.tickerRoot, o])); expect(byTicker.get('SIVB')).toMatchObject({ delistReason: 'moved_to_otc', terminalReturn: null, }); expect(byTicker.get('SIVBQ')).toMatchObject({ delistReason: 'bankruptcy_cancelled', terminalReturn: -1.0, }); expect(byTicker.get('SIVBC')).toMatchObject({ delistReason: 'active', terminalReturn: null, }); for (const suppressedPrimary of ['SUPP', 'DCY1', 'DCY2', 'AMBU']) { expect(byTicker.get(suppressedPrimary)).toMatchObject({ delistReason: 'unknown_involuntary', terminalReturn: -0.3, }); } assertReconciliationAndContracts(result, listings.length); }); test('T-66 suppression keys on undated OTC rows only: stale undated stubs suppress, undated non-OTC rows and active-only groups do not', () => { const datedPair = (isin: string, root: string): StageBListingCandidate[] => [ makeListing({ primaryIsin: isin, mic: 'XNAS', tickerRoot: root, listedTo: '2023-03-10' }), makeListing({ primaryIsin: isin, mic: 'OTCM', tickerRoot: `${root}Q`, listedFrom: '2023-03-15', listedTo: '2024-01-01', }), ]; const listings: StageBListingCandidate[] = [ // Undated OTC stub that ended years before the primary: still suppresses (conservative Rule 5). ...datedPair('US4600000001', 'STLE'), makeListing({ primaryIsin: 'US4600000001', mic: 'OTCM', tickerRoot: 'STLEU', listedFrom: null, listedTo: '2010-01-04', }), // Undated non-OTC row in the group is not an OTC continuation candidate: link still forms. ...datedPair('US4600000002', 'NOTC'), makeListing({ primaryIsin: 'US4600000002', mic: 'XNYS', tickerRoot: 'NOTCN', listedFrom: null, listedTo: null, }), // Undated OTC row with an active (never-ended) primary: nothing to link, no conflict. makeListing({ primaryIsin: 'US4600000003', mic: 'XNAS', tickerRoot: 'ACTV', listedTo: null }), makeListing({ primaryIsin: 'US4600000003', mic: 'OTCM', tickerRoot: 'ACTVU', listedFrom: null, listedTo: null, }), ]; const result = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2025-11-27' } ); expect(result.continuities).toHaveLength(1); expect(result.continuities[0]).toMatchObject({ fromListingKey: { primaryIsin: 'US4600000002', tickerRoot: 'NOTC' }, toListingKey: { primaryIsin: 'US4600000002', tickerRoot: 'NOTCQ' }, effectiveDate: '2023-03-15', }); expect(result.conflicts).toHaveLength(1); expect(result.conflicts[0]).toMatchObject({ conflictKind: 'missing_otc_listed_from', detail: { primaryIsin: 'US4600000001', listedFrom: null, listedTo: '2010-01-04' }, }); expect(result.conflicts[0]?.detail.toListingKeys.map(k => k.tickerRoot)).toEqual(['STLEU']); expect(result.conflicts[0]?.detail.fromListingKeys.map(k => k.tickerRoot)).toEqual(['STLE']); const byTicker = new Map(result.listingOutcomes.map(o => [o.listingKey.tickerRoot, o])); expect(byTicker.get('STLE')).toMatchObject({ delistReason: 'unknown_involuntary', terminalReturn: SHUMWAY_PRIMARY_TERMINAL_RETURN, }); expect(byTicker.get('NOTC')).toMatchObject({ delistReason: 'moved_to_otc', terminalReturn: null }); expect(byTicker.get('ACTV')).toMatchObject({ delistReason: 'active', terminalReturn: null }); expect(byTicker.get('ACTVU')).toMatchObject({ delistReason: 'active', terminalReturn: null }); expect(result.stats.continuitiesCreated).toBe(1); expect(result.stats.byOutcome.moved_to_otc).toBe(1); assertReconciliationAndContracts(result, listings.length); // Custom otcMics: suppression follows the caller's OTC venue set, not a hard-coded MIC. const customListings: StageBListingCandidate[] = [ makeListing({ primaryIsin: 'US4600000004', mic: 'XNAS', tickerRoot: 'CUST', listedTo: '2023-03-10' }), makeListing({ primaryIsin: 'US4600000004', mic: 'PINX', tickerRoot: 'CUSTQ', listedFrom: '2023-03-15', listedTo: '2024-01-01', }), makeListing({ primaryIsin: 'US4600000004', mic: 'PINX', tickerRoot: 'CUSTU', listedFrom: null, listedTo: null, }), ]; const suppressed = linkDelistingChains( { listings: customListings, otcMics: new Set(['PINX']) }, { asOfDate: '2025-11-27' } ); expect(suppressed.continuities).toEqual([]); expect(suppressed.conflicts.map(c => c.conflictKind)).toEqual(['missing_otc_listed_from']); assertReconciliationAndContracts(suppressed, customListings.length); // Removing only the undated OTC row restores the link, proving the undated row is the sole cause. const unsuppressed = linkDelistingChains( { listings: customListings.slice(0, 2), otcMics: new Set(['PINX']) }, { asOfDate: '2025-11-27' } ); expect(unsuppressed.continuities).toHaveLength(1); expect(unsuppressed.conflicts).toEqual([]); }); test('throws TypeError or RangeError on invalid options or container arguments', () => { const emptyInput = { listings: [], otcMics: DEFAULT_OTC_MICS }; const validOpts = { asOfDate: '2025-11-27' }; expect(() => linkDelistingChains(null as unknown as typeof emptyInput, validOpts)).toThrow( TypeError ); expect(() => linkDelistingChains( { listings: 'not-an-array' as unknown as StageBListingCandidate[], otcMics: DEFAULT_OTC_MICS }, validOpts ) ).toThrow(TypeError); expect(() => linkDelistingChains( { listings: [], otcMics: ['OTCM'] as unknown as ReadonlySet }, validOpts ) ).toThrow(TypeError); expect(() => linkDelistingChains({ listings: [], otcMics: new Set(['INVALID_MIC']) }, validOpts) ).toThrow(RangeError); expect(() => linkDelistingChains(emptyInput, null as unknown as typeof validOpts) ).toThrow(TypeError); expect(() => linkDelistingChains(emptyInput, {} as unknown as typeof validOpts) ).toThrow(TypeError); expect(() => linkDelistingChains(emptyInput, { asOfDate: '2023-02-29' })).toThrow(RangeError); expect(() => linkDelistingChains(emptyInput, { asOfDate: '2025-11-27T00:00:00Z' })).toThrow( RangeError ); expect(() => linkDelistingChains(emptyInput, { asOfDate: '2025-11-27', activeGraceDays: -1 }) ).toThrow(RangeError); expect(() => linkDelistingChains(emptyInput, { asOfDate: '2025-11-27', maxTransferGapDays: 1.5 }) ).toThrow(RangeError); expect(() => linkDelistingChains(emptyInput, { asOfDate: '2025-11-27', overlapToleranceDays: -2 }) ).toThrow(RangeError); expect(() => linkDelistingChains(emptyInput, { asOfDate: '2025-11-27', activeGraceDays: '10' as unknown as number, }) ).toThrow(TypeError); }); test('is deterministic across input shuffles, never mutates inputs, and never shares ListingNaturalKey references', () => { const listings: StageBListingCandidate[] = [ makeListing({ primaryIsin: 'US78486Q1013', mic: 'XNAS', tickerRoot: 'SIVB', listedFrom: '1987-10-26', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US78486Q1013', mic: 'OTCM', tickerRoot: 'SIVBQ', listedFrom: '2023-03-28', listedTo: '2024-11-07', }), makeListing({ primaryIsin: 'US5000000001', mic: 'XNAS', tickerRoot: 'AMBG', listedTo: '2023-05-01', }), makeListing({ primaryIsin: 'US5000000001', mic: 'OTCM', tickerRoot: 'AMBGQ', listedFrom: '2023-05-05', listedTo: '2024-01-01', }), makeListing({ primaryIsin: 'US5000000001', mic: 'OTCM', tickerRoot: 'AMBGA', listedFrom: '2023-05-10', listedTo: '2024-01-01', }), makeListing({ primaryIsin: 'US5000000002', mic: 'XNYS', tickerRoot: 'ACTV', listedTo: null, }), makeListing({ primaryIsin: 'US5000000003', mic: 'XNAS', tickerRoot: 'BADD', listedFrom: '2024-05-01', listedTo: '2024-01-01', }), ]; const snapshotBefore = structuredClone(listings); for (const item of listings) { Object.freeze(item); } Object.freeze(listings); const otcMics = new Set(['OTCM']); const baseline = linkDelistingChains({ listings, otcMics }, { asOfDate: '2025-11-27' }); const baselineJson = JSON.stringify(baseline); // Input immutability check. expect(listings).toEqual(snapshotBefore); expect([...otcMics]).toEqual(['OTCM']); // Reference isolation check (T-58): every returned ListingNaturalKey object must be unique and distinct from input rows. const inputRefs = new Set(listings); const seenKeyRefs = new Set(); const registerKey = (key: ListingNaturalKey): void => { expect(inputRefs.has(key)).toBe(false); expect(seenKeyRefs.has(key)).toBe(false); seenKeyRefs.add(key); }; for (const c of baseline.continuities) { registerKey(c.fromListingKey); registerKey(c.toListingKey); } for (const o of baseline.listingOutcomes) { registerKey(o.listingKey); } for (const conflict of baseline.conflicts) { for (const k of conflict.detail.fromListingKeys) { registerKey(k); } for (const k of conflict.detail.toListingKeys) { registerKey(k); } for (const k of conflict.detail.candidateListingKeys) { registerKey(k); } } expect(seenKeyRefs.size).toBeGreaterThan(0); // Shuffle determinism across multiple seeds. for (const seed of [1, 42, 1337, 99999]) { const shuffled = shuffleWithSeed(listings, seed); const res = linkDelistingChains({ listings: shuffled, otcMics }, { asOfDate: '2025-11-27' }); expect(JSON.stringify(res)).toBe(baselineJson); assertReconciliationAndContracts(res, listings.length); } }); test('scale smoke: 50,000 synthetic listings complete under 1000 ms with exact stats reconciliation', () => { const TOTAL = 50_000; const listings: StageBListingCandidate[] = []; // 10,000 linked primary -> OTC pairs (20,000 listings; half ended -Q, half active OTC) for (let i = 0; i < 10_000; i++) { const isin = `US${String(1000000000 + i)}`; const isBankruptOtc = (i & 1) === 0; const root4 = String.fromCharCode(65 + ((i >> 12) % 26)) + String.fromCharCode(65 + ((i >> 8) % 26)) + String.fromCharCode(65 + ((i >> 4) % 26)) + String.fromCharCode(65 + (i % 26)); listings.push( makeListing({ primaryIsin: isin, mic: 'XNAS', tickerRoot: `P${i}`, listedFrom: '2015-01-02', listedTo: '2023-03-10', }), makeListing({ primaryIsin: isin, mic: 'OTCM', tickerRoot: isBankruptOtc ? `${root4}Q` : `O${i}`, listedFrom: '2023-03-20', listedTo: isBankruptOtc ? '2024-06-01' : null, }) ); } // 1,000 ambiguous 1-to-2 groups (3,000 listings) for (let i = 0; i < 1_000; i++) { const isin = `US${String(2000000000 + i)}`; listings.push( makeListing({ primaryIsin: isin, mic: 'XNYS', tickerRoot: `AP${i}`, listedFrom: '2015-01-02', listedTo: '2023-04-01', }), makeListing({ primaryIsin: isin, mic: 'OTCM', tickerRoot: `AO1${i}`, listedFrom: '2023-04-05', listedTo: '2024-01-01', }), makeListing({ primaryIsin: isin, mic: 'OTCM', tickerRoot: `AO2${i}`, listedFrom: '2023-04-10', listedTo: '2024-01-01', }) ); } // 17,000 active primary listings for (let i = 0; i < 17_000; i++) { listings.push( makeListing({ primaryIsin: `US${String(3000000000 + i)}`, mic: 'XNAS', tickerRoot: `ACT${i}`, listedFrom: '2018-01-02', listedTo: null, }) ); } // 10,000 unlinked ended primary listings for (let i = 0; i < 10_000; i++) { listings.push( makeListing({ primaryIsin: `US${String(4000000000 + i)}`, mic: 'XNYS', tickerRoot: `END${i}`, listedFrom: '2015-01-02', listedTo: '2022-12-30', }) ); } expect(listings).toHaveLength(TOTAL); const startMs = performance.now(); const result = linkDelistingChains( { listings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2025-11-27' } ); const elapsedMs = performance.now() - startMs; process.stdout.write( `[benchmark] linkDelistingChains(${TOTAL} listings): ${elapsedMs.toFixed(1)} ms (${result.continuities.length} continuities, ${result.conflicts.length} conflicts)\n` ); expect(elapsedMs).toBeLessThan(1000); expect(result.continuities).toHaveLength(10_000); expect(result.conflicts).toHaveLength(1_000); expect(result.stats.byOutcome.moved_to_otc).toBe(10_000); expect(result.stats.byOutcome.bankruptcy_cancelled).toBe(5_000); expect(result.stats.byOutcome.active).toBe(22_000); expect(result.stats.byOutcome.unknown_involuntary).toBe(13_000); expect( result.stats.byOutcome.active + result.stats.byOutcome.moved_to_otc + result.stats.byOutcome.bankruptcy_cancelled + result.stats.byOutcome.unknown_involuntary ).toBe(TOTAL); assertReconciliationAndContracts(result, TOTAL); }); test('dense same-ISIN groups stay O(n log n) without edge enumeration or quadratic null-start conflicts', () => { const SIDE_COUNT = 5_000; const denseAmbiguousListings: StageBListingCandidate[] = []; for (let i = 0; i < SIDE_COUNT; i++) { denseAmbiguousListings.push( makeListing({ primaryIsin: 'US9999990001', mic: 'XNAS', tickerRoot: `DP${i}`, listedFrom: '2015-01-02', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US9999990001', mic: 'OTCM', tickerRoot: `DO${i}`, listedFrom: '2023-03-20', listedTo: '2024-01-01', }) ); } const startAmbiguousMs = performance.now(); const ambiguousResult = linkDelistingChains( { listings: denseAmbiguousListings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2025-11-27' } ); const ambiguousElapsedMs = performance.now() - startAmbiguousMs; process.stdout.write( `[benchmark] dense same-ISIN ambiguous (${SIDE_COUNT}x${SIDE_COUNT} = 25M potential edges): ${ambiguousElapsedMs.toFixed(1)} ms\n` ); expect(ambiguousElapsedMs).toBeLessThan(1000); expect(ambiguousResult.continuities).toEqual([]); expect(ambiguousResult.conflicts).toHaveLength(1); expect(ambiguousResult.conflicts[0]?.conflictKind).toBe('ambiguous_otc_continuation'); expect(ambiguousResult.conflicts[0]?.detail.fromListingKeys).toHaveLength(SIDE_COUNT); expect(ambiguousResult.conflicts[0]?.detail.toListingKeys).toHaveLength(SIDE_COUNT); expect(ambiguousResult.conflicts[0]?.detail.candidateListingKeys).toHaveLength(SIDE_COUNT * 2); assertReconciliationAndContracts(ambiguousResult, SIDE_COUNT * 2); // Dense same-ISIN group with undated OTC rows (listedFrom: null) consolidates into 1 conflict per group. const denseNullStartListings: StageBListingCandidate[] = []; for (let i = 0; i < SIDE_COUNT; i++) { denseNullStartListings.push( makeListing({ primaryIsin: 'US9999990002', mic: 'XNYS', tickerRoot: `NP${i}`, listedFrom: '2015-01-02', listedTo: '2023-03-10', }), makeListing({ primaryIsin: 'US9999990002', mic: 'OTCM', tickerRoot: `NO${i}`, listedFrom: null, listedTo: '2024-01-01', }) ); } const startNullMs = performance.now(); const nullStartResult = linkDelistingChains( { listings: denseNullStartListings, otcMics: DEFAULT_OTC_MICS }, { asOfDate: '2025-11-27' } ); const nullStartElapsedMs = performance.now() - startNullMs; process.stdout.write( `[benchmark] dense same-ISIN null-start OTC (${SIDE_COUNT}x${SIDE_COUNT}): ${nullStartElapsedMs.toFixed(1)} ms\n` ); expect(nullStartElapsedMs).toBeLessThan(1000); expect(nullStartResult.continuities).toEqual([]); expect(nullStartResult.conflicts).toHaveLength(1); expect(nullStartResult.conflicts[0]?.conflictKind).toBe('missing_otc_listed_from'); expect(nullStartResult.conflicts[0]?.detail.fromListingKeys).toHaveLength(SIDE_COUNT); expect(nullStartResult.conflicts[0]?.detail.toListingKeys).toHaveLength(SIDE_COUNT); expect(nullStartResult.conflicts[0]?.detail.candidateListingKeys).toHaveLength(SIDE_COUNT * 2); assertReconciliationAndContracts(nullStartResult, SIDE_COUNT * 2); }); });