diff --git a/apps/stock/data-pipeline/src/normalization/ticker.ts b/apps/stock/data-pipeline/src/normalization/ticker.ts index aad922b1..9bea8816 100644 --- a/apps/stock/data-pipeline/src/normalization/ticker.ts +++ b/apps/stock/data-pipeline/src/normalization/ticker.ts @@ -7,6 +7,13 @@ export interface ParsedTicker { classSuffix: string; } +export type ParseTickerFailureReason = 'invalid_ticker' | 'class_suffix_too_long'; + +export type ParseTickerDetailedResult = + | { ok: true; tickerRoot: string; classSuffix: string } + | { ok: false; reason: 'invalid_ticker' } + | { ok: false; reason: 'class_suffix_too_long'; tickerRoot: string; classSuffix: string }; + const CODE_TAB = 9; const CODE_SPACE = 32; const CODE_DASH = 45; @@ -37,21 +44,21 @@ function findNextSeparator(str: string, start: number): number { } /** - * Parses a raw provider ticker into a canonical uppercase `(tickerRoot, classSuffix)` pair. + * Parses a raw provider ticker into a canonical uppercase `(tickerRoot, classSuffix)` pair, + * returning a structured failure reason (`invalid_ticker` or `class_suffix_too_long`) on failure. * Strips embedded `.TO` / `.V` venue suffixes only when `source === 'ceo'`. - * Plain tickers return `classSuffix: ''`; empty or malformed inputs return `null`. */ -export function parseTicker( +export function parseTickerDetailed( raw: string | null | undefined, source: TickerSource -): ParsedTicker | null { +): ParseTickerDetailedResult { if (typeof raw !== 'string') { - return null; + return { ok: false, reason: 'invalid_ticker' }; } let s = raw.trim().toUpperCase(); if (s.length === 0) { - return null; + return { ok: false, reason: 'invalid_ticker' }; } if (source === 'ceo') { @@ -61,16 +68,16 @@ export function parseTicker( s = s.slice(0, -2).trimEnd(); } if (s.length === 0) { - return null; + return { ok: false, reason: 'invalid_ticker' }; } } const firstSep = findNextSeparator(s, 0); if (firstSep === -1) { - return { tickerRoot: s, classSuffix: '' }; + return { ok: true, tickerRoot: s, classSuffix: '' }; } if (firstSep === 0) { - return null; + return { ok: false, reason: 'invalid_ticker' }; } const tickerRoot = s.slice(0, firstSep); @@ -79,13 +86,16 @@ export function parseTicker( pos++; } if (pos >= s.length || isSeparator(s.charCodeAt(pos))) { - return null; + return { ok: false, reason: 'invalid_ticker' }; } const secondSep = findNextSeparator(s, pos); if (secondSep === -1) { const classSuffix = s.slice(pos); - return classSuffix.length <= MAX_CLASS_SUFFIX_LENGTH ? { tickerRoot, classSuffix } : null; + if (classSuffix.length > MAX_CLASS_SUFFIX_LENGTH) { + return { ok: false, reason: 'class_suffix_too_long', tickerRoot, classSuffix }; + } + return { ok: true, tickerRoot, classSuffix }; } let classSuffix = s.slice(pos, secondSep); @@ -96,7 +106,7 @@ export function parseTicker( pos++; } if (pos >= s.length || isSeparator(s.charCodeAt(pos))) { - return null; + return { ok: false, reason: 'invalid_ticker' }; } const nextSep = findNextSeparator(s, pos); if (nextSep === -1) { @@ -108,8 +118,21 @@ export function parseTicker( } if (classSuffix.length > MAX_CLASS_SUFFIX_LENGTH) { - return null; + return { ok: false, reason: 'class_suffix_too_long', tickerRoot, classSuffix }; } - return { tickerRoot, classSuffix }; + return { ok: true, tickerRoot, classSuffix }; +} + +/** + * Parses a raw provider ticker into a canonical uppercase `(tickerRoot, classSuffix)` pair. + * Strips embedded `.TO` / `.V` venue suffixes only when `source === 'ceo'`. + * Plain tickers return `classSuffix: ''`; empty or malformed inputs return `null`. + */ +export function parseTicker( + raw: string | null | undefined, + source: TickerSource +): ParsedTicker | null { + const result = parseTickerDetailed(raw, source); + return result.ok ? { tickerRoot: result.tickerRoot, classSuffix: result.classSuffix } : null; } diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 1b1b9d26..116056b2 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -58,3 +58,29 @@ export { type StageAStats, type StageAUnresolvedRecord, } from './instrument-stage-a'; + +export { + isStageBSource, + matchListingsStageB, + MAX_TICKER_ROOT_LENGTH, + STAGE_B_SOURCES, + type ListingNaturalKey, + type MatchListingsStageBOptions, + type StageBConflictDetail, + type StageBConflictKind, + type StageBConflictRecord, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBInput, + type StageBListingCandidate, + type StageBMatchMethod, + type StageBMatchResult, + type StageBProviderMappingCandidate, + type StageBSource, + type StageBSourceStats, + type StageBStats, + type StageBTickerSource, + type StageBTickerSourceInput, + type StageBUnresolvedReason, + type StageBUnresolvedRecord, +} from './listing-stage-b'; diff --git a/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts b/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts new file mode 100644 index 00000000..49e26f57 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts @@ -0,0 +1,1230 @@ +import { + normalizeBarDate, + spansOverlap, + type SpanDateRange, + type SpansOverlapOptions, +} from '../normalization/bar-spans'; +import { parseTickerDetailed } from '../normalization/ticker'; +import { compareAscii, type ExchangeRole } from './exchange-pass1'; +import type { + StageAInstrumentCandidate, + StageAMatchMethod, + StageASource, +} from './instrument-stage-a'; + +export const MAX_TICKER_ROOT_LENGTH = 24; + +export const STAGE_B_SOURCES = ['eod', 'ib', 'qm', 'ceo'] as const; + +export type StageBSource = (typeof STAGE_B_SOURCES)[number]; + +export type StageBTickerSource = 'qm' | 'ceo'; + +export type StageBMatchMethod = StageAMatchMethod | 'tier3_ticker_span'; + +export interface ListingNaturalKey { + primaryIsin: string; + mic: string; + tickerRoot: string; + classSuffix: string; + currency: string; +} + +export interface StageBEodListingInput { + sourceId: string; + ticker: string | null | undefined; + mic: string | null; + role: ExchangeRole | null; + currency?: string | null; + span: SpanDateRange | null; +} + +export interface StageBIbContractInput { + sourceId: string; + conid: number; + currency?: string | null; + primaryExchange: string | null; +} + +export interface StageBTickerSourceInput { + source: StageBTickerSource; + sourceId: string; + ticker: string | null | undefined; + mic: string | null; + role: ExchangeRole | null; + currency?: string | null; + span: SpanDateRange | null; +} + +export interface StageBInput { + readonly instruments: readonly StageAInstrumentCandidate[]; + readonly eodListings: + | readonly StageBEodListingInput[] + | ReadonlyMap>; + readonly ibContracts: + | readonly StageBIbContractInput[] + | ReadonlyMap>; + readonly tickerSources: readonly StageBTickerSourceInput[]; +} + +export interface MatchListingsStageBOptions { + readonly spanOverlapToleranceDays?: number; +} + +export interface StageBListingCandidate extends ListingNaturalKey { + ibConid: number | null; + ibPrimaryExchange: string | null; + listedFrom: string | null; + listedTo: string | null; +} + +export interface StageBProviderMappingCandidate { + source: StageBSource; + sourceId: string; + listingKey: ListingNaturalKey; + method: StageBMatchMethod; + validFrom: string | null; + validTo: string | null; +} + +export type StageBUnresolvedReason = + | 'excluded_fund' + | 'composite_venue' + | 'ats_routing_venue' + | 'forex_venue' + | 'missing_mic' + | 'invalid_mic' + | 'invalid_ticker' + | 'ticker_root_too_long' + | 'class_suffix_too_long' + | 'invalid_currency' + | 'missing_span' + | 'invalid_span' + | 'no_span_overlap' + | 'missing_eod_listing' + | 'missing_ib_contract' + | 'invalid_ib_conid' + | 'no_listing_for_currency' + | 'no_matching_listing'; + +export interface StageBUnresolvedRecord { + source: StageBSource; + sourceId: string; + reason: StageBUnresolvedReason; + primaryIsin: string | null; +} + +export type StageBConflictKind = + | 'duplicate_source_id' + | 'ambiguous_ib_listing' + | 'competing_ib_conid' + | 'ambiguous_ticker_span'; + +export interface StageBConflictDetail { + primaryIsin: string | null; + currency: string | null; + ibConid: number | null; + competingConids: number[]; + candidateListingKeys: ListingNaturalKey[]; +} + +export interface StageBConflictRecord { + source: StageBSource; + sourceId: string; + conflictKind: StageBConflictKind; + detail: StageBConflictDetail; +} + +export interface StageBSourceStats { + total: number; + matched: number; + unresolved: number; + conflict: number; +} + +export interface StageBStats { + totalListings: number; + totalProviderMappings: number; + listingsWithIbConid: number; + excludedFunds: number; + bySource: Record; +} + +export interface StageBMatchResult { + listings: StageBListingCandidate[]; + providerMappings: StageBProviderMappingCandidate[]; + unresolved: StageBUnresolvedRecord[]; + conflicts: StageBConflictRecord[]; + stats: StageBStats; +} + +type EodMetadata = Omit; +type IbMetadata = Omit; + +interface ListingAccumulator { + readonly key: ListingNaturalKey; + listedFrom: string | null; + listedTo: string | null; + ibConid: number | null; + ibPrimaryExchange: string | null; +} + +interface StagedIbCandidate { + sourceId: string; + primaryIsin: string; + currency: string; + conid: number; + primaryExchange: string | null; + method: StageAMatchMethod; +} + +const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/; +const ISO_CURRENCY_PATTERN = /^[A-Z]{3}$/; +const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; + +export function isStageBSource(value: unknown): value is StageBSource { + return value === 'eod' || value === 'ib' || value === 'qm' || value === 'ceo'; +} + +function isStageASourceValue(value: unknown): value is StageASource { + return value === 'ib' || value === 'eod'; +} + +function isStageAMatchMethodValue(value: unknown): value is StageAMatchMethod { + return value === 'tier1_isin' || value === 'tier2_cusip'; +} + +function isStageBTickerSourceValue(value: unknown): value is StageBTickerSource { + return value === 'qm' || value === 'ceo'; +} + +function isExchangeRoleValue(value: unknown): value is ExchangeRole { + return ( + value === 'primary_venue' || + value === 'composite' || + value === 'ats_routing' || + value === 'forex' || + value === 'excluded_fund' + ); +} + +function createEmptySourceStats(): StageBSourceStats { + return { + total: 0, + matched: 0, + unresolved: 0, + conflict: 0, + }; +} + +function classifyTicker( + raw: string | null | undefined, + source: StageBSource +): + | { ok: true; tickerRoot: string; classSuffix: string } + | { ok: false; reason: 'ticker_root_too_long' | 'class_suffix_too_long' | 'invalid_ticker' } { + const parsed = parseTickerDetailed(raw, source); + if (!parsed.ok) { + if ( + parsed.reason === 'class_suffix_too_long' && + parsed.tickerRoot.length > MAX_TICKER_ROOT_LENGTH + ) { + return { ok: false, reason: 'ticker_root_too_long' }; + } + return { ok: false, reason: parsed.reason }; + } + if (parsed.tickerRoot.length > MAX_TICKER_ROOT_LENGTH) { + return { ok: false, reason: 'ticker_root_too_long' }; + } + return parsed; +} + +function classifyVenueRoleAndMic( + role: ExchangeRole | null | undefined, + mic: string | null | undefined +): + | { ok: true; mic: string } + | { + ok: false; + reason: + | 'excluded_fund' + | 'composite_venue' + | 'ats_routing_venue' + | 'forex_venue' + | 'missing_mic' + | 'invalid_mic'; + } { + if (role === 'excluded_fund') { + return { ok: false, reason: 'excluded_fund' }; + } + if (role === 'composite') { + return { ok: false, reason: 'composite_venue' }; + } + if (role === 'ats_routing') { + return { ok: false, reason: 'ats_routing_venue' }; + } + if (role === 'forex') { + return { ok: false, reason: 'forex_venue' }; + } + if (role === null || role === undefined) { + return { ok: false, reason: 'missing_mic' }; + } + if (typeof mic !== 'string') { + return { ok: false, reason: 'missing_mic' }; + } + const normalizedMic = mic.trim().toUpperCase(); + if (normalizedMic.length === 0) { + return { ok: false, reason: 'missing_mic' }; + } + if (!ISO_MIC_PATTERN.test(normalizedMic)) { + return { ok: false, reason: 'invalid_mic' }; + } + return { ok: true, mic: normalizedMic }; +} + +function normalizeCurrency(value: string | null | undefined): string | null { + if (typeof value !== 'string') { + return null; + } + const normalized = value.trim().toUpperCase(); + return ISO_CURRENCY_PATTERN.test(normalized) ? normalized : null; +} + +function normalizeOptionalExchangeLabel(value: string | null | undefined): string | null { + if (typeof value !== 'string') { + return null; + } + const normalized = value.trim().toUpperCase(); + return normalized.length > 0 ? normalized : null; +} + +function validateSpan( + span: SpanDateRange | null | undefined +): + | { status: 'missing' } + | { status: 'invalid' } + | { status: 'valid'; span: SpanDateRange } { + if (span === null || span === undefined) { + return { status: 'missing' }; + } + if (typeof span !== 'object') { + return { status: 'invalid' }; + } + if (typeof span.firstBarDate !== 'string' || typeof span.lastBarDate !== 'string') { + return { status: 'invalid' }; + } + // Require exact YYYY-MM-DD strings so timezone-qualified timestamps cannot shift across UTC day boundaries. + if ( + !EXACT_YMD_PATTERN.test(span.firstBarDate) || + !EXACT_YMD_PATTERN.test(span.lastBarDate) + ) { + return { status: 'invalid' }; + } + const firstBarDate = normalizeBarDate(span.firstBarDate); + const lastBarDate = normalizeBarDate(span.lastBarDate); + if (firstBarDate === null || lastBarDate === null || firstBarDate > lastBarDate) { + return { status: 'invalid' }; + } + return { status: 'valid', span: { firstBarDate, lastBarDate } }; +} + +function makeListingNaturalKeyId(key: ListingNaturalKey): string { + return `${key.primaryIsin}\u0000${key.mic}\u0000${key.tickerRoot}\u0000${key.classSuffix}\u0000${key.currency}`; +} + +function makeTickerLookupKey( + mic: string, + currency: string, + tickerRoot: string, + classSuffix: string +): string { + return `${mic}\u0000${currency}\u0000${tickerRoot}\u0000${classSuffix}`; +} + +function compareListingNaturalKey(a: ListingNaturalKey, b: ListingNaturalKey): number { + return ( + compareAscii(a.primaryIsin, b.primaryIsin) || + compareAscii(a.mic, b.mic) || + compareAscii(a.tickerRoot, b.tickerRoot) || + compareAscii(a.classSuffix, b.classSuffix) || + compareAscii(a.currency, b.currency) + ); +} + +function compareNullableNumber(a: number | null, b: number | null): number { + if (a === b) { + return 0; + } + if (a === null) { + return -1; + } + if (b === null) { + return 1; + } + return a < b ? -1 : 1; +} + +function compareNumberArrays(a: readonly number[], b: readonly number[]): number { + const len = a.length < b.length ? a.length : b.length; + for (let i = 0; i < len; i++) { + const av = a[i] ?? 0; + const bv = b[i] ?? 0; + if (av !== bv) { + return av < bv ? -1 : 1; + } + } + return a.length - b.length; +} + +function compareListingKeyArrays( + a: readonly ListingNaturalKey[], + b: readonly ListingNaturalKey[] +): number { + const len = a.length < b.length ? a.length : b.length; + for (let i = 0; i < len; i++) { + const ak = a[i]; + const bk = b[i]; + if (ak !== undefined && bk !== undefined) { + const cmp = compareListingNaturalKey(ak, bk); + if (cmp !== 0) { + return cmp; + } + } + } + return a.length - b.length; +} + +function compareProviderMappings( + a: StageBProviderMappingCandidate, + b: StageBProviderMappingCandidate +): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareListingNaturalKey(a.listingKey, b.listingKey) || + compareAscii(a.method, b.method) || + compareAscii(a.validFrom ?? '', b.validFrom ?? '') || + compareAscii(a.validTo ?? '', b.validTo ?? '') + ); +} + +function compareUnresolved(a: StageBUnresolvedRecord, b: StageBUnresolvedRecord): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.reason, b.reason) || + compareAscii(a.primaryIsin ?? '', b.primaryIsin ?? '') + ); +} + +function compareConflicts(a: StageBConflictRecord, b: StageBConflictRecord): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.conflictKind, b.conflictKind) || + compareAscii(a.detail.primaryIsin ?? '', b.detail.primaryIsin ?? '') || + compareAscii(a.detail.currency ?? '', b.detail.currency ?? '') || + compareNullableNumber(a.detail.ibConid, b.detail.ibConid) || + compareNumberArrays(a.detail.competingConids, b.detail.competingConids) || + compareListingKeyArrays(a.detail.candidateListingKeys, b.detail.candidateListingKeys) + ); +} + +function assertIsArray(value: unknown, label: string): void { + if (!Array.isArray(value)) { + throw new TypeError(`Stage B ${label} must be an array`); + } +} + +function emptyConflictDetail( + primaryIsin: string | null = null, + currency: string | null = null +): StageBConflictDetail { + return { + primaryIsin, + currency, + ibConid: null, + competingConids: [], + candidateListingKeys: [], + }; +} + +/** + * Pass 3 Stage B pure in-memory listing matcher. + * + * 1. Builds primary-venue EOD listings keyed by `(primaryIsin, mic, tickerRoot, classSuffix, currency)`. + * 2. Attaches IB `conid`s strictly at `(instrument, currency)` with conflict quarantine; never uses + * IB `exchangeId` as a listing MIC. + * 3. Matches QM and CEO records via Tier 3 `(tickerRoot, classSuffix, mic, currency)` + `spansOverlap`. + */ +export function matchListingsStageB( + input: StageBInput, + options: MatchListingsStageBOptions = {} +): StageBMatchResult { + if (options === null || typeof options !== 'object') { + throw new TypeError('options must be an object'); + } + const toleranceDays = options.spanOverlapToleranceDays ?? 0; + if ( + typeof toleranceDays !== 'number' || + !Number.isSafeInteger(toleranceDays) || + toleranceDays < 0 + ) { + throw new RangeError( + `options.spanOverlapToleranceDays must be a non-negative safe integer, received ${String(toleranceDays)}` + ); + } + const overlapOptions: SpansOverlapOptions = { toleranceDays }; + + if (input === null || input === undefined || typeof input !== 'object') { + throw new TypeError('Stage B input must be an object'); + } + assertIsArray(input.instruments, 'input.instruments'); + assertIsArray(input.tickerSources, 'input.tickerSources'); + + // Validate instruments and count member `(source, sourceId)` occurrences in a single pass. + const memberCountsBySource: Record> = { + eod: new Map(), + ib: new Map(), + }; + const seenPrimaryIsins = new Set(); + + for (let i = 0; i < input.instruments.length; i++) { + if (!(i in input.instruments)) { + throw new TypeError(`Invalid sparse slot at instruments[${i}]: expected an instrument object`); + } + const inst = input.instruments[i]; + if (inst === undefined || inst === null || typeof inst !== 'object') { + throw new TypeError(`Invalid Stage B instrument at instruments[${i}]: expected an object`); + } + if (typeof inst.primaryIsin !== 'string' || inst.primaryIsin.trim().length === 0) { + throw new Error(`Invalid empty or non-string primaryIsin at instruments[${i}]`); + } + if (seenPrimaryIsins.has(inst.primaryIsin)) { + throw new Error(`Duplicate primaryIsin "${inst.primaryIsin}" at instruments[${i}]`); + } + seenPrimaryIsins.add(inst.primaryIsin); + + assertIsArray(inst.members, `instruments[${i}].members`); + for (let j = 0; j < inst.members.length; j++) { + if (!(j in inst.members)) { + throw new TypeError( + `Invalid sparse slot at instruments[${i}].members[${j}]: expected a member object` + ); + } + const member = inst.members[j]; + if (member === undefined || member === null || typeof member !== 'object') { + throw new TypeError( + `Invalid Stage B instrument member at instruments[${i}].members[${j}]: expected an object` + ); + } + if (!isStageASourceValue(member.source)) { + throw new Error( + `Unknown Stage A member source "${String(member.source)}" at instruments[${i}].members[${j}]` + ); + } + if (typeof member.sourceId !== 'string' || member.sourceId.length === 0) { + throw new Error( + `Invalid empty or non-string sourceId at instruments[${i}].members[${j}]` + ); + } + if (!isStageAMatchMethodValue(member.method)) { + throw new Error( + `Unknown Stage A member method "${String(member.method)}" at instruments[${i}].members[${j}]` + ); + } + const counts = memberCountsBySource[member.source]; + counts.set(member.sourceId, (counts.get(member.sourceId) ?? 0) + 1); + } + } + + // Validate and index eodListings. + const eodBySourceId = new Map(); + const eodMetadataCounts = new Map(); + + if (input.eodListings instanceof Map) { + let idx = 0; + for (const [sourceId, entry] of input.eodListings.entries()) { + if (typeof sourceId !== 'string' || sourceId.length === 0) { + throw new Error(`Invalid empty or non-string sourceId in eodListings map at entry ${idx}`); + } + if (entry === undefined || entry === null || typeof entry !== 'object') { + throw new TypeError( + `Invalid eodListings map value for sourceId "${sourceId}" at entry ${idx}: expected an object` + ); + } + if (entry.role !== null && entry.role !== undefined && !isExchangeRoleValue(entry.role)) { + throw new Error( + `Unknown exchange role "${String(entry.role)}" in eodListings map for sourceId "${sourceId}"` + ); + } + eodMetadataCounts.set(sourceId, 1); + eodBySourceId.set(sourceId, entry); + idx++; + } + } else { + if (!Array.isArray(input.eodListings)) { + throw new TypeError('Stage B input.eodListings must be an array or Map'); + } + const eodList: readonly StageBEodListingInput[] = input.eodListings; + for (let i = 0; i < eodList.length; i++) { + if (!(i in eodList)) { + throw new TypeError(`Invalid sparse slot at eodListings[${i}]: expected an object`); + } + const entry = eodList[i]; + if (entry === undefined || entry === null || typeof entry !== 'object') { + throw new TypeError(`Invalid eodListings entry at index ${i}: expected an object`); + } + if (typeof entry.sourceId !== 'string' || entry.sourceId.length === 0) { + throw new Error(`Invalid empty or non-string sourceId at eodListings[${i}]`); + } + if (entry.role !== null && entry.role !== undefined && !isExchangeRoleValue(entry.role)) { + throw new Error(`Unknown exchange role "${String(entry.role)}" at eodListings[${i}]`); + } + const nextCount = (eodMetadataCounts.get(entry.sourceId) ?? 0) + 1; + eodMetadataCounts.set(entry.sourceId, nextCount); + if (nextCount === 1) { + eodBySourceId.set(entry.sourceId, entry); + } + } + } + + // Validate and index ibContracts. + const ibBySourceId = new Map(); + const ibMetadataCounts = new Map(); + + if (input.ibContracts instanceof Map) { + let idx = 0; + for (const [sourceId, entry] of input.ibContracts.entries()) { + if (typeof sourceId !== 'string' || sourceId.length === 0) { + throw new Error(`Invalid empty or non-string sourceId in ibContracts map at entry ${idx}`); + } + if (entry === undefined || entry === null || typeof entry !== 'object') { + throw new TypeError( + `Invalid ibContracts map value for sourceId "${sourceId}" at entry ${idx}: expected an object` + ); + } + ibMetadataCounts.set(sourceId, 1); + ibBySourceId.set(sourceId, entry); + idx++; + } + } else { + if (!Array.isArray(input.ibContracts)) { + throw new TypeError('Stage B input.ibContracts must be an array or Map'); + } + const ibList: readonly StageBIbContractInput[] = input.ibContracts; + for (let i = 0; i < ibList.length; i++) { + if (!(i in ibList)) { + throw new TypeError(`Invalid sparse slot at ibContracts[${i}]: expected an object`); + } + const entry = ibList[i]; + if (entry === undefined || entry === null || typeof entry !== 'object') { + throw new TypeError(`Invalid ibContracts entry at index ${i}: expected an object`); + } + if (typeof entry.sourceId !== 'string' || entry.sourceId.length === 0) { + throw new Error(`Invalid empty or non-string sourceId at ibContracts[${i}]`); + } + const nextCount = (ibMetadataCounts.get(entry.sourceId) ?? 0) + 1; + ibMetadataCounts.set(entry.sourceId, nextCount); + if (nextCount === 1) { + ibBySourceId.set(entry.sourceId, entry); + } + } + } + + // Validate and count tickerSources (qm / ceo). + const tickerCountsBySource: Record> = { + qm: new Map(), + ceo: new Map(), + }; + + for (let i = 0; i < input.tickerSources.length; i++) { + if (!(i in input.tickerSources)) { + throw new TypeError(`Invalid sparse slot at tickerSources[${i}]: expected an object`); + } + const entry = input.tickerSources[i]; + if (entry === undefined || entry === null || typeof entry !== 'object') { + throw new TypeError(`Invalid tickerSources entry at index ${i}: expected an object`); + } + if (!isStageBTickerSourceValue(entry.source)) { + throw new Error( + `Unknown Stage B ticker source "${String(entry.source)}" at tickerSources[${i}]` + ); + } + if (typeof entry.sourceId !== 'string' || entry.sourceId.length === 0) { + throw new Error(`Invalid empty or non-string sourceId at tickerSources[${i}]`); + } + if (entry.role !== null && entry.role !== undefined && !isExchangeRoleValue(entry.role)) { + throw new Error(`Unknown exchange role "${String(entry.role)}" at tickerSources[${i}]`); + } + const counts = tickerCountsBySource[entry.source]; + counts.set(entry.sourceId, (counts.get(entry.sourceId) ?? 0) + 1); + } + + const statsBySource: Record = { + eod: createEmptySourceStats(), + ib: createEmptySourceStats(), + qm: createEmptySourceStats(), + ceo: createEmptySourceStats(), + }; + let excludedFunds = 0; + + const listingsByNaturalKey = new Map(); + const listingsByInstrumentCurrency = new Map>(); + const listingsByTickerKey = new Map(); + + const providerMappings: StageBProviderMappingCandidate[] = []; + const unresolved: StageBUnresolvedRecord[] = []; + const conflicts: StageBConflictRecord[] = []; + + // Step 1: EOD members -> primary-venue listing candidates + EOD provider mappings. + for (let i = 0; i < input.instruments.length; i++) { + const inst = input.instruments[i]; + if (inst === undefined) { + continue; + } + for (let j = 0; j < inst.members.length; j++) { + const member = inst.members[j]; + if (member === undefined || member.source !== 'eod') { + continue; + } + + statsBySource.eod.total += 1; + + if ( + (memberCountsBySource.eod.get(member.sourceId) ?? 0) > 1 || + (eodMetadataCounts.get(member.sourceId) ?? 0) > 1 + ) { + conflicts.push({ + source: 'eod', + sourceId: member.sourceId, + conflictKind: 'duplicate_source_id', + detail: emptyConflictDetail(inst.primaryIsin, member.currency), + }); + statsBySource.eod.conflict += 1; + continue; + } + + const eod = eodBySourceId.get(member.sourceId); + if (eod === undefined) { + unresolved.push({ + source: 'eod', + sourceId: member.sourceId, + reason: 'missing_eod_listing', + primaryIsin: inst.primaryIsin, + }); + statsBySource.eod.unresolved += 1; + continue; + } + + const venue = classifyVenueRoleAndMic(eod.role, eod.mic); + if (!venue.ok) { + if (venue.reason === 'excluded_fund') { + excludedFunds += 1; + } + unresolved.push({ + source: 'eod', + sourceId: member.sourceId, + reason: venue.reason, + primaryIsin: inst.primaryIsin, + }); + statsBySource.eod.unresolved += 1; + continue; + } + + const ticker = classifyTicker(eod.ticker, 'eod'); + if (!ticker.ok) { + unresolved.push({ + source: 'eod', + sourceId: member.sourceId, + reason: ticker.reason, + primaryIsin: inst.primaryIsin, + }); + statsBySource.eod.unresolved += 1; + continue; + } + + const currency = normalizeCurrency(eod.currency ?? member.currency); + if (currency === null) { + unresolved.push({ + source: 'eod', + sourceId: member.sourceId, + reason: 'invalid_currency', + primaryIsin: inst.primaryIsin, + }); + statsBySource.eod.unresolved += 1; + continue; + } + + const spanCheck = validateSpan(eod.span); + if (spanCheck.status === 'invalid') { + unresolved.push({ + source: 'eod', + sourceId: member.sourceId, + reason: 'invalid_span', + primaryIsin: inst.primaryIsin, + }); + statsBySource.eod.unresolved += 1; + continue; + } + const validSpan = spanCheck.status === 'valid' ? spanCheck.span : null; + + const key: ListingNaturalKey = { + primaryIsin: inst.primaryIsin, + mic: venue.mic, + tickerRoot: ticker.tickerRoot, + classSuffix: ticker.classSuffix, + currency, + }; + const keyId = makeListingNaturalKeyId(key); + let acc = listingsByNaturalKey.get(keyId); + if (acc === undefined) { + acc = { + key, + listedFrom: validSpan?.firstBarDate ?? null, + listedTo: validSpan?.lastBarDate ?? null, + ibConid: null, + ibPrimaryExchange: null, + }; + listingsByNaturalKey.set(keyId, acc); + + let byCurrency = listingsByInstrumentCurrency.get(inst.primaryIsin); + if (byCurrency === undefined) { + byCurrency = new Map(); + listingsByInstrumentCurrency.set(inst.primaryIsin, byCurrency); + } + let currencyList = byCurrency.get(currency); + if (currencyList === undefined) { + currencyList = []; + byCurrency.set(currency, currencyList); + } + currencyList.push(acc); + + const tickerKey = makeTickerLookupKey( + venue.mic, + currency, + ticker.tickerRoot, + ticker.classSuffix + ); + let tickerList = listingsByTickerKey.get(tickerKey); + if (tickerList === undefined) { + tickerList = []; + listingsByTickerKey.set(tickerKey, tickerList); + } + tickerList.push(acc); + } else if (validSpan !== null) { + // Associative & commutative min/max widening ensures shuffle invariance. + if (acc.listedFrom === null || validSpan.firstBarDate < acc.listedFrom) { + acc.listedFrom = validSpan.firstBarDate; + } + if (acc.listedTo === null || validSpan.lastBarDate > acc.listedTo) { + acc.listedTo = validSpan.lastBarDate; + } + } + + providerMappings.push({ + source: 'eod', + sourceId: member.sourceId, + listingKey: acc.key, + method: member.method, + validFrom: validSpan?.firstBarDate ?? null, + validTo: validSpan?.lastBarDate ?? null, + }); + statsBySource.eod.matched += 1; + } + } + + for (const [sourceId, count] of eodMetadataCounts.entries()) { + if (count > 1 && (memberCountsBySource.eod.get(sourceId) ?? 0) === 0) { + conflicts.push({ + source: 'eod', + sourceId, + conflictKind: 'duplicate_source_id', + detail: emptyConflictDetail(), + }); + statsBySource.eod.total += 1; + statsBySource.eod.conflict += 1; + } + } + + // Step 2: IB members -> attach conid strictly at (instrument, currency). + const ibCandidatesByListing = new Map(); + + for (let i = 0; i < input.instruments.length; i++) { + const inst = input.instruments[i]; + if (inst === undefined) { + continue; + } + for (let j = 0; j < inst.members.length; j++) { + const member = inst.members[j]; + if (member === undefined || member.source !== 'ib') { + continue; + } + + statsBySource.ib.total += 1; + + if ( + (memberCountsBySource.ib.get(member.sourceId) ?? 0) > 1 || + (ibMetadataCounts.get(member.sourceId) ?? 0) > 1 + ) { + conflicts.push({ + source: 'ib', + sourceId: member.sourceId, + conflictKind: 'duplicate_source_id', + detail: emptyConflictDetail(inst.primaryIsin, member.currency), + }); + statsBySource.ib.conflict += 1; + continue; + } + + const contract = ibBySourceId.get(member.sourceId); + if (contract === undefined) { + unresolved.push({ + source: 'ib', + sourceId: member.sourceId, + reason: 'missing_ib_contract', + primaryIsin: inst.primaryIsin, + }); + statsBySource.ib.unresolved += 1; + continue; + } + + if ( + typeof contract.conid !== 'number' || + !Number.isSafeInteger(contract.conid) || + contract.conid <= 0 + ) { + unresolved.push({ + source: 'ib', + sourceId: member.sourceId, + reason: 'invalid_ib_conid', + primaryIsin: inst.primaryIsin, + }); + statsBySource.ib.unresolved += 1; + continue; + } + + const currency = normalizeCurrency(contract.currency ?? member.currency); + if (currency === null) { + unresolved.push({ + source: 'ib', + sourceId: member.sourceId, + reason: 'invalid_currency', + primaryIsin: inst.primaryIsin, + }); + statsBySource.ib.unresolved += 1; + continue; + } + + const primaryExchange = normalizeOptionalExchangeLabel(contract.primaryExchange); + const candidates = listingsByInstrumentCurrency.get(inst.primaryIsin)?.get(currency); + + if (candidates === undefined || candidates.length === 0) { + unresolved.push({ + source: 'ib', + sourceId: member.sourceId, + reason: 'no_listing_for_currency', + primaryIsin: inst.primaryIsin, + }); + statsBySource.ib.unresolved += 1; + continue; + } + + if (candidates.length > 1) { + const candidateListingKeys = candidates.map(c => c.key).sort(compareListingNaturalKey); + conflicts.push({ + source: 'ib', + sourceId: member.sourceId, + conflictKind: 'ambiguous_ib_listing', + detail: { + primaryIsin: inst.primaryIsin, + currency, + ibConid: contract.conid, + competingConids: [], + candidateListingKeys, + }, + }); + statsBySource.ib.conflict += 1; + continue; + } + + const targetListing = candidates[0]; + if (targetListing === undefined) { + continue; + } + + let staged = ibCandidatesByListing.get(targetListing); + if (staged === undefined) { + staged = []; + ibCandidatesByListing.set(targetListing, staged); + } + staged.push({ + sourceId: member.sourceId, + primaryIsin: inst.primaryIsin, + currency, + conid: contract.conid, + primaryExchange, + method: member.method, + }); + } + } + + for (const [listingAcc, staged] of ibCandidatesByListing.entries()) { + if (staged.length === 1) { + const winner = staged[0]; + if (winner === undefined) { + continue; + } + listingAcc.ibConid = winner.conid; + listingAcc.ibPrimaryExchange = winner.primaryExchange; + providerMappings.push({ + source: 'ib', + sourceId: winner.sourceId, + listingKey: listingAcc.key, + method: winner.method, + validFrom: null, + validTo: null, + }); + statsBySource.ib.matched += 1; + } else if (staged.length > 1) { + const competingConids = Array.from(new Set(staged.map(s => s.conid))).sort((a, b) => a - b); + for (const item of staged) { + conflicts.push({ + source: 'ib', + sourceId: item.sourceId, + conflictKind: 'competing_ib_conid', + detail: { + primaryIsin: item.primaryIsin, + currency: item.currency, + ibConid: item.conid, + competingConids: [...competingConids], + candidateListingKeys: [listingAcc.key], + }, + }); + statsBySource.ib.conflict += 1; + } + } + } + + for (const [sourceId, count] of ibMetadataCounts.entries()) { + if (count > 1 && (memberCountsBySource.ib.get(sourceId) ?? 0) === 0) { + conflicts.push({ + source: 'ib', + sourceId, + conflictKind: 'duplicate_source_id', + detail: emptyConflictDetail(), + }); + statsBySource.ib.total += 1; + statsBySource.ib.conflict += 1; + } + } + + // Step 3: QM / CEO Tier 3 ticker + inclusive spansOverlap matching. + for (let i = 0; i < input.tickerSources.length; i++) { + const record = input.tickerSources[i]; + if (record === undefined) { + continue; + } + const source = record.source; + const sourceStats = statsBySource[source]; + sourceStats.total += 1; + + if ((tickerCountsBySource[source].get(record.sourceId) ?? 0) > 1) { + conflicts.push({ + source, + sourceId: record.sourceId, + conflictKind: 'duplicate_source_id', + detail: emptyConflictDetail(), + }); + sourceStats.conflict += 1; + continue; + } + + const venue = classifyVenueRoleAndMic(record.role, record.mic); + if (!venue.ok) { + if (venue.reason === 'excluded_fund') { + excludedFunds += 1; + } + unresolved.push({ + source, + sourceId: record.sourceId, + reason: venue.reason, + primaryIsin: null, + }); + sourceStats.unresolved += 1; + continue; + } + + const ticker = classifyTicker(record.ticker, source); + if (!ticker.ok) { + unresolved.push({ + source, + sourceId: record.sourceId, + reason: ticker.reason, + primaryIsin: null, + }); + sourceStats.unresolved += 1; + continue; + } + + const currency = normalizeCurrency(record.currency); + if (currency === null) { + unresolved.push({ + source, + sourceId: record.sourceId, + reason: 'invalid_currency', + primaryIsin: null, + }); + sourceStats.unresolved += 1; + continue; + } + + const spanCheck = validateSpan(record.span); + if (spanCheck.status === 'missing') { + unresolved.push({ + source, + sourceId: record.sourceId, + reason: 'missing_span', + primaryIsin: null, + }); + sourceStats.unresolved += 1; + continue; + } + if (spanCheck.status === 'invalid') { + unresolved.push({ + source, + sourceId: record.sourceId, + reason: 'invalid_span', + primaryIsin: null, + }); + sourceStats.unresolved += 1; + continue; + } + + const tickerKey = makeTickerLookupKey( + venue.mic, + currency, + ticker.tickerRoot, + ticker.classSuffix + ); + const candidates = listingsByTickerKey.get(tickerKey); + if (candidates === undefined || candidates.length === 0) { + unresolved.push({ + source, + sourceId: record.sourceId, + reason: 'no_matching_listing', + primaryIsin: null, + }); + sourceStats.unresolved += 1; + continue; + } + + const overlapping: ListingAccumulator[] = []; + let missingSpanCount = 0; + + for (let k = 0; k < candidates.length; k++) { + const cand = candidates[k]; + if (cand === undefined) { + continue; + } + if (cand.listedFrom === null || cand.listedTo === null) { + missingSpanCount += 1; + } else if ( + spansOverlap( + spanCheck.span, + { firstBarDate: cand.listedFrom, lastBarDate: cand.listedTo }, + overlapOptions + ) + ) { + overlapping.push(cand); + } + } + + if (overlapping.length > 1) { + const candidateListingKeys = overlapping.map(c => c.key).sort(compareListingNaturalKey); + conflicts.push({ + source, + sourceId: record.sourceId, + conflictKind: 'ambiguous_ticker_span', + detail: { + primaryIsin: null, + currency, + ibConid: null, + competingConids: [], + candidateListingKeys, + }, + }); + sourceStats.conflict += 1; + } else if (missingSpanCount > 0) { + // Never match when a same-key listing has an unknown span (could hide a reused-ticker collision). + unresolved.push({ + source, + sourceId: record.sourceId, + reason: 'missing_span', + primaryIsin: null, + }); + sourceStats.unresolved += 1; + } else if (overlapping.length === 1) { + const matchedListing = overlapping[0]; + if (matchedListing !== undefined) { + providerMappings.push({ + source, + sourceId: record.sourceId, + listingKey: matchedListing.key, + method: 'tier3_ticker_span', + validFrom: spanCheck.span.firstBarDate, + validTo: spanCheck.span.lastBarDate, + }); + sourceStats.matched += 1; + } + } else { + unresolved.push({ + source, + sourceId: record.sourceId, + reason: 'no_span_overlap', + primaryIsin: null, + }); + sourceStats.unresolved += 1; + } + } + + // Finalize deterministically sorted outputs and stats. + const listings: StageBListingCandidate[] = []; + let listingsWithIbConid = 0; + + for (const acc of listingsByNaturalKey.values()) { + if (acc.ibConid !== null) { + listingsWithIbConid += 1; + } + listings.push({ + primaryIsin: acc.key.primaryIsin, + mic: acc.key.mic, + tickerRoot: acc.key.tickerRoot, + classSuffix: acc.key.classSuffix, + currency: acc.key.currency, + ibConid: acc.ibConid, + ibPrimaryExchange: acc.ibPrimaryExchange, + listedFrom: acc.listedFrom, + listedTo: acc.listedTo, + }); + } + + listings.sort(compareListingNaturalKey); + providerMappings.sort(compareProviderMappings); + unresolved.sort(compareUnresolved); + conflicts.sort(compareConflicts); + + return { + listings, + providerMappings, + unresolved, + conflicts, + stats: { + totalListings: listings.length, + totalProviderMappings: providerMappings.length, + listingsWithIbConid, + excludedFunds, + bySource: statsBySource, + }, + }; +} diff --git a/test/integration/intraday-storage.test.ts b/test/integration/intraday-storage.test.ts index 887064b2..28ab7ac7 100644 --- a/test/integration/intraday-storage.test.ts +++ b/test/integration/intraday-storage.test.ts @@ -90,7 +90,7 @@ async function ingest(mongodb: MongoDBClient, bars = intradayResponse()) { return Response.json(bars); }; const previousToken = EOD_CONFIG.API_TOKEN; - EOD_CONFIG.API_TOKEN = 'test-fixture-token'; + EOD_CONFIG.API_TOKEN = 'test-eod-fixture-token'; const request = spyOn(globalThis, 'fetch').mockImplementation( Object.assign(fakeFetch, { preconnect: globalThis.fetch.preconnect }) ); @@ -102,8 +102,8 @@ async function ingest(mongodb: MongoDBClient, bars = intradayResponse()) { toDate: end, }); } finally { - EOD_CONFIG.API_TOKEN = previousToken; request.mockRestore(); + EOD_CONFIG.API_TOKEN = previousToken; } } diff --git a/test/unit/normalization-ticker.test.ts b/test/unit/normalization-ticker.test.ts index 258cbb20..50c5d142 100644 --- a/test/unit/normalization-ticker.test.ts +++ b/test/unit/normalization-ticker.test.ts @@ -5,6 +5,7 @@ import { } from '../../apps/stock/data-pipeline/src/normalization/identifiers'; import { parseTicker, + parseTickerDetailed, type TickerSource, } from '../../apps/stock/data-pipeline/src/normalization/ticker'; @@ -86,6 +87,23 @@ describe('parseTicker', () => { }); expect(parseTicker('RY.ABCDEFGHIJKLM', 'eod')).toBeNull(); expect(parseTicker('RY.PR.ABCDEFGHIJ', 'eod')).toBeNull(); + + expect(parseTickerDetailed('RY.ABCDEFGHIJKLM', 'eod')).toEqual({ + ok: false, + reason: 'class_suffix_too_long', + tickerRoot: 'RY', + classSuffix: 'ABCDEFGHIJKLM', + }); + expect(parseTickerDetailed('RY.PR.ABCDEFGHIJ.TO', 'ceo')).toEqual({ + ok: false, + reason: 'class_suffix_too_long', + tickerRoot: 'RY', + classSuffix: 'PR.ABCDEFGHIJ', + }); + expect(parseTickerDetailed('RY..A', 'eod')).toEqual({ + ok: false, + reason: 'invalid_ticker', + }); }); test('completes 100,000 resolveIsin + parseTicker calls in under 500 ms', () => { diff --git a/test/unit/security-master-listing-stage-b-edge.test.ts b/test/unit/security-master-listing-stage-b-edge.test.ts new file mode 100644 index 00000000..a088570f --- /dev/null +++ b/test/unit/security-master-listing-stage-b-edge.test.ts @@ -0,0 +1,546 @@ +import { describe, expect, test } from 'bun:test'; +import { + matchListingsStageB, + MAX_TICKER_ROOT_LENGTH, + STAGE_B_SOURCES, + type StageAInstrumentCandidate, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBInput, + type StageBMatchResult, + type StageBTickerSourceInput, +} from '../../apps/stock/data-pipeline/src/security-master'; +import { MAX_CLASS_SUFFIX_LENGTH } from '../../apps/stock/data-pipeline/src/normalization/ticker'; + +// QA edge cases for Pass 3 Stage B (T-56) not covered by security-master-listing-stage-b.test.ts. + +type Member = StageAInstrumentCandidate['members'][number]; + +function instrument(primaryIsin: string, members: Member[]): StageAInstrumentCandidate { + return { primaryIsin, primaryCusip: null, issuerCountry: 'US', canonicalName: null, members }; +} + +function eodMember(sourceId: string, currency = 'USD'): Member { + return { source: 'eod', sourceId, currency, method: 'tier1_isin' }; +} + +function ibMember(sourceId: string, currency = 'USD'): Member { + return { source: 'ib', sourceId, currency, method: 'tier2_cusip' }; +} + +function eod( + sourceId: string, + ticker: string, + mic: string, + span: [string, string] | null, + currency: string | null | undefined = 'USD' +): StageBEodListingInput { + return { + sourceId, + ticker, + mic, + role: 'primary_venue', + currency, + span: span === null ? null : { firstBarDate: span[0], lastBarDate: span[1] }, + }; +} + +function qm( + sourceId: string, + ticker: string, + mic: string, + span: [string, string] | null, + currency = 'USD', + source: 'qm' | 'ceo' = 'qm' +): StageBTickerSourceInput { + return { + source, + sourceId, + ticker, + mic, + role: 'primary_venue', + currency, + span: span === null ? null : { firstBarDate: span[0], lastBarDate: span[1] }, + }; +} + +function assertReconciles(result: StageBMatchResult): void { + expect(result.stats.totalListings).toBe(result.listings.length); + expect(result.stats.totalProviderMappings).toBe(result.providerMappings.length); + for (const source of STAGE_B_SOURCES) { + const s = result.stats.bySource[source]; + expect(s.matched).toBe(result.providerMappings.filter(m => m.source === source).length); + expect(s.unresolved).toBe(result.unresolved.filter(u => u.source === source).length); + expect(s.conflict).toBe(result.conflicts.filter(c => c.source === source).length); + expect(s.matched + s.unresolved + s.conflict).toBe(s.total); + } +} + +function makeRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function shuffle(items: readonly T[], seed: number): T[] { + const copy = [...items]; + const rng = makeRng(seed); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + const a = copy[i] as T; + copy[i] = copy[j] as T; + copy[j] = a; + } + return copy; +} + +function deepFreeze(value: T): T { + if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) { + Object.freeze(value); + for (const key of Object.keys(value)) { + deepFreeze((value as Record)[key]); + } + } + return value; +} + +const FB_OLD_ISIN = 'US30303M1027'; +const FB_NEW_ISIN = 'US0000000026'; + +function reusedFbInput(tickerSources: StageBTickerSourceInput[]): StageBInput { + return { + instruments: [ + instrument(FB_OLD_ISIN, [eodMember('FB_OLD')]), + instrument(FB_NEW_ISIN, [eodMember('FB_NEW')]), + ], + eodListings: [ + eod('FB_OLD', 'FB', 'XNAS', ['2012-05-18', '2022-06-08']), + eod('FB_NEW', 'FB', 'XNAS', ['2025-01-02', '2025-11-26']), + ], + ibContracts: [], + tickerSources, + }; +} + +describe('Pass 3 Stage B listing matcher — QA edge cases', () => { + test('span overlap is inclusive on both edges of a reused-ticker boundary and tolerance only widens it', () => { + const tickerSources = [ + qm('QM_LAST_DAY_OLD', 'FB', 'XNAS', ['2022-06-08', '2022-06-08']), + qm('QM_DAY_AFTER_OLD', 'FB', 'XNAS', ['2022-06-09', '2022-06-09']), + qm('QM_DAY_BEFORE_NEW', 'FB', 'XNAS', ['2025-01-01', '2025-01-01']), + qm('QM_FIRST_DAY_NEW', 'FB', 'XNAS', ['2025-01-02', '2025-01-02']), + ]; + + const strict = matchListingsStageB(reusedFbInput(tickerSources)); + const strictMap = Object.fromEntries( + strict.providerMappings + .filter(m => m.source === 'qm') + .map(m => [m.sourceId, m.listingKey.primaryIsin]) + ); + expect(strictMap).toEqual({ QM_LAST_DAY_OLD: FB_OLD_ISIN, QM_FIRST_DAY_NEW: FB_NEW_ISIN }); + expect(strict.unresolved.map(u => [u.sourceId, u.reason])).toEqual([ + ['QM_DAY_AFTER_OLD', 'no_span_overlap'], + ['QM_DAY_BEFORE_NEW', 'no_span_overlap'], + ]); + assertReconciles(strict); + + const tolerant = matchListingsStageB(reusedFbInput(tickerSources), { + spanOverlapToleranceDays: 1, + }); + const tolerantMap = Object.fromEntries( + tolerant.providerMappings + .filter(m => m.source === 'qm') + .map(m => [m.sourceId, m.listingKey.primaryIsin]) + ); + expect(tolerantMap).toEqual({ + QM_LAST_DAY_OLD: FB_OLD_ISIN, + QM_DAY_AFTER_OLD: FB_OLD_ISIN, + QM_DAY_BEFORE_NEW: FB_NEW_ISIN, + QM_FIRST_DAY_NEW: FB_NEW_ISIN, + }); + expect(tolerant.unresolved).toEqual([]); + assertReconciles(tolerant); + }); + + test('ticker change FB→META keeps one instrument and never routes a stale FB alias to another security', () => { + // EOD stores Meta's whole history under META; a pre-2022 QM "FB" record must not be silently + // attached to anything, while QM "META" before and after the change resolves to one listing. + const result = matchListingsStageB({ + instruments: [ + instrument(FB_OLD_ISIN, [eodMember('META.US'), ibMember('ib-meta')]), + instrument(FB_NEW_ISIN, [eodMember('FB_NEW')]), + ], + eodListings: [ + eod('META.US', 'META', 'XNAS', ['2012-05-18', '2025-11-26']), + eod('FB_NEW', 'FB', 'XNAS', ['2025-01-02', '2025-11-26']), + ], + ibContracts: [{ sourceId: 'ib-meta', conid: 107113386, currency: 'USD', primaryExchange: 'NASDAQ' }], + tickerSources: [ + qm('QM_FB_2015', 'FB', 'XNAS', ['2015-01-02', '2015-12-31']), + qm('QM_META_PRE', 'META', 'XNAS', ['2022-06-08', '2022-06-08']), + qm('QM_META_POST', 'META', 'XNAS', ['2022-06-09', '2022-06-09']), + ], + }); + + const byId = new Map(result.providerMappings.map(m => [m.sourceId, m.listingKey])); + expect(byId.get('QM_META_PRE')).toEqual(byId.get('QM_META_POST')); + expect(byId.get('QM_META_PRE')?.primaryIsin).toBe(FB_OLD_ISIN); + expect(byId.has('QM_FB_2015')).toBe(false); + expect(result.unresolved).toEqual([ + { source: 'qm', sourceId: 'QM_FB_2015', reason: 'no_span_overlap', primaryIsin: null }, + ]); + const meta = result.listings.filter(l => l.primaryIsin === FB_OLD_ISIN); + expect(meta).toHaveLength(1); + expect(meta[0]?.ibConid).toBe(107113386); + assertReconciles(result); + }); + + test('accepts ticker root of exactly 24 chars and class suffix of exactly MAX_CLASS_SUFFIX_LENGTH', () => { + const root24 = 'R'.repeat(MAX_TICKER_ROOT_LENGTH); + const suffix12 = 'S'.repeat(MAX_CLASS_SUFFIX_LENGTH); + const result = matchListingsStageB({ + instruments: [instrument('US9999999991', [eodMember('BOUND')])], + eodListings: [eod('BOUND', `${root24}.${suffix12}`, 'XNYS', ['2020-01-02', '2024-12-31'])], + ibContracts: [], + tickerSources: [qm('QM_BOUND', `${root24}-${suffix12}`, 'XNYS', ['2021-01-04', '2021-12-31'])], + }); + + expect(result.unresolved).toEqual([]); + expect(result.listings).toHaveLength(1); + expect(result.listings[0]?.tickerRoot).toBe(root24); + expect(result.listings[0]?.classSuffix).toBe(suffix12); + expect(result.providerMappings.map(m => [m.source, m.method])).toEqual([ + ['eod', 'tier1_isin'], + ['qm', 'tier3_ticker_span'], + ]); + assertReconciles(result); + }); + + test('normalizes lowercase MIC/currency and falls back to member currency when provider currency is absent', () => { + const result = matchListingsStageB({ + instruments: [ + instrument('CA1111111111', [ + eodMember('EOD_CAD', 'CAD'), + eodMember('EOD_USD', 'USD'), + ibMember('IB_CAD', 'CAD'), + ibMember('IB_USD', 'usd'), + ]), + ], + eodListings: [ + { ...eod('EOD_CAD', 'abc', ' xtse ', ['2020-01-02', '2024-12-31']), currency: undefined }, + eod('EOD_USD', 'ABC', 'XNYS', ['2020-01-02', '2024-12-31'], null), + ], + ibContracts: [ + { sourceId: 'IB_CAD', conid: 11, currency: 'cad', primaryExchange: ' tse ' }, + { sourceId: 'IB_USD', conid: 12, currency: null, primaryExchange: null }, + ], + tickerSources: [qm('CEO_ABC', 'abc.to', 'xtse', ['2022-01-03', '2022-01-03'], 'cad', 'ceo')], + }); + + expect(result.unresolved).toEqual([]); + expect(result.conflicts).toEqual([]); + expect( + result.listings.map(l => [l.mic, l.currency, l.tickerRoot, l.ibConid, l.ibPrimaryExchange]) + ).toEqual([ + ['XNYS', 'USD', 'ABC', 12, null], + ['XTSE', 'CAD', 'ABC', 11, 'TSE'], + ]); + expect(result.providerMappings.find(m => m.source === 'ceo')?.listingKey.mic).toBe('XTSE'); + assertReconciles(result); + }); + + test('IB conid attaches only within its own instrument, even when another instrument has a same-currency listing', () => { + const result = matchListingsStageB({ + instruments: [ + instrument('US0000000A01', [eodMember('A_CAD', 'CAD'), ibMember('IB_A_USD', 'USD')]), + instrument('US0000000B02', [eodMember('B_USD', 'USD')]), + ], + eodListings: [ + eod('A_CAD', 'AAA', 'XTSE', null, 'CAD'), + eod('B_USD', 'AAA', 'XNYS', null, 'USD'), + ], + ibContracts: [{ sourceId: 'IB_A_USD', conid: 5, currency: 'USD', primaryExchange: 'NYSE' }], + tickerSources: [], + }); + + expect(result.listings.every(l => l.ibConid === null)).toBe(true); + expect(result.unresolved).toEqual([ + { source: 'ib', sourceId: 'IB_A_USD', reason: 'no_listing_for_currency', primaryIsin: 'US0000000A01' }, + ]); + assertReconciles(result); + }); + + test('two IB members carrying the same conid for one listing still conflict and attach nothing', () => { + const result = matchListingsStageB({ + instruments: [instrument('US0000000C03', [eodMember('C'), ibMember('IB_C1'), ibMember('IB_C2')])], + eodListings: [eod('C', 'CCC', 'XNAS', null)], + ibContracts: [ + { sourceId: 'IB_C1', conid: 77, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'IB_C2', conid: 77, currency: 'USD', primaryExchange: 'NASDAQ' }, + ], + tickerSources: [], + }); + + expect(result.listings[0]?.ibConid).toBeNull(); + expect(result.providerMappings.filter(m => m.source === 'ib')).toEqual([]); + expect(result.conflicts.map(c => [c.sourceId, c.conflictKind, c.detail.competingConids])).toEqual([ + ['IB_C1', 'competing_ib_conid', [77]], + ['IB_C2', 'competing_ib_conid', [77]], + ]); + assertReconciles(result); + }); + + test('ambiguous overlap wins over a same-key listing with missing span; a lone missing-span partner blocks a match', () => { + const base = (extraNullSpan: boolean): StageBInput => ({ + instruments: [ + instrument('US00000000D1', [eodMember('D1')]), + instrument('US00000000D2', [eodMember('D2')]), + instrument('US00000000D3', [eodMember('D3')]), + ], + eodListings: [ + eod('D1', 'DDD', 'XNAS', ['2020-01-02', '2024-12-31']), + extraNullSpan ? eod('D2', 'DDD', 'XNAS', null) : eod('D2', 'DDD', 'XNAS', ['2021-01-04', '2022-12-30']), + eod('D3', 'DDD', 'XNAS', null), + ], + ibContracts: [], + tickerSources: [qm('QM_D', 'DDD', 'XNAS', ['2021-06-01', '2021-06-30'])], + }); + + const ambiguous = matchListingsStageB(base(false)); + expect(ambiguous.conflicts.map(c => [c.sourceId, c.conflictKind])).toEqual([ + ['QM_D', 'ambiguous_ticker_span'], + ]); + expect(ambiguous.conflicts[0]?.detail.candidateListingKeys.map(k => k.primaryIsin)).toEqual([ + 'US00000000D1', + 'US00000000D2', + ]); + + const blocked = matchListingsStageB(base(true)); + expect(blocked.providerMappings.filter(m => m.source === 'qm')).toEqual([]); + expect(blocked.unresolved).toEqual([ + { source: 'qm', sourceId: 'QM_D', reason: 'missing_span', primaryIsin: null }, + ]); + assertReconciles(ambiguous); + assertReconciles(blocked); + }); + + test('same-key EOD members merge spans the same way regardless of order, including a null-span member', () => { + const members = [eodMember('E_NULL'), eodMember('E_EARLY'), eodMember('E_LATE')]; + const listings = [ + eod('E_NULL', 'EEE', 'XNAS', null), + eod('E_EARLY', 'EEE', 'XNAS', ['2010-01-04', '2015-12-31']), + eod('E_LATE', 'EEE', 'XNAS', ['2014-01-02', '2025-11-26']), + ]; + const run = (seed: number): StageBMatchResult => + matchListingsStageB({ + instruments: [instrument('US00000000E1', shuffle(members, seed))], + eodListings: shuffle(listings, seed + 1), + ibContracts: [], + tickerSources: [], + }); + + const baseline = run(1); + expect(baseline.listings).toHaveLength(1); + expect(baseline.listings[0]?.listedFrom).toBe('2010-01-04'); + expect(baseline.listings[0]?.listedTo).toBe('2025-11-26'); + expect(baseline.providerMappings).toHaveLength(3); + for (const seed of [2, 3, 4, 5, 6, 7, 8]) { + expect(run(seed)).toEqual(baseline); + } + }); + + test('qm and ceo records sharing a sourceId are not duplicates; duplicate EOD members across instruments are', () => { + const result = matchListingsStageB({ + instruments: [ + instrument('US00000000F1', [eodMember('SHARED_EOD'), eodMember('F1')]), + instrument('US00000000F2', [eodMember('SHARED_EOD')]), + ], + eodListings: [eod('SHARED_EOD', 'FFF', 'XNAS', null), eod('F1', 'FFG', 'XNAS', ['2020-01-02', '2024-12-31'])], + ibContracts: [], + tickerSources: [ + qm('SAME_ID', 'FFG', 'XNAS', ['2021-01-04', '2021-12-31'], 'USD', 'qm'), + qm('SAME_ID', 'FFG', 'XNAS', ['2021-01-04', '2021-12-31'], 'USD', 'ceo'), + ], + }); + + expect(result.conflicts.map(c => [c.source, c.sourceId, c.detail.primaryIsin])).toEqual([ + ['eod', 'SHARED_EOD', 'US00000000F1'], + ['eod', 'SHARED_EOD', 'US00000000F2'], + ]); + expect(result.listings.map(l => l.tickerRoot)).toEqual(['FFG']); + expect(result.providerMappings.map(m => [m.source, m.sourceId])).toEqual([ + ['ceo', 'SAME_ID'], + ['eod', 'F1'], + ['qm', 'SAME_ID'], + ]); + assertReconciles(result); + }); + + test('does not mutate frozen inputs and returns identical output on repeated calls', () => { + const input = deepFreeze( + reusedFbInput([ + qm('QM_FB_2015', 'FB', 'XNAS', ['2015-01-02', '2015-12-31']), + qm('QM_FB_2023', 'FB', 'XNAS', ['2023-01-03', '2023-12-29']), + ]) + ); + const snapshot = JSON.stringify(input); + const first = matchListingsStageB(input); + const second = matchListingsStageB(input); + expect(second).toEqual(first); + expect(JSON.stringify(input)).toBe(snapshot); + }); + + test('failure-heavy input is invariant to array shuffles and to Map insertion order', () => { + const instruments: StageAInstrumentCandidate[] = [ + instrument('US00000000G1', [ + eodMember('G_OK'), + eodMember('G_COMP'), + eodMember('G_FUND'), + eodMember('G_DUP'), + ibMember('IB_G1'), + ibMember('IB_G2'), + ibMember('IB_G_EUR', 'EUR'), + ]), + instrument('US00000000G2', [eodMember('G_DUP'), eodMember('G_X1'), eodMember('G_X2'), ibMember('IB_GX')]), + ]; + const eodListings: StageBEodListingInput[] = [ + eod('G_OK', 'GGG', 'XNAS', ['2018-01-02', '2024-12-31']), + { ...eod('G_COMP', 'GGG', 'XNAS', null), mic: null, role: 'composite' }, + { ...eod('G_FUND', 'GGGFX', 'XNAS', null), mic: null, role: 'excluded_fund' }, + eod('G_DUP', 'GGH', 'XNAS', null), + eod('G_X1', 'GXX', 'XNAS', ['2019-01-02', '2020-12-31']), + eod('G_X2', 'GXX', 'XNYS', ['2019-01-02', '2020-12-31']), + ]; + const ibContracts: StageBIbContractInput[] = [ + { sourceId: 'IB_G1', conid: 1, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'IB_G2', conid: 2, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'IB_G_EUR', conid: 3, currency: 'EUR', primaryExchange: 'IBIS' }, + { sourceId: 'IB_GX', conid: 4, currency: 'USD', primaryExchange: 'NYSE' }, + ]; + const tickerSources: StageBTickerSourceInput[] = [ + qm('QM_G', 'GGG', 'XNAS', ['2020-01-02', '2020-12-31']), + qm('QM_G', 'GGG', 'XNAS', ['2021-01-04', '2021-12-31']), + qm('QM_GX', 'GXX', 'XNYS', ['2020-01-02', '2020-01-02']), + qm('CEO_NONE', 'ZZZ.V', 'XTSX', ['2020-01-02', '2020-01-02'], 'CAD', 'ceo'), + ]; + + const baseline = matchListingsStageB({ instruments, eodListings, ibContracts, tickerSources }); + assertReconciles(baseline); + expect(baseline.stats.excludedFunds).toBe(1); + expect(baseline.conflicts.map(c => c.conflictKind).sort()).toEqual([ + 'ambiguous_ib_listing', + 'competing_ib_conid', + 'competing_ib_conid', + 'duplicate_source_id', + 'duplicate_source_id', + 'duplicate_source_id', + 'duplicate_source_id', + ]); + const baselineJson = JSON.stringify(baseline); + + for (const seed of [11, 23, 97, 4242, 77777]) { + const shuffledEod = shuffle(eodListings, seed + 1); + const shuffledIb = shuffle(ibContracts, seed + 2); + const arrayResult = matchListingsStageB({ + instruments: shuffle(instruments, seed).map((inst, i) => ({ + ...inst, + members: shuffle(inst.members, seed * 31 + i), + })), + eodListings: shuffledEod, + ibContracts: shuffledIb, + tickerSources: shuffle(tickerSources, seed + 3), + }); + expect(JSON.stringify(arrayResult)).toBe(baselineJson); + + const mapResult = matchListingsStageB({ + instruments, + eodListings: new Map(shuffledEod.map(({ sourceId, ...rest }) => [sourceId, rest])), + ibContracts: new Map(shuffledIb.map(({ sourceId, ...rest }) => [sourceId, rest])), + tickerSources, + }); + expect(JSON.stringify(mapResult)).toBe(baselineJson); + } + }); + + test('rejects invalid options and structurally invalid inputs with errors naming the location', () => { + const empty: StageBInput = { instruments: [], eodListings: [], ibContracts: [], tickerSources: [] }; + expect(() => matchListingsStageB(empty, { spanOverlapToleranceDays: Number.NaN })).toThrow(RangeError); + expect(() => matchListingsStageB(empty, { spanOverlapToleranceDays: Infinity })).toThrow(RangeError); + expect(() => + matchListingsStageB(empty, { spanOverlapToleranceDays: '1' as unknown as number }) + ).toThrow(RangeError); + expect(() => matchListingsStageB(empty, null as unknown as object)).toThrow(TypeError); + expect(matchListingsStageB(empty, { spanOverlapToleranceDays: undefined }).listings).toEqual([]); + expect(() => matchListingsStageB(null as unknown as StageBInput)).toThrow(TypeError); + + expect(() => + matchListingsStageB({ + ...empty, + instruments: [instrument('US0000000001', []), instrument('US0000000001', [])], + }) + ).toThrow(/Duplicate primaryIsin.*instruments\[1\]/); + + expect(() => + matchListingsStageB({ + ...empty, + instruments: [ + instrument('US0000000001', [ + eodMember('A'), + { source: 'yahoo', sourceId: 'B', currency: 'USD', method: 'tier1_isin' } as unknown as Member, + ]), + ], + }) + ).toThrow(/instruments\[0\]\.members\[1\]/); + + expect(() => + matchListingsStageB({ + ...empty, + instruments: [ + instrument('US0000000001', [ + { source: 'eod', sourceId: 'A', currency: 'USD', method: 'tier3_ticker_span' } as unknown as Member, + ]), + ], + }) + ).toThrow(/instruments\[0\]\.members\[0\]/); + + expect(() => + matchListingsStageB({ + ...empty, + instruments: [instrument('US0000000001', [{ ...eodMember('A'), sourceId: 42 as unknown as string }])], + }) + ).toThrow(/instruments\[0\]\.members\[0\]/); + + expect(() => + matchListingsStageB({ + ...empty, + ibContracts: [ + { sourceId: 'ok', conid: 1, primaryExchange: null }, + { sourceId: 7 as unknown as string, conid: 2, primaryExchange: null }, + ], + }) + ).toThrow(/ibContracts\[1\]/); + + expect(() => + matchListingsStageB({ + ...empty, + tickerSources: [{ ...qm('Q', 'A', 'XNAS', null), source: 'ib' as unknown as 'qm' }], + }) + ).toThrow(/tickerSources\[0\]/); + + expect(() => + matchListingsStageB({ + ...empty, + eodListings: [{ ...eod('E', 'A', 'XNAS', null), role: 'otc' as unknown as 'composite' }], + }) + ).toThrow(/eodListings\[0\]/); + + expect(() => + matchListingsStageB({ ...empty, eodListings: {} as unknown as StageBEodListingInput[] }) + ).toThrow(TypeError); + }); +}); diff --git a/test/unit/security-master-listing-stage-b.test.ts b/test/unit/security-master-listing-stage-b.test.ts new file mode 100644 index 00000000..1e8b1709 --- /dev/null +++ b/test/unit/security-master-listing-stage-b.test.ts @@ -0,0 +1,1483 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { + isStageBSource, + matchListingsStageB, + MAX_TICKER_ROOT_LENGTH, + STAGE_B_SOURCES, + type StageAInstrumentCandidate, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBInput, + type StageBMatchResult, + type StageBTickerSourceInput, +} from '../../apps/stock/data-pipeline/src/security-master'; +import { MAX_CLASS_SUFFIX_LENGTH } from '../../apps/stock/data-pipeline/src/normalization/ticker'; + +const stageBSourcePath = fileURLToPath( + new URL( + '../../apps/stock/data-pipeline/src/security-master/listing-stage-b.ts', + import.meta.url + ) +); + +const ALLOWED_METHODS = new Set(['tier1_isin', 'tier2_cusip', 'tier3_ticker_span']); +const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/; +const ISO_CURRENCY_PATTERN = /^[A-Z]{3}$/; + +function assertReconciliationAndContracts(result: StageBMatchResult): void { + expect(result.stats.totalListings).toBe(result.listings.length); + expect(result.stats.totalProviderMappings).toBe(result.providerMappings.length); + + let listingsWithConid = 0; + for (const listing of result.listings) { + expect(ISO_MIC_PATTERN.test(listing.mic)).toBe(true); + expect(ISO_CURRENCY_PATTERN.test(listing.currency)).toBe(true); + expect(listing.tickerRoot.length).toBeGreaterThan(0); + expect(listing.tickerRoot.length).toBeLessThanOrEqual(MAX_TICKER_ROOT_LENGTH); + expect(listing.classSuffix.length).toBeLessThanOrEqual(MAX_CLASS_SUFFIX_LENGTH); + if (listing.ibConid !== null) { + expect(Number.isSafeInteger(listing.ibConid)).toBe(true); + expect(listing.ibConid).toBeGreaterThan(0); + listingsWithConid += 1; + } + } + expect(result.stats.listingsWithIbConid).toBe(listingsWithConid); + + const matchedBySource = { eod: 0, ib: 0, qm: 0, ceo: 0 }; + for (const mapping of result.providerMappings) { + expect(ALLOWED_METHODS.has(mapping.method)).toBe(true); + matchedBySource[mapping.source] += 1; + } + + const unresolvedBySource = { eod: 0, ib: 0, qm: 0, ceo: 0 }; + let excludedFundCount = 0; + for (const row of result.unresolved) { + unresolvedBySource[row.source] += 1; + if (row.reason === 'excluded_fund') { + excludedFundCount += 1; + } + } + expect(result.stats.excludedFunds).toBe(excludedFundCount); + + const conflictBySource = { eod: 0, ib: 0, qm: 0, ceo: 0 }; + for (const row of result.conflicts) { + conflictBySource[row.source] += 1; + } + + for (const source of STAGE_B_SOURCES) { + const s = result.stats.bySource[source]; + expect(s.matched).toBe(matchedBySource[source]); + expect(s.unresolved).toBe(unresolvedBySource[source]); + expect(s.conflict).toBe(conflictBySource[source]); + expect(s.matched + s.unresolved + s.conflict).toBe(s.total); + } +} + +function makeRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function 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; +} + +describe('security master Pass 3 Stage B listing matcher', () => { + test('is exported from security-master barrel and performs zero I/O imports', () => { + expect(typeof matchListingsStageB).toBe('function'); + expect(STAGE_B_SOURCES).toEqual(['eod', 'ib', 'qm', 'ceo']); + expect(MAX_TICKER_ROOT_LENGTH).toBe(24); + expect(isStageBSource('eod')).toBe(true); + expect(isStageBSource('ib')).toBe(true); + expect(isStageBSource('qm')).toBe(true); + expect(isStageBSource('ceo')).toBe(true); + expect(isStageBSource('yahoo')).toBe(false); + + const sourceText = readFileSync(stageBSourcePath, '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('produces 2 listings with matching IB conids for interlisted US+CA instrument and never uses ATS exchangeId as MIC', () => { + const instruments: StageAInstrumentCandidate[] = [ + { + primaryIsin: 'CA82509L1076', + primaryCusip: '82509L107', + issuerCountry: 'CA', + canonicalName: 'Shopify Inc.', + members: [ + { source: 'eod', sourceId: 'SHOP.TO', currency: 'CAD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'SHOP.US', currency: 'USD', method: 'tier2_cusip' }, + { source: 'ib', sourceId: 'ib-shop-cad', currency: 'CAD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-shop-usd', currency: 'USD', method: 'tier2_cusip' }, + ], + }, + ]; + + const eodListings: StageBEodListingInput[] = [ + { + sourceId: 'SHOP.TO', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2015-05-21', lastBarDate: '2025-11-26' }, + }, + { + sourceId: 'SHOP.US', + ticker: 'SHOP', + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2015-05-21', lastBarDate: '2025-11-26' }, + }, + ]; + + // Extra ATS exchangeId fields on raw IB objects must never leak into listing MICs. + const ibContracts: StageBIbContractInput[] = [ + { + sourceId: 'ib-shop-cad', + conid: 194041555, + currency: 'CAD', + primaryExchange: 'tse', + ...({ exchangeId: 'AEQLIT' } as Record), + }, + { + sourceId: 'ib-shop-usd', + conid: 194041552, + currency: 'USD', + primaryExchange: 'nyse', + ...({ exchangeId: 'DRCTEDGE' } as Record), + }, + ]; + + const result = matchListingsStageB({ + instruments, + eodListings, + ibContracts, + tickerSources: [], + }); + + expect(result.unresolved).toEqual([]); + expect(result.conflicts).toEqual([]); + expect(result.listings).toEqual([ + { + primaryIsin: 'CA82509L1076', + mic: 'XNYS', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'USD', + ibConid: 194041552, + ibPrimaryExchange: 'NYSE', + listedFrom: '2015-05-21', + listedTo: '2025-11-26', + }, + { + primaryIsin: 'CA82509L1076', + mic: 'XTSE', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'CAD', + ibConid: 194041555, + ibPrimaryExchange: 'TSE', + listedFrom: '2015-05-21', + listedTo: '2025-11-26', + }, + ]); + + const mics = new Set(result.listings.map(l => l.mic)); + expect(mics.has('AEQLIT')).toBe(false); + expect(mics.has('DRCTEDGE')).toBe(false); + + expect(result.providerMappings).toEqual([ + { + source: 'eod', + sourceId: 'SHOP.TO', + listingKey: { + primaryIsin: 'CA82509L1076', + mic: 'XTSE', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'CAD', + }, + method: 'tier1_isin', + validFrom: '2015-05-21', + validTo: '2025-11-26', + }, + { + source: 'eod', + sourceId: 'SHOP.US', + listingKey: { + primaryIsin: 'CA82509L1076', + mic: 'XNYS', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'USD', + }, + method: 'tier2_cusip', + validFrom: '2015-05-21', + validTo: '2025-11-26', + }, + { + source: 'ib', + sourceId: 'ib-shop-cad', + listingKey: { + primaryIsin: 'CA82509L1076', + mic: 'XTSE', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'CAD', + }, + method: 'tier1_isin', + validFrom: null, + validTo: null, + }, + { + source: 'ib', + sourceId: 'ib-shop-usd', + listingKey: { + primaryIsin: 'CA82509L1076', + mic: 'XNYS', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'USD', + }, + method: 'tier2_cusip', + validFrom: null, + validTo: null, + }, + ]); + assertReconciliationAndContracts(result); + }); + + test('disambiguates reused ticker FB on XNAS USD by span overlap and quarantines cross-span overlap', () => { + const instruments: StageAInstrumentCandidate[] = [ + { + primaryIsin: 'US30303M1027', + primaryCusip: '30303M102', + issuerCountry: 'US', + canonicalName: 'Facebook Inc.', + members: [{ source: 'eod', sourceId: 'FB_META.US', currency: 'USD', method: 'tier1_isin' }], + }, + { + primaryIsin: 'US0000000026', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'FB Financial Reused Ticker', + members: [{ source: 'eod', sourceId: 'FB_NEW.US', currency: 'USD', method: 'tier1_isin' }], + }, + ]; + + const eodListings: StageBEodListingInput[] = [ + { + sourceId: 'FB_META.US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2012-05-18', lastBarDate: '2022-06-08' }, + }, + { + sourceId: 'FB_NEW.US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2025-01-02', lastBarDate: '2025-11-26' }, + }, + ]; + + const tickerSources: StageBTickerSourceInput[] = [ + { + source: 'qm', + sourceId: 'QM_FB_2015', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2015-01-02', lastBarDate: '2015-12-31' }, + }, + { + source: 'qm', + sourceId: 'QM_FB_2025', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2025-02-03', lastBarDate: '2025-10-31' }, + }, + { + source: 'qm', + sourceId: 'QM_FB_2023', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2023-01-03', lastBarDate: '2023-12-29' }, + }, + { + source: 'qm', + sourceId: 'QM_FB_BOTH', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-06-01' }, + }, + ]; + + const result = matchListingsStageB({ + instruments, + eodListings, + ibContracts: [], + tickerSources, + }); + + expect(result.listings).toHaveLength(2); + const qmMappings = result.providerMappings.filter(m => m.source === 'qm'); + expect(qmMappings).toEqual([ + { + source: 'qm', + sourceId: 'QM_FB_2015', + listingKey: { + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }, + method: 'tier3_ticker_span', + validFrom: '2015-01-02', + validTo: '2015-12-31', + }, + { + source: 'qm', + sourceId: 'QM_FB_2025', + listingKey: { + primaryIsin: 'US0000000026', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }, + method: 'tier3_ticker_span', + validFrom: '2025-02-03', + validTo: '2025-10-31', + }, + ]); + + expect(result.unresolved).toEqual([ + { + source: 'qm', + sourceId: 'QM_FB_2023', + reason: 'no_span_overlap', + primaryIsin: null, + }, + ]); + + expect(result.conflicts).toEqual([ + { + source: 'qm', + sourceId: 'QM_FB_BOTH', + conflictKind: 'ambiguous_ticker_span', + detail: { + primaryIsin: null, + currency: 'USD', + ibConid: null, + competingConids: [], + candidateListingKeys: [ + { + primaryIsin: 'US0000000026', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }, + { + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }, + ], + }, + }, + ]); + assertReconciliationAndContracts(result); + }); + + test('normalizes CEO .TO/.V suffixes and QM/EOD class-share separators identically', () => { + const result = matchListingsStageB({ + instruments: [ + { + primaryIsin: 'CA0977512007', + primaryCusip: '097751200', + issuerCountry: 'CA', + canonicalName: 'Bombardier Inc. Class B', + members: [{ source: 'eod', sourceId: 'BBD-B.TO', currency: 'CAD', method: 'tier1_isin' }], + }, + { + primaryIsin: 'US0846707026', + primaryCusip: '084670702', + issuerCountry: 'US', + canonicalName: 'Berkshire Hathaway Class B', + members: [{ source: 'eod', sourceId: 'BRK-B.US', currency: 'USD', method: 'tier1_isin' }], + }, + ], + eodListings: [ + { + sourceId: 'BBD-B.TO', + ticker: 'BBD-B', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2010-01-04', lastBarDate: '2025-11-26' }, + }, + { + sourceId: 'BRK-B.US', + ticker: 'BRK-B', + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2010-01-04', lastBarDate: '2025-11-26' }, + }, + ], + ibContracts: [], + tickerSources: [ + { + source: 'ceo', + sourceId: 'ceo-bbd-b', + ticker: 'BBD.B.TO', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'qm', + sourceId: 'qm-brk-b', + ticker: 'BRK.B', + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2021-01-04', lastBarDate: '2024-12-31' }, + }, + ], + }); + + expect(result.unresolved).toEqual([]); + expect(result.conflicts).toEqual([]); + expect(result.providerMappings.filter(m => m.method === 'tier3_ticker_span')).toEqual([ + { + source: 'ceo', + sourceId: 'ceo-bbd-b', + listingKey: { + primaryIsin: 'CA0977512007', + mic: 'XTSE', + tickerRoot: 'BBD', + classSuffix: 'B', + currency: 'CAD', + }, + method: 'tier3_ticker_span', + validFrom: '2020-01-02', + validTo: '2024-12-31', + }, + { + source: 'qm', + sourceId: 'qm-brk-b', + listingKey: { + primaryIsin: 'US0846707026', + mic: 'XNYS', + tickerRoot: 'BRK', + classSuffix: 'B', + currency: 'USD', + }, + method: 'tier3_ticker_span', + validFrom: '2021-01-04', + validTo: '2024-12-31', + }, + ]); + assertReconciliationAndContracts(result); + }); + + test('routes non-primary, excluded-fund, null/invalid MIC venues to distinct unresolved reasons', () => { + const result = matchListingsStageB({ + instruments: [ + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Venue Test Corp', + members: [ + { source: 'eod', sourceId: 'EOD_COMP', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_ATS', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_FX', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_FUND', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_NULL_MIC', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_NULL_ROLE', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_BAD_MIC', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_MISSING_META', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ], + eodListings: [ + { sourceId: 'EOD_COMP', ticker: 'AAPL', mic: null, role: 'composite', currency: 'USD', span: null }, + { sourceId: 'EOD_ATS', ticker: 'AAPL', mic: null, role: 'ats_routing', currency: 'USD', span: null }, + { sourceId: 'EOD_FX', ticker: 'USDCAD', mic: null, role: 'forex', currency: 'USD', span: null }, + { sourceId: 'EOD_FUND', ticker: 'VFIAX', mic: null, role: 'excluded_fund', currency: 'USD', span: null }, + { sourceId: 'EOD_NULL_MIC', ticker: 'AAPL', mic: null, role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'EOD_NULL_ROLE', ticker: 'AAPL', mic: 'XNAS', role: null, currency: 'USD', span: null }, + { sourceId: 'EOD_BAD_MIC', ticker: 'AAPL', mic: 'NASDAQ', role: 'primary_venue', currency: 'USD', span: null }, + ], + ibContracts: [], + tickerSources: [ + { + source: 'qm', + sourceId: 'QM_FUND', + ticker: 'VFIAX', + mic: null, + role: 'excluded_fund', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'ceo', + sourceId: 'CEO_ATS', + ticker: 'SHOP.TO', + mic: null, + role: 'ats_routing', + currency: 'CAD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + ], + }); + + expect(result.listings).toEqual([]); + expect(result.providerMappings).toEqual([]); + expect(result.conflicts).toEqual([]); + expect(result.stats.excludedFunds).toBe(2); + expect(result.unresolved).toEqual([ + { source: 'ceo', sourceId: 'CEO_ATS', reason: 'ats_routing_venue', primaryIsin: null }, + { source: 'eod', sourceId: 'EOD_ATS', reason: 'ats_routing_venue', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_BAD_MIC', reason: 'invalid_mic', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_COMP', reason: 'composite_venue', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_FUND', reason: 'excluded_fund', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_FX', reason: 'forex_venue', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_MISSING_META', reason: 'missing_eod_listing', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_NULL_MIC', reason: 'missing_mic', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_NULL_ROLE', reason: 'missing_mic', primaryIsin: 'US0378331005' }, + { source: 'qm', sourceId: 'QM_FUND', reason: 'excluded_fund', primaryIsin: null }, + ]); + assertReconciliationAndContracts(result); + }); + + test('handles IB failure modes and quarantines ambiguous_ib_listing and competing_ib_conid without attaching', () => { + const result = matchListingsStageB({ + instruments: [ + // Instrument 1: single USD listing, 2 competing IB conids -> neither attached + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Competing Conid Corp', + members: [ + { source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-aapl-1', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-aapl-2', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-aapl-eur', currency: 'EUR', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-aapl-missing', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-aapl-badconid', currency: 'USD', method: 'tier1_isin' }, + ], + }, + // Instrument 2: 2 USD listings -> ambiguous_ib_listing, nothing attached + { + primaryIsin: 'US5949181045', + primaryCusip: '594918104', + issuerCountry: 'US', + canonicalName: 'Ambiguous USD Listings Corp', + members: [ + { source: 'eod', sourceId: 'MSFT_XNAS', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'MSFT_XNYS', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-msft', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ], + eodListings: [ + { sourceId: 'AAPL.US', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'MSFT_XNAS', ticker: 'MSFT', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'MSFT_XNYS', ticker: 'MSFT', mic: 'XNYS', role: 'primary_venue', currency: 'USD', span: null }, + ], + ibContracts: [ + { sourceId: 'ib-aapl-1', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'ib-aapl-2', conid: 999999, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'ib-aapl-eur', conid: 38708077, currency: 'EUR', primaryExchange: 'IBIS' }, + { sourceId: 'ib-aapl-badconid', conid: 0, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'ib-msft', conid: 272093, currency: 'USD', primaryExchange: 'NASDAQ' }, + ], + tickerSources: [], + }); + + // No listing should have an ibConid attached. + for (const listing of result.listings) { + expect(listing.ibConid).toBeNull(); + expect(listing.ibPrimaryExchange).toBeNull(); + } + expect(result.stats.listingsWithIbConid).toBe(0); + + expect(result.unresolved).toEqual([ + { source: 'ib', sourceId: 'ib-aapl-badconid', reason: 'invalid_ib_conid', primaryIsin: 'US0378331005' }, + { source: 'ib', sourceId: 'ib-aapl-eur', reason: 'no_listing_for_currency', primaryIsin: 'US0378331005' }, + { source: 'ib', sourceId: 'ib-aapl-missing', reason: 'missing_ib_contract', primaryIsin: 'US0378331005' }, + ]); + + expect(result.conflicts).toEqual([ + { + source: 'ib', + sourceId: 'ib-aapl-1', + conflictKind: 'competing_ib_conid', + detail: { + primaryIsin: 'US0378331005', + currency: 'USD', + ibConid: 265598, + competingConids: [265598, 999999], + candidateListingKeys: [ + { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }, + ], + }, + }, + { + source: 'ib', + sourceId: 'ib-aapl-2', + conflictKind: 'competing_ib_conid', + detail: { + primaryIsin: 'US0378331005', + currency: 'USD', + ibConid: 999999, + competingConids: [265598, 999999], + candidateListingKeys: [ + { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }, + ], + }, + }, + { + source: 'ib', + sourceId: 'ib-msft', + conflictKind: 'ambiguous_ib_listing', + detail: { + primaryIsin: 'US5949181045', + currency: 'USD', + ibConid: 272093, + competingConids: [], + candidateListingKeys: [ + { + primaryIsin: 'US5949181045', + mic: 'XNAS', + tickerRoot: 'MSFT', + classSuffix: '', + currency: 'USD', + }, + { + primaryIsin: 'US5949181045', + mic: 'XNYS', + tickerRoot: 'MSFT', + classSuffix: '', + currency: 'USD', + }, + ], + }, + }, + ]); + assertReconciliationAndContracts(result); + }); + + test('enforces span edge cases (missing span on either side, invalid span, and toleranceDays)', () => { + const baseInput: StageBInput = { + instruments: [ + { + primaryIsin: 'US1111111111', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'Null Span Listing', + members: [{ source: 'eod', sourceId: 'NULLSPAN.US', currency: 'USD', method: 'tier1_isin' }], + }, + { + primaryIsin: 'US2222222222', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'Overlap Plus Null Span Partner', + members: [{ source: 'eod', sourceId: 'MIXED_KNOWN.US', currency: 'USD', method: 'tier1_isin' }], + }, + { + primaryIsin: 'US3333333333', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'Mixed Null Span Partner', + members: [{ source: 'eod', sourceId: 'MIXED_NULL.US', currency: 'USD', method: 'tier1_isin' }], + }, + { + primaryIsin: 'US4444444444', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'Adjacent Tolerance Listing', + members: [ + { source: 'eod', sourceId: 'ADJ.US', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'BADSPAN.US', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ], + eodListings: [ + { sourceId: 'NULLSPAN.US', ticker: 'NSPN', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { + sourceId: 'MIXED_KNOWN.US', + ticker: 'MIXD', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + { sourceId: 'MIXED_NULL.US', ticker: 'MIXD', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { + sourceId: 'ADJ.US', + ticker: 'ADJC', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2020-06-30' }, + }, + { + sourceId: 'BADSPAN.US', + ticker: 'BDSP', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2024-06-01', lastBarDate: '2024-01-01' }, + }, + ], + ibContracts: [], + tickerSources: [ + { source: 'qm', sourceId: 'QM_NULL_REC_SPAN', ticker: 'ADJC', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { + source: 'qm', + sourceId: 'QM_NULL_LISTING_SPAN', + ticker: 'NSPN', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2020-12-31' }, + }, + { + source: 'qm', + sourceId: 'QM_MIXED_NULL_PARTNER', + ticker: 'MIXD', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2021-01-04', lastBarDate: '2022-12-30' }, + }, + { + source: 'qm', + sourceId: 'QM_INVALID_DATE', + ticker: 'ADJC', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2023-02-29', lastBarDate: '2023-03-05' }, + }, + { + source: 'qm', + sourceId: 'QM_ADJACENT', + ticker: 'ADJC', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-07-02', lastBarDate: '2020-12-31' }, + }, + ], + }; + + const strict = matchListingsStageB(baseInput); + expect(strict.unresolved).toEqual([ + { source: 'eod', sourceId: 'BADSPAN.US', reason: 'invalid_span', primaryIsin: 'US4444444444' }, + { source: 'qm', sourceId: 'QM_ADJACENT', reason: 'no_span_overlap', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_INVALID_DATE', reason: 'invalid_span', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_MIXED_NULL_PARTNER', reason: 'missing_span', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_NULL_LISTING_SPAN', reason: 'missing_span', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_NULL_REC_SPAN', reason: 'missing_span', primaryIsin: null }, + ]); + assertReconciliationAndContracts(strict); + + const tolerant = matchListingsStageB(baseInput, { spanOverlapToleranceDays: 2 }); + expect(tolerant.providerMappings.filter(m => m.sourceId === 'QM_ADJACENT')).toHaveLength(1); + assertReconciliationAndContracts(tolerant); + + expect(() => matchListingsStageB(baseInput, { spanOverlapToleranceDays: -1 })).toThrow(RangeError); + expect(() => matchListingsStageB(baseInput, { spanOverlapToleranceDays: 1.5 })).toThrow(RangeError); + }); + + test('rejects timestamp-shaped and padded spans as invalid_span instead of shifting across UTC day boundaries', () => { + const result = matchListingsStageB({ + instruments: [ + { + primaryIsin: 'US0000000026', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'FB Reused Listing', + members: [ + { source: 'eod', sourceId: 'FB_NEW.US', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'FB_TS_EOD.US', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ], + eodListings: [ + { + sourceId: 'FB_NEW.US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2025-01-02', lastBarDate: '2025-11-26' }, + }, + { + sourceId: 'FB_TS_EOD.US', + ticker: 'FBTS', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { + firstBarDate: '2025-01-01T23:30:00-05:00', + lastBarDate: '2025-01-02T00:00:00Z', + }, + }, + ], + ibContracts: [], + tickerSources: [ + // Timezone offset would shift 2025-01-01T23:30:00-05:00 -> 2025-01-02 UTC and falsely match FB_NEW.US. + { + source: 'qm', + sourceId: 'QM_TZ_SHIFT', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { + firstBarDate: '2025-01-01T23:30:00-05:00', + lastBarDate: '2025-01-01T23:30:00-05:00', + }, + }, + { + source: 'qm', + sourceId: 'QM_UTC_TS', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { + firstBarDate: '2025-01-02T00:00:00Z', + lastBarDate: '2025-01-02T00:00:00Z', + }, + }, + { + source: 'qm', + sourceId: 'QM_PADDED_YMD', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { + firstBarDate: ' 2025-01-02 ', + lastBarDate: '2025-01-03', + }, + }, + ], + }); + + expect(result.listings).toHaveLength(1); + expect(result.providerMappings.filter(m => m.source === 'qm')).toEqual([]); + expect(result.unresolved).toEqual([ + { source: 'eod', sourceId: 'FB_TS_EOD.US', reason: 'invalid_span', primaryIsin: 'US0000000026' }, + { source: 'qm', sourceId: 'QM_PADDED_YMD', reason: 'invalid_span', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_TZ_SHIFT', reason: 'invalid_span', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_UTC_TS', reason: 'invalid_span', primaryIsin: null }, + ]); + assertReconciliationAndContracts(result); + }); + + test('enforces ticker/classSuffix/currency bounds and does not mask explicitly invalid eod.currency', () => { + const root25 = 'A'.repeat(MAX_TICKER_ROOT_LENGTH + 1); + const suffix13 = 'B'.repeat(MAX_CLASS_SUFFIX_LENGTH + 1); + + const result = matchListingsStageB({ + instruments: [ + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Bounds Corp', + members: [ + { source: 'eod', sourceId: 'LONG_ROOT', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'LONG_SUFFIX', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'BAD_TICKER', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EMPTY_CCY_MASK', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'BAD_CCY_DIGITS', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'BAD_CCY_LEN', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ], + eodListings: [ + { sourceId: 'LONG_ROOT', ticker: root25, mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'LONG_SUFFIX', ticker: `AAPL.${suffix13}`, mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'BAD_TICKER', ticker: 'BRK..B', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'EMPTY_CCY_MASK', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: '', span: null }, + { sourceId: 'BAD_CCY_DIGITS', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: '123', span: null }, + { sourceId: 'BAD_CCY_LEN', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USDD', span: null }, + ], + ibContracts: [], + tickerSources: [ + { + source: 'qm', + sourceId: 'QM_LONG_SUFFIX', + ticker: `BRK-${suffix13}`, + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'ceo', + sourceId: 'CEO_LONG_ROOT', + ticker: `${root25}.TO`, + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'qm', + sourceId: 'QM_SHORT_CCY', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'US', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + ], + }); + + expect(result.listings).toEqual([]); + expect(result.unresolved).toEqual([ + { source: 'ceo', sourceId: 'CEO_LONG_ROOT', reason: 'ticker_root_too_long', primaryIsin: null }, + { source: 'eod', sourceId: 'BAD_CCY_DIGITS', reason: 'invalid_currency', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'BAD_CCY_LEN', reason: 'invalid_currency', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'BAD_TICKER', reason: 'invalid_ticker', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EMPTY_CCY_MASK', reason: 'invalid_currency', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'LONG_ROOT', reason: 'ticker_root_too_long', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'LONG_SUFFIX', reason: 'class_suffix_too_long', primaryIsin: 'US0378331005' }, + { source: 'qm', sourceId: 'QM_LONG_SUFFIX', reason: 'class_suffix_too_long', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_SHORT_CCY', reason: 'invalid_currency', primaryIsin: null }, + ]); + assertReconciliationAndContracts(result); + }); + + test('quarantines duplicate (source, sourceId) across all inputs and throws on sparse slots or invalid IDs', () => { + const dupResult = matchListingsStageB({ + instruments: [ + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Dup Corp', + members: [ + { source: 'eod', sourceId: 'DUP_EOD_MEM', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'DUP_EOD_MEM', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'DUP_EOD_META', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'DUP_IB_MEM', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'DUP_IB_MEM', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ], + eodListings: [ + { sourceId: 'DUP_EOD_MEM', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'DUP_EOD_META', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'DUP_EOD_META', ticker: 'AAPL', mic: 'XNYS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'ORPHAN_EOD_DUP', ticker: 'ORPH', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'ORPHAN_EOD_DUP', ticker: 'ORPH', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + ], + ibContracts: [ + { sourceId: 'DUP_IB_MEM', conid: 100, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'ORPHAN_IB_DUP', conid: 200, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'ORPHAN_IB_DUP', conid: 201, currency: 'USD', primaryExchange: 'NASDAQ' }, + ], + tickerSources: [ + { + source: 'qm', + sourceId: 'DUP_QM', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'qm', + sourceId: 'DUP_QM', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2021-01-02', lastBarDate: '2024-12-31' }, + }, + ], + }); + + expect(dupResult.listings).toEqual([]); + expect(dupResult.providerMappings).toEqual([]); + expect(dupResult.conflicts.every(c => c.conflictKind === 'duplicate_source_id')).toBe(true); + expect(dupResult.conflicts).toHaveLength(9); + assertReconciliationAndContracts(dupResult); + + // Sparse array slots throw naming the index. + const sparseInstruments = new Array(2) as unknown as StageAInstrumentCandidate[]; + sparseInstruments[1] = { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: null, + members: [], + }; + expect(() => + matchListingsStageB({ + instruments: sparseInstruments, + eodListings: [], + ibContracts: [], + tickerSources: [], + }) + ).toThrow(/instruments\[0\]/); + + const sparseMembers = new Array(2) as unknown as StageAInstrumentCandidate['members']; + sparseMembers[1] = { source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }; + expect(() => + matchListingsStageB({ + instruments: [ + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: null, + members: sparseMembers, + }, + ], + eodListings: [], + ibContracts: [], + tickerSources: [], + }) + ).toThrow(/instruments\[0\]\.members\[0\]/); + + const sparseEod = new Array(2) as unknown as StageBEodListingInput[]; + sparseEod[0] = { sourceId: 'A', ticker: 'A', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }; + expect(() => + matchListingsStageB({ + instruments: [], + eodListings: sparseEod, + ibContracts: [], + tickerSources: [], + }) + ).toThrow(/eodListings\[1\]/); + + const sparseIb = new Array(2) as unknown as StageBIbContractInput[]; + sparseIb[0] = { sourceId: '1', conid: 1, currency: 'USD', primaryExchange: null }; + expect(() => + matchListingsStageB({ + instruments: [], + eodListings: [], + ibContracts: sparseIb, + tickerSources: [], + }) + ).toThrow(/ibContracts\[1\]/); + + const sparseTickers = new Array(2) as unknown as StageBTickerSourceInput[]; + sparseTickers[0] = { + source: 'qm', + sourceId: 'Q1', + ticker: 'A', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }; + expect(() => + matchListingsStageB({ + instruments: [], + eodListings: [], + ibContracts: [], + tickerSources: sparseTickers, + }) + ).toThrow(/tickerSources\[1\]/); + + // Non-string / empty IDs throw naming the index. + expect(() => + matchListingsStageB({ + instruments: [ + { + primaryIsin: '', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: null, + members: [], + }, + ], + eodListings: [], + ibContracts: [], + tickerSources: [], + }) + ).toThrow(/instruments\[0\]/); + + expect(() => + matchListingsStageB({ + instruments: [], + eodListings: [ + { sourceId: '', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + ], + ibContracts: [], + tickerSources: [], + }) + ).toThrow(/eodListings\[0\]/); + }); + + test('is invariant to shuffling every input array and matches ReadonlyMap inputs identically', () => { + const instruments: StageAInstrumentCandidate[] = [ + { + primaryIsin: 'CA82509L1076', + primaryCusip: '82509L107', + issuerCountry: 'CA', + canonicalName: 'Shopify Inc.', + members: [ + { source: 'eod', sourceId: 'SHOP.TO', currency: 'CAD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'SHOP.TO.ALT', currency: 'CAD', method: 'tier2_cusip' }, + { source: 'eod', sourceId: 'SHOP.US', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-shop-cad', currency: 'CAD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-shop-usd', currency: 'USD', method: 'tier1_isin' }, + ], + }, + { + primaryIsin: 'US30303M1027', + primaryCusip: '30303M102', + issuerCountry: 'US', + canonicalName: 'Facebook Inc.', + members: [ + { source: 'eod', sourceId: 'FB_OLD', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-fb-1', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-fb-2', currency: 'USD', method: 'tier1_isin' }, + ], + }, + { + primaryIsin: 'US0000000026', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'FB New', + members: [{ source: 'eod', sourceId: 'FB_NEW', currency: 'USD', method: 'tier1_isin' }], + }, + ]; + + const eodListings: StageBEodListingInput[] = [ + { + sourceId: 'SHOP.TO', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2015-05-21', lastBarDate: '2022-12-31' }, + }, + { + sourceId: 'SHOP.TO.ALT', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-11-26' }, + }, + { + sourceId: 'SHOP.US', + ticker: 'SHOP', + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2015-05-21', lastBarDate: '2025-11-26' }, + }, + { + sourceId: 'FB_OLD', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2012-05-18', lastBarDate: '2022-06-08' }, + }, + { + sourceId: 'FB_NEW', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2025-01-02', lastBarDate: '2025-11-26' }, + }, + ]; + + const ibContracts: StageBIbContractInput[] = [ + { sourceId: 'ib-shop-cad', conid: 194041555, currency: 'CAD', primaryExchange: 'TSE' }, + { sourceId: 'ib-shop-usd', conid: 194041552, currency: 'USD', primaryExchange: 'NYSE' }, + { sourceId: 'ib-fb-1', conid: 107113386, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'ib-fb-2', conid: 999113386, currency: 'USD', primaryExchange: 'NASDAQ' }, + ]; + + const tickerSources: StageBTickerSourceInput[] = [ + { + source: 'ceo', + sourceId: 'ceo-shop', + ticker: 'SHOP.TO', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2018-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'qm', + sourceId: 'qm-fb-old', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2016-01-04', lastBarDate: '2017-12-29' }, + }, + { + source: 'qm', + sourceId: 'qm-fb-both', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-06-01' }, + }, + { + source: 'qm', + sourceId: 'qm-fb-gap', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2023-01-03', lastBarDate: '2023-12-29' }, + }, + ]; + + const baseline = matchListingsStageB({ + instruments, + eodListings, + ibContracts, + tickerSources, + }); + const baselineJson = JSON.stringify(baseline); + assertReconciliationAndContracts(baseline); + + // Same-natural-key EOD members widened listedFrom/listedTo to [2015-05-21, 2025-11-26]. + const shopCad = baseline.listings.find(l => l.mic === 'XTSE' && l.tickerRoot === 'SHOP'); + expect(shopCad?.listedFrom).toBe('2015-05-21'); + expect(shopCad?.listedTo).toBe('2025-11-26'); + + // ReadonlyMap inputs match array inputs byte-for-byte. + const eodMap = new Map(eodListings.map(({ sourceId, ...rest }) => [sourceId, rest])); + const ibMap = new Map(ibContracts.map(({ sourceId, ...rest }) => [sourceId, rest])); + const mapResult = matchListingsStageB({ + instruments, + eodListings: eodMap, + ibContracts: ibMap, + tickerSources, + }); + expect(JSON.stringify(mapResult)).toBe(baselineJson); + + // Shuffling every input array (including inner members) yields byte-identical output. + for (const seed of [7, 42, 1337, 202611]) { + const shuffledInstruments = shuffleWithSeed(instruments, seed).map((inst, idx) => ({ + ...inst, + members: shuffleWithSeed(inst.members, seed + idx + 100), + })); + const shuffledResult = matchListingsStageB({ + instruments: shuffledInstruments, + eodListings: shuffleWithSeed(eodListings, seed + 1), + ibContracts: shuffleWithSeed(ibContracts, seed + 2), + tickerSources: shuffleWithSeed(tickerSources, seed + 3), + }); + expect(JSON.stringify(shuffledResult)).toBe(baselineJson); + assertReconciliationAndContracts(shuffledResult); + } + }); + + test('local scale benchmark: ~20k instruments, ~60k EOD, ~18k IB, ~40k QM/CEO complete under 5000 ms', () => { + const NUM_INSTRUMENTS = 20_000; + const instruments: StageAInstrumentCandidate[] = new Array( + NUM_INSTRUMENTS + ); + const eodListings: StageBEodListingInput[] = []; + const ibContracts: StageBIbContractInput[] = []; + const tickerSources: StageBTickerSourceInput[] = []; + + for (let i = 0; i < NUM_INSTRUMENTS; i++) { + const isCa = (i & 1) === 1; + const isin = `${isCa ? 'CA' : 'US'}${String(1000000000 + i)}`; + const ticker = `T${i}`; + const members: StageAInstrumentCandidate['members'] = []; + + // 3 EOD members per instrument = 60,000 EOD records (2 primary venues + 1 composite/fund). + const eodPrimary1 = `EOD1_${i}`; + const eodPrimary2 = `EOD2_${i}`; + const eodNonPrimary = `EOD3_${i}`; + members.push( + { source: 'eod', sourceId: eodPrimary1, currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: eodPrimary2, currency: 'CAD', method: 'tier2_cusip' }, + { source: 'eod', sourceId: eodNonPrimary, currency: 'USD', method: 'tier1_isin' } + ); + eodListings.push( + { + sourceId: eodPrimary1, + ticker, + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2015-01-02', lastBarDate: '2025-11-26' }, + }, + { + sourceId: eodPrimary2, + ticker, + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2015-01-02', lastBarDate: '2025-11-26' }, + }, + { + sourceId: eodNonPrimary, + ticker, + mic: null, + role: i % 10 === 0 ? 'excluded_fund' : 'composite', + currency: 'USD', + span: null, + } + ); + + // 18,000 IB members (90% of instruments). + if (i < 18_000) { + const ibId = `IB_${i}`; + const ibCcy = isCa ? 'CAD' : 'USD'; + members.push({ source: 'ib', sourceId: ibId, currency: ibCcy, method: 'tier1_isin' }); + ibContracts.push({ + sourceId: ibId, + conid: 100_000 + i, + currency: ibCcy, + primaryExchange: isCa ? 'TSE' : 'NASDAQ', + }); + } + + instruments[i] = { + primaryIsin: isin, + primaryCusip: null, + issuerCountry: isCa ? 'CA' : 'US', + canonicalName: `Issuer ${i}`, + members, + }; + + // 40,000 QM + CEO records (20k QM USD + 20k CEO CAD). + tickerSources.push( + { + source: 'qm', + sourceId: `QM_${i}`, + ticker, + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2018-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'ceo', + sourceId: `CEO_${i}`, + ticker: `${ticker}.TO`, + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2019-01-02', lastBarDate: '2025-06-30' }, + } + ); + } + + const startMs = performance.now(); + const result = matchListingsStageB({ + instruments, + eodListings, + ibContracts, + tickerSources, + }); + const elapsedMs = performance.now() - startMs; + + process.stdout.write( + `[benchmark] matchListingsStageB(${NUM_INSTRUMENTS} instruments, ${eodListings.length} EOD, ${ibContracts.length} IB, ${tickerSources.length} QM+CEO): ${elapsedMs.toFixed(1)} ms (${result.stats.totalListings} listings, ${result.stats.totalProviderMappings} mappings)\n` + ); + + expect(elapsedMs).toBeLessThan(5000); + expect(result.stats.totalListings).toBe(40_000); + expect(result.stats.listingsWithIbConid).toBe(18_000); + expect(result.stats.excludedFunds).toBe(2_000); + expect(result.stats.bySource.eod.total).toBe(60_000); + expect(result.stats.bySource.eod.matched).toBe(40_000); + expect(result.stats.bySource.eod.unresolved).toBe(20_000); + expect(result.stats.bySource.ib.total).toBe(18_000); + expect(result.stats.bySource.ib.matched).toBe(18_000); + expect(result.stats.bySource.qm.matched).toBe(20_000); + expect(result.stats.bySource.ceo.matched).toBe(20_000); + assertReconciliationAndContracts(result); + }); +});