From 3bdf7a8da6ad5e129fc3f8c838305dfc93a036bd Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 05:38:20 -0500 Subject: [PATCH] =?UTF-8?q?T-88:=20M1.1m=20=E2=80=94=20Security-master=20r?= =?UTF-8?q?un=20composer:=20readers=20output=20+=20bar=20spans=20=E2=86=92?= =?UTF-8?q?=20Stage=20A=20=E2=86=92=20Stage=20B=20=E2=86=92=20Pass=206=20?= =?UTF-8?q?=E2=86=92=20Pass=204=20=E2=86=92=20match=20report=20+=20persist?= =?UTF-8?q?=20input=20(pure,=20in-memory,=20no=20new=20dependencies)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/stock/data-pipeline/README.md | 18 + .../src/security-master/index.ts | 23 + .../src/security-master/match-report.ts | 7 +- .../src/security-master/persist.ts | 82 +- .../data-pipeline/src/security-master/run.ts | 958 ++++++++++++++++++ test/postgres/security-master-run.test.ts | 511 ++++++++++ .../unit/security-master-match-report.test.ts | 27 + test/unit/security-master-persist.test.ts | 149 +++ test/unit/security-master-run.test.ts | 953 +++++++++++++++++ 9 files changed, 2722 insertions(+), 6 deletions(-) create mode 100644 apps/stock/data-pipeline/src/security-master/run.ts create mode 100644 test/postgres/security-master-run.test.ts create mode 100644 test/unit/security-master-run.test.ts diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index 809cbd57..8f3262c9 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -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`). diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 1e7998fc..92c93268 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -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, diff --git a/apps/stock/data-pipeline/src/security-master/match-report.ts b/apps/stock/data-pipeline/src/security-master/match-report.ts index 6ab8b082..3e9ab06a 100644 --- a/apps/stock/data-pipeline/src/security-master/match-report.ts +++ b/apps/stock/data-pipeline/src/security-master/match-report.ts @@ -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}`, diff --git a/apps/stock/data-pipeline/src/security-master/persist.ts b/apps/stock/data-pipeline/src/security-master/persist.ts index b90ea6cd..17a4b606 100644 --- a/apps/stock/data-pipeline/src/security-master/persist.ts +++ b/apps/stock/data-pipeline/src/security-master/persist.ts @@ -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; } @@ -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(); 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(); - 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( `SELECT DISTINCT rc.source, @@ -1377,9 +1419,43 @@ async function persistWithinTransaction( } } + const existingPass4ConflictKeys = new Set(); + for (let offset = 0; offset < pass4Conflicts.length; offset += chunkSize) { + const slice = pass4Conflicts.slice(offset, offset + chunkSize); + const res = await client.query( + `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); diff --git a/apps/stock/data-pipeline/src/security-master/run.ts b/apps/stock/data-pipeline/src/security-master/run.ts new file mode 100644 index 00000000..f7f31507 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/run.ts @@ -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 { + readonly otcMics?: ReadonlySet; +} + +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 = (() => { + const map = new Map(); + 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; + 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>(); + 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(); + 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(); + 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, + 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, + stageB: Pick +): Map { + const fromResolvedMappings = new Map(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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, + }, + }; +} diff --git a/test/postgres/security-master-run.test.ts b/test/postgres/security-master-run.test.ts new file mode 100644 index 00000000..06561ad4 --- /dev/null +++ b/test/postgres/security-master-run.test.ts @@ -0,0 +1,511 @@ +import { randomUUID } from 'node:crypto'; +import { afterEach, describe, expect, test } from 'bun:test'; +import { Pool, type PoolClient } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import type { BarSpan } from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; +import { + classifySourceExchanges, + composeSecurityMasterRun, + CONTINUITY_KIND_OTC_DELIST_TRANSFER, + formatListingNaturalKey, + persistSecurityMaster, + type FxRateByDateRecord, + type SampleCloseRecord, + type SecurityMasterQueryable, + type SecurityMasterSourcesResult, + type SecurityType, + type StageASourceRecord, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBTickerSourceInput, +} from '../../apps/stock/data-pipeline/src/security-master'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('security-master-run-pg-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; + +const cleanup: (() => Promise | void)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) { + await close(); + } +}); + +async function createIsolatedFixture(statementTimeoutMs = 15_000) { + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { + throw new Error('Dedicated stock_bot_safety database required'); + } + const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; + const admin = new Pool({ connectionString: url }); + await admin.query(`CREATE SCHEMA ${schema}`); + const pool = new Pool({ + connectionString: url, + options: `-c search_path=${schema} -c statement_timeout=${statementTimeoutMs} -c lock_timeout=15000`, + }); + cleanup.push(async () => { + await pool.end(); + await admin.query(`DROP SCHEMA ${schema} CASCADE`); + await admin.end(); + }); + + const postgres = new PostgreSQLClient( + { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, + logger + ); + Object.defineProperty(postgres, 'connectionPool', { + get: () => ({ + connect: () => pool.connect(), + }), + }); + + await runPostgresMigrations(postgres, { track: 'master' }); + + return { pool, schema, postgres }; +} + +async function withClient(pool: Pool, fn: (client: PoolClient) => Promise): Promise { + const client = await pool.connect(); + try { + return await fn(client); + } finally { + client.release(); + } +} + +async function getSevenTableCounts(pool: Pool): Promise> { + const tables = [ + 'instrument', + 'instrument_identifier_history', + 'listing', + 'listing_symbol_history', + 'provider_mapping', + 'resolution_conflict', + 'corporate_action_continuity', + ] as const; + const counts: Record = {}; + for (const table of tables) { + const res = await pool.query<{ count: number }>(`SELECT count(*)::int AS count FROM ${table}`); + counts[table] = res.rows[0]?.count ?? -1; + } + return counts; +} + +function makeEmptyCollectionStats( + collection: 'eodSymbols' | 'ibSymbols' | 'qmSymbols' | 'ceoSymbols' | 'eodSymbolChange' +) { + return { + collection, + docsRead: 0, + emitted: 0, + invalidIdentifiersNulled: 0, + skips: { + missingId: 0, + invalidFieldType: 0, + invalidIdentifier: 0, + excludedMutualFund: 0, + unmappedExchange: 0, + outOfScopeCountry: 0, + }, + }; +} + +function buildComposedExitCriterionRun() { + const stageARecords: StageASourceRecord[] = [ + { + source: 'ib', + sourceId: '265598', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc.', + }, + { + source: 'eod', + sourceId: 'AAPL.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc', + }, + { + source: 'eod', + sourceId: 'FB_OLD.US', + isin: 'US30303M1027', + cusip: '30303M102', + country: 'US', + currency: 'USD', + name: 'Meta Platforms Inc', + }, + { + source: 'eod', + sourceId: 'FB_ETF.US', + isin: 'US4642872000', + cusip: '464287200', + country: 'US', + currency: 'USD', + name: 'FB Thematic ETF', + }, + { + source: 'eod', + sourceId: 'SIVB.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group', + }, + { + source: 'eod', + sourceId: 'SIVBQ.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group', + }, + { + source: 'eod', + sourceId: 'SHOP.TO', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'CAD', + name: 'Shopify Inc.', + }, + { + source: 'eod', + sourceId: 'SHOP.US', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'USD', + name: 'Shopify Inc.', + }, + { + source: 'ib', + sourceId: '2001', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'CAD', + name: 'Shopify Inc.', + }, + { + source: 'ib', + sourceId: '2002', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'USD', + name: 'Shopify Inc.', + }, + ]; + + const eodListings: StageBEodListingInput[] = [ + { sourceId: 'AAPL.US', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'FB_OLD.US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'FB_ETF.US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'SIVB.US', ticker: 'SIVB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'SIVBQ.US', ticker: 'SIVBQ', mic: 'OTCM', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'SHOP.TO', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue', currency: 'CAD', span: null }, + { sourceId: 'SHOP.US', ticker: 'SHOP', mic: 'XNYS', role: 'primary_venue', currency: 'USD', span: null }, + ]; + + const ibContracts: StageBIbContractInput[] = [ + { sourceId: '265598', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: '2001', conid: 2001, currency: 'CAD', primaryExchange: 'TSE' }, + { sourceId: '2002', conid: 2002, currency: 'USD', primaryExchange: 'NYSE' }, + ]; + + const tickerSources: StageBTickerSourceInput[] = [ + { source: 'qm', sourceId: 'AAPL:US', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { source: 'qm', sourceId: 'FB_OLD:US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { source: 'qm', sourceId: 'FB_ETF:US', ticker: 'FB', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { source: 'qm', sourceId: 'SHOP:CA', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue', currency: 'CAD', span: null }, + { + source: 'ceo', + sourceId: 'ceo:SHOP', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-11-28' }, + }, + ]; + + const barSpans: BarSpan[] = [ + { source: 'eod', sourceId: 'AAPL.US', firstBarDate: '2010-01-04', lastBarDate: '2025-11-28', barCount: 4000 }, + { source: 'eod', sourceId: 'FB_OLD.US', firstBarDate: '2012-05-18', lastBarDate: '2022-06-08', barCount: 2530 }, + { source: 'eod', sourceId: 'FB_ETF.US', firstBarDate: '2025-01-02', lastBarDate: '2025-11-28', barCount: 230 }, + { source: 'eod', sourceId: 'SIVB.US', firstBarDate: '2015-01-02', lastBarDate: '2023-03-10', barCount: 2060 }, + { source: 'eod', sourceId: 'SIVBQ.US', firstBarDate: '2023-03-28', lastBarDate: '2024-11-07', barCount: 410 }, + { source: 'eod', sourceId: 'SHOP.TO', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 }, + { source: 'eod', sourceId: 'SHOP.US', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 }, + { source: 'qm', sourceId: 'AAPL:US', firstBarDate: '2015-01-02', lastBarDate: '2025-11-28', barCount: 2700 }, + { source: 'qm', sourceId: 'FB_OLD:US', firstBarDate: '2014-01-02', lastBarDate: '2022-06-08', barCount: 2100 }, + { source: 'qm', sourceId: 'FB_ETF:US', firstBarDate: '2025-02-03', lastBarDate: '2025-11-28', barCount: 205 }, + { source: 'qm', sourceId: 'SHOP:CA', firstBarDate: '2018-01-02', lastBarDate: '2025-11-28', barCount: 1980 }, + ]; + + const securityTypeByIsin = new Map([ + ['US0378331005', 'common'], + ['US30303M1027', 'common'], + ['US4642872000', 'etf'], + ['US78486Q1013', 'common'], + ['CA82509L1076', 'common'], + ]); + + const sources: SecurityMasterSourcesResult = { + stageARecords, + stageBInput: { + eodListings, + ibContracts, + tickerSources, + symbolChanges: [], + }, + securityTypeRecords: [], + securityTypeByIsin, + securityTypeStats: { + totalRecords: 0, + mapped: 0, + missingType: 0, + unknownType: 0, + invalidIsin: 0, + isinsResolved: securityTypeByIsin.size, + isinsConflicting: 0, + conflictsTruncated: 0, + }, + securityTypeLoaderStats: { + totalRecords: 0, + mapped: 0, + missingType: 0, + unknownType: 0, + invalidIsin: 0, + isinsResolved: securityTypeByIsin.size, + isinsConflicting: 0, + conflictsTruncated: 0, + }, + unknownSecurityTypes: [], + securityTypeConflicts: [], + stats: { + eodSymbols: makeEmptyCollectionStats('eodSymbols'), + ibSymbols: makeEmptyCollectionStats('ibSymbols'), + qmSymbols: makeEmptyCollectionStats('qmSymbols'), + ceoSymbols: makeEmptyCollectionStats('ceoSymbols'), + eodSymbolChange: makeEmptyCollectionStats('eodSymbolChange'), + }, + }; + + const exchanges = classifySourceExchanges([ + { source: 'eod', sourceCode: 'NASDAQ', name: 'NASDAQ', country: 'US', operatingMic: 'XNAS' }, + { source: 'eod', sourceCode: 'NYSE', name: 'NYSE', country: 'US', operatingMic: 'XNYS' }, + { source: 'eod', sourceCode: 'TO', name: 'TSX', country: 'CA', operatingMic: 'XTSE' }, + { source: 'eod', sourceCode: 'OTC', name: 'OTC', country: 'US', operatingMic: 'OTCM' }, + ]); + + const dates = [ + '2025-01-02', + '2025-01-03', + '2025-01-06', + '2025-01-07', + '2025-01-08', + '2025-01-09', + ]; + const aaplPrices = [185.0, 188.5, 184.2, 191.0, 195.4, 193.1]; + const shopCadPrices = [140.0, 145.0, 138.0, 148.5, 152.0, 149.0]; + + const sampleCloses: SampleCloseRecord[] = []; + const fxRates: FxRateByDateRecord[] = []; + for (let i = 0; i < dates.length; i++) { + const date = dates[i]!; + const aapl = aaplPrices[i]!; + const shop = shopCadPrices[i]!; + fxRates.push({ date, usdCad: 1.38 + i * 0.005 }); + // AAPL: confirmed + sampleCloses.push({ source: 'eod', sourceId: 'AAPL.US', date, close: aapl }); + sampleCloses.push({ source: 'qm', sourceId: 'AAPL:US', date, close: aapl * 1.001 }); + // SHOP XTSE: two Pass 4 mismatches sharing left endpoint (ceo:SHOP vs eod:SHOP.TO, ceo:SHOP vs qm:SHOP:CA) + // and eod:SHOP.TO vs qm:SHOP:CA -> all three pairs mismatch! + sampleCloses.push({ source: 'ceo', sourceId: 'ceo:SHOP', date, close: shop }); + sampleCloses.push({ source: 'eod', sourceId: 'SHOP.TO', date, close: shop * 1.5 }); + sampleCloses.push({ source: 'qm', sourceId: 'SHOP:CA', date, close: shop * 2.2 }); + } + + return composeSecurityMasterRun( + { sources, barSpans, exchanges, sampleCloses, fxRates }, + { asOfDate: '2025-11-28' } + ); +} + +describe('composeSecurityMasterRun -> persistSecurityMaster PostgreSQL integration', () => { + test('persists FB vs FB-ETF distinct listing_ids, SIVB -> SIVBQ continuity, Pass 4 conflicts (including shared left endpoint), and is idempotent on re-run', async () => { + const { pool } = await createIsolatedFixture(); + const composed = buildComposedExitCriterionRun(); + + // First run + const first = await withClient(pool, client => + persistSecurityMaster(client as unknown as SecurityMasterQueryable, composed.persistInput) + ); + + expect(first.instrumentsInserted).toBe(5); + expect(first.listingsInserted).toBe(7); + expect(first.continuitiesInserted).toBe(1); + expect(first.conflictsInserted).toBe(composed.pass4!.conflicts.length); + expect(first.conflictsInserted).toBeGreaterThanOrEqual(3); + + // 1. Two distinct listing_ids and instrument_ids for FB common vs FB ETF + const fbCommonKey = formatListingNaturalKey({ + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }); + const fbEtfKey = formatListingNaturalKey({ + primaryIsin: 'US4642872000', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }); + const fbCommonListingId = first.listingIdByKey.get(fbCommonKey); + const fbEtfListingId = first.listingIdByKey.get(fbEtfKey); + expect(fbCommonListingId).toBeDefined(); + expect(fbEtfListingId).toBeDefined(); + expect(fbCommonListingId).not.toBe(fbEtfListingId); + + const fbRows = await pool.query<{ + listing_id: number; + instrument_id: number; + primary_isin: string; + security_type: string; + }>( + `SELECT l.listing_id, l.instrument_id, i.primary_isin, i.security_type + FROM listing l + JOIN instrument i ON i.instrument_id = l.instrument_id + WHERE l.ticker_root = 'FB' + ORDER BY i.primary_isin` + ); + expect(fbRows.rows.length).toBe(2); + expect(fbRows.rows[0]?.primary_isin).toBe('US30303M1027'); + expect(fbRows.rows[0]?.security_type).toBe('common'); + expect(fbRows.rows[1]?.primary_isin).toBe('US4642872000'); + expect(fbRows.rows[1]?.security_type).toBe('etf'); + expect(fbRows.rows[0]?.listing_id).not.toBe(fbRows.rows[1]?.listing_id); + + // 2. SIVB -> SIVBQ continuity row and delist outcomes + const sivbKey = formatListingNaturalKey({ + primaryIsin: 'US78486Q1013', + mic: 'XNAS', + tickerRoot: 'SIVB', + classSuffix: '', + currency: 'USD', + }); + const sivbqKey = formatListingNaturalKey({ + primaryIsin: 'US78486Q1013', + mic: 'OTCM', + tickerRoot: 'SIVBQ', + classSuffix: '', + currency: 'USD', + }); + const sivbListingId = first.listingIdByKey.get(sivbKey); + const sivbqListingId = first.listingIdByKey.get(sivbqKey); + expect(sivbListingId).toBeDefined(); + expect(sivbqListingId).toBeDefined(); + + const continuityRows = await pool.query<{ + from_listing_id: number; + to_listing_id: number; + kind: string; + effective_date: string; + }>( + `SELECT from_listing_id, to_listing_id, kind, effective_date::text + FROM corporate_action_continuity` + ); + expect(continuityRows.rows.length).toBe(1); + expect(continuityRows.rows[0]).toEqual({ + from_listing_id: sivbListingId!, + to_listing_id: sivbqListingId!, + kind: CONTINUITY_KIND_OTC_DELIST_TRANSFER, + effective_date: '2023-03-28', + }); + + const sivbDelistRows = await pool.query<{ + ticker_root: string; + delist_reason: string | null; + terminal_return: string | null; + }>( + `SELECT ticker_root, delist_reason, terminal_return::text + FROM listing + WHERE listing_id IN ($1, $2) + ORDER BY ticker_root`, + [sivbListingId, sivbqListingId] + ); + expect(sivbDelistRows.rows).toEqual([ + { ticker_root: 'SIVB', delist_reason: 'moved_to_otc', terminal_return: null }, + { ticker_root: 'SIVBQ', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1.000000' }, + ]); + + // 3. Pass 4 price_ratio_mismatch rows persisted with both endpoints in JSONB detail + const conflictRows = await pool.query<{ + source: string; + source_id: string; + conflict_kind: string; + detail: { left: { source: string; sourceId: string }; right: { source: string; sourceId: string } }; + status: string; + }>( + `SELECT source, source_id, conflict_kind, detail, status + FROM resolution_conflict + ORDER BY source, source_id, detail::text` + ); + expect(conflictRows.rows.length).toBe(composed.pass4!.conflicts.length); + const sharedLeftRows = conflictRows.rows.filter( + r => r.source === 'ceo' && r.source_id === 'ceo:SHOP' && r.conflict_kind === 'price_ratio_mismatch' + ); + expect(sharedLeftRows.length).toBe(2); + expect(sharedLeftRows.map(r => r.detail.right.sourceId).sort()).toEqual([ + 'SHOP.TO', + 'SHOP:CA', + ]); + for (const row of conflictRows.rows) { + expect(row.status).toBe('open'); + expect(row.detail.left.sourceId).toBe(row.source_id); + expect(row.detail.right.sourceId.length).toBeGreaterThan(0); + } + + const countsAfterFirst = await getSevenTableCounts(pool); + + // 4. Second identical run changes zero IDs and inserts zero rows across all 7 tables + const second = await withClient(pool, client => + persistSecurityMaster(client as unknown as SecurityMasterQueryable, composed.persistInput) + ); + + expect(second.instrumentsInserted).toBe(0); + expect(second.instrumentsUpdated).toBe(0); + expect(second.identifierHistoryInserted).toBe(0); + expect(second.listingsInserted).toBe(0); + expect(second.listingsUpdated).toBe(0); + expect(second.listingSymbolHistoryInserted).toBe(0); + expect(second.listingSymbolHistoryUpdated).toBe(0); + expect(second.providerMappingsInserted).toBe(0); + expect(second.providerMappingsUpdated).toBe(0); + expect(second.conflictsInserted).toBe(0); + expect(second.conflictsUnchanged).toBe(composed.pass4!.conflicts.length); + expect(second.continuitiesInserted).toBe(0); + expect(second.continuitiesUpdated).toBe(0); + expect(second.continuitiesUnchanged).toBe(1); + + expect(Array.from(second.instrumentIdByIsin.entries())).toEqual( + Array.from(first.instrumentIdByIsin.entries()) + ); + expect(Array.from(second.listingIdByKey.entries())).toEqual( + Array.from(first.listingIdByKey.entries()) + ); + + const countsAfterSecond = await getSevenTableCounts(pool); + expect(countsAfterSecond).toEqual(countsAfterFirst); + }); +}); diff --git a/test/unit/security-master-match-report.test.ts b/test/unit/security-master-match-report.test.ts index d60e1b80..8fe87dc9 100644 --- a/test/unit/security-master-match-report.test.ts +++ b/test/unit/security-master-match-report.test.ts @@ -1055,4 +1055,31 @@ describe('generateOverrideSeedSql & generateOverrideTemplateSql', () => { } expect(emptyTemplate).toContain('No source-attributed open conflicts'); }); + + test('renderMatchReportMarkdown emits Status: skipped when priceCrossCheck is null and omits it when supplied', () => { + const reportWithoutPass4 = buildMatchReport({ + stageA: makeEmptyStageA(), + stageB: makeEmptyStageB(), + }); + expect(reportWithoutPass4.priceCrossCheck).toBeNull(); + const mdSkipped = renderMatchReportMarkdown(reportWithoutPass4); + expect(mdSkipped).toContain( + '## Pass 4 Price Cross-Check Verdicts\n\n- Status: skipped (no sample closes supplied)\n- Pairs In: 0' + ); + + const pass4 = crossCheckPrices({ + pairs: [], + closes: [], + usdCadByDate: [], + }); + const reportWithPass4 = buildMatchReport({ + stageA: makeEmptyStageA(), + stageB: makeEmptyStageB(), + priceCrossCheck: pass4, + }); + expect(reportWithPass4.priceCrossCheck).not.toBeNull(); + const mdExecuted = renderMatchReportMarkdown(reportWithPass4); + expect(mdExecuted).not.toContain('Status: skipped'); + expect(mdExecuted).toContain('## Pass 4 Price Cross-Check Verdicts\n\n- Pairs In: 0'); + }); }); diff --git a/test/unit/security-master-persist.test.ts b/test/unit/security-master-persist.test.ts index c6f098ba..bbe42567 100644 --- a/test/unit/security-master-persist.test.ts +++ b/test/unit/security-master-persist.test.ts @@ -10,6 +10,8 @@ import { stableJsonStringify, type DelistingChainResult, type PersistSecurityMasterInput, + type PriceCrossCheckConflictRecord, + type PriceCrossCheckResult, type SecurityMasterQueryable, type SecurityMasterQueryResult, type SecurityType, @@ -801,4 +803,151 @@ describe('persistSecurityMaster unit tests', () => { expect(result.providerMappingsUpdated).toBe(1); // eod (existing+overridden) expect(result.providerMappingsUnchanged).toBe(2); // qm AAPL:US + OVR_SAME }); + + test('pass4 omitted leaves conflict SQL and counts identical to non-Pass-4 behavior', async () => { + const stageA = emptyStageA(); + stageA.conflicts.push({ + source: 'eod', + sourceId: 'BAD.US', + conflictKind: 'isin_cusip_mismatch', + detail: { + isin: 'US0378331005', + cusip: '594918104', + country: 'US', + derivedIsin: 'US5949181045', + }, + }); + const stageB = emptyStageB(); + + const { client, queries } = createMockClient(); + const result = await persistSecurityMaster(client, { + stageA, + stageB, + securityTypeByIsin: new Map(), + }); + + expect(result.conflictsInserted).toBe(1); + expect(result.conflictsUnchanged).toBe(0); + expect(result.conflictsDeduplicated).toBe(0); + + // Must run ONLY the 3-column non-Pass-4 existence query, never the Pass 4 JSONB detail query. + const conflictSelects = queries.filter(q => q.text.includes('FROM resolution_conflict rc')); + expect(conflictSelects.length).toBe(1); + expect(conflictSelects[0]?.text).not.toContain('rc.detail = u.detail'); + }); + + test('pass4 supplied preserves distinct pairs sharing a left endpoint, deduplicates exact duplicates, and checks rc.detail = u.detail', async () => { + const stageA = emptyStageA(); + const stageB = emptyStageB(); + + const conflictPair1: PriceCrossCheckConflictRecord = { + source: 'eod', + sourceId: 'AAPL.US', + conflictKind: 'price_ratio_mismatch', + detail: { + left: { source: 'eod', sourceId: 'AAPL.US', currency: 'USD' }, + right: { source: 'qm', sourceId: 'AAPL:US', currency: 'USD' }, + verdict: 'ratio_mismatch', + usableDates: 5, + medianRatio: 1.5, + priceCorr: 0.99, + ratioTolerance: 0.02, + minCorrelation: 0.9, + }, + }; + const conflictPair2SameLeft: PriceCrossCheckConflictRecord = { + source: 'eod', + sourceId: 'AAPL.US', + conflictKind: 'price_ratio_mismatch', + detail: { + left: { source: 'eod', sourceId: 'AAPL.US', currency: 'USD' }, + right: { source: 'ceo', sourceId: 'AAPL', currency: 'USD' }, + verdict: 'ratio_mismatch', + usableDates: 5, + medianRatio: 2.0, + priceCorr: 0.98, + ratioTolerance: 0.02, + minCorrelation: 0.9, + }, + }; + + const pass4: PriceCrossCheckResult = { + results: [], + conflicts: [conflictPair1, conflictPair2SameLeft, conflictPair1], // 1 exact duplicate + stats: { + pairsIn: 2, + invalidPairs: 0, + byVerdict: { + unsupported_currency_pair: 0, + insufficient_data: 0, + ratio_mismatch: 2, + low_correlation: 0, + confirmed: 0, + }, + conflictsEmitted: 3, + droppedInvalidCloses: 0, + droppedConflictingCloses: 0, + droppedInvalidFxRates: 0, + droppedConflictingFxRates: 0, + skippedMissingFxDates: 0, + }, + }; + + // First run: neither pair exists in DB -> both inserted, 1 exact duplicate deduplicated. + const first = createMockClient(); + const firstResult = await persistSecurityMaster(first.client, { + stageA, + stageB, + pass4, + securityTypeByIsin: new Map(), + }); + + expect(firstResult.conflictsInserted).toBe(2); + expect(firstResult.conflictsUnchanged).toBe(0); + expect(firstResult.conflictsDeduplicated).toBe(1); + + const pass4Selects = first.queries.filter( + q => q.text.includes('FROM resolution_conflict rc') && q.text.includes('rc.detail = u.detail') + ); + expect(pass4Selects.length).toBe(1); + const conflictInserts = first.queries.filter(q => + q.text.startsWith('INSERT INTO resolution_conflict') + ); + expect(conflictInserts.length).toBe(1); + expect((conflictInserts[0]?.values?.[0] as string[]).length).toBe(2); + + // Second run: simulate pair 1 already existing in DB via its conflict_key -> only pair 2 inserted. + const existingKey = + 'eod\u0000AAPL.US\u0000price_ratio_mismatch\u0000qm\u0000AAPL:US'; + const second = createMockClient(text => { + if (text.includes('FROM resolution_conflict rc') && text.includes('rc.detail = u.detail')) { + return { rows: [{ conflict_key: existingKey }] }; + } + return { rows: [] }; + }); + + const secondResult = await persistSecurityMaster(second.client, { + stageA, + stageB, + pass4, + securityTypeByIsin: new Map(), + }); + + expect(secondResult.conflictsUnchanged).toBe(1); + expect(secondResult.conflictsInserted).toBe(1); + expect(secondResult.conflictsDeduplicated).toBe(1); + }); + + test('rejects invalid pass4.conflicts shape before BEGIN', async () => { + const { client, queries } = createMockClient(); + await expect( + persistSecurityMaster(client, { + stageA: emptyStageA(), + stageB: emptyStageB(), + pass4: { conflicts: 'bad' } as unknown as PriceCrossCheckResult, + securityTypeByIsin: new Map(), + }) + ).rejects.toThrow(TypeError); + expect(queries.length).toBe(0); + }); }); diff --git a/test/unit/security-master-run.test.ts b/test/unit/security-master-run.test.ts new file mode 100644 index 00000000..a933d3f6 --- /dev/null +++ b/test/unit/security-master-run.test.ts @@ -0,0 +1,953 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { + BarSpanIndex, + type BarSpan, + type ComputeBarSpansResult, +} from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; +import { cusipToIsin } from '../../apps/stock/data-pipeline/src/normalization/identifiers'; +import { + attachBarSpansToStageBInput, + classifySourceExchanges, + composeSecurityMasterRun, + CONTINUITY_KIND_OTC_DELIST_TRANSFER, + derivePass4CandidatePairs, + deriveSourceCountries, + formatListingNaturalKey, + type ComposeSecurityMasterRunInput, + type FxRateByDateRecord, + type SampleCloseRecord, + type SecurityMasterSourcesResult, + type SecurityMasterStageBSourceInput, + type SecurityType, + type StageASourceRecord, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBSymbolChangeInput, + type StageBTickerSourceInput, +} from '../../apps/stock/data-pipeline/src/security-master'; + +const runSourcePath = fileURLToPath( + new URL('../../apps/stock/data-pipeline/src/security-master/run.ts', import.meta.url) +); + +function makeRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function shuffleWithSeed(items: readonly T[], seed: number): T[] { + const copy = [...items]; + const rng = makeRng(seed); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + const a = copy[i]; + const b = copy[j]; + if (a !== undefined && b !== undefined) { + copy[i] = b; + copy[j] = a; + } + } + return copy; +} + +function makeEmptyCollectionStats( + collection: 'eodSymbols' | 'ibSymbols' | 'qmSymbols' | 'ceoSymbols' | 'eodSymbolChange' +) { + return { + collection, + docsRead: 0, + emitted: 0, + invalidIdentifiersNulled: 0, + skips: { + missingId: 0, + invalidFieldType: 0, + invalidIdentifier: 0, + excludedMutualFund: 0, + unmappedExchange: 0, + outOfScopeCountry: 0, + }, + }; +} + +function makeSourcesResult(params: { + stageARecords: StageASourceRecord[]; + eodListings: StageBEodListingInput[]; + ibContracts: StageBIbContractInput[]; + tickerSources: StageBTickerSourceInput[]; + symbolChanges?: StageBSymbolChangeInput[]; + securityTypeByIsin: Map; +}): SecurityMasterSourcesResult { + return { + stageARecords: params.stageARecords, + stageBInput: { + eodListings: params.eodListings, + ibContracts: params.ibContracts, + tickerSources: params.tickerSources, + symbolChanges: params.symbolChanges ?? [], + }, + securityTypeRecords: [], + securityTypeByIsin: params.securityTypeByIsin, + securityTypeStats: { + totalRecords: 0, + mapped: 0, + missingType: 0, + unknownType: 0, + invalidIsin: 0, + isinsResolved: params.securityTypeByIsin.size, + isinsConflicting: 0, + conflictsTruncated: 0, + }, + securityTypeLoaderStats: { + totalRecords: 0, + mapped: 0, + missingType: 0, + unknownType: 0, + invalidIsin: 0, + isinsResolved: params.securityTypeByIsin.size, + isinsConflicting: 0, + conflictsTruncated: 0, + }, + unknownSecurityTypes: [], + securityTypeConflicts: [], + stats: { + eodSymbols: makeEmptyCollectionStats('eodSymbols'), + ibSymbols: makeEmptyCollectionStats('ibSymbols'), + qmSymbols: makeEmptyCollectionStats('qmSymbols'), + ceoSymbols: makeEmptyCollectionStats('ceoSymbols'), + eodSymbolChange: makeEmptyCollectionStats('eodSymbolChange'), + }, + }; +} + +/** + * Canonical M1 exit-criterion fixture: + * - AAPL (`US0378331005`): EOD + IB + QM on XNAS (USD) + * - FB common (`US30303M1027`, 2012-2022) vs FB ETF (`US4642872000`, 2025) on XNAS (USD) + * - SIVB (`US78486Q1013`) XNAS (2015..2023-03-10) -> SIVBQ OTCM (2023-03-28..2024-11-07) + * - SHOP (`CA82509L1076`) interlisted XTSE (CAD) + XNYS (USD) with IB contracts in CAD & USD + */ +function buildCanonicalFixture(): { + input: ComposeSecurityMasterRunInput; + sampleCloses: SampleCloseRecord[]; + fxRates: FxRateByDateRecord[]; +} { + const stageARecords: StageASourceRecord[] = [ + { + source: 'ib', + sourceId: '265598', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc.', + }, + { + source: 'eod', + sourceId: 'AAPL.US', + isin: 'US0378331005', + cusip: '037833100', + country: 'US', + currency: 'USD', + name: 'Apple Inc', + }, + { + source: 'eod', + sourceId: 'FB_OLD.US', + isin: 'US30303M1027', + cusip: '30303M102', + country: 'US', + currency: 'USD', + name: 'Meta Platforms Inc', + }, + { + source: 'eod', + sourceId: 'FB_ETF.US', + isin: 'US4642872000', + cusip: '464287200', + country: 'US', + currency: 'USD', + name: 'FB Thematic ETF', + }, + { + source: 'eod', + sourceId: 'SIVB.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group', + }, + { + source: 'eod', + sourceId: 'SIVBQ.US', + isin: 'US78486Q1013', + cusip: '78486Q101', + country: 'US', + currency: 'USD', + name: 'SVB Financial Group', + }, + { + source: 'eod', + sourceId: 'SHOP.TO', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'CAD', + name: 'Shopify Inc.', + }, + { + source: 'eod', + sourceId: 'SHOP.US', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'USD', + name: 'Shopify Inc.', + }, + { + source: 'ib', + sourceId: '2001', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'CAD', + name: 'Shopify Inc.', + }, + { + source: 'ib', + sourceId: '2002', + isin: 'CA82509L1076', + cusip: '82509L107', + country: 'CA', + currency: 'USD', + name: 'Shopify Inc.', + }, + ]; + + // Spans start as null on EOD/QM to verify attachBarSpansToStageBInput wires them from barSpans. + const eodListings: StageBEodListingInput[] = [ + { + sourceId: 'AAPL.US', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + sourceId: 'FB_OLD.US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + sourceId: 'FB_ETF.US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + sourceId: 'SIVB.US', + ticker: 'SIVB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + sourceId: 'SIVBQ.US', + ticker: 'SIVBQ', + mic: 'OTCM', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + sourceId: 'SHOP.TO', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: null, + }, + { + sourceId: 'SHOP.US', + ticker: 'SHOP', + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + ]; + + const ibContracts: StageBIbContractInput[] = [ + { sourceId: '265598', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: '2001', conid: 2001, currency: 'CAD', primaryExchange: 'TSE' }, + { sourceId: '2002', conid: 2002, currency: 'USD', primaryExchange: 'NYSE' }, + ]; + + const tickerSources: StageBTickerSourceInput[] = [ + { + source: 'qm', + sourceId: 'AAPL:US', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + source: 'qm', + sourceId: 'FB_OLD:US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + source: 'qm', + sourceId: 'FB_ETF:US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + { + source: 'qm', + sourceId: 'SHOP:CA', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: null, + }, + { + source: 'ceo', + sourceId: 'ceo:SHOP', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-11-28' }, + }, + ]; + + const barSpans: BarSpan[] = [ + { source: 'eod', sourceId: 'AAPL.US', firstBarDate: '2010-01-04', lastBarDate: '2025-11-28', barCount: 4000 }, + { source: 'eod', sourceId: 'FB_OLD.US', firstBarDate: '2012-05-18', lastBarDate: '2022-06-08', barCount: 2530 }, + { source: 'eod', sourceId: 'FB_ETF.US', firstBarDate: '2025-01-02', lastBarDate: '2025-11-28', barCount: 230 }, + { source: 'eod', sourceId: 'SIVB.US', firstBarDate: '2015-01-02', lastBarDate: '2023-03-10', barCount: 2060 }, + { source: 'eod', sourceId: 'SIVBQ.US', firstBarDate: '2023-03-28', lastBarDate: '2024-11-07', barCount: 410 }, + { source: 'eod', sourceId: 'SHOP.TO', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 }, + { source: 'eod', sourceId: 'SHOP.US', firstBarDate: '2015-05-21', lastBarDate: '2025-11-28', barCount: 2650 }, + { source: 'qm', sourceId: 'AAPL:US', firstBarDate: '2015-01-02', lastBarDate: '2025-11-28', barCount: 2700 }, + { source: 'qm', sourceId: 'FB_OLD:US', firstBarDate: '2014-01-02', lastBarDate: '2022-06-08', barCount: 2100 }, + { source: 'qm', sourceId: 'FB_ETF:US', firstBarDate: '2025-02-03', lastBarDate: '2025-11-28', barCount: 205 }, + { source: 'qm', sourceId: 'SHOP:CA', firstBarDate: '2018-01-02', lastBarDate: '2025-11-28', barCount: 1980 }, + ]; + + const securityTypeByIsin = new Map([ + ['US0378331005', 'common'], + ['US30303M1027', 'common'], + ['US4642872000', 'etf'], + ['US78486Q1013', 'common'], + ['CA82509L1076', 'common'], + ]); + + const exchanges = classifySourceExchanges([ + { source: 'eod', sourceCode: 'NASDAQ', name: 'NASDAQ', country: 'US', operatingMic: 'XNAS' }, + { source: 'eod', sourceCode: 'NYSE', name: 'NYSE', country: 'US', operatingMic: 'XNYS' }, + { source: 'eod', sourceCode: 'TO', name: 'TSX', country: 'CA', operatingMic: 'XTSE' }, + { source: 'eod', sourceCode: 'OTC', name: 'OTC', country: 'US', operatingMic: 'OTCM' }, + ]); + + const dates = [ + '2025-01-02', + '2025-01-03', + '2025-01-06', + '2025-01-07', + '2025-01-08', + '2025-01-09', + ]; + const aaplPrices = [185.0, 188.5, 184.2, 191.0, 195.4, 193.1]; + const shopCadPrices = [140.0, 145.0, 138.0, 148.5, 152.0, 149.0]; + + const sampleCloses: SampleCloseRecord[] = []; + const fxRates: FxRateByDateRecord[] = []; + for (let i = 0; i < dates.length; i++) { + const date = dates[i]!; + const aapl = aaplPrices[i]!; + const shop = shopCadPrices[i]!; + fxRates.push({ date, usdCad: 1.38 + i * 0.005 }); + // AAPL: eod vs qm matching closes -> confirmed + sampleCloses.push({ source: 'eod', sourceId: 'AAPL.US', date, close: aapl }); + sampleCloses.push({ source: 'qm', sourceId: 'AAPL:US', date, close: aapl * 1.001 }); + // SHOP.TO: eod vs qm deliberately 1.5x ratio mismatch -> price_ratio_mismatch + sampleCloses.push({ source: 'eod', sourceId: 'SHOP.TO', date, close: shop }); + sampleCloses.push({ source: 'qm', sourceId: 'SHOP:CA', date, close: shop * 1.5 }); + // ceo:SHOP also mismatches eod SHOP.TO (2.0x) to exercise two mismatches sharing a left endpoint + sampleCloses.push({ source: 'ceo', sourceId: 'ceo:SHOP', date, close: shop * 2.0 }); + } + + const input: ComposeSecurityMasterRunInput = { + sources: makeSourcesResult({ + stageARecords, + eodListings, + ibContracts, + tickerSources, + securityTypeByIsin, + }), + barSpans, + exchanges, + }; + + return { input, sampleCloses, fxRates }; +} + +describe('security-master run composer purity & exports', () => { + test('contains zero I/O imports and zero wall-clock calls', () => { + const src = readFileSync(runSourcePath, 'utf8'); + expect(src).not.toMatch(/\bfrom\s+['"](node:)?(fs|net|http|https|pg|mongodb)['"]/); + expect(src).not.toMatch(/\bfrom\s+['"]@stock-bot\/(mongodb|postgres)['"]/); + expect(src).not.toMatch(/\bDate\.now\b/); + expect(src).not.toMatch(/\bnew\s+Date\b/); + expect(src).not.toMatch(/\bperformance\.now\b/); + + expect(typeof composeSecurityMasterRun).toBe('function'); + expect(typeof attachBarSpansToStageBInput).toBe('function'); + expect(typeof derivePass4CandidatePairs).toBe('function'); + expect(typeof deriveSourceCountries).toBe('function'); + }); +}); + +describe('security-master run composer adapter helpers', () => { + test('attachBarSpansToStageBInput supports BarSpan[], BarSpanIndex, ComputeBarSpansResult, merges duplicates, preserves CEO spans, and skips malformed entries', () => { + const baseStageB: SecurityMasterStageBSourceInput = { + eodListings: [ + { sourceId: 'A.US', ticker: 'A', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { + sourceId: 'B.US', + ticker: 'B', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2020-12-31' }, + }, + ], + ibContracts: [{ sourceId: '101', conid: 101, currency: 'USD', primaryExchange: 'NASDAQ' }], + tickerSources: [ + { source: 'qm', sourceId: 'A:US', ticker: 'A', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { + source: 'ceo', + sourceId: 'ceo:A', + ticker: 'A', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2021-01-04', lastBarDate: '2024-12-31' }, + }, + ], + symbolChanges: [], + }; + + const barSpansArray: BarSpan[] = [ + { source: 'eod', sourceId: 'A.US', firstBarDate: '2018-01-02', lastBarDate: '2022-12-30', barCount: 1000 }, + { source: 'eod', sourceId: 'A.US', firstBarDate: '2016-01-04', lastBarDate: '2024-12-31', barCount: 500 }, + { source: 'qm', sourceId: 'A:US', firstBarDate: '2019-01-02', lastBarDate: '2024-12-31', barCount: 1500 }, + // Malformed entry (inverted dates) + { source: 'eod', sourceId: 'BAD.US', firstBarDate: '2025-01-02', lastBarDate: '2024-01-02', barCount: 10 }, + ]; + + const fromArray = attachBarSpansToStageBInput(baseStageB, barSpansArray); + expect(fromArray.stats.recordsIn).toBe(4); + expect(fromArray.stats.resolved).toBe(3); + expect(fromArray.stats.skipped).toBe(1); + expect(fromArray.stats.attachedEodListings).toBe(1); + expect(fromArray.stats.attachedQmTickerSources).toBe(1); + // Merged min/max span for A.US + expect(fromArray.stageBInput.eodListings[0]?.span).toEqual({ + firstBarDate: '2016-01-04', + lastBarDate: '2024-12-31', + }); + // Existing span on B.US preserved when absent from barSpans + expect(fromArray.stageBInput.eodListings[1]?.span).toEqual({ + firstBarDate: '2020-01-02', + lastBarDate: '2020-12-31', + }); + // QM span attached, CEO span preserved + expect(fromArray.stageBInput.tickerSources[0]?.span).toEqual({ + firstBarDate: '2019-01-02', + lastBarDate: '2024-12-31', + }); + expect(fromArray.stageBInput.tickerSources[1]?.span).toEqual({ + firstBarDate: '2021-01-04', + lastBarDate: '2024-12-31', + }); + // Original input not mutated + expect(baseStageB.eodListings[0]?.span).toBeNull(); + + // BarSpanIndex and ComputeBarSpansResult inputs produce identical spans + const index = new BarSpanIndex(); + index.merge(barSpansArray[0]!); + index.merge(barSpansArray[1]!); + index.merge(barSpansArray[2]!); + + const fromIndex = attachBarSpansToStageBInput(baseStageB, index); + expect(fromIndex.stageBInput).toEqual(fromArray.stageBInput); + + const computeResult: ComputeBarSpansResult = { + index, + bySource: {}, + skipped: { invalidId: 0, invalidDate: 0, invalidCount: 0, total: 0 }, + totalRowsRead: 3, + totalSpans: index.size, + }; + const fromComputeResult = attachBarSpansToStageBInput(baseStageB, computeResult); + expect(fromComputeResult.stageBInput).toEqual(fromArray.stageBInput); + }); + + test('derivePass4CandidatePairs emits deduplicated ASCII-sorted cross-source pairs per listing', () => { + const key = { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }; + const mappings = [ + { source: 'qm' as const, sourceId: 'AAPL:US', listingKey: key, method: 'tier3_ticker_span' as const, validFrom: null, validTo: null }, + { source: 'eod' as const, sourceId: 'AAPL.US', listingKey: key, method: 'tier1_isin' as const, validFrom: null, validTo: null }, + { source: 'eod' as const, sourceId: 'AAPL_DUP.US', listingKey: key, method: 'tier1_isin' as const, validFrom: null, validTo: null }, + { source: 'ib' as const, sourceId: '265598', listingKey: key, method: 'tier1_isin' as const, validFrom: null, validTo: null }, + ]; + + const pairsA = derivePass4CandidatePairs(mappings); + const pairsB = derivePass4CandidatePairs([...mappings].reverse()); + expect(pairsA).toEqual(pairsB); + // Same-source pair (eod, eod) must never be emitted + for (const pair of pairsA) { + expect(pair.left.source).not.toBe(pair.right.source); + } + // 2 eod * 1 ib + 2 eod * 1 qm + 1 ib * 1 qm = 5 cross-source pairs + expect(pairsA.length).toBe(5); + }); + + test('deriveSourceCountries resolves MIC countries with Stage A fallback deterministically', () => { + const stageARecords: StageASourceRecord[] = [ + { source: 'ib', sourceId: '265598', isin: 'US0378331005', country: 'US' }, + { source: 'eod', sourceId: 'SHOP.TO', isin: 'CA82509L1076', country: 'CA' }, + ]; + const stageBInput = { + eodListings: [ + { sourceId: 'SHOP.TO', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue' as const, currency: 'CAD', span: null }, + ], + tickerSources: [ + { source: 'qm' as const, sourceId: 'SHOP:CA', ticker: 'SHOP', mic: 'XTSE', role: 'primary_venue' as const, currency: 'CAD', span: null }, + ], + }; + const countries = deriveSourceCountries(stageARecords, stageBInput, { providerMappings: [] }); + expect(countries.get('ib:265598')).toBe('US'); + expect(countries.get('eod:SHOP.TO')).toBe('CA'); + expect(countries.get('qm:SHOP:CA')).toBe('CA'); + }); +}); + +describe('composeSecurityMasterRun', () => { + test('resolves FB common vs FB ETF to two distinct instruments and listings, chains SIVB -> SIVBQ, and attaches IB + interlisted SHOP', () => { + const { input } = buildCanonicalFixture(); + const result = composeSecurityMasterRun(input, { asOfDate: '2025-11-28' }); + + // FB common (US30303M1027) vs FB ETF (US4642872000) + const fbListings = result.stageB.listings.filter(l => l.tickerRoot === 'FB'); + expect(fbListings.length).toBe(2); + const fbKeys = fbListings.map(l => formatListingNaturalKey(l)); + expect(new Set(fbKeys).size).toBe(2); + expect(new Set(fbListings.map(l => l.primaryIsin))).toEqual( + new Set(['US30303M1027', 'US4642872000']) + ); + expect(result.persistInput.stageA.instruments.filter(i => i.primaryIsin === 'US30303M1027' || i.primaryIsin === 'US4642872000').length).toBe(2); + expect(result.persistInput.securityTypeByIsin.get('US30303M1027')).toBe('common'); + expect(result.persistInput.securityTypeByIsin.get('US4642872000')).toBe('etf'); + + // QM FB_OLD:US -> US30303M1027, QM FB_ETF:US -> US4642872000 + const qmFbOld = result.stageB.providerMappings.find(m => m.source === 'qm' && m.sourceId === 'FB_OLD:US'); + const qmFbEtf = result.stageB.providerMappings.find(m => m.source === 'qm' && m.sourceId === 'FB_ETF:US'); + expect(qmFbOld?.listingKey.primaryIsin).toBe('US30303M1027'); + expect(qmFbEtf?.listingKey.primaryIsin).toBe('US4642872000'); + + // SIVB -> SIVBQ OTC continuity + expect(result.pass6.continuities.length).toBe(1); + const continuity = result.pass6.continuities[0]!; + expect(continuity.fromListingKey.tickerRoot).toBe('SIVB'); + expect(continuity.fromListingKey.mic).toBe('XNAS'); + expect(continuity.toListingKey.tickerRoot).toBe('SIVBQ'); + expect(continuity.toListingKey.mic).toBe('OTCM'); + expect(continuity.kind).toBe(CONTINUITY_KIND_OTC_DELIST_TRANSFER); + expect(result.persistInput.pass6?.continuities).toEqual(result.pass6.continuities); + expect(result.report.delistingChains?.continuitiesCreated).toBe(1); + expect(result.reportMarkdown).toContain('- Continuities Created: 1'); + + // Interlisted SHOP (CA82509L1076) -> 1 instrument, 2 listings (CAD + USD), IB attached at (instrument, currency) + const shopInstruments = result.stageA.instruments.filter(i => i.primaryIsin === 'CA82509L1076'); + expect(shopInstruments.length).toBe(1); + const shopListings = result.stageB.listings.filter(l => l.primaryIsin === 'CA82509L1076'); + expect(shopListings.length).toBe(2); + const shopCad = shopListings.find(l => l.currency === 'CAD'); + const shopUsd = shopListings.find(l => l.currency === 'USD'); + expect(shopCad?.mic).toBe('XTSE'); + expect(shopCad?.ibConid).toBe(2001); + expect(shopUsd?.mic).toBe('XNYS'); + expect(shopUsd?.ibConid).toBe(2002); + + // IB AAPL attached at (US0378331005, USD) + const aaplListing = result.stageB.listings.find(l => l.primaryIsin === 'US0378331005'); + expect(aaplListing?.ibConid).toBe(265598); + }); + + test('Pass 4 supplied confirms matching pairs and emits price_ratio_mismatch into report, CSV, SQL, and persistInput; omitted marks Pass 4 skipped', () => { + const { input, sampleCloses, fxRates } = buildCanonicalFixture(); + + // 1. Omitted sampleCloses -> Pass 4 skipped (never reported as passed) + const skippedRun = composeSecurityMasterRun(input, { asOfDate: '2025-11-28' }); + expect(skippedRun.pass4).toBeNull(); + expect(skippedRun.persistInput.pass4).toBeUndefined(); + expect(skippedRun.stats.pass4.status).toBe('skipped'); + expect(skippedRun.stats.pass4.resolved).toBe(0); + expect(skippedRun.stats.pass4.skipped).toBe(skippedRun.pass4CandidatePairs.length); + expect(skippedRun.report.priceCrossCheck).toBeNull(); + expect(skippedRun.report.conflicts.filter(c => c.pass === 'pass4').length).toBe(0); + expect(skippedRun.reportMarkdown).toContain('- Status: skipped (no sample closes supplied)'); + + // 2. Supplied sampleCloses + fxRates -> AAPL confirmed, SHOP mismatches emitted everywhere + const suppliedRun = composeSecurityMasterRun( + { ...input, sampleCloses, fxRates }, + { asOfDate: '2025-11-28' } + ); + expect(suppliedRun.pass4).not.toBeNull(); + expect(suppliedRun.persistInput.pass4).toBe(suppliedRun.pass4); + expect(suppliedRun.stats.pass4.status).toBe('executed'); + expect(suppliedRun.reportMarkdown).not.toContain('Status: skipped'); + + const aaplRow = suppliedRun.pass4!.results.find( + r => r.left.sourceId === 'AAPL.US' && r.right.sourceId === 'AAPL:US' + ); + expect(aaplRow?.verdict).toBe('confirmed'); + + const pass4Conflicts = suppliedRun.pass4!.conflicts; + expect(pass4Conflicts.length).toBeGreaterThanOrEqual(2); + expect(pass4Conflicts.every(c => c.conflictKind === 'price_ratio_mismatch')).toBe(true); + expect(suppliedRun.report.conflicts.filter(c => c.pass === 'pass4').length).toBe( + pass4Conflicts.length + ); + expect(suppliedRun.conflictsCsv).toContain('price_ratio_mismatch'); + expect(suppliedRun.overrideTemplateSql).toContain('price_ratio_mismatch'); + expect(suppliedRun.persistInput.pass4?.conflicts).toEqual(pass4Conflicts); + }); + + test('produces byte-identical Markdown, CSV, override SQL, and deep-equal persistInput under shuffled inputs', () => { + const { input, sampleCloses, fxRates } = buildCanonicalFixture(); + const baseline = composeSecurityMasterRun( + { ...input, sampleCloses, fxRates }, + { asOfDate: '2025-11-28' } + ); + + const shuffledSecTypes = new Map( + shuffleWithSeed(Array.from(input.sources.securityTypeByIsin.entries()), 77) + ); + const shuffledInput: ComposeSecurityMasterRunInput = { + sources: makeSourcesResult({ + stageARecords: shuffleWithSeed(input.sources.stageARecords, 11), + eodListings: shuffleWithSeed(input.sources.stageBInput.eodListings, 22), + ibContracts: shuffleWithSeed(input.sources.stageBInput.ibContracts, 33), + tickerSources: shuffleWithSeed(input.sources.stageBInput.tickerSources, 44), + symbolChanges: shuffleWithSeed(input.sources.stageBInput.symbolChanges, 55), + securityTypeByIsin: shuffledSecTypes, + }), + barSpans: shuffleWithSeed(input.barSpans as readonly BarSpan[], 66), + exchanges: input.exchanges, + sampleCloses: shuffleWithSeed(sampleCloses, 88), + fxRates: shuffleWithSeed(fxRates, 99), + }; + + const shuffled = composeSecurityMasterRun(shuffledInput, { asOfDate: '2025-11-28' }); + + expect(shuffled.reportMarkdown).toBe(baseline.reportMarkdown); + expect(shuffled.conflictsCsv).toBe(baseline.conflictsCsv); + expect(shuffled.overrideTemplateSql).toBe(baseline.overrideTemplateSql); + expect(shuffled.persistInput).toEqual(baseline.persistInput); + expect(Array.from(shuffled.persistInput.securityTypeByIsin.entries())).toEqual( + Array.from(baseline.persistInput.securityTypeByIsin.entries()) + ); + expect(shuffled.stats).toEqual(baseline.stats); + }); + + test('reconciles per-step stats and conflict totals while counting malformed/sparse records without throwing', () => { + const { input, sampleCloses, fxRates } = buildCanonicalFixture(); + + // Add a Stage A conflict (isin_cusip_mismatch) so conflicts come from multiple passes + const stageARecords: StageASourceRecord[] = [ + ...input.sources.stageARecords, + { + source: 'eod', + sourceId: 'CONFLICT_A.US', + isin: 'US0378331005', + cusip: '594918104', + country: 'US', + currency: 'USD', + name: 'Conflict Co', + }, + // Malformed Stage A records + null as unknown as StageASourceRecord, + { source: 'bogus' as 'eod', sourceId: 'X.US' }, + { source: 'eod', sourceId: '' }, + ]; + // Sparse slot + stageARecords.length += 1; + + const eodListings: StageBEodListingInput[] = [ + ...input.sources.stageBInput.eodListings, + null as unknown as StageBEodListingInput, + { sourceId: 'BAD_ROLE.US', ticker: 'BR', mic: 'XNAS', role: 'invalid_role' as 'primary_venue', currency: 'USD', span: null }, + ]; + const ibContracts: StageBIbContractInput[] = [ + ...input.sources.stageBInput.ibContracts, + { sourceId: '', conid: 999, currency: 'USD', primaryExchange: 'NASDAQ' }, + ]; + const tickerSources: StageBTickerSourceInput[] = [ + ...input.sources.stageBInput.tickerSources, + { source: 'unknown' as 'qm', sourceId: 'U:US', ticker: 'U', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + ]; + const symbolChanges: StageBSymbolChangeInput[] = [ + { eodSourceId: '', oldTicker: 'OLD', effectiveDate: '2022-01-01' }, + { eodSourceId: 'AAPL.US', oldTicker: 'AAPL_OLD', effectiveDate: 'not-a-date' }, + { eodSourceId: 'AAPL.US', oldTicker: 'AAPL_OLD', effectiveDate: '2022-01-01', validFrom: '2023-01-01' }, + ]; + const barSpans: BarSpan[] = [ + ...(input.barSpans as readonly BarSpan[]), + null as unknown as BarSpan, + { source: 'eod', sourceId: 'NEG.US', firstBarDate: '2020-01-02', lastBarDate: '2020-12-31', barCount: -5 }, + ]; + const badCloses: SampleCloseRecord[] = [ + ...sampleCloses, + { source: 'eod', sourceId: 'AAPL.US', date: 'bad-date', close: 100 }, + { source: 'eod', sourceId: 'AAPL.US', date: '2025-01-02', close: -1 }, + ]; + const badFx: FxRateByDateRecord[] = [ + ...fxRates, + { date: '2025-01-02', usdCad: 0 }, + ]; + + const result = composeSecurityMasterRun( + { + sources: makeSourcesResult({ + stageARecords, + eodListings, + ibContracts, + tickerSources, + symbolChanges, + securityTypeByIsin: input.sources.securityTypeByIsin, + }), + barSpans, + exchanges: input.exchanges, + sampleCloses: badCloses, + fxRates: badFx, + }, + { asOfDate: '2025-11-28' } + ); + + // Every step reconciles: recordsIn === resolved + unresolved + skipped + const { stats } = result; + expect(stats.barSpans.recordsIn).toBe( + stats.barSpans.resolved + stats.barSpans.unresolved + stats.barSpans.skipped + ); + expect(stats.stageA.recordsIn).toBe( + stats.stageA.resolved + stats.stageA.unresolved + stats.stageA.skipped + ); + expect(stats.stageB.recordsIn).toBe( + stats.stageB.resolved + stats.stageB.unresolved + stats.stageB.skipped + ); + expect(stats.pass6.recordsIn).toBe( + stats.pass6.resolved + stats.pass6.unresolved + stats.pass6.skipped + ); + expect(stats.pass4.recordsIn).toBe( + stats.pass4.resolved + stats.pass4.unresolved + stats.pass4.skipped + ); + + // Malformed counts surfaced accurately + expect(stats.malformedInputs.stageARecords).toBe(4); // null + bogus source + empty sourceId + sparse slot + expect(stats.malformedInputs.eodListings).toBe(2); + expect(stats.malformedInputs.ibContracts).toBe(1); + expect(stats.malformedInputs.tickerSources).toBe(1); + expect(stats.malformedInputs.symbolChanges).toBe(3); + expect(stats.malformedInputs.barSpans).toBe(2); + expect(stats.malformedInputs.sampleCloses).toBe(2); + expect(stats.malformedInputs.fxRates).toBe(1); + expect(stats.malformedInputs.total).toBe(16); + + // Conflict totals reconcile with report.conflicts.length + expect(stats.conflicts.stageA).toBe(1); + expect(stats.conflicts.pass4).toBeGreaterThanOrEqual(2); + expect(stats.conflicts.total).toBe( + stats.conflicts.stageA + + stats.conflicts.stageB + + stats.conflicts.pass4 + + stats.conflicts.pass6 + ); + expect(result.report.conflicts.length).toBe(stats.conflicts.total); + }); + + test('composes a fixed-seed 100,000-record synthetic workload end to end above the sandbox throughput floor', () => { + // 50,000 EOD + 25,000 IB + 25,000 QM = 100,000 source records + const numInstruments = 50_000; + const numIb = 25_000; + const numQm = 25_000; + const totalSourceRecords = numInstruments + numIb + numQm; + + const stageARecords: StageASourceRecord[] = new Array(numInstruments + numIb); + const eodListings: StageBEodListingInput[] = new Array(numInstruments); + const ibContracts: StageBIbContractInput[] = new Array(numIb); + const tickerSources: StageBTickerSourceInput[] = new Array(numQm); + const barSpans: BarSpan[] = new Array(numInstruments + numQm); + const securityTypeByIsin = new Map(); + + const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; + let stageAIdx = 0; + let spanIdx = 0; + + for (let i = 0; i < numInstruments; i++) { + // Deterministic valid US ISIN via cusipToIsin (9-char CUSIP: 6-digit issuer + 2-char issue + check) + // Construct a valid 9-char CUSIP using cusipToIsin after computing CUSIP check digit, or direct ISIN: + const base8 = `A${String(i).padStart(7, '0')}`; + // Compute CUSIP check digit (Luhn mod 10 over A=10..Z=35) + let sum = 0; + for (let pos = 0; pos < 8; pos++) { + const ch = base8.charCodeAt(pos); + let v = ch >= 65 ? ch - 55 : ch - 48; + if (pos % 2 === 1) { + v *= 2; + } + sum += Math.floor(v / 10) + (v % 10); + } + const checkDigit = (10 - (sum % 10)) % 10; + const cusip = `${base8}${checkDigit}`; + const isin = cusipToIsin(cusip, 'US')!; + + // Unique 4-letter ticker from i + const c0 = alphabet[Math.floor(i / (26 * 26 * 26)) % 26]!; + const c1 = alphabet[Math.floor(i / (26 * 26)) % 26]!; + const c2 = alphabet[Math.floor(i / 26) % 26]!; + const c3 = alphabet[i % 26]!; + const ticker = `${c0}${c1}${c2}${c3}`; + const eodId = `${ticker}.US`; + + stageARecords[stageAIdx++] = { + source: 'eod', + sourceId: eodId, + isin, + cusip, + country: 'US', + currency: 'USD', + name: `Bench Corp ${i}`, + }; + eodListings[i] = { + sourceId: eodId, + ticker, + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }; + barSpans[spanIdx++] = { + source: 'eod', + sourceId: eodId, + firstBarDate: '2018-01-02', + lastBarDate: '2025-11-28', + barCount: 1980, + }; + securityTypeByIsin.set(isin, 'common'); + + if (i < numIb) { + const ibId = String(1_000_000 + i); + stageARecords[stageAIdx++] = { + source: 'ib', + sourceId: ibId, + isin, + cusip, + country: 'US', + currency: 'USD', + name: `Bench Corp ${i}`, + }; + ibContracts[i] = { + sourceId: ibId, + conid: 1_000_000 + i, + currency: 'USD', + primaryExchange: 'NASDAQ', + }; + } + + if (i < numQm) { + const qmId = `${ticker}:US`; + tickerSources[i] = { + source: 'qm', + sourceId: qmId, + ticker, + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }; + barSpans[spanIdx++] = { + source: 'qm', + sourceId: qmId, + firstBarDate: '2020-01-02', + lastBarDate: '2025-11-28', + barCount: 1480, + }; + } + } + + const sources = makeSourcesResult({ + stageARecords, + eodListings, + ibContracts, + tickerSources, + securityTypeByIsin, + }); + + const startMs = performance.now(); + const result = composeSecurityMasterRun( + { sources, barSpans }, + { asOfDate: '2025-11-28' } + ); + const elapsedMs = performance.now() - startMs; + const recordsPerSec = totalSourceRecords / (elapsedMs / 1000); + + expect(totalSourceRecords).toBe(100_000); + expect(result.stageA.instruments.length).toBe(numInstruments); + expect(result.stageB.listings.length).toBe(numInstruments); + expect(result.stageB.providerMappings.length).toBe(totalSourceRecords); + expect(result.stats.stageA.recordsIn).toBe( + result.stats.stageA.resolved + result.stats.stageA.unresolved + result.stats.stageA.skipped + ); + expect(result.stats.stageB.recordsIn).toBe( + result.stats.stageB.resolved + result.stats.stageB.unresolved + result.stats.stageB.skipped + ); + expect(result.stats.pass4.status).toBe('skipped'); + // Assert conservative sandbox throughput floor (>= 10,000 records/s) + expect(recordsPerSec).toBeGreaterThanOrEqual(10_000); + }); +});