2006 lines
83 KiB
TypeScript
2006 lines
83 KiB
TypeScript
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 { cusipToIsin } from '../../apps/stock/data-pipeline/src/normalization/identifiers';
|
|
import { parseTickerDetailed } from '../../apps/stock/data-pipeline/src/normalization/ticker';
|
|
import {
|
|
buildSecurityTypeByIsin,
|
|
buildSecurityTypeByIsinForStageA,
|
|
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,
|
|
readEodSymbols,
|
|
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,
|
|
} 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 _exactCollectionClientKeysCheck: AssertExact<
|
|
keyof ReadOnlyMongoCollectionClient,
|
|
'isReadOnly' | 'getCollection'
|
|
> = true;
|
|
const _mongoClientAssignableCheck: MongoDBClientSourceSymbolReaderCheck = 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;
|
|
filter: Record<string, unknown> | undefined;
|
|
options: SourceSymbolFindOptions | undefined;
|
|
}
|
|
|
|
interface FakeReaderOptions {
|
|
readOnly?: boolean;
|
|
applyFilterAndProjection?: boolean;
|
|
failOnCollection?: {
|
|
collection: string;
|
|
afterDocs?: number;
|
|
errorMessage?: string;
|
|
};
|
|
}
|
|
|
|
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 applyFilterAndProjection: 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.applyFilterAndProjection = options.applyFilterAndProjection ?? 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<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] ?? [];
|
|
const failConfig =
|
|
this.failOnCollection !== undefined && this.failOnCollection.collection === collectionName
|
|
? this.failOnCollection
|
|
: undefined;
|
|
const applyQuery = this.applyFilterAndProjection;
|
|
const projection = options?.projection;
|
|
|
|
return {
|
|
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
|
let yielded = 0;
|
|
for (const doc of docs) {
|
|
if (applyQuery && !matchesMongoFilter(doc, filter)) {
|
|
continue;
|
|
}
|
|
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;
|
|
}
|
|
},
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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: 'EDGX', exchangeName: 'Cboe EDGX', 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: 'EDGX', name: 'Cboe EDGX', 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' }),
|
|
];
|
|
|
|
const pass1 = classifySourceExchanges(rawPass1Records);
|
|
return createExchangeSourceLookup([...pass1.mapped, ...extraRows]);
|
|
}
|
|
|
|
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(_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(
|
|
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 = createPass1ExchangeLookup();
|
|
|
|
// 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);
|
|
|
|
// 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 });
|
|
|
|
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 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);
|
|
expect(EOD_SYMBOLS_PROJECTION._id).toBe(0);
|
|
expect(EOD_SYMBOLS_PROJECTION.Type).toBe(1);
|
|
expect(EOD_SYMBOLS_PROJECTION.type).toBe(1);
|
|
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 include spellings and venue fallbacks.
|
|
expect(DEFAULT_SOURCE_COUNTRIES).toEqual(['US', 'CA']);
|
|
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 });
|
|
await readSecurityMasterSources(unfilteredReader, { exchangeLookup, countries: null });
|
|
for (const call of unfilteredReader.calls) {
|
|
expect(call.filter).toEqual({});
|
|
}
|
|
});
|
|
|
|
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, both VOY records, and QM EDGX (AACT.U:EGX)', async () => {
|
|
// Structural integrity of REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS:
|
|
// sorted by (source, sourceCode), zero collisions with explicit baseline,
|
|
// primary_venue rows reference ISO_EXCHANGE_SEEDS with matching countryIso,
|
|
// and ats_routing/composite rows carry mic: null with US/CA countryIso.
|
|
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 (let i = 0; i < REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS.length; i++) {
|
|
const row = REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS[i]!;
|
|
expect(explicitKeys.has(`${row.source}:${row.sourceCode}`)).toBe(false);
|
|
if (i > 0) {
|
|
const prev = REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS[i - 1]!;
|
|
const cmp =
|
|
compareAscii(prev.source, row.source) || compareAscii(prev.sourceCode, row.sourceCode);
|
|
expect(cmp).toBeLessThan(0);
|
|
}
|
|
if (row.role === 'primary_venue') {
|
|
expect(row.mic).not.toBeNull();
|
|
const seed = seedByMic.get(row.mic!);
|
|
expect(seed).toBeDefined();
|
|
expect(row.countryIso).toBe(seed?.countryIso);
|
|
} else {
|
|
expect(row.mic).toBeNull();
|
|
expect(['US', 'CA']).toContain(row.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');
|
|
expect(exchangeLookup.get('qm', 'EDGX')).toMatchObject({
|
|
role: 'ats_routing',
|
|
mic: null,
|
|
countryIso: 'US',
|
|
});
|
|
expect(exchangeLookup.get('ib', 'EDGX')).toMatchObject({
|
|
role: 'ats_routing',
|
|
mic: null,
|
|
countryIso: 'US',
|
|
});
|
|
expect(exchangeLookup.get('qm', 'NYSE American')).toMatchObject({
|
|
role: 'primary_venue',
|
|
mic: 'XASE',
|
|
countryIso: 'US',
|
|
});
|
|
expect(exchangeLookup.get('qm', 'CCQ TSX')).toMatchObject({
|
|
role: 'composite',
|
|
mic: null,
|
|
countryIso: 'CA',
|
|
});
|
|
expect(exchangeLookup.get('qm', 'CCQ TSXV')).toMatchObject({
|
|
role: 'composite',
|
|
mic: null,
|
|
countryIso: 'CA',
|
|
});
|
|
|
|
const barSpans = new BarSpanIndex();
|
|
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: '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 });
|
|
barSpans.merge({ source: 'qm', sourceId: 'AACT.U:EGX', firstBarDate: '2023-05-01', lastBarDate: '2025-06-30', barCount: 540 });
|
|
|
|
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: [
|
|
// Captured phase1-investigation.md:261 shape: SLB with exchangeId='EDGX' (ATS venue)
|
|
{
|
|
conid: 880001,
|
|
symbol: 'SLB',
|
|
localSymbol: 'SLB',
|
|
exchangeId: 'EDGX',
|
|
isin: 'AN8068571086',
|
|
cusip: '806857108',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
},
|
|
],
|
|
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 },
|
|
// Captured phase1-investigation.md:272 shape: AACT.U:EGX with exchange='EDGX', countryCode='US'
|
|
{ qmSearchCode: 'AACT.U:EGX', symbol: 'AACT.U', exchange: 'EDGX', countryCode: 'US', active: true },
|
|
],
|
|
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(4);
|
|
expect(sources.stats.qmSymbols.skips.unmappedExchange).toBe(0);
|
|
assertStatsConservation(sources.stats.qmSymbols);
|
|
|
|
// IB EDGX ATS must not become primaryExchange.
|
|
expect(sources.stageBInput.ibContracts).toEqual([
|
|
{ sourceId: '880001', conid: 880001, currency: 'USD', primaryExchange: null },
|
|
]);
|
|
|
|
// AACT.U:EGX reaches Stage B classified as ats_routing (not dropped as unmappedExchange).
|
|
const aactQm = sources.stageBInput.tickerSources.find(
|
|
t => t.source === 'qm' && t.sourceId === 'AACT.U:EGX'
|
|
);
|
|
expect(aactQm).toMatchObject({
|
|
source: 'qm',
|
|
sourceId: 'AACT.U:EGX',
|
|
ticker: 'AACT.U',
|
|
mic: null,
|
|
role: 'ats_routing',
|
|
currency: 'USD',
|
|
});
|
|
|
|
const stageA = matchInstrumentsStageA(sources.stageARecords);
|
|
const stageB = matchListingsStageB({ instruments: stageA.instruments, ...sources.stageBInput });
|
|
expect(stageB.conflicts).toEqual([]);
|
|
expect(
|
|
stageB.unresolved.find(u => u.source === 'qm' && u.sourceId === 'AACT.U:EGX')
|
|
).toMatchObject({
|
|
source: 'qm',
|
|
sourceId: 'AACT.U:EGX',
|
|
reason: 'ats_routing_venue',
|
|
});
|
|
|
|
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',
|
|
Exchange: 'NASDAQ',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'US0378331005',
|
|
Cusip: '037833100',
|
|
Name: 'Apple Inc.',
|
|
},
|
|
{
|
|
_id: 'eod-2',
|
|
eodSearchCode: 'RY.TO',
|
|
Code: 'RY',
|
|
eodExchange: 'TO',
|
|
Exchange: 'TO',
|
|
Country: 'Canada',
|
|
Currency: 'CAD',
|
|
Isin: 'CA7800871021',
|
|
Cusip: '780087102',
|
|
Name: 'Royal Bank of Canada',
|
|
},
|
|
{
|
|
_id: 'eod-3',
|
|
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'.
|
|
{
|
|
_id: 'eod-4',
|
|
eodSearchCode: 'SHOP.US',
|
|
Code: 'SHOP',
|
|
eodExchange: 'US',
|
|
Exchange: 'NYSE',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'CA82509L1076',
|
|
Cusip: '82509L107',
|
|
Name: 'Shopify Inc.',
|
|
},
|
|
{
|
|
_id: 'eod-5',
|
|
eodSearchCode: 'META.US',
|
|
Code: 'META',
|
|
eodExchange: 'US',
|
|
Exchange: 'NASDAQ',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'US30303M1027',
|
|
Cusip: '30303M102',
|
|
Name: 'Meta Platforms Inc.',
|
|
},
|
|
],
|
|
ibSymbols: [
|
|
{
|
|
_id: 'ib-1',
|
|
conid: 265598,
|
|
symbol: 'AAPL',
|
|
exchangeId: 'ARCAEDGE',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
isin: 'US0378331005',
|
|
cusip: '037833100',
|
|
description: 'APPLE INC',
|
|
},
|
|
{
|
|
_id: 'ib-2',
|
|
conid: 4001,
|
|
symbol: 'RY',
|
|
exchangeId: 'AEQLIT',
|
|
country: 'CA',
|
|
currency: 'CAD',
|
|
isin: 'CA7800871021',
|
|
cusip: '780087102',
|
|
description: 'ROYAL BANK OF CANADA',
|
|
},
|
|
{
|
|
_id: 'ib-3',
|
|
conid: 199100,
|
|
symbol: 'SHOP',
|
|
exchangeId: 'AEQLIT',
|
|
country: 'CA',
|
|
currency: 'CAD',
|
|
isin: 'CA82509L1076',
|
|
cusip: '82509L107',
|
|
description: 'SHOPIFY INC - CLASS A',
|
|
},
|
|
{
|
|
_id: 'ib-4',
|
|
conid: 199101,
|
|
symbol: 'SHOP',
|
|
exchangeId: 'OTCLNKECN',
|
|
country: 'US',
|
|
currency: 'USD',
|
|
isin: 'CA82509L1076',
|
|
cusip: '82509L107',
|
|
description: 'SHOPIFY INC - CLASS A',
|
|
},
|
|
],
|
|
qmSymbols: [
|
|
{ _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: [
|
|
{ _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: 'US',
|
|
effective: '2022-06-09',
|
|
},
|
|
],
|
|
},
|
|
{ readOnly: true, applyFilterAndProjection: 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);
|
|
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(
|
|
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.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 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'
|
|
);
|
|
expect(ceoShopMapping?.listingKey.mic).toBe('XTSE');
|
|
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);
|
|
|
|
// Regression: a supported `get`-only ExchangeSourceLookup (without getCodesForCountries)
|
|
// must use conservative `{}` pushdown so countryless docs (notably stored-shape US
|
|
// eodSymbolChange with exchange='US' and effective, no country field) are not dropped
|
|
// before the adapter enforces the country filter.
|
|
const getOnlyLookup: ExchangeSourceLookup = {
|
|
get: (source, sourceCode) => germanLookup.get(source, sourceCode),
|
|
};
|
|
const getOnlyReader = new FakeSourceSymbolReader(
|
|
{
|
|
eodSymbols: [
|
|
{
|
|
_id: 'eod-noloc-us',
|
|
eodSearchCode: 'AAPL.US',
|
|
Code: 'AAPL',
|
|
Exchange: 'NASDAQ',
|
|
Currency: 'USD',
|
|
Isin: 'US0378331005',
|
|
Name: 'Apple Inc.',
|
|
},
|
|
{
|
|
_id: 'eod-noloc-de',
|
|
eodSearchCode: 'SVQ.F',
|
|
Code: 'SVQ',
|
|
Exchange: 'F',
|
|
Currency: 'EUR',
|
|
Isin: 'DE0007164600',
|
|
Name: 'SAP SE',
|
|
},
|
|
],
|
|
ibSymbols: [],
|
|
qmSymbols: [
|
|
{ _id: 'qm-noloc-us', qmSearchCode: 'AAPL:US', symbol: 'AAPL', exchange: 'NSQ' },
|
|
{ _id: 'qm-noloc-de', qmSearchCode: 'SAP:FRA', symbol: 'SAP', exchange: 'FRA' },
|
|
],
|
|
ceoSymbols: [
|
|
{ _id: 'ceo-noloc-ca', ceoId: 'RY', symbol: 'RY.TO', exchange: 'TSX' },
|
|
],
|
|
eodSymbolChange: [
|
|
{ _id: 'sc-us-stored', oldSymbol: 'FB', newSymbol: 'META', exchange: 'US', effective: '2022-06-09' },
|
|
{ _id: 'sc-de-stored', oldSymbol: 'OLDDE', newSymbol: 'NEWDE', exchange: 'F', effective: '2024-09-01' },
|
|
],
|
|
},
|
|
{ readOnly: true, applyFilterAndProjection: true }
|
|
);
|
|
|
|
const getOnlyResult = await readSecurityMasterSources(getOnlyReader, {
|
|
exchangeLookup: getOnlyLookup,
|
|
});
|
|
|
|
// Conservative `{}` filter used for venue-fallback collections when getCodesForCountries is absent.
|
|
const recordedByCollection = new Map(getOnlyReader.calls.map(c => [c.collectionName, c.filter]));
|
|
expect(recordedByCollection.get('eodSymbols')).toEqual({});
|
|
expect(recordedByCollection.get('qmSymbols')).toEqual({});
|
|
expect(recordedByCollection.get('ceoSymbols')).toEqual({});
|
|
expect(recordedByCollection.get('eodSymbolChange')).toEqual({});
|
|
|
|
// Stored-shape countryless US symbol change survives; out-of-scope German change is counted by adapter.
|
|
expect(getOnlyResult.stats.eodSymbolChange.docsRead).toBe(2);
|
|
expect(getOnlyResult.stats.eodSymbolChange.emitted).toBe(1);
|
|
expect(getOnlyResult.stats.eodSymbolChange.skips.outOfScopeCountry).toBe(1);
|
|
expect(getOnlyResult.stageBInput.symbolChanges).toEqual([
|
|
{
|
|
eodSourceId: 'META.US',
|
|
oldTicker: 'FB',
|
|
effectiveDate: '2022-06-09',
|
|
},
|
|
]);
|
|
assertStatsConservation(getOnlyResult.stats.eodSymbolChange);
|
|
|
|
// Countryless US/CA EOD, QM, and CEO rows also survive; German rows skipped by adapter.
|
|
expect(getOnlyResult.stats.eodSymbols.emitted).toBe(1);
|
|
expect(getOnlyResult.stats.eodSymbols.skips.outOfScopeCountry).toBe(1);
|
|
expect(getOnlyResult.stats.qmSymbols.emitted).toBe(1);
|
|
expect(getOnlyResult.stats.qmSymbols.skips.outOfScopeCountry).toBe(1);
|
|
expect(getOnlyResult.stats.ceoSymbols.emitted).toBe(1);
|
|
assertStatsConservation(getOnlyResult.stats.eodSymbols);
|
|
assertStatsConservation(getOnlyResult.stats.qmSymbols);
|
|
assertStatsConservation(getOnlyResult.stats.ceoSymbols);
|
|
});
|
|
|
|
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 = 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 });
|
|
|
|
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 813137106 + 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 = createPass1ExchangeLookup();
|
|
|
|
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', 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
|
|
],
|
|
});
|
|
|
|
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: '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' },
|
|
],
|
|
},
|
|
{
|
|
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 = createPass1ExchangeLookup();
|
|
|
|
const baseCollections = {
|
|
eodSymbols: [
|
|
{ eodSearchCode: 'Z.US', Code: 'Z', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US98954M1018', Name: 'Zillow', Type: 'Common Stock' },
|
|
{ eodSearchCode: 'AAPL.US', Code: 'AAPL', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US0378331005', Name: 'Apple', Type: 'Common Stock' },
|
|
// 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', Type: 'ETF' },
|
|
{ eodSearchCode: 'DUP.US', Code: 'DUP', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Name: 'Dup A', Type: 'ETF' },
|
|
{ eodSearchCode: 'RY.TO', Code: 'RY', Exchange: 'TO', Country: 'Canada', Currency: 'CAD', Isin: 'CA7800871021', Name: 'RBC', type: 'Common Stock' },
|
|
],
|
|
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: 'US', effective: '2022-06-09' },
|
|
{ oldSymbol: 'ANTM', newSymbol: 'ELV', exchange: 'US', effective: '2022-06-28' },
|
|
],
|
|
};
|
|
|
|
const baseline = await readSecurityMasterSources(new FakeSourceSymbolReader(baseCollections), {
|
|
exchangeLookup,
|
|
});
|
|
const baselineJson = JSON.stringify(baseline);
|
|
const baselineTypeEntries = [...baseline.securityTypeByIsin.entries()];
|
|
expect(baselineTypeEntries).toEqual([
|
|
['CA7800871021', 'common'],
|
|
['US0378331005', 'common'],
|
|
['US98954M1018', 'common'],
|
|
]);
|
|
|
|
// 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);
|
|
expect([...candidate.securityTypeByIsin.entries()]).toEqual(baselineTypeEntries);
|
|
}
|
|
|
|
// Reversed-input determinism fixture: duplicate rows sharing (sourceId, isin) with distinct
|
|
// object/array malformed `Type` values normalize to a single `null` missing-type sentinel so
|
|
// `securityTypeRecords` order is cursor-order independent.
|
|
const malformedDocs = [
|
|
{
|
|
eodSearchCode: 'MALF.US',
|
|
Code: 'MALF',
|
|
Exchange: 'NASDAQ',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'US0378331005',
|
|
Name: 'Malformed Type Co',
|
|
Type: { kind: 'A', nested: 1 } as unknown as string,
|
|
},
|
|
{
|
|
eodSearchCode: 'MALF.US',
|
|
Code: 'MALF',
|
|
Exchange: 'NASDAQ',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'US0378331005',
|
|
Name: 'Malformed Type Co',
|
|
Type: { kind: 'B', nested: 2 } as unknown as string,
|
|
},
|
|
{
|
|
eodSearchCode: 'MALF.US',
|
|
Code: 'MALF',
|
|
Exchange: 'NASDAQ',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'US0378331005',
|
|
Name: 'Malformed Type Co',
|
|
Type: ['ETF'] as unknown as string,
|
|
},
|
|
];
|
|
const forwardMalformed = await readSecurityMasterSources(
|
|
new FakeSourceSymbolReader({ eodSymbols: malformedDocs }),
|
|
{ exchangeLookup }
|
|
);
|
|
const reversedMalformed = await readSecurityMasterSources(
|
|
new FakeSourceSymbolReader({ eodSymbols: [...malformedDocs].reverse() }),
|
|
{ exchangeLookup }
|
|
);
|
|
expect(JSON.stringify(reversedMalformed)).toBe(JSON.stringify(forwardMalformed));
|
|
expect(forwardMalformed.securityTypeRecords).toEqual([
|
|
{ isin: 'US0378331005', rawType: null, sourceId: 'MALF.US' },
|
|
{ isin: 'US0378331005', rawType: null, sourceId: 'MALF.US' },
|
|
{ isin: 'US0378331005', rawType: null, sourceId: 'MALF.US' },
|
|
]);
|
|
expect(forwardMalformed.securityTypeStats.missingType).toBe(3);
|
|
});
|
|
|
|
test('security-type wiring & Stage A integration: maps typed EOD docs (including lowercase type and CUSIP-derived ISIN), keeps non-string Type docs, and reports conflicts/unknowns', async () => {
|
|
const exchangeLookup = createPass1ExchangeLookup();
|
|
const expectedDerivedCaIsin = cusipToIsin('813137106', 'CA');
|
|
expect(expectedDerivedCaIsin).not.toBeNull();
|
|
|
|
const reader = new FakeSourceSymbolReader(
|
|
{
|
|
eodSymbols: [
|
|
// Standard Type: 'Common Stock'
|
|
{
|
|
eodSearchCode: 'AAPL.US',
|
|
Code: 'AAPL',
|
|
Exchange: 'NASDAQ',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'US0378331005',
|
|
Name: 'Apple Inc.',
|
|
Type: 'Common Stock',
|
|
},
|
|
// Lowercase `type` fallback
|
|
{
|
|
eodSearchCode: 'SPY.US',
|
|
Code: 'SPY',
|
|
Exchange: 'NYSE',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'US78462F1030',
|
|
Name: 'SPDR S&P 500 ETF',
|
|
type: 'etf',
|
|
},
|
|
// CUSIP-derived ISIN: bad ISIN check digit with CA prefix + valid CUSIP 813137106
|
|
{
|
|
eodSearchCode: 'SCU-UN.TO',
|
|
Code: 'SCU-UN',
|
|
Exchange: 'TO',
|
|
Country: 'Canada',
|
|
Currency: 'CAD',
|
|
Isin: 'CA8131391062',
|
|
Cusip: '813137106',
|
|
Name: 'Second Cup Income Fund',
|
|
Type: 'Unit',
|
|
},
|
|
// Non-string Type must NOT skip the doc (emitted to Stage A/B, counted in missingType)
|
|
{
|
|
eodSearchCode: 'RY.TO',
|
|
Code: 'RY',
|
|
Exchange: 'TO',
|
|
Country: 'Canada',
|
|
Currency: 'CAD',
|
|
Isin: 'CA7800871021',
|
|
Name: 'Royal Bank of Canada',
|
|
Type: 42 as unknown as string,
|
|
},
|
|
// Unknown Type ('Mutual Fund') emitted to Stage A/B, omitted from securityTypeByIsin
|
|
{
|
|
eodSearchCode: 'META.US',
|
|
Code: 'META',
|
|
Exchange: 'NASDAQ',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'US30303M1027',
|
|
Name: 'Meta Platforms Inc.',
|
|
Type: 'Mutual Fund',
|
|
},
|
|
// Conflicting types across two EOD docs sharing the same ISIN (SHOP)
|
|
{
|
|
eodSearchCode: 'SHOP.TO',
|
|
Code: 'SHOP',
|
|
Exchange: 'TO',
|
|
Country: 'Canada',
|
|
Currency: 'CAD',
|
|
Isin: 'CA82509L1076',
|
|
Name: 'Shopify Inc.',
|
|
Type: 'Common Stock',
|
|
},
|
|
{
|
|
eodSearchCode: 'SHOP.US',
|
|
Code: 'SHOP',
|
|
Exchange: 'NYSE',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'CA82509L1076',
|
|
Name: 'Shopify Inc.',
|
|
Type: 'ETF',
|
|
},
|
|
],
|
|
ibSymbols: [],
|
|
qmSymbols: [],
|
|
ceoSymbols: [],
|
|
eodSymbolChange: [],
|
|
},
|
|
{ readOnly: true, applyFilterAndProjection: true }
|
|
);
|
|
|
|
const sources = await readSecurityMasterSources(reader, { exchangeLookup });
|
|
|
|
// All 7 EOD docs emitted (non-string Type did NOT trigger invalidFieldType skip).
|
|
expect(sources.stats.eodSymbols.docsRead).toBe(7);
|
|
expect(sources.stats.eodSymbols.emitted).toBe(7);
|
|
expect(sources.stats.eodSymbols.skips.invalidFieldType).toBe(0);
|
|
assertStatsConservation(sources.stats.eodSymbols);
|
|
|
|
// Check securityTypeByIsin contents and stats.
|
|
expect([...sources.securityTypeByIsin.entries()]).toEqual([
|
|
[expectedDerivedCaIsin!, 'unit'],
|
|
['US0378331005', 'common'],
|
|
['US78462F1030', 'etf'],
|
|
]);
|
|
expect(sources.unknownSecurityTypes).toEqual([{ rawType: 'Mutual Fund', count: 1 }]);
|
|
expect(sources.securityTypeConflicts).toEqual([
|
|
{
|
|
isin: 'CA82509L1076',
|
|
types: ['common', 'etf'],
|
|
sourceIds: ['SHOP.TO', 'SHOP.US'],
|
|
recordCount: 2,
|
|
},
|
|
]);
|
|
expect(sources.securityTypeStats).toEqual({
|
|
recordsIn: 7,
|
|
classified: 5,
|
|
missingIsin: 0,
|
|
missingType: 1,
|
|
unknownType: 1,
|
|
distinctClassifiedIsins: 4,
|
|
isinsMapped: 3,
|
|
isinsConflicting: 1,
|
|
conflictsTruncated: 0,
|
|
});
|
|
expect(sources.securityTypeLoaderStats).toEqual(sources.securityTypeStats);
|
|
|
|
// Feed reader output directly into Stage A and verify every typed non-conflicting EOD instrument
|
|
// resolves to an ISIN present in securityTypeByIsin (zero missing_security_type skips in persistSecurityMaster).
|
|
const stageA = matchInstrumentsStageA(sources.stageARecords);
|
|
expect(stageA.conflicts).toEqual([]);
|
|
expect(stageA.unresolved).toEqual([]);
|
|
|
|
const stageAIsins = new Set(stageA.instruments.map(i => i.primaryIsin));
|
|
expect(stageAIsins).toEqual(
|
|
new Set([
|
|
'US0378331005',
|
|
'US78462F1030',
|
|
expectedDerivedCaIsin!,
|
|
'CA7800871021',
|
|
'US30303M1027',
|
|
'CA82509L1076',
|
|
])
|
|
);
|
|
|
|
const typedNonConflictingIsins = ['US0378331005', 'US78462F1030', expectedDerivedCaIsin!];
|
|
const missingForTyped = stageA.instruments.filter(
|
|
inst =>
|
|
typedNonConflictingIsins.includes(inst.primaryIsin) &&
|
|
!sources.securityTypeByIsin.has(inst.primaryIsin)
|
|
);
|
|
expect(missingForTyped).toEqual([]);
|
|
|
|
// Untyped, unknown-typed, and conflicting instruments are omitted from securityTypeByIsin.
|
|
expect(sources.securityTypeByIsin.has('CA7800871021')).toBe(false);
|
|
expect(sources.securityTypeByIsin.has('US30303M1027')).toBe(false);
|
|
expect(sources.securityTypeByIsin.has('CA82509L1076')).toBe(false);
|
|
});
|
|
|
|
test('regression: Stage A-quarantined EOD rows cannot veto a valid member type or supply a type, while raw emitted rows remain available for vocabulary diagnostics', async () => {
|
|
const exchangeLookup = createPass1ExchangeLookup();
|
|
|
|
const reader = new FakeSourceSymbolReader(
|
|
{
|
|
eodSymbols: [
|
|
// Valid EOD Common Stock row for AAPL (matching ISIN + CUSIP)
|
|
{
|
|
eodSearchCode: 'AAPL.US',
|
|
Code: 'AAPL',
|
|
Exchange: 'NASDAQ',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'US0378331005',
|
|
Cusip: '037833100',
|
|
Name: 'Apple Inc.',
|
|
Type: 'Common Stock',
|
|
},
|
|
// Stale EOD ETF row sharing AAPL's valid ISIN but carrying SPY's valid CUSIP ->
|
|
// Stage A quarantines as `isin_cusip_mismatch`. Must NOT veto AAPL's 'common' type.
|
|
{
|
|
eodSearchCode: 'AAPL_STALE.US',
|
|
Code: 'AAPL',
|
|
Exchange: 'NYSE',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'US0378331005',
|
|
Cusip: '78462F103',
|
|
Name: 'Stale Apple ETF Row',
|
|
Type: 'ETF',
|
|
},
|
|
// Quarantined-only EOD row with an unmapped raw Type -> must NOT supply a type,
|
|
// but its raw Type must stay available in `securityTypeRecords` for vocabulary diagnostics.
|
|
{
|
|
eodSearchCode: 'BAD_ONLY.US',
|
|
Code: 'BADO',
|
|
Exchange: 'NASDAQ',
|
|
Country: 'USA',
|
|
Currency: 'USD',
|
|
Isin: 'US30303M1027',
|
|
Cusip: '037833100',
|
|
Name: 'Mismatched Meta Row',
|
|
Type: 'Structured Note',
|
|
},
|
|
// Duplicate EOD sourceId -> Stage A quarantines both as `duplicate_source_id`.
|
|
// Must NOT supply a type for CA7800871021.
|
|
{
|
|
eodSearchCode: 'DUP.TO',
|
|
Code: 'RY',
|
|
Exchange: 'TO',
|
|
Country: 'Canada',
|
|
Currency: 'CAD',
|
|
Isin: 'CA7800871021',
|
|
Name: 'Royal Bank Dup 1',
|
|
Type: 'Preferred Stock',
|
|
},
|
|
{
|
|
eodSearchCode: 'DUP.TO',
|
|
Code: 'RY',
|
|
Exchange: 'TO',
|
|
Country: 'Canada',
|
|
Currency: 'CAD',
|
|
Isin: 'CA7800871021',
|
|
Name: 'Royal Bank Dup 2',
|
|
Type: 'Preferred Stock',
|
|
},
|
|
],
|
|
ibSymbols: [],
|
|
qmSymbols: [],
|
|
ceoSymbols: [],
|
|
eodSymbolChange: [],
|
|
},
|
|
{ readOnly: true, applyFilterAndProjection: true }
|
|
);
|
|
|
|
const sources = await readSecurityMasterSources(reader, { exchangeLookup });
|
|
assertStatsConservation(sources.stats.eodSymbols);
|
|
expect(sources.stats.eodSymbols.docsRead).toBe(5);
|
|
expect(sources.stats.eodSymbols.emitted).toBe(5);
|
|
|
|
const stageA = matchInstrumentsStageA(sources.stageARecords);
|
|
expect(stageA.instruments.map(i => i.primaryIsin)).toEqual(['US0378331005']);
|
|
expect(stageA.instruments[0]?.members.map(m => m.sourceId)).toEqual(['AAPL.US']);
|
|
expect(
|
|
stageA.conflicts.map(c => `${c.sourceId}:${c.conflictKind}`).sort(compareAscii)
|
|
).toEqual([
|
|
'AAPL_STALE.US:isin_cusip_mismatch',
|
|
'BAD_ONLY.US:isin_cusip_mismatch',
|
|
'DUP.TO:duplicate_source_id',
|
|
'DUP.TO:duplicate_source_id',
|
|
]);
|
|
|
|
// Loader-facing map, conflicts, and loader stats reflect ONLY Stage A-accepted EOD members.
|
|
expect([...sources.securityTypeByIsin.entries()]).toEqual([['US0378331005', 'common']]);
|
|
expect(sources.securityTypeConflicts).toEqual([]);
|
|
expect(sources.securityTypeByIsin.has('US30303M1027')).toBe(false);
|
|
expect(sources.securityTypeByIsin.has('CA7800871021')).toBe(false);
|
|
expect(sources.securityTypeLoaderStats).toEqual({
|
|
recordsIn: 1,
|
|
classified: 1,
|
|
missingIsin: 0,
|
|
missingType: 0,
|
|
unknownType: 0,
|
|
distinctClassifiedIsins: 1,
|
|
isinsMapped: 1,
|
|
isinsConflicting: 0,
|
|
conflictsTruncated: 0,
|
|
});
|
|
|
|
// Returned vocabulary diagnostics (`securityTypeStats` & `unknownSecurityTypes`) cover ALL 5
|
|
// emitted EOD rows directly, including quarantined rows like `Structured Note`.
|
|
expect(sources.securityTypeStats).toEqual({
|
|
recordsIn: 5,
|
|
classified: 4,
|
|
missingIsin: 0,
|
|
missingType: 0,
|
|
unknownType: 1,
|
|
distinctClassifiedIsins: 2,
|
|
isinsMapped: 1,
|
|
isinsConflicting: 1,
|
|
conflictsTruncated: 0,
|
|
});
|
|
expect(sources.unknownSecurityTypes).toEqual([{ rawType: 'Structured Note', count: 1 }]);
|
|
|
|
// Helper produces the identical loader-facing map when called explicitly after Stage A.
|
|
const explicitStageAMap = buildSecurityTypeByIsinForStageA(
|
|
sources.securityTypeRecords,
|
|
stageA.instruments
|
|
);
|
|
expect([...explicitStageAMap.securityTypeByIsin.entries()]).toEqual([
|
|
...sources.securityTypeByIsin.entries(),
|
|
]);
|
|
expect(explicitStageAMap.stats).toEqual(sources.securityTypeLoaderStats);
|
|
|
|
// All 5 emitted EOD rows also remain available in `securityTypeRecords` and reconcile with returned diagnostics.
|
|
expect(sources.securityTypeRecords.length).toBe(5);
|
|
const rawDiagnostics = buildSecurityTypeByIsin(sources.securityTypeRecords);
|
|
expect(rawDiagnostics.stats).toEqual(sources.securityTypeStats);
|
|
expect(rawDiagnostics.unknownRawTypes).toEqual(sources.unknownSecurityTypes);
|
|
});
|
|
|
|
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 = createPass1ExchangeLookup();
|
|
|
|
// 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): AsyncIterable<T> {
|
|
if (collectionName === SOURCE_SYMBOL_COLLECTIONS.eod) {
|
|
return {
|
|
async *[Symbol.asyncIterator](): AsyncIterator<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 {
|
|
async *[Symbol.asyncIterator](): AsyncIterator<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 {
|
|
async *[Symbol.asyncIterator](): AsyncIterator<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 {
|
|
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
|
// empty cursor
|
|
},
|
|
};
|
|
},
|
|
};
|
|
|
|
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);
|
|
});
|
|
});
|
|
|
|
describe('security-master source-symbol-readers security-type QA edges', () => {
|
|
test('Type/type precedence: blank or non-string `Type` falls back to string `type`; string `Type` wins over `type`', async () => {
|
|
const exchangeLookup = createPass1ExchangeLookup();
|
|
const base = { Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD' };
|
|
const reader = new FakeSourceSymbolReader(
|
|
{
|
|
eodSymbols: [
|
|
{ ...base, eodSearchCode: 'AAPL.US', Code: 'AAPL', Isin: 'US0378331005', Name: 'Apple', Type: ' ', type: 'Common Stock' },
|
|
{ ...base, eodSearchCode: 'SPY.US', Code: 'SPY', Isin: 'US78462F1030', Name: 'SPY', Type: 7, type: 'ETF' },
|
|
{ ...base, eodSearchCode: 'Z.US', Code: 'Z', Isin: 'US98954M1018', Name: 'Zillow', Type: 'Common Stock', type: 'ETF' },
|
|
],
|
|
ibSymbols: [],
|
|
qmSymbols: [],
|
|
ceoSymbols: [],
|
|
eodSymbolChange: [],
|
|
},
|
|
{ readOnly: true, applyFilterAndProjection: true }
|
|
);
|
|
|
|
const sources = await readSecurityMasterSources(reader, { exchangeLookup });
|
|
|
|
assertStatsConservation(sources.stats.eodSymbols);
|
|
expect(sources.stats.eodSymbols.emitted).toBe(3);
|
|
expect([...sources.securityTypeByIsin.entries()]).toEqual([
|
|
['US0378331005', 'common'],
|
|
['US78462F1030', 'etf'],
|
|
['US98954M1018', 'common'],
|
|
]);
|
|
expect(sources.securityTypeStats.missingType).toBe(0);
|
|
expect(sources.securityTypeConflicts).toEqual([]);
|
|
});
|
|
|
|
test('mixed EOD + IB sources: full-source Stage A EOD members all have a loader type, IB-only instruments are not typed', async () => {
|
|
const exchangeLookup = createPass1ExchangeLookup();
|
|
const reader = new FakeSourceSymbolReader(
|
|
{
|
|
eodSymbols: [
|
|
{ eodSearchCode: 'AAPL.US', Code: 'AAPL', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US0378331005', Name: 'Apple', Type: 'Common Stock' },
|
|
{ eodSearchCode: 'SHOP.TO', Code: 'SHOP', Exchange: 'TO', Country: 'Canada', Currency: 'CAD', Isin: 'CA82509L1076', Name: 'Shopify', Type: 'Common Stock' },
|
|
{ eodSearchCode: 'SHOP.US', Code: 'SHOP', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Isin: 'CA82509L1076', Name: 'Shopify', Type: 'common stock' },
|
|
],
|
|
ibSymbols: [
|
|
{ conid: 265598, symbol: 'AAPL', exchangeId: 'NASDAQ', country: 'US', currency: 'USD', isin: 'US0378331005' },
|
|
{ conid: 900, symbol: 'Z', exchangeId: 'NASDAQ', country: 'US', currency: 'USD', isin: 'US98954M1018' },
|
|
],
|
|
qmSymbols: [],
|
|
ceoSymbols: [],
|
|
eodSymbolChange: [],
|
|
},
|
|
{ readOnly: true, applyFilterAndProjection: true }
|
|
);
|
|
|
|
const sources = await readSecurityMasterSources(reader, { exchangeLookup });
|
|
assertStatsConservation(sources.stats.eodSymbols);
|
|
assertStatsConservation(sources.stats.ibSymbols);
|
|
|
|
// Same Stage A that the orchestrator will run over every source.
|
|
const stageA = matchInstrumentsStageA(sources.stageARecords);
|
|
const withEodMember = stageA.instruments.filter(inst => inst.members.some(m => m.source === 'eod'));
|
|
expect(withEodMember.map(i => i.primaryIsin)).toEqual(['CA82509L1076', 'US0378331005']);
|
|
for (const inst of withEodMember) {
|
|
expect(sources.securityTypeByIsin.get(inst.primaryIsin)).toBe('common');
|
|
}
|
|
// Zillow is IB-only: IB type inference is out of scope, so it stays untyped (no guessing).
|
|
expect(stageA.instruments.some(i => i.primaryIsin === 'US98954M1018')).toBe(true);
|
|
expect(sources.securityTypeByIsin.has('US98954M1018')).toBe(false);
|
|
expect(sources.securityTypeLoaderStats.isinsMapped).toBe(2);
|
|
expect(sources.securityTypeLoaderStats.recordsIn).toBe(3);
|
|
});
|
|
|
|
test('maxSecurityTypeConflicts option caps loader conflicts and invalid values reject', async () => {
|
|
const exchangeLookup = createPass1ExchangeLookup();
|
|
const docs = [
|
|
{ eodSearchCode: 'SHOP.TO', Code: 'SHOP', Exchange: 'TO', Country: 'Canada', Currency: 'CAD', Isin: 'CA82509L1076', Name: 'Shopify', Type: 'Common Stock' },
|
|
{ eodSearchCode: 'SHOP.US', Code: 'SHOP', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Isin: 'CA82509L1076', Name: 'Shopify', Type: 'ETF' },
|
|
{ eodSearchCode: 'AAPL.US', Code: 'AAPL', Exchange: 'NASDAQ', Country: 'USA', Currency: 'USD', Isin: 'US0378331005', Name: 'Apple', Type: 'Common Stock' },
|
|
{ eodSearchCode: 'AAPL.NEO', Code: 'AAPL', Exchange: 'NYSE', Country: 'USA', Currency: 'USD', Isin: 'US0378331005', Name: 'Apple', Type: 'CDR' },
|
|
];
|
|
const make = () =>
|
|
new FakeSourceSymbolReader(
|
|
{ eodSymbols: docs, ibSymbols: [], qmSymbols: [], ceoSymbols: [], eodSymbolChange: [] },
|
|
{ readOnly: true, applyFilterAndProjection: true }
|
|
);
|
|
|
|
const capped = await readSecurityMasterSources(make(), { exchangeLookup, maxSecurityTypeConflicts: 1 });
|
|
expect(capped.securityTypeByIsin.size).toBe(0);
|
|
expect(capped.securityTypeConflicts.map(c => c.isin)).toEqual(['CA82509L1076']);
|
|
expect(capped.securityTypeLoaderStats.isinsConflicting).toBe(2);
|
|
expect(capped.securityTypeLoaderStats.conflictsTruncated).toBe(1);
|
|
|
|
await expect(
|
|
readSecurityMasterSources(make(), { exchangeLookup, maxSecurityTypeConflicts: -1 })
|
|
).rejects.toThrow(RangeError);
|
|
});
|
|
|
|
test('readEodSymbols on an empty collection returns an empty map and zeroed stats', async () => {
|
|
const reader = new FakeSourceSymbolReader(
|
|
{ eodSymbols: [] },
|
|
{ readOnly: true, applyFilterAndProjection: true }
|
|
);
|
|
const result = await readEodSymbols(reader, { exchangeLookup: createPass1ExchangeLookup() });
|
|
expect(result.securityTypeByIsin.size).toBe(0);
|
|
expect(result.securityTypeRecords).toEqual([]);
|
|
expect(result.unknownSecurityTypes).toEqual([]);
|
|
expect(result.securityTypeConflicts).toEqual([]);
|
|
expect(result.securityTypeStats.recordsIn).toBe(0);
|
|
expect(result.securityTypeLoaderStats.recordsIn).toBe(0);
|
|
assertStatsConservation(result.stats);
|
|
});
|
|
});
|