diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index d2e41f6b..767fbddb 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -84,14 +84,14 @@ bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/secu ## 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. +- **Read-only streaming contract:** `ReadOnlySourceSymbolReader` exposes strictly `isReadOnly()` and `find()` returning an incremental `AsyncIterable` (rejecting buffered array results). Production callers adapt a read-only `MongoDBClient` via `createReadOnlyMongoSourceSymbolReader(client)`, which streams through `collection.find(filter, options)` (`FindCursor`, never `cursor.toArray()`), closes cursors in `finally`, projects `_id: 0` (omitting `qmSymbols.profile`/`symbolInfo`, projecting `eodSymbolChange.effective`), and pushes down `$or` country/venue filters preserving normalized spellings and venue fallbacks (default `['US', 'CA']`). +- **Provider & Pass 1 rules enforced:** `createExchangeSourceLookup` layers reviewed US+CA venue mappings (`REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS`) on top of the 17-row Pass 1 baseline (`EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS`) with caller/Pass 1 rows overriding. Readers exclude `eodSymbols` `Exchange="NMFQS"` mutual funds, preserve `delisted: true` and duplicate QM `(symbol, exchange)` pairs (`VOY:CNX` + `VOY:CC`), set Stage A country strictly to issuer country (never listing country), never use IB ATS `exchangeId` venues (`AEQLIT`, `OTCLNKECN`, etc.) as listing MIC or `primaryExchange`, strip CEO `.TO`/`.V` suffixes with Stage B double-strip protection, parse `eodSymbolChange.effective` (alongside `effectiveDate`/`date`), null invalid ISIN/CUSIP check digits without throwing, and reconcile `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):** +- **Recorded baseline (`2026-11-28`, local sandbox, in-memory async cursor 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`). + - Observed throughput: `754,047 docs/s` (`488.0 ms` wall time, floor `>= 25,000 docs/s`). diff --git a/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts b/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts index de857f66..bf0bb590 100644 --- a/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts +++ b/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts @@ -272,6 +272,100 @@ export const EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMapRow[] })) ); +/** + * Reviewed US + Canada provider venue mappings supplementing the immutable + * 17-row Pass 1 baseline seed (`35-security-master-exchange-seed.sql`). + * Covers EOD US sub-exchanges under composite `eodExchange="US"` (`NASDAQ`, + * `NYSE`, `PINK`, etc.), EOD CA venues, IB primary venues, and QuoteMedia + * US/CA venue codes (whose `qmExchanges` collection carries no OperatingMICs), + * sorted by `(source, sourceCode)`. + */ +export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMapRow[] = + Object.freeze( + [ + // EOD US + CA primary venues + { source: 'eod' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'BATS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'CN', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' }, + { source: 'eod' as const, sourceCode: 'IEX', role: 'primary_venue' as const, mic: 'IEXG', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' }, + { source: 'eod' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'NYSE ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'NYSE MKT', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'OTC', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'OTCGREY', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'OTCMKTS', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'OTCQB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'OTCQX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'eod' as const, sourceCode: 'TO', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' }, + { source: 'eod' as const, sourceCode: 'V', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + // IB US + CA primary venues (ATS/routing venues live in EXPLICIT_EXCHANGE_SOURCE_RULES) + { source: 'ib' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'BATS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'ISLAND', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' }, + { source: 'ib' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'PURE', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' }, + { source: 'ib' as const, sourceCode: 'TSE', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' }, + { source: 'ib' as const, sourceCode: 'VALUE', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'ib' as const, sourceCode: 'VENTURE', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + // QuoteMedia US + CA primary venues (qmExchanges has 0% OperatingMIC) + { source: 'qm' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'AQL', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'ARC', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'ASE', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'BATS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'BTS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'BZX', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'CC', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'CDX', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'CNQ', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'CNX', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'CSE', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'CVE', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'IEX', role: 'primary_venue' as const, mic: 'IEXG', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NCM', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'NEOE', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'NGM', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NGS', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NSD', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NSQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NYE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NYS', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'NYSEMKT', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'OBB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'OTC', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'OTCBB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'OTCMKTS', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'OTCQB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'OTCQX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'PCX', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'PNK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'QB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'QX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' }, + { source: 'qm' as const, sourceCode: 'TOR', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'TSE', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'TSV', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'TSX', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'TSXV', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + { source: 'qm' as const, sourceCode: 'VNX', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' }, + ].map(rule => ({ + ...rule, + method: 'explicit_rule' as const, + reviewedBy: 'reviewed_us_ca_venues', + })) + ); + function makeRuleKey(source: ExchangeSource, sourceCode: string): string { return `${source}\u0000${sourceCode}`; } diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 31590801..8e531e38 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -32,6 +32,7 @@ export { isExchangeSource, ISO_EXCHANGE_SEEDS, normalizeRawExchangeDoc, + REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS, type BoardLotPolicy, type ClassificationMethod, type ClassifySourceExchangesOptions, @@ -198,6 +199,7 @@ export { adaptQmSymbolDoc, CEO_SYMBOLS_PROJECTION, createExchangeSourceLookup, + createReadOnlyMongoSourceSymbolReader, DEFAULT_SOURCE_COUNTRIES, EOD_SYMBOL_CHANGE_PROJECTION, EOD_SYMBOLS_PROJECTION, @@ -227,6 +229,9 @@ export { type ReadEodSymbolChangesResult, type ReadEodSymbolsResult, type ReadIbSymbolsResult, + type ReadOnlyMongoCollectionClient, + type ReadOnlySourceSymbolCollection, + type ReadOnlySourceSymbolCursor, type ReadOnlySourceSymbolReader, type ReadSecurityMasterSourcesOptions, type ReadSourceCollectionOptions, 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 index ef7d3077..7f6ec8e9 100644 --- a/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts +++ b/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts @@ -11,6 +11,7 @@ import { compareAscii, EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS, ISO_EXCHANGE_SEEDS, + REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS, type ExchangeRole, type ExchangeSeedRow, type ExchangeSource, @@ -45,10 +46,41 @@ export interface SourceSymbolFindOptions { batchSize?: number; } +/** + * Minimal cursor contract returned by a read-only MongoDB collection `find()`. + * Supports incremental async iteration without materializing the full result set. + */ +export interface ReadOnlySourceSymbolCursor< + T extends Record = Record, +> extends AsyncIterable { + close?(): Promise; +} + +/** + * Minimal read-only collection view exposing strictly `find()` returning an + * incremental async cursor. + */ +export interface ReadOnlySourceSymbolCollection { + find( + filter: Record, + options?: SourceSymbolFindOptions + ): ReadOnlySourceSymbolCursor>; +} + +/** + * Minimal structural slice of a read-only `MongoDBClient` required to construct + * a cursor-backed `ReadOnlySourceSymbolReader` via `createReadOnlyMongoSourceSymbolReader`. + */ +export interface ReadOnlyMongoCollectionClient { + isReadOnly(): boolean; + getCollection(name: string): ReadOnlySourceSymbolCollection; +} + /** * 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. + * Exposes strictly `isReadOnly()` and `find()` returning an incremental + * `AsyncIterable` — no write, index, drop, collection-mutation, or eager array + * buffering methods are reachable through this contract. */ export interface ReadOnlySourceSymbolReader { isReadOnly(): boolean; @@ -56,14 +88,16 @@ export interface ReadOnlySourceSymbolReader { collectionName: string, filter?: Record, options?: SourceSymbolFindOptions - ): Promise | AsyncIterable> | Iterable | AsyncIterable; + ): Promise> | AsyncIterable; } // Compile-time structural compatibility check (type-only, erased at runtime): -// ensures MongoDBClient satisfies ReadOnlySourceSymbolReader under `bun run typecheck`. +// ensures the real `MongoDBClient` satisfies `ReadOnlyMongoCollectionClient` +// so `createReadOnlyMongoSourceSymbolReader(client)` streams via `FindCursor` +// instead of `MongoDBClient.find()`'s `cursor.toArray()` buffering. type AssertAssignable = true; export type MongoDBClientSourceSymbolReaderCheck = AssertAssignable< - ReadOnlySourceSymbolReader, + ReadOnlyMongoCollectionClient, MongoDBClient >; @@ -82,6 +116,7 @@ export interface ExchangeSourceLookup { export interface CreateExchangeSourceLookupOptions { readonly includeExplicitRules?: boolean; + readonly includeReviewedUsCaVenues?: boolean; } export type SourceSymbolSkipReason = @@ -230,147 +265,80 @@ export interface SecurityMasterSourcesResult { 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']), +const COUNTRY_ISO2_ALIASES: Readonly> = Object.freeze({ + US: Object.freeze(['US', 'USA', 'U.S.', 'U.S.A.', 'United States', 'United States of America']), CA: Object.freeze(['CA', 'CAN', 'Canada']), + GB: Object.freeze(['GB', 'GBR', 'UK', 'United Kingdom', 'Great Britain']), + DE: Object.freeze(['DE', 'DEU', 'Germany']), + FR: Object.freeze(['FR', 'FRA', 'France']), + AU: Object.freeze(['AU', 'AUS', 'Australia']), + JP: Object.freeze(['JP', 'JPN', 'Japan']), + CN: Object.freeze(['CN', 'CHN', 'China']), + HK: Object.freeze(['HK', 'HKG', 'Hong Kong']), + CH: Object.freeze(['CH', 'CHE', 'Switzerland']), + NL: Object.freeze(['NL', 'NLD', 'Netherlands']), + IT: Object.freeze(['IT', 'ITA', 'Italy']), + ES: Object.freeze(['ES', 'ESP', 'Spain']), + SE: Object.freeze(['SE', 'SWE', 'Sweden']), + NO: Object.freeze(['NO', 'NOR', 'Norway']), + DK: Object.freeze(['DK', 'DNK', 'Denmark']), + FI: Object.freeze(['FI', 'FIN', 'Finland']), + BE: Object.freeze(['BE', 'BEL', 'Belgium']), + AT: Object.freeze(['AT', 'AUT', 'Austria']), + IE: Object.freeze(['IE', 'IRL', 'Ireland']), + IN: Object.freeze(['IN', 'IND', 'India']), + BR: Object.freeze(['BR', 'BRA', 'Brazil']), + MX: Object.freeze(['MX', 'MEX', 'Mexico']), + KR: Object.freeze(['KR', 'KOR', 'South Korea', 'Korea']), + TW: Object.freeze(['TW', 'TWN', 'Taiwan']), + SG: Object.freeze(['SG', 'SGP', 'Singapore']), + NZ: Object.freeze(['NZ', 'NZL', 'New Zealand']), + IL: Object.freeze(['IL', 'ISR', 'Israel']), + ZA: Object.freeze(['ZA', 'ZAF', 'South Africa']), + PL: Object.freeze(['PL', 'POL', 'Poland']), + PT: Object.freeze(['PT', 'PRT', 'Portugal']), + GR: Object.freeze(['GR', 'GRC', 'Greece']), + TR: Object.freeze(['TR', 'TUR', 'Turkey']), + AR: Object.freeze(['AR', 'ARG', 'Argentina']), + CL: Object.freeze(['CL', 'CHL', 'Chile']), + ID: Object.freeze(['ID', 'IDN', 'Indonesia']), + MY: Object.freeze(['MY', 'MYS', 'Malaysia']), + TH: Object.freeze(['TH', 'THA', 'Thailand']), + VN: Object.freeze(['VN', 'VNM', 'Vietnam']), + PH: Object.freeze(['PH', 'PHL', 'Philippines']), + SA: Object.freeze(['SA', 'SAU', 'Saudi Arabia']), + AE: Object.freeze(['AE', 'ARE', 'UAE', 'United Arab Emirates']), }); +const COUNTRY_NAME_TO_ISO2: ReadonlyMap = (() => { + const map = new Map(); + for (const [iso, aliases] of Object.entries(COUNTRY_ISO2_ALIASES)) { + for (let i = 0; i < aliases.length; i++) { + const alias = aliases[i]; + if (alias !== undefined) { + map.set(alias.toUpperCase(), iso); + } + } + } + return map; +})(); + +const COUNTRY_ISO2_TO_FILTER_VALUES: ReadonlyMap = (() => { + const map = new Map(); + for (const [iso, aliases] of Object.entries(COUNTRY_ISO2_ALIASES)) { + const values = new Set(); + for (let i = 0; i < aliases.length; i++) { + const alias = aliases[i]; + if (alias !== undefined) { + values.add(alias); + values.add(alias.toUpperCase()); + } + } + map.set(iso, Object.freeze([...values].sort(compareAscii))); + } + return map; +})(); + export const EOD_SYMBOLS_PROJECTION: Readonly> = Object.freeze({ _id: 0, eodSearchCode: 1, @@ -450,6 +418,7 @@ export const EOD_SYMBOL_CHANGE_PROJECTION: Readonly> = Obj exchange: 1, eodExchange: 1, eodSearchCode: 1, + effective: 1, date: 1, effectiveDate: 1, validFrom: 1, @@ -479,10 +448,11 @@ export function normalizeCountryIso2(value: string | null | undefined): string | /** * 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. + * Seeds `EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS` and `REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS` + * by default with caller rows taking highest precedence. */ export function createExchangeSourceLookup( - rows: readonly ExchangeSourceMapRow[], + rows: readonly ExchangeSourceMapRow[] = [], options: CreateExchangeSourceLookupOptions = {} ): ExchangeSourceLookup { const bySource: Readonly>> = { @@ -520,6 +490,15 @@ export function createExchangeSourceLookup( } } + if (options.includeReviewedUsCaVenues !== false) { + for (let i = 0; i < REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS.length; i++) { + const row = REVIEWED_US_CA_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) { @@ -635,14 +614,6 @@ function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void { } } -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 && @@ -651,6 +622,65 @@ function isAsyncIterable(value: unknown): value is AsyncIterable { ); } +/** + * Adapts a read-only `MongoDBClient` (or compatible `ReadOnlyMongoCollectionClient`) + * into a cursor-backed `ReadOnlySourceSymbolReader` that streams documents + * incrementally via `collection.find(filter, options)` without buffering the full + * collection through `cursor.toArray()`. + */ +export function createReadOnlyMongoSourceSymbolReader( + client: ReadOnlyMongoCollectionClient +): ReadOnlySourceSymbolReader { + if ( + client === null || + client === undefined || + typeof client !== 'object' || + typeof client.isReadOnly !== 'function' || + !client.isReadOnly() + ) { + throw new Error( + 'Source symbol reader requires a read-only MongoDB client (isReadOnly() must be true)' + ); + } + + return Object.freeze({ + isReadOnly(): boolean { + return client.isReadOnly(); + }, + find = Record>( + collectionName: string, + filter: Record = {}, + options?: SourceSymbolFindOptions + ): AsyncIterable { + if (!client.isReadOnly()) { + throw new Error( + 'Source symbol reader requires a read-only MongoDB client (isReadOnly() must be true)' + ); + } + const collection = client.getCollection(collectionName); + const cursor = collection.find(filter, options); + if (Array.isArray(cursor) || !isAsyncIterable>(cursor)) { + throw new TypeError( + `Collection "${collectionName}" find() must return an incremental async cursor (got buffered or non-async result)` + ); + } + return { + async *[Symbol.asyncIterator](): AsyncIterator { + try { + for await (const doc of cursor) { + yield doc as T; + } + } finally { + if (typeof cursor.close === 'function') { + await cursor.close(); + } + } + }, + }; + }, + }); +} + async function streamCollection>( reader: ReadOnlySourceSymbolReader, collectionName: SourceSymbolCollectionName, @@ -661,21 +691,14 @@ async function streamCollection>( assertReadOnlyReader(reader); try { const cursor = await reader.find(collectionName, filter, options); - if (isAsyncIterable(cursor)) { - for await (const doc of cursor) { - onDoc(doc); - } - return; + if (Array.isArray(cursor) || !isAsyncIterable(cursor)) { + throw new TypeError( + `Reader for collection "${collectionName}" must return an incremental AsyncIterable cursor (use createReadOnlyMongoSourceSymbolReader for MongoDBClient)` + ); } - if (isSyncIterable(cursor)) { - for (const doc of cursor) { - onDoc(doc); - } - return; + for await (const doc of cursor) { + onDoc(doc); } - 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) @@ -773,43 +796,107 @@ function toSpanDateRange(span: SpanDateRange | undefined | null): SpanDateRange }; } -function buildEodCountryFilter(countries: readonly string[] | null): Record { +const EMPTY_MATCH_FILTER: Record = Object.freeze({ _id: { $in: [] } }); + +function expandCountryFilterValues(countries: readonly string[]): string[] { + const expanded = new Set(); + for (let i = 0; i < countries.length; i++) { + const raw = countries[i]; + if (raw === undefined) { + continue; + } + const iso = normalizeCountryIso2(raw) ?? raw.trim().toUpperCase(); + if (iso.length === 0) { + continue; + } + expanded.add(iso); + const aliases = COUNTRY_ISO2_TO_FILTER_VALUES.get(iso); + if (aliases !== undefined) { + for (let j = 0; j < aliases.length; j++) { + const alias = aliases[j]; + if (alias !== undefined) { + expanded.add(alias); + } + } + } + } + return [...expanded].sort(compareAscii); +} + +function buildOrFilter(clauses: readonly Record[]): Record { + const first = clauses[0]; + if (first === undefined) { + return { ...EMPTY_MATCH_FILTER }; + } + if (clauses.length === 1) { + return first; + } + return { $or: [...clauses] }; +} + +function buildEodCountryFilter( + exchangeLookup: ExchangeSourceLookup, + 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); - } + const countryValues = expandCountryFilterValues(countries); + const exchangeCodes = + typeof exchangeLookup.getCodesForCountries === 'function' + ? exchangeLookup.getCodesForCountries('eod', countries) + : []; + + const clauses: Record[] = []; + if (countryValues.length > 0) { + clauses.push({ Country: { $in: countryValues } }); + clauses.push({ countryCode: { $in: countryValues } }); } - return { Country: { $in: [...expanded].sort(compareAscii) } }; + if (exchangeCodes.length > 0) { + clauses.push({ Exchange: { $in: exchangeCodes } }); + clauses.push({ exchange: { $in: exchangeCodes } }); + clauses.push({ exchangeCode: { $in: exchangeCodes } }); + } + return buildOrFilter(clauses); } function buildIbCountryFilter(countries: readonly string[] | null): Record { if (countries === null) { return {}; } - return { country: { $in: [...countries] } }; + const countryValues = expandCountryFilterValues(countries); + if (countryValues.length === 0) { + return { ...EMPTY_MATCH_FILTER }; + } + return buildOrFilter([ + { country: { $in: countryValues } }, + { countryCode: { $in: countryValues } }, + ]); } -function buildQmCountryFilter(countries: readonly string[] | null): Record { +function buildQmCountryFilter( + exchangeLookup: ExchangeSourceLookup, + countries: readonly string[] | null +): Record { if (countries === null) { return {}; } - return { countryCode: { $in: [...countries] } }; + const countryValues = expandCountryFilterValues(countries); + const exchangeCodes = + typeof exchangeLookup.getCodesForCountries === 'function' + ? exchangeLookup.getCodesForCountries('qm', countries) + : []; + + const clauses: Record[] = []; + if (countryValues.length > 0) { + clauses.push({ countryCode: { $in: countryValues } }); + clauses.push({ country: { $in: countryValues } }); + } + if (exchangeCodes.length > 0) { + clauses.push({ exchange: { $in: exchangeCodes } }); + clauses.push({ exchangeCode: { $in: exchangeCodes } }); + } + return buildOrFilter(clauses); } function buildCeoCountryFilter( @@ -819,11 +906,24 @@ function buildCeoCountryFilter( if (countries === null) { return {}; } - if (typeof exchangeLookup.getCodesForCountries === 'function') { - return { exchange: { $in: exchangeLookup.getCodesForCountries('ceo', countries) } }; + const countryValues = expandCountryFilterValues(countries); + const exchangeCodes = + typeof exchangeLookup.getCodesForCountries === 'function' + ? exchangeLookup.getCodesForCountries('ceo', countries) + : countries.includes('CA') + ? [...DEFAULT_CEO_CA_CODES] + : []; + + const clauses: Record[] = []; + if (countryValues.length > 0) { + clauses.push({ countryCode: { $in: countryValues } }); + clauses.push({ country: { $in: countryValues } }); } - const codes = countries.includes('CA') ? [...DEFAULT_CEO_CA_CODES] : []; - return { exchange: { $in: codes } }; + if (exchangeCodes.length > 0) { + clauses.push({ exchange: { $in: exchangeCodes } }); + clauses.push({ exchangeCode: { $in: exchangeCodes } }); + } + return buildOrFilter(clauses); } function buildEodSymbolChangeFilter( @@ -833,10 +933,21 @@ function buildEodSymbolChangeFilter( if (countries === null) { return {}; } - if (typeof exchangeLookup.getCodesForCountries === 'function') { - return { exchange: { $in: exchangeLookup.getCodesForCountries('eod', countries) } }; + const countryValues = expandCountryFilterValues(countries); + const exchangeCodes = + typeof exchangeLookup.getCodesForCountries === 'function' + ? exchangeLookup.getCodesForCountries('eod', countries) + : []; + + const clauses: Record[] = []; + if (countryValues.length > 0) { + clauses.push({ country: { $in: countryValues } }); + clauses.push({ Country: { $in: countryValues } }); } - return {}; + if (exchangeCodes.length > 0) { + clauses.push({ exchange: { $in: exchangeCodes } }); + } + return buildOrFilter(clauses); } function compareStageARecords(a: StageASourceRecord, b: StageASourceRecord): number { @@ -1386,19 +1497,22 @@ export function adaptEodSymbolChangeDoc( const eodSearchCodeField = readOptionalString(doc, 'eodSearchCode'); const countryField = readFirstOptionalString(doc, ['country', 'Country']); - const rawDate = doc.effectiveDate !== undefined ? doc.effectiveDate : doc.date; + const isValidDateField = (value: unknown): boolean => + value === undefined || value === null || typeof value === 'string' || value instanceof Date; + const dateTypeValid = - rawDate === undefined || - rawDate === null || - typeof rawDate === 'string' || - rawDate instanceof Date; + isValidDateField(doc.effective) && + isValidDateField(doc.effectiveDate) && + isValidDateField(doc.date); + const rawDate = + doc.effective !== undefined && doc.effective !== null + ? doc.effective + : doc.effectiveDate !== undefined && doc.effectiveDate !== null + ? doc.effectiveDate + : doc.date; const rawValidFrom = doc.validFrom; - const validFromTypeValid = - rawValidFrom === undefined || - rawValidFrom === null || - typeof rawValidFrom === 'string' || - rawValidFrom instanceof Date; + const validFromTypeValid = isValidDateField(rawValidFrom); if ( !oldSymbolField.ok || @@ -1513,7 +1627,7 @@ export async function readEodSymbols( await streamCollection( reader, SOURCE_SYMBOL_COLLECTIONS.eod, - buildEodCountryFilter(countryList), + buildEodCountryFilter(options.exchangeLookup, countryList), findOptions, doc => { stats.docsRead += 1; @@ -1605,7 +1719,7 @@ export async function readQmSymbols( await streamCollection( reader, SOURCE_SYMBOL_COLLECTIONS.qm, - buildQmCountryFilter(countryList), + buildQmCountryFilter(options.exchangeLookup, countryList), findOptions, doc => { stats.docsRead += 1; diff --git a/test/unit/security-master-source-symbol-readers.test.ts b/test/unit/security-master-source-symbol-readers.test.ts index b647c836..77300fb3 100644 --- a/test/unit/security-master-source-symbol-readers.test.ts +++ b/test/unit/security-master-source-symbol-readers.test.ts @@ -6,15 +6,20 @@ import { BarSpanIndex } from '../../apps/stock/data-pipeline/src/normalization/b import { parseTickerDetailed } from '../../apps/stock/data-pipeline/src/normalization/ticker'; import { CEO_SYMBOLS_PROJECTION, + classifySourceExchanges, compareAscii, createExchangeSourceLookup, + createReadOnlyMongoSourceSymbolReader, DEFAULT_SOURCE_COUNTRIES, EOD_SYMBOL_CHANGE_PROJECTION, EOD_SYMBOLS_PROJECTION, + EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS, IB_SYMBOLS_PROJECTION, + ISO_EXCHANGE_SEEDS, matchInstrumentsStageA, matchListingsStageB, normalizeCountryIso2, + normalizeRawExchangeDoc, QM_SYMBOLS_PROJECTION, readCeoSymbols, readEodSymbolChanges, @@ -22,9 +27,12 @@ import { readIbSymbols, readQmSymbols, readSecurityMasterSources, + REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS, SOURCE_SYMBOL_COLLECTIONS, type ExchangeSourceMapRow, type MongoDBClientSourceSymbolReaderCheck, + type ReadOnlyMongoCollectionClient, + type ReadOnlySourceSymbolCursor, type ReadOnlySourceSymbolReader, type SourceCollectionReadStats, type SourceSymbolFindOptions, @@ -34,9 +42,21 @@ import { type AssertExact = [A] extends [B] ? ([B] extends [A] ? true : never) : never; const _exactReaderKeysCheck: AssertExact = true; +const _exactCollectionClientKeysCheck: AssertExact< + keyof ReadOnlyMongoCollectionClient, + 'isReadOnly' | 'getCollection' +> = true; const _mongoClientAssignableCheck: MongoDBClientSourceSymbolReaderCheck = true; -type AssertMongoAssignable = MongoDBClient extends ReadOnlySourceSymbolReader ? true : never; -const _mongoClientStructuralCheck: AssertMongoAssignable = true; +type AssertMongoCollectionAssignable = MongoDBClient extends ReadOnlyMongoCollectionClient + ? true + : never; +const _mongoClientStructuralCheck: AssertMongoCollectionAssignable = true; +// Raw MongoDBClient.find() calls cursor.toArray() (Promise), so it must NOT be +// directly assignable to ReadOnlySourceSymbolReader (which requires incremental AsyncIterable). +type AssertRawMongoFindNotDirectlyAssignable = MongoDBClient extends ReadOnlySourceSymbolReader + ? never + : true; +const _rawMongoFindNotBufferedCheck: AssertRawMongoFindNotDirectlyAssignable = true; interface RecordedFindCall { collectionName: string; @@ -46,7 +66,7 @@ interface RecordedFindCall { interface FakeReaderOptions { readOnly?: boolean; - asyncIterable?: boolean; + applyFilterAndProjection?: boolean; failOnCollection?: { collection: string; afterDocs?: number; @@ -54,11 +74,77 @@ interface FakeReaderOptions { }; } +function matchesMongoFilter( + doc: Record, + filter: Record | undefined +): boolean { + if (filter === undefined) { + return true; + } + const entries = Object.entries(filter); + for (let i = 0; i < entries.length; i++) { + const [key, expected] = entries[i]!; + if (key === '$or') { + if (!Array.isArray(expected) || expected.length === 0) { + throw new Error('$or must be a nonempty array'); + } + const matchedAny = expected.some(clause => + matchesMongoFilter(doc, clause as Record) + ); + if (!matchedAny) { + return false; + } + continue; + } + const actual = doc[key]; + if (expected !== null && typeof expected === 'object' && !Array.isArray(expected)) { + const operators = expected as Record; + if ('$in' in operators) { + const list = operators.$in; + if (!Array.isArray(list)) { + return false; + } + if (!list.includes(actual)) { + return false; + } + continue; + } + } + if (actual !== expected) { + return false; + } + } + return true; +} + +function applyMongoProjection( + doc: Record, + projection: Record | undefined +): Record { + if (projection === undefined) { + return { ...doc }; + } + const includedKeys = Object.entries(projection) + .filter(([, flag]) => flag === 1) + .map(([key]) => key); + const out: Record = {}; + for (let i = 0; i < includedKeys.length; i++) { + const key = includedKeys[i]!; + if (key in doc) { + out[key] = doc[key]; + } + } + if (projection._id !== 0 && '_id' in doc) { + out._id = doc._id; + } + return out; +} + class FakeSourceSymbolReader implements ReadOnlySourceSymbolReader { public readonly calls: RecordedFindCall[] = []; private readonly collections: Readonly[]>>; private readonly readOnly: boolean; - private readonly asyncIterable: boolean; + private readonly applyFilterAndProjection: boolean; private readonly failOnCollection?: FakeReaderOptions['failOnCollection']; constructor( @@ -67,7 +153,7 @@ class FakeSourceSymbolReader implements ReadOnlySourceSymbolReader { ) { this.collections = collections; this.readOnly = options.readOnly ?? true; - this.asyncIterable = options.asyncIterable ?? false; + this.applyFilterAndProjection = options.applyFilterAndProjection ?? false; this.failOnCollection = options.failOnCollection; } @@ -79,7 +165,7 @@ class FakeSourceSymbolReader implements ReadOnlySourceSymbolReader { collectionName: string, filter?: Record, options?: SourceSymbolFindOptions - ): Promise | AsyncIterable> { + ): Promise> { this.calls.push({ collectionName, filter, options }); if ( @@ -90,57 +176,65 @@ class FakeSourceSymbolReader implements ReadOnlySourceSymbolReader { throw new Error(this.failOnCollection.errorMessage ?? 'connection reset by peer'); } - const docs = (this.collections[collectionName] ?? []) as readonly T[]; + const docs = this.collections[collectionName] ?? []; const failConfig = this.failOnCollection !== undefined && this.failOnCollection.collection === collectionName ? this.failOnCollection : undefined; + const applyQuery = this.applyFilterAndProjection; + const projection = options?.projection; - 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 { + async *[Symbol.asyncIterator](): AsyncIterator { + let yielded = 0; + for (const doc of docs) { + if (applyQuery && !matchesMongoFilter(doc, filter)) { + continue; } - }, - }; - } - - return docs; + if (failConfig?.afterDocs !== undefined && yielded >= failConfig.afterDocs) { + throw new Error(failConfig.errorMessage ?? 'mid-stream cursor error'); + } + yielded += 1; + yield (applyQuery ? applyMongoProjection(doc, projection) : doc) as T; + } + }, + }; } } -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 +/** + * Builds the Pass 1 exchange lookup strictly through the repo's Pass 1 path + * (`normalizeRawExchangeDoc` -> `classifySourceExchanges` -> `createExchangeSourceLookup`), + * matching live QA MongoDB where `eodExchanges` holds composite `US` + CA venues and + * `qmExchanges` / `ibExchanges` carry zero OperatingMICs. + */ +function createPass1ExchangeLookup(extraRows: readonly ExchangeSourceMapRow[] = []) { + const rawPass1Records = [ + // eodExchanges (US is composite; CA exchanges carry OperatingMIC) + normalizeRawExchangeDoc('eod', { Code: 'US', Name: 'USA Stocks', CountryISO2: 'US', OperatingMIC: 'XNAS, XNYS' }), + normalizeRawExchangeDoc('eod', { Code: 'TO', Name: 'Toronto Exchange', CountryISO2: 'CA', OperatingMIC: 'XTSE' }), + normalizeRawExchangeDoc('eod', { Code: 'V', Name: 'TSX Venture', CountryISO2: 'CA', OperatingMIC: 'XTSX' }), + normalizeRawExchangeDoc('eod', { Code: 'CN', Name: 'CSE', CountryISO2: 'CA', OperatingMIC: 'XCNQ' }), + normalizeRawExchangeDoc('eod', { Code: 'NEO', Name: 'Cboe Canada', CountryISO2: 'CA', OperatingMIC: 'NEOE' }), + // qmExchanges (0% OperatingMIC in QA MongoDB per phase1-investigation.md) + normalizeRawExchangeDoc('qm', { exchange: 'NSQ', exchangeName: 'NASDAQ', countryCode: 'US' }), + normalizeRawExchangeDoc('qm', { exchange: 'NYE', exchangeName: 'NYSE', countryCode: 'US' }), + normalizeRawExchangeDoc('qm', { exchange: 'TSE', exchangeName: 'TSX', countryCode: 'CA' }), + normalizeRawExchangeDoc('qm', { exchange: 'CNX', exchangeName: 'CSE', countryCode: 'CA' }), + normalizeRawExchangeDoc('qm', { exchange: 'CC', exchangeName: 'CSE Legacy', countryCode: 'CA' }), + // ibExchanges (0% OperatingMIC in QA MongoDB) + normalizeRawExchangeDoc('ib', { id: 'AEQLIT', name: 'Aequitas NEO', country_code: 'CA' }), + normalizeRawExchangeDoc('ib', { id: 'OTCLNKECN', name: 'OTC Link ECN', country_code: 'US' }), + normalizeRawExchangeDoc('ib', { id: 'NYSE', name: 'NYSE', country_code: 'US' }), + // ceoExchanges + normalizeRawExchangeDoc('ceo', { exchange: 'TSX', countryCode: 'CA' }), + normalizeRawExchangeDoc('ceo', { exchange: 'CDX', countryCode: 'CA' }), + normalizeRawExchangeDoc('ceo', { exchange: 'CNQ', countryCode: 'CA' }), + normalizeRawExchangeDoc('ceo', { exchange: 'AQL', countryCode: 'CA' }), ]; - return createExchangeSourceLookup(rows); + + const pass1 = classifySourceExchanges(rawPass1Records); + return createExchangeSourceLookup([...pass1.mapped, ...extraRows]); } function sumSkips(stats: SourceCollectionReadStats): number { @@ -183,8 +277,10 @@ function shuffleWithSeed(items: readonly T[], seed: number): T[] { 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(_exactCollectionClientKeysCheck).toBe(true); expect(_mongoClientAssignableCheck).toBe(true); expect(_mongoClientStructuralCheck).toBe(true); + expect(_rawMongoFindNotBufferedCheck).toBe(true); // Static check: source-symbol-readers.ts must not contain runtime DB, fs, or network imports. const sourcePath = resolve( @@ -196,7 +292,7 @@ describe('security-master source-symbol-readers', () => { 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(); + const exchangeLookup = createPass1ExchangeLookup(); // Writable reader must fail before issuing any find() call. const writableReader = new FakeSourceSymbolReader({}, { readOnly: false }); @@ -212,6 +308,13 @@ describe('security-master source-symbol-readers', () => { ); expect(writableReader.calls.length).toBe(0); + // Buffered array result must be rejected at runtime (enforcing incremental streaming). + const bufferingReader: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find: async () => [] as unknown as AsyncIterable, + }; + await expect(readEodSymbols(bufferingReader, { exchangeLookup })).rejects.toThrow(/eodSymbols/); + // 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 }); @@ -229,7 +332,7 @@ describe('security-master source-symbol-readers', () => { expect(call.options?.batchSize).toBe(2000); } - // Verify qmSymbols projection omits bloated profile/symbolInfo blobs. + // Verify projections omit bloated blobs and include documented `effective` date field. expect(QM_SYMBOLS_PROJECTION._id).toBe(0); expect('profile' in QM_SYMBOLS_PROJECTION).toBe(false); expect('symbolInfo' in QM_SYMBOLS_PROJECTION).toBe(false); @@ -237,20 +340,15 @@ describe('security-master source-symbol-readers', () => { expect(IB_SYMBOLS_PROJECTION._id).toBe(0); expect(CEO_SYMBOLS_PROJECTION._id).toBe(0); expect(EOD_SYMBOL_CHANGE_PROJECTION._id).toBe(0); + expect(EOD_SYMBOL_CHANGE_PROJECTION.effective).toBe(1); - // Verify default US + CA country pushdown filters. + // Verify default US + CA country pushdown filters include spellings and venue fallbacks. 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'] }, - }); + expect(readOnlyReader.calls[0]?.filter).toHaveProperty('$or'); + expect(readOnlyReader.calls[1]?.filter).toHaveProperty('$or'); + expect(readOnlyReader.calls[2]?.filter).toHaveProperty('$or'); + expect(readOnlyReader.calls[3]?.filter).toHaveProperty('$or'); + expect(readOnlyReader.calls[4]?.filter).toHaveProperty('$or'); // When countries: null, filters must be empty {}. const unfilteredReader = new FakeSourceSymbolReader({}, { readOnly: true }); @@ -260,24 +358,249 @@ describe('security-master source-symbol-readers', () => { } }); - test('happy path: US, CA domestic, CA interlisted (SHOP), and symbol change resolve unchanged through Stage A and Stage B', async () => { - const exchangeLookup = createTestExchangeLookup(); + test('cursor-backed MongoDB adapter streams incrementally via getCollection().find() without toArray() and closes cursors', async () => { + const exchangeLookup = createPass1ExchangeLookup(); + + // Writable client rejected immediately before any getCollection() call. + let writableGetCollectionCalled = false; + const writableClient: ReadOnlyMongoCollectionClient = { + isReadOnly: () => false, + getCollection: () => { + writableGetCollectionCalled = true; + throw new Error('should not be called'); + }, + }; + expect(() => createReadOnlyMongoSourceSymbolReader(writableClient)).toThrow(/read-only/i); + expect(writableGetCollectionCalled).toBe(false); + + // In-memory cursor fixture proving incremental iteration, zero toArray() buffering, and cursor.close(). + const events: string[] = []; + const closedCollections: string[] = []; + const recordedOptions: Array<{ + collection: string; + filter: Record; + options: SourceSymbolFindOptions | undefined; + }> = []; + + const fixtures: Record[]> = { + eodSymbols: [ + { + _id: 'raw-1', + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + eodExchange: 'US', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Name: 'Apple Inc.', + }, + { + _id: 'raw-2', + eodSearchCode: 'RY.TO', + Code: 'RY', + eodExchange: 'TO', + Exchange: 'TO', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA7800871021', + Name: 'Royal Bank of Canada', + }, + ], + ibSymbols: [], + qmSymbols: [ + { _id: 'qm-1', qmSearchCode: 'VOY:CNX', symbol: 'VOY', exchange: 'CNX', countryCode: 'CA', active: true, profile: { huge: 'blob' } }, + { _id: 'qm-2', qmSearchCode: 'VOY:CC', symbol: 'VOY', exchange: 'CC', countryCode: 'CA', active: false, symbolInfo: { huge: 'blob' } }, + ], + ceoSymbols: [], + eodSymbolChange: [], + }; + + const cursorClient: ReadOnlyMongoCollectionClient = { + isReadOnly: () => true, + getCollection(name: string) { + return { + find(filter: Record, options?: SourceSymbolFindOptions) { + recordedOptions.push({ collection: name, filter, options }); + const docs = fixtures[name] ?? []; + const cursor: ReadOnlySourceSymbolCursor> & { + toArray: () => never; + } = { + toArray() { + throw new Error('toArray() must never be called on streaming cursor path'); + }, + async *[Symbol.asyncIterator]() { + for (let i = 0; i < docs.length; i++) { + const doc = docs[i]!; + if (!matchesMongoFilter(doc, filter)) { + continue; + } + events.push(`yield:${name}:${i}`); + yield applyMongoProjection(doc, options?.projection); + } + }, + async close() { + closedCollections.push(name); + }, + }; + return cursor; + }, + }; + }, + }; + + const reader = createReadOnlyMongoSourceSymbolReader(cursorClient); + const result = await readSecurityMasterSources(reader, { exchangeLookup, batchSize: 500 }); + + expect(result.stats.eodSymbols.emitted).toBe(2); + expect(result.stats.qmSymbols.emitted).toBe(2); + expect(closedCollections).toEqual([ + 'eodSymbols', + 'ibSymbols', + 'qmSymbols', + 'ceoSymbols', + 'eodSymbolChange', + ]); + expect(events).toEqual([ + 'yield:eodSymbols:0', + 'yield:eodSymbols:1', + 'yield:qmSymbols:0', + 'yield:qmSymbols:1', + ]); + for (const rec of recordedOptions) { + expect(rec.options?.projection?._id).toBe(0); + expect(rec.options?.batchSize).toBe(500); + } + + // Cursor must still be closed when an error occurs mid-stream. + let errorCursorClosed = false; + const failingCursorClient: ReadOnlyMongoCollectionClient = { + isReadOnly: () => true, + getCollection() { + return { + find() { + return { + async *[Symbol.asyncIterator]() { + yield { eodSearchCode: 'AAPL.US', Code: 'AAPL', Exchange: 'NASDAQ', Country: 'USA' }; + throw new Error('network interrupted'); + }, + async close() { + errorCursorClosed = true; + }, + }; + }, + }; + }, + }; + const failingReader = createReadOnlyMongoSourceSymbolReader(failingCursorClient); + await expect(readEodSymbols(failingReader, { exchangeLookup })).rejects.toThrow(/eodSymbols/); + expect(errorCursorClosed).toBe(true); + }); + + test('Pass 1 lookup coverage: reviewed US+CA venue rules are valid and Pass 1 path resolves NASDAQ, NYSE, and both VOY records', async () => { + // Structural integrity of REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: + // every MIC is in ISO_EXCHANGE_SEEDS with matching countryIso and zero collisions with explicit baseline. + const seedByMic = new Map(ISO_EXCHANGE_SEEDS.map(row => [row.mic, row])); + const explicitKeys = new Set( + EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS.map(row => `${row.source}:${row.sourceCode}`) + ); + for (const row of REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS) { + expect(explicitKeys.has(`${row.source}:${row.sourceCode}`)).toBe(false); + expect(row.mic).not.toBeNull(); + const seed = seedByMic.get(row.mic!); + expect(seed).toBeDefined(); + expect(row.countryIso).toBe(seed?.countryIso); + expect(row.reviewedBy).toBe('reviewed_us_ca_venues'); + } + + // Build lookup strictly through the repo's Pass 1 path (no hand-built rows). + const exchangeLookup = createPass1ExchangeLookup(); + expect(exchangeLookup.get('eod', 'NASDAQ')?.mic).toBe('XNAS'); + expect(exchangeLookup.get('eod', 'NYSE')?.mic).toBe('XNYS'); + expect(exchangeLookup.get('qm', 'CNX')?.mic).toBe('XCNQ'); + expect(exchangeLookup.get('qm', 'CC')?.mic).toBe('XCNQ'); + 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: 'eod', sourceId: 'AAPL.US', firstBarDate: '2010-01-04', lastBarDate: '2025-06-30', barCount: 3900 }); + barSpans.merge({ source: 'eod', sourceId: 'VOY.CN', firstBarDate: '2020-01-03', lastBarDate: '2025-01-03', barCount: 1250 }); 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 }); + 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: [ { + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + eodExchange: 'US', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Name: 'Apple Inc.', + }, + { + eodSearchCode: 'VOY.CN', + Code: 'VOY', + eodExchange: 'CN', + Exchange: 'CN', + Country: 'Canada', + Currency: 'CAD', + Isin: 'CA92919V1085', + Name: 'Voyager Digital Ltd.', + }, + ], + ibSymbols: [], + qmSymbols: [ + { qmSearchCode: 'AAPL:US', symbol: 'AAPL', exchange: 'NSQ', countryCode: 'US', active: true }, + { qmSearchCode: 'VOY:CNX', symbol: 'VOY', exchange: 'CNX', countryCode: 'CA', active: true }, + { qmSearchCode: 'VOY:CC', symbol: 'VOY', exchange: 'CC', countryCode: 'CA', active: false }, + ], + ceoSymbols: [], + eodSymbolChange: [], + }, + { readOnly: true, applyFilterAndProjection: true } + ); + + const sources = await readSecurityMasterSources(reader, { exchangeLookup, barSpans }); + expect(sources.stats.eodSymbols.emitted).toBe(2); + expect(sources.stats.qmSymbols.emitted).toBe(3); + + const stageA = matchInstrumentsStageA(sources.stageARecords); + const stageB = matchListingsStageB({ instruments: stageA.instruments, ...sources.stageBInput }); + expect(stageB.conflicts).toEqual([]); + expect(stageB.unresolved).toEqual([]); + + const qmMappedIds = stageB.providerMappings + .filter(m => m.source === 'qm') + .map(m => m.sourceId) + .sort(compareAscii); + expect(qmMappedIds).toEqual(['AAPL:US', 'VOY:CC', 'VOY:CNX']); + }); + + test('happy path: US, CA domestic, CA interlisted (SHOP), and provider-shaped eodSymbolChange (`effective`) resolve unchanged through Stage A and Stage B', async () => { + const exchangeLookup = createPass1ExchangeLookup(); + 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 }); + // Pre-effective FB (Facebook, ends 2022-06-08 < effective 2022-06-09) -> MUST resolve to META + barSpans.merge({ source: 'qm', sourceId: 'FB:US', firstBarDate: '2015-01-02', lastBarDate: '2022-06-08', barCount: 1870 }); + // Post-effective FB (2025 ETF reusing ticker FB after 2022-06-09) -> MUST NOT resolve to META + barSpans.merge({ source: 'qm', sourceId: 'FB_ETF:US', firstBarDate: '2025-01-02', lastBarDate: '2025-06-30', barCount: 120 }); + + const reader = new FakeSourceSymbolReader( + { + eodSymbols: [ + { + _id: 'eod-1', eodSearchCode: 'AAPL.US', Code: 'AAPL', eodExchange: 'US', @@ -289,6 +612,7 @@ describe('security-master source-symbol-readers', () => { Name: 'Apple Inc.', }, { + _id: 'eod-2', eodSearchCode: 'RY.TO', Code: 'RY', eodExchange: 'TO', @@ -300,6 +624,7 @@ describe('security-master source-symbol-readers', () => { Name: 'Royal Bank of Canada', }, { + _id: 'eod-3', eodSearchCode: 'SHOP.TO', Code: 'SHOP', eodExchange: 'TO', @@ -312,6 +637,7 @@ describe('security-master source-symbol-readers', () => { }, // CA interlisted share on NYSE: listing Country='USA' differs from issuer country 'CA'. { + _id: 'eod-4', eodSearchCode: 'SHOP.US', Code: 'SHOP', eodExchange: 'US', @@ -323,6 +649,7 @@ describe('security-master source-symbol-readers', () => { Name: 'Shopify Inc.', }, { + _id: 'eod-5', eodSearchCode: 'META.US', Code: 'META', eodExchange: 'US', @@ -336,6 +663,7 @@ describe('security-master source-symbol-readers', () => { ], ibSymbols: [ { + _id: 'ib-1', conid: 265598, symbol: 'AAPL', exchangeId: 'ARCAEDGE', @@ -346,6 +674,7 @@ describe('security-master source-symbol-readers', () => { description: 'APPLE INC', }, { + _id: 'ib-2', conid: 4001, symbol: 'RY', exchangeId: 'AEQLIT', @@ -356,6 +685,7 @@ describe('security-master source-symbol-readers', () => { description: 'ROYAL BANK OF CANADA', }, { + _id: 'ib-3', conid: 199100, symbol: 'SHOP', exchangeId: 'AEQLIT', @@ -366,6 +696,7 @@ describe('security-master source-symbol-readers', () => { description: 'SHOPIFY INC - CLASS A', }, { + _id: 'ib-4', conid: 199101, symbol: 'SHOP', exchangeId: 'OTCLNKECN', @@ -377,26 +708,29 @@ describe('security-master source-symbol-readers', () => { }, ], 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 }, + { _id: 'qm-1', qmSearchCode: 'AAPL:US', symbol: 'AAPL', exchange: 'NSQ', countryCode: 'US', active: true, profile: { omitted: true } }, + { _id: 'qm-2', qmSearchCode: 'RY:CA', symbol: 'RY', exchange: 'TSE', countryCode: 'CA', active: true }, + { _id: 'qm-3', qmSearchCode: 'SHOP:CA', symbol: 'SHOP', exchange: 'TSE', countryCode: 'CA', active: true }, + { _id: 'qm-4', qmSearchCode: 'SHOP:US', symbol: 'SHOP', exchange: 'NYE', countryCode: 'US', active: true }, + { _id: 'qm-5', qmSearchCode: 'FB:US', symbol: 'FB', exchange: 'NSQ', countryCode: 'US', active: false }, + { _id: 'qm-6', qmSearchCode: 'FB_ETF:US', symbol: 'FB', exchange: 'NSQ', countryCode: 'US', active: true }, ], 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' }, + { _id: 'ceo-1', ceoId: 'RY', symbol: 'RY.TO', exchange: 'TSX', name: 'Royal Bank', lastSeen: '2025-03-15' }, + { _id: 'ceo-2', ceoId: 'SHOP', symbol: 'SHOP.TO', exchange: 'TSX', name: 'Shopify', lastSeen: '2025-03-15' }, ], + // Provider-shaped eodSymbolChange doc matching REVIEW.md:71 (`exchange: 'US'`, `effective` date field). eodSymbolChange: [ { + _id: 'sc-1', oldSymbol: 'FB', newSymbol: 'META', - exchange: 'NASDAQ', - date: '2022-06-09', + exchange: 'US', + effective: '2022-06-09', }, ], }, - { readOnly: true, asyncIterable: true } + { readOnly: true, applyFilterAndProjection: true } ); const sources = await readSecurityMasterSources(reader, { exchangeLookup, barSpans }); @@ -406,6 +740,14 @@ describe('security-master source-symbol-readers', () => { assertStatsConservation(sources.stats.qmSymbols); assertStatsConservation(sources.stats.ceoSymbols); assertStatsConservation(sources.stats.eodSymbolChange); + expect(sources.stats.eodSymbolChange.emitted).toBe(1); + expect(sources.stageBInput.symbolChanges).toEqual([ + { + eodSourceId: 'META.US', + oldTicker: 'FB', + effectiveDate: '2022-06-09', + }, + ]); // T-55: SHOP.US Stage A record carries issuer country 'CA', not listing country 'US'. const shopUsStageA = sources.stageARecords.find( @@ -428,7 +770,6 @@ describe('security-master source-symbol-readers', () => { ...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. @@ -443,13 +784,19 @@ describe('security-master source-symbol-readers', () => { 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. + // Historical pre-effective FB:US resolved to META listing via `effective: '2022-06-09'`. 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'); + // Post-effective FB_ETF:US (2025) must NOT resolve to META — stays unresolved. + expect(stageB.providerMappings.some(m => m.source === 'qm' && m.sourceId === 'FB_ETF:US')).toBe( + false + ); + expect(stageB.unresolved.map(u => `${u.source}:${u.sourceId}`)).toEqual(['qm:FB_ETF:US']); + // CEO mappings resolved to XTSE listings. const ceoShopMapping = stageB.providerMappings.find( m => m.source === 'ceo' && m.sourceId === 'SHOP' @@ -458,8 +805,119 @@ describe('security-master source-symbol-readers', () => { expect(ceoShopMapping?.listingKey.tickerRoot).toBe('SHOP'); }); + test('query pushdown with filter+projection fake: non-US/CA countries (DE/Germany) and venue fallbacks retain eligible documents', async () => { + const germanLookup = createPass1ExchangeLookup([ + { source: 'eod', sourceCode: 'F', role: 'primary_venue', mic: 'XFRA', countryIso: 'DE', method: 'operating_mic' }, + { source: 'eod', sourceCode: 'XETRA', role: 'primary_venue', mic: 'XETR', countryIso: 'DE', method: 'operating_mic' }, + { source: 'qm', sourceCode: 'FRA', role: 'primary_venue', mic: 'XFRA', countryIso: 'DE', method: 'explicit_rule' }, + ]); + + const reader = new FakeSourceSymbolReader( + { + eodSymbols: [ + // Documented EOD record SVQ.F with full country name 'Germany' + { + _id: 'de-1', + eodSearchCode: 'SVQ.F', + Code: 'SVQ', + Exchange: 'F', + Country: 'Germany', + Currency: 'EUR', + Isin: 'DE0007164600', + Name: 'SAP SE', + }, + // Missing Country/countryCode -> falls back to mapped German venue 'F' + { + _id: 'de-2', + eodSearchCode: 'ADS.F', + Code: 'ADS', + Exchange: 'F', + Currency: 'EUR', + Isin: 'DE000A1EWWW0', + Name: 'Adidas AG', + }, + // Uses countryCode: 'DE' instead of Country + { + _id: 'de-3', + eodSearchCode: 'SIE.XETRA', + Code: 'SIE', + Exchange: 'XETRA', + countryCode: 'DE', + Currency: 'EUR', + Name: 'Siemens AG', + }, + // Out-of-scope US record filtered out by MongoDB query pushdown + { + _id: 'us-1', + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + Exchange: 'NASDAQ', + Country: 'USA', + Currency: 'USD', + Isin: 'US0378331005', + Name: 'Apple Inc.', + }, + ], + ibSymbols: [ + { _id: 'ib-de-1', conid: 90001, symbol: 'SAP', country: 'Germany', currency: 'EUR', isin: 'DE0007164600' }, + { _id: 'ib-de-2', conid: 90002, symbol: 'ADS', countryCode: 'DE', currency: 'EUR', isin: 'DE000A1EWWW0' }, + { _id: 'ib-us-1', conid: 265598, symbol: 'AAPL', country: 'US', currency: 'USD', isin: 'US0378331005' }, + ], + qmSymbols: [ + // Venue fallback when countryCode is absent + { _id: 'qm-de-1', qmSearchCode: 'SAP:FRA', symbol: 'SAP', exchange: 'FRA', currency: 'EUR', profile: { huge: true } }, + // Country spelling 'Germany' + { _id: 'qm-de-2', qmSearchCode: 'ADS:FRA', symbol: 'ADS', exchange: 'FRA', country: 'Germany', currency: 'EUR' }, + // Out-of-scope US record + { _id: 'qm-us-1', qmSearchCode: 'AAPL:US', symbol: 'AAPL', exchange: 'NSQ', countryCode: 'US' }, + ], + ceoSymbols: [], + eodSymbolChange: [ + { _id: 'sc-de-1', oldSymbol: 'OLDDE', newSymbol: 'NEWDE', exchange: 'F', effective: '2024-09-01' }, + { _id: 'sc-us-1', oldSymbol: 'FB', newSymbol: 'META', exchange: 'US', effective: '2022-06-09' }, + ], + }, + { readOnly: true, applyFilterAndProjection: true } + ); + + const result = await readSecurityMasterSources(reader, { + exchangeLookup: germanLookup, + countries: ['DE'], + }); + + // All three eligible German EOD records survive MongoDB query pushdown + projection. + expect(result.stats.eodSymbols.docsRead).toBe(3); + expect(result.stats.eodSymbols.emitted).toBe(3); + expect(result.stageBInput.eodListings.map(l => l.sourceId)).toEqual([ + 'ADS.F', + 'SIE.XETRA', + 'SVQ.F', + ]); + + // Both German IB records (country='Germany' and countryCode='DE') survive. + expect(result.stats.ibSymbols.docsRead).toBe(2); + expect(result.stats.ibSymbols.emitted).toBe(2); + + // Both German QM records (venue fallback and country='Germany') survive. + expect(result.stats.qmSymbols.docsRead).toBe(2); + expect(result.stats.qmSymbols.emitted).toBe(2); + + // German symbol change survives; US symbol change filtered out by pushdown. + expect(result.stats.eodSymbolChange.docsRead).toBe(1); + expect(result.stats.eodSymbolChange.emitted).toBe(1); + expect(result.stageBInput.symbolChanges[0]?.eodSourceId).toBe('NEWDE.F'); + + // Empty countries: [] yields a valid MongoDB filter (never $or: []) and reads 0 docs. + const emptyResult = await readSecurityMasterSources(reader, { + exchangeLookup: germanLookup, + countries: [], + }); + expect(emptyResult.stats.eodSymbols.docsRead).toBe(0); + expect(emptyResult.stats.ibSymbols.docsRead).toBe(0); + }); + 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 exchangeLookup = createPass1ExchangeLookup(); 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 }); @@ -567,7 +1025,7 @@ describe('security-master source-symbol-readers', () => { 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) + // Stage A recovers 777001 via tier2_cusip (valid CUSIP 813137106 + CA prefix from invalid ISIN) const stageA = matchInstrumentsStageA(result.stageARecords); const scuMember = stageA.instruments .flatMap(i => i.members) @@ -607,7 +1065,7 @@ describe('security-master source-symbol-readers', () => { }); 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 exchangeLookup = createPass1ExchangeLookup(); const reader = new FakeSourceSymbolReader({ eodSymbols: [ @@ -643,15 +1101,15 @@ describe('security-master source-symbol-readers', () => { { 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 + { oldSymbol: '', newSymbol: 'B', exchange: 'NASDAQ', effective: '2024-05-01' }, // missingId + { oldSymbol: 123 as unknown as string, newSymbol: 'B', exchange: 'NASDAQ', effective: '2024-05-01' }, // invalidFieldType + { oldSymbol: 'A', newSymbol: 'B', exchange: 'XETRA', country: 'Germany', effective: '2024-05-01' }, // outOfScopeCountry + { oldSymbol: 'A', newSymbol: 'B', exchange: 'UNKNOWN_EX', effective: '2024-05-01' }, // unmappedExchange + { oldSymbol: 'A', newSymbol: 'B', exchange: 'NASDAQ', effective: '0001-01-01' }, // invalidIdentifier (<= 0001-01-01) + { oldSymbol: 'A', newSymbol: 'B', exchange: 'NASDAQ', effective: 'not-a-date' }, // invalidIdentifier + { oldSymbol: 'A', newSymbol: 'B', exchange: 'NASDAQ', effective: '2024-05-01', validFrom: '2024-05-01' }, // invalidIdentifier (validFrom >= effectiveDate) + { oldSymbol: 'A'.repeat(30), newSymbol: 'B', exchange: 'NASDAQ', effective: '2024-05-01' }, // invalidIdentifier (root > MAX_TICKER_ROOT_LENGTH) + { oldSymbol: 'OLD', newSymbol: 'NEW', exchange: 'US', effective: '2024-05-01' }, // emitted ], }); @@ -719,8 +1177,8 @@ describe('security-master source-symbol-readers', () => { 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' }, + { eodSearchCode: 'A.US', conid: 1, qmSearchCode: 'A:US', ceoId: 'A', oldSymbol: 'A', newSymbol: 'B', exchange: 'US', effective: '2024-05-01' }, + { eodSearchCode: 'B.US', conid: 2, qmSearchCode: 'B:US', ceoId: 'B', oldSymbol: 'C', newSymbol: 'D', exchange: 'US', effective: '2024-05-02' }, ], }, { @@ -743,7 +1201,7 @@ describe('security-master source-symbol-readers', () => { }); test('determinism: shuffling fake-cursor order across seeds yields byte-identical JSON output sorted by (source, sourceId)', async () => { - const exchangeLookup = createTestExchangeLookup(); + const exchangeLookup = createPass1ExchangeLookup(); const baseCollections = { eodSymbols: [ @@ -771,8 +1229,8 @@ describe('security-master source-symbol-readers', () => { { 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' }, + { oldSymbol: 'FB', newSymbol: 'META', exchange: 'US', effective: '2022-06-09' }, + { oldSymbol: 'ANTM', newSymbol: 'ELV', exchange: 'US', effective: '2022-06-28' }, ], }; @@ -816,16 +1274,16 @@ describe('security-master source-symbol-readers', () => { const IB_COUNT = 18_000; const TOTAL_DOCS = EOD_COUNT + QM_COUNT + IB_COUNT; - const exchangeLookup = createTestExchangeLookup(); + const exchangeLookup = createPass1ExchangeLookup(); - // Streaming generator fake reader so benchmark measures reader/adapter + sort throughput - // without pre-allocating 368k raw fixture objects in RAM before timing starts. + // Incremental AsyncIterable fake cursor so benchmark measures streaming 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 { + find>(collectionName: string): AsyncIterable { if (collectionName === SOURCE_SYMBOL_COLLECTIONS.eod) { return { - *[Symbol.iterator](): Iterator { + async *[Symbol.asyncIterator](): AsyncIterator { for (let i = 0; i < EOD_COUNT; i++) { const isMutualFund = i % 10 === 0; const isCa = !isMutualFund && i % 5 === 0; @@ -846,7 +1304,7 @@ describe('security-master source-symbol-readers', () => { } if (collectionName === SOURCE_SYMBOL_COLLECTIONS.qm) { return { - *[Symbol.iterator](): Iterator { + async *[Symbol.asyncIterator](): AsyncIterator { for (let i = 0; i < QM_COUNT; i++) { const isCa = i % 4 === 0; const doc = { @@ -863,7 +1321,7 @@ describe('security-master source-symbol-readers', () => { } if (collectionName === SOURCE_SYMBOL_COLLECTIONS.ib) { return { - *[Symbol.iterator](): Iterator { + async *[Symbol.asyncIterator](): AsyncIterator { for (let i = 0; i < IB_COUNT; i++) { const isCa = i % 5 === 0; const doc = { @@ -881,7 +1339,11 @@ describe('security-master source-symbol-readers', () => { }, }; } - return []; + return { + async *[Symbol.asyncIterator](): AsyncIterator { + // empty cursor + }, + }; }, };