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

479 lines
17 KiB
TypeScript

/**
* Supervises one durable research attempt: SQL claim -> engine replay -> SQL result.
* The engine owns financial execution; this class owns attempt lifetime and reporting.
* ResearchBacktestPool supplies a separate runner/engine per concurrent trial, so these
* mutable fields never represent a shared paper account or several simultaneous runs.
*/
import { EventEmitter } from 'node:events';
import { redactLogValue } from '@stock-bot/logger';
import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import {
canonicalRunRequestSchema,
canonicalStrategyExecution,
type CanonicalRunRequest,
type CanonicalRunResult,
} from '@stock-bot/stock-config/canonical-research';
import type { BacktestRunResult } from '@stock-bot/types';
import type { BacktestConfig } from '../types';
import {
BacktestCancelledError,
LEGACY_EXECUTION_RETIRED,
type BacktestExecutionEngine,
} from './execution-engine';
import {
BacktestConflictError,
BacktestLeaseLostError,
type BacktestRunRepository,
type CanonicalRunClaim,
} 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);
}
/**
* Executes only requests already admitted to the durable run store. A run ID identifies
* the experiment trial; its attempt ID identifies the worker currently allowed to write.
* A recovered attempt replays the original inputs from the beginning. Creating a new
* reproduction run is an API operation, outside this supervisor.
*/
export class BacktestRunner extends EventEmitter {
private busy = false;
private active: 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<CanonicalRunResult> | undefined;
constructor(
private readonly dependencies: {
engine: BacktestExecutionEngine;
repository: BacktestRunRepository;
logger: Pick<Logger, 'error'>;
heartbeatMs?: number;
heartbeatTimeoutMs?: number;
}
) {
super();
}
/** Retained only to diagnose obsolete callers; canonical work requires durable admission. */
async runBacktest(input: unknown): Promise<BacktestRunResult> {
parseBacktestRequest(input);
throw new BacktestConflictError(LEGACY_EXECUTION_RETIRED);
}
/** Reserve this in-process slot before execute() reaches its first database await. */
private begin(config: CanonicalRunRequest): Promise<CanonicalRunResult> {
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;
}
/**
* Resolve queue identity into the saved request; a message never supplies executable
* configuration. Terminal redelivery only acknowledges status. The repository claim,
* not this preliminary read, arbitrates competing workers for a pending run.
*/
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;
}
if (!isCanonicalRequest(snapshot)) {
await this.dependencies.repository.rejectPending(runId, LEGACY_EXECUTION_RETIRED);
const retired = await this.dependencies.repository.load(runId);
return { runId, status: retired?.status ?? 'missing' };
}
const result = await this.begin(snapshot);
return { runId, status: result.status };
}
/**
* Keep a lease while preparing/executing/persisting, and finish only under that lease.
* Any uncertainty about renewal stops execution without writing a terminal state;
* the dispatcher later recovers expired attempts under its retry/deadline policy.
*/
private async execute(config: CanonicalRunRequest): Promise<CanonicalRunResult> {
const started = performance.now();
this.progressWrites = Promise.resolve();
let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
let heartbeatWork: Promise<void> | undefined;
let executionDeadline: ReturnType<typeof setTimeout> | undefined;
let deadlineFailure: Error | undefined;
let deadlineStop: Promise<void> | undefined;
// This wall-clock budget limits research work; it is not the historical replay clock.
const checkDeadline = () => {
const deadline = this.active?.executionDeadlineAt;
if (deadline !== undefined && Date.now() >= deadline) {
deadlineFailure ??= new Error('Research attempt exceeded its admitted execution deadline');
}
if (deadlineFailure) {
throw deadlineFailure;
}
};
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;
// Serialize event-driven writes and capture this attempt's identity. Completion
// drains the chain so a delayed progress write cannot follow the terminal commit.
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 {
this.active = await this.dependencies.repository.startCanonical(config);
if (
this.active.executionDeadlineAt !== undefined &&
(!Number.isSafeInteger(this.active.executionDeadlineAt) ||
this.active.executionDeadlineAt - Date.now() > 2_147_483_647)
) {
throw new Error('Invalid admitted research execution deadline');
}
checkDeadline();
if (this.active.executionDeadlineAt !== undefined) {
executionDeadline = setTimeout(
() => {
deadlineFailure = new Error(
'Research attempt exceeded its admitted execution deadline'
);
if (this.phase === 'executing') {
deadlineStop = this.dependencies.engine.stopBacktest().catch(error => {
this.dependencies.logger.error('Could not stop expired research attempt', {
error,
});
});
}
},
Math.max(0, this.active.executionDeadlineAt - Date.now())
);
executionDeadline.unref();
}
// Execute the repository's claimed snapshot, never a newly edited template.
const executionConfig = canonicalRunRequestSchema.parse(this.active.config);
if (
executionConfig.runId !== this.active.runId ||
executionConfig.backtestId !== this.active.backtestId
) {
throw new Error('Canonical claim identity mismatch');
}
// Do not pile up periodic renewals when SQL is slow. Keep the pending renewal
// available to finally so it cannot leak into this runner's next attempt.
heartbeatTimer = setInterval(() => {
if (!heartbeatWork) {
heartbeatWork = heartbeat().finally(() => {
heartbeatWork = undefined;
});
}
}, this.dependencies.heartbeatMs ?? 5_000);
heartbeatTimer.unref();
await heartbeat();
checkDeadline();
if (this.leaseFailure) {
throw this.leaseFailure;
}
if (this.cancelled) {
throw new BacktestCancelledError();
}
this.phase = 'executing';
let result: CanonicalRunResult;
{
const engine = this.dependencies.engine;
const repository = this.dependencies.repository;
const claim = this.active;
// Resolve retained data through the owning attempt. The adapter supplies its
// abort signal; neither this callback nor the worker fetches fresh provider bars.
const report = await engine.runCanonical(
executionConfig,
signal =>
repository.loadCanonicalDataset(
claim.runId,
claim.attemptId,
executionConfig.datasetHash,
signal
),
{ executionDeadlineAt: claim.executionDeadlineAt }
);
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: canonicalStrategyExecution(executionConfig),
request: executionConfig,
...report,
};
}
checkDeadline();
this.phase = 'persisting';
await this.progressWrites;
if (this.leaseFailure) {
throw this.leaseFailure;
}
checkDeadline();
await this.dependencies.repository.completeCanonical(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 ?? deadlineFailure ?? error;
const publicFailure = () =>
new Error(
`Backtest failed during ${this.phase}: ${redactLogValue(failure instanceof Error ? failure.message : String(failure))}`
);
// After lease loss, another worker may own the run. Even a failure/cancellation
// write would be an unauthorized state change, so leave recovery to the store.
if (this.active && !(failure instanceof BacktestLeaseLostError)) {
try {
if (failure instanceof BacktestCancelledError) {
await this.dependencies.repository.cancel(this.active.runId, this.active.attemptId);
} else {
await this.dependencies.repository.fail(
this.active.runId,
publicFailure().message,
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 (failure 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', publicFailure());
}
throw failure;
} finally {
if (executionDeadline) {
clearTimeout(executionDeadline);
}
await deadlineStop;
if (heartbeatTimer) {
clearInterval(heartbeatTimer);
}
await heartbeatWork;
this.dependencies.engine.off('progress', onProgress);
this.active = undefined;
this.busy = false;
}
}
/** Observer failures are diagnostics; they must not alter the execution outcome. */
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;
}
/**
* Stop the locally owned attempt and wait for its cancellation write. Remote API
* cancellation is observed separately through heartbeat's SQL cancel_requested flag.
* Once persistence starts, local stop refuses rather than racing a completed result.
*/
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;
}
}
}
/**
* Refuse new work, cancel unfinished execution, and let an in-progress result commit
* finish before closing the engine. Call while the run repository is still available.
*/
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();
}
}
/** Retained control routes reject playback operations without mutating durable state. */
async pauseBacktest(runId?: string): Promise<void> {
this.requireActive(runId);
throw new Error('Native backtests do not support pause');
}
async resumeBacktest(runId?: string): Promise<void> {
this.requireActive(runId);
throw new Error('Native backtests do not support resume');
}
async setSpeedMultiplier(speed: number | null, runId?: string): Promise<void> {
if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) {
throw new Error('Backtest speed must be positive or null');
}
this.requireActive(runId);
throw new Error('Native backtests run at maximum speed');
}
/** A local attempt snapshot; PostgreSQL remains authoritative for leases. */
getAttemptDiagnostics() {
return {
runId: this.active?.runId ?? null,
backtestId: this.active?.backtestId ?? null,
attemptId: this.active?.attemptId ?? null,
strategyVersionId: this.active?.config.strategy.versionId ?? null,
phase: this.busy ? this.phase : ('idle' as const),
};
}
/** Local worker projection; persisted run status remains authoritative after restart. */
getStatus() {
return {
...this.dependencies.engine.getStatus(),
isRunning: this.busy,
runId: this.active?.runId,
};
}
}