stock-bot/test/unit/security-master-run.test.ts

953 lines
34 KiB
TypeScript

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { describe, expect, test } from 'bun:test';
import {
BarSpanIndex,
type BarSpan,
type ComputeBarSpansResult,
} from '../../apps/stock/data-pipeline/src/normalization/bar-spans';
import { cusipToIsin } from '../../apps/stock/data-pipeline/src/normalization/identifiers';
import {
attachBarSpansToStageBInput,
classifySourceExchanges,
composeSecurityMasterRun,
CONTINUITY_KIND_OTC_DELIST_TRANSFER,
derivePass4CandidatePairs,
deriveSourceCountries,
formatListingNaturalKey,
type ComposeSecurityMasterRunInput,
type FxRateByDateRecord,
type SampleCloseRecord,
type SecurityMasterSourcesResult,
type SecurityMasterStageBSourceInput,
type SecurityType,
type StageASourceRecord,
type StageBEodListingInput,
type StageBIbContractInput,
type StageBSymbolChangeInput,
type StageBTickerSourceInput,
} from '../../apps/stock/data-pipeline/src/security-master';
const runSourcePath = fileURLToPath(
new URL('../../apps/stock/data-pipeline/src/security-master/run.ts', import.meta.url)
);
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<T>(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];
const b = copy[j];
if (a !== undefined && b !== undefined) {
copy[i] = b;
copy[j] = a;
}
}
return copy;
}
function makeEmptyCollectionStats(
collection: 'eodSymbols' | 'ibSymbols' | 'qmSymbols' | 'ceoSymbols' | 'eodSymbolChange'
) {
return {
collection,
docsRead: 0,
emitted: 0,
invalidIdentifiersNulled: 0,
skips: {
missingId: 0,
invalidFieldType: 0,
invalidIdentifier: 0,
excludedMutualFund: 0,
unmappedExchange: 0,
outOfScopeCountry: 0,
},
};
}
function makeSourcesResult(params: {
stageARecords: StageASourceRecord[];
eodListings: StageBEodListingInput[];
ibContracts: StageBIbContractInput[];
tickerSources: StageBTickerSourceInput[];
symbolChanges?: StageBSymbolChangeInput[];
securityTypeByIsin: Map<string, SecurityType>;
}): SecurityMasterSourcesResult {
return {
stageARecords: params.stageARecords,
stageBInput: {
eodListings: params.eodListings,
ibContracts: params.ibContracts,
tickerSources: params.tickerSources,
symbolChanges: params.symbolChanges ?? [],
},
securityTypeRecords: [],
securityTypeByIsin: params.securityTypeByIsin,
securityTypeStats: {
totalRecords: 0,
mapped: 0,
missingType: 0,
unknownType: 0,
invalidIsin: 0,
isinsResolved: params.securityTypeByIsin.size,
isinsConflicting: 0,
conflictsTruncated: 0,
},
securityTypeLoaderStats: {
totalRecords: 0,
mapped: 0,
missingType: 0,
unknownType: 0,
invalidIsin: 0,
isinsResolved: params.securityTypeByIsin.size,
isinsConflicting: 0,
conflictsTruncated: 0,
},
unknownSecurityTypes: [],
securityTypeConflicts: [],
stats: {
eodSymbols: makeEmptyCollectionStats('eodSymbols'),
ibSymbols: makeEmptyCollectionStats('ibSymbols'),
qmSymbols: makeEmptyCollectionStats('qmSymbols'),
ceoSymbols: makeEmptyCollectionStats('ceoSymbols'),
eodSymbolChange: makeEmptyCollectionStats('eodSymbolChange'),
},
};
}
/**
* Canonical M1 exit-criterion fixture:
* - AAPL (`US0378331005`): EOD + IB + QM on XNAS (USD)
* - FB common (`US30303M1027`, 2012-2022) vs FB ETF (`US4642872000`, 2025) on XNAS (USD)
* - SIVB (`US78486Q1013`) XNAS (2015..2023-03-10) -> SIVBQ OTCM (2023-03-28..2024-11-07)
* - SHOP (`CA82509L1076`) interlisted XTSE (CAD) + XNYS (USD) with IB contracts in CAD & USD
*/
function buildCanonicalFixture(): {
input: ComposeSecurityMasterRunInput;
sampleCloses: SampleCloseRecord[];
fxRates: FxRateByDateRecord[];
} {
const stageARecords: StageASourceRecord[] = [
{
source: 'ib',
sourceId: '265598',
isin: 'US0378331005',
cusip: '037833100',
country: 'US',
currency: 'USD',
name: 'Apple Inc.',
},
{
source: 'eod',
sourceId: 'AAPL.US',
isin: 'US0378331005',
cusip: '037833100',
country: 'US',
currency: 'USD',
name: 'Apple Inc',
},
{
source: 'eod',
sourceId: 'FB_OLD.US',
isin: 'US30303M1027',
cusip: '30303M102',
country: 'US',
currency: 'USD',
name: 'Meta Platforms Inc',
},
{
source: 'eod',
sourceId: 'FB_ETF.US',
isin: 'US4642872000',
cusip: '464287200',
country: 'US',
currency: 'USD',
name: 'FB Thematic ETF',
},
{
source: 'eod',
sourceId: 'SIVB.US',
isin: 'US78486Q1013',
cusip: '78486Q101',
country: 'US',
currency: 'USD',
name: 'SVB Financial Group',
},
{
source: 'eod',
sourceId: 'SIVBQ.US',
isin: 'US78486Q1013',
cusip: '78486Q101',
country: 'US',
currency: 'USD',
name: 'SVB Financial Group',
},
{
source: 'eod',
sourceId: 'SHOP.TO',
isin: 'CA82509L1076',
cusip: '82509L107',
country: 'CA',
currency: 'CAD',
name: 'Shopify Inc.',
},
{
source: 'eod',
sourceId: 'SHOP.US',
isin: 'CA82509L1076',
cusip: '82509L107',
country: 'CA',
currency: 'USD',
name: 'Shopify Inc.',
},
{
source: 'ib',
sourceId: '2001',
isin: 'CA82509L1076',
cusip: '82509L107',
country: 'CA',
currency: 'CAD',
name: 'Shopify Inc.',
},
{
source: 'ib',
sourceId: '2002',
isin: 'CA82509L1076',
cusip: '82509L107',
country: 'CA',
currency: 'USD',
name: 'Shopify Inc.',
},
];
// Spans start as null on EOD/QM to verify attachBarSpansToStageBInput wires them from barSpans.
const eodListings: StageBEodListingInput[] = [
{
sourceId: 'AAPL.US',
ticker: 'AAPL',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
{
sourceId: 'FB_OLD.US',
ticker: 'FB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
{
sourceId: 'FB_ETF.US',
ticker: 'FB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
{
sourceId: 'SIVB.US',
ticker: 'SIVB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
{
sourceId: 'SIVBQ.US',
ticker: 'SIVBQ',
mic: 'OTCM',
role: 'primary_venue',
currency: 'USD',
span: null,
},
{
sourceId: 'SHOP.TO',
ticker: 'SHOP',
mic: 'XTSE',
role: 'primary_venue',
currency: 'CAD',
span: null,
},
{
sourceId: 'SHOP.US',
ticker: 'SHOP',
mic: 'XNYS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
];
const ibContracts: StageBIbContractInput[] = [
{ sourceId: '265598', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ' },
{ sourceId: '2001', conid: 2001, currency: 'CAD', primaryExchange: 'TSE' },
{ sourceId: '2002', conid: 2002, currency: 'USD', primaryExchange: 'NYSE' },
];
const tickerSources: StageBTickerSourceInput[] = [
{
source: 'qm',
sourceId: 'AAPL:US',
ticker: 'AAPL',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
{
source: 'qm',
sourceId: 'FB_OLD:US',
ticker: 'FB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
{
source: 'qm',
sourceId: 'FB_ETF:US',
ticker: 'FB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
{
source: 'qm',
sourceId: 'SHOP:CA',
ticker: 'SHOP',
mic: 'XTSE',
role: 'primary_venue',
currency: 'CAD',
span: null,
},
{
source: 'ceo',
sourceId: 'ceo:SHOP',
ticker: 'SHOP',
mic: 'XTSE',
role: 'primary_venue',
currency: 'CAD',
span: { firstBarDate: '2020-01-02', lastBarDate: '2025-11-28' },
},
];
const barSpans: BarSpan[] = [
{ source: 'eod', sourceId: 'AAPL.US', firstBarDate: '2010-01-04', lastBarDate: '2025-11-28', barCount: 4000 },
{ source: 'eod', sourceId: 'FB_OLD.US', firstBarDate: '2012-05-18', lastBarDate: '2022-06-08', barCount: 2530 },
{ source: 'eod', sourceId: 'FB_ETF.US', firstBarDate: '2025-01-02', lastBarDate: '2025-11-28', barCount: 230 },
{ source: 'eod', sourceId: 'SIVB.US', firstBarDate: '2015-01-02', lastBarDate: '2023-03-10', barCount: 2060 },
{ source: 'eod', sourceId: 'SIVBQ.US', firstBarDate: '2023-03-28', lastBarDate: '2024-11-07', barCount: 410 },
{ source: 'eod', sourceId: 'SHOP.TO', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 },
{ source: 'eod', sourceId: 'SHOP.US', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 },
{ source: 'qm', sourceId: 'AAPL:US', firstBarDate: '2015-01-02', lastBarDate: '2025-11-28', barCount: 2700 },
{ source: 'qm', sourceId: 'FB_OLD:US', firstBarDate: '2014-01-02', lastBarDate: '2022-06-08', barCount: 2100 },
{ source: 'qm', sourceId: 'FB_ETF:US', firstBarDate: '2025-02-03', lastBarDate: '2025-11-28', barCount: 205 },
{ source: 'qm', sourceId: 'SHOP:CA', firstBarDate: '2018-01-02', lastBarDate: '2025-11-28', barCount: 1980 },
];
const securityTypeByIsin = new Map<string, SecurityType>([
['US0378331005', 'common'],
['US30303M1027', 'common'],
['US4642872000', 'etf'],
['US78486Q1013', 'common'],
['CA82509L1076', 'common'],
]);
const exchanges = classifySourceExchanges([
{ source: 'eod', sourceCode: 'NASDAQ', name: 'NASDAQ', country: 'US', operatingMic: 'XNAS' },
{ source: 'eod', sourceCode: 'NYSE', name: 'NYSE', country: 'US', operatingMic: 'XNYS' },
{ source: 'eod', sourceCode: 'TO', name: 'TSX', country: 'CA', operatingMic: 'XTSE' },
{ source: 'eod', sourceCode: 'OTC', name: 'OTC', country: 'US', operatingMic: 'OTCM' },
]);
const dates = [
'2025-01-02',
'2025-01-03',
'2025-01-06',
'2025-01-07',
'2025-01-08',
'2025-01-09',
];
const aaplPrices = [185.0, 188.5, 184.2, 191.0, 195.4, 193.1];
const shopCadPrices = [140.0, 145.0, 138.0, 148.5, 152.0, 149.0];
const sampleCloses: SampleCloseRecord[] = [];
const fxRates: FxRateByDateRecord[] = [];
for (let i = 0; i < dates.length; i++) {
const date = dates[i]!;
const aapl = aaplPrices[i]!;
const shop = shopCadPrices[i]!;
fxRates.push({ date, usdCad: 1.38 + i * 0.005 });
// AAPL: eod vs qm matching closes -> confirmed
sampleCloses.push({ source: 'eod', sourceId: 'AAPL.US', date, close: aapl });
sampleCloses.push({ source: 'qm', sourceId: 'AAPL:US', date, close: aapl * 1.001 });
// SHOP.TO: eod vs qm deliberately 1.5x ratio mismatch -> price_ratio_mismatch
sampleCloses.push({ source: 'eod', sourceId: 'SHOP.TO', date, close: shop });
sampleCloses.push({ source: 'qm', sourceId: 'SHOP:CA', date, close: shop * 1.5 });
// ceo:SHOP also mismatches eod SHOP.TO (2.0x) to exercise two mismatches sharing a left endpoint
sampleCloses.push({ source: 'ceo', sourceId: 'ceo:SHOP', date, close: shop * 2.0 });
}
const input: ComposeSecurityMasterRunInput = {
sources: makeSourcesResult({
stageARecords,
eodListings,
ibContracts,
tickerSources,
securityTypeByIsin,
}),
barSpans,
exchanges,
};
return { input, sampleCloses, fxRates };
}
describe('security-master run composer purity & exports', () => {
test('contains zero I/O imports and zero wall-clock calls', () => {
const src = readFileSync(runSourcePath, 'utf8');
expect(src).not.toMatch(/\bfrom\s+['"](node:)?(fs|net|http|https|pg|mongodb)['"]/);
expect(src).not.toMatch(/\bfrom\s+['"]@stock-bot\/(mongodb|postgres)['"]/);
expect(src).not.toMatch(/\bDate\.now\b/);
expect(src).not.toMatch(/\bnew\s+Date\b/);
expect(src).not.toMatch(/\bperformance\.now\b/);
expect(typeof composeSecurityMasterRun).toBe('function');
expect(typeof attachBarSpansToStageBInput).toBe('function');
expect(typeof derivePass4CandidatePairs).toBe('function');
expect(typeof deriveSourceCountries).toBe('function');
});
});
describe('security-master run composer adapter helpers', () => {
test('attachBarSpansToStageBInput supports BarSpan[], BarSpanIndex, ComputeBarSpansResult, merges duplicates, preserves CEO spans, and skips malformed entries', () => {
const baseStageB: SecurityMasterStageBSourceInput = {
eodListings: [
{ sourceId: 'A.US', ticker: 'A', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null },
{
sourceId: 'B.US',
ticker: 'B',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2020-01-02', lastBarDate: '2020-12-31' },
},
],
ibContracts: [{ sourceId: '101', conid: 101, currency: 'USD', primaryExchange: 'NASDAQ' }],
tickerSources: [
{ source: 'qm', sourceId: 'A:US', ticker: 'A', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null },
{
source: 'ceo',
sourceId: 'ceo:A',
ticker: 'A',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: { firstBarDate: '2021-01-04', lastBarDate: '2024-12-31' },
},
],
symbolChanges: [],
};
const barSpansArray: BarSpan[] = [
{ source: 'eod', sourceId: 'A.US', firstBarDate: '2018-01-02', lastBarDate: '2022-12-30', barCount: 1000 },
{ source: 'eod', sourceId: 'A.US', firstBarDate: '2016-01-04', lastBarDate: '2024-12-31', barCount: 500 },
{ source: 'qm', sourceId: 'A:US', firstBarDate: '2019-01-02', lastBarDate: '2024-12-31', barCount: 1500 },
// Malformed entry (inverted dates)
{ source: 'eod', sourceId: 'BAD.US', firstBarDate: '2025-01-02', lastBarDate: '2024-01-02', barCount: 10 },
];
const fromArray = attachBarSpansToStageBInput(baseStageB, barSpansArray);
expect(fromArray.stats.recordsIn).toBe(4);
expect(fromArray.stats.resolved).toBe(3);
expect(fromArray.stats.skipped).toBe(1);
expect(fromArray.stats.attachedEodListings).toBe(1);
expect(fromArray.stats.attachedQmTickerSources).toBe(1);
// Merged min/max span for A.US
expect(fromArray.stageBInput.eodListings[0]?.span).toEqual({
firstBarDate: '2016-01-04',
lastBarDate: '2024-12-31',
});
// Existing span on B.US preserved when absent from barSpans
expect(fromArray.stageBInput.eodListings[1]?.span).toEqual({
firstBarDate: '2020-01-02',
lastBarDate: '2020-12-31',
});
// QM span attached, CEO span preserved
expect(fromArray.stageBInput.tickerSources[0]?.span).toEqual({
firstBarDate: '2019-01-02',
lastBarDate: '2024-12-31',
});
expect(fromArray.stageBInput.tickerSources[1]?.span).toEqual({
firstBarDate: '2021-01-04',
lastBarDate: '2024-12-31',
});
// Original input not mutated
expect(baseStageB.eodListings[0]?.span).toBeNull();
// BarSpanIndex and ComputeBarSpansResult inputs produce identical spans
const index = new BarSpanIndex();
index.merge(barSpansArray[0]!);
index.merge(barSpansArray[1]!);
index.merge(barSpansArray[2]!);
const fromIndex = attachBarSpansToStageBInput(baseStageB, index);
expect(fromIndex.stageBInput).toEqual(fromArray.stageBInput);
const computeResult: ComputeBarSpansResult = {
index,
bySource: {},
skipped: { invalidId: 0, invalidDate: 0, invalidCount: 0, total: 0 },
totalRowsRead: 3,
totalSpans: index.size,
};
const fromComputeResult = attachBarSpansToStageBInput(baseStageB, computeResult);
expect(fromComputeResult.stageBInput).toEqual(fromArray.stageBInput);
});
test('derivePass4CandidatePairs emits deduplicated ASCII-sorted cross-source pairs per listing', () => {
const key = {
primaryIsin: 'US0378331005',
mic: 'XNAS',
tickerRoot: 'AAPL',
classSuffix: '',
currency: 'USD',
};
const mappings = [
{ source: 'qm' as const, sourceId: 'AAPL:US', listingKey: key, method: 'tier3_ticker_span' as const, validFrom: null, validTo: null },
{ source: 'eod' as const, sourceId: 'AAPL.US', listingKey: key, method: 'tier1_isin' as const, validFrom: null, validTo: null },
{ source: 'eod' as const, sourceId: 'AAPL_DUP.US', listingKey: key, method: 'tier1_isin' as const, validFrom: null, validTo: null },
{ source: 'ib' as const, sourceId: '265598', listingKey: key, method: 'tier1_isin' as const, validFrom: null, validTo: null },
];
const pairsA = derivePass4CandidatePairs(mappings);
const pairsB = derivePass4CandidatePairs([...mappings].reverse());
expect(pairsA).toEqual(pairsB);
// Same-source pair (eod, eod) must never be emitted
for (const pair of pairsA) {
expect(pair.left.source).not.toBe(pair.right.source);
}
// 2 eod * 1 ib + 2 eod * 1 qm + 1 ib * 1 qm = 5 cross-source pairs
expect(pairsA.length).toBe(5);
});
test('deriveSourceCountries resolves MIC countries with Stage A fallback deterministically', () => {
const stageARecords: StageASourceRecord[] = [
{ source: 'ib', sourceId: '265598', isin: 'US0378331005', country: 'US' },
{ source: 'eod', sourceId: 'SHOP.TO', isin: 'CA82509L1076', country: 'CA' },
];
const stageBInput = {
eodListings: [
{ sourceId: 'SHOP.TO', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue' as const, currency: 'CAD', span: null },
],
tickerSources: [
{ source: 'qm' as const, sourceId: 'SHOP:CA', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue' as const, currency: 'CAD', span: null },
],
};
const countries = deriveSourceCountries(stageARecords, stageBInput, { providerMappings: [] });
expect(countries.get('ib:265598')).toBe('US');
expect(countries.get('eod:SHOP.TO')).toBe('CA');
expect(countries.get('qm:SHOP:CA')).toBe('CA');
});
});
describe('composeSecurityMasterRun', () => {
test('resolves FB common vs FB ETF to two distinct instruments and listings, chains SIVB -> SIVBQ, and attaches IB + interlisted SHOP', () => {
const { input } = buildCanonicalFixture();
const result = composeSecurityMasterRun(input, { asOfDate: '2025-11-28' });
// FB common (US30303M1027) vs FB ETF (US4642872000)
const fbListings = result.stageB.listings.filter(l => l.tickerRoot === 'FB');
expect(fbListings.length).toBe(2);
const fbKeys = fbListings.map(l => formatListingNaturalKey(l));
expect(new Set(fbKeys).size).toBe(2);
expect(new Set(fbListings.map(l => l.primaryIsin))).toEqual(
new Set(['US30303M1027', 'US4642872000'])
);
expect(result.persistInput.stageA.instruments.filter(i => i.primaryIsin === 'US30303M1027' || i.primaryIsin === 'US4642872000').length).toBe(2);
expect(result.persistInput.securityTypeByIsin.get('US30303M1027')).toBe('common');
expect(result.persistInput.securityTypeByIsin.get('US4642872000')).toBe('etf');
// QM FB_OLD:US -> US30303M1027, QM FB_ETF:US -> US4642872000
const qmFbOld = result.stageB.providerMappings.find(m => m.source === 'qm' && m.sourceId === 'FB_OLD:US');
const qmFbEtf = result.stageB.providerMappings.find(m => m.source === 'qm' && m.sourceId === 'FB_ETF:US');
expect(qmFbOld?.listingKey.primaryIsin).toBe('US30303M1027');
expect(qmFbEtf?.listingKey.primaryIsin).toBe('US4642872000');
// SIVB -> SIVBQ OTC continuity
expect(result.pass6.continuities.length).toBe(1);
const continuity = result.pass6.continuities[0]!;
expect(continuity.fromListingKey.tickerRoot).toBe('SIVB');
expect(continuity.fromListingKey.mic).toBe('XNAS');
expect(continuity.toListingKey.tickerRoot).toBe('SIVBQ');
expect(continuity.toListingKey.mic).toBe('OTCM');
expect(continuity.kind).toBe(CONTINUITY_KIND_OTC_DELIST_TRANSFER);
expect(result.persistInput.pass6?.continuities).toEqual(result.pass6.continuities);
expect(result.report.delistingChains?.continuitiesCreated).toBe(1);
expect(result.reportMarkdown).toContain('- Continuities Created: 1');
// Interlisted SHOP (CA82509L1076) -> 1 instrument, 2 listings (CAD + USD), IB attached at (instrument, currency)
const shopInstruments = result.stageA.instruments.filter(i => i.primaryIsin === 'CA82509L1076');
expect(shopInstruments.length).toBe(1);
const shopListings = result.stageB.listings.filter(l => l.primaryIsin === 'CA82509L1076');
expect(shopListings.length).toBe(2);
const shopCad = shopListings.find(l => l.currency === 'CAD');
const shopUsd = shopListings.find(l => l.currency === 'USD');
expect(shopCad?.mic).toBe('XTSE');
expect(shopCad?.ibConid).toBe(2001);
expect(shopUsd?.mic).toBe('XNYS');
expect(shopUsd?.ibConid).toBe(2002);
// IB AAPL attached at (US0378331005, USD)
const aaplListing = result.stageB.listings.find(l => l.primaryIsin === 'US0378331005');
expect(aaplListing?.ibConid).toBe(265598);
});
test('Pass 4 supplied confirms matching pairs and emits price_ratio_mismatch into report, CSV, SQL, and persistInput; omitted marks Pass 4 skipped', () => {
const { input, sampleCloses, fxRates } = buildCanonicalFixture();
// 1. Omitted sampleCloses -> Pass 4 skipped (never reported as passed)
const skippedRun = composeSecurityMasterRun(input, { asOfDate: '2025-11-28' });
expect(skippedRun.pass4).toBeNull();
expect(skippedRun.persistInput.pass4).toBeUndefined();
expect(skippedRun.stats.pass4.status).toBe('skipped');
expect(skippedRun.stats.pass4.resolved).toBe(0);
expect(skippedRun.stats.pass4.skipped).toBe(skippedRun.pass4CandidatePairs.length);
expect(skippedRun.report.priceCrossCheck).toBeNull();
expect(skippedRun.report.conflicts.filter(c => c.pass === 'pass4').length).toBe(0);
expect(skippedRun.reportMarkdown).toContain('- Status: skipped (no sample closes supplied)');
// 2. Supplied sampleCloses + fxRates -> AAPL confirmed, SHOP mismatches emitted everywhere
const suppliedRun = composeSecurityMasterRun(
{ ...input, sampleCloses, fxRates },
{ asOfDate: '2025-11-28' }
);
expect(suppliedRun.pass4).not.toBeNull();
expect(suppliedRun.persistInput.pass4).toBe(suppliedRun.pass4);
expect(suppliedRun.stats.pass4.status).toBe('executed');
expect(suppliedRun.reportMarkdown).not.toContain('Status: skipped');
const aaplRow = suppliedRun.pass4!.results.find(
r => r.left.sourceId === 'AAPL.US' && r.right.sourceId === 'AAPL:US'
);
expect(aaplRow?.verdict).toBe('confirmed');
const pass4Conflicts = suppliedRun.pass4!.conflicts;
expect(pass4Conflicts.length).toBeGreaterThanOrEqual(2);
expect(pass4Conflicts.every(c => c.conflictKind === 'price_ratio_mismatch')).toBe(true);
expect(suppliedRun.report.conflicts.filter(c => c.pass === 'pass4').length).toBe(
pass4Conflicts.length
);
expect(suppliedRun.conflictsCsv).toContain('price_ratio_mismatch');
expect(suppliedRun.overrideTemplateSql).toContain('price_ratio_mismatch');
expect(suppliedRun.persistInput.pass4?.conflicts).toEqual(pass4Conflicts);
});
test('produces byte-identical Markdown, CSV, override SQL, and deep-equal persistInput under shuffled inputs', () => {
const { input, sampleCloses, fxRates } = buildCanonicalFixture();
const baseline = composeSecurityMasterRun(
{ ...input, sampleCloses, fxRates },
{ asOfDate: '2025-11-28' }
);
const shuffledSecTypes = new Map<string, SecurityType>(
shuffleWithSeed(Array.from(input.sources.securityTypeByIsin.entries()), 77)
);
const shuffledInput: ComposeSecurityMasterRunInput = {
sources: makeSourcesResult({
stageARecords: shuffleWithSeed(input.sources.stageARecords, 11),
eodListings: shuffleWithSeed(input.sources.stageBInput.eodListings, 22),
ibContracts: shuffleWithSeed(input.sources.stageBInput.ibContracts, 33),
tickerSources: shuffleWithSeed(input.sources.stageBInput.tickerSources, 44),
symbolChanges: shuffleWithSeed(input.sources.stageBInput.symbolChanges, 55),
securityTypeByIsin: shuffledSecTypes,
}),
barSpans: shuffleWithSeed(input.barSpans as readonly BarSpan[], 66),
exchanges: input.exchanges,
sampleCloses: shuffleWithSeed(sampleCloses, 88),
fxRates: shuffleWithSeed(fxRates, 99),
};
const shuffled = composeSecurityMasterRun(shuffledInput, { asOfDate: '2025-11-28' });
expect(shuffled.reportMarkdown).toBe(baseline.reportMarkdown);
expect(shuffled.conflictsCsv).toBe(baseline.conflictsCsv);
expect(shuffled.overrideTemplateSql).toBe(baseline.overrideTemplateSql);
expect(shuffled.persistInput).toEqual(baseline.persistInput);
expect(Array.from(shuffled.persistInput.securityTypeByIsin.entries())).toEqual(
Array.from(baseline.persistInput.securityTypeByIsin.entries())
);
expect(shuffled.stats).toEqual(baseline.stats);
});
test('reconciles per-step stats and conflict totals while counting malformed/sparse records without throwing', () => {
const { input, sampleCloses, fxRates } = buildCanonicalFixture();
// Add a Stage A conflict (isin_cusip_mismatch) so conflicts come from multiple passes
const stageARecords: StageASourceRecord[] = [
...input.sources.stageARecords,
{
source: 'eod',
sourceId: 'CONFLICT_A.US',
isin: 'US0378331005',
cusip: '594918104',
country: 'US',
currency: 'USD',
name: 'Conflict Co',
},
// Malformed Stage A records
null as unknown as StageASourceRecord,
{ source: 'bogus' as 'eod', sourceId: 'X.US' },
{ source: 'eod', sourceId: '' },
];
// Sparse slot
stageARecords.length += 1;
const eodListings: StageBEodListingInput[] = [
...input.sources.stageBInput.eodListings,
null as unknown as StageBEodListingInput,
{ sourceId: 'BAD_ROLE.US', ticker: 'BR', mic: 'XNAS', role: 'invalid_role' as 'primary_venue', currency: 'USD', span: null },
];
const ibContracts: StageBIbContractInput[] = [
...input.sources.stageBInput.ibContracts,
{ sourceId: '', conid: 999, currency: 'USD', primaryExchange: 'NASDAQ' },
];
const tickerSources: StageBTickerSourceInput[] = [
...input.sources.stageBInput.tickerSources,
{ source: 'unknown' as 'qm', sourceId: 'U:US', ticker: 'U', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null },
];
const symbolChanges: StageBSymbolChangeInput[] = [
{ eodSourceId: '', oldTicker: 'OLD', effectiveDate: '2022-01-01' },
{ eodSourceId: 'AAPL.US', oldTicker: 'AAPL_OLD', effectiveDate: 'not-a-date' },
{ eodSourceId: 'AAPL.US', oldTicker: 'AAPL_OLD', effectiveDate: '2022-01-01', validFrom: '2023-01-01' },
];
const barSpans: BarSpan[] = [
...(input.barSpans as readonly BarSpan[]),
null as unknown as BarSpan,
{ source: 'eod', sourceId: 'NEG.US', firstBarDate: '2020-01-02', lastBarDate: '2020-12-31', barCount: -5 },
];
const badCloses: SampleCloseRecord[] = [
...sampleCloses,
{ source: 'eod', sourceId: 'AAPL.US', date: 'bad-date', close: 100 },
{ source: 'eod', sourceId: 'AAPL.US', date: '2025-01-02', close: -1 },
];
const badFx: FxRateByDateRecord[] = [
...fxRates,
{ date: '2025-01-02', usdCad: 0 },
];
const result = composeSecurityMasterRun(
{
sources: makeSourcesResult({
stageARecords,
eodListings,
ibContracts,
tickerSources,
symbolChanges,
securityTypeByIsin: input.sources.securityTypeByIsin,
}),
barSpans,
exchanges: input.exchanges,
sampleCloses: badCloses,
fxRates: badFx,
},
{ asOfDate: '2025-11-28' }
);
// Every step reconciles: recordsIn === resolved + unresolved + skipped
const { stats } = result;
expect(stats.barSpans.recordsIn).toBe(
stats.barSpans.resolved + stats.barSpans.unresolved + stats.barSpans.skipped
);
expect(stats.stageA.recordsIn).toBe(
stats.stageA.resolved + stats.stageA.unresolved + stats.stageA.skipped
);
expect(stats.stageB.recordsIn).toBe(
stats.stageB.resolved + stats.stageB.unresolved + stats.stageB.skipped
);
expect(stats.pass6.recordsIn).toBe(
stats.pass6.resolved + stats.pass6.unresolved + stats.pass6.skipped
);
expect(stats.pass4.recordsIn).toBe(
stats.pass4.resolved + stats.pass4.unresolved + stats.pass4.skipped
);
// Malformed counts surfaced accurately
expect(stats.malformedInputs.stageARecords).toBe(4); // null + bogus source + empty sourceId + sparse slot
expect(stats.malformedInputs.eodListings).toBe(2);
expect(stats.malformedInputs.ibContracts).toBe(1);
expect(stats.malformedInputs.tickerSources).toBe(1);
expect(stats.malformedInputs.symbolChanges).toBe(3);
expect(stats.malformedInputs.barSpans).toBe(2);
expect(stats.malformedInputs.sampleCloses).toBe(2);
expect(stats.malformedInputs.fxRates).toBe(1);
expect(stats.malformedInputs.total).toBe(16);
// Conflict totals reconcile with report.conflicts.length
expect(stats.conflicts.stageA).toBe(1);
expect(stats.conflicts.pass4).toBeGreaterThanOrEqual(2);
expect(stats.conflicts.total).toBe(
stats.conflicts.stageA +
stats.conflicts.stageB +
stats.conflicts.pass4 +
stats.conflicts.pass6
);
expect(result.report.conflicts.length).toBe(stats.conflicts.total);
});
test('composes a fixed-seed 100,000-record synthetic workload end to end above the sandbox throughput floor', () => {
// 50,000 EOD + 25,000 IB + 25,000 QM = 100,000 source records
const numInstruments = 50_000;
const numIb = 25_000;
const numQm = 25_000;
const totalSourceRecords = numInstruments + numIb + numQm;
const stageARecords: StageASourceRecord[] = new Array(numInstruments + numIb);
const eodListings: StageBEodListingInput[] = new Array(numInstruments);
const ibContracts: StageBIbContractInput[] = new Array(numIb);
const tickerSources: StageBTickerSourceInput[] = new Array(numQm);
const barSpans: BarSpan[] = new Array(numInstruments + numQm);
const securityTypeByIsin = new Map<string, SecurityType>();
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let stageAIdx = 0;
let spanIdx = 0;
for (let i = 0; i < numInstruments; i++) {
// Deterministic valid US ISIN via cusipToIsin (9-char CUSIP: 6-digit issuer + 2-char issue + check)
// Construct a valid 9-char CUSIP using cusipToIsin after computing CUSIP check digit, or direct ISIN:
const base8 = `A${String(i).padStart(7, '0')}`;
// Compute CUSIP check digit (Luhn mod 10 over A=10..Z=35)
let sum = 0;
for (let pos = 0; pos < 8; pos++) {
const ch = base8.charCodeAt(pos);
let v = ch >= 65 ? ch - 55 : ch - 48;
if (pos % 2 === 1) {
v *= 2;
}
sum += Math.floor(v / 10) + (v % 10);
}
const checkDigit = (10 - (sum % 10)) % 10;
const cusip = `${base8}${checkDigit}`;
const isin = cusipToIsin(cusip, 'US')!;
// Unique 4-letter ticker from i
const c0 = alphabet[Math.floor(i / (26 * 26 * 26)) % 26]!;
const c1 = alphabet[Math.floor(i / (26 * 26)) % 26]!;
const c2 = alphabet[Math.floor(i / 26) % 26]!;
const c3 = alphabet[i % 26]!;
const ticker = `${c0}${c1}${c2}${c3}`;
const eodId = `${ticker}.US`;
stageARecords[stageAIdx++] = {
source: 'eod',
sourceId: eodId,
isin,
cusip,
country: 'US',
currency: 'USD',
name: `Bench Corp ${i}`,
};
eodListings[i] = {
sourceId: eodId,
ticker,
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
};
barSpans[spanIdx++] = {
source: 'eod',
sourceId: eodId,
firstBarDate: '2018-01-02',
lastBarDate: '2025-11-28',
barCount: 1980,
};
securityTypeByIsin.set(isin, 'common');
if (i < numIb) {
const ibId = String(1_000_000 + i);
stageARecords[stageAIdx++] = {
source: 'ib',
sourceId: ibId,
isin,
cusip,
country: 'US',
currency: 'USD',
name: `Bench Corp ${i}`,
};
ibContracts[i] = {
sourceId: ibId,
conid: 1_000_000 + i,
currency: 'USD',
primaryExchange: 'NASDAQ',
};
}
if (i < numQm) {
const qmId = `${ticker}:US`;
tickerSources[i] = {
source: 'qm',
sourceId: qmId,
ticker,
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
};
barSpans[spanIdx++] = {
source: 'qm',
sourceId: qmId,
firstBarDate: '2020-01-02',
lastBarDate: '2025-11-28',
barCount: 1480,
};
}
}
const sources = makeSourcesResult({
stageARecords,
eodListings,
ibContracts,
tickerSources,
securityTypeByIsin,
});
const startMs = performance.now();
const result = composeSecurityMasterRun(
{ sources, barSpans },
{ asOfDate: '2025-11-28' }
);
const elapsedMs = performance.now() - startMs;
const recordsPerSec = totalSourceRecords / (elapsedMs / 1000);
expect(totalSourceRecords).toBe(100_000);
expect(result.stageA.instruments.length).toBe(numInstruments);
expect(result.stageB.listings.length).toBe(numInstruments);
expect(result.stageB.providerMappings.length).toBe(totalSourceRecords);
expect(result.stats.stageA.recordsIn).toBe(
result.stats.stageA.resolved + result.stats.stageA.unresolved + result.stats.stageA.skipped
);
expect(result.stats.stageB.recordsIn).toBe(
result.stats.stageB.resolved + result.stats.stageB.unresolved + result.stats.stageB.skipped
);
expect(result.stats.pass4.status).toBe('skipped');
// Assert conservative sandbox throughput floor (>= 10,000 records/s)
expect(recordsPerSec).toBeGreaterThanOrEqual(10_000);
});
});