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
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);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue