feat(engine): expose canonical replay sessions through native workers

This commit is contained in:
Boki 2026-10-23 00:54:36 -04:00
parent 417a7bd21e
commit e3635f23cf
26 changed files with 2693 additions and 33 deletions

378
scripts/benchmark-replay.ts Normal file
View file

@ -0,0 +1,378 @@
/** F07 extension of P01, invoked only through benchmark-research.ts --session. */
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import type { ReplayResult } from '../apps/stock/orchestrator/src/contracts/native-replay';
type SessionWorkload = { totalBars: number; assets: number; owners: number; eventBudget: number };
const hash = (value: string) => createHash('sha256').update(value).digest('hex');
const capital = '1000000.00000000';
function cents(value: bigint): string {
const magnitude = value < 0n ? -value : value;
return `${value < 0n ? '-' : ''}${magnitude / 100n}.${String(magnitude % 100n).padStart(2, '0')}000000`;
}
/** Independent integer-cent oracle for this fixture only, not a second simulator.
* One unit per owner/asset alternates buy/sell at opens 1..N-1, with a 1% fee.
* Final position is marked at last close (open+1); no invented liquidation. */
export function turnoverOracle(barsPerAsset: number, assets: number, owners: number) {
if (
![barsPerAsset, assets, owners].every(Number.isSafeInteger) ||
barsPerAsset < 3 ||
assets < 1 ||
owners < 1
) {
throw new Error('Expected at least three bars and positive asset/owner counts');
}
let cashDelta = 0n,
fee = 0n;
for (let step = 1; step < barsPerAsset; step++) {
const price = BigInt(10 + (step % 20) * 2);
cashDelta += (step % 2 ? -price : price) * 100n - price;
fee += price;
}
const books = BigInt(assets * owners),
holding = (barsPerAsset - 1) % 2;
const lastOpen = BigInt(10 + ((barsPerAsset - 1) % 20) * 2);
const cash = 100_000_000n + cashDelta * books;
return {
cash: cents(cash),
equity: cents(cash + BigInt(holding) * (lastOpen + 1n) * 100n * books),
feePerOwner: cents(fee * BigInt(assets)),
quantity: `${holding}.00000000`,
remainingCost: cents(BigInt(holding) * lastOpen * 100n),
fills: (barsPerAsset - 1) * assets * owners,
decisions: (barsPerAsset - 1) * owners,
};
}
function assertEconomics(result: ReplayResult, workload: SessionWorkload) {
const expected = turnoverOracle(
workload.totalBars / workload.assets,
workload.assets,
workload.owners
);
const portfolio = result.view.portfolio;
if (
portfolio.cash !== expected.cash ||
result.view.equity !== expected.equity ||
portfolio.positions.length !== workload.assets * workload.owners ||
portfolio.positions.some(
p => p.quantity !== expected.quantity || p.remainingCost !== expected.remainingCost
) ||
portfolio.fees.length !== workload.owners ||
portfolio.fees.some(f => f.amount !== expected.feePerOwner) ||
result.view.orders.length ||
result.view.reservations.length
) {
throw new Error('Canonical benchmark failed independent cash/equity/owner/basis/fee oracle');
}
let fills = 0,
fees = 0;
for (const receipt of result.receipts) {
for (const effect of receipt.outcome.effects) {
if (!('Risk' in effect)) {
continue;
}
const risk = effect.Risk as {
outcome: {
disposition: unknown;
financial: null | { replayed: boolean; effects: { effects: { kind: string }[] } };
};
};
if (risk.outcome.disposition !== 'Accepted') {
throw new Error('Unexpected benchmark risk rejection');
}
if (!risk.outcome.financial) {
continue;
}
if (risk.outcome.financial.replayed) {
throw new Error('Unexpected benchmark duplicate effect');
}
for (const financial of risk.outcome.financial.effects.effects) {
if (financial.kind === 'fillApplied') {
fills++;
}
if (financial.kind === 'feeApplied') {
fees++;
}
}
}
}
if (fills !== expected.fills || fees !== fills) {
throw new Error('Unexpected benchmark fill/fee count');
}
return { ...expected, fees };
}
export async function sessionChild(workload: SessionWorkload) {
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 { validateDatasetV2 } = await import(
'../apps/stock/orchestrator/src/data/historical-dataset-v2'
);
const { nativeReplayFixture } = await import('../test/fixtures/native-replay');
const { parseFinancialDecimal } = await import('@stock-bot/types');
const applicationImportMs = elapsed();
await import('@stock-bot/engine');
const addonImportMs = elapsed();
const { prepareReplayLoad, NativeReplaySession, runReplayConformance } = await import(
'../apps/stock/orchestrator/src/backtest/native-replay'
);
const adapterImportMs = elapsed();
const ownerIds = Array.from({ length: workload.owners }, (_, i) => `owner-${i}`);
const fixture = nativeReplayFixture(
workload.totalBars / workload.assets,
workload.assets,
ownerIds
);
fixture.config.matching.risk.ledger.initialCapital = capital;
const fixtureGenerationMs = elapsed();
// Detach so the first verification cannot hit D01's immutable-object cache.
const wireDataset = JSON.stringify(fixture.dataset);
const detached = JSON.parse(wireDataset);
const datasetTransportRoundtripMs = elapsed();
const dataset = validateDatasetV2(detached);
const frozenDatasetVerificationMs = elapsed();
const load = prepareReplayLoad(dataset, fixture.config);
const preparedReuseAndMappingMs = elapsed();
const createRequestBytes = Buffer.byteLength(JSON.stringify(load));
const advanceRequestBytes = Buffer.byteLength(
JSON.stringify({ identity: load.identity, eventBudget: workload.eventBudget })
);
const finalizeRequestBytes = Buffer.byteLength(JSON.stringify(load.identity));
const requestSizingMs = elapsed();
const trials = [];
for (let repeat = 0; repeat < 2; repeat++) {
const trialStart = performance.now();
const session = new NativeReplaySession(load);
const nativeCreateMs = performance.now() - trialStart;
const counts = new Map<string, number>();
const one = parseFinancialDecimal('1'),
zero = parseFinancialDecimal('0');
const runStart = performance.now();
const { result, metrics } = runReplayConformance(
session,
owner => {
const decision = counts.get(owner) ?? 0;
counts.set(owner, decision + 1);
return {
mode: 'target',
targets: fixture.instruments.map(instrumentId => ({
instrumentId,
quantity: decision % 2 ? zero : one,
})),
};
},
{ eventBudget: workload.eventBudget, reverseCallbacks: repeat === 1 }
);
const runWallMs = performance.now() - runStart;
const validationStart = performance.now();
const economic = assertEconomics(result, workload);
const decisions = [...counts.values()].reduce((a, b) => a + b, 0);
if (decisions !== economic.decisions) {
throw new Error('Unexpected benchmark decision count');
}
// Exact complete normalized result bytes include provenance, ordered receipts,
// policy and terminal holdings, not just a selectively hashed P&L summary.
const resultHash = hash(JSON.stringify(result));
const validationAndHashMs = performance.now() - validationStart;
const wallMs = performance.now() - trialStart;
trials.push({
repeat,
reverseCallbacks: repeat === 1,
resultHash,
economic,
calls: {
create: 1,
advance: metrics.advanceCalls,
submit: metrics.submitCalls,
finalize: 1,
dispose: 1,
decisions,
},
bytes: {
createRequest: createRequestBytes,
advanceRequests: advanceRequestBytes * metrics.advanceCalls,
advanceResponses: metrics.contextBytes,
submitRequests: metrics.submissionBytes,
submitResponses: metrics.outcomeBytes,
finalizeRequest: finalizeRequestBytes,
finalizeResponse: metrics.resultBytes,
},
timingsMs: {
nativeCreateMs,
advance: metrics.advanceMs,
submit: metrics.submitMs,
decisions: metrics.decisionMs,
finalize: metrics.finalizeMs,
runWallMs,
validationAndHashMs,
wallMs,
},
meanCallMs: {
advance: metrics.advanceMs / metrics.advanceCalls,
submit: metrics.submitMs / metrics.submitCalls,
},
rates: {
runBarsPerSecond: workload.totalBars / (runWallMs / 1000),
wholeTrialBarsPerSecond: workload.totalBars / (wallMs / 1000),
decisionsPerSecond: decisions / (runWallMs / 1000),
trialsPerSecond: 1000 / wallMs,
},
rssBytes: process.memoryUsage().rss,
});
}
const peakRss =
process.platform === 'linux'
? /^VmHWM:\s+(\d+) kB$/m.exec(readFileSync('/proc/self/status', 'utf8'))
: null;
return {
workload,
datasetHash: dataset.manifest.hash,
policyHash: hash(
JSON.stringify({ config: load.config, strategy: 'alternating-unit-target-v1' })
),
datasetBytes: Buffer.byteLength(wireDataset),
policy: load.config,
phasesMs: {
entryUptimeMs,
applicationImportMs,
addonImportMs,
adapterImportMs,
fixtureGenerationMs,
datasetTransportRoundtripMs,
frozenDatasetVerificationMs,
preparedReuseAndMappingMs,
requestSizingMs,
childWallMs: performance.now() - start,
},
peakRssBytes: peakRss ? Number(peakRss[1]) * 1024 : null,
peakRssSource: peakRss ? '/proc/self/status VmHWM' : 'unavailable',
trials,
};
}
export function verifySessionRepeats(
samples: { datasetHash: string; policyHash: string; trials: { resultHash: string }[] }[]
) {
const first = samples[0],
expected = first?.trials[0]?.resultHash;
if (!first || !expected) {
throw new Error('Missing canonical benchmark samples');
}
for (const sample of samples) {
if (
sample.datasetHash !== first.datasetHash ||
sample.policyHash !== first.policyHash ||
!sample.trials.length ||
sample.trials.some(trial => trial.resultHash !== expected)
) {
throw new Error('Canonical dataset/policy/result mismatch; no timing comparison is valid');
}
}
}
export async function sessionBenchmark(
root: string,
entry: string,
metadata: object,
measured: boolean,
large: boolean
) {
const workloads = (measured ? (large ? [1000, 10000, 100000] : [1000, 10000]) : [8]).flatMap(
bars => [
{ totalBars: bars, assets: 1, owners: 1, eventBudget: 64 },
{
totalBars: measured ? bars : bars * 2,
assets: measured ? 10 : 2,
owners: 2,
eventBudget: 64,
},
]
);
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, entry, '--session-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(`Canonical benchmark child failed (${exit}): ${stderr}\n${stdout}`);
}
const sample = JSON.parse(stdout) as Awaited<ReturnType<typeof sessionChild>>;
samples.push({
...sample,
processRepeat,
processWallMs,
nativeDiagnosticBytes: Buffer.byteLength(stderr),
processTrialsPerSecond: sample.trials.length / (processWallMs / 1000),
processBarsPerSecond: (workload.totalBars * sample.trials.length) / (processWallMs / 1000),
});
}
verifySessionRepeats(samples);
measurements.push({ workload, repeatedResultHashesMatch: true, samples });
process.stderr.write(
`Verified canonical ${workload.totalBars} bars / ${workload.assets} assets / ${workload.owners} owners, 2 fresh processes × 2 fresh sessions\n`
);
}
process.stdout.write(
JSON.stringify(
{
schemaVersion: 1,
path: 'canonical-pull-session',
mode: measured ? 'measurement' : 'self-test',
...metadata,
strategy: {
definition: 'alternating-unit-target-v1',
randomness: 'None; controlled deterministic fixture/decision counters',
},
unavailable: {
storage: 'Synthetic fixture; no database I/O.',
queue: 'Direct child/session calls, not durable dispatch.',
allocations: 'No allocation counter or native/JS heap attribution.',
residentDataset: 'Every trial creates and reloads a fresh native session.',
pureBoundary:
'Timings include JS encoding/validation, native work and serialization; not empty NAPI crossing cost.',
sharedIndicators: 'No indicator cache or feature model in this conformance trace.',
parallelism: 'Sequential trials; no parallel simulation.',
perCallDistribution:
'Mean and total latency only; no latency histogram or cancellation wall-time claim.',
},
limitations: [
'Component conformance throughput, not a production strategy or durable research run; no comparison/speedup against legacy economics.',
'First imports and detached dataset verification are separate from once-per-child prepared-JS-object mapping and repeated fresh-session loads. OS page caches are not flushed.',
'First session and repeat are reported separately; no explicit warmup. Every repeated result, including reversed callback order, must match exactly.',
'Advance response bytes include immutable context, observation deltas and protocol envelopes; they are not feature payload bytes alone.',
'Financial oracle uses integer cents for this fixed-price/unit/1%-fee fixture only. Multi-asset sequential-mark risk semantics remain unchanged.',
'Full retained receipts are finalized and parsed; RSS is process-wide, not native residency. Metadata hashing and parent aggregation are outside child timings.',
'An event budget bounds event count, not elapsed time. JSON throughput and actual decision costs are measured together with boundary work.',
],
measurements,
},
null,
2
) + '\n'
);
}

View file

@ -1,8 +1,10 @@
/**
* Existing one-shot native path only; no DB, broker, queue or strategy callbacks.
* 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';
@ -335,19 +337,37 @@ export function verifyRepeats(
}
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'].includes(a)) ||
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');
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 }))

View file

@ -183,11 +183,15 @@ describe('orchestrator architecture boundaries', () => {
relative(root, file).startsWith('backtest/') &&
imports.get(file)?.includes('@stock-bot/engine')
);
expect(nativeEntrypoints.map(file => relative(root, file))).toEqual([
expect(nativeEntrypoints.map(file => relative(root, file)).sort()).toEqual([
'backtest/native-replay.ts',
'backtest/native-worker.ts',
]);
for (const file of files) {
const path = relative(root, file);
if (reachable(file).has(join(root, 'backtest/native-replay.ts'))) {
expect(['backtest/native-replay.ts', 'backtest/native-worker.ts']).toContain(path);
}
const source = ts.createSourceFile(
file,
readFileSync(file, 'utf8'),
@ -211,6 +215,12 @@ describe('orchestrator architecture boundaries', () => {
) {
expect(path).toBe('backtest/native-worker.ts');
}
if (
!binding.isTypeOnly &&
(binding.propertyName ?? binding.name).text === 'FinancialReplaySession'
) {
expect(path).toBe('backtest/native-replay.ts');
}
}
}
}

View file

@ -0,0 +1,81 @@
import { expect, test } from 'bun:test';
import { turnoverOracle, verifySessionRepeats } from '../benchmark-replay';
test('canonical benchmark integer-cent oracle includes fees and terminal marks', () => {
expect(turnoverOracle(3, 1, 1)).toEqual({
cash: '1000001.74000000',
equity: '1000001.74000000',
feePerOwner: '0.26000000',
quantity: '0.00000000',
remainingCost: '0.00000000',
fills: 2,
decisions: 2,
});
expect(turnoverOracle(4, 2, 2)).toEqual({
cash: '999942.32000000',
equity: '1000010.32000000',
feePerOwner: '0.84000000',
quantity: '1.00000000',
remainingCost: '16.00000000',
fills: 12,
decisions: 6,
});
expect(() => turnoverOracle(2, 1, 1)).toThrow('three bars');
});
test('canonical benchmark rejects any changed provenance or complete result hash', () => {
const sample = {
datasetHash: 'dataset',
policyHash: 'policy',
trials: [{ resultHash: 'result' }, { resultHash: 'result' }],
};
expect(() => verifySessionRepeats([sample, structuredClone(sample)])).not.toThrow();
for (const changed of [
{ ...sample, datasetHash: 'changed' },
{ ...sample, policyHash: 'changed' },
{ ...sample, trials: [{ resultHash: 'changed' }] },
{ ...sample, trials: [] },
]) {
expect(() => verifySessionRepeats([sample, changed])).toThrow('mismatch');
}
expect(() => verifySessionRepeats([])).toThrow('Missing');
});
test('canonical self-test measures real sessions and verifies repeated full-result hashes', async () => {
const worker = Bun.spawn([process.execPath, 'scripts/benchmark-research.ts', '--session'], {
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.path).toBe('canonical-pull-session');
expect(report.mode).toBe('self-test');
expect(report.native.sha256).toMatch(/^[a-f0-9]{64}$/);
expect(report.measurements.map((m: any) => m.workload.owners)).toEqual([1, 2]);
for (const measurement of report.measurements) {
verifySessionRepeats(measurement.samples);
expect(measurement.samples).toHaveLength(2);
for (const sample of measurement.samples) {
expect(sample.trials).toHaveLength(2);
expect(sample.phasesMs.frozenDatasetVerificationMs).toBeGreaterThanOrEqual(0);
expect(sample.phasesMs.preparedReuseAndMappingMs).toBeGreaterThanOrEqual(0);
for (const trial of sample.trials) {
expect(trial.resultHash).toMatch(/^[a-f0-9]{64}$/);
expect(trial.calls.decisions).toBe(trial.economic.decisions);
expect(trial.economic.fees).toBe(trial.economic.fills);
expect(trial.calls.advance).toBeGreaterThan(trial.calls.submit);
expect(trial.bytes.advanceResponses).toBeGreaterThan(0);
expect(trial.bytes.submitRequests).toBeGreaterThan(0);
expect(trial.bytes.finalizeResponse).toBeGreaterThan(0);
expect(trial.timingsMs.nativeCreateMs).toBeGreaterThanOrEqual(0);
expect(trial.timingsMs.finalize).toBeGreaterThanOrEqual(0);
}
}
}
});

View file

@ -2,6 +2,7 @@ import { createRequire } from 'node:module';
import { describe, expect, it } from 'bun:test';
import {
BacktestEngine,
FinancialReplaySession,
IncrementalSMA,
TechnicalIndicators,
TradingEngine,
@ -70,6 +71,7 @@ describe('generated native bindings', () => {
const binding = createRequire(import.meta.url)('@stock-bot/engine');
expect(binding.TechnicalIndicators).toBe(TechnicalIndicators);
expect(binding.IncrementalSMA).toBe(IncrementalSMA);
expect(binding.FinancialReplaySession).toBe(FinancialReplaySession);
});
it('MACD keeps full-length EMA series aligned without out-of-bounds access', () => {