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:
Studio 2026-11-28 04:27:43 -05:00
parent 32677c50da
commit cadc3d1b6d
5 changed files with 995 additions and 320 deletions

View file

@ -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, B> = [A] extends [B] ? ([B] extends [A] ? true : never) : never;
const _exactReaderKeysCheck: AssertExact<keyof ReadOnlySourceSymbolReader, 'isReadOnly' | 'find'> =
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<T[]>), 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<string, unknown>,
filter: Record<string, unknown> | 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<string, unknown>)
);
if (!matchedAny) {
return false;
}
continue;
}
const actual = doc[key];
if (expected !== null && typeof expected === 'object' && !Array.isArray(expected)) {
const operators = expected as Record<string, unknown>;
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<string, unknown>,
projection: Record<string, 0 | 1> | undefined
): Record<string, unknown> {
if (projection === undefined) {
return { ...doc };
}
const includedKeys = Object.entries(projection)
.filter(([, flag]) => flag === 1)
.map(([key]) => key);
const out: Record<string, unknown> = {};
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<Record<string, readonly Record<string, unknown>[]>>;
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<string, unknown>,
options?: SourceSymbolFindOptions
): Promise<Iterable<T> | AsyncIterable<T>> {
): Promise<AsyncIterable<T>> {
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<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 {
async *[Symbol.asyncIterator](): AsyncIterator<T> {
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<T>(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<never>,
};
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<string, unknown>;
options: SourceSymbolFindOptions | undefined;
}> = [];
const fixtures: Record<string, Record<string, unknown>[]> = {
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<string, unknown>, options?: SourceSymbolFindOptions) {
recordedOptions.push({ collection: name, filter, options });
const docs = fixtures[name] ?? [];
const cursor: ReadOnlySourceSymbolCursor<Record<string, unknown>> & {
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<T extends Record<string, unknown>>(collectionName: string): Iterable<T> {
find<T extends Record<string, unknown>>(collectionName: string): AsyncIterable<T> {
if (collectionName === SOURCE_SYMBOL_COLLECTIONS.eod) {
return {
*[Symbol.iterator](): Iterator<T> {
async *[Symbol.asyncIterator](): AsyncIterator<T> {
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<T> {
async *[Symbol.asyncIterator](): AsyncIterator<T> {
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<T> {
async *[Symbol.asyncIterator](): AsyncIterator<T> {
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<T> {
// empty cursor
},
};
},
};