import { randomUUID } from 'node:crypto'; 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 { buildMatchReport, generateOverrideSeedSql, generateOverrideTemplateSql, type OverrideSeedRow, } from '../../apps/stock/data-pipeline/src/security-master'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('security-master-override-seed-test'); const url = process.env.PIPELINE_TEST_DATABASE_URL; 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(), }), }); await runPostgresMigrations(postgres, { track: 'master' }); return { pool, schema, postgres }; } async function seedSingleListing(pool: Pool): Promise { const instrumentResult = await pool.query<{ instrument_id: number }>( `INSERT INTO instrument (primary_isin, primary_cusip, canonical_name, security_type, issuer_country) VALUES ('US0378331005', '037833100', 'Apple Inc.', 'common', 'US') RETURNING instrument_id` ); const instrumentId = instrumentResult.rows[0]?.instrument_id; if (instrumentId === undefined) { throw new Error('Failed to insert fixture instrument'); } const listingResult = await pool.query<{ listing_id: number }>( `INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency) VALUES ($1, 'XNAS', 'AAPL', '', 'USD') RETURNING listing_id`, [instrumentId] ); const listingId = listingResult.rows[0]?.listing_id; if (listingId === undefined) { throw new Error('Failed to insert fixture listing'); } return listingId; } describe.skipIf(!url)('security master override seed SQL', () => { test('inserts matching override row with resolved listing_id and is idempotent on re-run', async () => { const f = await createIsolatedFixture(); const expectedListingId = await seedSingleListing(f.pool); const row: OverrideSeedRow = { source: 'eod', sourceId: 'AAPL.US', validFrom: '2020-01-15', validTo: '2025-12-31', primaryIsin: 'US0378331005', mic: 'XNAS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', reason: "O'Brien fix", createdBy: 'director', }; const sql = generateOverrideSeedSql([row]); // First run inserts exactly one row with the resolved listing_id await f.pool.query(sql); const rowsAfterFirst = ( await f.pool.query<{ source: string; source_id: string; valid_from: string; valid_to: string | null; listing_id: number; reason: string; created_by: string; }>( `SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, to_char(valid_to, 'YYYY-MM-DD') AS valid_to, listing_id, reason, created_by FROM override` ) ).rows; expect(rowsAfterFirst).toEqual([ { source: 'eod', source_id: 'AAPL.US', valid_from: '2020-01-15', valid_to: '2025-12-31', listing_id: expectedListingId, reason: "O'Brien fix", created_by: 'director', }, ]); // Second run is a no-op via ON CONFLICT (source, source_id, valid_from) DO NOTHING await f.pool.query(sql); const countAfterSecond = ( await f.pool.query<{ count: number }>('SELECT count(*)::int AS count FROM override') ).rows[0]?.count; expect(countAfterSecond).toBe(1); }); test('natural key matching no listing inserts nothing and raises no error', async () => { const f = await createIsolatedFixture(); await seedSingleListing(f.pool); const sql = generateOverrideSeedSql([ { source: 'qm', sourceId: 'MISSING:US', validFrom: '1900-01-01', validTo: null, primaryIsin: 'US9999999999', mic: 'XNAS', tickerRoot: 'MISSING', classSuffix: '', currency: 'USD', reason: 'Non-existent listing test', createdBy: 'director', }, ]); await f.pool.query(sql); const count = ( await f.pool.query<{ count: number }>('SELECT count(*)::int AS count FROM override') ).rows[0]?.count; expect(count).toBe(0); }); test('duplicate natural key raises cardinality_violation and inserts no override row', async () => { const f = await createIsolatedFixture(); await seedSingleListing(f.pool); // Insert a second listing row with the same natural key (e.g., different listing dates) const instrumentResult = await f.pool.query<{ instrument_id: number }>( `SELECT instrument_id FROM instrument WHERE primary_isin = 'US0378331005'` ); const instrumentId = instrumentResult.rows[0]?.instrument_id; if (instrumentId === undefined) { throw new Error('Expected fixture instrument'); } await f.pool.query( `INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency, listed_from) VALUES ($1, 'XNAS', 'AAPL', '', 'USD', DATE '2022-01-03')`, [instrumentId] ); const sql = generateOverrideSeedSql([ { source: 'eod', sourceId: 'AAPL.US', validFrom: '2020-01-15', validTo: null, primaryIsin: 'US0378331005', mic: 'XNAS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', reason: 'Ambiguous natural key test', createdBy: 'director', }, ]); let caughtError: unknown; try { await f.pool.query(sql); } catch (err) { caughtError = err; } expect(caughtError).toBeDefined(); expect((caughtError as { code?: string }).code).toBe('21000'); const count = ( await f.pool.query<{ count: number }>('SELECT count(*)::int AS count FROM override') ).rows[0]?.count; expect(count).toBe(0); }); test('empty seed SQL and template SQL execute cleanly without inserting rows', async () => { const f = await createIsolatedFixture(); await seedSingleListing(f.pool); const emptySql = generateOverrideSeedSql([]); await f.pool.query(emptySql); const report = buildMatchReport({ stageA: { instruments: [], unresolved: [], conflicts: [ { source: 'eod', sourceId: 'AAPL.US', conflictKind: 'isin_cusip_mismatch', detail: { isin: 'US0378331005', cusip: '037833100', country: 'US', derivedIsin: null }, }, ], stats: { totalInputRecords: 1, totalInstruments: 0, bySource: { ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, eod: { total: 1, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 1 }, }, }, }, stageB: { listings: [], providerMappings: [], unresolved: [], conflicts: [], stats: { totalListings: 0, totalProviderMappings: 0, listingsWithIbConid: 0, excludedFunds: 0, bySource: { eod: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, }, }, }, }); const templateSql = generateOverrideTemplateSql(report); await f.pool.query(templateSql); const count = ( await f.pool.query<{ count: number }>('SELECT count(*)::int AS count FROM override') ).rows[0]?.count; expect(count).toBe(0); }); test('uncommented template candidate with CR/LF source_id preserves the exact ID in PostgreSQL', async () => { const f = await createIsolatedFixture(); const expectedListingId = await seedSingleListing(f.pool); const rawSourceId = "AAPL\r\nLINE2'\\END"; const report = buildMatchReport({ stageA: { instruments: [], unresolved: [], conflicts: [ { source: 'eod', sourceId: rawSourceId, conflictKind: 'isin_cusip_mismatch', detail: { isin: 'US0378331005', cusip: '037833100', country: 'US', derivedIsin: null }, }, ], stats: { totalInputRecords: 1, totalInstruments: 0, bySource: { ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, eod: { total: 1, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 1 }, }, }, }, stageB: { listings: [], providerMappings: [], unresolved: [], conflicts: [], stats: { totalListings: 0, totalProviderMappings: 0, listingsWithIbConid: 0, excludedFunds: 0, bySource: { eod: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, }, }, }, }); const templateSql = generateOverrideTemplateSql(report); const candidateLines = templateSql .split('\n') .slice(templateSql.split('\n').findIndex(line => line === '-- INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)')) .filter(line => line.startsWith('-- ')) .map(line => line.slice(3)) .join('\n') .replace("'TODO_ISIN_12'", "'US0378331005'") .replace("'TODO_MIC'", "'XNAS'") .replace("'TODO_TICKER'", "'AAPL'"); await f.pool.query(candidateLines); const inserted = ( await f.pool.query<{ source_id: string; listing_id: number }>( 'SELECT source_id, listing_id FROM override' ) ).rows; expect(inserted).toEqual([{ source_id: rawSourceId, listing_id: expectedListingId }]); }); test('uncommented template candidate with unstorable source_id fails not_null_violation and inserts no row when marker is left in place', async () => { const f = await createIsolatedFixture(); await seedSingleListing(f.pool); const overlongSourceId = 'X'.repeat(65); const report = buildMatchReport({ stageA: { instruments: [], unresolved: [], conflicts: [ { source: 'eod', sourceId: overlongSourceId, conflictKind: 'isin_cusip_mismatch', detail: { isin: 'US0378331005', cusip: '037833100', country: 'US', derivedIsin: null }, }, ], stats: { totalInputRecords: 1, totalInstruments: 0, bySource: { ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 }, eod: { total: 1, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 1 }, }, }, }, stageB: { listings: [], providerMappings: [], unresolved: [], conflicts: [], stats: { totalListings: 0, totalProviderMappings: 0, listingsWithIbConid: 0, excludedFunds: 0, bySource: { eod: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 }, }, }, }, }); const templateSql = generateOverrideTemplateSql(report); const templateLines = templateSql.split('\n'); const insertStartIndex = templateLines.findIndex( line => line === '-- INSERT INTO override (source, source_id, valid_from, valid_to, listing_id, reason, created_by)' ); expect(insertStartIndex).toBeGreaterThan(-1); const candidateSql = templateLines .slice(insertStartIndex) .filter(line => line.startsWith('-- ')) .map(line => line.slice(3)) .join('\n') .replace("'TODO_ISIN_12'", "'US0378331005'") .replace("'TODO_MIC'", "'XNAS'") .replace("'TODO_TICKER'", "'AAPL'"); let caughtError: unknown; try { await f.pool.query(candidateSql); } catch (err) { caughtError = err; } expect(caughtError).toBeDefined(); expect((caughtError as { code?: string }).code).toBe('23502'); const count = ( await f.pool.query<{ count: number }>('SELECT count(*)::int AS count FROM override') ).rows[0]?.count; expect(count).toBe(0); }); test('multi-statement seed file round-trips special characters, class suffix keys, and distinct valid_from rows', async () => { const f = await createIsolatedFixture(); const aaplListingId = await seedSingleListing(f.pool); const brk = await f.pool.query<{ instrument_id: number }>( `INSERT INTO instrument (primary_isin, canonical_name, security_type, issuer_country) VALUES ('US0846707026', 'Berkshire Hathaway', 'common', 'US') RETURNING instrument_id` ); const brkA = await f.pool.query<{ listing_id: number }>( `INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency) VALUES ($1, 'XNYS', 'BRK', 'A', 'USD') RETURNING listing_id`, [brk.rows[0]?.instrument_id] ); const brkB = await f.pool.query<{ listing_id: number }>( `INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency) VALUES ($1, 'XNYS', 'BRK', 'B', 'USD') RETURNING listing_id`, [brk.rows[0]?.instrument_id] ); const trickyReason = "line1\nO'Brien \\ back\r\nslash -- not a comment; DROP TABLE override;"; const sql = generateOverrideSeedSql([ { source: 'eod', sourceId: 'BRK-B.US', validFrom: '2021-01-01', validTo: null, primaryIsin: 'US0846707026', mic: 'XNYS', tickerRoot: 'BRK', classSuffix: 'B', currency: 'USD', reason: trickyReason, createdBy: 'director' }, { source: 'eod', sourceId: 'BRK-B.US', validFrom: '2020-01-01', validTo: '2020-12-31', primaryIsin: 'US0846707026', mic: 'XNYS', tickerRoot: 'BRK', classSuffix: 'A', currency: 'USD', reason: 'pre-split mapping', createdBy: 'director' }, { source: 'qm', sourceId: "AAPL'Q", primaryIsin: 'US0378331005', mic: 'XNAS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', reason: 'default dates', createdBy: 'qa' }, ]); await f.pool.query(sql); const rows = ( await f.pool.query<{ source: string; source_id: string; valid_from: string; valid_to: string | null; listing_id: number; reason: string }>( `SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from, to_char(valid_to, 'YYYY-MM-DD') AS valid_to, listing_id, reason FROM override ORDER BY source, source_id, valid_from` ) ).rows; expect(rows).toEqual([ { source: 'eod', source_id: 'BRK-B.US', valid_from: '2020-01-01', valid_to: '2020-12-31', listing_id: brkA.rows[0]?.listing_id ?? -1, reason: 'pre-split mapping' }, { source: 'eod', source_id: 'BRK-B.US', valid_from: '2021-01-01', valid_to: null, listing_id: brkB.rows[0]?.listing_id ?? -1, reason: trickyReason }, { source: 'qm', source_id: "AAPL'Q", valid_from: '1900-01-01', valid_to: null, listing_id: aaplListingId, reason: 'default dates' }, ]); }); test('re-seeding an existing override key keeps the originally stored listing_id (DO NOTHING, no overwrite)', async () => { const f = await createIsolatedFixture(); const aaplListingId = await seedSingleListing(f.pool); await f.pool.query( `INSERT INTO override (source, source_id, valid_from, listing_id, reason, created_by) VALUES ('eod', 'AAPL.US', DATE '1900-01-01', $1, 'original', 'director')`, [aaplListingId] ); const instrumentId = (await f.pool.query<{ instrument_id: number }>(`SELECT instrument_id FROM instrument`)).rows[0]?.instrument_id; await f.pool.query( `INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency) VALUES ($1, 'XNYS', 'AAPL', '', 'USD')`, [instrumentId] ); await f.pool.query( generateOverrideSeedSql([ { source: 'eod', sourceId: 'AAPL.US', primaryIsin: 'US0378331005', mic: 'XNYS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', reason: 'replacement', createdBy: 'qa' }, ]) ); const rows = (await f.pool.query<{ listing_id: number; reason: string }>('SELECT listing_id, reason FROM override')).rows; expect(rows).toEqual([{ listing_id: aaplListingId, reason: 'original' }]); }); });