feat(research): run retained strategies through durable canonical engine

This commit is contained in:
Boki 2026-10-23 21:59:09 -04:00
parent d929db707a
commit 618fb9e33c
58 changed files with 6596 additions and 779 deletions

View file

@ -1,6 +1,13 @@
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';
@ -10,21 +17,31 @@ 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 | undefined;
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<BacktestRunResult> | undefined;
private execution: Promise<ResearchRunResult> | undefined;
constructor(
private readonly dependencies: {
@ -41,7 +58,13 @@ export class BacktestRunner extends EventEmitter {
}
async runBacktest(input: unknown): Promise<BacktestRunResult> {
const config = parseBacktestRequest(input);
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');
}
@ -65,9 +88,12 @@ export class BacktestRunner extends EventEmitter {
if (['completed', 'cancelled', 'failed'].includes(run.status)) {
return { runId, status: run.status };
}
let snapshot: BacktestConfig;
let snapshot: DurableRequest;
try {
snapshot = parseBacktestRequest(run.config);
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,
@ -75,11 +101,11 @@ export class BacktestRunner extends EventEmitter {
);
throw error;
}
const result = await this.runBacktest({ ...snapshot, runId });
const result = await this.begin({ ...snapshot, runId });
return { runId, status: result.status };
}
private async execute(config: BacktestConfig): Promise<BacktestRunResult> {
private async execute(config: DurableRequest): Promise<ResearchRunResult> {
const started = performance.now();
this.progressWrites = Promise.resolve();
let heartbeatTimer: ReturnType<typeof setInterval> | undefined;
@ -157,8 +183,15 @@ export class BacktestRunner extends EventEmitter {
};
this.dependencies.engine.on('progress', onProgress);
try {
this.active = await this.dependencies.repository.start(config);
const executionConfig = parseBacktestRequest({
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,
@ -178,7 +211,9 @@ export class BacktestRunner extends EventEmitter {
if (this.cancelled) {
throw new BacktestCancelledError();
}
await this.dependencies.prepare?.(executionConfig);
if (!isCanonicalRequest(executionConfig)) {
await this.dependencies.prepare?.(executionConfig);
}
if (this.leaseFailure) {
throw this.leaseFailure;
}
@ -186,59 +221,101 @@ export class BacktestRunner extends EventEmitter {
throw new BacktestCancelledError();
}
this.phase = 'executing';
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(
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
);
const dataset = await prepareDataset(saved ?? (await load()), executionConfig, signal);
signal?.throwIfAborted();
const frozen =
saved ??
(await this.dependencies.repository.freezeDataset(
)
);
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,
dataset,
executionConfig.datasetHash,
signal
));
signal?.throwIfAborted();
manifest = frozen.manifest;
return frozen;
);
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 });
}
);
if (!manifest) {
throw new Error('Backtest engine did not resolve frozen execution inputs');
}
if (this.leaseFailure) {
throw this.leaseFailure;
}
this.phase = 'persisting';
let result: BacktestRunResult;
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 });
}
await this.progressWrites;
if (this.leaseFailure) {
throw this.leaseFailure;
}
await this.dependencies.repository.complete(result, this.active.attemptId);
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;