/** P08 paired workload, invoked through benchmark-research.ts --sma. */ import assert from 'node:assert/strict'; import { createHash } from 'node:crypto'; import { readFileSync } from 'node:fs'; import { loadavg } from 'node:os'; import { join } from 'node:path'; import type { ReplayOutput, ReplayProjectionResult } from '@stock-bot/stock-config/canonical-replay'; import type { FinancialStrategyDecision } from '@stock-bot/types'; type Mode = 'sma' | 'recorded'; export type SmaWorkload = { totalBars: number; assets: number; owners: number; fastPeriod: number; slowPeriod: number; untradedAssets: number }; const hash = (value: string | Uint8Array) => createHash('sha256').update(value).digest('hex'); export function validateSmaWorkload(workload: SmaWorkload, mode: Mode): void { assert(mode === 'sma' || mode === 'recorded', 'Unknown SMA benchmark mode'); const { totalBars, assets, owners, fastPeriod, slowPeriod, untradedAssets } = workload; assert([totalBars, assets, owners, fastPeriod, slowPeriod, untradedAssets].every(Number.isSafeInteger), 'Expected integer benchmark selections'); assert(totalBars > 0 && assets > 0 && owners > 0 && owners <= assets && totalBars % assets === 0, 'Invalid asset/owner topology'); assert(fastPeriod > 0 && slowPeriod > fastPeriod && totalBars / assets > slowPeriod + 1, 'Invalid SMA periods or insufficient bars'); assert(untradedAssets === assets - owners, 'Incorrect untraded asset count'); } export async function smaChild(root: string, workload: SmaWorkload, mode: Mode) { validateSmaWorkload(workload, mode); const addon = join(root, 'apps/stock/engine/dist/engine.node'); const start = performance.now(); const nativeSha256 = hash(readFileSync(addon)); const importsStart = performance.now(); const { nativeReplayFixture } = await import('../test/fixtures/native-replay'); const { validateDatasetV2 } = await import('../apps/stock/orchestrator/src/data/historical-dataset-v2'); const { builtinStrategySelectionSchema } = await import('@stock-bot/stock-config/strategy'); const { createBuiltinStrategy, validateBuiltinStrategyBindings } = await import('../apps/stock/orchestrator/src/strategies/canonical-builtins'); const { prepareReplayLoad, NativeReplaySession, runReplaySession } = await import('../apps/stock/orchestrator/src/backtest/native-replay'); const { runStrategyReplay } = await import('../apps/stock/orchestrator/src/backtest/strategy-runtime'); const importMs = performance.now() - importsStart; const preparationStart = performance.now(); const owners = Array.from({ length: workload.owners }, (_, i) => `owner-${i}`); const barsPerAsset = workload.totalBars / workload.assets; assert(Number.isSafeInteger(barsPerAsset) && barsPerAsset > workload.slowPeriod + 1); assert(workload.owners <= workload.assets && workload.untradedAssets === workload.assets - workload.owners); const fixture = nativeReplayFixture(barsPerAsset, workload.assets, owners); fixture.config.matching.risk.ledger.initialCapital = '1000000.00000000'; // One owner selects one series. Remaining assets still replay/mark but are untraded. fixture.config.cadence = owners.map((owner_id, i) => ({ owner_id, series_ids: [`${fixture.instruments[i]}:1m`] })); const dataset = validateDatasetV2(JSON.parse(JSON.stringify(fixture.dataset))); const load = prepareReplayLoad(dataset, fixture.config); const selections = owners.map((ownerId, i) => builtinStrategySelectionSchema.parse({ ownerId, strategyId: 'sma_crossover', strategyVersion: 'sma-crossover-long-only/v1', seed: i + 42, instrumentId: fixture.instruments[i], seriesId: `${fixture.instruments[i]}:1m`, ownerBudget: '1000.00000000', parameters: { fastPeriod: workload.fastPeriod, slowPeriod: workload.slowPeriod }, })); validateBuiltinStrategyBindings(selections, load); const programs = selections.map(createBuiltinStrategy); const preparationMs = performance.now() - preparationStart; const selectedByOwner = new Map(selections.map((selection) => [selection.ownerId, selection.instrumentId])); function validateFinancial(result: ReplayOutput): asserts result is ReplayProjectionResult { assert('format' in result && result.format === 'projection'); assert.equal(result.status, 'complete'); assert.equal(result.view.orders.length, 0, 'Termination must clear active orders'); assert.equal(result.view.reservations.length, 0, 'Termination must clear reservations'); assert.equal(result.view.portfolio.fees.length, workload.owners); assert(result.projection.fills.length > 0, 'Fixture must exercise actual trading'); for (const position of result.view.portfolio.positions) { assert.equal(position.instrumentId, selectedByOwner.get(position.ownerId), 'Strategy crossed instrument ownership'); assert(!position.quantity.startsWith('-'), 'Long-only quantity became negative'); } for (const fill of result.projection.fills) assert.equal(fill.instrumentId, selectedByOwner.get(fill.ownerId)); } // Untimed reference captures ACTUAL owner-stamped decisions, including all IDs. // The comparison removes author/state overhead without normalizing economic output. const referenceStart = performance.now(); const tape: { barrierId: string; decisions: FinancialStrategyDecision[] }[] = []; const originalSubmit = NativeReplaySession.prototype.submit; NativeReplaySession.prototype.submit = function (barrierId: string, decisions: FinancialStrategyDecision[]) { tape.push({ barrierId, decisions: structuredClone(decisions) }); return originalSubmit.call(this, barrierId, decisions); }; let referenceResultHash: string, referenceDiagnosticsHash: string; let economic: { cash: string; equity: string; positions: ReplayProjectionResult['view']['portfolio']['positions']; fees: ReplayProjectionResult['view']['portfolio']['fees']; fills: number; decisions: number }; try { const reference = runStrategyReplay(load, programs, { resultFormat: 'projection', eventBudget: 64 }); validateFinancial(reference.result); referenceResultHash = hash(JSON.stringify(reference.result)); referenceDiagnosticsHash = hash(JSON.stringify(reference.diagnostics)); assert.equal(tape.length, barsPerAsset - 1); assert.equal(tape.reduce((sum, row) => sum + row.decisions.length, 0), workload.owners * (barsPerAsset - 1)); for (const strategy of reference.diagnostics.strategies) { assert.equal(strategy.nextDecisionSequence, barsPerAsset - 1); assert.equal(strategy.rng.draws, 0, 'Canonical SMA must not consume randomness'); assert.equal(strategy.observationCount, workload.assets * (barsPerAsset - 1)); assert.equal((strategy.state as { closes: unknown[] }).closes.length, workload.slowPeriod + 1); } economic = { cash: reference.result.view.portfolio.cash, equity: reference.result.view.equity, positions: reference.result.view.portfolio.positions, fees: reference.result.view.portfolio.fees, fills: reference.result.projection.fills.length, decisions: tape.reduce((sum, row) => sum + row.decisions.length, 0) }; } finally { NativeReplaySession.prototype.submit = originalSubmit; } const referenceCaptureAndVerificationMs = performance.now() - referenceStart; const tapeHash = hash(JSON.stringify(tape)); const trials = []; for (let repeat = 0; repeat < 2; repeat++) { const executionStart = performance.now(); let cursor = 0; const output = mode === 'sma' ? runStrategyReplay(load, repeat === 1 ? [...programs].reverse() : programs, { resultFormat: 'projection', eventBudget: 64 }) : runReplaySession(new NativeReplaySession(load), { stage(context) { const recorded = tape[cursor++]; assert(recorded, 'Unexpected replay barrier'); assert.equal(recorded.barrierId, context.barrier.barrier_id); assert(recorded.decisions.every(decision => decision.revision === context.barrier.revision)); return recorded.decisions; }, }, { resultFormat: 'projection', eventBudget: 64 }); const executionWallMs = performance.now() - executionStart; const verificationStart = performance.now(); if (mode === 'recorded') assert.equal(cursor, tape.length, 'Unused recorded decisions'); validateFinancial(output.result); const resultHash = hash(JSON.stringify(output.result)); assert.equal(resultHash, referenceResultHash, 'Complete financial output differs from exact recorded-decision replay'); const diagnosticsHash = 'diagnostics' in output ? hash(JSON.stringify(output.diagnostics)) : null; if (mode === 'sma') assert.equal(diagnosticsHash, referenceDiagnosticsHash, 'Owner state/RNG/cursors changed on fresh replay/reordered owners'); trials.push({ repeat, reversePrograms: mode === 'sma' && repeat === 1, resultHash, diagnosticsHash, executionWallMs, metrics: output.metrics, verificationMs: performance.now() - verificationStart, rssBytes: process.memoryUsage().rss }); } const peak = process.platform === 'linux' ? /^VmHWM:\s+(\d+) kB$/m.exec(readFileSync('/proc/self/status', 'utf8')) : null; return { workload, mode, nativeSha256, datasetHash: dataset.manifest.hash, configHash: hash(JSON.stringify(load.config)), programHash: hash(JSON.stringify(selections)), selections, referenceResultHash, referenceDiagnosticsHash, tapeHash, economic, phasesMs: { importMs, preparationMs, referenceCaptureAndVerificationMs, childWallMs: performance.now() - start }, peakRssBytes: peak ? Number(peak[1]) * 1024 : null, trials }; } function median(values: number[]) { const sorted = [...values].sort((a, b) => a - b), middle = Math.floor(sorted.length / 2); return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2; } export async function smaBenchmark(root: string, entrypoint: string, identity: ReturnType, measured: boolean) { const smoke = !measured, measurements = []; assert(smoke || identity.native.matchedBuildProfiles.includes('release'), 'Full measurements require the matching release addon'); const shapes = smoke ? [[1, 1, 300], [10, 2, 3000], [10, 10, 3000]] : [[1, 1, 10000], [10, 2, 10000], [10, 10, 10000]]; for (const [fastPeriod, slowPeriod] of [[5, 15], [15, 252]]) { for (const [assets, owners, totalBars] of shapes) { const workload: SmaWorkload = { totalBars: totalBars!, assets: assets!, owners: owners!, fastPeriod: fastPeriod!, slowPeriod: slowPeriod!, untradedAssets: assets! - owners! }; const samples: (Awaited> & { processRepeat: number; processWallMs: number })[] = []; for (let processRepeat = 0; processRepeat < 2; processRepeat++) { const modes: Mode[] = processRepeat === 0 ? ['recorded', 'sma'] : ['sma', 'recorded']; for (const mode of modes) { const start = performance.now(); const worker = Bun.spawn([process.execPath, entrypoint, '--sma-child', JSON.stringify({ workload, mode })], { 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]); if (stderr) process.stderr.write(`[${fastPeriod}/${slowPeriod}/${assets}/${owners}/${mode}/${processRepeat}]\n${stderr}`); assert.equal(exit, 0, `${stderr}\n${stdout}`); const sample = JSON.parse(stdout) as Awaited>; assert.deepEqual(sample.workload, workload); assert.equal(sample.mode, mode); assert.equal(sample.nativeSha256, identity.native.sha256); samples.push({ ...sample, processRepeat, processWallMs: performance.now() - start }); } } const reference = samples[0]!; for (const sample of samples) for (const key of ['datasetHash', 'configHash', 'programHash', 'referenceResultHash', 'referenceDiagnosticsHash', 'tapeHash'] as const) assert.equal(sample[key], reference[key]); const summaries = (['recorded', 'sma'] as Mode[]).map(mode => { const trials = samples.filter(s => s.mode === mode).flatMap(s => s.trials); assert.equal(trials.length, 4); const medianExecutionWallMs = median(trials.map(t => t.executionWallMs)); return { mode, samples: 4, medianExecutionWallMs, medianBarsPerSecond: workload.totalBars / (medianExecutionWallMs / 1000), medianDecisionsPerSecond: reference.economic.decisions / (medianExecutionWallMs / 1000), medianVerificationMs: median(trials.map(t => t.verificationMs)), resultHash: reference.referenceResultHash, medianMetrics: Object.fromEntries(Object.keys(trials[0]!.metrics).map(key => [key, median(trials.map(t => t.metrics[key as keyof typeof t.metrics]))])) }; }); measurements.push({ workload, verified: true, summaries, samples }); process.stderr.write(`Verified SMA ${fastPeriod}/${slowPeriod}, ${assets} assets, ${owners} owners (${workload.untradedAssets} untraded assets): exact recorded/SMA financial hashes, 4 timed samples per mode\n`); } } process.stdout.write(JSON.stringify({ schemaVersion: 1, path: 'canonical-sma-versus-exact-recorded', mode: smoke ? 'smoke' : 'measurement', ...identity, hostLoadAtFinish: loadavg(), limitations: [ '10,000 TOTAL bars in full workloads, not per asset. Synthetic sawtooth fixture unchanged; one owner per selected asset. Ten-assets/two-owners explicitly leaves eight assets untraded while all ten replay/mark.', 'No database, durable queue, public-result mapping, real native-worker IPC, or production wall-clock throughput measurement. Each child imports modules and directly executes the canonical runtime.', 'Each fresh child first runs an untimed SMA reference to capture exact submitted financial identities. Timed fresh sessions therefore run in warmed processes; imports, preparation, reference capture and process wall time are separate.', 'Actual versioned SMA code uses bounded slow+1 JSON history and reviewed trailing calculations. Both 5/15 and 15/252 are measured; large-period copying/scanning costs remain included.', 'Recorded control replays exact captured decisions through the same Rust/native pull loop. Complete financial projection hashes including all IDs must match; there is no TypeScript accounting oracle or financial normalization.', 'executionWallMs includes native-session construction, replay, state copying/strategy/staging/feedback where applicable, finalization and disposal. Benchmark verification/hashing is measured separately.', 'decisionMs includes host validation/state copying/strategy execution/admission feedback for SMA and tape lookup/checks for recorded control. Difference is not pure callback or NAPI crossing cost.', 'Both modes retain reference decision tapes; RSS includes reference activity and tape memory. No allocation attribution or resident-dataset caching claim.', 'Two separate processes per mode, two fresh timed sessions each, counterbalanced mode order. Second SMA session reverses owner callback order and must preserve financial and diagnostic hashes. This checks fresh whole-attempt recomputation, not native checkpoint resume.', 'Shared host, no timing assertion, confidence interval, cold-start SLA, or cross-artifact performance attribution. Root must freeze source and use the matching release addon before execution.', ], measurements }, null, 2) + '\n'); }