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'; // Verifies the live PostgreSQL catalog produced by the master track (column types, nullability, // PK/FK/UNIQUE definitions) and the implicit behaviours a static read of the DDL can miss. setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('security-master-catalog-test'); const url = process.env.PIPELINE_TEST_DATABASE_URL; type Column = [name: string, type: string, notNull: boolean]; const EXPECTED_COLUMNS: Record = { exchange: [ ['mic', 'character varying(10)', true], ['operating_mic', 'character varying(10)', true], ['name', 'text', true], ['country_iso', 'character(2)', true], ['currency', 'character(3)', true], ['timezone', 'text', true], ['calendar_code', 'character varying(16)', true], ['board_lot_policy', 'character varying(16)', true], ['created_at', 'timestamp with time zone', true], ], exchange_source_map: [ ['source', 'character varying(16)', true], ['source_code', 'character varying(32)', true], ['role', 'character varying(20)', true], ['mic', 'character varying(10)', false], ['country_iso', 'character(2)', false], ['method', 'character varying(32)', true], ['reviewed_by', 'text', false], ], instrument: [ ['instrument_id', 'integer', true], ['primary_isin', 'character(12)', false], ['primary_cusip', 'character(9)', false], ['canonical_name', 'text', true], ['security_type', 'character varying(16)', true], ['issuer_country', 'character(2)', false], ['created_at', 'timestamp with time zone', true], ], instrument_identifier_history: [ ['instrument_id', 'integer', true], ['id_type', 'character varying(8)', true], ['id_value', 'character varying(16)', true], // Declared nullable in the contract, but PRIMARY KEY membership forces NOT NULL. ['valid_from', 'date', true], ['valid_to', 'date', false], ['source', 'character varying(16)', true], ], listing: [ ['listing_id', 'integer', true], ['instrument_id', 'integer', true], ['mic', 'character varying(10)', true], ['ticker_root', 'character varying(24)', true], ['class_suffix', 'character varying(12)', true], ['currency', 'character(3)', true], ['ib_conid', 'bigint', false], ['ib_primary_exchange', 'character varying(16)', false], ['listed_from', 'date', false], ['listed_to', 'date', false], ['delist_reason', 'character varying(24)', false], ['terminal_return', 'numeric(10,6)', false], ['created_at', 'timestamp with time zone', true], ], corporate_action_continuity: [ ['from_listing_id', 'integer', true], ['to_listing_id', 'integer', true], ['effective_date', 'date', true], ['kind', 'character varying(24)', true], ], listing_symbol_history: [ ['listing_id', 'integer', true], ['ticker', 'character varying(32)', true], ['valid_from', 'date', true], ['valid_to', 'date', false], ['source', 'character varying(16)', true], ], provider_mapping: [ ['source', 'character varying(16)', true], ['source_id', 'character varying(64)', true], ['valid_from', 'date', true], ['valid_to', 'date', false], ['listing_id', 'integer', true], ['method', 'character varying(24)', true], ['confidence', 'numeric(4,3)', true], ['price_corr', 'numeric(5,4)', false], ], resolution_conflict: [ ['conflict_id', 'integer', true], ['source', 'character varying(16)', true], ['source_id', 'character varying(64)', true], ['conflict_kind', 'character varying(32)', true], ['candidate_listing_id', 'integer', false], ['existing_listing_id', 'integer', false], ['detail', 'jsonb', true], ['status', 'character varying(16)', true], ['created_at', 'timestamp with time zone', true], ['resolved_at', 'timestamp with time zone', false], ], override: [ ['source', 'character varying(16)', true], ['source_id', 'character varying(64)', true], ['valid_from', 'date', true], ['valid_to', 'date', false], ['listing_id', 'integer', true], ['reason', 'text', true], ['created_by', 'text', true], ['created_at', 'timestamp with time zone', true], ], golden_field_audit: [ ['audit_id', 'integer', true], ['entity_type', 'character varying(16)', true], ['entity_id', 'integer', true], ['field_name', 'text', true], ['chosen_value', 'text', false], ['chosen_source', 'character varying(16)', true], ['candidates', 'jsonb', true], ['decided_at', 'timestamp with time zone', true], ], }; const EXPECTED_KEYS: Record = { exchange: ['PRIMARY KEY (mic)'], exchange_source_map: [ 'FOREIGN KEY (mic) REFERENCES exchange(mic)', 'PRIMARY KEY (source, source_code)', ], instrument: ['PRIMARY KEY (instrument_id)', 'UNIQUE (primary_isin)'], instrument_identifier_history: [ 'FOREIGN KEY (instrument_id) REFERENCES instrument(instrument_id)', 'PRIMARY KEY (id_type, id_value, valid_from)', ], listing: [ 'FOREIGN KEY (instrument_id) REFERENCES instrument(instrument_id)', 'FOREIGN KEY (mic) REFERENCES exchange(mic)', 'PRIMARY KEY (listing_id)', ], corporate_action_continuity: [ 'FOREIGN KEY (from_listing_id) REFERENCES listing(listing_id)', 'FOREIGN KEY (to_listing_id) REFERENCES listing(listing_id)', 'PRIMARY KEY (from_listing_id, effective_date)', ], listing_symbol_history: [ 'FOREIGN KEY (listing_id) REFERENCES listing(listing_id)', 'PRIMARY KEY (listing_id, ticker, valid_from)', ], provider_mapping: [ 'FOREIGN KEY (listing_id) REFERENCES listing(listing_id)', 'PRIMARY KEY (source, source_id, valid_from)', ], resolution_conflict: [ 'FOREIGN KEY (candidate_listing_id) REFERENCES listing(listing_id)', 'FOREIGN KEY (existing_listing_id) REFERENCES listing(listing_id)', 'PRIMARY KEY (conflict_id)', ], override: [ 'FOREIGN KEY (listing_id) REFERENCES listing(listing_id)', 'PRIMARY KEY (source, source_id, valid_from)', ], golden_field_audit: ['PRIMARY KEY (audit_id)'], }; const cleanup: (() => Promise)[] = []; 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 }; } async function expectPgErrorCode(operation: Promise, expectedCode: string): Promise { let code: string | undefined; try { await operation; } catch (error) { code = (error as { code?: string } | null)?.code ?? 'no-code'; } expect(code).toBe(expectedCode); } async function seedListing(pool: Pool) { await 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') ON CONFLICT (mic) DO NOTHING` ); const instrumentId = ( await pool.query( `INSERT INTO instrument (canonical_name, security_type) VALUES ('Catalog Test Corp', 'common') RETURNING instrument_id` ) ).rows[0].instrument_id as number; const listingId = ( await pool.query( `INSERT INTO listing (instrument_id, mic, ticker_root, currency) VALUES ($1, 'XNYS', 'CAT', 'USD') RETURNING listing_id`, [instrumentId] ) ).rows[0].listing_id as number; return { instrumentId, listingId }; } describe.skipIf(!url)('security master PostgreSQL catalog', () => { test('master track creates the 11 tables in the connection schema with contract column types', async () => { const f = await createIsolatedFixture(); const placement = await f.pool.query( `SELECT table_schema, count(*)::int AS n FROM information_schema.tables WHERE table_name = ANY($1) AND table_schema = current_schema() GROUP BY table_schema`, [Object.keys(EXPECTED_COLUMNS)] ); expect(placement.rows).toEqual([{ table_schema: f.schema, n: 11 }]); for (const [table, expected] of Object.entries(EXPECTED_COLUMNS)) { const actual = ( await f.pool.query( `SELECT attname, format_type(atttypid, atttypmod) AS type, attnotnull FROM pg_attribute WHERE attrelid = $1::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum`, [table] ) ).rows.map(row => [row.attname, row.type, row.attnotnull]); expect({ table, columns: actual }).toEqual({ table, columns: expected }); } }); test('PK, FK and UNIQUE constraints match the contract, with no cascading deletes', async () => { const f = await createIsolatedFixture(); for (const [table, expected] of Object.entries(EXPECTED_KEYS)) { const actual = ( await f.pool.query( `SELECT pg_get_constraintdef(oid) AS def FROM pg_constraint WHERE conrelid = $1::regclass AND contype IN ('p', 'f', 'u')`, [table] ) ).rows .map(row => row.def as string) .sort(); expect({ table, keys: actual }).toEqual({ table, keys: [...expected].sort() }); } }); test('identity keys reject caller-supplied ids (GENERATED ALWAYS)', async () => { const f = await createIsolatedFixture(); const { instrumentId } = await seedListing(f.pool); await expectPgErrorCode( f.pool.query( `INSERT INTO instrument (instrument_id, canonical_name, security_type) VALUES (424242, 'Explicit Id', 'common')` ), '428C9' ); await expectPgErrorCode( f.pool.query( `INSERT INTO listing (listing_id, instrument_id, mic, ticker_root, currency) VALUES (424242, $1, 'XNYS', 'EXP', 'USD')`, [instrumentId] ), '428C9' ); }); test('NOT NULL columns reject NULL, including PK-implied instrument_identifier_history.valid_from', async () => { const f = await createIsolatedFixture(); const { instrumentId, listingId } = await seedListing(f.pool); await expectPgErrorCode( f.pool.query( `INSERT INTO instrument_identifier_history (instrument_id, id_type, id_value, valid_from, source) VALUES ($1, 'ISIN', 'US0000000001', NULL, 'ib')`, [instrumentId] ), '23502' ); await expectPgErrorCode( f.pool.query( `INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence) VALUES ('eod', 'NULLCONF.US', $1, 'tier1_isin', NULL)`, [listingId] ), '23502' ); await expectPgErrorCode( f.pool.query( `INSERT INTO override (source, source_id, listing_id, reason, created_by) VALUES ('eod', 'NULLREASON.US', $1, NULL, 'tester')`, [listingId] ), '23502' ); }); test('referenced listings and exchanges cannot be deleted while mappings point at them', async () => { const f = await createIsolatedFixture(); const { listingId } = await seedListing(f.pool); await f.pool.query( `INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence) VALUES ('eod', 'CAT.US', $1, 'tier1_isin', 1.000)`, [listingId] ); await expectPgErrorCode( f.pool.query('DELETE FROM listing WHERE listing_id = $1', [listingId]), '23503' ); await expectPgErrorCode(f.pool.query(`DELETE FROM exchange WHERE mic = 'XNYS'`), '23503'); expect((await f.pool.query('SELECT count(*)::int AS n FROM provider_mapping')).rows[0].n).toBe( 1 ); }); test('confidence is stored at NUMERIC(4,3): 0.9995 rounds to 1.000 and passes the CHECK', async () => { const f = await createIsolatedFixture(); const { listingId } = await seedListing(f.pool); const row = ( await f.pool.query( `INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence) VALUES ('eod', 'ROUND.US', $1, 'tier3_ticker_span', 0.9995) RETURNING confidence::text AS confidence`, [listingId] ) ).rows[0]; expect(row.confidence).toBe('1.000'); await expectPgErrorCode( f.pool.query( `INSERT INTO provider_mapping (source, source_id, listing_id, method, confidence) VALUES ('eod', 'ROUND_HI.US', $1, 'tier3_ticker_span', 1.0005)`, [listingId] ), '23514' ); }); test('re-running the master track after data exists applies nothing and keeps the rows', async () => { const f = await createIsolatedFixture(); await seedListing(f.pool); const postgres = new PostgreSQLClient( { host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' }, logger ); Object.defineProperty(postgres, 'connectionPool', { get: () => ({ connect: () => f.pool.connect() }), }); expect(await runPostgresMigrations(postgres, { track: 'master' })).toEqual([]); expect((await f.pool.query('SELECT count(*)::int AS n FROM listing')).rows[0].n).toBe(1); }); });