T-50: M1.1e — Pass 3 Stage A: pure in-memory instrument matcher (global ISIN / CUSIP-derived ISIN, IB ↔ EOD)

This commit is contained in:
Studio 2026-11-27 16:03:50 -05:00
parent b20fc28e45
commit 895a49e7ad
3 changed files with 1071 additions and 0 deletions

View file

@ -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';

View file

@ -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<StageASource, StageASourceStats>;
}
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<StageASource, BestSourceName | null>;
}
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<StageASource, Map<string, number>> = {
ib: new Map<string, number>(),
eod: new Map<string, number>(),
};
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<StageASource, StageASourceStats> = {
ib: createEmptySourceStats(),
eod: createEmptySourceStats(),
};
const instrumentsByIsin = new Map<string, InstrumentAccumulator>();
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,
},
};
}