T-40: M1.1c — Pass 1 exchanges: ISO MIC seed, source-code role classifier and reviewable seed-SQL generator

This commit is contained in:
Studio 2026-11-27 14:56:52 -05:00
parent 2dbfb7e5bc
commit c36f89352c
12 changed files with 1848 additions and 20 deletions

View file

@ -20,6 +20,7 @@ const MASTER_FILES = [
'04-provider-exchange-mapping-schema.sql',
'05-add-visible-column.sql',
'34-security-master.sql',
'35-security-master-exchange-seed.sql',
];
const LEGACY_MASTER_TABLES = [
@ -136,13 +137,13 @@ async function createIsolatedFixture() {
}
describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
test('Case A: init SQL 01-34 contain no CREATE DATABASE/\\c and create all master and research tables', async () => {
test('Case A: init SQL 01-35 contain no CREATE DATABASE/\\c and create all master and research tables', async () => {
const f = await createIsolatedFixture();
const sqlFiles = readdirSync(initDir)
.filter(file => file.endsWith('.sql'))
.sort();
expect(sqlFiles.length).toBeGreaterThanOrEqual(34);
expect(sqlFiles.length).toBeGreaterThanOrEqual(35);
for (const file of sqlFiles) {
const sql = readFileSync(join(initDir, file), 'utf8');
@ -176,7 +177,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
expect(await f.hasColumn('backtest_results', 'canonical_result')).toBe(true);
});
test('Case B: master track creates master tables, records exact 6 files, and is idempotent', async () => {
test('Case B: master track creates master tables, records exact 7 files, and is idempotent', async () => {
const f = await createIsolatedFixture();
const first = await runPostgresMigrations(f.postgres, { track: 'master' });

View file

@ -367,7 +367,7 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
).toBe(1);
});
test('34-security-master.sql is applied on master and all tracks, excluded from research, and idempotent', async () => {
test('34-security-master.sql and 35-security-master-exchange-seed.sql are applied on master and all tracks, excluded from research, and idempotent', async () => {
const securityMasterTables = [
'exchange',
'exchange_source_map',
@ -382,13 +382,16 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
'golden_field_audit',
];
// 1. research track must NOT apply 34-security-master.sql or create any of its 11 tables;
// master track applies it and is idempotent on re-run.
// 1. research track must NOT apply 34-security-master.sql or 35-security-master-exchange-seed.sql;
// master track applies both in order and is idempotent on re-run.
const f1 = await fixture();
const runner1 = f1.startup();
const researchApplied = await runner1.runTrack('research');
expect(researchApplied).not.toContain('34-security-master.sql');
expect(await f1.recorded()).not.toContain('34-security-master.sql');
expect(researchApplied).not.toContain('35-security-master-exchange-seed.sql');
const recordedAfterResearch = await f1.recorded();
expect(recordedAfterResearch).not.toContain('34-security-master.sql');
expect(recordedAfterResearch).not.toContain('35-security-master-exchange-seed.sql');
const tablesAfterResearch = new Set(await f1.relations());
for (const table of securityMasterTables) {
@ -397,7 +400,13 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
const masterApplied = await runner1.runTrack('master');
expect(masterApplied).toContain('34-security-master.sql');
expect(await f1.recorded()).toContain('34-security-master.sql');
expect(masterApplied).toContain('35-security-master-exchange-seed.sql');
expect(masterApplied.indexOf('35-security-master-exchange-seed.sql')).toBe(
masterApplied.indexOf('34-security-master.sql') + 1
);
const recordedAfterMaster = await f1.recorded();
expect(recordedAfterMaster).toContain('34-security-master.sql');
expect(recordedAfterMaster).toContain('35-security-master-exchange-seed.sql');
const tablesAfterMaster = new Set(await f1.relations());
for (const table of securityMasterTables) {
@ -406,7 +415,7 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
expect(await runner1.runTrack('master')).toEqual([]);
// 2. all track applies 34-security-master.sql alongside 01-05 and 09-33 and is idempotent.
// 2. all track applies 34 and 35 alongside 01-05 and 09-33 and is idempotent.
const f2 = await fixture();
const runner2 = f2.startup();
const allApplied = await runner2.runTrack('all');
@ -415,7 +424,10 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
expect(allApplied).toContain('09-backtest-run-contract.sql');
expect(allApplied).toContain('33-candidate-decimal-normalization.sql');
expect(allApplied).toContain('34-security-master.sql');
expect(await f2.recorded()).toContain('34-security-master.sql');
expect(allApplied).toContain('35-security-master-exchange-seed.sql');
const recordedAfterAll = await f2.recorded();
expect(recordedAfterAll).toContain('34-security-master.sql');
expect(recordedAfterAll).toContain('35-security-master-exchange-seed.sql');
const tablesAfterAll = new Set(await f2.relations());
for (const table of securityMasterTables) {

View file

@ -0,0 +1,227 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('security-master-exchange-seed-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const exchangeSeedSqlPath = fileURLToPath(
new URL('../../database/postgres/init/35-security-master-exchange-seed.sql', import.meta.url)
);
const REQUIRED_US_MICS = ['ARCX', 'BATS', 'IEXG', 'OTCM', 'XASE', 'XNAS', 'XNYS'] as const;
const REQUIRED_CA_MICS = ['NEOE', 'XCNQ', 'XTSE', 'XTSX'] as const;
const REQUIRED_MICS = [...REQUIRED_US_MICS, ...REQUIRED_CA_MICS] as const;
const IB_ATS_ROUTING_CODES = [
'AEQLIT',
'ARCAEDGE',
'BEX',
'DRCTEDGE',
'EDGEA',
'IBEOS',
'IEX',
'MEMX',
'OTCLNKECN',
'PSX',
] as const;
const cleanup: (() => Promise<void> | void)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function createIsolatedFixture() {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Dedicated stock_bot_safety database required');
}
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: url,
options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
});
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', {
get: () => ({
connect: () => pool.connect(),
}),
});
await runPostgresMigrations(postgres, { track: 'master' });
return { pool, schema, postgres };
}
describe.skipIf(!url)('security master Pass 1 exchange seed migration', () => {
test('seeds all 11 required US+CA ISO MICs and explicit source mappings with referential integrity', async () => {
const f = await createIsolatedFixture();
const exchanges = (
await f.pool.query(
`SELECT mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy
FROM exchange
ORDER BY mic`
)
).rows as Array<{
mic: string;
operating_mic: string;
name: string;
country_iso: string;
currency: string;
timezone: string;
calendar_code: string;
board_lot_policy: string;
}>;
const exchangeByMic = new Map(exchanges.map(row => [row.mic, row]));
for (const mic of REQUIRED_MICS) {
const row = exchangeByMic.get(mic);
expect(row).toBeDefined();
expect(row?.timezone.trim().length).toBeGreaterThan(0);
expect(row?.calendar_code.trim().length).toBeGreaterThan(0);
}
for (const caMic of REQUIRED_CA_MICS) {
const row = exchangeByMic.get(caMic);
expect(row?.board_lot_policy).toBe('tsx_tiered');
expect(row?.country_iso).toBe('CA');
expect(row?.currency).toBe('CAD');
}
for (const usMic of REQUIRED_US_MICS) {
const row = exchangeByMic.get(usMic);
expect(row?.board_lot_policy).toBe('us_100');
expect(row?.country_iso).toBe('US');
expect(row?.currency).toBe('USD');
}
const mappings = (
await f.pool.query(
`SELECT source, source_code, role, mic, country_iso, method, reviewed_by
FROM exchange_source_map
ORDER BY source, source_code`
)
).rows as Array<{
source: string;
source_code: string;
role: string;
mic: string | null;
country_iso: string | null;
method: string;
reviewed_by: string | null;
}>;
const mappingByKey = new Map(mappings.map(row => [`${row.source}:${row.source_code}`, row]));
// CEO primary venues
expect(mappingByKey.get('ceo:TSX')).toMatchObject({ role: 'primary_venue', mic: 'XTSE' });
expect(mappingByKey.get('ceo:CDX')).toMatchObject({ role: 'primary_venue', mic: 'XTSX' });
expect(mappingByKey.get('ceo:CNQ')).toMatchObject({ role: 'primary_venue', mic: 'XCNQ' });
expect(mappingByKey.get('ceo:AQL')).toMatchObject({ role: 'primary_venue', mic: 'NEOE' });
// EOD non-venue / composite / forex codes
expect(mappingByKey.get('eod:US')).toMatchObject({ role: 'composite', mic: null });
expect(mappingByKey.get('eod:NMFQS')).toMatchObject({ role: 'excluded_fund', mic: null });
expect(mappingByKey.get('eod:FOREX')).toMatchObject({ role: 'forex', mic: null });
// IB ATS routing codes
for (const code of IB_ATS_ROUTING_CODES) {
expect(mappingByKey.get(`ib:${code}`)).toMatchObject({ role: 'ats_routing', mic: null });
}
// Every non-null exchange_source_map.mic resolves to an exchange row
const orphanCount = (
await f.pool.query(
`SELECT count(*)::int AS count
FROM exchange_source_map m
LEFT JOIN exchange e ON e.mic = m.mic
WHERE m.mic IS NOT NULL AND e.mic IS NULL`
)
).rows[0].count as number;
expect(orphanCount).toBe(0);
});
test('is idempotent on raw SQL re-apply, preserves reviewed rows, and refreshes unreviewed rows', async () => {
const f = await createIsolatedFixture();
const rawSql = readFileSync(exchangeSeedSqlPath, 'utf8');
const countRows = async () => ({
exchanges: (await f.pool.query('SELECT count(*)::int AS count FROM exchange')).rows[0]
.count as number,
mappings: (await f.pool.query('SELECT count(*)::int AS count FROM exchange_source_map'))
.rows[0].count as number,
});
const initialCounts = await countRows();
expect(initialCounts.exchanges).toBe(11);
expect(initialCounts.mappings).toBe(17);
// Re-apply twice: row counts stay identical
await f.pool.query(rawSql);
await f.pool.query(rawSql);
expect(await countRows()).toEqual(initialCounts);
// Director-reviewed override must NOT be overwritten by re-apply
await f.pool.query(
`UPDATE exchange_source_map
SET role = 'primary_venue', mic = 'XNYS', method = 'director_override', reviewed_by = 'director'
WHERE source = 'eod' AND source_code = 'US'`
);
// Unreviewed row modification SHOULD be refreshed back to seed values on re-apply
await f.pool.query(
`UPDATE exchange_source_map
SET role = 'composite', mic = NULL, method = 'stale_value'
WHERE source = 'ceo' AND source_code = 'TSX' AND reviewed_by IS NULL`
);
await f.pool.query(rawSql);
const reviewedRow = (
await f.pool.query(
`SELECT role, mic, method, reviewed_by
FROM exchange_source_map
WHERE source = 'eod' AND source_code = 'US'`
)
).rows[0];
expect(reviewedRow).toEqual({
role: 'primary_venue',
mic: 'XNYS',
method: 'director_override',
reviewed_by: 'director',
});
const refreshedRow = (
await f.pool.query(
`SELECT role, mic, method, reviewed_by
FROM exchange_source_map
WHERE source = 'ceo' AND source_code = 'TSX'`
)
).rows[0];
expect(refreshedRow).toEqual({
role: 'primary_venue',
mic: 'XTSE',
method: 'explicit_rule',
reviewed_by: null,
});
expect(await countRows()).toEqual(initialCounts);
});
});

View file

@ -85,6 +85,37 @@ async function expectPgErrorCode(operation: Promise<unknown>, expectedCode: stri
throw new Error(`Expected PostgreSQL error code ${expectedCode}, but query succeeded`);
}
async function ensureExchange(
pool: Pool,
mic: string,
overrides: {
operatingMic?: string;
name?: string;
countryIso?: string;
currency?: string;
timezone?: string;
calendarCode?: string;
boardLotPolicy?: string;
} = {}
): Promise<void> {
await pool.query(
`INSERT INTO exchange (
mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (mic) DO NOTHING`,
[
mic,
overrides.operatingMic ?? mic,
overrides.name ?? `${mic} Exchange`,
overrides.countryIso ?? 'US',
overrides.currency ?? 'USD',
overrides.timezone ?? 'America/New_York',
overrides.calendarCode ?? mic,
overrides.boardLotPolicy ?? 'us_100',
]
);
}
async function seedExchange(
pool: Pool,
mic: string,
@ -144,24 +175,25 @@ describe.skipIf(!url)('security master PostgreSQL schema', () => {
test('accepts valid insert chain across all 11 tables and populates defaults', async () => {
const f = await createIsolatedFixture();
// 1. exchange (omitting board_lot_policy to verify default 'us_100')
// 1. exchange (omitting board_lot_policy on an unseeded synthetic MIC to verify default 'us_100')
const exchangeRow = (
await f.pool.query(
`INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code)
VALUES ('XNYS', 'XNYS', 'New York Stock Exchange', 'US', 'USD', 'America/New_York', 'XNYS')
VALUES ('XTST', 'XTST', 'Synthetic Test Exchange', 'US', 'USD', 'America/New_York', 'XNYS')
RETURNING board_lot_policy`
)
).rows[0];
expect(exchangeRow.board_lot_policy).toBe('us_100');
await seedExchange(f.pool, 'OTCM', { name: 'OTC Markets' });
await ensureExchange(f.pool, 'XNYS', { name: 'New York Stock Exchange' });
await ensureExchange(f.pool, 'OTCM', { name: 'OTC Markets' });
// 2. exchange_source_map (primary_venue with mic, and composite with NULL mic)
await f.pool.query(
`INSERT INTO exchange_source_map (source, source_code, role, mic, country_iso, method)
VALUES
('eod', 'NYSE', 'primary_venue', 'XNYS', 'US', 'manual_seed'),
('eod', 'US', 'composite', NULL, 'US', 'manual_seed')`
('eod', 'TEST_COMP', 'composite', NULL, 'US', 'manual_seed')`
);
// 3. instrument
@ -269,7 +301,7 @@ describe.skipIf(!url)('security master PostgreSQL schema', () => {
test('rejects foreign key violations (23503)', async () => {
const f = await createIsolatedFixture();
await seedExchange(f.pool, 'XNYS');
await ensureExchange(f.pool, 'XNYS');
const instrumentId = (
await f.pool.query(
`INSERT INTO instrument (canonical_name, security_type)
@ -330,7 +362,7 @@ describe.skipIf(!url)('security master PostgreSQL schema', () => {
test('rejects unique and primary key violations (23505) while allowing distinct dates and NULL ISINs', async () => {
const f = await createIsolatedFixture();
await seedExchange(f.pool, 'XNYS');
await ensureExchange(f.pool, 'XNYS');
const instrumentId = (
await f.pool.query(
@ -409,7 +441,7 @@ describe.skipIf(!url)('security master PostgreSQL schema', () => {
test('rejects CHECK constraint violations (23514) and accepts valid boundary values', async () => {
const f = await createIsolatedFixture();
await seedExchange(f.pool, 'XNYS');
await ensureExchange(f.pool, 'XNYS');
const instrumentId = (
await f.pool.query(
`INSERT INTO instrument (canonical_name, security_type)
@ -531,15 +563,15 @@ describe.skipIf(!url)('security master PostgreSQL schema', () => {
test('allows interlisted listings on different mics and ticker reuse across distinct instruments', async () => {
const f = await createIsolatedFixture();
await seedExchange(f.pool, 'XTSE', {
await ensureExchange(f.pool, 'XTSE', {
name: 'Toronto Stock Exchange',
countryIso: 'CA',
currency: 'CAD',
timezone: 'America/Toronto',
boardLotPolicy: 'tsx_tiered',
});
await seedExchange(f.pool, 'XNYS');
await seedExchange(f.pool, 'XNAS', { name: 'NASDAQ' });
await ensureExchange(f.pool, 'XNYS');
await ensureExchange(f.pool, 'XNAS', { name: 'NASDAQ' });
// Interlisted Shopify: one instrument, two listings on XTSE (CAD) and XNYS (USD)
const shopInstrumentId = (

View file

@ -0,0 +1,504 @@
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, test } from 'bun:test';
import {
classifySourceExchanges,
escapeSqlLiteral,
EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS,
generateExchangeSeedFromMongo,
generateExchangeSeedSql,
generateUnresolvedExchangesMarkdown,
ISO_EXCHANGE_SEEDS,
normalizeRawExchangeDoc,
parseGenerateExchangeSeedArgs,
resolveReadOnlyMongoClientConfig,
SOURCE_EXCHANGE_COLLECTIONS,
type ExchangeSource,
type ReadOnlyExchangeMongoClient,
type SourceExchangeRecord,
} from '../../apps/stock/data-pipeline/src/security-master';
const committedSeedPath = fileURLToPath(
new URL('../../database/postgres/init/35-security-master-exchange-seed.sql', import.meta.url)
);
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe('security master Pass 1 exchange classifier', () => {
test('explicit rules take precedence over OperatingMIC', () => {
const result = classifySourceExchanges([
{ source: 'eod', code: 'US', operatingMic: 'XNYS', country: 'US' },
{ source: 'eod', code: 'NMFQS', operatingMic: 'XNAS', country: 'US' },
{ source: 'eod', code: 'FOREX', operatingMic: 'XNYS' },
{ source: 'ib', code: 'IEX', operatingMic: 'IEXG', country: 'US' },
{ source: 'ceo', code: 'TSX', operatingMic: 'XNYS', country: 'CA' },
]);
expect(result.unresolved).toEqual([]);
expect(result.mapped).toEqual([
{
source: 'ceo',
sourceCode: 'TSX',
role: 'primary_venue',
mic: 'XTSE',
countryIso: 'CA',
method: 'explicit_rule',
reviewedBy: null,
},
{
source: 'eod',
sourceCode: 'FOREX',
role: 'forex',
mic: null,
countryIso: null,
method: 'explicit_rule',
reviewedBy: null,
},
{
source: 'eod',
sourceCode: 'NMFQS',
role: 'excluded_fund',
mic: null,
countryIso: 'US',
method: 'explicit_rule',
reviewedBy: null,
},
{
source: 'eod',
sourceCode: 'US',
role: 'composite',
mic: null,
countryIso: 'US',
method: 'explicit_rule',
reviewedBy: null,
},
{
source: 'ib',
sourceCode: 'IEX',
role: 'ats_routing',
mic: null,
countryIso: 'US',
method: 'explicit_rule',
reviewedBy: null,
},
]);
});
test('trims, uppercases, and collapses duplicate source codes deterministically', () => {
const result = classifySourceExchanges([
{ source: 'ceo', code: ' tsx ' },
{ source: 'ceo', code: 'TSX' },
{ source: 'eod', code: ' to ', operatingMic: ' xtse ' },
{ source: 'eod', code: 'TO', operatingMic: 'XTSE' },
{ source: 'eod', code: 'to', operatingMic: null },
]);
expect(result.unresolved).toEqual([]);
expect(result.mapped).toEqual([
{
source: 'ceo',
sourceCode: 'TSX',
role: 'primary_venue',
mic: 'XTSE',
countryIso: 'CA',
method: 'explicit_rule',
reviewedBy: null,
},
{
source: 'eod',
sourceCode: 'TO',
role: 'primary_venue',
mic: 'XTSE',
countryIso: 'CA',
method: 'operating_mic',
reviewedBy: null,
},
]);
});
test('resolves valid single OperatingMIC to primary_venue with exchange countryIso', () => {
const result = classifySourceExchanges([
{ source: 'eod', code: 'NASDAQ', operatingMic: 'xnas', country: 'USA' },
{ source: 'qm', code: 'TSV', operatingMic: 'XTSX', country: 'Canada' },
]);
expect(result.unresolved).toEqual([]);
expect(result.mapped).toEqual([
{
source: 'eod',
sourceCode: 'NASDAQ',
role: 'primary_venue',
mic: 'XNAS',
countryIso: 'US',
method: 'operating_mic',
reviewedBy: null,
},
{
source: 'qm',
sourceCode: 'TSV',
role: 'primary_venue',
mic: 'XTSX',
countryIso: 'CA',
method: 'operating_mic',
reviewedBy: null,
},
]);
});
test('routes empty codes, missing/unknown/malformed/multi-valued/conflicting MICs to unresolved without guessing', () => {
const result = classifySourceExchanges([
{ source: 'eod', code: ' ', name: 'Blank' },
{ source: 'qm', code: 'MYSTERY', name: 'No MIC' },
{ source: 'eod', code: 'LSE', operatingMic: 'XLON', country: 'GB' },
{ source: 'eod', code: 'BADFMT', operatingMic: 'XN-Y' },
{ source: 'eod', code: 'MULTI_COMMA', operatingMic: 'XNAS, XNYS' },
{ source: 'eod', code: 'MULTI_SEMI', operatingMic: 'XNYS;XNAS' },
{ source: 'eod', code: 'MULTI_SPACE', operatingMic: 'XNAS XNYS' },
{ source: 'eod', code: 'MULTI_SLASH', operatingMic: 'XNAS/XNYS' },
{ source: 'eod', code: 'MULTI_PIPE', operatingMic: 'XNAS|XNYS' },
{ source: 'ib', code: 'CONFLICT', operatingMic: 'XNYS' },
{ source: 'ib', code: 'conflict', operatingMic: 'XNAS' },
]);
expect(result.mapped).toEqual([]);
expect(result.unresolved.map(row => [row.source, row.sourceCode, row.reason])).toEqual([
['eod', '', 'empty_code'],
['eod', 'BADFMT', 'invalid_operating_mic_format'],
['eod', 'LSE', 'unknown_operating_mic'],
['eod', 'MULTI_COMMA', 'multi_valued_operating_mic'],
['eod', 'MULTI_PIPE', 'multi_valued_operating_mic'],
['eod', 'MULTI_SEMI', 'multi_valued_operating_mic'],
['eod', 'MULTI_SLASH', 'multi_valued_operating_mic'],
['eod', 'MULTI_SPACE', 'multi_valued_operating_mic'],
['ib', 'CONFLICT', 'multi_valued_operating_mic'],
['qm', 'MYSTERY', 'missing_operating_mic'],
]);
});
test('throws an error naming both source and code on unknown source', () => {
expect(() =>
classifySourceExchanges([
{ source: 'yahoo' as unknown as ExchangeSource, code: 'NYSE', operatingMic: 'XNYS' },
])
).toThrow(/yahoo.*NYSE/);
});
test('normalizes observed raw MongoDB field spellings across all four provider collections', () => {
expect(
normalizeRawExchangeDoc('eod', {
Code: 'TO',
Name: 'Toronto Exchange',
CountryISO2: 'CA',
OperatingMIC: 'XTSE',
Currency: 'CAD',
})
).toEqual({
source: 'eod',
code: 'TO',
name: 'Toronto Exchange',
country: 'CA',
operatingMic: 'XTSE',
currency: 'CAD',
});
expect(
normalizeRawExchangeDoc('ib', {
id: 'DRCTEDGE',
description: 'Direct Edge',
country_code: 'US',
})
).toEqual({
source: 'ib',
code: 'DRCTEDGE',
name: 'Direct Edge',
country: 'US',
operatingMic: null,
currency: null,
});
expect(
normalizeRawExchangeDoc('ib', {
exchange_id: 'AEQLIT',
name: 'Aequitas NEO',
countryCode: 'CA',
})
).toEqual({
source: 'ib',
code: 'AEQLIT',
name: 'Aequitas NEO',
country: 'CA',
operatingMic: null,
currency: null,
});
expect(
normalizeRawExchangeDoc('qm', {
exchange: 'TSX',
exchangeName: 'Toronto Stock Exchange',
countryCode: 'CA',
OperatingMIC: 'XTSE',
})
).toEqual({
source: 'qm',
code: 'TSX',
name: 'Toronto Stock Exchange',
country: 'CA',
operatingMic: 'XTSE',
currency: null,
});
expect(
normalizeRawExchangeDoc('qm', {
exchangeCode: 'NGS',
exchangeShortName: 'NASDAQ',
country_code: 'US',
})
).toEqual({
source: 'qm',
code: 'NGS',
name: 'NASDAQ',
country: 'US',
operatingMic: null,
currency: null,
});
expect(
normalizeRawExchangeDoc('ceo', {
exchange: 'CDX',
name: 'TSX Venture',
country: 'CA',
})
).toEqual({
source: 'ceo',
code: 'CDX',
name: 'TSX Venture',
country: 'CA',
operatingMic: null,
currency: null,
});
});
});
describe('security master Pass 1 SQL and Markdown generator', () => {
test('escapes single quotes and rejects NUL bytes in SQL literals', () => {
expect(escapeSqlLiteral(null)).toBe('NULL');
expect(escapeSqlLiteral(undefined)).toBe('NULL');
expect(escapeSqlLiteral("O'Hare's Exchange")).toBe("'O''Hare''s Exchange'");
expect(() => escapeSqlLiteral('BAD\0VALUE')).toThrow(/NUL/);
});
test('produces byte-identical SQL and Markdown for shuffled inputs sorted by mic and (source, source_code)', () => {
const recordsA: SourceExchangeRecord[] = [
{ source: 'ib', code: 'PSX' },
{ source: 'ceo', code: 'TSX' },
{ source: 'eod', code: 'TO', operatingMic: 'XTSE' },
{ source: 'eod', code: 'US' },
{ source: 'qm', code: 'UNK_B', name: 'Pipe | Name\nLine2' },
{ source: 'eod', code: 'UNK_A', operatingMic: 'XLON' },
];
const recordsB: SourceExchangeRecord[] = [
recordsA[5]!,
recordsA[2]!,
recordsA[0]!,
recordsA[4]!,
recordsA[3]!,
recordsA[1]!,
];
const resA = classifySourceExchanges(recordsA);
const resB = classifySourceExchanges(recordsB);
const sqlA = generateExchangeSeedSql({
exchanges: ISO_EXCHANGE_SEEDS,
mappings: resA.mapped,
});
const sqlB = generateExchangeSeedSql({
exchanges: [...ISO_EXCHANGE_SEEDS].reverse(),
mappings: [...resB.mapped].reverse(),
});
expect(sqlA).toBe(sqlB);
expect(sqlA.indexOf("('ceo', 'TSX'")).toBeLessThan(sqlA.indexOf("('eod', 'TO'"));
expect(sqlA.indexOf("('eod', 'TO'")).toBeLessThan(sqlA.indexOf("('eod', 'US'"));
expect(sqlA.indexOf("('eod', 'US'")).toBeLessThan(sqlA.indexOf("('ib', 'PSX'"));
const mdA = generateUnresolvedExchangesMarkdown(resA);
const mdB = generateUnresolvedExchangesMarkdown(resB);
expect(mdA).toBe(mdB);
expect(mdA).toContain('Pipe \\| Name Line2');
});
test('escapes single quotes in generated SQL values', () => {
const sql = generateExchangeSeedSql({
exchanges: [
{
mic: 'XTST',
operatingMic: 'XTST',
name: "O'Connor's Venue",
countryIso: 'US',
currency: 'USD',
timezone: 'America/New_York',
calendarCode: 'XNYS',
boardLotPolicy: 'us_100',
},
],
mappings: [],
});
expect(sql).toContain("'O''Connor''s Venue'");
});
test('generated SQL for baseline seeds matches committed 35-security-master-exchange-seed.sql byte-for-byte', () => {
const generated = generateExchangeSeedSql({
exchanges: ISO_EXCHANGE_SEEDS,
mappings: EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS,
});
const committed = readFileSync(committedSeedPath, 'utf8');
expect(generated).toBe(committed);
});
});
describe('security master Pass 1 read-only MongoDB generator wrapper', () => {
test('only calls isReadOnly and find on the four exchange collections and fails loudly on write methods', async () => {
const dir = mkdtempSync(join(tmpdir(), 'pass1-seed-gen-'));
tempDirs.push(dir);
const sqlOutPath = join(dir, 'out', 'seed.sql');
const reportOutPath = join(dir, 'out', 'unresolved.md');
const fixtures: Record<string, Record<string, unknown>[]> = {
[SOURCE_EXCHANGE_COLLECTIONS.eod]: [
{ Code: 'US', Name: 'USA Stocks', CountryISO2: 'US', OperatingMIC: 'XNAS, XNYS' },
{ Code: 'TO', Name: 'Toronto', CountryISO2: 'CA', OperatingMIC: 'XTSE' },
{ Code: 'LSE', Name: 'London', CountryISO2: 'GB', OperatingMIC: 'XLON' },
],
[SOURCE_EXCHANGE_COLLECTIONS.ib]: [
{ id: 'IEX', name: 'IEX Routing', country_code: 'US' },
],
[SOURCE_EXCHANGE_COLLECTIONS.qm]: [
{ exchange: 'NGS', exchangeName: 'NASDAQ Global Select', OperatingMIC: 'XNAS' },
],
[SOURCE_EXCHANGE_COLLECTIONS.ceo]: [
{ exchange: 'TSX', name: 'Toronto Stock Exchange', country: 'CA' },
],
};
const calls: Array<{ method: string; collection?: string }> = [];
const readOnlyFake = new Proxy(
{},
{
get(_target, prop) {
if (prop === 'isReadOnly') {
return () => {
calls.push({ method: 'isReadOnly' });
return true;
};
}
if (prop === 'find') {
return async (collectionName: string, filter?: Record<string, unknown>) => {
expect(filter).toEqual({});
calls.push({ method: 'find', collection: collectionName });
return fixtures[collectionName] ?? [];
};
}
return () => {
throw new Error(`Forbidden MongoDB method invoked: ${String(prop)}`);
};
},
}
) as ReadOnlyExchangeMongoClient & { insertOne: () => void };
expect(() => readOnlyFake.insertOne()).toThrow(/Forbidden MongoDB method invoked: insertOne/);
const output = await generateExchangeSeedFromMongo(readOnlyFake, {
sqlOutPath,
reportOutPath,
});
expect(calls).toEqual([
{ method: 'isReadOnly' },
{ method: 'find', collection: 'eodExchanges' },
{ method: 'find', collection: 'ibExchanges' },
{ method: 'find', collection: 'qmExchanges' },
{ method: 'find', collection: 'ceoExchanges' },
]);
expect(output.countsByCollection).toEqual({ eod: 3, ib: 1, qm: 1, ceo: 1 });
expect(output.classification.mapped).toHaveLength(5);
expect(output.classification.unresolved).toHaveLength(1);
expect(output.classification.unresolved[0]?.sourceCode).toBe('LSE');
expect(readFileSync(sqlOutPath, 'utf8')).toBe(output.sql);
expect(readFileSync(reportOutPath, 'utf8')).toBe(output.reportMarkdown);
});
test('rejects a non-read-only MongoDB client before calling find', async () => {
const dir = mkdtempSync(join(tmpdir(), 'pass1-seed-nonro-'));
tempDirs.push(dir);
let findCalled = false;
const nonReadOnlyFake: ReadOnlyExchangeMongoClient = {
isReadOnly: () => false,
find: async () => {
findCalled = true;
return [];
},
};
await expect(
generateExchangeSeedFromMongo(nonReadOnlyFake, {
sqlOutPath: join(dir, 'seed.sql'),
reportOutPath: join(dir, 'report.md'),
})
).rejects.toThrow(/read-only/i);
expect(findCalled).toBe(false);
});
test('parses CLI arguments and resolves read-only MongoDB config from readUri', () => {
expect(parseGenerateExchangeSeedArgs([])).toEqual({
sqlOutPath: './tmp/35-security-master-exchange-seed.generated.sql',
reportOutPath: './tmp/pass1-unresolved-exchanges.md',
});
expect(
parseGenerateExchangeSeedArgs(['--sql-out', '/tmp/a.sql', '--report-out=/tmp/b.md'])
).toEqual({
sqlOutPath: '/tmp/a.sql',
reportOutPath: '/tmp/b.md',
});
expect(() => parseGenerateExchangeSeedArgs(['--unknown'])).toThrow(/Unknown argument/);
expect(() => parseGenerateExchangeSeedArgs(['--sql-out'])).toThrow(/Missing value/);
const resolved = resolveReadOnlyMongoClientConfig({
database: {
mongodb: {
enabled: true,
host: 'localhost',
port: 27018,
database: 'stock_dev',
uri: 'mongodb://localhost:27018/stock_dev',
readUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock',
readOnly: false,
poolSize: 10,
},
postgres: {} as never,
questdb: {} as never,
dragonfly: {} as never,
},
});
expect(resolved.readOnly).toBe(true);
expect(resolved.uri).toBe(
'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock'
);
expect(resolved.database).toBe('stock');
});
});