From 895a49e7add654df0ea364e59992a47ba456665c Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 16:03:50 -0500 Subject: [PATCH] =?UTF-8?q?T-50:=20M1.1e=20=E2=80=94=20Pass=203=20Stage=20?= =?UTF-8?q?A:=20pure=20in-memory=20instrument=20matcher=20(global=20ISIN?= =?UTF-8?q?=20/=20CUSIP-derived=20ISIN,=20IB=20=E2=86=94=20EOD)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/security-master/index.ts | 19 + .../src/security-master/instrument-stage-a.ts | 355 +++++++++ ...security-master-instrument-stage-a.test.ts | 697 ++++++++++++++++++ 3 files changed, 1071 insertions(+) create mode 100644 apps/stock/data-pipeline/src/security-master/instrument-stage-a.ts create mode 100644 test/unit/security-master-instrument-stage-a.test.ts diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 1a40e633..1b1b9d26 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -39,3 +39,22 @@ export { type ParsedGenerateExchangeSeedArgs, type ReadOnlyExchangeMongoClient, } from './generate-exchange-seed'; + +export { + isStageASource, + matchInstrumentsStageA, + STAGE_A_SOURCES, + type MatchInstrumentsStageAOptions, + type StageAConflictDetail, + type StageAConflictKind, + type StageAConflictRecord, + type StageAInstrumentCandidate, + type StageAInstrumentMember, + type StageAMatchMethod, + type StageAMatchResult, + type StageASource, + type StageASourceRecord, + type StageASourceStats, + type StageAStats, + type StageAUnresolvedRecord, +} from './instrument-stage-a'; diff --git a/apps/stock/data-pipeline/src/security-master/instrument-stage-a.ts b/apps/stock/data-pipeline/src/security-master/instrument-stage-a.ts new file mode 100644 index 00000000..c667bb54 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/instrument-stage-a.ts @@ -0,0 +1,355 @@ +import { + cusipToIsin, + isValidCusip, + resolveIsin, + type NorthAmericaCountry, + type ResolveIsinRejectionReason, +} from '../normalization/identifiers'; +import { compareAscii } from './exchange-pass1'; + +export const STAGE_A_SOURCES = ['ib', 'eod'] as const; + +export type StageASource = (typeof STAGE_A_SOURCES)[number]; + +export type StageAMatchMethod = 'tier1_isin' | 'tier2_cusip'; + +export type StageAConflictKind = 'isin_cusip_mismatch' | 'duplicate_source_id'; + +export interface StageASourceRecord { + source: StageASource; + sourceId: string; + isin?: string | null; + cusip?: string | null; + country?: string | null; + currency?: string | null; + name?: string | null; +} + +export interface StageAInstrumentMember { + source: StageASource; + sourceId: string; + currency: string | null; + method: StageAMatchMethod; +} + +export interface StageAInstrumentCandidate { + primaryIsin: string; + primaryCusip: string | null; + issuerCountry: string; + canonicalName: string | null; + members: StageAInstrumentMember[]; +} + +export interface StageAUnresolvedRecord { + source: StageASource; + sourceId: string; + reason: ResolveIsinRejectionReason; +} + +export interface StageAConflictDetail { + isin: string | null; + cusip: string | null; + country: string | null; + derivedIsin: string | null; +} + +export interface StageAConflictRecord { + source: StageASource; + sourceId: string; + conflictKind: StageAConflictKind; + detail: StageAConflictDetail; +} + +export interface StageASourceStats { + total: number; + tier1Isin: number; + tier2Cusip: number; + unresolved: number; + conflict: number; +} + +export interface StageAStats { + totalInputRecords: number; + totalInstruments: number; + bySource: Record; +} + +export interface MatchInstrumentsStageAOptions { + readonly nameSourcePrecedence?: readonly StageASource[]; +} + +export interface StageAMatchResult { + instruments: StageAInstrumentCandidate[]; + unresolved: StageAUnresolvedRecord[]; + conflicts: StageAConflictRecord[]; + stats: StageAStats; +} + +interface BestSourceName { + sourceId: string; + name: string; +} + +interface InstrumentAccumulator { + members: StageAInstrumentMember[]; + bestNameBySource: Record; +} + +export function isStageASource(value: unknown): value is StageASource { + return value === 'ib' || value === 'eod'; +} + +function isNorthAmericaCountry(value: string): value is NorthAmericaCountry { + return value === 'US' || value === 'CA'; +} + +function normalizeCode(value: string | null | undefined): string | null { + if (typeof value !== 'string') { + return null; + } + const normalized = value.trim().toUpperCase(); + return normalized.length === 0 ? null : normalized; +} + +function normalizeName(value: string | null | undefined): string | null { + if (typeof value !== 'string') { + return null; + } + const trimmed = value.trim(); + return trimmed.length === 0 ? null : trimmed; +} + +function createEmptySourceStats(): StageASourceStats { + return { + total: 0, + tier1Isin: 0, + tier2Cusip: 0, + unresolved: 0, + conflict: 0, + }; +} + +function compareMembers(a: StageAInstrumentMember, b: StageAInstrumentMember): number { + return compareAscii(a.source, b.source) || compareAscii(a.sourceId, b.sourceId); +} + +function compareUnresolved(a: StageAUnresolvedRecord, b: StageAUnresolvedRecord): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.reason, b.reason) + ); +} + +function compareConflicts(a: StageAConflictRecord, b: StageAConflictRecord): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.conflictKind, b.conflictKind) || + compareAscii(a.detail.isin ?? '', b.detail.isin ?? '') || + compareAscii(a.detail.cusip ?? '', b.detail.cusip ?? '') || + compareAscii(a.detail.country ?? '', b.detail.country ?? '') || + compareAscii(a.detail.derivedIsin ?? '', b.detail.derivedIsin ?? '') + ); +} + +/** + * Pass 3 Stage A pure in-memory instrument matcher. + * Groups IB and EOD symbol records into instrument candidates by ISO 6166 Luhn-valid ISIN + * (`tier1_isin`) or US/CA CUSIP-derived ISIN (`tier2_cusip`), quarantining identifier mismatches + * and duplicate `(source, sourceId)` records into `conflicts`. + */ +export function matchInstrumentsStageA( + records: readonly StageASourceRecord[], + options: MatchInstrumentsStageAOptions = {} +): StageAMatchResult { + const nameSourcePrecedence = options.nameSourcePrecedence ?? STAGE_A_SOURCES; + for (const source of nameSourcePrecedence) { + if (!isStageASource(source)) { + throw new Error(`Unknown Stage A nameSourcePrecedence source "${String(source)}"`); + } + } + + // Per-source occurrence counts avoid composite-key allocations in the hot path while ensuring + // every duplicate `(source, sourceId)` is quarantined regardless of input ordering. + const countsBySource: Record> = { + ib: new Map(), + eod: new Map(), + }; + + for (let i = 0; i < records.length; i++) { + const record = records[i]; + if (record === undefined) { + continue; + } + if (!isStageASource(record.source)) { + throw new Error( + `Unknown Stage A source "${String(record.source)}" for sourceId "${String(record.sourceId)}"` + ); + } + if (typeof record.sourceId !== 'string' || record.sourceId.length === 0) { + throw new Error(`Invalid empty or non-string sourceId for source "${record.source}"`); + } + const sourceCounts = countsBySource[record.source]; + sourceCounts.set(record.sourceId, (sourceCounts.get(record.sourceId) ?? 0) + 1); + } + + const statsBySource: Record = { + ib: createEmptySourceStats(), + eod: createEmptySourceStats(), + }; + const instrumentsByIsin = new Map(); + const unresolved: StageAUnresolvedRecord[] = []; + const conflicts: StageAConflictRecord[] = []; + + for (let i = 0; i < records.length; i++) { + const record = records[i]; + if (record === undefined) { + continue; + } + const source = record.source; + const sourceId = record.sourceId; + const sourceStats = statsBySource[source]; + sourceStats.total += 1; + + if ((countsBySource[source].get(sourceId) ?? 0) > 1) { + conflicts.push({ + source, + sourceId, + conflictKind: 'duplicate_source_id', + detail: { + isin: normalizeCode(record.isin), + cusip: normalizeCode(record.cusip), + country: normalizeCode(record.country), + derivedIsin: null, + }, + }); + sourceStats.conflict += 1; + continue; + } + + const resolved = resolveIsin(record); + if (resolved.isin === null) { + unresolved.push({ + source, + sourceId, + reason: resolved.reason, + }); + sourceStats.unresolved += 1; + continue; + } + + if (resolved.source === 'isin' && typeof record.cusip === 'string') { + const normalizedCusip = normalizeCode(record.cusip); + if (normalizedCusip !== null) { + const normalizedCountry = normalizeCode(record.country); + let derivedCountry: NorthAmericaCountry | null = null; + if (normalizedCountry !== null) { + derivedCountry = isNorthAmericaCountry(normalizedCountry) ? normalizedCountry : null; + } else { + const isinPrefix = resolved.isin.slice(0, 2); + derivedCountry = isNorthAmericaCountry(isinPrefix) ? isinPrefix : null; + } + + if (derivedCountry !== null) { + const derivedIsin = cusipToIsin(normalizedCusip, derivedCountry); + if (derivedIsin !== null && derivedIsin !== resolved.isin) { + conflicts.push({ + source, + sourceId, + conflictKind: 'isin_cusip_mismatch', + detail: { + isin: resolved.isin, + cusip: normalizedCusip, + country: normalizedCountry, + derivedIsin, + }, + }); + sourceStats.conflict += 1; + continue; + } + } + } + } + + const method: StageAMatchMethod = resolved.source === 'isin' ? 'tier1_isin' : 'tier2_cusip'; + const currency = normalizeCode(record.currency); + const name = normalizeName(record.name); + + let acc = instrumentsByIsin.get(resolved.isin); + if (acc === undefined) { + acc = { + members: [], + bestNameBySource: { + ib: null, + eod: null, + }, + }; + instrumentsByIsin.set(resolved.isin, acc); + } + + acc.members.push({ + source, + sourceId, + currency, + method, + }); + + if (name !== null) { + const existingBest = acc.bestNameBySource[source]; + if (existingBest === null || compareAscii(sourceId, existingBest.sourceId) < 0) { + acc.bestNameBySource[source] = { sourceId, name }; + } + } + + if (method === 'tier1_isin') { + sourceStats.tier1Isin += 1; + } else { + sourceStats.tier2Cusip += 1; + } + } + + const instruments: StageAInstrumentCandidate[] = []; + for (const [primaryIsin, acc] of instrumentsByIsin.entries()) { + const issuerCountry = primaryIsin.slice(0, 2); + const embeddedCusip = primaryIsin.slice(2, 11); + const primaryCusip = + isNorthAmericaCountry(issuerCountry) && isValidCusip(embeddedCusip) ? embeddedCusip : null; + + let canonicalName: string | null = null; + for (const source of nameSourcePrecedence) { + const candidate = acc.bestNameBySource[source]; + if (candidate !== null) { + canonicalName = candidate.name; + break; + } + } + + if (acc.members.length > 1) { + acc.members.sort(compareMembers); + } + + instruments.push({ + primaryIsin, + primaryCusip, + issuerCountry, + canonicalName, + members: acc.members, + }); + } + + instruments.sort((a, b) => compareAscii(a.primaryIsin, b.primaryIsin)); + unresolved.sort(compareUnresolved); + conflicts.sort(compareConflicts); + + return { + instruments, + unresolved, + conflicts, + stats: { + totalInputRecords: records.length, + totalInstruments: instruments.length, + bySource: statsBySource, + }, + }; +} diff --git a/test/unit/security-master-instrument-stage-a.test.ts b/test/unit/security-master-instrument-stage-a.test.ts new file mode 100644 index 00000000..122d97e8 --- /dev/null +++ b/test/unit/security-master-instrument-stage-a.test.ts @@ -0,0 +1,697 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { + cusipToIsin, + isValidCusip, +} from '../../apps/stock/data-pipeline/src/normalization/identifiers'; +import { + isStageASource, + matchInstrumentsStageA, + STAGE_A_SOURCES, + type StageAMatchResult, + type StageASource, + type StageASourceRecord, +} from '../../apps/stock/data-pipeline/src/security-master'; + +const stageASourcePath = fileURLToPath( + new URL('../../apps/stock/data-pipeline/src/security-master/instrument-stage-a.ts', import.meta.url) +); + +const ISIN_SCHEMA_PATTERN = /^[A-Z]{2}[A-Z0-9]{9}[0-9]$/; +const ALLOWED_METHODS = new Set(['tier1_isin', 'tier2_cusip']); +const CUSIP_ALNUM = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + +function assertConservationAndSchema(result: StageAMatchResult, inputLength: number): void { + expect(result.stats.totalInputRecords).toBe(inputLength); + expect(result.stats.totalInstruments).toBe(result.instruments.length); + + const ibStats = result.stats.bySource.ib; + const eodStats = result.stats.bySource.eod; + expect(ibStats.total + eodStats.total).toBe(inputLength); + expect(ibStats.tier1Isin + ibStats.tier2Cusip + ibStats.unresolved + ibStats.conflict).toBe( + ibStats.total + ); + expect(eodStats.tier1Isin + eodStats.tier2Cusip + eodStats.unresolved + eodStats.conflict).toBe( + eodStats.total + ); + + let totalMembers = 0; + for (const instrument of result.instruments) { + expect(ISIN_SCHEMA_PATTERN.test(instrument.primaryIsin)).toBe(true); + expect(instrument.issuerCountry).toHaveLength(2); + expect(instrument.issuerCountry).toBe(instrument.primaryIsin.slice(0, 2)); + if (instrument.primaryCusip !== null) { + expect(instrument.primaryCusip).toHaveLength(9); + expect(isValidCusip(instrument.primaryCusip)).toBe(true); + } + for (const member of instrument.members) { + expect(ALLOWED_METHODS.has(member.method)).toBe(true); + totalMembers += 1; + } + } + + expect(totalMembers + result.unresolved.length + result.conflicts.length).toBe(inputLength); +} + +function makeRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function shuffleWithSeed(items: readonly T[], seed: number): T[] { + const copy = [...items]; + const rng = makeRng(seed); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + const tmp = copy[i]; + const swap = copy[j]; + if (tmp !== undefined && swap !== undefined) { + copy[i] = swap; + copy[j] = tmp; + } + } + return copy; +} + +function computeCusipWithCheckDigit(base8: string): string { + let sum = 0; + for (let i = 0; i < 8; i++) { + let val = CUSIP_ALNUM.indexOf(base8.charAt(i)); + if ((i & 1) === 1) { + val *= 2; + } + sum += Math.floor(val / 10) + (val % 10); + } + const checkDigit = (10 - (sum % 10)) % 10; + return base8 + String(checkDigit); +} + +describe('security master Pass 3 Stage A instrument matcher', () => { + test('is exported from security-master barrel and performs zero I/O imports', () => { + expect(typeof matchInstrumentsStageA).toBe('function'); + expect(STAGE_A_SOURCES).toEqual(['ib', 'eod']); + expect(isStageASource('ib')).toBe(true); + expect(isStageASource('eod')).toBe(true); + expect(isStageASource('qm')).toBe(false); + + const sourceText = readFileSync(stageASourcePath, 'utf8'); + const forbiddenImports = [ + '@stock-bot/mongodb', + '@stock-bot/postgres', + 'node:fs', + 'node:http', + 'node:https', + 'node:net', + 'bun:sqlite', + "'fs'", + '"fs"', + "'http'", + '"http"', + "'https'", + '"https"', + "'net'", + '"net"', + ]; + for (const forbidden of forbiddenImports) { + expect(sourceText).not.toContain(forbidden); + } + }); + + test('merges IB and EOD records sharing a Luhn-valid ISIN into one tier1_isin instrument', () => { + const result = matchInstrumentsStageA([ + { + source: 'ib', + sourceId: '265598', + isin: ' us0378331005 ', + currency: ' usd ', + name: 'Apple Inc.', + }, + { + source: 'eod', + sourceId: 'AAPL.US', + isin: 'US0378331005', + currency: 'USD', + name: 'APPLE INC', + }, + ]); + + expect(result.unresolved).toEqual([]); + expect(result.conflicts).toEqual([]); + expect(result.instruments).toEqual([ + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Apple Inc.', + members: [ + { source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: '265598', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ]); + assertConservationAndSchema(result, 2); + }); + + test('keeps interlisted USD and CAD members under one instrument while preserving both currencies', () => { + const result = matchInstrumentsStageA([ + { + source: 'ib', + sourceId: '11666', + isin: 'CA7800871021', + currency: 'USD', + name: 'Royal Bank of Canada', + }, + { + source: 'eod', + sourceId: 'RY.TO', + isin: 'CA7800871021', + currency: 'CAD', + name: 'ROYAL BANK OF CANADA', + }, + ]); + + expect(result.unresolved).toEqual([]); + expect(result.conflicts).toEqual([]); + expect(result.instruments).toEqual([ + { + primaryIsin: 'CA7800871021', + primaryCusip: '780087102', + issuerCountry: 'CA', + canonicalName: 'Royal Bank of Canada', + members: [ + { source: 'eod', sourceId: 'RY.TO', currency: 'CAD', method: 'tier1_isin' }, + { source: 'ib', sourceId: '11666', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ]); + assertConservationAndSchema(result, 2); + }); + + test('recovers tier2_cusip from explicit or embedded US/CA CUSIP and rejects placeholder ISINs', () => { + const result = matchInstrumentsStageA([ + { + source: 'eod', + sourceId: 'BAD_ISIN_WITH_CUSIP', + isin: 'CA8131391062', + cusip: '813137106', + country: 'CA', + currency: 'CAD', + name: 'Recovered Via Explicit CUSIP', + }, + { + source: 'ib', + sourceId: 'EMBEDDED_CUSIP_RECOVERY', + isin: 'CA7800871029', + currency: 'CAD', + name: 'Recovered Via Embedded CUSIP', + }, + { + source: 'eod', + sourceId: 'TEST_PLACEHOLDER_1', + isin: 'CATSETEST001', + country: 'CA', + }, + { + source: 'eod', + sourceId: 'TEST_PLACEHOLDER_2', + isin: 'CA00149WBAD4', + country: 'CA', + }, + ]); + + expect(result.conflicts).toEqual([]); + expect(result.instruments).toEqual([ + { + primaryIsin: 'CA7800871021', + primaryCusip: '780087102', + issuerCountry: 'CA', + canonicalName: 'Recovered Via Embedded CUSIP', + members: [ + { + source: 'ib', + sourceId: 'EMBEDDED_CUSIP_RECOVERY', + currency: 'CAD', + method: 'tier2_cusip', + }, + ], + }, + { + primaryIsin: 'CA8131371061', + primaryCusip: '813137106', + issuerCountry: 'CA', + canonicalName: 'Recovered Via Explicit CUSIP', + members: [ + { + source: 'eod', + sourceId: 'BAD_ISIN_WITH_CUSIP', + currency: 'CAD', + method: 'tier2_cusip', + }, + ], + }, + ]); + expect(result.unresolved).toEqual([ + { + source: 'eod', + sourceId: 'TEST_PLACEHOLDER_1', + reason: 'invalid_isin_and_no_valid_cusip', + }, + { + source: 'eod', + sourceId: 'TEST_PLACEHOLDER_2', + reason: 'invalid_isin_and_no_valid_cusip', + }, + ]); + assertConservationAndSchema(result, 4); + }); + + test('routes missing, invalid-CUSIP, and unsupported-country records to unresolved without throwing', () => { + const result = matchInstrumentsStageA([ + { source: 'eod', sourceId: 'NO_IDS', name: 'Missing Everything' }, + { source: 'ib', sourceId: 'BLANK_IDS', isin: ' ', cusip: '' }, + { source: 'eod', sourceId: 'BAD_CUSIP_ONLY', cusip: '813137109', country: 'CA' }, + { source: 'eod', sourceId: 'GB_CUSIP_ONLY', cusip: '813137106', country: 'GB' }, + { source: 'ib', sourceId: 'NO_COUNTRY_CUSIP', cusip: '037833100' }, + ]); + + expect(result.instruments).toEqual([]); + expect(result.conflicts).toEqual([]); + expect(result.unresolved).toEqual([ + { source: 'eod', sourceId: 'BAD_CUSIP_ONLY', reason: 'invalid_cusip' }, + { source: 'eod', sourceId: 'GB_CUSIP_ONLY', reason: 'unsupported_country_for_cusip' }, + { source: 'eod', sourceId: 'NO_IDS', reason: 'missing_identifiers' }, + { source: 'ib', sourceId: 'BLANK_IDS', reason: 'missing_identifiers' }, + { source: 'ib', sourceId: 'NO_COUNTRY_CUSIP', reason: 'unsupported_country_for_cusip' }, + ]); + assertConservationAndSchema(result, 5); + }); + + test('quarantines isin_cusip_mismatch and duplicate_source_id without joining any instrument', () => { + const result = matchInstrumentsStageA([ + // Explicit CA country mismatch + { + source: 'eod', + sourceId: 'MISMATCH_EXPLICIT_CA', + isin: 'CA8131371061', + cusip: '780087102', + country: 'CA', + }, + // Missing country falls back to CA ISIN prefix and still detects mismatch + { + source: 'ib', + sourceId: 'MISMATCH_PREFIX_CA', + isin: 'CA8131371061', + cusip: '780087102', + country: null, + }, + // Non-US/CA ISIN with explicit US country + valid CUSIP triggers mismatch + { + source: 'eod', + sourceId: 'MISMATCH_AU_WITH_US_CUSIP', + isin: 'AU0000XVGZA3', + cusip: '037833100', + country: 'US', + }, + // Non-US/CA ISIN with AU country or null country joins with primaryCusip: null + { + source: 'eod', + sourceId: 'VALID_AU_WITH_AU_COUNTRY', + isin: 'AU0000XVGZA3', + cusip: '037833100', + country: 'AU', + currency: 'AUD', + }, + { + source: 'ib', + sourceId: 'VALID_AU_NULL_COUNTRY', + isin: 'AU0000XVGZA3', + cusip: '037833100', + country: null, + currency: 'AUD', + }, + // Valid ISIN + invalid CUSIP is NOT a mismatch and joins as tier1_isin + { + source: 'eod', + sourceId: 'VALID_ISIN_BAD_CUSIP', + isin: 'US0378331005', + cusip: '037833109', + country: 'US', + currency: 'USD', + }, + // Duplicate (source, sourceId) with identical ISIN + { + source: 'ib', + sourceId: 'DUP_SAME', + isin: 'CA7800871021', + currency: 'CAD', + }, + { + source: 'ib', + sourceId: 'DUP_SAME', + isin: 'CA7800871021', + currency: 'USD', + }, + // Duplicate (source, sourceId) with differing ISINs + { + source: 'eod', + sourceId: 'DUP_DIFF', + isin: 'CA7800871021', + }, + { + source: 'eod', + sourceId: 'DUP_DIFF', + isin: 'CA8131371061', + }, + ]); + + expect(result.unresolved).toEqual([]); + expect(result.instruments).toEqual([ + { + primaryIsin: 'AU0000XVGZA3', + primaryCusip: null, + issuerCountry: 'AU', + canonicalName: null, + members: [ + { + source: 'eod', + sourceId: 'VALID_AU_WITH_AU_COUNTRY', + currency: 'AUD', + method: 'tier1_isin', + }, + { + source: 'ib', + sourceId: 'VALID_AU_NULL_COUNTRY', + currency: 'AUD', + method: 'tier1_isin', + }, + ], + }, + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: null, + members: [ + { + source: 'eod', + sourceId: 'VALID_ISIN_BAD_CUSIP', + currency: 'USD', + method: 'tier1_isin', + }, + ], + }, + ]); + + expect(result.conflicts).toEqual([ + { + source: 'eod', + sourceId: 'DUP_DIFF', + conflictKind: 'duplicate_source_id', + detail: { isin: 'CA7800871021', cusip: null, country: null, derivedIsin: null }, + }, + { + source: 'eod', + sourceId: 'DUP_DIFF', + conflictKind: 'duplicate_source_id', + detail: { isin: 'CA8131371061', cusip: null, country: null, derivedIsin: null }, + }, + { + source: 'eod', + sourceId: 'MISMATCH_AU_WITH_US_CUSIP', + conflictKind: 'isin_cusip_mismatch', + detail: { + isin: 'AU0000XVGZA3', + cusip: '037833100', + country: 'US', + derivedIsin: 'US0378331005', + }, + }, + { + source: 'eod', + sourceId: 'MISMATCH_EXPLICIT_CA', + conflictKind: 'isin_cusip_mismatch', + detail: { + isin: 'CA8131371061', + cusip: '780087102', + country: 'CA', + derivedIsin: 'CA7800871021', + }, + }, + { + source: 'ib', + sourceId: 'DUP_SAME', + conflictKind: 'duplicate_source_id', + detail: { isin: 'CA7800871021', cusip: null, country: null, derivedIsin: null }, + }, + { + source: 'ib', + sourceId: 'DUP_SAME', + conflictKind: 'duplicate_source_id', + detail: { isin: 'CA7800871021', cusip: null, country: null, derivedIsin: null }, + }, + { + source: 'ib', + sourceId: 'MISMATCH_PREFIX_CA', + conflictKind: 'isin_cusip_mismatch', + detail: { + isin: 'CA8131371061', + cusip: '780087102', + country: null, + derivedIsin: 'CA7800871021', + }, + }, + ]); + assertConservationAndSchema(result, 10); + }); + + test('applies IB -> EOD canonicalName precedence with ASCII sourceId tie-breaking and fallback', () => { + const result = matchInstrumentsStageA([ + // Instrument 1: multiple IB members + EOD member -> lowest-ASCII IB sourceId with non-empty name wins + { source: 'eod', sourceId: 'A_EOD', isin: 'US0378331005', name: 'EOD Name' }, + { source: 'ib', sourceId: '200', isin: 'US0378331005', name: 'IB Higher SourceId' }, + { source: 'ib', sourceId: '050', isin: 'US0378331005', name: ' ' }, + { source: 'ib', sourceId: '100', isin: 'US0378331005', name: ' IB Lowest Non-Empty ' }, + + // Instrument 2: IB names are null/undefined/blank -> falls back to lowest-ASCII EOD name + { source: 'ib', sourceId: '1', isin: 'CA7800871021', name: null }, + { source: 'ib', sourceId: '2', isin: 'CA7800871021', name: ' ' }, + { source: 'eod', sourceId: 'Z.TO', isin: 'CA7800871021', name: 'EOD Later' }, + { source: 'eod', sourceId: 'A.TO', isin: 'CA7800871021', name: 'EOD First' }, + + // Instrument 3: all members lack a name -> null + { source: 'ib', sourceId: '999', isin: 'CA8131371061' }, + { source: 'eod', sourceId: 'NO_NAME.TO', isin: 'CA8131371061', name: '' }, + ]); + + expect(result.instruments.map(inst => [inst.primaryIsin, inst.canonicalName])).toEqual([ + ['CA7800871021', 'EOD First'], + ['CA8131371061', null], + ['US0378331005', 'IB Lowest Non-Empty'], + ]); + + const eodFirst = matchInstrumentsStageA( + [ + { source: 'ib', sourceId: '100', isin: 'US0378331005', name: 'IB Name' }, + { source: 'eod', sourceId: 'AAPL.US', isin: 'US0378331005', name: 'EOD Name' }, + ], + { nameSourcePrecedence: ['eod', 'ib'] } + ); + expect(eodFirst.instruments[0]?.canonicalName).toBe('EOD Name'); + }); + + test('preserves sourceId verbatim without trimming and throws on empty sourceId or unknown source', () => { + const result = matchInstrumentsStageA([ + { source: 'eod', sourceId: ' AAPL.US', isin: 'US0378331005', currency: 'USD' }, + { source: 'eod', sourceId: 'AAPL.US', isin: 'US0378331005', currency: 'USD' }, + { source: 'eod', sourceId: ' MISSING ', isin: null }, + { source: 'ib', sourceId: ' CON ', isin: 'CA8131371061', cusip: '780087102', country: 'CA' }, + ]); + + expect(result.instruments[0]?.members.map(m => m.sourceId)).toEqual([' AAPL.US', 'AAPL.US']); + expect(result.unresolved[0]?.sourceId).toBe(' MISSING '); + expect(result.conflicts[0]?.sourceId).toBe(' CON '); + assertConservationAndSchema(result, 4); + + expect(() => + matchInstrumentsStageA([{ source: 'eod', sourceId: '', isin: 'US0378331005' }]) + ).toThrow(/sourceId/i); + + expect(() => + matchInstrumentsStageA([ + { source: 'qm' as unknown as StageASource, sourceId: 'AAPL', isin: 'US0378331005' }, + ]) + ).toThrow(/qm.*AAPL/); + + expect(() => + matchInstrumentsStageA([], { + nameSourcePrecedence: ['qm' as unknown as StageASource], + }) + ).toThrow(/qm/); + }); + + test('produces byte-identical JSON output across shuffled input orderings and preserves conservation', () => { + const corpus: StageASourceRecord[] = [ + { source: 'ib', sourceId: '100', isin: 'US0378331005', currency: 'USD', name: 'Apple IB' }, + { source: 'eod', sourceId: 'AAPL.US', isin: 'US0378331005', currency: 'USD', name: 'Apple EOD' }, + { source: 'ib', sourceId: '11666', isin: 'CA7800871021', currency: 'USD', name: 'RBC US' }, + { source: 'eod', sourceId: 'RY.TO', isin: 'CA7800871021', currency: 'CAD', name: 'RBC CA' }, + { + source: 'eod', + sourceId: 'TIER2_CA', + isin: 'CA8131391062', + cusip: '813137106', + country: 'CA', + currency: 'CAD', + name: 'Tier 2', + }, + { source: 'ib', sourceId: 'TIER2_EMBED', isin: 'CA7800871029', currency: 'CAD' }, + { source: 'eod', sourceId: 'UNRES_MISSING' }, + { source: 'eod', sourceId: 'UNRES_PLACEHOLDER', isin: 'CATSETEST001', country: 'CA' }, + { + source: 'eod', + sourceId: 'CONF_MISMATCH', + isin: 'CA8131371061', + cusip: '780087102', + country: 'CA', + }, + { source: 'ib', sourceId: 'CONF_DUP', isin: 'US0378331005', country: 'US' }, + { source: 'ib', sourceId: 'CONF_DUP', isin: 'CA7800871021', country: 'CA' }, + ]; + + const baseline = matchInstrumentsStageA(corpus); + const baselineJson = JSON.stringify(baseline); + assertConservationAndSchema(baseline, corpus.length); + + const reversed = matchInstrumentsStageA([...corpus].reverse()); + expect(JSON.stringify(reversed)).toBe(baselineJson); + + for (const seed of [1, 42, 1337, 99999]) { + const shuffled = shuffleWithSeed(corpus, seed); + const res = matchInstrumentsStageA(shuffled); + expect(JSON.stringify(res)).toBe(baselineJson); + assertConservationAndSchema(res, corpus.length); + } + }); + + test('local benchmark: 300,000 synthetic records complete in under 2 seconds', () => { + const TOTAL_RECORDS = 300_000; + const UNIQUE_INSTRUMENTS = 100_000; + const records: StageASourceRecord[] = new Array(TOTAL_RECORDS); + + // Pre-generate 100k valid US/CA CUSIPs and derived ISINs outside the timed window. + const validCusips: string[] = new Array(UNIQUE_INSTRUMENTS); + const validIsins: string[] = new Array(UNIQUE_INSTRUMENTS); + for (let i = 0; i < UNIQUE_INSTRUMENTS; i++) { + const base8 = String(10000000 + i); + const cusip = computeCusipWithCheckDigit(base8); + const country = (i & 1) === 0 ? 'US' : 'CA'; + const isin = cusipToIsin(cusip, country); + if (isin === null) { + throw new Error(`Failed to generate synthetic ISIN for base8=${base8}`); + } + validCusips[i] = cusip; + validIsins[i] = isin; + } + + let idx = 0; + // 100k IB tier1_isin records + for (let i = 0; i < UNIQUE_INSTRUMENTS; i++) { + const isin = validIsins[i] ?? 'US0378331005'; + records[idx++] = { + source: 'ib', + sourceId: `IB${i}`, + isin, + currency: (i & 1) === 0 ? 'USD' : 'CAD', + name: `Issuer ${i}`, + }; + } + + // 100k EOD tier1_isin records pairing with the IB records + for (let i = 0; i < UNIQUE_INSTRUMENTS; i++) { + const isin = validIsins[i] ?? 'US0378331005'; + records[idx++] = { + source: 'eod', + sourceId: `EOD${i}`, + isin, + currency: (i & 1) === 0 ? 'USD' : 'CAD', + name: `ISSUER ${i} CORP`, + }; + } + + // 60k CUSIP-only tier2_cusip records + for (let i = 0; i < 60_000; i++) { + const cusip = validCusips[i] ?? '037833100'; + const country = (i & 1) === 0 ? 'US' : 'CA'; + records[idx++] = { + source: 'eod', + sourceId: `CUSIP${i}`, + cusip, + country, + currency: country === 'US' ? 'USD' : 'CAD', + }; + } + + // 35k unresolved records (missing + placeholders) + for (let i = 0; i < 35_000; i++) { + records[idx++] = + (i & 1) === 0 + ? { source: 'eod', sourceId: `UNRES${i}` } + : { source: 'ib', sourceId: `UNRES_PH${i}`, isin: 'CATSETEST001', country: 'CA' }; + } + + // 5k conflict records (3k isin_cusip_mismatch + 2k duplicate_source_id) + for (let i = 0; i < 3_000; i++) { + records[idx++] = { + source: 'eod', + sourceId: `MISMATCH${i}`, + isin: validIsins[i] ?? 'US0378331005', + cusip: validCusips[i + 1] ?? '780087102', + country: (i & 1) === 0 ? 'US' : 'CA', + }; + } + for (let i = 0; i < 1_000; i++) { + const dupId = `DUP${i}`; + const isin = validIsins[i] ?? 'US0378331005'; + records[idx++] = { source: 'ib', sourceId: dupId, isin, currency: 'USD' }; + records[idx++] = { source: 'ib', sourceId: dupId, isin, currency: 'CAD' }; + } + + expect(idx).toBe(TOTAL_RECORDS); + + const startMs = performance.now(); + const result = matchInstrumentsStageA(records); + const elapsedMs = performance.now() - startMs; + + process.stdout.write( + `[benchmark] matchInstrumentsStageA(${TOTAL_RECORDS} records): ${elapsedMs.toFixed(1)} ms (${result.stats.totalInstruments} instruments)\n` + ); + + expect(elapsedMs).toBeLessThan(2000); + expect(result.stats.totalInputRecords).toBe(TOTAL_RECORDS); + expect(result.stats.totalInstruments).toBe(UNIQUE_INSTRUMENTS); + expect(result.unresolved).toHaveLength(35_000); + expect(result.conflicts).toHaveLength(5_000); + expect( + result.stats.bySource.ib.total + result.stats.bySource.eod.total + ).toBe(TOTAL_RECORDS); + expect( + result.stats.bySource.ib.tier1Isin + + result.stats.bySource.ib.tier2Cusip + + result.stats.bySource.ib.unresolved + + result.stats.bySource.ib.conflict + ).toBe(result.stats.bySource.ib.total); + expect( + result.stats.bySource.eod.tier1Isin + + result.stats.bySource.eod.tier2Cusip + + result.stats.bySource.eod.unresolved + + result.stats.bySource.eod.conflict + ).toBe(result.stats.bySource.eod.total); + }); +});