stock-bot/apps/stock/orchestrator/src/backtest/BacktestRunner.ts

460 lines
15 KiB
TypeScript

import { EventEmitter } from 'node:events';
import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
isCanonicalRunResult,
type CanonicalRunRequest,
type CanonicalRunResult,
type ResearchRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
import { prepareDataset } from '../data/historical-dataset';
import type { BacktestConfig } from '../types';
import { BacktestCancelledError, type BacktestExecutionEngine } from './execution-engine';
import { normalizeBacktestResult } from './result';
import {
BacktestConflictError,
BacktestLeaseLostError,
type BacktestRunRepository,
type CanonicalRunClaim,
type RunClaim,
} from './run-repository';
export { parseBacktestRequest };
type DurableRequest = BacktestConfig | CanonicalRunRequest;
function isCanonicalRequest(value: DurableRequest): value is CanonicalRunRequest {
return 'kind' in value && value.kind === 'canonical-research/v1';
}
function parseDurableRequest(input: unknown): DurableRequest {
return input && typeof input === 'object' && 'kind' in input
? canonicalRunRequestSchema.parse(input)
: parseBacktestRequest(input);
}
/** One application workflow for HTTP, jobs, and both execution backends. */
export class BacktestRunner extends EventEmitter {
private busy = false;
private active: RunClaim | CanonicalRunClaim | undefined;
private leaseFailure: BacktestLeaseLostError | undefined;
private cancelled = false;
private progressWrites: Promise<void> = Promise.resolve();
private closing = false;
private phase: 'preparing' | 'executing' | 'persisting' = 'preparing';
private execution: Promise<ResearchRunResult> | undefined;
constructor(
private readonly dependencies: {
engine: BacktestExecutionEngine;
engineName: Exclude<BacktestRunResult['engine'], 'legacy'>;
repository: BacktestRunRepository;
logger: Pick<Logger, 'error'>;
heartbeatMs?: number;
heartbeatTimeoutMs?: number;
prepare?: (config: BacktestConfig) => Promise<void>;
}
) {
super();
}
async runBacktest(input: unknown): Promise<BacktestRunResult> {
return this.begin(parseBacktestRequest(input));
}
private begin(config: BacktestConfig): Promise<BacktestRunResult>;
private begin(config: CanonicalRunRequest): Promise<CanonicalRunResult>;
private begin(config: DurableRequest): Promise<ResearchRunResult>;
private begin(config: DurableRequest): Promise<ResearchRunResult> {
if (this.closing) {
throw new BacktestConflictError('Backtest runner is shutting down');
}
if (this.busy) {
throw new BacktestConflictError('A backtest is already running');
}
this.busy = true;
this.cancelled = false;
this.leaseFailure = undefined;
this.phase = 'preparing';
this.execution = this.execute(config);
return this.execution;
}
/** Queue redelivery is an acknowledgement for terminal runs, never a second execution. */
async runQueued(runId: string) {
const run = await this.dependencies.repository.load(runId);
if (!run) {
return { runId, status: 'missing' };
}
if (['completed', 'cancelled', 'failed'].includes(run.status)) {
return { runId, status: run.status };
}
let snapshot: DurableRequest;
try {
snapshot = parseDurableRequest(run.config);
if (isCanonicalRequest(snapshot) && snapshot.runId !== runId) {
throw new Error('Canonical queued run identity mismatch');
}
} catch (error) {
await this.dependencies.repository.rejectPending(
runId,
'Invalid persisted execution configuration'
);
throw error;
}
const result = await this.begin({ ...snapshot, runId });
return { runId, status: result.status };
}
private async execute(config: DurableRequest): Promise<ResearchRunResult> {
const started = performance.now();
this.progressWrites = Promise.resolve();
let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
let heartbeatWork: Promise<void> | undefined;
const heartbeat = async () => {
const active = this.active;
if (!active) {
return;
}
let deadline: ReturnType<typeof setTimeout> | undefined;
try {
const state = await Promise.race([
this.dependencies.repository.heartbeat(active.runId, active.attemptId),
new Promise<never>((_resolve, reject) => {
deadline = setTimeout(
() => reject(new Error('Execution heartbeat timed out')),
this.dependencies.heartbeatTimeoutMs ?? 5_000
);
}),
]);
if (!state.cancelRequested) {
return;
}
this.cancelled = true;
} catch (error) {
this.leaseFailure = new BacktestLeaseLostError(
'Could not renew execution lease; abandoning attempt',
{ cause: error }
);
} finally {
if (deadline) {
clearTimeout(deadline);
}
}
if (this.phase === 'executing') {
try {
await this.dependencies.engine.stopBacktest();
} catch (error) {
this.dependencies.logger.error('Could not stop abandoned/cancelled execution', { error });
}
}
};
const onProgress = (data: unknown) => {
const active = this.active;
if (
!active ||
typeof data !== 'object' ||
data === null ||
!('progress' in data) ||
typeof data.progress !== 'number' ||
!Number.isFinite(data.progress)
) {
return;
}
const progress = Math.max(0, Math.min(100, data.progress));
const date =
'currentDate' in data &&
typeof data.currentDate === 'string' &&
Number.isFinite(Date.parse(data.currentDate))
? data.currentDate
: undefined;
this.progressWrites = this.progressWrites
.then(() =>
this.dependencies.repository.updateProgress(
active.runId,
progress,
date,
active.attemptId
)
)
.catch(error => {
this.dependencies.logger.error('Could not persist backtest progress', { error });
});
this.publish('progress', { ...data, progress, runId: active.runId });
};
this.dependencies.engine.on('progress', onProgress);
try {
if (isCanonicalRequest(config)) {
if (!this.dependencies.repository.startCanonical) {
throw new Error('Canonical run repository is unavailable');
}
this.active = await this.dependencies.repository.startCanonical(config);
} else {
this.active = await this.dependencies.repository.start(config);
}
const executionConfig = parseDurableRequest({
...this.active.config,
runId: this.active.runId,
backtestId: this.active.backtestId,
});
heartbeatTimer = setInterval(() => {
if (!heartbeatWork) {
heartbeatWork = heartbeat().finally(() => {
heartbeatWork = undefined;
});
}
}, this.dependencies.heartbeatMs ?? 5_000);
heartbeatTimer.unref();
await heartbeat();
if (this.leaseFailure) {
throw this.leaseFailure;
}
if (this.cancelled) {
throw new BacktestCancelledError();
}
if (!isCanonicalRequest(executionConfig)) {
await this.dependencies.prepare?.(executionConfig);
}
if (this.leaseFailure) {
throw this.leaseFailure;
}
if (this.cancelled) {
throw new BacktestCancelledError();
}
this.phase = 'executing';
let result: ResearchRunResult;
if (isCanonicalRequest(executionConfig)) {
const engine = this.dependencies.engine;
const repository = this.dependencies.repository;
const loadCanonicalDataset = repository.loadCanonicalDataset;
if (!engine.runCanonical || !loadCanonicalDataset || !repository.completeCanonical) {
throw new Error('Canonical execution capabilities are unavailable');
}
const claim = this.active;
const report = await engine.runCanonical(executionConfig, signal =>
loadCanonicalDataset.call(
repository,
claim.runId,
claim.attemptId,
executionConfig.datasetHash,
signal
)
);
if (this.cancelled) {
throw new BacktestCancelledError();
}
result = {
kind: 'canonical-result/v1',
runId: claim.runId,
backtestId: claim.backtestId,
status: 'completed',
completedAt: new Date().toISOString(),
executionTime: performance.now() - started,
financialEngine: 'rust',
strategyExecution: 'typescript-retained-builtin/v1',
request: executionConfig,
...report,
};
} else {
let manifest: HistoricalDatasetManifest | undefined;
const claim = this.active;
const raw = await this.dependencies.engine.runBacktest(
executionConfig,
async (load, signal) => {
signal?.throwIfAborted();
const saved = await this.dependencies.repository.loadDataset(
claim.runId,
claim.attemptId,
executionConfig.datasetHash,
signal
);
const dataset = await prepareDataset(saved ?? (await load()), executionConfig, signal);
signal?.throwIfAborted();
const frozen =
saved ??
(await this.dependencies.repository.freezeDataset(
claim.runId,
claim.attemptId,
dataset,
signal
));
signal?.throwIfAborted();
manifest = frozen.manifest;
return frozen;
}
);
if (!manifest) {
throw new Error('Backtest engine did not resolve frozen execution inputs');
}
if (this.leaseFailure) {
throw this.leaseFailure;
}
try {
result = normalizeBacktestResult(
raw,
this.dependencies.engineName,
executionConfig,
this.active,
performance.now() - started,
this.cancelled,
manifest
);
} catch (error) {
throw new Error('Backtest engine returned an invalid result', { cause: error });
}
}
this.phase = 'persisting';
await this.progressWrites;
if (this.leaseFailure) {
throw this.leaseFailure;
}
if (isCanonicalRunResult(result)) {
const completeCanonical = this.dependencies.repository.completeCanonical;
if (!completeCanonical) {
throw new Error('Canonical result persistence is unavailable');
}
await completeCanonical.call(this.dependencies.repository, result, this.active.attemptId);
} else {
await this.dependencies.repository.complete(result, this.active.attemptId);
}
// Observers cannot turn a committed success into a failed run.
this.publish('complete', result);
return result;
} catch (error) {
await this.progressWrites;
let failure = this.leaseFailure ?? error;
if (this.active && !(failure instanceof BacktestLeaseLostError)) {
try {
if (error instanceof BacktestCancelledError) {
await this.dependencies.repository.cancel(this.active.runId, this.active.attemptId);
} else {
await this.dependencies.repository.fail(
this.active.runId,
error instanceof Error ? error.message : String(error),
this.active.attemptId
);
}
} catch (persistenceError) {
this.dependencies.logger.error('Could not record backtest failure', { persistenceError });
// A cancellation acknowledgement must never conceal a failed status write.
if (error instanceof BacktestCancelledError) {
failure = persistenceError;
}
}
}
if (failure instanceof BacktestCancelledError) {
this.publish('cancelled', {
runId: this.active?.runId,
backtestId: this.active?.backtestId,
status: 'cancelled',
});
} else if (this.listenerCount('error')) {
this.publish('error', failure);
}
throw failure;
} finally {
if (heartbeatTimer) {
clearInterval(heartbeatTimer);
}
await heartbeatWork;
this.dependencies.engine.off('progress', onProgress);
this.active = undefined;
this.busy = false;
}
}
private publish(event: string, value: unknown) {
try {
this.emit(event, value);
} catch (error) {
this.dependencies.logger.error('Backtest observer failed', { event, error });
}
}
private requireActive(runId?: string) {
if (!this.active || (runId && this.active.runId !== runId)) {
throw new BacktestConflictError('No matching active backtest');
}
return this.active;
}
async stopBacktest(runId?: string) {
this.requireActive(runId);
if (this.phase === 'persisting') {
throw new BacktestConflictError('Backtest execution has already finished');
}
const execution = this.execution;
this.cancelled = true;
if (this.phase === 'executing') {
try {
await this.dependencies.engine.stopBacktest();
} catch (error) {
this.cancelled = false;
throw error;
}
}
try {
await execution;
} catch (error) {
if (!(error instanceof BacktestCancelledError)) {
throw error;
}
}
}
async shutdown(): Promise<void> {
this.closing = true;
const execution = this.busy ? this.execution : undefined;
if (this.busy && this.phase !== 'persisting') {
this.cancelled = true;
if (this.phase === 'executing') {
await this.dependencies.engine.stopBacktest();
}
}
// Allow the owner to commit cancellation/failure before database shutdown.
try {
await execution?.catch(error => {
if (!(error instanceof BacktestCancelledError)) {
throw error;
}
});
} finally {
await this.dependencies.engine.shutdown();
}
}
async pauseBacktest(runId?: string) {
const active = this.requireActive(runId);
await this.dependencies.engine.pauseBacktest();
await this.dependencies.repository.updateControl(
active.runId,
{ status: 'paused' },
active.attemptId
);
}
async resumeBacktest(runId?: string) {
const active = this.requireActive(runId);
await this.dependencies.engine.resumeBacktest();
await this.dependencies.repository.updateControl(
active.runId,
{ status: 'running' },
active.attemptId
);
}
async setSpeedMultiplier(speed: number | null, runId?: string) {
if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) {
throw new Error('Backtest speed must be positive or null');
}
const active = this.requireActive(runId);
this.dependencies.engine.setSpeedMultiplier(speed);
await this.dependencies.repository.updateControl(
active.runId,
{ speedMultiplier: speed },
active.attemptId
);
}
getStatus() {
return {
...this.dependencies.engine.getStatus(),
isRunning: this.busy,
runId: this.active?.runId,
};
}
}