From 32677c50da33cc5c4bab6ba9dabfc9a0de68e840 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 04:13:30 -0500 Subject: [PATCH] =?UTF-8?q?T-86:=20M1.1k=20=E2=80=94=20Read-only=20Mongo?= =?UTF-8?q?=20source-symbol=20readers:=20`eodSymbols`=20/=20`ibSymbols`=20?= =?UTF-8?q?/=20`qmSymbols`=20/=20`ceoSymbols`=20/=20`eodSymbolChange`=20?= =?UTF-8?q?=E2=86=92=20Stage=20A=20+=20Stage=20B=20input=20records=20(no?= =?UTF-8?q?=20new=20dependencies)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/stock/data-pipeline/README.md | 15 + .../src/security-master/index.ts | 52 + .../security-master/source-symbol-readers.ts | 1756 +++++++++++++++++ ...urity-master-source-symbol-readers.test.ts | 906 +++++++++ 4 files changed, 2729 insertions(+) create mode 100644 apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts create mode 100644 test/unit/security-master-source-symbol-readers.test.ts diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index 6ab39648..d2e41f6b 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -80,3 +80,18 @@ bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/secu - Workload: `20,000` instruments, `20,000` listings, `60,000` provider mappings (`100,000` core rows; `140,000` total rows including `20,000` `instrument_identifier_history` and `20,000` `listing_symbol_history` rows). - Observed end-to-end test wall time: `2.20s` (`2200.02ms`, reported by `bun test`; includes isolated schema migration, synthetic fixture construction, `persistSecurityMaster`, and `COUNT(*)` verification because `test/setup.ts` suppresses `console.info`). - Throughput (conservative lower bound over full test wall time): `45,454` core rows/s (`100,000 / 2.20002s`), `63,636` total rows/s (`140,000 / 2.20002s`). + +## Read-Only Source-Symbol Readers (`source-symbol-readers.ts`) +`apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts` adapts raw `eodSymbols`, `ibSymbols`, `qmSymbols`, `ceoSymbols`, and `eodSymbolChange` documents into deterministic Stage A (`StageASourceRecord`) and Stage B (`StageBEodListingInput`, `StageBIbContractInput`, `StageBTickerSourceInput`, `StageBSymbolChangeInput`) inputs via `readSecurityMasterSources`: + +- **Read-only contract:** Exposes only `isReadOnly()` and `find()` on `ReadOnlySourceSymbolReader` (compile-time verified against `MongoDBClient`) with explicit `_id: 0` projections (omitting `qmSymbols.profile`/`symbolInfo`) and pushed-down country/venue filters (default `['US', 'CA']`). +- **Provider rules enforced:** Excludes `eodSymbols` `Exchange="NMFQS"` mutual funds, preserves `delisted: true` and duplicate QM `(symbol, exchange)` pairs (`VOY:CNX` + `VOY:CC`), sets Stage A country strictly to issuer country (never listing country), never uses IB ATS `exchangeId` venues (`AEQLIT`, `OTCLNKECN`, etc.) as listing MIC or `primaryExchange`, strips CEO `.TO`/`.V` suffixes with Stage B double-strip protection, nulls invalid ISIN/CUSIP check digits without throwing, and reconciles `docsRead === emitted + sum(skips)` per collection. +- **Local synthetic benchmark:** Run the unit suite and fixed-seed 368,000-doc synthetic benchmark (`300,000` `eodSymbols` + `50,000` `qmSymbols` + `18,000` `ibSymbols`, zero DB connections) with: + +```bash +bun test test/unit/security-master-source-symbol-readers.test.ts +``` + +- **Recorded baseline (`2026-11-28`, local sandbox, in-memory streaming fake reader):** + - Workload: `368,000` synthetic docs (`300,000` `eodSymbols`, `50,000` `qmSymbols`, `18,000` `ibSymbols`) including NMFQS exclusion, country normalization, ISIN/CUSIP check-digit validation, ticker parsing, and deterministic ASCII sorting. + - Observed throughput: `940,646 docs/s` (`391.2 ms` wall time, floor `>= 25,000 docs/s`). diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 51d424f9..31590801 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -189,3 +189,55 @@ export { type SampleCloseRecord, type SelectSampleDatesOptions, } from './price-cross-check'; + +export { + adaptCeoSymbolDoc, + adaptEodSymbolChangeDoc, + adaptEodSymbolDoc, + adaptIbSymbolDoc, + adaptQmSymbolDoc, + CEO_SYMBOLS_PROJECTION, + createExchangeSourceLookup, + DEFAULT_SOURCE_COUNTRIES, + EOD_SYMBOL_CHANGE_PROJECTION, + EOD_SYMBOLS_PROJECTION, + IB_SYMBOLS_PROJECTION, + normalizeCountryIso2, + QM_SYMBOLS_PROJECTION, + readCeoSymbols, + readEodSymbolChanges, + readEodSymbols, + readIbSymbols, + readQmSymbols, + readSecurityMasterSources, + SOURCE_SYMBOL_COLLECTIONS, + type AdaptCeoSymbolContext, + type AdaptEodSymbolChangeContext, + type AdaptEodSymbolChangeResult, + type AdaptEodSymbolContext, + type AdaptEodSymbolResult, + type AdaptIbSymbolContext, + type AdaptIbSymbolResult, + type AdaptQmSymbolContext, + type AdaptTickerSourceResult, + type CreateExchangeSourceLookupOptions, + type ExchangeSourceLookup, + type ExchangeSourceLookupEntry, + type MongoDBClientSourceSymbolReaderCheck, + type ReadEodSymbolChangesResult, + type ReadEodSymbolsResult, + type ReadIbSymbolsResult, + type ReadOnlySourceSymbolReader, + type ReadSecurityMasterSourcesOptions, + type ReadSourceCollectionOptions, + type ReadTickerSourcesResult, + type SecurityMasterSourcesResult, + type SecurityMasterSourcesStats, + type SecurityMasterStageBSourceInput, + type SourceCollectionReadStats, + type SourceSymbolCollectionKey, + type SourceSymbolCollectionName, + type SourceSymbolFindOptions, + type SourceSymbolSkipCounts, + type SourceSymbolSkipReason, +} from './source-symbol-readers'; diff --git a/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts b/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts new file mode 100644 index 00000000..ef7d3077 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts @@ -0,0 +1,1756 @@ +import type { MongoDBClient } from '@stock-bot/mongodb'; +import { + normalizeBarDate, + type BarSpanIndex, + type SpanDateRange, +} from '../normalization/bar-spans'; +import { isValidCusip, isValidIsin } from '../normalization/identifiers'; +import { normalizeProviderSymbol } from '../normalization/provider-symbol'; +import { parseTickerDetailed } from '../normalization/ticker'; +import { + compareAscii, + EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS, + ISO_EXCHANGE_SEEDS, + type ExchangeRole, + type ExchangeSeedRow, + type ExchangeSource, + type ExchangeSourceMapRow, +} from './exchange-pass1'; +import type { StageASourceRecord } from './instrument-stage-a'; +import { + MAX_TICKER_ROOT_LENGTH, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBInput, + type StageBSymbolChangeInput, + type StageBTickerSourceInput, +} from './listing-stage-b'; + +export const SOURCE_SYMBOL_COLLECTIONS = Object.freeze({ + eod: 'eodSymbols', + ib: 'ibSymbols', + qm: 'qmSymbols', + ceo: 'ceoSymbols', + eodSymbolChange: 'eodSymbolChange', +} as const); + +export type SourceSymbolCollectionKey = keyof typeof SOURCE_SYMBOL_COLLECTIONS; +export type SourceSymbolCollectionName = + (typeof SOURCE_SYMBOL_COLLECTIONS)[SourceSymbolCollectionKey]; + +export const DEFAULT_SOURCE_COUNTRIES: readonly string[] = Object.freeze(['US', 'CA']); + +export interface SourceSymbolFindOptions { + projection?: Record; + batchSize?: number; +} + +/** + * Narrow read-only MongoDB reader interface for source-symbol collections. + * Exposes strictly `isReadOnly()` and `find()` — no write, index, drop, or + * collection-mutation methods are reachable through this contract. + */ +export interface ReadOnlySourceSymbolReader { + isReadOnly(): boolean; + find = Record>( + collectionName: string, + filter?: Record, + options?: SourceSymbolFindOptions + ): Promise | AsyncIterable> | Iterable | AsyncIterable; +} + +// Compile-time structural compatibility check (type-only, erased at runtime): +// ensures MongoDBClient satisfies ReadOnlySourceSymbolReader under `bun run typecheck`. +type AssertAssignable = true; +export type MongoDBClientSourceSymbolReaderCheck = AssertAssignable< + ReadOnlySourceSymbolReader, + MongoDBClient +>; + +export interface ExchangeSourceLookupEntry { + readonly source: ExchangeSource; + readonly sourceCode: string; + readonly role: ExchangeRole; + readonly mic: string | null; + readonly countryIso: string | null; +} + +export interface ExchangeSourceLookup { + get(source: ExchangeSource, sourceCode: string): ExchangeSourceLookupEntry | undefined; + getCodesForCountries?(source: ExchangeSource, countries: readonly string[]): string[]; +} + +export interface CreateExchangeSourceLookupOptions { + readonly includeExplicitRules?: boolean; +} + +export type SourceSymbolSkipReason = + | 'missingId' + | 'invalidFieldType' + | 'invalidIdentifier' + | 'excludedMutualFund' + | 'unmappedExchange' + | 'outOfScopeCountry'; + +export interface SourceSymbolSkipCounts { + missingId: number; + invalidFieldType: number; + invalidIdentifier: number; + excludedMutualFund: number; + unmappedExchange: number; + outOfScopeCountry: number; +} + +export interface SourceCollectionReadStats { + collection: SourceSymbolCollectionName; + docsRead: number; + emitted: number; + invalidIdentifiersNulled: number; + skips: SourceSymbolSkipCounts; +} + +export interface ReadSourceCollectionOptions { + readonly exchangeLookup: ExchangeSourceLookup; + readonly barSpans?: Pick | null; + readonly ceoSpans?: ReadonlyMap | null; + readonly countries?: readonly string[] | null; + readonly knownExchanges?: readonly ExchangeSeedRow[]; + readonly batchSize?: number; +} + +export type ReadSecurityMasterSourcesOptions = ReadSourceCollectionOptions; + +export interface AdaptEodSymbolContext { + readonly exchangeLookup: ExchangeSourceLookup; + readonly barSpans?: Pick | null; + readonly allowedCountries: ReadonlySet | null; + readonly micCurrencyMap: ReadonlyMap; +} + +export interface AdaptIbSymbolContext { + readonly exchangeLookup: ExchangeSourceLookup; + readonly allowedCountries: ReadonlySet | null; +} + +export interface AdaptQmSymbolContext { + readonly exchangeLookup: ExchangeSourceLookup; + readonly barSpans?: Pick | null; + readonly allowedCountries: ReadonlySet | null; + readonly micCurrencyMap: ReadonlyMap; +} + +export interface AdaptCeoSymbolContext { + readonly exchangeLookup: ExchangeSourceLookup; + readonly ceoSpans?: ReadonlyMap | null; + readonly allowedCountries: ReadonlySet | null; + readonly micCurrencyMap: ReadonlyMap; +} + +export interface AdaptEodSymbolChangeContext { + readonly exchangeLookup: ExchangeSourceLookup; + readonly allowedCountries: ReadonlySet | null; +} + +export type AdaptEodSymbolResult = + | { + readonly ok: true; + readonly stageARecord: StageASourceRecord; + readonly eodListing: StageBEodListingInput; + readonly invalidIdentifiersNulled: number; + } + | { readonly ok: false; readonly skipReason: SourceSymbolSkipReason }; + +export type AdaptIbSymbolResult = + | { + readonly ok: true; + readonly stageARecord: StageASourceRecord; + readonly ibContract: StageBIbContractInput; + readonly invalidIdentifiersNulled: number; + } + | { readonly ok: false; readonly skipReason: SourceSymbolSkipReason }; + +export type AdaptTickerSourceResult = + | { + readonly ok: true; + readonly tickerSource: StageBTickerSourceInput; + } + | { readonly ok: false; readonly skipReason: SourceSymbolSkipReason }; + +export type AdaptEodSymbolChangeResult = + | { + readonly ok: true; + readonly symbolChange: StageBSymbolChangeInput; + } + | { readonly ok: false; readonly skipReason: SourceSymbolSkipReason }; + +export interface ReadEodSymbolsResult { + stageARecords: StageASourceRecord[]; + eodListings: StageBEodListingInput[]; + stats: SourceCollectionReadStats; +} + +export interface ReadIbSymbolsResult { + stageARecords: StageASourceRecord[]; + ibContracts: StageBIbContractInput[]; + stats: SourceCollectionReadStats; +} + +export interface ReadTickerSourcesResult { + tickerSources: StageBTickerSourceInput[]; + stats: SourceCollectionReadStats; +} + +export interface ReadEodSymbolChangesResult { + symbolChanges: StageBSymbolChangeInput[]; + stats: SourceCollectionReadStats; +} + +export interface SecurityMasterStageBSourceInput + extends Omit { + eodListings: StageBEodListingInput[]; + ibContracts: StageBIbContractInput[]; + tickerSources: StageBTickerSourceInput[]; + symbolChanges: StageBSymbolChangeInput[]; +} + +export interface SecurityMasterSourcesStats { + eodSymbols: SourceCollectionReadStats; + ibSymbols: SourceCollectionReadStats; + qmSymbols: SourceCollectionReadStats; + ceoSymbols: SourceCollectionReadStats; + eodSymbolChange: SourceCollectionReadStats; +} + +export interface SecurityMasterSourcesResult { + stageARecords: StageASourceRecord[]; + stageBInput: SecurityMasterStageBSourceInput; + stats: SecurityMasterSourcesStats; +} + +const ISO2_PATTERN = /^[A-Z]{2}$/; +const DEFAULT_CEO_CA_CODES: readonly string[] = Object.freeze(['AQL', 'CDX', 'CNQ', 'TSX']); + +const COUNTRY_NAME_TO_ISO2: ReadonlyMap = new Map([ + ['US', 'US'], + ['USA', 'US'], + ['U.S.', 'US'], + ['U.S.A.', 'US'], + ['UNITED STATES', 'US'], + ['UNITED STATES OF AMERICA', 'US'], + ['CA', 'CA'], + ['CAN', 'CA'], + ['CANADA', 'CA'], + ['GB', 'GB'], + ['GBR', 'GB'], + ['UK', 'GB'], + ['UNITED KINGDOM', 'GB'], + ['GREAT BRITAIN', 'GB'], + ['DE', 'DE'], + ['DEU', 'DE'], + ['GERMANY', 'DE'], + ['FR', 'FR'], + ['FRA', 'FR'], + ['FRANCE', 'FR'], + ['AU', 'AU'], + ['AUS', 'AU'], + ['AUSTRALIA', 'AU'], + ['JP', 'JP'], + ['JPN', 'JP'], + ['JAPAN', 'JP'], + ['CN', 'CN'], + ['CHN', 'CN'], + ['CHINA', 'CN'], + ['HK', 'HK'], + ['HKG', 'HK'], + ['HONG KONG', 'HK'], + ['CH', 'CH'], + ['CHE', 'CH'], + ['SWITZERLAND', 'CH'], + ['NL', 'NL'], + ['NLD', 'NL'], + ['NETHERLANDS', 'NL'], + ['IT', 'IT'], + ['ITA', 'IT'], + ['ITALY', 'IT'], + ['ES', 'ES'], + ['ESP', 'ES'], + ['SPAIN', 'ES'], + ['SE', 'SE'], + ['SWE', 'SE'], + ['SWEDEN', 'SE'], + ['NO', 'NO'], + ['NOR', 'NO'], + ['NORWAY', 'NO'], + ['DK', 'DK'], + ['DNK', 'DK'], + ['DENMARK', 'DK'], + ['FI', 'FI'], + ['FIN', 'FI'], + ['FINLAND', 'FI'], + ['BE', 'BE'], + ['BEL', 'BE'], + ['BELGIUM', 'BE'], + ['AT', 'AT'], + ['AUT', 'AT'], + ['AUSTRIA', 'AT'], + ['IE', 'IE'], + ['IRL', 'IE'], + ['IRELAND', 'IE'], + ['IN', 'IN'], + ['IND', 'IN'], + ['INDIA', 'IN'], + ['BR', 'BR'], + ['BRA', 'BR'], + ['BRAZIL', 'BR'], + ['MX', 'MX'], + ['MEX', 'MX'], + ['MEXICO', 'MX'], + ['KR', 'KR'], + ['KOR', 'KR'], + ['SOUTH KOREA', 'KR'], + ['KOREA', 'KR'], + ['TW', 'TW'], + ['TWN', 'TW'], + ['TAIWAN', 'TW'], + ['SG', 'SG'], + ['SGP', 'SG'], + ['SINGAPORE', 'SG'], + ['NZ', 'NZ'], + ['NZL', 'NZ'], + ['NEW ZEALAND', 'NZ'], + ['IL', 'IL'], + ['ISR', 'IL'], + ['ISRAEL', 'IL'], + ['ZA', 'ZA'], + ['ZAF', 'ZA'], + ['SOUTH AFRICA', 'ZA'], + ['PL', 'PL'], + ['POL', 'PL'], + ['POLAND', 'PL'], + ['PT', 'PT'], + ['PRT', 'PT'], + ['PORTUGAL', 'PT'], + ['GR', 'GR'], + ['GRC', 'GR'], + ['GREECE', 'GR'], + ['TR', 'TR'], + ['TUR', 'TR'], + ['TURKEY', 'TR'], + ['AR', 'AR'], + ['ARG', 'AR'], + ['ARGENTINA', 'AR'], + ['CL', 'CL'], + ['CHL', 'CL'], + ['CHILE', 'CL'], + ['ID', 'ID'], + ['IDN', 'ID'], + ['INDONESIA', 'ID'], + ['MY', 'MY'], + ['MYS', 'MY'], + ['MALAYSIA', 'MY'], + ['TH', 'TH'], + ['THA', 'TH'], + ['THAILAND', 'TH'], + ['VN', 'VN'], + ['VNM', 'VN'], + ['VIETNAM', 'VN'], + ['PH', 'PH'], + ['PHL', 'PH'], + ['PHILIPPINES', 'PH'], + ['SA', 'SA'], + ['SAU', 'SA'], + ['SAUDI ARABIA', 'SA'], + ['AE', 'AE'], + ['ARE', 'AE'], + ['UAE', 'AE'], + ['UNITED ARAB EMIRATES', 'AE'], +]); + +const EOD_COUNTRY_FILTER_SPELLINGS: Readonly> = Object.freeze({ + US: Object.freeze(['US', 'USA', 'United States', 'United States of America']), + CA: Object.freeze(['CA', 'CAN', 'Canada']), +}); + +export const EOD_SYMBOLS_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + eodSearchCode: 1, + Code: 1, + code: 1, + symbol: 1, + Exchange: 1, + eodExchange: 1, + exchange: 1, + exchangeCode: 1, + Country: 1, + countryCode: 1, + Currency: 1, + currency: 1, + Isin: 1, + isin: 1, + Cusip: 1, + cusip: 1, + Name: 1, + name: 1, + companyName: 1, + delisted: 1, +}); + +export const IB_SYMBOLS_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + conid: 1, + symbol: 1, + localSymbol: 1, + exchangeId: 1, + exchange: 1, + exchangeCode: 1, + primaryExchange: 1, + listingExchange: 1, + country: 1, + countryCode: 1, + currency: 1, + isin: 1, + cusip: 1, + description: 1, + name: 1, + companyName: 1, +}); + +export const QM_SYMBOLS_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + qmSearchCode: 1, + symbol: 1, + code: 1, + exchange: 1, + exchangeCode: 1, + countryCode: 1, + country: 1, + currency: 1, + name: 1, + companyName: 1, + active: 1, +}); + +export const CEO_SYMBOLS_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + ceoId: 1, + symbol: 1, + exchange: 1, + exchangeCode: 1, + countryCode: 1, + country: 1, + currency: 1, + name: 1, + lastSeen: 1, +}); + +export const EOD_SYMBOL_CHANGE_PROJECTION: Readonly> = Object.freeze({ + _id: 0, + oldSymbol: 1, + newSymbol: 1, + exchange: 1, + eodExchange: 1, + eodSearchCode: 1, + date: 1, + effectiveDate: 1, + validFrom: 1, + country: 1, + Country: 1, +}); + +/** + * Normalizes ISO-2 country codes and common provider country name spellings + * (e.g. EODHD `'USA'`, `'United States'`, `'Canada'`) to uppercase ISO-2. + */ +export function normalizeCountryIso2(value: string | null | undefined): string | null { + if (typeof value !== 'string') { + return null; + } + const trimmed = value.trim(); + if (trimmed.length === 0) { + return null; + } + const upper = trimmed.toUpperCase(); + const mapped = COUNTRY_NAME_TO_ISO2.get(upper); + if (mapped !== undefined) { + return mapped; + } + return ISO2_PATTERN.test(upper) ? upper : null; +} + +/** + * Builds an in-memory per-source lookup map from Pass 1 `exchange_source_map` rows. + * Seeds `EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS` by default with caller rows taking precedence. + */ +export function createExchangeSourceLookup( + rows: readonly ExchangeSourceMapRow[], + options: CreateExchangeSourceLookupOptions = {} +): ExchangeSourceLookup { + const bySource: Readonly>> = { + eod: new Map(), + ib: new Map(), + qm: new Map(), + ceo: new Map(), + }; + + const insertRow = (row: ExchangeSourceMapRow): void => { + const code = row.sourceCode.trim().toUpperCase(); + if (code.length === 0) { + return; + } + const mic = row.mic === null ? null : row.mic.trim().toUpperCase() || null; + const countryIso = + row.countryIso === null + ? null + : (normalizeCountryIso2(row.countryIso) ?? (row.countryIso.trim().toUpperCase() || null)); + bySource[row.source].set(code, { + source: row.source, + sourceCode: code, + role: row.role, + mic, + countryIso, + }); + }; + + if (options.includeExplicitRules !== false) { + for (let i = 0; i < EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS.length; i++) { + const row = EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS[i]; + if (row !== undefined) { + insertRow(row); + } + } + } + + for (let i = 0; i < rows.length; i++) { + const row = rows[i]; + if (row !== undefined) { + insertRow(row); + } + } + + return { + get(source: ExchangeSource, sourceCode: string): ExchangeSourceLookupEntry | undefined { + const code = sourceCode.trim().toUpperCase(); + if (code.length === 0) { + return undefined; + } + return bySource[source].get(code); + }, + getCodesForCountries(source: ExchangeSource, countries: readonly string[]): string[] { + const allowed = new Set(); + for (let i = 0; i < countries.length; i++) { + const iso = normalizeCountryIso2(countries[i]); + if (iso !== null) { + allowed.add(iso); + } + } + if (allowed.size === 0) { + return []; + } + const codes: string[] = []; + for (const entry of bySource[source].values()) { + if (entry.countryIso !== null && allowed.has(entry.countryIso)) { + codes.push(entry.sourceCode); + } + } + codes.sort(compareAscii); + return codes; + }, + }; +} + +function buildMicCurrencyMap( + knownExchanges: readonly ExchangeSeedRow[] = ISO_EXCHANGE_SEEDS +): ReadonlyMap { + const map = new Map(); + for (let i = 0; i < knownExchanges.length; i++) { + const row = knownExchanges[i]; + if (row === undefined) { + continue; + } + const mic = row.mic.trim().toUpperCase(); + const currency = row.currency.trim().toUpperCase(); + if (mic.length > 0 && currency.length > 0) { + map.set(mic, currency); + } + } + return map; +} + +function resolveAllowedCountries(countries?: readonly string[] | null): { + set: ReadonlySet | null; + list: string[] | null; +} { + if (countries === null) { + return { set: null, list: null }; + } + const source = countries === undefined ? DEFAULT_SOURCE_COUNTRIES : countries; + const set = new Set(); + for (let i = 0; i < source.length; i++) { + const raw = source[i]; + const normalized = normalizeCountryIso2(raw); + if (normalized !== null) { + set.add(normalized); + } else if (typeof raw === 'string' && raw.trim().length > 0) { + set.add(raw.trim().toUpperCase()); + } + } + const list = [...set].sort(compareAscii); + return { set, list }; +} + +function createEmptySkipCounts(): SourceSymbolSkipCounts { + return { + missingId: 0, + invalidFieldType: 0, + invalidIdentifier: 0, + excludedMutualFund: 0, + unmappedExchange: 0, + outOfScopeCountry: 0, + }; +} + +function createCollectionStats( + collection: SourceSymbolCollectionName +): SourceCollectionReadStats { + return { + collection, + docsRead: 0, + emitted: 0, + invalidIdentifiersNulled: 0, + skips: createEmptySkipCounts(), + }; +} + +function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void { + if ( + reader === null || + reader === undefined || + typeof reader !== 'object' || + typeof reader.isReadOnly !== 'function' || + !reader.isReadOnly() + ) { + throw new Error( + 'Source symbol reader requires a read-only MongoDB client (isReadOnly() must be true)' + ); + } +} + +function isSyncIterable(value: unknown): value is Iterable { + return ( + value !== null && + (typeof value === 'object' || typeof value === 'function') && + typeof (value as Record)[Symbol.iterator] === 'function' + ); +} + +function isAsyncIterable(value: unknown): value is AsyncIterable { + return ( + value !== null && + (typeof value === 'object' || typeof value === 'function') && + typeof (value as Record)[Symbol.asyncIterator] === 'function' + ); +} + +async function streamCollection>( + reader: ReadOnlySourceSymbolReader, + collectionName: SourceSymbolCollectionName, + filter: Record, + options: SourceSymbolFindOptions, + onDoc: (doc: unknown) => void +): Promise { + assertReadOnlyReader(reader); + try { + const cursor = await reader.find(collectionName, filter, options); + if (isAsyncIterable(cursor)) { + for await (const doc of cursor) { + onDoc(doc); + } + return; + } + if (isSyncIterable(cursor)) { + for (const doc of cursor) { + onDoc(doc); + } + return; + } + throw new TypeError( + `Reader returned a non-iterable result for collection "${collectionName}"` + ); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + const message = detail.includes(collectionName) + ? detail + : `Failed reading collection "${collectionName}": ${detail}`; + throw new Error(message, { cause: error }); + } +} + +type StringFieldResult = { readonly ok: true; readonly value: string | null } | { readonly ok: false }; + +function readOptionalString(doc: Record, key: string): StringFieldResult { + const raw = doc[key]; + if (raw === undefined || raw === null) { + return { ok: true, value: null }; + } + if (typeof raw !== 'string') { + return { ok: false }; + } + const trimmed = raw.trim(); + return { ok: true, value: trimmed.length > 0 ? trimmed : null }; +} + +function readFirstOptionalString( + doc: Record, + keys: readonly string[] +): StringFieldResult { + let found: string | null = null; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (key === undefined) { + continue; + } + const res = readOptionalString(doc, key); + if (!res.ok) { + return res; + } + if (found === null && res.value !== null) { + found = res.value; + } + } + return { ok: true, value: found }; +} + +function isPlainRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function isNorthAmericaIso(code: string | null): code is 'US' | 'CA' { + return code === 'US' || code === 'CA'; +} + +function countryFallbackCurrency(countryIso: string | null): string | null { + if (countryIso === 'US') { + return 'USD'; + } + if (countryIso === 'CA') { + return 'CAD'; + } + return null; +} + +function formatCanonicalTicker(tickerRoot: string, classSuffix: string): string { + return classSuffix.length > 0 ? `${tickerRoot}.${classSuffix}` : tickerRoot; +} + +/** + * Formats a parsed CEO ticker so Stage B's `parseTickerDetailed(ticker, 'ceo')` + * recovers the exact `(tickerRoot, classSuffix)` without double-stripping a + * share-class suffix that happens to be `TO` or `V`. + */ +function formatStageBSafeCeoTicker(tickerRoot: string, classSuffix: string): string { + if (classSuffix.length === 0) { + return tickerRoot; + } + if (classSuffix === 'TO' || classSuffix === 'V') { + return `${tickerRoot}-${classSuffix}`; + } + if (classSuffix.endsWith('.TO')) { + return `${tickerRoot}.${classSuffix.slice(0, -3)}-TO`; + } + if (classSuffix.endsWith('.V')) { + return `${tickerRoot}.${classSuffix.slice(0, -2)}-V`; + } + return `${tickerRoot}.${classSuffix}`; +} + +function toSpanDateRange(span: SpanDateRange | undefined | null): SpanDateRange | null { + if (span === undefined || span === null) { + return null; + } + return { + firstBarDate: span.firstBarDate, + lastBarDate: span.lastBarDate, + }; +} + +function buildEodCountryFilter(countries: readonly string[] | null): Record { + if (countries === null) { + return {}; + } + const expanded = new Set(); + for (let i = 0; i < countries.length; i++) { + const iso = countries[i]; + if (iso === undefined) { + continue; + } + const spellings = EOD_COUNTRY_FILTER_SPELLINGS[iso]; + if (spellings !== undefined) { + for (let j = 0; j < spellings.length; j++) { + const spelling = spellings[j]; + if (spelling !== undefined) { + expanded.add(spelling); + } + } + } else { + expanded.add(iso); + } + } + return { Country: { $in: [...expanded].sort(compareAscii) } }; +} + +function buildIbCountryFilter(countries: readonly string[] | null): Record { + if (countries === null) { + return {}; + } + return { country: { $in: [...countries] } }; +} + +function buildQmCountryFilter(countries: readonly string[] | null): Record { + if (countries === null) { + return {}; + } + return { countryCode: { $in: [...countries] } }; +} + +function buildCeoCountryFilter( + exchangeLookup: ExchangeSourceLookup, + countries: readonly string[] | null +): Record { + if (countries === null) { + return {}; + } + if (typeof exchangeLookup.getCodesForCountries === 'function') { + return { exchange: { $in: exchangeLookup.getCodesForCountries('ceo', countries) } }; + } + const codes = countries.includes('CA') ? [...DEFAULT_CEO_CA_CODES] : []; + return { exchange: { $in: codes } }; +} + +function buildEodSymbolChangeFilter( + exchangeLookup: ExchangeSourceLookup, + countries: readonly string[] | null +): Record { + if (countries === null) { + return {}; + } + if (typeof exchangeLookup.getCodesForCountries === 'function') { + return { exchange: { $in: exchangeLookup.getCodesForCountries('eod', countries) } }; + } + return {}; +} + +function compareStageARecords(a: StageASourceRecord, b: StageASourceRecord): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.isin ?? '', b.isin ?? '') || + compareAscii(a.cusip ?? '', b.cusip ?? '') || + compareAscii(a.country ?? '', b.country ?? '') || + compareAscii(a.currency ?? '', b.currency ?? '') || + compareAscii(a.name ?? '', b.name ?? '') + ); +} + +function compareEodListings(a: StageBEodListingInput, b: StageBEodListingInput): number { + return ( + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.mic ?? '', b.mic ?? '') || + compareAscii(a.role ?? '', b.role ?? '') || + compareAscii(a.ticker ?? '', b.ticker ?? '') || + compareAscii(a.currency ?? '', b.currency ?? '') || + compareAscii(a.span?.firstBarDate ?? '', b.span?.firstBarDate ?? '') || + compareAscii(a.span?.lastBarDate ?? '', b.span?.lastBarDate ?? '') + ); +} + +function compareIbContracts(a: StageBIbContractInput, b: StageBIbContractInput): number { + return ( + compareAscii(a.sourceId, b.sourceId) || + (a.conid === b.conid ? 0 : a.conid < b.conid ? -1 : 1) || + compareAscii(a.currency ?? '', b.currency ?? '') || + compareAscii(a.primaryExchange ?? '', b.primaryExchange ?? '') + ); +} + +function compareTickerSources(a: StageBTickerSourceInput, b: StageBTickerSourceInput): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.mic ?? '', b.mic ?? '') || + compareAscii(a.role ?? '', b.role ?? '') || + compareAscii(a.ticker ?? '', b.ticker ?? '') || + compareAscii(a.currency ?? '', b.currency ?? '') || + compareAscii(a.span?.firstBarDate ?? '', b.span?.firstBarDate ?? '') || + compareAscii(a.span?.lastBarDate ?? '', b.span?.lastBarDate ?? '') + ); +} + +function compareSymbolChanges(a: StageBSymbolChangeInput, b: StageBSymbolChangeInput): number { + return ( + compareAscii(a.eodSourceId, b.eodSourceId) || + compareAscii(a.effectiveDate, b.effectiveDate) || + compareAscii(a.oldTicker, b.oldTicker) || + compareAscii(a.validFrom ?? '', b.validFrom ?? '') + ); +} + +/** + * Pure adapter converting a raw `eodSymbols` document into a Stage A source record + * and Stage B EOD listing input. + */ +export function adaptEodSymbolDoc( + doc: unknown, + context: AdaptEodSymbolContext +): AdaptEodSymbolResult { + if (!isPlainRecord(doc)) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + const sourceIdField = readOptionalString(doc, 'eodSearchCode'); + const tickerField = readFirstOptionalString(doc, ['Code', 'code', 'symbol']); + // Resolve listing venue from Exchange/exchange/exchangeCode — never from composite eodExchange="US". + const exchangeField = readFirstOptionalString(doc, ['Exchange', 'exchange', 'exchangeCode']); + const countryField = readFirstOptionalString(doc, ['Country', 'countryCode']); + const currencyField = readFirstOptionalString(doc, ['Currency', 'currency']); + const isinField = readFirstOptionalString(doc, ['Isin', 'isin']); + const cusipField = readFirstOptionalString(doc, ['Cusip', 'cusip']); + const nameField = readFirstOptionalString(doc, ['Name', 'name', 'companyName']); + + if ( + !sourceIdField.ok || + !tickerField.ok || + !exchangeField.ok || + !countryField.ok || + !currencyField.ok || + !isinField.ok || + !cusipField.ok || + !nameField.ok + ) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + if (sourceIdField.value === null) { + return { ok: false, skipReason: 'missingId' }; + } + + const sourceId = sourceIdField.value; + const rawExchange = exchangeField.value; + const exchangeEntry = + rawExchange !== null ? context.exchangeLookup.get('eod', rawExchange) : undefined; + + if (context.allowedCountries !== null) { + if (countryField.value !== null) { + const normalizedCountry = normalizeCountryIso2(countryField.value); + if (normalizedCountry === null || !context.allowedCountries.has(normalizedCountry)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } else if (exchangeEntry?.countryIso !== undefined && exchangeEntry.countryIso !== null) { + if (!context.allowedCountries.has(exchangeEntry.countryIso)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } + } + + if (rawExchange !== null && rawExchange.toUpperCase() === 'NMFQS') { + return { ok: false, skipReason: 'excludedMutualFund' }; + } + if (exchangeEntry?.role === 'excluded_fund') { + return { ok: false, skipReason: 'excludedMutualFund' }; + } + + if (rawExchange === null || exchangeEntry === undefined) { + return { ok: false, skipReason: 'unmappedExchange' }; + } + + const normalized = normalizeProviderSymbol({ + Code: tickerField.value, + Exchange: rawExchange, + Name: nameField.value, + Country: countryField.value, + Currency: currencyField.value, + eodSearchCode: sourceId, + }); + + let invalidIdentifiersNulled = 0; + let validIsin: string | null = null; + if (isinField.value !== null) { + const candidate = isinField.value.toUpperCase(); + if (isValidIsin(candidate)) { + validIsin = candidate; + } else { + invalidIdentifiersNulled += 1; + } + } + + let validCusip: string | null = null; + if (cusipField.value !== null) { + const candidate = cusipField.value.toUpperCase(); + if (isValidCusip(candidate)) { + validCusip = candidate; + } else { + invalidIdentifiersNulled += 1; + } + } + + // Per T-55: Stage A country must be issuer country (from ISIN prefix), never listing Country. + let issuerCountry: string | null = null; + if (validIsin !== null) { + issuerCountry = validIsin.slice(0, 2); + } else if (validCusip !== null && isinField.value !== null && isinField.value.length >= 2) { + const rawPrefix = isinField.value.slice(0, 2).toUpperCase(); + if (isNorthAmericaIso(rawPrefix)) { + issuerCountry = rawPrefix; + } + } + + const rawCurrency = normalized?.currency ?? currencyField.value; + const currency = + rawCurrency !== null + ? rawCurrency.toUpperCase() + : exchangeEntry.mic !== null + ? context.micCurrencyMap.get(exchangeEntry.mic) ?? null + : null; + + const name = normalized?.companyName ?? nameField.value; + const ticker = normalized?.symbol ?? tickerField.value; + const span = toSpanDateRange(context.barSpans?.get('eod', sourceId)); + + return { + ok: true, + stageARecord: { + source: 'eod', + sourceId, + isin: validIsin, + cusip: validCusip, + country: issuerCountry, + currency, + name, + }, + eodListing: { + sourceId, + ticker, + mic: exchangeEntry.mic, + role: exchangeEntry.role, + currency, + span, + }, + invalidIdentifiersNulled, + }; +} + +/** + * Pure adapter converting a raw `ibSymbols` document into a Stage A source record + * and Stage B IB contract input. Never blocks on `exchangeId` or treats ATS venues + * (e.g. `AEQLIT`, `OTCLNKECN`) as listing MICs or primary exchanges. + */ +export function adaptIbSymbolDoc( + doc: unknown, + context: AdaptIbSymbolContext +): AdaptIbSymbolResult { + if (!isPlainRecord(doc)) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + const rawConid = doc.conid; + if (rawConid === undefined || rawConid === null) { + return { ok: false, skipReason: 'missingId' }; + } + if (typeof rawConid !== 'number') { + return { ok: false, skipReason: 'invalidFieldType' }; + } + if (!Number.isSafeInteger(rawConid) || rawConid <= 0) { + return { ok: false, skipReason: 'invalidIdentifier' }; + } + + const symbolField = readFirstOptionalString(doc, ['symbol', 'localSymbol']); + const exchangeIdField = readFirstOptionalString(doc, ['exchangeId', 'exchange', 'exchangeCode']); + const explicitPrimaryExchangeField = readFirstOptionalString(doc, [ + 'primaryExchange', + 'listingExchange', + ]); + const countryField = readFirstOptionalString(doc, ['country', 'countryCode']); + const currencyField = readOptionalString(doc, 'currency'); + const isinField = readOptionalString(doc, 'isin'); + const cusipField = readOptionalString(doc, 'cusip'); + const nameField = readFirstOptionalString(doc, ['companyName', 'name', 'description']); + + if ( + !symbolField.ok || + !exchangeIdField.ok || + !explicitPrimaryExchangeField.ok || + !countryField.ok || + !currencyField.ok || + !isinField.ok || + !cusipField.ok || + !nameField.ok + ) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + const normalizedDocCountry = + countryField.value !== null ? normalizeCountryIso2(countryField.value) : null; + if (context.allowedCountries !== null) { + if (normalizedDocCountry === null || !context.allowedCountries.has(normalizedDocCountry)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } + + const normalized = normalizeProviderSymbol({ + symbol: symbolField.value, + exchangeId: exchangeIdField.value, + description: nameField.value, + countryCode: countryField.value, + currency: currencyField.value, + }); + + let invalidIdentifiersNulled = 0; + let validIsin: string | null = null; + if (isinField.value !== null) { + const candidate = isinField.value.toUpperCase(); + if (isValidIsin(candidate)) { + validIsin = candidate; + } else { + invalidIdentifiersNulled += 1; + } + } + + let validCusip: string | null = null; + if (cusipField.value !== null) { + const candidate = cusipField.value.toUpperCase(); + if (isValidCusip(candidate)) { + validCusip = candidate; + } else { + invalidIdentifiersNulled += 1; + } + } + + // Derive Stage A issuer country without leaking listing country when valid ISIN is present. + let issuerCountry: string | null = null; + if (validIsin !== null) { + issuerCountry = validIsin.slice(0, 2); + } else if (validCusip !== null) { + const rawPrefix = + isinField.value !== null && isinField.value.length >= 2 + ? isinField.value.slice(0, 2).toUpperCase() + : null; + if (isNorthAmericaIso(rawPrefix)) { + issuerCountry = rawPrefix; + } else if (isNorthAmericaIso(normalizedDocCountry)) { + issuerCountry = normalizedDocCountry; + } + } + + let primaryExchange: string | null = null; + if (explicitPrimaryExchangeField.value !== null) { + primaryExchange = explicitPrimaryExchangeField.value.toUpperCase(); + } else if (exchangeIdField.value !== null) { + const entry = context.exchangeLookup.get('ib', exchangeIdField.value); + if (entry?.role === 'primary_venue') { + primaryExchange = exchangeIdField.value.toUpperCase(); + } + } + + const sourceId = String(rawConid); + const currency = currencyField.value !== null ? currencyField.value.toUpperCase() : null; + const name = normalized?.companyName ?? nameField.value; + + return { + ok: true, + stageARecord: { + source: 'ib', + sourceId, + isin: validIsin, + cusip: validCusip, + country: issuerCountry, + currency, + name, + }, + ibContract: { + sourceId, + conid: rawConid, + currency, + primaryExchange, + }, + invalidIdentifiersNulled, + }; +} + +/** + * Pure adapter converting a raw `qmSymbols` document into a Stage B ticker-source input. + * Preserves inactive (`active: false`) records and duplicate `(symbol, exchange)` pairs + * (such as `VOY:CNX` and `VOY:CC`) as distinct `qmSearchCode` `sourceId`s. + */ +export function adaptQmSymbolDoc( + doc: unknown, + context: AdaptQmSymbolContext +): AdaptTickerSourceResult { + if (!isPlainRecord(doc)) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + const sourceIdField = readOptionalString(doc, 'qmSearchCode'); + const symbolField = readFirstOptionalString(doc, ['symbol', 'code']); + const exchangeField = readFirstOptionalString(doc, ['exchange', 'exchangeCode']); + const countryField = readFirstOptionalString(doc, ['countryCode', 'country']); + const currencyField = readOptionalString(doc, 'currency'); + + if ( + !sourceIdField.ok || + !symbolField.ok || + !exchangeField.ok || + !countryField.ok || + !currencyField.ok + ) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + if (sourceIdField.value === null) { + return { ok: false, skipReason: 'missingId' }; + } + + const sourceId = sourceIdField.value; + const rawExchange = exchangeField.value; + const exchangeEntry = + rawExchange !== null ? context.exchangeLookup.get('qm', rawExchange) : undefined; + + const normalizedCountry = + countryField.value !== null ? normalizeCountryIso2(countryField.value) : null; + + if (context.allowedCountries !== null) { + if (countryField.value !== null) { + if (normalizedCountry === null || !context.allowedCountries.has(normalizedCountry)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } else if (exchangeEntry?.countryIso !== undefined && exchangeEntry.countryIso !== null) { + if (!context.allowedCountries.has(exchangeEntry.countryIso)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } + } + + if (exchangeEntry?.role === 'excluded_fund') { + return { ok: false, skipReason: 'excludedMutualFund' }; + } + + if (rawExchange === null || exchangeEntry === undefined) { + return { ok: false, skipReason: 'unmappedExchange' }; + } + + const parsedTicker = parseTickerDetailed(symbolField.value, 'qm'); + const ticker = parsedTicker.ok + ? formatCanonicalTicker(parsedTicker.tickerRoot, parsedTicker.classSuffix) + : symbolField.value; + + const effectiveCountry = normalizedCountry ?? exchangeEntry.countryIso; + const currency = + currencyField.value !== null + ? currencyField.value.toUpperCase() + : exchangeEntry.mic !== null + ? context.micCurrencyMap.get(exchangeEntry.mic) ?? countryFallbackCurrency(effectiveCountry) + : countryFallbackCurrency(effectiveCountry); + + const span = toSpanDateRange(context.barSpans?.get('qm', sourceId)); + + return { + ok: true, + tickerSource: { + source: 'qm', + sourceId, + ticker, + mic: exchangeEntry.mic, + role: exchangeEntry.role, + currency, + span, + }, + }; +} + +/** + * Pure adapter converting a raw `ceoSymbols` document into a Stage B ticker-source input. + * Maps `TSX`/`CDX`/`CNQ`/`AQL` through `exchangeLookup` and parses embedded `.TO`/`.V` suffixes. + */ +export function adaptCeoSymbolDoc( + doc: unknown, + context: AdaptCeoSymbolContext +): AdaptTickerSourceResult { + if (!isPlainRecord(doc)) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + const sourceIdField = readOptionalString(doc, 'ceoId'); + const symbolField = readOptionalString(doc, 'symbol'); + const exchangeField = readFirstOptionalString(doc, ['exchange', 'exchangeCode']); + const countryField = readFirstOptionalString(doc, ['countryCode', 'country']); + const currencyField = readOptionalString(doc, 'currency'); + + const rawLastSeen = doc.lastSeen; + const lastSeenTypeValid = + rawLastSeen === undefined || + rawLastSeen === null || + typeof rawLastSeen === 'string' || + rawLastSeen instanceof Date; + + if ( + !sourceIdField.ok || + !symbolField.ok || + !exchangeField.ok || + !countryField.ok || + !currencyField.ok || + !lastSeenTypeValid + ) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + if (sourceIdField.value === null) { + return { ok: false, skipReason: 'missingId' }; + } + + const sourceId = sourceIdField.value; + const rawExchange = exchangeField.value; + const exchangeEntry = + rawExchange !== null ? context.exchangeLookup.get('ceo', rawExchange) : undefined; + + const normalizedCountry = + countryField.value !== null ? normalizeCountryIso2(countryField.value) : null; + + if (context.allowedCountries !== null) { + if (countryField.value !== null) { + if (normalizedCountry === null || !context.allowedCountries.has(normalizedCountry)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } else if (exchangeEntry?.countryIso !== undefined && exchangeEntry.countryIso !== null) { + if (!context.allowedCountries.has(exchangeEntry.countryIso)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } + } + + if (exchangeEntry?.role === 'excluded_fund') { + return { ok: false, skipReason: 'excludedMutualFund' }; + } + + if (rawExchange === null || exchangeEntry === undefined) { + return { ok: false, skipReason: 'unmappedExchange' }; + } + + const parsedTicker = parseTickerDetailed(symbolField.value, 'ceo'); + const ticker = parsedTicker.ok + ? formatStageBSafeCeoTicker(parsedTicker.tickerRoot, parsedTicker.classSuffix) + : symbolField.value; + + const currency = + currencyField.value !== null + ? currencyField.value.toUpperCase() + : exchangeEntry.mic !== null + ? context.micCurrencyMap.get(exchangeEntry.mic) ?? 'CAD' + : 'CAD'; + + let span = toSpanDateRange(context.ceoSpans?.get(sourceId)); + if (span === null && rawLastSeen !== undefined && rawLastSeen !== null) { + const lastSeenDate = normalizeBarDate(rawLastSeen); + if (lastSeenDate !== null) { + span = { firstBarDate: lastSeenDate, lastBarDate: lastSeenDate }; + } + } + + return { + ok: true, + tickerSource: { + source: 'ceo', + sourceId, + ticker, + mic: exchangeEntry.mic, + role: exchangeEntry.role, + currency, + span, + }, + }; +} + +/** + * Pure adapter converting a raw `eodSymbolChange` document into a validated + * Stage B symbol-change input that will never throw in `matchListingsStageB`. + */ +export function adaptEodSymbolChangeDoc( + doc: unknown, + context: AdaptEodSymbolChangeContext +): AdaptEodSymbolChangeResult { + if (!isPlainRecord(doc)) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + const oldSymbolField = readOptionalString(doc, 'oldSymbol'); + const newSymbolField = readOptionalString(doc, 'newSymbol'); + const exchangeField = readOptionalString(doc, 'exchange'); + const eodExchangeField = readOptionalString(doc, 'eodExchange'); + const eodSearchCodeField = readOptionalString(doc, 'eodSearchCode'); + const countryField = readFirstOptionalString(doc, ['country', 'Country']); + + const rawDate = doc.effectiveDate !== undefined ? doc.effectiveDate : doc.date; + const dateTypeValid = + rawDate === undefined || + rawDate === null || + typeof rawDate === 'string' || + rawDate instanceof Date; + + const rawValidFrom = doc.validFrom; + const validFromTypeValid = + rawValidFrom === undefined || + rawValidFrom === null || + typeof rawValidFrom === 'string' || + rawValidFrom instanceof Date; + + if ( + !oldSymbolField.ok || + !newSymbolField.ok || + !exchangeField.ok || + !eodExchangeField.ok || + !eodSearchCodeField.ok || + !countryField.ok || + !dateTypeValid || + !validFromTypeValid + ) { + return { ok: false, skipReason: 'invalidFieldType' }; + } + + if ( + oldSymbolField.value === null || + newSymbolField.value === null || + exchangeField.value === null + ) { + return { ok: false, skipReason: 'missingId' }; + } + + const exchange = exchangeField.value; + const exchangeEntry = context.exchangeLookup.get('eod', exchange); + + if (context.allowedCountries !== null) { + if (countryField.value !== null) { + const normalizedCountry = normalizeCountryIso2(countryField.value); + if (normalizedCountry === null || !context.allowedCountries.has(normalizedCountry)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } else if (exchangeEntry?.countryIso !== undefined && exchangeEntry.countryIso !== null) { + if (!context.allowedCountries.has(exchangeEntry.countryIso)) { + return { ok: false, skipReason: 'outOfScopeCountry' }; + } + } + } + + if (exchange.toUpperCase() === 'NMFQS' || exchangeEntry?.role === 'excluded_fund') { + return { ok: false, skipReason: 'excludedMutualFund' }; + } + + if (exchangeEntry === undefined) { + return { ok: false, skipReason: 'unmappedExchange' }; + } + + const parsedOld = parseTickerDetailed(oldSymbolField.value, 'eod'); + if (!parsedOld.ok || parsedOld.tickerRoot.length > MAX_TICKER_ROOT_LENGTH) { + return { ok: false, skipReason: 'invalidIdentifier' }; + } + + const effectiveDate = normalizeBarDate(rawDate); + if (effectiveDate === null || effectiveDate <= '0001-01-01') { + return { ok: false, skipReason: 'invalidIdentifier' }; + } + + let validFrom: string | null = null; + if (rawValidFrom !== undefined && rawValidFrom !== null) { + const normalizedValidFrom = normalizeBarDate(rawValidFrom); + if (normalizedValidFrom === null || normalizedValidFrom >= effectiveDate) { + return { ok: false, skipReason: 'invalidIdentifier' }; + } + validFrom = normalizedValidFrom; + } + + const eodSourceId = + eodSearchCodeField.value ?? + `${newSymbolField.value}.${ + eodExchangeField.value ?? (exchangeEntry.countryIso === 'US' ? 'US' : exchange) + }`; + + const symbolChange: StageBSymbolChangeInput = + validFrom !== null + ? { + eodSourceId, + oldTicker: formatCanonicalTicker(parsedOld.tickerRoot, parsedOld.classSuffix), + effectiveDate, + validFrom, + } + : { + eodSourceId, + oldTicker: formatCanonicalTicker(parsedOld.tickerRoot, parsedOld.classSuffix), + effectiveDate, + }; + + return { ok: true, symbolChange }; +} + +/** Streams and adapts `eodSymbols` from a read-only MongoDB reader. */ +export async function readEodSymbols( + reader: ReadOnlySourceSymbolReader, + options: ReadSourceCollectionOptions +): Promise { + const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries); + const micCurrencyMap = buildMicCurrencyMap(options.knownExchanges); + const context: AdaptEodSymbolContext = { + exchangeLookup: options.exchangeLookup, + barSpans: options.barSpans, + allowedCountries, + micCurrencyMap, + }; + + const stageARecords: StageASourceRecord[] = []; + const eodListings: StageBEodListingInput[] = []; + const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.eod); + + const findOptions: SourceSymbolFindOptions = { + projection: { ...EOD_SYMBOLS_PROJECTION }, + ...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}), + }; + + await streamCollection( + reader, + SOURCE_SYMBOL_COLLECTIONS.eod, + buildEodCountryFilter(countryList), + findOptions, + doc => { + stats.docsRead += 1; + const adapted = adaptEodSymbolDoc(doc, context); + if (!adapted.ok) { + stats.skips[adapted.skipReason] += 1; + return; + } + stageARecords.push(adapted.stageARecord); + eodListings.push(adapted.eodListing); + stats.emitted += 1; + stats.invalidIdentifiersNulled += adapted.invalidIdentifiersNulled; + } + ); + + stageARecords.sort(compareStageARecords); + eodListings.sort(compareEodListings); + + return { stageARecords, eodListings, stats }; +} + +/** Streams and adapts `ibSymbols` from a read-only MongoDB reader. */ +export async function readIbSymbols( + reader: ReadOnlySourceSymbolReader, + options: ReadSourceCollectionOptions +): Promise { + const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries); + const context: AdaptIbSymbolContext = { + exchangeLookup: options.exchangeLookup, + allowedCountries, + }; + + const stageARecords: StageASourceRecord[] = []; + const ibContracts: StageBIbContractInput[] = []; + const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.ib); + + const findOptions: SourceSymbolFindOptions = { + projection: { ...IB_SYMBOLS_PROJECTION }, + ...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}), + }; + + await streamCollection( + reader, + SOURCE_SYMBOL_COLLECTIONS.ib, + buildIbCountryFilter(countryList), + findOptions, + doc => { + stats.docsRead += 1; + const adapted = adaptIbSymbolDoc(doc, context); + if (!adapted.ok) { + stats.skips[adapted.skipReason] += 1; + return; + } + stageARecords.push(adapted.stageARecord); + ibContracts.push(adapted.ibContract); + stats.emitted += 1; + stats.invalidIdentifiersNulled += adapted.invalidIdentifiersNulled; + } + ); + + stageARecords.sort(compareStageARecords); + ibContracts.sort(compareIbContracts); + + return { stageARecords, ibContracts, stats }; +} + +/** Streams and adapts `qmSymbols` from a read-only MongoDB reader. */ +export async function readQmSymbols( + reader: ReadOnlySourceSymbolReader, + options: ReadSourceCollectionOptions +): Promise { + const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries); + const micCurrencyMap = buildMicCurrencyMap(options.knownExchanges); + const context: AdaptQmSymbolContext = { + exchangeLookup: options.exchangeLookup, + barSpans: options.barSpans, + allowedCountries, + micCurrencyMap, + }; + + const tickerSources: StageBTickerSourceInput[] = []; + const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.qm); + + const findOptions: SourceSymbolFindOptions = { + projection: { ...QM_SYMBOLS_PROJECTION }, + ...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}), + }; + + await streamCollection( + reader, + SOURCE_SYMBOL_COLLECTIONS.qm, + buildQmCountryFilter(countryList), + findOptions, + doc => { + stats.docsRead += 1; + const adapted = adaptQmSymbolDoc(doc, context); + if (!adapted.ok) { + stats.skips[adapted.skipReason] += 1; + return; + } + tickerSources.push(adapted.tickerSource); + stats.emitted += 1; + } + ); + + tickerSources.sort(compareTickerSources); + + return { tickerSources, stats }; +} + +/** Streams and adapts `ceoSymbols` from a read-only MongoDB reader. */ +export async function readCeoSymbols( + reader: ReadOnlySourceSymbolReader, + options: ReadSourceCollectionOptions +): Promise { + const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries); + const micCurrencyMap = buildMicCurrencyMap(options.knownExchanges); + const context: AdaptCeoSymbolContext = { + exchangeLookup: options.exchangeLookup, + ceoSpans: options.ceoSpans, + allowedCountries, + micCurrencyMap, + }; + + const tickerSources: StageBTickerSourceInput[] = []; + const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.ceo); + + const findOptions: SourceSymbolFindOptions = { + projection: { ...CEO_SYMBOLS_PROJECTION }, + ...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}), + }; + + await streamCollection( + reader, + SOURCE_SYMBOL_COLLECTIONS.ceo, + buildCeoCountryFilter(options.exchangeLookup, countryList), + findOptions, + doc => { + stats.docsRead += 1; + const adapted = adaptCeoSymbolDoc(doc, context); + if (!adapted.ok) { + stats.skips[adapted.skipReason] += 1; + return; + } + tickerSources.push(adapted.tickerSource); + stats.emitted += 1; + } + ); + + tickerSources.sort(compareTickerSources); + + return { tickerSources, stats }; +} + +/** Streams and adapts `eodSymbolChange` from a read-only MongoDB reader. */ +export async function readEodSymbolChanges( + reader: ReadOnlySourceSymbolReader, + options: ReadSourceCollectionOptions +): Promise { + const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries); + const context: AdaptEodSymbolChangeContext = { + exchangeLookup: options.exchangeLookup, + allowedCountries, + }; + + const symbolChanges: StageBSymbolChangeInput[] = []; + const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.eodSymbolChange); + + const findOptions: SourceSymbolFindOptions = { + projection: { ...EOD_SYMBOL_CHANGE_PROJECTION }, + ...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}), + }; + + await streamCollection( + reader, + SOURCE_SYMBOL_COLLECTIONS.eodSymbolChange, + buildEodSymbolChangeFilter(options.exchangeLookup, countryList), + findOptions, + doc => { + stats.docsRead += 1; + const adapted = adaptEodSymbolChangeDoc(doc, context); + if (!adapted.ok) { + stats.skips[adapted.skipReason] += 1; + return; + } + symbolChanges.push(adapted.symbolChange); + stats.emitted += 1; + } + ); + + symbolChanges.sort(compareSymbolChanges); + + return { symbolChanges, stats }; +} + +/** + * Aggregate read-only entry point reading `eodSymbols`, `ibSymbols`, `qmSymbols`, + * `ceoSymbols`, and `eodSymbolChange` into deterministic Stage A and Stage B inputs. + */ +export async function readSecurityMasterSources( + reader: ReadOnlySourceSymbolReader, + options: ReadSecurityMasterSourcesOptions +): Promise { + assertReadOnlyReader(reader); + + const eodResult = await readEodSymbols(reader, options); + const ibResult = await readIbSymbols(reader, options); + const qmResult = await readQmSymbols(reader, options); + const ceoResult = await readCeoSymbols(reader, options); + const symbolChangeResult = await readEodSymbolChanges(reader, options); + + const stageARecords: StageASourceRecord[] = [ + ...eodResult.stageARecords, + ...ibResult.stageARecords, + ]; + stageARecords.sort(compareStageARecords); + + const tickerSources: StageBTickerSourceInput[] = [ + ...qmResult.tickerSources, + ...ceoResult.tickerSources, + ]; + tickerSources.sort(compareTickerSources); + + return { + stageARecords, + stageBInput: { + eodListings: eodResult.eodListings, + ibContracts: ibResult.ibContracts, + tickerSources, + symbolChanges: symbolChangeResult.symbolChanges, + }, + stats: { + eodSymbols: eodResult.stats, + ibSymbols: ibResult.stats, + qmSymbols: qmResult.stats, + ceoSymbols: ceoResult.stats, + eodSymbolChange: symbolChangeResult.stats, + }, + }; +} diff --git a/test/unit/security-master-source-symbol-readers.test.ts b/test/unit/security-master-source-symbol-readers.test.ts new file mode 100644 index 00000000..b647c836 --- /dev/null +++ b/test/unit/security-master-source-symbol-readers.test.ts @@ -0,0 +1,906 @@ +import { describe, expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import type { MongoDBClient } from '@stock-bot/mongodb'; +import { BarSpanIndex } from '../../apps/stock/data-pipeline/src/normalization/bar-spans'; +import { parseTickerDetailed } from '../../apps/stock/data-pipeline/src/normalization/ticker'; +import { + CEO_SYMBOLS_PROJECTION, + compareAscii, + createExchangeSourceLookup, + DEFAULT_SOURCE_COUNTRIES, + EOD_SYMBOL_CHANGE_PROJECTION, + EOD_SYMBOLS_PROJECTION, + IB_SYMBOLS_PROJECTION, + matchInstrumentsStageA, + matchListingsStageB, + normalizeCountryIso2, + QM_SYMBOLS_PROJECTION, + readCeoSymbols, + readEodSymbolChanges, + readEodSymbols, + readIbSymbols, + readQmSymbols, + readSecurityMasterSources, + SOURCE_SYMBOL_COLLECTIONS, + type ExchangeSourceMapRow, + type MongoDBClientSourceSymbolReaderCheck, + type ReadOnlySourceSymbolReader, + type SourceCollectionReadStats, + type SourceSymbolFindOptions, +} from '../../apps/stock/data-pipeline/src/security-master'; + +// Compile-time read-only contract proofs (erased at runtime, verified by `bun run typecheck`). +type AssertExact = [A] extends [B] ? ([B] extends [A] ? true : never) : never; +const _exactReaderKeysCheck: AssertExact = + true; +const _mongoClientAssignableCheck: MongoDBClientSourceSymbolReaderCheck = true; +type AssertMongoAssignable = MongoDBClient extends ReadOnlySourceSymbolReader ? true : never; +const _mongoClientStructuralCheck: AssertMongoAssignable = true; + +interface RecordedFindCall { + collectionName: string; + filter: Record | undefined; + options: SourceSymbolFindOptions | undefined; +} + +interface FakeReaderOptions { + readOnly?: boolean; + asyncIterable?: boolean; + failOnCollection?: { + collection: string; + afterDocs?: number; + errorMessage?: string; + }; +} + +class FakeSourceSymbolReader implements ReadOnlySourceSymbolReader { + public readonly calls: RecordedFindCall[] = []; + private readonly collections: Readonly[]>>; + private readonly readOnly: boolean; + private readonly asyncIterable: boolean; + private readonly failOnCollection?: FakeReaderOptions['failOnCollection']; + + constructor( + collections: Readonly[]>>, + options: FakeReaderOptions = {} + ) { + this.collections = collections; + this.readOnly = options.readOnly ?? true; + this.asyncIterable = options.asyncIterable ?? false; + this.failOnCollection = options.failOnCollection; + } + + isReadOnly(): boolean { + return this.readOnly; + } + + async find = Record>( + collectionName: string, + filter?: Record, + options?: SourceSymbolFindOptions + ): Promise | AsyncIterable> { + this.calls.push({ collectionName, filter, options }); + + if ( + this.failOnCollection !== undefined && + this.failOnCollection.collection === collectionName && + this.failOnCollection.afterDocs === undefined + ) { + throw new Error(this.failOnCollection.errorMessage ?? 'connection reset by peer'); + } + + const docs = (this.collections[collectionName] ?? []) as readonly T[]; + const failConfig = + this.failOnCollection !== undefined && this.failOnCollection.collection === collectionName + ? this.failOnCollection + : undefined; + + if (this.asyncIterable || failConfig !== undefined) { + return { + async *[Symbol.asyncIterator](): AsyncIterator { + let yielded = 0; + for (const doc of docs) { + if (failConfig?.afterDocs !== undefined && yielded >= failConfig.afterDocs) { + throw new Error(failConfig.errorMessage ?? 'mid-stream cursor error'); + } + yielded += 1; + yield doc; + } + }, + }; + } + + return docs; + } +} + +function createTestExchangeLookup() { + const rows: ExchangeSourceMapRow[] = [ + // EOD US + CA primary venues + { source: 'eod', sourceCode: 'NASDAQ', role: 'primary_venue', mic: 'XNAS', countryIso: 'US', method: 'operating_mic' }, + { source: 'eod', sourceCode: 'NYSE', role: 'primary_venue', mic: 'XNYS', countryIso: 'US', method: 'operating_mic' }, + { source: 'eod', sourceCode: 'NYSE ARCA', role: 'primary_venue', mic: 'ARCX', countryIso: 'US', method: 'operating_mic' }, + { source: 'eod', sourceCode: 'PINK', role: 'primary_venue', mic: 'OTCM', countryIso: 'US', method: 'operating_mic' }, + { source: 'eod', sourceCode: 'TO', role: 'primary_venue', mic: 'XTSE', countryIso: 'CA', method: 'operating_mic' }, + { source: 'eod', sourceCode: 'V', role: 'primary_venue', mic: 'XTSX', countryIso: 'CA', method: 'operating_mic' }, + { source: 'eod', sourceCode: 'CN', role: 'primary_venue', mic: 'XCNQ', countryIso: 'CA', method: 'operating_mic' }, + { source: 'eod', sourceCode: 'NEO', role: 'primary_venue', mic: 'NEOE', countryIso: 'CA', method: 'operating_mic' }, + // IB primary venues (ATS venues AEQLIT/OTCLNKECN/ARCAEDGE come from EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS) + { source: 'ib', sourceCode: 'NYSE', role: 'primary_venue', mic: 'XNYS', countryIso: 'US', method: 'explicit_rule' }, + { source: 'ib', sourceCode: 'NASDAQ', role: 'primary_venue', mic: 'XNAS', countryIso: 'US', method: 'explicit_rule' }, + { source: 'ib', sourceCode: 'TSE', role: 'primary_venue', mic: 'XTSE', countryIso: 'CA', method: 'explicit_rule' }, + { source: 'ib', sourceCode: 'VENTURE', role: 'primary_venue', mic: 'XTSX', countryIso: 'CA', method: 'explicit_rule' }, + // QM US + CA venues + { source: 'qm', sourceCode: 'NSQ', role: 'primary_venue', mic: 'XNAS', countryIso: 'US', method: 'explicit_rule' }, + { source: 'qm', sourceCode: 'NYE', role: 'primary_venue', mic: 'XNYS', countryIso: 'US', method: 'explicit_rule' }, + { source: 'qm', sourceCode: 'TSE', role: 'primary_venue', mic: 'XTSE', countryIso: 'CA', method: 'explicit_rule' }, + { source: 'qm', sourceCode: 'TSX', role: 'primary_venue', mic: 'XTSE', countryIso: 'CA', method: 'explicit_rule' }, + { source: 'qm', sourceCode: 'CNX', role: 'primary_venue', mic: 'XCNQ', countryIso: 'CA', method: 'explicit_rule' }, + { source: 'qm', sourceCode: 'CC', role: 'primary_venue', mic: 'XCNQ', countryIso: 'CA', method: 'explicit_rule' }, + // CEO mappings (TSX/CDX/CNQ/AQL) are seeded automatically from EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS + ]; + return createExchangeSourceLookup(rows); +} + +function sumSkips(stats: SourceCollectionReadStats): number { + return ( + stats.skips.missingId + + stats.skips.invalidFieldType + + stats.skips.invalidIdentifier + + stats.skips.excludedMutualFund + + stats.skips.unmappedExchange + + stats.skips.outOfScopeCountry + ); +} + +function assertStatsConservation(stats: SourceCollectionReadStats): void { + expect(stats.docsRead).toBe(stats.emitted + sumSkips(stats)); +} + +function mulberry32(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function shuffleWithSeed(items: readonly T[], seed: number): T[] { + const copy = items.slice(); + const rand = mulberry32(seed); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rand() * (i + 1)); + const tmp = copy[i]!; + copy[i] = copy[j]!; + copy[j] = tmp; + } + return copy; +} + +describe('security-master source-symbol-readers', () => { + test('read-only proof: interface surface, zero runtime DB/I/O imports, guard, and find-only projections', async () => { + expect(_exactReaderKeysCheck).toBe(true); + expect(_mongoClientAssignableCheck).toBe(true); + expect(_mongoClientStructuralCheck).toBe(true); + + // Static check: source-symbol-readers.ts must not contain runtime DB, fs, or network imports. + const sourcePath = resolve( + import.meta.dir, + '../../apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts' + ); + const sourceText = readFileSync(sourcePath, 'utf8'); + expect(sourceText).toContain("import type { MongoDBClient } from '@stock-bot/mongodb'"); + expect(sourceText).not.toMatch(/^\s*import\s+(?!type\b).*@stock-bot\/mongodb/m); + expect(sourceText).not.toMatch(/from\s+['"](?:node:fs|node:net|node:http|mongodb|pg)['"]/); + + const exchangeLookup = createTestExchangeLookup(); + + // Writable reader must fail before issuing any find() call. + const writableReader = new FakeSourceSymbolReader({}, { readOnly: false }); + await expect(readSecurityMasterSources(writableReader, { exchangeLookup })).rejects.toThrow( + /read-only/i + ); + await expect(readEodSymbols(writableReader, { exchangeLookup })).rejects.toThrow(/read-only/i); + await expect(readIbSymbols(writableReader, { exchangeLookup })).rejects.toThrow(/read-only/i); + await expect(readQmSymbols(writableReader, { exchangeLookup })).rejects.toThrow(/read-only/i); + await expect(readCeoSymbols(writableReader, { exchangeLookup })).rejects.toThrow(/read-only/i); + await expect(readEodSymbolChanges(writableReader, { exchangeLookup })).rejects.toThrow( + /read-only/i + ); + expect(writableReader.calls.length).toBe(0); + + // Read-only reader must record strictly find() calls with _id: 0 projections and pushdown filters. + const readOnlyReader = new FakeSourceSymbolReader({}, { readOnly: true }); + await readSecurityMasterSources(readOnlyReader, { exchangeLookup, batchSize: 2000 }); + + expect(readOnlyReader.calls.map(c => c.collectionName)).toEqual([ + SOURCE_SYMBOL_COLLECTIONS.eod, + SOURCE_SYMBOL_COLLECTIONS.ib, + SOURCE_SYMBOL_COLLECTIONS.qm, + SOURCE_SYMBOL_COLLECTIONS.ceo, + SOURCE_SYMBOL_COLLECTIONS.eodSymbolChange, + ]); + + for (const call of readOnlyReader.calls) { + expect(call.options?.projection?._id).toBe(0); + expect(call.options?.batchSize).toBe(2000); + } + + // Verify qmSymbols projection omits bloated profile/symbolInfo blobs. + expect(QM_SYMBOLS_PROJECTION._id).toBe(0); + expect('profile' in QM_SYMBOLS_PROJECTION).toBe(false); + expect('symbolInfo' in QM_SYMBOLS_PROJECTION).toBe(false); + expect(EOD_SYMBOLS_PROJECTION._id).toBe(0); + expect(IB_SYMBOLS_PROJECTION._id).toBe(0); + expect(CEO_SYMBOLS_PROJECTION._id).toBe(0); + expect(EOD_SYMBOL_CHANGE_PROJECTION._id).toBe(0); + + // Verify default US + CA country pushdown filters. + expect(DEFAULT_SOURCE_COUNTRIES).toEqual(['US', 'CA']); + expect(readOnlyReader.calls[0]?.filter).toEqual({ + Country: { $in: ['CA', 'CAN', 'Canada', 'US', 'USA', 'United States', 'United States of America'] }, + }); + expect(readOnlyReader.calls[1]?.filter).toEqual({ country: { $in: ['CA', 'US'] } }); + expect(readOnlyReader.calls[2]?.filter).toEqual({ countryCode: { $in: ['CA', 'US'] } }); + expect(readOnlyReader.calls[3]?.filter).toEqual({ + exchange: { $in: ['AQL', 'CDX', 'CNQ', 'TSX'] }, + }); + expect(readOnlyReader.calls[4]?.filter).toEqual({ + exchange: { $in: ['CN', 'NASDAQ', 'NEO', 'NMFQS', 'NYSE', 'NYSE ARCA', 'PINK', 'TO', 'US', 'V'] }, + }); + + // When countries: null, filters must be empty {}. + const unfilteredReader = new FakeSourceSymbolReader({}, { readOnly: true }); + await readSecurityMasterSources(unfilteredReader, { exchangeLookup, countries: null }); + for (const call of unfilteredReader.calls) { + expect(call.filter).toEqual({}); + } + }); + + test('happy path: US, CA domestic, CA interlisted (SHOP), and symbol change resolve unchanged through Stage A and Stage B', async () => { + const exchangeLookup = createTestExchangeLookup(); + const barSpans = new BarSpanIndex(); + barSpans.merge({ source: 'eod', sourceId: 'AAPL.US', firstBarDate: '2000-01-03', lastBarDate: '2025-06-30', barCount: 6400 }); + barSpans.merge({ source: 'eod', sourceId: 'RY.TO', firstBarDate: '2000-01-03', lastBarDate: '2025-06-30', barCount: 6400 }); + barSpans.merge({ source: 'eod', sourceId: 'SHOP.TO', firstBarDate: '2015-05-21', lastBarDate: '2025-06-30', barCount: 2540 }); + barSpans.merge({ source: 'eod', sourceId: 'SHOP.US', firstBarDate: '2015-05-21', lastBarDate: '2025-06-30', barCount: 2540 }); + barSpans.merge({ source: 'eod', sourceId: 'META.US', firstBarDate: '2012-05-18', lastBarDate: '2025-06-30', barCount: 3300 }); + barSpans.merge({ source: 'qm', sourceId: 'AAPL:US', firstBarDate: '2010-01-04', lastBarDate: '2025-06-30', barCount: 3900 }); + barSpans.merge({ source: 'qm', sourceId: 'RY:CA', firstBarDate: '2010-01-04', lastBarDate: '2025-06-30', barCount: 3900 }); + barSpans.merge({ source: 'qm', sourceId: 'SHOP:CA', firstBarDate: '2015-05-21', lastBarDate: '2025-06-30', barCount: 2540 }); + barSpans.merge({ source: 'qm', sourceId: 'SHOP:US', firstBarDate: '2015-05-21', lastBarDate: '2025-06-30', barCount: 2540 }); + barSpans.merge({ source: 'qm', sourceId: 'FB:US', firstBarDate: '2015-01-02', lastBarDate: '2022-06-08', barCount: 1870 }); + + const reader = new FakeSourceSymbolReader( + { + eodSymbols: [ + { + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + eodExchange: 'US', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Cusip: '037833100', + Name: 'Apple Inc.', + }, + { + eodSearchCode: 'RY.TO', + Code: 'RY', + eodExchange: 'TO', + Exchange: 'TO', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA7800871021', + Cusip: '780087102', + Name: 'Royal Bank of Canada', + }, + { + eodSearchCode: 'SHOP.TO', + Code: 'SHOP', + eodExchange: 'TO', + Exchange: 'TO', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA82509L1076', + Cusip: '82509L107', + Name: 'Shopify Inc.', + }, + // CA interlisted share on NYSE: listing Country='USA' differs from issuer country 'CA'. + { + eodSearchCode: 'SHOP.US', + Code: 'SHOP', + eodExchange: 'US', + Exchange: 'NYSE', + Country: 'USA', + Currency: 'USD', + Isin: 'CA82509L1076', + Cusip: '82509L107', + Name: 'Shopify Inc.', + }, + { + eodSearchCode: 'META.US', + Code: 'META', + eodExchange: 'US', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US30303M1027', + Cusip: '30303M102', + Name: 'Meta Platforms Inc.', + }, + ], + ibSymbols: [ + { + conid: 265598, + symbol: 'AAPL', + exchangeId: 'ARCAEDGE', + country: 'US', + currency: 'USD', + isin: 'US0378331005', + cusip: '037833100', + description: 'APPLE INC', + }, + { + conid: 4001, + symbol: 'RY', + exchangeId: 'AEQLIT', + country: 'CA', + currency: 'CAD', + isin: 'CA7800871021', + cusip: '780087102', + description: 'ROYAL BANK OF CANADA', + }, + { + conid: 199100, + symbol: 'SHOP', + exchangeId: 'AEQLIT', + country: 'CA', + currency: 'CAD', + isin: 'CA82509L1076', + cusip: '82509L107', + description: 'SHOPIFY INC - CLASS A', + }, + { + conid: 199101, + symbol: 'SHOP', + exchangeId: 'OTCLNKECN', + country: 'US', + currency: 'USD', + isin: 'CA82509L1076', + cusip: '82509L107', + description: 'SHOPIFY INC - CLASS A', + }, + ], + qmSymbols: [ + { qmSearchCode: 'AAPL:US', symbol: 'AAPL', exchange: 'NSQ', countryCode: 'US', active: true }, + { qmSearchCode: 'RY:CA', symbol: 'RY', exchange: 'TSE', countryCode: 'CA', active: true }, + { qmSearchCode: 'SHOP:CA', symbol: 'SHOP', exchange: 'TSE', countryCode: 'CA', active: true }, + { qmSearchCode: 'SHOP:US', symbol: 'SHOP', exchange: 'NYE', countryCode: 'US', active: true }, + { qmSearchCode: 'FB:US', symbol: 'FB', exchange: 'NSQ', countryCode: 'US', active: false }, + ], + ceoSymbols: [ + { ceoId: 'RY', symbol: 'RY.TO', exchange: 'TSX', name: 'Royal Bank', lastSeen: '2025-03-15' }, + { ceoId: 'SHOP', symbol: 'SHOP.TO', exchange: 'TSX', name: 'Shopify', lastSeen: '2025-03-15' }, + ], + eodSymbolChange: [ + { + oldSymbol: 'FB', + newSymbol: 'META', + exchange: 'NASDAQ', + date: '2022-06-09', + }, + ], + }, + { readOnly: true, asyncIterable: true } + ); + + const sources = await readSecurityMasterSources(reader, { exchangeLookup, barSpans }); + + assertStatsConservation(sources.stats.eodSymbols); + assertStatsConservation(sources.stats.ibSymbols); + assertStatsConservation(sources.stats.qmSymbols); + assertStatsConservation(sources.stats.ceoSymbols); + assertStatsConservation(sources.stats.eodSymbolChange); + + // T-55: SHOP.US Stage A record carries issuer country 'CA', not listing country 'US'. + const shopUsStageA = sources.stageARecords.find( + r => r.source === 'eod' && r.sourceId === 'SHOP.US' + ); + expect(shopUsStageA?.country).toBe('CA'); + + // Feed output unchanged into Stage A and Stage B. + const stageA = matchInstrumentsStageA(sources.stageARecords); + expect(stageA.conflicts).toEqual([]); + expect(stageA.unresolved).toEqual([]); + expect(stageA.instruments.length).toBe(4); // AAPL, RY, SHOP, META + + const shopInstrument = stageA.instruments.find(i => i.primaryIsin === 'CA82509L1076'); + expect(shopInstrument?.issuerCountry).toBe('CA'); + expect(shopInstrument?.members.length).toBe(4); // EOD SHOP.TO, EOD SHOP.US, IB 199100, IB 199101 + + const stageB = matchListingsStageB({ + instruments: stageA.instruments, + ...sources.stageBInput, + }); + expect(stageB.conflicts).toEqual([]); + expect(stageB.unresolved).toEqual([]); + expect(stageB.listings.length).toBe(5); // AAPL XNAS, RY XTSE, SHOP XTSE CAD, SHOP XNYS USD, META XNAS + + // Interlisted SHOP listings get distinct CAD and USD IB conids. + const shopCadListing = stageB.listings.find( + l => l.primaryIsin === 'CA82509L1076' && l.mic === 'XTSE' && l.currency === 'CAD' + ); + const shopUsdListing = stageB.listings.find( + l => l.primaryIsin === 'CA82509L1076' && l.mic === 'XNYS' && l.currency === 'USD' + ); + expect(shopCadListing?.ibConid).toBe(199100); + expect(shopCadListing?.ibPrimaryExchange).toBeNull(); // AEQLIT ATS never used as primaryExchange + expect(shopUsdListing?.ibConid).toBe(199101); + expect(shopUsdListing?.ibPrimaryExchange).toBeNull(); // OTCLNKECN ATS never used as primaryExchange + + // Historical FB:US QM record resolved to META listing via eodSymbolChange alias. + const fbMapping = stageB.providerMappings.find( + m => m.source === 'qm' && m.sourceId === 'FB:US' + ); + expect(fbMapping?.listingKey.primaryIsin).toBe('US30303M1027'); + expect(fbMapping?.listingKey.tickerRoot).toBe('META'); + + // CEO mappings resolved to XTSE listings. + const ceoShopMapping = stageB.providerMappings.find( + m => m.source === 'ceo' && m.sourceId === 'SHOP' + ); + expect(ceoShopMapping?.listingKey.mic).toBe('XTSE'); + expect(ceoShopMapping?.listingKey.tickerRoot).toBe('SHOP'); + }); + + test('edge cases: NMFQS exclusion, delisted preservation, IB ATS handling, CEO .TO/.V & double-strip guard, QM duplicates, invalid ISIN/CUSIP recovery', async () => { + const exchangeLookup = createTestExchangeLookup(); + const barSpans = new BarSpanIndex(); + barSpans.merge({ source: 'qm', sourceId: 'VOY:CNX', firstBarDate: '2022-01-03', lastBarDate: '2025-01-03', barCount: 750 }); + barSpans.merge({ source: 'qm', sourceId: 'VOY:CC', firstBarDate: '2020-01-03', lastBarDate: '2021-12-31', barCount: 500 }); + + const reader = new FakeSourceSymbolReader({ + eodSymbols: [ + // NMFQS mutual fund must be excluded and counted + { + eodSearchCode: 'VFIAX.US', + Code: 'VFIAX', + eodExchange: 'US', + Exchange: 'NMFQS', + Country: 'USA', + Currency: 'USD', + Isin: 'US9229087104', + Name: 'Vanguard 500 Index Fund', + }, + // Delisted EOD symbol must be preserved + { + eodSearchCode: 'OLDCO.US', + Code: 'OLDCO', + eodExchange: 'US', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'CA52886N1024', // invalid check digit -> nulled, not thrown + Name: 'Old Co Inc.', + delisted: true, + }, + ], + ibSymbols: [ + // IB ATS venue AEQLIT + invalid ISIN CA8131391062 + valid CUSIP 813137106 -> recovers via Stage A tier2_cusip + { + conid: 777001, + symbol: 'SCU.UN', + exchangeId: 'AEQLIT', + country: 'CA', + currency: 'CAD', + isin: 'CA8131391062', + cusip: '813137106', + description: 'SECOND CUP INCOME FUND', + }, + // IB placeholder ISIN CATSETEST001 (invalid ISIN, invalid CUSIP) -> both nulled and counted + { + conid: 777002, + symbol: 'TEST', + exchangeId: 'OTCLNKECN', + country: 'CA', + currency: 'CAD', + isin: 'CATSETEST001', + cusip: 'BAD000000', + description: 'TEST PLACEHOLDER', + }, + // IB primary_venue exchangeId is preserved as primaryExchange + { + conid: 777003, + symbol: 'IBM', + exchangeId: 'NYSE', + country: 'US', + currency: 'USD', + isin: 'US4592001014', + cusip: '459200101', + description: 'IBM CORP', + }, + ], + qmSymbols: [ + // Duplicate (symbol, exchange-mic) pair on CSE: both active VOY:CNX and inactive VOY:CC must survive + { qmSearchCode: 'VOY:CNX', symbol: 'VOY', exchange: 'CNX', countryCode: 'CA', active: true }, + { qmSearchCode: 'VOY:CC', symbol: 'VOY', exchange: 'CC', countryCode: 'CA', active: false }, + ], + ceoSymbols: [ + { ceoId: 'BIP.UN', symbol: 'BIP.UN.TO', exchange: 'TSX', name: 'Brookfield Infra', lastSeen: '2025-05-01' }, + { ceoId: 'A.V', symbol: 'A.V', exchange: 'CDX', name: 'Armor Minerals', lastSeen: '2025-05-01' }, + { ceoId: 'VOY', symbol: 'VOY', exchange: 'CNQ', name: 'Voyager', lastSeen: '2025-05-01' }, + { ceoId: 'NEO1', symbol: 'NEO1', exchange: 'AQL', name: 'Neo Issuer', lastSeen: '2025-05-01' }, + // Double-strip guard: class suffix itself is 'V' with '.V' venue suffix + { ceoId: 'ABC.V', symbol: 'ABC.V.V', exchange: 'CDX', name: 'ABC Class V', lastSeen: '2025-05-01' }, + ], + eodSymbolChange: [], + }); + + const result = await readSecurityMasterSources(reader, { exchangeLookup, barSpans }); + + // NMFQS excluded from both Stage A and Stage B + expect(result.stats.eodSymbols.skips.excludedMutualFund).toBe(1); + expect(result.stats.eodSymbols.emitted).toBe(1); + expect(result.stats.eodSymbols.invalidIdentifiersNulled).toBe(1); + expect(result.stageARecords.some(r => r.sourceId === 'VFIAX.US')).toBe(false); + expect(result.stageBInput.eodListings.some(l => l.sourceId === 'VFIAX.US')).toBe(false); + + // Delisted EOD doc preserved with nulled invalid ISIN + const oldCo = result.stageARecords.find(r => r.source === 'eod' && r.sourceId === 'OLDCO.US'); + expect(oldCo).toBeDefined(); + expect(oldCo?.isin).toBeNull(); + expect(oldCo?.country).toBeNull(); + + // IB ATS handling & invalid ISIN/CUSIP counting + CUSIP recovery in Stage A + expect(result.stats.ibSymbols.emitted).toBe(3); + expect(result.stats.ibSymbols.invalidIdentifiersNulled).toBe(3); // 1 on 777001 + 2 on 777002 + + const ibAts = result.stageBInput.ibContracts.find(c => c.sourceId === '777001'); + expect(ibAts?.primaryExchange).toBeNull(); + const ibOtc = result.stageBInput.ibContracts.find(c => c.sourceId === '777002'); + expect(ibOtc?.primaryExchange).toBeNull(); + const ibNyse = result.stageBInput.ibContracts.find(c => c.sourceId === '777003'); + expect(ibNyse?.primaryExchange).toBe('NYSE'); + + // Stage A recovers 777001 via tier2_cusip (valid CUSIP 813139106 + CA prefix from invalid ISIN) + const stageA = matchInstrumentsStageA(result.stageARecords); + const scuMember = stageA.instruments + .flatMap(i => i.members) + .find(m => m.source === 'ib' && m.sourceId === '777001'); + expect(scuMember?.method).toBe('tier2_cusip'); + + // Duplicate QM (symbol, exchange) pairs both survive with MIC-inferred CAD currency + const qmSources = result.stageBInput.tickerSources.filter(t => t.source === 'qm'); + expect(qmSources.map(q => q.sourceId)).toEqual(['VOY:CC', 'VOY:CNX']); + expect(qmSources[0]?.currency).toBe('CAD'); + expect(qmSources[1]?.currency).toBe('CAD'); + expect(qmSources[0]?.mic).toBe('XCNQ'); + expect(qmSources[1]?.mic).toBe('XCNQ'); + + // CEO exchange mappings TSX/CDX/CNQ/AQL -> XTSE/XTSX/XCNQ/NEOE + .TO/.V parsing + double-strip guard + const ceoById = new Map( + result.stageBInput.tickerSources.filter(t => t.source === 'ceo').map(t => [t.sourceId, t]) + ); + expect(ceoById.get('BIP.UN')).toMatchObject({ mic: 'XTSE', ticker: 'BIP.UN', currency: 'CAD' }); + expect(ceoById.get('A.V')).toMatchObject({ mic: 'XTSX', ticker: 'A', currency: 'CAD' }); + expect(ceoById.get('VOY')).toMatchObject({ mic: 'XCNQ', ticker: 'VOY', currency: 'CAD' }); + expect(ceoById.get('NEO1')).toMatchObject({ mic: 'NEOE', ticker: 'NEO1', currency: 'CAD' }); + + const abcV = ceoById.get('ABC.V'); + expect(abcV?.ticker).toBe('ABC-V'); + expect(parseTickerDetailed(abcV?.ticker, 'ceo')).toEqual({ + ok: true, + tickerRoot: 'ABC', + classSuffix: 'V', + }); + + assertStatsConservation(result.stats.eodSymbols); + assertStatsConservation(result.stats.ibSymbols); + assertStatsConservation(result.stats.qmSymbols); + assertStatsConservation(result.stats.ceoSymbols); + assertStatsConservation(result.stats.eodSymbolChange); + }); + + test('failure modes: missing id, unmapped exchange, non-string fields, out-of-scope country, invalid conid/date, and mid-stream collection errors', async () => { + const exchangeLookup = createTestExchangeLookup(); + + const reader = new FakeSourceSymbolReader({ + eodSymbols: [ + { eodSearchCode: ' ', Code: 'X', Exchange: 'NASDAQ', Country: 'USA' }, // missingId + { eodSearchCode: 12345 as unknown as string, Code: 'X', Exchange: 'NASDAQ', Country: 'USA' }, // invalidFieldType + { eodSearchCode: 'SAP.F', Code: 'SAP', Exchange: 'XETRA', Country: 'Germany' }, // outOfScopeCountry + { eodSearchCode: 'UNK.US', Code: 'UNK', Exchange: 'MYSTERY_EX', Country: 'USA' }, // unmappedExchange + { eodSearchCode: 'BADTYPE.US', Code: 999 as unknown as string, Exchange: 'NASDAQ', Country: 'USA' }, // invalidFieldType + { eodSearchCode: 'GOOD.US', Code: 'GOOD', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD' }, // emitted + ], + ibSymbols: [ + { symbol: 'NOID', country: 'US' }, // missingId + { conid: '123' as unknown as number, symbol: 'STR', country: 'US' }, // invalidFieldType + { conid: 0, symbol: 'ZERO', country: 'US' }, // invalidIdentifier + { conid: -42, symbol: 'NEG', country: 'US' }, // invalidIdentifier + { conid: 12.5, symbol: 'FLOAT', country: 'US' }, // invalidIdentifier + { conid: 500, symbol: 'DE', country: 'DE' }, // outOfScopeCountry + { conid: 501, symbol: 123 as unknown as string, country: 'US' }, // invalidFieldType + { conid: 502, symbol: 'OK', country: 'US', currency: 'USD' }, // emitted + ], + qmSymbols: [ + { qmSearchCode: '', symbol: 'A', exchange: 'NSQ', countryCode: 'US' }, // missingId + { qmSearchCode: 'BAD:US', symbol: ['A'] as unknown as string, exchange: 'NSQ', countryCode: 'US' }, // invalidFieldType + { qmSearchCode: 'DE:XET', symbol: 'SAP', exchange: 'XET', countryCode: 'DE' }, // outOfScopeCountry + { qmSearchCode: 'NOEX:US', symbol: 'A', exchange: 'NOEX', countryCode: 'US' }, // unmappedExchange + { qmSearchCode: 'OK:US', symbol: 'OK', exchange: 'NSQ', countryCode: 'US' }, // emitted + ], + ceoSymbols: [ + { ceoId: ' ', symbol: 'A.TO', exchange: 'TSX' }, // missingId + { ceoId: 'BAD', symbol: 'A.TO', exchange: 'TSX', lastSeen: 12345 as unknown as string }, // invalidFieldType + { ceoId: 'UK1', symbol: 'UK1', exchange: 'TSX', countryCode: 'GB' }, // outOfScopeCountry + { ceoId: 'NOEX', symbol: 'NOEX', exchange: 'UNKNOWN' }, // unmappedExchange + { ceoId: 'OK', symbol: 'OK.TO', exchange: 'TSX' }, // emitted + ], + eodSymbolChange: [ + { oldSymbol: '', newSymbol: 'B', exchange: 'NASDAQ', date: '2024-05-01' }, // missingId + { oldSymbol: 123 as unknown as string, newSymbol: 'B', exchange: 'NASDAQ', date: '2024-05-01' }, // invalidFieldType + { oldSymbol: 'A', newSymbol: 'B', exchange: 'XETRA', country: 'Germany', date: '2024-05-01' }, // outOfScopeCountry + { oldSymbol: 'A', newSymbol: 'B', exchange: 'UNKNOWN_EX', date: '2024-05-01' }, // unmappedExchange + { oldSymbol: 'A', newSymbol: 'B', exchange: 'NASDAQ', date: '0001-01-01' }, // invalidIdentifier (<= 0001-01-01) + { oldSymbol: 'A', newSymbol: 'B', exchange: 'NASDAQ', date: 'not-a-date' }, // invalidIdentifier + { oldSymbol: 'A', newSymbol: 'B', exchange: 'NASDAQ', date: '2024-05-01', validFrom: '2024-05-01' }, // invalidIdentifier (validFrom >= effectiveDate) + { oldSymbol: 'A'.repeat(30), newSymbol: 'B', exchange: 'NASDAQ', date: '2024-05-01' }, // invalidIdentifier (root > MAX_TICKER_ROOT_LENGTH) + { oldSymbol: 'OLD', newSymbol: 'NEW', exchange: 'NASDAQ', date: '2024-05-01' }, // emitted + ], + }); + + const result = await readSecurityMasterSources(reader, { exchangeLookup }); + + expect(result.stats.eodSymbols.skips).toEqual({ + missingId: 1, + invalidFieldType: 2, + invalidIdentifier: 0, + excludedMutualFund: 0, + unmappedExchange: 1, + outOfScopeCountry: 1, + }); + expect(result.stats.eodSymbols.emitted).toBe(1); + + expect(result.stats.ibSymbols.skips).toEqual({ + missingId: 1, + invalidFieldType: 2, + invalidIdentifier: 3, + excludedMutualFund: 0, + unmappedExchange: 0, + outOfScopeCountry: 1, + }); + expect(result.stats.ibSymbols.emitted).toBe(1); + + expect(result.stats.qmSymbols.skips).toEqual({ + missingId: 1, + invalidFieldType: 1, + invalidIdentifier: 0, + excludedMutualFund: 0, + unmappedExchange: 1, + outOfScopeCountry: 1, + }); + expect(result.stats.qmSymbols.emitted).toBe(1); + + expect(result.stats.ceoSymbols.skips).toEqual({ + missingId: 1, + invalidFieldType: 1, + invalidIdentifier: 0, + excludedMutualFund: 0, + unmappedExchange: 1, + outOfScopeCountry: 1, + }); + expect(result.stats.ceoSymbols.emitted).toBe(1); + + expect(result.stats.eodSymbolChange.skips).toEqual({ + missingId: 1, + invalidFieldType: 1, + invalidIdentifier: 4, + excludedMutualFund: 0, + unmappedExchange: 1, + outOfScopeCountry: 1, + }); + expect(result.stats.eodSymbolChange.emitted).toBe(1); + + assertStatsConservation(result.stats.eodSymbols); + assertStatsConservation(result.stats.ibSymbols); + assertStatsConservation(result.stats.qmSymbols); + assertStatsConservation(result.stats.ceoSymbols); + assertStatsConservation(result.stats.eodSymbolChange); + + // Mid-stream error on each of the 5 collections must reject with the collection name in the message. + const collectionNames = Object.values(SOURCE_SYMBOL_COLLECTIONS); + for (const collection of collectionNames) { + const failingReader = new FakeSourceSymbolReader( + { + [collection]: [ + { eodSearchCode: 'A.US', conid: 1, qmSearchCode: 'A:US', ceoId: 'A', oldSymbol: 'A', newSymbol: 'B', exchange: 'NASDAQ', date: '2024-05-01' }, + { eodSearchCode: 'B.US', conid: 2, qmSearchCode: 'B:US', ceoId: 'B', oldSymbol: 'C', newSymbol: 'D', exchange: 'NASDAQ', date: '2024-05-02' }, + ], + }, + { + readOnly: true, + failOnCollection: { collection, afterDocs: 1, errorMessage: 'socket hang up' }, + } + ); + + await expect( + readSecurityMasterSources(failingReader, { exchangeLookup }) + ).rejects.toThrow(collection); + } + + // Also verify normalizeCountryIso2 aliases directly. + expect(normalizeCountryIso2('United States of America')).toBe('US'); + expect(normalizeCountryIso2('USA')).toBe('US'); + expect(normalizeCountryIso2('Canada')).toBe('CA'); + expect(normalizeCountryIso2('Germany')).toBe('DE'); + expect(normalizeCountryIso2(' ')).toBeNull(); + }); + + test('determinism: shuffling fake-cursor order across seeds yields byte-identical JSON output sorted by (source, sourceId)', async () => { + const exchangeLookup = createTestExchangeLookup(); + + const baseCollections = { + eodSymbols: [ + { eodSearchCode: 'Z.US', Code: 'Z', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US98954M1018', Name: 'Zillow' }, + { eodSearchCode: 'AAPL.US', Code: 'AAPL', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US0378331005', Name: 'Apple' }, + // Duplicate sourceId with different names to test full tie-breaker determinism + { eodSearchCode: 'DUP.US', Code: 'DUP', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Name: 'Dup B' }, + { eodSearchCode: 'DUP.US', Code: 'DUP', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Name: 'Dup A' }, + { eodSearchCode: 'RY.TO', Code: 'RY', Exchange: 'TO', Country: 'Canada', Currency: 'CAD', Isin: 'CA7800871021', Name: 'RBC' }, + ], + ibSymbols: [ + { conid: 900, symbol: 'Z', exchangeId: 'NASDAQ', country: 'US', currency: 'USD', isin: 'US98954M1018' }, + { conid: 100, symbol: 'AAPL', exchangeId: 'ARCAEDGE', country: 'US', currency: 'USD', isin: 'US0378331005' }, + { conid: 200, symbol: 'RY', exchangeId: 'AEQLIT', country: 'CA', currency: 'CAD', isin: 'CA7800871021' }, + ], + qmSymbols: [ + { qmSearchCode: 'Z:US', symbol: 'Z', exchange: 'NSQ', countryCode: 'US' }, + { qmSearchCode: 'AAPL:US', symbol: 'AAPL', exchange: 'NSQ', countryCode: 'US' }, + { qmSearchCode: 'VOY:CNX', symbol: 'VOY', exchange: 'CNX', countryCode: 'CA' }, + { qmSearchCode: 'VOY:CC', symbol: 'VOY', exchange: 'CC', countryCode: 'CA' }, + ], + ceoSymbols: [ + { ceoId: 'SHOP', symbol: 'SHOP.TO', exchange: 'TSX', lastSeen: '2025-01-01' }, + { ceoId: 'A.V', symbol: 'A.V', exchange: 'CDX', lastSeen: '2025-01-02' }, + { ceoId: 'RY', symbol: 'RY.TO', exchange: 'TSX', lastSeen: '2025-01-03' }, + ], + eodSymbolChange: [ + { oldSymbol: 'FB', newSymbol: 'META', exchange: 'NASDAQ', date: '2022-06-09' }, + { oldSymbol: 'ANTM', newSymbol: 'ELV', exchange: 'NYSE', date: '2022-06-28' }, + ], + }; + + const baseline = await readSecurityMasterSources(new FakeSourceSymbolReader(baseCollections), { + exchangeLookup, + }); + const baselineJson = JSON.stringify(baseline); + + // Verify (source, sourceId) compareAscii sort order. + for (let i = 1; i < baseline.stageARecords.length; i++) { + const prev = baseline.stageARecords[i - 1]!; + const curr = baseline.stageARecords[i]!; + const cmp = compareAscii(prev.source, curr.source) || compareAscii(prev.sourceId, curr.sourceId); + expect(cmp).toBeLessThanOrEqual(0); + } + for (let i = 1; i < baseline.stageBInput.tickerSources.length; i++) { + const prev = baseline.stageBInput.tickerSources[i - 1]!; + const curr = baseline.stageBInput.tickerSources[i]!; + const cmp = compareAscii(prev.source, curr.source) || compareAscii(prev.sourceId, curr.sourceId); + expect(cmp).toBeLessThanOrEqual(0); + } + + for (const seed of [11, 42, 1337, 99999]) { + const shuffled = { + eodSymbols: shuffleWithSeed(baseCollections.eodSymbols, seed), + ibSymbols: shuffleWithSeed(baseCollections.ibSymbols, seed + 1), + qmSymbols: shuffleWithSeed(baseCollections.qmSymbols, seed + 2), + ceoSymbols: shuffleWithSeed(baseCollections.ceoSymbols, seed + 3), + eodSymbolChange: shuffleWithSeed(baseCollections.eodSymbolChange, seed + 4), + }; + const candidate = await readSecurityMasterSources(new FakeSourceSymbolReader(shuffled), { + exchangeLookup, + }); + expect(JSON.stringify(candidate)).toBe(baselineJson); + } + }); + + test('local benchmark: >= 368k synthetic docs (300k eod + 50k qm + 18k ib) sustain >= 25,000 docs/s', async () => { + const EOD_COUNT = 300_000; + const QM_COUNT = 50_000; + const IB_COUNT = 18_000; + const TOTAL_DOCS = EOD_COUNT + QM_COUNT + IB_COUNT; + + const exchangeLookup = createTestExchangeLookup(); + + // Streaming generator fake reader so benchmark measures reader/adapter + sort throughput + // without pre-allocating 368k raw fixture objects in RAM before timing starts. + const benchmarkReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find>(collectionName: string): Iterable { + if (collectionName === SOURCE_SYMBOL_COLLECTIONS.eod) { + return { + *[Symbol.iterator](): Iterator { + for (let i = 0; i < EOD_COUNT; i++) { + const isMutualFund = i % 10 === 0; + const isCa = !isMutualFund && i % 5 === 0; + const doc = { + eodSearchCode: `SYM${i}.${isCa ? 'TO' : 'US'}`, + Code: `SYM${i}`, + eodExchange: isCa ? 'TO' : 'US', + Exchange: isMutualFund ? 'NMFQS' : isCa ? 'TO' : 'NASDAQ', + Country: isCa ? 'Canada' : 'USA', + Currency: isCa ? 'CAD' : 'USD', + Isin: isCa ? 'CA82509L1076' : 'US0378331005', + Name: `Company ${i}`, + }; + yield doc as unknown as T; + } + }, + }; + } + if (collectionName === SOURCE_SYMBOL_COLLECTIONS.qm) { + return { + *[Symbol.iterator](): Iterator { + for (let i = 0; i < QM_COUNT; i++) { + const isCa = i % 4 === 0; + const doc = { + qmSearchCode: `SYM${i}:${isCa ? 'CA' : 'US'}`, + symbol: `SYM${i}`, + exchange: isCa ? 'TSE' : 'NSQ', + countryCode: isCa ? 'CA' : 'US', + active: i % 3 !== 0, + }; + yield doc as unknown as T; + } + }, + }; + } + if (collectionName === SOURCE_SYMBOL_COLLECTIONS.ib) { + return { + *[Symbol.iterator](): Iterator { + for (let i = 0; i < IB_COUNT; i++) { + const isCa = i % 5 === 0; + const doc = { + conid: 100_000 + i, + symbol: `SYM${i}`, + exchangeId: isCa ? 'AEQLIT' : 'ARCAEDGE', + country: isCa ? 'CA' : 'US', + currency: isCa ? 'CAD' : 'USD', + isin: isCa ? 'CA82509L1076' : 'US0378331005', + cusip: isCa ? '82509L107' : '037833100', + description: `IB COMPANY ${i}`, + }; + yield doc as unknown as T; + } + }, + }; + } + return []; + }, + }; + + const started = performance.now(); + const result = await readSecurityMasterSources(benchmarkReader, { exchangeLookup }); + const elapsedMs = performance.now() - started; + const docsPerSec = Math.round(TOTAL_DOCS / (elapsedMs / 1000)); + + process.stdout.write( + `[source-symbol-readers benchmark] ${TOTAL_DOCS} docs (eod=${EOD_COUNT}, qm=${QM_COUNT}, ib=${IB_COUNT}) in ${elapsedMs.toFixed(1)} ms (${docsPerSec.toLocaleString('en-US')} docs/s)\n` + ); + + expect(result.stats.eodSymbols.docsRead).toBe(EOD_COUNT); + expect(result.stats.eodSymbols.skips.excludedMutualFund).toBe(EOD_COUNT / 10); + expect(result.stats.qmSymbols.docsRead).toBe(QM_COUNT); + expect(result.stats.ibSymbols.docsRead).toBe(IB_COUNT); + assertStatsConservation(result.stats.eodSymbols); + assertStatsConservation(result.stats.qmSymbols); + assertStatsConservation(result.stats.ibSymbols); + expect(docsPerSec).toBeGreaterThanOrEqual(25_000); + }); +});