perf(research): add reproducible native baseline benchmarks

This commit is contained in:
Boki 2026-10-22 16:24:57 -04:00
parent bba5aa1269
commit 2e851ec351
2 changed files with 573 additions and 0 deletions

View file

@ -0,0 +1,428 @@
/**
* Existing one-shot native path only; no DB, broker, queue or strategy callbacks.
* 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)
* 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, unknown>): 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<string, string>();
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] === '--child') {
process.stdout.write(JSON.stringify(await child(JSON.parse(args[1] ?? ''))) + '\n');
return;
}
if (
args.some(a => !['--self-test', '--measure', '--large'].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');
}
const metadata = identity(); // Excluded from workload timings.
const measured = args.includes('--measure');
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<ReturnType<typeof child>>;
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));
}

View file

@ -0,0 +1,145 @@
import { describe, expect, test } from 'bun:test';
import { prepareDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
import {
economicHash,
parameters,
researchFixture,
unavailable,
verifyRepeats,
} from '../benchmark-research';
describe('existing-path research benchmark', () => {
test('fixture is seeded, ordered, hash-verified and detached by real dataset preparation', async () => {
for (const assets of [1, 10]) {
const source = researchFixture(80 * assets, assets);
const dataset = await prepareDataset(source);
expect(dataset).not.toBe(source);
expect(Object.isFrozen(dataset.bars)).toBe(true);
expect(dataset.manifest.hash).toBe(researchFixture(80 * assets, assets).manifest.hash);
expect(dataset.manifest.hash).not.toBe(
researchFixture(80 * assets, assets, 43).manifest.hash
);
expect(dataset.manifest.barCount).toBe(80 * assets);
expect(new Set(dataset.bars.map(b => b.symbol)).size).toBe(assets);
expect(await prepareDataset(dataset)).toBe(dataset);
}
expect(() => researchFixture(81, 10)).toThrow('divisible');
expect(() => researchFixture(80, 0)).toThrow('assets');
expect(() => researchFixture(80, 1, NaN)).toThrow('seed');
});
test('economic hash ignores only run metadata, map order and unordered position summaries', () => {
const a = {
backtestId: 'first',
completedAt: 'now',
executionTime: 1,
metrics: { cash: 99, commission: 1 },
positions: [
{ symbol: 'B', quantity: 2 },
{ symbol: 'A', quantity: 1 },
],
trades: [
{ id: 'first', price: 5 },
{ id: 'second', price: 6 },
],
equity: [100, 99],
ohlcData: { B: [2, 3], A: [1, 4] },
};
const b = {
...a,
backtestId: 'second',
completedAt: 'later',
executionTime: 99,
metrics: { commission: 1, cash: 99 },
positions: [...a.positions].reverse(),
ohlcData: { A: [1, 4], B: [2, 3] },
};
expect(economicHash(a)).toBe(economicHash(b));
expect(economicHash(a)).not.toBe(economicHash({ ...b, trades: [...b.trades].reverse() }));
expect(economicHash(a)).not.toBe(economicHash({ ...b, equity: [...b.equity].reverse() }));
expect(economicHash(a)).not.toBe(economicHash({ ...b, metrics: { commission: 2, cash: 98 } }));
expect(economicHash(a)).not.toBe(economicHash({ ...b, newEconomicField: 1 }));
expect(a.positions[0]!.symbol).toBe('B');
});
test('comparison rejects changed data, policy or economics instead of accepting faster results', () => {
const sample = {
datasetHash: 'dataset',
policyHash: 'policy',
trials: [{ strategyParameters: parameters[0]!, economicHash: 'economic' }],
};
expect(() => verifyRepeats([sample, structuredClone(sample)])).not.toThrow();
expect(() => verifyRepeats([sample, { ...sample, datasetHash: 'changed' }])).toThrow(
'Dataset/policy'
);
expect(() => verifyRepeats([sample, { ...sample, policyHash: 'changed' }])).toThrow(
'Dataset/policy'
);
expect(() =>
verifyRepeats([
sample,
{ ...sample, trials: [{ ...sample.trials[0]!, economicHash: 'changed' }] },
])
).toThrow('Economic mismatch');
expect(() => verifyRepeats([])).toThrow('Missing');
expect(
Object.values(unavailable).every(reason => typeof reason === 'string' && reason.length > 0)
).toBe(true);
});
test('tiny native self-test records honest phases and pinned identities without timing thresholds', async () => {
const worker = Bun.spawn([process.execPath, 'scripts/benchmark-research.ts', '--self-test'], {
cwd: new URL('../..', import.meta.url).pathname,
stdout: 'pipe',
stderr: 'pipe',
});
const [stdout, stderr, exit] = await Promise.all([
new Response(worker.stdout).text(),
new Response(worker.stderr).text(),
worker.exited,
]);
expect(exit, stderr).toBe(0);
const report = JSON.parse(stdout);
expect(report.mode).toBe('self-test');
expect(report.source.commit).toMatch(/^[a-f0-9]{40}$/);
for (const hash of [
report.source.contentSha256,
report.native.sha256,
report.runtime.executableSha256,
report.runtime.lockSha256,
report.runtime.cargoLockSha256,
report.host.sha256,
report.seed.sha256,
]) {
expect(hash).toMatch(/^[a-f0-9]{64}$/);
}
expect(typeof report.source.dirty).toBe('boolean');
expect(report.runtime.bun).toBe(Bun.version);
expect(report.native.path).toContain('/apps/stock/engine/dist/engine.node');
expect(report.native.buildProfile).toMatch(/^(debug|release|unverified)$/);
expect(report.unavailable).toEqual(unavailable);
expect(report.measurements.map((m: any) => m.workload.assets)).toEqual([1, 10]);
for (const measurement of report.measurements) {
expect(measurement.repeatedEconomicHashesMatch).toBe(true);
expect(measurement.samples).toHaveLength(2);
verifyRepeats(measurement.samples);
for (const sample of measurement.samples) {
expect(sample.trials).toHaveLength(6);
expect(sample.datasetHash).toMatch(/^[a-f0-9]{64}$/);
expect(sample.policyHash).toMatch(/^[a-f0-9]{64}$/);
expect(sample.processWallMs).toBeGreaterThan(0);
expect(sample.phasesMs).toHaveProperty('addonImportMs');
expect(sample.phasesMs).toHaveProperty('datasetPreparationMs');
for (const trial of sample.trials) {
expect(trial.fills).toBeGreaterThan(0);
expect(trial.resultBytes).toBeGreaterThan(0);
expect(trial.rssBytes).toBeGreaterThan(0);
expect(trial.timingsMs).toHaveProperty('nativeLoadMs');
expect(trial.timingsMs).toHaveProperty('nativeRunMs');
expect(trial.timingsMs).toHaveProperty('resultParseMs');
expect(trial.economicHash).toMatch(/^[a-f0-9]{64}$/);
}
}
}
});
});