148 lines
5.7 KiB
TypeScript
148 lines
5.7 KiB
TypeScript
import type { StrategyReplayResult } from '../contracts/strategy-replay';
|
|
import {
|
|
createBuiltinStrategy,
|
|
validateBuiltinStrategyBindings,
|
|
} from '../strategies/canonical-builtins';
|
|
import {
|
|
importRetainedProgram,
|
|
verifyRetainedProgramPackage,
|
|
} from '../strategies/retained-program';
|
|
import { IsolatedCandidateController } from './candidate-sandbox';
|
|
import { verifyCanonicalWorkerBuild } from './canonical-build';
|
|
import { buildCanonicalBacktestReport } from './canonical-result';
|
|
import {
|
|
executeReplayTrace,
|
|
NativeReplaySession,
|
|
prepareReplayLoad,
|
|
runReplaySessionAsync,
|
|
} from './native-replay';
|
|
import {
|
|
nativeWorkerRequestSchema,
|
|
type NativeWorkerMessage,
|
|
type RetainedStrategyResult,
|
|
} from './native-worker-protocol';
|
|
import { runStrategyReplay } from './strategy-runtime';
|
|
|
|
/** One process, one native engine, one request. No database or service-container access. */
|
|
function send(message: NativeWorkerMessage): Promise<void> {
|
|
return new Promise((resolve, reject) => {
|
|
if (!process.send) {
|
|
reject(new Error('Native backtest worker requires an IPC channel'));
|
|
return;
|
|
}
|
|
process.send(message, (error: Error | null) => (error ? reject(error) : resolve()));
|
|
});
|
|
}
|
|
|
|
process.once('message', async (input: unknown) => {
|
|
try {
|
|
const request = nativeWorkerRequestSchema.parse(input);
|
|
if (request.type === 'runRetainedStrategy') {
|
|
const admitted = request.request;
|
|
// Identity checks precede bundle import, including any top-level module side effects.
|
|
const build = await verifyCanonicalWorkerBuild(admitted.build, import.meta.url);
|
|
const pkg = verifyRetainedProgramPackage(admitted.strategy.package);
|
|
const load = prepareReplayLoad(request.dataset, admitted.policy);
|
|
if (
|
|
load.identity.datasetHash !== admitted.datasetHash ||
|
|
load.manifest.eligibility !== 'eligible' ||
|
|
load.manifest.series.length !== 1
|
|
) {
|
|
throw new Error('Retained strategy requires its exact eligible single-series dataset');
|
|
}
|
|
await send({
|
|
type: 'progress',
|
|
progress: 0,
|
|
message: 'Retained canonical strategy replay started',
|
|
});
|
|
let result;
|
|
if (admitted.strategy.origin === 'candidate') {
|
|
if (!request.candidateContainerName) {
|
|
throw new Error('Isolated candidate lacks its owned container identity');
|
|
}
|
|
const controller = await IsolatedCandidateController.start(
|
|
admitted,
|
|
request.candidateContainerName,
|
|
request.executionDeadlineAt
|
|
);
|
|
try {
|
|
result = (
|
|
await runReplaySessionAsync(new NativeReplaySession(load), controller, {
|
|
resultFormat: 'report',
|
|
})
|
|
).result;
|
|
await controller.finish();
|
|
} finally {
|
|
await controller.dispose();
|
|
}
|
|
} else {
|
|
validateBuiltinStrategyBindings([admitted.strategy.selection], load);
|
|
const program = await importRetainedProgram(pkg, admitted.strategy.selection);
|
|
result = runStrategyReplay(load, [program], { resultFormat: 'report' }).result;
|
|
}
|
|
if (!('format' in result) || result.format !== 'report') {
|
|
throw new Error('Retained replay requires the canonical report format');
|
|
}
|
|
const report = buildCanonicalBacktestReport(result, admitted.analyticsPolicy);
|
|
const envelope: RetainedStrategyResult = {
|
|
type: 'retainedStrategyResult',
|
|
version: 1,
|
|
build,
|
|
artifactHash: pkg.artifact.sha256,
|
|
...(admitted.strategy.origin === 'candidate'
|
|
? { execution: admitted.strategy.execution }
|
|
: {}),
|
|
financial: report.financial,
|
|
analytics: report.analytics,
|
|
};
|
|
await send({ type: 'result', result: JSON.stringify(envelope) });
|
|
return;
|
|
}
|
|
if (request.type === 'runStrategyReplay') {
|
|
const load = prepareReplayLoad(request.dataset, request.config);
|
|
validateBuiltinStrategyBindings(request.strategies, load);
|
|
const programs = request.strategies.map(selection => {
|
|
const program = createBuiltinStrategy(selection);
|
|
if (
|
|
program.ownerId !== selection.ownerId ||
|
|
program.strategyId !== selection.strategyId ||
|
|
program.strategyVersion !== selection.strategyVersion ||
|
|
program.seed !== selection.seed ||
|
|
program.mode !== 'target'
|
|
) {
|
|
throw new Error('Trusted strategy constructor identity mismatch');
|
|
}
|
|
return program;
|
|
});
|
|
await send({ type: 'progress', progress: 0, message: 'Canonical strategy replay started' });
|
|
const { result } = runStrategyReplay(load, programs, {
|
|
eventBudget: request.eventBudget,
|
|
resultFormat: request.resultFormat,
|
|
});
|
|
const envelope: StrategyReplayResult = {
|
|
type: 'strategyReplayResult',
|
|
version: 1,
|
|
strategies: request.strategies,
|
|
result,
|
|
};
|
|
await send({ type: 'result', result: JSON.stringify(envelope) });
|
|
return;
|
|
}
|
|
if (request.type === 'runReplayTrace') {
|
|
await send({ type: 'progress', progress: 0, message: 'Canonical replay trace started' });
|
|
// One load and a local pull loop; no per-observation IPC. The supervisor
|
|
// can still SIGKILL native work, without changing financial execution semantics.
|
|
const { result } = executeReplayTrace(request);
|
|
await send({ type: 'result', result: JSON.stringify(result) });
|
|
return;
|
|
}
|
|
} catch (error) {
|
|
await send({ type: 'error', message: error instanceof Error ? error.message : String(error) });
|
|
process.exitCode = 1;
|
|
} finally {
|
|
process.disconnect?.();
|
|
}
|
|
});
|
|
|
|
// Exit on parent disconnection once control returns from native code.
|
|
process.once('disconnect', () => process.exit(process.exitCode ?? 0));
|