diff --git a/test/postgres/security-master-exchange-seed-upgrade.test.ts b/test/postgres/security-master-exchange-seed-upgrade.test.ts new file mode 100644 index 00000000..b6b0d906 --- /dev/null +++ b/test/postgres/security-master-exchange-seed-upgrade.test.ts @@ -0,0 +1,284 @@ +import { randomUUID } from 'node:crypto'; +import { copyFileSync, mkdtempSync, 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 { Pool } from 'pg'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres'; +import { + generateExchangeSeedFromMongo, + ISO_EXCHANGE_SEEDS, + type ExchangeSeedRow, + type ReadOnlyExchangeMongoClient, +} from '../../apps/stock/data-pipeline/src/security-master'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); +const logger = getLogger('security-master-exchange-seed-upgrade-test'); +const url = process.env.PIPELINE_TEST_DATABASE_URL; +const initDir = fileURLToPath(new URL('../../database/postgres/init', import.meta.url)); + +const PRE_SEED_MASTER_FILES = [ + '01-init-database.sql', + '02-master-schema.sql', + '03-initial-data.sql', + '04-provider-exchange-mapping-schema.sql', + '05-add-visible-column.sql', + '34-security-master.sql', +]; + +const cleanup: (() => Promise | 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(), + }), + }); + + return { pool, postgres }; +} + +function makeTempDir(prefix: string): string { + const dir = mkdtempSync(join(tmpdir(), prefix)); + cleanup.push(() => rmSync(dir, { recursive: true, force: true })); + return dir; +} + +describe.skipIf(!url)('security master Pass 1 exchange seed upgrade and generated SQL', () => { + test('upgrading a schema that already ran 34 applies only 35 and keeps pre-existing director data', async () => { + const f = await createIsolatedFixture(); + + // Arrange: a database migrated before migration 35 existed. + const preSeedDir = makeTempDir('pass1-pre-seed-migrations-'); + for (const file of PRE_SEED_MASTER_FILES) { + copyFileSync(join(initDir, file), join(preSeedDir, file)); + } + expect( + await runPostgresMigrations(f.postgres, { track: 'master', migrationsDir: preSeedDir }) + ).toEqual(PRE_SEED_MASTER_FILES); + + await f.pool.query( + `INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy) + VALUES ('XNYS', 'XNYS', 'NYSE (director-curated)', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100')` + ); + await f.pool.query( + `INSERT INTO exchange_source_map (source, source_code, role, mic, country_iso, method, reviewed_by) + VALUES + ('eod', 'US', 'primary_venue', 'XNYS', 'US', 'director_override', 'director'), + ('ceo', 'TSX', 'composite', NULL, NULL, 'stale_manual', NULL)` + ); + + // Act: run the real master track. + const applied = await runPostgresMigrations(f.postgres, { track: 'master' }); + + // Assert + expect(applied).toEqual(['35-security-master-exchange-seed.sql']); + + const xnys = (await f.pool.query(`SELECT name FROM exchange WHERE mic = 'XNYS'`)).rows[0]; + expect(xnys).toEqual({ name: 'NYSE (director-curated)' }); + + const micCount = (await f.pool.query('SELECT count(*)::int AS count FROM exchange')).rows[0] + .count as number; + expect(micCount).toBe(11); + + const reviewed = ( + await f.pool.query( + `SELECT role, mic, method, reviewed_by FROM exchange_source_map + WHERE source = 'eod' AND source_code = 'US'` + ) + ).rows[0]; + expect(reviewed).toEqual({ + role: 'primary_venue', + mic: 'XNYS', + method: 'director_override', + reviewed_by: 'director', + }); + + const refreshed = ( + await f.pool.query( + `SELECT role, mic, country_iso, method, reviewed_by FROM exchange_source_map + WHERE source = 'ceo' AND source_code = 'TSX'` + ) + ).rows[0]; + expect(refreshed).toEqual({ + role: 'primary_venue', + mic: 'XTSE', + country_iso: 'CA', + method: 'explicit_rule', + reviewed_by: null, + }); + + const mappingCount = ( + await f.pool.query('SELECT count(*)::int AS count FROM exchange_source_map') + ).rows[0].count as number; + expect(mappingCount).toBe(17); + + expect(await runPostgresMigrations(f.postgres, { track: 'master' })).toEqual([]); + }); + + test('host-generator SQL from a fake read-only Mongo applies on top of migration 35, round-trips quoted names, and is idempotent', async () => { + const f = await createIsolatedFixture(); + await runPostgresMigrations(f.postgres, { track: 'master' }); + + const syntheticExchange: ExchangeSeedRow = { + mic: 'XTST', + operatingMic: 'XTST', + name: "O'Brien \\ Test Exchange", + countryIso: 'US', + currency: 'USD', + timezone: 'America/New_York', + calendarCode: 'XNYS', + boardLotPolicy: 'us_100', + }; + const fixtures: Record[]> = { + eodExchanges: [ + { Code: 'US', OperatingMIC: 'XNAS, XNYS' }, + { Code: 'TO', OperatingMIC: 'XTSE' }, + { Code: 'V', OperatingMIC: 'XTSX' }, + { Code: 'LSE', OperatingMIC: 'XLON' }, + ], + ibExchanges: [ + { id: 'IEX' }, + { id: 'NYSE', OperatingMIC: 'XNYS' }, + { id: 'TESTX', OperatingMIC: 'xtst' }, + ], + qmExchanges: [ + { exchange: 'NGS', OperatingMIC: 'XNAS' }, + { exchange: 'MULTI', OperatingMIC: 'XNAS/XNYS' }, + ], + ceoExchanges: [{ exchange: 'TSX' }, { exchange: 'AQL' }], + }; + const mongo: ReadOnlyExchangeMongoClient = { + isReadOnly: () => true, + find: async >(collection: string): Promise => + (fixtures[collection] ?? []) as T[], + }; + + const dir = makeTempDir('pass1-generated-sql-'); + const output = await generateExchangeSeedFromMongo(mongo, { + sqlOutPath: join(dir, 'generated.sql'), + reportOutPath: join(dir, 'unresolved.md'), + knownExchanges: [...ISO_EXCHANGE_SEEDS, syntheticExchange], + }); + + 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, + }); + + await f.pool.query(output.sql); + const afterFirst = await countRows(); + await f.pool.query(output.sql); + expect(await countRows()).toEqual(afterFirst); + + // 11 seeded + XTST; 17 baseline + eod TO, eod V, ib NYSE, ib TESTX, qm NGS. + expect(afterFirst).toEqual({ exchanges: 12, mappings: 22 }); + + const name = (await f.pool.query(`SELECT name FROM exchange WHERE mic = 'XTST'`)).rows[0]; + expect(name).toEqual({ name: "O'Brien \\ Test Exchange" }); + + const generated = ( + await f.pool.query( + `SELECT source, source_code, role, mic, method + FROM exchange_source_map + WHERE method = 'operating_mic' + ORDER BY source, source_code` + ) + ).rows; + expect(generated).toEqual([ + { + source: 'eod', + source_code: 'TO', + role: 'primary_venue', + mic: 'XTSE', + method: 'operating_mic', + }, + { + source: 'eod', + source_code: 'V', + role: 'primary_venue', + mic: 'XTSX', + method: 'operating_mic', + }, + { + source: 'ib', + source_code: 'NYSE', + role: 'primary_venue', + mic: 'XNYS', + method: 'operating_mic', + }, + { + source: 'ib', + source_code: 'TESTX', + role: 'primary_venue', + mic: 'XTST', + method: 'operating_mic', + }, + { + source: 'qm', + source_code: 'NGS', + role: 'primary_venue', + mic: 'XNAS', + method: 'operating_mic', + }, + ]); + + // Unresolved codes never reach the table. + const leaked = ( + await f.pool.query( + `SELECT count(*)::int AS count FROM exchange_source_map + WHERE (source, source_code) IN (('eod', 'LSE'), ('qm', 'MULTI'))` + ) + ).rows[0].count as number; + expect(leaked).toBe(0); + expect(output.reportMarkdown).toContain('| eod | LSE |'); + expect(output.reportMarkdown).toContain('| qm | MULTI |'); + + // Explicit rule kept eod US as composite despite its multi-valued OperatingMIC. + const us = ( + await f.pool.query( + `SELECT role, mic FROM exchange_source_map WHERE source = 'eod' AND source_code = 'US'` + ) + ).rows[0]; + expect(us).toEqual({ role: 'composite', mic: null }); + + const orphans = ( + 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(orphans).toBe(0); + }); +}); diff --git a/test/unit/security-master-exchange-pass1-edge-cases.test.ts b/test/unit/security-master-exchange-pass1-edge-cases.test.ts new file mode 100644 index 00000000..b0195908 --- /dev/null +++ b/test/unit/security-master-exchange-pass1-edge-cases.test.ts @@ -0,0 +1,354 @@ +import { existsSync, 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, + EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS, + generateExchangeSeedFromMongo, + generateExchangeSeedSql, + generateUnresolvedExchangesMarkdown, + ISO_EXCHANGE_SEEDS, + normalizeRawExchangeDoc, + parseGenerateExchangeSeedArgs, + resolveReadOnlyMongoClientConfig, + type ExchangeSource, + type ReadOnlyExchangeMongoClient, +} 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('Pass 1 classifier edge cases', () => { + test('explicit rule matches after trim/uppercase even when the record carries a multi-valued OperatingMIC', () => { + const result = classifySourceExchanges([ + { source: 'eod', code: ' us ', operatingMic: 'XNAS, XNYS' }, + ]); + + expect(result.unresolved).toEqual([]); + expect(result.mapped).toEqual([ + { + source: 'eod', + sourceCode: 'US', + role: 'composite', + mic: null, + countryIso: 'US', + method: 'explicit_rule', + reviewedBy: null, + }, + ]); + }); + + test('a repeated MIC inside one multi-valued string is still unresolved, not picked', () => { + const result = classifySourceExchanges([ + { source: 'eod', code: 'DUP', operatingMic: 'XNAS,XNAS' }, + ]); + + expect(result.mapped).toEqual([]); + expect(result.unresolved.map(row => row.reason)).toEqual(['multi_valued_operating_mic']); + }); + + test('a multi-valued duplicate wins over a clean duplicate of the same code (no silent first pick)', () => { + const result = classifySourceExchanges([ + { source: 'eod', code: 'MIX', operatingMic: 'XNAS' }, + { source: 'eod', code: 'mix', operatingMic: 'XNAS; XNYS' }, + ]); + + expect(result.mapped).toEqual([]); + expect(result.unresolved).toHaveLength(1); + expect(result.unresolved[0]?.reason).toBe('multi_valued_operating_mic'); + }); + + test('same code under different sources stays as separate rows; explicit rules are per-source', () => { + const result = classifySourceExchanges([ + { source: 'ceo', code: 'TSX' }, + { source: 'qm', code: 'TSX' }, + { source: 'ib', code: 'TSX', operatingMic: 'XTSE' }, + ]); + + expect(result.mapped.map(row => [row.source, row.sourceCode, row.mic, row.method])).toEqual([ + ['ceo', 'TSX', 'XTSE', 'explicit_rule'], + ['ib', 'TSX', 'XTSE', 'operating_mic'], + ]); + // qm TSX has no explicit rule and no MIC: must not borrow the CEO mapping. + expect(result.unresolved.map(row => [row.source, row.sourceCode, row.reason])).toEqual([ + ['qm', 'TSX', 'missing_operating_mic'], + ]); + }); + + test('source names are case-sensitive and the error names both source and code', () => { + expect(() => + classifySourceExchanges([{ source: 'EOD' as unknown as ExchangeSource, code: 'US' }]) + ).toThrow('Unknown exchange source "EOD" for exchange code "US"'); + }); + + test('an unknown source anywhere in the batch throws even after valid records', () => { + expect(() => + classifySourceExchanges([ + { source: 'eod', code: 'US' }, + { source: 'bloomberg' as unknown as ExchangeSource, code: 'XNYS' }, + ]) + ).toThrow(/bloomberg.*XNYS/); + }); + + test('a MIC outside the supplied knownExchanges is unknown even if it is a real ISO MIC', () => { + const onlyTsx = ISO_EXCHANGE_SEEDS.filter(row => row.mic === 'XTSE'); + const result = classifySourceExchanges( + [ + { source: 'eod', code: 'TO', operatingMic: 'XTSE' }, + { source: 'eod', code: 'NASDAQ', operatingMic: 'XNAS' }, + ], + { knownExchanges: onlyTsx } + ); + + expect(result.mapped.map(row => row.sourceCode)).toEqual(['TO']); + expect(result.unresolved.map(row => [row.sourceCode, row.reason])).toEqual([ + ['NASDAQ', 'unknown_operating_mic'], + ]); + }); + + test('classification output is identical for every rotation of the input', () => { + const records = [ + { source: 'eod' as const, code: 'TO', operatingMic: 'XTSE', name: 'Toronto' }, + { source: 'eod' as const, code: 'to', operatingMic: 'xtse', name: 'TSX' }, + { source: 'ib' as const, code: 'IEX' }, + { source: 'qm' as const, code: 'X1', operatingMic: 'XLON' }, + { source: 'qm' as const, code: '', name: 'blank' }, + ]; + const baseline = classifySourceExchanges(records); + for (let shift = 1; shift < records.length; shift++) { + const rotated = [...records.slice(shift), ...records.slice(0, shift)]; + expect(classifySourceExchanges(rotated)).toEqual(baseline); + } + }); +}); + +describe('Pass 1 raw document normalization edge cases', () => { + test('falls through non-string and blank aliases to the next field spelling', () => { + expect(normalizeRawExchangeDoc('ib', { id: 42, exchange_id: 'NYSE' }).code).toBe('NYSE'); + expect(normalizeRawExchangeDoc('eod', { Code: ' ', code: 'TO' }).code).toBe('TO'); + }); + + test('a document with no recognised code field normalizes to an empty code that lands in unresolved', () => { + const record = normalizeRawExchangeDoc('qm', { foo: 'bar', name: 'Orphan' }); + expect(record.code).toBe(''); + + const result = classifySourceExchanges([record]); + expect(result.mapped).toEqual([]); + expect(result.unresolved).toEqual([ + { + source: 'qm', + sourceCode: '', + rawCode: '', + name: 'Orphan', + country: null, + operatingMic: null, + currency: null, + reason: 'empty_code', + }, + ]); + }); + + test('unknown source throws naming the source and the code found in the document', () => { + expect(() => + normalizeRawExchangeDoc('yahoo' as unknown as ExchangeSource, { Code: 'NYQ' }) + ).toThrow(/yahoo.*NYQ/); + }); +}); + +describe('Pass 1 SQL generator and committed seed edge cases', () => { + test('empty input emits only the header comment and no INSERT statements', () => { + const sql = generateExchangeSeedSql({ mappings: [] }); + expect(sql).not.toContain('INSERT'); + expect(sql.endsWith('\n')).toBe(true); + }); + + test('committed seed is self-contained: no meta-commands, no schema qualifiers, no CREATE DATABASE', () => { + const committed = readFileSync(committedSeedPath, 'utf8'); + expect(committed).not.toMatch(/^\s*\\/m); + expect(committed).not.toMatch(/CREATE\s+DATABASE/i); + expect(committed).not.toMatch(/\b(public|stock_bot\w*)\.(exchange|exchange_source_map)\b/i); + expect(committed).not.toMatch(/now\(\)|current_timestamp/i); + expect(committed).toContain('ON CONFLICT (mic) DO NOTHING;'); + expect(committed).toContain('WHERE exchange_source_map.reviewed_by IS NULL;'); + }); + + test('committed seed covers exactly the 11 MICs and 17 explicit mappings, all unreviewed', () => { + const committed = readFileSync(committedSeedPath, 'utf8'); + const exchangeRows = committed.match(/^ {2}\('[A-Z0-9]{4}', '/gm) ?? []; + const mappingRows = committed.match(/^ {2}\('(eod|qm|ib|ceo)', /gm) ?? []; + + expect(exchangeRows).toHaveLength(11); + expect(mappingRows).toHaveLength(17); + expect(ISO_EXCHANGE_SEEDS).toHaveLength(11); + expect(EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS).toHaveLength(17); + for (const row of EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS) { + expect(row.reviewedBy).toBeNull(); + } + }); + + test('every non-null mic in the explicit rules refers to a seeded exchange', () => { + const seeded = new Set(ISO_EXCHANGE_SEEDS.map(row => row.mic)); + for (const row of EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS) { + if (row.mic !== null) { + expect(seeded.has(row.mic)).toBe(true); + } + } + }); + + test('seed data is internally consistent: CA venues tsx_tiered/CAD/Toronto, US venues us_100/USD/New_York', () => { + for (const row of ISO_EXCHANGE_SEEDS) { + if (row.countryIso === 'CA') { + expect([row.boardLotPolicy, row.currency, row.timezone]).toEqual([ + 'tsx_tiered', + 'CAD', + 'America/Toronto', + ]); + } else { + expect(row.countryIso).toBe('US'); + expect([row.boardLotPolicy, row.currency, row.timezone]).toEqual([ + 'us_100', + 'USD', + 'America/New_York', + ]); + } + expect(row.calendarCode.length).toBeGreaterThan(0); + } + }); + + test('backslashes pass through untouched (standard_conforming_strings literal) while quotes double', () => { + const sql = generateExchangeSeedSql({ + mappings: [ + { + source: 'qm', + sourceCode: "A\\B'C", + role: 'primary_venue', + mic: 'XNYS', + countryIso: 'US', + method: 'operating_mic', + reviewedBy: "o'neil", + }, + ], + }); + expect(sql).toContain( + "('qm', 'A\\B''C', 'primary_venue', 'XNYS', 'US', 'operating_mic', 'o''neil')" + ); + }); + + test('NUL byte in any mapping field aborts generation instead of emitting truncated SQL', () => { + expect(() => + generateExchangeSeedSql({ + mappings: [ + { + source: 'eod', + sourceCode: 'BAD\0', + role: 'composite', + mic: null, + countryIso: null, + method: 'explicit_rule', + }, + ], + }) + ).toThrow(/NUL/); + }); + + test('Markdown report states that everything resolved when there are no unresolved rows', () => { + const md = generateUnresolvedExchangesMarkdown( + classifySourceExchanges([{ source: 'eod', code: 'US' }]) + ); + expect(md).toContain('- Mapped: 1'); + expect(md).toContain('- Unresolved: 0'); + expect(md).toContain('All source exchange records resolved cleanly.'); + expect(md).not.toContain('| Source |'); + }); +}); + +describe('Pass 1 read-only generator wrapper edge cases', () => { + test('a failing find propagates and leaves no partial output files behind', async () => { + const dir = mkdtempSync(join(tmpdir(), 'pass1-seed-fail-')); + tempDirs.push(dir); + const sqlOutPath = join(dir, 'seed.sql'); + const reportOutPath = join(dir, 'report.md'); + + const failing: ReadOnlyExchangeMongoClient = { + isReadOnly: () => true, + find: async >(collection: string): Promise => { + if (collection === 'qmExchanges') { + throw new Error('cursor killed'); + } + return []; + }, + }; + + await expect( + generateExchangeSeedFromMongo(failing, { sqlOutPath, reportOutPath }) + ).rejects.toThrow('cursor killed'); + expect(existsSync(sqlOutPath)).toBe(false); + expect(existsSync(reportOutPath)).toBe(false); + }); + + test('an unrecognised raw document shape never makes the wrapper guess a mapping', async () => { + const dir = mkdtempSync(join(tmpdir(), 'pass1-seed-shape-')); + tempDirs.push(dir); + + const mongo: ReadOnlyExchangeMongoClient = { + isReadOnly: () => true, + find: async >(collection: string): Promise => + (collection === 'ibExchanges' + ? [{ unexpected: 'NYSE', OperatingMIC: 'XNYS' }] + : []) as unknown as T[], + }; + + const output = await generateExchangeSeedFromMongo(mongo, { + sqlOutPath: join(dir, 'seed.sql'), + reportOutPath: join(dir, 'report.md'), + }); + + expect(output.classification.mapped).toEqual([]); + expect(output.classification.unresolved.map(row => [row.source, row.reason])).toEqual([ + ['ib', 'empty_code'], + ]); + expect(output.sql).not.toContain('INSERT INTO exchange_source_map'); + }); + + test('CLI rejects a flag used as the value of another flag', () => { + expect(() => parseGenerateExchangeSeedArgs(['--report-out', '--sql-out', 'a.sql'])).toThrow( + 'Missing value for --report-out' + ); + expect(() => parseGenerateExchangeSeedArgs(['--sql-out='])).toThrow( + 'Missing value for --sql-out' + ); + }); + + test('without readUri the config falls back to uri but is still forced read-only', () => { + const resolved = resolveReadOnlyMongoClientConfig({ + database: { + mongodb: { + enabled: true, + host: 'localhost', + port: 27018, + database: 'stock_dev', + uri: 'mongodb://localhost:27018/stock_dev', + readOnly: false, + poolSize: 5, + }, + postgres: {} as never, + questdb: {} as never, + dragonfly: {} as never, + }, + }); + + expect(resolved.readOnly).toBe(true); + expect(resolved.uri).toBe('mongodb://localhost:27018/stock_dev'); + expect(resolved.database).toBe('stock_dev'); + }); +});