feat(research): run retained strategies through durable canonical engine

This commit is contained in:
Boki 2026-10-23 21:59:09 -04:00
parent d929db707a
commit 618fb9e33c
58 changed files with 6596 additions and 779 deletions

View file

@ -0,0 +1,331 @@
import { randomUUID } from 'node:crypto';
import { EventEmitter } from 'node:events';
import { describe, expect, test } from 'bun:test';
import {
canonicalRunRequestSchema,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetV2 } from '@stock-bot/types';
import { builtinCatalogDescriptors } from '../../apps/stock/config/src/contracts/strategy';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import {
BacktestCancelledError,
type BacktestExecutionEngine,
} from '../../apps/stock/orchestrator/src/backtest/execution-engine';
import {
BacktestLeaseLostError,
type BacktestRunRepository,
} from '../../apps/stock/orchestrator/src/backtest/run-repository';
import { canonicalSmaFixture } from '../fixtures/canonical-sma';
const logger = { error() {} };
function setup() {
const versionId = randomUUID(),
runId = randomUUID(),
ownerId = `strategy:${versionId}`;
const { dataset, config, selections } = canonicalSmaFixture([ownerId]);
config.matching.risk.ledger.sessionId = runId;
config.matching.risk.ledger.accountId = `research:${runId}`;
const descriptor = builtinCatalogDescriptors.find(d => d.program.strategyId === 'sma_crossover')!;
const request = canonicalRunRequestSchema.parse({
kind: 'canonical-research/v1',
runId,
backtestId: randomUUID(),
name: 'Runner boundary',
strategy: {
familyId: randomUUID(),
versionId,
origin: 'builtin',
reviewId: randomUUID(),
selection: selections[0],
package: {
version: 1,
program: descriptor.program,
parameterSchema: descriptor.parameterSchema,
artifact: {
format: 'esm-bundle/v1',
entryExport: descriptor.entryExport,
content: 'not executed by this lifecycle fixture',
sha256: 'a'.repeat(64),
},
dependencyLock: { format: 'bun-lock/v1', content: 'fixture', sha256: 'b'.repeat(64) },
source: { revision: 'c'.repeat(40), dirty: false },
build: { tool: 'bun', version: 'fixture', target: 'browser' },
},
},
datasetHash: dataset.manifest.hash,
policy: config,
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
modelArtifacts: [],
build: {
version: 1,
workerSha256: 'd'.repeat(64),
engineWrapperSha256: 'e'.repeat(64),
engineBinarySha256: 'f'.repeat(64),
dependencyLockSha256: 'b'.repeat(64),
runtime: 'bun',
runtimeVersion: 'fixture',
platform: 'linux',
arch: 'x64',
},
});
const events: string[] = [];
let result: CanonicalRunResult | undefined;
let heartbeatFailure = false;
let status = 'pending';
const repo: BacktestRunRepository = {
async start() {
throw new Error('legacy claim must not run');
},
async startCanonical(input) {
events.push('claim');
status = 'running';
return {
runId,
backtestId: request.backtestId,
attemptId: 'attempt',
config: structuredClone(input),
};
},
async load() {
return { status, config: structuredClone(request) };
},
async rejectPending() {
events.push('reject');
status = 'failed';
},
async heartbeat() {
events.push('heartbeat');
if (heartbeatFailure) {
throw new Error('lost');
}
return { cancelRequested: false };
},
async loadDataset() {
throw new Error('v1 data must not run');
},
async freezeDataset() {
throw new Error('provider freeze must not run');
},
async loadCanonicalDataset(_id, _attempt, hash) {
expect(hash).toBe(dataset.manifest.hash);
events.push('dataset');
return dataset;
},
async complete() {
throw new Error('legacy completion must not run');
},
async completeCanonical(input) {
events.push('complete');
result = input;
status = 'completed';
},
async updateProgress() {
events.push('progress');
},
async fail() {
events.push('fail');
status = 'failed';
},
async cancel() {
events.push('cancel');
status = 'cancelled';
},
async updateControl() {},
};
const engine = Object.assign(new EventEmitter(), {
async runBacktest(): Promise<never> {
throw new Error('legacy simulator must not run');
},
async runCanonical(
_input: typeof request,
resolve: (signal: AbortSignal) => Promise<HistoricalDatasetV2>
) {
await resolve(new AbortController().signal);
events.push('execute');
// Economic validation belongs to the actual worker/SQL fixtures; this fixture probes lifecycle only.
return {
financial: {} as CanonicalRunResult['financial'],
analytics: {} as CanonicalRunResult['analytics'],
};
},
async stopBacktest() {
events.push('stop');
},
async pauseBacktest() {},
async resumeBacktest() {},
setSpeedMultiplier() {},
getStatus() {
return { isRunning: false, isPaused: false, progress: 0, currentTime: 0 };
},
async shutdown() {},
}) satisfies BacktestExecutionEngine;
const runner = new BacktestRunner({
engine,
repository: repo,
engineName: 'native',
logger,
heartbeatMs: 5,
heartbeatTimeoutMs: 50,
async prepare() {
throw new Error('legacy preparation must not run');
},
});
return {
request,
dataset,
repo,
engine,
runner,
events,
get result() {
return result;
},
loseLease() {
heartbeatFailure = true;
},
};
}
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: Error) => void;
const promise = new Promise<T>((a, b) => {
resolve = a;
reject = b;
});
return { promise, resolve, reject };
}
describe('canonical jobs share the durable runner lifecycle', () => {
test('queued canonical result preserves admitted request and bypasses every legacy seam', async () => {
const f = setup();
expect(await f.runner.runQueued(f.request.runId)).toEqual({
runId: f.request.runId,
status: 'completed',
});
expect(f.events).toEqual(['claim', 'heartbeat', 'dataset', 'execute', 'complete']);
expect(f.result?.request).toEqual(f.request);
expect(f.result?.kind).toBe('canonical-result/v1');
expect(await f.runner.runQueued(f.request.runId)).toEqual({
runId: f.request.runId,
status: 'completed',
});
expect(f.events.filter(e => e === 'execute')).toHaveLength(1);
await expect(f.runner.runBacktest(f.request)).rejects.toThrow();
await f.runner.shutdown();
});
test('legacy entry refuses canonical markers even when the remaining fields look legacy', async () => {
const f = setup();
const legacy = {
mode: 'backtest',
strategy: 'sma-crossover',
symbols: ['X.US'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-02-01T00:00:00.000Z',
initialCapital: 10000,
dataFrequency: '1d',
};
for (const marker of [
{ kind: 'canonical-research/v1' },
{ kind: 'canonical-research/v999' },
{ canonical: {} },
]) {
await expect(f.runner.runBacktest({ ...legacy, ...marker })).rejects.toThrow(
'Retained strategy versions'
);
}
expect(f.events).toEqual([]);
await f.runner.shutdown();
});
test('a runner without canonical execution fails without preparation or legacy/provider fallback', async () => {
const f = setup();
const engine: BacktestExecutionEngine = f.engine;
delete engine.runCanonical;
const fail = f.repo.fail.bind(f.repo);
let savedFailure: string | undefined;
f.repo.fail = async (runId, error, attemptId) => {
savedFailure = error;
await fail(runId, error, attemptId);
};
try {
await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow(
'Canonical execution capabilities are unavailable'
);
expect(savedFailure).toBe('Canonical execution capabilities are unavailable');
expect(f.events).toEqual(['claim', 'heartbeat', 'fail']);
expect(f.result).toBeUndefined();
expect(await f.runner.runQueued(f.request.runId)).toEqual({
runId: f.request.runId,
status: 'failed',
});
expect(f.events).toEqual(['claim', 'heartbeat', 'fail']);
} finally {
await f.runner.shutdown();
}
});
test('cancel waits for execution to finish before committing cancellation', async () => {
const f = setup(),
entered = deferred<void>(),
reaped = deferred<void>(),
exit = deferred<never>();
f.engine.runCanonical = async () => {
entered.resolve();
return exit.promise;
};
f.engine.stopBacktest = async () => {
f.events.push('stop');
await reaped.promise;
exit.reject(new BacktestCancelledError());
};
const run = f.runner.runQueued(f.request.runId);
const failed = run.catch(error => error);
await entered.promise;
let stopped = false;
const stop = f.runner.stopBacktest(f.request.runId).then(() => {
stopped = true;
});
await Promise.resolve();
expect(stopped).toBe(false);
expect(f.events).not.toContain('cancel');
reaped.resolve();
await stop;
expect(await failed).toBeInstanceOf(BacktestCancelledError);
expect(f.events).toContain('cancel');
expect(f.events).not.toContain('complete');
await f.runner.shutdown();
});
test('lease loss stops execution without overwriting a newer owner terminal state', async () => {
const f = setup(),
entered = deferred<void>(),
exit = deferred<never>();
f.engine.runCanonical = async () => {
entered.resolve();
return exit.promise;
};
f.engine.stopBacktest = async () => {
f.events.push('stop');
exit.reject(new BacktestCancelledError());
};
const run = f.runner.runQueued(f.request.runId);
const failed = run.catch(error => error);
await entered.promise;
f.loseLease();
expect(await failed).toBeInstanceOf(BacktestLeaseLostError);
expect(f.events).toContain('stop');
expect(f.events).not.toContain('fail');
expect(f.events).not.toContain('cancel');
expect(f.events).not.toContain('complete');
await f.runner.shutdown();
});
test('invalid persisted canonical kind never becomes a legacy run', async () => {
const f = setup();
f.repo.load = async () => ({
status: 'pending',
config: { ...f.request, kind: 'canonical-research/v2' },
});
await expect(f.runner.runQueued(f.request.runId)).rejects.toThrow();
expect(f.events).toEqual(['reject']);
await f.runner.shutdown();
});
});

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,351 @@
import { fork } from 'node:child_process';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { beforeAll, describe, expect, test } from 'bun:test';
import {
canonicalRunRequestSchema,
type CanonicalRunRequest,
} from '@stock-bot/stock-config/canonical-research';
import { parseFinancialDecimal, type StrategyVersionPackage } from '@stock-bot/types';
import {
canonicalWorkerUrl,
readCanonicalBuildIdentity,
} from '../../apps/stock/orchestrator/src/backtest/canonical-build';
import { buildCanonicalBacktestReport } from '../../apps/stock/orchestrator/src/backtest/canonical-result';
import { prepareReplayLoad } from '../../apps/stock/orchestrator/src/backtest/native-replay';
import {
nativeWorkerRequestSchema,
parseRetainedStrategyResult,
} from '../../apps/stock/orchestrator/src/backtest/native-worker-protocol';
import { NativeBacktestWorker } from '../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker';
import { runStrategyReplay } from '../../apps/stock/orchestrator/src/backtest/strategy-runtime';
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
import { packageBuiltinStrategies } from '../../scripts/package-builtin-strategies';
import { nativeReplayFixture } from '../fixtures/native-replay';
const runId = 'b96aae03-f6d6-43b5-a006-a160e37f012b';
const versionId = '212a7d31-893d-46c9-910b-2234566f20d6';
const ownerId = `strategy:${versionId}`;
const sha = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex');
let packages: StrategyVersionPackage[];
beforeAll(async () => {
packages = await packageBuiltinStrategies();
});
async function input(strategyId = 'sma_crossover') {
const { dataset, config } = nativeReplayFixture(24, 1, [ownerId]);
config.matching.risk.ledger.sessionId = runId;
config.matching.risk.ledger.accountId = `research:${runId}`;
const pkg = structuredClone(packages.find(item => item.program.strategyId === strategyId)!);
const request = canonicalRunRequestSchema.parse({
kind: 'canonical-research/v1',
runId,
backtestId: '4ea6a0fa-7bab-416f-b99e-ef9456567f66',
name: 'Exact retained built-in',
strategy: {
familyId: '05c49df3-08a4-40c5-b78d-4ee3364ac7a9',
versionId,
origin: 'builtin',
reviewId: 'e06828fc-8b37-4631-bf32-828d6095fdb6',
package: pkg,
selection: {
strategyId,
strategyVersion: pkg.program.strategyVersion,
ownerId,
seed: 17,
instrumentId: 'X0.US',
seriesId: 'X0.US:1m',
ownerBudget: '100',
parameters:
strategyId === 'sma_crossover'
? { fastPeriod: 1, slowPeriod: 2 }
: {
lookbackPeriod: 2,
trendPeriod: 3,
momentumPeriod: 1,
volatilityPeriod: 2,
entryZScore: 1,
exitZScore: 0,
minTrendReturn: -0.9,
minMomentumReturn: -0.9,
maxVolatility: 1,
minNotionalVolume: '0',
regimeFilter: 'none',
},
},
},
datasetHash: dataset.manifest.hash,
policy: config,
analyticsPolicy: { version: 1, periodsPerYear: 252, annualRiskFreeRate: 0, benchmark: null },
build: await readCanonicalBuildIdentity(),
modelArtifacts: [],
});
return { type: 'runRetainedStrategy' as const, request, dataset };
}
function retainedSource(request: CanonicalRunRequest, source: string) {
request.strategy.package.artifact.content = source;
request.strategy.package.artifact.sha256 = sha(source);
}
async function execute(value: Awaited<ReturnType<typeof input>>) {
const raw = await new NativeBacktestWorker().execute(
value,
new AbortController().signal,
() => {}
);
return { raw, result: parseRetainedStrategyResult(raw, value.request) };
}
describe('retained canonical strategy worker', () => {
test.each(['sma_crossover', 'mean_reversion'])(
'%s exact packaged bytes match the native report and repeat identically',
async strategyId => {
const value = await input(strategyId);
const load = prepareReplayLoad(value.dataset, value.request.policy);
const direct = runStrategyReplay(
load,
[createBuiltinStrategy(value.request.strategy.selection)],
{
resultFormat: 'report',
}
).result;
const expected = buildCanonicalBacktestReport(direct, value.request.analyticsPolicy);
const first = await execute(value);
expect(first.result.financial).toEqual(expected.financial);
expect(first.result.analytics).toEqual(expected.analytics);
expect(first.result.build).toEqual(value.request.build);
expect(first.result.artifactHash).toBe(value.request.strategy.package.artifact.sha256);
expect((await execute(value)).raw).toBe(first.raw);
}
);
test('a retained version executes its own bytes when the current constructor differs', async () => {
const value = await input();
const current = runStrategyReplay(
prepareReplayLoad(value.dataset, value.request.policy),
[createBuiltinStrategy(value.request.strategy.selection)],
{ resultFormat: 'report' }
).result;
expect(current.projection.fills.length).toBeGreaterThan(0);
// An earlier retained implementation that holds cash, with the same author API.
retainedSource(
value.request,
`export function createSmaStrategy(selection) {
return { ownerId:selection.ownerId, strategyId:selection.strategyId,
strategyVersion:selection.strategyVersion, seed:selection.seed, mode:'target',
initialState:{draws:0}, decide(context) { context.random();
return {nextState:{draws:context.state.draws+1}, intent:{mode:'target',targets:[]}}; }
};
}`
);
const first = await execute(value);
expect(first.result.financial.projection.fills).toEqual([]);
expect(first.result.financial.projection.valuation.equity).toBe(parseFinancialDecimal('10000'));
expect(first.result.analytics.metrics.exposureTime).toBe(0);
expect(first.result.analytics.metrics.roundTripCount).toBeNull();
expect((await execute(value)).raw).toBe(first.raw);
});
test('build and retained hashes are checked before module or factory side effects', async () => {
for (const changed of [
'workerSha256',
'engineWrapperSha256',
'engineBinarySha256',
'dependencyLockSha256',
'runtimeVersion',
'platform',
'arch',
] as const) {
const value = await input();
retainedSource(value.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
value.request.build[changed] = changed.endsWith('Sha256') ? 'f'.repeat(64) : 'wrong-build';
await expect(execute(value)).rejects.toThrow('build identity mismatch');
}
for (const changed of ['artifact', 'dependencyLock'] as const) {
const value = await input();
retainedSource(value.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
value.request.strategy.package[changed].sha256 = 'f'.repeat(64);
await expect(execute(value)).rejects.toThrow('artifact or dependency lock hash mismatch');
}
const verified = await input();
retainedSource(verified.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
await expect(execute(verified)).rejects.toThrow('RETAINED_MODULE_EXECUTED');
});
test('eligible exact single-series data and ownership are required before bundle import', async () => {
const value = await input();
retainedSource(value.request, 'throw new Error("RETAINED_MODULE_EXECUTED");');
const corrupt = {
...value,
dataset: {
manifest: structuredClone(value.dataset.manifest),
bars: value.dataset.bars.map(bar => ({ ...bar })),
},
};
corrupt.dataset.bars[0]!.volume += 1;
await expect(execute(corrupt)).rejects.toThrow('Dataset v2');
const other = nativeReplayFixture(24, 2, [ownerId]).dataset;
value.request.datasetHash = other.manifest.hash;
await expect(
new NativeBacktestWorker().execute(
{ ...value, dataset: other },
new AbortController().signal,
() => {}
)
).rejects.toThrow('Execution series must exactly match');
const candidate = await input();
expect(() =>
nativeWorkerRequestSchema.parse({
...candidate,
request: {
...candidate.request,
strategy: { ...candidate.request.strategy, origin: 'candidate' },
},
})
).toThrow();
const owners = await input();
owners.request.policy.matching.risk.ledger.ownerIds.push('second-owner');
await expect(execute(owners)).rejects.toThrow('single-asset');
});
test('factory identity, missing exports, thrown decisions and no-result exits fail closed', async () => {
for (const [source, reason] of [
['export const somethingElse = 1;', 'factory export is missing'],
['export function createSmaStrategy() { return {}; }', 'factory identity or API mismatch'],
[
'export function createSmaStrategy(selection) { selection.seed = 99; return {}; }',
'readonly',
],
['process.exit(0);', 'exited without a result'],
[
'export function createSmaStrategy() { throw new Error("bad retained factory"); }',
'bad retained factory',
],
[
'export function createSmaStrategy(selection) { return { ...selection, mode:"target", initialState:null, decide() { throw new Error("bad retained decision"); } }; }',
'bad retained decision',
],
]) {
const value = await input();
retainedSource(value.request, source!);
await expect(execute(value)).rejects.toThrow(reason!);
}
});
test('capture detaches all admitted inputs before the caller can mutate them', async () => {
const value = structuredClone(await input());
const captured = structuredClone(value.request);
const running = new NativeBacktestWorker().execute(
value,
new AbortController().signal,
() => {}
);
value.request.strategy.package.artifact.content = 'throw new Error("mutated");';
value.request.strategy.selection.seed = 222;
value.request.build.engineBinarySha256 = 'f'.repeat(64);
(value.dataset.bars as unknown[]).length = 0;
const result = parseRetainedStrategyResult(await running, captured);
expect(result.artifactHash).toBe(captured.strategy.package.artifact.sha256);
expect(result.financial.projection.fills.length).toBeGreaterThan(0);
});
test('result parser rejects false identity, policy and statistical claims', async () => {
const value = await input();
const { raw } = await execute(value);
for (const mutate of [
(result: ReturnType<typeof JSON.parse>) => {
result.type = 'strategyReplayResult';
},
(result: ReturnType<typeof JSON.parse>) => {
result.version = 2;
},
(result: ReturnType<typeof JSON.parse>) => {
result.artifactHash = 'f'.repeat(64);
},
(result: ReturnType<typeof JSON.parse>) => {
result.build.workerSha256 = 'f'.repeat(64);
},
(result: ReturnType<typeof JSON.parse>) => {
result.financial.identity.sessionId = 'wrong';
},
(result: ReturnType<typeof JSON.parse>) => {
result.financial.identity.datasetHash = 'f'.repeat(64);
},
(result: ReturnType<typeof JSON.parse>) => {
result.financial.policy.matching.risk.feeRate = '0';
},
(result: ReturnType<typeof JSON.parse>) => {
result.analytics.metrics.exposureTime = null;
},
(result: ReturnType<typeof JSON.parse>) => {
result.analytics.metrics.roundTripCount = 0;
},
(result: ReturnType<typeof JSON.parse>) => {
result.analytics.policy.periodsPerYear = 365;
},
]) {
const result = JSON.parse(raw);
mutate(result);
expect(() => parseRetainedStrategyResult(JSON.stringify(result), value.request)).toThrow();
}
});
test('alternate and source workers cannot claim the bundled worker identity', async () => {
const value = await input();
const sourceUrl = new URL(
'../../apps/stock/orchestrator/src/backtest/native-worker.ts',
import.meta.url
);
await expect(
new NativeBacktestWorker(sourceUrl).execute(value, new AbortController().signal, () => {})
).rejects.toThrow('canonical bundled worker');
expect(
await new NativeBacktestWorker(canonicalWorkerUrl).execute(
value,
new AbortController().signal,
() => {}
)
).toContain('retainedStrategyResult');
// Bypass the supervisor to test the source child's independent own-file check.
const messages = await new Promise<{ type: string; message?: string }[]>((resolve, reject) => {
const child = fork(fileURLToPath(sourceUrl), [], {
execPath: process.execPath,
execArgv: [],
serialization: 'json',
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
});
const received: { type: string; message?: string }[] = [];
const timer = setTimeout(() => {
child.kill('SIGKILL');
reject(new Error('Source worker timeout'));
}, 5000);
child.stderr?.resume();
child.on('message', message => received.push(message as { type: string; message?: string }));
child.on('error', reject);
child.on('close', () => {
clearTimeout(timer);
resolve(received);
});
child.send(value);
});
expect(messages).toEqual([
{
type: 'error',
message: 'Canonical research requires the bundled worker from this checkout',
},
]);
});
test('hard cancellation discards retained execution and the worker can be reused', async () => {
const value = await input();
const worker = new NativeBacktestWorker();
const abort = new AbortController();
await expect(
worker.execute(value, abort.signal, () => abort.abort(new Error('cancel retained replay')))
).rejects.toThrow('cancel retained replay');
expect(
JSON.parse(await worker.execute(value, new AbortController().signal, () => {})).type
).toBe('retainedStrategyResult');
});
});

View file

@ -953,7 +953,7 @@ describe('strategy workbench', () => {
await flush(() => {
void latest.createRun(null);
});
expect(latest.submissionError).toContain('save-only');
expect(latest.submissionError).toContain('configure a supported canonical dataset');
expect(requests.some(item => item.method === 'POST')).toBe(false);
let cancelled = false;
await flush(() =>