/** * Existing one-shot native path by default; no DB, broker or durable queue. * bun run scripts/benchmark-research.ts # tiny deterministic self-test * bun run scripts/benchmark-research.ts --measure # 1k/10k total bars, 1/10 assets * bun run scripts/benchmark-research.ts --measure --large # additionally 100k (quadratic queue) * bun run scripts/benchmark-research.ts --session # canonical pull-session self-test * bun run scripts/benchmark-research.ts --session --measure # 1k/10k bars, actual TS decisions * Build workspace libraries/config and the local engine first. JSON stdout; diagnostics stderr. */ import { createHash } from 'node:crypto'; import { existsSync, readFileSync } from 'node:fs'; import { availableParallelism, cpus, release, totalmem } from 'node:os'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import type { HistoricalDataset } from '@stock-bot/types'; const root = dirname(dirname(fileURLToPath(import.meta.url))); const sha256 = (value: string | Uint8Array) => createHash('sha256').update(value).digest('hex'); export const parameters = [ { fastPeriod: 2, slowPeriod: 5, quantity: 1 }, { fastPeriod: 3, slowPeriod: 8, quantity: 1 }, { fastPeriod: 5, slowPeriod: 12, quantity: 1 }, ]; export const unavailable = { callbackBoundary: 'Native TypeScript callbacks are unsupported.', multiStrategyOwnership: 'Not benchmarked until canonical ownership is implemented.', residentDataset: 'Each trial constructs a new one-shot engine and reloads all bars.', sharedIndicatorCache: 'No shared indicator cache exists in this path.', nativeSerialization: 'Included in nativeRunMs; no separate instrumentation.', storage: 'Synthetic fixture; database reads/writes are not measured.', queueDispatch: 'Direct native call; durable job queue is not measured.', allocations: 'Allocation counts and native/JS heap attribution are not instrumented.', parallelSimulation: 'Sequential baseline; no parallel batch API is exercised.', emptyNapiCrossing: 'No empty-call probe exists; reported native calls include conversion/work.', }; /** Integer arithmetic keeps fixture bytes stable; seeded offsets do not change trend slopes. */ export function researchFixture(totalBars: number, assets: number, seed = 42): HistoricalDataset { if ( !Number.isSafeInteger(totalBars) || !Number.isSafeInteger(assets) || assets < 1 || assets > 100 || totalBars % assets !== 0 || totalBars / assets < 80 || !Number.isSafeInteger(seed) || seed < 0 || seed > 0xffffffff ) { throw new Error( 'Use 1–100 assets, at least 80 bars per asset, divisible total bars and a uint32 seed' ); } const instruments = Array.from({ length: assets }, (_, i) => { const symbol = `S${String(i).padStart(3, '0')}`; return { id: `${symbol}.US`, symbol, exchange: 'US' }; }); let state = seed; const offsets = instruments.map((_, i) => { state = (Math.imul(state, 1664525) + 1013904223) >>> 0; return i * 2 + (state % 100) / 100; }); const start = Date.parse('2024-01-01T00:00:00.000Z'); const bars = Array.from({ length: totalBars }, (_, i) => { const asset = i % assets, step = Math.floor(i / assets), phase = step % 40; const instrument = instruments[asset], offset = offsets[asset]; if (!instrument || offset === undefined) { throw new Error('Missing fixture instrument'); } const close = (phase < 20 ? 110 - phase : 90 + phase - 20) + offset; return { symbol: instrument.id, timestamp: start + step * 60_000, open: close, high: close + 1, low: close - 1, close, volume: 10_000, vwap: close, }; }); const manifest: HistoricalDataset['manifest'] = { version: 1, hash: '0'.repeat(64), instruments, startDate: new Date(start).toISOString(), endDate: new Date(start + (totalBars / assets) * 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: 'synthetic', revision: 'research-benchmark-v1', })), barCount: totalBars, }; const { hash: _hash, ...content } = manifest; manifest.hash = sha256(JSON.stringify({ manifest: content, bars })); return { manifest, bars }; } function canonical(value: unknown): unknown { if (Array.isArray(value)) { return value.map(canonical); } if (value !== null && typeof value === 'object') { return Object.fromEntries( Object.entries(value) .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) .map(([key, item]) => [key, canonical(item)]) ); } return value; } /** Keep trade/equity/OHLC order and every economic field; only position summaries are unordered. */ export function economicHash(result: Record): string { const { backtestId: _id, completedAt: _time, executionTime: _duration, ...economic } = result; if (Array.isArray(economic.positions)) { economic.positions = [...economic.positions].sort((a, b) => { const left = JSON.stringify(canonical(a)), right = JSON.stringify(canonical(b)); return left < right ? -1 : left > right ? 1 : 0; }); } return sha256(JSON.stringify(canonical(economic))); } type Workload = { totalBars: number; assets: number; seed: number }; async function child(workload: Workload) { const entryUptimeMs = process.uptime() * 1000, start = performance.now(); let clock = start; const elapsed = () => { const now = performance.now(), duration = now - clock; clock = now; return duration; }; const { prepareDataset } = await import('../apps/stock/orchestrator/src/data/historical-dataset'); const { nativeResultSchema } = await import( '../apps/stock/orchestrator/src/backtest/native-result' ); const applicationImportMs = elapsed(); const { BacktestEngine } = await import('@stock-bot/engine'); const addonImportMs = elapsed(); const source = researchFixture(workload.totalBars, workload.assets, workload.seed); const fixtureGenerationMs = elapsed(); const dataset = await prepareDataset(source); const datasetPreparationMs = elapsed(); const rows = dataset.bars.map(bar => ({ ...bar, type: 'bar' })); const nativeInputMappingMs = elapsed(); const config = { name: 'P01 one-shot SMA baseline', symbols: dataset.manifest.instruments.map(i => i.id), startDate: dataset.manifest.startDate, endDate: dataset.manifest.endDate, initialCapital: 1_000_000, commission: 0.001, slippage: 0.001, dataFrequency: '1m', }; const trials = []; for (let repeat = 0; repeat < 2; repeat++) { for (const strategyParameters of parameters) { const trialStart = performance.now(); clock = trialStart; if ((await prepareDataset(dataset)) !== dataset) { throw new Error('Prepared input was not reused'); } const preparedInputReuseMs = elapsed(); const engine = new BacktestEngine(config); const engineConstructionMs = elapsed(); engine.addNativeStrategy('sma_crossover', 'P01 SMA', 'p01-sma', strategyParameters); const strategyRegistrationMs = elapsed(); engine.loadMarketData(rows); const nativeLoadMs = elapsed(); const output = engine.run(); const nativeRunMs = elapsed(); const parsed = JSON.parse(output); const resultParseMs = elapsed(); nativeResultSchema.parse(parsed); // Validate, but hash the unstripped result. if (parsed.status !== 'completed' || parsed.trades.length === 0) { throw new Error('Fixture must complete and exercise fills'); } const hash = economicHash(parsed), resultBytes = Buffer.byteLength(output); const validationAndHashMs = elapsed(); const wallMs = performance.now() - trialStart; trials.push({ repeat, strategyParameters, economicHash: hash, resultBytes, fills: parsed.trades.length, timingsMs: { preparedInputReuseMs, engineConstructionMs, strategyRegistrationMs, nativeLoadMs, nativeRunMs, resultParseMs, validationAndHashMs, wallMs, }, rates: { nativeRunBarsPerSecond: workload.totalBars / (nativeRunMs / 1000), wholeTrialBarsPerSecond: workload.totalBars / (wallMs / 1000), trialsPerSecond: 1000 / wallMs, }, rssBytes: process.memoryUsage().rss, }); } } const childWallMs = performance.now() - start; const peakRss = process.platform === 'linux' ? /^VmHWM:\s+(\d+) kB$/m.exec(readFileSync('/proc/self/status', 'utf8')) : null; return { workload, datasetHash: dataset.manifest.hash, config, parameters, policyHash: sha256(JSON.stringify({ config, parameters, fixture: 'research-benchmark-v1' })), phasesMs: { entryUptimeMs, applicationImportMs, addonImportMs, fixtureGenerationMs, datasetPreparationMs, nativeInputMappingMs, childWallMs, }, trials, // Bun 1.2.17 getrusage peaks inflate after repeated native runtimes; use the OS counter. peakRssBytes: peakRss ? Number(peakRss[1]) * 1024 : null, peakRssSource: peakRss ? '/proc/self/status VmHWM' : 'unavailable', }; } function command(args: string[]): string { const result = Bun.spawnSync(args, { cwd: root, stdout: 'pipe', stderr: 'pipe' }); if (result.exitCode !== 0) { throw new Error(`${args[0]} failed: ${result.stderr.toString()}`); } return result.stdout.toString().trimEnd(); } function identity() { const paths = command(['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z']) .split('\0') .filter(Boolean) .sort(); const source = createHash('sha256'); for (const path of paths) { const absolute = join(root, path); source.update( JSON.stringify([path, existsSync(absolute) ? sha256(readFileSync(absolute)) : 'deleted']) ); } const addon = join(root, 'apps/stock/engine/dist/engine.node'); const nativeSha256 = sha256(readFileSync(addon)); const artifactName = process.platform === 'darwin' ? 'libengine.dylib' : 'libengine.so'; const matchedProfiles = ['debug', 'release'].filter(profile => { const artifact = join(root, 'target', profile, artifactName); return existsSync(artifact) && sha256(readFileSync(artifact)) === nativeSha256; }); const host = { platform: process.platform, arch: process.arch, kernel: release(), cpu: cpus()[0]?.model, logicalCpus: cpus().length, availableParallelism: availableParallelism(), totalMemoryBytes: totalmem(), }; return { source: { commit: command(['git', 'rev-parse', 'HEAD']), dirty: command(['git', 'status', '--porcelain']).length > 0, contentSha256: source.digest('hex'), files: paths.length, scope: 'Tracked and nonignored untracked file paths/content, including dirty changes; generated ignored artifacts excluded.', }, native: { path: addon, sha256: nativeSha256, matchedBuildProfiles: matchedProfiles, buildProfile: matchedProfiles.length === 1 ? matchedProfiles[0] : 'unverified', }, runtime: { bun: Bun.version, nodeCompatibility: process.version, executableSha256: sha256(readFileSync(process.execPath)), rustc: command(['rustc', '--version']), lockSha256: sha256(readFileSync(join(root, 'bun.lock'))), cargoLockSha256: sha256(readFileSync(join(root, 'Cargo.lock'))), }, host: { ...host, sha256: sha256(JSON.stringify(host)) }, }; } export function verifyRepeats( samples: { datasetHash: string; policyHash: string; trials: { strategyParameters: (typeof parameters)[number]; economicHash: string }[]; }[] ): void { const expected = new Map(); const first = samples[0]; if (!first) { throw new Error('Missing benchmark samples'); } for (const sample of samples) { if (sample.datasetHash !== first.datasetHash || sample.policyHash !== first.policyHash) { throw new Error('Dataset/policy identity changed between fresh processes'); } for (const trial of sample.trials) { const key = JSON.stringify(trial.strategyParameters), previous = expected.get(key); if (previous && previous !== trial.economicHash) { throw new Error( `Economic mismatch for ${key}: ${previous} != ${trial.economicHash}; no timing comparison is valid` ); } expected.set(key, trial.economicHash); } } } async function main(args: string[]) { if (args[0] === '--session-child') { const { sessionChild } = await import('./benchmark-replay'); process.stdout.write(JSON.stringify(await sessionChild(JSON.parse(args[1] ?? ''))) + '\n'); return; } if (args[0] === '--child') { process.stdout.write(JSON.stringify(await child(JSON.parse(args[1] ?? ''))) + '\n'); return; } if ( args.some(a => !['--self-test', '--measure', '--large', '--session'].includes(a)) || (args.includes('--large') && !args.includes('--measure')) || (args.includes('--self-test') && args.includes('--measure')) ) { throw new Error( 'Use no flags/--self-test, --measure, or --measure --large; optionally --session' ); } const metadata = identity(); // Excluded from workload timings. const measured = args.includes('--measure'); if (args.includes('--session')) { const { sessionBenchmark } = await import('./benchmark-replay'); await sessionBenchmark( root, fileURLToPath(import.meta.url), metadata, measured, args.includes('--large') ); return; } const workloads = measured ? (args.includes('--large') ? [1000, 10_000, 100_000] : [1000, 10_000]).flatMap(totalBars => [1, 10].map(assets => ({ totalBars, assets, seed: 42 })) ) : [ { totalBars: 80, assets: 1, seed: 42 }, { totalBars: 800, assets: 10, seed: 42 }, ]; const measurements = []; for (const workload of workloads) { const samples = []; for (let processRepeat = 0; processRepeat < 2; processRepeat++) { const start = performance.now(); const worker = Bun.spawn( [process.execPath, fileURLToPath(import.meta.url), '--child', JSON.stringify(workload)], { cwd: root, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, NODE_ENV: 'production' }, } ); const [stdout, stderr, exit] = await Promise.all([ new Response(worker.stdout).text(), new Response(worker.stderr).text(), worker.exited, ]); const processWallMs = performance.now() - start; if (exit !== 0) { throw new Error(`Child failed (${exit}): ${stderr}\n${stdout}`); } const sample = JSON.parse(stdout) as Awaited>; samples.push({ ...sample, processRepeat, processWallMs, processBarsPerSecond: (workload.totalBars * sample.trials.length) / (processWallMs / 1000), processTrialsPerSecond: sample.trials.length / (processWallMs / 1000), nativeDiagnosticBytes: Buffer.byteLength(stderr), }); } verifyRepeats(samples); measurements.push({ workload, repeatedEconomicHashesMatch: true, samples }); process.stderr.write( `Verified ${workload.totalBars} total bars / ${workload.assets} assets, 2 fresh processes × 6 one-shot trials\n` ); } process.stdout.write( JSON.stringify( { schemaVersion: 1, mode: measured ? 'measurement' : 'self-test', ...metadata, seed: { value: 42, sha256: sha256('42'), algorithm: 'LCG fixture offsets only; no engine RNG API', }, unavailable, limitations: [ 'Existing native same-bar execution, legacy ownership/funding policies and placeholder analytics are not certified financial semantics.', 'A matching hash detects changes under this pinned artifact; it does not certify economic correctness.', 'Fresh processes do not flush OS page caches. Reused prepared JS objects still reload the native engine every trial.', 'Boundary timings include conversion/work, not an isolated empty NAPI-call cost. Native run includes replay, calculation, matching and serialization.', 'Native diagnostics are captured (byte count reported); logging overhead remains in timings. No timing gates or hardware comparisons.', 'RSS is process-wide; parent aggregation, source hashing and report serialization are not included in child timings.', ], measurements, }, null, 2 ) + '\n' ); } if (import.meta.main) { await main(process.argv.slice(2)); }