stock-bot/apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts

140 lines
4.7 KiB
TypeScript

/**
* Reproducible headless benchmark for `exportRawBsonCollection`.
* Streams >= 1,000,000 fixed-seed synthetic ~100 B raw BSON `eodPrices` frames through
* `exportRawBsonCollection` into a temporary directory (cleaned up in `finally`), with zero
* MongoDB or network dependencies.
*
* Usage:
* bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts [docCount]
*/
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { BSON } from 'mongodb';
import {
DEFAULT_WRITE_BUFFER_BYTES,
exportRawBsonCollection,
type ReadOnlyRawBsonSource,
} from '../src/security-master/export-raw-bson';
const DEFAULT_DOC_COUNT = 1_000_000;
const POOL_SIZE = 1_024;
function parseDocCount(): number {
const raw = process.argv[2];
if (raw === undefined) {
return DEFAULT_DOC_COUNT;
}
if (!/^\d+$/.test(raw)) {
throw new Error(`Invalid docCount "${raw}": expected a positive integer`);
}
const parsed = Number(raw);
if (!Number.isSafeInteger(parsed) || parsed < 1) {
throw new Error(`Invalid docCount "${raw}": expected a positive integer`);
}
return parsed;
}
/**
* Deterministic PRNG (Mulberry32) so the synthetic BSON pool is identical across runs.
*/
function createSeededRng(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function buildSyntheticBsonPool(): Uint8Array[] {
const rng = createSeededRng(0x5eed117);
const pool = new Array<Uint8Array>(POOL_SIZE);
for (let i = 0; i < POOL_SIZE; i++) {
const base = 10 + Math.round(rng() * 20000) / 100;
const high = Math.round((base + rng() * 3) * 100) / 100;
const low = Math.max(0.01, Math.round((base - rng() * 3) * 100) / 100);
const close = Math.round((low + rng() * (high - low)) * 100) / 100;
const volume = Math.floor(1_000 + rng() * 5_000_000);
const month = String((i % 12) + 1).padStart(2, '0');
const day = String((i % 28) + 1).padStart(2, '0');
const doc = {
eodSearchCode: `SYM${String(i).padStart(4, '0')}.US`,
date: `2025-${month}-${day}`,
open: base,
high,
low,
close,
volume,
};
pool[i] = Uint8Array.from(BSON.serialize(doc));
}
return pool;
}
function createSyntheticRawSource(pool: readonly Uint8Array[], totalDocs: number): ReadOnlyRawBsonSource {
const poolLen = pool.length;
return {
isReadOnly: () => true,
find() {
return {
async *[Symbol.asyncIterator]() {
for (let i = 0; i < totalDocs; i++) {
const frame = pool[i % poolLen];
if (frame !== undefined) {
yield frame;
}
}
},
};
},
};
}
async function main(): Promise<void> {
const docCount = parseDocCount();
const pool = buildSyntheticBsonPool();
const avgDocBytes =
pool.reduce((acc, frame) => acc + frame.byteLength, 0) / pool.length;
const source = createSyntheticRawSource(pool, docCount);
const outDir = await mkdtemp(join(tmpdir(), 'export-raw-bson-bench-'));
try {
const rssBeforeMiB = process.memoryUsage().rss / (1024 * 1024);
const startNs = Bun.nanoseconds();
const result = await exportRawBsonCollection(source, {
collection: 'eodPrices',
outDir,
writeBufferBytes: DEFAULT_WRITE_BUFFER_BYTES,
});
const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6;
const rssAfterMiB = process.memoryUsage().rss / (1024 * 1024);
// process.resourceUsage().maxRSS is reported in KiB on Linux.
const peakRssMiB = process.resourceUsage().maxRSS / 1024;
const elapsedSec = elapsedMs / 1000;
const docsPerSec = result.docsWritten / elapsedSec;
const mibPerSec = result.bytesWritten / (1024 * 1024) / elapsedSec;
process.stdout.write('exportRawBsonCollection benchmark complete\n');
process.stdout.write(
` docs=${result.docsWritten} avg_doc_bytes=${avgDocBytes.toFixed(1)} bytes_written=${result.bytesWritten} write_buffer_bytes=${DEFAULT_WRITE_BUFFER_BYTES}\n`
);
process.stdout.write(
` elapsed_ms=${elapsedMs.toFixed(1)} throughput=${Math.round(docsPerSec)} docs/s rate=${mibPerSec.toFixed(2)} MiB/s\n`
);
process.stdout.write(
` rss_before=${rssBeforeMiB.toFixed(2)} MiB rss_after=${rssAfterMiB.toFixed(2)} MiB peak_rss=${peakRssMiB.toFixed(2)} MiB\n`
);
process.stdout.write(` sha256=${result.sha256}\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);
});