T-88: M1.1m — Security-master run composer: readers output + bar spans → Stage A → Stage B → Pass 6 → Pass 4 → match report + persist input (pure, in-memory, no new dependencies)

This commit is contained in:
Studio 2026-11-28 05:54:45 -05:00
parent 8ccca45174
commit bd8ddab1a2
3 changed files with 886 additions and 11 deletions

View file

@ -14,6 +14,7 @@ import {
CONTINUITY_KIND_OTC_DELIST_TRANSFER,
derivePass4CandidatePairs,
deriveSourceCountries,
filterSampleClosesByMappingBounds,
formatListingNaturalKey,
type ComposeSecurityMasterRunInput,
type FxRateByDateRecord,
@ -810,6 +811,500 @@ describe('composeSecurityMasterRun', () => {
expect(result.report.conflicts.length).toBe(stats.conflicts.total);
});
test('fails the 95% equity-resolution gate when Stage A rejects >5% of eligible EOD records despite 100% Stage B coverage', () => {
const stageARecords: StageASourceRecord[] = [];
const eodListings: StageBEodListingInput[] = [];
const barSpans: BarSpan[] = [];
const securityTypeByIsin = new Map<string, SecurityType>();
// 90 valid in-scope EOD equities that all pass Stage A and match in Stage B (100% Stage B)
for (let i = 0; i < 90; i++) {
const base8 = `B${String(i).padStart(7, '0')}`;
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 cusip = `${base8}${(10 - (sum % 10)) % 10}`;
const isin = cusipToIsin(cusip, 'US')!;
const ticker = `E${String(i).padStart(3, '0')}`;
const sourceId = `${ticker}.US`;
stageARecords.push({
source: 'eod',
sourceId,
isin,
cusip,
country: 'US',
currency: 'USD',
name: `Equity ${i}`,
});
eodListings.push({
sourceId,
ticker,
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
});
barSpans.push({
source: 'eod',
sourceId,
firstBarDate: '2020-01-02',
lastBarDate: '2025-11-28',
barCount: 1500,
});
securityTypeByIsin.set(isin, 'common');
}
// 10 in-scope EOD equities lacking usable identifiers (rejected by Stage A, never reach Stage B)
for (let i = 0; i < 10; i++) {
const ticker = `N${String(i).padStart(3, '0')}`;
const sourceId = `${ticker}.US`;
stageARecords.push({
source: 'eod',
sourceId,
isin: null,
cusip: null,
country: 'US',
currency: 'USD',
name: `NoId Equity ${i}`,
});
eodListings.push({
sourceId,
ticker,
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
});
}
// 5 excluded_fund EOD records also lacking identifiers (must be excludedByDesign, not penalizing eligibleTotal)
for (let i = 0; i < 5; i++) {
const ticker = `F${String(i).padStart(3, '0')}`;
const sourceId = `${ticker}.US`;
stageARecords.push({
source: 'eod',
sourceId,
isin: null,
cusip: null,
country: 'US',
currency: 'USD',
name: `Mutual Fund ${i}`,
});
eodListings.push({
sourceId,
ticker,
mic: 'XNAS',
role: 'excluded_fund',
currency: 'USD',
span: null,
});
}
const sources = makeSourcesResult({
stageARecords,
eodListings,
ibContracts: [],
tickerSources: [],
securityTypeByIsin,
});
const result = composeSecurityMasterRun({ sources, barSpans }, { asOfDate: '2025-11-28' });
// Stage B itself saw 90/90 matched (100%), but end-to-end eligible coverage is 90/100 (90%)
expect(result.stageB.stats.bySource.eod.total).toBe(90);
expect(result.stageB.stats.bySource.eod.matched).toBe(90);
const eodRow = result.report.resolutionBySource.find(r => r.source === 'eod');
expect(eodRow).toBeDefined();
expect(eodRow?.total).toBe(105);
expect(eodRow?.matched).toBe(90);
expect(eodRow?.unresolved).toBe(15);
expect(eodRow?.conflict).toBe(0);
expect(eodRow?.excludedByDesign).toBe(5);
expect(eodRow?.eligibleTotal).toBe(100);
expect(eodRow?.eligibleResolvedPct).toBeCloseTo(0.9, 10);
expect(result.report.meetsExitThresholds.equitiesResolved95).toBe(false);
expect(result.reportMarkdown).toContain('| Equities Resolved (Eligible) | FAIL | >= 95.00% |');
const usRow = result.report.resolutionByCountry.find(r => r.country === 'US');
expect(usRow?.eligibleTotal).toBe(100);
expect(usRow?.matched).toBe(90);
expect(usRow?.eligibleResolvedPct).toBeCloseTo(0.9, 10);
// Duplicate sourceId in both stageARecords (2 rows) and eodListings (2 rows) must not be counted 3 times
const dupSources = makeSourcesResult({
stageARecords: [
{
source: 'eod',
sourceId: 'DUP.US',
isin: 'US0378331005',
country: 'US',
currency: 'USD',
name: 'Dup A',
},
{
source: 'eod',
sourceId: 'DUP.US',
isin: 'US0378331005',
country: 'US',
currency: 'USD',
name: 'Dup B',
},
],
eodListings: [
{
sourceId: 'DUP.US',
ticker: 'DUP',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
{
sourceId: 'DUP.US',
ticker: 'DUP',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
],
ibContracts: [],
tickerSources: [],
securityTypeByIsin: new Map([['US0378331005', 'common']]),
});
const dupResult = composeSecurityMasterRun({ sources: dupSources }, { asOfDate: '2025-11-28' });
const dupEodRow = dupResult.report.resolutionBySource.find(r => r.source === 'eod');
expect(dupEodRow?.total).toBe(2);
expect(dupEodRow?.conflict).toBe(2);
expect(dupResult.report.meetsExitThresholds.equitiesResolved95).toBe(false);
});
test('restricts Pass 4 sample closes to Stage B mapping validity windows on reused tickers', () => {
const sources = makeSourcesResult({
stageARecords: [
{
source: 'eod',
sourceId: 'META.US',
isin: 'US30303M1027',
cusip: '30303M102',
country: 'US',
currency: 'USD',
name: 'Meta Platforms Inc.',
},
],
eodListings: [
{
sourceId: 'META.US',
ticker: 'META',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
],
ibContracts: [],
tickerSources: [
{
source: 'qm',
sourceId: 'FB:US',
ticker: 'FB',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
],
symbolChanges: [
{
eodSourceId: 'META.US',
oldTicker: 'FB',
effectiveDate: '2022-06-09',
},
],
securityTypeByIsin: new Map([['US30303M1027', 'common']]),
});
const barSpans: BarSpan[] = [
{
source: 'eod',
sourceId: 'META.US',
firstBarDate: '2012-05-18',
lastBarDate: '2025-11-28',
barCount: 3400,
},
{
source: 'qm',
sourceId: 'FB:US',
firstBarDate: '2012-05-18',
lastBarDate: '2025-11-28',
barCount: 3400,
},
];
// 2 matching closes before rename (too few for minCommonDates=5) + 5 mismatched post-rename closes
const postRenameMismatchedCloses: SampleCloseRecord[] = [
{ source: 'eod', sourceId: 'META.US', date: '2025-03-03', close: 650.0 },
{ source: 'qm', sourceId: 'FB:US', date: '2025-03-03', close: 25.0 },
{ source: 'eod', sourceId: 'META.US', date: '2025-03-04', close: 655.0 },
{ source: 'qm', sourceId: 'FB:US', date: '2025-03-04', close: 25.5 },
{ source: 'eod', sourceId: 'META.US', date: '2025-03-05', close: 660.0 },
{ source: 'qm', sourceId: 'FB:US', date: '2025-03-05', close: 24.8 },
{ source: 'eod', sourceId: 'META.US', date: '2025-03-06', close: 645.0 },
{ source: 'qm', sourceId: 'FB:US', date: '2025-03-06', close: 25.1 },
{ source: 'eod', sourceId: 'META.US', date: '2025-03-07', close: 670.0 },
{ source: 'qm', sourceId: 'FB:US', date: '2025-03-07', close: 26.0 },
];
const twoPreRenameCloses: SampleCloseRecord[] = [
{ source: 'eod', sourceId: 'META.US', date: '2022-05-02', close: 211.13 },
{ source: 'qm', sourceId: 'FB:US', date: '2022-05-02', close: 211.15 },
{ source: 'eod', sourceId: 'META.US', date: '2022-05-03', close: 212.03 },
{ source: 'qm', sourceId: 'FB:US', date: '2022-05-03', close: 212.0 },
];
const insufficientResult = composeSecurityMasterRun(
{
sources,
barSpans,
sampleCloses: [...twoPreRenameCloses, ...postRenameMismatchedCloses],
},
{ asOfDate: '2025-11-28' }
);
const qmMapping = insufficientResult.stageB.providerMappings.find(
m => m.source === 'qm' && m.sourceId === 'FB:US'
);
expect(qmMapping?.validTo).toBe('2022-06-08');
expect(insufficientResult.pass4).not.toBeNull();
expect(insufficientResult.pass4?.results.length).toBe(1);
expect(insufficientResult.pass4?.results[0]?.verdict).toBe('insufficient_data');
expect(insufficientResult.pass4?.results[0]?.usableDates).toBe(2);
expect(insufficientResult.pass4?.conflicts.length).toBe(0);
// 5 matching closes inside the valid window + 5 mismatched post-rename closes -> confirmed, 0 conflicts
const fivePreRenameCloses: SampleCloseRecord[] = [
...twoPreRenameCloses,
{ source: 'eod', sourceId: 'META.US', date: '2022-05-04', close: 223.41 },
{ source: 'qm', sourceId: 'FB:US', date: '2022-05-04', close: 223.4 },
{ source: 'eod', sourceId: 'META.US', date: '2022-05-05', close: 208.28 },
{ source: 'qm', sourceId: 'FB:US', date: '2022-05-05', close: 208.3 },
{ source: 'eod', sourceId: 'META.US', date: '2022-05-06', close: 203.77 },
{ source: 'qm', sourceId: 'FB:US', date: '2022-05-06', close: 203.75 },
];
const confirmedResult = composeSecurityMasterRun(
{
sources,
barSpans,
sampleCloses: [...fivePreRenameCloses, ...postRenameMismatchedCloses],
},
{ asOfDate: '2025-11-28' }
);
expect(confirmedResult.pass4?.results[0]?.verdict).toBe('confirmed');
expect(confirmedResult.pass4?.results[0]?.usableDates).toBe(5);
expect(confirmedResult.pass4?.conflicts.length).toBe(0);
// Direct helper check: malformed closes pass through so crossCheckPrices counts droppedInvalidCloses
const filtered = filterSampleClosesByMappingBounds(insufficientResult.stageB.providerMappings, [
{ source: 'qm', sourceId: 'FB:US', date: '2022-06-08', close: 195.0 },
{ source: 'qm', sourceId: 'FB:US', date: '2022-06-09', close: 25.0 },
{ source: 'qm', sourceId: 'FB:US', date: 'bad-date', close: 10.0 },
]);
expect(filtered.map(c => c.date)).toEqual(['2022-06-08', 'bad-date']);
});
test('rejects zero-bar spans as malformed and prevents a zero-bar OTC span from establishing continuity', () => {
const sources = makeSourcesResult({
stageARecords: [
{
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 OTC',
},
],
eodListings: [
{
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,
},
],
ibContracts: [],
tickerSources: [],
securityTypeByIsin: new Map([['US78486Q1013', 'common']]),
});
const barSpans: BarSpan[] = [
{
source: 'eod',
sourceId: 'SIVB.US',
firstBarDate: '2015-01-02',
lastBarDate: '2023-03-10',
barCount: 2050,
},
{
source: 'eod',
sourceId: 'SIVBQ.US',
firstBarDate: '2023-03-28',
lastBarDate: '2024-11-07',
barCount: 0,
},
];
const result = composeSecurityMasterRun({ sources, barSpans }, { asOfDate: '2025-11-28' });
expect(result.stats.barSpans.recordsIn).toBe(2);
expect(result.stats.barSpans.resolved).toBe(1);
expect(result.stats.barSpans.unresolved).toBe(0);
expect(result.stats.barSpans.skipped).toBe(1);
expect(result.stats.barSpans.indexedSpans).toBe(1);
expect(result.stats.malformedInputs.barSpans).toBe(1);
const sivbqListing = result.stageB.listings.find(l => l.tickerRoot === 'SIVBQ');
expect(sivbqListing?.listedFrom).toBeNull();
expect(sivbqListing?.listedTo).toBeNull();
expect(result.pass6.continuities.length).toBe(0);
});
test('carries through totalRowsRead and skipped.total from ComputeBarSpansResult and separates accepted rows from distinct indexed spans', () => {
const index = new BarSpanIndex();
for (let i = 0; i < 99; i++) {
index.merge({
source: 'eod',
sourceId: `SYM${i}.US`,
firstBarDate: '2020-01-02',
lastBarDate: '2025-11-28',
barCount: 1000,
});
}
// Merge one duplicate row into an existing span: 100 accepted rows -> 99 distinct indexed spans
index.merge({
source: 'eod',
sourceId: 'SYM0.US',
firstBarDate: '2019-01-02',
lastBarDate: '2025-11-28',
barCount: 250,
});
const readerResult: ComputeBarSpansResult = {
index,
bySource: {
eod: {
source: 'eod',
collection: 'eodPrices',
batchesRun: 1,
rowsRead: 101,
spansIndexed: 99,
skipped: { invalidId: 0, invalidDate: 1, invalidCount: 0, total: 1 },
},
},
skipped: { invalidId: 0, invalidDate: 1, invalidCount: 0, total: 1 },
totalRowsRead: 101,
totalSpans: 99,
};
const attached = attachBarSpansToStageBInput(
{
eodListings: [
{
sourceId: 'SYM0.US',
ticker: 'SYM0',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
],
ibContracts: [],
tickerSources: [],
symbolChanges: [],
},
readerResult
);
expect(attached.stats.recordsIn).toBe(101);
expect(attached.stats.resolved).toBe(100);
expect(attached.stats.unresolved).toBe(0);
expect(attached.stats.skipped).toBe(1);
expect(attached.stats.indexedSpans).toBe(99);
expect(attached.stats.recordsIn).toBe(
attached.stats.resolved + attached.stats.unresolved + attached.stats.skipped
);
expect(attached.malformed.barSpans).toBe(1);
expect(attached.stageBInput.eodListings[0]?.span).toEqual({
firstBarDate: '2019-01-02',
lastBarDate: '2025-11-28',
});
const sources = makeSourcesResult({
stageARecords: [
{
source: 'eod',
sourceId: 'SYM0.US',
isin: 'US0378331005',
country: 'US',
currency: 'USD',
name: 'Sym Zero',
},
],
eodListings: [
{
sourceId: 'SYM0.US',
ticker: 'SYM0',
mic: 'XNAS',
role: 'primary_venue',
currency: 'USD',
span: null,
},
],
ibContracts: [],
tickerSources: [],
securityTypeByIsin: new Map([['US0378331005', 'common']]),
});
const composed = composeSecurityMasterRun(
{ sources, barSpans: readerResult },
{ asOfDate: '2025-11-28' }
);
expect(composed.stats.barSpans.recordsIn).toBe(101);
expect(composed.stats.barSpans.resolved).toBe(100);
expect(composed.stats.barSpans.skipped).toBe(1);
expect(composed.stats.barSpans.indexedSpans).toBe(99);
expect(composed.stats.malformedInputs.barSpans).toBe(1);
});
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;