204 lines
7.3 KiB
TypeScript
204 lines
7.3 KiB
TypeScript
import { fork, type ChildProcess } from 'node:child_process';
|
|
import { realpathSync } from 'node:fs';
|
|
import { fileURLToPath } from 'node:url';
|
|
import {
|
|
parseReplayProjectionResult,
|
|
parseReplayReportResult,
|
|
parseReplayResult,
|
|
replayConfigSchema,
|
|
replayIdentitySchema,
|
|
replayResultFormatSchema,
|
|
} from '../contracts/native-replay';
|
|
import {
|
|
parseStrategyReplayResult,
|
|
strategyReplayRequestSchema,
|
|
} from '../contracts/strategy-replay';
|
|
import { canonicalWorkerUrl } from './canonical-build';
|
|
import {
|
|
nativeWorkerMessageSchema,
|
|
parseRetainedStrategyResult,
|
|
retainedStrategyRequestSchema,
|
|
type NativeWorkerRequest,
|
|
} from './native-worker-protocol';
|
|
import { BacktestConflictError } from './run-repository';
|
|
|
|
/** Hard cancellation requires a process boundary: a thread cannot interrupt native Rust. */
|
|
export class NativeBacktestWorker {
|
|
private active: ChildProcess | undefined;
|
|
|
|
constructor(private readonly workerUrl?: URL) {}
|
|
|
|
async execute(
|
|
request: NativeWorkerRequest,
|
|
signal: AbortSignal,
|
|
onProgress: (progress: { progress: number; message: string }) => void
|
|
): Promise<string> {
|
|
signal.throwIfAborted();
|
|
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 retainedRequest =
|
|
request.type === 'runRetainedStrategy'
|
|
? structuredClone(retainedStrategyRequestSchema.parse(request))
|
|
: undefined;
|
|
const strategyRequest =
|
|
request.type === 'runStrategyReplay'
|
|
? structuredClone(strategyReplayRequestSchema.parse(request))
|
|
: undefined;
|
|
const submitted = retainedRequest ?? strategyRequest ?? request;
|
|
if (
|
|
retainedRequest &&
|
|
this.workerUrl &&
|
|
realpathSync(fileURLToPath(this.workerUrl)) !==
|
|
realpathSync(fileURLToPath(canonicalWorkerUrl))
|
|
) {
|
|
throw new Error('Retained strategy execution requires the canonical bundled worker');
|
|
}
|
|
const workerUrl = retainedRequest
|
|
? canonicalWorkerUrl
|
|
: (this.workerUrl ??
|
|
new URL(
|
|
import.meta.url.endsWith('.ts') ? './native-worker.ts' : './native-worker.js',
|
|
import.meta.url
|
|
));
|
|
// Capture expected identity/policy before asynchronous execution. A caller
|
|
// mutating its request cannot change which completed child result is valid.
|
|
const expectedReplay =
|
|
submitted.type === 'runReplayTrace' || submitted.type === 'runStrategyReplay'
|
|
? {
|
|
identity: replayIdentitySchema.parse({
|
|
version: 1,
|
|
sessionId: submitted.config.matching.risk.ledger.sessionId,
|
|
datasetHash: (submitted.dataset as { manifest?: { hash?: unknown } })?.manifest?.hash,
|
|
}),
|
|
policy: replayConfigSchema.parse(submitted.config),
|
|
format: replayResultFormatSchema.parse(submitted.resultFormat ?? 'trace'),
|
|
}
|
|
: undefined;
|
|
const child = fork(fileURLToPath(workerUrl), [], {
|
|
execPath: process.execPath,
|
|
execArgv: [],
|
|
serialization: 'json',
|
|
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
|
|
});
|
|
this.active = child;
|
|
return new Promise<string>((resolve, reject) => {
|
|
let result: string | undefined;
|
|
let failure: Error | undefined;
|
|
let stderr = '';
|
|
let settled = false;
|
|
const terminate = (error: Error) => {
|
|
failure ??= error;
|
|
// SIGKILL also interrupts an uncooperative synchronous native call.
|
|
child.kill('SIGKILL');
|
|
};
|
|
const onAbort = () =>
|
|
terminate(
|
|
signal.reason instanceof Error ? signal.reason : new Error('Native execution aborted')
|
|
);
|
|
const onStderr = (chunk: Buffer) => {
|
|
// Drain native diagnostics without unbounded buffering or blocking on a full pipe.
|
|
stderr = (stderr + chunk.toString()).slice(-4096);
|
|
};
|
|
const onMessage = (input: unknown) => {
|
|
if (failure) {
|
|
return;
|
|
}
|
|
const parsed = nativeWorkerMessageSchema.safeParse(input);
|
|
if (!parsed.success || result !== undefined) {
|
|
terminate(new Error('Invalid native backtest worker response'));
|
|
return;
|
|
}
|
|
const message = parsed.data;
|
|
if (message.type === 'error') {
|
|
terminate(new Error(message.message));
|
|
} else if (message.type === 'result') {
|
|
if (retainedRequest) {
|
|
try {
|
|
parseRetainedStrategyResult(message.result, retainedRequest.request);
|
|
} catch (error) {
|
|
terminate(error instanceof Error ? error : new Error(String(error)));
|
|
return;
|
|
}
|
|
}
|
|
if (expectedReplay) {
|
|
try {
|
|
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;
|
|
}
|
|
}
|
|
result = message.result;
|
|
} else {
|
|
try {
|
|
onProgress({ progress: message.progress, message: message.message });
|
|
} catch (error) {
|
|
terminate(error instanceof Error ? error : new Error(String(error)));
|
|
}
|
|
}
|
|
};
|
|
const finish = (code: number | null, exitSignal: NodeJS.Signals | null) => {
|
|
if (settled) {
|
|
return;
|
|
}
|
|
settled = true;
|
|
signal.removeEventListener('abort', onAbort);
|
|
child.off('message', onMessage);
|
|
child.stderr?.off('data', onStderr);
|
|
this.active = undefined;
|
|
if (failure) {
|
|
reject(failure);
|
|
} else if (code !== 0 || result === undefined) {
|
|
reject(
|
|
new Error(
|
|
`Native backtest worker exited without a result (code ${code}, signal ${exitSignal})${stderr ? `: ${stderr}` : ''}`
|
|
)
|
|
);
|
|
} else {
|
|
resolve(result);
|
|
}
|
|
};
|
|
child.on('message', onMessage);
|
|
child.stderr?.on('data', onStderr);
|
|
child.once('error', error => {
|
|
terminate(error);
|
|
// Spawn failures have no process to reap; normal errors wait for exit.
|
|
if (child.pid === undefined) {
|
|
finish(null, null);
|
|
}
|
|
});
|
|
// Wait for IPC/stdio to drain too; exit alone can precede the last message.
|
|
child.once('close', finish);
|
|
signal.addEventListener('abort', onAbort, { once: true });
|
|
if (signal.aborted) {
|
|
onAbort();
|
|
return;
|
|
}
|
|
try {
|
|
child.send(submitted, error => {
|
|
if (error) {
|
|
terminate(error);
|
|
}
|
|
});
|
|
} catch (error) {
|
|
terminate(error instanceof Error ? error : new Error(String(error)));
|
|
}
|
|
});
|
|
}
|
|
}
|