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);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue