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

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', () => {