refactor(orchestrator): require canonical research contracts (CL14)

This commit is contained in:
Boki 2026-10-26 19:22:01 -04:00
parent bc2b8a89da
commit 21666242f4
37 changed files with 151 additions and 319 deletions

View file

@ -14,7 +14,7 @@ import type { BacktestConfig } from '../types';
import { BacktestMarket } from './BacktestMarket';
import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback';
import { BacktestReport } from './BacktestReport';
import type { BacktestExecutionEngine } from './execution-engine';
import type { LegacyBacktestExecutionEngine } from './execution-engine';
import { closedTradesSchema } from './native-result';
import { backtestStrategies } from './strategy-plan';
import type { BacktestResult } from './typescript-result';
@ -23,7 +23,7 @@ export type { BacktestResult } from './typescript-result';
const speeds = { max: null, realtime: 1, '2x': 2, '5x': 5, '10x': 10 } as const;
/** Composes one run's playback, market projection and report. The runner owns durable lifecycle. */
export class BacktestEngine extends EventEmitter implements BacktestExecutionEngine {
export class BacktestEngine extends EventEmitter implements LegacyBacktestExecutionEngine {
private playback?: BacktestPlayback;
private active?: Promise<BacktestResult>;
private completedReport?: BacktestReport;

View file

@ -57,7 +57,6 @@ export class BacktestRunner extends EventEmitter {
constructor(
private readonly dependencies: {
engine: BacktestExecutionEngine;
engineName: Exclude<BacktestRunResult['engine'], 'legacy'>;
repository: BacktestRunRepository;
logger: Pick<Logger, 'error'>;
heartbeatMs?: number;
@ -222,9 +221,6 @@ export class BacktestRunner extends EventEmitter {
};
this.dependencies.engine.on('progress', onProgress);
try {
if (!this.dependencies.repository.startCanonical) {
throw new Error('Canonical run repository is unavailable');
}
this.active = await this.dependencies.repository.startCanonical(config);
if (
this.active.executionDeadlineAt !== undefined &&
@ -283,18 +279,13 @@ export class BacktestRunner extends EventEmitter {
{
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;
// 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 =>
loadCanonicalDataset.call(
repository,
repository.loadCanonicalDataset(
claim.runId,
claim.attemptId,
executionConfig.datasetHash,
@ -324,12 +315,8 @@ export class BacktestRunner extends EventEmitter {
if (this.leaseFailure) {
throw this.leaseFailure;
}
const completeCanonical = this.dependencies.repository.completeCanonical;
if (!completeCanonical) {
throw new Error('Canonical result persistence is unavailable');
}
checkDeadline();
await completeCanonical.call(this.dependencies.repository, result, this.active.attemptId);
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;
@ -450,36 +437,21 @@ export class BacktestRunner extends EventEmitter {
await this.dependencies.engine.shutdown();
}
}
/** Compatibility control; the engine must accept it before SQL records a pause. */
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
);
/** 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) {
const active = this.requireActive(runId);
await this.dependencies.engine.resumeBacktest();
await this.dependencies.repository.updateControl(
active.runId,
{ status: 'running' },
active.attemptId
);
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) {
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');
}
const active = this.requireActive(runId);
this.dependencies.engine.setSpeedMultiplier(speed);
await this.dependencies.repository.updateControl(
active.runId,
{ speedMultiplier: speed },
active.attemptId
);
this.requireActive(runId);
throw new Error('Native backtests run at maximum speed');
}
/** Local worker projection; persisted run status remains authoritative after restart. */
getStatus() {

View file

@ -7,7 +7,6 @@ import {
} from '@stock-bot/stock-config/canonical-research';
import type { HistoricalDatasetV2 } from '@stock-bot/types';
import type { DatasetResolver } from '../data/historical-dataset';
import type { StorageService } from '../services/StorageService';
import type { BacktestConfig } from '../types';
import {
BacktestCancelledError,
@ -33,7 +32,6 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
constructor(
private readonly dependencies: {
logger: Pick<Logger, 'error'>;
storage: Pick<StorageService, 'getHistoricalBars'>;
},
options: { timeoutMs?: number; workerUrl?: URL } = {}
) {

View file

@ -9,21 +9,14 @@ import type { BacktestConfig } from '../types';
import type { NativeBacktestResult } from './native-result';
import type { BacktestResult } from './typescript-result';
/** The runner depends on execution capabilities, not backend implementations. */
/** Capabilities required by the canonical durable runner. No provider loading or playback. */
export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'> {
runBacktest(
config: BacktestConfig,
dataset?: DatasetResolver
): Promise<BacktestResult | NativeBacktestResult>;
runCanonical?(
runCanonical(
request: CanonicalRunRequest,
resolveDataset: (signal: AbortSignal) => Promise<HistoricalDatasetV2>,
controls?: { executionDeadlineAt?: number }
): Promise<Pick<CanonicalRunResult, 'financial' | 'analytics'>>;
stopBacktest(): Promise<void>;
pauseBacktest(): Promise<void>;
resumeBacktest(): Promise<void>;
setSpeedMultiplier(speed: number | null): void;
getStatus(): {
isRunning: boolean;
isPaused: boolean;
@ -33,6 +26,18 @@ export interface BacktestExecutionEngine extends Pick<EventEmitter, 'on' | 'off'
shutdown(): Promise<void>;
}
/** Retained algorithm/playback examples only; cannot satisfy the durable runner contract. */
export interface LegacyBacktestExecutionEngine
extends Pick<BacktestExecutionEngine, 'on' | 'off' | 'stopBacktest' | 'getStatus' | 'shutdown'> {
runBacktest(
config: BacktestConfig,
dataset?: DatasetResolver
): Promise<BacktestResult | NativeBacktestResult>;
pauseBacktest(): Promise<void>;
resumeBacktest(): Promise<void>;
setSpeedMultiplier(speed: number | null): void;
}
/** Cancellation has no result when a native worker is forcibly stopped. */
export class BacktestCancelledError extends Error {
constructor() {

View file

@ -21,34 +21,21 @@ export interface CanonicalRunClaim extends RunIdentity {
config: CanonicalRunRequest;
}
/** Every execution write must prove ownership of an unexpired attempt. */
/** Canonical execution only; every write proves ownership of an unexpired attempt.
* Concrete compatibility methods for older saved runs are outside this contract. */
export interface BacktestRunRepository {
start(config: BacktestConfig): Promise<RunClaim>;
/** Only already admitted canonical rows may be claimed; no implicit creation. */
startCanonical?(request: CanonicalRunRequest): Promise<CanonicalRunClaim>;
loadCanonicalDataset?(
startCanonical(request: CanonicalRunRequest): Promise<CanonicalRunClaim>;
loadCanonicalDataset(
runId: string,
attemptId: string,
requestedHash: string,
signal?: AbortSignal
): Promise<HistoricalDatasetV2>;
completeCanonical?(result: CanonicalRunResult, attemptId: string): Promise<void>;
completeCanonical(result: CanonicalRunResult, attemptId: string): Promise<void>;
load(runId: string): Promise<{ status: string; config: unknown } | null>;
rejectPending(runId: string, error: string): Promise<void>;
heartbeat(runId: string, attemptId: string): Promise<{ cancelRequested: boolean }>;
loadDataset(
runId: string,
attemptId: string,
requestedHash?: string,
signal?: AbortSignal
): Promise<HistoricalDataset | null>;
freezeDataset(
runId: string,
attemptId: string,
dataset: HistoricalDataset,
signal?: AbortSignal
): Promise<HistoricalDataset>;
complete(result: BacktestRunResult, attemptId: string): Promise<void>;
updateProgress(
runId: string,
progress: number,
@ -57,11 +44,6 @@ export interface BacktestRunRepository {
): Promise<void>;
fail(runId: string, error: string, attemptId: string): Promise<void>;
cancel(runId: string, attemptId: string): Promise<void>;
updateControl(
runId: string,
update: { status?: 'running' | 'paused'; speedMultiplier?: number | null },
attemptId: string
): Promise<void>;
}
export class BacktestConflictError extends Error {}
export class BacktestLeaseLostError extends BacktestConflictError {}
@ -71,6 +53,16 @@ export class UnavailableBacktestRunRepository implements BacktestRunRepository {
private unavailable(): never {
throw new Error('Backtest execution requires a PostgreSQL run repository');
}
async startCanonical(_request: CanonicalRunRequest): Promise<CanonicalRunClaim> {
return this.unavailable();
}
async loadCanonicalDataset(): Promise<HistoricalDatasetV2> {
return this.unavailable();
}
async completeCanonical(_result: CanonicalRunResult, _attemptId: string): Promise<void> {
this.unavailable();
}
/** Compatibility diagnostics for callers of the retired repository surface. */
async start(_config: BacktestConfig): Promise<RunClaim> {
return this.unavailable();
}

View file

@ -152,10 +152,9 @@ export async function registerOrchestratorServices(
() =>
new BacktestRunner({
engine: new RustBacktestAdapter(
{ logger: services.logger, storage: storageService },
{ logger: services.logger },
{ timeoutMs: options.nativeExecutionTimeoutMs }
),
engineName: 'native',
repository: services.postgres
? new PostgresBacktestRunRepository(services.postgres)
: new UnavailableBacktestRunRepository(),