stock-bot/test/postgres/security-master-export-curate-inputs.test.ts

493 lines
17 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool, type PoolClient } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
import {
exportCurateInputs,
pinCurateInputSnapshot,
type SecurityMasterQueryable,
type SecurityMasterQueryResult,
} from '../../apps/stock/data-pipeline/src/security-master';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('security-master-export-curate-inputs-pg-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void> | void)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function makeTempDir(prefix = 'curate-inputs-pg-'): Promise<string> {
const dir = await mkdtemp(join(tmpdir(), prefix));
cleanup.push(() => rm(dir, { recursive: true, force: true }));
return dir;
}
async function createIsolatedFixture(statementTimeoutMs = 15_000) {
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=${statementTimeoutMs} -c lock_timeout=15000`,
});
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 withRecordingClient<T>(
pool: Pool,
fn: (queryable: SecurityMasterQueryable, recordedSql: string[]) => Promise<T>
): Promise<T> {
const client: PoolClient = await pool.connect();
const recordedSql: string[] = [];
const queryable: SecurityMasterQueryable = {
query<Row = Record<string, unknown>>(
text: string,
values?: readonly unknown[]
): Promise<SecurityMasterQueryResult<Row>> {
recordedSql.push(text.replace(/\s+/g, ' ').trim());
return client.query(
text,
values === undefined ? undefined : [...values]
) as unknown as Promise<SecurityMasterQueryResult<Row>>;
},
release: () => {
client.release();
},
};
try {
return await fn(queryable, recordedSql);
} finally {
client.release();
}
}
async function seedFixtureData(pool: Pool) {
const client = await pool.connect();
try {
await client.query('BEGIN');
// Ensure required 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
('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')
ON CONFLICT (mic) DO NOTHING
`);
const insertInstrument = async (
isin: string,
cusip: string,
name: string,
securityType: string,
country: string
): Promise<number> => {
const res = await client.query<{ instrument_id: number }>(
`INSERT INTO instrument (primary_isin, primary_cusip, canonical_name, security_type, issuer_country)
VALUES ($1, $2, $3, $4, $5)
RETURNING instrument_id`,
[isin, cusip, name, securityType, country]
);
return res.rows[0]!.instrument_id;
};
const instAapl = await insertInstrument('US0378331005', '037833100', 'Apple Inc.', 'common', 'US');
const instShop = await insertInstrument('CA82509L1076', '82509L107', 'Shopify Inc.', 'common', 'CA');
const instFbOld = await insertInstrument('US30303M1027', '30303M102', 'Meta Platforms', 'common', 'US');
const instFbNew = await insertInstrument('US4642872000', '464287200', 'FB Thematic ETF', 'etf', 'US');
const instSivb = await insertInstrument('US78486Q1013', '78486Q101', 'SVB Financial Group', 'common', 'US');
const instSivbReuse = await insertInstrument('US0000000019', '000000001', 'SIVB Reused Corp', 'common', 'US');
const instDel30 = await insertInstrument('US0000000027', '000000002', 'Delisted 30 Corp', 'common', 'US');
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 insertListing = async (params: {
instrumentId: number;
mic: string;
tickerRoot: string;
currency: string;
listedFrom: string | null;
listedTo: string | null;
delistReason: string | null;
terminalReturn: string | null;
}): Promise<number> => {
const res = 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, $2, $3, '', $4, $5::date, $6::date, $7, $8::numeric)
RETURNING listing_id`,
[
params.instrumentId,
params.mic,
params.tickerRoot,
params.currency,
params.listedFrom,
params.listedTo,
params.delistReason,
params.terminalReturn,
]
);
return res.rows[0]!.listing_id;
};
const aaplId = await insertListing({
instrumentId: instAapl,
mic: 'XNAS',
tickerRoot: 'AAPL',
currency: 'USD',
listedFrom: '1980-12-12',
listedTo: null,
delistReason: 'active',
terminalReturn: null,
});
const shopId = await insertListing({
instrumentId: instShop,
mic: 'XTSE',
tickerRoot: 'SHOP',
currency: 'CAD',
listedFrom: '2015-05-21',
listedTo: null,
delistReason: 'active',
terminalReturn: null,
});
const fbOldId = await insertListing({
instrumentId: instFbOld,
mic: 'XNAS',
tickerRoot: 'FB',
currency: 'USD',
listedFrom: '2012-05-18',
listedTo: '2022-06-08',
delistReason: null,
terminalReturn: null,
});
const fbNewId = await insertListing({
instrumentId: instFbNew,
mic: 'XNYS',
tickerRoot: 'FB',
currency: 'USD',
listedFrom: '2022-06-09',
listedTo: null,
delistReason: 'active',
terminalReturn: null,
});
const sivbId = await insertListing({
instrumentId: instSivb,
mic: 'XNAS',
tickerRoot: 'SIVB',
currency: 'USD',
listedFrom: '1988-01-04',
listedTo: '2023-03-10',
delistReason: 'moved_to_otc',
terminalReturn: null,
});
const sivbReuseId = await insertListing({
instrumentId: instSivbReuse,
mic: 'XNAS',
tickerRoot: 'SIVB',
currency: 'USD',
listedFrom: '2023-03-20',
listedTo: null,
delistReason: 'active',
terminalReturn: null,
});
const sivbqId = await insertListing({
instrumentId: instSivb,
mic: 'OTCM',
tickerRoot: 'SIVBQ',
currency: 'USD',
listedFrom: '2023-03-28',
listedTo: '2024-11-07',
delistReason: 'bankruptcy_cancelled',
terminalReturn: '-1.000000',
});
const del30Id = await insertListing({
instrumentId: instDel30,
mic: 'XNYS',
tickerRoot: 'DEL30',
currency: 'USD',
listedFrom: '2018-01-02',
listedTo: '2023-06-15',
delistReason: 'unknown_involuntary',
terminalReturn: '-0.300000',
});
const noListedToId = await insertListing({
instrumentId: instNoListedTo,
mic: 'XNYS',
tickerRoot: 'NLDT',
currency: 'USD',
listedFrom: '2019-01-02',
listedTo: null,
delistReason: 'unknown_involuntary',
terminalReturn: '-0.300000',
});
const noQmId = await insertListing({
instrumentId: instNoQm,
mic: 'XNYS',
tickerRoot: 'NOQM',
currency: 'USD',
listedFrom: '2019-01-02',
listedTo: '2023-07-01',
delistReason: 'unknown_involuntary',
terminalReturn: '-0.300000',
});
const noSuccQmFromId = await insertListing({
instrumentId: instNoSuccQm,
mic: 'XNYS',
tickerRoot: 'NOSU',
currency: 'USD',
listedFrom: '2019-01-02',
listedTo: '2023-03-10',
delistReason: 'moved_to_otc',
terminalReturn: null,
});
const noSuccQmToId = await insertListing({
instrumentId: instNoSuccQm,
mic: 'OTCM',
tickerRoot: 'NOSUQ',
currency: 'USD',
listedFrom: '2023-03-28',
listedTo: null,
delistReason: null,
terminalReturn: null,
});
const insertMapping = async (
source: string,
sourceId: string,
validFrom: string,
validTo: string | null,
listingId: number
) => {
await client.query(
`INSERT INTO provider_mapping (source, source_id, valid_from, valid_to, listing_id, method, confidence)
VALUES ($1, $2, $3::date, $4::date, $5, 'tier1_isin', 0.990)`,
[source, sourceId, validFrom, validTo, listingId]
);
};
// Active US + CA
await insertMapping('eod', 'AAPL.US', '1980-12-12', null, aaplId);
await insertMapping('qm', 'AAPL', '1980-12-12', null, aaplId);
await insertMapping('eod', 'SHOP.TO', '2015-05-21', null, shopId);
await insertMapping('qm', 'SHOP:CA', '2015-05-21', null, shopId);
// Ticker reuse FB across two date ranges
await insertMapping('eod', 'FB.US', '2012-05-18', '2022-06-08', fbOldId);
await insertMapping('eod', 'FB.US', '2022-06-09', null, fbNewId);
await insertMapping('qm', 'FB', '2012-05-18', '2022-06-08', fbOldId);
await insertMapping('qm', 'FB', '2022-06-09', null, fbNewId);
// SIVB -> SIVBQ across ticker reuse
await insertMapping('eod', 'SIVB.US', '1988-01-04', '2023-03-10', sivbId);
await insertMapping('eod', 'SIVB.US', '2023-03-20', null, sivbReuseId);
await insertMapping('eod', 'SIVBQ.US', '2023-03-28', '2024-11-07', sivbqId);
await insertMapping('qm', 'SIVB', '1988-01-04', '2023-03-10', sivbId);
await insertMapping('qm', 'SIVB', '2023-03-20', null, sivbReuseId);
await insertMapping('qm', 'SIVBQ', '2023-03-28', '2024-11-07', sivbqId);
// DEL30 -0.3 terminal delisting
await insertMapping('eod', 'DEL30.US', '2018-01-02', '2023-06-15', del30Id);
await insertMapping('qm', 'DEL30', '2018-01-02', '2023-06-15', del30Id);
// Skipped-row mappings: noQm has only eod; noSuccQmFrom has qm, successor has no qm
await insertMapping('eod', 'NOQM.US', '2019-01-02', '2023-07-01', noQmId);
await insertMapping('qm', 'NOSU', '2019-01-02', '2023-03-10', noSuccQmFromId);
// Continuities
await client.query(
`INSERT INTO corporate_action_continuity (from_listing_id, to_listing_id, effective_date, kind)
VALUES
($1, $2, '2023-03-28'::date, 'otc_delist_transfer'),
($3, $4, '2023-03-28'::date, 'otc_delist_transfer')`,
[sivbId, sivbqId, noSuccQmFromId, noSuccQmToId]
);
await client.query('COMMIT');
return {
aaplId,
shopId,
fbOldId,
fbNewId,
sivbId,
sivbReuseId,
sivbqId,
del30Id,
noListedToId,
noQmId,
noSuccQmFromId,
noSuccQmToId,
};
} catch (error) {
await client.query('ROLLBACK').catch(() => {});
throw error;
} finally {
client.release();
}
}
describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*)', () => {
test('exports exact TSV bytes read-only and matches across chunkSize=1 and chunkSize=5000', async () => {
const { pool } = await createIsolatedFixture();
const ids = await seedFixtureData(pool);
const outDir5000 = await makeTempDir('curate-inputs-pg-5000-');
const outDir1 = await makeTempDir('curate-inputs-pg-1-');
const { result: res5000, sql: sql5000 } = await withRecordingClient(
pool,
async (queryable, recordedSql) => ({
result: await exportCurateInputs(queryable, { outDir: outDir5000, chunkSize: 5000 }),
sql: recordedSql,
})
);
const { result: res1, sql: sql1 } = await withRecordingClient(
pool,
async (queryable, recordedSql) => ({
result: await exportCurateInputs(queryable, { outDir: outDir1, chunkSize: 1 }),
sql: recordedSql,
})
);
// Read-only SQL verification: REPEATABLE READ READ ONLY transaction + server-side cursor + zero writes/DDL.
for (const sqlLog of [sql5000, sql1]) {
expect(sqlLog[0]).toBe('BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
expect(sqlLog[sqlLog.length - 1]).toBe('COMMIT');
expect(sqlLog.some(s => s.startsWith('DECLARE curate_export_pm_cursor NO SCROLL CURSOR FOR'))).toBe(
true
);
expect(sqlLog.some(s => s === 'CLOSE curate_export_pm_cursor')).toBe(true);
for (const stmt of sqlLog) {
expect(stmt).not.toMatch(/\b(INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|TRUNCATE|GRANT|REVOKE)\b/i);
}
}
// Verify snapshot pinning resolves to the published immutable generation.
const pinned5000 = await pinCurateInputSnapshot(outDir5000);
expect(pinned5000.generationId).toBe(res5000.generationId);
expect(pinned5000.providerMapping).toBe(res5000.providerMapping.path);
expect(pinned5000.listingCurrencies).toBe(res5000.listingCurrencies.path);
expect(pinned5000.delistings).toBe(res5000.delistings.path);
// Verify chunkSize=1 actually paginated across multiple queries.
expect(sql1.length).toBeGreaterThan(sql5000.length);
// 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 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.delistings.path, 'utf8')).toBe(dl5000);
// Assert exact provider_mapping.tsv content (COLLATE "C" ASCII order).
expect(pm5000).toBe(
[
`eod\tAAPL.US\t1980-12-12\t\t${ids.aaplId}`,
`eod\tDEL30.US\t2018-01-02\t2023-06-15\t${ids.del30Id}`,
`eod\tFB.US\t2012-05-18\t2022-06-08\t${ids.fbOldId}`,
`eod\tFB.US\t2022-06-09\t\t${ids.fbNewId}`,
`eod\tNOQM.US\t2019-01-02\t2023-07-01\t${ids.noQmId}`,
`eod\tSHOP.TO\t2015-05-21\t\t${ids.shopId}`,
`eod\tSIVB.US\t1988-01-04\t2023-03-10\t${ids.sivbId}`,
`eod\tSIVB.US\t2023-03-20\t\t${ids.sivbReuseId}`,
`eod\tSIVBQ.US\t2023-03-28\t2024-11-07\t${ids.sivbqId}`,
`qm\tAAPL\t1980-12-12\t\t${ids.aaplId}`,
`qm\tDEL30\t2018-01-02\t2023-06-15\t${ids.del30Id}`,
`qm\tFB\t2012-05-18\t2022-06-08\t${ids.fbOldId}`,
`qm\tFB\t2022-06-09\t\t${ids.fbNewId}`,
`qm\tNOSU\t2019-01-02\t2023-03-10\t${ids.noSuccQmFromId}`,
`qm\tSHOP:CA\t2015-05-21\t\t${ids.shopId}`,
`qm\tSIVB\t1988-01-04\t2023-03-10\t${ids.sivbId}`,
`qm\tSIVB\t2023-03-20\t\t${ids.sivbReuseId}`,
`qm\tSIVBQ\t2023-03-28\t2024-11-07\t${ids.sivbqId}`,
'',
].join('\n')
);
// Assert exact listing_currencies.tsv content (btrim(CHAR(3)), ascending listing_id).
expect(lc5000).toBe(
[
`${ids.aaplId}\tUSD`,
`${ids.shopId}\tCAD`,
`${ids.fbOldId}\tUSD`,
`${ids.fbNewId}\tUSD`,
`${ids.sivbId}\tUSD`,
`${ids.sivbReuseId}\tUSD`,
`${ids.sivbqId}\tUSD`,
`${ids.del30Id}\tUSD`,
`${ids.noListedToId}\tUSD`,
`${ids.noQmId}\tUSD`,
`${ids.noSuccQmFromId}\tUSD`,
`${ids.noSuccQmToId}\tUSD`,
'',
].join('\n')
);
// Assert exact delistings.tsv content.
expect(dl5000).toBe(
[
`DEL30\t2023-06-15\t${ids.del30Id}\t\t-0.3`,
`SIVB\t2023-03-28\t${ids.sivbId}\tSIVBQ\t`,
`SIVBQ\t2024-11-07\t${ids.sivbqId}\t\t-1`,
'',
].join('\n')
);
// Assert exact stats reconciliation.
const stats = res5000.delistings.stats;
expect(stats).toEqual({
rowsIn: 12,
rowsOut: 3,
otcTransfersOut: 1,
terminalDelistingsOut: 2,
skippedTotal: 9,
skipped: {
active: 4, // AAPL, SHOP, FB new, SIVB reuse
noOutcome: 2, // FB old, NOSUQ
missingListedTo: 1, // NLDT
missingOutgoingQmMapping: 1, // NOQM
missingSuccessorQmMapping: 1, // NOSU -> NOSUQ
nonOtcContinuity: 0,
},
});
expect(stats.rowsIn).toBe(stats.rowsOut + stats.skippedTotal);
expect(res1.delistings.stats).toEqual(stats);
});
});