/** * Reproducible headless benchmark for Pass 4a `readSampleCloses`. * Streams 500,025 synthetic documents (25 sample dates × 20,000 IDs split across * eodPrices + qmPrices, plus 25 CAD.FOREX FX documents) through an in-memory * async-generator fake reader with zero MongoDB or network dependencies. * * Usage: * bun run apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts */ import { FX_USD_CAD_SOURCE_ID, readSampleCloses, type ReadOnlySourceSymbolCursor, type ReadOnlySourceSymbolReader, type SampleCloseSourceReadStats, } from '../src/security-master/sample-closes'; const SAMPLE_DATE_COUNT = 25; const EOD_ID_COUNT = 10_000; const QM_ID_COUNT = 10_000; function buildSampleDates(count: number): string[] { const dates: string[] = []; let year = 2024; let month = 1; let day = 2; while (dates.length < count) { dates.push( `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}` ); day += 14; if (day > 28) { day -= 28; month += 1; if (month > 12) { month = 1; year += 1; } } } return dates; } function buildIds(prefix: string, suffix: string, count: number): string[] { const ids = new Array(count); for (let i = 0; i < count; i++) { ids[i] = `${prefix}${String(i).padStart(5, '0')}${suffix}`; } return ids; } function assertStatsReconcile(label: string, stats: SampleCloseSourceReadStats): void { const skipSum = stats.skipped.missingId + stats.skipped.unrequestedId + stats.skipped.invalidDate + stats.skipped.unrequestedDate + stats.skipped.invalidClose; if (stats.skippedTotal !== skipSum || stats.docsRead !== stats.emitted + stats.skippedTotal) { throw new Error( `Stats reconciliation failed for ${label}: docsRead=${stats.docsRead}, emitted=${stats.emitted}, skippedTotal=${stats.skippedTotal}, skipSum=${skipSum}` ); } } function createStreamingBenchmarkReader( sampleDates: readonly string[], eodIds: readonly string[], qmIds: readonly string[] ): ReadOnlySourceSymbolReader { return { isReadOnly(): boolean { return true; }, find = Record>( collectionName: string, filter?: Record ): ReadOnlySourceSymbolCursor { const idFilter = collectionName === 'eodPrices' ? ((filter?.eodSearchCode as { $in?: string[] } | undefined)?.$in ?? []) : ((filter?.qmSearchCode as { $in?: string[] } | undefined)?.$in ?? []); const isFxCall = collectionName === 'eodPrices' && idFilter.length === 1 && idFilter[0] === FX_USD_CAD_SOURCE_ID; return { async *[Symbol.asyncIterator](): AsyncIterator { if (isFxCall) { for (let d = 0; d < sampleDates.length; d++) { yield { eodSearchCode: FX_USD_CAD_SOURCE_ID, date: sampleDates[d], close: 1.34 + (d % 7) * 0.005, } as unknown as T; } return; } if (collectionName === 'eodPrices') { const ids = idFilter.length > 0 ? idFilter : eodIds; for (let d = 0; d < sampleDates.length; d++) { const date = sampleDates[d]; for (let i = 0; i < ids.length; i++) { yield { eodSearchCode: ids[i], date, close: 10 + ((i + d) % 250) + 0.25, } as unknown as T; } } return; } if (collectionName === 'qmPrices') { const ids = idFilter.length > 0 ? idFilter : qmIds; for (let d = 0; d < sampleDates.length; d++) { const date = sampleDates[d]; for (let i = 0; i < ids.length; i++) { yield { qmSearchCode: ids[i], date, unadjustedclose: 10 + ((i + d) % 250) + 0.25, } as unknown as T; } } } }, async close(): Promise { // No-op for in-memory benchmark cursor. }, }; }, }; } async function main(): Promise { const sampleDates = buildSampleDates(SAMPLE_DATE_COUNT); const eodIds = buildIds('EOD', '.US', EOD_ID_COUNT); const qmIds = buildIds('QM', '', QM_ID_COUNT); const reader = createStreamingBenchmarkReader(sampleDates, eodIds, qmIds); if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') { Bun.gc(true); } const heapBefore = process.memoryUsage().heapUsed; const startedAt = performance.now(); const result = await readSampleCloses(reader, { sampleDates, sourceIdsBySource: { eod: eodIds, qm: qmIds }, batchSize: 5_000, }); const elapsedMs = performance.now() - startedAt; const heapAfter = process.memoryUsage().heapUsed; const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024); assertStatsReconcile('eod', result.stats.eod); assertStatsReconcile('qm', result.stats.qm); assertStatsReconcile('fx', result.stats.fx); const totalDocsRead = result.stats.eod.docsRead + result.stats.qm.docsRead + result.stats.fx.docsRead; const expectedEquityDocs = SAMPLE_DATE_COUNT * (EOD_ID_COUNT + QM_ID_COUNT); if (result.closes.length !== expectedEquityDocs || result.fxRates.length !== SAMPLE_DATE_COUNT) { throw new Error( `Unexpected emitted counts: closes=${result.closes.length} (expected ${expectedEquityDocs}), fxRates=${result.fxRates.length} (expected ${SAMPLE_DATE_COUNT})` ); } const docsPerSec = Math.round(totalDocsRead / (elapsedMs / 1000)); const lines = [ 'Pass 4a sample-closes benchmark (in-memory async cursor, zero MongoDB)', ` Workload: ${totalDocsRead.toLocaleString('en-US')} docs (${SAMPLE_DATE_COUNT} dates x ${(EOD_ID_COUNT + QM_ID_COUNT).toLocaleString('en-US')} ids + ${SAMPLE_DATE_COUNT} FX)`, ` Emitted: ${result.closes.length.toLocaleString('en-US')} closes, ${result.fxRates.length.toLocaleString('en-US')} fxRates`, ` Elapsed: ${elapsedMs.toFixed(1)} ms`, ` Throughput: ${docsPerSec.toLocaleString('en-US')} docs/s`, ` Heap delta: ${heapDeltaMb.toFixed(2)} MiB`, ]; process.stdout.write(`${lines.join('\n')}\n`); } await main();