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-schema-test'); const url = process.env.PIPELINE_TEST_DATABASE_URL; const securityMasterSqlPath = fileURLToPath( new URL('../../database/postgres/init/34-security-master.sql', import.meta.url) ); const SECURITY_MASTER_TABLES = [ 'exchange', 'exchange_source_map', 'instrument', 'instrument_identifier_history', 'listing', 'corporate_action_continuity', 'listing_symbol_history', 'provider_mapping', 'resolution_conflict', 'override', 'golden_field_audit', ]; const SECURITY_MASTER_INDEXES = [ 'idx_listing_instrument_id', 'idx_listing_mic_ticker', 'idx_listing_ib_conid', 'idx_provider_mapping_listing_id', 'idx_instrument_identifier_history_instrument_id', ]; 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 expectPgErrorCode(operation: Promise, expectedCode: string): Promise { try { await operation; } catch (error) { const code = (error as { code?: string } | null)?.code; expect(code).toBe(expectedCode); return; } throw new Error(`Expected PostgreSQL error code ${expectedCode}, but query succeeded`); } async function seedExchange( pool: Pool, mic: string, overrides: { operatingMic?: string; name?: string; countryIso?: string; currency?: string; timezone?: string; calendarCode?: string; boardLotPolicy?: string; } = {} ): Promise { 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)`, [ 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', ] ); } describe.skipIf(!url)('security master PostgreSQL schema', () => { test('creates all 11 tables and 5 lookup indexes and is idempotent on raw SQL re-run', async () => { const f = await createIsolatedFixture(); const tables = new Set( ( await f.pool.query('SELECT tablename FROM pg_tables WHERE schemaname = $1', [f.schema]) ).rows.map(row => row.tablename as string) ); for (const table of SECURITY_MASTER_TABLES) { expect(tables.has(table)).toBe(true); } const indexes = new Set( ( await f.pool.query('SELECT indexname FROM pg_indexes WHERE schemaname = $1', [f.schema]) ).rows.map(row => row.indexname as string) ); for (const index of SECURITY_MASTER_INDEXES) { expect(indexes.has(index)).toBe(true); } const rawSql = readFileSync(securityMasterSqlPath, 'utf8'); await f.pool.query(rawSql); }); 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') 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') RETURNING board_lot_policy` ) ).rows[0]; expect(exchangeRow.board_lot_policy).toBe('us_100'); await seedExchange(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')` ); // 3. instrument const instrumentId = ( await f.pool.query( `INSERT INTO instrument (primary_isin, primary_cusip, canonical_name, security_type, issuer_country) VALUES ('US0378331005', '037833100', 'Apple Inc.', 'common', 'US') RETURNING instrument_id` ) ).rows[0].instrument_id as number; // 4. instrument_identifier_history await f.pool.query( `INSERT INTO instrument_identifier_history (instrument_id, id_type, id_value, valid_from, source) VALUES ($1, 'ISIN', 'US0378331005', '1980-12-12', 'ib'), ($1, 'CUSIP', '037833100', '1980-12-12', 'ib')`, [instrumentId] ); // 5. listing (omitting class_suffix to verify default ''; testing NULL and 'unknown_involuntary' delist_reason) const primaryListing = ( await f.pool.query( `INSERT INTO listing (instrument_id, mic, ticker_root, currency, ib_conid, ib_primary_exchange, listed_from, delist_reason) VALUES ($1, 'XNYS', 'AAPL', 'USD', 265598, 'NYSE', '1980-12-12', NULL) RETURNING listing_id, class_suffix`, [instrumentId] ) ).rows[0]; const primaryListingId = primaryListing.listing_id as number; expect(primaryListing.class_suffix).toBe(''); const otcListingId = ( await f.pool.query( `INSERT INTO listing (instrument_id, mic, ticker_root, currency, delist_reason, terminal_return) VALUES ($1, 'OTCM', 'AAPLQ', 'USD', 'unknown_involuntary', -0.300000) RETURNING listing_id`, [instrumentId] ) ).rows[0].listing_id as number; // 6. listing_symbol_history await f.pool.query( `INSERT INTO listing_symbol_history (listing_id, ticker, valid_from, source) VALUES ($1, 'AAPL', '1980-12-12', 'eod')`, [primaryListingId] ); // 7. corporate_action_continuity await f.pool.query( `INSERT INTO corporate_action_continuity (from_listing_id, to_listing_id, effective_date, kind) VALUES ($1, $2, '2025-01-15', 'otc_delist_transfer')`, [primaryListingId, otcListingId] ); // 8. provider_mapping (omitting valid_from to verify default '1900-01-01') const mappingRow = ( await f.pool.query( `INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence, price_corr) VALUES ('eod', 'AAPL.US', $1, 'tier1_isin', 1.000, 0.9995) RETURNING to_char(valid_from, 'YYYY-MM-DD') AS valid_from`, [primaryListingId] ) ).rows[0]; expect(mappingRow.valid_from).toBe('1900-01-01'); // 9. resolution_conflict (omitting detail and status to verify defaults) const conflictRow = ( await f.pool.query( `INSERT INTO resolution_conflict (source, source_id, conflict_kind, candidate_listing_id, existing_listing_id) VALUES ('qm', 'AAPL:US', 'ambiguous_ticker', $1, $2) RETURNING detail, status`, [primaryListingId, otcListingId] ) ).rows[0]; expect(conflictRow.detail).toEqual({}); expect(conflictRow.status).toBe('open'); // 10. override (omitting valid_from to verify default '1900-01-01') const overrideRow = ( await f.pool.query( `INSERT INTO override (source, source_id, listing_id, reason, created_by) VALUES ('qm', 'AAPL:US', $1, 'Verified against EDGAR CIK', 'operator') RETURNING to_char(valid_from, 'YYYY-MM-DD') AS valid_from`, [primaryListingId] ) ).rows[0]; expect(overrideRow.valid_from).toBe('1900-01-01'); // 11. golden_field_audit (both 'instrument' and 'listing') const auditRows = ( await f.pool.query( `INSERT INTO golden_field_audit (entity_type, entity_id, field_name, chosen_value, chosen_source) VALUES ('instrument', $1, 'canonical_name', 'Apple Inc.', 'ib'), ('listing', $2, 'ticker_root', 'AAPL', 'eod') RETURNING entity_type, candidates`, [instrumentId, primaryListingId] ) ).rows; expect(auditRows).toHaveLength(2); expect(auditRows[0].candidates).toEqual({}); expect(auditRows[1].candidates).toEqual({}); }); test('rejects foreign key violations (23503)', async () => { const f = await createIsolatedFixture(); await seedExchange(f.pool, 'XNYS'); const instrumentId = ( await f.pool.query( `INSERT INTO instrument (canonical_name, security_type) VALUES ('Test Corp', 'common') RETURNING instrument_id` ) ).rows[0].instrument_id as number; await expectPgErrorCode( f.pool.query( `INSERT INTO listing (instrument_id, mic, ticker_root, currency) VALUES ($1, 'NOPE', 'TEST', 'USD')`, [instrumentId] ), '23503' ); await expectPgErrorCode( f.pool.query( `INSERT INTO listing (instrument_id, mic, ticker_root, currency) VALUES (999999, 'XNYS', 'TEST', 'USD')` ), '23503' ); await expectPgErrorCode( f.pool.query( `INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence) VALUES ('eod', 'TEST.US', 999999, 'tier3_ticker_span', 0.850)` ), '23503' ); await expectPgErrorCode( f.pool.query( `INSERT INTO override (source, source_id, listing_id, reason, created_by) VALUES ('eod', 'TEST.US', 999999, 'Invalid listing test', 'tester')` ), '23503' ); await expectPgErrorCode( f.pool.query( `INSERT INTO resolution_conflict (source, source_id, conflict_kind, candidate_listing_id) VALUES ('eod', 'TEST.US', 'missing_listing', 999999)` ), '23503' ); await expectPgErrorCode( f.pool.query( `INSERT INTO resolution_conflict (source, source_id, conflict_kind, existing_listing_id) VALUES ('eod', 'TEST.US', 'missing_listing', 999999)` ), '23503' ); }); 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'); const instrumentId = ( await f.pool.query( `INSERT INTO instrument (primary_isin, canonical_name, security_type) VALUES ('US5949181045', 'Microsoft Corp', 'common') RETURNING instrument_id` ) ).rows[0].instrument_id as number; // Duplicate primary_isin rejected await expectPgErrorCode( f.pool.query( `INSERT INTO instrument (primary_isin, canonical_name, security_type) VALUES ('US5949181045', 'Microsoft Duplicate', 'common')` ), '23505' ); // Multiple NULL primary_isin instruments allowed await f.pool.query( `INSERT INTO instrument (primary_isin, canonical_name, security_type) VALUES (NULL, 'Unlisted Co A', 'common'), (NULL, 'Unlisted Co B', 'common')` ); const listingId = ( await f.pool.query( `INSERT INTO listing (instrument_id, mic, ticker_root, currency) VALUES ($1, 'XNYS', 'MSFT', 'USD') RETURNING listing_id`, [instrumentId] ) ).rows[0].listing_id as number; // Duplicate provider_mapping PK rejected; distinct valid_from allowed await f.pool.query( `INSERT INTO provider_mapping (source, source_id, valid_from, listing_id, method, confidence) VALUES ('eod', 'MSFT.US', '2000-01-01', $1, 'tier1_isin', 1.000)`, [listingId] ); await expectPgErrorCode( f.pool.query( `INSERT INTO provider_mapping (source, source_id, valid_from, listing_id, method, confidence) VALUES ('eod', 'MSFT.US', '2000-01-01', $1, 'tier2_cusip', 0.950)`, [listingId] ), '23505' ); await f.pool.query( `INSERT INTO provider_mapping (source, source_id, valid_from, listing_id, method, confidence) VALUES ('eod', 'MSFT.US', '2020-01-01', $1, 'tier1_isin', 1.000)`, [listingId] ); // Duplicate override PK rejected; distinct valid_from allowed await f.pool.query( `INSERT INTO override (source, source_id, valid_from, listing_id, reason, created_by) VALUES ('eod', 'MSFT.US', '2000-01-01', $1, 'Initial override', 'tester')`, [listingId] ); await expectPgErrorCode( f.pool.query( `INSERT INTO override (source, source_id, valid_from, listing_id, reason, created_by) VALUES ('eod', 'MSFT.US', '2000-01-01', $1, 'Duplicate override', 'tester')`, [listingId] ), '23505' ); await f.pool.query( `INSERT INTO override (source, source_id, valid_from, listing_id, reason, created_by) VALUES ('eod', 'MSFT.US', '2020-01-01', $1, 'Later override', 'tester')`, [listingId] ); }); test('rejects CHECK constraint violations (23514) and accepts valid boundary values', async () => { const f = await createIsolatedFixture(); await seedExchange(f.pool, 'XNYS'); const instrumentId = ( await f.pool.query( `INSERT INTO instrument (canonical_name, security_type) VALUES ('Check Test Corp', 'common') RETURNING instrument_id` ) ).rows[0].instrument_id as number; const listingId = ( await f.pool.query( `INSERT INTO listing (instrument_id, mic, ticker_root, currency) VALUES ($1, 'XNYS', 'CHK', 'USD') RETURNING listing_id`, [instrumentId] ) ).rows[0].listing_id as number; // exchange.board_lot_policy await expectPgErrorCode(seedExchange(f.pool, 'XBAD', { boardLotPolicy: 'odd_lot' }), '23514'); // exchange_source_map.role await expectPgErrorCode( f.pool.query( `INSERT INTO exchange_source_map (source, source_code, role, mic, method) VALUES ('eod', 'BAD', 'not_a_role', 'XNYS', 'manual')` ), '23514' ); // instrument.security_type await expectPgErrorCode( f.pool.query( `INSERT INTO instrument (canonical_name, security_type) VALUES ('Bad Type', 'crypto')` ), '23514' ); // instrument_identifier_history.id_type await expectPgErrorCode( f.pool.query( `INSERT INTO instrument_identifier_history (instrument_id, id_type, id_value, valid_from, source) VALUES ($1, 'SEDOL', '2046251', '2020-01-01', 'ib')`, [instrumentId] ), '23514' ); // listing.delist_reason: old stray-space typo must fail; 'unknown_involuntary' and NULL succeed await expectPgErrorCode( f.pool.query( `INSERT INTO listing (instrument_id, mic, ticker_root, currency, delist_reason) VALUES ($1, 'XNYS', 'TYPO', 'USD', 'unknown_ involuntary')`, [instrumentId] ), '23514' ); await f.pool.query( `INSERT INTO listing (instrument_id, mic, ticker_root, currency, delist_reason) VALUES ($1, 'XNYS', 'OK1', 'USD', 'unknown_involuntary'), ($1, 'XNYS', 'OK2', 'USD', NULL)`, [instrumentId] ); // corporate_action_continuity.kind await expectPgErrorCode( f.pool.query( `INSERT INTO corporate_action_continuity (from_listing_id, to_listing_id, effective_date, kind) VALUES ($1, $1, '2024-01-01', 'reverse_split')`, [listingId] ), '23514' ); // provider_mapping.method await expectPgErrorCode( f.pool.query( `INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence) VALUES ('eod', 'CHK.US', $1, 'tier5_guess', 0.500)`, [listingId] ), '23514' ); // provider_mapping.confidence out of [0, 1] fails; 0 and 1 succeed await expectPgErrorCode( f.pool.query( `INSERT INTO provider_mapping (source, source_id, valid_from, listing_id, method, confidence) VALUES ('eod', 'CHK_HI', '2020-01-01', $1, 'tier1_isin', 1.500)`, [listingId] ), '23514' ); await expectPgErrorCode( f.pool.query( `INSERT INTO provider_mapping (source, source_id, valid_from, listing_id, method, confidence) VALUES ('eod', 'CHK_LO', '2020-01-01', $1, 'tier1_isin', -0.001)`, [listingId] ), '23514' ); await f.pool.query( `INSERT INTO provider_mapping (source, source_id, valid_from, listing_id, method, confidence) VALUES ('eod', 'CHK_ZERO', '2020-01-01', $1, 'tier4_name', 0.000), ('eod', 'CHK_ONE', '2020-01-01', $1, 'override', 1.000)`, [listingId] ); // golden_field_audit.entity_type await expectPgErrorCode( f.pool.query( `INSERT INTO golden_field_audit (entity_type, entity_id, field_name, chosen_value, chosen_source) VALUES ('exchange', 1, 'name', 'NYSE', 'manual')` ), '23514' ); }); test('allows interlisted listings on different mics and ticker reuse across distinct instruments', async () => { const f = await createIsolatedFixture(); await seedExchange(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' }); // Interlisted Shopify: one instrument, two listings on XTSE (CAD) and XNYS (USD) const shopInstrumentId = ( await f.pool.query( `INSERT INTO instrument (primary_isin, canonical_name, security_type, issuer_country) VALUES ('CA82509L1076', 'Shopify Inc.', 'common', 'CA') RETURNING instrument_id` ) ).rows[0].instrument_id as number; const shopListings = ( await f.pool.query( `INSERT INTO listing (instrument_id, mic, ticker_root, currency) VALUES ($1, 'XTSE', 'SHOP', 'CAD'), ($1, 'XNYS', 'SHOP', 'USD') RETURNING listing_id, mic, currency`, [shopInstrumentId] ) ).rows; expect(shopListings).toHaveLength(2); // Ticker reuse across distinct instruments: Meta Platforms (2012-2022 FB) vs ProShares ETF (2025 FB) const metaInstrumentId = ( await f.pool.query( `INSERT INTO instrument (canonical_name, security_type, issuer_country) VALUES ('Meta Platforms Inc.', 'common', 'US') RETURNING instrument_id` ) ).rows[0].instrument_id as number; const fbEtfInstrumentId = ( await f.pool.query( `INSERT INTO instrument (canonical_name, security_type, issuer_country) VALUES ('ProShares FB ETF', 'etf', 'US') RETURNING instrument_id` ) ).rows[0].instrument_id as number; const fbListings = ( await f.pool.query( `INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency, listed_from, listed_to) VALUES ($1, 'XNAS', 'FB', '', 'USD', '2012-05-18', '2022-06-08'), ($2, 'XNAS', 'FB', '', 'USD', '2025-01-10', NULL) RETURNING listing_id, instrument_id`, [metaInstrumentId, fbEtfInstrumentId] ) ).rows; expect(fbListings).toHaveLength(2); expect(fbListings[0].instrument_id).not.toBe(fbListings[1].instrument_id); }); });