diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 5d369504..64d1dd2e 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -103,6 +103,7 @@ export { type StageBSource, type StageBSourceStats, type StageBStats, + type StageBSymbolChangeInput, type StageBTickerSource, type StageBTickerSourceInput, type StageBUnresolvedReason, diff --git a/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts b/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts index 49e26f57..a2c1e77b 100644 --- a/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts +++ b/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts @@ -56,6 +56,13 @@ export interface StageBTickerSourceInput { span: SpanDateRange | null; } +export interface StageBSymbolChangeInput { + readonly eodSourceId: string; + readonly oldTicker: string; + readonly effectiveDate: string; + readonly validFrom?: string | null; +} + export interface StageBInput { readonly instruments: readonly StageAInstrumentCandidate[]; readonly eodListings: @@ -65,6 +72,7 @@ export interface StageBInput { | readonly StageBIbContractInput[] | ReadonlyMap>; readonly tickerSources: readonly StageBTickerSourceInput[]; + readonly symbolChanges?: readonly StageBSymbolChangeInput[]; } export interface MatchListingsStageBOptions { @@ -81,7 +89,7 @@ export interface StageBListingCandidate extends ListingNaturalKey { export interface StageBProviderMappingCandidate { source: StageBSource; sourceId: string; - listingKey: ListingNaturalKey; + listingKey: Readonly; method: StageBMatchMethod; validFrom: string | null; validTo: string | null; @@ -125,7 +133,7 @@ export interface StageBConflictDetail { currency: string | null; ibConid: number | null; competingConids: number[]; - candidateListingKeys: ListingNaturalKey[]; + candidateListingKeys: Readonly[]; } export interface StageBConflictRecord { @@ -162,13 +170,26 @@ type EodMetadata = Omit; type IbMetadata = Omit; interface ListingAccumulator { - readonly key: ListingNaturalKey; + readonly key: Readonly; listedFrom: string | null; listedTo: string | null; ibConid: number | null; ibPrimaryExchange: string | null; } +interface TickerLookupCandidate { + readonly acc: ListingAccumulator; + readonly aliasSpan: SpanDateRange | null; +} + +interface ValidatedSymbolChange { + readonly eodSourceId: string; + readonly oldTickerRoot: string; + readonly oldClassSuffix: string; + readonly dayBeforeEffective: string; + readonly validFrom: string | null; +} + interface StagedIbCandidate { sourceId: string; primaryIsin: string; @@ -328,7 +349,63 @@ function validateSpan( return { status: 'valid', span: { firstBarDate, lastBarDate } }; } -function makeListingNaturalKeyId(key: ListingNaturalKey): string { +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function daysInMonth(year: number, month: number): number { + switch (month) { + case 1: + case 3: + case 5: + case 7: + case 8: + case 10: + case 12: + return 31; + case 4: + case 6: + case 9: + case 11: + return 30; + case 2: + return isLeapYear(year) ? 29 : 28; + default: + return 0; + } +} + +/** + * Pure integer UTC calendar predecessor for exact `YYYY-MM-DD` strings. + * Returns `null` for malformed dates or dates `<= '0001-01-01'`. + */ +function previousCalendarDate(ymd: string): string | null { + if (!EXACT_YMD_PATTERN.test(ymd) || normalizeBarDate(ymd) !== ymd) { + return null; + } + let year = Number(ymd.slice(0, 4)); + let month = Number(ymd.slice(5, 7)); + let day = Number(ymd.slice(8, 10)); + if (year < 1 || (year === 1 && month === 1 && day === 1)) { + return null; + } + if (day > 1) { + day -= 1; + } else if (month > 1) { + month -= 1; + day = daysInMonth(year, month); + } else { + year -= 1; + month = 12; + day = 31; + } + const y = String(year).padStart(4, '0'); + const m = month < 10 ? `0${month}` : String(month); + const d = day < 10 ? `0${day}` : String(day); + return `${y}-${m}-${d}`; +} + +function makeListingNaturalKeyId(key: Readonly): string { return `${key.primaryIsin}\u0000${key.mic}\u0000${key.tickerRoot}\u0000${key.classSuffix}\u0000${key.currency}`; } @@ -341,7 +418,10 @@ function makeTickerLookupKey( return `${mic}\u0000${currency}\u0000${tickerRoot}\u0000${classSuffix}`; } -function compareListingNaturalKey(a: ListingNaturalKey, b: ListingNaturalKey): number { +function compareListingNaturalKey( + a: Readonly, + b: Readonly +): number { return ( compareAscii(a.primaryIsin, b.primaryIsin) || compareAscii(a.mic, b.mic) || @@ -377,8 +457,8 @@ function compareNumberArrays(a: readonly number[], b: readonly number[]): number } function compareListingKeyArrays( - a: readonly ListingNaturalKey[], - b: readonly ListingNaturalKey[] + a: readonly Readonly[], + b: readonly Readonly[] ): number { const len = a.length < b.length ? a.length : b.length; for (let i = 0; i < len; i++) { @@ -661,6 +741,69 @@ export function matchListingsStageB( counts.set(entry.sourceId, (counts.get(entry.sourceId) ?? 0) + 1); } + // Validate optional symbolChanges (historical EOD ticker aliases). + const validatedSymbolChanges: ValidatedSymbolChange[] = []; + if (input.symbolChanges !== undefined) { + assertIsArray(input.symbolChanges, 'input.symbolChanges'); + for (let i = 0; i < input.symbolChanges.length; i++) { + if (!(i in input.symbolChanges)) { + throw new TypeError(`Invalid sparse slot at symbolChanges[${i}]: expected an object`); + } + const entry = input.symbolChanges[i]; + if (entry === undefined || entry === null || typeof entry !== 'object') { + throw new TypeError(`Invalid symbolChanges entry at index ${i}: expected an object`); + } + if (typeof entry.eodSourceId !== 'string' || entry.eodSourceId.length === 0) { + throw new Error(`Invalid empty or non-string eodSourceId at symbolChanges[${i}]`); + } + if (typeof entry.oldTicker !== 'string') { + throw new TypeError(`Invalid non-string oldTicker at symbolChanges[${i}]`); + } + const parsedOldTicker = classifyTicker(entry.oldTicker, 'eod'); + if (!parsedOldTicker.ok) { + throw new Error( + `Invalid oldTicker "${entry.oldTicker}" (${parsedOldTicker.reason}) at symbolChanges[${i}]` + ); + } + if (typeof entry.effectiveDate !== 'string') { + throw new TypeError(`Invalid non-string effectiveDate at symbolChanges[${i}]`); + } + const dayBeforeEffective = previousCalendarDate(entry.effectiveDate); + if (dayBeforeEffective === null) { + throw new RangeError( + `Invalid effectiveDate "${entry.effectiveDate}" at symbolChanges[${i}]: expected exact valid YYYY-MM-DD > 0001-01-01` + ); + } + let validFrom: string | null = null; + if (entry.validFrom !== undefined && entry.validFrom !== null) { + if (typeof entry.validFrom !== 'string') { + throw new TypeError(`Invalid non-string validFrom at symbolChanges[${i}]`); + } + if ( + !EXACT_YMD_PATTERN.test(entry.validFrom) || + normalizeBarDate(entry.validFrom) !== entry.validFrom + ) { + throw new RangeError( + `Invalid validFrom "${entry.validFrom}" at symbolChanges[${i}]: expected exact valid YYYY-MM-DD` + ); + } + if (entry.validFrom >= entry.effectiveDate) { + throw new RangeError( + `Invalid validFrom "${entry.validFrom}" at symbolChanges[${i}]: must be strictly before effectiveDate "${entry.effectiveDate}"` + ); + } + validFrom = entry.validFrom; + } + validatedSymbolChanges.push({ + eodSourceId: entry.eodSourceId, + oldTickerRoot: parsedOldTicker.tickerRoot, + oldClassSuffix: parsedOldTicker.classSuffix, + dayBeforeEffective, + validFrom, + }); + } + } + const statsBySource: Record = { eod: createEmptySourceStats(), ib: createEmptySourceStats(), @@ -671,7 +814,8 @@ export function matchListingsStageB( const listingsByNaturalKey = new Map(); const listingsByInstrumentCurrency = new Map>(); - const listingsByTickerKey = new Map(); + const listingsByTickerKey = new Map(); + const listingByEodSourceId = new Map(); const providerMappings: StageBProviderMappingCandidate[] = []; const unresolved: StageBUnresolvedRecord[] = []; @@ -769,13 +913,13 @@ export function matchListingsStageB( } const validSpan = spanCheck.status === 'valid' ? spanCheck.span : null; - const key: ListingNaturalKey = { + const key: Readonly = Object.freeze({ primaryIsin: inst.primaryIsin, mic: venue.mic, tickerRoot: ticker.tickerRoot, classSuffix: ticker.classSuffix, currency, - }; + }); const keyId = makeListingNaturalKeyId(key); let acc = listingsByNaturalKey.get(keyId); if (acc === undefined) { @@ -811,7 +955,7 @@ export function matchListingsStageB( tickerList = []; listingsByTickerKey.set(tickerKey, tickerList); } - tickerList.push(acc); + tickerList.push({ acc, aliasSpan: null }); } else if (validSpan !== null) { // Associative & commutative min/max widening ensures shuffle invariance. if (acc.listedFrom === null || validSpan.firstBarDate < acc.listedFrom) { @@ -822,6 +966,8 @@ export function matchListingsStageB( } } + listingByEodSourceId.set(member.sourceId, acc); + providerMappings.push({ source: 'eod', sourceId: member.sourceId, @@ -834,6 +980,49 @@ export function matchListingsStageB( } } + // Register historical EOD symbol-change aliases after Step 1 so listedFrom/listedTo widening is finalized. + for (let i = 0; i < validatedSymbolChanges.length; i++) { + const change = validatedSymbolChanges[i]; + if (change === undefined) { + continue; + } + const acc = listingByEodSourceId.get(change.eodSourceId); + if (acc === undefined) { + continue; + } + const aliasTickerKey = makeTickerLookupKey( + acc.key.mic, + acc.key.currency, + change.oldTickerRoot, + change.oldClassSuffix + ); + let candidate: TickerLookupCandidate | null = null; + if (acc.listedFrom === null || acc.listedTo === null) { + candidate = { acc, aliasSpan: null }; + } else { + const aliasFrom = + change.validFrom !== null && change.validFrom > acc.listedFrom + ? change.validFrom + : acc.listedFrom; + const aliasTo = + change.dayBeforeEffective < acc.listedTo ? change.dayBeforeEffective : acc.listedTo; + if (aliasFrom <= aliasTo) { + candidate = { + acc, + aliasSpan: { firstBarDate: aliasFrom, lastBarDate: aliasTo }, + }; + } + } + if (candidate !== null) { + let tickerList = listingsByTickerKey.get(aliasTickerKey); + if (tickerList === undefined) { + tickerList = []; + listingsByTickerKey.set(aliasTickerKey, tickerList); + } + tickerList.push(candidate); + } + } + for (const [sourceId, count] of eodMetadataCounts.entries()) { if (count > 1 && (memberCountsBySource.eod.get(sourceId) ?? 0) === 0) { conflicts.push({ @@ -1119,29 +1308,34 @@ export function matchListingsStageB( continue; } - const overlapping: ListingAccumulator[] = []; - let missingSpanCount = 0; + const overlappingSet = new Set(); + const missingSpanSet = new Set(); for (let k = 0; k < candidates.length; k++) { const cand = candidates[k]; if (cand === undefined) { continue; } - if (cand.listedFrom === null || cand.listedTo === null) { - missingSpanCount += 1; - } else if ( - spansOverlap( - spanCheck.span, - { firstBarDate: cand.listedFrom, lastBarDate: cand.listedTo }, - overlapOptions - ) - ) { - overlapping.push(cand); + let candSpan: SpanDateRange | null; + if (cand.aliasSpan !== null) { + candSpan = cand.aliasSpan; + } else if (cand.acc.listedFrom !== null && cand.acc.listedTo !== null) { + candSpan = { firstBarDate: cand.acc.listedFrom, lastBarDate: cand.acc.listedTo }; + } else { + candSpan = null; + } + + if (candSpan === null) { + missingSpanSet.add(cand.acc); + } else if (spansOverlap(spanCheck.span, candSpan, overlapOptions)) { + overlappingSet.add(cand.acc); } } - if (overlapping.length > 1) { - const candidateListingKeys = overlapping.map(c => c.key).sort(compareListingNaturalKey); + if (overlappingSet.size > 1) { + const candidateListingKeys = Array.from(overlappingSet, c => c.key).sort( + compareListingNaturalKey + ); conflicts.push({ source, sourceId: record.sourceId, @@ -1155,7 +1349,7 @@ export function matchListingsStageB( }, }); sourceStats.conflict += 1; - } else if (missingSpanCount > 0) { + } else if (missingSpanSet.size > 0) { // Never match when a same-key listing has an unknown span (could hide a reused-ticker collision). unresolved.push({ source, @@ -1164,8 +1358,8 @@ export function matchListingsStageB( primaryIsin: null, }); sourceStats.unresolved += 1; - } else if (overlapping.length === 1) { - const matchedListing = overlapping[0]; + } else if (overlappingSet.size === 1) { + const matchedListing = overlappingSet.values().next().value; if (matchedListing !== undefined) { providerMappings.push({ source, diff --git a/design/PLATFORM-PLAN.md b/design/PLATFORM-PLAN.md index 4ab93132..2935064e 100644 --- a/design/PLATFORM-PLAN.md +++ b/design/PLATFORM-PLAN.md @@ -270,7 +270,7 @@ Extends the existing 8-decimal Rust kernel (retiring legacy `f64` `BacktestEngin ### Validation suite, Trial Ledger & 6-Month Vault -- **Trial ledger (`trial_ledger` in PostgreSQL):** Groups trials deterministically by `(universe_market, horizon_bucket)` (`{US, CA, US_CA, FX} × {intraday, swing_1_10d, position_10d_plus}`) and stores each variant's out-of-warmup daily return/IC vector (`FLOAT4[]`) to compute Bailey & López de Prado **effective independent trials $\hat{N}$**, non-normal **Deflated Sharpe Ratio (DSR $\ge 0.95$)**, and **PBO ($\le 0.20$)** via CSCV ($S = 16$). +- **Trial ledger (`trial_ledger` in PostgreSQL):** Groups trials deterministically by `(universe_market, horizon_bucket)` (`{US_EQ, CA_EQ, US_CA_EQ, FX} × {intraday, swing_1_10d, position_10d_plus}`) and stores each variant's out-of-warmup daily return/IC vector (`FLOAT4[]`) to compute Bailey & López de Prado **effective independent trials $\hat{N}$**, non-normal **Deflated Sharpe Ratio (DSR $\ge 0.95$)**, and **PBO ($\le 0.20$)** via CSCV ($S = 16$). - **Purged Walk-Forward & CPCV:** Replaces `labelHorizonMs = 0` with mandatory `purge = horizon + warmup` and `embargo = max(5d, 0.01 * T)`. - **Post-2023 Recency Gate:** Post-2023 IC and Sharpe must be positive and $\ge 50\%$ of pre-2023 levels so decayed pre-LLM anomalies fail automatically. - **Rolling 6-Month Air-Gapped Vault (`D10`):** Most recent 6 months (~126 trading days) fenced off from all research/MCP/marimo reads; evaluated **once** when **you** promote a `Validated` strategy toward `Paper` ($\le 10$ vault evaluations/year recorded in immutable `vault_evaluations`). diff --git a/design/VALIDATION-AND-RIGOR.md b/design/VALIDATION-AND-RIGOR.md index fab6d36c..251e6e20 100644 --- a/design/VALIDATION-AND-RIGOR.md +++ b/design/VALIDATION-AND-RIGOR.md @@ -88,7 +88,7 @@ Computed on any synchronous screen/experiment return matrix $M \in \mathbb{R}^{T ### Vault Evaluations Schema (Append-Only) -Protected against `UPDATE`/`DELETE`/`TRUNCATE` by `reject_research_evidence_mutation()`. A `BEFORE INSERT` trigger requires `READ COMMITTED` transaction isolation (rejecting `REPEATABLE READ` and `SERIALIZABLE` so a waiting writer cannot evaluate the cap against a stale snapshot), forces `evaluated_at := now()` under a schema-scoped transaction advisory lock, and rejects inserts once 10 evaluations exist in the rolling 1-year window (`evaluated_at > now() - interval '1 year'`) on the target table (`TG_RELID`), paired with a statement-level `AFTER INSERT` check so multi-row inserts cannot bypass the cap: +Protected against `UPDATE`/`DELETE`/`TRUNCATE` by `reject_research_evidence_mutation()`. A `BEFORE INSERT` trigger requires `READ COMMITTED` or `READ UNCOMMITTED` transaction isolation (PostgreSQL treats `READ UNCOMMITTED` identically to `READ COMMITTED`, while rejecting `REPEATABLE READ` and `SERIALIZABLE` so a waiting writer cannot evaluate the cap against a stale snapshot), forces `evaluated_at := now()` under a schema-scoped transaction advisory lock, and rejects inserts once 10 evaluations exist in the rolling 1-year window (`evaluated_at > now() - interval '1 year'`) on the target table (`TG_RELID`), paired with a statement-level `AFTER INSERT` check so multi-row inserts cannot bypass the cap: ```sql CREATE TABLE IF NOT EXISTS vault_evaluations ( diff --git a/test/unit/security-master-listing-stage-b.test.ts b/test/unit/security-master-listing-stage-b.test.ts index 1e8b1709..269d6414 100644 --- a/test/unit/security-master-listing-stage-b.test.ts +++ b/test/unit/security-master-listing-stage-b.test.ts @@ -11,6 +11,7 @@ import { type StageBIbContractInput, type StageBInput, type StageBMatchResult, + type StageBSymbolChangeInput, type StageBTickerSourceInput, } from '../../apps/stock/data-pipeline/src/security-master'; import { MAX_CLASS_SUFFIX_LENGTH } from '../../apps/stock/data-pipeline/src/normalization/ticker'; @@ -1359,6 +1360,580 @@ describe('security master Pass 3 Stage B listing matcher', () => { } }); + test('freezes listingKey objects across providerMappings and conflicts so strict-mode mutation throws without side effects (T-58)', () => { + const result = matchListingsStageB({ + instruments: [ + { + primaryIsin: 'US30303M1027', + primaryCusip: '30303M102', + issuerCountry: 'US', + canonicalName: 'Meta Platforms Inc.', + members: [ + { source: 'eod', sourceId: 'META.US', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-meta-1', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-meta-2', currency: 'USD', method: 'tier1_isin' }, + ], + }, + { + primaryIsin: 'US0000000026', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'FB Reused Listing', + members: [{ source: 'eod', sourceId: 'FB_NEW.US', currency: 'USD', method: 'tier1_isin' }], + }, + ], + eodListings: [ + { + sourceId: 'META.US', + ticker: 'META', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2012-05-18', lastBarDate: '2025-11-26' }, + }, + { + sourceId: 'FB_NEW.US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2025-01-02', lastBarDate: '2025-11-26' }, + }, + ], + ibContracts: [ + { sourceId: 'ib-meta-1', conid: 107113386, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'ib-meta-2', conid: 999113386, currency: 'USD', primaryExchange: 'NASDAQ' }, + ], + tickerSources: [ + { + source: 'qm', + sourceId: 'QM_META_2024', + ticker: 'META', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2024-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'qm', + sourceId: 'QM_FB_BOTH', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-06-01' }, + }, + ], + symbolChanges: [{ eodSourceId: 'META.US', oldTicker: 'FB', effectiveDate: '2022-06-09' }], + }); + + expect(result.providerMappings.length).toBeGreaterThan(0); + expect(result.conflicts.length).toBeGreaterThan(0); + + for (const mapping of result.providerMappings) { + expect(Object.isFrozen(mapping.listingKey)).toBe(true); + } + for (const conflict of result.conflicts) { + for (const candidateKey of conflict.detail.candidateListingKeys) { + expect(Object.isFrozen(candidateKey)).toBe(true); + } + } + + const snapshotBefore = JSON.stringify(result); + + const firstMappingKey = result.providerMappings[0]?.listingKey as unknown as Record< + string, + unknown + >; + expect(() => { + firstMappingKey.tickerRoot = 'MUTATED'; + }).toThrow(TypeError); + expect(() => { + firstMappingKey.dbId = 42; + }).toThrow(TypeError); + + const firstConflictKey = result.conflicts[0]?.detail.candidateListingKeys[0] as unknown as + | Record + | undefined; + expect(firstConflictKey).toBeDefined(); + expect(() => { + if (firstConflictKey !== undefined) { + firstConflictKey.mic = 'XXXX'; + } + }).toThrow(TypeError); + + expect(JSON.stringify(result)).toBe(snapshotBefore); + assertReconciliationAndContracts(result); + }); + + test('resolves historical QM FB rows to META.US via dated EOD symbolChanges without mis-linking 2025 FB.US (T-59)', () => { + const instruments: StageAInstrumentCandidate[] = [ + { + primaryIsin: 'US30303M1027', + primaryCusip: '30303M102', + issuerCountry: 'US', + canonicalName: 'Meta Platforms Inc.', + members: [{ source: 'eod', sourceId: 'META.US', currency: 'USD', method: 'tier1_isin' }], + }, + { + primaryIsin: 'US0000000026', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'FB Reused Ticker 2025', + members: [{ source: 'eod', sourceId: 'FB.US', currency: 'USD', method: 'tier1_isin' }], + }, + ]; + + const eodListings: StageBEodListingInput[] = [ + { + sourceId: 'META.US', + ticker: 'META', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2012-05-18', lastBarDate: '2025-11-26' }, + }, + { + sourceId: 'FB.US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2025-01-02', lastBarDate: '2025-11-26' }, + }, + ]; + + const tickerSources: StageBTickerSourceInput[] = [ + { + source: 'qm', + sourceId: 'QM_FB_2015', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2015-01-02', lastBarDate: '2015-12-31' }, + }, + { + source: 'qm', + sourceId: 'QM_FB_2022_06_08', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2022-06-08', lastBarDate: '2022-06-08' }, + }, + { + source: 'qm', + sourceId: 'QM_FB_2022_06_09', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2022-06-09', lastBarDate: '2022-06-09' }, + }, + { + source: 'qm', + sourceId: 'QM_FB_2023', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2023-01-03', lastBarDate: '2023-12-29' }, + }, + { + source: 'qm', + sourceId: 'QM_FB_2025', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2025-02-03', lastBarDate: '2025-10-31' }, + }, + { + source: 'qm', + sourceId: 'QM_META_2024', + ticker: 'META', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2024-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'qm', + sourceId: 'QM_FB_CROSS_SPAN', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-06-01' }, + }, + ]; + + const symbolChanges: StageBSymbolChangeInput[] = [ + { eodSourceId: 'META.US', oldTicker: 'FB', effectiveDate: '2022-06-09' }, + ]; + + const withHistory = matchListingsStageB({ + instruments, + eodListings, + ibContracts: [], + tickerSources, + symbolChanges, + }); + + const qmMappings = withHistory.providerMappings.filter(m => m.source === 'qm'); + expect(qmMappings).toEqual([ + { + source: 'qm', + sourceId: 'QM_FB_2015', + listingKey: { + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'META', + classSuffix: '', + currency: 'USD', + }, + method: 'tier3_ticker_span', + validFrom: '2015-01-02', + validTo: '2015-12-31', + }, + { + source: 'qm', + sourceId: 'QM_FB_2022_06_08', + listingKey: { + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'META', + classSuffix: '', + currency: 'USD', + }, + method: 'tier3_ticker_span', + validFrom: '2022-06-08', + validTo: '2022-06-08', + }, + { + source: 'qm', + sourceId: 'QM_FB_2025', + listingKey: { + primaryIsin: 'US0000000026', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }, + method: 'tier3_ticker_span', + validFrom: '2025-02-03', + validTo: '2025-10-31', + }, + { + source: 'qm', + sourceId: 'QM_META_2024', + listingKey: { + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'META', + classSuffix: '', + currency: 'USD', + }, + method: 'tier3_ticker_span', + validFrom: '2024-01-02', + validTo: '2024-12-31', + }, + ]); + + expect(withHistory.unresolved).toEqual([ + { source: 'qm', sourceId: 'QM_FB_2022_06_09', reason: 'no_span_overlap', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_FB_2023', reason: 'no_span_overlap', primaryIsin: null }, + ]); + + expect(withHistory.conflicts).toEqual([ + { + source: 'qm', + sourceId: 'QM_FB_CROSS_SPAN', + conflictKind: 'ambiguous_ticker_span', + detail: { + primaryIsin: null, + currency: 'USD', + ibConid: null, + competingConids: [], + candidateListingKeys: [ + { + primaryIsin: 'US0000000026', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }, + { + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'META', + classSuffix: '', + currency: 'USD', + }, + ], + }, + }, + ]); + assertReconciliationAndContracts(withHistory); + + // Omitted or empty symbolChanges leaves historical QM FB rows unresolved as no_span_overlap. + for (const noHistoryInput of [ + { instruments, eodListings, ibContracts: [], tickerSources }, + { instruments, eodListings, ibContracts: [], tickerSources, symbolChanges: [] }, + ]) { + const noHistory = matchListingsStageB(noHistoryInput); + expect(noHistory.conflicts).toEqual([]); + expect( + noHistory.unresolved.find(u => u.sourceId === 'QM_FB_2015')?.reason + ).toBe('no_span_overlap'); + expect( + noHistory.unresolved.find(u => u.sourceId === 'QM_FB_2022_06_08')?.reason + ).toBe('no_span_overlap'); + expect( + noHistory.providerMappings.find(m => m.sourceId === 'QM_FB_2025')?.listingKey.primaryIsin + ).toBe('US0000000026'); + expect( + noHistory.providerMappings.find(m => m.sourceId === 'QM_META_2024')?.listingKey.primaryIsin + ).toBe('US30303M1027'); + assertReconciliationAndContracts(noHistory); + } + }); + + test('handles symbolChanges edge cases: chained renames, duplicate/self aliases, unknown eodSourceId, undated listing, shuffle invariance, and malformed inputs (T-59)', () => { + const instruments: StageAInstrumentCandidate[] = [ + { + primaryIsin: 'US5555555555', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'Chained Rename Corp', + members: [{ source: 'eod', sourceId: 'CUR.US', currency: 'USD', method: 'tier1_isin' }], + }, + { + primaryIsin: 'US6666666666', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'Undated Aliased Corp', + members: [{ source: 'eod', sourceId: 'UNDATED.US', currency: 'USD', method: 'tier1_isin' }], + }, + ]; + + const eodListings: StageBEodListingInput[] = [ + { + sourceId: 'CUR.US', + ticker: 'CUR', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2010-01-04', lastBarDate: '2025-11-26' }, + }, + { + sourceId: 'UNDATED.US', + ticker: 'UND', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }, + ]; + + const symbolChanges: StageBSymbolChangeInput[] = [ + // Chained renames: OLD1 (< 2015-01-01) -> OLD2 (2015-01-01..2020-02-29, leap day) -> CUR + { eodSourceId: 'CUR.US', oldTicker: 'OLD1', effectiveDate: '2015-01-01' }, + { eodSourceId: 'CUR.US', oldTicker: 'OLD2', validFrom: '2015-01-01', effectiveDate: '2020-03-01' }, + // Duplicate alias entry and self-referential alias must not cause ambiguous_ticker_span. + { eodSourceId: 'CUR.US', oldTicker: 'OLD2', validFrom: '2015-01-01', effectiveDate: '2020-03-01' }, + { eodSourceId: 'CUR.US', oldTicker: 'CUR', effectiveDate: '2022-01-01' }, + // Unknown eodSourceId is a no-op. + { eodSourceId: 'UNKNOWN.US', oldTicker: 'GHOST', effectiveDate: '2021-05-01' }, + // Alias on an undated listing must preserve the missing_span safety guard. + { eodSourceId: 'UNDATED.US', oldTicker: 'OLDUND', effectiveDate: '2021-05-01' }, + ]; + + const tickerSources: StageBTickerSourceInput[] = [ + { + source: 'qm', + sourceId: 'QM_OLD1_2014', + ticker: 'OLD1', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2014-01-02', lastBarDate: '2014-12-31' }, + }, + { + source: 'qm', + sourceId: 'QM_OLD2_TOO_EARLY', + ticker: 'OLD2', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2014-06-01', lastBarDate: '2014-12-31' }, + }, + { + source: 'qm', + sourceId: 'QM_OLD2_LEAP_DAY', + ticker: 'OLD2', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-02-29', lastBarDate: '2020-02-29' }, + }, + { + source: 'qm', + sourceId: 'QM_OLD2_AFTER', + ticker: 'OLD2', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-03-01', lastBarDate: '2020-03-01' }, + }, + { + source: 'qm', + sourceId: 'QM_CUR_SELF_ALIAS', + ticker: 'CUR', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2019-01-02', lastBarDate: '2021-12-31' }, + }, + { + source: 'qm', + sourceId: 'QM_OLDUND', + ticker: 'OLDUND', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2019-01-02', lastBarDate: '2020-12-31' }, + }, + ]; + + const baseline = matchListingsStageB({ + instruments, + eodListings, + ibContracts: [], + tickerSources, + symbolChanges, + }); + + expect(baseline.conflicts).toEqual([]); + expect(baseline.providerMappings.filter(m => m.source === 'qm').map(m => m.sourceId)).toEqual([ + 'QM_CUR_SELF_ALIAS', + 'QM_OLD1_2014', + 'QM_OLD2_LEAP_DAY', + ]); + for (const m of baseline.providerMappings.filter(x => x.source === 'qm')) { + expect(m.listingKey.primaryIsin).toBe('US5555555555'); + expect(m.listingKey.tickerRoot).toBe('CUR'); + } + expect(baseline.unresolved).toEqual([ + { source: 'qm', sourceId: 'QM_OLD2_AFTER', reason: 'no_span_overlap', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_OLD2_TOO_EARLY', reason: 'no_span_overlap', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_OLDUND', reason: 'missing_span', primaryIsin: null }, + ]); + assertReconciliationAndContracts(baseline); + + // Shuffle invariance including symbolChanges. + const baselineJson = JSON.stringify(baseline); + for (const seed of [11, 99, 2026]) { + const shuffled = matchListingsStageB({ + instruments: shuffleWithSeed(instruments, seed), + eodListings: shuffleWithSeed(eodListings, seed + 1), + ibContracts: [], + tickerSources: shuffleWithSeed(tickerSources, seed + 2), + symbolChanges: shuffleWithSeed(symbolChanges, seed + 3), + }); + expect(JSON.stringify(shuffled)).toBe(baselineJson); + } + + // Malformed symbolChanges inputs throw explicit validation errors. + const baseEmpty = { instruments: [], eodListings: [], ibContracts: [], tickerSources: [] }; + + expect(() => + matchListingsStageB({ + ...baseEmpty, + symbolChanges: {} as unknown as StageBSymbolChangeInput[], + }) + ).toThrow(TypeError); + + const sparseChanges = new Array(2) as unknown as StageBSymbolChangeInput[]; + sparseChanges[1] = { eodSourceId: 'META.US', oldTicker: 'FB', effectiveDate: '2022-06-09' }; + expect(() => matchListingsStageB({ ...baseEmpty, symbolChanges: sparseChanges })).toThrow( + /symbolChanges\[0\]/ + ); + + expect(() => + matchListingsStageB({ + ...baseEmpty, + symbolChanges: [null as unknown as StageBSymbolChangeInput], + }) + ).toThrow(TypeError); + + expect(() => + matchListingsStageB({ + ...baseEmpty, + symbolChanges: [{ eodSourceId: '', oldTicker: 'FB', effectiveDate: '2022-06-09' }], + }) + ).toThrow(/symbolChanges\[0\]/); + + expect(() => + matchListingsStageB({ + ...baseEmpty, + symbolChanges: [{ eodSourceId: 'META.US', oldTicker: 'BRK..B', effectiveDate: '2022-06-09' }], + }) + ).toThrow(/symbolChanges\[0\]/); + + expect(() => + matchListingsStageB({ + ...baseEmpty, + symbolChanges: [{ eodSourceId: 'META.US', oldTicker: 'FB', effectiveDate: '2023-02-29' }], + }) + ).toThrow(RangeError); + + expect(() => + matchListingsStageB({ + ...baseEmpty, + symbolChanges: [{ eodSourceId: 'META.US', oldTicker: 'FB', effectiveDate: '0001-01-01' }], + }) + ).toThrow(RangeError); + + expect(() => + matchListingsStageB({ + ...baseEmpty, + symbolChanges: [ + { eodSourceId: 'META.US', oldTicker: 'FB', effectiveDate: '2022-06-09T00:00:00Z' }, + ], + }) + ).toThrow(RangeError); + + expect(() => + matchListingsStageB({ + ...baseEmpty, + symbolChanges: [ + { + eodSourceId: 'META.US', + oldTicker: 'FB', + effectiveDate: '2022-06-09', + validFrom: '2022-06-09', + }, + ], + }) + ).toThrow(RangeError); + + expect(() => + matchListingsStageB({ + ...baseEmpty, + symbolChanges: [ + { + eodSourceId: 'META.US', + oldTicker: 'FB', + effectiveDate: '2022-06-09', + validFrom: '2023-02-29', + }, + ], + }) + ).toThrow(RangeError); + }); + test('local scale benchmark: ~20k instruments, ~60k EOD, ~18k IB, ~40k QM/CEO complete under 5000 ms', () => { const NUM_INSTRUMENTS = 20_000; const instruments: StageAInstrumentCandidate[] = new Array(