T-211: M2.2v — Export listing_venues.tsv and extend field-shape probe & BSON fixture exporter for M2 collections

This commit is contained in:
Studio 2026-12-04 14:09:44 -05:00
parent e6bc956e49
commit c9ab13d5a3
12 changed files with 1047 additions and 71 deletions

View file

@ -1,5 +1,5 @@
import { randomUUID } from 'node:crypto';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, test } from 'bun:test';
@ -7,6 +7,8 @@ import { Pool, type PoolClient } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
import {
CURATE_INPUT_FILES,
CurateInputExportError,
exportCurateInputs,
pinCurateInputSnapshot,
type SecurityMasterQueryable,
@ -95,14 +97,21 @@ async function seedFixtureData(pool: Pool) {
try {
await client.query('BEGIN');
// Ensure required MICs exist (migration 35 seeds them, ON CONFLICT DO NOTHING keeps idempotent).
// Ensure all 11 ISO MICs exist (migration 35 seeds them, ON CONFLICT DO NOTHING keeps idempotent).
await client.query(`
INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy)
VALUES
('ARCX', 'XNYS', 'NYSE Arca', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('BATS', 'BATS', 'Cboe BZX Exchange', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('IEXG', 'IEXG', 'Investors Exchange', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('NEOE', 'NEOE', 'Cboe Canada (NEO Exchange)', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'),
('OTCM', 'OTCM', 'OTC Markets', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('XASE', 'XNYS', 'NYSE American', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('XCNQ', 'XCNQ', 'Canadian Securities Exchange', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'),
('XNAS', 'XNAS', 'NASDAQ', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('XNYS', 'XNYS', 'NYSE', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('XTSE', 'XTSE', 'TSX', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'),
('OTCM', 'OTCM', 'OTC Markets', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100')
('XTSX', 'XTSX', 'TSX Venture Exchange', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered')
ON CONFLICT (mic) DO NOTHING
`);
@ -132,6 +141,13 @@ async function seedFixtureData(pool: Pool) {
const instNoListedTo = await insertInstrument('US0000000035', '000000003', 'No ListedTo Corp', 'common', 'US');
const instNoQm = await insertInstrument('US0000000043', '000000004', 'No QM Mapping Corp', 'common', 'US');
const instNoSuccQm = await insertInstrument('US0000000050', '000000005', 'No Succ QM Corp', 'common', 'US');
const instArcx = await insertInstrument('US0000000068', '000000006', 'Arca ETF Corp', 'etf', 'US');
const instXase = await insertInstrument('US0000000076', '000000007', 'American Corp', 'common', 'US');
const instBats = await insertInstrument('US0000000084', '000000008', 'BZX ETF Corp', 'etf', 'US');
const instIexg = await insertInstrument('US0000000092', '000000009', 'IEX Corp', 'common', 'US');
const instNeoe = await insertInstrument('CA0000000109', '000000010', 'NEO Corp', 'common', 'CA');
const instXtsx = await insertInstrument('CA0000000117', '000000011', 'Venture Mining Corp', 'common', 'CA');
const instXcnq = await insertInstrument('CA0000000125', '000000012', 'CSE Junior Corp', 'common', 'CA');
const insertListing = async (params: {
instrumentId: number;
@ -284,6 +300,76 @@ async function seedFixtureData(pool: Pool) {
delistReason: null,
terminalReturn: null,
});
const arcxId = await insertListing({
instrumentId: instArcx,
mic: 'ARCX',
tickerRoot: 'ARCA',
currency: 'USD',
listedFrom: '2020-01-02',
listedTo: null,
delistReason: 'active',
terminalReturn: null,
});
const xaseId = await insertListing({
instrumentId: instXase,
mic: 'XASE',
tickerRoot: 'AMEX',
currency: 'USD',
listedFrom: '2020-01-02',
listedTo: null,
delistReason: 'active',
terminalReturn: null,
});
const batsId = await insertListing({
instrumentId: instBats,
mic: 'BATS',
tickerRoot: 'CBOE',
currency: 'USD',
listedFrom: '2020-01-02',
listedTo: null,
delistReason: 'active',
terminalReturn: null,
});
const iexgId = await insertListing({
instrumentId: instIexg,
mic: 'IEXG',
tickerRoot: 'IEXX',
currency: 'USD',
listedFrom: '2020-01-02',
listedTo: null,
delistReason: 'active',
terminalReturn: null,
});
const neoeId = await insertListing({
instrumentId: instNeoe,
mic: 'NEOE',
tickerRoot: 'NEOC',
currency: 'CAD',
listedFrom: '2020-01-02',
listedTo: null,
delistReason: 'active',
terminalReturn: null,
});
const xtsxId = await insertListing({
instrumentId: instXtsx,
mic: 'XTSX',
tickerRoot: 'VMIN',
currency: 'CAD',
listedFrom: '2020-01-02',
listedTo: null,
delistReason: 'active',
terminalReturn: null,
});
const xcnqId = await insertListing({
instrumentId: instXcnq,
mic: 'XCNQ',
tickerRoot: 'CSEJ',
currency: 'CAD',
listedFrom: '2020-01-02',
listedTo: null,
delistReason: 'active',
terminalReturn: null,
});
const insertMapping = async (
source: string,
@ -351,6 +437,13 @@ async function seedFixtureData(pool: Pool) {
noQmId,
noSuccQmFromId,
noSuccQmToId,
arcxId,
xaseId,
batsId,
iexgId,
neoeId,
xtsxId,
xcnqId,
};
} catch (error) {
await client.query('ROLLBACK').catch(() => {});
@ -402,6 +495,7 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*
expect(pinned5000.generationId).toBe(res5000.generationId);
expect(pinned5000.providerMapping).toBe(res5000.providerMapping.path);
expect(pinned5000.listingCurrencies).toBe(res5000.listingCurrencies.path);
expect(pinned5000.listingVenues).toBe(res5000.listingVenues.path);
expect(pinned5000.delistings).toBe(res5000.delistings.path);
// Verify chunkSize=1 actually paginated across multiple queries.
@ -410,10 +504,12 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*
// Byte-identical outputs between chunkSize=1 and chunkSize=5000.
const pm5000 = await readFile(res5000.providerMapping.path, 'utf8');
const lc5000 = await readFile(res5000.listingCurrencies.path, 'utf8');
const lv5000 = await readFile(res5000.listingVenues.path, 'utf8');
const dl5000 = await readFile(res5000.delistings.path, 'utf8');
expect(await readFile(res1.providerMapping.path, 'utf8')).toBe(pm5000);
expect(await readFile(res1.listingCurrencies.path, 'utf8')).toBe(lc5000);
expect(await readFile(res1.listingVenues.path, 'utf8')).toBe(lv5000);
expect(await readFile(res1.delistings.path, 'utf8')).toBe(dl5000);
// Assert exact provider_mapping.tsv content (COLLATE "C" ASCII order).
@ -456,10 +552,60 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*
`${ids.noQmId}\tUSD`,
`${ids.noSuccQmFromId}\tUSD`,
`${ids.noSuccQmToId}\tUSD`,
`${ids.arcxId}\tUSD`,
`${ids.xaseId}\tUSD`,
`${ids.batsId}\tUSD`,
`${ids.iexgId}\tUSD`,
`${ids.neoeId}\tCAD`,
`${ids.xtsxId}\tCAD`,
`${ids.xcnqId}\tCAD`,
'',
].join('\n')
);
// Assert exact listing_venues.tsv content covering all 11 ISO MICs (us_tsx vs tsxv_cse).
expect(lv5000).toBe(
[
`${ids.aaplId}\tus_tsx`,
`${ids.shopId}\tus_tsx`,
`${ids.fbOldId}\tus_tsx`,
`${ids.fbNewId}\tus_tsx`,
`${ids.sivbId}\tus_tsx`,
`${ids.sivbReuseId}\tus_tsx`,
`${ids.sivbqId}\tus_tsx`,
`${ids.del30Id}\tus_tsx`,
`${ids.noListedToId}\tus_tsx`,
`${ids.noQmId}\tus_tsx`,
`${ids.noSuccQmFromId}\tus_tsx`,
`${ids.noSuccQmToId}\tus_tsx`,
`${ids.arcxId}\tus_tsx`,
`${ids.xaseId}\tus_tsx`,
`${ids.batsId}\tus_tsx`,
`${ids.iexgId}\tus_tsx`,
`${ids.neoeId}\tus_tsx`,
`${ids.xtsxId}\ttsxv_cse`,
`${ids.xcnqId}\ttsxv_cse`,
'',
].join('\n')
);
// Verify strict load_listing_venues_tsv compliance (headerless 2-col LF TSV, ascending positive i32).
expect(lv5000.includes('\r')).toBe(false);
expect(lv5000.endsWith('\n')).toBe(true);
const lvLines = lv5000.slice(0, -1).split('\n');
expect(lvLines).toHaveLength(19);
let prevListingId = 0;
for (const line of lvLines) {
const cols = line.split('\t');
expect(cols).toHaveLength(2);
expect(cols[0]).toMatch(/^[1-9]\d*$/);
const id = Number(cols[0]);
expect(id).toBeGreaterThan(prevListingId);
expect(id).toBeLessThanOrEqual(2_147_483_647);
expect(cols[1] === 'us_tsx' || cols[1] === 'tsxv_cse').toBe(true);
prevListingId = id;
}
// Assert exact delistings.tsv content.
expect(dl5000).toBe(
[
@ -473,13 +619,13 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*
// Assert exact stats reconciliation.
const stats = res5000.delistings.stats;
expect(stats).toEqual({
rowsIn: 12,
rowsIn: 19,
rowsOut: 3,
otcTransfersOut: 1,
terminalDelistingsOut: 2,
skippedTotal: 9,
skippedTotal: 16,
skipped: {
active: 4, // AAPL, SHOP, FB new, SIVB reuse
active: 11, // AAPL, SHOP, FB new, SIVB reuse + 7 MIC-coverage active listings
noOutcome: 2, // FB old, NOSUQ
missingListedTo: 1, // NLDT
missingOutgoingQmMapping: 1, // NOQM
@ -489,5 +635,80 @@ describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*
});
expect(stats.rowsIn).toBe(stats.rowsOut + stats.skippedTotal);
expect(res1.delistings.stats).toEqual(stats);
expect(res5000.listingVenues.rowsIn).toBe(19);
expect(res5000.listingVenues.rowsOut).toBe(19);
expect(res1.listingVenues.bytesWritten).toBe(res5000.listingVenues.bytesWritten);
});
test('fails closed with UNKNOWN_LISTING_MIC on an unmapped exchange MIC (XLON) and leaves existing outDir files intact', async () => {
const { pool } = await createIsolatedFixture();
const client = await pool.connect();
let xlonListingId = 0;
try {
await client.query('BEGIN');
await client.query(`
INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy)
VALUES ('XLON', 'XLON', 'London Stock Exchange', 'GB', 'GBP', 'Europe/London', 'XLON', 'us_100')
ON CONFLICT (mic) DO NOTHING
`);
const instRes = await client.query<{ instrument_id: number }>(
`INSERT INTO instrument (primary_isin, primary_cusip, canonical_name, security_type, issuer_country)
VALUES ('GB0000000011', 'G00000001', 'London Test PLC', 'common', 'GB')
RETURNING instrument_id`
);
const listRes = await client.query<{ listing_id: number }>(
`INSERT INTO listing (
instrument_id, mic, ticker_root, class_suffix, currency,
listed_from, listed_to, delist_reason, terminal_return
)
VALUES ($1, 'XLON', 'LSE', '', 'GBP', '2020-01-02'::date, NULL, 'active', NULL)
RETURNING listing_id`,
[instRes.rows[0]!.instrument_id]
);
xlonListingId = listRes.rows[0]!.listing_id;
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK').catch(() => {});
throw error;
} finally {
client.release();
}
const outDir = await makeTempDir('curate-inputs-pg-unknown-mic-');
const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n';
const origLc = '1\tUSD\n';
const origLv = '1\tus_tsx\n';
const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n';
await writeFile(join(outDir, CURATE_INPUT_FILES.providerMapping), origPm, 'utf8');
await writeFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), origLc, 'utf8');
await writeFile(join(outDir, CURATE_INPUT_FILES.listingVenues), origLv, 'utf8');
await writeFile(join(outDir, CURATE_INPUT_FILES.delistings), origDl, 'utf8');
let caught: unknown;
try {
await withRecordingClient(pool, async queryable => {
await exportCurateInputs(queryable, { outDir });
});
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(CurateInputExportError);
const err = caught as CurateInputExportError;
expect(err.code).toBe('UNKNOWN_LISTING_MIC');
expect(err.table).toBe('listing');
expect(err.key).toBe(`listing_id=${xlonListingId}`);
expect(err.message).toContain('XLON');
expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe(origPm);
expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe(origLc);
expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingVenues), 'utf8')).toBe(origLv);
expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe(origDl);
expect((await readdir(outDir)).sort()).toEqual([
CURATE_INPUT_FILES.delistings,
CURATE_INPUT_FILES.listingCurrencies,
CURATE_INPUT_FILES.listingVenues,
CURATE_INPUT_FILES.providerMapping,
]);
});
});