/** * Reproducible headless benchmark for `exportCurateInputs`. * Streams 500,000 `provider_mapping` rows + 100,000 `listing` rows + 2,000 OTC continuities + * terminal delistings + skipped rows through an in-memory keyset-paginated * `SecurityMasterQueryable` into a temporary directory (cleaned up in `finally`), with zero * database or network dependencies. * * Usage: * bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts */ import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { DEFAULT_EXPORT_CHUNK_SIZE, exportCurateInputs, type SecurityMasterQueryable, type SecurityMasterQueryResult, } from '../src/security-master/export-curate-inputs'; const LISTING_COUNT = 100_000; const PROVIDER_MAPPING_COUNT = 500_000; const OTC_CONTINUITY_COUNT = 2_000; interface BenchContinuityRow { from_listing_id: number; to_listing_id: number; effective_date: string; kind: string; } interface BenchListingRow { listing_id: number; currency: string; listed_to: string | null; delist_reason: string | null; terminal_return: string | null; } interface BenchMappingRow { source: string; source_id: string; valid_from: string; valid_to: string | null; listing_id: number; } /** * Generates deterministic sorted synthetic rows (matching PostgreSQL ORDER BY): * - 100,000 listings: * - 1..2000: OTC outgoing listings (moved_to_otc -> successor listing_id + 2000) * - 2001..4000: OTC successor listings (half bankruptcy_cancelled -1.0, half active) * - 4001..8000: terminal delistings (-0.3; every 20th has listed_to = null -> missingListedTo) * - 8001..10000: delisted with null outcome (noOutcome) * - 10001..100000: active US/CA listings * - 500,000 provider_mapping rows in strict ASCII COLLATE "C" order across 5 sources: * ceo (100k), eod (100k), ib (100k), qm (100k), te (100k). * For a small deterministic subset of listings, omit the `qm` mapping (assign to listing 10001) * so missingOutgoingQmMapping and missingSuccessorQmMapping are exercised too. */ function buildSyntheticTables(): { continuities: BenchContinuityRow[]; listings: BenchListingRow[]; mappings: BenchMappingRow[]; } { const continuities = new Array(OTC_CONTINUITY_COUNT); for (let i = 0; i < OTC_CONTINUITY_COUNT; i++) { const fromId = i + 1; continuities[i] = { from_listing_id: fromId, to_listing_id: fromId + OTC_CONTINUITY_COUNT, effective_date: '2023-03-28', kind: 'otc_delist_transfer', }; } const listings = new Array(LISTING_COUNT); for (let i = 0; i < LISTING_COUNT; i++) { const id = i + 1; const currency = id % 5 === 0 ? 'CAD' : 'USD'; if (id <= OTC_CONTINUITY_COUNT) { listings[i] = { listing_id: id, currency, listed_to: '2023-03-10', delist_reason: 'moved_to_otc', terminal_return: null, }; } else if (id <= OTC_CONTINUITY_COUNT * 2) { if (id % 2 === 0) { listings[i] = { listing_id: id, currency, listed_to: '2024-11-07', delist_reason: 'bankruptcy_cancelled', terminal_return: '-1.000000', }; } else { listings[i] = { listing_id: id, currency, listed_to: null, delist_reason: 'active', terminal_return: null, }; } } else if (id <= 8_000) { const missingDate = id % 20 === 0; listings[i] = { listing_id: id, currency, listed_to: missingDate ? null : '2023-06-15', delist_reason: 'unknown_involuntary', terminal_return: '-0.300000', }; } else if (id <= 10_000) { listings[i] = { listing_id: id, currency, listed_to: '2022-12-30', delist_reason: null, terminal_return: null, }; } else { listings[i] = { listing_id: id, currency, listed_to: null, delist_reason: 'active', terminal_return: null, }; } } // 5 sources in strict ASCII order: ceo, eod, ib, qm, te (100,000 rows each = 500,000 total). const sources = ['ceo', 'eod', 'ib', 'qm', 'te'] as const; const mappings = new Array(PROVIDER_MAPPING_COUNT); let idx = 0; for (const source of sources) { for (let i = 0; i < LISTING_COUNT; i++) { const naturalListingId = i + 1; const padded = String(naturalListingId).padStart(6, '0'); let listingId = naturalListingId; let validFrom = '2015-01-02'; let validTo: string | null = null; if (naturalListingId <= OTC_CONTINUITY_COUNT) { validTo = '2023-03-10'; // Drop QM mapping for every 40th outgoing OTC listing (redirect to active listing 10001). if (source === 'qm' && naturalListingId % 40 === 0) { listingId = 10_001; } } else if (naturalListingId <= OTC_CONTINUITY_COUNT * 2) { validFrom = '2023-03-28'; validTo = naturalListingId % 2 === 0 ? '2024-11-07' : null; // Drop QM mapping for every 50th successor OTC listing. if (source === 'qm' && naturalListingId % 50 === 0) { listingId = 10_002; } } else if (naturalListingId <= 8_000) { validTo = '2023-06-15'; } mappings[idx++] = { source, source_id: `SYM${padded}`, valid_from: validFrom, valid_to: validTo, listing_id: listingId, }; } } return { continuities, listings, mappings }; } function createFastPaginatedQueryable(tables: { continuities: BenchContinuityRow[]; listings: BenchListingRow[]; mappings: BenchMappingRow[]; }): SecurityMasterQueryable { let contOffset = 0; let listingOffset = 0; let mappingOffset = 0; return { async query>( text: string, values?: readonly unknown[] ): Promise> { const normalized = text.replace(/\s+/g, ' ').trim(); if (normalized.startsWith('BEGIN')) { contOffset = 0; listingOffset = 0; mappingOffset = 0; return { rows: [] }; } if (normalized === 'COMMIT' || normalized === 'ROLLBACK') { return { rows: [] }; } if (normalized.startsWith('DECLARE ') && normalized.includes('FROM provider_mapping')) { mappingOffset = 0; return { rows: [] }; } const fetchMatch = /^FETCH FORWARD (\d+) FROM \S+$/i.exec(normalized); if (fetchMatch) { const fetchLimit = Number(fetchMatch[1]); const slice = tables.mappings.slice(mappingOffset, mappingOffset + fetchLimit); mappingOffset += slice.length; return { rows: slice as unknown as Row[] }; } if (/^CLOSE \S+$/i.test(normalized)) { return { rows: [] }; } const limit = values ? (values[values.length - 1] as number) : DEFAULT_EXPORT_CHUNK_SIZE; if (normalized.includes('FROM corporate_action_continuity')) { const slice = tables.continuities.slice(contOffset, contOffset + limit); contOffset += slice.length; return { rows: slice as unknown as Row[] }; } if (normalized.includes('FROM listing')) { const slice = tables.listings.slice(listingOffset, listingOffset + limit); listingOffset += slice.length; return { rows: slice as unknown as Row[] }; } if (normalized.includes('FROM provider_mapping')) { const slice = tables.mappings.slice(mappingOffset, mappingOffset + limit); mappingOffset += slice.length; return { rows: slice as unknown as Row[] }; } throw new Error(`Unexpected SQL in benchmark queryable: ${normalized}`); }, release: () => {}, }; } async function main(): Promise { const tables = buildSyntheticTables(); const queryable = createFastPaginatedQueryable(tables); const outDir = await mkdtemp(join(tmpdir(), 'curate-inputs-bench-')); try { const startNs = Bun.nanoseconds(); const result = await exportCurateInputs(queryable, { outDir, chunkSize: DEFAULT_EXPORT_CHUNK_SIZE, }); const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6; const d = result.delistings.stats; const skipSum = d.skipped.active + d.skipped.noOutcome + d.skipped.missingListedTo + d.skipped.missingOutgoingQmMapping + d.skipped.missingSuccessorQmMapping + d.skipped.nonOtcContinuity; if (d.skippedTotal !== skipSum || d.rowsIn !== d.rowsOut + d.skippedTotal) { throw new Error( `Delisting stats reconciliation failed: rowsIn=${d.rowsIn} rowsOut=${d.rowsOut} skippedTotal=${d.skippedTotal} skipSum=${skipSum}` ); } const totalRowsExported = result.providerMapping.rowsOut + result.listingCurrencies.rowsOut + result.delistings.rowsOut; const rowsPerSec = totalRowsExported / (elapsedMs / 1000); // process.resourceUsage().maxRSS is reported in KiB on Linux. const peakRssMiB = process.resourceUsage().maxRSS / 1024; process.stdout.write('exportCurateInputs benchmark complete\n'); process.stdout.write( ` inputs: provider_mapping=${PROVIDER_MAPPING_COUNT} listings=${LISTING_COUNT} otc_continuities=${OTC_CONTINUITY_COUNT}\n` ); process.stdout.write( ` exported: provider_mapping=${result.providerMapping.rowsOut} listing_currencies=${result.listingCurrencies.rowsOut} delistings=${result.delistings.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut} skipped=${d.skippedTotal})\n` ); process.stdout.write( ` total_rows_out=${totalRowsExported} bytes_written=${result.totalBytesWritten} elapsed_ms=${elapsedMs.toFixed(1)} throughput=${Math.round(rowsPerSec)} rows/s peak_rss=${peakRssMiB.toFixed(2)} MiB\n` ); } finally { await rm(outDir, { recursive: true, force: true }); } } main().catch(error => { process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`); process.exit(1); });