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
33b1d23f84
commit
3bdf7a8da6
9 changed files with 2722 additions and 6 deletions
|
|
@ -124,3 +124,21 @@ bun test test/unit/security-master-security-type.test.ts
|
|||
- **Recorded baseline (`2026-11-28`, local sandbox, zero DB connections):**
|
||||
- Workload: `300,000` synthetic EOD records (`100,000` distinct ISIN buckets, mixed mapped/unknown/missing types, and `20` conflicting ISINs exercising Pass 2 conflict collection).
|
||||
- Observed throughput: `4,277,092 records/s` (`70.1 ms` wall time, floor `>= 100,000 records/s`).
|
||||
|
||||
## Security-Master Run Composer (`run.ts`)
|
||||
`apps/stock/data-pipeline/src/security-master/run.ts` provides a pure, zero-I/O entry point (`composeSecurityMasterRun`) that wires in-memory source-symbol reader outputs and observed bar spans end to end without touching MongoDB, PostgreSQL, or the filesystem:
|
||||
|
||||
`sources + barSpans -> matchInstrumentsStageA -> attachBarSpansToStageBInput -> matchListingsStageB -> linkDelistingChains (Pass 6) -> optional crossCheckPrices (Pass 4) -> buildMatchReport (+ Markdown / CSV / override-template SQL) + PersistSecurityMasterInput`
|
||||
|
||||
- **Pure & deterministic:** Contains zero I/O imports and zero wall-clock calls. Shuffling any input array or `securityTypeByIsin` map insertion order produces byte-identical Markdown, CSV, override-template SQL, and deep-equal `PersistSecurityMasterInput`.
|
||||
- **Explicit Pass 4 skipping:** When `sampleCloses` is omitted or empty, Pass 4 is marked `skipped` in both `stats.pass4` and the rendered Markdown (`- Status: skipped (no sample closes supplied)`), `pass4` is `null`, and `persistInput.pass4` is omitted — it is never reported as passed.
|
||||
- **Malformed-record resilience & reconciliation:** Pre-pass sanitizers skip and count malformed or sparse entries across every input array without aborting the run, and every step reconciles `recordsIn === resolved + unresolved + skipped` with `report.conflicts.length === stageA + stageB + pass4 + pass6`.
|
||||
- **Local synthetic benchmark:** Run the unit suite and fixed-seed 100,000-record synthetic benchmark (zero DB connections) with:
|
||||
|
||||
```bash
|
||||
bun test test/unit/security-master-run.test.ts
|
||||
```
|
||||
|
||||
- **Recorded baseline (`2026-11-28`, local sandbox, zero DB connections):**
|
||||
- Workload: `100,000` synthetic source records (`50,000` EOD + `25,000` IB + `25,000` QM, `75,000` bar spans, `50,000` security types) composed end to end through Stage A, Stage B, Pass 6, Pass 4 pair derivation, MatchReport + Markdown/CSV/SQL rendering, and `PersistSecurityMasterInput` assembly.
|
||||
- Observed throughput: `208,502 records/s` (`479.6 ms` wall time, asserted floor `>= 10,000 records/s`).
|
||||
|
|
|
|||
|
|
@ -191,6 +191,29 @@ export {
|
|||
type SelectSampleDatesOptions,
|
||||
} from './price-cross-check';
|
||||
|
||||
export {
|
||||
attachBarSpansToStageBInput,
|
||||
composeSecurityMasterRun,
|
||||
derivePass4CandidatePairs,
|
||||
deriveSourceCountries,
|
||||
type AttachBarSpansMalformedCounts,
|
||||
type AttachBarSpansResult,
|
||||
type BarSpansStepStats,
|
||||
type ComposeConflictTotals,
|
||||
type ComposeMalformedInputStats,
|
||||
type ComposeSecurityMasterPass6Options,
|
||||
type ComposeSecurityMasterRunInput,
|
||||
type ComposeSecurityMasterRunOptions,
|
||||
type ComposeSecurityMasterRunResult,
|
||||
type ComposeSecurityMasterRunStats,
|
||||
type ObservedBarSpansInput,
|
||||
type Pass4ComposeStepStats,
|
||||
type Pass6ComposeStepStats,
|
||||
type ReconcilingStepStats,
|
||||
type StageAComposeStepStats,
|
||||
type StageBComposeStepStats,
|
||||
} from './run';
|
||||
|
||||
export {
|
||||
buildSecurityTypeByIsin,
|
||||
buildSecurityTypeByIsinForStageA,
|
||||
|
|
|
|||
|
|
@ -757,10 +757,11 @@ export function renderMatchReportMarkdown(
|
|||
}
|
||||
}
|
||||
|
||||
lines.push('', '## Pass 4 Price Cross-Check Verdicts', '');
|
||||
if (report.priceCrossCheck === null) {
|
||||
lines.push('- Status: skipped (no sample closes supplied)');
|
||||
}
|
||||
lines.push(
|
||||
'',
|
||||
'## Pass 4 Price Cross-Check Verdicts',
|
||||
'',
|
||||
`- Pairs In: ${report.priceCrossCheck?.pairsIn ?? 0}`,
|
||||
`- Invalid Pairs: ${report.priceCrossCheck?.invalidPairs ?? 0}`,
|
||||
`- Conflicts Emitted: ${report.priceCrossCheck?.conflictsEmitted ?? 0}`,
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ import type {
|
|||
StageBMatchResult,
|
||||
StageBProviderMappingCandidate,
|
||||
} from './listing-stage-b';
|
||||
import type { PriceCrossCheckResult } from './price-cross-check';
|
||||
|
||||
export const SECURITY_TYPES = [
|
||||
'common',
|
||||
|
|
@ -90,6 +91,7 @@ export interface SecurityMasterQueryable {
|
|||
export interface PersistSecurityMasterInput {
|
||||
readonly stageA: StageAMatchResult;
|
||||
readonly stageB: StageBMatchResult;
|
||||
readonly pass4?: PriceCrossCheckResult;
|
||||
readonly pass6?: DelistingChainResult;
|
||||
readonly securityTypeByIsin: ReadonlyMap<string, SecurityType>;
|
||||
}
|
||||
|
|
@ -230,6 +232,10 @@ interface ExistingConflictRow {
|
|||
conflict_kind: string;
|
||||
}
|
||||
|
||||
interface ExistingPass4ConflictRow {
|
||||
conflict_key: string;
|
||||
}
|
||||
|
||||
interface PreparedInstrument {
|
||||
readonly primaryIsin: string;
|
||||
readonly primaryCusip: string | null;
|
||||
|
|
@ -289,6 +295,7 @@ interface PreparedConflict {
|
|||
readonly sourceId: string;
|
||||
readonly conflictKind: string;
|
||||
readonly detailJson: string;
|
||||
readonly isPass4: boolean;
|
||||
}
|
||||
|
||||
interface PreparedContinuity {
|
||||
|
|
@ -430,6 +437,15 @@ function validateInputsAndIndexPass6(input: PersistSecurityMasterInput): {
|
|||
if (!(input.securityTypeByIsin instanceof Map) && typeof input.securityTypeByIsin?.get !== 'function') {
|
||||
throw new TypeError('persistSecurityMaster requires a securityTypeByIsin Map');
|
||||
}
|
||||
if (input.pass4 !== undefined) {
|
||||
if (
|
||||
input.pass4 === null ||
|
||||
typeof input.pass4 !== 'object' ||
|
||||
!Array.isArray(input.pass4.conflicts)
|
||||
) {
|
||||
throw new TypeError('persistSecurityMaster requires pass4.conflicts to be an array');
|
||||
}
|
||||
}
|
||||
|
||||
const seenIsins = new Set<string>();
|
||||
for (const inst of input.stageA.instruments) {
|
||||
|
|
@ -502,6 +518,7 @@ function collectAndDeduplicateConflicts(input: PersistSecurityMasterInput): {
|
|||
sourceId: c.sourceId,
|
||||
conflictKind: c.conflictKind,
|
||||
detailJson: stableJsonStringify(c.detail),
|
||||
isPass4: false,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -512,9 +529,23 @@ function collectAndDeduplicateConflicts(input: PersistSecurityMasterInput): {
|
|||
sourceId: c.sourceId,
|
||||
conflictKind: c.conflictKind,
|
||||
detailJson: stableJsonStringify(c.detail),
|
||||
isPass4: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (input.pass4 !== undefined) {
|
||||
for (const c of input.pass4.conflicts) {
|
||||
raw.push({
|
||||
key: `${c.source}\u0000${c.sourceId}\u0000${c.conflictKind}\u0000${c.detail.right.source}\u0000${c.detail.right.sourceId}`,
|
||||
source: c.source,
|
||||
sourceId: c.sourceId,
|
||||
conflictKind: c.conflictKind,
|
||||
detailJson: stableJsonStringify(c.detail),
|
||||
isPass4: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (input.pass6 !== undefined) {
|
||||
for (const c of input.pass6.conflicts) {
|
||||
const sourceId = c.detail.primaryIsin;
|
||||
|
|
@ -524,6 +555,7 @@ function collectAndDeduplicateConflicts(input: PersistSecurityMasterInput): {
|
|||
sourceId,
|
||||
conflictKind: c.conflictKind,
|
||||
detailJson: stableJsonStringify(c.detail),
|
||||
isPass4: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1349,9 +1381,19 @@ async function persistWithinTransaction(
|
|||
collectAndDeduplicateConflicts(input);
|
||||
|
||||
if (uniqueConflicts.length > 0) {
|
||||
const nonPass4Conflicts: PreparedConflict[] = [];
|
||||
const pass4Conflicts: PreparedConflict[] = [];
|
||||
for (const conflict of uniqueConflicts) {
|
||||
if (conflict.isPass4) {
|
||||
pass4Conflicts.push(conflict);
|
||||
} else {
|
||||
nonPass4Conflicts.push(conflict);
|
||||
}
|
||||
}
|
||||
|
||||
const existingConflictKeys = new Set<string>();
|
||||
for (let offset = 0; offset < uniqueConflicts.length; offset += chunkSize) {
|
||||
const slice = uniqueConflicts.slice(offset, offset + chunkSize);
|
||||
for (let offset = 0; offset < nonPass4Conflicts.length; offset += chunkSize) {
|
||||
const slice = nonPass4Conflicts.slice(offset, offset + chunkSize);
|
||||
const res = await client.query<ExistingConflictRow>(
|
||||
`SELECT DISTINCT
|
||||
rc.source,
|
||||
|
|
@ -1377,9 +1419,43 @@ async function persistWithinTransaction(
|
|||
}
|
||||
}
|
||||
|
||||
const existingPass4ConflictKeys = new Set<string>();
|
||||
for (let offset = 0; offset < pass4Conflicts.length; offset += chunkSize) {
|
||||
const slice = pass4Conflicts.slice(offset, offset + chunkSize);
|
||||
const res = await client.query<ExistingPass4ConflictRow>(
|
||||
`SELECT DISTINCT
|
||||
u.conflict_key
|
||||
FROM resolution_conflict rc
|
||||
INNER JOIN UNNEST(
|
||||
$1::varchar[],
|
||||
$2::varchar[],
|
||||
$3::varchar[],
|
||||
$4::jsonb[],
|
||||
$5::text[]
|
||||
) AS u(source, source_id, conflict_kind, detail, conflict_key)
|
||||
ON rc.source = u.source
|
||||
AND rc.source_id = u.source_id
|
||||
AND rc.conflict_kind = u.conflict_kind
|
||||
AND rc.detail = u.detail`,
|
||||
[
|
||||
slice.map(c => c.source),
|
||||
slice.map(c => c.sourceId),
|
||||
slice.map(c => c.conflictKind),
|
||||
slice.map(c => c.detailJson),
|
||||
slice.map(c => c.key),
|
||||
]
|
||||
);
|
||||
for (const row of res.rows) {
|
||||
existingPass4ConflictKeys.add(row.conflict_key);
|
||||
}
|
||||
}
|
||||
|
||||
const toInsertConflicts: PreparedConflict[] = [];
|
||||
for (const conflict of uniqueConflicts) {
|
||||
if (existingConflictKeys.has(conflict.key)) {
|
||||
const exists = conflict.isPass4
|
||||
? existingPass4ConflictKeys.has(conflict.key)
|
||||
: existingConflictKeys.has(conflict.key);
|
||||
if (exists) {
|
||||
conflictsUnchanged += 1;
|
||||
} else {
|
||||
toInsertConflicts.push(conflict);
|
||||
|
|
|
|||
958
apps/stock/data-pipeline/src/security-master/run.ts
Normal file
958
apps/stock/data-pipeline/src/security-master/run.ts
Normal file
|
|
@ -0,0 +1,958 @@
|
|||
import {
|
||||
BarSpanIndex,
|
||||
normalizeBarDate,
|
||||
type BarSpan,
|
||||
type ComputeBarSpansResult,
|
||||
type SpanDateRange,
|
||||
} from '../normalization/bar-spans';
|
||||
import { parseTickerDetailed } from '../normalization/ticker';
|
||||
import {
|
||||
DEFAULT_OTC_MICS,
|
||||
linkDelistingChains,
|
||||
type DelistingChainResult,
|
||||
type LinkDelistingChainsOptions,
|
||||
} from './delisting-chains';
|
||||
import {
|
||||
compareAscii,
|
||||
ISO_EXCHANGE_SEEDS,
|
||||
type ExchangeClassificationResult,
|
||||
type ExchangeRole,
|
||||
} from './exchange-pass1';
|
||||
import {
|
||||
isStageASource,
|
||||
matchInstrumentsStageA,
|
||||
STAGE_A_SOURCES,
|
||||
type MatchInstrumentsStageAOptions,
|
||||
type StageAMatchResult,
|
||||
type StageASourceRecord,
|
||||
} from './instrument-stage-a';
|
||||
import {
|
||||
matchListingsStageB,
|
||||
MAX_TICKER_ROOT_LENGTH,
|
||||
STAGE_B_SOURCES,
|
||||
type MatchListingsStageBOptions,
|
||||
type StageBEodListingInput,
|
||||
type StageBIbContractInput,
|
||||
type StageBMatchResult,
|
||||
type StageBProviderMappingCandidate,
|
||||
type StageBSymbolChangeInput,
|
||||
type StageBTickerSourceInput,
|
||||
} from './listing-stage-b';
|
||||
import {
|
||||
buildMatchReport,
|
||||
generateOverrideTemplateSql,
|
||||
renderConflictsCsv,
|
||||
renderMatchReportMarkdown,
|
||||
sourceCountryKey,
|
||||
type BuildMatchReportOptions,
|
||||
type MatchReport,
|
||||
type RenderMatchReportMarkdownOptions,
|
||||
type SourceCountryLookup,
|
||||
} from './match-report';
|
||||
import {
|
||||
formatListingNaturalKey,
|
||||
type PersistSecurityMasterInput,
|
||||
type SecurityType,
|
||||
} from './persist';
|
||||
import {
|
||||
crossCheckPrices,
|
||||
type CrossCheckPricesOptions,
|
||||
type FxRateByDateRecord,
|
||||
type PriceCrossCheckPair,
|
||||
type PriceCrossCheckResult,
|
||||
type PriceSeriesEndpoint,
|
||||
type SampleCloseRecord,
|
||||
} from './price-cross-check';
|
||||
import {
|
||||
normalizeCountryIso2,
|
||||
type SecurityMasterSourcesResult,
|
||||
type SecurityMasterStageBSourceInput,
|
||||
} from './source-symbol-readers';
|
||||
|
||||
export type ObservedBarSpansInput =
|
||||
| readonly BarSpan[]
|
||||
| ComputeBarSpansResult
|
||||
| BarSpanIndex;
|
||||
|
||||
export interface ComposeSecurityMasterPass6Options
|
||||
extends Omit<LinkDelistingChainsOptions, 'asOfDate'> {
|
||||
readonly otcMics?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
export interface ComposeSecurityMasterRunInput {
|
||||
readonly sources: SecurityMasterSourcesResult;
|
||||
readonly barSpans?: ObservedBarSpansInput | null;
|
||||
readonly exchanges?: ExchangeClassificationResult;
|
||||
readonly sampleCloses?: readonly SampleCloseRecord[];
|
||||
readonly fxRates?: readonly FxRateByDateRecord[];
|
||||
readonly sourceCountries?: SourceCountryLookup;
|
||||
}
|
||||
|
||||
export interface ComposeSecurityMasterRunOptions {
|
||||
readonly asOfDate: string;
|
||||
readonly stageA?: MatchInstrumentsStageAOptions;
|
||||
readonly stageB?: MatchListingsStageBOptions;
|
||||
readonly pass6?: ComposeSecurityMasterPass6Options;
|
||||
readonly pass4?: CrossCheckPricesOptions;
|
||||
readonly report?: BuildMatchReportOptions;
|
||||
readonly markdown?: RenderMatchReportMarkdownOptions;
|
||||
}
|
||||
|
||||
export interface ReconcilingStepStats {
|
||||
readonly recordsIn: number;
|
||||
readonly resolved: number;
|
||||
readonly unresolved: number;
|
||||
readonly skipped: number;
|
||||
}
|
||||
|
||||
export interface BarSpansStepStats extends ReconcilingStepStats {
|
||||
readonly attachedEodListings: number;
|
||||
readonly attachedQmTickerSources: number;
|
||||
}
|
||||
|
||||
export interface StageAComposeStepStats extends ReconcilingStepStats {
|
||||
readonly conflicts: number;
|
||||
}
|
||||
|
||||
export interface StageBComposeStepStats extends ReconcilingStepStats {
|
||||
readonly conflicts: number;
|
||||
}
|
||||
|
||||
export interface Pass6ComposeStepStats extends ReconcilingStepStats {
|
||||
readonly continuitiesCreated: number;
|
||||
readonly conflicts: number;
|
||||
}
|
||||
|
||||
export interface Pass4ComposeStepStats extends ReconcilingStepStats {
|
||||
readonly status: 'executed' | 'skipped';
|
||||
readonly conflicts: number;
|
||||
}
|
||||
|
||||
export interface ComposeMalformedInputStats {
|
||||
readonly stageARecords: number;
|
||||
readonly eodListings: number;
|
||||
readonly ibContracts: number;
|
||||
readonly tickerSources: number;
|
||||
readonly symbolChanges: number;
|
||||
readonly barSpans: number;
|
||||
readonly sampleCloses: number;
|
||||
readonly fxRates: number;
|
||||
readonly total: number;
|
||||
}
|
||||
|
||||
export interface ComposeConflictTotals {
|
||||
readonly stageA: number;
|
||||
readonly stageB: number;
|
||||
readonly pass4: number;
|
||||
readonly pass6: number;
|
||||
readonly total: number;
|
||||
}
|
||||
|
||||
export interface ComposeSecurityMasterRunStats {
|
||||
readonly barSpans: BarSpansStepStats;
|
||||
readonly stageA: StageAComposeStepStats;
|
||||
readonly stageB: StageBComposeStepStats;
|
||||
readonly pass6: Pass6ComposeStepStats;
|
||||
readonly pass4: Pass4ComposeStepStats;
|
||||
readonly conflicts: ComposeConflictTotals;
|
||||
readonly malformedInputs: ComposeMalformedInputStats;
|
||||
}
|
||||
|
||||
export interface AttachBarSpansMalformedCounts {
|
||||
readonly barSpans: number;
|
||||
readonly eodListings: number;
|
||||
readonly ibContracts: number;
|
||||
readonly tickerSources: number;
|
||||
readonly symbolChanges: number;
|
||||
}
|
||||
|
||||
export interface AttachBarSpansResult {
|
||||
readonly stageBInput: SecurityMasterStageBSourceInput;
|
||||
readonly stats: BarSpansStepStats;
|
||||
readonly malformed: AttachBarSpansMalformedCounts;
|
||||
}
|
||||
|
||||
export interface ComposeSecurityMasterRunResult {
|
||||
readonly stageA: StageAMatchResult;
|
||||
readonly stageB: StageBMatchResult;
|
||||
readonly pass6: DelistingChainResult;
|
||||
readonly pass4: PriceCrossCheckResult | null;
|
||||
readonly pass4CandidatePairs: readonly PriceCrossCheckPair[];
|
||||
readonly report: MatchReport;
|
||||
readonly reportMarkdown: string;
|
||||
readonly conflictsCsv: string;
|
||||
readonly overrideTemplateSql: string;
|
||||
readonly persistInput: PersistSecurityMasterInput;
|
||||
readonly stats: ComposeSecurityMasterRunStats;
|
||||
}
|
||||
|
||||
const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
const MIC_TO_COUNTRY: ReadonlyMap<string, string> = (() => {
|
||||
const map = new Map<string, string>();
|
||||
for (const seed of ISO_EXCHANGE_SEEDS) {
|
||||
map.set(seed.mic, seed.countryIso);
|
||||
}
|
||||
return map;
|
||||
})();
|
||||
|
||||
function isExchangeRoleValue(value: unknown): value is ExchangeRole {
|
||||
return (
|
||||
value === 'primary_venue' ||
|
||||
value === 'composite' ||
|
||||
value === 'ats_routing' ||
|
||||
value === 'forex' ||
|
||||
value === 'excluded_fund'
|
||||
);
|
||||
}
|
||||
|
||||
function isValidExactYmd(value: unknown): value is string {
|
||||
return (
|
||||
typeof value === 'string' &&
|
||||
EXACT_YMD_PATTERN.test(value) &&
|
||||
normalizeBarDate(value) === value
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeObservedBarSpans(barSpans: ObservedBarSpansInput | null | undefined): {
|
||||
readonly lookup: BarSpanIndex | null;
|
||||
readonly recordsIn: number;
|
||||
readonly resolved: number;
|
||||
readonly skipped: number;
|
||||
} {
|
||||
if (barSpans === undefined || barSpans === null) {
|
||||
return { lookup: null, recordsIn: 0, resolved: 0, skipped: 0 };
|
||||
}
|
||||
|
||||
if (barSpans instanceof BarSpanIndex) {
|
||||
return {
|
||||
lookup: barSpans,
|
||||
recordsIn: barSpans.size,
|
||||
resolved: barSpans.size,
|
||||
skipped: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (Array.isArray(barSpans)) {
|
||||
const index = new BarSpanIndex();
|
||||
let resolved = 0;
|
||||
let skipped = 0;
|
||||
|
||||
for (let i = 0; i < barSpans.length; i++) {
|
||||
if (!(i in barSpans)) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
const entry = barSpans[i] as unknown;
|
||||
if (entry === undefined || entry === null || typeof entry !== 'object') {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
const rec = entry as Partial<BarSpan>;
|
||||
if (rec.source !== 'eod' && rec.source !== 'qm') {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
if (typeof rec.sourceId !== 'string' || rec.sourceId.length === 0) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
const firstBarDate = normalizeBarDate(rec.firstBarDate);
|
||||
const lastBarDate = normalizeBarDate(rec.lastBarDate);
|
||||
if (firstBarDate === null || lastBarDate === null || firstBarDate > lastBarDate) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof rec.barCount !== 'number' ||
|
||||
!Number.isSafeInteger(rec.barCount) ||
|
||||
rec.barCount < 0
|
||||
) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
index.merge({
|
||||
source: rec.source,
|
||||
sourceId: rec.sourceId,
|
||||
firstBarDate,
|
||||
lastBarDate,
|
||||
barCount: rec.barCount,
|
||||
});
|
||||
resolved += 1;
|
||||
}
|
||||
|
||||
return {
|
||||
lookup: index,
|
||||
recordsIn: barSpans.length,
|
||||
resolved,
|
||||
skipped,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
typeof barSpans === 'object' &&
|
||||
'index' in barSpans &&
|
||||
barSpans.index instanceof BarSpanIndex
|
||||
) {
|
||||
return {
|
||||
lookup: barSpans.index,
|
||||
recordsIn: barSpans.index.size,
|
||||
resolved: barSpans.index.size,
|
||||
skipped: 0,
|
||||
};
|
||||
}
|
||||
|
||||
throw new TypeError(
|
||||
'barSpans must be a BarSpan[], ComputeBarSpansResult, BarSpanIndex, null, or undefined'
|
||||
);
|
||||
}
|
||||
|
||||
function sanitizeStageARecords(records: readonly StageASourceRecord[]): {
|
||||
readonly sanitized: StageASourceRecord[];
|
||||
readonly malformed: number;
|
||||
} {
|
||||
if (!Array.isArray(records)) {
|
||||
throw new TypeError('sources.stageARecords must be an array');
|
||||
}
|
||||
const sanitized: StageASourceRecord[] = [];
|
||||
let malformed = 0;
|
||||
|
||||
for (let i = 0; i < records.length; i++) {
|
||||
if (!(i in records)) {
|
||||
malformed += 1;
|
||||
continue;
|
||||
}
|
||||
const record = records[i] as unknown;
|
||||
if (record === undefined || record === null || typeof record !== 'object') {
|
||||
malformed += 1;
|
||||
continue;
|
||||
}
|
||||
const candidate = record as StageASourceRecord;
|
||||
if (!isStageASource(candidate.source)) {
|
||||
malformed += 1;
|
||||
continue;
|
||||
}
|
||||
if (typeof candidate.sourceId !== 'string' || candidate.sourceId.length === 0) {
|
||||
malformed += 1;
|
||||
continue;
|
||||
}
|
||||
sanitized.push(candidate);
|
||||
}
|
||||
|
||||
return { sanitized, malformed };
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure adapter that normalizes observed bar spans (`BarSpan[]`, `ComputeBarSpansResult`, or
|
||||
* `BarSpanIndex`), sanitizes Stage B source arrays against malformed/sparse entries that would
|
||||
* throw inside `matchListingsStageB`, and attaches observed `eod`/`qm` spans onto shallow-cloned
|
||||
* entries while preserving existing spans (including `ceo` spans) when absent from `barSpans`.
|
||||
*/
|
||||
export function attachBarSpansToStageBInput(
|
||||
stageBInput: SecurityMasterStageBSourceInput,
|
||||
barSpans?: ObservedBarSpansInput | null
|
||||
): AttachBarSpansResult {
|
||||
if (stageBInput === null || stageBInput === undefined || typeof stageBInput !== 'object') {
|
||||
throw new TypeError('stageBInput must be an object');
|
||||
}
|
||||
if (!Array.isArray(stageBInput.eodListings)) {
|
||||
throw new TypeError('stageBInput.eodListings must be an array');
|
||||
}
|
||||
if (!Array.isArray(stageBInput.ibContracts)) {
|
||||
throw new TypeError('stageBInput.ibContracts must be an array');
|
||||
}
|
||||
if (!Array.isArray(stageBInput.tickerSources)) {
|
||||
throw new TypeError('stageBInput.tickerSources must be an array');
|
||||
}
|
||||
if (!Array.isArray(stageBInput.symbolChanges)) {
|
||||
throw new TypeError('stageBInput.symbolChanges must be an array');
|
||||
}
|
||||
|
||||
const normalizedSpans = normalizeObservedBarSpans(barSpans);
|
||||
const lookup = normalizedSpans.lookup;
|
||||
|
||||
let malformedEodListings = 0;
|
||||
let attachedEodListings = 0;
|
||||
const eodListings: StageBEodListingInput[] = [];
|
||||
for (let i = 0; i < stageBInput.eodListings.length; i++) {
|
||||
if (!(i in stageBInput.eodListings)) {
|
||||
malformedEodListings += 1;
|
||||
continue;
|
||||
}
|
||||
const entry = stageBInput.eodListings[i] as unknown;
|
||||
if (entry === undefined || entry === null || typeof entry !== 'object') {
|
||||
malformedEodListings += 1;
|
||||
continue;
|
||||
}
|
||||
const rec = entry as StageBEodListingInput;
|
||||
if (typeof rec.sourceId !== 'string' || rec.sourceId.length === 0) {
|
||||
malformedEodListings += 1;
|
||||
continue;
|
||||
}
|
||||
if (rec.role !== null && rec.role !== undefined && !isExchangeRoleValue(rec.role)) {
|
||||
malformedEodListings += 1;
|
||||
continue;
|
||||
}
|
||||
const observed = lookup?.get('eod', rec.sourceId);
|
||||
if (observed !== undefined) {
|
||||
const span: SpanDateRange = {
|
||||
firstBarDate: observed.firstBarDate,
|
||||
lastBarDate: observed.lastBarDate,
|
||||
};
|
||||
eodListings.push({ ...rec, span });
|
||||
attachedEodListings += 1;
|
||||
} else {
|
||||
eodListings.push({ ...rec });
|
||||
}
|
||||
}
|
||||
|
||||
let malformedIbContracts = 0;
|
||||
const ibContracts: StageBIbContractInput[] = [];
|
||||
for (let i = 0; i < stageBInput.ibContracts.length; i++) {
|
||||
if (!(i in stageBInput.ibContracts)) {
|
||||
malformedIbContracts += 1;
|
||||
continue;
|
||||
}
|
||||
const entry = stageBInput.ibContracts[i] as unknown;
|
||||
if (entry === undefined || entry === null || typeof entry !== 'object') {
|
||||
malformedIbContracts += 1;
|
||||
continue;
|
||||
}
|
||||
const rec = entry as StageBIbContractInput;
|
||||
if (typeof rec.sourceId !== 'string' || rec.sourceId.length === 0) {
|
||||
malformedIbContracts += 1;
|
||||
continue;
|
||||
}
|
||||
ibContracts.push({ ...rec });
|
||||
}
|
||||
|
||||
let malformedTickerSources = 0;
|
||||
let attachedQmTickerSources = 0;
|
||||
const tickerSources: StageBTickerSourceInput[] = [];
|
||||
for (let i = 0; i < stageBInput.tickerSources.length; i++) {
|
||||
if (!(i in stageBInput.tickerSources)) {
|
||||
malformedTickerSources += 1;
|
||||
continue;
|
||||
}
|
||||
const entry = stageBInput.tickerSources[i] as unknown;
|
||||
if (entry === undefined || entry === null || typeof entry !== 'object') {
|
||||
malformedTickerSources += 1;
|
||||
continue;
|
||||
}
|
||||
const rec = entry as StageBTickerSourceInput;
|
||||
if (rec.source !== 'qm' && rec.source !== 'ceo') {
|
||||
malformedTickerSources += 1;
|
||||
continue;
|
||||
}
|
||||
if (typeof rec.sourceId !== 'string' || rec.sourceId.length === 0) {
|
||||
malformedTickerSources += 1;
|
||||
continue;
|
||||
}
|
||||
if (rec.role !== null && rec.role !== undefined && !isExchangeRoleValue(rec.role)) {
|
||||
malformedTickerSources += 1;
|
||||
continue;
|
||||
}
|
||||
if (rec.source === 'qm') {
|
||||
const observed = lookup?.get('qm', rec.sourceId);
|
||||
if (observed !== undefined) {
|
||||
const span: SpanDateRange = {
|
||||
firstBarDate: observed.firstBarDate,
|
||||
lastBarDate: observed.lastBarDate,
|
||||
};
|
||||
tickerSources.push({ ...rec, span });
|
||||
attachedQmTickerSources += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
tickerSources.push({ ...rec });
|
||||
}
|
||||
|
||||
let malformedSymbolChanges = 0;
|
||||
const symbolChanges: StageBSymbolChangeInput[] = [];
|
||||
for (let i = 0; i < stageBInput.symbolChanges.length; i++) {
|
||||
if (!(i in stageBInput.symbolChanges)) {
|
||||
malformedSymbolChanges += 1;
|
||||
continue;
|
||||
}
|
||||
const entry = stageBInput.symbolChanges[i] as unknown;
|
||||
if (entry === undefined || entry === null || typeof entry !== 'object') {
|
||||
malformedSymbolChanges += 1;
|
||||
continue;
|
||||
}
|
||||
const rec = entry as StageBSymbolChangeInput;
|
||||
if (typeof rec.eodSourceId !== 'string' || rec.eodSourceId.length === 0) {
|
||||
malformedSymbolChanges += 1;
|
||||
continue;
|
||||
}
|
||||
if (typeof rec.oldTicker !== 'string') {
|
||||
malformedSymbolChanges += 1;
|
||||
continue;
|
||||
}
|
||||
const parsedOldTicker = parseTickerDetailed(rec.oldTicker, 'eod');
|
||||
if (!parsedOldTicker.ok || parsedOldTicker.tickerRoot.length > MAX_TICKER_ROOT_LENGTH) {
|
||||
malformedSymbolChanges += 1;
|
||||
continue;
|
||||
}
|
||||
if (!isValidExactYmd(rec.effectiveDate) || rec.effectiveDate === '0001-01-01') {
|
||||
malformedSymbolChanges += 1;
|
||||
continue;
|
||||
}
|
||||
if (rec.validFrom !== undefined && rec.validFrom !== null) {
|
||||
if (!isValidExactYmd(rec.validFrom) || rec.validFrom >= rec.effectiveDate) {
|
||||
malformedSymbolChanges += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
symbolChanges.push({ ...rec });
|
||||
}
|
||||
|
||||
return {
|
||||
stageBInput: {
|
||||
eodListings,
|
||||
ibContracts,
|
||||
tickerSources,
|
||||
symbolChanges,
|
||||
},
|
||||
stats: {
|
||||
recordsIn: normalizedSpans.recordsIn,
|
||||
resolved: normalizedSpans.resolved,
|
||||
unresolved: 0,
|
||||
skipped: normalizedSpans.skipped,
|
||||
attachedEodListings,
|
||||
attachedQmTickerSources,
|
||||
},
|
||||
malformed: {
|
||||
barSpans: normalizedSpans.skipped,
|
||||
eodListings: malformedEodListings,
|
||||
ibContracts: malformedIbContracts,
|
||||
tickerSources: malformedTickerSources,
|
||||
symbolChanges: malformedSymbolChanges,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function comparePriceEndpoint(a: PriceSeriesEndpoint, b: PriceSeriesEndpoint): number {
|
||||
return (
|
||||
compareAscii(a.source, b.source) ||
|
||||
compareAscii(a.sourceId, b.sourceId) ||
|
||||
compareAscii(a.currency, b.currency)
|
||||
);
|
||||
}
|
||||
|
||||
function comparePricePair(a: PriceCrossCheckPair, b: PriceCrossCheckPair): number {
|
||||
return comparePriceEndpoint(a.left, b.left) || comparePriceEndpoint(a.right, b.right);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure adapter that derives deterministic Pass 4 candidate pairs from Stage B provider mappings
|
||||
* sharing a listing natural key across distinct sources (`left.source !== right.source`).
|
||||
*/
|
||||
export function derivePass4CandidatePairs(
|
||||
providerMappings: readonly StageBProviderMappingCandidate[]
|
||||
): PriceCrossCheckPair[] {
|
||||
if (!Array.isArray(providerMappings)) {
|
||||
throw new TypeError('providerMappings must be an array');
|
||||
}
|
||||
|
||||
const endpointsByListing = new Map<string, Map<string, PriceSeriesEndpoint>>();
|
||||
for (let i = 0; i < providerMappings.length; i++) {
|
||||
const mapping = providerMappings[i];
|
||||
if (mapping === undefined || mapping === null) {
|
||||
continue;
|
||||
}
|
||||
const listingKey = formatListingNaturalKey(mapping.listingKey);
|
||||
let endpointMap = endpointsByListing.get(listingKey);
|
||||
if (endpointMap === undefined) {
|
||||
endpointMap = new Map<string, PriceSeriesEndpoint>();
|
||||
endpointsByListing.set(listingKey, endpointMap);
|
||||
}
|
||||
const endpointKey = `${mapping.source}\u0000${mapping.sourceId}\u0000${mapping.listingKey.currency}`;
|
||||
if (!endpointMap.has(endpointKey)) {
|
||||
endpointMap.set(endpointKey, {
|
||||
source: mapping.source,
|
||||
sourceId: mapping.sourceId,
|
||||
currency: mapping.listingKey.currency,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const seenPairKeys = new Set<string>();
|
||||
const pairs: PriceCrossCheckPair[] = [];
|
||||
|
||||
for (const endpointMap of endpointsByListing.values()) {
|
||||
if (endpointMap.size < 2) {
|
||||
continue;
|
||||
}
|
||||
const endpoints = Array.from(endpointMap.values()).sort(comparePriceEndpoint);
|
||||
for (let i = 0; i < endpoints.length; i++) {
|
||||
const left = endpoints[i];
|
||||
if (left === undefined) {
|
||||
continue;
|
||||
}
|
||||
for (let j = i + 1; j < endpoints.length; j++) {
|
||||
const right = endpoints[j];
|
||||
if (right === undefined || left.source === right.source) {
|
||||
continue;
|
||||
}
|
||||
const pairKey = `${left.source}\u0000${left.sourceId}\u0000${left.currency}\u0000${right.source}\u0000${right.sourceId}\u0000${right.currency}`;
|
||||
if (seenPairKeys.has(pairKey)) {
|
||||
continue;
|
||||
}
|
||||
seenPairKeys.add(pairKey);
|
||||
pairs.push({ left, right });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pairs.sort(comparePricePair);
|
||||
return pairs;
|
||||
}
|
||||
|
||||
function recordCountryCandidate(
|
||||
target: Map<string, string>,
|
||||
key: string,
|
||||
country: string | undefined | null
|
||||
): void {
|
||||
if (typeof country !== 'string' || country.length === 0) {
|
||||
return;
|
||||
}
|
||||
const existing = target.get(key);
|
||||
if (existing === undefined || compareAscii(country, existing) < 0) {
|
||||
target.set(key, country);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministically builds a `sourceCountryKey(source, sourceId) -> ISO-2 country` map for
|
||||
* `buildMatchReport`'s `resolutionByCountry` summary, prioritizing resolved listing MICs,
|
||||
* then Stage B input MICs, then Stage A issuer countries.
|
||||
*/
|
||||
export function deriveSourceCountries(
|
||||
stageARecords: readonly StageASourceRecord[],
|
||||
stageBInput: Pick<SecurityMasterStageBSourceInput, 'eodListings' | 'tickerSources'>,
|
||||
stageB: Pick<StageBMatchResult, 'providerMappings'>
|
||||
): Map<string, string> {
|
||||
const fromResolvedMappings = new Map<string, string>();
|
||||
for (let i = 0; i < stageB.providerMappings.length; i++) {
|
||||
const mapping = stageB.providerMappings[i];
|
||||
if (mapping === undefined) {
|
||||
continue;
|
||||
}
|
||||
const country = MIC_TO_COUNTRY.get(mapping.listingKey.mic);
|
||||
recordCountryCandidate(
|
||||
fromResolvedMappings,
|
||||
sourceCountryKey(mapping.source, mapping.sourceId),
|
||||
country
|
||||
);
|
||||
}
|
||||
|
||||
const fromStageBMics = new Map<string, string>();
|
||||
for (let i = 0; i < stageBInput.eodListings.length; i++) {
|
||||
const entry = stageBInput.eodListings[i];
|
||||
if (entry === undefined || entry.mic === null) {
|
||||
continue;
|
||||
}
|
||||
recordCountryCandidate(
|
||||
fromStageBMics,
|
||||
sourceCountryKey('eod', entry.sourceId),
|
||||
MIC_TO_COUNTRY.get(entry.mic)
|
||||
);
|
||||
}
|
||||
for (let i = 0; i < stageBInput.tickerSources.length; i++) {
|
||||
const entry = stageBInput.tickerSources[i];
|
||||
if (entry === undefined || entry.mic === null) {
|
||||
continue;
|
||||
}
|
||||
recordCountryCandidate(
|
||||
fromStageBMics,
|
||||
sourceCountryKey(entry.source, entry.sourceId),
|
||||
MIC_TO_COUNTRY.get(entry.mic)
|
||||
);
|
||||
}
|
||||
|
||||
const fromStageA = new Map<string, string>();
|
||||
for (let i = 0; i < stageARecords.length; i++) {
|
||||
const record = stageARecords[i];
|
||||
if (record === undefined) {
|
||||
continue;
|
||||
}
|
||||
const country = normalizeCountryIso2(record.country);
|
||||
recordCountryCandidate(
|
||||
fromStageA,
|
||||
sourceCountryKey(record.source, record.sourceId),
|
||||
country
|
||||
);
|
||||
}
|
||||
|
||||
const merged = new Map<string, string>();
|
||||
for (const [k, v] of fromStageA.entries()) {
|
||||
merged.set(k, v);
|
||||
}
|
||||
for (const [k, v] of fromStageBMics.entries()) {
|
||||
merged.set(k, v);
|
||||
}
|
||||
for (const [k, v] of fromResolvedMappings.entries()) {
|
||||
merged.set(k, v);
|
||||
}
|
||||
|
||||
const sorted = new Map<string, string>();
|
||||
const keys = Array.from(merged.keys()).sort(compareAscii);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i];
|
||||
if (key === undefined) {
|
||||
continue;
|
||||
}
|
||||
const value = merged.get(key);
|
||||
if (value !== undefined) {
|
||||
sorted.set(key, value);
|
||||
}
|
||||
}
|
||||
return sorted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure, in-memory security-master run composer wiring:
|
||||
* `sources + barSpans -> Stage A -> Stage B -> Pass 6 -> optional Pass 4 -> MatchReport + PersistSecurityMasterInput`.
|
||||
*
|
||||
* Performs zero I/O, zero network/database calls, and zero wall-clock reads.
|
||||
*/
|
||||
export function composeSecurityMasterRun(
|
||||
input: ComposeSecurityMasterRunInput,
|
||||
options: ComposeSecurityMasterRunOptions
|
||||
): ComposeSecurityMasterRunResult {
|
||||
if (input === null || input === undefined || typeof input !== 'object') {
|
||||
throw new TypeError('composeSecurityMasterRun requires an input object');
|
||||
}
|
||||
if (input.sources === null || input.sources === undefined || typeof input.sources !== 'object') {
|
||||
throw new TypeError('composeSecurityMasterRun requires input.sources');
|
||||
}
|
||||
const rawSecurityTypes: unknown = input.sources.securityTypeByIsin;
|
||||
if (
|
||||
!(rawSecurityTypes instanceof Map) &&
|
||||
(rawSecurityTypes === null ||
|
||||
rawSecurityTypes === undefined ||
|
||||
typeof (rawSecurityTypes as { entries?: unknown }).entries !== 'function' ||
|
||||
typeof (rawSecurityTypes as { get?: unknown }).get !== 'function')
|
||||
) {
|
||||
throw new TypeError('composeSecurityMasterRun requires sources.securityTypeByIsin Map');
|
||||
}
|
||||
if (options === null || options === undefined || typeof options !== 'object') {
|
||||
throw new TypeError('composeSecurityMasterRun requires an options object');
|
||||
}
|
||||
|
||||
// 1. Stage A (instrument matching)
|
||||
const { sanitized: sanitizedStageARecords, malformed: malformedStageARecords } =
|
||||
sanitizeStageARecords(input.sources.stageARecords);
|
||||
const stageA = matchInstrumentsStageA(sanitizedStageARecords, options.stageA);
|
||||
|
||||
// 2. Stage B (attach bar spans + listing matching)
|
||||
const attached = attachBarSpansToStageBInput(input.sources.stageBInput, input.barSpans);
|
||||
const stageB = matchListingsStageB(
|
||||
{
|
||||
instruments: stageA.instruments,
|
||||
eodListings: attached.stageBInput.eodListings,
|
||||
ibContracts: attached.stageBInput.ibContracts,
|
||||
tickerSources: attached.stageBInput.tickerSources,
|
||||
symbolChanges: attached.stageBInput.symbolChanges,
|
||||
},
|
||||
options.stageB
|
||||
);
|
||||
|
||||
// 3. Pass 6 (delisting chain linking)
|
||||
const otcMics = options.pass6?.otcMics ?? DEFAULT_OTC_MICS;
|
||||
const pass6Options: LinkDelistingChainsOptions = {
|
||||
asOfDate: options.asOfDate,
|
||||
...(options.pass6?.activeGraceDays !== undefined
|
||||
? { activeGraceDays: options.pass6.activeGraceDays }
|
||||
: {}),
|
||||
...(options.pass6?.maxTransferGapDays !== undefined
|
||||
? { maxTransferGapDays: options.pass6.maxTransferGapDays }
|
||||
: {}),
|
||||
...(options.pass6?.overlapToleranceDays !== undefined
|
||||
? { overlapToleranceDays: options.pass6.overlapToleranceDays }
|
||||
: {}),
|
||||
};
|
||||
const pass6 = linkDelistingChains({ listings: stageB.listings, otcMics }, pass6Options);
|
||||
|
||||
// 4. Optional Pass 4 (price cross-check over cross-source pairs sharing a listing)
|
||||
const pass4CandidatePairs = derivePass4CandidatePairs(stageB.providerMappings);
|
||||
const hasSampleCloses =
|
||||
input.sampleCloses !== undefined &&
|
||||
Array.isArray(input.sampleCloses) &&
|
||||
input.sampleCloses.length > 0;
|
||||
const pass4: PriceCrossCheckResult | null = hasSampleCloses
|
||||
? crossCheckPrices(
|
||||
{
|
||||
pairs: pass4CandidatePairs,
|
||||
closes: input.sampleCloses,
|
||||
usdCadByDate: input.fxRates ?? [],
|
||||
},
|
||||
options.pass4
|
||||
)
|
||||
: null;
|
||||
|
||||
// 5. Match report + rendered Markdown / CSV / override-template SQL
|
||||
const sourceCountries =
|
||||
input.sourceCountries ??
|
||||
deriveSourceCountries(sanitizedStageARecords, attached.stageBInput, stageB);
|
||||
const report = buildMatchReport(
|
||||
{
|
||||
...(input.exchanges !== undefined ? { exchanges: input.exchanges } : {}),
|
||||
stageA,
|
||||
stageB,
|
||||
...(pass4 !== null ? { priceCrossCheck: pass4 } : {}),
|
||||
delistingChains: pass6,
|
||||
sourceCountries,
|
||||
},
|
||||
options.report
|
||||
);
|
||||
const reportMarkdown = renderMatchReportMarkdown(report, options.markdown);
|
||||
const conflictsCsv = renderConflictsCsv(report);
|
||||
const overrideTemplateSql = generateOverrideTemplateSql(report);
|
||||
|
||||
// 6. Deterministic PersistSecurityMasterInput (do not call persistSecurityMaster here)
|
||||
const sortedSecurityTypeByIsin = new Map<string, SecurityType>();
|
||||
const secTypeEntries = Array.from(input.sources.securityTypeByIsin.entries()).sort((a, b) =>
|
||||
compareAscii(a[0], b[0])
|
||||
);
|
||||
for (let i = 0; i < secTypeEntries.length; i++) {
|
||||
const entry = secTypeEntries[i];
|
||||
if (entry !== undefined) {
|
||||
sortedSecurityTypeByIsin.set(entry[0], entry[1]);
|
||||
}
|
||||
}
|
||||
|
||||
const persistInput: PersistSecurityMasterInput = {
|
||||
stageA,
|
||||
stageB,
|
||||
...(pass4 !== null ? { pass4 } : {}),
|
||||
pass6,
|
||||
securityTypeByIsin: sortedSecurityTypeByIsin,
|
||||
};
|
||||
|
||||
// 7. Reconciling per-step stats
|
||||
let stageAResolved = 0;
|
||||
let stageAUnresolved = 0;
|
||||
for (const source of STAGE_A_SOURCES) {
|
||||
const s = stageA.stats.bySource[source];
|
||||
stageAResolved += s.tier1Isin + s.tier2Cusip;
|
||||
stageAUnresolved += s.unresolved + s.conflict;
|
||||
}
|
||||
const stageAStepStats: StageAComposeStepStats = {
|
||||
recordsIn: input.sources.stageARecords.length,
|
||||
resolved: stageAResolved,
|
||||
unresolved: stageAUnresolved,
|
||||
skipped: malformedStageARecords,
|
||||
conflicts: stageA.conflicts.length,
|
||||
};
|
||||
|
||||
let stageBTotalProcessed = 0;
|
||||
let stageBResolved = 0;
|
||||
let stageBUnresolved = 0;
|
||||
for (const source of STAGE_B_SOURCES) {
|
||||
const s = stageB.stats.bySource[source];
|
||||
stageBTotalProcessed += s.total;
|
||||
stageBResolved += s.matched;
|
||||
stageBUnresolved += s.unresolved + s.conflict;
|
||||
}
|
||||
const stageBStepStats: StageBComposeStepStats = {
|
||||
recordsIn: stageBTotalProcessed + attached.malformed.tickerSources,
|
||||
resolved: stageBResolved,
|
||||
unresolved: stageBUnresolved,
|
||||
skipped: attached.malformed.tickerSources,
|
||||
conflicts: stageB.conflicts.length,
|
||||
};
|
||||
|
||||
const pass6Skipped =
|
||||
pass6.stats.skippedMalformedEntries +
|
||||
pass6.stats.skippedInvalidDates +
|
||||
pass6.stats.skippedDuplicateKeys;
|
||||
const pass6StepStats: Pass6ComposeStepStats = {
|
||||
recordsIn: pass6.stats.totalInputListings,
|
||||
resolved: pass6.stats.processedListings,
|
||||
unresolved: 0,
|
||||
skipped: pass6Skipped,
|
||||
continuitiesCreated: pass6.stats.continuitiesCreated,
|
||||
conflicts: pass6.conflicts.length,
|
||||
};
|
||||
|
||||
const pass4StepStats: Pass4ComposeStepStats =
|
||||
pass4 === null
|
||||
? {
|
||||
status: 'skipped',
|
||||
recordsIn: pass4CandidatePairs.length,
|
||||
resolved: 0,
|
||||
unresolved: 0,
|
||||
skipped: pass4CandidatePairs.length,
|
||||
conflicts: 0,
|
||||
}
|
||||
: {
|
||||
status: 'executed',
|
||||
recordsIn: pass4.stats.pairsIn,
|
||||
resolved: pass4.stats.byVerdict.confirmed,
|
||||
unresolved:
|
||||
pass4.stats.byVerdict.ratio_mismatch +
|
||||
pass4.stats.byVerdict.low_correlation +
|
||||
pass4.stats.byVerdict.insufficient_data +
|
||||
pass4.stats.byVerdict.unsupported_currency_pair,
|
||||
skipped: 0,
|
||||
conflicts: pass4.conflicts.length,
|
||||
};
|
||||
|
||||
const pass4ConflictsCount = pass4?.conflicts.length ?? 0;
|
||||
const conflictTotals: ComposeConflictTotals = {
|
||||
stageA: stageA.conflicts.length,
|
||||
stageB: stageB.conflicts.length,
|
||||
pass4: pass4ConflictsCount,
|
||||
pass6: pass6.conflicts.length,
|
||||
total:
|
||||
stageA.conflicts.length +
|
||||
stageB.conflicts.length +
|
||||
pass4ConflictsCount +
|
||||
pass6.conflicts.length,
|
||||
};
|
||||
|
||||
const malformedSampleCloses = pass4?.stats.droppedInvalidCloses ?? 0;
|
||||
const malformedFxRates = pass4?.stats.droppedInvalidFxRates ?? 0;
|
||||
const malformedInputs: ComposeMalformedInputStats = {
|
||||
stageARecords: malformedStageARecords,
|
||||
eodListings: attached.malformed.eodListings,
|
||||
ibContracts: attached.malformed.ibContracts,
|
||||
tickerSources: attached.malformed.tickerSources,
|
||||
symbolChanges: attached.malformed.symbolChanges,
|
||||
barSpans: attached.malformed.barSpans,
|
||||
sampleCloses: malformedSampleCloses,
|
||||
fxRates: malformedFxRates,
|
||||
total:
|
||||
malformedStageARecords +
|
||||
attached.malformed.eodListings +
|
||||
attached.malformed.ibContracts +
|
||||
attached.malformed.tickerSources +
|
||||
attached.malformed.symbolChanges +
|
||||
attached.malformed.barSpans +
|
||||
malformedSampleCloses +
|
||||
malformedFxRates,
|
||||
};
|
||||
|
||||
return {
|
||||
stageA,
|
||||
stageB,
|
||||
pass6,
|
||||
pass4,
|
||||
pass4CandidatePairs,
|
||||
report,
|
||||
reportMarkdown,
|
||||
conflictsCsv,
|
||||
overrideTemplateSql,
|
||||
persistInput,
|
||||
stats: {
|
||||
barSpans: attached.stats,
|
||||
stageA: stageAStepStats,
|
||||
stageB: stageBStepStats,
|
||||
pass6: pass6StepStats,
|
||||
pass4: pass4StepStats,
|
||||
conflicts: conflictTotals,
|
||||
malformedInputs,
|
||||
},
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue