T-40: M1.1c — Pass 1 exchanges: ISO MIC seed, source-code role classifier and reviewable seed-SQL generator
This commit is contained in:
parent
2dbfb7e5bc
commit
c36f89352c
12 changed files with 1848 additions and 20 deletions
|
|
@ -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' });
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
227
test/postgres/security-master-exchange-seed.test.ts
Normal file
227
test/postgres/security-master-exchange-seed.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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 = (
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue