import { afterEach, describe, expect, test } from 'bun:test'; import { mkdtemp, open, readdir, readFile, rename, rm, unlink, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { initializeStockConfig, resetStockConfig, type StockAppConfig, } from '@stock-bot/stock-config'; import { assertExportCurateInputsSafety, buildDelistingExportRows, CURATE_INPUT_FILES, CURATE_INPUT_PUBLISH_LOCK, CurateInputExportError, DEFAULT_EXPORT_CHUNK_SIZE, EXPORT_CURATE_INPUTS_USAGE, exportCurateInputs, formatDelistingsTsv, formatExportCurateInputsSummary, formatListingCurrenciesTsv, formatPlainDecimal, formatProviderMappingTsv, parseExportCurateInputsArgs, pinCurateInputSnapshot, runExportCurateInputs, runExportCurateInputsCli, type ContinuityExportSourceRow, type DelistingExportRow, type ListingCurrencyExportRow, type ListingDelistingSourceRow, type ProviderMappingExportRow, type SecurityMasterQueryable, type SecurityMasterQueryResult, } from '../../apps/stock/data-pipeline/src/security-master'; import { compareAscii } from '../../apps/stock/data-pipeline/src/security-master/exchange-pass1'; const tempDirs: string[] = []; afterEach(async () => { for (const dir of tempDirs.splice(0).reverse()) { await rm(dir, { recursive: true, force: true }); } }); async function makeTempDir(prefix = 'curate-inputs-unit-'): Promise { const dir = await mkdtemp(join(tmpdir(), prefix)); tempDirs.push(dir); return dir; } function expectExportError( fn: () => unknown, expectedCode: CurateInputExportError['code'], expectedTable: string, expectedKeySubstring: string ): CurateInputExportError { try { fn(); } catch (error) { expect(error).toBeInstanceOf(CurateInputExportError); const err = error as CurateInputExportError; expect(err.code).toBe(expectedCode); expect(err.table).toBe(expectedTable); expect(err.key).toContain(expectedKeySubstring); expect(err.message).toContain(expectedTable); expect(err.message).toContain(expectedKeySubstring); return err; } throw new Error(`Expected CurateInputExportError(${expectedCode}), but function did not throw`); } async function expectExportErrorAsync( fn: () => Promise, expectedCode: CurateInputExportError['code'], expectedTable: string, expectedKeySubstring: string ): Promise { try { await fn(); } catch (error) { expect(error).toBeInstanceOf(CurateInputExportError); const err = error as CurateInputExportError; expect(err.code).toBe(expectedCode); expect(err.table).toBe(expectedTable); expect(err.key).toContain(expectedKeySubstring); expect(err.message).toContain(expectedTable); expect(err.message).toContain(expectedKeySubstring); return err; } throw new Error(`Expected CurateInputExportError(${expectedCode}), but async fn did not throw`); } interface InMemorySecurityMasterData { readonly listings: readonly { readonly listing_id: number; readonly currency: string | null; readonly listed_to: string | null; readonly delist_reason: string | null; readonly terminal_return: string | null; }[]; readonly continuities: readonly { readonly from_listing_id: number; readonly to_listing_id: number; readonly effective_date: string; readonly kind: string; }[]; readonly providerMappings: readonly { readonly source: string | null; readonly source_id: string | null; readonly valid_from: string | null; readonly valid_to: string | null; readonly listing_id: number; }[]; } function createInMemoryQueryable( data: InMemorySecurityMasterData, hooks?: { readonly failOnQueryNumber?: number; readonly recordedSql?: string[]; } ): SecurityMasterQueryable { const sortedContinuities = [...data.continuities] .filter(c => c.kind === 'otc_delist_transfer') .sort( (a, b) => a.from_listing_id - b.from_listing_id || compareAscii(a.effective_date, b.effective_date) ); const sortedListings = [...data.listings].sort((a, b) => a.listing_id - b.listing_id); const sortedMappings = [...data.providerMappings].sort( (a, b) => compareAscii(a.source ?? '', b.source ?? '') || compareAscii(a.source_id ?? '', b.source_id ?? '') || compareAscii(a.valid_from ?? '', b.valid_from ?? '') ); let queryCount = 0; let pmCursorOpen = false; let pmCursorOffset = 0; return { async query>( text: string, values?: readonly unknown[] ): Promise> { queryCount += 1; hooks?.recordedSql?.push(text.trim()); if (hooks?.failOnQueryNumber === queryCount) { throw new Error(`Simulated DB query failure at query #${queryCount}`); } const normalized = text.replace(/\s+/g, ' ').trim(); if ( normalized.startsWith('BEGIN') || normalized === 'COMMIT' || normalized === 'ROLLBACK' ) { if (normalized === 'COMMIT' || normalized === 'ROLLBACK') { pmCursorOpen = false; pmCursorOffset = 0; } return { rows: [] }; } if (normalized.startsWith('DECLARE ') && normalized.includes('FROM provider_mapping')) { pmCursorOpen = true; pmCursorOffset = 0; return { rows: [] }; } const fetchMatch = /^FETCH FORWARD (\d+) FROM \S+$/i.exec(normalized); if (fetchMatch) { if (!pmCursorOpen) { throw new Error('Cursor not open for FETCH'); } const limit = Number(fetchMatch[1]); const slice = sortedMappings.slice(pmCursorOffset, pmCursorOffset + limit); pmCursorOffset += slice.length; return { rows: slice as unknown as Row[] }; } if (/^CLOSE \S+$/i.test(normalized)) { pmCursorOpen = false; pmCursorOffset = 0; return { rows: [] }; } if (normalized.includes('FROM corporate_action_continuity')) { if (values && values.length === 1) { const limit = values[0] as number; return { rows: sortedContinuities.slice(0, limit) as unknown as Row[] }; } const [lastFromId, lastEffDate, limit] = values as [number, string, number]; const filtered = sortedContinuities.filter( c => c.from_listing_id > lastFromId || (c.from_listing_id === lastFromId && c.effective_date > lastEffDate) ); return { rows: filtered.slice(0, limit) as unknown as Row[] }; } if (normalized.includes('FROM listing')) { if (values && values.length === 1) { const limit = values[0] as number; return { rows: sortedListings.slice(0, limit) as unknown as Row[] }; } const [lastListingId, limit] = values as [number, number]; const filtered = sortedListings.filter(l => l.listing_id > lastListingId); return { rows: filtered.slice(0, limit) as unknown as Row[] }; } if (normalized.includes('FROM provider_mapping')) { if (values && values.length === 1) { const limit = values[0] as number; return { rows: sortedMappings.slice(0, limit) as unknown as Row[] }; } const [lastSource, lastSourceId, lastValidFrom, limit] = values as [ string, string, string, number, ]; const filtered = sortedMappings.filter(m => { const src = m.source ?? ''; const sid = m.source_id ?? ''; const vf = m.valid_from ?? ''; const srcCmp = compareAscii(src, lastSource); if (srcCmp !== 0) { return srcCmp > 0; } const sidCmp = compareAscii(sid, lastSourceId); if (sidCmp !== 0) { return sidCmp > 0; } return compareAscii(vf, lastValidFrom) > 0; }); return { rows: filtered.slice(0, limit) as unknown as Row[] }; } throw new Error(`Unexpected SQL in in-memory queryable: ${normalized}`); }, release: () => {}, }; } /** * Canonical golden fixture dataset shared with `tools/curate-etl/tests/fixtures/curate-inputs/` * and `tools/curate-etl/src/tsv_fixture_tests.rs`. */ function buildGoldenFixtureDataset() { const listings: ListingCurrencyExportRow[] = [ { listingId: 1, currency: 'USD' }, // AAPL active US { listingId: 2, currency: 'USD' }, // FB old (ticker reuse range 1) { listingId: 3, currency: 'USD' }, // FB new ETF (ticker reuse range 2) { listingId: 4, currency: 'USD' }, // SIVB primary listing -> OTC transfer to 6 { listingId: 5, currency: 'USD' }, // SIVB unrelated ticker reuse after halt { listingId: 6, currency: 'USD' }, // SIVBQ OTC successor -> later cancelled (-1) { listingId: 7, currency: 'USD' }, // DEL30 Shumway terminal delisting (-0.3) { listingId: 8, currency: 'CAD' }, // SHOP active CA ]; const delistingListings: ListingDelistingSourceRow[] = [ { listingId: 1, listedTo: null, delistReason: 'active', terminalReturn: null }, { listingId: 2, listedTo: '2022-06-08', delistReason: null, terminalReturn: null }, { listingId: 3, listedTo: null, delistReason: 'active', terminalReturn: null }, { listingId: 4, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null }, { listingId: 5, listedTo: null, delistReason: 'active', terminalReturn: null }, { listingId: 6, listedTo: '2024-11-07', delistReason: 'bankruptcy_cancelled', terminalReturn: '-1.000000', }, { listingId: 7, listedTo: '2023-06-15', delistReason: 'unknown_involuntary', terminalReturn: '-0.300000', }, { listingId: 8, listedTo: null, delistReason: 'active', terminalReturn: null }, ]; const continuities: ContinuityExportSourceRow[] = [ { fromListingId: 4, toListingId: 6, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer', }, ]; const providerMappings: ProviderMappingExportRow[] = [ { source: 'eod', sourceId: 'AAPL.US', validFrom: '1980-12-12', validTo: null, listingId: 1 }, { source: 'eod', sourceId: 'DEL30.US', validFrom: '2018-01-02', validTo: '2023-06-15', listingId: 7, }, { source: 'eod', sourceId: 'FB.US', validFrom: '2012-05-18', validTo: '2022-06-08', listingId: 2, }, { source: 'eod', sourceId: 'FB.US', validFrom: '2022-06-09', validTo: null, listingId: 3 }, { source: 'eod', sourceId: 'SHOP.TO', validFrom: '2015-05-21', validTo: null, listingId: 8 }, { source: 'eod', sourceId: 'SIVB.US', validFrom: '1988-01-04', validTo: '2023-03-10', listingId: 4, }, { source: 'eod', sourceId: 'SIVB.US', validFrom: '2023-03-20', validTo: null, listingId: 5 }, { source: 'eod', sourceId: 'SIVBQ.US', validFrom: '2023-03-28', validTo: '2024-11-07', listingId: 6, }, { source: 'qm', sourceId: 'AAPL', validFrom: '1980-12-12', validTo: null, listingId: 1 }, { source: 'qm', sourceId: 'DEL30', validFrom: '2018-01-02', validTo: '2023-06-15', listingId: 7, }, { source: 'qm', sourceId: 'FB', validFrom: '2012-05-18', validTo: '2022-06-08', listingId: 2, }, { source: 'qm', sourceId: 'FB', validFrom: '2022-06-09', validTo: null, listingId: 3 }, { source: 'qm', sourceId: 'SHOP:CA', validFrom: '2015-05-21', validTo: null, listingId: 8 }, { source: 'qm', sourceId: 'SIVB', validFrom: '1988-01-04', validTo: '2023-03-10', listingId: 4, }, { source: 'qm', sourceId: 'SIVB', validFrom: '2023-03-20', validTo: null, listingId: 5 }, { source: 'qm', sourceId: 'SIVBQ', validFrom: '2023-03-28', validTo: '2024-11-07', listingId: 6, }, ]; return { listings, delistingListings, continuities, providerMappings }; } describe('formatPlainDecimal', () => { test('normalizes -0 to 0 and expands scientific notation without losing precision', () => { expect(formatPlainDecimal(-0)).toBe('0'); expect(formatPlainDecimal(0)).toBe('0'); expect(formatPlainDecimal(-1)).toBe('-1'); expect(formatPlainDecimal(-0.3)).toBe('-0.3'); expect(formatPlainDecimal(-1e-7)).toBe('-0.0000001'); expect(formatPlainDecimal(-5.25e-8)).toBe('-0.0000000525'); }); }); describe('formatProviderMappingTsv', () => { test('emits exact bytes with deterministic ASCII sort under shuffled input, empty valid_to, and verbatim source_id', () => { const rows: ProviderMappingExportRow[] = [ { source: 'qm', sourceId: 'b', validFrom: '2020-01-01', validTo: null, listingId: 2 }, { source: 'eod', sourceId: ' AAPL.US ', validFrom: '2000-01-03', validTo: null, listingId: 1 }, { source: 'qm', sourceId: 'A', validFrom: '2022-06-09', validTo: null, listingId: 4 }, { source: 'qm', sourceId: 'A', validFrom: '2012-05-18', validTo: '2022-06-08', listingId: 3, }, ]; const expected = [ 'eod\t AAPL.US \t2000-01-03\t\t1', 'qm\tA\t2012-05-18\t2022-06-08\t3', 'qm\tA\t2022-06-09\t\t4', 'qm\tb\t2020-01-01\t\t2', '', ].join('\n'); expect(formatProviderMappingTsv(rows)).toBe(expected); expect(formatProviderMappingTsv([...rows].reverse())).toBe(expected); }); test('empty input produces empty string (0-byte file)', () => { expect(formatProviderMappingTsv([])).toBe(''); }); test('fails closed on forbidden control chars, blanks, bad dates, bad listing_id, duplicates, and overlaps', () => { expectExportError( () => formatProviderMappingTsv([ { source: 'eod', sourceId: 'BAD\tID', validFrom: '2020-01-01', validTo: null, listingId: 1 }, ]), 'FORBIDDEN_CONTROL_CHAR', 'provider_mapping', 'eod:row#0' ); expectExportError( () => formatProviderMappingTsv([ { source: 'eod', sourceId: 'BAD\nID', validFrom: '2020-01-01', validTo: null, listingId: 1 }, ]), 'FORBIDDEN_CONTROL_CHAR', 'provider_mapping', 'eod:row#0' ); expectExportError( () => formatProviderMappingTsv([ { source: 'eod', sourceId: 'BAD\rID', validFrom: '2020-01-01', validTo: null, listingId: 1 }, ]), 'FORBIDDEN_CONTROL_CHAR', 'provider_mapping', 'eod:row#0' ); expectExportError( () => formatProviderMappingTsv([ { source: ' ', sourceId: 'AAPL', validFrom: '2020-01-01', validTo: null, listingId: 1 }, ]), 'BLANK_FIELD', 'provider_mapping', 'row#0' ); expectExportError( () => formatProviderMappingTsv([ { source: 'eod', sourceId: ' ', validFrom: '2020-01-01', validTo: null, listingId: 1 }, ]), 'BLANK_FIELD', 'provider_mapping', 'eod:row#0' ); expectExportError( () => formatProviderMappingTsv([ { source: 'eod', sourceId: 'AAPL', validFrom: '2023-02-29', validTo: null, listingId: 1 }, ]), 'INVALID_DATE', 'provider_mapping', 'eod:AAPL:2023-02-29' ); expectExportError( () => formatProviderMappingTsv([ { source: 'eod', sourceId: 'AAPL', validFrom: '2023-05-01', validTo: '2023-04-30', listingId: 1, }, ]), 'INVALID_DATE_RANGE', 'provider_mapping', 'eod:AAPL:2023-05-01' ); expectExportError( () => formatProviderMappingTsv([ { source: 'eod', sourceId: 'AAPL', validFrom: '2020-01-01', validTo: null, listingId: 0 }, ]), 'INVALID_LISTING_ID', 'provider_mapping', 'eod:AAPL:2020-01-01' ); expectExportError( () => formatProviderMappingTsv([ { source: 'eod', sourceId: 'AAPL', validFrom: '2020-01-01', validTo: null, listingId: 2_147_483_648, }, ]), 'INVALID_LISTING_ID', 'provider_mapping', 'eod:AAPL:2020-01-01' ); expectExportError( () => formatProviderMappingTsv([ { source: 'qm', sourceId: 'FB', validFrom: '2020-01-01', validTo: '2021-01-01', listingId: 1 }, { source: 'qm', sourceId: 'FB', validFrom: '2020-01-01', validTo: '2022-01-01', listingId: 2 }, ]), 'DUPLICATE_PROVIDER_MAPPING', 'provider_mapping', 'qm:FB:2020-01-01' ); expectExportError( () => formatProviderMappingTsv([ { source: 'qm', sourceId: 'FB', validFrom: '2020-01-01', validTo: '2021-06-01', listingId: 1 }, { source: 'qm', sourceId: 'FB', validFrom: '2021-06-01', validTo: null, listingId: 2 }, ]), 'OVERLAPPING_PROVIDER_MAPPING', 'provider_mapping', 'qm:FB:2021-06-01' ); expectExportError( () => formatProviderMappingTsv([ { source: 'qm', sourceId: 'FB', validFrom: '2020-01-01', validTo: null, listingId: 1 }, { source: 'qm', sourceId: 'FB', validFrom: '2021-06-01', validTo: null, listingId: 2 }, ]), 'OVERLAPPING_PROVIDER_MAPPING', 'provider_mapping', 'qm:FB:2021-06-01' ); }); }); describe('formatListingCurrenciesTsv', () => { test('sorts by ascending listing_id and handles empty input', () => { expect(formatListingCurrenciesTsv([])).toBe(''); const rows: ListingCurrencyExportRow[] = [ { listingId: 10, currency: 'CAD' }, { listingId: 2, currency: 'USD' }, { listingId: 5, currency: 'USD' }, ]; const expected = '2\tUSD\n5\tUSD\n10\tCAD\n'; expect(formatListingCurrenciesTsv(rows)).toBe(expected); expect(formatListingCurrenciesTsv([...rows].reverse())).toBe(expected); }); test('fails closed on blank/null currency, control chars, invalid listing_id, and duplicate listing_id', () => { expectExportError( () => formatListingCurrenciesTsv([{ listingId: 1, currency: '' }]), 'BLANK_FIELD', 'listing', 'listing_id=1' ); expectExportError( () => formatListingCurrenciesTsv([{ listingId: 1, currency: null as unknown as string }]), 'BLANK_FIELD', 'listing', 'listing_id=1' ); expectExportError( () => formatListingCurrenciesTsv([{ listingId: 1, currency: 'US\tD' }]), 'FORBIDDEN_CONTROL_CHAR', 'listing', 'listing_id=1' ); expectExportError( () => formatListingCurrenciesTsv([{ listingId: -3, currency: 'USD' }]), 'INVALID_LISTING_ID', 'listing', 'row#0' ); expectExportError( () => formatListingCurrenciesTsv([ { listingId: 7, currency: 'USD' }, { listingId: 7, currency: 'CAD' }, ]), 'DUPLICATE_LISTING_CURRENCY', 'listing', 'listing_id=7' ); }); }); describe('buildDelistingExportRows and formatDelistingsTsv', () => { test('handles OTC transfer + successor terminal delisting (SIVB -> SIVBQ -> -1), -0.3 Shumway, active/null skips, and stats conservation', () => { const listings: ListingDelistingSourceRow[] = [ { listingId: 1, listedTo: null, delistReason: 'active', terminalReturn: null }, { listingId: 2, listedTo: '2022-06-08', delistReason: null, terminalReturn: null }, { listingId: 4, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null }, { listingId: 6, listedTo: '2024-11-07', delistReason: 'bankruptcy_cancelled', terminalReturn: -1 }, { listingId: 7, listedTo: '2023-06-15', delistReason: 'unknown_involuntary', terminalReturn: -0.3 }, { listingId: 9, listedTo: null, delistReason: 'unknown_involuntary', terminalReturn: -0.3 }, // missingListedTo { listingId: 10, listedTo: '2023-07-01', delistReason: 'unknown_involuntary', terminalReturn: -0.3 }, // missingOutgoingQmMapping { listingId: 11, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null }, // missingSuccessorQmMapping { listingId: 12, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null }, // missingOutgoingQmMapping for OTC { listingId: 13, listedTo: '2023-08-01', delistReason: 'merger_cash', terminalReturn: -0 }, // -0 normalized to 0 { listingId: 14, listedTo: '2023-08-02', delistReason: 'merger_cash', terminalReturn: -1e-7 }, // tiny decimal without sci notation ]; const continuities: ContinuityExportSourceRow[] = [ { fromListingId: 4, toListingId: 6, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' }, { fromListingId: 11, toListingId: 99, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' }, { fromListingId: 12, toListingId: 6, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' }, { fromListingId: 1, toListingId: 2, effectiveDate: '2021-01-01', kind: 'venue_uplisting' }, ]; const mappings: ProviderMappingExportRow[] = [ { source: 'qm', sourceId: 'SIVB', validFrom: '1988-01-04', validTo: '2023-03-10', listingId: 4 }, { source: 'qm', sourceId: 'SIVBQ', validFrom: '2023-03-28', validTo: '2024-11-07', listingId: 6 }, { source: 'qm', sourceId: 'DEL30', validFrom: '2018-01-02', validTo: '2023-06-15', listingId: 7 }, { source: 'qm', sourceId: 'NOSUCC', validFrom: '2019-01-01', validTo: '2023-03-10', listingId: 11 }, { source: 'qm', sourceId: 'ZERO', validFrom: '2020-01-01', validTo: '2023-08-01', listingId: 13 }, { source: 'qm', sourceId: 'TINY', validFrom: '2020-01-01', validTo: '2023-08-02', listingId: 14 }, { source: 'eod', sourceId: 'NOQM.US', validFrom: '2020-01-01', validTo: '2023-07-01', listingId: 10 }, ]; const result = buildDelistingExportRows(listings, continuities, mappings); const { stats } = result; expect(stats.otcTransfersOut).toBe(1); expect(stats.terminalDelistingsOut).toBe(4); expect(stats.rowsOut).toBe(5); expect(stats.skipped).toEqual({ active: 1, noOutcome: 1, missingListedTo: 1, missingOutgoingQmMapping: 2, missingSuccessorQmMapping: 1, nonOtcContinuity: 1, }); expect(stats.skippedTotal).toBe(7); expect(stats.rowsIn).toBe(stats.rowsOut + stats.skippedTotal); const tsv = formatDelistingsTsv(result.rows); expect(tsv).toBe( [ 'DEL30\t2023-06-15\t7\t\t-0.3', 'SIVB\t2023-03-28\t4\tSIVBQ\t', 'SIVBQ\t2024-11-07\t6\t\t-1', 'TINY\t2023-08-02\t14\t\t-0.0000001', 'ZERO\t2023-08-01\t13\t\t0', '', ].join('\n') ); // Deterministic under shuffled inputs const shuffledResult = buildDelistingExportRows( [...listings].reverse(), [...continuities].reverse(), [...mappings].reverse() ); expect(formatDelistingsTsv(shuffledResult.rows)).toBe(tsv); expect(shuffledResult.stats).toEqual(stats); }); test('empty input produces empty string (0-byte file)', () => { expect(formatDelistingsTsv([])).toBe(''); }); test('fails closed on invalid delisting rows and DB conflicts', () => { const bothOutcomes: DelistingExportRow = { sourceId: 'SIVB', delistDate: '2023-03-28', fromListingId: 4, successorSourceId: 'SIVBQ', terminalReturn: -0.3, }; expectExportError( () => formatDelistingsTsv([bothOutcomes]), 'INVALID_DELISTING_OUTCOME', 'delistings', 'SIVB:2023-03-28' ); const neitherOutcome: DelistingExportRow = { sourceId: 'SIVB', delistDate: '2023-03-28', fromListingId: 4, successorSourceId: null, terminalReturn: null, }; expectExportError( () => formatDelistingsTsv([neitherOutcome]), 'INVALID_DELISTING_OUTCOME', 'delistings', 'SIVB:2023-03-28' ); expectExportError( () => formatDelistingsTsv([ { sourceId: 'SIVB', delistDate: '2023-03-28', fromListingId: null, successorSourceId: 'SIVBQ', terminalReturn: null, }, ]), 'MISSING_FROM_LISTING_ID', 'delistings', 'SIVB:2023-03-28' ); for (const badReturn of [0.01, -1.01, Number.NaN, Number.POSITIVE_INFINITY, ' -0.3', 'abc']) { expectExportError( () => formatDelistingsTsv([ { sourceId: 'BADRET', delistDate: '2023-06-15', fromListingId: 7, successorSourceId: null, terminalReturn: badReturn, }, ]), 'INVALID_TERMINAL_RETURN', 'delistings', 'BADRET:2023-06-15' ); } expectExportError( () => buildDelistingExportRows( [{ listingId: 1, listedTo: null, delistReason: 'active', terminalReturn: -0.3 }], [], [] ), 'ACTIVE_LISTING_WITH_OUTCOME', 'listing', 'listing_id=1' ); expectExportError( () => buildDelistingExportRows( [{ listingId: 4, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: -0.3 }], [{ fromListingId: 4, toListingId: 6, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' }], [] ), 'INVALID_DELISTING_OUTCOME', 'listing', 'listing_id=4' ); expectExportError( () => buildDelistingExportRows( [{ listingId: 4, listedTo: '2023-03-10', delistReason: 'moved_to_otc', terminalReturn: null }], [{ fromListingId: 4, toListingId: 4, effectiveDate: '2023-03-28', kind: 'otc_delist_transfer' }], [] ), 'SELF_SUCCESSOR_CONTINUITY', 'corporate_action_continuity', 'from_listing_id=4@2023-03-28' ); }); }); describe('exportCurateInputs atomic publish and streaming', () => { test('leaves pre-existing files byte-identical with zero leftover temp/bak files on mid-query, mid-validation, and mid-rename failures', async () => { const outDir = await makeTempDir('curate-inputs-atomic-'); const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping); const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies); const dlPath = join(outDir, CURATE_INPUT_FILES.delistings); const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n'; const origLc = '1\tUSD\n'; const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n'; await writeFile(pmPath, origPm, 'utf8'); await writeFile(lcPath, origLc, 'utf8'); await writeFile(dlPath, origDl, 'utf8'); const baseData: InMemorySecurityMasterData = { listings: [ { listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ { source: 'eod', source_id: 'NEW.US', valid_from: '2021-01-01', valid_to: null, listing_id: 1 }, ], }; const assertIntact = async () => { expect(await readFile(pmPath, 'utf8')).toBe(origPm); expect(await readFile(lcPath, 'utf8')).toBe(origLc); expect(await readFile(dlPath, 'utf8')).toBe(origDl); const entries = (await readdir(outDir)).sort(); expect(entries).toEqual([ CURATE_INPUT_FILES.delistings, CURATE_INPUT_FILES.listingCurrencies, CURATE_INPUT_FILES.providerMapping, ]); }; // 1. Mid-query failure const failingQueryClient = createInMemoryQueryable(baseData, { failOnQueryNumber: 3 }); await expect(exportCurateInputs(failingQueryClient, { outDir })).rejects.toThrow( 'Simulated DB query failure' ); await assertIntact(); // 2. Mid-validation failure (tab inside source_id) const badDataClient = createInMemoryQueryable({ ...baseData, providerMappings: [ { source: 'eod', source_id: 'BAD\tID', valid_from: '2021-01-01', valid_to: null, listing_id: 1 }, ], }); await expectExportErrorAsync( () => exportCurateInputs(badDataClient, { outDir }), 'FORBIDDEN_CONTROL_CHAR', 'provider_mapping', 'eod:row#0' ); await assertIntact(); // 3. Mid-rename failure on the 2nd top-level target symlink replacement (after staging->gen + 1st backup/link + 2nd backup) let renameCalls = 0; const goodClient = createInMemoryQueryable(baseData); await expect( exportCurateInputs(goodClient, { outDir, fs: { rename: async (oldPath, newPath) => { renameCalls += 1; if (renameCalls === 5) { throw new Error('Simulated EIO on 2nd target publish rename'); } return rename(oldPath, newPath); }, }, }) ).rejects.toThrow('Simulated EIO on 2nd target publish rename'); await assertIntact(); // 4. Failure at the atomic `current` commit rename restores all 3 pre-existing files cleanly const commitFailClient = createInMemoryQueryable(baseData); await expect( exportCurateInputs(commitFailClient, { outDir, fs: { rename: async (oldPath, newPath) => { if (String(newPath) === join(outDir, 'current')) { throw new Error('Simulated EIO on current commit rename'); } return rename(oldPath, newPath); }, }, }) ).rejects.toThrow('Simulated EIO on current commit rename'); await assertIntact(); }); test('post-commit backup deletion failure does not roll back committed publication and reports warning', async () => { const outDir = await makeTempDir('curate-inputs-post-commit-cleanup-'); const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping); const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies); const dlPath = join(outDir, CURATE_INPUT_FILES.delistings); await writeFile(pmPath, 'eod\tOLD.US\t2020-01-01\t\t1\n', 'utf8'); await writeFile(lcPath, '1\tUSD\n', 'utf8'); await writeFile(dlPath, 'OLD\t2023-01-01\t1\t\t-0.3\n', 'utf8'); const newData: InMemorySecurityMasterData = { listings: [ { listing_id: 2, currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ { source: 'eod', source_id: 'NEW.TO', valid_from: '2022-01-01', valid_to: null, listing_id: 2 }, ], }; let backupUnlinkCalls = 0; const result = await exportCurateInputs(createInMemoryQueryable(newData), { outDir, fs: { unlink: async filePath => { if (String(filePath).endsWith('.bak')) { backupUnlinkCalls += 1; if (backupUnlinkCalls === 2) { throw new Error('Simulated EIO deleting 2nd backup'); } } return unlink(filePath); }, }, }); // All three live paths reflect the new committed snapshot (no partial rollback). expect(await readFile(pmPath, 'utf8')).toBe('eod\tNEW.TO\t2022-01-01\t\t2\n'); expect(await readFile(lcPath, 'utf8')).toBe('2\tCAD\n'); expect(await readFile(dlPath, 'utf8')).toBe(''); // Backup #1 and #3 were deleted; #2 failed and is reported in cleanupWarnings. expect(backupUnlinkCalls).toBe(3); expect(result.cleanupWarnings).toHaveLength(1); expect(result.cleanupWarnings[0]).toContain('Simulated EIO deleting 2nd backup'); expect(result.cleanupWarnings[0]).toContain('.bak'); expect(formatExportCurateInputsSummary(result)).toContain('warning:'); }); test('failure during rollback restoration retains unrestored backup on disk and reports it', async () => { const outDir = await makeTempDir('curate-inputs-restore-fail-'); const pmPath = join(outDir, CURATE_INPUT_FILES.providerMapping); const lcPath = join(outDir, CURATE_INPUT_FILES.listingCurrencies); const dlPath = join(outDir, CURATE_INPUT_FILES.delistings); const origPm = 'eod\tORIG.US\t2020-01-01\t\t1\n'; const origLc = '1\tUSD\n'; const origDl = 'ORIG\t2023-01-01\t1\t\t-0.3\n'; await writeFile(pmPath, origPm, 'utf8'); await writeFile(lcPath, origLc, 'utf8'); await writeFile(dlPath, origDl, 'utf8'); const newData: InMemorySecurityMasterData = { listings: [ { listing_id: 2, currency: 'CAD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ { source: 'eod', source_id: 'NEW.TO', valid_from: '2022-01-01', valid_to: null, listing_id: 2 }, ], }; const err = await expectExportErrorAsync( () => exportCurateInputs(createInMemoryQueryable(newData), { outDir, fs: { rename: async (oldPath, newPath) => { // Fail at the atomic commit point to trigger rollback of all 3 backups. if (String(newPath) === join(outDir, 'current')) { throw new Error('Simulated commit EIO'); } // Fail restoring the provider_mapping backup specifically. if ( String(oldPath).includes(`${CURATE_INPUT_FILES.providerMapping}.`) && String(oldPath).endsWith('.bak') && String(newPath) === pmPath ) { throw new Error('Simulated restore EIO'); } return rename(oldPath, newPath); }, }, }), 'PUBLISH_ROLLBACK_FAILED', 'publish', 'providerMapping' ); expect(err.message).toContain('Simulated commit EIO'); expect(err.message).toContain('Simulated restore EIO'); expect(err.message).toContain('.bak'); // The other two targets were restored intact. expect(await readFile(lcPath, 'utf8')).toBe(origLc); expect(await readFile(dlPath, 'utf8')).toBe(origDl); // The unrestored provider_mapping backup MUST still exist on disk with original bytes! const entries = await readdir(outDir); const retainedBackups = entries.filter( e => e.startsWith(`${CURATE_INPUT_FILES.providerMapping}.`) && e.endsWith('.bak') ); expect(retainedBackups).toHaveLength(1); expect(await readFile(join(outDir, retainedBackups[0]!), 'utf8')).toBe(origPm); }); test('consumer pinning snapshot during publication reads consistent pre-refresh generation while new consumers see new generation', async () => { const outDir = await makeTempDir('curate-inputs-pin-during-publish-'); // Generation 1: only SIVB active (no SIVBQ successor yet). const gen1Data: InMemorySecurityMasterData = { listings: [ { listing_id: 4, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ { source: 'qm', source_id: 'SIVB', valid_from: '1988-01-04', valid_to: null, listing_id: 4 }, ], }; // Generation 2: SIVB -> SIVBQ OTC transfer added to both provider_mapping and delistings. const gen2Data: InMemorySecurityMasterData = { listings: [ { listing_id: 4, currency: 'USD', listed_to: '2023-03-10', delist_reason: 'moved_to_otc', terminal_return: null }, { listing_id: 6, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [ { from_listing_id: 4, to_listing_id: 6, effective_date: '2023-03-28', kind: 'otc_delist_transfer' }, ], providerMappings: [ { source: 'qm', source_id: 'SIVB', valid_from: '1988-01-04', valid_to: '2023-03-10', listing_id: 4 }, { source: 'qm', source_id: 'SIVBQ', valid_from: '2023-03-28', valid_to: null, listing_id: 6 }, ], }; const res1 = await exportCurateInputs(createInMemoryQueryable(gen1Data), { outDir }); // Consumer 1 pins generation 1 before opening any TSV, then reads provider_mapping.tsv. const pinned1 = await pinCurateInputSnapshot(outDir); expect(pinned1.generationId).toBe(res1.generationId); const consumer1Pm = await readFile(pinned1.providerMapping, 'utf8'); expect(consumer1Pm).toBe('qm\tSIVB\t1988-01-04\t\t4\n'); // While Consumer 1 is mid-read, Generation 2 publishes atomically. const res2 = await exportCurateInputs(createInMemoryQueryable(gen2Data), { outDir }); expect(res2.generationId).not.toBe(res1.generationId); // Consumer 1 finishes reading listing_currencies.tsv and delistings.tsv from its pinned generation 1. const consumer1Lc = await readFile(pinned1.listingCurrencies, 'utf8'); const consumer1Dl = await readFile(pinned1.delistings, 'utf8'); expect(consumer1Lc).toBe('4\tUSD\n'); expect(consumer1Dl).toBe(''); // Consistent with gen1 (no SIVBQ transfer referencing missing SIVBQ!) // Consumer 2 pins after Generation 2 committed and sees the full Generation 2 snapshot. const pinned2 = await pinCurateInputSnapshot(outDir); expect(pinned2.generationId).toBe(res2.generationId); expect(await readFile(pinned2.providerMapping, 'utf8')).toBe( 'qm\tSIVB\t1988-01-04\t2023-03-10\t4\nqm\tSIVBQ\t2023-03-28\t\t6\n' ); expect(await readFile(pinned2.listingCurrencies, 'utf8')).toBe('4\tUSD\n6\tUSD\n'); expect(await readFile(pinned2.delistings, 'utf8')).toBe('SIVB\t2023-03-28\t4\tSIVBQ\t\n'); }); test('concurrent exports to the same outDir never interleave into a mixed snapshot', async () => { const outDir = await makeTempDir('curate-inputs-concurrent-'); const snapA: InMemorySecurityMasterData = { listings: [ { listing_id: 10, currency: 'USD', listed_to: '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.3' }, ], continuities: [], providerMappings: [ { source: 'qm', source_id: 'SNAP_A', valid_from: '2020-01-01', valid_to: '2023-06-15', listing_id: 10 }, ], }; const snapB: InMemorySecurityMasterData = { listings: [ { listing_id: 20, currency: 'CAD', listed_to: '2024-01-15', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1' }, ], continuities: [], providerMappings: [ { source: 'qm', source_id: 'SNAP_B', valid_from: '2021-01-01', valid_to: '2024-01-15', listing_id: 20 }, ], }; const [resA, resB] = await Promise.all([ exportCurateInputs(createInMemoryQueryable(snapA), { outDir }), exportCurateInputs(createInMemoryQueryable(snapB), { outDir }), ]); const pinned = await pinCurateInputSnapshot(outDir); const pm = await readFile(pinned.providerMapping, 'utf8'); const lc = await readFile(pinned.listingCurrencies, 'utf8'); const dl = await readFile(pinned.delistings, 'utf8'); const isAllA = pinned.generationId === resA.generationId && pm === 'qm\tSNAP_A\t2020-01-01\t2023-06-15\t10\n' && lc === '10\tUSD\n' && dl === 'SNAP_A\t2023-06-15\t10\t\t-0.3\n'; const isAllB = pinned.generationId === resB.generationId && pm === 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' && lc === '20\tCAD\n' && dl === 'SNAP_B\t2024-01-15\t20\t\t-1\n'; expect(isAllA || isAllB).toBe(true); }); test('concurrent fresh-dir exports serialize publish/rollback so a failed export never deletes a committed export top-level links', async () => { const snapA: InMemorySecurityMasterData = { listings: [ { listing_id: 10, currency: 'USD', listed_to: '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.3' }, ], continuities: [], providerMappings: [ { source: 'qm', source_id: 'SNAP_A', valid_from: '2020-01-01', valid_to: '2023-06-15', listing_id: 10 }, ], }; const snapB: InMemorySecurityMasterData = { listings: [ { listing_id: 20, currency: 'CAD', listed_to: '2024-01-15', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1' }, ], continuities: [], providerMappings: [ { source: 'qm', source_id: 'SNAP_B', valid_from: '2021-01-01', valid_to: '2024-01-15', listing_id: 20 }, ], }; // Case 1: Export A enters publish first on a fresh dir, creates top-level links, and fails at // commit rename while Export B is waiting for `.publish.lock`. A rolls back cleanly under the // lock; B then acquires the lock and commits with all top-level and pinned paths readable. { const outDir = await makeTempDir('curate-inputs-race-a-fails-'); let aEnteredPublishResolve!: () => void; const aEnteredPublish = new Promise(resolve => { aEnteredPublishResolve = resolve; }); let bWaitingForLockResolve!: () => void; const bWaitingForLock = new Promise(resolve => { bWaitingForLockResolve = resolve; }); const promiseA = exportCurateInputs(createInMemoryQueryable(snapA), { outDir, fs: { rename: async (oldPath, newPath) => { if (String(newPath) === join(outDir, 'current')) { aEnteredPublishResolve(); await bWaitingForLock; throw new Error('Simulated commit EIO in Export A'); } return rename(oldPath, newPath); }, }, }); const promiseB = (async () => { await aEnteredPublish; let signaledWait = false; return exportCurateInputs(createInMemoryQueryable(snapB), { outDir, fs: { open: async (filePath, flags) => { if (String(filePath) === join(outDir, CURATE_INPUT_PUBLISH_LOCK) && !signaledWait) { signaledWait = true; bWaitingForLockResolve(); } return open(filePath, flags); }, }, }); })(); const [settledA, settledB] = await Promise.allSettled([promiseA, promiseB]); expect(settledA.status).toBe('rejected'); expect(settledB.status).toBe('fulfilled'); // Top-level TSV paths AND pinned snapshot must both resolve to Export B cleanly. expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe( 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' ); expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe( '20\tCAD\n' ); expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe( 'SNAP_B\t2024-01-15\t20\t\t-1\n' ); const pinned = await pinCurateInputSnapshot(outDir); expect(await readFile(pinned.delistings, 'utf8')).toBe('SNAP_B\t2024-01-15\t20\t\t-1\n'); const entries = await readdir(outDir); expect(entries.some(e => e.includes('.tmp') || e.includes('.bak') || e === CURATE_INPUT_PUBLISH_LOCK)).toBe(false); } // Case 2: Export B enters publish first on a fresh dir and commits while Export A is waiting // on `.publish.lock`; Export A then acquires the lock, sees existing top-level links, and fails // at commit rename. A's rollback must leave B's top-level links and `current` intact. { const outDir = await makeTempDir('curate-inputs-race-b-commits-'); let bEnteredPublishResolve!: () => void; const bEnteredPublish = new Promise(resolve => { bEnteredPublishResolve = resolve; }); let aWaitingForLockResolve!: () => void; const aWaitingForLock = new Promise(resolve => { aWaitingForLockResolve = resolve; }); const promiseB = exportCurateInputs(createInMemoryQueryable(snapB), { outDir, fs: { rename: async (oldPath, newPath) => { if (String(newPath) === join(outDir, 'current')) { bEnteredPublishResolve(); await aWaitingForLock; } return rename(oldPath, newPath); }, }, }); const promiseA = (async () => { await bEnteredPublish; let signaledWait = false; return exportCurateInputs(createInMemoryQueryable(snapA), { outDir, fs: { open: async (filePath, flags) => { if (String(filePath) === join(outDir, CURATE_INPUT_PUBLISH_LOCK) && !signaledWait) { signaledWait = true; aWaitingForLockResolve(); } return open(filePath, flags); }, rename: async (oldPath, newPath) => { if (String(newPath) === join(outDir, 'current')) { throw new Error('Simulated commit EIO in Export A after B committed'); } return rename(oldPath, newPath); }, }, }); })(); const [settledB, settledA] = await Promise.allSettled([promiseB, promiseA]); expect(settledB.status).toBe('fulfilled'); expect(settledA.status).toBe('rejected'); // Export B's top-level TSV paths AND pinned snapshot remain 100% readable. expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe( 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' ); expect(await readFile(join(outDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe( '20\tCAD\n' ); expect(await readFile(join(outDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe( 'SNAP_B\t2024-01-15\t20\t\t-1\n' ); const pinned = await pinCurateInputSnapshot(outDir); expect(await readFile(pinned.providerMapping, 'utf8')).toBe( 'qm\tSNAP_B\t2021-01-01\t2024-01-15\t20\n' ); const entries = await readdir(outDir); expect(entries.some(e => e.includes('.tmp') || e.includes('.bak') || e === CURATE_INPUT_PUBLISH_LOCK)).toBe(false); } }); test('fails closed with PUBLISH_LOCK_TIMEOUT when publish lock is held past timeout without removing foreign lock', async () => { const outDir = await makeTempDir('curate-inputs-lock-timeout-'); const lockPath = join(outDir, CURATE_INPUT_PUBLISH_LOCK); await writeFile(lockPath, '{"pid":999999,"runTag":"foreign"}\n', 'utf8'); const client = createInMemoryQueryable({ listings: [], continuities: [], providerMappings: [], }); await expectExportErrorAsync( () => exportCurateInputs(client, { outDir, publishLockTimeoutMs: 15 }), 'PUBLISH_LOCK_TIMEOUT', 'publish', outDir ); // Foreign lock file must remain untouched. expect(await readFile(lockPath, 'utf8')).toBe('{"pid":999999,"runTag":"foreign"}\n'); }); test('removes .publish.lock when writing metadata fails after exclusive creation so an immediate retry succeeds', async () => { const outDir = await makeTempDir('curate-inputs-lock-write-fail-'); const lockPath = join(outDir, CURATE_INPUT_PUBLISH_LOCK); const makeClient = () => createInMemoryQueryable({ listings: [ { listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null, }, ], continuities: [], providerMappings: [ { source: 'qm', source_id: 'AAPL', valid_from: '2020-01-01', valid_to: null, listing_id: 1, }, ], }); let injected = false; await expect( exportCurateInputs(makeClient(), { outDir, fs: { open: async (path, flags, mode) => { const realHandle = await open(path, flags, mode); if (!injected && String(path) === lockPath && flags === 'wx') { injected = true; const wrappedHandle = Object.create(realHandle) as typeof realHandle; wrappedHandle.write = async () => { const err = new Error('Simulated ENOSPC while writing lock metadata') as NodeJS.ErrnoException; err.code = 'ENOSPC'; throw err; }; wrappedHandle.close = () => realHandle.close(); return wrappedHandle; } return realHandle; }, }, }) ).rejects.toThrow('Simulated ENOSPC while writing lock metadata'); expect(injected).toBe(true); const entriesAfterFailure = await readdir(outDir); expect(entriesAfterFailure).not.toContain(CURATE_INPUT_PUBLISH_LOCK); // Immediate retry to the same outDir must succeed without PUBLISH_LOCK_TIMEOUT. const retryResult = await exportCurateInputs(makeClient(), { outDir, publishLockTimeoutMs: 50, }); expect(retryResult.providerMapping.rowsOut).toBe(1); expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe( 'qm\tAAPL\t2020-01-01\t\t1\n' ); const entriesAfterRetry = await readdir(outDir); expect(entriesAfterRetry).not.toContain(CURATE_INPUT_PUBLISH_LOCK); }); test('rejects pool-like objects and invalid chunkSize', async () => { const outDir = await makeTempDir('curate-inputs-pool-'); const poolLike = { query: async () => ({ rows: [] }), connect: async () => ({}), } as unknown as SecurityMasterQueryable; await expectExportErrorAsync( () => exportCurateInputs(poolLike, { outDir }), 'INVALID_CLIENT', 'connection', 'client' ); const validClient = createInMemoryQueryable({ listings: [], continuities: [], providerMappings: [], }); await expectExportErrorAsync( () => exportCurateInputs(validClient, { outDir, chunkSize: 5001 }), 'INVALID_OPTION', 'options', 'chunkSize' ); }); }); describe('golden fixtures cross-language parity', () => { test('TS exporter reproduces committed tools/curate-etl/tests/fixtures/curate-inputs/*.tsv byte-for-byte', async () => { const fixtureDir = resolve( import.meta.dir, '../../tools/curate-etl/tests/fixtures/curate-inputs' ); const dataset = buildGoldenFixtureDataset(); const expectedPm = formatProviderMappingTsv(dataset.providerMappings); const expectedLc = formatListingCurrenciesTsv(dataset.listings); const builtDelistings = buildDelistingExportRows( dataset.delistingListings, dataset.continuities, dataset.providerMappings ); const expectedDl = formatDelistingsTsv(builtDelistings.rows); expect(await readFile(join(fixtureDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe( expectedPm ); expect(await readFile(join(fixtureDir, CURATE_INPUT_FILES.listingCurrencies), 'utf8')).toBe( expectedLc ); expect(await readFile(join(fixtureDir, CURATE_INPUT_FILES.delistings), 'utf8')).toBe( expectedDl ); // Also verify streaming exportCurateInputs produces identical bytes with chunkSize=2. const outDir = await makeTempDir('curate-inputs-golden-'); const queryable = createInMemoryQueryable({ listings: dataset.delistingListings.map((l, idx) => ({ listing_id: l.listingId, currency: dataset.listings[idx]!.currency, listed_to: l.listedTo, delist_reason: l.delistReason, terminal_return: l.terminalReturn === null ? null : String(l.terminalReturn), })), continuities: dataset.continuities.map(c => ({ from_listing_id: c.fromListingId, to_listing_id: c.toListingId, effective_date: c.effectiveDate, kind: c.kind, })), providerMappings: dataset.providerMappings.map(m => ({ source: m.source, source_id: m.sourceId, valid_from: m.validFrom, valid_to: m.validTo, listing_id: m.listingId, })), }); const result = await exportCurateInputs(queryable, { outDir, chunkSize: 2 }); expect(await readFile(result.providerMapping.path, 'utf8')).toBe(expectedPm); expect(await readFile(result.listingCurrencies.path, 'utf8')).toBe(expectedLc); expect(await readFile(result.delistings.path, 'utf8')).toBe(expectedDl); expect(result.delistings.stats).toEqual(builtDelistings.stats); }); }); describe('CLI args, safety guard, and runner', () => { test('parseExportCurateInputsArgs parses --out-dir, --chunk-size, and --help', () => { expect(parseExportCurateInputsArgs(['--help'])).toEqual({ help: true }); expect(parseExportCurateInputsArgs(['--out-dir', '/tmp/curate'])).toEqual({ help: false, outDir: '/tmp/curate', chunkSize: DEFAULT_EXPORT_CHUNK_SIZE, }); expect(parseExportCurateInputsArgs(['--out-dir=/tmp/curate', '--chunk-size=250'])).toEqual({ help: false, outDir: '/tmp/curate', chunkSize: 250, }); expect(() => parseExportCurateInputsArgs([])).toThrow(EXPORT_CURATE_INPUTS_USAGE); expect(() => parseExportCurateInputsArgs(['--out-dir', '/tmp/a', '--chunk-size', '5001'])).toThrow( 'Invalid --chunk-size' ); expect(() => parseExportCurateInputsArgs(['--unknown'])).toThrow('Unknown argument'); }); test('assertExportCurateInputsSafety blocks disabled PG and dev->QA PG even when override env var is set', () => { const devOnQaConfig = { environment: 'development', database: { postgres: { enabled: true, host: 'localhost', port: 5432, database: 'trading_bot', }, mongodb: { enabled: true, uri: 'mongodb://localhost:27017/stock', database: 'stock', }, }, } as unknown as StockAppConfig; expect(() => assertExportCurateInputsSafety(devOnQaConfig, { STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true', }) ).toThrow(); const disabledPgConfig = { ...devOnQaConfig, database: { ...devOnQaConfig.database, postgres: { ...devOnQaConfig.database.postgres, enabled: false }, }, } as unknown as StockAppConfig; expect(() => assertExportCurateInputsSafety(disabledPgConfig, {})).toThrow( 'PostgreSQL is disabled' ); const safeDevConfig = { ...devOnQaConfig, database: { ...devOnQaConfig.database, postgres: { enabled: true, host: 'localhost', port: 5433, database: 'trading_bot_dev', }, }, } as unknown as StockAppConfig; expect(() => assertExportCurateInputsSafety(safeDevConfig, {})).not.toThrow(); }); test('runExportCurateInputs runs safety, exports, closes PG client, and prints summary', async () => { const outDir = await makeTempDir('curate-inputs-cli-'); let safetyChecked = false; let closed = false; let stdoutText = ''; const queryable = createInMemoryQueryable({ listings: [ { listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ { source: 'qm', source_id: 'AAPL', valid_from: '2020-01-01', valid_to: null, listing_id: 1 }, ], }); const output = await runExportCurateInputs( { assertSafety: () => { safetyChecked = true; }, createPostgresClient: () => ({ queryable, close: () => { closed = true; }, }), writeStdout: text => { stdoutText += text; }, }, { outDir, chunkSize: 100 } ); expect(safetyChecked).toBe(true); expect(closed).toBe(true); expect(output.summary).toBe(formatExportCurateInputsSummary(output.result)); expect(stdoutText).toContain('provider_mapping.tsv: rows_in=1 rows_out=1'); expect(stdoutText).toContain('listing_currencies.tsv: rows_in=1 rows_out=1'); expect(stdoutText).toContain('delistings.tsv: rows_in=1 rows_out=0'); }); test('runExportCurateInputsCli initializes postgresOnly config so unrelated QA MONGODB_URI does not block dev PostgreSQL export', async () => { const outDir = await makeTempDir('curate-inputs-cli-pg-only-'); const envKeys = [ 'NODE_ENV', 'POSTGRES_ENABLED', 'POSTGRES_HOST', 'POSTGRES_PORT', 'POSTGRES_DATABASE', 'DATABASE_POSTGRES_HOST', 'DATABASE_POSTGRES_PORT', 'DATABASE_POSTGRES_DATABASE', 'MONGODB_URI', 'MONGODB_READ_URI', 'DATABASE_MONGODB_URI', 'DATABASE_MONGODB_READURI', 'STOCK_BOT_ALLOW_DEV_ON_QA_DB', ] as const; const savedEnv: Record = {}; for (const key of envKeys) { savedEnv[key] = process.env[key]; } try { resetStockConfig(); process.env.NODE_ENV = 'development'; process.env.POSTGRES_ENABLED = 'true'; process.env.POSTGRES_HOST = 'localhost'; process.env.POSTGRES_PORT = '5433'; process.env.POSTGRES_DATABASE = 'trading_bot_dev'; process.env.DATABASE_POSTGRES_HOST = 'localhost'; process.env.DATABASE_POSTGRES_PORT = '5433'; process.env.DATABASE_POSTGRES_DATABASE = 'trading_bot_dev'; process.env.MONGODB_URI = 'mongodb://trading_admin:secret@localhost:27017/stock'; delete process.env.MONGODB_READ_URI; delete process.env.DATABASE_MONGODB_URI; delete process.env.DATABASE_MONGODB_READURI; delete process.env.STOCK_BOT_ALLOW_DEV_ON_QA_DB; // Prove the exact same env fails under the old mongoReadOnly config init. expect(() => initializeStockConfig('dataPipeline', { mongoReadOnly: true })).toThrow( 'Safety guard' ); resetStockConfig(); const queryable = createInMemoryQueryable({ listings: [ { listing_id: 1, currency: 'USD', listed_to: null, delist_reason: 'active', terminal_return: null }, ], continuities: [], providerMappings: [ { source: 'qm', source_id: 'AAPL', valid_from: '2020-01-01', valid_to: null, listing_id: 1 }, ], }); let stdoutText = ''; await runExportCurateInputsCli(['--out-dir', outDir], { createPostgresClient: () => ({ queryable, close: () => {}, }), writeStdout: text => { stdoutText += text; }, }); expect(stdoutText).toContain('Curate-ETL TSV export complete'); expect(await readFile(join(outDir, CURATE_INPUT_FILES.providerMapping), 'utf8')).toBe( 'qm\tAAPL\t2020-01-01\t\t1\n' ); // Still rejects dev -> QA PostgreSQL even with STOCK_BOT_ALLOW_DEV_ON_QA_DB=true! resetStockConfig(); process.env.POSTGRES_PORT = '5432'; process.env.POSTGRES_DATABASE = 'trading_bot'; process.env.DATABASE_POSTGRES_PORT = '5432'; process.env.DATABASE_POSTGRES_DATABASE = 'trading_bot'; process.env.STOCK_BOT_ALLOW_DEV_ON_QA_DB = 'true'; await expect( runExportCurateInputsCli(['--out-dir', outDir], { createPostgresClient: () => ({ queryable, close: () => {}, }), writeStdout: () => {}, }) ).rejects.toThrow('Safety guard'); } finally { for (const key of envKeys) { const value = savedEnv[key]; if (value === undefined) { delete process.env[key]; } else { process.env[key] = value; } } resetStockConfig(); } }); });