T-86: M1.1k — Read-only Mongo source-symbol readers: eodSymbols / ibSymbols / qmSymbols / ceoSymbols / eodSymbolChange → Stage A + Stage B input records (no new dependencies)
This commit is contained in:
parent
fa55ff16fa
commit
32677c50da
4 changed files with 2729 additions and 0 deletions
|
|
@ -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`).
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
906
test/unit/security-master-source-symbol-readers.test.ts
Normal file
906
test/unit/security-master-source-symbol-readers.test.ts
Normal file
|
|
@ -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, B> = [A] extends [B] ? ([B] extends [A] ? true : never) : never;
|
||||
const _exactReaderKeysCheck: AssertExact<keyof ReadOnlySourceSymbolReader, 'isReadOnly' | 'find'> =
|
||||
true;
|
||||
const _mongoClientAssignableCheck: MongoDBClientSourceSymbolReaderCheck = true;
|
||||
type AssertMongoAssignable = MongoDBClient extends ReadOnlySourceSymbolReader ? true : never;
|
||||
const _mongoClientStructuralCheck: AssertMongoAssignable = true;
|
||||
|
||||
interface RecordedFindCall {
|
||||
collectionName: string;
|
||||
filter: Record<string, unknown> | 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<Record<string, readonly Record<string, unknown>[]>>;
|
||||
private readonly readOnly: boolean;
|
||||
private readonly asyncIterable: boolean;
|
||||
private readonly failOnCollection?: FakeReaderOptions['failOnCollection'];
|
||||
|
||||
constructor(
|
||||
collections: Readonly<Record<string, readonly Record<string, unknown>[]>>,
|
||||
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<T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
collectionName: string,
|
||||
filter?: Record<string, unknown>,
|
||||
options?: SourceSymbolFindOptions
|
||||
): Promise<Iterable<T> | AsyncIterable<T>> {
|
||||
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<T> {
|
||||
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<T>(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<T extends Record<string, unknown>>(collectionName: string): Iterable<T> {
|
||||
if (collectionName === SOURCE_SYMBOL_COLLECTIONS.eod) {
|
||||
return {
|
||||
*[Symbol.iterator](): Iterator<T> {
|
||||
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<T> {
|
||||
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<T> {
|
||||
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);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue