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:
parent
8ccca45174
commit
bd8ddab1a2
3 changed files with 886 additions and 11 deletions
|
|
@ -196,6 +196,7 @@ export {
|
|||
composeSecurityMasterRun,
|
||||
derivePass4CandidatePairs,
|
||||
deriveSourceCountries,
|
||||
filterSampleClosesByMappingBounds,
|
||||
type AttachBarSpansMalformedCounts,
|
||||
type AttachBarSpansResult,
|
||||
type BarSpansStepStats,
|
||||
|
|
|
|||
|
|
@ -45,9 +45,11 @@ import {
|
|||
renderMatchReportMarkdown,
|
||||
sourceCountryKey,
|
||||
type BuildMatchReportOptions,
|
||||
type CountryResolutionSummary,
|
||||
type MatchReport,
|
||||
type RenderMatchReportMarkdownOptions,
|
||||
type SourceCountryLookup,
|
||||
type SourceResolutionSummary,
|
||||
} from './match-report';
|
||||
import {
|
||||
formatListingNaturalKey,
|
||||
|
|
@ -106,6 +108,7 @@ export interface ReconcilingStepStats {
|
|||
}
|
||||
|
||||
export interface BarSpansStepStats extends ReconcilingStepStats {
|
||||
readonly indexedSpans: number;
|
||||
readonly attachedEodListings: number;
|
||||
readonly attachedQmTickerSources: number;
|
||||
}
|
||||
|
|
@ -219,9 +222,10 @@ function normalizeObservedBarSpans(barSpans: ObservedBarSpansInput | null | unde
|
|||
readonly recordsIn: number;
|
||||
readonly resolved: number;
|
||||
readonly skipped: number;
|
||||
readonly indexedSpans: number;
|
||||
} {
|
||||
if (barSpans === undefined || barSpans === null) {
|
||||
return { lookup: null, recordsIn: 0, resolved: 0, skipped: 0 };
|
||||
return { lookup: null, recordsIn: 0, resolved: 0, skipped: 0, indexedSpans: 0 };
|
||||
}
|
||||
|
||||
if (barSpans instanceof BarSpanIndex) {
|
||||
|
|
@ -230,6 +234,7 @@ function normalizeObservedBarSpans(barSpans: ObservedBarSpansInput | null | unde
|
|||
recordsIn: barSpans.size,
|
||||
resolved: barSpans.size,
|
||||
skipped: 0,
|
||||
indexedSpans: barSpans.size,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -253,7 +258,7 @@ function normalizeObservedBarSpans(barSpans: ObservedBarSpansInput | null | unde
|
|||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
if (typeof rec.sourceId !== 'string' || rec.sourceId.length === 0) {
|
||||
if (typeof rec.sourceId !== 'string' || rec.sourceId.trim().length === 0) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
|
@ -266,7 +271,7 @@ function normalizeObservedBarSpans(barSpans: ObservedBarSpansInput | null | unde
|
|||
if (
|
||||
typeof rec.barCount !== 'number' ||
|
||||
!Number.isSafeInteger(rec.barCount) ||
|
||||
rec.barCount < 0
|
||||
rec.barCount <= 0
|
||||
) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
|
|
@ -286,6 +291,7 @@ function normalizeObservedBarSpans(barSpans: ObservedBarSpansInput | null | unde
|
|||
recordsIn: barSpans.length,
|
||||
resolved,
|
||||
skipped,
|
||||
indexedSpans: index.size,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -294,11 +300,30 @@ function normalizeObservedBarSpans(barSpans: ObservedBarSpansInput | null | unde
|
|||
'index' in barSpans &&
|
||||
barSpans.index instanceof BarSpanIndex
|
||||
) {
|
||||
const rawSkippedTotal =
|
||||
typeof barSpans.skipped === 'object' && barSpans.skipped !== null
|
||||
? barSpans.skipped.total
|
||||
: undefined;
|
||||
const skipped =
|
||||
typeof rawSkippedTotal === 'number' &&
|
||||
Number.isSafeInteger(rawSkippedTotal) &&
|
||||
rawSkippedTotal >= 0
|
||||
? rawSkippedTotal
|
||||
: 0;
|
||||
const rawTotalRowsRead = barSpans.totalRowsRead;
|
||||
const recordsIn =
|
||||
typeof rawTotalRowsRead === 'number' &&
|
||||
Number.isSafeInteger(rawTotalRowsRead) &&
|
||||
rawTotalRowsRead >= skipped
|
||||
? rawTotalRowsRead
|
||||
: barSpans.index.size + skipped;
|
||||
const resolved = recordsIn - skipped;
|
||||
return {
|
||||
lookup: barSpans.index,
|
||||
recordsIn: barSpans.index.size,
|
||||
resolved: barSpans.index.size,
|
||||
skipped: 0,
|
||||
recordsIn,
|
||||
resolved,
|
||||
skipped,
|
||||
indexedSpans: barSpans.index.size,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -394,7 +419,7 @@ export function attachBarSpansToStageBInput(
|
|||
continue;
|
||||
}
|
||||
const observed = lookup?.get('eod', rec.sourceId);
|
||||
if (observed !== undefined) {
|
||||
if (observed !== undefined && observed.barCount > 0) {
|
||||
const span: SpanDateRange = {
|
||||
firstBarDate: observed.firstBarDate,
|
||||
lastBarDate: observed.lastBarDate,
|
||||
|
|
@ -454,7 +479,7 @@ export function attachBarSpansToStageBInput(
|
|||
}
|
||||
if (rec.source === 'qm') {
|
||||
const observed = lookup?.get('qm', rec.sourceId);
|
||||
if (observed !== undefined) {
|
||||
if (observed !== undefined && observed.barCount > 0) {
|
||||
const span: SpanDateRange = {
|
||||
firstBarDate: observed.firstBarDate,
|
||||
lastBarDate: observed.lastBarDate,
|
||||
|
|
@ -518,6 +543,7 @@ export function attachBarSpansToStageBInput(
|
|||
resolved: normalizedSpans.resolved,
|
||||
unresolved: 0,
|
||||
skipped: normalizedSpans.skipped,
|
||||
indexedSpans: normalizedSpans.indexedSpans,
|
||||
attachedEodListings,
|
||||
attachedQmTickerSources,
|
||||
},
|
||||
|
|
@ -608,6 +634,348 @@ export function derivePass4CandidatePairs(
|
|||
return pairs;
|
||||
}
|
||||
|
||||
interface MappingValidityWindow {
|
||||
readonly validFrom: string | null;
|
||||
readonly validTo: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure adapter that restricts valid `sampleCloses` to each provider mapping's Stage B
|
||||
* `[validFrom, validTo]` window before Pass 4 price cross-checks. Malformed close records
|
||||
* are passed through unchanged so `crossCheckPrices` continues to count them in
|
||||
* `droppedInvalidCloses`. Because `crossCheckPrices` aligns dates present in both endpoints,
|
||||
* filtering each endpoint to its own mapping window ensures every comparison only uses dates
|
||||
* where both mappings are valid.
|
||||
*/
|
||||
export function filterSampleClosesByMappingBounds(
|
||||
providerMappings: readonly StageBProviderMappingCandidate[],
|
||||
sampleCloses: readonly SampleCloseRecord[]
|
||||
): SampleCloseRecord[] {
|
||||
if (!Array.isArray(providerMappings)) {
|
||||
throw new TypeError('providerMappings must be an array');
|
||||
}
|
||||
if (!Array.isArray(sampleCloses)) {
|
||||
throw new TypeError('sampleCloses must be an array');
|
||||
}
|
||||
|
||||
const windowsBySeries = new Map<string, MappingValidityWindow[]>();
|
||||
for (let i = 0; i < providerMappings.length; i++) {
|
||||
const mapping = providerMappings[i];
|
||||
if (mapping === undefined || mapping === null) {
|
||||
continue;
|
||||
}
|
||||
const key = `${mapping.source}\u0000${mapping.sourceId}`;
|
||||
let windows = windowsBySeries.get(key);
|
||||
if (windows === undefined) {
|
||||
windows = [];
|
||||
windowsBySeries.set(key, windows);
|
||||
}
|
||||
windows.push({
|
||||
validFrom: mapping.validFrom,
|
||||
validTo: mapping.validTo,
|
||||
});
|
||||
}
|
||||
|
||||
const filtered: SampleCloseRecord[] = [];
|
||||
for (let i = 0; i < sampleCloses.length; i++) {
|
||||
if (!(i in sampleCloses)) {
|
||||
filtered.push(sampleCloses[i] as SampleCloseRecord);
|
||||
continue;
|
||||
}
|
||||
const row = sampleCloses[i];
|
||||
if (row === undefined || row === null || typeof row !== 'object') {
|
||||
filtered.push(row as SampleCloseRecord);
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof row.source !== 'string' ||
|
||||
row.source.length === 0 ||
|
||||
typeof row.sourceId !== 'string' ||
|
||||
row.sourceId.length === 0 ||
|
||||
!isValidExactYmd(row.date) ||
|
||||
typeof row.close !== 'number' ||
|
||||
!Number.isFinite(row.close) ||
|
||||
row.close <= 0
|
||||
) {
|
||||
filtered.push(row);
|
||||
continue;
|
||||
}
|
||||
|
||||
const windows = windowsBySeries.get(`${row.source}\u0000${row.sourceId}`);
|
||||
if (windows === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let inAnyWindow = false;
|
||||
for (let w = 0; w < windows.length; w++) {
|
||||
const win = windows[w];
|
||||
if (win === undefined) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
(win.validFrom === null || row.date >= win.validFrom) &&
|
||||
(win.validTo === null || row.date <= win.validTo)
|
||||
) {
|
||||
inAnyWindow = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (inAnyWindow) {
|
||||
filtered.push(row);
|
||||
}
|
||||
}
|
||||
|
||||
return filtered;
|
||||
}
|
||||
|
||||
function isExcludedByDesignRole(role: ExchangeRole | null | 'mixed' | undefined): boolean {
|
||||
return (
|
||||
role === 'excluded_fund' ||
|
||||
role === 'composite' ||
|
||||
role === 'ats_routing' ||
|
||||
role === 'forex'
|
||||
);
|
||||
}
|
||||
|
||||
function lookupSourceCountryValue(
|
||||
lookup: SourceCountryLookup | undefined,
|
||||
source: string,
|
||||
sourceId: string
|
||||
): string | null {
|
||||
if (!lookup) {
|
||||
return null;
|
||||
}
|
||||
const primaryKey = sourceCountryKey(source, sourceId);
|
||||
const fallbackKey = `${source}\u0000${sourceId}`;
|
||||
|
||||
let raw: string | undefined;
|
||||
if (lookup instanceof Map) {
|
||||
raw = lookup.get(primaryKey) ?? lookup.get(fallbackKey);
|
||||
} else {
|
||||
const record = lookup as Readonly<Record<string, string>>;
|
||||
if (Object.prototype.hasOwnProperty.call(record, primaryKey)) {
|
||||
raw = record[primaryKey];
|
||||
} else if (Object.prototype.hasOwnProperty.call(record, fallbackKey)) {
|
||||
raw = record[fallbackKey];
|
||||
}
|
||||
}
|
||||
if (typeof raw !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const normalized = raw.trim().toUpperCase();
|
||||
return normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds Stage A unresolved/conflict failures that did not reach Stage B into end-to-end
|
||||
* `resolutionBySource`, `resolutionByCountry`, and `meetsExitThresholds.equitiesResolved95`
|
||||
* without double-counting any record already counted in Stage B.
|
||||
*/
|
||||
function applyEndToEndStageACoverage(
|
||||
baseReport: MatchReport,
|
||||
stageA: StageAMatchResult,
|
||||
stageB: StageBMatchResult,
|
||||
eodListings: readonly StageBEodListingInput[],
|
||||
sourceCountries: SourceCountryLookup | undefined
|
||||
): MatchReport {
|
||||
if (stageA.unresolved.length === 0 && stageA.conflicts.length === 0) {
|
||||
return baseReport;
|
||||
}
|
||||
|
||||
const eodRoleBySourceId = new Map<string, ExchangeRole | null | 'mixed'>();
|
||||
for (let i = 0; i < eodListings.length; i++) {
|
||||
const entry = eodListings[i];
|
||||
if (entry === undefined) {
|
||||
continue;
|
||||
}
|
||||
const role = entry.role ?? null;
|
||||
if (!eodRoleBySourceId.has(entry.sourceId)) {
|
||||
eodRoleBySourceId.set(entry.sourceId, role);
|
||||
} else if (eodRoleBySourceId.get(entry.sourceId) !== role) {
|
||||
eodRoleBySourceId.set(entry.sourceId, 'mixed');
|
||||
}
|
||||
}
|
||||
|
||||
const stageBCountedByKey = new Map<string, number>();
|
||||
const recordStageBCount = (source: string, sourceId: string): void => {
|
||||
if (source !== 'eod' && source !== 'ib') {
|
||||
return;
|
||||
}
|
||||
const key = `${source}\u0000${sourceId}`;
|
||||
stageBCountedByKey.set(key, (stageBCountedByKey.get(key) ?? 0) + 1);
|
||||
};
|
||||
for (let i = 0; i < stageB.providerMappings.length; i++) {
|
||||
const m = stageB.providerMappings[i];
|
||||
if (m !== undefined) {
|
||||
recordStageBCount(m.source, m.sourceId);
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < stageB.unresolved.length; i++) {
|
||||
const u = stageB.unresolved[i];
|
||||
if (u !== undefined) {
|
||||
recordStageBCount(u.source, u.sourceId);
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < stageB.conflicts.length; i++) {
|
||||
const c = stageB.conflicts[i];
|
||||
if (c !== undefined) {
|
||||
recordStageBCount(c.source, c.sourceId);
|
||||
}
|
||||
}
|
||||
|
||||
const deltaBySource: Record<
|
||||
'eod' | 'ib',
|
||||
{ total: number; unresolved: number; conflict: number; excludedByDesign: number }
|
||||
> = {
|
||||
eod: { total: 0, unresolved: 0, conflict: 0, excludedByDesign: 0 },
|
||||
ib: { total: 0, unresolved: 0, conflict: 0, excludedByDesign: 0 },
|
||||
};
|
||||
|
||||
const countryAccs = new Map<
|
||||
string,
|
||||
{ total: number; matched: number; unresolved: number; conflict: number; excludedByDesign: number }
|
||||
>();
|
||||
for (let i = 0; i < baseReport.resolutionByCountry.length; i++) {
|
||||
const row = baseReport.resolutionByCountry[i];
|
||||
if (row !== undefined) {
|
||||
countryAccs.set(row.country, {
|
||||
total: row.total,
|
||||
matched: row.matched,
|
||||
unresolved: row.unresolved,
|
||||
conflict: row.conflict,
|
||||
excludedByDesign: row.excludedByDesign,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const getOrCreateCountry = (country: string) => {
|
||||
let acc = countryAccs.get(country);
|
||||
if (acc === undefined) {
|
||||
acc = { total: 0, matched: 0, unresolved: 0, conflict: 0, excludedByDesign: 0 };
|
||||
countryAccs.set(country, acc);
|
||||
}
|
||||
return acc;
|
||||
};
|
||||
|
||||
const consumeStageBCount = (source: 'eod' | 'ib', sourceId: string): boolean => {
|
||||
const key = `${source}\u0000${sourceId}`;
|
||||
const remaining = stageBCountedByKey.get(key) ?? 0;
|
||||
if (remaining > 0) {
|
||||
stageBCountedByKey.set(key, remaining - 1);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
for (let i = 0; i < stageA.unresolved.length; i++) {
|
||||
const rec = stageA.unresolved[i];
|
||||
if (rec === undefined || consumeStageBCount(rec.source, rec.sourceId)) {
|
||||
continue;
|
||||
}
|
||||
const excluded =
|
||||
rec.source === 'eod' && isExcludedByDesignRole(eodRoleBySourceId.get(rec.sourceId));
|
||||
const d = deltaBySource[rec.source];
|
||||
d.total += 1;
|
||||
d.unresolved += 1;
|
||||
if (excluded) {
|
||||
d.excludedByDesign += 1;
|
||||
}
|
||||
|
||||
const country = lookupSourceCountryValue(sourceCountries, rec.source, rec.sourceId);
|
||||
if (country !== null) {
|
||||
const cAcc = getOrCreateCountry(country);
|
||||
cAcc.total += 1;
|
||||
cAcc.unresolved += 1;
|
||||
if (excluded) {
|
||||
cAcc.excludedByDesign += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < stageA.conflicts.length; i++) {
|
||||
const rec = stageA.conflicts[i];
|
||||
if (rec === undefined || consumeStageBCount(rec.source, rec.sourceId)) {
|
||||
continue;
|
||||
}
|
||||
const d = deltaBySource[rec.source];
|
||||
d.total += 1;
|
||||
d.conflict += 1;
|
||||
|
||||
const country = lookupSourceCountryValue(sourceCountries, rec.source, rec.sourceId);
|
||||
if (country !== null) {
|
||||
const cAcc = getOrCreateCountry(country);
|
||||
cAcc.total += 1;
|
||||
cAcc.conflict += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (deltaBySource.eod.total === 0 && deltaBySource.ib.total === 0) {
|
||||
return baseReport;
|
||||
}
|
||||
|
||||
const resolutionBySource: SourceResolutionSummary[] = baseReport.resolutionBySource.map(row => {
|
||||
if (row.source !== 'eod' && row.source !== 'ib') {
|
||||
return row;
|
||||
}
|
||||
const d = deltaBySource[row.source];
|
||||
if (d.total === 0) {
|
||||
return row;
|
||||
}
|
||||
const total = row.total + d.total;
|
||||
const unresolved = row.unresolved + d.unresolved;
|
||||
const conflict = row.conflict + d.conflict;
|
||||
const excludedByDesign = row.excludedByDesign + d.excludedByDesign;
|
||||
const eligibleTotal = Math.max(0, total - excludedByDesign);
|
||||
return {
|
||||
source: row.source,
|
||||
total,
|
||||
matched: row.matched,
|
||||
unresolved,
|
||||
conflict,
|
||||
excludedByDesign,
|
||||
eligibleTotal,
|
||||
resolvedPct: total > 0 ? row.matched / total : null,
|
||||
eligibleResolvedPct: eligibleTotal > 0 ? row.matched / eligibleTotal : null,
|
||||
};
|
||||
});
|
||||
|
||||
const resolutionByCountry: CountryResolutionSummary[] = sourceCountries
|
||||
? Array.from(countryAccs.entries())
|
||||
.sort((a, b) => compareAscii(a[0], b[0]))
|
||||
.map(([country, acc]) => {
|
||||
const eligibleTotal = Math.max(0, acc.total - acc.excludedByDesign);
|
||||
return {
|
||||
country,
|
||||
total: acc.total,
|
||||
matched: acc.matched,
|
||||
unresolved: acc.unresolved,
|
||||
conflict: acc.conflict,
|
||||
excludedByDesign: acc.excludedByDesign,
|
||||
eligibleTotal,
|
||||
resolvedPct: acc.total > 0 ? acc.matched / acc.total : null,
|
||||
eligibleResolvedPct: eligibleTotal > 0 ? acc.matched / eligibleTotal : null,
|
||||
};
|
||||
})
|
||||
: baseReport.resolutionByCountry;
|
||||
|
||||
const eligibleSources = resolutionBySource.filter(row => row.total > 0 && row.eligibleTotal > 0);
|
||||
const equitiesResolved95 =
|
||||
eligibleSources.length > 0 &&
|
||||
eligibleSources.every(
|
||||
row => row.eligibleResolvedPct !== null && row.eligibleResolvedPct >= baseReport.minResolvedPct
|
||||
);
|
||||
|
||||
return {
|
||||
...baseReport,
|
||||
resolutionBySource,
|
||||
resolutionByCountry,
|
||||
meetsExitThresholds: {
|
||||
...baseReport.meetsExitThresholds,
|
||||
equitiesResolved95,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function recordCountryCandidate(
|
||||
target: Map<string, string>,
|
||||
key: string,
|
||||
|
|
@ -774,17 +1142,21 @@ export function composeSecurityMasterRun(
|
|||
};
|
||||
const pass6 = linkDelistingChains({ listings: stageB.listings, otcMics }, pass6Options);
|
||||
|
||||
// 4. Optional Pass 4 (price cross-check over cross-source pairs sharing a listing)
|
||||
// 4. Optional Pass 4 (price cross-check over cross-source pairs sharing a listing,
|
||||
// bounded to dates where both Stage B mappings are valid)
|
||||
const pass4CandidatePairs = derivePass4CandidatePairs(stageB.providerMappings);
|
||||
const hasSampleCloses =
|
||||
input.sampleCloses !== undefined &&
|
||||
Array.isArray(input.sampleCloses) &&
|
||||
input.sampleCloses.length > 0;
|
||||
const boundedSampleCloses = hasSampleCloses
|
||||
? filterSampleClosesByMappingBounds(stageB.providerMappings, input.sampleCloses)
|
||||
: [];
|
||||
const pass4: PriceCrossCheckResult | null = hasSampleCloses
|
||||
? crossCheckPrices(
|
||||
{
|
||||
pairs: pass4CandidatePairs,
|
||||
closes: input.sampleCloses,
|
||||
closes: boundedSampleCloses,
|
||||
usdCadByDate: input.fxRates ?? [],
|
||||
},
|
||||
options.pass4
|
||||
|
|
@ -795,7 +1167,7 @@ export function composeSecurityMasterRun(
|
|||
const sourceCountries =
|
||||
input.sourceCountries ??
|
||||
deriveSourceCountries(sanitizedStageARecords, attached.stageBInput, stageB);
|
||||
const report = buildMatchReport(
|
||||
const baseReport = buildMatchReport(
|
||||
{
|
||||
...(input.exchanges !== undefined ? { exchanges: input.exchanges } : {}),
|
||||
stageA,
|
||||
|
|
@ -806,6 +1178,13 @@ export function composeSecurityMasterRun(
|
|||
},
|
||||
options.report
|
||||
);
|
||||
const report = applyEndToEndStageACoverage(
|
||||
baseReport,
|
||||
stageA,
|
||||
stageB,
|
||||
attached.stageBInput.eodListings,
|
||||
sourceCountries
|
||||
);
|
||||
const reportMarkdown = renderMatchReportMarkdown(report, options.markdown);
|
||||
const conflictsCsv = renderConflictsCsv(report);
|
||||
const overrideTemplateSql = generateOverrideTemplateSql(report);
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue