From 19e77d68aaaab63d37ea0678d51dcbafdab0714d Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 18:03:27 -0500 Subject: [PATCH] =?UTF-8?q?T-60:=20M1.1g=20=E2=80=94=20Pass=206:=20pure=20?= =?UTF-8?q?in-memory=20OTC=20delisting=20chain=20linker=20(same-ISIN=20pri?= =?UTF-8?q?mary=20venue=20=E2=86=92=20OTC=20continuation,=20`SIVB`=20?= =?UTF-8?q?=E2=86=92=20`SIVBQ`)=20+=20delist=20reason=20/=20Shumway=20term?= =?UTF-8?q?inal=20return?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/security-master/delisting-chains.ts | 295 ++++++++++-------- .../security-master-delisting-chains.test.ts | 89 ++++++ 2 files changed, 256 insertions(+), 128 deletions(-) diff --git a/apps/stock/data-pipeline/src/security-master/delisting-chains.ts b/apps/stock/data-pipeline/src/security-master/delisting-chains.ts index 2a15b300..8342334e 100644 --- a/apps/stock/data-pipeline/src/security-master/delisting-chains.ts +++ b/apps/stock/data-pipeline/src/security-master/delisting-chains.ts @@ -42,6 +42,13 @@ export interface DelistingContinuityCandidate { kind: DelistingContinuityKind; } +/** + * Delisting classification for a single listing as of `options.asOfDate`. + * + * Note: `delistReason: 'active'` indicates delisting status (not delisted as of `asOfDate`), + * not point-in-time universe eligibility. Historical callers must filter listings by + * `listedFrom <= asOfDate` before using outcomes for universe membership. + */ export interface ListingDelistOutcome { listingKey: ListingNaturalKey; delistReason: Pass6DelistReason; @@ -290,13 +297,40 @@ function normalizeKeyFromListing(listing: StageBListingCandidate): ListingNatura }; } -function lowerBoundByListedFromDay(otcs: readonly EligibleOtcRow[], targetDay: number): number { +interface OtcPrimaryInterval { + readonly startIdx: number; + readonly endIdx: number; + readonly otcIdx: number; +} + +function lowerBoundPrimaryByListedToDay( + primaries: readonly EndedPrimaryRow[], + targetDay: number +): number { let lo = 0; - let hi = otcs.length; + let hi = primaries.length; while (lo < hi) { const mid = (lo + hi) >>> 1; - const midRow = otcs[mid]; - if (midRow !== undefined && midRow.listedFromDay < targetDay) { + const midRow = primaries[mid]; + if (midRow !== undefined && midRow.listedToDay < targetDay) { + lo = mid + 1; + } else { + hi = mid; + } + } + return lo; +} + +function upperBoundPrimaryByListedToDay( + primaries: readonly EndedPrimaryRow[], + targetDay: number +): number { + let lo = 0; + let hi = primaries.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + const midRow = primaries[mid]; + if (midRow !== undefined && midRow.listedToDay <= targetDay) { lo = mid + 1; } else { hi = mid; @@ -312,6 +346,10 @@ function lowerBoundByListedFromDay(otcs: readonly EligibleOtcRow[], targetDay: n * (e.g. `SIVB` on `XNAS` -> `SIVBQ` on `OTCM`), classifies each listing's `delistReason` * and Shumway/bankruptcy `terminalReturn`, and quarantines ambiguous candidates as typed * conflicts without guessing. + * + * Note: `delistReason: 'active'` is strictly a delisting status ("not delisted as of + * `options.asOfDate`"). Historical callers must filter listings by `listedFrom <= asOfDate` + * before using outcomes for point-in-time universe membership. */ export function linkDelistingChains( input: DelistingChainInput, @@ -515,22 +553,29 @@ export function linkDelistingChains( const sortedPrimaryKeys = group.endedPrimaries .map(p => p.key) .sort(compareListingNaturalKey); - for (const otc of group.missingFromOtcs) { - const allKeys = [...sortedPrimaryKeys, otc.key].sort(compareListingNaturalKey); - conflicts.push({ - conflictKind: 'missing_otc_listed_from', - detail: { - primaryIsin: group.primaryIsin, - currency: group.currency, - fromListingKeys: sortedPrimaryKeys.map(cloneListingKey), - toListingKeys: [cloneListingKey(otc.key)], - candidateListingKeys: allKeys.map(cloneListingKey), - listedFrom: null, - listedTo: otc.listedTo, - reason: 'OTC listing has null listedFrom; cannot establish transfer window or effectiveDate', - }, - }); - } + const sortedMissingOtcKeys = group.missingFromOtcs + .map(o => o.key) + .sort(compareListingNaturalKey); + const allKeys = [...sortedPrimaryKeys, ...sortedMissingOtcKeys].sort( + compareListingNaturalKey + ); + const singleOtc = group.missingFromOtcs.length === 1 ? group.missingFromOtcs[0] : undefined; + conflicts.push({ + conflictKind: 'missing_otc_listed_from', + detail: { + primaryIsin: group.primaryIsin, + currency: group.currency, + fromListingKeys: sortedPrimaryKeys.map(cloneListingKey), + toListingKeys: sortedMissingOtcKeys.map(cloneListingKey), + candidateListingKeys: allKeys.map(cloneListingKey), + listedFrom: null, + listedTo: singleOtc !== undefined ? singleOtc.listedTo : null, + reason: + group.missingFromOtcs.length === 1 + ? 'OTC listing has null listedFrom; cannot establish transfer window or effectiveDate' + : `${group.missingFromOtcs.length} OTC listings have null listedFrom; cannot establish transfer window or effectiveDate`, + }, + }); } if (group.eligibleOtcs.length === 0) { @@ -539,92 +584,63 @@ export function linkDelistingChains( const primaries = group.endedPrimaries; const otcs = group.eligibleOtcs; - otcs.sort( - (a, b) => a.listedFromDay - b.listedFromDay || compareListingNaturalKey(a.key, b.key) + primaries.sort( + (a, b) => a.listedToDay - b.listedToDay || compareListingNaturalKey(a.key, b.key) ); - const primaryAdj: number[][] = Array.from({ length: primaries.length }, () => []); - const otcAdj: number[][] = Array.from({ length: otcs.length }, () => []); - - for (let pIdx = 0; pIdx < primaries.length; pIdx++) { - const primary = primaries[pIdx]; - if (primary === undefined) { + // For each eligible OTC listing, its matching ended primaries form a contiguous index + // range [startIdx, endIdx] in `primaries` sorted by `listedToDay`: + // otc.listedFromDay - maxTransferGapDays <= primary.listedToDay + // primary.listedToDay <= min(otc.listedFromDay + overlapToleranceDays, otc.listedToDay ?? +inf) + // Merging overlapping intervals finds all bipartite connected components in O((P + O) log (P + O)) + // time and O(P + O) memory without enumerating O(P * O) candidate edges. + const intervals: OtcPrimaryInterval[] = []; + for (let oIdx = 0; oIdx < otcs.length; oIdx++) { + const otc = otcs[oIdx]; + if (otc === undefined) { continue; } - const minDay = primary.listedToDay - overlapToleranceDays; - const maxDay = primary.listedToDay + maxTransferGapDays; - let oIdx = lowerBoundByListedFromDay(otcs, minDay); - while (oIdx < otcs.length) { - const otc = otcs[oIdx]; - if (otc === undefined || otc.listedFromDay > maxDay) { - break; - } - // Reject OTC stubs that had already ended before the primary listing ended. - if (otc.listedToDay === null || otc.listedToDay >= primary.listedToDay) { - primaryAdj[pIdx]?.push(oIdx); - otcAdj[oIdx]?.push(pIdx); - } - oIdx += 1; + const lowDay = otc.listedFromDay - maxTransferGapDays; + const maxWindowDay = otc.listedFromDay + overlapToleranceDays; + // Reject OTC stubs that had already ended before the primary listing ended. + const highDay = + otc.listedToDay === null || otc.listedToDay > maxWindowDay + ? maxWindowDay + : otc.listedToDay; + if (lowDay > highDay) { + continue; + } + const startIdx = lowerBoundPrimaryByListedToDay(primaries, lowDay); + const endExclusive = upperBoundPrimaryByListedToDay(primaries, highDay); + if (startIdx < endExclusive) { + intervals.push({ startIdx, endIdx: endExclusive - 1, otcIdx: oIdx }); } } - // Partition bipartite candidate edges into connected components. - const visitedPrimary = new Uint8Array(primaries.length); - const visitedOtc = new Uint8Array(otcs.length); + if (intervals.length === 0) { + continue; + } - for (let startP = 0; startP < primaries.length; startP++) { - const startNeighbors = primaryAdj[startP]; - if (visitedPrimary[startP] === 1 || startNeighbors === undefined || startNeighbors.length === 0) { - continue; - } + intervals.sort( + (a, b) => a.startIdx - b.startIdx || a.endIdx - b.endIdx || a.otcIdx - b.otcIdx + ); - const compPrimaries: number[] = []; - const compOtcs: number[] = []; - const primaryQueue: number[] = [startP]; - const otcQueue: number[] = []; - visitedPrimary[startP] = 1; + const firstInterval = intervals[0]; + if (firstInterval === undefined) { + continue; + } - while (primaryQueue.length > 0 || otcQueue.length > 0) { - while (primaryQueue.length > 0) { - const pIdx = primaryQueue.pop(); - if (pIdx === undefined) { - continue; - } - compPrimaries.push(pIdx); - const neighbors = primaryAdj[pIdx]; - if (neighbors !== undefined) { - for (let k = 0; k < neighbors.length; k++) { - const oIdx = neighbors[k]; - if (oIdx !== undefined && visitedOtc[oIdx] === 0) { - visitedOtc[oIdx] = 1; - otcQueue.push(oIdx); - } - } - } - } - while (otcQueue.length > 0) { - const oIdx = otcQueue.pop(); - if (oIdx === undefined) { - continue; - } - compOtcs.push(oIdx); - const neighbors = otcAdj[oIdx]; - if (neighbors !== undefined) { - for (let k = 0; k < neighbors.length; k++) { - const pIdx = neighbors[k]; - if (pIdx !== undefined && visitedPrimary[pIdx] === 0) { - visitedPrimary[pIdx] = 1; - primaryQueue.push(pIdx); - } - } - } - } - } + let compStart = firstInterval.startIdx; + let compEnd = firstInterval.endIdx; + let compOtcs: number[] = [firstInterval.otcIdx]; - if (compPrimaries.length === 1 && compOtcs.length === 1) { - const pIdx = compPrimaries[0]; - const oIdx = compOtcs[0]; - const primary = pIdx !== undefined ? primaries[pIdx] : undefined; + const flushComponent = (startIdx: number, endIdx: number, otcIndices: readonly number[]): void => { + const primaryCount = endIdx - startIdx + 1; + const otcCount = otcIndices.length; + + if (primaryCount === 1 && otcCount === 1) { + const primary = primaries[startIdx]; + const oIdx = otcIndices[0]; const otc = oIdx !== undefined ? otcs[oIdx] : undefined; if (primary !== undefined && otc !== undefined) { linkedPrimaryIndices.add(primary.index); @@ -638,42 +654,63 @@ export function linkDelistingChains( kind: CONTINUITY_KIND_OTC_DELIST_TRANSFER, }); } + return; + } + + const fromKeys: ListingNaturalKey[] = []; + for (let pIdx = startIdx; pIdx <= endIdx; pIdx++) { + const p = primaries[pIdx]; + if (p !== undefined) { + fromKeys.push(p.key); + } + } + fromKeys.sort(compareListingNaturalKey); + + const toKeys: ListingNaturalKey[] = []; + for (let k = 0; k < otcIndices.length; k++) { + const oIdx = otcIndices[k]; + const o = oIdx !== undefined ? otcs[oIdx] : undefined; + if (o !== undefined) { + toKeys.push(o.key); + } + } + toKeys.sort(compareListingNaturalKey); + + const allKeys = [...fromKeys, ...toKeys].sort(compareListingNaturalKey); + + conflicts.push({ + conflictKind: 'ambiguous_otc_continuation', + detail: { + primaryIsin: group.primaryIsin, + currency: group.currency, + fromListingKeys: fromKeys.map(cloneListingKey), + toListingKeys: toKeys.map(cloneListingKey), + candidateListingKeys: allKeys.map(cloneListingKey), + listedFrom: null, + listedTo: null, + reason: `Ambiguous OTC delisting continuation component (${primaryCount} primary, ${otcCount} OTC)`, + }, + }); + }; + + for (let i = 1; i < intervals.length; i++) { + const interval = intervals[i]; + if (interval === undefined) { + continue; + } + if (interval.startIdx <= compEnd) { + if (interval.endIdx > compEnd) { + compEnd = interval.endIdx; + } + compOtcs.push(interval.otcIdx); } else { - const fromKeys: ListingNaturalKey[] = []; - for (const idx of compPrimaries) { - const p = primaries[idx]; - if (p !== undefined) { - fromKeys.push(p.key); - } - } - fromKeys.sort(compareListingNaturalKey); - - const toKeys: ListingNaturalKey[] = []; - for (const idx of compOtcs) { - const o = otcs[idx]; - if (o !== undefined) { - toKeys.push(o.key); - } - } - toKeys.sort(compareListingNaturalKey); - - const allKeys = [...fromKeys, ...toKeys].sort(compareListingNaturalKey); - - conflicts.push({ - conflictKind: 'ambiguous_otc_continuation', - detail: { - primaryIsin: group.primaryIsin, - currency: group.currency, - fromListingKeys: fromKeys.map(cloneListingKey), - toListingKeys: toKeys.map(cloneListingKey), - candidateListingKeys: allKeys.map(cloneListingKey), - listedFrom: null, - listedTo: null, - reason: `Ambiguous OTC delisting continuation component (${compPrimaries.length} primary, ${compOtcs.length} OTC)`, - }, - }); + flushComponent(compStart, compEnd, compOtcs); + compStart = interval.startIdx; + compEnd = interval.endIdx; + compOtcs = [interval.otcIdx]; } } + flushComponent(compStart, compEnd, compOtcs); } // Pass 3: classify every valid unique listing into its delistReason and terminalReturn. @@ -697,6 +734,8 @@ export function linkDelistingChains( delistReason = 'moved_to_otc'; terminalReturn = null; } else if (row.listedToDay === null || row.listedToDay >= activeCutoffDay) { + // 'active' is a delisting status (not delisted as of options.asOfDate), not a + // universe-membership flag; historical callers must filter by listedFrom <= asOfDate. delistReason = 'active'; terminalReturn = null; } else if (!row.isOtc) { diff --git a/test/unit/security-master-delisting-chains.test.ts b/test/unit/security-master-delisting-chains.test.ts index 4c7f0a05..81bfb487 100644 --- a/test/unit/security-master-delisting-chains.test.ts +++ b/test/unit/security-master-delisting-chains.test.ts @@ -236,6 +236,8 @@ describe('security master Pass 6 OTC delisting chain linker', () => { 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' } @@ -245,6 +247,9 @@ describe('security master Pass 6 OTC delisting chain linker', () => { 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. @@ -1057,4 +1062,88 @@ describe('security master Pass 6 OTC delisting chain linker', () => { ).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); + }); });