/** Reproducible CPU/peak-RSS comparison. No DB, native engine, credentials or network. */ import { createHash } from 'node:crypto'; import { fileURLToPath } from 'node:url'; import { parseInstrumentId, validateHistoricalDataRequest, type HistoricalDataset, } from '@stock-bot/types'; import { datasetSchema } from '../apps/stock/orchestrator/src/contracts/historical'; import { prepareDataset } from '../apps/stock/orchestrator/src/data/historical-dataset'; function hash(dataset: HistoricalDataset): string { const { hash: _hash, ...manifest } = dataset.manifest; return createHash('sha256') .update(JSON.stringify({ manifest, bars: dataset.bars })) .digest('hex'); } /** Pre-refactor v1 validation, retained here solely as the benchmark baseline. */ function legacyValidate(input: unknown): HistoricalDataset { const dataset = datasetSchema.parse(input); const m = dataset.manifest; const ids = m.instruments.map(i => i.id), sorted = [...ids].sort(), idSet = new Set(ids); const rangeStart = Date.parse(m.startDate), rangeEnd = Date.parse(m.endDate); validateHistoricalDataRequest({ symbols: ids, startDate: m.startDate, endDate: m.endDate, dataFrequency: m.interval, dataPolicy: m.policy, datasetHash: m.hash, }); if ( ids.some((id, i) => id !== sorted[i]) || m.instruments.some(i => JSON.stringify(i) !== JSON.stringify(parseInstrumentId(i.id))) || m.sources.length !== ids.length || m.sources.some((s, i) => s.instrumentId !== ids[i]) || m.barCount !== dataset.bars.length ) { throw new Error('Invalid dataset manifest'); } const seen = new Set(); let previous: HistoricalDataset['bars'][number] | undefined; for (const bar of dataset.bars) { if ( !idSet.has(bar.symbol) || bar.timestamp < rangeStart || bar.timestamp >= rangeEnd || bar.high < Math.max(bar.open, bar.close) || bar.low > Math.min(bar.open, bar.close) || (m.policy.timestamp === 'utc-session-date' && bar.timestamp % 86400000 !== 0) || (previous && (bar.timestamp < previous.timestamp || (bar.timestamp === previous.timestamp && bar.symbol <= previous.symbol))) ) { throw new Error('Invalid or unordered dataset bars'); } seen.add(bar.symbol); previous = bar; } if (seen.size !== ids.length || hash(dataset) !== m.hash) { throw new Error('Dataset hash/content mismatch'); } return dataset; } function fixture(barCount: number, instrumentCount: number): HistoricalDataset { const instruments = Array.from({ length: instrumentCount }, (_, i) => parseInstrumentId(`S${String(i).padStart(3, '0')}.US`) ); const start = Date.parse('2024-01-01T00:00:00.000Z'); const bars: HistoricalDataset['bars'] = []; for (let i = 0; i < barCount; i++) { bars.push({ symbol: instruments[i % instrumentCount]!.id, timestamp: start + Math.floor(i / instrumentCount) * 60_000, open: 100, high: 102, low: 99, close: 101, volume: i, vwap: 100.5, }); } const dataset: HistoricalDataset = { manifest: { version: 1, hash: '0'.repeat(64), instruments, startDate: new Date(start).toISOString(), endDate: new Date(start + (Math.ceil(barCount / instrumentCount) + 1) * 60_000).toISOString(), interval: '1m', policy: { adjustment: 'raw', timestamp: 'utc-instant' }, volumePolicy: 'reported', qualityPolicy: 'reject-invalid-no-interpolation', sources: instruments.map(({ id }) => ({ instrumentId: id, provider: 'questdb', revision: 'benchmark-v1', })), barCount, }, bars, }; dataset.manifest.hash = hash(dataset); return dataset; } const [mode, countArg, instrumentsArg] = process.argv.slice(2); if (mode === 'legacy' || mode === 'prepared') { const count = Number(countArg), instruments = Number(instrumentsArg); const source = fixture(count, instruments); const expected = source.manifest.hash; let dataset = source; const start = performance.now(); // Four in-process handoffs of the SAME content. Persistence/IPC boundary work is excluded. for (let i = 0; i < 4; i++) { dataset = mode === 'legacy' ? legacyValidate(dataset) : await prepareDataset(dataset); } if (dataset.manifest.hash !== expected) { throw new Error('Benchmark changed content identity'); } process.stdout.write( JSON.stringify({ mode, bars: count, instruments, milliseconds: Math.round(performance.now() - start), peakRssMiB: Math.round(process.resourceUsage().maxRSS / 1024), hash: expected, }) + '\n' ); } else { for (const [bars, instruments] of [ [10_000, 1], [100_000, 10], [1_000_000, 100], ]) { const results = []; for (const mode of ['legacy', 'prepared']) { // Isolate peak RSS and garbage collector history for each measurement. const child = Bun.spawn( [process.execPath, fileURLToPath(import.meta.url), mode, String(bars), String(instruments)], { stdout: 'pipe', stderr: 'inherit', env: { ...process.env, NODE_ENV: 'production' } } ); const output = await new Response(child.stdout).text(); if ((await child.exited) !== 0) { throw new Error(`Benchmark failed: ${mode} ${bars}`); } const result = JSON.parse(output); results.push(result); process.stdout.write(output); } if (results[0].hash !== results[1].hash) { throw new Error('Baseline/prepared hash mismatch'); } } }