feat(research): run trusted SMA strategies through native workers
This commit is contained in:
parent
4f6e44a853
commit
ca5abdde0e
16 changed files with 1682 additions and 28 deletions
|
|
@ -8,6 +8,10 @@ import {
|
|||
replayIdentitySchema,
|
||||
replayResultFormatSchema,
|
||||
} from '../contracts/native-replay';
|
||||
import {
|
||||
parseStrategyReplayResult,
|
||||
strategyReplayRequestSchema,
|
||||
} from '../contracts/strategy-replay';
|
||||
import { nativeWorkerMessageSchema, type NativeWorkerRequest } from './native-worker-protocol';
|
||||
import { BacktestConflictError } from './run-repository';
|
||||
|
||||
|
|
@ -31,18 +35,25 @@ export class NativeBacktestWorker {
|
|||
if (this.active) {
|
||||
throw new BacktestConflictError('A native backtest worker is already running');
|
||||
}
|
||||
// Detach the entire normalized strategy request, including the frozen-data
|
||||
// payload. The caller must not mutate what is sent or what counts as success.
|
||||
const strategyRequest =
|
||||
request.type === 'runStrategyReplay'
|
||||
? structuredClone(strategyReplayRequestSchema.parse(request))
|
||||
: undefined;
|
||||
const submitted = strategyRequest ?? request;
|
||||
// Capture expected identity/policy before asynchronous execution. A caller
|
||||
// mutating its request cannot change which completed child result is valid.
|
||||
const expectedReplay =
|
||||
request.type === 'runReplayTrace'
|
||||
submitted.type === 'runReplayTrace' || submitted.type === 'runStrategyReplay'
|
||||
? {
|
||||
identity: replayIdentitySchema.parse({
|
||||
version: 1,
|
||||
sessionId: request.config.matching.risk.ledger.sessionId,
|
||||
datasetHash: (request.dataset as { manifest?: { hash?: unknown } })?.manifest?.hash,
|
||||
sessionId: submitted.config.matching.risk.ledger.sessionId,
|
||||
datasetHash: (submitted.dataset as { manifest?: { hash?: unknown } })?.manifest?.hash,
|
||||
}),
|
||||
policy: replayConfigSchema.parse(request.config),
|
||||
format: replayResultFormatSchema.parse(request.resultFormat ?? 'trace'),
|
||||
policy: replayConfigSchema.parse(submitted.config),
|
||||
format: replayResultFormatSchema.parse(submitted.resultFormat ?? 'trace'),
|
||||
}
|
||||
: undefined;
|
||||
const child = fork(fileURLToPath(this.workerUrl), [], {
|
||||
|
|
@ -85,13 +96,20 @@ export class NativeBacktestWorker {
|
|||
} else if (message.type === 'result') {
|
||||
if (expectedReplay) {
|
||||
try {
|
||||
const parse =
|
||||
expectedReplay.format === 'report'
|
||||
? parseReplayReportResult
|
||||
: expectedReplay.format === 'projection'
|
||||
? parseReplayProjectionResult
|
||||
: parseReplayResult;
|
||||
parse(message.result, expectedReplay.identity, expectedReplay.policy);
|
||||
if (strategyRequest) {
|
||||
parseStrategyReplayResult(message.result, {
|
||||
...expectedReplay,
|
||||
strategies: strategyRequest.strategies,
|
||||
});
|
||||
} else {
|
||||
const parse =
|
||||
expectedReplay.format === 'report'
|
||||
? parseReplayReportResult
|
||||
: expectedReplay.format === 'projection'
|
||||
? parseReplayProjectionResult
|
||||
: parseReplayResult;
|
||||
parse(message.result, expectedReplay.identity, expectedReplay.policy);
|
||||
}
|
||||
} catch (error) {
|
||||
terminate(error instanceof Error ? error : new Error(String(error)));
|
||||
return;
|
||||
|
|
@ -144,7 +162,7 @@ export class NativeBacktestWorker {
|
|||
return;
|
||||
}
|
||||
try {
|
||||
child.send(request, error => {
|
||||
child.send(submitted, error => {
|
||||
if (error) {
|
||||
terminate(error);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { z } from 'zod';
|
||||
import { replayTraceSchema } from '../contracts/native-replay';
|
||||
import { strategyReplayRequestSchema } from '../contracts/strategy-replay';
|
||||
import { BacktestConfigSchema } from '../types';
|
||||
|
||||
const finite = z.number().finite();
|
||||
|
|
@ -21,7 +22,11 @@ const legacyRequestSchema = z.object({
|
|||
),
|
||||
});
|
||||
|
||||
export const nativeWorkerRequestSchema = z.union([legacyRequestSchema, replayTraceSchema]);
|
||||
export const nativeWorkerRequestSchema = z.union([
|
||||
legacyRequestSchema,
|
||||
replayTraceSchema,
|
||||
strategyReplayRequestSchema,
|
||||
]);
|
||||
|
||||
export const nativeWorkerMessageSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('progress'), progress: finite.min(0).max(100), message: z.string() }),
|
||||
|
|
@ -29,5 +34,5 @@ export const nativeWorkerMessageSchema = z.discriminatedUnion('type', [
|
|||
z.object({ type: z.literal('error'), message: z.string() }),
|
||||
]);
|
||||
|
||||
export type NativeWorkerRequest = z.infer<typeof nativeWorkerRequestSchema>;
|
||||
export type NativeWorkerRequest = z.input<typeof nativeWorkerRequestSchema>;
|
||||
export type NativeWorkerMessage = z.infer<typeof nativeWorkerMessageSchema>;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,13 @@
|
|||
import { BacktestEngine } from '@stock-bot/engine';
|
||||
import { executeReplayTrace } from './native-replay';
|
||||
import type { StrategyReplayResult } from '../contracts/strategy-replay';
|
||||
import {
|
||||
createBuiltinStrategy,
|
||||
validateBuiltinStrategyBindings,
|
||||
} from '../strategies/canonical-sma';
|
||||
import { executeReplayTrace, prepareReplayLoad } from './native-replay';
|
||||
import { resolveNativeStrategies } from './native-strategies';
|
||||
import { nativeWorkerRequestSchema, type NativeWorkerMessage } 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> {
|
||||
|
|
@ -17,6 +23,36 @@ function send(message: NativeWorkerMessage): Promise<void> {
|
|||
process.once('message', async (input: unknown) => {
|
||||
try {
|
||||
const request = nativeWorkerRequestSchema.parse(input);
|
||||
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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue