T-50: tests

This commit is contained in:
Studio 2026-11-27 16:11:25 -05:00
parent 895a49e7ad
commit 315ec0367e

View file

@ -15,7 +15,10 @@ import {
} 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)
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]$/;
@ -539,7 +542,13 @@ describe('security master Pass 3 Stage A instrument matcher', () => {
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: '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' },
{
@ -678,9 +687,16 @@ describe('security master Pass 3 Stage A instrument matcher', () => {
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);
// Reconcile the stats counters with the emitted rows, not just with each other.
let benchmarkMembers = 0;
for (const instrument of result.instruments) {
benchmarkMembers += instrument.members.length;
}
expect(benchmarkMembers).toBe(260_000);
expect(benchmarkMembers + result.unresolved.length + result.conflicts.length).toBe(
TOTAL_RECORDS
);
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 +
@ -695,3 +711,345 @@ describe('security master Pass 3 Stage A instrument matcher', () => {
).toBe(result.stats.bySource.eod.total);
});
});
const CUSIP_CHARSET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#';
function withCusipCheckDigit(base8: string): string {
let sum = 0;
for (let i = 0; i < 8; i++) {
let val = CUSIP_CHARSET.indexOf(base8.charAt(i));
if (val < 0) {
throw new Error(`Unsupported CUSIP character in ${base8}`);
}
if ((i & 1) === 1) {
val *= 2;
}
sum += Math.floor(val / 10) + (val % 10);
}
return base8 + String((10 - (sum % 10)) % 10);
}
function deepFreezeRecords(records: StageASourceRecord[]): readonly StageASourceRecord[] {
for (const record of records) {
Object.freeze(record);
}
return Object.freeze(records);
}
describe('security master Pass 3 Stage A instrument matcher — QA edge cases', () => {
test('empty input yields an empty, fully zeroed result', () => {
const result = matchInstrumentsStageA([]);
expect(result).toEqual({
instruments: [],
unresolved: [],
conflicts: [],
stats: {
totalInputRecords: 0,
totalInstruments: 0,
bySource: {
ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 },
eod: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 },
},
},
});
});
test('tier1 and tier2 members resolving to the same ISIN merge into one instrument keeping per-member methods', () => {
const result = matchInstrumentsStageA([
{ source: 'ib', sourceId: '4001', isin: 'CA8131371061', currency: 'CAD', name: 'IB Name' },
// Checksum-corrupted ISIN recovered through explicit CUSIP
{
source: 'eod',
sourceId: 'SCU-UN.TO',
isin: 'CA8131391062',
cusip: '813137106',
country: 'CA',
currency: 'CAD',
},
// CUSIP-only record recovered through explicit country
{ source: 'eod', sourceId: 'SCU-UN.V', cusip: '813137106', country: 'ca', currency: 'cad' },
]);
expect(result.instruments).toHaveLength(1);
expect(result.instruments[0]?.primaryIsin).toBe('CA8131371061');
expect(result.instruments[0]?.members).toEqual([
{ source: 'eod', sourceId: 'SCU-UN.TO', currency: 'CAD', method: 'tier2_cusip' },
{ source: 'eod', sourceId: 'SCU-UN.V', currency: 'CAD', method: 'tier2_cusip' },
{ source: 'ib', sourceId: '4001', currency: 'CAD', method: 'tier1_isin' },
]);
expect(result.stats.bySource.ib).toEqual({
total: 1,
tier1Isin: 1,
tier2Cusip: 0,
unresolved: 0,
conflict: 0,
});
expect(result.stats.bySource.eod).toEqual({
total: 2,
tier1Isin: 0,
tier2Cusip: 2,
unresolved: 0,
conflict: 0,
});
assertConservationAndSchema(result, 3);
});
test('a valid ISIN with a valid private-placement CUSIP (*, @, #) is not flagged as a mismatch', () => {
const privatePlacementCusips = [
withCusipCheckDigit('12345*67'),
withCusipCheckDigit('1234@567'),
withCusipCheckDigit('123#4567'),
];
for (const cusip of privatePlacementCusips) {
// Arrange: guard that the vector really is a valid CUSIP that cannot become an ISIN.
expect(isValidCusip(cusip)).toBe(true);
expect(cusipToIsin(cusip, 'US')).toBeNull();
}
const result = matchInstrumentsStageA(
privatePlacementCusips.map((cusip, i) => ({
source: 'ib' as const,
sourceId: `PP${i}`,
isin: 'US0378331005',
cusip,
country: 'US',
}))
);
expect(result.conflicts).toEqual([]);
expect(result.instruments).toHaveLength(1);
expect(result.instruments[0]?.members.map(m => m.method)).toEqual([
'tier1_isin',
'tier1_isin',
'tier1_isin',
]);
assertConservationAndSchema(result, 3);
});
test('a valid ISIN whose own CUSIP matches is accepted regardless of case and padding', () => {
const result = matchInstrumentsStageA([
{
source: 'eod',
sourceId: 'RY.US',
isin: 'ca7800871021',
cusip: ' 780087102 ',
country: ' ca ',
},
{
source: 'ib',
sourceId: '11666',
isin: 'CA7800871021',
cusip: '780087102',
country: undefined,
},
]);
expect(result.conflicts).toEqual([]);
expect(result.instruments).toHaveLength(1);
expect(result.instruments[0]?.members.map(m => [m.sourceId, m.method])).toEqual([
['RY.US', 'tier1_isin'],
['11666', 'tier1_isin'],
]);
});
test('mismatch conflict detail normalizes cusip and country to trimmed upper case', () => {
const result = matchInstrumentsStageA([
{
source: 'eod',
sourceId: 'MIX',
isin: 'CA8131371061',
cusip: ' 780087102 ',
country: ' ca ',
},
]);
expect(result.instruments).toEqual([]);
expect(result.conflicts).toEqual([
{
source: 'eod',
sourceId: 'MIX',
conflictKind: 'isin_cusip_mismatch',
detail: {
isin: 'CA8131371061',
cusip: '780087102',
country: 'CA',
derivedIsin: 'CA7800871021',
},
},
]);
expect(result.stats.bySource.eod.conflict).toBe(1);
});
test('the same sourceId under different sources is not a duplicate', () => {
const result = matchInstrumentsStageA([
{ source: 'ib', sourceId: 'SAME', isin: 'US0378331005' },
{ source: 'eod', sourceId: 'SAME', isin: 'US0378331005' },
]);
expect(result.conflicts).toEqual([]);
expect(result.instruments[0]?.members.map(m => `${m.source}:${m.sourceId}`)).toEqual([
'eod:SAME',
'ib:SAME',
]);
});
test('duplicate detection takes precedence over unresolved and mismatch, and every occurrence is quarantined', () => {
const result = matchInstrumentsStageA([
{ source: 'eod', sourceId: 'TRIPLE', isin: 'US0378331005' },
{ source: 'eod', sourceId: 'TRIPLE' },
{
source: 'eod',
sourceId: 'TRIPLE',
isin: 'CA8131371061',
cusip: '780087102',
country: 'CA',
},
{ source: 'eod', sourceId: 'SOLO', isin: 'US0378331005' },
]);
expect(result.unresolved).toEqual([]);
expect(result.conflicts.map(c => [c.sourceId, c.conflictKind])).toEqual([
['TRIPLE', 'duplicate_source_id'],
['TRIPLE', 'duplicate_source_id'],
['TRIPLE', 'duplicate_source_id'],
]);
expect(result.conflicts.every(c => c.detail.derivedIsin === null)).toBe(true);
expect(result.instruments).toHaveLength(1);
expect(result.instruments[0]?.members.map(m => m.sourceId)).toEqual(['SOLO']);
expect(result.stats.bySource.eod).toEqual({
total: 4,
tier1Isin: 1,
tier2Cusip: 0,
unresolved: 0,
conflict: 3,
});
assertConservationAndSchema(result, 4);
});
test('members, names and unresolved rows sort by ASCII code unit, not locale', () => {
const result = matchInstrumentsStageA([
{ source: 'ib', sourceId: 'a1', isin: 'US0378331005', name: 'Lowercase Id' },
{ source: 'ib', sourceId: 'B1', isin: 'US0378331005', name: 'Uppercase Id' },
{ source: 'ib', sourceId: '_1', isin: 'US0378331005' },
{ source: 'eod', sourceId: 'z' },
{ source: 'eod', sourceId: 'Z' },
]);
// ASCII: 'B' (66) < '_' (95) < 'a' (97); locale collation would put 'a1' before 'B1'.
expect(result.instruments[0]?.members.map(m => m.sourceId)).toEqual(['B1', '_1', 'a1']);
expect(result.instruments[0]?.canonicalName).toBe('Uppercase Id');
expect(result.unresolved.map(u => u.sourceId)).toEqual(['Z', 'z']);
});
test('nameSourcePrecedence restricted to one source ignores the other source names', () => {
const records: StageASourceRecord[] = [
{ source: 'ib', sourceId: '1', isin: 'US0378331005', name: 'IB Only' },
{ source: 'eod', sourceId: 'X.TO', isin: 'CA7800871021', name: 'EOD Only' },
];
const precedence: readonly StageASource[] = Object.freeze(['eod'] as StageASource[]);
const eodOnly = matchInstrumentsStageA(records, { nameSourcePrecedence: precedence });
const none = matchInstrumentsStageA(records, { nameSourcePrecedence: [] });
expect(eodOnly.instruments.map(i => [i.primaryIsin, i.canonicalName])).toEqual([
['CA7800871021', 'EOD Only'],
['US0378331005', null],
]);
expect(none.instruments.map(i => i.canonicalName)).toEqual([null, null]);
expect(precedence).toEqual(['eod']);
});
test('does not mutate frozen inputs and repeated calls share no state', () => {
const makeInput = (): StageASourceRecord[] => [
{ source: 'ib', sourceId: '2', isin: ' us0378331005 ', currency: ' usd ', name: ' Apple ' },
{ source: 'ib', sourceId: '1', isin: 'US0378331005', currency: 'USD' },
{ source: 'eod', sourceId: 'BAD', isin: 'CATSETEST001' },
{ source: 'eod', sourceId: 'D', isin: 'US0378331005' },
{ source: 'eod', sourceId: 'D', isin: 'US0378331005' },
];
const frozen = deepFreezeRecords(makeInput());
const snapshot = JSON.stringify(frozen);
const first = matchInstrumentsStageA(frozen);
const firstJson = JSON.stringify(first);
// Mutating a returned result must not leak into a later call.
first.instruments[0]?.members.push({
source: 'ib',
sourceId: 'INJECTED',
currency: null,
method: 'tier1_isin',
});
first.stats.bySource.ib.total = 999;
const second = matchInstrumentsStageA(frozen);
expect(JSON.stringify(frozen)).toBe(snapshot);
expect(JSON.stringify(second)).toBe(firstJson);
expect(JSON.stringify(matchInstrumentsStageA(makeInput()))).toBe(firstJson);
});
test('a larger seeded mixed corpus is byte-identical under shuffling and conserves every record', () => {
const rng = makeRng(20261127);
const isins: string[] = [];
const cusips: string[] = [];
for (let i = 0; i < 200; i++) {
const cusip = withCusipCheckDigit(String(20000000 + i * 7));
const isin = cusipToIsin(cusip, (i & 1) === 0 ? 'US' : 'CA');
if (isin === null) {
throw new Error(`Failed to build ISIN for ${cusip}`);
}
cusips.push(cusip);
isins.push(isin);
}
const corpus: StageASourceRecord[] = [];
for (let i = 0; i < 2_000; i++) {
const source: StageASource = rng() < 0.5 ? 'ib' : 'eod';
const k = Math.floor(rng() * isins.length);
const isin = isins[k] ?? 'US0378331005';
const cusip = cusips[k] ?? '037833100';
const country = isin.slice(0, 2);
const roll = rng();
// sourceIds intentionally collide sometimes to create duplicates.
const sourceId = `S${Math.floor(rng() * 1_800)}`;
const name = rng() < 0.3 ? null : `Name ${Math.floor(rng() * 5)}`;
const currency = rng() < 0.5 ? 'USD' : 'CAD';
if (roll < 0.4) {
corpus.push({ source, sourceId, isin, currency, name });
} else if (roll < 0.6) {
corpus.push({ source, sourceId, cusip, country, currency, name });
} else if (roll < 0.7) {
corpus.push({
source,
sourceId,
isin: `${isin.slice(0, 11)}${(Number(isin.charAt(11)) + 1) % 10}`,
currency,
name,
});
} else if (roll < 0.8) {
const otherCusip = cusips[(k + 1) % cusips.length] ?? '780087102';
corpus.push({ source, sourceId, isin, cusip: otherCusip, country, currency, name });
} else if (roll < 0.9) {
corpus.push({ source, sourceId, isin: 'CATSETEST001', country: 'CA', name });
} else {
corpus.push({ source, sourceId, name });
}
}
const baseline = matchInstrumentsStageA(corpus);
const baselineJson = JSON.stringify(baseline);
assertConservationAndSchema(baseline, corpus.length);
expect(baseline.conflicts.some(c => c.conflictKind === 'duplicate_source_id')).toBe(true);
expect(baseline.conflicts.some(c => c.conflictKind === 'isin_cusip_mismatch')).toBe(true);
expect(baseline.unresolved.length).toBeGreaterThan(0);
expect(
baseline.stats.bySource.ib.tier2Cusip + baseline.stats.bySource.eod.tier2Cusip
).toBeGreaterThan(0);
for (const seed of [7, 8, 9]) {
expect(JSON.stringify(matchInstrumentsStageA(shuffleWithSeed(corpus, seed)))).toBe(
baselineJson
);
}
});
});